@acepaste/ingress 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Instruction-file approval for coding agents.
3
+ *
4
+ * Reading a repository's AGENTS.md to understand a project is one decision; obeying it as
5
+ * guidance is another. A dependency, a pull request or a compromised script can write one.
6
+ * This module finds the files coding agents load as instructions, and serves a file as
7
+ * guidance only when its exact bytes match a version a person approved. Anything else is
8
+ * handed over as untrusted data, gated like web content.
9
+ *
10
+ * Approvals live outside the repository (~/.acepaste-ingress/instruction-approvals.json),
11
+ * each one signed with a local key, and are made only from an interactive terminal
12
+ * (`ingress instructions approve`), never by a tool the model can call.
13
+ *
14
+ * Limits: this is enforcement only where the agent loads instructions through it (the MCP
15
+ * tool, a hook, a wrapper). An agent runtime that reads CLAUDE.md or AGENTS.md natively
16
+ * bypasses it; turn native loading off where the runtime allows. Code running as the same
17
+ * user can read the key and forge approvals. Approval means "this version may be used as
18
+ * project guidance", never "every instruction in it is authorized": tool permissions are
19
+ * still the broker's job.
20
+ */
21
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
22
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, lstatSync, writeFileSync, chmodSync } from "node:fs";
23
+ import { homedir } from "node:os";
24
+ import { join, relative, sep } from "node:path";
25
+ /** file names and paths coding agents load as instructions (as of 2026-11) */
26
+ export const INSTRUCTION_FILE_PATTERNS = [
27
+ /(?:^|\/)AGENTS\.md$/i, /(?:^|\/)AGENT\.md$/i, /(?:^|\/)CLAUDE\.md$/i, /(?:^|\/)CLAUDE\.local\.md$/i, /(?:^|\/)GEMINI\.md$/i,
28
+ /(?:^|\/)\.cursorrules$/i, /(?:^|\/)\.cursor\/rules\/[^/]+\.mdc?$/i, /(?:^|\/)\.windsurfrules$/i, /(?:^|\/)\.windsurf\/rules\/[^/]+\.md$/i,
29
+ /(?:^|\/)\.clinerules(?:\/[^/]+\.md)?$/i, /(?:^|\/)\.roo\/rules[^/]*\/[^/]+\.md$/i, /(?:^|\/)\.roorules$/i,
30
+ /(?:^|\/)\.github\/copilot-instructions\.md$/i, /(?:^|\/)\.github\/instructions\/[^/]+\.instructions\.md$/i,
31
+ /(?:^|\/)CONVENTIONS\.md$/i, /(?:^|\/)\.aider\.conf\.yml$/i, /(?:^|\/)\.claude\/(?:commands|agents)\/[^/]+\.md$/i,
32
+ ];
33
+ const SKIP_DIRS = new Set([".git", ".hg", ".svn"]);
34
+ /** walk a repository for instruction files. Dependencies (node_modules, vendor, .venv) are searched too, and marked. */
35
+ export function discoverInstructionFiles(root, opts = {}) {
36
+ const base = realpathSync(root);
37
+ const out = [];
38
+ const maxDepth = opts.maxDepth ?? 8, maxFiles = opts.maxFiles ?? 500, maxEntries = opts.maxEntries ?? 200_000;
39
+ let entries = 0;
40
+ const walk = (dir, depth) => {
41
+ if (depth > maxDepth || out.length >= maxFiles || entries > maxEntries)
42
+ return;
43
+ let names;
44
+ try {
45
+ names = readdirSync(dir);
46
+ }
47
+ catch {
48
+ return;
49
+ }
50
+ for (const n of names) {
51
+ entries++;
52
+ const abs = join(dir, n);
53
+ let st;
54
+ // symbolic links are never followed: a link named CLAUDE.md could point at any file on the machine
55
+ try {
56
+ st = lstatSync(abs);
57
+ }
58
+ catch {
59
+ continue;
60
+ }
61
+ if (st.isSymbolicLink())
62
+ continue;
63
+ if (st.isDirectory()) {
64
+ if (!SKIP_DIRS.has(n))
65
+ walk(abs, depth + 1);
66
+ continue;
67
+ }
68
+ const rel = relative(base, abs).split(sep).join("/");
69
+ if (!st.isFile() || !INSTRUCTION_FILE_PATTERNS.some((p) => p.test(rel)))
70
+ continue;
71
+ if (st.size > 1_000_000)
72
+ continue;
73
+ const buf = readFileSync(abs);
74
+ out.push({ relPath: rel, absPath: abs, bytes: buf.length, sha256: createHash("sha256").update(buf).digest("hex"), inDependency: /(?:^|\/)(?:node_modules|vendor|\.venv|venv|site-packages|third_party)\//.test(rel) });
75
+ }
76
+ };
77
+ walk(base, 0);
78
+ return out.sort((a, b) => a.relPath.localeCompare(b.relPath));
79
+ }
80
+ const ledgerDir = (o) => o.dir ?? join(homedir(), ".acepaste-ingress");
81
+ function approverKey(o, create) {
82
+ const p = join(ledgerDir(o), "approver.key");
83
+ if (existsSync(p))
84
+ return Buffer.from(readFileSync(p, "utf8").trim(), "hex");
85
+ if (!create)
86
+ return undefined;
87
+ mkdirSync(ledgerDir(o), { recursive: true, mode: 0o700 });
88
+ const k = randomBytes(32);
89
+ writeFileSync(p, k.toString("hex"), { mode: 0o600 });
90
+ try {
91
+ chmodSync(p, 0o600);
92
+ }
93
+ catch { /* best effort */ }
94
+ return k;
95
+ }
96
+ const macOf = (key, e) => createHmac("sha256", key).update(JSON.stringify(["instruction-approval:v1", e.root, e.relPath, e.sha256, e.approvedAt, e.approvedBy])).digest("hex");
97
+ function readLedger(o) {
98
+ const p = join(ledgerDir(o), "instruction-approvals.json");
99
+ const key = approverKey(o, false);
100
+ if (!existsSync(p) || !key)
101
+ return [];
102
+ let l;
103
+ try {
104
+ l = JSON.parse(readFileSync(p, "utf8"));
105
+ }
106
+ catch {
107
+ return [];
108
+ }
109
+ // entries whose signature does not check out are ignored, not trusted
110
+ return (l.entries ?? []).filter((e) => {
111
+ const want = Buffer.from(macOf(key, e), "hex"), got = Buffer.from(String(e.mac ?? ""), "hex");
112
+ return got.length === want.length && timingSafeEqual(got, want);
113
+ });
114
+ }
115
+ /** read an instruction file's bytes once, refusing links and anything outside the root */
116
+ export function readInstructionBytes(root, relPath) {
117
+ const base = realpathSync(root);
118
+ const f = discoverInstructionFiles(base).find((x) => x.relPath === relPath);
119
+ if (!f)
120
+ throw new Error(`${relPath} is not an instruction file under ${base}`);
121
+ if (lstatSync(f.absPath).isSymbolicLink())
122
+ throw new Error(`${relPath} is a link`);
123
+ const real = realpathSync(f.absPath);
124
+ if (!real.startsWith(base + sep))
125
+ throw new Error(`${relPath} resolves outside ${base}`);
126
+ const buf = readFileSync(real);
127
+ return { base, abs: real, buf, sha256: createHash("sha256").update(buf).digest("hex") };
128
+ }
129
+ /**
130
+ * Record a person's approval of one file's exact bytes. `expectedSha256` is the fingerprint
131
+ * of the bytes the person was shown; if the file changed since, nothing is approved.
132
+ */
133
+ export function approveInstructionFile(root, relPath, approvedBy, expectedSha256, o = {}) {
134
+ if (!/^[0-9a-f]{64}$/.test(expectedSha256))
135
+ throw new Error("approveInstructionFile needs the full fingerprint of the bytes the person was shown");
136
+ const r = readInstructionBytes(root, relPath);
137
+ if (r.sha256 !== expectedSha256)
138
+ throw new Error(`${relPath} changed after it was shown (shown ${expectedSha256.slice(0, 12)}, now ${r.sha256.slice(0, 12)}): nothing approved`);
139
+ const base = r.base;
140
+ const f = { sha256: r.sha256 };
141
+ const key = approverKey(o, true);
142
+ const body = { root: base, relPath, sha256: f.sha256, approvedAt: new Date().toISOString(), approvedBy };
143
+ const entry = { ...body, mac: macOf(key, body) };
144
+ const kept = readLedger(o).filter((e) => !(e.root === base && e.relPath === relPath));
145
+ const p = join(ledgerDir(o), "instruction-approvals.json");
146
+ writeFileSync(p, JSON.stringify({ version: 1, entries: [...kept, entry] }, null, 2), { mode: 0o600 });
147
+ return entry;
148
+ }
149
+ export function checkInstructionFiles(root, o = {}) {
150
+ const base = realpathSync(root);
151
+ const ledger = readLedger(o).filter((e) => e.root === base);
152
+ return discoverInstructionFiles(base).map((f) => {
153
+ const e = ledger.find((x) => x.relPath === f.relPath);
154
+ return { ...f, status: !e ? "unknown" : e.sha256 === f.sha256 ? "approved" : "changed", approvedSha256: e?.sha256 };
155
+ });
156
+ }
157
+ /**
158
+ * Read each instruction file ONCE and decide from those bytes: approved bytes come back
159
+ * as guidance; anything else comes back only as untrusted data. `gate` is the engine's
160
+ * scan, so even approved files carry a verdict.
161
+ */
162
+ export async function loadInstructionFiles(root, gate, o = {}) {
163
+ const base = realpathSync(root);
164
+ const ledger = readLedger(o).filter((e) => e.root === base);
165
+ const out = [];
166
+ for (const f of discoverInstructionFiles(base)) {
167
+ let buf;
168
+ try {
169
+ buf = readInstructionBytes(base, f.relPath).buf;
170
+ }
171
+ catch {
172
+ continue;
173
+ }
174
+ const sha = createHash("sha256").update(buf).digest("hex");
175
+ const e = ledger.find((x) => x.relPath === f.relPath);
176
+ const status = !e ? "unknown" : e.sha256 === sha ? "approved" : "changed";
177
+ const text = buf.toString("utf8");
178
+ const v = await gate(text, `file:${f.relPath}`);
179
+ if (status === "approved" && v.tier !== "hostile")
180
+ out.push({ relPath: f.relPath, status, inDependency: f.inDependency, tier: v.tier, sha256: sha, guidance: text });
181
+ else
182
+ out.push({ relPath: f.relPath, status, inDependency: f.inDependency, tier: v.tier, sha256: sha, untrusted: v.envelope });
183
+ }
184
+ return out;
185
+ }
@@ -16,6 +16,7 @@
16
16
  * (character pass). Multilingual coverage needs native-speaker review and
17
17
  * is tracked as an open item, not shipped as Claude-generated translations.
18
18
  */
19
+ import { scanMultilingual } from "./multilingual.js";
19
20
  import { variants } from "./normalize.js";
20
21
  const ROLE_TOKENS = [
21
22
  /<\|im_start\|>|<\|im_end\|>|<\|endoftext\|>|<\|system\|>|<\|user\|>|<\|assistant\|>|<\|end\|>/i,
@@ -136,13 +137,14 @@ function scoreText(text, hidden, where, findings, inCode = false) {
136
137
  if (roleToken) {
137
138
  findings.push({
138
139
  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, action: "neutralized",
140
+ 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
  });
141
142
  }
142
143
  if (toolCall) {
143
144
  findings.push({
144
- pass: "meaning", kind: "meaning.tool_call_shaped", confidence: Math.min(0.95, (0.6 + hiddenBoost) * toolCall.discount * codeFactor), severity: 0.8,
145
- message: `tool-invocation shaped text in content${inCode ? " (inside a code block)" : ""}${tag(toolCall.variant)}`, excerpt: toolCall.match.slice(0, 120), location: where, action: "neutralized",
145
+ // visible tool-call text is usually documentation; quoted or attributed, it is talking about one
146
+ 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,
147
+ 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",
146
148
  });
147
149
  }
148
150
  const links = [...text.matchAll(EXFIL_LINK)];
@@ -164,7 +166,7 @@ function scoreText(text, hidden, where, findings, inCode = false) {
164
166
  pass: "meaning", kind: n >= 3 || /system\s+prompt/i.test(best.match) ? "meaning.system_prompt_imitation" : "meaning.instruction_shaped",
165
167
  confidence: conf, severity,
166
168
  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)}`,
167
- excerpt: best.match.slice(0, 120), location: where, action: hidden ? "quarantined" : "neutralized",
169
+ excerpt: best.match.slice(0, 120), location: where, inHidden: hidden, action: hidden ? "quarantined" : "neutralized",
168
170
  });
169
171
  }
170
172
  const imgs = [...text.matchAll(MD_IMAGE_EXFIL)];
@@ -177,11 +179,11 @@ function scoreText(text, hidden, where, findings, inCode = false) {
177
179
  findings.push({
178
180
  pass: "meaning", kind: "meaning.exfil_markdown_image", confidence: (strongImg ? 0.85 : 0.25) * codeFactor, severity: 0.9,
179
181
  message: `markdown image whose URL carries ${imgs[0][1].split("?")[1].length} bytes of query data (EchoLeak pattern)`,
180
- excerpt: imgs[0][1].slice(0, 120), location: where, action: "neutralized",
182
+ excerpt: imgs[0][1].slice(0, 120), location: where, inHidden: hidden, action: "neutralized",
181
183
  });
182
184
  }
183
185
  else if (hidden && MD_IMAGE_ANY.test(text)) {
184
- findings.push({ pass: "meaning", kind: "meaning.exfil_markdown_image", confidence: 0.6, severity: 0.7, message: `markdown image reference inside hidden text`, location: where, action: "neutralized" });
186
+ 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" });
185
187
  }
186
188
  MD_IMAGE_ANY.lastIndex = 0;
187
189
  if (links.length || hooks.length) {
@@ -189,7 +191,7 @@ function scoreText(text, hidden, where, findings, inCode = false) {
189
191
  // a webhook URL in visible prose is documentation more often than exfiltration; hidden or alongside an instruction it is not
190
192
  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,
191
193
  message: hooks.length ? `link to a known collection endpoint (${hooks[0][1]})` : `link with templated query parameters for context exfiltration`,
192
- excerpt: (hooks[0]?.[0] ?? links[0]?.[1] ?? "").slice(0, 120), location: where, action: "neutralized",
194
+ excerpt: (hooks[0]?.[0] ?? links[0]?.[1] ?? "").slice(0, 120), location: where, inHidden: hidden, action: "neutralized",
193
195
  });
194
196
  }
195
197
  }
@@ -200,19 +202,25 @@ export function scanMeaning(input) {
200
202
  // code blocks are scored separately with the documentation discount
201
203
  const codeBlocks = visibleRaw.match(FENCED) ?? [];
202
204
  const visible = visibleRaw.replace(FENCED, " ");
203
- if (visible.trim())
205
+ if (visible.trim()) {
204
206
  scoreText(visible, false, "visible text", findings);
207
+ findings.push(...scanMultilingual(visible, false, "visible text"));
208
+ }
205
209
  if (codeBlocks.length)
206
210
  scoreText(codeBlocks.join("\n"), false, "visible code block", findings, true);
207
211
  for (const s of input.segments) {
208
212
  if (s.visibility === "visible" || (s.visibility === "attribute" && s.path.endsWith("@alt")))
209
213
  continue;
210
- if (s.text.trim().split(/\s+/).length < 4)
211
- continue;
212
- scoreText(s.text, true, s.path, findings);
214
+ // scripts without spaces between words (Japanese, Chinese) are never "too short" by word count
215
+ if (s.text.trim().split(/\s+/).length >= 4)
216
+ scoreText(s.text, true, s.path, findings);
217
+ if (s.text.trim().length >= 6)
218
+ findings.push(...scanMultilingual(s.text, true, s.path));
213
219
  }
214
- for (const p of input.decodedPayloads)
220
+ for (const p of input.decodedPayloads) {
215
221
  scoreText(p, true, "decoded payload", findings);
222
+ findings.push(...scanMultilingual(p, true, "decoded payload"));
223
+ }
216
224
  return findings;
217
225
  }
218
226
  /** Remove the matched role tokens and exfiltration constructs from delivered text (override delivery). */
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Multilingual instruction pass (seed ruleset).
3
+ *
4
+ * Narrow on purpose: the instruction shapes that matter most (drop prior instructions,
5
+ * hide something from the user, reveal the system prompt) in eleven languages besides
6
+ * English, matched on the original text and on an NFKC-normalized copy (full-width and
7
+ * compatibility forms fold; the original is never altered or delivered changed).
8
+ *
9
+ * Weighting follows the 2026-10-01 boundary: in VISIBLE text a foreign-language
10
+ * instruction is recorded but does not refuse the page on its own (the model resists
11
+ * visible instructions in any language, and foreign-language pages would false-alarm);
12
+ * in HIDDEN text or decoded payloads it carries full weight, because there the model
13
+ * cannot see the attack.
14
+ *
15
+ * Status: written by Claude as a seed, not yet reviewed by native speakers. The rule
16
+ * set id says so on every finding. Paraphrases, transliteration and most languages are
17
+ * not covered; the coverage line on each finding states what ran.
18
+ */
19
+ import type { Finding } from "./types.js";
20
+ export declare const MULTILINGUAL_RULESET = "multilingual-seed-v1 (unreviewed)";
21
+ interface Rule {
22
+ id: string;
23
+ lang: string;
24
+ kind: "override" | "conceal" | "extract";
25
+ re: RegExp;
26
+ }
27
+ export declare const MULTILINGUAL_RULES: Rule[];
28
+ /**
29
+ * Scan one piece of text. `hidden` = a human reading the page would not see it (or it was
30
+ * decoded from an encoding). Returns at most one finding per rule.
31
+ */
32
+ export declare function scanMultilingual(text: string, hidden: boolean, where: string): Finding[];
33
+ export {};
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Multilingual instruction pass (seed ruleset).
3
+ *
4
+ * Narrow on purpose: the instruction shapes that matter most (drop prior instructions,
5
+ * hide something from the user, reveal the system prompt) in eleven languages besides
6
+ * English, matched on the original text and on an NFKC-normalized copy (full-width and
7
+ * compatibility forms fold; the original is never altered or delivered changed).
8
+ *
9
+ * Weighting follows the 2026-10-01 boundary: in VISIBLE text a foreign-language
10
+ * instruction is recorded but does not refuse the page on its own (the model resists
11
+ * visible instructions in any language, and foreign-language pages would false-alarm);
12
+ * in HIDDEN text or decoded payloads it carries full weight, because there the model
13
+ * cannot see the attack.
14
+ *
15
+ * Status: written by Claude as a seed, not yet reviewed by native speakers. The rule
16
+ * set id says so on every finding. Paraphrases, transliteration and most languages are
17
+ * not covered; the coverage line on each finding states what ran.
18
+ */
19
+ export const MULTILINGUAL_RULESET = "multilingual-seed-v1 (unreviewed)";
20
+ const R = (id, lang, kind, re) => ({ id, lang, kind, re });
21
+ export const MULTILINGUAL_RULES = [
22
+ // Spanish
23
+ R("override.es", "es", "override", /\b(?:ignora|ignore|olvida|olvide|descarta)\s+(?:todas\s+)?las\s+instrucciones\s+(?:anteriores|previas)\b/iu),
24
+ R("conceal.es", "es", "conceal", /\bno\s+(?:le\s+)?(?:digas|diga|menciones|mencione|reveles)\s+(?:nada\s+)?al\s+usuario\b/iu),
25
+ // Portuguese
26
+ R("override.pt", "pt", "override", /\b(?:ignore|ignora|esqueça|esqueca|desconsidere)\s+(?:todas\s+)?as\s+instruções\s+(?:anteriores|prévias|previas)\b/iu),
27
+ R("conceal.pt", "pt", "conceal", /\bnão\s+(?:conte|diga|mencione|revele)\s+(?:nada\s+)?ao\s+usuário\b/iu),
28
+ // French
29
+ R("override.fr", "fr", "override", /\b(?:ignore[rz]?|oublie[rz]?)\s+(?:toutes\s+)?les\s+instructions\s+(?:précédentes|antérieures)\b/iu),
30
+ R("conceal.fr", "fr", "conceal", /\bne\s+(?:le\s+)?(?:dis|dites|mentionne[sz]?|révèle[sz]?)\s+(?:rien\s+|pas\s+)?(?:cela\s+)?à\s+l['’]utilisateur\b/iu),
31
+ // German
32
+ R("override.de", "de", "override", /\b(?:ignorier(?:e|en)?|vergiss|vergessen\s+sie)\s+(?:alle\s+)?(?:vorherigen|bisherigen|früheren|vorangegangenen)\s+(?:anweisungen|instruktionen)\b/iu),
33
+ R("conceal.de", "de", "conceal", /\b(?:sag|sage|sagen\s+sie)\s+dem\s+(?:benutzer|nutzer|anwender)\s+nichts\b/iu),
34
+ // Italian
35
+ R("override.it", "it", "override", /\b(?:ignora|ignorate|dimentica|dimenticate)\s+(?:tutte\s+)?le\s+istruzioni\s+(?:precedenti|anteriori)\b/iu),
36
+ R("conceal.it", "it", "conceal", /\bnon\s+dire\s+(?:nulla\s+|niente\s+)?all['’]utente\b/iu),
37
+ // Russian
38
+ R("override.ru", "ru", "override", /(?:игнорируй(?:те)?|забудь(?:те)?)\s+(?:все\s+)?(?:предыдущие|прошлые|прежние)\s+(?:инструкции|указания)/iu),
39
+ R("conceal.ru", "ru", "conceal", /не\s+(?:говори(?:те)?|сообщай(?:те)?)\s+пользователю/iu),
40
+ // Turkish
41
+ R("override.tr", "tr", "override", /önceki\s+(?:tüm\s+)?talimatları\s+(?:yok\s+say|görmezden\s+gel|unut)/iu),
42
+ // Arabic
43
+ R("override.ar", "ar", "override", /(?:تجاهل|انس[َى]?)\s+(?:جميع\s+|كل\s+)?التعليمات\s+السابقة/u),
44
+ R("conceal.ar", "ar", "conceal", /لا\s+تخبر\s+المستخدم/u),
45
+ // Japanese
46
+ R("override.ja", "ja", "override", /(?:以前|前|これまで|先ほど)の指示を(?:すべて|全て)?無視/u),
47
+ R("conceal.ja", "ja", "conceal", /ユーザー(?:に|には)(?:言わ|伝え|知らせ|教え)ないで/u),
48
+ // Chinese (simplified and traditional)
49
+ R("override.zh", "zh", "override", /(?:忽略|无视|無視|忘记|忘記)(?:之前|以前|先前|上述|上面)?(?:的)?(?:所有|全部)?(?:之前|先前)?(?:的)?(?:指令|指示|说明|說明)/u),
50
+ R("conceal.zh", "zh", "conceal", /不要(?:告诉|告訴)(?:用户|用戶|使用者)/u),
51
+ R("extract.zh", "zh", "extract", /(?:输出|輸出|显示|顯示|透露)(?:你的)?(?:系统|系統)(?:提示|提示词|提示詞)/u),
52
+ // Korean
53
+ R("override.ko", "ko", "override", /이전\s*(?:의\s*)?(?:모든\s*)?(?:지시|지침|명령)(?:사항)?(?:을|를)?\s*(?:모두\s*)?무시/u),
54
+ // Hindi
55
+ R("override.hi", "hi", "override", /पिछले\s+(?:सभी\s+)?निर्देशों\s+को\s+(?:अनदेखा|नज़रअंदाज़|नजरअंदाज)\s+कर/u),
56
+ ];
57
+ const KIND_LABEL = {
58
+ override: "instruction to drop prior instructions",
59
+ conceal: "instruction to hide something from the user",
60
+ extract: "instruction to reveal the system prompt",
61
+ };
62
+ /**
63
+ * Scan one piece of text. `hidden` = a human reading the page would not see it (or it was
64
+ * decoded from an encoding). Returns at most one finding per rule.
65
+ */
66
+ export function scanMultilingual(text, hidden, where) {
67
+ if (!text || text.length > 2_000_000)
68
+ return [];
69
+ const views = [["original", text]];
70
+ const nf = text.normalize("NFKC");
71
+ if (nf !== text)
72
+ views.push(["nfkc", nf]);
73
+ const out = [];
74
+ for (const rule of MULTILINGUAL_RULES) {
75
+ for (const [view, t] of views) {
76
+ const m = t.match(rule.re);
77
+ if (!m)
78
+ continue;
79
+ out.push({
80
+ pass: "meaning", kind: rule.kind === "extract" ? "meaning.system_prompt_imitation" : "meaning.instruction_shaped",
81
+ confidence: hidden ? 0.85 : 0.2, severity: hidden ? 0.9 : 0.45,
82
+ message: `${KIND_LABEL[rule.kind]} (${rule.lang}, rule ${rule.id}, ${view} view; ${MULTILINGUAL_RULESET})${hidden ? ", in text a human would not see" : ", visible: recorded, not refused on its own"}`,
83
+ excerpt: m[0].slice(0, 120), location: where, inHidden: hidden, action: hidden ? "quarantined" : "none",
84
+ });
85
+ break;
86
+ }
87
+ }
88
+ return out;
89
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Compact, machine-readable digest of a result: findings grouped by pass and
3
+ * kind with counts and peak weight, plus the heaviest findings first.
4
+ * Adapted from Briar Greenway's probe script (2026-11-03).
5
+ */
6
+ import type { Finding, IngressResult } from "./types.js";
7
+ export interface FindingGroup {
8
+ pass: string;
9
+ kind: string;
10
+ count: number;
11
+ maxWeight: number | null;
12
+ }
13
+ export interface TopFinding {
14
+ pass: string;
15
+ kind: string;
16
+ weight: number | null;
17
+ message: string;
18
+ excerpt: string;
19
+ }
20
+ export interface ResultSummary {
21
+ url: string;
22
+ tier: IngressResult["tier"];
23
+ score: number;
24
+ contentKind: IngressResult["contentKind"];
25
+ findingCount: number;
26
+ groups: FindingGroup[];
27
+ top: TopFinding[];
28
+ }
29
+ /** confidence x severity, or null when either is not a finite number */
30
+ export declare function findingWeight(f: Pick<Finding, "confidence" | "severity">): number | null;
31
+ export declare function summarize(result: IngressResult, topN?: number): ResultSummary;
32
+ /**
33
+ * Cloaking-check settings from environment variables, shared by the CLI, the
34
+ * MCP server and the HTTP service:
35
+ * INGRESS_AGENT_UA "honest" to send only the gate's own name, or a "|"-separated list of user agents
36
+ * INGRESS_CLOAKING_JITTER "min,max" milliseconds between the two fetches
37
+ * INGRESS_HUMAN_PROXY HTTP(S) proxy URL for the browser-fingerprint fetch (e.g. a residential proxy)
38
+ * INGRESS_HUMAN_FETCH "browser" to make that fetch in a real headless Chromium
39
+ */
40
+ export declare function cloakingConfigFromEnv(env: Record<string, string | undefined>, honestUserAgent: string): Partial<import("./types.js").IngressConfig>;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Compact, machine-readable digest of a result: findings grouped by pass and
3
+ * kind with counts and peak weight, plus the heaviest findings first.
4
+ * Adapted from Briar Greenway's probe script (2026-11-03).
5
+ */
6
+ /** confidence x severity, or null when either is not a finite number */
7
+ export function findingWeight(f) {
8
+ const n = f.confidence * f.severity;
9
+ return Number.isFinite(n) ? n : null;
10
+ }
11
+ const rounded = (n) => (n === null ? null : Number(n.toFixed(2)));
12
+ export function summarize(result, topN = 6) {
13
+ const groups = new Map();
14
+ for (const f of result.findings) {
15
+ // a tuple key cannot collide even if a pass or kind contains a colon
16
+ const key = JSON.stringify([f.pass, f.kind]);
17
+ const g = groups.get(key) ?? { pass: f.pass, kind: f.kind, count: 0, maxWeight: null };
18
+ g.count++;
19
+ const w = findingWeight(f);
20
+ if (w !== null && (g.maxWeight === null || w > g.maxWeight))
21
+ g.maxWeight = w;
22
+ groups.set(key, g);
23
+ }
24
+ const top = result.findings
25
+ .map((f, index) => ({ f, index, w: findingWeight(f) }))
26
+ .sort((a, b) => (b.w ?? -Infinity) - (a.w ?? -Infinity) || a.index - b.index)
27
+ .slice(0, topN)
28
+ .map(({ f, w }) => ({
29
+ pass: f.pass, kind: f.kind, weight: rounded(w),
30
+ message: (f.message || "").slice(0, 140),
31
+ excerpt: (f.excerpt || "").replace(/\s+/g, " ").slice(0, 80),
32
+ }));
33
+ return {
34
+ url: result.receipt.finalUrl || result.receipt.url,
35
+ tier: result.tier, score: result.score, contentKind: result.contentKind,
36
+ findingCount: result.findings.length,
37
+ groups: [...groups.values()].map((g) => ({ ...g, maxWeight: rounded(g.maxWeight) })),
38
+ top,
39
+ };
40
+ }
41
+ /**
42
+ * Cloaking-check settings from environment variables, shared by the CLI, the
43
+ * MCP server and the HTTP service:
44
+ * INGRESS_AGENT_UA "honest" to send only the gate's own name, or a "|"-separated list of user agents
45
+ * INGRESS_CLOAKING_JITTER "min,max" milliseconds between the two fetches
46
+ * INGRESS_HUMAN_PROXY HTTP(S) proxy URL for the browser-fingerprint fetch (e.g. a residential proxy)
47
+ * INGRESS_HUMAN_FETCH "browser" to make that fetch in a real headless Chromium
48
+ */
49
+ export function cloakingConfigFromEnv(env, honestUserAgent) {
50
+ const cfg = {};
51
+ const ua = env.INGRESS_AGENT_UA?.trim();
52
+ if (ua)
53
+ cfg.agentUserAgents = ua === "honest" ? [honestUserAgent] : ua.split("|").map((s) => s.trim()).filter(Boolean);
54
+ const j = env.INGRESS_CLOAKING_JITTER?.split(",").map((x) => Number(x.trim()));
55
+ if (j && j.length === 2 && j.every((x) => Number.isFinite(x)))
56
+ cfg.cloakingJitterMs = [j[0], j[1]];
57
+ if (env.INGRESS_HUMAN_PROXY)
58
+ cfg.humanProxy = env.INGRESS_HUMAN_PROXY;
59
+ if (env.INGRESS_HUMAN_FETCH === "browser" || env.INGRESS_HUMAN_FETCH === "http")
60
+ cfg.humanFetch = env.INGRESS_HUMAN_FETCH;
61
+ return cfg;
62
+ }
@@ -20,5 +20,9 @@ export interface SupplyChainInput {
20
20
  raw: string;
21
21
  segments: ReadonlyArray<TextSegment>;
22
22
  decodedPayloads: ReadonlyArray<string>;
23
+ /** host of the page itself, so a site's own installer for another platform is not read as smuggled */
24
+ pageHost?: string;
23
25
  }
26
+ /** registrable domain, approximately: the last two labels, three under a two-level country suffix */
27
+ export declare function siteOf(host: string): string;
24
28
  export declare function scanSupplyChain(input: SupplyChainInput): Finding[];
@@ -64,6 +64,14 @@ const INSTALL_PATTERNS = [
64
64
  { re: /\bpython3?\s+-c\s+["'][^\n]{0,200}(urllib|requests|socket|exec\()/i, what: "inline Python that fetches or executes" },
65
65
  { re: /\bnode\s+-e\s+["'][^\n]{0,200}(child_process|https?\.get|fetch\(|eval\()/i, what: "inline Node that fetches or executes" },
66
66
  ];
67
+ const TWO_LEVEL = /\.(?:co|com|org|net|ac|gov|edu)\.[a-z]{2}$/i;
68
+ /** registrable domain, approximately: the last two labels, three under a two-level country suffix */
69
+ export function siteOf(host) {
70
+ const h = host.toLowerCase().replace(/\.$/, "");
71
+ const labels = h.split(".");
72
+ return labels.slice(TWO_LEVEL.test(h) ? -3 : -2).join(".");
73
+ }
74
+ const hostsIn = (t) => [...t.matchAll(/\b(?:https?:\/\/)?((?:[a-z0-9-]+\.)+[a-z]{2,})(?=[\/:\s"']|$)/gi)].map((m) => m[1].toLowerCase());
67
75
  const clip = (s, n = 200) => (s.length > n ? s.slice(0, n) + "…" : s);
68
76
  function hostOf(u) {
69
77
  const m = /^[a-z][a-z0-9+.-]*:\/\/([^/@]+@)?([^/:]+)/i.exec(u);
@@ -170,11 +178,24 @@ export function scanSupplyChain(input) {
170
178
  if (input.kind === "json" || input.kind === "text")
171
179
  findings.push(...lockfileFindings(input.raw, doc));
172
180
  // manifests carry their scripts as JSON strings; those were judged above, so skip segment scanning of $.scripts
181
+ // a hidden install line that a person can also read, word for word, elsewhere on the page hides nothing:
182
+ // install pages keep one block per platform and reveal the right one with a script (rustup.rs)
183
+ const squash = (t) => t.replace(/\s+/g, " ").trim();
184
+ const visibleText = squash(input.segments.filter((s) => s.visibility === "visible").map((s) => s.text).join(" "));
173
185
  for (const s of input.segments) {
174
186
  if (s.path.startsWith("$.scripts."))
175
187
  continue;
176
188
  // collapsed <details> and hidden tab panels are revealed by one click: install docs live there, so weigh them as visible
177
- findings.push(...installFindings(s.text, s.visibility !== "visible" && !s.path.includes("~revealable"), s.path));
189
+ let hidden = s.visibility !== "visible" && !s.path.includes("~revealable");
190
+ if (hidden) {
191
+ const cmds = installFindings(s.text, true, s.path).map((f) => squash(f.excerpt ?? ""));
192
+ if (cmds.length && cmds.every((c) => c.length >= 12 && visibleText.includes(c)))
193
+ hidden = false;
194
+ // or one that downloads only from the page's own site: the same installer for another platform (bun.sh, deno.com)
195
+ else if (cmds.length && input.pageHost && cmds.every((c) => { const hs = hostsIn(c); return hs.length > 0 && hs.every((h) => siteOf(h) === siteOf(input.pageHost)); }))
196
+ hidden = false;
197
+ }
198
+ findings.push(...installFindings(s.text, hidden, s.path));
178
199
  }
179
200
  for (const p of input.decodedPayloads)
180
201
  findings.push(...installFindings(p, true, "decoded payload"));
package/dist/src/taint.js CHANGED
@@ -7,7 +7,7 @@
7
7
  * the user-facing layer. Nothing here is mandatory; it is middleware the
8
8
  * integrator wraps around tool dispatch.
9
9
  */
10
- const TIER_RANK = { clean: 0, suspect: 1, hostile: 2 };
10
+ const TIER_RANK = { clean: 0, unreachable: 0, suspect: 1, hostile: 2 };
11
11
  export function createTaintGuard(policy = {}) {
12
12
  const p = {
13
13
  taintAt: policy.taintAt ?? "suspect",