@verax-ai/proxy 0.4.2 → 0.4.4

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,24 @@
1
+ export declare const ANCHORS_NAME = "checkpoint-anchors.jsonl";
2
+ /** `register`: the SCITT digest route; the log's leaf entry is SHA-256 of the 32 checkpoint-hash octets. */
3
+ export type AnchorRoute = "register";
4
+ export type AnchorRow = {
5
+ v: 1;
6
+ checkpointHash: string;
7
+ service: string;
8
+ route: AnchorRoute;
9
+ entryHash: string;
10
+ leafIndex: number;
11
+ treeSize: number;
12
+ receiptB64: string;
13
+ atMs: number;
14
+ };
15
+ export declare function anchorsPath(dir: string): string;
16
+ /** The leaf entry the service's log holds for this checkpoint under `route`. */
17
+ export declare function anchorEntryHash(checkpointHash: string, route: AnchorRoute): string;
18
+ /** Rows in file order. A line that is not a row is named, not skipped silently. */
19
+ export declare function readAnchors(dir: string): {
20
+ present: boolean;
21
+ rows: AnchorRow[];
22
+ problems: string[];
23
+ };
24
+ export declare function appendAnchor(dir: string, row: AnchorRow): void;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Checkpoints registered with a Transparency Service run by someone else.
3
+ *
4
+ * `verax anchor` sends a service the SHA-256 of a checkpoint's COSE octets
5
+ * (the checkpoint hash core-03 defines) and nothing else: the window, the
6
+ * counts and the head stay on this machine. The service appends that digest to
7
+ * its RFC 9162 log and returns a COSE Receipt, which is kept here, one row per
8
+ * checkpoint and service, so `verax verify` can check it later with no network.
9
+ *
10
+ * What a verified receipt adds is a second party: the service's log held this
11
+ * checkpoint at the tree size in the receipt, under the service's key. A
12
+ * receipt does not show the service agrees with anything the checkpoint
13
+ * counts, and a reader who has only these files cannot tell whether a newer
14
+ * checkpoint was registered and then removed from them; asking the service is
15
+ * the check for that.
16
+ */
17
+ import { createHash } from "node:crypto";
18
+ import { appendFileSync, existsSync, lstatSync, readFileSync } from "node:fs";
19
+ import { join } from "node:path";
20
+ export const ANCHORS_NAME = "checkpoint-anchors.jsonl";
21
+ const HASH = /^[0-9a-f]{64}$/;
22
+ export function anchorsPath(dir) {
23
+ return join(dir, ANCHORS_NAME);
24
+ }
25
+ /** The leaf entry the service's log holds for this checkpoint under `route`. */
26
+ export function anchorEntryHash(checkpointHash, route) {
27
+ if (!HASH.test(checkpointHash))
28
+ throw new Error("anchor-checkpoint-hash");
29
+ if (route === "register")
30
+ return createHash("sha256").update(Buffer.from(checkpointHash, "hex")).digest("hex");
31
+ throw new Error(`anchor-route-${String(route)}`);
32
+ }
33
+ function asRow(value) {
34
+ if (!value || typeof value !== "object" || Array.isArray(value))
35
+ return null;
36
+ const r = value;
37
+ if (r.v !== 1 || r.route !== "register")
38
+ return null;
39
+ if (typeof r.checkpointHash !== "string" || !HASH.test(r.checkpointHash))
40
+ return null;
41
+ if (typeof r.entryHash !== "string" || !HASH.test(r.entryHash))
42
+ return null;
43
+ if (typeof r.service !== "string" || r.service === "")
44
+ return null;
45
+ if (typeof r.receiptB64 !== "string" || r.receiptB64 === "")
46
+ return null;
47
+ if (!Number.isSafeInteger(r.leafIndex) || !Number.isSafeInteger(r.treeSize))
48
+ return null;
49
+ if (typeof r.atMs !== "number")
50
+ return null;
51
+ return r;
52
+ }
53
+ /** Rows in file order. A line that is not a row is named, not skipped silently. */
54
+ export function readAnchors(dir) {
55
+ const path = anchorsPath(dir);
56
+ if (!existsSync(path))
57
+ return { present: false, rows: [], problems: [] };
58
+ if (lstatSync(path).isSymbolicLink())
59
+ return { present: true, rows: [], problems: [`symbolic link: ${path}`] };
60
+ const rows = [];
61
+ const problems = [];
62
+ const lines = readFileSync(path, "utf8").split("\n");
63
+ for (let i = 0; i < lines.length; i += 1) {
64
+ const line = lines[i].trim();
65
+ if (line === "")
66
+ continue;
67
+ let parsed;
68
+ try {
69
+ parsed = JSON.parse(line);
70
+ }
71
+ catch {
72
+ problems.push(`anchor line ${i + 1} is not JSON`);
73
+ continue;
74
+ }
75
+ const row = asRow(parsed);
76
+ if (!row) {
77
+ problems.push(`anchor line ${i + 1} is not an anchor row`);
78
+ continue;
79
+ }
80
+ rows.push(row);
81
+ }
82
+ return { present: true, rows, problems };
83
+ }
84
+ export function appendAnchor(dir, row) {
85
+ appendFileSync(anchorsPath(dir), `${JSON.stringify(row)}\n`, { encoding: "utf8" });
86
+ }
@@ -23,6 +23,8 @@ import { sha256Canonical } from "./hash.js";
23
23
  const HALT_SWITCH = "halted";
