@descryy/runtime-controller 0.3.8 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/attach-fencing.d.ts +109 -0
  2. package/dist/attach-fencing.d.ts.map +1 -0
  3. package/dist/attach-fencing.js +215 -0
  4. package/dist/attach-fencing.js.map +1 -0
  5. package/dist/capability-registry.d.ts +9 -0
  6. package/dist/capability-registry.d.ts.map +1 -0
  7. package/dist/capability-registry.js +32 -0
  8. package/dist/capability-registry.js.map +1 -0
  9. package/dist/collector-version.d.ts +3 -0
  10. package/dist/collector-version.d.ts.map +1 -0
  11. package/dist/collector-version.js +5 -0
  12. package/dist/collector-version.js.map +1 -0
  13. package/dist/container-sandbox.d.ts +104 -0
  14. package/dist/container-sandbox.d.ts.map +1 -0
  15. package/dist/container-sandbox.js +152 -0
  16. package/dist/container-sandbox.js.map +1 -0
  17. package/dist/controller.d.ts +138 -0
  18. package/dist/controller.d.ts.map +1 -0
  19. package/dist/controller.js +449 -0
  20. package/dist/controller.js.map +1 -0
  21. package/dist/dependency-version-check.d.ts +36 -0
  22. package/dist/dependency-version-check.d.ts.map +1 -0
  23. package/dist/dependency-version-check.js +72 -0
  24. package/dist/dependency-version-check.js.map +1 -0
  25. package/dist/env.d.ts +10 -0
  26. package/dist/env.d.ts.map +1 -0
  27. package/dist/env.js +12 -0
  28. package/dist/env.js.map +1 -0
  29. package/dist/environment-metadata.d.ts +15 -0
  30. package/dist/environment-metadata.d.ts.map +1 -0
  31. package/dist/environment-metadata.js +63 -0
  32. package/dist/environment-metadata.js.map +1 -0
  33. package/dist/environment-version-check.d.ts +40 -0
  34. package/dist/environment-version-check.d.ts.map +1 -0
  35. package/dist/environment-version-check.js +176 -0
  36. package/dist/environment-version-check.js.map +1 -0
  37. package/dist/execution-safety.d.ts +96 -0
  38. package/dist/execution-safety.d.ts.map +1 -0
  39. package/dist/execution-safety.js +140 -0
  40. package/dist/execution-safety.js.map +1 -0
  41. package/dist/index.d.ts +31 -0
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/index.js +17 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/orchestration.d.ts +55 -0
  46. package/dist/orchestration.d.ts.map +1 -0
  47. package/dist/orchestration.js +219 -0
  48. package/dist/orchestration.js.map +1 -0
  49. package/dist/preflight.d.ts +122 -0
  50. package/dist/preflight.d.ts.map +1 -0
  51. package/dist/preflight.js +177 -0
  52. package/dist/preflight.js.map +1 -0
  53. package/dist/process-collector.d.ts +20 -0
  54. package/dist/process-collector.d.ts.map +1 -0
  55. package/dist/process-collector.js +116 -0
  56. package/dist/process-collector.js.map +1 -0
  57. package/dist/process-identity.d.ts +46 -0
  58. package/dist/process-identity.d.ts.map +1 -0
  59. package/dist/process-identity.js +186 -0
  60. package/dist/process-identity.js.map +1 -0
  61. package/dist/process-manager.d.ts +137 -0
  62. package/dist/process-manager.d.ts.map +1 -0
  63. package/dist/process-manager.js +365 -0
  64. package/dist/process-manager.js.map +1 -0
  65. package/dist/readiness.d.ts +122 -0
  66. package/dist/readiness.d.ts.map +1 -0
  67. package/dist/readiness.js +214 -0
  68. package/dist/readiness.js.map +1 -0
  69. package/dist/sandbox.d.ts +94 -0
  70. package/dist/sandbox.d.ts.map +1 -0
  71. package/dist/sandbox.js +228 -0
  72. package/dist/sandbox.js.map +1 -0
  73. package/package.json +1 -1
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Readiness (§6): "readiness must not equal 'process exists.'" Mechanisms: HTTP
3
+ * check, TCP/port check, log pattern, subprocess command, or a caller hook
4
+ * (consolidates the plan's "framework readiness hook" and "user-defined readiness"
5
+ * into one predicate shape).
6
+ *
7
+ * **`command` is not `custom-hook` (RT-193).** `custom-hook` runs a caller's
8
+ * in-process predicate; `command` runs a real subprocess and reads its exit code --
9
+ * built once so a caller with a real CLI health check (`pg_isready`) doesn't have to
10
+ * shell out from inside a hand-written hook.
11
+ *
12
+ * **What `ready: true` does not claim (RT-024).** All mechanisms answer "is
13
+ * something listening/responding," none confirm it's the process *this* spawn
14
+ * produced -- a stale listener from an already-dead run satisfies `http`/`tcp-port`
15
+ * identically. `log-pattern` only carries the stronger this-run guarantee if `read`
16
+ * is wired to this execution's own `readOutput()` (caller discipline, not enforced
17
+ * by the type). An ephemeral port closes this gap by construction; a fixed,
18
+ * guessable port doesn't. Found via a real 30s collector timeout that looked like a
19
+ * Playwright bug and was actually a wait on an orphaned process from a dead session
20
+ * (RT-024).
21
+ *
22
+ * **A single probe attempt cannot outlive `timeoutMs` (RT-030).** `http`/`tcp-port`
23
+ * bind I/O to the remaining time until `deadline`, not a fresh per-attempt budget --
24
+ * measured: an unbound `fetch` here let `awaitReadiness` run 8s+ past a 3s budget.
25
+ * `command` gets the same treatment via `execFile`'s `timeout`. `custom-hook` is not
26
+ * wrapped this way -- a caller predicate owns its own timeout, same as every other
27
+ * `Collector` callback contract here.
28
+ */
29
+ import { createConnection } from "node:net";
30
+ import { execFile } from "node:child_process";
31
+ import { verifyListeningSocketOwner } from "./process-identity.js";
32
+ export const READINESS_MECHANISMS = ["http", "tcp-port", "log-pattern", "command", "custom-hook"];
33
+ /**
34
+ * How strongly a successful readiness result establishes that the answering
35
+ * process is THIS run's own -- RT-024. `"verified"`: a real kernel-state
36
+ * check (`process-identity.ts`) or a mechanism that is this-run-bound by
37
+ * construction (a directly-executed `command`, or `log-pattern` reading a
38
+ * branded `ProcessOutputReader`) confirmed it. `"unverified"`: the mechanism
39
+ * succeeded but nothing confirmed identity -- disclosed, not hidden.
40
+ * `"not-applicable"`: nothing succeeded, so no identity claim is being made.
41
+ */
42
+ export const READINESS_IDENTITY_LEVELS = ["verified", "unverified", "not-applicable"];
43
+ // Unexported on purpose: a real, module-private `unique symbol` (TS infers
44
+ // that type for a `const` initialised with `Symbol()`) that only this module
45
+ // can name. Nothing outside `readiness.ts` can construct a
46
+ // structurally-compatible value even though TS is structurally typed
47
+ // elsewhere -- the brand is the enforcement. See `ProcessOutputReader` below.
48
+ const PROCESS_OUTPUT_READER_BRAND = Symbol("ProcessOutputReader");
49
+ /** The only way to mint a `ProcessOutputReader` -- wrap the real output source this execution owns (`ManagedProcess.readOutput`, or an equivalent). */
50
+ export function createProcessOutputReader(readOutput) {
51
+ return { [PROCESS_OUTPUT_READER_BRAND]: true, read: readOutput };
52
+ }
53
+ const DEFAULT_POLL_INTERVAL_MS = 200;
54
+ export async function awaitReadiness(checks, options) {
55
+ const startedAt = Date.now();
56
+ const deadline = startedAt + options.timeoutMs;
57
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
58
+ if (checks.length === 0) {
59
+ return { ready: false, mechanism: null, elapsedMs: 0, reason: "no readiness checks configured", identity: "not-applicable" };
60
+ }
61
+ // C-F4: last real diagnostic any probe captured before giving up (chiefly
62
+ // `command`'s stderr/exit code -- http/tcp-port have nothing richer than
63
+ // "connection refused"). Kept as "last seen", most likely to explain the timeout.
64
+ let lastDetail = null;
65
+ do {
66
+ for (const check of checks) {
67
+ const result = await probe(check, deadline);
68
+ if (result.ok) {
69
+ return { ready: true, mechanism: check.kind, elapsedMs: Date.now() - startedAt, reason: null, identity: result.identity };
70
+ }
71
+ if (result.detail !== null)
72
+ lastDetail = `${check.kind}: ${result.detail}`;
73
+ }
74
+ await sleep(pollIntervalMs);
75
+ } while (Date.now() < deadline);
76
+ // Names what was actually probed, not just that nothing answered -- the only
77
+ // cheap mitigation for the ephemeral-port race in `allocateEphemeralPort`
78
+ // (bind 0, read, close, spawn): if another process grabs the port first, the
79
+ // child never comes up and this message is the only symptom. Naming the exact
80
+ // address probed sends the reader to the port, not the application.
81
+ return {
82
+ ready: false,
83
+ mechanism: null,
84
+ elapsedMs: Date.now() - startedAt,
85
+ // "timeout" stays in the wording deliberately -- §41's hung-process test
86
+ // matches on that word.
87
+ reason: `no readiness mechanism succeeded within the ${options.timeoutMs}ms timeout — probed ${checks.map(describeCheck).join(", ")}` +
88
+ (lastDetail !== null ? `; last observed failure — ${lastDetail}` : ""),
89
+ identity: "not-applicable",
90
+ };
91
+ }
92
+ function describeCheck(check) {
93
+ switch (check.kind) {
94
+ case "http":
95
+ return check.url;
96
+ case "tcp-port":
97
+ return `tcp ${check.host}:${check.port}`;
98
+ case "log-pattern":
99
+ return `log pattern ${String(check.pattern)}`;
100
+ case "command":
101
+ return `command ${[check.command, ...(check.args ?? [])].join(" ")}`;
102
+ case "custom-hook":
103
+ return "custom hook";
104
+ }
105
+ }
106
+ function ok(identity = "not-applicable") {
107
+ return { ok: true, detail: null, identity };
108
+ }
109
+ function notReady(detail = null) {
110
+ return { ok: false, detail, identity: "not-applicable" };
111
+ }
112
+ /**
113
+ * Applies RT-024's identity check to a successful TCP-level connection
114
+ * (shared by `http` and `tcp-port`, which are both "something answered on
115
+ * this host:port"). No `expectedPid` supplied: succeeds, disclosed as
116
+ * `"unverified"` -- the caller gave this module nothing to check against, so
117
+ * it makes no claim either way rather than a silent pass reading as a
118
+ * guarantee. `expectedPid` supplied: only a real, kernel-confirmed
119
+ * `"verified"` is accepted as ready; `"mismatch"` is refused outright — a
120
+ * connection accepted by someone else's listener is not this run being
121
+ * ready; `"unsupported"` (non-Linux, or the pid can't be inspected) degrades
122
+ * to `"unverified"` rather than blocking a run this module simply cannot
123
+ * check on this platform.
124
+ */
125
+ function identityCheckedConnection(port, expectedPid) {
126
+ if (expectedPid === undefined)
127
+ return ok("unverified");
128
+ const verification = verifyListeningSocketOwner(port, expectedPid);
129
+ if (verification === "verified")
130
+ return ok("verified");
131
+ if (verification === "unsupported")
132
+ return ok("unverified");
133
+ return notReady(`connected, but the listening socket on port ${String(port)} is not owned by pid ${String(expectedPid)} ` +
134
+ "(process-identity check via /proc) -- likely a stale listener from a different process, not this run's own");
135
+ }
136
+ async function probe(check, deadline) {
137
+ switch (check.kind) {
138
+ case "http":
139
+ return probeHttp(check, deadline);
140
+ case "tcp-port":
141
+ return probeTcpPort(check, deadline);
142
+ case "log-pattern":
143
+ // `read` is a branded ProcessOutputReader -- sourced from this
144
+ // execution's own output by construction, so a match is `"verified"`.
145
+ return check.pattern.test(check.read.read()) ? ok("verified") : notReady();
146
+ case "command":
147
+ return probeCommand(check, deadline);
148
+ case "custom-hook":
149
+ // An arbitrary caller predicate -- this module has no way to know
150
+ // whether it actually checks this run's own process, so it never
151
+ // claims more than "unverified" for a caller that passes.
152
+ return (await check.check()) ? ok("unverified") : notReady();
153
+ }
154
+ }
155
+ async function probeHttp(check, deadline) {
156
+ try {
157
+ const response = await fetch(check.url, { signal: AbortSignal.timeout(Math.max(0, deadline - Date.now())) });
158
+ if (response.status !== (check.expectedStatus ?? 200)) {
159
+ return notReady(`responded with status ${String(response.status)}, expected ${String(check.expectedStatus ?? 200)}`);
160
+ }
161
+ const url = new URL(check.url);
162
+ const port = url.port !== "" ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
163
+ return identityCheckedConnection(port, check.expectedPid);
164
+ }
165
+ catch (error) {
166
+ return notReady(error instanceof Error ? error.message : String(error));
167
+ }
168
+ }
169
+ function probeTcpPort(check, deadline) {
170
+ return new Promise((resolve) => {
171
+ const socket = createConnection({ host: check.host, port: check.port });
172
+ socket.setTimeout(Math.max(0, deadline - Date.now()));
173
+ const finish = (result) => {
174
+ socket.destroy();
175
+ resolve(result);
176
+ };
177
+ socket.once("connect", () => finish(identityCheckedConnection(check.port, check.expectedPid)));
178
+ socket.once("error", (error) => finish(notReady(error.message)));
179
+ socket.once("timeout", () => finish(notReady("connection attempt timed out")));
180
+ });
181
+ }
182
+ /**
183
+ * Ready when `check.command` exits 0 within the remaining time until `deadline`
184
+ * (RT-030). Non-zero exit, spawn failure, and timeout kill are all "not ready yet" --
185
+ * same as every other mechanism's `false`.
186
+ *
187
+ * C-F4: stdout/stderr are the actual health-check output, the richest diagnostic
188
+ * available here. Preferring stderr, then stdout, then the bare error message
189
+ * mirrors `runAttacher`'s ordering in `attach-to-running-jvm-process.ts`.
190
+ */
191
+ function probeCommand(check, deadline) {
192
+ return new Promise((resolve) => {
193
+ const remainingMs = Math.max(0, deadline - Date.now());
194
+ if (remainingMs === 0) {
195
+ resolve(notReady("no time remaining before the readiness deadline"));
196
+ return;
197
+ }
198
+ execFile(check.command, check.args ?? [], { cwd: check.cwd, timeout: remainingMs }, (error, stdout, stderr) => {
199
+ if (error === null) {
200
+ // A directly `execFile`d subprocess is this-run-bound by
201
+ // construction -- there is no "which process answered" ambiguity
202
+ // the way a network probe has.
203
+ resolve(ok("verified"));
204
+ return;
205
+ }
206
+ const detail = stderr.trim() || stdout.trim() || error.message;
207
+ resolve(notReady(detail));
208
+ });
209
+ });
210
+ }
211
+ function sleep(ms) {
212
+ return new Promise((resolve) => setTimeout(resolve, ms));
213
+ }
214
+ //# sourceMappingURL=readiness.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readiness.js","sourceRoot":"","sources":["../src/readiness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAEnE,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,UAAU,EAAE,aAAa,EAAE,SAAS,EAAE,aAAa,CAAU,CAAC;AAG3G;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,UAAU,EAAE,YAAY,EAAE,gBAAgB,CAAU,CAAC;AA2B/F,2EAA2E;AAC3E,6EAA6E;AAC7E,2DAA2D;AAC3D,qEAAqE;AACrE,8EAA8E;AAC9E,MAAM,2BAA2B,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAkBlE,uJAAuJ;AACvJ,MAAM,UAAU,yBAAyB,CAAC,UAAwB;IAChE,OAAO,EAAE,CAAC,2BAA2B,CAAC,EAAE,IAAI,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,OAAO;QACT,CAAC;QACD,QAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE;YAC5G,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;gBACnB,yDAAyD;gBACzD,iEAAiE;gBACjE,+BAA+B;gBAC/B,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;gBACxB,OAAO;YACT,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,EAAE,IAAI,MAAM,CAAC,IAAI,EAAE,IAAI,KAAK,CAAC,OAAO,CAAC;YAC/D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;QAC5B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC"}
@@ -0,0 +1,94 @@
1
+ /**
2
+ * §21's execution boundary, real isolation half. RT-070/RT-193 gave this runtime a
3
+ * *named* boundary (trusted-local, resource limits, privilege reporting) but not an
4
+ * *isolating* one -- nothing stopped a spawned process from reading any file, or
5
+ * reaching any host, the invoking user could. This module closes that gap for real,
6
+ * on Linux, for processes this runtime SPAWNS.
7
+ *
8
+ * **Architectural constraint this module cannot solve around:** isolation can only
9
+ * wrap a process Descry itself launches. Attach-mode reaches a process already
10
+ * running, unconfined, before Descry touched it -- there is no honest way to
11
+ * retroactively contain it (ptrace-based interception was investigated and rejected
12
+ * elsewhere as not honestly generalizable). Attach-mode stays permanently and
13
+ * explicitly unsandboxed -- `SANDBOX_BOUNDARY_DISCLOSURE` in `execution-safety.ts`
14
+ * discloses this in-product; this module does not and structurally cannot change it.
15
+ *
16
+ * **Mechanism: bubblewrap (bwrap), not raw `unshare`/`clone`.** bwrap is the
17
+ * unprivileged sandboxing helper behind Flatpak -- small, auditable, actively
18
+ * maintained, not a bespoke native module this repo builds per-platform. Runs
19
+ * setuid-free on any kernel with unprivileged user namespaces enabled (checked
20
+ * below, never assumed) and gives one process a new mount namespace (real
21
+ * filesystem visibility control) and network namespace (real network denial) in one
22
+ * exec. Composes with `applyResourceLimits`'s `prlimit` wrap and with
23
+ * `process-manager.ts`'s process-group kill -- verified directly: bwrap does not
24
+ * create a new process group unless asked, so the existing group-kill reaches it
25
+ * unchanged. The one dependency this buys: `bwrap` must be on PATH, reported as a
26
+ * capability exactly like `prlimit` -- refused, never silently unconstrained, when
27
+ * requested and absent.
28
+ *
29
+ * **NOT attempted, deliberately: a native macOS or Windows sandbox.** `sandbox-exec`/
30
+ * Seatbelt is deprecated with no public API replacement; the Endpoint Security
31
+ * Framework needs an Apple entitlement this project doesn't have; Windows Job
32
+ * Objects + AppContainer + WFP would be a second and third bespoke native sandbox.
33
+ * This is an explicit decision not to build native sandboxes for those platforms at
34
+ * all -- `../container-sandbox.ts` closes the gap instead, routing macOS/Windows
35
+ * through a real Docker container that reuses this module's proven Linux mechanism
36
+ * (see that module's doc for what's real-tested there vs unverified on real
37
+ * hardware). `filesystemIsolationCapability`/`networkIsolationCapability` below
38
+ * still report `unavailable` with a reason on non-Linux -- never silently claimed
39
+ * as covered.
40
+ */
41
+ import type { CapabilityStatus, FilesystemPolicy, NetworkPolicy } from "@descryy/runtime-contracts";
42
+ /** Real capability check, same shape as `resourceLimitCapability`: PATH existence first, then the Linux-specific precondition existence alone doesn't prove -- unprivileged user namespaces actually usable, not just bwrap installed. */
43
+ export declare function filesystemIsolationCapability(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): CapabilityStatus;
44
+ /** Same underlying mechanism as `filesystemIsolationCapability` (one bwrap namespace set covers both) -- delegates rather than duplicating. Kept as its own function because the two policies are declared and reasoned about independently. */
45
+ export declare function networkIsolationCapability(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): CapabilityStatus;
46
+ /**
47
+ * `NetworkPolicy`'s general shape (arbitrary allow/deny host lists) is not what
48
+ * this mechanism enforces -- only full denial. Returns the reason a policy can't be
49
+ * applied, or `null` if it's the one shape that can. Checked independently of
50
+ * `networkIsolationCapability`: "nothing here can enforce any policy" and "this
51
+ * specific policy asks for something not built yet" are different claims.
52
+ */
53
+ export declare function unsupportedNetworkPolicyReason(policy: NetworkPolicy): string | null;
54
+ /**
55
+ * Resolves the real, symlink-followed directory containing the executable
56
+ * `command` would run as -- the one extra host path a sandboxed process needs
57
+ * beyond standard OS dirs and whatever the caller declared. Computed generically,
58
+ * not per-language: an interpreter installed outside `/usr` (nvm, rbenv, pyenv,
59
+ * sdkman) would otherwise be invisible inside the sandbox regardless of language.
60
+ * Returns `null` when unresolvable -- the caller proceeds without an extra bind;
61
+ * the exec fails inside the sandbox the same honest way it would outside one.
62
+ */
63
+ export declare function resolveExecutableDirectory(command: string, cwd: string, env: NodeJS.ProcessEnv): string | null;
64
+ export interface SandboxOptions {
65
+ /** Original, un-resource-limit-wrapped command (e.g. "node") -- used only to resolve which extra directory the interpreter needs bound in. */
66
+ readonly interpreterCommand: string;
67
+ /** Command to actually exec inside the sandbox -- already passed through `applyResourceLimits`, so may be "prlimit" with the real command in `args`. */
68
+ readonly command: string;
69
+ readonly args: readonly string[];
70
+ readonly cwd: string;
71
+ readonly filesystemPolicy?: FilesystemPolicy;
72
+ readonly networkPolicy?: NetworkPolicy;
73
+ readonly env?: NodeJS.ProcessEnv;
74
+ readonly platform?: NodeJS.Platform;
75
+ }
76
+ /**
77
+ * Wraps `command`/`args` with `bwrap` so the OS enforces `filesystemPolicy`/
78
+ * `networkPolicy`. Neither declared returns them unchanged -- same non-regression
79
+ * contract as `applyResourceLimits`.
80
+ *
81
+ * **Throws rather than silently spawning unconstrained** when a policy is
82
+ * requested and the real mechanism can't back it -- no mechanism on this platform,
83
+ * or a declared shape this mechanism doesn't implement.
84
+ *
85
+ * Composes with `applyResourceLimits` by wrapping *outside* it (`bwrap … --
86
+ * prlimit … -- realCommand`) -- the mount namespace must exist before `prlimit` or
87
+ * the real command run inside it; `prlimit` (in `/usr/bin`) is reachable through
88
+ * the same base OS binding every sandboxed process gets.
89
+ */
90
+ export declare function applySandbox(options: SandboxOptions): {
91
+ readonly command: string;
92
+ readonly args: readonly string[];
93
+ };
94
+ //# sourceMappingURL=sandbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAKH,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAkCpG,0OAA0O;AAC1O,wBAAgB,6BAA6B,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,EAAE,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,gBAAgB,CAoBlJ;AAED,gPAAgP;AAChP,wBAAgB,0BAA0B,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,EAAE,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,gBAAgB,CAE/I;AAED;;;;;;GAMG;AACH,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM,GAAG,IAAI,CAOnF;AAOD;;;;;;;;GAQG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,MAAM,GAAG,IAAI,CAwB9G;AAED,MAAM,WAAW,cAAc;IAC7B,8IAA8I;IAC9I,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,wJAAwJ;IACxJ,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IACjC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;IAC7C,QAAQ,CAAC,aAAa,CAAC,EAAE,aAAa,CAAC;IACvC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACjC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;CACrC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,cAAc,GAAG;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAkFpH"}
@@ -0,0 +1,228 @@
1
+ /**
2
+ * §21's execution boundary, real isolation half. RT-070/RT-193 gave this runtime a
3
+ * *named* boundary (trusted-local, resource limits, privilege reporting) but not an
4
+ * *isolating* one -- nothing stopped a spawned process from reading any file, or
5
+ * reaching any host, the invoking user could. This module closes that gap for real,
6
+ * on Linux, for processes this runtime SPAWNS.
7
+ *
8
+ * **Architectural constraint this module cannot solve around:** isolation can only
9
+ * wrap a process Descry itself launches. Attach-mode reaches a process already
10
+ * running, unconfined, before Descry touched it -- there is no honest way to
11
+ * retroactively contain it (ptrace-based interception was investigated and rejected
12
+ * elsewhere as not honestly generalizable). Attach-mode stays permanently and
13
+ * explicitly unsandboxed -- `SANDBOX_BOUNDARY_DISCLOSURE` in `execution-safety.ts`
14
+ * discloses this in-product; this module does not and structurally cannot change it.
15
+ *
16
+ * **Mechanism: bubblewrap (bwrap), not raw `unshare`/`clone`.** bwrap is the
17
+ * unprivileged sandboxing helper behind Flatpak -- small, auditable, actively
18
+ * maintained, not a bespoke native module this repo builds per-platform. Runs
19
+ * setuid-free on any kernel with unprivileged user namespaces enabled (checked
20
+ * below, never assumed) and gives one process a new mount namespace (real
21
+ * filesystem visibility control) and network namespace (real network denial) in one
22
+ * exec. Composes with `applyResourceLimits`'s `prlimit` wrap and with
23
+ * `process-manager.ts`'s process-group kill -- verified directly: bwrap does not
24
+ * create a new process group unless asked, so the existing group-kill reaches it
25
+ * unchanged. The one dependency this buys: `bwrap` must be on PATH, reported as a
26
+ * capability exactly like `prlimit` -- refused, never silently unconstrained, when
27
+ * requested and absent.
28
+ *
29
+ * **NOT attempted, deliberately: a native macOS or Windows sandbox.** `sandbox-exec`/
30
+ * Seatbelt is deprecated with no public API replacement; the Endpoint Security
31
+ * Framework needs an Apple entitlement this project doesn't have; Windows Job
32
+ * Objects + AppContainer + WFP would be a second and third bespoke native sandbox.
33
+ * This is an explicit decision not to build native sandboxes for those platforms at
34
+ * all -- `../container-sandbox.ts` closes the gap instead, routing macOS/Windows
35
+ * through a real Docker container that reuses this module's proven Linux mechanism
36
+ * (see that module's doc for what's real-tested there vs unverified on real
37
+ * hardware). `filesystemIsolationCapability`/`networkIsolationCapability` below
38
+ * still report `unavailable` with a reason on non-Linux -- never silently claimed
39
+ * as covered.
40
+ */
41
+ import { execFileSync } from "node:child_process";
42
+ import { accessSync, constants as fsConstants, readFileSync, realpathSync } from "node:fs";
43
+ import { dirname, isAbsolute, join, relative } from "node:path";
44
+ /**
45
+ * Whether unprivileged user namespaces -- the kernel feature bwrap needs to build a
46
+ * mount/network namespace without running setuid-root -- are actually enabled on
47
+ * this host, never merely assumed from "the kernel supports namespaces in general."
48
+ * Two independent sysctls can each disable it. IMPORTANT: a sysctl file not existing
49
+ * is NOT evidence it's unrestricted -- only Debian/Ubuntu-derived kernels gate it
50
+ * through `unprivileged_userns_clone` at all, so a missing file proves nothing
51
+ * either way. We can't tell from absence, so we don't read it as a positive signal:
52
+ * `ok: true` here means "neither sysctl was found to explicitly disable it," not
53
+ * "isolation is confirmed available" -- it only rules out these two specific,
54
+ * explicit-disable signals.
55
+ */
56
+ function unprivilegedUserNamespaceStatus() {
57
+ try {
58
+ const clone = readFileSync("/proc/sys/kernel/unprivileged_userns_clone", "utf8").trim();
59
+ if (clone === "0") {
60
+ return { ok: false, reason: "kernel.unprivileged_userns_clone=0 -- unprivileged user namespaces are disabled on this host" };
61
+ }
62
+ }
63
+ catch {
64
+ // Sysctl absent -- not evidence either way, not just non-Debian kernels.
65
+ }
66
+ try {
67
+ const max = readFileSync("/proc/sys/user/max_user_namespaces", "utf8").trim();
68
+ if (max === "0") {
69
+ return { ok: false, reason: "user.max_user_namespaces=0 -- unprivileged user namespaces are disabled on this host" };
70
+ }
71
+ }
72
+ catch {
73
+ // Same reasoning: absent is not evidence of a restriction.
74
+ }
75
+ return { ok: true, reason: null };
76
+ }
77
+ /** Real capability check, same shape as `resourceLimitCapability`: PATH existence first, then the Linux-specific precondition existence alone doesn't prove -- unprivileged user namespaces actually usable, not just bwrap installed. */
78
+ export function filesystemIsolationCapability(env = process.env, platform = process.platform) {
79
+ if (platform !== "linux") {
80
+ return {
81
+ availability: "unavailable",
82
+ reason: `no filesystem isolation mechanism is wired up on "${platform}" for bwrap -- by design, not by omission (native sandbox-exec/Seatbelt and Job Objects/AppContainer were researched and rejected); see container-sandbox.ts, which routes "${platform}" through a real Docker container instead`,
83
+ };
84
+ }
85
+ try {
86
+ execFileSync("bwrap", ["--version"], { env, stdio: "ignore" });
87
+ }
88
+ catch {
89
+ return {
90
+ availability: "unavailable",
91
+ reason: "bubblewrap (bwrap) is not on PATH -- filesystem isolation cannot be enforced without it",
92
+ };
93
+ }
94
+ const userns = unprivilegedUserNamespaceStatus();
95
+ if (!userns.ok) {
96
+ return { availability: "unavailable", reason: `bubblewrap is installed but unprivileged user namespaces are unavailable: ${userns.reason}` };
97
+ }
98
+ return { availability: "available", reason: null };
99
+ }
100
+ /** Same underlying mechanism as `filesystemIsolationCapability` (one bwrap namespace set covers both) -- delegates rather than duplicating. Kept as its own function because the two policies are declared and reasoned about independently. */
101
+ export function networkIsolationCapability(env = process.env, platform = process.platform) {
102
+ return filesystemIsolationCapability(env, platform);
103
+ }
104
+ /**
105
+ * `NetworkPolicy`'s general shape (arbitrary allow/deny host lists) is not what
106
+ * this mechanism enforces -- only full denial. Returns the reason a policy can't be
107
+ * applied, or `null` if it's the one shape that can. Checked independently of
108
+ * `networkIsolationCapability`: "nothing here can enforce any policy" and "this
109
+ * specific policy asks for something not built yet" are different claims.
110
+ */
111
+ export function unsupportedNetworkPolicyReason(policy) {
112
+ if (policy.mode === "allow" && policy.hosts.length === 0)
113
+ return null;
114
+ return ('only full network denial ({ mode: "allow", hosts: [] }) is enforced -- selective allow- or deny-listing of ' +
115
+ "specific hosts needs DNS interception and IP filtering inside the sandbox's network namespace (a veth pair, " +
116
+ "NAT, iptables/nftables rules), not built in this iteration");
117
+ }
118
+ function isWithin(root, target) {
119
+ const rel = relative(root, target);
120
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
121
+ }
122
+ /**
123
+ * Resolves the real, symlink-followed directory containing the executable
124
+ * `command` would run as -- the one extra host path a sandboxed process needs
125
+ * beyond standard OS dirs and whatever the caller declared. Computed generically,
126
+ * not per-language: an interpreter installed outside `/usr` (nvm, rbenv, pyenv,
127
+ * sdkman) would otherwise be invisible inside the sandbox regardless of language.
128
+ * Returns `null` when unresolvable -- the caller proceeds without an extra bind;
129
+ * the exec fails inside the sandbox the same honest way it would outside one.
130
+ */
131
+ export function resolveExecutableDirectory(command, cwd, env) {
132
+ let candidate = null;
133
+ if (command.includes("/")) {
134
+ candidate = isAbsolute(command) ? command : join(cwd, command);
135
+ }
136
+ else {
137
+ const pathVar = env.PATH ?? "";
138
+ for (const dir of pathVar.split(":")) {
139
+ if (dir === "")
140
+ continue;
141
+ const full = join(dir, command);
142
+ try {
143
+ accessSync(full, fsConstants.X_OK);
144
+ candidate = full;
145
+ break;
146
+ }
147
+ catch {
148
+ continue;
149
+ }
150
+ }
151
+ }
152
+ if (candidate === null)
153
+ return null;
154
+ try {
155
+ return dirname(realpathSync(candidate));
156
+ }
157
+ catch {
158
+ return null;
159
+ }
160
+ }
161
+ /**
162
+ * Wraps `command`/`args` with `bwrap` so the OS enforces `filesystemPolicy`/
163
+ * `networkPolicy`. Neither declared returns them unchanged -- same non-regression
164
+ * contract as `applyResourceLimits`.
165
+ *
166
+ * **Throws rather than silently spawning unconstrained** when a policy is
167
+ * requested and the real mechanism can't back it -- no mechanism on this platform,
168
+ * or a declared shape this mechanism doesn't implement.
169
+ *
170
+ * Composes with `applyResourceLimits` by wrapping *outside* it (`bwrap … --
171
+ * prlimit … -- realCommand`) -- the mount namespace must exist before `prlimit` or
172
+ * the real command run inside it; `prlimit` (in `/usr/bin`) is reachable through
173
+ * the same base OS binding every sandboxed process gets.
174
+ */
175
+ export function applySandbox(options) {
176
+ const { filesystemPolicy, networkPolicy } = options;
177
+ if (filesystemPolicy === undefined && networkPolicy === undefined) {
178
+ return { command: options.command, args: options.args };
179
+ }
180
+ const env = options.env ?? process.env;
181
+ const platform = options.platform ?? process.platform;
182
+ if (networkPolicy !== undefined) {
183
+ const shapeReason = unsupportedNetworkPolicyReason(networkPolicy);
184
+ if (shapeReason !== null) {
185
+ throw new Error(`networkPolicy was configured but cannot be enforced: ${shapeReason}`);
186
+ }
187
+ const capability = networkIsolationCapability(env, platform);
188
+ if (capability.availability !== "available") {
189
+ throw new Error(`networkPolicy was configured but cannot be enforced on this platform: ${capability.reason}`);
190
+ }
191
+ }
192
+ if (filesystemPolicy !== undefined) {
193
+ const capability = filesystemIsolationCapability(env, platform);
194
+ if (capability.availability !== "available") {
195
+ throw new Error(`filesystemPolicy was configured but cannot be enforced on this platform: ${capability.reason}`);
196
+ }
197
+ }
198
+ const bwrapArgs = [];
199
+ if (filesystemPolicy !== undefined) {
200
+ bwrapArgs.push("--ro-bind", "/usr", "/usr", "--symlink", "/usr/bin", "/bin", "--symlink", "/usr/lib", "/lib", "--symlink", "/usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--bind", options.cwd, options.cwd);
201
+ const boundRoots = ["/usr", options.cwd, ...filesystemPolicy.allowedRoots];
202
+ for (const root of filesystemPolicy.allowedRoots) {
203
+ bwrapArgs.push("--bind", root, root);
204
+ }
205
+ const interpreterDir = resolveExecutableDirectory(options.interpreterCommand, options.cwd, env);
206
+ if (interpreterDir !== null && !boundRoots.some((root) => isWithin(root, interpreterDir))) {
207
+ bwrapArgs.push("--ro-bind", interpreterDir, interpreterDir);
208
+ }
209
+ }
210
+ else {
211
+ // No filesystem restriction declared -- mirror the host root exactly (matches
212
+ // FilesystemPolicy's "absent means unconstrained" default). A mount namespace
213
+ // is still created (bwrap always builds one; --unshare-net below needs it), so
214
+ // /proc, /dev, /tmp are remounted explicitly -- a plain `--bind / /` is not
215
+ // recursive and would leave them looking empty inside otherwise.
216
+ bwrapArgs.push("--bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--bind", "/tmp", "/tmp");
217
+ }
218
+ bwrapArgs.push("--chdir", options.cwd);
219
+ if (networkPolicy !== undefined) {
220
+ bwrapArgs.push("--unshare-net");
221
+ }
222
+ // Kills the sandboxed tree if bwrap's parent (this Node process) dies
223
+ // unexpectedly -- a second, independent backstop alongside process-manager.ts's
224
+ // group-kill, not a replacement for it.
225
+ bwrapArgs.push("--die-with-parent", "--", options.command, ...options.args);
226
+ return { command: "bwrap", args: bwrapArgs };
227
+ }
228
+ //# sourceMappingURL=sandbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox.js","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,SAAS,IAAI,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC3F,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAA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IAAI,EAAE,IAAI,CAAC,CAAC;QACvC,CAAC;QACD,MAAM,cAAc,GAAG,0BAA0B,CAAC,OAAO,CAAC,kBAAkB,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QAChG,IAAI,cAAc,KAAK,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC,EAAE,CAAC;YAC1F,SAAS,CAAC,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,cAAc,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;SAAM,CAAC;QACN,8EAA8E;QAC9E,8EAA8E;QAC9E,+EAA+E;QAC/E,4EAA4E;QAC5E,iEAAiE;QACjE,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACnG,CAAC;IAED,SAAS,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAEvC,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;QAChC,SAAS,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAClC,CAAC;IAED,sEAAsE;IACtE,gFAAgF;IAChF,wCAAwC;IACxC,SAAS,CAAC,IAAI,CAAC,mBAAmB,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE5E,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;AAC/C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@descryy/runtime-controller",
3
- "version": "0.3.8",
3
+ "version": "0.3.9",
4
4
  "type": "module",
5
5
  "description": "Runtime controller: process manager, readiness, timeout/cancellation, execution IDs, cleanup. Deliverable 2 of the runtime phase — depends on @descryy/runtime-contracts, builds no collectors.",
6
6
  "license": "UNLICENSED",