// warden.scan@v1 for HESTIA: @aimarket/warden 0.35.0 static scan, bundled by esbuild 0.28.2. // Generated by hestia-agents/scripts/build_warden_scan.sh from warden/src; do not edit by hand. var handler = (() => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // agents/warden-scan/src/entry.ts var entry_exports = {}; __export(entry_exports, { handle: () => handle }); // agents/warden-scan/src/node-shims.js var K = new Uint32Array([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); function utf8Bytes(text) { const out = []; for (const ch of text) { let c = ch.codePointAt(0); if (c >= 55296 && c <= 57343) c = 65533; if (c < 128) out.push(c); else if (c < 2048) out.push(192 | c >> 6, 128 | c & 63); else if (c < 65536) out.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63); else out.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63); } return new Uint8Array(out); } function sha256(bytes) { const h = new Uint32Array([ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]); const total = bytes.length; const padded = new Uint8Array(total + 9 + 63 >> 6 << 6); padded.set(bytes); padded[total] = 128; const view = new DataView(padded.buffer); view.setUint32(padded.length - 8, Math.floor(total / 536870912)); view.setUint32(padded.length - 4, total << 3 >>> 0); const w = new Uint32Array(64); for (let off = 0; off < padded.length; off += 64) { for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4); for (let i = 16; i < 64; i++) { const a2 = w[i - 15], b2 = w[i - 2]; const s0 = (a2 >>> 7 | a2 << 25) ^ (a2 >>> 18 | a2 << 14) ^ a2 >>> 3; const s1 = (b2 >>> 17 | b2 << 15) ^ (b2 >>> 19 | b2 << 13) ^ b2 >>> 10; w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0; } let [a, b, c, d, e, f, g, k] = h; for (let i = 0; i < 64; i++) { const s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); const t1 = k + s1 + (e & f ^ ~e & g) + K[i] + w[i] >>> 0; const s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); const t2 = s0 + (a & b ^ a & c ^ b & c) >>> 0; k = g; g = f; f = e; e = d + t1 >>> 0; d = c; c = b; b = a; a = t1 + t2 >>> 0; } h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += k; } const out = new Uint8Array(32); const outView = new DataView(out.buffer); for (let i = 0; i < 8; i++) outView.setUint32(i * 4, h[i]); return out; } var STD = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; function encode(bytes, alphabet, pad) { let out = ""; let i = 0; for (; i + 2 < bytes.length; i += 3) { const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2]; out += alphabet[n >> 18] + alphabet[n >> 12 & 63] + alphabet[n >> 6 & 63] + alphabet[n & 63]; } if (i < bytes.length) { const n = bytes[i] << 16 | (bytes[i + 1] ?? 0) << 8; out += alphabet[n >> 18] + alphabet[n >> 12 & 63]; out += i + 1 < bytes.length ? alphabet[n >> 6 & 63] : ""; if (pad) out += i + 1 < bytes.length ? "=" : "=="; } return out; } function decode(text) { const out = []; let bits = 0, count = 0; for (const ch of text) { if (ch === "=") break; let v = STD.indexOf(ch); if (v < 0) v = URL.indexOf(ch); if (v < 0) continue; bits = bits << 6 | v; count += 6; if (count >= 8) { count -= 8; out.push(bits >> count & 255); bits &= (1 << count) - 1; } } return new Uint8Array(out); } var Bytes = class extends Uint8Array { toString(encoding) { if (encoding === "base64url") return encode(this, URL, false); if (encoding === "base64") return encode(this, STD, true); if (encoding === "hex") return Array.from(this, (b) => b.toString(16).padStart(2, "0")).join(""); return new TextDecoder("utf-8").decode(this); } }; var Buffer2 = { from(value, encoding) { if (typeof value === "string") { if (encoding === "base64url" || encoding === "base64") { const raw2 = decode(value); return new Bytes(raw2.buffer, raw2.byteOffset, raw2.length); } const raw = utf8Bytes(value); return new Bytes(raw.buffer, raw.byteOffset, raw.length); } return new Bytes(Uint8Array.from(value)); } }; var TextDecoder = class { constructor(label = "utf-8", options = {}) { if (String(label).toLowerCase().replace("-", "") !== "utf8") throw new RangeError("only utf-8"); this.fatal = Boolean(options.fatal); } decode(input) { const b = input instanceof Uint8Array ? input : new Uint8Array(input ?? []); let out = ""; for (let i = 0; i < b.length; ) { const x = b[i]; let need = 0, cp = 0, min = 0; if (x < 128) { out += String.fromCharCode(x); i++; continue; } if (x >= 194 && x <= 223) { need = 1; cp = x & 31; min = 128; } else if (x >= 224 && x <= 239) { need = 2; cp = x & 15; min = 2048; } else if (x >= 240 && x <= 244) { need = 3; cp = x & 7; min = 65536; } else need = -1; let ok = need > 0 && i + need < b.length; for (let j = 1; ok && j <= need; j++) { const y = b[i + j]; if (y === void 0 || (y & 192) !== 128) ok = false; else cp = cp << 6 | y & 63; } if (ok && (cp < min || cp > 1114111 || cp >= 55296 && cp <= 57343)) ok = false; if (!ok) { if (this.fatal) throw new TypeError("The encoded data was not valid for encoding utf-8"); out += "�"; i++; continue; } out += String.fromCodePoint(cp); i += need + 1; } return out; } }; var Hash = class { constructor() { this.parts = []; } update(data, encoding) { this.parts.push(typeof data === "string" ? utf8Bytes(data) : Uint8Array.from(data)); void encoding; return this; } digest(encoding) { const size = this.parts.reduce((n, p) => n + p.length, 0); const all = new Uint8Array(size); let at = 0; for (const p of this.parts) { all.set(p, at); at += p.length; } const out = sha256(all); if (encoding === "hex") return Array.from(out, (b) => b.toString(16).padStart(2, "0")).join(""); if (encoding === "base64") return encode(out, STD, true); if (encoding === "base64url") return encode(out, URL, false); return Buffer2.from(out); } }; function createHash(algorithm) { if (String(algorithm).toLowerCase() !== "sha256") throw new Error("only sha256 is available here"); return new Hash(); } // ../warden/src/jcs.ts var CanonicalizationError = class extends Error { constructor(code, detail) { super(`${code}: ${detail}`); this.code = code; this.name = "CanonicalizationError"; } code; }; var MAX_DEPTH = 64; function canonicalize(value) { const out = []; serialize(value, out, "$", 0, /* @__PURE__ */ new Set(), serializeNumber); return out.join(""); } function serialize(value, out, path, depth, seen, num) { if (depth > MAX_DEPTH) { throw new CanonicalizationError("AWR-CANON-005", `nesting deeper than ${MAX_DEPTH} at ${path}`); } if (value === null) { out.push("null"); return; } switch (typeof value) { case "boolean": out.push(value ? "true" : "false"); return; case "number": out.push(num(value, path)); return; case "string": out.push(serializeString(value, path)); return; case "object": break; default: throw new CanonicalizationError("AWR-CANON-005", `${typeof value} at ${path} is not representable in JSON`); } const obj = value; if (seen.has(obj)) throw new CanonicalizationError("AWR-CANON-005", `circular reference at ${path}`); seen.add(obj); try { if (Array.isArray(obj)) { out.push("["); for (let i = 0; i < obj.length; i++) { if (i > 0) out.push(","); serialize(obj[i], out, `${path}[${i}]`, depth + 1, seen, num); } out.push("]"); return; } const proto = Object.getPrototypeOf(obj); if (proto !== Object.prototype && proto !== null) { throw new CanonicalizationError( "AWR-CANON-005", `${obj.constructor?.name ?? "object"} at ${path} is not a plain JSON object` ); } const record = obj; out.push("{"); let first = true; for (const key of Object.keys(record).sort()) { const member = record[key]; if (member === void 0) { throw new CanonicalizationError( "AWR-CANON-005", `property "${key}" at ${path} is undefined — JSON has no such value (JSON.stringify would drop it silently, changing the signed bytes)` ); } if (!first) out.push(","); first = false; out.push(serializeString(key, `property name "${key}" at ${path}`), ":"); serialize(member, out, `${path}.${key}`, depth + 1, seen, num); } out.push("}"); } finally { seen.delete(obj); } } function serializeNumber(n, path) { if (!Number.isFinite(n)) { throw new CanonicalizationError("AWR-CANON-001", `${String(n)} at ${path} is not a JSON number`); } if (!Number.isInteger(n)) { throw new CanonicalizationError("AWR-CANON-001", `non-integer JSON number ${n} at ${path}`); } if (!Number.isSafeInteger(n)) { throw new CanonicalizationError("AWR-CANON-002", `integer ${n} at ${path} is outside ±(2^53−1)`); } return String(n); } function serializeString(text, path) { assertWellFormed(text, path); return JSON.stringify(text); } function assertWellFormed(text, path) { for (let i = 0; i < text.length; i++) { const unit = text.charCodeAt(i); if (unit >= 55296 && unit <= 56319) { const low = text.charCodeAt(i + 1); if (!(low >= 56320 && low <= 57343)) { throw new CanonicalizationError( "AWR-CANON-003", `lone high surrogate U+${unit.toString(16).toUpperCase()} at index ${i} in ${path}` ); } i++; } else if (unit >= 56320 && unit <= 57343) { throw new CanonicalizationError( "AWR-CANON-003", `lone low surrogate U+${unit.toString(16).toUpperCase()} at index ${i} in ${path}` ); } } } // ../warden/src/sanitize.ts var INVISIBLE = "\\u200B-\\u200F\\u202A-\\u202E\\u2060\\u2066-\\u2069\\uFEFF\\u{E0000}-\\u{E007F}"; var CONTROL = "\\u0000-\\u001F\\u007F-\\u009F"; var UNSAFE = new RegExp(`[${CONTROL}${INVISIBLE}]`, "gu"); var DEFAULT_DISPLAY_MAX = 200; function displaySafe(value, max = DEFAULT_DISPLAY_MAX) { const text = typeof value === "string" ? value : String(value ?? ""); const escaped = text.replace(UNSAFE, (ch) => { const code = ch.codePointAt(0) ?? 0; return `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`; }); if (escaped.length <= max) return escaped; return `${escaped.slice(0, max)}... [truncated, ${text.length} chars]`; } // ../warden/src/encoded-text.ts var MAX_TOKEN = 8192; var MAX_DECODED = 65536; var MAX_PASSES = 4; var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", colon: ":", sol: "/", bsol: "\\", tab: " ", newline: "\n", nbsp: " " }; var utf8 = new TextDecoder("utf-8", { fatal: true }); function point(raw, radix, fallback) { const n = Number.parseInt(raw, radix); return n > 0 && n <= 1114111 && !(n >= 55296 && n <= 57343) ? String.fromCodePoint(n) : fallback; } function decodeForScan(text) { let out = text; let budget = MAX_DECODED; for (let pass = 0; pass < MAX_PASSES; pass++) { const before = out; const replace = (whole, decoded) => { if (whole.length > MAX_TOKEN || whole.length > budget || decoded.length > whole.length) return whole; budget -= whole.length; return decoded; }; out = out.replace( /&#(?:x([0-9a-f]{1,6})|([0-9]{1,7}));|&(amp|lt|gt|quot|apos|colon|sol|bsol|Tab|NewLine|nbsp);/gi, (whole, hex, decimal, named) => replace(whole, named ? ENTITIES[named.toLowerCase()] ?? whole : point(hex ?? decimal, hex ? 16 : 10, whole)) ); out = out.replace( /(? replace(whole, brace ? point(brace, 16, whole) : String.fromCharCode(Number.parseInt(unit ?? hex, 16))) ); out = out.replace(/(?:%[0-9a-f]{2})+/gi, (whole) => { if (whole.length > MAX_TOKEN || whole.length > budget) return whole; try { return replace(whole, decodeURIComponent(whole)); } catch { return whole; } }); out = out.replace(/(? { if (whole.length > MAX_TOKEN || whole.length > budget || whole.replace(/=+$/, "").length % 4 === 1) return whole; try { const buffer = Buffer2.from(whole, "base64url"); if (buffer.toString("base64url") !== whole.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")) return whole; const decoded = utf8.decode(buffer); if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(decoded) || !/\p{L}[\s\S]*\p{L}/u.test(decoded)) return whole; return replace(whole, decoded); } catch { return whole; } }); if (out === before || budget <= 0) break; } return out; } // ../warden/src/fold.ts var FOLD_ID = "escapes+entities+percent+base64/4x64k+nfkc+tags+invisible+confusables/2"; var INVISIBLE_RE = new RegExp( "[\\u00AD\\u034F\\u061C\\u115F\\u1160\\u17B4\\u17B5\\u180B-\\u180F\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u206F\\u3164\\uFE00-\\uFE0F\\uFEFF\\uFFA0\\u{E0000}-\\u{E001F}\\u{E007F}\\u{E0100}-\\u{E01EF}]", "gu" ); var TAG_RE = /[\u{E0020}-\u{E007E}]/gu; var CONFUSABLE = { // Cyrillic lower case "а": "a", "в": "b", "е": "e", "ё": "e", "к": "k", "м": "m", "н": "h", "о": "o", "р": "p", "с": "c", "т": "t", "у": "y", "х": "x", "і": "i", "ї": "i", "ј": "j", "ѕ": "s", "ԁ": "d", "ԛ": "q", "ԝ": "w", "ӏ": "l", "һ": "h", "ɡ": "g", // Cyrillic upper case "А": "A", "В": "B", "Е": "E", "Ё": "E", "К": "K", "М": "M", "Н": "H", "О": "O", "Р": "P", "С": "C", "Т": "T", "У": "Y", "Х": "X", "І": "I", "Ї": "I", "Ј": "J", "Ѕ": "S", "Һ": "H", "Ԛ": "Q", "Ԝ": "W", "Ӏ": "I", // Greek "α": "a", "ε": "e", "ι": "i", "κ": "k", "ν": "v", "ο": "o", "ρ": "p", "τ": "t", "υ": "u", "χ": "x", "Α": "A", "Β": "B", "Ε": "E", "Ζ": "Z", "Η": "H", "Ι": "I", "Κ": "K", "Μ": "M", "Ν": "N", "Ο": "O", "Ρ": "P", "Τ": "T", "Υ": "Y", "Χ": "X" }; var TOKEN_RE = /[\p{L}\p{M}]+/gu; var LATIN_RE = /[A-Za-z]/; var CONFUSABLE_RE = new RegExp(`[${Object.keys(CONFUSABLE).join("")}]`, "gu"); function foldForScan(text) { if (!text) return text; let out = decodeForScan(text.normalize("NFKC")).normalize("NFKC"); out = out.replace(TAG_RE, (ch) => String.fromCharCode((ch.codePointAt(0) ?? 917536) - 917504)); out = out.replace(INVISIBLE_RE, ""); CONFUSABLE_RE.lastIndex = 0; if (!CONFUSABLE_RE.test(out)) return out; return out.replace(TOKEN_RE, (tok) => { const marks = tok.replace(/\p{M}/gu, ""); if (!LATIN_RE.test(tok) && !allConfusable(marks)) return tok; return tok.replace(CONFUSABLE_RE, (ch) => CONFUSABLE[ch] ?? ch); }); } function allConfusable(letters) { if (!letters) return false; for (const ch of letters) { if (!(ch in CONFUSABLE) && !/[A-Za-z]/.test(ch)) return false; } return /[^A-Za-z]/.test(letters); } // ../warden/src/logger.ts function silentLogger() { const noop = () => { }; const self = { debug: noop, info: noop, warn: noop, error: noop, child: () => self }; return self; } // ../warden/src/ssh-reference.ts function benignSshReference(text, start, end) { if (end - start > 256) return null; let left = start, right = end; const boundary = /[\s"'`\\,;:!?()[\]]/; const floor = Math.max(0, start - 256), ceiling = Math.min(text.length, end + 256); while (left > floor && !boundary.test(text[left - 1])) left--; while (right < ceiling && !boundary.test(text[right])) right++; if (left > 0 && !boundary.test(text[left - 1]) || right < text.length && !boundary.test(text[right]) || right - left > 256) return null; if (text[right] === "\\" && text[right + 1] !== '"') return null; const token = text.slice(left, right).replace(/([^\.])\.$/, "$1"); if (token.includes("/../") || token.includes("/./") || /\.pub\//i.test(token)) return null; if (/(?:^|\/)[^/]+\.pub$/i.test(token) || /(?:^|\/)\.ssh\/(?:authorized_keys|known_hosts)$/i.test(token)) { return "this exact path names public SSH material"; } if (!/^~\/\.ssh\/[^/]+$/.test(token)) return null; const before = text.slice(Math.max(0, left - 180), left); const sshOption = /\bssh(?:\s+(?:-[A-Za-z]+(?:\s+[^\s;"'`]+)?)){0,4}\s+-i\s+$/i.test(before); const describedSshOption = /\bssh\s+command\s+(?:uses?|includes?)\s+[`"']?-i\s+$/i.test(before); const describedPlaceholder = /^~\/\.ssh\/<[A-Za-z_][A-Za-z0-9_]*>$/.test(token) && /\b(?:the\s+)?command\s+(?:uses?|includes?)\s+[`"']?-i\s+$/i.test(before) && !/\b(?:base64|curl|openssl|cat|encode)\s+command\s+(?:uses?|includes?)\s+[`"']?-i\s+$/i.test(before); const describedOption = describedSshOption || describedPlaceholder; if (!sshOption && !describedOption) return null; if (!describedPlaceholder) { const tail = text.slice(right); if (tail.length > 512) return null; const connectionTail = /^(?:\s+(?:-p\s+\d{1,5}|-o\s+IdentitiesOnly=(?:yes|no)|-l\s+[A-Za-z0-9_.-]+))*\s+(?:[A-Za-z0-9_.-]+@)?(?:\[[a-f0-9:]+\]|[A-Za-z0-9][A-Za-z0-9.-]*)[`"']?\.?\s*$/i; const authenticationTail = /^[`"']?\s*(?:(?:when|for)\s+authenticating|(?:to|for)\s+authenticat(?:e|ion))?\.?\s*$/i; if (!(sshOption && connectionTail.test(tail)) && !(describedSshOption && authenticationTail.test(tail))) return null; } const after = text.slice(end, Math.min(text.length, right + 160)); if (/\b(?:contents?|bytes|material|values?)\b/i.test(after) || /\b(?:read|cat|paste|send|upload|attach|append|insert|share|transmit|encode|dump|reveal|export|include|copy|return|put|provide|pass|supply|print|log)\b[^.!?\n";]{0,50}\b(?:key|contents?|it|bytes|material|values?)\b/i.test(after)) return null; return "the path is the local identity argument of an SSH connection command"; } // ../warden/src/static-scan.ts var PROSE = ["description", "inputSchema", "title", "outputSchema", "annotations", "metadata"]; var ALL_SURFACES = ["name", ...PROSE]; var INJECTION_PATTERNS = [ // v10. A definition claiming to outrank the user ("this description's priority is higher than the // user's query"). { re: /\b(?:priority|precedence)\s+(?:is\s+)?(?:higher\s+than|over|above)\s+(?:that\s+of\s+)?(?:the\s+|any\s+|all\s+)?(?:user'?s?\b|user\s+(?:query|request|instructions?)|(?:previous\s+|other\s+)?instructions?\b|system\s+prompt)/i, code: "TOOL_DEF_INJECTION", severity: "high", tier: "block", surfaces: ALL_SURFACES, guards: ["polarity", "detection"] }, { re: /\bignore\s+(?:all\s+|the\s+)?(?:previous|prior|above|preceding)\b/i, code: "TOOL_DEF_INJECTION", severity: "critical", tier: "block", surfaces: ALL_SURFACES, guards: ["mention"] }, { re: /\bdisregard\s+(?:all\s+|the\s+|any\s+)?(?:previous|prior|above|instructions?|rules?)\b/i, code: "TOOL_DEF_INJECTION", severity: "critical", tier: "block", surfaces: ALL_SURFACES, guards: ["mention"] }, // Demoted in v4. The survey found four real uses and all four were the // OPPOSITE of concealment: "no refund is issued automatically … do not tell // the user a refund is coming". Conscientious authors use the phrase to stop // the model inventing reassurance. Blocking on it selected for exactly the // servers that were being careful. A blocking rule needs a concealment target // that refers to the tool's own action; the bare phrase does not carry one. { re: /\bdo\s+not\s+(?:tell|inform|mention|reveal\s+to|notify)\s+(?:the\s+)?user\b/i, code: "TOOL_DEF_INJECTION", severity: "medium", tier: "advise", surfaces: ALL_SURFACES, guards: ["mention"] }, { re: /\bwithout\s+(?:telling|informing|asking)\s+(?:the\s+)?user\b/i, code: "TOOL_DEF_INJECTION", severity: "high", tier: "block", surfaces: ALL_SURFACES, guards: ["autonomy"] }, // v9. What the v4 demotion asked for: a concealment whose target is the tool's OWN // behaviour. "do not tell the user ABOUT THIS / THAT THIS TOOL …" and "do not mention // that you (first read …)" hide an action; the honest uses the survey found ("do not // tell the user a refund is coming", "… the check digits are wrong", "… results were // filtered") stop the model inventing a claim and never take these objects. { re: /\b(?:do\s+not|don'?t|never)\s+(?:tell|inform|notify|alert)\s+(?:the\s+)?user\s+(?:about\s+(?:this|these|it|that)\b|that\s+(?:this|the)\s+tool\b|of\s+(?:this|these)\b)/i, code: "TOOL_DEF_INJECTION", severity: "high", tier: "block", surfaces: ALL_SURFACES, guards: ["mention"] }, { re: /\b(?:do\s+not|don'?t|never)\s+mention\s+that\s+you\b/i, code: "TOOL_DEF_INJECTION", severity: "high", tier: "block", surfaces: ALL_SURFACES, guards: ["mention"] }, { re: /<\s*\/?\s*(?:system|instructions?|important)\s*>/i, code: "TOOL_DEF_INJECTION", severity: "high", tier: "block", surfaces: ALL_SURFACES }, // Demoted in v4. The comment here used to say this was "the blocking rule most // likely to need a policy override"; the survey settled it — 15 findings across // 6 servers, every one an LLM proxy, persona manager or agent-configuration // tool that declares a `system` parameter because setting a system prompt is // its entire job. The phrase is the domain's vocabulary, not the attack. { re: /\b(?:system\s+prompt|developer\s+(?:message|prompt))\b/i, code: "TOOL_DEF_INJECTION", severity: "low", tier: "advise", surfaces: ALL_SURFACES }, // Ordinary English. Kept as a signal because it co-occurs with real poisoning, // demoted because on its own it is noise: "You must supply a subject." { re: /\byou\s+must\b/i, code: "TOOL_DEF_IMPERATIVE", severity: "low", tier: "advise", surfaces: ALL_SURFACES }, { re: /\binstead\s+of\b/i, code: "TOOL_DEF_IMPERATIVE", severity: "info", tier: "advise", surfaces: ALL_SURFACES } ]; var EXFIL_PATTERNS = [ // Demoted in v4. An attacker does not name the attack; a defender names it in // every sentence. All three of the survey's hits were defensive tools — an MCP // endpoint scanner, an injection scanner, and a policy builder whose `enum` is // `["exfiltration", "recon_then_destroy", …]`. The anchored "send X to // " rules below carry the blocking weight instead. { re: /\bexfiltrat\w*/i, code: "TOOL_DEF_EXFIL", severity: "medium", tier: "advise", surfaces: ALL_SURFACES, guards: ["mention"] }, // Anchored on an EXTERNAL destination. Unanchored, this matched "Send the // message to the recipient" in any honest email or webhook tool. { re: /\b(?:send|post|forward|relay)\s+(?:it|them|this|the\s+\w+|all|results?|output|data|contents?)\s+to\s+(?:https?:\/\/|\b[\w-]+(?:\.[\w-]+)*\.[a-z]{2,}\b)/i, code: "TOOL_DEF_EXFIL", severity: "high", tier: "block", surfaces: ALL_SURFACES, // "send the user to https://…" is a redirect of a person, not a copy of data. guards: ["navigation"] }, { re: /\b(?:post|send|put)\s+to\s+https?:\/\//i, code: "TOOL_DEF_EXFIL", severity: "critical", tier: "block", surfaces: ALL_SURFACES }, { re: /\bupload\b[\s\S]{0,40}\bto\s+(?:https?:\/\/|[\w.-]+\.[a-z]{2,})/i, code: "TOOL_DEF_EXFIL", severity: "high", tier: "block", surfaces: ALL_SURFACES }, // v9. "POST the original text and the conversation history to https://…", "send a copy // of all messages to someone@host": the object is a phrase, not one word, and the // destination may be a mailbox. Imperative base forms only ("Posts the page to // https://api.notion.com" describes the tool's own call and does not match), a // literal URL or address only, and the object must name data the user owns. { re: /\b(?:send|post|forward|relay|copy|transmit|e-?mail)\s[^.;!?\n]{0,80}?\bto\s+(?:https?:\/\/[^\s"'<>)]+|[\w.+-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63})+)/i, code: "TOOL_DEF_EXFIL", severity: "high", tier: "block", surfaces: ALL_SURFACES, guards: ["navigation", "mention", "dataObject", "placeholderAddress", "polarity"] }, // v9. A blind copy to a fixed mailbox is the shadowing shape: "add bcc x@host". { re: /\b(?:bcc|cc)\b\s*:?\s*[\w.+-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63})+/i, code: "TOOL_DEF_EXFIL", severity: "high", tier: "block", surfaces: ALL_SURFACES, guards: ["mention", "placeholderAddress", "polarity"] }, // v17. The same blind copy written the other way round: "add x@host in BCC", "put x@host as cc". { re: /[\w.+-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63})+\s+(?:in|as|to|into)\s+(?:the\s+)?(?:bcc|cc)\b/i, code: "TOOL_DEF_EXFIL", severity: "high", tier: "block", surfaces: ALL_SURFACES, guards: ["mention", "placeholderAddress", "polarity"] }, // v9. The conversation itself as the payload. Blocking only together with a reason to // believe it leaves: an external address in the same definition, a credential in the // same clause, or a concealment cue. "Saves the entire conversation to your notes" has // none of them. { re: /\b(?:entire|whole|full|complete)\s+(?:conversation|chat)(?:\s+(?:history|log|so\s+far))?|\bconversation\s+history\b|\b(?:list\s+of\s+)?(?:last|previous|all)\s+(?:the\s+)?(?:messages|chats)\b/i, code: "TOOL_DEF_EXFIL", severity: "high", tier: "block", surfaces: ALL_SURFACES, note: "asks for the conversation itself, alongside an outside address, a credential or a concealment cue", guards: ["mention", "polarity", "contextExfil"] } ]; var SECRET_PATTERNS = [ // v18. Contents transferred into model/tool arguments, rather than an ordinary // credential parameter or a tool reading its own local configuration. { re: /(?(?:读取|讀取|获取|獲取|读出|讀出|提取|导出|導出|把|将|將)[^。!?;\n"]{0,40}?(?:\.env\b|凭据文件|憑據文件|密钥文件|金鑰檔案)[^。!?;\n"]{0,40}?(?:内容|內容)[^。!?;\n"]{0,12}?)(?放进|放入|填入|写入|寫入|附加到|发送到|發送到)[^。!?;\n"]{0,40}?(?:参数|參數|字段|欄位|备注|備註)/u, code: "TOOL_DEF_SECRET_HARVEST", severity: "critical", tier: "block", surfaces: ALL_SURFACES, guards: ["chineseRefusal"] }, { re: /(?\b(?:gather|assemble|round\s+up|collect|harvest|grab|copy|read|retrieve|fetch|obtain)\s+[^.;"\n]{0,64}?\bcredentials?[\s-]+files?\b[^.;"\n]{0,100}?)\b(?attach|append|include|paste|copy|put|send|write)\s+(?:(?:their|the|its|all|of|complete|full|entire|raw)\s+){0,5}(?:contents?|text|values?)\b[^.;"\n]{0,60}?\b(?:fields?|arguments?|parameters?|params?|reports?|notes?|context)\b/i, code: "TOOL_DEF_SECRET_HARVEST", severity: "critical", tier: "block", surfaces: ALL_SURFACES, guards: ["transferRefusal"] }, { re: /\b(?:include|attach|paste|append|copy|put|send|write|dump|return)\s+(?:(?:the|a|an)\s+)?(?:(?:(?:full|complete|entire|raw)\s+)?output\s+(?:of|from)\s+[`']?(?:env|printenv)\b|all\s+(?:the\s+)?environment[\s-]+variables?(?:\s+values?)?\b|(?:full|complete|entire|raw)\s+(?:process\s+)?environment\b)[^.;"\n]{0,100}?\b(?:fields?|arguments?|parameters?|params?|reports?|notes?|context)\b/i, code: "TOOL_DEF_SECRET_HARVEST", severity: "critical", tier: "block", surfaces: ALL_SURFACES, guards: ["transferRefusal"] }, { // The gap may no longer cross a sentence or a JSON string boundary. It used // to be `[\s\S]{0,30}`, which matched "read an open or sealed run (pass // api_key" — a verb in prose reaching into the next field's parameter name. // v9: a dot followed by a word character or a slash is part of a path, not the end of // a sentence, so "read ~/.aws/credentials" is one clause again; and the stores that // hold cloud and registry credentials are named. re: /\b(?:read|extract|retrieve|fetch|obtain|dump|reveal|collect|harvest|grab|copy|print)\s(?:[^.;"\n]|\.(?=[\w/])){0,40}?(?:\b(?:api[_\s-]?key|access[_\s-]?token|bearer\s+token|credential|password|passwd|secret|environment\s+variable)|\.env\b|\.kube\/config\b|application_default_credentials|\.docker\/config\.json|\.git-credentials|\.netrc\b|\.pgpass\b|\.npmrc\b|\.pypirc\b)/i, code: "TOOL_DEF_SECRET_HARVEST", severity: "critical", tier: "block", // Phrase-keyed: the verb must be followed by whitespace, so `read_api_key` // as an identifier cannot match while `read api_key` in a name can. surfaces: ALL_SURFACES, // "never store secrets", "never collect card data", "does not reveal or mint // a standalone agent credential" — three servers blocked for promising in // writing not to do this. "The key is read from the MCP connection's // X-API-Key header" — a server describing its own authentication. guards: ["polarity", "harvestTarget", "ownAuthHeader"] }, // Severity lowered from critical to high in v4: still over the default block // threshold, but no longer zeroing the gate score outright. One noun in a // schema template shared by 377 tools should not read as "this server is // maximally compromised" — and with the polarity guard, the template that // caused it ("do not … include private key material") no longer matches at all. { re: /\bprivate[_\s-]?key\b/i, code: "TOOL_DEF_SECRET_REQUEST", severity: "high", tier: "block", surfaces: PROSE, guards: ["polarity", "detection", "identifierFragment", "keyValue", "outputEnumLabel", "keyStaysLocal"] }, { re: /\bseed[_\s-]?phrase\b|\bmnemonic\b/i, code: "TOOL_DEF_SECRET_REQUEST", severity: "high", tier: "block", surfaces: PROSE, guards: ["polarity", "mention", "detection", "identifierFragment", "evmOpcodeMnemonic", "seedPhraseProperty"] }, { re: /~\/\.ssh|\bid_rsa\b|\.ssh\/[\w.-]+/i, code: "TOOL_DEF_SECRET_REQUEST", severity: "high", tier: "block", surfaces: PROSE, guards: ["polarity", "publicKeyPath"] }, // v13. An ARGUMENT that takes key material by value, in words the private-key and seed-phrase rules do not // spell: a signing key, a wallet key, a key pair, a recovery phrase. The one rule that skips the tool's // description: there the same words are what key-handling tools say about themselves ("rotate my signing // key", "returns the public key of the signing key pair"), and on the 2026-10-01 corpus they blocked six // honest servers; in argument descriptions, none. Suggested by a reader of the scanner // comparison: the argument's own description is where a tool that takes the key ("the signing key, hex") // differs from one that uses a stored key ("the name of a saved login"). It only ADDS findings: the // description is the author's text, so it never excuses a match another rule made, and a reference to a key // (its id, name, path or the public half) is not the key. { re: /\b(?:signing|wallet)\s+(?:private\s+|secret\s+)?key\b|\bkey[\s-]?pair\b|\b(?:secret\s+)?recovery\s+(?:phrase|words)\b|\bsecret\s+phrase\b/i, code: "TOOL_DEF_SECRET_REQUEST", severity: "high", tier: "block", surfaces: ["inputSchema"], guards: ["polarity", "detection", "identifierFragment", "keyReference", "keyStaysLocal"] }, // Advisory: these are ordinary parameter names and ordinary setup prose. // v21: "No API key needed", "free, no API key", "works without an API key" say the tool takes NO credential // (warden#14: 4 of 29 advisory matches on one marketplace's live tools/list). Only the absence of the noun // itself — "no" / "without" right before it, or "not required" right after — and never on a block-tier rule. { re: /\bapi[_\s-]?key\b/i, code: "TOOL_DEF_CREDENTIAL_PARAM", severity: "low", tier: "advise", surfaces: PROSE, guards: ["absentCredential"] }, { re: /\bcredentials?\b|\baccess[_\s-]?token\b|\bbearer\s+token\b/i, code: "TOOL_DEF_CREDENTIAL_PARAM", severity: "low", tier: "advise", surfaces: PROSE, guards: ["absentCredential"] }, { re: /\bsecret(?:s)?\b/i, code: "TOOL_DEF_CREDENTIAL_PARAM", severity: "low", tier: "advise", surfaces: PROSE, guards: ["absentCredential"] }, { re: /\bpassword\b|\bpasswd\b/i, code: "TOOL_DEF_CREDENTIAL_PARAM", severity: "medium", tier: "advise", surfaces: PROSE, guards: ["absentCredential"] }, { re: /(?:^|[^.\w])\.env\b|\benvironment\s+variables?\b/i, code: "TOOL_DEF_ENV_REFERENCE", severity: "medium", tier: "advise", surfaces: PROSE } ]; var SECRET_EXFIL_PATTERNS = [ { re: /~\/\.ssh\/[\w.-]{1,64}|\bid_rsa\b|~?\/?\.aws\/credentials\b|~?\/?\.(?:npmrc|pgpass|netrc|git-credentials)\b|(?:^|[^.\w])\.env(?:\.[\w-]{1,40})?\b|\bprocess\.env\b/i, code: "TOOL_DEF_SECRET_EXFIL", severity: "medium", tier: "advise", surfaces: PROSE, note: "names a secret store and an external address in the same breath", guards: ["publicKeyPath", "polarity", "detection", "secretExfilPair"] } ]; var ID = String.raw`(?:[\`'"]?([A-Za-z][A-Za-z0-9]*(?:[_-][A-Za-z0-9]+)+|[a-z]+[A-Z][A-Za-z0-9]+)[\`'"]?|[\`'"]([a-z][A-Za-z0-9]{1,40})[\`'"])(?:\s+tool)?`; var ci = (w) => w.replace(/[a-z]/g, (c) => `[${c}${c.toUpperCase()}]`); var CALL_VERB = `(?:${["call", "calling", "use", "using", "run", "running", "invoke", "invoking", "execute", "executing", "fetch", "fetching", "query", "querying", "trigger", "triggering"].map(ci).join("|")})`; var S = String.raw`\s+`; var WHEN = `(?:${["when", "whenever", "if"].map(ci).join("|")})`; var CROSS_TOOL_FRAME = new RegExp( String.raw`\b(?:${["when", "whenever", "before", "after", "while", "if"].map(ci).join("|")}|${ci("each")}${S}${ci("time")}|${ci("every")}${S}${ci("time")})${S}(?:${ci("you")}${S})?(?:${ci("are")}${S})?(?:${ci("first")}${S})?${CALL_VERB}${S}(?:${ci("the")}${S})?(?:${ci("tool")}${S})?${ID}` + // v15: the call is the user's ("when a user calls `X`", "when a user's query for `X` …") or named passively // ("when `X` is called"), or every call of it is meant ("all `X` requests must …"). String.raw`|\b${WHEN}${S}(?:${ci("a")}|${ci("the")}|${ci("any")})${S}${ci("user")}${S}(?:${["calls", "uses", "invokes", "runs", "executes"].map(ci).join("|")})${S}(?:${ci("the")}${S})?(?:${ci("tool")}${S})?${ID}` + String.raw`|\b${WHEN}${S}(?:${ci("a")}|${ci("the")})${S}(?:${ci("user")}'s${S})?(?:${["query", "request", "call", "input"].map(ci).join("|")})${S}(?:${ci("for")}|${ci("to")})${S}(?:${ci("the")}${S})?${ID}` + String.raw`|\b(?:${["all", "any", "every", "each"].map(ci).join("|")})\b[^.;\n]{0,60}?\b(?:${["via", "using", "through"].map(ci).join("|")}|${ci("provided")}${S}${ci("to")})${S}${ci("the")}${S}${ID}${S}${ci("tool")}\b` + String.raw`|\b${WHEN}${S}(?:${ci("a")}|${ci("the")})${S}${ci("user")}${S}(?:${["queries", "searches", "asks", "requests"].map(ci).join("|")})\b[^.;\n]{0,40}?\b(?:${ci("using")}|${ci("via")})${S}(?:${ci("the")}${S})?${ID}` + // v17: a short qualifier may sit between the tool and the verb ("when the `send_email` tool from any other server // is used"): the shadowing shape, which binds to a tool of ANOTHER server. String.raw`|\b${WHEN}${S}(?:${ci("the")}${S})?${ID}${S}(?:${ci("tool")}${S})?(?:(?:${["from", "of", "on", "in", "by"].map(ci).join("|")})${S}[^.;,\n]{1,40}?${S})?(?:${ci("is")}|${ci("are")})${S}(?:${["called", "used", "invoked", "run", "executed"].map(ci).join("|")})\b` + String.raw`|\b(?:${["all", "any", "every", "each"].map(ci).join("|")})${S}${ID}${S}(?:${["requests", "request", "calls", "call", "queries", "lookups", "operations"].map(ci).join("|")})\b` + String.raw`|\b(?:${["submitted", "passed", "sent", "given"].map(ci).join("|")})${S}${ci("to")}${S}(?:${ci("the")}${S})?${ID}` + String.raw`|\b(?:${["queries", "query", "requests", "request", "calls", "call", "inputs", "input"].map(ci).join("|")})${S}${ci("to")}${S}(?:${ci("the")}${S})?${ID}` + String.raw`|\b${ci("before")}${S}\w+ing\b[^.; ]{0,60}?\b(?:${["using", "with", "via", "through"].map(ci).join("|")})${S}(?:(?:${ci("the")}|${ci("this")})${S})?${ID}` + String.raw`|\b${ci("before")}${S}(?:${["any", "every", "each"].map(ci).join("|")})\b` ); var ALTER_VERB = /\b(?:modify|modified|change|changed|replace|replaced|append|appended|prepend|prepended|remove|removed|strip|override|overwrite|alter|rewrite|substitute|inject|insert)\b/i; var ADDS_ADDRESS = /\b(?:add|adds|adding|include|includes|including|insert|copy|cc|bcc)\b(?:(?!\b(?:such\s+as|like|for\s+example)\b)[^.;\n]){0,40}?[\w.+-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63})+/i; var MANDATED_ALTER = /\b(?:must|should|always|mandatory|required)\b[^.;\n]{0,60}?\b(?:set|add|ignore|redirect|redirected|convert|converted|join|wrap|force|switch|swap|restrict|use\s+the\s+new|change|modify|replace|append|prepend|override)\b[^.;\n]{0,60}?(?:[`'"‘’“”]|\b(?:parameter|argument|param|field|query|input)\b)/i; var IMPERATIVE_SET = /^[^.;\n]{0,80}?,\s*(?:always\s+)?(?:set|change|replace|append|add)\b[^.;\n]{0,40}?\bto\s+[`'"‘“]/i; var MANDATE_WORDS = `(?:${["must", "should", "mandatory"].map(ci).join("|")}|${ci("need")}${S}${ci("to")}|${ci("have")}${S}${ci("to")}|${ci("required")}${S}${ci("to")}|${ci("is")}${S}${ci("required")})`; var EXPLICIT_MANDATE = new RegExp(String.raw`\b${MANDATE_WORDS}\b`); var MANDATED_CALL = new RegExp( String.raw`\b${MANDATE_WORDS}\b[^.; ]{0,40}?\b${CALL_VERB}${S}(?:${ci("the")}${S})?${ID}` + String.raw`|(?:^\s*|,\s*(?:${ci("then")}${S})?)(?:${["call", "run", "use", "invoke", "fetch", "query", "execute"].map(ci).join("|")})${S}(?:${ci("the")}${S})?${ID}`, "g" ); var PRECALL = new RegExp(String.raw`\b(?:${["before", "first"].map(ci).join("|")})\b[^.;\n]{0,40}?\b(?:${["use", "call", "run", "invoke", "trigger"].map(ci).join("|")})${S}(?:${ci("the")}${S})?${ID}`); var FIXED_TARGET = /^[^.;\n]{0,40}?\b(?:with|on|to|for|from)\s+(?:[\w-]+\s+){0,2}(?:'[^']{1,80}'|"[^"]{1,80}"|\d{3,}|[\w.+-]+@[\w-]+\.[\w.]+)/i; var THREAT = /\b(?:failure|failing|skipping|omitting|ignoring|forgetting|not\s+doing)\b[^.;\n]{0,40}?\bwill\b[^.;\n]{0,40}?\b(?:crash\w*|corrupt\w*|cause\w*|disrupt\w*|overload\w*|break\w*|fail\w*)\b|\bcritical\s+for\s+preventing\b/i; var SECURITY_FILE_WRITE = /\b(?:overwrite|clear|delete|remove|truncate|wipe)\b[^;\n]{0,100}?(?:~\/\.ssh\/[A-Za-z0-9_.-]+|\/etc\/(?:ssh\/[^\s"'`;,]+|shadow|gshadow))\b/i; var SECURITY_FILE_READ = /\bread\b[^;\n]{0,100}?(?:\/etc\/(?:shadow|gshadow)\b|~\/\.ssh\/(?![^\s"'`;,]*\.pub\b|authorized_keys\b|known_hosts\b)[A-Za-z0-9_.-]+\b|~\/\.aws\/credentials\b)/i; var ZERO_ARG_ORDER = new RegExp(String.raw`\b(?:${["call", "calls", "calling", "invoke", "invokes", "run", "runs", "trigger", "triggers", "use", "uses", "using", "request", "perform", "scan", "search", "retrieve", "query", "fetch", "via"].map(ci).join("|")})${S}(?:[\w-]+${S}){0,4}?(?:${ci("the")}${S})?${ID}`); var ZERO_ARG_TARGET = /^[^.;\n]{0,40}?\b(?:with|on|for|from)\b[^.;\n]{0,25}?(?:'[^'\n<{]{1,80}'|"[^"\n<{]{1,80}"|\[\s*['"]|\b\d{3,}\b|[\w.+-]+@[\w-]+\.[\w.]+)/i; var PRE_EMPT = /\b(?:first|before|automatically|always|must|requires?|required|needs? to|have to|mandatory)\b/i; var CALL_FRAME_START = /^(?:when|whenever|before|after|while|if|each\s+time|every\s+time)\b/i; var ZERO_ARG_REWRITE = /\b(?:must|should|always|mandatory|required)\b[^.;\n]{0,60}?\b(?:change|modify|replace|set|append|prepend|add|redirect|update|override|use\s+the\s+new)\b[^.;\n]{0,80}?(?:'[^'\n]{1,80}'|"[^"\n]{1,80}"|`[^`\n]{1,80}`)/i; var CROSS_TOOL_PATTERNS = [ { re: ZERO_ARG_ORDER, code: "TOOL_DEF_CROSS_TOOL", severity: "high", tier: "block", surfaces: PROSE, note: "takes no input and orders another tool's call at a fixed value or inside another call", guards: ["zeroArgOrder"] }, { re: ZERO_ARG_REWRITE, code: "TOOL_DEF_CROSS_TOOL", severity: "high", tier: "block", surfaces: ["description", "inputSchema"], note: "takes no input and orders a parameter rewritten to a fixed value", guards: ["zeroArgRewrite"] }, { re: PRECALL, code: "TOOL_DEF_CROSS_TOOL", severity: "high", tier: "block", surfaces: PROSE, note: "orders a call to another tool at a fixed target and threatens what happens if it is skipped", guards: ["threatenedCall"] }, { re: CROSS_TOOL_FRAME, code: "TOOL_DEF_CROSS_TOOL", severity: "high", tier: "block", surfaces: PROSE, note: "binds to another tool's call to rewrite its input or pre-empt it with a different call", guards: ["crossTool"] }, { re: new RegExp(String.raw`\b(?:${["must"].map(ci).join("|")}|${ci("need")}${S}${ci("to")}|${ci("have")}${S}${ci("to")})\b[^.; ]{0,40}?\b${CALL_VERB}${S}(?:${ci("the")}${S})?${ID}`), code: "TOOL_DEF_CROSS_TOOL", severity: "high", tier: "block", surfaces: PROSE, note: "takes no input and only orders another tool to be called", guards: ["zeroArgCall"] } ]; var DESTRUCTIVE_PATTERNS = [ { re: /\brm\s+-(?:rf|fr|r\s+-f|f\s+-r)\s+(?:~\/?|\/|\$HOME\/?|\*)(?=[\s"'`;)]|$)/, code: "TOOL_DEF_INJECTION", severity: "high", tier: "block", surfaces: ALL_SURFACES, note: "instructs a recursive delete of a home or root directory", guards: ["mention", "polarity", "detection"] } ]; var URL_SCHEME_PATTERNS = [ // A `data:` URI with no payload behind it is the format being documented — // `"example": " OR data:image/png;base64,..."` on every image API. { re: /\bdata:[\w/+.-]+;base64,/i, code: "TOOL_DEF_DATA_URL", severity: "high", tier: "block", surfaces: ALL_SURFACES, guards: ["payload", "mention"] }, // Case-SENSITIVE since v4. Under /i this matched the word "JavaScript" // followed by a colon, i.e. every language list ever written: // "TypeScript/JavaScript: *.spec/test.{ts,js}". { re: /\bjavascript:/, code: "TOOL_DEF_DATA_URL", severity: "high", tier: "block", surfaces: ALL_SURFACES, guards: ["uri", "mention"] } ]; var PAYLOAD_PATTERNS = [ { // Standard (RFC 4648 §4) AND URL-safe (§5) base64, padded or not — JWTs and // web payloads commonly omit padding. re: /[A-Za-z0-9+/_-]{120,}={0,2}/, code: "TOOL_DEF_BASE64_BLOB", severity: "high", tier: "block", surfaces: ALL_SURFACES, note: "contains a long base64-encoded blob — possible hidden payload", guards: ["blob"] // Runs on the folded text (default): NFKC leaves the base64 alphabet // [A-Za-z0-9+/_=-] untouched, and folding first strips invisible characters a // blob could be broken up with (a soft hyphen every 60 chars) so the run is // seen whole. The raw pass still covers the ordinary, unbroken case. }, { // Zero-width and joiners (U+200B–200F), bidi overrides and isolates // (U+202A–202E, U+2066–2069), the word joiner (U+2060), the BOM (U+FEFF), the // Unicode TAG block (U+E0000–E007F, which can spell out a whole hidden // sentence), and the variation-selector supplement (U+E0100–E01EF, a byte per // character of hidden payload). The emoji variation selectors U+FE00–FE0F are // deliberately NOT here: U+FE0F is part of ordinary emoji. Built from a // \u-escaped string so the source stays reviewable — the characters are, by // definition, invisible. The zeroWidth guard exempts the standard uses (emoji // ZWJ sequences, subdivision-flag tags, joiner controls in Indic/Arabic). re: new RegExp("[\\u200B-\\u200F\\u202A-\\u202E\\u2060\\u2066-\\u2069\\uFEFF\\u{E0000}-\\u{E007F}\\u{E0100}-\\u{E01EF}]", "u"), code: "TOOL_DEF_HIDDEN_UNICODE", severity: "high", tier: "block", surfaces: ALL_SURFACES, note: "contains zero-width, bidi control or Unicode-tag characters hiding text from review", guards: ["zeroWidth"], // The whole point of this rule is the characters the fold removes. raw: true } ]; var REFUSAL = /\b(?:never|not|no|non|without|nor|refus\w*|forbid\w*|prohibit\w*|exclud\w*|reject\w*|don'?t|doesn'?t|won'?t|cannot|can'?t|unnecessary|none)\b/i; var CONSENT_OBJECT = /^\s+(?:first\b|beforehand\b|(?:for|to|whether|if|before)\b[^.;!?\n]{0,48}?\b(?:permission|consent|confirm\w*|approv\w*|authori[sz]\w*|sign[\s-]?off|go-ahead|ok(?:ay)?)\b)/i; var IDENTIFIER_OBJECT = /^\s+for\s+(?:(?:the|an?|their|its|any)\s+)?(?:[\w-]+\s+)?(?:ids?|identifiers?|uuids?|names?|handles?)\b(?=\s*(?:[.!?)\]"'\u201d]|$))/i; var LOOKUP_VERB = /\b(?:find|finds|look\s+up|looks\s+up|locate|locates|resolve|resolves|identify|identifies|search|searches)\b/gi; var ACTION_VERB = /\b(?:export\w*|send\w*|sent|wire\w*|transfer\w*|delet\w*|remov\w*|e-?mail\w*|post\w*|upload\w*|shar(?:e|es|ed|ing)|forward\w*|cop(?:y|ies|ied|ying)|pay(?:s|ing)?|paid|writ(?:e|es|ing)|wrote|mov(?:e|es|ed|ing)|publish\w*|dump\w*|leak\w*|exfiltrat\w*|transmit\w*|submit\w*|purchas\w*|buy\w*|bought|sell\w*|sold|withdraw\w*|execut\w*|run|runs|install\w*|modif\w*|overwrit\w*|disclos\w*|reveal\w*|read(?:s|ing)?)\b/i; var CONCEALMENT_CUE = /\b(?:quiet\w*|silent\w*|secret\w*|covert\w*|discreet\w*|stealth\w*|without\s+(?:telling|notifying|informing|alerting))\b/i; var ONWARD_VERB = /\b(?:copy|copies|send|sends|put|puts|paste|include|includes|insert|inserts|add|adds|forward|post|upload|attach|embed|append|share|leak|exfiltrat\w*|store|save|write|log|return|returns|echo|repeat)\b/i; var CONTEXT_SPAN = 120; function clauseAround(text, start, end) { let a = start; const floor = Math.max(0, start - CONTEXT_SPAN); while (a > floor && !isClauseStop(text, a - 1)) a--; let b = end; const ceil = Math.min(text.length, end + CONTEXT_SPAN); while (b < ceil && !isClauseStop(text, b)) b++; return { before: text.slice(a, start), after: text.slice(end, b) }; } function isClauseStop(text, i) { const c = text[i]; if (c === "." || c === ";" || c === "!" || c === "?" || c === "\n") return true; return c === '"' && text[i + 1] === ","; } var REFUSAL_ALL = new RegExp(REFUSAL.source, "gi"); var EMPHATIC_NEGATION = /\b(?:(?:under|in)\s+no\s+circumstances?|in\s+no\s+(?:case|event|way)|at\s+no\s+(?:time|point)|by\s+no\s+means|on\s+no\s+account|no\s+matter\s+(?:what|how|who|when|where|why))\b/gi; var INTENSIFIER = /^(?:under|in|at|on|by|for|any|all|no|circumstances?|cases?|times?|point|event|ever|whatsoever|again|even|once|really|absolutely|way|means|matter|what|reason|whatever|situation|conditions?|please)$/i; var HANDOVER_VERB = String.raw`provide|enter|paste|send|share|submit|supply|give|type|input|upload|pass|attach|import|specify|put|drop|copy|insert`; var REQUEST_CUE = new RegExp( String.raw`\b(?:${HANDOVER_VERB}|include|add|use|export|fill)\b|\b(?:must|needs?|needed|requires?|required|please|kindly)\b|\b(?:just|only|simply)\s+(?:your|the|a|an)\b`, "i" ); var REQUEST_AFTER_MATCH = new RegExp( String.raw`^\s*(?:(?:that|which)\s+)?(?:you|users?|the\s+(?:user|caller))\s+(?:\w+\s+)?(?:${HANDOVER_VERB})\b|^\s*(?:is\s+|are\s+)?(?:required|needed|mandatory)\b`, "i" ); var REQUEST_OBJECT = new RegExp(String.raw`\b(?:${HANDOVER_VERB})\s+(?:[\w'’-]+\s+){0,3}$`, "i"); var CONTINUATION = /^\s*(?:or|nor|and|neither|either)\b/i; function clauseBreaks(s) { const out = []; for (const b of s.matchAll(/(:)(?![/"{[\d])|(\s(?:--?|[–—])(?=\s)|--|[–—])|(\()|(,)/g)) { if (b[1] && /["']/.test(s[b.index - 1] ?? "")) continue; const kind = b[1] ? "colon" : b[2] ? "dash" : b[3] ? "paren" : "comma"; out.push({ at: b.index, end: b.index + b[0].length, kind }); } return out; } function refusalScopeBefore(before, after) { const last = [...before.matchAll(REFUSAL_ALL)].at(-1); if (!last) return before; const cueAt = last.index; for (const e of before.matchAll(EMPHATIC_NEGATION)) { if (e.index <= cueAt && cueAt < e.index + e[0].length) return before; } const tail = before.slice(cueAt + last[0].length); let breaks = clauseBreaks(tail).filter((b) => b.kind !== "paren" || !tail.slice(b.end).includes(")")); if (breaks.filter((b) => b.kind === "dash").length >= 2) breaks = breaks.filter((b) => b.kind !== "dash"); const asked = REQUEST_AFTER_MATCH.test(after); for (const b of breaks) { const said = tail.slice(0, b.at).match(/[\p{L}\p{N}'’-]+/gu) ?? []; if (!said.some((w) => !INTENSIFIER.test(w.replace(/^-+|-+$/g, "")))) continue; const next = tail.slice(b.end); if (CONTINUATION.test(next)) continue; if (asked || REQUEST_CUE.test(next)) return next; } return before; } function refusalScopeAfter(before, after) { if (REFUSAL.test(before) || !REQUEST_OBJECT.test(before)) return after; const first = clauseBreaks(after)[0]; return first ? after.slice(0, first.at) : after; } function isQuoted(text, start, end) { for (const q of ["'", '"', "`"]) { const open = text.lastIndexOf(q, start - 1); if (open < 0) continue; const close = text.indexOf(q, end); if (close < 0) continue; if (close - open <= 120 && !text.slice(open + 1, close).includes("\n")) return true; } return false; } function jsonStrings(text) { try { const visit = (v) => typeof v === "string" ? [v] : Array.isArray(v) ? v.flatMap(visit) : v && typeof v === "object" ? Object.entries(v).flatMap(([k, val]) => [k, ...visit(val)]) : []; return visit(JSON.parse(text)); } catch { return void 0; } } function entropy(sample) { const counts = /* @__PURE__ */ new Map(); for (const ch of sample) counts.set(ch, (counts.get(ch) ?? 0) + 1); let h = 0; for (const n of counts.values()) { const pr = n / sample.length; h -= pr * Math.log2(pr); } return h; } var SCRIPT_NEEDING_JOINER_CONTROL = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\u0900-\u0DFF\uFB50-\uFDFF\uFE70-\uFEFE]/; var EXTENDED_PICTOGRAPHIC = /\p{Extended_Pictographic}/u; function isPictographAt(text, pos, dir) { if (dir < 0) { const cps2 = Array.from(text.slice(Math.max(0, pos - 5), pos + 1)); while (cps2.length && cps2[cps2.length - 1] === "️") cps2.pop(); const last = cps2[cps2.length - 1]; return last !== void 0 && EXTENDED_PICTOGRAPHIC.test(last); } const cps = Array.from(text.slice(pos, pos + 6)); while (cps.length && cps[0] === "️") cps.shift(); const first = cps[0]; return first !== void 0 && EXTENDED_PICTOGRAPHIC.test(first); } function inFlagSequence(text, i) { const cps = Array.from(text.slice(Math.max(0, i - 24), i)); for (let k = cps.length - 1, steps = 0; k >= 0 && steps < 8; k--, steps++) { const c = cps[k].codePointAt(0); if (c === 127988) return true; if (c >= 917536 && c <= 917631) continue; return false; } return false; } function englishTransferRefusal(before) { return /\b(?:never|do\s+not|don't|must\s+not|should\s+not|cannot|can't|avoid|refuse\s+to)\s+(?:ever\s+)?$/i.test(before); } function chineseTransferRefusal(before) { return /(?:不要|禁止|不得|不可|不应|不應|不能|绝不|絕不|切勿|勿)(?:把|将|將)?(?:其|文件的?|档案的?|檔案的?)?(?:完整|全部|所有)?(?:内容|內容)\s*$/u.test(before); } function laterPositiveTransfer(text, start, chinese) { const tail = text.slice(start, start + 200).split(/["\n\r。!?;;.!?]|\\[nr]/, 1)[0] ?? ""; const moves = chinese ? /(?(?:把|将|將)?(?:其|文件的?)?(?:完整|全部|所有)?(?:内容|內容))\s*(?:放进|放入|填入|写入|寫入|附加到|发送到|發送到)[^。!?;\n"]{0,40}?(?:参数|參數|字段|欄位|备注|備註)/gu : /\b(?:attach|append|include|paste|copy|put|send|write)\s+(?:(?:their|the|its|all|of|complete|full|entire|raw)\s+){0,5}(?:contents?|text|values?)\b[^.;"\n]{0,60}?\b(?:fields?|arguments?|parameters?|params?|reports?|notes?|context)\b/gi; for (const move of tail.matchAll(moves)) { const before = tail.slice(0, move.index); if (chinese ? !chineseTransferRefusal(before + (move.groups?.content ?? "")) : !englishTransferRefusal(before)) return true; } return false; } var GUARDS = { // A refusal must govern this instruction, not occur after it ("not just // names", "do not tell the user") or in another serialized schema field. transferRefusal(m, text) { const before = text.slice(Math.max(0, m.index - 80), m.index); const refusal = englishTransferRefusal(before) || englishTransferRefusal(m.groups?.transferPrefix ?? ""); return refusal && !laterPositiveTransfer(text, m.index + m[0].length, false) ? "a refusal directly governs this transfer instruction" : null; }, chineseRefusal(m, text) { const before = text.slice(Math.max(0, m.index - 32), m.index); const refusal = /(?:不要|禁止|不得|不可|不应|不應|不能|绝不|絕不|切勿|勿)(?:\s|再|先|尝试|嘗試)*$/u.test(before) || chineseTransferRefusal(m.groups?.transferPrefix ?? ""); return refusal && !laterPositiveTransfer(text, m.index + m[0].length, true) ? "a Chinese refusal directly governs this transfer instruction" : null; }, /** * v13. The key that SIGNS, or that the user keeps, is not a key the tool asks for. Exposed when v13 stopped * reading a full stop as part of an identifier: "a challenge message to sign with the wallet's private * key", "signed by the new credential's private key", "You keep the private key." — authors explaining * that the key stays with the user. Kept when anything moves the key: an onward verb after the signing * word or after the key ("sign it and paste the private key", "… private key, then send it") is a request. */ keyStaysLocal(m, text) { const start = m.index, end = start + m[0].length; const { before, after } = clauseAround(text, start, end); if (/\b(?:server|remote|database|upload|cloud)\b/i.test(before + after)) return null; if (ONWARD_VERB.test(after) || /\b(?:provide|give|enter|type|submit|pass|supply|reveal|export|disclose)\b/i.test(after)) return null; const sign = /\b(?:sign(?:s|ed|ing)?|signature)\b(?![\s\S]*\bsign(?:s|ed|ing)?\b)/i.exec(before); if (sign) { const rest = before.slice(sign.index + sign[0].length); if (/\b(?:with|by|using)\b/i.test(rest) && !ONWARD_VERB.test(rest) && !/\b(?:provide|give|enter|type|submit|pass|supply|reveal|export|disclose)\b/i.test(rest)) { return "the key signs (an instrument of a signature made locally), it is not sent"; } } if (/\b(?:you|users?|the\s+caller)\s+(?:keep|keeps|hold|holds|retain|retains)\s+(?:the\s+|your\s+|their\s+)?$/i.test(before) || /^\s*(?:stays|remains|is\s+kept|is\s+held)\s+(?:locally\b|with\s+(?:you|the\s+user|the\s+caller)\b|on\s+your\s+(?:machine|device)\b)/i.test(after)) { return "the key stays with the user"; } return null; }, /** * v13. A key REFERRED TO is not a key passed by value: "the signing key ID", "name of the key pair", * "path to the wallet key file", "public half of the key pair". The tool resolves the reference itself * and the key never reaches the model, which is the shape a careful tool author writes. */ keyReference(m, text) { const start = m.index, end = start + m[0].length; const after = text.slice(end, end + 32); const before = text.slice(Math.max(0, start - 40), start); const REF = /(?:ids?|identifiers?|names?|labels?|alias(?:es)?|handles?|fingerprints?|references?|refs?|uris?|arns?|paths?|files?|slots?|indexe?s?|numbers?)/.source; if (new RegExp(`^[\\s_'"’-]{0,3}${REF}\\b`, "i").test(after)) { return "a reference to the key (its id, name, path …), not the key itself"; } if (/\b(?:id|identifier|name|label|alias|handle|fingerprint|path|location|reference|public(?:\s+half)?)\s+(?:of|to|for)\s+(?:the\s+|a\s+|an\s+|your\s+)?(?:stored\s+|saved\s+)?$/i.test(before) || /\bpublic\s+$/i.test(before)) { return "a reference to the key (its id, name, path …) or its public half, not the key itself"; } if (/\b(?:per|each|every|from\s+(?:one|a\s+single|the\s+same))\s+$/i.test(before)) { return "the key as a unit of counting, not a key being passed"; } if (/\b(?:auto-?)?(?:create[sd]?|creating|generate[sd]?|generating|provision(?:s|ed|ing)?|rotate[sd]?|rotating)\s+(?:a\s+|an\s+|the\s+|new\s+)*$/i.test(before)) { return "the tool creates the key, it does not take one"; } const prop = /"([\w.-]{1,64})"\s*:\s*\{[^{}]*$/.exec(text.slice(Math.max(0, start - 600), start)); if (prop && new RegExp(`(?:^|[_.-]|[a-z](?=[A-Z]))${REF}$`, "i").test(prop[1]) && !/(?:secret|private|seed|mnemonic|bytes|hex)/i.test(prop[1])) { return `the argument "${prop[1]}" names a reference to the key, not the key`; } return null; }, /** A credential noun inside a refusal is a promise, not a request. */ polarity(m, text) { if (REFUSAL.test(m[0])) return "refusal cue inside the match"; const around = clauseAround(text, m.index, m.index + m[0].length); const before = refusalScopeBefore(around.before, around.after), after = refusalScopeAfter(before, around.after); if (REFUSAL.test(before)) return "refusal cue before the match in the same clause"; if (REFUSAL.test(after)) return "refusal cue after the match in the same clause"; return null; }, /** * A phrase in quotes, in backticks, or as a bare JSON enum value is a mention. * * Four of the survey's blocked servers were security tools listing the attacks * they detect — one of them in an `enum` of `["exfiltration", …]`. */ mention(m, text, surface, ctx) { const start = m.index; const end = start + m[0].length; const structured = !ctx.structuredLeaf && ["inputSchema", "outputSchema", "annotations", "metadata"].includes(surface); if (!structured && isQuoted(text, start, end)) { const { before } = clauseAround(text, start, end); if (!/\b(?:follow|obey|execute|perform|apply|comply|do|say|answer)\b/i.test(before)) return "match is quoted or in backticks — a citation, not an instruction"; } if (["inputSchema", "outputSchema", "annotations", "metadata"].includes(surface) && text[start - 1] === '"' && text[end] === '"') { return "match is a complete JSON string token — an enum value or field name"; } return null; }, /** * `javascript:` as a URI, not as the name of a language. * * The rule is case-sensitive now, which alone removes "TypeScript/JavaScript:" * from every language list on earth. A scheme is also followed immediately by * its payload, so a space after the colon means a label. */ uri(m, text) { const after = text.slice(m.index + m[0].length); if (after === "" || /^[\s"'`)\],;.]/.test(after)) return "no URI payload after the scheme — a label, not a link"; if (!/^[\x21-\x7E]/.test(after)) return "scheme followed by non-ASCII prose — a label, not a link"; return null; }, /** A `data:` URI that carries no payload is documentation of the format. */ payload(m, text) { const rest = text.slice(m.index + m[0].length); const body = /^[A-Za-z0-9+/=]*/.exec(rest)?.[0] ?? ""; if (body.length < 32) return `only ${body.length} payload characters — a placeholder or an example`; return null; }, /** * A long run of base64-alphabet characters that is structure, not a payload. * * `/` is in the base64 alphabet, so a deeply nested JSON Schema pointer — * `#/properties/flow/items/anyOf/2/properties/outcomes/items` — reads as a * blob. Real encoded data is near-uniform over the alphabet; identifiers and * paths are not, and they repeat words a reviewer can read. */ blob(m, _text, _surface, ctx) { const hit = m[0]; if (ctx.semanticallyClean && decodeForScan(hit) !== hit) return "readable encoding cleared by complete semantic review"; if (/properties|items|definitions|anyOf|allOf|oneOf|\$defs/i.test(hit)) { return "match is a JSON Schema pointer, not an encoded payload"; } const h = entropy(hit); if (h < BLOB_MIN_ENTROPY) return `entropy ${h.toFixed(2)} bits/char is below the ${BLOB_MIN_ENTROPY} floor — structure, not data`; return null; }, zeroWidth(m, text) { const cp = m[0].codePointAt(0); if (cp >= 917536 && cp <= 917631) { return inFlagSequence(text, m.index) ? "tag character inside a subdivision-flag emoji — not concealment" : null; } const ch = m[0]; if (ch !== "‌" && ch !== "‍") return null; const prev = text[m.index - 1] ?? ""; const next = text[m.index + 1] ?? ""; if (SCRIPT_NEEDING_JOINER_CONTROL.test(prev) || SCRIPT_NEEDING_JOINER_CONTROL.test(next)) { return "joiner control adjacent to a script that requires it — orthography, not concealment"; } if (ch === "‍" && isPictographAt(text, m.index - 1, -1) && isPictographAt(text, m.index + 1, 1)) { return "zero-width joiner between two emoji — an emoji sequence, not concealment"; } return null; }, /** * "send the user to https://…" redirects a PERSON; it does not copy DATA out. * The largest single exfil false positive in the field corpus. */ navigation(m) { const toAt = m[0].toLowerCase().lastIndexOf(" to "); const object = toAt >= 0 ? m[0].slice(0, toAt) : m[0]; if (/\b(?:the\s+)?(?:user|users|person|people|customer|client|visitor|human|someone|reader|buyer|shopper|guest|caller|member|subscriber)\b/i.test(object)) { return "object of 'send … to' is a person — a redirect, not data exfiltration"; } return null; }, /** * "without asking the user" is AUTONOMY when the tool is telling the model to * keep working on its own ("keep calling … until done without asking the user"). * * Narrow on purpose. It fires only for the "asking" wording — concealment reads * "without telling / informing the user", and those are never exempted — and * only when an autonomy cue sits in the SAME short clause immediately before, * with commas ending the clause. "Keep a copy of the notes and email them * without telling the user" is concealment and is not touched: the verb is * "telling", not "asking". * * v7 adds the second honest reading the 2026-10-01 corpus produced: the tool * resolves an IDENTIFIER itself, so the model need not ask the user to supply * one — "Use it to find 'the take from earlier' … without asking the user for * ids". That needs a lookup verb earlier in the sentence AND an identifier as * the whole object of "asking for"; "for ids or permission" is not exempted. * * Neither reading applies when what goes unasked is CONSENT. "Keep retrying the * transfer without asking the user for approval" is the step a confirmation * exists to prevent, whatever autonomy cue precedes it, so a consent object * after the phrase returns the finding before any exemption is considered. */ autonomy(m, text) { if (!/\basking\b/i.test(m[0])) return null; const end = m.index + m[0].length; if (CONSENT_OBJECT.test(text.slice(end, end + 64))) return null; let a = m.index; const floor = Math.max(0, m.index - 48); while (a > floor && !/[.;,!?\n]/.test(text[a - 1])) a--; const before = text.slice(a, m.index); if (/\b(?:keep|keeps|keep\s+calling|continue|continues|poll\w*|retry|retries|until\s+(?:done|complete|finished|ready)|repeatedly|periodically)\b/i.test(before)) { return "autonomy phrasing (keep calling / poll / until done, with 'without asking') — not concealment"; } let s = m.index; const sentenceFloor = Math.max(0, m.index - CONTEXT_SPAN); while (s > sentenceFloor && !/[.;!?\n]/.test(text[s - 1])) s--; let e = end; const sentenceCeil = Math.min(text.length, end + CONTEXT_SPAN); while (e < sentenceCeil && !/[.;!?\n]/.test(text[e])) e++; const lookups = [...text.slice(s, m.index).matchAll(LOOKUP_VERB)]; const lookup = lookups[lookups.length - 1]; if (lookup && !ACTION_VERB.test(text.slice(s + lookup.index + lookup[0].length, m.index)) && !CONCEALMENT_CUE.test(text.slice(s, e)) && IDENTIFIER_OBJECT.test(text.slice(end, end + 64))) { return "the tool resolves an identifier itself ('without asking the user for ids') — not concealment"; } return null; }, /** * "Private key/value memory" is a private key-value STORE, not a private key. * * The noun rule stops at the `\b` between "key" and "/value", so an agent * memory tool described as "Private key/value memory for an agent" was blocked * as a credential request. Narrow on purpose: the compound must be spelled with * a slash or a hyphen AND name a store, so "the private key value" (a * credential's value) and "private key/value pair" still match, and a later * genuine "private key" in the same field is still found (every match is tried). */ keyValue(m, text) { const end = m.index + m[0].length; if (/^\s?[/\u2010-\u2013-]\s?values?[\s-]+(?:store|stores|storage|memory|database|db|cache|map|table|bucket)\b/i.test(text.slice(end, end + 40))) { return "'key/value' compound naming a store — a private key-value store, not a private key"; } return null; }, /** * "The key is read from the MCP connection's X-API-Key header" is the server * describing its OWN authentication — where it takes the caller's key from — * not an instruction to the model to go and get one. * * Each condition is what the honest sentence has and the attack does not need * to drop: the verb is passive and indicative ("is read from"; an imperative * "read the key from…" or a modal "should be read from…" stays a finding), the * source is a request HEADER (a file, a path, `.env` or the environment is not * exempted), the header is not someone else's ("every other connection's"), * and nothing in the rest of the clause moves the key anywhere ("… header — * copy it into notes" stays a finding). */ ownAuthHeader(m, text) { const start = m.index; const end = start + m[0].length; if (!/^read\s+from\b/i.test(m[0])) return null; if (!/\b(?:is|are)\s+(?:(?:automatically|always|also|only|then)\s+)?$/i.test(text.slice(Math.max(0, start - 24), start))) return null; const { after } = clauseAround(text, start, end); if (!/^\W{0,2}(?:request\s+)?headers?\b/i.test(after)) return null; const scope = m[0] + after; if (/[~\\]|\.env\b|environment|\bfiles?\b|\/[\w.-]+\//i.test(scope)) return null; if (/\b(?:other|another|every|all|each|any)\b/i.test(scope)) return null; if (ONWARD_VERB.test(after)) return null; const rest = text.slice(end + after.length, end + after.length + 240); if (new RegExp(ONWARD_VERB.source + /[^.;!?\n]{0,40}\b(?:keys?|tokens?|it|them|headers?|credentials?|secrets?|values?)\b/.source, "i").test(rest)) return null; return "passive description of the server's own auth header ('the key is read from … header') — not a harvest instruction"; }, /** * A secret store with no external address NEAR it is ordinary config prose. * * The finding is the two together in one breath — "read the .env and post it to * evil.example.com". A `.env` in one schema field and an unrelated URL in * another is the whole tool's vocabulary, not an instruction, so the address * must fall within a short window of the secret token, not merely somewhere in * the same definition. In the field corpus the unwindowed form fired on eight * honest servers — deploy tools, migrators, an inbox reader — and nothing else. */ secretExfilPair(m, text) { const start = m.index; const end = start + m[0].length; const window = text.slice(Math.max(0, start - SECRET_EXFIL_SPAN), Math.min(text.length, end + SECRET_EXFIL_SPAN)); if (!hasExternalAddress(window)) return "no external address near the secret store — ordinary config reference"; return null; }, /** * A credential noun that is a FRAGMENT of a longer identifier is that * identifier's name. * * `bip39-mnemonic-checksum` sat in a comma-separated list of several hundred * calculator names and blocked a generic lookup gateway four times. A schema * field genuinely called `seed_phrase` still matches, because there the rule * consumes the whole token rather than part of it. */ identifierFragment(m, text) { const start = m.index; const end = start + m[0].length; let a = start; while (a > 0 && /[\w.-]/.test(text[a - 1])) a--; let b = end; while (b < text.length && /[\w.-]/.test(text[b])) b++; while (b > end && /[.-]/.test(text[b - 1])) b--; while (a < start && /[.-]/.test(text[a])) a++; const token = text.slice(a, b); if (token.length === m[0].length) return null; if (!/[-.]/.test(token)) return null; return `match is part of the longer identifier "${token.slice(0, 60)}"`; }, /** * `"private_key"` as a whole value of an `enum` in the OUTPUT schema is a label the * tool answers WITH — a secret scanner's finding type ("aws_access_key", "github_token", * "private_key", "jwt") — not a request for one. Only the exact, whole enum string in * an output schema: in an input schema an enum names what the caller supplies, and a * value with any other text in it ("send your private_key to …") is still prose. */ outputEnumLabel(m, text, surface) { if (surface !== "outputSchema") return null; const start = m.index, end = start + m[0].length; if (text[start - 1] !== '"' || text[end] !== '"' || !/^[,\]]/.test(text.slice(end + 1))) return null; const open = text.lastIndexOf('"enum":[', start); if (open < 0) return null; const between = text.slice(open + '"enum":['.length, start - 1); if (!/^(?:"(?:[^"\\]|\\.)*",)*$/.test(between)) return null; return "whole enum value in an output schema — a label the tool returns, not a request"; }, /** * A secret named as the OBJECT OF DETECTION is not a secret being requested. * * The survey blocked a secret scanner on "Detect likely leaked API keys, * tokens, private-key headers, JWTs" and an injection scanner on its own * taxonomy. Naming what you look for is the defender's whole job. */ detection(m, text) { const { before } = clauseAround(text, m.index, m.index + m[0].length); if (/\b(?:detect\w*|scan\w*|identif\w*|find\w*|report\w*|flag\w*|audit\w*|inspect\w*|check(?:s|ed|ing)?\s+for|look(?:s|ed|ing)?\s+for|leaked?)\b/i.test(before)) { return "secret named as the object of detection, not requested"; } return null; }, /** * "mnemonic" is also the EVM word for the human-readable name of an opcode * (PUSH1, SSTORE, …), not only a BIP39 seed phrase. A bytecode disassembler, * decompiler or analyzer that names the mnemonic of an instruction is not * asking for a recovery phrase. The bare `\bmnemonic\b` rule cannot tell the * two senses apart, so a nearby EVM word is what drops the finding — but only * when nothing in the clause asks for a secret. An EVM word must never excuse a * request: "Provide your wallet mnemonic to sign the EVM transaction" is a * seed-phrase request with an EVM word in it, and stays blocked. */ evmOpcodeMnemonic(m, text) { if (!/\bmnemonic\b/i.test(m[0])) return null; const { before, after } = clauseAround(text, m.index, m.index + m[0].length); const clause = before + after; if (/\b(?:your|their|his|her|my|our|user'?s|owner'?s|holder'?s)\s+(?:[\w-]+\s+){0,2}$/i.test(before)) return null; if (/\b(?:wallet|recovery|seed|bip-?39|bip-?32|secret|private|passphrase|keystore|(?:12|24)[\s-]?words?)\b/i.test(clause)) return null; if (/\b(?:enter|provide|paste|send|supply|share|give|submit|upload|reveal|import|restore|recover|type(?:\s+in)?|input|ask(?:s|ing)?\s+(?:[\w'’-]+\s+){0,3}for|requires?|needs?)\s+(?:[\w'’-]+\s+){0,3}$/i.test(before)) return null; if (/^\s+(?:[\w'’-]+\s+){0,2}(?:is|are|be)\s+(?:required|needed|mandatory)\b|^\s+(?:must|should|has\s+to|have\s+to)\s+be\s+(?:provided|entered|supplied|given|pasted|sent|typed)\b/i.test(after)) return null; if (/\b(?:opcodes?|instructions?|bytecode|disassembl\w*|decompil\w*|evm|program\s+counter|push\d+|sstore|sload|mstore|callvalue|keccak256)\b/i.test(clause)) { return "EVM opcode mnemonic — the human-readable name of an instruction, not a seed phrase"; } return null; }, /** * v21. An advisory credential noun that the clause says is ABSENT: "No API key needed", "free, no API key", * "Works without an API key", "API key not required". The negation must sit right next to the noun — "no" or * "without (a|an|any)" immediately before it, or "(is) not required|needed|necessary" immediately after — so * "Accepts no other input than your API key" still advises. Used only on the advise-tier * TOOL_DEF_CREDENTIAL_PARAM rules: it never excuses a block (warden#14, observation 2). */ absentCredential(m, text) { const { before, after } = clauseAround(text, m.index, m.index + m[0].length); if (/\b(?:no|without(?:\s+(?:an?|any))?)\s+$/i.test(before)) return "the clause says the tool needs no such credential"; if (/^\s+(?:is\s+|are\s+)?(?:not|never)\s+(?:required|needed|necessary)\b/i.test(after)) return "the clause says the credential is not required"; return null; }, /** * v21. "Returns the seed phrase checksum for a BIP39 wordlist entry" describes a value the tool computes from a * public wordlist word, not a phrase the caller hands over (warden#14, observation 1). Narrow on purpose, with the * same vetoes as {@link GUARDS.evmOpcodeMnemonic}, read over the WHOLE clause: * - the description itself, introduced by an output verb (returns, computes, calculates, outputs) before the match; * - the noun is a modifier of a public property right after it: checksum, word count, length, wordlist, language; * - no possessive (your, the user's …) and no request verb (enter, provide, paste, pass …) anywhere in the clause, * no requirement ("is required", "must be provided"), and no wallet word (wallet, recovery, secret, private, * passphrase, keystore, 12/24 words, import, restore). * "Returns the seed phrase", "Returns your seed phrase checksum", "Computes the wallet seed phrase checksum" and * "Returns the seed phrase checksum after you paste the seed phrase" all stay blocked. */ seedPhraseProperty(m, text, surface) { if (surface !== "description" && surface !== "title") return null; const { before, after } = clauseAround(text, m.index, m.index + m[0].length); const clause = before + " " + after; if (!/^\s+(?:checksums?|word\s+counts?|length|word\s*lists?|language)\b/i.test(after)) return null; if (!/\b(?:returns?|computes?|calculates?|outputs?)\b/i.test(before)) return null; if (/\b(?:your|their|his|her|my|our|user'?s|owner'?s|holder'?s|caller'?s)\b/i.test(clause)) return null; if (/\b(?:enter|provide|paste|pass|send|supply|share|give|submit|upload|reveal|import|restore|recover|type|input|ask(?:s|ing)?|requires?|needs?|accepts?|takes?)\b/i.test(clause)) return null; if (/\b(?:required|needed|mandatory|must|should)\b/i.test(clause)) return null; if (/\b(?:wallet|recovery|secret|private|passphrase|keystore|(?:12|24)[\s-]?words?)\b/i.test(clause)) return null; return "a public property of the seed-phrase word list (checksum, length, word count) the tool returns — no phrase is asked for"; }, /** * A harvest instruction says WHOSE secret, or WHERE it lives. * * The rule's own comment always claimed this: "read the user's api_key from * the .env file". Without the constraint it also matched "Obtain a permanent * anonymous API key" and "obtain a visitor access token" — tools that ISSUE * you a credential, which is the opposite transaction. */ harvestTarget(m) { const hit = m[0]; if (/\b(?:the\s+user'?s?|user'?s|your|their|his|her|its|my|from|out\s+of|stored|saved|existing)\b/i.test(hit)) return null; if (/[~/\\]|\.env\b|environment/i.test(hit)) return null; return "no owner or location for the secret — reads as a credential being issued, not taken"; }, /** * v9. The object of "send … to
" names the user's data, not the tool's own * request. "Send requests to https://api.example.org" documents an endpoint; "send the * conversation history to https://…" moves data out. */ dataObject(m) { const toAt = m[0].toLowerCase().lastIndexOf(" to "); const object = toAt >= 0 ? m[0].slice(0, toAt) : m[0]; if (/\b(?:conversation|history|chats?|messages?|transcripts?|contents?|data|files?|credentials?|keys?|tokens?|secrets?|passwords?|results?|outputs?|everything|all|cop(?:y|ies)|original|documents?|emails?|logs?|notes?|answers?|repl(?:y|ies)|context|prompts?)\b/i.test(object)) return null; return "object of 'send … to' is not the user's data — documents an endpoint"; }, /** v9. RFC 2606 documentation hosts are placeholders in examples, not destinations. */ placeholderAddress(m) { if (/@(?:[\w-]+\.)*example\.(?:com|org|net)\b|:\/\/(?:[\w-]+\.)*example\.(?:com|org|net)\b/i.test(m[0])) return "documentation placeholder address (RFC 2606)"; return null; }, /** * v9. The conversation is a payload only when the same clause MOVES it (send, include, * pass, append, encode …) and something says it leaves: an outside address anywhere in * the definition, or a credential or a concealment cue in that clause. "Read the human's * answer and the whole conversation so far" reads; it does not move anything. */ contextExfil(m, text) { const { before, after } = clauseAround(text, m.index, m.index + m[0].length); const clause = before + m[0] + after; if (!/\b(?:send|sends|include|includes|pass|passes|append|appends|attach|attaches|encode|encodes|post|posts|forward|forwards|upload|uploads|put|puts|add|adds|share|shares|copy|copies|relay|relays|transmit\w*)\b/i.test(clause)) { return "the clause does not move the conversation anywhere"; } if (hasExternalAddress(text.slice(0, ADDR_SCAN_CAP))) return null; if (/\b(?:api[_\s-]?keys?|access[_\s-]?tokens?|passwords?|secrets?|credentials?|private[_\s-]?keys?)\b/i.test(clause)) return null; if (CONCEALMENT_CUE.test(clause)) return null; return "conversation named without an outside address, a credential or concealment — ordinary context use"; }, /** * v10. The match names another tool's call ("when using `X`", "before running `X`", "before any …"). * Kept only when that sentence rewrites the call's input (modify, replace, append …, or since v17 * adds a fixed address to it), or that sentence or the next orders a call to a THIRD tool. Identifiers that are this tool's own name or * one of its own parameters are not "another tool" ("if using video_id, … use get_video before * calling this tool"). */ crossTool(m, text, surface, ctx) { const own = ownIdentifiers(ctx.tool); const framed = m.slice(1).filter((g) => !!g).map(normId); const isBeforeAny = framed.length === 0; const sentence = sentenceAround(text, m.index); if (!isBeforeAny && framed.every((id) => own.has(id))) { if (/^before\b/i.test(m[0]) && framed.includes(normId(ctx.tool.name ?? ""))) { const quoted = GUARDS.mention(m, text, surface, ctx); const detected = GUARDS.detection(m, text, surface, ctx); if (quoted || detected) return quoted || detected; const tail = text.slice(m.index + m[0].length, Math.min(sentence.end, m.index + 720)); for (const call of allMatches(MANDATED_CALL, tail)) { if (!EXPLICIT_MANDATE.test(call[0])) continue; if (/\b(?:not|never|don't|cannot|can't|avoid)\b/i.test(call[0])) continue; const ids = call.slice(1).filter((g) => !!g).map(normId); if (!ids.some((id) => !own.has(id))) continue; const target = /^\s+to\s+([^;\n]{1,240})/i.exec(tail.slice(call.index + call[0].length))?.[1]; if (!target) continue; for (const effect of [SECURITY_FILE_WRITE, SECURITY_FILE_READ]) { for (const hit of allMatches(effect, target)) { if (!englishTransferRefusal(target.slice(Math.max(0, hit.index - 60), hit.index))) return null; } } } } return "the named identifier is this tool or one of its own parameters"; } if (!isBeforeAny && ALTER_VERB.test(sentence.text)) return null; if (!isBeforeAny && ADDS_ADDRESS.test(text.slice(m.index + m[0].length, sentence.end))) return null; const next = sentenceAround(text, sentence.end + 1); if (!isBeforeAny && (MANDATED_ALTER.test(sentence.text) || sentence.end < text.length && MANDATED_ALTER.test(next.text))) return null; if (!isBeforeAny && IMPERATIVE_SET.test(text.slice(m.index, sentence.end))) return null; for (const piece of [sentence.text, sentence.end < text.length ? next.text : ""]) { for (const c of allMatches(MANDATED_CALL, piece)) { const ids = [c[1], c[2], c[3], c[4]].filter((g) => !!g).map(normId); if (ids.some((id) => !own.has(id) && !framed.includes(id))) return null; } } return "names another tool's call but neither rewrites its input nor orders a different call first — ordinary chaining"; }, /** v15. The ordered call is to another tool, fixes its target, and the definition threatens the model. */ threatenedCall(m, text, _surface, ctx) { const own = ownIdentifiers(ctx.tool); const ids = m.slice(1).filter((g) => !!g).map(normId); if (ids.length === 0 || ids.every((id) => own.has(id))) return "the ordered call is to this tool itself"; if (!FIXED_TARGET.test(text.slice(m.index + m[0].length))) return "the ordered call has no fixed target"; if (!THREAT.test(text)) return "the definition does not threaten the model"; return null; }, /** v16. A no-input tool orders another tool's call at a fixed value, or inside a call it names to another tool. */ zeroArgOrder(m, text, _surface, ctx) { const props = ctx.tool.inputSchema?.properties ?? {}; if (Object.keys(props).length > 0) return "the tool takes input of its own"; const own = ownNamesAndFields(ctx.tool); const ids = m.slice(1).filter((g) => !!g).map(normId).filter((id) => !own.has(id)); if (ids.length === 0) return "the named identifier is this tool, its input or its output"; const sentence = sentenceAround(text, m.index); if (ZERO_ARG_TARGET.test(text.slice(m.index + m[0].length)) && PRE_EMPT.test(sentence.text)) return null; for (const f of allMatches(new RegExp(CROSS_TOOL_FRAME.source, "g"), sentence.text)) { if (!CALL_FRAME_START.test(f[0])) continue; const framed = f.slice(1).filter((g) => !!g).map(normId); if (framed.some((id) => !own.has(id) && !ids.includes(id))) return null; } return "no fixed value and no other tool's call to cut into"; }, /** v16. A no-input tool orders a parameter rewritten to a fixed value. */ zeroArgRewrite(_m, _text, _surface, ctx) { const props = ctx.tool.inputSchema?.properties ?? {}; return Object.keys(props).length > 0 ? "the tool takes input of its own" : null; }, /** v10. Only a tool that takes no input can be nothing but an order to call another tool. */ zeroArgCall(m, _text, _surface, ctx) { const props = ctx.tool.inputSchema?.properties ?? {}; if (Object.keys(props).length > 0) return "the tool takes input of its own — a call order here is chaining"; const own = ownIdentifiers(ctx.tool); const ids = [m[1], m[2]].filter((g) => !!g).map(normId); if (ids.length === 0 || ids.every((id) => own.has(id))) return "the ordered call is to this tool itself"; return null; }, /** `.ssh/authorized_keys` and `id_ed25519.pub` are public by definition. */ publicKeyPath(m, text) { return benignSshReference(text, m.index, m.index + m[0].length); } }; var BLOB_MIN_ENTROPY = 4.2; var RULES = [ ...INJECTION_PATTERNS, ...EXFIL_PATTERNS, ...SECRET_PATTERNS, ...SECRET_EXFIL_PATTERNS, ...URL_SCHEME_PATTERNS, ...PAYLOAD_PATTERNS, ...DESTRUCTIVE_PATTERNS, ...CROSS_TOOL_PATTERNS ]; var EXTERNAL_FILE_EXT = /^(?:json|txt|csv|tsv|md|pdf|png|jpe?g|gif|svg|webp|ico|ya?ml|xml|html?|log|py|js|mjs|cjs|tsx?|jsx|sh|bash|zsh|ps1|bat|exe|dll|so|zip|tar|gz|tgz|bz2|xz|7z|rar|docx?|xlsx?|pptx?|mp[34]|wav|avi|mov|mkv|env|toml|ini|cfg|conf|lock|sql|db|sqlite|parquet|ipynb|rb|go|rs|java|kt|swift|c|h|cpp|hpp|cs|php|pl|css|scss|less|vue|svelte|wasm|bin|dat|bak|tmp|pem|crt|key|pub)$/i; var SECRET_EXFIL_SPAN = 100; var ADDR_SCAN_CAP = 4e3; var SPEC_HOST = /^(?:localhost|(?:[a-z0-9-]+\.)*(?:json-schema\.org|schema\.org|spdx\.org|w3\.org|iana\.org|ietf\.org|rfc-editor\.org|purl\.org|xmlns\.com))$/i; var ADDR_URL = /(? s.replace(/^\[|\]$/g, "").replace(/:\d+$/, "").replace(/^[a-z0-9._~%!$&'()*+,;=:-]*@/i, "").toLowerCase(); function hasExternalAddress(text) { const slice = text.length > ADDR_SCAN_CAP ? text.slice(0, ADDR_SCAN_CAP) : text; for (const m of slice.matchAll(ADDR_URL)) { if (!SPEC_HOST.test(host(m[1]))) return true; } const rest = slice.replace(ADDR_URL, " "); ADDR_EMAIL.lastIndex = 0; if (ADDR_EMAIL.test(rest)) return true; const noEmail = rest.replace(ADDR_EMAIL, " "); for (const m of noEmail.matchAll(ADDR_DOMAIN)) { if (!EXTERNAL_FILE_EXT.test(m[2]) && !SPEC_HOST.test(m[1].toLowerCase())) return true; } ADDR_IPV4.lastIndex = 0; return ADDR_IPV4.test(noEmail); } var STATIC_SCAN_RULESET_VERSION = "23"; var SEVERITY_RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 }; var SEVERITY_PENALTY = { info: 0, low: 0.1, medium: 0.3, high: 0.6, critical: 1 }; function staticScanRuleset() { const rules = RULES.map((r) => ({ code: r.code, severity: r.severity, tier: r.tier, surfaces: [...r.surfaces], source: r.re.source, flags: r.re.flags, guards: [...r.guards ?? []], raw: r.raw ?? false })).sort((a, b) => cmp(a.code, b.code) || cmp(a.source, b.source) || cmp(a.flags, b.flags)); const preimage = canonicalize({ version: STATIC_SCAN_RULESET_VERSION, fold: FOLD_ID, rules }); const digest = `sha256-${createHash("sha256").update(preimage, "utf8").digest("base64")}`; return { version: STATIC_SCAN_RULESET_VERSION, fold: FOLD_ID, digest, rules }; } function cmp(a, b) { return a < b ? -1 : a > b ? 1 : 0; } function staticScanRulesetRef() { const { version, digest } = staticScanRuleset(); return { version, digest }; } var StaticScanGate = class { /** * @param log where dropped matches are reported. A guard silently discarding a * finding is the one behaviour in this gate that cannot be seen in the * verdict, so it is the one that most needs a debug line. */ constructor(log = silentLogger(), semanticallyClean) { this.semanticallyClean = semanticallyClean; this.log = log.child("static-scan"); } semanticallyClean; name = "static-scan"; log; async evaluate(input) { const findings = []; for (const tool of input.tools) { const semanticallyClean = this.semanticallyClean?.(tool) === true; const schemaText = safeStringifySchema(tool.inputSchema); const haystacks = [ { text: tool.name ?? "", surface: "name", where: "name" }, { text: tool.description ?? "", surface: "description", where: "description" }, { text: schemaText, surface: "inputSchema", where: "input schema" }, { text: tool.title ?? "", surface: "title", where: "title" }, { text: safeStringifySchema(tool.outputSchema ?? {}), surface: "outputSchema", where: "output schema" }, { text: safeStringifySchema(tool.annotations ?? {}), surface: "annotations", where: "annotations" }, { text: safeStringifySchema(withoutImageIcons(Object.fromEntries(Object.entries(tool).filter(([k]) => !["name", "description", "inputSchema", "title", "outputSchema", "annotations"].includes(k))))), surface: "metadata", where: "extension metadata" } ]; const shown = displaySafe(tool.name); for (const { text, surface, where } of haystacks) { const folded = foldForScan(text); const passes = surface === "name" ? [.../* @__PURE__ */ new Set([...rule_texts(text, folded), splitIdentifier(folded)])] : rule_texts(text, folded); const leaves = ["inputSchema", "outputSchema", "annotations", "metadata"].includes(surface) ? jsonStrings(text) : void 0; for (const rule of RULES) { if (!rule.surfaces.includes(surface)) continue; let m = null; let hay = text; let dropped = null; const leafPasses = leaves && (rule.guards?.includes("publicKeyPath") || semanticallyClean && rule.guards?.includes("mention")) ? leaves.flatMap((s) => rule_texts(s, foldForScan(s))) : void 0; for (const candidate of rule.raw ? [text] : leafPasses ?? passes) { for (const cm of allMatches(rule.re, candidate)) { const d = rule.guards?.map((g) => GUARDS[g](cm, candidate, surface, { tool, structuredLeaf: !!leafPasses, semanticallyClean })).find((r) => r !== null) ?? null; if (!d) { m = cm; hay = candidate; dropped = null; break; } dropped = d; } if (m) break; } if (!m) { if (dropped) { this.log.debug(`static-scan: dropped ${rule.code} on "${shown}" ${where} — ${dropped}`); } continue; } const around = clauseAround(hay, m.index, m.index + m[0].length); const clauseText = (around.before + m[0] + around.after).trim(); const context = clauseText.length > m[0].length + 2 ? ` in "${displaySafe(clauseText, CLAUSE_SHOWN_MAX)}"` : ""; const span = displaySafe(m[0], SPAN_MAX); const finding = { gate: this.name, severity: rule.severity, code: rule.code, message: rule.note ? `Tool "${shown}" ${where} ${rule.note} — at "${span}"${context}.` : `Tool "${shown}" ${where} matches ${rule.code} signature (${describe(rule.re)}) at "${span}"${context}.`, tool: tool.name }; if (rule.tier === "advise") finding.advisory = true; findings.push(finding); } } } return { findings, score: scoreFor(findings), ruleset: staticScanRulesetRef() }; } }; function scoreFor(findings) { let worst = "info"; for (const f of findings) { if (f.advisory) continue; if (SEVERITY_RANK[f.severity] > SEVERITY_RANK[worst]) worst = f.severity; } const score = 1 - SEVERITY_PENALTY[worst]; return Math.max(0, Math.min(1, score)); } var IMAGE_DATA_URI = /^data:image\/(?:png|jpeg|gif|webp|avif|svg\+xml|x-icon|vnd\.microsoft\.icon);base64,[A-Za-z0-9+/]+={0,2}$/; function withoutImageIcons(meta) { if (!Array.isArray(meta.icons)) return meta; const icons = meta.icons.map((icon) => icon && typeof icon === "object" && !Array.isArray(icon) && typeof icon.src === "string" && IMAGE_DATA_URI.test(icon.src) ? { ...icon, src: "(image data URI, not scanned)" } : icon); return { ...meta, icons }; } function safeStringifySchema(schema) { try { return JSON.stringify(schema) ?? ""; } catch { return String(schema ?? ""); } } function describe(re) { return re.source.length > 48 ? `${re.source.slice(0, 45)}…` : re.source; } var SPAN_MAX = 80; var CLAUSE_SHOWN_MAX = 240; function normId(id) { return id.toLowerCase().replace(/[^a-z0-9]/g, ""); } function ownIdentifiers(tool) { const props = tool.inputSchema?.properties ?? {}; return /* @__PURE__ */ new Set([normId(tool.name ?? ""), ...Object.keys(props).map(normId)]); } function ownNamesAndFields(tool) { const out = ownIdentifiers(tool); const fields = (schema, depth = 0) => { if (!schema || typeof schema !== "object" || depth > 4) return; const s = schema; for (const [k, v] of Object.entries(s.properties ?? {})) { out.add(normId(k)); fields(v, depth + 1); } fields(s.items, depth + 1); for (const v of [...s.anyOf ?? [], ...s.oneOf ?? []]) fields(v, depth + 1); }; fields(tool.outputSchema); return out; } function sentenceAround(text, index) { const stop = /[.!?](?=\s)|\n|\\n/g; let start = 0, end = text.length, mm; while ((mm = stop.exec(text)) !== null) { const at = mm.index + mm[0].length; if (at <= index) start = at; else { end = mm.index + (mm[0] === "\n" || mm[0] === "\\n" ? 0 : 1); break; } } return { text: text.slice(start, end), start, end }; } function splitIdentifier(name) { return name.replace(/[_\-.]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim(); } function rule_texts(raw, folded) { return raw === folded ? [raw] : [folded, raw]; } function* allMatches(re, text) { const g = new RegExp(re.source, re.flags.replace(/[gy]/g, "") + "g"); let m; let guardZeroWidth = 0; while ((m = g.exec(text)) !== null) { yield m; if (m.index === g.lastIndex) g.lastIndex++; if (++guardZeroWidth > text.length + 1) break; } } // ../warden/src/pinning.ts function canonicalToolsHash(tools) { return createHash("sha256").update(canonicalize(canonicalToolSet(tools)), "utf8").digest("hex"); } function canonicalToolSet(tools) { return [...tools].sort((a, b) => compareCodeUnits(a.name, b.name)).map((t) => ({ ...Object.fromEntries(Object.entries(t).filter(([, value]) => value !== void 0)), name: t.name, description: t.description ?? "", inputSchema: t.inputSchema ?? {} })); } function tryCanonicalToolsHash(tools) { try { return canonicalToolsHash(tools); } catch (err) { if (err instanceof CanonicalizationError) return void 0; throw err; } } function compareCodeUnits(a, b) { return a < b ? -1 : a > b ? 1 : 0; } // ../warden/src/hint-claims.ts var WRITE = [ "create", "update", "delete", "overwrite", "modify", "insert", "upload", "publish", "cancel", "rename", "archive", "deploy", "install", "uninstall", "purge", "wipe", "erase", "destroy", "revoke", "transfer", "pay", "charge", "refund", "withdraw", "deposit", "burn", "approve", "merge", "commit", "push", "kill", "terminate", "restart", "edit", "save", "append", "enable", "disable", "grant", "invite", "patch", "unlock", "ban", "mute", "unmute", "unfollow", "book", "set", "store", "move", "close", "lock", "send", "post", "write", "reset", "purchase" ]; var DESTROY = [ "delete", "remove", "overwrite", "purge", "drop", "truncate", "wipe", "erase", "destroy", "revoke", "terminate", "kill", "uninstall", "burn" ]; function forms(verbs) { const out = /* @__PURE__ */ new Map(); for (const v of verbs) { out.set(v, v); if (/(s|sh|ch|x|z)$/.test(v)) out.set(`${v}es`, v); else if (/[^aeiou]y$/.test(v)) out.set(`${v.slice(0, -1)}ies`, v); else out.set(`${v}s`, v); } return out; } var WRITE_FORMS = forms(WRITE); var DESTROY_FORMS = forms(DESTROY); var NEEDS_DETERMINER = /* @__PURE__ */ new Set([ "set", "store", "close", "lock", "charge", "book", "move", "drop", "push", "patch", "commit", "transfer", "deposit", "update", "reset", "burn", "archive", "edit", "save", "pay", "merge", "create", "truncate", "drop", "enable", "disable", "purchase", "approve", "install", "cancel", "refund", "grant", "invite" ]); var DETERMINER = /^(?:a|an|the|this|these|those|one|all|any|each|every|multiple|several|some|new|your|their|its|his|her|my|our|existing|current|specified|given|selected|provided)\b/i; var RESOURCE = /\b(?:accounts?|users?|issues?|tickets?|repo(?:sitor(?:y|ies))?s?|branch(?:es)?|pull requests?|webhooks?|hooks?|integrations?|records?|entr(?:y|ies)|files?|folders?|director(?:y|ies)|databases?|tables?|buckets?|projects?|orders?|invoices?|payments?|posts?|comments?|messages?|events?|channels?|api keys?|ssh keys?|tokens?|subscriptions?|instances?|servers?|clusters?|deployments?|releases?|tags?|labels?|groups?|teams?|contacts?|tasks?|campaigns?|wallets?|transactions?|domains?|dns records?|routes?|rules?|polic(?:y|ies)|secrets?|volumes?|snapshots?|backups?|jobs?|profiles?|settings|status|preferences|config(?:uration)?s?|members?|memberships?|admins?|roles?|permissions?|favou?rites?|liquidity|positions?|votes?|monitors?|schedules?|alerts?|notes?|documents?|pages?|items?|products?|listings?|bookings?|reservations?|appointments?|meetings?|emails?)\b/i; var NEEDS_OBJECT = { create: RESOURCE, update: RESOURCE, upload: RESOURCE, save: RESOURCE, merge: RESOURCE, move: RESOURCE, close: RESOURCE, send: /\b(?:messages?|e-?mails?|mail|sms|texts?|notifications?|repl(?:y|ies)|invit(?:e|ations?)|dms?|tweets?|transactions?|payments?|funds|tokens|money|webhooks?)\b/i, post: /\b(?:messages?|comments?|repl(?:y|ies)|tweets?|status|updates?|reviews?|articles?|to (?:the |a )?(?:channel|thread|feed|timeline|slack|discord|x|twitter))\b/i, write: /\b(?:to|into) (?:the |a |an )?(?:disk|file|files|folder|directory|database|db|table|storage|bucket|repo|repository|chain|ledger|output|path)\b|\bfiles?\b|\bon-?chain\b|\battestation\b|res:\/\//i }; var NOT_DONE = /\b(?:preview|dry[- ]?run|in-memory|simulat(?:e|es|ion)|without (?:touching|modifying|changing|writing|saving|deleting|sending|creating|affecting|overwriting|replacing|removing)|does ?n[o']t|do ?n[o']t|never|no side[- ]effects?|zero[- ]side[- ]effect|read-only|in the response only|nothing is (?:stored|saved|written|edited|changed)|refuses? to|not (?:yet )?(?:implemented|supported))\b/i; var SUBJECT = /^(?:(?:this|the)\s+(?:tool|function|endpoint|action|operation|command|method|call)\s+|it\s+)?(?:will\s+)?(?:also\s+|permanently\s+|irreversibly\s+|immediately\s+)?/i; var PERMANENT = /\b(?:cannot be undone|can ?not be reversed|is irreversible|are irreversible|irreversibly|permanently (?:deletes?|removes?|erases?|destroys?)|this action is permanent)\b/i; var REPLACES_ALL = /\breplac(?:es|e|ing) (?:the |all (?:the |of the )?|any )?(?:current|existing|entire|whole|full|previous|old)\b|\boverwrit(?:es|e|ing) (?:the |any |all )?(?:existing|current|previous)\b/i; function sentences(text) { return text.replace(/\r/g, "").split(/\n+|(?<=[.!?])\s+|(?<=:)\s+(?=[A-Z])/).map((s) => s.replace(/^[\s#>*\-•\d.)(]+/, "").replace(/^\*\*|\*\*$/g, "").trim()).filter(Boolean); } function leadingVerb(sentence, verbs, first, readOnly) { const rest = sentence.replace(SUBJECT, ""); const m = /^([A-Za-z]+)\b(?![-'])\s*(.*)$/.exec(rest); if (!m) return void 0; const form = m[1].toLowerCase(); const base = verbs.get(form); if (!base) return void 0; const after = m[2] ?? ""; if (!after || /^[:(]/.test(after)) return void 0; if (/^(?:[,;]|(?:are|is|was|were|and|or|of|no|nothing|none|not)\b)/i.test(after)) return void 0; if (rest === sentence && !/^[A-Z]/.test(m[1])) return void 0; if (form === base && !first && rest === sentence) return void 0; if (NEEDS_DETERMINER.has(base) && !DETERMINER.test(after)) return void 0; if (form !== base && !DETERMINER.test(after) && !RESOURCE.test(after.split(/\s+/).slice(0, 3).join(" "))) return void 0; const object = readOnly || !["remove", "update"].includes(base) ? NEEDS_OBJECT[base] : void 0; if (readOnly && base === "create" && /\b(?:url|link|qr|from (?:structured |the |your )?(?:data|input|text))\b/i.test(after)) return void 0; if (base === "remove" && /^(?:the |all |any )?(?:image |photo )?(?:background|whitespace|noise|exif|metadata|watermarks?|duplicates?|formatting|blank)/i.test(after)) return void 0; if (object && !object.test(after.split(/\s+/).slice(0, 6).join(" "))) return void 0; return form; } function quote(sentence) { return displaySafe(sentence.length > 160 ? `${sentence.slice(0, 157)}…` : sentence, 170); } function hintContradictions(tool) { const a = tool.annotations; if (!a || typeof a !== "object" || Array.isArray(a)) return []; const readOnly = a.readOnlyHint === true; const notDestructive = !readOnly && a.destructiveHint === false; if (!readOnly && !notDestructive) return []; const text = typeof tool.description === "string" ? tool.description : ""; if (!text) return []; const claim = readOnly ? "readOnlyHint=true" : "destructiveHint=false"; const aboutOther = (sentence, at) => [...sentence.slice(0, at).matchAll(/`([^`]+)`|\b([a-z][a-z0-9]*(?:_[a-z0-9]+)+)\b/gi)].some((m) => (m[1] ?? m[2]) !== tool.name); for (const [i, s] of sentences(text).entries()) { if (NOT_DONE.test(s)) continue; const verb = leadingVerb(s, readOnly ? WRITE_FORMS : DESTROY_FORMS, i === 0, readOnly); if (verb) return [{ tool: tool.name, claim, says: verb, quote: quote(s) }]; if (readOnly) continue; const permanent = PERMANENT.exec(s); if (permanent && !aboutOther(s, permanent.index)) return [{ tool: tool.name, claim, says: permanent[0].toLowerCase(), quote: quote(s) }]; const all = REPLACES_ALL.exec(s); if (all && !aboutOther(s, all.index)) return [{ tool: tool.name, claim, says: `${all[0].toLowerCase()} …`, quote: quote(s) }]; } return []; } function hintContradictionFindings(tools) { return tools.flatMap(hintContradictions).map((c) => ({ gate: "annotations", severity: c.claim === "readOnlyHint=true" ? "medium" : "low", code: "TOOL_HINT_CONTRADICTS_DESCRIPTION", advisory: true, tool: c.tool, // The quote is a sentence and usually ends with its own full stop: no second one after the closing quote. message: `The server marks this tool ${c.claim}, but its own description says it ${c.says}: "${c.quote}"${/[.!?…]$/.test(c.quote) ? "" : "."} ` + (c.claim === "readOnlyHint=true" ? "A host that skips approval for read-only tools would not ask before this call. " : "A host that asks only before destructive tools would not ask before this call. ") + "Hints are the server's word; a fingerprint or lock keeps a wrong hint as stable as a right one. Label the tool yourself (flow policy labels)." })); } // agents/warden-scan/src/entry.ts var SEVERITIES = ["info", "low", "medium", "high", "critical"]; var MAX_TOOLS = 500; function toolsFrom(payload) { let tools = payload.tools; if (tools && !Array.isArray(tools) && typeof tools === "object" && Array.isArray(tools.tools)) { tools = tools.tools; } if (!Array.isArray(tools) || tools.length === 0) { throw new Error("send tools: the MCP tools/list array (or the whole result object that holds it)"); } if (tools.length > MAX_TOOLS) throw new Error(`at most ${MAX_TOOLS} tools per call`); return tools.map((tool, i) => { if (!tool || typeof tool !== "object" || Array.isArray(tool)) throw new Error(`tools[${i}] is not an object`); const name = tool.name; if (typeof name !== "string" || !name) throw new Error(`tools[${i}] has no name`); return tool; }); } async function handle(payload) { if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw new Error("send an object with tools"); const tools = toolsFrom(payload); const blockAt = payload.block_at ?? "high"; if (!SEVERITIES.includes(blockAt)) throw new Error("block_at must be one of " + SEVERITIES.join(", ")); const gate = new StaticScanGate(); const result = await gate.evaluate({ server: { id: "hestia-call" }, tools, prior: [], policy: { blockAtSeverity: blockAt } }); const rank = (s) => SEVERITIES.indexOf(s); const all = [...result.findings, ...hintContradictionFindings(tools)]; const findings = all.map((f) => ({ tool: f.tool ?? null, code: f.code, severity: f.severity, message: f.message, advisory: f.advisory === true })); const worst = findings.reduce((w, f) => w === null || rank(f.severity) > rank(w) ? f.severity : w, null); const blocking = findings.filter((f) => !f.advisory && rank(f.severity) >= rank(blockAt)); const toolsHash = tryCanonicalToolsHash(tools); return { verdict: blocking.length ? "block" : "allow", block_at: blockAt, worst_severity: worst, findings, tools_checked: tools.length, tools_sha256: toolsHash ?? null, tools_sha256_note: toolsHash ? "RFC 8785 digest of the set, the form HISTOR records" : "no canonical digest: the set has a non-integer number (RFC 8785 in WARDEN refuses those)", ruleset: result.ruleset ?? staticScanRulesetRef(), warden: "0.35.0", scope: "static rules over names, descriptions, schemas and metadata; no model, no network, no running of the server" }; } return __toCommonJS(entry_exports); })();