@acepaste/ingress 0.8.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,393 @@
1
+ /**
2
+ * Environment audit (collectors). Read-only: it reads settings files and runs a few
3
+ * read-only system commands; it changes nothing. Secrets are never printed (MCP env
4
+ * values, proxy credentials). macOS is covered most fully; Linux partly; what was not
5
+ * checked is listed in `checked`, so a short report is never mistaken for a clean one.
6
+ */
7
+ import { execFile } from "node:child_process";
8
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
9
+ import { homedir, platform, networkInterfaces } from "node:os";
10
+ import { join } from "node:path";
11
+ import { lookup } from "node:dns/promises";
12
+ import { connect } from "node:tls";
13
+ import { createHash } from "node:crypto";
14
+ import { compareServed } from "./engine.js";
15
+ import { classifyHosts, classifyDnsmasq, classifyDnscryptRules, classifyResolvConf, classifyScutilDns, classifyScutilProxy, classifyProxyEnv, classifyChromiumSearch, classifyExtension, classifyChromiumPolicy, classifyTrustSettings, classifySystemExtensions, classifyMcpServers, classifyHooks, classifyResolution, summarizeAudit, ipv6Prefix64, WATCHED_DOMAINS, } from "./audit-parsers.js";
16
+ const read = (p) => { try {
17
+ return readFileSync(p, "utf8");
18
+ }
19
+ catch {
20
+ return undefined;
21
+ } };
22
+ const json = (p) => { const t = read(p); if (t === undefined)
23
+ return undefined; try {
24
+ return JSON.parse(t);
25
+ }
26
+ catch {
27
+ return undefined;
28
+ } };
29
+ const isDir = (p) => { try {
30
+ return statSync(p).isDirectory();
31
+ }
32
+ catch {
33
+ return false;
34
+ } };
35
+ const ls = (p) => { try {
36
+ return readdirSync(p);
37
+ }
38
+ catch {
39
+ return [];
40
+ } };
41
+ function defaultRun(cmd, args) {
42
+ return new Promise((res) => execFile(cmd, args, { timeout: 15_000, maxBuffer: 8 * 1024 * 1024 }, (err, out, errOut) => res(err && !out ? (String(errOut || "") || undefined) : String(out))));
43
+ }
44
+ export async function auditEnvironment(o = {}) {
45
+ const home = o.home ?? homedir();
46
+ const run = o.run ?? defaultRun;
47
+ const os = platform();
48
+ const findings = [];
49
+ const checked = [];
50
+ const note = (area, what, status, n) => checked.push({ area, what, status, note: n });
51
+ // ---------- hosts and local DNS ----------
52
+ const hostsPath = os === "win32" ? "C:\\Windows\\System32\\drivers\\etc\\hosts" : "/etc/hosts";
53
+ const hosts = read(hostsPath);
54
+ if (hosts !== undefined) {
55
+ findings.push(...classifyHosts(hosts, hostsPath));
56
+ note("hosts", hostsPath, "checked");
57
+ }
58
+ else
59
+ note("hosts", hostsPath, "error", "could not read");
60
+ const resolv = read("/etc/resolv.conf");
61
+ if (resolv !== undefined) {
62
+ const prefixes = Object.values(networkInterfaces()).flat().filter((a) => !!a && a.family === "IPv6" && !a.internal && !/^fe80:/i.test(a.address)).map((a) => ipv6Prefix64(a.address));
63
+ findings.push(...classifyResolvConf(resolv, "/etc/resolv.conf", prefixes));
64
+ note("dns", "/etc/resolv.conf", "checked");
65
+ }
66
+ if (os === "darwin") {
67
+ const dns = await run("/usr/sbin/scutil", ["--dns"]);
68
+ if (dns) {
69
+ findings.push(...classifyScutilDns(dns));
70
+ note("dns", "scutil --dns", "checked");
71
+ }
72
+ else
73
+ note("dns", "scutil --dns", "error");
74
+ for (const f of ls("/etc/resolver")) {
75
+ const t = read(join("/etc/resolver", f));
76
+ if (t)
77
+ findings.push({ area: "dns", severity: "review", title: `per-domain resolver for ${f}`, detail: `/etc/resolver/${f} sends lookups for ${f} to: ${[...t.matchAll(/nameserver\s+(\S+)/g)].map((m) => m[1]).join(", ") || "(see file)"}.`, where: `/etc/resolver/${f}` });
78
+ }
79
+ note("dns", "/etc/resolver", isDir("/etc/resolver") ? "checked" : "not present");
80
+ }
81
+ const dnsmasqFiles = ["/opt/homebrew/etc/dnsmasq.conf", "/usr/local/etc/dnsmasq.conf", "/etc/dnsmasq.conf", ...ls("/opt/homebrew/etc/dnsmasq.d").map((f) => `/opt/homebrew/etc/dnsmasq.d/${f}`), ...ls("/etc/dnsmasq.d").map((f) => `/etc/dnsmasq.d/${f}`)];
82
+ let sawDnsmasq = false;
83
+ for (const p of dnsmasqFiles) {
84
+ const t = read(p);
85
+ if (t === undefined)
86
+ continue;
87
+ sawDnsmasq = true;
88
+ const r = classifyDnsmasq(t, p);
89
+ findings.push(...r.findings);
90
+ for (const h of r.addnHosts) {
91
+ const ht = read(h);
92
+ if (ht)
93
+ findings.push(...classifyHosts(ht, h));
94
+ }
95
+ for (const d of r.confDirs)
96
+ for (const f of ls(d)) {
97
+ const ft = read(join(d, f));
98
+ if (ft)
99
+ findings.push(...classifyDnsmasq(ft, join(d, f)).findings);
100
+ }
101
+ }
102
+ note("dns", "dnsmasq configuration", sawDnsmasq ? "checked" : "not present");
103
+ let sawDnscrypt = false;
104
+ for (const dir of ["/opt/homebrew/etc", "/usr/local/etc", "/etc/dnscrypt-proxy", "/opt/homebrew/etc/dnscrypt-proxy"]) {
105
+ for (const [f, kind] of [["cloaking-rules.txt", "cloaking"], ["forwarding-rules.txt", "forwarding"]]) {
106
+ const t = read(join(dir, f));
107
+ if (t !== undefined) {
108
+ sawDnscrypt = true;
109
+ findings.push(...classifyDnscryptRules(t, join(dir, f), kind));
110
+ }
111
+ }
112
+ if (existsSync(join(dir, "dnscrypt-proxy.toml")))
113
+ sawDnscrypt = true;
114
+ }
115
+ note("dns", "dnscrypt-proxy rules", sawDnscrypt ? "checked" : "not present");
116
+ // ---------- proxies ----------
117
+ findings.push(...classifyProxyEnv(process.env));
118
+ note("proxy", "proxy environment variables", "checked");
119
+ if (os === "darwin") {
120
+ const p = await run("/usr/sbin/scutil", ["--proxy"]);
121
+ if (p) {
122
+ findings.push(...classifyScutilProxy(p));
123
+ note("proxy", "scutil --proxy", "checked");
124
+ }
125
+ else
126
+ note("proxy", "scutil --proxy", "error");
127
+ }
128
+ // ---------- browsers ----------
129
+ const chromiumRoots = os === "darwin" ? [
130
+ ["Chrome", join(home, "Library/Application Support/Google/Chrome"), ["com.google.Chrome"]],
131
+ ["Brave", join(home, "Library/Application Support/BraveSoftware/Brave-Browser"), ["com.brave.Browser"]],
132
+ ["Edge", join(home, "Library/Application Support/Microsoft Edge"), ["com.microsoft.Edge"]],
133
+ ["Arc", join(home, "Library/Application Support/Arc/User Data"), ["company.thebrowser.Browser"]],
134
+ ["Vivaldi", join(home, "Library/Application Support/Vivaldi"), ["com.vivaldi.Vivaldi"]],
135
+ ["Chromium", join(home, "Library/Application Support/Chromium"), ["org.chromium.Chromium"]],
136
+ ] : [
137
+ ["Chrome", join(home, ".config/google-chrome"), []], ["Brave", join(home, ".config/BraveSoftware/Brave-Browser"), []],
138
+ ["Edge", join(home, ".config/microsoft-edge"), []], ["Chromium", join(home, ".config/chromium"), []], ["Vivaldi", join(home, ".config/vivaldi"), []],
139
+ ];
140
+ for (const [browser, root, bundles] of chromiumRoots) {
141
+ if (!isDir(root)) {
142
+ note("browser-search", `${browser}`, "not present");
143
+ continue;
144
+ }
145
+ const profiles = ls(root).filter((d) => d === "Default" || /^Profile \d+$/.test(d));
146
+ for (const prof of profiles) {
147
+ const pdir = join(root, prof);
148
+ const prefs = json(join(pdir, "Preferences")) ?? {};
149
+ const secure = json(join(pdir, "Secure Preferences")) ?? {};
150
+ findings.push(...classifyChromiumSearch(prefs, `${browser} ${prof}`));
151
+ const settings = { ...(prefs.extensions?.settings ?? {}), ...(secure.extensions?.settings ?? {}) };
152
+ for (const x of readChromiumExtensions(join(pdir, "Extensions"), settings))
153
+ findings.push(...classifyExtension(x, `${browser} ${prof}`));
154
+ }
155
+ note("browser-search", `${browser} (${profiles.length} profile${profiles.length === 1 ? "" : "s"})`, "checked");
156
+ note("browser-extension", `${browser} extensions`, "checked");
157
+ // policies
158
+ if (os === "darwin") {
159
+ for (const b of bundles) {
160
+ for (const p of [`/Library/Managed Preferences/${b}.plist`, `/Library/Managed Preferences/${process.env.USER ?? ""}/${b}.plist`]) {
161
+ if (!existsSync(p))
162
+ continue;
163
+ const j = await run("/usr/bin/plutil", ["-convert", "json", "-o", "-", p]);
164
+ try {
165
+ if (j)
166
+ findings.push(...classifyChromiumPolicy(JSON.parse(j), p));
167
+ }
168
+ catch {
169
+ note("browser-policy", p, "error", "unreadable");
170
+ }
171
+ }
172
+ }
173
+ note("browser-policy", `${browser} managed policies`, "checked");
174
+ }
175
+ }
176
+ if (os === "linux")
177
+ for (const d of ["/etc/opt/chrome/policies/managed", "/etc/chromium/policies/managed", "/etc/brave/policies/managed", "/etc/opt/edge/policies/managed"]) {
178
+ for (const f of ls(d)) {
179
+ const j = json(join(d, f));
180
+ if (j)
181
+ findings.push(...classifyChromiumPolicy(j, join(d, f)));
182
+ }
183
+ note("browser-policy", d, isDir(d) ? "checked" : "not present");
184
+ }
185
+ // Firefox: policies, proxy prefs, extensions
186
+ const ffPolicies = os === "darwin" ? "/Applications/Firefox.app/Contents/Resources/distribution/policies.json" : "/etc/firefox/policies/policies.json";
187
+ const ffp = json(ffPolicies);
188
+ if (ffp?.policies) {
189
+ const p = ffp.policies;
190
+ if (p.SearchEngines?.Default || p.SearchEngines?.Add)
191
+ findings.push({ area: "browser-policy", severity: "high", title: "Firefox policy sets search engines", detail: `Default: ${p.SearchEngines.Default ?? "(unchanged)"}; added: ${(p.SearchEngines.Add ?? []).map((e) => e.Name).join(", ")}.`, where: ffPolicies });
192
+ if (p.Proxy)
193
+ findings.push({ area: "browser-policy", severity: "high", title: "Firefox policy sets a proxy", detail: JSON.stringify(p.Proxy).slice(0, 200), where: ffPolicies });
194
+ if (p.ExtensionSettings || p.Extensions)
195
+ findings.push({ area: "browser-policy", severity: "review", title: "Firefox policy manages extensions", detail: JSON.stringify(p.ExtensionSettings ?? p.Extensions).slice(0, 200), where: ffPolicies });
196
+ if (p.WebsiteFilter)
197
+ findings.push({ area: "browser-policy", severity: "review", title: "Firefox policy filters websites", detail: JSON.stringify(p.WebsiteFilter).slice(0, 200), where: ffPolicies });
198
+ }
199
+ const ffRoot = os === "darwin" ? join(home, "Library/Application Support/Firefox/Profiles") : join(home, ".mozilla/firefox");
200
+ if (isDir(ffRoot)) {
201
+ for (const prof of ls(ffRoot).filter((d) => isDir(join(ffRoot, d)))) {
202
+ const prefs = read(join(ffRoot, prof, "prefs.js")) ?? "";
203
+ const ptype = prefs.match(/user_pref\("network\.proxy\.type",\s*(\d)\)/)?.[1];
204
+ if (ptype === "1" || ptype === "2")
205
+ findings.push({ area: "proxy", severity: "review", title: `Firefox profile ${prof} uses a ${ptype === "2" ? "PAC" : "manual"} proxy`, detail: (prefs.match(/user_pref\("network\.proxy\.(?:autoconfig_url|http)",\s*"([^"]+)"\)/)?.[1]) ?? "", where: join(ffRoot, prof, "prefs.js") });
206
+ const ext = json(join(ffRoot, prof, "extensions.json"));
207
+ for (const a of ext?.addons ?? []) {
208
+ if (a.location === "app-builtin" || a.location === "app-system-defaults" || a.isSystem)
209
+ continue;
210
+ const perms = [...(a.userPermissions?.permissions ?? []), ...(a.optionalPermissions?.permissions ?? [])];
211
+ const origins = a.userPermissions?.origins ?? [];
212
+ findings.push(...classifyExtension({ id: a.id, name: a.defaultLocale?.name ?? a.id, version: a.version, permissions: perms, hostPermissions: origins, contentMatches: [], searchOverride: undefined, fromStore: a.signedState >= 2 || a.sourceURI?.startsWith?.("https://addons.mozilla.org"), enabled: a.active !== false }, `Firefox ${prof}`));
213
+ }
214
+ }
215
+ note("browser-extension", "Firefox profiles", "checked", "search engine settings are stored compressed and not read");
216
+ }
217
+ else
218
+ note("browser-extension", "Firefox", "not present");
219
+ if (os === "darwin")
220
+ note("browser-search", "Safari", "skipped", "Safari's settings are sandboxed from other programs");
221
+ // ---------- certificates and network extensions ----------
222
+ if (os === "darwin") {
223
+ const admin = await run("/usr/bin/security", ["dump-trust-settings", "-d"]);
224
+ const user = await run("/usr/bin/security", ["dump-trust-settings"]);
225
+ if (admin !== undefined)
226
+ findings.push(...classifyTrustSettings(admin, "admin"));
227
+ if (user !== undefined)
228
+ findings.push(...classifyTrustSettings(user, "user"));
229
+ note("certificates", "custom certificate trust (admin and user)", admin !== undefined || user !== undefined ? "checked" : "error");
230
+ const sx = await run("/usr/bin/systemextensionsctl", ["list"]);
231
+ if (sx) {
232
+ findings.push(...classifySystemExtensions(sx));
233
+ note("network-extension", "system extensions", "checked");
234
+ }
235
+ else
236
+ note("network-extension", "system extensions", "error");
237
+ }
238
+ else if (os === "linux") {
239
+ const extra = ls("/usr/local/share/ca-certificates");
240
+ for (const c of extra)
241
+ findings.push({ area: "certificates", severity: "review", title: `locally added CA certificate: ${c}`, detail: "A certificate added to the system trust store. It can be used to read and change encrypted traffic.", where: "/usr/local/share/ca-certificates" });
242
+ note("certificates", "/usr/local/share/ca-certificates", isDir("/usr/local/share/ca-certificates") ? "checked" : "not present");
243
+ }
244
+ // ---------- agent configuration ----------
245
+ const mcpConfigs = [
246
+ ["Claude Desktop", os === "darwin" ? join(home, "Library/Application Support/Claude/claude_desktop_config.json") : join(home, ".config/Claude/claude_desktop_config.json")],
247
+ ["Claude Code", join(home, ".claude.json")], ["Claude Code settings", join(home, ".claude/settings.json")],
248
+ ["Cursor", join(home, ".cursor/mcp.json")], ["Windsurf", join(home, ".codeium/windsurf/mcp_config.json")],
249
+ ["VS Code", os === "darwin" ? join(home, "Library/Application Support/Code/User/mcp.json") : join(home, ".config/Code/User/mcp.json")],
250
+ ["Gemini CLI", join(home, ".gemini/settings.json")],
251
+ ];
252
+ for (const [label, p] of mcpConfigs) {
253
+ const j = json(p);
254
+ if (!j) {
255
+ note("agent-config", label, "not present");
256
+ continue;
257
+ }
258
+ findings.push(...classifyMcpServers(j, `${label} (${p})`), ...classifyHooks(j, `${label} (${p})`));
259
+ note("agent-config", label, "checked");
260
+ }
261
+ const globalInstr = [join(home, ".claude/CLAUDE.md"), join(home, ".codex/AGENTS.md"), join(home, ".gemini/GEMINI.md"), join(home, ".codeium/windsurf/memories/global_rules.md"), join(home, ".config/opencode/AGENTS.md"), ...ls(join(home, ".cursor/rules")).map((f) => join(home, ".cursor/rules", f)), ...ls(join(home, ".claude/commands")).map((f) => join(home, ".claude/commands", f)), ...ls(join(home, ".claude/agents")).map((f) => join(home, ".claude/agents", f))];
262
+ for (const p of globalInstr) {
263
+ const t = read(p);
264
+ if (t === undefined)
265
+ continue;
266
+ const sha = createHash("sha256").update(t).digest("hex").slice(0, 12);
267
+ let verdict = "";
268
+ if (o.gate) {
269
+ const v = await o.gate(t, `file:${p}`);
270
+ if (v.tier !== "clean") {
271
+ findings.push({ area: "agent-instructions", severity: "high", title: `global agent instructions flagged: ${p}`, detail: `Loaded into every session of that agent, and the gate rates it ${v.tier}: ${[...new Set(v.findings.map((f) => f.message))].slice(0, 3).join("; ")}.`, where: p });
272
+ continue;
273
+ }
274
+ verdict = ", gate: clean";
275
+ }
276
+ findings.push({ area: "agent-instructions", severity: "info", title: `global agent instructions: ${p}`, detail: `${t.length} characters, fingerprint ${sha}${verdict}. Loaded into every session of that agent; check it says only what you wrote.`, where: p });
277
+ }
278
+ note("agent-instructions", "global instruction files (Claude, Codex, Gemini, Windsurf, Cursor)", "checked");
279
+ // ---------- live resolution and TLS ----------
280
+ if (o.network) {
281
+ const names = WATCHED_DOMAINS.filter((d) => !d.startsWith("www.") && d !== "en.wikipedia.org");
282
+ await Promise.all(names.map(async (n) => {
283
+ let local = [];
284
+ try {
285
+ local = (await lookup(n, { all: true })).map((a) => a.address);
286
+ }
287
+ catch { /* unresolvable here */ }
288
+ let doh;
289
+ try {
290
+ const r = await fetch(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(n)}&type=A`, { headers: { accept: "application/dns-json" }, signal: AbortSignal.timeout(8000) });
291
+ const j = await r.json();
292
+ doh = (j.Answer ?? []).filter((a) => a.type === 1).map((a) => a.data);
293
+ }
294
+ catch {
295
+ doh = undefined;
296
+ }
297
+ const tlsError = local.length && !local.every((a) => a === "0.0.0.0" || a.startsWith("127.")) ? await tlsCheck(n) : undefined;
298
+ findings.push(...classifyResolution(n, local, doh, tlsError));
299
+ }));
300
+ note("resolution", `name resolution and TLS for ${names.length} sites agents rely on, compared with DNS-over-HTTPS`, "checked");
301
+ }
302
+ else
303
+ note("resolution", "live resolution and TLS checks", "skipped", "run with --network");
304
+ // ---------- the same pages from another network ----------
305
+ if (o.remote) {
306
+ const urls = o.remote.urls ?? ["https://example.com/", "https://www.iana.org/help/example-domains", "https://en.wikipedia.org/wiki/Domain_Name_System"];
307
+ for (const u of urls) {
308
+ try {
309
+ const [here, there] = await Promise.all([
310
+ o.remote.localFetch(u),
311
+ fetch(new URL("/v1/fetch", o.remote.base), { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${o.remote.key}` }, body: JSON.stringify({ url: u }), signal: AbortSignal.timeout(30_000) }).then(async (r) => { const j = await r.json(); return { tier: j.tier ?? `error ${r.status}${j.error ? ": " + j.error : ""}`, delivered: j.delivered ?? "" }; }),
312
+ ]);
313
+ if (!here.delivered || !there.delivered) {
314
+ findings.push({ area: "resolution", severity: "info", title: `could not compare ${u}`, detail: `here: ${here.tier}, from the remote gate: ${there.tier}.`, where: u });
315
+ continue;
316
+ }
317
+ const c = compareServed(here.delivered, there.delivered);
318
+ if (c.agentOnlyWords >= 15 && c.agentOnlyShare >= 0.1)
319
+ findings.push({ area: "resolution", severity: "high", title: `${u} reads differently from this machine`, detail: `${(c.agentOnlyShare * 100).toFixed(0)}% of the words this machine received never appear in the copy fetched from another network. Something on this machine's path is changing pages. Words seen only here: ${c.sample}`, where: u });
320
+ else
321
+ findings.push({ area: "resolution", severity: "info", title: `${u} matches the copy from another network`, detail: `${c.agentWords} words compared.`, where: u });
322
+ }
323
+ catch (e) {
324
+ findings.push({ area: "resolution", severity: "info", title: `could not compare ${u}`, detail: e.message, where: u });
325
+ }
326
+ }
327
+ note("resolution", `${urls.length} stable pages compared with copies fetched by ${new URL(o.remote.base).host}`, "checked");
328
+ }
329
+ else
330
+ note("resolution", "comparison with another network", "skipped", "run with --remote=<gate URL> and INGRESS_API_KEY");
331
+ const order = { high: 0, review: 1, info: 2 };
332
+ findings.sort((a, b) => order[a.severity] - order[b.severity]);
333
+ return { at: new Date().toISOString(), platform: os, summary: summarizeAudit(findings), findings, checked };
334
+ }
335
+ function tlsCheck(host) {
336
+ return new Promise((res) => {
337
+ const s = connect({ host, port: 443, servername: host, timeout: 8000 }, () => { s.end(); res(undefined); });
338
+ s.on("error", (e) => res(/ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|ETIMEDOUT|ECONNRESET/.test(e.code ?? "") ? undefined : `${e.code ?? "error"}: ${e.message}`));
339
+ s.on("timeout", () => { s.destroy(); res(undefined); });
340
+ });
341
+ }
342
+ /** installed Chromium extensions from the profile's Extensions folder, joined with their settings (store or not, enabled or not) */
343
+ export function readChromiumExtensions(dir, settings) {
344
+ const out = [];
345
+ for (const id of ls(dir)) {
346
+ if (!/^[a-p]{32}$/.test(id))
347
+ continue;
348
+ const vers = ls(join(dir, id)).filter((v) => isDir(join(dir, id, v))).sort();
349
+ const v = vers[vers.length - 1];
350
+ if (!v)
351
+ continue;
352
+ const base = join(dir, id, v);
353
+ const m = json(join(base, "manifest.json"));
354
+ if (!m)
355
+ continue;
356
+ const st = settings[id] ?? {};
357
+ if (st.location === 5 || st.location === 10)
358
+ continue; // the browser's own components
359
+ let name = m.name ?? id;
360
+ const msg = name.match(/^__MSG_(\w+)__$/);
361
+ if (msg) {
362
+ const loc = json(join(base, "_locales", "en", "messages.json")) ?? json(join(base, "_locales", m.default_locale ?? "en", "messages.json")) ?? {};
363
+ const key = Object.keys(loc).find((k) => k.toLowerCase() === msg[1].toLowerCase());
364
+ name = key ? loc[key].message : id;
365
+ }
366
+ const cso = m.chrome_settings_overrides ?? {};
367
+ out.push({
368
+ id, name, version: m.version,
369
+ permissions: (m.permissions ?? []).filter((p) => typeof p === "string"),
370
+ hostPermissions: [...(m.host_permissions ?? []), ...(m.permissions ?? []).filter((p) => typeof p === "string" && /[:/*]/.test(p))],
371
+ contentMatches: (m.content_scripts ?? []).flatMap((c) => c.matches ?? []),
372
+ searchOverride: cso.search_provider?.search_url, homepageOverride: cso.homepage, startupOverride: !!cso.startup_pages,
373
+ fromStore: st.from_webstore === true || st.location === 1 || (st.location === undefined && !!m.update_url && /clients2\.google\.com|edge\.microsoft\.com/.test(m.update_url)),
374
+ enabled: st.state === undefined ? !st.disable_reasons : st.state === 1,
375
+ });
376
+ }
377
+ return out;
378
+ }
379
+ export function formatAudit(r) {
380
+ const lines = [`AcePaste Ingress environment audit, ${r.at} (${r.platform})`, `${r.summary.high} high, ${r.summary.review} to review, ${r.summary.info} noted`, ""];
381
+ for (const sev of ["high", "review", "info"]) {
382
+ const fs = r.findings.filter((f) => f.severity === sev);
383
+ if (!fs.length)
384
+ continue;
385
+ lines.push(sev === "high" ? "HIGH: can steer what agents receive and looks out of place" : sev === "review" ? "REVIEW: changes what agents receive; may well be yours" : "NOTED", "");
386
+ for (const f of fs)
387
+ lines.push(` [${f.area}] ${f.title}`, ` ${f.detail}`, ...(f.where ? [` where: ${f.where}`] : []), "");
388
+ }
389
+ lines.push("What was checked:");
390
+ for (const c of r.checked)
391
+ lines.push(` ${c.status.padEnd(11)} ${c.what}${c.note ? ` (${c.note})` : ""}`);
392
+ return lines.join("\n");
393
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Action broker: the enforcement point between an agent and its side-effecting tools.
3
+ *
4
+ * The gate's verdict never authorizes an action. The broker decides, outside the model:
5
+ * - a run is tainted as soon as it has taken in any outside content, whatever that
6
+ * content scored (a low score is a prioritization signal, not proof of safety)
7
+ * - while tainted, tools the policy marks as side-effecting need a person's approval of
8
+ * the EXACT call (tool + arguments, by digest); approvals are single-use, short-lived
9
+ * and bound to the run
10
+ * - approvals come only from an Approver: a channel the model cannot drive (a native
11
+ * dialog, a console behind its own credential). There is no tool the model can call
12
+ * to approve itself
13
+ * - arguments that carry data out (long query strings, encoded blobs, URLs to hosts
14
+ * outside an allowlist) need approval while tainted, even on "read" tools
15
+ * - a run that touched a quarantined source is denied side effects outright
16
+ *
17
+ * Limit, stated plainly: the broker enforces only on calls routed through it. A tool the
18
+ * agent can reach directly is outside its control.
19
+ */
20
+ export type ActionDecision = "allow" | "require_approval" | "deny";
21
+ export interface ActionRule {
22
+ /** tool name, exact or with * wildcards ("*__send_*", "filesystem__write_file") */
23
+ tool: string;
24
+ /** decision when the run has not taken in outside content */
25
+ clean?: ActionDecision;
26
+ /** decision when the run is tainted */
27
+ tainted?: ActionDecision;
28
+ /** if set, any host found in the arguments must match one of these (exact or ".suffix") or the call needs approval */
29
+ allowDestinations?: string[];
30
+ }
31
+ export interface BrokerPolicy {
32
+ name: string;
33
+ version: number;
34
+ rules: ActionRule[];
35
+ /**
36
+ * Tools that only read and may run without approval while tainted (globs). Everything
37
+ * else that has no rule needs approval once the run is tainted: a tool the broker does not
38
+ * know is treated as able to act, never guessed from its name.
39
+ */
40
+ readOnlyTools: string[];
41
+ /** words that mark a tool as side-effecting; used only to explain decisions, never to allow */
42
+ sideEffectHints: string[];
43
+ /** hosts any call may send to without approval while tainted (exact or ".suffix") */
44
+ allowHosts: string[];
45
+ /** while tainted, arguments shaped like data leaving (see exfilShapes) need approval */
46
+ guardOutboundData: boolean;
47
+ /** how long an approval stays usable */
48
+ approvalTtlMs: number;
49
+ /** arguments longer than this cannot be shown in full to the person, so they are refused */
50
+ maxShownArgChars: number;
51
+ /** what to do when approval is needed but no approver is configured or it fails */
52
+ onApproverUnavailable: "deny";
53
+ }
54
+ export declare const DEFAULT_BROKER_POLICY: BrokerPolicy;
55
+ export interface ProposedAction {
56
+ runId: string;
57
+ tool: string;
58
+ args: unknown;
59
+ }
60
+ export interface ApprovalRequest {
61
+ id: string;
62
+ runId: string;
63
+ tool: string;
64
+ /** canonical JSON of the arguments, exactly what will run */
65
+ canonicalArgs: string;
66
+ digest: string;
67
+ reasons: string[];
68
+ /** hosts and addresses found in the arguments, listed first for the person */
69
+ destinations?: string[];
70
+ /** every field name in the arguments */
71
+ fields?: string[];
72
+ /** outside sources this run has taken in, for the person deciding */
73
+ sources: string[];
74
+ createdAt: number;
75
+ expiresAt: number;
76
+ }
77
+ export interface Approver {
78
+ /** show the exact action to a person and return their answer. Must not be reachable by the model. */
79
+ request(req: ApprovalRequest): Promise<"approved" | "denied" | "timeout">;
80
+ readonly name: string;
81
+ }
82
+ export interface BrokerVerdict {
83
+ decision: ActionDecision;
84
+ /** final outcome after any approval: run it or not */
85
+ permitted: boolean;
86
+ reasons: string[];
87
+ digest: string;
88
+ approval?: {
89
+ id: string;
90
+ outcome: "approved" | "denied" | "timeout" | "unavailable";
91
+ };
92
+ policy: {
93
+ name: string;
94
+ version: number;
95
+ };
96
+ }
97
+ export interface BrokerEvent {
98
+ event: "broker.decision";
99
+ at: string;
100
+ runId: string;
101
+ tool: string;
102
+ digest: string;
103
+ decision: ActionDecision;
104
+ permitted: boolean;
105
+ reasons: string[];
106
+ approval?: BrokerVerdict["approval"];
107
+ sources: string[];
108
+ policy: {
109
+ name: string;
110
+ version: number;
111
+ };
112
+ }
113
+ /** deterministic JSON: object keys sorted at every depth, so one call has one digest */
114
+ export declare function canonicalJson(v: unknown): string;
115
+ export declare function actionDigest(runId: string, tool: string, canonicalArgs: string): string;
116
+ /**
117
+ * Whether a tool's name says it acts. Used only to explain a decision: an unknown tool
118
+ * needs approval while tainted whatever its name says.
119
+ */
120
+ export declare function isSideEffectName(tool: string, hints: readonly string[]): boolean;
121
+ /** hosts and addresses named in the arguments, broadly: URLs of any scheme, scheme-less URLs, bare domains, email domains, IP addresses */
122
+ export declare function destinationsIn(args: unknown): {
123
+ hosts: string[];
124
+ oddities: string[];
125
+ complete: boolean;
126
+ };
127
+ /** argument shapes that look like data leaving through a URL: encoded tokens anywhere in it, long subdomains, long query or fragment */
128
+ export declare function exfilShapes(args: unknown): string[];
129
+ export declare class ActionBroker {
130
+ private deps;
131
+ readonly policy: BrokerPolicy;
132
+ private runs;
133
+ private globalQuarantine;
134
+ private used;
135
+ constructor(policy?: Partial<BrokerPolicy>, deps?: {
136
+ approver?: Approver;
137
+ log?: (e: BrokerEvent) => void;
138
+ now?: () => number;
139
+ });
140
+ private run;
141
+ private quarantineHit;
142
+ /** is this URL or host quarantined? (check before fetching, and on the final URL after redirects) */
143
+ isQuarantined(urlOrHost: string): string | undefined;
144
+ /** record outside content the run has taken in. Any source taints the run, whatever its verdict. */
145
+ ingest(runId: string, source: {
146
+ ref: string;
147
+ receiptDigest?: string;
148
+ host?: string;
149
+ }): {
150
+ tainted: true;
151
+ sources: string[];
152
+ };
153
+ /** mark a source (URL prefix, host with its subdomains, or receipt digest) as quarantined everywhere; returns the runs that already touched it */
154
+ quarantine(ref: string): string[];
155
+ state(runId: string): {
156
+ tainted: boolean;
157
+ sources: string[];
158
+ quarantined: string[];
159
+ };
160
+ /** decide without asking anyone (for previews and tests) */
161
+ classify(action: ProposedAction): {
162
+ decision: ActionDecision;
163
+ reasons: string[];
164
+ digest: string;
165
+ canonicalArgs: string;
166
+ destinations: string[];
167
+ fields: string[];
168
+ };
169
+ /**
170
+ * Decide, asking the approver when needed. The caller must then execute EXACTLY the
171
+ * arguments it gets back (frozen) or not at all.
172
+ */
173
+ authorize(action: ProposedAction): Promise<BrokerVerdict & {
174
+ args: unknown;
175
+ }>;
176
+ }
177
+ /** readable text of an approval request for a human: destinations and field names first, every invisible or format character made visible */
178
+ export declare function describeApproval(req: ApprovalRequest, maxArgs?: number): string;