opencode-fs-plugin 0.0.0-stage → 1.0.2
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/INSTALL.md +186 -0
- package/LICENSE +225 -0
- package/README.md +266 -2
- package/SPEC.md +45 -0
- package/package.json +63 -4
- package/skills/filesystem/SKILL.md +153 -0
- package/src/core/errors.ts +81 -0
- package/src/core/format.ts +100 -0
- package/src/core/fsutil.ts +228 -0
- package/src/core/mode.ts +107 -0
- package/src/core/parallel.ts +76 -0
- package/src/core/permissions.ts +134 -0
- package/src/core/sandbox.ts +270 -0
- package/src/core/schema.ts +16 -0
- package/src/core/stream.ts +84 -0
- package/src/core/types.ts +51 -0
- package/src/index.ts +172 -0
- package/src/tools/cat.ts +90 -0
- package/src/tools/chmod.ts +93 -0
- package/src/tools/cp.ts +136 -0
- package/src/tools/cut.ts +93 -0
- package/src/tools/df.ts +78 -0
- package/src/tools/diff.ts +136 -0
- package/src/tools/du.ts +102 -0
- package/src/tools/find.ts +181 -0
- package/src/tools/grep.ts +205 -0
- package/src/tools/gzip.ts +164 -0
- package/src/tools/hash.ts +84 -0
- package/src/tools/head.ts +78 -0
- package/src/tools/ln.ts +98 -0
- package/src/tools/ls.ts +178 -0
- package/src/tools/mkdir.ts +70 -0
- package/src/tools/mktemp.ts +83 -0
- package/src/tools/mv.ts +135 -0
- package/src/tools/pipe.ts +107 -0
- package/src/tools/readlink.ts +90 -0
- package/src/tools/rm.ts +91 -0
- package/src/tools/rmdir.ts +117 -0
- package/src/tools/sed.ts +151 -0
- package/src/tools/sort.ts +73 -0
- package/src/tools/stat.ts +157 -0
- package/src/tools/tail.ts +74 -0
- package/src/tools/tar.ts +195 -0
- package/src/tools/tee.ts +51 -0
- package/src/tools/touch.ts +130 -0
- package/src/tools/tr.ts +123 -0
- package/src/tools/trash.ts +86 -0
- package/src/tools/truncate.ts +96 -0
- package/src/tools/uniq.ts +76 -0
- package/src/tools/wc.ts +97 -0
- package/src/tools/zip.ts +231 -0
package/src/core/mode.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { FsError } from "./errors.js";
|
|
7
|
+
|
|
8
|
+
const WHO = {
|
|
9
|
+
u: 0o700,
|
|
10
|
+
g: 0o070,
|
|
11
|
+
o: 0o007,
|
|
12
|
+
a: 0o777,
|
|
13
|
+
} as const;
|
|
14
|
+
|
|
15
|
+
const PERM = {
|
|
16
|
+
r: 0o444,
|
|
17
|
+
w: 0o222,
|
|
18
|
+
x: 0o111,
|
|
19
|
+
X: 0o111,
|
|
20
|
+
} as const;
|
|
21
|
+
|
|
22
|
+
export function parseMode(
|
|
23
|
+
mode: string,
|
|
24
|
+
base: number,
|
|
25
|
+
isDirectory: boolean,
|
|
26
|
+
umask = 0o022,
|
|
27
|
+
): number {
|
|
28
|
+
if (typeof mode !== "string" || mode.length === 0) {
|
|
29
|
+
throw new FsError("mode is empty.", "invalid");
|
|
30
|
+
}
|
|
31
|
+
if (/^[0-7]{3,4}$/.test(mode)) {
|
|
32
|
+
return Number.parseInt(mode, 8);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let result = base & 0o7777;
|
|
36
|
+
for (const clause of mode.split(",")) {
|
|
37
|
+
const match = /^([ugoa]*)([+\-=])(.*)$/.exec(clause);
|
|
38
|
+
if (match === null) throw new FsError(`Invalid mode: ${mode}`, "invalid");
|
|
39
|
+
const who = match[1] as string;
|
|
40
|
+
const op = match[2] as string;
|
|
41
|
+
const permissions = match[3] as string;
|
|
42
|
+
if (permissions.length === 0 && op !== "=") continue;
|
|
43
|
+
const whoMask =
|
|
44
|
+
who.length > 0
|
|
45
|
+
? [...who].reduce((mask, ch) => mask | WHO[ch as keyof typeof WHO], 0)
|
|
46
|
+
: ~umask & 0o777;
|
|
47
|
+
let bits = 0;
|
|
48
|
+
for (const ch of permissions) {
|
|
49
|
+
if (ch === "X") {
|
|
50
|
+
if (isDirectory || (result & 0o111) !== 0) bits |= PERM.X & whoMask;
|
|
51
|
+
} else if (ch === "s") {
|
|
52
|
+
bits |= ((who === "" || who.includes("u")) ? 0o4000 : 0) | ((who === "" || who.includes("g")) ? 0o2000 : 0);
|
|
53
|
+
} else if (ch === "t") {
|
|
54
|
+
bits |= who === "" || who.includes("o") || who.includes("a") ? 0o1000 : 0;
|
|
55
|
+
} else if (ch in PERM) {
|
|
56
|
+
bits |= PERM[ch as keyof typeof PERM] & whoMask;
|
|
57
|
+
} else {
|
|
58
|
+
throw new FsError(`Invalid mode: ${mode}`, "invalid");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (op === "+") result |= bits;
|
|
62
|
+
if (op === "-") result &= ~bits;
|
|
63
|
+
if (op === "=") result = (result & ~whoMask & 0o7777) | bits;
|
|
64
|
+
}
|
|
65
|
+
return result & 0o7777;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function formatMode(mode: number): string {
|
|
69
|
+
return `${fileType(mode)}${triplet(mode, 6, 0o4000, "s")}${triplet(mode, 3, 0o2000, "s")}${triplet(
|
|
70
|
+
mode,
|
|
71
|
+
0,
|
|
72
|
+
0o1000,
|
|
73
|
+
"t",
|
|
74
|
+
)}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function formatOctalMode(mode: number): string {
|
|
78
|
+
return (mode & 0o7777).toString(8).padStart(4, "0");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function triplet(mode: number, shift: number, special: number, specialChar: string): string {
|
|
82
|
+
const bits = (mode >> shift) & 0o7;
|
|
83
|
+
const execute = bits & 0o1;
|
|
84
|
+
const specialSet = (mode & special) !== 0;
|
|
85
|
+
return `${bits & 0o4 ? "r" : "-"}${bits & 0o2 ? "w" : "-"}${
|
|
86
|
+
specialSet ? (execute ? specialChar : specialChar.toUpperCase()) : execute ? "x" : "-"
|
|
87
|
+
}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function fileType(mode: number): string {
|
|
91
|
+
switch (mode & 0o170000) {
|
|
92
|
+
case 0o040000:
|
|
93
|
+
return "d";
|
|
94
|
+
case 0o120000:
|
|
95
|
+
return "l";
|
|
96
|
+
case 0o010000:
|
|
97
|
+
return "p";
|
|
98
|
+
case 0o140000:
|
|
99
|
+
return "s";
|
|
100
|
+
case 0o060000:
|
|
101
|
+
return "b";
|
|
102
|
+
case 0o020000:
|
|
103
|
+
return "c";
|
|
104
|
+
default:
|
|
105
|
+
return "-";
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as os from "node:os";
|
|
7
|
+
import { FsError } from "./errors.js";
|
|
8
|
+
|
|
9
|
+
export function autoConcurrency(): number {
|
|
10
|
+
const raw = process.env.OPENCODE_FS_CONCURRENCY;
|
|
11
|
+
if (raw !== undefined) {
|
|
12
|
+
const parsed = Number(raw);
|
|
13
|
+
if (Number.isInteger(parsed) && parsed > 0) return parsed;
|
|
14
|
+
}
|
|
15
|
+
return Math.max(1, os.availableParallelism());
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function clampConcurrency(value: number | undefined): number {
|
|
19
|
+
if (value === undefined) return autoConcurrency();
|
|
20
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
21
|
+
throw new FsError("concurrency must be a positive integer.", "invalid");
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Bounded parallel map that preserves input order and stops scheduling new
|
|
28
|
+
* work as soon as the signal aborts or a task fails.
|
|
29
|
+
*/
|
|
30
|
+
export async function mapLimit<T, R>(
|
|
31
|
+
items: readonly T[],
|
|
32
|
+
limit: number,
|
|
33
|
+
mapper: (item: T, index: number) => Promise<R>,
|
|
34
|
+
signal?: AbortSignal,
|
|
35
|
+
): Promise<R[]> {
|
|
36
|
+
if (!Number.isInteger(limit) || limit < 1) {
|
|
37
|
+
throw new FsError("parallel limit must be a positive integer.", "invalid");
|
|
38
|
+
}
|
|
39
|
+
if (items.length === 0) return [];
|
|
40
|
+
|
|
41
|
+
const results = new Array<R>(items.length);
|
|
42
|
+
let next = 0;
|
|
43
|
+
let failed: unknown;
|
|
44
|
+
|
|
45
|
+
const worker = async (): Promise<void> => {
|
|
46
|
+
for (;;) {
|
|
47
|
+
if (failed !== undefined) return;
|
|
48
|
+
if (signal?.aborted) {
|
|
49
|
+
failed = new FsError("Operation interrupted.", "interrupted");
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const index = next++;
|
|
53
|
+
if (index >= items.length) return;
|
|
54
|
+
try {
|
|
55
|
+
results[index] = await mapper(items[index] as T, index);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
failed ??= error;
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker());
|
|
64
|
+
await Promise.all(workers);
|
|
65
|
+
if (failed !== undefined) throw failed;
|
|
66
|
+
return results;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function forEachLimit<T>(
|
|
70
|
+
items: readonly T[],
|
|
71
|
+
limit: number,
|
|
72
|
+
mapper: (item: T, index: number) => Promise<void>,
|
|
73
|
+
signal?: AbortSignal,
|
|
74
|
+
): Promise<void> {
|
|
75
|
+
await mapLimit(items, limit, mapper, signal);
|
|
76
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as fs from "node:fs/promises";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import type { ResolvedTarget } from "./sandbox.js";
|
|
9
|
+
|
|
10
|
+
export interface PermissionContext {
|
|
11
|
+
readonly sessionID: string;
|
|
12
|
+
readonly agent: string;
|
|
13
|
+
readonly messageID: string;
|
|
14
|
+
readonly id: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PermissionAssertInput {
|
|
18
|
+
sessionID: string;
|
|
19
|
+
agent: string;
|
|
20
|
+
source: { type: "tool"; messageID: string; id: string };
|
|
21
|
+
action: string;
|
|
22
|
+
resources: string[];
|
|
23
|
+
save: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type PermissionAssert = (input: PermissionAssertInput) => Promise<void>;
|
|
27
|
+
|
|
28
|
+
export interface PermissionEntry {
|
|
29
|
+
readonly target: ResolvedTarget;
|
|
30
|
+
/** Absolute boundary directory for external_directory. */
|
|
31
|
+
readonly boundary: string;
|
|
32
|
+
/** Optional resource override; defaults to the sandbox-relative path. */
|
|
33
|
+
readonly resource?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Asserts an action for one or more resolved targets. Internal targets use the
|
|
38
|
+
* project-relative resource; external targets first require external_directory
|
|
39
|
+
* on the absolute boundary, then the action on the absolute path.
|
|
40
|
+
*/
|
|
41
|
+
export class PermissionGate {
|
|
42
|
+
constructor(
|
|
43
|
+
private readonly context: PermissionContext,
|
|
44
|
+
private readonly action: string,
|
|
45
|
+
private readonly sandboxResource: (full: string) => string,
|
|
46
|
+
private readonly assertPermission: PermissionAssert,
|
|
47
|
+
) {}
|
|
48
|
+
|
|
49
|
+
/** Assert an action on trusted tool-owned paths without an external gate. */
|
|
50
|
+
async assertTrusted(resources: readonly string[]): Promise<void> {
|
|
51
|
+
await this.assertAction(resources.length === 0 ? ["*"] : [...resources], ["*"]);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async assert(entries: readonly PermissionEntry[]): Promise<void> {
|
|
55
|
+
if (entries.length === 0) {
|
|
56
|
+
await this.assertAction(["*"], ["*"]);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const external = entries.filter((entry) => entry.target.outside);
|
|
61
|
+
const boundaries = new Map<string, string[]>();
|
|
62
|
+
for (const entry of external) {
|
|
63
|
+
const dir = path.resolve(entry.boundary);
|
|
64
|
+
const saves = boundaries.get(dir) ?? [];
|
|
65
|
+
const repoRoot = await this.projectRootOf(dir);
|
|
66
|
+
if (!saves.includes(repoRoot)) saves.push(repoRoot);
|
|
67
|
+
boundaries.set(dir, saves);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
for (const [dir, repoRoots] of boundaries) {
|
|
71
|
+
await this.assertPermission({
|
|
72
|
+
...this.base(),
|
|
73
|
+
action: "external_directory",
|
|
74
|
+
resources: [`${slash(dir)}/*`],
|
|
75
|
+
save: repoRoots.map((root) => `${slash(root)}/*`),
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const resources = unique(
|
|
80
|
+
entries.map((entry) =>
|
|
81
|
+
entry.target.outside
|
|
82
|
+
? slash(entry.target.full)
|
|
83
|
+
: (entry.resource ?? this.sandboxResource(entry.target.full)),
|
|
84
|
+
),
|
|
85
|
+
);
|
|
86
|
+
await this.assertAction(resources, ["*"]);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private async assertAction(resources: string[], save: string[]): Promise<void> {
|
|
90
|
+
await this.assertPermission({
|
|
91
|
+
...this.base(),
|
|
92
|
+
action: this.action,
|
|
93
|
+
resources,
|
|
94
|
+
save,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private base() {
|
|
99
|
+
return {
|
|
100
|
+
sessionID: this.context.sessionID,
|
|
101
|
+
agent: this.context.agent,
|
|
102
|
+
source: {
|
|
103
|
+
type: "tool" as const,
|
|
104
|
+
messageID: this.context.messageID,
|
|
105
|
+
id: this.context.id,
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
private async projectRootOf(dir: string): Promise<string> {
|
|
111
|
+
let current = dir;
|
|
112
|
+
for (;;) {
|
|
113
|
+
for (const marker of [".git", ".hg"]) {
|
|
114
|
+
try {
|
|
115
|
+
await fs.lstat(path.join(current, marker));
|
|
116
|
+
return current;
|
|
117
|
+
} catch {
|
|
118
|
+
// keep walking up
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const parent = path.dirname(current);
|
|
122
|
+
if (parent === current) return dir;
|
|
123
|
+
current = parent;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function slash(value: string): string {
|
|
129
|
+
return value.split(path.sep).join("/");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function unique(values: string[]): string[] {
|
|
133
|
+
return [...new Set(values)];
|
|
134
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as fs from "node:fs/promises";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import { FsError, fromErrno, isMissing } from "./errors.js";
|
|
9
|
+
|
|
10
|
+
export interface ResolvedTarget {
|
|
11
|
+
/** Absolute path to operate on. */
|
|
12
|
+
full: string;
|
|
13
|
+
/** True when the real location escapes the sandbox root. */
|
|
14
|
+
outside: boolean;
|
|
15
|
+
/** Path as requested by the caller, useful in error messages. */
|
|
16
|
+
requested: string;
|
|
17
|
+
/** Realpath of the deepest existing ancestor, or the target itself. */
|
|
18
|
+
realAncestor: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface ResolveOptions {
|
|
22
|
+
/** Allow the sandbox root itself as a target. */
|
|
23
|
+
allowRoot?: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const CRITICAL_PATHS = new Set([
|
|
27
|
+
"/",
|
|
28
|
+
"/bin",
|
|
29
|
+
"/boot",
|
|
30
|
+
"/dev",
|
|
31
|
+
"/etc",
|
|
32
|
+
"/home",
|
|
33
|
+
"/lib",
|
|
34
|
+
"/lib64",
|
|
35
|
+
"/proc",
|
|
36
|
+
"/root",
|
|
37
|
+
"/run",
|
|
38
|
+
"/sbin",
|
|
39
|
+
"/sys",
|
|
40
|
+
"/usr",
|
|
41
|
+
"/var",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* An asynchronous, symlink-aware filesystem sandbox.
|
|
46
|
+
*
|
|
47
|
+
* The root is canonicalized once. Every public resolver follows symlinks for
|
|
48
|
+
* *traversed* components and reports whether the real target escapes the root.
|
|
49
|
+
* Outside targets are not rejected here; callers gate them with the
|
|
50
|
+
* external_directory permission, exactly like OpenCode's built-ins.
|
|
51
|
+
*/
|
|
52
|
+
export class Sandbox {
|
|
53
|
+
readonly root: string;
|
|
54
|
+
readonly lexicalRoot: string;
|
|
55
|
+
private readonly rootSep: string;
|
|
56
|
+
|
|
57
|
+
private constructor(root: string, lexicalRoot: string) {
|
|
58
|
+
this.root = root;
|
|
59
|
+
this.lexicalRoot = lexicalRoot;
|
|
60
|
+
/* v8 ignore next */
|
|
61
|
+
this.rootSep = root.endsWith(path.sep) ? root : root + path.sep;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
static async create(rawRoot: string): Promise<Sandbox> {
|
|
65
|
+
if (typeof rawRoot !== "string" || rawRoot.length === 0) {
|
|
66
|
+
throw new FsError("Sandbox root is empty.", "empty");
|
|
67
|
+
}
|
|
68
|
+
const lexicalRoot = path.resolve(rawRoot);
|
|
69
|
+
let root: string;
|
|
70
|
+
try {
|
|
71
|
+
root = await fs.realpath(lexicalRoot);
|
|
72
|
+
} catch {
|
|
73
|
+
root = lexicalRoot;
|
|
74
|
+
}
|
|
75
|
+
return new Sandbox(root, lexicalRoot);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
isWithin(candidate: string): boolean {
|
|
79
|
+
return candidate === this.root || candidate.startsWith(this.rootSep);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Convert an absolute path to the permission resource form. */
|
|
83
|
+
resource(full: string): string {
|
|
84
|
+
const rel = path.relative(this.lexicalRoot, full);
|
|
85
|
+
return (rel === "" ? "." : rel).split(path.sep).join("/");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Resolve a path that is about to be created. Only the parent chain is
|
|
90
|
+
* followed; an existing final symlink is left as the link itself so callers
|
|
91
|
+
* can replace it (for example `ln -f`) instead of silently touching its
|
|
92
|
+
* target.
|
|
93
|
+
*/
|
|
94
|
+
async resolveForCreate(target: string): Promise<ResolvedTarget> {
|
|
95
|
+
this.assertTarget(target);
|
|
96
|
+
const abs = path.resolve(this.root, target);
|
|
97
|
+
if (abs === this.root) {
|
|
98
|
+
return { full: this.root, outside: false, requested: target, realAncestor: this.root };
|
|
99
|
+
}
|
|
100
|
+
const parentAbs = path.dirname(abs);
|
|
101
|
+
const { real, tail } = await this.deepestExistingAncestor(parentAbs);
|
|
102
|
+
const full = path.join(real, ...tail, path.basename(abs));
|
|
103
|
+
return {
|
|
104
|
+
full,
|
|
105
|
+
outside: !this.isWithin(real),
|
|
106
|
+
requested: target,
|
|
107
|
+
realAncestor: real,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Resolve an existing target without following its final component. Used by
|
|
113
|
+
* deletion, rename, lstat-style metadata, and symlink operations.
|
|
114
|
+
*/
|
|
115
|
+
async resolveExisting(target: string, options: ResolveOptions = {}): Promise<ResolvedTarget> {
|
|
116
|
+
this.assertTarget(target);
|
|
117
|
+
const abs = path.resolve(this.root, target);
|
|
118
|
+
if (!options.allowRoot && abs === this.root) {
|
|
119
|
+
throw new FsError(`Blocked: the sandbox root itself (${this.root}) is a hard stop.`, "outside");
|
|
120
|
+
}
|
|
121
|
+
await this.lstat(abs, target);
|
|
122
|
+
const parentAbs = path.dirname(abs);
|
|
123
|
+
const { real: parentReal, tail } = await this.deepestExistingAncestor(parentAbs);
|
|
124
|
+
return {
|
|
125
|
+
full: abs,
|
|
126
|
+
outside: tail.length > 0 || !this.isWithin(parentReal),
|
|
127
|
+
requested: target,
|
|
128
|
+
realAncestor: parentReal,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Resolve an existing target, following a final symlink. */
|
|
133
|
+
async resolveFollow(target: string): Promise<ResolvedTarget> {
|
|
134
|
+
this.assertTarget(target);
|
|
135
|
+
const abs = path.resolve(this.root, target);
|
|
136
|
+
let real: string;
|
|
137
|
+
try {
|
|
138
|
+
real = await fs.realpath(abs);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
/* v8 ignore next */
|
|
141
|
+
if (isMissing(error)) throw new FsError(`Not found: "${target}"`, "not-found");
|
|
142
|
+
/* v8 ignore next */
|
|
143
|
+
throw fromErrno(error, "access");
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
full: real,
|
|
147
|
+
outside: !this.isWithin(real),
|
|
148
|
+
requested: target,
|
|
149
|
+
realAncestor: real,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Resolve the parent of a target that may be created or replaced. */
|
|
154
|
+
async resolveParent(target: string): Promise<ResolvedTarget> {
|
|
155
|
+
this.assertTarget(target);
|
|
156
|
+
const abs = path.resolve(this.root, target);
|
|
157
|
+
const parentAbs = path.dirname(abs);
|
|
158
|
+
const { real, tail } = await this.deepestExistingAncestor(parentAbs);
|
|
159
|
+
const parent = tail.length > 0 ? path.join(real, ...tail) : real;
|
|
160
|
+
return {
|
|
161
|
+
full: parent,
|
|
162
|
+
outside: !this.isWithin(real),
|
|
163
|
+
requested: target,
|
|
164
|
+
realAncestor: real,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async lstat(full: string, label = full): Promise<Awaited<ReturnType<typeof fs.lstat>>> {
|
|
169
|
+
try {
|
|
170
|
+
return await fs.lstat(full);
|
|
171
|
+
} catch (error) {
|
|
172
|
+
/* v8 ignore next */
|
|
173
|
+
if (isMissing(error)) throw new FsError(`Not found: "${label}"`, "not-found");
|
|
174
|
+
/* v8 ignore next */
|
|
175
|
+
throw fromErrno(error, "access");
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async stat(full: string, label = full): Promise<Awaited<ReturnType<typeof fs.stat>>> {
|
|
180
|
+
try {
|
|
181
|
+
return await fs.stat(full);
|
|
182
|
+
} catch (error) {
|
|
183
|
+
/* v8 ignore next */
|
|
184
|
+
if (isMissing(error)) throw new FsError(`Not found: "${label}"`, "not-found");
|
|
185
|
+
/* v8 ignore next */
|
|
186
|
+
throw fromErrno(error, "access");
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async readdir(full: string): Promise<import("node:fs").Dirent[]> {
|
|
191
|
+
try {
|
|
192
|
+
return await fs.readdir(full, { withFileTypes: true });
|
|
193
|
+
} catch (error) {
|
|
194
|
+
/* v8 ignore next */
|
|
195
|
+
throw fromErrno(error, "access");
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async exists(full: string): Promise<boolean> {
|
|
200
|
+
try {
|
|
201
|
+
await fs.lstat(full);
|
|
202
|
+
return true;
|
|
203
|
+
} catch (error) {
|
|
204
|
+
/* v8 ignore next */
|
|
205
|
+
if (isMissing(error)) return false;
|
|
206
|
+
/* v8 ignore next */
|
|
207
|
+
throw fromErrno(error, "access");
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Refuse destructive operations on the root, its ancestors, and core paths. */
|
|
212
|
+
assertSafeToDelete(full: string): void {
|
|
213
|
+
const resolved = path.resolve(full);
|
|
214
|
+
if (resolved === this.root) {
|
|
215
|
+
throw new FsError(`Blocked: the sandbox root itself (${this.root}) cannot be removed.`, "outside");
|
|
216
|
+
}
|
|
217
|
+
if (this.root.startsWith(resolved + path.sep) || resolved === path.parse(resolved).root) {
|
|
218
|
+
throw new FsError(`Blocked: "${resolved}" is an ancestor of the sandbox root.`, "outside");
|
|
219
|
+
}
|
|
220
|
+
if (CRITICAL_PATHS.has(resolved)) {
|
|
221
|
+
throw new FsError(`Blocked: refusing a destructive operation on "${resolved}".`, "outside");
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Boundary directory used for the external_directory permission. */
|
|
226
|
+
boundaryFor(full: string, kind: "file" | "directory"): string {
|
|
227
|
+
return kind === "directory" ? full : path.dirname(full);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private assertTarget(target: string): void {
|
|
231
|
+
if (typeof target !== "string" || target.length === 0) {
|
|
232
|
+
throw new FsError("Target path is empty.", "empty");
|
|
233
|
+
}
|
|
234
|
+
if (target.includes("\0")) {
|
|
235
|
+
throw new FsError("Target path contains a NUL byte.", "invalid");
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private async deepestExistingAncestor(abs: string): Promise<{ real: string; tail: string[] }> {
|
|
240
|
+
let node = abs;
|
|
241
|
+
const tail: string[] = [];
|
|
242
|
+
for (;;) {
|
|
243
|
+
try {
|
|
244
|
+
await fs.lstat(node);
|
|
245
|
+
break;
|
|
246
|
+
} catch (error) {
|
|
247
|
+
/* v8 ignore next */
|
|
248
|
+
if (isMissing(error)) {
|
|
249
|
+
const base = path.basename(node);
|
|
250
|
+
const parent = path.dirname(node);
|
|
251
|
+
/* v8 ignore next */
|
|
252
|
+
if (base === "" || parent === node) break;
|
|
253
|
+
tail.unshift(base);
|
|
254
|
+
node = parent;
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
/* v8 ignore next */
|
|
258
|
+
throw fromErrno(error, "access");
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
let real: string;
|
|
262
|
+
try {
|
|
263
|
+
real = await fs.realpath(node);
|
|
264
|
+
} catch (error) {
|
|
265
|
+
/* v8 ignore next 2 */
|
|
266
|
+
throw fromErrno(error, "access");
|
|
267
|
+
}
|
|
268
|
+
return { real, tail };
|
|
269
|
+
}
|
|
270
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { Value } from "@sinclair/typebox/value";
|
|
7
|
+
import type { TSchema } from "@sinclair/typebox";
|
|
8
|
+
import { FsError } from "./errors.js";
|
|
9
|
+
|
|
10
|
+
export function parseSchema<T>(schema: TSchema, input: unknown, label = "input"): T {
|
|
11
|
+
if (!Value.Check(schema, input)) {
|
|
12
|
+
const first = Value.Errors(schema, input).First() as { path: string; message: string };
|
|
13
|
+
throw new FsError(`Invalid ${label}: ${first.path}: ${first.message}`, "invalid");
|
|
14
|
+
}
|
|
15
|
+
return input as T;
|
|
16
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-License-Identifier: EPL-2.0
|
|
3
|
+
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as fs from "node:fs/promises";
|
|
7
|
+
import { createReadStream } from "node:fs";
|
|
8
|
+
import { FsError, fromErrno } from "./errors.js";
|
|
9
|
+
|
|
10
|
+
export async function* readFiles(paths: readonly string[]): AsyncGenerator<Buffer> {
|
|
11
|
+
for (const file of paths) {
|
|
12
|
+
const stream = createReadStream(file);
|
|
13
|
+
try {
|
|
14
|
+
for await (const chunk of stream) yield chunk as Buffer;
|
|
15
|
+
} catch (error) {
|
|
16
|
+
throw fromErrno(error);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function* inputStream(
|
|
22
|
+
paths: readonly string[],
|
|
23
|
+
stdin: AsyncIterable<Buffer> | undefined,
|
|
24
|
+
): AsyncGenerator<Buffer> {
|
|
25
|
+
if (paths.length > 0) {
|
|
26
|
+
yield* readFiles(paths);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (stdin === undefined) throw new FsError("no input files and no stdin.", "invalid");
|
|
30
|
+
yield* stdin;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function collect(
|
|
34
|
+
stream: AsyncIterable<Buffer>,
|
|
35
|
+
limit = Number.POSITIVE_INFINITY,
|
|
36
|
+
): Promise<Buffer> {
|
|
37
|
+
const chunks: Buffer[] = [];
|
|
38
|
+
let total = 0;
|
|
39
|
+
for await (const chunk of stream) {
|
|
40
|
+
if (total + chunk.length > limit) {
|
|
41
|
+
chunks.push(chunk.subarray(0, Math.max(0, limit - total)));
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
chunks.push(chunk);
|
|
45
|
+
total += chunk.length;
|
|
46
|
+
}
|
|
47
|
+
return Buffer.concat(chunks);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function* lines(
|
|
51
|
+
stream: AsyncIterable<Buffer>,
|
|
52
|
+
): AsyncGenerator<{ text: string; newline: boolean }> {
|
|
53
|
+
let buffer = "";
|
|
54
|
+
for await (const chunk of stream) {
|
|
55
|
+
buffer += chunk.toString("utf8");
|
|
56
|
+
for (;;) {
|
|
57
|
+
const index = buffer.indexOf("\n");
|
|
58
|
+
if (index < 0) break;
|
|
59
|
+
yield { text: buffer.slice(0, index), newline: true };
|
|
60
|
+
buffer = buffer.slice(index + 1);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (buffer.length > 0) yield { text: buffer, newline: false };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function writeAll(path: string, data: AsyncIterable<Buffer> | Buffer, append = false): Promise<void> {
|
|
67
|
+
let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
|
|
68
|
+
try {
|
|
69
|
+
handle = await fs.open(path, append ? "a" : "w");
|
|
70
|
+
if (Buffer.isBuffer(data)) {
|
|
71
|
+
await handle.write(data);
|
|
72
|
+
} else {
|
|
73
|
+
for await (const chunk of data) await handle.write(chunk);
|
|
74
|
+
}
|
|
75
|
+
} catch (error) {
|
|
76
|
+
throw fromErrno(error);
|
|
77
|
+
} finally {
|
|
78
|
+
await handle?.close();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function toBuffer(text: string): Buffer {
|
|
83
|
+
return Buffer.from(text, "utf8");
|
|
84
|
+
}
|