@capybara-hq/device 0.1.0-rc.3 → 0.1.0-rc.5

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,58 @@
1
+ /**
2
+ * The macOS localhost proxy guard (spec §5.2.3). `dev` lets sandboxed commands reach any port on
3
+ * this machine's localhost, which includes a local proxy that forwards past the network allowlist
4
+ * (Clash and the like) or Docker's TCP API. The device looks for one at start, whenever the
5
+ * policy is reloaded and again before a command once the last result is older than
6
+ * {@link PROXY_GUARD_TTL_MS}; when it finds one, `dev` / `open` run without local binding unless the
7
+ * owner set `localhost: allow`. A check that cannot run on macOS counts as a finding (fail safe).
8
+ */
9
+ /** How long a proxy guard result is used before the next command runs the guard again. */
10
+ export declare const PROXY_GUARD_TTL_MS = 30000;
11
+ /** Common local proxy ports (Clash, V2Ray, Surge, Privoxy, Tor) and Docker's TCP API ports. */
12
+ export declare const PROXY_PORTS: readonly number[];
13
+ export interface ProxyGuardResult {
14
+ detected: boolean;
15
+ /** What was found, in English (for `policy show` and the log). */
16
+ reasons: string[];
17
+ }
18
+ export interface ProxyGuardDeps {
19
+ platform?: NodeJS.Platform;
20
+ /** The program's environment (default: `process.env`). */
21
+ env?: Record<string, string | undefined>;
22
+ /** `scutil --proxy`'s output, or undefined when it cannot run (default: runs it on macOS). */
23
+ scutil?: () => Promise<string | undefined>;
24
+ /** Whether something accepts TCP connections on `host`:`port` (default: a short connect). */
25
+ probe?: (port: number, host: string) => Promise<boolean>;
26
+ ports?: readonly number[];
27
+ }
28
+ /** Whether `host` names this machine's loopback. */
29
+ export declare function isLoopbackHost(host: string): boolean;
30
+ /**
31
+ * The loopback proxies `scutil --proxy` reports as enabled: `HTTPEnable`, `HTTPSEnable`,
32
+ * `SOCKSEnable` set to 1 with their `*Proxy` host on loopback. Returns `"HTTP 127.0.0.1:7890"`
33
+ * style entries.
34
+ */
35
+ export declare function parseScutilProxy(text: string): string[];
36
+ /**
37
+ * `value` with the user and password of a proxy URL (`user:pass@`) replaced by `***@`. The
38
+ * userinfo ends at the last `@` before the host, so a password with an unencoded `@`, `/` or `:`
39
+ * is hidden whole.
40
+ */
41
+ export declare function redactProxyUserinfo(value: string): string;
42
+ /**
43
+ * The proxy variables of `env` (any case) whose host is loopback, as `NAME=value` (credentials in
44
+ * the value redacted: the result is printed and logged).
45
+ */
46
+ export declare function loopbackProxyEnv(env: Record<string, string | undefined>): string[];
47
+ /** The loopback addresses probed: a proxy may listen on either. */
48
+ export declare const PROBE_HOSTS: readonly string[];
49
+ /** Whether something accepts a TCP connection on `host`:`port` within a short time. */
50
+ export declare function probeLoopbackPort(port: number, host?: string, timeoutMs?: number): Promise<boolean>;
51
+ /**
52
+ * Looks for a local forwarding proxy: the system proxy (macOS `scutil --proxy`), loopback proxy
53
+ * variables in the program's environment, and a listener on {@link PROXY_PORTS} of 127.0.0.1 or
54
+ * ::1. A proxy configured only through a PAC file (automatic proxy configuration) is not read.
55
+ * Never throws. On macOS a system proxy setting that cannot be read counts as found (fail safe);
56
+ * a port probe that cannot run finds nothing.
57
+ */
58
+ export declare function detectLocalProxy(deps?: ProxyGuardDeps): Promise<ProxyGuardResult>;
@@ -0,0 +1,137 @@
1
+ import { execFile } from "node:child_process";
2
+ import { connect } from "node:net";
3
+ /**
4
+ * The macOS localhost proxy guard (spec §5.2.3). `dev` lets sandboxed commands reach any port on
5
+ * this machine's localhost, which includes a local proxy that forwards past the network allowlist
6
+ * (Clash and the like) or Docker's TCP API. The device looks for one at start, whenever the
7
+ * policy is reloaded and again before a command once the last result is older than
8
+ * {@link PROXY_GUARD_TTL_MS}; when it finds one, `dev` / `open` run without local binding unless the
9
+ * owner set `localhost: allow`. A check that cannot run on macOS counts as a finding (fail safe).
10
+ */
11
+ /** How long a proxy guard result is used before the next command runs the guard again. */
12
+ export const PROXY_GUARD_TTL_MS = 30_000;
13
+ /** Common local proxy ports (Clash, V2Ray, Surge, Privoxy, Tor) and Docker's TCP API ports. */
14
+ export const PROXY_PORTS = Object.freeze([
15
+ 7890, 7891, 7897, 1080, 1087, 8118, 9050, 9150, 2375, 2376,
16
+ ]);
17
+ /** How long one port probe waits for a connection. */
18
+ const PROBE_TIMEOUT_MS = 150;
19
+ /** The proxy variables of a program's environment, checked in any case. */
20
+ const PROXY_ENV = ["http_proxy", "https_proxy", "all_proxy"];
21
+ /** Whether `host` names this machine's loopback. */
22
+ export function isLoopbackHost(host) {
23
+ const h = host
24
+ .trim()
25
+ .toLowerCase()
26
+ .replace(/^\[|\]$/g, "");
27
+ return h === "localhost" || h === "::1" || h.startsWith("127.") || h === "0.0.0.0";
28
+ }
29
+ /**
30
+ * The loopback proxies `scutil --proxy` reports as enabled: `HTTPEnable`, `HTTPSEnable`,
31
+ * `SOCKSEnable` set to 1 with their `*Proxy` host on loopback. Returns `"HTTP 127.0.0.1:7890"`
32
+ * style entries.
33
+ */
34
+ export function parseScutilProxy(text) {
35
+ const fields = new Map();
36
+ for (const line of text.split("\n")) {
37
+ const m = /^\s*([A-Za-z]+)\s*:\s*(.*?)\s*$/.exec(line);
38
+ if (m !== null)
39
+ fields.set(m[1], m[2]);
40
+ }
41
+ const out = [];
42
+ for (const kind of ["HTTP", "HTTPS", "SOCKS"]) {
43
+ if (fields.get(`${kind}Enable`) !== "1")
44
+ continue;
45
+ const host = fields.get(`${kind}Proxy`);
46
+ if (host === undefined || !isLoopbackHost(host))
47
+ continue;
48
+ const port = fields.get(`${kind}Port`);
49
+ out.push(`${kind} ${host}${port !== undefined ? `:${port}` : ""}`);
50
+ }
51
+ return out;
52
+ }
53
+ /**
54
+ * `value` with the user and password of a proxy URL (`user:pass@`) replaced by `***@`. The
55
+ * userinfo ends at the last `@` before the host, so a password with an unencoded `@`, `/` or `:`
56
+ * is hidden whole.
57
+ */
58
+ export function redactProxyUserinfo(value) {
59
+ const scheme = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.exec(value)?.[0] ?? "";
60
+ const rest = value.slice(scheme.length);
61
+ // the host part never holds an `@`: everything before the last one is userinfo
62
+ const at = rest.lastIndexOf("@");
63
+ return at === -1 ? value : `${scheme}***@${rest.slice(at + 1)}`;
64
+ }
65
+ /**
66
+ * The proxy variables of `env` (any case) whose host is loopback, as `NAME=value` (credentials in
67
+ * the value redacted: the result is printed and logged).
68
+ */
69
+ export function loopbackProxyEnv(env) {
70
+ const out = [];
71
+ for (const [name, value] of Object.entries(env)) {
72
+ if (!PROXY_ENV.includes(name.toLowerCase()) || value === undefined || value === "")
73
+ continue;
74
+ let host;
75
+ try {
76
+ // `127.0.0.1:7890` without a scheme is common too.
77
+ host = new URL(value.includes("://") ? value : `http://${value}`).hostname;
78
+ }
79
+ catch {
80
+ continue;
81
+ }
82
+ if (isLoopbackHost(host))
83
+ out.push(`${name}=${redactProxyUserinfo(value)}`);
84
+ }
85
+ return out;
86
+ }
87
+ function runScutil() {
88
+ return new Promise((resolve) => {
89
+ execFile("/usr/sbin/scutil", ["--proxy"], { timeout: 2_000 }, (e, stdout) => resolve(e === null ? stdout : undefined));
90
+ });
91
+ }
92
+ /** The loopback addresses probed: a proxy may listen on either. */
93
+ export const PROBE_HOSTS = Object.freeze(["127.0.0.1", "::1"]);
94
+ /** Whether something accepts a TCP connection on `host`:`port` within a short time. */
95
+ export function probeLoopbackPort(port, host = "127.0.0.1", timeoutMs = PROBE_TIMEOUT_MS) {
96
+ return new Promise((resolve) => {
97
+ const socket = connect({ host, port });
98
+ const done = (open) => {
99
+ socket.destroy();
100
+ resolve(open);
101
+ };
102
+ socket.setTimeout(timeoutMs, () => done(false));
103
+ socket.once("connect", () => done(true));
104
+ socket.once("error", () => done(false));
105
+ });
106
+ }
107
+ /**
108
+ * Looks for a local forwarding proxy: the system proxy (macOS `scutil --proxy`), loopback proxy
109
+ * variables in the program's environment, and a listener on {@link PROXY_PORTS} of 127.0.0.1 or
110
+ * ::1. A proxy configured only through a PAC file (automatic proxy configuration) is not read.
111
+ * Never throws. On macOS a system proxy setting that cannot be read counts as found (fail safe);
112
+ * a port probe that cannot run finds nothing.
113
+ */
114
+ export async function detectLocalProxy(deps = {}) {
115
+ const platform = deps.platform ?? process.platform;
116
+ const reasons = [];
117
+ if (platform === "darwin") {
118
+ const text = await (deps.scutil ?? runScutil)().catch(() => undefined);
119
+ if (text === undefined)
120
+ reasons.push("the system proxy settings could not be read");
121
+ else
122
+ for (const p of parseScutilProxy(text))
123
+ reasons.push(`system proxy ${p}`);
124
+ }
125
+ for (const v of loopbackProxyEnv(deps.env ?? process.env))
126
+ reasons.push(`environment ${v}`);
127
+ const probe = deps.probe ?? ((port, host) => probeLoopbackPort(port, host));
128
+ const ports = deps.ports ?? PROXY_PORTS;
129
+ const targets = PROBE_HOSTS.flatMap((host) => ports.map((port) => ({ host, port })));
130
+ const open = await Promise.all(targets.map((t) => probe(t.port, t.host).catch(() => false)));
131
+ targets.forEach((t, i) => {
132
+ const where = t.host.includes(":") ? `[${t.host}]` : t.host;
133
+ if (open[i])
134
+ reasons.push(`a listener on ${where}:${t.port}`);
135
+ });
136
+ return { detected: reasons.length > 0, reasons };
137
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Why a `*.` wildcard is too broad to add from the device page: its remainder is a whole public
3
+ * suffix (one label such as `com`, or a known multi-label one such as `co.uk`, `github.io`);
4
+ * null for an exact host or a narrower wildcard.
5
+ */
6
+ export declare function publicSuffixWildcard(pattern: string): string | null;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Public suffixes of more than one label that a device-page wildcard may not cover (a small
3
+ * built-in list, not the public suffix list; the kernel keeps the same list in
4
+ * packages/kernel/src/devices/public-suffix.ts). Includes the shared hosting suffixes where each
5
+ * subdomain belongs to someone else.
6
+ */
7
+ const MULTI_LABEL_SUFFIXES = new Set([
8
+ "ac.uk",
9
+ "co.uk",
10
+ "gov.uk",
11
+ "ltd.uk",
12
+ "me.uk",
13
+ "net.uk",
14
+ "org.uk",
15
+ "plc.uk",
16
+ "com.cn",
17
+ "edu.cn",
18
+ "gov.cn",
19
+ "net.cn",
20
+ "org.cn",
21
+ "com.hk",
22
+ "org.hk",
23
+ "com.tw",
24
+ "org.tw",
25
+ "co.jp",
26
+ "ne.jp",
27
+ "or.jp",
28
+ "ac.jp",
29
+ "co.kr",
30
+ "or.kr",
31
+ "com.au",
32
+ "net.au",
33
+ "org.au",
34
+ "edu.au",
35
+ "co.nz",
36
+ "org.nz",
37
+ "com.br",
38
+ "com.mx",
39
+ "com.sg",
40
+ "com.my",
41
+ "co.in",
42
+ "co.za",
43
+ "com.tr",
44
+ "com.ar",
45
+ "github.io",
46
+ "gitlab.io",
47
+ "pages.dev",
48
+ "workers.dev",
49
+ "vercel.app",
50
+ "netlify.app",
51
+ "herokuapp.com",
52
+ "appspot.com",
53
+ "web.app",
54
+ "firebaseapp.com",
55
+ "azurewebsites.net",
56
+ "cloudfront.net",
57
+ "amazonaws.com",
58
+ "blogspot.com",
59
+ "ngrok.io",
60
+ "ngrok-free.app",
61
+ "trycloudflare.com",
62
+ "onrender.com",
63
+ "fly.dev",
64
+ "glitch.me",
65
+ ]);
66
+ /**
67
+ * Why a `*.` wildcard is too broad to add from the device page: its remainder is a whole public
68
+ * suffix (one label such as `com`, or a known multi-label one such as `co.uk`, `github.io`);
69
+ * null for an exact host or a narrower wildcard.
70
+ */
71
+ export function publicSuffixWildcard(pattern) {
72
+ if (!pattern.startsWith("*."))
73
+ return null;
74
+ const rest = pattern.slice(2).toLowerCase();
75
+ if (!rest.includes(".") || MULTI_LABEL_SUFFIXES.has(rest)) {
76
+ return `Use a narrower domain; ${pattern.toLowerCase()} covers a whole public suffix.`;
77
+ }
78
+ return null;
79
+ }
@@ -1,10 +1,68 @@
1
- import type { DeviceRes, KernelReq } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceLocalPolicySummary, type DeviceRes, type KernelReq } from "@capybara-hq/plugin-sdk";
2
2
  import type { CommandLogEntry } from "./command-log.js";
