@verax-ai/proxy 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.
@@ -0,0 +1,343 @@
1
+ import { createHash } from "node:crypto";
2
+ import { appendFileSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { decisionRecordHash, signDecisionRecord } from "@cedulon/core";
5
+ import { sha256Canonical } from "./hash.js";
6
+ import { inputsMatchingHash, readInputsIndex } from "./inputs.js";
7
+ import { tenantKey } from "./tenant.js";
8
+ /** One token. The body refuses a call whose JWT has no `jti`. Any other `jti` stays. */
9
+ export const TAINT_CLEAR_FILE = "taint-clear.jsonl";
10
+ export const TAINT_CLEAR_SUBJECT = "verax.taint-clear";
11
+ export const TAINT_CLEAR_REASON = "taint-cleared";
12
+ const CONTROL_EFFECT = "verax.control";
13
+ export function createTaintMemory() {
14
+ return {
15
+ loaded: false,
16
+ replayFailed: false,
17
+ tainted: new Map(),
18
+ jtiBySession: new Map(),
19
+ recorded: new Set(),
20
+ clearWarned: new Set(),
21
+ };
22
+ }
23
+ /**
24
+ * Session key for one token: SHA-256 of the tenant key concatenated with the
25
+ * JWT `jti`. The body already requires a `jti` and refuses only an empty one,
26
+ * so a long `jti` or one that contains a control character is still a session.
27
+ * Absent or empty is not a session.
28
+ */
29
+ export function sessionIdOf(principal) {
30
+ if (!principal)
31
+ return null;
32
+ const jti = principal.jti;
33
+ if (typeof jti !== "string" || jti.length < 1)
34
+ return null;
35
+ const key = tenantKey({
36
+ brain: principal.brain ?? "",
37
+ iss: principal.iss,
38
+ tenant: principal.tenant,
39
+ org: principal.org,
40
+ });
41
+ return createHash("sha256").update(key + jti, "utf8").digest("hex");
42
+ }
43
+ /** What an operator may write as `--session`. A newline would be a second line. */
44
+ function clearSessionToken(value) {
45
+ if (typeof value !== "string" || value.length < 1 || value.length > 4096)
46
+ return null;
47
+ for (let i = 0; i < value.length; i += 1) {
48
+ const c = value.charCodeAt(i);
49
+ if (c < 0x20 || c === 0x7f)
50
+ return null;
51
+ }
52
+ return value;
53
+ }
54
+ /**
55
+ * Cedulon accepts a decision time only when it is a non-negative safe integer.
56
+ * The effect extract's window ends one millisecond later, so that sum has to
57
+ * be a safe integer too. `9007199254740991` is safe, and the next integer is not.
58
+ */
59
+ function clearAtMs(value) {
60
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
61
+ return null;
62
+ if (!Number.isSafeInteger(value + 1))
63
+ return null;
64
+ return value;
65
+ }
66
+ export function taintSourceOf(memory, session) {
67
+ return memory.tainted.get(session) ?? null;
68
+ }
69
+ /** The first return that taints a clean session is the source. A later one does not replace it. */
70
+ export function noteTaintReturn(memory, session, source, jti) {
71
+ if (memory.tainted.has(session))
72
+ return;
73
+ memory.tainted.set(session, source);
74
+ if (typeof jti === "string" && jti.length > 0)
75
+ memory.jtiBySession.set(session, jti);
76
+ }
77
+ /**
78
+ * `token` is either the session key or the raw `jti`. A raw `jti` shared by
79
+ * two sessions clears neither of them.
80
+ */
81
+ export function noteTaintClear(memory, token) {
82
+ if (memory.tainted.delete(token)) {
83
+ memory.jtiBySession.delete(token);
84
+ return;
85
+ }
86
+ const hits = [];
87
+ for (const [id, jti] of memory.jtiBySession) {
88
+ if (jti === token && memory.tainted.has(id))
89
+ hits.push(id);
90
+ }
91
+ if (hits.length !== 1)
92
+ return;
93
+ const id = hits[0];
94
+ memory.tainted.delete(id);
95
+ memory.jtiBySession.delete(id);
96
+ }
97
+ /**
98
+ * The operator command appends one line. The body copies it into a signed
99
+ * record on the next sync. A tool call does not write this file.
100
+ */
101
+ export function appendTaintClearLine(stateDir, line) {
102
+ const session = clearSessionToken(line.session);
103
+ if (!session)
104
+ throw new Error("taint-clear-session");
105
+ const by = typeof line.by === "string" && line.by !== "" && line.by.length <= 256 ? line.by : "unknown";
106
+ const atMs = clearAtMs(line.atMs);
107
+ if (atMs === null)
108
+ throw new Error("taint-clear-time");
109
+ const row = { session, by, via: "cli", atMs };
110
+ appendFileSync(join(stateDir, TAINT_CLEAR_FILE), `${JSON.stringify(row)}\n`, { encoding: "utf8", mode: 0o600 });
111
+ }
112
+ function readClearLines(stateDir, warned) {
113
+ let text;
114
+ try {
115
+ text = readFileSync(join(stateDir, TAINT_CLEAR_FILE), "utf8");
116
+ }
117
+ catch (err) {
118
+ if (err.code === "ENOENT")
119
+ return [];
120
+ throw err;
121
+ }
122
+ const out = [];
123
+ const lines = text.split("\n");
124
+ for (let i = 0; i < lines.length; i += 1) {
125
+ const line = lines[i] ?? "";
126
+ if (line === "")
127
+ continue;
128
+ try {
129
+ const row = JSON.parse(line);
130
+ const atMs = clearAtMs(row.atMs);
131
+ if (atMs === null) {
132
+ const warnKey = `${i + 1}:${line}`;
133
+ if (!warned.has(warnKey)) {
134
+ warned.add(warnKey);
135
+ process.stderr.write(`verax-proxy: taint-clear skipped ${TAINT_CLEAR_FILE}:${i + 1}\n`);
136
+ }
137
+ continue;
138
+ }
139
+ const session = clearSessionToken(row.session);
140
+ if (!session)
141
+ continue;
142
+ const by = typeof row.by === "string" && row.by !== "" && row.by.length <= 256 ? row.by : "unknown";
143
+ out.push({ session, by, via: "cli", atMs, lineNo: i + 1 });
144
+ }
145
+ catch {
146
+ // A torn last line is skipped. The next append is a new line.
147
+ }
148
+ }
149
+ return out;
150
+ }
151
+ function storedSession(inputs) {
152
+ if (typeof inputs.session !== "string" || inputs.session.length < 1)
153
+ return null;
154
+ const brain = inputs.principal?.brain;
155
+ if (typeof brain !== "string")
156
+ return null;
157
+ const id = sessionIdOf({
158
+ brain,
159
+ iss: inputs.principal.iss,
160
+ tenant: inputs.principal.tenant,
161
+ org: inputs.principal.org,
162
+ jti: inputs.session,
163
+ });
164
+ if (!id)
165
+ return null;
166
+ return { id, jti: inputs.session };
167
+ }
168
+ function clearRequestHash(line) {
169
+ return sha256Canonical({ action: "taint-clear", session: line.session, by: line.by, via: line.via, atMs: line.atMs });
170
+ }
171
+ /**
172
+ * Runs after the ledger snapshot is in hand and before it is merged.
173
+ * The race test records a return the snapshot did not include.
174
+ * Production leaves this null.
175
+ */
176
+ export const taintReplayHooks = {
177
+ afterRead: null,
178
+ };
179
+ /**
180
+ * Replay taint from the ledger in durable effect order. A reads-untrusted
181
+ * allow taints only once its effect row is there, including `:threw`, and
182
+ * not when the only effect is `:halted`. A clear effect lifts it. A
183
+ * decision with no effect is not a completed read and is not a completed
184
+ * clear. The source stays the first completed return until the clear.
185
+ *
186
+ * The replay is built into fresh maps and then merged. A session the
187
+ * snapshot has keeps the ledger's source, because that is the first
188
+ * return. A live entry the snapshot does not have stays: it is newer
189
+ * than every clear in the snapshot. A clear is signed only after a
190
+ * replay has succeeded, and a retry runs only while that has not
191
+ * happened yet.
192
+ */
193
+ export async function loadTaintFromLedger(opts) {
194
+ const decisions = await opts.ledger.decisions();
195
+ const effects = await opts.ledger.effects();
196
+ const index = await readInputsIndex(opts.inputsLog);
197
+ taintReplayHooks.afterRead?.(opts.memory);
198
+ const replay = createTaintMemory();
199
+ const byRef = new Map();
200
+ for (const rec of decisions) {
201
+ const ref = rec.claims.ref;
202
+ if (typeof ref !== "string")
203
+ continue;
204
+ const list = byRef.get(ref);
205
+ if (list)
206
+ list.push(rec);
207
+ else
208
+ byRef.set(ref, [rec]);
209
+ if (rec.claims.reasonCode === TAINT_CLEAR_REASON && typeof rec.claims.requestHash === "string") {
210
+ replay.recorded.add(rec.claims.requestHash);
211
+ }
212
+ }
213
+ for (const effect of effects) {
214
+ const effectClass = effect.row.effectClass;
215
+ if (effectClass === "duplicate-effect" || effectClass.endsWith(":halted"))
216
+ continue;
217
+ const ref = effect.row.ref;
218
+ if (typeof ref !== "string")
219
+ continue;
220
+ const recs = byRef.get(ref);
221
+ if (!recs)
222
+ continue;
223
+ for (const rec of recs) {
224
+ if (typeof rec.claims.inputsHash !== "string")
225
+ continue;
226
+ const inputs = index
227
+ ? (index.get(`${rec.claims.inputsHash}:${ref}`) ?? null)
228
+ : await inputsMatchingHash(opts.inputsLog, ref, rec.claims.inputsHash);
229
+ if (!inputs)
230
+ continue;
231
+ if (inputs.taintClear && rec.claims.reasonCode === TAINT_CLEAR_REASON && effectClass === CONTROL_EFFECT) {
232
+ noteTaintClear(replay, inputs.taintClear.session);
233
+ continue;
234
+ }
235
+ const receiving = effect.receivingSession;
236
+ const fromEffect = receiving &&
237
+ typeof receiving.jti === "string" &&
238
+ receiving.jti !== "" &&
239
+ typeof receiving.sessionId === "string" &&
240
+ receiving.sessionId !== ""
241
+ ? { id: receiving.sessionId, jti: receiving.jti }
242
+ : null;
243
+ const stored = fromEffect ?? storedSession(inputs);
244
+ const subject = rec.claims.subject;
245
+ if (stored &&
246
+ rec.claims.decision === "allow" &&
247
+ inputs.toolLabels?.readsUntrusted === true &&
248
+ typeof subject === "string" &&
249
+ (effectClass === subject || effectClass === `${subject}:threw`) &&
250
+ !replay.tainted.has(stored.id)) {
251
+ replay.tainted.set(stored.id, {
252
+ sourceRecordId: decisionRecordHash(rec),
253
+ sourceRef: ref,
254
+ });
255
+ replay.jtiBySession.set(stored.id, stored.jti);
256
+ }
257
+ }
258
+ }
259
+ for (const [session, source] of replay.tainted) {
260
+ opts.memory.tainted.set(session, source);
261
+ const jti = replay.jtiBySession.get(session);
262
+ if (jti !== undefined)
263
+ opts.memory.jtiBySession.set(session, jti);
264
+ }
265
+ for (const hash of replay.recorded)
266
+ opts.memory.recorded.add(hash);
267
+ }
268
+ export async function applyTaintClearFile(opts) {
269
+ // The request time stays in the signed inputs (`atMs`). The decision and
270
+ // the effect are stamped when they are written, so a late clear cannot
271
+ // hide an earlier row from a window read.
272
+ for (const line of readClearLines(opts.stateDir, opts.memory.clearWarned)) {
273
+ const writtenAt = opts.now();
274
+ const requestHash = clearRequestHash(line);
275
+ if (opts.memory.recorded.has(requestHash))
276
+ continue;
277
+ try {
278
+ const ref = opts.nonce();
279
+ const inputs = {
280
+ principal: { brain: "verax-proxy", scopes: [] },
281
+ inputs: [],
282
+ taintClear: { session: line.session, by: line.by, via: line.via, atMs: line.atMs },
283
+ };
284
+ const inputsHash = sha256Canonical(inputs);
285
+ const effectHash = sha256Canonical({
286
+ action: "taint-clear",
287
+ session: line.session,
288
+ by: line.by,
289
+ via: line.via,
290
+ atMs: line.atMs,
291
+ });
292
+ await opts.inputsLog.append(ref, inputs);
293
+ await opts.ledger.appendDecisionChained((prevRecordHash) => signDecisionRecord({
294
+ decider: "verax-proxy",
295
+ subject: TAINT_CLEAR_SUBJECT,
296
+ requestHash,
297
+ policyHash: opts.policyHash,
298
+ inputsHash,
299
+ decision: "allow",
300
+ reasonCode: TAINT_CLEAR_REASON,
301
+ ref,
302
+ effectHash,
303
+ effectClass: CONTROL_EFFECT,
304
+ timestampMs: writtenAt,
305
+ nonce: ref,
306
+ prevRecordHash,
307
+ }, opts.recordSigner.privateKeyPem, opts.recordSigner.publicKeyPem));
308
+ // Seen before the effect row. A throw there must not sign this line again.
309
+ opts.memory.recorded.add(requestHash);
310
+ const row = {
311
+ ref,
312
+ effectHash,
313
+ effectClass: CONTROL_EFFECT,
314
+ timestampMs: writtenAt,
315
+ actor: line.by,
316
+ };
317
+ await opts.ledger.appendEffect(row, "self", effectHash);
318
+ noteTaintClear(opts.memory, line.session);
319
+ }
320
+ catch (err) {
321
+ const message = (err instanceof Error ? err.message : "taint-clear-failed").replace(/[\r\n]+/g, " ").slice(0, 200);
322
+ const warnKey = `apply:${line.lineNo}:${requestHash}`;
323
+ if (!opts.memory.clearWarned.has(warnKey)) {
324
+ opts.memory.clearWarned.add(warnKey);
325
+ process.stderr.write(`verax-proxy: taint-clear failed ${TAINT_CLEAR_FILE}:${line.lineNo}: ${message}\n`);
326
+ }
327
+ }
328
+ }
329
+ }
330
+ /** Used by explain, which already holds the inputs document. */
331
+ export function taintOnInputs(inputs) {
332
+ const taint = inputs?.sessionTaint;
333
+ if (!taint)
334
+ return undefined;
335
+ if (typeof taint.sourceRecordId !== "string" || taint.sourceRecordId === "")
336
+ return undefined;
337
+ if (typeof taint.sourceRef !== "string" || taint.sourceRef === "")
338
+ return undefined;
339
+ return taint;
340
+ }
341
+ export function isTaintClearRecord(rec) {
342
+ return rec.claims.subject === TAINT_CLEAR_SUBJECT && rec.claims.reasonCode === TAINT_CLEAR_REASON;
343
+ }
@@ -0,0 +1,26 @@
1
+ /** The DER certificates of a PEM chain, leaf first. A chain is a leaf and at least one CA. */
2
+ export declare function readIssuerChain(pem: string): Uint8Array[];
3
+ export declare function didX509Value(value: string): string;
4
+ /** did:x509:0:sha256:<root fingerprint>::subject:CN:<leaf CN>. */
5
+ export declare function didX509Issuer(chain: readonly Uint8Array[]): string;
6
+ /** The ledger a witness key signs for, as the statement's subject. */
7
+ export declare function ledgerSubject(publicKeyPem: string): string;
8
+ /** The Signed Statement for one checkpoint hash, signed by the witness key the chain's leaf holds. */
9
+ export declare function checkpointStatement(checkpointHash: string, chain: readonly Uint8Array[], keys: {
10
+ privateKeyPem: string;
11
+ publicKeyPem: string;
12
+ }): Uint8Array;
13
+ export type StatementRead = {
14
+ ok: true;
15
+ issuer: string;
16
+ subject: string;
17
+ } | {
18
+ ok: false;
19
+ reason: string;
20
+ };
21
+ /**
22
+ * Whether `bytes` is this ledger's Signed Statement for `checkpointHash`,
23
+ * signed by `publicKeyPem` with a chain whose leaf holds that key. The
24
+ * did:x509 itself is the service's to resolve when it registers the statement.
25
+ */
26
+ export declare function readCheckpointStatement(bytes: Uint8Array, checkpointHash: string, publicKeyPem: string): StatementRead;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * A Signed Statement (RFC 9943) about one checkpoint, for a SCITT
3
+ * Transparency Service that registers statements over SCRAPI.
4
+ *
5
+ * The statement is a COSE Hash Envelope (draft-ietf-cose-hash-envelope): the
6
+ * payload is the 32-octet checkpoint hash, 258 names SHA-256 and 259 the
7
+ * preimage's type, a COSE_Sign1. Only the hash leaves the machine, as with the
8
+ * digest route; what changes is that the witness signs it as an Issuer.
9
+ *
10
+ * The Issuer is named in the CWT claims (15) as a did:x509 over the X.509
11
+ * chain the statement carries in x5chain (33), leaf first. The leaf must hold
12
+ * the witness key. Verax does not mint certificates; the operator issues the
13
+ * leaf for the witness public key and hands Verax the chain as PEM. The
14
+ * subject (CWT sub) is the ledger, named by the SHA-256 of the witness key.
15
+ */
16
+ import { createHash, createPublicKey, sign, verify, X509Certificate } from "node:crypto";
17
+ import { cborMap, encodeCbor } from "@cedulon/cose";
18
+ import { decodeSign1, sign1Structure } from "./transparency-receipt.js";
19
+ const HDR_ALG = 1;
20
+ const HDR_CWT_CLAIMS = 15;
21
+ const HDR_X5CHAIN = 33;
22
+ const HDR_PAYLOAD_HASH_ALG = 258;
23
+ const HDR_PREIMAGE_CONTENT_TYPE = 259;
24
+ const CWT_ISS = 1;
25
+ const CWT_SUB = 2;
26
+ const ALG_EDDSA = -8;
27
+ const HASH_SHA256 = -16;
28
+ const PREIMAGE_TYPE = "application/cose";
29
+ const HASH = /^[0-9a-f]{64}$/;
30
+ /** The DER certificates of a PEM chain, leaf first. A chain is a leaf and at least one CA. */
31
+ export function readIssuerChain(pem) {
32
+ const blocks = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ?? [];
33
+ if (blocks.length < 2)
34
+ throw new Error("issuer-chain-too-short");
35
+ return blocks.map((block) => {
36
+ try {
37
+ return new Uint8Array(new X509Certificate(block).raw);
38
+ }
39
+ catch {
40
+ throw new Error("issuer-chain-certificate");
41
+ }
42
+ });
43
+ }
44
+ // did:x509 keeps ALPHA / DIGIT / "-" / "." / "_" and percent-encodes the rest.
45
+ export function didX509Value(value) {
46
+ return Array.from(Buffer.from(value, "utf8"))
47
+ .map((b) => {
48
+ const c = String.fromCharCode(b);
49
+ return /[A-Za-z0-9._-]/.test(c) ? c : `%${b.toString(16).toUpperCase().padStart(2, "0")}`;
50
+ })
51
+ .join("");
52
+ }
53
+ /** did:x509:0:sha256:<root fingerprint>::subject:CN:<leaf CN>. */
54
+ export function didX509Issuer(chain) {
55
+ if (chain.length < 2)
56
+ throw new Error("issuer-chain-too-short");
57
+ const leaf = new X509Certificate(chain[0]);
58
+ const cn = leaf.subject
59
+ .split("\n")
60
+ .map((line) => line.trim())
61
+ .find((line) => line.startsWith("CN="));
62
+ if (!cn || cn.length === 3)
63
+ throw new Error("issuer-chain-leaf-cn");
64
+ const fingerprint = createHash("sha256").update(chain[chain.length - 1]).digest("base64url");
65
+ return `did:x509:0:sha256:${fingerprint}::subject:CN:${didX509Value(cn.slice(3))}`;
66
+ }
67
+ function spki(publicKeyPem) {
68
+ return createPublicKey(publicKeyPem).export({ type: "spki", format: "der" });
69
+ }
70
+ /** The ledger a witness key signs for, as the statement's subject. */
71
+ export function ledgerSubject(publicKeyPem) {
72
+ return `verax-ledger:${createHash("sha256").update(spki(publicKeyPem)).digest("hex")}`;
73
+ }
74
+ /** The Signed Statement for one checkpoint hash, signed by the witness key the chain's leaf holds. */
75
+ export function checkpointStatement(checkpointHash, chain, keys) {
76
+ if (!HASH.test(checkpointHash))
77
+ throw new Error("statement-checkpoint-hash");
78
+ const leafKey = new X509Certificate(chain[0]).publicKey.export({ type: "spki", format: "der" });
79
+ if (!leafKey.equals(spki(keys.publicKeyPem)))
80
+ throw new Error("issuer-chain-leaf-key");
81
+ const protectedBytes = encodeCbor(cborMap([
82
+ [HDR_ALG, ALG_EDDSA],
83
+ [
84
+ HDR_CWT_CLAIMS,
85
+ cborMap([
86
+ [CWT_ISS, didX509Issuer(chain)],
87
+ [CWT_SUB, ledgerSubject(keys.publicKeyPem)],
88
+ ]),
89
+ ],
90
+ [HDR_X5CHAIN, chain.map((der) => new Uint8Array(der))],
91
+ [HDR_PAYLOAD_HASH_ALG, HASH_SHA256],
92
+ [HDR_PREIMAGE_CONTENT_TYPE, PREIMAGE_TYPE],
93
+ ]));
94
+ const payload = new Uint8Array(Buffer.from(checkpointHash, "hex"));
95
+ const signature = new Uint8Array(sign(null, sign1Structure(protectedBytes, payload), keys.privateKeyPem));
96
+ // Tagged COSE_Sign1 (tag 18, one octet 0xd2): scitt-ccf-ledger refuses an untagged one.
97
+ return new Uint8Array(Buffer.concat([Buffer.of(0xd2), encodeCbor([protectedBytes, cborMap([]), payload, signature])]));
98
+ }
99
+ /**
100
+ * Whether `bytes` is this ledger's Signed Statement for `checkpointHash`,
101
+ * signed by `publicKeyPem` with a chain whose leaf holds that key. The
102
+ * did:x509 itself is the service's to resolve when it registers the statement.
103
+ */
104
+ export function readCheckpointStatement(bytes, checkpointHash, publicKeyPem) {
105
+ let sign1;
106
+ try {
107
+ sign1 = decodeSign1(bytes);
108
+ }
109
+ catch {
110
+ return { ok: false, reason: "the statement is not a COSE_Sign1" };
111
+ }
112
+ const h = sign1.protectedHeader;
113
+ if (h.get(HDR_ALG) !== ALG_EDDSA)
114
+ return { ok: false, reason: "the statement is not EdDSA" };
115
+ if (h.get(HDR_PAYLOAD_HASH_ALG) !== HASH_SHA256)
116
+ return { ok: false, reason: "the statement is not a SHA-256 hash envelope" };
117
+ const cwt = h.get(HDR_CWT_CLAIMS);
118
+ const issuer = cwt instanceof Map ? cwt.get(CWT_ISS) : undefined;
119
+ const subject = cwt instanceof Map ? cwt.get(CWT_SUB) : undefined;
120
+ if (typeof issuer !== "string" || !issuer.startsWith("did:x509:") || typeof subject !== "string") {
121
+ return { ok: false, reason: "the statement names no did:x509 issuer and subject" };
122
+ }
123
+ if (!HASH.test(checkpointHash) || !(sign1.payload instanceof Uint8Array) || !Buffer.from(sign1.payload).equals(Buffer.from(checkpointHash, "hex"))) {
124
+ return { ok: false, reason: "the statement names another checkpoint" };
125
+ }
126
+ let signed = false;
127
+ try {
128
+ signed = verify(null, sign1Structure(sign1.protectedBytes, sign1.payload), publicKeyPem, sign1.signature);
129
+ }
130
+ catch {
131
+ signed = false;
132
+ }
133
+ if (!signed)
134
+ return { ok: false, reason: "the statement does not verify under the checkpoint key" };
135
+ const x5chain = h.get(HDR_X5CHAIN);
136
+ const leaf = Array.isArray(x5chain) ? x5chain[0] : x5chain;
137
+ try {
138
+ if (!(leaf instanceof Uint8Array) || !new X509Certificate(leaf).publicKey.export({ type: "spki", format: "der" }).equals(spki(publicKeyPem))) {
139
+ return { ok: false, reason: "the statement's x5chain leaf holds another key" };
140
+ }
141
+ }
142
+ catch {
143
+ return { ok: false, reason: "the statement's x5chain leaf is not a certificate" };
144
+ }
145
+ return { ok: true, issuer, subject };
146
+ }
@@ -0,0 +1,43 @@
1
+ import type { ToolLabelName } from "./types.ts";
2
+ /**
3
+ * Built-in tools whose results or effects cross the operator's boundary.
4
+ * A policy `toolLabels` entry for the same name replaces this list, including
5
+ * an empty list (the operator labelled it as neither).
6
+ *
7
+ * `message.read` returns the inbox: messages that arrived from outside.
8
+ * `message.send` queues a message for delivery. `spend` authorizes a payment.
9
+ * `memory.get`, `memory.put` and `audit.explain` stay on this machine's own
10
+ * store and ledger, so they carry neither label.
11
+ */
12
+ export declare const BUILTIN_TOOL_LABELS: Readonly<Record<string, readonly ToolLabelName[]>>;
13
+ export type ResolvedToolLabels = {
14
+ readsUntrusted: boolean;
15
+ egress: boolean;
16
+ /** False only for a downstream tool nobody labelled. Doctor lists those. */
17
+ labelled: boolean;
18
+ };
19
+ export declare function parseToolLabelMap(raw: unknown, code: string): Readonly<Record<string, readonly ToolLabelName[]>>;
20
+ export declare function parseToolLabelList(value: unknown, code: string): ToolLabelName[];
21
+ /**
22
+ * Policy labels win, then the downstream document, then the built-in defaults.
23
+ * A downstream tool with no entry in either place is both labels, unless the
24
+ * policy sets `unlabelledDownstream` to `neither`. A key that is present and
25
+ * empty is a label: the operator said neither.
26
+ */
27
+ export declare function resolveToolLabels(opts: {
28
+ tool: string;
29
+ policyLabels?: Readonly<Record<string, readonly ToolLabelName[]>>;
30
+ documentLabels?: Readonly<Record<string, readonly ToolLabelName[]>>;
31
+ downstreamTools?: ReadonlySet<string>;
32
+ unlabelledDownstream?: "both" | "neither";
33
+ }): ResolvedToolLabels;
34
+ /**
35
+ * Downstream tools the operator did not label, prefixed (`web.fetch`).
36
+ * A child with no `tools` list is named by its prefix: the body cannot see
37
+ * the child's list without attaching it, and doctor does not attach.
38
+ */
39
+ export declare function unlabelledDownstreamNames(specs: readonly {
40
+ prefix: string;
41
+ tools?: readonly string[];
42
+ labels?: Readonly<Record<string, readonly string[]>>;
43
+ }[], policyLabels: Readonly<Record<string, readonly ToolLabelName[]>>): string[];
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Built-in tools whose results or effects cross the operator's boundary.
3
+ * A policy `toolLabels` entry for the same name replaces this list, including
4
+ * an empty list (the operator labelled it as neither).
5
+ *
6
+ * `message.read` returns the inbox: messages that arrived from outside.
7
+ * `message.send` queues a message for delivery. `spend` authorizes a payment.
8
+ * `memory.get`, `memory.put` and `audit.explain` stay on this machine's own
9
+ * store and ledger, so they carry neither label.
10
+ */
11
+ export const BUILTIN_TOOL_LABELS = {
12
+ "message.read": ["reads-untrusted"],
13
+ "message.send": ["egress"],
14
+ spend: ["egress"],
15
+ };
16
+ const TOOL_NAME_RE = /^[A-Za-z][A-Za-z0-9._-]{0,96}$/;
17
+ export function parseToolLabelMap(raw, code) {
18
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
19
+ throw new Error(code);
20
+ const out = {};
21
+ for (const [tool, value] of Object.entries(raw)) {
22
+ if (!TOOL_NAME_RE.test(tool))
23
+ throw new Error(`${code}:${tool}`);
24
+ out[tool] = parseToolLabelList(value, `${code}:${tool}`);
25
+ }
26
+ return out;
27
+ }
28
+ export function parseToolLabelList(value, code) {
29
+ if (!Array.isArray(value))
30
+ throw new Error(code);
31
+ const out = [];
32
+ for (const item of value) {
33
+ if (item !== "reads-untrusted" && item !== "egress")
34
+ throw new Error(code);
35
+ if (!out.includes(item))
36
+ out.push(item);
37
+ }
38
+ return out;
39
+ }
40
+ function flags(labels, labelled) {
41
+ return {
42
+ readsUntrusted: labels.includes("reads-untrusted"),
43
+ egress: labels.includes("egress"),
44
+ labelled,
45
+ };
46
+ }
47
+ /**
48
+ * Policy labels win, then the downstream document, then the built-in defaults.
49
+ * A downstream tool with no entry in either place is both labels, unless the
50
+ * policy sets `unlabelledDownstream` to `neither`. A key that is present and
51
+ * empty is a label: the operator said neither.
52
+ */
53
+ export function resolveToolLabels(opts) {
54
+ const policyLabels = opts.policyLabels ?? {};
55
+ const unlabelledDownstream = opts.unlabelledDownstream ?? "both";
56
+ if (Object.prototype.hasOwnProperty.call(policyLabels, opts.tool)) {
57
+ return flags(policyLabels[opts.tool] ?? [], true);
58
+ }
59
+ if (opts.documentLabels && Object.prototype.hasOwnProperty.call(opts.documentLabels, opts.tool)) {
60
+ return flags(opts.documentLabels[opts.tool] ?? [], true);
61
+ }
62
+ if (Object.prototype.hasOwnProperty.call(BUILTIN_TOOL_LABELS, opts.tool)) {
63
+ return flags(BUILTIN_TOOL_LABELS[opts.tool] ?? [], true);
64
+ }
65
+ if (opts.downstreamTools?.has(opts.tool)) {
66
+ if (unlabelledDownstream === "neither") {
67
+ return { readsUntrusted: false, egress: false, labelled: false };
68
+ }
69
+ return { readsUntrusted: true, egress: true, labelled: false };
70
+ }
71
+ return { readsUntrusted: false, egress: false, labelled: true };
72
+ }
73
+ /**
74
+ * Downstream tools the operator did not label, prefixed (`web.fetch`).
75
+ * A child with no `tools` list is named by its prefix: the body cannot see
76
+ * the child's list without attaching it, and doctor does not attach.
77
+ */
78
+ export function unlabelledDownstreamNames(specs, policyLabels) {
79
+ const names = [];
80
+ for (const spec of specs) {
81
+ if (spec.tools === undefined) {
82
+ names.push(spec.prefix);
83
+ continue;
84
+ }
85
+ for (const child of spec.tools) {
86
+ const prefixed = `${spec.prefix}.${child}`;
87
+ const inDoc = spec.labels !== undefined && Object.prototype.hasOwnProperty.call(spec.labels, child);
88
+ const inPolicy = Object.prototype.hasOwnProperty.call(policyLabels, prefixed);
89
+ if (!inDoc && !inPolicy)
90
+ names.push(prefixed);
91
+ }
92
+ }
93
+ return names;
94
+ }