@verax-ai/proxy 0.6.1 → 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.
@@ -6,12 +6,18 @@ export declare const approvalFs: {
6
6
  export declare const drainMetrics: {
7
7
  renameBusy: number;
8
8
  };
9
- import type { ApprovalChannel, ApprovalSignature, InputsLog, Ledger, Policy, RecordSigner } from "./types.ts";
9
+ import type { ApprovalChannel, ApprovalSignature, DecisionInputs, InputsLog, Ledger, Policy, RecordSigner } from "./types.ts";
10
10
  export type ApprovalRow = {
11
11
  ref: string;
12
12
  requestHash: string;
13
13
  subject: string;
14
14
  args: Record<string, unknown>;
15
+ /** Masked arguments to forward after approval. Absent on older snapshots. */
16
+ forwardedArgs?: Record<string, unknown>;
17
+ dataClasses?: {
18
+ masked: Record<string, number>;
19
+ forwardedHash: string;
20
+ };
15
21
  ruleId: string | null;
16
22
  ruleText: string | null;
17
23
  inputsSummary: {
@@ -29,6 +35,29 @@ export type ApprovalRow = {
29
35
  brain: string;
30
36
  allowRef?: string;
31
37
  };
38
+ /** Arguments the operator is shown and that a retry will send. */
39
+ export declare function approvalDispatchArgs(row: Pick<ApprovalRow, "args" | "forwardedArgs">): Record<string, unknown>;
40
+ export declare function approvalDispatchHash(row: Pick<ApprovalRow, "subject" | "args" | "forwardedArgs">): string;
41
+ /**
42
+ * What the signed defer committed to: the hash of what will be sent, and the
43
+ * inputs row its inputsHash names (null on a record that has no inputsHash).
44
+ * Null when no inputs row hashes to the record — fail closed. The defer comes
45
+ * from the ref index; only an index line written before 0.8.0, which does not
46
+ * carry inputsHash, sends this to the decision log.
47
+ */
48
+ export declare function signedApprovalDispatch(ledger: Ledger, inputsLog: InputsLog, ref: string, defer: {
49
+ requestHash: string;
50
+ inputsHash?: string;
51
+ }): Promise<{
52
+ hash: string;
53
+ inputs: DecisionInputs | null;
54
+ } | null>;
55
+ /**
56
+ * True when the approvals row is the call the signed defer names.
57
+ * `signedForwardedHash` is null when the defer's inputs row is not on disk,
58
+ * or no longer hashes to the record: nothing is bound then.
59
+ */
60
+ export declare function approvalArgsBound(row: Pick<ApprovalRow, "subject" | "args" | "forwardedArgs" | "requestHash" | "dataClasses">, signedRequestHash: string, signedForwardedHash?: string | null): boolean;
32
61
  export type ApprovalsLog = {
33
62
  append(row: ApprovalRow): Promise<void>;
34
63
  get(ref: string): Promise<ApprovalRow | null>;
package/dist/approvals.js CHANGED
@@ -9,8 +9,56 @@ import { signDecisionRecord } from "@cedulon/core";
9
9
  import { appendDurable, lookupDecisionByRef, lookupResolvedBy, noteResolution } from "./ledger.js";
10
10
  import { effectDescriptor, sha256Canonical } from "./hash.js";
11
11
  import { terminalText } from "./policy.js";
12
- import { inputsLogFor } from "./inputs.js";
12
+ import { isProxyHalted } from "./process-halt.js";
13
+ import { inputsLogFor, inputsMatchingHash } from "./inputs.js";
13
14
  import { SerialQueue } from "./serial-queue.js";
15
+ /** Arguments the operator is shown and that a retry will send. */
16
+ export function approvalDispatchArgs(row) {
17
+ return row.forwardedArgs ?? row.args;
18
+ }
19
+ export function approvalDispatchHash(row) {
20
+ return sha256Canonical({ name: row.subject, arguments: approvalDispatchArgs(row) });
21
+ }
22
+ /**
23
+ * What the signed defer committed to: the hash of what will be sent, and the
24
+ * inputs row its inputsHash names (null on a record that has no inputsHash).
25
+ * Null when no inputs row hashes to the record — fail closed. The defer comes
26
+ * from the ref index; only an index line written before 0.8.0, which does not
27
+ * carry inputsHash, sends this to the decision log.
28
+ */
29
+ export async function signedApprovalDispatch(ledger, inputsLog, ref, defer) {
30
+ let inputsHash = defer.inputsHash;
31
+ if (inputsHash === undefined) {
32
+ const rec = (await ledger.decisions()).find((d) => d.claims.ref === ref);
33
+ if (!rec)
34
+ return null;
35
+ if (typeof rec.claims.inputsHash !== "string")
36
+ return { hash: defer.requestHash, inputs: null };
37
+ inputsHash = rec.claims.inputsHash;
38
+ }
39
+ const inputs = await inputsMatchingHash(inputsLog, ref, inputsHash);
40
+ if (!inputs)
41
+ return null;
42
+ return { hash: inputs.dataClasses?.forwardedHash ?? defer.requestHash, inputs };
43
+ }
44
+ /**
45
+ * True when the approvals row is the call the signed defer names.
46
+ * `signedForwardedHash` is null when the defer's inputs row is not on disk,
47
+ * or no longer hashes to the record: nothing is bound then.
48
+ */
49
+ export function approvalArgsBound(row, signedRequestHash, signedForwardedHash) {
50
+ if (row.requestHash !== signedRequestHash)
51
+ return false;
52
+ if (signedForwardedHash === null)
53
+ return false;
54
+ const dispatchHash = approvalDispatchHash(row);
55
+ if (signedForwardedHash !== undefined) {
56
+ return dispatchHash === signedForwardedHash && row.dataClasses?.forwardedHash === signedForwardedHash;
57
+ }
58
+ if (row.dataClasses !== undefined)
59
+ return false;
60
+ return dispatchHash === signedRequestHash;
61
+ }
14
62
  function withStatus(cur, status, extra) {
15
63
  return {
16
64
  ...cur,
@@ -146,9 +194,10 @@ export function spentTodayMinorOf(rows, nowMs, currency, approvalTtlMs, dayOffse
146
194
  else {
147
195
  continue;
148
196
  }
149
- if (row.args.currency !== currency)
197
+ const args = approvalDispatchArgs(row);
198
+ if (args.currency !== currency)
150
199
  continue;
151
- const amt = row.args.amountMinor;
200
+ const amt = args.amountMinor;
152
201
  if (typeof amt === "number")
153
202
  sum += amt;
154
203
  }
@@ -166,8 +215,11 @@ export function createApprovalBudgetGuard(opts) {
166
215
  const dailyMax = rule.spend?.dailyMaxMinor;
167
216
  if (dailyMax === undefined)
168
217
  return { ok: true };
169
- const currency = typeof snap.args.currency === "string" ? snap.args.currency : "";
170
- const amount = typeof snap.args.amountMinor === "number" ? snap.args.amountMinor : 0;
218
+ // The amount that will be sent: approvePending checked its hash against the
219
+ // signed defer. `args` alone is not bound when forwardedArgs is present.
220
+ const sent = approvalDispatchArgs(snap);
221
+ const currency = typeof sent.currency === "string" ? sent.currency : "";
222
+ const amount = typeof sent.amountMinor === "number" ? sent.amountMinor : 0;
171
223
  // Sibling pending rows are not authorized yet. Counting them here would
172
224
  // deadlock two 100-unit pendings against a later 150 cap. A pending row
173
225
  // whose ref the ledger already resolved as allow was authorized; the
@@ -237,7 +289,7 @@ function approvalsHalted(ledger) {
237
289
  const dir = ledgerStateDir(ledger);
238
290
  if (!dir)
239
291
  return false;
240
- return existsSync(join(dir, "halted"));
292
+ return isProxyHalted(dir);
241
293
  }
242
294
  async function approvePendingUnlocked(opts) {
243
295
  if (approvalsHalted(opts.ledger))
@@ -267,8 +319,9 @@ async function approvePendingUnlocked(opts) {
267
319
  }
268
320
  if (!snap)
269
321
  return { ok: false, reason: "snapshot-missing" };
270
- const requestHash = sha256Canonical({ name: snap.subject, arguments: snap.args });
271
- if (requestHash !== defer.requestHash || requestHash !== snap.requestHash) {
322
+ const dispatchHash = approvalDispatchHash(snap);
323
+ const signed = await signedApprovalDispatch(opts.ledger, inputsLog, opts.ref, defer);
324
+ if (signed === null || dispatchHash !== signed.hash || snap.requestHash !== defer.requestHash) {
272
325
  return { ok: false, reason: "hash-mismatch" };
273
326
  }
274
327
  if (opts.now() > snap.expiresAtMs) {
@@ -308,14 +361,18 @@ async function approvePendingUnlocked(opts) {
308
361
  return guarded;
309
362
  }
310
363
  const allowRef = opts.nonce();
311
- const prior = await inputsLog.get(opts.ref);
364
+ // The class counts the allow signs come from the signed defer, not from the
365
+ // approvals row, which nothing signs.
366
+ const prior = signed.inputs ?? (await inputsLog.get(opts.ref));
312
367
  const inputs = {
313
368
  principal: prior?.principal ?? { brain: snap.brain, scopes: [] },
314
369
  inputs: prior?.inputs ?? [],
315
370
  approver: approverInputs(opts),
371
+ ...(signed.inputs?.dataClasses !== undefined ? { dataClasses: signed.inputs.dataClasses } : {}),
316
372
  };
317
373
  const inputsHash = sha256Canonical(inputs);
318
- const effectHash = sha256Canonical(effectDescriptor(snap.subject, snap.args));
374
+ const dispatchArgs = approvalDispatchArgs(snap);
375
+ const effectHash = sha256Canonical(effectDescriptor(snap.subject, dispatchArgs));
319
376
  await inputsLog.append(allowRef, inputs);
320
377
  await opts.ledger.appendDecisionChained((prevRecordHash) => signDecisionRecord({
321
378
  decider: "verax-operator",
@@ -342,10 +399,10 @@ async function approvePendingUnlocked(opts) {
342
399
  const resultHash = sha256Canonical({
343
400
  authorized: true,
344
401
  ref: allowRef,
345
- amountMinor: snap.args.amountMinor,
346
- currency: snap.args.currency,
347
- payee: snap.args.payee,
348
- reference: snap.args.reference,
402
+ amountMinor: dispatchArgs.amountMinor,
403
+ currency: dispatchArgs.currency,
404
+ payee: dispatchArgs.payee,
405
+ reference: dispatchArgs.reference,
349
406
  });
350
407
  await opts.ledger.appendEffect({
351
408
  ref: allowRef,
@@ -213,7 +213,13 @@ function parseHistoryLine(raw, line) {
213
213
  return null;
214
214
  if (typeof row.by !== "string" || row.by.length === 0 || row.by.length > 256)
215
215
  return null;
216
- const via = row.via === "http" ? "http" : row.via === "file" ? "file" : "cli";
216
+ const via = row.via === "http" || row.via === "file"
217
+ ? row.via
218
+ : row.via === "integrity"
219
+ ? "integrity"
220
+ : "cli";
221
+ // via: integrity is copied as claimed. verax verify accepts it only for
222
+ // action halt by verax:memory-integrity; any other pair is unsigned/failed.
217
223
  const parsed = { action: row.action, atMs: row.atMs, by: row.by, via, line };
218
224
  // The signature is copied as the line carries it, not judged here: a body
219
225
  // that dropped a bad one would turn a forged line into a quiet unsigned one.
@@ -0,0 +1,36 @@
1
+ import { type SpanClass } from "@conarium-ai/mask";
2
+ import type { DataClassChoice, DataClassConfig, ToolCall } from "./types.ts";
3
+ /** Detector class names, in the order a block or local deny names the first hit. */
4
+ export declare const SPAN_CLASSES: readonly SpanClass[];
5
+ /** Conarium's default when the policy does not set `scanCharCap`. */
6
+ export declare const DEFAULT_SCAN_CHAR_CAP = 16384;
7
+ /** Nested objects or arrays deeper than this cannot be hashed or scanned safely. */
8
+ export declare const MAX_ARGUMENT_DEPTH = 64;
9
+ export type DataClassGateResult = {
10
+ action: "unchanged";
11
+ } | {
12
+ action: "deny";
13
+ reasonCode: string;
14
+ } | {
15
+ action: "forward";
16
+ arguments: Record<string, unknown>;
17
+ dataClasses: {
18
+ masked: Record<string, number>;
19
+ forwardedHash: string;
20
+ };
21
+ };
22
+ export declare function parseDataClassMap(raw: unknown): Record<string, DataClassChoice>;
23
+ export declare function dataClassMapHasLocal(map: Readonly<Record<string, DataClassChoice>> | undefined): boolean;
24
+ /** Conarium leaves the IP detector off unless the operator names `ip`. */
25
+ export declare function detectorsFor(choices: Readonly<Record<string, unknown>>): {
26
+ ip: true;
27
+ } | undefined;
28
+ /** Iterative depth of objects and arrays. Leaves are the depth they sit at. */
29
+ export declare function argumentDepth(value: unknown): number;
30
+ /**
31
+ * Scan Verax's own `_ref` / `_inputs` (ids, sources, every nested string).
32
+ * A blocked file type is `file-type-block:<ext>`, as on the arguments, whatever
33
+ * the classes; a class whose choice is not `allow` is `data-class-meta:<class>`.
34
+ */
35
+ export declare function scanCallMeta(call: ToolCall, config: DataClassConfig): string | null;
36
+ export declare function gateDataClasses(call: ToolCall, config: DataClassConfig | undefined): DataClassGateResult;
@@ -0,0 +1,412 @@
1
+ import { maskField } from "@conarium-ai/mask";
2
+ import { sha256Canonical } from "./hash.js";
3
+ /** Detector class names, in the order a block or local deny names the first hit. */
4
+ export const SPAN_CLASSES = [
5
+ "email",
6
+ "entity-email",
7
+ "phone",
8
+ "tckn",
9
+ "card",
10
+ "ssn",
11
+ "iban",
12
+ "mrz",
13
+ "ip",
14
+ "secret",
15
+ "connection",
16
+ "bearer",
17
+ "labelled-secret",
18
+ "name",
19
+ "embedded",
20
+ "custom",
21
+ ];
22
+ const SPAN_CLASS_SET = new Set(SPAN_CLASSES);
23
+ const CHOICES = new Set(["allow", "mask", "local", "block"]);
24
+ /** Conarium's default when the policy does not set `scanCharCap`. */
25
+ export const DEFAULT_SCAN_CHAR_CAP = 16_384;
26
+ /** Nested objects or arrays deeper than this cannot be hashed or scanned safely. */
27
+ export const MAX_ARGUMENT_DEPTH = 64;
28
+ export function parseDataClassMap(raw) {
29
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
30
+ throw new Error("policy-data-class-unknown");
31
+ }
32
+ const out = {};
33
+ for (const [name, choice] of Object.entries(raw)) {
34
+ if (!SPAN_CLASS_SET.has(name))
35
+ throw new Error(`policy-data-class-unknown:${name}`);
36
+ if (typeof choice !== "string" || !CHOICES.has(choice)) {
37
+ throw new Error(`policy-data-class-choice:${name}`);
38
+ }
39
+ out[name] = choice;
40
+ }
41
+ return out;
42
+ }
43
+ export function dataClassMapHasLocal(map) {
44
+ if (!map)
45
+ return false;
46
+ return Object.values(map).some((choice) => choice === "local");
47
+ }
48
+ const FILE_TYPE_TOKEN_SPLIT = /[\s"'`,;|&<>()[\]{}$=]+/;
49
+ function lastMeaningfulSegment(text) {
50
+ const trimmed = text.replace(/[/\\]+$/u, "");
51
+ const parts = trimmed.split(/[/\\]/).filter((seg) => seg !== "" && seg !== "." && seg !== "..");
52
+ return parts.length === 0 ? undefined : parts[parts.length - 1];
53
+ }
54
+ function cutQueryAndFragment(text) {
55
+ const cut = text.search(/[?#]/);
56
+ return cut === -1 ? text : text.slice(0, cut);
57
+ }
58
+ function decodeWherePossible(text) {
59
+ return text.replace(/%([0-9A-Fa-f]{2})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
60
+ }
61
+ function decodeCandidates(text) {
62
+ const out = [text];
63
+ const partial = decodeWherePossible(text);
64
+ if (partial !== text)
65
+ out.push(partial);
66
+ try {
67
+ const full = decodeURIComponent(text);
68
+ if (full !== text && full !== partial)
69
+ out.push(full);
70
+ }
71
+ catch {
72
+ // Malformed escape: keep the original and the partial decode.
73
+ }
74
+ return out;
75
+ }
76
+ function ntfsNameCandidates(segment) {
77
+ const colon = segment.indexOf(":");
78
+ if (colon === -1)
79
+ return [segment];
80
+ const parts = segment.split(":");
81
+ return [parts[0] ?? "", ...parts.slice(1), segment];
82
+ }
83
+ function trimTrailingDotsAndSpaces(text) {
84
+ return text.replace(/[.\s]+$/u, "");
85
+ }
86
+ function nameHasListedExtension(name, listed) {
87
+ const lower = name.toLowerCase();
88
+ const ext = listed.toLowerCase();
89
+ return lower.length >= ext.length && lower.endsWith(ext);
90
+ }
91
+ function blockedFileTypeInToken(text, blocked) {
92
+ const stripped = cutQueryAndFragment(text);
93
+ for (const candidate of decodeCandidates(stripped)) {
94
+ const segment = lastMeaningfulSegment(cutQueryAndFragment(candidate));
95
+ if (segment === undefined)
96
+ continue;
97
+ for (const raw of ntfsNameCandidates(segment)) {
98
+ const name = trimTrailingDotsAndSpaces(raw);
99
+ if (name === "" || name === "." || name === "..")
100
+ continue;
101
+ for (const listed of blocked) {
102
+ if (nameHasListedExtension(name, listed))
103
+ return listed;
104
+ }
105
+ }
106
+ }
107
+ return undefined;
108
+ }
109
+ function blockedFileType(text, blocked) {
110
+ if (blocked.length === 0)
111
+ return undefined;
112
+ const tokens = text.split(FILE_TYPE_TOKEN_SPLIT).filter((token) => token.length > 0);
113
+ for (const token of tokens) {
114
+ const hit = blockedFileTypeInToken(token, blocked);
115
+ if (hit !== undefined)
116
+ return hit;
117
+ }
118
+ return undefined;
119
+ }
120
+ function restrictsChoices(choices) {
121
+ return Object.values(choices).some((choice) => choice === "mask" || choice === "block" || choice === "local");
122
+ }
123
+ function firstBlockedFileType(value, blocked) {
124
+ if (blocked.length === 0)
125
+ return undefined;
126
+ const stack = [value];
127
+ while (stack.length > 0) {
128
+ const cur = stack.pop();
129
+ if (typeof cur === "string") {
130
+ const hit = blockedFileType(cur, blocked);
131
+ if (hit !== undefined)
132
+ return hit;
133
+ continue;
134
+ }
135
+ if (Array.isArray(cur)) {
136
+ for (const item of cur)
137
+ stack.push(item);
138
+ continue;
139
+ }
140
+ if (cur !== null && typeof cur === "object") {
141
+ const rec = cur;
142
+ for (const key of Object.keys(rec)) {
143
+ const keyHit = blockedFileType(key, blocked);
144
+ if (keyHit !== undefined)
145
+ return keyHit;
146
+ stack.push(rec[key]);
147
+ }
148
+ }
149
+ }
150
+ return undefined;
151
+ }
152
+ function addCounts(into, add) {
153
+ if (!add)
154
+ return;
155
+ for (const [key, n] of Object.entries(add)) {
156
+ if (typeof n !== "number" || n <= 0)
157
+ continue;
158
+ into[key] = (into[key] ?? 0) + n;
159
+ }
160
+ }
161
+ function choicesFor(config, tool) {
162
+ return { ...config.document, ...(config.byTool[tool] ?? {}) };
163
+ }
164
+ /** Conarium leaves the IP detector off unless the operator names `ip`. */
165
+ export function detectorsFor(choices) {
166
+ return choices.ip !== undefined ? { ip: true } : undefined;
167
+ }
168
+ function asDecimalString(value) {
169
+ return typeof value === "bigint" ? value.toString(10) : value.toString(10);
170
+ }
171
+ /** Iterative depth of objects and arrays. Leaves are the depth they sit at. */
172
+ export function argumentDepth(value) {
173
+ let max = 0;
174
+ const stack = [{ value, depth: 0 }];
175
+ while (stack.length > 0) {
176
+ const frame = stack.pop();
177
+ if (frame.depth > max)
178
+ max = frame.depth;
179
+ if (frame.depth > MAX_ARGUMENT_DEPTH)
180
+ return frame.depth;
181
+ const cur = frame.value;
182
+ if (cur === null || typeof cur !== "object")
183
+ continue;
184
+ const next = frame.depth + 1;
185
+ if (Array.isArray(cur)) {
186
+ for (const item of cur)
187
+ stack.push({ value: item, depth: next });
188
+ }
189
+ else {
190
+ for (const child of Object.values(cur)) {
191
+ stack.push({ value: child, depth: next });
192
+ }
193
+ }
194
+ }
195
+ return max;
196
+ }
197
+ function restrictedClass(classes, choices) {
198
+ if (!classes)
199
+ return undefined;
200
+ for (const cls of SPAN_CLASSES) {
201
+ if ((classes[cls] ?? 0) > 0 && choices[cls] !== undefined && choices[cls] !== "allow") {
202
+ return cls;
203
+ }
204
+ }
205
+ return undefined;
206
+ }
207
+ /**
208
+ * Scan Verax's own `_ref` / `_inputs` (ids, sources, every nested string).
209
+ * A blocked file type is `file-type-block:<ext>`, as on the arguments, whatever
210
+ * the classes; a class whose choice is not `allow` is `data-class-meta:<class>`.
211
+ */
212
+ export function scanCallMeta(call, config) {
213
+ const args = call.arguments;
214
+ for (const key of ["_ref", "_inputs"]) {
215
+ if (!Object.prototype.hasOwnProperty.call(args, key))
216
+ continue;
217
+ const fileType = firstBlockedFileType(args[key], config.blockedFileTypes);
218
+ if (fileType !== undefined)
219
+ return `file-type-block:${fileType}`;
220
+ }
221
+ const choices = choicesFor(config, call.name);
222
+ if (!restrictsChoices(choices))
223
+ return null;
224
+ const effectiveCap = config.scanCharCap ?? DEFAULT_SCAN_CHAR_CAP;
225
+ const detectors = detectorsFor(choices);
226
+ const opts = {
227
+ pipeline: "text",
228
+ only: [],
229
+ ...(detectors ? { detectors } : {}),
230
+ ...(config.scanCharCap !== undefined ? { scanCharCap: config.scanCharCap } : {}),
231
+ };
232
+ const hitIn = (text) => {
233
+ try {
234
+ const result = maskField(text, opts);
235
+ const cls = restrictedClass(result.classes, choices);
236
+ if (cls)
237
+ return `data-class-meta:${cls}`;
238
+ if (couldNotScan(text, result, effectiveCap))
239
+ return "data-class-unscanned";
240
+ return null;
241
+ }
242
+ catch {
243
+ return "data-class-error";
244
+ }
245
+ };
246
+ const walkMeta = (value) => {
247
+ const stack = [{ value, depth: 0 }];
248
+ while (stack.length > 0) {
249
+ const frame = stack.pop();
250
+ if (frame.depth > MAX_ARGUMENT_DEPTH)
251
+ return "data-class-unscanned";
252
+ const cur = frame.value;
253
+ if (typeof cur === "string") {
254
+ const hit = hitIn(cur);
255
+ if (hit)
256
+ return hit;
257
+ continue;
258
+ }
259
+ if (typeof cur === "number" || typeof cur === "bigint") {
260
+ const hit = hitIn(asDecimalString(cur));
261
+ if (hit)
262
+ return hit;
263
+ continue;
264
+ }
265
+ if (cur === null || typeof cur !== "object")
266
+ continue;
267
+ const next = frame.depth + 1;
268
+ if (Array.isArray(cur)) {
269
+ for (const item of cur)
270
+ stack.push({ value: item, depth: next });
271
+ continue;
272
+ }
273
+ const rec = cur;
274
+ for (const key of Object.keys(rec)) {
275
+ const keyHit = hitIn(key);
276
+ if (keyHit)
277
+ return keyHit;
278
+ stack.push({ value: rec[key], depth: next });
279
+ }
280
+ }
281
+ return null;
282
+ };
283
+ if (Object.prototype.hasOwnProperty.call(args, "_ref")) {
284
+ const hit = walkMeta(args._ref);
285
+ if (hit)
286
+ return hit;
287
+ }
288
+ if (Object.prototype.hasOwnProperty.call(args, "_inputs")) {
289
+ const hit = walkMeta(args._inputs);
290
+ if (hit)
291
+ return hit;
292
+ }
293
+ return null;
294
+ }
295
+ function couldNotScan(text, result, cap) {
296
+ return (result.masked.whole ?? 0) > 0 || text.length > cap;
297
+ }
298
+ export function gateDataClasses(call, config) {
299
+ if (!config)
300
+ return { action: "unchanged" };
301
+ const choices = choicesFor(config, call.name);
302
+ if (!restrictsChoices(choices)) {
303
+ const fileType = firstBlockedFileType(call.arguments, config.blockedFileTypes);
304
+ if (fileType !== undefined)
305
+ return { action: "deny", reasonCode: `file-type-block:${fileType}` };
306
+ return { action: "unchanged" };
307
+ }
308
+ const only = SPAN_CLASSES.filter((cls) => choices[cls] === "mask");
309
+ const hasBlockOrLocal = SPAN_CLASSES.some((cls) => choices[cls] === "block" || choices[cls] === "local");
310
+ const effectiveCap = config.scanCharCap ?? DEFAULT_SCAN_CHAR_CAP;
311
+ const detectors = detectorsFor(choices);
312
+ const opts = {
313
+ pipeline: "text",
314
+ only,
315
+ ...(detectors ? { detectors } : {}),
316
+ ...(config.scanCharCap !== undefined ? { scanCharCap: config.scanCharCap } : {}),
317
+ };
318
+ const state = {
319
+ classCounts: {},
320
+ masked: {},
321
+ keyClasses: {},
322
+ fileType: undefined,
323
+ error: null,
324
+ };
325
+ const scanText = (text, kind) => {
326
+ if (state.fileType === undefined) {
327
+ state.fileType = blockedFileType(text, config.blockedFileTypes);
328
+ }
329
+ try {
330
+ const result = maskField(text, opts);
331
+ addCounts(state.classCounts, result.classes);
332
+ if (kind === "key")
333
+ addCounts(state.keyClasses, result.classes);
334
+ else
335
+ addCounts(state.masked, result.masked);
336
+ const unscanned = couldNotScan(text, result, effectiveCap);
337
+ if (unscanned && state.error === null) {
338
+ // A key cannot be rewritten; an unscanned key is always a deny.
339
+ // A value the masker could not scan, while any class is block or
340
+ // local, is a deny even if another class is mask.
341
+ if (kind === "key" || hasBlockOrLocal) {
342
+ state.error = "data-class-unscanned";
343
+ }
344
+ }
345
+ // Keys cannot be rewritten; values (and numbers) take the engine's text,
346
+ // which is the whole-field label when the string could not be scanned.
347
+ return kind === "key" ? text : result.text;
348
+ }
349
+ catch {
350
+ if (state.error === null)
351
+ state.error = "data-class-error";
352
+ return text;
353
+ }
354
+ };
355
+ const walk = (value, depth) => {
356
+ if (depth > MAX_ARGUMENT_DEPTH) {
357
+ if (state.error === null)
358
+ state.error = "data-class-unscanned";
359
+ return value;
360
+ }
361
+ if (typeof value === "string")
362
+ return scanText(value, "value");
363
+ if (typeof value === "number" || typeof value === "bigint") {
364
+ const text = asDecimalString(value);
365
+ const replaced = scanText(text, "number");
366
+ return replaced === text ? value : replaced;
367
+ }
368
+ if (Array.isArray(value))
369
+ return value.map((item) => walk(item, depth + 1));
370
+ if (value !== null && typeof value === "object") {
371
+ const src = value;
372
+ const out = {};
373
+ for (const key of Object.keys(src)) {
374
+ scanText(key, "key");
375
+ out[key] = walk(src[key], depth + 1);
376
+ }
377
+ return out;
378
+ }
379
+ return value;
380
+ };
381
+ const argumentsOut = walk(call.arguments, 0);
382
+ if (state.fileType !== undefined) {
383
+ return { action: "deny", reasonCode: `file-type-block:${state.fileType}` };
384
+ }
385
+ if (state.error !== null)
386
+ return { action: "deny", reasonCode: state.error };
387
+ for (const cls of SPAN_CLASSES) {
388
+ if (choices[cls] === "block" && (state.classCounts[cls] ?? 0) > 0) {
389
+ return { action: "deny", reasonCode: `data-class-block:${cls}` };
390
+ }
391
+ }
392
+ for (const cls of SPAN_CLASSES) {
393
+ if (choices[cls] === "local" &&
394
+ (state.classCounts[cls] ?? 0) > 0 &&
395
+ !config.localTools.includes(call.name)) {
396
+ return { action: "deny", reasonCode: `data-class-local:${cls}` };
397
+ }
398
+ }
399
+ for (const cls of SPAN_CLASSES) {
400
+ if (choices[cls] === "mask" && (state.keyClasses[cls] ?? 0) > 0) {
401
+ return { action: "deny", reasonCode: `data-class-key:${cls}` };
402
+ }
403
+ }
404
+ return {
405
+ action: "forward",
406
+ arguments: argumentsOut,
407
+ dataClasses: {
408
+ masked: state.masked,
409
+ forwardedHash: sha256Canonical({ name: call.name, arguments: argumentsOut }),
410
+ },
411
+ };
412
+ }