cursedauth 0.1.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +87 -0
  3. package/dist/account/AccountMenu.d.ts +153 -0
  4. package/dist/account/AccountMenu.d.ts.map +1 -0
  5. package/dist/account/AccountMenu.js +388 -0
  6. package/dist/account/AccountMenu.js.map +1 -0
  7. package/dist/account/AccountNotice.d.ts +35 -0
  8. package/dist/account/AccountNotice.d.ts.map +1 -0
  9. package/dist/account/AccountNotice.js +133 -0
  10. package/dist/account/AccountNotice.js.map +1 -0
  11. package/dist/account/accountNotice.state.d.ts +20 -0
  12. package/dist/account/accountNotice.state.d.ts.map +1 -0
  13. package/dist/account/accountNotice.state.js +55 -0
  14. package/dist/account/accountNotice.state.js.map +1 -0
  15. package/dist/account/avatar.d.ts +37 -0
  16. package/dist/account/avatar.d.ts.map +1 -0
  17. package/dist/account/avatar.js +47 -0
  18. package/dist/account/avatar.js.map +1 -0
  19. package/dist/accountSlot.client.d.ts +113 -0
  20. package/dist/accountSlot.client.d.ts.map +1 -0
  21. package/dist/accountSlot.client.js +330 -0
  22. package/dist/accountSlot.client.js.map +1 -0
  23. package/dist/accountSlots.d.ts +192 -0
  24. package/dist/accountSlots.d.ts.map +1 -0
  25. package/dist/accountSlots.js +274 -0
  26. package/dist/accountSlots.js.map +1 -0
  27. package/dist/auth.d.ts +167 -0
  28. package/dist/auth.d.ts.map +1 -0
  29. package/dist/auth.js +310 -0
  30. package/dist/auth.js.map +1 -0
  31. package/dist/auth.server.d.ts +35 -0
  32. package/dist/auth.server.d.ts.map +1 -0
  33. package/dist/auth.server.js +67 -0
  34. package/dist/auth.server.js.map +1 -0
  35. package/dist/clientDescription.d.ts +186 -0
  36. package/dist/clientDescription.d.ts.map +1 -0
  37. package/dist/clientDescription.js +278 -0
  38. package/dist/clientDescription.js.map +1 -0
  39. package/dist/constantTime.d.ts +35 -0
  40. package/dist/constantTime.d.ts.map +1 -0
  41. package/dist/constantTime.js +46 -0
  42. package/dist/constantTime.js.map +1 -0
  43. package/dist/contentCensus.d.ts +59 -0
  44. package/dist/contentCensus.d.ts.map +1 -0
  45. package/dist/contentCensus.js +55 -0
  46. package/dist/contentCensus.js.map +1 -0
  47. package/dist/index.d.ts +25 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +24 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/mountGatedApp.d.ts +128 -0
  52. package/dist/mountGatedApp.d.ts.map +1 -0
  53. package/dist/mountGatedApp.js +107 -0
  54. package/dist/mountGatedApp.js.map +1 -0
  55. package/dist/runtimeMode.d.ts +28 -0
  56. package/dist/runtimeMode.d.ts.map +1 -0
  57. package/dist/runtimeMode.js +37 -0
  58. package/dist/runtimeMode.js.map +1 -0
  59. package/dist/secureRequest.d.ts +22 -0
  60. package/dist/secureRequest.d.ts.map +1 -0
  61. package/dist/secureRequest.js +27 -0
  62. package/dist/secureRequest.js.map +1 -0
  63. package/dist/sso.d.ts +373 -0
  64. package/dist/sso.d.ts.map +1 -0
  65. package/dist/sso.js +420 -0
  66. package/dist/sso.js.map +1 -0
  67. package/dist/ssoAutoSignIn.d.ts +272 -0
  68. package/dist/ssoAutoSignIn.d.ts.map +1 -0
  69. package/dist/ssoAutoSignIn.js +431 -0
  70. package/dist/ssoAutoSignIn.js.map +1 -0
  71. package/dist/ssoConsumer.server.d.ts +295 -0
  72. package/dist/ssoConsumer.server.d.ts.map +1 -0
  73. package/dist/ssoConsumer.server.js +972 -0
  74. package/dist/ssoConsumer.server.js.map +1 -0
  75. package/dist/stageIdentity.d.ts +72 -0
  76. package/dist/stageIdentity.d.ts.map +1 -0
  77. package/dist/stageIdentity.js +74 -0
  78. package/dist/stageIdentity.js.map +1 -0
  79. package/dist/ui/popover.d.ts +190 -0
  80. package/dist/ui/popover.d.ts.map +1 -0
  81. package/dist/ui/popover.js +351 -0
  82. package/dist/ui/popover.js.map +1 -0
  83. package/dist/userSessions.d.ts +205 -0
  84. package/dist/userSessions.d.ts.map +1 -0
  85. package/dist/userSessions.js +419 -0
  86. package/dist/userSessions.js.map +1 -0
  87. package/package.json +115 -0
  88. package/src/account/AccountMenu.tsx +729 -0
  89. package/src/account/AccountNotice.tsx +223 -0
  90. package/src/account/accountNotice.state.ts +66 -0
  91. package/src/account/avatar.ts +50 -0
  92. package/src/accountSlot.client.ts +362 -0
  93. package/src/accountSlots.ts +305 -0
  94. package/src/auth.server.ts +89 -0
  95. package/src/auth.ts +515 -0
  96. package/src/clientDescription.ts +366 -0
  97. package/src/constantTime.ts +45 -0
  98. package/src/contentCensus.ts +106 -0
  99. package/src/index.ts +58 -0
  100. package/src/mountGatedApp.ts +240 -0
  101. package/src/runtimeMode.ts +37 -0
  102. package/src/secureRequest.ts +25 -0
  103. package/src/sso.ts +767 -0
  104. package/src/ssoAutoSignIn.ts +544 -0
  105. package/src/ssoConsumer.server.ts +1260 -0
  106. package/src/stageIdentity.ts +76 -0
  107. package/src/ui/popover.ts +390 -0
  108. package/src/userSessions.ts +678 -0
