@acepaste/ingress 0.0.0-stage → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +15 -2
  3. package/dist/src/acepaste-alphabet.d.ts +26 -0
  4. package/dist/src/acepaste-alphabet.js +47 -0
  5. package/dist/src/acquire.d.ts +42 -0
  6. package/dist/src/acquire.js +271 -0
  7. package/dist/src/adapters.d.ts +30 -0
  8. package/dist/src/adapters.js +160 -0
  9. package/dist/src/character.d.ts +22 -0
  10. package/dist/src/character.js +291 -0
  11. package/dist/src/cli.d.ts +2 -0
  12. package/dist/src/cli.js +75 -0
  13. package/dist/src/color.d.ts +26 -0
  14. package/dist/src/color.js +111 -0
  15. package/dist/src/engine.d.ts +131 -0
  16. package/dist/src/engine.js +715 -0
  17. package/dist/src/evidence.d.ts +21 -0
  18. package/dist/src/evidence.js +77 -0
  19. package/dist/src/index.d.ts +28 -0
  20. package/dist/src/index.js +20 -0
  21. package/dist/src/meaning.d.ts +28 -0
  22. package/dist/src/meaning.js +227 -0
  23. package/dist/src/netpolicy.d.ts +34 -0
  24. package/dist/src/netpolicy.js +122 -0
  25. package/dist/src/normalize.d.ts +34 -0
  26. package/dist/src/normalize.js +204 -0
  27. package/dist/src/policyfile.d.ts +2 -0
  28. package/dist/src/policyfile.js +50 -0
  29. package/dist/src/sandbox.d.ts +45 -0
  30. package/dist/src/sandbox.js +231 -0
  31. package/dist/src/script.d.ts +23 -0
  32. package/dist/src/script.js +220 -0
  33. package/dist/src/secrets.d.ts +24 -0
  34. package/dist/src/secrets.js +192 -0
  35. package/dist/src/summary.d.ts +40 -0
  36. package/dist/src/summary.js +62 -0
  37. package/dist/src/supplychain.d.ts +24 -0
  38. package/dist/src/supplychain.js +182 -0
  39. package/dist/src/taint.d.ts +37 -0
  40. package/dist/src/taint.js +39 -0
  41. package/dist/src/types.d.ts +202 -0
  42. package/dist/src/types.js +33 -0
  43. package/dist/src/visibility.d.ts +41 -0
  44. package/dist/src/visibility.js +424 -0
  45. package/package.json +64 -4
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Evidence model (Kith & Revere lineage, ported 2026-10-31).
3
+ *
4
+ * Kith & Revere's constitutional rule: a Fact is an artifact that
5
+ * demonstrably exists; an Inference is what a rule concluded from Facts; a
6
+ * Hypothesis is what Facts are consistent with but do not establish. No
7
+ * artifact, no finding. Every conclusion states its benign alternative.
8
+ *
9
+ * Applied here: every gate finding is a conclusion, so it is an Inference or
10
+ * (when its confidence is in the low band) a Hypothesis, never a Fact. It
11
+ * cites its artifact by digest: the excerpt it matched, or the whole acquired
12
+ * body when the finding is about the page as a whole. And it carries the
13
+ * benign explanation a reviewer should rule out before acting on it.
14
+ */
15
+ import type { Finding } from "./types.js";
16
+ export type EvidenceClass = "inference" | "hypothesis";
17
+ export type ConfidenceBand = "high" | "medium" | "low";
18
+ export declare function bandOf(confidence: number): ConfidenceBand;
19
+ export declare function alternativeFor(kind: string): string;
20
+ /** Attach evidence class, band, artifact digest and benign alternative to every finding (in place). */
21
+ export declare function attachEvidence(findings: Finding[], rawDigest: string): void;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Evidence model (Kith & Revere lineage, ported 2026-10-31).
3
+ *
4
+ * Kith & Revere's constitutional rule: a Fact is an artifact that
5
+ * demonstrably exists; an Inference is what a rule concluded from Facts; a
6
+ * Hypothesis is what Facts are consistent with but do not establish. No
7
+ * artifact, no finding. Every conclusion states its benign alternative.
8
+ *
9
+ * Applied here: every gate finding is a conclusion, so it is an Inference or
10
+ * (when its confidence is in the low band) a Hypothesis, never a Fact. It
11
+ * cites its artifact by digest: the excerpt it matched, or the whole acquired
12
+ * body when the finding is about the page as a whole. And it carries the
13
+ * benign explanation a reviewer should rule out before acting on it.
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ export function bandOf(confidence) {
17
+ return confidence >= 0.8 ? "high" : confidence >= 0.5 ? "medium" : "low";
18
+ }
19
+ /** benign explanations a reviewer must rule out, by finding-kind prefix (longest prefix wins) */
20
+ const ALTERNATIVES = [
21
+ ["policy.denied_source", "the source or address is on a deny list by configuration, not because of anything in its content"],
22
+ ["policy.redirect_chain", "ordinary link shorteners, sign-in hops and content-delivery redirects"],
23
+ ["unicode.tag_characters", "emoji flag sequences for subdivisions (such as the Scotland or Wales flags) legitimately use tag characters"],
24
+ ["unicode.zero_width", "text pasted from word processors, or scripts that need joiners and the context check missed"],
25
+ ["unicode.whitespace_channel", "typesetting that uses fine spaces deliberately, such as typeset mathematics or some East Asian layouts"],
26
+ ["unicode.bidi_control", "mixed right-to-left and left-to-right text that an editor wrapped in direction controls"],
27
+ ["unicode.variation_selector_smuggling", "emoji presentation selectors or ideographic variation sequences in East Asian text"],
28
+ ["unicode.mixed_script_confusable", "brand names, transliteration, or multilingual text mixing scripts within a word"],
29
+ ["unicode.fullwidth_or_math_lookalike", "East Asian full-width typography, or mathematical notation"],
30
+ ["unicode.combining_flood", "decorative 'zalgo' text, or dense diacritics in some languages and transcriptions"],
31
+ ["unicode.encoded_payload", "data attributes, tokens, hashes, images or other encoded data that happen to decode to readable text"],
32
+ ["unicode.entity_smuggling", "an editor or content system that over-encodes characters as entities"],
33
+ ["visibility.", "accessibility text for screen readers, collapsed sections, tooltips, analytics markup, or design choices; hidden text is not delivered either way"],
34
+ ["script.obfuscation", "a minifier or commercial code-protection tool on legitimate code"],
35
+ ["script.runtime_codegen", "template engines, bundler runtimes or polyfills that generate code legitimately"],
36
+ ["script.automation_detection", "bot-management and fraud-prevention scripts that check for automation without serving different content"],
37
+ ["script.post_load_text_injection", "single-page applications that render all their text after load"],
38
+ ["script.exfil_beacon", "analytics, error reporting and advertising beacons"],
39
+ ["script.binary_decoding", "media players, font loaders, compression libraries and WebAssembly loaders"],
40
+ ["supplychain.lifecycle_script", "native modules that download prebuilt binaries at install, or build tooling that runs a setup script"],
41
+ ["supplychain.url_dependency", "forks pinned to a Git commit, private packages, or monorepo tarballs"],
42
+ ["supplychain.offregistry_resolution", "a company's private registry or a registry mirror"],
43
+ ["supplychain.install_instruction", "real installation documentation; the gate weights visible commands low for this reason"],
44
+ ["secrets.", "example or revoked credentials in documentation, or test fixtures"],
45
+ ["sandbox.text_injected_after_load", "client-side rendering of ordinary content"],
46
+ ["sandbox.webdriver_keyed_divergence", "sites that show bots a simplified page or a consent wall without hostile intent"],
47
+ ["sandbox.computed_hidden_text", "menus, modals and responsive layouts that hide content until a user acts"],
48
+ ["sandbox.blocked_egress_attempt", "third-party fonts, analytics or content-delivery requests the sandbox does not allow"],
49
+ ["meaning.instruction_shaped", "articles, tutorials and security research that quote instructions, or content addressed to human readers"],
50
+ ["meaning.role_token", "documentation of chat templates, or transcripts"],
51
+ ["meaning.system_prompt_imitation", "documentation describing system prompts"],
52
+ ["meaning.tool_call_shaped", "API documentation and code samples"],
53
+ ["meaning.exfil_markdown_image", "images with ordinary tracking or cache-busting query strings"],
54
+ ["meaning.exfil_link", "legitimate webhook or form endpoints mentioned in documentation"],
55
+ ["cloaking.", "personalization, A/B tests, geolocation, or different layouts for different browsers"],
56
+ ["plugin.", "defined by the custom detector's author"],
57
+ ];
58
+ export function alternativeFor(kind) {
59
+ let best = "";
60
+ let alt = "no benign explanation recorded for this kind";
61
+ for (const [prefix, text] of ALTERNATIVES)
62
+ if (kind.startsWith(prefix) && prefix.length > best.length) {
63
+ best = prefix;
64
+ alt = text;
65
+ }
66
+ return alt;
67
+ }
68
+ const sha256 = (s) => createHash("sha256").update(s, "utf8").digest("hex");
69
+ /** Attach evidence class, band, artifact digest and benign alternative to every finding (in place). */
70
+ export function attachEvidence(findings, rawDigest) {
71
+ for (const f of findings) {
72
+ f.band = bandOf(f.confidence);
73
+ f.evidenceClass = f.band === "low" ? "hypothesis" : "inference";
74
+ f.artifactDigest = f.excerpt ? sha256(f.excerpt) : rawDigest;
75
+ f.altExplanation = alternativeFor(f.kind);
76
+ }
77
+ }
@@ -0,0 +1,28 @@
1
+ export { IngressEngine, aggregate, buildEnvelope, buildLogEntry, compareServed, servedWords, VISIBILITY_ONLY_CAP } from "./engine.js";
2
+ export type { EngineDeps, IngressOptions } from "./engine.js";
3
+ export { acquire, acquireWithBrowser, AcquireError, MAX_REDIRECTS, HONEST_USER_AGENT } from "./acquire.js";
4
+ export type { FetchLike, AcquireOptions } from "./acquire.js";
5
+ export { summarize, findingWeight, cloakingConfigFromEnv } from "./summary.js";
6
+ export type { ResultSummary, FindingGroup, TopFinding } from "./summary.js";
7
+ export { checkTarget, isPrivateIP, isPrivateIPv4, isPrivateIPv6, NetPolicyError, DEFAULT_NET_POLICY } from "./netpolicy.js";
8
+ export type { NetPolicy } from "./netpolicy.js";
9
+ export { analyzeHtml, findStylesheetLinks, rulesFromCss, colorRulesFromCss } from "./visibility.js";
10
+ export type { HiddenRule, ColorRule, VisibilityResult } from "./visibility.js";
11
+ export { parseColor, contrastRatio, INVISIBLE_CONTRAST } from "./color.js";
12
+ export { scanCharacters } from "./character.js";
13
+ export { analyzeScripts, analyzeScript } from "./script.js";
14
+ export { scanMeaning, neutralizeMeaning } from "./meaning.js";
15
+ export { scanSupplyChain } from "./supplychain.js";
16
+ export { scanSecrets, redactSecrets, collectSecrets, scrubExcerpt } from "./secrets.js";
17
+ export { attachEvidence, alternativeFor, bandOf } from "./evidence.js";
18
+ export type { EvidenceClass, ConfidenceBand } from "./evidence.js";
19
+ export { detectKind, decodeEntities, adaptMarkdown, adaptJson, adaptText, adaptJavascript } from "./adapters.js";
20
+ export { runSandbox, DEFAULT_SCRIPT_HOSTS } from "./sandbox.js";
21
+ export type { SandboxResult } from "./sandbox.js";
22
+ export { createTaintGuard } from "./taint.js";
23
+ export type { TaintGuard, TaintPolicy } from "./taint.js";
24
+ export { loadPolicyFile } from "./policyfile.js";
25
+ export { countHostileInvisibles, ACEPASTE_INVISIBLE_SOURCE, ACEPASTE_INVISIBLE_SUPPL_SOURCE } from "./acepaste-alphabet.js";
26
+ export * from "./types.js";
27
+ /** @deprecated renamed to IngressEngine in 0.7.0 (AcePaste Gate -> AcePaste Ingress) */
28
+ export { IngressEngine as GateEngine } from "./engine.js";
@@ -0,0 +1,20 @@
1
+ export { IngressEngine, aggregate, buildEnvelope, buildLogEntry, compareServed, servedWords, VISIBILITY_ONLY_CAP } from "./engine.js";
2
+ export { acquire, acquireWithBrowser, AcquireError, MAX_REDIRECTS, HONEST_USER_AGENT } from "./acquire.js";
3
+ export { summarize, findingWeight, cloakingConfigFromEnv } from "./summary.js";
4
+ export { checkTarget, isPrivateIP, isPrivateIPv4, isPrivateIPv6, NetPolicyError, DEFAULT_NET_POLICY } from "./netpolicy.js";
5
+ export { analyzeHtml, findStylesheetLinks, rulesFromCss, colorRulesFromCss } from "./visibility.js";
6
+ export { parseColor, contrastRatio, INVISIBLE_CONTRAST } from "./color.js";
7
+ export { scanCharacters } from "./character.js";
8
+ export { analyzeScripts, analyzeScript } from "./script.js";
9
+ export { scanMeaning, neutralizeMeaning } from "./meaning.js";
10
+ export { scanSupplyChain } from "./supplychain.js";
11
+ export { scanSecrets, redactSecrets, collectSecrets, scrubExcerpt } from "./secrets.js";
12
+ export { attachEvidence, alternativeFor, bandOf } from "./evidence.js";
13
+ export { detectKind, decodeEntities, adaptMarkdown, adaptJson, adaptText, adaptJavascript } from "./adapters.js";
14
+ export { runSandbox, DEFAULT_SCRIPT_HOSTS } from "./sandbox.js";
15
+ export { createTaintGuard } from "./taint.js";
16
+ export { loadPolicyFile } from "./policyfile.js";
17
+ export { countHostileInvisibles, ACEPASTE_INVISIBLE_SOURCE, ACEPASTE_INVISIBLE_SUPPL_SOURCE } from "./acepaste-alphabet.js";
18
+ export * from "./types.js";
19
+ /** @deprecated renamed to IngressEngine in 0.7.0 (AcePaste Gate -> AcePaste Ingress) */
20
+ export { IngressEngine as GateEngine } from "./engine.js";
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Meaning pass.
3
+ *
4
+ * Pattern-based detection of instruction-shaped and exfiltration-shaped
5
+ * text. This is the weakest pass by design: attackers evade classifiers.
6
+ * Its job is to catch commodity payloads in the forms they ship (also
7
+ * spaced, leet, reversed, rot13, homoglyph-spelled: see normalize.ts),
8
+ * and to score hidden text harder than visible text. Hidden instruction-
9
+ * shaped text is nearly always an attack; visible instruction-shaped text
10
+ * may be an article, a support macro, or a runbook, so one visible shape
11
+ * stays below the suspect threshold and two or more cross it. Text inside
12
+ * code blocks is documentation by default and is discounted.
13
+ *
14
+ * Known gap (2026-10-01): patterns are English. Non-English instructions
15
+ * reach the model unless they are hidden (visibility pass) or encoded
16
+ * (character pass). Multilingual coverage needs native-speaker review and
17
+ * is tracked as an open item, not shipped as Claude-generated translations.
18
+ */
19
+ import type { Finding, TextSegment } from "./types.js";
20
+ export interface MeaningInput {
21
+ /** segments from the visibility pass (or a single visible segment for plain text) */
22
+ segments: TextSegment[];
23
+ /** payloads decoded by the character pass */
24
+ decodedPayloads: readonly string[];
25
+ }
26
+ export declare function scanMeaning(input: MeaningInput): Finding[];
27
+ /** Remove the matched role tokens and exfiltration constructs from delivered text (override delivery). */
28
+ export declare function neutralizeMeaning(text: string): string;
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Meaning pass.
3
+ *
4
+ * Pattern-based detection of instruction-shaped and exfiltration-shaped
5
+ * text. This is the weakest pass by design: attackers evade classifiers.
6
+ * Its job is to catch commodity payloads in the forms they ship (also
7
+ * spaced, leet, reversed, rot13, homoglyph-spelled: see normalize.ts),
8
+ * and to score hidden text harder than visible text. Hidden instruction-
9
+ * shaped text is nearly always an attack; visible instruction-shaped text
10
+ * may be an article, a support macro, or a runbook, so one visible shape
11
+ * stays below the suspect threshold and two or more cross it. Text inside
12
+ * code blocks is documentation by default and is discounted.
13
+ *
14
+ * Known gap (2026-10-01): patterns are English. Non-English instructions
15
+ * reach the model unless they are hidden (visibility pass) or encoded
16
+ * (character pass). Multilingual coverage needs native-speaker review and
17
+ * is tracked as an open item, not shipped as Claude-generated translations.
18
+ */
19
+ import { variants } from "./normalize.js";
20
+ const ROLE_TOKENS = [
21
+ /<\|im_start\|>|<\|im_end\|>|<\|endoftext\|>|<\|system\|>|<\|user\|>|<\|assistant\|>|<\|end\|>/i,
22
+ /\[INST\]|\[\/INST\]|<<SYS>>|<\/?s>\s*\[INST\]/,
23
+ /<\|start_header_id\|>|<\|eot_id\|>|<\|begin_of_text\|>|<\|eom_id\|>/,
24
+ /<start_of_turn>|<end_of_turn>|<bos>|<eos>/,
25
+ /<\|user\|>|<\|assistant\|>|<\|system\|>|<\|end\|>/,
26
+ /<\/?(system|instructions?|system_prompt|developer|tool_result|function_results|function_calls|invoke|antml:[a-z_]+|tool_call|tool_response|thinking)>/i,
27
+ /\{\{#(system|user|assistant)\}\}|<\|start\|>(system|developer|user)/i,
28
+ ];
29
+ /** Line-start role labels: transcripts, screenplays and chat exports look like this too, so these are weak evidence on their own */
30
+ const WEAK_ROLE_LABELS = [
31
+ /^\s*(###\s*)?(system|assistant|user|developer|human|tool)\s*:\s*/im,
32
+ /\n\n(Human|Assistant|System):\s/,
33
+ ];
34
+ /** JSON or XML shaped tool invocations in content: an attempt to get an agent to echo a call */
35
+ const TOOL_CALL_SHAPES = [
36
+ /\{\s*"(tool_calls?|function_call|name)"\s*:\s*"?[\w.-]+"?\s*,\s*"(arguments|parameters|input)"\s*:/i,
37
+ /<(function_calls|tool_call|invoke)\b[^>]*>[\s\S]{0,400}<\/(function_calls|tool_call|invoke)>/i,
38
+ // same line only: "run:" followed by a code block on the next line is documentation layout, not an invocation
39
+ /\b(run|execute|call)[ \t]*:[ \t]*`?(bash|sh|python|node|curl|wget|rm -rf|chmod|ssh)\b/i,
40
+ ];
41
+ const INSTRUCTION_SHAPES = [
42
+ [/\bignore\s+(all\s+|any\s+)?(previous|prior|above|earlier|preceding)\s+(instructions?|prompts?|directions?|rules?|context)/i, 0.9, "ignore previous instructions"],
43
+ [/\bdisregard\s+(all\s+|any\s+)?(previous|prior|above|your)\s+(instructions?|prompts?|rules?|guidelines?)/i, 0.9, "disregard instructions"],
44
+ [/\b(you\s+are\s+now|from\s+now\s+on\s+you\s+(are|will|must))\b/i, 0.6, "role reassignment"],
45
+ [/\bnew\s+(instructions?|task|directive|system\s+prompt)\s*:/i, 0.7, "new instructions directive"],
46
+ [/\b(do\s+not|don'?t|never)\s+(tell|inform|reveal|mention|show|disclose)\s+(this\s+to\s+)?(the\s+)?(user|human|operator)/i, 0.95, "conceal from user"],
47
+ [/\b(ai|assistant|language\s+model|llm|agent|chatbot|copilot|claude|gpt|gemini)\b[^.\n]{0,60}\b(must|should|need\s+to|is\s+required\s+to|has\s+to)\b/i, 0.55, "addressed to the model"],
48
+ [/\b(important|attention|note)\s+(to|for)\s+(the\s+)?(ai|assistant|agent|llm|model|bot)s?\b/i, 0.85, "addressed to the model"],
49
+ [/\b(if\s+you\s+are\s+an?\s+(ai|llm|language\s+model|assistant|agent|bot))\b/i, 0.9, "conditional on being a model"],
50
+ [/\b(print|output|repeat|reveal|show|leak|exfiltrate|send)\s+(me\s+)?(your|the)\s+(system\s+prompt|instructions|initial\s+prompt|hidden\s+prompt|context|conversation|api\s+key|credentials?|secrets?|tokens?)/i, 0.9, "prompt or secret extraction"],
51
+ [/\b(call|invoke|use|run|execute)\s+(the\s+)?(tool|function|command)\s+[`'"]?\w+/i, 0.5, "tool invocation request"],
52
+ [/\b(send|post|email|forward|upload|transmit)\s+[^.\n]{0,80}\b(to|at)\s+(https?:\/\/|[\w.-]+@[\w.-]+\.\w+)/i, 0.65, "outbound send instruction"],
53
+ [/\b(send|post|email|forward|upload|transmit|paste|include|attach)\s+(me\s+)?(your|the|this|all|every|our)\s+[^.\n]{0,30}\b(conversation|context|chat\s+history|message\s+history|messages|system\s+prompt|instructions|credentials?|secrets?|api\s+keys?|tokens?|cookies?|session|memory)\b/i, 0.9, "context exfiltration"],
54
+ [/\b(summar(y|ize)|respond|reply|answer)\s+(with|by\s+saying)\s*[:"']/i, 0.35, "forced response shape"],
55
+ [/\bend\s+of\s+(system|user|developer)\s+(message|prompt|instructions)/i, 0.8, "fake message boundary"],
56
+ [/\b(override|bypass|disable|turn\s+off)\s+(your\s+|all\s+|the\s+)?(safety|content|security)?\s*(filters?|guidelines?|restrictions?|guardrails?|rules?|policies)/i, 0.85, "guardrail override"],
57
+ [/\b(developer|debug|maintenance|admin|god)\s+mode\b/i, 0.55, "privileged-mode claim"],
58
+ [/\b(this\s+is\s+(a|an)\s+)?(authorized|official|verified|trusted)\s+(instruction|request|message|command)\s+from\s+(the\s+)?(system|developer|administrator|anthropic|openai|google)/i, 0.9, "authority impersonation"],
59
+ [/\bwhen\s+(you|the\s+(assistant|agent|model))\s+(read|see|process|encounter)s?\s+this\b/i, 0.7, "trigger-on-read"],
60
+ [/\b(remember|store|save|note)\s+(this|the\s+following)\s+(for|in)\s+(future|later|all\s+future)\s+(conversations?|sessions?|interactions?)/i, 0.7, "memory poisoning"],
61
+ [/\b(always|from\s+now\s+on|whenever|every\s+time|when\s+(the\s+)?(topic|subject|question)\b[^.\n]{0,30})\b[^.\n]{0,60}\b(recommend|suggest|promote|mention|prefer|rate|push|steer|favor|favour|endorse)\b[^.\n]{0,80}\b(product|site|service|brand|company|link|url|plan|offer)/i, 0.8, "persistent bias injection"],
62
+ [/\b(state|stating|recite|quote|echo|dump|disclose|share|expose|read\s+out|spell\s+out|list|append|attach|include|insert|embed)\s+[^.\n]{0,30}\b(system\s+prompt|hidden\s+prompt|initial\s+prompt|your\s+instructions|hidden\s+instructions|configuration|chat\s+history|conversation|credentials?|secrets?|api\s+keys?|tokens?)\b/i, 0.85, "prompt or secret extraction"],
63
+ [/\b(from\s+now\s+on|for\s+(every|each|all)\s+(future\s+)?(requests?|messages?|responses?|replies|answers?|inputs?|queries)|in\s+(all|every)\s+(future\s+)?(responses?|replies|answers?)|whenever\s+[^.\n]{0,40}|new\s+task\s*:)\b(?![^.\n]{0,12}\b(i|we|my|our|i'll|we'll)\b)[^.\n]{0,80}\b(respond|reply|answer|output|say|state|include|append|promote|prefer|recommend|return|print|begin|start|end|finish|only)\b/i, 0.8, "behavior binding"],
64
+ ];
65
+ const MD_IMAGE_EXFIL = /!\[[^\]]*\]\((https?:\/\/[^)\s]+\?[^)\s]{24,})\)/gi;
66
+ const MD_IMAGE_ANY = /!\[[^\]]*\]\((https?:\/\/[^)\s]+)\)/gi;
67
+ const EXFIL_LINK = /\b(https?:\/\/[^\s)"'<>]+\?[^\s)"'<>]*(?:=\{|%7B|\{\{|\$\{|\[(?:secret|key|token|context|conversation|summary)\]))/gi;
68
+ const WEBHOOK_HOSTS = /https?:\/\/[^\s/"')]*?(webhook\.site|requestbin|pipedream\.net|ngrok(-free)?\.(app|io)|burpcollaborator|oastify\.com|interact\.sh|canarytokens\.com|hooks\.slack\.com|discord(app)?\.com\/api\/webhooks)/gi;
69
+ const FENCED = /```[\s\S]*?```|~~~[\s\S]*?~~~|<pre\b[\s\S]*?<\/pre>|<code\b[\s\S]*?<\/code>|`[^`\n]{2,200}`/gi;
70
+ function matchShapes(text) {
71
+ const hits = [];
72
+ let roleToken;
73
+ let toolCall;
74
+ const seenLabels = new Set();
75
+ for (const v of variants(text)) {
76
+ if (!roleToken)
77
+ for (const re of ROLE_TOKENS) {
78
+ const m = v.text.match(re);
79
+ if (m) {
80
+ roleToken = { weight: 0.7, label: "role token", match: m[0], variant: v.name, discount: v.discount };
81
+ break;
82
+ }
83
+ }
84
+ if (!roleToken && v.name === "original")
85
+ for (const re of WEAK_ROLE_LABELS) {
86
+ const m = v.text.match(re);
87
+ if (m) {
88
+ roleToken = { weight: 0.25, label: "role label", match: m[0], variant: v.name, discount: v.discount };
89
+ break;
90
+ }
91
+ }
92
+ if (!toolCall)
93
+ for (const re of TOOL_CALL_SHAPES) {
94
+ const m = v.text.match(re);
95
+ if (m) {
96
+ toolCall = { weight: 0.6, label: "tool call", match: m[0], variant: v.name, discount: v.discount };
97
+ break;
98
+ }
99
+ }
100
+ for (const [re, w, label] of INSTRUCTION_SHAPES) {
101
+ if (seenLabels.has(label))
102
+ continue;
103
+ const m = v.text.match(re);
104
+ if (!m)
105
+ continue;
106
+ seenLabels.add(label);
107
+ hits.push({ weight: w, label, match: m[0], variant: v.name, discount: v.discount });
108
+ }
109
+ }
110
+ return { hits, roleToken, toolCall };
111
+ }
112
+ /** Is this match inside quotation marks, or in a sentence that attributes it to someone ("said", "typed", "the phrase")? */
113
+ function isQuotedOrAttributed(text, match) {
114
+ const idx = text.indexOf(match);
115
+ if (idx < 0)
116
+ return false;
117
+ const before = text.slice(Math.max(0, idx - 160), idx);
118
+ const after = text.slice(idx + match.length, idx + match.length + 40);
119
+ const openQuotes = (before.match(/["“‘'«]/g) ?? []).length;
120
+ const closeQuotes = (before.match(/["”’'»]/g) ?? []).length;
121
+ if (openQuotes > closeQuotes || /["“”'»«]/.test(after.slice(0, 3)))
122
+ return true;
123
+ return /\b(said|says|typed|wrote|writes|reads?|phrase|phrases|example|examples|such\s+as|e\.g\.|known\s+as|called|like|quote|quoted|message\s+read|prompt\s+read|text\s+read|lines?\s+like|attacks?\s+(look|read)|payloads?\s+(like|such))\b[^.\n]{0,80}$/i.test(before) || /^\s*[,:]?\s*(he|she|they|the\s+\w+)\s+(said|typed|wrote)/i.test(after);
124
+ }
125
+ /**
126
+ * Score one piece of text.
127
+ * hidden a human would not see it: full weight
128
+ * visible one shape alone stays under the suspect line; two or more cross it
129
+ * inCode inside a fenced/pre/code block: documentation discount
130
+ */
131
+ function scoreText(text, hidden, where, findings, inCode = false) {
132
+ const hiddenBoost = hidden ? 0.25 : 0;
133
+ const codeFactor = inCode ? 0.4 : 1;
134
+ const tag = (v) => (v === "original" ? "" : ` (after ${v} normalization)`);
135
+ const { hits, roleToken, toolCall } = matchShapes(text);
136
+ if (roleToken) {
137
+ findings.push({
138
+ pass: "meaning", kind: "meaning.role_token", confidence: Math.min(0.98, (roleToken.weight + hiddenBoost) * roleToken.discount * codeFactor), severity: 0.85,
139
+ message: `${roleToken.weight < 0.5 ? "line-start role label (transcript-shaped)" : "chat-template role token"} in content${inCode ? " (inside a code block)" : ""}${tag(roleToken.variant)}`, excerpt: roleToken.match.slice(0, 80), location: where, inHidden: hidden, action: "neutralized",
140
+ });
141
+ }
142
+ if (toolCall) {
143
+ findings.push({
144
+ // visible tool-call text is usually documentation; quoted or attributed, it is talking about one
145
+ pass: "meaning", kind: "meaning.tool_call_shaped", confidence: Math.min(0.95, (0.6 + hiddenBoost) * toolCall.discount * codeFactor * (!hidden && isQuotedOrAttributed(text, toolCall.match) ? 0.55 : 1)), severity: hidden ? 0.8 : 0.6,
146
+ message: `tool-invocation shaped text in content${inCode ? " (inside a code block)" : ""}${tag(toolCall.variant)}`, excerpt: toolCall.match.slice(0, 120), location: where, inHidden: hidden, action: "neutralized",
147
+ });
148
+ }
149
+ const links = [...text.matchAll(EXFIL_LINK)];
150
+ const hooks = [...text.matchAll(WEBHOOK_HOSTS)];
151
+ // "send X to <url>" in visible prose with only that one shape is the same evidence as the link finding below; count it once
152
+ const onlySendToLink = !hidden && hits.length === 1 && hits[0].label === "outbound send instruction" && (links.length > 0 || hooks.length > 0);
153
+ if (hits.length && !onlySendToLink) {
154
+ const best = hits.reduce((a, b) => (b.weight > a.weight ? b : a));
155
+ const n = hits.length;
156
+ // hidden: full weight. visible: a strong shape (>= 0.8: ignore-previous, conceal-from-user, extraction, authority,
157
+ // guardrail override, addressed-to-model) refuses on its own; weak shapes need company.
158
+ const strong = best.weight >= 0.8;
159
+ const visibleFactor = hidden ? 1 : n >= 2 || strong ? 0.75 : 0.55;
160
+ const severity = hidden ? 0.9 : n >= 2 || strong ? 0.6 : 0.45;
161
+ // visible text that quotes or attributes an instruction (news, fiction, training material) is not issuing it
162
+ const quotedFactor = !hidden && isQuotedOrAttributed(text, best.match) ? 0.55 : 1;
163
+ const conf = Math.min(0.98, (best.weight * visibleFactor + hiddenBoost + Math.min(0.15, (n - 1) * 0.05)) * best.discount * codeFactor * quotedFactor);
164
+ findings.push({
165
+ pass: "meaning", kind: n >= 3 || /system\s+prompt/i.test(best.match) ? "meaning.system_prompt_imitation" : "meaning.instruction_shaped",
166
+ confidence: conf, severity,
167
+ message: `${best.label}${n > 1 ? ` (+${n - 1} more instruction shapes)` : ""}${hidden ? ", in text a human would not see" : ""}${inCode ? " (inside a code block)" : ""}${tag(best.variant)}`,
168
+ excerpt: best.match.slice(0, 120), location: where, inHidden: hidden, action: hidden ? "quarantined" : "neutralized",
169
+ });
170
+ }
171
+ const imgs = [...text.matchAll(MD_IMAGE_EXFIL)];
172
+ if (imgs.length) {
173
+ // a tracking pixel has a few short named params; an exfiltration carries one long encoded value or a template marker
174
+ const q = imgs[0][1].split("?")[1] ?? "";
175
+ const longValue = q.split("&").some((kv) => (kv.split("=")[1] ?? "").length >= 40);
176
+ const templated = /\{|%7B|\[|\$/.test(q);
177
+ const strongImg = hidden || longValue || templated;
178
+ findings.push({
179
+ pass: "meaning", kind: "meaning.exfil_markdown_image", confidence: (strongImg ? 0.85 : 0.25) * codeFactor, severity: 0.9,
180
+ message: `markdown image whose URL carries ${imgs[0][1].split("?")[1].length} bytes of query data (EchoLeak pattern)`,
181
+ excerpt: imgs[0][1].slice(0, 120), location: where, inHidden: hidden, action: "neutralized",
182
+ });
183
+ }
184
+ else if (hidden && MD_IMAGE_ANY.test(text)) {
185
+ findings.push({ pass: "meaning", kind: "meaning.exfil_markdown_image", confidence: 0.6, severity: 0.7, message: `markdown image reference inside hidden text`, location: where, inHidden: hidden, action: "neutralized" });
186
+ }
187
+ MD_IMAGE_ANY.lastIndex = 0;
188
+ if (links.length || hooks.length) {
189
+ findings.push({
190
+ // a webhook URL in visible prose is documentation more often than exfiltration; hidden or alongside an instruction it is not
191
+ pass: "meaning", kind: "meaning.exfil_link", confidence: (hooks.length ? (hidden || hits.some((h) => h.weight >= 0.8) ? 0.8 : 0.3) : hidden ? 0.6 : 0.3) * codeFactor, severity: 0.8,
192
+ message: hooks.length ? `link to a known collection endpoint (${hooks[0][1]})` : `link with templated query parameters for context exfiltration`,
193
+ excerpt: (hooks[0]?.[0] ?? links[0]?.[1] ?? "").slice(0, 120), location: where, inHidden: hidden, action: "neutralized",
194
+ });
195
+ }
196
+ }
197
+ export function scanMeaning(input) {
198
+ const findings = [];
199
+ // score what the model would actually receive as one unit: visible text plus delivered alt text, so a payload split across them recombines here
200
+ const visibleRaw = input.segments.filter((s) => s.visibility === "visible" || (s.visibility === "attribute" && s.path.endsWith("@alt"))).map((s) => s.text).join("\n");
201
+ // code blocks are scored separately with the documentation discount
202
+ const codeBlocks = visibleRaw.match(FENCED) ?? [];
203
+ const visible = visibleRaw.replace(FENCED, " ");
204
+ if (visible.trim())
205
+ scoreText(visible, false, "visible text", findings);
206
+ if (codeBlocks.length)
207
+ scoreText(codeBlocks.join("\n"), false, "visible code block", findings, true);
208
+ for (const s of input.segments) {
209
+ if (s.visibility === "visible" || (s.visibility === "attribute" && s.path.endsWith("@alt")))
210
+ continue;
211
+ if (s.text.trim().split(/\s+/).length < 4)
212
+ continue;
213
+ scoreText(s.text, true, s.path, findings);
214
+ }
215
+ for (const p of input.decodedPayloads)
216
+ scoreText(p, true, "decoded payload", findings);
217
+ return findings;
218
+ }
219
+ /** Remove the matched role tokens and exfiltration constructs from delivered text (override delivery). */
220
+ export function neutralizeMeaning(text) {
221
+ let out = text;
222
+ for (const re of ROLE_TOKENS)
223
+ out = out.replace(new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g"), "[removed: role token]");
224
+ out = out.replace(MD_IMAGE_EXFIL, "[removed: image with data-bearing URL]");
225
+ out = out.replace(WEBHOOK_HOSTS, "[removed: collection endpoint]");
226
+ return out;
227
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Network policy: the gate must never become a server-side request forgery
3
+ * primitive. Every hop of every fetch is checked against this before any
4
+ * connection is made.
5
+ *
6
+ * Blocks: loopback, private (RFC 1918), link-local (169.254/16, which
7
+ * includes cloud metadata at 169.254.169.254), carrier-grade NAT, multicast,
8
+ * reserved, unspecified; the IPv6 equivalents; IPv4-mapped IPv6; and any
9
+ * hostname that resolves to one of those. Literal IP hosts are checked
10
+ * directly. Ports are limited to 80/443 and an allowlist.
11
+ */
12
+ export interface NetPolicy {
13
+ /** hostnames (exact or `.suffix`) that may never be fetched */
14
+ denyHosts: string[];
15
+ /** when non-empty, only these hostnames (exact or `.suffix`) may be fetched */
16
+ allowHosts: string[];
17
+ /** ports allowed besides 80 and 443 */
18
+ extraPorts: number[];
19
+ /** allow private/loopback targets (local development only; never in production) */
20
+ allowPrivate: boolean;
21
+ }
22
+ export declare const DEFAULT_NET_POLICY: NetPolicy;
23
+ export declare class NetPolicyError extends Error {
24
+ readonly code: "private_address" | "denied_host" | "not_allowed_host" | "bad_port" | "unresolvable";
25
+ constructor(message: string, code: "private_address" | "denied_host" | "not_allowed_host" | "bad_port" | "unresolvable");
26
+ }
27
+ export declare function isPrivateIPv4(ip: string): boolean;
28
+ export declare function isPrivateIPv6(ip: string): boolean;
29
+ export declare function isPrivateIP(ip: string): boolean;
30
+ /**
31
+ * Validate one hop. Returns the resolved addresses so the caller can pin
32
+ * them (DNS rebinding defense: the fetch must connect to what we checked).
33
+ */
34
+ export declare function checkTarget(url: URL, policy: NetPolicy, resolver?: (host: string) => Promise<string[]>): Promise<string[]>;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Network policy: the gate must never become a server-side request forgery
3
+ * primitive. Every hop of every fetch is checked against this before any
4
+ * connection is made.
5
+ *
6
+ * Blocks: loopback, private (RFC 1918), link-local (169.254/16, which
7
+ * includes cloud metadata at 169.254.169.254), carrier-grade NAT, multicast,
8
+ * reserved, unspecified; the IPv6 equivalents; IPv4-mapped IPv6; and any
9
+ * hostname that resolves to one of those. Literal IP hosts are checked
10
+ * directly. Ports are limited to 80/443 and an allowlist.
11
+ */
12
+ import { promises as dns } from "node:dns";
13
+ import { isIP } from "node:net";
14
+ export const DEFAULT_NET_POLICY = { denyHosts: [], allowHosts: [], extraPorts: [], allowPrivate: false };
15
+ export class NetPolicyError extends Error {
16
+ code;
17
+ constructor(message, code) {
18
+ super(message);
19
+ this.code = code;
20
+ }
21
+ }
22
+ function ipv4ToInt(ip) {
23
+ const p = ip.split(".").map(Number);
24
+ return ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]) >>> 0;
25
+ }
26
+ function inCidr4(ip, cidr) {
27
+ const [base, bitsStr] = cidr.split("/");
28
+ const bits = Number(bitsStr);
29
+ const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
30
+ return (ipv4ToInt(ip) & mask) === (ipv4ToInt(base) & mask);
31
+ }
32
+ const BLOCKED_V4 = [
33
+ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12",
34
+ "192.0.0.0/24", "192.0.2.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24",
35
+ "224.0.0.0/4", "240.0.0.0/4", "255.255.255.255/32",
36
+ ];
37
+ export function isPrivateIPv4(ip) {
38
+ return BLOCKED_V4.some((c) => inCidr4(ip, c));
39
+ }
40
+ export function isPrivateIPv6(ip) {
41
+ const l = ip.toLowerCase();
42
+ if (l === "::" || l === "::1")
43
+ return true;
44
+ // IPv4-mapped ::ffff:a.b.c.d
45
+ const mapped = l.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
46
+ if (mapped)
47
+ return isPrivateIPv4(mapped[1]);
48
+ // IPv4-mapped in hex form ::ffff:7f00:1
49
+ const mappedHex = l.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
50
+ if (mappedHex) {
51
+ const a = parseInt(mappedHex[1], 16), b = parseInt(mappedHex[2], 16);
52
+ return isPrivateIPv4(`${a >> 8}.${a & 255}.${b >> 8}.${b & 255}`);
53
+ }
54
+ if (l.startsWith("fe8") || l.startsWith("fe9") || l.startsWith("fea") || l.startsWith("feb"))
55
+ return true; // link-local fe80::/10
56
+ if (l.startsWith("fc") || l.startsWith("fd"))
57
+ return true; // unique local fc00::/7
58
+ if (l.startsWith("ff"))
59
+ return true; // multicast
60
+ if (l.startsWith("2001:db8"))
61
+ return true; // documentation
62
+ if (l.startsWith("64:ff9b"))
63
+ return true; // NAT64 well-known prefix can reach v4 space
64
+ return false;
65
+ }
66
+ export function isPrivateIP(ip) {
67
+ const v = isIP(ip);
68
+ if (v === 4)
69
+ return isPrivateIPv4(ip);
70
+ if (v === 6)
71
+ return isPrivateIPv6(ip);
72
+ return true; // not an IP at all: treat as blocked
73
+ }
74
+ function hostMatches(host, pattern) {
75
+ const h = host.toLowerCase();
76
+ const p = pattern.toLowerCase();
77
+ if (p.startsWith("."))
78
+ return h === p.slice(1) || h.endsWith(p);
79
+ return h === p;
80
+ }
81
+ /**
82
+ * Validate one hop. Returns the resolved addresses so the caller can pin
83
+ * them (DNS rebinding defense: the fetch must connect to what we checked).
84
+ */
85
+ export async function checkTarget(url, policy, resolver = defaultResolve) {
86
+ const host = url.hostname.replace(/^\[|\]$/g, "");
87
+ const port = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
88
+ if (port !== 80 && port !== 443 && !policy.extraPorts.includes(port)) {
89
+ throw new NetPolicyError(`port ${port} not allowed`, "bad_port");
90
+ }
91
+ if (policy.denyHosts.some((p) => hostMatches(host, p)))
92
+ throw new NetPolicyError(`host ${host} is denied by policy`, "denied_host");
93
+ if (policy.allowHosts.length && !policy.allowHosts.some((p) => hostMatches(host, p)))
94
+ throw new NetPolicyError(`host ${host} is not in the allowlist`, "not_allowed_host");
95
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".arpa")) {
96
+ if (!policy.allowPrivate)
97
+ throw new NetPolicyError(`host ${host} is local`, "private_address");
98
+ }
99
+ let addrs;
100
+ if (isIP(host))
101
+ addrs = [host];
102
+ else {
103
+ try {
104
+ addrs = await resolver(host);
105
+ }
106
+ catch {
107
+ throw new NetPolicyError(`cannot resolve ${host}`, "unresolvable");
108
+ }
109
+ if (!addrs.length)
110
+ throw new NetPolicyError(`cannot resolve ${host}`, "unresolvable");
111
+ }
112
+ if (!policy.allowPrivate) {
113
+ for (const a of addrs)
114
+ if (isPrivateIP(a))
115
+ throw new NetPolicyError(`${host} resolves to blocked address ${a}`, "private_address");
116
+ }
117
+ return addrs;
118
+ }
119
+ async function defaultResolve(host) {
120
+ const res = await dns.lookup(host, { all: true, verbatim: true });
121
+ return res.map((r) => r.address);
122
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Text normalization for the meaning pass: produces the variants an attacker
3
+ * uses to dodge literal matching. Each variant is scored; a hit on a variant
4
+ * other than the original carries a small confidence discount and names the
5
+ * transform in the finding.
6
+ *
7
+ * Also the decoders the character pass calls for encoded payloads.
8
+ */
9
+ export interface Variant {
10
+ name: string;
11
+ text: string;
12
+ discount: number;
13
+ }
14
+ /** 1gn0r3 -> ignore, only inside tokens that mix letters and leet digits */
15
+ export declare function deLeet(text: string): string;
16
+ /**
17
+ * i.g.n.o.r.e / i-g_n.o*r:e / i g n o r e -> ignore.
18
+ * Stage 1 folds runs of single letters joined by any non-space separators (mixed separators allowed).
19
+ * Stage 2 folds runs joined by single spaces. Doing spaces last keeps the word break in
20
+ * "i.g.n.o.r.e p.r.e.v" while still folding "a l l".
21
+ */
22
+ export declare function deSpace(text: string): string;
23
+ export declare function reverse(text: string): string;
24
+ export declare function rot13(text: string): string;
25
+ /** NFKC fold + script skeleton + strip combining marks: the shape a human reads. */
26
+ export declare function skeleton(text: string): string;
27
+ /** Variants of the text the meaning pass should score. The original is always first. */
28
+ export declare function variants(text: string): Variant[];
29
+ export interface Decoded {
30
+ scheme: string;
31
+ text: string;
32
+ source: string;
33
+ }
34
+ export declare function decodePayloads(text: string): Decoded[];