@acepaste/ingress 0.9.24 → 0.9.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/cli.js CHANGED
@@ -21,17 +21,20 @@ import { trackAudit, confirmAuditArea, formatAuditChanges, AUDIT_NEEDS_CONFIRMAT
21
21
  import { confirmServerTools, describeServerTools } from "./tooldefs.js";
22
22
  import { BaselineStore } from "./changes.js";
23
23
  import { engageStop, clearStop, stopReason } from "./safeguards.js";
24
- import { postToolUse, preToolUse, userPromptSubmit, preCompact, postCompact, sessionStart, remoteGate } from "./agent-hooks.js";
25
- import { Blocklist, BLOCKLIST_FEEDS } from "./egress.js";
24
+ import { postToolUse, preToolUse, preToolUseAnswered, egressProxyBefore, userPromptSubmit, preCompact, postCompact, sessionStart, remoteGate } from "./agent-hooks.js";
25
+ import { startEgressProxy, egressProxyOptionsFromEnv, egressProxyOn, ensureEgressProxy, proxyHealth, proxySecret, sessionToken, sessionOfToken, proxyEnv, commandStart, connectionsSince, sandboxUsable, runSandboxed } from "./egress-proxy.js";
26
+ import { Blocklist } from "./egress.js";
27
+ import { updateBlocklists, blocklistsRefreshedAt, startBlocklistRefresh } from "./blocklist-update.js";
26
28
  import { ProvenanceLedger, describeMark, downloadOrigin } from "./provenance.js";
27
29
  import { buildVisionHelper, buildNativeHelper, visionHelperPath, visionHelperProblem } from "./image.js";
28
- import { presenceHelperPath } from "./approvers.js";
30
+ import { presenceHelperPath, presenceApprover } from "./approvers.js";
31
+ import { existsSync } from "node:fs";
29
32
  import { collectNearby } from "./nearby.js";
30
33
  import { execFileSync } from "node:child_process";
31
34
  import { mkdtempSync, rmSync } from "node:fs";
32
35
  import { tmpdir } from "node:os";
33
36
  import { stateDir } from "./changes.js";
34
- import { appendFileSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
37
+ import { appendFileSync } from "node:fs";
35
38
  import { homedir } from "node:os";
36
39
  import { join } from "node:path";
37
40
  import { createInterface } from "node:readline/promises";
@@ -51,6 +54,10 @@ async function main() {
51
54
  return toolsCommand(args.slice(1));
52
55
  if (args[0] === "blocklist")
53
56
  return blocklistCommand(args.slice(1));
57
+ if (args[0] === "egress-proxy")
58
+ return egressProxyCommand(args.slice(1));
59
+ if (args[0] === "run")
60
+ return runCommand(args.slice(1));
54
61
  if (args[0] === "provenance")
55
62
  return provenanceCommand(args.slice(1));
56
63
  if (args[0] === "vision")
@@ -304,6 +311,100 @@ async function main() {
304
311
  console.error(`\n[timings] ${Object.entries(result.timings).map(([k, v]) => `${k}=${v.toFixed(1)}ms`).join(" ")}`);
305
312
  }
306
313
  main().catch((e) => { console.error(e); process.exit(1); });
314
+ /**
315
+ * ingress egress-proxy run the egress proxy on 127.0.0.1 (see egress-proxy.ts and docs/EGRESS.md)
316
+ * ingress egress-proxy status is it running
317
+ * ingress egress-proxy env [name] the variables that point a shell at it, for a session called <name>
318
+ * ingress egress-proxy log [n] the last n connections it decided (host, port, bytes, decision; never content)
319
+ * Settings: INGRESS_EGRESS_PROXY_PORT (8788), INGRESS_EGRESS_PROXY_MODE=strict, INGRESS_EGRESS_ALLOW_HOSTS,
320
+ * INGRESS_EGRESS_PROXY_ALLOW_PRIVATE, INGRESS_EGRESS_PROXY_PORTS, INGRESS_EGRESS_PROXY_APPROVER=macos-presence.
321
+ */
322
+ async function egressProxyCommand(a) {
323
+ const o = egressProxyOptionsFromEnv();
324
+ const port = o.port ?? 8788;
325
+ if (a[0] === "status") {
326
+ const s = await proxyHealth(port);
327
+ console.log(s === "ours" ? `running on 127.0.0.1:${port}` : s === "other" ? `port ${port} answers, but not as this installation's egress proxy` : `not running (port ${port})`);
328
+ if (s !== "ours")
329
+ process.exitCode = 1;
330
+ return;
331
+ }
332
+ if (a[0] === "env") {
333
+ const name = a[1] ?? `shell-${process.ppid}`;
334
+ for (const [k, v] of Object.entries(proxyEnv(port, sessionToken(proxySecret(), name))))
335
+ console.log(`export ${k}='${v}'`);
336
+ return;
337
+ }
338
+ if (a[0] === "log") {
339
+ const n = Math.max(1, Math.min(1000, Number(a[1]) || 30));
340
+ let lines = [];
341
+ try {
342
+ lines = readFileSync(join(stateDir(), "egress-proxy", "connections.jsonl"), "utf8").trim().split("\n").slice(-n);
343
+ }
344
+ catch { /* nothing logged yet */ }
345
+ for (const l of lines) {
346
+ try {
347
+ const e = JSON.parse(l);
348
+ console.log([e.at, e.decision, `${e.host}:${e.port}`, e.closed ? `up ${e.up} down ${e.down} bytes` : e.reason, e.flag ? `FLAG ${e.flag}` : ""].filter(Boolean).join(" "));
349
+ }
350
+ catch { /* skip */ }
351
+ }
352
+ if (!lines.length)
353
+ console.log("no connections logged");
354
+ return;
355
+ }
356
+ // a host known only from outside content: refused, unless a person at this Mac is asked (Touch ID or password)
357
+ if ((process.env.INGRESS_EGRESS_PROXY_APPROVER ?? "") === "macos-presence" && process.platform === "darwin" && existsSync(presenceHelperPath())) {
358
+ o.approver = presenceApprover(macosDialogApprover({ timeoutSec: 60 }), { biometryOnly: process.env.INGRESS_PRESENCE_BIOMETRY_ONLY === "1" });
359
+ o.policy = { ...o.policy, contentHosts: "ask" };
360
+ }
361
+ // started on demand by a hook: leave after twelve hours with no connection (a hook starts it again when needed)
362
+ if (a.includes("--idle-exit")) {
363
+ o.idleExitMs = 12 * 3600 * 1000;
364
+ o.onIdle = () => process.exit(0);
365
+ }
366
+ try {
367
+ const p = await startEgressProxy(o);
368
+ process.stderr.write(JSON.stringify({ event: "ingress.egress-proxy.listen", host: "127.0.0.1", port: p.port, mode: o.policy?.mode ?? "log", approver: o.approver?.name ?? "none" }) + "\n");
369
+ }
370
+ catch (e) {
371
+ console.error(`ingress egress-proxy: could not listen on 127.0.0.1:${port} (${e.message})`);
372
+ process.exit(1);
373
+ }
374
+ }
375
+ /**
376
+ * ingress run [--loopback=allow] -- <command> [args...] run a command with its network confined to the egress proxy
377
+ * ingress run [--loopback=allow] -c '<shell script>' the same for a line of shell
378
+ * macOS only (sandbox-exec). The command and everything it starts can open network connections only to the
379
+ * proxy; with --loopback=allow, also to other ports on this machine (a test suite and its own server), except
380
+ * the name-service ports. Inside an agent session whose commands are already pointed at the proxy, the
381
+ * session's token is used, so the proxy judges the connections with what that session has read.
382
+ */
383
+ async function runCommand(a) {
384
+ const loopback = a.includes("--loopback=allow") ? "allow" : "proxy-only";
385
+ const sep = a.indexOf("--"), c = a.indexOf("-c");
386
+ const argv = c >= 0 && (sep < 0 || c < sep) ? [process.env.SHELL || "/bin/sh", "-c", a[c + 1] ?? ""] : sep >= 0 ? a.slice(sep + 1) : [];
387
+ if (!argv.length || (c >= 0 && !a[c + 1])) {
388
+ console.error("usage: ingress run [--loopback=allow] -- <command> [args...] | ingress run [--loopback=allow] -c '<shell script>'");
389
+ process.exit(2);
390
+ }
391
+ const usable = sandboxUsable();
392
+ if (!usable.ok) {
393
+ console.error(`ingress run: ${usable.why}.`);
394
+ process.exit(126);
395
+ }
396
+ const port = egressProxyOptionsFromEnv().port ?? 8788;
397
+ const up = await ensureEgressProxy({ port });
398
+ if (!up.ok) {
399
+ console.error(`ingress run: the egress proxy is not running (${up.why}). Nothing was run.`);
400
+ process.exit(126);
401
+ }
402
+ const secret = proxySecret();
403
+ // the token this shell was given at session start, if it is one of ours; else a session of its own
404
+ const given = (process.env.INGRESS_EGRESS_PROXY_URL ?? "").match(/^http:\/\/[^:@/]*:([^@/]+)@/)?.[1];
405
+ const token = given && sessionOfToken(secret, given) ? given : sessionToken(secret, `run-${process.pid}-${Date.now().toString(36)}`);
406
+ process.exit(runSandboxed(argv, { proxyPort: port, token, loopback }));
407
+ }
307
408
  /**
308
409
  * ingress hook <event> reply to an agent harness hook: the event's JSON on stdin, the reply on stdout
309
410
  * events: pre-tool-use, post-tool-use, user-prompt-submit, pre-compact, post-compact, session-start
@@ -364,8 +465,41 @@ async function hookCommand(event, stdin) {
364
465
  switch (event) {
365
466
  // the egress gate needs no engine: it judges the action with what the session has already read.
366
467
  // INGRESS_EGRESS_ALLOW_HOSTS: comma-separated hosts data may go to without a question (".example.com" covers subdomains)
367
- case "pre-tool-use": return out(preToolUse(input, { ownPort, allowHosts: (process.env.INGRESS_EGRESS_ALLOW_HOSTS ?? "").split(",").map((s) => s.trim()).filter(Boolean) }));
368
- case "post-tool-use": return out(await postToolUse(input, gate, { ownPort }));
468
+ case "pre-tool-use": {
469
+ const egress = { ownPort, allowHosts: (process.env.INGRESS_EGRESS_ALLOW_HOSTS ?? "").split(",").map((s) => s.trim()).filter(Boolean) };
470
+ // INGRESS_EGRESS_PROXY=on: after the decision, a shell command's start and the hosts it names are noted for
471
+ // the egress proxy, and the proxy is started if it is not running. The command is never rewritten.
472
+ const proxied = (reply) => (egressProxyOn() ? egressProxyBefore(input, reply, { ensure: () => ensureEgressProxy({ port: egressProxyOptionsFromEnv().port }) }) : Promise.resolve(reply));
473
+ // INGRESS_HOOK_APPROVER: who answers when the gate has a question. Unset: the harness's own prompt (which a
474
+ // mode that approves prompts automatically answers for the person). "macos-presence": a person at this Mac,
475
+ // through a system dialog showing the action and then Touch ID or the login password. "deny": nobody; every
476
+ // question is a refusal. Anything else is a mistake in the settings and is treated as "deny", not ignored.
477
+ const who = (process.env.INGRESS_HOOK_APPROVER ?? "").trim();
478
+ if (!who)
479
+ return out(await proxied(preToolUse(input, egress)));
480
+ // INGRESS_HOOK_APPROVER_SECONDS: how long a person has to answer (default 120, 20 to 540). The hook's timeout
481
+ // in the harness settings must be longer than this, or the harness kills the hook and carries on without it.
482
+ const budget = Math.max(20, Math.min(540, Number(process.env.INGRESS_HOOK_APPROVER_SECONDS) || 120));
483
+ const cannot = (why) => ({ name: who, request: async () => { throw new Error(why); } });
484
+ const approver = who !== "macos-presence" ? cannot(who === "deny" ? "no approver" : `unknown approver ${who}`)
485
+ : process.platform !== "darwin" ? cannot("macos-presence needs macOS")
486
+ : !existsSync(presenceHelperPath()) ? cannot("the presence helper is not built (ingress presence build)")
487
+ : presenceApprover(macosDialogApprover({ timeoutSec: Math.round(budget * 0.6) }), { biometryOnly: process.env.INGRESS_PRESENCE_BIOMETRY_ONLY === "1" });
488
+ const reply = await proxied(await preToolUseAnswered(input, approver, { ...egress, answerWithinMs: budget * 1000 }));
489
+ // The answer is written, then the process ends at once: a dialog nobody answered may still be on the
490
+ // screen, and waiting for it would hold the hook past the harness's timeout (which would count as no answer).
491
+ if (reply !== undefined)
492
+ await new Promise((done) => process.stdout.write(JSON.stringify(reply) + "\n", () => done()));
493
+ process.exit(0);
494
+ }
495
+ case "post-tool-use": {
496
+ // with the egress proxy on: what it carried or refused for this session since the command started
497
+ const proxyConnections = !egressProxyOn() ? undefined : (session, toolUseId) => {
498
+ const since = commandStart(stateDir(), session, toolUseId);
499
+ return since === undefined ? [] : connectionsSince(stateDir(), session, since - 250);
500
+ };
501
+ return out(await postToolUse(input, gate, { ownPort, ...(proxyConnections ? { proxyConnections } : {}) }));
502
+ }
369
503
  case "user-prompt-submit": return out(await userPromptSubmit(input, gate));
370
504
  case "pre-compact":
371
505
  process.stdout.write(preCompact() + "\n");
@@ -373,7 +507,17 @@ async function hookCommand(event, stdin) {
373
507
  case "post-compact":
374
508
  await postCompact(input, gate);
375
509
  return;
376
- case "session-start": return out(sessionStart(input, { marker: process.env.INGRESS_SESSION_MARKER !== "0" }));
510
+ case "session-start":
511
+ // stale blocklists are refreshed by a separate process; the reply does not wait for it
512
+ startBlocklistRefresh();
513
+ // INGRESS_EGRESS_PROXY=on: the proxy is started if need be, and the session's shell commands are pointed at
514
+ // it through the file the harness reads variables from (CLAUDE_ENV_FILE, which only this hook is given)
515
+ if (egressProxyOn()) {
516
+ const port = egressProxyOptionsFromEnv().port ?? 8788;
517
+ await ensureEgressProxy({ port });
518
+ return out(sessionStart(input, { marker: process.env.INGRESS_SESSION_MARKER !== "0", egressProxy: { port, envFile: process.env.CLAUDE_ENV_FILE || undefined } }));
519
+ }
520
+ return out(sessionStart(input, { marker: process.env.INGRESS_SESSION_MARKER !== "0" }));
377
521
  default:
378
522
  console.error("usage: ingress hook pre-tool-use|post-tool-use|user-prompt-submit|pre-compact|post-compact|session-start (event JSON on stdin)");
379
523
  process.exit(2);
@@ -497,35 +641,22 @@ async function provenanceCommand(a) {
497
641
  * ingress blocklist check <host> is this host or address on a list?
498
642
  * Lists are plain text files in <state>/blocklists; add your own there, one host, address or IPv4 range per line.
499
643
  * The broker and the egress hook refuse any action whose arguments name a listed destination.
644
+ * The downloaded lists refresh themselves once a day (see blocklist-update.ts); INGRESS_BLOCKLIST_AUTO=off stops that.
500
645
  */
501
646
  async function blocklistCommand(a) {
502
647
  const dir = join(stateDir(), "blocklists");
503
648
  if (a[0] === "update") {
504
- mkdirSync(dir, { recursive: true, mode: 0o700 });
505
- let failed = 0;
506
- for (const f of BLOCKLIST_FEEDS) {
507
- try {
508
- const res = await fetch(f.url, { signal: AbortSignal.timeout(30_000), redirect: "follow", headers: { "user-agent": HONEST_USER_AGENT } });
509
- if (!res.ok)
510
- throw new Error(`HTTP ${res.status}`);
511
- const text = await res.text();
512
- if (text.length > 50_000_000)
513
- throw new Error("larger than 50 MB");
514
- // a list is kept only if it parses as one: a block page or an error page saved as a list would silently protect nothing
515
- const n = new Blocklist().add(text, f.name);
516
- if (n < 5)
517
- throw new Error(`only ${n} entries parsed; keeping the previous copy`);
518
- const p = join(dir, `${f.name}.txt`);
519
- writeFileSync(`${p}.tmp`, `# ${f.what}\n# from ${f.url} on ${new Date().toISOString()} (${f.terms})\n${text}`, { mode: 0o600 });
520
- renameSync(`${p}.tmp`, p);
521
- console.log(`${f.name}: ${n} entries (${f.what})`);
522
- }
523
- catch (e) {
524
- failed++;
525
- console.error(`${f.name}: not updated (${e.message ?? e})`);
526
- }
527
- }
528
- if (failed)
649
+ const quiet = a.includes("--quiet"); // how the background refresh runs it: nothing to print to
650
+ const outcomes = await updateBlocklists(dir);
651
+ for (const f of outcomes) {
652
+ if (quiet)
653
+ continue;
654
+ if (f.error)
655
+ console.error(`${f.name}: not updated (${f.error})`);
656
+ else
657
+ console.log(`${f.name}: ${f.entries} entries (${f.what})`);
658
+ }
659
+ if (outcomes.some((f) => f.error))
529
660
  process.exitCode = 1;
530
661
  return;
531
662
  }
@@ -541,11 +672,14 @@ async function blocklistCommand(a) {
541
672
  process.exitCode = 1;
542
673
  return;
543
674
  }
675
+ const auto = /^(off|0|false|no)$/i.test(process.env.INGRESS_BLOCKLIST_AUTO ?? "") ? "automatic refresh is off (INGRESS_BLOCKLIST_AUTO)" : "refreshed automatically once a day";
544
676
  if (!b.size) {
545
- console.log(`no blocklists in ${dir}\nrun: ingress blocklist update`);
677
+ console.log(`no blocklists in ${dir}\nrun: ingress blocklist update (${auto})`);
546
678
  return;
547
679
  }
548
- console.log(`${b.size} entries in ${dir}\n${b.sources.map((s) => ` ${s}`).join("\n")}`);
680
+ const at = blocklistsRefreshedAt(dir);
681
+ const when = at === undefined ? "the free lists have not been downloaded" : `last refreshed ${new Date(at).toISOString().slice(0, 16).replace("T", " ")} UTC (${Math.max(0, Math.round((Date.now() - at) / 3_600_000))} hours ago)`;
682
+ console.log(`${b.size} entries in ${dir}\n${b.sources.map((s) => ` ${s}`).join("\n")}\n${when}; ${auto}`);
549
683
  }
550
684
  /**
551
685
  * ingress tools downstream MCP servers whose tools were recorded, and their state
@@ -0,0 +1,182 @@
1
+ /**
2
+ * The egress proxy: where programs an agent runs actually connect.
3
+ *
4
+ * The egress hook reads a command. It does not read the program the command starts: `python upload.py` sends
5
+ * whatever the script sends. Stopping that for a whole machine needs a network filter Apple licenses. This is
6
+ * the part that needs no licence: an HTTP forward proxy on 127.0.0.1 that the agent's shell commands are
7
+ * pointed at (HTTPS_PROXY and friends), which decides each connection by its destination.
8
+ *
9
+ * - CONNECT (everything over TLS) and plain HTTP. It sees a host name and a port, and counts bytes. It never
10
+ * reads what is sent: TLS is not opened.
11
+ * - Every client presents a token made for one agent session. No token, no service. The token says whose
12
+ * connection this is, so the decision can use what that session has read.
13
+ * - The decision reuses what the action broker knows (see ActionBroker.hostStanding): a blocklisted host or
14
+ * address is refused; an address on this machine or a private network is refused (the proxy must not be a
15
+ * way around the checks the gate's own fetches make); a host that came into the session only through
16
+ * outside content, and that no command named, is refused (or put to a person, when an approver is
17
+ * configured); a host on the allowlist, or one the person typed, passes. Anything else passes and is
18
+ * logged, or is refused in strict mode.
19
+ * - Every connection is logged in <state>/egress-proxy/connections.jsonl: time, session, host, port, bytes
20
+ * each way, decision. Never content.
21
+ *
22
+ * What it is not: a firewall. A program that ignores proxy settings connects directly unless it runs under the
23
+ * sandbox wrapper below (`ingress run`). A host that is allowed can pass data on to another. It covers what
24
+ * the agent starts, not the machine.
25
+ */
26
+ import { type Server } from "node:http";
27
+ import { type Approver } from "./broker.js";
28
+ import { Blocklist } from "./egress.js";
29
+ export declare const EGRESS_PROXY_PORT = 8788;
30
+ /** how long a host named in a command the hook let through stays usable by what that command started */
31
+ export declare const VISIBLE_HOST_TTL_MS: number;
32
+ /** The secret tokens are made with. Created on first use; readable by this user only. */
33
+ export declare function proxySecret(dir?: string): string;
34
+ /** A token for one session: the session's name and a keyed digest of it. Safe to put in a URL. */
35
+ export declare function sessionToken(secret: string, session: string): string;
36
+ /** The session a token was made for, or undefined when it was not made with this secret. */
37
+ export declare function sessionOfToken(secret: string, token: string): string | undefined;
38
+ /** The variables that point a command's network calls at the proxy. Loopback is left alone. */
39
+ export declare function proxyEnv(port: number, token: string): Record<string, string>;
40
+ /** Hosts named in a command the egress hook let through: what that command starts may connect to them. */
41
+ export declare function noteVisibleHosts(dir: string, session: string, hosts: readonly string[], now?: number): void;
42
+ export declare function isVisibleHost(dir: string, session: string, host: string, now?: number): boolean;
43
+ /** When a shell command started, so the hook that runs after it can ask what connected meanwhile. */
44
+ export declare function noteCommandStart(dir: string, session: string, toolUseId: string, now?: number): void;
45
+ export declare function commandStart(dir: string, session: string, toolUseId: string | undefined): number | undefined;
46
+ export interface ProxyConnection {
47
+ at: string;
48
+ session: string;
49
+ host: string;
50
+ port: number;
51
+ decision: "allow" | "refuse";
52
+ /** why, in a few words a person can read */
53
+ reason: string;
54
+ code: string;
55
+ up?: number;
56
+ down?: number;
57
+ ms?: number;
58
+ flag?: string;
59
+ id: string;
60
+ closed?: boolean;
61
+ }
62
+ /** Connections a session opened (or was refused) since a moment. One entry per connection, with the bytes when it has closed. */
63
+ export declare function connectionsSince(dir: string, session: string, sinceMs: number): ProxyConnection[];
64
+ export interface ProxyPolicy {
65
+ /** "log": what no rule refuses passes and is logged. "strict": only allowlisted, typed and command-named hosts pass. */
66
+ mode: "log" | "strict";
67
+ /** hosts that pass without a question (a leading dot covers subdomains) */
68
+ allowHosts: string[];
69
+ /** hosts that may resolve to this machine or a private network */
70
+ allowPrivate: string[];
71
+ /** ports besides 80 and 443 */
72
+ ports: number[];
73
+ /** a host known only from outside content: refuse, or ask the approver */
74
+ contentHosts: "refuse" | "ask";
75
+ /** bytes sent on one connection, after the session has read outside content, that get the connection flagged */
76
+ uploadFlagBytes: number;
77
+ }
78
+ export declare const DEFAULT_PROXY_POLICY: ProxyPolicy;
79
+ export interface ConnectionDecision {
80
+ decision: "allow" | "refuse" | "ask";
81
+ code: string;
82
+ reason: string;
83
+ }
84
+ /**
85
+ * Decide one connection. Pure: everything it needs is handed in.
86
+ * `addresses` are what the name resolved to (or the literal address); the caller connects to one of exactly those.
87
+ * Without `addresses` only the rules about the name are applied. The proxy asks that way first: a name it is
88
+ * going to refuse is never looked up, because a lookup of `<anything>.their-domain` is itself a message to
89
+ * whoever runs that domain.
90
+ */
91
+ export declare function decideConnection(c: {
92
+ host: string;
93
+ port: number;
94
+ addresses?: readonly string[];
95
+ }, ctx: {
96
+ policy: ProxyPolicy;
97
+ blocklist: Blocklist;
98
+ standing: {
99
+ allowed: boolean;
100
+ typed: boolean;
101
+ fromContent?: string;
102
+ tainted: boolean;
103
+ };
104
+ visible: boolean;
105
+ stopped?: string;
106
+ }): ConnectionDecision;
107
+ export interface EgressProxyOptions {
108
+ dir?: string;
109
+ /** 0 picks a free port (tests) */
110
+ port?: number;
111
+ policy?: Partial<ProxyPolicy>;
112
+ blocklist?: Blocklist;
113
+ /** who answers when a host known only from content is put to a person */
114
+ approver?: Approver;
115
+ /** how long a person has to answer */
116
+ approvalMs?: number;
117
+ resolve?: (host: string) => Promise<string[]>;
118
+ now?: () => number;
119
+ /** leave when nothing has connected for this long (a proxy a hook started on demand) */
120
+ idleExitMs?: number;
121
+ onIdle?: () => void;
122
+ }
123
+ export interface RunningEgressProxy {
124
+ port: number;
125
+ server: Server;
126
+ close(): Promise<void>;
127
+ }
128
+ /** Start the proxy on 127.0.0.1. Resolves once it is listening. */
129
+ export declare function startEgressProxy(o?: EgressProxyOptions): Promise<RunningEgressProxy>;
130
+ /** Options from the environment, shared by `ingress egress-proxy` and the HTTP service. */
131
+ export declare function egressProxyOptionsFromEnv(env?: Record<string, string | undefined>): EgressProxyOptions;
132
+ export declare const egressProxyOn: (env?: Record<string, string | undefined>) => boolean;
133
+ /** Is our proxy (one that holds this state folder's secret) listening on the port? */
134
+ export declare function proxyHealth(port: number, dir?: string, timeoutMs?: number): Promise<"ours" | "other" | "down">;
135
+ /**
136
+ * Make sure the proxy is listening, starting `ingress egress-proxy` as a detached process when it is not.
137
+ * Never throws. "other": something else has the port, and nothing was started.
138
+ */
139
+ export declare function ensureEgressProxy(o?: {
140
+ port?: number;
141
+ dir?: string;
142
+ cli?: string;
143
+ waitMs?: number;
144
+ spawnImpl?: (command: string, args: string[]) => void;
145
+ }): Promise<{
146
+ ok: boolean;
147
+ why?: string;
148
+ }>;
149
+ /**
150
+ * A macOS sandbox profile (the language `sandbox-exec` reads): everything is allowed except the process's own
151
+ * outbound network, which may only reach the proxy.
152
+ * loopback "proxy-only" nothing but the proxy's port
153
+ * loopback "allow" other ports on this machine too (a test suite talking to its own server), except
154
+ * the name-service ports: a resolver listening on this machine would carry data out
155
+ * Name lookups through the system (which is how nearly every program resolves a name) go over a local socket
156
+ * to a system service; "deny network-outbound" covers that socket, so they fail. A program using the proxy
157
+ * does not need them: the proxy resolves. The files that would let a program speak for another session, or
158
+ * use the Ingress service as a relay, cannot be read.
159
+ */
160
+ export declare function sandboxProfile(o: {
161
+ proxyPort: number;
162
+ loopback?: "proxy-only" | "allow";
163
+ denyRead?: string[];
164
+ }): string;
165
+ /** Files a sandboxed program must not read: the token secret, and the keys of the local Ingress service. */
166
+ export declare function sandboxSecrets(dir?: string): string[];
167
+ /** Can this process start a sandbox? Not on other systems, and not from inside another sandbox. */
168
+ export declare function sandboxUsable(): {
169
+ ok: boolean;
170
+ why?: string;
171
+ };
172
+ /**
173
+ * Run a command with its network confined to the proxy. Returns the command's exit status.
174
+ * The command inherits this process's terminal. Its children are confined too: a sandbox cannot be left.
175
+ */
176
+ export declare function runSandboxed(argv: string[], o: {
177
+ proxyPort: number;
178
+ token: string;
179
+ dir?: string;
180
+ loopback?: "proxy-only" | "allow";
181
+ env?: Record<string, string | undefined>;
182
+ }): number;