@coffre/conformance 0.0.0 → 0.1.1

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,1122 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { SignJWT, exportJWK, generateKeyPair } from "jose";
4
+ //#region src/idp/http.ts
5
+ function sendJson(res, status, body, headers = {}) {
6
+ res.writeHead(status, {
7
+ "content-type": "application/json",
8
+ ...headers
9
+ });
10
+ res.end(JSON.stringify(body));
11
+ }
12
+ function sendHtml(res, status, html) {
13
+ res.writeHead(status, {
14
+ "content-type": "text/html; charset=utf-8",
15
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'",
16
+ "x-frame-options": "DENY",
17
+ "cache-control": "no-store"
18
+ });
19
+ res.end(html);
20
+ }
21
+ function redirect(res, location) {
22
+ res.writeHead(302, {
23
+ location,
24
+ "cache-control": "no-store"
25
+ });
26
+ res.end();
27
+ }
28
+ function escapeHtml(value) {
29
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
30
+ }
31
+ /**
32
+ * Read a form or JSON body as parameters. Returns null for a body that does
33
+ * not parse, so callers can answer with their own protocol's error shape.
34
+ */
35
+ async function readParams(req) {
36
+ const chunks = [];
37
+ let size = 0;
38
+ for await (const chunk of req) {
39
+ size += chunk.length;
40
+ if (size > 65536) return null;
41
+ chunks.push(chunk);
42
+ }
43
+ const body = Buffer.concat(chunks).toString("utf8");
44
+ const type = (req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
45
+ if (type === "application/json") try {
46
+ const parsed = JSON.parse(body);
47
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
48
+ const params = new URLSearchParams();
49
+ for (const [key, value] of Object.entries(parsed)) if (typeof value === "string") params.set(key, value);
50
+ return params;
51
+ } catch {
52
+ return null;
53
+ }
54
+ if (type === "application/x-www-form-urlencoded") return new URLSearchParams(body);
55
+ return null;
56
+ }
57
+ /** RFC 6749 §3.1: request parameters must not be included more than once. */
58
+ function repeatedParam(params) {
59
+ const seen = /* @__PURE__ */ new Set();
60
+ for (const key of params.keys()) {
61
+ if (seen.has(key)) return key;
62
+ seen.add(key);
63
+ }
64
+ }
65
+ /** The token from `Authorization: <scheme> <token>`, for any of the given schemes. */
66
+ function authorizationToken(req, schemes) {
67
+ const match = /^(\S+) +(\S+)$/.exec(req.headers.authorization ?? "");
68
+ if (!match || !schemes.includes(match[1].toLowerCase())) return void 0;
69
+ return match[2];
70
+ }
71
+ //#endregion
72
+ //#region src/idp/people.ts
73
+ /**
74
+ * The people the sign-in pages offer. Mirrors the users in
75
+ * `dev/seed-config.mjs` (a test keeps the two in step), so each button
76
+ * lands on a seeded account.
77
+ */
78
+ const PERSONAS = Object.freeze([
79
+ {
80
+ email: "admin@acme.example",
81
+ name: "Ada Admin",
82
+ note: "root admin"
83
+ },
84
+ {
85
+ email: "lead@acme.example",
86
+ name: "Lea Lead",
87
+ note: "owner"
88
+ },
89
+ {
90
+ email: "dev@acme.example",
91
+ name: "Devon Dev",
92
+ note: "developer on dev"
93
+ },
94
+ {
95
+ email: "auditor@acme.example",
96
+ name: "Audrey Auditor",
97
+ note: "auditor"
98
+ },
99
+ {
100
+ email: "accessmgr@acme.example",
101
+ name: "Max Access",
102
+ note: "access manager"
103
+ },
104
+ {
105
+ email: "outsider@acme.example",
106
+ name: "Otto Outsider",
107
+ note: "registered, no grants"
108
+ }
109
+ ]);
110
+ function normalizeEmail(email) {
111
+ return email.trim().toLowerCase();
112
+ }
113
+ function isEmail(value) {
114
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
115
+ }
116
+ function sha256Hex(value) {
117
+ return createHash("sha256").update(value).digest("hex");
118
+ }
119
+ /**
120
+ * Stable for an email but deliberately not the email, the way real providers
121
+ * key accounts: a client that binds to `sub` survives an address changing
122
+ * hands, one that binds to `email` does not.
123
+ */
124
+ function defaultSubject(email) {
125
+ return `dev-${sha256Hex(email).slice(0, 24)}`;
126
+ }
127
+ function displayName(email) {
128
+ const persona = PERSONAS.find((p) => p.email === email);
129
+ if (persona) return persona.name;
130
+ const local = email.split("@")[0];
131
+ return local.charAt(0).toUpperCase() + local.slice(1);
132
+ }
133
+ /**
134
+ * Outsider's GitHub account also lists lead's address, unverified: a client
135
+ * that trusts unverified emails signs Otto in as Lea.
136
+ */
137
+ const UNVERIFIED_GITHUB_EMAILS = { "outsider@acme.example": ["lead@acme.example"] };
138
+ function gitHubEmails(list) {
139
+ const primary = Math.max(0, list.findIndex((e) => e.primary));
140
+ return list.map((e, i) => ({
141
+ email: normalizeEmail(e.email),
142
+ primary: i === primary,
143
+ verified: e.verified ?? true,
144
+ visibility: e.visibility !== void 0 ? e.visibility : i === primary ? "public" : null
145
+ }));
146
+ }
147
+ /** Stable per email, so a persona keeps its numeric id across runs. */
148
+ function defaultGitHubAccount(email) {
149
+ const unverified = UNVERIFIED_GITHUB_EMAILS[email] ?? [];
150
+ return {
151
+ id: 1e6 + Number.parseInt(sha256Hex(`github:${email}`).slice(0, 7), 16),
152
+ login: email.split("@")[0].replace(/[^A-Za-z0-9-]/g, "-"),
153
+ name: displayName(email),
154
+ emails: gitHubEmails([{ email }, ...unverified.map((e) => ({
155
+ email: e,
156
+ verified: false
157
+ }))]),
158
+ orgs: ["acme"]
159
+ };
160
+ }
161
+ //#endregion
162
+ //#region src/idp/pages.ts
163
+ const STYLE = `
164
+ :root { color-scheme: light dark; --fg: #1c1c1e; --muted: #6b6b70; --line: #dcdce0;
165
+ --bg: #fafafa; --card: #fff; --accent: #2f5bd3; --danger: #b3261e; }
166
+ @media (prefers-color-scheme: dark) { :root { --fg: #ececee; --muted: #9a9aa2;
167
+ --line: #34343a; --bg: #151517; --card: #1d1d20; --accent: #8aa8ff; --danger: #ff8a80; } }
168
+ * { box-sizing: border-box; }
169
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: var(--bg);
170
+ color: var(--fg); font: 15px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; }
171
+ main { width: min(440px, calc(100vw - 32px)); margin: 32px 0; }
172
+ .eyebrow { margin: 0; color: var(--muted); font-size: 13px; }
173
+ h1 { margin: 4px 0 6px; font-size: 20px; font-weight: 600; }
174
+ p { margin: 0 0 16px; color: var(--muted); }
175
+ code { font: 13px ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--fg); word-break: break-all; }
176
+ ul { list-style: none; margin: 0 0 16px; padding: 0; border: 1px solid var(--line);
177
+ border-radius: 8px; background: var(--card); overflow: hidden; }
178
+ li + li { border-top: 1px solid var(--line); }
179
+ button { font: inherit; cursor: pointer; }
180
+ .persona { all: unset; box-sizing: border-box; display: grid; grid-template-columns: 1fr auto;
181
+ width: 100%; padding: 10px 14px; cursor: pointer; }
182
+ .persona:hover, .persona:focus-visible { background: color-mix(in srgb, var(--accent) 8%, transparent); }
183
+ .persona:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
184
+ .persona small { grid-column: 1; color: var(--muted); }
185
+ .persona em { grid-row: 1 / span 2; grid-column: 2; align-self: center; font-style: normal;
186
+ font-size: 12px; color: var(--muted); }
187
+ .other { display: flex; gap: 8px; margin-bottom: 12px; }
188
+ input { flex: 1; min-width: 0; font: inherit; padding: 7px 10px; color: var(--fg);
189
+ background: var(--card); border: 1px solid var(--line); border-radius: 6px; }
190
+ .primary { padding: 7px 14px; border: 0; border-radius: 6px; background: var(--accent); color: var(--bg); }
191
+ .deny { padding: 0; border: 0; background: none; color: var(--muted); text-decoration: underline; }
192
+ .error { color: var(--danger); }
193
+ `;
194
+ function layout(title, body) {
195
+ return `<!doctype html>
196
+ <html lang="en">
197
+ <head>
198
+ <meta charset="utf-8">
199
+ <meta name="viewport" content="width=device-width, initial-scale=1">
200
+ <title>${escapeHtml(title)}</title>
201
+ <style>${STYLE}</style>
202
+ </head>
203
+ <body><main>
204
+ ${body}
205
+ </main></body>
206
+ </html>
207
+ `;
208
+ }
209
+ function hiddenInputs(params) {
210
+ return [...params].map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`).join("");
211
+ }
212
+ function consentPage(opts) {
213
+ const carry = hiddenInputs(opts.carry);
214
+ const personas = PERSONAS.map((p) => `<li><button class="persona" name="email" value="${escapeHtml(p.email)}">
215
+ <span>${escapeHtml(p.name)}</span><small>${escapeHtml(p.email)}</small><em>${escapeHtml(p.note)}</em>
216
+ </button></li>`).join("\n");
217
+ const scope = opts.scope.length > 0 ? opts.scope.join(" ") : "(none)";
218
+ return layout(`Sign in to ${opts.clientId}`, `<p class="eyebrow">${escapeHtml(opts.label)}</p>
219
+ <h1>Sign in to <code>${escapeHtml(opts.clientId)}</code></h1>
220
+ <p>Returns to <code>${escapeHtml(opts.redirectUri)}</code><br>with scope <code>${escapeHtml(scope)}</code></p>
221
+ ${opts.message ? `<p class="error">${escapeHtml(opts.message)}</p>` : ""}
222
+ <form method="post" action="${escapeHtml(opts.action)}">${carry}
223
+ <ul>
224
+ ${personas}
225
+ </ul>
226
+ </form>
227
+ <form method="post" action="${escapeHtml(opts.action)}" class="other">${carry}
228
+ <input type="email" name="email" required placeholder="someone@example.com" aria-label="Another email" value="${escapeHtml(opts.hint ?? "")}">
229
+ <button class="primary">Continue</button>
230
+ </form>
231
+ <form method="post" action="${escapeHtml(opts.action)}">${carry}
232
+ <button class="deny" name="deny" value="1">Deny access</button>
233
+ </form>`);
234
+ }
235
+ /** For requests that cannot safely be sent back to the client. */
236
+ function errorPage(label, message) {
237
+ return layout("Sign-in error", `<p class="eyebrow">${escapeHtml(label)}</p>
238
+ <h1>This sign-in request is invalid</h1>
239
+ <p class="error">${escapeHtml(message)}</p>
240
+ <p>The client was not redirected back, because it or its redirect URI could not be trusted.</p>`);
241
+ }
242
+ //#endregion
243
+ //#region src/idp/authorize.ts
244
+ function randomToken() {
245
+ return randomBytes(32).toString("base64url");
246
+ }
247
+ /**
248
+ * The built-in client accepts any loopback URI, because local dev ports vary;
249
+ * every other redirect URI must match a registered one exactly.
250
+ */
251
+ function allowsRedirect(client, uri) {
252
+ if (client.redirectUris.includes(uri)) return true;
253
+ if (!client.anyLoopbackRedirect) return false;
254
+ let url;
255
+ try {
256
+ url = new URL(uri);
257
+ } catch {
258
+ return false;
259
+ }
260
+ return url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "localhost") && url.username === "" && url.password === "" && !uri.includes("#");
261
+ }
262
+ /** RFC 7636 §4.6, S256 only. */
263
+ function verifies(verifier, challenge) {
264
+ if (!/^[A-Za-z0-9\-._~]{43,128}$/.test(verifier)) return false;
265
+ return createHash("sha256").update(verifier).digest("base64url") === challenge;
266
+ }
267
+ /** Codes and the access tokens they turn into, for both flavors. In memory only. */
268
+ var AuthorizationServer = class {
269
+ #idp;
270
+ #codes = /* @__PURE__ */ new Map();
271
+ #tokens = /* @__PURE__ */ new Map();
272
+ constructor(idp) {
273
+ this.#idp = idp;
274
+ }
275
+ /** The GET (show the page, or auto-approve) and POST (the page's answer) routes. */
276
+ routes(flavor) {
277
+ return [{
278
+ method: "GET",
279
+ path: flavor.path,
280
+ handler: async (_req, res, url) => {
281
+ const parsed = this.#parse(flavor, url.searchParams);
282
+ if (parsed.kind !== "ok") return this.#fail(flavor, res, parsed);
283
+ const hint = parsed.request.hint;
284
+ if (this.#idp.autoApprove && hint !== void 0 && isEmail(hint)) return redirect(res, this.#approve(flavor, parsed, normalizeEmail(hint)));
285
+ this.#page(flavor, res, 200, parsed, url.searchParams);
286
+ }
287
+ }, {
288
+ method: "POST",
289
+ path: flavor.path,
290
+ handler: async (req, res) => {
291
+ const params = await readParams(req);
292
+ if (params === null) return sendHtml(res, 400, errorPage(flavor.label, "The form could not be read."));
293
+ const email = normalizeEmail(params.get("email") ?? "");
294
+ const deny = params.has("deny");
295
+ params.delete("email");
296
+ params.delete("deny");
297
+ const parsed = this.#parse(flavor, params);
298
+ if (parsed.kind !== "ok") return this.#fail(flavor, res, parsed);
299
+ if (deny) return redirect(res, this.#location(flavor, parsed.redirectUri, {
300
+ error: "access_denied",
301
+ ...flavor.denied,
302
+ state: parsed.state
303
+ }));
304
+ if (!isEmail(email)) return this.#page(flavor, res, 400, parsed, params, "Pick a persona or enter an email address.");
305
+ redirect(res, this.#approve(flavor, parsed, email));
306
+ }
307
+ }];
308
+ }
309
+ /**
310
+ * Redeem a code. Codes are single-use even when the attempt fails, and
311
+ * presenting a spent code revokes the token it produced (RFC 6749 §4.1.2).
312
+ */
313
+ exchange(flavor, opts) {
314
+ this.#sweep();
315
+ const record = this.#codes.get(opts.code);
316
+ if (!record || record.grant.flavor !== flavor) return {
317
+ ok: false,
318
+ error: "invalid_code"
319
+ };
320
+ if (record.used) {
321
+ if (record.accessToken) this.#tokens.delete(record.accessToken);
322
+ this.#codes.delete(opts.code);
323
+ return {
324
+ ok: false,
325
+ error: "invalid_code"
326
+ };
327
+ }
328
+ record.used = true;
329
+ const { grant } = record;
330
+ if (grant.clientId !== opts.client.clientId) return {
331
+ ok: false,
332
+ error: "invalid_code"
333
+ };
334
+ if (opts.redirectUri !== void 0 && opts.redirectUri !== grant.redirectUri) return {
335
+ ok: false,
336
+ error: "redirect_uri_mismatch"
337
+ };
338
+ if (!verifies(opts.codeVerifier, grant.codeChallenge)) return {
339
+ ok: false,
340
+ error: "invalid_verifier"
341
+ };
342
+ const accessToken = (opts.accessTokenPrefix ?? "") + randomToken();
343
+ record.accessToken = accessToken;
344
+ this.#tokens.set(accessToken, {
345
+ grant,
346
+ expiresAt: Date.now() + opts.accessTokenTtl * 1e3
347
+ });
348
+ return {
349
+ ok: true,
350
+ grant,
351
+ accessToken,
352
+ expiresIn: opts.accessTokenTtl
353
+ };
354
+ }
355
+ /** The grant behind a live access token of this flavor. */
356
+ grantFor(flavor, accessToken) {
357
+ const record = this.#tokens.get(accessToken);
358
+ if (!record || record.grant.flavor !== flavor || record.expiresAt <= Date.now()) return void 0;
359
+ return record.grant;
360
+ }
361
+ #parse(flavor, params) {
362
+ const repeated = repeatedParam(params);
363
+ if (repeated) return {
364
+ kind: "untrusted",
365
+ message: `Parameter ${repeated} is repeated.`
366
+ };
367
+ const clientId = params.get("client_id");
368
+ if (!clientId) return {
369
+ kind: "untrusted",
370
+ message: "client_id is missing."
371
+ };
372
+ const client = this.#idp.client(clientId);
373
+ if (!client) return {
374
+ kind: "untrusted",
375
+ message: `Unknown client ${clientId}.`
376
+ };
377
+ const redirectUri = params.get("redirect_uri");
378
+ if (!redirectUri) return {
379
+ kind: "untrusted",
380
+ message: "redirect_uri is missing."
381
+ };
382
+ if (!allowsRedirect(client, redirectUri)) return {
383
+ kind: "untrusted",
384
+ message: `${redirectUri} is not a redirect URI registered for ${clientId}.`
385
+ };
386
+ const fail = (error, description) => ({
387
+ kind: "error",
388
+ redirectUri,
389
+ state: params.get("state") ?? void 0,
390
+ error,
391
+ description
392
+ });
393
+ const request = flavor.parse(params);
394
+ if ("error" in request) return fail(request.error, request.description);
395
+ const state = params.get("state");
396
+ if (!state) return fail("invalid_request", "state is required");
397
+ const method = params.get("code_challenge_method");
398
+ const codeChallenge = params.get("code_challenge");
399
+ if (!codeChallenge) return fail("invalid_request", "code_challenge is required");
400
+ if (method !== "S256") return fail("invalid_request", "code_challenge_method must be S256");
401
+ if (!/^[A-Za-z0-9_-]{43}$/.test(codeChallenge)) return fail("invalid_request", "code_challenge must be a base64url SHA-256 digest");
402
+ return {
403
+ kind: "ok",
404
+ client,
405
+ redirectUri,
406
+ state,
407
+ codeChallenge,
408
+ request
409
+ };
410
+ }
411
+ #fail(flavor, res, parsed) {
412
+ if (parsed.kind === "untrusted") return sendHtml(res, 400, errorPage(flavor.label, parsed.message));
413
+ redirect(res, this.#location(flavor, parsed.redirectUri, {
414
+ error: parsed.error,
415
+ error_description: parsed.description,
416
+ state: parsed.state
417
+ }));
418
+ }
419
+ #page(flavor, res, status, parsed, carry, message) {
420
+ sendHtml(res, status, consentPage({
421
+ label: flavor.label,
422
+ action: flavor.path,
423
+ clientId: parsed.client.clientId,
424
+ redirectUri: parsed.redirectUri,
425
+ scope: parsed.request.scope,
426
+ carry,
427
+ hint: parsed.request.hint,
428
+ message
429
+ }));
430
+ }
431
+ #approve(flavor, parsed, email) {
432
+ this.#sweep();
433
+ const code = randomToken();
434
+ this.#codes.set(code, {
435
+ grant: {
436
+ flavor: flavor.name,
437
+ clientId: parsed.client.clientId,
438
+ redirectUri: parsed.redirectUri,
439
+ scope: parsed.request.scope,
440
+ nonce: parsed.request.nonce,
441
+ codeChallenge: parsed.codeChallenge,
442
+ email,
443
+ authTime: Math.floor(Date.now() / 1e3)
444
+ },
445
+ expiresAt: Date.now() + flavor.codeTtl * 1e3,
446
+ used: false
447
+ });
448
+ return this.#location(flavor, parsed.redirectUri, {
449
+ code,
450
+ state: parsed.state
451
+ });
452
+ }
453
+ #location(flavor, redirectUri, params) {
454
+ const url = new URL(redirectUri);
455
+ for (const [name, value] of Object.entries(params)) if (value !== void 0) url.searchParams.set(name, value);
456
+ if (flavor.issuer) url.searchParams.set("iss", flavor.issuer());
457
+ return url.href;
458
+ }
459
+ #sweep() {
460
+ const now = Date.now();
461
+ for (const [code, record] of this.#codes) if (record.expiresAt <= now) this.#codes.delete(code);
462
+ for (const [token, record] of this.#tokens) if (record.expiresAt <= now) this.#tokens.delete(token);
463
+ }
464
+ };
465
+ //#endregion
466
+ //#region src/idp/github.ts
467
+ const WEB = "/github";
468
+ const API = "/github/api";
469
+ const DOCS = "https://docs.github.com/rest";
470
+ const TROUBLESHOOTING = "https://docs.github.com/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors";
471
+ /**
472
+ * Enough of GitHub's OAuth apps and REST API for coffre's GitHub sign-in:
473
+ * the web flow, the authenticated user, their emails, and org membership.
474
+ * GitHub is not an OIDC provider, and its token endpoint has quirks a
475
+ * standard OAuth client trips on; this imitates them rather than smoothing
476
+ * them over.
477
+ */
478
+ var FakeGitHub = class {
479
+ #idp;
480
+ #authz;
481
+ flavor;
482
+ constructor(idp, authz) {
483
+ this.#idp = idp;
484
+ this.#authz = authz;
485
+ this.flavor = {
486
+ name: "github",
487
+ path: `${WEB}/login/oauth/authorize`,
488
+ label: "coffre dev IdP · fake GitHub",
489
+ codeTtl: 600,
490
+ issuer: null,
491
+ parse(params) {
492
+ const scope = (params.get("scope") ?? "").split(/[\s,]+/).filter(Boolean);
493
+ const login = params.get("login") ?? void 0;
494
+ const hint = params.get("login_hint") ?? (login === void 0 || isEmail(login) ? login : idp.emailForGitHubLogin(login));
495
+ return {
496
+ scope: [...new Set(scope)],
497
+ hint
498
+ };
499
+ },
500
+ denied: {
501
+ error_description: "The user has denied your application access.",
502
+ error_uri: "https://docs.github.com/apps/managing-oauth-apps/troubleshooting-authorization-request-errors/#access-denied"
503
+ }
504
+ };
505
+ }
506
+ routes() {
507
+ return [
508
+ ...this.#authz.routes(this.flavor),
509
+ {
510
+ method: "POST",
511
+ path: `${WEB}/login/oauth/access_token`,
512
+ handler: (req, res) => this.#accessToken(req, res)
513
+ },
514
+ {
515
+ method: "GET",
516
+ path: `${API}/user`,
517
+ handler: async (req, res) => this.#user(req, res)
518
+ },
519
+ {
520
+ method: "GET",
521
+ path: `${API}/user/emails`,
522
+ handler: async (req, res) => this.#emails(req, res)
523
+ },
524
+ {
525
+ method: "GET",
526
+ path: new RegExp(`^${API}/user/memberships/orgs/[^/]+$`),
527
+ handler: async (req, res, url) => this.#membership(req, res, decodeURIComponent(url.pathname.split("/").pop()))
528
+ }
529
+ ];
530
+ }
531
+ /**
532
+ * The quirks: JSON only when asked for with `Accept`, form-encoded
533
+ * otherwise; errors are HTTP 200 with an `error` field; scopes come back
534
+ * comma-separated.
535
+ * https://docs.github.com/en/apps/oauth-apps/maintaining-oauth-apps/troubleshooting-oauth-app-access-token-request-errors
536
+ */
537
+ async #accessToken(req, res) {
538
+ const reply = (body) => {
539
+ if ((req.headers.accept ?? "").includes("application/json")) return sendJson(res, 200, body);
540
+ res.writeHead(200, { "content-type": "application/x-www-form-urlencoded; charset=utf-8" });
541
+ res.end(new URLSearchParams(body).toString());
542
+ };
543
+ const fail = (error, description) => reply({
544
+ error,
545
+ error_description: description,
546
+ error_uri: `${TROUBLESHOOTING}#${error.replaceAll("_", "-")}`
547
+ });
548
+ const params = await readParams(req) ?? new URLSearchParams();
549
+ let clientId = params.get("client_id");
550
+ let clientSecret = params.get("client_secret");
551
+ const basic = authorizationToken(req, ["basic"]);
552
+ if (basic !== void 0 && clientSecret === null) {
553
+ const decoded = Buffer.from(basic, "base64").toString("utf8");
554
+ const colon = decoded.indexOf(":");
555
+ clientId = decoded.slice(0, colon);
556
+ clientSecret = decoded.slice(colon + 1);
557
+ }
558
+ const client = clientId ? this.#idp.client(clientId) : void 0;
559
+ if (!client || client.clientSecret !== clientSecret) return fail("incorrect_client_credentials", "The client_id and/or client_secret passed are incorrect.");
560
+ const result = this.#authz.exchange("github", {
561
+ client,
562
+ code: params.get("code") ?? "",
563
+ redirectUri: params.get("redirect_uri") ?? void 0,
564
+ codeVerifier: params.get("code_verifier") ?? "",
565
+ accessTokenTtl: Infinity,
566
+ accessTokenPrefix: "gho_"
567
+ });
568
+ if (!result.ok) {
569
+ if (result.error === "redirect_uri_mismatch") return fail("redirect_uri_mismatch", "The redirect_uri MUST match the registered callback URL for this application.");
570
+ return fail("bad_verification_code", "The code passed is incorrect or expired.");
571
+ }
572
+ reply({
573
+ access_token: result.accessToken,
574
+ token_type: "bearer",
575
+ scope: result.grant.scope.join(",")
576
+ });
577
+ }
578
+ /** https://docs.github.com/en/rest/users/users#get-the-authenticated-user */
579
+ #user(req, res) {
580
+ const auth = this.#authenticate(req, res);
581
+ if (!auth) return;
582
+ const { account } = auth;
583
+ const publicEmail = account.emails.find((e) => e.primary && e.visibility === "public");
584
+ this.#json(res, auth.grant, 200, {
585
+ login: account.login,
586
+ id: account.id,
587
+ node_id: `U_dev${account.id}`,
588
+ html_url: `${this.#idp.origin}${WEB}/${account.login}`,
589
+ type: "User",
590
+ site_admin: false,
591
+ name: account.name,
592
+ email: publicEmail?.email ?? null
593
+ });
594
+ }
595
+ /**
596
+ * Needs `user:email` (or `user`). Without it GitHub answers 404, not 403.
597
+ * https://docs.github.com/en/rest/users/emails#list-email-addresses-for-the-authenticated-user
598
+ */
599
+ #emails(req, res) {
600
+ const auth = this.#authenticate(req, res);
601
+ if (!auth) return;
602
+ if (!this.#hasScope(auth.grant, ["user:email", "user"])) return this.#notFound(res, auth.grant);
603
+ this.#json(res, auth.grant, 200, auth.account.emails);
604
+ }
605
+ /**
606
+ * Needs `read:org` (implied by `write:org`, `admin:org` and `user`), else 403;
607
+ * 404 when the user is not a member.
608
+ * https://docs.github.com/en/rest/orgs/members#get-an-organization-membership-for-the-authenticated-user
609
+ * https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
610
+ */
611
+ #membership(req, res, org) {
612
+ const auth = this.#authenticate(req, res);
613
+ if (!auth) return;
614
+ if (!this.#hasScope(auth.grant, [
615
+ "read:org",
616
+ "write:org",
617
+ "admin:org",
618
+ "user"
619
+ ])) return this.#json(res, auth.grant, 403, {
620
+ message: "You need at least read:org scope or user scope to read organization memberships.",
621
+ documentation_url: DOCS
622
+ });
623
+ const login = auth.account.orgs.find((o) => o.toLowerCase() === org.toLowerCase());
624
+ if (!login) return this.#notFound(res, auth.grant);
625
+ const api = `${this.#idp.origin}${API}`;
626
+ this.#json(res, auth.grant, 200, {
627
+ url: `${api}/orgs/${login}/memberships/${auth.account.login}`,
628
+ state: "active",
629
+ role: "member",
630
+ organization_url: `${api}/orgs/${login}`,
631
+ organization: {
632
+ login,
633
+ id: 2e6 + Number.parseInt(sha256Hex(`github-org:${login.toLowerCase()}`).slice(0, 7), 16),
634
+ url: `${api}/orgs/${login}`
635
+ },
636
+ user: {
637
+ login: auth.account.login,
638
+ id: auth.account.id,
639
+ type: "User"
640
+ }
641
+ });
642
+ }
643
+ /** `Bearer` or GitHub's older `token` scheme; 401 otherwise. */
644
+ #authenticate(req, res) {
645
+ const token = authorizationToken(req, ["bearer", "token"]);
646
+ if (token === void 0) {
647
+ sendJson(res, 401, {
648
+ message: "Requires authentication",
649
+ documentation_url: DOCS
650
+ });
651
+ return;
652
+ }
653
+ const grant = this.#authz.grantFor("github", token);
654
+ if (!grant) {
655
+ sendJson(res, 401, {
656
+ message: "Bad credentials",
657
+ documentation_url: DOCS
658
+ });
659
+ return;
660
+ }
661
+ return {
662
+ grant,
663
+ account: this.#idp.gitHubUserFor(normalizeEmail(grant.email))
664
+ };
665
+ }
666
+ #hasScope(grant, accepted) {
667
+ return grant.scope.some((s) => accepted.includes(s));
668
+ }
669
+ /** Every authenticated response lists the token's scopes, as GitHub's do. */
670
+ #json(res, grant, status, body) {
671
+ sendJson(res, status, body, { "x-oauth-scopes": grant.scope.join(", ") });
672
+ }
673
+ #notFound(res, grant) {
674
+ this.#json(res, grant, 404, {
675
+ message: "Not Found",
676
+ documentation_url: DOCS
677
+ });
678
+ }
679
+ };
680
+ //#endregion
681
+ //#region src/idp/oidc.ts
682
+ const ACCESS_TOKEN_TTL = 3600;
683
+ /**
684
+ * A small OpenID Connect provider: authorization code flow with PKCE,
685
+ * confidential clients, userinfo. Enough for a generic OIDC client to run
686
+ * its real code path end to end.
687
+ */
688
+ var OidcProvider = class {
689
+ #idp;
690
+ #authz;
691
+ flavor;
692
+ constructor(idp, authz) {
693
+ this.#idp = idp;
694
+ this.#authz = authz;
695
+ this.flavor = {
696
+ name: "oidc",
697
+ path: "/oauth/authorize",
698
+ label: "coffre dev IdP · OpenID Connect",
699
+ codeTtl: 60,
700
+ issuer: () => idp.issuer,
701
+ parse(params) {
702
+ const responseType = params.get("response_type");
703
+ if (!responseType) return {
704
+ error: "invalid_request",
705
+ description: "response_type is required"
706
+ };
707
+ if (responseType !== "code") return {
708
+ error: "unsupported_response_type",
709
+ description: "only response_type=code is supported"
710
+ };
711
+ const scope = (params.get("scope") ?? "").split(" ").filter(Boolean);
712
+ if (!scope.includes("openid")) return {
713
+ error: "invalid_scope",
714
+ description: "scope must include openid"
715
+ };
716
+ return {
717
+ scope: [...new Set(scope)],
718
+ nonce: params.get("nonce") ?? void 0,
719
+ hint: params.get("login_hint") ?? void 0
720
+ };
721
+ },
722
+ denied: { error_description: "The user denied the request" }
723
+ };
724
+ }
725
+ routes() {
726
+ return [
727
+ {
728
+ method: "GET",
729
+ path: "/.well-known/openid-configuration",
730
+ handler: async (_req, res) => sendJson(res, 200, this.#discovery())
731
+ },
732
+ ...this.#authz.routes(this.flavor),
733
+ {
734
+ method: "POST",
735
+ path: "/oauth/token",
736
+ handler: (req, res) => this.#token(req, res)
737
+ },
738
+ {
739
+ method: "GET",
740
+ path: "/oauth/userinfo",
741
+ handler: async (req, res) => this.#userinfo(req, res)
742
+ }
743
+ ];
744
+ }
745
+ #discovery() {
746
+ const origin = this.#idp.origin;
747
+ return {
748
+ issuer: this.#idp.issuer,
749
+ authorization_endpoint: `${origin}/oauth/authorize`,
750
+ token_endpoint: `${origin}/oauth/token`,
751
+ userinfo_endpoint: `${origin}/oauth/userinfo`,
752
+ jwks_uri: this.#idp.jwksUrl,
753
+ response_types_supported: ["code"],
754
+ response_modes_supported: ["query"],
755
+ grant_types_supported: ["authorization_code"],
756
+ subject_types_supported: ["public"],
757
+ id_token_signing_alg_values_supported: ["RS256"],
758
+ code_challenge_methods_supported: ["S256"],
759
+ token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"],
760
+ scopes_supported: [
761
+ "openid",
762
+ "email",
763
+ "profile"
764
+ ],
765
+ claims_supported: [
766
+ "iss",
767
+ "sub",
768
+ "aud",
769
+ "iat",
770
+ "exp",
771
+ "auth_time",
772
+ "nonce",
773
+ "email",
774
+ "email_verified",
775
+ "name"
776
+ ],
777
+ authorization_response_iss_parameter_supported: true
778
+ };
779
+ }
780
+ /** RFC 6749 §4.1.3, errors per §5.2. */
781
+ async #token(req, res) {
782
+ const fail = (status, error, description, headers = {}) => sendJson(res, status, {
783
+ error,
784
+ error_description: description
785
+ }, {
786
+ "cache-control": "no-store",
787
+ ...headers
788
+ });
789
+ const params = await readParams(req);
790
+ if (params === null) return fail(400, "invalid_request", "expected an application/x-www-form-urlencoded body");
791
+ const repeated = repeatedParam(params);
792
+ if (repeated) return fail(400, "invalid_request", `parameter ${repeated} is repeated`);
793
+ const auth = this.#authenticate(req, params);
794
+ if ("error" in auth) {
795
+ if (auth.error !== "invalid_client") return fail(400, auth.error, auth.description);
796
+ return fail(401, auth.error, auth.description, { "www-authenticate": "Basic realm=\"dev-idp\"" });
797
+ }
798
+ const grantType = params.get("grant_type");
799
+ if (grantType !== "authorization_code") return fail(400, grantType ? "unsupported_grant_type" : "invalid_request", "grant_type must be authorization_code");
800
+ const code = params.get("code");
801
+ const redirectUri = params.get("redirect_uri");
802
+ const codeVerifier = params.get("code_verifier");
803
+ if (!code || !redirectUri || !codeVerifier) return fail(400, "invalid_request", "code, redirect_uri and code_verifier are required");
804
+ const result = this.#authz.exchange("oidc", {
805
+ client: auth.client,
806
+ code,
807
+ redirectUri,
808
+ codeVerifier,
809
+ accessTokenTtl: ACCESS_TOKEN_TTL
810
+ });
811
+ if (!result.ok) {
812
+ const description = {
813
+ invalid_code: "the code is invalid, expired, already used, or was issued to another client",
814
+ redirect_uri_mismatch: "redirect_uri does not match the authorization request",
815
+ invalid_verifier: "code_verifier does not match the code_challenge"
816
+ }[result.error];
817
+ return fail(400, "invalid_grant", description);
818
+ }
819
+ const { grant } = result;
820
+ const idToken = await this.#idp.mintIdToken({
821
+ clientId: grant.clientId,
822
+ email: grant.email,
823
+ nonce: grant.nonce,
824
+ authTime: grant.authTime
825
+ });
826
+ sendJson(res, 200, {
827
+ access_token: result.accessToken,
828
+ token_type: "Bearer",
829
+ expires_in: result.expiresIn,
830
+ id_token: idToken,
831
+ scope: grant.scope.join(" ")
832
+ }, {
833
+ "cache-control": "no-store",
834
+ pragma: "no-cache"
835
+ });
836
+ }
837
+ /** client_secret_basic or client_secret_post, never both (RFC 6749 §2.3). */
838
+ #authenticate(req, params) {
839
+ const basic = authorizationToken(req, ["basic"]);
840
+ let clientId;
841
+ let clientSecret;
842
+ if (basic !== void 0) {
843
+ if (params.has("client_secret")) return {
844
+ error: "invalid_request",
845
+ description: "use one client authentication method"
846
+ };
847
+ const decoded = Buffer.from(basic, "base64").toString("utf8");
848
+ const colon = decoded.indexOf(":");
849
+ if (colon < 0) return {
850
+ error: "invalid_client",
851
+ description: "malformed Basic credentials"
852
+ };
853
+ try {
854
+ const formDecode = (s) => decodeURIComponent(s.replaceAll("+", " "));
855
+ clientId = formDecode(decoded.slice(0, colon));
856
+ clientSecret = formDecode(decoded.slice(colon + 1));
857
+ } catch {
858
+ return {
859
+ error: "invalid_client",
860
+ description: "malformed Basic credentials"
861
+ };
862
+ }
863
+ const bodyId = params.get("client_id");
864
+ if (bodyId !== null && bodyId !== clientId) return {
865
+ error: "invalid_client",
866
+ description: "client_id does not match the credentials"
867
+ };
868
+ } else {
869
+ clientId = params.get("client_id");
870
+ clientSecret = params.get("client_secret");
871
+ }
872
+ if (!clientId || !clientSecret) return {
873
+ error: "invalid_client",
874
+ description: "client authentication is required"
875
+ };
876
+ const client = this.#idp.client(clientId);
877
+ if (!client || client.clientSecret !== clientSecret) return {
878
+ error: "invalid_client",
879
+ description: "unknown client or wrong secret"
880
+ };
881
+ return { client };
882
+ }
883
+ #userinfo(req, res) {
884
+ const token = authorizationToken(req, ["bearer"]);
885
+ if (token === void 0) return sendJson(res, 401, { error: "invalid_request" }, { "www-authenticate": "Bearer realm=\"dev-idp\"" });
886
+ const grant = this.#authz.grantFor("oidc", token);
887
+ if (!grant) return sendJson(res, 401, { error: "invalid_token" }, { "www-authenticate": "Bearer realm=\"dev-idp\", error=\"invalid_token\"" });
888
+ sendJson(res, 200, {
889
+ sub: this.#idp.subjectFor(grant.email),
890
+ email: grant.email,
891
+ email_verified: true,
892
+ name: displayName(grant.email)
893
+ }, { "cache-control": "no-store" });
894
+ }
895
+ };
896
+ //#endregion
897
+ //#region src/idp/idp.ts
898
+ /** Built in, so local dev needs no registration step. */
899
+ const DEFAULT_CLIENT = Object.freeze({
900
+ clientId: "coffre-local",
901
+ clientSecret: "coffre-local-secret"
902
+ });
903
+ /**
904
+ * A local stand-in for the identity providers coffre trusts.
905
+ *
906
+ * For Cloudflare Access, it generates a keypair, serves a JWKS at the same
907
+ * `cdn-cgi` path Access uses, and mints Access-shaped tokens. It is also an
908
+ * OpenID Connect provider (under `/oauth`) signing with the same key, and an
909
+ * imitation of GitHub's OAuth apps and REST API (under `/github`). The
910
+ * point is that the code under test runs its real remote code paths against
911
+ * real HTTP endpoints -- local mode is a different implementation of the same
912
+ * interface, never a branch that skips verification.
913
+ */
914
+ var DevIdp = class {
915
+ #server = null;
916
+ #port = 0;
917
+ #clients = /* @__PURE__ */ new Map();
918
+ #subjects = /* @__PURE__ */ new Map();
919
+ #gitHubAccounts = /* @__PURE__ */ new Map();
920
+ #routes;
921
+ privateKey;
922
+ publicJwk;
923
+ kid = "dev-idp-key-1";
924
+ /** Used by the /dev/mint convenience endpoint when no aud is supplied. */
925
+ defaultAudience = "coffre-local-dev-aud";
926
+ /** Fixed port for the standalone dev server; 0 (ephemeral) in tests. */
927
+ listenPort = 0;
928
+ /** See {@link DevIdpOptions.autoApprove}. */
929
+ autoApprove;
930
+ constructor(options = {}) {
931
+ this.autoApprove = options.autoApprove ?? false;
932
+ this.#clients.set(DEFAULT_CLIENT.clientId, {
933
+ ...DEFAULT_CLIENT,
934
+ redirectUris: [],
935
+ anyLoopbackRedirect: true
936
+ });
937
+ for (const client of options.clients ?? []) this.registerClient(client);
938
+ const authz = new AuthorizationServer(this);
939
+ this.#routes = [...new OidcProvider(this, authz).routes(), ...new FakeGitHub(this, authz).routes()];
940
+ }
941
+ get origin() {
942
+ if (this.#port === 0) throw new Error("DevIdp is not started");
943
+ return `http://127.0.0.1:${this.#port}`;
944
+ }
945
+ /** Matches the Cloudflare Access team-domain issuer shape. */
946
+ get issuer() {
947
+ return this.origin;
948
+ }
949
+ /** Access publishes its keys under this exact path. */
950
+ get jwksUrl() {
951
+ return `${this.origin}/cdn-cgi/access/certs`;
952
+ }
953
+ async start() {
954
+ const { privateKey, publicKey } = await generateKeyPair("RS256", { extractable: true });
955
+ this.privateKey = privateKey;
956
+ this.publicJwk = {
957
+ ...await exportJWK(publicKey),
958
+ kid: this.kid,
959
+ alg: "RS256",
960
+ use: "sig"
961
+ };
962
+ this.#server = createServer((req, res) => {
963
+ if (req.url?.startsWith("/dev/mint")) {
964
+ const url = new URL(req.url, this.origin);
965
+ const audience = url.searchParams.get("aud") ?? this.defaultAudience;
966
+ const email = url.searchParams.get("email");
967
+ const commonName = url.searchParams.get("common_name");
968
+ const requested = Number(url.searchParams.get("expires_in"));
969
+ const expiresIn = Number.isInteger(requested) && requested > 0 ? requested : void 0;
970
+ (commonName ? this.mintServiceToken({
971
+ audience,
972
+ commonName,
973
+ expiresIn
974
+ }) : this.mintUserToken({
975
+ audience,
976
+ email: email ?? "admin@acme.example",
977
+ expiresIn
978
+ })).then((token) => {
979
+ res.writeHead(200, { "content-type": "application/json" });
980
+ res.end(JSON.stringify({ token }));
981
+ });
982
+ return;
983
+ }
984
+ if (req.url === "/cdn-cgi/access/certs") {
985
+ res.writeHead(200, { "content-type": "application/json" });
986
+ res.end(JSON.stringify({ keys: [this.publicJwk] }));
987
+ return;
988
+ }
989
+ this.#dispatch(req, res);
990
+ });
991
+ await new Promise((resolve) => {
992
+ this.#server.listen(this.listenPort, "127.0.0.1", () => {
993
+ const address = this.#server.address();
994
+ if (address === null || typeof address === "string") throw new Error("no port");
995
+ this.#port = address.port;
996
+ resolve();
997
+ });
998
+ });
999
+ }
1000
+ async stop() {
1001
+ if (!this.#server) return;
1002
+ await new Promise((resolve) => this.#server.close(() => resolve()));
1003
+ this.#server = null;
1004
+ this.#port = 0;
1005
+ }
1006
+ registerClient(client) {
1007
+ this.#clients.set(client.clientId, {
1008
+ clientId: client.clientId,
1009
+ clientSecret: client.clientSecret,
1010
+ redirectUris: [...client.redirectUris],
1011
+ anyLoopbackRedirect: false
1012
+ });
1013
+ }
1014
+ client(clientId) {
1015
+ return this.#clients.get(clientId);
1016
+ }
1017
+ /** The OIDC `sub` for an email: derived, unless {@link setSubject} overrode it. */
1018
+ subjectFor(email) {
1019
+ const normalized = normalizeEmail(email);
1020
+ return this.#subjects.get(normalized) ?? defaultSubject(normalized);
1021
+ }
1022
+ /**
1023
+ * From now on, whoever signs in with this email gets this subject. Simulates
1024
+ * an address being recycled to a new person: same email, different account.
1025
+ */
1026
+ setSubject(email, subject) {
1027
+ this.#subjects.set(normalizeEmail(email), subject);
1028
+ }
1029
+ /** The fake GitHub account that signs in with this email. */
1030
+ gitHubUserFor(email) {
1031
+ const normalized = normalizeEmail(email);
1032
+ return this.#gitHubAccounts.get(normalized) ?? defaultGitHubAccount(normalized);
1033
+ }
1034
+ /**
1035
+ * From now on, whoever picks this email on the fake GitHub gets this account,
1036
+ * patched over the current one. A new `id` simulates a recycled address;
1037
+ * `emails` can add several, unverified ones included; `orgs` sets memberships.
1038
+ */
1039
+ setGitHubUser(email, patch) {
1040
+ const current = this.gitHubUserFor(email);
1041
+ this.#gitHubAccounts.set(normalizeEmail(email), {
1042
+ id: patch.id ?? current.id,
1043
+ login: patch.login ?? current.login,
1044
+ name: patch.name ?? current.name,
1045
+ emails: patch.emails ? gitHubEmails(patch.emails) : current.emails,
1046
+ orgs: patch.orgs ? [...patch.orgs] : current.orgs
1047
+ });
1048
+ }
1049
+ /** The email that signs in as a GitHub login, for GitHub's `login` hint. */
1050
+ emailForGitHubLogin(login) {
1051
+ const wanted = login.toLowerCase();
1052
+ for (const [email, account] of this.#gitHubAccounts) if (account.login.toLowerCase() === wanted) return email;
1053
+ return PERSONAS.find((p) => this.gitHubUserFor(p.email).login.toLowerCase() === wanted)?.email;
1054
+ }
1055
+ /** An OIDC ID token, as the token endpoint issues it. */
1056
+ async mintIdToken(opts) {
1057
+ const email = normalizeEmail(opts.email);
1058
+ return this.#sign({
1059
+ sub: this.subjectFor(email),
1060
+ auth_time: opts.authTime ?? Math.floor(Date.now() / 1e3),
1061
+ ...opts.nonce !== void 0 && { nonce: opts.nonce },
1062
+ email,
1063
+ email_verified: true,
1064
+ name: displayName(email)
1065
+ }, {
1066
+ audience: opts.clientId,
1067
+ expiresIn: opts.expiresIn ?? 600
1068
+ });
1069
+ }
1070
+ /** Mint a token shaped like an Access identity (human) token. */
1071
+ async mintUserToken(opts) {
1072
+ return this.#sign({
1073
+ email: opts.email ?? "admin@acme.example",
1074
+ sub: opts.sub ?? "0f9a1c2e-1111-2222-3333-444455556666",
1075
+ identity_nonce: "devnonce"
1076
+ }, opts);
1077
+ }
1078
+ /**
1079
+ * Mint a token shaped like an Access *service token*.
1080
+ *
1081
+ * Deliberately faithful to the real thing: no email claim at all, and an
1082
+ * empty sub. Code that reads `claims.email` to identify the caller produces
1083
+ * `undefined` here, which is how machine callers end up in the audit log
1084
+ * with no actor.
1085
+ */
1086
+ async mintServiceToken(opts) {
1087
+ return this.#sign({
1088
+ sub: "",
1089
+ common_name: opts.commonName ?? "e367826f93b8d71185e03fe518aff3b4.access"
1090
+ }, opts);
1091
+ }
1092
+ #dispatch(req, res) {
1093
+ const url = new URL(req.url ?? "/", this.origin);
1094
+ const matches = this.#routes.filter((route) => typeof route.path === "string" ? route.path === url.pathname : route.path.test(url.pathname));
1095
+ if (matches.length === 0) {
1096
+ res.writeHead(404).end();
1097
+ return;
1098
+ }
1099
+ const route = matches.find((r) => r.method === req.method);
1100
+ if (!route) {
1101
+ res.writeHead(405, { allow: matches.map((r) => r.method).join(", ") }).end();
1102
+ return;
1103
+ }
1104
+ route.handler(req, res, url).catch((error) => {
1105
+ console.error(error);
1106
+ if (!res.headersSent) res.writeHead(500);
1107
+ res.end();
1108
+ });
1109
+ }
1110
+ async #sign(claims, opts) {
1111
+ const now = Math.floor(Date.now() / 1e3);
1112
+ const expiresIn = opts.expiresIn ?? 900;
1113
+ const jwt = new SignJWT(claims).setProtectedHeader({
1114
+ alg: "RS256",
1115
+ kid: this.kid
1116
+ }).setIssuedAt(now).setIssuer(opts.issuer ?? this.issuer).setAudience(opts.audience).setExpirationTime(now + expiresIn);
1117
+ if (opts.notBefore !== void 0) jwt.setNotBefore(now + opts.notBefore);
1118
+ return jwt.sign(opts.key ?? this.privateKey);
1119
+ }
1120
+ };
1121
+ //#endregion
1122
+ export { defaultGitHubAccount as i, DevIdp as n, PERSONAS as r, DEFAULT_CLIENT as t };