3
- import { type Executor } from "./exec/types.js";
4
- /** The local-log line for a finished request. */
5
- export declare function logEntryFor(req: KernelReq, res: DeviceRes, now: Date): CommandLogEntry;
3
+ import { type ExecIsolation, type Executor } from "./exec/types.js";
4
+ import { type TierLimits } from "./policy.js";
5
+ import type { PolicyStore } from "./policy-store.js";
6
+ import { type Policy } from "./state.js";
7
+ /** What this program has seen across requests (one per program run, kept over reconnects). */
8
+ export interface SeenState {
9
+ /** The tier limits of the latest exec: the org's ceiling and default, for the summary. */
10
+ limits?: TierLimits;
11
+ }
12
+ /** What a request may need beyond the executor. */
13
+ export interface OpContext {
14
+ /**
15
+ * The local policy this program serves (the one the executor reads). Without it the device
16
+ * answers the `policy` op as unsupported (and does not announce `policyOp` in its hello).
17
+ */
18
+ policy?: PolicyStore;
19
+ /** Updated by every exec; read by the policy op's summary. */
20
+ seen?: SeenState;
21
+ /** The platform the summary describes (default: this process's). */
22
+ platform?: NodeJS.Platform;
23
+ }
24
+ /** The refusal of a `policy` op adding hosts under `remoteGrants: "off"`. */
25
+ export declare const REMOTE_GRANTS_OFF_MESSAGE: string;
26
+ /** The refusal of a `policy` op raising the tier under `remoteGrants: "off"`. */
27
+ export declare const REMOTE_TIER_OFF_MESSAGE: string;
6
28
  /**
7
- * Runs one request on the executor and returns the answer. A vanished device directory
8
- * answers `fs_gone` for every operation except `stop`. Never throws.
29
+ * The refusal of a `policy` op that tries to turn the sandbox off: whatever `remoteGrants` says,
30
+ * only the person on the machine does that (spec §5.4).
9
31
  */
