@verax-ai/body 0.4.1 → 0.4.2

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,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,281 @@
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
+ const approverByAllow = new Map();
190
+ for (const piece of listPieceFiles(stateDir)) {
191
+ for (const line of readLines(piece.decisions)) {
192
+ try {
193
+ decisions.push(JSON.parse(line));
194
+ }
195
+ catch {
196
+ // A line that does not parse is the ledger statement's problem.
197
+ }
198
+ }
199
+ for (const line of readLines(piece.inputs)) {
200
+ try {
201
+ const row = JSON.parse(line);
202
+ if (typeof row.ref !== "string" || !row.inputs?.approver)
203
+ continue;
204
+ approverByAllow.set(row.ref, row.inputs.approver);
205
+ }
206
+ catch {
207
+ // Same as a decision line: skip, do not invent a failure from a torn line.
208
+ }
209
+ }
210
+ }
211
+ let signedVerified = 0;
212
+ let signedFailed = 0;
213
+ let unsignedHttp = 0;
214
+ let cli = 0;
215
+ let other = 0;
216
+ const origins = [];
217
+ // A defer resolves once. A second signed allow for the same defer reuses an
218
+ // operator signature the operator gave for one approval.
219
+ const signedDefers = new Set();
220
+ for (const row of decisions) {
221
+ // A parsed line that is not a decision record is the ledger statement's problem, not a crash here.
222
+ if (!row || typeof row !== "object" || !row.claims || typeof row.claims !== "object")
223
+ continue;
224
+ if (row.claims.decision !== "allow" || typeof row.claims.ref !== "string")
225
+ continue;
226
+ const approver = approverByAllow.get(row.claims.ref);
227
+ if (!approver)
228
+ continue;
229
+ if (approver.signature === undefined) {
230
+ if (approver.via === "http")
231
+ unsignedHttp += 1;
232
+ else if (approver.via === "cli" || approver.via === "cli-script")
233
+ cli += 1;
234
+ else
235
+ other += 1;
236
+ continue;
237
+ }
238
+ const seen = originOnSignature(approver.signature);
239
+ if (seen && !origins.includes(seen))
240
+ origins.push(seen);
241
+ const sig = signatureOf(approver.signature);
242
+ const cred = sig ? credentials.find((c) => c.id === sig.credentialId && c.sub === sig.sub) : undefined;
243
+ const defer = sig && typeof approver.resolves === "string"
244
+ ? decisions.find((d) => d?.claims?.ref === approver.resolves && d.claims.decision === "defer")
245
+ : undefined;
246
+ let recordHash = null;
247
+ if (defer) {
248
+ try {
249
+ recordHash = decisionRecordHash(defer);
250
+ }
251
+ catch {
252
+ recordHash = null;
253
+ }
254
+ }
255
+ // The signature covers the defer; the allow must be for that same request,
256
+ // or a body holding one genuine signature could attach it to another allow.
257
+ const sameRequest = defer !== undefined && row.claims.requestHash === defer.claims.requestHash;
258
+ const firstUse = recordHash !== null && !signedDefers.has(recordHash);
259
+ if (recordHash !== null)
260
+ signedDefers.add(recordHash);
261
+ const challenge = sig && defer && sameRequest && firstUse && recordHash && recordHash === sig.deferRecordHash && typeof defer.claims.requestHash === "string"
262
+ ? approvalChallenge({ ref: approver.resolves, requestHash: defer.claims.requestHash, deferRecordHash: recordHash })
263
+ : null;
264
+ if (sig && cred && challenge && assertionMatches(sig, cred.publicKey, challenge))
265
+ signedVerified += 1;
266
+ else
267
+ signedFailed += 1;
268
+ }
269
+ const originSuffix = origins.length === 0 ? "" : ` · origin ${origins.join(", ")}`;
270
+ const report = {
271
+ ok: signedFailed === 0,
272
+ signedVerified,
273
+ signedFailed,
274
+ unsignedHttp,
275
+ cli,
276
+ line: `approval signatures signed-verified ${signedVerified} · signed-failed ${signedFailed} · unsigned-http ${unsignedHttp} · cli ${cli}${other > 0 ? ` · other ${other}` : ""}${originSuffix}`,
277
+ trustSource: trust.trustSource,
278
+ trustNote: trust.trustNote,
279
+ };
280
+ return report;
281
+ }
package/dist/cli.js CHANGED
@@ -48,7 +48,7 @@ Usage: verax <command> [options]
48
48
  operator <args> enrol an operator and manage their passkeys
49
49
  reconcile <args> compare the ledger against a statement
50
50
  verify <stateDir> read a ledger back without a body: signatures, chain,
51
- effect binding, and which key answered
51
+ effect binding, which key answered, and approval signatures
52
52
  witness <stateDir> run the witness alongside a body
53
53
  halt <stateDir> stop the body from allowing anything further
54
54
  resume <stateDir> lift a halt; who and when go to halt-history.jsonl
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>;