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.
- package/README.md +20 -2
- package/dist/d1Stores.d.ts +161 -0
- package/dist/d1Stores.d.ts.map +1 -0
- package/dist/d1Stores.js +295 -0
- package/dist/d1Stores.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/offlineGrant.d.ts +127 -0
- package/dist/offlineGrant.d.ts.map +1 -0
- package/dist/offlineGrant.js +104 -0
- package/dist/offlineGrant.js.map +1 -0
- package/dist/ssoConsumer.server.d.ts +19 -3
- package/dist/ssoConsumer.server.d.ts.map +1 -1
- package/dist/ssoConsumer.server.js +58 -66
- package/dist/ssoConsumer.server.js.map +1 -1
- package/dist/ssoUsers.d.ts +122 -0
- package/dist/ssoUsers.d.ts.map +1 -0
- package/dist/ssoUsers.js +119 -0
- package/dist/ssoUsers.js.map +1 -0
- package/dist/userSessions.core.d.ts +284 -0
- package/dist/userSessions.core.d.ts.map +1 -0
- package/dist/userSessions.core.js +389 -0
- package/dist/userSessions.core.js.map +1 -0
- package/dist/userSessions.d.ts +16 -198
- package/dist/userSessions.d.ts.map +1 -1
- package/dist/userSessions.js +77 -355
- package/dist/userSessions.js.map +1 -1
- package/package.json +33 -2
- package/src/d1Stores.ts +444 -0
- package/src/index.ts +20 -0
- package/src/offlineGrant.ts +153 -0
- package/src/ssoConsumer.server.ts +79 -99
- package/src/ssoUsers.ts +243 -0
- package/src/userSessions.core.ts +685 -0
- package/src/userSessions.ts +122 -601
package/src/d1Stores.ts
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `cursedauth` on Cloudflare D1 โ the two stores an app's DOOR needs, snapshot-and-settle.
|
|
3
|
+
*
|
|
4
|
+
* ## ๐ด The problem this solves, stated once
|
|
5
|
+
*
|
|
6
|
+
* `createUserSessionStore` and `createSsoConsumer` are synchronous **by publication**:
|
|
7
|
+
* nineteen members and five statements, every one of them called in the middle of
|
|
8
|
+
* resolving a cookie, by six apps that have not ported. Cloudflare's only database is
|
|
9
|
+
* async. Neither side can move โ making the stores async breaks the six, and `workerd`
|
|
10
|
+
* will never have `bun:sqlite` โ so an app ported to a Worker could serve its catalogue
|
|
11
|
+
* and refuse its own front door. Measured 2026-09-19: `apps/collections` shipped exactly
|
|
12
|
+
* that, a `503` on every `/api/*` naming this gap.
|
|
13
|
+
*
|
|
14
|
+
* The answer, which is the fleet's established one (`tasks/Procedures/move-an-app-to-cloudflare.md`
|
|
15
|
+
* ยง3, and the two working examples in `apps/patterns/worker/stores.ts` and
|
|
16
|
+
* `apps/collections/worker/stores.ts`):
|
|
17
|
+
*
|
|
18
|
+
* 1. before `app.fetch`, ONE D1 read fills an in-memory snapshot;
|
|
19
|
+
* 2. every synchronous call during the request answers from that snapshot;
|
|
20
|
+
* 3. writes are collected as pending promises, and the entry point **awaits them before
|
|
21
|
+
* it returns the response** โ so nothing is acknowledged before it is durable.
|
|
22
|
+
*
|
|
23
|
+
* Two extra queries per invocation, against a 1,000-query budget.
|
|
24
|
+
*
|
|
25
|
+
* ## ๐ด What this must never become: an in-memory store with no read-back
|
|
26
|
+
*
|
|
27
|
+
* A Worker isolate is per-colo and short-lived. A revocation kept only in one isolate's
|
|
28
|
+
* memory means **signing out works until the next request lands somewhere else** โ which
|
|
29
|
+
* reads to the person as the feature being broken rather than absent, and leaves a
|
|
30
|
+
* credential live that a human believes they ended. That is the worst outcome this file
|
|
31
|
+
* has, it is invisible in any single-process test, and `d1Stores.lostWrite.test.ts` is
|
|
32
|
+
* what holds the line: it drives two separate store instances standing for two isolates
|
|
33
|
+
* over one database, and it carries a test of its own failure path โ a collector that
|
|
34
|
+
* DROPS writes, proving the harness can tell a durable store from a memory-only one.
|
|
35
|
+
*
|
|
36
|
+
* ## What is honest about the staleness
|
|
37
|
+
*
|
|
38
|
+
* A write made by request A is not visible to request B until B takes its own snapshot.
|
|
39
|
+
* For a sign-out that is milliseconds. Within ONE invocation a read-after-write is exact,
|
|
40
|
+
* because every mutation below updates the snapshot as well as queueing the statement โ
|
|
41
|
+
* the property `bun:sqlite` has for free and whose absence would make `revoke()` followed
|
|
42
|
+
* by a session check disagree with itself inside one request.
|
|
43
|
+
*
|
|
44
|
+
* ## Where the SCHEMA comes from
|
|
45
|
+
*
|
|
46
|
+
* D1 has no migration story inside a request and DDL per invocation would spend the query
|
|
47
|
+
* budget on statements that can only ever matter once. So `ensureSchema()` here is a
|
|
48
|
+
* documented no-op and the tables come from the app's `db/schema.sql`, applied by
|
|
49
|
+
* `wrangler d1 execute --file db/schema.sql`. Paste {@link SESSIONS_DDL} and
|
|
50
|
+
* {@link SSO_USERS_DDL} into it โ both are exported for that purpose and both are driven
|
|
51
|
+
* by the sameShape specs, so they are schemas that have been PROVED to answer identically
|
|
52
|
+
* to the `bun:sqlite` ones rather than transcribed by hand. A missing table is not silent:
|
|
53
|
+
* the snapshot read below is the first thing that happens and D1 fails it by name.
|
|
54
|
+
*/
|
|
55
|
+
import {
|
|
56
|
+
normalizeSsoUserRow,
|
|
57
|
+
type RawSsoUserRow,
|
|
58
|
+
type SsoUserRow,
|
|
59
|
+
type SsoUserStore,
|
|
60
|
+
} from "./ssoUsers";
|
|
61
|
+
import type { SessionRow, SessionRows } from "./userSessions.core";
|
|
62
|
+
|
|
63
|
+
export { SESSIONS_DDL } from "./userSessions.core";
|
|
64
|
+
export { SSO_USERS_DDL } from "./ssoUsers";
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The slice of a D1 handle these stores use.
|
|
68
|
+
*
|
|
69
|
+
* ๐ด Declared HERE rather than imported from `cursedbelt-server/d1`, deliberately. This
|
|
70
|
+
* package sits UNDER that one โ every app installs `cursedauth` and not all of them
|
|
71
|
+
* install the belt โ so a type-only import would put a required peer on a package that
|
|
72
|
+
* needs nothing else from it, and would couple two independently-published majors in one
|
|
73
|
+
* `node_modules`. It is structural: `cursedbelt-server/d1`'s `D1LikeDatabase` and
|
|
74
|
+
* Cloudflare's own `D1Database` both satisfy it as they are, and
|
|
75
|
+
* `d1Stores.handleShape.test.ts` asserts the first of those at compile time so that a
|
|
76
|
+
* change on the other side of the seam is a red here rather than a surprise in somebody's
|
|
77
|
+
* `wrangler deploy`.
|
|
78
|
+
*/
|
|
79
|
+
export interface D1HandleStatement {
|
|
80
|
+
bind(...values: (string | number | null)[]): D1HandleStatement;
|
|
81
|
+
all<T>(): Promise<{ results: T[] }>;
|
|
82
|
+
run(): Promise<unknown>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface D1Handle {
|
|
86
|
+
prepare(sql: string): D1HandleStatement;
|
|
87
|
+
/**
|
|
88
|
+
* Several statements, atomically, in ORDER, as one round trip.
|
|
89
|
+
*
|
|
90
|
+
* ๐ด Required rather than convenient. {@link WriteCollector} fires what it is given
|
|
91
|
+
* immediately and awaits the set at the end, so two separately-collected statements
|
|
92
|
+
* race โ and `upsert` below is a DELETE that MUST land before its INSERT or the
|
|
93
|
+
* unique index on `lower(email)` refuses a legitimate sign-in. Ordering that matters
|
|
94
|
+
* goes in one `batch`, never in two `add`s.
|
|
95
|
+
*/
|
|
96
|
+
batch(statements: D1HandleStatement[]): Promise<unknown>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Where a durable write goes on its way out.
|
|
101
|
+
*
|
|
102
|
+
* Two members is deliberately fewer than the `PendingWrites` interface `apps/patterns` and
|
|
103
|
+
* `apps/collections` already carry โ this needs only `add`, so both of those objects
|
|
104
|
+
* satisfy it verbatim and neither app has to change anything to adopt these stores.
|
|
105
|
+
*/
|
|
106
|
+
export interface WriteCollector {
|
|
107
|
+
add(promise: Promise<unknown>): void;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A write that must land before the response is returned. See the header. */
|
|
111
|
+
export interface PendingWrites extends WriteCollector {
|
|
112
|
+
/** Await every collected write. Called BEFORE the response is returned, never after. */
|
|
113
|
+
settle(): Promise<void>;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function createPendingWrites(): PendingWrites {
|
|
117
|
+
const pending: Promise<unknown>[] = [];
|
|
118
|
+
return {
|
|
119
|
+
add: (promise) => void pending.push(promise),
|
|
120
|
+
async settle() {
|
|
121
|
+
// `all`, not `allSettled`: a failed durable write must not be reported as a
|
|
122
|
+
// success. It surfaces as a 500 from the entry point, which is the honest answer
|
|
123
|
+
// to "did my sign-out take".
|
|
124
|
+
await Promise.all(pending);
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* How many rows either snapshot may hold before this refuses to take one.
|
|
131
|
+
*
|
|
132
|
+
* ๐ด It REFUSES rather than truncating, and the difference is the whole point. A silently
|
|
133
|
+
* truncated snapshot of a credential table answers "no such session" for everybody past
|
|
134
|
+
* the cut โ so signing in appears to work, the cookie is real, and every subsequent
|
|
135
|
+
* request is anonymous. A throw is a 500 naming the table and the number, which somebody
|
|
136
|
+
* can act on.
|
|
137
|
+
*
|
|
138
|
+
* The default suits a household: `sessions` is bounded by people ร devices and swept on
|
|
139
|
+
* every write, `sso_users` by how many accounts have ever signed in here. An app with
|
|
140
|
+
* thousands of principals must move these reads into SQL โ a per-request snapshot keyed on
|
|
141
|
+
* the cookie the request actually carries โ rather than raising this number.
|
|
142
|
+
*/
|
|
143
|
+
export const SNAPSHOT_MAX_ROWS = 5_000;
|
|
144
|
+
|
|
145
|
+
export class D1SnapshotTooLargeError extends RangeError {
|
|
146
|
+
readonly table: string;
|
|
147
|
+
constructor(table: string, max: number) {
|
|
148
|
+
super(
|
|
149
|
+
`cursedauth's D1 ${table} snapshot would exceed ${max} rows. These stores read the ` +
|
|
150
|
+
`live table once per invocation and serve the request from it, which is only honest ` +
|
|
151
|
+
`while the table is small. Do NOT raise the limit: move this read into SQL, keyed on ` +
|
|
152
|
+
`the session the request actually carries.`,
|
|
153
|
+
);
|
|
154
|
+
this.name = "D1SnapshotTooLargeError";
|
|
155
|
+
this.table = table;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** One read, bounded, that refuses rather than truncates. */
|
|
160
|
+
async function snapshot<T>(
|
|
161
|
+
db: D1Handle,
|
|
162
|
+
table: string,
|
|
163
|
+
sql: string,
|
|
164
|
+
binds: (string | number | null)[],
|
|
165
|
+
max: number,
|
|
166
|
+
): Promise<T[]> {
|
|
167
|
+
// `max + 1` is what turns "we got exactly the limit" from ambiguous into decisive: a
|
|
168
|
+
// full page could mean a full table or a cut one, and one extra row says which.
|
|
169
|
+
const rows = (await db.prepare(`${sql} LIMIT ?`).bind(...binds, max + 1).all<T>()).results;
|
|
170
|
+
if (rows.length > max) throw new D1SnapshotTooLargeError(table, max);
|
|
171
|
+
return rows;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const SESSION_COLUMNS = "id, user_id, expires_at, user_agent, ip, created_at, last_seen_at, place";
|
|
175
|
+
|
|
176
|
+
interface RawSessionRow {
|
|
177
|
+
id: string;
|
|
178
|
+
user_id: string;
|
|
179
|
+
expires_at: number;
|
|
180
|
+
user_agent: string | null;
|
|
181
|
+
ip: string | null;
|
|
182
|
+
created_at: number | null;
|
|
183
|
+
last_seen_at: number | null;
|
|
184
|
+
place: string | null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The same fail-closed normalization the `bun:sqlite` implementation performs. */
|
|
188
|
+
const normalizeSessionRow = (row: RawSessionRow): SessionRow => ({
|
|
189
|
+
id: row.id,
|
|
190
|
+
user_id: row.user_id,
|
|
191
|
+
expires_at: row.expires_at,
|
|
192
|
+
user_agent: row.user_agent ?? "",
|
|
193
|
+
ip: row.ip ?? "",
|
|
194
|
+
created_at: row.created_at ?? 0,
|
|
195
|
+
last_seen_at: row.last_seen_at ?? 0,
|
|
196
|
+
place: row.place ?? "",
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
export interface D1StoreOptions {
|
|
200
|
+
/** The invocation's clock, in ms. One value for the whole request. */
|
|
201
|
+
now: number;
|
|
202
|
+
/** Override {@link SNAPSHOT_MAX_ROWS} โ lower it in a test that proves the refusal. */
|
|
203
|
+
maxRows?: number;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* The `sessions` table for one invocation. Hand the result to
|
|
208
|
+
* `createUserSessionStoreOver` from `cursedauth/user-sessions-core`.
|
|
209
|
+
*
|
|
210
|
+
* ## ๐ด What the snapshot is, and what it deliberately is not
|
|
211
|
+
*
|
|
212
|
+
* It is every row that is still LIVE at `now` โ not the whole table. Expired rows are
|
|
213
|
+
* excluded because every reader discards them anyway (`byId`'s call sites re-check
|
|
214
|
+
* `expires_at > now()`; `forUser` takes the cutoff), and because including them would let
|
|
215
|
+
* a table nobody has swept push a working app past {@link SNAPSHOT_MAX_ROWS}. The one way
|
|
216
|
+
* the two implementations could then disagree is a clock that runs BACKWARDS inside a
|
|
217
|
+
* single invocation, which `options.now` makes possible in a test and nothing makes
|
|
218
|
+
* possible in production โ which is why the sameShape spec drives both sides from one
|
|
219
|
+
* non-decreasing fake clock rather than pretending the question does not exist.
|
|
220
|
+
*
|
|
221
|
+
* The store sweeps on every write, so the live set is also very nearly the whole table.
|
|
222
|
+
*/
|
|
223
|
+
export async function createD1SessionRows(
|
|
224
|
+
db: D1Handle,
|
|
225
|
+
writes: WriteCollector,
|
|
226
|
+
options: D1StoreOptions,
|
|
227
|
+
): Promise<SessionRows> {
|
|
228
|
+
const max = options.maxRows ?? SNAPSHOT_MAX_ROWS;
|
|
229
|
+
const rows = await snapshot<RawSessionRow>(
|
|
230
|
+
db,
|
|
231
|
+
"sessions",
|
|
232
|
+
`SELECT ${SESSION_COLUMNS} FROM sessions WHERE expires_at > ?`,
|
|
233
|
+
[options.now],
|
|
234
|
+
max,
|
|
235
|
+
);
|
|
236
|
+
const live = new Map<string, SessionRow>();
|
|
237
|
+
for (const row of rows) live.set(row.id, normalizeSessionRow(row));
|
|
238
|
+
|
|
239
|
+
return {
|
|
240
|
+
byId: (id) => live.get(id) ?? null,
|
|
241
|
+
|
|
242
|
+
forUser: (userId, liveAfter) =>
|
|
243
|
+
[...live.values()]
|
|
244
|
+
.filter((row) => row.user_id === userId && row.expires_at > liveAfter)
|
|
245
|
+
// The ORDER is part of the seam's contract โ `SessionRows.forUser` says why.
|
|
246
|
+
// `bun:sqlite` gets it from `ORDER BY last_seen_at DESC, expires_at DESC`;
|
|
247
|
+
// here it is the same two keys, same direction, applied to the snapshot.
|
|
248
|
+
.sort((a, b) => b.last_seen_at - a.last_seen_at || b.expires_at - a.expires_at),
|
|
249
|
+
|
|
250
|
+
insert(row) {
|
|
251
|
+
live.set(row.id, row);
|
|
252
|
+
writes.add(
|
|
253
|
+
db
|
|
254
|
+
.prepare(`INSERT INTO sessions (${SESSION_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
255
|
+
.bind(
|
|
256
|
+
row.id,
|
|
257
|
+
row.user_id,
|
|
258
|
+
row.expires_at,
|
|
259
|
+
row.user_agent,
|
|
260
|
+
row.ip,
|
|
261
|
+
row.created_at,
|
|
262
|
+
row.last_seen_at,
|
|
263
|
+
row.place,
|
|
264
|
+
)
|
|
265
|
+
.run(),
|
|
266
|
+
);
|
|
267
|
+
},
|
|
268
|
+
|
|
269
|
+
touch(id, at) {
|
|
270
|
+
const row = live.get(id);
|
|
271
|
+
if (row) live.set(id, { ...row, last_seen_at: at });
|
|
272
|
+
writes.add(db.prepare("UPDATE sessions SET last_seen_at = ? WHERE id = ?").bind(at, id).run());
|
|
273
|
+
},
|
|
274
|
+
|
|
275
|
+
deleteById(id) {
|
|
276
|
+
live.delete(id);
|
|
277
|
+
writes.add(db.prepare("DELETE FROM sessions WHERE id = ?").bind(id).run());
|
|
278
|
+
},
|
|
279
|
+
|
|
280
|
+
deleteByIdForUser(id, userId) {
|
|
281
|
+
// Scoped in the snapshot exactly as it is scoped in SQL: a handle that names
|
|
282
|
+
// somebody else's session must delete nothing on either side.
|
|
283
|
+
if (live.get(id)?.user_id === userId) live.delete(id);
|
|
284
|
+
writes.add(
|
|
285
|
+
db.prepare("DELETE FROM sessions WHERE id = ? AND user_id = ?").bind(id, userId).run(),
|
|
286
|
+
);
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
deleteForUser(userId) {
|
|
290
|
+
for (const [id, row] of live) if (row.user_id === userId) live.delete(id);
|
|
291
|
+
writes.add(db.prepare("DELETE FROM sessions WHERE user_id = ?").bind(userId).run());
|
|
292
|
+
},
|
|
293
|
+
|
|
294
|
+
deleteOthersForUser(userId, keepId) {
|
|
295
|
+
for (const [id, row] of live) if (row.user_id === userId && id !== keepId) live.delete(id);
|
|
296
|
+
writes.add(
|
|
297
|
+
db
|
|
298
|
+
.prepare("DELETE FROM sessions WHERE user_id = ? AND id != ?")
|
|
299
|
+
.bind(userId, keepId)
|
|
300
|
+
.run(),
|
|
301
|
+
);
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
deleteExpired(at) {
|
|
305
|
+
for (const [id, row] of live) if (row.expires_at <= at) live.delete(id);
|
|
306
|
+
writes.add(db.prepare("DELETE FROM sessions WHERE expires_at <= ?").bind(at).run());
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const SSO_USER_COLUMNS =
|
|
312
|
+
"id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at";
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* The `sso_users` snapshot for one invocation. Pass the result as `users` to
|
|
316
|
+
* `createSsoConsumer`.
|
|
317
|
+
*
|
|
318
|
+
* The whole table, because it IS the household: one row per account that has ever signed
|
|
319
|
+
* in to this app. The consumer reads it by id for the request's own user and once per
|
|
320
|
+
* occupied account slot, so a snapshot costs one query where per-key reads would cost one
|
|
321
|
+
* per slot โ up to `MAX_ACCOUNT_SLOTS` of them on the account switcher's own route.
|
|
322
|
+
*/
|
|
323
|
+
export async function createD1SsoUserStore(
|
|
324
|
+
db: D1Handle,
|
|
325
|
+
writes: WriteCollector,
|
|
326
|
+
options: D1StoreOptions,
|
|
327
|
+
): Promise<SsoUserStore> {
|
|
328
|
+
const max = options.maxRows ?? SNAPSHOT_MAX_ROWS;
|
|
329
|
+
const rows = await snapshot<RawSsoUserRow>(
|
|
330
|
+
db,
|
|
331
|
+
"sso_users",
|
|
332
|
+
`SELECT ${SSO_USER_COLUMNS} FROM sso_users`,
|
|
333
|
+
[],
|
|
334
|
+
max,
|
|
335
|
+
);
|
|
336
|
+
const users = new Map<string, SsoUserRow>();
|
|
337
|
+
for (const row of rows) users.set(row.id, normalizeSsoUserRow(row));
|
|
338
|
+
|
|
339
|
+
const sameAddress = (a: string, b: string): boolean => a.toLowerCase() === b.toLowerCase();
|
|
340
|
+
|
|
341
|
+
return {
|
|
342
|
+
ensureSchema() {
|
|
343
|
+
// ๐ด Deliberately nothing. D1's schema is applied out of band by
|
|
344
|
+
// `wrangler d1 execute --file db/schema.sql` โ paste `SSO_USERS_DDL` into it โ
|
|
345
|
+
// and a per-invocation `CREATE TABLE IF NOT EXISTS` would spend the request's
|
|
346
|
+
// query budget on DDL that can only ever matter once. It is not a silent
|
|
347
|
+
// no-op: the snapshot above runs BEFORE any of this and D1 fails it by name if
|
|
348
|
+
// the table is absent, so a forgotten migration is a loud 500 on the first
|
|
349
|
+
// request rather than a door that refuses everybody.
|
|
350
|
+
},
|
|
351
|
+
|
|
352
|
+
byId: (id) => users.get(id) ?? null,
|
|
353
|
+
|
|
354
|
+
upsert(row) {
|
|
355
|
+
// The snapshot first, so the rest of THIS invocation sees the account it just
|
|
356
|
+
// wrote โ the callback mints a session and reads the user back within one
|
|
357
|
+
// request.
|
|
358
|
+
for (const [id, existing] of users) {
|
|
359
|
+
if (id !== row.id && sameAddress(existing.email, row.email)) users.delete(id);
|
|
360
|
+
}
|
|
361
|
+
const previous = users.get(row.id);
|
|
362
|
+
users.set(row.id, {
|
|
363
|
+
...row,
|
|
364
|
+
// `created_at` belongs to the row's first write. The SQL below says the same
|
|
365
|
+
// thing by leaving it out of the `DO UPDATE SET` list; saying it here too is
|
|
366
|
+
// what keeps the snapshot from disagreeing with what was durably stored.
|
|
367
|
+
created_at: previous?.created_at ?? row.created_at,
|
|
368
|
+
});
|
|
369
|
+
// ๐ด ONE batch, not two `add`s. The DELETE must land before the INSERT or the
|
|
370
|
+
// unique index on `lower(email)` refuses a legitimate re-issued account id โ
|
|
371
|
+
// and a collector fires what it is given immediately, so two adds race. See
|
|
372
|
+
// `D1Handle.batch`.
|
|
373
|
+
writes.add(
|
|
374
|
+
db.batch([
|
|
375
|
+
db
|
|
376
|
+
.prepare("DELETE FROM sso_users WHERE lower(email) = lower(?) AND id <> ?")
|
|
377
|
+
.bind(row.email, row.id),
|
|
378
|
+
db
|
|
379
|
+
.prepare(
|
|
380
|
+
`INSERT INTO sso_users (${SSO_USER_COLUMNS})
|
|
381
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
382
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
383
|
+
email = excluded.email, name = excluded.name, is_admin = excluded.is_admin,
|
|
384
|
+
is_owner = excluded.is_owner, is_granted = excluded.is_granted,
|
|
385
|
+
last_login_at = excluded.last_login_at, updated_at = excluded.updated_at`,
|
|
386
|
+
)
|
|
387
|
+
.bind(
|
|
388
|
+
row.id,
|
|
389
|
+
row.email,
|
|
390
|
+
row.name,
|
|
391
|
+
row.is_admin,
|
|
392
|
+
row.is_owner,
|
|
393
|
+
row.is_granted,
|
|
394
|
+
row.last_login_at,
|
|
395
|
+
row.created_at,
|
|
396
|
+
row.updated_at,
|
|
397
|
+
),
|
|
398
|
+
]),
|
|
399
|
+
);
|
|
400
|
+
},
|
|
401
|
+
|
|
402
|
+
deleteById(id) {
|
|
403
|
+
users.delete(id);
|
|
404
|
+
writes.add(db.prepare("DELETE FROM sso_users WHERE id = ?").bind(id).run());
|
|
405
|
+
},
|
|
406
|
+
|
|
407
|
+
dropDuplicates() {
|
|
408
|
+
// Unreachable from `ensureSchema` here โ a database that starts behind the unique
|
|
409
|
+
// index cannot grow a duplicate โ but implemented rather than thrown, because a
|
|
410
|
+
// one-off import script that copies a Mac's table into D1 CAN, and a member that
|
|
411
|
+
// silently did nothing would be a repair somebody believed had run.
|
|
412
|
+
const keep = new Map<string, SsoUserRow>();
|
|
413
|
+
for (const row of users.values()) {
|
|
414
|
+
const key = row.email.toLowerCase();
|
|
415
|
+
const winner = keep.get(key);
|
|
416
|
+
if (
|
|
417
|
+
!winner ||
|
|
418
|
+
row.last_login_at > winner.last_login_at ||
|
|
419
|
+
(row.last_login_at === winner.last_login_at && row.updated_at > winner.updated_at)
|
|
420
|
+
) {
|
|
421
|
+
keep.set(key, row);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const survivors = new Set([...keep.values()].map((row) => row.id));
|
|
425
|
+
for (const id of [...users.keys()]) if (!survivors.has(id)) users.delete(id);
|
|
426
|
+
writes.add(
|
|
427
|
+
db
|
|
428
|
+
.prepare(
|
|
429
|
+
`DELETE FROM sso_users WHERE rowid NOT IN (
|
|
430
|
+
SELECT rowid FROM (
|
|
431
|
+
SELECT rowid,
|
|
432
|
+
ROW_NUMBER() OVER (
|
|
433
|
+
PARTITION BY lower(email)
|
|
434
|
+
ORDER BY last_login_at DESC, updated_at DESC, rowid DESC
|
|
435
|
+
) AS rn
|
|
436
|
+
FROM sso_users
|
|
437
|
+
) WHERE rn = 1
|
|
438
|
+
)`,
|
|
439
|
+
)
|
|
440
|
+
.run(),
|
|
441
|
+
);
|
|
442
|
+
},
|
|
443
|
+
};
|
|
444
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -32,14 +32,34 @@ export {
|
|
|
32
32
|
type SsoUser,
|
|
33
33
|
} from "./ssoConsumer.server";
|
|
34
34
|
export {
|
|
35
|
+
createSqliteSessionRows,
|
|
35
36
|
createUserSessionStore,
|
|
37
|
+
createUserSessionStoreOver,
|
|
38
|
+
SESSIONS_DDL,
|
|
36
39
|
type SessionRecord,
|
|
40
|
+
type SessionRow,
|
|
41
|
+
type SessionRows,
|
|
37
42
|
type SignedIn,
|
|
38
43
|
type SignInOptions,
|
|
39
44
|
type SlotOccupant,
|
|
40
45
|
type UserSessionStore,
|
|
46
|
+
type UserSessionStoreCoreOptions,
|
|
41
47
|
type UserSessionStoreOptions,
|
|
42
48
|
} from "./userSessions";
|
|
49
|
+
/*
|
|
50
|
+
* The `sso_users` seam. ๐ด `cursedauth/d1-stores` is deliberately NOT re-exported from
|
|
51
|
+
* this barrel: it has no reason to be here (a Worker cannot import this file at all โ
|
|
52
|
+
* the barrel reaches `bun:sqlite` through `./userSessions`), and re-exporting it would
|
|
53
|
+
* put a second, Bun-only route to a Worker-only module in front of every reader.
|
|
54
|
+
*/
|
|
55
|
+
export {
|
|
56
|
+
createSqliteSsoUserStore,
|
|
57
|
+
normalizeSsoUserRow,
|
|
58
|
+
type RawSsoUserRow,
|
|
59
|
+
SSO_USERS_DDL,
|
|
60
|
+
type SsoUserRow,
|
|
61
|
+
type SsoUserStore,
|
|
62
|
+
} from "./ssoUsers";
|
|
43
63
|
export {
|
|
44
64
|
DEFAULT_GATE_PATH,
|
|
45
65
|
type GatedMountPlan,
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The offline validity window โ the bounded answer to "a disabled account cannot
|
|
3
|
+
* be revoked on a device that is offline".
|
|
4
|
+
*
|
|
5
|
+
* Cached bytes cannot be revoked and auth's revocation ticket cannot reach an
|
|
6
|
+
* offline device, so we do NOT pretend a disable is instantaneous. Instead every
|
|
7
|
+
* successful ONLINE session verification stamps a grant; offline use is allowed
|
|
8
|
+
* only while that stamp is recent. A reconnect re-verifies and either refreshes
|
|
9
|
+
* the stamp (still valid) or drops the grant and purges the cache (revoked).
|
|
10
|
+
*
|
|
11
|
+
* This module is pure: it never touches storage, `Date` or the network โ the
|
|
12
|
+
* caller passes `now` and the persisted grant. That is what makes the window a
|
|
13
|
+
* unit-testable decision rather than a scattering of `Date.now()` comparisons.
|
|
14
|
+
* It imports nothing, so it is a leaf on both sides of the wire.
|
|
15
|
+
*
|
|
16
|
+
* ## ๐ด This is NOT the SSO grant
|
|
17
|
+
*
|
|
18
|
+
* `cursedauth/sso` publishes *the grant*: a signed, single-use credential the
|
|
19
|
+
* accounts service mints, which authorizes a sign-in. An {@link OfflineGrant} is
|
|
20
|
+
* the opposite kind of object โ a local stamp that authorizes nothing and is
|
|
21
|
+
* never sent anywhere. Same word, two meanings, and the distinction is the whole
|
|
22
|
+
* safety argument below, so the two live on separate subpaths and never import
|
|
23
|
+
* each other.
|
|
24
|
+
*
|
|
25
|
+
* ## Where it came from
|
|
26
|
+
*
|
|
27
|
+
* Built, tested and justified in `roms` as `src/offline/validity.ts`, which is
|
|
28
|
+
* still where the trade-off is written down: `apps/roms/docs/offline.md`
|
|
29
|
+
* ยง"Constraint 2 โ offline play vs. account disable: a bounded window". Lifted
|
|
30
|
+
* here on 2026-09-17 because the window is a property of a *session*, the
|
|
31
|
+
* revocation argument is auth's, and `music` was named as the second app that
|
|
32
|
+
* wants it โ one app's `src/offline/` is unreachable from every other app.
|
|
33
|
+
*
|
|
34
|
+
* The shell/service-worker/cache half of `roms`' offline work deliberately did
|
|
35
|
+
* NOT come with it: `swRouting`, the outbox and quota relief are shaped around
|
|
36
|
+
* ROM bytes and save states, and whether they generalise is a question to answer
|
|
37
|
+
* with a second consumer in hand.
|
|
38
|
+
*
|
|
39
|
+
* One rename on the way over, and nothing else: `isOfflinePlayAllowed` is
|
|
40
|
+
* {@link isOfflineGrantValid} here, because a library that knows nothing about
|
|
41
|
+
* games should not decide whether "play" is allowed. Every other name, every
|
|
42
|
+
* default and every spec is the one `roms` reasoned about.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The maximum time a device may use cached content while offline, measured from
|
|
47
|
+
* the last successful online session check. Seven days: long enough for a normal
|
|
48
|
+
* trip, short enough that a revoked account cannot indefinitely retain access by
|
|
49
|
+
* never reconnecting. See the trade-off write-up in `apps/roms/docs/offline.md`.
|
|
50
|
+
*
|
|
51
|
+
* ๐ด **A consumer may pass a SHORTER `maxWindowMs`, never a longer one by
|
|
52
|
+
* default.** This number *is* the revocation argument: the exposure a disabled
|
|
53
|
+
* account keeps is exactly this window, and it was justified against cached game
|
|
54
|
+
* bytes on a device that may never reconnect. Raising the shared default would
|
|
55
|
+
* widen every app's exposure at once, on no app's reasoning.
|
|
56
|
+
*/
|
|
57
|
+
export const OFFLINE_MAX_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Proof, stamped at the last successful ONLINE session verification, that this
|
|
61
|
+
* device was a valid session for `accountId` at `lastVerifiedAt`. Persisted
|
|
62
|
+
* locally (e.g. localStorage). It is not a credential โ it grants nothing on its
|
|
63
|
+
* own; it only bounds how long already-cached bytes may be replayed offline.
|
|
64
|
+
*/
|
|
65
|
+
export interface OfflineGrant {
|
|
66
|
+
accountId: string;
|
|
67
|
+
/** Epoch ms of the last successful online session check. */
|
|
68
|
+
lastVerifiedAt: number;
|
|
69
|
+
/**
|
|
70
|
+
* The account's email, purely so a cold OFFLINE load can put a name in the
|
|
71
|
+
* header instead of a uuid (`apps/roms/src/offlineAuth.ts` is the app that
|
|
72
|
+
* does exactly this). Optional: grants written before 2026-08-05 have none,
|
|
73
|
+
* and nothing may depend on it โ it is a label, never a credential and never
|
|
74
|
+
* an identity check.
|
|
75
|
+
*/
|
|
76
|
+
email?: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type OfflineValidity =
|
|
80
|
+
/** No grant on this device โ it never signed in. Offline use is refused. */
|
|
81
|
+
| { state: "no-grant" }
|
|
82
|
+
/** Within the window โ offline use allowed. */
|
|
83
|
+
| { state: "valid"; remainingMs: number }
|
|
84
|
+
/** The window has lapsed โ offline use refused until a reconnect re-checks. */
|
|
85
|
+
| { state: "expired"; expiredForMs: number };
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* How much of the offline window is left, clamped to zero. Negative inputs
|
|
89
|
+
* (a grant stamped in the "future" by a skewed clock) are treated as fully spent
|
|
90
|
+
* rather than trusted, so clock games cannot extend the window.
|
|
91
|
+
*/
|
|
92
|
+
export function offlineWindowRemainingMs(
|
|
93
|
+
grant: OfflineGrant,
|
|
94
|
+
now: number,
|
|
95
|
+
maxWindowMs: number = OFFLINE_MAX_WINDOW_MS,
|
|
96
|
+
): number {
|
|
97
|
+
const elapsed = now - grant.lastVerifiedAt;
|
|
98
|
+
if (elapsed < 0) return 0; // future-stamped grant: don't trust it
|
|
99
|
+
return Math.max(0, maxWindowMs - elapsed);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The full validity verdict for a (possibly absent) grant at time `now`. */
|
|
103
|
+
export function offlineValidity(
|
|
104
|
+
grant: OfflineGrant | null | undefined,
|
|
105
|
+
now: number,
|
|
106
|
+
maxWindowMs: number = OFFLINE_MAX_WINDOW_MS,
|
|
107
|
+
): OfflineValidity {
|
|
108
|
+
if (!grant) return { state: "no-grant" };
|
|
109
|
+
const remainingMs = offlineWindowRemainingMs(grant, now, maxWindowMs);
|
|
110
|
+
if (remainingMs > 0) return { state: "valid", remainingMs };
|
|
111
|
+
const elapsed = now - grant.lastVerifiedAt;
|
|
112
|
+
return { state: "expired", expiredForMs: Math.max(0, elapsed - maxWindowMs) };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Convenience: is offline use permitted on the strength of this grant right now?
|
|
117
|
+
*
|
|
118
|
+
* (`roms` calls this `isOfflinePlayAllowed`; it is the same predicate.)
|
|
119
|
+
*/
|
|
120
|
+
export function isOfflineGrantValid(
|
|
121
|
+
grant: OfflineGrant | null | undefined,
|
|
122
|
+
now: number,
|
|
123
|
+
maxWindowMs: number = OFFLINE_MAX_WINDOW_MS,
|
|
124
|
+
): boolean {
|
|
125
|
+
return offlineValidity(grant, now, maxWindowMs).state === "valid";
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The outcome of an online reconnect check. `revoked` means auth reported the
|
|
130
|
+
* account disabled or the session no longer valid; `verified` means it is still
|
|
131
|
+
* this account and still valid.
|
|
132
|
+
*/
|
|
133
|
+
export type ReconnectCheck = { verified: true; accountId: string; at: number } | { revoked: true };
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Fold a fresh online check into the stored grant โ the stamp-on-successful-
|
|
137
|
+
* verification hook, and the only way a grant is ever created or refreshed.
|
|
138
|
+
*
|
|
139
|
+
* - verified โ a refreshed grant stamped `at` (the window resets).
|
|
140
|
+
* - revoked, OR verified as a DIFFERENT account than the one that cached the
|
|
141
|
+
* bytes โ `null`. The caller MUST then purge its content cache: a null grant is
|
|
142
|
+
* the signal that whatever is cached must no longer be usable.
|
|
143
|
+
*/
|
|
144
|
+
export function reconcileGrant(
|
|
145
|
+
previous: OfflineGrant | null | undefined,
|
|
146
|
+
check: ReconnectCheck,
|
|
147
|
+
): OfflineGrant | null {
|
|
148
|
+
if ("revoked" in check) return null;
|
|
149
|
+
// A device that comes back as a different account must not inherit the prior
|
|
150
|
+
// account's offline window over the prior account's cached library.
|
|
151
|
+
if (previous && previous.accountId !== check.accountId) return null;
|
|
152
|
+
return { accountId: check.accountId, lastVerifiedAt: check.at };
|
|
153
|
+
}
|