@jeffjassky/oauth-host 0.2.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.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import mongoose from 'mongoose';
2
2
  import express2 from 'express';
3
3
  import { createHash, randomBytes, createPrivateKey, createPublicKey, generateKeyPairSync, timingSafeEqual, sign, createHmac } from 'crypto';
4
+ import { decodeJwt, decodeProtectedHeader, importJWK, jwtVerify } from 'jose';
4
5
 
5
6
  // src/server/models.ts
6
7
  var DEFAULT_NAMES = {
@@ -22,9 +23,11 @@ function clientSchema() {
22
23
  {
23
24
  clientId: { type: String, required: true, unique: true },
24
25
  name: { type: String, required: true },
25
- // `public` exists for CIMD clients, which hold no secret and are bound by
26
- // PKCE instead. The enum was written with this widening in mind, so it
27
- // was one member rather than a migration.
26
+ // `public` is a client that holds no secret and is bound by PKCE instead.
27
+ // Two ways in and they are independent: a CIMD row is written public, and
28
+ // `clients.create({ type: 'public' })` registers one by hand. The enum was
29
+ // written with this widening in mind, so it was one member rather than a
30
+ // migration.
28
31
  type: { type: String, enum: ["confidential", "public"], default: "confidential" },
29
32
  // How the row got here. A `cimd` row is re-derived from the client's own
30
33
  // metadata document, so this is what tells the re-fetch path which fields
@@ -33,6 +36,18 @@ function clientSchema() {
33
36
  metadataUrl: String,
34
37
  metadataFetchedAt: Date,
35
38
  metadataEtag: String,
39
+ // The usable (intersected) token endpoint auth method set for a CIMD
40
+ // client — absent on a manual registration, whose behavior derives from
41
+ // `type` exactly as before. A row with no value here supports no
42
+ // assertion-based method; see `authenticateClient`'s fallback rule.
43
+ tokenEndpointAuthMethods: [String],
44
+ // Exactly one of these two is set when `private_key_jwt` is in
45
+ // `tokenEndpointAuthMethods` — `validateMetadataDocument` refuses a
46
+ // document declaring both. Neither is ever required at the schema
47
+ // level: a manual client, or a CIMD client that only offers `none`,
48
+ // legitimately has neither.
49
+ jwksUri: String,
50
+ jwks: mongoose.Schema.Types.Mixed,
36
51
  trusted: { type: Boolean, default: false },
37
52
  // An array, not a string: rotation needs two live secrets at once or it
38
53
  // cannot be deployed without downtime.
@@ -376,7 +391,10 @@ function resolveCimd(input, scopeIndex) {
376
391
  fetchTimeoutMs: 5e3,
377
392
  maxBytes: 65536,
378
393
  allowedScopes: [],
379
- failures: /* @__PURE__ */ new Map()
394
+ failures: /* @__PURE__ */ new Map(),
395
+ jwksCache: /* @__PURE__ */ new Map(),
396
+ jwksForceRefetchAt: /* @__PURE__ */ new Map(),
397
+ assertionReplay: /* @__PURE__ */ new Map()
380
398
  };
381
399
  if (!input || !input.enabled) return off;
382
400
  if (!Array.isArray(input.allowedHosts) || input.allowedHosts.length === 0) {
@@ -409,7 +427,10 @@ function resolveCimd(input, scopeIndex) {
409
427
  fetchTimeoutMs: positive(input.fetchTimeoutMs, "fetchTimeoutMs", 5e3),
410
428
  maxBytes: positive(input.maxBytes, "maxBytes", 65536),
411
429
  allowedScopes: [...allowedScopes],
412
- failures: /* @__PURE__ */ new Map()
430
+ failures: /* @__PURE__ */ new Map(),
431
+ jwksCache: /* @__PURE__ */ new Map(),
432
+ jwksForceRefetchAt: /* @__PURE__ */ new Map(),
433
+ assertionReplay: /* @__PURE__ */ new Map()
413
434
  };
414
435
  }
415
436
  function resolveConfig(config) {
@@ -657,15 +678,19 @@ function authorizationServerMetadata(ctx, mountPath) {
657
678
  // S256 only. `plain` is not implemented anywhere in this package, so
658
679
  // advertising it would be a lie a client would discover at redemption.
659
680
  code_challenge_methods_supported: ["S256"],
660
- // `none` is advertised only when CIMD is on. Listing it unconditionally
661
- // would tell every client that secretless authentication is available here,
662
- // and the only clients that can use it are the ones this server would then
663
- // refuse to register.
681
+ // `none` and `private_key_jwt` are advertised only when CIMD is on.
682
+ // Listing either unconditionally would tell every client that secretless
683
+ // authentication is available here, and the only clients that can use it
684
+ // are the ones this server would then refuse to register.
664
685
  token_endpoint_auth_methods_supported: [
665
686
  "client_secret_basic",
666
687
  "client_secret_post",
667
- ...ctx.cimd.enabled ? ["none"] : []
688
+ ...ctx.cimd.enabled ? ["none", "private_key_jwt"] : []
668
689
  ],
690
+ // RFC 7523 §2.2 — the only two algorithms `authenticateClient` accepts
691
+ // for a `client_assertion` signature. Same gate as the line above: it
692
+ // names a capability that only exists for a CIMD client.
693
+ ...ctx.cimd.enabled ? { token_endpoint_auth_signing_alg_values_supported: ["RS256", "ES256"] } : {},
669
694
  // What tells Claude and ChatGPT to skip registration entirely and send
670
695
  // their metadata document URL as `client_id`.
671
696
  ...ctx.cimd.enabled ? { client_id_metadata_document_supported: true } : {},
@@ -1268,749 +1293,1055 @@ function createKeyManager(ctx) {
1268
1293
  };
1269
1294
  }
1270
1295
 
1271
- // src/server/services/admin.ts
1272
- var MAX_LIST = 200;
1273
- var DEFAULT_LIST = 50;
1274
- function clampLimit(requested) {
1275
- const n = typeof requested === "number" && Number.isFinite(requested) ? Math.floor(requested) : DEFAULT_LIST;
1276
- if (n < 1) return 1;
1277
- return Math.min(n, MAX_LIST);
1296
+ // src/server/services/cimd.ts
1297
+ var NEGATIVE_TTL_MS = 6e4;
1298
+ var MAX_REMEMBERED_FAILURES = 1e3;
1299
+ function refuse(description) {
1300
+ return new UnredirectableError("invalid_client", description);
1278
1301
  }
1279
- function clampSkip(requested) {
1280
- const n = typeof requested === "number" && Number.isFinite(requested) ? Math.floor(requested) : 0;
1281
- return n > 0 ? n : 0;
1302
+ function isMetadataUrl(clientId) {
1303
+ return /^https:\/\//i.test(clientId);
1282
1304
  }
1283
- function notFound(clientId) {
1284
- return new Error(`oauth-host: no client registered with clientId '${clientId}'`);
1305
+ function hostAllowed(rules, url) {
1306
+ const hostname = url.hostname.toLowerCase();
1307
+ return rules.some((rule) => {
1308
+ if (url.port !== rule.port) return false;
1309
+ if (hostname === rule.host) return true;
1310
+ return rule.subdomains && hostname.endsWith(`.${rule.host}`);
1311
+ });
1285
1312
  }
1286
- function toPublicClient(doc) {
1313
+ function assertFetchableUrl(ctx, clientId) {
1314
+ let url;
1315
+ try {
1316
+ url = new URL(clientId);
1317
+ } catch {
1318
+ throw refuse(`client_id is not a valid URL: '${clientId}'`);
1319
+ }
1320
+ if (url.protocol !== "https:") {
1321
+ throw refuse(`client_id metadata must be served over https (got '${url.protocol}')`);
1322
+ }
1323
+ if (url.username || url.password) {
1324
+ throw refuse("client_id must not contain URL credentials");
1325
+ }
1326
+ if (url.hash) {
1327
+ throw refuse("client_id must not contain a fragment");
1328
+ }
1329
+ if (!hostAllowed(ctx.cimd.allowedHosts, url)) {
1330
+ throw refuse(`client_id host '${url.host}' is not in clientIdMetadata.allowedHosts`);
1331
+ }
1332
+ return url;
1333
+ }
1334
+ var JSON_CONTENT_TYPE = /^application\/(?:[\w.+-]+\+)?json\s*(?:;|$)/i;
1335
+ async function readCapped(res, maxBytes, docSubject) {
1336
+ const body = res.body;
1337
+ if (!body) throw refuse(`${docSubject} was empty`);
1338
+ const reader = body.getReader();
1339
+ const chunks = [];
1340
+ let total = 0;
1341
+ for (; ; ) {
1342
+ const { done, value } = await reader.read();
1343
+ if (done) break;
1344
+ if (!value) continue;
1345
+ total += value.byteLength;
1346
+ if (total > maxBytes) {
1347
+ void reader.cancel();
1348
+ throw refuse(`${docSubject} exceeds ${maxBytes} bytes`);
1349
+ }
1350
+ chunks.push(Buffer.from(value));
1351
+ }
1352
+ return Buffer.concat(chunks).toString("utf8");
1353
+ }
1354
+ async function hardenedFetch(ctx, url, opts) {
1355
+ const { subject, redirectAdvice, etag } = opts;
1356
+ const docSubject = `${subject} document`;
1357
+ let res;
1358
+ try {
1359
+ res = await fetch(url.toString(), {
1360
+ method: "GET",
1361
+ // The single most important line in this file. A 3xx is a failure below,
1362
+ // not a hop: following redirects would let an allowlisted host forward us
1363
+ // to any address it likes, allowlist intact.
1364
+ redirect: "manual",
1365
+ headers: {
1366
+ accept: "application/json",
1367
+ ...etag ? { "if-none-match": etag } : {}
1368
+ },
1369
+ signal: AbortSignal.timeout(ctx.cimd.fetchTimeoutMs)
1370
+ });
1371
+ } catch (err) {
1372
+ const name = err?.name;
1373
+ if (name === "TimeoutError" || name === "AbortError") {
1374
+ throw refuse(`${subject} fetch timed out after ${ctx.cimd.fetchTimeoutMs}ms`);
1375
+ }
1376
+ throw refuse(`${subject} could not be fetched: ${err?.message ?? "network error"}`);
1377
+ }
1378
+ if (res.status === 304) return { document: null };
1379
+ if (res.status >= 300 && res.status < 400) {
1380
+ throw refuse(`${subject} returned a ${res.status} redirect, which is not followed \u2014 ${redirectAdvice}`);
1381
+ }
1382
+ if (res.status !== 200) {
1383
+ throw refuse(`${subject} returned HTTP ${res.status}`);
1384
+ }
1385
+ const contentType = res.headers.get("content-type") ?? "";
1386
+ if (!JSON_CONTENT_TYPE.test(contentType)) {
1387
+ throw refuse(`${subject} must be JSON (got content-type '${contentType || "none"}')`);
1388
+ }
1389
+ const text = await readCapped(res, ctx.cimd.maxBytes, docSubject);
1390
+ let parsed;
1391
+ try {
1392
+ parsed = JSON.parse(text);
1393
+ } catch {
1394
+ throw refuse(`${docSubject} is not valid JSON`);
1395
+ }
1396
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1397
+ throw refuse(`${docSubject} must be a JSON object`);
1398
+ }
1287
1399
  return {
1288
- clientId: doc.clientId,
1289
- name: doc.name,
1290
- type: doc.type,
1291
- // Defaulted rather than read straight through: rows written before the
1292
- // field existed have no value, and `undefined` here would read as "unknown
1293
- // provenance" on a client that plainly was registered by hand.
1294
- registration: doc.registration ?? "manual",
1295
- ...doc.metadataUrl ? { metadataUrl: doc.metadataUrl } : {},
1296
- trusted: Boolean(doc.trusted),
1297
- redirectUris: [...doc.redirectUris ?? []],
1298
- allowedScopes: [...doc.allowedScopes ?? []],
1299
- allowedResources: [...doc.allowedResources ?? []],
1300
- branding: { ...doc.branding ?? {} },
1301
- status: doc.status,
1302
- createdAt: doc.createdAt
1400
+ document: parsed,
1401
+ ...res.headers.get("etag") ? { etag: res.headers.get("etag") } : {}
1303
1402
  };
1304
1403
  }
1305
- function assertRedirectUri(value) {
1306
- if (typeof value !== "string" || !value) {
1307
- throw new TypeError(`oauth-host: every redirectUri must be a string (got ${JSON.stringify(value)})`);
1404
+ async function fetchMetadata(ctx, url, etag) {
1405
+ return hardenedFetch(ctx, url, {
1406
+ subject: "client_id metadata",
1407
+ redirectAdvice: "serve the document at the client_id URL itself",
1408
+ etag
1409
+ });
1410
+ }
1411
+ async function fetchJwks(ctx, jwksUri) {
1412
+ const url = new URL(jwksUri);
1413
+ const { document } = await hardenedFetch(ctx, url, {
1414
+ subject: "jwks_uri",
1415
+ redirectAdvice: "serve the JWK Set at the jwks_uri URL itself"
1416
+ });
1417
+ if (!document) throw refuse("jwks_uri fetch returned no document");
1418
+ return document;
1419
+ }
1420
+ var SERVER_CIMD_AUTH_METHODS = ["none", "private_key_jwt"];
1421
+ function assertJwksUri(ctx, value) {
1422
+ if (typeof value !== "string" || !value.trim()) {
1423
+ throw refuse("client_id metadata field 'jwks_uri' must be a non-empty string");
1308
1424
  }
1309
1425
  let url;
1310
1426
  try {
1311
1427
  url = new URL(value);
1312
1428
  } catch {
1313
- throw new TypeError(`oauth-host: redirectUri must be an absolute URI: '${value}'`);
1429
+ throw refuse(`client_id metadata field 'jwks_uri' is not a valid URL: '${value}'`);
1314
1430
  }
1315
- const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
1316
- if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
1317
- throw new TypeError(
1318
- `oauth-host: redirectUri must be https (http is allowed only on localhost/127.0.0.1): '${value}'`
1319
- );
1431
+ if (url.protocol !== "https:") {
1432
+ throw refuse(`client_id metadata field 'jwks_uri' must be served over https (got '${url.protocol}')`);
1433
+ }
1434
+ if (url.username || url.password) {
1435
+ throw refuse("client_id metadata field 'jwks_uri' must not contain URL credentials");
1320
1436
  }
1321
1437
  if (url.hash) {
1322
- throw new TypeError(`oauth-host: redirectUri must not contain a fragment: '${value}'`);
1438
+ throw refuse("client_id metadata field 'jwks_uri' must not contain a fragment");
1323
1439
  }
1324
- return value;
1325
- }
1326
- function assertRedirectUris(input) {
1327
- if (!Array.isArray(input) || input.length === 0) {
1328
- throw new TypeError("oauth-host: a client needs at least one redirectUri");
1440
+ if (!hostAllowed(ctx.cimd.allowedHosts, url)) {
1441
+ throw refuse(`client_id metadata field 'jwks_uri' host '${url.host}' is not in clientIdMetadata.allowedHosts`);
1329
1442
  }
1330
- return input.map(assertRedirectUri);
1443
+ return url.href;
1331
1444
  }
1332
- function assertScopes(ctx, input) {
1333
- if (!Array.isArray(input) || input.length === 0) {
1334
- throw new TypeError("oauth-host: a client needs at least one entry in allowedScopes");
1445
+ function assertInlineJwks(value) {
1446
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1447
+ throw refuse("client_id metadata field 'jwks' must be a JSON object");
1335
1448
  }
1336
- for (const id of input) {
1337
- if (typeof id !== "string" || !ctx.scopeIndex.has(id)) {
1338
- throw new TypeError(
1339
- `oauth-host: allowedScopes contains '${String(id)}', which is not in the configured scope catalog`
1340
- );
1449
+ const keys = value.keys;
1450
+ if (!Array.isArray(keys) || keys.length === 0) {
1451
+ throw refuse("client_id metadata field 'jwks' must contain a non-empty 'keys' array");
1452
+ }
1453
+ for (const key of keys) {
1454
+ if (!key || typeof key !== "object" || Array.isArray(key)) {
1455
+ throw refuse("client_id metadata field 'jwks' contains a non-object entry in 'keys'");
1341
1456
  }
1342
1457
  }
1343
- return [...input];
1458
+ return value;
1344
1459
  }
1345
- function assertResources(ctx, input) {
1346
- const declared = new Set(ctx.resources.map((r) => r.id));
1347
- if (input === void 0) return ctx.resources.map((r) => r.id);
1348
- if (!Array.isArray(input) || input.length === 0) {
1349
- throw new TypeError("oauth-host: allowedResources, when given, must list at least one resource");
1350
- }
1351
- for (const id of input) {
1352
- if (typeof id !== "string" || !declared.has(id)) {
1353
- throw new TypeError(
1354
- `oauth-host: allowedResources contains '${String(id)}', which is not a configured resource`
1460
+ function offeredAuthMethods(doc) {
1461
+ const plural = doc.token_endpoint_auth_methods_supported;
1462
+ if (plural !== void 0) {
1463
+ if (!Array.isArray(plural) || plural.length === 0 || !plural.every((entry) => typeof entry === "string" && entry.length > 0)) {
1464
+ throw refuse(
1465
+ "client_id metadata field 'token_endpoint_auth_methods_supported' must be a non-empty array of strings"
1355
1466
  );
1356
1467
  }
1468
+ return [...new Set(plural)];
1357
1469
  }
1358
- return [...input];
1470
+ const singular = doc.token_endpoint_auth_method;
1471
+ if (singular !== void 0) {
1472
+ if (typeof singular !== "string" || !singular) {
1473
+ throw refuse("client_id metadata field 'token_endpoint_auth_method' must be a string");
1474
+ }
1475
+ return [singular];
1476
+ }
1477
+ return ["none"];
1359
1478
  }
1360
- function assertName(value) {
1479
+ function requireString(doc, field) {
1480
+ const value = doc[field];
1361
1481
  if (typeof value !== "string" || !value.trim()) {
1362
- throw new TypeError("oauth-host: a client needs a non-empty `name` \u2014 it is what the consent screen shows");
1482
+ throw refuse(`client_id metadata field '${field}' must be a non-empty string`);
1363
1483
  }
1364
1484
  return value.trim();
1365
1485
  }
1366
- async function revokeGrantsMatching(ctx, filter, by) {
1367
- const res = await ctx.models.Grant.updateMany(
1368
- { ...filter, revokedAt: null },
1369
- { $set: { revokedAt: /* @__PURE__ */ new Date(), revokedBy: by } }
1370
- );
1371
- return { grantsRevoked: res.modifiedCount ?? 0 };
1486
+ function optionalHttpsUri(doc, field) {
1487
+ const value = doc[field];
1488
+ if (value === void 0 || value === null) return void 0;
1489
+ if (typeof value !== "string" || !value.trim()) {
1490
+ throw refuse(`client_id metadata field '${field}' must be a string`);
1491
+ }
1492
+ let url;
1493
+ try {
1494
+ url = new URL(value);
1495
+ } catch {
1496
+ throw refuse(`client_id metadata field '${field}' must be an absolute URL: '${value}'`);
1497
+ }
1498
+ if (url.protocol !== "https:") {
1499
+ throw refuse(`client_id metadata field '${field}' must be https (got '${url.protocol}')`);
1500
+ }
1501
+ return value;
1372
1502
  }
1373
- async function revokeTokensMatching(ctx, filter) {
1374
- const res = await ctx.models.Token.updateMany(
1375
- { ...filter, revokedAt: null },
1376
- { $set: { revokedAt: /* @__PURE__ */ new Date() } }
1377
- );
1378
- return res.modifiedCount ?? 0;
1503
+ function assertRedirectUris(doc) {
1504
+ const value = doc.redirect_uris;
1505
+ if (!Array.isArray(value) || value.length === 0) {
1506
+ throw refuse("client_id metadata field 'redirect_uris' must be a non-empty array");
1507
+ }
1508
+ return value.map((entry) => {
1509
+ if (typeof entry !== "string" || !entry) {
1510
+ throw refuse(`client_id metadata 'redirect_uris' entries must be strings (got ${JSON.stringify(entry)})`);
1511
+ }
1512
+ let url;
1513
+ try {
1514
+ url = new URL(entry);
1515
+ } catch {
1516
+ throw refuse(`client_id metadata 'redirect_uris' entry must be an absolute URI: '${entry}'`);
1517
+ }
1518
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
1519
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
1520
+ throw refuse(
1521
+ `client_id metadata 'redirect_uris' entry must be https (http is allowed only on localhost/127.0.0.1): '${entry}'`
1522
+ );
1523
+ }
1524
+ if (url.hash) {
1525
+ throw refuse(`client_id metadata 'redirect_uris' entry must not contain a fragment: '${entry}'`);
1526
+ }
1527
+ return entry;
1528
+ });
1379
1529
  }
1380
- function createClientsApi(ctx) {
1381
- return {
1382
- async create(spec) {
1383
- if (!spec || typeof spec !== "object") {
1384
- throw new TypeError("oauth-host: clients.create(spec) requires a spec object");
1385
- }
1386
- const name = assertName(spec.name);
1387
- const redirectUris = assertRedirectUris(spec.redirectUris);
1388
- const allowedScopes = assertScopes(ctx, spec.allowedScopes);
1389
- const allowedResources = assertResources(ctx, spec.allowedResources);
1390
- const clientId = spec.clientId ?? generateClientId();
1391
- const clientSecret = generateClientSecret();
1392
- const doc = await ctx.models.Client.create({
1393
- clientId,
1394
- name,
1395
- type: "confidential",
1396
- registration: "manual",
1397
- trusted: Boolean(spec.trusted),
1398
- // Only the digest is stored. `clientSecret` below is the only time the
1399
- // raw value exists outside the caller's variable.
1400
- secrets: [{ hash: sha256(clientSecret), label: "initial", createdAt: /* @__PURE__ */ new Date() }],
1401
- redirectUris,
1402
- allowedScopes,
1403
- allowedResources,
1404
- branding: spec.branding ?? {},
1405
- status: "active"
1406
- });
1407
- await ctx.audit({ type: "oauth.client_created", actor: "admin", clientId });
1408
- return { client: toPublicClient(doc), clientId, clientSecret };
1409
- },
1410
- async rotateSecret(clientId, opts = {}) {
1411
- const doc = await ctx.models.Client.findOne({ clientId });
1412
- if (!doc) throw notFound(clientId);
1413
- if (doc.type === "public") {
1414
- throw new Error(
1415
- `oauth-host: client '${clientId}' is a public client and has no secret to rotate. Public clients authenticate with client_id and PKCE.`
1416
- );
1417
- }
1418
- const retireAfter = typeof opts.retireAfter === "number" && opts.retireAfter > 0 ? opts.retireAfter : 0;
1419
- const retiresAt = new Date(Date.now() + retireAfter);
1420
- for (const record of doc.secrets) {
1421
- record.retiresAt = record.retiresAt && record.retiresAt < retiresAt ? record.retiresAt : retiresAt;
1422
- }
1423
- const clientSecret = generateClientSecret();
1424
- doc.secrets.push({
1425
- hash: sha256(clientSecret),
1426
- label: opts.label ?? `rotated-${(/* @__PURE__ */ new Date()).toISOString()}`,
1427
- createdAt: /* @__PURE__ */ new Date()
1428
- });
1429
- doc.markModified("secrets");
1430
- await doc.save();
1431
- ctx.track({ type: "oauth.client_secret_rotated", clientId });
1432
- await ctx.audit({
1433
- type: "oauth.client_secret_rotated",
1434
- actor: "admin",
1435
- clientId,
1436
- meta: { retireAfter, retiresAt }
1437
- });
1438
- return { client: toPublicClient(doc), clientId, clientSecret };
1439
- },
1440
- async update(clientId, patch) {
1441
- const doc = await ctx.models.Client.findOne({ clientId });
1442
- if (!doc) throw notFound(clientId);
1443
- if (patch.name !== void 0) doc.name = assertName(patch.name);
1444
- if (patch.redirectUris !== void 0) doc.redirectUris = assertRedirectUris(patch.redirectUris);
1445
- if (patch.allowedScopes !== void 0) doc.allowedScopes = assertScopes(ctx, patch.allowedScopes);
1446
- if (patch.allowedResources !== void 0) {
1447
- doc.allowedResources = assertResources(ctx, patch.allowedResources);
1448
- }
1449
- if (patch.branding !== void 0) doc.branding = patch.branding;
1450
- if (patch.trusted !== void 0) doc.trusted = Boolean(patch.trusted);
1451
- await doc.save();
1452
- await ctx.audit({ type: "oauth.client_updated", actor: "admin", clientId });
1453
- return toPublicClient(doc);
1454
- },
1455
- async list(query = {}) {
1456
- const limit = clampLimit(query.limit);
1457
- const skip = clampSkip(query.skip);
1458
- const filter = {};
1459
- if (query.status) filter.status = query.status;
1460
- const docs = await ctx.models.Client.find(filter).sort({ createdAt: -1 }).skip(skip).limit(limit).lean();
1461
- return { items: docs.map(toPublicClient), limit };
1462
- },
1463
- async get(clientId) {
1464
- const doc = await ctx.models.Client.findOne({ clientId }).lean();
1465
- return doc ? toPublicClient(doc) : null;
1466
- },
1467
- async disable(clientId) {
1468
- const doc = await ctx.models.Client.findOne({ clientId });
1469
- if (!doc) throw notFound(clientId);
1470
- doc.status = "disabled";
1471
- await doc.save();
1472
- const { grantsRevoked } = await revokeGrantsMatching(ctx, { clientId }, "admin");
1473
- const tokensRevoked = await revokeTokensMatching(ctx, { clientId });
1474
- await ctx.models.Code.deleteMany({ clientId });
1475
- await ctx.models.Request.deleteMany({ clientId });
1476
- await ctx.audit({
1477
- type: "oauth.client_disabled",
1478
- actor: "admin",
1479
- clientId,
1480
- meta: { grantsRevoked, tokensRevoked }
1481
- });
1482
- return { grantsRevoked, tokensRevoked };
1483
- }
1484
- };
1485
- }
1486
- function formUrlDecode(value) {
1530
+ function validateMetadataDocument(ctx, url, doc) {
1531
+ const declared = requireString(doc, "client_id");
1532
+ let declaredUrl;
1487
1533
  try {
1488
- return decodeURIComponent(value.replace(/\+/g, " "));
1534
+ declaredUrl = new URL(declared);
1489
1535
  } catch {
1490
- return value;
1536
+ throw refuse(`client_id metadata field 'client_id' is not a URL: '${declared}'`);
1491
1537
  }
1492
- }
1493
- function readCredentials(req) {
1494
- const header = req.headers?.authorization;
1495
- if (typeof header === "string" && /^Basic /i.test(header)) {
1496
- const decoded = Buffer.from(header.slice(6).trim(), "base64").toString("utf8");
1497
- const sep = decoded.indexOf(":");
1498
- const clientId = formUrlDecode(sep < 0 ? decoded : decoded.slice(0, sep));
1499
- const secret = sep < 0 ? "" : formUrlDecode(decoded.slice(sep + 1));
1500
- return { clientId, clientSecret: secret === "" ? null : secret, viaBasic: true };
1538
+ if (declaredUrl.href !== url.href) {
1539
+ throw refuse(
1540
+ `client_id metadata field 'client_id' is '${declared}', which is not the URL it was fetched from ('${url.href}')`
1541
+ );
1501
1542
  }
1502
- const body = req.body ?? {};
1503
- if (typeof body.client_id === "string" && body.client_id) {
1504
- return {
1505
- clientId: body.client_id,
1506
- clientSecret: typeof body.client_secret === "string" && body.client_secret ? body.client_secret : null,
1507
- viaBasic: false
1508
- };
1543
+ const offered = offeredAuthMethods(doc);
1544
+ let usableMethods = offered.filter((m) => SERVER_CIMD_AUTH_METHODS.includes(m));
1545
+ if (usableMethods.length === 0) {
1546
+ throw refuse(
1547
+ `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`
1548
+ );
1509
1549
  }
1510
- return null;
1511
- }
1512
- function authFailure(viaBasic) {
1513
- return new OAuthError(401, "invalid_client", "client authentication failed", {
1514
- // RFC 6749 §5.2 a 401 answering a Basic credential MUST carry the challenge.
1515
- headers: viaBasic ? { "WWW-Authenticate": 'Basic realm="oauth", charset="UTF-8"' } : {}
1516
- });
1550
+ let jwksUri;
1551
+ let jwks;
1552
+ if (usableMethods.includes("private_key_jwt")) {
1553
+ const hasJwksUri = doc.jwks_uri !== void 0 && doc.jwks_uri !== null;
1554
+ const hasJwks = doc.jwks !== void 0 && doc.jwks !== null;
1555
+ if (hasJwksUri && hasJwks) {
1556
+ throw refuse("client_id metadata must not contain both 'jwks' and 'jwks_uri'");
1557
+ }
1558
+ if (hasJwksUri) {
1559
+ jwksUri = assertJwksUri(ctx, doc.jwks_uri);
1560
+ } else if (hasJwks) {
1561
+ jwks = assertInlineJwks(doc.jwks);
1562
+ } else if (usableMethods.includes("none")) {
1563
+ usableMethods = usableMethods.filter((m) => m !== "private_key_jwt");
1564
+ } else {
1565
+ throw refuse("client_id metadata offers private_key_jwt but carries no 'jwks' or 'jwks_uri'");
1566
+ }
1567
+ }
1568
+ const name = requireString(doc, "client_name");
1569
+ const redirectUris = assertRedirectUris(doc);
1570
+ const permitted = new Set(ctx.cimd.allowedScopes.filter((id) => ctx.scopeIndex.has(id)));
1571
+ let allowedScopes;
1572
+ if (doc.scope === void 0 || doc.scope === null) {
1573
+ allowedScopes = [...permitted];
1574
+ } else {
1575
+ if (typeof doc.scope !== "string") {
1576
+ throw refuse("client_id metadata field 'scope' must be a space-delimited string");
1577
+ }
1578
+ const requested = new Set(doc.scope.split(/\s+/).filter(Boolean));
1579
+ allowedScopes = [...permitted].filter((id) => requested.has(id));
1580
+ }
1581
+ if (allowedScopes.length === 0) {
1582
+ throw refuse(
1583
+ "client_id metadata field 'scope' has no overlap with what this server offers \u2014 there is nothing this client could be granted"
1584
+ );
1585
+ }
1586
+ const branding = {};
1587
+ const logoUrl = optionalHttpsUri(doc, "logo_uri");
1588
+ const homepageUrl = optionalHttpsUri(doc, "client_uri");
1589
+ const tosUrl = optionalHttpsUri(doc, "tos_uri");
1590
+ const privacyUrl = optionalHttpsUri(doc, "policy_uri");
1591
+ if (logoUrl) branding.logoUrl = logoUrl;
1592
+ if (homepageUrl) branding.homepageUrl = homepageUrl;
1593
+ if (tosUrl) branding.tosUrl = tosUrl;
1594
+ if (privacyUrl) branding.privacyUrl = privacyUrl;
1595
+ return {
1596
+ name,
1597
+ redirectUris,
1598
+ allowedScopes,
1599
+ branding,
1600
+ usableMethods,
1601
+ ...jwksUri ? { jwksUri } : {},
1602
+ ...jwks ? { jwks } : {}
1603
+ };
1517
1604
  }
1518
- async function authenticateClient(ctx, req) {
1519
- const creds = readCredentials(req);
1520
- if (!creds || !creds.clientId) throw authFailure(Boolean(creds?.viaBasic));
1521
- const client = await ctx.models.Client.findOne({ clientId: creds.clientId });
1522
- if (!client || client.status !== "active") throw authFailure(creds.viaBasic);
1523
- if (client.type === "public") {
1524
- if (creds.clientSecret !== null) throw authFailure(creds.viaBasic);
1525
- return client;
1605
+ function rememberFailure(ctx, key, message) {
1606
+ const { failures } = ctx.cimd;
1607
+ if (failures.size >= MAX_REMEMBERED_FAILURES) {
1608
+ const oldest = failures.keys().next();
1609
+ if (!oldest.done) failures.delete(oldest.value);
1526
1610
  }
1527
- if (creds.clientSecret === null) throw authFailure(creds.viaBasic);
1528
- const now = Date.now();
1529
- let matched;
1530
- for (const record of client.secrets) {
1531
- if (record.retiresAt && record.retiresAt.getTime() <= now) continue;
1532
- if (safeEqual(sha256(creds.clientSecret), record.hash)) matched = record;
1611
+ failures.set(key, { until: Date.now() + NEGATIVE_TTL_MS, message });
1612
+ }
1613
+ function rememberedFailure(ctx, key) {
1614
+ const found = ctx.cimd.failures.get(key);
1615
+ if (!found) return null;
1616
+ if (found.until <= Date.now()) {
1617
+ ctx.cimd.failures.delete(key);
1618
+ return null;
1533
1619
  }
1534
- if (!matched) throw authFailure(creds.viaBasic);
1535
- const usedAt = /* @__PURE__ */ new Date();
1536
- matched.lastUsedAt = usedAt;
1537
- await ctx.models.Client.updateOne(
1538
- { clientId: client.clientId, "secrets.hash": matched.hash },
1539
- { $set: { "secrets.$.lastUsedAt": usedAt } }
1540
- );
1541
- return client;
1620
+ return found.message;
1542
1621
  }
1543
- function describeGrantScopes(ctx, ids) {
1544
- return ids.map((id) => ctx.scopeIndex.get(id) ?? { id, label: id });
1622
+ function isFresh(ctx, client) {
1623
+ const fetchedAt = client.metadataFetchedAt?.getTime();
1624
+ if (fetchedAt === void 0) return false;
1625
+ return Date.now() - fetchedAt < ctx.cimd.cacheTtlMs;
1545
1626
  }
1546
- function createGrantsApi(ctx) {
1547
- return {
1548
- async list(query) {
1549
- const limit = clampLimit(query?.limit);
1550
- const skip = clampSkip(query?.skip);
1551
- const filter = { revokedAt: null };
1552
- if (query?.userId !== void 0) filter.userId = query.userId;
1553
- if (query?.clientId !== void 0) filter.clientId = query.clientId;
1554
- const grants = await ctx.models.Grant.find(filter).sort({ createdAt: -1 }).skip(skip).limit(limit).lean();
1555
- if (grants.length === 0) return { items: [], limit };
1556
- const clientIds = [...new Set(grants.map((g) => g.clientId))];
1557
- const clients = await ctx.models.Client.find({ clientId: { $in: clientIds } }).lean();
1558
- const byId = new Map(clients.map((c) => [c.clientId, toPublicClient(c)]));
1559
- const contextCache = /* @__PURE__ */ new Map();
1560
- const items = [];
1561
- for (const grant of grants) {
1562
- const client = byId.get(grant.clientId);
1563
- const summary = {
1564
- id: String(grant._id),
1565
- client: client ? { clientId: client.clientId, name: client.name, branding: client.branding } : { clientId: grant.clientId, name: grant.clientId, branding: {} },
1566
- scopes: describeGrantScopes(ctx, grant.scopes ?? []),
1567
- createdAt: grant.createdAt,
1568
- ...grant.lastUsedAt ? { lastUsedAt: grant.lastUsedAt } : {}
1569
- };
1570
- if (ctx.grantContext && grant.contextId) {
1571
- const cacheKey = `${String(grant.userId)}:${grant.clientId}`;
1572
- let available = contextCache.get(cacheKey);
1573
- if (!available) {
1574
- const user = { id: grant.userId };
1575
- available = client ? await ctx.grantContext.list(user, { client, scopes: grant.scopes ?? [] }) : [];
1576
- contextCache.set(cacheKey, available);
1577
- }
1578
- summary.context = available.find((c) => c.id === grant.contextId) ?? { id: grant.contextId, label: grant.contextId };
1579
- }
1580
- items.push(summary);
1627
+ async function persist(ctx, clientId, url, registration, etag) {
1628
+ const unset = {};
1629
+ const jwksFields = {};
1630
+ if (registration.jwksUri) jwksFields.jwksUri = registration.jwksUri;
1631
+ else unset.jwksUri = "";
1632
+ if (registration.jwks) jwksFields.jwks = registration.jwks;
1633
+ else unset.jwks = "";
1634
+ const doc = await ctx.models.Client.findOneAndUpdate(
1635
+ { clientId },
1636
+ {
1637
+ $set: {
1638
+ name: registration.name,
1639
+ redirectUris: registration.redirectUris,
1640
+ allowedScopes: registration.allowedScopes,
1641
+ // Every declared resource. A CIMD client cannot express an audience
1642
+ // preference, and RFC 8707 validation at `/authorize` narrows it anyway.
1643
+ allowedResources: ctx.resources.map((r) => r.id),
1644
+ branding: registration.branding,
1645
+ metadataUrl: url.href,
1646
+ metadataFetchedAt: /* @__PURE__ */ new Date(),
1647
+ tokenEndpointAuthMethods: registration.usableMethods,
1648
+ ...jwksFields,
1649
+ ...etag ? { metadataEtag: etag } : {}
1650
+ },
1651
+ ...Object.keys(unset).length ? { $unset: unset } : {},
1652
+ $setOnInsert: {
1653
+ type: "public",
1654
+ registration: "cimd",
1655
+ trusted: false,
1656
+ secrets: [],
1657
+ status: "active"
1581
1658
  }
1582
- return { items, limit };
1583
1659
  },
1584
- async revoke(grantId, opts = {}) {
1585
- const by = opts.by ?? "admin";
1586
- const grant = await ctx.models.Grant.findById(grantId).catch(() => null);
1587
- if (!grant) return { tokensRevoked: 0 };
1588
- const alreadyRevoked = Boolean(grant.revokedAt);
1589
- if (!alreadyRevoked) {
1590
- grant.revokedAt = /* @__PURE__ */ new Date();
1591
- grant.revokedBy = by;
1592
- await grant.save();
1593
- }
1594
- const tokensRevoked = await revokeTokensMatching(ctx, { grantId: grant._id });
1595
- if (!alreadyRevoked) {
1596
- ctx.track({
1597
- type: "oauth.grant_revoked",
1598
- userId: grant.userId,
1599
- clientId: grant.clientId,
1600
- grantId: String(grant._id),
1601
- ...grant.contextId ? { contextId: grant.contextId } : {},
1602
- scopes: grant.scopes
1603
- });
1604
- await ctx.audit({
1605
- type: "oauth.grant_revoked",
1606
- actor: by,
1607
- clientId: grant.clientId,
1608
- userId: grant.userId,
1609
- grantId: grant._id,
1610
- meta: { tokensRevoked }
1611
- });
1612
- }
1613
- return { tokensRevoked };
1614
- }
1615
- };
1660
+ { upsert: true, returnDocument: "after", setDefaultsOnInsert: false }
1661
+ ).exec();
1662
+ return doc;
1616
1663
  }
1617
- function pairwiseKey(userId) {
1618
- const key = String(userId);
1619
- if (!key || key.includes(".") || key.startsWith("$")) return null;
1620
- return key;
1621
- }
1622
- function createUsersApi(ctx) {
1623
- return {
1624
- /**
1625
- * Erasure. The user is gone and every trace of them has to go with them.
1626
- *
1627
- * This is the destructive twin of `revokeAll`, and the difference is the
1628
- * whole reason both exist: `forget` DELETES the grant documents and the
1629
- * user's audit rows, `revokeAll` keeps both. A password change must leave a
1630
- * history an operator can read; a deletion request must not.
1631
- *
1632
- * Idempotent — it will be called twice, by a retry or by a host that wires
1633
- * it to both a soft-delete and a hard-delete hook.
1634
- */
1635
- async forget(userId) {
1636
- const grantsResult = await ctx.models.Grant.deleteMany({ userId });
1637
- const tokensResult = await ctx.models.Token.deleteMany({ userId });
1638
- await ctx.models.Code.deleteMany({ userId });
1639
- await ctx.models.Request.deleteMany({ userId });
1640
- const key = pairwiseKey(userId);
1641
- if (key) {
1642
- await ctx.models.Client.updateMany(
1643
- { [`pairwiseSubjects.${key}`]: { $exists: true } },
1644
- { $unset: { [`pairwiseSubjects.${key}`]: "" } }
1645
- );
1646
- }
1647
- await ctx.models.Audit.deleteMany({ userId });
1648
- const grants = grantsResult.deletedCount ?? 0;
1649
- const tokens = tokensResult.deletedCount ?? 0;
1650
- await ctx.audit({ type: "oauth.user_forgotten", actor: "system", meta: { grants, tokens } });
1651
- return { grants, tokens };
1652
- },
1653
- /**
1654
- * Password change, deactivation, suspected compromise.
1655
- *
1656
- * Kills live access and KEEPS everything else: the grant documents stay so
1657
- * the audit trail still resolves and so the user's connected apps remain
1658
- * visible, and the audit rows stay because that is the record the operator
1659
- * called this to create. See `forget` above for the destructive twin.
1660
- */
1661
- async revokeAll(userId, opts = {}) {
1662
- const live = await ctx.models.Grant.find({ userId, revokedAt: null }).limit(MAX_LIST).lean();
1663
- const { grantsRevoked } = await revokeGrantsMatching(ctx, { userId }, "system");
1664
- const tokensRevoked = await revokeTokensMatching(ctx, { userId });
1665
- await ctx.models.Code.deleteMany({ userId });
1666
- await ctx.models.Request.deleteMany({ userId });
1667
- for (const grant of live) {
1668
- ctx.track({
1669
- type: "oauth.grant_revoked",
1670
- userId,
1671
- clientId: grant.clientId,
1672
- grantId: String(grant._id),
1673
- ...grant.contextId ? { contextId: grant.contextId } : {},
1674
- scopes: grant.scopes
1675
- });
1676
- }
1677
- await ctx.audit({
1678
- type: "oauth.user_access_revoked",
1679
- actor: "system",
1680
- userId,
1681
- meta: { grantsRevoked, tokensRevoked, ...opts.reason ? { reason: opts.reason } : {} }
1682
- });
1683
- return { grantsRevoked, tokensRevoked };
1664
+ async function resolveCimdClient(ctx, clientId) {
1665
+ const url = assertFetchableUrl(ctx, clientId);
1666
+ const existing = await ctx.models.Client.findOne({ clientId }).exec();
1667
+ if (existing) {
1668
+ if (existing.status !== "active") {
1669
+ throw refuse(`client '${clientId}' is disabled`);
1684
1670
  }
1685
- };
1686
- }
1687
- function createContextsApi(ctx) {
1688
- return {
1689
- /**
1690
- * A grant made as an employee has to die when the employment does.
1691
- *
1692
- * `grantContext.verify()` catches this on the next refresh, but an access
1693
- * token already issued is valid for its full hour and nothing re-checks it.
1694
- * This is the push half of that pair, and it is why the adapter has an
1695
- * outbound direction at all.
1696
- */
1697
- async revoked(userId, contextId) {
1698
- const live = await ctx.models.Grant.find({ userId, contextId, revokedAt: null }).limit(MAX_LIST).lean();
1699
- const { grantsRevoked } = await revokeGrantsMatching(ctx, { userId, contextId }, "system");
1700
- const tokensRevoked = await revokeTokensMatching(ctx, { userId, contextId });
1701
- await ctx.models.Code.deleteMany({ userId, contextId });
1702
- for (const grant of live) {
1703
- ctx.track({
1704
- type: "oauth.grant_revoked",
1705
- userId,
1706
- clientId: grant.clientId,
1707
- grantId: String(grant._id),
1708
- contextId,
1709
- scopes: grant.scopes
1710
- });
1711
- await ctx.audit({
1712
- type: "oauth.grant_revoked",
1713
- actor: "system",
1714
- clientId: grant.clientId,
1715
- userId,
1716
- grantId: grant._id,
1717
- meta: { contextId, reason: "context_membership_ended" }
1718
- });
1671
+ if (existing.registration !== "cimd") return existing;
1672
+ if (isFresh(ctx, existing)) return existing;
1673
+ }
1674
+ const remembered = rememberedFailure(ctx, url.href);
1675
+ if (remembered) throw refuse(remembered);
1676
+ try {
1677
+ const { document, etag } = await fetchMetadata(ctx, url, existing?.metadataEtag);
1678
+ if (!document) {
1679
+ if (existing) {
1680
+ existing.metadataFetchedAt = /* @__PURE__ */ new Date();
1681
+ await existing.save();
1682
+ return existing;
1719
1683
  }
1720
- return { grantsRevoked, tokensRevoked };
1684
+ throw refuse("client_id metadata returned 304 with nothing cached to answer from");
1721
1685
  }
1722
- };
1686
+ const registration = validateMetadataDocument(ctx, url, document);
1687
+ const client = await persist(ctx, clientId, url, registration, etag);
1688
+ ctx.logger.debug?.({ clientId }, "oauth-host: client_id metadata document resolved");
1689
+ return client;
1690
+ } catch (err) {
1691
+ const message = err instanceof UnredirectableError ? err.description ?? "client_id metadata could not be resolved" : "client_id metadata could not be resolved";
1692
+ rememberFailure(ctx, url.href, message);
1693
+ ctx.logger.warn?.({ clientId, err }, "oauth-host: client_id metadata resolution failed");
1694
+ throw err instanceof UnredirectableError ? err : refuse(message);
1695
+ }
1723
1696
  }
1724
1697
 
1725
- // src/server/services/cimd.ts
1726
- var NEGATIVE_TTL_MS = 6e4;
1727
- var MAX_REMEMBERED_FAILURES = 1e3;
1728
- function refuse(description) {
1729
- return new UnredirectableError("invalid_client", description);
1698
+ // src/server/services/admin.ts
1699
+ var MAX_LIST = 200;
1700
+ var DEFAULT_LIST = 50;
1701
+ function clampLimit(requested) {
1702
+ const n = typeof requested === "number" && Number.isFinite(requested) ? Math.floor(requested) : DEFAULT_LIST;
1703
+ if (n < 1) return 1;
1704
+ return Math.min(n, MAX_LIST);
1730
1705
  }
1731
- function isMetadataUrl(clientId) {
1732
- return /^https:\/\//i.test(clientId);
1706
+ function clampSkip(requested) {
1707
+ const n = typeof requested === "number" && Number.isFinite(requested) ? Math.floor(requested) : 0;
1708
+ return n > 0 ? n : 0;
1733
1709
  }
1734
- function hostAllowed(rules, url) {
1735
- const hostname = url.hostname.toLowerCase();
1736
- return rules.some((rule) => {
1737
- if (url.port !== rule.port) return false;
1738
- if (hostname === rule.host) return true;
1739
- return rule.subdomains && hostname.endsWith(`.${rule.host}`);
1740
- });
1710
+ function notFound(clientId) {
1711
+ return new Error(`oauth-host: no client registered with clientId '${clientId}'`);
1741
1712
  }
1742
- function assertFetchableUrl(ctx, clientId) {
1713
+ function toPublicClient(doc) {
1714
+ return {
1715
+ clientId: doc.clientId,
1716
+ name: doc.name,
1717
+ type: doc.type,
1718
+ // Defaulted rather than read straight through: rows written before the
1719
+ // field existed have no value, and `undefined` here would read as "unknown
1720
+ // provenance" on a client that plainly was registered by hand.
1721
+ registration: doc.registration ?? "manual",
1722
+ ...doc.metadataUrl ? { metadataUrl: doc.metadataUrl } : {},
1723
+ trusted: Boolean(doc.trusted),
1724
+ redirectUris: [...doc.redirectUris ?? []],
1725
+ allowedScopes: [...doc.allowedScopes ?? []],
1726
+ allowedResources: [...doc.allowedResources ?? []],
1727
+ branding: { ...doc.branding ?? {} },
1728
+ status: doc.status,
1729
+ createdAt: doc.createdAt
1730
+ };
1731
+ }
1732
+ function assertRedirectUri(value) {
1733
+ if (typeof value !== "string" || !value) {
1734
+ throw new TypeError(`oauth-host: every redirectUri must be a string (got ${JSON.stringify(value)})`);
1735
+ }
1743
1736
  let url;
1744
1737
  try {
1745
- url = new URL(clientId);
1738
+ url = new URL(value);
1746
1739
  } catch {
1747
- throw refuse(`client_id is not a valid URL: '${clientId}'`);
1748
- }
1749
- if (url.protocol !== "https:") {
1750
- throw refuse(`client_id metadata must be served over https (got '${url.protocol}')`);
1740
+ throw new TypeError(`oauth-host: redirectUri must be an absolute URI: '${value}'`);
1751
1741
  }
1752
- if (url.username || url.password) {
1753
- throw refuse("client_id must not contain URL credentials");
1742
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
1743
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
1744
+ throw new TypeError(
1745
+ `oauth-host: redirectUri must be https (http is allowed only on localhost/127.0.0.1): '${value}'`
1746
+ );
1754
1747
  }
1755
1748
  if (url.hash) {
1756
- throw refuse("client_id must not contain a fragment");
1749
+ throw new TypeError(`oauth-host: redirectUri must not contain a fragment: '${value}'`);
1757
1750
  }
1758
- if (!hostAllowed(ctx.cimd.allowedHosts, url)) {
1759
- throw refuse(`client_id host '${url.host}' is not in clientIdMetadata.allowedHosts`);
1751
+ return value;
1752
+ }
1753
+ function assertRedirectUris2(input) {
1754
+ if (!Array.isArray(input) || input.length === 0) {
1755
+ throw new TypeError("oauth-host: a client needs at least one redirectUri");
1760
1756
  }
1761
- return url;
1757
+ return input.map(assertRedirectUri);
1762
1758
  }
1763
- var JSON_CONTENT_TYPE = /^application\/(?:[\w.+-]+\+)?json\s*(?:;|$)/i;
1764
- async function readCapped(res, maxBytes) {
1765
- const body = res.body;
1766
- if (!body) throw refuse("client_id metadata document was empty");
1767
- const reader = body.getReader();
1768
- const chunks = [];
1769
- let total = 0;
1770
- for (; ; ) {
1771
- const { done, value } = await reader.read();
1772
- if (done) break;
1773
- if (!value) continue;
1774
- total += value.byteLength;
1775
- if (total > maxBytes) {
1776
- void reader.cancel();
1777
- throw refuse(`client_id metadata document exceeds ${maxBytes} bytes`);
1759
+ function assertScopes(ctx, input) {
1760
+ if (!Array.isArray(input) || input.length === 0) {
1761
+ throw new TypeError("oauth-host: a client needs at least one entry in allowedScopes");
1762
+ }
1763
+ for (const id of input) {
1764
+ if (typeof id !== "string" || !ctx.scopeIndex.has(id)) {
1765
+ throw new TypeError(
1766
+ `oauth-host: allowedScopes contains '${String(id)}', which is not in the configured scope catalog`
1767
+ );
1778
1768
  }
1779
- chunks.push(Buffer.from(value));
1780
1769
  }
1781
- return Buffer.concat(chunks).toString("utf8");
1770
+ return [...input];
1782
1771
  }
1783
- async function fetchMetadata(ctx, url, etag) {
1784
- let res;
1785
- try {
1786
- res = await fetch(url.toString(), {
1787
- method: "GET",
1788
- // The single most important line in this file. A 3xx is a failure below,
1789
- // not a hop: following redirects would let an allowlisted host forward us
1790
- // to any address it likes, allowlist intact.
1791
- redirect: "manual",
1792
- headers: {
1793
- accept: "application/json",
1794
- ...etag ? { "if-none-match": etag } : {}
1795
- },
1796
- signal: AbortSignal.timeout(ctx.cimd.fetchTimeoutMs)
1797
- });
1798
- } catch (err) {
1799
- const name = err?.name;
1800
- if (name === "TimeoutError" || name === "AbortError") {
1801
- throw refuse(`client_id metadata fetch timed out after ${ctx.cimd.fetchTimeoutMs}ms`);
1772
+ function assertResources(ctx, input) {
1773
+ const declared = new Set(ctx.resources.map((r) => r.id));
1774
+ if (input === void 0) return ctx.resources.map((r) => r.id);
1775
+ if (!Array.isArray(input) || input.length === 0) {
1776
+ throw new TypeError("oauth-host: allowedResources, when given, must list at least one resource");
1777
+ }
1778
+ for (const id of input) {
1779
+ if (typeof id !== "string" || !declared.has(id)) {
1780
+ throw new TypeError(
1781
+ `oauth-host: allowedResources contains '${String(id)}', which is not a configured resource`
1782
+ );
1802
1783
  }
1803
- throw refuse(`client_id metadata could not be fetched: ${err?.message ?? "network error"}`);
1804
1784
  }
1805
- if (res.status === 304) return { document: null };
1806
- if (res.status >= 300 && res.status < 400) {
1807
- throw refuse(
1808
- `client_id metadata returned a ${res.status} redirect, which is not followed \u2014 serve the document at the client_id URL itself`
1785
+ return [...input];
1786
+ }
1787
+ function assertClientType(value) {
1788
+ if (value === void 0) return "confidential";
1789
+ if (value !== "confidential" && value !== "public") {
1790
+ throw new TypeError(
1791
+ `oauth-host: client type must be 'confidential' or 'public' (got ${JSON.stringify(value)})`
1809
1792
  );
1810
1793
  }
1811
- if (res.status !== 200) {
1812
- throw refuse(`client_id metadata returned HTTP ${res.status}`);
1794
+ return value;
1795
+ }
1796
+ function assertName(value) {
1797
+ if (typeof value !== "string" || !value.trim()) {
1798
+ throw new TypeError("oauth-host: a client needs a non-empty `name` \u2014 it is what the consent screen shows");
1813
1799
  }
1814
- const contentType = res.headers.get("content-type") ?? "";
1815
- if (!JSON_CONTENT_TYPE.test(contentType)) {
1816
- throw refuse(`client_id metadata must be JSON (got content-type '${contentType || "none"}')`);
1800
+ return value.trim();
1801
+ }
1802
+ async function revokeGrantsMatching(ctx, filter, by) {
1803
+ const res = await ctx.models.Grant.updateMany(
1804
+ { ...filter, revokedAt: null },
1805
+ { $set: { revokedAt: /* @__PURE__ */ new Date(), revokedBy: by } }
1806
+ );
1807
+ return { grantsRevoked: res.modifiedCount ?? 0 };
1808
+ }
1809
+ async function revokeTokensMatching(ctx, filter) {
1810
+ const res = await ctx.models.Token.updateMany(
1811
+ { ...filter, revokedAt: null },
1812
+ { $set: { revokedAt: /* @__PURE__ */ new Date() } }
1813
+ );
1814
+ return res.modifiedCount ?? 0;
1815
+ }
1816
+ function createClientsApi(ctx) {
1817
+ async function create(spec) {
1818
+ if (!spec || typeof spec !== "object") {
1819
+ throw new TypeError("oauth-host: clients.create(spec) requires a spec object");
1820
+ }
1821
+ const name = assertName(spec.name);
1822
+ const type = assertClientType(spec.type);
1823
+ const redirectUris = assertRedirectUris2(spec.redirectUris);
1824
+ const allowedScopes = assertScopes(ctx, spec.allowedScopes);
1825
+ const allowedResources = assertResources(ctx, spec.allowedResources);
1826
+ const clientId = spec.clientId ?? generateClientId();
1827
+ const clientSecret = type === "confidential" ? generateClientSecret() : void 0;
1828
+ const doc = await ctx.models.Client.create({
1829
+ clientId,
1830
+ name,
1831
+ type,
1832
+ registration: "manual",
1833
+ trusted: Boolean(spec.trusted),
1834
+ // Only the digest is stored. `clientSecret` below is the only time the
1835
+ // raw value exists outside the caller's variable. Empty for a public
1836
+ // client, which is the same shape a CIMD row is written with.
1837
+ secrets: clientSecret ? [{ hash: sha256(clientSecret), label: "initial", createdAt: /* @__PURE__ */ new Date() }] : [],
1838
+ redirectUris,
1839
+ allowedScopes,
1840
+ allowedResources,
1841
+ branding: spec.branding ?? {},
1842
+ status: "active"
1843
+ });
1844
+ await ctx.audit({ type: "oauth.client_created", actor: "admin", clientId, meta: { type } });
1845
+ return clientSecret ? { client: toPublicClient(doc), clientId, type: "confidential", clientSecret } : { client: toPublicClient(doc), clientId, type: "public" };
1817
1846
  }
1818
- const text = await readCapped(res, ctx.cimd.maxBytes);
1819
- let parsed;
1847
+ return {
1848
+ create,
1849
+ async rotateSecret(clientId, opts = {}) {
1850
+ const doc = await ctx.models.Client.findOne({ clientId });
1851
+ if (!doc) throw notFound(clientId);
1852
+ if (doc.type === "public") {
1853
+ throw new Error(
1854
+ `oauth-host: client '${clientId}' is a public client and has no secret to rotate. Public clients authenticate with client_id and PKCE.`
1855
+ );
1856
+ }
1857
+ const retireAfter = typeof opts.retireAfter === "number" && opts.retireAfter > 0 ? opts.retireAfter : 0;
1858
+ const retiresAt = new Date(Date.now() + retireAfter);
1859
+ for (const record of doc.secrets) {
1860
+ record.retiresAt = record.retiresAt && record.retiresAt < retiresAt ? record.retiresAt : retiresAt;
1861
+ }
1862
+ const clientSecret = generateClientSecret();
1863
+ doc.secrets.push({
1864
+ hash: sha256(clientSecret),
1865
+ label: opts.label ?? `rotated-${(/* @__PURE__ */ new Date()).toISOString()}`,
1866
+ createdAt: /* @__PURE__ */ new Date()
1867
+ });
1868
+ doc.markModified("secrets");
1869
+ await doc.save();
1870
+ ctx.track({ type: "oauth.client_secret_rotated", clientId });
1871
+ await ctx.audit({
1872
+ type: "oauth.client_secret_rotated",
1873
+ actor: "admin",
1874
+ clientId,
1875
+ meta: { retireAfter, retiresAt }
1876
+ });
1877
+ return { client: toPublicClient(doc), clientId, type: "confidential", clientSecret };
1878
+ },
1879
+ async update(clientId, patch) {
1880
+ const doc = await ctx.models.Client.findOne({ clientId });
1881
+ if (!doc) throw notFound(clientId);
1882
+ if (patch.name !== void 0) doc.name = assertName(patch.name);
1883
+ if (patch.redirectUris !== void 0) doc.redirectUris = assertRedirectUris2(patch.redirectUris);
1884
+ if (patch.allowedScopes !== void 0) doc.allowedScopes = assertScopes(ctx, patch.allowedScopes);
1885
+ if (patch.allowedResources !== void 0) {
1886
+ doc.allowedResources = assertResources(ctx, patch.allowedResources);
1887
+ }
1888
+ if (patch.branding !== void 0) doc.branding = patch.branding;
1889
+ if (patch.trusted !== void 0) doc.trusted = Boolean(patch.trusted);
1890
+ await doc.save();
1891
+ await ctx.audit({ type: "oauth.client_updated", actor: "admin", clientId });
1892
+ return toPublicClient(doc);
1893
+ },
1894
+ async list(query = {}) {
1895
+ const limit = clampLimit(query.limit);
1896
+ const skip = clampSkip(query.skip);
1897
+ const filter = {};
1898
+ if (query.status) filter.status = query.status;
1899
+ const docs = await ctx.models.Client.find(filter).sort({ createdAt: -1 }).skip(skip).limit(limit).lean();
1900
+ return { items: docs.map(toPublicClient), limit };
1901
+ },
1902
+ async get(clientId) {
1903
+ const doc = await ctx.models.Client.findOne({ clientId }).lean();
1904
+ return doc ? toPublicClient(doc) : null;
1905
+ },
1906
+ async disable(clientId) {
1907
+ const doc = await ctx.models.Client.findOne({ clientId });
1908
+ if (!doc) throw notFound(clientId);
1909
+ doc.status = "disabled";
1910
+ await doc.save();
1911
+ const { grantsRevoked } = await revokeGrantsMatching(ctx, { clientId }, "admin");
1912
+ const tokensRevoked = await revokeTokensMatching(ctx, { clientId });
1913
+ await ctx.models.Code.deleteMany({ clientId });
1914
+ await ctx.models.Request.deleteMany({ clientId });
1915
+ await ctx.audit({
1916
+ type: "oauth.client_disabled",
1917
+ actor: "admin",
1918
+ clientId,
1919
+ meta: { grantsRevoked, tokensRevoked }
1920
+ });
1921
+ return { grantsRevoked, tokensRevoked };
1922
+ }
1923
+ };
1924
+ }
1925
+ function formUrlDecode(value) {
1820
1926
  try {
1821
- parsed = JSON.parse(text);
1927
+ return decodeURIComponent(value.replace(/\+/g, " "));
1822
1928
  } catch {
1823
- throw refuse("client_id metadata document is not valid JSON");
1929
+ return value;
1824
1930
  }
1825
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1826
- throw refuse("client_id metadata document must be a JSON object");
1931
+ }
1932
+ function readCredentials(req) {
1933
+ const header = req.headers?.authorization;
1934
+ if (typeof header === "string" && /^Basic /i.test(header)) {
1935
+ const decoded = Buffer.from(header.slice(6).trim(), "base64").toString("utf8");
1936
+ const sep = decoded.indexOf(":");
1937
+ const clientId = formUrlDecode(sep < 0 ? decoded : decoded.slice(0, sep));
1938
+ const secret = sep < 0 ? "" : formUrlDecode(decoded.slice(sep + 1));
1939
+ return { clientId, clientSecret: secret === "" ? null : secret, viaBasic: true };
1827
1940
  }
1828
- return {
1829
- document: parsed,
1830
- ...res.headers.get("etag") ? { etag: res.headers.get("etag") } : {}
1831
- };
1941
+ const body = req.body ?? {};
1942
+ if (typeof body.client_id === "string" && body.client_id) {
1943
+ return {
1944
+ clientId: body.client_id,
1945
+ clientSecret: typeof body.client_secret === "string" && body.client_secret ? body.client_secret : null,
1946
+ viaBasic: false
1947
+ };
1948
+ }
1949
+ return null;
1832
1950
  }
1833
- function requireString(doc, field) {
1834
- const value = doc[field];
1835
- if (typeof value !== "string" || !value.trim()) {
1836
- throw refuse(`client_id metadata field '${field}' must be a non-empty string`);
1951
+ function authFailure(viaBasic) {
1952
+ return new OAuthError(401, "invalid_client", "client authentication failed", {
1953
+ // RFC 6749 §5.2 a 401 answering a Basic credential MUST carry the challenge.
1954
+ headers: viaBasic ? { "WWW-Authenticate": 'Basic realm="oauth", charset="UTF-8"' } : {}
1955
+ });
1956
+ }
1957
+ var CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
1958
+ var MAX_ASSERTION_BYTES = 8192;
1959
+ var COMPACT_JWS_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
1960
+ var ASSERTION_ALGORITHMS = ["RS256", "ES256"];
1961
+ var MAX_ASSERTION_AGE_S = 3600;
1962
+ var MAX_JTI_LEN = 256;
1963
+ var REPLAY_CACHE_MAX = 1e4;
1964
+ var JWKS_CACHE_MAX = 100;
1965
+ var JWKS_FORCE_REFETCH_INTERVAL_MS = 6e4;
1966
+ var ASSERTION_CLOCK_TOLERANCE_S = 60;
1967
+ function tokenEndpointUrl(ctx) {
1968
+ return `${ctx.issuer}${ctx.mountPath}/token`;
1969
+ }
1970
+ function isJwkSet(doc) {
1971
+ return Boolean(doc) && typeof doc === "object" && Array.isArray(doc.keys);
1972
+ }
1973
+ function assertionFailure(reason) {
1974
+ return new Error(reason);
1975
+ }
1976
+ function selectCandidateKeys(keys, header) {
1977
+ return keys.filter((key) => {
1978
+ if (header.kid !== void 0 && key.kid !== header.kid) return false;
1979
+ const use = key.use;
1980
+ if (use !== void 0 && use !== "sig") return false;
1981
+ const alg = key.alg;
1982
+ if (alg !== void 0 && alg !== header.alg) return false;
1983
+ return true;
1984
+ });
1985
+ }
1986
+ async function resolveJwksKeys(ctx, jwksUri, forceRefetch) {
1987
+ const { jwksCache, jwksForceRefetchAt } = ctx.cimd;
1988
+ const now = Date.now();
1989
+ const cached = jwksCache.get(jwksUri);
1990
+ const fresh = cached !== void 0 && now - cached.fetchedAt < ctx.cimd.cacheTtlMs;
1991
+ if (fresh && !forceRefetch) return cached.keys;
1992
+ if (forceRefetch) {
1993
+ const lastForced = jwksForceRefetchAt.get(jwksUri) ?? 0;
1994
+ if (now - lastForced < JWKS_FORCE_REFETCH_INTERVAL_MS) {
1995
+ return cached?.keys ?? [];
1996
+ }
1997
+ jwksForceRefetchAt.set(jwksUri, now);
1837
1998
  }
1838
- return value.trim();
1999
+ const doc = await fetchJwks(ctx, jwksUri);
2000
+ if (!isJwkSet(doc)) throw assertionFailure(`jwks_uri '${jwksUri}' did not serve a JWK Set`);
2001
+ if (!jwksCache.has(jwksUri) && jwksCache.size >= JWKS_CACHE_MAX) {
2002
+ const oldest = jwksCache.keys().next();
2003
+ if (!oldest.done) jwksCache.delete(oldest.value);
2004
+ }
2005
+ jwksCache.set(jwksUri, { keys: doc.keys, fetchedAt: now });
2006
+ return doc.keys;
1839
2007
  }
1840
- function optionalHttpsUri(doc, field) {
1841
- const value = doc[field];
1842
- if (value === void 0 || value === null) return void 0;
1843
- if (typeof value !== "string" || !value.trim()) {
1844
- throw refuse(`client_id metadata field '${field}' must be a string`);
2008
+ async function loadClientJwks(ctx, client) {
2009
+ if (client.jwks !== void 0 && client.jwks !== null) {
2010
+ if (!isJwkSet(client.jwks)) {
2011
+ throw assertionFailure(`client '${client.clientId}' has a malformed stored 'jwks'`);
2012
+ }
2013
+ return client.jwks.keys;
1845
2014
  }
1846
- let url;
2015
+ if (client.jwksUri) {
2016
+ return resolveJwksKeys(ctx, client.jwksUri, false);
2017
+ }
2018
+ throw assertionFailure(`client '${client.clientId}' has neither 'jwks' nor 'jwksUri' stored`);
2019
+ }
2020
+ async function verifyClientAssertion(ctx, body) {
2021
+ if (body.client_assertion_type !== CLIENT_ASSERTION_TYPE) {
2022
+ throw assertionFailure(
2023
+ `client_assertion_type must be '${CLIENT_ASSERTION_TYPE}' (got ${JSON.stringify(body.client_assertion_type)})`
2024
+ );
2025
+ }
2026
+ const assertion = body.client_assertion;
2027
+ if (typeof assertion !== "string" || !assertion || Buffer.byteLength(assertion, "utf8") > MAX_ASSERTION_BYTES || !COMPACT_JWS_RE.test(assertion)) {
2028
+ throw assertionFailure("client_assertion is not a well-formed compact JWS");
2029
+ }
2030
+ if (typeof body.client_secret === "string" && body.client_secret) {
2031
+ throw assertionFailure("client_assertion was presented alongside a client_secret");
2032
+ }
2033
+ let unverified;
1847
2034
  try {
1848
- url = new URL(value);
2035
+ unverified = decodeJwt(assertion);
1849
2036
  } catch {
1850
- throw refuse(`client_id metadata field '${field}' must be an absolute URL: '${value}'`);
2037
+ throw assertionFailure("client_assertion could not be decoded");
1851
2038
  }
1852
- if (url.protocol !== "https:") {
1853
- throw refuse(`client_id metadata field '${field}' must be https (got '${url.protocol}')`);
2039
+ const iss = unverified.iss;
2040
+ if (typeof iss !== "string" || !iss) {
2041
+ throw assertionFailure("client_assertion is missing iss");
1854
2042
  }
1855
- return value;
1856
- }
1857
- function assertRedirectUris2(doc) {
1858
- const value = doc.redirect_uris;
1859
- if (!Array.isArray(value) || value.length === 0) {
1860
- throw refuse("client_id metadata field 'redirect_uris' must be a non-empty array");
2043
+ if (typeof body.client_id === "string" && body.client_id && body.client_id !== iss) {
2044
+ throw assertionFailure("client_assertion iss does not match client_id");
1861
2045
  }
1862
- return value.map((entry) => {
1863
- if (typeof entry !== "string" || !entry) {
1864
- throw refuse(`client_id metadata 'redirect_uris' entries must be strings (got ${JSON.stringify(entry)})`);
1865
- }
1866
- let url;
1867
- try {
1868
- url = new URL(entry);
1869
- } catch {
1870
- throw refuse(`client_id metadata 'redirect_uris' entry must be an absolute URI: '${entry}'`);
1871
- }
1872
- const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
1873
- if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
1874
- throw refuse(
1875
- `client_id metadata 'redirect_uris' entry must be https (http is allowed only on localhost/127.0.0.1): '${entry}'`
1876
- );
1877
- }
1878
- if (url.hash) {
1879
- throw refuse(`client_id metadata 'redirect_uris' entry must not contain a fragment: '${entry}'`);
1880
- }
1881
- return entry;
1882
- });
1883
- }
1884
- function validateMetadataDocument(ctx, url, doc) {
1885
- const declared = requireString(doc, "client_id");
1886
- let declaredUrl;
2046
+ const client = await ctx.models.Client.findOne({ clientId: iss });
2047
+ if (!client || client.status !== "active" || !client.tokenEndpointAuthMethods?.includes("private_key_jwt")) {
2048
+ throw assertionFailure(`client '${iss}' does not support private_key_jwt`);
2049
+ }
2050
+ let header;
1887
2051
  try {
1888
- declaredUrl = new URL(declared);
2052
+ header = decodeProtectedHeader(assertion);
1889
2053
  } catch {
1890
- throw refuse(`client_id metadata field 'client_id' is not a URL: '${declared}'`);
2054
+ throw assertionFailure("client_assertion header could not be decoded");
1891
2055
  }
1892
- if (declaredUrl.href !== url.href) {
1893
- throw refuse(
1894
- `client_id metadata field 'client_id' is '${declared}', which is not the URL it was fetched from ('${url.href}')`
1895
- );
2056
+ const alg = header.alg;
2057
+ if (alg !== "RS256" && alg !== "ES256") {
2058
+ throw assertionFailure(`client_assertion alg '${String(alg)}' is not permitted`);
1896
2059
  }
1897
- const method = doc.token_endpoint_auth_method;
1898
- if (method !== void 0 && method !== "none") {
1899
- throw refuse(
1900
- `client_id metadata field 'token_endpoint_auth_method' must be 'none' (got ${JSON.stringify(method)}) \u2014 a CIMD client holds no secret`
1901
- );
2060
+ const stored = await loadClientJwks(ctx, client);
2061
+ let candidates = selectCandidateKeys(stored, { alg, kid: header.kid });
2062
+ if (candidates.length === 0 && client.jwksUri) {
2063
+ const refetched = await resolveJwksKeys(ctx, client.jwksUri, true);
2064
+ candidates = selectCandidateKeys(refetched, { alg, kid: header.kid });
1902
2065
  }
1903
- const name = requireString(doc, "client_name");
1904
- const redirectUris = assertRedirectUris2(doc);
1905
- const permitted = new Set(ctx.cimd.allowedScopes.filter((id) => ctx.scopeIndex.has(id)));
1906
- let allowedScopes;
1907
- if (doc.scope === void 0 || doc.scope === null) {
1908
- allowedScopes = [...permitted];
1909
- } else {
1910
- if (typeof doc.scope !== "string") {
1911
- throw refuse("client_id metadata field 'scope' must be a space-delimited string");
2066
+ if (candidates.length === 0) {
2067
+ throw assertionFailure(`no candidate key for kid '${String(header.kid)}'`);
2068
+ }
2069
+ const tokenEndpoint = tokenEndpointUrl(ctx);
2070
+ let verified;
2071
+ let lastJoseError;
2072
+ for (const jwk of candidates) {
2073
+ try {
2074
+ const key = await importJWK(jwk, alg);
2075
+ verified = await jwtVerify(assertion, key, {
2076
+ // Passed explicitly rather than trusting the header a second time —
2077
+ // this is the actual alg-confusion guard, not the earlier check,
2078
+ // which only short-circuits the common case before a fetch.
2079
+ algorithms: [...ASSERTION_ALGORITHMS],
2080
+ audience: [tokenEndpoint, ctx.issuer],
2081
+ clockTolerance: ASSERTION_CLOCK_TOLERANCE_S
2082
+ });
2083
+ break;
2084
+ } catch (err) {
2085
+ lastJoseError = err;
1912
2086
  }
1913
- const requested = new Set(doc.scope.split(/\s+/).filter(Boolean));
1914
- allowedScopes = [...permitted].filter((id) => requested.has(id));
1915
2087
  }
1916
- if (allowedScopes.length === 0) {
1917
- throw refuse(
1918
- "client_id metadata field 'scope' has no overlap with what this server offers \u2014 there is nothing this client could be granted"
2088
+ if (!verified) {
2089
+ throw assertionFailure(
2090
+ `client_assertion did not verify: ${lastJoseError instanceof Error ? lastJoseError.message : "unknown error"}`
1919
2091
  );
1920
2092
  }
1921
- const branding = {};
1922
- const logoUrl = optionalHttpsUri(doc, "logo_uri");
1923
- const homepageUrl = optionalHttpsUri(doc, "client_uri");
1924
- const tosUrl = optionalHttpsUri(doc, "tos_uri");
1925
- const privacyUrl = optionalHttpsUri(doc, "policy_uri");
1926
- if (logoUrl) branding.logoUrl = logoUrl;
1927
- if (homepageUrl) branding.homepageUrl = homepageUrl;
1928
- if (tosUrl) branding.tosUrl = tosUrl;
1929
- if (privacyUrl) branding.privacyUrl = privacyUrl;
1930
- return { name, redirectUris, allowedScopes, branding };
1931
- }
1932
- function rememberFailure(ctx, key, message) {
1933
- const { failures } = ctx.cimd;
1934
- if (failures.size >= MAX_REMEMBERED_FAILURES) {
1935
- const oldest = failures.keys().next();
1936
- if (!oldest.done) failures.delete(oldest.value);
2093
+ const { payload } = verified;
2094
+ if (payload.iss !== client.clientId || payload.sub !== client.clientId) {
2095
+ throw assertionFailure("client_assertion iss/sub must both equal the client_id");
1937
2096
  }
1938
- failures.set(key, { until: Date.now() + NEGATIVE_TTL_MS, message });
1939
- }
1940
- function rememberedFailure(ctx, key) {
1941
- const found = ctx.cimd.failures.get(key);
1942
- if (!found) return null;
1943
- if (found.until <= Date.now()) {
1944
- ctx.cimd.failures.delete(key);
1945
- return null;
2097
+ const exp = payload.exp;
2098
+ const nowS = Math.floor(Date.now() / 1e3);
2099
+ if (typeof exp !== "number" || exp - nowS > MAX_ASSERTION_AGE_S) {
2100
+ throw assertionFailure("client_assertion exp is too far in the future");
1946
2101
  }
1947
- return found.message;
2102
+ const jti = payload.jti;
2103
+ if (typeof jti !== "string" || !jti || jti.length > MAX_JTI_LEN) {
2104
+ throw assertionFailure("client_assertion is missing jti");
2105
+ }
2106
+ const replay = ctx.cimd.assertionReplay;
2107
+ const replayKey = `${client.clientId}:${jti}`;
2108
+ const existing = replay.get(replayKey);
2109
+ if (existing !== void 0 && existing > Date.now()) {
2110
+ ctx.logger.warn?.({ clientId: client.clientId }, "oauth-host: private_key_jwt assertion replay detected");
2111
+ throw assertionFailure("client_assertion jti has already been used");
2112
+ }
2113
+ if (!replay.has(replayKey) && replay.size >= REPLAY_CACHE_MAX) {
2114
+ const oldest = replay.keys().next();
2115
+ if (!oldest.done) replay.delete(oldest.value);
2116
+ }
2117
+ replay.set(replayKey, (exp + 60) * 1e3);
2118
+ return client;
1948
2119
  }
1949
- function isFresh(ctx, client) {
1950
- const fetchedAt = client.metadataFetchedAt?.getTime();
1951
- if (fetchedAt === void 0) return false;
1952
- return Date.now() - fetchedAt < ctx.cimd.cacheTtlMs;
2120
+ async function authenticateClient(ctx, req) {
2121
+ const body = req.body ?? {};
2122
+ const header = req.headers?.authorization;
2123
+ const viaBasic = typeof header === "string" && /^Basic /i.test(header);
2124
+ if (body.client_assertion !== void 0 || body.client_assertion_type !== void 0) {
2125
+ if (viaBasic) {
2126
+ ctx.logger.debug?.(
2127
+ "oauth-host: client_assertion presented alongside a Basic Authorization header"
2128
+ );
2129
+ throw authFailure(viaBasic);
2130
+ }
2131
+ try {
2132
+ return await verifyClientAssertion(ctx, body);
2133
+ } catch (err) {
2134
+ ctx.logger.debug?.(
2135
+ { err: err instanceof Error ? err.message : err },
2136
+ "oauth-host: private_key_jwt assertion rejected"
2137
+ );
2138
+ throw authFailure(viaBasic);
2139
+ }
2140
+ }
2141
+ const creds = readCredentials(req);
2142
+ if (!creds || !creds.clientId) throw authFailure(Boolean(creds?.viaBasic));
2143
+ const client = await ctx.models.Client.findOne({ clientId: creds.clientId });
2144
+ if (!client || client.status !== "active") throw authFailure(creds.viaBasic);
2145
+ if (client.type === "public") {
2146
+ if (creds.clientSecret !== null) throw authFailure(creds.viaBasic);
2147
+ return client;
2148
+ }
2149
+ if (creds.clientSecret === null) throw authFailure(creds.viaBasic);
2150
+ const now = Date.now();
2151
+ let matched;
2152
+ for (const record of client.secrets) {
2153
+ if (record.retiresAt && record.retiresAt.getTime() <= now) continue;
2154
+ if (safeEqual(sha256(creds.clientSecret), record.hash)) matched = record;
2155
+ }
2156
+ if (!matched) throw authFailure(creds.viaBasic);
2157
+ const usedAt = /* @__PURE__ */ new Date();
2158
+ matched.lastUsedAt = usedAt;
2159
+ await ctx.models.Client.updateOne(
2160
+ { clientId: client.clientId, "secrets.hash": matched.hash },
2161
+ { $set: { "secrets.$.lastUsedAt": usedAt } }
2162
+ );
2163
+ return client;
1953
2164
  }
1954
- async function persist(ctx, clientId, url, registration, etag) {
1955
- const doc = await ctx.models.Client.findOneAndUpdate(
1956
- { clientId },
1957
- {
1958
- $set: {
1959
- name: registration.name,
1960
- redirectUris: registration.redirectUris,
1961
- allowedScopes: registration.allowedScopes,
1962
- // Every declared resource. A CIMD client cannot express an audience
1963
- // preference, and RFC 8707 validation at `/authorize` narrows it anyway.
1964
- allowedResources: ctx.resources.map((r) => r.id),
1965
- branding: registration.branding,
1966
- metadataUrl: url.href,
1967
- metadataFetchedAt: /* @__PURE__ */ new Date(),
1968
- ...etag ? { metadataEtag: etag } : {}
1969
- },
1970
- $setOnInsert: {
1971
- type: "public",
1972
- registration: "cimd",
1973
- trusted: false,
1974
- secrets: [],
1975
- status: "active"
2165
+ function describeGrantScopes(ctx, ids) {
2166
+ return ids.map((id) => ctx.scopeIndex.get(id) ?? { id, label: id });
2167
+ }
2168
+ function createGrantsApi(ctx) {
2169
+ return {
2170
+ async list(query) {
2171
+ const limit = clampLimit(query?.limit);
2172
+ const skip = clampSkip(query?.skip);
2173
+ const filter = { revokedAt: null };
2174
+ if (query?.userId !== void 0) filter.userId = query.userId;
2175
+ if (query?.clientId !== void 0) filter.clientId = query.clientId;
2176
+ const grants = await ctx.models.Grant.find(filter).sort({ createdAt: -1 }).skip(skip).limit(limit).lean();
2177
+ if (grants.length === 0) return { items: [], limit };
2178
+ const clientIds = [...new Set(grants.map((g) => g.clientId))];
2179
+ const clients = await ctx.models.Client.find({ clientId: { $in: clientIds } }).lean();
2180
+ const byId = new Map(clients.map((c) => [c.clientId, toPublicClient(c)]));
2181
+ const contextCache = /* @__PURE__ */ new Map();
2182
+ const items = [];
2183
+ for (const grant of grants) {
2184
+ const client = byId.get(grant.clientId);
2185
+ const summary = {
2186
+ id: String(grant._id),
2187
+ client: client ? { clientId: client.clientId, name: client.name, branding: client.branding } : { clientId: grant.clientId, name: grant.clientId, branding: {} },
2188
+ scopes: describeGrantScopes(ctx, grant.scopes ?? []),
2189
+ createdAt: grant.createdAt,
2190
+ ...grant.lastUsedAt ? { lastUsedAt: grant.lastUsedAt } : {}
2191
+ };
2192
+ if (ctx.grantContext && grant.contextId) {
2193
+ const cacheKey = `${String(grant.userId)}:${grant.clientId}`;
2194
+ let available = contextCache.get(cacheKey);
2195
+ if (!available) {
2196
+ const user = { id: grant.userId };
2197
+ available = client ? await ctx.grantContext.list(user, { client, scopes: grant.scopes ?? [] }) : [];
2198
+ contextCache.set(cacheKey, available);
2199
+ }
2200
+ summary.context = available.find((c) => c.id === grant.contextId) ?? { id: grant.contextId, label: grant.contextId };
2201
+ }
2202
+ items.push(summary);
1976
2203
  }
2204
+ return { items, limit };
1977
2205
  },
1978
- { upsert: true, returnDocument: "after", setDefaultsOnInsert: false }
1979
- ).exec();
1980
- return doc;
2206
+ async revoke(grantId, opts = {}) {
2207
+ const by = opts.by ?? "admin";
2208
+ const grant = await ctx.models.Grant.findById(grantId).catch(() => null);
2209
+ if (!grant) return { tokensRevoked: 0 };
2210
+ const alreadyRevoked = Boolean(grant.revokedAt);
2211
+ if (!alreadyRevoked) {
2212
+ grant.revokedAt = /* @__PURE__ */ new Date();
2213
+ grant.revokedBy = by;
2214
+ await grant.save();
2215
+ }
2216
+ const tokensRevoked = await revokeTokensMatching(ctx, { grantId: grant._id });
2217
+ if (!alreadyRevoked) {
2218
+ ctx.track({
2219
+ type: "oauth.grant_revoked",
2220
+ userId: grant.userId,
2221
+ clientId: grant.clientId,
2222
+ grantId: String(grant._id),
2223
+ ...grant.contextId ? { contextId: grant.contextId } : {},
2224
+ scopes: grant.scopes
2225
+ });
2226
+ await ctx.audit({
2227
+ type: "oauth.grant_revoked",
2228
+ actor: by,
2229
+ clientId: grant.clientId,
2230
+ userId: grant.userId,
2231
+ grantId: grant._id,
2232
+ meta: { tokensRevoked }
2233
+ });
2234
+ }
2235
+ return { tokensRevoked };
2236
+ }
2237
+ };
1981
2238
  }
1982
- async function resolveCimdClient(ctx, clientId) {
1983
- const url = assertFetchableUrl(ctx, clientId);
1984
- const existing = await ctx.models.Client.findOne({ clientId }).exec();
1985
- if (existing) {
1986
- if (existing.status !== "active") {
1987
- throw refuse(`client '${clientId}' is disabled`);
2239
+ function pairwiseKey(userId) {
2240
+ const key = String(userId);
2241
+ if (!key || key.includes(".") || key.startsWith("$")) return null;
2242
+ return key;
2243
+ }
2244
+ function createUsersApi(ctx) {
2245
+ return {
2246
+ /**
2247
+ * Erasure. The user is gone and every trace of them has to go with them.
2248
+ *
2249
+ * This is the destructive twin of `revokeAll`, and the difference is the
2250
+ * whole reason both exist: `forget` DELETES the grant documents and the
2251
+ * user's audit rows, `revokeAll` keeps both. A password change must leave a
2252
+ * history an operator can read; a deletion request must not.
2253
+ *
2254
+ * Idempotent — it will be called twice, by a retry or by a host that wires
2255
+ * it to both a soft-delete and a hard-delete hook.
2256
+ */
2257
+ async forget(userId) {
2258
+ const grantsResult = await ctx.models.Grant.deleteMany({ userId });
2259
+ const tokensResult = await ctx.models.Token.deleteMany({ userId });
2260
+ await ctx.models.Code.deleteMany({ userId });
2261
+ await ctx.models.Request.deleteMany({ userId });
2262
+ const key = pairwiseKey(userId);
2263
+ if (key) {
2264
+ await ctx.models.Client.updateMany(
2265
+ { [`pairwiseSubjects.${key}`]: { $exists: true } },
2266
+ { $unset: { [`pairwiseSubjects.${key}`]: "" } }
2267
+ );
2268
+ }
2269
+ await ctx.models.Audit.deleteMany({ userId });
2270
+ const grants = grantsResult.deletedCount ?? 0;
2271
+ const tokens = tokensResult.deletedCount ?? 0;
2272
+ await ctx.audit({ type: "oauth.user_forgotten", actor: "system", meta: { grants, tokens } });
2273
+ return { grants, tokens };
2274
+ },
2275
+ /**
2276
+ * Password change, deactivation, suspected compromise.
2277
+ *
2278
+ * Kills live access and KEEPS everything else: the grant documents stay so
2279
+ * the audit trail still resolves and so the user's connected apps remain
2280
+ * visible, and the audit rows stay because that is the record the operator
2281
+ * called this to create. See `forget` above for the destructive twin.
2282
+ */
2283
+ async revokeAll(userId, opts = {}) {
2284
+ const live = await ctx.models.Grant.find({ userId, revokedAt: null }).limit(MAX_LIST).lean();
2285
+ const { grantsRevoked } = await revokeGrantsMatching(ctx, { userId }, "system");
2286
+ const tokensRevoked = await revokeTokensMatching(ctx, { userId });
2287
+ await ctx.models.Code.deleteMany({ userId });
2288
+ await ctx.models.Request.deleteMany({ userId });
2289
+ for (const grant of live) {
2290
+ ctx.track({
2291
+ type: "oauth.grant_revoked",
2292
+ userId,
2293
+ clientId: grant.clientId,
2294
+ grantId: String(grant._id),
2295
+ ...grant.contextId ? { contextId: grant.contextId } : {},
2296
+ scopes: grant.scopes
2297
+ });
2298
+ }
2299
+ await ctx.audit({
2300
+ type: "oauth.user_access_revoked",
2301
+ actor: "system",
2302
+ userId,
2303
+ meta: { grantsRevoked, tokensRevoked, ...opts.reason ? { reason: opts.reason } : {} }
2304
+ });
2305
+ return { grantsRevoked, tokensRevoked };
1988
2306
  }
1989
- if (existing.registration !== "cimd") return existing;
1990
- if (isFresh(ctx, existing)) return existing;
1991
- }
1992
- const remembered = rememberedFailure(ctx, url.href);
1993
- if (remembered) throw refuse(remembered);
1994
- try {
1995
- const { document, etag } = await fetchMetadata(ctx, url, existing?.metadataEtag);
1996
- if (!document) {
1997
- if (existing) {
1998
- existing.metadataFetchedAt = /* @__PURE__ */ new Date();
1999
- await existing.save();
2000
- return existing;
2307
+ };
2308
+ }
2309
+ function createContextsApi(ctx) {
2310
+ return {
2311
+ /**
2312
+ * A grant made as an employee has to die when the employment does.
2313
+ *
2314
+ * `grantContext.verify()` catches this on the next refresh, but an access
2315
+ * token already issued is valid for its full hour and nothing re-checks it.
2316
+ * This is the push half of that pair, and it is why the adapter has an
2317
+ * outbound direction at all.
2318
+ */
2319
+ async revoked(userId, contextId) {
2320
+ const live = await ctx.models.Grant.find({ userId, contextId, revokedAt: null }).limit(MAX_LIST).lean();
2321
+ const { grantsRevoked } = await revokeGrantsMatching(ctx, { userId, contextId }, "system");
2322
+ const tokensRevoked = await revokeTokensMatching(ctx, { userId, contextId });
2323
+ await ctx.models.Code.deleteMany({ userId, contextId });
2324
+ for (const grant of live) {
2325
+ ctx.track({
2326
+ type: "oauth.grant_revoked",
2327
+ userId,
2328
+ clientId: grant.clientId,
2329
+ grantId: String(grant._id),
2330
+ contextId,
2331
+ scopes: grant.scopes
2332
+ });
2333
+ await ctx.audit({
2334
+ type: "oauth.grant_revoked",
2335
+ actor: "system",
2336
+ clientId: grant.clientId,
2337
+ userId,
2338
+ grantId: grant._id,
2339
+ meta: { contextId, reason: "context_membership_ended" }
2340
+ });
2001
2341
  }
2002
- throw refuse("client_id metadata returned 304 with nothing cached to answer from");
2342
+ return { grantsRevoked, tokensRevoked };
2003
2343
  }
2004
- const registration = validateMetadataDocument(ctx, url, document);
2005
- const client = await persist(ctx, clientId, url, registration, etag);
2006
- ctx.logger.debug?.({ clientId }, "oauth-host: client_id metadata document resolved");
2007
- return client;
2008
- } catch (err) {
2009
- const message = err instanceof UnredirectableError ? err.description ?? "client_id metadata could not be resolved" : "client_id metadata could not be resolved";
2010
- rememberFailure(ctx, url.href, message);
2011
- ctx.logger.warn?.({ clientId, err }, "oauth-host: client_id metadata resolution failed");
2012
- throw err instanceof UnredirectableError ? err : refuse(message);
2013
- }
2344
+ };
2014
2345
  }
2015
2346
 
2016
2347
  // src/server/services/scopes.ts