@aiquants/auth-react-router 0.25.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -49,13 +49,48 @@ export const authServer = createAuthServer({
49
49
  warmup: async () => { await Promise.all([ensurePrimaryConnection(), ensureSecondaryConnection()]) },
50
50
  mockUser: mockUserPort, // test backdoor (E2E) — omit in production-only apps
51
51
  })
52
- export const { authenticator, sessionStorage, getSession, getSessionUser, saveSession, requireUser, requireAdminUser, commitSession, destroySession, authenticate, refreshedAccessToken, authenticateInLoader, loginLoader, loginAction, logoutLoader, logout, logoutAndRedirect, googleCallbackLoader } = authServer
52
+ export const { authenticator, sessionStorage, getSession, getSessionUser, saveSession, requireUser, requireAdminUser, commitSession, destroySession, sessionMaxAgeSeconds, authenticate, refreshedAccessToken, authenticateInLoader, loginLoader, loginAction, startGoogleSignIn, logoutLoader, logout, logoutAndRedirect, googleCallbackLoader } = authServer
53
+ ```
54
+
55
+ A sign-in can return to a page of the host instead of `postLoginRedirect` (a landing page that tells the host's other tabs
56
+ that the user signed in again, say). List the exact paths a sign-in may return to; the sign-in page's address names one in
57
+ `returnTo` (`RETURN_TO_SEARCH_PARAM`), and any other value is refused with 400:
58
+
59
+ ```ts
60
+ createAuthServer({
61
+ ...,
62
+ returnTo: { allowedPaths: ["/auth/signed-in"] }, // exact same-origin paths; omit to allow none
63
+ })
64
+ ```
65
+
66
+ ```ts
67
+ // In the browser (the entry imports nothing, so a chunk that links to the sign-in page carries nothing else)
68
+ import { signInPathWithReturnTo } from "@aiquants/auth-react-router/return-to"
69
+
70
+ window.open(signInPathWithReturnTo("/auth/login", "/auth/signed-in"), "_blank") // "/auth/login?returnTo=%2Fauth%2Fsigned-in"
71
+ ```
72
+
73
+ A host route that starts the Google sign-in from its own loader (a re-authorization link, say) calls `startGoogleSignIn`,
74
+ so the return-to is honoured there too:
75
+
76
+ ```ts
77
+ export const loader = async ({ request }: LoaderFunctionArgs) => {
78
+ if (isReauthorization(request)) return await authServer.startGoogleSignIn(request) // always throws: 400, or the redirect to Google
79
+ return authServer.loginLoader({ request })
80
+ }
81
+ ```
82
+
83
+ A page that tells users how long a session lasts reads the lifetime the session cookie is given, never a copy of it:
84
+
85
+ ```ts
86
+ export const loader = async ({ request }: LoaderFunctionArgs) => ({ ...(await authServer.loginLoader({ request })), sessionMaxAgeSeconds: authServer.sessionMaxAgeSeconds })
53
87
  ```
54
88
 
55
89
  Optional settings for sign-out and the token requests:
56
90
 
57
91
  ```ts
