@aiquants/auth-react-router 0.44.0 → 0.46.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
@@ -47,12 +47,13 @@ export const authServer = createAuthServer({
47
47
  isEmailAllowed: emailDomainAllowlist(parseAllowlistCsv(env.AUTHZ_ALLOWED_EMAILS), parseAllowlistCsv(env.AUTHZ_ALLOWED_DOMAINS)),
48
48
  isUserActive: async (profile) => isAccountEnabled(profile), // optional: deactivation revokes live sessions; look the person up by (profile.provider, profile.id)
49
49
  sessionGeneration: { store: sessionGenerationStore }, // REQUIRED: sign-out generation store shared by every process (or false)
50
+ readerCheck: true, // REQUIRED: refuse a write a page of another reader sent (false while some page still sends unstamped writes)
50
51
  backendAuth: { verify: verifyBackend, signup: (p, t) => signupBackend(p, t) }, // FastAPI verify/signup
51
52
  getUserPhoto: async (profile) => (await getOpenids({ provider: profile.provider, openid: profile.id }))[0]?.picture ?? "", // your identity store, keyed by (provider, id)
52
53
  warmup: async () => { await Promise.all([ensurePrimaryConnection(), ensureSecondaryConnection()]) },
53
54
  mockUser: mockUserPort, // test backdoor (E2E) — omit in production-only apps
54
55
  })
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
+ export const { authenticator, sessionStorage, getSession, getSessionUser, readerStampOf, saveSession, requireUser, requireAdminUser, signInRedirect, commitSession, destroySession, sessionMaxAgeSeconds, authenticate, refreshedAccessToken, authenticateInLoader, loginLoader, loginAction, startGoogleSignIn, logoutLoader, logout, logoutAndRedirect, googleCallbackLoader, messages } = authServer
56
57
  ```
57
58
 
58
59
  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
@@ -200,9 +201,9 @@ export const userAdminApp = createUserAdminApp({
200
201
  ```
201
202
 
202
203
  ```tsx
203
- import { accessFailureBody } from "@aiquants/auth-core"
204
+ import { accessFailureBody, stampReader } from "@aiquants/auth-core"
204
205
  import { AuthUserAdminAppView } from "@aiquants/auth-react-router/admin"
205
- import { type ActionFunctionArgs, data, type LoaderFunctionArgs } from "react-router"
206
+ import { type ActionFunctionArgs, data, type LoaderFunctionArgs, useRouteLoaderData } from "react-router"
206
207
 
207
208
  // mounted as the splat route "/users/*"
208
209
  export const loader = async (args: LoaderFunctionArgs) => {
@@ -216,7 +217,12 @@ export const action = async (args: ActionFunctionArgs) => {
216
217
  if (user === undefined) return data(accessFailureBody("unauthenticated"), { status: 401, headers: cookie === undefined ? undefined : { "Set-Cookie": cookie } })
217
218
  return await userAdminApp.action(args)
218
219
  }
219
- export default () => <AuthUserAdminAppView basePath="/users" accessFailure={accessFailurePresenter} />
220
+ export default () => {
221
+ // the reader stamp the host's root loader hands its pages (readerStampOf of the reader the page was opened for)
222
+ const root = useRouteLoaderData<typeof rootLoader>("root")
223
+ if (root === undefined) throw new Error("the root route's data is missing")
224
+ return <AuthUserAdminAppView basePath="/users" accessFailure={accessFailurePresenter} stampWrite={(target) => stampReader(target, root.readerStamp)} />
225
+ }
220
226
  ```
221
227
 
222
228
  The guard receives only the request, and a client-side navigation reaches the loader through a single-fetch data request
@@ -234,6 +240,12 @@ first from the loader's `url`. The guard's own check is reached only by a sessio
234
240
  with an access-failure body (place `write`): a denied one (403, with `labels.errors.forbidden` as the denied sentence)
235
241
  and one from a reader who is not signed in (401). `ConsoleUiRoot` throws `TypeError` when it is not a
236
242
  function.
