@verax-ai/body 0.4.1 → 0.4.3

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,2 @@
1
+ export declare const EX_ANCHOR_FAILED = 1;
2
+ export declare function runAnchor(argv: readonly string[], out?: (s: string) => void, fetchImpl?: typeof fetch, now?: () => number): Promise<number>;
@@ -0,0 +1,203 @@
1
+ /**
2
+ * `verax anchor <stateDir> --service <url>` registers each checkpoint this
3
+ * ledger holds with a SCITT Transparency Service that someone else runs, and
4
+ * keeps the COSE Receipt it returns in `checkpoint-anchors.jsonl`.
5
+ *
6
+ * Only the checkpoint hash leaves the machine: `POST <service>/register` with
7
+ * `{"capsule_id": <SHA-256 of the checkpoint's COSE octets>}`. The window, the
8
+ * counts and the head stay here. A checkpoint already anchored at that service
9
+ * is not sent again.
10
+ *
11
+ * `--service-key <pem>` checks each receipt as it arrives and refuses to keep
12
+ * one that does not verify. Without it the receipt is kept and `verax verify
13
+ * --anchor-key` is where it is first checked.
14
+ */
15
+ import { readFileSync } from "node:fs";
16
+ import { anchorEntryHash, appendAnchor, readAnchors, readCheckpointFile, verifyReceipt, } from "@verax-ai/proxy";
17
+ import { checkpointHash } from "@cedulon/checkpoint";
18
+ export const EX_ANCHOR_FAILED = 1;
19
+ const EX_USAGE = 64;
20
+ function usage() {
21
+ return [
22
+ "usage: verax anchor <stateDir> --service <url> [--service-key <public.pem>] [--json]",
23
+ "",
24
+ " --service <url> the Transparency Service, for example https://witness.agentactioncapsule.org.",
25
+ " https only; http is accepted for a loopback address.",
26
+ " --service-key <file> the service's public key; each receipt must verify under it before it is kept",
27
+ " --json one JSON object per anchored checkpoint",
28
+ "",
29
+ "Sends the SHA-256 of each checkpoint not yet anchored at that service, and nothing else.",
30
+ ].join("\n");
31
+ }
32
+ function serviceUrl(raw) {
33
+ let url;
34
+ try {
35
+ url = new URL(raw);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "")
41
+ return null;
42
+ const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]";
43
+ if (url.protocol === "https:")
44
+ return url;
45
+ if (url.protocol === "http:" && loopback)
46
+ return url;
47
+ return null;
48
+ }
49
+ // A receipt is a few hundred bytes; the reader refuses CBOR over 64 KiB.
50
+ const MAX_ANSWER_BYTES = 256 * 1024;
51
+ const MAX_RECEIPT_BYTES = 64 * 1024;
52
+ const MAX_RECEIPT_B64 = Math.ceil(MAX_RECEIPT_BYTES / 3) * 4;
53
+ /** The body as text, refused once it passes MAX_ANSWER_BYTES rather than held in full. */
54
+ async function boundedText(res) {
55
+ const declared = Number(res.headers.get("content-length") ?? "0");
56
+ if (declared > MAX_ANSWER_BYTES)
57
+ throw new Error("answer too large");
58
+ if (!res.body)
59
+ return "";
60
+ const reader = res.body.getReader();
61
+ const chunks = [];
62
+ let size = 0;
63
+ for (;;) {
64
+ const { done, value } = await reader.read();
65
+ if (done)
66
+ break;
67
+ size += value.length;
68
+ if (size > MAX_ANSWER_BYTES) {
69
+ await reader.cancel();
70
+ throw new Error("answer too large");
71
+ }
72
+ chunks.push(value);
73
+ }
74
+ return Buffer.concat(chunks).toString("utf8");
75
+ }
76
+ export async function runAnchor(argv, out = (s) => process.stdout.write(`${s}\n`), fetchImpl = fetch, now = Date.now) {
77
+ const args = [...argv];
78
+ if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
79
+ out(usage());
80
+ return args.length === 0 ? EX_USAGE : 0;
81
+ }
82
+ const json = args.includes("--json");
83
+ const take = (flag) => {
84
+ const at = args.indexOf(flag);
85
+ if (at === -1)
86
+ return undefined;
87
+ const value = args[at + 1];
88
+ if (!value || value.startsWith("-"))
89
+ return null;
90
+ args.splice(at, 2);
91
+ return value;
92
+ };
93
+ const rawService = take("--service");
94
+ if (!rawService) {
95
+ out("anchor: --service <url> is required");
96
+ return EX_USAGE;
97
+ }
98
+ const service = serviceUrl(rawService);
99
+ if (!service) {
100
+ out("anchor: --service must be an https URL with no credentials, query or fragment (http only on loopback)");
101
+ return EX_USAGE;
102
+ }
103
+ const keyPath = take("--service-key");
104
+ if (keyPath === null) {
105
+ out("anchor: --service-key needs a file path");
106
+ return EX_USAGE;
107
+ }
108
+ let serviceKey = null;
109
+ if (keyPath) {
110
+ try {
111
+ serviceKey = readFileSync(keyPath, "utf8");
112
+ }
113
+ catch {
114
+ out(`anchor: cannot read key file ${keyPath}`);
115
+ return EX_USAGE;
116
+ }
117
+ if (serviceKey.trim() === "") {
118
+ out(`anchor: key file ${keyPath} is empty`);
119
+ return EX_USAGE;
120
+ }
121
+ }
122
+ const dir = args.find((a) => !a.startsWith("-"));
123
+ if (!dir) {
124
+ out(usage());
125
+ return EX_USAGE;
126
+ }
127
+ const serviceName = service.origin + service.pathname.replace(/\/+$/, "");
128
+ const loaded = readCheckpointFile(dir);
129
+ if (loaded.problems.length > 0) {
130
+ for (const p of loaded.problems)
131
+ out(`anchor: ${p}`);
132
+ return EX_ANCHOR_FAILED;
133
+ }
134
+ const existing = readAnchors(dir);
135
+ if (existing.problems.length > 0) {
136
+ for (const p of existing.problems)
137
+ out(`anchor: ${p}`);
138
+ return EX_ANCHOR_FAILED;
139
+ }
140
+ const done = new Set(existing.rows.filter((r) => r.service === serviceName).map((r) => r.checkpointHash));
141
+ const pending = loaded.rows.map((row) => checkpointHash(row)).filter((hash) => !done.has(hash));
142
+ if (pending.length === 0) {
143
+ out(json ? JSON.stringify({ anchored: 0, service: serviceName }) : `nothing to anchor at ${serviceName}`);
144
+ return 0;
145
+ }
146
+ let failed = 0;
147
+ for (const hash of pending) {
148
+ const entryHash = anchorEntryHash(hash, "register");
149
+ let answer;
150
+ try {
151
+ const res = await fetchImpl(`${serviceName}/register`, {
152
+ method: "POST",
153
+ headers: { "content-type": "application/json", accept: "application/json" },
154
+ body: JSON.stringify({ capsule_id: hash }),
155
+ signal: AbortSignal.timeout(15_000),
156
+ redirect: "error",
157
+ });
158
+ if (!res.ok)
159
+ throw new Error(`HTTP ${res.status}`);
160
+ answer = JSON.parse(await boundedText(res));
161
+ }
162
+ catch (err) {
163
+ failed += 1;
164
+ out(`anchor: ${hash.slice(0, 12)} not registered: ${err instanceof Error ? err.message : String(err)}`);
165
+ continue;
166
+ }
167
+ const { receipt_b64, entry_hash, leaf_index, tree_size } = answer;
168
+ if (typeof receipt_b64 !== "string" ||
169
+ receipt_b64.length > MAX_RECEIPT_B64 ||
170
+ Buffer.from(receipt_b64, "base64").length > MAX_RECEIPT_BYTES ||
171
+ entry_hash !== entryHash ||
172
+ !Number.isSafeInteger(leaf_index) ||
173
+ !Number.isSafeInteger(tree_size)) {
174
+ failed += 1;
175
+ out(`anchor: ${hash.slice(0, 12)} the service answered with a receipt for another entry, or no receipt`);
176
+ continue;
177
+ }
178
+ if (serviceKey) {
179
+ const check = verifyReceipt(Buffer.from(receipt_b64, "base64"), Buffer.from(entryHash, "hex"), serviceKey);
180
+ if (!check.ok || check.treeSize !== tree_size || check.leafIndex !== leaf_index) {
181
+ failed += 1;
182
+ out(`anchor: ${hash.slice(0, 12)} receipt does not verify under --service-key; not kept`);
183
+ continue;
184
+ }
185
+ }
186
+ const row = {
187
+ v: 1,
188
+ checkpointHash: hash,
189
+ service: serviceName,
190
+ route: "register",
191
+ entryHash,
192
+ leafIndex: leaf_index,
193
+ treeSize: tree_size,
194
+ receiptB64: receipt_b64,
195
+ atMs: now(),
196
+ };
197
+ appendAnchor(dir, row);
198
+ out(json
199
+ ? JSON.stringify(row)
200
+ : `anchored ${hash.slice(0, 12)} at ${serviceName}: leaf ${row.leafIndex} of ${row.treeSize}${serviceKey ? ", receipt verified" : ", receipt not yet checked"}`);
201
+ }
202
+ return failed === 0 ? 0 : EX_ANCHOR_FAILED;
203
+ }
@@ -0,0 +1,47 @@
1
+ import type { ApprovalSignature } from "@verax-ai/proxy";
2
+ export declare function approvalChallenge(input: {
3
+ ref: string;
4
+ requestHash: string;
5
+ deferRecordHash: string;
6
+ }): string;
7
+ export type ApprovalGate = {
8
+ ok: true;
9
+ signature?: ApprovalSignature;
10
+ } | {
11
+ ok: false;
12
+ status: 403 | 503;
13
+ error: "approve-signature-required" | "approve-signature-invalid" | "unknown-credential" | "cloned-authenticator" | "passkey-closed";
14
+ reason?: string;
15
+ };
16
+ /**
17
+ * When an operator is registered, the approval body must carry that
18
+ * operator's assertion for this defer. No registered operator keeps today's
19
+ * unsigned HTTP approval, and the signature is not written.
20
+ */
21
+ export declare function gateApprovalSignature(opts: {
22
+ stateDir: string;
23
+ env: NodeJS.ProcessEnv;
24
+ assertion: unknown;
25
+ ref: string;
26
+ requestHash: string;
27
+ deferRecordHash: string;
28
+ }): Promise<ApprovalGate>;
29
+ export type ApprovalSignatureReport = {
30
+ ok: boolean;
31
+ signedVerified: number;
32
+ signedFailed: number;
33
+ unsignedHttp: number;
34
+ cli: number;
35
+ line: string;
36
+ trustSource: "pinned" | "in-ledger" | "none";
37
+ trustNote: string;
38
+ };
39
+ /**
40
+ * Recount operator approvals without a body. A signature is checked against
41
+ * the operator public key and the challenge rebuilt from the defer record.
42
+ * The authenticator counter is not consulted: this is a re-read, not a second use.
43
+ * `cli` and `cli-script` are both the unsigned CLI door.
44
+ */
45
+ export declare function verifyApprovalSignatures(stateDir: string, opts?: {
46
+ credentialsFile?: string;
47
+ }): Promise<ApprovalSignatureReport>;
@@ -0,0 +1,290 @@
1
+ /**
2
+ * An HTTP approval is bound to one defer record by a challenge the body and
3
+ * `verax verify` both rebuild from that record. Nothing about that challenge
4
+ * is remembered on the server.
5
+ */
6
+ import { createHash } from "node:crypto";
7
+ import { readFileSync } from "node:fs";
8
+ import { canonical, decisionRecordHash } from "@cedulon/core";
9
+ import { listPieceFiles } from "@verax-ai/proxy";
10
+ import { credentialsPath, findCredential, hasRegisteredOperator, readCredentialsAt, updateCounter, } from "./operator-credentials.js";
11
+ import { readRpConfig } from "./rp-config.js";
12
+ import { verifyAssertion } from "./webauthn-verify.js";
13
+ export function approvalChallenge(input) {
14
+ const json = canonical({
15
+ v: 1,
16
+ purpose: "verax.approve",
17
+ ref: input.ref,
18
+ requestHash: input.requestHash,
19
+ deferRecordHash: input.deferRecordHash,
20
+ });
21
+ return createHash("sha256").update(json).digest("base64url");
22
+ }
23
+ function asAssertion(value) {
24
+ if (!value || typeof value !== "object")
25
+ return null;
26
+ const row = value;
27
+ if (typeof row.id !== "string" || row.id === "" || row.rawId !== row.id)
28
+ return null;
29
+ if (row.type !== "public-key")
30
+ return null;
31
+ const response = row.response;
32
+ if (!response || typeof response !== "object")
33
+ return null;
34
+ if (typeof response.clientDataJSON !== "string" || response.clientDataJSON === "")
35
+ return null;
36
+ if (typeof response.authenticatorData !== "string" || response.authenticatorData === "")
37
+ return null;
38
+ if (typeof response.signature !== "string" || response.signature === "")
39
+ return null;
40
+ if (row.clientExtensionResults === undefined)
41
+ return { ...row, clientExtensionResults: {} };
42
+ return row;
43
+ }
44
+ /**
45
+ * When an operator is registered, the approval body must carry that
46
+ * operator's assertion for this defer. No registered operator keeps today's
47
+ * unsigned HTTP approval, and the signature is not written.
48
+ */
49
+ export async function gateApprovalSignature(opts) {
50
+ if (!hasRegisteredOperator(opts.stateDir))
51
+ return { ok: true };
52
+ const rp = readRpConfig(opts.env);
53
+ if (!rp.ok)
54
+ return { ok: false, status: 503, error: "passkey-closed", reason: rp.reason };
55
+ if (opts.assertion === undefined || opts.assertion === null) {
56
+ return { ok: false, status: 403, error: "approve-signature-required" };
57
+ }
58
+ const assertion = asAssertion(opts.assertion);
59
+ if (!assertion)
60
+ return { ok: false, status: 403, error: "approve-signature-invalid" };
61
+ const stored = findCredential(opts.stateDir, assertion.id);
62
+ if (!stored)
63
+ return { ok: false, status: 403, error: "unknown-credential" };
64
+ const expectedChallenge = approvalChallenge({
65
+ ref: opts.ref,
66
+ requestHash: opts.requestHash,
67
+ deferRecordHash: opts.deferRecordHash,
68
+ });
69
+ const verified = verifyAssertion({
70
+ response: assertion,
71
+ expectedChallenge,
72
+ expectedOrigins: rp.config.origins,
73
+ rpId: rp.config.rpID,
74
+ publicKeyCose: stored.publicKey,
75
+ });
76
+ if (!verified.ok)
77
+ return { ok: false, status: 403, error: "approve-signature-invalid" };
78
+ if (!updateCounter(opts.stateDir, stored.id, verified.counter)) {
79
+ return { ok: false, status: 403, error: "cloned-authenticator" };
80
+ }
81
+ return {
82
+ ok: true,
83
+ signature: {
84
+ credentialId: stored.id,
85
+ sub: stored.sub,
86
+ authenticatorData: assertion.response.authenticatorData,
87
+ clientDataJSON: assertion.response.clientDataJSON,
88
+ signature: assertion.response.signature,
89
+ deferRecordHash: opts.deferRecordHash,
90
+ rpId: rp.config.rpID,
91
+ },
92
+ };
93
+ }
94
+ const PINNED_NOTE = "verified against a key the reader supplied, not one taken from these files";
95
+ const FILE_NOTE = "verified against the key carried in operator-credentials.json: this shows the files are internally consistent, not that the key was ever trusted. Pin a key you hold to check that.";
96
+ const NO_KEY_NOTE = "no operator key was found in these files";
97
+ function readLines(path) {
98
+ try {
99
+ return readFileSync(path, "utf8")
100
+ .split("\n")
101
+ .filter((line) => line !== "");
102
+ }
103
+ catch (err) {
104
+ if (err.code === "ENOENT")
105
+ return [];
106
+ throw err;
107
+ }
108
+ }
109
+ function signatureOf(value) {
110
+ if (!value || typeof value !== "object")
111
+ return null;
112
+ const row = value;
113
+ if (typeof row.credentialId !== "string" || row.credentialId === "")
114
+ return null;
115
+ if (typeof row.sub !== "string" || row.sub === "")
116
+ return null;
117
+ if (typeof row.authenticatorData !== "string" || row.authenticatorData === "")
118
+ return null;
119
+ if (typeof row.clientDataJSON !== "string" || row.clientDataJSON === "")
120
+ return null;
121
+ if (typeof row.signature !== "string" || row.signature === "")
122
+ return null;
123
+ if (typeof row.deferRecordHash !== "string" || row.deferRecordHash === "")
124
+ return null;
125
+ if (typeof row.rpId !== "string" || row.rpId === "")
126
+ return null;
127
+ return row;
128
+ }
129
+ function originInClientData(clientDataJSON) {
130
+ try {
131
+ const parsed = JSON.parse(Buffer.from(clientDataJSON, "base64url").toString("utf8"));
132
+ if (!parsed || typeof parsed !== "object")
133
+ return null;
134
+ const origin = parsed.origin;
135
+ return typeof origin === "string" && origin !== "" ? origin : null;
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ }
141
+ function originOnSignature(value) {
142
+ if (!value || typeof value !== "object")
143
+ return null;
144
+ const clientDataJSON = value.clientDataJSON;
145
+ if (typeof clientDataJSON !== "string" || clientDataJSON === "")
146
+ return null;
147
+ return originInClientData(clientDataJSON);
148
+ }
149
+ function assertionMatches(sig, publicKey, challenge) {
150
+ // The origin stays in clientDataJSON and is reported on the verify line.
151
+ // This re-read does not judge it: the allow-list is not in these files, so
152
+ // handing the claimed origin back is not an allow-list decision. rpIdHash
153
+ // and the user-verification flag are still required.
154
+ const origin = originInClientData(sig.clientDataJSON);
155
+ if (!origin)
156
+ return false;
157
+ return verifyAssertion({
158
+ response: {
159
+ response: {
160
+ clientDataJSON: sig.clientDataJSON,
161
+ authenticatorData: sig.authenticatorData,
162
+ signature: sig.signature,
163
+ },
164
+ },
165
+ expectedChallenge: challenge,
166
+ expectedOrigins: [origin],
167
+ rpId: sig.rpId,
168
+ publicKeyCose: publicKey,
169
+ }).ok;
170
+ }
171
+ function trustOf(pinned, credentials) {
172
+ if (pinned)
173
+ return { trustSource: "pinned", trustNote: PINNED_NOTE };
174
+ if (credentials.length > 0)
175
+ return { trustSource: "in-ledger", trustNote: FILE_NOTE };
176
+ return { trustSource: "none", trustNote: NO_KEY_NOTE };
177
+ }
178
+ /**
179
+ * Recount operator approvals without a body. A signature is checked against
180
+ * the operator public key and the challenge rebuilt from the defer record.
181
+ * The authenticator counter is not consulted: this is a re-read, not a second use.
182
+ * `cli` and `cli-script` are both the unsigned CLI door.
183
+ */
184
+ export async function verifyApprovalSignatures(stateDir, opts = {}) {
185
+ const pinned = typeof opts.credentialsFile === "string";
186
+ const credentials = readCredentialsAt(pinned ? opts.credentialsFile : credentialsPath(stateDir));
187
+ const trust = trustOf(pinned, credentials);
188
+ const decisions = [];
189
+ // Every inputs row under a ref, by the hash of its inputs document. A ref can
190
+ // hold rows with no record (a crash, a retry, or a row appended by hand);
191
+ // only the row the allow's signed inputsHash names speaks for that allow.
192
+ const inputsByRef = new Map();
193
+ for (const piece of listPieceFiles(stateDir)) {
194
+ for (const line of readLines(piece.decisions)) {
195
+ try {
196
+ decisions.push(JSON.parse(line));
197
+ }
198
+ catch {
199
+ // A line that does not parse is the ledger statement's problem.
200
+ }
201
+ }
202
+ for (const line of readLines(piece.inputs)) {
203
+ try {
204
+ const row = JSON.parse(line);
205
+ if (typeof row.ref !== "string" || row.inputs === undefined)
206
+ continue;
207
+ const hash = createHash("sha256").update(canonical(row.inputs), "utf8").digest("hex");
208
+ const byHash = inputsByRef.get(row.ref) ?? new Map();
209
+ byHash.set(hash, row.inputs?.approver ?? null);
210
+ inputsByRef.set(row.ref, byHash);
211
+ }
212
+ catch {
213
+ // Same as a decision line: skip, do not invent a failure from a torn line.
214
+ }
215
+ }
216
+ }
217
+ let signedVerified = 0;
218
+ let signedFailed = 0;
219
+ let unsignedHttp = 0;
220
+ let cli = 0;
221
+ let other = 0;
222
+ const origins = [];
223
+ // A defer resolves once. A second signed allow for the same defer reuses an
224
+ // operator signature the operator gave for one approval.
225
+ const signedDefers = new Set();
226
+ for (const row of decisions) {
227
+ // A parsed line that is not a decision record is the ledger statement's problem, not a crash here.
228
+ if (!row || typeof row !== "object" || !row.claims || typeof row.claims !== "object")
229
+ continue;
230
+ if (row.claims.decision !== "allow" || typeof row.claims.ref !== "string")
231
+ continue;
232
+ // No row hashes to the signed inputsHash: the ledger statement names that
233
+ // record, and no other row is read in its place.
234
+ const signedInputs = typeof row.claims.inputsHash === "string" ? row.claims.inputsHash : null;
235
+ const approver = signedInputs === null ? null : inputsByRef.get(row.claims.ref)?.get(signedInputs);
236
+ if (!approver)
237
+ continue;
238
+ if (approver.signature === undefined) {
239
+ if (approver.via === "http")
240
+ unsignedHttp += 1;
241
+ else if (approver.via === "cli" || approver.via === "cli-script")
242
+ cli += 1;
243
+ else
244
+ other += 1;
245
+ continue;
246
+ }
247
+ const seen = originOnSignature(approver.signature);
248
+ if (seen && !origins.includes(seen))
249
+ origins.push(seen);
250
+ const sig = signatureOf(approver.signature);
251
+ const cred = sig ? credentials.find((c) => c.id === sig.credentialId && c.sub === sig.sub) : undefined;
252
+ const defer = sig && typeof approver.resolves === "string"
253
+ ? decisions.find((d) => d?.claims?.ref === approver.resolves && d.claims.decision === "defer")
254
+ : undefined;
255
+ let recordHash = null;
256
+ if (defer) {
257
+ try {
258
+ recordHash = decisionRecordHash(defer);
259
+ }
260
+ catch {
261
+ recordHash = null;
262
+ }
263
+ }
264
+ // The signature covers the defer; the allow must be for that same request,
265
+ // or a body holding one genuine signature could attach it to another allow.
266
+ const sameRequest = defer !== undefined && row.claims.requestHash === defer.claims.requestHash;
267
+ const firstUse = recordHash !== null && !signedDefers.has(recordHash);
268
+ if (recordHash !== null)
269
+ signedDefers.add(recordHash);
270
+ const challenge = sig && defer && sameRequest && firstUse && recordHash && recordHash === sig.deferRecordHash && typeof defer.claims.requestHash === "string"
271
+ ? approvalChallenge({ ref: approver.resolves, requestHash: defer.claims.requestHash, deferRecordHash: recordHash })
272
+ : null;
273
+ if (sig && cred && challenge && assertionMatches(sig, cred.publicKey, challenge))
274
+ signedVerified += 1;
275
+ else
276
+ signedFailed += 1;
277
+ }
278
+ const originSuffix = origins.length === 0 ? "" : ` · origin ${origins.join(", ")}`;
279
+ const report = {
280
+ ok: signedFailed === 0,
281
+ signedVerified,
282
+ signedFailed,
283
+ unsignedHttp,
284
+ cli,
285
+ line: `approval signatures signed-verified ${signedVerified} · signed-failed ${signedFailed} · unsigned-http ${unsignedHttp} · cli ${cli}${other > 0 ? ` · other ${other}` : ""}${originSuffix}`,
286
+ trustSource: trust.trustSource,
287
+ trustNote: trust.trustNote,
288
+ };
289
+ return report;
290
+ }
package/dist/cli.js CHANGED
@@ -11,6 +11,7 @@ import { clearCliCodeCheckPassed, defaultElevated, directoryAccess, doctorStateT
11
11
  import { runHalt, runResume } from "./halt.js";
12
12
  import { main } from "./main.js";
13
13
  import { runOperator } from "./operator-cli.js";
14
+ import { runAnchor } from "./anchor-cli.js";
14
15
  import { runReconcile } from "./reconcile-cli.js";
15
16
  import { runVerify } from "./verify-cli.js";
16
17
  import { runUnlock } from "./unlock.js";
@@ -48,7 +49,10 @@ Usage: verax <command> [options]
48
49
  operator <args> enrol an operator and manage their passkeys
49
50
  reconcile <args> compare the ledger against a statement
50
51
  verify <stateDir> read a ledger back without a body: signatures, chain,
51
- effect binding, and which key answered
52
+ effect binding, which key answered, and approval signatures
53
+ anchor <stateDir> --service <url>
54
+ register each checkpoint's hash with a transparency service
55
+ someone else runs and keep its receipt for verify --anchor-key
52
56
  witness <stateDir> run the witness alongside a body
53
57
  halt <stateDir> stop the body from allowing anything further
54
58
  resume <stateDir> lift a halt; who and when go to halt-history.jsonl
@@ -262,6 +266,9 @@ async function dispatchCli(argv, stdout, stderr, env) {
262
266
  if (argv[0] === "verify") {
263
267
  return runVerify(argv.slice(1), (s) => stdout.write(`${s}\n`));
264
268
  }
269
+ if (argv[0] === "anchor") {
270
+ return runAnchor(argv.slice(1), (s) => stdout.write(`${s}\n`));
271
+ }
265
272
  if (argv[0] === "desktop") {
266
273
  stderr.write("desktop-not-released: the desktop panel is not in this release\n");
267
274
  return 64;
package/dist/desktop.d.ts CHANGED
@@ -58,7 +58,9 @@ export declare function issuerJwksPinPath(stateDir: string): string;
58
58
  export declare function discardStaleFile(file: string): void;
59
59
  /**
60
60
  * The pin is the file the issuer just wrote. Compact JSON, or a throw when
61
- * it is not a key set. Nothing is fetched.
61
+ * it is not a key set. Nothing is fetched. A symlink for `dev-issuer` or for
62
+ * the pin file is refused, and so is any key that carries private material:
63
+ * those fail closed instead of being stripped out.
62
64
  */
63
65
  export declare function readIssuerJwksPin(stateDir: string): string;
64
66
  export declare function issuerReadyLine(port: number): string;
@@ -146,6 +148,14 @@ export type DesktopHooks = {
146
148
  * DACL hook is set and this is not, ancestors are not read from the machine.
147
149
  */
148
150
  windowsAncestorDacl?: (dir: string) => string;
151
+ /**
152
+ * Replaces the one Windows DACL read of the code this run launches.
153
+ * When set, that check runs even if `spawn` is also set, so a test can
154
+ * read the refusal's fix line without starting a child.
155
+ */
156
+ windowsCodeAcl?: (paths: readonly string[]) => Map<string, {
157
+ sddl: string | null;
158
+ }>;
149
159
  /** Replaces `killTree` for the children this run started. */
150
160
  kill?: (pid: number | undefined) => void;
151
161
  /** Called with the capped stdout/stderr kept for one child. */
@@ -153,6 +163,11 @@ export type DesktopHooks = {
153
163
  /** Replaces `process` for stop handlers. Production uses this process. */
154
164
  signals?: DesktopSignalHost;
155
165
  };
166
+ /**
167
+ * Built-in Administrator (`LA`) and Guest (`LG`) via the SID constructor.
168
+ * The constructor lives in the runtime, so this command loads no module.
169
+ */
170
+ export declare const LOCAL_ACCOUNT_SIDS_COMMAND = "[Security.Principal.SecurityIdentifier]::new('LA').Value; [Security.Principal.SecurityIdentifier]::new('LG').Value";
156
171
  /**
157
172
  * The account SIDs in place of the `LA` / `LG` aliases, so the built-in
158
173
  * Administrator's own entry compares equal to its SID (a GitHub Windows
@@ -180,5 +195,32 @@ export declare function issuerEnv(base: NodeJS.ProcessEnv, opts: {
180
195
  issuerPort: number;
181
196
  panelPort: number;
182
197
  }, audience: string, issuerUrl: string): NodeJS.ProcessEnv;
198
+ /**
199
+ * The approval ceremony runs on the panel page, so the body names that
200
+ * origin. An operator who already set either value keeps it. This does not
201
+ * touch the issuer: `/authorize` and `/enroll` still use `issuerEnv`.
202
+ */
203
+ export declare function bodyRpEnv(base: NodeJS.ProcessEnv, panelOrigin: string): NodeJS.ProcessEnv;
204
+ /**
205
+ * Environment handed to a desktop child. Bootstrap and preload variables are
206
+ * removed. Other `VERAX_*` names are left as given. `NO_COLOR` and `FORCE_COLOR`
207
+ * stay forced off, as they were before this filter.
208
+ */
209
+ export declare function desktopChildEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
210
+ /**
211
+ * First launched script, parent, ancestor, or module directory that someone
212
+ * else can replace. Null when every target is held tightly enough to run.
213
+ * `detail` is the second line of the refusal. On Windows one `read` (or
214
+ * `readWindowsAcls`) judges the whole list with `svcSid`: someone other than
215
+ * the operator, Administrators, or SYSTEM. On POSIX the owner is trusted
216
+ * when it is the operator or root, then `posixOthersCanReplace`, then one
217
+ * `posixAclWriters` read of the whole list.
218
+ */
219
+ export declare function desktopCodeRefusal(paths: readonly string[], platform: NodeJS.Platform, read?: (p: readonly string[]) => Map<string, {
220
+ sddl: string | null;
221
+ }>, invoking?: string): {
222
+ path: string;
223
+ detail: string;
224
+ } | null;
183
225
  export declare function runDesktop(opts: DesktopOpts, writeErr?: (s: string) => void, hooks?: DesktopHooks): Promise<number>;
184
226
  export declare function desktopMain(argv: string[]): Promise<number>;