@lumoauth/agent 0.0.0-stage → 1.0.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.mjs ADDED
@@ -0,0 +1,717 @@
1
+ // src/agent.ts
2
+ import {
3
+ HttpClient,
4
+ AgentsModule,
5
+ ApprovalsModule,
6
+ DelegationModule,
7
+ JitModule,
8
+ McpModule,
9
+ LumoAuthApiError,
10
+ LumoAuthConfigError,
11
+ LumoAuthNetworkError,
12
+ ROUTES,
13
+ buildPath
14
+ } from "@lumoauth/shared";
15
+ function envVar(name) {
16
+ return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
17
+ }
18
+ var TOKEN_REFRESH_BUFFER_MS = 6e4;
19
+ var LumoAgent = class {
20
+ constructor(options = {}) {
21
+ this.token = null;
22
+ this.refreshPromise = null;
23
+ this.baseUrl = (options.baseUrl ?? envVar("LUMOAUTH_URL") ?? "https://app.lumoauth.dev").replace(/\/+$/, "");
24
+ this.orgId = options.orgId ?? envVar("LUMOAUTH_ORG_ID") ?? "";
25
+ this.clientId = options.clientId ?? envVar("AGENT_CLIENT_ID") ?? "";
26
+ this.clientSecret = options.clientSecret ?? envVar("AGENT_CLIENT_SECRET") ?? "";
27
+ this.scopes = options.scopes;
28
+ this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
29
+ if (!this.clientId || !this.clientSecret) {
30
+ throw new LumoAuthConfigError(
31
+ "Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET environment variables or pass clientId/clientSecret to the constructor."
32
+ );
33
+ }
34
+ const tokenProvider = () => this.getAccessToken();
35
+ const http = new HttpClient({
36
+ baseUrl: this.baseUrl,
37
+ token: tokenProvider,
38
+ timeout: options.timeout,
39
+ fetch: options.fetch
40
+ });
41
+ this.agents = new AgentsModule(http, this.orgId);
42
+ this.jit = new JitModule(http, this.orgId);
43
+ this.approvals = new ApprovalsModule(http, this.orgId);
44
+ this.mcp = new McpModule({
45
+ baseUrl: this.baseUrl,
46
+ orgId: this.orgId,
47
+ token: tokenProvider,
48
+ fetch: options.fetch
49
+ });
50
+ this.delegation = new DelegationModule({
51
+ baseUrl: this.baseUrl,
52
+ orgId: this.orgId,
53
+ clientId: this.clientId,
54
+ clientSecret: this.clientSecret,
55
+ redirectUri: options.redirectUri,
56
+ agentToken: tokenProvider,
57
+ fetch: options.fetch
58
+ });
59
+ }
60
+ // ── Authentication ────────────────────────────────────────────────
61
+ /**
62
+ * Authenticate with the client-credentials flow. Called automatically
63
+ * by every API method — invoke it directly only to fail fast at
64
+ * startup or to request non-default scopes.
65
+ */
66
+ async authenticate(scopes) {
67
+ const form = {
68
+ grant_type: "client_credentials",
69
+ client_id: this.clientId,
70
+ client_secret: this.clientSecret
71
+ };
72
+ const requested = scopes ?? this.scopes;
73
+ if (requested?.length) form.scope = requested.join(" ");
74
+ const url = `${this.baseUrl}${buildPath(ROUTES["oauth.token"].path, { orgId: this.requireOrgId() })}`;
75
+ let res;
76
+ try {
77
+ res = await this.fetchFn(url, {
78
+ method: "POST",
79
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
80
+ body: new URLSearchParams(form)
81
+ });
82
+ } catch (error) {
83
+ throw new LumoAuthNetworkError(
84
+ `Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,
85
+ error
86
+ );
87
+ }
88
+ const body = await res.json().catch(() => ({}));
89
+ if (!res.ok || typeof body.access_token !== "string") {
90
+ throw new LumoAuthApiError(
91
+ typeof body.error_description === "string" ? body.error_description : `Agent authentication failed (HTTP ${res.status})`,
92
+ typeof body.error === "string" ? body.error : "AUTHENTICATION_ERROR",
93
+ res.status,
94
+ body
95
+ );
96
+ }
97
+ const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 3600;
98
+ this.token = {
99
+ accessToken: body.access_token,
100
+ refreshAt: Date.now() + expiresIn * 1e3 - TOKEN_REFRESH_BUFFER_MS,
101
+ scopes: typeof body.scope === "string" ? body.scope.split(" ").filter(Boolean) : []
102
+ };
103
+ return this.token.accessToken;
104
+ }
105
+ /**
106
+ * The current access token, re-authenticating transparently when it is
107
+ * missing or within 60 s of expiry. Concurrent callers share one
108
+ * in-flight token request.
109
+ */
110
+ async getAccessToken() {
111
+ if (this.token && Date.now() < this.token.refreshAt) {
112
+ return this.token.accessToken;
113
+ }
114
+ this.refreshPromise ?? (this.refreshPromise = this.authenticate(
115
+ this.token?.scopes.length ? this.token.scopes : void 0
116
+ ).finally(() => {
117
+ this.refreshPromise = null;
118
+ }));
119
+ return this.refreshPromise;
120
+ }
121
+ /** Scopes granted by the last successful authentication. */
122
+ get tokenScopes() {
123
+ return this.token ? [...this.token.scopes] : [];
124
+ }
125
+ // ── Ask API & self-inspection (delegates to `agents`) ─────────────
126
+ /** Preflight check: is the agent authorised to perform `action`? */
127
+ async ask(action, context) {
128
+ return this.agents.ask(action, context);
129
+ }
130
+ /** Convenience wrapper: `true` when `action` is allowed. */
131
+ async isAllowed(action, context) {
132
+ return this.agents.isAllowed(action, context);
133
+ }
134
+ /** The agent's own identity, capabilities, and workspace. */
135
+ async getCurrentAgent() {
136
+ return this.agents.me();
137
+ }
138
+ /** The agent's declared capability slugs. */
139
+ async capabilities() {
140
+ return this.agents.capabilities();
141
+ }
142
+ /** The agent's budget policy (empty object when no policy is set). */
143
+ async budget() {
144
+ return this.agents.budget();
145
+ }
146
+ // ── Internal ──────────────────────────────────────────────────────
147
+ requireOrgId() {
148
+ if (!this.orgId) {
149
+ throw new LumoAuthConfigError(
150
+ "orgId is required \u2014 pass it to the LumoAgent constructor or set LUMOAUTH_ORG_ID."
151
+ );
152
+ }
153
+ return this.orgId;
154
+ }
155
+ };
156
+
157
+ // src/keys.ts
158
+ import { createHash, createPublicKey, createPrivateKey, generateKeyPairSync } from "crypto";
159
+ function generateKeypair(kid = "key-1") {
160
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
161
+ const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
162
+ const publicKeyPem = publicKey.export({ type: "spki", format: "pem" }).toString();
163
+ const rawJwk = publicKey.export({ format: "jwk" });
164
+ const jwk = {
165
+ kty: rawJwk.kty,
166
+ crv: rawJwk.crv,
167
+ x: rawJwk.x,
168
+ use: "sig",
169
+ kid
170
+ };
171
+ return { privateKeyPem, publicKeyPem, jwk, jwks: { keys: [jwk] } };
172
+ }
173
+ function jwkThumbprint(jwk) {
174
+ let canonical;
175
+ switch (jwk.kty) {
176
+ case "OKP":
177
+ canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });
178
+ break;
179
+ case "EC":
180
+ canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });
181
+ break;
182
+ case "RSA":
183
+ canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });
184
+ break;
185
+ default:
186
+ throw new Error(`Unsupported key type for thumbprint: ${jwk.kty}`);
187
+ }
188
+ return createHash("sha256").update(canonical, "utf8").digest("base64url");
189
+ }
190
+ function loadPrivateKey(pem) {
191
+ const key = createPrivateKey(pem);
192
+ if (key.asymmetricKeyType === "ed25519") {
193
+ return { key, type: "ed25519" };
194
+ }
195
+ if (key.asymmetricKeyType === "rsa" || key.asymmetricKeyType === "rsa-pss") {
196
+ return { key, type: "rsa" };
197
+ }
198
+ throw new Error(
199
+ `AAuth requires an Ed25519 or RSA private key (got ${String(key.asymmetricKeyType)}).`
200
+ );
201
+ }
202
+ function publicJwkFromPrivateKey(pem, kid) {
203
+ const priv = createPrivateKey(pem);
204
+ const pub = createPublicKey(priv);
205
+ const jwk = pub.export({ format: "jwk" });
206
+ if (kid) jwk.kid = kid;
207
+ return jwk;
208
+ }
209
+
210
+ // src/signing.ts
211
+ import {
212
+ constants,
213
+ createHash as createHash2,
214
+ randomBytes,
215
+ sign as cryptoSign,
216
+ verify as cryptoVerify
217
+ } from "crypto";
218
+ var AAUTH_COVERED_COMPONENTS = [
219
+ "@method",
220
+ "@authority",
221
+ "@path",
222
+ "signature-key",
223
+ "content-digest",
224
+ "content-type",
225
+ "authorization"
226
+ ];
227
+ var SIGNATURE_LABEL = "sig1";
228
+ function contentDigestSha256(body) {
229
+ const digest = createHash2("sha256").update(body).digest("base64");
230
+ return `sha-256=:${digest}:`;
231
+ }
232
+ function generateNonce() {
233
+ return randomBytes(16).toString("base64url");
234
+ }
235
+ function buildSignatureBase(components, values, created, nonce) {
236
+ const lines = components.map((c) => `"${c}": ${values[c] ?? ""}`);
237
+ lines.push(`"@signature-params": ${signatureParams(components, created, nonce)}`);
238
+ return lines.join("\n");
239
+ }
240
+ function signatureParams(components, created, nonce) {
241
+ const coveredList = components.map((c) => `"${c}"`).join(" ");
242
+ return `(${coveredList});created=${created};nonce="${nonce}"`;
243
+ }
244
+ function signSignatureBase(signatureBase, privateKey) {
245
+ const data = Buffer.from(signatureBase, "utf8");
246
+ let signature;
247
+ if (privateKey.asymmetricKeyType === "ed25519") {
248
+ signature = cryptoSign(null, data, privateKey);
249
+ } else {
250
+ signature = cryptoSign("sha512", data, {
251
+ key: privateKey,
252
+ padding: constants.RSA_PKCS1_PSS_PADDING,
253
+ saltLength: constants.RSA_PSS_SALTLEN_DIGEST
254
+ // 64 bytes for SHA-512
255
+ });
256
+ }
257
+ return signature.toString("base64url");
258
+ }
259
+ function verifySignatureBase(signatureBase, signatureB64url, publicKey) {
260
+ const data = Buffer.from(signatureBase, "utf8");
261
+ const sig = Buffer.from(signatureB64url, "base64url");
262
+ if (publicKey.asymmetricKeyType === "ed25519") {
263
+ return cryptoVerify(null, data, publicKey, sig);
264
+ }
265
+ return cryptoVerify("sha512", data, {
266
+ key: publicKey,
267
+ padding: constants.RSA_PKCS1_PSS_PADDING,
268
+ saltLength: constants.RSA_PSS_SALTLEN_DIGEST
269
+ }, sig);
270
+ }
271
+ function signRequest(privateKeyPem, method, url, options = {}) {
272
+ const { key } = loadPrivateKey(privateKeyPem);
273
+ const parsed = new URL(url);
274
+ const authority = parsed.host;
275
+ const path = parsed.pathname || "/";
276
+ const query = parsed.search;
277
+ const body = options.body ?? Buffer.alloc(0);
278
+ const contentType = options.contentType ?? "application/json";
279
+ const contentDigest = contentDigestSha256(body);
280
+ const created = options.created ?? Math.floor(Date.now() / 1e3);
281
+ const nonce = options.nonce ?? generateNonce();
282
+ const components = ["@method", "@authority", "@path"];
283
+ if (query !== "") components.push("@query");
284
+ components.push("signature-key", "content-digest", "content-type", "authorization");
285
+ const values = {
286
+ "@method": method.toUpperCase(),
287
+ "@authority": authority,
288
+ "@path": path,
289
+ "signature-key": options.signatureKey ?? "",
290
+ "content-digest": contentDigest,
291
+ "content-type": contentType,
292
+ authorization: options.authorization ?? ""
293
+ };
294
+ if (query !== "") values["@query"] = query;
295
+ const signatureBase = buildSignatureBase(components, values, created, nonce);
296
+ const signature = signSignatureBase(signatureBase, key);
297
+ const headers = {
298
+ "Content-Digest": contentDigest,
299
+ "Content-Type": contentType,
300
+ "Signature-Input": `${SIGNATURE_LABEL}=${signatureParams(components, created, nonce)}`,
301
+ Signature: `${SIGNATURE_LABEL}=:${signature}:`
302
+ };
303
+ if (options.agentToken) {
304
+ headers["Agent-Auth"] = `agent_token=${options.agentToken}`;
305
+ }
306
+ if (options.signatureKey) {
307
+ headers["Signature-Key"] = options.signatureKey;
308
+ }
309
+ return headers;
310
+ }
311
+
312
+ // src/verify.ts
313
+ import { constants as constants2, createPublicKey as createPublicKey2, verify as cryptoVerify2 } from "crypto";
314
+
315
+ // src/errors.ts
316
+ import { LumoAuthError } from "@lumoauth/shared";
317
+ var AAuthError = class extends LumoAuthError {
318
+ constructor(message, code, statusCode, body) {
319
+ super(message, code, statusCode);
320
+ this.body = body;
321
+ this.name = "AAuthError";
322
+ }
323
+ };
324
+
325
+ // src/verify.ts
326
+ var JWS_VERIFIERS = {
327
+ RS256: (d, k, s) => cryptoVerify2("sha256", d, k, s),
328
+ RS384: (d, k, s) => cryptoVerify2("sha384", d, k, s),
329
+ RS512: (d, k, s) => cryptoVerify2("sha512", d, k, s),
330
+ PS256: (d, k, s) => cryptoVerify2("sha256", d, pss(k), s),
331
+ PS384: (d, k, s) => cryptoVerify2("sha384", d, pss(k), s),
332
+ PS512: (d, k, s) => cryptoVerify2("sha512", d, pss(k), s),
333
+ ES256: (d, k, s) => cryptoVerify2("sha256", d, p1363(k), s),
334
+ ES384: (d, k, s) => cryptoVerify2("sha384", d, p1363(k), s),
335
+ ES512: (d, k, s) => cryptoVerify2("sha512", d, p1363(k), s),
336
+ EdDSA: (d, k, s) => cryptoVerify2(null, d, k, s)
337
+ };
338
+ function pss(key) {
339
+ return { key, padding: constants2.RSA_PKCS1_PSS_PADDING, saltLength: constants2.RSA_PSS_SALTLEN_DIGEST };
340
+ }
341
+ function p1363(key) {
342
+ return { key, dsaEncoding: "ieee-p1363" };
343
+ }
344
+ function decodeSegment(segment) {
345
+ return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
346
+ }
347
+ function decodeJwt(token) {
348
+ const parts = token.split(".");
349
+ if (parts.length !== 3) {
350
+ throw new AAuthError("Invalid JWT format", "invalid_token");
351
+ }
352
+ return {
353
+ header: decodeSegment(parts[0]),
354
+ claims: decodeSegment(parts[1])
355
+ };
356
+ }
357
+ async function verifyAuthToken(token, options) {
358
+ const parts = token.split(".");
359
+ if (parts.length !== 3) {
360
+ throw new AAuthError("Invalid JWT format", "invalid_token");
361
+ }
362
+ const header = decodeSegment(parts[0]);
363
+ const claims = decodeSegment(parts[1]);
364
+ if (header.typ !== "auth+jwt") {
365
+ throw new AAuthError(`Unexpected token type: ${String(header.typ)}`, "invalid_token");
366
+ }
367
+ const alg = typeof header.alg === "string" ? header.alg : "";
368
+ const kid = typeof header.kid === "string" ? header.kid : "";
369
+ if (!alg || !kid) {
370
+ throw new AAuthError("Missing kid or alg in JOSE header", "invalid_token");
371
+ }
372
+ const verifier = JWS_VERIFIERS[alg];
373
+ if (!verifier) {
374
+ throw new AAuthError(`Disallowed JWS algorithm: ${alg}`, "invalid_token");
375
+ }
376
+ if (claims.iss !== options.issuer) {
377
+ throw new AAuthError("Untrusted issuer", "invalid_token");
378
+ }
379
+ const jwks = options.jwks ?? await fetchIssuerJwks(options.issuer, options.fetch);
380
+ const jwk = jwks.keys.find((k) => k.kid === kid);
381
+ if (!jwk) {
382
+ throw new AAuthError(`Key not found: kid=${kid}`, "invalid_token");
383
+ }
384
+ assertAlgMatchesKey(alg, jwk);
385
+ const publicKey = createPublicKey2({ key: jwk, format: "jwk" });
386
+ const data = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
387
+ const signature = Buffer.from(parts[2], "base64url");
388
+ if (!verifier(data, publicKey, signature)) {
389
+ throw new AAuthError("Signature verification failed", "invalid_token");
390
+ }
391
+ const now = Math.floor(Date.now() / 1e3);
392
+ const skew = options.clockSkew ?? 0;
393
+ if (typeof claims.exp !== "number" || claims.exp < now - skew) {
394
+ throw new AAuthError("Auth token expired", "invalid_token");
395
+ }
396
+ if (claims.aud !== options.resource) {
397
+ throw new AAuthError("Invalid audience", "invalid_token");
398
+ }
399
+ const cnf = claims.cnf;
400
+ if (!cnf || !cnf.jwk) {
401
+ throw new AAuthError("Missing cnf.jwk claim", "invalid_token");
402
+ }
403
+ return claims;
404
+ }
405
+ function assertAlgMatchesKey(alg, jwk) {
406
+ const compatible = jwk.kty === "RSA" && (alg.startsWith("RS") || alg.startsWith("PS")) || jwk.kty === "EC" && alg.startsWith("ES") || jwk.kty === "OKP" && alg === "EdDSA";
407
+ if (!compatible) {
408
+ throw new AAuthError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, "invalid_token");
409
+ }
410
+ if (jwk.alg && jwk.alg !== alg) {
411
+ throw new AAuthError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, "invalid_token");
412
+ }
413
+ }
414
+ async function fetchIssuerJwks(issuer, fetchFn) {
415
+ const doFetch = fetchFn ?? globalThis.fetch;
416
+ const url = `${issuer.replace(/\/+$/, "")}/aauth/jwks.json`;
417
+ const response = await doFetch(url, { headers: { Accept: "application/json" } });
418
+ if (!response.ok) {
419
+ throw new AAuthError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, "jwks_fetch_failed", response.status);
420
+ }
421
+ const jwks = await response.json();
422
+ if (!Array.isArray(jwks.keys)) {
423
+ throw new AAuthError("Issuer JWKS is malformed", "jwks_fetch_failed");
424
+ }
425
+ return { keys: jwks.keys };
426
+ }
427
+
428
+ // src/client.ts
429
+ import { LumoAuthConfigError as LumoAuthConfigError2, LumoAuthNetworkError as LumoAuthNetworkError2, ROUTES as ROUTES2, buildPath as buildPath2 } from "@lumoauth/shared";
430
+ function envVar2(name) {
431
+ return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
432
+ }
433
+ var AAuthClient = class {
434
+ constructor(options) {
435
+ if (!options.agentIdentifier) {
436
+ throw new LumoAuthConfigError2("agentIdentifier is required");
437
+ }
438
+ if (!options.privateKeyPem) {
439
+ throw new LumoAuthConfigError2("privateKeyPem is required");
440
+ }
441
+ this.agentIdentifier = options.agentIdentifier;
442
+ this.privateKeyPem = options.privateKeyPem;
443
+ this.baseUrl = (options.baseUrl ?? envVar2("LUMOAUTH_URL") ?? "https://app.lumoauth.dev").replace(/\/+$/, "");
444
+ this.orgId = options.orgId ?? envVar2("LUMOAUTH_ORG_ID") ?? "";
445
+ this.kid = options.kid ?? "key-1";
446
+ this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
447
+ this.timeout = options.timeout ?? 3e4;
448
+ }
449
+ /** The organization's AAuth issuer URL: `{baseUrl}/orgs/{orgId}/api/v1`. */
450
+ get issuer() {
451
+ return `${this.baseUrl}/orgs/${this.orgId}/api/v1`;
452
+ }
453
+ /** The agent's public JWK derived from its private key. */
454
+ get publicJwk() {
455
+ return publicJwkFromPrivateKey(this.privateKeyPem, this.kid);
456
+ }
457
+ /** RFC 7638 thumbprint of the agent's public key (the `jkt` binding value). */
458
+ get publicJwkThumbprint() {
459
+ return jwkThumbprint(this.publicJwk);
460
+ }
461
+ // ─── HTTP Message Signing ─────────────────────────────────────────
462
+ /**
463
+ * Create RFC 9421 signature headers for a request per the AAuth profile.
464
+ * See `signRequest()` in `signing.ts` for the exact contract.
465
+ */
466
+ signRequest(method, url, options = {}) {
467
+ return signRequest(this.privateKeyPem, method, url, options);
468
+ }
469
+ // ─── Token flows ──────────────────────────────────────────────────
470
+ /**
471
+ * Request an auth token (`request_type=auth` — direct authorization).
472
+ *
473
+ * Presents the resource token in the body and the agent token in the
474
+ * `Agent-Auth` header, signed with the agent's key. If the server
475
+ * requires user consent it returns `{ authorizationRequired: true,
476
+ * requestToken, authorizationUri }` — redirect the user, then call
477
+ * `exchangeCode()` with the code delivered to your `redirectUri`.
478
+ */
479
+ async requestAuthToken(params) {
480
+ this.requireAgentToken(params.agentToken);
481
+ const body = {
482
+ request_type: "auth",
483
+ resource_token: params.resourceToken
484
+ };
485
+ if (params.scope) body.scope = params.scope;
486
+ if (params.redirectUri) body.redirect_uri = params.redirectUri;
487
+ const data = await this.tokenRequest(body, params.agentToken);
488
+ if (!data.auth_token && (data.request_token || data.authorization_uri || data.auth_url)) {
489
+ return {
490
+ authorizationRequired: true,
491
+ requestToken: data.request_token ?? "",
492
+ authorizationUri: data.authorization_uri ?? data.auth_url ?? "",
493
+ expiresIn: data.expires_in
494
+ };
495
+ }
496
+ return this.mapTokenResponse(data);
497
+ }
498
+ /**
499
+ * Build the user-consent URL for a pending request token
500
+ * (`GET {issuer}/aauth/agent/auth?request_token=…`). Prefer the
501
+ * `authorizationUri` returned by `requestAuthToken()` when present.
502
+ */
503
+ buildConsentUrl(requestToken) {
504
+ return `${this.routeUrl("aauth.agentAuth")}?request_token=${encodeURIComponent(requestToken)}`;
505
+ }
506
+ /**
507
+ * Exchange an authorization code for tokens (`request_type=code`) after
508
+ * user consent. `redirectUri` must be the exact URI the code was
509
+ * delivered to.
510
+ */
511
+ async exchangeCode(params) {
512
+ this.requireAgentToken(params.agentToken);
513
+ const data = await this.tokenRequest(
514
+ { request_type: "code", code: params.code, redirect_uri: params.redirectUri },
515
+ params.agentToken
516
+ );
517
+ return this.mapTokenResponse(data);
518
+ }
519
+ /**
520
+ * Multi-hop token exchange (`request_type=exchange`): trade an upstream
521
+ * auth token plus a downstream resource token for a new auth token with
522
+ * an `act` actor chain. Requires token exchange to be enabled for the
523
+ * agent.
524
+ */
525
+ async exchangeToken(params) {
526
+ this.requireAgentToken(params.agentToken);
527
+ const data = await this.tokenRequest(
528
+ {
529
+ request_type: "exchange",
530
+ auth_token: params.authToken,
531
+ resource_token: params.resourceToken
532
+ },
533
+ params.agentToken
534
+ );
535
+ return this.mapTokenResponse(data);
536
+ }
537
+ /**
538
+ * Refresh an auth token (`request_type=refresh`). A fresh resource token
539
+ * for the target resource is required; scopes requested via the resource
540
+ * token must be a subset of the original grant. Refresh tokens are not
541
+ * rotated.
542
+ */
543
+ async refresh(params) {
544
+ this.requireAgentToken(params.agentToken);
545
+ const body = {
546
+ request_type: "refresh",
547
+ refresh_token: params.refreshToken,
548
+ resource_token: params.resourceToken
549
+ };
550
+ if (params.scope) body.scope = params.scope;
551
+ const data = await this.tokenRequest(body, params.agentToken);
552
+ return this.mapTokenResponse(data);
553
+ }
554
+ /**
555
+ * Revoke an auth token (by its `jti`) or a refresh token (by value).
556
+ * Always resolves `{ revoked: true }` — the server does not reveal
557
+ * whether the token existed.
558
+ */
559
+ async revoke(params) {
560
+ this.requireAgentToken(params.agentToken);
561
+ const url = this.routeUrl("aauth.tokenRevoke");
562
+ const data = await this.signedPost(url, {
563
+ token: params.token,
564
+ token_type: params.tokenType ?? "auth_token"
565
+ }, params.agentToken);
566
+ return { revoked: Boolean(data.revoked ?? true) };
567
+ }
568
+ // ─── Signed requests to protected resources ───────────────────────
569
+ /**
570
+ * Make a signed, authenticated request to a protected resource.
571
+ *
572
+ * Carries the auth token as `Authorization: Bearer …` **and** an RFC
573
+ * 9421 signature proving possession of the key bound in the token's
574
+ * `cnf.jwk`. The signature covers the `authorization` component, so the
575
+ * resource can verify both together.
576
+ *
577
+ * Returns the raw `fetch` Response.
578
+ */
579
+ async signedRequest(method, url, options) {
580
+ const bodyStr = options.data != null ? JSON.stringify(options.data) : "";
581
+ const authorization = `Bearer ${options.authToken}`;
582
+ const sigHeaders = this.signRequest(method, url, { body: bodyStr, authorization });
583
+ return this.doFetch(url, {
584
+ method: method.toUpperCase(),
585
+ headers: { Authorization: authorization, ...sigHeaders, ...options.headers ?? {} },
586
+ body: bodyStr !== "" ? bodyStr : void 0
587
+ });
588
+ }
589
+ // ─── Verification (resource-server side) ──────────────────────────
590
+ /**
591
+ * Verify an `auth+jwt` against this organization's issuer JWKS.
592
+ * See `verifyAuthToken()` for details (PoP still required!).
593
+ */
594
+ async verifyAuthToken(token, options) {
595
+ return verifyAuthToken(token, {
596
+ issuer: options.issuer ?? this.issuer,
597
+ fetch: this.fetchFn,
598
+ ...options
599
+ });
600
+ }
601
+ // ─── Discovery ────────────────────────────────────────────────────
602
+ /** Fetch `{issuer}/.well-known/aauth-issuer`. */
603
+ async discoverIssuer() {
604
+ return this.getJson(this.routeUrl("aauth.issuerMetadata"));
605
+ }
606
+ /** Fetch `{issuer}/.well-known/aauth-agent` — metadata for all active agents. */
607
+ async discoverAgents() {
608
+ return this.getJson(this.routeUrl("aauth.agentMetadata"));
609
+ }
610
+ /** Fetch `{resourceUrl}/.well-known/aauth-resource` from a resource server. */
611
+ async discoverResource(resourceUrl) {
612
+ const base = resourceUrl.replace(/\/+$/, "");
613
+ return this.getJson(`${base}/.well-known/aauth-resource`);
614
+ }
615
+ // ─── Internals ────────────────────────────────────────────────────
616
+ requireAgentToken(agentToken) {
617
+ if (!agentToken) {
618
+ throw new AAuthError(
619
+ "agentToken is required \u2014 the /agent/token endpoint authenticates the agent via the Agent-Auth header.",
620
+ "invalid_request"
621
+ );
622
+ }
623
+ }
624
+ tokenUrl() {
625
+ return this.routeUrl("aauth.agentToken");
626
+ }
627
+ /** Absolute URL for an org-scoped route from the shared registry. */
628
+ routeUrl(name) {
629
+ return `${this.baseUrl}${buildPath2(ROUTES2[name].path, { orgId: this.orgId })}`;
630
+ }
631
+ async tokenRequest(body, agentToken) {
632
+ return await this.signedPost(this.tokenUrl(), body, agentToken);
633
+ }
634
+ async signedPost(url, body, agentToken) {
635
+ if (!this.orgId) {
636
+ throw new LumoAuthConfigError2("orgId is required for AAuth token operations");
637
+ }
638
+ const bodyStr = JSON.stringify(body);
639
+ const headers = this.signRequest("POST", url, { body: bodyStr, agentToken });
640
+ const response = await this.doFetch(url, { method: "POST", headers, body: bodyStr });
641
+ const text = await response.text();
642
+ let parsed;
643
+ try {
644
+ parsed = JSON.parse(text);
645
+ } catch {
646
+ parsed = void 0;
647
+ }
648
+ if (!response.ok) {
649
+ const err = parsed ?? {};
650
+ throw new AAuthError(
651
+ err.error_description ?? err.error ?? `AAuth request failed: HTTP ${response.status}`,
652
+ err.error ?? "aauth_error",
653
+ response.status,
654
+ parsed ?? text
655
+ );
656
+ }
657
+ return parsed ?? {};
658
+ }
659
+ mapTokenResponse(data) {
660
+ if (!data.auth_token) {
661
+ throw new AAuthError("Token response missing auth_token", "invalid_response", void 0, data);
662
+ }
663
+ const result = {
664
+ requestType: data.request_type ?? "auth",
665
+ authToken: data.auth_token,
666
+ expiresIn: data.expires_in ?? 0,
667
+ tokenType: data.token_type ?? "auth+jwt"
668
+ };
669
+ if (data.refresh_token) result.refreshToken = data.refresh_token;
670
+ return result;
671
+ }
672
+ async getJson(url) {
673
+ const response = await this.doFetch(url, { headers: { Accept: "application/json" } });
674
+ if (!response.ok) {
675
+ throw new AAuthError(`Discovery request failed: HTTP ${response.status}`, "discovery_failed", response.status);
676
+ }
677
+ return await response.json();
678
+ }
679
+ async doFetch(url, init) {
680
+ const controller = new AbortController();
681
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
682
+ try {
683
+ return await this.fetchFn(url, { ...init, signal: controller.signal });
684
+ } catch (error) {
685
+ if (error instanceof DOMException && error.name === "AbortError") {
686
+ throw new LumoAuthNetworkError2(`Request to ${url} timed out after ${this.timeout}ms`, error);
687
+ }
688
+ throw new LumoAuthNetworkError2(
689
+ `Network request to ${url} failed: ${error instanceof Error ? error.message : String(error)}`,
690
+ error
691
+ );
692
+ } finally {
693
+ clearTimeout(timeoutId);
694
+ }
695
+ }
696
+ };
697
+ /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */
698
+ AAuthClient.generateKeypair = generateKeypair;
699
+ export {
700
+ AAUTH_COVERED_COMPONENTS,
701
+ AAuthClient,
702
+ AAuthError,
703
+ LumoAgent,
704
+ buildSignatureBase,
705
+ contentDigestSha256,
706
+ decodeJwt,
707
+ generateKeypair,
708
+ generateNonce,
709
+ jwkThumbprint,
710
+ publicJwkFromPrivateKey,
711
+ signRequest,
712
+ signSignatureBase,
713
+ signatureParams,
714
+ verifyAuthToken,
715
+ verifySignatureBase
716
+ };
717
+ //# sourceMappingURL=index.mjs.map