@aiquants/auth-react-router 0.38.0 → 0.39.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
@@ -52,20 +52,37 @@ export const authServer = createAuthServer({
52
52
  warmup: async () => { await Promise.all([ensurePrimaryConnection(), ensureSecondaryConnection()]) },
53
53
  mockUser: mockUserPort, // test backdoor (E2E) — omit in production-only apps
54
54
  })
55
- export const { authenticator, sessionStorage, getSession, getSessionUser, saveSession, requireUser, requireAdminUser, commitSession, destroySession, sessionMaxAgeSeconds, authenticate, refreshedAccessToken, authenticateInLoader, loginLoader, loginAction, startGoogleSignIn, logoutLoader, logout, logoutAndRedirect, googleCallbackLoader } = authServer
55
+ export const { authenticator, sessionStorage, getSession, getSessionUser, saveSession, requireUser, requireAdminUser, signInRedirect, commitSession, destroySession, sessionMaxAgeSeconds, authenticate, refreshedAccessToken, authenticateInLoader, loginLoader, loginAction, startGoogleSignIn, logoutLoader, logout, logoutAndRedirect, googleCallbackLoader, messages } = authServer
56
56
  ```
57
57
 
58
- A sign-in can return to a page of the host instead of `postLoginRedirect` (a landing page that tells the host's other tabs
59
- 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
60
- `returnTo` (`RETURN_TO_SEARCH_PARAM`), and any other value is refused with 400:
58
+ A sign-in can return the reader to the page they were sent from, or to a page of the host listed exactly (a landing page
59
+ that tells the host's other tabs that the user signed in again, say), instead of `postLoginRedirect`. The sign-in page's
60
+ address names the return-to in `returnTo` (`RETURN_TO_SEARCH_PARAM`); a return-to the server does not accept is refused by
61
+ redirecting to the sign-in page with the failure key `returnToRefused` (`<loginPath>?error=returnToRefused`):
61
62
 
62
63
  ```ts
63
64
  createAuthServer({
64
65
  ...,
65
- returnTo: { allowedPaths: ["/auth/signed-in"] }, // exact same-origin paths; omit to allow none
66
+ returnTo: {
67
+ allowedPaths: ["/auth/signed-in"], // exact same-origin paths
68
+ pages: { excludedPathPrefixes: ["/auth/", "/api/", "/sse/"], maxLength: 2048 }, // REQUIRED key: the pages a sign-in returns to, or null for none
69
+ }, // omit returnTo to accept no return-to
66
70
  })
67
71
  ```
68
72
 
73
+ A page loader hands its guard the page's path and query, so an unauthenticated reader is sent to the sign-in page that
74
+ returns here (an action passes `{ failureRedirect: null }` instead and answers 401 data):
75
+
76
+ ```ts
77
+ export const loader = async ({ request }: LoaderFunctionArgs) => {
78
+ const url = new URL(request.url)
79
+ const returnTo = url.pathname + url.search
80
+ const { user, cookie } = await authServer.authenticateInLoader(request, { failureRedirect: "/auth/login", returnTo }) // failureRedirect must be loginPath; GET and HEAD only
81
+ ...
82
+ }
83
+ // requireUser(request, returnTo) and requireAdminUser(request, returnTo) take the same return-to
84
+ ```
85
+
69
86
  ```ts
70
87
  // In the browser (the entry imports nothing, so a chunk that links to the sign-in page carries nothing else)
71
88
  import { signInPathWithReturnTo } from "@aiquants/auth-react-router/return-to"
@@ -78,7 +95,7 @@ so the return-to is honoured there too:
78
95
 
79
96
  ```ts
80
97
  export const loader = async ({ request }: LoaderFunctionArgs) => {
81
- if (isReauthorization(request)) return await authServer.startGoogleSignIn(request) // always throws: 400, or the redirect to Google
98
+ if (isReauthorization(request)) return await authServer.startGoogleSignIn(request) // always throws: the refusal's redirect (?error=returnToRefused), or the redirect to Google
82
99
  return authServer.loginLoader({ request })
83
100
  }
84
101
  ```
