cursedauth 0.1.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/LICENSE +21 -0
- package/README.md +87 -0
- package/dist/account/AccountMenu.d.ts +153 -0
- package/dist/account/AccountMenu.d.ts.map +1 -0
- package/dist/account/AccountMenu.js +388 -0
- package/dist/account/AccountMenu.js.map +1 -0
- package/dist/account/AccountNotice.d.ts +35 -0
- package/dist/account/AccountNotice.d.ts.map +1 -0
- package/dist/account/AccountNotice.js +133 -0
- package/dist/account/AccountNotice.js.map +1 -0
- package/dist/account/accountNotice.state.d.ts +20 -0
- package/dist/account/accountNotice.state.d.ts.map +1 -0
- package/dist/account/accountNotice.state.js +55 -0
- package/dist/account/accountNotice.state.js.map +1 -0
- package/dist/account/avatar.d.ts +37 -0
- package/dist/account/avatar.d.ts.map +1 -0
- package/dist/account/avatar.js +47 -0
- package/dist/account/avatar.js.map +1 -0
- package/dist/accountSlot.client.d.ts +113 -0
- package/dist/accountSlot.client.d.ts.map +1 -0
- package/dist/accountSlot.client.js +330 -0
- package/dist/accountSlot.client.js.map +1 -0
- package/dist/accountSlots.d.ts +192 -0
- package/dist/accountSlots.d.ts.map +1 -0
- package/dist/accountSlots.js +274 -0
- package/dist/accountSlots.js.map +1 -0
- package/dist/auth.d.ts +167 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +310 -0
- package/dist/auth.js.map +1 -0
- package/dist/auth.server.d.ts +35 -0
- package/dist/auth.server.d.ts.map +1 -0
- package/dist/auth.server.js +67 -0
- package/dist/auth.server.js.map +1 -0
- package/dist/clientDescription.d.ts +186 -0
- package/dist/clientDescription.d.ts.map +1 -0
- package/dist/clientDescription.js +278 -0
- package/dist/clientDescription.js.map +1 -0
- package/dist/constantTime.d.ts +35 -0
- package/dist/constantTime.d.ts.map +1 -0
- package/dist/constantTime.js +46 -0
- package/dist/constantTime.js.map +1 -0
- package/dist/contentCensus.d.ts +59 -0
- package/dist/contentCensus.d.ts.map +1 -0
- package/dist/contentCensus.js +55 -0
- package/dist/contentCensus.js.map +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/dist/mountGatedApp.d.ts +128 -0
- package/dist/mountGatedApp.d.ts.map +1 -0
- package/dist/mountGatedApp.js +107 -0
- package/dist/mountGatedApp.js.map +1 -0
- package/dist/runtimeMode.d.ts +28 -0
- package/dist/runtimeMode.d.ts.map +1 -0
- package/dist/runtimeMode.js +37 -0
- package/dist/runtimeMode.js.map +1 -0
- package/dist/secureRequest.d.ts +22 -0
- package/dist/secureRequest.d.ts.map +1 -0
- package/dist/secureRequest.js +27 -0
- package/dist/secureRequest.js.map +1 -0
- package/dist/sso.d.ts +373 -0
- package/dist/sso.d.ts.map +1 -0
- package/dist/sso.js +420 -0
- package/dist/sso.js.map +1 -0
- package/dist/ssoAutoSignIn.d.ts +272 -0
- package/dist/ssoAutoSignIn.d.ts.map +1 -0
- package/dist/ssoAutoSignIn.js +431 -0
- package/dist/ssoAutoSignIn.js.map +1 -0
- package/dist/ssoConsumer.server.d.ts +295 -0
- package/dist/ssoConsumer.server.d.ts.map +1 -0
- package/dist/ssoConsumer.server.js +972 -0
- package/dist/ssoConsumer.server.js.map +1 -0
- package/dist/stageIdentity.d.ts +72 -0
- package/dist/stageIdentity.d.ts.map +1 -0
- package/dist/stageIdentity.js +74 -0
- package/dist/stageIdentity.js.map +1 -0
- package/dist/ui/popover.d.ts +190 -0
- package/dist/ui/popover.d.ts.map +1 -0
- package/dist/ui/popover.js +351 -0
- package/dist/ui/popover.js.map +1 -0
- package/dist/userSessions.d.ts +205 -0
- package/dist/userSessions.d.ts.map +1 -0
- package/dist/userSessions.js +419 -0
- package/dist/userSessions.js.map +1 -0
- package/package.json +115 -0
- package/src/account/AccountMenu.tsx +729 -0
- package/src/account/AccountNotice.tsx +223 -0
- package/src/account/accountNotice.state.ts +66 -0
- package/src/account/avatar.ts +50 -0
- package/src/accountSlot.client.ts +362 -0
- package/src/accountSlots.ts +305 -0
- package/src/auth.server.ts +89 -0
- package/src/auth.ts +515 -0
- package/src/clientDescription.ts +366 -0
- package/src/constantTime.ts +45 -0
- package/src/contentCensus.ts +106 -0
- package/src/index.ts +58 -0
- package/src/mountGatedApp.ts +240 -0
- package/src/runtimeMode.ts +37 -0
- package/src/secureRequest.ts +25 -0
- package/src/sso.ts +767 -0
- package/src/ssoAutoSignIn.ts +544 -0
- package/src/ssoConsumer.server.ts +1260 -0
- package/src/stageIdentity.ts +76 -0
- package/src/ui/popover.ts +390 -0
- package/src/userSessions.ts +678 -0
package/src/sso.ts
ADDED
|
@@ -0,0 +1,767 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SSO grant — the wire credential between `apps/auth` (the accounts
|
|
3
|
+
* satellite) and every satellite that shares its user set.
|
|
4
|
+
*
|
|
5
|
+
* ── The model (2026-07-28) ──────────────────────────────────────────────────
|
|
6
|
+
* One satellite (`apps/auth`) owns the user registry: passwords, reset emails,
|
|
7
|
+
* the admin page. A satellite that wants a signed-in user redirects the browser
|
|
8
|
+
* to auth's `/sso/authorize`; auth answers with a GRANT — a short-lived,
|
|
9
|
+
* single-audience, Ed25519-signed statement "this user, for that app, right
|
|
10
|
+
* now" — and the satellite trades it for its OWN per-app session cookie and
|
|
11
|
+
* never sees a password. Auth built once; every future private satellite
|
|
12
|
+
* integrates by mounting the consumer (`cursedauth/sso-consumer`).
|
|
13
|
+
*
|
|
14
|
+
* ── Why Ed25519 and not an HMAC shared secret ───────────────────────────────
|
|
15
|
+
* A shared secret would let ANY satellite mint grants for every other one — the
|
|
16
|
+
* blast radius of one compromised app becomes the whole fleet. With a keypair,
|
|
17
|
+
* satellites hold only the PUBLIC key; compromising one leaks nothing that can
|
|
18
|
+
* sign. Ed25519 over RSA/ECDSA: built into node:crypto, no parameters to get
|
|
19
|
+
* wrong, 64-byte signatures.
|
|
20
|
+
*
|
|
21
|
+
* ── Why grants are single-use and 60 seconds ────────────────────────────────
|
|
22
|
+
* The grant rides a redirect URL, and URLs leak — proxy logs, referrer headers,
|
|
23
|
+
* a pasted link. A leaked grant must therefore be worth as little as possible:
|
|
24
|
+
* it expires in seconds, names exactly one consumer app (`aud`), and the
|
|
25
|
+
* consumer refuses to accept the same nonce twice (`createNonceGuard`). This is
|
|
26
|
+
* the OAuth authorization-code posture without the second server-to-server
|
|
27
|
+
* round trip — the signature already proves the issuer, so there is nothing a
|
|
28
|
+
* code exchange would add here but a runtime dependency on auth being up.
|
|
29
|
+
*
|
|
30
|
+
* The payload deliberately carries the user snapshot (email, name, admin) so a
|
|
31
|
+
* consumer can answer "who is this?" without ever calling auth at request time.
|
|
32
|
+
* Auth being down means new LOGINS fail; every existing session keeps working.
|
|
33
|
+
*/
|
|
34
|
+
import {
|
|
35
|
+
createHash,
|
|
36
|
+
generateKeyPairSync,
|
|
37
|
+
type KeyObject,
|
|
38
|
+
createPrivateKey,
|
|
39
|
+
createPublicKey,
|
|
40
|
+
sign as edSign,
|
|
41
|
+
verify as edVerify,
|
|
42
|
+
} from "node:crypto";
|
|
43
|
+
|
|
44
|
+
/** How long a grant is valid. Long enough for one redirect hop on a slow
|
|
45
|
+
* connection, short enough that a logged URL is stale before anyone reads
|
|
46
|
+
* the log. */
|
|
47
|
+
export const GRANT_TTL_MS = 60 * 1000;
|
|
48
|
+
|
|
49
|
+
/** The user snapshot a grant carries — everything a consumer app may cache. */
|
|
50
|
+
export interface SsoGrantUser {
|
|
51
|
+
/** The auth registry's user id. Stable across apps — satellites key their
|
|
52
|
+
* own rows on it. */
|
|
53
|
+
id: string;
|
|
54
|
+
email: string;
|
|
55
|
+
name: string;
|
|
56
|
+
/** The registry-level admin flag (may add/delete users on auth's admin
|
|
57
|
+
* page). Consumer apps MAY surface it (e.g. show an "Accounts" link) but
|
|
58
|
+
* must gate their own privileged surfaces on their own rules. */
|
|
59
|
+
admin: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Is this the person who OWNS the machine (2026-08-02)? Distinct from
|
|
62
|
+
* `admin` on purpose — admin is a flag on a row that an admin can hand to
|
|
63
|
+
* anyone, and the fleet directory uses this one to decide whether somebody
|
|
64
|
+
* is shown localhost links. Nobody else has a machine those URLs resolve
|
|
65
|
+
* on, so a wrong answer here is either a dead link or a map of the owner's
|
|
66
|
+
* private ports.
|
|
67
|
+
*
|
|
68
|
+
* OPTIONAL on the wire, and absent must read as `false`: auth and its
|
|
69
|
+
* consumers deploy independently, so a grant minted by an auth that predates
|
|
70
|
+
* this field has to keep working — and it has to fail CLOSED, which "absent
|
|
71
|
+
* means not the owner" does.
|
|
72
|
+
*/
|
|
73
|
+
owner?: boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Did auth grant this account access to THIS app explicitly, rather than by
|
|
76
|
+
* the app's default tier (2026-08-02)? It is what lets a household member
|
|
77
|
+
* into an admin-tier app without being made an admin of the user registry.
|
|
78
|
+
*
|
|
79
|
+
* Consumers read it as an ALTERNATIVE to `requireAdmin`, never as a
|
|
80
|
+
* replacement for the audience check: a grant still proves only what it was
|
|
81
|
+
* minted for. Optional and absent-means-false, same deploy-skew reason.
|
|
82
|
+
*/
|
|
83
|
+
granted?: boolean;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface SsoGrantClaims extends SsoGrantUser {
|
|
87
|
+
/** Which consumer app this grant is FOR — its registered app key. A grant
|
|
88
|
+
* for "hobbies" proves nothing to "roms". */
|
|
89
|
+
aud: string;
|
|
90
|
+
/** Issued-at, ms epoch. */
|
|
91
|
+
iat: number;
|
|
92
|
+
/** Expiry, ms epoch (iat + GRANT_TTL_MS). */
|
|
93
|
+
exp: number;
|
|
94
|
+
/** 128-bit random single-use marker — see `createNonceGuard`. */
|
|
95
|
+
nonce: string;
|
|
96
|
+
/** Key id that signed this grant, so rotation can overlap keys. */
|
|
97
|
+
kid: string;
|
|
98
|
+
v: 1;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface SsoKeyPair {
|
|
102
|
+
/** PKCS8 PEM. Lives ONLY in auth's data dir / secrets — never in a consumer. */
|
|
103
|
+
privateKeyPem: string;
|
|
104
|
+
/** SPKI PEM. What consumers verify with; public by definition. */
|
|
105
|
+
publicKeyPem: string;
|
|
106
|
+
/** First 16 hex chars of SHA-256 of the SPKI DER — stable, collision-safe
|
|
107
|
+
* at fleet scale, short enough to read in a log line. */
|
|
108
|
+
kid: string;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export const kidOfPublicKeyPem = (publicKeyPem: string): string => {
|
|
112
|
+
const der = createPublicKey(publicKeyPem).export({ type: "spki", format: "der" });
|
|
113
|
+
return createHash("sha256").update(der).digest("hex").slice(0, 16);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
export function generateSsoKeyPair(): SsoKeyPair {
|
|
117
|
+
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
|
|
118
|
+
const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
|
119
|
+
const publicKeyPem = publicKey.export({ type: "spki", format: "pem" }).toString();
|
|
120
|
+
return { privateKeyPem, publicKeyPem, kid: kidOfPublicKeyPem(publicKeyPem) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const b64url = (buf: Buffer): string => buf.toString("base64url");
|
|
124
|
+
|
|
125
|
+
export interface MintGrantOptions {
|
|
126
|
+
privateKeyPem: string;
|
|
127
|
+
kid: string;
|
|
128
|
+
aud: string;
|
|
129
|
+
user: SsoGrantUser;
|
|
130
|
+
now?: () => number;
|
|
131
|
+
/** Test hook only — production grants are always GRANT_TTL_MS. */
|
|
132
|
+
ttlMs?: number;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** `base64url(payload JSON).base64url(signature)` — no header, because the
|
|
136
|
+
* algorithm is pinned (Ed25519) and the kid lives in the payload. Not a JWT on
|
|
137
|
+
* purpose: nothing here should ever be handed to a general JWT library with
|
|
138
|
+
* its algorithm-confusion surface. */
|
|
139
|
+
export function mintGrant(options: MintGrantOptions): string {
|
|
140
|
+
const now = options.now?.() ?? Date.now();
|
|
141
|
+
const claims: SsoGrantClaims = {
|
|
142
|
+
...options.user,
|
|
143
|
+
aud: options.aud,
|
|
144
|
+
iat: now,
|
|
145
|
+
exp: now + (options.ttlMs ?? GRANT_TTL_MS),
|
|
146
|
+
nonce: b64url(Buffer.from(crypto.getRandomValues(new Uint8Array(16)))),
|
|
147
|
+
kid: options.kid,
|
|
148
|
+
v: 1,
|
|
149
|
+
};
|
|
150
|
+
const payload = b64url(Buffer.from(JSON.stringify(claims), "utf8"));
|
|
151
|
+
const key = createPrivateKey(options.privateKeyPem);
|
|
152
|
+
const signature = edSign(null, Buffer.from(payload, "utf8"), key);
|
|
153
|
+
return `${payload}.${b64url(signature)}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ── Revocation tickets (2026-08-01) ─────────────────────────────────────────
|
|
157
|
+
// A grant says "let this person in"; a ticket says "throw this person out". The
|
|
158
|
+
// cascade exists because a consumer NEVER calls auth at request time — that is
|
|
159
|
+
// the design's whole point (auth down breaks new logins and nothing else) — and
|
|
160
|
+
// the cost of it is that disabling or deleting an account at auth left every
|
|
161
|
+
// already-minted per-app cookie (roms_session, hobbies_session…) working until
|
|
162
|
+
// it expired. So auth pushes instead: one signed, single-audience, 60-second
|
|
163
|
+
// ticket per registered consumer.
|
|
164
|
+
//
|
|
165
|
+
// It rides the SAME Ed25519 keypair as grants, and is deliberately impossible
|
|
166
|
+
// to confuse with one in either direction: `k` ("kind") is checked before
|
|
167
|
+
// anything else in each verifier, so a grant handed to the revoke endpoint is
|
|
168
|
+
// refused, and a ticket replayed at a callback is refused. Sharing the keypair
|
|
169
|
+
// is the point — a consumer that can verify grants can verify revocations with
|
|
170
|
+
// no new key to distribute, and the private half still never leaves auth.
|
|
171
|
+
|
|
172
|
+
/** How long a revocation ticket is valid — same posture as a grant. */
|
|
173
|
+
export const REVOCATION_TTL_MS = 60 * 1000;
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* What the consumer should do with the named user.
|
|
177
|
+
*
|
|
178
|
+
* `revoke` — end every session; keep the `sso_users` snapshot row. This is
|
|
179
|
+
* "disabled" and "password reset": the person still exists and their app data
|
|
180
|
+
* must stay keyed to them for when they come back.
|
|
181
|
+
*
|
|
182
|
+
* `delete` — end every session AND drop the snapshot row, so the account stops
|
|
183
|
+
* appearing in the app's own user lists. App data keyed on the id is orphaned
|
|
184
|
+
* rather than cascaded, exactly as auth's own delete already warns.
|
|
185
|
+
*/
|
|
186
|
+
export type RevocationAction = "revoke" | "delete";
|
|
187
|
+
|
|
188
|
+
export interface SsoRevocationClaims {
|
|
189
|
+
/** Kind discriminator — checked FIRST by both verifiers. */
|
|
190
|
+
k: "revoke";
|
|
191
|
+
/** Which consumer this ticket is for. A ticket for "roms" does nothing at
|
|
192
|
+
* "hobbies", so one compromised consumer cannot sign the fleet out. */
|
|
193
|
+
aud: string;
|
|
194
|
+
/** The auth registry user id whose sessions end. */
|
|
195
|
+
sub: string;
|
|
196
|
+
action: RevocationAction;
|
|
197
|
+
/**
|
|
198
|
+
* ONE session of `sub`, by its public handle (2026-08-12) — "sign this
|
|
199
|
+
* laptop out" rather than "sign this person out".
|
|
200
|
+
*
|
|
201
|
+
* Absent is the original meaning and stays the default: every session of
|
|
202
|
+
* `sub` ends. Present narrows the SAME ticket rather than introducing a
|
|
203
|
+
* second revocation path, which is the whole point — the fleet has exactly
|
|
204
|
+
* one way for auth to end a session, and the session list drives it.
|
|
205
|
+
*
|
|
206
|
+
* Only legal with `action: "revoke"`. A `delete` drops the account's
|
|
207
|
+
* snapshot row, which is not a thing one session can be half of, and the
|
|
208
|
+
* verifier refuses the combination rather than quietly ignoring the field.
|
|
209
|
+
*/
|
|
210
|
+
sid?: string;
|
|
211
|
+
iat: number;
|
|
212
|
+
exp: number;
|
|
213
|
+
nonce: string;
|
|
214
|
+
kid: string;
|
|
215
|
+
v: 1;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export interface MintRevocationOptions {
|
|
219
|
+
privateKeyPem: string;
|
|
220
|
+
kid: string;
|
|
221
|
+
aud: string;
|
|
222
|
+
sub: string;
|
|
223
|
+
action: RevocationAction;
|
|
224
|
+
/** End only this one session of `sub` — see {@link SsoRevocationClaims.sid}. */
|
|
225
|
+
sid?: string;
|
|
226
|
+
now?: () => number;
|
|
227
|
+
/** Test hook only. */
|
|
228
|
+
ttlMs?: number;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export function mintRevocation(options: MintRevocationOptions): string {
|
|
232
|
+
const now = options.now?.() ?? Date.now();
|
|
233
|
+
if (options.sid && options.action !== "revoke") {
|
|
234
|
+
// Thrown at the MINT, not left for the consumer to refuse: a caller that
|
|
235
|
+
// built this ticket has a bug in its own logic, and finding out at the far
|
|
236
|
+
// end (as a 401 from another app) is how that becomes a mystery.
|
|
237
|
+
throw new Error(`a ${options.action} ticket cannot name a single session`);
|
|
238
|
+
}
|
|
239
|
+
const claims: SsoRevocationClaims = {
|
|
240
|
+
k: "revoke",
|
|
241
|
+
aud: options.aud,
|
|
242
|
+
sub: options.sub,
|
|
243
|
+
action: options.action,
|
|
244
|
+
...(options.sid ? { sid: options.sid } : {}),
|
|
245
|
+
iat: now,
|
|
246
|
+
exp: now + (options.ttlMs ?? REVOCATION_TTL_MS),
|
|
247
|
+
nonce: b64url(Buffer.from(crypto.getRandomValues(new Uint8Array(16)))),
|
|
248
|
+
kid: options.kid,
|
|
249
|
+
v: 1,
|
|
250
|
+
};
|
|
251
|
+
const payload = b64url(Buffer.from(JSON.stringify(claims), "utf8"));
|
|
252
|
+
const key = createPrivateKey(options.privateKeyPem);
|
|
253
|
+
const signature = edSign(null, Buffer.from(payload, "utf8"), key);
|
|
254
|
+
return `${payload}.${b64url(signature)}`;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export type VerifyRevocationResult =
|
|
258
|
+
| { ok: true; claims: SsoRevocationClaims }
|
|
259
|
+
| { ok: false; reason: string };
|
|
260
|
+
|
|
261
|
+
export interface VerifyRevocationOptions {
|
|
262
|
+
keyOf: (kid: string) => KeyObject | null;
|
|
263
|
+
/** The consumer's OWN app key. */
|
|
264
|
+
aud: string;
|
|
265
|
+
now?: () => number;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function verifyRevocation(
|
|
269
|
+
ticket: string,
|
|
270
|
+
options: VerifyRevocationOptions,
|
|
271
|
+
): VerifyRevocationResult {
|
|
272
|
+
const parts = ticket.split(".");
|
|
273
|
+
if (parts.length !== 2) return { ok: false, reason: "malformed ticket" };
|
|
274
|
+
const [payload, signature] = parts as [string, string];
|
|
275
|
+
|
|
276
|
+
let claims: SsoRevocationClaims;
|
|
277
|
+
try {
|
|
278
|
+
claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as SsoRevocationClaims;
|
|
279
|
+
} catch {
|
|
280
|
+
return { ok: false, reason: "malformed payload" };
|
|
281
|
+
}
|
|
282
|
+
// The kind check comes before every other semantic check: a GRANT presented
|
|
283
|
+
// here must be refused as a grant, not fall through to some field test that
|
|
284
|
+
// happens to pass.
|
|
285
|
+
if (claims?.k !== "revoke") return { ok: false, reason: "not a revocation ticket" };
|
|
286
|
+
if (claims.v !== 1) return { ok: false, reason: "unsupported ticket version" };
|
|
287
|
+
if (
|
|
288
|
+
!strField(claims.aud) ||
|
|
289
|
+
!strField(claims.sub) ||
|
|
290
|
+
!strField(claims.nonce) ||
|
|
291
|
+
!strField(claims.kid) ||
|
|
292
|
+
(claims.action !== "revoke" && claims.action !== "delete") ||
|
|
293
|
+
typeof claims.iat !== "number" ||
|
|
294
|
+
typeof claims.exp !== "number" ||
|
|
295
|
+
// Optional, but when present it must be a real handle — and never on a
|
|
296
|
+
// `delete`, which has no one-session meaning. Refused rather than ignored:
|
|
297
|
+
// a ticket that says something the verifier does not act on is a ticket
|
|
298
|
+
// whose author believes something untrue about what it will do.
|
|
299
|
+
(claims.sid !== undefined && !strField(claims.sid)) ||
|
|
300
|
+
(claims.sid !== undefined && claims.action !== "revoke")
|
|
301
|
+
) {
|
|
302
|
+
return { ok: false, reason: "malformed claims" };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Signature BEFORE semantics — same ordering and same reason as verifyGrant.
|
|
306
|
+
const key = options.keyOf(claims.kid);
|
|
307
|
+
if (!key) return { ok: false, reason: `unknown signing key ${claims.kid}` };
|
|
308
|
+
const valid = edVerify(
|
|
309
|
+
null,
|
|
310
|
+
Buffer.from(payload, "utf8"),
|
|
311
|
+
key,
|
|
312
|
+
Buffer.from(signature, "base64url"),
|
|
313
|
+
);
|
|
314
|
+
if (!valid) return { ok: false, reason: "bad signature" };
|
|
315
|
+
|
|
316
|
+
if (claims.aud !== options.aud) {
|
|
317
|
+
return { ok: false, reason: `ticket is for "${claims.aud}", not "${options.aud}"` };
|
|
318
|
+
}
|
|
319
|
+
const now = options.now?.() ?? Date.now();
|
|
320
|
+
if (now >= claims.exp) return { ok: false, reason: "ticket expired" };
|
|
321
|
+
if (claims.iat > now + 30_000) return { ok: false, reason: "ticket issued in the future" };
|
|
322
|
+
return { ok: true, claims };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ── Content-census tickets (2026-08-10) ─────────────────────────────────────
|
|
326
|
+
// The third statement auth can make to a consumer, and the only one that ASKS
|
|
327
|
+
// rather than tells: "before I take these accounts' access away, how much of
|
|
328
|
+
// what is in you did they make?"
|
|
329
|
+
//
|
|
330
|
+
// It exists because taking access away and destroying access to data are
|
|
331
|
+
// different acts that look identical on an admin page. Closing ROMs to a
|
|
332
|
+
// household member strands their save states; closing an app whose library is
|
|
333
|
+
// shared strands nothing. Auth cannot tell those apart — it holds no app data
|
|
334
|
+
// by design — so it asks the app, at the moment the owner is deciding, and puts
|
|
335
|
+
// the answer in the confirmation dialog.
|
|
336
|
+
//
|
|
337
|
+
// Same keypair, same single-audience posture, same 60-second life as a
|
|
338
|
+
// revocation, and the same `k` discriminator checked first in every verifier. It
|
|
339
|
+
// is READ-ONLY by construction: a consumer that answers a census changes
|
|
340
|
+
// nothing, so the worst a replayed ticket can do is make the app count rows
|
|
341
|
+
// twice.
|
|
342
|
+
|
|
343
|
+
/** How long a census ticket is valid — same posture as a grant. */
|
|
344
|
+
export const CENSUS_TTL_MS = 60 * 1000;
|
|
345
|
+
|
|
346
|
+
/** How many accounts one ticket may ask about. The admin dialog asks about the
|
|
347
|
+
* people a single change moves, which is a household; a bound is here so a
|
|
348
|
+
* malformed caller cannot turn one request into a table scan per user. */
|
|
349
|
+
export const CENSUS_MAX_SUBJECTS = 200;
|
|
350
|
+
|
|
351
|
+
/** One kind of thing an account made, as the app itself names it. */
|
|
352
|
+
export interface ContentCensusItem {
|
|
353
|
+
/** Stable machine id for the kind — `save-states`, `shelves`. Never shown. */
|
|
354
|
+
kind: string;
|
|
355
|
+
/** How the owner should read it, plural: "save states", "tracked items". */
|
|
356
|
+
label: string;
|
|
357
|
+
count: number;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** What one account has in one app. */
|
|
361
|
+
export interface ContentCensusUser {
|
|
362
|
+
userId: string;
|
|
363
|
+
items: ContentCensusItem[];
|
|
364
|
+
/** Sum of `items` — the number the dialog leads with. */
|
|
365
|
+
total: number;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* An app's answer about who made what.
|
|
370
|
+
*
|
|
371
|
+
* `per-user` — this app attributes rows to accounts and here are the counts.
|
|
372
|
+
* `shared` — this app HAS data, but none of it is keyed to an individual
|
|
373
|
+
* account (the notes corpus, the family tree). Losing access loses
|
|
374
|
+
* nothing personal, and saying so is as useful as a count.
|
|
375
|
+
*
|
|
376
|
+
* A consumer that implements no census at all is a THIRD answer (`unknown`),
|
|
377
|
+
* produced by auth rather than by the app — see `ssoConsumer.server.ts`. The
|
|
378
|
+
* three must stay distinct: "nothing of theirs is here" and "I could not find
|
|
379
|
+
* out" lead an owner to opposite decisions.
|
|
380
|
+
*/
|
|
381
|
+
export type ContentCensus =
|
|
382
|
+
| { scope: "per-user"; users: ContentCensusUser[]; note?: string }
|
|
383
|
+
| { scope: "shared"; note: string };
|
|
384
|
+
|
|
385
|
+
export interface SsoCensusClaims {
|
|
386
|
+
/** Kind discriminator — checked FIRST by the verifier. */
|
|
387
|
+
k: "census";
|
|
388
|
+
/** Which consumer this ticket is for. */
|
|
389
|
+
aud: string;
|
|
390
|
+
/** The registry user ids being asked about. */
|
|
391
|
+
subs: string[];
|
|
392
|
+
iat: number;
|
|
393
|
+
exp: number;
|
|
394
|
+
nonce: string;
|
|
395
|
+
kid: string;
|
|
396
|
+
v: 1;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export interface MintCensusOptions {
|
|
400
|
+
privateKeyPem: string;
|
|
401
|
+
kid: string;
|
|
402
|
+
aud: string;
|
|
403
|
+
subs: string[];
|
|
404
|
+
now?: () => number;
|
|
405
|
+
/** Test hook only. */
|
|
406
|
+
ttlMs?: number;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
export function mintCensus(options: MintCensusOptions): string {
|
|
410
|
+
const now = options.now?.() ?? Date.now();
|
|
411
|
+
const claims: SsoCensusClaims = {
|
|
412
|
+
k: "census",
|
|
413
|
+
aud: options.aud,
|
|
414
|
+
subs: [...options.subs],
|
|
415
|
+
iat: now,
|
|
416
|
+
exp: now + (options.ttlMs ?? CENSUS_TTL_MS),
|
|
417
|
+
nonce: b64url(Buffer.from(crypto.getRandomValues(new Uint8Array(16)))),
|
|
418
|
+
kid: options.kid,
|
|
419
|
+
v: 1,
|
|
420
|
+
};
|
|
421
|
+
const payload = b64url(Buffer.from(JSON.stringify(claims), "utf8"));
|
|
422
|
+
const key = createPrivateKey(options.privateKeyPem);
|
|
423
|
+
const signature = edSign(null, Buffer.from(payload, "utf8"), key);
|
|
424
|
+
return `${payload}.${b64url(signature)}`;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
export type VerifyCensusResult =
|
|
428
|
+
| { ok: true; claims: SsoCensusClaims }
|
|
429
|
+
| { ok: false; reason: string };
|
|
430
|
+
|
|
431
|
+
export interface VerifyCensusOptions {
|
|
432
|
+
keyOf: (kid: string) => KeyObject | null;
|
|
433
|
+
/** The consumer's OWN app key. */
|
|
434
|
+
aud: string;
|
|
435
|
+
now?: () => number;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export function verifyCensus(ticket: string, options: VerifyCensusOptions): VerifyCensusResult {
|
|
439
|
+
const parts = ticket.split(".");
|
|
440
|
+
if (parts.length !== 2) return { ok: false, reason: "malformed ticket" };
|
|
441
|
+
const [payload, signature] = parts as [string, string];
|
|
442
|
+
|
|
443
|
+
let claims: SsoCensusClaims;
|
|
444
|
+
try {
|
|
445
|
+
claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as SsoCensusClaims;
|
|
446
|
+
} catch {
|
|
447
|
+
return { ok: false, reason: "malformed payload" };
|
|
448
|
+
}
|
|
449
|
+
// Kind first, same ordering and same reason as the other two verifiers: a
|
|
450
|
+
// grant presented here must be refused AS a grant, never fall through to a
|
|
451
|
+
// field test that happens to pass.
|
|
452
|
+
if (claims?.k !== "census") return { ok: false, reason: "not a census ticket" };
|
|
453
|
+
if (claims.v !== 1) return { ok: false, reason: "unsupported ticket version" };
|
|
454
|
+
if (
|
|
455
|
+
!strField(claims.aud) ||
|
|
456
|
+
!strField(claims.nonce) ||
|
|
457
|
+
!strField(claims.kid) ||
|
|
458
|
+
!Array.isArray(claims.subs) ||
|
|
459
|
+
claims.subs.length === 0 ||
|
|
460
|
+
claims.subs.length > CENSUS_MAX_SUBJECTS ||
|
|
461
|
+
!claims.subs.every((sub) => strField(sub)) ||
|
|
462
|
+
typeof claims.iat !== "number" ||
|
|
463
|
+
typeof claims.exp !== "number"
|
|
464
|
+
) {
|
|
465
|
+
return { ok: false, reason: "malformed claims" };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// Signature BEFORE semantics — same ordering and same reason as verifyGrant.
|
|
469
|
+
const key = options.keyOf(claims.kid);
|
|
470
|
+
if (!key) return { ok: false, reason: `unknown signing key ${claims.kid}` };
|
|
471
|
+
const valid = edVerify(
|
|
472
|
+
null,
|
|
473
|
+
Buffer.from(payload, "utf8"),
|
|
474
|
+
key,
|
|
475
|
+
Buffer.from(signature, "base64url"),
|
|
476
|
+
);
|
|
477
|
+
if (!valid) return { ok: false, reason: "bad signature" };
|
|
478
|
+
|
|
479
|
+
if (claims.aud !== options.aud) {
|
|
480
|
+
return { ok: false, reason: `ticket is for "${claims.aud}", not "${options.aud}"` };
|
|
481
|
+
}
|
|
482
|
+
const now = options.now?.() ?? Date.now();
|
|
483
|
+
if (now >= claims.exp) return { ok: false, reason: "ticket expired" };
|
|
484
|
+
if (claims.iat > now + 30_000) return { ok: false, reason: "ticket issued in the future" };
|
|
485
|
+
return { ok: true, claims };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// ── Session-list tickets (2026-08-12) ───────────────────────────────────────
|
|
489
|
+
// The fourth statement auth can make to a consumer, and the second that asks
|
|
490
|
+
// rather than tells: "which sessions of this account are alive in you, and what
|
|
491
|
+
// do they look like?"
|
|
492
|
+
//
|
|
493
|
+
// It exists because the fleet could sign somebody out of everything and could
|
|
494
|
+
// not show anybody what "everything" was. A session you did not open is only
|
|
495
|
+
// discoverable by being LISTED, so the list is the security control and the
|
|
496
|
+
// revoke button is what it enables — which is why this ticket is read-only and
|
|
497
|
+
// the ending of a session stays on the revocation ticket above, narrowed by
|
|
498
|
+
// `sid`. One revocation path, one place it can be wrong.
|
|
499
|
+
//
|
|
500
|
+
// Same keypair, same single-audience posture, same 60-second life, same `k`
|
|
501
|
+
// discriminator checked first in every verifier.
|
|
502
|
+
|
|
503
|
+
/** How long a session-list ticket is valid — same posture as a grant. */
|
|
504
|
+
export const SESSIONS_TTL_MS = 60 * 1000;
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* How many sessions one app may report for one account.
|
|
508
|
+
*
|
|
509
|
+
* A person has a handful of devices; a bound is here so a compromised or
|
|
510
|
+
* confused consumer cannot turn one question into an unbounded response auth
|
|
511
|
+
* has to hold in memory and render.
|
|
512
|
+
*/
|
|
513
|
+
export const SESSIONS_MAX_PER_APP = 200;
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* One live session as a consumer reports it.
|
|
517
|
+
*
|
|
518
|
+
* Structurally a `SessionRecord` (`userSessions.ts`) minus the row id and minus
|
|
519
|
+
* `current` — "the session you are holding" is a fact about a browser, and this
|
|
520
|
+
* is a server-to-server answer where nobody is holding anything.
|
|
521
|
+
*/
|
|
522
|
+
export interface SsoSessionSummary {
|
|
523
|
+
/** The session's public handle — what a revoke-one ticket names. */
|
|
524
|
+
handle: string;
|
|
525
|
+
/** Whose it is. Auth drops anything that is not the account it asked about. */
|
|
526
|
+
userId: string;
|
|
527
|
+
createdAt: number;
|
|
528
|
+
lastSeenAt: number;
|
|
529
|
+
expiresAt: number;
|
|
530
|
+
/** The user-agent verbatim; auth renders it. `""` when the app has none. */
|
|
531
|
+
userAgent: string;
|
|
532
|
+
ip: string;
|
|
533
|
+
/**
|
|
534
|
+
* Where the address was when the session was created — "Austin, Texas, US",
|
|
535
|
+
* or `""` when the app could not place it.
|
|
536
|
+
*
|
|
537
|
+
* OPTIONAL on the wire, and read defensively by auth: a satellite that has
|
|
538
|
+
* not been redeployed since 2026-08-25 answers without it, and a fleet-wide
|
|
539
|
+
* list that went blank for every app awaiting a deploy would be a worse
|
|
540
|
+
* regression than the missing city it is reporting.
|
|
541
|
+
*/
|
|
542
|
+
place?: string;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
export interface SsoSessionsClaims {
|
|
546
|
+
/** Kind discriminator — checked FIRST by the verifier. */
|
|
547
|
+
k: "sessions";
|
|
548
|
+
/** Which consumer this ticket is for. */
|
|
549
|
+
aud: string;
|
|
550
|
+
/** The one registry user id whose sessions are being asked about. Singular,
|
|
551
|
+
* unlike the census: this question is always asked about one account, on
|
|
552
|
+
* one screen, and a list endpoint that can be asked about everybody at once
|
|
553
|
+
* is a different (and much larger) disclosure. */
|
|
554
|
+
sub: string;
|
|
555
|
+
iat: number;
|
|
556
|
+
exp: number;
|
|
557
|
+
nonce: string;
|
|
558
|
+
kid: string;
|
|
559
|
+
v: 1;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export interface MintSessionsOptions {
|
|
563
|
+
privateKeyPem: string;
|
|
564
|
+
kid: string;
|
|
565
|
+
aud: string;
|
|
566
|
+
sub: string;
|
|
567
|
+
now?: () => number;
|
|
568
|
+
/** Test hook only. */
|
|
569
|
+
ttlMs?: number;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
export function mintSessionsRequest(options: MintSessionsOptions): string {
|
|
573
|
+
const now = options.now?.() ?? Date.now();
|
|
574
|
+
const claims: SsoSessionsClaims = {
|
|
575
|
+
k: "sessions",
|
|
576
|
+
aud: options.aud,
|
|
577
|
+
sub: options.sub,
|
|
578
|
+
iat: now,
|
|
579
|
+
exp: now + (options.ttlMs ?? SESSIONS_TTL_MS),
|
|
580
|
+
nonce: b64url(Buffer.from(crypto.getRandomValues(new Uint8Array(16)))),
|
|
581
|
+
kid: options.kid,
|
|
582
|
+
v: 1,
|
|
583
|
+
};
|
|
584
|
+
const payload = b64url(Buffer.from(JSON.stringify(claims), "utf8"));
|
|
585
|
+
const key = createPrivateKey(options.privateKeyPem);
|
|
586
|
+
const signature = edSign(null, Buffer.from(payload, "utf8"), key);
|
|
587
|
+
return `${payload}.${b64url(signature)}`;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
export type VerifySessionsResult =
|
|
591
|
+
| { ok: true; claims: SsoSessionsClaims }
|
|
592
|
+
| { ok: false; reason: string };
|
|
593
|
+
|
|
594
|
+
export interface VerifySessionsOptions {
|
|
595
|
+
keyOf: (kid: string) => KeyObject | null;
|
|
596
|
+
/** The consumer's OWN app key. */
|
|
597
|
+
aud: string;
|
|
598
|
+
now?: () => number;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
export function verifySessionsRequest(
|
|
602
|
+
ticket: string,
|
|
603
|
+
options: VerifySessionsOptions,
|
|
604
|
+
): VerifySessionsResult {
|
|
605
|
+
const parts = ticket.split(".");
|
|
606
|
+
if (parts.length !== 2) return { ok: false, reason: "malformed ticket" };
|
|
607
|
+
const [payload, signature] = parts as [string, string];
|
|
608
|
+
|
|
609
|
+
let claims: SsoSessionsClaims;
|
|
610
|
+
try {
|
|
611
|
+
claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as SsoSessionsClaims;
|
|
612
|
+
} catch {
|
|
613
|
+
return { ok: false, reason: "malformed payload" };
|
|
614
|
+
}
|
|
615
|
+
// Kind first, same ordering and same reason as the other three verifiers.
|
|
616
|
+
if (claims?.k !== "sessions") return { ok: false, reason: "not a session-list ticket" };
|
|
617
|
+
if (claims.v !== 1) return { ok: false, reason: "unsupported ticket version" };
|
|
618
|
+
if (
|
|
619
|
+
!strField(claims.aud) ||
|
|
620
|
+
!strField(claims.sub) ||
|
|
621
|
+
!strField(claims.nonce) ||
|
|
622
|
+
!strField(claims.kid) ||
|
|
623
|
+
typeof claims.iat !== "number" ||
|
|
624
|
+
typeof claims.exp !== "number"
|
|
625
|
+
) {
|
|
626
|
+
return { ok: false, reason: "malformed claims" };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// Signature BEFORE semantics — same ordering and same reason as verifyGrant.
|
|
630
|
+
const key = options.keyOf(claims.kid);
|
|
631
|
+
if (!key) return { ok: false, reason: `unknown signing key ${claims.kid}` };
|
|
632
|
+
const valid = edVerify(
|
|
633
|
+
null,
|
|
634
|
+
Buffer.from(payload, "utf8"),
|
|
635
|
+
key,
|
|
636
|
+
Buffer.from(signature, "base64url"),
|
|
637
|
+
);
|
|
638
|
+
if (!valid) return { ok: false, reason: "bad signature" };
|
|
639
|
+
|
|
640
|
+
if (claims.aud !== options.aud) {
|
|
641
|
+
return { ok: false, reason: `ticket is for "${claims.aud}", not "${options.aud}"` };
|
|
642
|
+
}
|
|
643
|
+
const now = options.now?.() ?? Date.now();
|
|
644
|
+
if (now >= claims.exp) return { ok: false, reason: "ticket expired" };
|
|
645
|
+
if (claims.iat > now + 30_000) return { ok: false, reason: "ticket issued in the future" };
|
|
646
|
+
return { ok: true, claims };
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
export type VerifyGrantResult =
|
|
650
|
+
| { ok: true; claims: SsoGrantClaims }
|
|
651
|
+
| { ok: false; reason: string };
|
|
652
|
+
|
|
653
|
+
export interface VerifyGrantOptions {
|
|
654
|
+
/** Resolve a kid to a verification key, or null for an unknown kid. A
|
|
655
|
+
* consumer backed by a JWKS cache uses the miss to trigger a refresh. */
|
|
656
|
+
keyOf: (kid: string) => KeyObject | null;
|
|
657
|
+
/** The consumer's OWN app key — a grant for anyone else is refused. */
|
|
658
|
+
aud: string;
|
|
659
|
+
now?: () => number;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
const strField = (v: unknown): v is string => typeof v === "string" && v.length > 0;
|
|
663
|
+
/** An optional boolean claim: absent is fine, present must be a real boolean.
|
|
664
|
+
* Never coerce — the whole point is that a string cannot pass as `true`. */
|
|
665
|
+
const optionalBool = (v: unknown): boolean => v === undefined || typeof v === "boolean";
|
|
666
|
+
|
|
667
|
+
export function verifyGrant(grant: string, options: VerifyGrantOptions): VerifyGrantResult {
|
|
668
|
+
const parts = grant.split(".");
|
|
669
|
+
if (parts.length !== 2) return { ok: false, reason: "malformed grant" };
|
|
670
|
+
const [payload, signature] = parts as [string, string];
|
|
671
|
+
|
|
672
|
+
let claims: SsoGrantClaims;
|
|
673
|
+
try {
|
|
674
|
+
claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as SsoGrantClaims;
|
|
675
|
+
} catch {
|
|
676
|
+
return { ok: false, reason: "malformed payload" };
|
|
677
|
+
}
|
|
678
|
+
// Every non-grant statement this key signs carries a `k`; a grant carries
|
|
679
|
+
// none. So the guard is "any kind at all", not a list of the kinds that
|
|
680
|
+
// exist today — a third one (`census`, 2026-08-10) must be refused by the
|
|
681
|
+
// rule that already existed rather than by remembering to extend it here.
|
|
682
|
+
// Refused BY NAME, too, rather than falling through to the field checks and
|
|
683
|
+
// coming back as a vague "malformed claims".
|
|
684
|
+
const kind = (claims as unknown as { k?: unknown }).k;
|
|
685
|
+
if (kind !== undefined) {
|
|
686
|
+
return {
|
|
687
|
+
ok: false,
|
|
688
|
+
reason:
|
|
689
|
+
kind === "revoke"
|
|
690
|
+
? "revocation ticket presented as a grant"
|
|
691
|
+
: `${String(kind)} ticket presented as a grant`,
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
if (claims?.v !== 1) return { ok: false, reason: "unsupported grant version" };
|
|
695
|
+
if (
|
|
696
|
+
!strField(claims.id) ||
|
|
697
|
+
!strField(claims.email) ||
|
|
698
|
+
typeof claims.name !== "string" ||
|
|
699
|
+
typeof claims.admin !== "boolean" ||
|
|
700
|
+
!strField(claims.aud) ||
|
|
701
|
+
!strField(claims.nonce) ||
|
|
702
|
+
!strField(claims.kid) ||
|
|
703
|
+
typeof claims.iat !== "number" ||
|
|
704
|
+
typeof claims.exp !== "number" ||
|
|
705
|
+
// Optional (deploy skew — see SsoGrantUser), but when PRESENT they must be
|
|
706
|
+
// booleans. A truthy string would otherwise hand somebody the owner's
|
|
707
|
+
// localhost map through a field that was never meant to carry it.
|
|
708
|
+
!optionalBool(claims.owner) ||
|
|
709
|
+
!optionalBool(claims.granted)
|
|
710
|
+
) {
|
|
711
|
+
return { ok: false, reason: "malformed claims" };
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// Signature BEFORE semantics: an unsigned payload's contents mean nothing,
|
|
715
|
+
// and the checks below must not become an oracle over forged input.
|
|
716
|
+
const key = options.keyOf(claims.kid);
|
|
717
|
+
if (!key) return { ok: false, reason: `unknown signing key ${claims.kid}` };
|
|
718
|
+
const valid = edVerify(
|
|
719
|
+
null,
|
|
720
|
+
Buffer.from(payload, "utf8"),
|
|
721
|
+
key,
|
|
722
|
+
Buffer.from(signature, "base64url"),
|
|
723
|
+
);
|
|
724
|
+
if (!valid) return { ok: false, reason: "bad signature" };
|
|
725
|
+
|
|
726
|
+
if (claims.aud !== options.aud) {
|
|
727
|
+
return { ok: false, reason: `grant is for "${claims.aud}", not "${options.aud}"` };
|
|
728
|
+
}
|
|
729
|
+
const now = options.now?.() ?? Date.now();
|
|
730
|
+
if (now >= claims.exp) return { ok: false, reason: "grant expired" };
|
|
731
|
+
// Clock-skew guard: an iat meaningfully in the future means someone's clock
|
|
732
|
+
// is wrong enough that "expires in 60s" no longer means anything.
|
|
733
|
+
if (claims.iat > now + 30_000) return { ok: false, reason: "grant issued in the future" };
|
|
734
|
+
return { ok: true, claims };
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Single-use enforcement for grant nonces, in memory.
|
|
739
|
+
*
|
|
740
|
+
* In memory is CORRECT here, not a shortcut: a nonce only needs to be
|
|
741
|
+
* remembered for the grant's own 60-second lifetime (after `exp` the expiry
|
|
742
|
+
* check refuses it regardless), every satellite is a single Bun process, and a
|
|
743
|
+
* process restart forgetting the set merely re-opens a ≤60s replay window for
|
|
744
|
+
* a URL that already succeeded once — against a session the same browser
|
|
745
|
+
* already holds.
|
|
746
|
+
*/
|
|
747
|
+
export interface NonceGuard {
|
|
748
|
+
/** True the FIRST time a nonce is seen; false on any replay. */
|
|
749
|
+
consume(nonce: string, expiresAt: number): boolean;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
export function createNonceGuard(now: () => number = Date.now): NonceGuard {
|
|
753
|
+
const seen = new Map<string, number>();
|
|
754
|
+
return {
|
|
755
|
+
consume(nonce, expiresAt) {
|
|
756
|
+
const at = now();
|
|
757
|
+
// Sweep on write: the map only grows while grants are being consumed,
|
|
758
|
+
// which is exactly when sweeping is cheap and worthwhile.
|
|
759
|
+
for (const [key, exp] of seen) {
|
|
760
|
+
if (exp <= at) seen.delete(key);
|
|
761
|
+
}
|
|
762
|
+
if (seen.has(nonce)) return false;
|
|
763
|
+
seen.set(nonce, expiresAt);
|
|
764
|
+
return true;
|
|
765
|
+
},
|
|
766
|
+
};
|
|
767
|
+
}
|