cursedauth 0.9.5 → 0.10.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 +2 -0
- package/dist/relayDoor.d.ts +127 -0
- package/dist/relayDoor.d.ts.map +1 -0
- package/dist/relayDoor.js +261 -0
- package/dist/relayDoor.js.map +1 -0
- package/dist/relayIdentity.d.ts +50 -0
- package/dist/relayIdentity.d.ts.map +1 -0
- package/dist/relayIdentity.js +87 -0
- package/dist/relayIdentity.js.map +1 -0
- package/package.json +13 -1
- package/src/relayDoor.ts +338 -0
- package/src/relayIdentity.ts +119 -0
package/README.md
CHANGED
|
@@ -50,6 +50,8 @@ logins and nothing else. The provider is a separate service reached over HTTPS a
|
|
|
50
50
|
| `cursedauth/constant-time` | both | `constantTimeEqual` — compare two secrets without leaking where they differ |
|
|
51
51
|
| `cursedauth/secure-request` | both | `isSecureRequest` — whether a request arrived over HTTPS (reading `x-forwarded-proto` behind the tunnel), the one question the cookie `Secure` attribute turns on. Published 0.9.3 because `patterns` and `auth` each carried a copy (task 2106) |
|
|
52
52
|
| `cursedauth/offline-grant` | both | the bounded offline window: how long a device with no network may keep using cached content |
|
|
53
|
+
| `cursedauth/relay-door` | server | a relay app's door on its Worker (`cursedops/relay`): the SSO consumer over D1, the account signed into `<app>_as` for the Mac, the browser's session cookies stripped, the door's schema and the cutover's session import. Lifted from `apps/roms` in 0.10.0. **Worker-safe** |
|
|
54
|
+
| `cursedauth/relay-identity` | server | the Mac's half: believe `<app>_as` only on a request that came down the link, under the link key's digest, and gate on it like the consumer would. `node:crypto`, Mac only |
|
|
53
55
|
| `cursedauth/auth` | browser | `startSsoSignIn`, `useSsoAutoSignIn`, session hooks |
|
|
54
56
|
| `cursedauth/account-ui` | browser | the account menu |
|
|
55
57
|
| `cursedauth/account-slot-client` | browser | slot switching in the page |
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { type D1Handle, type WriteCollector } from "./d1Stores.js";
|
|
2
|
+
import { type SsoConsumer, type SsoUser } from "./ssoConsumer.server.js";
|
|
3
|
+
/** The account the Worker vouches for — `SsoUser`, field for field. */
|
|
4
|
+
export interface LinkIdentity {
|
|
5
|
+
id: string;
|
|
6
|
+
email: string;
|
|
7
|
+
name: string;
|
|
8
|
+
isAdmin: boolean;
|
|
9
|
+
isOwner: boolean;
|
|
10
|
+
isGranted: boolean;
|
|
11
|
+
}
|
|
12
|
+
/** The identity cookie's name for an app — `roms_as`, `station_as`. */
|
|
13
|
+
export declare const identityCookieName: (app: string) => string;
|
|
14
|
+
export interface RelayDoorOptions {
|
|
15
|
+
/** The app's name — the consumer's, the identity cookie's prefix, the secret fingerprint's domain. */
|
|
16
|
+
app: string;
|
|
17
|
+
/** The Mac's session cookie name, unchanged, so the cutover carries sessions across. */
|
|
18
|
+
cookieName: string;
|
|
19
|
+
/** The session secret — the Mac's own, so a Mac-era cookie verifies at the door. Blank → no door. */
|
|
20
|
+
sessionSecret: string | undefined;
|
|
21
|
+
/** The Mac's session TTL — never widened by the move: an expired session is a sign-in away, Mac or no Mac. */
|
|
22
|
+
sessionTtlSeconds: number;
|
|
23
|
+
/** The accounts service's origin (`https://auth.cursedalchemy.com`, or auth-stage's). */
|
|
24
|
+
authUrl: string;
|
|
25
|
+
/** This app's own public origin. */
|
|
26
|
+
publicUrl: string;
|
|
27
|
+
/** The audiences this app answers to — the Mac's list. */
|
|
28
|
+
registeredAudiences: readonly string[];
|
|
29
|
+
/** The Mac's allow-list, when it has one — enforced at the Worker's callback AND per request. */
|
|
30
|
+
allowedEmails?: string[];
|
|
31
|
+
/** Admin-or-granted only, when the Mac's consumer says so. */
|
|
32
|
+
requireAdmin?: boolean;
|
|
33
|
+
/** A static grant-verification key (tests); unset → auth's live JWKS through {@link fetchImpl}. */
|
|
34
|
+
publicKeyPem?: string;
|
|
35
|
+
/**
|
|
36
|
+
* How JWKS refreshes reach auth — 🔴 a Service Binding's `fetch` (task 2150): a same-zone
|
|
37
|
+
* subrequest to `auth.cursedalchemy.com` falls through to the zone's origin, the Mac's tunnel.
|
|
38
|
+
*/
|
|
39
|
+
fetchImpl?: typeof fetch;
|
|
40
|
+
}
|
|
41
|
+
export interface RelayDoor {
|
|
42
|
+
sso: SsoConsumer;
|
|
43
|
+
}
|
|
44
|
+
/** The fetch for a Service Binding named e.g. `AUTH`, or the global `fetch` when there is none. */
|
|
45
|
+
export declare function bindingFetch(binding: {
|
|
46
|
+
fetch(input: Request | string, init?: RequestInit): Promise<Response>;
|
|
47
|
+
} | undefined): typeof fetch;
|
|
48
|
+
/**
|
|
49
|
+
* The door for ONE invocation — two D1 reads (the `sessions` and `sso_users` snapshots); every
|
|
50
|
+
* write they collect goes to `writes`, which the caller settles before the response leaves.
|
|
51
|
+
* Null when there is no session secret.
|
|
52
|
+
*/
|
|
53
|
+
export declare function createRelayDoor(options: RelayDoorOptions, db: D1Handle, writes: WriteCollector): Promise<RelayDoor | null>;
|
|
54
|
+
/** Answered by the Worker's door rather than relayed: every `/api/auth/*` but the census. */
|
|
55
|
+
export declare function relayDoorAnswers(path: string): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* The door's own answer to `/api/auth/*`, marked with `answeredByHeader: worker` so a client
|
|
58
|
+
* never reads the Worker's word as the Mac waking.
|
|
59
|
+
*/
|
|
60
|
+
export declare function answerAtDoor(request: Request, door: RelayDoor, answeredByHeader: string): Promise<Response>;
|
|
61
|
+
/** Hex SHA-256 — WebCrypto, so it runs the same on workerd. */
|
|
62
|
+
export declare function sha256Hex(text: string): Promise<string>;
|
|
63
|
+
/**
|
|
64
|
+
* A PUBLIC fingerprint of the session secret — `/healthz` publishes it and the app's
|
|
65
|
+
* `worker:secrets` compares it with the Mac's, so a Worker signing with the wrong secret
|
|
66
|
+
* (every Mac-era cookie refused, everybody signed out) is red with no session anywhere.
|
|
67
|
+
* Domain-separated per app, truncated: it names the secret, it cannot stand in for it. `""`
|
|
68
|
+
* when there is none.
|
|
69
|
+
*/
|
|
70
|
+
export declare function sessionSecretId(app: string, secret: string | undefined): Promise<string>;
|
|
71
|
+
/**
|
|
72
|
+
* The door's D1 schema — cursedauth's OWN two tables and nothing of the app's, one statement
|
|
73
|
+
* per line (D1's `exec` splits on newlines), every one `IF NOT EXISTS` because a deploy applies
|
|
74
|
+
* it on every ship. An app writes it to `db/schema.sql` and a test holds the file to this.
|
|
75
|
+
*/
|
|
76
|
+
export declare function relayDoorSchemaSql(app: string, generator: string): string;
|
|
77
|
+
/** A row of the Mac's `sessions` table. */
|
|
78
|
+
export interface MacSessionRow {
|
|
79
|
+
id: string;
|
|
80
|
+
user_id: string;
|
|
81
|
+
expires_at: number;
|
|
82
|
+
user_agent: string;
|
|
83
|
+
ip: string;
|
|
84
|
+
created_at: number;
|
|
85
|
+
last_seen_at: number;
|
|
86
|
+
place: string;
|
|
87
|
+
}
|
|
88
|
+
/** A row of the Mac's `sso_users` table. */
|
|
89
|
+
export interface MacSsoUserRow {
|
|
90
|
+
id: string;
|
|
91
|
+
email: string;
|
|
92
|
+
name: string;
|
|
93
|
+
is_admin: number;
|
|
94
|
+
is_owner: number;
|
|
95
|
+
is_granted: number;
|
|
96
|
+
last_login_at: string;
|
|
97
|
+
created_at: string;
|
|
98
|
+
updated_at: string;
|
|
99
|
+
}
|
|
100
|
+
/** The two SELECTs that read a Mac's rows in {@link MacSessionRow} / {@link MacSsoUserRow} shape. */
|
|
101
|
+
export declare const MAC_SESSIONS_SELECT = "SELECT id, user_id, expires_at, COALESCE(user_agent, '') AS user_agent, COALESCE(ip, '') AS ip, COALESCE(created_at, 0) AS created_at, COALESCE(last_seen_at, 0) AS last_seen_at, COALESCE(place, '') AS place FROM sessions";
|
|
102
|
+
export declare const MAC_SSO_USERS_SELECT = "SELECT id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at FROM sso_users";
|
|
103
|
+
/**
|
|
104
|
+
* The statements that copy the Mac's rows into the door's D1, pure: every user, then every
|
|
105
|
+
* session still live at `now`. `INSERT OR IGNORE` — a row the door already has (somebody signed
|
|
106
|
+
* in through it since) is never overwritten, and a re-run is a no-op.
|
|
107
|
+
*/
|
|
108
|
+
export declare function sessionImportStatements(sessions: readonly MacSessionRow[], users: readonly MacSsoUserRow[], now: number): string[];
|
|
109
|
+
/** The account a VERIFIED payload names, or null for one that does not parse as one. */
|
|
110
|
+
export declare function accountOf(payloadJson: string): LinkIdentity | null;
|
|
111
|
+
/** The cookie VALUE vouching for `user` — WebCrypto HMAC-SHA256. `key` is the link key's SHA-256, hex. */
|
|
112
|
+
export declare function signIdentity(user: LinkIdentity | SsoUser, key: string): Promise<string>;
|
|
113
|
+
/** One cookie's value off a `cookie` header, or null — exact name match, `=` in the value kept. */
|
|
114
|
+
export declare function cookieValueOf(header: string | null, name: string): string | null;
|
|
115
|
+
/**
|
|
116
|
+
* `request` as the Mac should see it, once the Worker is the door: every `identityCookie` the
|
|
117
|
+
* BROWSER sent removed, the Worker's own appended when it resolved an account — and 🔴 the
|
|
118
|
+
* browser's session cookies in every slot removed too. The Mac falls back to its OWN session
|
|
119
|
+
* rows for a request with no identity, and those rows were imported at the cutover; a cookie
|
|
120
|
+
* the Worker has signed out (its D1 row gone) must not be honoured by the Mac's stale copy.
|
|
121
|
+
* The body, method and every other header ride along.
|
|
122
|
+
*/
|
|
123
|
+
export declare function withIdentity(request: Request, signed: string | null, cookies: {
|
|
124
|
+
identityCookie: string;
|
|
125
|
+
sessionCookie: string;
|
|
126
|
+
}): Request;
|
|
127
|
+
//# sourceMappingURL=relayDoor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relayDoor.d.ts","sourceRoot":"","sources":["../src/relayDoor.ts"],"names":[],"mappings":"AA+CA,OAAO,EAA6C,KAAK,QAAQ,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAC9G,OAAO,EAAsC,KAAK,WAAW,EAAE,KAAK,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAI7G,uEAAuE;AACvE,MAAM,WAA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rG,eAAO,MAAM,mBAAmB,iOAC+L,CAAC;AAChO,eAAO,MAAM,oBAAoB,iHAAiH,CAAC;AAWnJ;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,SAAS,aAAa,EAAE,EAAE,KAAK,EAAE,SAAS,aAAa,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAYlI;AAyBD,wFAAwF;AACxF,wBAAgB,SAAS,CAAC,WAAW,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAelE;AAED,0GAA0G;AAC1G,wBAAsB,YAAY,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAK7F;AAED,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAMhF;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,EAAE;IAAE,cAAc,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAsBzI"}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DOOR of a relay app, on its Worker — `cursedauth/relay-door`.
|
|
3
|
+
*
|
|
4
|
+
* A relay app (`cursedops/relay`) is one whose Worker hands every API request down a WebSocket
|
|
5
|
+
* the Mac dialled out. Until its Worker is the door, the gate is the Mac's: with the Mac off
|
|
6
|
+
* nobody can sign in, and a signed-in browser reads what the relay kept for exactly as long as
|
|
7
|
+
* its one session cookie lives. `apps/roms` moved its door onto the Worker on 2026-09-26
|
|
8
|
+
* (roms `726710a`) and proved it on its stage (a fresh 2FA sign-in with the Mac stopped reads
|
|
9
|
+
* the library); this module is that move lifted, so the next relay app takes it in data rather
|
|
10
|
+
* than in 1,200 copied lines.
|
|
11
|
+
*
|
|
12
|
+
* ## The shape
|
|
13
|
+
*
|
|
14
|
+
* · The Worker is the SSO consumer over its own two D1 tables ({@link relayDoorSchemaSql}:
|
|
15
|
+
* cursedauth's `sessions` and `sso_users`, nothing of the app's). `/api/auth/*` is answered
|
|
16
|
+
* there ({@link relayDoorAnswers}) — except the content CENSUS, which counts what lives on
|
|
17
|
+
* the Mac and so is relayed.
|
|
18
|
+
* · Every relayed request is resolved against those sessions and handed to the Mac with the
|
|
19
|
+
* account signed into ONE cookie ({@link signIdentity}, {@link withIdentity}):
|
|
20
|
+
*
|
|
21
|
+
* <app>_as=<base64url(JSON account)>.<base64url(HMAC-SHA256(key, payload))>
|
|
22
|
+
*
|
|
23
|
+
* A cookie, not a header, because the relay's offline cache keys what it keeps on a cookie
|
|
24
|
+
* and replays its wake-up reads with that cookie alone — keyed on this one, what is kept is
|
|
25
|
+
* the ACCOUNT's, so a fresh sign-in on a new device with the Mac off still reads it.
|
|
26
|
+
* · The Mac believes that cookie ONLY on a request that came down the link, under the SHA-256
|
|
27
|
+
* of the link key it dialled with (`cursedauth/relay-identity`) — the Worker holds exactly
|
|
28
|
+
* that digest as its link secret, and nobody else holds either.
|
|
29
|
+
* · The Worker strips the browser's own `<app>_as` and every `<session>*` slot cookie before
|
|
30
|
+
* it signs its own, so a browser can neither forge an account nor have a session the door
|
|
31
|
+
* ended honoured by the Mac's stale copy of the same row.
|
|
32
|
+
*
|
|
33
|
+
* Deterministic on purpose — no timestamp, no nonce: the same account must sign to the same
|
|
34
|
+
* value every time, or the relay's cache would key every request apart. Its lifetime is not
|
|
35
|
+
* its own: the Worker re-checks the SESSION on every request before it signs.
|
|
36
|
+
*
|
|
37
|
+
* 🔴 Worker-safe: WebCrypto only, no `bun:*`, no `node:` import of its own
|
|
38
|
+
* (`subpathsReachNoBunBuiltin.test.ts`). The Mac's half verifies synchronously with
|
|
39
|
+
* `node:crypto` and lives in `./relayIdentity.ts`; `relayDoor.test.ts` holds the two to the
|
|
40
|
+
* same bytes.
|
|
41
|
+
*
|
|
42
|
+
* 🔴 No session secret, no door: {@link createRelayDoor} answers null and the app relays as it
|
|
43
|
+
* did before. A Worker that invented a secret would sign everybody out on every deploy or sign
|
|
44
|
+
* cookies anybody could forge.
|
|
45
|
+
*/
|
|
46
|
+
import { Hono } from "hono";
|
|
47
|
+
import { allSlotCookieNames } from "./accountSlots.js";
|
|
48
|
+
import { createD1SessionRows, createD1SsoUserStore } from "./d1Stores.js";
|
|
49
|
+
import { createSsoConsumer, SSO_CENSUS_PATH } from "./ssoConsumer.server.js";
|
|
50
|
+
import { SSO_USERS_DDL } from "./ssoUsers.js";
|
|
51
|
+
import { createUserSessionStoreOver, SESSIONS_DDL } from "./userSessions.core.js";
|
|
52
|
+
/** The identity cookie's name for an app — `roms_as`, `station_as`. */
|
|
53
|
+
export const identityCookieName = (app) => `${app}_as`;
|
|
54
|
+
/** The fetch for a Service Binding named e.g. `AUTH`, or the global `fetch` when there is none. */
|
|
55
|
+
export function bindingFetch(binding) {
|
|
56
|
+
if (!binding)
|
|
57
|
+
return fetch;
|
|
58
|
+
return ((input, init) => binding.fetch(input, init));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The door for ONE invocation — two D1 reads (the `sessions` and `sso_users` snapshots); every
|
|
62
|
+
* write they collect goes to `writes`, which the caller settles before the response leaves.
|
|
63
|
+
* Null when there is no session secret.
|
|
64
|
+
*/
|
|
65
|
+
export async function createRelayDoor(options, db, writes) {
|
|
66
|
+
const secret = options.sessionSecret?.trim() ?? "";
|
|
67
|
+
if (!secret)
|
|
68
|
+
return null;
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
const sessions = createUserSessionStoreOver(await createD1SessionRows(db, writes, { now }), {
|
|
71
|
+
cookieName: options.cookieName,
|
|
72
|
+
sessionSecret: secret,
|
|
73
|
+
sessionTtlSeconds: options.sessionTtlSeconds,
|
|
74
|
+
});
|
|
75
|
+
const sso = createSsoConsumer({
|
|
76
|
+
app: options.app,
|
|
77
|
+
authUrl: options.authUrl.replace(/\/$/, ""),
|
|
78
|
+
publicUrl: options.publicUrl.replace(/\/$/, ""),
|
|
79
|
+
sessions,
|
|
80
|
+
users: await createD1SsoUserStore(db, writes, { now }),
|
|
81
|
+
registeredAudiences: options.registeredAudiences,
|
|
82
|
+
...(options.allowedEmails ? { allowedEmails: options.allowedEmails } : {}),
|
|
83
|
+
...(options.requireAdmin ? { requireAdmin: true } : {}),
|
|
84
|
+
...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
|
|
85
|
+
...(options.publicKeyPem?.trim() ? { publicKeyPem: options.publicKeyPem.trim() } : {}),
|
|
86
|
+
});
|
|
87
|
+
return { sso };
|
|
88
|
+
}
|
|
89
|
+
/** Answered by the Worker's door rather than relayed: every `/api/auth/*` but the census. */
|
|
90
|
+
export function relayDoorAnswers(path) {
|
|
91
|
+
return path.startsWith("/api/auth/") && path !== SSO_CENSUS_PATH;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The door's own answer to `/api/auth/*`, marked with `answeredByHeader: worker` so a client
|
|
95
|
+
* never reads the Worker's word as the Mac waking.
|
|
96
|
+
*/
|
|
97
|
+
export async function answerAtDoor(request, door, answeredByHeader) {
|
|
98
|
+
const app = new Hono();
|
|
99
|
+
door.sso.mountSsoRoutes(app);
|
|
100
|
+
app.notFound((c) => c.json({ error: "Not found" }, 404, { "cache-control": "no-store" }));
|
|
101
|
+
const res = await app.fetch(request);
|
|
102
|
+
const headers = new Headers(res.headers);
|
|
103
|
+
headers.set(answeredByHeader, "worker");
|
|
104
|
+
return new Response(res.body, { status: res.status, headers });
|
|
105
|
+
}
|
|
106
|
+
/** Hex SHA-256 — WebCrypto, so it runs the same on workerd. */
|
|
107
|
+
export async function sha256Hex(text) {
|
|
108
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
|
|
109
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* A PUBLIC fingerprint of the session secret — `/healthz` publishes it and the app's
|
|
113
|
+
* `worker:secrets` compares it with the Mac's, so a Worker signing with the wrong secret
|
|
114
|
+
* (every Mac-era cookie refused, everybody signed out) is red with no session anywhere.
|
|
115
|
+
* Domain-separated per app, truncated: it names the secret, it cannot stand in for it. `""`
|
|
116
|
+
* when there is none.
|
|
117
|
+
*/
|
|
118
|
+
export async function sessionSecretId(app, secret) {
|
|
119
|
+
const s = secret?.trim() ?? "";
|
|
120
|
+
return s ? (await sha256Hex(`${app}-session-secret-id:${s}`)).slice(0, 16) : "";
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The door's D1 schema — cursedauth's OWN two tables and nothing of the app's, one statement
|
|
124
|
+
* per line (D1's `exec` splits on newlines), every one `IF NOT EXISTS` because a deploy applies
|
|
125
|
+
* it on every ship. An app writes it to `db/schema.sql` and a test holds the file to this.
|
|
126
|
+
*/
|
|
127
|
+
export function relayDoorSchemaSql(app, generator) {
|
|
128
|
+
const statements = `${SESSIONS_DDL}\n${SSO_USERS_DDL}`
|
|
129
|
+
.split(";")
|
|
130
|
+
.map((statement) => statement.replace(/\s+/g, " ").trim())
|
|
131
|
+
.filter((statement) => statement.length > 0);
|
|
132
|
+
return [
|
|
133
|
+
`-- GENERATED by \`${generator}\` from cursedauth's SESSIONS_DDL and SSO_USERS_DDL (cursedauth/relay-door). Do not edit.`,
|
|
134
|
+
`-- ${app}'s Worker door: the sessions and the SSO snapshot, nothing else.`,
|
|
135
|
+
...statements.map((statement) => `${statement};`),
|
|
136
|
+
"",
|
|
137
|
+
].join("\n");
|
|
138
|
+
}
|
|
139
|
+
/** The two SELECTs that read a Mac's rows in {@link MacSessionRow} / {@link MacSsoUserRow} shape. */
|
|
140
|
+
export const MAC_SESSIONS_SELECT = "SELECT id, user_id, expires_at, COALESCE(user_agent, '') AS user_agent, COALESCE(ip, '') AS ip, COALESCE(created_at, 0) AS created_at, COALESCE(last_seen_at, 0) AS last_seen_at, COALESCE(place, '') AS place FROM sessions";
|
|
141
|
+
export const MAC_SSO_USERS_SELECT = "SELECT id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at FROM sso_users";
|
|
142
|
+
const sqlLiteral = (value) => {
|
|
143
|
+
if (value === null || value === undefined)
|
|
144
|
+
return "NULL";
|
|
145
|
+
if (typeof value === "number") {
|
|
146
|
+
if (!Number.isFinite(value))
|
|
147
|
+
throw new Error(`not a finite number: ${value}`);
|
|
148
|
+
return String(value);
|
|
149
|
+
}
|
|
150
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
151
|
+
};
|
|
152
|
+
/**
|
|
153
|
+
* The statements that copy the Mac's rows into the door's D1, pure: every user, then every
|
|
154
|
+
* session still live at `now`. `INSERT OR IGNORE` — a row the door already has (somebody signed
|
|
155
|
+
* in through it since) is never overwritten, and a re-run is a no-op.
|
|
156
|
+
*/
|
|
157
|
+
export function sessionImportStatements(sessions, users, now) {
|
|
158
|
+
const out = [];
|
|
159
|
+
for (const u of users) {
|
|
160
|
+
const values = [u.id, u.email, u.name ?? "", u.is_admin ? 1 : 0, u.is_owner ? 1 : 0, u.is_granted ? 1 : 0, u.last_login_at ?? "", u.created_at, u.updated_at];
|
|
161
|
+
out.push(`INSERT OR IGNORE INTO sso_users (id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at) VALUES (${values.map(sqlLiteral).join(", ")});`);
|
|
162
|
+
}
|
|
163
|
+
for (const s of sessions) {
|
|
164
|
+
if (s.expires_at <= now)
|
|
165
|
+
continue;
|
|
166
|
+
const values = [s.id, s.user_id, s.expires_at, s.user_agent ?? "", s.ip ?? "", s.created_at ?? 0, s.last_seen_at ?? 0, s.place ?? ""];
|
|
167
|
+
out.push(`INSERT OR IGNORE INTO sessions (id, user_id, expires_at, user_agent, ip, created_at, last_seen_at, place) VALUES (${values.map(sqlLiteral).join(", ")});`);
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
// ── the account, signed for the Mac ────────────────────────────────────────
|
|
172
|
+
/** base64url of UTF-8 text or raw bytes — no `Buffer`, so it runs the same on workerd. */
|
|
173
|
+
function base64url(input) {
|
|
174
|
+
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
|
|
175
|
+
let binary = "";
|
|
176
|
+
for (const byte of bytes)
|
|
177
|
+
binary += String.fromCharCode(byte);
|
|
178
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
179
|
+
}
|
|
180
|
+
/** The account as the signed payload carries it — every field, in this order, booleans strict. */
|
|
181
|
+
function identityPayload(user) {
|
|
182
|
+
const account = {
|
|
183
|
+
id: user.id,
|
|
184
|
+
email: user.email,
|
|
185
|
+
name: user.name ?? "",
|
|
186
|
+
isAdmin: user.isAdmin === true,
|
|
187
|
+
isOwner: user.isOwner === true,
|
|
188
|
+
isGranted: user.isGranted === true,
|
|
189
|
+
};
|
|
190
|
+
return base64url(JSON.stringify(account));
|
|
191
|
+
}
|
|
192
|
+
/** The account a VERIFIED payload names, or null for one that does not parse as one. */
|
|
193
|
+
export function accountOf(payloadJson) {
|
|
194
|
+
try {
|
|
195
|
+
const account = JSON.parse(payloadJson);
|
|
196
|
+
if (typeof account.id !== "string" || account.id.length === 0 || typeof account.email !== "string")
|
|
197
|
+
return null;
|
|
198
|
+
return {
|
|
199
|
+
id: account.id,
|
|
200
|
+
email: account.email,
|
|
201
|
+
name: typeof account.name === "string" ? account.name : "",
|
|
202
|
+
isAdmin: account.isAdmin === true,
|
|
203
|
+
isOwner: account.isOwner === true,
|
|
204
|
+
isGranted: account.isGranted === true,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** The cookie VALUE vouching for `user` — WebCrypto HMAC-SHA256. `key` is the link key's SHA-256, hex. */
|
|
212
|
+
export async function signIdentity(user, key) {
|
|
213
|
+
const payload = identityPayload(user);
|
|
214
|
+
const hmac = await crypto.subtle.importKey("raw", new TextEncoder().encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
215
|
+
const tag = new Uint8Array(await crypto.subtle.sign("HMAC", hmac, new TextEncoder().encode(payload)));
|
|
216
|
+
return `${payload}.${base64url(tag)}`;
|
|
217
|
+
}
|
|
218
|
+
/** One cookie's value off a `cookie` header, or null — exact name match, `=` in the value kept. */
|
|
219
|
+
export function cookieValueOf(header, name) {
|
|
220
|
+
for (const part of (header ?? "").split(";")) {
|
|
221
|
+
const eq = part.indexOf("=");
|
|
222
|
+
if (eq > 0 && part.slice(0, eq).trim() === name)
|
|
223
|
+
return part.slice(eq + 1).trim();
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* `request` as the Mac should see it, once the Worker is the door: every `identityCookie` the
|
|
229
|
+
* BROWSER sent removed, the Worker's own appended when it resolved an account — and 🔴 the
|
|
230
|
+
* browser's session cookies in every slot removed too. The Mac falls back to its OWN session
|
|
231
|
+
* rows for a request with no identity, and those rows were imported at the cutover; a cookie
|
|
232
|
+
* the Worker has signed out (its D1 row gone) must not be honoured by the Mac's stale copy.
|
|
233
|
+
* The body, method and every other header ride along.
|
|
234
|
+
*/
|
|
235
|
+
export function withIdentity(request, signed, cookies) {
|
|
236
|
+
const macSessions = new Set(allSlotCookieNames(cookies.sessionCookie));
|
|
237
|
+
const kept = (request.headers.get("cookie") ?? "")
|
|
238
|
+
.split(";")
|
|
239
|
+
.map((part) => part.trim())
|
|
240
|
+
.filter((part) => {
|
|
241
|
+
const name = part.split("=")[0]?.trim() ?? "";
|
|
242
|
+
return part.length > 0 && name !== cookies.identityCookie && !macSessions.has(name);
|
|
243
|
+
});
|
|
244
|
+
if (signed)
|
|
245
|
+
kept.push(`${cookies.identityCookie}=${signed}`);
|
|
246
|
+
const headers = new Headers(request.headers);
|
|
247
|
+
if (kept.length > 0)
|
|
248
|
+
headers.set("cookie", kept.join("; "));
|
|
249
|
+
else
|
|
250
|
+
headers.delete("cookie");
|
|
251
|
+
// 🔴 A NEW request from the parts, never `new Request(request, { headers })`: Bun keeps the
|
|
252
|
+
// original's `cookie` when the new headers have none, so a stripped cookie came back — a
|
|
253
|
+
// browser's forged identity included (roms' `worker/romBytes.test.ts` caught it).
|
|
254
|
+
const init = { method: request.method, headers, redirect: request.redirect };
|
|
255
|
+
if (request.method !== "GET" && request.method !== "HEAD" && request.body) {
|
|
256
|
+
init.body = request.body;
|
|
257
|
+
init.duplex = "half";
|
|
258
|
+
}
|
|
259
|
+
return new Request(request.url, init);
|
|
260
|
+
}
|
|
261
|
+
//# sourceMappingURL=relayDoor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relayDoor.js","sourceRoot":"","sources":["../src/relayDoor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAsC,MAAM,eAAe,CAAC;AAC9G,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAkC,MAAM,yBAAyB,CAAC;AAC7G,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAAE,0BAA0B,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAYlF,uEAAuE;AACvE,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,GAAW,EAAU,EAAE,CAAC,GAAG,GAAG,KAAK,CAAC;AAoCvE,mGAAmG;AACnG,MAAM,UAAU,YAAY,CAAC,OAA8F;IAC1H,IAAI,CAAC,OAAO;QAAE,OAAO,KAAK,CAAC;IAC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AAI,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;IACD,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AACvC,CAAC"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type RequireSession } from "./auth.server.js";
|
|
2
|
+
import { type LinkIdentity } from "./relayDoor.js";
|
|
3
|
+
import type { SsoConsumer, SsoUser } from "./ssoConsumer.server.js";
|
|
4
|
+
export type { LinkIdentity } from "./relayDoor.js";
|
|
5
|
+
/** The link key's SHA-256, hex — exactly the digest the Worker holds as its link secret. */
|
|
6
|
+
export declare const linkKeyDigest: (key: string) => string;
|
|
7
|
+
/**
|
|
8
|
+
* The account an identity cookie value vouches for under `key` (the link key's digest), or null
|
|
9
|
+
* — never throws. The same HMAC-SHA256 the Worker signs with, checked in constant time.
|
|
10
|
+
*/
|
|
11
|
+
export declare function readIdentity(value: string | null | undefined, key: string | null | undefined): LinkIdentity | null;
|
|
12
|
+
export interface LinkIdentityReader {
|
|
13
|
+
/**
|
|
14
|
+
* `fetch`, marking every request it is handed as the link's — hand THIS to the dialer, and
|
|
15
|
+
* the key it dialled with. The mark is a WeakSet of the exact `Request` objects (Hono keeps
|
|
16
|
+
* them as `c.req.raw`); nothing a request can carry can put itself in there.
|
|
17
|
+
*/
|
|
18
|
+
linkFetch(fetch: (request: Request) => Response | Promise<Response>, key: string): (request: Request) => Response | Promise<Response>;
|
|
19
|
+
/** The account the Worker vouches for on `request`, or null: only down the link, only under this link's key. */
|
|
20
|
+
userOf(request: Request): LinkIdentity | null;
|
|
21
|
+
}
|
|
22
|
+
/** One app's reader — `identityCookie` is `<app>_as` (`identityCookieName`). */
|
|
23
|
+
export declare function createLinkIdentityReader(identityCookie: string): LinkIdentityReader;
|
|
24
|
+
export interface LinkGateOptions {
|
|
25
|
+
/** The Mac's own SSO consumer — its gate for every request the Worker did not vouch for. */
|
|
26
|
+
sso: Pick<SsoConsumer, "requireUser" | "authorizeRequest">;
|
|
27
|
+
/** The Worker's word for a request, or null (`LinkIdentityReader.userOf`). */
|
|
28
|
+
linkUser: (request: Request) => LinkIdentity | null;
|
|
29
|
+
/** The claims' scopes for an account — the app's own first, as its consumer sets them. */
|
|
30
|
+
scopes: (user: LinkIdentity) => string[];
|
|
31
|
+
/**
|
|
32
|
+
* The Mac's allow-list, when it has one. The Worker's consumer enforces the same list, so a
|
|
33
|
+
* refusal here means the two disagree — refused all the same (403), never widened.
|
|
34
|
+
*/
|
|
35
|
+
allowedEmails?: string[];
|
|
36
|
+
}
|
|
37
|
+
export interface LinkGate {
|
|
38
|
+
/** The consumer's own gate, with ONE door in front of it: the Worker's word for a link request. */
|
|
39
|
+
requireSession: RequireSession;
|
|
40
|
+
/** The same question for a caller that has only the request (a WebSocket upgrade). */
|
|
41
|
+
authorizeRequest(request: Request): SsoUser | LinkIdentity | null;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The Mac's gate once the Worker is the door. Everything the consumer's `requireUser` does after
|
|
45
|
+
* it has a user is done here the same way — the account-drift 409, the claims `userOf` reads —
|
|
46
|
+
* so a route cannot tell which door admitted the request. Null falls through to the Mac's own
|
|
47
|
+
* sessions: the local listener, dev, the rehearsals.
|
|
48
|
+
*/
|
|
49
|
+
export declare function createLinkGate(options: LinkGateOptions): LinkGate;
|
|
50
|
+
//# sourceMappingURL=relayIdentity.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relayIdentity.d.ts","sourceRoot":"","sources":["../src/relayIdentity.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,KAAK,cAAc,EAAsB,MAAM,kBAAkB,CAAC;AAE3E,OAAO,EAA4B,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAEpE,YAAY,EAAE,YAAY,EAAE,MAAM,gBAAgB,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AAe,GAAG,QAAQ,CAuBjE"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The MAC's half of a relay app's Worker door — `cursedauth/relay-identity`.
|
|
3
|
+
*
|
|
4
|
+
* `./relayDoor.ts` has the whole shape. Here: the Mac believes the Worker's signed account
|
|
5
|
+
* ({@link LinkIdentity} in `<app>_as`) only on a request that came DOWN THE LINK, only under
|
|
6
|
+
* the SHA-256 of the key this process dialled with — and turns it into the same session claims
|
|
7
|
+
* the SSO consumer's own gate sets, so a route cannot tell which door admitted a request.
|
|
8
|
+
*
|
|
9
|
+
* Synchronous with `node:crypto`, because a presence door asks its question synchronously; the
|
|
10
|
+
* Worker signs with WebCrypto, and `relayDoor.test.ts` holds the two to the same bytes. A Mac
|
|
11
|
+
* process only — a Worker never imports this.
|
|
12
|
+
*/
|
|
13
|
+
import { createHash, createHmac } from "node:crypto";
|
|
14
|
+
import { ACCOUNT_DRIFT_STATUS, ACCOUNT_USER_HEADER, accountDriftBody, isAccountDrift } from "./accountSlots.js";
|
|
15
|
+
import { SESSION_CLAIMS_KEY } from "./auth.server.js";
|
|
16
|
+
import { constantTimeEqual } from "./constantTime.js";
|
|
17
|
+
import { accountOf, cookieValueOf } from "./relayDoor.js";
|
|
18
|
+
/** The link key's SHA-256, hex — exactly the digest the Worker holds as its link secret. */
|
|
19
|
+
export const linkKeyDigest = (key) => createHash("sha256").update(key).digest("hex");
|
|
20
|
+
/**
|
|
21
|
+
* The account an identity cookie value vouches for under `key` (the link key's digest), or null
|
|
22
|
+
* — never throws. The same HMAC-SHA256 the Worker signs with, checked in constant time.
|
|
23
|
+
*/
|
|
24
|
+
export function readIdentity(value, key) {
|
|
25
|
+
if (!value || !key)
|
|
26
|
+
return null;
|
|
27
|
+
const dot = value.indexOf(".");
|
|
28
|
+
if (dot <= 0 || dot !== value.lastIndexOf("."))
|
|
29
|
+
return null;
|
|
30
|
+
const payload = value.slice(0, dot);
|
|
31
|
+
const want = createHmac("sha256", key).update(payload).digest("base64url");
|
|
32
|
+
if (!constantTimeEqual(value.slice(dot + 1), want))
|
|
33
|
+
return null;
|
|
34
|
+
return accountOf(Buffer.from(payload, "base64url").toString("utf8"));
|
|
35
|
+
}
|
|
36
|
+
/** One app's reader — `identityCookie` is `<app>_as` (`identityCookieName`). */
|
|
37
|
+
export function createLinkIdentityReader(identityCookie) {
|
|
38
|
+
const viaLink = new WeakSet();
|
|
39
|
+
let key = null;
|
|
40
|
+
return {
|
|
41
|
+
linkFetch(fetch, linkKey) {
|
|
42
|
+
key = linkKeyDigest(linkKey);
|
|
43
|
+
return (request) => {
|
|
44
|
+
viaLink.add(request);
|
|
45
|
+
return fetch(request);
|
|
46
|
+
};
|
|
47
|
+
},
|
|
48
|
+
userOf(request) {
|
|
49
|
+
if (!viaLink.has(request))
|
|
50
|
+
return null;
|
|
51
|
+
return readIdentity(cookieValueOf(request.headers.get("cookie"), identityCookie), key);
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The Mac's gate once the Worker is the door. Everything the consumer's `requireUser` does after
|
|
57
|
+
* it has a user is done here the same way — the account-drift 409, the claims `userOf` reads —
|
|
58
|
+
* so a route cannot tell which door admitted the request. Null falls through to the Mac's own
|
|
59
|
+
* sessions: the local listener, dev, the rehearsals.
|
|
60
|
+
*/
|
|
61
|
+
export function createLinkGate(options) {
|
|
62
|
+
const allowed = options.allowedEmails ? new Set(options.allowedEmails.map((e) => e.trim().toLowerCase()).filter(Boolean)) : null;
|
|
63
|
+
const admitted = (user) => (user && (!allowed || allowed.has(user.email.trim().toLowerCase())) ? user : null);
|
|
64
|
+
const requireSession = async (c, next) => {
|
|
65
|
+
const vouched = options.linkUser(c.req.raw);
|
|
66
|
+
if (!vouched)
|
|
67
|
+
return options.sso.requireUser(c, next);
|
|
68
|
+
const user = admitted(vouched);
|
|
69
|
+
if (!user)
|
|
70
|
+
return c.json({ error: "This account may not use this app" }, 403, { "cache-control": "no-store" });
|
|
71
|
+
const raw = c.req.raw.headers.get(ACCOUNT_USER_HEADER)?.trim() ?? "";
|
|
72
|
+
const expected = raw.length > 0 && raw.length <= 200 ? raw : null;
|
|
73
|
+
if (isAccountDrift(expected, user.id)) {
|
|
74
|
+
return c.json(accountDriftBody(expected ?? "", { id: user.id, email: user.email, name: user.name }), ACCOUNT_DRIFT_STATUS, { "cache-control": "no-store" });
|
|
75
|
+
}
|
|
76
|
+
c.set(SESSION_CLAIMS_KEY, { userId: user.id, tenantId: "default", scopes: options.scopes(user), ssoUser: user });
|
|
77
|
+
await next();
|
|
78
|
+
};
|
|
79
|
+
return {
|
|
80
|
+
requireSession,
|
|
81
|
+
authorizeRequest: (request) => {
|
|
82
|
+
const vouched = options.linkUser(request);
|
|
83
|
+
return vouched ? admitted(vouched) : options.sso.authorizeRequest(request);
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
//# sourceMappingURL=relayIdentity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relayIdentity.js","sourceRoot":"","sources":["../src/relayIdentity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAChH,OAAO,EAAuB,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,aAAa,EAAqB,MAAM,gBAAgB,CAAC;AAK7E,4FAA4F;AAC5F,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,GAAW,EAAU,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,C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
|
{
|
|
2
2
|
"name": "cursedauth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "The app side of fleet SSO — sign in through the accounts service, keep a local snapshot of who signed in, and gate the app on it. Bun + Hono + React, one SQLite file per app.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -113,6 +113,18 @@
|
|
|
113
113
|
"source": "./src/offlineGrant.ts",
|
|
114
114
|
"import": "./dist/offlineGrant.js"
|
|
115
115
|
},
|
|
116
|
+
"./relay-door": {
|
|
117
|
+
"types": "./dist/relayDoor.d.ts",
|
|
118
|
+
"bun": "./src/relayDoor.ts",
|
|
119
|
+
"source": "./src/relayDoor.ts",
|
|
120
|
+
"import": "./dist/relayDoor.js"
|
|
121
|
+
},
|
|
122
|
+
"./relay-identity": {
|
|
123
|
+
"types": "./dist/relayIdentity.d.ts",
|
|
124
|
+
"bun": "./src/relayIdentity.ts",
|
|
125
|
+
"source": "./src/relayIdentity.ts",
|
|
126
|
+
"import": "./dist/relayIdentity.js"
|
|
127
|
+
},
|
|
116
128
|
"./package.json": "./package.json"
|
|
117
129
|
},
|
|
118
130
|
"files": [
|
package/src/relayDoor.ts
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DOOR of a relay app, on its Worker — `cursedauth/relay-door`.
|
|
3
|
+
*
|
|
4
|
+
* A relay app (`cursedops/relay`) is one whose Worker hands every API request down a WebSocket
|
|
5
|
+
* the Mac dialled out. Until its Worker is the door, the gate is the Mac's: with the Mac off
|
|
6
|
+
* nobody can sign in, and a signed-in browser reads what the relay kept for exactly as long as
|
|
7
|
+
* its one session cookie lives. `apps/roms` moved its door onto the Worker on 2026-09-26
|
|
8
|
+
* (roms `726710a`) and proved it on its stage (a fresh 2FA sign-in with the Mac stopped reads
|
|
9
|
+
* the library); this module is that move lifted, so the next relay app takes it in data rather
|
|
10
|
+
* than in 1,200 copied lines.
|
|
11
|
+
*
|
|
12
|
+
* ## The shape
|
|
13
|
+
*
|
|
14
|
+
* · The Worker is the SSO consumer over its own two D1 tables ({@link relayDoorSchemaSql}:
|
|
15
|
+
* cursedauth's `sessions` and `sso_users`, nothing of the app's). `/api/auth/*` is answered
|
|
16
|
+
* there ({@link relayDoorAnswers}) — except the content CENSUS, which counts what lives on
|
|
17
|
+
* the Mac and so is relayed.
|
|
18
|
+
* · Every relayed request is resolved against those sessions and handed to the Mac with the
|
|
19
|
+
* account signed into ONE cookie ({@link signIdentity}, {@link withIdentity}):
|
|
20
|
+
*
|
|
21
|
+
* <app>_as=<base64url(JSON account)>.<base64url(HMAC-SHA256(key, payload))>
|
|
22
|
+
*
|
|
23
|
+
* A cookie, not a header, because the relay's offline cache keys what it keeps on a cookie
|
|
24
|
+
* and replays its wake-up reads with that cookie alone — keyed on this one, what is kept is
|
|
25
|
+
* the ACCOUNT's, so a fresh sign-in on a new device with the Mac off still reads it.
|
|
26
|
+
* · The Mac believes that cookie ONLY on a request that came down the link, under the SHA-256
|
|
27
|
+
* of the link key it dialled with (`cursedauth/relay-identity`) — the Worker holds exactly
|
|
28
|
+
* that digest as its link secret, and nobody else holds either.
|
|
29
|
+
* · The Worker strips the browser's own `<app>_as` and every `<session>*` slot cookie before
|
|
30
|
+
* it signs its own, so a browser can neither forge an account nor have a session the door
|
|
31
|
+
* ended honoured by the Mac's stale copy of the same row.
|
|
32
|
+
*
|
|
33
|
+
* Deterministic on purpose — no timestamp, no nonce: the same account must sign to the same
|
|
34
|
+
* value every time, or the relay's cache would key every request apart. Its lifetime is not
|
|
35
|
+
* its own: the Worker re-checks the SESSION on every request before it signs.
|
|
36
|
+
*
|
|
37
|
+
* 🔴 Worker-safe: WebCrypto only, no `bun:*`, no `node:` import of its own
|
|
38
|
+
* (`subpathsReachNoBunBuiltin.test.ts`). The Mac's half verifies synchronously with
|
|
39
|
+
* `node:crypto` and lives in `./relayIdentity.ts`; `relayDoor.test.ts` holds the two to the
|
|
40
|
+
* same bytes.
|
|
41
|
+
*
|
|
42
|
+
* 🔴 No session secret, no door: {@link createRelayDoor} answers null and the app relays as it
|
|
43
|
+
* did before. A Worker that invented a secret would sign everybody out on every deploy or sign
|
|
44
|
+
* cookies anybody could forge.
|
|
45
|
+
*/
|
|
46
|
+
import { Hono } from "hono";
|
|
47
|
+
import { allSlotCookieNames } from "./accountSlots.js";
|
|
48
|
+
import { createD1SessionRows, createD1SsoUserStore, type D1Handle, type WriteCollector } from "./d1Stores.js";
|
|
49
|
+
import { createSsoConsumer, SSO_CENSUS_PATH, type SsoConsumer, type SsoUser } from "./ssoConsumer.server.js";
|
|
50
|
+
import { SSO_USERS_DDL } from "./ssoUsers.js";
|
|
51
|
+
import { createUserSessionStoreOver, SESSIONS_DDL } from "./userSessions.core.js";
|
|
52
|
+
|
|
53
|
+
/** The account the Worker vouches for — `SsoUser`, field for field. */
|
|
54
|
+
export interface LinkIdentity {
|
|
55
|
+
id: string;
|
|
56
|
+
email: string;
|
|
57
|
+
name: string;
|
|
58
|
+
isAdmin: boolean;
|
|
59
|
+
isOwner: boolean;
|
|
60
|
+
isGranted: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The identity cookie's name for an app — `roms_as`, `station_as`. */
|
|
64
|
+
export const identityCookieName = (app: string): string => `${app}_as`;
|
|
65
|
+
|
|
66
|
+
// ── the door ────────────────────────────────────────────────────────────────
|
|
67
|
+
|
|
68
|
+
export interface RelayDoorOptions {
|
|
69
|
+
/** The app's name — the consumer's, the identity cookie's prefix, the secret fingerprint's domain. */
|
|
70
|
+
app: string;
|
|
71
|
+
/** The Mac's session cookie name, unchanged, so the cutover carries sessions across. */
|
|
72
|
+
cookieName: string;
|
|
73
|
+
/** The session secret — the Mac's own, so a Mac-era cookie verifies at the door. Blank → no door. */
|
|
74
|
+
sessionSecret: string | undefined;
|
|
75
|
+
/** The Mac's session TTL — never widened by the move: an expired session is a sign-in away, Mac or no Mac. */
|
|
76
|
+
sessionTtlSeconds: number;
|
|
77
|
+
/** The accounts service's origin (`https://auth.cursedalchemy.com`, or auth-stage's). */
|
|
78
|
+
authUrl: string;
|
|
79
|
+
/** This app's own public origin. */
|
|
80
|
+
publicUrl: string;
|
|
81
|
+
/** The audiences this app answers to — the Mac's list. */
|
|
82
|
+
registeredAudiences: readonly string[];
|
|
83
|
+
/** The Mac's allow-list, when it has one — enforced at the Worker's callback AND per request. */
|
|
84
|
+
allowedEmails?: string[];
|
|
85
|
+
/** Admin-or-granted only, when the Mac's consumer says so. */
|
|
86
|
+
requireAdmin?: boolean;
|
|
87
|
+
/** A static grant-verification key (tests); unset → auth's live JWKS through {@link fetchImpl}. */
|
|
88
|
+
publicKeyPem?: string;
|
|
89
|
+
/**
|
|
90
|
+
* How JWKS refreshes reach auth — 🔴 a Service Binding's `fetch` (task 2150): a same-zone
|
|
91
|
+
* subrequest to `auth.cursedalchemy.com` falls through to the zone's origin, the Mac's tunnel.
|
|
92
|
+
*/
|
|
93
|
+
fetchImpl?: typeof fetch;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface RelayDoor {
|
|
97
|
+
sso: SsoConsumer;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The fetch for a Service Binding named e.g. `AUTH`, or the global `fetch` when there is none. */
|
|
101
|
+
export function bindingFetch(binding: { fetch(input: Request | string, init?: RequestInit): Promise<Response> } | undefined): typeof fetch {
|
|
102
|
+
if (!binding) return fetch;
|
|
103
|
+
return ((input: RequestInfo | URL, init?: RequestInit) => binding.fetch(input as Request | string, init)) as typeof fetch;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The door for ONE invocation — two D1 reads (the `sessions` and `sso_users` snapshots); every
|
|
108
|
+
* write they collect goes to `writes`, which the caller settles before the response leaves.
|
|
109
|
+
* Null when there is no session secret.
|
|
110
|
+
*/
|
|
111
|
+
export async function createRelayDoor(options: RelayDoorOptions, db: D1Handle, writes: WriteCollector): Promise<RelayDoor | null> {
|
|
112
|
+
const secret = options.sessionSecret?.trim() ?? "";
|
|
113
|
+
if (!secret) return null;
|
|
114
|
+
const now = Date.now();
|
|
115
|
+
const sessions = createUserSessionStoreOver(await createD1SessionRows(db, writes, { now }), {
|
|
116
|
+
cookieName: options.cookieName,
|
|
117
|
+
sessionSecret: secret,
|
|
118
|
+
sessionTtlSeconds: options.sessionTtlSeconds,
|
|
119
|
+
});
|
|
120
|
+
const sso = createSsoConsumer({
|
|
121
|
+
app: options.app,
|
|
122
|
+
authUrl: options.authUrl.replace(/\/$/, ""),
|
|
123
|
+
publicUrl: options.publicUrl.replace(/\/$/, ""),
|
|
124
|
+
sessions,
|
|
125
|
+
users: await createD1SsoUserStore(db, writes, { now }),
|
|
126
|
+
registeredAudiences: options.registeredAudiences,
|
|
127
|
+
...(options.allowedEmails ? { allowedEmails: options.allowedEmails } : {}),
|
|
128
|
+
...(options.requireAdmin ? { requireAdmin: true } : {}),
|
|
129
|
+
...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
|
|
130
|
+
...(options.publicKeyPem?.trim() ? { publicKeyPem: options.publicKeyPem.trim() } : {}),
|
|
131
|
+
});
|
|
132
|
+
return { sso };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Answered by the Worker's door rather than relayed: every `/api/auth/*` but the census. */
|
|
136
|
+
export function relayDoorAnswers(path: string): boolean {
|
|
137
|
+
return path.startsWith("/api/auth/") && path !== SSO_CENSUS_PATH;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The door's own answer to `/api/auth/*`, marked with `answeredByHeader: worker` so a client
|
|
142
|
+
* never reads the Worker's word as the Mac waking.
|
|
143
|
+
*/
|
|
144
|
+
export async function answerAtDoor(request: Request, door: RelayDoor, answeredByHeader: string): Promise<Response> {
|
|
145
|
+
const app = new Hono();
|
|
146
|
+
door.sso.mountSsoRoutes(app);
|
|
147
|
+
app.notFound((c) => c.json({ error: "Not found" }, 404, { "cache-control": "no-store" }));
|
|
148
|
+
const res = await app.fetch(request);
|
|
149
|
+
const headers = new Headers(res.headers);
|
|
150
|
+
headers.set(answeredByHeader, "worker");
|
|
151
|
+
return new Response(res.body, { status: res.status, headers });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Hex SHA-256 — WebCrypto, so it runs the same on workerd. */
|
|
155
|
+
export async function sha256Hex(text: string): Promise<string> {
|
|
156
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
|
|
157
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* A PUBLIC fingerprint of the session secret — `/healthz` publishes it and the app's
|
|
162
|
+
* `worker:secrets` compares it with the Mac's, so a Worker signing with the wrong secret
|
|
163
|
+
* (every Mac-era cookie refused, everybody signed out) is red with no session anywhere.
|
|
164
|
+
* Domain-separated per app, truncated: it names the secret, it cannot stand in for it. `""`
|
|
165
|
+
* when there is none.
|
|
166
|
+
*/
|
|
167
|
+
export async function sessionSecretId(app: string, secret: string | undefined): Promise<string> {
|
|
168
|
+
const s = secret?.trim() ?? "";
|
|
169
|
+
return s ? (await sha256Hex(`${app}-session-secret-id:${s}`)).slice(0, 16) : "";
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The door's D1 schema — cursedauth's OWN two tables and nothing of the app's, one statement
|
|
174
|
+
* per line (D1's `exec` splits on newlines), every one `IF NOT EXISTS` because a deploy applies
|
|
175
|
+
* it on every ship. An app writes it to `db/schema.sql` and a test holds the file to this.
|
|
176
|
+
*/
|
|
177
|
+
export function relayDoorSchemaSql(app: string, generator: string): string {
|
|
178
|
+
const statements = `${SESSIONS_DDL}\n${SSO_USERS_DDL}`
|
|
179
|
+
.split(";")
|
|
180
|
+
.map((statement) => statement.replace(/\s+/g, " ").trim())
|
|
181
|
+
.filter((statement) => statement.length > 0);
|
|
182
|
+
return [
|
|
183
|
+
`-- GENERATED by \`${generator}\` from cursedauth's SESSIONS_DDL and SSO_USERS_DDL (cursedauth/relay-door). Do not edit.`,
|
|
184
|
+
`-- ${app}'s Worker door: the sessions and the SSO snapshot, nothing else.`,
|
|
185
|
+
...statements.map((statement) => `${statement};`),
|
|
186
|
+
"",
|
|
187
|
+
].join("\n");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ── the cutover: the Mac's live rows into the door's D1 ────────────────────
|
|
191
|
+
|
|
192
|
+
/** A row of the Mac's `sessions` table. */
|
|
193
|
+
export interface MacSessionRow {
|
|
194
|
+
id: string;
|
|
195
|
+
user_id: string;
|
|
196
|
+
expires_at: number;
|
|
197
|
+
user_agent: string;
|
|
198
|
+
ip: string;
|
|
199
|
+
created_at: number;
|
|
200
|
+
last_seen_at: number;
|
|
201
|
+
place: string;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** A row of the Mac's `sso_users` table. */
|
|
205
|
+
export interface MacSsoUserRow {
|
|
206
|
+
id: string;
|
|
207
|
+
email: string;
|
|
208
|
+
name: string;
|
|
209
|
+
is_admin: number;
|
|
210
|
+
is_owner: number;
|
|
211
|
+
is_granted: number;
|
|
212
|
+
last_login_at: string;
|
|
213
|
+
created_at: string;
|
|
214
|
+
updated_at: string;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** The two SELECTs that read a Mac's rows in {@link MacSessionRow} / {@link MacSsoUserRow} shape. */
|
|
218
|
+
export const MAC_SESSIONS_SELECT =
|
|
219
|
+
"SELECT id, user_id, expires_at, COALESCE(user_agent, '') AS user_agent, COALESCE(ip, '') AS ip, COALESCE(created_at, 0) AS created_at, COALESCE(last_seen_at, 0) AS last_seen_at, COALESCE(place, '') AS place FROM sessions";
|
|
220
|
+
export const MAC_SSO_USERS_SELECT = "SELECT id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at FROM sso_users";
|
|
221
|
+
|
|
222
|
+
const sqlLiteral = (value: string | number | null | undefined): string => {
|
|
223
|
+
if (value === null || value === undefined) return "NULL";
|
|
224
|
+
if (typeof value === "number") {
|
|
225
|
+
if (!Number.isFinite(value)) throw new Error(`not a finite number: ${value}`);
|
|
226
|
+
return String(value);
|
|
227
|
+
}
|
|
228
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The statements that copy the Mac's rows into the door's D1, pure: every user, then every
|
|
233
|
+
* session still live at `now`. `INSERT OR IGNORE` — a row the door already has (somebody signed
|
|
234
|
+
* in through it since) is never overwritten, and a re-run is a no-op.
|
|
235
|
+
*/
|
|
236
|
+
export function sessionImportStatements(sessions: readonly MacSessionRow[], users: readonly MacSsoUserRow[], now: number): string[] {
|
|
237
|
+
const out: string[] = [];
|
|
238
|
+
for (const u of users) {
|
|
239
|
+
const values = [u.id, u.email, u.name ?? "", u.is_admin ? 1 : 0, u.is_owner ? 1 : 0, u.is_granted ? 1 : 0, u.last_login_at ?? "", u.created_at, u.updated_at];
|
|
240
|
+
out.push(`INSERT OR IGNORE INTO sso_users (id, email, name, is_admin, is_owner, is_granted, last_login_at, created_at, updated_at) VALUES (${values.map(sqlLiteral).join(", ")});`);
|
|
241
|
+
}
|
|
242
|
+
for (const s of sessions) {
|
|
243
|
+
if (s.expires_at <= now) continue;
|
|
244
|
+
const values = [s.id, s.user_id, s.expires_at, s.user_agent ?? "", s.ip ?? "", s.created_at ?? 0, s.last_seen_at ?? 0, s.place ?? ""];
|
|
245
|
+
out.push(`INSERT OR IGNORE INTO sessions (id, user_id, expires_at, user_agent, ip, created_at, last_seen_at, place) VALUES (${values.map(sqlLiteral).join(", ")});`);
|
|
246
|
+
}
|
|
247
|
+
return out;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ── the account, signed for the Mac ────────────────────────────────────────
|
|
251
|
+
|
|
252
|
+
/** base64url of UTF-8 text or raw bytes — no `Buffer`, so it runs the same on workerd. */
|
|
253
|
+
function base64url(input: string | Uint8Array): string {
|
|
254
|
+
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
|
|
255
|
+
let binary = "";
|
|
256
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
257
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** The account as the signed payload carries it — every field, in this order, booleans strict. */
|
|
261
|
+
function identityPayload(user: LinkIdentity | SsoUser): string {
|
|
262
|
+
const account: LinkIdentity = {
|
|
263
|
+
id: user.id,
|
|
264
|
+
email: user.email,
|
|
265
|
+
name: user.name ?? "",
|
|
266
|
+
isAdmin: user.isAdmin === true,
|
|
267
|
+
isOwner: user.isOwner === true,
|
|
268
|
+
isGranted: user.isGranted === true,
|
|
269
|
+
};
|
|
270
|
+
return base64url(JSON.stringify(account));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** The account a VERIFIED payload names, or null for one that does not parse as one. */
|
|
274
|
+
export function accountOf(payloadJson: string): LinkIdentity | null {
|
|
275
|
+
try {
|
|
276
|
+
const account = JSON.parse(payloadJson) as Partial<LinkIdentity>;
|
|
277
|
+
if (typeof account.id !== "string" || account.id.length === 0 || typeof account.email !== "string") return null;
|
|
278
|
+
return {
|
|
279
|
+
id: account.id,
|
|
280
|
+
email: account.email,
|
|
281
|
+
name: typeof account.name === "string" ? account.name : "",
|
|
282
|
+
isAdmin: account.isAdmin === true,
|
|
283
|
+
isOwner: account.isOwner === true,
|
|
284
|
+
isGranted: account.isGranted === true,
|
|
285
|
+
};
|
|
286
|
+
} catch {
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The cookie VALUE vouching for `user` — WebCrypto HMAC-SHA256. `key` is the link key's SHA-256, hex. */
|
|
292
|
+
export async function signIdentity(user: LinkIdentity | SsoUser, key: string): Promise<string> {
|
|
293
|
+
const payload = identityPayload(user);
|
|
294
|
+
const hmac = await crypto.subtle.importKey("raw", new TextEncoder().encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
295
|
+
const tag = new Uint8Array(await crypto.subtle.sign("HMAC", hmac, new TextEncoder().encode(payload)));
|
|
296
|
+
return `${payload}.${base64url(tag)}`;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** One cookie's value off a `cookie` header, or null — exact name match, `=` in the value kept. */
|
|
300
|
+
export function cookieValueOf(header: string | null, name: string): string | null {
|
|
301
|
+
for (const part of (header ?? "").split(";")) {
|
|
302
|
+
const eq = part.indexOf("=");
|
|
303
|
+
if (eq > 0 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
|
|
304
|
+
}
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* `request` as the Mac should see it, once the Worker is the door: every `identityCookie` the
|
|
310
|
+
* BROWSER sent removed, the Worker's own appended when it resolved an account — and 🔴 the
|
|
311
|
+
* browser's session cookies in every slot removed too. The Mac falls back to its OWN session
|
|
312
|
+
* rows for a request with no identity, and those rows were imported at the cutover; a cookie
|
|
313
|
+
* the Worker has signed out (its D1 row gone) must not be honoured by the Mac's stale copy.
|
|
314
|
+
* The body, method and every other header ride along.
|
|
315
|
+
*/
|
|
316
|
+
export function withIdentity(request: Request, signed: string | null, cookies: { identityCookie: string; sessionCookie: string }): Request {
|
|
317
|
+
const macSessions = new Set(allSlotCookieNames(cookies.sessionCookie));
|
|
318
|
+
const kept = (request.headers.get("cookie") ?? "")
|
|
319
|
+
.split(";")
|
|
320
|
+
.map((part) => part.trim())
|
|
321
|
+
.filter((part) => {
|
|
322
|
+
const name = part.split("=")[0]?.trim() ?? "";
|
|
323
|
+
return part.length > 0 && name !== cookies.identityCookie && !macSessions.has(name);
|
|
324
|
+
});
|
|
325
|
+
if (signed) kept.push(`${cookies.identityCookie}=${signed}`);
|
|
326
|
+
const headers = new Headers(request.headers);
|
|
327
|
+
if (kept.length > 0) headers.set("cookie", kept.join("; "));
|
|
328
|
+
else headers.delete("cookie");
|
|
329
|
+
// 🔴 A NEW request from the parts, never `new Request(request, { headers })`: Bun keeps the
|
|
330
|
+
// original's `cookie` when the new headers have none, so a stripped cookie came back — a
|
|
331
|
+
// browser's forged identity included (roms' `worker/romBytes.test.ts` caught it).
|
|
332
|
+
const init: RequestInit & { duplex?: "half" } = { method: request.method, headers, redirect: request.redirect };
|
|
333
|
+
if (request.method !== "GET" && request.method !== "HEAD" && request.body) {
|
|
334
|
+
init.body = request.body;
|
|
335
|
+
init.duplex = "half";
|
|
336
|
+
}
|
|
337
|
+
return new Request(request.url, init);
|
|
338
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The MAC's half of a relay app's Worker door — `cursedauth/relay-identity`.
|
|
3
|
+
*
|
|
4
|
+
* `./relayDoor.ts` has the whole shape. Here: the Mac believes the Worker's signed account
|
|
5
|
+
* ({@link LinkIdentity} in `<app>_as`) only on a request that came DOWN THE LINK, only under
|
|
6
|
+
* the SHA-256 of the key this process dialled with — and turns it into the same session claims
|
|
7
|
+
* the SSO consumer's own gate sets, so a route cannot tell which door admitted a request.
|
|
8
|
+
*
|
|
9
|
+
* Synchronous with `node:crypto`, because a presence door asks its question synchronously; the
|
|
10
|
+
* Worker signs with WebCrypto, and `relayDoor.test.ts` holds the two to the same bytes. A Mac
|
|
11
|
+
* process only — a Worker never imports this.
|
|
12
|
+
*/
|
|
13
|
+
import { createHash, createHmac } from "node:crypto";
|
|
14
|
+
import { ACCOUNT_DRIFT_STATUS, ACCOUNT_USER_HEADER, accountDriftBody, isAccountDrift } from "./accountSlots.js";
|
|
15
|
+
import { type RequireSession, SESSION_CLAIMS_KEY } from "./auth.server.js";
|
|
16
|
+
import { constantTimeEqual } from "./constantTime.js";
|
|
17
|
+
import { accountOf, cookieValueOf, type LinkIdentity } from "./relayDoor.js";
|
|
18
|
+
import type { SsoConsumer, SsoUser } from "./ssoConsumer.server.js";
|
|
19
|
+
|
|
20
|
+
export type { LinkIdentity } from "./relayDoor.js";
|
|
21
|
+
|
|
22
|
+
/** The link key's SHA-256, hex — exactly the digest the Worker holds as its link secret. */
|
|
23
|
+
export const linkKeyDigest = (key: string): string => createHash("sha256").update(key).digest("hex");
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The account an identity cookie value vouches for under `key` (the link key's digest), or null
|
|
27
|
+
* — never throws. The same HMAC-SHA256 the Worker signs with, checked in constant time.
|
|
28
|
+
*/
|
|
29
|
+
export function readIdentity(value: string | null | undefined, key: string | null | undefined): LinkIdentity | null {
|
|
30
|
+
if (!value || !key) return null;
|
|
31
|
+
const dot = value.indexOf(".");
|
|
32
|
+
if (dot <= 0 || dot !== value.lastIndexOf(".")) return null;
|
|
33
|
+
const payload = value.slice(0, dot);
|
|
34
|
+
const want = createHmac("sha256", key).update(payload).digest("base64url");
|
|
35
|
+
if (!constantTimeEqual(value.slice(dot + 1), want)) return null;
|
|
36
|
+
return accountOf(Buffer.from(payload, "base64url").toString("utf8"));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface LinkIdentityReader {
|
|
40
|
+
/**
|
|
41
|
+
* `fetch`, marking every request it is handed as the link's — hand THIS to the dialer, and
|
|
42
|
+
* the key it dialled with. The mark is a WeakSet of the exact `Request` objects (Hono keeps
|
|
43
|
+
* them as `c.req.raw`); nothing a request can carry can put itself in there.
|
|
44
|
+
*/
|
|
45
|
+
linkFetch(fetch: (request: Request) => Response | Promise<Response>, key: string): (request: Request) => Response | Promise<Response>;
|
|
46
|
+
/** The account the Worker vouches for on `request`, or null: only down the link, only under this link's key. */
|
|
47
|
+
userOf(request: Request): LinkIdentity | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One app's reader — `identityCookie` is `<app>_as` (`identityCookieName`). */
|
|
51
|
+
export function createLinkIdentityReader(identityCookie: string): LinkIdentityReader {
|
|
52
|
+
const viaLink = new WeakSet<Request>();
|
|
53
|
+
let key: string | null = null;
|
|
54
|
+
return {
|
|
55
|
+
linkFetch(fetch, linkKey) {
|
|
56
|
+
key = linkKeyDigest(linkKey);
|
|
57
|
+
return (request) => {
|
|
58
|
+
viaLink.add(request);
|
|
59
|
+
return fetch(request);
|
|
60
|
+
};
|
|
61
|
+
},
|
|
62
|
+
userOf(request) {
|
|
63
|
+
if (!viaLink.has(request)) return null;
|
|
64
|
+
return readIdentity(cookieValueOf(request.headers.get("cookie"), identityCookie), key);
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface LinkGateOptions {
|
|
70
|
+
/** The Mac's own SSO consumer — its gate for every request the Worker did not vouch for. */
|
|
71
|
+
sso: Pick<SsoConsumer, "requireUser" | "authorizeRequest">;
|
|
72
|
+
/** The Worker's word for a request, or null (`LinkIdentityReader.userOf`). */
|
|
73
|
+
linkUser: (request: Request) => LinkIdentity | null;
|
|
74
|
+
/** The claims' scopes for an account — the app's own first, as its consumer sets them. */
|
|
75
|
+
scopes: (user: LinkIdentity) => string[];
|
|
76
|
+
/**
|
|
77
|
+
* The Mac's allow-list, when it has one. The Worker's consumer enforces the same list, so a
|
|
78
|
+
* refusal here means the two disagree — refused all the same (403), never widened.
|
|
79
|
+
*/
|
|
80
|
+
allowedEmails?: string[];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface LinkGate {
|
|
84
|
+
/** The consumer's own gate, with ONE door in front of it: the Worker's word for a link request. */
|
|
85
|
+
requireSession: RequireSession;
|
|
86
|
+
/** The same question for a caller that has only the request (a WebSocket upgrade). */
|
|
87
|
+
authorizeRequest(request: Request): SsoUser | LinkIdentity | null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The Mac's gate once the Worker is the door. Everything the consumer's `requireUser` does after
|
|
92
|
+
* it has a user is done here the same way — the account-drift 409, the claims `userOf` reads —
|
|
93
|
+
* so a route cannot tell which door admitted the request. Null falls through to the Mac's own
|
|
94
|
+
* sessions: the local listener, dev, the rehearsals.
|
|
95
|
+
*/
|
|
96
|
+
export function createLinkGate(options: LinkGateOptions): LinkGate {
|
|
97
|
+
const allowed = options.allowedEmails ? new Set(options.allowedEmails.map((e) => e.trim().toLowerCase()).filter(Boolean)) : null;
|
|
98
|
+
const admitted = (user: LinkIdentity | null): LinkIdentity | null => (user && (!allowed || allowed.has(user.email.trim().toLowerCase())) ? user : null);
|
|
99
|
+
const requireSession: RequireSession = async (c, next) => {
|
|
100
|
+
const vouched = options.linkUser(c.req.raw);
|
|
101
|
+
if (!vouched) return options.sso.requireUser(c, next);
|
|
102
|
+
const user = admitted(vouched);
|
|
103
|
+
if (!user) return c.json({ error: "This account may not use this app" }, 403, { "cache-control": "no-store" });
|
|
104
|
+
const raw = c.req.raw.headers.get(ACCOUNT_USER_HEADER)?.trim() ?? "";
|
|
105
|
+
const expected = raw.length > 0 && raw.length <= 200 ? raw : null;
|
|
106
|
+
if (isAccountDrift(expected, user.id)) {
|
|
107
|
+
return c.json(accountDriftBody(expected ?? "", { id: user.id, email: user.email, name: user.name }), ACCOUNT_DRIFT_STATUS, { "cache-control": "no-store" });
|
|
108
|
+
}
|
|
109
|
+
c.set(SESSION_CLAIMS_KEY, { userId: user.id, tenantId: "default", scopes: options.scopes(user), ssoUser: user });
|
|
110
|
+
await next();
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
requireSession,
|
|
114
|
+
authorizeRequest: (request) => {
|
|
115
|
+
const vouched = options.linkUser(request);
|
|
116
|
+
return vouched ? admitted(vouched) : options.sso.authorizeRequest(request);
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|