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,678 @@
1
+ /**
2
+ * Multi-user sessions: an HMAC-signed cookie carrying a random id, resolved to
3
+ * a user through a server-side row.
4
+ *
5
+ * ── Why a session TABLE, when the kit's owner-auth deliberately has none ────
6
+ * `cursedauth`'s `secureRequest` serves apps with exactly ONE principal, so its
7
+ * cookie only has to prove "the owner signed in" and a table would be surface
8
+ * without purpose. Here the cookie must answer "WHICH user", and admin actions
9
+ * must end sessions the server never got handed back (delete a user, issue a
10
+ * temp password, change a password on every other device). A row per session
11
+ * answers all of that with one primitive: login inserts, lookup joins, admin
12
+ * deletes. The revocation-store/valid-from machinery owner-auth grew for the
13
+ * same needs would have to be duplicated per-user here — the table IS the
14
+ * simpler design at N > 1.
15
+ *
16
+ * The cookie value is `<expiry>.<id>.<sig>` — same shape, same constant-time
17
+ * verification, same TLS-aware attributes as owner-auth; the signature keeps
18
+ * every request from being a blind db probe, and the row keeps the cookie
19
+ * revocable. Sessions live in their OWN sqlite file (`sessions.sqlite`), not in
20
+ * the app db — the split roms made, and for the same reason: a credential
21
+ * surface should not share a Database handle with app data.
22
+ *
23
+ * Extracted from `apps/hobbies` (2026-07-28; that app retired 2026-08-25) when `apps/auth` became the second
24
+ * app to need it — cookie NAME is the only thing an app says for itself,
25
+ * because sibling subdomains sharing one cookie name invites the belief that a
26
+ * session in one means something in another (the repo's standing rule).
27
+ *
28
+ * ── Sessions are LISTABLE and individually revocable (2026-08-12) ───────────
29
+ * A row per session was always what made "sign everybody out" possible. What it
30
+ * could not do was answer "signed in WHERE, from what, since when" — the row
31
+ * held an id, a user and an expiry and nothing a person could recognise. ca's
32
+ * admin console had that page; this fleet did not, and it is a security control
33
+ * rather than a convenience: the only way to notice a session you did not open
34
+ * is to be shown the list.
35
+ *
36
+ * So every row now carries a device, an address, a creation time and a
37
+ * last-seen time, every satellite gets it from this one store with no per-app
38
+ * wiring, and `apps/auth` collects them across the fleet over the same signed
39
+ * channel the revocation cascade uses.
40
+ *
41
+ * 🔴 **The row id never leaves this module.** It is the secret half of the
42
+ * cookie (`<expiry>.<id>.<sig>`), and while a signature is still required to
43
+ * use one, a list API that printed session ids would be publishing a credential
44
+ * component to a screen, a log and a JSON body between two apps. What leaves is
45
+ * a HANDLE — `sha256(id)`, truncated — which is stable, comparable, useless
46
+ * without the id, and needs no column of its own (so no migration, and no
47
+ * second thing that can disagree with the first).
48
+ *
49
+ * ── Several accounts at once, in one browser (2026-08-12) ───────────────────
50
+ * The table never needed changing for this: a row per session already allowed
51
+ * one person to be signed in from five places, and nothing in it says "one per
52
+ * browser". The single-account limit lived entirely in the COOKIE — one name,
53
+ * one value, one session reachable per origin.
54
+ *
55
+ * So the cookie became N cookies, one per SLOT (`accountSlots.ts` holds the
56
+ * vocabulary and the reasoning), and every method that used to mean "the
57
+ * session" now means "the session in the slot this request named". Slot 0 is
58
+ * the bare cookie name and the default for every caller that says nothing, so
59
+ * this is additive in the strictest sense — no migration, no expired sessions,
60
+ * and an app that never opens a second account is byte-identical to before.
61
+ *
62
+ * 🔴 The slot is chosen by the REQUEST and is attacker-writable. It selects
63
+ * among this browser's own cookies and can never conjure one: an empty slot
64
+ * resolves to null and the request is anonymous. Never treat a slot number as
65
+ * identity — resolve it here, every time.
66
+ */
67
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
68
+ import { mkdirSync } from "node:fs";
69
+ import path from "node:path";
70
+ import { Database } from "bun:sqlite";
71
+ import {
72
+ ACCOUNT_SLOT_HEADER,
73
+ ACCOUNT_USER_HEADER,
74
+ MAX_ACCOUNT_SLOTS,
75
+ normalizeSlot,
76
+ slotCookieName,
77
+ slotFromUrl,
78
+ } from "./accountSlots";
79
+ import {
80
+ clientAddressOf,
81
+ clientFactsOf,
82
+ clientUserAgentOf,
83
+ describePlace,
84
+ type PlaceLookup,
85
+ } from "./clientDescription";
86
+ import { isSecureRequest } from "./secureRequest";
87
+
88
+ export interface UserSessionStoreOptions {
89
+ /** Per-app cookie name, e.g. "hobbies_session" — never shared across apps. */
90
+ cookieName: string;
91
+ dbPath: string;
92
+ sessionSecret: string;
93
+ sessionTtlSeconds: number;
94
+ /**
95
+ * Where an address is, for the `place` stamped on a new session row.
96
+ *
97
+ * 🔴 There is NO default here, and that is the one deliberate behaviour
98
+ * change this module carries out of the previous generation. It used to
99
+ * default to a machine-wide 375MB IP→city snapshot kept outside any repo;
100
+ * this generation has two roots and nothing else, so a library may not
101
+ * reach for a file it did not put there. Unset, the row records whatever
102
+ * the edge headers said (`cf-ipcity` and friends) — which is what every
103
+ * request behind Cloudflare already carries — or nothing.
104
+ *
105
+ * Pass a lookup to restore city-from-address; `null` and unset are the
106
+ * same thing and both are safe in a test.
107
+ */
108
+ placeLookup?: PlaceLookup | null;
109
+ now?: () => number;
110
+ }
111
+
112
+ /**
113
+ * One live session, as anything outside this module may see it.
114
+ *
115
+ * Deliberately without the row id — see the header. Times are ms epoch so the
116
+ * shape survives a JSON hop between two satellites without a date parser at
117
+ * each end.
118
+ */
119
+ export interface SessionRecord {
120
+ /** Stable public name for this session: `sha256(id)`, first 24 hex chars.
121
+ * What a revoke-one call names, and the only id that crosses the wire. */
122
+ handle: string;
123
+ userId: string;
124
+ createdAt: number;
125
+ /** Last request this session made, throttled to the minute — see `TOUCH`. */
126
+ lastSeenAt: number;
127
+ expiresAt: number;
128
+ /** The user-agent verbatim, bounded, never parsed here. `""` for a session
129
+ * minted before this column existed, or by a client that sent none. */
130
+ userAgent: string;
131
+ /** Best-effort client address, or `""`. Never used to authorize anything. */
132
+ ip: string;
133
+ /**
134
+ * Where the address was, when the session was created — `"Austin, Texas,
135
+ * US"`, or `""`.
136
+ *
137
+ * Stamped at sign-in and never refreshed, deliberately: the row answers
138
+ * "where was I when I signed in on this thing", and a value that moved with
139
+ * the session's later requests would make an old row disagree with the alert
140
+ * that was mailed about it. Added 2026-08-25 with the same owner ask that
141
+ * put the city in the security alerts.
142
+ */
143
+ place: string;
144
+ /** Is this the session the request asking the question is holding? Only ever
145
+ * true when `list` was given that request — "you are on this one" is the
146
+ * difference between signing someone else out and signing yourself out. */
147
+ current: boolean;
148
+ }
149
+
150
+ /** Who is signed in at one slot of this browser. */
151
+ export interface SlotOccupant {
152
+ slot: number;
153
+ userId: string;
154
+ }
155
+
156
+ /** How a new session differs from the store's defaults. */
157
+ export interface SignInOptions {
158
+ /**
159
+ * Which slot to put it in. Defaults to the slot the request names — which
160
+ * for every existing caller is 0, the bare cookie name.
161
+ */
162
+ slot?: number;
163
+ /**
164
+ * Lifetime for THIS session, overriding the store's default.
165
+ *
166
+ * This is what "remember me" buys, and it is a property of the session
167
+ * rather than of the store because the two answers have to coexist: the
168
+ * owner's own browser keeps a month-long session while a shared machine
169
+ * gets the short default. The row's `expires_at`, the cookie's embedded
170
+ * expiry and the cookie's `Max-Age` are all derived from this one number,
171
+ * so they cannot disagree.
172
+ */
173
+ ttlSeconds?: number;
174
+ }
175
+
176
+ /** A minted session and everything the caller needs to install it. */
177
+ export interface SignedIn {
178
+ /** The `Set-Cookie` header value, already slot- and lifetime-correct. */
179
+ cookie: string;
180
+ /** Where it landed — the caller has to tell the browser, via `?authuser=`. */
181
+ slot: number;
182
+ expiresAt: number;
183
+ }
184
+
185
+ export interface UserSessionStore {
186
+ /** The cookie name this store was built with (for tests and smokes). */
187
+ cookieName: string;
188
+ /**
189
+ * Mint a session for a user; returns the cookie VALUE.
190
+ *
191
+ * `req` is optional and every caller that has one should pass it: it is what
192
+ * stamps the device and address onto the row, and a session that cannot say
193
+ * where it came from is one the owner cannot recognise on the list. Omitting
194
+ * it is legal (a CLI-minted session, a test) and lands as `""`, never as a
195
+ * guess.
196
+ */
197
+ create(userId: string, req?: Request, options?: SignInOptions): string;
198
+ /**
199
+ * Mint a session AND the `Set-Cookie` that installs it, together.
200
+ *
201
+ * 🔴 Prefer this over `create` + `sessionCookie` for anything slot- or
202
+ * lifetime-aware. Those two are separate calls that each have to be told the
203
+ * same slot and the same TTL, and the failure when they are not told the
204
+ * same thing is silent: a session minted into slot 2 with a cookie written
205
+ * to slot 0 evicts the account the person was already using and signs them
206
+ * in as somebody else in the tab they did not touch.
207
+ */
208
+ signIn(userId: string, req: Request, options?: SignInOptions): SignedIn;
209
+ /** Which slot this request is acting as. Never throws; garbage means 0. */
210
+ slotOf(req: Request): number;
211
+ /**
212
+ * The account id this request's PAGE believes it is acting as, or null when
213
+ * it did not say. Only ever compared against the resolved user — never a
214
+ * credential, never a selector. See {@link ACCOUNT_USER_HEADER}.
215
+ */
216
+ expectedUserOf(req: Request): string | null;
217
+ /** The user id this request's cookie proves, or null. */
218
+ userIdOf(req: Request): string | null;
219
+ /**
220
+ * Every slot of this browser that holds a live session, slot order.
221
+ *
222
+ * This is the account switcher's whole data source, and the reason it can
223
+ * offer a one-click swap with no password: an account with a live session
224
+ * here is one this browser has already proved it may act as.
225
+ */
226
+ signedInSlots(req: Request): SlotOccupant[];
227
+ /**
228
+ * The slot already holding `userId` in this browser, or null.
229
+ *
230
+ * 🔴 Signing in as somebody who is already signed in must REUSE their slot,
231
+ * never take a second one. Otherwise every re-hop of an app that is already
232
+ * open burns a slot, and five visits leave no room for the second account
233
+ * the feature exists to hold.
234
+ */
235
+ slotForUser(req: Request, userId: string): number | null;
236
+ /**
237
+ * Where a NEW account should go: their existing slot, else the lowest empty
238
+ * one, else null when all {@link MAX_ACCOUNT_SLOTS} are taken.
239
+ *
240
+ * Null is a real answer the caller must render, not an error — "sign out of
241
+ * one of these first" is the only honest response, and silently evicting
242
+ * somebody's session to make room is the thing that must not happen.
243
+ */
244
+ slotToAdd(req: Request, userId: string): number | null;
245
+ /** End the session this request carries, in the slot it names. */
246
+ revoke(req: Request): void;
247
+ /**
248
+ * End the session at ONE named slot of this browser; true if there was one.
249
+ *
250
+ * Distinct from `revoke` because the switcher acts on a slot the request is
251
+ * NOT on — "remove that other account" is a button pressed from this tab
252
+ * about a different tab's session.
253
+ */
254
+ revokeAt(req: Request, slot: number): boolean;
255
+ /**
256
+ * End EVERY slot's session in this browser; returns the slots that held one.
257
+ *
258
+ * The shared-machine exit. Distinct from `revokeAllForUser`, which ends one
259
+ * account everywhere, where this ends every account in one place.
260
+ */
261
+ revokeEverySlot(req: Request): number[];
262
+ /** End every session of a user (delete / temp password). */
263
+ revokeAllForUser(userId: string): void;
264
+ /** End every OTHER session of a user (their own password change). */
265
+ revokeOthersForUser(userId: string, req: Request): void;
266
+ /**
267
+ * Every live session of one user, newest first.
268
+ *
269
+ * Expired rows are never returned — the sweep is opportunistic, so the query
270
+ * filters rather than trusting the table to be clean.
271
+ */
272
+ listForUser(userId: string, req?: Request): SessionRecord[];
273
+ /**
274
+ * End ONE session, named by its handle, and say whether it existed.
275
+ *
276
+ * 🔴 The user id is REQUIRED and is part of the match, not a courtesy. A
277
+ * handle is shown on a screen and travels between apps; scoping the delete
278
+ * to the account it was listed under means a stray, stale or guessed handle
279
+ * can only ever end a session of the person it was already about.
280
+ */
281
+ revokeByHandle(userId: string, handle: string): boolean;
282
+ /**
283
+ * `Set-Cookie` for a fresh value, TLS-aware.
284
+ *
285
+ * `Max-Age` is read out of the VALUE's own embedded expiry rather than from
286
+ * the store's default, so a remember-me session's cookie outlives the
287
+ * default the same way its row does. A value that cannot be read falls back
288
+ * to the store default — a cookie slightly too short is a re-login, where
289
+ * one too long is a dead cookie sent on every request forever.
290
+ */
291
+ sessionCookie(value: string, req: Request, slot?: number): string;
292
+ /** `Set-Cookie` that ends the browser's copy, for one slot. */
293
+ clearedCookie(req: Request, slot?: number): string;
294
+ }
295
+
296
+ /**
297
+ * How stale `last_seen_at` may get before a request writes it.
298
+ *
299
+ * `userIdOf` runs on EVERY request, and a write per request is a write per
300
+ * image, poll and asset probe on a database that exists to hold credentials.
301
+ * A minute of resolution is far finer than the question this answers ("is that
302
+ * session still being used, or is it a laptop I left at the office?"), and it
303
+ * turns a per-request write into roughly one per minute per active session.
304
+ */
305
+ const TOUCH_THROTTLE_MS = 60_000;
306
+
307
+ /**
308
+ * The public name of a session: one-way, so it can be printed and posted
309
+ * without ever being usable as the id it came from.
310
+ *
311
+ * Derived rather than stored, so a deployment that predates the session list
312
+ * gets correct handles for the sessions it is already holding — a migration
313
+ * could not have backfilled them (sqlite has no sha256), and rows without one
314
+ * would have been sessions the owner could see and not revoke.
315
+ */
316
+ const handleOf = (id: string): string => createHash("sha256").update(id).digest("hex").slice(0, 24);
317
+
318
+ function constantTimeEqual(a: string, b: string): boolean {
319
+ const ab = Buffer.from(a, "utf8");
320
+ const bb = Buffer.from(b, "utf8");
321
+ const len = Math.max(ab.length, bb.length);
322
+ const pa = Buffer.alloc(len);
323
+ const pb = Buffer.alloc(len);
324
+ ab.copy(pa);
325
+ bb.copy(pb);
326
+ return timingSafeEqual(pa, pb) && ab.length === bb.length;
327
+ }
328
+
329
+ export function createUserSessionStore(options: UserSessionStoreOptions): UserSessionStore {
330
+ // Resolved once per store rather than per sign-in. `null` and unset are the
331
+ // same thing — see `placeLookup` on the options for why there is no default.
332
+ const placeLookup = options.placeLookup ?? undefined;
333
+ const now = options.now ?? Date.now;
334
+ if (options.dbPath !== ":memory:") mkdirSync(path.dirname(options.dbPath), { recursive: true });
335
+ const db = new Database(options.dbPath, { create: true });
336
+ // busy_timeout FIRST — journal_mode takes a lock. scripts/sqliteBusyTimeout.test.ts
337
+ db.exec("PRAGMA busy_timeout = 5000;");
338
+ db.exec("PRAGMA journal_mode = WAL;");
339
+ db.exec(`CREATE TABLE IF NOT EXISTS sessions (
340
+ id TEXT PRIMARY KEY,
341
+ user_id TEXT NOT NULL,
342
+ expires_at INTEGER NOT NULL
343
+ );
344
+ CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);`);
345
+ // The session-list columns (2026-08-12), added by ALTER because every
346
+ // satellite already has this table with live sessions in it. All four default
347
+ // to a value that reads as "we do not know", never as a fabricated one: a
348
+ // session minted before the upgrade shows an unknown device and an unknown
349
+ // address, which is honest, where a zero timestamp would render as 1970 and a
350
+ // blank device would read as "no device" rather than "not recorded".
351
+ //
352
+ // `created_at`/`last_seen_at` default to 0 in SQL and are read through
353
+ // `orZero` below, which falls back to the expiry-derived start rather than to
354
+ // the epoch — the column cannot express "unknown" and the reader can.
355
+ for (const column of [
356
+ "user_agent TEXT NOT NULL DEFAULT ''",
357
+ "ip TEXT NOT NULL DEFAULT ''",
358
+ "created_at INTEGER NOT NULL DEFAULT 0",
359
+ "last_seen_at INTEGER NOT NULL DEFAULT 0",
360
+ // 2026-08-25, same ALTER-because-it-is-live reasoning as the four above.
361
+ "place TEXT NOT NULL DEFAULT ''",
362
+ ]) {
363
+ try {
364
+ db.exec(`ALTER TABLE sessions ADD COLUMN ${column}`);
365
+ } catch {
366
+ // Already there. sqlite has no ADD COLUMN IF NOT EXISTS, and reading
367
+ // pragma table_info to decide costs more than catching the one error
368
+ // this can throw — the same shape `sso_users` uses.
369
+ }
370
+ }
371
+
372
+ const sign = (payload: string): string =>
373
+ createHmac("sha256", options.sessionSecret).update(payload).digest("base64url");
374
+
375
+ const cookieAttributes = (req: Request, maxAge: number): string =>
376
+ [
377
+ "Path=/",
378
+ "HttpOnly",
379
+ // Lax, not Strict: the SSO callback ARRIVES as a cross-site top-level
380
+ // navigation (auth redirects the browser back with the grant), and the
381
+ // very next request must already carry the fresh cookie. Lax sends it on
382
+ // top-level GETs while still refusing cross-site POSTs and subresources,
383
+ // which is the CSRF posture the state-changing routes rely on (all are
384
+ // POST/PATCH/DELETE).
385
+ "SameSite=Lax",
386
+ ...(isSecureRequest(req) ? ["Secure"] : []),
387
+ `Max-Age=${maxAge}`,
388
+ ].join("; ");
389
+
390
+ /**
391
+ * Which account this request is acting as — see `accountSlots.ts`.
392
+ *
393
+ * URL first, header second. The URL is the one a full page load, a bookmark
394
+ * and an `<img src>` can carry, so it has to be authoritative; the header is
395
+ * how an SPA's `fetch` calls say the same thing without every route constant
396
+ * in the app growing a query param.
397
+ */
398
+ const slotOf = (req: Request): number => {
399
+ const fromUrl = slotFromUrl(req.url);
400
+ if (fromUrl !== null) return fromUrl;
401
+ const header = req.headers.get(ACCOUNT_SLOT_HEADER);
402
+ return header === null ? 0 : normalizeSlot(header);
403
+ };
404
+
405
+ /**
406
+ * Who the CLIENT said it was rendering for, or null if it did not say.
407
+ *
408
+ * 🔴 This is never identity and can never be read as any. It exists so a
409
+ * guard can notice that the account behind this browser's slot has been
410
+ * replaced since the page was drawn — see `accountSlots.ts` for the failure
411
+ * and `isAccountDrift` for the one rule that decides it. Bounded, because it
412
+ * is attacker-supplied and only ever compared to a string we already hold.
413
+ */
414
+ const expectedUserOf = (req: Request): string | null => {
415
+ const raw = req.headers.get(ACCOUNT_USER_HEADER);
416
+ if (raw === null) return null;
417
+ const value = raw.trim();
418
+ return value.length > 0 && value.length <= 200 ? value : null;
419
+ };
420
+
421
+ /**
422
+ * Signature first, expiry second — an unsigned value proves nothing.
423
+ *
424
+ * `slot` names WHICH cookie to read. It defaults to the one the request
425
+ * asked for, so every existing caller keeps reading the bare cookie name.
426
+ */
427
+ const parse = (req: Request, slot?: number): { id: string } | null => {
428
+ const cookie = req.headers.get("cookie");
429
+ if (!cookie) return null;
430
+ const name = slotCookieName(options.cookieName, slot ?? slotOf(req));
431
+ const match = new RegExp(`(?:^|;\\s*)${name}=([^;]+)`).exec(cookie);
432
+ const value = match?.[1];
433
+ if (!value) return null;
434
+ const parts = value.split(".");
435
+ if (parts.length !== 3) return null;
436
+ const [expiry, id, signature] = parts as [string, string, string];
437
+ if (!expiry || !id || !signature) return null;
438
+ if (!constantTimeEqual(signature, sign(`${expiry}.${id}`))) return null;
439
+ const expiresAt = Number(expiry);
440
+ if (!Number.isFinite(expiresAt) || expiresAt <= now()) return null;
441
+ return { id };
442
+ };
443
+
444
+ /** The live user at one slot, or null. One query, used by three methods. */
445
+ const userAt = (req: Request, slot: number): string | null => {
446
+ const session = parse(req, slot);
447
+ if (!session) return null;
448
+ const row = db
449
+ .query("SELECT user_id, expires_at FROM sessions WHERE id = ?")
450
+ .get(session.id) as {
451
+ user_id: string;
452
+ expires_at: number;
453
+ } | null;
454
+ return row && row.expires_at > now() ? row.user_id : null;
455
+ };
456
+
457
+ /**
458
+ * The seconds a cookie for `value` should live, from the value's own expiry.
459
+ *
460
+ * Deriving it rather than passing it is what keeps a remember-me cookie and
461
+ * its row in agreement — there is one number and both read it. A value this
462
+ * cannot read falls back to the store default, deliberately erring SHORT:
463
+ * too short costs a sign-in, too long leaves a dead cookie riding every
464
+ * request until the browser gives up on it.
465
+ */
466
+ const cookieLifetimeOf = (value: string): number => {
467
+ const expiresAt = Number(value.split(".")[0]);
468
+ if (!Number.isFinite(expiresAt)) return options.sessionTtlSeconds;
469
+ const seconds = Math.ceil((expiresAt - now()) / 1000);
470
+ return seconds > 0 ? seconds : options.sessionTtlSeconds;
471
+ };
472
+
473
+ /** Opportunistic, on writes: rare, cheap, and exactly when the table grew. */
474
+ const sweep = () => {
475
+ db.query("DELETE FROM sessions WHERE expires_at <= ?").run(now());
476
+ };
477
+
478
+ /** A session minted before `created_at` existed still has a real start: its
479
+ * expiry minus the TTL. Better than 0, which renders as 1970. */
480
+ const startOf = (row: { created_at?: number; expires_at: number }): number =>
481
+ row.created_at && row.created_at > 0
482
+ ? row.created_at
483
+ : row.expires_at - options.sessionTtlSeconds * 1000;
484
+
485
+ // 🔴 These three are plain closures rather than methods called through
486
+ // `this` on the returned object, because call sites in this repo destructure
487
+ // stores (`const { userIdOf } = sessions`) and a `this`-dependent method
488
+ // would throw the moment one of them did.
489
+ const create = (userId: string, req?: Request, signInOptions?: SignInOptions): string => {
490
+ const at = now();
491
+ const ttl = signInOptions?.ttlSeconds ?? options.sessionTtlSeconds;
492
+ const expiresAt = at + ttl * 1000;
493
+ const id = randomBytes(16).toString("base64url");
494
+ db.query(
495
+ `INSERT INTO sessions (id, user_id, expires_at, user_agent, ip, created_at, last_seen_at, place)
496
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
497
+ ).run(
498
+ id,
499
+ userId,
500
+ expiresAt,
501
+ req ? clientUserAgentOf(req) : "",
502
+ req ? clientAddressOf(req) : "",
503
+ at,
504
+ at,
505
+ // The place is resolved HERE, not read back later: `describePlace` of
506
+ // the edge headers merged with this machine's snapshot is a fact about
507
+ // the moment of sign-in, and the snapshot is refreshed monthly.
508
+ req ? describePlace(clientFactsOf(req, { lookup: placeLookup })) : "",
509
+ );
510
+ sweep();
511
+ const payload = `${expiresAt}.${id}`;
512
+ return `${payload}.${sign(payload)}`;
513
+ };
514
+
515
+ const sessionCookie = (value: string, req: Request, slot?: number): string => {
516
+ const name = slotCookieName(options.cookieName, slot ?? slotOf(req));
517
+ return `${name}=${value}; ${cookieAttributes(req, cookieLifetimeOf(value))}`;
518
+ };
519
+
520
+ const revokeAt = (req: Request, slot: number): boolean => {
521
+ const session = parse(req, slot);
522
+ if (!session) return false;
523
+ db.query("DELETE FROM sessions WHERE id = ?").run(session.id);
524
+ return true;
525
+ };
526
+
527
+ const signedInSlots = (req: Request): SlotOccupant[] => {
528
+ const occupants: SlotOccupant[] = [];
529
+ for (let slot = 0; slot < MAX_ACCOUNT_SLOTS; slot++) {
530
+ const userId = userAt(req, slot);
531
+ if (userId) occupants.push({ slot, userId });
532
+ }
533
+ return occupants;
534
+ };
535
+
536
+ return {
537
+ cookieName: options.cookieName,
538
+
539
+ slotOf,
540
+ expectedUserOf,
541
+ create,
542
+ signedInSlots,
543
+
544
+ signIn(userId, req, signInOptions) {
545
+ const slot = normalizeSlot(signInOptions?.slot ?? slotOf(req));
546
+ const value = create(userId, req, signInOptions);
547
+ return {
548
+ cookie: sessionCookie(value, req, slot),
549
+ slot,
550
+ expiresAt: Number(value.split(".")[0]),
551
+ };
552
+ },
553
+
554
+ slotForUser(req, userId) {
555
+ return signedInSlots(req).find((entry) => entry.userId === userId)?.slot ?? null;
556
+ },
557
+
558
+ slotToAdd(req, userId) {
559
+ const occupied = signedInSlots(req);
560
+ // Already here → their slot. Signing in twice must never take a second
561
+ // one; see the interface for why that exhausts the switcher.
562
+ const mine = occupied.find((entry) => entry.userId === userId);
563
+ if (mine) return mine.slot;
564
+ const taken = new Set(occupied.map((entry) => entry.slot));
565
+ for (let slot = 0; slot < MAX_ACCOUNT_SLOTS; slot++) {
566
+ if (!taken.has(slot)) return slot;
567
+ }
568
+ // Full. The caller says so; nothing is evicted to make room.
569
+ return null;
570
+ },
571
+
572
+ userIdOf(req) {
573
+ const session = parse(req);
574
+ if (!session) return null;
575
+ const row = db
576
+ .query("SELECT user_id, expires_at, last_seen_at FROM sessions WHERE id = ?")
577
+ .get(session.id) as {
578
+ user_id: string;
579
+ expires_at: number;
580
+ last_seen_at?: number;
581
+ } | null;
582
+ if (!row || row.expires_at <= now()) return null;
583
+ // "Last seen" is maintained HERE because this is the one call every
584
+ // satellite makes on every authenticated request — the alternative is a
585
+ // per-app middleware that eighteen apps have to remember, which is the
586
+ // same as not having it. Throttled; see TOUCH_THROTTLE_MS.
587
+ const at = now();
588
+ if (at - (row.last_seen_at ?? 0) >= TOUCH_THROTTLE_MS) {
589
+ db.query("UPDATE sessions SET last_seen_at = ? WHERE id = ?").run(at, session.id);
590
+ }
591
+ return row.user_id;
592
+ },
593
+
594
+ listForUser(userId, req) {
595
+ const currentId = req ? (parse(req)?.id ?? null) : null;
596
+ const rows = db
597
+ .query(
598
+ `SELECT id, user_id, expires_at, user_agent, ip, created_at, last_seen_at, place
599
+ FROM sessions WHERE user_id = ? AND expires_at > ?
600
+ ORDER BY last_seen_at DESC, expires_at DESC`,
601
+ )
602
+ .all(userId, now()) as {
603
+ id: string;
604
+ user_id: string;
605
+ expires_at: number;
606
+ user_agent?: string;
607
+ ip?: string;
608
+ created_at?: number;
609
+ last_seen_at?: number;
610
+ place?: string;
611
+ }[];
612
+ return rows.map((row) => ({
613
+ handle: handleOf(row.id),
614
+ userId: row.user_id,
615
+ createdAt: startOf(row),
616
+ lastSeenAt: row.last_seen_at && row.last_seen_at > 0 ? row.last_seen_at : startOf(row),
617
+ expiresAt: row.expires_at,
618
+ userAgent: row.user_agent ?? "",
619
+ ip: row.ip ?? "",
620
+ place: row.place ?? "",
621
+ current: currentId !== null && row.id === currentId,
622
+ }));
623
+ },
624
+
625
+ revokeByHandle(userId, handle) {
626
+ if (!handle) return false;
627
+ // Matched in JS against this user's own rows rather than in SQL,
628
+ // because the handle is a hash and sqlite cannot compute one. The scan
629
+ // is over one account's live sessions — single digits — and it is the
630
+ // same bound the list above already pays.
631
+ const rows = db
632
+ .query("SELECT id FROM sessions WHERE user_id = ? AND expires_at > ?")
633
+ .all(userId, now()) as { id: string }[];
634
+ const match = rows.find((row) => handleOf(row.id) === handle);
635
+ if (!match) return false;
636
+ db.query("DELETE FROM sessions WHERE id = ? AND user_id = ?").run(match.id, userId);
637
+ return true;
638
+ },
639
+
640
+ revoke(req) {
641
+ const session = parse(req);
642
+ if (!session) return;
643
+ db.query("DELETE FROM sessions WHERE id = ?").run(session.id);
644
+ sweep();
645
+ },
646
+
647
+ revokeAt,
648
+
649
+ revokeEverySlot(req) {
650
+ const cleared: number[] = [];
651
+ for (let slot = 0; slot < MAX_ACCOUNT_SLOTS; slot++) {
652
+ if (revokeAt(req, slot)) cleared.push(slot);
653
+ }
654
+ if (cleared.length > 0) sweep();
655
+ return cleared;
656
+ },
657
+
658
+ revokeAllForUser(userId) {
659
+ db.query("DELETE FROM sessions WHERE user_id = ?").run(userId);
660
+ },
661
+
662
+ revokeOthersForUser(userId, req) {
663
+ const session = parse(req);
664
+ if (session) {
665
+ db.query("DELETE FROM sessions WHERE user_id = ? AND id != ?").run(userId, session.id);
666
+ } else {
667
+ db.query("DELETE FROM sessions WHERE user_id = ?").run(userId);
668
+ }
669
+ },
670
+
671
+ sessionCookie,
672
+
673
+ clearedCookie(req, slot) {
674
+ const name = slotCookieName(options.cookieName, slot ?? slotOf(req));
675
+ return `${name}=; ${cookieAttributes(req, 0)}`;
676
+ },
677
+ };
678
+ }