@lumoauth/agent 1.1.0 → 1.3.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
@@ -23,37 +23,210 @@ __export(index_exports, {
23
23
  AAUTH_COVERED_COMPONENTS: () => AAUTH_COVERED_COMPONENTS,
24
24
  AAuthClient: () => AAuthClient,
25
25
  AAuthError: () => AAuthError,
26
+ AccessTokenError: () => AccessTokenError,
27
+ CLIENT_ASSERTION_TYP: () => CLIENT_ASSERTION_TYP,
28
+ CLIENT_ASSERTION_TYPE: () => CLIENT_ASSERTION_TYPE,
29
+ ClientAssertionSigner: () => ClientAssertionSigner,
30
+ DPOP_NONCE_HEADER: () => import_shared7.DPOP_NONCE_HEADER,
31
+ DPOP_SCHEME: () => import_shared7.DPOP_SCHEME,
32
+ DpopProofSigner: () => DpopProofSigner,
33
+ InMemoryDpopReplayCache: () => InMemoryDpopReplayCache,
34
+ JwksCache: () => JwksCache,
26
35
  LumoAgent: () => LumoAgent,
27
- LumoAuthApiError: () => import_shared4.LumoAuthApiError,
28
- LumoAuthApprovalDeniedError: () => import_shared4.LumoAuthApprovalDeniedError,
29
- LumoAuthApprovalNotDeliveredError: () => import_shared4.LumoAuthApprovalNotDeliveredError,
30
- LumoAuthApprovalTimeoutError: () => import_shared4.LumoAuthApprovalTimeoutError,
31
- LumoAuthAuthenticationError: () => import_shared4.LumoAuthAuthenticationError,
32
- LumoAuthBudgetExceededError: () => import_shared4.LumoAuthBudgetExceededError,
33
- LumoAuthConfigError: () => import_shared4.LumoAuthConfigError,
34
- LumoAuthError: () => import_shared4.LumoAuthError,
35
- LumoAuthNetworkError: () => import_shared4.LumoAuthNetworkError,
36
- LumoAuthNotFoundError: () => import_shared4.LumoAuthNotFoundError,
37
- LumoAuthPermissionDeniedError: () => import_shared4.LumoAuthPermissionDeniedError,
38
- LumoAuthRateLimitError: () => import_shared4.LumoAuthRateLimitError,
39
- LumoAuthValidationError: () => import_shared4.LumoAuthValidationError,
36
+ LumoAuthApiError: () => import_shared8.LumoAuthApiError,
37
+ LumoAuthApprovalDeniedError: () => import_shared8.LumoAuthApprovalDeniedError,
38
+ LumoAuthApprovalNotDeliveredError: () => import_shared8.LumoAuthApprovalNotDeliveredError,
39
+ LumoAuthApprovalTimeoutError: () => import_shared8.LumoAuthApprovalTimeoutError,
40
+ LumoAuthAuthenticationError: () => import_shared8.LumoAuthAuthenticationError,
41
+ LumoAuthBudgetExceededError: () => import_shared8.LumoAuthBudgetExceededError,
42
+ LumoAuthConfigError: () => import_shared8.LumoAuthConfigError,
43
+ LumoAuthError: () => import_shared8.LumoAuthError,
44
+ LumoAuthNetworkError: () => import_shared8.LumoAuthNetworkError,
45
+ LumoAuthNotFoundError: () => import_shared8.LumoAuthNotFoundError,
46
+ LumoAuthPermissionDeniedError: () => import_shared8.LumoAuthPermissionDeniedError,
47
+ LumoAuthRateLimitError: () => import_shared8.LumoAuthRateLimitError,
48
+ LumoAuthValidationError: () => import_shared8.LumoAuthValidationError,
49
+ MAX_ASSERTION_LIFETIME_SECONDS: () => MAX_ASSERTION_LIFETIME_SECONDS,
50
+ USE_DPOP_NONCE: () => import_shared7.USE_DPOP_NONCE,
51
+ accessTokenScopes: () => accessTokenScopes,
52
+ attestWorkload: () => attestWorkload,
53
+ buildDpopHeaders: () => import_shared7.buildDpopHeaders,
40
54
  buildSignatureBase: () => buildSignatureBase,
41
55
  contentDigestSha256: () => contentDigestSha256,
56
+ createAccessTokenVerifier: () => createAccessTokenVerifier,
42
57
  decodeJwt: () => decodeJwt,
58
+ dpopAth: () => dpopAth,
59
+ dpopHtu: () => import_shared7.dpopHtu,
60
+ fetchWithDpop: () => import_shared7.fetchWithDpop,
43
61
  generateKeypair: () => generateKeypair,
44
62
  generateNonce: () => generateNonce,
63
+ issuerFor: () => issuerFor,
45
64
  jwkThumbprint: () => jwkThumbprint,
65
+ parseAuthorizationHeader: () => parseAuthorizationHeader,
46
66
  publicJwkFromPrivateKey: () => publicJwkFromPrivateKey,
47
67
  signRequest: () => signRequest,
48
68
  signSignatureBase: () => signSignatureBase,
49
69
  signatureParams: () => signatureParams,
70
+ verifyAccessToken: () => verifyAccessToken,
50
71
  verifyAuthToken: () => verifyAuthToken,
72
+ verifyDpopProof: () => verifyDpopProof,
51
73
  verifySignatureBase: () => verifySignatureBase
52
74
  });
53
75
  module.exports = __toCommonJS(index_exports);
54
76
 
55
77
  // src/agent.ts
56
78
  var import_shared = require("@lumoauth/shared");