@@ -131,15 +148,18 @@ const setCookie = await authServer.storage.saveSignedInSession(new Request("http
131
148
  ```
132
149
 
133
150
  A host that writes its own sign-out route (to add headers to the answer, say) applies the same request rule as
134
- `logoutLoader` before signing out:
151
+ `logoutLoader` before signing out, logs the reason, and answers with the server's text:
135
152
 
136
153
  ```ts
137
154
  import { signOutRefusal, signOutRefusalResponse } from "@aiquants/auth-react-router/server"
138
155
 
139
156
  export const loader = async ({ request }: LoaderFunctionArgs) => {
140
157
  const refusal = signOutRefusal(request)
141
- if (refusal !== undefined) throw signOutRefusalResponse(refusal) // 403, no Set-Cookie, session and grant untouched
142
- throw await authServer.logoutAndRedirect(request) // revokes the grant, then deletes the session cookie
158
+ if (refusal !== undefined) {
159
+ logger.warn(`Signing out is refused because ${refusal}`) // the reason is for the log only
160
+ throw signOutRefusalResponse(authServer.messages) // 403 whose body is the reader's text signOutRefused; no Set-Cookie, session and grant untouched
161
+ }
162
+ throw await authServer.logoutAndRedirect(request) // revokes the grant, then deletes the session cookie
143
163
  }
144
164
  ```
145
165
 
@@ -147,9 +167,13 @@ Client:
147
167
 
148
168
  ```tsx
149
169
  import { GoogleForm } from "@aiquants/auth-react-router/client"
150
- <GoogleForm /> // <Form method="POST"> + _action="Sign In with Google"
170
+ <GoogleForm /> // <Form method="POST"> + _action="Sign In with Google"; the button reads 「Google でサインイン」 (the label prop changes it)
151
171
  ```
152
172
 
173
+ The button is at least 44 px high, its fill and text are the 7:1 pair of `@aiquants/console-ui/core` (`on-solid` on
174
+ `info-solid`, in both colour schemes) and its focus ring is `focus`; no state changes the colours. The icon is hidden from
175
+ assistive technology, so the button's name is its label.
176
+
153
177
  ## User administration surface (`/admin`)
154
178
 
155
179
  A splat-mounted admin UI for users, groups, group members, and the sign-in allowlist — the identity-side counterpart to `@aiquants/authz-react-router`.
@@ -163,7 +187,8 @@ export const userAdminApp = createUserAdminApp({
163
187
  labels: jaUserAdminLabels, // optional; package default is English
164
188
  guards: { // REQUIRED — see below
165
189
  requireAccess: async (request, { action }) => {
166
- await requireUser(request)
190
+ const url = new URL(request.url)
191
+ await requireUser(request, url.pathname + url.search)
167
192
  await requirePermission(request, { resourceKey: "user_admin", action })
168
193
  },
169
194
  },
@@ -175,7 +200,7 @@ import { AuthUserAdminAppView } from "@aiquants/auth-react-router/admin"
175
200
  export const loader = userAdminApp.loader
176
201
  export const action = userAdminApp.action
177
202
  // mounted as the splat route "/users/*"
178
- export default () => <AuthUserAdminAppView basePath="/users" />
203
+ export default () => <AuthUserAdminAppView basePath="/users" accessFailure={accessFailurePresenter} />
179
204
  ```
180
205
 
181
206
  - **`basePath` is required** (`AuthUserAdminAppView` / `UserAdminShell`): the absolute path the console is mounted at,
@@ -183,6 +208,11 @@ export default () => <AuthUserAdminAppView basePath="/users" />
183
208
  groups tab are built from it. There is no default: the host decides where the console lives, and a built-in default
184
209
  would keep drawing links to that default after the mount moves — the routes still resolve and the build still
185
210
  passes, only the links point at a place that is not served.
211
+ - **`accessFailure` is required** (`AuthUserAdminAppView` / `UserAdminShell`): the host's access-failure presenter
212
+ (`AccessFailurePresenter` of `@aiquants/auth-core`), the same one its other screens use, so a denial reads the same
213
+ everywhere. The shell's root (`ConsoleUiRoot`) holds it, and the views draw every denied write through it (place
214
+ `write`, with `labels.errors.forbidden` as the denied sentence). `ConsoleUiRoot` throws `TypeError` when it is not a
215
+ function.
186
216
  - **Serve the view with `userAdminApp.loader`**: `AuthUserAdminAppView` draws the tab its loader's `segment` names
187
217
  (`users`, `groups`, `group_members`, `allowlist` or `directory`; the package's loader reads any other path below the
188
218
  base as `users`) and throws `RangeError` for any other value, no loader data included, so a wiring mistake surfaces
@@ -197,19 +227,25 @@ export default () => <AuthUserAdminAppView basePath="/users" />
197
227
  "Upstream group catalog" below for why.
198
228
  - **Denials (`status: 403`) never surface as a 500.** A thrown value whose `status` is `403` is a denial, recognised by
199
229
  that HTTP vocabulary alone (no authorization library is imported):
200
- - the **loader** answers a denial that is not a `Response` with a 403 route error response,
201
- `data(labels.errors.forbidden, { status: 403, statusText: "Forbidden" })`, after reporting it to `guards.onDenied`
202
- (`intent: "loader"`, `actions: ["read"]`). React Router answers any other thrown value with 500 and, outside
203
- development, replaces it with "Unexpected Server Error" before the route's `ErrorBoundary` sees it, so a plain
204
- denial would reach the boundary looking like any other failure. A guard that throws a `Response` (a 403, a 401, a
205
- redirect) and every other rejection propagate unchanged;
206
- - the **action** answers a denial thrown by the guard or the store with an in-page
207
- `{ ok: false, error: labels.errors.forbidden }` at status 403, so the other tabs and operations stay usable; any
208
- other guard rejection propagates unchanged.
209
- - Neither returns the guard's own message: it carries internal vocabulary (tenant ids, denial reasons).
230
+ - the **loader** answers a denial that is not a `Response` with the 403 access-failure response of
231
+ `@aiquants/auth-core`, `accessFailureResponse("forbidden")` (a JSON body that names only the kind,
232
+ `Cache-Control: no-store`), after reporting it to `guards.onDenied` (`intent: "loader"`, `actions: ["read"]`); the
233
+ host's route error boundary draws it through its presenter. React Router answers any other thrown value with 500
234
+ and, outside development, replaces it with "Unexpected Server Error" before the route's `ErrorBoundary` sees it, so a
235
+ plain denial would reach the boundary looking like any other failure. A guard that throws a `Response` (a 403, a
236
+ 401, a redirect) and every other rejection propagate unchanged;
237
+ - the **action** answers a denial thrown by the guard or the store in page with the access-failure body
238
+ (`data(accessFailureBody("forbidden"), { status: 403 })`); the views draw it in place through the root's presenter
239
+ (place `write`, denied sentence `labels.errors.forbidden`, no retry), so the other tabs and operations stay usable.
240
+ A refusal stated in words (`{ ok: false, error }`: a lockout reason, a taken key, an invalid field) stays an alert
241
+ the page announces (`data-testid="user-admin-action-error"`, `role="alert"`). Any other guard rejection propagates
242
+ unchanged.
243
+ - Neither returns the guard's own message, nor any text: it carries internal vocabulary (tenant ids, denial reasons),
244
+ and the body names only the kind. `errors.forbidden` states only what was refused (the presenter adds the title and
245
+ the request to ask an administrator); `resolveUserAdminLabels` refuses a blank one with `RangeError`.
210
246
  - Labels default to **English** (`defaultUserAdminLabels`); inject `jaUserAdminLabels` or a partial override via `resolveUserAdminLabels`.
211
247
  - **Stylesheet**: the views are `@aiquants/console-ui` parts inside the console's root (`ConsoleUiRoot`, which the shell
212
- opens with `labels.locale`, `labels.formatLocale` and `labels.timeZone`), so the host loads
248
+ opens with `labels.locale`, `labels.formatLocale`, `labels.timeZone` and the host's `accessFailure`), so the host loads
213
249
  `@aiquants/console-ui/styles/console-ui.css` once, with the `cui` layer above its reset layer (console-ui's README,
214
250
  "Loading the stylesheet"). Without it the parts draw unstyled and the layout below has no lengths to count. A view
