@czottmann/pi-automode 1.13.0 → 1.15.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/CHANGELOG.md +19 -0
- package/README.md +5 -1
- package/extensions/auto-mode/classifier.ts +126 -13
- package/extensions/auto-mode/config.ts +7 -3
- package/extensions/auto-mode/constants.ts +2 -0
- package/extensions/auto-mode/hard-deny.ts +134 -23
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [1.15.0] - 2026-08-28
|
|
8
|
+
|
|
9
|
+
## Bug fixes
|
|
10
|
+
|
|
11
|
+
- **OMP 18 classifier compatibility** — Support OMP 18 model registries that lack `complete()` and `getProvider()`. Load the legacy completion API only for these registries. Keep current Pi on its runtime registry path so extension-registered providers remain available. Thanks, @NarryG! (#29)
|
|
12
|
+
|
|
13
|
+
## [1.14.0] - 2026-08-27
|
|
14
|
+
|
|
15
|
+
## Bug fixes
|
|
16
|
+
|
|
17
|
+
- **Classifier stream timeout** — Apply `classifierTimeoutMs` to the full response stream. Provider behavior cannot keep classifier calls pending after the deadline. Parent cancellation remains active. Reject values above the Node.js timer limit. (#30)
|
|
18
|
+
- **OS temp-directory deletes** — Stop hard-denying recursive-delete subtrees under `os.tmpdir()` and `/tmp`. On macOS these resolve into `/private/tmp` and `/private/var/folders`, which matched the `/private` system root and blocked every temp cleanup. Deleting a temp root itself stays blocked. (#31)
|
|
19
|
+
- **Validated temp-root declarations** — Derive the exempt temp roots only from launcher-declared values that stay safe: reject values such as `/`, empty strings, aliases of `HOME`, `/`, or a system root, and ancestors of `HOME`. Without validation, a malformed `TMPDIR` could disable deterministic denials for protected targets, and a broad `permissions.allow` rule could then allow the action without classifier review. Recompute candidates when the effective tmpdir changes. (#31)
|
|
20
|
+
|
|
5
21
|
## [1.13.0] - 2026-08-25
|
|
6
22
|
|
|
7
23
|
## New features
|
|
@@ -35,5 +51,8 @@ All notable changes to this project are documented in this file.
|
|
|
35
51
|
- **Project config trust gate** — Ignore `.pi/automode.local.json` and `.pi/automode.json` until Pi trusts the project. Apply the trust gate during startup and config reloads. (#16)
|
|
36
52
|
- **In-memory observability logs** — Write logs to an extension-owned directory (`~/.pi/agent/extensions/pi-automode/logs/`) instead of the launching project directory. Thanks, @HerbertGao! (#13)
|
|
37
53
|
|
|
54
|
+
[Unreleased]: https://github.com/czottmann/pi-automode/compare/v1.15.0...HEAD
|
|
55
|
+
[1.15.0]: https://github.com/czottmann/pi-automode/compare/v1.14.0...v1.15.0
|
|
56
|
+
[1.14.0]: https://github.com/czottmann/pi-automode/compare/v1.13.0...v1.14.0
|
|
38
57
|
[1.13.0]: https://github.com/czottmann/pi-automode/compare/v1.12.0...v1.13.0
|
|
39
58
|
[1.12.0]: https://github.com/czottmann/pi-automode/compare/v1.11.0...v1.12.0
|
package/README.md
CHANGED
|
@@ -8,6 +8,10 @@ It is not a sandbox. Extensions run in the Pi process. A malicious extension can
|
|
|
8
8
|
|
|
9
9
|
Pi-automode does not guard user `!` or `!!` shell commands. It guards only agent tool calls. Use it to reduce unsafe autonomous tool use. Do not use it as an OS security boundary.
|
|
10
10
|
|
|
11
|
+
## Compatibility
|
|
12
|
+
|
|
13
|
+
Pi-automode supports Pi and Oh My Pi (OMP) 18. It automatically uses OMP's legacy completion API. The integration needs no OMP-specific configuration.
|
|
14
|
+
|
|
11
15
|
## Install
|
|
12
16
|
|
|
13
17
|
From npm:
|
|
@@ -101,7 +105,7 @@ The extension blocks these before any allow or classifier decision:
|
|
|
101
105
|
- SSH `authorized_keys` writes
|
|
102
106
|
- cron, launch agent, and system service persistence
|
|
103
107
|
- TLS/certificate/auth weakening patterns
|
|
104
|
-
- root, home, and system-path destructive deletes
|
|
108
|
+
- root, home, and system-path destructive deletes. Subtrees of validated launcher-declared temp directories are treated as disposable. Declared roots that alias `HOME`, `/`, or a system root, or that contain `HOME`, are rejected instead.
|
|
105
109
|
- edits to `.pi/automode*`, `.pi` auto-mode files, and this extension's safety-control files
|
|
106
110
|
|
|
107
111
|
After these checks, pi-automode applies `permissions.allow`. Protected `write` and `edit` targets continue to the classifier.
|
|
@@ -84,10 +84,9 @@ async function resolveClassifier(
|
|
|
84
84
|
};
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
-
const rawComplete
|
|
88
|
-
ctx.modelRegistry
|
|
89
|
-
|
|
90
|
-
completeSimpleWithRegistry(ctx, callModel, context, options);
|
|
87
|
+
const { rawComplete, simpleComplete } = createRegistryCompletionFns(
|
|
88
|
+
ctx.modelRegistry,
|
|
89
|
+
);
|
|
91
90
|
const completionPlan = createClassifierCompletionPlan(
|
|
92
91
|
model,
|
|
93
92
|
config.classifierReasoningLevel,
|
|
@@ -125,6 +124,70 @@ export type ClassifierCompletionFn = (
|
|
|
125
124
|
},
|
|
126
125
|
) => Promise<AssistantMessage>;
|
|
127
126
|
|
|
127
|
+
type RegistryCompletionApi = {
|
|
128
|
+
complete?: ClassifierCompletionFn;
|
|
129
|
+
getProvider?: (provider: string) => {
|
|
130
|
+
streamSimple: (
|
|
131
|
+
model: Model<any>,
|
|
132
|
+
context: { systemPrompt: string; messages: UserMessage[] },
|
|
133
|
+
options: Parameters<ClassifierCompletionFn>[2],
|
|
134
|
+
) => { result: () => Promise<AssistantMessage> };
|
|
135
|
+
} | undefined;
|
|
136
|
+
};
|
|
137
|
+
type ClassifierCompletionFallbacks = {
|
|
138
|
+
rawComplete: ClassifierCompletionFn;
|
|
139
|
+
simpleComplete: ClassifierCompletionFn;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
type ClassifierCompletionFallbackLoader =
|
|
143
|
+
() => Promise<ClassifierCompletionFallbacks>;
|
|
144
|
+
|
|
145
|
+
// Static import would initialize deprecated compat registries on current Pi;
|
|
146
|
+
// OMP rewrites this literal dynamic import to its native pi-ai module.
|
|
147
|
+
async function loadCompatCompletionFns(): Promise<ClassifierCompletionFallbacks> {
|
|
148
|
+
const { complete, completeSimple } = await import(
|
|
149
|
+
"@earendil-works/pi-ai/compat"
|
|
150
|
+
);
|
|
151
|
+
return {
|
|
152
|
+
rawComplete: complete as ClassifierCompletionFn,
|
|
153
|
+
simpleComplete: completeSimple as ClassifierCompletionFn,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Prefer the current runtime registry so extension-registered providers remain
|
|
159
|
+
* visible. Older Pi-family runtimes (including OMP 18) expose neither
|
|
160
|
+
* `complete` nor `getProvider`; lazily load the compat API they already use.
|
|
161
|
+
*/
|
|
162
|
+
export function createRegistryCompletionFns(
|
|
163
|
+
registry: RegistryCompletionApi,
|
|
164
|
+
fallbackLoader: ClassifierCompletionFallbackLoader =
|
|
165
|
+
loadCompatCompletionFns,
|
|
166
|
+
): ClassifierCompletionFallbacks {
|
|
167
|
+
let fallbackPromise: Promise<ClassifierCompletionFallbacks> | undefined;
|
|
168
|
+
const rawComplete: ClassifierCompletionFn =
|
|
169
|
+
typeof registry.complete === "function"
|
|
170
|
+
? (model, context, options) =>
|
|
171
|
+
registry.complete!.call(registry, model, context, options)
|
|
172
|
+
: async (model, context, options) =>
|
|
173
|
+
(await (fallbackPromise ??= fallbackLoader())).rawComplete(
|
|
174
|
+
model,
|
|
175
|
+
context,
|
|
176
|
+
options,
|
|
177
|
+
);
|
|
178
|
+
const simpleComplete: ClassifierCompletionFn =
|
|
179
|
+
typeof registry.getProvider === "function"
|
|
180
|
+
? (model, context, options) =>
|
|
181
|
+
completeSimpleWithRegistry(registry, model, context, options)
|
|
182
|
+
: async (model, context, options) =>
|
|
183
|
+
(await (fallbackPromise ??= fallbackLoader())).simpleComplete(
|
|
184
|
+
model,
|
|
185
|
+
context,
|
|
186
|
+
options,
|
|
187
|
+
);
|
|
188
|
+
return { rawComplete, simpleComplete };
|
|
189
|
+
}
|
|
190
|
+
|
|
128
191
|
export type RetryOptions = {
|
|
129
192
|
maxAttempts?: number;
|
|
130
193
|
maxTokens?: number;
|
|
@@ -155,19 +218,67 @@ export type ClassifierCompletionPlan = {
|
|
|
155
218
|
reasoningLevel?: Exclude<EffectiveClassifierReasoningLevel, "off">;
|
|
156
219
|
};
|
|
157
220
|
|
|
221
|
+
async function completeClassifierAttempt(
|
|
222
|
+
completeFn: ClassifierCompletionFn,
|
|
223
|
+
model: Model<any>,
|
|
224
|
+
prompt: Parameters<ClassifierCompletionFn>[1],
|
|
225
|
+
parentSignal: AbortSignal | undefined,
|
|
226
|
+
options: Omit<Parameters<ClassifierCompletionFn>[2], "signal">,
|
|
227
|
+
): Promise<AssistantMessage> {
|
|
228
|
+
if (options.timeoutMs === undefined) {
|
|
229
|
+
return completeFn(model, prompt, {
|
|
230
|
+
...options,
|
|
231
|
+
...(parentSignal === undefined ? {} : { signal: parentSignal }),
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const controller = new AbortController();
|
|
236
|
+
const onParentAbort = () => controller.abort(parentSignal?.reason);
|
|
237
|
+
if (parentSignal?.aborted) onParentAbort();
|
|
238
|
+
else parentSignal?.addEventListener("abort", onParentAbort, { once: true });
|
|
239
|
+
|
|
240
|
+
let onAbort: (() => void) | undefined;
|
|
241
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
242
|
+
onAbort = () => {
|
|
243
|
+
const reason = controller.signal.reason;
|
|
244
|
+
reject(reason instanceof Error ? reason : new Error("Classifier request aborted."));
|
|
245
|
+
};
|
|
246
|
+
if (controller.signal.aborted) onAbort();
|
|
247
|
+
else controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
248
|
+
});
|
|
249
|
+
const timer = setTimeout(() => {
|
|
250
|
+
controller.abort(
|
|
251
|
+
new Error(`Classifier request timed out after ${options.timeoutMs} ms.`),
|
|
252
|
+
);
|
|
253
|
+
}, options.timeoutMs);
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
return await Promise.race([
|
|
257
|
+
completeFn(model, prompt, {
|
|
258
|
+
...options,
|
|
259
|
+
signal: controller.signal,
|
|
260
|
+
}),
|
|
261
|
+
aborted,
|
|
262
|
+
]);
|
|
263
|
+
} finally {
|
|
264
|
+
clearTimeout(timer);
|
|
265
|
+
if (onAbort) controller.signal.removeEventListener("abort", onAbort);
|
|
266
|
+
parentSignal?.removeEventListener("abort", onParentAbort);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
158
270
|
/**
|
|
159
271
|
* Run normalized Pi AI completion through the provider in Pi's runtime registry.
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
* that API when the project's minimum supported Pi version includes it.
|
|
272
|
+
* Callers use this only when the registry exposes `getProvider`; legacy
|
|
273
|
+
* registries take the compat completion path instead.
|
|
163
274
|
*/
|
|
164
275
|
async function completeSimpleWithRegistry(
|
|
165
|
-
|
|
276
|
+
registry: RegistryCompletionApi,
|
|
166
277
|
model: Model<any>,
|
|
167
278
|
context: { systemPrompt: string; messages: UserMessage[] },
|
|
168
279
|
options: Parameters<ClassifierCompletionFn>[2],
|
|
169
280
|
): Promise<AssistantMessage> {
|
|
170
|
-
const provider =
|
|
281
|
+
const provider = registry.getProvider?.(model.provider);
|
|
171
282
|
if (!provider) throw new Error(`Unknown provider: ${model.provider}`);
|
|
172
283
|
return provider.streamSimple(model, context, options).result();
|
|
173
284
|
}
|
|
@@ -435,14 +546,15 @@ export async function classifyWithRetry(
|
|
|
435
546
|
const started = Date.now();
|
|
436
547
|
let response: AssistantMessage;
|
|
437
548
|
try {
|
|
438
|
-
response = await
|
|
549
|
+
response = await completeClassifierAttempt(
|
|
550
|
+
completeFn,
|
|
439
551
|
classifier.model,
|
|
440
552
|
prompt,
|
|
553
|
+
signal,
|
|
441
554
|
{
|
|
442
555
|
apiKey: classifier.apiKey,
|
|
443
556
|
headers: classifier.headers,
|
|
444
557
|
env: classifier.env,
|
|
445
|
-
signal,
|
|
446
558
|
maxTokens,
|
|
447
559
|
...(temperature === undefined ? {} : { temperature }),
|
|
448
560
|
...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
|
|
@@ -505,7 +617,8 @@ export async function classifyInStages(
|
|
|
505
617
|
const fastStarted = Date.now();
|
|
506
618
|
let fastResponse: AssistantMessage;
|
|
507
619
|
try {
|
|
508
|
-
fastResponse = await
|
|
620
|
+
fastResponse = await completeClassifierAttempt(
|
|
621
|
+
completeFn,
|
|
509
622
|
classifier.model,
|
|
510
623
|
{
|
|
511
624
|
systemPrompt: prompt.systemPrompt,
|
|
@@ -515,11 +628,11 @@ export async function classifyInStages(
|
|
|
515
628
|
stageMessage(CLASSIFIER_FAST_INSTRUCTION),
|
|
516
629
|
],
|
|
517
630
|
},
|
|
631
|
+
signal,
|
|
518
632
|
{
|
|
519
633
|
apiKey: classifier.apiKey,
|
|
520
634
|
headers: classifier.headers,
|
|
521
635
|
env: classifier.env,
|
|
522
|
-
signal,
|
|
523
636
|
// Reasoning and OpenAI-compatible models may consume hidden reasoning,
|
|
524
637
|
// control, and EOS tokens before emitting the required visible digit.
|
|
525
638
|
maxTokens: options.fastClassifierMaxTokens ??
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
DEFAULT_MAX_USER_TRANSCRIPT_TOKENS,
|
|
23
23
|
DEFAULT_PROTECTED_PATHS,
|
|
24
24
|
DEFAULT_SOFT_DENY,
|
|
25
|
+
MAX_CLASSIFIER_TIMEOUT_MS,
|
|
25
26
|
PI_GLOBAL_SETTINGS,
|
|
26
27
|
PI_LEGACY_GLOBAL_SETTINGS,
|
|
27
28
|
PI_PROJECT_LOCAL_SETTINGS,
|
|
@@ -324,10 +325,11 @@ export function validateSettingsFile(
|
|
|
324
325
|
if (
|
|
325
326
|
hasOwn(autoMode, "classifierTimeoutMs") &&
|
|
326
327
|
(!Number.isInteger(autoMode.classifierTimeoutMs) ||
|
|
327
|
-
(autoMode.classifierTimeoutMs as number) < 1000
|
|
328
|
+
(autoMode.classifierTimeoutMs as number) < 1000 ||
|
|
329
|
+
(autoMode.classifierTimeoutMs as number) > MAX_CLASSIFIER_TIMEOUT_MS)
|
|
328
330
|
) {
|
|
329
331
|
diagnostics.push(
|
|
330
|
-
`${source}: autoMode.classifierTimeoutMs must be an integer
|
|
332
|
+
`${source}: autoMode.classifierTimeoutMs must be an integer from 1000 through ${MAX_CLASSIFIER_TIMEOUT_MS}`,
|
|
331
333
|
);
|
|
332
334
|
}
|
|
333
335
|
if (
|
|
@@ -591,7 +593,9 @@ function validFastClassifierBudget(value: unknown): value is number {
|
|
|
591
593
|
}
|
|
592
594
|
|
|
593
595
|
function validClassifierTimeout(value: unknown): value is number {
|
|
594
|
-
return Number.isInteger(value) &&
|
|
596
|
+
return Number.isInteger(value) &&
|
|
597
|
+
Number(value) >= 1000 &&
|
|
598
|
+
Number(value) <= MAX_CLASSIFIER_TIMEOUT_MS;
|
|
595
599
|
}
|
|
596
600
|
|
|
597
601
|
function applyAutoModeScalars(
|
|
@@ -61,6 +61,8 @@ export const DENIAL_HISTORY_LIMIT = 12;
|
|
|
61
61
|
|
|
62
62
|
/** Per-request timeout for classifier completions (fast and detailed stages). */
|
|
63
63
|
export const DEFAULT_CLASSIFIER_TIMEOUT_MS = 20_000;
|
|
64
|
+
/** Largest timeout that Node can represent without reducing it to 1 ms. */
|
|
65
|
+
export const MAX_CLASSIFIER_TIMEOUT_MS = 2_147_483_647;
|
|
64
66
|
|
|
65
67
|
/** Built-in trusted environment. Users extend this with `$defaults`. */
|
|
66
68
|
export const DEFAULT_ENVIRONMENT = [
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { statSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
2
3
|
import { resolve } from "node:path";
|
|
3
4
|
import {
|
|
4
5
|
analyzeBash,
|
|
@@ -77,9 +78,115 @@ function matchesPathRoot(path: string, root: string): boolean {
|
|
|
77
78
|
return isSameExistingPath(path.slice(0, root.length), root);
|
|
78
79
|
}
|
|
79
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Top-level directories whose deletion or wholesale modification is a
|
|
83
|
+
* system-wide event. Shared between candidate validation and path
|
|
84
|
+
* classification; do not inline copies.
|
|
85
|
+
*/
|
|
86
|
+
const SYSTEM_ROOTS: ReadonlyArray<string> = [
|
|
87
|
+
"/bin",
|
|
88
|
+
"/boot",
|
|
89
|
+
"/dev",
|
|
90
|
+
"/etc",
|
|
91
|
+
"/home",
|
|
92
|
+
"/lib",
|
|
93
|
+
"/lib64",
|
|
94
|
+
"/Library",
|
|
95
|
+
"/private",
|
|
96
|
+
"/proc",
|
|
97
|
+
"/root",
|
|
98
|
+
"/run",
|
|
99
|
+
"/sbin",
|
|
100
|
+
"/sys",
|
|
101
|
+
"/System",
|
|
102
|
+
"/usr",
|
|
103
|
+
"/var",
|
|
104
|
+
];
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Normalize a proposed temp-root value into a comparable absolute path.
|
|
108
|
+
* Returns undefined for values that cannot denote a subdirectory: the
|
|
109
|
+
* empty string, `/`, and slash-only artifacts.
|
|
110
|
+
*/
|
|
111
|
+
function normalizeRootCandidate(value: string): string | undefined {
|
|
112
|
+
const stripped = value.replace(/\/+$/, "");
|
|
113
|
+
// An empty stripped value must not fall through to `resolve()`, which
|
|
114
|
+
// would silently turn `/` into the process working directory.
|
|
115
|
+
if (!stripped) return undefined;
|
|
116
|
+
const normalized = resolve(stripped);
|
|
117
|
+
if (normalized === "/") return undefined;
|
|
118
|
+
return normalized;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* True when a candidate temp root would weaken the deterministic deny tiers:
|
|
123
|
+
* it aliases (exact, case-folded, or dev/inode) `HOME`, `/`, or any system
|
|
124
|
+
* root, or it is a proper ancestor of the canonical home directory.
|
|
125
|
+
*
|
|
126
|
+
* Dev/inode identity covers symlinked spellings of existing directories;
|
|
127
|
+
* string comparison alone handles candidates that do not exist yet. See
|
|
128
|
+
* issue #31: without these guards, `TMPDIR=/` reduced every absolute path
|
|
129
|
+
* below an empty-string prefix match, and `TMPDIR=/private` made
|
|
130
|
+
* `/private/etc/**` disposable.
|
|
131
|
+
*/
|
|
132
|
+
function conflictsWithProtectedRoots(candidate: string, home: string): boolean {
|
|
133
|
+
if (candidate === "/") return true;
|
|
134
|
+
for (const protectedRoot of ["/", home, ...SYSTEM_ROOTS]) {
|
|
135
|
+
const canonical = resolve(protectedRoot);
|
|
136
|
+
if (
|
|
137
|
+
candidate === canonical ||
|
|
138
|
+
candidate.toLowerCase() === canonical.toLowerCase()
|
|
139
|
+
) {
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
if (isSameExistingPath(candidate, canonical)) return true;
|
|
143
|
+
}
|
|
144
|
+
const homeCanonical = resolvePathForPolicy(home) ?? resolve(home);
|
|
145
|
+
return homeCanonical.toLowerCase().startsWith(`${candidate.toLowerCase()}/`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
let cachedTempRoots: ReadonlyArray<string> | undefined;
|
|
149
|
+
let cachedTmpdirValue: string | undefined;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Validated launcher-declared temp-dir roots whose subtrees are treated as
|
|
153
|
+
* disposable by `isRootHomeOrSystemPath`: the platform tmpdir, plus `/tmp` on
|
|
154
|
+
* macOS where it exists independently of `os.tmpdir()`. Each root appears in
|
|
155
|
+
* canonical and resolved spelling because callers pass symlink-resolved
|
|
156
|
+
* policy paths (`/tmp` → `/private/tmp` on macOS) and unresolved fallbacks
|
|
157
|
+
* alike. Values from `os.tmpdir()` are not trusted blindly; see
|
|
158
|
+
* `conflictsWithProtectedRoots`. The roots themselves are never exempt:
|
|
159
|
+
* deleting one is a system-wide delete.
|
|
160
|
+
*
|
|
161
|
+
* The memoization keys on the effective `os.tmpdir()` return value so tests
|
|
162
|
+
* can mutate `TMPDIR`, `TMP`, or `TEMP` between calls.
|
|
163
|
+
*/
|
|
164
|
+
export function tempRootCandidates(): ReadonlyArray<string> {
|
|
165
|
+
const currentTmpdir = tmpdir();
|
|
166
|
+
if (cachedTempRoots && cachedTmpdirValue === currentTmpdir) {
|
|
167
|
+
return cachedTempRoots;
|
|
168
|
+
}
|
|
169
|
+
cachedTmpdirValue = currentTmpdir;
|
|
170
|
+
cachedTempRoots = (() => {
|
|
171
|
+
const roots = new Set<string>();
|
|
172
|
+
const consider = (value: string) => {
|
|
173
|
+
const candidate = normalizeRootCandidate(value);
|
|
174
|
+
if (!candidate || conflictsWithProtectedRoots(candidate, HOME)) return;
|
|
175
|
+
roots.add(candidate);
|
|
176
|
+
const resolved = resolvePathForPolicy(candidate);
|
|
177
|
+
if (resolved) roots.add(resolved);
|
|
178
|
+
};
|
|
179
|
+
consider(currentTmpdir);
|
|
180
|
+
if (process.platform === "darwin") consider("/tmp");
|
|
181
|
+
return [...roots];
|
|
182
|
+
})();
|
|
183
|
+
return cachedTempRoots;
|
|
184
|
+
}
|
|
185
|
+
|
|
80
186
|
/**
|
|
81
187
|
* True for `/`, the user's home root, or a top-level system root such as
|
|
82
|
-
* `/etc`, `/usr`, or `/var`. Excludes the home *subtree
|
|
188
|
+
* `/etc`, `/usr`, or `/var`. Excludes the home *subtree* and the subtrees of
|
|
189
|
+
* platform temp directories (`os.tmpdir()` and `/tmp` on macOS).
|
|
83
190
|
*
|
|
84
191
|
* On some distros (e.g. Fedora Silverblue) HOME lives under `/var`, which is
|
|
85
192
|
* in `systemRoots`. Without the subtree exemption, `path.startsWith("/var/")`
|
|
@@ -87,32 +194,36 @@ function matchesPathRoot(path: string, root: string): boolean {
|
|
|
87
194
|
* `rm -rf ~/...`. HOME itself is still matched below, so `rm -rf ~` stays
|
|
88
195
|
* blocked. `home` is a parameter so this can be unit-tested with a synthetic
|
|
89
196
|
* `/var/home/...` value.
|
|
197
|
+
*
|
|
198
|
+
* The temp exemption mirrors the home one and covers cleanup of directories
|
|
199
|
+
* created with `mktemp`, `os.tmpdir()`, or plain `/tmp` paths. On macOS these
|
|
200
|
+
* resolve into `/private/tmp` or `/private/var/folders`, which used to match
|
|
201
|
+
* the `/private` system root and hard-deny every temp cleanup. Deleting a
|
|
202
|
+
* temp root itself still returns true; `tempRoots` is injectable for tests.
|
|
203
|
+
*
|
|
204
|
+
* Protection order matters (issue #31): exact `/`, the exact home root, and
|
|
205
|
+
* system roots win over every exemption. Injected `tempRoots` values are
|
|
206
|
+
* validated per call so hostile or malformed candidates cannot weaken the
|
|
207
|
+
* deterministic tiers.
|
|
90
208
|
*/
|
|
91
|
-
export function isRootHomeOrSystemPath(
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
"/lib",
|
|
99
|
-
"/lib64",
|
|
100
|
-
"/Library",
|
|
101
|
-
"/private",
|
|
102
|
-
"/proc",
|
|
103
|
-
"/root",
|
|
104
|
-
"/run",
|
|
105
|
-
"/sbin",
|
|
106
|
-
"/sys",
|
|
107
|
-
"/System",
|
|
108
|
-
"/usr",
|
|
109
|
-
"/var",
|
|
110
|
-
];
|
|
209
|
+
export function isRootHomeOrSystemPath(
|
|
210
|
+
path: string,
|
|
211
|
+
home: string,
|
|
212
|
+
tempRoots: ReadonlyArray<string> = tempRootCandidates(),
|
|
213
|
+
): boolean {
|
|
214
|
+
if (path === "/") return true;
|
|
215
|
+
if (path === home || isSameExistingPath(path, home)) return true;
|
|
111
216
|
if (matchesPathRoot(path, home) && path.length > home.length) return false;
|
|
217
|
+
for (const root of tempRoots) {
|
|
218
|
+
const candidate = normalizeRootCandidate(root);
|
|
219
|
+
if (!candidate || conflictsWithProtectedRoots(candidate, home)) continue;
|
|
220
|
+
if (!matchesPathRoot(path, candidate)) continue;
|
|
221
|
+
// Subtree: disposable. Exact match: the temp root stays protected.
|
|
222
|
+
return path.length > candidate.length ? false : true;
|
|
223
|
+
}
|
|
112
224
|
return (
|
|
113
|
-
path === "/" ||
|
|
114
225
|
matchesPathRoot(path, home) ||
|
|
115
|
-
|
|
226
|
+
SYSTEM_ROOTS.some((root) => matchesPathRoot(path, root))
|
|
116
227
|
);
|
|
117
228
|
}
|
|
118
229
|
|