@verax-ai/proxy 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/approvals.d.ts +30 -1
- package/dist/approvals.js +69 -13
- package/dist/data-classes.d.ts +36 -0
- package/dist/data-classes.js +412 -0
- package/dist/explain.js +63 -13
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/inputs.d.ts +4 -0
- package/dist/inputs.js +41 -0
- package/dist/ledger-manifest.d.ts +2 -0
- package/dist/ledger-manifest.js +1 -0
- package/dist/ledger.d.ts +2 -0
- package/dist/ledger.js +4 -0
- package/dist/policy.d.ts +12 -2
- package/dist/policy.js +208 -7
- package/dist/proxy.js +149 -20
- package/dist/reconcile.d.ts +10 -1
- package/dist/reconcile.js +79 -14
- package/dist/result-classes.d.ts +35 -0
- package/dist/result-classes.js +485 -0
- package/dist/types.d.ts +59 -5
- package/dist/types.js +6 -1
- package/dist/verify-ledger.d.ts +7 -0
- package/dist/verify-ledger.js +127 -2
- package/package.json +3 -2
package/dist/explain.js
CHANGED
|
@@ -2,10 +2,11 @@ import { audit, DECISION_PROFILE } from "@cedulon/audit";
|
|
|
2
2
|
import { findDecisionRecordChainBreak } from "@cedulon/core";
|
|
3
3
|
import { approvalsLogFor } from "./approvals.js";
|
|
4
4
|
import { sha256Canonical } from "./hash.js";
|
|
5
|
-
import { inputsLogFor } from "./inputs.js";
|
|
5
|
+
import { inputsLogFor, inputsMatchingHash } from "./inputs.js";
|
|
6
6
|
import { lookupResolvedBy } from "./ledger.js";
|
|
7
7
|
import { loadCheckpoints } from "./checkpoints.js";
|
|
8
8
|
import { samePublicKey, thirdPartyReceiptCoversRow } from "./third-party.js";
|
|
9
|
+
import { resultRecordIsMismatch } from "./verify-ledger.js";
|
|
9
10
|
async function pairFor(ledger, decisions, record, inputsLog, approvals) {
|
|
10
11
|
const ref = record.claims.ref;
|
|
11
12
|
if (!ref)
|
|
@@ -23,7 +24,9 @@ async function pairFor(ledger, decisions, record, inputsLog, approvals) {
|
|
|
23
24
|
}
|
|
24
25
|
return { defer: null, resolution: null };
|
|
25
26
|
}
|
|
26
|
-
const own =
|
|
27
|
+
const own = typeof record.claims.inputsHash === "string"
|
|
28
|
+
? await inputsMatchingHash(inputsLog, ref, record.claims.inputsHash)
|
|
29
|
+
: await inputsLog.get(ref);
|
|
27
30
|
if (own?.approver?.resolves) {
|
|
28
31
|
const defer = decisions.find((d) => d.claims.ref === own.approver?.resolves) ?? null;
|
|
29
32
|
return { defer, resolution: record };
|
|
@@ -73,6 +76,15 @@ function auditedRows(effect, explainedRef, presentedExtract) {
|
|
|
73
76
|
}
|
|
74
77
|
return rows;
|
|
75
78
|
}
|
|
79
|
+
function dropResultRecordMissingEffect(findings, record, resultOf, effect) {
|
|
80
|
+
if (typeof resultOf !== "string" || !effect || effect.row.ref !== resultOf)
|
|
81
|
+
return findings;
|
|
82
|
+
if (typeof effect.resultHash === "string" && record.claims.requestHash !== effect.resultHash) {
|
|
83
|
+
return findings;
|
|
84
|
+
}
|
|
85
|
+
const ref = record.claims.ref;
|
|
86
|
+
return findings.filter((finding) => !(finding.id === ref && finding.code === "receipt-without-settlement"));
|
|
87
|
+
}
|
|
76
88
|
function dropBoundHaltedClassMismatch(findings, decisions, effects, explainedRef, presentedExtract) {
|
|
77
89
|
return findings.filter((finding) => {
|
|
78
90
|
if (finding.code !== "effect-class-mismatch")
|
|
@@ -151,7 +163,17 @@ export async function explain(ledger, ref, opts) {
|
|
|
151
163
|
if (!record) {
|
|
152
164
|
throw new Error(`explain-unknown-ref:${ref}`);
|
|
153
165
|
}
|
|
154
|
-
const
|
|
166
|
+
const inputsLog = opts?.inputsLog ?? inputsLogFor(ledger);
|
|
167
|
+
// The row inputsHash names. When none does, the last row for the ref is
|
|
168
|
+
// read so a tampered row is an inputs-hash-mismatch, not a missing document.
|
|
169
|
+
const inputsDoc = !record.claims.ref
|
|
170
|
+
? null
|
|
171
|
+
: typeof record.claims.inputsHash === "string"
|
|
172
|
+
? ((await inputsMatchingHash(inputsLog, record.claims.ref, record.claims.inputsHash)) ??
|
|
173
|
+
(await inputsLog.get(record.claims.ref)))
|
|
174
|
+
: await inputsLog.get(record.claims.ref);
|
|
175
|
+
const resultOf = typeof inputsDoc?.resultOf === "string" ? inputsDoc.resultOf : undefined;
|
|
176
|
+
const effect = effects.find((e) => e.row.ref === (resultOf ?? ref) && e.row.effectClass !== "duplicate-effect") ?? null;
|
|
155
177
|
const userExtract = opts?.extract;
|
|
156
178
|
const presentedExtract = userExtract ?? effect?.receipt;
|
|
157
179
|
const extractPresented = Boolean(presentedExtract);
|
|
@@ -187,8 +209,8 @@ export async function explain(ledger, ref, opts) {
|
|
|
187
209
|
.map((f) => f.code)),
|
|
188
210
|
]
|
|
189
211
|
: [];
|
|
190
|
-
const applicable = dropBoundHaltedClassMismatch(dropWindow ? report.findings.filter((f) => f.code !== WINDOW_COVERAGE) : report.findings, decisions, effects, ref, presentedExtract);
|
|
191
|
-
const applicableWarnings = dropBoundHaltedClassMismatch(dropWindow ? report.warnings.filter((f) => f.code !== WINDOW_COVERAGE) : report.warnings, decisions, effects, ref, presentedExtract);
|
|
212
|
+
const applicable = dropResultRecordMissingEffect(dropBoundHaltedClassMismatch(dropWindow ? report.findings.filter((f) => f.code !== WINDOW_COVERAGE) : report.findings, decisions, effects, ref, presentedExtract), record, resultOf, effect);
|
|
213
|
+
const applicableWarnings = dropResultRecordMissingEffect(dropBoundHaltedClassMismatch(dropWindow ? report.warnings.filter((f) => f.code !== WINDOW_COVERAGE) : report.warnings, decisions, effects, ref, presentedExtract), record, resultOf, effect);
|
|
192
214
|
const refFindings = applicable.filter((f) => f.id === ref);
|
|
193
215
|
const issuerFinding = applicable.find((f) => f.code === "issuer-key-mismatch" || f.id === "issuer") ??
|
|
194
216
|
applicableWarnings.find((f) => f.code === "issuer-key-mismatch") ??
|
|
@@ -227,13 +249,35 @@ export async function explain(ledger, ref, opts) {
|
|
|
227
249
|
conditions.push(name);
|
|
228
250
|
}
|
|
229
251
|
const issuerMismatch = applicable.concat(applicableWarnings).some((f) => f.code === "issuer-key-mismatch" || (pinned && f.code === "unauthenticated-issuer"));
|
|
230
|
-
const inputsLog = opts?.inputsLog ?? inputsLogFor(ledger);
|
|
231
252
|
const approvals = approvalsLogFor(ledger);
|
|
232
|
-
const inputsDoc = record.claims.ref ? await inputsLog.get(record.claims.ref) : null;
|
|
233
253
|
const inputsMismatch = Boolean(inputsDoc &&
|
|
234
254
|
typeof record.claims.inputsHash === "string" &&
|
|
235
255
|
sha256Canonical(inputsDoc) !== record.claims.inputsHash);
|
|
236
256
|
const inputsMissing = typeof record.claims.inputsHash === "string" && inputsDoc === null;
|
|
257
|
+
let resultMismatch = false;
|
|
258
|
+
if (typeof inputsDoc?.resultOf === "string") {
|
|
259
|
+
const resultHashByRef = new Map();
|
|
260
|
+
const effectClassByRef = new Map();
|
|
261
|
+
for (const e of effects) {
|
|
262
|
+
if (e.row.effectClass === "duplicate-effect")
|
|
263
|
+
continue;
|
|
264
|
+
if (typeof e.resultHash === "string")
|
|
265
|
+
resultHashByRef.set(e.row.ref, e.resultHash);
|
|
266
|
+
if (typeof e.row.effectClass === "string")
|
|
267
|
+
effectClassByRef.set(e.row.ref, e.row.effectClass);
|
|
268
|
+
}
|
|
269
|
+
let namedCount = 0;
|
|
270
|
+
for (const rec of decisions) {
|
|
271
|
+
if (typeof rec.claims.ref !== "string" || typeof rec.claims.inputsHash !== "string")
|
|
272
|
+
continue;
|
|
273
|
+
const other = rec.claims.ref === record.claims.ref
|
|
274
|
+
? inputsDoc
|
|
275
|
+
: await inputsMatchingHash(inputsLog, rec.claims.ref, rec.claims.inputsHash);
|
|
276
|
+
if (other?.resultOf === inputsDoc.resultOf)
|
|
277
|
+
namedCount += 1;
|
|
278
|
+
}
|
|
279
|
+
resultMismatch = resultRecordIsMismatch(record, { resultOf: inputsDoc.resultOf, resultClasses: inputsDoc.resultClasses }, resultHashByRef, effectClassByRef, namedCount);
|
|
280
|
+
}
|
|
237
281
|
if (inputsMissing)
|
|
238
282
|
conditions.push("inputs document missing");
|
|
239
283
|
const haltedUnbound = effect !== null &&
|
|
@@ -243,6 +287,7 @@ export async function explain(ledger, ref, opts) {
|
|
|
243
287
|
!issuerMismatch &&
|
|
244
288
|
!inputsMismatch &&
|
|
245
289
|
!inputsMissing &&
|
|
290
|
+
!resultMismatch &&
|
|
246
291
|
!haltedUnbound;
|
|
247
292
|
const code = chainBreak
|
|
248
293
|
? "receipt-chain-break"
|
|
@@ -250,24 +295,29 @@ export async function explain(ledger, ref, opts) {
|
|
|
250
295
|
? "inputs-hash-mismatch"
|
|
251
296
|
: inputsMissing
|
|
252
297
|
? "inputs-document-missing"
|
|
253
|
-
:
|
|
254
|
-
?
|
|
255
|
-
:
|
|
298
|
+
: resultMismatch
|
|
299
|
+
? "result-record-mismatch"
|
|
300
|
+
: haltedUnbound
|
|
301
|
+
? (hit?.code ?? "effect-class-mismatch")
|
|
302
|
+
: (hit?.code ?? null);
|
|
256
303
|
const detail = chainBreak
|
|
257
304
|
? `receipt-chain-break at ${breakAt ?? "unknown"} (${brk?.reason ?? "broken"})`
|
|
258
305
|
: inputsMismatch
|
|
259
306
|
? "inputs document hash does not match claims.inputsHash"
|
|
260
307
|
: inputsMissing
|
|
261
308
|
? "claims.inputsHash is on the record; the inputs document is not on disk"
|
|
262
|
-
:
|
|
263
|
-
? "
|
|
264
|
-
:
|
|
309
|
+
: resultMismatch
|
|
310
|
+
? "result record does not bind to the named call the way verifyLedger requires"
|
|
311
|
+
: haltedUnbound && !hit
|
|
312
|
+
? "halted effect is not bound to the same allow"
|
|
313
|
+
: (hit?.detail ?? null);
|
|
265
314
|
const findingCount = chainBreak
|
|
266
315
|
? Math.max(refFindings.length, 1)
|
|
267
316
|
: refFindings.length +
|
|
268
317
|
(issuerMismatch && pinned ? 1 : 0) +
|
|
269
318
|
(inputsMismatch ? 1 : 0) +
|
|
270
319
|
(inputsMissing ? 1 : 0) +
|
|
320
|
+
(resultMismatch ? 1 : 0) +
|
|
271
321
|
(haltedUnbound && refFindings.length === 0 ? 1 : 0);
|
|
272
322
|
const guarantee = guaranteeWithConditions(report.guarantee, conditions);
|
|
273
323
|
const summary = balanced
|
package/dist/index.d.ts
CHANGED
|
@@ -7,8 +7,8 @@ export type { PolicyParseOptions } from "./policy.ts";
|
|
|
7
7
|
export { FileLedger, MemoryLedger, readLedgerTail, lockHolderAlive, lockState, lockBeatOf } from "./ledger.ts";
|
|
8
8
|
export { indexCoverage, listPieceFiles } from "./ledger-manifest.ts";
|
|
9
9
|
export { explain } from "./explain.ts";
|
|
10
|
-
export { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.ts";
|
|
11
|
-
export { loadDecisionRefsFromDir, loadDecisionRequestHashesFromDir, loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile, } from "./reconcile.ts";
|
|
10
|
+
export { approvalArgsBound, approvalDispatchArgs, approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.ts";
|
|
11
|
+
export { loadDecisionRefsFromDir, loadDecisionRequestHashesFromDir, loadSignedForwardedHashesFromDir, loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile, } from "./reconcile.ts";
|
|
12
12
|
export { tenantKey } from "./tenant.ts";
|
|
13
13
|
export { diskProbe } from "./disk.ts";
|
|
14
14
|
export { checkpointsPath, readCheckpointFile } from "./checkpoints.ts";
|
|
@@ -19,7 +19,7 @@ export type { ApprovalRow, ApproveResult } from "./approvals.ts";
|
|
|
19
19
|
export type { CardCsvOpts, ChannelRow, ReconcileReport } from "./reconcile.ts";
|
|
20
20
|
export type { FileLedgerOpts, LedgerCounts, LockHolder } from "./ledger.ts";
|
|
21
21
|
export type { ApprovalSignature, ControlSignature, OperatorRemovalInput, RevokeInput } from "./types.ts";
|
|
22
|
-
export type { EffectSigner, ExplainChain, ExplainPair, ExplainFinding, ExplainOpts, ExplainResult, ExplainTrustRoot, ExplainWarning, ExtractWindow, Ledger, LedgerEffect, Policy, PolicyDecision, Principal, ProxyDeps, RecordSigner, ToolCall, ToolResult, WitnessClass, } from "./types.ts";
|
|
22
|
+
export type { EffectSigner, ExplainChain, ExplainPair, ExplainFinding, ExplainOpts, ExplainResult, ExplainTrustRoot, ExplainWarning, ExtractWindow, Ledger, LedgerEffect, MediaContent, Policy, PolicyDecision, Principal, ProxyDeps, RecordSigner, ResultContent, TextContent, ToolCall, ToolResult, WitnessClass, } from "./types.ts";
|
|
23
23
|
export { verifyLedger } from "./verify-ledger.ts";
|
|
24
24
|
export type { VerifyResult, VerifyOptions, VerifyTrust, VerifyControl, VerifyInputs, VerifyAnchors, } from "./verify-ledger.ts";
|
|
25
25
|
export { anchorEntryHash, appendAnchor, readAnchors } from "./anchors.ts";
|
package/dist/index.js
CHANGED
|
@@ -6,8 +6,8 @@ export { loadPolicy, TERMINAL_CONTROL_CLASS, DISPLAY_ESCAPE_CLASS, terminalText,
|
|
|
6
6
|
export { FileLedger, MemoryLedger, readLedgerTail, lockHolderAlive, lockState, lockBeatOf } from "./ledger.js";
|
|
7
7
|
export { indexCoverage, listPieceFiles } from "./ledger-manifest.js";
|
|
8
8
|
export { explain } from "./explain.js";
|
|
9
|
-
export { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.js";
|
|
10
|
-
export { loadDecisionRefsFromDir, loadDecisionRequestHashesFromDir, loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile, } from "./reconcile.js";
|
|
9
|
+
export { approvalArgsBound, approvalDispatchArgs, approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.js";
|
|
10
|
+
export { loadDecisionRefsFromDir, loadDecisionRequestHashesFromDir, loadSignedForwardedHashesFromDir, loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile, } from "./reconcile.js";
|
|
11
11
|
export { tenantKey } from "./tenant.js";
|
|
12
12
|
// The body writes checkpoints and signs its own effect attestations. Both were
|
|
13
13
|
// reached through a relative path into this package, which only exists inside
|
package/dist/inputs.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ export declare class MemoryInputsLog implements InputsLog {
|
|
|
3
3
|
private readonly rows;
|
|
4
4
|
append(ref: string, inputs: DecisionInputs): Promise<void>;
|
|
5
5
|
get(ref: string): Promise<DecisionInputs | null>;
|
|
6
|
+
getMatching(ref: string, hash: string): Promise<DecisionInputs | null>;
|
|
6
7
|
}
|
|
7
8
|
export declare class FileInputsLog implements InputsLog {
|
|
8
9
|
private readonly dir;
|
|
@@ -15,5 +16,8 @@ export declare class FileInputsLog implements InputsLog {
|
|
|
15
16
|
private paths;
|
|
16
17
|
append(ref: string, inputs: DecisionInputs): Promise<void>;
|
|
17
18
|
get(ref: string): Promise<DecisionInputs | null>;
|
|
19
|
+
getMatching(ref: string, hash: string): Promise<DecisionInputs | null>;
|
|
18
20
|
}
|
|
21
|
+
/** The inputs row `hash` names. Last-row `get` is not this. */
|
|
22
|
+
export declare function inputsMatchingHash(log: InputsLog, ref: string, hash: string): Promise<DecisionInputs | null>;
|
|
19
23
|
export declare function inputsLogFor(ledger: object): InputsLog;
|
package/dist/inputs.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
|
+
import { sha256Canonical } from "./hash.js";
|
|
2
3
|
import { appendDurable, ledgerFs } from "./ledger.js";
|
|
3
4
|
export class MemoryInputsLog {
|
|
4
5
|
rows = new Map();
|
|
@@ -8,6 +9,12 @@ export class MemoryInputsLog {
|
|
|
8
9
|
async get(ref) {
|
|
9
10
|
return this.rows.get(ref) ?? null;
|
|
10
11
|
}
|
|
12
|
+
async getMatching(ref, hash) {
|
|
13
|
+
const row = this.rows.get(ref);
|
|
14
|
+
if (!row)
|
|
15
|
+
return null;
|
|
16
|
+
return sha256Canonical(row) === hash ? row : null;
|
|
17
|
+
}
|
|
11
18
|
}
|
|
12
19
|
export class FileInputsLog {
|
|
13
20
|
dir;
|
|
@@ -52,6 +59,40 @@ export class FileInputsLog {
|
|
|
52
59
|
}
|
|
53
60
|
return found;
|
|
54
61
|
}
|
|
62
|
+
async getMatching(ref, hash) {
|
|
63
|
+
let found = null;
|
|
64
|
+
for (const path of this.paths().all) {
|
|
65
|
+
let text;
|
|
66
|
+
try {
|
|
67
|
+
text = await ledgerFs.readFile(path, "utf8");
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
if (err.code === "ENOENT")
|
|
71
|
+
continue;
|
|
72
|
+
throw err;
|
|
73
|
+
}
|
|
74
|
+
for (const line of text.split("\n")) {
|
|
75
|
+
if (line === "")
|
|
76
|
+
continue;
|
|
77
|
+
const row = JSON.parse(line);
|
|
78
|
+
if (row.ref !== ref)
|
|
79
|
+
continue;
|
|
80
|
+
if (sha256Canonical(row.inputs) === hash)
|
|
81
|
+
found = row.inputs;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return found;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** The inputs row `hash` names. Last-row `get` is not this. */
|
|
88
|
+
export async function inputsMatchingHash(log, ref, hash) {
|
|
89
|
+
const matching = log;
|
|
90
|
+
if (typeof matching.getMatching === "function")
|
|
91
|
+
return matching.getMatching(ref, hash);
|
|
92
|
+
const row = await log.get(ref);
|
|
93
|
+
if (!row)
|
|
94
|
+
return null;
|
|
95
|
+
return sha256Canonical(row) === hash ? row : null;
|
|
55
96
|
}
|
|
56
97
|
const STASH = Symbol.for("verax.inputsLog");
|
|
57
98
|
export function inputsLogFor(ledger) {
|
package/dist/ledger-manifest.js
CHANGED
|
@@ -226,6 +226,7 @@ export function parseIndexText(text) {
|
|
|
226
226
|
reasonCode: typeof raw.reasonCode === "string" ? raw.reasonCode : "",
|
|
227
227
|
subject: typeof raw.subject === "string" ? raw.subject : "",
|
|
228
228
|
policyHash: typeof raw.policyHash === "string" ? raw.policyHash : "",
|
|
229
|
+
...(typeof raw.inputsHash === "string" ? { inputsHash: raw.inputsHash } : {}),
|
|
229
230
|
});
|
|
230
231
|
}
|
|
231
232
|
return rows;
|
package/dist/ledger.d.ts
CHANGED
package/dist/ledger.js
CHANGED
|
@@ -179,6 +179,7 @@ function indexRowOf(signed) {
|
|
|
179
179
|
subject: signed.claims.subject,
|
|
180
180
|
policyHash: signed.claims.policyHash,
|
|
181
181
|
timestampMs: signed.claims.timestampMs,
|
|
182
|
+
...(typeof signed.claims.inputsHash === "string" ? { inputsHash: signed.claims.inputsHash } : {}),
|
|
182
183
|
};
|
|
183
184
|
}
|
|
184
185
|
function resolutionKindOf(row) {
|
|
@@ -604,6 +605,7 @@ export class FileLedger {
|
|
|
604
605
|
subject: line.subject,
|
|
605
606
|
policyHash: line.policyHash,
|
|
606
607
|
timestampMs: line.ts,
|
|
608
|
+
...(line.inputsHash !== undefined ? { inputsHash: line.inputsHash } : {}),
|
|
607
609
|
};
|
|
608
610
|
this.byRef.set(line.ref, row);
|
|
609
611
|
if (line.tenantRef !== "")
|
|
@@ -665,6 +667,7 @@ export class FileLedger {
|
|
|
665
667
|
reasonCode: row.reasonCode,
|
|
666
668
|
subject: row.subject,
|
|
667
669
|
policyHash: row.policyHash,
|
|
670
|
+
...(row.inputsHash !== undefined ? { inputsHash: row.inputsHash } : {}),
|
|
668
671
|
});
|
|
669
672
|
}
|
|
670
673
|
}
|
|
@@ -706,6 +709,7 @@ export class FileLedger {
|
|
|
706
709
|
reasonCode: row.reasonCode,
|
|
707
710
|
subject: row.subject,
|
|
708
711
|
policyHash: row.policyHash,
|
|
712
|
+
...(row.inputsHash !== undefined ? { inputsHash: row.inputsHash } : {}),
|
|
709
713
|
};
|
|
710
714
|
await appendPlain(indexPath(this.dir), lineOf(line));
|
|
711
715
|
this.applyIndexLine(line);
|
package/dist/policy.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Policy } from "./types.ts";
|
|
1
|
+
import type { DataClassChoice, MediaConfig, Policy, ResultClassChoice } from "./types.ts";
|
|
2
2
|
export type PolicySpend = {
|
|
3
3
|
maxAmountMinor: number;
|
|
4
4
|
currency: string;
|
|
@@ -20,9 +20,11 @@ export type PolicyRule = {
|
|
|
20
20
|
mode?: "allow" | "approve";
|
|
21
21
|
spend?: PolicySpend;
|
|
22
22
|
egress?: true;
|
|
23
|
+
dataClasses?: Readonly<Record<string, DataClassChoice>>;
|
|
24
|
+
resultClasses?: Readonly<Record<string, ResultClassChoice>>;
|
|
23
25
|
};
|
|
24
26
|
export type PolicyDocument = {
|
|
25
|
-
version: 1;
|
|
27
|
+
version: 1 | 2;
|
|
26
28
|
default: "deny";
|
|
27
29
|
approvalTtlMs?: number;
|
|
28
30
|
egress?: readonly string[];
|
|
@@ -33,6 +35,14 @@ export type PolicyDocument = {
|
|
|
33
35
|
dailyMax?: number;
|
|
34
36
|
diskFreeBytes?: number;
|
|
35
37
|
};
|
|
38
|
+
dataClasses?: Readonly<Record<string, DataClassChoice>>;
|
|
39
|
+
resultClasses?: Readonly<Record<string, ResultClassChoice>>;
|
|
40
|
+
media?: MediaConfig;
|
|
41
|
+
localTools?: readonly string[];
|
|
42
|
+
fileTypes?: {
|
|
43
|
+
block: readonly string[];
|
|
44
|
+
};
|
|
45
|
+
scanCharCap?: number;
|
|
36
46
|
rules: PolicyRule[];
|
|
37
47
|
};
|
|
38
48
|
/** Named per tool. Do not sniff `host` / `url` on arbitrary arguments. */
|
package/dist/policy.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseIJson } from "@cedulon/core";
|
|
2
|
+
import { dataClassMapHasLocal, parseDataClassMap } from "./data-classes.js";
|
|
2
3
|
import { defaultDiskFreeBytes } from "./disk.js";
|
|
3
4
|
import { sha256Canonical } from "./hash.js";
|
|
4
5
|
/** One DNS label: letters, digits, hyphens; no leading or trailing hyphen. */
|
|
@@ -48,7 +49,19 @@ export const HOST_EXTRACTORS = {
|
|
|
48
49
|
};
|
|
49
50
|
const DEFAULT_APPROVAL_TTL_MS = 86_400_000;
|
|
50
51
|
const DOCUMENT_KEYS = new Set(["version", "default", "rules", "egress", "approvalTtlMs", "limits", "requireInputs"]);
|
|
52
|
+
const DOCUMENT_KEYS_V2 = new Set([
|
|
53
|
+
...DOCUMENT_KEYS,
|
|
54
|
+
"dataClasses",
|
|
55
|
+
"resultClasses",
|
|
56
|
+
"media",
|
|
57
|
+
"localTools",
|
|
58
|
+
"fileTypes",
|
|
59
|
+
"scanCharCap",
|
|
60
|
+
]);
|
|
51
61
|
const RULE_KEYS = new Set(["id", "tool", "requires", "text", "mode", "spend", "egress"]);
|
|
62
|
+
const RULE_KEYS_V2 = new Set([...RULE_KEYS, "dataClasses", "resultClasses"]);
|
|
63
|
+
const DEFAULT_TRANSCRIBER_TIMEOUT_MS = 60_000;
|
|
64
|
+
const MAX_TRANSCRIBER_TIMEOUT_MS = 600_000;
|
|
52
65
|
const SPEND_KEYS = new Set(["maxAmountMinor", "currency", "payees", "dailyMaxMinor", "dayOffsetMinutes", "descriptors"]);
|
|
53
66
|
const LIMIT_KEYS = new Set(["ratePerMinute", "dailyMax", "diskFreeBytes"]);
|
|
54
67
|
function rejectUnknownKeys(rec, known, code, options) {
|
|
@@ -59,7 +72,7 @@ function rejectUnknownKeys(rec, known, code, options) {
|
|
|
59
72
|
throw new Error(`${code}:${key}`);
|
|
60
73
|
}
|
|
61
74
|
}
|
|
62
|
-
function asRule(raw, index, options) {
|
|
75
|
+
function asRule(raw, index, options, version) {
|
|
63
76
|
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
64
77
|
throw new Error(`policy-rule-invalid:${index}`);
|
|
65
78
|
}
|
|
@@ -67,7 +80,7 @@ function asRule(raw, index, options) {
|
|
|
67
80
|
if (typeof rec.id !== "string" || rec.id === "") {
|
|
68
81
|
throw new Error(`policy-rule-id:${index}`);
|
|
69
82
|
}
|
|
70
|
-
rejectUnknownKeys(rec, RULE_KEYS, `policy-rule-unknown-key:${rec.id}`, options);
|
|
83
|
+
rejectUnknownKeys(rec, version === 2 ? RULE_KEYS_V2 : RULE_KEYS, `policy-rule-unknown-key:${rec.id}`, options);
|
|
71
84
|
if (typeof rec.tool !== "string" || rec.tool === "") {
|
|
72
85
|
throw new Error(`policy-rule-tool:${rec.id}`);
|
|
73
86
|
}
|
|
@@ -119,6 +132,12 @@ function asRule(raw, index, options) {
|
|
|
119
132
|
// the call would reach any host, so the rule does not load.
|
|
120
133
|
throw new Error(`policy-rule-egress-unmarked:${rec.id}`);
|
|
121
134
|
}
|
|
135
|
+
if (version === 2 && rec.dataClasses !== undefined) {
|
|
136
|
+
rule.dataClasses = parseDataClassMap(rec.dataClasses);
|
|
137
|
+
}
|
|
138
|
+
if (version === 2 && rec.resultClasses !== undefined) {
|
|
139
|
+
rule.resultClasses = parseResultClassMap(rec.resultClasses);
|
|
140
|
+
}
|
|
122
141
|
return rule;
|
|
123
142
|
}
|
|
124
143
|
function asSpend(raw, id, options) {
|
|
@@ -239,9 +258,15 @@ export function parsePolicyDocument(json, options = {}) {
|
|
|
239
258
|
throw new Error("policy-not-object");
|
|
240
259
|
}
|
|
241
260
|
const rec = raw;
|
|
242
|
-
|
|
243
|
-
if (
|
|
244
|
-
|
|
261
|
+
const version = rec.version === 2 ? 2 : rec.version === 1 ? 1 : undefined;
|
|
262
|
+
if (version === 2) {
|
|
263
|
+
rejectUnknownKeys(rec, DOCUMENT_KEYS_V2, "policy-unknown-key", options);
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
rejectUnknownKeys(rec, DOCUMENT_KEYS, "policy-unknown-key", options);
|
|
267
|
+
if (version !== 1) {
|
|
268
|
+
throw new Error("policy-version");
|
|
269
|
+
}
|
|
245
270
|
}
|
|
246
271
|
if (rec.default !== "deny") {
|
|
247
272
|
throw new Error("policy-default-not-deny");
|
|
@@ -250,9 +275,9 @@ export function parsePolicyDocument(json, options = {}) {
|
|
|
250
275
|
throw new Error("policy-rules");
|
|
251
276
|
}
|
|
252
277
|
const document = {
|
|
253
|
-
version: 1,
|
|
278
|
+
version: version ?? 1,
|
|
254
279
|
default: "deny",
|
|
255
|
-
rules: rec.rules.map((rule, index) => asRule(rule, index, options)),
|
|
280
|
+
rules: rec.rules.map((rule, index) => asRule(rule, index, options, version ?? 1)),
|
|
256
281
|
};
|
|
257
282
|
if (rec.egress !== undefined) {
|
|
258
283
|
if (!Array.isArray(rec.egress) ||
|
|
@@ -284,9 +309,154 @@ export function parsePolicyDocument(json, options = {}) {
|
|
|
284
309
|
}
|
|
285
310
|
document.requireInputs = true;
|
|
286
311
|
}
|
|
312
|
+
if (version === 2) {
|
|
313
|
+
if (rec.dataClasses !== undefined) {
|
|
314
|
+
document.dataClasses = parseDataClassMap(rec.dataClasses);
|
|
315
|
+
}
|
|
316
|
+
if (rec.localTools !== undefined) {
|
|
317
|
+
document.localTools = asLocalTools(rec.localTools);
|
|
318
|
+
}
|
|
319
|
+
if (rec.fileTypes !== undefined) {
|
|
320
|
+
document.fileTypes = asFileTypes(rec.fileTypes);
|
|
321
|
+
}
|
|
322
|
+
if (rec.scanCharCap !== undefined) {
|
|
323
|
+
if (typeof rec.scanCharCap !== "number" ||
|
|
324
|
+
!Number.isInteger(rec.scanCharCap) ||
|
|
325
|
+
rec.scanCharCap <= 0) {
|
|
326
|
+
throw new Error("policy-scan-char-cap");
|
|
327
|
+
}
|
|
328
|
+
document.scanCharCap = rec.scanCharCap;
|
|
329
|
+
}
|
|
330
|
+
if (rec.resultClasses !== undefined) {
|
|
331
|
+
document.resultClasses = parseResultClassMap(rec.resultClasses);
|
|
332
|
+
}
|
|
333
|
+
if (rec.media !== undefined) {
|
|
334
|
+
document.media = parseMedia(rec.media);
|
|
335
|
+
}
|
|
336
|
+
const localUsed = dataClassMapHasLocal(document.dataClasses) ||
|
|
337
|
+
document.rules.some((rule) => dataClassMapHasLocal(rule.dataClasses));
|
|
338
|
+
if (localUsed && (document.localTools === undefined || document.localTools.length === 0)) {
|
|
339
|
+
throw new Error("policy-data-class-local-tools");
|
|
340
|
+
}
|
|
341
|
+
}
|
|
287
342
|
rejectDuplicateRules(document.rules);
|
|
288
343
|
return document;
|
|
289
344
|
}
|
|
345
|
+
function parseResultClassMap(raw) {
|
|
346
|
+
const map = parseDataClassMap(raw);
|
|
347
|
+
const out = {};
|
|
348
|
+
for (const [name, choice] of Object.entries(map)) {
|
|
349
|
+
if (choice === "local")
|
|
350
|
+
throw new Error(`policy-result-class-local:${name}`);
|
|
351
|
+
out[name] = choice;
|
|
352
|
+
}
|
|
353
|
+
return out;
|
|
354
|
+
}
|
|
355
|
+
function countToken(haystack, needle) {
|
|
356
|
+
if (needle === "")
|
|
357
|
+
return 0;
|
|
358
|
+
let n = 0;
|
|
359
|
+
let from = 0;
|
|
360
|
+
while (from <= haystack.length) {
|
|
361
|
+
const at = haystack.indexOf(needle, from);
|
|
362
|
+
if (at === -1)
|
|
363
|
+
return n;
|
|
364
|
+
n += 1;
|
|
365
|
+
from = at + needle.length;
|
|
366
|
+
}
|
|
367
|
+
return n;
|
|
368
|
+
}
|
|
369
|
+
function parseTranscriber(raw) {
|
|
370
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
371
|
+
throw new Error("policy-media-transcriber");
|
|
372
|
+
}
|
|
373
|
+
const rec = raw;
|
|
374
|
+
for (const key of Object.keys(rec)) {
|
|
375
|
+
if (key !== "command" && key !== "timeoutMs")
|
|
376
|
+
throw new Error(`policy-media-transcriber:${key}`);
|
|
377
|
+
}
|
|
378
|
+
if (!Array.isArray(rec.command) ||
|
|
379
|
+
rec.command.length === 0 ||
|
|
380
|
+
rec.command.some((part) => typeof part !== "string")) {
|
|
381
|
+
throw new Error("policy-media-transcriber");
|
|
382
|
+
}
|
|
383
|
+
const command = rec.command;
|
|
384
|
+
if (command[0] !== undefined && command[0].includes("{file}")) {
|
|
385
|
+
throw new Error("policy-media-transcriber");
|
|
386
|
+
}
|
|
387
|
+
let fileMarks = 0;
|
|
388
|
+
for (const part of command)
|
|
389
|
+
fileMarks += countToken(part, "{file}");
|
|
390
|
+
if (fileMarks !== 1)
|
|
391
|
+
throw new Error("policy-media-transcriber");
|
|
392
|
+
let timeoutMs = DEFAULT_TRANSCRIBER_TIMEOUT_MS;
|
|
393
|
+
if (rec.timeoutMs !== undefined) {
|
|
394
|
+
if (typeof rec.timeoutMs !== "number" ||
|
|
395
|
+
!Number.isInteger(rec.timeoutMs) ||
|
|
396
|
+
rec.timeoutMs <= 0 ||
|
|
397
|
+
rec.timeoutMs > MAX_TRANSCRIBER_TIMEOUT_MS) {
|
|
398
|
+
throw new Error("policy-media-transcriber");
|
|
399
|
+
}
|
|
400
|
+
timeoutMs = rec.timeoutMs;
|
|
401
|
+
}
|
|
402
|
+
return { command, timeoutMs };
|
|
403
|
+
}
|
|
404
|
+
function parseMedia(raw) {
|
|
405
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
406
|
+
throw new Error("policy-media");
|
|
407
|
+
}
|
|
408
|
+
const rec = raw;
|
|
409
|
+
const out = {};
|
|
410
|
+
for (const [kind, value] of Object.entries(rec)) {
|
|
411
|
+
if (kind === "transcriber") {
|
|
412
|
+
out.transcriber = parseTranscriber(value);
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
if (kind === "audio") {
|
|
416
|
+
if (value !== "allow" && value !== "transcribe" && value !== "withhold") {
|
|
417
|
+
throw new Error("policy-media-choice:audio");
|
|
418
|
+
}
|
|
419
|
+
out.audio = value;
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (kind === "image") {
|
|
423
|
+
if (value !== "allow" && value !== "withhold") {
|
|
424
|
+
throw new Error("policy-media-choice:image");
|
|
425
|
+
}
|
|
426
|
+
out.image = value;
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
throw new Error(`policy-media-kind:${kind}`);
|
|
430
|
+
}
|
|
431
|
+
if (out.audio === "transcribe" && out.transcriber === undefined) {
|
|
432
|
+
throw new Error("policy-media-transcriber");
|
|
433
|
+
}
|
|
434
|
+
return out;
|
|
435
|
+
}
|
|
436
|
+
function asLocalTools(raw) {
|
|
437
|
+
if (!Array.isArray(raw) || raw.some((t) => typeof t !== "string" || t === "")) {
|
|
438
|
+
throw new Error("policy-data-class-local-tools");
|
|
439
|
+
}
|
|
440
|
+
return raw;
|
|
441
|
+
}
|
|
442
|
+
function asFileTypes(raw) {
|
|
443
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
444
|
+
throw new Error("policy-file-types");
|
|
445
|
+
}
|
|
446
|
+
const rec = raw;
|
|
447
|
+
for (const key of Object.keys(rec)) {
|
|
448
|
+
if (key !== "block")
|
|
449
|
+
throw new Error("policy-file-types");
|
|
450
|
+
}
|
|
451
|
+
if (!Array.isArray(rec.block))
|
|
452
|
+
throw new Error("policy-file-types");
|
|
453
|
+
for (const ext of rec.block) {
|
|
454
|
+
if (typeof ext !== "string" || !ext.startsWith(".") || ext !== ext.toLowerCase() || ext.length < 2) {
|
|
455
|
+
throw new Error("policy-file-types");
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return { block: rec.block };
|
|
459
|
+
}
|
|
290
460
|
function rejectDuplicateRules(rules) {
|
|
291
461
|
const seenId = new Set();
|
|
292
462
|
const toolOwner = new Map();
|
|
@@ -347,6 +517,37 @@ export function loadPolicy(json, options = {}) {
|
|
|
347
517
|
approvalTtlMs: document.approvalTtlMs ?? DEFAULT_APPROVAL_TTL_MS,
|
|
348
518
|
limits,
|
|
349
519
|
...(document.requireInputs ? { requireInputs: true } : {}),
|
|
520
|
+
...(document.version === 2
|
|
521
|
+
? {
|
|
522
|
+
...(document.dataClasses !== undefined ||
|
|
523
|
+
document.fileTypes !== undefined ||
|
|
524
|
+
document.rules.some((rule) => rule.dataClasses !== undefined)
|
|
525
|
+
? {
|
|
526
|
+
dataClasses: {
|
|
527
|
+
document: document.dataClasses ?? {},
|
|
528
|
+
byTool: Object.fromEntries(document.rules
|
|
529
|
+
.filter((rule) => rule.dataClasses !== undefined)
|
|
530
|
+
.map((rule) => [rule.tool, rule.dataClasses])),
|
|
531
|
+
localTools: document.localTools ?? [],
|
|
532
|
+
blockedFileTypes: [...(document.fileTypes?.block ?? [])],
|
|
533
|
+
...(document.scanCharCap !== undefined ? { scanCharCap: document.scanCharCap } : {}),
|
|
534
|
+
},
|
|
535
|
+
}
|
|
536
|
+
: {}),
|
|
537
|
+
...(document.resultClasses !== undefined || document.rules.some((rule) => rule.resultClasses !== undefined)
|
|
538
|
+
? {
|
|
539
|
+
resultClasses: {
|
|
540
|
+
document: document.resultClasses ?? {},
|
|
541
|
+
byTool: Object.fromEntries(document.rules
|
|
542
|
+
.filter((rule) => rule.resultClasses !== undefined)
|
|
543
|
+
.map((rule) => [rule.tool, rule.resultClasses])),
|
|
544
|
+
},
|
|
545
|
+
}
|
|
546
|
+
: {}),
|
|
547
|
+
...(document.media !== undefined ? { media: document.media } : {}),
|
|
548
|
+
...(document.scanCharCap !== undefined ? { scanCharCap: document.scanCharCap } : {}),
|
|
549
|
+
}
|
|
550
|
+
: {}),
|
|
350
551
|
rule(id) {
|
|
351
552
|
if (id === null)
|
|
352
553
|
return null;
|