215
251
  rendered outside the shell (`UsersView` and the others) sits inside a `ConsoleUiRoot` of the host's: the parts throw
@@ -550,9 +586,22 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
550
586
  without its `=` padding, 43 characters, 43 to 129 once URL-encoded. React Router 7 and 8 sign the same way, and the package's
551
587
  tests pin the name and the shape. Change `cookieName`, the default name or the signing scheme only together with every such
552
588
  proxy's rule: a mismatch raises no error anywhere, the proxy just stops recognising the browser.
553
- - **Verify order**: Google profile check → `backendAuth.verify` → allowlist → `backendAuth.signup` (every login). Failures redirect to `<loginPath>?error=<encoded error message>` (messages overridable via `messages`; a key that `AuthMessages` lacks, or a text that is not a non-blank string, throws a `RangeError` when `createGoogleAuthenticator` builds the authenticator).
554
- - **Token refresh**: expiry check → Google `oauth2/v4/token` rotate → session update; `invalid_grant` destroys the session and redirects to login with `Set-Cookie`.
555
- - **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.
589
+ - **Verify order**: Google profile check → `backendAuth.verify` → allowlist → `backendAuth.signup` (every login). Failures redirect to `<loginPath>?error=<key>` with the failure's key only (`SignInFailureKey` of `@aiquants/auth-core`), never its text.
590
+ - **Sign-in failures travel as keys**: `loginLoader` returns `{ error }`, the text of the server's `messages` for a key it knows
591
+ (`isSignInFailureKey`), and `null` for an unknown key, free text, an empty value or none, so no text of the address reaches
592
+ the page. While a failure is shown it does not send a signed-in user on to the return-to. The Google callback names its own
593
+ failures too: `consentDenied` when the reader did not grant the sign-in on Google's page (the OAuth error `access_denied`),
594
+ `googleFailed` for any other error of the authenticator, and `backendUnreachable` (the generation store cannot be reached) or
595
+ `unexpected` when the signed-in session cannot be saved. The texts default to `defaultAuthMessages` (Japanese) and are
596
+ overridable key by key via `messages`; an unknown key, or a text that is not a non-blank string, throws a `RangeError` when
597
+ `createAuthHandlers` (and so `createAuthServer`) is built. The checked texts are the bundle's `messages`.
598
+ - **Token refresh**: expiry check → Google `oauth2/v4/token` rotate → session update; `invalid_grant` destroys the session and answers with the deletion's `Set-Cookie`: in the redirect mode by the redirect to the sign-in page that carries the accepted return-to, in the `null` mode by `AuthRequiredError` with `setCookie`.
599
+ - **Loader guard**: `authenticateInLoader(request, { failureRedirect, returnTo })` returns `{ user, cookie? }` with `user`
600
+ **required** (any authentication failure throws the redirect to the sign-in page that returns to `returnTo`), and
601
+ `authenticateInLoader(request, { failureRedirect: null })` returns `{ user?, cookie? }` (no-redirect mode, for actions and
602
+ optional sign-ins). The redirect mode serves page loaders only: `failureRedirect` must be `loginPath`, `returnTo` a string and
603
+ the request a GET or a HEAD, else it throws a `TypeError` before any work (the warmup included), for a signed-in request as
604
+ well. `authenticate(request, session, options)` takes the same two modes and its `options` is required.
556
605
  - **One authentication per request**: the guard performs its work at most once per `Request` instance and shares a mode-neutral result, so a root loader (`null`) and a leaf loader (`"/auth/login"`) in the same React Router data pass share a single pass — one warmup, one token refresh, one `Set-Cookie`. The failure policy is applied per caller on top of the shared result, so it must never be part of the cache key.