243
+ - **`stampWrite` is required** (`AuthUserAdminAppView`, and each tab view): it puts the reader stamp of the page on the
244
+ address of every write the console sends (`StampWrite` of `@aiquants/auth-core`). A host whose server checks readers
245
+ (`readerCheck: true`) passes `(target) => stampReader(target, stamp)` with the stamp its loader got from
246
+ `readerStampOf`; a host without that check passes `(target) => target`. Every write goes through the view's one fetcher
247
+ to the route's own path relative to the router (the router adds its `basename` once; an index route keeps `?index`)
248
+ with the page's query, and the console has no other way to send one.
237
249
  - **Serve the view with `userAdminApp.loader`**: `AuthUserAdminAppView` draws the tab its loader's `segment` names
238
250
  (`users`, `groups`, `group_members`, `allowlist` or `directory`; the package's loader reads any other path below the
239
251
  base as `users`) and throws `RangeError` for any other value, no loader data included, so a wiring mistake surfaces
@@ -550,6 +562,39 @@ domain with no groups.
550
562
  - `createLinkedGroup` creates the group and links it in **one** intent, and therefore requires the union of the verbs both
551
563
  halves need (`create` + `update` + `delete`). Splitting it in two would leave a state where only one half succeeded.
552
564
 
565
+ ### Fuzzy search workers of the pickers
566
+
567
+ The two upstream-group pickers (the create-group dialog's and the directory view's external key) are
568
+ `@aiquants/select-box` boxes, and each runs its fuzzy search in the two Web Workers of `@aiquants/fuzzy-search` under a
569
+ fixed `workerId`. The ids follow the sets of options: pickers that always list the same options share an id (one index,
570
+ one pair of workers), pickers that list different options never do, and no id is made per mount. Both pickers list the
571
+ directory catalog's upstream groups, marked from the same links, so they share one id on their two screens:
572
+
573
+ | `workerId` | Options | Pickers |
574
+ | --- | --- | --- |
575
+ | `@aiquants/auth-react-router:upstream-groups` | the catalog's upstream groups | the create-group dialog's upstream picker and the directory view's external key picker |
576
+
577
+ - The engine starts the pair of workers when the first of the pickers mounts and keeps it for the rest of the page. Give
578
+ the host's own boxes other ids.
579
+ - The worker scripts come from the engine's rule ("The worker URL rule" in the `@aiquants/fuzzy-search` README). Its built-in
580
+ default loads in a production build from `@aiquants/fuzzy-search` 3.2.2 on — the peer floor of this package: the
581
+ bundler (Vite, for one) emits both scripts as assets and rewrites the URL. On the Vite dev server a pre-bundled copy of
582
+ the package cannot load it — keep `@aiquants/fuzzy-search` out of `optimizeDeps`, or give the URLs.
583
+ - Neither picker passes `workerUrls`, so a host gives the URLs page-wide through the static
584
+ `FuzzySearchManager.defaultWorkerUrls`, set before the first picker mounts:
585
+
586
+ ```ts
587
+ import { FuzzySearchManager } from "@aiquants/fuzzy-search"
588
+ import indexWorkerUrl from "@aiquants/fuzzy-search/worker/indexWorker?url"
589
+ import levenshteinWorkerUrl from "@aiquants/fuzzy-search/worker/levenshteinWorker?url"
590
+
591
+ FuzzySearchManager.defaultWorkerUrls = { indexWorker: indexWorkerUrl, levenshteinWorker: levenshteinWorkerUrl }
592
+ ```
593
+
594
+ - When a worker fails, both pickers list direct matches only (the index worker) or the index worker's fuzzy matches
595
+ without the Levenshtein stage (the Levenshtein worker) for the rest of the page, and select-box reports the failure
596
+ once, naming the `workerId`.
597
+
553
598
  ### Sync requests: queued on link, followed through on screen
554
599
 
555
600
  The console never reaches the upstream itself. "Sync now" — and, since 0.15.0, **every link creation** — queues a request
@@ -791,6 +836,34 @@ this package's peers meets theirs too.
791
836
  an integer from 0 to 2147483647 and `timeoutMs` one from 1 to 2147483647 (`RangeError` otherwise).
