cursedauth 0.5.1 → 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,122 @@
1
+ /**
2
+ * `sso_users` — the local snapshot of whoever has signed in here — behind a seam.
3
+ *
4
+ * ## 🔴 Why this is a seam and not a `Database`
5
+ *
6
+ * `createSsoConsumer` took `db: Database` and issued five statements against it directly.
7
+ * That is fine on Bun and impossible on `workerd`, which has no `bun:sqlite` and no
8
+ * synchronous database at all — so an app ported to a Cloudflare Worker could serve its
9
+ * catalogue and not its door. The alternative the port reached for first was an app-local
10
+ * facade that matched this file's private SQL strings by hand, and its failure mode is the
11
+ * one that matters: the library changes one query, the facade stops matching, and a
12
+ * session check starts answering "no such user" — or worse, "yes".
13
+ *
14
+ * So the five operations are named here, the `bun:sqlite` implementation is the code that
15
+ * used to be inline (moved, not rewritten), and `cursedauth/d1-stores` is the
16
+ * snapshot-and-settle implementation a Worker uses. `SsoConsumerOptions` still accepts
17
+ * `db`, so the six apps that have not ported pass exactly what they passed before.
18
+ *
19
+ * 🔴 `import type` — the `bun:sqlite` import below is erased by every bundler, which is
20
+ * what keeps `cursedauth/sso-consumer` and `cursedauth/sso-user-store` importable on a
21
+ * Worker. `subpathsReachNoBunBuiltin.test.ts` is what proves it, and it is the check that
22
+ * caught the original version of this problem.
23
+ */
24
+ import type { Database } from "bun:sqlite";
25
+ /**
26
+ * One row of `sso_users`, normalized.
27
+ *
28
+ * 🔴 `is_owner` and `is_granted` were added by `ALTER` on 2026-08-02 to tables that
29
+ * already had rows, so a row written before then has no value for them. Both must fail
30
+ * CLOSED — no owner links, no granted bypass — which is why an implementation normalizes a
31
+ * missing column to `0` here rather than letting `undefined` reach a comparison. That is
32
+ * the same decision the old inline `SsoUserRow` made with `is_owner?: number` and
33
+ * `row.is_owner === 1`; stating it once in the seam means two implementations cannot make
34
+ * it differently.
35
+ */
36
+ export interface SsoUserRow {
37
+ id: string;
38
+ email: string;
39
+ name: string;
40
+ is_admin: number;
41
+ is_owner: number;
42
+ is_granted: number;
43
+ last_login_at: string;
44
+ created_at: string;
45
+ updated_at: string;
46
+ }
47
+ /** The five operations `createSsoConsumer` performs against `sso_users`. */
48
+ export interface SsoUserStore {
49
+ /**
50
+ * Make the table exist and be correct, for a host that migrates its own schema.
51
+ *
52
+ * 🔴 A host whose schema is applied OUT OF BAND — D1, where `wrangler d1 execute
53
+ * --file db/schema.sql` is the migration — implements this as a no-op, and that is
54
+ * legitimate rather than a hole: the read that follows it fails loudly and by name if
55
+ * the table is absent, where a per-request `CREATE TABLE` would spend the invocation's
56
+ * query budget on DDL that can never be needed twice.
57
+ */
58
+ ensureSchema(): void;
59
+ byId(id: string): SsoUserRow | null;
60
+ /**
61
+ * Write the snapshot for one account.
62
+ *
63
+ * 🔴 An implementation MUST clear any row holding the same address under a DIFFERENT
64
+ * id before it inserts, and the two statements must land in that ORDER. The unique
65
+ * index on `lower(email)` is what makes a second row for one address impossible; the
66
+ * delete is what keeps a legitimate re-issued account id from hitting that index
67
+ * instead of updating in place. See `reconcileByEmail` in `ssoConsumer.server.ts` for
68
+ * the ghost this removes.
69
+ */
70
+ upsert(row: SsoUserRow): void;
71
+ /**
72
+ * Drop the snapshot so the account stops showing up in this app's own lists.
73
+ *
74
+ * Rows keyed on the id are ORPHANED, not cascaded — the same posture auth's delete
75
+ * already warns about, and the alternative (deleting a household member's save states
76
+ * because their account was tidied up) is unrecoverable.
77
+ */
78
+ deleteById(id: string): void;
79
+ /**
80
+ * Keep one row per ADDRESS, newest first, and drop the rest.
81
+ *
82
+ * The one-time repair for a table that grew duplicates before the unique index
83
+ * existed. Called from {@link ensureSchema} on a host that migrates in place; a host
84
+ * whose database starts empty behind the index has nothing to repair.
85
+ */
86
+ dropDuplicates(): void;
87
+ }
88
+ /**
89
+ * The `sso_users` table in its FINAL shape — every column, no `ALTER` history.
90
+ *
91
+ * Exported for a host that starts empty: this is what goes in an app's `db/schema.sql`
92
+ * next to its own tables. `ssoUsers.sameShape.test.ts` builds the sqlite side the old way
93
+ * (a seven-column `CREATE` plus two `ALTER`s) and the D1 side from this constant, then
94
+ * requires identical answers from both — so it is a schema that has been proved
95
+ * equivalent, not one that was transcribed.
96
+ *
97
+ * 🔴 The unique index is part of it and is not optional. It is what makes one row per
98
+ * address a property of the database rather than a convention two call sites remember.
99
+ */
100
+ export declare const SSO_USERS_DDL = "CREATE TABLE IF NOT EXISTS sso_users (\n\tid TEXT PRIMARY KEY,\n\temail TEXT NOT NULL,\n\tname TEXT NOT NULL DEFAULT '',\n\tis_admin INTEGER NOT NULL DEFAULT 0,\n\tis_owner INTEGER NOT NULL DEFAULT 0,\n\tis_granted INTEGER NOT NULL DEFAULT 0,\n\tlast_login_at TEXT NOT NULL DEFAULT '',\n\tcreated_at TEXT NOT NULL,\n\tupdated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX IF NOT EXISTS sso_users_email ON sso_users (lower(email));";
101
+ /** A row as a driver may hand it back, before the fail-closed normalization above. */
102
+ export interface RawSsoUserRow {
103
+ id: string;
104
+ email: string;
105
+ name: string;
106
+ is_admin: number;
107
+ is_owner?: number | null;
108
+ is_granted?: number | null;
109
+ last_login_at?: string | null;
110
+ created_at: string;
111
+ updated_at: string;
112
+ }
113
+ export declare const normalizeSsoUserRow: (row: RawSsoUserRow) => SsoUserRow;
114
+ /**
115
+ * `sso_users` on `bun:sqlite` — the code that used to be inline in
116
+ * `ssoConsumer.server.ts`, moved rather than rewritten.
117
+ *
118
+ * The table lives in the APP's database (not in the sessions file) so app tables can
119
+ * foreign-key the user id; that is why this takes a handle instead of opening one.
120
+ */
121
+ export declare function createSqliteSsoUserStore(db: Database): SsoUserStore;
122
+ //# sourceMappingURL=ssoUsers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssoUsers.d.ts","sourceRoot":"","sources":["../src/ssoUsers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,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;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,EAAE,EAAE,QAAQ,GAAG,YAAY,CA2FnE"}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The `sso_users` table in its FINAL shape — every column, no `ALTER` history.
3
+ *
4
+ * Exported for a host that starts empty: this is what goes in an app's `db/schema.sql`
5
+ * next to its own tables. `ssoUsers.sameShape.test.ts` builds the sqlite side the old way
6
+ * (a seven-column `CREATE` plus two `ALTER`s) and the D1 side from this constant, then
7
+ * requires identical answers from both — so it is a schema that has been proved
8
+ * equivalent, not one that was transcribed.
9
+ *
10
+ * 🔴 The unique index is part of it and is not optional. It is what makes one row per
11
+ * address a property of the database rather than a convention two call sites remember.
12
+ */
13
+ export const SSO_USERS_DDL = `CREATE TABLE IF NOT EXISTS sso_users (
14
+ id TEXT PRIMARY KEY,
15
+ email TEXT NOT NULL,
16
+ name TEXT NOT NULL DEFAULT '',
17
+ is_admin INTEGER NOT NULL DEFAULT 0,
18
+ is_owner INTEGER NOT NULL DEFAULT 0,
19
+ is_granted INTEGER NOT NULL DEFAULT 0,
20
+ last_login_at TEXT NOT NULL DEFAULT '',
21
+ created_at TEXT NOT NULL,
22
+ updated_at TEXT NOT NULL
23
+ );
24
+ CREATE UNIQUE INDEX IF NOT EXISTS sso_users_email ON sso_users (lower(email));`;
25
+ /** `SELECT *` used to be the read; naming the columns is what makes the two sides comparable. */
26
+ const COLUMNS = "id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at";
27
+ export const normalizeSsoUserRow = (row) => ({
28
+ id: row.id,
29
+ email: row.email,
30
+ name: row.name,
31
+ is_admin: row.is_admin === 1 ? 1 : 0,
32
+ is_owner: row.is_owner === 1 ? 1 : 0,
33
+ is_granted: row.is_granted === 1 ? 1 : 0,
34
+ last_login_at: row.last_login_at ?? "",
35
+ created_at: row.created_at,
36
+ updated_at: row.updated_at,
37
+ });
38
+ /**
39
+ * `sso_users` on `bun:sqlite` — the code that used to be inline in
40
+ * `ssoConsumer.server.ts`, moved rather than rewritten.
41
+ *
42
+ * The table lives in the APP's database (not in the sessions file) so app tables can
43
+ * foreign-key the user id; that is why this takes a handle instead of opening one.
44
+ */
45
+ export function createSqliteSsoUserStore(db) {
46
+ const store = {
47
+ ensureSchema() {
48
+ db.exec(`CREATE TABLE IF NOT EXISTS sso_users (
49
+ id TEXT PRIMARY KEY,
50
+ email TEXT NOT NULL,
51
+ name TEXT NOT NULL DEFAULT '',
52
+ is_admin INTEGER NOT NULL DEFAULT 0,
53
+ last_login_at TEXT NOT NULL DEFAULT '',
54
+ created_at TEXT NOT NULL,
55
+ updated_at TEXT NOT NULL
56
+ );`);
57
+ // 2026-08-02: the fleet directory needs two more facts per account. Added by
58
+ // ALTER rather than by bumping the CREATE, because every deployed satellite
59
+ // already has this table with rows in it. Both default to 0, so an account
60
+ // that has not signed in since the upgrade simply gets no localhost links
61
+ // and no grant bypass until it does — the safe direction.
62
+ for (const column of ["is_owner", "is_granted"]) {
63
+ try {
64
+ db.exec(`ALTER TABLE sso_users ADD COLUMN ${column} INTEGER NOT NULL DEFAULT 0`);
65
+ }
66
+ catch {
67
+ // Already there. sqlite has no ADD COLUMN IF NOT EXISTS, and reading
68
+ // pragma table_info to decide costs more than catching the one error
69
+ // this can throw.
70
+ }
71
+ }
72
+ // 🔴 One row per ADDRESS, not just per id (2026-08-23). The index is what makes
73
+ // it impossible to grow a second one. Created AFTER the sweep, because a live
74
+ // duplicate would refuse the index and leave the table exactly as it was found.
75
+ store.dropDuplicates();
76
+ db.exec("CREATE UNIQUE INDEX IF NOT EXISTS sso_users_email ON sso_users (lower(email))");
77
+ },
78
+ byId(id) {
79
+ const row = db
80
+ .query(`SELECT ${COLUMNS} FROM sso_users WHERE id = ?`)
81
+ .get(id);
82
+ return row ? normalizeSsoUserRow(row) : null;
83
+ },
84
+ upsert(row) {
85
+ // 🔴 The same address under a DIFFERENT id is the ghost described on the
86
+ // interface, and this is the moment it would be created. Clearing it first is
87
+ // what turns the unique index from a constraint that would throw on a legitimate
88
+ // sign-in into one that simply cannot be violated. Scoped to `id <> ?` so an
89
+ // ordinary re-sign-in — by far the common path — deletes nothing and the upsert
90
+ // below updates in place.
91
+ db.query("DELETE FROM sso_users WHERE lower(email) = lower(?) AND id <> ?").run(row.email, row.id);
92
+ db.query(`INSERT INTO sso_users (${COLUMNS})
93
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
94
+ ON CONFLICT(id) DO UPDATE SET
95
+ email = excluded.email, name = excluded.name, is_admin = excluded.is_admin,
96
+ is_owner = excluded.is_owner, is_granted = excluded.is_granted,
97
+ last_login_at = excluded.last_login_at, updated_at = excluded.updated_at`).run(row.id, row.email, row.name, row.is_admin, row.is_owner, row.is_granted, row.last_login_at, row.created_at, row.updated_at);
98
+ },
99
+ deleteById(id) {
100
+ db.query("DELETE FROM sso_users WHERE id = ?").run(id);
101
+ },
102
+ dropDuplicates() {
103
+ // `lower(email)` so two rows differing only in case are one account, which is
104
+ // the same rule `emailAllowed` and auth's own registry already apply.
105
+ db.exec(`DELETE FROM sso_users WHERE rowid NOT IN (
106
+ SELECT rowid FROM (
107
+ SELECT rowid,
108
+ ROW_NUMBER() OVER (
109
+ PARTITION BY lower(email)
110
+ ORDER BY last_login_at DESC, updated_at DESC, rowid DESC
111
+ ) AS rn
112
+ FROM sso_users
113
+ ) WHERE rn = 1
114
+ )`);
115
+ },
116
+ };
117
+ return store;
118
+ }
119
+ //# sourceMappingURL=ssoUsers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssoUsers.js","sourceRoot":"","sources":["../src/ssoUsers.ts"],"names":[],"mappings":"AA0FA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG;;;;;;;;;;;+EAWkD,CAAC;AAEhF,iGAAiG;AACjG,MAAM,OAAO,GACZ,wFAAwF,CAAC;AAe1F,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,GAAkB,EAAc,EAAE,CAAC,CAAC;IACvE,EAAE,E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,OAAO,8BAA8B,CAAC;iBACtD,GAAG,CAAC,EAAE,CAAyB,CAAC;YAClC,OAAO,GAAG,CAAC,CAAC,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC9C,CAAC;QAED,MAAM,CAAC,GAAG;YACT,yEAAyE;YACzE,8EAA8E;YAC9E,iFAAiF;YACjF,6EAA6E;YAC7E,gFAAgF;YAChF,0BAA0B;YAC1B,EAAE,CAAC,KAAK,CAAC,iEAAiE,CAAC,CAAC,GAAG,CAC9E,GAAG,CAAC,KAAK,EACT,GAAG,CAAC,EAAE,CACN,CAAC;YACF,EAAE,CAAC,KAAK,CACP,0BAA0B,OAAO;;;;;8EAKyC,CAC1E,CAAC,GAAG,CACJ,GAAG,CAAC,EAAE,EACN,GAAG,CAAC,KAAK,EACT,GAAG,CAAC,IAAI,EACR,GAAG,CAAC,QAAQ,EACZ,GAAG,CAAC,QAAQ,EACZ,GAAG,CAAC,UAAU,EACd,GAAG,CAAC,aAAa,EACjB,GAAG,CAAC,UAAU,EACd,GAAG,CAAC,UAAU,CACd,CAAC;QACH,CAAC;QAED,UAAU,CAAC,EAAE;YACZ,EAAE,CAAC,KAAK,CAAC,oCAAoC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACxD,CAAC;QAED,cAAc;YACb,8EAA8E;YAC9E,sEAAsE;YACtE,EAAE,CAAC,IAAI,CAAC;;;;;;;;;KASN,CAAC,CAAC;QACL,CAAC;KACD,CAAC;IACF,OAAO,KAAK,CAAC;AACd,CAAC"}
@@ -0,0 +1,284 @@
1
+ import { type PlaceLookup } from "./clientDescription";
2
+ /**
3
+ * One row of the `sessions` table, as both implementations hand it over.
4
+ *
5
+ * 🔴 Every field is REQUIRED here even though five of the columns were added by `ALTER`
6
+ * to tables that already had rows in them. An implementation normalizes — `""` for a
7
+ * device nobody recorded, `0` for a timestamp that predates the column — so that this
8
+ * file has one shape to read rather than eight optional ones, and so that the two
9
+ * implementations cannot disagree about what "not recorded" looks like. `startOf` below
10
+ * is what turns a `0` back into an honest answer.
11
+ */
12
+ export interface SessionRow {
13
+ id: string;
14
+ user_id: string;
15
+ expires_at: number;
16
+ user_agent: string;
17
+ ip: string;
18
+ created_at: number;
19
+ last_seen_at: number;
20
+ place: string;
21
+ }
22
+ /**
23
+ * The nine operations the session store performs against its table — the whole seam.
24
+ *
25
+ * 🔴 **Expiry is filtered HERE, in SQL, only where the query already did it.** `byId`
26
+ * returns the row whatever its expiry and the caller compares against its own clock;
27
+ * `forUser` takes the cutoff. That is not a style choice: `userIdOf` reads `expires_at`
28
+ * out of the row it fetched and compares it to `now()` *after* the read, and an
29
+ * implementation that filtered early would change what a store built with a fake clock
30
+ * answers. The sameShape spec drives both implementations through the same fake clock
31
+ * for exactly this reason.
32
+ */
33
+ export interface SessionRows {
34
+ /** The row with this id, expired or not. `null` when there is none. */
35
+ byId(id: string): SessionRow | null;
36
+ /**
37
+ * Every row of one user that is still live at `liveAfter`, ordered
38
+ * `last_seen_at DESC, expires_at DESC` — newest activity first.
39
+ *
40
+ * 🔴 The ORDER is part of the contract, not an implementation detail: it is what the
41
+ * owner's session list is sorted by, and two implementations that ordered differently
42
+ * would show the same account two different "most recent device"s.
43
+ */
44
+ forUser(userId: string, liveAfter: number): SessionRow[];
45
+ insert(row: SessionRow): void;
46
+ /** Move `last_seen_at`. Throttled by the caller — see `TOUCH_THROTTLE_MS`. */
47
+ touch(id: string, at: number): void;
48
+ deleteById(id: string): void;
49
+ /**
50
+ * Delete one row only if it belongs to `userId`.
51
+ *
52
+ * Scoped deliberately: a handle is shown on a screen and travels between apps, so a
53
+ * stray, stale or guessed one may only ever end a session of the account it was
54
+ * already listed under.
55
+ */
56
+ deleteByIdForUser(id: string, userId: string): void;
57
+ deleteForUser(userId: string): void;
58
+ deleteOthersForUser(userId: string, keepId: string): void;
59
+ /** Opportunistic sweep: everything whose expiry has passed at `at`. */
60
+ deleteExpired(at: number): void;
61
+ }
62
+ /**
63
+ * The `sessions` table in its FINAL shape — every column, no `ALTER` history.
64
+ *
65
+ * 🔴 Exported because a host with no migration story needs the schema as a statement
66
+ * rather than as a sequence. On `bun:sqlite` the table is still built the way it always
67
+ * was (a three-column `CREATE` plus five `ALTER`s, because every deployed satellite
68
+ * already has rows in it); on D1 the database starts empty and this is what an app puts
69
+ * in its `db/schema.sql`. `sessionRows.sameShape.test.ts` builds the sqlite side the old
70
+ * way and the D1 side from this constant and requires identical answers from both — so
71
+ * this is a schema that has been PROVED equivalent, not one that was transcribed.
72
+ */
73
+ export declare const SESSIONS_DDL = "CREATE TABLE IF NOT EXISTS sessions (\n\tid TEXT PRIMARY KEY,\n\tuser_id TEXT NOT NULL,\n\texpires_at INTEGER NOT NULL,\n\tuser_agent TEXT NOT NULL DEFAULT '',\n\tip TEXT NOT NULL DEFAULT '',\n\tcreated_at INTEGER NOT NULL DEFAULT 0,\n\tlast_seen_at INTEGER NOT NULL DEFAULT 0,\n\tplace TEXT NOT NULL DEFAULT ''\n);\nCREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);";
74
+ /** Everything a store needs that is not the rows. See `userSessions.ts` for the `dbPath` form. */
75
+ export interface UserSessionStoreCoreOptions {
76
+ /** Per-app cookie name, e.g. "hobbies_session" — never shared across apps. */
77
+ cookieName: string;
78
+ sessionSecret: string;
79
+ sessionTtlSeconds: number;
80
+ /**
81
+ * Where an address is, for the `place` stamped on a new session row.
82
+ *
83
+ * 🔴 There is NO default here, and that is the one deliberate behaviour
84
+ * change this module carries out of the previous generation. It used to
85
+ * default to a machine-wide 375MB IP→city snapshot kept outside any repo;
86
+ * this generation has two roots and nothing else, so a library may not
87
+ * reach for a file it did not put there. Unset, the row records whatever
88
+ * the edge headers said (`cf-ipcity` and friends) — which is what every
89
+ * request behind Cloudflare already carries — or nothing.
90
+ *
91
+ * Pass a lookup to restore city-from-address; `null` and unset are the
92
+ * same thing and both are safe in a test.
93
+ */
94
+ placeLookup?: PlaceLookup | null;
95
+ now?: () => number;
96
+ }
97
+ /**
98
+ * One live session, as anything outside this module may see it.
99
+ *
100
+ * Deliberately without the row id — see the header. Times are ms epoch so the
101
+ * shape survives a JSON hop between two satellites without a date parser at
102
+ * each end.
103
+ */
104
+ export interface SessionRecord {
105
+ /** Stable public name for this session: `sha256(id)`, first 24 hex chars.
106
+ * What a revoke-one call names, and the only id that crosses the wire. */
107
+ handle: string;
108
+ userId: string;
109
+ createdAt: number;
110
+ /** Last request this session made, throttled to the minute — see `TOUCH`. */
111
+ lastSeenAt: number;
112
+ expiresAt: number;
113
+ /** The user-agent verbatim, bounded, never parsed here. `""` for a session
114
+ * minted before this column existed, or by a client that sent none. */
115
+ userAgent: string;
116
+ /** Best-effort client address, or `""`. Never used to authorize anything. */
117
+ ip: string;
118
+ /**
119
+ * Where the address was, when the session was created — `"Austin, Texas,
120
+ * US"`, or `""`.
121
+ *
122
+ * Stamped at sign-in and never refreshed, deliberately: the row answers
123
+ * "where was I when I signed in on this thing", and a value that moved with
124
+ * the session's later requests would make an old row disagree with the alert
125
+ * that was mailed about it.
126
+ */
127
+ place: string;
128
+ /** Is this the session the request asking the question is holding? Only ever
129
+ * true when `list` was given that request — "you are on this one" is the
130
+ * difference between signing someone else out and signing yourself out. */
131
+ current: boolean;
132
+ }
133
+ /** Who is signed in at one slot of this browser. */
134
+ export interface SlotOccupant {
135
+ slot: number;
136
+ userId: string;
137
+ }
138
+ /** How a new session differs from the store's defaults. */
139
+ export interface SignInOptions {
140
+ /**
141
+ * Which slot to put it in. Defaults to the slot the request names — which
142
+ * for every existing caller is 0, the bare cookie name.
143
+ */
144
+ slot?: number;
145
+ /**
146
+ * Lifetime for THIS session, overriding the store's default.
147
+ *
148
+ * This is what "remember me" buys, and it is a property of the session
149
+ * rather than of the store because the two answers have to coexist: the
150
+ * owner's own browser keeps a month-long session while a shared machine
151
+ * gets the short default. The row's `expires_at`, the cookie's embedded
152
+ * expiry and the cookie's `Max-Age` are all derived from this one number,
153
+ * so they cannot disagree.
154
+ */
155
+ ttlSeconds?: number;
156
+ }
157
+ /** A minted session and everything the caller needs to install it. */
158
+ export interface SignedIn {
159
+ /** The `Set-Cookie` header value, already slot- and lifetime-correct. */
160
+ cookie: string;
161
+ /** Where it landed — the caller has to tell the browser, via `?authuser=`. */
162
+ slot: number;
163
+ expiresAt: number;
164
+ }
165
+ export interface UserSessionStore {
166
+ /** The cookie name this store was built with (for tests and smokes). */
167
+ cookieName: string;
168
+ /**
169
+ * Mint a session for a user; returns the cookie VALUE.
170
+ *
171
+ * `req` is optional and every caller that has one should pass it: it is what
172
+ * stamps the device and address onto the row, and a session that cannot say
173
+ * where it came from is one the owner cannot recognise on the list. Omitting
174
+ * it is legal (a CLI-minted session, a test) and lands as `""`, never as a
175
+ * guess.
176
+ */
177
+ create(userId: string, req?: Request, options?: SignInOptions): string;
178
+ /**
179
+ * Mint a session AND the `Set-Cookie` that installs it, together.
180
+ *
181
+ * 🔴 Prefer this over `create` + `sessionCookie` for anything slot- or
182
+ * lifetime-aware. Those two are separate calls that each have to be told the
183
+ * same slot and the same TTL, and the failure when they are not told the
184
+ * same thing is silent: a session minted into slot 2 with a cookie written
185
+ * to slot 0 evicts the account the person was already using and signs them
186
+ * in as somebody else in the tab they did not touch.
187
+ */
188
+ signIn(userId: string, req: Request, options?: SignInOptions): SignedIn;
189
+ /** Which slot this request is acting as. Never throws; garbage means 0. */
190
+ slotOf(req: Request): number;
191
+ /**
192
+ * The account id this request's PAGE believes it is acting as, or null when
193
+ * it did not say. Only ever compared against the resolved user — never a
194
+ * credential, never a selector. See {@link ACCOUNT_USER_HEADER}.
195
+ */
196
+ expectedUserOf(req: Request): string | null;
197
+ /** The user id this request's cookie proves, or null. */
198
+ userIdOf(req: Request): string | null;
199
+ /**
200
+ * Every slot of this browser that holds a live session, slot order.
201
+ *
202
+ * This is the account switcher's whole data source, and the reason it can
203
+ * offer a one-click swap with no password: an account with a live session
204
+ * here is one this browser has already proved it may act as.
205
+ */
206
+ signedInSlots(req: Request): SlotOccupant[];
207
+ /**
208
+ * The slot already holding `userId` in this browser, or null.
209
+ *
210
+ * 🔴 Signing in as somebody who is already signed in must REUSE their slot,
211
+ * never take a second one. Otherwise every re-hop of an app that is already
212
+ * open burns a slot, and five visits leave no room for the second account
213
+ * the feature exists to hold.
214
+ */
215
+ slotForUser(req: Request, userId: string): number | null;
216
+ /**
217
+ * Where a NEW account should go: their existing slot, else the lowest empty
218
+ * one, else null when all {@link MAX_ACCOUNT_SLOTS} are taken.
219
+ *
220
+ * Null is a real answer the caller must render, not an error — "sign out of
221
+ * one of these first" is the only honest response, and silently evicting
222
+ * somebody's session to make room is the thing that must not happen.
223
+ */
224
+ slotToAdd(req: Request, userId: string): number | null;
225
+ /** End the session this request carries, in the slot it names. */
226
+ revoke(req: Request): void;
227
+ /**
228
+ * End the session at ONE named slot of this browser; true if there was one.
229
+ *
230
+ * Distinct from `revoke` because the switcher acts on a slot the request is
231
+ * NOT on — "remove that other account" is a button pressed from this tab
232
+ * about a different tab's session.
233
+ */
234
+ revokeAt(req: Request, slot: number): boolean;
235
+ /**
236
+ * End EVERY slot's session in this browser; returns the slots that held one.
237
+ *
238
+ * The shared-machine exit. Distinct from `revokeAllForUser`, which ends one
239
+ * account everywhere, where this ends every account in one place.
240
+ */
241
+ revokeEverySlot(req: Request): number[];
242
+ /** End every session of a user (delete / temp password). */
243
+ revokeAllForUser(userId: string): void;
244
+ /** End every OTHER session of a user (their own password change). */
245
+ revokeOthersForUser(userId: string, req: Request): void;
246
+ /**
247
+ * Every live session of one user, newest first.
248
+ *
249
+ * Expired rows are never returned — the sweep is opportunistic, so the query
250
+ * filters rather than trusting the table to be clean.
251
+ */
252
+ listForUser(userId: string, req?: Request): SessionRecord[];
253
+ /**
254
+ * End ONE session, named by its handle, and say whether it existed.
255
+ *
256
+ * 🔴 The user id is REQUIRED and is part of the match, not a courtesy. A
257
+ * handle is shown on a screen and travels between apps; scoping the delete
258
+ * to the account it was listed under means a stray, stale or guessed handle
259
+ * can only ever end a session of the person it was already about.
260
+ */
261
+ revokeByHandle(userId: string, handle: string): boolean;
262
+ /**
263
+ * `Set-Cookie` for a fresh value, TLS-aware.
264
+ *
265
+ * `Max-Age` is read out of the VALUE's own embedded expiry rather than from
266
+ * the store's default, so a remember-me session's cookie outlives the
267
+ * default the same way its row does. A value that cannot be read falls back
268
+ * to the store default — a cookie slightly too short is a re-login, where
269
+ * one too long is a dead cookie sent on every request forever.
270
+ */
271
+ sessionCookie(value: string, req: Request, slot?: number): string;
272
+ /** `Set-Cookie` that ends the browser's copy, for one slot. */
273
+ clearedCookie(req: Request, slot?: number): string;
274
+ }
275
+ /**
276
+ * The store, over whatever holds the rows.
277
+ *
278
+ * `userSessions.ts` calls this with a `bun:sqlite` implementation and is the entry point
279
+ * six apps use; `cursedauth/d1-stores` provides the snapshot-and-settle implementation a
280
+ * Worker needs. Nothing below this line knows which one it got — which is the property
281
+ * that makes `sessionRows.sameShape.test.ts` meaningful.
282
+ */
283
+ export declare function createUserSessionStoreOver(rows: SessionRows, options: UserSessionStoreCoreOptions): UserSessionStore;
284
+ //# sourceMappingURL=userSessions.core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"userSessions.core.d.ts","sourceRoot":"","sources":["../src/userSessions.core.ts"],"names":[],"mappings":"AAoEA,OAAO,EAKN,KAAK,WAAW,EAChB,MAAM,qBAAqB,CAAC;AAU7B;;;;;;;;;GASG;AACH,MAAM,WAAW,UAAU;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;CACd;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,WAAW;IAC3B,uEAAuE;IACvE,IAAI,CAAC,EAAE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