@softistx/alxia-react-router 0.87.0 → 0.89.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.
Files changed (76) hide show
  1. package/README.md +72 -3
  2. package/dist/chunks/{index-t2ph23wk.js → index-5hjhzztk.js} +6 -17
  3. package/dist/chunks/{index-t2ph23wk.js.map → index-5hjhzztk.js.map} +3 -4
  4. package/dist/chunks/{index-v2z5k640.js → index-6zx9dfvs.js} +3 -18
  5. package/dist/chunks/{index-v2z5k640.js.map → index-6zx9dfvs.js.map} +3 -4
  6. package/dist/chunks/index-njfh26ez.js +19 -0
  7. package/dist/chunks/index-njfh26ez.js.map +10 -0
  8. package/dist/chunks/index-t68hwhz1.js +37 -0
  9. package/dist/chunks/{index-0786n4qe.js.map → index-t68hwhz1.js.map} +5 -4
  10. package/dist/errors/index.js +5 -3
  11. package/dist/errors/index.js.map +2 -2
  12. package/dist/oidc/callback.d.ts +4 -0
  13. package/dist/oidc/callback.d.ts.map +1 -0
  14. package/dist/oidc/client.d.ts +57 -0
  15. package/dist/oidc/client.d.ts.map +1 -0
  16. package/dist/oidc/context.d.ts +42 -0
  17. package/dist/oidc/context.d.ts.map +1 -0
  18. package/dist/oidc/dpop-fetch.d.ts +40 -0
  19. package/dist/oidc/dpop-fetch.d.ts.map +1 -0
  20. package/dist/oidc/env.d.ts +52 -0
  21. package/dist/oidc/env.d.ts.map +1 -0
  22. package/dist/oidc/index.d.ts +5 -1
  23. package/dist/oidc/index.d.ts.map +1 -1
  24. package/dist/oidc/index.js +614 -326
  25. package/dist/oidc/index.js.map +19 -7
  26. package/dist/oidc/logout.d.ts +4 -0
  27. package/dist/oidc/logout.d.ts.map +1 -0
  28. package/dist/oidc/refresh.d.ts +10 -0
  29. package/dist/oidc/refresh.d.ts.map +1 -0
  30. package/dist/oidc/routes.d.ts +76 -0
  31. package/dist/oidc/routes.d.ts.map +1 -0
  32. package/dist/oidc/session.d.ts +7 -0
  33. package/dist/oidc/session.d.ts.map +1 -0
  34. package/dist/oidc/signin.d.ts +4 -0
  35. package/dist/oidc/signin.d.ts.map +1 -0
  36. package/dist/oidc/stored.d.ts +21 -0
  37. package/dist/oidc/stored.d.ts.map +1 -0
  38. package/dist/oidc/tokens.d.ts +13 -0
  39. package/dist/oidc/tokens.d.ts.map +1 -0
  40. package/dist/oidc/{oidc.d.ts → types.d.ts} +8 -45
  41. package/dist/oidc/{oidc.d.ts.map → types.d.ts.map} +1 -1
  42. package/dist/oidc/user.d.ts +6 -0
  43. package/dist/oidc/user.d.ts.map +1 -0
  44. package/dist/pwa/react/index.d.ts +2 -0
  45. package/dist/pwa/react/index.d.ts.map +1 -1
  46. package/dist/pwa/react/index.js +264 -3
  47. package/dist/pwa/react/index.js.map +6 -3
  48. package/dist/pwa/react/push-status.d.ts +31 -0
  49. package/dist/pwa/react/push-status.d.ts.map +1 -0
  50. package/dist/pwa/react/push-store.d.ts +55 -0
  51. package/dist/pwa/react/push-store.d.ts.map +1 -0
  52. package/dist/pwa/react/use-push-subscription.d.ts +15 -0
  53. package/dist/pwa/react/use-push-subscription.d.ts.map +1 -0
  54. package/dist/pwa/worker/index.d.ts +2 -0
  55. package/dist/pwa/worker/index.d.ts.map +1 -1
  56. package/dist/pwa/worker/index.js +94 -4
  57. package/dist/pwa/worker/index.js.map +7 -6
  58. package/dist/pwa/worker/plan.d.ts +7 -0
  59. package/dist/pwa/worker/plan.d.ts.map +1 -1
  60. package/dist/pwa/worker/push.d.ts +48 -0
  61. package/dist/pwa/worker/push.d.ts.map +1 -0
  62. package/dist/pwa/worker/scope.d.ts +23 -0
  63. package/dist/pwa/worker/scope.d.ts.map +1 -1
  64. package/dist/pwa/worker/start-worker.d.ts +2 -0
  65. package/dist/pwa/worker/start-worker.d.ts.map +1 -1
  66. package/dist/session/index.js +9 -7
  67. package/dist/session/index.js.map +2 -2
  68. package/dist/session/model/index.js +2 -2
  69. package/docs/README.md +1 -1
  70. package/docs/guide/fetcher.md +13 -0
  71. package/docs/guide/oidc.md +172 -6
  72. package/docs/guide/pwa.md +101 -1
  73. package/docs/roadmap.md +8 -0
  74. package/docs/troubleshooting.md +127 -0
  75. package/package.json +7 -7
  76. package/dist/chunks/index-0786n4qe.js +0 -25
package/docs/README.md CHANGED
@@ -26,7 +26,7 @@ installable and usable offline, wording an API's refusals, the BFF session, a Gr
26
26
  | [Lists whose state is the URL](guide/lists.md) | a search and filters in the address bar that drop the cursor (`useSearchChange`), a skeleton while the same page reloads (`useSameRouteLoading`), and a load-more button that appends pages by cursor and keeps the rows when one fails (`usePagedRows`), numbered pages over a cursor-paged connection (`connectionPage`), a connection's nodes as an array (`nodesOf`); `@softistx/alxia-react-router/lists` |
27
27
  | [Per-role flow docs and a help panel](guide/help.md) | documenting each role's flows screen by screen in `docs/flows/<name>.<lang>.md` (the front-matter format, steps, the four WebP captures), loading them at build time (`loadHelpFlows`), the flows of the current screen and the user's roles in the shape of `HelpSheet` (`useHelpFlows`), and the coverage check of routes, flows and captures (`alxia-react-router help check`); `@softistx/alxia-react-router/help`, `/help/check` |
