@marver-design/marver 0.10.2 → 0.11.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.
@@ -0,0 +1,411 @@
1
+ import { createHash, createVerify, randomBytes, timingSafeEqual } from "node:crypto";
2
+ //#region src/server/marver-id.ts
3
+ /**
4
+ * Marver ID - the canvas half of the protocol.
5
+ *
6
+ * A canvas never trusts a token because it looks well-formed. The sequence is:
7
+ *
8
+ * 1. mint() - the canvas invents a nonce and remembers it, bound
9
+ * to this browser and this exact origin.
10
+ * 2. the TAB goes to id.marver.design/authorize and comes back to
11
+ * /__mv/id/finish with the assertion in the URL fragment. One tab, one
12
+ * redirect each way - no popup and no postMessage, because Google serves
13
+ * COOP: same-origin and severs window.opener permanently. See
14
+ * marver-id-gate.ts for the full reasoning.
15
+ * 3. verifyAssertion() - the canvas SERVER checks every claim against the
16
+ * published keys, then consumes the transaction.
17
+ *
18
+ * Step 3 is the one that matters. `aud` must equal this canvas's own origin,
19
+ * so an assertion captured on an attacker's site is inert here; the nonce must
20
+ * match a transaction we actually issued, so a token cannot be injected from
21
+ * nowhere; and the transaction is single-use, so it cannot be replayed even
22
+ * within its short life.
23
+ *
24
+ * Everything here is dependency-free and runs in the OSS canvas, because every
25
+ * self-hosted deployment needs to do this for itself. Nothing phones home
26
+ * except the periodic fetch of public keys.
27
+ */
28
+ /**
29
+ * How long a sign-in may take, start to finish.
30
+ *
31
+ * Was five minutes, which quietly assumed the identity service answers
32
+ * instantly. It does not: a sign-in there can mean waiting for an emailed code,
33
+ * and mail is store-and-forward - a first-time sender can be greylisted and
34
+ * deferred for minutes before the message is even accepted. Somebody who went to
35
+ * find their code and came back to "unknown or spent nonce" did nothing wrong.
36
+ *
37
+ * Fifteen minutes covers a slow round trip with room to spare, and costs little:
38
+ * the nonce is single-use, bound to one browser and one origin, and useless
39
+ * without a signature from the issuer. The browser handle below is set to match,
40
+ * so the two halves of the same deadline expire together rather than leaving a
41
+ * window where the transaction lives but the handle that owns it is gone.
42
+ */
43
+ const TRANSACTION_TTL_MS = 9e5;
44
+ /** Servers drift; allow a little, but not enough to matter. */
45
+ const CLOCK_TOLERANCE_S = 30;
46
+ /** Public keys are cached; rotation publishes a key well before it signs. */
47
+ const JWKS_TTL_MS = 6e5;
48
+ /** A ceiling on token size - nothing legitimate is close to this. */
49
+ const MAX_TOKEN_BYTES = 8192;
50
+ /**
51
+ * The transaction store.
52
+ *
53
+ * In memory on purpose: a transaction is short-lived, and a canvas that
54
+ * restarts mid-sign-in should simply ask the person to try again rather than
55
+ * persist half-finished authentications to disk.
56
+ */
57
+ /** A ceiling on live transactions - /start is unauthenticated by necessity. */
58
+ const MAX_TRANSACTIONS = 1e4;
59
+ /** How often the expiry sweep is allowed to walk the whole map. */
60
+ const SWEEP_INTERVAL_MS = 1e4;
61
+ var TransactionStore = class {
62
+ items = /* @__PURE__ */ new Map();
63
+ /** nonce currently held by each browser, so one browser holds one slot. */
64
+ byBrowser = /* @__PURE__ */ new Map();
65
+ lastSweep = 0;
66
+ /** Invent a nonce for a sign-in attempt from this browser to this origin. */
67
+ mint(origin, browser, next) {
68
+ this.sweep();
69
+ const held = this.byBrowser.get(browser);
70
+ if (held) {
71
+ const live = this.items.get(held);
72
+ if (live && live.exp >= Date.now() && live.origin === origin) {
73
+ if (next) live.next = next;
74
+ live.exp = Date.now() + TRANSACTION_TTL_MS;
75
+ return live;
76
+ }
77
+ if (held) this.items.delete(held);
78
+ }
79
+ if (this.items.size >= MAX_TRANSACTIONS) {
80
+ const oldest = this.items.keys().next().value;
81
+ if (oldest) {
82
+ const victim = this.items.get(oldest);
83
+ this.items.delete(oldest);
84
+ if (victim && this.byBrowser.get(victim.browser) === oldest) this.byBrowser.delete(victim.browser);
85
+ }
86
+ }
87
+ const tx = {
88
+ nonce: randomBytes(32).toString("base64url"),
89
+ origin,
90
+ browser,
91
+ exp: Date.now() + TRANSACTION_TTL_MS,
92
+ ...next ? { next } : {}
93
+ };
94
+ this.items.set(tx.nonce, tx);
95
+ this.byBrowser.set(browser, tx.nonce);
96
+ return tx;
97
+ }
98
+ /**
99
+ * Take a transaction, if it is real, unexpired, and belongs to this browser.
100
+ *
101
+ * The browser check happens BEFORE the delete, and that ordering is the whole
102
+ * point: a stranger who somehow learns a nonce must not be able to destroy
103
+ * somebody else's live sign-in by presenting it. Only the browser that owns a
104
+ * transaction can spend it - for anyone else it is inert, and left alone.
105
+ *
106
+ * Once ownership is proved the transaction is removed unconditionally, so the
107
+ * legitimate browser gets exactly one attempt and a forged signature cannot be
108
+ * ground against a live nonce.
109
+ */
110
+ consume(nonce, browser) {
111
+ const tx = this.items.get(nonce);
112
+ if (!tx) return null;
113
+ if (!constantTimeEqual(tx.browser, browser)) return null;
114
+ this.items.delete(nonce);
115
+ if (this.byBrowser.get(tx.browser) === nonce) this.byBrowser.delete(tx.browser);
116
+ if (tx.exp < Date.now()) return null;
117
+ return tx;
118
+ }
119
+ /**
120
+ * Drop what has expired.
121
+ *
122
+ * Throttled, because this walks the whole map and it is reached from an
123
+ * unauthenticated endpoint - running it on every mint turns /start into a
124
+ * quadratic cost the caller controls. Expiry is still enforced exactly, in
125
+ * consume(); this only reclaims memory, and ten seconds late is fine.
126
+ */
127
+ sweep() {
128
+ const now = Date.now();
129
+ if (now - this.lastSweep < SWEEP_INTERVAL_MS) return;
130
+ this.lastSweep = now;
131
+ for (const [k, v] of this.items) if (v.exp < now) {
132
+ this.items.delete(k);
133
+ if (this.byBrowser.get(v.browser) === k) this.byBrowser.delete(v.browser);
134
+ }
135
+ }
136
+ get size() {
137
+ return this.items.size;
138
+ }
139
+ };
140
+ /**
141
+ * Reduce a configured issuer to a bare origin, or refuse it.
142
+ *
143
+ * The issuer is the trust root: its published keys decide who may open this
144
+ * canvas. Taken as a raw string it is far too easy to configure into something
145
+ * that is not a trust root at all - `http://` invites anyone on the path
146
+ * between here and there to serve their own keys, and a value carrying a path,
147
+ * a query or embedded credentials means the URL the operator read is not the
148
+ * URL that gets fetched.
149
+ *
150
+ * Loopback over http is allowed because that is how the protocol is developed
151
+ * against a local identity service, and there is no network to sit on.
152
+ *
153
+ * Returns null when the value cannot be trusted, so the caller can refuse to
154
+ * start rather than run with a trust root nobody vetted.
155
+ */
156
+ function normalizeIssuer(raw) {
157
+ if (!raw) return null;
158
+ let url;
159
+ try {
160
+ url = new URL(raw.trim());
161
+ } catch {
162
+ return null;
163
+ }
164
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
165
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) return null;
166
+ if (url.username || url.password) return null;
167
+ if (url.pathname !== "/" || url.search || url.hash) return null;
168
+ return url.origin;
169
+ }
170
+ let jwksCache = null;
171
+ /**
172
+ * The last time an unknown kid forced a refetch, and how rarely that may happen.
173
+ *
174
+ * The token chooses the kid, so without a floor here a caller manufactures one
175
+ * outbound request per attempt.
176
+ */
177
+ let lastForcedFetch = 0;
178
+ const FORCED_FETCH_COOLDOWN_MS = 3e4;
179
+ /**
180
+ * The fetch currently in flight, if there is one.
181
+ *
182
+ * The cooldown above bounds refetches for an UNKNOWN kid, but says nothing about
183
+ * a cold cache: at boot, or the moment the cache ages out, every callback that
184
+ * arrives at once sees no entry and starts its own request. That is a thundering
185
+ * herd pointed at the identity service, and a caller holding transactions can
186
+ * time it deliberately. One request per URL, shared by everyone waiting for it.
187
+ */
188
+ let inFlight = null;
189
+ async function fetchJwks(issuer, force = false) {
190
+ const url = `${issuer.replace(/\/$/, "")}/.well-known/jwks.json`;
191
+ if (!force && jwksCache && jwksCache.url === url && Date.now() - jwksCache.at < JWKS_TTL_MS) return jwksCache.jwks;
192
+ if (inFlight && inFlight.url === url) return inFlight.p;
193
+ const p = fetchJwksNow(url);
194
+ inFlight = {
195
+ url,
196
+ p
197
+ };
198
+ try {
199
+ return await p;
200
+ } finally {
201
+ if (inFlight?.p === p) inFlight = null;
202
+ }
203
+ }
204
+ async function fetchJwksNow(url) {
205
+ const res = await fetch(url, {
206
+ signal: AbortSignal.timeout(5e3),
207
+ redirect: "error"
208
+ });
209
+ if (!res.ok) throw new Error(`jwks fetch failed (${res.status})`);
210
+ const jwks = await res.json();
211
+ if (!Array.isArray(jwks.keys)) throw new Error("jwks malformed");
212
+ jwksCache = {
213
+ at: Date.now(),
214
+ url,
215
+ jwks
216
+ };
217
+ return jwks;
218
+ }
219
+ /**
220
+ * Verify an assertion against everything it claims to be.
221
+ *
222
+ * Deliberately returns a reason string rather than throwing: the caller logs it
223
+ * and shows the person a single generic failure. Distinguishing "expired" from
224
+ * "wrong audience" to the browser would be handing an attacker a debugger.
225
+ */
226
+ async function verifyAssertion(opts) {
227
+ const { token, origin, issuer, store, browser } = opts;
228
+ if (!token || token.length > MAX_TOKEN_BYTES) return {
229
+ ok: false,
230
+ reason: "token size"
231
+ };
232
+ const parts = token.split(".");
233
+ if (parts.length !== 3) return {
234
+ ok: false,
235
+ reason: "not a jws"
236
+ };
237
+ let header;
238
+ let claims;
239
+ try {
240
+ const h = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf8"));
241
+ const c = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
242
+ if (!isPlainObject(h) || !isPlainObject(c)) return {
243
+ ok: false,
244
+ reason: "malformed json"
245
+ };
246
+ header = h;
247
+ claims = c;
248
+ } catch {
249
+ return {
250
+ ok: false,
251
+ reason: "malformed json"
252
+ };
253
+ }
254
+ if (header.alg !== "ES256") return {
255
+ ok: false,
256
+ reason: "alg"
257
+ };
258
+ if (header.typ !== "marver-assertion+jwt") return {
259
+ ok: false,
260
+ reason: "typ"
261
+ };
262
+ if ("jku" in header || "x5u" in header || "jwk" in header) return {
263
+ ok: false,
264
+ reason: "header injection"
265
+ };
266
+ const kid = typeof header.kid === "string" ? header.kid : null;
267
+ if (!kid || kid.length > 128) return {
268
+ ok: false,
269
+ reason: "kid"
270
+ };
271
+ if (claims.iss !== issuer) return {
272
+ ok: false,
273
+ reason: "iss"
274
+ };
275
+ if (claims.aud !== origin) return {
276
+ ok: false,
277
+ reason: "aud"
278
+ };
279
+ if (claims.email_verified !== true) return {
280
+ ok: false,
281
+ reason: "email unverified"
282
+ };
283
+ const sub = typeof claims.sub === "string" ? claims.sub : "";
284
+ const email = typeof claims.email === "string" ? claims.email : "";
285
+ const nonce = typeof claims.nonce === "string" ? claims.nonce : "";
286
+ if (!sub || !email || !nonce) return {
287
+ ok: false,
288
+ reason: "missing claims"
289
+ };
290
+ const now = Math.floor(Date.now() / 1e3);
291
+ const exp = typeof claims.exp === "number" ? claims.exp : 0;
292
+ const nbf = typeof claims.nbf === "number" ? claims.nbf : 0;
293
+ const iat = typeof claims.iat === "number" ? claims.iat : 0;
294
+ if (!exp || exp + CLOCK_TOLERANCE_S < now) return {
295
+ ok: false,
296
+ reason: "expired"
297
+ };
298
+ if (nbf && nbf - CLOCK_TOLERANCE_S > now) return {
299
+ ok: false,
300
+ reason: "not yet valid"
301
+ };
302
+ if (!iat || iat - CLOCK_TOLERANCE_S > now) return {
303
+ ok: false,
304
+ reason: "issued in the future"
305
+ };
306
+ const tx = store.consume(nonce, browser);
307
+ if (!tx) return {
308
+ ok: false,
309
+ reason: "unknown or spent nonce"
310
+ };
311
+ if (tx.origin !== origin) return {
312
+ ok: false,
313
+ reason: "origin mismatch"
314
+ };
315
+ opts.onConsumed?.(tx);
316
+ let verified = false;
317
+ try {
318
+ verified = await verifySignature(parts, kid, issuer);
319
+ } catch {
320
+ return {
321
+ ok: false,
322
+ reason: "key fetch failed"
323
+ };
324
+ }
325
+ if (!verified) return {
326
+ ok: false,
327
+ reason: "signature"
328
+ };
329
+ return {
330
+ ok: true,
331
+ identity: {
332
+ subject: sub,
333
+ email,
334
+ ...displayClaims(claims)
335
+ }
336
+ };
337
+ }
338
+ async function verifySignature(parts, kid, issuer) {
339
+ let jwks = await fetchJwks(issuer);
340
+ let jwk = jwks.keys.find((k) => k.kid === kid);
341
+ if (!jwk && Date.now() - lastForcedFetch >= FORCED_FETCH_COOLDOWN_MS) {
342
+ lastForcedFetch = Date.now();
343
+ jwks = await fetchJwks(issuer, true);
344
+ jwk = jwks.keys.find((k) => k.kid === kid);
345
+ }
346
+ if (!jwk) return false;
347
+ const k = jwk;
348
+ if (k.kty !== "EC" || k.crv !== "P-256") return false;
349
+ if (k.alg && k.alg !== "ES256") return false;
350
+ if (k.use && k.use !== "sig") return false;
351
+ if (Array.isArray(k.key_ops) && !k.key_ops.includes("verify")) return false;
352
+ const { createPublicKey } = await import("node:crypto");
353
+ const key = createPublicKey({
354
+ key: jwk,
355
+ format: "jwk"
356
+ });
357
+ const signature = Buffer.from(parts[2], "base64url");
358
+ if (signature.length !== 64) return false;
359
+ const v = createVerify("SHA256");
360
+ v.update(`${parts[0]}.${parts[1]}`);
361
+ v.end();
362
+ return v.verify({
363
+ key,
364
+ dsaEncoding: "ieee-p1363"
365
+ }, signature);
366
+ }
367
+ /**
368
+ * The optional display claims, taken only if they are the right shape.
369
+ *
370
+ * Deliberately forgiving: a malformed name or picture drops that ONE field and
371
+ * lets the sign-in through, because neither decides anything. Refusing a valid
372
+ * assertion over a bad avatar URL would trade a cosmetic problem for a lockout.
373
+ *
374
+ * The bounds are what stop this being a hole. A name is capped so it cannot be
375
+ * used to write a paragraph into somebody's comment sidebar, and control
376
+ * characters go because that is how a value gets smuggled into a log line. A
377
+ * picture must be https and bounded - the canvas will make a server-side request
378
+ * to whatever survives this, so http, data:, file: and friends never get that
379
+ * far.
380
+ */
381
+ function displayClaims(claims) {
382
+ const out = {};
383
+ const name = (typeof claims.name === "string" ? claims.name : "").replace(/[\u0000-\u001f\u007f]/g, "").replace(/\s+/g, " ").trim().slice(0, 80);
384
+ if (name) out.name = name;
385
+ if (typeof claims.picture === "string" && claims.picture.length <= 2048) try {
386
+ const u = new URL(claims.picture);
387
+ if (u.protocol === "https:" && !u.username && !u.password) out.picture = u.toString();
388
+ } catch {}
389
+ return out;
390
+ }
391
+ /** A JSON object, and not an array or null - both of which pass `typeof === 'object'`. */
392
+ function isPlainObject(v) {
393
+ return typeof v === "object" && v !== null && !Array.isArray(v);
394
+ }
395
+ /** Length-safe string compare, so a mismatch leaks nothing through timing. */
396
+ function constantTimeEqual(a, b) {
397
+ const ha = createHash("sha256").update(a).digest();
398
+ const hb = createHash("sha256").update(b).digest();
399
+ return timingSafeEqual(ha, hb);
400
+ }
401
+ /**
402
+ * A stable, opaque handle for "this browser", used to bind a transaction to the
403
+ * client that started it. Derived from a random cookie value the canvas already
404
+ * sets - never from IP or user agent, both of which change legitimately
405
+ * mid-flow (mobile networks, upgrades) and would lock people out.
406
+ */
407
+ function browserBinding(cookieValue) {
408
+ return createHash("sha256").update(cookieValue).digest("base64url");
409
+ }
410
+ //#endregion
411
+ export { TransactionStore, browserBinding, normalizeIssuer, verifyAssertion };