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
|
@@ -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,
|
|
@@ -494,7 +502,24 @@ export function resolveSsoAudience(
|
|
|
494
502
|
}
|
|
495
503
|
|
|
496
504
|
export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
497
|
-
const { app: appKey, sessions
|
|
505
|
+
const { app: appKey, sessions } = options;
|
|
506
|
+
/*
|
|
507
|
+
* 🔴 `users` wins, `db` is the six unported apps' spelling, and NEITHER is a
|
|
508
|
+
* construction-time throw rather than a surprise at the first sign-in. A consumer
|
|
509
|
+
* with no snapshot store cannot answer "who is this" at all — failing here names the
|
|
510
|
+
* missing option, where failing later would present as a door that refuses everybody.
|
|
511
|
+
*/
|
|
512
|
+
const users: SsoUserStore =
|
|
513
|
+
options.users ??
|
|
514
|
+
(options.db
|
|
515
|
+
? createSqliteSsoUserStore(options.db)
|
|
516
|
+
: (() => {
|
|
517
|
+
throw new TypeError(
|
|
518
|
+
"createSsoConsumer needs somewhere to keep its sso_users snapshot: pass `db` " +
|
|
519
|
+
"(a bun:sqlite Database) or `users` (an SsoUserStore — see cursedauth/d1-stores " +
|
|
520
|
+
"for the Cloudflare Workers implementation).",
|
|
521
|
+
);
|
|
522
|
+
})());
|
|
498
523
|
const authUrl = options.authUrl.replace(/\/$/, "");
|
|
499
524
|
/**
|
|
500
525
|
* What this consumer asks auth FOR and verifies grants AGAINST — see
|
|
@@ -526,35 +551,15 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
526
551
|
const emailAllowed = (email: string): boolean =>
|
|
527
552
|
allowedEmails === null || allowedEmails.has(email.trim().toLowerCase());
|
|
528
553
|
|
|
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))");
|
|
554
|
+
/*
|
|
555
|
+
* 🔴 The table, the two ALTERs, the duplicate sweep and the unique index — all of it
|
|
556
|
+
* moved into `ssoUsers.ts` behind one call, because a host whose schema is applied out
|
|
557
|
+
* of band (D1, where `wrangler d1 execute --file db/schema.sql` is the migration)
|
|
558
|
+
* must be able to answer this with a no-op. See `reconcileByEmail` for the ghost the
|
|
559
|
+
* sweep removes and `SSO_USERS_DDL` for the same schema stated for a host that starts
|
|
560
|
+
* empty.
|
|
561
|
+
*/
|
|
562
|
+
users.ensureSchema();
|
|
558
563
|
|
|
559
564
|
// ── Verification keys ───────────────────────────────────────────────────
|
|
560
565
|
const staticKeys: Map<string, KeyObject> | null = options.publicKeyPem
|
|
@@ -601,7 +606,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
601
606
|
const sessionUser = (c: Context): SsoUser | null => {
|
|
602
607
|
const userId = sessions.userIdOf(c.req.raw);
|
|
603
608
|
if (!userId) return null;
|
|
604
|
-
const row =
|
|
609
|
+
const row = users.byId(userId);
|
|
605
610
|
return row ? toUser(row) : null;
|
|
606
611
|
};
|
|
607
612
|
|
|
@@ -634,7 +639,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
634
639
|
const authorizeRequest = (req: Request): SsoUser | null => {
|
|
635
640
|
const userId = sessions.userIdOf(req);
|
|
636
641
|
if (!userId) return null;
|
|
637
|
-
const row =
|
|
642
|
+
const row = users.byId(userId);
|
|
638
643
|
const user = row ? toUser(row) : null;
|
|
639
644
|
if (!user) return null;
|
|
640
645
|
if (!adminOrGranted(user)) return null;
|
|
@@ -904,7 +909,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
904
909
|
slot = normalizeSlot(instruction ?? 0);
|
|
905
910
|
}
|
|
906
911
|
|
|
907
|
-
upsertUser(
|
|
912
|
+
upsertUser(users, claims, now);
|
|
908
913
|
// The request is passed so the row records the device and address
|
|
909
914
|
// this session was opened from — the whole substance of the fleet
|
|
910
915
|
// session list. A session that cannot say where it came from is one
|
|
@@ -994,7 +999,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
994
999
|
// same posture auth's delete already warns about, and the
|
|
995
1000
|
// alternative (deleting a household member's save states because
|
|
996
1001
|
// their account was tidied up) is unrecoverable.
|
|
997
|
-
|
|
1002
|
+
users.deleteById(sub);
|
|
998
1003
|
}
|
|
999
1004
|
console.warn(`[${appKey}] SSO ${action} applied for user ${sub}`);
|
|
1000
1005
|
return c.json({ ok: true, action, scope: "user" as const }, 200, noStore);
|
|
@@ -1120,9 +1125,7 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
1120
1125
|
// and a caller in slot 1 sees exactly what their own cookies prove.
|
|
1121
1126
|
const occupants = sessions.signedInSlots(c.req.raw);
|
|
1122
1127
|
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;
|
|
1128
|
+
const row = users.byId(userId);
|
|
1126
1129
|
// A slot whose row this app has never seen is skipped rather than
|
|
1127
1130
|
// rendered nameless: it means a session survived a database reset,
|
|
1128
1131
|
// and offering an unlabelled button to switch to it is worse than
|
|
@@ -1200,51 +1203,28 @@ export function createSsoConsumer(options: SsoConsumerOptions): SsoConsumer {
|
|
|
1200
1203
|
* shipping this: the stale id appeared in exactly one place in family's whole
|
|
1201
1204
|
* database — its own `sso_users` row.
|
|
1202
1205
|
*/
|
|
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 {
|
|
1206
|
+
/**
|
|
1207
|
+
* A verified grant, as one `sso_users` row.
|
|
1208
|
+
*
|
|
1209
|
+
* 🔴 The SQL that used to be here is in `ssoUsers.ts` now, with the delete-then-insert
|
|
1210
|
+
* ordering stated on the interface rather than left as two adjacent statements a second
|
|
1211
|
+
* implementation could reorder. What is left here is the only part that is about GRANTS:
|
|
1212
|
+
* the three optional claims each fail CLOSED (`=== true`, never truthiness), so a grant
|
|
1213
|
+
* from an older issuer that says nothing about ownership does not become an owner.
|
|
1214
|
+
*/
|
|
1215
|
+
function upsertUser(users: SsoUserStore, claims: SsoGrantClaims, now: () => number): void {
|
|
1219
1216
|
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
|
-
);
|
|
1217
|
+
users.upsert({
|
|
1218
|
+
id: claims.id,
|
|
1219
|
+
email: claims.email,
|
|
1220
|
+
name: claims.name,
|
|
1221
|
+
is_admin: claims.admin ? 1 : 0,
|
|
1222
|
+
is_owner: claims.owner === true ? 1 : 0,
|
|
1223
|
+
is_granted: claims.granted === true ? 1 : 0,
|
|
1224
|
+
last_login_at: at,
|
|
1225
|
+
created_at: at,
|
|
1226
|
+
updated_at: at,
|
|
1227
|
+
});
|
|
1248
1228
|
}
|
|
1249
1229
|
|
|
1250
1230
|
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
|
+
}
|