24
24
  const HALT_HISTORY = "halt-history.jsonl";
25
25
  const CONTROL_EFFECT = "verax.control";
26
+ /** A signature larger than this is not an assertion; the line is copied without it. */
27
+ const MAX_SIGNATURE_JSON = 8192;
26
28
  export function createControlMemory() {
27
29
  return {
28
30
  loaded: false,
@@ -212,7 +214,18 @@ function parseHistoryLine(raw, line) {
212
214
  if (typeof row.by !== "string" || row.by.length === 0 || row.by.length > 256)
213
215
  return null;
214
216
  const via = row.via === "http" ? "http" : row.via === "file" ? "file" : "cli";
215
- return { action: row.action, atMs: row.atMs, by: row.by, via, line };
217
+ const parsed = { action: row.action, atMs: row.atMs, by: row.by, via, line };
218
+ // The signature is copied as the line carries it, not judged here: a body
219
+ // that dropped a bad one would turn a forged line into a quiet unsigned one.
220
+ // `verax verify` decides whether it holds.
221
+ const signature = row.signature;
222
+ if (signature !== null &&
223
+ typeof signature === "object" &&
224
+ !Array.isArray(signature) &&
225
+ JSON.stringify(signature).length <= MAX_SIGNATURE_JSON) {
226
+ parsed.signature = signature;
227
+ }
228
+ return parsed;
216
229
  }
217
230
  function lastAction(lines) {
218
231
  for (let i = lines.length - 1; i >= 0; i -= 1) {
@@ -315,6 +328,7 @@ async function writeControlAllow(opts, event, lineHash) {
315
328
  by: event.by,
316
329
  via: event.via,
317
330
  line: event.line,
331
+ ...(event.signature ? { signature: event.signature } : {}),
318
332
  };
319
333
  const bound = sha256Canonical(body);
320
334
  const ref = await writeDecision(opts, {
package/dist/explain.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import type { ExplainOpts, ExplainResult, Ledger } from "./types.ts";
2
+ export declare function balancedSummary(guarantee: "unconditional" | "conditional", conditions: readonly string[], cedulonSummary: string): string;
3
+ /** Local deployment conditions can only narrow the audit's guarantee. */
4
+ export declare function guaranteeWithConditions(guarantee: ExplainResult["guarantee"], conditions: readonly string[]): ExplainResult["guarantee"];
2
5
  /**
3
6
  * Re-runs the Cedulon decision profile on the whole ledger. Finding codes
4
7
  * are Cedulon's; this wrapper does not invent names. With no durable
package/dist/explain.js CHANGED
@@ -5,6 +5,7 @@ import { sha256Canonical } from "./hash.js";
5
5
  import { inputsLogFor } from "./inputs.js";
6
6
  import { lookupResolvedBy } from "./ledger.js";
7
7
  import { loadCheckpoints } from "./checkpoints.js";
8
+ import { samePublicKey, thirdPartyReceiptCoversRow } from "./third-party.js";
8
9
  async function pairFor(ledger, decisions, record, inputsLog, approvals) {
9
10
  const ref = record.claims.ref;
10
11
  if (!ref)
@@ -53,21 +54,32 @@ function conditionName(f, extractPresented) {
53
54
  // Name from whether an extract was handed to audit, not Cedulon detail text.
54
55
  return extractPresented ? "extract unpinned" : "extract unsigned";
55
56
  }
57
+ // A one-row extract does not state the period or the path it covers, so it cannot show completeness.
58
+ if (f.code === "unstated-audit-window")
59
+ return "audit window unstated";
60
+ if (f.code === "unstated-audit-scope")
61
+ return "audit scope unstated";
56
62
  return null;
57
63
  }
58
- function balancedSummary(guarantee, conditions, cedulonSummary) {
64
+ export function balancedSummary(guarantee, conditions, cedulonSummary) {
59
65
  if (conditions.length > 0) {
60
- return `audit: balanced (${guarantee}: ${conditions.join("; ")})`;
66
+ return `audit: balanced (conditional: ${conditions.join("; ")})`;
61
67
  }
62
68
  if (guarantee === "unconditional") {
63
69
  return "audit: balanced (unconditional)";
64
70
  }
71
+ // Cedulon's summary counts findings this wrapper may have dropped (window-coverage with no checkpoint),
72
+ // so a failing summary is never echoed inside a balanced one.
65
73
  const why = cedulonSummary.replace(/^audit:\s*/i, "").trim();
66
- if (why !== "" && why !== "balanced" && why !== "conditional") {
74
+ if (why !== "" && why !== "balanced" && why !== "conditional" && !/FAIL|finding\(s\)/.test(why)) {
67
75
  return `audit: balanced (${guarantee}: ${why})`;
68
76
  }
69
77
  return `audit: balanced (${guarantee})`;
70
78
  }
79
+ /** Local deployment conditions can only narrow the audit's guarantee. */
80
+ export function guaranteeWithConditions(guarantee, conditions) {
81
+ return conditions.length > 0 ? "conditional" : guarantee;
82
+ }
71
83
  /**
72
84
  * Re-runs the Cedulon decision profile on the whole ledger. Finding codes
73
85
  * are Cedulon's; this wrapper does not invent names. With no durable
@@ -93,6 +105,13 @@ export async function explain(ledger, ref, opts) {
93
105
  const issuerTrust = resolvedTrust.pin;
94
106
  const pinSource = resolvedTrust.source;
95
107
  const pinned = issuerTrust !== undefined;
108
+ const thirdPartyTrust = opts?.thirdPartyTrust;
109
+ const thirdPartyVerified = effect?.witnessClass === "third-party" && thirdPartyTrust !== undefined &&
110
+ thirdPartyReceiptCoversRow(effect.receipt, effect.row, thirdPartyTrust.publicKeyPem);
111
+ const issuerKeys = issuerTrust ? (typeof issuerTrust.publicKeyPem === "string"
112
+ ? [issuerTrust.publicKeyPem] : issuerTrust.publicKeyPem) : [];
113
+ const sameParty = thirdPartyTrust !== undefined && [record.publicKeyPem, ...issuerKeys]
114
+ .some(key => samePublicKey(thirdPartyTrust.publicKeyPem, key));
96
115
  const dir = ledger.dir;
97
116
  const checkpoints = typeof dir === "string" ? loadCheckpoints(dir) : [];
98
117
  const report = audit({
@@ -102,6 +121,9 @@ export async function explain(ledger, ref, opts) {
102
121
  profile: DECISION_PROFILE,
103
122
  ...(issuerTrust ? { issuerTrust } : {}),
104
123
  ...(presentedExtract ? { extract: presentedExtract } : {}),
124
+ // On DECISION_PROFILE RailTrustPin pins the effect-extract signer.
125
+ ...(thirdPartyVerified && presentedExtract === effect?.receipt
126
+ ? { trust: { publicKeyPem: thirdPartyTrust.publicKeyPem } } : {}),
105
127
  });
106
128
  const dropWindow = checkpoints.length === 0;
107
129
  const dropped = dropWindow
@@ -135,6 +157,18 @@ export async function explain(ledger, ref, opts) {
135
157
  const conditions = [];
136
158
  if (self)
137
159
  conditions.push("self witness");
160
+ if (witnessClass === "same-org")
161
+ conditions.push("same-party witness");
162
+ if (witnessClass === "third-party") {
163
+ if (!thirdPartyTrust)
164
+ conditions.push("third-party witness unpinned");
165
+ else if (sameParty)
166
+ conditions.push("same-party witness");
167
+ else if (thirdPartyTrust.independent !== true || typeof thirdPartyTrust.party !== "string" || !thirdPartyTrust.party.trim())
168
+ conditions.push("witness independence unstated");
169
+ else if (!thirdPartyVerified)
170
+ conditions.push("third-party witness unpinned");
171
+ }
138
172
  if (pinSource === "own-key")
139
173
  conditions.push("issuer pinned to own key");
140
174
  for (const w of applicableWarnings) {
@@ -173,10 +207,10 @@ export async function explain(ledger, ref, opts) {
173
207
  (issuerMismatch && pinned ? 1 : 0) +
174
208
  (inputsMismatch ? 1 : 0) +
175
209
  (inputsMissing ? 1 : 0);
176
- const guarantee = report.guarantee;
210
+ const guarantee = guaranteeWithConditions(report.guarantee, conditions);
177
211
  const summary = balanced
178
212
  ? balancedSummary(guarantee, conditions, report.summary)
179
- : `audit: ${Math.max(findingCount, 1)} finding(s) → FAIL`;
213
+ : `audit: ${Math.max(findingCount, 1)} finding(s) → FAIL${witnessClass === "third-party" && conditions.length > 0 ? ` (conditional: ${conditions.join("; ")})` : ""}`;
180
214
  const warnings = applicableWarnings.filter((f) => f.id === "issuer" || f.id === "extract").map(asWarning);
181
215
  if (inputsMissing) {
182
216
  warnings.push({
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { createProxy, LedgerDenyUnrecorded } from "./proxy.ts";
2
+ export { effectDescriptor, sha256Canonical } from "./hash.ts";
3
+ export { samePublicKey, thirdPartyReceiptRejection } from "./third-party.ts";
2
4
  export { loadPolicy, TERMINAL_CONTROL_CLASS } from "./policy.ts";
3
5
  export { FileLedger, MemoryLedger, readLedgerTail } from "./ledger.ts";
4
6
  export { indexCoverage, listPieceFiles } from "./ledger-manifest.ts";
@@ -7,13 +9,17 @@ export { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueAppr
7
9
  export { loadDecisionRefsFromDir, loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile } from "./reconcile.ts";
8
10
  export { tenantKey } from "./tenant.ts";
9
11
  export { diskProbe } from "./disk.ts";
10
- export { checkpointsPath } from "./checkpoints.ts";
12
+ export { checkpointsPath, readCheckpointFile } from "./checkpoints.ts";
11
13
  export { signEffectAttestation } from "./ledger.ts";
12
14
  export { spokenReason } from "./spoken-reason.ts";
13
15
  export type { ApprovalRow, ApproveResult } from "./approvals.ts";
14
16
  export type { CardCsvOpts, ChannelRow, ReconcileReport } from "./reconcile.ts";
15
17
  export type { FileLedgerOpts, LedgerCounts } from "./ledger.ts";
16
- export type { ApprovalSignature } from "./types.ts";
18
+ export type { ApprovalSignature, ControlSignature, RevokeInput } from "./types.ts";
17
19
  export type { EffectSigner, ExplainChain, ExplainPair, ExplainFinding, ExplainOpts, ExplainResult, ExplainTrustRoot, ExplainWarning, ExtractWindow, Ledger, LedgerEffect, Policy, PolicyDecision, Principal, ProxyDeps, RecordSigner, ToolCall, ToolResult, WitnessClass, } from "./types.ts";
18
20
  export { verifyLedger } from "./verify-ledger.ts";
19
- export type { VerifyResult, VerifyOptions, VerifyTrust, VerifyControl } from "./verify-ledger.ts";
21
+ export type { VerifyResult, VerifyOptions, VerifyTrust, VerifyControl, VerifyInputs, VerifyAnchors, } from "./verify-ledger.ts";
22
+ export { anchorEntryHash, appendAnchor, readAnchors } from "./anchors.ts";
23
+ export type { AnchorRoute, AnchorRow } from "./anchors.ts";
24
+ export { verifyReceipt } from "./transparency-receipt.ts";
25
+ export type { ReceiptCheck, ReceiptStage } from "./transparency-receipt.ts";
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export { createProxy, LedgerDenyUnrecorded } from "./proxy.js";
2
+ export { effectDescriptor, sha256Canonical } from "./hash.js";
3
+ export { samePublicKey, thirdPartyReceiptRejection } from "./third-party.js";
2
4
  export { loadPolicy, TERMINAL_CONTROL_CLASS } from "./policy.js";
3
5
  export { FileLedger, MemoryLedger, readLedgerTail } from "./ledger.js";
4
6
  export { indexCoverage, listPieceFiles } from "./ledger-manifest.js";
@@ -13,7 +15,9 @@ export { tenantKey } from "./tenant.js";
13
15
  // through this package must be able to inject a full disk into the very
14
16
  // instance the proxy uses. Deep imports are not in the exports map.
15
17
  export { diskProbe } from "./disk.js";
16
- export { checkpointsPath } from "./checkpoints.js";
18
+ export { checkpointsPath, readCheckpointFile } from "./checkpoints.js";
17
19
  export { signEffectAttestation } from "./ledger.js";
18
20
  export { spokenReason } from "./spoken-reason.js";
19
21
  export { verifyLedger } from "./verify-ledger.js";
22
+ export { anchorEntryHash, appendAnchor, readAnchors } from "./anchors.js";
23
+ export { verifyReceipt } from "./transparency-receipt.js";
package/dist/ledger.d.ts CHANGED
@@ -14,7 +14,7 @@ export type PermissionCheck = "owner-only" | "not checked on this platform";
14
14
  /** Appends that already hold the ledger queue. Calling the public methods from here deadlocks. */
15
15
  export type LedgerWriter = {
16
16
  appendDecisionChained(build: (prevRecordHash: string | null) => SignedDecisionRecord): Promise<void>;
17
- appendEffect(row: EffectRow, witnessClass: WitnessClass, resultHash?: string): Promise<void>;
17
+ appendEffect(row: EffectRow, witnessClass: WitnessClass, resultHash?: string, externalReceipt?: SignedEffectExtract): Promise<void>;
18
18
  };
19
19
  /**
20
20
  * A ledger file read from its end through the same seam the reads above use,
@@ -71,7 +71,7 @@ export declare class MemoryLedger implements Ledger {
71
71
  private appendDecisionChainedUnlocked;
72
72
  /** One turn of this ledger's queue: read a cursor and append without a second writer seeing the same cursor. */
73
73
  exclusive<T>(fn: (writer: LedgerWriter) => Promise<T>): Promise<T>;
74
- appendEffect(row: EffectRow, witnessClass?: WitnessClass, resultHash?: string): Promise<void>;
74
+ appendEffect(row: EffectRow, witnessClass?: WitnessClass, resultHash?: string, externalReceipt?: SignedEffectExtract): Promise<void>;
75
75
  private appendEffectUnlocked;
76
76
  decisions(): Promise<SignedDecisionRecord[]>;
77
77
  effects(): Promise<LedgerEffect[]>;
@@ -195,7 +195,7 @@ export declare class FileLedger implements Ledger {
195
195
  }>;
196
196
  /** Effects stamped in [fromMs, toMs), read from the end of each overlapping piece. */
197
197
  effectsWindow(fromMs: number, toMs: number): Promise<LedgerEffect[]>;
198
- appendEffect(row: EffectRow, witnessClass?: WitnessClass, resultHash?: string): Promise<void>;
198
+ appendEffect(row: EffectRow, witnessClass?: WitnessClass, resultHash?: string, externalReceipt?: SignedEffectExtract): Promise<void>;
199
199
  private appendEffectUnlocked;
200
200
  decisions(): Promise<SignedDecisionRecord[]>;
201
201
  effects(): Promise<LedgerEffect[]>;
package/dist/ledger.js CHANGED
@@ -153,7 +153,12 @@ function asEffectRow(row) {
153
153
  ...(row.actor !== undefined ? { actor: row.actor } : {}),
154
154
  };
155
155
  }
156
- function asStoredEffect(row, witnessClass, resultHash, signer) {
156
+ function asStoredEffect(row, witnessClass, resultHash, signer, externalReceipt) {
157
+ if (witnessClass === "third-party") {
158
+ // The downstream signed only the extract: resultHash is stored but unattested.
159
+ return { row: structuredClone(row), witnessClass, ...(externalReceipt ? { receipt: externalReceipt } : {}),
160
+ ...(resultHash !== undefined ? { resultHash } : {}) };
161
+ }
157
162
  const stored = {
158
163
  row: asEffectRow(row),
159
164
  witnessClass,
@@ -259,13 +264,13 @@ export class MemoryLedger {
259
264
  async exclusive(fn) {
260
265
  return this.q.enqueue(() => fn({
261
266
  appendDecisionChained: (build) => this.appendDecisionChainedUnlocked(build),
262
- appendEffect: (row, witnessClass, resultHash) => this.appendEffectUnlocked(row, witnessClass, resultHash),
267
+ appendEffect: (row, witnessClass, resultHash, externalReceipt) => this.appendEffectUnlocked(row, witnessClass, resultHash, externalReceipt),
263
268
  }));
264
269
  }
265
- async appendEffect(row, witnessClass = DEFAULT_WITNESS, resultHash) {
266
- return this.q.enqueue(async () => this.appendEffectUnlocked(row, witnessClass, resultHash));
270
+ async appendEffect(row, witnessClass = DEFAULT_WITNESS, resultHash, externalReceipt) {
271
+ return this.q.enqueue(async () => this.appendEffectUnlocked(row, witnessClass, resultHash, externalReceipt));
267
272
  }
268
- async appendEffectUnlocked(row, witnessClass, resultHash) {
273
+ async appendEffectUnlocked(row, witnessClass, resultHash, externalReceipt) {
269
274
  const existing = this._effects.find((e) => e.row.ref === row.ref && e.row.effectClass !== "duplicate-effect");
270
275
  if (existing && row.effectClass !== "duplicate-effect") {
271
276
  this._effects.push(asStoredEffect({
@@ -277,7 +282,7 @@ export class MemoryLedger {
277
282
  }, DEFAULT_WITNESS, resultHash, this.effectSigner));
278
283
  throw new Error(`duplicate-effect:${row.ref}`);
279
284
  }
280
- this._effects.push(asStoredEffect(row, witnessClass, resultHash, this.effectSigner));
285
+ this._effects.push(asStoredEffect(row, witnessClass, resultHash, this.effectSigner, externalReceipt));
281
286
  }
282
287
  async decisions() {
283
288
  return [...this._decisions];
@@ -835,7 +840,7 @@ export class FileLedger {
835
840
  async exclusive(fn) {
836
841
  return this.q.enqueue(() => fn({
837
842
  appendDecisionChained: (build) => this.appendDecisionChainedUnlocked(build),
838
- appendEffect: (row, witnessClass, resultHash) => this.appendEffectUnlocked(row, witnessClass, resultHash),
843
+ appendEffect: (row, witnessClass, resultHash, externalReceipt) => this.appendEffectUnlocked(row, witnessClass, resultHash, externalReceipt),
839
844
  }));
840
845
  }
841
846
  /**
@@ -929,13 +934,13 @@ export class FileLedger {
929
934
  }
930
935
  return collected;
931
936
  }
932
- async appendEffect(row, witnessClass = DEFAULT_WITNESS, resultHash) {
937
+ async appendEffect(row, witnessClass = DEFAULT_WITNESS, resultHash, externalReceipt) {
933
938
  return this.q.enqueue(async () => {
934
939
  this.assertOwned();
935
- return this.appendEffectUnlocked(row, witnessClass, resultHash);
940
+ return this.appendEffectUnlocked(row, witnessClass, resultHash, externalReceipt);
936
941
  });
937
942
  }
938
- async appendEffectUnlocked(row, witnessClass = DEFAULT_WITNESS, resultHash) {
943
+ async appendEffectUnlocked(row, witnessClass = DEFAULT_WITNESS, resultHash, externalReceipt) {
939
944
  this.assertOwned();
940
945
  if (row.effectClass !== "duplicate-effect" && this.effectRefs.has(row.ref)) {
941
946
  const dup = lineOf(asStoredEffect({
@@ -950,7 +955,7 @@ export class FileLedger {
950
955
  this.activeEffectN += 1;
951
956
  throw new Error(`duplicate-effect:${row.ref}`);
952
957
  }
953
- const line = lineOf(await this.storeEffect(row, witnessClass, resultHash));
958
+ const line = lineOf(await this.storeEffect(row, witnessClass, resultHash, externalReceipt));
954
959
  await appendDurable(this.effectsPath, line);
955
960
  await this.pulse("effects.jsonl", line, "effect");
956
961
  this.activeEffectN += 1;
@@ -1020,7 +1025,10 @@ export class FileLedger {
1020
1025
  lastEffectN: this.effectCount,
1021
1026
  })}\n`, { encoding: "utf8", mode: 0o600 });
1022
1027
  }
1023
- async storeEffect(row, witnessClass, resultHash) {
1028
+ async storeEffect(row, witnessClass, resultHash, externalReceipt) {
1029
+ // Never ask the body or its same-org witness to sign an external receipt.
1030
+ if (witnessClass === "third-party")
1031
+ return asStoredEffect(row, witnessClass, resultHash, undefined, externalReceipt);
1024
1032
  if (this.remoteWitness && row.effectClass !== "duplicate-effect") {
1025
1033
  const remote = await this.remoteWitness(row, resultHash);
1026
1034
  if (remote?.attestation && remote.receipt && remote.witnessClass && remote.witnessClass !== "self") {
package/dist/proxy.js CHANGED
@@ -8,6 +8,7 @@ import { markEnded, markStarted, startedWithoutEnd } from "./in-flight-log.js";
8
8
  import { effectDescriptor, sha256Canonical } from "./hash.js";
9
9
  import { inputsLogFor } from "./inputs.js";
10
10
  import { controlUnchanged, createControlMemory, syncHaltControl } from "./control-sync.js";
11
+ import { createRevokeMemory, revokeUnchanged, syncRevokeControl } from "./revoke-sync.js";
11
12
  import { countedWork, hasPrimaryEffect, lookupDecisionByRef, lookupReauthByHash, lookupResolvedBy, noteResolution, noteTenantRef, } from "./ledger.js";
12
13
  import { spokenReason } from "./spoken-reason.js";
13
14
  import { tenantKey } from "./tenant.js";
@@ -193,6 +194,7 @@ export function createProxy(deps) {
193
194
  // Single writer: after open, the ledger lock is this process. The first
194
195
  // sync reads control records once; this snapshot is updated in place.
195
196
  const controlMemory = createControlMemory();
197
+ const revokeMemory = createRevokeMemory();
196
198
  let controlSyncReported = false;
197
199
  if (stateDir === null) {
198
200
  process.stderr.write("verax-proxy: halt and disk limits are inactive without a ledger directory\n");
@@ -308,8 +310,15 @@ export function createProxy(deps) {
308
310
  timestampMs: deps.now(),
309
311
  actor: principal.brain,
310
312
  };
313
+ const { effectReceipt, ...normalResult } = result;
314
+ const signedRow = effectReceipt?.body?.effects?.[0];
315
+ const external = effectReceipt?.body?.effects?.length === 1 && signedRow?.ref === ref &&
316
+ signedRow.effectHash === dispatchedHash && signedRow.effectClass === dispatchedName;
311
317
  try {
312
- await deps.ledger.appendEffect(row, "self", sha256Canonical(result));
318
+ if (external)
319
+ await deps.ledger.appendEffect(signedRow, "third-party", sha256Canonical(normalResult), effectReceipt);
320
+ else
321
+ await deps.ledger.appendEffect(row, "self", sha256Canonical(normalResult));
313
322
  effectRecorded.ok = true;
314
323
  }
315
324
  catch {
@@ -318,7 +327,7 @@ export function createProxy(deps) {
318
327
  // stays false) and a restart answers outcome-unknown instead of running again.
319
328
  return effectUnrecorded(ref);
320
329
  }
321
- return result;
330
+ return normalResult;
322
331
  }
323
332
  async function resolveInputs(call, principal, timestampMs) {
324
333
  const declared = declaredInputs(call.arguments);
@@ -439,20 +448,30 @@ export function createProxy(deps) {
439
448
  async function syncControlRecords() {
440
449
  if (stateDir === null)
441
450
  return;
451
+ // A revocation list that cannot be read must not throw away the halt
452
+ // snapshot too, or every call would read the whole ledger again.
453
+ let haltSynced = false;
442
454
  try {
443
- if (controlUnchanged(stateDir, controlMemory))
455
+ if (controlUnchanged(stateDir, controlMemory) && revokeUnchanged(stateDir, revokeMemory))
444
456
  return;
445
- const run = (writer) => syncHaltControl({
446
- stateDir,
447
- now: deps.now,
448
- nonce: deps.nonce,
449
- policyHash: deps.policy.hash,
450
- recordSigner: deps.recordSigner,
451
- inputsLog,
452
- decisions: () => deps.ledger.decisions(),
453
- memory: controlMemory,
454
- writer,
455
- });
457
+ const run = async (writer) => {
458
+ // Both snapshots load from one read. The halt sync writes only halt
459
+ // and resume records, which the revoke replay does not read.
460
+ let read = null;
461
+ const shared = {
462
+ stateDir,
463
+ now: deps.now,
464
+ nonce: deps.nonce,
465
+ policyHash: deps.policy.hash,
466
+ recordSigner: deps.recordSigner,
467
+ inputsLog,
468
+ decisions: () => (read ??= deps.ledger.decisions()),
469
+ writer,
470
+ };
471
+ await syncHaltControl({ ...shared, memory: controlMemory });
472
+ haltSynced = true;
473
+ await syncRevokeControl({ ...shared, memory: revokeMemory });
474
+ };
456
475
  const host = deps.ledger;
457
476
  if (typeof host.exclusive === "function") {
458
477
  await host.exclusive((writer) => run(writer));
@@ -460,7 +479,7 @@ export function createProxy(deps) {
460
479
  else {
461
480
  await controlQueue.enqueue(() => run({
462
481
  appendDecisionChained: (build) => deps.ledger.appendDecisionChained(build),
463
- appendEffect: (row, witnessClass, resultHash) => deps.ledger.appendEffect(row, witnessClass, resultHash),
482
+ appendEffect: (row, witnessClass, resultHash, externalReceipt) => deps.ledger.appendEffect(row, witnessClass, resultHash, externalReceipt),
464
483
  }));
465
484
  }
466
485
  controlSyncReported = false;
@@ -470,7 +489,9 @@ export function createProxy(deps) {
470
489
  // unloaded so the next call reads again, and keep going: the halt switch
471
490
  // and the rate limit still fail closed on their own path. One line per
472
491
  // failure streak, so the admission retry in the same call does not repeat it.
473
- controlMemory.loaded = false;
492
+ if (!haltSynced)
493
+ controlMemory.loaded = false;
494
+ revokeMemory.loaded = false;
474
495
  if (controlSyncReported)
475
496
  return;
476
497
  controlSyncReported = true;
@@ -0,0 +1,26 @@
1
+ import type { SignedDecisionRecord } from "@cedulon/core";
2
+ import type { LedgerWriter } from "./ledger.ts";
3
+ import type { InputsLog, RecordSigner } from "./types.ts";
4
+ type Stamp = {
5
+ size: number;
6
+ mtimeMs: number;
7
+ } | null;
8
+ export type RevokeMemory = {
9
+ loaded: boolean;
10
+ stamp: Stamp;
11
+ revoked: Set<string>;
12
+ };
13
+ export declare function createRevokeMemory(): RevokeMemory;
14
+ export declare function revokeUnchanged(stateDir: string, memory: RevokeMemory): boolean;
15
+ export declare function syncRevokeControl(opts: {
16
+ stateDir: string;
17
+ now: () => number;
18
+ nonce: () => string;
19
+ policyHash: string;
20
+ recordSigner: RecordSigner;
21
+ inputsLog: InputsLog;
22
+ decisions: () => Promise<SignedDecisionRecord[]>;
23
+ memory: RevokeMemory;
24
+ writer: LedgerWriter;
25
+ }): Promise<void>;
26
+ export {};