@agledger/mcp-server 3.0.0 → 3.2.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/CHANGELOG.md +130 -170
- package/README.md +24 -21
- package/dist/api-client.d.ts +18 -0
- package/dist/api-client.js +80 -20
- package/dist/credentials.d.ts +52 -1
- package/dist/credentials.js +184 -10
- package/dist/delegation.js +2 -1
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +18 -0
- package/dist/index.js +66 -17
- package/dist/server.d.ts +35 -1
- package/dist/server.js +310 -136
- package/dist/zod-integrity.d.ts +7 -7
- package/dist/zod-integrity.js +11 -9
- package/package.json +12 -10
package/README.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
The official [MCP](https://modelcontextprotocol.io) server for the [AGLedger](https://agledger.ai) API: change control for AI agents. Agent memory, approvals, audit trail, and notifications: one API, one signed ledger, self-hosted.
|
|
4
4
|
|
|
5
|
+
Requires an AGLedger Server 2.0 or later. For a 1.x Server, use `@agledger/mcp-server@2.11.0`, the last release that supports it.
|
|
6
|
+
|
|
5
7
|
Connects any MCP-compatible AI agent (Claude, Cursor, Windsurf, etc.) to the AGLedger API with 2 universal API-pass-through tools plus an offline audit verifier. No SDK code required. Just point your agent at this server.
|
|
6
8
|
|
|
7
9
|
**Learn more**
|
|
@@ -26,17 +28,17 @@ Add to your MCP client configuration (e.g. `claude_desktop_config.json`):
|
|
|
26
28
|
"mcpServers": {
|
|
27
29
|
"agledger": {
|
|
28
30
|
"command": "agledger-mcp",
|
|
29
|
-
"args": [
|
|
30
|
-
|
|
31
|
-
"--api-url", "https://your-agledger-instance"
|
|
32
|
-
]
|
|
31
|
+
"args": ["--api-url", "https://your-agledger-instance"],
|
|
32
|
+
"env": { "AGLEDGER_API_KEY": "your-api-key" }
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
The API URL and the API key are both required, unless an OIDC token source
|
|
39
|
+
stands in for the key (see
|
|
40
|
+
[below](#authenticating-with-oidc-instead-of-an-api-key)). The key can also be
|
|
41
|
+
passed as `--api-key`, but the `env` form keeps it out of the process list. AGLedger is
|
|
40
42
|
self-hosted, so there is no default server to call: without `--api-url`, or
|
|
41
43
|
with one that is not an absolute `http` or `https` URL, the server exits before
|
|
42
44
|
it accepts a connection.
|
|
@@ -66,6 +68,7 @@ Nothing is written to disk.
|
|
|
66
68
|
|---------|-------------|
|
|
67
69
|
| `AGLEDGER_OIDC_TOKEN_FILE` | A file holding an OIDC JWT, such as a Kubernetes projected service-account token. Read on every exchange, so a token rotated on disk is picked up. |
|
|
68
70
|
| `AGLEDGER_OIDC_TOKEN_CMD` | A shell command whose stdout is an OIDC JWT. Run on every exchange. |
|
|
71
|
+
| `AGLEDGER_AGENT_KEYS_FILE` | Optional. A JWK Set file the server's cert public key is added to on each exchange, before the cert is used. The key re-verifies the agent signatures the server seals, offline: pass the file as `agentKeys` to `agledger_verify` or `--agent-keys` to a verifier. One key per server process; `agledger_discover` also shows it as `agentKey`. Server processes and agledger CLI commands can share one file: each takes `<file>.lock` while it adds its key. Public keys only. |
|
|
69
72
|
| `AGLEDGER_OIDC_AGENT_ID` | Optional. An assertion of the agent id the token binds to, sent on the exchange. It never chooses the agent: when it names a different one, or the token binds none, the Server refuses the exchange with 403 `CERT_AGENT_BINDING_MISMATCH` rather than issue a cert for an agent you did not expect. Leave it unset unless you want that check. |
|
|
70
73
|
|
|
71
74
|
An API key wins when one is set, then the command, then the file.
|
|
@@ -162,12 +165,12 @@ to compare, and it is recorded `unbound`.
|
|
|
162
165
|
| Tool | Description |
|
|
163
166
|
|------|-------------|
|
|
164
167
|
| `agledger_discover` | Returns API health, your identity, available scopes, and a quickstart workflow. Call this first. |
|
|
165
|
-
| `agledger_api` | Make any AGLedger API call (method, path, params). Every POST carries a generated `Idempotency-Key`; pass `idempotencyKey` to reuse the first attempt's key when retrying a call that may already have landed.
|
|
166
|
-
| `agledger_verify` | Verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network calls. Returns the verifier's result as one JSON text block (the same object as `structuredContent`), with `summary` stating the verdict and the next step. Pass `trustAnchors` (`["sha256:<digest>"]`, the SPKI digest of a vault key the operator took out of band; the installer prints the first one) so the export's signed key statements are walked from a key you trust: an entry under a key the walk does not reach fails `CHAIN_SIGNING_KEY_UNANCHORED`, and a statement that does not hold fails `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`. The result carries `verdict`: `trusted` (text `Verdict: PASS`) only when the chain is valid and the walk reached a signature, `failed` (`Verdict: FAIL`), or `unanchored` (`Verdict: VERIFIED, NOT ANCHORED`), which is not a trusted verdict. A run is unanchored without `trustAnchors` (`keyTrust.status` `no_anchor`, the keys taken on the export's word) and when the pin was walked but no signature verified under a key it anchors (`no_anchored_signature`, as for an export of unsigned entries). `distrustedKeys` takes the operator's `VAULT_DISTRUSTED_KEYS` entries and needs `trustAnchors`, and a key both pinned and distrusted is refused (`INVALID_ARGUMENT`), as the Server refuses to start with it; a key statement a distrusted key signed counts for nothing at any instant, because the write times an export carries are not signed. Where an export lists a key retired at the instant the Server distrusts it from (`distrustedFrom`), earlier than its signed retirement, a pinned call without the same `distrustedKeys` entry fails on that key's window (`CHAIN_KEY_WINDOW_DRIFT`, or `KEY_CLOSURE_INVALID` where no closure retires it), and the finding names the entry (`distrustedKeys sha256:<hex>@<distrustedFrom>`), the listing's unsigned word, to confirm with the operator before passing it. `publicKeys` supplies keys (the `GET /v1/verification-keys` response works as is), `requireSuppliedKeys` refuses the export's embedded keys,
|
|
168
|
+
| `agledger_api` | Make any AGLedger API call (method, path, params). Every POST carries a generated `Idempotency-Key`; pass `idempotencyKey` to reuse the first attempt's key when retrying a call that may already have landed. Most responses carry `nextSteps` for self-guided workflow discovery; listing pages, `GET /v1/schemas` and `GET /v1/admin/orgs` carry none. It reaches the request fields and filters of AGLedger Server 3.0.0 as they are: `producedBy` on a record or completion, `traceId`, `originRecordId`, `producedBy[key]` and the numeric `criteriaGt/Gte/Lt/Lte` and `metadataGt/Gte/Lt/Lte` bounds on search (nested objects in `params`, sent as `criteriaGte[amount]=500`), `GET /v1/records/counts` with `groupBy`, `signatureMeaning` on a verdict (taken only on an ephemeral OIDC cert; the Server refuses it with 422 on an API key), and `format=html` on an audit export, which comes back as the page text exactly as the Server sent it. |
|
|
169
|
+
| `agledger_verify` | Verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network calls. Returns the verifier's result as one JSON text block (the same object as `structuredContent`), with `summary` stating the verdict and the next step. Pass `trustAnchors` (`["sha256:<digest>"]`, the SPKI digest of a vault key the operator took out of band; the installer prints the first one) so the export's signed key statements are walked from a key you trust: an entry under a key the walk does not reach fails `CHAIN_SIGNING_KEY_UNANCHORED`, and a statement that does not hold fails `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`. The result carries `verdict`: `trusted` (text `Verdict: PASS`) only when the chain is valid and the walk reached a signature, `failed` (`Verdict: FAIL`), or `unanchored` (`Verdict: VERIFIED, NOT ANCHORED`), which is not a trusted verdict. A run is unanchored without `trustAnchors` (`keyTrust.status` `no_anchor`, the keys taken on the export's word) and when the pin was walked but no signature verified under a key it anchors (`no_anchored_signature`, as for an export of unsigned entries). A pinned run whose `trustAnchors` reach none of the export's keys, on an export that verifies without them, is `unanchored` with `valid: false` (`Verdict: NOT ANCHORED`): that is another Server's pin, or an export re-signed under keys of its own. `isError` is set only for `failed`. `distrustedKeys` takes the operator's `VAULT_DISTRUSTED_KEYS` entries and needs `trustAnchors`, and a key both pinned and distrusted is refused (`INVALID_ARGUMENT`), as the Server refuses to start with it; a key statement a distrusted key signed counts for nothing at any instant, because the write times an export carries are not signed. Where an export lists a key retired at the instant the Server distrusts it from (`distrustedFrom`), earlier than its signed retirement, a pinned call without the same `distrustedKeys` entry fails on that key's window (`CHAIN_KEY_WINDOW_DRIFT`, or `KEY_CLOSURE_INVALID` where no closure retires it), and the finding names the entry (`distrustedKeys sha256:<hex>@<distrustedFrom>`), the listing's unsigned word, to confirm with the operator before passing it. `publicKeys` supplies keys (the `GET /v1/verification-keys` response works as is), `requireSuppliedKeys` refuses the export's embedded keys, `agentKeys` (the agents' cert public keys: an array of JWKs, one JWK, or the `{"keys":[...]}` set `AGLEDGER_AGENT_KEYS_FILE` collects) re-verifies the agent signatures sealed in the chain, and `federationKeys` (`{"<hubId>": "<key>"}`, each peer Server's federation key as its operator gives it) re-verifies the peer messages a receiving Server sealed on its `FEDERATION_*` entries, which fail `CHAIN_FEDERATION_WIRE_INVALID` when they do not hold. After a peer changes its federation key, give an array entry `history`, the JSON the peer serves at `GET /.well-known/agledger-federation-keys.json`, so the entries sealed under its earlier keys verify too. Federation key histories need a Server 2.2 or later on the peer. A peer message signed more than 300 seconds after its key's retirement fails unless `allowAfterRetirement` is true. `expectedEntryCount` holds the export to an entry count taken out of band, since the counts it states are unsigned: a different number of entries fails `CHAIN_POSITION_GAP`. Input verify-core refuses, such as a supplied key window that is not RFC 3339, is `INVALID_ARGUMENT`. Built on the shared `@agledger/verify-core`. |
|
|
167
170
|
|
|
168
171
|
## Resources
|
|
169
172
|
|
|
170
|
-
Both are fetched live from the running instance
|
|
173
|
+
Both are fetched live from the running instance on every read.
|
|
171
174
|
|
|
172
175
|
| Resource | Description |
|
|
173
176
|
|------|-------------|
|
|
@@ -178,20 +181,20 @@ Both are fetched live from the running instance, so neither can go stale.
|
|
|
178
181
|
|
|
179
182
|
The `agledger_discover` tool returns a quickstart workflow that guides agents through the accountability flow:
|
|
180
183
|
|
|
181
|
-
1. `GET /v1/schemas
|
|
182
|
-
2. `GET /v1/schemas/{type}
|
|
183
|
-
3. `POST /v1/records
|
|
184
|
-
4. `POST /v1/records/{id}/completions
|
|
184
|
+
1. `GET /v1/schemas`: list available Record types
|
|
185
|
+
2. `GET /v1/schemas/{type}`: get required fields and examples
|
|
186
|
+
3. `POST /v1/records`: create a record
|
|
187
|
+
4. `POST /v1/records/{id}/completions`: submit a completion (evidence) when done
|
|
185
188
|
|
|
186
|
-
|
|
189
|
+
An error from the Server is passed through as sent, with its `recoveryHint` naming the fix where it gives one, so an agent can correct itself without a human. The result adds `httpStatus`, and `retryAfter` (seconds) when the Server sent a `Retry-After` header. Errors raised by the MCP server itself (an argument the tool does not declare, a timeout, a credential failure) carry a `code` and a `suggestion` instead.
|
|
187
190
|
|
|
188
191
|
## Configuration
|
|
189
192
|
|
|
190
193
|
| Flag | Env Var | Description |
|
|
191
194
|
|------|---------|-------------|
|
|
192
195
|
| `--api-key` | `AGLEDGER_API_KEY` | AGLedger API key. Required unless an OIDC token source is set (see above). |
|
|
193
|
-
| `--api-url` | `AGLEDGER_API_URL` | API base URL of your instance (required). AGLedger is self-hosted, so there is no default; the server refuses to start without it. |
|
|
194
|
-
| `--timeout` | `AGLEDGER_TIMEOUT` | Seconds to wait for each API response (default 30). A
|
|
196
|
+
| `--api-url` | `AGLEDGER_API_URL` | API base URL of your instance (required), which may carry a path prefix such as a gateway mount point. AGLedger is self-hosted, so there is no default; the server refuses to start without it. |
|
|
197
|
+
| `--timeout` | `AGLEDGER_TIMEOUT` | Seconds to wait for each API response (default 30). A number from 0.001 to 2147483; anything else exits 2. |
|
|
195
198
|
|
|
196
199
|
A call that times out may still have been applied. On a POST, the `TIMEOUT` error carries the `idempotencyKey` that was sent: retry with exactly that key and the Server returns the original result instead of creating a second record. Reads and other methods carry no key.
|
|
197
200
|
|
|
@@ -199,14 +202,14 @@ A call that times out may still have been applied. On a POST, the `TIMEOUT` erro
|
|
|
199
202
|
|
|
200
203
|
AGLedger is change control for AI agents, delivered as a signed ledger for agentic work. Agents notarize what they intended and what they did, principals approve the work that needs a decision, and every entry is signed, hash-chained and verifiable offline.
|
|
201
204
|
|
|
202
|
-
- **Records
|
|
203
|
-
- **Completions
|
|
204
|
-
- **Verdicts
|
|
205
|
-
- **Audit chain
|
|
205
|
+
- **Records**: structured commitments with acceptance criteria and tolerance bands
|
|
206
|
+
- **Completions**: performer evidence recording what was reported to be done
|
|
207
|
+
- **Verdicts**: principal accept/reject decisions on a Completion (the Gate), with settlement signals
|
|
208
|
+
- **Audit chain**: notarized records as COSE_Sign1 envelopes, hash-chained, signed (Ed25519, or ES256 when the operator chooses it), tamper-evident, verifiable offline
|
|
206
209
|
|
|
207
210
|
Learn more at [agledger.ai](https://www.agledger.ai) | [API docs](https://www.agledger.ai/docs/)
|
|
208
211
|
|
|
209
|
-
Each self-hosted AGLedger instance
|
|
212
|
+
Each self-hosted AGLedger instance serves its OpenAPI document at `{AGLEDGER_API_URL}/openapi.json`, and an interactive API UI at `{AGLEDGER_API_URL}/docs` when the operator enables it.
|
|
210
213
|
|
|
211
214
|
## Requirements
|
|
212
215
|
|
package/dist/api-client.d.ts
CHANGED
|
@@ -4,6 +4,13 @@ export interface ApiResponse {
|
|
|
4
4
|
status: number;
|
|
5
5
|
body: unknown;
|
|
6
6
|
ok: boolean;
|
|
7
|
+
/** The Retry-After header as whole seconds from now, when the Server sent one. */
|
|
8
|
+
retryAfterSeconds?: number;
|
|
9
|
+
}
|
|
10
|
+
/** A query value the bracket form cannot carry: an object or array nested below its one level. */
|
|
11
|
+
export declare class QueryShapeError extends Error {
|
|
12
|
+
readonly param: string;
|
|
13
|
+
constructor(param: string);
|
|
7
14
|
}
|
|
8
15
|
export interface RequestOptions {
|
|
9
16
|
query?: Record<string, unknown>;
|
|
@@ -26,6 +33,17 @@ export declare class ApiClient {
|
|
|
26
33
|
/** Where the delegation token comes from, or undefined when none is configured. Never the token. */
|
|
27
34
|
get delegationOrigin(): string | undefined;
|
|
28
35
|
request(method: string, path: string, options?: RequestOptions): Promise<ApiResponse>;
|
|
36
|
+
/**
|
|
37
|
+
* The request URL: the base URL (with any path prefix, such as a gateway
|
|
38
|
+
* mount point) followed by `path`. `new URL(path, base)` would replace that
|
|
39
|
+
* prefix.
|
|
40
|
+
*
|
|
41
|
+
* Defense-in-depth: every request is pinned to the configured API origin. A
|
|
42
|
+
* protocol-relative or absolute `path` (e.g. `//evil.com/x`,
|
|
43
|
+
* `https://evil.com`) would send the `Authorization: Bearer` header off-host,
|
|
44
|
+
* and no caller may steer the client there.
|
|
45
|
+
*/
|
|
46
|
+
private urlFor;
|
|
29
47
|
/** The delegation token never comes back to a tool, even if the Server echoes it. */
|
|
30
48
|
private scrubbed;
|
|
31
49
|
private postAnonymous;
|
package/dist/api-client.js
CHANGED
|
@@ -2,6 +2,16 @@ import { ApiKeyCredential, cutSecret } from './credentials.js';
|
|
|
2
2
|
import { namesDelegation, ON_BEHALF_OF_HEADER } from './delegation.js';
|
|
3
3
|
import { SERVER_VERSION } from './version.js';
|
|
4
4
|
const USER_AGENT = `agledger-mcp-server/${SERVER_VERSION}`;
|
|
5
|
+
/** Retry-After as seconds from now: delay-seconds, or an HTTP date. Undefined when absent or unreadable. */
|
|
6
|
+
function retryAfterSeconds(header) {
|
|
7
|
+
if (header === null)
|
|
8
|
+
return undefined;
|
|
9
|
+
const value = header.trim();
|
|
10
|
+
if (/^\d+$/.test(value))
|
|
11
|
+
return Number(value);
|
|
12
|
+
const at = Date.parse(value);
|
|
13
|
+
return Number.isNaN(at) ? undefined : Math.max(0, Math.ceil((at - Date.now()) / 1000));
|
|
14
|
+
}
|
|
5
15
|
// Strip trailing slashes with a single linear scan. A regex like /\/+$/ is
|
|
6
16
|
// O(n^2) on inputs of many slashes (CodeQL js/polynomial-redos); this is O(n).
|
|
7
17
|
function stripTrailingSlashes(s) {
|
|
@@ -10,6 +20,29 @@ function stripTrailingSlashes(s) {
|
|
|
10
20
|
end--;
|
|
11
21
|
return s.slice(0, end);
|
|
12
22
|
}
|
|
23
|
+
/** A query value the bracket form cannot carry: an object or array nested below its one level. */
|
|
24
|
+
export class QueryShapeError extends Error {
|
|
25
|
+
param;
|
|
26
|
+
constructor(param) {
|
|
27
|
+
super(`Query parameter ${param} is a nested object or array, which has no query-string form: the bracket form goes one level deep (criteriaGte[amount]=500).`);
|
|
28
|
+
this.param = param;
|
|
29
|
+
this.name = 'QueryShapeError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A query value as text. A value below the bracket form's one level is
|
|
34
|
+
* refused rather than sent as `[object Object]`, which the Server would read
|
|
35
|
+
* as a filter on that literal string.
|
|
36
|
+
*/
|
|
37
|
+
function queryScalar(name, value) {
|
|
38
|
+
if (value instanceof Date)
|
|
39
|
+
return value.toISOString();
|
|
40
|
+
if (typeof value === 'string')
|
|
41
|
+
return value;
|
|
42
|
+
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint')
|
|
43
|
+
return String(value);
|
|
44
|
+
throw new QueryShapeError(name);
|
|
45
|
+
}
|
|
13
46
|
/**
|
|
14
47
|
* Serialize one query parameter.
|
|
15
48
|
*
|
|
@@ -30,7 +63,7 @@ function appendQueryParam(search, key, value) {
|
|
|
30
63
|
for (const item of value) {
|
|
31
64
|
if (item === undefined || item === null)
|
|
32
65
|
continue;
|
|
33
|
-
search.append(key,
|
|
66
|
+
search.append(key, queryScalar(key, item));
|
|
34
67
|
}
|
|
35
68
|
return;
|
|
36
69
|
}
|
|
@@ -38,11 +71,11 @@ function appendQueryParam(search, key, value) {
|
|
|
38
71
|
for (const [sub, subValue] of Object.entries(value)) {
|
|
39
72
|
if (subValue === undefined || subValue === null)
|
|
40
73
|
continue;
|
|
41
|
-
search.set(`${key}[${sub}]`,
|
|
74
|
+
search.set(`${key}[${sub}]`, queryScalar(`${key}[${sub}]`, subValue));
|
|
42
75
|
}
|
|
43
76
|
return;
|
|
44
77
|
}
|
|
45
|
-
search.set(key,
|
|
78
|
+
search.set(key, queryScalar(key, value));
|
|
46
79
|
}
|
|
47
80
|
export class ApiClient {
|
|
48
81
|
apiUrl;
|
|
@@ -65,15 +98,7 @@ export class ApiClient {
|
|
|
65
98
|
return this.delegation?.origin;
|
|
66
99
|
}
|
|
67
100
|
async request(method, path, options) {
|
|
68
|
-
const url =
|
|
69
|
-
// Defense-in-depth: pin every request to the configured API origin. A
|
|
70
|
-
// protocol-relative or absolute `path` (e.g. `//evil.com/x`,
|
|
71
|
-
// `https://evil.com`) resolves against the base to a different origin, which
|
|
72
|
-
// would leak the `Authorization: Bearer` header off-host. No caller
|
|
73
|
-
// may steer the client off-origin.
|
|
74
|
-
if (url.origin !== new URL(this.apiUrl).origin) {
|
|
75
|
-
throw new Error(`Refusing to send request off-origin: path "${path}" resolves to ${url.origin}, expected ${new URL(this.apiUrl).origin}.`);
|
|
76
|
-
}
|
|
101
|
+
const url = this.urlFor(path);
|
|
77
102
|
if (options?.query) {
|
|
78
103
|
for (const [k, v] of Object.entries(options.query)) {
|
|
79
104
|
if (v !== undefined && v !== null) {
|
|
@@ -112,7 +137,8 @@ export class ApiClient {
|
|
|
112
137
|
Object.assign(headers, this.credential.signBody(body));
|
|
113
138
|
}
|
|
114
139
|
// Every route that declares AGLedger-On-Behalf-Of is a POST.
|
|
115
|
-
|
|
140
|
+
const delegation = this.delegation;
|
|
141
|
+
let onBehalfOf = delegation && method.toUpperCase() === 'POST' ? await delegation.token() : undefined;
|
|
116
142
|
const withDelegation = (h) => onBehalfOf ? { ...h, [ON_BEHALF_OF_HEADER]: onBehalfOf } : h;
|
|
117
143
|
const ctx = { postAnonymous: (p, b) => this.postAnonymous(p, b) };
|
|
118
144
|
let bearer = await this.credential.bearer(ctx);
|
|
@@ -123,9 +149,9 @@ export class ApiClient {
|
|
|
123
149
|
// delegation token is re-read only when the Server names it; otherwise a
|
|
124
150
|
// cert can be revoked or expire server-side before our clock says so, and
|
|
125
151
|
// gets exactly one re-exchange. A second 401 is the answer.
|
|
126
|
-
if (onBehalfOf && namesDelegation(first.body)) {
|
|
152
|
+
if (delegation && onBehalfOf && namesDelegation(first.body)) {
|
|
127
153
|
const refused = onBehalfOf;
|
|
128
|
-
onBehalfOf = await
|
|
154
|
+
onBehalfOf = await delegation.token(refused);
|
|
129
155
|
if (onBehalfOf === refused)
|
|
130
156
|
return this.scrubbed(first, refused);
|
|
131
157
|
}
|
|
@@ -138,12 +164,33 @@ export class ApiClient {
|
|
|
138
164
|
const second = await this.send(url, method, withDelegation({ ...headers, Authorization: `Bearer ${bearer}` }), body);
|
|
139
165
|
return this.scrubbed(second, onBehalfOf);
|
|
140
166
|
}
|
|
167
|
+
/**
|
|
168
|
+
* The request URL: the base URL (with any path prefix, such as a gateway
|
|
169
|
+
* mount point) followed by `path`. `new URL(path, base)` would replace that
|
|
170
|
+
* prefix.
|
|
171
|
+
*
|
|
172
|
+
* Defense-in-depth: every request is pinned to the configured API origin. A
|
|
173
|
+
* protocol-relative or absolute `path` (e.g. `//evil.com/x`,
|
|
174
|
+
* `https://evil.com`) would send the `Authorization: Bearer` header off-host,
|
|
175
|
+
* and no caller may steer the client there.
|
|
176
|
+
*/
|
|
177
|
+
urlFor(path) {
|
|
178
|
+
const origin = new URL(this.apiUrl).origin;
|
|
179
|
+
if (!path.startsWith('/') || path.startsWith('//')) {
|
|
180
|
+
throw new Error(`Refusing to send request off-origin: path "${path}" is not an absolute path on ${origin}.`);
|
|
181
|
+
}
|
|
182
|
+
const url = new URL(this.apiUrl + path);
|
|
183
|
+
if (url.origin !== origin) {
|
|
184
|
+
throw new Error(`Refusing to send request off-origin: path "${path}" resolves to ${url.origin}, expected ${origin}.`);
|
|
185
|
+
}
|
|
186
|
+
return url;
|
|
187
|
+
}
|
|
141
188
|
/** The delegation token never comes back to a tool, even if the Server echoes it. */
|
|
142
189
|
scrubbed(res, onBehalfOf) {
|
|
143
190
|
return onBehalfOf ? { ...res, body: cutSecret(res.body, onBehalfOf) } : res;
|
|
144
191
|
}
|
|
145
192
|
async postAnonymous(path, payload) {
|
|
146
|
-
const res = await this.send(
|
|
193
|
+
const res = await this.send(this.urlFor(path), 'POST', { Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': USER_AGENT }, JSON.stringify(payload));
|
|
147
194
|
return { status: res.status, body: res.body };
|
|
148
195
|
}
|
|
149
196
|
async send(url, method, headers, body) {
|
|
@@ -157,15 +204,28 @@ export class ApiClient {
|
|
|
157
204
|
signal: controller.signal,
|
|
158
205
|
});
|
|
159
206
|
const contentType = res.headers.get('content-type') ?? '';
|
|
207
|
+
// Text first: `res.json()` throws on an empty body, which turned a
|
|
208
|
+
// successful 204 write into an error the caller could retry. An empty body
|
|
209
|
+
// is `{}`, and a body that does not parse under a JSON content type is
|
|
210
|
+
// handed back as the text it was.
|
|
211
|
+
const text = await res.text();
|
|
160
212
|
let parsed;
|
|
161
|
-
if (
|
|
162
|
-
parsed =
|
|
213
|
+
if (text === '') {
|
|
214
|
+
parsed = {};
|
|
215
|
+
}
|
|
216
|
+
else if (contentType.includes('json')) {
|
|
217
|
+
try {
|
|
218
|
+
parsed = JSON.parse(text);
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
parsed = { _raw: text, _contentType: contentType };
|
|
222
|
+
}
|
|
163
223
|
}
|
|
164
224
|
else {
|
|
165
|
-
const text = await res.text();
|
|
166
225
|
parsed = { _raw: text, _contentType: contentType };
|
|
167
226
|
}
|
|
168
|
-
|
|
227
|
+
const retryAfter = retryAfterSeconds(res.headers.get('retry-after'));
|
|
228
|
+
return { status: res.status, body: parsed, ok: res.ok, ...(retryAfter !== undefined ? { retryAfterSeconds: retryAfter } : {}) };
|
|
169
229
|
}
|
|
170
230
|
finally {
|
|
171
231
|
clearTimeout(timeout);
|
package/dist/credentials.d.ts
CHANGED
|
@@ -16,11 +16,13 @@
|
|
|
16
16
|
* output. Server error bodies and token-command stderr are scrubbed before
|
|
17
17
|
* they are surfaced, because either can echo a token back.
|
|
18
18
|
*/
|
|
19
|
-
/** The env vars the server reads a token source from.
|
|
19
|
+
/** The env vars the server reads a token source from. */
|
|
20
20
|
export declare const OIDC_ENV: {
|
|
21
21
|
readonly TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD';
|
|
22
22
|
readonly TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE';
|
|
23
23
|
readonly AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID';
|
|
24
|
+
/** A JWK Set file each cert exchange adds the server's public key to, for agledger_verify's agentKeys. */
|
|
25
|
+
readonly AGENT_KEYS_FILE: 'AGLEDGER_AGENT_KEYS_FILE';
|
|
24
26
|
};
|
|
25
27
|
/** Replace anything shaped like a JWT with a placeholder. */
|
|
26
28
|
export declare function redactTokens(text: string): string;
|
|
@@ -43,6 +45,36 @@ export declare class OidcTokenSourceError extends Error {
|
|
|
43
45
|
/** @param unrotated the source returned the token it returned last time, which is expected for a file between rotations */
|
|
44
46
|
constructor(message: string, unrotated?: boolean);
|
|
45
47
|
}
|
|
48
|
+
/** The agent keys file could not be read or written; nothing was signed under the new cert. */
|
|
49
|
+
export declare class AgentKeysFileError extends Error {
|
|
50
|
+
readonly path: string;
|
|
51
|
+
readonly code = "AGENT_KEYS_FILE_FAILED";
|
|
52
|
+
constructor(message: string, path: string);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Add one exchanged cert's public key to the JWK Set at `path`, creating it if
|
|
56
|
+
* needed: `{ keys: [{ publicKeyJwk, certId, agentId, issuedAt, expiresAt }] }`,
|
|
57
|
+
* the shape every AGLedger verifier's agent keys input reads. A key already
|
|
58
|
+
* listed is not added twice. Written through a temp file and a rename; a file
|
|
59
|
+
* that does not hold a `keys` list is refused, never overwritten. The read and
|
|
60
|
+
* the write happen under `<path>.lock`, the same lock the agledger CLI takes,
|
|
61
|
+
* so processes sharing one file each add their key. The same format and rules
|
|
62
|
+
* as the CLI's `--agent-keys-file`.
|
|
63
|
+
*/
|
|
64
|
+
export declare function recordAgentKey(path: string, entry: {
|
|
65
|
+
publicKeyJwk: {
|
|
66
|
+
kty: 'OKP';
|
|
67
|
+
crv: 'Ed25519';
|
|
68
|
+
x: string;
|
|
69
|
+
};
|
|
70
|
+
} & Record<string, unknown>): Promise<void>;
|
|
71
|
+
/** Bounds on the agent keys file lock. Mutable so tests can shorten them. */
|
|
72
|
+
export declare const KEYS_FILE_LOCK: {
|
|
73
|
+
/** How long to wait for another process to release the lock. */
|
|
74
|
+
waitMs: number;
|
|
75
|
+
/** A lock older than this was left by a process that died holding it. */
|
|
76
|
+
staleMs: number;
|
|
77
|
+
};
|
|
46
78
|
/** The Server refused the exchange. `body` is its error response, scrubbed. */
|
|
47
79
|
export declare class OidcExchangeError extends Error {
|
|
48
80
|
readonly status: number;
|
|
@@ -62,6 +94,8 @@ export interface TokenCommandOptions {
|
|
|
62
94
|
/** Refuse more stdout than this. Default 64 KiB; a JWT is a few KiB at most. */
|
|
63
95
|
maxStdoutBytes?: number;
|
|
64
96
|
}
|
|
97
|
+
/** Kill every token command still running. For a signal handler: the commands run detached, so they would outlive this process. */
|
|
98
|
+
export declare function killRunningTokenCommands(): void;
|
|
65
99
|
/**
|
|
66
100
|
* Runs a shell command on every call; its stdout is the token. The command
|
|
67
101
|
* runs in its own process group, which is killed on timeout, on oversized
|
|
@@ -111,6 +145,12 @@ export interface OidcCertCredentialOptions {
|
|
|
111
145
|
* CERT_AGENT_BINDING_MISMATCH rather than bind a different one.
|
|
112
146
|
*/
|
|
113
147
|
agentId?: string;
|
|
148
|
+
/**
|
|
149
|
+
* A JWK Set file the cert's public key is added to on each exchange, before
|
|
150
|
+
* the cert is used (see {@link recordAgentKey}), so the agent signatures
|
|
151
|
+
* this server seals can be re-verified offline.
|
|
152
|
+
*/
|
|
153
|
+
agentKeysFile?: string;
|
|
114
154
|
/** Re-exchange once this fraction of the cert's lifetime has passed. Default 0.5. */
|
|
115
155
|
refreshFraction?: number;
|
|
116
156
|
/** Names the token source in errors, e.g. `AGLEDGER_OIDC_TOKEN_FILE`. */
|
|
@@ -124,6 +164,7 @@ export declare class OidcCertCredential implements Credential {
|
|
|
124
164
|
readonly renewable = true;
|
|
125
165
|
private readonly getOidcToken;
|
|
126
166
|
private readonly agentId;
|
|
167
|
+
private readonly agentKeysFile;
|
|
127
168
|
private readonly refreshFraction;
|
|
128
169
|
private readonly origin;
|
|
129
170
|
private readonly onWarning;
|
|
@@ -136,6 +177,16 @@ export declare class OidcCertCredential implements Credential {
|
|
|
136
177
|
/** The last token the Server accepted. A token carrying a `jti` is exchangeable once. */
|
|
137
178
|
private lastExchangedToken;
|
|
138
179
|
constructor(options: OidcCertCredentialOptions);
|
|
180
|
+
/**
|
|
181
|
+
* The public half of this server's key pair, as sent at every exchange. The
|
|
182
|
+
* cert carries only its thumbprint; this is the key agledger_verify's
|
|
183
|
+
* agentKeys needs to re-verify what this server signed. One per process.
|
|
184
|
+
*/
|
|
185
|
+
get publicKeyJwk(): {
|
|
186
|
+
kty: 'OKP';
|
|
187
|
+
crv: 'Ed25519';
|
|
188
|
+
x: string;
|
|
189
|
+
};
|
|
139
190
|
bearer(ctx: CredentialContext): Promise<string>;
|
|
140
191
|
signBody(body: string): Record<string, string>;
|
|
141
192
|
/** Single-flight: concurrent callers share one exchange. */
|