28
28
  | [The consent screen of an OAuth server](guide/oauth.md) | letting a viewer allow or deny an OAuth client: `oauthConsent` (the route's loader and action over the janus-oauth GraphQL, passed in as functions), `useConsent` (the decision, the step-up replay, the callback) `oauthGrants` (an account's connected apps: the list newest first, the revoke) and the pure helpers; `@softistx/alxia-react-router/oauth` |
29
- | [A relying party of an OpenID Connect issuer](guide/oidc.md) | signing users in with an external issuer: `oidcClient` (authorization code + PKCE S256, state and nonce in a `__Host-` challenge cookie, discovery, the code exchange, the id token validated against the issuer's JWKS with `jose`, a sealed `__Host-` token cookie, a single-flight refresh, `requireOidcUser`, RP-initiated logout, pushed authorization requests, DPoP), its options and limits; `@softistx/alxia-react-router/oidc` |
29
+ | [A relying party of an OpenID Connect issuer](guide/oidc.md) | signing users in with an external issuer: `oidcClient` (authorization code + PKCE S256, state and nonce in a `__Host-` challenge cookie, discovery, the code exchange, the id token validated against the issuer's JWKS with `jose`, a sealed `__Host-` token cookie, a single-flight refresh, `requireOidcUser`, RP-initiated logout, pushed authorization requests, DPoP), `oidcFromEnv`, the route helpers (`signInRoute`, `callbackRoute`, `signOutRoute`) and `dpopFetch`, its options and limits; `@softistx/alxia-react-router/oidc` |
30
30
  | [Media through the BFF](guide/media.md) | serving and uploading an API's `@softistx/alxia-media` files on the app's own origin: `proxyMediaRead` and `proxyMediaWrite` in a `/media/*` resource route, the kinds and their limits, the same-site check, the 413 before the API, streaming both ways, Range and ETag passed through, the no-store exemption (`@softistx/alxia-react-router/media`), and the page's `uploadMedia` with progress, abort and typed refusals (`@softistx/alxia-react-router/media/client`) |
31
31
  | [A user's API keys](guide/api-keys.md) | listing a user's API keys, creating one behind a step-up with its secret shown once, and revoking one: `apiKeys` and the page's `useStepUpReplay` (`@softistx/alxia-react-router/api-keys`) |
32
32
  | [MCP and OAuth through the BFF](guide/mcp.md) | serving an API's MCP server and OAuth endpoints on the app's own origin: `mcpRelay` as a `beforeAll` plugin, the exact paths relayed, what is stripped and set on the request (Cookie, X-Forwarded-For, the shared secret, no Bearer) and on the response (Set-Cookie, CSP, nosniff), body limits and the timeout (`@softistx/alxia-react-router/mcp`) |
@@ -81,6 +81,19 @@ const onDelete = async () => {
81
81
  };
82
82
  ```
83
83
 
84
+ Since 0.87.0 `post` resolves to `Answer | undefined`, not `void`. A handler
85
+ typed `() => void | Promise<void>` that returns `post(...)` (a confirm
86
+ dialog's `onConfirm={() => post(...)}`) no longer typechecks. To ignore the
87
+ answer, discard it with `void`:
88
+
89
+ ```tsx
90
+ <ConfirmDialog onConfirm={() => { void post({ intent: 'delete', id }); }} />
91
+ ```
92
+
93
+ `async () => { await post(...); }` also typechecks, but it keeps the dialog
94
+ open until the answer arrives, so focus returns later than with `void post(...)`:
95
+ use it only when that is wanted.
96
+
84
97
  A confirm dialog whose `onConfirm` returns a Promise stays open, and shows the
85
98
  error, while the Promise rejects. `useFetcherPromise` ties a submission to the
86
99
  fetcher's next new answer, on top of `useFetcherAnswer`, so the app keeps no
@@ -5,11 +5,11 @@ Authentik, Google, Microsoft Entra, an in-house provider) is an OpenID
5
5
  Connect *relying party*. The API's own sessions (`/session`) and a social
6
6
  sign-in delegated to the API do not cover that: the code flow runs between
7
7
  the BFF and the issuer. `@softistx/alxia-react-router/oidc` holds the whole flow, so
8
- an app writes four small routes and no crypto.
8
+ an app writes no crypto (and [little else](#less-glue)).
9
9
 
10
10
  | subpath | holds | imports |
11
11
  | --- | --- | --- |
12
- | `@softistx/alxia-react-router/oidc` | `oidcClient`, `OidcError`, `generateDpopKey`, `signDpopProof`, the `OidcOptions`, `OidcClient`, `OidcUser`, `OidcErrorCode`, `DpopKey`, `DpopBinding`, `DpopAlgorithm` and `DpopProofInput` types | `react-router`, `/session`'s cookie helpers, `jose` (optional peer) |
12
+ | `@softistx/alxia-react-router/oidc` | `oidcClient`, `oidcFromEnv`, `signInRoute`, `callbackRoute`, `signOutRoute`, `dpopFetch`, `OidcEnvError`, `OidcError`, `generateDpopKey`, `signDpopProof`, and the types `OidcOptions`, `OidcClient`, `OidcUser`, `OidcErrorCode`, `OidcEnvSource` (what `oidcFromEnv` takes), `OidcEnvOptions` (what it returns), `SignInRouteOptions`, `CallbackRouteOptions`, `SignOutRouteOptions`, `DpopFetchOptions`, `DpopFetch`, `DpopRefresher`, `DpopKey`, `DpopBinding`, `DpopAlgorithm` and `DpopProofInput` | `react-router`, `/session`'s cookie helpers, `jose` (optional peer) |
13
13
 
14
14
  Install the peer: `bun add jose`.
15
15
 
@@ -30,9 +30,11 @@ Install the peer: `bun add jose`.
30
30
  - **The token cookie** `__Host-<name>` holds the id, access and refresh tokens
31
31
  sealed with the same secret: the browser cannot read or edit it.
32
32
  - **Refresh** when the access token ends within `refreshSkewSeconds` (60).
33
- Parallel requests share one refresh (single flight), and for ten seconds
34
- after it a request still carrying the spent refresh token is answered with
35
- the rotated result, so a rotating issuer does not sign the user out.
33
+ Parallel requests share one refresh (single flight), and for
34
+ `refreshFlightMs` (10 s by default) after it a request still carrying the
35
+ spent refresh token is answered with the rotated result, so a rotating issuer
36
+ does not sign the user out. The flight is per process: two replicas can still
37
+ spend one rotating refresh token twice.
36
38
  - **RP-initiated logout** to the issuer's `end_session_endpoint` with
37
39
  `id_token_hint` and `post_logout_redirect_uri`.
38
40
 
@@ -145,6 +147,169 @@ session cookie, nothing is called. A refresh token is revoked only when the sess
145
147
  with `?next=` set to the current path, through `safeNext`: a path of this site
146
148
  only, never an absolute URL.
147
149
 
150
+ ## Less glue
151
+
152
+ Three helpers remove the usual wiring. A BFF that signs in with PAR and DPoP then
153
+ needs no more than this:
154
+
155
+ ```ts
156
+ // app/oidc.server.ts
157
+ import { oidcClient, oidcFromEnv } from '@softistx/alxia-react-router/oidc';
158
+
159
+ export const oidc = oidcClient({
160
+ ...(await oidcFromEnv()),
161
+ secure: !import.meta.env.DEV,
162
+ scopes: ['profile', 'email', 'offline_access'],
163
+ par: 'always',
164
+ dpop: {},
165
+ revokeOnLogout: true,
166
+ });
167
+ ```
168
+
169
+ Top-level `await` needs an ES module entry (Bun and Vite's SSR build have one).
170
+ Where a module cannot await, read the settings in the entry and pass them in:
171
+
172
+ ```ts
173
+ // app/oidc.server.ts, without top-level await
174
+ import { oidcClient, type OidcEnvOptions } from '@softistx/alxia-react-router/oidc';
175
+
176
+ export const createOidc = (env: OidcEnvOptions) =>
177
+ oidcClient({ ...env, secure: !import.meta.env.DEV, scopes: ['profile', 'offline_access'] });
178
+ ```
179
+
180
+ ```ts
181
+ // app/routes/sign-in.ts
182
+ import { signInRoute } from '@softistx/alxia-react-router/oidc';
183
+ import { oidc } from '../oidc.server';
184
+
185
+ export const { loader } = signInRoute(oidc);
186
+ ```
187
+
188
+ ```ts
189
+ // app/routes/auth.callback.ts: an OidcError redirects to /sign-in/failed?sign-in-error=<code>
190
+ import { callbackRoute } from '@softistx/alxia-react-router/oidc';
191
+ import { oidc } from '../oidc.server';
192
+
193
+ export const { loader } = callbackRoute(oidc, { errorPath: '/sign-in/failed' });
194
+ ```
195
+
196
+ ```ts
197
+ // app/routes/sign-out.ts
198
+ import { signOutRoute } from '@softistx/alxia-react-router/oidc';
199
+ import { oidc } from '../oidc.server';
200
+
201
+ export const { action, loader } = signOutRoute(oidc);
202
+ ```
203
+
204
+ ```ts
205
+ // app/routes/orders.ts: a loader that calls an API as the user
206
+ import { data, type LoaderFunctionArgs } from 'react-router';
207
+ import { dpopFetch } from '@softistx/alxia-react-router/oidc';
208
+ import { oidc } from '../oidc.server';
209
+
210
+ export async function loader({ request }: LoaderFunctionArgs) {
211
+ const user = await oidc.requireOidcUser(request);
212
+ const response = await dpopFetch(oidc, user)('https://api.example.com/orders?page=2');
213
+ return data(await response.json(), { headers: user.headers });
214
+ }
215
+ ```
216
+
217
+ ### `oidcFromEnv`
218
+
219
+ Reads the settings once, at start-up (it is `async`: it reads the secret files).
220
+ Every missing or malformed variable is listed in a single `OidcEnvError`
221
+ (`error.problems`), and a secret's value is never in a message. Its input is
222
+ `OidcEnvSource`, its result `OidcEnvOptions`, to spread into `oidcClient`.
223
+
224
+ | variable | |
225
+ | --- | --- |
226
+ | `OIDC_ISSUER` | required; `https:` (`http:` on loopback) |
227
+ | `OIDC_CLIENT_ID` | required |
228
+ | `OIDC_CLIENT_SECRET_FILE` or `OIDC_CLIENT_SECRET` | the secret of a confidential client; none for a public one |
229
+ | `OIDC_REDIRECT_URI` | required; `https:` (`http:` on loopback) |
230
+ | `OIDC_SESSION_SECRET_FILE` or `OIDC_SESSION_SECRET` | required, 32 characters or more |
231
+ | `OIDC_COOKIE_NAME` | `oidc` by default |
232
+ | `OIDC_POST_LOGOUT_REDIRECT_URI` | optional; `https:` (`http:` on loopback) |
233
+
234
+ `secure` is not read from the environment: pass it to `oidcClient` yourself
235
+ (`!import.meta.env.DEV` above), so a missing variable can never turn the
236
+ `Secure` cookie off.
237
+
238
+ A `_FILE` variable names a file; its trimmed content is the value (a Docker or
239
+ Kubernetes secret). The file must be readable by its owner only (no group or
240
+ other permission bit, such as `chmod 600`), else it is refused. Set one or the
241
+ other, not both. `prefix: 'SSO'` reads `SSO_*` instead; `env`, `readFile` and
242
+ `statFile` are there for tests. The default `readFile` is `Bun.file(path).text()`
243
+ (and `statFile` `Bun.file(path).stat()`), so `OIDC_*_FILE` needs Bun, or your own
244
+ `readFile` and `statFile` elsewhere. The scopes, `par`, `dpop` and the other options are not read from the
245
+ environment: pass them to `oidcClient`.
246
+
247
+ ### The route helpers
248
+
249
+ Each returns the exports of a route module, so a route is one line. Every one
250
+ takes `guard(request)` to run first (refuse a host, say) by throwing.
251
+ `errorPath` and `redirectTo` must be paths of this site (a single leading `/`);
252
+ anything else is a `TypeError` when the route is made.
253
+
254
+ - `signInRoute(oidc)`: `loader`, a redirect to the issuer; `?next=` is kept.
255
+ - `callbackRoute(oidc, { errorPath, onError })`: `loader`. An `OidcError` is
256
+ answered, never thrown, with the cookie that clears the spent challenge:
257
+ by default a redirect to `errorPath` (`/`, no query) with `?sign-in-error=<code>`, or
258
+ whatever `onError(error)` returns (put `error.headers` on it). Any other error is thrown.
259
+ - `signOutRoute(oidc, { origin, redirectTo })`: `action` refuses a cross-site
260
+ request (give `origin` behind a TLS-terminating proxy), then calls `logout`.
261
+ When discovery announces an `end_session_endpoint` the browser goes there
262
+ with `id_token_hint`, `client_id` and `post_logout_redirect_uri`
263
+ (RP-initiated logout); otherwise only the local session ends and the browser
264
+ goes to `postLogoutRedirectUri` or `/`. A GET (`loader`) only redirects to
265
+ `redirectTo` (`/`), so a link cannot sign the user out.
266
+
267
+ The option types are `SignInRouteOptions`, `CallbackRouteOptions` and
268
+ `SignOutRouteOptions`.
269
+
270
+ ### `dpopFetch` and `oidc.refresh`
271
+
272
+ `dpopFetch(oidc, user, options)` is a `fetch` for calls to an API as the user.
273
+ On a DPoP-bound session each call carries `Authorization: DPoP <token>` and a
274
+ fresh proof: `htm` (the method), `htu` (the URL without its query), `ath` (the
275
+ token's hash) and `jti`. A `401` with `WWW-Authenticate: DPoP
276
+ error="use_dpop_nonce"` is signed again with the `DPoP-Nonce` it sent and
277
+ retried once; the nonce is kept per server for the next calls. On a bearer
278
+ session it sends `Authorization: Bearer` through the client's own `fetch`. A
279
+ body must be a string or bytes. Its options are `DpopFetchOptions`.
280
+
281
+ It keeps the last user it got. Before each call it asks `oidc.refresh(user)`,
282
+ which refreshes only when the access token ends within `refreshSkewSeconds`,
283
+ and from that user's own tokens, never from the request's cookie: an issuer
284
+ that rotates refresh tokens refuses the old one, which the cookie still holds
285
+ once a refresh has happened. Collect the new cookie with `onUser`:
286
+
287
+ ```ts
288
+ import { data, type LoaderFunctionArgs } from 'react-router';
289
+ import { dpopFetch } from '@softistx/alxia-react-router/oidc';
290
+ import { oidc } from '../oidc.server';
291
+
292
+ export async function loader({ request }: LoaderFunctionArgs) {
293
+ let latest = await oidc.requireOidcUser(request);
294
+ const api = dpopFetch(oidc, latest, { onUser: (user) => (latest = user) });
295
+ const a = await (await api('https://api.example.com/a')).json();
296
+ const b = await (await api('https://api.example.com/b')).json();
297
+ return data({ a, b }, { headers: latest.headers });
298
+ }
299
+ ```
300
+
301
+ `oidc.refresh(user, { force? })` is there for code that holds a user for long:
302
+ it returns `user` itself while nothing is due (or when a transient failure
303
+ leaves a still-valid token), else a new user whose `headers` hold the
304
+ `Set-Cookie`, and throws `OidcError` (`refresh-failed`) once the token has
305
+ ended and the refresh fails. With `{ force: true }` it refreshes even when nothing
306
+ is due; with no refresh token it returns `user` unchanged while the access token
307
+ is valid, and a forced refresh inside the `refreshFlightMs` window (10 s) shares
308
+ the tokens of the flight already under way. Only a user this client returned can be
309
+ refreshed: a spread copy `{ ...user }` or a user of another client is a `TypeError`.
310
+ `OidcUser.fetch` is the client's own fetcher (its `fetch` option), which `dpopFetch`
311
+ uses for a bearer call.
312
+
148
313
  ## Options
149
314
 
150
315
  | option | default | |
@@ -154,11 +319,12 @@ only, never an absolute URL.
154
319
  | `scopes` | `profile email` | `openid` is always added |
155
320
  | `secret` | required | 32 characters or more; changing it signs everyone out |
156
321
  | `name` | required | the cookies' base name; `__Host-` is added when `secure` |
157
- | `secure` | required | pass `!import.meta.env.DEV` |
322
+ | `secure` | required | pass `!import.meta.env.DEV`; never read from the environment |
158
323
  | `signInPath` | `/sign-in` | where `requireOidcUser` redirects |
159
324
  | `postLogoutRedirectUri` | none | after `logout`; without it, `/` |
160
325
  | `sessionSeconds` | 30 days | the token cookie's life when there is a refresh token |
161
326
  | `refreshSkewSeconds` | 60 | refresh this long before the access token ends |
327
+ | `refreshFlightMs` | 10000 | parallel refreshes with one refresh token share one call this long, in ms; 0 or more, well under the access token's lifetime |
162
328
  | `clockToleranceSeconds` | 30 | accepted clock difference on `exp` and `iat` |
163
329
  | `algorithms` | `RS256 PS256 ES256 EdDSA` | accepted id token algorithms |
164
330
  | `authorizationParams` | none | extra authorization parameters, e.g. `{ prompt: 'login' }` |
package/docs/guide/pwa.md CHANGED
@@ -32,7 +32,7 @@ globals only inside its functions, never at load.
32
32
  | subpath | for | needs |
33
33
  | --- | --- | --- |
34
34
  | `/pwa` | every runtime: the contract, `cachingFor`, `isStorable`, `registerServiceWorker`, `createUpdateNotice`, `manifestHref`, `webAppManifest`, `clearAppCaches`, the precache parts and `SERVICE_WORKER_URL` | nothing: it imports nothing |
35
- | `/pwa/react` | the page's hooks: `useServiceWorker`, `useUpdateNotice`, `useOnline` | `react` (`^19`), an optional peer. Keep it out of the worker, which would bundle React |
35
+ | `/pwa/react` | the page's hooks: `useServiceWorker`, `useUpdateNotice`, `useOnline`, `usePushSubscription`, `usePushStatus` | `react` (`^19`), an optional peer. Keep it out of the worker, which would bundle React |
36
36
  | `/pwa/server` | the server file alone: `noCache` and `revalidated` | `@softistx/alxia`, a peer the package already has |
37
37
  | `/pwa/worker` | the service worker bundle alone: `startWorker`, `injectedPrecache` | the six `workbox-*` packages (`core`, `expiration`, `navigation-preload`, `precaching`, `routing`, `strategies`), optional peers (`^7`) |
38
38
  | `/pwa/build` | a build pipeline of your own: `buildWorker` | Bun; Node's built-ins are its only imports, and it reads `Bun` only inside the function. The Workbox peers must be installed to bundle the worker |
@@ -107,6 +107,7 @@ the six `workbox-*` packages it bundles as development dependencies
107
107
  | `static` | `{ maxEntries: 100, maxAgeSeconds: 2592000 }` | the same for the other static files (30 days) |
108
108
  | `navigationPreload` | `true` | the browser starts a page load's request alongside the worker |
109
109
  | `precache` | the list the build wrote in | `[{ url, revision }]`; a worker with neither throws at once |
110
+ | `push` | off | `true` or `{ fallbackTitle, icon, badge }`: show pushed notices and open them on click ([Push notifications](#push-notifications)) |
110
111
 
111
112
  What each answer of `cachingFor` becomes:
112
113
 
@@ -132,6 +133,103 @@ own bundle). Read without the build it is `undefined`, so the
132
133
  worker's error is [`startWorker(): no precache list`](../troubleshooting.md#startworker-no-precache-list-)
133
134
  instead of a `ReferenceError`.
134
135
 
136
+ ### Push notifications
137
+
138
+ Opt in with `push: true` and the worker shows pushed notices and opens them on
139
+ click. An app without it is unchanged: no `push` or `notificationclick`
140
+ listener is added.
141
+
142
+ ```ts
143
+ startWorker({
144
+ contract: workerContract,
145
+ push: { fallbackTitle: 'My app', icon: '/icons/192.png' },
146
+ });
147
+ ```
148
+
149
+ - **`push` event.** `handlePush` reads the JSON payload
150
+ `{ title, body?, url?, tag? }` and calls `showNotification`. With no payload,
151
+ or one that is not JSON or has no `title`, it shows `fallbackTitle`
152
+ (`'Notification'` by default), so a push is never silent. `icon` and
153
+ `badge` apply to every notice.
154
+ - **`notificationclick` event.** `handleNotificationClick` closes the notice,
155
+ then focuses an open window of the app (navigating it to `url` when it can)
156
+ or opens `url`. Only a same-origin `url` is used: a cross-origin or
157
+ malformed one is refused and the app's own origin is focused or opened
158
+ instead.
159
+
160
+ `handlePush(event, options?)` and `handleNotificationClick(event)` are also
161
+ exported from `/pwa/worker`, for a worker of your own that registers its
162
+ listeners itself. The subscription (VAPID key, `pushManager.subscribe`) stays
163
+ the page's job: `usePushSubscription()` from `/pwa/react` does it
164
+ ([Subscribing from the page](#subscribing-from-the-page)).
165
+
166
+ #### Subscribing from the page
167
+
168
+ ```tsx
169
+ // file: app/push-button.tsx
170
+ import { type PushSubscriptionJson, usePushSubscription } from '@softistx/alxia-react-router/pwa/react';
171
+
172
+ // Your own calls to the server (the subscribePush / unsubscribePush mutations).
173
+ declare function sendToServer(subscription: PushSubscriptionJson): Promise<void>;
174
+ declare function sendEndpointToServer(endpoint: string | null): Promise<void>;
175
+
176
+ export function PushButton({ vapidPublicKey }: { vapidPublicKey: string }) {
177
+ const push = usePushSubscription();
178
+ if (push.status === 'unsupported') return null;
179
+ if (push.status === 'install-required') return <p>Add the app to your home screen to get notices.</p>;
180
+ if (push.status === 'denied') return <p>Notices are blocked in your browser settings.</p>;
181
+ if (push.status === 'granted') {
182
+ return <button type="button" onClick={() => push.unsubscribe().then(sendEndpointToServer)}>Turn off</button>;
183
+ }
184
+ return (
185
+ <button type="button" disabled={push.status === 'asking'} onClick={() => push.subscribe(vapidPublicKey).then((json) => json && sendToServer(json))}>
186
+ Turn on
187
+ </button>
188
+ );
189
+ }
190
+ ```
191
+
192
+ - **`status`** is `available | asking | granted | denied | install-required | unsupported`.
193
+ `granted` means permission is granted **and** this browser holds a
194
+ subscription; permission with no subscription is `available`. `asking` is
195
+ while `subscribe()` runs. `install-required` is iOS outside an installed
196
+ app (no `display-mode: standalone`, no `PushManager`). On the server and
197
+ while hydrating it is `unsupported`; the browser is read in an effect, so no
198
+ `window` access happens during render. `usePushStatus()` returns just the
199
+ status, for a presentational opt-in card's `status` prop; `derivePushStatus(facts)`
200
+ is the pure rule.
201
+ - **One shared state.** Every `usePushSubscription()` and `usePushStatus()` on
202
+ the page reads one store, so a card and a button always agree. It reads the
203
+ browser once something is mounted, and again when the tab shows or the
204
+ permission changes (`navigator.permissions` `onchange` where available, the
205
+ `visibilitychange` event as the fallback), so a change in the browser's
206
+ settings shows up.
207
+ - **Never prompts on mount.** `subscribe(vapidPublicKey)` calls
208
+ `Notification.requestPermission()` only inside the call, so call it from a
209
+ click. A second call while one runs returns the same promise. It first checks
210
+ that a service worker is registered (before the prompt, so the user is never
211
+ asked for nothing) and rejects otherwise with
212
+ `usePushSubscription: no service worker is registered; register the service worker first`
213
+ ([troubleshooting](../troubleshooting.md#usepushsubscription-no-service-worker-is-registered-register-the-service-worker-first)). If permission is not granted it resolves `null`. Otherwise it calls
214
+ `pushManager.subscribe({ userVisibleOnly: true, applicationServerKey })`
215
+ (the base64url key decoded to bytes) and resolves with the
216
+ subscription's `toJSON()` for the app to send to its server. On a browser
217
+ with no Web Push, `subscribe` and `unsubscribe` resolve `null`.
218
+ - **A new VAPID key replaces the old subscription.** A subscription made with
219
+ another key (or an `InvalidStateError` from the browser) is unsubscribed and
220
+ made again, and the old endpoint is in `replaced` so the app can tell its
221
+ server (`unsubscribePush`) to drop it. A subscription already made with the
222
+ same key is returned as it is.
223
+ - **`unsubscribe()`** unsubscribes and resolves with the endpoint (to tell the
224
+ server), or `null` when there was none.
225
+ - The state also has `supported`, `permission` (`default | granted | denied`),
226
+ `installedPwa`, `subscription` (`toJSON()` or `null`) and `replaced`.
227
+ - **Types and helpers.** `PushSubscriptionState` is the hook's return type,
228
+ `PushSubscriptionJson` the shape `subscribe()` resolves, `PushFacts` and
229
+ `PushPermission` what `derivePushStatus(facts)` reads, and
230
+ `urlBase64ToBytes(key)` decodes a base64url VAPID key to the bytes
231
+ `applicationServerKey` takes.
232
+
135
233
  ## What the worker caches
136
234
 
137
235
  `cachingFor(request, origin, options?)` answers with one of four words:
@@ -464,6 +562,8 @@ export function UpdateBanner() {
464
562
  `undefined` on the server and while hydrating.
465
563
  - **`useOnline()`** is `navigator.onLine`, `true` on the server and while
466
564
  hydrating, so the first client render matches the server's.
565
+ - **`usePushSubscription()`** and **`usePushStatus()`** are described under
566
+ [Push notifications](#push-notifications).
467
567
  - **`updateNotice`** is the page's one store. It is made in this subpath, not in
468
568
  `/pwa`, so the model a worker bundle imports does nothing at load. Both
469
569
  hooks use it unless given another `notice`; pass the same store to both
package/docs/roadmap.md CHANGED
@@ -133,6 +133,14 @@ Nothing queued; see Later.
133
133
 
134
134
  ### Unreleased
135
135
 
136
+ - **`/oidc` helpers: less glue for a BFF.** `oidcFromEnv` (the settings from
137
+ `OIDC_*` variables and secret files, every start-up problem in one error),
138
+ `signInRoute`, `callbackRoute` and `signOutRoute` (the route modules in one
139
+ line, sign-out RP-initiated when the issuer announces `end_session_endpoint`)
140
+ and `dpopFetch` (API calls signed with DPoP, one `use_dpop_nonce` retry, an
141
+ ended token refreshed from the last user, with `oidc.refresh(user)`). See the
142
+ [OIDC guide](guide/oidc.md#less-glue).
143
+
136
144
  - **`useJsonFetcher(...).post` resolves with the answer.** `const answer =
137
145
  await post(body)` gives the action's JSON, a refusal included, once the
138
146
  fetcher is idle again; `undefined` when the call was replaced, the
@@ -9,6 +9,11 @@ a loader, a message React Router or the browser prints, or an error from
9
9
 
10
10
  - [`GET https://registry.npmjs.org/@softistx/… - 401`, or `404` on a `@softistx` package](#get-httpsregistrynpmjsorgsoftistx---401-or-404-on-a-softistx-package)
11
11
  - [`docs/flows/…: <what is wrong with the front-matter>`](#docsflows-what-is-wrong-with-the-front-matter)
12
+ - [`The OIDC environment is not usable:` (`/oidc`)](#the-oidc-environment-is-not-usable-oidc)
13
+ - [`TypeError: callbackRoute(): errorPath must be a path of this site with no query or fragment, starting with a single "/"; got ….` (`/oidc`)](#typeerror-callbackroute-errorpath-must-be-a-path-of-this-site-with-no-query-or-fragment-starting-with-a-single--got--oidc)
14
+ - [`TypeError: signOutRoute(): redirectTo must be a path of this site, starting with a single "/"; got ….` (`/oidc`)](#typeerror-signoutroute-redirectto-must-be-a-path-of-this-site-starting-with-a-single--got--oidc)
15
+ - [`TypeError: oidcClient(): refreshFlightMs must be a finite number of milliseconds, from 0 to 2147483647.` (`/oidc`)](#typeerror-oidcclient-refreshflightms-must-be-a-finite-number-of-milliseconds-from-0-to-2147483647-oidc)
16
+ - [`TypeError: oidc.refresh(): the user was not returned by this client.` (`/oidc`)](#typeerror-oidcrefresh-the-user-was-not-returned-by-this-client-oidc)
12
17
  - [`The returned state is not the one this sign-in sent.` and the other `OidcError` messages (`/oidc`)](#the-returned-state-is-not-the-one-this-sign-in-sent-and-the-other-oidcerror-messages-oidc)
13
18
  - [`capture file x.1440.light.webp is missing from docs/flows/captures/`](#capture-file-x1440lightwebp-is-missing-from-docsflowscaptures)
14
19
  - [`route "x" is covered by no flow: …`](#route-x-is-covered-by-no-flow-cite-it-in-a-flows-routes-or-add-it-to-the-ignore-list)
@@ -62,6 +67,7 @@ a loader, a message React Router or the browser prints, or an error from
62
67
  - [`TypeError: defineWorkerContract(): cacheVersion must be a non-empty name without '-', …`](#typeerror-defineworkercontract-cacheversion-must-be-a-non-empty-name-without---)
63
68
  - [`parseBrowserManifest(): not React Router's browser manifest …`](#parsebrowsermanifest-not-react-routers-browser-manifest-)
64
69
  - [`error: Cannot find package 'react' from '…/@softistx/alxia-react-router/dist/pwa/react/index.js'`](#error-cannot-find-package-react-from-softistxalxia-react-routerdistpwareactindexjs)
70
+ - [`usePushSubscription: no service worker is registered; register the service worker first`](#usepushsubscription-no-service-worker-is-registered-register-the-service-worker-first)
65
71
  - [`error: Cannot find package 'isbot' from '…/@softistx/alxia-react-router/dist/entry/index.js'`](#error-cannot-find-package-isbot-from-softistxalxia-react-routerdistentryindexjs)
66
72
  - [`error: Cannot find package '@softistx/alxia-proxy' from '…/@softistx/alxia-react-router/dist/mcp/index.js'`](#error-cannot-find-package-softistxalxia-proxy-from-softistxalxia-react-routerdistmcpindexjs)
67
73
  - [`TypeError: proxy(): the target must be an absolute URL, http:// or https://; got "…"`](#typeerror-proxy-the-target-must-be-an-absolute-url-http-or-https-got-)
@@ -1514,6 +1520,23 @@ this message too.
1514
1520
  `/pwa/react` from the page alone. The worker and a build script import
1515
1521
  `@softistx/alxia-react-router/pwa`, which imports nothing.
1516
1522
 
1523
+ ### `usePushSubscription: no service worker is registered; register the service worker first`
1524
+
1525
+ **When:** `subscribe(vapidPublicKey)` from `usePushSubscription()` is called
1526
+ on a page where no service worker is registered. The permission prompt is
1527
+ not shown.
1528
+
1529
+ **Why:** Web Push subscribes through the worker's registration, and
1530
+ `subscribe` checks for one before it asks the user, so nobody is prompted
1531
+ for a subscription that cannot be made. `useServiceWorker()` registers only
1532
+ when `enabled` is true (the app passes `import.meta.env.PROD`), so under
1533
+ `react-router dev` there is no worker.
1534
+
1535
+ **Fix:** call `useServiceWorker({ enabled: import.meta.env.PROD })` in the
1536
+ root route, and try push on a production build (`react-router build`, then
1537
+ start the server). Built with `push: true` in `startWorker()`, the worker
1538
+ also shows the notices it receives.
1539
+
1517
1540
  ### `error: Cannot find package 'isbot' from '…/@softistx/alxia-react-router/dist/entry/index.js'`
1518
1541
 
1519
1542
  **When:** a request with a user agent reaches `entry.server.tsx` re-exporting
@@ -2414,6 +2437,110 @@ catch (error) {
2414
2437
  }
2415
2438
  ```
2416
2439
 
2440
+ `callbackRoute(oidc, { errorPath })` does this for you.
2441
+
2442
+ See the [OIDC guide](guide/oidc.md).
2443
+
2444
+ ### `TypeError: callbackRoute(): errorPath must be a path of this site with no query or fragment, starting with a single "/"; got ….` (`/oidc`)
2445
+
2446
+ ```
2447
+ TypeError: callbackRoute(): errorPath must be a path of this site with no query or fragment, starting with a single "/"; got "https://evil.test".
2448
+ ```
2449
+
2450
+ **When:** the app calls `callbackRoute(oidc, { errorPath })` at startup.
2451
+
2452
+ **Why:** a failed callback redirects to `errorPath?sign-in-error=<code>`, so `errorPath` must be a path of this site: relative, starting with `//` or `/\`, an absolute URL, or holding a query (`?`) or fragment (`#`) is refused when the route is created, not at the first failure.
2453
+
2454
+ **Fix:** give the path alone; the code is added for you:
2455
+
2456
+ ```ts
2457
+ export const { loader } = callbackRoute(oidc, { errorPath: '/sign-in/failed' });
2458
+ ```
2459
+
2460
+ ### `TypeError: signOutRoute(): redirectTo must be a path of this site, starting with a single "/"; got ….` (`/oidc`)
2461
+
2462
+ ```
2463
+ TypeError: signOutRoute(): redirectTo must be a path of this site, starting with a single "/"; got "//evil.test".
2464
+ ```
2465
+
2466
+ **When:** the app calls `signOutRoute(oidc, { redirectTo })` at startup.
2467
+
2468
+ **Why:** after a local sign-out the route redirects to `redirectTo`, so it must be a path of this site: relative, an absolute URL, or starting with `//` or `/\` (which a redirect reads as another site) is refused. A query (`/?signed-out=1`) and a fragment (`/bye#done`) are allowed here.
2469
+
2470
+ **Fix:** pass a path of this site:
2471
+
2472
+ ```ts
2473
+ export const { action, loader } = signOutRoute(oidc, { redirectTo: '/?signed-out=1' });
2474
+ ```
2475
+
2476
+ ### `TypeError: oidcClient(): refreshFlightMs must be a finite number of milliseconds, from 0 to 2147483647.` (`/oidc`)
2477
+
2478
+ ```
2479
+ TypeError: oidcClient(): refreshFlightMs must be a finite number of milliseconds, from 0 to 2147483647.
2480
+ ```
2481
+
2482
+ **When:** the app calls `oidcClient({ refreshFlightMs })` at startup.
2483
+
2484
+ **Why:** `refreshFlightMs` is how long parallel refreshes share one flight. A negative number, `NaN`, `Infinity` or a value past 2147483647 (the longest a timer can wait; 2147483647 itself is allowed) is refused when the client is made. `0` is allowed: the flight is forgotten at once.
2485
+
2486
+ **Fix:** leave it out (10 s), or give a number of milliseconds well under the access token's lifetime:
2487
+
2488
+ ```ts
2489
+ oidcClient({ ...options, refreshFlightMs: 5_000 });
2490
+ ```
2491
+
2492
+ ### `TypeError: oidc.refresh(): the user was not returned by this client.` (`/oidc`)
2493
+
2494
+ ```
2495
+ TypeError: oidc.refresh(): the user was not returned by this client.
2496
+ ```
2497
+
2498
+ **When:** the app calls `oidc.refresh(user)` or `dpopFetch(oidc, user)` with a user that `oidc` did not return.
2499
+
2500
+ **Why:** the client refreshes from the tokens it holds for each user it returned (`oidcUser`, `requireOidcUser`, a previous `refresh`), not from the fields of the object. A spread copy (`{ ...user }`), a hand-made double or a user of another `oidcClient` has none, so it is refused rather than refreshed from a guess.
2501
+
2502
+ **Fix:** pass the user as `oidcUser` or `requireOidcUser` returned it, or the one `refresh` or `onUser` gave back:
2503
+
2504
+ ```ts
2505
+ const user = await oidc.requireOidcUser(request);
2506
+ const fresh = await oidc.refresh(user, { force: true });
2507
+ ```
2508
+
2509
+ See the [OIDC guide](guide/oidc.md).
2510
+
2511
+ ### `The OIDC environment is not usable:` (`/oidc`)
2512
+
2513
+ **When:** the server starts and `await oidcFromEnv()` throws an `OidcEnvError`
2514
+ whose message lists the problems, one per line. `error.problems` holds them.
2515
+
2516
+ **Why, by line:**
2517
+
2518
+ - `OIDC_ISSUER is not an absolute URL.` or `OIDC_ISSUER must be an https: URL.`
2519
+ (also `OIDC_REDIRECT_URI` and `OIDC_POST_LOGOUT_REDIRECT_URI`): the value has
2520
+ no scheme and host, or it is `http:` and not on loopback (`localhost`,
2521
+ `127.0.0.1`, `[::1]`); an address is `https:`, or `http:` on loopback.
2522
+ - `OIDC_ISSUER is not set.` (or `OIDC_CLIENT_ID`, `OIDC_REDIRECT_URI`) and
2523
+ `OIDC_SESSION_SECRET_FILE (or OIDC_SESSION_SECRET) is not set.`: a required
2524
+ variable is missing.
2525
+ - `Set OIDC_CLIENT_SECRET or OIDC_CLIENT_SECRET_FILE, not both.`: a secret is
2526
+ given directly and through a file.
2527
+ - `OIDC_SESSION_SECRET_FILE names a file that cannot be read: check the path and its permissions.`: the path,
2528
+ the mount, or the permissions. Without Bun the default reader is missing: pass
2529
+ `readFile` and `statFile`.
2530
+ - `OIDC_SESSION_SECRET_FILE names a file readable by group or others (mode …)`:
2531
+ `chmod 600` the file.
2532
+ - `OIDC_SESSION_SECRET_FILE names a file with whitespace inside: it must hold one value.`:
2533
+ a secret is one token; a space or a line break inside the file refuses it (a
2534
+ trailing newline is trimmed). The message never prints the path.
2535
+ - `OIDC_SESSION_SECRET_FILE names an empty file.`: the secret file has only
2536
+ whitespace.
2537
+ - `The session secret must be 32 characters or more (OIDC_SESSION_SECRET_FILE).`:
2538
+ the variable it came from is named.
2539
+
2540
+ **Fix:** set what the list names; the error holds every problem at once. A
2541
+ prefix other than `OIDC` is passed as `oidcFromEnv({ prefix })`. `secure` is not
2542
+ a variable: pass `secure: !import.meta.env.DEV` to `oidcClient`.
2543
+
2417
2544
  See the [OIDC guide](guide/oidc.md).
2418
2545
 
2419
2546
  ## Types
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softistx/alxia-react-router",
3
- "version": "0.87.0",
3
+ "version": "0.89.0",
4
4
  "description": "alxia as the server of a React Router framework app: server rendering behind the app's hooks, loaders reading its typed context, the client's assets served; the code with no UI an installable app shares (`/pwa`), its hooks (`/pwa/react`), `noCache` for the worker's script (`/pwa/server`), the service worker on Workbox (`/pwa/worker`) and its build (`/pwa/build`), an API's refusals worded for the page (`/errors`), the BFF session: cookies, sign-in, step-up and mail links (`/session`), its page hooks (`/session/react`) and what it shares with the page (`/session/model`), a GraphQL subscription relayed to the browser over SSE (`/subscription`) and kept alive in the page (`/subscription/react`), an API's MCP and OAuth endpoints relayed on the app's origin (`/mcp`), per-role flow docs, the help panel's data and its lazy `HelpPanel`, and the role guide's `useGuideRole` (`/help`, `/help/check`), an API's media files read and uploaded through the app (`/media`) and uploaded from the page with progress (`/media/client`), the page's CSP nonce and inline boot scripts (`/document`) and a streaming `entry.server` (`/entry`), the consent screen of an OAuth server: a route's loader and action, the connected apps' list and revoke (`/oauth`) and the decision hook (`/oauth/react`), a user's API keys listed, created behind a step-up and revoked (`/api-keys`) and `/oidc`: a relying party of an external OpenID Connect issuer (authorization code + PKCE, id token validation, a sealed token cookie, refresh and RP-initiated logout)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -213,20 +213,20 @@
213
213
  "@softistx/alxia-proxy": "^0.5.0",
214
214
  "@softistx/alxia-secure-headers": "^0.6.0",
215
215
  "@softistx/graphql-client": "^0.13.0",
216
- "@react-router/dev": "^8.5.0",
217
- "@softistx/janus": "^0.80.0",
216
+ "@react-router/dev": "^8.5.3",
217
+ "@softistx/janus": "^0.85.0",
218
218
  "@types/bun": "^1.4.5",
219
- "@types/react": "^19.3.0",
219
+ "@types/react": "^19.3.3",
220
220
  "@types/react-dom": "^19.3.0",
221
221
  "graphql": "^17.0.2",
222
222
  "happy-dom": "^21.0.4",
223
- "intl-messageformat": "^12.1.4",
224
- "isbot": "^5.2.2",
223
+ "intl-messageformat": "^12.2.1",
224
+ "isbot": "^5.2.4",
225
225
  "jose": "^6.2.0",
226
226
  "react": "^19.3.1",
227
227
  "react-dom": "^19.3.1",
228
228
  "react-hook-form": "^7.91.0",
229
- "react-router": "^8.5.0",
229
+ "react-router": "^8.5.3",
230
230
  "vite": "^7.0.0",
231
231
  "workbox-core": "^7.4.1",
232
232
  "workbox-expiration": "^7.4.1",
@@ -1,25 +0,0 @@
1
- // src/session/model/safe-next.ts
2
- var HOME2 = "/";
3
- var BASE = "http://next.invalid";
4
- function safeNext2(value) {
5
- if (!value || value.length > 2000)
6
- return HOME2;
7
- if (!value.startsWith("/") || value.startsWith("//"))
8
- return HOME2;
9
- if (/[\\\p{Cc}\s]/u.test(value))
10
- return HOME2;
11
- try {
12
- const url = new URL(value, BASE);
13
- const path = `${url.pathname}${url.search}${url.hash}`;
14
- if (url.origin !== BASE || path.startsWith("//"))
15
- return HOME2;
16
- return path;
17
- } catch {
18
- return HOME2;
19
- }
20
- }
21
-
22
- export { HOME2, safeNext2 };
23
-
24
- //# debugId=DC9B9B90F989919264756E2164756E21
25
- //# sourceMappingURL=index-0786n4qe.js.map