79
+
80
+ // src/client-assertion.ts
81
+ var import_node_crypto = require("crypto");
82
+ var CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
83
+ var CLIENT_ASSERTION_TYP = "client-authentication+jwt";
84
+ var MAX_ASSERTION_LIFETIME_SECONDS = 600;
85
+ var RSA_ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512"];
86
+ var EC_ALGORITHM_BY_CURVE = {
87
+ prime256v1: "ES256",
88
+ "P-256": "ES256",
89
+ secp384r1: "ES384",
90
+ "P-384": "ES384",
91
+ secp521r1: "ES512",
92
+ "P-521": "ES512"
93
+ };
94
+ var ClientAssertionSigner = class _ClientAssertionSigner {
95
+ /** Generate a new key: ES256 (default), ES384, ES512, EdDSA, or an RSA algorithm (2048-bit key). */
96
+ static generate(algorithm = "ES256", keyId) {
97
+ let privateKey;
98
+ if (algorithm === "ES256" || algorithm === "ES384" || algorithm === "ES512") {
99
+ const namedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[algorithm];
100
+ privateKey = (0, import_node_crypto.generateKeyPairSync)("ec", { namedCurve }).privateKey;
101
+ } else if (algorithm === "EdDSA") {
102
+ privateKey = (0, import_node_crypto.generateKeyPairSync)("ed25519").privateKey;
103
+ } else if (RSA_ALGORITHMS.includes(algorithm)) {
104
+ privateKey = (0, import_node_crypto.generateKeyPairSync)("rsa", { modulusLength: 2048 }).privateKey;
105
+ } else {
106
+ throw new Error(`Unsupported client assertion algorithm: ${String(algorithm)}`);
107
+ }
108
+ return new _ClientAssertionSigner({ privateKey, keyId, algorithm });
109
+ }
110
+ /** Load a PEM private key. */
111
+ static fromPem(pem, options = {}) {
112
+ return new _ClientAssertionSigner({ ...options, privateKeyPem: pem });
113
+ }
114
+ constructor(options) {
115
+ if (options.privateKey) {
116
+ this.key = options.privateKey;
117
+ } else if (options.privateKeyPem) {
118
+ this.key = (0, import_node_crypto.createPrivateKey)(options.privateKeyPem);
119
+ } else {
120
+ throw new Error("ClientAssertionSigner needs privateKeyPem or privateKey");
121
+ }
122
+ if (this.key.type !== "private") {
123
+ throw new Error("ClientAssertionSigner needs a private key");
124
+ }
125
+ const natural = naturalAlgorithm(this.key);
126
+ const chosen = options.algorithm ?? natural;
127
+ if (this.key.asymmetricKeyType === "rsa") {
128
+ if (!RSA_ALGORITHMS.includes(chosen)) {
129
+ throw new Error(`${chosen} does not fit an RSA key; use one of ${RSA_ALGORITHMS.join(", ")}`);
130
+ }
131
+ const bits = this.key.asymmetricKeyDetails?.modulusLength ?? 0;
132
+ if (bits < 2048) throw new Error("RSA keys must be at least 2048 bits");
133
+ } else if (chosen !== natural) {
134
+ throw new Error(`${chosen} does not fit this key; it signs with ${natural}`);
135
+ }
136
+ const lifetime = options.lifetimeSeconds ?? 60;
137
+ if (!Number.isInteger(lifetime) || lifetime < 1 || lifetime > MAX_ASSERTION_LIFETIME_SECONDS) {
138
+ throw new Error(`lifetimeSeconds must be an integer from 1 to ${MAX_ASSERTION_LIFETIME_SECONDS}`);
139
+ }
140
+ this.algorithm = chosen;
141
+ this.keyId = options.keyId;
142
+ this.lifetimeSeconds = lifetime;
143
+ this.now = options.now ?? (() => Math.floor(Date.now() / 1e3));
144
+ }
145
+ /** Sign one assertion for `clientId` (the agent ID) and `audience` (the organization's issuer). */
146
+ create(clientId, audience) {
147
+ if (!clientId || !audience) {
148
+ throw new Error("clientId and audience are required for a client assertion");
149
+ }
150
+ const iat = this.now();
151
+ const header = { alg: this.algorithm, typ: CLIENT_ASSERTION_TYP };
152
+ if (this.keyId) header.kid = this.keyId;
153
+ const claims = {
154
+ iss: clientId,
155
+ sub: clientId,
156
+ aud: audience,
157
+ iat,
158
+ exp: iat + this.lifetimeSeconds,
159
+ jti: (0, import_node_crypto.randomBytes)(24).toString("base64url")
160
+ };
161
+ const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
162
+ return `${signingInput}.${signAssertion(this.algorithm, Buffer.from(signingInput, "utf8"), this.key).toString("base64url")}`;
163
+ }
164
+ /** The public key as a JWK with `kid` (when set), `alg` and `use: "sig"`. */
165
+ get jwk() {
166
+ const pub = (0, import_node_crypto.createPublicKey)(this.key).export({ format: "jwk" });
167
+ const out = { kty: pub.kty };
168
+ for (const member of ["crv", "x", "y", "n", "e"]) {
169
+ if (typeof pub[member] === "string") out[member] = pub[member];
170
+ }
171
+ if (this.keyId) out.kid = this.keyId;
172
+ out.alg = this.algorithm;
173
+ out.use = "sig";
174
+ return out;
175
+ }
176
+ /** `{ keys: [jwk] }`: what to register on the agent. */
177
+ get jwks() {
178
+ return { keys: [this.jwk] };
179
+ }
180
+ /** The private key as PKCS#8 PEM, for your secret store. */
181
+ get privateKeyPem() {
182
+ return this.key.export({ type: "pkcs8", format: "pem" }).toString();
183
+ }
184
+ };
185
+ function issuerFor(baseUrl, orgId) {
186
+ return `${baseUrl.replace(/\/+$/, "")}/orgs/${orgId}/api/v1`;
187
+ }
188
+ function naturalAlgorithm(key) {
189
+ switch (key.asymmetricKeyType) {
190
+ case "ec": {
191
+ const curve = String(key.asymmetricKeyDetails?.namedCurve ?? "");
192
+ const alg = EC_ALGORITHM_BY_CURVE[curve];
193
+ if (!alg) throw new Error(`EC keys must use P-256, P-384 or P-521 (got ${curve})`);
194
+ return alg;
195
+ }
196
+ case "ed25519":
197
+ return "EdDSA";
198
+ case "rsa":
199
+ return "RS256";
200
+ default:
201
+ throw new Error(`Unsupported key type: ${String(key.asymmetricKeyType)}`);
202
+ }
203
+ }
204
+ function signAssertion(alg, data, key) {
205
+ const hash = `sha${alg.slice(2)}`;
206
+ switch (alg) {
207
+ case "ES256":
208
+ case "ES384":
209
+ case "ES512":
210
+ return (0, import_node_crypto.sign)(hash, data, { key, dsaEncoding: "ieee-p1363" });
211
+ case "EdDSA":
212
+ return (0, import_node_crypto.sign)(null, data, key);
213
+ case "PS256":
214
+ case "PS384":
215
+ case "PS512":
216
+ return (0, import_node_crypto.sign)(hash, data, {
217
+ key,
218
+ padding: import_node_crypto.constants.RSA_PKCS1_PSS_PADDING,
219
+ saltLength: import_node_crypto.constants.RSA_PSS_SALTLEN_DIGEST
220
+ });
221
+ default:
222
+ return (0, import_node_crypto.sign)(hash, data, key);
223
+ }
224
+ }
225
+ function b64url(text) {
226
+ return Buffer.from(text, "utf8").toString("base64url");
227
+ }
228
+
229
+ // src/agent.ts
57
230
  function envVar(name) {
58
231
  return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
59
232
  }
@@ -65,12 +238,22 @@ var LumoAgent = class {
65
238
  this.baseUrl = (options.baseUrl ?? envVar("LUMOAUTH_URL") ?? "https://app.lumoauth.dev").replace(/\/+$/, "");
66
239
  this.orgId = options.orgId ?? envVar("LUMOAUTH_ORG_ID") ?? "";
67
240
  this.clientId = options.clientId ?? envVar("AGENT_CLIENT_ID") ?? "";
68
- this.clientSecret = options.clientSecret ?? envVar("AGENT_CLIENT_SECRET") ?? "";
241
+ const privateKey = options.privateKey ?? envVar("AGENT_PRIVATE_KEY");
242
+ const keyId = options.keyId ?? envVar("AGENT_KEY_ID");
243
+ this.assertionSigner = privateKey === void 0 || privateKey === "" ? void 0 : privateKey instanceof ClientAssertionSigner ? privateKey : ClientAssertionSigner.fromPem(privateKey, { keyId });
244
+ this.clientSecret = options.clientSecret ?? (this.assertionSigner ? "" : envVar("AGENT_CLIENT_SECRET") ?? "");
245
+ this.issuer = options.issuer;
69
246
  this.scopes = options.scopes;
70
247
  this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
71
- if (!this.clientId || !this.clientSecret) {
248
+ this.dpop = options.dpop;
249
+ if (!this.clientId || !this.clientSecret && !this.assertionSigner) {
250
+ throw new import_shared.LumoAuthConfigError(
251
+ "Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET (or AGENT_PRIVATE_KEY for a private key JWT agent), or pass clientId with clientSecret or privateKey to the constructor."
252
+ );
253
+ }
254
+ if (this.clientSecret && this.assertionSigner) {
72
255
  throw new import_shared.LumoAuthConfigError(
73
- "Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET environment variables or pass clientId/clientSecret to the constructor."
256
+ "Pass clientSecret or privateKey, not both: an agent authenticates with one method."
74
257
  );
75
258
  }
76
259
  const tokenProvider = () => this.getAccessToken();
@@ -78,7 +261,8 @@ var LumoAgent = class {
78
261
  baseUrl: this.baseUrl,
79
262
  token: tokenProvider,
80
263
  timeout: options.timeout,
81
- fetch: options.fetch
264
+ fetch: options.fetch,
265
+ dpop: this.dpop
82
266
  });
83
267
  this.agents = new import_shared.AgentsModule(http, this.orgId);
84
268
  this.jit = new import_shared.JitModule(http, this.orgId);
@@ -87,7 +271,9 @@ var LumoAgent = class {
87
271
  baseUrl: this.baseUrl,
88
272
  orgId: this.orgId,
89
273
  token: tokenProvider,
90
- fetch: options.fetch
274
+ fetch: options.fetch,
275
+ http,
276
+ dpop: this.dpop
91
277
  });
