pi-better-background-tasks 0.9.1 → 0.11.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.
- package/README.md +99 -35
- package/package.json +1 -1
- package/src/adapter-contract.ts +56 -0
- package/src/navigator-provider.ts +5 -6
- package/src/output.ts +61 -20
- package/src/runtime.ts +130 -24
- package/src/sandbox.ts +273 -21
- package/src/shared-sandbox-core.ts +92 -0
- package/src/stall-attention.ts +31 -0
- package/src/stall.ts +14 -2
- package/src/task-diagnostics.ts +71 -0
- package/src/tools.ts +38 -14
- package/src/types.ts +19 -0
package/src/sandbox.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Background launch sandbox policy. New publishers provide a separate Background
|
|
3
|
+
* tasks profile; older publishers retain the historical Main-policy behavior.
|
|
4
|
+
* Every task keeps its policy snapshot for its whole lifetime.
|
|
3
5
|
*
|
|
4
6
|
* `pi-better-sandbox` owns the foreground policy and publishes an immutable
|
|
5
7
|
* snapshot of it on `pi.events`. This module is the consumer side of that wire
|
|
@@ -23,23 +25,36 @@
|
|
|
23
25
|
* tests that pin them.
|
|
24
26
|
*/
|
|
25
27
|
|
|
26
|
-
import { mkdirSync } from "node:fs";
|
|
28
|
+
import { accessSync, constants, mkdirSync, realpathSync, statSync } from "node:fs";
|
|
27
29
|
import { homedir } from "node:os";
|
|
28
|
-
import { dirname } from "node:path";
|
|
30
|
+
import { delimiter, dirname, resolve } from "node:path";
|
|
29
31
|
|
|
30
32
|
import { commandExecution } from "./process.js";
|
|
31
33
|
import { baseDir } from "./registry.js";
|
|
32
|
-
import { compileWritePolicy, describeSandboxSupport, maybeBuildSandboxCommand, type SandboxSeams } from "./shared-sandbox-core.js";
|
|
34
|
+
import { compileWritePolicy, describeSandboxSupport, directApplicationTarget, maybeBuildSandboxCommand, type SandboxSeams } from "./shared-sandbox-core.js";
|
|
33
35
|
|
|
34
36
|
type SandboxPermissions = {
|
|
35
37
|
/** `write` = read, create and overwrite in place; `read-write` = Write & delete. */
|
|
36
38
|
projectFiles: "off" | "read" | "write" | "read-write";
|
|
37
39
|
outsideProject: "off" | "read" | "write" | "read-write";
|
|
38
40
|
storedCredentials: "off" | "read" | "read-write";
|
|
41
|
+
/** Master switch for command execution. */
|
|
39
42
|
commands: boolean;
|
|
40
43
|
network: boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Optional refinement of `commands`: may a launch command be interpreted by a
|
|
46
|
+
* shell? Absent means yes (the historical behavior). Off confines a launch to
|
|
47
|
+
* a direct executable through `shell: false` argv.
|
|
48
|
+
*/
|
|
49
|
+
shell?: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* Optional outer cap for one launch command, in seconds. Absent or null means
|
|
52
|
+
* no cap. A value is validated here and copied into the immutable launch
|
|
53
|
+
* snapshot; it caps each actual command, never a watch's whole lifetime.
|
|
54
|
+
*/
|
|
55
|
+
commandTimeoutSeconds?: number | null;
|
|
41
56
|
};
|
|
42
|
-
import type { CommandSpec } from "./types.js";
|
|
57
|
+
import type { CommandSpec, TaskSandboxProvenance } from "./types.js";
|
|
43
58
|
import { SandboxDiagnostics, diagnosticPackageVersion, type DiagnosticResource } from "./shared-sandbox-diagnostics.js";
|
|
44
59
|
|
|
45
60
|
function backgroundDiagnostics(policy: unknown): SandboxDiagnostics | undefined {
|
|
@@ -63,7 +78,7 @@ function backgroundDiagnostics(policy: unknown): SandboxDiagnostics | undefined
|
|
|
63
78
|
* is an optional peer.
|
|
64
79
|
*/
|
|
65
80
|
export const FOREGROUND_SANDBOX_REMEDY =
|
|
66
|
-
"
|
|
81
|
+
"Change the controlling Sandbox column in /sandbox, or work in a session that has a backend.";
|
|
67
82
|
|
|
68
83
|
/** Channel `pi-better-sandbox` publishes every effective-policy change on. */
|
|
69
84
|
export const FOREGROUND_SANDBOX_POLICY_CHANNEL = "pi-better-sandbox:policy";
|
|
@@ -71,6 +86,114 @@ export const FOREGROUND_SANDBOX_POLICY_CHANNEL = "pi-better-sandbox:policy";
|
|
|
71
86
|
/** Channel a consumer emits on to ask for the current policy. */
|
|
72
87
|
export const FOREGROUND_SANDBOX_POLICY_REQUEST_CHANNEL = "pi-better-sandbox:policy-request";
|
|
73
88
|
|
|
89
|
+
/** Largest single-command cap a timer can hold: 2_147_483 seconds is 2_147_483_000 ms. */
|
|
90
|
+
export const MAX_COMMAND_TIMEOUT_SECONDS = 2_147_483;
|
|
91
|
+
|
|
92
|
+
/** A positive finite number of seconds no larger than {@link MAX_COMMAND_TIMEOUT_SECONDS}. */
|
|
93
|
+
export function isCommandTimeoutSeconds(value: unknown): value is number {
|
|
94
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= MAX_COMMAND_TIMEOUT_SECONDS;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Executables whose whole purpose is to interpret a shell command string. */
|
|
98
|
+
const SHELL_EXECUTABLES = Object.freeze([
|
|
99
|
+
"sh", "bash", "zsh", "dash", "ksh", "ksh93", "mksh", "pdksh", "ash", "csh", "tcsh", "fish",
|
|
100
|
+
"yash", "posh", "rbash", "busybox", "pwsh", "powershell", "cmd",
|
|
101
|
+
] as const);
|
|
102
|
+
const SHELL_NAMES = new Set<string>(SHELL_EXECUTABLES);
|
|
103
|
+
|
|
104
|
+
function shellExecutableName(path: string): boolean {
|
|
105
|
+
const normalized = String(path ?? "").replace(/\\/g, "/");
|
|
106
|
+
const name = normalized.slice(normalized.lastIndexOf("/") + 1).toLowerCase();
|
|
107
|
+
const stem = name.endsWith(".exe") ? name.slice(0, -4) : name;
|
|
108
|
+
return name.length > 0 && (SHELL_NAMES.has(name) || SHELL_NAMES.has(stem));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Resolve an executable the way spawn will: a relative or bare name against the
|
|
113
|
+
* launch cwd, and a bare name through the launch's PATH. A relative PATH entry
|
|
114
|
+
* is itself resolved against the launch cwd, because the child changes directory
|
|
115
|
+
* before it searches PATH.
|
|
116
|
+
*
|
|
117
|
+
* The candidate must be a regular file this process may execute, so a
|
|
118
|
+
* non-executable shadow earlier on PATH does not stand in for the real target.
|
|
119
|
+
*/
|
|
120
|
+
function resolvedExecutablePath(executable: string, env: NodeJS.ProcessEnv, cwd: string): string | undefined {
|
|
121
|
+
const value = String(executable ?? "");
|
|
122
|
+
if (value.includes("/") || (process.platform === "win32" && value.includes("\\"))) {
|
|
123
|
+
return resolve(cwd, value);
|
|
124
|
+
}
|
|
125
|
+
const path = env.PATH ?? env.Path;
|
|
126
|
+
if (!path) return undefined;
|
|
127
|
+
for (const directory of path.split(delimiter)) {
|
|
128
|
+
const candidate = resolve(cwd, directory || ".", value);
|
|
129
|
+
try {
|
|
130
|
+
if (!statSync(candidate).isFile()) continue;
|
|
131
|
+
accessSync(candidate, constants.X_OK);
|
|
132
|
+
return candidate;
|
|
133
|
+
} catch { /* A PATH entry may vanish, or not be executable. */ }
|
|
134
|
+
}
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
let shellIdentities: { path: string | undefined; cwd: string; ids: Set<string> } | undefined;
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Device/inode identities of the known shell binaries on this launch's PATH.
|
|
142
|
+
*
|
|
143
|
+
* A hardlink to a shell can carry any name, so a name check and a symlink's
|
|
144
|
+
* canonical target cannot see it. This mirrors the confined executor's identity
|
|
145
|
+
* check (`task-sandbox/exec.ts`), resolved against the launch cwd and PATH.
|
|
146
|
+
*/
|
|
147
|
+
function knownShellIdentities(env: NodeJS.ProcessEnv, cwd: string): Set<string> {
|
|
148
|
+
const path = env.PATH ?? env.Path;
|
|
149
|
+
const cached = shellIdentities;
|
|
150
|
+
if (cached && cached.path === path && cached.cwd === cwd) return cached.ids;
|
|
151
|
+
const ids = new Set<string>();
|
|
152
|
+
for (const directory of (path ?? "").split(delimiter)) {
|
|
153
|
+
for (const name of SHELL_EXECUTABLES) {
|
|
154
|
+
try {
|
|
155
|
+
const info = statSync(resolve(cwd, directory || ".", name), { bigint: true });
|
|
156
|
+
if (info.isFile()) ids.add(`${info.dev}:${info.ino}`);
|
|
157
|
+
} catch { /* Not present in this directory. */ }
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
shellIdentities = { path, cwd, ids };
|
|
161
|
+
return ids;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* True when `argv[0]` names a shell interpreter directly.
|
|
166
|
+
*
|
|
167
|
+
* With Shell scripts Off, a `shell: false` argv is still a way to ask a shell to
|
|
168
|
+
* run a command (`["/bin/bash", "-c", ...]`). The requested name is checked
|
|
169
|
+
* first, then the executable spawn would resolve against `cwd` and the launch's
|
|
170
|
+
* PATH, then its canonical target, so a symlink or an alternate name pointing at
|
|
171
|
+
* a shell is still refused. A hardlink to a shell is refused by inode identity.
|
|
172
|
+
* Only a direct interpreter is refused: an application that happens to launch a
|
|
173
|
+
* shell itself is a different capability from asking Pi to interpret a command.
|
|
174
|
+
*/
|
|
175
|
+
export function isShellExecutable(
|
|
176
|
+
executable: string,
|
|
177
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
178
|
+
cwd: string = process.cwd(),
|
|
179
|
+
): boolean {
|
|
180
|
+
if (shellExecutableName(executable)) return true;
|
|
181
|
+
const resolved = resolvedExecutablePath(String(executable ?? ""), env, cwd);
|
|
182
|
+
if (!resolved) return false;
|
|
183
|
+
let canonical: string;
|
|
184
|
+
try {
|
|
185
|
+
canonical = realpathSync.native(resolved);
|
|
186
|
+
} catch {
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
if (shellExecutableName(canonical)) return true;
|
|
190
|
+
try {
|
|
191
|
+
const info = statSync(canonical, { bigint: true });
|
|
192
|
+
if (knownShellIdentities(env, cwd).has(`${info.dev}:${info.ino}`)) return true;
|
|
193
|
+
} catch { /* A missing file fails when the launch runs it. */ }
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
|
|
74
197
|
/**
|
|
75
198
|
* What the foreground sandbox is doing right now.
|
|
76
199
|
*
|
|
@@ -92,6 +215,7 @@ export interface ForegroundSandboxPolicy {
|
|
|
92
215
|
/** Human-readable evidence for why `state` is what it is. */
|
|
93
216
|
readonly reason: string;
|
|
94
217
|
readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean }>;
|
|
218
|
+
readonly policySource?: "background" | "main-legacy";
|
|
95
219
|
}
|
|
96
220
|
|
|
97
221
|
/** The minimum `pi.events` surface this module uses. */
|
|
@@ -106,7 +230,7 @@ export class ForegroundSandboxBlockedError extends Error {
|
|
|
106
230
|
|
|
107
231
|
constructor(policy: ForegroundSandboxPolicy, detail?: string) {
|
|
108
232
|
super(
|
|
109
|
-
|
|
233
|
+
`${policy.policySource === "background" ? "Background tasks" : "Foreground"} sandbox is ${policy.state}; this local background task was blocked rather than launched unconfined. ${detail ?? policy.reason}`,
|
|
110
234
|
);
|
|
111
235
|
this.name = "ForegroundSandboxBlockedError";
|
|
112
236
|
this.policy = policy;
|
|
@@ -124,6 +248,12 @@ export type ForegroundSandboxPlan =
|
|
|
124
248
|
};
|
|
125
249
|
|
|
126
250
|
const UNCONFINED: ForegroundSandboxPlan = { confined: false };
|
|
251
|
+
const launchPolicies = new WeakMap<ForegroundSandboxPlan, ForegroundSandboxPolicy | undefined>();
|
|
252
|
+
function capturePlan(plan: ForegroundSandboxPlan, policy: ForegroundSandboxPolicy | undefined): ForegroundSandboxPlan {
|
|
253
|
+
const snapshot = { ...plan };
|
|
254
|
+
launchPolicies.set(snapshot, policy);
|
|
255
|
+
return snapshot;
|
|
256
|
+
}
|
|
127
257
|
|
|
128
258
|
const VALID_STATES = new Set<string>(["inactive", "enabled", "disabled", "unavailable", "failed"]);
|
|
129
259
|
|
|
@@ -134,7 +264,8 @@ const VALID_STATES = new Set<string>(["inactive", "enabled", "disabled", "unavai
|
|
|
134
264
|
* sessions inside one process (and separate tests) cannot read each other's
|
|
135
265
|
* policy.
|
|
136
266
|
*/
|
|
137
|
-
|
|
267
|
+
type PolicyMirror = { policy: ForegroundSandboxPolicy | undefined; error?: Error; processAccess?: "off" | "read"; mainConfined?: boolean };
|
|
268
|
+
const mirrors = new WeakMap<PolicyEventBus, PolicyMirror>();
|
|
138
269
|
|
|
139
270
|
function eventBusOf(pi: unknown): PolicyEventBus | undefined {
|
|
140
271
|
const events = (pi as { events?: unknown } | undefined)?.events;
|
|
@@ -149,7 +280,7 @@ function eventBusOf(pi: unknown): PolicyEventBus | undefined {
|
|
|
149
280
|
* understands, so an unrelated extension emitting on the channel cannot clear a
|
|
150
281
|
* real policy or invent one.
|
|
151
282
|
*/
|
|
152
|
-
function readPolicy(data: unknown): ForegroundSandboxPolicy | undefined {
|
|
283
|
+
function readPolicy(data: unknown, profile = "Main"): ForegroundSandboxPolicy | undefined {
|
|
153
284
|
if (!data || typeof data !== "object") return undefined;
|
|
154
285
|
const value = data as Record<string, unknown>;
|
|
155
286
|
if (typeof value.state !== "string" || !VALID_STATES.has(value.state)) return undefined;
|
|
@@ -159,7 +290,7 @@ function readPolicy(data: unknown): ForegroundSandboxPolicy | undefined {
|
|
|
159
290
|
: [];
|
|
160
291
|
const permissions = value.permissions === undefined ? undefined : readPermissions(value.permissions);
|
|
161
292
|
if (value.permissions !== undefined && !permissions) {
|
|
162
|
-
throw new Error(
|
|
293
|
+
throw new Error(`Invalid ${profile} sandbox permission profile; update permissions in the sandbox UI.`);
|
|
163
294
|
}
|
|
164
295
|
return {
|
|
165
296
|
state: value.state as ForegroundSandboxState,
|
|
@@ -177,12 +308,20 @@ function readPermissions(value: unknown): ForegroundSandboxPolicy["permissions"]
|
|
|
177
308
|
const access = (v: unknown) => credential(v) || v === "write";
|
|
178
309
|
if (typeof p.enabled !== "boolean" || typeof p.commands !== "boolean" ||
|
|
179
310
|
typeof p.network !== "boolean" || !access(p.projectFiles) ||
|
|
180
|
-
!access(p.outsideProject) || !credential(p.storedCredentials)
|
|
311
|
+
!access(p.outsideProject) || !credential(p.storedCredentials) ||
|
|
312
|
+
(p.processAccess !== undefined && p.processAccess !== "off" && p.processAccess !== "read") ||
|
|
313
|
+
(p.shell !== undefined && typeof p.shell !== "boolean") ||
|
|
314
|
+
(p.commandTimeoutSeconds !== undefined && p.commandTimeoutSeconds !== null &&
|
|
315
|
+
!isCommandTimeoutSeconds(p.commandTimeoutSeconds))) return undefined;
|
|
316
|
+
// Copy only what the publisher sent: absent optional settings keep their
|
|
317
|
+
// documented default meaning instead of being invented here.
|
|
181
318
|
return Object.freeze({
|
|
182
319
|
enabled: p.enabled, commands: p.commands, network: p.network,
|
|
183
320
|
projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
|
|
184
321
|
outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
|
|
185
322
|
storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
|
|
323
|
+
...(p.shell === undefined ? {} : { shell: p.shell as boolean }),
|
|
324
|
+
...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
|
|
186
325
|
});
|
|
187
326
|
}
|
|
188
327
|
|
|
@@ -198,14 +337,25 @@ export function observeForegroundSandboxPolicy(pi: unknown): void {
|
|
|
198
337
|
const events = eventBusOf(pi);
|
|
199
338
|
if (!events || mirrors.has(events)) return;
|
|
200
339
|
|
|
201
|
-
const mirror:
|
|
340
|
+
const mirror: PolicyMirror = { policy: undefined };
|
|
202
341
|
mirrors.set(events, mirror);
|
|
203
342
|
events.on(FOREGROUND_SANDBOX_POLICY_CHANNEL, (data) => {
|
|
204
343
|
try {
|
|
205
|
-
const
|
|
344
|
+
const published = data && typeof data === "object" ? data as Record<string, unknown> : undefined;
|
|
345
|
+
const hasBackground = published && Object.hasOwn(published, "background");
|
|
346
|
+
const policy = readPolicy(hasBackground ? published.background : data, hasBackground ? "Background tasks" : "Main");
|
|
347
|
+
if (hasBackground && !policy) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
|
|
348
|
+
const access = (value: unknown): unknown => {
|
|
349
|
+
if (!value || typeof value !== "object") return undefined;
|
|
350
|
+
return (value as { permissions?: { processAccess?: unknown } }).permissions?.processAccess;
|
|
351
|
+
};
|
|
352
|
+
mirror.mainConfined = published?.state !== "disabled" && published?.state !== "inactive";
|
|
353
|
+
mirror.processAccess = access(data) === "read" && access(hasBackground ? published.background : data) === "read" ? "read" : "off";
|
|
354
|
+
if (policy) Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
|
|
206
355
|
if (policy) { mirror.policy = policy; mirror.error = undefined; }
|
|
207
356
|
} catch (error) {
|
|
208
357
|
mirror.error = error as Error;
|
|
358
|
+
mirror.processAccess = "off";
|
|
209
359
|
}
|
|
210
360
|
});
|
|
211
361
|
events.emit(FOREGROUND_SANDBOX_POLICY_REQUEST_CHANNEL, undefined);
|
|
@@ -230,6 +380,28 @@ export function currentForegroundSandboxPolicy(pi: unknown): ForegroundSandboxPo
|
|
|
230
380
|
return mirror?.policy;
|
|
231
381
|
}
|
|
232
382
|
|
|
383
|
+
/** Current diagnostics permissions are independent of the task's launch snapshot. */
|
|
384
|
+
export function backgroundProcessDiagnosticsAccess(pi: unknown): "read" | "off" | "unknown" | "confined" {
|
|
385
|
+
try { currentForegroundSandboxPolicy(pi); } catch { return "off"; }
|
|
386
|
+
const events = eventBusOf(pi);
|
|
387
|
+
const mirror = events ? mirrors.get(events) : undefined;
|
|
388
|
+
const access = mirror?.processAccess ?? "unknown";
|
|
389
|
+
return access === "read" && mirror?.mainConfined ? "confined" : access;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export function sandboxProvenance(plan: ForegroundSandboxPlan, remote = false): TaskSandboxProvenance {
|
|
393
|
+
const policy = launchPolicies.get(plan);
|
|
394
|
+
const policySource = remote ? "remote" : policy?.policySource ?? (policy ? "main-legacy" : "no-publisher");
|
|
395
|
+
if (remote) return { confinement: "unknown", policySource, policySummary: "Remote execution; local sandbox does not establish remote confinement.", changesAffectTask: false };
|
|
396
|
+
if (!plan.confined) return { confinement: "unconfined", policySource,
|
|
397
|
+
policySummary: policy ? "Sandbox disabled at launch." : "No sandbox policy publisher at launch.", changesAffectTask: false };
|
|
398
|
+
const support = describeSandboxSupport();
|
|
399
|
+
const p = plan.permissions;
|
|
400
|
+
return { confinement: "confined", policySource, ...(support.supported ? { backend: support.backend } : {}),
|
|
401
|
+
policySummary: p ? `project=${p.projectFiles}; outside=${p.outsideProject}; credentials=${p.storedCredentials}; commands=${p.commands ? "on" : "off"}; network=${p.network ? "on" : "off"}`
|
|
402
|
+
: "Project write confinement with protected paths.", changesAffectTask: false };
|
|
403
|
+
}
|
|
404
|
+
|
|
233
405
|
/**
|
|
234
406
|
* Decide how a local launch must be confined, before the task has an id, a
|
|
235
407
|
* directory, or a log.
|
|
@@ -239,15 +411,15 @@ export function currentForegroundSandboxPolicy(pi: unknown): ForegroundSandboxPo
|
|
|
239
411
|
*/
|
|
240
412
|
export function resolveForegroundSandboxPlan(pi: unknown, remote = false, operation?: unknown, tool = "bg_task_spawn"): ForegroundSandboxPlan {
|
|
241
413
|
const policy = currentForegroundSandboxPolicy(pi);
|
|
242
|
-
if (remote && !policy?.permissions) return UNCONFINED; // Preserve legacy SSH behavior.
|
|
414
|
+
if (remote && !policy?.permissions) return capturePlan(UNCONFINED, policy); // Preserve legacy SSH behavior.
|
|
243
415
|
try {
|
|
244
416
|
const plan = planFor(policy);
|
|
245
417
|
if (remote && plan.confined) {
|
|
246
418
|
throw new ForegroundSandboxBlockedError(policy!, !plan.permissions?.network
|
|
247
|
-
? "Main profile disables network. SSH launches are blocked
|
|
248
|
-
:
|
|
419
|
+
? `${policy?.policySource === "background" ? "Background tasks" : "Main"} profile disables network. SSH launches are blocked.`
|
|
420
|
+
: `Structured SSH cannot apply local file and credential permissions yet. Use SSH through confined bash, or change ${policy?.policySource === "background" ? "Background tasks" : "Main"} permissions in /sandbox.`);
|
|
249
421
|
}
|
|
250
|
-
return plan;
|
|
422
|
+
return capturePlan(plan, policy);
|
|
251
423
|
} catch (error) {
|
|
252
424
|
if (error instanceof ForegroundSandboxBlockedError) {
|
|
253
425
|
const resource: DiagnosticResource = policy?.permissions?.enabled && !policy.permissions.commands ? "command-execution"
|
|
@@ -264,7 +436,7 @@ export function planFor(policy: ForegroundSandboxPolicy | undefined): Foreground
|
|
|
264
436
|
// keeps its historical unsandboxed behaviour.
|
|
265
437
|
if (!policy) return UNCONFINED;
|
|
266
438
|
if (policy.permissions?.enabled && !policy.permissions.commands) {
|
|
267
|
-
throw new ForegroundSandboxBlockedError(policy, "Main profile disables commands. Change permissions in
|
|
439
|
+
throw new ForegroundSandboxBlockedError(policy, `${policy.policySource === "background" ? "Background tasks" : "Main"} profile disables commands. Change permissions in /sandbox before launching background tasks.`);
|
|
268
440
|
}
|
|
269
441
|
if (policy.state === "inactive" || policy.state === "disabled") return UNCONFINED;
|
|
270
442
|
if (policy.state !== "enabled" || !policy.writableRoot) {
|
|
@@ -276,11 +448,85 @@ export function planFor(policy: ForegroundSandboxPolicy | undefined): Foreground
|
|
|
276
448
|
storedCredentials: policy.permissions.storedCredentials,
|
|
277
449
|
commands: policy.permissions.commands,
|
|
278
450
|
network: policy.permissions.network,
|
|
451
|
+
...(policy.permissions.shell === undefined ? {} : { shell: policy.permissions.shell }),
|
|
452
|
+
...(policy.permissions.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: policy.permissions.commandTimeoutSeconds }),
|
|
279
453
|
} : undefined;
|
|
280
454
|
return { confined: true, writableRoot: policy.writableRoot, denyWrite: policy.denyWrite,
|
|
281
455
|
...(permissions ? { permissions } : {}) };
|
|
282
456
|
}
|
|
283
457
|
|
|
458
|
+
/**
|
|
459
|
+
* The application, shell, and time switches captured with one launch plan.
|
|
460
|
+
*
|
|
461
|
+
* The Background tasks profile is the gate: when it is off, launches keep their
|
|
462
|
+
* historical unconfined behavior. When it is on, `commands` remains the master
|
|
463
|
+
* switch (enforced by {@link planFor}); this narrows it with the optional
|
|
464
|
+
* `shell` and `commandTimeoutSeconds` fields. An absent `shell` means On, and an
|
|
465
|
+
* absent or null cap means no cap, so a publisher that predates those fields is
|
|
466
|
+
* unchanged.
|
|
467
|
+
*/
|
|
468
|
+
export interface BackgroundExecutionLimits {
|
|
469
|
+
/** May a launch command be interpreted by a shell? */
|
|
470
|
+
readonly shell: boolean;
|
|
471
|
+
/** Immutable outer cap for one command, in seconds; undefined means unlimited. */
|
|
472
|
+
readonly commandTimeoutSeconds?: number;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const UNLIMITED_EXECUTION: BackgroundExecutionLimits = Object.freeze({ shell: true });
|
|
476
|
+
|
|
477
|
+
/** Read the immutable application switches captured for `plan`. */
|
|
478
|
+
export function backgroundExecutionLimits(plan: ForegroundSandboxPlan): BackgroundExecutionLimits {
|
|
479
|
+
const permissions = launchPolicies.get(plan)?.permissions;
|
|
480
|
+
if (!permissions?.enabled) return UNLIMITED_EXECUTION;
|
|
481
|
+
const cap = isCommandTimeoutSeconds(permissions.commandTimeoutSeconds)
|
|
482
|
+
? permissions.commandTimeoutSeconds
|
|
483
|
+
: undefined;
|
|
484
|
+
return Object.freeze({
|
|
485
|
+
shell: permissions.shell !== false,
|
|
486
|
+
...(cap === undefined ? {} : { commandTimeoutSeconds: cap }),
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Refuse a launch the captured Background tasks application switches forbid.
|
|
492
|
+
*
|
|
493
|
+
* Called before any task id, directory, log, or metadata exists, so a refused
|
|
494
|
+
* launch leaves nothing behind. `commands: false` is still the master refusal
|
|
495
|
+
* and is raised by {@link planFor}; this is the narrower shell rule. With Shell
|
|
496
|
+
* scripts Off, only a direct executable through `shell: false` argv is allowed.
|
|
497
|
+
* A shell command string and a direct shell interpreter in argv[0] would both
|
|
498
|
+
* reintroduce shell interpretation, and structured SSH carries a remote shell
|
|
499
|
+
* command, so all three are refused.
|
|
500
|
+
*
|
|
501
|
+
* `cwd` is the launch directory the task will actually run in. A relative
|
|
502
|
+
* executable, a relative PATH entry, and an alias found only in that directory
|
|
503
|
+
* are resolved exactly as the launch resolves them, never against Pi's own
|
|
504
|
+
* process cwd.
|
|
505
|
+
*/
|
|
506
|
+
export function assertBackgroundExecutionAllowed(
|
|
507
|
+
spec: CommandSpec,
|
|
508
|
+
plan: ForegroundSandboxPlan,
|
|
509
|
+
options: { remote?: boolean; cwd?: string } = {},
|
|
510
|
+
): void {
|
|
511
|
+
const limits = backgroundExecutionLimits(plan);
|
|
512
|
+
if (limits.shell) return;
|
|
513
|
+
const launchCwd = options.cwd ?? spec.cwd ?? process.cwd();
|
|
514
|
+
const detail = options.remote
|
|
515
|
+
? "Structured SSH carries a remote shell command, so it cannot run while Shell scripts is Off. Use a local shell:false argv launch, or turn Shell scripts on in /sandbox."
|
|
516
|
+
: spec.shell !== false
|
|
517
|
+
? "Background tasks profile disables shell commands. Pass shell:false with an argv for a direct executable, or turn Shell scripts on in /sandbox."
|
|
518
|
+
: isShellExecutable(spec.argv?.[0] ?? "", { ...process.env, ...spec.env }, launchCwd)
|
|
519
|
+
? "Background tasks profile disables shell commands. A direct shell executable is refused; launch the program itself with shell:false, or turn Shell scripts on in /sandbox."
|
|
520
|
+
: undefined;
|
|
521
|
+
if (detail === undefined) return;
|
|
522
|
+
const policy = launchPolicies.get(plan) ?? {
|
|
523
|
+
state: "failed" as const,
|
|
524
|
+
denyWrite: [],
|
|
525
|
+
reason: "The Background tasks profile disables shell commands.",
|
|
526
|
+
};
|
|
527
|
+
throw new ForegroundSandboxBlockedError(policy, detail);
|
|
528
|
+
}
|
|
529
|
+
|
|
284
530
|
/**
|
|
285
531
|
* Wrap a local command in the platform's write sandbox.
|
|
286
532
|
*
|
|
@@ -307,6 +553,10 @@ export function confineCommandSpec(
|
|
|
307
553
|
if (!plan.confined) return spec;
|
|
308
554
|
|
|
309
555
|
const { execPath, execArgs } = commandExecution(spec);
|
|
556
|
+
const directOnly = spec.shell === false && plan.permissions?.shell === false;
|
|
557
|
+
const target = directOnly
|
|
558
|
+
? directApplicationTarget(execPath, execArgs, { ...process.env, ...spec.env }, false)
|
|
559
|
+
: { execPath, execArgs };
|
|
310
560
|
// The generated profile is written here, so its directory must exist before
|
|
311
561
|
// the backend builds the command.
|
|
312
562
|
mkdirSync(dirname(profilePath), { recursive: true });
|
|
@@ -341,8 +591,8 @@ export function confineCommandSpec(
|
|
|
341
591
|
{
|
|
342
592
|
profilePath,
|
|
343
593
|
policy,
|
|
344
|
-
|
|
345
|
-
|
|
594
|
+
...target,
|
|
595
|
+
...(directOnly ? { internalHelperExecutable: true } : {}),
|
|
346
596
|
},
|
|
347
597
|
// `explicitSandbox` because the foreground state already said a sandbox
|
|
348
598
|
// applies: an absent or unusable backend must throw here rather than hand
|
|
@@ -361,13 +611,15 @@ export function confineCommandSpec(
|
|
|
361
611
|
}
|
|
362
612
|
for (const line of command.notices ?? []) onNotice(line);
|
|
363
613
|
|
|
364
|
-
return { ...spec,
|
|
614
|
+
return { ...spec, ...(directOnly ? { env: { PATH: "/usr/bin:/bin", HOME: homedir() } } : {}),
|
|
615
|
+
argv: [command.file, ...command.fileArgs], shell: false };
|
|
365
616
|
}
|
|
366
617
|
|
|
367
618
|
function blocked(plan: ForegroundSandboxPlan & { confined: true }, detail: string): Error {
|
|
368
619
|
return new ForegroundSandboxBlockedError(
|
|
369
620
|
{
|
|
370
621
|
state: "failed",
|
|
622
|
+
policySource: launchPolicies.get(plan)?.policySource,
|
|
371
623
|
writableRoot: plan.writableRoot,
|
|
372
624
|
denyWrite: plan.denyWrite,
|
|
373
625
|
reason: detail,
|
|
@@ -58,7 +58,16 @@ export type SandboxPermissions = {
|
|
|
58
58
|
projectFiles: SandboxFileAccess;
|
|
59
59
|
outsideProject: SandboxFileAccess;
|
|
60
60
|
storedCredentials: "off" | "read" | "read-write";
|
|
61
|
+
/** Run applications: the master switch for command execution (bash and run_application). */
|
|
61
62
|
commands: boolean;
|
|
63
|
+
/** Shell scripts inside commands; omitted (legacy) profiles keep shell execution On. */
|
|
64
|
+
shell?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Cap for every command path, in seconds. The effective timeout is
|
|
67
|
+
* `min(requested, cap)`, and the cap applies when the caller omits a timeout.
|
|
68
|
+
* Omitted or null means no limit. Must be positive, finite and <= 2147483.
|
|
69
|
+
*/
|
|
70
|
+
commandTimeoutSeconds?: number | null;
|
|
62
71
|
network: boolean;
|
|
63
72
|
/** Fixed process_list adapter only; omitted legacy profiles keep it Off. */
|
|
64
73
|
processAccess?: "off" | "read";
|
|
@@ -103,6 +112,89 @@ export type SandboxTarget = {
|
|
|
103
112
|
execArgs: readonly string[];
|
|
104
113
|
};
|
|
105
114
|
|
|
115
|
+
export const SHELL_EXECUTABLE_NAMES = Object.freeze([
|
|
116
|
+
"sh", "bash", "zsh", "dash", "ksh", "ksh93", "mksh", "pdksh", "ash", "csh", "tcsh", "fish",
|
|
117
|
+
"yash", "posh", "rbash", "busybox", "pwsh", "powershell", "cmd",
|
|
118
|
+
] as const);
|
|
119
|
+
|
|
120
|
+
// Fixed runtime code starts after confinement. The launch data is JSON, never
|
|
121
|
+
// env/shell syntax. Native execve never falls back to a command interpreter.
|
|
122
|
+
const APPLICATION_RUNNER = `
|
|
123
|
+
const fs = require("node:fs");
|
|
124
|
+
const path = require("node:path");
|
|
125
|
+
const spec = JSON.parse(process.argv[1]);
|
|
126
|
+
function resolveExecutable(executable) {
|
|
127
|
+
if (executable.includes(path.sep)) return path.resolve(executable);
|
|
128
|
+
const directories = (spec.env.PATH || spec.env.Path || "").split(path.delimiter);
|
|
129
|
+
const resolved = directories.map(directory => path.resolve(directory || ".", executable)).find(candidate => {
|
|
130
|
+
try { fs.accessSync(candidate, fs.constants.X_OK); return fs.statSync(candidate).isFile(); }
|
|
131
|
+
catch { return false; }
|
|
132
|
+
});
|
|
133
|
+
if (!resolved) throw new Error("Executable not found: " + executable);
|
|
134
|
+
return resolved;
|
|
135
|
+
}
|
|
136
|
+
function isShellInterpreter(interpreter) {
|
|
137
|
+
const canonical = fs.realpathSync(interpreter);
|
|
138
|
+
if (spec.shellNames.includes(path.basename(interpreter)) || spec.shellNames.includes(path.basename(canonical))) return true;
|
|
139
|
+
const target = fs.statSync(canonical, { bigint: true });
|
|
140
|
+
const directories = new Set(["/bin", "/usr/bin", ...(spec.env.PATH || spec.env.Path || "").split(path.delimiter)]);
|
|
141
|
+
for (const directory of directories) for (const name of spec.shellNames) {
|
|
142
|
+
try {
|
|
143
|
+
const known = fs.statSync(path.resolve(directory || ".", name), { bigint: true });
|
|
144
|
+
if (target.dev === known.dev && target.ino === known.ino) return true;
|
|
145
|
+
} catch { /* A shell need not exist in every executable directory. */ }
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
function verifyExecutable(executable, depth = 0) {
|
|
150
|
+
if (depth > 4) throw new Error("Too many shebang interpreters.");
|
|
151
|
+
fs.accessSync(executable, fs.constants.X_OK);
|
|
152
|
+
const fd = fs.openSync(executable, "r");
|
|
153
|
+
const header = Buffer.alloc(4096);
|
|
154
|
+
let size;
|
|
155
|
+
try { size = fs.readSync(fd, header, 0, header.length, 0); }
|
|
156
|
+
finally { fs.closeSync(fd); }
|
|
157
|
+
const magic = size >= 4 ? header.readUInt32BE(0) : 0;
|
|
158
|
+
const binary = [0x7f454c46, 0xfeedface, 0xcefaedfe, 0xfeedfacf, 0xcffaedfe,
|
|
159
|
+
0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic);
|
|
160
|
+
const script = size >= 2 && header[0] === 35 && header[1] === 33;
|
|
161
|
+
if (!binary && !script) throw new Error("Executable has no supported binary format or shebang; shell fallback is disabled.");
|
|
162
|
+
if (!spec.shell && script) {
|
|
163
|
+
const words = header.subarray(2, size).toString("utf8").split(/\\r?\\n/, 1)[0].trim().split(/\\s+/);
|
|
164
|
+
let interpreter = resolveExecutable(words[0]);
|
|
165
|
+
if (path.basename(fs.realpathSync(interpreter)) === "env") {
|
|
166
|
+
if (words.length !== 2 || words[1].startsWith("-") || words[1].includes("=")) {
|
|
167
|
+
throw new Error("Sandbox: Shell scripts are Off; an env shebang must name one direct interpreter without options.");
|
|
168
|
+
}
|
|
169
|
+
interpreter = resolveExecutable(words[1]);
|
|
170
|
+
}
|
|
171
|
+
if (isShellInterpreter(interpreter)) {
|
|
172
|
+
throw new Error("Sandbox: Shell scripts are Off; the executable uses a shell shebang.");
|
|
173
|
+
}
|
|
174
|
+
verifyExecutable(interpreter, depth + 1);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
if (typeof process.execve !== "function") {
|
|
179
|
+
throw new Error("Direct application execution requires Node.js with process.execve (22.15+ or 24+). Update Node.js; no shell fallback was run.");
|
|
180
|
+
}
|
|
181
|
+
const executable = resolveExecutable(spec.executable);
|
|
182
|
+
verifyExecutable(executable);
|
|
183
|
+
process.execve(executable, [executable, ...spec.args], spec.env);
|
|
184
|
+
} catch (error) {
|
|
185
|
+
console.error(error.code === "ENOEXEC" ? "Executable format is unsupported; shell fallback is disabled." : error.message);
|
|
186
|
+
process.exitCode = 126;
|
|
187
|
+
}
|
|
188
|
+
`;
|
|
189
|
+
|
|
190
|
+
/** Fixed post-boundary launcher for literal argv, without env assignment or shell fallback. */
|
|
191
|
+
export function directApplicationTarget(
|
|
192
|
+
executable: string, args: readonly string[], env: NodeJS.ProcessEnv, shell: boolean,
|
|
193
|
+
): SandboxTarget {
|
|
194
|
+
return { execPath: canonicalizePath(process.execPath), execArgs: ["--eval", APPLICATION_RUNNER,
|
|
195
|
+
JSON.stringify({ executable, args, env, shell, shellNames: SHELL_EXECUTABLE_NAMES })] };
|
|
196
|
+
}
|
|
197
|
+
|
|
106
198
|
export type SandboxCommandArgs = SandboxTarget & {
|
|
107
199
|
/** Where the macOS backend writes its generated SBPL profile. */
|
|
108
200
|
profilePath: string;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { failurePath, recordFailure, recoverFailure } from "./failures.js";
|
|
2
|
+
import { actionableFailures, failureIdentity, readFailureState } from "./shared-failure-observations.js";
|
|
3
|
+
import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.js";
|
|
4
|
+
import type { BackgroundTaskMeta } from "./types.js";
|
|
5
|
+
|
|
6
|
+
const STALL_OPERATION = "suspected-stall";
|
|
7
|
+
|
|
8
|
+
/** Observe silence without changing lifecycle. The caller schedules existing failure attention on true. */
|
|
9
|
+
export function observeTaskStallAttention(meta: BackgroundTaskMeta, now = Date.now()): boolean {
|
|
10
|
+
if (meta.status !== "running") {
|
|
11
|
+
recoverFailure(meta, STALL_OPERATION, ["terminal", meta.status], now);
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
const observation = observeBackgroundTaskStall(meta, now);
|
|
15
|
+
if (observation.observedAt === undefined || observation.state === "unknown") return false;
|
|
16
|
+
|
|
17
|
+
const path = failurePath(meta.id);
|
|
18
|
+
const before = readFailureState(path);
|
|
19
|
+
const prior = before.observations[failureIdentity(STALL_OPERATION)];
|
|
20
|
+
const eventKey = observation.observedAt;
|
|
21
|
+
const incidentId = failureIdentity(meta.id, STALL_OPERATION, eventKey);
|
|
22
|
+
|
|
23
|
+
// A new progress anchor ends the previous spell, even if the monitor missed the healthy interval.
|
|
24
|
+
if (prior && prior.id !== incidentId) recoverFailure(meta, STALL_OPERATION, eventKey, now);
|
|
25
|
+
if (observation.state !== "stalled") return false;
|
|
26
|
+
|
|
27
|
+
recordFailure(meta, STALL_OPERATION, formatBackgroundTaskStall(observation)!, eventKey, { category: "stall", at: now });
|
|
28
|
+
const previousActionable = new Set(actionableFailures(before).map((incident) => incident.id));
|
|
29
|
+
return actionableFailures(readFailureState(path))
|
|
30
|
+
.some((incident) => incident.id === incidentId && !previousActionable.has(incident.id));
|
|
31
|
+
}
|
package/src/stall.ts
CHANGED
|
@@ -25,7 +25,10 @@ export function backgroundTaskProgressAt(meta: BackgroundTaskMeta): number | und
|
|
|
25
25
|
const recorded = Math.max(meta.lastProgressAt ?? 0, meta.lastCheckedAt ?? 0, meta.startedAt);
|
|
26
26
|
if (meta.kind !== "process") return recorded;
|
|
27
27
|
try {
|
|
28
|
-
|
|
28
|
+
const log = statSync(meta.logPath);
|
|
29
|
+
const mtimeMs = Math.trunc(log.mtimeMs);
|
|
30
|
+
if (meta.logMaintenance?.mtimeMs === mtimeMs && meta.logMaintenance.size === log.size) return recorded;
|
|
31
|
+
return Math.max(recorded, mtimeMs);
|
|
29
32
|
} catch {
|
|
30
33
|
return recorded;
|
|
31
34
|
}
|
|
@@ -39,4 +42,13 @@ export function observeBackgroundTaskStall(meta: BackgroundTaskMeta, now = Date.
|
|
|
39
42
|
exempt: meta.status !== "running",
|
|
40
43
|
thresholds: backgroundTaskStallThresholds(),
|
|
41
44
|
});
|
|
42
|
-
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Silence is an observation, not proof that the process is hung. */
|
|
48
|
+
export function formatBackgroundTaskStall(observation: StallObservation): string | undefined {
|
|
49
|
+
if (observation.state !== "quiet" && observation.state !== "stalled") return undefined;
|
|
50
|
+
const seconds = Math.max(0, Math.round((observation.ageMs ?? 0) / 1000));
|
|
51
|
+
const duration = seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
|
|
52
|
+
const label = observation.state === "stalled" ? "suspected stall" : "quiet";
|
|
53
|
+
return `${label}; no observed progress for ${duration}`;
|
|
54
|
+
}
|