557
606
  - **Infrastructure failures are never laundered into logouts**: anything that is not an authentication failure (an unexpected error inside the auth step, a `getUserPhoto` port outage, a `saveSession` failure, a defect of the session generation store) propagates unchanged in **both** modes. The session is not destroyed and no redirect is produced.
558
607
  - Photo lookups are cached with in-flight dedup per factory instance.
@@ -582,29 +631,43 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
582
631
  exchanges the code inside the action and returns the profile with the user's tokens; `startGoogleSignIn` discards it,
583
632
  saves no session and throws a redirect to `loginPath` (keeping the return-to, if any): a sign-in completes only through
584
633
  `googleCallbackLoader`. `loginAction`'s type is `Promise<null>`: any other `_action` returns `null`.
585
- - **Per-flow return-to** (`returnTo: { allowedPaths }`, optional): a sign-in returns to the path its sign-in page's address
586
- names in `returnTo` (`RETURN_TO_SEARCH_PARAM`; build the address with `signInPathWithReturnTo` from
587
- `@aiquants/auth-react-router/return-to`) instead of `postLoginRedirect`.
588
- - **Allowed paths only**: the value is compared exactly with `allowedPaths`. An absolute URL, a protocol-relative `//host`,
589
- a backslash, a value that still holds a percent-encoding after the address is decoded, a dot segment, white space, a
590
- trailing slash, a different case, a query or fragment inside the value, an empty value, a second `returnTo` and any path
591
- not listed are refused with 400 (plain text, `Cache-Control: no-store`, no `Set-Cookie`) by `loginLoader`, `loginAction`
592
- and `startGoogleSignIn`, before the session is read and before Google is involved. Without `returnTo` in the config,
593
- every return-to is refused. When the server is built, `allowedPaths` must be a non-empty array (`TypeError` for the
594
- shape, `RangeError` when empty) of canonical paths: one leading `/`, no query, fragment, percent-encoding, backslash,
595
- white space, control or non-ASCII character, or dot segment (`RangeError` otherwise).
634
+ - **Per-flow return-to** (`returnTo: { allowedPaths, pages }`, optional): a sign-in returns to the address its sign-in
635
+ page's address names in `returnTo` (`RETURN_TO_SEARCH_PARAM`; the guards build it, and `signInPathWithReturnTo` from
636
+ `@aiquants/auth-react-router/return-to` builds it in the browser) instead of `postLoginRedirect`. The rules are checked
637
+ once and held by the session storage (`storage.returnToPolicy`); every guard, handler and `signInRedirect` judges by them.
638
+ - **What is accepted**: a value equal to one of `allowedPaths`, or, when `pages` is set, a page's path and query that
639
+ starts with a single `/` (not `//` or `/\`), holds no control character (tab and newline included), backslash or `#`,
640
+ follows every `%` with two hexadecimal digits, is left unchanged by the URL parser, has a path that decodes as UTF-8
641
+ to something not starting with `//` or `/\` and not under one of `excludedPathPrefixes` (compared without regard to
642
+ case, as React Router matches routes), and is at most `maxLength` characters long.
643
+ - **Refused at the sign-in page**: a return-to that is not accepted, and a second `returnTo`, are refused by
644
+ `loginLoader`, `loginAction` and `startGoogleSignIn` with a redirect to `<loginPath>?error=returnToRefused` (no
645
+ return-to), before the session is read and before Google is involved. Without `returnTo` in the config, every
646
+ return-to is refused.
647
+ - **Sent by the guards**: an unauthenticated page request is redirected to the sign-in page with its return-to when it
648
+ is accepted. One the host returns no reader to (`pages: null`) is left out silently; a malformed or too long one is
649
+ left out with a `logger.warn` that names the failed check or the length, never the value; a page under an excluded
650
+ prefix throws `TypeError` (a route there answers 401 instead of redirecting). The bundle's `signInRedirect(returnTo,
651
+ init?)` builds the same redirect for a loader that judges authentication itself.
652
+ - **Checked when the server is built**: `TypeError` for a shape that is not `{ allowedPaths: string[], pages:
653
+ { excludedPathPrefixes: string[], maxLength: number } | null }` (`pages` is a required key), `RangeError` for an
654
+ allowed path that is not canonical (one leading `/`, no query, fragment, percent-encoding, backslash, white space,
655
+ control or non-ASCII character, or dot segment), an excluded prefix that does not start with `/`, a `maxLength` that
656
+ is not a safe integer >= 1, or a setting that allows nothing (`allowedPaths` empty and `pages` `null`; omit `returnTo`
657
+ instead).
596
658
  - **Bound to the flow**: `startGoogleSignIn` adds to the strategy's redirect to Google a cookie named
597
659
  `__return_to.<state>` after the flow's OAuth `state` (signed with the session secrets, `HttpOnly`, `SameSite=Lax`,
598
660
  `Path=/`, `Secure` as the session cookie, `Max-Age` 300 seconds like the strategy's own state cookie). Each flow has its
599
661
  own cookie, so sign-ins in several tabs never take each other's return-to.
600
662
  - **Callback**: `googleCallbackLoader` reads the cookie of its request's `state`, redirects to its path with the session
601
- cookie, and deletes it. A cookie whose signature does not match, or whose path is no longer allowed, is deleted and
602
- logged with `logger.warn`, and the sign-in goes to `postLoginRedirect`; a cookie of another flow is left alone. A failed
603
- callback deletes the cookie and carries the path into its redirect to `loginPath` (`?error=...&returnTo=...`), so the
604
- next try from that page returns to it as well.
605
- - **Signed-in users**: `loginLoader` redirects a user who is already signed in to the page's return-to (else to
606
- `postLoginRedirect`), so a landing page reached from a second window still runs.
607
- - Name only pages that take nothing from the sign-in's address, and never a page that acts on arrival without the user.
663
+ cookie, and deletes it. A cookie whose signature does not match, or whose return-to is no longer accepted, is deleted
664
+ and logged with `logger.warn`, and the sign-in goes to `postLoginRedirect`; a cookie of another flow is left alone. A
665
+ failed callback deletes the cookie and carries the return-to into its redirect to `loginPath`
666
+ (`?error=<key>&returnTo=...`), so the next try from that page returns to it as well.
667
+ - **Signed-in users**: while the address names no failure, `loginLoader` redirects a user who is already signed in to
668
+ the page's return-to (else to `postLoginRedirect`), so a landing page reached from a second window still runs.
669
+ - List in `allowedPaths` only pages that take nothing from the sign-in's address. Put every route that acts on a GET
670
+ (the sign-out route, say) and every route that is not a page (APIs, server-sent events) under `excludedPathPrefixes`.
608
671
  - **Sign-out revokes the Google grant before it answers**: `logout` (and `logoutAndRedirect` / `logoutLoader`, which call it)
609
672
  POSTs the session's refresh token, or its access token when there is none, to `https://oauth2.googleapis.com/revoke` (in the
610
673
  form body, never the URL), waits until that settles, then destroys the session. The wait is bounded by
