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