792
837
  - **`false`** turns all of it off: nothing is stamped or checked, sign-out advances nothing, and the race above stays
793
838
  open.
839
+ - **Reader check of writes** (`readerCheck: boolean`, required): a page names the reader it was opened for on every
840
+ write it sends, so a write from a page another reader opened (a tab left open before someone else signed in on the
841
+ same browser) is not carried out under the new session.
842
+ - **The reader stamp**: the search parameter `_reader` (`READER_STAMP_SEARCH_PARAM`) holds `anonymous` for a page opened
843
+ signed out, or the HMAC-SHA-256 of the identity (`provider` and `id`) under the first session secret, in base64url
844
+ without padding (43 characters). Every secret of `session.secrets` verifies it, so a rotated secret keeps the stamps
845
+ it made valid while it stays in the list. `readerStampOf(reader)` makes the stamp of a page (`anonymous` for
846
+ `undefined`), whether `readerCheck` is on or not, so the pages can send stamped writes before the server checks them.
847
+ It reads the reader's `provider` and `id` alone, so a reader the host stripped of its tokens for the page's data gives
848
+ the same stamp as the session user.
849
+ - **What is checked**: with `readerCheck: true`, every request whose method is not GET or HEAD, through
850
+ `storage.resolveSession`, so every guard (`getSessionUser`, `requireUser`, `requireAdminUser`,
851
+ `authenticateInLoader`) checks it. Reads never read the stamp, and `readerCheck: false` reads none.
852
+ - **Missing or malformed stamp**: a write without `_reader`, with two of them, or with a value that is neither a keyed
853
+ stamp nor `anonymous` is refused with a 400 JSON response (`{ "error": "missing-reader-stamp" }` or
854
+ `{ "error": "malformed-reader-stamp" }`, `readerStampRefusalResponse`) thrown before the session is read: no
855
+ account check, no generation store, no `mockUser` backdoor.
856
+ - **Another reader** (`other-reader`): a well-formed stamp that does not match a signed-in session (the `mockUser`
857
+ backdoor's user included) resolves as not signed in, and the session is kept: `getSessionUser` returns `undefined`;
858
+ `requireUser` / `requireAdminUser` redirect to the sign-in page without the cookie's deletion; `authenticateInLoader`
859
+ returns `{}` in the `null` mode without a cookie and refreshes no token. It is logged with `logger.warn`, naming the
860
+ method, the path and the session's identity, never the stamp or the query. A stamp on a write whose session is
861
+ signed out, inactive or signed out by the generation does not change how that session resolves.
862
+ - **Not checked**: the raw session (`getSession`, `sessionStorage`) and the token pair (`authenticate`,
863
+ `refreshedAccessToken`), which work on a session their caller has read; read it through the guards. The sign-in
864
+ page's form posts to `loginAction`, which starts the sign-in and reads no session.
865
+ - **Settings**: anything but `true` or `false` — a missing key included — throws `TypeError` when the server is
866
+ built.
794
867
  - **`logoutLoader` refuses sign-outs the user did not ask for**, judged by the request's fetch metadata
795
868
  (`signOutRefusal`). It signs out a `Sec-Fetch-Dest: document` request only when its `Sec-Fetch-Site` is `none` (a typed
796
869
  address or a bookmark), `same-origin` or `same-site`, and a `Sec-Fetch-Dest: empty` request only when it is
package/dist/admin.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ConsoleUiLocale } from "@aiquants/console-ui/core";
2
2
  import { VirtualScrollLocale } from "@aiquants/virtualscroll";
3
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";
4
+ import { AuthUser, AuthGroup, AuthGroupMember, AuthAllowlistEntry, AuthDirectoryMembershipMode, AuthDirectoryStatus, AuthDirectoryCatalogSnapshot, AuthDirectoryCatalogGroup, AccessFailurePresenter, StampWrite } from "@aiquants/auth-core";
5
5
  import * as react_router from "react-router";
6
6
  import * as react from "react";
7
7
  import { ReactNode } from "react";
