pi-crew 0.6.0 → 0.6.3
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/CHANGELOG.md +225 -0
- package/README.md +70 -31
- package/docs/issue-29-analysis.md +189 -0
- package/docs/superpowers/plans/2026-06-09-fallow-patterns-adoption.md +1268 -0
- package/package.json +2 -2
- package/src/agents/agent-config.ts +2 -1
- package/src/benchmark/feedback-loop.ts +4 -2
- package/src/config/config.ts +106 -15
- package/src/errors.ts +107 -0
- package/src/extension/async-notifier.ts +6 -2
- package/src/extension/crew-cleanup.ts +8 -5
- package/src/extension/cross-extension-rpc.ts +48 -0
- package/src/extension/management.ts +464 -109
- package/src/extension/register.ts +194 -34
- package/src/extension/registration/commands.ts +4 -3
- package/src/extension/registration/subagent-helpers.ts +2 -2
- package/src/extension/registration/subagent-tools.ts +3 -1
- package/src/extension/registration/team-tool.ts +3 -1
- package/src/extension/registration/viewers.ts +3 -2
- package/src/extension/run-export.ts +16 -1
- package/src/extension/run-import.ts +16 -0
- package/src/extension/team-tool/anchor.ts +5 -1
- package/src/extension/team-tool/api.ts +12 -7
- package/src/extension/team-tool/cancel.ts +3 -3
- package/src/extension/team-tool/config-patch.ts +15 -1
- package/src/extension/team-tool/explain.ts +1 -1
- package/src/extension/team-tool/handle-schedule.ts +40 -0
- package/src/extension/team-tool/inspect.ts +3 -3
- package/src/extension/team-tool/lifecycle-actions.ts +4 -4
- package/src/extension/team-tool/respond.ts +2 -2
- package/src/extension/team-tool/run.ts +60 -11
- package/src/extension/team-tool/status.ts +1 -1
- package/src/extension/team-tool.ts +175 -47
- package/src/hooks/registry.ts +84 -12
- package/src/hooks/types.ts +12 -3
- package/src/i18n.ts +15 -2
- package/src/observability/exporters/otlp-exporter.ts +73 -0
- package/src/plugins/plugin-define.ts +6 -0
- package/src/plugins/plugin-registry.ts +32 -0
- package/src/plugins/plugins/index.ts +3 -0
- package/src/plugins/plugins/nextjs.ts +19 -0
- package/src/plugins/plugins/vite.ts +14 -0
- package/src/plugins/plugins/vitest.ts +14 -0
- package/src/runtime/adaptive-plan.ts +24 -0
- package/src/runtime/agent-control.ts +6 -3
- package/src/runtime/async-runner.ts +86 -3
- package/src/runtime/background-runner.ts +529 -144
- package/src/runtime/chain-parser.ts +5 -1
- package/src/runtime/chain-runner.ts +67 -3
- package/src/runtime/checkpoint.ts +262 -180
- package/src/runtime/child-pi.ts +165 -38
- package/src/runtime/crash-recovery.ts +25 -14
- package/src/runtime/crew-agent-records.ts +6 -3
- package/src/runtime/cross-extension-rpc.ts +34 -8
- package/src/runtime/diagnostic-export.ts +4 -5
- package/src/runtime/dynamic-script-runner.ts +9 -6
- package/src/runtime/foreground-watchdog.ts +3 -3
- package/src/runtime/heartbeat-watcher.ts +19 -2
- package/src/runtime/intercom-bridge.ts +7 -0
- package/src/runtime/iteration-hooks.ts +1 -1
- package/src/runtime/live-agent-manager.ts +6 -3
- package/src/runtime/live-irc.ts +4 -2
- package/src/runtime/manifest-cache.ts +4 -0
- package/src/runtime/orphan-worker-registry.ts +444 -0
- package/src/runtime/parallel-utils.ts +2 -1
- package/src/runtime/parent-guard.ts +70 -16
- package/src/runtime/pi-args.ts +437 -14
- package/src/runtime/pi-spawn.ts +1 -0
- package/src/runtime/post-checks.ts +11 -4
- package/src/runtime/retry-runner.ts +9 -3
- package/src/runtime/{drift-detectors.ts → run-drift.ts} +1 -1
- package/src/runtime/run-tracker.ts +38 -10
- package/src/runtime/sandbox.ts +42 -21
- package/src/runtime/scheduler.ts +25 -2
- package/src/runtime/semaphore.ts +2 -1
- package/src/runtime/settings-store.ts +14 -2
- package/src/runtime/skill-effectiveness.ts +109 -64
- package/src/runtime/skill-instructions.ts +114 -33
- package/src/runtime/stale-reconciler.ts +310 -69
- package/src/runtime/subagent-manager.ts +265 -53
- package/src/runtime/subprocess-tool-registry.ts +2 -2
- package/src/runtime/task-health.ts +76 -0
- package/src/runtime/task-id.ts +20 -0
- package/src/runtime/task-packet.ts +13 -1
- package/src/runtime/task-runner/live-executor.ts +1 -1
- package/src/runtime/task-runner/progress.ts +1 -1
- package/src/runtime/task-runner/state-helpers.ts +110 -6
- package/src/runtime/task-runner.ts +98 -67
- package/src/runtime/team-runner.ts +186 -20
- package/src/runtime/usage-tracker.ts +4 -2
- package/src/runtime/verification-gates.ts +36 -9
- package/src/schema/team-tool-schema.ts +27 -9
- package/src/skills/discover-skills.ts +9 -3
- package/src/state/active-run-registry.ts +170 -38
- package/src/state/artifact-store.ts +25 -13
- package/src/state/atomic-write-v2.ts +86 -0
- package/src/state/atomic-write.ts +346 -55
- package/src/state/blob-store.ts +178 -10
- package/src/state/contracts.ts +2 -1
- package/src/state/crew-init.ts +161 -28
- package/src/state/decision-ledger.ts +172 -111
- package/src/state/event-log-rotation.ts +82 -52
- package/src/state/event-log.ts +270 -75
- package/src/state/health-store.ts +71 -0
- package/src/state/hook-instinct-bridge.ts +2 -1
- package/src/state/locks.ts +109 -20
- package/src/state/mailbox.ts +45 -7
- package/src/state/observation-store.ts +4 -1
- package/src/state/run-graph.ts +141 -130
- package/src/state/run-metrics.ts +24 -8
- package/src/state/state-store.ts +333 -44
- package/src/state/task-claims.ts +9 -2
- package/src/tools/safe-bash.ts +69 -20
- package/src/types/new-api-types.ts +10 -5
- package/src/ui/keybinding-map.ts +2 -1
- package/src/ui/live-run-sidebar.ts +1 -1
- package/src/ui/loaders.ts +4 -0
- package/src/ui/overlays/agent-picker-overlay.ts +1 -1
- package/src/ui/overlays/mailbox-detail-overlay.ts +1 -1
- package/src/ui/run-action-dispatcher.ts +4 -3
- package/src/ui/run-snapshot-cache.ts +1 -1
- package/src/ui/status-colors.ts +2 -1
- package/src/ui/syntax-highlight.ts +2 -1
- package/src/ui/tool-render.ts +13 -3
- package/src/utils/env-filter.ts +66 -0
- package/src/utils/file-coalescer.ts +9 -1
- package/src/utils/fs-watch.ts +4 -2
- package/src/utils/gh-protocol.ts +2 -1
- package/src/utils/paths.ts +80 -5
- package/src/utils/redaction.ts +6 -1
- package/src/utils/safe-paths.ts +287 -10
- package/src/worktree/cleanup.ts +117 -26
- package/src/worktree/worktree-manager.ts +128 -15
- package/test-bugs-all.mjs +10 -6
- package/test-integration-check.ts +4 -0
|
@@ -15,11 +15,48 @@
|
|
|
15
15
|
* const parentPid = Number(process.env.PI_CREW_PARENT_PID);
|
|
16
16
|
* if (parentPid > 0) startParentGuard(parentPid);
|
|
17
17
|
* ```
|
|
18
|
+
*
|
|
19
|
+
* ## Trust model
|
|
20
|
+
*
|
|
21
|
+
* `PI_CREW_PARENT_PID` is propagated from the spawning team-runner to each
|
|
22
|
+
* child via the explicit env allow-list in `child-pi.ts`. The PID itself is
|
|
23
|
+
* NOT a secret — process identifiers are public knowledge on Unix-like
|
|
24
|
+
* systems (visible in `ps`, `/proc`, etc.) and carry no privilege.
|
|
25
|
+
*
|
|
26
|
+
* Residual risk: a malicious or compromised child can spoof
|
|
27
|
+
* `process.env.PI_CREW_PARENT_PID` before invoking `startParentGuard()`.
|
|
28
|
+
* This is acceptable because the parent-guard is a self-termination
|
|
29
|
+
* signal, NOT a security boundary:
|
|
30
|
+
* - It only causes the (already-compromised) child to exit earlier.
|
|
31
|
+
* - A truly malicious child can simply not call `startParentGuard()`.
|
|
32
|
+
* - Real protection against hostile children comes from the sandbox,
|
|
33
|
+
* env-filter allowlist, and redaction — all enforced before spawn.
|
|
34
|
+
*
|
|
35
|
+
* The guard exists for the benign case: a parent dies (user closes the
|
|
36
|
+
* terminal, pi crashes, machine loses power) and we want all detached
|
|
37
|
+
* workers to stop wasting CPU. It is NOT an anti-tampering mechanism.
|
|
18
38
|
*/
|
|
19
39
|
|
|
20
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Poll interval for parent liveness checks (in milliseconds).
|
|
42
|
+
* Default: 500ms. A parent killed by SIGKILL is detected within one poll
|
|
43
|
+
* interval (max 500ms latency).
|
|
44
|
+
*
|
|
45
|
+
* For latency-sensitive workloads (e.g., preventing orphaned workers from
|
|
46
|
+
* running with a dead supervisor), you can tune this lower by setting the
|
|
47
|
+
* PI_CREW_PARENT_GUARD_INTERVAL_MS environment variable.
|
|
48
|
+
*
|
|
49
|
+
* WARNING: Values below 100ms significantly increase overhead for large
|
|
50
|
+
* numbers of parallel workers, since each poll issues a process.kill(pid, 0)
|
|
51
|
+
* syscall per worker. Only tune this if immediate detection is critical.
|
|
52
|
+
*
|
|
53
|
+
* FUTURE: An event-based SIGCHLD handler could supplement or replace this
|
|
54
|
+
* polling approach for near-instantaneous parent-death detection on Unix
|
|
55
|
+
* systems, avoiding the polling overhead entirely.
|
|
56
|
+
*/
|
|
57
|
+
const POLL_INTERVAL_MS = Number(process.env.PI_CREW_PARENT_GUARD_INTERVAL_MS) || 500;
|
|
21
58
|
|
|
22
|
-
|
|
59
|
+
const guardIntervals = new Map<number, ReturnType<typeof setInterval>>();
|
|
23
60
|
|
|
24
61
|
function isPidAlive(pid: number): boolean {
|
|
25
62
|
try {
|
|
@@ -46,26 +83,43 @@ function selfTerminate(parentPid: number): never {
|
|
|
46
83
|
* Start a lightweight poll that checks if the parent process is still alive.
|
|
47
84
|
* If the parent dies, this worker exits immediately with code 124.
|
|
48
85
|
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
86
|
+
* FIX: Removed unref() — the guard interval MUST keep the event loop alive
|
|
87
|
+
* to prevent premature worker exit when the parent is still alive but the
|
|
88
|
+
* worker has no other pending work (LLM calls, timers, I/O). Without this,
|
|
89
|
+
* a worker in pure CPU wait could exit even though its parent is alive.
|
|
52
90
|
*/
|
|
53
91
|
export function startParentGuard(parentPid: number): void {
|
|
54
92
|
if (!parentPid || !Number.isFinite(parentPid) || parentPid <= 0) return;
|
|
55
93
|
|
|
56
|
-
//
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
94
|
+
// Clear any existing guard for this specific parentPid before setting a new one
|
|
95
|
+
const existing = guardIntervals.get(parentPid);
|
|
96
|
+
if (existing) clearInterval(existing);
|
|
97
|
+
|
|
98
|
+
// Add ±20% jitter to prevent synchronized polling across workers that
|
|
99
|
+
// start simultaneously (e.g., after pi restart). Without jitter, all
|
|
100
|
+
// workers would poll at exactly the same interval, creating load spikes.
|
|
101
|
+
const jitter = POLL_INTERVAL_MS * 0.2 * (Math.random() - 0.5) * 2;
|
|
102
|
+
const actualInterval = POLL_INTERVAL_MS + jitter;
|
|
60
103
|
|
|
61
|
-
|
|
104
|
+
const interval = setInterval(() => {
|
|
105
|
+
// Immediate check on every tick — detects parent death within one poll
|
|
106
|
+
// interval (max POLL_INTERVAL_MS latency, default 500ms).
|
|
62
107
|
if (!isPidAlive(parentPid)) {
|
|
63
|
-
|
|
108
|
+
const guard = guardIntervals.get(parentPid);
|
|
109
|
+
if (guard) clearInterval(guard);
|
|
110
|
+
guardIntervals.delete(parentPid);
|
|
64
111
|
selfTerminate(parentPid);
|
|
65
112
|
}
|
|
66
|
-
},
|
|
113
|
+
}, actualInterval);
|
|
114
|
+
|
|
115
|
+
guardIntervals.set(parentPid, interval);
|
|
67
116
|
|
|
68
|
-
guardInterval.unref()
|
|
117
|
+
// NOTE: Intentionally NOT calling guardInterval.unref() here.
|
|
118
|
+
// The watchdog timer must keep the event loop alive to ensure the worker
|
|
119
|
+
// doesn't exit while the parent is alive. If other work (child processes,
|
|
120
|
+
// timers, I/O) keeps the loop alive, that's fine — the guard runs as a
|
|
121
|
+
// side effect. If no other work exists, the guard is the only thing
|
|
122
|
+
// keeping the process alive, and that's by design.
|
|
69
123
|
}
|
|
70
124
|
|
|
71
125
|
/**
|
|
@@ -73,8 +127,8 @@ export function startParentGuard(parentPid: number): void {
|
|
|
73
127
|
* and doesn't need to watch the parent anymore.
|
|
74
128
|
*/
|
|
75
129
|
export function stopParentGuard(): void {
|
|
76
|
-
|
|
77
|
-
clearInterval(
|
|
78
|
-
guardInterval = undefined;
|
|
130
|
+
for (const interval of guardIntervals.values()) {
|
|
131
|
+
clearInterval(interval);
|
|
79
132
|
}
|
|
133
|
+
guardIntervals.clear();
|
|
80
134
|
}
|
package/src/runtime/pi-args.ts
CHANGED
|
@@ -4,12 +4,29 @@ import * as path from "node:path";
|
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import type { AgentConfig } from "../agents/agent-config.ts";
|
|
6
6
|
import { getAgentSessionOptions } from "../agents/agent-config.ts";
|
|
7
|
+
import { userPiRoot } from "../utils/paths.ts";
|
|
7
8
|
|
|
8
9
|
const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
|
|
9
10
|
const PROMPT_RUNTIME_EXTENSION_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "prompt", "prompt-runtime.ts");
|
|
10
11
|
const TASK_ARG_LIMIT = 8000;
|
|
11
12
|
const DEFAULT_MAX_CREW_DEPTH = 2;
|
|
12
13
|
|
|
14
|
+
// Track every temp dir created in this process so we can clean them up
|
|
15
|
+
// even if the parent is killed before child-pi.ts cleanup runs.
|
|
16
|
+
// Prevents accumulation of /tmp/pi-crew-* dirs from crashed/killed tests.
|
|
17
|
+
const createdTempDirs = new Set<string>();
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the temp-dir base path.
|
|
21
|
+
* Uses pi-crew's own user-root (`~/.pi/agent/pi-crew/tmp/`) so the temp
|
|
22
|
+
* files live alongside other pi-crew state and never pollute the shared
|
|
23
|
+
* /tmp directory. Uses `userPiRoot()` so the path stays consistent with
|
|
24
|
+
* the rest of pi-crew (respects PI_TEAMS_HOME / PI_CODING_AGENT_DIR).
|
|
25
|
+
*/
|
|
26
|
+
function getPiTempBase(): string {
|
|
27
|
+
return path.join(userPiRoot(), "tmp");
|
|
28
|
+
}
|
|
29
|
+
|
|
13
30
|
export interface BuildPiWorkerArgsInput {
|
|
14
31
|
task: string;
|
|
15
32
|
agent: AgentConfig;
|
|
@@ -51,7 +68,15 @@ export function resolveCrewMaxDepth(inputMaxDepth?: number, env: NodeJS.ProcessE
|
|
|
51
68
|
const raw = env.PI_CREW_MAX_DEPTH ?? env.PI_TEAMS_MAX_DEPTH;
|
|
52
69
|
const envDepth = raw !== undefined ? Number(raw) : NaN;
|
|
53
70
|
if (Number.isInteger(envDepth) && envDepth >= 1 && envDepth <= 10) return envDepth;
|
|
71
|
+
if (Number.isInteger(envDepth) && envDepth > 10) {
|
|
72
|
+
console.warn(`PI_CREW_MAX_DEPTH=${envDepth} exceeds cap of 10, clamping to 10. Set 10 or lower to avoid this warning.`);
|
|
73
|
+
return 10;
|
|
74
|
+
}
|
|
54
75
|
if (Number.isInteger(inputMaxDepth) && inputMaxDepth !== undefined && inputMaxDepth >= 1 && inputMaxDepth <= 10) return inputMaxDepth;
|
|
76
|
+
if (Number.isInteger(inputMaxDepth) && inputMaxDepth !== undefined && inputMaxDepth > 10) {
|
|
77
|
+
console.warn(`maxDepth=${inputMaxDepth} exceeds cap of 10, clamping to 10. Set 10 or lower to avoid this warning.`);
|
|
78
|
+
return 10;
|
|
79
|
+
}
|
|
55
80
|
return DEFAULT_MAX_CREW_DEPTH;
|
|
56
81
|
}
|
|
57
82
|
|
|
@@ -67,13 +92,139 @@ export function checkCrewDepth(inputMaxDepth?: number, env: NodeJS.ProcessEnv =
|
|
|
67
92
|
* 2. lstatSync to verify it is not a symlink (TOCTOU safety)
|
|
68
93
|
* 3. realpathSync to resolve the canonical path
|
|
69
94
|
*/
|
|
70
|
-
|
|
95
|
+
/**
|
|
96
|
+
* Create a temp dir with symlink-safety checks. Tracked in the
|
|
97
|
+
* `createdTempDirs` Set for global cleanup.
|
|
98
|
+
*
|
|
99
|
+
* Exported (rather than module-private) so unit tests can populate
|
|
100
|
+
* the tracking Set without going through the public build flow.
|
|
101
|
+
*/
|
|
102
|
+
export function createSafeTempDir(base: string, prefix: string): string {
|
|
103
|
+
// FIX: Walk FULL ancestor chain for symlinks BEFORE creating any directories.
|
|
104
|
+
// An attacker could plant a symlink at any ancestor of base (e.g.,
|
|
105
|
+
// making /home/bom/.pi -> /tmp/attacker). Walk from root to base
|
|
106
|
+
// and verify no component is a symlink. Only THEN create base if needed.
|
|
107
|
+
const absoluteBase = path.resolve(base);
|
|
108
|
+
const parts = absoluteBase.split(path.sep);
|
|
109
|
+
let accumulated = "";
|
|
110
|
+
if (parts[0] === "") accumulated = "/"; // Unix root
|
|
111
|
+
for (let i = 1; i < parts.length; i++) {
|
|
112
|
+
if (parts[i] === "") continue;
|
|
113
|
+
accumulated = path.join(accumulated, parts[i]);
|
|
114
|
+
try {
|
|
115
|
+
const stat = fs.lstatSync(accumulated);
|
|
116
|
+
if (stat.isSymbolicLink()) {
|
|
117
|
+
// On macOS, /var → /private/var, /tmp → /private/tmp, /etc → /private/etc
|
|
118
|
+
// are system symlinks managed by the OS. Allow them.
|
|
119
|
+
const knownDarwinSymlinks = ["/var", "/tmp", "/etc", "/private/var", "/private/tmp", "/private/etc"];
|
|
120
|
+
if (process.platform === "darwin" && knownDarwinSymlinks.includes(accumulated)) continue;
|
|
121
|
+
throw new Error("Refusing to create temp dir: ancestor is a symlink: " + accumulated);
|
|
122
|
+
}
|
|
123
|
+
} catch (e) {
|
|
124
|
+
if (e instanceof Error && e.message.includes("symlink")) throw e;
|
|
125
|
+
// Component doesn't exist yet — OK, proceed
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// Verify base dir itself is not a symlink before realpathSync.
|
|
130
|
+
// Issue #1 fix: if baseDir itself is a symlink, realpathSync would
|
|
131
|
+
// resolve to an attacker-controlled location.
|
|
132
|
+
try {
|
|
133
|
+
const baseStat = fs.lstatSync(base);
|
|
134
|
+
if (baseStat.isSymbolicLink()) throw new Error("Refusing to create temp dir in symlinked base: " + base);
|
|
135
|
+
} catch (e) {
|
|
136
|
+
if (e instanceof Error && e.message.includes("symlink")) throw e;
|
|
137
|
+
// ENOENT: base doesn't exist yet — will be created below.
|
|
138
|
+
}
|
|
139
|
+
// Create base dir only AFTER all ancestor symlink checks pass.
|
|
71
140
|
if (!fs.existsSync(base)) fs.mkdirSync(base, { recursive: true });
|
|
72
|
-
//
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
//
|
|
76
|
-
|
|
141
|
+
// Issue #1 fix: re-validate the FULL ancestor chain immediately after
|
|
142
|
+
// mkdirSync to close the TOCTOU window between initial validation
|
|
143
|
+
// (lines 111-122) and directory creation. An attacker could have
|
|
144
|
+
// deleted a validated ancestor and recreated it as a symlink in that
|
|
145
|
+
// window.
|
|
146
|
+
for (let i = 1; i < parts.length; i++) {
|
|
147
|
+
if (parts[i] === "") continue;
|
|
148
|
+
accumulated = path.join(accumulated, parts[i]);
|
|
149
|
+
try {
|
|
150
|
+
const stat = fs.lstatSync(accumulated);
|
|
151
|
+
if (stat.isSymbolicLink()) {
|
|
152
|
+
const knownDarwinSymlinks = ["/var", "/tmp", "/etc", "/private/var", "/private/tmp", "/private/etc"];
|
|
153
|
+
if (process.platform === "darwin" && knownDarwinSymlinks.includes(accumulated)) continue;
|
|
154
|
+
throw new Error("Refusing to create temp dir: ancestor is a symlink (post-mkdir): " + accumulated);
|
|
155
|
+
}
|
|
156
|
+
} catch (e) {
|
|
157
|
+
if (e instanceof Error && e.message.includes("symlink")) throw e;
|
|
158
|
+
// Component doesn't exist — OK
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Resolve base to canonical path before joining.
|
|
163
|
+
// Issue #1 fix: if the base dir is deleted between the post-mkdir
|
|
164
|
+
// validation loop (lines 135-146) and realpathSync, realpathSync throws
|
|
165
|
+
// ENOENT. Re-validate and retry to handle fast delete+recreate races.
|
|
166
|
+
let resolvedBase: string;
|
|
167
|
+
let retries = 3;
|
|
168
|
+
while (true) {
|
|
169
|
+
try {
|
|
170
|
+
resolvedBase = fs.realpathSync(base);
|
|
171
|
+
break;
|
|
172
|
+
} catch (e: unknown) {
|
|
173
|
+
if (--retries <= 0) throw e;
|
|
174
|
+
// ENOENT: re-validate ancestor chain and retry
|
|
175
|
+
const code = e instanceof Object && "code" in e ? (e as { code: string }).code : undefined;
|
|
176
|
+
if (code !== "ENOENT") throw e;
|
|
177
|
+
}
|
|
178
|
+
// Re-validate ancestor chain post-mkdir (same logic as lines 135-146)
|
|
179
|
+
const revalidateParts = absoluteBase.split(path.sep);
|
|
180
|
+
let revalidateAccumulated = "";
|
|
181
|
+
if (revalidateParts[0] === "") revalidateAccumulated = "/";
|
|
182
|
+
for (let i = 1; i < revalidateParts.length; i++) {
|
|
183
|
+
if (revalidateParts[i] === "") continue;
|
|
184
|
+
revalidateAccumulated = path.join(revalidateAccumulated, revalidateParts[i]);
|
|
185
|
+
try {
|
|
186
|
+
const stat = fs.lstatSync(revalidateAccumulated);
|
|
187
|
+
if (stat.isSymbolicLink()) {
|
|
188
|
+
const knownDarwinSymlinks = ["/var", "/tmp", "/etc", "/private/var", "/private/tmp", "/private/etc"];
|
|
189
|
+
if (process.platform === "darwin" && knownDarwinSymlinks.includes(revalidateAccumulated)) continue;
|
|
190
|
+
throw new Error("Refusing to create temp dir: ancestor is a symlink (post-mkdir): " + revalidateAccumulated);
|
|
191
|
+
}
|
|
192
|
+
} catch (e) {
|
|
193
|
+
if (e instanceof Error && e.message.includes("symlink")) throw e;
|
|
194
|
+
// Component doesn't exist — stop re-validating, retry realpathSync
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
// Issue #2 fix: verify resolvedBase itself is not a symlink (TOCTOU
|
|
200
|
+
// between realpathSync and the ancestor walk). If a symlink was
|
|
201
|
+
// created at the base path after realpathSync returned, catch it.
|
|
202
|
+
let resolvedBaseStat: fs.Stats;
|
|
203
|
+
try {
|
|
204
|
+
resolvedBaseStat = fs.lstatSync(resolvedBase);
|
|
205
|
+
if (resolvedBaseStat.isSymbolicLink()) throw new Error("Refusing to create temp dir: resolved base is a symlink: " + resolvedBase);
|
|
206
|
+
} catch (e) {
|
|
207
|
+
if (e instanceof Error && e.message.includes("symlink")) throw e;
|
|
208
|
+
// resolvedBase doesn't exist yet — OK
|
|
209
|
+
}
|
|
210
|
+
// Verify resolved path has no symlink ancestors. realpathSync follows
|
|
211
|
+
// symlinks, so if any ancestor is a symlink the resolved path will be
|
|
212
|
+
// inside the attacker's target. Catch that by walking the resolved path.
|
|
213
|
+
const resolvedParts = resolvedBase.split(path.sep);
|
|
214
|
+
let resolvedAccumulated = "";
|
|
215
|
+
if (resolvedParts[0] === "") resolvedAccumulated = "/"; // Unix root
|
|
216
|
+
for (let i = 1; i < resolvedParts.length; i++) {
|
|
217
|
+
if (resolvedParts[i] === "") continue;
|
|
218
|
+
resolvedAccumulated = path.join(resolvedAccumulated, resolvedParts[i]);
|
|
219
|
+
try {
|
|
220
|
+
const stat = fs.lstatSync(resolvedAccumulated);
|
|
221
|
+
if (stat.isSymbolicLink()) throw new Error("Refusing to create temp dir: resolved path contains symlink ancestor: " + resolvedAccumulated);
|
|
222
|
+
} catch (e) {
|
|
223
|
+
if (e instanceof Error && e.message.includes("symlink")) throw e;
|
|
224
|
+
// Component doesn't exist — OK
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
77
228
|
const rawTempDir = fs.mkdtempSync(path.join(resolvedBase, prefix));
|
|
78
229
|
try {
|
|
79
230
|
const stat = fs.lstatSync(rawTempDir);
|
|
@@ -85,7 +236,10 @@ function createSafeTempDir(base: string, prefix: string): string {
|
|
|
85
236
|
}
|
|
86
237
|
throw e;
|
|
87
238
|
}
|
|
88
|
-
|
|
239
|
+
const resolved = fs.realpathSync(rawTempDir);
|
|
240
|
+
// Track for global cleanup on shutdown / crash
|
|
241
|
+
createdTempDirs.add(resolved);
|
|
242
|
+
return resolved;
|
|
89
243
|
}
|
|
90
244
|
|
|
91
245
|
export function buildPiWorkerArgs(input: BuildPiWorkerArgsInput): BuildPiWorkerArgsResult {
|
|
@@ -123,10 +277,9 @@ export function buildPiWorkerArgs(input: BuildPiWorkerArgsInput): BuildPiWorkerA
|
|
|
123
277
|
|
|
124
278
|
let tempDir: string | undefined;
|
|
125
279
|
if (input.agent.systemPrompt) {
|
|
126
|
-
//
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
: os.tmpdir();
|
|
280
|
+
// Use pi's own config dir instead of /tmp so temp files live alongside
|
|
281
|
+
// other pi state and don't pollute the shared system temp dir.
|
|
282
|
+
const tmpBase = getPiTempBase();
|
|
130
283
|
tempDir = createSafeTempDir(tmpBase, `pi-crew-${process.pid}-`);
|
|
131
284
|
const promptPath = path.join(tempDir, `${input.agent.name.replace(/[^\w.-]/g, "_")}.md`);
|
|
132
285
|
fs.writeFileSync(promptPath, input.agent.systemPrompt, { mode: 0o600 });
|
|
@@ -135,9 +288,7 @@ export function buildPiWorkerArgs(input: BuildPiWorkerArgsInput): BuildPiWorkerA
|
|
|
135
288
|
|
|
136
289
|
if (input.task.length > TASK_ARG_LIMIT) {
|
|
137
290
|
if (!tempDir) {
|
|
138
|
-
const tmpBase =
|
|
139
|
-
? path.join(os.homedir(), ".pi-crew", "tmp")
|
|
140
|
-
: os.tmpdir();
|
|
291
|
+
const tmpBase = getPiTempBase();
|
|
141
292
|
tempDir = createSafeTempDir(tmpBase, `pi-crew-${process.pid}-`);
|
|
142
293
|
}
|
|
143
294
|
const taskPath = path.join(tempDir, "task.md");
|
|
@@ -171,8 +322,280 @@ export function buildPiWorkerArgs(input: BuildPiWorkerArgsInput): BuildPiWorkerA
|
|
|
171
322
|
export function cleanupTempDir(tempDir: string | undefined): void {
|
|
172
323
|
if (!tempDir) return;
|
|
173
324
|
try {
|
|
325
|
+
// CRITICAL: never rmSync a symlink. fs.rmSync with recursive:true
|
|
326
|
+
// FOLLOWS symlinks — use lstatSync (does not follow) to verify.
|
|
327
|
+
let lstat: fs.Stats;
|
|
328
|
+
try {
|
|
329
|
+
lstat = fs.lstatSync(tempDir);
|
|
330
|
+
} catch {
|
|
331
|
+
// Dir doesn't exist or inaccessible — best effort
|
|
332
|
+
createdTempDirs.delete(tempDir);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (lstat.isSymbolicLink()) {
|
|
336
|
+
// Symlinks should not be in createdTempDirs (createSafeTempDir
|
|
337
|
+
// rejects symlinked base dirs), but guard anyway.
|
|
338
|
+
createdTempDirs.delete(tempDir);
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
174
341
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
342
|
+
createdTempDirs.delete(tempDir);
|
|
175
343
|
} catch {
|
|
176
344
|
// Best effort.
|
|
177
345
|
}
|
|
178
346
|
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Clean up ALL temp dirs created in this process. Called from
|
|
350
|
+
* crew-cleanup.ts on session_shutdown to prevent accumulation of
|
|
351
|
+
* /tmp/pi-crew-* dirs when individual cleanupTempDir calls are missed
|
|
352
|
+
* (e.g. parent process killed before child-pi.ts settles).
|
|
353
|
+
*/
|
|
354
|
+
export function cleanupAllTrackedTempDirs(): { cleaned: number; failed: number } {
|
|
355
|
+
let cleaned = 0;
|
|
356
|
+
let failed = 0;
|
|
357
|
+
// Snapshot to avoid mutation during iteration
|
|
358
|
+
for (const dir of [...createdTempDirs]) {
|
|
359
|
+
try {
|
|
360
|
+
// CRITICAL: never rmSync a symlink. fs.rmSync with recursive:true
|
|
361
|
+
// FOLLOWS symlinks — use lstatSync to verify first.
|
|
362
|
+
let lstat: fs.Stats;
|
|
363
|
+
try {
|
|
364
|
+
lstat = fs.lstatSync(dir);
|
|
365
|
+
} catch {
|
|
366
|
+
// Dir gone or inaccessible — best effort cleanup
|
|
367
|
+
createdTempDirs.delete(dir);
|
|
368
|
+
failed++;
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (lstat.isSymbolicLink()) {
|
|
372
|
+
// Should never happen (createSafeTempDir rejects symlinked
|
|
373
|
+
// base), but guard anyway to prevent accidental target deletion.
|
|
374
|
+
createdTempDirs.delete(dir);
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
378
|
+
createdTempDirs.delete(dir);
|
|
379
|
+
cleaned++;
|
|
380
|
+
} catch {
|
|
381
|
+
failed++;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return { cleaned, failed };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* @internal Test-only: reset the in-memory `createdTempDirs` Set.
|
|
389
|
+
* Used by unit tests to ensure isolation between cases. Not exported
|
|
390
|
+
* via the public API surface.
|
|
391
|
+
*/
|
|
392
|
+
export function __test_resetTrackedTempDirs(): void {
|
|
393
|
+
createdTempDirs.clear();
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* @internal Test-only: get a snapshot of currently tracked temp dirs.
|
|
398
|
+
*/
|
|
399
|
+
export function __test_getTrackedTempDirs(): readonly string[] {
|
|
400
|
+
return [...createdTempDirs];
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Purge stale entries from createdTempDirs — directories that no longer
|
|
405
|
+
* exist on disk. This handles the case where a process crashed before
|
|
406
|
+
* cleanupAllTrackedTempDirs ran, leaving orphaned entries in the Set.
|
|
407
|
+
* Called at startup as a belt-and-suspenders measure alongside the
|
|
408
|
+
* periodic cleanupOrphanTempDirs.
|
|
409
|
+
*/
|
|
410
|
+
export function purgeStaleTrackedTempDirs(): { removed: number; remaining: number } {
|
|
411
|
+
let removed = 0;
|
|
412
|
+
for (const dir of [...createdTempDirs]) {
|
|
413
|
+
if (!fs.existsSync(dir)) {
|
|
414
|
+
createdTempDirs.delete(dir);
|
|
415
|
+
removed++;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return { removed, remaining: createdTempDirs.size };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Run startup purge to prevent unbounded Set growth from crash loops.
|
|
422
|
+
purgeStaleTrackedTempDirs();
|
|
423
|
+
|
|
424
|
+
/** Max age (ms) for orphan temp dirs. Anything older is considered abandoned. */
|
|
425
|
+
const ORPHAN_TEMP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24h
|
|
426
|
+
/** Cap dirs removed per call to avoid main-thread stalls. */
|
|
427
|
+
const ORPHAN_TEMP_CLEAN_BATCH_SIZE = 50;
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Remove orphan temp dirs in `~/.pi/agent/pi-crew/tmp/` older than the age
|
|
431
|
+
* threshold. This catches dirs left behind by parent processes that were
|
|
432
|
+
* SIGKILL'd (no graceful shutdown to call cleanupAllTrackedTempDirs).
|
|
433
|
+
*
|
|
434
|
+
* Called periodically by register.ts:tempReconcileTimer.
|
|
435
|
+
*
|
|
436
|
+
* @param now Current epoch ms (parameter for testability)
|
|
437
|
+
* @param baseDir Override base dir (for testing). Defaults to
|
|
438
|
+
* `<userPiRoot>/tmp/`.
|
|
439
|
+
*/
|
|
440
|
+
export function cleanupOrphanTempDirs(
|
|
441
|
+
now: number = Date.now(),
|
|
442
|
+
baseDir: string = path.join(userPiRoot(), "tmp"),
|
|
443
|
+
): { scanned: number; cleaned: number; failed: number } {
|
|
444
|
+
let scanned = 0;
|
|
445
|
+
let cleaned = 0;
|
|
446
|
+
let failed = 0;
|
|
447
|
+
try {
|
|
448
|
+
if (!fs.existsSync(baseDir)) return { scanned: 0, cleaned: 0, failed: 0 };
|
|
449
|
+
const entries = fs.readdirSync(baseDir, { withFileTypes: true });
|
|
450
|
+
// Only process pi-crew-* dirs to avoid touching unrelated files
|
|
451
|
+
const candidates = entries
|
|
452
|
+
.filter((e) => e.isDirectory() && e.name.startsWith("pi-crew-"))
|
|
453
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
454
|
+
.slice(0, ORPHAN_TEMP_CLEAN_BATCH_SIZE);
|
|
455
|
+
for (const entry of candidates) {
|
|
456
|
+
scanned++;
|
|
457
|
+
const dir = path.join(baseDir, entry.name);
|
|
458
|
+
// CRITICAL: never rmSync a symlink. fs.rmSync with recursive:true
|
|
459
|
+
// FOLLOWS symlinks — an attacker could plant a symlink to /etc and
|
|
460
|
+
// wipe the system. Use lstat (does not follow) and skip.
|
|
461
|
+
let lstat: fs.Stats;
|
|
462
|
+
try {
|
|
463
|
+
lstat = fs.lstatSync(dir);
|
|
464
|
+
} catch {
|
|
465
|
+
failed++;
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
if (lstat.isSymbolicLink()) continue;
|
|
469
|
+
// Skip dirs currently in use by this process. A long-running child
|
|
470
|
+
// pi (>24h) would otherwise have its prompt/task tmp dir deleted
|
|
471
|
+
// mid-execution, causing broken-pipe failures when the child
|
|
472
|
+
// reads the system prompt.
|
|
473
|
+
if (createdTempDirs.has(dir)) continue;
|
|
474
|
+
try {
|
|
475
|
+
// FIX: Perform lstatSync BEFORE statSync mtime check to close TOCTOU window.
|
|
476
|
+
// An attacker could plant a symlink between the early lstatSync (line 373) and statSync.
|
|
477
|
+
// If statSync follows the symlink, it reads the target's mtime, not the dir's.
|
|
478
|
+
// By checking lstatSync first, we skip the mtime check entirely for symlinks.
|
|
479
|
+
let preRmlstat: fs.Stats | undefined;
|
|
480
|
+
try {
|
|
481
|
+
preRmlstat = fs.lstatSync(dir);
|
|
482
|
+
} catch {
|
|
483
|
+
failed++;
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
if (!preRmlstat || preRmlstat.isSymbolicLink()) continue;
|
|
487
|
+
// Reuse preRmlstat (captured at line 408) — already verified non-symlink at line 415.
|
|
488
|
+
// Avoid calling lstatSync again to eliminate the TOCTOU window between
|
|
489
|
+
// preRmlstat lstatSync (line 408) and this mtime check.
|
|
490
|
+
// NOTE: This is a best-effort approximation. The mtime was captured at line 408,
|
|
491
|
+
// potentially seconds before the rmSync at line 420. If the directory was modified
|
|
492
|
+
// after line 408, the age check uses stale data. This could cause premature cleanup
|
|
493
|
+
// of dirs that were recently modified but appeared old based on cached mtime (±seconds jitter).
|
|
494
|
+
if (now - preRmlstat.mtimeMs > ORPHAN_TEMP_MAX_AGE_MS) {
|
|
495
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
496
|
+
createdTempDirs.delete(dir);
|
|
497
|
+
cleaned++;
|
|
498
|
+
}
|
|
499
|
+
} catch {
|
|
500
|
+
failed++;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
} catch {
|
|
504
|
+
/* skip if tmpdir unreadable */
|
|
505
|
+
}
|
|
506
|
+
return { scanned, cleaned, failed };
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Clean up orphan `pi-crew-*` prompt/task temp dirs left in the system
|
|
511
|
+
* `/tmp/` directory. Before commit 8ba270d these were the primary location
|
|
512
|
+
* for temp dirs; users who upgraded may have thousands of orphans (the
|
|
513
|
+
* user's /tmp had 2498 of these). The existing
|
|
514
|
+
* `reconcileOrphanedTempWorkspaces` only cleans dirs containing
|
|
515
|
+
* `.crew/state/runs/` (the run-state dirs), so prompt/task orphans are
|
|
516
|
+
* never touched.
|
|
517
|
+
*
|
|
518
|
+
* Strategy: remove `pi-crew-*` dirs in /tmp that DO NOT contain
|
|
519
|
+
* `.crew/state/runs/` AND are older than the age threshold. The age
|
|
520
|
+
* threshold protects active processes that might still be writing.
|
|
521
|
+
*
|
|
522
|
+
* Bounded to ORPHAN_TEMP_CLEAN_BATCH_SIZE dirs per call.
|
|
523
|
+
*
|
|
524
|
+
* @param now Current epoch ms (parameter for testability)
|
|
525
|
+
* @param tmpDirOverride Override /tmp dir (for testing). Defaults to
|
|
526
|
+
* `os.tmpdir()`.
|
|
527
|
+
*/
|
|
528
|
+
export function cleanupLegacyOrphanTempDirs(
|
|
529
|
+
now: number = Date.now(),
|
|
530
|
+
tmpDirOverride: string = os.tmpdir(),
|
|
531
|
+
): { scanned: number; cleaned: number; failed: number } {
|
|
532
|
+
const tmpDir = tmpDirOverride;
|
|
533
|
+
let scanned = 0;
|
|
534
|
+
let cleaned = 0;
|
|
535
|
+
let failed = 0;
|
|
536
|
+
try {
|
|
537
|
+
if (!fs.existsSync(tmpDir)) return { scanned: 0, cleaned: 0, failed: 0 };
|
|
538
|
+
const entries = fs.readdirSync(tmpDir, { withFileTypes: true });
|
|
539
|
+
const candidates = entries
|
|
540
|
+
.filter((e) => e.isDirectory() && e.name.startsWith("pi-crew-"))
|
|
541
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
542
|
+
.slice(0, ORPHAN_TEMP_CLEAN_BATCH_SIZE);
|
|
543
|
+
for (const entry of candidates) {
|
|
544
|
+
scanned++;
|
|
545
|
+
const dir = path.join(tmpDir, entry.name);
|
|
546
|
+
// Symlink guard
|
|
547
|
+
let lstat: fs.Stats;
|
|
548
|
+
try {
|
|
549
|
+
lstat = fs.lstatSync(dir);
|
|
550
|
+
} catch {
|
|
551
|
+
failed++;
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
if (lstat.isSymbolicLink()) continue;
|
|
555
|
+
// Skip dirs containing active run state — those are handled by
|
|
556
|
+
// reconcileOrphanedTempWorkspaces which has run-state semantics.
|
|
557
|
+
const crewDir = path.join(dir, ".crew");
|
|
558
|
+
let crewDirLstat: fs.Stats | undefined;
|
|
559
|
+
try {
|
|
560
|
+
crewDirLstat = fs.lstatSync(crewDir);
|
|
561
|
+
} catch {
|
|
562
|
+
// doesn't exist
|
|
563
|
+
}
|
|
564
|
+
if (crewDirLstat && !crewDirLstat.isSymbolicLink()) continue;
|
|
565
|
+
// Skip dirs currently tracked by this process (defense in depth:
|
|
566
|
+
// with 8ba270d the Set should never contain /tmp/ paths, but
|
|
567
|
+
// future code or external callers might).
|
|
568
|
+
if (createdTempDirs.has(dir)) continue;
|
|
569
|
+
try {
|
|
570
|
+
// FIX: Perform lstatSync BEFORE statSync mtime check to close TOCTOU window.
|
|
571
|
+
// An attacker could plant a symlink between the early lstatSync (line 457) and statSync.
|
|
572
|
+
// If statSync follows the symlink, it reads the target's mtime, not the dir's.
|
|
573
|
+
// By checking lstatSync first, we skip the mtime check entirely for symlinks.
|
|
574
|
+
let preRmlstat: fs.Stats;
|
|
575
|
+
try {
|
|
576
|
+
preRmlstat = fs.lstatSync(dir);
|
|
577
|
+
} catch {
|
|
578
|
+
failed++;
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
if (preRmlstat.isSymbolicLink()) continue;
|
|
582
|
+
// Reuse preRmlstat (captured at line 494) — already verified non-symlink at line 501.
|
|
583
|
+
// Avoid calling lstatSync again to eliminate the TOCTOU window between
|
|
584
|
+
// preRmlstat lstatSync (line 494) and this mtime check.
|
|
585
|
+
// NOTE: This is a best-effort approximation. The mtime was captured at line 494,
|
|
586
|
+
// potentially seconds before the rmSync at line 505. If the directory was modified
|
|
587
|
+
// after line 494, the age check uses stale data. This could cause premature cleanup
|
|
588
|
+
// of dirs that were recently modified but appeared old based on cached mtime (±seconds jitter).
|
|
589
|
+
if (now - preRmlstat.mtimeMs > ORPHAN_TEMP_MAX_AGE_MS) {
|
|
590
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
591
|
+
cleaned++;
|
|
592
|
+
}
|
|
593
|
+
} catch {
|
|
594
|
+
failed++;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
} catch {
|
|
598
|
+
/* skip if tmpdir unreadable */
|
|
599
|
+
}
|
|
600
|
+
return { scanned, cleaned, failed };
|
|
601
|
+
}
|
package/src/runtime/pi-spawn.ts
CHANGED
|
@@ -161,6 +161,7 @@ function validateExplicitBin(explicit: string): string | undefined {
|
|
|
161
161
|
}
|
|
162
162
|
} catch (e) {
|
|
163
163
|
if (e instanceof Error && e.message.includes("allowed prefixes")) throw e;
|
|
164
|
+
console.error("[pi-spawn] validateExplicitBin: unexpected realpathSync error:", e);
|
|
164
165
|
return undefined;
|
|
165
166
|
}
|
|
166
167
|
return resolved;
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* Distilled from pi-autoresearch's post-check / backpressure pattern.
|
|
6
6
|
*/
|
|
7
7
|
import { execFileSync } from "node:child_process";
|
|
8
|
+
import * as path from "node:path";
|
|
8
9
|
import { resolveShellForScript } from "../utils/resolve-shell.ts";
|
|
9
10
|
import { sanitizeEnvSecrets } from "../utils/env-filter.ts";
|
|
10
11
|
|
|
@@ -56,9 +57,8 @@ function resolveScriptPath(config: PostCheckConfig): string | undefined {
|
|
|
56
57
|
* If no script path is available (neither config nor env var), the check
|
|
57
58
|
* passes by default with a note.
|
|
58
59
|
*
|
|
59
|
-
* **Security note:** The script path is
|
|
60
|
-
*
|
|
61
|
-
* paths. No path containment validation is performed.
|
|
60
|
+
* **Security note:** The script path is validated to stay within `cwd`.
|
|
61
|
+
* Scripts that escape the working directory are rejected.
|
|
62
62
|
*
|
|
63
63
|
* @param config - Post-check configuration (script path and timeout)
|
|
64
64
|
* @param cwd - Working directory for script execution
|
|
@@ -77,6 +77,13 @@ export async function runPostCheck(config: PostCheckConfig, cwd: string): Promis
|
|
|
77
77
|
};
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
+
// M1: Validate that the script path is contained within cwd to prevent arbitrary file execution
|
|
81
|
+
const resolved = path.resolve(cwd, scriptPath);
|
|
82
|
+
const resolvedCwd = path.resolve(cwd);
|
|
83
|
+
if (!resolved.startsWith(resolvedCwd + path.sep) && resolved !== resolvedCwd) {
|
|
84
|
+
throw new Error(`Security: PI_CREW_POST_CHECK_SCRIPT escapes cwd: ${scriptPath}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
80
87
|
const startTime = Date.now();
|
|
81
88
|
|
|
82
89
|
return new Promise<PostCheckResult>((resolve) => {
|
|
@@ -87,7 +94,7 @@ export async function runPostCheck(config: PostCheckConfig, cwd: string): Promis
|
|
|
87
94
|
timeout: timeoutMs,
|
|
88
95
|
encoding: "utf-8",
|
|
89
96
|
maxBuffer: 10 * 1024 * 1024, // 10 MB
|
|
90
|
-
env: { ...sanitizeEnvSecrets(process.env, { allowList: ["PATH", "HOME", "USER", "USERPROFILE", "TEMP", "TMP", "TMPDIR", "LANG", "LC_ALL", "ComSpec", "SystemRoot", "
|
|
97
|
+
env: { ...sanitizeEnvSecrets(process.env, { allowList: ["PATH", "HOME", "USER", "USERPROFILE", "TEMP", "TMP", "TMPDIR", "LANG", "LC_ALL", "ComSpec", "SystemRoot", "PI_CREW_*"] }), PI_CREW_POST_CHECK: "1" },
|
|
91
98
|
});
|
|
92
99
|
|
|
93
100
|
const durationMs = Date.now() - startTime;
|