92
278
  this.delegation = new import_shared.DelegationModule({
93
279
  baseUrl: this.baseUrl,
@@ -96,7 +282,8 @@ var LumoAgent = class {
96
282
  clientSecret: this.clientSecret,
97
283
  redirectUri: options.redirectUri,
98
284
  agentToken: tokenProvider,
99
- fetch: options.fetch
285
+ fetch: options.fetch,
286
+ dpop: this.dpop
100
287
  });
101
288
  }
102
289
  // ── Authentication ────────────────────────────────────────────────
@@ -108,19 +295,25 @@ var LumoAgent = class {
108
295
  async authenticate(scopes) {
109
296
  const form = {
110
297
  grant_type: "client_credentials",
111
- client_id: this.clientId,
112
- client_secret: this.clientSecret
298
+ client_id: this.clientId
113
299
  };
300
+ if (this.assertionSigner) {
301
+ form.client_assertion_type = CLIENT_ASSERTION_TYPE;
302
+ form.client_assertion = this.createClientAssertion();
303
+ } else {
304
+ form.client_secret = this.clientSecret;
305
+ }
114
306
  const requested = scopes ?? this.scopes;
115
307
  if (requested?.length) form.scope = requested.join(" ");
116
308
  const url = `${this.baseUrl}${(0, import_shared.buildPath)(import_shared.ROUTES["oauth.token"].path, { orgId: this.requireOrgId() })}`;
309
+ const init = {
310
+ method: "POST",
311
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
312
+ body: new URLSearchParams(form)
313
+ };
117
314
  let res;
118
315
  try {
119
- res = await this.fetchFn(url, {
120
- method: "POST",
121
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
122
- body: new URLSearchParams(form)
123
- });
316
+ res = this.dpop ? await (0, import_shared.fetchWithDpop)(this.fetchFn, url, init, this.dpop) : await this.fetchFn(url, init);
124
317
  } catch (error) {
125
318
  throw new import_shared.LumoAuthNetworkError(
126
319
  `Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,
@@ -139,11 +332,39 @@ var LumoAgent = class {
139
332
  const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 3600;
140
333
  this.token = {
141
334
  accessToken: body.access_token,
335
+ tokenType: typeof body.token_type === "string" ? body.token_type : "Bearer",
142
336
  refreshAt: Date.now() + expiresIn * 1e3 - TOKEN_REFRESH_BUFFER_MS,
143
337
  scopes: typeof body.scope === "string" ? body.scope.split(" ").filter(Boolean) : []
144
338
  };
145
339
  return this.token.accessToken;
146
340
  }
341
+ /**
342
+ * `token_type` of the last successful authentication: `DPoP` when the
343
+ * token is sender-constrained, otherwise `Bearer`; `null` before the
344
+ * first sign-in. Present the token with that `Authorization` scheme.
345
+ */
346
+ get tokenType() {
347
+ return this.token?.tokenType ?? null;
348
+ }
349
+ /**
350
+ * A new `private_key_jwt` client assertion for this agent (single-use),
351
+ * addressed to `issuer` or `{baseUrl}/orgs/{orgId}/api/v1`.
352
+ */
353
+ createClientAssertion() {
354
+ if (!this.assertionSigner) {
355
+ throw new import_shared.LumoAuthConfigError("This agent signs no client assertions: create it with privateKey.");
356
+ }
357
+ const audience = this.issuer ?? issuerFor(this.baseUrl, this.requireOrgId());
358
+ return this.assertionSigner.create(this.clientId, audience);
359
+ }
360
+ /** The client assertion signer this agent was configured with, if any. */
361
+ get clientAssertionSigner() {
362
+ return this.assertionSigner;
363
+ }
364
+ /** The DPoP proof signer this agent was configured with, if any. */
365
+ get dpopSigner() {
366
+ return this.dpop;
367
+ }
147
368
  /**
148
369
  * The current access token, re-authenticating transparently when it is
149
370
  * missing or within 60 s of expiry. Concurrent callers share one
@@ -173,6 +394,13 @@ var LumoAgent = class {
173
394
  async isAllowed(action, context) {
174
395
  return this.agents.isAllowed(action, context);
175
396
  }
397
+ /**
398
+ * May this agent run `tool` on the registered MCP server `serverId`?
399
+ * A deny returns `{ allowed: false }` and does not throw.
400
+ */
401
+ async authorizeMcpTool(serverId, tool) {
402
+ return this.agents.authorizeMcpTool(serverId, tool);
403
+ }
176
404
  /** The agent's own identity, capabilities, and workspace. */
177
405
  async getCurrentAgent() {
178
406
  return this.agents.me();
@@ -197,9 +425,9 @@ var LumoAgent = class {
197
425
  };
198
426
 
199
427
  // src/keys.ts
200
- var import_node_crypto = require("crypto");
428
+ var import_node_crypto2 = require("crypto");
201
429
  function generateKeypair(kid = "key-1") {
202
- const { privateKey, publicKey } = (0, import_node_crypto.generateKeyPairSync)("ed25519");
430
+ const { privateKey, publicKey } = (0, import_node_crypto2.generateKeyPairSync)("ed25519");
203
431
  const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
204
432
  const publicKeyPem = publicKey.export({ type: "spki", format: "pem" }).toString();
205
433
  const rawJwk = publicKey.export({ format: "jwk" });
@@ -227,10 +455,10 @@ function jwkThumbprint(jwk) {
227
455
  default:
228
456
  throw new Error(`Unsupported key type for thumbprint: ${jwk.kty}`);
229
457
  }
230
- return (0, import_node_crypto.createHash)("sha256").update(canonical, "utf8").digest("base64url");
458
+ return (0, import_node_crypto2.createHash)("sha256").update(canonical, "utf8").digest("base64url");
231
459
  }
232
460
  function loadPrivateKey(pem) {
233
- const key = (0, import_node_crypto.createPrivateKey)(pem);
461
+ const key = (0, import_node_crypto2.createPrivateKey)(pem);
234
462
  if (key.asymmetricKeyType === "ed25519") {
235
463
  return { key, type: "ed25519" };
236
464
  }
@@ -242,15 +470,15 @@ function loadPrivateKey(pem) {
242
470
  );
243
471
  }
244
472
  function publicJwkFromPrivateKey(pem, kid) {
245
- const priv = (0, import_node_crypto.createPrivateKey)(pem);
246
- const pub = (0, import_node_crypto.createPublicKey)(priv);
473
+ const priv = (0, import_node_crypto2.createPrivateKey)(pem);
474
+ const pub = (0, import_node_crypto2.createPublicKey)(priv);
247
475
  const jwk = pub.export({ format: "jwk" });
248
476
  if (kid) jwk.kid = kid;
249
477
  return jwk;
250
478
  }
251
479
 
252
480
  // src/signing.ts
253
- var import_node_crypto2 = require("crypto");
481
+ var import_node_crypto3 = require("crypto");
254
482
  var AAUTH_COVERED_COMPONENTS = [
255
483
  "@method",
256
484
  "@authority",
@@ -262,11 +490,11 @@ var AAUTH_COVERED_COMPONENTS = [
262
490
  ];
263
491
  var SIGNATURE_LABEL = "sig1";
264
492
  function contentDigestSha256(body) {
265
- const digest = (0, import_node_crypto2.createHash)("sha256").update(body).digest("base64");
493
+ const digest = (0, import_node_crypto3.createHash)("sha256").update(body).digest("base64");
266
494
  return `sha-256=:${digest}:`;
267
495
  }
268
496
  function generateNonce() {
269
- return (0, import_node_crypto2.randomBytes)(16).toString("base64url");
497
+ return (0, import_node_crypto3.randomBytes)(16).toString("base64url");
270
498
  }
271
499
  function buildSignatureBase(components, values, created, nonce) {
272
500
  const lines = components.map((c) => `"${c}": ${values[c] ?? ""}`);
@@ -281,12 +509,12 @@ function signSignatureBase(signatureBase, privateKey) {
281
509
  const data = Buffer.from(signatureBase, "utf8");
282
510
  let signature;
283
511
  if (privateKey.asymmetricKeyType === "ed25519") {
284
- signature = (0, import_node_crypto2.sign)(null, data, privateKey);
512
+ signature = (0, import_node_crypto3.sign)(null, data, privateKey);
285
513
  } else {
286
- signature = (0, import_node_crypto2.sign)("sha512", data, {
514
+ signature = (0, import_node_crypto3.sign)("sha512", data, {
287
515
  key: privateKey,
288
- padding: import_node_crypto2.constants.RSA_PKCS1_PSS_PADDING,
289
- saltLength: import_node_crypto2.constants.RSA_PSS_SALTLEN_DIGEST
516
+ padding: import_node_crypto3.constants.RSA_PKCS1_PSS_PADDING,
517
+ saltLength: import_node_crypto3.constants.RSA_PSS_SALTLEN_DIGEST
290
518
  // 64 bytes for SHA-512
291
519
  });
292
520
  }
@@ -296,12 +524,12 @@ function verifySignatureBase(signatureBase, signatureB64url, publicKey) {
296
524
  const data = Buffer.from(signatureBase, "utf8");
297
525
  const sig = Buffer.from(signatureB64url, "base64url");
298
526
  if (publicKey.asymmetricKeyType === "ed25519") {
299
- return (0, import_node_crypto2.verify)(null, data, publicKey, sig);
527
+ return (0, import_node_crypto3.verify)(null, data, publicKey, sig);
300
528
  }
301
- return (0, import_node_crypto2.verify)("sha512", data, {
529
+ return (0, import_node_crypto3.verify)("sha512", data, {
302
530
  key: publicKey,
303
- padding: import_node_crypto2.constants.RSA_PKCS1_PSS_PADDING,
304
- saltLength: import_node_crypto2.constants.RSA_PSS_SALTLEN_DIGEST
531
+ padding: import_node_crypto3.constants.RSA_PKCS1_PSS_PADDING,
532
+ saltLength: import_node_crypto3.constants.RSA_PSS_SALTLEN_DIGEST
305
533
  }, sig);
306
534
  }
307
535
  function signRequest(privateKeyPem, method, url, options = {}) {
@@ -346,7 +574,7 @@ function signRequest(privateKeyPem, method, url, options = {}) {
346
574
  }
347
575
 
348
576
  // src/verify.ts
349
- var import_node_crypto3 = require("crypto");
577
+ var import_node_crypto4 = require("crypto");
350
578
 
351
579
  // src/errors.ts
352
580
  var import_shared2 = require("@lumoauth/shared");
@@ -360,19 +588,19 @@ var AAuthError = class extends import_shared2.LumoAuthError {
360
588
 
361
589
  // src/verify.ts
362
590
  var JWS_VERIFIERS = {
363
- RS256: (d, k, s) => (0, import_node_crypto3.verify)("sha256", d, k, s),
364
- RS384: (d, k, s) => (0, import_node_crypto3.verify)("sha384", d, k, s),
365
- RS512: (d, k, s) => (0, import_node_crypto3.verify)("sha512", d, k, s),
366
- PS256: (d, k, s) => (0, import_node_crypto3.verify)("sha256", d, pss(k), s),
367
- PS384: (d, k, s) => (0, import_node_crypto3.verify)("sha384", d, pss(k), s),
368
- PS512: (d, k, s) => (0, import_node_crypto3.verify)("sha512", d, pss(k), s),
369
- ES256: (d, k, s) => (0, import_node_crypto3.verify)("sha256", d, p1363(k), s),
370
- ES384: (d, k, s) => (0, import_node_crypto3.verify)("sha384", d, p1363(k), s),
371
- ES512: (d, k, s) => (0, import_node_crypto3.verify)("sha512", d, p1363(k), s),
372
- EdDSA: (d, k, s) => (0, import_node_crypto3.verify)(null, d, k, s)
591
+ RS256: (d, k, s) => (0, import_node_crypto4.verify)("sha256", d, k, s),
592
+ RS384: (d, k, s) => (0, import_node_crypto4.verify)("sha384", d, k, s),
593
+ RS512: (d, k, s) => (0, import_node_crypto4.verify)("sha512", d, k, s),
594
+ PS256: (d, k, s) => (0, import_node_crypto4.verify)("sha256", d, pss(k), s),
595
+ PS384: (d, k, s) => (0, import_node_crypto4.verify)("sha384", d, pss(k), s),
596
+ PS512: (d, k, s) => (0, import_node_crypto4.verify)("sha512", d, pss(k), s),
597
+ ES256: (d, k, s) => (0, import_node_crypto4.verify)("sha256", d, p1363(k), s),
598
+ ES384: (d, k, s) => (0, import_node_crypto4.verify)("sha384", d, p1363(k), s),
599
+ ES512: (d, k, s) => (0, import_node_crypto4.verify)("sha512", d, p1363(k), s),
600
+ EdDSA: (d, k, s) => (0, import_node_crypto4.verify)(null, d, k, s)
373
601
  };
374
602
  function pss(key) {
375
- return { key, padding: import_node_crypto3.constants.RSA_PKCS1_PSS_PADDING, saltLength: import_node_crypto3.constants.RSA_PSS_SALTLEN_DIGEST };
603
+ return { key, padding: import_node_crypto4.constants.RSA_PKCS1_PSS_PADDING, saltLength: import_node_crypto4.constants.RSA_PSS_SALTLEN_DIGEST };
376
604
  }
377
605
  function p1363(key) {
378
606
  return { key, dsaEncoding: "ieee-p1363" };
@@ -418,7 +646,7 @@ async function verifyAuthToken(token, options) {
418
646
  throw new AAuthError(`Key not found: kid=${kid}`, "invalid_token");
419
647
  }
420
648
  assertAlgMatchesKey(alg, jwk);
421
- const publicKey = (0, import_node_crypto3.createPublicKey)({ key: jwk, format: "jwk" });
649
+ const publicKey = (0, import_node_crypto4.createPublicKey)({ key: jwk, format: "jwk" });
422
650
  const data = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
423
651
  const signature = Buffer.from(parts[2], "base64url");
424
652
  if (!verifier(data, publicKey, signature)) {
@@ -733,13 +961,573 @@ var AAuthClient = class {
733
961
  /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */
734
962
  AAuthClient.generateKeypair = generateKeypair;
735
963
 
736
- // src/index.ts
964
+ // src/dpop.ts
965
+ var import_node_crypto5 = require("crypto");
737
966
  var import_shared4 = require("@lumoauth/shared");
967
+ var DpopProofSigner = class _DpopProofSigner {
968
+ constructor(options) {
969
+ this.nonces = /* @__PURE__ */ new Map();
970
+ if (options.privateKey) {
971
+ this.key = options.privateKey;
972
+ } else if (options.privateKeyPem) {
973
+ this.key = (0, import_node_crypto5.createPrivateKey)(options.privateKeyPem);
974
+ } else {
975
+ throw new Error("DpopProofSigner needs privateKeyPem or privateKey");
976
+ }
977
+ if (this.key.type !== "private") {
978
+ throw new Error("DpopProofSigner needs a private key");
979
+ }
980
+ this.algorithm = algorithmFor(this.key);
981
+ this.now = options.now ?? (() => Math.floor(Date.now() / 1e3));
982
+ const pub = (0, import_node_crypto5.createPublicKey)(this.key).export({ format: "jwk" });
983
+ this.jwk = publicMembers(pub);
984
+ this.thumbprint = jwkThumbprint(this.jwk);
985
+ }
986
+ /**
987
+ * Generate a fresh key. ES256 (P-256) by default; pass `'EdDSA'` for an
988
+ * Ed25519 key or `'RS256'` for a 2048-bit RSA key.
989
+ */
990
+ static generate(algorithm = "ES256") {
991
+ let privateKey;
992
+ switch (algorithm) {
993
+ case "ES256":
994
+ privateKey = (0, import_node_crypto5.generateKeyPairSync)("ec", { namedCurve: "P-256" }).privateKey;
995
+ break;
996
+ case "EdDSA":
997
+ privateKey = (0, import_node_crypto5.generateKeyPairSync)("ed25519").privateKey;
998
+ break;
999
+ case "RS256":
1000
+ privateKey = (0, import_node_crypto5.generateKeyPairSync)("rsa", { modulusLength: 2048 }).privateKey;
1001
+ break;
1002
+ default:
1003
+ throw new Error(`Unsupported DPoP algorithm: ${String(algorithm)}`);
1004
+ }
1005
+ return new _DpopProofSigner({ privateKey });
1006
+ }
1007
+ /** The private key as PKCS#8 PEM, for your secret store. */
1008
+ get privateKeyPem() {
1009
+ return this.key.export({ type: "pkcs8", format: "pem" }).toString();
1010
+ }
1011
+ /** Create one proof JWT. See the file comment for the claims. */
1012
+ createProof(input) {
1013
+ const method = input.method.toUpperCase();
1014
+ const htu = (0, import_shared4.dpopHtu)(input.url);
1015
+ const nonce = input.nonce ?? this.getNonce(input.url);
1016
+ const header = { typ: "dpop+jwt", alg: this.algorithm, jwk: this.jwk };
1017
+ const claims = {
1018
+ jti: (0, import_node_crypto5.randomBytes)(24).toString("base64url"),
1019
+ htm: method,
1020
+ htu,
1021
+ iat: this.now()
1022
+ };
1023
+ if (input.accessToken) claims.ath = dpopAth(input.accessToken);
1024
+ if (nonce) claims.nonce = nonce;
1025
+ const signingInput = `${b64url2(JSON.stringify(header))}.${b64url2(JSON.stringify(claims))}`;
1026
+ const signature = signJws(this.algorithm, Buffer.from(signingInput, "utf8"), this.key);
1027
+ return `${signingInput}.${signature.toString("base64url")}`;
1028
+ }
1029
+ /** Remember the latest server nonce for the origin of `url`. */
1030
+ setNonce(url, nonce) {
1031
+ this.nonces.set(originOf(url), nonce);
1032
+ }
1033
+ /** The remembered nonce for the origin of `url`, if any. */
1034
+ getNonce(url) {
1035
+ return this.nonces.get(originOf(url));
1036
+ }
1037
+ /** Forget every remembered nonce. */
1038
+ clearNonces() {
1039
+ this.nonces.clear();
1040
+ }
1041
+ };
1042
+ function dpopAth(accessToken) {
1043
+ return (0, import_node_crypto5.createHash)("sha256").update(accessToken, "ascii").digest("base64url");
1044
+ }
1045
+ function signJws(alg, data, key) {
1046
+ switch (alg) {
1047
+ case "ES256":
1048
+ return (0, import_node_crypto5.sign)("sha256", data, { key, dsaEncoding: "ieee-p1363" });
1049
+ case "EdDSA":
1050
+ return (0, import_node_crypto5.sign)(null, data, key);
1051
+ case "RS256":
1052
+ return (0, import_node_crypto5.sign)("sha256", data, key);
1053
+ default:
1054
+ throw new Error(`Unsupported DPoP algorithm: ${String(alg)}`);
1055
+ }
1056
+ }
1057
+ function algorithmFor(key) {
1058
+ switch (key.asymmetricKeyType) {
1059
+ case "ec": {
1060
+ const curve = key.asymmetricKeyDetails?.namedCurve;
1061
+ if (curve !== "prime256v1" && curve !== "P-256") {
1062
+ throw new Error(`DPoP EC keys must use P-256 (got ${String(curve)})`);
1063
+ }
1064
+ return "ES256";
1065
+ }
1066
+ case "ed25519":
1067
+ return "EdDSA";
1068
+ case "rsa":
1069
+ return "RS256";
1070
+ default:
1071
+ throw new Error(`Unsupported DPoP key type: ${String(key.asymmetricKeyType)}`);
1072
+ }
1073
+ }
1074
+ function publicMembers(jwk) {
1075
+ const out = { kty: jwk.kty };
1076
+ for (const member of ["crv", "x", "y", "n", "e"]) {
1077
+ if (typeof jwk[member] === "string") out[member] = jwk[member];
1078
+ }
1079
+ return out;
1080
+ }
1081
+ function originOf(url) {
1082
+ return new URL(url).origin;
1083
+ }
1084
+ function b64url2(text) {
1085
+ return Buffer.from(text, "utf8").toString("base64url");
1086
+ }
1087
+
1088
+ // src/index.ts
1089
+ var import_shared7 = require("@lumoauth/shared");
1090
+
1091
+ // src/attest.ts
1092
+ var import_shared5 = require("@lumoauth/shared");
1093
+ function envVar3(name) {
1094
+ return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
1095
+ }
1096
+ async function attestWorkload(options) {
1097
+ const baseUrl = (options.baseUrl ?? envVar3("LUMOAUTH_URL") ?? "https://app.lumoauth.dev").replace(/\/+$/, "");
1098
+ const orgId = options.orgId ?? envVar3("LUMOAUTH_ORG_ID") ?? "";
1099
+ if (!orgId) {
1100
+ throw new import_shared5.LumoAuthConfigError("attestWorkload requires orgId (or LUMOAUTH_ORG_ID).");
1101
+ }
1102
+ if (!options.agentId || !options.attestationToken) {
1103
+ throw new import_shared5.LumoAuthConfigError("attestWorkload requires agentId and attestationToken.");
1104
+ }
1105
+ const url = `${baseUrl}/orgs/${encodeURIComponent(orgId)}/api/v1/agents/${encodeURIComponent(options.agentId)}/attest`;
1106
+ const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
1107
+ const init = {
1108
+ method: "POST",
1109
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
1110
+ body: JSON.stringify({ attestation_token: options.attestationToken })
1111
+ };
1112
+ let res;
1113
+ try {
1114
+ res = options.dpop ? await (0, import_shared5.fetchWithDpop)(fetchFn, url, init, options.dpop) : await fetchFn(url, init);
1115
+ } catch (error) {
1116
+ throw new import_shared5.LumoAuthNetworkError(
1117
+ `Agent attestation failed: ${error instanceof Error ? error.message : String(error)}`,
1118
+ error
1119
+ );
1120
+ }
1121
+ const body = await res.json().catch(() => ({}));
1122
+ if (!res.ok || typeof body.access_token !== "string") {
1123
+ throw new import_shared5.LumoAuthApiError(
1124
+ typeof body.error_description === "string" ? body.error_description : `Agent attestation failed (HTTP ${res.status})`,
1125
+ typeof body.error === "string" ? body.error : "ATTESTATION_ERROR",
1126
+ res.status,
1127
+ body
1128
+ );
1129
+ }
1130
+ return {
1131
+ accessToken: body.access_token,
1132
+ tokenType: typeof body.token_type === "string" ? body.token_type : "Bearer",
1133
+ expiresIn: typeof body.expires_in === "number" ? body.expires_in : null,
1134
+ scope: typeof body.scope === "string" ? body.scope : null,
1135
+ identity: typeof body.identity === "object" && body.identity !== null ? body.identity : {}
1136
+ };
1137
+ }
1138
+
1139
+ // src/access-token.ts
1140
+ var import_node_crypto6 = require("crypto");
1141
+ var import_shared6 = require("@lumoauth/shared");
1142
+ var AccessTokenError = class extends import_shared6.LumoAuthError {
1143
+ constructor(message, code, statusCode = 401) {
1144
+ super(message, code, statusCode);
1145
+ this.name = "AccessTokenError";
1146
+ }
1147
+ };
1148
+ var AT_JWT_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
1149
+ var DPOP_PROOF_TYP = "dpop+jwt";
1150
+ var DPOP_IAT_FUTURE_SECONDS = 60;
1151
+ var DPOP_IAT_PAST_SECONDS = 300;
1152
+ var DPOP_JTI_TTL_SECONDS = 300;
1153
+ var DPOP_JTI_MIN_LENGTH = 16;
1154
+ var JWKS_REFETCH_INTERVAL_MS = 3e4;
1155
+ var JWS_VERIFIERS2 = {
1156
+ RS256: (d, k, s) => (0, import_node_crypto6.verify)("sha256", d, k, s),
1157
+ RS384: (d, k, s) => (0, import_node_crypto6.verify)("sha384", d, k, s),
1158
+ RS512: (d, k, s) => (0, import_node_crypto6.verify)("sha512", d, k, s),
1159
+ PS256: (d, k, s) => (0, import_node_crypto6.verify)("sha256", d, pss2(k), s),
1160
+ PS384: (d, k, s) => (0, import_node_crypto6.verify)("sha384", d, pss2(k), s),
1161
+ PS512: (d, k, s) => (0, import_node_crypto6.verify)("sha512", d, pss2(k), s),
1162
+ ES256: (d, k, s) => (0, import_node_crypto6.verify)("sha256", d, p13632(k), s),
1163
+ ES384: (d, k, s) => (0, import_node_crypto6.verify)("sha384", d, p13632(k), s),
1164
+ ES512: (d, k, s) => (0, import_node_crypto6.verify)("sha512", d, p13632(k), s),
1165
+ EdDSA: (d, k, s) => (0, import_node_crypto6.verify)(null, d, k, s)
1166
+ };
1167
+ var DPOP_ALG_KEYS = {
1168
+ ES256: { kty: "EC", crv: "P-256" },
1169
+ ES384: { kty: "EC", crv: "P-384" },
1170
+ ES512: { kty: "EC", crv: "P-521" },
1171
+ RS256: { kty: "RSA" },
1172
+ RS384: { kty: "RSA" },
1173
+ RS512: { kty: "RSA" },
1174
+ PS256: { kty: "RSA" },
1175
+ PS384: { kty: "RSA" },
1176
+ PS512: { kty: "RSA" },
1177
+ EdDSA: { kty: "OKP", crv: "Ed25519" }
1178
+ };
1179
+ function pss2(key) {
1180
+ return { key, padding: import_node_crypto6.constants.RSA_PKCS1_PSS_PADDING, saltLength: import_node_crypto6.constants.RSA_PSS_SALTLEN_DIGEST };
1181
+ }
1182
+ function p13632(key) {
1183
+ return { key, dsaEncoding: "ieee-p1363" };
1184
+ }
1185
+ var JwksCache = class {
1186
+ constructor(fetchFn) {
1187
+ this.fetchFn = fetchFn;
1188
+ this.entries = /* @__PURE__ */ new Map();
1189
+ }
1190
+ /**
1191
+ * Find `kid` in the issuer's JWKS. An unknown `kid` triggers one refetch
1192
+ * (a key rotation); repeated misses refetch at most every 30 s, so a
1193
+ * stream of bogus tokens cannot hammer the JWKS endpoint.
1194
+ */
1195
+ async find(issuer, kid, fetchFn) {
1196
+ const doFetch = fetchFn ?? this.fetchFn ?? globalThis.fetch;
1197
+ let entry = this.entries.get(issuer);
1198
+ if (!entry) {
1199
+ entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: 0 };
1200
+ this.entries.set(issuer, entry);
1201
+ }
1202
+ let jwk = entry.keys.find((k) => k.kid === kid);
1203
+ if (!jwk && Date.now() - entry.missRefetchAt >= JWKS_REFETCH_INTERVAL_MS) {
1204
+ entry = { keys: await fetchJwks(issuer, doFetch), missRefetchAt: Date.now() };
1205
+ this.entries.set(issuer, entry);
1206
+ jwk = entry.keys.find((k) => k.kid === kid);
1207
+ }
1208
+ return jwk;
1209
+ }
1210
+ /** Drop the cached keys of one issuer, or of all when omitted. */
1211
+ clear(issuer) {
1212
+ if (issuer) this.entries.delete(issuer);
1213
+ else this.entries.clear();
1214
+ }
1215
+ };
1216
+ async function fetchJwks(issuer, doFetch) {
1217
+ const base = issuer.replace(/\/+$/, "");
1218
+ const discovery = await doFetch(`${base}/.well-known/openid-configuration`, {
1219
+ headers: { Accept: "application/json" }
1220
+ });
1221
+ if (!discovery.ok) {
1222
+ throw new AccessTokenError(`Failed to fetch issuer discovery (HTTP ${discovery.status})`, "jwks_fetch_failed", 503);
1223
+ }
1224
+ const metadata = await discovery.json();
1225
+ const jwksUri = typeof metadata.jwks_uri === "string" ? metadata.jwks_uri : `${base}/.well-known/jwks.json`;
1226
+ const response = await doFetch(jwksUri, { headers: { Accept: "application/json" } });
1227
+ if (!response.ok) {
1228
+ throw new AccessTokenError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, "jwks_fetch_failed", 503);
1229
+ }
1230
+ const jwks = await response.json();
1231
+ if (!Array.isArray(jwks.keys)) {
1232
+ throw new AccessTokenError("Issuer JWKS is malformed", "jwks_fetch_failed", 503);
1233
+ }
1234
+ return jwks.keys;
1235
+ }
1236
+ var sharedJwksCache = new JwksCache();
1237
+ var InMemoryDpopReplayCache = class {
1238
+ constructor(now = () => Date.now()) {
1239
+ this.now = now;
1240
+ this.seen = /* @__PURE__ */ new Map();
1241
+ }
1242
+ add(key, ttlSeconds) {
1243
+ const now = this.now();
1244
+ if (this.seen.size > 0 && this.seen.size % 256 === 0) this.prune(now);
1245
+ const expiresAt = this.seen.get(key);
1246
+ if (expiresAt !== void 0 && expiresAt > now) return false;
1247
+ this.seen.set(key, now + ttlSeconds * 1e3);
1248
+ return true;
1249
+ }
1250
+ prune(now) {
1251
+ for (const [key, expiresAt] of this.seen) {
1252
+ if (expiresAt <= now) this.seen.delete(key);
1253
+ }
1254
+ }
1255
+ };
1256
+ var sharedReplayCache = new InMemoryDpopReplayCache();
1257
+ function decodeSegment2(segment) {
1258
+ try {
1259
+ return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
1260
+ } catch {
1261
+ throw new AccessTokenError("Invalid JWT encoding", "invalid_token");
1262
+ }
1263
+ }
1264
+ function isObject(value) {
1265
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1266
+ }
1267
+ function parseAuthorizationHeader(header) {
1268
+ if (!header) return null;
1269
+ const match = /^\s*([A-Za-z][A-Za-z0-9+.-]*)\s+(\S+)\s*$/.exec(header);
1270
+ return match ? { scheme: match[1], token: match[2] } : null;
1271
+ }
1272
+ function accessTokenScopes(claims) {
1273
+ return typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [];
1274
+ }
1275
+ async function verifyAccessToken(token, options) {
1276
+ if (typeof token !== "string" || token === "") {
1277
+ throw new AccessTokenError("Missing access token", "invalid_token");
1278
+ }
1279
+ const parts = token.split(".");
1280
+ if (parts.length !== 3) {
1281
+ throw new AccessTokenError("Invalid JWT format", "invalid_token");
1282
+ }
1283
+ const header = decodeSegment2(parts[0]);
1284
+ const claims = decodeSegment2(parts[1]);
1285
+ if (!isObject(header) || !isObject(claims)) {
1286
+ throw new AccessTokenError("Invalid JWT format", "invalid_token");
1287
+ }
1288
+ if (typeof header.typ !== "string" || !AT_JWT_TYPES.has(header.typ)) {
1289
+ throw new AccessTokenError(`Unexpected token type: ${String(header.typ)}`, "invalid_token");
1290
+ }
1291
+ const alg = typeof header.alg === "string" ? header.alg : "";
1292
+ const kid = typeof header.kid === "string" ? header.kid : "";
1293
+ if (!alg || !kid) {
1294
+ throw new AccessTokenError("Missing kid or alg in JOSE header", "invalid_token");
1295
+ }
1296
+ const verifier = JWS_VERIFIERS2[alg];
1297
+ if (!verifier) {
1298
+ throw new AccessTokenError(`Disallowed JWS algorithm: ${alg}`, "invalid_token");
1299
+ }
1300
+ if (claims.iss !== options.issuer) {
1301
+ throw new AccessTokenError("Untrusted issuer", "invalid_token");
1302
+ }
1303
+ let jwk;
1304
+ if (options.jwks) {
1305
+ jwk = options.jwks.keys.find((k) => k.kid === kid);
1306
+ } else {
1307
+ const cache = options.jwksCache ?? sharedJwksCache;
1308
+ jwk = await cache.find(options.issuer, kid, options.fetch);
1309
+ }
1310
+ if (!jwk) {
1311
+ throw new AccessTokenError(`Key not found: kid=${kid}`, "invalid_token");
1312
+ }
1313
+ assertAlgMatchesKey2(alg, jwk);
1314
+ const publicKey = (0, import_node_crypto6.createPublicKey)({ key: jwk, format: "jwk" });
1315
+ const data = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
1316
+ const signature = Buffer.from(parts[2], "base64url");
1317
+ if (!verifier(data, publicKey, signature)) {
1318
+ throw new AccessTokenError("Signature verification failed", "invalid_token");
1319
+ }
1320
+ const now = Math.floor(Date.now() / 1e3);
1321
+ const skew = options.clockSkew ?? 60;
1322
+ if (typeof claims.exp !== "number" || claims.exp < now - skew) {
1323
+ throw new AccessTokenError("Access token expired", "invalid_token");
1324
+ }
1325
+ if (claims.nbf !== void 0 && (typeof claims.nbf !== "number" || claims.nbf > now + skew)) {
1326
+ throw new AccessTokenError("Access token not yet valid", "invalid_token");
1327
+ }
1328
+ const aud = claims.aud;
1329
+ const audiences = typeof aud === "string" ? [aud] : Array.isArray(aud) ? aud : [];
1330
+ if (!audiences.includes(options.resource)) {
1331
+ throw new AccessTokenError("Invalid audience", "invalid_token");
1332
+ }
1333
+ if (typeof claims.sub !== "string" || claims.sub === "") {
1334
+ throw new AccessTokenError("Missing sub claim", "invalid_token");
1335
+ }
1336
+ if (claims.token_use === "test") {
1337
+ throw new AccessTokenError("Test tokens are not accepted by resource servers", "invalid_token");
1338
+ }
1339
+ const cnf = isObject(claims.cnf) ? claims.cnf : void 0;
1340
+ const jkt = typeof cnf?.jkt === "string" ? cnf.jkt : void 0;
1341
+ if (jkt) {
1342
+ await verifyDpopBinding(token, jkt, options);
1343
+ } else if (options.requireDpop) {
1344
+ throw new AccessTokenError("Access token is not DPoP-bound", "invalid_token");
1345
+ } else if (options.dpop?.authorizationScheme && options.dpop.authorizationScheme.toLowerCase() === import_shared6.DPOP_SCHEME.toLowerCase()) {
1346
+ throw new AccessTokenError("Access token is not DPoP-bound but was presented with the DPoP scheme", "invalid_token");
1347
+ }
1348
+ return claims;
1349
+ }
1350
+ async function verifyDpopBinding(token, jkt, options) {
1351
+ const incoming = options.dpop;
1352
+ if (!incoming) {
1353
+ throw new AccessTokenError(
1354
+ "Access token is DPoP-bound: pass the incoming request (method, url, proof, authorizationScheme) in `dpop`",
1355
+ "invalid_dpop_proof"
1356
+ );
1357
+ }
1358
+ if ((incoming.authorizationScheme ?? "").toLowerCase() !== import_shared6.DPOP_SCHEME.toLowerCase()) {
1359
+ throw new AccessTokenError("DPoP-bound access token must be presented with the DPoP scheme", "invalid_token");
1360
+ }
1361
+ if (!incoming.proof) {
1362
+ throw new AccessTokenError("DPoP proof required for sender-constrained token", "invalid_dpop_proof");
1363
+ }
1364
+ const proof = await verifyDpopProof(incoming.proof, {
1365
+ method: incoming.method,
1366
+ url: incoming.url,
1367
+ accessToken: token,
1368
+ nonce: incoming.nonce,
1369
+ replayCache: options.replayCache
1370
+ });
1371
+ if (proof.thumbprint !== jkt) {
1372
+ throw new AccessTokenError("DPoP key does not match token binding", "invalid_dpop_proof");
1373
+ }
1374
+ }
1375
+ function assertAlgMatchesKey2(alg, jwk) {
1376
+ const compatible = jwk.kty === "RSA" && (alg.startsWith("RS") || alg.startsWith("PS")) || jwk.kty === "EC" && alg.startsWith("ES") || jwk.kty === "OKP" && alg === "EdDSA";
1377
+ if (!compatible) {
1378
+ throw new AccessTokenError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, "invalid_token");
1379
+ }
1380
+ if (jwk.alg && jwk.alg !== alg) {
1381
+ throw new AccessTokenError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, "invalid_token");
1382
+ }
1383
+ }
1384
+ async function verifyDpopProof(proof, options) {
1385
+ const parts = proof.split(".");
1386
+ if (parts.length !== 3) {
1387
+ throw new AccessTokenError("Invalid DPoP proof format", "invalid_dpop_proof");
1388
+ }
1389
+ let header;
1390
+ let claims;
1391
+ try {
1392
+ header = decodeSegment2(parts[0]);
1393
+ claims = decodeSegment2(parts[1]);
1394
+ } catch {
1395
+ throw new AccessTokenError("Invalid DPoP proof encoding", "invalid_dpop_proof");
1396
+ }
1397
+ if (!isObject(header) || !isObject(claims)) {
1398
+ throw new AccessTokenError("Invalid DPoP proof format", "invalid_dpop_proof");
1399
+ }
1400
+ if (header.typ !== DPOP_PROOF_TYP) {
1401
+ throw new AccessTokenError("DPoP proof typ must be dpop+jwt", "invalid_dpop_proof");
1402
+ }
1403
+ const alg = typeof header.alg === "string" ? header.alg : "";
1404
+ const expectedKey = DPOP_ALG_KEYS[alg];
1405
+ if (!expectedKey) {
1406
+ throw new AccessTokenError(`Disallowed DPoP proof algorithm: ${alg || "(none)"}`, "invalid_dpop_proof");
1407
+ }
1408
+ const jwk = header.jwk;
1409
+ if (!isObject(jwk) || typeof jwk.kty !== "string") {
1410
+ throw new AccessTokenError("DPoP proof is missing its jwk", "invalid_dpop_proof");
1411
+ }
1412
+ if ("d" in jwk) {
1413
+ throw new AccessTokenError("DPoP proof jwk must not carry private members", "invalid_dpop_proof");
1414
+ }
1415
+ if (jwk.kty !== expectedKey.kty || expectedKey.crv && jwk.crv !== expectedKey.crv) {
1416
+ throw new AccessTokenError(`DPoP proof jwk does not match ${alg}`, "invalid_dpop_proof");
1417
+ }
1418
+ if (typeof jwk.alg === "string" && jwk.alg !== alg) {
1419
+ throw new AccessTokenError("DPoP proof jwk alg does not match the header", "invalid_dpop_proof");
1420
+ }
1421
+ let publicKey;
1422
+ try {
1423
+ publicKey = (0, import_node_crypto6.createPublicKey)({ key: jwk, format: "jwk" });
1424
+ } catch {
1425
+ throw new AccessTokenError("DPoP proof jwk is not a valid public key", "invalid_dpop_proof");
1426
+ }
1427
+ const data = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
1428
+ const signature = Buffer.from(parts[2], "base64url");
1429
+ let valid = false;
1430
+ try {
1431
+ valid = JWS_VERIFIERS2[alg](data, publicKey, signature);
1432
+ } catch {
1433
+ valid = false;
1434
+ }
1435
+ if (!valid) {
1436
+ throw new AccessTokenError("DPoP proof signature verification failed", "invalid_dpop_proof");
1437
+ }
1438
+ if (typeof claims.htm !== "string" || claims.htm.toUpperCase() !== options.method.toUpperCase()) {
1439
+ throw new AccessTokenError("DPoP proof htm does not match the request method", "invalid_dpop_proof");
1440
+ }
1441
+ if (typeof claims.htu !== "string" || !htuMatches(claims.htu, options.url)) {
1442
+ throw new AccessTokenError("DPoP proof htu does not match the request URL", "invalid_dpop_proof");
1443
+ }
1444
+ const now = options.now ? options.now() : Math.floor(Date.now() / 1e3);
1445
+ if (typeof claims.iat !== "number" || claims.iat > now + DPOP_IAT_FUTURE_SECONDS || claims.iat < now - DPOP_IAT_PAST_SECONDS) {
1446
+ throw new AccessTokenError("DPoP proof iat is outside the accepted window", "invalid_dpop_proof");
1447
+ }
1448
+ if (typeof claims.jti !== "string" || claims.jti.length < DPOP_JTI_MIN_LENGTH) {
1449
+ throw new AccessTokenError("DPoP proof jti is missing or too short", "invalid_dpop_proof");
1450
+ }
1451
+ if (options.nonce !== void 0 && claims.nonce !== options.nonce) {
1452
+ throw new AccessTokenError("DPoP proof nonce does not match", "invalid_dpop_proof");
1453
+ }
1454
+ if (options.accessToken !== void 0) {
1455
+ const expectedAth = (0, import_node_crypto6.createHash)("sha256").update(options.accessToken, "ascii").digest("base64url");
1456
+ if (claims.ath !== expectedAth) {
1457
+ throw new AccessTokenError("DPoP proof ath does not match the access token", "invalid_dpop_proof");
1458
+ }
1459
+ }
1460
+ const thumbprint = jwkThumbprint(jwk);
1461
+ const cache = options.replayCache ?? sharedReplayCache;
1462
+ if (!await cache.add(`${thumbprint}:${claims.jti}`, DPOP_JTI_TTL_SECONDS)) {
1463
+ throw new AccessTokenError("DPoP proof jti was already used", "invalid_dpop_proof");
1464
+ }
1465
+ return { jwk, thumbprint, claims };
1466
+ }
1467
+ function htuMatches(htu, requestUrl) {
1468
+ try {
1469
+ return (0, import_shared6.dpopHtu)(htu) === (0, import_shared6.dpopHtu)(requestUrl);
1470
+ } catch {
1471
+ return false;
1472
+ }
1473
+ }
1474
+ function createAccessTokenVerifier(options) {
1475
+ const jwksCache = new JwksCache(options.fetch);
1476
+ const replayCache = options.replayCache ?? new InMemoryDpopReplayCache();
1477
+ const base = { ...options, jwksCache, replayCache };
1478
+ return {
1479
+ verify: (token, dpop) => verifyAccessToken(token, dpop ? { ...base, dpop } : base),
1480
+ verifyRequest: async (request) => {
1481
+ const authorization = parseAuthorizationHeader(headerValue(request.headers, "authorization"));
1482
+ if (!authorization) {
1483
+ throw new AccessTokenError("Missing or malformed Authorization header", "invalid_token");
1484
+ }
1485
+ if (!["bearer", "dpop"].includes(authorization.scheme.toLowerCase())) {
1486
+ throw new AccessTokenError(`Unsupported authorization scheme: ${authorization.scheme}`, "invalid_token");
1487
+ }
1488
+ return verifyAccessToken(authorization.token, {
1489
+ ...base,
1490
+ dpop: {
1491
+ method: request.method,
1492
+ url: request.url,
1493
+ proof: headerValue(request.headers, "dpop"),
1494
+ authorizationScheme: authorization.scheme,
1495
+ nonce: request.nonce
1496
+ }
1497
+ });
1498
+ },
1499
+ clearCache: () => jwksCache.clear()
1500
+ };
1501
+ }
1502
+ function headerValue(headers, name) {
1503
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
1504
+ return headers.get(name);
1505
+ }
1506
+ for (const [key, value] of Object.entries(headers)) {
1507
+ if (key.toLowerCase() === name) {
1508
+ if (Array.isArray(value)) return value[0] ?? null;
1509
+ return value ?? null;
1510
+ }
1511
+ }
1512
+ return null;
1513
+ }
1514
+
1515
+ // src/index.ts
1516
+ var import_shared8 = require("@lumoauth/shared");
738
1517
  // Annotate the CommonJS export names for ESM import in node:
739
1518
  0 && (module.exports = {
740
1519
  AAUTH_COVERED_COMPONENTS,
741
1520
  AAuthClient,
742
1521
  AAuthError,
1522
+ AccessTokenError,
1523
+ CLIENT_ASSERTION_TYP,
1524
+ CLIENT_ASSERTION_TYPE,
1525
+ ClientAssertionSigner,
1526
+ DPOP_NONCE_HEADER,
1527
+ DPOP_SCHEME,
1528
+ DpopProofSigner,
1529
+ InMemoryDpopReplayCache,
1530
+ JwksCache,
743
1531
  LumoAgent,
744
1532
  LumoAuthApiError,
745
1533
  LumoAuthApprovalDeniedError,
@@ -754,17 +1542,30 @@ var import_shared4 = require("@lumoauth/shared");
754
1542
  LumoAuthPermissionDeniedError,
755
1543
  LumoAuthRateLimitError,
756
1544
  LumoAuthValidationError,
1545
+ MAX_ASSERTION_LIFETIME_SECONDS,
1546
+ USE_DPOP_NONCE,
1547
+ accessTokenScopes,
1548
+ attestWorkload,
1549
+ buildDpopHeaders,
757
1550
  buildSignatureBase,
758
1551
  contentDigestSha256,
1552
+ createAccessTokenVerifier,
759
1553
  decodeJwt,
1554
+ dpopAth,
1555
+ dpopHtu,
1556
+ fetchWithDpop,
760
1557
  generateKeypair,
761
1558
  generateNonce,
1559
+ issuerFor,
762
1560
  jwkThumbprint,
1561
+ parseAuthorizationHeader,
763
1562
  publicJwkFromPrivateKey,
764
1563
  signRequest,
765
1564
  signSignatureBase,
766
1565
  signatureParams,
1566
+ verifyAccessToken,
767
1567
  verifyAuthToken,
1568
+ verifyDpopProof,
768
1569
  verifySignatureBase
769
1570
  });
770
1571
  //# sourceMappingURL=index.js.map