@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.
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
- rejectUnknownKeys(rec, DOCUMENT_KEYS, "policy-unknown-key", options);
243
- if (rec.version !== 1) {
244
- throw new Error("policy-version");
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;
@@ -0,0 +1,9 @@
1
+ export declare const HALT_SWITCH = "halted";
2
+ export declare function haltSwitchPath(stateDir: string): string;
3
+ export declare function isHaltedSwitchFile(stateDir: string): boolean;
4
+ export declare function markProcessHalted(stateDir: string): void;
5
+ export declare function isProcessHalted(stateDir: string): boolean;
6
+ export declare function clearProcessHalted(stateDir: string): void;
7
+ /** If the process flag is set and the switch path is free, write the empty file. A written file owns the halt; the flag is then dropped. */
8
+ export declare function persistHaltedSwitch(stateDir: string): boolean;
9
+ export declare function isProxyHalted(stateDir: string): boolean;
@@ -0,0 +1,68 @@
1
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ /**
4
+ * Process-wide halt gate. The on-disk switch is `<stateDir>/halted`. The
5
+ * process flag is only for a halt whose file could not be written; once the
6
+ * file is there it is the single source of truth and the flag is cleared.
7
+ * The set lives on `globalThis` so source and dist copies of this module
8
+ * share one flag.
9
+ */
10
+ const FLAG = Symbol.for("verax.process-halt");
11
+ export const HALT_SWITCH = "halted";
12
+ function bag() {
13
+ const g = globalThis;
14
+ const existing = g[FLAG];
15
+ if (existing)
16
+ return existing;
17
+ const created = { dirs: new Set() };
18
+ g[FLAG] = created;
19
+ return created;
20
+ }
21
+ function keyOf(stateDir) {
22
+ return resolve(stateDir);
23
+ }
24
+ export function haltSwitchPath(stateDir) {
25
+ return join(stateDir, HALT_SWITCH);
26
+ }
27
+ export function isHaltedSwitchFile(stateDir) {
28
+ try {
29
+ return statSync(haltSwitchPath(stateDir)).isFile();
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ export function markProcessHalted(stateDir) {
36
+ bag().dirs.add(keyOf(stateDir));
37
+ }
38
+ export function isProcessHalted(stateDir) {
39
+ return bag().dirs.has(keyOf(stateDir));
40
+ }
41
+ export function clearProcessHalted(stateDir) {
42
+ bag().dirs.delete(keyOf(stateDir));
43
+ }
44
+ /** If the process flag is set and the switch path is free, write the empty file. A written file owns the halt; the flag is then dropped. */
45
+ export function persistHaltedSwitch(stateDir) {
46
+ if (isHaltedSwitchFile(stateDir)) {
47
+ clearProcessHalted(stateDir);
48
+ return true;
49
+ }
50
+ if (!isProcessHalted(stateDir))
51
+ return false;
52
+ const path = haltSwitchPath(stateDir);
53
+ try {
54
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
55
+ if (existsSync(path))
56
+ return false;
57
+ writeFileSync(path, "", { encoding: "utf8", mode: 0o600 });
58
+ clearProcessHalted(stateDir);
59
+ return true;
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ export function isProxyHalted(stateDir) {
66
+ persistHaltedSwitch(stateDir);
67
+ return isHaltedSwitchFile(stateDir) || isProcessHalted(stateDir);
68
+ }