58
92
  createAuthServer({
93
+ session: { secrets: [...], maxAge: 7 * 24 * 60 * 60 }, // the session cookie's lifetime in seconds (default DEFAULT_SESSION_MAX_AGE_SECONDS, 30 days)
59
94
  google: { ..., revocationTimeoutMs: 3_000 }, // how long sign-out waits for Google's revocation (default 5000)
60
95
  fetch: instrumentedFetch, // the fetch for the token refresh and the revocation (default: global fetch)
61
96
  sessionGeneration: {
@@ -148,8 +183,32 @@ export default () => <AuthUserAdminAppView basePath="/users" />
148
183
  - **`guards` is mandatory** — this surface lists every user and mutates group membership, so an unguarded mount is an account-enumeration and privilege-escalation path. Allow by returning, deny by throwing (`Response` / `redirect` / `Error`); the return value is `void` by contract, so a predicate-style guard that returns `false` cannot silently fail open.
149
184
  - **Per-operation authorization**: the guard receives the CRUD verb each intent actually performs (`read` / `create` / `update` / `delete`), so a principal holding only `update` cannot delete. Membership add/remove map to `create`/`delete` because they add and remove rows.
150
185
  - Unknown intents reach neither the guard nor the store (the intent table is a `Map`, so prototype keys such as `constructor` do not resolve).
151
- - Store errors (e.g. "cannot remove the last administrator") are returned as `{ ok: false, error }` and rendered by the views; guard rejections propagate untouched.
186
+ - Store errors (e.g. "cannot remove the last administrator") are returned as `{ ok: false, error }` and rendered by the views.
187
+ - **Denials (`status: 403`) never surface as a 500.** A thrown value whose `status` is `403` is a denial, recognised by
188
+ that HTTP vocabulary alone (no authorization library is imported):
189
+ - the **loader** answers a denial that is not a `Response` with a 403 route error response,
190
+ `data(labels.errors.forbidden, { status: 403, statusText: "Forbidden" })`, after reporting it to `guards.onDenied`
191
+ (`intent: "loader"`, `actions: ["read"]`). React Router answers any other thrown value with 500 and, outside
192
+ development, replaces it with "Unexpected Server Error" before the route's `ErrorBoundary` sees it, so a plain
193
+ denial would reach the boundary looking like any other failure. A guard that throws a `Response` (a 403, a 401, a
194
+ redirect) and every other rejection propagate unchanged;
195
+ - the **action** answers a denial thrown by the guard or the store with an in-page
196
+ `{ ok: false, error: labels.errors.forbidden }` at status 403, so the other tabs and operations stay usable; any
197
+ other guard rejection propagates unchanged.
198
+ - Neither returns the guard's own message: it carries internal vocabulary (tenant ids, denial reasons).
152
199
  - Labels default to **English** (`defaultUserAdminLabels`); inject `jaUserAdminLabels` or a partial override via `resolveUserAdminLabels`.
200
+ - **Every control is a 44 × 44 CSS px target under every pointer** (mouse, pen and touch alike; WCAG 2.2 SC 2.5.5,
201
+ AAA): the tabs, the sort buttons, the row actions, the links to a group's members, the search and form fields, the
202
+ selects, and every control of the dialogs. Where the control is drawn smaller than its target, the target is the
203
+ element around it: the label of the visually hidden "create from" radios and of the "members only" checkbox. The two
204
+ upstream-group pickers keep the 44 px targets of `@aiquants/select-box` itself. Rows grow to hold their actions; on
205
+ a narrow screen the toolbars and the tabs wrap, the tables scroll sideways, and a dialog taller than the screen
206
+ scrolls with its backdrop.
207
+ - **The group-members tab reflows without a media query** (WCAG 2.2 SC 1.4.10): the group list keeps a 240 px basis
208
+ and the member panel never takes less than half the row, so the two sit side by side from about 518 px
209
+ (`2 × (240 px + 1.2rem)`) and stack, each at the full width, below it. The heading, the action error and the
210
+ deep-link note are rows of the vertical stack outside the wrapping row, so they span the whole width in both
211
+ arrangements. Long addresses wrap inside a member row.
153
212
 
154
213
  ### Localization (`labels.locale` vs `labels.formatLocale`)
155
214
 
@@ -349,10 +408,22 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
349
408
 
350
409
  ## Behavior Contract
351
410
 
352
- - **Session cookie**: `__session` (httpOnly/lax/30d) with key `"user"`, value = `{ id, displayName, name, emails, accessToken, refreshToken?, expirationDateMs?, provider, role? }` — never `photo`/`_json`/`photos` — and, when `sessionGeneration` is enabled, key `"generation"` = the identity's sign-out generation at sign-in.
411
+ - **Session cookie**: `__session` (httpOnly/lax) with key `"user"`, value = `{ id, displayName, name, emails, accessToken, refreshToken?, expirationDateMs?, provider, role? }` — never `photo`/`_json`/`photos` — and, when `sessionGeneration` is enabled, key `"generation"` = the identity's sign-out generation at sign-in.
353
412
  With the check enabled a cookie without a valid `"generation"` is rejected, so every user signs in once after a host
354
- turns it on. Changing the cookie name, the `"user"` key or the profile shape invalidates all live 30-day sessions.
413
+ turns it on. Changing the cookie name, the `"user"` key or the profile shape invalidates all live sessions.
355
414
  `session.sessionKey` must not be `"generation"` (`RangeError` when the server is built).
415
+ - **Session lifetime**: the cookie's `Max-Age` is `session.maxAge` seconds, `DEFAULT_SESSION_MAX_AGE_SECONDS` (30 days) when
416
+ it is omitted; anything other than a safe integer >= 1 throws `RangeError` when the server is built. Every write of the
417
+ session (a sign-in, a token refresh) sets it again, so the cookie lasts that long from its last write. The resolved value is
418
+ `sessionMaxAgeSeconds` on the server bundle and on `storage`, for a page that tells users how long a session lasts. A
419
+ session also ends earlier: when Google refuses to refresh the access token (the refresh token expired or was revoked), at a
420
+ sign-out on any device (the sign-out generation below), and when `isUserActive` reports the account deactivated.
421
+ - **The cookie's name and value shape are a contract with reverse proxies**: a proxy in front of the host may key per-browser
422
+ limits on this cookie, reading the name `__session` and the value `<payload>.<signature>` exactly as the `Cookie` header carries
423
+ it: the URL-encoded payload, a `.`, and the signature React Router's `sign()` appends — the base64 of an HMAC-SHA256 (32 bytes)
424
+ without its `=` padding, 43 characters, 43 to 129 once URL-encoded. React Router 7 and 8 sign the same way, and the package's
425
+ tests pin the name and the shape. Change `cookieName`, the default name or the signing scheme only together with every such
426
+ proxy's rule: a mismatch raises no error anywhere, the proxy just stops recognising the browser.
356
427
  - **Verify order**: Google profile check → `backendAuth.verify` → allowlist → `backendAuth.signup` (every login). Failures redirect to `<loginPath>?error=<encoded error message>` (messages overridable via `messages`).
357
428
  - **Token refresh**: expiry check → Google `oauth2/v4/token` rotate → session update; `invalid_grant` destroys the session and redirects to login with `Set-Cookie`.
358
429
  - **Loader guard**: `authenticateInLoader(request, { failureRedirect })` returns `{ user, cookie? }` with `user` **required** when `failureRedirect` is a string (any authentication failure throws a redirect), and `{ user?, cookie? }` when it is `null` (no-redirect mode). Passing `""` throws a `TypeError` before any work — it is a mistake, not a request for the default.
@@ -379,12 +450,35 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
379
450
  - The `Set-Cookie` values of `saveSession` / `commitSession` / `storage.saveSignedInSession` and the `cookie` of
380
451
  `authenticateInLoader`: the session cookie is signed, not encrypted, so the token can be read out of it. Put them
381
452
  in a `Set-Cookie` header only.
382
- - **`loginAction` never hands out the signed-in profile**: for `_action === "Sign In with Google"` it always ends by
383
- throwing a redirect. The strategy normally throws the redirect to Google's authorization endpoint. When the POST's URL
384
- carries `code` and the `state` of the user's state cookie, remix-auth exchanges the code inside the action and returns
385
- the profile with the user's tokens; `loginAction` discards it, saves no session and throws a redirect to `loginPath`
386
- (a sign-in completes only through `googleCallbackLoader`). Its type is `Promise<null>`: any other `_action` returns
387
- `null`.
453
+ - **`loginAction` never hands out the signed-in profile**: for `_action === "Sign In with Google"` it starts the sign-in
454
+ through `startGoogleSignIn`, which always ends by throwing. The strategy normally throws the redirect to Google's
455
+ authorization endpoint. When the POST's URL carries `code` and the `state` of the user's state cookie, remix-auth
456
+ exchanges the code inside the action and returns the profile with the user's tokens; `startGoogleSignIn` discards it,
457
+ saves no session and throws a redirect to `loginPath` (keeping the return-to, if any): a sign-in completes only through
458
+ `googleCallbackLoader`. `loginAction`'s type is `Promise<null>`: any other `_action` returns `null`.
459
+ - **Per-flow return-to** (`returnTo: { allowedPaths }`, optional): a sign-in returns to the path its sign-in page's address
460
+ names in `returnTo` (`RETURN_TO_SEARCH_PARAM`; build the address with `signInPathWithReturnTo` from
461
+ `@aiquants/auth-react-router/return-to`) instead of `postLoginRedirect`.
462
+ - **Allowed paths only**: the value is compared exactly with `allowedPaths`. An absolute URL, a protocol-relative `//host`,
463
+ a backslash, a value that still holds a percent-encoding after the address is decoded, a dot segment, white space, a
464
+ trailing slash, a different case, a query or fragment inside the value, an empty value, a second `returnTo` and any path
465
+ not listed are refused with 400 (plain text, `Cache-Control: no-store`, no `Set-Cookie`) by `loginLoader`, `loginAction`
466
+ and `startGoogleSignIn`, before the session is read and before Google is involved. Without `returnTo` in the config,
467
+ every return-to is refused. When the server is built, `allowedPaths` must be a non-empty array (`TypeError` for the
468
+ shape, `RangeError` when empty) of canonical paths: one leading `/`, no query, fragment, percent-encoding, backslash,
469
+ white space, control or non-ASCII character, or dot segment (`RangeError` otherwise).
470
+ - **Bound to the flow**: `startGoogleSignIn` adds to the strategy's redirect to Google a cookie named
471
+ `__return_to.<state>` after the flow's OAuth `state` (signed with the session secrets, `HttpOnly`, `SameSite=Lax`,
472
+ `Path=/`, `Secure` as the session cookie, `Max-Age` 300 seconds like the strategy's own state cookie). Each flow has its
473
+ own cookie, so sign-ins in several tabs never take each other's return-to.
474
+ - **Callback**: `googleCallbackLoader` reads the cookie of its request's `state`, redirects to its path with the session
475
+ cookie, and deletes it. A cookie whose signature does not match, or whose path is no longer allowed, is deleted and
476
+ logged with `logger.warn`, and the sign-in goes to `postLoginRedirect`; a cookie of another flow is left alone. A failed
477
+ callback deletes the cookie and carries the path into its redirect to `loginPath` (`?error=...&returnTo=...`), so the
478
+ next try from that page returns to it as well.
479
+ - **Signed-in users**: `loginLoader` redirects a user who is already signed in to the page's return-to (else to
480
+ `postLoginRedirect`), so a landing page reached from a second window still runs.
481
+ - Name only pages that take nothing from the sign-in's address, and never a page that acts on arrival without the user.
388
482
  - **Sign-out revokes the Google grant before it answers**: `logout` (and `logoutAndRedirect` / `logoutLoader`, which call it)
389
483
  POSTs the session's refresh token, or its access token when there is none, to `https://oauth2.googleapis.com/revoke` (in the
390
484
  form body, never the URL), waits until that settles, then destroys the session. The wait is bounded by