@@ -0,0 +1,1260 @@
1
+ /**
2
+ * The satellite side of SSO — everything an app needs to say "sign in through
3
+ * `apps/auth`" instead of carrying its own password surface.
4
+ *
5
+ * Mounts five routes and one gate:
6
+ *
7
+ * GET /api/auth/sso/start → 302 to auth's /sso/authorize for THIS app.
8
+ * `?switch=1` forwards `prompt=login`, i.e.
9
+ * "show the form, somebody else wants in"
10
+ * GET /api/auth/sso/callback → verify the grant, mint the app's own session
11
+ * GET /api/auth/sso/signout → end THIS app's session, then 302 through
12
+ * auth's /sso/logout to end its session too
13
+ * GET /api/auth/session → { authenticated, user?, accountsUrl }
14
+ * POST /api/auth/logout → end THIS app's session ONLY. Kept for the
15
+ * callers that want exactly that (and for the
16
+ * smokes); the sign-out a person presses is
17
+ * the route above
18
+ * requireUser → 401 gate that resolves the session user
19
+ *
20
+ * The consumer keeps a LOCAL snapshot of every user who has ever signed in
21
+ * (`sso_users`, in the app's own db) so request-time auth never calls the auth
22
+ * satellite: the grant carries the snapshot, the callback upserts it, and from
23
+ * then on the app answers "which user is this?" from its own tables. Auth being
24
+ * down breaks new logins and nothing else.
25
+ *
26
+ * Verification keys come from auth's JWKS endpoint, cached with a TTL and kept
27
+ * stale-on-error — or from `publicKeyPem` (env/config) which wins outright and
28
+ * is how tests and air-gapped dev runs work.
29
+ */
30
+ import type { KeyObject } from "node:crypto";
31
+ import { createPublicKey } from "node:crypto";
32
+ import type { Database } from "bun:sqlite";
33
+ import type { Context, Hono, MiddlewareHandler, Next } from "hono";
34
+ import { stageIdentityIsLocal } from "./stageIdentity";
35
+ import { SESSION_CLAIMS_KEY, type SessionClaims } from "./auth.server";
36
+ import { isSecureRequest } from "./secureRequest";
37
+ import {
38
+ CENSUS_MAX_SUBJECTS,
39
+ type ContentCensus,
40
+ createNonceGuard,
41
+ kidOfPublicKeyPem,
42
+ SESSIONS_MAX_PER_APP,
43
+ type SsoGrantClaims,
44
+ type SsoSessionSummary,
45
+ verifyCensus,
46
+ verifyGrant,
47
+ verifyRevocation,
48
+ verifySessionsRequest,
49
+ } from "./sso";
50
+ import {
51
+ ACCOUNT_DRIFT_STATUS,
52
+ accountDriftBody,
53
+ isAccountDrift,
54
+ MAX_ACCOUNT_SLOTS,
55
+ normalizeSlot,
56
+ withSlot,
57
+ } from "./accountSlots";
58
+ import type { UserSessionStore } from "./userSessions";
59
+
60
+ export const SSO_CALLBACK_PATH = "/api/auth/sso/callback";
61
+ export const SSO_START_PATH = "/api/auth/sso/start";
62
+ /**
63
+ * The GLOBAL sign-out door (2026-08-10) — this app's session AND auth's.
64
+ *
65
+ * 🔴 GET, unlike `POST /api/auth/logout` right below it, and the difference is
66
+ * forced: this route ends in a redirect to ANOTHER ORIGIN, so it has to be a
67
+ * top-level navigation the browser drives, and a form POST cannot carry auth's
68
+ * cookie back on the return hop. That re-opens the CSRF surface the POST
69
+ * logout was written to close, and the trade is deliberate: the whole damage a
70
+ * forged sign-out can do is sign somebody out, which they can undo in one
71
+ * click. It is the same shape as OIDC RP-initiated logout for the same reason.
72
+ * Prefetching is not a concern the way it is for `<a href>` — the only caller
73
+ * is `startSsoSignOut`, which navigates from a click handler.
74
+ *
75
+ * The mirror of this constant lives in `ssoAutoSignIn.ts` (browser-side, which
76
+ * must not import `bun:sqlite`); `ssoAutoSignIn.test.ts` pins them equal.
77
+ */
78
+ export const SSO_SIGNOUT_PATH = "/api/auth/sso/signout";
79
+ /**
80
+ * Where auth pushes a revocation. Server-to-server, not a browser redirect: no
81
+ * cookie, no session, no CSRF surface — the signed ticket IS the authorization,
82
+ * so this route sits OUTSIDE `requireUser` by construction.
83
+ */
84
+ export const SSO_REVOKE_PATH = "/api/auth/sso/revoke";
85
+ /**
86
+ * Where auth ASKS this app what the named accounts have made here, before it
87
+ * takes their access away (2026-08-10). Same shape as the revoke route — a
88
+ * signed, single-audience ticket IS the authorization, so no cookie and no
89
+ * session — and read-only: it counts rows and answers, never writes.
90
+ */
91
+ export const SSO_CENSUS_PATH = "/api/auth/sso/census";
92
+ /**
93
+ * Where auth ASKS this app which of an account's sessions are alive here
94
+ * (2026-08-12) — the read half of the fleet-wide Login Sessions list.
95
+ *
96
+ * Same shape and same posture as the two above: a signed, single-audience,
97
+ * 60-second ticket IS the authorization, so no cookie, no session, and the
98
+ * route sits outside `requireUser`. Read-only — ENDING a session is the
99
+ * revocation ticket narrowed by `sid`, never a second door here.
100
+ *
101
+ * 🔴 A new server-to-server path is a new thing an edge gate can silently eat.
102
+ * Five hostnames sit behind Cloudflare Access, whose bypass list is enumerated
103
+ * per path (see `AS-BUILT-cloudflare-access.md`); this path is on it for the
104
+ * same reason `/revoke` and `/census` are, and auth reads any 3xx here as a
105
+ * failure rather than as an empty list.
106
+ */
107
+ export const SSO_SESSIONS_PATH = "/api/auth/sso/sessions";
108
+ /**
109
+ * The one-shot cookie that carries a signed-out deep link across the grant round
110
+ * trip (2026-08-05). A shared `/play/<name>` link opened signed out used to land
111
+ * on the app's index after the SSO hop, because the callback's redirect target
112
+ * belonged to this module, not to the app. The return path now rides HERE — a
113
+ * cookie on THIS app's own origin, set at `/sso/start`, read at the callback —
114
+ * so it never passes through the auth satellite and can never be smuggled
115
+ * through it into an open redirect. It is validated on the way in AND again on
116
+ * the way back (`sanitizeReturnPath`), so only a same-origin path of this app
117
+ * can ever survive to become a redirect target.
118
+ */
119
+ export const SSO_RETURN_COOKIE = "sso_return";
120
+ /** Long enough to finish a login (and a 2FA email) at auth, short enough that a
121
+ * stale deep link never resurfaces on a much later, unrelated sign-in. */
122
+ const SSO_RETURN_TTL_SECONDS = 15 * 60;
123
+
124
+ /**
125
+ * The one-shot cookie that carries the target ACCOUNT SLOT across the same
126
+ * round trip (2026-08-12).
127
+ *
128
+ * 🔴 It has to be a cookie, for a reason that is easy to miss: the callback URL
129
+ * is the app's REGISTERED `redirect_uri`, matched at auth by exact string, and
130
+ * auth appends nothing but `?grant=`. So there is no way for the hop to tell
131
+ * the callback which slot it was started from — the query param that names the
132
+ * slot everywhere else in the fleet cannot survive a registered redirect. The
133
+ * same one-shot mechanism the deep link already uses carries it instead.
134
+ *
135
+ * Two values, and the difference matters:
136
+ *
137
+ * `add` — "put this person in a NEW slot, keep everyone else signed in".
138
+ * The slot is chosen at the CALLBACK, not here, because the browser
139
+ * can gain or lose a session during the round trip and a number
140
+ * pinned at the start would then evict somebody.
141
+ * `<n>` — "put them in slot n", which is the tab that started the hop.
142
+ *
143
+ * Absent means slot 0: an old cookie jar, an expired one-shot, or a plain first
144
+ * sign-in. All three are the single-account path this fleet already had.
145
+ *
146
+ * Like the slot param itself this is a HINT, never an authorization. The worst
147
+ * a tampered value achieves is landing your own new session in a different slot
148
+ * of your own browser.
149
+ */
150
+ export const SSO_SLOT_COOKIE = "sso_slot";
151
+ /** The `SSO_SLOT_COOKIE` value meaning "choose a free slot at the callback". */
152
+ const SLOT_COOKIE_ADD = "add";
153
+
154
+ /**
155
+ * THE open-redirect gate for every private satellite. The only return target a
156
+ * signed-out deep link may resume to is a same-origin PATH on this app; anything
157
+ * that could send the browser to another origin is refused and the caller falls
158
+ * back to the index. It fails closed by construction — every branch that is not
159
+ * a provably-safe relative path returns null:
160
+ *
161
+ * - absolute URLs (`https://evil.com/x`, `javascript:…`) → not `/`-rooted
162
+ * - protocol-relative `//evil.com` → second char `/`
163
+ * - `\`-smuggled authority (`/\evil.com`, browsers fold `\`→`/`)
164
+ * - control characters (NUL/CR/LF/TAB — header splitting / re-parsing)
165
+ * - percent-encoded slash/backslash/dot that could hide `//` or `..`
166
+ * - `..` path traversal
167
+ *
168
+ * Exported so `ssoConsumer.server.test.ts` can hammer each form directly — an
169
+ * open redirect on every private satellite at once is the primary risk of this
170
+ * change, so it is tested as a unit, not only through the routes.
171
+ */
172
+ export function sanitizeReturnPath(raw: string | null | undefined): string | null {
173
+ if (typeof raw !== "string") return null;
174
+ if (raw.length === 0 || raw.length > 2048) return null;
175
+ // Must be rooted at this origin and be a bare path, not `//authority`.
176
+ if (raw[0] !== "/") return null;
177
+ if (raw[1] === "/" || raw[1] === "\\") return null;
178
+ // Control chars can split a header or be re-read as an authority separator.
179
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: refusing them is the point.
180
+ if (/[\u0000-\u001f\u007f]/.test(raw)) return null;
181
+ // A backslash is normalized to `/` by browsers, so `/\evil.com` becomes
182
+ // `//evil.com`. Refuse the character anywhere in the path.
183
+ if (raw.includes("\\")) return null;
184
+ // Percent-encoded slash / backslash / dot can hide `//` or `..` from the
185
+ // checks above after a further decode. No deep link this fleet produces needs
186
+ // them, so refuse rather than guess.
187
+ if (/%2f|%5c|%2e/i.test(raw)) return null;
188
+ // Traversal in the already-decoded path.
189
+ const path = raw.split(/[?#]/, 1)[0] ?? "";
190
+ if (path.split("/").some((seg) => seg === "..")) return null;
191
+ return raw;
192
+ }
193
+
194
+ const returnCookieAttributes = (req: Request, maxAge: number): string =>
195
+ [
196
+ "Path=/",
197
+ "HttpOnly",
198
+ // Lax so it survives the cross-site top-level GET the callback arrives as
199
+ // (auth redirects the browser back) — the same reason the session cookie is
200
+ // Lax; see userSessions.ts.
201
+ "SameSite=Lax",
202
+ ...(isSecureRequest(req) ? ["Secure"] : []),
203
+ `Max-Age=${maxAge}`,
204
+ ].join("; ");
205
+
206
+ const setReturnCookie = (req: Request, path: string): string =>
207
+ `${SSO_RETURN_COOKIE}=${encodeURIComponent(path)}; ${returnCookieAttributes(req, SSO_RETURN_TTL_SECONDS)}`;
208
+
209
+ const clearReturnCookie = (req: Request): string =>
210
+ `${SSO_RETURN_COOKIE}=; ${returnCookieAttributes(req, 0)}`;
211
+
212
+ const readReturnCookie = (req: Request): string | null => {
213
+ const cookie = req.headers.get("cookie");
214
+ if (!cookie) return null;
215
+ const match = new RegExp(`(?:^|;\\s*)${SSO_RETURN_COOKIE}=([^;]+)`).exec(cookie);
216
+ if (!match?.[1]) return null;
217
+ try {
218
+ return decodeURIComponent(match[1]);
219
+ } catch {
220
+ return null;
221
+ }
222
+ };
223
+
224
+ /** Is a return cookie present at all (even an undecodable one)? The failure path
225
+ * clears it only when it exists, so a plain failed grant still sets NO cookie —
226
+ * the invariant the callback's other tests rely on. */
227
+ const hasReturnCookie = (req: Request): boolean =>
228
+ new RegExp(`(?:^|;\\s*)${SSO_RETURN_COOKIE}=`).test(req.headers.get("cookie") ?? "");
229
+
230
+ /** Same attributes as the return cookie, and for the same reasons: one-shot,
231
+ * HttpOnly, and Lax so it survives the cross-site top-level GET back. */
232
+ const setSlotCookie = (req: Request, value: string): string =>
233
+ `${SSO_SLOT_COOKIE}=${encodeURIComponent(value)}; ${returnCookieAttributes(req, SSO_RETURN_TTL_SECONDS)}`;
234
+
235
+ const clearSlotCookie = (req: Request): string =>
236
+ `${SSO_SLOT_COOKIE}=; ${returnCookieAttributes(req, 0)}`;
237
+
238
+ /** The raw one-shot slot instruction, or null. */
239
+ const readSlotCookie = (req: Request): string | null => {
240
+ const cookie = req.headers.get("cookie");
241
+ if (!cookie) return null;
242
+ const match = new RegExp(`(?:^|;\\s*)${SSO_SLOT_COOKIE}=([^;]+)`).exec(cookie);
243
+ if (!match?.[1]) return null;
244
+ try {
245
+ return decodeURIComponent(match[1]).slice(0, 8);
246
+ } catch {
247
+ return null;
248
+ }
249
+ };
250
+
251
+ const hasSlotCookie = (req: Request): boolean =>
252
+ new RegExp(`(?:^|;\\s*)${SSO_SLOT_COOKIE}=`).test(req.headers.get("cookie") ?? "");
253
+
254
+ /** How long a fetched JWKS is trusted before re-reading. Rotation overlap on
255
+ * the auth side is hours, so minutes here costs nothing. */
256
+ const JWKS_TTL_MS = 5 * 60 * 1000;
257
+ /** Floor between forced refreshes (unknown kid), so a garbage grant cannot
258
+ * turn the consumer into a hammer against auth. */
259
+ const JWKS_MIN_REFRESH_GAP_MS = 30 * 1000;
260
+
261
+ export interface SsoUser {
262
+ id: string;
263
+ email: string;
264
+ name: string;
265
+ isAdmin: boolean;
266
+ /** The machine's owner — decides who is shown localhost links in the fleet
267
+ * directory. Never inferred from `isAdmin`; see `fleet/access.ts`. */
268
+ isOwner: boolean;
269
+ /** Auth explicitly granted this account access to THIS app, rather than the
270
+ * app's default tier admitting them. Lets a household member into an
271
+ * admin-tier app without being made an admin of the user registry. */
272
+ isGranted: boolean;
273
+ }
274
+
275
+ export interface SsoConsumerOptions {
276
+ /**
277
+ * This app's registered key at auth (e.g. "hobbies"). Doubles as `aud` — except
278
+ * on a staged artifact, where the audience becomes `<app>-local`; see
279
+ * {@link resolveSsoAudience}. This value stays the app's own identity for
280
+ * session scopes, log prefixes and the fleet row either way.
281
+ */
282
+ app: string;
283
+ /** The auth satellite's origin, no trailing slash. */
284
+ authUrl: string;
285
+ /**
286
+ * The environment the audience switch is read from. Defaults to `process.env`;
287
+ * threaded so a test can prove both branches without mutating the process, the
288
+ * same reason `readSatelliteConfig` takes one.
289
+ */
290
+ env?: NodeJS.ProcessEnv;
291
+ /** THIS app's own origin — what the callback URL is built from. Configured,
292
+ * not derived from the request: a Host-header value must never choose where
293
+ * a credential gets redirected. */
294
+ publicUrl: string;
295
+ sessions: UserSessionStore;
296
+ /** The app's own database — the `sso_users` snapshot lives here so app
297
+ * tables can foreign-key the user id. */
298
+ db: Database;
299
+ /** Static verification key (SPKI PEM). Set → JWKS is never fetched. */
300
+ publicKeyPem?: string;
301
+ /**
302
+ * Admin accounts only (2026-07-28, for the orchestrator's companion). The
303
+ * registry is one HOUSEHOLD user set — an account that may open ROMs must
304
+ * not automatically open an app that mirrors every task on the owner's
305
+ * machine. Enforced at BOTH doors: a non-admin grant never mints a session
306
+ * (callback), and a session whose snapshot row has since lost the flag is
307
+ * refused per request (requireUser).
308
+ */
309
+ requireAdmin?: boolean;
310
+ /**
311
+ * Restrict sign-in to specific accounts by email (2026-08-01, for the station —
312
+ * the control plane is the OWNER's, and "admin" is a grantable flag, not a
313
+ * structural one-person guarantee). Case-insensitive; composes with
314
+ * `requireAdmin` (both must pass). Enforced at BOTH doors, exactly like
315
+ * `requireAdmin`: the callback never mints a session for an unlisted account,
316
+ * and a session whose snapshot email has since left the list is refused per
317
+ * request. An empty array means "nobody" and is almost certainly a config
318
+ * error — prefer omitting the option to allow all registered users.
319
+ */
320
+ allowedEmails?: string[];
321
+ /**
322
+ * What the named accounts have MADE in this app (2026-08-10).
323
+ *
324
+ * Auth calls it while the owner is deciding whether to close this app to
325
+ * somebody, and puts the answer in the confirmation dialog — "Sam would lose
326
+ * access to 34 save states" is a different decision from "Sam has nothing
327
+ * here". Auth cannot work this out itself: it holds no app data, by design.
328
+ *
329
+ * Implement it wherever rows are keyed on the user id, and implement it as
330
+ * `{ scope: "shared" }` where they are NOT — an app with one shared library
331
+ * (the notes corpus, the family tree) should say so rather than stay silent,
332
+ * because silence reads as "could not find out" and stalls a decision that
333
+ * nothing was ever at risk in.
334
+ *
335
+ * Rules for an implementation: COUNT, never read content (auth is not
336
+ * entitled to what the rows say, only to how many there are), and never
337
+ * write. Throwing is safe — auth reports the app as unreachable rather than
338
+ * as empty.
339
+ */
340
+ contentCensus?: (userIds: string[]) => ContentCensus | Promise<ContentCensus>;
341
+ /**
342
+ * Every audience auth will mint a grant for on THIS app's behalf — its prod
343
+ * key and, if it has one, its local-stage twin (`["flix", "flix-local"]`).
344
+ *
345
+ * 🔴 The app declares this, and that is a deliberate change from the
346
+ * previous generation (2026-09-14). There, the list came from a 777-line
347
+ * fleet-wide registry compiled into the library: every app carried a table
348
+ * of every other app, and adding a satellite meant editing the shared
349
+ * platform. Here a consumer knows only its own doors. Omitted, the audience
350
+ * is always {@link SsoConsumerOptions.app} — which is the correct answer for
351
+ * any app that has no local stage, and the safe answer for one that does.
352
+ */
353
+ registeredAudiences?: readonly string[];
354
+ fetchImpl?: typeof fetch;
355
+ now?: () => number;
356
+ }
357
+
358
+ export interface SsoConsumer {
359
+ /** 401 gate for `/api/*`: resolves the cookie to a user, sets claims. */
360
+ requireUser: MiddlewareHandler;
361
+ /** The signed-in user, for handlers behind `requireUser`. */
362
+ userOf(c: Context): SsoUser | null;
363
+ /**
364
+ * The same authorization decision `requireUser` makes, for a door that has no
365
+ * Hono `Context` — today that means a WebSocket upgrade.
366
+ *
367
+ * 🔴 It exists because "a socket is not a lesser door" is only true if both
368
+ * doors ask the same question, and an app that re-implements the rule against
369
+ * the `sso_users` snapshot gets a DIFFERENT answer. Measured in apps/orch on
370
+ * 2026-08-12: its handshake accepted `is_admin = 1` only, so every HTTP route
371
+ * served the deploy smoke's session (200) while the WS upgrade refused it —
372
+ * the smoke account is GRANTED this app, not an admin, and `requireAdmin` has
373
+ * meant "admin OR granted" since 2026-08-02. The owner is an admin, so no
374
+ * human ever saw it; it only ever failed the smoke, which then failed and
375
+ * rolled back every orch-local deploy.
376
+ *
377
+ * Returns the user when the request may proceed, `null` for every refusal —
378
+ * the same collapse `requireUser` already makes (all three of its rejection
379
+ * branches return an identical 401, deliberately: a door that explains WHICH
380
+ * check failed is a door that helps enumerate accounts).
381
+ */
382
+ authorizeRequest(req: Request): SsoUser | null;
383
+ /**
384
+ * The same decision again, for a door that has only HEADERS — a WebSocket
385
+ * upgrade, whose only credential is the cookie the browser attaches itself
386
+ * (a browser `WebSocket` cannot send an `Authorization` header).
387
+ *
388
+ * 🔴 This is {@link authorizeRequest} with an adapter, deliberately, and the
389
+ * adapter is the whole feature: every app that had to write one wrote a
390
+ * DIFFERENT rule. `apps/arcade` resolved the cookie to an `sso_users` row and
391
+ * stopped there — no `adminOrGranted`, no `emailAllowed` — so a person whose
392
+ * grant had been revoked, or whose address had left the allow-list, was
393
+ * refused by every HTTP route and still opened a socket. Its own comment said
394
+ * the check "goes through the SAME session store the HTTP routes do", which
395
+ * was true and not the point.
396
+ *
397
+ * That is the shape a second authorization path always has: it drifts silently,
398
+ * because a socket that authenticates wrongly still opens and nothing 401s. The
399
+ * fix is not a better copy, it is no copy — which is why this delegates rather
400
+ * than reimplementing, and why the delegation must not be "simplified" into a
401
+ * cookie lookup here.
402
+ */
403
+ verifyHandshake(headers: Headers): SsoUser | null;
404
+ mountSsoRoutes(app: Hono): void;
405
+ }
406
+
407
+ const noStore = { "cache-control": "no-store" } as const;
408
+
409
+ interface SsoUserRow {
410
+ id: string;
411
+ email: string;
412
+ name: string;
413
+ is_admin: number;
414
+ /** Added 2026-08-02. Read defensively: a row written before the ALTER has
415
+ * `undefined` here, and both flags must fail CLOSED on a missing column
416
+ * (no owner links, no granted bypass) rather than open. */
417
+ is_owner?: number;
418
+ is_granted?: number;
419
+ last_login_at: string;
420
+ created_at: string;
421
+ updated_at: string;
422
+ }
423
+
424
+ const toUser = (row: SsoUserRow): SsoUser => ({
425
+ id: row.id,
426
+ email: row.email,
427
+ name: row.name,
428
+ isAdmin: row.is_admin === 1,
429
+ isOwner: row.is_owner === 1,
430
+ isGranted: row.is_granted === 1,
431
+ });
432
+
433
+ /** `http://127.0.0.1:3309` / `http://localhost:3309` → true. Anything else → false. */
434
+ function isLoopbackOrigin(url: string): boolean {
435
+ try {
436
+ const host = new URL(url).hostname.toLowerCase();
437
+ return host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "[::1]";
438
+ } catch {
439
+ // Unparseable is not loopback: the safe answer is "this is the real registry",
440
+ // which leaves the audience at the app's own prod key and changes nothing.
441
+ return false;
442
+ }
443
+ }
444
+
445
+ /**
446
+ * THE GRANT AUDIENCE — this app's own key, or its LOCAL twin on a staged artifact.
447
+ *
448
+ * ## What this buys, and why it is the audience rather than just the URL
449
+ *
450
+ * Pointing a staged artifact at the local accounts daemon (`appConfig`'s forced
451
+ * `authUrl`) stops it writing sessions into the owner's real registry. That is one
452
+ * direction. This function is the OTHER direction, and it is the half that makes the
453
+ * isolation mutual: a grant minted by `auth-local` carries `aud: "<app>-local"`, and
454
+ * the production deployment of that app verifies `aud: "<app>"` — so a credential
455
+ * minted on this Mac is **structurally unusable against production**, not merely
456
+ * unlikely to be sent there. `<app>-local` additionally has an EMPTY `prodOrigin` in
457
+ * the roster, so even a registry that allows local consumers has no callback for it on
458
+ * the internet. That is the `orch-local` / `station-local` shape, which those two apps
459
+ * have carried since 2026-07-31; this is the thirteen others adopting it without each
460
+ * hand-writing a second `createSsoConsumer` branch.
461
+ *
462
+ * ## Three conditions, all required, and each one closes a different door
463
+ *
464
+ * 1. **the stage marker** — `APP_STAGE_IDENTITY=local`, written only by
465
+ * `smoke/localStage.ts`. Without it an ordinary `bun run dev` shell keeps signing
466
+ * in as `<app>` through the dev-gateway alias (`http://<app>.localhost:3300`),
467
+ * which is registered on the PROD key and deliberately not on the local one — the
468
+ * `*.localhost` exclusion `sso.test.ts` pins. Deriving the switch from "authUrl is
469
+ * loopback" alone would have silently broken gateway sign-in in every app.
470
+ * 2. **a loopback registry** — belt and braces on the marker. A stray marker on a
471
+ * real release cannot move the audience while `authUrl` is the internet.
472
+ * 3. **`<app>-local` is actually in the roster** — so an app whose local door has not
473
+ * been registered keeps its own key and fails visibly at the ROSTER, instead of
474
+ * asking auth for an audience nobody has heard of and getting 400 `unknown app` at
475
+ * the far end of a browser hop. It is also what keeps `station-local` and
476
+ * `orch-local` unchanged when they pass through here: `station-local-local` is not
477
+ * a key, so their explicit audience wins, as it must.
478
+ *
479
+ * 🔴 It moves the AUDIENCE only. `appKey` stays the app's own identity everywhere else
480
+ * — the session `scopes`, the log prefixes, the fleet row — because those are read by
481
+ * app code that has no idea it is on a stage, and a scope string that changed shape
482
+ * under the app would be a permissions bug wearing a stage costume.
483
+ */
484
+ export function resolveSsoAudience(
485
+ appKey: string,
486
+ authUrl: string,
487
+ env: NodeJS.ProcessEnv = process.env,
488
+ registered: readonly string[] = [],
489
+ ): string {
490
+ if (!stageIdentityIsLocal(env)) return appKey;
491
+ if (!isLoopbackOrigin(authUrl)) return appKey;
492
+ const local = `${appKey}-local`;
493
+ return registered.includes(local) ? local : appKey;
494
+ }
495
+
496
+ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
497
+ const { app: appKey, sessions, db } = options;
498
+ const authUrl = options.authUrl.replace(/\/$/, "");
499
+ /**
500
+ * What this consumer asks auth FOR and verifies grants AGAINST — see
501
+ * {@link resolveSsoAudience}. Equal to `appKey` everywhere except a staged
502
+ * artifact, so the ordinary reading of this file is unchanged.
503
+ */
504
+ const audience = resolveSsoAudience(
505
+ appKey,
506
+ authUrl,
507
+ options.env ?? process.env,
508
+ options.registeredAudiences ?? [],
509
+ );
510
+ if (audience !== appKey) {
511
+ console.log(
512
+ `[${appKey}] SSO audience is "${audience}" — this is a LOCAL STAGE, signing in ` +
513
+ `against ${authUrl}. A grant minted here cannot open the production deployment.`,
514
+ );
515
+ }
516
+ const publicUrl = options.publicUrl.replace(/\/$/, "");
517
+ const fetchImpl = options.fetchImpl ?? fetch;
518
+ const now = options.now ?? Date.now;
519
+ const nonces = createNonceGuard(now);
520
+ const allowedEmails =
521
+ options.allowedEmails === undefined
522
+ ? null
523
+ : new Set(
524
+ options.allowedEmails.map((e) => e.trim().toLowerCase()).filter((e) => e.length > 0),
525
+ );
526
+ const emailAllowed = (email: string): boolean =>
527
+ allowedEmails === null || allowedEmails.has(email.trim().toLowerCase());
528
+
529
+ db.exec(`CREATE TABLE IF NOT EXISTS sso_users (
530
+ id TEXT PRIMARY KEY,
531
+ email TEXT NOT NULL,
532
+ name TEXT NOT NULL DEFAULT '',
533
+ is_admin INTEGER NOT NULL DEFAULT 0,
534
+ last_login_at TEXT NOT NULL DEFAULT '',
535
+ created_at TEXT NOT NULL,
536
+ updated_at TEXT NOT NULL
537
+ );`);
538
+ // 2026-08-02: the fleet directory needs two more facts per account. Added by
539
+ // ALTER rather than by bumping the CREATE, because every deployed satellite
540
+ // already has this table with rows in it. Both default to 0, so an account
541
+ // that has not signed in since the upgrade simply gets no localhost links
542
+ // and no grant bypass until it does — the safe direction.
543
+ for (const column of ["is_owner", "is_granted"]) {
544
+ try {
545
+ db.exec(`ALTER TABLE sso_users ADD COLUMN ${column} INTEGER NOT NULL DEFAULT 0`);
546
+ } catch {
547
+ // Already there. sqlite has no ADD COLUMN IF NOT EXISTS, and reading
548
+ // pragma table_info to decide costs more than catching the one error
549
+ // this can throw.
550
+ }
551
+ }
552
+ // 🔴 One row per ADDRESS, not just per id (2026-08-23). See `reconcileByEmail`
553
+ // for the ghost this removes; the index is what makes it impossible to grow a
554
+ // second one. Created AFTER the sweep, because a live duplicate would refuse
555
+ // the index and leave the table exactly as it was found.
556
+ dropDuplicateSnapshots(db);
557
+ db.exec("CREATE UNIQUE INDEX IF NOT EXISTS sso_users_email ON sso_users (lower(email))");
558
+
559
+ // ── Verification keys ───────────────────────────────────────────────────
560
+ const staticKeys: Map<string, KeyObject> | null = options.publicKeyPem
561
+ ? new Map([[kidOfPublicKeyPem(options.publicKeyPem), createPublicKey(options.publicKeyPem)]])
562
+ : null;
563
+ let fetched: Map<string, KeyObject> = new Map();
564
+ let fetchedAt = 0;
565
+ let lastRefreshAttempt = 0;
566
+
567
+ async function refreshJwks(): Promise<void> {
568
+ lastRefreshAttempt = now();
569
+ try {
570
+ const res = await fetchImpl(`${authUrl}/api/sso/jwks`, {
571
+ signal: AbortSignal.timeout(5000),
572
+ });
573
+ if (!res.ok) throw new Error(`jwks answered ${res.status}`);
574
+ const body = (await res.json()) as { keys?: { kid?: string; publicKeyPem?: string }[] };
575
+ const next = new Map<string, KeyObject>();
576
+ for (const key of body.keys ?? []) {
577
+ if (typeof key.kid === "string" && typeof key.publicKeyPem === "string") {
578
+ next.set(key.kid, createPublicKey(key.publicKeyPem));
579
+ }
580
+ }
581
+ if (next.size === 0) throw new Error("jwks contained no usable keys");
582
+ fetched = next;
583
+ fetchedAt = now();
584
+ } catch (err) {
585
+ // Stale keys keep verifying; only a rotation while auth is unreachable
586
+ // fails, and it fails CLOSED (unknown kid → refused grant).
587
+ console.warn(`[${appKey}] SSO jwks refresh failed (${String(err)}) — keeping cached keys`);
588
+ }
589
+ }
590
+
591
+ async function keysFor(kid: string): Promise<Map<string, KeyObject>> {
592
+ if (staticKeys) return staticKeys;
593
+ const expired = now() - fetchedAt > JWKS_TTL_MS;
594
+ const unknown = !fetched.has(kid);
595
+ const gapOk = now() - lastRefreshAttempt > JWKS_MIN_REFRESH_GAP_MS;
596
+ if (fetched.size === 0 || ((expired || unknown) && gapOk)) await refreshJwks();
597
+ return fetched;
598
+ }
599
+
600
+ // ── Session resolution ──────────────────────────────────────────────────
601
+ const sessionUser = (c: Context): SsoUser | null => {
602
+ const userId = sessions.userIdOf(c.req.raw);
603
+ if (!userId) return null;
604
+ const row = db.query("SELECT * FROM sso_users WHERE id = ?").get(userId) as SsoUserRow | null;
605
+ return row ? toUser(row) : null;
606
+ };
607
+
608
+ const userOf = (c: Context): SsoUser | null => {
609
+ const claims = c.get(SESSION_CLAIMS_KEY) as (SessionClaims & { ssoUser?: SsoUser }) | undefined;
610
+ return claims?.ssoUser ?? null;
611
+ };
612
+
613
+ /**
614
+ * `requireAdmin` means "admin OR explicitly granted this app" as of
615
+ * 2026-08-02. The flag was the fleet's only way to widen an app past the
616
+ * household default, so opening Notes to one person also handed them the
617
+ * user registry. A per-app grant separates those two decisions; admins keep
618
+ * working with no rows at all, so nothing that passed before now fails.
619
+ *
620
+ * `allowedEmails` is deliberately NOT softened this way — the station pins
621
+ * itself to the owner's address precisely because admin is grantable, and a
622
+ * grant must not be able to reach past that.
623
+ */
624
+ const adminOrGranted = (user: SsoUser): boolean =>
625
+ !options.requireAdmin || user.isAdmin || user.isGranted;
626
+
627
+ /**
628
+ * The WHOLE authorization rule, over a raw `Request`. See `SsoConsumer` for
629
+ * why this is shared rather than re-implemented per door.
630
+ *
631
+ * `requireUser` is defined in terms of it below, which is the point: the two
632
+ * cannot answer differently, because there is only one of them.
633
+ */
634
+ const authorizeRequest = (req: Request): SsoUser | null => {
635
+ const userId = sessions.userIdOf(req);
636
+ if (!userId) return null;
637
+ const row = db.query("SELECT * FROM sso_users WHERE id = ?").get(userId) as SsoUserRow | null;
638
+ const user = row ? toUser(row) : null;
639
+ if (!user) return null;
640
+ if (!adminOrGranted(user)) return null;
641
+ if (!emailAllowed(user.email)) return null;
642
+ return user;
643
+ };
644
+
645
+ /**
646
+ * The handshake door. See `SsoConsumer.verifyHandshake` for why it is an
647
+ * adapter over `authorizeRequest` and must stay one.
648
+ *
649
+ * The URL is a placeholder and is never read: a session is resolved from the
650
+ * `Cookie` header alone, and the upgrade's own URL carries no credential. A
651
+ * constant here is honest about that — reaching for the app's public URL would
652
+ * imply the origin was being checked, which it is not (the browser's
653
+ * same-origin cookie rules are what bound where the cookie can come from).
654
+ */
655
+ const verifyHandshake = (headers: Headers): SsoUser | null =>
656
+ authorizeRequest(new Request("http://handshake.invalid/", { headers }));
657
+
658
+ const requireUser: MiddlewareHandler = async (c: Context, next: Next) => {
659
+ const user = authorizeRequest(c.req.raw);
660
+ if (!user) return c.json({ error: "unauthorized" }, 401, noStore);
661
+ /**
662
+ * 🔴 The account behind this browser's slot changed while the page that is
663
+ * asking was already open (owner, 2026-08-15 — see `accountSlots.ts` for
664
+ * the whole failure). The credential is valid and the person is signed in,
665
+ * so this is neither a 401 nor a 403: it is a CONFLICT between the identity
666
+ * the page rendered for and the one this request resolves to, and answering
667
+ * it as anything else is what let a console stay drawn for somebody who was
668
+ * no longer there.
669
+ *
670
+ * It sits INSIDE the authorization above rather than in front of it, and
671
+ * that order is deliberate: an anonymous request must still be told it is
672
+ * anonymous, and drift is only interesting once we know who this actually
673
+ * is — which is also the only way the answer can name them.
674
+ */
675
+ const expected = sessions.expectedUserOf(c.req.raw);
676
+ if (isAccountDrift(expected, user.id)) {
677
+ return c.json(
678
+ accountDriftBody(expected ?? "", {
679
+ id: user.id,
680
+ email: user.email,
681
+ name: user.name,
682
+ }),
683
+ ACCOUNT_DRIFT_STATUS,
684
+ noStore,
685
+ );
686
+ }
687
+ c.set(SESSION_CLAIMS_KEY, {
688
+ userId: user.id,
689
+ tenantId: "default",
690
+ /**
691
+ * 🔴 `owner` is a scope of its own, not "admin, but more".
692
+ *
693
+ * Several satellites have a surface that is the OWNER's alone — the fleet
694
+ * quota knobs, a spend decision, a limit somebody else's data lives under
695
+ * — and until 2026-08-12 the only signal that crossed into a consumer app
696
+ * was `admin`. An app that wanted owner-only had to re-read `ssoUser`, or
697
+ * (worse, and this is the one that has actually shipped elsewhere) settle
698
+ * for admin and call it close enough. `apps/auth` already draws this
699
+ * distinction on its own routes; this is the same line, made visible to
700
+ * every consumer through the claims they already read.
701
+ */
702
+ scopes: [appKey, ...(user.isAdmin ? ["admin"] : []), ...(user.isOwner ? ["owner"] : [])],
703
+ ssoUser: user,
704
+ } satisfies SessionClaims & { ssoUser: SsoUser });
705
+ await next();
706
+ };
707
+
708
+ return {
709
+ requireUser,
710
+ userOf,
711
+ authorizeRequest,
712
+ verifyHandshake,
713
+
714
+ mountSsoRoutes(app) {
715
+ app.get(SSO_START_PATH, (c) => {
716
+ const target = new URL(`${authUrl}/sso/authorize`);
717
+ target.searchParams.set("app", audience);
718
+ target.searchParams.set("redirect_uri", `${publicUrl}${SSO_CALLBACK_PATH}`);
719
+ // "Somebody else wants in" — ask auth for the credential form even
720
+ // though it holds a live session. Without it the hop re-issues a
721
+ // grant for whoever is already signed in there, which is exactly the
722
+ // dead end this fixes. Translated here rather than passed straight
723
+ // through so the app-facing vocabulary stays `switch=1` and auth's
724
+ // protocol vocabulary stays `prompt=login`.
725
+ if (c.req.query("switch") === "1") target.searchParams.set("prompt", "login");
726
+
727
+ // ── Adding a SECOND account, side by side (2026-08-12) ──────────
728
+ // `switch=1` replaces whoever this tab is. `add=1` does not: it asks
729
+ // auth for its account chooser and lands the result in a FREE slot,
730
+ // so the account already open in the other tab keeps working. That
731
+ // distinction is the whole owner-facing feature — "one tab as owner,
732
+ // another as a test user, at the same time".
733
+ //
734
+ // `prompt=select_account` is OIDC's own word for this and auth
735
+ // implements it as "offer the accounts this browser already holds,
736
+ // with a password form under them". Translated here, like
737
+ // `prompt=login` above, so apps keep saying `add=1`.
738
+ const adding = c.req.query("add") === "1";
739
+ if (adding) target.searchParams.set("prompt", "select_account");
740
+ // A specific account the person picked from the menu. Auth mints for
741
+ // that account IF this browser already proved it may (it holds a live
742
+ // auth session for them) and shows the password form if not — so this
743
+ // parameter can never be a way IN, only a way to skip retyping.
744
+ const account = (c.req.query("account") ?? "").slice(0, 64);
745
+ if (account) target.searchParams.set("account", account);
746
+
747
+ // Stash the signed-out deep link (`?return=`) in a one-shot cookie on
748
+ // THIS origin so the callback can resume it after the round trip. The
749
+ // path never travels to auth, so it can never ride the grant into an
750
+ // open redirect there. A missing or refused return CLEARS any stale
751
+ // cookie, so the fallback is today's "land on the index" rather than a
752
+ // leftover from an earlier attempt.
753
+ const ret = sanitizeReturnPath(c.req.query("return"));
754
+ c.header(
755
+ "set-cookie",
756
+ ret ? setReturnCookie(c.req.raw, ret) : clearReturnCookie(c.req.raw),
757
+ );
758
+ // And stash where the result should land. Always written, never left
759
+ // stale: a plain hop that inherited an `add` from an abandoned attempt
760
+ // would silently open a second session instead of refreshing this one.
761
+ c.header(
762
+ "set-cookie",
763
+ setSlotCookie(c.req.raw, adding ? SLOT_COOKIE_ADD : String(sessions.slotOf(c.req.raw))),
764
+ { append: true },
765
+ );
766
+ return c.redirect(target.toString(), 302);
767
+ });
768
+
769
+ // ── Leaving, for real (2026-08-10) ────────────────────────────────
770
+ // Ending this app's cookie was never a sign-out: auth's session
771
+ // outlives it, so the next "Sign in" press — or the automatic hop on
772
+ // the next tab — silently returns the SAME person. This route ends
773
+ // both, in the only order that is safe: this app's session dies here
774
+ // and now (so a failure at the auth hop still leaves this app locked),
775
+ // and auth's dies on the redirect that follows.
776
+ //
777
+ // `redirect_uri` is this app's REGISTERED callback rather than a page
778
+ // of its own. Auth already validates that exact string by exact match
779
+ // against the registry, so the sign-out door adds no second place a
780
+ // redirect target can be registered — auth lands the browser on that
781
+ // URL's origin, not the callback path itself.
782
+ app.get(SSO_SIGNOUT_PATH, (c) => {
783
+ // ── Which sign-out is this? (2026-08-12) ────────────────────────
784
+ // With several accounts in one browser, "sign out" split into two
785
+ // genuinely different actions and conflating them is destructive in
786
+ // one direction: ending the owner's session because a test account
787
+ // left is work lost in a tab nobody touched.
788
+ //
789
+ // default — leave THIS slot. Every other account stays signed in,
790
+ // here and at auth.
791
+ // all=1 — leave every account on this machine. The shared-
792
+ // computer exit, and the only one that ends auth's
793
+ // whole session.
794
+ const all = c.req.query("all") === "1";
795
+ // Read the occupant BEFORE revoking — after, there is nobody to name,
796
+ // and auth needs the id to end that person's auth session alone.
797
+ const leaving = all ? null : sessions.userIdOf(c.req.raw);
798
+ const slot = sessions.slotOf(c.req.raw);
799
+
800
+ if (all) {
801
+ for (const cleared of sessions.revokeEverySlot(c.req.raw)) {
802
+ c.header("set-cookie", sessions.clearedCookie(c.req.raw, cleared), { append: true });
803
+ }
804
+ // Even with nothing live here, still clear the slot the request
805
+ // names: a cookie whose row expired is a cookie the browser keeps
806
+ // sending, and the visible result of "sign out" must not be
807
+ // nothing.
808
+ c.header("set-cookie", sessions.clearedCookie(c.req.raw, slot), { append: true });
809
+ } else {
810
+ sessions.revoke(c.req.raw);
811
+ c.header("set-cookie", sessions.clearedCookie(c.req.raw, slot), { append: true });
812
+ }
813
+ // An abandoned deep link must not resume for whoever signs in next.
814
+ if (hasReturnCookie(c.req.raw)) {
815
+ c.header("set-cookie", clearReturnCookie(c.req.raw), { append: true });
816
+ }
817
+ if (hasSlotCookie(c.req.raw)) {
818
+ c.header("set-cookie", clearSlotCookie(c.req.raw), { append: true });
819
+ }
820
+ const target = new URL(`${authUrl}/sso/logout`);
821
+ target.searchParams.set("app", audience);
822
+ target.searchParams.set("redirect_uri", `${publicUrl}${SSO_CALLBACK_PATH}`);
823
+ // 🔴 Name the account, so auth ends ONE of its sessions rather than
824
+ // all of them. Without this, signing a test account out of one tab
825
+ // signs the owner out of auth too, and the next hop in their tab
826
+ // silently demands a password. `all=1` deliberately sends no account
827
+ // and gets the old, total behavior.
828
+ if (all) target.searchParams.set("all", "1");
829
+ else if (leaving) target.searchParams.set("account", leaving);
830
+ return c.redirect(target.toString(), 302);
831
+ });
832
+
833
+ app.get(SSO_CALLBACK_PATH, async (c) => {
834
+ const fail = (reason: string) => {
835
+ // Land the user somewhere visible with the reason — the SPA renders
836
+ // it as a toast next to the sign-in button. Never a bare 400 page.
837
+ // Also drop the return cookie IF one exists: this attempt is over, and
838
+ // a later, unrelated success must not resume a deep link this one
839
+ // failed on. Only when present, so a plain failed grant still sets no
840
+ // cookie at all.
841
+ if (hasReturnCookie(c.req.raw)) c.header("set-cookie", clearReturnCookie(c.req.raw));
842
+ // Same one-shot discipline for the slot instruction: this attempt
843
+ // is over, and an `add` left behind would make the NEXT ordinary
844
+ // sign-in quietly open a second session instead of refreshing one.
845
+ if (hasSlotCookie(c.req.raw)) {
846
+ c.header("set-cookie", clearSlotCookie(c.req.raw), { append: true });
847
+ }
848
+ return c.redirect(`/?ssoError=${encodeURIComponent(reason)}`, 302);
849
+ };
850
+
851
+ const grant = c.req.query("grant") ?? "";
852
+ if (!grant) return fail("missing grant");
853
+
854
+ // Peek the kid (unverified — only used to decide whether a JWKS
855
+ // refresh is worth it; verification below re-reads it from the same
856
+ // payload under the signature).
857
+ const kid = peekKid(grant);
858
+ const keys = await keysFor(kid ?? "");
859
+ const verdict = verifyGrant(grant, {
860
+ aud: audience,
861
+ keyOf: (k) => keys.get(k) ?? null,
862
+ now,
863
+ });
864
+ if (!verdict.ok) return fail(verdict.reason);
865
+ const claims = verdict.claims;
866
+ if (options.requireAdmin && !claims.admin && claims.granted !== true) {
867
+ // Named plainly: the person DID sign in correctly; the account is
868
+ // simply not allowed here, and "invalid grant" would send them to
869
+ // reset a password that works fine.
870
+ return fail("this account does not have access to this app");
871
+ }
872
+ if (!emailAllowed(claims.email)) {
873
+ // Same plainness, same reason — a working password must never be
874
+ // blamed for an allowlist refusal.
875
+ return fail("this account does not have access to this app");
876
+ }
877
+ if (!nonces.consume(claims.nonce, claims.exp)) return fail("grant already used");
878
+
879
+ // ── Which slot does this session land in? (2026-08-12) ──────────
880
+ // The instruction rode a one-shot cookie because a registered
881
+ // redirect_uri cannot carry a query param — see SSO_SLOT_COOKIE.
882
+ const instruction = readSlotCookie(c.req.raw);
883
+ let slot: number;
884
+ if (instruction === SLOT_COOKIE_ADD) {
885
+ // Chosen HERE rather than at the start, so a browser that gained or
886
+ // lost a session mid-hop still lands somewhere free. `slotToAdd`
887
+ // reuses this person's existing slot when they already have one, so
888
+ // re-adding an account already open is a no-op rather than a
889
+ // duplicate that eats the last free slot.
890
+ const target = sessions.slotToAdd(c.req.raw, claims.id);
891
+ if (target === null) {
892
+ // 🔴 Refuse rather than evict. Somebody's live session is worth
893
+ // more than the convenience of not saying no, and the message
894
+ // names the fix.
895
+ return fail(
896
+ `this browser is already signed into ${MAX_ACCOUNT_SLOTS} accounts here — sign one out first`,
897
+ );
898
+ }
899
+ slot = target;
900
+ } else {
901
+ // A plain hop refreshes the tab that started it. Absent (an expired
902
+ // one-shot, a first sign-in, a build that predates slots) is slot 0
903
+ // — the single-account behavior this fleet already had.
904
+ slot = normalizeSlot(instruction ?? 0);
905
+ }
906
+
907
+ upsertUser(db, claims, now);
908
+ // The request is passed so the row records the device and address
909
+ // this session was opened from — the whole substance of the fleet
910
+ // session list. A session that cannot say where it came from is one
911
+ // the owner cannot recognise, and therefore cannot act on.
912
+ //
913
+ // `signIn` rather than create + sessionCookie: those are two calls
914
+ // that must be told the same slot, and being told different ones is
915
+ // silent — a row in slot 2 with a cookie written to slot 0 evicts
916
+ // whoever the person was already using in another tab.
917
+ const issued = sessions.signIn(claims.id, c.req.raw, { slot });
918
+ c.header("set-cookie", issued.cookie, { append: true });
919
+ // Resume the deep link the sign-out interrupted, re-validating on the
920
+ // way back: the cookie is unsigned, and validation is what makes that
921
+ // safe — only a same-origin path of this app can pass, so a tampered
922
+ // cookie is at worst a harmless local path. Consume it either way, so
923
+ // the return is strictly one-shot.
924
+ const back = sanitizeReturnPath(readReturnCookie(c.req.raw));
925
+ c.header("set-cookie", clearReturnCookie(c.req.raw), { append: true });
926
+ c.header("set-cookie", clearSlotCookie(c.req.raw), { append: true });
927
+ // 🔴 The landing URL CARRIES the slot. This is what makes the tab
928
+ // stick to the account it just opened — through a reload, a bookmark
929
+ // and every link inside the app. `withSlot` strips the param for slot
930
+ // 0, so the single-account case keeps the clean URLs it has today.
931
+ return c.redirect(withSlot(back ?? "/", issued.slot), 302);
932
+ });
933
+
934
+ // ── The cascade (2026-08-01) ──────────────────────────────────────
935
+ // Disabling or deleting an account at auth used to leave this app's
936
+ // already-minted cookie working until it expired, because request-time
937
+ // auth deliberately never calls auth. So auth pushes the news here.
938
+ //
939
+ // Failure is LOUD (a non-2xx auth can report) rather than a silent 200:
940
+ // the admin page shows which apps confirmed, and "roms did not answer"
941
+ // is the difference between a locked-out account and one that is still
942
+ // playing. It is also idempotent — revoking nobody's sessions twice is
943
+ // a no-op, so auth is free to retry.
944
+ app.post(SSO_REVOKE_PATH, async (c) => {
945
+ const body = await c.req.json().catch(() => null);
946
+ const ticket =
947
+ body && typeof (body as { ticket?: unknown }).ticket === "string"
948
+ ? (body as { ticket: string }).ticket
949
+ : "";
950
+ if (!ticket) return c.json({ error: "missing ticket" }, 400, noStore);
951
+
952
+ const kid = peekKid(ticket);
953
+ const keys = await keysFor(kid ?? "");
954
+ const verdict = verifyRevocation(ticket, {
955
+ aud: audience,
956
+ keyOf: (k) => keys.get(k) ?? null,
957
+ now,
958
+ });
959
+ if (!verdict.ok) {
960
+ console.warn(`[${appKey}] refused an SSO revocation: ${verdict.reason}`);
961
+ return c.json({ error: verdict.reason }, 401, noStore);
962
+ }
963
+ const { sub, action, sid, nonce, exp } = verdict.claims;
964
+ // Replay protection shares the grant nonce guard: both are 60-second
965
+ // single-use statements from the same issuer, and a replayed
966
+ // revocation is harmless anyway (it re-revokes nothing).
967
+ if (!nonces.consume(nonce, exp)) {
968
+ return c.json({ error: "ticket already used" }, 401, noStore);
969
+ }
970
+
971
+ // One session, or all of them (2026-08-12). `sid` narrows the SAME
972
+ // ticket rather than adding a second revocation path — the store
973
+ // scopes the handle to `sub`, so a stale or guessed one can only ever
974
+ // end a session of the account the ticket already names.
975
+ //
976
+ // A handle that matches nothing answers `matched: false` and 200, not
977
+ // an error: the session it named is gone, which is the state the
978
+ // caller asked for. Auth renders the distinction ("already ended")
979
+ // rather than a red failure the owner would re-press.
980
+ if (sid) {
981
+ const matched = sessions.revokeByHandle(sub, sid);
982
+ console.warn(
983
+ `[${appKey}] SSO revoke of one session for user ${sub}: ${
984
+ matched ? "ended" : "no live session with that handle"
985
+ }`,
986
+ );
987
+ return c.json({ ok: true, action, scope: "session" as const, matched }, 200, noStore);
988
+ }
989
+
990
+ sessions.revokeAllForUser(sub);
991
+ if (action === "delete") {
992
+ // Drop the snapshot so the account stops showing up in this app's
993
+ // own lists. Rows keyed on the id are ORPHANED, not cascaded —
994
+ // same posture auth's delete already warns about, and the
995
+ // alternative (deleting a household member's save states because
996
+ // their account was tidied up) is unrecoverable.
997
+ db.query("DELETE FROM sso_users WHERE id = ?").run(sub);
998
+ }
999
+ console.warn(`[${appKey}] SSO ${action} applied for user ${sub}`);
1000
+ return c.json({ ok: true, action, scope: "user" as const }, 200, noStore);
1001
+ });
1002
+
1003
+ // ── The session list (2026-08-12) ─────────────────────────────────
1004
+ // The other read-only twin of the cascade, and the one that makes it
1005
+ // usable as a security control rather than a blunt instrument: auth
1006
+ // can now show every live session of an account across the whole
1007
+ // fleet — device, address, when it started, when it was last used —
1008
+ // and end exactly one of them.
1009
+ //
1010
+ // Unlike the census there is nothing to opt into. Every consumer has a
1011
+ // session store (it is how it holds anyone signed in at all), so this
1012
+ // route can always answer, and an app that CANNOT answer is a 404 from
1013
+ // a build that predates it. Auth renders that as "could not say",
1014
+ // never as "no sessions" — a false empty here reads as "nothing is
1015
+ // signed in over there", which is the one sentence this feature exists
1016
+ // to stop somebody believing.
1017
+ app.post(SSO_SESSIONS_PATH, async (c) => {
1018
+ const body = await c.req.json().catch(() => null);
1019
+ const ticket =
1020
+ body && typeof (body as { ticket?: unknown }).ticket === "string"
1021
+ ? (body as { ticket: string }).ticket
1022
+ : "";
1023
+ if (!ticket) return c.json({ error: "missing ticket" }, 400, noStore);
1024
+
1025
+ const kid = peekKid(ticket);
1026
+ const keys = await keysFor(kid ?? "");
1027
+ const verdict = verifySessionsRequest(ticket, {
1028
+ aud: audience,
1029
+ keyOf: (k) => keys.get(k) ?? null,
1030
+ now,
1031
+ });
1032
+ if (!verdict.ok) {
1033
+ console.warn(`[${appKey}] refused an SSO session-list request: ${verdict.reason}`);
1034
+ return c.json({ error: verdict.reason }, 401, noStore);
1035
+ }
1036
+ // Deliberately NOT nonce-consumed, for the census's reason exactly:
1037
+ // this route writes nothing, so a replay costs a re-read, and
1038
+ // burning the shared nonce guard on a read would make auth's own
1039
+ // timeout-and-retry fail on the retry.
1040
+ const rows = sessions
1041
+ .listForUser(verdict.claims.sub)
1042
+ .slice(0, SESSIONS_MAX_PER_APP)
1043
+ .map(
1044
+ ({ handle, userId, createdAt, lastSeenAt, expiresAt, userAgent, ip, place }) =>
1045
+ ({
1046
+ handle,
1047
+ userId,
1048
+ createdAt,
1049
+ lastSeenAt,
1050
+ expiresAt,
1051
+ userAgent,
1052
+ ip,
1053
+ place,
1054
+ }) satisfies SsoSessionSummary,
1055
+ );
1056
+ return c.json({ sessions: rows }, 200, noStore);
1057
+ });
1058
+
1059
+ // ── The census (2026-08-10) ───────────────────────────────────────
1060
+ // The read-only twin of the route above, and the reason it exists: an
1061
+ // admin page that can take access away must be able to say what that
1062
+ // costs the person. Auth asks here, counts nothing itself, and shows
1063
+ // the answer in the confirmation dialog.
1064
+ //
1065
+ // An app that implements no `contentCensus` answers 200 with
1066
+ // `scope: "unknown"` rather than 404 — auth then says "this app could
1067
+ // not tell me", which is honest, where a 404 would be indistinguishable
1068
+ // from an old deployment that has not been rebuilt yet. Both read as
1069
+ // "do not trust a zero here", which is the point.
1070
+ app.post(SSO_CENSUS_PATH, async (c) => {
1071
+ const body = await c.req.json().catch(() => null);
1072
+ const ticket =
1073
+ body && typeof (body as { ticket?: unknown }).ticket === "string"
1074
+ ? (body as { ticket: string }).ticket
1075
+ : "";
1076
+ if (!ticket) return c.json({ error: "missing ticket" }, 400, noStore);
1077
+
1078
+ const kid = peekKid(ticket);
1079
+ const keys = await keysFor(kid ?? "");
1080
+ const verdict = verifyCensus(ticket, {
1081
+ aud: audience,
1082
+ keyOf: (k) => keys.get(k) ?? null,
1083
+ now,
1084
+ });
1085
+ if (!verdict.ok) {
1086
+ console.warn(`[${appKey}] refused an SSO census: ${verdict.reason}`);
1087
+ return c.json({ error: verdict.reason }, 401, noStore);
1088
+ }
1089
+ // Deliberately NOT nonce-consumed. This route writes nothing, so a
1090
+ // replay costs a re-count and discloses what the same caller could
1091
+ // ask for again anyway — and burning the shared nonce guard on a
1092
+ // read would make auth's own timeout-and-retry fail on the retry.
1093
+ const subs = verdict.claims.subs.slice(0, CENSUS_MAX_SUBJECTS);
1094
+ if (!options.contentCensus) {
1095
+ return c.json({ census: { scope: "unknown" as const } }, 200, noStore);
1096
+ }
1097
+ try {
1098
+ const census = await options.contentCensus(subs);
1099
+ return c.json({ census }, 200, noStore);
1100
+ } catch (err) {
1101
+ // Loud and non-2xx: auth must report "this app could not answer",
1102
+ // never render a silent zero. A zero the owner believes is exactly
1103
+ // how somebody's save states get deleted by a dropdown.
1104
+ const error = err instanceof Error ? err.message : String(err);
1105
+ console.warn(`[${appKey}] content census failed: ${error}`);
1106
+ return c.json({ error }, 500, noStore);
1107
+ }
1108
+ });
1109
+
1110
+ app.get("/api/auth/session", (c) => {
1111
+ const user = sessionUser(c);
1112
+ // ── What the account switcher needs, answered LOCALLY (2026-08-12)
1113
+ // Every account signed in on this browser, from this app's own
1114
+ // `sso_users` rows plus its own cookies. No call to auth, which is
1115
+ // the fleet's central property: the switcher keeps working while the
1116
+ // box hosting auth is asleep, and it costs one sqlite read.
1117
+ //
1118
+ // Only the slots this browser ALREADY holds are listed. This is not
1119
+ // a directory of accounts — an anonymous caller sees an empty list,
1120
+ // and a caller in slot 1 sees exactly what their own cookies prove.
1121
+ const occupants = sessions.signedInSlots(c.req.raw);
1122
+ const accounts = occupants.flatMap(({ slot, userId }) => {
1123
+ const row = db
1124
+ .query("SELECT id, email, name FROM sso_users WHERE id = ?")
1125
+ .get(userId) as { id: string; email: string; name: string } | null;
1126
+ // A slot whose row this app has never seen is skipped rather than
1127
+ // rendered nameless: it means a session survived a database reset,
1128
+ // and offering an unlabelled button to switch to it is worse than
1129
+ // not offering one.
1130
+ return row ? [{ slot, id: row.id, email: row.email, name: row.name }] : [];
1131
+ });
1132
+ const base = {
1133
+ accountsUrl: authUrl,
1134
+ slot: sessions.slotOf(c.req.raw),
1135
+ accounts,
1136
+ /** No room to add another without signing one out — the menu says
1137
+ * so rather than offering a button that fails at the callback. */
1138
+ slotsFull: occupants.length >= MAX_ACCOUNT_SLOTS,
1139
+ maxAccounts: MAX_ACCOUNT_SLOTS,
1140
+ };
1141
+ return c.json(
1142
+ user
1143
+ ? { authenticated: true as const, user, ...base }
1144
+ : { authenticated: false as const, ...base },
1145
+ 200,
1146
+ noStore,
1147
+ );
1148
+ });
1149
+
1150
+ // POST, not GET: a GET logout is CSRF-able and prefetchable.
1151
+ //
1152
+ // Slot-scoped like its redirecting sibling: this ends the account the
1153
+ // request names and nothing else. It has always ended only THIS app's
1154
+ // session (auth's outlives it), so there is no `all=1` here — leaving
1155
+ // every account on a shared machine is the door that must also reach
1156
+ // auth, and that one has to redirect.
1157
+ app.post("/api/auth/logout", (c) => {
1158
+ const slot = sessions.slotOf(c.req.raw);
1159
+ sessions.revoke(c.req.raw);
1160
+ return c.json({ authenticated: false }, 200, {
1161
+ "set-cookie": sessions.clearedCookie(c.req.raw, slot),
1162
+ ...noStore,
1163
+ });
1164
+ });
1165
+ },
1166
+ };
1167
+ }
1168
+
1169
+ /**
1170
+ * One account, one row — even when auth re-issues its id (2026-08-23).
1171
+ *
1172
+ * ── The ghost ───────────────────────────────────────────────────────────────
1173
+ * The owner, on family's Permissions screen: *"I notice two entries for
1174
+ * smoke@auth.local."* Measured on prod the same day, and he was right — two rows,
1175
+ * one address, two different auth ids, one of them last seen on 2026-08-10 and
1176
+ * never again. It was **not** a family bug and not a display bug.
1177
+ *
1178
+ * `upsertUser` conflicts on `id`. So an account whose id at auth CHANGES — the
1179
+ * smoke account being rotated by `bun run user -- --smoke --write`, an account
1180
+ * recreated by hand, one of the several rows still keyed on an email address from
1181
+ * before uuids — arrives as a brand new row and the old one is never touched
1182
+ * again by anything. It is invisible to the revocation cascade (which deletes by
1183
+ * the id auth still knows) and to the census, so it survives every sign-in,
1184
+ * every deploy and every account deletion, forever, in every app that ever saw
1185
+ * that person. This one had `is_admin = 1` frozen from before the smoke account
1186
+ * was demoted, so family's own people list showed a **ghost administrator**.
1187
+ *
1188
+ * ── Why it is fixed HERE and not in family ──────────────────────────────────
1189
+ * Nineteen apps keep this snapshot from this one function. Family is simply the
1190
+ * app with the most rows in it, so it is where a duplicate showed up first.
1191
+ *
1192
+ * ── Why the newest row wins, and the old id is DROPPED ──────────────────────
1193
+ * The id auth is presenting now is the only one that will ever resolve a session
1194
+ * again, so the other row is unreachable by construction — it cannot sign in,
1195
+ * cannot be revoked and cannot be deleted through the cascade. Dropping it is the
1196
+ * only operation that changes what a person sees. 🔴 App rows keyed on the stale
1197
+ * id are left ALONE, deliberately: that is the same posture the `delete` cascade
1198
+ * already takes ("orphaned, not cascaded"), and deleting somebody's saved work
1199
+ * because their account id was reissued is unrecoverable. Measured on prod before
1200
+ * shipping this: the stale id appeared in exactly one place in family's whole
1201
+ * database — its own `sso_users` row.
1202
+ */
1203
+ function dropDuplicateSnapshots(db: Database): void {
1204
+ // `lower(email)` so two rows differing only in case are one account, which is
1205
+ // the same rule `emailAllowed` and auth's own registry already apply.
1206
+ db.exec(`DELETE FROM sso_users WHERE rowid NOT IN (
1207
+ SELECT rowid FROM (
1208
+ SELECT rowid,
1209
+ ROW_NUMBER() OVER (
1210
+ PARTITION BY lower(email)
1211
+ ORDER BY last_login_at DESC, updated_at DESC, rowid DESC
1212
+ ) AS rn
1213
+ FROM sso_users
1214
+ ) WHERE rn = 1
1215
+ )`);
1216
+ }
1217
+
1218
+ function upsertUser(db: Database, claims: SsoGrantClaims, now: () => number): void {
1219
+ const at = new Date(now()).toISOString();
1220
+ // 🔴 The same address under a DIFFERENT id is the ghost described above, and
1221
+ // this is the moment it would be created. Clearing it first is what turns the
1222
+ // unique index from a constraint that would throw on a legitimate sign-in into
1223
+ // one that simply cannot be violated. Scoped to `id <> ?` so an ordinary
1224
+ // re-sign-in — by far the common path — deletes nothing and the upsert below
1225
+ // updates in place.
1226
+ db.query("DELETE FROM sso_users WHERE lower(email) = lower(?) AND id <> ?").run(
1227
+ claims.email,
1228
+ claims.id,
1229
+ );
1230
+ db.query(
1231
+ `INSERT INTO sso_users (id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at)
1232
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1233
+ ON CONFLICT(id) DO UPDATE SET
1234
+ email = excluded.email, name = excluded.name, is_admin = excluded.is_admin,
1235
+ is_owner = excluded.is_owner, is_granted = excluded.is_granted,
1236
+ last_login_at = excluded.last_login_at, updated_at = excluded.updated_at`,
1237
+ ).run(
1238
+ claims.id,
1239
+ claims.email,
1240
+ claims.name,
1241
+ claims.admin ? 1 : 0,
1242
+ claims.owner === true ? 1 : 0,
1243
+ claims.granted === true ? 1 : 0,
1244
+ at,
1245
+ at,
1246
+ at,
1247
+ );
1248
+ }
1249
+
1250
+ function peekKid(grant: string): string | null {
1251
+ try {
1252
+ const payload = grant.split(".")[0] ?? "";
1253
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
1254
+ kid?: unknown;
1255
+ };
1256
+ return typeof claims.kid === "string" ? claims.kid : null;
1257
+ } catch {
1258
+ return null;
1259
+ }
1260
+ }