@xtrom-ai/sdk 0.0.0-stage → 0.7.1
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/LICENSE +190 -0
- package/README.md +185 -2
- package/dist/allowances.js +74 -0
- package/dist/cli.js +268 -0
- package/dist/credentials.js +37 -0
- package/dist/directive.js +57 -0
- package/dist/enforce.js +972 -0
- package/dist/index.js +31 -0
- package/dist/inspect.js +135 -0
- package/dist/local/agents.js +378 -0
- package/dist/local/appliers.js +61 -0
- package/dist/local/browser.js +135 -0
- package/dist/local/discover.js +154 -0
- package/dist/local/hook.js +778 -0
- package/dist/local/install.js +238 -0
- package/dist/local/inventory.js +219 -0
- package/dist/local/reasonText.js +29 -0
- package/dist/local/shipper.js +251 -0
- package/dist/local/spool.js +178 -0
- package/dist/local/updateKeys.js +3 -0
- package/dist/local/updater.js +224 -0
- package/dist/local/view.js +110 -0
- package/dist/memory.js +172 -0
- package/dist/reporter.js +336 -0
- package/dist/session.js +439 -0
- package/dist/version.js +2 -0
- package/dist/workspace.js +72 -0
- package/package.json +23 -4
- package/src/allowances.ts +74 -0
- package/src/cli.ts +268 -0
- package/src/credentials.ts +37 -0
- package/src/directive.ts +57 -0
- package/src/enforce.ts +972 -0
- package/src/index.ts +31 -0
- package/src/inspect.ts +135 -0
- package/src/local/agents.ts +378 -0
- package/src/local/appliers.ts +61 -0
- package/src/local/browser.ts +135 -0
- package/src/local/discover.ts +154 -0
- package/src/local/hook.ts +778 -0
- package/src/local/install.ts +238 -0
- package/src/local/inventory.ts +219 -0
- package/src/local/reasonText.ts +29 -0
- package/src/local/shipper.ts +251 -0
- package/src/local/spool.ts +178 -0
- package/src/local/updateKeys.ts +3 -0
- package/src/local/updater.ts +224 -0
- package/src/local/view.ts +110 -0
- package/src/memory.ts +172 -0
- package/src/reporter.ts +336 -0
- package/src/session.ts +439 -0
- package/src/version.ts +2 -0
- package/src/workspace.ts +72 -0
package/dist/enforce.js
ADDED
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
// Xtrom enforcement core (TypeScript) — deterministic taint/IFC + policy + risk fusion.
|
|
2
|
+
// A rule-for-rule port of the Python reference engine (xtrom-engine/xtrom/core.py `_authorize`).
|
|
3
|
+
// Parity is gated by test/parity.test.ts (shared golden vectors + a differential fuzz against Python).
|
|
4
|
+
import { DEFAULT_MEMORY_READ_ACTIONS, DEFAULT_MEMORY_WRITE_ACTIONS } from "./memory.js";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
export const Sensitivity = { LOW: 0, MEDIUM: 1, HIGH: 2 } ;
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_SENSITIVITY = Object.freeze({
|
|
46
|
+
read_file: 0, query_ledger: 0, list_dir: 0, git_commit: 1, http_fetch: 1,
|
|
47
|
+
send_email: 2, http_post: 2, wire_transfer: 2, kms_decrypt: 2,
|
|
48
|
+
execute_shell: 2, rds_delete: 2, kubectl_delete: 2, terraform_apply: 2,
|
|
49
|
+
});
|
|
50
|
+
export const EGRESS_ACTIONS = new Set(["http_post", "http_fetch", "send_email"]);
|
|
51
|
+
export const DESTRUCTIVE_ACTIONS = new Set(["rds_delete", "kubectl_delete", "terraform_apply", "execute_shell"]);
|
|
52
|
+
/** A wire_transfer above this asks a person; a policy may lower it, never raise it (docs/design/POLICY-THRESHOLDS.md). */
|
|
53
|
+
export const TRANSFER_STEPUP_THRESHOLD = 10_000;
|
|
54
|
+
export const SINK_ACTIONS = new Set([
|
|
55
|
+
...EGRESS_ACTIONS, ...DESTRUCTIVE_ACTIONS, "git_commit", "wire_transfer", "kms_decrypt", "send_email",
|
|
56
|
+
]);
|
|
57
|
+
export const FINANCIAL_ACTIONS = new Set(["wire_transfer"]);
|
|
58
|
+
export const CREDENTIAL_ACTIONS = new Set(["kms_decrypt", "get_secret", "assume_role", "create_access_key"]);
|
|
59
|
+
|
|
60
|
+
export const ReasonCode = Object.freeze({
|
|
61
|
+
SCOPE_DENY: "scope.deny",
|
|
62
|
+
IFC_UNTRUSTED_TO_SINK: "ifc.untrusted_to_sink",
|
|
63
|
+
SECRET_EGRESS_DENY: "egress.secret_non_allowlisted",
|
|
64
|
+
SECRET_TO_SINK_STEPUP: "egress.secret_to_durable_sink",
|
|
65
|
+
DESTRUCTIVE_STEPUP: "policy.destructive_prod_stepup",
|
|
66
|
+
TRANSFER_THRESHOLD_STEPUP: "policy.transfer_threshold_stepup",
|
|
67
|
+
CONTEXT_TAINT_STEPUP: "ifc.context_tainted_stepup",
|
|
68
|
+
UNTRUSTED_CONTENT_STEPUP: "ifc.untrusted_content_stepup",
|
|
69
|
+
RISK_HIGH_BLOCK: "risk.high_block",
|
|
70
|
+
RISK_ELEVATED_STEPUP: "risk.elevated_stepup",
|
|
71
|
+
PLANNED_CALL: "plan.planned_call",
|
|
72
|
+
ALLOWLISTED_READ: "ifc.allowlisted_read",
|
|
73
|
+
ALLOW_WITHIN_POLICY: "policy.allow",
|
|
74
|
+
FAIL_CLOSED: "fail_closed",
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
export const DEFAULT_DESTINATION_ARGS = new Set([
|
|
78
|
+
"to", "cc", "bcc", "recipient", "recipients", "email", "emails", "address", "url", "uri",
|
|
79
|
+
"host", "domain", "endpoint", "webhook", "iban", "account", "phone", "channel", "user",
|
|
80
|
+
"users", "participants", "attendees", "member", "members", "destination", "dest", "target",
|
|
81
|
+
"remote", "repo", "bucket",
|
|
82
|
+
]);
|
|
83
|
+
|
|
84
|
+
// ─────────────────────────── secret / entropy detection (L0) ───────────────────────────
|
|
85
|
+
// Same patterns, same order as xtrom.core._SECRET_PATTERNS (the hooks map index → secret type).
|
|
86
|
+
export const SECRET_RX = [
|
|
87
|
+
/AKIA[0-9A-Z]{16}/,
|
|
88
|
+
/aws_secret_access_key/i,
|
|
89
|
+
/gh[pousr]_[A-Za-z0-9]{20,}/,
|
|
90
|
+
/sk-[A-Za-z0-9]{20,}/,
|
|
91
|
+
/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/,
|
|
92
|
+
/(password|passwd|secret|api[_-]?key|token)\s*[=:]\s*\S+/i,
|
|
93
|
+
/postgres(?:ql)?:\/\/\S+:\S+@\S+/,
|
|
94
|
+
/:\/\/[^\s/:@]+:[^\s/@]+@/, // any URL carrying a password (user:pass@); starts at "://" so it stays linear
|
|
95
|
+
];
|
|
96
|
+
const ENCODED_SECRET_MIN_LEN = 6;
|
|
97
|
+
const ENCODING_TOKEN_RX = /[A-Za-z0-9+/_%-]{8,}={0,2}/g;
|
|
98
|
+
|
|
99
|
+
export function encodedVariants(secret , minLen = ENCODED_SECRET_MIN_LEN) {
|
|
100
|
+
const s = safeStr(secret);
|
|
101
|
+
if ([...s].length < minLen) return [];
|
|
102
|
+
const b64 = Buffer.from(s, "utf8").toString("base64");
|
|
103
|
+
const b64url = Buffer.from(s, "utf8").toString("base64url");
|
|
104
|
+
return [...new Set([
|
|
105
|
+
s, b64, b64.replace(/=+$/g, ""), b64url, b64url.replace(/=+$/g, ""),
|
|
106
|
+
Buffer.from(s, "utf8").toString("hex"),
|
|
107
|
+
Buffer.from(s, "utf8").toString("hex").toUpperCase(),
|
|
108
|
+
encodeURIComponent(s), [...s].reverse().join(""),
|
|
109
|
+
].filter((v) => [...v].length >= minLen))].sort();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function decodedViews(text ) {
|
|
113
|
+
const s = safeStr(text);
|
|
114
|
+
const out = new Set ([s, [...s].reverse().join("")]);
|
|
115
|
+
for (const m of s.matchAll(ENCODING_TOKEN_RX)) {
|
|
116
|
+
const tok = m[0], bare = tok.replace(/=+$/g, "");
|
|
117
|
+
if (out.size >= 32) break;
|
|
118
|
+
if (tok.includes("%")) {
|
|
119
|
+
try {
|
|
120
|
+
const u = decodeURIComponent(tok);
|
|
121
|
+
if (u !== tok) out.add(u);
|
|
122
|
+
} catch { /* ignore */ }
|
|
123
|
+
}
|
|
124
|
+
for (const enc of ["base64", "base64url"] ) {
|
|
125
|
+
try {
|
|
126
|
+
const v = Buffer.from(bare, enc).toString("utf8");
|
|
127
|
+
if (v) out.add(v);
|
|
128
|
+
} catch { /* ignore */ }
|
|
129
|
+
}
|
|
130
|
+
if (bare.length >= 12 && bare.length % 2 === 0 && /^[0-9A-Fa-f]+$/.test(bare)) {
|
|
131
|
+
try {
|
|
132
|
+
const v = Buffer.from(bare, "hex").toString("utf8");
|
|
133
|
+
if (v) out.add(v);
|
|
134
|
+
} catch { /* ignore */ }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return [...out].filter(Boolean);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** str() that never throws on hostile input (mirrors core._safe_str). */
|
|
141
|
+
export function safeStr(data ) {
|
|
142
|
+
try {
|
|
143
|
+
return String(data);
|
|
144
|
+
} catch {
|
|
145
|
+
return "<unstringable>";
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function shannon(s ) {
|
|
150
|
+
const chars = [...s];
|
|
151
|
+
if (!chars.length) return 0;
|
|
152
|
+
const counts = new Map ();
|
|
153
|
+
for (const c of chars) counts.set(c, (counts.get(c) ?? 0) + 1);
|
|
154
|
+
let h = 0;
|
|
155
|
+
for (const n of counts.values()) h -= (n / chars.length) * Math.log2(n / chars.length);
|
|
156
|
+
return h;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Precise credential patterns only (no entropy heuristic). */
|
|
160
|
+
export function matchesSecretPattern(text ) {
|
|
161
|
+
const s = typeof text === "string" ? text : safeStr(text);
|
|
162
|
+
return decodedViews(s).some((view) => SECRET_RX.some((rx) => rx.test(view)));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Advisory backstop only — authoritative labels come from `secret()` and policy fingerprints. */
|
|
166
|
+
export function looksLikeSecret(text ) {
|
|
167
|
+
const s = typeof text === "string" ? text : safeStr(text);
|
|
168
|
+
if (matchesSecretPattern(s)) return true;
|
|
169
|
+
for (const tok of s.split(/\s+/)) {
|
|
170
|
+
const [parts, split] = entropyCandidates(tok);
|
|
171
|
+
for (const part of parts) {
|
|
172
|
+
if (WORDY_RX.test(part)) continue; // words joined by . _ - (billing_support_archive): a name, not a key
|
|
173
|
+
const n = [...part].length;
|
|
174
|
+
if (n >= 20 && shannon(part) > 4.0) return true;
|
|
175
|
+
// Hex tops out at 4.0 bits/char: inside a URL or address it was only caught by its surroundings.
|
|
176
|
+
if (split && n >= 32 && HEX_RX.test(part)) return true;
|
|
177
|
+
// A short random secret split out of a URL: mixed case and digits is the tell.
|
|
178
|
+
if (split && n >= 20 && shannon(part) > 3.5 && charClasses(part) >= 3) return true;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Two or more word-like segments (a letter, then lowercase, then up to six digits) joined by . _ or -;
|
|
185
|
+
// separators can't occur inside a segment, so matching is linear.
|
|
186
|
+
const WORDY_RX = /^[A-Za-z][a-z]{1,15}[0-9]{0,6}(?:[._-][A-Za-z][a-z]{1,15}[0-9]{0,6})+$/;
|
|
187
|
+
const URL_TOKEN_RX = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//;
|
|
188
|
+
const EMAIL_TOKEN_RX = /^([^@\s]+)@([A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,24}$/;
|
|
189
|
+
// The last label is a top-level-domain shape (letters only), so a JWT (dot-separated base64) is never a host.
|
|
190
|
+
const HOST_TOKEN_RX = /^(?=.{4,253}$)([A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,24}\.?(:\d{1,5})?$/;
|
|
191
|
+
// One way to match each character (a "/" before every segment): no nested-quantifier backtracking (ReDoS).
|
|
192
|
+
const PATH_TOKEN_RX = /^(?:~|\.{1,2})?(?:\/[A-Za-z0-9._-]+)+\/?$/;
|
|
193
|
+
const HEX_RX = /^[0-9A-Fa-f]+$/;
|
|
194
|
+
const charClasses = (s ) => [/[a-z]/, /[A-Z]/, /[0-9]/].filter((rx) => rx.test(s)).length;
|
|
195
|
+
|
|
196
|
+
/** The parts of one token the entropy check judges (parity with xtrom-engine `_entropy_candidates`): a URL →
|
|
197
|
+
* user-info, path segments, each query value and the fragment, never scheme or host; an email → local part;
|
|
198
|
+
* a hostname → nothing; a plain file path → segments; anything else → whole. Returns [parts, split]. */
|
|
199
|
+
// The labels left of a host's last two (`<data>.evil.example` → [<data>]): the registrable name can't carry
|
|
200
|
+
// a secret, but labels in front of it can (DNS exfiltration).
|
|
201
|
+
function subdomainLabels(host ) {
|
|
202
|
+
return host.split(":")[0].replace(/\.+$/, "").split(".").slice(0, -2);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function entropyCandidates(tok ) {
|
|
206
|
+
const m = URL_TOKEN_RX.exec(tok);
|
|
207
|
+
if (m) {
|
|
208
|
+
const rest = tok.slice(m[0].length);
|
|
209
|
+
const cuts = ["/", "?", "#", "\\"].map((c) => rest.indexOf(c)).filter((i) => i >= 0);
|
|
210
|
+
const cut = cuts.length ? Math.min(...cuts) : rest.length;
|
|
211
|
+
const authority = rest.slice(0, cut), tail = rest.slice(cut);
|
|
212
|
+
const parts = authority.includes("@") ? authority.slice(0, authority.lastIndexOf("@")).split(":") : [];
|
|
213
|
+
parts.push(...subdomainLabels(authority.slice(authority.lastIndexOf("@") + 1)));
|
|
214
|
+
const qi = tail.indexOf("?");
|
|
215
|
+
let path = qi >= 0 ? tail.slice(0, qi) : tail, query = qi >= 0 ? tail.slice(qi + 1) : "", frag = "";
|
|
216
|
+
if (qi >= 0) { const h = query.indexOf("#"); if (h >= 0) { frag = query.slice(h + 1); query = query.slice(0, h); } }
|
|
217
|
+
else { const h = path.indexOf("#"); if (h >= 0) { frag = path.slice(h + 1); path = path.slice(0, h); } }
|
|
218
|
+
parts.push(...path.split(/[/\\]/).filter(Boolean));
|
|
219
|
+
// Query values are judged whole (base64 often carries an unencoded "/"); the key is never secret.
|
|
220
|
+
for (const kv of query.split("&").filter(Boolean)) { const e = kv.indexOf("="); parts.push(e >= 0 ? kv.slice(e + 1) || kv : kv); }
|
|
221
|
+
if (frag) parts.push(frag);
|
|
222
|
+
return [parts.filter(Boolean), true];
|
|
223
|
+
}
|
|
224
|
+
const em = EMAIL_TOKEN_RX.exec(tok);
|
|
225
|
+
if (em) return [[em[1], ...subdomainLabels(tok.slice(tok.lastIndexOf("@") + 1))], true];
|
|
226
|
+
if (HOST_TOKEN_RX.test(tok)) return [subdomainLabels(tok), true];
|
|
227
|
+
if (PATH_TOKEN_RX.test(tok)) return [tok.split("/").filter(Boolean), true];
|
|
228
|
+
return [[tok], false];
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ─────────────────────────────────── policy (L4) ───────────────────────────────────
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
export function isFetch(action , policy ) {
|
|
267
|
+
if (action === "http_fetch") return true;
|
|
268
|
+
return (policy?.fetchActions?.has(action) ?? false) && !SINK_ACTIONS.has(action) && !isDestructive(action, policy)
|
|
269
|
+
&& !writeLikeName(action);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Name tokens that make a tool a write, never a fetch. Parity: core.WRITE_VERBS. */
|
|
273
|
+
export const WRITE_VERBS = new Set([
|
|
274
|
+
"add", "append", "approve", "assign", "book", "call", "cancel", "charge", "chmod", "comment", "commit", "create",
|
|
275
|
+
"delete", "deploy", "destroy", "drop", "edit", "email", "eval", "exec", "execute", "forward", "grant", "insert",
|
|
276
|
+
"invite", "invoke", "kill", "merge", "message", "modify", "move", "notify", "patch", "pay", "payment", "post",
|
|
277
|
+
"publish", "purge", "push", "put", "remove", "rename", "reserve", "schedule", "send", "set", "share", "shell",
|
|
278
|
+
"transfer", "update", "upload", "wire", "write",
|
|
279
|
+
]);
|
|
280
|
+
|
|
281
|
+
/** Any token of the tool's name (after "mcp:", split on _ - . : / and camelCase) is a write verb. */
|
|
282
|
+
export function writeLikeName(tool ) {
|
|
283
|
+
const name = tool.startsWith("mcp:") ? tool.slice(4) : tool;
|
|
284
|
+
return name.replace(/(?<=.)([A-Z])/g, "_$1").toLowerCase().split(/[_\-.:/]+/).some((t) => t && WRITE_VERBS.has(t));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** The transfer hold in force: the policy's when above 0 and at most the built-in, else the built-in. */
|
|
288
|
+
export function transferThreshold(policy ) {
|
|
289
|
+
const t = policy?.transferStepupThreshold;
|
|
290
|
+
return typeof t === "number" && t > 0 && t <= TRANSFER_STEPUP_THRESHOLD ? t : TRANSFER_STEPUP_THRESHOLD;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function isDestructive(action , policy ) {
|
|
294
|
+
return DESTRUCTIVE_ACTIONS.has(action) || (policy?.destructiveActions?.has(action) ?? false);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function defaultPolicy() {
|
|
298
|
+
return {
|
|
299
|
+
capabilities: new Set([
|
|
300
|
+
"read_file", "query_ledger", "list_dir", "git_commit",
|
|
301
|
+
"send_email", "http_post", "http_fetch", "wire_transfer", "kms_decrypt",
|
|
302
|
+
]),
|
|
303
|
+
allowlistHosts: new Set (),
|
|
304
|
+
env: "prod",
|
|
305
|
+
sensitivity: { ...DEFAULT_SENSITIVITY },
|
|
306
|
+
failClosed: true,
|
|
307
|
+
version: "",
|
|
308
|
+
secretFingerprints: new Set (),
|
|
309
|
+
contextTaintExempt: new Set (),
|
|
310
|
+
untrustedContentStepup: false,
|
|
311
|
+
destinationArgs: new Set(DEFAULT_DESTINATION_ARGS),
|
|
312
|
+
knownDestinations: new Set (),
|
|
313
|
+
memoryWriteActions: new Set(DEFAULT_MEMORY_WRITE_ACTIONS),
|
|
314
|
+
memoryReadActions: new Set(DEFAULT_MEMORY_READ_ACTIONS),
|
|
315
|
+
memoryUnknown: "untrusted",
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Policy-aware sensitivity. Unknown actions are HIGH unless the policy opts out of fail-closed. */
|
|
320
|
+
export function sensitivity(action , policy ) {
|
|
321
|
+
const table = policy?.sensitivity ?? DEFAULT_SENSITIVITY;
|
|
322
|
+
if (Object.hasOwn(table, action)) return table[action];
|
|
323
|
+
return policy?.failClosed === false ? Sensitivity.LOW : Sensitivity.HIGH;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export function isKnownSecret(policy , data ) {
|
|
327
|
+
const fps = policy?.secretFingerprints;
|
|
328
|
+
if (!fps || fps.size === 0) return false;
|
|
329
|
+
return decodedViews(data).some((view) => fps.has(createHash("sha256").update(view).digest("hex")));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function sinkClass(action , policy ) {
|
|
333
|
+
if (EGRESS_ACTIONS.has(action)) return "egress";
|
|
334
|
+
if (isDestructive(action, policy)) return "destructive";
|
|
335
|
+
if (FINANCIAL_ACTIONS.has(action)) return "financial";
|
|
336
|
+
if (CREDENTIAL_ACTIONS.has(action)) return "credential";
|
|
337
|
+
if (sensitivity(action, policy) === Sensitivity.LOW && !SINK_ACTIONS.has(action)) return "read";
|
|
338
|
+
return "write";
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const ORIGIN_TAG_RX = /^[a-z][a-z0-9_.-]{0,31}(?::[A-Za-z0-9_.-]{1,48})?$/;
|
|
342
|
+
|
|
343
|
+
/** Reduce a free-text origin to a coarse, privacy-safe telemetry tag ('file:/etc/x' → 'file'). */
|
|
344
|
+
export function originTag(origin ) {
|
|
345
|
+
const first = safeStr(origin).split(",")[0].trim();
|
|
346
|
+
const parts = first.split(":");
|
|
347
|
+
const kind = parts[0].toLowerCase();
|
|
348
|
+
const tag = ["tool", "mcp", "session"].includes(kind) && parts.length > 1 ? `${kind}:${parts[1]}` : kind;
|
|
349
|
+
if (!ORIGIN_TAG_RX.test(tag) || looksLikeSecret(tag)) return "other";
|
|
350
|
+
return tag;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function taintTags(labels , limit = 8) {
|
|
354
|
+
const tags = new Set ();
|
|
355
|
+
for (const l of labels) {
|
|
356
|
+
for (const o of safeStr(l.origin).split(", ")) {
|
|
357
|
+
tags.add(originTag(o));
|
|
358
|
+
if (tags.size >= limit) return [...tags];
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return [...tags];
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export function isDestinationArg(name , tokens = DEFAULT_DESTINATION_ARGS) {
|
|
365
|
+
return safeStr(name).toLowerCase().split("_").some((t) => tokens.has(t));
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// ─────────────────────────────── value constructors ───────────────────────────────
|
|
369
|
+
export function trusted(data , origin , policy ) {
|
|
370
|
+
return { data, label: { trust: "TRUSTED", isSecret: isKnownSecret(policy, data) || looksLikeSecret(data), origin } };
|
|
371
|
+
}
|
|
372
|
+
export function untrusted(data , origin , policy ) {
|
|
373
|
+
return { data, label: { trust: "UNTRUSTED", isSecret: isKnownSecret(policy, data) || looksLikeSecret(data), origin } };
|
|
374
|
+
}
|
|
375
|
+
/** Explicit secret ingress (e.g. broker-minted credentials): TRUSTED + secret, unconditionally. */
|
|
376
|
+
export function secret(data , origin ) {
|
|
377
|
+
return { data, label: { trust: "TRUSTED", isSecret: true, origin } };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Labels values by provenance with anti-laundering, like the Python `Engine.trusted()` /
|
|
381
|
+
* `untrusted()`. Every untrusted value's sha256 fingerprint is remembered in a bounded recency
|
|
382
|
+
* window; with `strict` (the default), `trusted()` on a VERBATIM copy of one returns it UNTRUSTED
|
|
383
|
+
* (origin `strict_ingress:refused_launder:<origin>`) instead of blessing it. Exact match only: a
|
|
384
|
+
* backstop for `trusted(String(untrustedValue.data))`, not a guarantee against transformed copies
|
|
385
|
+
* (route tool output through `untrusted()` and let taint propagate — the Session does this). */
|
|
386
|
+
export class Ingress {
|
|
387
|
+
static WINDOW = 4096;
|
|
388
|
+
strict ;
|
|
389
|
+
policy ;
|
|
390
|
+
window = [];
|
|
391
|
+
seen = new Map (); // fingerprint → copies in the window
|
|
392
|
+
|
|
393
|
+
constructor(opts = {}) {
|
|
394
|
+
this.strict = opts.strict ?? true;
|
|
395
|
+
this.policy = opts.policy;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
static fingerprint(data ) {
|
|
399
|
+
return createHash("sha256").update(safeStr(data)).digest("hex");
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
record(data ) {
|
|
403
|
+
const fp = Ingress.fingerprint(data);
|
|
404
|
+
if (this.window.length >= Ingress.WINDOW) {
|
|
405
|
+
const old = this.window.shift() ;
|
|
406
|
+
const n = (this.seen.get(old) ?? 1) - 1;
|
|
407
|
+
if (n > 0) this.seen.set(old, n); else this.seen.delete(old);
|
|
408
|
+
}
|
|
409
|
+
this.window.push(fp);
|
|
410
|
+
this.seen.set(fp, (this.seen.get(fp) ?? 0) + 1);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** True if `data` is a verbatim copy of untrusted content still in the window. */
|
|
414
|
+
isLaundered(data ) {
|
|
415
|
+
return this.seen.has(Ingress.fingerprint(data));
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
trusted(data , origin ) {
|
|
419
|
+
if (this.strict && this.isLaundered(data)) return this.untrusted(data, `strict_ingress:refused_launder:${origin}`);
|
|
420
|
+
return trusted(data, origin, this.policy);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
untrusted(data , origin ) {
|
|
424
|
+
this.record(data);
|
|
425
|
+
return untrusted(data, origin, this.policy);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
secret(data , origin ) {
|
|
429
|
+
return secret(data, origin);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export function isValue(v ) {
|
|
434
|
+
if (typeof v !== "object" || v === null || !("label" in v) || !("data" in v)) return false;
|
|
435
|
+
const l = (v ).label;
|
|
436
|
+
return typeof l === "object" && l !== null && (l.trust === "TRUSTED" || l.trust === "UNTRUSTED");
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function rawOf(v ) {
|
|
440
|
+
return isValue(v) ? v.data : v;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// CANONICAL single-value host parse — identical in every engine: only http(s) is parsed; any other or
|
|
444
|
+
// absent scheme returns the raw string (cannot match an allowlist → fail closed). The authority ends at the
|
|
445
|
+
// first / \ ? # (WHATWG: "\" is a path separator for http(s)), and the host is after its LAST '@'.
|
|
446
|
+
function parseHost(s ) {
|
|
447
|
+
let rest ;
|
|
448
|
+
if (s.startsWith("http://")) rest = s.slice(7);
|
|
449
|
+
else if (s.startsWith("https://")) rest = s.slice(8);
|
|
450
|
+
else return s;
|
|
451
|
+
const end = rest.search(/[/\\?#]/);
|
|
452
|
+
if (end >= 0) rest = rest.slice(0, end);
|
|
453
|
+
const at = rest.lastIndexOf("@");
|
|
454
|
+
if (at >= 0) rest = rest.slice(at + 1);
|
|
455
|
+
return rest || null;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// The PRIMARY destination (fixed key priority) — what a decision is labelled with. NOT the egress check:
|
|
459
|
+
// every destination a request names must be allowlisted (egressHosts / egressAllowed).
|
|
460
|
+
export function hostOf(args ) {
|
|
461
|
+
for (const key of ["host", "url", "to", "endpoint"]) {
|
|
462
|
+
if (Object.hasOwn(args, key)) return parseHost(safeStr(rawOf(args[key])));
|
|
463
|
+
}
|
|
464
|
+
return null;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Arg-name tokens that carry WHERE data is sent (per "_"-token: callback_url, webhook_url, redirect_uri,
|
|
468
|
+
// to_address). Narrower than DESTINATION_ARGS on purpose: repo/account/email name a target inside a service.
|
|
469
|
+
export const EGRESS_HOST_TOKENS = new Set(["host", "url", "uri", "endpoint", "webhook", "callback", "destination",
|
|
470
|
+
"dest", "domain", "server", "to"]);
|
|
471
|
+
|
|
472
|
+
/** EVERY destination a request names, in sorted arg-name order: args whose name carries a host token,
|
|
473
|
+
* plus any arg whose whole value is an http(s) URL. Mirrors core._egress_hosts. */
|
|
474
|
+
export function egressHosts(args ) {
|
|
475
|
+
const out = [];
|
|
476
|
+
for (const k of Object.keys(args).sort()) {
|
|
477
|
+
const s = safeStr(rawOf(args[k]));
|
|
478
|
+
if (k.toLowerCase().split("_").some((t) => EGRESS_HOST_TOKENS.has(t)) || s.startsWith("http://") || s.startsWith("https://")) {
|
|
479
|
+
const h = parseHost(s);
|
|
480
|
+
if (h && !out.includes(h)) out.push(h);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return out;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Primary destination allowlisted AND every other destination too — closes the decoy-host evasion
|
|
487
|
+
* (an allowlisted url covering an attacker webhook). Strictly tighter than the primary check alone. */
|
|
488
|
+
export function egressAllowed(args , allow ) {
|
|
489
|
+
const primary = hostOf(args);
|
|
490
|
+
return primary !== null && allow.has(primary) && egressHosts(args).every((h) => allow.has(h));
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** May a secret leave on this call? Canonical egress actions use egressAllowed; any other sink is egress
|
|
494
|
+
* only because it names destinations, so each of those must be allowlisted. Mirrors core._secret_egress_allowed. */
|
|
495
|
+
export function secretEgressAllowed(action , args , allow ) {
|
|
496
|
+
if (EGRESS_ACTIONS.has(action)) return egressAllowed(args, allow);
|
|
497
|
+
const hosts = egressHosts(args);
|
|
498
|
+
return hosts.length > 0 && hosts.every((h) => allow.has(h));
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// Python float() semantics: "1_000_000", "inf" and " 12 " parse; "0x10", "" and objects do not.
|
|
502
|
+
const PY_FLOAT_RX = /^[+-]?(?:\d(?:_?\d)*(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?$/;
|
|
503
|
+
export function amountOf(args ) {
|
|
504
|
+
if (!Object.hasOwn(args, "amount")) return null;
|
|
505
|
+
const v = rawOf(args.amount);
|
|
506
|
+
if (typeof v === "number") return v;
|
|
507
|
+
if (typeof v === "boolean") return v ? 1 : 0;
|
|
508
|
+
if (typeof v === "bigint") return Number(v);
|
|
509
|
+
if (typeof v !== "string") return null;
|
|
510
|
+
const s = v.trim();
|
|
511
|
+
if (/^[+-]?(inf|infinity)$/i.test(s)) return s.startsWith("-") ? -Infinity : Infinity;
|
|
512
|
+
if (/^[+-]?nan$/i.test(s)) return NaN;
|
|
513
|
+
if (!PY_FLOAT_RX.test(s)) return null;
|
|
514
|
+
return Number(s.replaceAll("_", ""));
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
/** tool → field → the list elements that tool returned this session. */
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
/** A plan step: the tool, the values the planner fixed, and typed slots later data may fill
|
|
531
|
+
* (text | number | date | id | enum:a|b|c). Parity with the engine's PlanStep (plan_golden.json). */
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
export const PLAN_TEXT_MAX = 8000;
|
|
541
|
+
export const PLAN_CHOICES_MAX = 1000;
|
|
542
|
+
export const PLAN_CHOICE_LEN_MAX = 256;
|
|
543
|
+
|
|
544
|
+
/** The values a list-chosen destination may take from one tool result (parity: core.extract_choices). Whole
|
|
545
|
+
* elements only: field "" → a JSON array of strings; a field name → an array of objects, each giving its string
|
|
546
|
+
* under that key. A one-key object is unwrapped first and a string is parsed as JSON. Anything else → none. */
|
|
547
|
+
export function extractChoices(result , field ) {
|
|
548
|
+
let v = result;
|
|
549
|
+
if (typeof v === "string") {
|
|
550
|
+
const t = v.trim();
|
|
551
|
+
if (!t.startsWith("[") && !t.startsWith("{")) return [];
|
|
552
|
+
try { v = JSON.parse(t); } catch { return []; }
|
|
553
|
+
}
|
|
554
|
+
if (v !== null && typeof v === "object" && !Array.isArray(v)) {
|
|
555
|
+
const keys = Object.keys(v );
|
|
556
|
+
if (keys.length === 1) v = (v )[keys[0]];
|
|
557
|
+
}
|
|
558
|
+
if (!Array.isArray(v)) return [];
|
|
559
|
+
const out = [];
|
|
560
|
+
for (const e of v.slice(0, PLAN_CHOICES_MAX)) {
|
|
561
|
+
const x = field === "" ? e
|
|
562
|
+
: (e !== null && typeof e === "object" && !Array.isArray(e) ? (e )[field] : undefined);
|
|
563
|
+
if (typeof x === "string" && x.length > 0 && [...x].length <= PLAN_CHOICE_LEN_MAX) out.push(x);
|
|
564
|
+
}
|
|
565
|
+
return out;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function readOnly(policy , tool ) {
|
|
569
|
+
return sensitivity(tool, policy) === Sensitivity.LOW && !SINK_ACTIONS.has(tool) && !isDestructive(tool, policy);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** A list-chosen value: from a read-only source tool's list in this session, and known or from a directory. */
|
|
573
|
+
export function planChoiceOk(src , value , choices ,
|
|
574
|
+
policy ) {
|
|
575
|
+
if (!policy || src === null || typeof src !== "object" || Array.isArray(src)) return false;
|
|
576
|
+
const { tool, field = "" } = src ;
|
|
577
|
+
if (typeof tool !== "string" || !tool || typeof field !== "string" || !readOnly(policy, tool)) return false;
|
|
578
|
+
const s = safeStr(value);
|
|
579
|
+
if (!(choices?.[tool]?.[field]?.has(s) ?? false)) return false;
|
|
580
|
+
return (policy.knownDestinations?.has(s) ?? false) || (policy.directoryTools?.has(tool) ?? false);
|
|
581
|
+
}
|
|
582
|
+
const PLAN_DATE_RX = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2})?)?/;
|
|
583
|
+
const PLAN_ID_RX = /^[A-Za-z0-9_.:@-]{1,128}$/;
|
|
584
|
+
const PLAN_NUM_RX = /^-?\d{1,15}(\.\d{1,6})?$/;
|
|
585
|
+
|
|
586
|
+
export function planSlotOk(kind , value ) {
|
|
587
|
+
const s = safeStr(value);
|
|
588
|
+
if (kind === "text") return [...s].length <= PLAN_TEXT_MAX;
|
|
589
|
+
if (kind === "number") return PLAN_NUM_RX.test(s.trim());
|
|
590
|
+
if (kind === "date") return PLAN_DATE_RX.test(s.trim());
|
|
591
|
+
if (kind === "id") return PLAN_ID_RX.test(s);
|
|
592
|
+
if (kind.startsWith("enum:")) return kind.slice(5).split("|").includes(s);
|
|
593
|
+
return false;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** The call is exactly what the step planned: same tool, every fixed value present and equal, every
|
|
597
|
+
* other argument a declared slot of the right type or a list choice that holds, and no destination
|
|
598
|
+
* argument left to a slot. */
|
|
599
|
+
export function planMatches(step , action , args ,
|
|
600
|
+
choices , policy ) {
|
|
601
|
+
if (!step || step.action !== action) return false;
|
|
602
|
+
const fixed = step.fixed ?? {}, slots = step.slots ?? {}, chosen = step.choose_from ?? {};
|
|
603
|
+
if (Object.keys(slots).some((k) => isDestinationArg(k))) return false;
|
|
604
|
+
if (Object.keys(chosen).some((k) => k in fixed || k in slots)) return false;
|
|
605
|
+
const names = Object.keys(args ?? {});
|
|
606
|
+
if (!Object.keys(fixed).every((k) => names.includes(k))) return false;
|
|
607
|
+
if (!names.every((k) => k in fixed || k in slots || k in chosen)) return false;
|
|
608
|
+
for (const [k, src] of Object.entries(chosen)) {
|
|
609
|
+
if (k in args && !planChoiceOk(src, rawOf(args[k]), choices, policy)) return false;
|
|
610
|
+
}
|
|
611
|
+
for (const [k, want] of Object.entries(fixed)) if (safeStr(rawOf(args[k])) !== safeStr(want)) return false;
|
|
612
|
+
for (const [k, kind] of Object.entries(slots)) if (k in args && !planSlotOk(String(kind), rawOf(args[k]))) return false;
|
|
613
|
+
return true;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
// ─────────────── target signals: WHAT a call touched, as categories (parity: core.target_signals) ───────────────
|
|
630
|
+
// dest_class allowlisted|internal|ip_literal|public · dest_fp first 32 hex of sha256(lowercased host, port
|
|
631
|
+
// stripped; unsalted on purpose so the control plane can match known-bad services) · dest_count 1–16 ·
|
|
632
|
+
// path_class credentials|system|temp|home|workspace|other · arg_bytes lt_1k|lt_10k|lt_100k|ge_100k ·
|
|
633
|
+
// amount_band lt_100|lt_500|lt_1k|lt_2500|lt_5k|le_10k|gt_10k (the amount arg, parsed as the transfer rule does).
|
|
634
|
+
// Pinned by xtrom-engine/target_golden.json.
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
const INTERNAL_SUFFIXES = [".internal", ".local", ".localhost", ".lan", ".home", ".corp", ".intranet"];
|
|
649
|
+
const PATH_TOKENS = new Set(["path", "file", "filename", "filepath", "dir", "directory", "src", "dst", "source",
|
|
650
|
+
"target", "dest", "folder"]);
|
|
651
|
+
const CRED_MARKERS = ["/.ssh/", "id_rsa", "id_ed25519", "/.aws/", "/.env", ".netrc", ".npmrc", ".pypirc",
|
|
652
|
+
".git-credentials", "/.kube/config", "/.docker/config.json", "/.gnupg/", "credentials"];
|
|
653
|
+
const SYSTEM_PREFIXES = ["/etc/", "/usr/", "/bin/", "/sbin/", "/var/", "/proc/", "/sys/", "/boot/", "/root/", "c:/windows/"];
|
|
654
|
+
const TEMP_PREFIXES = ["/tmp/", "/var/tmp/", "/private/tmp/", "/dev/shm/"];
|
|
655
|
+
const HOME_PREFIXES = ["~/", "/users/", "/home/"];
|
|
656
|
+
|
|
657
|
+
function stripPort(host ) {
|
|
658
|
+
let h = host.trim().toLowerCase().replace(/\.+$/, "");
|
|
659
|
+
if (h.startsWith("[")) { const e = h.indexOf("]"); return e >= 0 ? h.slice(1, e) : h.slice(1); }
|
|
660
|
+
if ((h.match(/:/g) ?? []).length === 1) h = h.split(":", 1)[0];
|
|
661
|
+
return h;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
function v4ToInt(s ) {
|
|
665
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s);
|
|
666
|
+
if (!m) return null;
|
|
667
|
+
const o = m.slice(1).map(Number);
|
|
668
|
+
if (o.some((x, i) => x > 255 || (m[i + 1].length > 1 && m[i + 1].startsWith("0")))) return null;
|
|
669
|
+
return ((o[0] << 24) >>> 0) + (o[1] << 16) + (o[2] << 8) + o[3];
|
|
670
|
+
}
|
|
671
|
+
const PRIVATE_V4 = [["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8],
|
|
672
|
+
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.168.0.0", 16]].map(([a, b]) => [v4ToInt(a ) , b ]);
|
|
673
|
+
|
|
674
|
+
function v4Private(n ) {
|
|
675
|
+
return PRIVATE_V4.some(([base, bits]) => bits === 0 || (n >>> (32 - bits)) === (base >>> (32 - bits)));
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** Expand an IPv6 literal to 8 hextets, or null. */
|
|
679
|
+
function v6Hextets(s ) {
|
|
680
|
+
if (!s.includes(":")) return null;
|
|
681
|
+
let tail = [];
|
|
682
|
+
const v4 = /(\d{1,3}(?:\.\d{1,3}){3})$/.exec(s);
|
|
683
|
+
if (v4) {
|
|
684
|
+
const n = v4ToInt(v4[1]);
|
|
685
|
+
if (n === null) return null;
|
|
686
|
+
tail = [n >>> 16, n & 0xffff];
|
|
687
|
+
s = s.slice(0, -v4[1].length) + "0:0";
|
|
688
|
+
}
|
|
689
|
+
const halves = s.split("::");
|
|
690
|
+
if (halves.length > 2) return null;
|
|
691
|
+
const parse = (x ) => (x ? x.split(":") : []).map((h) => (/^[0-9a-f]{1,4}$/.test(h) ? parseInt(h, 16) : NaN));
|
|
692
|
+
const head = parse(halves[0]);
|
|
693
|
+
const rest = halves.length === 2 ? parse(halves[1]) : [];
|
|
694
|
+
const fill = 8 - head.length - rest.length;
|
|
695
|
+
if ((halves.length === 2 ? fill < 1 : fill !== 0) || [...head, ...rest].some(Number.isNaN)) return null;
|
|
696
|
+
const out = [...head, ...Array(halves.length === 2 ? fill : 0).fill(0), ...rest];
|
|
697
|
+
if (tail.length) out.splice(6, 2, ...tail);
|
|
698
|
+
return out;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function ipKind(h ) {
|
|
702
|
+
const n4 = v4ToInt(h);
|
|
703
|
+
if (n4 !== null) return v4Private(n4) ? "private" : "public";
|
|
704
|
+
const x = v6Hextets(h);
|
|
705
|
+
if (!x) return null;
|
|
706
|
+
if (x.slice(0, 5).every((v) => v === 0) && x[5] === 0xffff) return v4Private(((x[6] << 16) >>> 0) + x[7]) ? "private" : "public";
|
|
707
|
+
if (x.slice(0, 7).every((v) => v === 0) && x[7] === 1) return "private"; // ::1
|
|
708
|
+
if ((x[0] & 0xfe00) === 0xfc00 || (x[0] & 0xffc0) === 0xfe80) return "private"; // fc00::/7, fe80::/10
|
|
709
|
+
return "public";
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
export function destClass(host , allow ) {
|
|
713
|
+
if (allow.has(host)) return "allowlisted";
|
|
714
|
+
const h = stripPort(host);
|
|
715
|
+
const kind = ipKind(h);
|
|
716
|
+
if (kind === "private") return "internal";
|
|
717
|
+
if (kind === "public") return "ip_literal";
|
|
718
|
+
if (h === "localhost" || !h.includes(".") || INTERNAL_SUFFIXES.some((s) => h.endsWith(s))) return "internal";
|
|
719
|
+
return "public";
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Every destination a call names, as one fingerprint (parity with Python to_fingerprint): the host of
|
|
723
|
+
* each URL value, the full lower-cased identifier of every other destination arg (list elements one by
|
|
724
|
+
* one). Domain-separated from dest_fp. null when the call names none. */
|
|
725
|
+
export function toFingerprint(args ) {
|
|
726
|
+
const items = new Set ();
|
|
727
|
+
for (const k of Object.keys(args).sort()) {
|
|
728
|
+
const v = rawOf(args[k]);
|
|
729
|
+
const vals = Array.isArray(v) ? v : [v];
|
|
730
|
+
const named = isDestinationArg(k);
|
|
731
|
+
for (const x of vals) {
|
|
732
|
+
const sx = safeStr(x).trim();
|
|
733
|
+
if (!sx) continue;
|
|
734
|
+
if (sx.startsWith("http://") || sx.startsWith("https://")) {
|
|
735
|
+
const h = parseHost(sx);
|
|
736
|
+
if (h) items.add("host:" + stripPort(h));
|
|
737
|
+
} else if (named) {
|
|
738
|
+
items.add("id:" + sx.toLowerCase());
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
if (!items.size) return null;
|
|
743
|
+
return createHash("sha256").update("xtrom-to\u0000" + [...items].sort().join("\n")).digest("hex").slice(0, 32);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
export function destFingerprint(host ) {
|
|
747
|
+
return createHash("sha256").update(stripPort(host)).digest("hex").slice(0, 32);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
export function destRoot(host ) {
|
|
751
|
+
const h = stripPort(host);
|
|
752
|
+
const labels = h.split(".");
|
|
753
|
+
if (labels.length < 3 || ipKind(h) !== null || labels.some((l) => !l)) return null;
|
|
754
|
+
return labels.slice(-2).join(".");
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
export function pathClass(p ) {
|
|
758
|
+
const s = p.trim().replaceAll("\\", "/").toLowerCase();
|
|
759
|
+
if (CRED_MARKERS.some((m) => s.includes(m))) return "credentials";
|
|
760
|
+
if (SYSTEM_PREFIXES.some((x) => s.startsWith(x))) return "system";
|
|
761
|
+
if (TEMP_PREFIXES.some((x) => s.startsWith(x))) return "temp";
|
|
762
|
+
if (HOME_PREFIXES.some((x) => s.startsWith(x))) return "home";
|
|
763
|
+
if (!s.startsWith("/") && !/^[a-z]:\//.test(s)) return "workspace";
|
|
764
|
+
return "other";
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
const looksLikePath = (v ) => ["/", "~/", "./", "../"].some((x) => v.startsWith(x)) || /^[A-Za-z]:[\\/]/.test(v);
|
|
768
|
+
const AMOUNT_EDGES = [[100, "lt_100"], [500, "lt_500"], [1000, "lt_1k"], [2500, "lt_2500"], [5000, "lt_5k"]];
|
|
769
|
+
const amountBand = (a ) => AMOUNT_EDGES.find(([e]) => a < e)?.[1] ?? (a <= 10000 ? "le_10k" : "gt_10k");
|
|
770
|
+
const bytesBucket = (n ) => (n < 1024 ? "lt_1k" : n < 10240 ? "lt_10k" : n < 102400 ? "lt_100k" : "ge_100k");
|
|
771
|
+
|
|
772
|
+
/** Categories for what a call targeted. Never throws. */
|
|
773
|
+
export function targetSignals(args , allow = new Set()) {
|
|
774
|
+
try {
|
|
775
|
+
const out = {};
|
|
776
|
+
const hosts = egressHosts(args);
|
|
777
|
+
const host = hostOf(args) ?? hosts[0] ?? null;
|
|
778
|
+
if (host) {
|
|
779
|
+
out.dest_class = destClass(host, allow);
|
|
780
|
+
out.dest_fp = destFingerprint(host);
|
|
781
|
+
const root = destRoot(host);
|
|
782
|
+
if (root) out.dest_root_fp = destFingerprint(root);
|
|
783
|
+
}
|
|
784
|
+
if (hosts.length || host) out.dest_count = Math.min(16, Math.max(1, hosts.length));
|
|
785
|
+
const toFp = toFingerprint(args);
|
|
786
|
+
if (toFp) out.to_fp = toFp;
|
|
787
|
+
let total = 0;
|
|
788
|
+
let path = null;
|
|
789
|
+
for (const k of Object.keys(args).sort()) {
|
|
790
|
+
const v = rawOf(args[k]);
|
|
791
|
+
const s = safeStr(v);
|
|
792
|
+
total += Buffer.byteLength(s, "utf8");
|
|
793
|
+
if (path === null && typeof v === "string"
|
|
794
|
+
&& (k.toLowerCase().split("_").some((t) => PATH_TOKENS.has(t)) || looksLikePath(s))
|
|
795
|
+
&& !s.startsWith("http://") && !s.startsWith("https://")) path = s;
|
|
796
|
+
}
|
|
797
|
+
if (path !== null) out.path_class = pathClass(path);
|
|
798
|
+
out.arg_bytes = bytesBucket(total);
|
|
799
|
+
const amt = amountOf(args);
|
|
800
|
+
if (amt !== null && Number.isFinite(amt)) out.amount_band = amountBand(amt);
|
|
801
|
+
return out;
|
|
802
|
+
} catch { return {}; }
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
function emit(action , identity , policy , ctx ,
|
|
806
|
+
verdict , layer , reason , reasonCode ) {
|
|
807
|
+
return {
|
|
808
|
+
verdict, layer, reason, action, identity, reasonCode,
|
|
809
|
+
policyVersion: policy?.version ?? "",
|
|
810
|
+
sinkClass: ctx.sinkClass, tainted: ctx.tainted, taintSources: ctx.taintSources,
|
|
811
|
+
secretInArgs: ctx.secretInArgs, contextTainted: ctx.contextTainted,
|
|
812
|
+
latencyUs: Math.max(0, Math.floor((performance.now() - ctx.t0) * 1000)),
|
|
813
|
+
...(ctx.target ? { target: ctx.target } : {}),
|
|
814
|
+
...(ctx.planned ? { planned: true } : {}),
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
function contentOnlyTaint(tainted , labels , args , p ) {
|
|
819
|
+
if (!p.untrustedContentStepup) return false;
|
|
820
|
+
const allow = p.allowlistHosts;
|
|
821
|
+
for (const k of tainted) {
|
|
822
|
+
if (labels[k].origin.startsWith("unlabeled:")) return false;
|
|
823
|
+
if (isDestinationArg(k, p.destinationArgs ?? DEFAULT_DESTINATION_ARGS)) {
|
|
824
|
+
const v = rawOf(args[k]);
|
|
825
|
+
if (p.knownDestinations?.has(safeStr(v))) continue;
|
|
826
|
+
const h = hostOf({ url: v });
|
|
827
|
+
if (h !== null && allow.has(h) && allow.size > 0) continue;
|
|
828
|
+
return false;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
return true;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function authorizeInner(action , args , policy , risk , ctx , identity ) {
|
|
835
|
+
const out = (v , layer , reason , code ) => emit(action, identity, policy, ctx, v, layer, reason, code);
|
|
836
|
+
args = args ?? {};
|
|
837
|
+
const sens = sensitivity(action, policy);
|
|
838
|
+
// S1 — fail-closed labeling: an unlabeled (plain) arg has no provenance → UNTRUSTED.
|
|
839
|
+
const labels = {};
|
|
840
|
+
for (const [k, v] of Object.entries(args)) {
|
|
841
|
+
labels[k] = isValue(v) ? v.label : { trust: "UNTRUSTED", isSecret: looksLikeSecret(v), origin: `unlabeled:${k}` };
|
|
842
|
+
}
|
|
843
|
+
const untrustedLabels = Object.values(labels).filter((l) => l.trust === "UNTRUSTED");
|
|
844
|
+
ctx.sinkClass = sinkClass(action, policy);
|
|
845
|
+
ctx.tainted = untrustedLabels.length > 0;
|
|
846
|
+
ctx.taintSources = taintTags(untrustedLabels);
|
|
847
|
+
ctx.secretInArgs = Object.values(labels).some((l) => l.isSecret);
|
|
848
|
+
ctx.target = targetSignals(args, policy.allowlistHosts);
|
|
849
|
+
|
|
850
|
+
// Rule 0 — scope / least privilege.
|
|
851
|
+
if (!policy.capabilities.has(action))
|
|
852
|
+
return out("BLOCK", "L4:scope", `action '${action}' not in identity capabilities`, ReasonCode.SCOPE_DENY);
|
|
853
|
+
|
|
854
|
+
// Planned call: matches a step written from the user's request. Untrusted data in it can't steer the
|
|
855
|
+
// tool, destination or fixed values; everything below except the taint holds still applies.
|
|
856
|
+
const planned = planMatches(ctx.planStep, action, args, ctx.planChoices, policy);
|
|
857
|
+
ctx.planned = planned;
|
|
858
|
+
|
|
859
|
+
// Rule 1 — taint/IFC: untrusted data may not parameterize a sink (anything not LOW, plus SINK_ACTIONS).
|
|
860
|
+
const isSink = sens !== Sensitivity.LOW || SINK_ACTIONS.has(action) || (policy.destructiveActions?.has(action) ?? false);
|
|
861
|
+
let contentStepup = null;
|
|
862
|
+
// A read of a site the organisation trusts: untrusted data can only choose which allowlisted page is read.
|
|
863
|
+
const knownRead = !!policy.allowlistedReads && isFetch(action, policy) && egressAllowed(args, policy.allowlistHosts);
|
|
864
|
+
if (isSink) {
|
|
865
|
+
const taintedArgs = planned || knownRead ? [] : Object.keys(labels).filter((k) => labels[k].trust === "UNTRUSTED");
|
|
866
|
+
if (taintedArgs.length) {
|
|
867
|
+
const chain = taintedArgs.map((k) => `${k}<-${labels[k].origin}`).join("; ");
|
|
868
|
+
if (contentOnlyTaint(taintedArgs, labels, args, policy)) {
|
|
869
|
+
contentStepup = `untrusted data reached content arg(s) [${chain}]; approval required`;
|
|
870
|
+
} else {
|
|
871
|
+
return out("BLOCK", "L3:taint/IFC", `untrusted data reached sensitive arg(s) [${chain}]`, ReasonCode.IFC_UNTRUSTED_TO_SINK);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// Rule 2 — secrets: egress to a non-allowlisted host BLOCKs; other durable sinks STEP_UP.
|
|
877
|
+
// Egress is a property of the CALL: any sink naming a network destination can carry a secret out.
|
|
878
|
+
const hasSecret = ctx.secretInArgs;
|
|
879
|
+
// Explicit durable sinks keep their own rule below (a URL in a commit is content, not a destination).
|
|
880
|
+
const egressLike = EGRESS_ACTIONS.has(action) || (isSink && !SINK_ACTIONS.has(action) && egressHosts(args).length > 0);
|
|
881
|
+
if (egressLike) {
|
|
882
|
+
if (hasSecret && !secretEgressAllowed(action, args, policy.allowlistHosts)) {
|
|
883
|
+
const primary = hostOf(args);
|
|
884
|
+
const bad = primary !== null && !policy.allowlistHosts.has(primary)
|
|
885
|
+
? primary : egressHosts(args).find((h) => !policy.allowlistHosts.has(h)) ?? primary;
|
|
886
|
+
return out("BLOCK", "L3:secret-egress", `secret in egress to non-allowlisted host '${bad || "?"}'`, ReasonCode.SECRET_EGRESS_DENY);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
// A durable sink still needs approval for a secret even when every destination it names is allowlisted.
|
|
890
|
+
if (hasSecret && SINK_ACTIONS.has(action) && !EGRESS_ACTIONS.has(action)) {
|
|
891
|
+
return out("STEP_UP", "L3:secret-sink", `secret-labeled arg reaching durable sink '${action}' requires approval`, ReasonCode.SECRET_TO_SINK_STEPUP);
|
|
892
|
+
}
|
|
893
|
+
// Agent memory is durable too: a secret written there is recalled into later sessions and other tools.
|
|
894
|
+
if (hasSecret && (policy.memoryWriteActions ?? DEFAULT_MEMORY_WRITE_ACTIONS).has(action)) {
|
|
895
|
+
return out("STEP_UP", "L3:secret-sink", `secret-labeled arg written to agent memory via '${action}' requires approval`, ReasonCode.SECRET_TO_SINK_STEPUP);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
if (contentStepup !== null) {
|
|
899
|
+
if (risk >= 0.75)
|
|
900
|
+
return out("BLOCK", "L1/L2:high-risk", `untrusted content at sink with high risk score ${risk.toFixed(2)}`, ReasonCode.RISK_HIGH_BLOCK);
|
|
901
|
+
return out("STEP_UP", "L3:taint/IFC", contentStepup, ReasonCode.UNTRUSTED_CONTENT_STEPUP);
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// Rule 2b — session (context) taint: not proof → STEP_UP; read-only fetch to an allowlisted host is exempt.
|
|
905
|
+
if (isSink && ctx.contextTainted && risk < 0.75 && !planned
|
|
906
|
+
&& !(policy.contextTaintExempt?.has(action))
|
|
907
|
+
&& !knownRead
|
|
908
|
+
&& !(action === "http_fetch" && egressAllowed(args, policy.allowlistHosts))) {
|
|
909
|
+
return out("STEP_UP", "L3:context-taint", `session ingested untrusted content; '${action}' needs approval`, ReasonCode.CONTEXT_TAINT_STEPUP);
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
// Rule 3 — destructive prod actions require human step-up.
|
|
913
|
+
if (isDestructive(action, policy) && policy.env === "prod")
|
|
914
|
+
return out("STEP_UP", "L4:policy", `destructive action '${action}' on prod requires approval`, ReasonCode.DESTRUCTIVE_STEPUP);
|
|
915
|
+
|
|
916
|
+
// Rule 4 — high-value transfer threshold.
|
|
917
|
+
if (action === "wire_transfer") {
|
|
918
|
+
const amt = amountOf(args);
|
|
919
|
+
const limit = transferThreshold(policy);
|
|
920
|
+
if (amt !== null && amt > limit)
|
|
921
|
+
return out("STEP_UP", "L4:policy", `wire_transfer ${amt} exceeds ${limit} threshold`, ReasonCode.TRANSFER_THRESHOLD_STEPUP);
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
// Rule 5 — probabilistic fusion only escalates the otherwise-ALLOW path.
|
|
925
|
+
if (risk >= 0.75) return out("BLOCK", "L1/L2:high-risk", `probabilistic risk ${risk.toFixed(2)} >= 0.75`, ReasonCode.RISK_HIGH_BLOCK);
|
|
926
|
+
if (risk >= 0.40) return out("STEP_UP", "L1/L2:elevated-risk", `probabilistic risk ${risk.toFixed(2)} elevated`, ReasonCode.RISK_ELEVATED_STEPUP);
|
|
927
|
+
|
|
928
|
+
if (knownRead && !planned && (ctx.tainted || ctx.contextTainted))
|
|
929
|
+
return out("ALLOW", "L3:known-read", "a read of an allowlisted site; untrusted data can only choose which allowlisted page",
|
|
930
|
+
ReasonCode.ALLOWLISTED_READ);
|
|
931
|
+
if (planned && (ctx.tainted || ctx.contextTainted))
|
|
932
|
+
return out("ALLOW", "L3:plan", "planned from the user's request; untrusted data only in planned slots", ReasonCode.PLANNED_CALL);
|
|
933
|
+
return out("ALLOW", "L4:policy", "within policy", ReasonCode.ALLOW_WITHIN_POLICY);
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* The deterministic guarantee + probabilistic fusion, fail-CLOSED: if adjudication itself
|
|
938
|
+
* throws, the call is BLOCKed (layer L0:fail-closed), never allowed.
|
|
939
|
+
* Args may be labeled `Value`s or plain values; plain values are treated as UNTRUSTED.
|
|
940
|
+
*/
|
|
941
|
+
export function decide(action , args , policy , risk = 0, opts = {}) {
|
|
942
|
+
const ctx = {
|
|
943
|
+
t0: performance.now(), contextTainted: !!opts.contextTainted,
|
|
944
|
+
sinkClass: "", tainted: false, taintSources: [], secretInArgs: false,
|
|
945
|
+
planStep: opts.planStep ?? null, planChoices: opts.planChoices ?? null, planned: false,
|
|
946
|
+
};
|
|
947
|
+
const identity = opts.identity ?? "svc-agent";
|
|
948
|
+
try {
|
|
949
|
+
return authorizeInner(action, args, policy, risk, ctx, identity);
|
|
950
|
+
} catch (ex) {
|
|
951
|
+
const name = ex instanceof Error ? ex.name : "Error";
|
|
952
|
+
const msg = ex instanceof Error ? ex.message : safeStr(ex);
|
|
953
|
+
return emit(safeStr(action), identity, policy, ctx, "BLOCK", "L0:fail-closed",
|
|
954
|
+
`enforcement error — failing closed: ${name}: ${msg}`, ReasonCode.FAIL_CLOSED);
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
export const SIGNALS_SCHEMA_VERSION = 2;
|
|
959
|
+
|
|
960
|
+
/** Signals-v2 wire block (snake_case) — the one shape every mediator sends to the control plane. */
|
|
961
|
+
export function decisionSignals(d ) {
|
|
962
|
+
return {
|
|
963
|
+
v: SIGNALS_SCHEMA_VERSION,
|
|
964
|
+
sink_class: d.sinkClass,
|
|
965
|
+
tainted: d.tainted,
|
|
966
|
+
taint_sources: [...d.taintSources],
|
|
967
|
+
secret_in_args: d.secretInArgs,
|
|
968
|
+
context_tainted: d.contextTainted,
|
|
969
|
+
latency_us: d.latencyUs,
|
|
970
|
+
...(d.target ?? {}),
|
|
971
|
+
};
|
|
972
|
+
}
|