@jeffjassky/oauth-host 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,6 +3,7 @@
3
3
  var mongoose = require('mongoose');
4
4
  var express2 = require('express');
5
5
  var crypto = require('crypto');
6
+ var jose = require('jose');
6
7
 
7
8
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
9
 
@@ -42,6 +43,18 @@ function clientSchema() {
42
43
  metadataUrl: String,
43
44
  metadataFetchedAt: Date,
44
45
  metadataEtag: String,
46
+ // The usable (intersected) token endpoint auth method set for a CIMD
47
+ // client — absent on a manual registration, whose behavior derives from
48
+ // `type` exactly as before. A row with no value here supports no
49
+ // assertion-based method; see `authenticateClient`'s fallback rule.
50
+ tokenEndpointAuthMethods: [String],
51
+ // Exactly one of these two is set when `private_key_jwt` is in
52
+ // `tokenEndpointAuthMethods` — `validateMetadataDocument` refuses a
53
+ // document declaring both. Neither is ever required at the schema
54
+ // level: a manual client, or a CIMD client that only offers `none`,
55
+ // legitimately has neither.
56
+ jwksUri: String,
57
+ jwks: mongoose__default.default.Schema.Types.Mixed,
45
58
  trusted: { type: Boolean, default: false },
46
59
  // An array, not a string: rotation needs two live secrets at once or it
47
60
  // cannot be deployed without downtime.
@@ -385,7 +398,10 @@ function resolveCimd(input, scopeIndex) {
385
398
  fetchTimeoutMs: 5e3,
386
399
  maxBytes: 65536,
387
400
  allowedScopes: [],
388
- failures: /* @__PURE__ */ new Map()
401
+ failures: /* @__PURE__ */ new Map(),
402
+ jwksCache: /* @__PURE__ */ new Map(),
403
+ jwksForceRefetchAt: /* @__PURE__ */ new Map(),
404
+ assertionReplay: /* @__PURE__ */ new Map()
389
405
  };
390
406
  if (!input || !input.enabled) return off;
391
407
  if (!Array.isArray(input.allowedHosts) || input.allowedHosts.length === 0) {
@@ -418,7 +434,10 @@ function resolveCimd(input, scopeIndex) {
418
434
  fetchTimeoutMs: positive(input.fetchTimeoutMs, "fetchTimeoutMs", 5e3),
419
435
  maxBytes: positive(input.maxBytes, "maxBytes", 65536),
420
436
  allowedScopes: [...allowedScopes],
421
- failures: /* @__PURE__ */ new Map()
437
+ failures: /* @__PURE__ */ new Map(),
438
+ jwksCache: /* @__PURE__ */ new Map(),
439
+ jwksForceRefetchAt: /* @__PURE__ */ new Map(),
440
+ assertionReplay: /* @__PURE__ */ new Map()
422
441
  };
423
442
  }
424
443
  function resolveConfig(config) {
@@ -666,15 +685,19 @@ function authorizationServerMetadata(ctx, mountPath) {
666
685
  // S256 only. `plain` is not implemented anywhere in this package, so
667
686
  // advertising it would be a lie a client would discover at redemption.
668
687
  code_challenge_methods_supported: ["S256"],
669
- // `none` is advertised only when CIMD is on. Listing it unconditionally
670
- // would tell every client that secretless authentication is available here,
671
- // and the only clients that can use it are the ones this server would then
672
- // refuse to register.
688
+ // `none` and `private_key_jwt` are advertised only when CIMD is on.
689
+ // Listing either unconditionally would tell every client that secretless
690
+ // authentication is available here, and the only clients that can use it
691
+ // are the ones this server would then refuse to register.
673
692
  token_endpoint_auth_methods_supported: [
674
693
  "client_secret_basic",
675
694
  "client_secret_post",
676
- ...ctx.cimd.enabled ? ["none"] : []
695
+ ...ctx.cimd.enabled ? ["none", "private_key_jwt"] : []
677
696
  ],
697
+ // RFC 7523 §2.2 — the only two algorithms `authenticateClient` accepts
698
+ // for a `client_assertion` signature. Same gate as the line above: it
699
+ // names a capability that only exists for a CIMD client.
700
+ ...ctx.cimd.enabled ? { token_endpoint_auth_signing_alg_values_supported: ["RS256", "ES256"] } : {},
678
701
  // What tells Claude and ChatGPT to skip registration entirely and send
679
702
  // their metadata document URL as `client_id`.
680
703
  ...ctx.cimd.enabled ? { client_id_metadata_document_supported: true } : {},
@@ -1277,135 +1300,537 @@ function createKeyManager(ctx) {
1277
1300
  };
1278
1301
  }
1279
1302
 
1280
- // src/server/services/admin.ts
1281
- var MAX_LIST = 200;
1282
- var DEFAULT_LIST = 50;
1283
- function clampLimit(requested) {
1284
- const n = typeof requested === "number" && Number.isFinite(requested) ? Math.floor(requested) : DEFAULT_LIST;
1285
- if (n < 1) return 1;
1286
- return Math.min(n, MAX_LIST);
1303
+ // src/server/services/cimd.ts
1304
+ var NEGATIVE_TTL_MS = 6e4;
1305
+ var MAX_REMEMBERED_FAILURES = 1e3;
1306
+ function refuse(description) {
1307
+ return new UnredirectableError("invalid_client", description);
1287
1308
  }
1288
- function clampSkip(requested) {
1289
- const n = typeof requested === "number" && Number.isFinite(requested) ? Math.floor(requested) : 0;
1290
- return n > 0 ? n : 0;
1309
+ function isMetadataUrl(clientId) {
1310
+ return /^https:\/\//i.test(clientId);
1291
1311
  }
1292
- function notFound(clientId) {
1293
- return new Error(`oauth-host: no client registered with clientId '${clientId}'`);
1312
+ function hostAllowed(rules, url) {
1313
+ const hostname = url.hostname.toLowerCase();
1314
+ return rules.some((rule) => {
1315
+ if (url.port !== rule.port) return false;
1316
+ if (hostname === rule.host) return true;
1317
+ return rule.subdomains && hostname.endsWith(`.${rule.host}`);
1318
+ });
1294
1319
  }
1295
- function toPublicClient(doc) {
1320
+ function assertFetchableUrl(ctx, clientId) {
1321
+ let url;
1322
+ try {
1323
+ url = new URL(clientId);
1324
+ } catch {
1325
+ throw refuse(`client_id is not a valid URL: '${clientId}'`);
1326
+ }
1327
+ if (url.protocol !== "https:") {
1328
+ throw refuse(`client_id metadata must be served over https (got '${url.protocol}')`);
1329
+ }
1330
+ if (url.username || url.password) {
1331
+ throw refuse("client_id must not contain URL credentials");
1332
+ }
1333
+ if (url.hash) {
1334
+ throw refuse("client_id must not contain a fragment");
1335
+ }
1336
+ if (!hostAllowed(ctx.cimd.allowedHosts, url)) {
1337
+ throw refuse(`client_id host '${url.host}' is not in clientIdMetadata.allowedHosts`);
1338
+ }
1339
+ return url;
1340
+ }
1341
+ var JSON_CONTENT_TYPE = /^application\/(?:[\w.+-]+\+)?json\s*(?:;|$)/i;
1342
+ async function readCapped(res, maxBytes, docSubject) {
1343
+ const body = res.body;
1344
+ if (!body) throw refuse(`${docSubject} was empty`);
1345
+ const reader = body.getReader();
1346
+ const chunks = [];
1347
+ let total = 0;
1348
+ for (; ; ) {
1349
+ const { done, value } = await reader.read();
1350
+ if (done) break;
1351
+ if (!value) continue;
1352
+ total += value.byteLength;
1353
+ if (total > maxBytes) {
1354
+ void reader.cancel();
1355
+ throw refuse(`${docSubject} exceeds ${maxBytes} bytes`);
1356
+ }
1357
+ chunks.push(Buffer.from(value));
1358
+ }
1359
+ return Buffer.concat(chunks).toString("utf8");
1360
+ }
1361
+ async function hardenedFetch(ctx, url, opts) {
1362
+ const { subject, redirectAdvice, etag } = opts;
1363
+ const docSubject = `${subject} document`;
1364
+ let res;
1365
+ try {
1366
+ res = await fetch(url.toString(), {
1367
+ method: "GET",
1368
+ // The single most important line in this file. A 3xx is a failure below,
1369
+ // not a hop: following redirects would let an allowlisted host forward us
1370
+ // to any address it likes, allowlist intact.
1371
+ redirect: "manual",
1372
+ headers: {
1373
+ accept: "application/json",
1374
+ ...etag ? { "if-none-match": etag } : {}
1375
+ },
1376
+ signal: AbortSignal.timeout(ctx.cimd.fetchTimeoutMs)
1377
+ });
1378
+ } catch (err) {
1379
+ const name = err?.name;
1380
+ if (name === "TimeoutError" || name === "AbortError") {
1381
+ throw refuse(`${subject} fetch timed out after ${ctx.cimd.fetchTimeoutMs}ms`);
1382
+ }
1383
+ throw refuse(`${subject} could not be fetched: ${err?.message ?? "network error"}`);
1384
+ }
1385
+ if (res.status === 304) return { document: null };
1386
+ if (res.status >= 300 && res.status < 400) {
1387
+ throw refuse(`${subject} returned a ${res.status} redirect, which is not followed \u2014 ${redirectAdvice}`);
1388
+ }
1389
+ if (res.status !== 200) {
1390
+ throw refuse(`${subject} returned HTTP ${res.status}`);
1391
+ }
1392
+ const contentType = res.headers.get("content-type") ?? "";
1393
+ if (!JSON_CONTENT_TYPE.test(contentType)) {
1394
+ throw refuse(`${subject} must be JSON (got content-type '${contentType || "none"}')`);
1395
+ }
1396
+ const text = await readCapped(res, ctx.cimd.maxBytes, docSubject);
1397
+ let parsed;
1398
+ try {
1399
+ parsed = JSON.parse(text);
1400
+ } catch {
1401
+ throw refuse(`${docSubject} is not valid JSON`);
1402
+ }
1403
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1404
+ throw refuse(`${docSubject} must be a JSON object`);
1405
+ }
1296
1406
  return {
1297
- clientId: doc.clientId,
1298
- name: doc.name,
1299
- type: doc.type,
1300
- // Defaulted rather than read straight through: rows written before the
1301
- // field existed have no value, and `undefined` here would read as "unknown
1302
- // provenance" on a client that plainly was registered by hand.
1303
- registration: doc.registration ?? "manual",
1304
- ...doc.metadataUrl ? { metadataUrl: doc.metadataUrl } : {},
1305
- trusted: Boolean(doc.trusted),
1306
- redirectUris: [...doc.redirectUris ?? []],
1307
- allowedScopes: [...doc.allowedScopes ?? []],
1308
- allowedResources: [...doc.allowedResources ?? []],
1309
- branding: { ...doc.branding ?? {} },
1310
- status: doc.status,
1311
- createdAt: doc.createdAt
1407
+ document: parsed,
1408
+ ...res.headers.get("etag") ? { etag: res.headers.get("etag") } : {}
1312
1409
  };
1313
1410
  }
1314
- function assertRedirectUri(value) {
1315
- if (typeof value !== "string" || !value) {
1316
- throw new TypeError(`oauth-host: every redirectUri must be a string (got ${JSON.stringify(value)})`);
1411
+ async function fetchMetadata(ctx, url, etag) {
1412
+ return hardenedFetch(ctx, url, {
1413
+ subject: "client_id metadata",
1414
+ redirectAdvice: "serve the document at the client_id URL itself",
1415
+ etag
1416
+ });
1417
+ }
1418
+ async function fetchJwks(ctx, jwksUri) {
1419
+ const url = new URL(jwksUri);
1420
+ const { document } = await hardenedFetch(ctx, url, {
1421
+ subject: "jwks_uri",
1422
+ redirectAdvice: "serve the JWK Set at the jwks_uri URL itself"
1423
+ });
1424
+ if (!document) throw refuse("jwks_uri fetch returned no document");
1425
+ return document;
1426
+ }
1427
+ var SERVER_CIMD_AUTH_METHODS = ["none", "private_key_jwt"];
1428
+ function assertJwksUri(ctx, value) {
1429
+ if (typeof value !== "string" || !value.trim()) {
1430
+ throw refuse("client_id metadata field 'jwks_uri' must be a non-empty string");
1317
1431
  }
1318
1432
  let url;
1319
1433
  try {
1320
1434
  url = new URL(value);
1321
1435
  } catch {
1322
- throw new TypeError(`oauth-host: redirectUri must be an absolute URI: '${value}'`);
1436
+ throw refuse(`client_id metadata field 'jwks_uri' is not a valid URL: '${value}'`);
1323
1437
  }
1324
- const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
1325
- if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
1326
- throw new TypeError(
1327
- `oauth-host: redirectUri must be https (http is allowed only on localhost/127.0.0.1): '${value}'`
1328
- );
1438
+ if (url.protocol !== "https:") {
1439
+ throw refuse(`client_id metadata field 'jwks_uri' must be served over https (got '${url.protocol}')`);
1440
+ }
1441
+ if (url.username || url.password) {
1442
+ throw refuse("client_id metadata field 'jwks_uri' must not contain URL credentials");
1329
1443
  }
1330
1444
  if (url.hash) {
1331
- throw new TypeError(`oauth-host: redirectUri must not contain a fragment: '${value}'`);
1445
+ throw refuse("client_id metadata field 'jwks_uri' must not contain a fragment");
1332
1446
  }
1333
- return value;
1334
- }
1335
- function assertRedirectUris(input) {
1336
- if (!Array.isArray(input) || input.length === 0) {
1337
- throw new TypeError("oauth-host: a client needs at least one redirectUri");
1447
+ if (!hostAllowed(ctx.cimd.allowedHosts, url)) {
1448
+ throw refuse(`client_id metadata field 'jwks_uri' host '${url.host}' is not in clientIdMetadata.allowedHosts`);
1338
1449
  }
1339
- return input.map(assertRedirectUri);
1450
+ return url.href;
1340
1451
  }
1341
- function assertScopes(ctx, input) {
1342
- if (!Array.isArray(input) || input.length === 0) {
1343
- throw new TypeError("oauth-host: a client needs at least one entry in allowedScopes");
1452
+ function assertInlineJwks(value) {
1453
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1454
+ throw refuse("client_id metadata field 'jwks' must be a JSON object");
1344
1455
  }
1345
- for (const id of input) {
1346
- if (typeof id !== "string" || !ctx.scopeIndex.has(id)) {
1347
- throw new TypeError(
1348
- `oauth-host: allowedScopes contains '${String(id)}', which is not in the configured scope catalog`
1349
- );
1456
+ const keys = value.keys;
1457
+ if (!Array.isArray(keys) || keys.length === 0) {
1458
+ throw refuse("client_id metadata field 'jwks' must contain a non-empty 'keys' array");
1459
+ }
1460
+ for (const key of keys) {
1461
+ if (!key || typeof key !== "object" || Array.isArray(key)) {
1462
+ throw refuse("client_id metadata field 'jwks' contains a non-object entry in 'keys'");
1350
1463
  }
1351
1464
  }
1352
- return [...input];
1465
+ return value;
1353
1466
  }
1354
- function assertResources(ctx, input) {
1355
- const declared = new Set(ctx.resources.map((r) => r.id));
1356
- if (input === void 0) return ctx.resources.map((r) => r.id);
1357
- if (!Array.isArray(input) || input.length === 0) {
1358
- throw new TypeError("oauth-host: allowedResources, when given, must list at least one resource");
1359
- }
1360
- for (const id of input) {
1361
- if (typeof id !== "string" || !declared.has(id)) {
1362
- throw new TypeError(
1363
- `oauth-host: allowedResources contains '${String(id)}', which is not a configured resource`
1467
+ function offeredAuthMethods(doc) {
1468
+ const plural = doc.token_endpoint_auth_methods_supported;
1469
+ if (plural !== void 0) {
1470
+ if (!Array.isArray(plural) || plural.length === 0 || !plural.every((entry) => typeof entry === "string" && entry.length > 0)) {
1471
+ throw refuse(
1472
+ "client_id metadata field 'token_endpoint_auth_methods_supported' must be a non-empty array of strings"
1364
1473
  );
1365
1474
  }
1475
+ return [...new Set(plural)];
1366
1476
  }
1367
- return [...input];
1368
- }
1369
- function assertClientType(value) {
1370
- if (value === void 0) return "confidential";
1371
- if (value !== "confidential" && value !== "public") {
1372
- throw new TypeError(
1373
- `oauth-host: client type must be 'confidential' or 'public' (got ${JSON.stringify(value)})`
1374
- );
1477
+ const singular = doc.token_endpoint_auth_method;
1478
+ if (singular !== void 0) {
1479
+ if (typeof singular !== "string" || !singular) {
1480
+ throw refuse("client_id metadata field 'token_endpoint_auth_method' must be a string");
1481
+ }
1482
+ return [singular];
1375
1483
  }
1376
- return value;
1484
+ return ["none"];
1377
1485
  }
1378
- function assertName(value) {
1486
+ function requireString(doc, field) {
1487
+ const value = doc[field];
1379
1488
  if (typeof value !== "string" || !value.trim()) {
1380
- throw new TypeError("oauth-host: a client needs a non-empty `name` \u2014 it is what the consent screen shows");
1489
+ throw refuse(`client_id metadata field '${field}' must be a non-empty string`);
1381
1490
  }
1382
1491
  return value.trim();
1383
1492
  }
1384
- async function revokeGrantsMatching(ctx, filter, by) {
1385
- const res = await ctx.models.Grant.updateMany(
1386
- { ...filter, revokedAt: null },
1387
- { $set: { revokedAt: /* @__PURE__ */ new Date(), revokedBy: by } }
1388
- );
1389
- return { grantsRevoked: res.modifiedCount ?? 0 };
1493
+ function optionalHttpsUri(doc, field) {
1494
+ const value = doc[field];
1495
+ if (value === void 0 || value === null) return void 0;
1496
+ if (typeof value !== "string" || !value.trim()) {
1497
+ throw refuse(`client_id metadata field '${field}' must be a string`);
1498
+ }
1499
+ let url;
1500
+ try {
1501
+ url = new URL(value);
1502
+ } catch {
1503
+ throw refuse(`client_id metadata field '${field}' must be an absolute URL: '${value}'`);
1504
+ }
1505
+ if (url.protocol !== "https:") {
1506
+ throw refuse(`client_id metadata field '${field}' must be https (got '${url.protocol}')`);
1507
+ }
1508
+ return value;
1390
1509
  }
1391
- async function revokeTokensMatching(ctx, filter) {
1392
- const res = await ctx.models.Token.updateMany(
1393
- { ...filter, revokedAt: null },
1394
- { $set: { revokedAt: /* @__PURE__ */ new Date() } }
1395
- );
1396
- return res.modifiedCount ?? 0;
1510
+ function assertRedirectUris(doc) {
1511
+ const value = doc.redirect_uris;
1512
+ if (!Array.isArray(value) || value.length === 0) {
1513
+ throw refuse("client_id metadata field 'redirect_uris' must be a non-empty array");
1514
+ }
1515
+ return value.map((entry) => {
1516
+ if (typeof entry !== "string" || !entry) {
1517
+ throw refuse(`client_id metadata 'redirect_uris' entries must be strings (got ${JSON.stringify(entry)})`);
1518
+ }
1519
+ let url;
1520
+ try {
1521
+ url = new URL(entry);
1522
+ } catch {
1523
+ throw refuse(`client_id metadata 'redirect_uris' entry must be an absolute URI: '${entry}'`);
1524
+ }
1525
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
1526
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
1527
+ throw refuse(
1528
+ `client_id metadata 'redirect_uris' entry must be https (http is allowed only on localhost/127.0.0.1): '${entry}'`
1529
+ );
1530
+ }
1531
+ if (url.hash) {
1532
+ throw refuse(`client_id metadata 'redirect_uris' entry must not contain a fragment: '${entry}'`);
1533
+ }
1534
+ return entry;
1535
+ });
1397
1536
  }
1398
- function createClientsApi(ctx) {
1399
- async function create(spec) {
1400
- if (!spec || typeof spec !== "object") {
1401
- throw new TypeError("oauth-host: clients.create(spec) requires a spec object");
1537
+ function validateMetadataDocument(ctx, url, doc) {
1538
+ const declared = requireString(doc, "client_id");
1539
+ let declaredUrl;
1540
+ try {
1541
+ declaredUrl = new URL(declared);
1542
+ } catch {
1543
+ throw refuse(`client_id metadata field 'client_id' is not a URL: '${declared}'`);
1544
+ }
1545
+ if (declaredUrl.href !== url.href) {
1546
+ throw refuse(
1547
+ `client_id metadata field 'client_id' is '${declared}', which is not the URL it was fetched from ('${url.href}')`
1548
+ );
1549
+ }
1550
+ const offered = offeredAuthMethods(doc);
1551
+ let usableMethods = offered.filter((m) => SERVER_CIMD_AUTH_METHODS.includes(m));
1552
+ if (usableMethods.length === 0) {
1553
+ throw refuse(
1554
+ `client_id metadata offers token endpoint auth methods [${offered.join(", ")}]; this server supports [${SERVER_CIMD_AUTH_METHODS.join(", ")}] for CIMD clients \u2014 no usable method in the intersection`
1555
+ );
1556
+ }
1557
+ let jwksUri;
1558
+ let jwks;
1559
+ if (usableMethods.includes("private_key_jwt")) {
1560
+ const hasJwksUri = doc.jwks_uri !== void 0 && doc.jwks_uri !== null;
1561
+ const hasJwks = doc.jwks !== void 0 && doc.jwks !== null;
1562
+ if (hasJwksUri && hasJwks) {
1563
+ throw refuse("client_id metadata must not contain both 'jwks' and 'jwks_uri'");
1402
1564
  }
1403
- const name = assertName(spec.name);
1404
- const type = assertClientType(spec.type);
1405
- const redirectUris = assertRedirectUris(spec.redirectUris);
1406
- const allowedScopes = assertScopes(ctx, spec.allowedScopes);
1407
- const allowedResources = assertResources(ctx, spec.allowedResources);
1408
- const clientId = spec.clientId ?? generateClientId();
1565
+ if (hasJwksUri) {
1566
+ jwksUri = assertJwksUri(ctx, doc.jwks_uri);
1567
+ } else if (hasJwks) {
1568
+ jwks = assertInlineJwks(doc.jwks);
1569
+ } else if (usableMethods.includes("none")) {
1570
+ usableMethods = usableMethods.filter((m) => m !== "private_key_jwt");
1571
+ } else {
1572
+ throw refuse("client_id metadata offers private_key_jwt but carries no 'jwks' or 'jwks_uri'");
1573
+ }
1574
+ }
1575
+ const name = requireString(doc, "client_name");
1576
+ const redirectUris = assertRedirectUris(doc);
1577
+ const permitted = new Set(ctx.cimd.allowedScopes.filter((id) => ctx.scopeIndex.has(id)));
1578
+ let allowedScopes;
1579
+ if (doc.scope === void 0 || doc.scope === null) {
1580
+ allowedScopes = [...permitted];
1581
+ } else {
1582
+ if (typeof doc.scope !== "string") {
1583
+ throw refuse("client_id metadata field 'scope' must be a space-delimited string");
1584
+ }
1585
+ const requested = new Set(doc.scope.split(/\s+/).filter(Boolean));
1586
+ allowedScopes = [...permitted].filter((id) => requested.has(id));
1587
+ }
1588
+ if (allowedScopes.length === 0) {
1589
+ throw refuse(
1590
+ "client_id metadata field 'scope' has no overlap with what this server offers \u2014 there is nothing this client could be granted"
1591
+ );
1592
+ }
1593
+ const branding = {};
1594
+ const logoUrl = optionalHttpsUri(doc, "logo_uri");
1595
+ const homepageUrl = optionalHttpsUri(doc, "client_uri");
1596
+ const tosUrl = optionalHttpsUri(doc, "tos_uri");
1597
+ const privacyUrl = optionalHttpsUri(doc, "policy_uri");
1598
+ if (logoUrl) branding.logoUrl = logoUrl;
1599
+ if (homepageUrl) branding.homepageUrl = homepageUrl;
1600
+ if (tosUrl) branding.tosUrl = tosUrl;
1601
+ if (privacyUrl) branding.privacyUrl = privacyUrl;
1602
+ return {
1603
+ name,
1604
+ redirectUris,
1605
+ allowedScopes,
1606
+ branding,
1607
+ usableMethods,
1608
+ ...jwksUri ? { jwksUri } : {},
1609
+ ...jwks ? { jwks } : {}
1610
+ };
1611
+ }
1612
+ function rememberFailure(ctx, key, message) {
1613
+ const { failures } = ctx.cimd;
1614
+ if (failures.size >= MAX_REMEMBERED_FAILURES) {
1615
+ const oldest = failures.keys().next();
1616
+ if (!oldest.done) failures.delete(oldest.value);
1617
+ }
1618
+ failures.set(key, { until: Date.now() + NEGATIVE_TTL_MS, message });
1619
+ }
1620
+ function rememberedFailure(ctx, key) {
1621
+ const found = ctx.cimd.failures.get(key);
1622
+ if (!found) return null;
1623
+ if (found.until <= Date.now()) {
1624
+ ctx.cimd.failures.delete(key);
1625
+ return null;
1626
+ }
1627
+ return found.message;
1628
+ }
1629
+ function isFresh(ctx, client) {
1630
+ const fetchedAt = client.metadataFetchedAt?.getTime();
1631
+ if (fetchedAt === void 0) return false;
1632
+ return Date.now() - fetchedAt < ctx.cimd.cacheTtlMs;
1633
+ }
1634
+ async function persist(ctx, clientId, url, registration, etag) {
1635
+ const unset = {};
1636
+ const jwksFields = {};
1637
+ if (registration.jwksUri) jwksFields.jwksUri = registration.jwksUri;
1638
+ else unset.jwksUri = "";
1639
+ if (registration.jwks) jwksFields.jwks = registration.jwks;
1640
+ else unset.jwks = "";
1641
+ const doc = await ctx.models.Client.findOneAndUpdate(
1642
+ { clientId },
1643
+ {
1644
+ $set: {
1645
+ name: registration.name,
1646
+ redirectUris: registration.redirectUris,
1647
+ allowedScopes: registration.allowedScopes,
1648
+ // Every declared resource. A CIMD client cannot express an audience
1649
+ // preference, and RFC 8707 validation at `/authorize` narrows it anyway.
1650
+ allowedResources: ctx.resources.map((r) => r.id),
1651
+ branding: registration.branding,
1652
+ metadataUrl: url.href,
1653
+ metadataFetchedAt: /* @__PURE__ */ new Date(),
1654
+ tokenEndpointAuthMethods: registration.usableMethods,
1655
+ ...jwksFields,
1656
+ ...etag ? { metadataEtag: etag } : {}
1657
+ },
1658
+ ...Object.keys(unset).length ? { $unset: unset } : {},
1659
+ $setOnInsert: {
1660
+ type: "public",
1661
+ registration: "cimd",
1662
+ trusted: false,
1663
+ secrets: [],
1664
+ status: "active"
1665
+ }
1666
+ },
1667
+ { upsert: true, returnDocument: "after", setDefaultsOnInsert: false }
1668
+ ).exec();
1669
+ return doc;
1670
+ }
1671
+ async function resolveCimdClient(ctx, clientId) {
1672
+ const url = assertFetchableUrl(ctx, clientId);
1673
+ const existing = await ctx.models.Client.findOne({ clientId }).exec();
1674
+ if (existing) {
1675
+ if (existing.status !== "active") {
1676
+ throw refuse(`client '${clientId}' is disabled`);
1677
+ }
1678
+ if (existing.registration !== "cimd") return existing;
1679
+ if (isFresh(ctx, existing)) return existing;
1680
+ }
1681
+ const remembered = rememberedFailure(ctx, url.href);
1682
+ if (remembered) throw refuse(remembered);
1683
+ try {
1684
+ const { document, etag } = await fetchMetadata(ctx, url, existing?.metadataEtag);
1685
+ if (!document) {
1686
+ if (existing) {
1687
+ existing.metadataFetchedAt = /* @__PURE__ */ new Date();
1688
+ await existing.save();
1689
+ return existing;
1690
+ }
1691
+ throw refuse("client_id metadata returned 304 with nothing cached to answer from");
1692
+ }
1693
+ const registration = validateMetadataDocument(ctx, url, document);
1694
+ const client = await persist(ctx, clientId, url, registration, etag);
1695
+ ctx.logger.debug?.({ clientId }, "oauth-host: client_id metadata document resolved");
1696
+ return client;
1697
+ } catch (err) {
1698
+ const message = err instanceof UnredirectableError ? err.description ?? "client_id metadata could not be resolved" : "client_id metadata could not be resolved";
1699
+ rememberFailure(ctx, url.href, message);
1700
+ ctx.logger.warn?.({ clientId, err }, "oauth-host: client_id metadata resolution failed");
1701
+ throw err instanceof UnredirectableError ? err : refuse(message);
1702
+ }
1703
+ }
1704
+
1705
+ // src/server/services/admin.ts
1706
+ var MAX_LIST = 200;
1707
+ var DEFAULT_LIST = 50;
1708
+ function clampLimit(requested) {
1709
+ const n = typeof requested === "number" && Number.isFinite(requested) ? Math.floor(requested) : DEFAULT_LIST;
1710
+ if (n < 1) return 1;
1711
+ return Math.min(n, MAX_LIST);
1712
+ }
1713
+ function clampSkip(requested) {
1714
+ const n = typeof requested === "number" && Number.isFinite(requested) ? Math.floor(requested) : 0;
1715
+ return n > 0 ? n : 0;
1716
+ }
1717
+ function notFound(clientId) {
1718
+ return new Error(`oauth-host: no client registered with clientId '${clientId}'`);
1719
+ }
1720
+ function toPublicClient(doc) {
1721
+ return {
1722
+ clientId: doc.clientId,
1723
+ name: doc.name,
1724
+ type: doc.type,
1725
+ // Defaulted rather than read straight through: rows written before the
1726
+ // field existed have no value, and `undefined` here would read as "unknown
1727
+ // provenance" on a client that plainly was registered by hand.
1728
+ registration: doc.registration ?? "manual",
1729
+ ...doc.metadataUrl ? { metadataUrl: doc.metadataUrl } : {},
1730
+ trusted: Boolean(doc.trusted),
1731
+ redirectUris: [...doc.redirectUris ?? []],
1732
+ allowedScopes: [...doc.allowedScopes ?? []],
1733
+ allowedResources: [...doc.allowedResources ?? []],
1734
+ branding: { ...doc.branding ?? {} },
1735
+ status: doc.status,
1736
+ createdAt: doc.createdAt
1737
+ };
1738
+ }
1739
+ function assertRedirectUri(value) {
1740
+ if (typeof value !== "string" || !value) {
1741
+ throw new TypeError(`oauth-host: every redirectUri must be a string (got ${JSON.stringify(value)})`);
1742
+ }
1743
+ let url;
1744
+ try {
1745
+ url = new URL(value);
1746
+ } catch {
1747
+ throw new TypeError(`oauth-host: redirectUri must be an absolute URI: '${value}'`);
1748
+ }
1749
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
1750
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
1751
+ throw new TypeError(
1752
+ `oauth-host: redirectUri must be https (http is allowed only on localhost/127.0.0.1): '${value}'`
1753
+ );
1754
+ }
1755
+ if (url.hash) {
1756
+ throw new TypeError(`oauth-host: redirectUri must not contain a fragment: '${value}'`);
1757
+ }
1758
+ return value;
1759
+ }
1760
+ function assertRedirectUris2(input) {
1761
+ if (!Array.isArray(input) || input.length === 0) {
1762
+ throw new TypeError("oauth-host: a client needs at least one redirectUri");
1763
+ }
1764
+ return input.map(assertRedirectUri);
1765
+ }
1766
+ function assertScopes(ctx, input) {
1767
+ if (!Array.isArray(input) || input.length === 0) {
1768
+ throw new TypeError("oauth-host: a client needs at least one entry in allowedScopes");
1769
+ }
1770
+ for (const id of input) {
1771
+ if (typeof id !== "string" || !ctx.scopeIndex.has(id)) {
1772
+ throw new TypeError(
1773
+ `oauth-host: allowedScopes contains '${String(id)}', which is not in the configured scope catalog`
1774
+ );
1775
+ }
1776
+ }
1777
+ return [...input];
1778
+ }
1779
+ function assertResources(ctx, input) {
1780
+ const declared = new Set(ctx.resources.map((r) => r.id));
1781
+ if (input === void 0) return ctx.resources.map((r) => r.id);
1782
+ if (!Array.isArray(input) || input.length === 0) {
1783
+ throw new TypeError("oauth-host: allowedResources, when given, must list at least one resource");
1784
+ }
1785
+ for (const id of input) {
1786
+ if (typeof id !== "string" || !declared.has(id)) {
1787
+ throw new TypeError(
1788
+ `oauth-host: allowedResources contains '${String(id)}', which is not a configured resource`
1789
+ );
1790
+ }
1791
+ }
1792
+ return [...input];
1793
+ }
1794
+ function assertClientType(value) {
1795
+ if (value === void 0) return "confidential";
1796
+ if (value !== "confidential" && value !== "public") {
1797
+ throw new TypeError(
1798
+ `oauth-host: client type must be 'confidential' or 'public' (got ${JSON.stringify(value)})`
1799
+ );
1800
+ }
1801
+ return value;
1802
+ }
1803
+ function assertName(value) {
1804
+ if (typeof value !== "string" || !value.trim()) {
1805
+ throw new TypeError("oauth-host: a client needs a non-empty `name` \u2014 it is what the consent screen shows");
1806
+ }
1807
+ return value.trim();
1808
+ }
1809
+ async function revokeGrantsMatching(ctx, filter, by) {
1810
+ const res = await ctx.models.Grant.updateMany(
1811
+ { ...filter, revokedAt: null },
1812
+ { $set: { revokedAt: /* @__PURE__ */ new Date(), revokedBy: by } }
1813
+ );
1814
+ return { grantsRevoked: res.modifiedCount ?? 0 };
1815
+ }
1816
+ async function revokeTokensMatching(ctx, filter) {
1817
+ const res = await ctx.models.Token.updateMany(
1818
+ { ...filter, revokedAt: null },
1819
+ { $set: { revokedAt: /* @__PURE__ */ new Date() } }
1820
+ );
1821
+ return res.modifiedCount ?? 0;
1822
+ }
1823
+ function createClientsApi(ctx) {
1824
+ async function create(spec) {
1825
+ if (!spec || typeof spec !== "object") {
1826
+ throw new TypeError("oauth-host: clients.create(spec) requires a spec object");
1827
+ }
1828
+ const name = assertName(spec.name);
1829
+ const type = assertClientType(spec.type);
1830
+ const redirectUris = assertRedirectUris2(spec.redirectUris);
1831
+ const allowedScopes = assertScopes(ctx, spec.allowedScopes);
1832
+ const allowedResources = assertResources(ctx, spec.allowedResources);
1833
+ const clientId = spec.clientId ?? generateClientId();
1409
1834
  const clientSecret = type === "confidential" ? generateClientSecret() : void 0;
1410
1835
  const doc = await ctx.models.Client.create({
1411
1836
  clientId,
@@ -1462,7 +1887,7 @@ function createClientsApi(ctx) {
1462
1887
  const doc = await ctx.models.Client.findOne({ clientId });
1463
1888
  if (!doc) throw notFound(clientId);
1464
1889
  if (patch.name !== void 0) doc.name = assertName(patch.name);
1465
- if (patch.redirectUris !== void 0) doc.redirectUris = assertRedirectUris(patch.redirectUris);
1890
+ if (patch.redirectUris !== void 0) doc.redirectUris = assertRedirectUris2(patch.redirectUris);
1466
1891
  if (patch.allowedScopes !== void 0) doc.allowedScopes = assertScopes(ctx, patch.allowedScopes);
1467
1892
  if (patch.allowedResources !== void 0) {
1468
1893
  doc.allowedResources = assertResources(ctx, patch.allowedResources);
@@ -1536,19 +1961,202 @@ function authFailure(viaBasic) {
1536
1961
  headers: viaBasic ? { "WWW-Authenticate": 'Basic realm="oauth", charset="UTF-8"' } : {}
1537
1962
  });
1538
1963
  }
1539
- async function authenticateClient(ctx, req) {
1540
- const creds = readCredentials(req);
1541
- if (!creds || !creds.clientId) throw authFailure(Boolean(creds?.viaBasic));
1542
- const client = await ctx.models.Client.findOne({ clientId: creds.clientId });
1543
- if (!client || client.status !== "active") throw authFailure(creds.viaBasic);
1544
- if (client.type === "public") {
1545
- if (creds.clientSecret !== null) throw authFailure(creds.viaBasic);
1546
- return client;
1547
- }
1548
- if (creds.clientSecret === null) throw authFailure(creds.viaBasic);
1964
+ var CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
1965
+ var MAX_ASSERTION_BYTES = 8192;
1966
+ var COMPACT_JWS_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
1967
+ var ASSERTION_ALGORITHMS = ["RS256", "ES256"];
1968
+ var MAX_ASSERTION_AGE_S = 3600;
1969
+ var MAX_JTI_LEN = 256;
1970
+ var REPLAY_CACHE_MAX = 1e4;
1971
+ var JWKS_CACHE_MAX = 100;
1972
+ var JWKS_FORCE_REFETCH_INTERVAL_MS = 6e4;
1973
+ var ASSERTION_CLOCK_TOLERANCE_S = 60;
1974
+ function tokenEndpointUrl(ctx) {
1975
+ return `${ctx.issuer}${ctx.mountPath}/token`;
1976
+ }
1977
+ function isJwkSet(doc) {
1978
+ return Boolean(doc) && typeof doc === "object" && Array.isArray(doc.keys);
1979
+ }
1980
+ function assertionFailure(reason) {
1981
+ return new Error(reason);
1982
+ }
1983
+ function selectCandidateKeys(keys, header) {
1984
+ return keys.filter((key) => {
1985
+ if (header.kid !== void 0 && key.kid !== header.kid) return false;
1986
+ const use = key.use;
1987
+ if (use !== void 0 && use !== "sig") return false;
1988
+ const alg = key.alg;
1989
+ if (alg !== void 0 && alg !== header.alg) return false;
1990
+ return true;
1991
+ });
1992
+ }
1993
+ async function resolveJwksKeys(ctx, jwksUri, forceRefetch) {
1994
+ const { jwksCache, jwksForceRefetchAt } = ctx.cimd;
1549
1995
  const now = Date.now();
1550
- let matched;
1551
- for (const record of client.secrets) {
1996
+ const cached = jwksCache.get(jwksUri);
1997
+ const fresh = cached !== void 0 && now - cached.fetchedAt < ctx.cimd.cacheTtlMs;
1998
+ if (fresh && !forceRefetch) return cached.keys;
1999
+ if (forceRefetch) {
2000
+ const lastForced = jwksForceRefetchAt.get(jwksUri) ?? 0;
2001
+ if (now - lastForced < JWKS_FORCE_REFETCH_INTERVAL_MS) {
2002
+ return cached?.keys ?? [];
2003
+ }
2004
+ jwksForceRefetchAt.set(jwksUri, now);
2005
+ }
2006
+ const doc = await fetchJwks(ctx, jwksUri);
2007
+ if (!isJwkSet(doc)) throw assertionFailure(`jwks_uri '${jwksUri}' did not serve a JWK Set`);
2008
+ if (!jwksCache.has(jwksUri) && jwksCache.size >= JWKS_CACHE_MAX) {
2009
+ const oldest = jwksCache.keys().next();
2010
+ if (!oldest.done) jwksCache.delete(oldest.value);
2011
+ }
2012
+ jwksCache.set(jwksUri, { keys: doc.keys, fetchedAt: now });
2013
+ return doc.keys;
2014
+ }
2015
+ async function loadClientJwks(ctx, client) {
2016
+ if (client.jwks !== void 0 && client.jwks !== null) {
2017
+ if (!isJwkSet(client.jwks)) {
2018
+ throw assertionFailure(`client '${client.clientId}' has a malformed stored 'jwks'`);
2019
+ }
2020
+ return client.jwks.keys;
2021
+ }
2022
+ if (client.jwksUri) {
2023
+ return resolveJwksKeys(ctx, client.jwksUri, false);
2024
+ }
2025
+ throw assertionFailure(`client '${client.clientId}' has neither 'jwks' nor 'jwksUri' stored`);
2026
+ }
2027
+ async function verifyClientAssertion(ctx, body) {
2028
+ if (body.client_assertion_type !== CLIENT_ASSERTION_TYPE) {
2029
+ throw assertionFailure(
2030
+ `client_assertion_type must be '${CLIENT_ASSERTION_TYPE}' (got ${JSON.stringify(body.client_assertion_type)})`
2031
+ );
2032
+ }
2033
+ const assertion = body.client_assertion;
2034
+ if (typeof assertion !== "string" || !assertion || Buffer.byteLength(assertion, "utf8") > MAX_ASSERTION_BYTES || !COMPACT_JWS_RE.test(assertion)) {
2035
+ throw assertionFailure("client_assertion is not a well-formed compact JWS");
2036
+ }
2037
+ if (typeof body.client_secret === "string" && body.client_secret) {
2038
+ throw assertionFailure("client_assertion was presented alongside a client_secret");
2039
+ }
2040
+ let unverified;
2041
+ try {
2042
+ unverified = jose.decodeJwt(assertion);
2043
+ } catch {
2044
+ throw assertionFailure("client_assertion could not be decoded");
2045
+ }
2046
+ const iss = unverified.iss;
2047
+ if (typeof iss !== "string" || !iss) {
2048
+ throw assertionFailure("client_assertion is missing iss");
2049
+ }
2050
+ if (typeof body.client_id === "string" && body.client_id && body.client_id !== iss) {
2051
+ throw assertionFailure("client_assertion iss does not match client_id");
2052
+ }
2053
+ const client = await ctx.models.Client.findOne({ clientId: iss });
2054
+ if (!client || client.status !== "active" || !client.tokenEndpointAuthMethods?.includes("private_key_jwt")) {
2055
+ throw assertionFailure(`client '${iss}' does not support private_key_jwt`);
2056
+ }
2057
+ let header;
2058
+ try {
2059
+ header = jose.decodeProtectedHeader(assertion);
2060
+ } catch {
2061
+ throw assertionFailure("client_assertion header could not be decoded");
2062
+ }
2063
+ const alg = header.alg;
2064
+ if (alg !== "RS256" && alg !== "ES256") {
2065
+ throw assertionFailure(`client_assertion alg '${String(alg)}' is not permitted`);
2066
+ }
2067
+ const stored = await loadClientJwks(ctx, client);
2068
+ let candidates = selectCandidateKeys(stored, { alg, kid: header.kid });
2069
+ if (candidates.length === 0 && client.jwksUri) {
2070
+ const refetched = await resolveJwksKeys(ctx, client.jwksUri, true);
2071
+ candidates = selectCandidateKeys(refetched, { alg, kid: header.kid });
2072
+ }
2073
+ if (candidates.length === 0) {
2074
+ throw assertionFailure(`no candidate key for kid '${String(header.kid)}'`);
2075
+ }
2076
+ const tokenEndpoint = tokenEndpointUrl(ctx);
2077
+ let verified;
2078
+ let lastJoseError;
2079
+ for (const jwk of candidates) {
2080
+ try {
2081
+ const key = await jose.importJWK(jwk, alg);
2082
+ verified = await jose.jwtVerify(assertion, key, {
2083
+ // Passed explicitly rather than trusting the header a second time —
2084
+ // this is the actual alg-confusion guard, not the earlier check,
2085
+ // which only short-circuits the common case before a fetch.
2086
+ algorithms: [...ASSERTION_ALGORITHMS],
2087
+ audience: [tokenEndpoint, ctx.issuer],
2088
+ clockTolerance: ASSERTION_CLOCK_TOLERANCE_S
2089
+ });
2090
+ break;
2091
+ } catch (err) {
2092
+ lastJoseError = err;
2093
+ }
2094
+ }
2095
+ if (!verified) {
2096
+ throw assertionFailure(
2097
+ `client_assertion did not verify: ${lastJoseError instanceof Error ? lastJoseError.message : "unknown error"}`
2098
+ );
2099
+ }
2100
+ const { payload } = verified;
2101
+ if (payload.iss !== client.clientId || payload.sub !== client.clientId) {
2102
+ throw assertionFailure("client_assertion iss/sub must both equal the client_id");
2103
+ }
2104
+ const exp = payload.exp;
2105
+ const nowS = Math.floor(Date.now() / 1e3);
2106
+ if (typeof exp !== "number" || exp - nowS > MAX_ASSERTION_AGE_S) {
2107
+ throw assertionFailure("client_assertion exp is too far in the future");
2108
+ }
2109
+ const jti = payload.jti;
2110
+ if (typeof jti !== "string" || !jti || jti.length > MAX_JTI_LEN) {
2111
+ throw assertionFailure("client_assertion is missing jti");
2112
+ }
2113
+ const replay = ctx.cimd.assertionReplay;
2114
+ const replayKey = `${client.clientId}:${jti}`;
2115
+ const existing = replay.get(replayKey);
2116
+ if (existing !== void 0 && existing > Date.now()) {
2117
+ ctx.logger.warn?.({ clientId: client.clientId }, "oauth-host: private_key_jwt assertion replay detected");
2118
+ throw assertionFailure("client_assertion jti has already been used");
2119
+ }
2120
+ if (!replay.has(replayKey) && replay.size >= REPLAY_CACHE_MAX) {
2121
+ const oldest = replay.keys().next();
2122
+ if (!oldest.done) replay.delete(oldest.value);
2123
+ }
2124
+ replay.set(replayKey, (exp + 60) * 1e3);
2125
+ return client;
2126
+ }
2127
+ async function authenticateClient(ctx, req) {
2128
+ const body = req.body ?? {};
2129
+ const header = req.headers?.authorization;
2130
+ const viaBasic = typeof header === "string" && /^Basic /i.test(header);
2131
+ if (body.client_assertion !== void 0 || body.client_assertion_type !== void 0) {
2132
+ if (viaBasic) {
2133
+ ctx.logger.debug?.(
2134
+ "oauth-host: client_assertion presented alongside a Basic Authorization header"
2135
+ );
2136
+ throw authFailure(viaBasic);
2137
+ }
2138
+ try {
2139
+ return await verifyClientAssertion(ctx, body);
2140
+ } catch (err) {
2141
+ ctx.logger.debug?.(
2142
+ { err: err instanceof Error ? err.message : err },
2143
+ "oauth-host: private_key_jwt assertion rejected"
2144
+ );
2145
+ throw authFailure(viaBasic);
2146
+ }
2147
+ }
2148
+ const creds = readCredentials(req);
2149
+ if (!creds || !creds.clientId) throw authFailure(Boolean(creds?.viaBasic));
2150
+ const client = await ctx.models.Client.findOne({ clientId: creds.clientId });
2151
+ if (!client || client.status !== "active") throw authFailure(creds.viaBasic);
2152
+ if (client.type === "public") {
2153
+ if (creds.clientSecret !== null) throw authFailure(creds.viaBasic);
2154
+ return client;
2155
+ }
2156
+ if (creds.clientSecret === null) throw authFailure(creds.viaBasic);
2157
+ const now = Date.now();
2158
+ let matched;
2159
+ for (const record of client.secrets) {
1552
2160
  if (record.retiresAt && record.retiresAt.getTime() <= now) continue;
1553
2161
  if (safeEqual(sha256(creds.clientSecret), record.hash)) matched = record;
1554
2162
  }
@@ -1743,297 +2351,6 @@ function createContextsApi(ctx) {
1743
2351
  };
1744
2352
  }
1745
2353
 
1746
- // src/server/services/cimd.ts
1747
- var NEGATIVE_TTL_MS = 6e4;
1748
- var MAX_REMEMBERED_FAILURES = 1e3;
1749
- function refuse(description) {
1750
- return new UnredirectableError("invalid_client", description);
1751
- }
1752
- function isMetadataUrl(clientId) {
1753
- return /^https:\/\//i.test(clientId);
1754
- }
1755
- function hostAllowed(rules, url) {
1756
- const hostname = url.hostname.toLowerCase();
1757
- return rules.some((rule) => {
1758
- if (url.port !== rule.port) return false;
1759
- if (hostname === rule.host) return true;
1760
- return rule.subdomains && hostname.endsWith(`.${rule.host}`);
1761
- });
1762
- }
1763
- function assertFetchableUrl(ctx, clientId) {
1764
- let url;
1765
- try {
1766
- url = new URL(clientId);
1767
- } catch {
1768
- throw refuse(`client_id is not a valid URL: '${clientId}'`);
1769
- }
1770
- if (url.protocol !== "https:") {
1771
- throw refuse(`client_id metadata must be served over https (got '${url.protocol}')`);
1772
- }
1773
- if (url.username || url.password) {
1774
- throw refuse("client_id must not contain URL credentials");
1775
- }
1776
- if (url.hash) {
1777
- throw refuse("client_id must not contain a fragment");
1778
- }
1779
- if (!hostAllowed(ctx.cimd.allowedHosts, url)) {
1780
- throw refuse(`client_id host '${url.host}' is not in clientIdMetadata.allowedHosts`);
1781
- }
1782
- return url;
1783
- }
1784
- var JSON_CONTENT_TYPE = /^application\/(?:[\w.+-]+\+)?json\s*(?:;|$)/i;
1785
- async function readCapped(res, maxBytes) {
1786
- const body = res.body;
1787
- if (!body) throw refuse("client_id metadata document was empty");
1788
- const reader = body.getReader();
1789
- const chunks = [];
1790
- let total = 0;
1791
- for (; ; ) {
1792
- const { done, value } = await reader.read();
1793
- if (done) break;
1794
- if (!value) continue;
1795
- total += value.byteLength;
1796
- if (total > maxBytes) {
1797
- void reader.cancel();
1798
- throw refuse(`client_id metadata document exceeds ${maxBytes} bytes`);
1799
- }
1800
- chunks.push(Buffer.from(value));
1801
- }
1802
- return Buffer.concat(chunks).toString("utf8");
1803
- }
1804
- async function fetchMetadata(ctx, url, etag) {
1805
- let res;
1806
- try {
1807
- res = await fetch(url.toString(), {
1808
- method: "GET",
1809
- // The single most important line in this file. A 3xx is a failure below,
1810
- // not a hop: following redirects would let an allowlisted host forward us
1811
- // to any address it likes, allowlist intact.
1812
- redirect: "manual",
1813
- headers: {
1814
- accept: "application/json",
1815
- ...etag ? { "if-none-match": etag } : {}
1816
- },
1817
- signal: AbortSignal.timeout(ctx.cimd.fetchTimeoutMs)
1818
- });
1819
- } catch (err) {
1820
- const name = err?.name;
1821
- if (name === "TimeoutError" || name === "AbortError") {
1822
- throw refuse(`client_id metadata fetch timed out after ${ctx.cimd.fetchTimeoutMs}ms`);
1823
- }
1824
- throw refuse(`client_id metadata could not be fetched: ${err?.message ?? "network error"}`);
1825
- }
1826
- if (res.status === 304) return { document: null };
1827
- if (res.status >= 300 && res.status < 400) {
1828
- throw refuse(
1829
- `client_id metadata returned a ${res.status} redirect, which is not followed \u2014 serve the document at the client_id URL itself`
1830
- );
1831
- }
1832
- if (res.status !== 200) {
1833
- throw refuse(`client_id metadata returned HTTP ${res.status}`);
1834
- }
1835
- const contentType = res.headers.get("content-type") ?? "";
1836
- if (!JSON_CONTENT_TYPE.test(contentType)) {
1837
- throw refuse(`client_id metadata must be JSON (got content-type '${contentType || "none"}')`);
1838
- }
1839
- const text = await readCapped(res, ctx.cimd.maxBytes);
1840
- let parsed;
1841
- try {
1842
- parsed = JSON.parse(text);
1843
- } catch {
1844
- throw refuse("client_id metadata document is not valid JSON");
1845
- }
1846
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1847
- throw refuse("client_id metadata document must be a JSON object");
1848
- }
1849
- return {
1850
- document: parsed,
1851
- ...res.headers.get("etag") ? { etag: res.headers.get("etag") } : {}
1852
- };
1853
- }
1854
- function requireString(doc, field) {
1855
- const value = doc[field];
1856
- if (typeof value !== "string" || !value.trim()) {
1857
- throw refuse(`client_id metadata field '${field}' must be a non-empty string`);
1858
- }
1859
- return value.trim();
1860
- }
1861
- function optionalHttpsUri(doc, field) {
1862
- const value = doc[field];
1863
- if (value === void 0 || value === null) return void 0;
1864
- if (typeof value !== "string" || !value.trim()) {
1865
- throw refuse(`client_id metadata field '${field}' must be a string`);
1866
- }
1867
- let url;
1868
- try {
1869
- url = new URL(value);
1870
- } catch {
1871
- throw refuse(`client_id metadata field '${field}' must be an absolute URL: '${value}'`);
1872
- }
1873
- if (url.protocol !== "https:") {
1874
- throw refuse(`client_id metadata field '${field}' must be https (got '${url.protocol}')`);
1875
- }
1876
- return value;
1877
- }
1878
- function assertRedirectUris2(doc) {
1879
- const value = doc.redirect_uris;
1880
- if (!Array.isArray(value) || value.length === 0) {
1881
- throw refuse("client_id metadata field 'redirect_uris' must be a non-empty array");
1882
- }
1883
- return value.map((entry) => {
1884
- if (typeof entry !== "string" || !entry) {
1885
- throw refuse(`client_id metadata 'redirect_uris' entries must be strings (got ${JSON.stringify(entry)})`);
1886
- }
1887
- let url;
1888
- try {
1889
- url = new URL(entry);
1890
- } catch {
1891
- throw refuse(`client_id metadata 'redirect_uris' entry must be an absolute URI: '${entry}'`);
1892
- }
1893
- const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
1894
- if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
1895
- throw refuse(
1896
- `client_id metadata 'redirect_uris' entry must be https (http is allowed only on localhost/127.0.0.1): '${entry}'`
1897
- );
1898
- }
1899
- if (url.hash) {
1900
- throw refuse(`client_id metadata 'redirect_uris' entry must not contain a fragment: '${entry}'`);
1901
- }
1902
- return entry;
1903
- });
1904
- }
1905
- function validateMetadataDocument(ctx, url, doc) {
1906
- const declared = requireString(doc, "client_id");
1907
- let declaredUrl;
1908
- try {
1909
- declaredUrl = new URL(declared);
1910
- } catch {
1911
- throw refuse(`client_id metadata field 'client_id' is not a URL: '${declared}'`);
1912
- }
1913
- if (declaredUrl.href !== url.href) {
1914
- throw refuse(
1915
- `client_id metadata field 'client_id' is '${declared}', which is not the URL it was fetched from ('${url.href}')`
1916
- );
1917
- }
1918
- const method = doc.token_endpoint_auth_method;
1919
- if (method !== void 0 && method !== "none") {
1920
- throw refuse(
1921
- `client_id metadata field 'token_endpoint_auth_method' must be 'none' (got ${JSON.stringify(method)}) \u2014 a CIMD client holds no secret`
1922
- );
1923
- }
1924
- const name = requireString(doc, "client_name");
1925
- const redirectUris = assertRedirectUris2(doc);
1926
- const permitted = new Set(ctx.cimd.allowedScopes.filter((id) => ctx.scopeIndex.has(id)));
1927
- let allowedScopes;
1928
- if (doc.scope === void 0 || doc.scope === null) {
1929
- allowedScopes = [...permitted];
1930
- } else {
1931
- if (typeof doc.scope !== "string") {
1932
- throw refuse("client_id metadata field 'scope' must be a space-delimited string");
1933
- }
1934
- const requested = new Set(doc.scope.split(/\s+/).filter(Boolean));
1935
- allowedScopes = [...permitted].filter((id) => requested.has(id));
1936
- }
1937
- if (allowedScopes.length === 0) {
1938
- throw refuse(
1939
- "client_id metadata field 'scope' has no overlap with what this server offers \u2014 there is nothing this client could be granted"
1940
- );
1941
- }
1942
- const branding = {};
1943
- const logoUrl = optionalHttpsUri(doc, "logo_uri");
1944
- const homepageUrl = optionalHttpsUri(doc, "client_uri");
1945
- const tosUrl = optionalHttpsUri(doc, "tos_uri");
1946
- const privacyUrl = optionalHttpsUri(doc, "policy_uri");
1947
- if (logoUrl) branding.logoUrl = logoUrl;
1948
- if (homepageUrl) branding.homepageUrl = homepageUrl;
1949
- if (tosUrl) branding.tosUrl = tosUrl;
1950
- if (privacyUrl) branding.privacyUrl = privacyUrl;
1951
- return { name, redirectUris, allowedScopes, branding };
1952
- }
1953
- function rememberFailure(ctx, key, message) {
1954
- const { failures } = ctx.cimd;
1955
- if (failures.size >= MAX_REMEMBERED_FAILURES) {
1956
- const oldest = failures.keys().next();
1957
- if (!oldest.done) failures.delete(oldest.value);
1958
- }
1959
- failures.set(key, { until: Date.now() + NEGATIVE_TTL_MS, message });
1960
- }
1961
- function rememberedFailure(ctx, key) {
1962
- const found = ctx.cimd.failures.get(key);
1963
- if (!found) return null;
1964
- if (found.until <= Date.now()) {
1965
- ctx.cimd.failures.delete(key);
1966
- return null;
1967
- }
1968
- return found.message;
1969
- }
1970
- function isFresh(ctx, client) {
1971
- const fetchedAt = client.metadataFetchedAt?.getTime();
1972
- if (fetchedAt === void 0) return false;
1973
- return Date.now() - fetchedAt < ctx.cimd.cacheTtlMs;
1974
- }
1975
- async function persist(ctx, clientId, url, registration, etag) {
1976
- const doc = await ctx.models.Client.findOneAndUpdate(
1977
- { clientId },
1978
- {
1979
- $set: {
1980
- name: registration.name,
1981
- redirectUris: registration.redirectUris,
1982
- allowedScopes: registration.allowedScopes,
1983
- // Every declared resource. A CIMD client cannot express an audience
1984
- // preference, and RFC 8707 validation at `/authorize` narrows it anyway.
1985
- allowedResources: ctx.resources.map((r) => r.id),
1986
- branding: registration.branding,
1987
- metadataUrl: url.href,
1988
- metadataFetchedAt: /* @__PURE__ */ new Date(),
1989
- ...etag ? { metadataEtag: etag } : {}
1990
- },
1991
- $setOnInsert: {
1992
- type: "public",
1993
- registration: "cimd",
1994
- trusted: false,
1995
- secrets: [],
1996
- status: "active"
1997
- }
1998
- },
1999
- { upsert: true, returnDocument: "after", setDefaultsOnInsert: false }
2000
- ).exec();
2001
- return doc;
2002
- }
2003
- async function resolveCimdClient(ctx, clientId) {
2004
- const url = assertFetchableUrl(ctx, clientId);
2005
- const existing = await ctx.models.Client.findOne({ clientId }).exec();
2006
- if (existing) {
2007
- if (existing.status !== "active") {
2008
- throw refuse(`client '${clientId}' is disabled`);
2009
- }
2010
- if (existing.registration !== "cimd") return existing;
2011
- if (isFresh(ctx, existing)) return existing;
2012
- }
2013
- const remembered = rememberedFailure(ctx, url.href);
2014
- if (remembered) throw refuse(remembered);
2015
- try {
2016
- const { document, etag } = await fetchMetadata(ctx, url, existing?.metadataEtag);
2017
- if (!document) {
2018
- if (existing) {
2019
- existing.metadataFetchedAt = /* @__PURE__ */ new Date();
2020
- await existing.save();
2021
- return existing;
2022
- }
2023
- throw refuse("client_id metadata returned 304 with nothing cached to answer from");
2024
- }
2025
- const registration = validateMetadataDocument(ctx, url, document);
2026
- const client = await persist(ctx, clientId, url, registration, etag);
2027
- ctx.logger.debug?.({ clientId }, "oauth-host: client_id metadata document resolved");
2028
- return client;
2029
- } catch (err) {
2030
- const message = err instanceof UnredirectableError ? err.description ?? "client_id metadata could not be resolved" : "client_id metadata could not be resolved";
2031
- rememberFailure(ctx, url.href, message);
2032
- ctx.logger.warn?.({ clientId, err }, "oauth-host: client_id metadata resolution failed");
2033
- throw err instanceof UnredirectableError ? err : refuse(message);
2034
- }
2035
- }
2036
-
2037
2354
  // src/server/services/scopes.ts
2038
2355
  function parseScope(raw) {
2039
2356
  if (typeof raw !== "string") return [];