opencode-fs-plugin 3.5.0 → 3.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +118 -28
- package/SPEC.md +119 -20
- package/package.json +1 -1
- package/skills/filesystem/SKILL.md +92 -21
- package/src/core/fsutil.ts +84 -23
- package/src/core/jobs.ts +210 -34
- package/src/core/relay-protocol.ts +45 -0
- package/src/core/safe-output.ts +290 -0
- package/src/core/sandbox.ts +43 -0
- package/src/index.ts +23 -6
- package/src/tools/ar.ts +62 -29
- package/src/tools/chmod.ts +30 -19
- package/src/tools/chown.ts +24 -16
- package/src/tools/command.ts +8 -5
- package/src/tools/cp.ts +84 -20
- package/src/tools/cpio.ts +204 -65
- package/src/tools/curl.ts +123 -6
- package/src/tools/dd.ts +15 -9
- package/src/tools/diff.ts +46 -15
- package/src/tools/grep.ts +5 -2
- package/src/tools/gzip.ts +13 -15
- package/src/tools/mktemp.ts +41 -26
- package/src/tools/mv.ts +69 -28
- package/src/tools/pipe.ts +17 -9
- package/src/tools/split.ts +26 -12
- package/src/tools/tar.ts +132 -57
- package/src/tools/tee.ts +7 -4
- package/src/tools/touch.ts +12 -4
- package/src/tools/truncate.ts +17 -7
- package/src/tools/zip.ts +119 -54
package/src/core/fsutil.ts
CHANGED
|
@@ -133,6 +133,8 @@ async function walkDir(
|
|
|
133
133
|
return output;
|
|
134
134
|
}
|
|
135
135
|
|
|
136
|
+
export type CopyLimiter = <T>(fn: () => Promise<T>) => Promise<T>;
|
|
137
|
+
|
|
136
138
|
export interface CopyOptions {
|
|
137
139
|
readonly recursive?: boolean;
|
|
138
140
|
readonly dereference?: boolean;
|
|
@@ -141,16 +143,24 @@ export interface CopyOptions {
|
|
|
141
143
|
readonly update?: boolean;
|
|
142
144
|
readonly signal?: AbortSignal;
|
|
143
145
|
readonly concurrency: number;
|
|
146
|
+
/** Shared syscall limiter for nested trees; never held across recursion. */
|
|
147
|
+
readonly limiter?: CopyLimiter;
|
|
148
|
+
/** Called when noClobber or update leaves an existing destination in place. */
|
|
149
|
+
readonly onSkip?: () => void;
|
|
144
150
|
}
|
|
145
151
|
|
|
146
152
|
export async function copyTree(src: string, dest: string, options: CopyOptions): Promise<number> {
|
|
147
153
|
if (options.signal?.aborted) throw new FsError("Operation interrupted.", "interrupted");
|
|
148
|
-
const
|
|
154
|
+
const limit = options.limiter ?? immediate;
|
|
155
|
+
const stats = await limit(() => (options.dereference === false ? fs.lstat(src) : fs.stat(src)));
|
|
149
156
|
if (options.update === true) {
|
|
150
157
|
try {
|
|
151
|
-
const destStats = await fs.lstat(dest);
|
|
158
|
+
const destStats = await limit(() => fs.lstat(dest));
|
|
152
159
|
/* v8 ignore next */
|
|
153
|
-
if (destStats.mtimeMs >= stats.mtimeMs)
|
|
160
|
+
if (destStats.mtimeMs >= stats.mtimeMs) {
|
|
161
|
+
options.onSkip?.();
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
|
154
164
|
} catch (error) {
|
|
155
165
|
/* v8 ignore next 2 */
|
|
156
166
|
if (!isMissing(error)) throw fromErrno(error, "access");
|
|
@@ -158,18 +168,19 @@ export async function copyTree(src: string, dest: string, options: CopyOptions):
|
|
|
158
168
|
}
|
|
159
169
|
|
|
160
170
|
if (stats.isSymbolicLink() && options.dereference === false) {
|
|
161
|
-
const target = await fs.readlink(src);
|
|
162
|
-
await ensureParent(dest);
|
|
171
|
+
const target = await limit(() => fs.readlink(src));
|
|
172
|
+
await limit(() => ensureParent(dest));
|
|
163
173
|
try {
|
|
164
|
-
await fs.symlink(target, dest);
|
|
174
|
+
await limit(() => fs.symlink(target, dest));
|
|
165
175
|
} catch (error) {
|
|
166
176
|
/* v8 ignore next */
|
|
167
|
-
if (isExists(error)
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
throw fromErrno(error);
|
|
177
|
+
if (!isExists(error)) throw fromErrno(error);
|
|
178
|
+
if (options.noClobber === true) {
|
|
179
|
+
options.onSkip?.();
|
|
180
|
+
return 0;
|
|
172
181
|
}
|
|
182
|
+
await limit(() => fs.unlink(dest));
|
|
183
|
+
await limit(() => fs.symlink(target, dest));
|
|
173
184
|
}
|
|
174
185
|
return 1;
|
|
175
186
|
}
|
|
@@ -178,45 +189,85 @@ export async function copyTree(src: string, dest: string, options: CopyOptions):
|
|
|
178
189
|
if (options.recursive !== true) {
|
|
179
190
|
throw new FsError(`"${src}" is a directory; recursive is required.`, "not-file");
|
|
180
191
|
}
|
|
192
|
+
const existing = await lstatOptional(dest, limit);
|
|
193
|
+
if (existing?.isSymbolicLink() === true) {
|
|
194
|
+
throw new FsError(`Refusing to write through symbolic link: "${dest}".`, "invalid");
|
|
195
|
+
}
|
|
181
196
|
try {
|
|
182
|
-
await fs.mkdir(dest, { recursive: true });
|
|
197
|
+
await limit(() => fs.mkdir(dest, { recursive: true }));
|
|
183
198
|
} catch (error) {
|
|
184
199
|
/* v8 ignore next */
|
|
185
200
|
throw fromErrno(error);
|
|
186
201
|
}
|
|
187
|
-
const entries = await fs.readdir(src);
|
|
188
|
-
|
|
189
|
-
const limit = Math.max(1, options.concurrency);
|
|
202
|
+
const entries = await limit(() => fs.readdir(src));
|
|
203
|
+
const parallelism = Math.max(1, options.concurrency);
|
|
190
204
|
let index = 0;
|
|
191
|
-
const workers = Array.from({ length: Math.min(
|
|
205
|
+
const workers = Array.from({ length: Math.min(parallelism, entries.length) }, async () => {
|
|
206
|
+
let copied = 0;
|
|
192
207
|
for (;;) {
|
|
193
208
|
const current = index++;
|
|
194
|
-
if (current >= entries.length)
|
|
209
|
+
if (current >= entries.length) break;
|
|
195
210
|
const name = entries[current] as string;
|
|
196
211
|
copied += await copyTree(path.join(src, name), path.join(dest, name), options);
|
|
197
212
|
}
|
|
213
|
+
return copied;
|
|
198
214
|
});
|
|
199
|
-
await Promise.all(workers);
|
|
200
|
-
if (options.preserve === true) await preserve(dest, stats);
|
|
215
|
+
const copied = 1 + (await Promise.all(workers)).reduce((sum, value) => sum + value, 0);
|
|
216
|
+
if (options.preserve === true) await limit(() => preserve(dest, stats));
|
|
201
217
|
return copied;
|
|
202
218
|
}
|
|
203
219
|
|
|
204
220
|
if (!stats.isFile()) {
|
|
205
221
|
throw new FsError(`"${src}" is not a regular file or directory.`, "unsupported");
|
|
206
222
|
}
|
|
207
|
-
await
|
|
223
|
+
const existing = await lstatOptional(dest, limit);
|
|
224
|
+
if (options.noClobber === true && existing !== undefined) {
|
|
225
|
+
options.onSkip?.();
|
|
226
|
+
return 0;
|
|
227
|
+
}
|
|
228
|
+
if (existing?.isSymbolicLink() === true) {
|
|
229
|
+
throw new FsError(`Refusing to write through symbolic link: "${dest}".`, "invalid");
|
|
230
|
+
}
|
|
231
|
+
if (
|
|
232
|
+
existing !== undefined &&
|
|
233
|
+
num(existing.dev) === num(stats.dev) &&
|
|
234
|
+
num(existing.ino) === num(stats.ino)
|
|
235
|
+
) {
|
|
236
|
+
throw new FsError(`"${src}" and destination are the same file.`, "invalid");
|
|
237
|
+
}
|
|
238
|
+
await limit(() => ensureParent(dest));
|
|
208
239
|
try {
|
|
209
|
-
await fs.copyFile(src, dest, options.noClobber === true ? constants.COPYFILE_EXCL : 0);
|
|
240
|
+
await limit(() => fs.copyFile(src, dest, options.noClobber === true ? constants.COPYFILE_EXCL : 0));
|
|
210
241
|
} catch (error) {
|
|
211
242
|
/* v8 ignore next */
|
|
212
|
-
if (options.noClobber === true && isExists(error))
|
|
243
|
+
if (options.noClobber === true && isExists(error)) {
|
|
244
|
+
options.onSkip?.();
|
|
245
|
+
return 0;
|
|
246
|
+
}
|
|
213
247
|
/* v8 ignore next */
|
|
214
248
|
throw fromErrno(error);
|
|
215
249
|
}
|
|
216
|
-
if (options.preserve === true) await preserve(dest, stats);
|
|
250
|
+
if (options.preserve === true) await limit(() => preserve(dest, stats));
|
|
217
251
|
return 1;
|
|
218
252
|
}
|
|
219
253
|
|
|
254
|
+
async function lstatOptional(
|
|
255
|
+
dest: string,
|
|
256
|
+
limit: CopyLimiter,
|
|
257
|
+
): Promise<Awaited<ReturnType<typeof fs.lstat>> | undefined> {
|
|
258
|
+
try {
|
|
259
|
+
return await limit(() => fs.lstat(dest));
|
|
260
|
+
} catch (error) {
|
|
261
|
+
/* v8 ignore next */
|
|
262
|
+
if (!isMissing(error)) throw fromErrno(error, "access");
|
|
263
|
+
return undefined;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function immediate<T>(fn: () => Promise<T>): Promise<T> {
|
|
268
|
+
return fn();
|
|
269
|
+
}
|
|
270
|
+
|
|
220
271
|
export async function ensureParent(dest: string): Promise<void> {
|
|
221
272
|
try {
|
|
222
273
|
await fs.mkdir(path.dirname(dest), { recursive: true });
|
|
@@ -230,10 +281,20 @@ export function num(value: number | bigint): number {
|
|
|
230
281
|
}
|
|
231
282
|
|
|
232
283
|
export async function preserve(dest: string, stats: Awaited<ReturnType<typeof fs.stat>>): Promise<void> {
|
|
284
|
+
let current: Awaited<ReturnType<typeof fs.lstat>>;
|
|
285
|
+
try {
|
|
286
|
+
current = await fs.lstat(dest);
|
|
287
|
+
} catch (error) {
|
|
288
|
+
throw fromErrno(error, "io");
|
|
289
|
+
}
|
|
290
|
+
if (current.isSymbolicLink()) {
|
|
291
|
+
throw new FsError(`Refusing to preserve metadata through symbolic link: "${dest}".`, "invalid");
|
|
292
|
+
}
|
|
233
293
|
try {
|
|
234
294
|
await fs.chmod(dest, num(stats.mode) & 0o7777);
|
|
235
295
|
await fs.utimes(dest, stats.atime, stats.mtime);
|
|
236
296
|
} catch (error) {
|
|
297
|
+
/* v8 ignore next */
|
|
237
298
|
throw fromErrno(error, "io");
|
|
238
299
|
}
|
|
239
300
|
}
|
package/src/core/jobs.ts
CHANGED
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
7
7
|
import * as fs from "node:fs/promises";
|
|
8
8
|
import * as os from "node:os";
|
|
9
9
|
import * as path from "node:path";
|
|
10
|
-
import { FsError, errorMessage } from "./errors.js";
|
|
10
|
+
import { FsError, errorMessage, fromErrno, isMissing } from "./errors.js";
|
|
11
11
|
import type { RenderedResult } from "./format.js";
|
|
12
12
|
|
|
13
13
|
export type JobState = "running" | "completed" | "failed" | "cancelled";
|
|
@@ -33,6 +33,10 @@ export interface JobManagerOptions {
|
|
|
33
33
|
readonly limit?: number;
|
|
34
34
|
readonly ttlMs?: number;
|
|
35
35
|
readonly now?: () => number;
|
|
36
|
+
/** Internal bound on retained finished jobs; not a plugin option. */
|
|
37
|
+
readonly retainedLimit?: number;
|
|
38
|
+
/** Internal bound on one rendered result's content; not a plugin option. */
|
|
39
|
+
readonly maxResultBytes?: number;
|
|
36
40
|
}
|
|
37
41
|
|
|
38
42
|
interface JobRecord {
|
|
@@ -44,6 +48,8 @@ interface JobRecord {
|
|
|
44
48
|
error?: string;
|
|
45
49
|
readonly statusPath: string;
|
|
46
50
|
readonly controller: AbortController;
|
|
51
|
+
/** Session that created the job; never exposed in snapshots. */
|
|
52
|
+
readonly owner: string;
|
|
47
53
|
result?: RenderedResult;
|
|
48
54
|
done: Promise<void>;
|
|
49
55
|
timer?: NodeJS.Timeout;
|
|
@@ -51,6 +57,23 @@ interface JobRecord {
|
|
|
51
57
|
|
|
52
58
|
const DEFAULT_LIMIT = 8;
|
|
53
59
|
const DEFAULT_TTL_MS = 60 * 60 * 1000;
|
|
60
|
+
/**
|
|
61
|
+
* Finished jobs are kept so `fs.job wait` can return their results. The TTL
|
|
62
|
+
* alone bounds time, not count, so a burst of quick jobs would retain an
|
|
63
|
+
* unbounded number of results and status files. Keep a finite window and evict
|
|
64
|
+
* the oldest finished job before admitting a new one.
|
|
65
|
+
*/
|
|
66
|
+
const DEFAULT_MAX_RETAINED_JOBS = 64;
|
|
67
|
+
/** One retained rendered result; larger text is truncated and binary is dropped. */
|
|
68
|
+
const DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;
|
|
69
|
+
const TRUNCATION_MARKER = "\n[truncated]";
|
|
70
|
+
/**
|
|
71
|
+
* Owner used by direct `JobManager` callers (unit tests and internal helpers).
|
|
72
|
+
* The plugin always passes the originating host session id, so this namespace
|
|
73
|
+
* cannot collide with a real `ses_…` session and never widens another caller's
|
|
74
|
+
* view.
|
|
75
|
+
*/
|
|
76
|
+
const LOCAL_OWNER = "local";
|
|
54
77
|
|
|
55
78
|
function snapshot(job: JobRecord): JobStatus {
|
|
56
79
|
return {
|
|
@@ -71,36 +94,31 @@ export class JobManager {
|
|
|
71
94
|
private readonly dir: string;
|
|
72
95
|
private readonly limit: number;
|
|
73
96
|
private readonly ttlMs: number;
|
|
97
|
+
private readonly retainedLimit: number;
|
|
98
|
+
private readonly maxResultBytes: number;
|
|
74
99
|
private readonly now: () => number;
|
|
100
|
+
/** Serializes admission so concurrent starts cannot overrun either cap. */
|
|
101
|
+
private admission: Promise<void> = Promise.resolve();
|
|
75
102
|
|
|
76
103
|
constructor(options: JobManagerOptions = {}) {
|
|
77
104
|
this.dir = options.dir ?? path.join(os.tmpdir(), "opencode", "fs-jobs", String(process.pid));
|
|
78
105
|
this.limit = options.limit ?? DEFAULT_LIMIT;
|
|
79
106
|
this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
107
|
+
this.retainedLimit = options.retainedLimit ?? DEFAULT_MAX_RETAINED_JOBS;
|
|
108
|
+
this.maxResultBytes = options.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES;
|
|
80
109
|
this.now = options.now ?? Date.now;
|
|
81
110
|
}
|
|
82
111
|
|
|
83
|
-
async start(
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
const job: JobRecord = {
|
|
90
|
-
id,
|
|
91
|
-
tool,
|
|
92
|
-
state: "running",
|
|
93
|
-
startedAt: this.now(),
|
|
94
|
-
statusPath: path.join(this.dir, `${id}.json`),
|
|
95
|
-
controller: new AbortController(),
|
|
96
|
-
done: Promise.resolve(),
|
|
97
|
-
};
|
|
98
|
-
this.jobs.set(id, job);
|
|
99
|
-
|
|
112
|
+
async start(
|
|
113
|
+
tool: string,
|
|
114
|
+
run: (signal: AbortSignal) => Promise<RenderedResult>,
|
|
115
|
+
owner: string = LOCAL_OWNER,
|
|
116
|
+
): Promise<JobStatus> {
|
|
117
|
+
const job = await this.admit(tool, owner);
|
|
100
118
|
try {
|
|
101
119
|
await this.write(job);
|
|
102
120
|
} catch (error) {
|
|
103
|
-
this.jobs.delete(id);
|
|
121
|
+
this.jobs.delete(job.id);
|
|
104
122
|
throw error;
|
|
105
123
|
}
|
|
106
124
|
|
|
@@ -109,19 +127,23 @@ export class JobManager {
|
|
|
109
127
|
return snapshot(job);
|
|
110
128
|
}
|
|
111
129
|
|
|
112
|
-
status(id: string): JobStatus {
|
|
113
|
-
return snapshot(this.require(id));
|
|
130
|
+
status(id: string, owner: string = LOCAL_OWNER): JobStatus {
|
|
131
|
+
return snapshot(this.require(id, owner));
|
|
114
132
|
}
|
|
115
133
|
|
|
116
|
-
list(): JobStatus[] {
|
|
134
|
+
list(owner: string = LOCAL_OWNER): JobStatus[] {
|
|
117
135
|
return [...this.jobs.values()]
|
|
136
|
+
.filter((job) => job.owner === owner)
|
|
118
137
|
.sort((a, b) => b.startedAt - a.startedAt)
|
|
119
138
|
.map((job) => snapshot(job));
|
|
120
139
|
}
|
|
121
140
|
|
|
122
|
-
async wait(id: string, timeoutMs: number): Promise<JobWait> {
|
|
123
|
-
const job = this.require(id);
|
|
141
|
+
async wait(id: string, timeoutMs: number, owner: string = LOCAL_OWNER): Promise<JobWait> {
|
|
142
|
+
const job = this.require(id, owner);
|
|
124
143
|
if (job.state !== "running") {
|
|
144
|
+
// State flips before the final status write in `execute`; await the
|
|
145
|
+
// completion promise so a caller never observes a stale "running" file.
|
|
146
|
+
await job.done;
|
|
125
147
|
return { status: snapshot(job), timedOut: false, ...(job.result ? { result: job.result } : {}) };
|
|
126
148
|
}
|
|
127
149
|
await new Promise<void>((resolve) => {
|
|
@@ -138,8 +160,8 @@ export class JobManager {
|
|
|
138
160
|
};
|
|
139
161
|
}
|
|
140
162
|
|
|
141
|
-
cancel(id: string): JobStatus {
|
|
142
|
-
const job = this.require(id);
|
|
163
|
+
cancel(id: string, owner: string = LOCAL_OWNER): JobStatus {
|
|
164
|
+
const job = this.require(id, owner);
|
|
143
165
|
if (job.state === "running") job.controller.abort();
|
|
144
166
|
return snapshot(job);
|
|
145
167
|
}
|
|
@@ -152,6 +174,85 @@ export class JobManager {
|
|
|
152
174
|
this.jobs.clear();
|
|
153
175
|
}
|
|
154
176
|
|
|
177
|
+
/**
|
|
178
|
+
* Reserve both a running slot and a retained slot. The check, eviction and
|
|
179
|
+
* insertion run under one admission lock, so two concurrent starts cannot
|
|
180
|
+
* both observe free capacity and then both insert.
|
|
181
|
+
*/
|
|
182
|
+
private async admit(tool: string, owner: string): Promise<JobRecord> {
|
|
183
|
+
if (owner.length === 0) throw new FsError("job owner is required.", "invalid");
|
|
184
|
+
return this.withAdmission(async () => {
|
|
185
|
+
if (this.runningCount() >= this.limit) {
|
|
186
|
+
throw new FsError(`background job limit reached (${this.limit} running).`, "busy");
|
|
187
|
+
}
|
|
188
|
+
await this.ensureCapacity();
|
|
189
|
+
|
|
190
|
+
const id = `job_${randomUUID()}`;
|
|
191
|
+
const job: JobRecord = {
|
|
192
|
+
id,
|
|
193
|
+
tool,
|
|
194
|
+
owner,
|
|
195
|
+
state: "running",
|
|
196
|
+
startedAt: this.now(),
|
|
197
|
+
statusPath: path.join(this.dir, `${id}.json`),
|
|
198
|
+
controller: new AbortController(),
|
|
199
|
+
done: Promise.resolve(),
|
|
200
|
+
};
|
|
201
|
+
this.jobs.set(id, job);
|
|
202
|
+
return job;
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private async withAdmission<T>(task: () => Promise<T>): Promise<T> {
|
|
207
|
+
const previous = this.admission;
|
|
208
|
+
let release!: () => void;
|
|
209
|
+
this.admission = new Promise<void>((resolve) => {
|
|
210
|
+
release = resolve;
|
|
211
|
+
});
|
|
212
|
+
await previous;
|
|
213
|
+
try {
|
|
214
|
+
return await task();
|
|
215
|
+
} finally {
|
|
216
|
+
release();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Evict the oldest finished jobs until one slot remains for a new job.
|
|
222
|
+
* Running jobs are never evicted; if only running jobs remain, the caller
|
|
223
|
+
* fails with `busy` rather than growing the retained window.
|
|
224
|
+
*/
|
|
225
|
+
private async ensureCapacity(): Promise<void> {
|
|
226
|
+
while (this.jobs.size >= this.retainedLimit) {
|
|
227
|
+
const victim = this.oldestFinished();
|
|
228
|
+
if (victim === undefined) {
|
|
229
|
+
throw new FsError(
|
|
230
|
+
`background job retention limit reached (${this.retainedLimit} jobs).`,
|
|
231
|
+
"busy",
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
// Remove it from the map first so concurrent starts cannot pick the same
|
|
235
|
+
// victim; then wait for its final status write before deleting the file.
|
|
236
|
+
this.jobs.delete(victim.id);
|
|
237
|
+
clearTimeout(victim.timer);
|
|
238
|
+
await victim.done;
|
|
239
|
+
clearTimeout(victim.timer);
|
|
240
|
+
/* v8 ignore next -- retained status-file cleanup is best-effort */
|
|
241
|
+
await fs.rm(victim.statusPath, { force: true }).catch(() => {});
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
private oldestFinished(): JobRecord | undefined {
|
|
246
|
+
let oldest: JobRecord | undefined;
|
|
247
|
+
for (const job of this.jobs.values()) {
|
|
248
|
+
if (job.state === "running") continue;
|
|
249
|
+
if (oldest === undefined || (job.finishedAt as number) < (oldest.finishedAt as number)) {
|
|
250
|
+
oldest = job;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return oldest;
|
|
254
|
+
}
|
|
255
|
+
|
|
155
256
|
private async execute(
|
|
156
257
|
job: JobRecord,
|
|
157
258
|
run: (signal: AbortSignal) => Promise<RenderedResult>,
|
|
@@ -162,7 +263,7 @@ export class JobManager {
|
|
|
162
263
|
job.state = "cancelled";
|
|
163
264
|
} else {
|
|
164
265
|
job.state = "completed";
|
|
165
|
-
job.result = result;
|
|
266
|
+
job.result = this.boundResult(result);
|
|
166
267
|
}
|
|
167
268
|
} catch (error) {
|
|
168
269
|
job.state = job.controller.signal.aborted ? "cancelled" : "failed";
|
|
@@ -193,19 +294,87 @@ export class JobManager {
|
|
|
193
294
|
}
|
|
194
295
|
|
|
195
296
|
private async write(job: JobRecord): Promise<void> {
|
|
196
|
-
await
|
|
197
|
-
|
|
297
|
+
await this.ensureDir();
|
|
298
|
+
// A random, exclusive-create temp name prevents a pre-planted symlink from
|
|
299
|
+
// redirecting the status write (the job id and pid alone are predictable).
|
|
300
|
+
const temp = `${job.statusPath}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
301
|
+
// Keep sensitive runtime data (raw errors, absolute status path) out of the
|
|
302
|
+
// on-disk file; the owner still gets the rich snapshot from fs.job.
|
|
198
303
|
const payload = {
|
|
199
|
-
|
|
304
|
+
id: job.id,
|
|
305
|
+
tool: job.tool,
|
|
306
|
+
state: job.state,
|
|
307
|
+
startedAt: job.startedAt,
|
|
308
|
+
...(job.finishedAt === undefined ? {} : { finishedAt: job.finishedAt }),
|
|
200
309
|
...(job.result ? { hasResult: true } : {}),
|
|
201
310
|
};
|
|
202
|
-
await fs.writeFile(temp, `${JSON.stringify(payload)}\n`,
|
|
311
|
+
await fs.writeFile(temp, `${JSON.stringify(payload)}\n`, {
|
|
312
|
+
encoding: "utf8",
|
|
313
|
+
mode: 0o600,
|
|
314
|
+
flag: "wx",
|
|
315
|
+
});
|
|
316
|
+
await fs.chmod(temp, 0o600);
|
|
203
317
|
await fs.rename(temp, job.statusPath);
|
|
204
318
|
}
|
|
205
319
|
|
|
206
|
-
|
|
320
|
+
/**
|
|
321
|
+
* Create or validate the status directory without following a pre-existing
|
|
322
|
+
* symlink anywhere in the configured path. A caller-supplied ordinary nested
|
|
323
|
+
* directory keeps working; any symlink, non-directory, root, or inaccessible
|
|
324
|
+
* component fails before a chmod or write. A resolve/check-to-syscall race
|
|
325
|
+
* remains possible, so this is a guardrail, not a kernel boundary.
|
|
326
|
+
*/
|
|
327
|
+
private async ensureDir(): Promise<void> {
|
|
328
|
+
const absolute = path.resolve(this.dir);
|
|
329
|
+
const root = path.parse(absolute).root;
|
|
330
|
+
if (absolute === root) {
|
|
331
|
+
throw new FsError(`job directory must not be the filesystem root: ${absolute}`, "invalid");
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
let current = root;
|
|
335
|
+
let missing = false;
|
|
336
|
+
for (const part of path.relative(root, absolute).split(path.sep)) {
|
|
337
|
+
current = path.join(current, part);
|
|
338
|
+
if (missing) continue;
|
|
339
|
+
let stats: Awaited<ReturnType<typeof fs.lstat>>;
|
|
340
|
+
try {
|
|
341
|
+
stats = await fs.lstat(current);
|
|
342
|
+
} catch (error) {
|
|
343
|
+
/* v8 ignore next -- a non-missing lstat error is an OS access failure */
|
|
344
|
+
if (!isMissing(error)) throw fromErrno(error, "access");
|
|
345
|
+
missing = true;
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
if (stats.isSymbolicLink()) {
|
|
349
|
+
throw new FsError(`job directory must not contain a symbolic link: ${current}`, "invalid");
|
|
350
|
+
}
|
|
351
|
+
if (!stats.isDirectory()) {
|
|
352
|
+
throw new FsError(`job directory component is not a directory: ${current}`, "not-directory");
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
if (missing) await fs.mkdir(absolute, { recursive: true, mode: 0o700 });
|
|
357
|
+
await fs.chmod(absolute, 0o700);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
private boundResult(result: RenderedResult): RenderedResult {
|
|
361
|
+
const bytes = Buffer.byteLength(result.content, "utf8");
|
|
362
|
+
if (bytes <= this.maxResultBytes) return result;
|
|
363
|
+
const metadata = { ...result.metadata, truncated: true, originalBytes: bytes };
|
|
364
|
+
if (result.metadata.encoding === "base64") {
|
|
365
|
+
return { content: "", metadata };
|
|
366
|
+
}
|
|
367
|
+
const limit = Math.max(0, this.maxResultBytes - Buffer.byteLength(TRUNCATION_MARKER, "utf8"));
|
|
368
|
+
return { content: `${truncateUtf8(result.content, limit)}${TRUNCATION_MARKER}`, metadata };
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
private require(id: string, owner: string = LOCAL_OWNER): JobRecord {
|
|
207
372
|
const job = this.jobs.get(id);
|
|
208
|
-
if (
|
|
373
|
+
if (job === undefined || job.owner !== owner) {
|
|
374
|
+
// Deliberately identical for missing and foreign jobs: a caller without
|
|
375
|
+
// the owner token must not learn that another session's id exists.
|
|
376
|
+
throw new FsError(`job not found: ${id}`, "not-found");
|
|
377
|
+
}
|
|
209
378
|
return job;
|
|
210
379
|
}
|
|
211
380
|
|
|
@@ -215,3 +384,10 @@ export class JobManager {
|
|
|
215
384
|
return count;
|
|
216
385
|
}
|
|
217
386
|
}
|
|
387
|
+
|
|
388
|
+
function truncateUtf8(text: string, maxBytes: number): string {
|
|
389
|
+
const bytes = Buffer.from(text, "utf8");
|
|
390
|
+
let end = Math.min(bytes.length, maxBytes);
|
|
391
|
+
while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;
|
|
392
|
+
return bytes.subarray(0, end).toString("utf8");
|
|
393
|
+
}
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
* license-wizard managed-header v1 EPL-2.0 short 73897e75828f
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
+
import { isIP } from "node:net";
|
|
7
|
+
|
|
6
8
|
/**
|
|
7
9
|
* Wire format shared with procage's relay control client.
|
|
8
10
|
*
|
|
@@ -76,6 +78,46 @@ export class RelayProtocolError extends Error {
|
|
|
76
78
|
|
|
77
79
|
const UTF8 = new TextDecoder("utf-8", { fatal: true });
|
|
78
80
|
const FORBIDDEN_RESOURCE = /[\u0000-\u0020\u007f]/;
|
|
81
|
+
const HOST_LABEL = /^[A-Za-z0-9_](?:[A-Za-z0-9_-]*[A-Za-z0-9_])?$/;
|
|
82
|
+
const PORT_TEXT = /^\d{1,5}$/;
|
|
83
|
+
|
|
84
|
+
function isPort(value: string): boolean {
|
|
85
|
+
if (!PORT_TEXT.test(value)) return false;
|
|
86
|
+
const port = Number(value);
|
|
87
|
+
return port >= 1 && port <= 65535;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function isHostName(host: string): boolean {
|
|
91
|
+
const trimmed = host.endsWith(".") ? host.slice(0, -1) : host;
|
|
92
|
+
if (trimmed.length === 0) return false;
|
|
93
|
+
return trimmed.split(".").every((label) => HOST_LABEL.test(label));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* A resource is a DNS name, IP literal, or HTTP Host (optionally host:port).
|
|
98
|
+
* IPv6 literals may be bare or bracketed for the Host form. Wildcards, glob
|
|
99
|
+
* metacharacters, malformed brackets, invalid ports and other URI syntax are
|
|
100
|
+
* rejected before they can reach a wildcard-aware permission layer.
|
|
101
|
+
*/
|
|
102
|
+
function isRelayResource(resource: string): boolean {
|
|
103
|
+
if (resource.startsWith("[")) {
|
|
104
|
+
const end = resource.indexOf("]");
|
|
105
|
+
if (end < 0) return false;
|
|
106
|
+
if (isIP(resource.slice(1, end)) !== 6) return false;
|
|
107
|
+
const rest = resource.slice(end + 1);
|
|
108
|
+
if (rest.length === 0) return true;
|
|
109
|
+
if (!rest.startsWith(":")) return false;
|
|
110
|
+
return isPort(rest.slice(1));
|
|
111
|
+
}
|
|
112
|
+
if (resource.includes("[") || resource.includes("]")) return false;
|
|
113
|
+
const firstColon = resource.indexOf(":");
|
|
114
|
+
if (firstColon !== -1) {
|
|
115
|
+
if (firstColon !== resource.lastIndexOf(":")) return isIP(resource) === 6;
|
|
116
|
+
if (!isPort(resource.slice(firstColon + 1))) return false;
|
|
117
|
+
return isHostName(resource.slice(0, firstColon));
|
|
118
|
+
}
|
|
119
|
+
return isHostName(resource);
|
|
120
|
+
}
|
|
79
121
|
|
|
80
122
|
/** Wrap one payload in the length prefix. */
|
|
81
123
|
export function encodeFrame(payload: Buffer): Buffer {
|
|
@@ -174,6 +216,9 @@ export function decodeDecisionRequest(payload: Buffer): RelayDecisionRequest {
|
|
|
174
216
|
if (FORBIDDEN_RESOURCE.test(resource)) {
|
|
175
217
|
throw new RelayProtocolError("DECIDE_REQ resource contains whitespace or control characters");
|
|
176
218
|
}
|
|
219
|
+
if (!isRelayResource(resource)) {
|
|
220
|
+
throw new RelayProtocolError("DECIDE_REQ resource is not a valid host or IP literal");
|
|
221
|
+
}
|
|
177
222
|
|
|
178
223
|
const port = payload.readUInt16BE(portOffset);
|
|
179
224
|
if (port === 0) {
|