@cygnuxlabs/tracekit 1.7.3 → 1.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.
@@ -0,0 +1,238 @@
1
+ /**
2
+ * tracekit/signer/labels.py's Sources and tracekit/verify/v2.py's _run_labels: which run labels a run's records set,
3
+ * replayed under its compiled policy, for the verifier's `run labels` check (docs/policy-v2.md#run-conditions). A port
4
+ * kept in step with the reference by tests/test_run_conditions.py.
5
+ */
6
+ import { Detector, glob } from "./detect.js";
7
+ import { Budget, Pattern, PolicyError } from "./rx.js";
8
+ const SECTIONS = ["deny", "ask", "flag"];
9
+ const UNTRUSTED = "untrusted_content";
10
+ const UNREAD = "TK-OVERSIZE"; // a call the policy couldn't read: it sets every label the policy reads
11
+ // tracekit/signer/labels.py LOST: the gaps of calls the signer never decided
12
+ const LOST = ["client_counter_gap", "signer_unavailable", "tailer_lost", "observer_lost"];
13
+ // tracekit/policy2/compile.py CLASSES: an `untrusted` entry that names one is a class, any other a tool name glob
14
+ const CLASSES = ["shell", "fs", "http", "sql", "payment", "email", "mcp", "browser", "a2a", "app", "unknown", "harness"];
15
+ const cut = (s, n) => [...s].slice(0, n).join("");
16
+ const str = (v) => v === null || v === undefined ? "None" : v === true ? "True" : v === false ? "False"
17
+ : typeof v === "string" ? v : JSON.stringify(v);
18
+ const key = (v) => typeof v === "string" ? v : null; // a schema-invalid id names nothing
19
+ /** Python's order of strings, by code point (JavaScript's `<` and sort() compare UTF-16 code units, which put a
20
+ * character above U+FFFF before one in U+E000..U+FFFF). */
21
+ export const byCodePoint = (a, b) => {
22
+ const unit = (u) => u >= 0xd800 && u < 0xe000 ? u + 0x2000 : u >= 0xe000 ? u - 0x800 : u;
23
+ for (let i = 0; i < Math.min(a.length, b.length); i++)
24
+ if (a.charCodeAt(i) !== b.charCodeAt(i))
25
+ return unit(a.charCodeAt(i)) - unit(b.charCodeAt(i));
26
+ return a.length - b.length;
27
+ };
28
+ /** tracekit/policy2/compile.py subject_labels: {rule id: label} of the rules whose labels a rule on the labels field
29
+ * reads, each rule's non-empty label but a run condition rule's and another labels field rule's. */
30
+ export function subjectLabels(policy) {
31
+ return new Map(SECTIONS.flatMap((sec) => policy[sec] ?? []).filter((r) => typeof r.label === "string" && r.label
32
+ && !Object.hasOwn(r, "when") && r.field !== "labels").map((r) => [r.id, r.label]));
33
+ }
34
+ /** tracekit/policy2/compile.py labels_subject: the labels `labels` gives `ids`, each once, sorted by code point and
35
+ * joined by a space; "" when none has one. */
36
+ export const labelsSubject = (ids, labels) => [...new Set(ids.filter((i) => labels.has(i)).map((i) => labels.get(i)))].sort(byCodePoint).join(" ");
37
+ /** A tool name as CrewAI's sanitize_tool_name leaves it, without its `_` (tracekit/policy2/engine.py _spelling). */
38
+ function spelling(name) {
39
+ return name.normalize("NFKD").replace(/[^\x00-\x7f]/g, "").toLowerCase().replace(/[^0-9a-z]/g, "");
40
+ }
41
+ export class Sources {
42
+ when = new Map();
43
+ tracked = new Set();
44
+ label = new Map();
45
+ subjectLabels;
46
+ onLabels = [];
47
+ refused = new Map(); // rule id -> why its labels pattern can't be compiled as the signer does
48
+ untrusted;
49
+ tools;
50
+ spelled = new Map();
51
+ classes;
52
+ constructor(policy) {
53
+ const rules = SECTIONS.flatMap((sec) => policy[sec] ?? []);
54
+ for (const r of rules)
55
+ if (Object.hasOwn(r, "when"))
56
+ this.when.set(r.id, new Set(r.when.run_has));
57
+ for (const ls of this.when.values())
58
+ for (const x of ls)
59
+ this.tracked.add(x);
60
+ for (const x of policy.approval_agent?.run?.clean ?? [])
61
+ this.tracked.add(x); // the AI approver's run bound
62
+ for (const r of rules)
63
+ if (this.tracked.has(r.label))
64
+ this.label.set(r.id, r.label);
65
+ this.subjectLabels = subjectLabels(policy);
66
+ const compiled = (p) => {
67
+ if (typeof p !== "string")
68
+ throw new PolicyError("the pattern is not a string");
69
+ return new Pattern(p);
70
+ };
71
+ for (const r of rules)
72
+ if (r.field === "labels" && Object.hasOwn(r, "when") && !Object.hasOwn(r, "tool")) {
73
+ try { // a bundle's own policy may hold any pattern: searched in linear time, as RE2 reads it (rx.ts)
74
+ this.onLabels.push([r.id, compiled(r.pattern), Object.hasOwn(r, "unless") ? compiled(r.unless) : null,
75
+ r.class ?? null]);
76
+ }
77
+ catch (e) {
78
+ if (!(e instanceof PolicyError))
79
+ throw e;
80
+ this.refused.set(r.id, e.message);
81
+ }
82
+ }
83
+ this.untrusted = policy.untrusted ?? [];
84
+ this.tools = policy.tools ?? {};
85
+ this.classes = new Detector(policy);
86
+ for (const t of Object.keys(this.tools))
87
+ if (!/[*?[]/.test(t) && spelling(t))
88
+ this.spelled.set(spelling(t), [...this.spelled.get(spelling(t)) ?? [], t]);
89
+ }
90
+ /** The names `tools:` lists that `tool` spells, when it lists neither the tool nor a glob that takes it. */
91
+ listed(tool) {
92
+ if (Object.hasOwn(this.tools, tool) || this.classes.toolClass(tool) !== "unknown")
93
+ return [];
94
+ return this.spelled.get(spelling(tool)) ?? [];
95
+ }
96
+ untrustedResults(tool) {
97
+ return [tool, ...this.listed(tool)].some((name) => this.untrusted.some((u) => CLASSES.includes(u) ? u === this.classes.toolClass(name) : glob(u).test(name)));
98
+ }
99
+ ofCall(tool, ruleIds) {
100
+ if (typeof tool === "string" && this.classes.toolClass(tool) === "harness")
101
+ return new Set();
102
+ if (ruleIds.includes(UNREAD))
103
+ return new Set(this.tracked);
104
+ const out = new Set(ruleIds.filter((i) => this.label.has(i)).map((i) => this.label.get(i)));
105
+ if (this.tracked.has(UNTRUSTED) && typeof tool === "string" && this.untrustedResults(tool))
106
+ out.add(UNTRUSTED);
107
+ return out;
108
+ }
109
+ /** The labels record `e` sets; `requested`, `decided`: {tool, rule_ids} of an approval's call and a call's latest
110
+ * decision, or undefined. */
111
+ sets(e, requested, decided) {
112
+ const t = e.type, d = e.data;
113
+ if (t === "policy.decision" && (d.decision === "allow" || d.decision === "flag"))
114
+ return this.ofCall(d.tool, d.rule_ids);
115
+ const call = t === "approval.consumed" ? requested(d.approval_id ?? null)
116
+ : t === "capture.gap" && d.kind === "executed_against_policy" ? decided(e.tool_call_id ?? null) : undefined;
117
+ if (call)
118
+ return this.ofCall(call.tool, call.rule_ids);
119
+ if (t === "input.observed" && d.trust === "untrusted" && this.tracked.has(UNTRUSTED))
120
+ return new Set([UNTRUSTED]);
121
+ if (t === "capture.gap" && LOST.includes(d.kind) || t === "reconcile.hook_missing")
122
+ return new Set(this.tracked);
123
+ return new Set();
124
+ }
125
+ }
126
+ /** The policies each of a run's records is replayed under (tracekit/verify/v2.py _policies_at): a decision's own; another
127
+ * record's, that of the decision before it (the first one's before any) and, between two decisions under different
128
+ * policies, the next one's too. */
129
+ export function policiesAt(events, srcs) {
130
+ if (srcs.size === 1)
131
+ return events.map(() => [...srcs.values()]);
132
+ const named = events.map((e) => e.type === "policy.decision" && Object.hasOwn(e.data, "policy_hash")
133
+ ? str(e.data.policy_hash) : null);
134
+ const next = [];
135
+ let after = null, before = null;
136
+ for (let i = named.length - 1; i >= 0; i--)
137
+ next[i] = after = named[i] ?? after;
138
+ return named.map((h, i) => {
139
+ before = h ?? before;
140
+ return [...new Set([before ?? next[i], next[i] ?? before])].map((x) => srcs.get(x));
141
+ });
142
+ }
143
+ /** The problems of one run's labels under `srcs` (policy_hash -> Sources), each record under its policy
144
+ * (tracekit/verify/v2.py _run_labels); each inherited add of a label its policy reads goes to `inherited` as [where,
145
+ * label, the add it cites]. */
146
+ export function runLabels(events, srcs, inherited, budget = new Budget()) {
147
+ const problems = [], carried = new Set(), asked = new Map(), decided = new Map();
148
+ const seqs = new Map(), at = policiesAt(events, srcs);
149
+ let owed = new Map(), may = new Map(), owner = null;
150
+ const callers = new Set();
151
+ for (const [n, e] of events.entries()) {
152
+ const t = e.type, d = e.data, where = `seq ${str(e.seq)}`, cands = at[n], src = cands[0];
153
+ if (!Number.isInteger(e.run_seq))
154
+ continue; // schema-invalid: its schema check fails it
155
+ seqs.set(e.run_seq, e.seq ?? null);
156
+ if (t === "run.registered" && typeof d.identity === "object" && d.identity !== null && !Array.isArray(d.identity))
157
+ owner = `${str(d.identity.scheme ?? null)}:${str(d.identity.subject ?? null)}`;
158
+ // the client a gateway registered it for, a writer: requesters of the run
159
+ if (t === "run.registered" || t === "run.writer")
160
+ callers.add(t === "run.registered" ? d.caller : d.identity);
161
+ if (t === "run.label" && d.action === "clear" && Object.hasOwn(d, "run_id"))
162
+ continue; // an ended run's
163
+ if (t === "run.label") {
164
+ const x = key(d.label);
165
+ if (d.action === "add") {
166
+ if (x !== null && carried.has(x))
167
+ problems.push(`${where}: adds ${cut(str(x), 32)}, which the run carries already`);
168
+ else if (Object.hasOwn(d, "inherited") && x !== null && cands.some((c) => c.tracked.has(x)))
169
+ inherited.push([where, x, d.inherited]);
170
+ else if (Object.hasOwn(d, "inherited"))
171
+ problems.push(`${where}: inherits ${cut(str(x), 32)}, which the run's policy doesn't read`);
172
+ else if (x === null || d.source === undefined || d.source === null
173
+ || (owed.get(x) !== d.source && may.get(x) !== d.source))
174
+ problems.push(`${where}: adds ${cut(str(x), 32)} citing run_seq ${cut(str(d.source ?? null), 20)}, which doesn't `
175
+ + "set it under the run's policy");
176
+ if (x !== null) {
177
+ owed.delete(x);
178
+ may.delete(x);
179
+ carried.add(x);
180
+ }
181
+ }
182
+ else if (x === null || !carried.has(x))
183
+ problems.push(`${where}: clears ${cut(str(x), 32)}, which the run doesn't carry`);
184
+ else if ((d.identity ?? null) === owner && d.self_cleared !== true)
185
+ problems.push(`${where}: ${cut(str(x), 32)} cleared by the run's own owner`);
186
+ else if (callers.has(d.identity) && d.self_cleared !== true)
187
+ problems.push(`${where}: ${cut(str(x), 32)} cleared by a requester of the run (a writer or a gateway's caller)`);
188
+ else
189
+ carried.delete(x);
190
+ continue;
191
+ }
192
+ if (t === "policy.decision" || t === "approval.consumed") {
193
+ for (const [x, s] of owed)
194
+ problems.push(`seq ${str(seqs.get(s) ?? null)}: sets ${x}, which no run.label adds before ${where}`);
195
+ for (const x of owed.keys())
196
+ carried.add(x);
197
+ owed = new Map();
198
+ may = new Map();
199
+ }
200
+ const ids = Array.isArray(d.rule_ids) ? d.rule_ids.filter((i) => typeof i === "string") : [];
201
+ if (t === "policy.decision") {
202
+ const have = new Set([...carried, ...ids.filter((i) => src.label.has(i)).map((i) => src.label.get(i))]);
203
+ const used = new Set(Array.isArray(d.run_labels) ? d.run_labels.filter((x) => typeof x === "string") : []);
204
+ for (const x of [...used].filter((x) => !have.has(x)).sort(byCodePoint))
205
+ problems.push(`${where}: run_labels names ${cut(x, 32)}, which the run didn't carry`);
206
+ for (const i of ids)
207
+ if (src.when.has(i) && ![...src.when.get(i)].every((x) => used.has(x)))
208
+ problems.push(`${where}: ${i} applied without run_labels naming ${[...src.when.get(i)].sort(byCodePoint).join(", ")}`);
209
+ // a run condition on the labels field, replayed from the call's rule ids as Engine.condition matches it
210
+ // (labels.py, verify/v2.py _run_labels)
211
+ const subject = labelsSubject(ids, src.subjectLabels);
212
+ const tool = typeof d.tool === "string" ? d.tool : null;
213
+ if (subject && !decided.has(key(e.tool_call_id ?? null)) && tool && src.classes.toolClass(tool) !== "harness")
214
+ for (const [rid, rx, unless, cls] of src.onLabels)
215
+ if (!ids.includes(rid) && [...src.when.get(rid)].every((x) => have.has(x))
216
+ && (cls === null || cls === src.classes.toolClass(tool)) && rx.search(subject, budget)
217
+ && !(unless && unless.search(subject, budget)))
218
+ problems.push(`${where}: ${rid} applies (the call's labels ${subject}; the run carried `
219
+ + `${[...src.when.get(rid)].sort(byCodePoint).join(", ")}) but the decision doesn't name it`);
220
+ if (typeof d.caller === "string")
221
+ callers.add(d.caller);
222
+ decided.set(key(e.tool_call_id ?? null), { tool: d.tool ?? null, rule_ids: ids });
223
+ }
224
+ else if (t === "approval.request" && typeof d.binding === "object" && d.binding !== null && !Array.isArray(d.binding))
225
+ asked.set(key(d.approval_id ?? null), { tool: d.binding.tool ?? null, rule_ids: ids });
226
+ const call = t === "policy.decision" ? { ...d, rule_ids: ids } : d;
227
+ const sets = cands.map((c) => c.sets({ ...e, data: call }, (a) => asked.get(key(a)), (c) => decided.get(key(c))));
228
+ const need = [...sets[0]].filter((x) => sets.every((s) => s.has(x)));
229
+ for (const x of need.filter((x) => !carried.has(x) && !owed.has(x)).sort(byCodePoint))
230
+ owed.set(x, e.run_seq);
231
+ for (const x of [...new Set(sets.flatMap((s) => [...s]))].filter((x) => !need.includes(x) && !carried.has(x)
232
+ && !owed.has(x) && !may.has(x)).sort(byCodePoint))
233
+ may.set(x, e.run_seq);
234
+ }
235
+ for (const [x, s] of owed)
236
+ problems.push(`seq ${str(seqs.get(s) ?? null)}: sets ${x}, which no run.label adds`);
237
+ return problems;
238
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * tracekit/policy2/linear.py's Pattern: a linear-time search for the patterns tracekit/policy2/compile.py check_pattern
3
+ * accepts, with RE2's semantics, for the verifier's label patterns (labels.ts): a bundle's own policy may hold any
4
+ * pattern, and JavaScript's RegExp backtracks, so a hostile one would hang the verifier. A pattern outside the subset
5
+ * (translate's lexical rules, sre's syntax, a repeat of a repeat, nested repeat counts past 1000) throws PolicyError;
6
+ * every search spends a Budget the verification shares and throws Spent when it runs out. A port kept in step with the
7
+ * reference by tests/test_run_conditions.py.
8
+ */
9
+ export declare class PolicyError extends Error {
10
+ }
11
+ export declare class Spent extends Error {
12
+ }
13
+ export declare const STEPS = 20000000;
14
+ export declare class Budget {
15
+ steps: number;
16
+ left: number;
17
+ constructor(steps?: number);
18
+ spend(n: number): void;
19
+ }
20
+ type Test = (c: string) => boolean;
21
+ type Ins = ["char", Test] | ["split", number, number] | ["jmp", number] | ["at", string] | ["match"];
22
+ export declare class Pattern {
23
+ prog: Ins[];
24
+ found: Map<string, boolean>;
25
+ constructor(pattern: string);
26
+ private at;
27
+ /** Whether the pattern matches somewhere in `text`, spending `budget`; a text searched before is answered again. */
28
+ search(text: string, budget: Budget): boolean;
29
+ private run;
30
+ }
31
+ export {};
@@ -0,0 +1,355 @@
1
+ /**
2
+ * tracekit/policy2/linear.py's Pattern: a linear-time search for the patterns tracekit/policy2/compile.py check_pattern
3
+ * accepts, with RE2's semantics, for the verifier's label patterns (labels.ts): a bundle's own policy may hold any
4
+ * pattern, and JavaScript's RegExp backtracks, so a hostile one would hang the verifier. A pattern outside the subset
5
+ * (translate's lexical rules, sre's syntax, a repeat of a repeat, nested repeat counts past 1000) throws PolicyError;
6
+ * every search spends a Budget the verification shares and throws Spent when it runs out. A port kept in step with the
7
+ * reference by tests/test_run_conditions.py.
8
+ */
9
+ export class PolicyError extends Error {
10
+ }
11
+ export class Spent extends Error {
12
+ }
13
+ const MAX_REPEAT = 1000, MAX_PROGRAM = 20000;
14
+ export const STEPS = 20_000_000;
15
+ const ESCAPES = new Set("dDwWsSbAntrfv"), CLASS_ESCAPES = new Set("dDwWsntrfv"); // compile.py's (no \B)
16
+ const CONTROL = { n: "\n", t: "\t", r: "\r", f: "\f", v: "\v" };
17
+ const isWord = (c) => /^[0-9A-Za-z_]$/.test(c);
18
+ const SPACE = "\t\n\f\r ";
19
+ const CATS = {
20
+ d: (c) => c >= "0" && c <= "9", D: (c) => !(c >= "0" && c <= "9"), w: isWord, W: (c) => !isWord(c),
21
+ s: (c) => SPACE.includes(c), S: (c) => !SPACE.includes(c),
22
+ };
23
+ export class Budget {
24
+ steps;
25
+ left;
26
+ constructor(steps = STEPS) {
27
+ this.steps = steps;
28
+ this.left = steps;
29
+ }
30
+ spend(n) {
31
+ this.left -= n;
32
+ if (this.left < 0)
33
+ throw new Spent(`the label patterns took more than ${this.steps} steps to replay`);
34
+ }
35
+ }
36
+ const uniq = (items) => [...new Map(items.map((x) => [JSON.stringify(x), x])).values()];
37
+ const key = (n) => n.op === "char" ? n.kind + JSON.stringify(n.items) : n.op === "at" ? "@" + n.kind : null;
38
+ function charTest(n) {
39
+ if (n.kind === "any")
40
+ return (x) => x !== "\n";
41
+ const tests = n.items.map((it) => it[0] === "L" ? (x) => x.codePointAt(0) === it[1]
42
+ : it[0] === "R" ? (x) => x.codePointAt(0) >= it[1] && x.codePointAt(0) <= it[2] : CATS[it[1]]);
43
+ const negate = n.kind === "notlit" || n.kind === "notin";
44
+ return (x) => tests.some((t) => t(x)) !== negate;
45
+ }
46
+ /** sre's parse of a pattern translate() lets through, as Nodes; PolicyError for what either refuses. */
47
+ class Parser {
48
+ s;
49
+ i = 0;
50
+ names = new Set();
51
+ constructor(s) {
52
+ this.s = s;
53
+ }
54
+ fail(why) { throw new PolicyError(why); }
55
+ /** sre's _parse_sub: the alternatives, their common first nodes moved out, and alternatives of one literal or class
56
+ * each as one class. */
57
+ alternation() {
58
+ const alts = [this.sequence()];
59
+ while (this.s[this.i] === "|") {
60
+ this.i++;
61
+ alts.push(this.sequence());
62
+ }
63
+ if (alts.length === 1)
64
+ return alts[0];
65
+ const out = [];
66
+ while (alts.every((a) => a.length) && key(alts[0][0]) !== null && alts.every((a) => key(a[0]) === key(alts[0][0]))) {
67
+ out.push(alts[0][0]);
68
+ for (const a of alts)
69
+ a.shift();
70
+ }
71
+ if (alts.every((a) => a.length === 1 && a[0].op === "char" && (a[0].kind === "lit" || a[0].kind === "in")))
72
+ return [...out, { op: "char", kind: "in", items: uniq(alts.flatMap((a) => a[0].items)) }];
73
+ return [...out, { op: "branch", alts }];
74
+ }
75
+ sequence() {
76
+ const out = [];
77
+ while (this.i < this.s.length && this.s[this.i] !== "|" && this.s[this.i] !== ")") {
78
+ const c = this.s[this.i];
79
+ if ("*+?{".includes(c)) {
80
+ const [min, max] = this.repeat();
81
+ if (this.s[this.i] === "?")
82
+ this.i++; // lazy: the same whether it matches
83
+ if (this.i < this.s.length && "*+?{".includes(this.s[this.i]))
84
+ this.fail("multiple repeat");
85
+ const last = out.pop();
86
+ if (!last || last.op === "at")
87
+ this.fail("nothing to repeat");
88
+ if (last.op === "repeat")
89
+ this.fail("multiple repeat");
90
+ out.push({ op: "repeat", min, max, body: last.op === "group" ? last.body : [last] });
91
+ continue;
92
+ }
93
+ out.push(this.atom());
94
+ }
95
+ // sre's _parse: a non-capturing group no repeat took is its nodes, in its place (`(?:a)|b` is a class)
96
+ return out.flatMap((n) => n.op === "group" && !n.capture ? n.body : [n]);
97
+ }
98
+ repeat() {
99
+ const c = this.s[this.i++];
100
+ if (c === "*")
101
+ return [0, Infinity];
102
+ if (c === "+")
103
+ return [1, Infinity];
104
+ if (c === "?")
105
+ return [0, 1];
106
+ const m = /^\{(\d+)(,(\d*))?\}/.exec(this.s.slice(this.i - 1, this.i + 40).join(""));
107
+ if (!m)
108
+ this.fail("a literal { must be escaped, and a repeat needs a lower bound");
109
+ this.i += m[0].length - 1;
110
+ const min = Number(m[1]), max = m[2] === undefined ? min : m[3] === "" ? Infinity : Number(m[3]);
111
+ if (max < min)
112
+ this.fail("min repeat greater than max repeat");
113
+ return [min, max];
114
+ }
115
+ atom() {
116
+ const c = this.s[this.i++];
117
+ if (c === "(") {
118
+ const capture = this.s[this.i] !== "?" || this.s[this.i + 1] !== ":";
119
+ if (this.s[this.i] === "?") {
120
+ if (this.s[this.i + 1] === ":")
121
+ this.i += 2;
122
+ else if (this.s[this.i + 1] === "P" && this.s[this.i + 2] === "<") {
123
+ const end = this.s.indexOf(">", this.i + 3);
124
+ const name = end < 0 ? "" : this.s.slice(this.i + 3, end).join("");
125
+ // (Python's str.isidentifier, near enough: a letter or _, then letters, digits, marks or _)
126
+ if (!/^[\p{L}\p{Nl}_][\p{L}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/u.test(name))
127
+ this.fail(`bad character in group name ${name}`);
128
+ if (this.names.has(name))
129
+ this.fail(`redefinition of group name ${name}`);
130
+ this.names.add(name);
131
+ this.i = end + 1;
132
+ }
133
+ else
134
+ this.fail("only (?: and (?P< groups are allowed (no flags, lookaround or comments)");
135
+ }
136
+ const body = this.alternation();
137
+ if (this.s[this.i++] !== ")")
138
+ this.fail("missing ), unterminated subpattern");
139
+ return { op: "group", body, capture };
140
+ }
141
+ if (c === ")")
142
+ this.fail("unbalanced parenthesis");
143
+ if (c === "[")
144
+ return this.set();
145
+ if (c === ".")
146
+ return { op: "char", kind: "any", items: [] };
147
+ if (c === "^")
148
+ return { op: "at", kind: "begin" };
149
+ if (c === "$")
150
+ return { op: "at", kind: "end" };
151
+ if (c === "\\") {
152
+ const e = this.escape(false);
153
+ return typeof e === "string" ? { op: "at", kind: e } : e[0] === "C" ? { op: "char", kind: "in", items: [e] }
154
+ : { op: "char", kind: "lit", items: [e] };
155
+ }
156
+ return { op: "char", kind: "lit", items: [["L", c.codePointAt(0)]] };
157
+ }
158
+ /** The class item an escape names; outside a class \A \b are the assertions "beginstr", "boundary". */
159
+ escape(inClass) {
160
+ const e = this.s[this.i++];
161
+ if (e === undefined)
162
+ this.fail("bad escape (end of pattern)");
163
+ if (e === "x") {
164
+ const h = this.s.slice(this.i, this.i + 2).join("");
165
+ if (!/^[0-9a-fA-F]{2}$/.test(h))
166
+ this.fail("escape \\x is outside the RE2 subset");
167
+ this.i += 2;
168
+ return ["L", parseInt(h, 16)];
169
+ }
170
+ if (/^[0-9A-Za-z]$/.test(e) && !(inClass ? CLASS_ESCAPES : ESCAPES).has(e) || e.codePointAt(0) > 127)
171
+ this.fail(`escape \\${e} is outside the RE2 subset`);
172
+ if (CONTROL[e])
173
+ return ["L", CONTROL[e].codePointAt(0)];
174
+ if (CATS[e])
175
+ return ["C", e];
176
+ if (e === "A")
177
+ return "beginstr";
178
+ if (e === "b")
179
+ return "boundary";
180
+ return ["L", e.codePointAt(0)]; // punctuation, as itself
181
+ }
182
+ /** sre's character set: its items, each once; one literal is a literal (negated: notlit). */
183
+ set() {
184
+ const negate = this.s[this.i] === "^";
185
+ if (negate)
186
+ this.i++;
187
+ const items = [];
188
+ const one = (c) => {
189
+ if (c === "[")
190
+ this.fail("nested sets and [: :] classes are outside the RE2 subset; escape a literal [");
191
+ return c === "\\" ? this.escape(true) : ["L", c.codePointAt(0)];
192
+ };
193
+ for (;;) {
194
+ const c = this.s[this.i++];
195
+ if (c === undefined)
196
+ this.fail("unterminated character set");
197
+ if (c === "]" && items.length)
198
+ break;
199
+ const lo = one(c);
200
+ if (this.s[this.i] === "-" && this.s[this.i + 1] !== "]" && this.s[this.i + 1] !== undefined) {
201
+ this.i++;
202
+ const hi = one(this.s[this.i++]);
203
+ if (lo[0] !== "L" || hi[0] !== "L" || hi[1] < lo[1])
204
+ this.fail("bad character range");
205
+ items.push(["R", lo[1], hi[1]]);
206
+ }
207
+ else
208
+ items.push(lo);
209
+ }
210
+ const u = uniq(items);
211
+ const cat = (x) => u.some((it) => it[0] === "C" && it[1] === x);
212
+ if (negate && (cat("d") && cat("D") || cat("w") && cat("W"))) // compile.py _walk's
213
+ this.fail("a negated class of an escape and its complement ([^\\w\\W]) matches nothing, and the fallback engine "
214
+ + "reads it as any character");
215
+ return u.length === 1 && u[0][0] === "L" ? { op: "char", kind: negate ? "notlit" : "lit", items: u }
216
+ : { op: "char", kind: negate ? "notin" : "in", items: u };
217
+ }
218
+ }
219
+ /** compile.py _risky: an unbounded repeat whose body itself begins with an unbounded repeat ((a+)+). */
220
+ function risky(items) {
221
+ const unbounded = (n) => n.op === "repeat" && n.max === Infinity;
222
+ const starts = (seq) => seq.length > 0 && (unbounded(seq[0]) || seq[0].op === "group"
223
+ && starts(seq[0].body) || seq[0].op === "branch" && seq[0].alts.some(starts));
224
+ return items.some((n) => n.op === "repeat" ? unbounded(n) && starts(n.body) || risky(n.body)
225
+ : n.op === "group" ? risky(n.body) : n.op === "branch" && n.alts.some(risky));
226
+ }
227
+ /** compile.py _walk: nested repeat counts multiply to at most MAX_REPEAT. */
228
+ function walk(items, room = MAX_REPEAT) {
229
+ for (const n of items) {
230
+ if (n.op === "repeat") {
231
+ const count = n.max === Infinity ? n.min : n.max;
232
+ if (count > room)
233
+ throw new PolicyError(`repeat counts above ${MAX_REPEAT}, nested ones multiplied, are outside the RE2 subset`);
234
+ walk(n.body, Math.floor(room / Math.max(count, 1)));
235
+ }
236
+ else if (n.op === "group")
237
+ walk(n.body, room);
238
+ else if (n.op === "branch")
239
+ for (const a of n.alts)
240
+ walk(a, room);
241
+ }
242
+ }
243
+ function emit(items, prog) {
244
+ for (const n of items) {
245
+ if (prog.length > MAX_PROGRAM)
246
+ throw new PolicyError(`the pattern compiles to more than ${MAX_PROGRAM} instructions`);
247
+ if (n.op === "char")
248
+ prog.push(["char", charTest(n)]);
249
+ else if (n.op === "at")
250
+ prog.push(["at", n.kind]);
251
+ else if (n.op === "group")
252
+ emit(n.body, prog);
253
+ else if (n.op === "branch") {
254
+ const ends = [];
255
+ for (const alt of n.alts.slice(0, -1)) {
256
+ const at = prog.length;
257
+ prog.push(null);
258
+ emit(alt, prog);
259
+ ends.push(prog.length);
260
+ prog.push(null);
261
+ prog[at] = ["split", at + 1, prog.length];
262
+ }
263
+ emit(n.alts[n.alts.length - 1], prog);
264
+ for (const at of ends)
265
+ prog[at] = ["jmp", prog.length];
266
+ }
267
+ else {
268
+ for (let k = 0; k < n.min; k++)
269
+ emit(n.body, prog);
270
+ if (n.max === Infinity) {
271
+ const at = prog.length;
272
+ prog.push(null);
273
+ emit(n.body, prog);
274
+ prog.push(["jmp", at]);
275
+ prog[at] = ["split", at + 1, prog.length];
276
+ }
277
+ else {
278
+ const outs = [];
279
+ for (let k = n.min; k < n.max; k++) {
280
+ outs.push(prog.length);
281
+ prog.push(null);
282
+ emit(n.body, prog);
283
+ }
284
+ for (const at of outs)
285
+ prog[at] = ["split", at + 1, prog.length];
286
+ }
287
+ }
288
+ }
289
+ }
290
+ export class Pattern {
291
+ prog;
292
+ found = new Map();
293
+ constructor(pattern) {
294
+ const p = new Parser([...pattern]);
295
+ const items = p.alternation();
296
+ if (p.i < p.s.length)
297
+ p.fail("unbalanced parenthesis");
298
+ if (risky(items))
299
+ throw new PolicyError("regex has a repeat of a repeat (e.g. '(a+)+'), which can hang matching");
300
+ walk(items);
301
+ const prog = [];
302
+ emit(items, prog);
303
+ prog.push(["match"]);
304
+ if (prog.length > MAX_PROGRAM)
305
+ throw new PolicyError(`the pattern compiles to more than ${MAX_PROGRAM} instructions`);
306
+ this.prog = prog;
307
+ }
308
+ at(kind, t, i) {
309
+ if (kind === "begin" || kind === "beginstr")
310
+ return i === 0;
311
+ if (kind === "end")
312
+ return i === t.length;
313
+ return (i > 0 && isWord(t[i - 1])) !== (i < t.length && isWord(t[i])); // \b
314
+ }
315
+ /** Whether the pattern matches somewhere in `text`, spending `budget`; a text searched before is answered again. */
316
+ search(text, budget) {
317
+ if (!this.found.has(text))
318
+ this.found.set(text, this.run([...text], budget));
319
+ return this.found.get(text);
320
+ }
321
+ run(t, budget) {
322
+ let threads = [];
323
+ for (let i = 0; i <= t.length; i++) {
324
+ const seen = new Set(), ready = [];
325
+ for (const start of [...threads, 0]) {
326
+ const stack = [start];
327
+ while (stack.length) {
328
+ const pc = stack.pop();
329
+ if (seen.has(pc))
330
+ continue;
331
+ seen.add(pc);
332
+ budget.spend(1);
333
+ const ins = this.prog[pc];
334
+ if (ins[0] === "match")
335
+ return true;
336
+ if (ins[0] === "jmp")
337
+ stack.push(ins[1]);
338
+ else if (ins[0] === "split")
339
+ stack.push(ins[2], ins[1]);
340
+ else if (ins[0] === "at") {
341
+ if (this.at(ins[1], t, i))
342
+ stack.push(pc + 1);
343
+ }
344
+ else
345
+ ready.push(pc);
346
+ }
347
+ }
348
+ if (i === t.length)
349
+ return false;
350
+ budget.spend(ready.length);
351
+ threads = ready.filter((pc) => this.prog[pc][1](t[i])).map((pc) => pc + 1);
352
+ }
353
+ return false;
354
+ }
355
+ }