@@ -627,12 +690,13 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
627
690
  processes share, starting at 0 and raised past the signed-out session's stamp at each sign-out.
628
691
  - **Sign-in** (`googleCallbackLoader`, through `storage.saveSignedInSession`) reads the identity's generation afresh
629
692
  (never from the cache) and stamps it into the session beside the profile, overwriting any older stamp. A store that
630
- cannot be read fails the sign-in: it is logged (`Authentication error:`) and redirected to `loginPath`, and no session
631
- cookie is set. A token refresh (`saveSession`) keeps the stamp of the sign-in.
693
+ cannot be read fails the sign-in: it is logged (`Saving the signed-in session failed:`) and redirected to the sign-in
694
+ page with the key `backendUnreachable` (the store cannot be reached) or `unexpected` (any other error), and no
695
+ session cookie is set. A token refresh (`saveSession`) keeps the stamp of the sign-in.
632
696
  - **Every guard checks the stamp**: `getSessionUser` / `requireUser` / `requireAdminUser`, `authenticateInLoader` and
633
697
  `authenticate`. A stamp older than the identity's generation, or a missing or invalid one, means the session was
634
- signed out: `getSessionUser` returns `undefined`; `requireUser` / `requireAdminUser` redirect to `loginPath` with the
635
- cookie's deletion; `authenticateInLoader` returns the deletion as `cookie` (`null` mode) or throws the redirect
698
+ signed out: `getSessionUser` returns `undefined`; `requireUser` / `requireAdminUser` redirect to the sign-in page
699
+ (carrying the accepted return-to) with the cookie's deletion; `authenticateInLoader` returns the deletion as `cookie` (`null` mode) or throws the redirect
636
700
  carrying it; `authenticate` destroys the session (`AuthRequiredError` with `setCookie`, or the redirect with
637
701
  `Set-Cookie`). The deletion wins over an `isUserActive` that also answers `false` (that alone keeps the cookie).
