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