@verax-ai/body 0.8.2 → 0.10.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 +9 -6
- package/dist/anchor-cli.d.ts +48 -3
- package/dist/anchor-cli.js +256 -17
- package/dist/auth.d.ts +14 -1
- package/dist/auth.js +25 -4
- package/dist/canary-cli.d.ts +5 -0
- package/dist/canary-cli.js +213 -0
- package/dist/cli.js +93 -6
- package/dist/config.d.ts +6 -0
- package/dist/config.js +1 -0
- package/dist/demo.js +3 -0
- package/dist/doctor.d.ts +11 -0
- package/dist/doctor.js +88 -2
- package/dist/downstream-pin.js +11 -1
- package/dist/downstream.d.ts +51 -0
- package/dist/downstream.js +329 -4
- package/dist/explain-cli.d.ts +5 -0
- package/dist/explain-cli.js +132 -0
- package/dist/init-local.d.ts +5 -0
- package/dist/init-local.js +1 -0
- package/dist/install.js +1 -1
- package/dist/policy-cli.d.ts +8 -0
- package/dist/policy-cli.js +169 -0
- package/dist/policy-rehearsal.d.ts +39 -0
- package/dist/policy-rehearsal.js +512 -0
- package/dist/report-cli.d.ts +163 -0
- package/dist/report-cli.js +1101 -0
- package/dist/server.js +43 -6
- package/dist/taint-cli.d.ts +5 -0
- package/dist/taint-cli.js +80 -0
- package/dist/verify-cli.d.ts +40 -0
- package/dist/verify-cli.js +131 -58
- package/dist/webauthn-verify.d.ts +3 -1
- package/dist/webauthn-verify.js +97 -4
- package/dist/wiring.d.ts +5 -0
- package/dist/wiring.js +2 -0
- package/dist/witness.d.ts +16 -5
- package/dist/witness.js +67 -8
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -31,27 +31,30 @@ Bearer token the configured issuer did not sign.
|
|
|
31
31
|
| `VERAX_ISSUER` | yes | Issuer the agent's token must carry. |
|
|
32
32
|
| `VERAX_JWKS_URL` | one of | Where the body fetches the keys that verify that token. Set this or `VERAX_JWKS_FILE`, not both. |
|
|
33
33
|
| `VERAX_JWKS_FILE` | one of | Path to a JWKS JSON file read once at start, instead of fetching `VERAX_JWKS_URL`. Accepted only with a loopback bind. |
|
|
34
|
-
| `
|
|
34
|
+
| `VERAX_INSTALLED` | no | `1` when `verax install` wrote `verax.env`. A body without a JWKS file refuses the HTTP credential check; a body with a JWKS file refuses when this is `1`. Absent, a JWKS file is local mode and that check only warns. |
|
|
35
|
+
| `VERAX_AUDIENCE` | yes | Audience the token must name, so a token minted for something else is refused. Use the MCP URL, for example `https://verax.example/mcp`: a 401 then names the resource metadata a client reads to find the issuer. Any other string works for tokens, but the 401 carries a plain `Bearer` challenge and `verax doctor` warns. |
|
|
35
36
|
| `VERAX_STATE_DIR` | yes | Directory the ledger, keys and approvals live in. It stays on this machine. |
|
|
36
37
|
| `VERAX_POLICY_FILE` | yes | Policy the gate applies. `@verax-ai/proxy` ships `policy/default.json`, which denies what it does not name. |
|
|
37
38
|
| `VERAX_BIND` | no | `host:port` to listen on. Default `127.0.0.1:8787`; anything but loopback needs `VERAX_TLS_TERMINATED=1`. |
|
|
38
39
|
| `VERAX_INVENTORY_FILE` | no | Roster document the body serves. The format is `@verax-ai/inventory`. |
|
|
39
|
-
| `VERAX_DOWNSTREAM` | no | Path to a JSON document naming MCP servers to put behind this gate: one `{ prefix, command?, args?, cwd?, env?, url?, headers?, timeoutMs?, trust? }` or an array of them. Each child names exactly one way in — `command` to spawn it over stdio, or `url` to reach one already running over Streamable HTTP, with `headers`
|
|
40
|
+
| `VERAX_DOWNSTREAM` | no | Path to a JSON document naming MCP servers to put behind this gate: one `{ prefix, command?, args?, cwd?, env?, url?, headers?, timeoutMs?, trust?, unauthenticated? }` or an array of them. Each child names exactly one way in — `command` to spawn it over stdio, or `url` to reach one already running over Streamable HTTP. An HTTP child must require a credential that only the Verax service holds, set in `headers`. A body without a JWKS file, and a body with a JWKS file when `VERAX_INSTALLED=1` (`verax install` writes it into `verax.env`), refuses a child that has no such header, one that answers an initialize without those headers (`downstream-http-credential-required`), or one the probe cannot decide (`downstream-http-credential-undecided`). Only 401 and 403 count as the child refusing that initialize. `"unauthenticated": "acknowledged"` attaches it anyway. The probe sends the protocol version the real connection sends, reads the stream as it arrives, and counts only the message whose `id` is its request. A JSON-RPC `result` counts, `"error": null` included, and so does a 2xx that times out after the headers, passes 1 MiB, or does not parse. A JSON-RPC `error`, any other status, a connection error, or a timeout before the headers is undecided. The acknowledgement is part of the child's pin. `verax doctor --env-file <file>` loads that file the way `verax serve --env-file` does, fails when the probe sees a result or cannot decide, and warns for the acknowledgement. Doctor does not open `verax.env` unless the flag names it. `verax init --local` does not write `VERAX_INSTALLED` and only warns, including one line on stderr at attach. Verax can check that the downstream refuses an unauthenticated call; it cannot check where else the downstream's own credential is stored. A stdio child requires `"trust": "same-user"` (it runs as the same user as the body and can read the signing keys); an HTTP child does not ask for that field and must not carry it. This is a breaking change: existing stdio documents do not open until the field is added. A path and not the JSON itself, because the document may name a key in `env` or `headers`. Their tools are served as `prefix.childName` and need an exact policy rule under that name; a named child that cannot be opened stops the body. |
|
|
40
41
|
|
|
41
|
-
The agent's token is a JWT signed with ES256 or
|
|
42
|
+
The agent's token is a JWT signed with ES256, EdDSA or RS256 by a key in that JWKS. An RSA key must be at least 2048 bits; HS256 and other shared-secret algorithms are refused.
|
|
42
43
|
It must carry `iss` (`VERAX_ISSUER`), `aud` (`VERAX_AUDIENCE`), `sub`, `iat`,
|
|
43
44
|
`exp` and `jti`; `scope` is a space-separated list the policy reads. A token
|
|
44
45
|
without `jti` is refused with 401, because a revocation names a token by its
|
|
45
46
|
`jti`. Check that your issuer sets it on the tokens it gives agents.
|
|
46
47
|
|
|
47
|
-
`verax doctor` names what is missing.
|
|
48
|
-
|
|
48
|
+
`verax doctor` names what is missing. `verax doctor --env-file verax.env` reads
|
|
49
|
+
the file an install wrote; without that flag a `VERAX_DOWNSTREAM` that lives
|
|
50
|
+
only there is not checked. A misconfigured body exits with code 78 before it
|
|
51
|
+
listens.
|
|
49
52
|
|
|
50
53
|
## Run
|
|
51
54
|
|
|
52
55
|
```sh
|
|
53
56
|
verax # serve MCP at http://127.0.0.1:8787/mcp
|
|
54
|
-
verax doctor
|
|
57
|
+
verax doctor --env-file verax.env # same check, after loading that file
|
|
55
58
|
```
|
|
56
59
|
|
|
57
60
|
Point an MCP client at `http://127.0.0.1:8787/mcp` with a Bearer token from
|
package/dist/anchor-cli.d.ts
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import { type AnchorRow } from "@verax-ai/proxy";
|
|
2
2
|
export declare const EX_ANCHOR_FAILED = 1;
|
|
3
|
+
/**
|
|
4
|
+
* Reads a bearer token from a file. Trimmed content must be 20 to 512 printable
|
|
5
|
+
* ASCII characters. The token is never written to stdout or state files here.
|
|
6
|
+
*/
|
|
7
|
+
export declare function readAnchorTokenFile(path: string): {
|
|
8
|
+
ok: true;
|
|
9
|
+
token: string;
|
|
10
|
+
} | {
|
|
11
|
+
ok: false;
|
|
12
|
+
reason: string;
|
|
13
|
+
};
|
|
3
14
|
/** https only; http is accepted for a loopback address. No credentials, query or fragment. */
|
|
4
15
|
export declare function serviceUrl(raw: string): URL | null;
|
|
5
16
|
/** The name a service's rows are kept under: origin and path, no trailing slash. */
|
|
@@ -10,18 +21,52 @@ export type Registered = {
|
|
|
10
21
|
checked: boolean;
|
|
11
22
|
} | {
|
|
12
23
|
ok: false;
|
|
13
|
-
reason: "unreachable" | "wrong-receipt" | "receipt-unverified";
|
|
24
|
+
reason: "unreachable" | "unauthorized" | "wrong-receipt" | "receipt-unverified";
|
|
14
25
|
message: string;
|
|
15
26
|
};
|
|
16
27
|
/**
|
|
17
28
|
* Registers one checkpoint hash at `serviceName` and returns the row to keep.
|
|
18
29
|
* Nothing is written here; the caller appends the row. With `serviceKey` the
|
|
19
30
|
* receipt must verify under it, at the tree size and leaf the service named.
|
|
31
|
+
* With `token` every request carries `Authorization: Bearer …`.
|
|
32
|
+
*/
|
|
33
|
+
export declare function registerCheckpoint(serviceName: string, hash: string, serviceKey: string | null, fetchImpl?: typeof fetch, now?: () => number, token?: string | null): Promise<Registered>;
|
|
34
|
+
/**
|
|
35
|
+
* "HTTP <status>", with the title or detail of the concise problem details
|
|
36
|
+
* (RFC 9290) the service sent, so the operator reads why it refused. The text
|
|
37
|
+
* is the service's: it is cut short and printable ASCII only.
|
|
20
38
|
*/
|
|
21
|
-
export declare function
|
|
39
|
+
export declare function httpFailure(res: Response): Promise<string>;
|
|
40
|
+
/** The entry id at the end of a Location the service sent; its host is not followed. */
|
|
41
|
+
export declare function entryIdFromLocation(location: string | null, serviceName: string): string | null;
|
|
42
|
+
/**
|
|
43
|
+
* Registers one checkpoint's Signed Statement at `serviceName` over SCRAPI and
|
|
44
|
+
* returns the row to keep. The receipt must commit to the SHA-256 of
|
|
45
|
+
* `statement`; with `serviceKey` it must also verify under that key.
|
|
46
|
+
*/
|
|
47
|
+
export declare function registerStatement(serviceName: string, hash: string, statement: Uint8Array, serviceKey: string | null, fetchImpl?: typeof fetch, now?: () => number, wait?: (ms: number) => Promise<void>, token?: string | null): Promise<Registered>;
|
|
22
48
|
/** Checkpoint hashes in this directory with no row at `serviceName`, in file order. */
|
|
23
49
|
export declare function pendingAnchors(dir: string, serviceName: string): {
|
|
24
50
|
pending: string[];
|
|
25
51
|
problems: string[];
|
|
26
52
|
};
|
|
27
|
-
export
|
|
53
|
+
export type StatementIssuer = {
|
|
54
|
+
chain: Uint8Array[];
|
|
55
|
+
keys: {
|
|
56
|
+
privateKeyPem: string;
|
|
57
|
+
publicKeyPem: string;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* The issuer chain read from `chainPem` with the witness keys in
|
|
62
|
+
* `<stateDir>/keys`, when the chain's leaf holds the witness public key. The
|
|
63
|
+
* keys are read, never created: a ledger with no witness has no checkpoint.
|
|
64
|
+
*/
|
|
65
|
+
export declare function statementIssuer(stateDir: string, chainPem: string): {
|
|
66
|
+
ok: true;
|
|
67
|
+
issuer: StatementIssuer;
|
|
68
|
+
} | {
|
|
69
|
+
ok: false;
|
|
70
|
+
reason: string;
|
|
71
|
+
};
|
|
72
|
+
export declare function runAnchor(argv: readonly string[], out?: (s: string) => void, fetchImpl?: typeof fetch, now?: () => number, wait?: (ms: number) => Promise<void>): Promise<number>;
|
package/dist/anchor-cli.js
CHANGED
|
@@ -12,23 +12,47 @@
|
|
|
12
12
|
* one that does not verify. Without it the receipt is kept and `verax verify
|
|
13
13
|
* --anchor-key` is where it is first checked.
|
|
14
14
|
*/
|
|
15
|
+
import { createHash, createPublicKey, X509Certificate } from "node:crypto";
|
|
15
16
|
import { readFileSync } from "node:fs";
|
|
16
|
-
import {
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
import { anchorEntryHash, appendAnchor, checkpointStatement, decodeCborItem, isEntryId, readAnchors, readCcfReceipt, readCheckpointFile, readIssuerChain, verifyCcfReceipt, verifyReceipt, } from "@verax-ai/proxy";
|
|
17
19
|
import { checkpointHash } from "@cedulon/checkpoint";
|
|
18
20
|
export const EX_ANCHOR_FAILED = 1;
|
|
19
21
|
const EX_USAGE = 64;
|
|
20
22
|
function usage() {
|
|
21
23
|
return [
|
|
22
|
-
"usage: verax anchor <stateDir> --service <url> [--service-key <public.pem>] [--json]",
|
|
24
|
+
"usage: verax anchor <stateDir> --service <url> [--x5chain <chain.pem>] [--service-key <public.pem>] [--token-file <file>] [--json]",
|
|
23
25
|
"",
|
|
24
26
|
" --service <url> the Transparency Service, for example https://witness.agentactioncapsule.org.",
|
|
25
27
|
" https only; http is accepted for a loopback address.",
|
|
28
|
+
" --x5chain <file> register over SCRAPI (POST /entries) as a Signed Statement the witness key signs;",
|
|
29
|
+
" the file is the PEM chain for that key, leaf first, then its CA certificates",
|
|
26
30
|
" --service-key <file> the service's public key; each receipt must verify under it before it is kept",
|
|
31
|
+
" --token-file <file> bearer token the service requires; the file holds 20 to 512 printable ASCII characters",
|
|
27
32
|
" --json one JSON object per anchored checkpoint",
|
|
28
33
|
"",
|
|
29
|
-
"Sends the SHA-256 of each checkpoint not yet anchored at that service, and nothing else
|
|
34
|
+
"Sends the SHA-256 of each checkpoint not yet anchored at that service, and nothing else;",
|
|
35
|
+
"with --x5chain that hash travels inside a Signed Statement that also carries the chain.",
|
|
30
36
|
].join("\n");
|
|
31
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Reads a bearer token from a file. Trimmed content must be 20 to 512 printable
|
|
40
|
+
* ASCII characters. The token is never written to stdout or state files here.
|
|
41
|
+
*/
|
|
42
|
+
export function readAnchorTokenFile(path) {
|
|
43
|
+
let raw;
|
|
44
|
+
try {
|
|
45
|
+
raw = readFileSync(path, "utf8");
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return { ok: false, reason: `cannot read token file ${path}` };
|
|
49
|
+
}
|
|
50
|
+
const token = raw.trim();
|
|
51
|
+
if (token.length < 20 || token.length > 512 || !/^[\x21-\x7e]+$/.test(token)) {
|
|
52
|
+
return { ok: false, reason: "token file must hold 20 to 512 printable ASCII characters" };
|
|
53
|
+
}
|
|
54
|
+
return { ok: true, token };
|
|
55
|
+
}
|
|
32
56
|
/** https only; http is accepted for a loopback address. No credentials, query or fragment. */
|
|
33
57
|
export function serviceUrl(raw) {
|
|
34
58
|
let url;
|
|
@@ -51,13 +75,13 @@ export function serviceUrl(raw) {
|
|
|
51
75
|
const MAX_ANSWER_BYTES = 256 * 1024;
|
|
52
76
|
const MAX_RECEIPT_BYTES = 64 * 1024;
|
|
53
77
|
const MAX_RECEIPT_B64 = Math.ceil(MAX_RECEIPT_BYTES / 3) * 4;
|
|
54
|
-
/** The body
|
|
55
|
-
async function
|
|
78
|
+
/** The body, refused once it passes `max` octets rather than held in full. */
|
|
79
|
+
async function boundedBytes(res, max = MAX_ANSWER_BYTES) {
|
|
56
80
|
const declared = Number(res.headers.get("content-length") ?? "0");
|
|
57
|
-
if (declared >
|
|
81
|
+
if (declared > max)
|
|
58
82
|
throw new Error("answer too large");
|
|
59
83
|
if (!res.body)
|
|
60
|
-
return
|
|
84
|
+
return Buffer.alloc(0);
|
|
61
85
|
const reader = res.body.getReader();
|
|
62
86
|
const chunks = [];
|
|
63
87
|
let size = 0;
|
|
@@ -66,34 +90,45 @@ async function boundedText(res) {
|
|
|
66
90
|
if (done)
|
|
67
91
|
break;
|
|
68
92
|
size += value.length;
|
|
69
|
-
if (size >
|
|
93
|
+
if (size > max) {
|
|
70
94
|
await reader.cancel();
|
|
71
95
|
throw new Error("answer too large");
|
|
72
96
|
}
|
|
73
97
|
chunks.push(value);
|
|
74
98
|
}
|
|
75
|
-
return Buffer.concat(chunks)
|
|
99
|
+
return Buffer.concat(chunks);
|
|
100
|
+
}
|
|
101
|
+
async function boundedText(res) {
|
|
102
|
+
return (await boundedBytes(res)).toString("utf8");
|
|
76
103
|
}
|
|
77
104
|
/** The name a service's rows are kept under: origin and path, no trailing slash. */
|
|
78
105
|
export function serviceNameOf(service) {
|
|
79
106
|
return service.origin + service.pathname.replace(/\/+$/, "");
|
|
80
107
|
}
|
|
108
|
+
function authHeaders(base, token) {
|
|
109
|
+
if (token === null)
|
|
110
|
+
return base;
|
|
111
|
+
return { ...base, authorization: `Bearer ${token}` };
|
|
112
|
+
}
|
|
81
113
|
/**
|
|
82
114
|
* Registers one checkpoint hash at `serviceName` and returns the row to keep.
|
|
83
115
|
* Nothing is written here; the caller appends the row. With `serviceKey` the
|
|
84
116
|
* receipt must verify under it, at the tree size and leaf the service named.
|
|
117
|
+
* With `token` every request carries `Authorization: Bearer …`.
|
|
85
118
|
*/
|
|
86
|
-
export async function registerCheckpoint(serviceName, hash, serviceKey, fetchImpl = fetch, now = Date.now) {
|
|
119
|
+
export async function registerCheckpoint(serviceName, hash, serviceKey, fetchImpl = fetch, now = Date.now, token = null) {
|
|
87
120
|
const entryHash = anchorEntryHash(hash, "register");
|
|
88
121
|
let answer;
|
|
89
122
|
try {
|
|
90
123
|
const res = await fetchImpl(`${serviceName}/register`, {
|
|
91
124
|
method: "POST",
|
|
92
|
-
headers: { "content-type": "application/json", accept: "application/json" },
|
|
125
|
+
headers: authHeaders({ "content-type": "application/json", accept: "application/json" }, token),
|
|
93
126
|
body: JSON.stringify({ capsule_id: hash }),
|
|
94
127
|
signal: AbortSignal.timeout(15_000),
|
|
95
128
|
redirect: "error",
|
|
96
129
|
});
|
|
130
|
+
if (res.status === 401)
|
|
131
|
+
return { ok: false, reason: "unauthorized", message: "HTTP 401" };
|
|
97
132
|
if (!res.ok)
|
|
98
133
|
throw new Error(`HTTP ${res.status}`);
|
|
99
134
|
answer = JSON.parse(await boundedText(res));
|
|
@@ -138,6 +173,135 @@ export async function registerCheckpoint(serviceName, hash, serviceKey, fetchImp
|
|
|
138
173
|
},
|
|
139
174
|
};
|
|
140
175
|
}
|
|
176
|
+
// SCRAPI (draft-ietf-scitt-scrapi) as scitt-ccf-ledger serves it when asked
|
|
177
|
+
// for this api-version: POST /entries answers 303 with the entry's location,
|
|
178
|
+
// GET /entries/{id} answers 302 while the entry is pending and 200 with the
|
|
179
|
+
// receipt once it is committed.
|
|
180
|
+
const SCRAPI_API_VERSION = "2026-03-26";
|
|
181
|
+
const POLL_INTERVAL_MS = 1_000;
|
|
182
|
+
const POLL_ATTEMPTS = 30;
|
|
183
|
+
/**
|
|
184
|
+
* "HTTP <status>", with the title or detail of the concise problem details
|
|
185
|
+
* (RFC 9290) the service sent, so the operator reads why it refused. The text
|
|
186
|
+
* is the service's: it is cut short and printable ASCII only.
|
|
187
|
+
*/
|
|
188
|
+
export async function httpFailure(res) {
|
|
189
|
+
let detail = "";
|
|
190
|
+
try {
|
|
191
|
+
if ((res.headers.get("content-type") ?? "").includes("concise-problem-details+cbor")) {
|
|
192
|
+
const body = decodeCborItem(await boundedBytes(res, 4096));
|
|
193
|
+
const text = body instanceof Map ? (body.get(-2) ?? body.get(-1)) : undefined;
|
|
194
|
+
if (typeof text === "string" && text !== "")
|
|
195
|
+
detail = `: ${text.slice(0, 200).replace(/[^\x20-\x7e]/g, "?")}`;
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
await res.body?.cancel();
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
// The status alone is still the answer.
|
|
203
|
+
}
|
|
204
|
+
return `HTTP ${res.status}${detail}`;
|
|
205
|
+
}
|
|
206
|
+
/** The entry id at the end of a Location the service sent; its host is not followed. */
|
|
207
|
+
export function entryIdFromLocation(location, serviceName) {
|
|
208
|
+
if (!location)
|
|
209
|
+
return null;
|
|
210
|
+
let url;
|
|
211
|
+
try {
|
|
212
|
+
url = new URL(location, `${serviceName}/`);
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
const match = /\/entries\/([^/]+)$/.exec(url.pathname);
|
|
218
|
+
if (!match)
|
|
219
|
+
return null;
|
|
220
|
+
let id;
|
|
221
|
+
try {
|
|
222
|
+
id = decodeURIComponent(match[1]);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
return isEntryId(id) ? id : null;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Registers one checkpoint's Signed Statement at `serviceName` over SCRAPI and
|
|
231
|
+
* returns the row to keep. The receipt must commit to the SHA-256 of
|
|
232
|
+
* `statement`; with `serviceKey` it must also verify under that key.
|
|
233
|
+
*/
|
|
234
|
+
export async function registerStatement(serviceName, hash, statement, serviceKey, fetchImpl = fetch, now = Date.now, wait = (ms) => new Promise((done) => setTimeout(done, ms)), token = null) {
|
|
235
|
+
const query = `api-version=${SCRAPI_API_VERSION}`;
|
|
236
|
+
let entryId;
|
|
237
|
+
let receipt = null;
|
|
238
|
+
try {
|
|
239
|
+
const res = await fetchImpl(`${serviceName}/entries?${query}`, {
|
|
240
|
+
method: "POST",
|
|
241
|
+
headers: authHeaders({ "content-type": "application/cose", accept: "application/scitt-receipt+cose" }, token),
|
|
242
|
+
body: new Uint8Array(statement),
|
|
243
|
+
signal: AbortSignal.timeout(15_000),
|
|
244
|
+
redirect: "manual",
|
|
245
|
+
});
|
|
246
|
+
if (res.status === 401)
|
|
247
|
+
return { ok: false, reason: "unauthorized", message: "HTTP 401" };
|
|
248
|
+
if (res.status !== 303 && res.status !== 201)
|
|
249
|
+
throw new Error(await httpFailure(res));
|
|
250
|
+
entryId = entryIdFromLocation(res.headers.get("location"), serviceName);
|
|
251
|
+
if (res.status === 201)
|
|
252
|
+
receipt = await boundedBytes(res, MAX_RECEIPT_BYTES);
|
|
253
|
+
else
|
|
254
|
+
await res.body?.cancel();
|
|
255
|
+
for (let attempt = 0; receipt === null && entryId !== null && attempt < POLL_ATTEMPTS; attempt += 1) {
|
|
256
|
+
const got = await fetchImpl(`${serviceName}/entries/${encodeURIComponent(entryId)}?${query}`, {
|
|
257
|
+
method: "GET",
|
|
258
|
+
headers: authHeaders({ accept: "application/scitt-receipt+cose" }, token),
|
|
259
|
+
signal: AbortSignal.timeout(15_000),
|
|
260
|
+
redirect: "manual",
|
|
261
|
+
});
|
|
262
|
+
if (got.status === 401)
|
|
263
|
+
return { ok: false, reason: "unauthorized", message: "HTTP 401" };
|
|
264
|
+
if (got.status === 200) {
|
|
265
|
+
receipt = await boundedBytes(got, MAX_RECEIPT_BYTES);
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
if (got.status !== 302 && got.status !== 202)
|
|
269
|
+
throw new Error(await httpFailure(got));
|
|
270
|
+
await got.body?.cancel();
|
|
271
|
+
await wait(POLL_INTERVAL_MS);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
catch (err) {
|
|
275
|
+
return { ok: false, reason: "unreachable", message: err instanceof Error ? err.message : String(err) };
|
|
276
|
+
}
|
|
277
|
+
if (entryId === null) {
|
|
278
|
+
return { ok: false, reason: "wrong-receipt", message: "the service named no entry for the statement" };
|
|
279
|
+
}
|
|
280
|
+
if (receipt === null) {
|
|
281
|
+
return { ok: false, reason: "unreachable", message: `entry ${entryId} was not committed in time` };
|
|
282
|
+
}
|
|
283
|
+
const digest = createHash("sha256").update(statement).digest();
|
|
284
|
+
if (!readCcfReceipt(receipt, digest).ok) {
|
|
285
|
+
return { ok: false, reason: "wrong-receipt", message: "the service answered with a receipt for another statement" };
|
|
286
|
+
}
|
|
287
|
+
if (serviceKey && !verifyCcfReceipt(receipt, digest, serviceKey).ok) {
|
|
288
|
+
return { ok: false, reason: "receipt-unverified", message: "receipt does not verify under the service key" };
|
|
289
|
+
}
|
|
290
|
+
return {
|
|
291
|
+
ok: true,
|
|
292
|
+
checked: serviceKey !== null,
|
|
293
|
+
row: {
|
|
294
|
+
v: 2,
|
|
295
|
+
checkpointHash: hash,
|
|
296
|
+
service: serviceName,
|
|
297
|
+
route: "entries",
|
|
298
|
+
entryId,
|
|
299
|
+
statementB64: Buffer.from(statement).toString("base64"),
|
|
300
|
+
receiptB64: receipt.toString("base64"),
|
|
301
|
+
atMs: now(),
|
|
302
|
+
},
|
|
303
|
+
};
|
|
304
|
+
}
|
|
141
305
|
/** Checkpoint hashes in this directory with no row at `serviceName`, in file order. */
|
|
142
306
|
export function pendingAnchors(dir, serviceName) {
|
|
143
307
|
const loaded = readCheckpointFile(dir);
|
|
@@ -149,7 +313,42 @@ export function pendingAnchors(dir, serviceName) {
|
|
|
149
313
|
const done = new Set(existing.rows.filter((r) => r.service === serviceName).map((r) => r.checkpointHash));
|
|
150
314
|
return { pending: loaded.rows.map((row) => checkpointHash(row)).filter((hash) => !done.has(hash)), problems: [] };
|
|
151
315
|
}
|
|
152
|
-
|
|
316
|
+
/**
|
|
317
|
+
* The issuer chain read from `chainPem` with the witness keys in
|
|
318
|
+
* `<stateDir>/keys`, when the chain's leaf holds the witness public key. The
|
|
319
|
+
* keys are read, never created: a ledger with no witness has no checkpoint.
|
|
320
|
+
*/
|
|
321
|
+
export function statementIssuer(stateDir, chainPem) {
|
|
322
|
+
let chain;
|
|
323
|
+
try {
|
|
324
|
+
chain = readIssuerChain(chainPem);
|
|
325
|
+
}
|
|
326
|
+
catch (err) {
|
|
327
|
+
const code = err instanceof Error ? err.message : String(err);
|
|
328
|
+
return {
|
|
329
|
+
ok: false,
|
|
330
|
+
reason: code === "issuer-chain-too-short"
|
|
331
|
+
? "the x5chain file must hold the witness certificate and at least one CA certificate, leaf first"
|
|
332
|
+
: "the x5chain file holds something that is not a certificate",
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
let keys;
|
|
336
|
+
try {
|
|
337
|
+
keys = {
|
|
338
|
+
privateKeyPem: readFileSync(join(stateDir, "keys", "witness.private.pem"), "utf8"),
|
|
339
|
+
publicKeyPem: readFileSync(join(stateDir, "keys", "witness.public.pem"), "utf8"),
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
return { ok: false, reason: `no witness key in ${join(stateDir, "keys")}` };
|
|
344
|
+
}
|
|
345
|
+
const leafKey = new X509Certificate(chain[0]).publicKey.export({ type: "spki", format: "der" });
|
|
346
|
+
if (!leafKey.equals(createPublicKey(keys.publicKeyPem).export({ type: "spki", format: "der" }))) {
|
|
347
|
+
return { ok: false, reason: "the x5chain leaf certificate does not hold this ledger's witness public key" };
|
|
348
|
+
}
|
|
349
|
+
return { ok: true, issuer: { chain, keys } };
|
|
350
|
+
}
|
|
351
|
+
export async function runAnchor(argv, out = (s) => process.stdout.write(`${s}\n`), fetchImpl = fetch, now = Date.now, wait) {
|
|
153
352
|
const args = [...argv];
|
|
154
353
|
if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
|
|
155
354
|
out(usage());
|
|
@@ -195,6 +394,25 @@ export async function runAnchor(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
195
394
|
return EX_USAGE;
|
|
196
395
|
}
|
|
197
396
|
}
|
|
397
|
+
const chainPath = take("--x5chain");
|
|
398
|
+
if (chainPath === null) {
|
|
399
|
+
out("anchor: --x5chain needs a file path");
|
|
400
|
+
return EX_USAGE;
|
|
401
|
+
}
|
|
402
|
+
const tokenPath = take("--token-file");
|
|
403
|
+
if (tokenPath === null) {
|
|
404
|
+
out("anchor: --token-file needs a file path");
|
|
405
|
+
return EX_USAGE;
|
|
406
|
+
}
|
|
407
|
+
let token = null;
|
|
408
|
+
if (tokenPath) {
|
|
409
|
+
const got = readAnchorTokenFile(tokenPath);
|
|
410
|
+
if (!got.ok) {
|
|
411
|
+
out(`anchor: ${got.reason}`);
|
|
412
|
+
return EX_USAGE;
|
|
413
|
+
}
|
|
414
|
+
token = got.token;
|
|
415
|
+
}
|
|
198
416
|
const dir = args.find((a) => !a.startsWith("-"));
|
|
199
417
|
if (!dir) {
|
|
200
418
|
out(usage());
|
|
@@ -211,24 +429,45 @@ export async function runAnchor(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
211
429
|
out(json ? JSON.stringify({ anchored: 0, service: serviceName }) : `nothing to anchor at ${serviceName}`);
|
|
212
430
|
return 0;
|
|
213
431
|
}
|
|
432
|
+
let issuer = null;
|
|
433
|
+
if (chainPath) {
|
|
434
|
+
let chainPem;
|
|
435
|
+
try {
|
|
436
|
+
chainPem = readFileSync(chainPath, "utf8");
|
|
437
|
+
}
|
|
438
|
+
catch {
|
|
439
|
+
out(`anchor: cannot read chain file ${chainPath}`);
|
|
440
|
+
return EX_USAGE;
|
|
441
|
+
}
|
|
442
|
+
const found = statementIssuer(dir, chainPem);
|
|
443
|
+
if (!found.ok) {
|
|
444
|
+
out(`anchor: ${found.reason}`);
|
|
445
|
+
return EX_USAGE;
|
|
446
|
+
}
|
|
447
|
+
issuer = found.issuer;
|
|
448
|
+
}
|
|
214
449
|
let failed = 0;
|
|
215
450
|
for (const hash of pending) {
|
|
216
|
-
const got =
|
|
451
|
+
const got = issuer
|
|
452
|
+
? await registerStatement(serviceName, hash, checkpointStatement(hash, issuer.chain, issuer.keys), serviceKey, fetchImpl, now, wait, token)
|
|
453
|
+
: await registerCheckpoint(serviceName, hash, serviceKey, fetchImpl, now, token);
|
|
217
454
|
if (!got.ok) {
|
|
218
455
|
failed += 1;
|
|
219
456
|
const short = hash.slice(0, 12);
|
|
220
457
|
out(got.reason === "unreachable"
|
|
221
458
|
? `anchor: ${short} not registered: ${got.message}`
|
|
222
|
-
: got.reason === "
|
|
223
|
-
? `anchor: ${short}
|
|
224
|
-
:
|
|
459
|
+
: got.reason === "unauthorized"
|
|
460
|
+
? `anchor: ${short} not registered: unauthorized`
|
|
461
|
+
: got.reason === "wrong-receipt"
|
|
462
|
+
? `anchor: ${short} ${got.message}`
|
|
463
|
+
: `anchor: ${short} receipt does not verify under --service-key; not kept`);
|
|
225
464
|
continue;
|
|
226
465
|
}
|
|
227
466
|
const row = got.row;
|
|
228
467
|
appendAnchor(dir, row);
|
|
229
468
|
out(json
|
|
230
469
|
? JSON.stringify(row)
|
|
231
|
-
: `anchored ${hash.slice(0, 12)} at ${serviceName}: leaf ${row.leafIndex} of ${row.treeSize}${got.checked ? ", receipt verified" : ", receipt not yet checked"}`);
|
|
470
|
+
: `anchored ${hash.slice(0, 12)} at ${serviceName}: ${row.v === 1 ? `leaf ${row.leafIndex} of ${row.treeSize}` : `entry ${row.entryId}`}${got.checked ? ", receipt verified" : ", receipt not yet checked"}`);
|
|
232
471
|
}
|
|
233
472
|
return failed === 0 ? 0 : EX_ANCHOR_FAILED;
|
|
234
473
|
}
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,10 +1,23 @@
|
|
|
1
1
|
import { type JWTPayload } from "jose";
|
|
2
2
|
import type { Principal } from "@verax-ai/proxy";
|
|
3
|
+
/**
|
|
4
|
+
* Accepted signature algorithms for agent tokens. RS256 is the default of most
|
|
5
|
+
* hosted identity providers; jose refuses an RSA key under 2048 bits when it
|
|
6
|
+
* verifies, and checks that the key type matches the algorithm. HS* and `none`
|
|
7
|
+
* are not in the list, so a token signed with a shared secret is refused.
|
|
8
|
+
*/
|
|
9
|
+
export declare const AGENT_TOKEN_ALGS: readonly ["ES256", "EdDSA", "RS256"];
|
|
3
10
|
export type VerifiedBearer = {
|
|
4
11
|
principal: Principal;
|
|
5
12
|
payload: JWTPayload;
|
|
6
13
|
};
|
|
7
|
-
|
|
14
|
+
/**
|
|
15
|
+
* The protected-resource metadata URL for this audience (RFC 9728), or null
|
|
16
|
+
* when the audience is not an http(s) URL. A token audience may be any
|
|
17
|
+
* string, but only a URL names a resource whose metadata a client can fetch.
|
|
18
|
+
*/
|
|
19
|
+
export declare function resourceMetadataUrl(audience: string): string | null;
|
|
20
|
+
/** A 401's challenge. Without a URL audience there is no metadata to point at. */
|
|
8
21
|
export declare function wwwAuthenticate(audience: string): string;
|
|
9
22
|
export declare class JwksFileError extends Error {
|
|
10
23
|
readonly code = 78;
|
package/dist/auth.js
CHANGED
|
@@ -1,16 +1,37 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { createLocalJWKSet, createRemoteJWKSet, jwtVerify } from "jose";
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Accepted signature algorithms for agent tokens. RS256 is the default of most
|
|
5
|
+
* hosted identity providers; jose refuses an RSA key under 2048 bits when it
|
|
6
|
+
* verifies, and checks that the key type matches the algorithm. HS* and `none`
|
|
7
|
+
* are not in the list, so a token signed with a shared secret is refused.
|
|
8
|
+
*/
|
|
9
|
+
export const AGENT_TOKEN_ALGS = ["ES256", "EdDSA", "RS256"];
|
|
10
|
+
/**
|
|
11
|
+
* The protected-resource metadata URL for this audience (RFC 9728), or null
|
|
12
|
+
* when the audience is not an http(s) URL. A token audience may be any
|
|
13
|
+
* string, but only a URL names a resource whose metadata a client can fetch.
|
|
14
|
+
*/
|
|
4
15
|
export function resourceMetadataUrl(audience) {
|
|
5
|
-
|
|
16
|
+
let u;
|
|
17
|
+
try {
|
|
18
|
+
u = new URL(audience);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
if (u.protocol !== "https:" && u.protocol !== "http:")
|
|
24
|
+
return null;
|
|
6
25
|
const path = u.pathname.replace(/\/+$/, "").replace(/^\/+/, "");
|
|
7
26
|
if (path === "") {
|
|
8
27
|
return `${u.origin}/.well-known/oauth-protected-resource`;
|
|
9
28
|
}
|
|
10
29
|
return `${u.origin}/.well-known/oauth-protected-resource/${path}`;
|
|
11
30
|
}
|
|
31
|
+
/** A 401's challenge. Without a URL audience there is no metadata to point at. */
|
|
12
32
|
export function wwwAuthenticate(audience) {
|
|
13
|
-
|
|
33
|
+
const metadata = resourceMetadataUrl(audience);
|
|
34
|
+
return metadata === null ? "Bearer" : `Bearer resource_metadata="${metadata}"`;
|
|
14
35
|
}
|
|
15
36
|
function localJwks(path) {
|
|
16
37
|
let parsed;
|
|
@@ -51,7 +72,7 @@ jwksPin) {
|
|
|
51
72
|
const { payload } = await jwtVerify(token, jwks, {
|
|
52
73
|
issuer,
|
|
53
74
|
audience,
|
|
54
|
-
algorithms: [...
|
|
75
|
+
algorithms: [...AGENT_TOKEN_ALGS],
|
|
55
76
|
requiredClaims: ["exp", "iat", "sub"],
|
|
56
77
|
clockTolerance: 60,
|
|
57
78
|
});
|