10
- export declare function runOp(executor: Executor, req: KernelReq, signal: AbortSignal): Promise<DeviceRes>;
32
+ export declare const ISOLATION_REMOTE_MESSAGE: string;
33
+ /**
34
+ * The refusal of a widening `policy` op in Docker mode: the container has either no network or the
35
+ * whole internet, so one allowed domain would open everything.
36
+ */
37
+ export declare const DOCKER_WIDENING_MESSAGE: string;
38
+ /** The local-log line for a finished request; `detail` is its audit line, `run` how an exec ran. */
39
+ export declare function logEntryFor(req: KernelReq, res: DeviceRes, now: Date, detail?: string, run?: Pick<ExecIsolation, "tier" | "isolation">): CommandLogEntry;
40
+ /** What the summary describes besides the policy file. */
41
+ export interface SummaryFacts {
42
+ mode: Executor["mode"];
43
+ /** The latest exec's tier limits; undefined before the first exec. */
44
+ limits?: TierLimits | undefined;
45
+ /** The localhost proxy guard found a local forwarding proxy (OS mode). */
46
+ proxyDetected?: boolean;
47
+ platform?: NodeJS.Platform;
48
+ }
49
+ /**
50
+ * The summary the kernel keeps of a local policy (hello, `policy` op result): the owner's tier,
51
+ * what it gives on this machine with the latest ceiling seen ({@link tierFacts}), and the
52
+ * isolation. Docker mode always reports `sandbox` (it ignores `isolation`).
53
+ */
54
+ export declare function policySummary(p: Policy, facts: SummaryFacts): DeviceLocalPolicySummary;
55
+ /** The summary facts of a request context. */
56
+ export declare function summaryFacts(executor: Executor, ctx: OpContext): SummaryFacts;
57
+ /**
58
+ * Runs one request and returns the answer plus its local audit line and, for an exec, its tier
59
+ * and isolation (for the local command log). A vanished device
60
+ * directory answers `fs_gone` for every operation except `stop` and `policy`. Never throws.
61
+ */
62
+ export declare function serveOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<{
63
+ res: DeviceRes;
64
+ detail?: string;
65
+ run?: ExecIsolation;
66
+ }>;
67
+ /** {@link serveOp} without the audit line. */
68
+ export declare function runOp(executor: Executor, req: KernelReq, signal: AbortSignal, ctx?: OpContext): Promise<DeviceRes>;