@broberg/sso 0.13.0 → 0.14.2

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/dist/index.js CHANGED
@@ -1,669 +1,145 @@
1
- import { importJWK, decodeProtectedHeader, jwtVerify } from 'jose';
1
+ import { SsoError, ALLOWED_ALGS, JwksUnavailableError, createJwksCache } from './chunk-ZPRWYUFG.js';
2
+ export { AVATAR_TYPES, DEFAULT_SESSION_MAX_AGE, JwksError, JwksUnavailableError, JwksUnknownKeyError, MAX_AVATAR_BYTES, MAX_INVITATIONS, SsoAppApiError, SsoAvatarRejectedError, SsoConfigError, SsoError, SsoInsufficientScopeError, SsoReauthError, cookieHeader, createJwksCache, createSsoClient, loadSsoConfig, memoryTokenStore, readCookie, signSession, signValue, verifySession, verifyValue } from './chunk-ZPRWYUFG.js';
3
+ import { existsSync } from 'fs';
4
+ import { request } from 'http';
5
+ import { decodeProtectedHeader, jwtVerify } from 'jose';
2
6
 
3
- // src/config.ts
4
- var SsoConfigError = class extends Error {
7
+ var DEFAULT_ISSUER = "https://id.broberg.ai";
8
+ var FLY_SOCKET = "/.fly/api";
9
+ var NoWorkloadIdentityError = class extends Error {
5
10
  constructor(message) {
6
11
  super(message);
7
- this.name = "SsoConfigError";
12
+ this.name = "NoWorkloadIdentityError";
8
13
  }
9
14
  };
10
- function required(env, name, hint) {
11
- const raw = env[name];
12
- if (typeof raw !== "string" || raw.trim() === "") {
13
- throw new SsoConfigError(`${name} is not set (or is blank). ${hint}`);
14
- }
15
- return raw.trim();
16
- }
17
- var DEFAULT_SESSION_MAX_AGE = 60 * 60 * 24 * 7;
18
- function loadSsoConfig(env = process.env) {
19
- const rawIssuer = required(
20
- env,
21
- "BID_ISSUER",
22
- "It is Broberg ID's bare origin, e.g. https://id.broberg.ai"
23
- );
24
- let issuer;
25
- try {
26
- const url = new URL(rawIssuer);
27
- if (url.protocol !== "https:" && url.hostname !== "localhost") {
28
- throw new SsoConfigError(
29
- `BID_ISSUER must be https (got ${url.protocol}//). Only localhost may be http.`
30
- );
31
- }
32
- issuer = url.origin;
33
- } catch (err) {
34
- if (err instanceof SsoConfigError) throw err;
35
- throw new SsoConfigError(`BID_ISSUER is not a valid URL: ${rawIssuer}`);
36
- }
37
- const cookieSecret = required(
38
- env,
39
- "SSO_COOKIE_SECRET",
40
- "Generate one with `openssl rand -hex 32`. It signs this app's session cookie."
41
- );
42
- if (cookieSecret.length < 32) {
43
- throw new SsoConfigError(
44
- `SSO_COOKIE_SECRET is ${cookieSecret.length} characters; it must be at least 32. A short secret is a forgeable session, and a forged session is any user you like.`
45
- );
46
- }
47
- const rawMaxAge = env.SSO_SESSION_MAX_AGE?.trim();
48
- let sessionMaxAge = DEFAULT_SESSION_MAX_AGE;
49
- if (rawMaxAge) {
50
- const n = Number(rawMaxAge);
51
- if (!Number.isFinite(n) || n <= 0) {
52
- throw new SsoConfigError(
53
- `SSO_SESSION_MAX_AGE must be a positive number of seconds (got ${JSON.stringify(rawMaxAge)}).`
54
- );
55
- }
56
- sessionMaxAge = Math.floor(n);
57
- }
58
- return {
59
- issuer,
60
- clientId: required(env, "SSO_CLIENT_ID", "The id this app is registered under in Broberg ID."),
61
- redirectUri: required(
62
- env,
63
- "SSO_REDIRECT_URI",
64
- "Must match the registered redirect EXACTLY \u2014 one trailing slash is a different address."
65
- ),
66
- scopes: (env.SSO_SCOPES?.trim() || "openid profile email").split(/\s+/),
67
- cookieSecret,
68
- cookieName: env.SSO_COOKIE_NAME?.trim() || "bid_session",
69
- sessionMaxAge,
70
- postLogoutRedirectUri: env.SSO_POST_LOGOUT_REDIRECT_URI?.trim() || void 0,
71
- clientSecret: env.SSO_CLIENT_SECRET?.trim() || void 0
72
- };
73
- }
74
- var JwksError = class extends Error {
75
- constructor(message) {
15
+ var TicketExchangeError = class extends Error {
16
+ constructor(message, code, status) {
76
17
  super(message);
77
- this.name = "JwksError";
78
- }
79
- };
80
- var JwksUnavailableError = class extends JwksError {
81
- constructor(message) {
82
- super(message);
83
- this.name = "JwksUnavailableError";
18
+ this.code = code;
19
+ this.status = status;
20
+ this.name = "TicketExchangeError";
84
21
  }
22
+ code;
23
+ status;
85
24
  };
86
- var JwksUnknownKeyError = class extends JwksError {
25
+ var TicketUnavailableError = class extends Error {
87
26
  constructor(message) {
88
27
  super(message);
89
- this.name = "JwksUnknownKeyError";
28
+ this.name = "TicketUnavailableError";
90
29
  }
91
30
  };
92
- function createJwksCache(options) {
93
- const {
94
- jwksUri,
95
- minRefetchIntervalMs = 1e4,
96
- warmUp = false,
97
- fetchImpl = fetch,
98
- now = () => Date.now()
99
- } = options;
100
- let keys = [];
101
- let lastFetchAt = -Infinity;
102
- let fetchCount = 0;
103
- let inFlight = null;
104
- async function refresh() {
105
- if (inFlight) return inFlight;
106
- inFlight = (async () => {
107
- let res;
108
- try {
109
- res = await fetchImpl(jwksUri);
110
- } catch (cause) {
111
- throw new JwksUnavailableError(
112
- `${jwksUri} could not be reached: ${cause instanceof Error ? cause.message : String(cause)}`
113
- );
114
- }
115
- if (!res.ok) {
116
- throw new JwksUnavailableError(
117
- `${jwksUri} answered ${res.status} \u2014 cannot verify any token right now`
118
- );
119
- }
120
- let body;
121
- try {
122
- body = await res.json();
123
- } catch {
124
- throw new JwksUnavailableError(`${jwksUri} answered 200 with a body that is not JSON`);
125
- }
126
- if (!Array.isArray(body?.keys)) {
127
- throw new JwksUnavailableError(`${jwksUri} returned no "keys" array`);
31
+ function flyOidcOverSocket(aud) {
32
+ return new Promise((resolve, reject) => {
33
+ const body = JSON.stringify({ aud });
34
+ const req = request(
35
+ { socketPath: FLY_SOCKET, path: "/v1/tokens/oidc", method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) } },
36
+ (res) => {
37
+ let data = "";
38
+ res.setEncoding("utf8");
39
+ res.on("data", (c) => data += c);
40
+ res.on("end", () => {
41
+ if ((res.statusCode ?? 0) >= 200 && (res.statusCode ?? 0) < 300) resolve(data.trim());
42
+ else reject(new TicketUnavailableError(`Fly OIDC answered ${res.statusCode}`));
43
+ });
128
44
  }
129
- keys = body.keys;
130
- lastFetchAt = now();
131
- fetchCount++;
132
- })().finally(() => {
133
- inFlight = null;
134
- });
135
- return inFlight;
136
- }
137
- if (warmUp) {
138
- void refresh().catch(() => {
139
- });
140
- }
141
- return {
142
- get fetchCount() {
143
- return fetchCount;
144
- },
145
- async getKey(kid, alg) {
146
- let jwk = keys.find((k) => k.kid === kid);
147
- if (!jwk) {
148
- const sinceLast = now() - lastFetchAt;
149
- if (sinceLast < minRefetchIntervalMs) {
150
- throw new JwksUnavailableError(
151
- `kid ${kid} is not in the key set we hold, fetched ${sinceLast}ms ago (we do not ask the issuer again within ${minRefetchIntervalMs}ms). A key set this fresh that lacks the kid means the token was not signed by this issuer \u2014 reject it. Only a key rotation within the last ${minRefetchIntervalMs}ms could make that wrong.`
152
- );
153
- }
154
- await refresh();
155
- jwk = keys.find((k) => k.kid === kid);
156
- }
157
- if (!jwk) {
158
- throw new JwksUnknownKeyError(
159
- `Broberg ID does not publish a signing key with kid ${kid}. The token was not signed by this issuer.`
160
- );
161
- }
162
- return importJWK(jwk, alg);
163
- }
164
- };
45
+ );
46
+ req.on("error", (e) => reject(new TicketUnavailableError(`Fly OIDC socket: ${e.message}`)));
47
+ req.end(body);
48
+ });
165
49
  }
166
-
167
- // src/client.ts
168
- var SsoError = class extends Error {
169
- constructor(message) {
170
- super(message);
171
- this.name = "SsoError";
172
- }
173
- };
174
- var SsoReauthError = class extends SsoError {
175
- constructor(message, reason) {
176
- super(message);
177
- this.reason = reason;
178
- this.name = "SsoReauthError";
179
- }
180
- reason;
181
- };
182
- var SsoAppApiError = class extends SsoError {
183
- constructor(message, status, code) {
184
- super(message);
185
- this.status = status;
186
- this.code = code;
187
- this.name = "SsoAppApiError";
188
- }
189
- status;
190
- code;
191
- };
192
- var SsoInsufficientScopeError = class extends SsoAppApiError {
193
- constructor(message, scope) {
194
- super(message, 403, "insufficient_scope");
195
- this.scope = scope;
196
- this.name = "SsoInsufficientScopeError";
197
- }
198
- scope;
199
- };
200
- var SsoAvatarRejectedError = class extends SsoError {
201
- constructor(message, reason) {
202
- super(message);
203
- this.reason = reason;
204
- this.name = "SsoAvatarRejectedError";
50
+ function jwtExp(token) {
51
+ try {
52
+ const payload = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8"));
53
+ return typeof payload.exp === "number" ? payload.exp : null;
54
+ } catch {
55
+ return null;
205
56
  }
206
- reason;
207
- };
208
- var MAX_AVATAR_BYTES = 2 * 1024 * 1024;
209
- var AVATAR_TYPES = ["image/png", "image/jpeg", "image/webp"];
210
- function mediaType(contentType) {
211
- return (contentType ?? "").split(";")[0].trim().toLowerCase();
212
- }
213
- var b64url = (bytes) => {
214
- const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
215
- let s = "";
216
- for (const b of view) s += String.fromCharCode(b);
217
- return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
218
- };
219
- var randomToken = (bytes = 32) => b64url(crypto.getRandomValues(new Uint8Array(bytes)));
220
- async function challengeFor(verifier) {
221
- return b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
222
- }
223
- var ADDRESS_OWNERSHIP = /* @__PURE__ */ new Set(["verified", "unverified", "not_on_account"]);
224
- var INVITATION_OUTCOMES = /* @__PURE__ */ new Set([
225
- "invited",
226
- "already_invited",
227
- "existing",
228
- "invalid",
229
- "too_soon",
230
- "too_many_today",
231
- "send_failed"
232
- ]);
233
- var MIGRATION_STATES = /* @__PURE__ */ new Set(["ready", "invited", "expired", "not_invited"]);
234
- var BACKCHANNEL_EVENT = "http://schemas.openid.net/event/backchannel-logout";
235
- var MAX_INVITATIONS = 500;
236
- function excerptForLog(raw, clientSecret) {
237
- let text = raw.replace(/\s+/g, " ").trim();
238
- if (clientSecret) text = text.split(clientSecret).join("[redacted client_secret]");
239
- if (text === "") return "(empty body)";
240
- return text.length > 200 ? `${text.slice(0, 200)}\u2026` : text;
241
- }
242
- function invalidClientHint(error, weSentASecret) {
243
- if (error !== "invalid_client") return "";
244
- return weSentASecret ? " \u2014 we DID send a client_secret, so either it is wrong or this client is registered as PUBLIC (in which case unset SSO_CLIENT_SECRET)." : " \u2014 we sent NO client_secret, so this client is likely registered as CONFIDENTIAL (set SSO_CLIENT_SECRET to the value it was registered with).";
245
57
  }
246
- var ALLOWED_ALGS = [
247
- // FIRST, because it is what Broberg ID actually signs with. Measured on the
248
- // live issuer 2026-09-20:
249
- // /jwks kid=Iodh… kty=OKP alg=EdDSA crv=Ed25519
250
- // discovery id_token_signing_alg_values_supported: ["EdDSA"]
251
- //
252
- // 0.2.1 SHIPPED THIS LIST WITHOUT IT and rejected every real token for an
253
- // hour. The list was written from what an OIDC client usually allows rather
254
- // than from what our issuer uses — and the whole suite missed it because the
255
- // fake issuer in the tests signs RS256. A fake agrees with whoever wrote it.
256
- // There is now a test that mints EdDSA, the algorithm production uses.
257
- "EdDSA",
258
- "RS256",
259
- "RS384",
260
- "RS512",
261
- "PS256",
262
- "PS384",
263
- "PS512",
264
- "ES256",
265
- "ES384",
266
- "ES512"
267
- ];
268
- function createSsoClient(config, options = {}) {
58
+ function createTicketClient(options = {}) {
59
+ const issuer = (options.issuer ?? DEFAULT_ISSUER).replace(/\/+$/, "");
60
+ const renewBeforeSec = options.renewBeforeSec ?? 30;
61
+ const env = options.env ?? process.env;
269
62
  const fetchImpl = options.fetchImpl ?? fetch;
270
- const timeoutMs = options.timeoutMs ?? 1e4;
271
- async function appPost(path, bearer, payload, what) {
272
- const url = new URL(path, config.issuer).toString();
273
- const ctrl = new AbortController();
274
- let timer;
275
- const timedOut = new Promise((_, reject) => {
276
- timer = setTimeout(() => {
277
- ctrl.abort();
278
- reject(new SsoError(`${url} did not answer within ${timeoutMs} ms \u2014 ${what} is unknown.`));
279
- }, timeoutMs);
280
- });
281
- try {
282
- const res = await Promise.race([
283
- fetchImpl(url, {
284
- method: "POST",
285
- headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" },
286
- body: JSON.stringify(payload),
287
- signal: ctrl.signal
288
- }),
289
- timedOut
290
- ]);
291
- if (!res.ok) {
292
- const detail = await res.text().catch(() => "");
293
- const hint = detail.includes("invalid_app_key") ? " (invalid_app_key: this app's bidk_ key was refused)" : "";
294
- throw new SsoError(`${url} answered ${res.status}${hint} \u2014 ${what} is unknown.`);
295
- }
296
- return await Promise.race([res.json().catch(() => null), timedOut]);
297
- } catch (e) {
298
- if (e instanceof SsoError) throw e;
299
- throw new SsoError(`${url} could not be reached: ${e instanceof Error ? e.message : String(e)} \u2014 ${what} is unknown.`);
300
- } finally {
301
- clearTimeout(timer);
302
- }
303
- }
304
- async function appRequest(path, bearer, init, what) {
305
- const url = new URL(path, config.issuer).toString();
306
- const ctrl = new AbortController();
307
- let timer;
308
- const timedOut = new Promise((_, reject) => {
309
- timer = setTimeout(() => {
310
- reject(new SsoAppApiError(`${url} did not answer within ${timeoutMs} ms \u2014 ${what} is unknown.`, null, void 0));
311
- ctrl.abort();
312
- }, timeoutMs);
313
- });
314
- const headers = { authorization: `Bearer ${bearer}` };
315
- let body;
316
- if (init.json !== void 0) {
317
- headers["content-type"] = "application/json";
318
- body = JSON.stringify(init.json);
319
- } else if (init.bytes !== void 0) {
320
- headers["content-type"] = init.contentType ?? "application/octet-stream";
321
- body = init.bytes;
322
- }
323
- try {
324
- const res = await Promise.race([
325
- fetchImpl(url, { method: init.method, headers, ...body !== void 0 ? { body } : {}, signal: ctrl.signal }),
326
- timedOut
327
- ]);
328
- const raw = await Promise.race([res.text(), timedOut]);
329
- let parsed;
63
+ const now = options.now ?? (() => Date.now());
64
+ const flyOidc = options.flyOidc ?? flyOidcOverSocket;
65
+ const onFly = options.onFly ?? (() => !!env.FLY_APP_NAME && existsSync(FLY_SOCKET));
66
+ const cache = /* @__PURE__ */ new Map();
67
+ const inFlight = /* @__PURE__ */ new Map();
68
+ async function platformToken() {
69
+ if (onFly()) return flyOidc(issuer);
70
+ const url = env.ACTIONS_ID_TOKEN_REQUEST_URL;
71
+ const bearer = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
72
+ if (url && bearer) {
73
+ let res;
330
74
  try {
331
- parsed = raw.trim() === "" ? void 0 : JSON.parse(raw);
332
- } catch {
333
- parsed = void 0;
334
- }
335
- const fields = parsed && typeof parsed === "object" ? parsed : {};
336
- const code = typeof fields.error === "string" ? fields.error : void 0;
337
- if (!res.ok) {
338
- if (res.status === 403 && code === "insufficient_scope") {
339
- const scope = typeof fields.scope === "string" && fields.scope ? fields.scope : init.method === "GET" ? "profile" : "profile:write";
340
- throw new SsoInsufficientScopeError(
341
- `${url} answered 403 insufficient_scope \u2014 the user's token lacks scope "${scope}"; log in again with it requested.`,
342
- scope
343
- );
344
- }
345
- throw new SsoAppApiError(`${url} answered ${res.status}${code ? ` (${code})` : ""} \u2014 ${what} is unknown.`, res.status, code);
346
- }
347
- if (parsed === void 0) {
348
- throw new SsoAppApiError(`${url} answered ${res.status} with a body that is not JSON \u2014 ${what} is unknown.`, res.status, void 0);
75
+ res = await fetchImpl(`${url}&audience=${encodeURIComponent(issuer)}`, { headers: { authorization: `Bearer ${bearer}` } });
76
+ } catch (e) {
77
+ throw new TicketUnavailableError(`GitHub OIDC endpoint unreachable: ${e instanceof Error ? e.message : String(e)}`);
349
78
  }
350
- return parsed;
351
- } catch (e) {
352
- if (e instanceof SsoError) throw e;
353
- throw new SsoAppApiError(`${url} could not be reached (${e instanceof Error ? e.name : "error"}) \u2014 ${what} is unknown.`, null, void 0);
354
- } finally {
355
- clearTimeout(timer);
79
+ if (!res.ok) throw new TicketUnavailableError(`GitHub OIDC endpoint answered ${res.status}`);
80
+ const { value } = await res.json();
81
+ if (!value) throw new TicketUnavailableError("GitHub OIDC endpoint returned no token");
82
+ return value;
356
83
  }
84
+ throw new NoWorkloadIdentityError(
85
+ "No workload identity to exchange for a ticket: not on a Fly machine (FLY_APP_NAME + /.fly/api) and not in a GitHub Actions job (ACTIONS_ID_TOKEN_REQUEST_URL/_TOKEN \u2014 add `permissions: id-token: write`). A Mac session keeps using its session key."
86
+ );
357
87
  }
358
- function asProfile(body, path) {
359
- const b = body ?? {};
360
- if (typeof b.sub !== "string" || b.sub === "" || typeof b.account_url !== "string") {
361
- throw new SsoAppApiError(`${path} returned no "sub" or "account_url" \u2014 the profile is unknown.`, 200, void 0);
362
- }
363
- const opt = (v) => typeof v === "string" ? v : null;
364
- return { sub: b.sub, name: opt(b.name), picture: opt(b.picture), email: opt(b.email), account_url: b.account_url };
365
- }
366
- let discoveryPromise = null;
367
- let jwksCache = null;
368
- async function discovery() {
369
- discoveryPromise ??= (async () => {
370
- const url = `${config.issuer}/.well-known/openid-configuration`;
371
- const res = await fetchImpl(url);
372
- if (!res.ok) throw new SsoError(`${url} answered ${res.status}`);
373
- const doc = await res.json();
374
- const advertised = doc.id_token_signing_alg_values_supported;
375
- if (Array.isArray(advertised) && advertised.length > 0) {
376
- const usable = advertised.filter((a) => ALLOWED_ALGS.includes(a));
377
- if (usable.length === 0) {
378
- throw new SsoError(
379
- `${config.issuer} signs ID tokens with ${advertised.join(", ")}, and this client accepts none of those (it allows ${ALLOWED_ALGS.join(", ")}). Every token would be rejected. This is a mismatch between the package and the issuer \u2014 report it rather than working around it.`
380
- );
381
- }
382
- }
383
- if (doc.issuer !== config.issuer) {
384
- throw new SsoError(
385
- `BID_ISSUER is ${config.issuer} but ${url} says its issuer is ${doc.issuer}. These must match exactly \u2014 tokens are validated against the issuer string.`
386
- );
387
- }
388
- return doc;
389
- })().catch((err) => {
390
- discoveryPromise = null;
391
- throw err;
88
+ async function exchange(audience, scope) {
89
+ const subject = await platformToken();
90
+ const form = new URLSearchParams({
91
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
92
+ subject_token: subject,
93
+ subject_token_type: "urn:ietf:params:oauth:token-type:jwt",
94
+ audience
392
95
  });
393
- return discoveryPromise;
394
- }
395
- async function keys() {
396
- if (!jwksCache) {
397
- const { jwks_uri } = await discovery();
398
- jwksCache = createJwksCache({
399
- jwksUri: jwks_uri,
400
- fetchImpl,
401
- ...options.minRefetchIntervalMs !== void 0 ? { minRefetchIntervalMs: options.minRefetchIntervalMs } : {}
96
+ if (scope) form.set("scope", scope);
97
+ let res;
98
+ try {
99
+ res = await fetchImpl(`${issuer}/oauth2/token`, {
100
+ method: "POST",
101
+ headers: { "content-type": "application/x-www-form-urlencoded" },
102
+ body: form
402
103
  });
104
+ } catch (e) {
105
+ throw new TicketUnavailableError(`${issuer} unreachable: ${e instanceof Error ? e.message : String(e)}`);
403
106
  }
404
- return jwksCache;
405
- }
406
- async function verifyLogoutToken(token) {
407
- const cache = await keys();
408
- let header;
107
+ let body = {};
409
108
  try {
410
- header = decodeProtectedHeader(token);
109
+ body = await res.json();
411
110
  } catch {
412
- throw new SsoError("logout_token is not a JWS");
413
- }
414
- if (!header.kid) throw new SsoError("logout_token has no kid \u2014 cannot pick a signing key");
415
- let payload;
416
- try {
417
- ({ payload } = await jwtVerify(token, async () => cache.getKey(header.kid, header.alg ?? "RS256"), {
418
- issuer: config.issuer,
419
- audience: config.clientId,
420
- algorithms: ALLOWED_ALGS,
421
- typ: "logout+jwt",
422
- requiredClaims: ["iat", "exp", "jti"]
423
- }));
424
- } catch (e) {
425
- throw new SsoError(`logout_token rejected: ${e instanceof Error ? e.message : String(e)}`);
426
- }
427
- const events = payload.events;
428
- if (!events || typeof events !== "object" || !(BACKCHANNEL_EVENT in events)) {
429
- throw new SsoError("logout_token has no back-channel logout event");
430
- }
431
- if ("nonce" in payload) throw new SsoError("logout_token carries a nonce \u2014 that is an ID token, not a logout token");
432
- if ("sid" in payload) {
433
- throw new SsoError("logout_token carries sid \u2014 only sub-wide \xABLog ud overalt\xBB is accepted (D-376ffa)");
434
- }
435
- if (typeof payload.sub !== "string" || payload.sub === "") throw new SsoError("logout_token has no sub");
436
- return { sub: payload.sub, iat: payload.iat, jti: String(payload.jti), exp: payload.exp };
437
- }
438
- async function verifyIdToken(idToken, opts = {}) {
439
- const cache = await keys();
440
- const header = decodeProtectedHeader(idToken);
441
- if (!header.kid) throw new SsoError("ID token has no kid \u2014 cannot pick a signing key");
442
- const { payload } = await jwtVerify(
443
- idToken,
444
- async () => cache.getKey(header.kid, header.alg ?? "RS256"),
445
- { issuer: config.issuer, audience: config.clientId, algorithms: ALLOWED_ALGS }
446
- );
447
- if (opts.nonce !== void 0 && payload.nonce !== opts.nonce) {
448
- throw new SsoError(
449
- "ID token nonce does not match this login request \u2014 refusing a token minted for another sign-in."
450
- );
451
- }
452
- if (typeof payload.sub !== "string" || payload.sub === "") {
453
- throw new SsoError("ID token has no sub \u2014 there is no user to be");
454
111
  }
455
- return payload;
456
- }
457
- async function withUserInfo(claims, accessToken) {
458
- const doc = await discovery();
459
- if (!doc.userinfo_endpoint) return { claims, unverifiedClaims: [] };
460
- const res = await fetchImpl(doc.userinfo_endpoint, {
461
- headers: { authorization: `Bearer ${accessToken}` }
462
- });
463
- if (!res.ok) return { claims, unverifiedClaims: [] };
464
- const info = await res.json();
465
- if (info.sub !== claims.sub) {
466
- throw new SsoError(
467
- `userinfo describes ${String(info.sub)} but the ID token is for ${claims.sub} \u2014 refusing to merge another user's profile onto this session.`
468
- );
112
+ if (res.status >= 500) throw new TicketUnavailableError(`${issuer} answered ${res.status}`);
113
+ if (!res.ok || !body.access_token) {
114
+ const desc = body.error_description ?? "";
115
+ const code = desc.includes(":") ? desc.slice(0, desc.indexOf(":")).trim() : body.error ?? "exchange_refused";
116
+ throw new TicketExchangeError(`Broberg ID refused the ticket for ${audience}: ${desc || body.error || res.status}`, code, res.status);
469
117
  }
470
- const unverifiedClaims = Object.keys(info).filter((k) => k !== "sub" && info[k] !== void 0 && !(k in claims)).sort();
471
- return { claims: { ...info, ...claims, sub: claims.sub }, unverifiedClaims };
118
+ const nowSec = Math.floor(now() / 1e3);
119
+ const exp = jwtExp(body.access_token) ?? nowSec + (body.expires_in ?? 300);
120
+ return { token: body.access_token, exp };
472
121
  }
473
122
  return {
474
- discovery,
475
- get jwks() {
476
- if (!jwksCache) throw new SsoError("the key cache is created on first verification");
477
- return jwksCache;
478
- },
479
- verifyIdToken,
480
- async beginLogin(opts = {}) {
481
- const { authorization_endpoint } = await discovery();
482
- const codeVerifier = randomToken();
483
- const state = randomToken(16);
484
- const nonce = randomToken(16);
485
- const params = new URLSearchParams({
486
- response_type: "code",
487
- client_id: config.clientId,
488
- redirect_uri: config.redirectUri,
489
- scope: [.../* @__PURE__ */ new Set([...config.scopes, ...opts.scopes ?? []])].join(" "),
490
- state,
491
- nonce,
492
- code_challenge: await challengeFor(codeVerifier),
493
- code_challenge_method: "S256"
494
- });
495
- if (opts.prompt) params.set("prompt", opts.prompt);
496
- return { url: `${authorization_endpoint}?${params}`, state, codeVerifier, nonce };
497
- },
498
- async completeLogin({ params, state, codeVerifier, nonce }) {
499
- const error = params.get("error");
500
- if (error) {
501
- throw new SsoError(
502
- `Broberg ID refused this login: ${error}` + (params.get("error_description") ? ` \u2014 ${params.get("error_description")}` : "")
503
- );
504
- }
505
- const returned = params.get("state");
506
- if (!returned || returned !== state) {
507
- throw new SsoError(
508
- "state does not match the login this browser started \u2014 refusing the callback."
509
- );
510
- }
511
- const code = params.get("code");
512
- if (!code) throw new SsoError("callback carried neither an error nor a code");
513
- const { token_endpoint } = await discovery();
514
- const res = await fetchImpl(token_endpoint, {
515
- method: "POST",
516
- headers: { "content-type": "application/x-www-form-urlencoded" },
517
- body: new URLSearchParams({
518
- grant_type: "authorization_code",
519
- code,
520
- redirect_uri: config.redirectUri,
521
- client_id: config.clientId,
522
- // ALWAYS sent, secret or not. See SsoConfig.clientSecret: the two
523
- // prove different things, so a confidential client keeps PKCE.
524
- code_verifier: codeVerifier,
525
- ...config.clientSecret ? { client_secret: config.clientSecret } : {}
526
- })
527
- });
528
- const raw = await res.text();
529
- let body;
530
- try {
531
- body = raw.trim() === "" ? {} : JSON.parse(raw);
532
- } catch {
533
- throw new SsoError(
534
- `token exchange failed (${res.status}): the response body is not JSON${res.headers.get("content-type") ? ` (content-type: ${res.headers.get("content-type")})` : ""} \u2014 ${excerptForLog(raw, config.clientSecret)}`
535
- );
536
- }
537
- if (!res.ok || !body.id_token) {
538
- throw new SsoError(
539
- `token exchange failed (${res.status}): ${body.error ?? "no id_token in response"}` + (body.error_description ? ` \u2014 ${body.error_description}` : "") + invalidClientHint(body.error, config.clientSecret !== void 0)
540
- );
541
- }
542
- const claims = await verifyIdToken(body.id_token, { nonce });
543
- const merged = body.access_token ? await withUserInfo(claims, body.access_token) : { claims, unverifiedClaims: [] };
544
- return {
545
- claims: merged.claims,
546
- unverifiedClaims: merged.unverifiedClaims,
547
- idToken: body.id_token,
548
- ...body.access_token ? { accessToken: body.access_token } : {},
549
- ...body.refresh_token ? { refreshToken: body.refresh_token } : {},
550
- ...typeof body.expires_in === "number" ? { expiresIn: body.expires_in } : {}
551
- };
552
- },
553
- async refreshTokens(refreshToken) {
554
- const { token_endpoint } = await discovery();
555
- const res = await fetchImpl(token_endpoint, {
556
- method: "POST",
557
- headers: { "content-type": "application/x-www-form-urlencoded" },
558
- body: new URLSearchParams({
559
- grant_type: "refresh_token",
560
- refresh_token: refreshToken,
561
- client_id: config.clientId,
562
- ...config.clientSecret ? { client_secret: config.clientSecret } : {}
563
- })
564
- });
565
- const raw = await res.text();
566
- let body;
567
- try {
568
- body = raw.trim() === "" ? {} : JSON.parse(raw);
569
- } catch {
570
- throw new SsoError(`token refresh failed (${res.status}): the response body is not JSON`);
571
- }
572
- if (!res.ok || typeof body.access_token !== "string" || body.access_token === "") {
573
- throw new SsoError(`token refresh failed (${res.status}): ${body.error ?? "no access_token in response"}`);
574
- }
575
- return {
576
- accessToken: body.access_token,
577
- ...typeof body.refresh_token === "string" && body.refresh_token ? { refreshToken: body.refresh_token } : {},
578
- ...typeof body.expires_in === "number" ? { expiresIn: body.expires_in } : {}
579
- };
580
- },
581
- async logoutUrl(opts = {}) {
582
- const doc = await discovery();
583
- if (!doc.end_session_endpoint) {
584
- throw new SsoError(
585
- `${config.issuer} does not advertise end_session_endpoint \u2014 central logout is unavailable.`
586
- );
587
- }
588
- const params = new URLSearchParams();
589
- if (opts.idTokenHint) params.set("id_token_hint", opts.idTokenHint);
590
- const post = opts.postLogoutRedirectUri ?? config.postLogoutRedirectUri;
591
- if (post) params.set("post_logout_redirect_uri", post);
592
- params.set("client_id", config.clientId);
593
- return `${doc.end_session_endpoint}?${params}`;
594
- },
595
- async addressOwnership(accessToken, address) {
596
- const body = await appPost(
597
- "/api/app/address-ownership",
598
- accessToken,
599
- { address },
600
- 'address ownership (not "unverified")'
601
- );
602
- const status = body?.status;
603
- if (typeof status !== "string" || !ADDRESS_OWNERSHIP.has(status)) {
604
- throw new SsoError(`address-ownership returned status ${JSON.stringify(status)} \u2014 expected verified, unverified or not_on_account.`);
605
- }
606
- return status;
607
- },
608
- verifyLogoutToken,
609
- async getProfile(accessToken) {
610
- const path = "/api/app/profile";
611
- return asProfile(await appRequest(path, accessToken, { method: "GET" }, "the profile"), path);
612
- },
613
- async updateProfile(accessToken, name) {
614
- const path = "/api/app/profile";
615
- return asProfile(await appRequest(path, accessToken, { method: "POST", json: { name } }, "the new name"), path);
616
- },
617
- async uploadAvatar(accessToken, bytes, contentType) {
618
- const type = mediaType(contentType);
619
- if (!AVATAR_TYPES.includes(type)) {
620
- throw new SsoAvatarRejectedError(
621
- `uploadAvatar: "${type}" is not accepted \u2014 BID takes ${AVATAR_TYPES.join(", ")}.`,
622
- "unsupported_type"
623
- );
624
- }
625
- if (bytes.byteLength > MAX_AVATAR_BYTES) {
626
- throw new SsoAvatarRejectedError(
627
- `uploadAvatar: ${bytes.byteLength} bytes \u2014 BID takes at most ${MAX_AVATAR_BYTES}.`,
628
- "too_large"
629
- );
630
- }
631
- const path = "/api/app/profile/avatar";
632
- return asProfile(await appRequest(path, accessToken, { method: "POST", bytes, contentType: type }, "the new picture"), path);
633
- },
634
- async removeAvatar(accessToken) {
635
- const path = "/api/app/profile/avatar/remove";
636
- return asProfile(await appRequest(path, accessToken, { method: "POST" }, "the removed picture"), path);
637
- },
638
- async inviteUsers(appKey, input) {
639
- if (input.users.length > MAX_INVITATIONS) {
640
- throw new SsoError(`inviteUsers: ${input.users.length} users, BID accepts at most ${MAX_INVITATIONS} per call.`);
641
- }
642
- const body = await appPost("/api/app/invitations", appKey, input, "the invitation outcome");
643
- if (!Array.isArray(body?.results)) {
644
- throw new SsoError(`invitations returned no "results" array \u2014 the invitation outcome is unknown.`);
645
- }
646
- for (const r of body.results) {
647
- if (typeof r?.outcome !== "string" || !INVITATION_OUTCOMES.has(r.outcome)) {
648
- throw new SsoError(`invitations returned outcome ${JSON.stringify(r?.outcome)} for ${String(r?.email)} \u2014 not one this client knows.`);
649
- }
650
- }
651
- return body.results;
652
- },
653
- async migrationStatus(appKey, emails) {
654
- const body = await appPost("/api/app/migration-status", appKey, { emails }, "the migration state");
655
- if (!Array.isArray(body?.users) || typeof body.complete !== "boolean") {
656
- throw new SsoError(`migration-status returned no "users" array or no "complete" flag \u2014 the migration state is unknown.`);
657
- }
658
- for (const u of body.users) {
659
- if (typeof u?.state !== "string" || !MIGRATION_STATES.has(u.state)) {
660
- throw new SsoError(`migration-status returned state ${JSON.stringify(u?.state)} for ${String(u?.email)} \u2014 never read as "ready".`);
661
- }
662
- }
663
- return body;
123
+ async get({ audience, scope }) {
124
+ const key = `${audience} ${scope ?? ""}`;
125
+ const hit = cache.get(key);
126
+ if (hit && hit.exp - renewBeforeSec > now() / 1e3) return hit.token;
127
+ const pending = inFlight.get(key);
128
+ if (pending) return pending;
129
+ const p = exchange(audience, scope).then((t) => {
130
+ cache.set(key, t);
131
+ return t.token;
132
+ }).finally(() => inFlight.delete(key));
133
+ inFlight.set(key, p);
134
+ return p;
664
135
  }
665
136
  };
666
137
  }
138
+ var shared = null;
139
+ function fetchTicket(opts) {
140
+ shared ??= createTicketClient();
141
+ return shared.get(opts);
142
+ }
667
143
  var PRINCIPAL_TYPES = ["human", "service", "agent"];
668
144
  function createTicketVerifier(options) {
669
145
  const {
@@ -743,8 +219,8 @@ function createTicketVerifier(options) {
743
219
  }
744
220
  if (typeof payload.sub !== "string" || payload.sub === "") throw new SsoError("ticket has no sub");
745
221
  const scopes = typeof payload.scope === "string" ? payload.scope.split(" ").filter(Boolean) : [];
746
- const required2 = opts.scope === void 0 ? [] : Array.isArray(opts.scope) ? opts.scope : [opts.scope];
747
- const missing = required2.filter((s) => !scopes.includes(s));
222
+ const required = opts.scope === void 0 ? [] : Array.isArray(opts.scope) ? opts.scope : [opts.scope];
223
+ const missing = required.filter((s) => !scopes.includes(s));
748
224
  if (missing.length) throw new SsoError(`ticket lacks scope ${missing.join(", ")}`);
749
225
  const actRaw = payload.act;
750
226
  const act = actRaw && typeof actRaw.sub === "string" && actRaw.sub ? { sub: actRaw.sub } : null;
@@ -762,125 +238,6 @@ function createTicketVerifier(options) {
762
238
  };
763
239
  }
764
240
 
765
- // src/session.ts
766
- var enc = new TextEncoder();
767
- var b64url2 = (bytes) => {
768
- let s = "";
769
- for (const b of bytes) s += String.fromCharCode(b);
770
- return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
771
- };
772
- var fromB64url = (s) => {
773
- const pad = s.replace(/-/g, "+").replace(/_/g, "/");
774
- const bin = atob(pad + "=".repeat((4 - pad.length % 4) % 4));
775
- return Uint8Array.from(bin, (c) => c.charCodeAt(0));
776
- };
777
- async function hmacKey(secret) {
778
- return crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
779
- "sign",
780
- "verify"
781
- ]);
782
- }
783
- async function signValue(value, secret, options = {}) {
784
- const payload = b64url2(enc.encode(value));
785
- const body = options.maxAgeSeconds === void 0 ? payload : `t${Math.floor((options.now ?? Date.now)() / 1e3)}~${payload}`;
786
- const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await hmacKey(secret), enc.encode(body)));
787
- return `${body}.${b64url2(sig)}`;
788
- }
789
- var STAMPED = /^t(\d+)~(.*)$/s;
790
- async function verifyValue(token, secret, options = {}) {
791
- if (!token) return null;
792
- const dot = token.lastIndexOf(".");
793
- if (dot <= 0) return null;
794
- const body = token.slice(0, dot);
795
- try {
796
- const ok = await crypto.subtle.verify(
797
- "HMAC",
798
- await hmacKey(secret),
799
- fromB64url(token.slice(dot + 1)),
800
- enc.encode(body)
801
- );
802
- if (!ok) return null;
803
- const stamped = STAMPED.exec(body);
804
- if (options.maxAgeSeconds !== void 0) {
805
- if (!stamped) return null;
806
- const issuedAt = Number(stamped[1]);
807
- if ((options.now ?? Date.now)() / 1e3 - issuedAt > options.maxAgeSeconds) return null;
808
- }
809
- return new TextDecoder().decode(fromB64url(stamped?.[2] ?? body));
810
- } catch {
811
- return null;
812
- }
813
- }
814
- async function signSession(payload, secret) {
815
- return signValue(JSON.stringify(payload), secret);
816
- }
817
- async function verifySession(token, secret, now = Date.now) {
818
- const body = await verifyValue(token, secret);
819
- if (body === null) return null;
820
- try {
821
- const payload = JSON.parse(body);
822
- if (typeof payload.sub !== "string" || payload.sub === "") return null;
823
- if (typeof payload.exp !== "number" || payload.exp * 1e3 <= now()) return null;
824
- return payload;
825
- } catch {
826
- return null;
827
- }
828
- }
829
- function cookieHeader(name, value, opts) {
830
- const parts = [
831
- `${name}=${value}`,
832
- `Path=${opts.path ?? "/"}`,
833
- `Max-Age=${opts.maxAge}`,
834
- "HttpOnly",
835
- // Lax, NOT Strict, and this is load-bearing: the callback from Broberg ID
836
- // is a top-level GET navigation from another site. Strict withholds the
837
- // cookie on exactly that navigation, so the login transaction cookie would
838
- // be missing when it is needed and every sign-in would fail with "state
839
- // does not match" — a message that sends you looking in the wrong place.
840
- `SameSite=${opts.sameSite ?? "Lax"}`
841
- ];
842
- if (opts.secure) parts.push("Secure");
843
- return parts.join("; ");
844
- }
845
- function readCookie(header, name) {
846
- if (!header) return void 0;
847
- for (const part of header.split(";")) {
848
- const eq = part.indexOf("=");
849
- if (eq === -1) continue;
850
- if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
851
- }
852
- return void 0;
853
- }
854
-
855
- // src/tokens.ts
856
- var warned = false;
857
- function memoryTokenStore(options = {}) {
858
- if (!options.quiet && !warned) {
859
- warned = true;
860
- console.warn(
861
- "@broberg/sso: memoryTokenStore() keeps tokens in this process only \u2014 they are lost on restart and not shared between instances. Give ssoRoutes a TokenStore backed by your database in production."
862
- );
863
- }
864
- const rows = /* @__PURE__ */ new Map();
865
- return {
866
- get size() {
867
- return rows.size;
868
- },
869
- async get(sid) {
870
- return rows.get(sid);
871
- },
872
- async set(sid, tokens) {
873
- rows.set(sid, { ...tokens });
874
- },
875
- async delete(sid) {
876
- rows.delete(sid);
877
- },
878
- async deleteSub(sub) {
879
- for (const [sid, t] of rows) if (t.sub === sub) rows.delete(sid);
880
- }
881
- };
882
- }
883
-
884
- export { AVATAR_TYPES, DEFAULT_SESSION_MAX_AGE, JwksError, JwksUnavailableError, JwksUnknownKeyError, MAX_AVATAR_BYTES, MAX_INVITATIONS, SsoAppApiError, SsoAvatarRejectedError, SsoConfigError, SsoError, SsoInsufficientScopeError, SsoReauthError, cookieHeader, createJwksCache, createSsoClient, createTicketVerifier, loadSsoConfig, memoryTokenStore, readCookie, signSession, signValue, verifySession, verifyValue };
241
+ export { DEFAULT_ISSUER, NoWorkloadIdentityError, TicketExchangeError, TicketUnavailableError, createTicketClient, createTicketVerifier, fetchTicket };
885
242
  //# sourceMappingURL=index.js.map
886
243
  //# sourceMappingURL=index.js.map