A React server action POSTs to the URL of the page it lives on, so the middleware's method check over /admin refused every form on the site to a viewer — including the sign-out button, which surfaced as "an unexpected response was received from the server". Gating pages by HTTP method was the wrong instrument: at the edge there is no way to tell a form that changes the shop's hours from one that ends a session. The method check now applies to /api/admin only, and page-level writes are authorised inside the actions themselves, where the intent is actually known. lib/auth/actions.ts carries that check and returns an error rather than throwing, since "you do not have permission" is a normal outcome and not a crash. The edge decision moves into a pure function with a regression test for this exact case. These rules are short, but they are the only thing in front of the administration and one of them has now been got wrong once. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012cSY9pVhZmJUKNN7wf1Myd
47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
/**
|
|
* What the edge should do with a request, decided in one pure function.
|
|
*
|
|
* Extracted from the middleware so it can be tested: the rules here are short
|
|
* but they are the only thing standing in front of the administration, and one
|
|
* of them has already been got wrong once.
|
|
*/
|
|
|
|
import type { Role } from './roles';
|
|
|
|
export type AccessDecision =
|
|
| { kind: 'allow' }
|
|
/** Send a browser to the sign-in screen. */
|
|
| { kind: 'redirect' }
|
|
/** Answer a fetch with a status code rather than an HTML page. */
|
|
| { kind: 'deny'; status: 401 | 403; error: string };
|
|
|
|
export type AccessRequest = {
|
|
pathname: string;
|
|
method: string;
|
|
role: Role | undefined;
|
|
};
|
|
|
|
export function decideAccess({ pathname, method, role }: AccessRequest): AccessDecision {
|
|
const isApi = pathname.startsWith('/api/admin');
|
|
|
|
if (!role) {
|
|
// A fetch that receives an HTML login page is a confusing way to learn
|
|
// you are signed out.
|
|
return isApi
|
|
? { kind: 'deny', status: 401, error: 'Non authentifié' }
|
|
: { kind: 'redirect' };
|
|
}
|
|
|
|
const isRead = method === 'GET' || method === 'HEAD';
|
|
|
|
// Only API routes are gated by method. A React server action POSTs to the
|
|
// URL of the page it lives on, so gating pages this way would refuse every
|
|
// form to a read-only account — including the sign-out button. Pages carry
|
|
// their own check inside the action, where the intent is known.
|
|
if (isApi && !isRead && role !== 'admin') {
|
|
return { kind: 'deny', status: 403, error: 'Compte en lecture seule' };
|
|
}
|
|
|
|
return { kind: 'allow' };
|
|
}
|