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