@@ -451,11 +451,14 @@ type UserAdminLoaderData = {
451
451
  fieldLimits: UserAdminFieldLimits;
452
452
  labels?: UserAdminLabels;
453
453
  };
454
- declare function UsersView(): react.JSX.Element;
455
- declare function GroupsView(): react.JSX.Element;
456
- declare function GroupMembersView(): react.JSX.Element;
457
- declare function AllowlistView(): react.JSX.Element;
458
- declare function DirectoryView(): react.JSX.Element;
459
- type AuthUserAdminAppViewProps = UserAdminShellProps;
460
- declare function AuthUserAdminAppView({ renderHeader, pendingSyncPolling, basePath, accessFailure }: AuthUserAdminAppViewProps): react.JSX.Element;
461
- 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 };
454
+ type UserAdminViewProps = {
455
+ readonly stampWrite: StampWrite;
456
+ };
457
+ declare function UsersView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
458
+ declare function GroupsView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
459
+ declare function GroupMembersView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
460
+ declare function AllowlistView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
461
+ declare function DirectoryView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
462
+ type AuthUserAdminAppViewProps = UserAdminShellProps & UserAdminViewProps;
463
+ declare function AuthUserAdminAppView({ renderHeader, pendingSyncPolling, basePath, accessFailure, stampWrite }: AuthUserAdminAppViewProps): react.JSX.Element;
464
+ 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, type UserAdminViewProps, UsersView, createInMemoryUserAdminStore, createUserAdminApp, defaultUserAdminLabels, jaUserAdminLabels, normalizeGroupKey, normalizeUpstreamKey, resolveUserAdminLabels, userAdminAccessFor, userAdminIntents };
package/dist/admin.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ConsoleUiLocale } from "@aiquants/console-ui/core";
2
2
  import { VirtualScrollLocale } from "@aiquants/virtualscroll";
3
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";
4
+ import { AuthUser, AuthGroup, AuthGroupMember, AuthAllowlistEntry, AuthDirectoryMembershipMode, AuthDirectoryStatus, AuthDirectoryCatalogSnapshot, AuthDirectoryCatalogGroup, AccessFailurePresenter, StampWrite } from "@aiquants/auth-core";
5
5
  import * as react_router from "react-router";
6
6
  import * as react from "react";
7
7
  import { ReactNode } from "react";
@@ -451,11 +451,14 @@ type UserAdminLoaderData = {
451
451
  fieldLimits: UserAdminFieldLimits;
452
452
  labels?: UserAdminLabels;
453
453
  };
454
- declare function UsersView(): react.JSX.Element;
455
- declare function GroupsView(): react.JSX.Element;
456
- declare function GroupMembersView(): react.JSX.Element;
457
- declare function AllowlistView(): react.JSX.Element;
458
- declare function DirectoryView(): react.JSX.Element;
459
- type AuthUserAdminAppViewProps = UserAdminShellProps;
460
- declare function AuthUserAdminAppView({ renderHeader, pendingSyncPolling, basePath, accessFailure }: AuthUserAdminAppViewProps): react.JSX.Element;
461
- 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 };
454
+ type UserAdminViewProps = {
455
+ readonly stampWrite: StampWrite;
456
+ };
457
+ declare function UsersView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
458
+ declare function GroupsView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
459
+ declare function GroupMembersView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
460
+ declare function AllowlistView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
461
+ declare function DirectoryView({ stampWrite }: UserAdminViewProps): react.JSX.Element;
462
+ type AuthUserAdminAppViewProps = UserAdminShellProps & UserAdminViewProps;
463
+ declare function AuthUserAdminAppView({ renderHeader, pendingSyncPolling, basePath, accessFailure, stampWrite }: AuthUserAdminAppViewProps): react.JSX.Element;
464
+ 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, type UserAdminViewProps, UsersView, createInMemoryUserAdminStore, createUserAdminApp, defaultUserAdminLabels, jaUserAdminLabels, normalizeGroupKey, normalizeUpstreamKey, resolveUserAdminLabels, userAdminAccessFor, userAdminIntents };