@lumoauth/agent 1.0.0 → 1.1.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/README.md CHANGED
@@ -1,51 +1,390 @@
1
1
  # @lumoauth/agent
2
2
 
3
- The LumoAuth SDK for AI agents (Node 18+). Two layers:
3
+ [![npm](https://img.shields.io/npm/v/@lumoauth/agent.svg)](https://www.npmjs.com/package/@lumoauth/agent)
4
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
4
5
 
5
- - **`LumoAgent`** — high-level client: OAuth 2.0 client-credentials auth with
6
- transparent refresh, preflight checks (`ask` / `isAllowed`), self-inspection
7
- (`capabilities`, `budget`), and the `jit`, `delegation`, `approvals`, and
8
- `mcp` namespaces.
9
- - **`AAuthClient`** + signing primitives — the AAuth protocol: cryptographic
10
- agent identity, proof-of-possession tokens, and RFC 9421 HTTP message
11
- signing (`node:crypto`, hence Node-only).
6
+ > The LumoAuth SDK for AI agents that run on Node 18 or newer. `LumoAgent`
7
+ > signs the agent in, checks permissions before it acts, asks people for
8
+ > approval, requests just-in-time permissions and gets MCP tokens.
9
+ > `AAuthClient` implements the AAuth protocol: a cryptographic agent identity
10
+ > with RFC 9421 HTTP message signatures.
11
+
12
+ This package is part of the [LumoAuth JavaScript SDK](../../README.md). Not
13
+ sure that it is the package that you need? See
14
+ [Which package do I need?](../../README.md#which-package-do-i-need).
15
+
16
+ ## Contents
17
+
18
+ - [Is this the right package?](#is-this-the-right-package)
19
+ - [Install](#install)
20
+ - [Quick start](#quick-start)
21
+ - [Configuration](#configuration)
22
+ - [Guides](#guides)
23
+ - [`LumoAgent` reference](#lumoagent-reference)
24
+ - [AAuth: cryptographic agent identity](#aauth-cryptographic-agent-identity)
25
+ - [Errors](#errors)
26
+ - [Troubleshooting](#troubleshooting)
27
+ - [Related packages](#related-packages)
28
+ - [Learn more](#learn-more)
29
+ - [License](#license)
30
+
31
+ ## Is this the right package?
32
+
33
+ | You are… | Use |
34
+ |---|---|
35
+ | Writing an agent (LangChain.js, Vercel AI SDK, your own loop) that signs in **as itself**, asks before acting, and gets a person's approval for risky actions | **This package**, `LumoAgent` |
36
+ | Building or calling an agent that needs a verifiable cryptographic identity, signed requests, or delegation between agents | **This package**, `AAuthClient` |
37
+ | Building a resource server that must verify incoming AAuth tokens | **This package**, `verifyAuthToken` |
38
+ | Starting a new agent app | [`npx create-lumo-agent`](../create-lumo-agent/README.md) |
39
+ | Writing an ordinary backend that acts for a user, not as an agent | [`@lumoauth/backend`](../backend/README.md) |
12
40
 
13
41
  ## Install
14
42
 
15
- ```sh
43
+ ```bash
16
44
  npm install @lumoauth/agent
17
45
  ```
18
46
 
19
- ## Example
47
+ **This package needs Node 18 or newer.** The AAuth part uses `node:crypto`, so
48
+ the package never runs in a browser.
49
+
50
+ ## Quick start
51
+
52
+ Create the agent in the LumoAuth portal first. You need its client ID, its
53
+ client secret and your organization slug.
54
+
55
+ ```bash
56
+ export LUMOAUTH_ORG_ID=acme-corp
57
+ export AGENT_CLIENT_ID=…
58
+ export AGENT_CLIENT_SECRET=…
59
+ ```
20
60
 
21
61
  ```ts
22
62
  import { LumoAgent } from '@lumoauth/agent';
23
63
 
24
- // Reads LUMOAUTH_URL / LUMOAUTH_ORG_ID / AGENT_CLIENT_ID / AGENT_CLIENT_SECRET
25
- const agent = new LumoAgent();
64
+ const agent = new LumoAgent(); // reads the variables above
26
65
 
27
- // Preflight before running a tool
66
+ // 1. Check first: may this agent do this, in this context?
28
67
  if (!(await agent.isAllowed('document.read', { id: 'doc_99' }))) {
29
68
  throw new Error('not allowed');
30
69
  }
31
70
 
32
- // Human approval for an irreversible action — push lands on the user's phone
71
+ // 2. Ask a person before an action that cannot be undone. A push arrives on
72
+ // the user's phone, and the promise resolves when they answer or time runs out.
33
73
  const approval = await agent.approvals.require({
34
74
  taskId: 'wire-001',
35
75
  reason: 'Wire $4,500 to vendor INV-7741',
36
76
  impact: 'high',
37
77
  onBehalfOf: 'ada@acme.com',
38
78
  });
39
- if (approval.status !== 'approved') throw new Error(`denied: ${approval.status}`);
79
+ if (approval.status !== 'approved') throw new Error(`not approved: ${approval.status}`);
40
80
 
41
- // Short-lived token for a secured MCP server
42
- const mcpToken = await agent.mcp.getToken('urn:mcp:financial-data');
81
+ // 3. Get a short-lived token for a secured MCP server.
82
+ // The server ID is the MCP server's https URL. It becomes the token's `aud`.
83
+ const mcpToken = await agent.mcp.getToken('https://mcp.example.com/mcp');
43
84
  ```
44
85
 
45
- ## Docs
86
+ Sign-in is automatic. The first call runs the OAuth 2.0 client credentials
87
+ grant. The SDK refreshes the token 60 seconds before it expires.
88
+
89
+ ## Configuration
90
+
91
+ `new LumoAgent(options?)`. Every option falls back to an environment variable.
92
+
93
+ | Option | Environment variable | Default | Description |
94
+ |---|---|---|---|
95
+ | `baseUrl` | `LUMOAUTH_URL` | `https://app.lumoauth.dev` | The LumoAuth host. Use `https://eu.app.lumoauth.dev` for the EU region |
96
+ | `orgId` | `LUMOAUTH_ORG_ID` | none | The organization slug. Every namespace needs it |
97
+ | `clientId` | `AGENT_CLIENT_ID` | required | The agent's OAuth client ID |
98
+ | `clientSecret` | `AGENT_CLIENT_SECRET` | required | The agent's OAuth client secret |
99
+ | `scopes` | none | the agent's defaults | Scopes to request |
100
+ | `redirectUri` | none | none | The callback URL of the delegation consent flow |
101
+ | `timeout` | none | 30 000 ms | Request timeout |
102
+ | `fetch` | none | global `fetch` | A custom `fetch` |
103
+
104
+ The constructor throws `LumoAuthConfigError` when the client ID or the client
105
+ secret is missing. It does not call the server.
106
+
107
+ ## Guides
108
+
109
+ ### Check before acting
110
+
111
+ `ask()` returns the decision and the reason. `isAllowed()` returns only the
112
+ boolean.
113
+
114
+ ```ts
115
+ const decision = await agent.ask('tickets.write', { ticket: 'T-42' });
116
+ // decision.allowed, decision.action, decision.reason, decision.audit_id
117
+ ```
118
+
119
+ The decision comes from the agent's capabilities and the organization's
120
+ policies. The server always sets `ip`, `userAgent`, `requestMethod` and
121
+ `requestPath` in the context from the real request. Values that you send under
122
+ those names move to `pep`.
123
+
124
+ ### Ask a person for approval
125
+
126
+ ```ts
127
+ const approval = await agent.approvals.require({
128
+ taskId: 'delete-42',
129
+ reason: 'Delete 1,204 archived invoices',
130
+ impact: 'critical', // 'low' | 'medium' | 'high' | 'critical'; default 'medium'
131
+ onBehalfOf: 'ada@acme.com', // email or user ID
132
+ meta: { count: 1204 }, // shown to the user
133
+ timeoutMs: 120_000, // default 90 000
134
+ });
135
+ ```
136
+
137
+ `approval.status` is `approved`, `denied`, `expired` or `pending`. `pending`
138
+ means that the wait ended before the user answered. `approval.token` lets you
139
+ check again later with `agent.approvals.getStatus(token)` or
140
+ `agent.approvals.wait(token)`.
141
+
142
+ When the user has no enrolled push device, no prompt is sent. `require()`
143
+ then throws `LumoAuthApprovalNotDeliveredError`. It never returns
144
+ `approved` in this case. Check `err.reason`:
145
+
146
+ - `email_fallback_sent`: the server emailed the user a notice with no
147
+ approval link. There is no token, so the SDK does not poll. An unknown
148
+ user gets the same answer.
149
+ - `no_enrolled_device`: the email could not be sent either.
150
+
151
+ ```ts
152
+ import { LumoAuthApprovalNotDeliveredError } from '@lumoauth/agent';
153
+
154
+ try {
155
+ await agent.approvals.require({ taskId: 'delete-42', reason: 'Delete invoices', onBehalfOf: 'ada@acme.com' });
156
+ } catch (err) {
157
+ if (err instanceof LumoAuthApprovalNotDeliveredError) {
158
+ // Ask the user to check their email, or to enrol the LumoAuth app.
159
+ } else throw err;
160
+ }
161
+ ```
162
+
163
+ `agent.approvals.create()` sends the request without waiting. It returns
164
+ `status: 'pending'` and a `token` when a prompt was sent. Otherwise it
165
+ returns `status: 'email_fallback_sent'` and `token: null`, without throwing.
166
+
167
+ ### Request just-in-time permissions
168
+
169
+ ```ts
170
+ await agent.jit.createTask({ name: 'Analyse the Q4 report', onBehalfOf: 'ada@acme.com' });
171
+
172
+ const result = await agent.jit.requestPermission(
173
+ { type: 'file_access', actions: ['read'], identifier: 'report_q4.pdf' },
174
+ { justification: 'The user asked for Q4 revenue', ttl: 300 },
175
+ );
176
+
177
+ if (result.status === 'approved') {
178
+ const token = await agent.jit.getToken(result.request_id);
179
+ // Call the resource with `Authorization: Bearer ${token}`.
180
+ }
181
+
182
+ await agent.jit.completeTask(); // ends the task and revokes its tokens
183
+ ```
184
+
185
+ When a request needs approval, `requestPermission()` keeps polling until a
186
+ person answers. It polls every 5 seconds for up to 5 minutes; pass `waitForApproval: false` to
187
+ return at once. A JIT token lasts at most 900 seconds.
188
+
189
+ ### Act for a user
190
+
191
+ ```ts
192
+ const agent = new LumoAgent({ redirectUri: 'https://agent.example.com/callback' });
193
+
194
+ const url = agent.delegation.getConsentUrl('session-1', ['read:documents']);
195
+ // …the user consents and returns with ?code=…
196
+ await agent.delegation.handleConsentCallback('session-1', code);
197
+
198
+ const delegated = await agent.delegation.exchange('session-1', ['read:documents'], {
199
+ resource: 'https://api.example.com', // becomes the token's aud
200
+ });
201
+ ```
202
+
203
+ When you already hold the user's access token, call
204
+ `agent.delegation.setUserToken('session-1', accessToken)` instead of the
205
+ consent steps. The token types and the `resource` option are explained in the
206
+ [workspace guide](../../README.md#act-on-a-users-behalf-delegation).
207
+
208
+ ## `LumoAgent` reference
209
+
210
+ ### Properties and methods
211
+
212
+ | Member | Returns | Description |
213
+ |---|---|---|
214
+ | `authenticate(scopes?)` | `Promise<string>` | Runs the client credentials grant now. You rarely need it, because every call signs in when needed |
215
+ | `getAccessToken()` | `Promise<string>` | The current access token, refreshed when it is about to expire |
216
+ | `tokenScopes` | `string[]` | The scopes that the server granted to the current token |
217
+ | `ask(action, context?)` | `Promise<AgentAskResult>` | The full decision for an action |
218
+ | `isAllowed(action, context?)` | `Promise<boolean>` | `ask()` reduced to a boolean |
219
+ | `getCurrentAgent()` | `Promise<AgentIdentity>` | The agent's identity, capabilities and workspace |
220
+ | `capabilities()` | `Promise<string[]>` | The agent's capabilities |
221
+ | `budget()` | `Promise<AgentBudget>` | The agent's budget policy, or `{}` when none is set |
222
+ | `baseUrl`, `orgId`, `clientId` | `string` | The resolved configuration |
223
+
224
+ ### Namespaces
225
+
226
+ | Namespace | What it does | Methods |
227
+ |---|---|---|
228
+ | `agents` | Agent identity | `ask`, `isAllowed`, `me`, `getCurrentAgent`, `capabilities`, `budget`, `register` |
229
+ | `approvals` | Push approval for agent actions | `require`, `create`, `getStatus`, `wait` |
230
+ | `jit` | Just-in-time permissions | `createTask`, `requestPermission`, `getRequestStatus`, `getToken`, `evaluateTask`, `completeTask`. `listPendingRequests` is the human reviewer's view. It needs a user token with `jit:approve`, so the server rejects an agent's own token |
231
+ | `delegation` | Act for a user, or hand work to a sub-agent, with RFC 8693 token exchange | `getConsentUrl`, `handleConsentCallback`, `setUserToken`, `exchange`, `request`, `delegateToSubAgent`, `revoke`, `revokeAll`, `hasDelegation`, `activeSessions` |
232
+ | `mcp` | Token exchange for secured MCP servers | `getToken`, `getTokenDetailed`. Pass the MCP server's https URL, such as `https://mcp.example.com/mcp`. The SDK sends it as the RFC 8707 `resource`, so the token's `aud` is that URL. Any other ID throws `LumoAuthValidationError` |
233
+
234
+ The parameters of each method are in the
235
+ [workspace API reference](../../README.md#api-reference).
236
+
237
+ ## AAuth: cryptographic agent identity
238
+
239
+ AAuth gives an agent an identity that a resource server can verify without a
240
+ shared secret. The agent holds an Ed25519 or RSA key pair. It signs each
241
+ request with RFC 9421 HTTP message signatures and presents
242
+ proof-of-possession tokens. The protocol has four token requests (`auth`,
243
+ `code`, `exchange` and `refresh`), which support user consent and delegation
244
+ across several agents.
245
+
246
+ ### Set up the key
247
+
248
+ ```ts
249
+ import { generateKeypair } from '@lumoauth/agent';
250
+
251
+ const { privateKeyPem, jwks } = generateKeypair(); // Ed25519, kid "key-1"
252
+ // Store privateKeyPem in your secret manager. Register jwks with your organization.
253
+ ```
254
+
255
+ ### Agent side
256
+
257
+ ```ts
258
+ import { AAuthClient } from '@lumoauth/agent';
259
+
260
+ const aauth = new AAuthClient({
261
+ agentIdentifier: 'https://my-agent.example.com', // an HTTPS URL that names the agent
262
+ privateKeyPem: process.env.AGENT_PRIVATE_KEY!,
263
+ orgId: 'acme-corp',
264
+ });
265
+
266
+ const result = await aauth.requestAuthToken({ resourceToken, agentToken, scope: 'read write' });
267
+
268
+ if ('authorizationRequired' in result) {
269
+ // The user has to consent first. Send them to result.authorizationUri,
270
+ // then call aauth.exchangeCode({ code, redirectUri, agentToken }).
271
+ } else {
272
+ const res = await aauth.signedRequest('GET', 'https://api.example.com/v1/data', {
273
+ authToken: result.authToken,
274
+ });
275
+ }
276
+ ```
277
+
278
+ `resourceToken` is the resource token that the target resource issued to the
279
+ agent. `agentToken` is the agent's own `agent+jwt`, sent in the `Agent-Auth`
280
+ header.
281
+
282
+ ### `AAuthClient` options
283
+
284
+ | Option | Default | Description |
285
+ |---|---|---|
286
+ | `agentIdentifier` | required | The HTTPS URL that names the agent |
287
+ | `privateKeyPem` | required | A PEM Ed25519 (PKCS#8) or RSA private key |
288
+ | `baseUrl` | `LUMOAUTH_URL`, then `https://app.lumoauth.dev` | The LumoAuth host |
289
+ | `orgId` | `LUMOAUTH_ORG_ID` | The organization slug |
290
+ | `kid` | `key-1` | The key ID. It must match the registered JWKS entry |
291
+ | `fetch` | global `fetch` | A custom `fetch` |
292
+ | `timeout` | 30 000 ms | Request timeout |
293
+
294
+ ### `AAuthClient` methods
295
+
296
+ | Method | What it does |
297
+ |---|---|
298
+ | `requestAuthToken({ resourceToken, agentToken, scope?, redirectUri? })` | Requests an auth token. Returns the token, or `{ authorizationRequired: true, requestToken, authorizationUri }` when the user must consent |
299
+ | `buildConsentUrl(requestToken)` | Builds the consent URL for a pending request token |
300
+ | `exchangeCode({ code, redirectUri, agentToken })` | Exchanges the consent code for an auth token |
301
+ | `exchangeToken({ authToken, resourceToken, agentToken })` | Exchanges an upstream auth token for a downstream one, which adds to the `act` chain |
302
+ | `refresh({ refreshToken, resourceToken, scope?, agentToken })` | Refreshes an auth token. It needs a fresh resource token |
303
+ | `revoke({ token, tokenType?, agentToken })` | Revokes an auth token by its `jti`, or a refresh token by value |
304
+ | `signRequest(method, url, options?)` | Returns RFC 9421 signature headers for a request |
305
+ | `signedRequest(method, url, { authToken, data?, headers? })` | Sends a signed request with the auth token, and returns the `fetch` `Response` |
306
+ | `verifyAuthToken(token, { resource, jwks?, clockSkew?, issuer? })` | Verifies a token. The issuer defaults to this organization's issuer |
307
+ | `discoverIssuer()`, `discoverAgents()`, `discoverResource(url)` | Read the AAuth metadata documents |
308
+ | `issuer`, `publicJwk`, `publicJwkThumbprint` | The issuer URL and the agent's public key |
309
+
310
+ ### Resource-server side
311
+
312
+ ```ts
313
+ import { verifyAuthToken } from '@lumoauth/agent';
314
+
315
+ const claims = await verifyAuthToken(bearer, {
316
+ issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',
317
+ resource: 'https://api.example.com', // must equal the token's aud
318
+ });
319
+ // Then check the request signature against claims.cnf.jwk.
320
+ ```
321
+
322
+ `verifyAuthToken()` fetches the issuer's keys unless you pass `jwks`. It
323
+ accepts only asymmetric algorithms, so `HS*` and `none` always fail. It allows
324
+ no clock skew on `exp` unless you set `clockSkew` in seconds. It throws
325
+ `AAuthError` when a check fails.
326
+
327
+ ### Exports
328
+
329
+ | Group | Exports |
330
+ |---|---|
331
+ | Client | `AAuthClient` |
332
+ | Keys | `generateKeypair`, `publicJwkFromPrivateKey`, `jwkThumbprint` |
333
+ | Signing primitives (RFC 9421) | `signRequest`, `buildSignatureBase`, `signatureParams`, `signSignatureBase`, `verifySignatureBase`, `contentDigestSha256`, `generateNonce`, `AAUTH_COVERED_COMPONENTS` |
334
+ | Verification | `verifyAuthToken`, `decodeJwt` |
335
+ | Errors | `AAuthError` |
336
+
337
+ The signing code is tested byte for byte against the shared test vector in
338
+ [`sdk-contract`](https://github.com/LumoAuth/sdk-contract). Signatures made
339
+ here therefore verify in the Python, Go, PHP, Java and .NET SDKs, and the
340
+ other way round.
341
+
342
+ ## Errors
343
+
344
+ This package re-exports the error classes of
345
+ [`@lumoauth/shared`](../shared/README.md#errors). The ones that agents meet
346
+ most often are:
347
+
348
+ | Class | When |
349
+ |---|---|
350
+ | `LumoAuthConfigError` | The client ID, client secret or `orgId` is missing |
351
+ | `LumoAuthApiError` | Sign-in failed: the server rejected the client credentials. `statusCode` holds the HTTP status |
352
+ | `LumoAuthAuthenticationError` | A later call got 401, for example because the agent was suspended |
353
+ | `LumoAuthPermissionDeniedError` | The server rejected the call. `requiredScopes` names a missing scope, when there is one |
354
+ | `LumoAuthRateLimitError` | Too many requests. `retryAfter` holds the wait in seconds |
355
+ | `LumoAuthApprovalDeniedError`, `LumoAuthApprovalTimeoutError` | A person declined, or nobody answered in time |
356
+ | `LumoAuthApprovalNotDeliveredError` | The approval prompt reached no device. `reason` is `email_fallback_sent` or `no_enrolled_device`, and `taskId` names the task |
357
+ | `LumoAuthBudgetExceededError` | The agent ran out of budget |
358
+ | `AAuthError` | An AAuth request or a token check failed |
359
+
360
+ ## Troubleshooting
361
+
362
+ | Symptom | Cause | Fix |
363
+ |---|---|---|
364
+ | `LumoAuthConfigError` at construction | `AGENT_CLIENT_ID` or `AGENT_CLIENT_SECRET` is not set | Set both, or pass `clientId` and `clientSecret` |
365
+ | `LumoAuthConfigError` that mentions `orgId` | `LUMOAUTH_ORG_ID` is not set | Set it, or pass `orgId` |
366
+ | 403 `test_token_not_accepted` from approvals, or 401 on a JIT route | The call used a portal test token | Use the agent's real credentials |
367
+ | 403 on `jit.listPendingRequests()` | It is the reviewer's view and needs a user token with `jit:approve` | Call it from the reviewer's app |
368
+ | `invalid_grant` from `delegation.exchange()` | The declared token type does not match, the user is no longer active, or the subject is a JIT token | Fix `subjectTokenType`, and use an active user token |
369
+ | 401 from an API with a delegated token | The token's `aud` is the agent ID | Pass `resource` to `exchange()` |
370
+ | `approvals.require()` throws `LumoAuthApprovalNotDeliveredError` | The user has no enrolled push device. With `reason` `email_fallback_sent`, the server emailed them a notice | Ask the user to enrol the LumoAuth app, then ask again |
371
+ | `mcp.getToken()` throws `LumoAuthValidationError` | The server ID is not an https URL, for example `urn:mcp:…` | Pass the MCP server's URL |
372
+
373
+ ## Related packages
374
+
375
+ | Package | How it relates |
376
+ |---|---|
377
+ | [`create-lumo-agent`](../create-lumo-agent/README.md) | Creates a complete agent app with one command |
378
+ | [`@lumoauth/backend`](../backend/README.md) | The same namespaces for a server that holds a user's token instead of agent credentials |
379
+ | [`@lumoauth/shared`](../shared/README.md) | The core that this package re-exports |
380
+ | [Workspace README](../../README.md) | How all of the packages fit together, with guides and the full API reference |
381
+
382
+ ## Learn more
46
383
 
47
- https://docs.lumoauth.dev
384
+ - [Enable security for AI agents](https://docs.lumoauth.dev/quickstarts/ai-agent-security/)
385
+ - [AAuth quickstart](https://docs.lumoauth.dev/agents/aauth-quickstart/)
386
+ - [SDK overview](https://docs.lumoauth.dev/developer/sdks/)
48
387
 
49
388
  ## License
50
389
 
51
- MIT
390
+ [MIT](./LICENSE)
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AgentsModule, JitModule, DelegationModule, ApprovalsModule, McpModule, AgentAskResult, AgentIdentity, AgentBudget, LumoAuthError } from '@lumoauth/shared';
2
+ export { ApprovalNotDeliveredReason, ApprovalRequestResult, ApprovalResult, CreateApprovalRequest, LumoAuthApiError, LumoAuthApprovalDeniedError, LumoAuthApprovalNotDeliveredError, LumoAuthApprovalTimeoutError, LumoAuthAuthenticationError, LumoAuthBudgetExceededError, LumoAuthConfigError, LumoAuthError, LumoAuthNetworkError, LumoAuthNotFoundError, LumoAuthPermissionDeniedError, LumoAuthRateLimitError, LumoAuthValidationError, RequireApprovalRequest } from '@lumoauth/shared';
2
3
  import { KeyObject } from 'node:crypto';
3
4
 
4
5
  interface LumoAgentOptions {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AgentsModule, JitModule, DelegationModule, ApprovalsModule, McpModule, AgentAskResult, AgentIdentity, AgentBudget, LumoAuthError } from '@lumoauth/shared';
2
+ export { ApprovalNotDeliveredReason, ApprovalRequestResult, ApprovalResult, CreateApprovalRequest, LumoAuthApiError, LumoAuthApprovalDeniedError, LumoAuthApprovalNotDeliveredError, LumoAuthApprovalTimeoutError, LumoAuthAuthenticationError, LumoAuthBudgetExceededError, LumoAuthConfigError, LumoAuthError, LumoAuthNetworkError, LumoAuthNotFoundError, LumoAuthPermissionDeniedError, LumoAuthRateLimitError, LumoAuthValidationError, RequireApprovalRequest } from '@lumoauth/shared';
2
3
  import { KeyObject } from 'node:crypto';
3
4
 
4
5
  interface LumoAgentOptions {
package/dist/index.js CHANGED
@@ -24,6 +24,19 @@ __export(index_exports, {
24
24
  AAuthClient: () => AAuthClient,
25
25
  AAuthError: () => AAuthError,
26
26
  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,
27
40
  buildSignatureBase: () => buildSignatureBase,
28
41
  contentDigestSha256: () => contentDigestSha256,
29
42
  decodeJwt: () => decodeJwt,
@@ -719,12 +732,28 @@ var AAuthClient = class {
719
732
  };
720
733
  /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */
721
734
  AAuthClient.generateKeypair = generateKeypair;
735
+
736
+ // src/index.ts
737
+ var import_shared4 = require("@lumoauth/shared");
722
738
  // Annotate the CommonJS export names for ESM import in node:
723
739
  0 && (module.exports = {
724
740
  AAUTH_COVERED_COMPONENTS,
725
741
  AAuthClient,
726
742
  AAuthError,
727
743
  LumoAgent,
744
+ LumoAuthApiError,
745
+ LumoAuthApprovalDeniedError,
746
+ LumoAuthApprovalNotDeliveredError,
747
+ LumoAuthApprovalTimeoutError,
748
+ LumoAuthAuthenticationError,
749
+ LumoAuthBudgetExceededError,
750
+ LumoAuthConfigError,
751
+ LumoAuthError,
752
+ LumoAuthNetworkError,
753
+ LumoAuthNotFoundError,
754
+ LumoAuthPermissionDeniedError,
755
+ LumoAuthRateLimitError,
756
+ LumoAuthValidationError,
728
757
  buildSignatureBase,
729
758
  contentDigestSha256,
730
759
  decodeJwt,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/agent.ts","../src/keys.ts","../src/signing.ts","../src/verify.ts","../src/errors.ts","../src/client.ts"],"sourcesContent":["// ─── @lumoauth/agent — the agent SDK ─────────────────────────────────\n//\n// Two layers:\n// - `LumoAgent` — high-level client (client-credentials auth, ask/\n// isAllowed, jit/delegation/approvals/mcp namespaces). Python parity\n// with `lumoauth.LumoAuthAgent`.\n// - `AAuthClient` + signing/verify primitives — the AAuth protocol\n// (cryptographic agent identity, RFC 9421 HTTP message signing).\n// Uses `node:crypto`, therefore Node-only (>= 18).\n\nexport { LumoAgent, type LumoAgentOptions } from './agent';\n\nexport {\n AAuthClient,\n type AAuthClientOptions,\n type AAuthTokenResponse,\n type AAuthAuthorizationRequired,\n type AAuthIssuerMetadata,\n type AAuthAgentMetadata,\n type AAuthResourceMetadata,\n} from './client';\n\nexport {\n generateKeypair,\n jwkThumbprint,\n publicJwkFromPrivateKey,\n type AAuthJwk,\n type AAuthKeypair,\n} from './keys';\n\nexport {\n signRequest,\n buildSignatureBase,\n signatureParams,\n signSignatureBase,\n verifySignatureBase,\n contentDigestSha256,\n generateNonce,\n AAUTH_COVERED_COMPONENTS,\n type SignRequestOptions,\n} from './signing';\n\nexport {\n verifyAuthToken,\n decodeJwt,\n type AAuthTokenClaims,\n type VerifyAuthTokenOptions,\n} from './verify';\n\nexport { AAuthError } from './errors';\n","import {\n HttpClient,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthApiError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n ROUTES,\n buildPath,\n type AgentAskResult,\n type AgentIdentity,\n type AgentBudget,\n} from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface LumoAgentOptions {\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization slug. Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** OAuth client ID. Defaults to `process.env.AGENT_CLIENT_ID`. */\n clientId?: string;\n /** OAuth client secret. Defaults to `process.env.AGENT_CLIENT_SECRET`. */\n clientSecret?: string;\n /** Scopes to request. When omitted the server grants the agent's defaults. */\n scopes?: string[];\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\ninterface TokenState {\n accessToken: string;\n /** Epoch ms after which we refresh (real expiry minus the safety buffer). */\n refreshAt: number;\n scopes: string[];\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n/** Safety margin (ms) subtracted from `expires_in` so we refresh early. */\nconst TOKEN_REFRESH_BUFFER_MS = 60_000;\n\n// ─── LumoAgent ────────────────────────────────────────────────────────\n\n/**\n * High-level agent client — the Node.js counterpart of the Python SDK's\n * `LumoAuthAgent`.\n *\n * Handles the full agent lifecycle:\n * - OAuth 2.0 client-credentials authentication with transparent refresh\n * (60 s safety buffer)\n * - Preflight capability checks (`ask` / `isAllowed`)\n * - Self-inspection (`getCurrentAgent`, `capabilities`, `budget`)\n * - `jit`, `delegation`, `approvals`, and `mcp` namespaces\n *\n * For the AAuth protocol (cryptographic agent identity, RFC 9421 message\n * signing) use {@link AAuthClient} from this same package.\n *\n * @example\n * ```ts\n * import { LumoAgent } from '@lumoauth/agent';\n *\n * const agent = new LumoAgent(); // reads env vars by default\n * if (await agent.isAllowed('document.read', { id: 'doc_99' })) {\n * // ... do the thing\n * }\n *\n * const approval = await agent.approvals.require({\n * taskId: 'wire-001',\n * reason: 'Wire $4,500 to vendor INV-7741',\n * impact: 'high',\n * onBehalfOf: 'ada@acme.com',\n * });\n * ```\n */\nexport class LumoAgent {\n readonly baseUrl: string;\n readonly orgId: string;\n readonly clientId: string;\n\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n readonly agents: AgentsModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n readonly jit: JitModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n readonly delegation: DelegationModule;\n /** Push-approval-for-agent-actions. */\n readonly approvals: ApprovalsModule;\n /** Token exchange for secured MCP servers. */\n readonly mcp: McpModule;\n\n private readonly clientSecret: string;\n private readonly scopes: string[] | undefined;\n private readonly fetchFn: typeof globalThis.fetch;\n private token: TokenState | null = null;\n private refreshPromise: Promise<string> | null = null;\n\n constructor(options: LumoAgentOptions = {}) {\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.clientId = options.clientId ?? envVar('AGENT_CLIENT_ID') ?? '';\n this.clientSecret = options.clientSecret ?? envVar('AGENT_CLIENT_SECRET') ?? '';\n this.scopes = options.scopes;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (!this.clientId || !this.clientSecret) {\n throw new LumoAuthConfigError(\n 'Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET ' +\n 'environment variables or pass clientId/clientSecret to the constructor.',\n );\n }\n\n const tokenProvider = () => this.getAccessToken();\n const http = new HttpClient({\n baseUrl: this.baseUrl,\n token: tokenProvider,\n timeout: options.timeout,\n fetch: options.fetch,\n });\n\n this.agents = new AgentsModule(http, this.orgId);\n this.jit = new JitModule(http, this.orgId);\n this.approvals = new ApprovalsModule(http, this.orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n token: tokenProvider,\n fetch: options.fetch,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n redirectUri: options.redirectUri,\n agentToken: tokenProvider,\n fetch: options.fetch,\n });\n }\n\n // ── Authentication ────────────────────────────────────────────────\n\n /**\n * Authenticate with the client-credentials flow. Called automatically\n * by every API method — invoke it directly only to fail fast at\n * startup or to request non-default scopes.\n */\n async authenticate(scopes?: string[]): Promise<string> {\n const form: Record<string, string> = {\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret,\n };\n const requested = scopes ?? this.scopes;\n if (requested?.length) form.scope = requested.join(' ');\n\n const url = `${this.baseUrl}${buildPath(ROUTES['oauth.token'].path, { orgId: this.requireOrgId() })}`;\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(form),\n });\n } catch (error) {\n throw new LumoAuthNetworkError(\n `Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new LumoAuthApiError(\n typeof body.error_description === 'string'\n ? body.error_description\n : `Agent authentication failed (HTTP ${res.status})`,\n typeof body.error === 'string' ? body.error : 'AUTHENTICATION_ERROR',\n res.status,\n body,\n );\n }\n\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 3600;\n this.token = {\n accessToken: body.access_token,\n refreshAt: Date.now() + expiresIn * 1000 - TOKEN_REFRESH_BUFFER_MS,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n };\n return this.token.accessToken;\n }\n\n /**\n * The current access token, re-authenticating transparently when it is\n * missing or within 60 s of expiry. Concurrent callers share one\n * in-flight token request.\n */\n async getAccessToken(): Promise<string> {\n if (this.token && Date.now() < this.token.refreshAt) {\n return this.token.accessToken;\n }\n this.refreshPromise ??= this.authenticate(\n this.token?.scopes.length ? this.token.scopes : undefined,\n ).finally(() => {\n this.refreshPromise = null;\n });\n return this.refreshPromise;\n }\n\n /** Scopes granted by the last successful authentication. */\n get tokenScopes(): string[] {\n return this.token ? [...this.token.scopes] : [];\n }\n\n // ── Ask API & self-inspection (delegates to `agents`) ─────────────\n\n /** Preflight check: is the agent authorised to perform `action`? */\n async ask(action: string, context?: Record<string, unknown>): Promise<AgentAskResult> {\n return this.agents.ask(action, context);\n }\n\n /** Convenience wrapper: `true` when `action` is allowed. */\n async isAllowed(action: string, context?: Record<string, unknown>): Promise<boolean> {\n return this.agents.isAllowed(action, context);\n }\n\n /** The agent's own identity, capabilities, and workspace. */\n async getCurrentAgent(): Promise<AgentIdentity> {\n return this.agents.me();\n }\n\n /** The agent's declared capability slugs. */\n async capabilities(): Promise<string[]> {\n return this.agents.capabilities();\n }\n\n /** The agent's budget policy (empty object when no policy is set). */\n async budget(): Promise<AgentBudget> {\n return this.agents.budget();\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private requireOrgId(): string {\n if (!this.orgId) {\n throw new LumoAuthConfigError(\n 'orgId is required — pass it to the LumoAgent constructor or set LUMOAUTH_ORG_ID.',\n );\n }\n return this.orgId;\n }\n}\n","import { createHash, createPublicKey, createPrivateKey, generateKeyPairSync, type KeyObject } from 'node:crypto';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\n/** A public JSON Web Key as published in a JWKS. */\nexport interface AAuthJwk {\n kty: string;\n crv?: string;\n x?: string;\n y?: string;\n n?: string;\n e?: string;\n use?: string;\n kid?: string;\n alg?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthKeypair {\n /** PKCS#8 PEM-encoded Ed25519 private key. Store in your secret manager. */\n privateKeyPem: string;\n /** SPKI PEM-encoded public key. */\n publicKeyPem: string;\n /** The public key as a JWK (with `use: \"sig\"` and the given `kid`). */\n jwk: AAuthJwk;\n /** A JWKS document ready to publish at `/.well-known/jwks.json`. */\n jwks: { keys: AAuthJwk[] };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\nexport function base64UrlEncode(data: Buffer | Uint8Array | string): string {\n return Buffer.from(data).toString('base64url');\n}\n\nexport function base64UrlDecode(data: string): Buffer {\n return Buffer.from(data, 'base64url');\n}\n\n// ─── Key generation ───────────────────────────────────────────────────\n\n/**\n * Generate an Ed25519 key pair suitable for AAuth.\n *\n * Mirrors the Python SDK's `AAuthClient.generate_keypair()`: returns the\n * PKCS#8 private key PEM plus a JWKS document ready to be published at\n * `/.well-known/jwks.json` (or registered inline with LumoAuth).\n *\n * @example\n * ```ts\n * import { generateKeypair } from '@lumoauth/agent';\n *\n * const { privateKeyPem, jwks } = generateKeypair();\n * console.log(JSON.stringify(jwks, null, 2));\n * ```\n */\nexport function generateKeypair(kid = 'key-1'): AAuthKeypair {\n const { privateKey, publicKey } = generateKeyPairSync('ed25519');\n\n const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();\n const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();\n\n const rawJwk = publicKey.export({ format: 'jwk' }) as { kty: string; crv: string; x: string };\n const jwk: AAuthJwk = {\n kty: rawJwk.kty,\n crv: rawJwk.crv,\n x: rawJwk.x,\n use: 'sig',\n kid,\n };\n\n return { privateKeyPem, publicKeyPem, jwk, jwks: { keys: [jwk] } };\n}\n\n/**\n * Compute the RFC 7638 JWK thumbprint (base64url-encoded SHA-256) of a\n * public JWK. This is the `jkt` value AAuth uses to bind tokens to keys.\n */\nexport function jwkThumbprint(jwk: AAuthJwk): string {\n let canonical: string;\n switch (jwk.kty) {\n case 'OKP':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });\n break;\n case 'EC':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });\n break;\n case 'RSA':\n canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });\n break;\n default:\n throw new Error(`Unsupported key type for thumbprint: ${jwk.kty}`);\n }\n return createHash('sha256').update(canonical, 'utf8').digest('base64url');\n}\n\n/**\n * Load a PEM private key (Ed25519 or RSA) into a Node.js KeyObject and\n * classify it for the RFC 9421 signing dispatch.\n */\nexport function loadPrivateKey(pem: string): { key: KeyObject; type: 'ed25519' | 'rsa' } {\n const key = createPrivateKey(pem);\n if (key.asymmetricKeyType === 'ed25519') {\n return { key, type: 'ed25519' };\n }\n if (key.asymmetricKeyType === 'rsa' || key.asymmetricKeyType === 'rsa-pss') {\n return { key, type: 'rsa' };\n }\n throw new Error(\n `AAuth requires an Ed25519 or RSA private key (got ${String(key.asymmetricKeyType)}).`\n );\n}\n\n/** Derive the public JWK for a loaded private key. */\nexport function publicJwkFromPrivateKey(pem: string, kid?: string): AAuthJwk {\n const priv = createPrivateKey(pem);\n const pub = createPublicKey(priv);\n const jwk = pub.export({ format: 'jwk' }) as AAuthJwk;\n if (kid) jwk.kid = kid;\n return jwk;\n}\n","import {\n constants,\n createHash,\n randomBytes,\n sign as cryptoSign,\n verify as cryptoVerify,\n type KeyObject,\n} from 'node:crypto';\nimport { loadPrivateKey } from './keys';\n\n/**\n * RFC 9421 HTTP Message Signing, profiled for AAuth.\n *\n * The LumoAuth agent token endpoint enforces a strict profile (AAuth 1.0 §4):\n *\n * - Covered components: `@method @authority @path signature-key\n * content-digest content-type authorization` (plus `@query` if and only if\n * the target URI has a query string).\n * - `Signature-Input` parameters: exactly `created` (within ±60 s) and a\n * fresh `nonce` (≥ 12 bytes / 96 bits of entropy, base64url).\n * - `Content-Digest` per RFC 9530 with **standard** base64 (`sha-256=:…:`).\n * - The `Signature` value is **base64url** encoded (`label=:…:`).\n * - Algorithms: Ed25519 or RSA-PSS-SHA512 (MGF1-SHA512, 64-byte salt),\n * dispatched by key type — do NOT declare an `alg` parameter.\n */\n\n// ─── Constants ────────────────────────────────────────────────────────\n\n/** Covered components required by the AAuth agent token endpoint, in order. */\nexport const AAUTH_COVERED_COMPONENTS = [\n '@method',\n '@authority',\n '@path',\n 'signature-key',\n 'content-digest',\n 'content-type',\n 'authorization',\n] as const;\n\nconst SIGNATURE_LABEL = 'sig1';\n\n// ─── Primitives ───────────────────────────────────────────────────────\n\n/**\n * Compute an RFC 9530 `Content-Digest` header value over the exact body\n * bytes. Uses sha-256 with STANDARD base64 (the server base64-decodes it).\n */\nexport function contentDigestSha256(body: Buffer | Uint8Array | string): string {\n const digest = createHash('sha256').update(body).digest('base64');\n return `sha-256=:${digest}:`;\n}\n\n/** Generate a fresh signature nonce: base64url of 16 random bytes (128 bits). */\nexport function generateNonce(): string {\n return randomBytes(16).toString('base64url');\n}\n\n/**\n * Build the RFC 9421 signature base: one `\"<component>\": <value>` line per\n * covered component in declared order, then the `\"@signature-params\"` line\n * carrying ONLY `created` and `nonce`.\n */\nexport function buildSignatureBase(\n components: readonly string[],\n values: Record<string, string>,\n created: number,\n nonce: string\n): string {\n const lines = components.map((c) => `\"${c}\": ${values[c] ?? ''}`);\n lines.push(`\"@signature-params\": ${signatureParams(components, created, nonce)}`);\n return lines.join('\\n');\n}\n\n/** The `(…);created=…;nonce=\"…\"` parameter string shared by the base and header. */\nexport function signatureParams(\n components: readonly string[],\n created: number,\n nonce: string\n): string {\n const coveredList = components.map((c) => `\"${c}\"`).join(' ');\n return `(${coveredList});created=${created};nonce=\"${nonce}\"`;\n}\n\n/**\n * Sign a signature base with the agent's private key.\n * Ed25519 keys produce `ed25519` signatures; RSA keys produce\n * `rsa-pss-sha512` signatures (MGF1-SHA512, salt length = digest length).\n * Returns the base64url-encoded signature (RFC 9421 profile).\n */\nexport function signSignatureBase(signatureBase: string, privateKey: KeyObject): string {\n const data = Buffer.from(signatureBase, 'utf8');\n let signature: Buffer;\n if (privateKey.asymmetricKeyType === 'ed25519') {\n signature = cryptoSign(null, data, privateKey);\n } else {\n signature = cryptoSign('sha512', data, {\n key: privateKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST, // 64 bytes for SHA-512\n });\n }\n return signature.toString('base64url');\n}\n\n/**\n * Verify a base64url signature over a signature base (resource-server side).\n * Dispatches on key type like the LumoAuth server does.\n */\nexport function verifySignatureBase(\n signatureBase: string,\n signatureB64url: string,\n publicKey: KeyObject\n): boolean {\n const data = Buffer.from(signatureBase, 'utf8');\n const sig = Buffer.from(signatureB64url, 'base64url');\n if (publicKey.asymmetricKeyType === 'ed25519') {\n return cryptoVerify(null, data, publicKey, sig);\n }\n return cryptoVerify('sha512', data, {\n key: publicKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST,\n }, sig);\n}\n\n// ─── Request signing ──────────────────────────────────────────────────\n\nexport interface SignRequestOptions {\n /** Raw request body. Defaults to the empty body. */\n body?: Buffer | Uint8Array | string;\n /** Media type of the body. Default: `application/json`. */\n contentType?: string;\n /** The `agent+jwt` to present in the `Agent-Auth` header. */\n agentToken?: string;\n /** Value of a covered `Authorization` header, if any (e.g. `Bearer …`). */\n authorization?: string;\n /** Value of a covered `Signature-Key` header, if any. */\n signatureKey?: string;\n /**\n * Override the `created` timestamp (seconds). Testing only — the server\n * rejects timestamps more than 60 s from its clock.\n */\n created?: number;\n /** Override the nonce. Testing only — nonces are single-use server-side. */\n nonce?: string;\n}\n\n/**\n * Create RFC 9421 signature headers for a request to the AAuth agent token\n * endpoint (or any endpoint enforcing the AAuth profile).\n *\n * Byte-compatible with the Python SDK's `AAuthClient.sign_request()`.\n */\nexport function signRequest(\n privateKeyPem: string,\n method: string,\n url: string,\n options: SignRequestOptions = {}\n): Record<string, string> {\n const { key } = loadPrivateKey(privateKeyPem);\n const parsed = new URL(url);\n const authority = parsed.host; // host[:port], lowercased by the URL parser\n const path = parsed.pathname || '/';\n const query = parsed.search; // '' or '?…'\n\n const body = options.body ?? Buffer.alloc(0);\n const contentType = options.contentType ?? 'application/json';\n const contentDigest = contentDigestSha256(body);\n\n const created = options.created ?? Math.floor(Date.now() / 1000);\n const nonce = options.nonce ?? generateNonce();\n\n // @query MUST be covered if and only if the target has a query string.\n const components: string[] = ['@method', '@authority', '@path'];\n if (query !== '') components.push('@query');\n components.push('signature-key', 'content-digest', 'content-type', 'authorization');\n\n const values: Record<string, string> = {\n '@method': method.toUpperCase(),\n '@authority': authority,\n '@path': path,\n 'signature-key': options.signatureKey ?? '',\n 'content-digest': contentDigest,\n 'content-type': contentType,\n authorization: options.authorization ?? '',\n };\n if (query !== '') values['@query'] = query;\n\n const signatureBase = buildSignatureBase(components, values, created, nonce);\n const signature = signSignatureBase(signatureBase, key);\n\n const headers: Record<string, string> = {\n 'Content-Digest': contentDigest,\n 'Content-Type': contentType,\n 'Signature-Input': `${SIGNATURE_LABEL}=${signatureParams(components, created, nonce)}`,\n Signature: `${SIGNATURE_LABEL}=:${signature}:`,\n };\n if (options.agentToken) {\n headers['Agent-Auth'] = `agent_token=${options.agentToken}`;\n }\n if (options.signatureKey) {\n headers['Signature-Key'] = options.signatureKey;\n }\n return headers;\n}\n","import { constants, createPublicKey, verify as cryptoVerify, type KeyObject } from 'node:crypto';\nimport type { AAuthJwk } from './keys';\nimport { AAuthError } from './errors';\n\n/**\n * Auth-token (`auth+jwt`) verification for resource servers.\n *\n * Verifies the JWS signature against the organization's AAuth issuer JWKS\n * (`{issuer}/aauth/jwks.json`), plus `typ`, `iss`, `aud`, and `exp` — the\n * same checks LumoAuth's own `validateAuthToken()` performs (revocation\n * excepted: use `POST {issuer}/aauth/auth/token/verify` for live\n * revocation-aware introspection).\n *\n * NOTE: AAuth auth tokens are proof-of-possession tokens. After verifying\n * the JWT, the resource MUST also verify the request's RFC 9421 signature\n * against the key in `cnf.jwk` (see `verifySignatureBase` and\n * `jwkThumbprint`).\n */\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthTokenClaims {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n jti: string;\n cnf: { jwk: AAuthJwk };\n agent?: string;\n agent_delegate?: string;\n scope?: string;\n sub?: string;\n act?: Record<string, unknown>;\n [claim: string]: unknown;\n}\n\nexport interface VerifyAuthTokenOptions {\n /** The trusted issuer URL, e.g. `https://app.lumoauth.dev/orgs/acme-corp/api/v1`. */\n issuer: string;\n /** Your resource identifier — must equal the token's `aud`. */\n resource: string;\n /** Pre-fetched issuer JWKS (skips the network fetch). */\n jwks?: { keys: AAuthJwk[] };\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Allowed clock skew in seconds for `exp`. Default 0 (like the server). */\n clockSkew?: number;\n}\n\n// Only asymmetric JWS algorithms; HS* and none are always rejected.\nconst JWS_VERIFIERS: Record<string, (data: Buffer, key: KeyObject, sig: Buffer) => boolean> = {\n RS256: (d, k, s) => cryptoVerify('sha256', d, k, s),\n RS384: (d, k, s) => cryptoVerify('sha384', d, k, s),\n RS512: (d, k, s) => cryptoVerify('sha512', d, k, s),\n PS256: (d, k, s) => cryptoVerify('sha256', d, pss(k), s),\n PS384: (d, k, s) => cryptoVerify('sha384', d, pss(k), s),\n PS512: (d, k, s) => cryptoVerify('sha512', d, pss(k), s),\n ES256: (d, k, s) => cryptoVerify('sha256', d, p1363(k), s),\n ES384: (d, k, s) => cryptoVerify('sha384', d, p1363(k), s),\n ES512: (d, k, s) => cryptoVerify('sha512', d, p1363(k), s),\n EdDSA: (d, k, s) => cryptoVerify(null, d, k, s),\n};\n\nfunction pss(key: KeyObject) {\n return { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST };\n}\n\nfunction p1363(key: KeyObject) {\n return { key, dsaEncoding: 'ieee-p1363' as const };\n}\n\nfunction decodeSegment(segment: string): unknown {\n return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n}\n\n/** Decode a JWT without verifying it. Useful for reading `aud`/`cnf` first. */\nexport function decodeJwt(token: string): { header: Record<string, unknown>; claims: Record<string, unknown> } {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n return {\n header: decodeSegment(parts[0]) as Record<string, unknown>,\n claims: decodeSegment(parts[1]) as Record<string, unknown>,\n };\n}\n\n/**\n * Verify an AAuth auth token (`auth+jwt`) against the issuing\n * organization's JWKS. Returns the verified claims or throws `AAuthError`.\n *\n * @example\n * ```ts\n * import { verifyAuthToken } from '@lumoauth/agent';\n *\n * const claims = await verifyAuthToken(bearer, {\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://api.example.com',\n * });\n * // Then enforce PoP: verify the request signature against claims.cnf.jwk.\n * ```\n */\nexport async function verifyAuthToken(\n token: string,\n options: VerifyAuthTokenOptions\n): Promise<AAuthTokenClaims> {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n const header = decodeSegment(parts[0]) as Record<string, unknown>;\n const claims = decodeSegment(parts[1]) as Record<string, unknown>;\n\n if (header.typ !== 'auth+jwt') {\n throw new AAuthError(`Unexpected token type: ${String(header.typ)}`, 'invalid_token');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const kid = typeof header.kid === 'string' ? header.kid : '';\n if (!alg || !kid) {\n throw new AAuthError('Missing kid or alg in JOSE header', 'invalid_token');\n }\n const verifier = JWS_VERIFIERS[alg];\n if (!verifier) {\n throw new AAuthError(`Disallowed JWS algorithm: ${alg}`, 'invalid_token');\n }\n\n if (claims.iss !== options.issuer) {\n throw new AAuthError('Untrusted issuer', 'invalid_token');\n }\n\n // Resolve the signing key from the issuer JWKS\n const jwks = options.jwks ?? (await fetchIssuerJwks(options.issuer, options.fetch));\n const jwk = jwks.keys.find((k) => k.kid === kid);\n if (!jwk) {\n throw new AAuthError(`Key not found: kid=${kid}`, 'invalid_token');\n }\n assertAlgMatchesKey(alg, jwk);\n\n const publicKey = createPublicKey({ key: jwk as unknown as Record<string, unknown>, format: 'jwk' });\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n if (!verifier(data, publicKey, signature)) {\n throw new AAuthError('Signature verification failed', 'invalid_token');\n }\n\n // Temporal + audience checks (post-signature, like the server)\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 0;\n if (typeof claims.exp !== 'number' || claims.exp < now - skew) {\n throw new AAuthError('Auth token expired', 'invalid_token');\n }\n if (claims.aud !== options.resource) {\n throw new AAuthError('Invalid audience', 'invalid_token');\n }\n const cnf = claims.cnf as { jwk?: AAuthJwk } | undefined;\n if (!cnf || !cnf.jwk) {\n throw new AAuthError('Missing cnf.jwk claim', 'invalid_token');\n }\n\n return claims as unknown as AAuthTokenClaims;\n}\n\nfunction assertAlgMatchesKey(alg: string, jwk: AAuthJwk): void {\n const compatible =\n (jwk.kty === 'RSA' && (alg.startsWith('RS') || alg.startsWith('PS'))) ||\n (jwk.kty === 'EC' && alg.startsWith('ES')) ||\n (jwk.kty === 'OKP' && alg === 'EdDSA');\n if (!compatible) {\n throw new AAuthError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, 'invalid_token');\n }\n if (jwk.alg && jwk.alg !== alg) {\n throw new AAuthError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, 'invalid_token');\n }\n}\n\nasync function fetchIssuerJwks(\n issuer: string,\n fetchFn?: typeof globalThis.fetch\n): Promise<{ keys: AAuthJwk[] }> {\n const doFetch = fetchFn ?? globalThis.fetch;\n const url = `${issuer.replace(/\\/+$/, '')}/aauth/jwks.json`;\n const response = await doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, 'jwks_fetch_failed', response.status);\n }\n const jwks = (await response.json()) as { keys?: AAuthJwk[] };\n if (!Array.isArray(jwks.keys)) {\n throw new AAuthError('Issuer JWKS is malformed', 'jwks_fetch_failed');\n }\n return { keys: jwks.keys };\n}\n","import { LumoAuthError } from '@lumoauth/shared';\n\n/**\n * Thrown for AAuth protocol failures — OAuth-style `{error,\n * error_description}` bodies from the agent token endpoint, signature\n * problems, and token-verification failures.\n */\nexport class AAuthError extends LumoAuthError {\n constructor(\n message: string,\n /** OAuth-style error code, e.g. `invalid_grant`, `authentication_required`. */\n code: string,\n statusCode?: number,\n /** The parsed response body, when the error came from the server. */\n public readonly body?: unknown\n ) {\n super(message, code, statusCode);\n this.name = 'AAuthError';\n }\n}\n","import { generateKeypair, jwkThumbprint, publicJwkFromPrivateKey, type AAuthJwk, type AAuthKeypair } from './keys';\nimport { signRequest, type SignRequestOptions } from './signing';\nimport { verifyAuthToken, type AAuthTokenClaims, type VerifyAuthTokenOptions } from './verify';\nimport { AAuthError } from './errors';\nimport { LumoAuthConfigError, LumoAuthNetworkError, ROUTES, buildPath } from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthClientOptions {\n /** HTTPS URL uniquely identifying the agent (e.g. `https://my-agent.example.com`). */\n agentIdentifier: string;\n /** PEM-encoded Ed25519 (PKCS#8) or RSA private key. */\n privateKeyPem: string;\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization ID (slug). Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** Key ID matching the JWKS entry registered with LumoAuth. Default `key-1`. */\n kid?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\n/** Successful response from the agent token endpoint. */\nexport interface AAuthTokenResponse {\n requestType: 'auth' | 'code' | 'exchange' | 'refresh';\n /** The `auth+jwt` access token to present to the resource. */\n authToken: string;\n expiresIn: number;\n tokenType: string; // \"auth+jwt\"\n refreshToken?: string;\n}\n\n/** Returned by `requestAuthToken()` when the user must consent first. */\nexport interface AAuthAuthorizationRequired {\n authorizationRequired: true;\n /** Opaque token identifying the pending request (600 s TTL). */\n requestToken: string;\n /** Consent page URL — redirect the user here. */\n authorizationUri: string;\n expiresIn?: number;\n}\n\nexport interface AAuthIssuerMetadata {\n issuer: string;\n aauth_version: string;\n jwks_uri: string;\n agent_token_endpoint: string;\n agent_auth_endpoint: string;\n agent_signing_algs_supported: string[];\n token_signing_algs_supported: string[];\n request_types_supported: string[];\n scopes_supported: string[];\n [key: string]: unknown;\n}\n\nexport interface AAuthAgentMetadata {\n agent: string;\n jwks_uri: string;\n redirect_uris?: string[];\n name?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthResourceMetadata {\n resource: string;\n jwks_uri: string;\n resource_token_endpoint?: string;\n supported_scopes?: string[];\n [key: string]: unknown;\n}\n\ninterface RawTokenResponse {\n request_type?: string;\n auth_token?: string;\n expires_in?: number;\n token_type?: string;\n refresh_token?: string;\n request_token?: string;\n authorization_uri?: string;\n auth_url?: string;\n error?: string;\n error_description?: string;\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * Client for the AAuth (Agent Auth) protocol — the Node.js counterpart of\n * the Python SDK's `lumoauth.AAuthClient`.\n *\n * AAuth extends OAuth 2.1 with cryptographic agent identity,\n * proof-of-possession tokens, and RFC 9421 HTTP message signing.\n *\n * @example\n * ```ts\n * import { AAuthClient } from '@lumoauth/agent';\n *\n * const client = new AAuthClient({\n * agentIdentifier: 'https://my-agent.example.com',\n * privateKeyPem: process.env.AGENT_PRIVATE_KEY!,\n * baseUrl: 'https://app.lumoauth.dev',\n * orgId: 'acme-corp',\n * });\n *\n * const result = await client.requestAuthToken({\n * resourceToken,\n * scope: 'read write',\n * agentToken,\n * });\n * if ('authorizationRequired' in result) {\n * // redirect the user to result.authorizationUri, then exchangeCode()\n * } else {\n * const resp = await client.signedRequest('GET', 'https://api.example.com/v1/data', {\n * authToken: result.authToken,\n * });\n * }\n * ```\n */\nexport class AAuthClient {\n /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */\n static generateKeypair = generateKeypair;\n\n readonly agentIdentifier: string;\n readonly baseUrl: string;\n readonly orgId: string;\n readonly kid: string;\n\n private readonly privateKeyPem: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly timeout: number;\n\n constructor(options: AAuthClientOptions) {\n if (!options.agentIdentifier) {\n throw new LumoAuthConfigError('agentIdentifier is required');\n }\n if (!options.privateKeyPem) {\n throw new LumoAuthConfigError('privateKeyPem is required');\n }\n this.agentIdentifier = options.agentIdentifier;\n this.privateKeyPem = options.privateKeyPem;\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.kid = options.kid ?? 'key-1';\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.timeout = options.timeout ?? 30_000;\n }\n\n /** The organization's AAuth issuer URL: `{baseUrl}/orgs/{orgId}/api/v1`. */\n get issuer(): string {\n return `${this.baseUrl}/orgs/${this.orgId}/api/v1`;\n }\n\n /** The agent's public JWK derived from its private key. */\n get publicJwk(): AAuthJwk {\n return publicJwkFromPrivateKey(this.privateKeyPem, this.kid);\n }\n\n /** RFC 7638 thumbprint of the agent's public key (the `jkt` binding value). */\n get publicJwkThumbprint(): string {\n return jwkThumbprint(this.publicJwk);\n }\n\n // ─── HTTP Message Signing ─────────────────────────────────────────\n\n /**\n * Create RFC 9421 signature headers for a request per the AAuth profile.\n * See `signRequest()` in `signing.ts` for the exact contract.\n */\n signRequest(method: string, url: string, options: SignRequestOptions = {}): Record<string, string> {\n return signRequest(this.privateKeyPem, method, url, options);\n }\n\n // ─── Token flows ──────────────────────────────────────────────────\n\n /**\n * Request an auth token (`request_type=auth` — direct authorization).\n *\n * Presents the resource token in the body and the agent token in the\n * `Agent-Auth` header, signed with the agent's key. If the server\n * requires user consent it returns `{ authorizationRequired: true,\n * requestToken, authorizationUri }` — redirect the user, then call\n * `exchangeCode()` with the code delivered to your `redirectUri`.\n */\n async requestAuthToken(params: {\n /** Resource token (`resource+jwt`) obtained from the target resource. */\n resourceToken: string;\n /** Space-separated scopes (informational; scopes bind via the resource token). */\n scope?: string;\n /** The `agent+jwt` presented in `Agent-Auth`. */\n agentToken: string;\n /** Redirect URI for user-consent flows (must be registered). */\n redirectUri?: string;\n }): Promise<AAuthTokenResponse | AAuthAuthorizationRequired> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'auth',\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n if (params.redirectUri) body.redirect_uri = params.redirectUri;\n\n const data = await this.tokenRequest(body, params.agentToken);\n\n if (!data.auth_token && (data.request_token || data.authorization_uri || data.auth_url)) {\n return {\n authorizationRequired: true,\n requestToken: data.request_token ?? '',\n authorizationUri: data.authorization_uri ?? data.auth_url ?? '',\n expiresIn: data.expires_in,\n };\n }\n return this.mapTokenResponse(data);\n }\n\n /**\n * Build the user-consent URL for a pending request token\n * (`GET {issuer}/aauth/agent/auth?request_token=…`). Prefer the\n * `authorizationUri` returned by `requestAuthToken()` when present.\n */\n buildConsentUrl(requestToken: string): string {\n return `${this.routeUrl('aauth.agentAuth')}?request_token=${encodeURIComponent(requestToken)}`;\n }\n\n /**\n * Exchange an authorization code for tokens (`request_type=code`) after\n * user consent. `redirectUri` must be the exact URI the code was\n * delivered to.\n */\n async exchangeCode(params: {\n code: string;\n redirectUri: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n { request_type: 'code', code: params.code, redirect_uri: params.redirectUri },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Multi-hop token exchange (`request_type=exchange`): trade an upstream\n * auth token plus a downstream resource token for a new auth token with\n * an `act` actor chain. Requires token exchange to be enabled for the\n * agent.\n */\n async exchangeToken(params: {\n /** The upstream `auth+jwt` addressed to this agent. */\n authToken: string;\n /** Resource token issued by the downstream resource to this agent. */\n resourceToken: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n {\n request_type: 'exchange',\n auth_token: params.authToken,\n resource_token: params.resourceToken,\n },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Refresh an auth token (`request_type=refresh`). A fresh resource token\n * for the target resource is required; scopes requested via the resource\n * token must be a subset of the original grant. Refresh tokens are not\n * rotated.\n */\n async refresh(params: {\n refreshToken: string;\n /** Fresh resource token for the target resource. */\n resourceToken: string;\n /** Optional scope narrowing. */\n scope?: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'refresh',\n refresh_token: params.refreshToken,\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n const data = await this.tokenRequest(body, params.agentToken);\n return this.mapTokenResponse(data);\n }\n\n /**\n * Revoke an auth token (by its `jti`) or a refresh token (by value).\n * Always resolves `{ revoked: true }` — the server does not reveal\n * whether the token existed.\n */\n async revoke(params: {\n /** A refresh-token value, or an auth token's `jti`. */\n token: string;\n tokenType?: 'auth_token' | 'refresh_token';\n agentToken: string;\n }): Promise<{ revoked: boolean }> {\n this.requireAgentToken(params.agentToken);\n const url = this.routeUrl('aauth.tokenRevoke');\n const data = await this.signedPost(url, {\n token: params.token,\n token_type: params.tokenType ?? 'auth_token',\n }, params.agentToken);\n return { revoked: Boolean((data as { revoked?: boolean }).revoked ?? true) };\n }\n\n // ─── Signed requests to protected resources ───────────────────────\n\n /**\n * Make a signed, authenticated request to a protected resource.\n *\n * Carries the auth token as `Authorization: Bearer …` **and** an RFC\n * 9421 signature proving possession of the key bound in the token's\n * `cnf.jwk`. The signature covers the `authorization` component, so the\n * resource can verify both together.\n *\n * Returns the raw `fetch` Response.\n */\n async signedRequest(\n method: string,\n url: string,\n options: {\n /** The AAuth `auth+jwt` access token. */\n authToken: string;\n /** JSON body (for POST/PUT). */\n data?: unknown;\n /** Extra headers (not covered by the signature). */\n headers?: Record<string, string>;\n }\n ): Promise<Response> {\n const bodyStr = options.data != null ? JSON.stringify(options.data) : '';\n const authorization = `Bearer ${options.authToken}`;\n const sigHeaders = this.signRequest(method, url, { body: bodyStr, authorization });\n\n return this.doFetch(url, {\n method: method.toUpperCase(),\n headers: { Authorization: authorization, ...sigHeaders, ...(options.headers ?? {}) },\n body: bodyStr !== '' ? bodyStr : undefined,\n });\n }\n\n // ─── Verification (resource-server side) ──────────────────────────\n\n /**\n * Verify an `auth+jwt` against this organization's issuer JWKS.\n * See `verifyAuthToken()` for details (PoP still required!).\n */\n async verifyAuthToken(\n token: string,\n options: Omit<VerifyAuthTokenOptions, 'issuer' | 'fetch'> & { issuer?: string }\n ): Promise<AAuthTokenClaims> {\n return verifyAuthToken(token, {\n issuer: options.issuer ?? this.issuer,\n fetch: this.fetchFn,\n ...options,\n });\n }\n\n // ─── Discovery ────────────────────────────────────────────────────\n\n /** Fetch `{issuer}/.well-known/aauth-issuer`. */\n async discoverIssuer(): Promise<AAuthIssuerMetadata> {\n return this.getJson<AAuthIssuerMetadata>(this.routeUrl('aauth.issuerMetadata'));\n }\n\n /** Fetch `{issuer}/.well-known/aauth-agent` — metadata for all active agents. */\n async discoverAgents(): Promise<AAuthAgentMetadata[]> {\n return this.getJson<AAuthAgentMetadata[]>(this.routeUrl('aauth.agentMetadata'));\n }\n\n /** Fetch `{resourceUrl}/.well-known/aauth-resource` from a resource server. */\n async discoverResource(resourceUrl: string): Promise<AAuthResourceMetadata | AAuthResourceMetadata[]> {\n const base = resourceUrl.replace(/\\/+$/, '');\n return this.getJson<AAuthResourceMetadata | AAuthResourceMetadata[]>(`${base}/.well-known/aauth-resource`);\n }\n\n // ─── Internals ────────────────────────────────────────────────────\n\n private requireAgentToken(agentToken: string): void {\n if (!agentToken) {\n throw new AAuthError(\n 'agentToken is required — the /agent/token endpoint authenticates the agent via the Agent-Auth header.',\n 'invalid_request'\n );\n }\n }\n\n private tokenUrl(): string {\n return this.routeUrl('aauth.agentToken');\n }\n\n /** Absolute URL for an org-scoped route from the shared registry. */\n private routeUrl(name: keyof typeof ROUTES): string {\n return `${this.baseUrl}${buildPath(ROUTES[name].path, { orgId: this.orgId })}`;\n }\n\n private async tokenRequest(body: Record<string, unknown>, agentToken: string): Promise<RawTokenResponse> {\n return (await this.signedPost(this.tokenUrl(), body, agentToken)) as RawTokenResponse;\n }\n\n private async signedPost(url: string, body: Record<string, unknown>, agentToken: string): Promise<unknown> {\n if (!this.orgId) {\n throw new LumoAuthConfigError('orgId is required for AAuth token operations');\n }\n const bodyStr = JSON.stringify(body);\n const headers = this.signRequest('POST', url, { body: bodyStr, agentToken });\n\n const response = await this.doFetch(url, { method: 'POST', headers, body: bodyStr });\n const text = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n\n if (!response.ok) {\n const err = (parsed ?? {}) as { error?: string; error_description?: string };\n throw new AAuthError(\n err.error_description ?? err.error ?? `AAuth request failed: HTTP ${response.status}`,\n err.error ?? 'aauth_error',\n response.status,\n parsed ?? text\n );\n }\n return parsed ?? {};\n }\n\n private mapTokenResponse(data: RawTokenResponse): AAuthTokenResponse {\n if (!data.auth_token) {\n throw new AAuthError('Token response missing auth_token', 'invalid_response', undefined, data);\n }\n const result: AAuthTokenResponse = {\n requestType: (data.request_type ?? 'auth') as AAuthTokenResponse['requestType'],\n authToken: data.auth_token,\n expiresIn: data.expires_in ?? 0,\n tokenType: data.token_type ?? 'auth+jwt',\n };\n if (data.refresh_token) result.refreshToken = data.refresh_token;\n return result;\n }\n\n private async getJson<T>(url: string): Promise<T> {\n const response = await this.doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Discovery request failed: HTTP ${response.status}`, 'discovery_failed', response.status);\n }\n return (await response.json()) as T;\n }\n\n private async doFetch(url: string, init: RequestInit): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n try {\n return await this.fetchFn(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n throw new LumoAuthNetworkError(`Request to ${url} timed out after ${this.timeout}ms`, error);\n }\n throw new LumoAuthNetworkError(\n `Network request to ${url} failed: ${error instanceof Error ? error.message : String(error)}`,\n error\n );\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n\nexport type { AAuthKeypair };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAeO;AAiCP,SAAS,OAAO,MAAkC;AAC9C,SAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,IAAI,IAAI,IAAI;AAC/E;AAGA,IAAM,0BAA0B;AAmCzB,IAAM,YAAN,MAAgB;AAAA,EAsBnB,YAAY,UAA4B,CAAC,GAAG;AAH5C,SAAQ,QAA2B;AACnC,SAAQ,iBAAyC;AAG7C,SAAK,WAAW,QAAQ,WAAW,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AAE;AACE,mBAAa,SAAS;AAAA,IAC1B;AAAA,EACJ;AACJ;AAAA;AAlWa,YAEF,kBAAkB;","names":["import_node_crypto","cryptoSign","cryptoVerify","import_node_crypto","import_shared","cryptoVerify","import_shared","envVar"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/agent.ts","../src/keys.ts","../src/signing.ts","../src/verify.ts","../src/errors.ts","../src/client.ts"],"sourcesContent":["// ─── @lumoauth/agent — the agent SDK ─────────────────────────────────\n//\n// Two layers:\n// - `LumoAgent` — high-level client (client-credentials auth, ask/\n// isAllowed, jit/delegation/approvals/mcp namespaces). Python parity\n// with `lumoauth.LumoAuthAgent`.\n// - `AAuthClient` + signing/verify primitives — the AAuth protocol\n// (cryptographic agent identity, RFC 9421 HTTP message signing).\n// Uses `node:crypto`, therefore Node-only (>= 18).\n\nexport { LumoAgent, type LumoAgentOptions } from './agent';\n\nexport {\n AAuthClient,\n type AAuthClientOptions,\n type AAuthTokenResponse,\n type AAuthAuthorizationRequired,\n type AAuthIssuerMetadata,\n type AAuthAgentMetadata,\n type AAuthResourceMetadata,\n} from './client';\n\nexport {\n generateKeypair,\n jwkThumbprint,\n publicJwkFromPrivateKey,\n type AAuthJwk,\n type AAuthKeypair,\n} from './keys';\n\nexport {\n signRequest,\n buildSignatureBase,\n signatureParams,\n signSignatureBase,\n verifySignatureBase,\n contentDigestSha256,\n generateNonce,\n AAUTH_COVERED_COMPONENTS,\n type SignRequestOptions,\n} from './signing';\n\nexport {\n verifyAuthToken,\n decodeJwt,\n type AAuthTokenClaims,\n type VerifyAuthTokenOptions,\n} from './verify';\n\nexport { AAuthError } from './errors';\n\n// The shared error taxonomy, so agent code can catch these without a direct\n// dependency on @lumoauth/shared.\nexport {\n LumoAuthError,\n LumoAuthApiError,\n LumoAuthAuthenticationError,\n LumoAuthPermissionDeniedError,\n LumoAuthNotFoundError,\n LumoAuthRateLimitError,\n LumoAuthValidationError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n LumoAuthApprovalDeniedError,\n LumoAuthApprovalTimeoutError,\n LumoAuthApprovalNotDeliveredError,\n LumoAuthBudgetExceededError,\n type ApprovalNotDeliveredReason,\n type ApprovalResult,\n type ApprovalRequestResult,\n type CreateApprovalRequest,\n type RequireApprovalRequest,\n} from '@lumoauth/shared';\n","import {\n HttpClient,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthApiError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n ROUTES,\n buildPath,\n type AgentAskResult,\n type AgentIdentity,\n type AgentBudget,\n} from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface LumoAgentOptions {\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization slug. Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** OAuth client ID. Defaults to `process.env.AGENT_CLIENT_ID`. */\n clientId?: string;\n /** OAuth client secret. Defaults to `process.env.AGENT_CLIENT_SECRET`. */\n clientSecret?: string;\n /** Scopes to request. When omitted the server grants the agent's defaults. */\n scopes?: string[];\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\ninterface TokenState {\n accessToken: string;\n /** Epoch ms after which we refresh (real expiry minus the safety buffer). */\n refreshAt: number;\n scopes: string[];\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n/** Safety margin (ms) subtracted from `expires_in` so we refresh early. */\nconst TOKEN_REFRESH_BUFFER_MS = 60_000;\n\n// ─── LumoAgent ────────────────────────────────────────────────────────\n\n/**\n * High-level agent client — the Node.js counterpart of the Python SDK's\n * `LumoAuthAgent`.\n *\n * Handles the full agent lifecycle:\n * - OAuth 2.0 client-credentials authentication with transparent refresh\n * (60 s safety buffer)\n * - Preflight capability checks (`ask` / `isAllowed`)\n * - Self-inspection (`getCurrentAgent`, `capabilities`, `budget`)\n * - `jit`, `delegation`, `approvals`, and `mcp` namespaces\n *\n * For the AAuth protocol (cryptographic agent identity, RFC 9421 message\n * signing) use {@link AAuthClient} from this same package.\n *\n * @example\n * ```ts\n * import { LumoAgent } from '@lumoauth/agent';\n *\n * const agent = new LumoAgent(); // reads env vars by default\n * if (await agent.isAllowed('document.read', { id: 'doc_99' })) {\n * // ... do the thing\n * }\n *\n * const approval = await agent.approvals.require({\n * taskId: 'wire-001',\n * reason: 'Wire $4,500 to vendor INV-7741',\n * impact: 'high',\n * onBehalfOf: 'ada@acme.com',\n * });\n * ```\n */\nexport class LumoAgent {\n readonly baseUrl: string;\n readonly orgId: string;\n readonly clientId: string;\n\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n readonly agents: AgentsModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n readonly jit: JitModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n readonly delegation: DelegationModule;\n /** Push-approval-for-agent-actions. */\n readonly approvals: ApprovalsModule;\n /** Token exchange for secured MCP servers. */\n readonly mcp: McpModule;\n\n private readonly clientSecret: string;\n private readonly scopes: string[] | undefined;\n private readonly fetchFn: typeof globalThis.fetch;\n private token: TokenState | null = null;\n private refreshPromise: Promise<string> | null = null;\n\n constructor(options: LumoAgentOptions = {}) {\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.clientId = options.clientId ?? envVar('AGENT_CLIENT_ID') ?? '';\n this.clientSecret = options.clientSecret ?? envVar('AGENT_CLIENT_SECRET') ?? '';\n this.scopes = options.scopes;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (!this.clientId || !this.clientSecret) {\n throw new LumoAuthConfigError(\n 'Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET ' +\n 'environment variables or pass clientId/clientSecret to the constructor.',\n );\n }\n\n const tokenProvider = () => this.getAccessToken();\n const http = new HttpClient({\n baseUrl: this.baseUrl,\n token: tokenProvider,\n timeout: options.timeout,\n fetch: options.fetch,\n });\n\n this.agents = new AgentsModule(http, this.orgId);\n this.jit = new JitModule(http, this.orgId);\n this.approvals = new ApprovalsModule(http, this.orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n token: tokenProvider,\n fetch: options.fetch,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n redirectUri: options.redirectUri,\n agentToken: tokenProvider,\n fetch: options.fetch,\n });\n }\n\n // ── Authentication ────────────────────────────────────────────────\n\n /**\n * Authenticate with the client-credentials flow. Called automatically\n * by every API method — invoke it directly only to fail fast at\n * startup or to request non-default scopes.\n */\n async authenticate(scopes?: string[]): Promise<string> {\n const form: Record<string, string> = {\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret,\n };\n const requested = scopes ?? this.scopes;\n if (requested?.length) form.scope = requested.join(' ');\n\n const url = `${this.baseUrl}${buildPath(ROUTES['oauth.token'].path, { orgId: this.requireOrgId() })}`;\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(form),\n });\n } catch (error) {\n throw new LumoAuthNetworkError(\n `Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new LumoAuthApiError(\n typeof body.error_description === 'string'\n ? body.error_description\n : `Agent authentication failed (HTTP ${res.status})`,\n typeof body.error === 'string' ? body.error : 'AUTHENTICATION_ERROR',\n res.status,\n body,\n );\n }\n\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 3600;\n this.token = {\n accessToken: body.access_token,\n refreshAt: Date.now() + expiresIn * 1000 - TOKEN_REFRESH_BUFFER_MS,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n };\n return this.token.accessToken;\n }\n\n /**\n * The current access token, re-authenticating transparently when it is\n * missing or within 60 s of expiry. Concurrent callers share one\n * in-flight token request.\n */\n async getAccessToken(): Promise<string> {\n if (this.token && Date.now() < this.token.refreshAt) {\n return this.token.accessToken;\n }\n this.refreshPromise ??= this.authenticate(\n this.token?.scopes.length ? this.token.scopes : undefined,\n ).finally(() => {\n this.refreshPromise = null;\n });\n return this.refreshPromise;\n }\n\n /** Scopes granted by the last successful authentication. */\n get tokenScopes(): string[] {\n return this.token ? [...this.token.scopes] : [];\n }\n\n // ── Ask API & self-inspection (delegates to `agents`) ─────────────\n\n /** Preflight check: is the agent authorised to perform `action`? */\n async ask(action: string, context?: Record<string, unknown>): Promise<AgentAskResult> {\n return this.agents.ask(action, context);\n }\n\n /** Convenience wrapper: `true` when `action` is allowed. */\n async isAllowed(action: string, context?: Record<string, unknown>): Promise<boolean> {\n return this.agents.isAllowed(action, context);\n }\n\n /** The agent's own identity, capabilities, and workspace. */\n async getCurrentAgent(): Promise<AgentIdentity> {\n return this.agents.me();\n }\n\n /** The agent's declared capability slugs. */\n async capabilities(): Promise<string[]> {\n return this.agents.capabilities();\n }\n\n /** The agent's budget policy (empty object when no policy is set). */\n async budget(): Promise<AgentBudget> {\n return this.agents.budget();\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private requireOrgId(): string {\n if (!this.orgId) {\n throw new LumoAuthConfigError(\n 'orgId is required — pass it to the LumoAgent constructor or set LUMOAUTH_ORG_ID.',\n );\n }\n return this.orgId;\n }\n}\n","import { createHash, createPublicKey, createPrivateKey, generateKeyPairSync, type KeyObject } from 'node:crypto';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\n/** A public JSON Web Key as published in a JWKS. */\nexport interface AAuthJwk {\n kty: string;\n crv?: string;\n x?: string;\n y?: string;\n n?: string;\n e?: string;\n use?: string;\n kid?: string;\n alg?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthKeypair {\n /** PKCS#8 PEM-encoded Ed25519 private key. Store in your secret manager. */\n privateKeyPem: string;\n /** SPKI PEM-encoded public key. */\n publicKeyPem: string;\n /** The public key as a JWK (with `use: \"sig\"` and the given `kid`). */\n jwk: AAuthJwk;\n /** A JWKS document ready to publish at `/.well-known/jwks.json`. */\n jwks: { keys: AAuthJwk[] };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\nexport function base64UrlEncode(data: Buffer | Uint8Array | string): string {\n return Buffer.from(data).toString('base64url');\n}\n\nexport function base64UrlDecode(data: string): Buffer {\n return Buffer.from(data, 'base64url');\n}\n\n// ─── Key generation ───────────────────────────────────────────────────\n\n/**\n * Generate an Ed25519 key pair suitable for AAuth.\n *\n * Mirrors the Python SDK's `AAuthClient.generate_keypair()`: returns the\n * PKCS#8 private key PEM plus a JWKS document ready to be published at\n * `/.well-known/jwks.json` (or registered inline with LumoAuth).\n *\n * @example\n * ```ts\n * import { generateKeypair } from '@lumoauth/agent';\n *\n * const { privateKeyPem, jwks } = generateKeypair();\n * console.log(JSON.stringify(jwks, null, 2));\n * ```\n */\nexport function generateKeypair(kid = 'key-1'): AAuthKeypair {\n const { privateKey, publicKey } = generateKeyPairSync('ed25519');\n\n const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();\n const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();\n\n const rawJwk = publicKey.export({ format: 'jwk' }) as { kty: string; crv: string; x: string };\n const jwk: AAuthJwk = {\n kty: rawJwk.kty,\n crv: rawJwk.crv,\n x: rawJwk.x,\n use: 'sig',\n kid,\n };\n\n return { privateKeyPem, publicKeyPem, jwk, jwks: { keys: [jwk] } };\n}\n\n/**\n * Compute the RFC 7638 JWK thumbprint (base64url-encoded SHA-256) of a\n * public JWK. This is the `jkt` value AAuth uses to bind tokens to keys.\n */\nexport function jwkThumbprint(jwk: AAuthJwk): string {\n let canonical: string;\n switch (jwk.kty) {\n case 'OKP':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });\n break;\n case 'EC':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });\n break;\n case 'RSA':\n canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });\n break;\n default:\n throw new Error(`Unsupported key type for thumbprint: ${jwk.kty}`);\n }\n return createHash('sha256').update(canonical, 'utf8').digest('base64url');\n}\n\n/**\n * Load a PEM private key (Ed25519 or RSA) into a Node.js KeyObject and\n * classify it for the RFC 9421 signing dispatch.\n */\nexport function loadPrivateKey(pem: string): { key: KeyObject; type: 'ed25519' | 'rsa' } {\n const key = createPrivateKey(pem);\n if (key.asymmetricKeyType === 'ed25519') {\n return { key, type: 'ed25519' };\n }\n if (key.asymmetricKeyType === 'rsa' || key.asymmetricKeyType === 'rsa-pss') {\n return { key, type: 'rsa' };\n }\n throw new Error(\n `AAuth requires an Ed25519 or RSA private key (got ${String(key.asymmetricKeyType)}).`\n );\n}\n\n/** Derive the public JWK for a loaded private key. */\nexport function publicJwkFromPrivateKey(pem: string, kid?: string): AAuthJwk {\n const priv = createPrivateKey(pem);\n const pub = createPublicKey(priv);\n const jwk = pub.export({ format: 'jwk' }) as AAuthJwk;\n if (kid) jwk.kid = kid;\n return jwk;\n}\n","import {\n constants,\n createHash,\n randomBytes,\n sign as cryptoSign,\n verify as cryptoVerify,\n type KeyObject,\n} from 'node:crypto';\nimport { loadPrivateKey } from './keys';\n\n/**\n * RFC 9421 HTTP Message Signing, profiled for AAuth.\n *\n * The LumoAuth agent token endpoint enforces a strict profile (AAuth 1.0 §4):\n *\n * - Covered components: `@method @authority @path signature-key\n * content-digest content-type authorization` (plus `@query` if and only if\n * the target URI has a query string).\n * - `Signature-Input` parameters: exactly `created` (within ±60 s) and a\n * fresh `nonce` (≥ 12 bytes / 96 bits of entropy, base64url).\n * - `Content-Digest` per RFC 9530 with **standard** base64 (`sha-256=:…:`).\n * - The `Signature` value is **base64url** encoded (`label=:…:`).\n * - Algorithms: Ed25519 or RSA-PSS-SHA512 (MGF1-SHA512, 64-byte salt),\n * dispatched by key type — do NOT declare an `alg` parameter.\n */\n\n// ─── Constants ────────────────────────────────────────────────────────\n\n/** Covered components required by the AAuth agent token endpoint, in order. */\nexport const AAUTH_COVERED_COMPONENTS = [\n '@method',\n '@authority',\n '@path',\n 'signature-key',\n 'content-digest',\n 'content-type',\n 'authorization',\n] as const;\n\nconst SIGNATURE_LABEL = 'sig1';\n\n// ─── Primitives ───────────────────────────────────────────────────────\n\n/**\n * Compute an RFC 9530 `Content-Digest` header value over the exact body\n * bytes. Uses sha-256 with STANDARD base64 (the server base64-decodes it).\n */\nexport function contentDigestSha256(body: Buffer | Uint8Array | string): string {\n const digest = createHash('sha256').update(body).digest('base64');\n return `sha-256=:${digest}:`;\n}\n\n/** Generate a fresh signature nonce: base64url of 16 random bytes (128 bits). */\nexport function generateNonce(): string {\n return randomBytes(16).toString('base64url');\n}\n\n/**\n * Build the RFC 9421 signature base: one `\"<component>\": <value>` line per\n * covered component in declared order, then the `\"@signature-params\"` line\n * carrying ONLY `created` and `nonce`.\n */\nexport function buildSignatureBase(\n components: readonly string[],\n values: Record<string, string>,\n created: number,\n nonce: string\n): string {\n const lines = components.map((c) => `\"${c}\": ${values[c] ?? ''}`);\n lines.push(`\"@signature-params\": ${signatureParams(components, created, nonce)}`);\n return lines.join('\\n');\n}\n\n/** The `(…);created=…;nonce=\"…\"` parameter string shared by the base and header. */\nexport function signatureParams(\n components: readonly string[],\n created: number,\n nonce: string\n): string {\n const coveredList = components.map((c) => `\"${c}\"`).join(' ');\n return `(${coveredList});created=${created};nonce=\"${nonce}\"`;\n}\n\n/**\n * Sign a signature base with the agent's private key.\n * Ed25519 keys produce `ed25519` signatures; RSA keys produce\n * `rsa-pss-sha512` signatures (MGF1-SHA512, salt length = digest length).\n * Returns the base64url-encoded signature (RFC 9421 profile).\n */\nexport function signSignatureBase(signatureBase: string, privateKey: KeyObject): string {\n const data = Buffer.from(signatureBase, 'utf8');\n let signature: Buffer;\n if (privateKey.asymmetricKeyType === 'ed25519') {\n signature = cryptoSign(null, data, privateKey);\n } else {\n signature = cryptoSign('sha512', data, {\n key: privateKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST, // 64 bytes for SHA-512\n });\n }\n return signature.toString('base64url');\n}\n\n/**\n * Verify a base64url signature over a signature base (resource-server side).\n * Dispatches on key type like the LumoAuth server does.\n */\nexport function verifySignatureBase(\n signatureBase: string,\n signatureB64url: string,\n publicKey: KeyObject\n): boolean {\n const data = Buffer.from(signatureBase, 'utf8');\n const sig = Buffer.from(signatureB64url, 'base64url');\n if (publicKey.asymmetricKeyType === 'ed25519') {\n return cryptoVerify(null, data, publicKey, sig);\n }\n return cryptoVerify('sha512', data, {\n key: publicKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST,\n }, sig);\n}\n\n// ─── Request signing ──────────────────────────────────────────────────\n\nexport interface SignRequestOptions {\n /** Raw request body. Defaults to the empty body. */\n body?: Buffer | Uint8Array | string;\n /** Media type of the body. Default: `application/json`. */\n contentType?: string;\n /** The `agent+jwt` to present in the `Agent-Auth` header. */\n agentToken?: string;\n /** Value of a covered `Authorization` header, if any (e.g. `Bearer …`). */\n authorization?: string;\n /** Value of a covered `Signature-Key` header, if any. */\n signatureKey?: string;\n /**\n * Override the `created` timestamp (seconds). Testing only — the server\n * rejects timestamps more than 60 s from its clock.\n */\n created?: number;\n /** Override the nonce. Testing only — nonces are single-use server-side. */\n nonce?: string;\n}\n\n/**\n * Create RFC 9421 signature headers for a request to the AAuth agent token\n * endpoint (or any endpoint enforcing the AAuth profile).\n *\n * Byte-compatible with the Python SDK's `AAuthClient.sign_request()`.\n */\nexport function signRequest(\n privateKeyPem: string,\n method: string,\n url: string,\n options: SignRequestOptions = {}\n): Record<string, string> {\n const { key } = loadPrivateKey(privateKeyPem);\n const parsed = new URL(url);\n const authority = parsed.host; // host[:port], lowercased by the URL parser\n const path = parsed.pathname || '/';\n const query = parsed.search; // '' or '?…'\n\n const body = options.body ?? Buffer.alloc(0);\n const contentType = options.contentType ?? 'application/json';\n const contentDigest = contentDigestSha256(body);\n\n const created = options.created ?? Math.floor(Date.now() / 1000);\n const nonce = options.nonce ?? generateNonce();\n\n // @query MUST be covered if and only if the target has a query string.\n const components: string[] = ['@method', '@authority', '@path'];\n if (query !== '') components.push('@query');\n components.push('signature-key', 'content-digest', 'content-type', 'authorization');\n\n const values: Record<string, string> = {\n '@method': method.toUpperCase(),\n '@authority': authority,\n '@path': path,\n 'signature-key': options.signatureKey ?? '',\n 'content-digest': contentDigest,\n 'content-type': contentType,\n authorization: options.authorization ?? '',\n };\n if (query !== '') values['@query'] = query;\n\n const signatureBase = buildSignatureBase(components, values, created, nonce);\n const signature = signSignatureBase(signatureBase, key);\n\n const headers: Record<string, string> = {\n 'Content-Digest': contentDigest,\n 'Content-Type': contentType,\n 'Signature-Input': `${SIGNATURE_LABEL}=${signatureParams(components, created, nonce)}`,\n Signature: `${SIGNATURE_LABEL}=:${signature}:`,\n };\n if (options.agentToken) {\n headers['Agent-Auth'] = `agent_token=${options.agentToken}`;\n }\n if (options.signatureKey) {\n headers['Signature-Key'] = options.signatureKey;\n }\n return headers;\n}\n","import { constants, createPublicKey, verify as cryptoVerify, type KeyObject } from 'node:crypto';\nimport type { AAuthJwk } from './keys';\nimport { AAuthError } from './errors';\n\n/**\n * Auth-token (`auth+jwt`) verification for resource servers.\n *\n * Verifies the JWS signature against the organization's AAuth issuer JWKS\n * (`{issuer}/aauth/jwks.json`), plus `typ`, `iss`, `aud`, and `exp` — the\n * same checks LumoAuth's own `validateAuthToken()` performs (revocation\n * excepted: use `POST {issuer}/aauth/auth/token/verify` for live\n * revocation-aware introspection).\n *\n * NOTE: AAuth auth tokens are proof-of-possession tokens. After verifying\n * the JWT, the resource MUST also verify the request's RFC 9421 signature\n * against the key in `cnf.jwk` (see `verifySignatureBase` and\n * `jwkThumbprint`).\n */\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthTokenClaims {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n jti: string;\n cnf: { jwk: AAuthJwk };\n agent?: string;\n agent_delegate?: string;\n scope?: string;\n sub?: string;\n act?: Record<string, unknown>;\n [claim: string]: unknown;\n}\n\nexport interface VerifyAuthTokenOptions {\n /** The trusted issuer URL, e.g. `https://app.lumoauth.dev/orgs/acme-corp/api/v1`. */\n issuer: string;\n /** Your resource identifier — must equal the token's `aud`. */\n resource: string;\n /** Pre-fetched issuer JWKS (skips the network fetch). */\n jwks?: { keys: AAuthJwk[] };\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Allowed clock skew in seconds for `exp`. Default 0 (like the server). */\n clockSkew?: number;\n}\n\n// Only asymmetric JWS algorithms; HS* and none are always rejected.\nconst JWS_VERIFIERS: Record<string, (data: Buffer, key: KeyObject, sig: Buffer) => boolean> = {\n RS256: (d, k, s) => cryptoVerify('sha256', d, k, s),\n RS384: (d, k, s) => cryptoVerify('sha384', d, k, s),\n RS512: (d, k, s) => cryptoVerify('sha512', d, k, s),\n PS256: (d, k, s) => cryptoVerify('sha256', d, pss(k), s),\n PS384: (d, k, s) => cryptoVerify('sha384', d, pss(k), s),\n PS512: (d, k, s) => cryptoVerify('sha512', d, pss(k), s),\n ES256: (d, k, s) => cryptoVerify('sha256', d, p1363(k), s),\n ES384: (d, k, s) => cryptoVerify('sha384', d, p1363(k), s),\n ES512: (d, k, s) => cryptoVerify('sha512', d, p1363(k), s),\n EdDSA: (d, k, s) => cryptoVerify(null, d, k, s),\n};\n\nfunction pss(key: KeyObject) {\n return { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST };\n}\n\nfunction p1363(key: KeyObject) {\n return { key, dsaEncoding: 'ieee-p1363' as const };\n}\n\nfunction decodeSegment(segment: string): unknown {\n return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n}\n\n/** Decode a JWT without verifying it. Useful for reading `aud`/`cnf` first. */\nexport function decodeJwt(token: string): { header: Record<string, unknown>; claims: Record<string, unknown> } {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n return {\n header: decodeSegment(parts[0]) as Record<string, unknown>,\n claims: decodeSegment(parts[1]) as Record<string, unknown>,\n };\n}\n\n/**\n * Verify an AAuth auth token (`auth+jwt`) against the issuing\n * organization's JWKS. Returns the verified claims or throws `AAuthError`.\n *\n * @example\n * ```ts\n * import { verifyAuthToken } from '@lumoauth/agent';\n *\n * const claims = await verifyAuthToken(bearer, {\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://api.example.com',\n * });\n * // Then enforce PoP: verify the request signature against claims.cnf.jwk.\n * ```\n */\nexport async function verifyAuthToken(\n token: string,\n options: VerifyAuthTokenOptions\n): Promise<AAuthTokenClaims> {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n const header = decodeSegment(parts[0]) as Record<string, unknown>;\n const claims = decodeSegment(parts[1]) as Record<string, unknown>;\n\n if (header.typ !== 'auth+jwt') {\n throw new AAuthError(`Unexpected token type: ${String(header.typ)}`, 'invalid_token');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const kid = typeof header.kid === 'string' ? header.kid : '';\n if (!alg || !kid) {\n throw new AAuthError('Missing kid or alg in JOSE header', 'invalid_token');\n }\n const verifier = JWS_VERIFIERS[alg];\n if (!verifier) {\n throw new AAuthError(`Disallowed JWS algorithm: ${alg}`, 'invalid_token');\n }\n\n if (claims.iss !== options.issuer) {\n throw new AAuthError('Untrusted issuer', 'invalid_token');\n }\n\n // Resolve the signing key from the issuer JWKS\n const jwks = options.jwks ?? (await fetchIssuerJwks(options.issuer, options.fetch));\n const jwk = jwks.keys.find((k) => k.kid === kid);\n if (!jwk) {\n throw new AAuthError(`Key not found: kid=${kid}`, 'invalid_token');\n }\n assertAlgMatchesKey(alg, jwk);\n\n const publicKey = createPublicKey({ key: jwk as unknown as Record<string, unknown>, format: 'jwk' });\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n if (!verifier(data, publicKey, signature)) {\n throw new AAuthError('Signature verification failed', 'invalid_token');\n }\n\n // Temporal + audience checks (post-signature, like the server)\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 0;\n if (typeof claims.exp !== 'number' || claims.exp < now - skew) {\n throw new AAuthError('Auth token expired', 'invalid_token');\n }\n if (claims.aud !== options.resource) {\n throw new AAuthError('Invalid audience', 'invalid_token');\n }\n const cnf = claims.cnf as { jwk?: AAuthJwk } | undefined;\n if (!cnf || !cnf.jwk) {\n throw new AAuthError('Missing cnf.jwk claim', 'invalid_token');\n }\n\n return claims as unknown as AAuthTokenClaims;\n}\n\nfunction assertAlgMatchesKey(alg: string, jwk: AAuthJwk): void {\n const compatible =\n (jwk.kty === 'RSA' && (alg.startsWith('RS') || alg.startsWith('PS'))) ||\n (jwk.kty === 'EC' && alg.startsWith('ES')) ||\n (jwk.kty === 'OKP' && alg === 'EdDSA');\n if (!compatible) {\n throw new AAuthError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, 'invalid_token');\n }\n if (jwk.alg && jwk.alg !== alg) {\n throw new AAuthError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, 'invalid_token');\n }\n}\n\nasync function fetchIssuerJwks(\n issuer: string,\n fetchFn?: typeof globalThis.fetch\n): Promise<{ keys: AAuthJwk[] }> {\n const doFetch = fetchFn ?? globalThis.fetch;\n const url = `${issuer.replace(/\\/+$/, '')}/aauth/jwks.json`;\n const response = await doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, 'jwks_fetch_failed', response.status);\n }\n const jwks = (await response.json()) as { keys?: AAuthJwk[] };\n if (!Array.isArray(jwks.keys)) {\n throw new AAuthError('Issuer JWKS is malformed', 'jwks_fetch_failed');\n }\n return { keys: jwks.keys };\n}\n","import { LumoAuthError } from '@lumoauth/shared';\n\n/**\n * Thrown for AAuth protocol failures — OAuth-style `{error,\n * error_description}` bodies from the agent token endpoint, signature\n * problems, and token-verification failures.\n */\nexport class AAuthError extends LumoAuthError {\n constructor(\n message: string,\n /** OAuth-style error code, e.g. `invalid_grant`, `authentication_required`. */\n code: string,\n statusCode?: number,\n /** The parsed response body, when the error came from the server. */\n public readonly body?: unknown\n ) {\n super(message, code, statusCode);\n this.name = 'AAuthError';\n }\n}\n","import { generateKeypair, jwkThumbprint, publicJwkFromPrivateKey, type AAuthJwk, type AAuthKeypair } from './keys';\nimport { signRequest, type SignRequestOptions } from './signing';\nimport { verifyAuthToken, type AAuthTokenClaims, type VerifyAuthTokenOptions } from './verify';\nimport { AAuthError } from './errors';\nimport { LumoAuthConfigError, LumoAuthNetworkError, ROUTES, buildPath } from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthClientOptions {\n /** HTTPS URL uniquely identifying the agent (e.g. `https://my-agent.example.com`). */\n agentIdentifier: string;\n /** PEM-encoded Ed25519 (PKCS#8) or RSA private key. */\n privateKeyPem: string;\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization ID (slug). Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** Key ID matching the JWKS entry registered with LumoAuth. Default `key-1`. */\n kid?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\n/** Successful response from the agent token endpoint. */\nexport interface AAuthTokenResponse {\n requestType: 'auth' | 'code' | 'exchange' | 'refresh';\n /** The `auth+jwt` access token to present to the resource. */\n authToken: string;\n expiresIn: number;\n tokenType: string; // \"auth+jwt\"\n refreshToken?: string;\n}\n\n/** Returned by `requestAuthToken()` when the user must consent first. */\nexport interface AAuthAuthorizationRequired {\n authorizationRequired: true;\n /** Opaque token identifying the pending request (600 s TTL). */\n requestToken: string;\n /** Consent page URL — redirect the user here. */\n authorizationUri: string;\n expiresIn?: number;\n}\n\nexport interface AAuthIssuerMetadata {\n issuer: string;\n aauth_version: string;\n jwks_uri: string;\n agent_token_endpoint: string;\n agent_auth_endpoint: string;\n agent_signing_algs_supported: string[];\n token_signing_algs_supported: string[];\n request_types_supported: string[];\n scopes_supported: string[];\n [key: string]: unknown;\n}\n\nexport interface AAuthAgentMetadata {\n agent: string;\n jwks_uri: string;\n redirect_uris?: string[];\n name?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthResourceMetadata {\n resource: string;\n jwks_uri: string;\n resource_token_endpoint?: string;\n supported_scopes?: string[];\n [key: string]: unknown;\n}\n\ninterface RawTokenResponse {\n request_type?: string;\n auth_token?: string;\n expires_in?: number;\n token_type?: string;\n refresh_token?: string;\n request_token?: string;\n authorization_uri?: string;\n auth_url?: string;\n error?: string;\n error_description?: string;\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * Client for the AAuth (Agent Auth) protocol — the Node.js counterpart of\n * the Python SDK's `lumoauth.AAuthClient`.\n *\n * AAuth extends OAuth 2.1 with cryptographic agent identity,\n * proof-of-possession tokens, and RFC 9421 HTTP message signing.\n *\n * @example\n * ```ts\n * import { AAuthClient } from '@lumoauth/agent';\n *\n * const client = new AAuthClient({\n * agentIdentifier: 'https://my-agent.example.com',\n * privateKeyPem: process.env.AGENT_PRIVATE_KEY!,\n * baseUrl: 'https://app.lumoauth.dev',\n * orgId: 'acme-corp',\n * });\n *\n * const result = await client.requestAuthToken({\n * resourceToken,\n * scope: 'read write',\n * agentToken,\n * });\n * if ('authorizationRequired' in result) {\n * // redirect the user to result.authorizationUri, then exchangeCode()\n * } else {\n * const resp = await client.signedRequest('GET', 'https://api.example.com/v1/data', {\n * authToken: result.authToken,\n * });\n * }\n * ```\n */\nexport class AAuthClient {\n /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */\n static generateKeypair = generateKeypair;\n\n readonly agentIdentifier: string;\n readonly baseUrl: string;\n readonly orgId: string;\n readonly kid: string;\n\n private readonly privateKeyPem: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly timeout: number;\n\n constructor(options: AAuthClientOptions) {\n if (!options.agentIdentifier) {\n throw new LumoAuthConfigError('agentIdentifier is required');\n }\n if (!options.privateKeyPem) {\n throw new LumoAuthConfigError('privateKeyPem is required');\n }\n this.agentIdentifier = options.agentIdentifier;\n this.privateKeyPem = options.privateKeyPem;\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.kid = options.kid ?? 'key-1';\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.timeout = options.timeout ?? 30_000;\n }\n\n /** The organization's AAuth issuer URL: `{baseUrl}/orgs/{orgId}/api/v1`. */\n get issuer(): string {\n return `${this.baseUrl}/orgs/${this.orgId}/api/v1`;\n }\n\n /** The agent's public JWK derived from its private key. */\n get publicJwk(): AAuthJwk {\n return publicJwkFromPrivateKey(this.privateKeyPem, this.kid);\n }\n\n /** RFC 7638 thumbprint of the agent's public key (the `jkt` binding value). */\n get publicJwkThumbprint(): string {\n return jwkThumbprint(this.publicJwk);\n }\n\n // ─── HTTP Message Signing ─────────────────────────────────────────\n\n /**\n * Create RFC 9421 signature headers for a request per the AAuth profile.\n * See `signRequest()` in `signing.ts` for the exact contract.\n */\n signRequest(method: string, url: string, options: SignRequestOptions = {}): Record<string, string> {\n return signRequest(this.privateKeyPem, method, url, options);\n }\n\n // ─── Token flows ──────────────────────────────────────────────────\n\n /**\n * Request an auth token (`request_type=auth` — direct authorization).\n *\n * Presents the resource token in the body and the agent token in the\n * `Agent-Auth` header, signed with the agent's key. If the server\n * requires user consent it returns `{ authorizationRequired: true,\n * requestToken, authorizationUri }` — redirect the user, then call\n * `exchangeCode()` with the code delivered to your `redirectUri`.\n */\n async requestAuthToken(params: {\n /** Resource token (`resource+jwt`) obtained from the target resource. */\n resourceToken: string;\n /** Space-separated scopes (informational; scopes bind via the resource token). */\n scope?: string;\n /** The `agent+jwt` presented in `Agent-Auth`. */\n agentToken: string;\n /** Redirect URI for user-consent flows (must be registered). */\n redirectUri?: string;\n }): Promise<AAuthTokenResponse | AAuthAuthorizationRequired> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'auth',\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n if (params.redirectUri) body.redirect_uri = params.redirectUri;\n\n const data = await this.tokenRequest(body, params.agentToken);\n\n if (!data.auth_token && (data.request_token || data.authorization_uri || data.auth_url)) {\n return {\n authorizationRequired: true,\n requestToken: data.request_token ?? '',\n authorizationUri: data.authorization_uri ?? data.auth_url ?? '',\n expiresIn: data.expires_in,\n };\n }\n return this.mapTokenResponse(data);\n }\n\n /**\n * Build the user-consent URL for a pending request token\n * (`GET {issuer}/aauth/agent/auth?request_token=…`). Prefer the\n * `authorizationUri` returned by `requestAuthToken()` when present.\n */\n buildConsentUrl(requestToken: string): string {\n return `${this.routeUrl('aauth.agentAuth')}?request_token=${encodeURIComponent(requestToken)}`;\n }\n\n /**\n * Exchange an authorization code for tokens (`request_type=code`) after\n * user consent. `redirectUri` must be the exact URI the code was\n * delivered to.\n */\n async exchangeCode(params: {\n code: string;\n redirectUri: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n { request_type: 'code', code: params.code, redirect_uri: params.redirectUri },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Multi-hop token exchange (`request_type=exchange`): trade an upstream\n * auth token plus a downstream resource token for a new auth token with\n * an `act` actor chain. Requires token exchange to be enabled for the\n * agent.\n */\n async exchangeToken(params: {\n /** The upstream `auth+jwt` addressed to this agent. */\n authToken: string;\n /** Resource token issued by the downstream resource to this agent. */\n resourceToken: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n {\n request_type: 'exchange',\n auth_token: params.authToken,\n resource_token: params.resourceToken,\n },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Refresh an auth token (`request_type=refresh`). A fresh resource token\n * for the target resource is required; scopes requested via the resource\n * token must be a subset of the original grant. Refresh tokens are not\n * rotated.\n */\n async refresh(params: {\n refreshToken: string;\n /** Fresh resource token for the target resource. */\n resourceToken: string;\n /** Optional scope narrowing. */\n scope?: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'refresh',\n refresh_token: params.refreshToken,\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n const data = await this.tokenRequest(body, params.agentToken);\n return this.mapTokenResponse(data);\n }\n\n /**\n * Revoke an auth token (by its `jti`) or a refresh token (by value).\n * Always resolves `{ revoked: true }` — the server does not reveal\n * whether the token existed.\n */\n async revoke(params: {\n /** A refresh-token value, or an auth token's `jti`. */\n token: string;\n tokenType?: 'auth_token' | 'refresh_token';\n agentToken: string;\n }): Promise<{ revoked: boolean }> {\n this.requireAgentToken(params.agentToken);\n const url = this.routeUrl('aauth.tokenRevoke');\n const data = await this.signedPost(url, {\n token: params.token,\n token_type: params.tokenType ?? 'auth_token',\n }, params.agentToken);\n return { revoked: Boolean((data as { revoked?: boolean }).revoked ?? true) };\n }\n\n // ─── Signed requests to protected resources ───────────────────────\n\n /**\n * Make a signed, authenticated request to a protected resource.\n *\n * Carries the auth token as `Authorization: Bearer …` **and** an RFC\n * 9421 signature proving possession of the key bound in the token's\n * `cnf.jwk`. The signature covers the `authorization` component, so the\n * resource can verify both together.\n *\n * Returns the raw `fetch` Response.\n */\n async signedRequest(\n method: string,\n url: string,\n options: {\n /** The AAuth `auth+jwt` access token. */\n authToken: string;\n /** JSON body (for POST/PUT). */\n data?: unknown;\n /** Extra headers (not covered by the signature). */\n headers?: Record<string, string>;\n }\n ): Promise<Response> {\n const bodyStr = options.data != null ? JSON.stringify(options.data) : '';\n const authorization = `Bearer ${options.authToken}`;\n const sigHeaders = this.signRequest(method, url, { body: bodyStr, authorization });\n\n return this.doFetch(url, {\n method: method.toUpperCase(),\n headers: { Authorization: authorization, ...sigHeaders, ...(options.headers ?? {}) },\n body: bodyStr !== '' ? bodyStr : undefined,\n });\n }\n\n // ─── Verification (resource-server side) ──────────────────────────\n\n /**\n * Verify an `auth+jwt` against this organization's issuer JWKS.\n * See `verifyAuthToken()` for details (PoP still required!).\n */\n async verifyAuthToken(\n token: string,\n options: Omit<VerifyAuthTokenOptions, 'issuer' | 'fetch'> & { issuer?: string }\n ): Promise<AAuthTokenClaims> {\n return verifyAuthToken(token, {\n issuer: options.issuer ?? this.issuer,\n fetch: this.fetchFn,\n ...options,\n });\n }\n\n // ─── Discovery ────────────────────────────────────────────────────\n\n /** Fetch `{issuer}/.well-known/aauth-issuer`. */\n async discoverIssuer(): Promise<AAuthIssuerMetadata> {\n return this.getJson<AAuthIssuerMetadata>(this.routeUrl('aauth.issuerMetadata'));\n }\n\n /** Fetch `{issuer}/.well-known/aauth-agent` — metadata for all active agents. */\n async discoverAgents(): Promise<AAuthAgentMetadata[]> {\n return this.getJson<AAuthAgentMetadata[]>(this.routeUrl('aauth.agentMetadata'));\n }\n\n /** Fetch `{resourceUrl}/.well-known/aauth-resource` from a resource server. */\n async discoverResource(resourceUrl: string): Promise<AAuthResourceMetadata | AAuthResourceMetadata[]> {\n const base = resourceUrl.replace(/\\/+$/, '');\n return this.getJson<AAuthResourceMetadata | AAuthResourceMetadata[]>(`${base}/.well-known/aauth-resource`);\n }\n\n // ─── Internals ────────────────────────────────────────────────────\n\n private requireAgentToken(agentToken: string): void {\n if (!agentToken) {\n throw new AAuthError(\n 'agentToken is required — the /agent/token endpoint authenticates the agent via the Agent-Auth header.',\n 'invalid_request'\n );\n }\n }\n\n private tokenUrl(): string {\n return this.routeUrl('aauth.agentToken');\n }\n\n /** Absolute URL for an org-scoped route from the shared registry. */\n private routeUrl(name: keyof typeof ROUTES): string {\n return `${this.baseUrl}${buildPath(ROUTES[name].path, { orgId: this.orgId })}`;\n }\n\n private async tokenRequest(body: Record<string, unknown>, agentToken: string): Promise<RawTokenResponse> {\n return (await this.signedPost(this.tokenUrl(), body, agentToken)) as RawTokenResponse;\n }\n\n private async signedPost(url: string, body: Record<string, unknown>, agentToken: string): Promise<unknown> {\n if (!this.orgId) {\n throw new LumoAuthConfigError('orgId is required for AAuth token operations');\n }\n const bodyStr = JSON.stringify(body);\n const headers = this.signRequest('POST', url, { body: bodyStr, agentToken });\n\n const response = await this.doFetch(url, { method: 'POST', headers, body: bodyStr });\n const text = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n\n if (!response.ok) {\n const err = (parsed ?? {}) as { error?: string; error_description?: string };\n throw new AAuthError(\n err.error_description ?? err.error ?? `AAuth request failed: HTTP ${response.status}`,\n err.error ?? 'aauth_error',\n response.status,\n parsed ?? text\n );\n }\n return parsed ?? {};\n }\n\n private mapTokenResponse(data: RawTokenResponse): AAuthTokenResponse {\n if (!data.auth_token) {\n throw new AAuthError('Token response missing auth_token', 'invalid_response', undefined, data);\n }\n const result: AAuthTokenResponse = {\n requestType: (data.request_type ?? 'auth') as AAuthTokenResponse['requestType'],\n authToken: data.auth_token,\n expiresIn: data.expires_in ?? 0,\n tokenType: data.token_type ?? 'auth+jwt',\n };\n if (data.refresh_token) result.refreshToken = data.refresh_token;\n return result;\n }\n\n private async getJson<T>(url: string): Promise<T> {\n const response = await this.doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Discovery request failed: HTTP ${response.status}`, 'discovery_failed', response.status);\n }\n return (await response.json()) as T;\n }\n\n private async doFetch(url: string, init: RequestInit): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n try {\n return await this.fetchFn(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n throw new LumoAuthNetworkError(`Request to ${url} timed out after ${this.timeout}ms`, error);\n }\n throw new LumoAuthNetworkError(\n `Network request to ${url} failed: ${error instanceof Error ? error.message : String(error)}`,\n error\n );\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n\nexport type { AAuthKeypair };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAeO;AAiCP,SAAS,OAAO,MAAkC;AAC9C,SAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,IAAI,IAAI,IAAI;AAC/E;AAGA,IAAM,0BAA0B;AAmCzB,IAAM,YAAN,MAAgB;AAAA,EAsBnB,YAAY,UAA4B,CAAC,GAAG;AAH5C,SAAQ,QAA2B;AACnC,SAAQ,iBAAyC;AAG7C,SAAK,WAAW,QAAQ,WAAW,OAA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;AACE,mBAAa,SAAS;AAAA,IAC1B;AAAA,EACJ;AACJ;AAAA;AAlWa,YAEF,kBAAkB;;;AN7E7B,IAAAC,iBAmBO;","names":["import_node_crypto","cryptoSign","cryptoVerify","import_node_crypto","import_shared","cryptoVerify","import_shared","envVar","import_shared"]}
package/dist/index.mjs CHANGED
@@ -696,11 +696,41 @@ var AAuthClient = class {
696
696
  };
697
697
  /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */
698
698
  AAuthClient.generateKeypair = generateKeypair;
699
+
700
+ // src/index.ts
701
+ import {
702
+ LumoAuthError as LumoAuthError2,
703
+ LumoAuthApiError as LumoAuthApiError2,
704
+ LumoAuthAuthenticationError,
705
+ LumoAuthPermissionDeniedError,
706
+ LumoAuthNotFoundError,
707
+ LumoAuthRateLimitError,
708
+ LumoAuthValidationError,
709
+ LumoAuthConfigError as LumoAuthConfigError3,
710
+ LumoAuthNetworkError as LumoAuthNetworkError3,
711
+ LumoAuthApprovalDeniedError,
712
+ LumoAuthApprovalTimeoutError,
713
+ LumoAuthApprovalNotDeliveredError,
714
+ LumoAuthBudgetExceededError
715
+ } from "@lumoauth/shared";
699
716
  export {
700
717
  AAUTH_COVERED_COMPONENTS,
701
718
  AAuthClient,
702
719
  AAuthError,
703
720
  LumoAgent,
721
+ LumoAuthApiError2 as LumoAuthApiError,
722
+ LumoAuthApprovalDeniedError,
723
+ LumoAuthApprovalNotDeliveredError,
724
+ LumoAuthApprovalTimeoutError,
725
+ LumoAuthAuthenticationError,
726
+ LumoAuthBudgetExceededError,
727
+ LumoAuthConfigError3 as LumoAuthConfigError,
728
+ LumoAuthError2 as LumoAuthError,
729
+ LumoAuthNetworkError3 as LumoAuthNetworkError,
730
+ LumoAuthNotFoundError,
731
+ LumoAuthPermissionDeniedError,
732
+ LumoAuthRateLimitError,
733
+ LumoAuthValidationError,
704
734
  buildSignatureBase,
705
735
  contentDigestSha256,
706
736
  decodeJwt,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent.ts","../src/keys.ts","../src/signing.ts","../src/verify.ts","../src/errors.ts","../src/client.ts"],"sourcesContent":["import {\n HttpClient,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthApiError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n ROUTES,\n buildPath,\n type AgentAskResult,\n type AgentIdentity,\n type AgentBudget,\n} from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface LumoAgentOptions {\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization slug. Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** OAuth client ID. Defaults to `process.env.AGENT_CLIENT_ID`. */\n clientId?: string;\n /** OAuth client secret. Defaults to `process.env.AGENT_CLIENT_SECRET`. */\n clientSecret?: string;\n /** Scopes to request. When omitted the server grants the agent's defaults. */\n scopes?: string[];\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\ninterface TokenState {\n accessToken: string;\n /** Epoch ms after which we refresh (real expiry minus the safety buffer). */\n refreshAt: number;\n scopes: string[];\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n/** Safety margin (ms) subtracted from `expires_in` so we refresh early. */\nconst TOKEN_REFRESH_BUFFER_MS = 60_000;\n\n// ─── LumoAgent ────────────────────────────────────────────────────────\n\n/**\n * High-level agent client — the Node.js counterpart of the Python SDK's\n * `LumoAuthAgent`.\n *\n * Handles the full agent lifecycle:\n * - OAuth 2.0 client-credentials authentication with transparent refresh\n * (60 s safety buffer)\n * - Preflight capability checks (`ask` / `isAllowed`)\n * - Self-inspection (`getCurrentAgent`, `capabilities`, `budget`)\n * - `jit`, `delegation`, `approvals`, and `mcp` namespaces\n *\n * For the AAuth protocol (cryptographic agent identity, RFC 9421 message\n * signing) use {@link AAuthClient} from this same package.\n *\n * @example\n * ```ts\n * import { LumoAgent } from '@lumoauth/agent';\n *\n * const agent = new LumoAgent(); // reads env vars by default\n * if (await agent.isAllowed('document.read', { id: 'doc_99' })) {\n * // ... do the thing\n * }\n *\n * const approval = await agent.approvals.require({\n * taskId: 'wire-001',\n * reason: 'Wire $4,500 to vendor INV-7741',\n * impact: 'high',\n * onBehalfOf: 'ada@acme.com',\n * });\n * ```\n */\nexport class LumoAgent {\n readonly baseUrl: string;\n readonly orgId: string;\n readonly clientId: string;\n\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n readonly agents: AgentsModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n readonly jit: JitModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n readonly delegation: DelegationModule;\n /** Push-approval-for-agent-actions. */\n readonly approvals: ApprovalsModule;\n /** Token exchange for secured MCP servers. */\n readonly mcp: McpModule;\n\n private readonly clientSecret: string;\n private readonly scopes: string[] | undefined;\n private readonly fetchFn: typeof globalThis.fetch;\n private token: TokenState | null = null;\n private refreshPromise: Promise<string> | null = null;\n\n constructor(options: LumoAgentOptions = {}) {\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.clientId = options.clientId ?? envVar('AGENT_CLIENT_ID') ?? '';\n this.clientSecret = options.clientSecret ?? envVar('AGENT_CLIENT_SECRET') ?? '';\n this.scopes = options.scopes;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (!this.clientId || !this.clientSecret) {\n throw new LumoAuthConfigError(\n 'Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET ' +\n 'environment variables or pass clientId/clientSecret to the constructor.',\n );\n }\n\n const tokenProvider = () => this.getAccessToken();\n const http = new HttpClient({\n baseUrl: this.baseUrl,\n token: tokenProvider,\n timeout: options.timeout,\n fetch: options.fetch,\n });\n\n this.agents = new AgentsModule(http, this.orgId);\n this.jit = new JitModule(http, this.orgId);\n this.approvals = new ApprovalsModule(http, this.orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n token: tokenProvider,\n fetch: options.fetch,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n redirectUri: options.redirectUri,\n agentToken: tokenProvider,\n fetch: options.fetch,\n });\n }\n\n // ── Authentication ────────────────────────────────────────────────\n\n /**\n * Authenticate with the client-credentials flow. Called automatically\n * by every API method — invoke it directly only to fail fast at\n * startup or to request non-default scopes.\n */\n async authenticate(scopes?: string[]): Promise<string> {\n const form: Record<string, string> = {\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret,\n };\n const requested = scopes ?? this.scopes;\n if (requested?.length) form.scope = requested.join(' ');\n\n const url = `${this.baseUrl}${buildPath(ROUTES['oauth.token'].path, { orgId: this.requireOrgId() })}`;\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(form),\n });\n } catch (error) {\n throw new LumoAuthNetworkError(\n `Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new LumoAuthApiError(\n typeof body.error_description === 'string'\n ? body.error_description\n : `Agent authentication failed (HTTP ${res.status})`,\n typeof body.error === 'string' ? body.error : 'AUTHENTICATION_ERROR',\n res.status,\n body,\n );\n }\n\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 3600;\n this.token = {\n accessToken: body.access_token,\n refreshAt: Date.now() + expiresIn * 1000 - TOKEN_REFRESH_BUFFER_MS,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n };\n return this.token.accessToken;\n }\n\n /**\n * The current access token, re-authenticating transparently when it is\n * missing or within 60 s of expiry. Concurrent callers share one\n * in-flight token request.\n */\n async getAccessToken(): Promise<string> {\n if (this.token && Date.now() < this.token.refreshAt) {\n return this.token.accessToken;\n }\n this.refreshPromise ??= this.authenticate(\n this.token?.scopes.length ? this.token.scopes : undefined,\n ).finally(() => {\n this.refreshPromise = null;\n });\n return this.refreshPromise;\n }\n\n /** Scopes granted by the last successful authentication. */\n get tokenScopes(): string[] {\n return this.token ? [...this.token.scopes] : [];\n }\n\n // ── Ask API & self-inspection (delegates to `agents`) ─────────────\n\n /** Preflight check: is the agent authorised to perform `action`? */\n async ask(action: string, context?: Record<string, unknown>): Promise<AgentAskResult> {\n return this.agents.ask(action, context);\n }\n\n /** Convenience wrapper: `true` when `action` is allowed. */\n async isAllowed(action: string, context?: Record<string, unknown>): Promise<boolean> {\n return this.agents.isAllowed(action, context);\n }\n\n /** The agent's own identity, capabilities, and workspace. */\n async getCurrentAgent(): Promise<AgentIdentity> {\n return this.agents.me();\n }\n\n /** The agent's declared capability slugs. */\n async capabilities(): Promise<string[]> {\n return this.agents.capabilities();\n }\n\n /** The agent's budget policy (empty object when no policy is set). */\n async budget(): Promise<AgentBudget> {\n return this.agents.budget();\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private requireOrgId(): string {\n if (!this.orgId) {\n throw new LumoAuthConfigError(\n 'orgId is required — pass it to the LumoAgent constructor or set LUMOAUTH_ORG_ID.',\n );\n }\n return this.orgId;\n }\n}\n","import { createHash, createPublicKey, createPrivateKey, generateKeyPairSync, type KeyObject } from 'node:crypto';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\n/** A public JSON Web Key as published in a JWKS. */\nexport interface AAuthJwk {\n kty: string;\n crv?: string;\n x?: string;\n y?: string;\n n?: string;\n e?: string;\n use?: string;\n kid?: string;\n alg?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthKeypair {\n /** PKCS#8 PEM-encoded Ed25519 private key. Store in your secret manager. */\n privateKeyPem: string;\n /** SPKI PEM-encoded public key. */\n publicKeyPem: string;\n /** The public key as a JWK (with `use: \"sig\"` and the given `kid`). */\n jwk: AAuthJwk;\n /** A JWKS document ready to publish at `/.well-known/jwks.json`. */\n jwks: { keys: AAuthJwk[] };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\nexport function base64UrlEncode(data: Buffer | Uint8Array | string): string {\n return Buffer.from(data).toString('base64url');\n}\n\nexport function base64UrlDecode(data: string): Buffer {\n return Buffer.from(data, 'base64url');\n}\n\n// ─── Key generation ───────────────────────────────────────────────────\n\n/**\n * Generate an Ed25519 key pair suitable for AAuth.\n *\n * Mirrors the Python SDK's `AAuthClient.generate_keypair()`: returns the\n * PKCS#8 private key PEM plus a JWKS document ready to be published at\n * `/.well-known/jwks.json` (or registered inline with LumoAuth).\n *\n * @example\n * ```ts\n * import { generateKeypair } from '@lumoauth/agent';\n *\n * const { privateKeyPem, jwks } = generateKeypair();\n * console.log(JSON.stringify(jwks, null, 2));\n * ```\n */\nexport function generateKeypair(kid = 'key-1'): AAuthKeypair {\n const { privateKey, publicKey } = generateKeyPairSync('ed25519');\n\n const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();\n const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();\n\n const rawJwk = publicKey.export({ format: 'jwk' }) as { kty: string; crv: string; x: string };\n const jwk: AAuthJwk = {\n kty: rawJwk.kty,\n crv: rawJwk.crv,\n x: rawJwk.x,\n use: 'sig',\n kid,\n };\n\n return { privateKeyPem, publicKeyPem, jwk, jwks: { keys: [jwk] } };\n}\n\n/**\n * Compute the RFC 7638 JWK thumbprint (base64url-encoded SHA-256) of a\n * public JWK. This is the `jkt` value AAuth uses to bind tokens to keys.\n */\nexport function jwkThumbprint(jwk: AAuthJwk): string {\n let canonical: string;\n switch (jwk.kty) {\n case 'OKP':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });\n break;\n case 'EC':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });\n break;\n case 'RSA':\n canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });\n break;\n default:\n throw new Error(`Unsupported key type for thumbprint: ${jwk.kty}`);\n }\n return createHash('sha256').update(canonical, 'utf8').digest('base64url');\n}\n\n/**\n * Load a PEM private key (Ed25519 or RSA) into a Node.js KeyObject and\n * classify it for the RFC 9421 signing dispatch.\n */\nexport function loadPrivateKey(pem: string): { key: KeyObject; type: 'ed25519' | 'rsa' } {\n const key = createPrivateKey(pem);\n if (key.asymmetricKeyType === 'ed25519') {\n return { key, type: 'ed25519' };\n }\n if (key.asymmetricKeyType === 'rsa' || key.asymmetricKeyType === 'rsa-pss') {\n return { key, type: 'rsa' };\n }\n throw new Error(\n `AAuth requires an Ed25519 or RSA private key (got ${String(key.asymmetricKeyType)}).`\n );\n}\n\n/** Derive the public JWK for a loaded private key. */\nexport function publicJwkFromPrivateKey(pem: string, kid?: string): AAuthJwk {\n const priv = createPrivateKey(pem);\n const pub = createPublicKey(priv);\n const jwk = pub.export({ format: 'jwk' }) as AAuthJwk;\n if (kid) jwk.kid = kid;\n return jwk;\n}\n","import {\n constants,\n createHash,\n randomBytes,\n sign as cryptoSign,\n verify as cryptoVerify,\n type KeyObject,\n} from 'node:crypto';\nimport { loadPrivateKey } from './keys';\n\n/**\n * RFC 9421 HTTP Message Signing, profiled for AAuth.\n *\n * The LumoAuth agent token endpoint enforces a strict profile (AAuth 1.0 §4):\n *\n * - Covered components: `@method @authority @path signature-key\n * content-digest content-type authorization` (plus `@query` if and only if\n * the target URI has a query string).\n * - `Signature-Input` parameters: exactly `created` (within ±60 s) and a\n * fresh `nonce` (≥ 12 bytes / 96 bits of entropy, base64url).\n * - `Content-Digest` per RFC 9530 with **standard** base64 (`sha-256=:…:`).\n * - The `Signature` value is **base64url** encoded (`label=:…:`).\n * - Algorithms: Ed25519 or RSA-PSS-SHA512 (MGF1-SHA512, 64-byte salt),\n * dispatched by key type — do NOT declare an `alg` parameter.\n */\n\n// ─── Constants ────────────────────────────────────────────────────────\n\n/** Covered components required by the AAuth agent token endpoint, in order. */\nexport const AAUTH_COVERED_COMPONENTS = [\n '@method',\n '@authority',\n '@path',\n 'signature-key',\n 'content-digest',\n 'content-type',\n 'authorization',\n] as const;\n\nconst SIGNATURE_LABEL = 'sig1';\n\n// ─── Primitives ───────────────────────────────────────────────────────\n\n/**\n * Compute an RFC 9530 `Content-Digest` header value over the exact body\n * bytes. Uses sha-256 with STANDARD base64 (the server base64-decodes it).\n */\nexport function contentDigestSha256(body: Buffer | Uint8Array | string): string {\n const digest = createHash('sha256').update(body).digest('base64');\n return `sha-256=:${digest}:`;\n}\n\n/** Generate a fresh signature nonce: base64url of 16 random bytes (128 bits). */\nexport function generateNonce(): string {\n return randomBytes(16).toString('base64url');\n}\n\n/**\n * Build the RFC 9421 signature base: one `\"<component>\": <value>` line per\n * covered component in declared order, then the `\"@signature-params\"` line\n * carrying ONLY `created` and `nonce`.\n */\nexport function buildSignatureBase(\n components: readonly string[],\n values: Record<string, string>,\n created: number,\n nonce: string\n): string {\n const lines = components.map((c) => `\"${c}\": ${values[c] ?? ''}`);\n lines.push(`\"@signature-params\": ${signatureParams(components, created, nonce)}`);\n return lines.join('\\n');\n}\n\n/** The `(…);created=…;nonce=\"…\"` parameter string shared by the base and header. */\nexport function signatureParams(\n components: readonly string[],\n created: number,\n nonce: string\n): string {\n const coveredList = components.map((c) => `\"${c}\"`).join(' ');\n return `(${coveredList});created=${created};nonce=\"${nonce}\"`;\n}\n\n/**\n * Sign a signature base with the agent's private key.\n * Ed25519 keys produce `ed25519` signatures; RSA keys produce\n * `rsa-pss-sha512` signatures (MGF1-SHA512, salt length = digest length).\n * Returns the base64url-encoded signature (RFC 9421 profile).\n */\nexport function signSignatureBase(signatureBase: string, privateKey: KeyObject): string {\n const data = Buffer.from(signatureBase, 'utf8');\n let signature: Buffer;\n if (privateKey.asymmetricKeyType === 'ed25519') {\n signature = cryptoSign(null, data, privateKey);\n } else {\n signature = cryptoSign('sha512', data, {\n key: privateKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST, // 64 bytes for SHA-512\n });\n }\n return signature.toString('base64url');\n}\n\n/**\n * Verify a base64url signature over a signature base (resource-server side).\n * Dispatches on key type like the LumoAuth server does.\n */\nexport function verifySignatureBase(\n signatureBase: string,\n signatureB64url: string,\n publicKey: KeyObject\n): boolean {\n const data = Buffer.from(signatureBase, 'utf8');\n const sig = Buffer.from(signatureB64url, 'base64url');\n if (publicKey.asymmetricKeyType === 'ed25519') {\n return cryptoVerify(null, data, publicKey, sig);\n }\n return cryptoVerify('sha512', data, {\n key: publicKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST,\n }, sig);\n}\n\n// ─── Request signing ──────────────────────────────────────────────────\n\nexport interface SignRequestOptions {\n /** Raw request body. Defaults to the empty body. */\n body?: Buffer | Uint8Array | string;\n /** Media type of the body. Default: `application/json`. */\n contentType?: string;\n /** The `agent+jwt` to present in the `Agent-Auth` header. */\n agentToken?: string;\n /** Value of a covered `Authorization` header, if any (e.g. `Bearer …`). */\n authorization?: string;\n /** Value of a covered `Signature-Key` header, if any. */\n signatureKey?: string;\n /**\n * Override the `created` timestamp (seconds). Testing only — the server\n * rejects timestamps more than 60 s from its clock.\n */\n created?: number;\n /** Override the nonce. Testing only — nonces are single-use server-side. */\n nonce?: string;\n}\n\n/**\n * Create RFC 9421 signature headers for a request to the AAuth agent token\n * endpoint (or any endpoint enforcing the AAuth profile).\n *\n * Byte-compatible with the Python SDK's `AAuthClient.sign_request()`.\n */\nexport function signRequest(\n privateKeyPem: string,\n method: string,\n url: string,\n options: SignRequestOptions = {}\n): Record<string, string> {\n const { key } = loadPrivateKey(privateKeyPem);\n const parsed = new URL(url);\n const authority = parsed.host; // host[:port], lowercased by the URL parser\n const path = parsed.pathname || '/';\n const query = parsed.search; // '' or '?…'\n\n const body = options.body ?? Buffer.alloc(0);\n const contentType = options.contentType ?? 'application/json';\n const contentDigest = contentDigestSha256(body);\n\n const created = options.created ?? Math.floor(Date.now() / 1000);\n const nonce = options.nonce ?? generateNonce();\n\n // @query MUST be covered if and only if the target has a query string.\n const components: string[] = ['@method', '@authority', '@path'];\n if (query !== '') components.push('@query');\n components.push('signature-key', 'content-digest', 'content-type', 'authorization');\n\n const values: Record<string, string> = {\n '@method': method.toUpperCase(),\n '@authority': authority,\n '@path': path,\n 'signature-key': options.signatureKey ?? '',\n 'content-digest': contentDigest,\n 'content-type': contentType,\n authorization: options.authorization ?? '',\n };\n if (query !== '') values['@query'] = query;\n\n const signatureBase = buildSignatureBase(components, values, created, nonce);\n const signature = signSignatureBase(signatureBase, key);\n\n const headers: Record<string, string> = {\n 'Content-Digest': contentDigest,\n 'Content-Type': contentType,\n 'Signature-Input': `${SIGNATURE_LABEL}=${signatureParams(components, created, nonce)}`,\n Signature: `${SIGNATURE_LABEL}=:${signature}:`,\n };\n if (options.agentToken) {\n headers['Agent-Auth'] = `agent_token=${options.agentToken}`;\n }\n if (options.signatureKey) {\n headers['Signature-Key'] = options.signatureKey;\n }\n return headers;\n}\n","import { constants, createPublicKey, verify as cryptoVerify, type KeyObject } from 'node:crypto';\nimport type { AAuthJwk } from './keys';\nimport { AAuthError } from './errors';\n\n/**\n * Auth-token (`auth+jwt`) verification for resource servers.\n *\n * Verifies the JWS signature against the organization's AAuth issuer JWKS\n * (`{issuer}/aauth/jwks.json`), plus `typ`, `iss`, `aud`, and `exp` — the\n * same checks LumoAuth's own `validateAuthToken()` performs (revocation\n * excepted: use `POST {issuer}/aauth/auth/token/verify` for live\n * revocation-aware introspection).\n *\n * NOTE: AAuth auth tokens are proof-of-possession tokens. After verifying\n * the JWT, the resource MUST also verify the request's RFC 9421 signature\n * against the key in `cnf.jwk` (see `verifySignatureBase` and\n * `jwkThumbprint`).\n */\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthTokenClaims {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n jti: string;\n cnf: { jwk: AAuthJwk };\n agent?: string;\n agent_delegate?: string;\n scope?: string;\n sub?: string;\n act?: Record<string, unknown>;\n [claim: string]: unknown;\n}\n\nexport interface VerifyAuthTokenOptions {\n /** The trusted issuer URL, e.g. `https://app.lumoauth.dev/orgs/acme-corp/api/v1`. */\n issuer: string;\n /** Your resource identifier — must equal the token's `aud`. */\n resource: string;\n /** Pre-fetched issuer JWKS (skips the network fetch). */\n jwks?: { keys: AAuthJwk[] };\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Allowed clock skew in seconds for `exp`. Default 0 (like the server). */\n clockSkew?: number;\n}\n\n// Only asymmetric JWS algorithms; HS* and none are always rejected.\nconst JWS_VERIFIERS: Record<string, (data: Buffer, key: KeyObject, sig: Buffer) => boolean> = {\n RS256: (d, k, s) => cryptoVerify('sha256', d, k, s),\n RS384: (d, k, s) => cryptoVerify('sha384', d, k, s),\n RS512: (d, k, s) => cryptoVerify('sha512', d, k, s),\n PS256: (d, k, s) => cryptoVerify('sha256', d, pss(k), s),\n PS384: (d, k, s) => cryptoVerify('sha384', d, pss(k), s),\n PS512: (d, k, s) => cryptoVerify('sha512', d, pss(k), s),\n ES256: (d, k, s) => cryptoVerify('sha256', d, p1363(k), s),\n ES384: (d, k, s) => cryptoVerify('sha384', d, p1363(k), s),\n ES512: (d, k, s) => cryptoVerify('sha512', d, p1363(k), s),\n EdDSA: (d, k, s) => cryptoVerify(null, d, k, s),\n};\n\nfunction pss(key: KeyObject) {\n return { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST };\n}\n\nfunction p1363(key: KeyObject) {\n return { key, dsaEncoding: 'ieee-p1363' as const };\n}\n\nfunction decodeSegment(segment: string): unknown {\n return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n}\n\n/** Decode a JWT without verifying it. Useful for reading `aud`/`cnf` first. */\nexport function decodeJwt(token: string): { header: Record<string, unknown>; claims: Record<string, unknown> } {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n return {\n header: decodeSegment(parts[0]) as Record<string, unknown>,\n claims: decodeSegment(parts[1]) as Record<string, unknown>,\n };\n}\n\n/**\n * Verify an AAuth auth token (`auth+jwt`) against the issuing\n * organization's JWKS. Returns the verified claims or throws `AAuthError`.\n *\n * @example\n * ```ts\n * import { verifyAuthToken } from '@lumoauth/agent';\n *\n * const claims = await verifyAuthToken(bearer, {\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://api.example.com',\n * });\n * // Then enforce PoP: verify the request signature against claims.cnf.jwk.\n * ```\n */\nexport async function verifyAuthToken(\n token: string,\n options: VerifyAuthTokenOptions\n): Promise<AAuthTokenClaims> {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n const header = decodeSegment(parts[0]) as Record<string, unknown>;\n const claims = decodeSegment(parts[1]) as Record<string, unknown>;\n\n if (header.typ !== 'auth+jwt') {\n throw new AAuthError(`Unexpected token type: ${String(header.typ)}`, 'invalid_token');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const kid = typeof header.kid === 'string' ? header.kid : '';\n if (!alg || !kid) {\n throw new AAuthError('Missing kid or alg in JOSE header', 'invalid_token');\n }\n const verifier = JWS_VERIFIERS[alg];\n if (!verifier) {\n throw new AAuthError(`Disallowed JWS algorithm: ${alg}`, 'invalid_token');\n }\n\n if (claims.iss !== options.issuer) {\n throw new AAuthError('Untrusted issuer', 'invalid_token');\n }\n\n // Resolve the signing key from the issuer JWKS\n const jwks = options.jwks ?? (await fetchIssuerJwks(options.issuer, options.fetch));\n const jwk = jwks.keys.find((k) => k.kid === kid);\n if (!jwk) {\n throw new AAuthError(`Key not found: kid=${kid}`, 'invalid_token');\n }\n assertAlgMatchesKey(alg, jwk);\n\n const publicKey = createPublicKey({ key: jwk as unknown as Record<string, unknown>, format: 'jwk' });\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n if (!verifier(data, publicKey, signature)) {\n throw new AAuthError('Signature verification failed', 'invalid_token');\n }\n\n // Temporal + audience checks (post-signature, like the server)\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 0;\n if (typeof claims.exp !== 'number' || claims.exp < now - skew) {\n throw new AAuthError('Auth token expired', 'invalid_token');\n }\n if (claims.aud !== options.resource) {\n throw new AAuthError('Invalid audience', 'invalid_token');\n }\n const cnf = claims.cnf as { jwk?: AAuthJwk } | undefined;\n if (!cnf || !cnf.jwk) {\n throw new AAuthError('Missing cnf.jwk claim', 'invalid_token');\n }\n\n return claims as unknown as AAuthTokenClaims;\n}\n\nfunction assertAlgMatchesKey(alg: string, jwk: AAuthJwk): void {\n const compatible =\n (jwk.kty === 'RSA' && (alg.startsWith('RS') || alg.startsWith('PS'))) ||\n (jwk.kty === 'EC' && alg.startsWith('ES')) ||\n (jwk.kty === 'OKP' && alg === 'EdDSA');\n if (!compatible) {\n throw new AAuthError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, 'invalid_token');\n }\n if (jwk.alg && jwk.alg !== alg) {\n throw new AAuthError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, 'invalid_token');\n }\n}\n\nasync function fetchIssuerJwks(\n issuer: string,\n fetchFn?: typeof globalThis.fetch\n): Promise<{ keys: AAuthJwk[] }> {\n const doFetch = fetchFn ?? globalThis.fetch;\n const url = `${issuer.replace(/\\/+$/, '')}/aauth/jwks.json`;\n const response = await doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, 'jwks_fetch_failed', response.status);\n }\n const jwks = (await response.json()) as { keys?: AAuthJwk[] };\n if (!Array.isArray(jwks.keys)) {\n throw new AAuthError('Issuer JWKS is malformed', 'jwks_fetch_failed');\n }\n return { keys: jwks.keys };\n}\n","import { LumoAuthError } from '@lumoauth/shared';\n\n/**\n * Thrown for AAuth protocol failures — OAuth-style `{error,\n * error_description}` bodies from the agent token endpoint, signature\n * problems, and token-verification failures.\n */\nexport class AAuthError extends LumoAuthError {\n constructor(\n message: string,\n /** OAuth-style error code, e.g. `invalid_grant`, `authentication_required`. */\n code: string,\n statusCode?: number,\n /** The parsed response body, when the error came from the server. */\n public readonly body?: unknown\n ) {\n super(message, code, statusCode);\n this.name = 'AAuthError';\n }\n}\n","import { generateKeypair, jwkThumbprint, publicJwkFromPrivateKey, type AAuthJwk, type AAuthKeypair } from './keys';\nimport { signRequest, type SignRequestOptions } from './signing';\nimport { verifyAuthToken, type AAuthTokenClaims, type VerifyAuthTokenOptions } from './verify';\nimport { AAuthError } from './errors';\nimport { LumoAuthConfigError, LumoAuthNetworkError, ROUTES, buildPath } from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthClientOptions {\n /** HTTPS URL uniquely identifying the agent (e.g. `https://my-agent.example.com`). */\n agentIdentifier: string;\n /** PEM-encoded Ed25519 (PKCS#8) or RSA private key. */\n privateKeyPem: string;\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization ID (slug). Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** Key ID matching the JWKS entry registered with LumoAuth. Default `key-1`. */\n kid?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\n/** Successful response from the agent token endpoint. */\nexport interface AAuthTokenResponse {\n requestType: 'auth' | 'code' | 'exchange' | 'refresh';\n /** The `auth+jwt` access token to present to the resource. */\n authToken: string;\n expiresIn: number;\n tokenType: string; // \"auth+jwt\"\n refreshToken?: string;\n}\n\n/** Returned by `requestAuthToken()` when the user must consent first. */\nexport interface AAuthAuthorizationRequired {\n authorizationRequired: true;\n /** Opaque token identifying the pending request (600 s TTL). */\n requestToken: string;\n /** Consent page URL — redirect the user here. */\n authorizationUri: string;\n expiresIn?: number;\n}\n\nexport interface AAuthIssuerMetadata {\n issuer: string;\n aauth_version: string;\n jwks_uri: string;\n agent_token_endpoint: string;\n agent_auth_endpoint: string;\n agent_signing_algs_supported: string[];\n token_signing_algs_supported: string[];\n request_types_supported: string[];\n scopes_supported: string[];\n [key: string]: unknown;\n}\n\nexport interface AAuthAgentMetadata {\n agent: string;\n jwks_uri: string;\n redirect_uris?: string[];\n name?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthResourceMetadata {\n resource: string;\n jwks_uri: string;\n resource_token_endpoint?: string;\n supported_scopes?: string[];\n [key: string]: unknown;\n}\n\ninterface RawTokenResponse {\n request_type?: string;\n auth_token?: string;\n expires_in?: number;\n token_type?: string;\n refresh_token?: string;\n request_token?: string;\n authorization_uri?: string;\n auth_url?: string;\n error?: string;\n error_description?: string;\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * Client for the AAuth (Agent Auth) protocol — the Node.js counterpart of\n * the Python SDK's `lumoauth.AAuthClient`.\n *\n * AAuth extends OAuth 2.1 with cryptographic agent identity,\n * proof-of-possession tokens, and RFC 9421 HTTP message signing.\n *\n * @example\n * ```ts\n * import { AAuthClient } from '@lumoauth/agent';\n *\n * const client = new AAuthClient({\n * agentIdentifier: 'https://my-agent.example.com',\n * privateKeyPem: process.env.AGENT_PRIVATE_KEY!,\n * baseUrl: 'https://app.lumoauth.dev',\n * orgId: 'acme-corp',\n * });\n *\n * const result = await client.requestAuthToken({\n * resourceToken,\n * scope: 'read write',\n * agentToken,\n * });\n * if ('authorizationRequired' in result) {\n * // redirect the user to result.authorizationUri, then exchangeCode()\n * } else {\n * const resp = await client.signedRequest('GET', 'https://api.example.com/v1/data', {\n * authToken: result.authToken,\n * });\n * }\n * ```\n */\nexport class AAuthClient {\n /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */\n static generateKeypair = generateKeypair;\n\n readonly agentIdentifier: string;\n readonly baseUrl: string;\n readonly orgId: string;\n readonly kid: string;\n\n private readonly privateKeyPem: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly timeout: number;\n\n constructor(options: AAuthClientOptions) {\n if (!options.agentIdentifier) {\n throw new LumoAuthConfigError('agentIdentifier is required');\n }\n if (!options.privateKeyPem) {\n throw new LumoAuthConfigError('privateKeyPem is required');\n }\n this.agentIdentifier = options.agentIdentifier;\n this.privateKeyPem = options.privateKeyPem;\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.kid = options.kid ?? 'key-1';\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.timeout = options.timeout ?? 30_000;\n }\n\n /** The organization's AAuth issuer URL: `{baseUrl}/orgs/{orgId}/api/v1`. */\n get issuer(): string {\n return `${this.baseUrl}/orgs/${this.orgId}/api/v1`;\n }\n\n /** The agent's public JWK derived from its private key. */\n get publicJwk(): AAuthJwk {\n return publicJwkFromPrivateKey(this.privateKeyPem, this.kid);\n }\n\n /** RFC 7638 thumbprint of the agent's public key (the `jkt` binding value). */\n get publicJwkThumbprint(): string {\n return jwkThumbprint(this.publicJwk);\n }\n\n // ─── HTTP Message Signing ─────────────────────────────────────────\n\n /**\n * Create RFC 9421 signature headers for a request per the AAuth profile.\n * See `signRequest()` in `signing.ts` for the exact contract.\n */\n signRequest(method: string, url: string, options: SignRequestOptions = {}): Record<string, string> {\n return signRequest(this.privateKeyPem, method, url, options);\n }\n\n // ─── Token flows ──────────────────────────────────────────────────\n\n /**\n * Request an auth token (`request_type=auth` — direct authorization).\n *\n * Presents the resource token in the body and the agent token in the\n * `Agent-Auth` header, signed with the agent's key. If the server\n * requires user consent it returns `{ authorizationRequired: true,\n * requestToken, authorizationUri }` — redirect the user, then call\n * `exchangeCode()` with the code delivered to your `redirectUri`.\n */\n async requestAuthToken(params: {\n /** Resource token (`resource+jwt`) obtained from the target resource. */\n resourceToken: string;\n /** Space-separated scopes (informational; scopes bind via the resource token). */\n scope?: string;\n /** The `agent+jwt` presented in `Agent-Auth`. */\n agentToken: string;\n /** Redirect URI for user-consent flows (must be registered). */\n redirectUri?: string;\n }): Promise<AAuthTokenResponse | AAuthAuthorizationRequired> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'auth',\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n if (params.redirectUri) body.redirect_uri = params.redirectUri;\n\n const data = await this.tokenRequest(body, params.agentToken);\n\n if (!data.auth_token && (data.request_token || data.authorization_uri || data.auth_url)) {\n return {\n authorizationRequired: true,\n requestToken: data.request_token ?? '',\n authorizationUri: data.authorization_uri ?? data.auth_url ?? '',\n expiresIn: data.expires_in,\n };\n }\n return this.mapTokenResponse(data);\n }\n\n /**\n * Build the user-consent URL for a pending request token\n * (`GET {issuer}/aauth/agent/auth?request_token=…`). Prefer the\n * `authorizationUri` returned by `requestAuthToken()` when present.\n */\n buildConsentUrl(requestToken: string): string {\n return `${this.routeUrl('aauth.agentAuth')}?request_token=${encodeURIComponent(requestToken)}`;\n }\n\n /**\n * Exchange an authorization code for tokens (`request_type=code`) after\n * user consent. `redirectUri` must be the exact URI the code was\n * delivered to.\n */\n async exchangeCode(params: {\n code: string;\n redirectUri: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n { request_type: 'code', code: params.code, redirect_uri: params.redirectUri },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Multi-hop token exchange (`request_type=exchange`): trade an upstream\n * auth token plus a downstream resource token for a new auth token with\n * an `act` actor chain. Requires token exchange to be enabled for the\n * agent.\n */\n async exchangeToken(params: {\n /** The upstream `auth+jwt` addressed to this agent. */\n authToken: string;\n /** Resource token issued by the downstream resource to this agent. */\n resourceToken: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n {\n request_type: 'exchange',\n auth_token: params.authToken,\n resource_token: params.resourceToken,\n },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Refresh an auth token (`request_type=refresh`). A fresh resource token\n * for the target resource is required; scopes requested via the resource\n * token must be a subset of the original grant. Refresh tokens are not\n * rotated.\n */\n async refresh(params: {\n refreshToken: string;\n /** Fresh resource token for the target resource. */\n resourceToken: string;\n /** Optional scope narrowing. */\n scope?: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'refresh',\n refresh_token: params.refreshToken,\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n const data = await this.tokenRequest(body, params.agentToken);\n return this.mapTokenResponse(data);\n }\n\n /**\n * Revoke an auth token (by its `jti`) or a refresh token (by value).\n * Always resolves `{ revoked: true }` — the server does not reveal\n * whether the token existed.\n */\n async revoke(params: {\n /** A refresh-token value, or an auth token's `jti`. */\n token: string;\n tokenType?: 'auth_token' | 'refresh_token';\n agentToken: string;\n }): Promise<{ revoked: boolean }> {\n this.requireAgentToken(params.agentToken);\n const url = this.routeUrl('aauth.tokenRevoke');\n const data = await this.signedPost(url, {\n token: params.token,\n token_type: params.tokenType ?? 'auth_token',\n }, params.agentToken);\n return { revoked: Boolean((data as { revoked?: boolean }).revoked ?? true) };\n }\n\n // ─── Signed requests to protected resources ───────────────────────\n\n /**\n * Make a signed, authenticated request to a protected resource.\n *\n * Carries the auth token as `Authorization: Bearer …` **and** an RFC\n * 9421 signature proving possession of the key bound in the token's\n * `cnf.jwk`. The signature covers the `authorization` component, so the\n * resource can verify both together.\n *\n * Returns the raw `fetch` Response.\n */\n async signedRequest(\n method: string,\n url: string,\n options: {\n /** The AAuth `auth+jwt` access token. */\n authToken: string;\n /** JSON body (for POST/PUT). */\n data?: unknown;\n /** Extra headers (not covered by the signature). */\n headers?: Record<string, string>;\n }\n ): Promise<Response> {\n const bodyStr = options.data != null ? JSON.stringify(options.data) : '';\n const authorization = `Bearer ${options.authToken}`;\n const sigHeaders = this.signRequest(method, url, { body: bodyStr, authorization });\n\n return this.doFetch(url, {\n method: method.toUpperCase(),\n headers: { Authorization: authorization, ...sigHeaders, ...(options.headers ?? {}) },\n body: bodyStr !== '' ? bodyStr : undefined,\n });\n }\n\n // ─── Verification (resource-server side) ──────────────────────────\n\n /**\n * Verify an `auth+jwt` against this organization's issuer JWKS.\n * See `verifyAuthToken()` for details (PoP still required!).\n */\n async verifyAuthToken(\n token: string,\n options: Omit<VerifyAuthTokenOptions, 'issuer' | 'fetch'> & { issuer?: string }\n ): Promise<AAuthTokenClaims> {\n return verifyAuthToken(token, {\n issuer: options.issuer ?? this.issuer,\n fetch: this.fetchFn,\n ...options,\n });\n }\n\n // ─── Discovery ────────────────────────────────────────────────────\n\n /** Fetch `{issuer}/.well-known/aauth-issuer`. */\n async discoverIssuer(): Promise<AAuthIssuerMetadata> {\n return this.getJson<AAuthIssuerMetadata>(this.routeUrl('aauth.issuerMetadata'));\n }\n\n /** Fetch `{issuer}/.well-known/aauth-agent` — metadata for all active agents. */\n async discoverAgents(): Promise<AAuthAgentMetadata[]> {\n return this.getJson<AAuthAgentMetadata[]>(this.routeUrl('aauth.agentMetadata'));\n }\n\n /** Fetch `{resourceUrl}/.well-known/aauth-resource` from a resource server. */\n async discoverResource(resourceUrl: string): Promise<AAuthResourceMetadata | AAuthResourceMetadata[]> {\n const base = resourceUrl.replace(/\\/+$/, '');\n return this.getJson<AAuthResourceMetadata | AAuthResourceMetadata[]>(`${base}/.well-known/aauth-resource`);\n }\n\n // ─── Internals ────────────────────────────────────────────────────\n\n private requireAgentToken(agentToken: string): void {\n if (!agentToken) {\n throw new AAuthError(\n 'agentToken is required — the /agent/token endpoint authenticates the agent via the Agent-Auth header.',\n 'invalid_request'\n );\n }\n }\n\n private tokenUrl(): string {\n return this.routeUrl('aauth.agentToken');\n }\n\n /** Absolute URL for an org-scoped route from the shared registry. */\n private routeUrl(name: keyof typeof ROUTES): string {\n return `${this.baseUrl}${buildPath(ROUTES[name].path, { orgId: this.orgId })}`;\n }\n\n private async tokenRequest(body: Record<string, unknown>, agentToken: string): Promise<RawTokenResponse> {\n return (await this.signedPost(this.tokenUrl(), body, agentToken)) as RawTokenResponse;\n }\n\n private async signedPost(url: string, body: Record<string, unknown>, agentToken: string): Promise<unknown> {\n if (!this.orgId) {\n throw new LumoAuthConfigError('orgId is required for AAuth token operations');\n }\n const bodyStr = JSON.stringify(body);\n const headers = this.signRequest('POST', url, { body: bodyStr, agentToken });\n\n const response = await this.doFetch(url, { method: 'POST', headers, body: bodyStr });\n const text = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n\n if (!response.ok) {\n const err = (parsed ?? {}) as { error?: string; error_description?: string };\n throw new AAuthError(\n err.error_description ?? err.error ?? `AAuth request failed: HTTP ${response.status}`,\n err.error ?? 'aauth_error',\n response.status,\n parsed ?? text\n );\n }\n return parsed ?? {};\n }\n\n private mapTokenResponse(data: RawTokenResponse): AAuthTokenResponse {\n if (!data.auth_token) {\n throw new AAuthError('Token response missing auth_token', 'invalid_response', undefined, data);\n }\n const result: AAuthTokenResponse = {\n requestType: (data.request_type ?? 'auth') as AAuthTokenResponse['requestType'],\n authToken: data.auth_token,\n expiresIn: data.expires_in ?? 0,\n tokenType: data.token_type ?? 'auth+jwt',\n };\n if (data.refresh_token) result.refreshToken = data.refresh_token;\n return result;\n }\n\n private async getJson<T>(url: string): Promise<T> {\n const response = await this.doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Discovery request failed: HTTP ${response.status}`, 'discovery_failed', response.status);\n }\n return (await response.json()) as T;\n }\n\n private async doFetch(url: string, init: RequestInit): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n try {\n return await this.fetchFn(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n throw new LumoAuthNetworkError(`Request to ${url} timed out after ${this.timeout}ms`, error);\n }\n throw new LumoAuthNetworkError(\n `Network request to ${url} failed: ${error instanceof Error ? error.message : String(error)}`,\n error\n );\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n\nexport type { AAuthKeypair };\n"],"mappings":";AAAA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIG;AAiCP,SAAS,OAAO,MAAkC;AAC9C,SAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,IAAI,IAAI,IAAI;AAC/E;AAGA,IAAM,0BAA0B;AAmCzB,IAAM,YAAN,MAAgB;AAAA,EAsBnB,YAAY,UAA4B,CAAC,GAAG;AAH5C,SAAQ,QAA2B;AACnC,SAAQ,iBAAyC;AAG7C,SAAK,WAAW,QAAQ,WAAW,OAAO,cAAc,KAAK,4BAA4B,QAAQ,QAAQ,EAAE;AAC3G,SAAK,QAAQ,QAAQ,SAAS,OAAO,iBAAiB,KAAK;AAC3D,SAAK,WAAW,QAAQ,YAAY,OAAO,iBAAiB,KAAK;AACjE,SAAK,eAAe,QAAQ,gBAAgB,OAAO,qBAAqB,KAAK;AAC7E,SA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uthConfigError","LumoAuthNetworkError","ROUTES","buildPath","envVar"]}
1
+ {"version":3,"sources":["../src/agent.ts","../src/keys.ts","../src/signing.ts","../src/verify.ts","../src/errors.ts","../src/client.ts","../src/index.ts"],"sourcesContent":["import {\n HttpClient,\n AgentsModule,\n ApprovalsModule,\n DelegationModule,\n JitModule,\n McpModule,\n LumoAuthApiError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n ROUTES,\n buildPath,\n type AgentAskResult,\n type AgentIdentity,\n type AgentBudget,\n} from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface LumoAgentOptions {\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization slug. Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** OAuth client ID. Defaults to `process.env.AGENT_CLIENT_ID`. */\n clientId?: string;\n /** OAuth client secret. Defaults to `process.env.AGENT_CLIENT_SECRET`. */\n clientSecret?: string;\n /** Scopes to request. When omitted the server grants the agent's defaults. */\n scopes?: string[];\n /** OAuth callback URL for the delegation consent flow. */\n redirectUri?: string;\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\ninterface TokenState {\n accessToken: string;\n /** Epoch ms after which we refresh (real expiry minus the safety buffer). */\n refreshAt: number;\n scopes: string[];\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n/** Safety margin (ms) subtracted from `expires_in` so we refresh early. */\nconst TOKEN_REFRESH_BUFFER_MS = 60_000;\n\n// ─── LumoAgent ────────────────────────────────────────────────────────\n\n/**\n * High-level agent client — the Node.js counterpart of the Python SDK's\n * `LumoAuthAgent`.\n *\n * Handles the full agent lifecycle:\n * - OAuth 2.0 client-credentials authentication with transparent refresh\n * (60 s safety buffer)\n * - Preflight capability checks (`ask` / `isAllowed`)\n * - Self-inspection (`getCurrentAgent`, `capabilities`, `budget`)\n * - `jit`, `delegation`, `approvals`, and `mcp` namespaces\n *\n * For the AAuth protocol (cryptographic agent identity, RFC 9421 message\n * signing) use {@link AAuthClient} from this same package.\n *\n * @example\n * ```ts\n * import { LumoAgent } from '@lumoauth/agent';\n *\n * const agent = new LumoAgent(); // reads env vars by default\n * if (await agent.isAllowed('document.read', { id: 'doc_99' })) {\n * // ... do the thing\n * }\n *\n * const approval = await agent.approvals.require({\n * taskId: 'wire-001',\n * reason: 'Wire $4,500 to vendor INV-7741',\n * impact: 'high',\n * onBehalfOf: 'ada@acme.com',\n * });\n * ```\n */\nexport class LumoAgent {\n readonly baseUrl: string;\n readonly orgId: string;\n readonly clientId: string;\n\n /** Agent identity — ask/isAllowed, self-inspection, registration. */\n readonly agents: AgentsModule;\n /** Just-in-Time permissions — ephemeral tasks and scoped tokens. */\n readonly jit: JitModule;\n /** Chain of Agency — RFC 8693 delegation and nested agent chains. */\n readonly delegation: DelegationModule;\n /** Push-approval-for-agent-actions. */\n readonly approvals: ApprovalsModule;\n /** Token exchange for secured MCP servers. */\n readonly mcp: McpModule;\n\n private readonly clientSecret: string;\n private readonly scopes: string[] | undefined;\n private readonly fetchFn: typeof globalThis.fetch;\n private token: TokenState | null = null;\n private refreshPromise: Promise<string> | null = null;\n\n constructor(options: LumoAgentOptions = {}) {\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.clientId = options.clientId ?? envVar('AGENT_CLIENT_ID') ?? '';\n this.clientSecret = options.clientSecret ?? envVar('AGENT_CLIENT_SECRET') ?? '';\n this.scopes = options.scopes;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (!this.clientId || !this.clientSecret) {\n throw new LumoAuthConfigError(\n 'Agent credentials required. Set AGENT_CLIENT_ID and AGENT_CLIENT_SECRET ' +\n 'environment variables or pass clientId/clientSecret to the constructor.',\n );\n }\n\n const tokenProvider = () => this.getAccessToken();\n const http = new HttpClient({\n baseUrl: this.baseUrl,\n token: tokenProvider,\n timeout: options.timeout,\n fetch: options.fetch,\n });\n\n this.agents = new AgentsModule(http, this.orgId);\n this.jit = new JitModule(http, this.orgId);\n this.approvals = new ApprovalsModule(http, this.orgId);\n this.mcp = new McpModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n token: tokenProvider,\n fetch: options.fetch,\n });\n this.delegation = new DelegationModule({\n baseUrl: this.baseUrl,\n orgId: this.orgId,\n clientId: this.clientId,\n clientSecret: this.clientSecret,\n redirectUri: options.redirectUri,\n agentToken: tokenProvider,\n fetch: options.fetch,\n });\n }\n\n // ── Authentication ────────────────────────────────────────────────\n\n /**\n * Authenticate with the client-credentials flow. Called automatically\n * by every API method — invoke it directly only to fail fast at\n * startup or to request non-default scopes.\n */\n async authenticate(scopes?: string[]): Promise<string> {\n const form: Record<string, string> = {\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret,\n };\n const requested = scopes ?? this.scopes;\n if (requested?.length) form.scope = requested.join(' ');\n\n const url = `${this.baseUrl}${buildPath(ROUTES['oauth.token'].path, { orgId: this.requireOrgId() })}`;\n let res: Response;\n try {\n res = await this.fetchFn(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(form),\n });\n } catch (error) {\n throw new LumoAuthNetworkError(\n `Agent authentication failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new LumoAuthApiError(\n typeof body.error_description === 'string'\n ? body.error_description\n : `Agent authentication failed (HTTP ${res.status})`,\n typeof body.error === 'string' ? body.error : 'AUTHENTICATION_ERROR',\n res.status,\n body,\n );\n }\n\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 3600;\n this.token = {\n accessToken: body.access_token,\n refreshAt: Date.now() + expiresIn * 1000 - TOKEN_REFRESH_BUFFER_MS,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n };\n return this.token.accessToken;\n }\n\n /**\n * The current access token, re-authenticating transparently when it is\n * missing or within 60 s of expiry. Concurrent callers share one\n * in-flight token request.\n */\n async getAccessToken(): Promise<string> {\n if (this.token && Date.now() < this.token.refreshAt) {\n return this.token.accessToken;\n }\n this.refreshPromise ??= this.authenticate(\n this.token?.scopes.length ? this.token.scopes : undefined,\n ).finally(() => {\n this.refreshPromise = null;\n });\n return this.refreshPromise;\n }\n\n /** Scopes granted by the last successful authentication. */\n get tokenScopes(): string[] {\n return this.token ? [...this.token.scopes] : [];\n }\n\n // ── Ask API & self-inspection (delegates to `agents`) ─────────────\n\n /** Preflight check: is the agent authorised to perform `action`? */\n async ask(action: string, context?: Record<string, unknown>): Promise<AgentAskResult> {\n return this.agents.ask(action, context);\n }\n\n /** Convenience wrapper: `true` when `action` is allowed. */\n async isAllowed(action: string, context?: Record<string, unknown>): Promise<boolean> {\n return this.agents.isAllowed(action, context);\n }\n\n /** The agent's own identity, capabilities, and workspace. */\n async getCurrentAgent(): Promise<AgentIdentity> {\n return this.agents.me();\n }\n\n /** The agent's declared capability slugs. */\n async capabilities(): Promise<string[]> {\n return this.agents.capabilities();\n }\n\n /** The agent's budget policy (empty object when no policy is set). */\n async budget(): Promise<AgentBudget> {\n return this.agents.budget();\n }\n\n // ── Internal ──────────────────────────────────────────────────────\n\n private requireOrgId(): string {\n if (!this.orgId) {\n throw new LumoAuthConfigError(\n 'orgId is required — pass it to the LumoAgent constructor or set LUMOAUTH_ORG_ID.',\n );\n }\n return this.orgId;\n }\n}\n","import { createHash, createPublicKey, createPrivateKey, generateKeyPairSync, type KeyObject } from 'node:crypto';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\n/** A public JSON Web Key as published in a JWKS. */\nexport interface AAuthJwk {\n kty: string;\n crv?: string;\n x?: string;\n y?: string;\n n?: string;\n e?: string;\n use?: string;\n kid?: string;\n alg?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthKeypair {\n /** PKCS#8 PEM-encoded Ed25519 private key. Store in your secret manager. */\n privateKeyPem: string;\n /** SPKI PEM-encoded public key. */\n publicKeyPem: string;\n /** The public key as a JWK (with `use: \"sig\"` and the given `kid`). */\n jwk: AAuthJwk;\n /** A JWKS document ready to publish at `/.well-known/jwks.json`. */\n jwks: { keys: AAuthJwk[] };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\nexport function base64UrlEncode(data: Buffer | Uint8Array | string): string {\n return Buffer.from(data).toString('base64url');\n}\n\nexport function base64UrlDecode(data: string): Buffer {\n return Buffer.from(data, 'base64url');\n}\n\n// ─── Key generation ───────────────────────────────────────────────────\n\n/**\n * Generate an Ed25519 key pair suitable for AAuth.\n *\n * Mirrors the Python SDK's `AAuthClient.generate_keypair()`: returns the\n * PKCS#8 private key PEM plus a JWKS document ready to be published at\n * `/.well-known/jwks.json` (or registered inline with LumoAuth).\n *\n * @example\n * ```ts\n * import { generateKeypair } from '@lumoauth/agent';\n *\n * const { privateKeyPem, jwks } = generateKeypair();\n * console.log(JSON.stringify(jwks, null, 2));\n * ```\n */\nexport function generateKeypair(kid = 'key-1'): AAuthKeypair {\n const { privateKey, publicKey } = generateKeyPairSync('ed25519');\n\n const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();\n const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();\n\n const rawJwk = publicKey.export({ format: 'jwk' }) as { kty: string; crv: string; x: string };\n const jwk: AAuthJwk = {\n kty: rawJwk.kty,\n crv: rawJwk.crv,\n x: rawJwk.x,\n use: 'sig',\n kid,\n };\n\n return { privateKeyPem, publicKeyPem, jwk, jwks: { keys: [jwk] } };\n}\n\n/**\n * Compute the RFC 7638 JWK thumbprint (base64url-encoded SHA-256) of a\n * public JWK. This is the `jkt` value AAuth uses to bind tokens to keys.\n */\nexport function jwkThumbprint(jwk: AAuthJwk): string {\n let canonical: string;\n switch (jwk.kty) {\n case 'OKP':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });\n break;\n case 'EC':\n canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });\n break;\n case 'RSA':\n canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });\n break;\n default:\n throw new Error(`Unsupported key type for thumbprint: ${jwk.kty}`);\n }\n return createHash('sha256').update(canonical, 'utf8').digest('base64url');\n}\n\n/**\n * Load a PEM private key (Ed25519 or RSA) into a Node.js KeyObject and\n * classify it for the RFC 9421 signing dispatch.\n */\nexport function loadPrivateKey(pem: string): { key: KeyObject; type: 'ed25519' | 'rsa' } {\n const key = createPrivateKey(pem);\n if (key.asymmetricKeyType === 'ed25519') {\n return { key, type: 'ed25519' };\n }\n if (key.asymmetricKeyType === 'rsa' || key.asymmetricKeyType === 'rsa-pss') {\n return { key, type: 'rsa' };\n }\n throw new Error(\n `AAuth requires an Ed25519 or RSA private key (got ${String(key.asymmetricKeyType)}).`\n );\n}\n\n/** Derive the public JWK for a loaded private key. */\nexport function publicJwkFromPrivateKey(pem: string, kid?: string): AAuthJwk {\n const priv = createPrivateKey(pem);\n const pub = createPublicKey(priv);\n const jwk = pub.export({ format: 'jwk' }) as AAuthJwk;\n if (kid) jwk.kid = kid;\n return jwk;\n}\n","import {\n constants,\n createHash,\n randomBytes,\n sign as cryptoSign,\n verify as cryptoVerify,\n type KeyObject,\n} from 'node:crypto';\nimport { loadPrivateKey } from './keys';\n\n/**\n * RFC 9421 HTTP Message Signing, profiled for AAuth.\n *\n * The LumoAuth agent token endpoint enforces a strict profile (AAuth 1.0 §4):\n *\n * - Covered components: `@method @authority @path signature-key\n * content-digest content-type authorization` (plus `@query` if and only if\n * the target URI has a query string).\n * - `Signature-Input` parameters: exactly `created` (within ±60 s) and a\n * fresh `nonce` (≥ 12 bytes / 96 bits of entropy, base64url).\n * - `Content-Digest` per RFC 9530 with **standard** base64 (`sha-256=:…:`).\n * - The `Signature` value is **base64url** encoded (`label=:…:`).\n * - Algorithms: Ed25519 or RSA-PSS-SHA512 (MGF1-SHA512, 64-byte salt),\n * dispatched by key type — do NOT declare an `alg` parameter.\n */\n\n// ─── Constants ────────────────────────────────────────────────────────\n\n/** Covered components required by the AAuth agent token endpoint, in order. */\nexport const AAUTH_COVERED_COMPONENTS = [\n '@method',\n '@authority',\n '@path',\n 'signature-key',\n 'content-digest',\n 'content-type',\n 'authorization',\n] as const;\n\nconst SIGNATURE_LABEL = 'sig1';\n\n// ─── Primitives ───────────────────────────────────────────────────────\n\n/**\n * Compute an RFC 9530 `Content-Digest` header value over the exact body\n * bytes. Uses sha-256 with STANDARD base64 (the server base64-decodes it).\n */\nexport function contentDigestSha256(body: Buffer | Uint8Array | string): string {\n const digest = createHash('sha256').update(body).digest('base64');\n return `sha-256=:${digest}:`;\n}\n\n/** Generate a fresh signature nonce: base64url of 16 random bytes (128 bits). */\nexport function generateNonce(): string {\n return randomBytes(16).toString('base64url');\n}\n\n/**\n * Build the RFC 9421 signature base: one `\"<component>\": <value>` line per\n * covered component in declared order, then the `\"@signature-params\"` line\n * carrying ONLY `created` and `nonce`.\n */\nexport function buildSignatureBase(\n components: readonly string[],\n values: Record<string, string>,\n created: number,\n nonce: string\n): string {\n const lines = components.map((c) => `\"${c}\": ${values[c] ?? ''}`);\n lines.push(`\"@signature-params\": ${signatureParams(components, created, nonce)}`);\n return lines.join('\\n');\n}\n\n/** The `(…);created=…;nonce=\"…\"` parameter string shared by the base and header. */\nexport function signatureParams(\n components: readonly string[],\n created: number,\n nonce: string\n): string {\n const coveredList = components.map((c) => `\"${c}\"`).join(' ');\n return `(${coveredList});created=${created};nonce=\"${nonce}\"`;\n}\n\n/**\n * Sign a signature base with the agent's private key.\n * Ed25519 keys produce `ed25519` signatures; RSA keys produce\n * `rsa-pss-sha512` signatures (MGF1-SHA512, salt length = digest length).\n * Returns the base64url-encoded signature (RFC 9421 profile).\n */\nexport function signSignatureBase(signatureBase: string, privateKey: KeyObject): string {\n const data = Buffer.from(signatureBase, 'utf8');\n let signature: Buffer;\n if (privateKey.asymmetricKeyType === 'ed25519') {\n signature = cryptoSign(null, data, privateKey);\n } else {\n signature = cryptoSign('sha512', data, {\n key: privateKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST, // 64 bytes for SHA-512\n });\n }\n return signature.toString('base64url');\n}\n\n/**\n * Verify a base64url signature over a signature base (resource-server side).\n * Dispatches on key type like the LumoAuth server does.\n */\nexport function verifySignatureBase(\n signatureBase: string,\n signatureB64url: string,\n publicKey: KeyObject\n): boolean {\n const data = Buffer.from(signatureBase, 'utf8');\n const sig = Buffer.from(signatureB64url, 'base64url');\n if (publicKey.asymmetricKeyType === 'ed25519') {\n return cryptoVerify(null, data, publicKey, sig);\n }\n return cryptoVerify('sha512', data, {\n key: publicKey,\n padding: constants.RSA_PKCS1_PSS_PADDING,\n saltLength: constants.RSA_PSS_SALTLEN_DIGEST,\n }, sig);\n}\n\n// ─── Request signing ──────────────────────────────────────────────────\n\nexport interface SignRequestOptions {\n /** Raw request body. Defaults to the empty body. */\n body?: Buffer | Uint8Array | string;\n /** Media type of the body. Default: `application/json`. */\n contentType?: string;\n /** The `agent+jwt` to present in the `Agent-Auth` header. */\n agentToken?: string;\n /** Value of a covered `Authorization` header, if any (e.g. `Bearer …`). */\n authorization?: string;\n /** Value of a covered `Signature-Key` header, if any. */\n signatureKey?: string;\n /**\n * Override the `created` timestamp (seconds). Testing only — the server\n * rejects timestamps more than 60 s from its clock.\n */\n created?: number;\n /** Override the nonce. Testing only — nonces are single-use server-side. */\n nonce?: string;\n}\n\n/**\n * Create RFC 9421 signature headers for a request to the AAuth agent token\n * endpoint (or any endpoint enforcing the AAuth profile).\n *\n * Byte-compatible with the Python SDK's `AAuthClient.sign_request()`.\n */\nexport function signRequest(\n privateKeyPem: string,\n method: string,\n url: string,\n options: SignRequestOptions = {}\n): Record<string, string> {\n const { key } = loadPrivateKey(privateKeyPem);\n const parsed = new URL(url);\n const authority = parsed.host; // host[:port], lowercased by the URL parser\n const path = parsed.pathname || '/';\n const query = parsed.search; // '' or '?…'\n\n const body = options.body ?? Buffer.alloc(0);\n const contentType = options.contentType ?? 'application/json';\n const contentDigest = contentDigestSha256(body);\n\n const created = options.created ?? Math.floor(Date.now() / 1000);\n const nonce = options.nonce ?? generateNonce();\n\n // @query MUST be covered if and only if the target has a query string.\n const components: string[] = ['@method', '@authority', '@path'];\n if (query !== '') components.push('@query');\n components.push('signature-key', 'content-digest', 'content-type', 'authorization');\n\n const values: Record<string, string> = {\n '@method': method.toUpperCase(),\n '@authority': authority,\n '@path': path,\n 'signature-key': options.signatureKey ?? '',\n 'content-digest': contentDigest,\n 'content-type': contentType,\n authorization: options.authorization ?? '',\n };\n if (query !== '') values['@query'] = query;\n\n const signatureBase = buildSignatureBase(components, values, created, nonce);\n const signature = signSignatureBase(signatureBase, key);\n\n const headers: Record<string, string> = {\n 'Content-Digest': contentDigest,\n 'Content-Type': contentType,\n 'Signature-Input': `${SIGNATURE_LABEL}=${signatureParams(components, created, nonce)}`,\n Signature: `${SIGNATURE_LABEL}=:${signature}:`,\n };\n if (options.agentToken) {\n headers['Agent-Auth'] = `agent_token=${options.agentToken}`;\n }\n if (options.signatureKey) {\n headers['Signature-Key'] = options.signatureKey;\n }\n return headers;\n}\n","import { constants, createPublicKey, verify as cryptoVerify, type KeyObject } from 'node:crypto';\nimport type { AAuthJwk } from './keys';\nimport { AAuthError } from './errors';\n\n/**\n * Auth-token (`auth+jwt`) verification for resource servers.\n *\n * Verifies the JWS signature against the organization's AAuth issuer JWKS\n * (`{issuer}/aauth/jwks.json`), plus `typ`, `iss`, `aud`, and `exp` — the\n * same checks LumoAuth's own `validateAuthToken()` performs (revocation\n * excepted: use `POST {issuer}/aauth/auth/token/verify` for live\n * revocation-aware introspection).\n *\n * NOTE: AAuth auth tokens are proof-of-possession tokens. After verifying\n * the JWT, the resource MUST also verify the request's RFC 9421 signature\n * against the key in `cnf.jwk` (see `verifySignatureBase` and\n * `jwkThumbprint`).\n */\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthTokenClaims {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n jti: string;\n cnf: { jwk: AAuthJwk };\n agent?: string;\n agent_delegate?: string;\n scope?: string;\n sub?: string;\n act?: Record<string, unknown>;\n [claim: string]: unknown;\n}\n\nexport interface VerifyAuthTokenOptions {\n /** The trusted issuer URL, e.g. `https://app.lumoauth.dev/orgs/acme-corp/api/v1`. */\n issuer: string;\n /** Your resource identifier — must equal the token's `aud`. */\n resource: string;\n /** Pre-fetched issuer JWKS (skips the network fetch). */\n jwks?: { keys: AAuthJwk[] };\n /** Custom fetch implementation. */\n fetch?: typeof globalThis.fetch;\n /** Allowed clock skew in seconds for `exp`. Default 0 (like the server). */\n clockSkew?: number;\n}\n\n// Only asymmetric JWS algorithms; HS* and none are always rejected.\nconst JWS_VERIFIERS: Record<string, (data: Buffer, key: KeyObject, sig: Buffer) => boolean> = {\n RS256: (d, k, s) => cryptoVerify('sha256', d, k, s),\n RS384: (d, k, s) => cryptoVerify('sha384', d, k, s),\n RS512: (d, k, s) => cryptoVerify('sha512', d, k, s),\n PS256: (d, k, s) => cryptoVerify('sha256', d, pss(k), s),\n PS384: (d, k, s) => cryptoVerify('sha384', d, pss(k), s),\n PS512: (d, k, s) => cryptoVerify('sha512', d, pss(k), s),\n ES256: (d, k, s) => cryptoVerify('sha256', d, p1363(k), s),\n ES384: (d, k, s) => cryptoVerify('sha384', d, p1363(k), s),\n ES512: (d, k, s) => cryptoVerify('sha512', d, p1363(k), s),\n EdDSA: (d, k, s) => cryptoVerify(null, d, k, s),\n};\n\nfunction pss(key: KeyObject) {\n return { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST };\n}\n\nfunction p1363(key: KeyObject) {\n return { key, dsaEncoding: 'ieee-p1363' as const };\n}\n\nfunction decodeSegment(segment: string): unknown {\n return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n}\n\n/** Decode a JWT without verifying it. Useful for reading `aud`/`cnf` first. */\nexport function decodeJwt(token: string): { header: Record<string, unknown>; claims: Record<string, unknown> } {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n return {\n header: decodeSegment(parts[0]) as Record<string, unknown>,\n claims: decodeSegment(parts[1]) as Record<string, unknown>,\n };\n}\n\n/**\n * Verify an AAuth auth token (`auth+jwt`) against the issuing\n * organization's JWKS. Returns the verified claims or throws `AAuthError`.\n *\n * @example\n * ```ts\n * import { verifyAuthToken } from '@lumoauth/agent';\n *\n * const claims = await verifyAuthToken(bearer, {\n * issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',\n * resource: 'https://api.example.com',\n * });\n * // Then enforce PoP: verify the request signature against claims.cnf.jwk.\n * ```\n */\nexport async function verifyAuthToken(\n token: string,\n options: VerifyAuthTokenOptions\n): Promise<AAuthTokenClaims> {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AAuthError('Invalid JWT format', 'invalid_token');\n }\n const header = decodeSegment(parts[0]) as Record<string, unknown>;\n const claims = decodeSegment(parts[1]) as Record<string, unknown>;\n\n if (header.typ !== 'auth+jwt') {\n throw new AAuthError(`Unexpected token type: ${String(header.typ)}`, 'invalid_token');\n }\n const alg = typeof header.alg === 'string' ? header.alg : '';\n const kid = typeof header.kid === 'string' ? header.kid : '';\n if (!alg || !kid) {\n throw new AAuthError('Missing kid or alg in JOSE header', 'invalid_token');\n }\n const verifier = JWS_VERIFIERS[alg];\n if (!verifier) {\n throw new AAuthError(`Disallowed JWS algorithm: ${alg}`, 'invalid_token');\n }\n\n if (claims.iss !== options.issuer) {\n throw new AAuthError('Untrusted issuer', 'invalid_token');\n }\n\n // Resolve the signing key from the issuer JWKS\n const jwks = options.jwks ?? (await fetchIssuerJwks(options.issuer, options.fetch));\n const jwk = jwks.keys.find((k) => k.kid === kid);\n if (!jwk) {\n throw new AAuthError(`Key not found: kid=${kid}`, 'invalid_token');\n }\n assertAlgMatchesKey(alg, jwk);\n\n const publicKey = createPublicKey({ key: jwk as unknown as Record<string, unknown>, format: 'jwk' });\n const data = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');\n const signature = Buffer.from(parts[2], 'base64url');\n if (!verifier(data, publicKey, signature)) {\n throw new AAuthError('Signature verification failed', 'invalid_token');\n }\n\n // Temporal + audience checks (post-signature, like the server)\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 0;\n if (typeof claims.exp !== 'number' || claims.exp < now - skew) {\n throw new AAuthError('Auth token expired', 'invalid_token');\n }\n if (claims.aud !== options.resource) {\n throw new AAuthError('Invalid audience', 'invalid_token');\n }\n const cnf = claims.cnf as { jwk?: AAuthJwk } | undefined;\n if (!cnf || !cnf.jwk) {\n throw new AAuthError('Missing cnf.jwk claim', 'invalid_token');\n }\n\n return claims as unknown as AAuthTokenClaims;\n}\n\nfunction assertAlgMatchesKey(alg: string, jwk: AAuthJwk): void {\n const compatible =\n (jwk.kty === 'RSA' && (alg.startsWith('RS') || alg.startsWith('PS'))) ||\n (jwk.kty === 'EC' && alg.startsWith('ES')) ||\n (jwk.kty === 'OKP' && alg === 'EdDSA');\n if (!compatible) {\n throw new AAuthError(`Algorithm ${alg} incompatible with key type ${jwk.kty}`, 'invalid_token');\n }\n if (jwk.alg && jwk.alg !== alg) {\n throw new AAuthError(`Algorithm ${alg} does not match key alg ${jwk.alg}`, 'invalid_token');\n }\n}\n\nasync function fetchIssuerJwks(\n issuer: string,\n fetchFn?: typeof globalThis.fetch\n): Promise<{ keys: AAuthJwk[] }> {\n const doFetch = fetchFn ?? globalThis.fetch;\n const url = `${issuer.replace(/\\/+$/, '')}/aauth/jwks.json`;\n const response = await doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Failed to fetch issuer JWKS (HTTP ${response.status})`, 'jwks_fetch_failed', response.status);\n }\n const jwks = (await response.json()) as { keys?: AAuthJwk[] };\n if (!Array.isArray(jwks.keys)) {\n throw new AAuthError('Issuer JWKS is malformed', 'jwks_fetch_failed');\n }\n return { keys: jwks.keys };\n}\n","import { LumoAuthError } from '@lumoauth/shared';\n\n/**\n * Thrown for AAuth protocol failures — OAuth-style `{error,\n * error_description}` bodies from the agent token endpoint, signature\n * problems, and token-verification failures.\n */\nexport class AAuthError extends LumoAuthError {\n constructor(\n message: string,\n /** OAuth-style error code, e.g. `invalid_grant`, `authentication_required`. */\n code: string,\n statusCode?: number,\n /** The parsed response body, when the error came from the server. */\n public readonly body?: unknown\n ) {\n super(message, code, statusCode);\n this.name = 'AAuthError';\n }\n}\n","import { generateKeypair, jwkThumbprint, publicJwkFromPrivateKey, type AAuthJwk, type AAuthKeypair } from './keys';\nimport { signRequest, type SignRequestOptions } from './signing';\nimport { verifyAuthToken, type AAuthTokenClaims, type VerifyAuthTokenOptions } from './verify';\nimport { AAuthError } from './errors';\nimport { LumoAuthConfigError, LumoAuthNetworkError, ROUTES, buildPath } from '@lumoauth/shared';\n\n// ─── Types ────────────────────────────────────────────────────────────\n\nexport interface AAuthClientOptions {\n /** HTTPS URL uniquely identifying the agent (e.g. `https://my-agent.example.com`). */\n agentIdentifier: string;\n /** PEM-encoded Ed25519 (PKCS#8) or RSA private key. */\n privateKeyPem: string;\n /**\n * LumoAuth instance URL. Defaults to `process.env.LUMOAUTH_URL` or\n * `https://app.lumoauth.dev`.\n */\n baseUrl?: string;\n /** Organization ID (slug). Defaults to `process.env.LUMOAUTH_ORG_ID`. */\n orgId?: string;\n /** Key ID matching the JWKS entry registered with LumoAuth. Default `key-1`. */\n kid?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof globalThis.fetch;\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n}\n\n/** Successful response from the agent token endpoint. */\nexport interface AAuthTokenResponse {\n requestType: 'auth' | 'code' | 'exchange' | 'refresh';\n /** The `auth+jwt` access token to present to the resource. */\n authToken: string;\n expiresIn: number;\n tokenType: string; // \"auth+jwt\"\n refreshToken?: string;\n}\n\n/** Returned by `requestAuthToken()` when the user must consent first. */\nexport interface AAuthAuthorizationRequired {\n authorizationRequired: true;\n /** Opaque token identifying the pending request (600 s TTL). */\n requestToken: string;\n /** Consent page URL — redirect the user here. */\n authorizationUri: string;\n expiresIn?: number;\n}\n\nexport interface AAuthIssuerMetadata {\n issuer: string;\n aauth_version: string;\n jwks_uri: string;\n agent_token_endpoint: string;\n agent_auth_endpoint: string;\n agent_signing_algs_supported: string[];\n token_signing_algs_supported: string[];\n request_types_supported: string[];\n scopes_supported: string[];\n [key: string]: unknown;\n}\n\nexport interface AAuthAgentMetadata {\n agent: string;\n jwks_uri: string;\n redirect_uris?: string[];\n name?: string;\n [key: string]: unknown;\n}\n\nexport interface AAuthResourceMetadata {\n resource: string;\n jwks_uri: string;\n resource_token_endpoint?: string;\n supported_scopes?: string[];\n [key: string]: unknown;\n}\n\ninterface RawTokenResponse {\n request_type?: string;\n auth_token?: string;\n expires_in?: number;\n token_type?: string;\n refresh_token?: string;\n request_token?: string;\n authorization_uri?: string;\n auth_url?: string;\n error?: string;\n error_description?: string;\n}\n\nfunction envVar(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * Client for the AAuth (Agent Auth) protocol — the Node.js counterpart of\n * the Python SDK's `lumoauth.AAuthClient`.\n *\n * AAuth extends OAuth 2.1 with cryptographic agent identity,\n * proof-of-possession tokens, and RFC 9421 HTTP message signing.\n *\n * @example\n * ```ts\n * import { AAuthClient } from '@lumoauth/agent';\n *\n * const client = new AAuthClient({\n * agentIdentifier: 'https://my-agent.example.com',\n * privateKeyPem: process.env.AGENT_PRIVATE_KEY!,\n * baseUrl: 'https://app.lumoauth.dev',\n * orgId: 'acme-corp',\n * });\n *\n * const result = await client.requestAuthToken({\n * resourceToken,\n * scope: 'read write',\n * agentToken,\n * });\n * if ('authorizationRequired' in result) {\n * // redirect the user to result.authorizationUri, then exchangeCode()\n * } else {\n * const resp = await client.signedRequest('GET', 'https://api.example.com/v1/data', {\n * authToken: result.authToken,\n * });\n * }\n * ```\n */\nexport class AAuthClient {\n /** Generate an Ed25519 key pair suitable for AAuth (parity with Python). */\n static generateKeypair = generateKeypair;\n\n readonly agentIdentifier: string;\n readonly baseUrl: string;\n readonly orgId: string;\n readonly kid: string;\n\n private readonly privateKeyPem: string;\n private readonly fetchFn: typeof globalThis.fetch;\n private readonly timeout: number;\n\n constructor(options: AAuthClientOptions) {\n if (!options.agentIdentifier) {\n throw new LumoAuthConfigError('agentIdentifier is required');\n }\n if (!options.privateKeyPem) {\n throw new LumoAuthConfigError('privateKeyPem is required');\n }\n this.agentIdentifier = options.agentIdentifier;\n this.privateKeyPem = options.privateKeyPem;\n this.baseUrl = (options.baseUrl ?? envVar('LUMOAUTH_URL') ?? 'https://app.lumoauth.dev').replace(/\\/+$/, '');\n this.orgId = options.orgId ?? envVar('LUMOAUTH_ORG_ID') ?? '';\n this.kid = options.kid ?? 'key-1';\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.timeout = options.timeout ?? 30_000;\n }\n\n /** The organization's AAuth issuer URL: `{baseUrl}/orgs/{orgId}/api/v1`. */\n get issuer(): string {\n return `${this.baseUrl}/orgs/${this.orgId}/api/v1`;\n }\n\n /** The agent's public JWK derived from its private key. */\n get publicJwk(): AAuthJwk {\n return publicJwkFromPrivateKey(this.privateKeyPem, this.kid);\n }\n\n /** RFC 7638 thumbprint of the agent's public key (the `jkt` binding value). */\n get publicJwkThumbprint(): string {\n return jwkThumbprint(this.publicJwk);\n }\n\n // ─── HTTP Message Signing ─────────────────────────────────────────\n\n /**\n * Create RFC 9421 signature headers for a request per the AAuth profile.\n * See `signRequest()` in `signing.ts` for the exact contract.\n */\n signRequest(method: string, url: string, options: SignRequestOptions = {}): Record<string, string> {\n return signRequest(this.privateKeyPem, method, url, options);\n }\n\n // ─── Token flows ──────────────────────────────────────────────────\n\n /**\n * Request an auth token (`request_type=auth` — direct authorization).\n *\n * Presents the resource token in the body and the agent token in the\n * `Agent-Auth` header, signed with the agent's key. If the server\n * requires user consent it returns `{ authorizationRequired: true,\n * requestToken, authorizationUri }` — redirect the user, then call\n * `exchangeCode()` with the code delivered to your `redirectUri`.\n */\n async requestAuthToken(params: {\n /** Resource token (`resource+jwt`) obtained from the target resource. */\n resourceToken: string;\n /** Space-separated scopes (informational; scopes bind via the resource token). */\n scope?: string;\n /** The `agent+jwt` presented in `Agent-Auth`. */\n agentToken: string;\n /** Redirect URI for user-consent flows (must be registered). */\n redirectUri?: string;\n }): Promise<AAuthTokenResponse | AAuthAuthorizationRequired> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'auth',\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n if (params.redirectUri) body.redirect_uri = params.redirectUri;\n\n const data = await this.tokenRequest(body, params.agentToken);\n\n if (!data.auth_token && (data.request_token || data.authorization_uri || data.auth_url)) {\n return {\n authorizationRequired: true,\n requestToken: data.request_token ?? '',\n authorizationUri: data.authorization_uri ?? data.auth_url ?? '',\n expiresIn: data.expires_in,\n };\n }\n return this.mapTokenResponse(data);\n }\n\n /**\n * Build the user-consent URL for a pending request token\n * (`GET {issuer}/aauth/agent/auth?request_token=…`). Prefer the\n * `authorizationUri` returned by `requestAuthToken()` when present.\n */\n buildConsentUrl(requestToken: string): string {\n return `${this.routeUrl('aauth.agentAuth')}?request_token=${encodeURIComponent(requestToken)}`;\n }\n\n /**\n * Exchange an authorization code for tokens (`request_type=code`) after\n * user consent. `redirectUri` must be the exact URI the code was\n * delivered to.\n */\n async exchangeCode(params: {\n code: string;\n redirectUri: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n { request_type: 'code', code: params.code, redirect_uri: params.redirectUri },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Multi-hop token exchange (`request_type=exchange`): trade an upstream\n * auth token plus a downstream resource token for a new auth token with\n * an `act` actor chain. Requires token exchange to be enabled for the\n * agent.\n */\n async exchangeToken(params: {\n /** The upstream `auth+jwt` addressed to this agent. */\n authToken: string;\n /** Resource token issued by the downstream resource to this agent. */\n resourceToken: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const data = await this.tokenRequest(\n {\n request_type: 'exchange',\n auth_token: params.authToken,\n resource_token: params.resourceToken,\n },\n params.agentToken\n );\n return this.mapTokenResponse(data);\n }\n\n /**\n * Refresh an auth token (`request_type=refresh`). A fresh resource token\n * for the target resource is required; scopes requested via the resource\n * token must be a subset of the original grant. Refresh tokens are not\n * rotated.\n */\n async refresh(params: {\n refreshToken: string;\n /** Fresh resource token for the target resource. */\n resourceToken: string;\n /** Optional scope narrowing. */\n scope?: string;\n agentToken: string;\n }): Promise<AAuthTokenResponse> {\n this.requireAgentToken(params.agentToken);\n const body: Record<string, unknown> = {\n request_type: 'refresh',\n refresh_token: params.refreshToken,\n resource_token: params.resourceToken,\n };\n if (params.scope) body.scope = params.scope;\n const data = await this.tokenRequest(body, params.agentToken);\n return this.mapTokenResponse(data);\n }\n\n /**\n * Revoke an auth token (by its `jti`) or a refresh token (by value).\n * Always resolves `{ revoked: true }` — the server does not reveal\n * whether the token existed.\n */\n async revoke(params: {\n /** A refresh-token value, or an auth token's `jti`. */\n token: string;\n tokenType?: 'auth_token' | 'refresh_token';\n agentToken: string;\n }): Promise<{ revoked: boolean }> {\n this.requireAgentToken(params.agentToken);\n const url = this.routeUrl('aauth.tokenRevoke');\n const data = await this.signedPost(url, {\n token: params.token,\n token_type: params.tokenType ?? 'auth_token',\n }, params.agentToken);\n return { revoked: Boolean((data as { revoked?: boolean }).revoked ?? true) };\n }\n\n // ─── Signed requests to protected resources ───────────────────────\n\n /**\n * Make a signed, authenticated request to a protected resource.\n *\n * Carries the auth token as `Authorization: Bearer …` **and** an RFC\n * 9421 signature proving possession of the key bound in the token's\n * `cnf.jwk`. The signature covers the `authorization` component, so the\n * resource can verify both together.\n *\n * Returns the raw `fetch` Response.\n */\n async signedRequest(\n method: string,\n url: string,\n options: {\n /** The AAuth `auth+jwt` access token. */\n authToken: string;\n /** JSON body (for POST/PUT). */\n data?: unknown;\n /** Extra headers (not covered by the signature). */\n headers?: Record<string, string>;\n }\n ): Promise<Response> {\n const bodyStr = options.data != null ? JSON.stringify(options.data) : '';\n const authorization = `Bearer ${options.authToken}`;\n const sigHeaders = this.signRequest(method, url, { body: bodyStr, authorization });\n\n return this.doFetch(url, {\n method: method.toUpperCase(),\n headers: { Authorization: authorization, ...sigHeaders, ...(options.headers ?? {}) },\n body: bodyStr !== '' ? bodyStr : undefined,\n });\n }\n\n // ─── Verification (resource-server side) ──────────────────────────\n\n /**\n * Verify an `auth+jwt` against this organization's issuer JWKS.\n * See `verifyAuthToken()` for details (PoP still required!).\n */\n async verifyAuthToken(\n token: string,\n options: Omit<VerifyAuthTokenOptions, 'issuer' | 'fetch'> & { issuer?: string }\n ): Promise<AAuthTokenClaims> {\n return verifyAuthToken(token, {\n issuer: options.issuer ?? this.issuer,\n fetch: this.fetchFn,\n ...options,\n });\n }\n\n // ─── Discovery ────────────────────────────────────────────────────\n\n /** Fetch `{issuer}/.well-known/aauth-issuer`. */\n async discoverIssuer(): Promise<AAuthIssuerMetadata> {\n return this.getJson<AAuthIssuerMetadata>(this.routeUrl('aauth.issuerMetadata'));\n }\n\n /** Fetch `{issuer}/.well-known/aauth-agent` — metadata for all active agents. */\n async discoverAgents(): Promise<AAuthAgentMetadata[]> {\n return this.getJson<AAuthAgentMetadata[]>(this.routeUrl('aauth.agentMetadata'));\n }\n\n /** Fetch `{resourceUrl}/.well-known/aauth-resource` from a resource server. */\n async discoverResource(resourceUrl: string): Promise<AAuthResourceMetadata | AAuthResourceMetadata[]> {\n const base = resourceUrl.replace(/\\/+$/, '');\n return this.getJson<AAuthResourceMetadata | AAuthResourceMetadata[]>(`${base}/.well-known/aauth-resource`);\n }\n\n // ─── Internals ────────────────────────────────────────────────────\n\n private requireAgentToken(agentToken: string): void {\n if (!agentToken) {\n throw new AAuthError(\n 'agentToken is required — the /agent/token endpoint authenticates the agent via the Agent-Auth header.',\n 'invalid_request'\n );\n }\n }\n\n private tokenUrl(): string {\n return this.routeUrl('aauth.agentToken');\n }\n\n /** Absolute URL for an org-scoped route from the shared registry. */\n private routeUrl(name: keyof typeof ROUTES): string {\n return `${this.baseUrl}${buildPath(ROUTES[name].path, { orgId: this.orgId })}`;\n }\n\n private async tokenRequest(body: Record<string, unknown>, agentToken: string): Promise<RawTokenResponse> {\n return (await this.signedPost(this.tokenUrl(), body, agentToken)) as RawTokenResponse;\n }\n\n private async signedPost(url: string, body: Record<string, unknown>, agentToken: string): Promise<unknown> {\n if (!this.orgId) {\n throw new LumoAuthConfigError('orgId is required for AAuth token operations');\n }\n const bodyStr = JSON.stringify(body);\n const headers = this.signRequest('POST', url, { body: bodyStr, agentToken });\n\n const response = await this.doFetch(url, { method: 'POST', headers, body: bodyStr });\n const text = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n\n if (!response.ok) {\n const err = (parsed ?? {}) as { error?: string; error_description?: string };\n throw new AAuthError(\n err.error_description ?? err.error ?? `AAuth request failed: HTTP ${response.status}`,\n err.error ?? 'aauth_error',\n response.status,\n parsed ?? text\n );\n }\n return parsed ?? {};\n }\n\n private mapTokenResponse(data: RawTokenResponse): AAuthTokenResponse {\n if (!data.auth_token) {\n throw new AAuthError('Token response missing auth_token', 'invalid_response', undefined, data);\n }\n const result: AAuthTokenResponse = {\n requestType: (data.request_type ?? 'auth') as AAuthTokenResponse['requestType'],\n authToken: data.auth_token,\n expiresIn: data.expires_in ?? 0,\n tokenType: data.token_type ?? 'auth+jwt',\n };\n if (data.refresh_token) result.refreshToken = data.refresh_token;\n return result;\n }\n\n private async getJson<T>(url: string): Promise<T> {\n const response = await this.doFetch(url, { headers: { Accept: 'application/json' } });\n if (!response.ok) {\n throw new AAuthError(`Discovery request failed: HTTP ${response.status}`, 'discovery_failed', response.status);\n }\n return (await response.json()) as T;\n }\n\n private async doFetch(url: string, init: RequestInit): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n try {\n return await this.fetchFn(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n throw new LumoAuthNetworkError(`Request to ${url} timed out after ${this.timeout}ms`, error);\n }\n throw new LumoAuthNetworkError(\n `Network request to ${url} failed: ${error instanceof Error ? error.message : String(error)}`,\n error\n );\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n\nexport type { AAuthKeypair };\n","// ─── @lumoauth/agent — the agent SDK ─────────────────────────────────\n//\n// Two layers:\n// - `LumoAgent` — high-level client (client-credentials auth, ask/\n// isAllowed, jit/delegation/approvals/mcp namespaces). Python parity\n// with `lumoauth.LumoAuthAgent`.\n// - `AAuthClient` + signing/verify primitives — the AAuth protocol\n// (cryptographic agent identity, RFC 9421 HTTP message signing).\n// Uses `node:crypto`, therefore Node-only (>= 18).\n\nexport { LumoAgent, type LumoAgentOptions } from './agent';\n\nexport {\n AAuthClient,\n type AAuthClientOptions,\n type AAuthTokenResponse,\n type AAuthAuthorizationRequired,\n type AAuthIssuerMetadata,\n type AAuthAgentMetadata,\n type AAuthResourceMetadata,\n} from './client';\n\nexport {\n generateKeypair,\n jwkThumbprint,\n publicJwkFromPrivateKey,\n type AAuthJwk,\n type AAuthKeypair,\n} from './keys';\n\nexport {\n signRequest,\n buildSignatureBase,\n signatureParams,\n signSignatureBase,\n verifySignatureBase,\n contentDigestSha256,\n generateNonce,\n AAUTH_COVERED_COMPONENTS,\n type SignRequestOptions,\n} from './signing';\n\nexport {\n verifyAuthToken,\n decodeJwt,\n type AAuthTokenClaims,\n type VerifyAuthTokenOptions,\n} from './verify';\n\nexport { AAuthError } from './errors';\n\n// The shared error taxonomy, so agent code can catch these without a direct\n// dependency on @lumoauth/shared.\nexport {\n LumoAuthError,\n LumoAuthApiError,\n LumoAuthAuthenticationError,\n LumoAuthPermissionDeniedError,\n LumoAuthNotFoundError,\n LumoAuthRateLimitError,\n LumoAuthValidationError,\n LumoAuthConfigError,\n LumoAuthNetworkError,\n LumoAuthApprovalDeniedError,\n LumoAuthApprovalTimeoutError,\n LumoAuthApprovalNotDeliveredError,\n LumoAuthBudgetExceededError,\n type ApprovalNotDeliveredReason,\n type ApprovalResult,\n type ApprovalRequestResult,\n type CreateApprovalRequest,\n type RequireApprovalRequest,\n} from '@lumoauth/shared';\n"],"mappings":";AAAA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIG;AAiCP,SAAS,OAAO,MAAkC;AAC9C,SAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,IAAI,IAAI,IAAI;AAC/E;AAGA,IAAM,0BAA0B;AAmCzB,IAAM,YAAN,MAAgB;AAAA,EAsBnB,YAAY,UAA4B,CAAC,GAAG;AAH5C,SAAQ,QAA2B;AACnC,SAAQ,iBAAyC;AAG7C,SAAK,WAAW,QAAQ,WAAW,OAAO,cAAc,KAAK,4BAA4B,QAAQ,QAAQ,EAAE;AAC3G,SAAK,QAAQ,QAAQ,SAAS,OAAO,iBAAiB,KAAK;AAC3D,SAAK,WAAW,QAAQ,YAAY,OAAO,iBAAiB,KAAK;AACjE,SAAK,eAAe,QAAQ,gBAAgB,OAAO,qBAAqB,KAAK;AAC7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A;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAAC;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMG;","names":["createHash","createHash","constants","createPublicKey","cryptoVerify","cryptoVerify","constants","createPublicKey","LumoAuthConfigError","LumoAuthNetworkError","ROUTES","buildPath","envVar","LumoAuthError","LumoAuthApiError","LumoAuthConfigError","LumoAuthNetworkError"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lumoauth/agent",
3
- "version": "1.0.0",
4
- "description": "LumoAuth AAuth client \u2014 agent identity, HTTP message signing (RFC 9421), and agent-to-agent delegation. Node 18+ only.",
3
+ "version": "1.1.0",
4
+ "description": "LumoAuth AAuth client — agent identity, HTTP message signing (RFC 9421), and agent-to-agent delegation. Node 18+ only.",
5
5
  "license": "MIT",
6
6
  "author": "LumoAuth",
7
7
  "publishConfig": {