cursedauth 0.7.0 → 0.9.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 +4 -1
- package/dist/d1Stores.d.ts +172 -0
- package/dist/d1Stores.d.ts.map +1 -0
- package/dist/d1Stores.js +306 -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/ssoConsumer.server.d.ts +40 -4
- package/dist/ssoConsumer.server.d.ts.map +1 -1
- package/dist/ssoConsumer.server.js +107 -70
- 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 +20 -1
- package/src/d1Stores.ts +455 -0
- package/src/index.ts +20 -0
- package/src/ssoConsumer.server.ts +128 -101
- package/src/ssoUsers.ts +243 -0
- package/src/userSessions.core.ts +685 -0
- package/src/userSessions.ts +122 -601
|
@@ -34,6 +34,7 @@ import type { Context, Hono, MiddlewareHandler, Next } from "hono";
|
|
|
34
34
|
import { stageIdentityIsLocal } from "./stageIdentity";
|
|
35
35
|
import { SESSION_CLAIMS_KEY, type SessionClaims } from "./auth.server";
|
|
36
36
|
import { isSecureRequest } from "./secureRequest";
|
|
37
|
+
import { createSqliteSsoUserStore, type SsoUserRow, type SsoUserStore } from "./ssoUsers";
|
|
37
38
|
import {
|
|
38
39
|
CENSUS_MAX_SUBJECTS,
|
|
39
40
|
type ContentCensus,
|
|
@@ -293,9 +294,24 @@ export interface SsoConsumerOptions {
|
|
|
293
294
|
* a credential gets redirected. */
|
|
294
295
|
publicUrl: string;
|
|
295
296
|
sessions: UserSessionStore;
|
|
296
|
-
/**
|
|
297
|
-
*
|
|
298
|
-
|
|
297
|
+
/**
|
|
298
|
+
* The app's own database — the `sso_users` snapshot lives here so app
|
|
299
|
+
* tables can foreign-key the user id.
|
|
300
|
+
*
|
|
301
|
+
* 🔴 Optional since 0.8.0, and still what every Bun-hosted app passes. Give
|
|
302
|
+
* {@link users} instead on a host with no synchronous database; exactly one of the
|
|
303
|
+
* two is required and passing neither throws at construction rather than at the
|
|
304
|
+
* first request. See `ssoUsers.ts` for why the seam is at the rows.
|
|
305
|
+
*/
|
|
306
|
+
db?: Database;
|
|
307
|
+
/**
|
|
308
|
+
* The `sso_users` snapshot behind a seam, for a host that is not Bun.
|
|
309
|
+
*
|
|
310
|
+
* `cursedauth/d1-stores`' `createD1SsoUserStore` is the Cloudflare Workers
|
|
311
|
+
* implementation: one read per invocation, writes collected and awaited before the
|
|
312
|
+
* response leaves. Wins over {@link db} when both are given.
|
|
313
|
+
*/
|
|
314
|
+
users?: SsoUserStore;
|
|
299
315
|
/** Static verification key (SPKI PEM). Set → JWKS is never fetched. */
|
|
300
316
|
publicKeyPem?: string;
|
|
301
317
|
/**
|
|
@@ -406,21 +422,13 @@ export interface SsoConsumer {
|
|
|
406
422
|
|
|
407
423
|
const noStore = { "cache-control": "no-store" } as const;
|
|
408
424
|
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
* (no owner links, no granted bypass) rather than open. */
|
|
417
|
-
is_owner?: number;
|
|
418
|
-
is_granted?: number;
|
|
419
|
-
last_login_at: string;
|
|
420
|
-
created_at: string;
|
|
421
|
-
updated_at: string;
|
|
422
|
-
}
|
|
423
|
-
|
|
425
|
+
/*
|
|
426
|
+
* 🔴 `SsoUserRow` moved to `ssoUsers.ts` with the store that reads it, and gained one
|
|
427
|
+
* property in the move: `is_owner` and `is_granted` are REQUIRED there. They used to be
|
|
428
|
+
* optional here because a row written before the 2026-08-02 ALTER has no value for them —
|
|
429
|
+
* a normalization every implementation now performs at the seam, fail-closed, so that two
|
|
430
|
+
* implementations cannot disagree about what a missing column means.
|
|
431
|
+
*/
|
|
424
432
|
const toUser = (row: SsoUserRow): SsoUser => ({
|
|
425
433
|
id: row.id,
|
|
426
434
|
email: row.email,
|
|
@@ -486,15 +494,78 @@ export function resolveSsoAudience(
|
|
|
486
494
|
authUrl: string,
|
|
487
495
|
env: NodeJS.ProcessEnv = process.env,
|
|
488
496
|
registered: readonly string[] = [],
|
|
497
|
+
publicUrl = "",
|
|
489
498
|
): string {
|
|
499
|
+
const hosted = hostedStageAudience(appKey, authUrl, publicUrl, registered);
|
|
500
|
+
if (hosted) return hosted;
|
|
490
501
|
if (!stageIdentityIsLocal(env)) return appKey;
|
|
491
502
|
if (!isLoopbackOrigin(authUrl)) return appKey;
|
|
492
503
|
const local = `${appKey}-local`;
|
|
493
504
|
return registered.includes(local) ? local : appKey;
|
|
494
505
|
}
|
|
495
506
|
|
|
507
|
+
/**
|
|
508
|
+
* 🔴 The HOSTED stage — `<app>-stage.<zone>` signing in at `auth-stage.<zone>` — which is
|
|
509
|
+
* `apps/auth` deployed a second time and mints grants for `<app>-stage` (its roster,
|
|
510
|
+
* `apps/auth/src/server/stageDoor.ts`). Added 2026-09-22, the day auth-stage stopped being a
|
|
511
|
+
* fork: until then only the LOCAL stage had a twin audience, and a hosted stage consumer asked
|
|
512
|
+
* for `<app>` and refused every grant the stage door minted — measured on `collections-stage`,
|
|
513
|
+
* *"grant is for "collections-stage", not "collections""*.
|
|
514
|
+
*
|
|
515
|
+
* Three conditions, all required, the same shape as the local branch and for the same reasons:
|
|
516
|
+
*
|
|
517
|
+
* 1. **this consumer's OWN origin is `<app>-stage.<zone>`** — a name in the fleet's zone that
|
|
518
|
+
* only a stage deploy creates. A production release cannot acquire it without the DNS record.
|
|
519
|
+
* 2. **the accounts door is `auth-stage.<zone>`, the same zone** — a stage origin talking to the
|
|
520
|
+
* REAL door keeps its real audience, so a stage can never mint itself production access.
|
|
521
|
+
* 3. **`<app>-stage` is registered** — an app that has not declared its stage twin keeps its own
|
|
522
|
+
* key and fails visibly at the roster rather than asking for an audience nobody knows.
|
|
523
|
+
*
|
|
524
|
+
* It moves the AUDIENCE only, exactly as the local branch does.
|
|
525
|
+
*/
|
|
526
|
+
export function hostedStageAudience(
|
|
527
|
+
appKey: string,
|
|
528
|
+
authUrl: string,
|
|
529
|
+
publicUrl: string,
|
|
530
|
+
registered: readonly string[],
|
|
531
|
+
): string | null {
|
|
532
|
+
const stage = `${appKey}-stage`;
|
|
533
|
+
if (!registered.includes(stage)) return null;
|
|
534
|
+
let app: URL;
|
|
535
|
+
let auth: URL;
|
|
536
|
+
try {
|
|
537
|
+
app = new URL(publicUrl);
|
|
538
|
+
auth = new URL(authUrl);
|
|
539
|
+
} catch {
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
if (app.protocol !== "https:" || auth.protocol !== "https:") return null;
|
|
543
|
+
const [appLabel, ...appZone] = app.hostname.split(".");
|
|
544
|
+
const [authLabel, ...authZone] = auth.hostname.split(".");
|
|
545
|
+
if (appLabel !== stage || authLabel !== "auth-stage") return null;
|
|
546
|
+
if (appZone.length < 2 || appZone.join(".") !== authZone.join(".")) return null;
|
|
547
|
+
return stage;
|
|
548
|
+
}
|
|
549
|
+
|
|
496
550
|
export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
497
|
-
const { app: appKey, sessions
|
|
551
|
+
const { app: appKey, sessions } = options;
|
|
552
|
+
/*
|
|
553
|
+
* 🔴 `users` wins, `db` is the six unported apps' spelling, and NEITHER is a
|
|
554
|
+
* construction-time throw rather than a surprise at the first sign-in. A consumer
|
|
555
|
+
* with no snapshot store cannot answer "who is this" at all — failing here names the
|
|
556
|
+
* missing option, where failing later would present as a door that refuses everybody.
|
|
557
|
+
*/
|
|
558
|
+
const users: SsoUserStore =
|
|
559
|
+
options.users ??
|
|
560
|
+
(options.db
|
|
561
|
+
? createSqliteSsoUserStore(options.db)
|
|
562
|
+
: (() => {
|
|
563
|
+
throw new TypeError(
|
|
564
|
+
"createSsoConsumer needs somewhere to keep its sso_users snapshot: pass `db` " +
|
|
565
|
+
"(a bun:sqlite Database) or `users` (an SsoUserStore — see cursedauth/d1-stores " +
|
|
566
|
+
"for the Cloudflare Workers implementation).",
|
|
567
|
+
);
|
|
568
|
+
})());
|
|
498
569
|
const authUrl = options.authUrl.replace(/\/$/, "");
|
|
499
570
|
/**
|
|
500
571
|
* What this consumer asks auth FOR and verifies grants AGAINST — see
|
|
@@ -506,11 +577,12 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
506
577
|
authUrl,
|
|
507
578
|
options.env ?? process.env,
|
|
508
579
|
options.registeredAudiences ?? [],
|
|
580
|
+
options.publicUrl,
|
|
509
581
|
);
|
|
510
582
|
if (audience !== appKey) {
|
|
511
583
|
console.log(
|
|
512
|
-
`[${appKey}] SSO audience is "${audience}" — this is a LOCAL STAGE,
|
|
513
|
-
`against ${authUrl}. A grant minted here cannot open the production deployment.`,
|
|
584
|
+
`[${appKey}] SSO audience is "${audience}" — this is a ${audience.endsWith("-stage") ? "HOSTED" : "LOCAL"} STAGE, ` +
|
|
585
|
+
`signing in against ${authUrl}. A grant minted here cannot open the production deployment.`,
|
|
514
586
|
);
|
|
515
587
|
}
|
|
516
588
|
const publicUrl = options.publicUrl.replace(/\/$/, "");
|
|
@@ -526,35 +598,15 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
526
598
|
const emailAllowed = (email: string): boolean =>
|
|
527
599
|
allowedEmails === null || allowedEmails.has(email.trim().toLowerCase());
|
|
528
600
|
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
)
|
|
538
|
-
// 2026-08-02: the fleet directory needs two more facts per account. Added by
|
|
539
|
-
// ALTER rather than by bumping the CREATE, because every deployed satellite
|
|
540
|
-
// already has this table with rows in it. Both default to 0, so an account
|
|
541
|
-
// that has not signed in since the upgrade simply gets no localhost links
|
|
542
|
-
// and no grant bypass until it does — the safe direction.
|
|
543
|
-
for (const column of ["is_owner", "is_granted"]) {
|
|
544
|
-
try {
|
|
545
|
-
db.exec(`ALTER TABLE sso_users ADD COLUMN ${column} INTEGER NOT NULL DEFAULT 0`);
|
|
546
|
-
} catch {
|
|
547
|
-
// Already there. sqlite has no ADD COLUMN IF NOT EXISTS, and reading
|
|
548
|
-
// pragma table_info to decide costs more than catching the one error
|
|
549
|
-
// this can throw.
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
// 🔴 One row per ADDRESS, not just per id (2026-08-23). See `reconcileByEmail`
|
|
553
|
-
// for the ghost this removes; the index is what makes it impossible to grow a
|
|
554
|
-
// second one. Created AFTER the sweep, because a live duplicate would refuse
|
|
555
|
-
// the index and leave the table exactly as it was found.
|
|
556
|
-
dropDuplicateSnapshots(db);
|
|
557
|
-
db.exec("CREATE UNIQUE INDEX IF NOT EXISTS sso_users_email ON sso_users (lower(email))");
|
|
601
|
+
/*
|
|
602
|
+
* 🔴 The table, the two ALTERs, the duplicate sweep and the unique index — all of it
|
|
603
|
+
* moved into `ssoUsers.ts` behind one call, because a host whose schema is applied out
|
|
604
|
+
* of band (D1, where `wrangler d1 execute --file db/schema.sql` is the migration)
|
|
605
|
+
* must be able to answer this with a no-op. See `reconcileByEmail` for the ghost the
|
|
606
|
+
* sweep removes and `SSO_USERS_DDL` for the same schema stated for a host that starts
|
|
607
|
+
* empty.
|
|
608
|
+
*/
|
|
609
|
+
users.ensureSchema();
|
|
558
610
|
|
|
559
611
|
// ── Verification keys ───────────────────────────────────────────────────
|
|
560
612
|
const staticKeys: Map<string, KeyObject> | null = options.publicKeyPem
|
|
@@ -601,7 +653,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
601
653
|
const sessionUser = (c: Context): SsoUser | null => {
|
|
602
654
|
const userId = sessions.userIdOf(c.req.raw);
|
|
603
655
|
if (!userId) return null;
|
|
604
|
-
const row =
|
|
656
|
+
const row = users.byId(userId);
|
|
605
657
|
return row ? toUser(row) : null;
|
|
606
658
|
};
|
|
607
659
|
|
|
@@ -634,7 +686,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
634
686
|
const authorizeRequest = (req: Request): SsoUser | null => {
|
|
635
687
|
const userId = sessions.userIdOf(req);
|
|
636
688
|
if (!userId) return null;
|
|
637
|
-
const row =
|
|
689
|
+
const row = users.byId(userId);
|
|
638
690
|
const user = row ? toUser(row) : null;
|
|
639
691
|
if (!user) return null;
|
|
640
692
|
if (!adminOrGranted(user)) return null;
|
|
@@ -904,7 +956,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
904
956
|
slot = normalizeSlot(instruction ?? 0);
|
|
905
957
|
}
|
|
906
958
|
|
|
907
|
-
upsertUser(
|
|
959
|
+
upsertUser(users, claims, now);
|
|
908
960
|
// The request is passed so the row records the device and address
|
|
909
961
|
// this session was opened from — the whole substance of the fleet
|
|
910
962
|
// session list. A session that cannot say where it came from is one
|
|
@@ -994,7 +1046,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
994
1046
|
// same posture auth's delete already warns about, and the
|
|
995
1047
|
// alternative (deleting a household member's save states because
|
|
996
1048
|
// their account was tidied up) is unrecoverable.
|
|
997
|
-
|
|
1049
|
+
users.deleteById(sub);
|
|
998
1050
|
}
|
|
999
1051
|
console.warn(`[${appKey}] SSO ${action} applied for user ${sub}`);
|
|
1000
1052
|
return c.json({ ok: true, action, scope: "user" as const }, 200, noStore);
|
|
@@ -1120,9 +1172,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
1120
1172
|
// and a caller in slot 1 sees exactly what their own cookies prove.
|
|
1121
1173
|
const occupants = sessions.signedInSlots(c.req.raw);
|
|
1122
1174
|
const accounts = occupants.flatMap(({ slot, userId }) => {
|
|
1123
|
-
const row =
|
|
1124
|
-
.query("SELECT id, email, name FROM sso_users WHERE id = ?")
|
|
1125
|
-
.get(userId) as { id: string; email: string; name: string } | null;
|
|
1175
|
+
const row = users.byId(userId);
|
|
1126
1176
|
// A slot whose row this app has never seen is skipped rather than
|
|
1127
1177
|
// rendered nameless: it means a session survived a database reset,
|
|
1128
1178
|
// and offering an unlabelled button to switch to it is worse than
|
|
@@ -1200,51 +1250,28 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
1200
1250
|
* shipping this: the stale id appeared in exactly one place in family's whole
|
|
1201
1251
|
* database — its own `sso_users` row.
|
|
1202
1252
|
*/
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
FROM sso_users
|
|
1214
|
-
) WHERE rn = 1
|
|
1215
|
-
)`);
|
|
1216
|
-
}
|
|
1217
|
-
|
|
1218
|
-
function upsertUser(db: Database, claims: SsoGrantClaims, now: () => number): void {
|
|
1253
|
+
/**
|
|
1254
|
+
* A verified grant, as one `sso_users` row.
|
|
1255
|
+
*
|
|
1256
|
+
* 🔴 The SQL that used to be here is in `ssoUsers.ts` now, with the delete-then-insert
|
|
1257
|
+
* ordering stated on the interface rather than left as two adjacent statements a second
|
|
1258
|
+
* implementation could reorder. What is left here is the only part that is about GRANTS:
|
|
1259
|
+
* the three optional claims each fail CLOSED (`=== true`, never truthiness), so a grant
|
|
1260
|
+
* from an older issuer that says nothing about ownership does not become an owner.
|
|
1261
|
+
*/
|
|
1262
|
+
function upsertUser(users: SsoUserStore, claims: SsoGrantClaims, now: () => number): void {
|
|
1219
1263
|
const at = new Date(now()).toISOString();
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
`INSERT INTO sso_users (id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at)
|
|
1232
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1233
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
1234
|
-
email = excluded.email, name = excluded.name, is_admin = excluded.is_admin,
|
|
1235
|
-
is_owner = excluded.is_owner, is_granted = excluded.is_granted,
|
|
1236
|
-
last_login_at = excluded.last_login_at, updated_at = excluded.updated_at`,
|
|
1237
|
-
).run(
|
|
1238
|
-
claims.id,
|
|
1239
|
-
claims.email,
|
|
1240
|
-
claims.name,
|
|
1241
|
-
claims.admin ? 1 : 0,
|
|
1242
|
-
claims.owner === true ? 1 : 0,
|
|
1243
|
-
claims.granted === true ? 1 : 0,
|
|
1244
|
-
at,
|
|
1245
|
-
at,
|
|
1246
|
-
at,
|
|
1247
|
-
);
|
|
1264
|
+
users.upsert({
|
|
1265
|
+
id: claims.id,
|
|
1266
|
+
email: claims.email,
|
|
1267
|
+
name: claims.name,
|
|
1268
|
+
is_admin: claims.admin ? 1 : 0,
|
|
1269
|
+
is_owner: claims.owner === true ? 1 : 0,
|
|
1270
|
+
is_granted: claims.granted === true ? 1 : 0,
|
|
1271
|
+
last_login_at: at,
|
|
1272
|
+
created_at: at,
|
|
1273
|
+
updated_at: at,
|
|
1274
|
+
});
|
|
1248
1275
|
}
|
|
1249
1276
|
|
|
1250
1277
|
function peekKid(grant: string): string | null {
|
package/src/ssoUsers.ts
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
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
|
+
/**
|
|
27
|
+
* One row of `sso_users`, normalized.
|
|
28
|
+
*
|
|
29
|
+
* 🔴 `is_owner` and `is_granted` were added by `ALTER` on 2026-08-02 to tables that
|
|
30
|
+
* already had rows, so a row written before then has no value for them. Both must fail
|
|
31
|
+
* CLOSED — no owner links, no granted bypass — which is why an implementation normalizes a
|
|
32
|
+
* missing column to `0` here rather than letting `undefined` reach a comparison. That is
|
|
33
|
+
* the same decision the old inline `SsoUserRow` made with `is_owner?: number` and
|
|
34
|
+
* `row.is_owner === 1`; stating it once in the seam means two implementations cannot make
|
|
35
|
+
* it differently.
|
|
36
|
+
*/
|
|
37
|
+
export interface SsoUserRow {
|
|
38
|
+
id: string;
|
|
39
|
+
email: string;
|
|
40
|
+
name: string;
|
|
41
|
+
is_admin: number;
|
|
42
|
+
is_owner: number;
|
|
43
|
+
is_granted: number;
|
|
44
|
+
last_login_at: string;
|
|
45
|
+
created_at: string;
|
|
46
|
+
updated_at: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The five operations `createSsoConsumer` performs against `sso_users`. */
|
|
50
|
+
export interface SsoUserStore {
|
|
51
|
+
/**
|
|
52
|
+
* Make the table exist and be correct, for a host that migrates its own schema.
|
|
53
|
+
*
|
|
54
|
+
* 🔴 A host whose schema is applied OUT OF BAND — D1, where `wrangler d1 execute
|
|
55
|
+
* --file db/schema.sql` is the migration — implements this as a no-op, and that is
|
|
56
|
+
* legitimate rather than a hole: the read that follows it fails loudly and by name if
|
|
57
|
+
* the table is absent, where a per-request `CREATE TABLE` would spend the invocation's
|
|
58
|
+
* query budget on DDL that can never be needed twice.
|
|
59
|
+
*/
|
|
60
|
+
ensureSchema(): void;
|
|
61
|
+
byId(id: string): SsoUserRow | null;
|
|
62
|
+
/**
|
|
63
|
+
* Write the snapshot for one account.
|
|
64
|
+
*
|
|
65
|
+
* 🔴 An implementation MUST clear any row holding the same address under a DIFFERENT
|
|
66
|
+
* id before it inserts, and the two statements must land in that ORDER. The unique
|
|
67
|
+
* index on `lower(email)` is what makes a second row for one address impossible; the
|
|
68
|
+
* delete is what keeps a legitimate re-issued account id from hitting that index
|
|
69
|
+
* instead of updating in place. See `reconcileByEmail` in `ssoConsumer.server.ts` for
|
|
70
|
+
* the ghost this removes.
|
|
71
|
+
*/
|
|
72
|
+
upsert(row: SsoUserRow): void;
|
|
73
|
+
/**
|
|
74
|
+
* Drop the snapshot so the account stops showing up in this app's own lists.
|
|
75
|
+
*
|
|
76
|
+
* Rows keyed on the id are ORPHANED, not cascaded — the same posture auth's delete
|
|
77
|
+
* already warns about, and the alternative (deleting a household member's save states
|
|
78
|
+
* because their account was tidied up) is unrecoverable.
|
|
79
|
+
*/
|
|
80
|
+
deleteById(id: string): void;
|
|
81
|
+
/**
|
|
82
|
+
* Keep one row per ADDRESS, newest first, and drop the rest.
|
|
83
|
+
*
|
|
84
|
+
* The one-time repair for a table that grew duplicates before the unique index
|
|
85
|
+
* existed. Called from {@link ensureSchema} on a host that migrates in place; a host
|
|
86
|
+
* whose database starts empty behind the index has nothing to repair.
|
|
87
|
+
*/
|
|
88
|
+
dropDuplicates(): void;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The `sso_users` table in its FINAL shape — every column, no `ALTER` history.
|
|
93
|
+
*
|
|
94
|
+
* Exported for a host that starts empty: this is what goes in an app's `db/schema.sql`
|
|
95
|
+
* next to its own tables. `ssoUsers.sameShape.test.ts` builds the sqlite side the old way
|
|
96
|
+
* (a seven-column `CREATE` plus two `ALTER`s) and the D1 side from this constant, then
|
|
97
|
+
* requires identical answers from both — so it is a schema that has been proved
|
|
98
|
+
* equivalent, not one that was transcribed.
|
|
99
|
+
*
|
|
100
|
+
* 🔴 The unique index is part of it and is not optional. It is what makes one row per
|
|
101
|
+
* address a property of the database rather than a convention two call sites remember.
|
|
102
|
+
*/
|
|
103
|
+
export const SSO_USERS_DDL = `CREATE TABLE IF NOT EXISTS sso_users (
|
|
104
|
+
id TEXT PRIMARY KEY,
|
|
105
|
+
email TEXT NOT NULL,
|
|
106
|
+
name TEXT NOT NULL DEFAULT '',
|
|
107
|
+
is_admin INTEGER NOT NULL DEFAULT 0,
|
|
108
|
+
is_owner INTEGER NOT NULL DEFAULT 0,
|
|
109
|
+
is_granted INTEGER NOT NULL DEFAULT 0,
|
|
110
|
+
last_login_at TEXT NOT NULL DEFAULT '',
|
|
111
|
+
created_at TEXT NOT NULL,
|
|
112
|
+
updated_at TEXT NOT NULL
|
|
113
|
+
);
|
|
114
|
+
CREATE UNIQUE INDEX IF NOT EXISTS sso_users_email ON sso_users (lower(email));`;
|
|
115
|
+
|
|
116
|
+
/** `SELECT *` used to be the read; naming the columns is what makes the two sides comparable. */
|
|
117
|
+
const COLUMNS =
|
|
118
|
+
"id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at";
|
|
119
|
+
|
|
120
|
+
/** A row as a driver may hand it back, before the fail-closed normalization above. */
|
|
121
|
+
export interface RawSsoUserRow {
|
|
122
|
+
id: string;
|
|
123
|
+
email: string;
|
|
124
|
+
name: string;
|
|
125
|
+
is_admin: number;
|
|
126
|
+
is_owner?: number | null;
|
|
127
|
+
is_granted?: number | null;
|
|
128
|
+
last_login_at?: string | null;
|
|
129
|
+
created_at: string;
|
|
130
|
+
updated_at: string;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export const normalizeSsoUserRow = (row: RawSsoUserRow): SsoUserRow => ({
|
|
134
|
+
id: row.id,
|
|
135
|
+
email: row.email,
|
|
136
|
+
name: row.name,
|
|
137
|
+
is_admin: row.is_admin === 1 ? 1 : 0,
|
|
138
|
+
is_owner: row.is_owner === 1 ? 1 : 0,
|
|
139
|
+
is_granted: row.is_granted === 1 ? 1 : 0,
|
|
140
|
+
last_login_at: row.last_login_at ?? "",
|
|
141
|
+
created_at: row.created_at,
|
|
142
|
+
updated_at: row.updated_at,
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* `sso_users` on `bun:sqlite` — the code that used to be inline in
|
|
147
|
+
* `ssoConsumer.server.ts`, moved rather than rewritten.
|
|
148
|
+
*
|
|
149
|
+
* The table lives in the APP's database (not in the sessions file) so app tables can
|
|
150
|
+
* foreign-key the user id; that is why this takes a handle instead of opening one.
|
|
151
|
+
*/
|
|
152
|
+
export function createSqliteSsoUserStore(db: Database): SsoUserStore {
|
|
153
|
+
const store: SsoUserStore = {
|
|
154
|
+
ensureSchema() {
|
|
155
|
+
db.exec(`CREATE TABLE IF NOT EXISTS sso_users (
|
|
156
|
+
id TEXT PRIMARY KEY,
|
|
157
|
+
email TEXT NOT NULL,
|
|
158
|
+
name TEXT NOT NULL DEFAULT '',
|
|
159
|
+
is_admin INTEGER NOT NULL DEFAULT 0,
|
|
160
|
+
last_login_at TEXT NOT NULL DEFAULT '',
|
|
161
|
+
created_at TEXT NOT NULL,
|
|
162
|
+
updated_at TEXT NOT NULL
|
|
163
|
+
);`);
|
|
164
|
+
// 2026-08-02: the fleet directory needs two more facts per account. Added by
|
|
165
|
+
// ALTER rather than by bumping the CREATE, because every deployed satellite
|
|
166
|
+
// already has this table with rows in it. Both default to 0, so an account
|
|
167
|
+
// that has not signed in since the upgrade simply gets no localhost links
|
|
168
|
+
// and no grant bypass until it does — the safe direction.
|
|
169
|
+
for (const column of ["is_owner", "is_granted"]) {
|
|
170
|
+
try {
|
|
171
|
+
db.exec(`ALTER TABLE sso_users ADD COLUMN ${column} INTEGER NOT NULL DEFAULT 0`);
|
|
172
|
+
} catch {
|
|
173
|
+
// Already there. sqlite has no ADD COLUMN IF NOT EXISTS, and reading
|
|
174
|
+
// pragma table_info to decide costs more than catching the one error
|
|
175
|
+
// this can throw.
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
// 🔴 One row per ADDRESS, not just per id (2026-08-23). The index is what makes
|
|
179
|
+
// it impossible to grow a second one. Created AFTER the sweep, because a live
|
|
180
|
+
// duplicate would refuse the index and leave the table exactly as it was found.
|
|
181
|
+
store.dropDuplicates();
|
|
182
|
+
db.exec("CREATE UNIQUE INDEX IF NOT EXISTS sso_users_email ON sso_users (lower(email))");
|
|
183
|
+
},
|
|
184
|
+
|
|
185
|
+
byId(id) {
|
|
186
|
+
const row = db
|
|
187
|
+
.query(`SELECT ${COLUMNS} FROM sso_users WHERE id = ?`)
|
|
188
|
+
.get(id) as RawSsoUserRow | null;
|
|
189
|
+
return row ? normalizeSsoUserRow(row) : null;
|
|
190
|
+
},
|
|
191
|
+
|
|
192
|
+
upsert(row) {
|
|
193
|
+
// 🔴 The same address under a DIFFERENT id is the ghost described on the
|
|
194
|
+
// interface, and this is the moment it would be created. Clearing it first is
|
|
195
|
+
// what turns the unique index from a constraint that would throw on a legitimate
|
|
196
|
+
// sign-in into one that simply cannot be violated. Scoped to `id <> ?` so an
|
|
197
|
+
// ordinary re-sign-in — by far the common path — deletes nothing and the upsert
|
|
198
|
+
// below updates in place.
|
|
199
|
+
db.query("DELETE FROM sso_users WHERE lower(email) = lower(?) AND id <> ?").run(
|
|
200
|
+
row.email,
|
|
201
|
+
row.id,
|
|
202
|
+
);
|
|
203
|
+
db.query(
|
|
204
|
+
`INSERT INTO sso_users (${COLUMNS})
|
|
205
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
206
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
207
|
+
email = excluded.email, name = excluded.name, is_admin = excluded.is_admin,
|
|
208
|
+
is_owner = excluded.is_owner, is_granted = excluded.is_granted,
|
|
209
|
+
last_login_at = excluded.last_login_at, updated_at = excluded.updated_at`,
|
|
210
|
+
).run(
|
|
211
|
+
row.id,
|
|
212
|
+
row.email,
|
|
213
|
+
row.name,
|
|
214
|
+
row.is_admin,
|
|
215
|
+
row.is_owner,
|
|
216
|
+
row.is_granted,
|
|
217
|
+
row.last_login_at,
|
|
218
|
+
row.created_at,
|
|
219
|
+
row.updated_at,
|
|
220
|
+
);
|
|
221
|
+
},
|
|
222
|
+
|
|
223
|
+
deleteById(id) {
|
|
224
|
+
db.query("DELETE FROM sso_users WHERE id = ?").run(id);
|
|
225
|
+
},
|
|
226
|
+
|
|
227
|
+
dropDuplicates() {
|
|
228
|
+
// `lower(email)` so two rows differing only in case are one account, which is
|
|
229
|
+
// the same rule `emailAllowed` and auth's own registry already apply.
|
|
230
|
+
db.exec(`DELETE FROM sso_users WHERE rowid NOT IN (
|
|
231
|
+
SELECT rowid FROM (
|
|
232
|
+
SELECT rowid,
|
|
233
|
+
ROW_NUMBER() OVER (
|
|
234
|
+
PARTITION BY lower(email)
|
|
235
|
+
ORDER BY last_login_at DESC, updated_at DESC, rowid DESC
|
|
236
|
+
) AS rn
|
|
237
|
+
FROM sso_users
|
|
238
|
+
) WHERE rn = 1
|
|
239
|
+
)`);
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
return store;
|
|
243
|
+
}
|