638
702
  `loginLoader` only reads, so it shows the login page and the next sign-in overwrites the cookie. The `mockUser`
@@ -685,8 +749,9 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
685
749
  `SameSite=Lax` cookie too). Every other destination, a navigation from another site (`cross-site`: sign-out revokes the
686
750
  grant and so ends the user's sessions on every device, which another site's link or script must not be able to cause),
687
751
  a request that states a destination but no `Sec-Fetch-Site`, and any request carrying `Sec-Purpose` (a prefetch or
688
- prerender) is answered with 403 (`signOutRefusalResponse`: plain text, `Cache-Control: no-store`, no `Set-Cookie`), and
689
- neither the session nor the grant is touched. A request without fetch metadata signs out. Without this, an
752
+ prerender) is answered with 403 (`signOutRefusalResponse(messages)`: the reader's text `messages.signOutRefused` as plain
753
+ text, `Cache-Control: no-store`, no `Set-Cookie`; the reason goes to `logger.warn` only), and neither the session nor
754
+ the grant is touched. A request without fetch metadata signs out. Without this, an
690
755
  `<img src="/auth/logout">` in any rendered document signs the reader out. `logout` and `logoutAndRedirect` do not check
691
756
  the request: a route that calls them applies `signOutRefusal` first.
692
757
  - **The rule needs HTTPS**: browsers send the `Sec-Fetch-*` headers only to potentially trustworthy URLs (`https:`, or
package/dist/admin.d.mts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { ConsoleUiLocale } from "@aiquants/console-ui/core";
2
2
  import { VirtualScrollLocale } from "@aiquants/virtualscroll";
3
+ import * as _aiquants_auth_core from "@aiquants/auth-core";
4
+ import { AuthUser, AuthGroup, AuthGroupMember, AuthAllowlistEntry, AuthDirectoryMembershipMode, AuthDirectoryStatus, AuthDirectoryCatalogSnapshot, AuthDirectoryCatalogGroup, AccessFailurePresenter } from "@aiquants/auth-core";
3
5
  import * as react_router from "react-router";
4
- import { AuthUser, AuthGroup, AuthGroupMember, AuthAllowlistEntry, AuthDirectoryMembershipMode, AuthDirectoryStatus, AuthDirectoryCatalogSnapshot, AuthDirectoryCatalogGroup } from "@aiquants/auth-core";
5
6
  import * as react from "react";
6
7
  import { ReactNode } from "react";
7
8
  type UserAdminLocale = VirtualScrollLocale & ConsoleUiLocale;
@@ -411,7 +412,7 @@ declare function createUserAdminApp(config: UserAdminAppConfig): {
411
412
  action: ({ request }: RouteArgs) => Promise<react_router.UNSAFE_DataWithResponseInit<{
412
413
  ok: boolean;
413
414
  error: string;
414
- }> | {
415
+ }> | react_router.UNSAFE_DataWithResponseInit<_aiquants_auth_core.AccessFailureBody> | {
415
416
  ok: boolean;
416
417
  syncRequest?: undefined;
417
418
  } | {
@@ -435,8 +436,9 @@ type UserAdminShellProps = {
435
436
  }) => ReactNode;
436
437
  basePath: string;
437
438
  pendingSyncPolling?: PendingSyncPolling;
439
+ accessFailure: AccessFailurePresenter<ReactNode>;
438
440
  };
439
- declare function UserAdminShell({ children, renderHeader, pendingSyncPolling, basePath }: UserAdminShellProps): react.JSX.Element;
441
+ declare function UserAdminShell({ children, renderHeader, pendingSyncPolling, basePath, accessFailure }: UserAdminShellProps): react.JSX.Element;
440
442
  type UserAdminLoaderData = {
441
443
  segment: string;
442
444
  users: AuthUser[];
@@ -454,5 +456,5 @@ declare function GroupMembersView(): react.JSX.Element;
454
456
  declare function AllowlistView(): react.JSX.Element;
455
457
  declare function DirectoryView(): react.JSX.Element;
456
458
  type AuthUserAdminAppViewProps = UserAdminShellProps;
457
- declare function AuthUserAdminAppView({ renderHeader, pendingSyncPolling, basePath }: AuthUserAdminAppViewProps): react.JSX.Element;
459
+ declare function AuthUserAdminAppView({ renderHeader, pendingSyncPolling, basePath, accessFailure }: AuthUserAdminAppViewProps): react.JSX.Element;
458
460
  export { AllowlistView, AuthUserAdminAppView, type AuthUserAdminAppViewProps, DEFAULT_PENDING_SYNC_POLLING, DirectoryView, GroupMembersView, GroupsView, type PartialUserAdminLabels, type PendingSyncPolling, type UserAdminAccess, type UserAdminAppConfig, type UserAdminCatalog, type UserAdminCatalogFailure, type UserAdminCatalogGroup, type UserAdminCatalogSnapshot, type UserAdminFieldLimits, type UserAdminGuards, UserAdminInputError, type UserAdminLabels, type UserAdminLinkSyncOutcome, type UserAdminLoaderData, type UserAdminLocale, UserAdminOperatorError, type UserAdminPermission, UserAdminShell, type UserAdminShellProps, type UserAdminStore, type UserAdminSyncRequestOutcome, UsersView, createInMemoryUserAdminStore, createUserAdminApp, defaultUserAdminLabels, jaUserAdminLabels, normalizeGroupKey, normalizeUpstreamKey, resolveUserAdminLabels, userAdminAccessFor, userAdminIntents };
package/dist/admin.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { ConsoleUiLocale } from "@aiquants/console-ui/core";
2
2
  import { VirtualScrollLocale } from "@aiquants/virtualscroll";
3
+ import * as _aiquants_auth_core from "@aiquants/auth-core";
4
+ import { AuthUser, AuthGroup, AuthGroupMember, AuthAllowlistEntry, AuthDirectoryMembershipMode, AuthDirectoryStatus, AuthDirectoryCatalogSnapshot, AuthDirectoryCatalogGroup, AccessFailurePresenter } from "@aiquants/auth-core";
3
5
  import * as react_router from "react-router";
4
- import { AuthUser, AuthGroup, AuthGroupMember, AuthAllowlistEntry, AuthDirectoryMembershipMode, AuthDirectoryStatus, AuthDirectoryCatalogSnapshot, AuthDirectoryCatalogGroup } from "@aiquants/auth-core";
5
6
  import * as react from "react";
6
7
  import { ReactNode } from "react";
7
8
  type UserAdminLocale = VirtualScrollLocale & ConsoleUiLocale;
@@ -411,7 +412,7 @@ declare function createUserAdminApp(config: UserAdminAppConfig): {
411
412
  action: ({ request }: RouteArgs) => Promise<react_router.UNSAFE_DataWithResponseInit<{
412
413
  ok: boolean;
413
414
  error: string;
414
- }> | {
415
+ }> | react_router.UNSAFE_DataWithResponseInit<_aiquants_auth_core.AccessFailureBody> | {
415
416
  ok: boolean;
416
417
  syncRequest?: undefined;
417
418
  } | {
@@ -435,8 +436,9 @@ type UserAdminShellProps = {
435
436
  }) => ReactNode;
436
437
  basePath: string;
437
438
  pendingSyncPolling?: PendingSyncPolling;
439
+ accessFailure: AccessFailurePresenter<ReactNode>;
438
440
  };
439
- declare function UserAdminShell({ children, renderHeader, pendingSyncPolling, basePath }: UserAdminShellProps): react.JSX.Element;
441
+ declare function UserAdminShell({ children, renderHeader, pendingSyncPolling, basePath, accessFailure }: UserAdminShellProps): react.JSX.Element;
440
442
  type UserAdminLoaderData = {
441
443
  segment: string;
442
444
  users: AuthUser[];
@@ -454,5 +456,5 @@ declare function GroupMembersView(): react.JSX.Element;
454
456
  declare function AllowlistView(): react.JSX.Element;
455
457
  declare function DirectoryView(): react.JSX.Element;
456
458
  type AuthUserAdminAppViewProps = UserAdminShellProps;
457
- declare function AuthUserAdminAppView({ renderHeader, pendingSyncPolling, basePath }: AuthUserAdminAppViewProps): react.JSX.Element;
459
+ declare function AuthUserAdminAppView({ renderHeader, pendingSyncPolling, basePath, accessFailure }: AuthUserAdminAppViewProps): react.JSX.Element;
458
460
  export { AllowlistView, AuthUserAdminAppView, type AuthUserAdminAppViewProps, DEFAULT_PENDING_SYNC_POLLING, DirectoryView, GroupMembersView, GroupsView, type PartialUserAdminLabels, type PendingSyncPolling, type UserAdminAccess, type UserAdminAppConfig, type UserAdminCatalog, type UserAdminCatalogFailure, type UserAdminCatalogGroup, type UserAdminCatalogSnapshot, type UserAdminFieldLimits, type UserAdminGuards, UserAdminInputError, type UserAdminLabels, type UserAdminLinkSyncOutcome, type UserAdminLoaderData, type UserAdminLocale, UserAdminOperatorError, type UserAdminPermission, UserAdminShell, type UserAdminShellProps, type UserAdminStore, type UserAdminSyncRequestOutcome, UsersView, createInMemoryUserAdminStore, createUserAdminApp, defaultUserAdminLabels, jaUserAdminLabels, normalizeGroupKey, normalizeUpstreamKey, resolveUserAdminLabels, userAdminAccessFor, userAdminIntents };