opencode-fs-plugin 3.4.0 → 3.6.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/src/tools/cp.ts CHANGED
@@ -8,7 +8,8 @@ import * as path from "node:path";
8
8
  import { Type, type Static } from "@sinclair/typebox";
9
9
  import { sourcesFrom } from "../core/aliases.js";
10
10
  import { FsError, fromErrno, isMissing } from "../core/errors.js";
11
- import { copyTree, isSubpath } from "../core/fsutil.js";
11
+ import { copyTree, isSubpath, num } from "../core/fsutil.js";
12
+ import { createLimiter, mapLimit } from "../core/parallel.js";
12
13
  import { textResult, type ToolSpec } from "../core/types.js";
13
14
 
14
15
  const Schema = Type.Object(
@@ -30,11 +31,19 @@ const Schema = Type.Object(
30
31
 
31
32
  type Input = Static<typeof Schema>;
32
33
 
34
+ interface Referent {
35
+ dev: number;
36
+ ino: number;
37
+ }
38
+
33
39
  interface Source {
34
40
  requested: string;
35
41
  full: string;
36
42
  isDirectory: boolean;
37
43
  isSymlink: boolean;
44
+ dev: number;
45
+ ino: number;
46
+ referent: Referent | undefined;
38
47
  }
39
48
 
40
49
  export const cpTool: ToolSpec<Input> = {
@@ -65,18 +74,34 @@ export const cpTool: ToolSpec<Input> = {
65
74
  if (stats.isDirectory() && !recursive) {
66
75
  throw new FsError(`"${requested}" is a directory; recursive is required.`, "not-file");
67
76
  }
77
+ const isSymlink = !dereference && stats.isSymbolicLink();
78
+ let referent: Referent | undefined;
79
+ if (isSymlink) {
80
+ try {
81
+ const followed = await ctx.sandbox.resolveFollow(requested);
82
+ const referentStats = await ctx.sandbox.stat(followed.full, requested);
83
+ referent = { dev: num(referentStats.dev), ino: num(referentStats.ino) };
84
+ } catch (error) {
85
+ /* v8 ignore next */
86
+ if (!(error instanceof FsError) || error.code !== "not-found") throw error;
87
+ }
88
+ }
68
89
  sources.push({
69
90
  requested,
70
91
  full: target.full,
71
92
  isDirectory: stats.isDirectory(),
72
- isSymlink: !dereference && stats.isSymbolicLink(),
93
+ isSymlink,
94
+ dev: num(stats.dev),
95
+ ino: num(stats.ino),
96
+ referent,
73
97
  });
74
98
  }
75
99
 
76
- const destTarget = await ctx.sandbox.resolveForCreate(input.destination);
100
+ const unfollowedTarget = await ctx.sandbox.resolveForCreate(input.destination);
101
+ const destinationTarget = await ctx.sandbox.resolveForWrite(input.destination);
77
102
  let destIsDirectory = false;
78
103
  try {
79
- destIsDirectory = (await fs.lstat(destTarget.full)).isDirectory();
104
+ destIsDirectory = (await fs.lstat(destinationTarget.full)).isDirectory();
80
105
  } catch (error) {
81
106
  /* v8 ignore next 2 */
82
107
  if (!isMissing(error)) throw fromErrno(error, "access");
@@ -85,21 +110,57 @@ export const cpTool: ToolSpec<Input> = {
85
110
  throw new FsError("Multiple sources require an existing directory destination.", "not-directory");
86
111
  }
87
112
 
88
- const jobs = sources.map((source) => ({
89
- source,
90
- destination:
91
- destIsDirectory || sources.length > 1
92
- ? path.join(destTarget.full, path.basename(path.resolve(source.requested)))
93
- : destTarget.full,
94
- }));
113
+ const jobs = await mapLimit(
114
+ sources,
115
+ ctx.concurrency,
116
+ async (source) => {
117
+ const unfollowed = input.noClobber === true || source.isSymlink;
118
+ const candidate =
119
+ destIsDirectory || sources.length > 1
120
+ ? path.join(destinationTarget.full, path.basename(path.resolve(source.requested)))
121
+ : unfollowed
122
+ ? unfollowedTarget.full
123
+ : destinationTarget.full;
124
+ const destination = unfollowed
125
+ ? await ctx.sandbox.resolveForCreate(candidate)
126
+ : await ctx.sandbox.resolveForWrite(candidate);
127
+ return { source, destination };
128
+ },
129
+ ctx.signal,
130
+ );
95
131
 
96
132
  for (const job of jobs) {
97
- if (job.source.full === job.destination) {
133
+ if (job.source.full === job.destination.full) {
98
134
  throw new FsError(`"${job.source.requested}" and destination are the same file.`, "invalid");
99
135
  }
100
- if (job.source.isDirectory && isSubpath(job.source.full, job.destination)) {
136
+ if (job.source.isDirectory && isSubpath(job.source.full, job.destination.full)) {
101
137
  throw new FsError(`Cannot copy a directory into itself: "${job.source.requested}".`, "invalid");
102
138
  }
139
+ let destinationStats: Awaited<ReturnType<typeof fs.lstat>> | undefined;
140
+ try {
141
+ destinationStats = await fs.lstat(job.destination.full);
142
+ } catch (error) {
143
+ /* v8 ignore next */
144
+ if (!isMissing(error)) throw fromErrno(error, "access");
145
+ }
146
+ if (
147
+ destinationStats !== undefined &&
148
+ num(destinationStats.dev) === job.source.dev &&
149
+ num(destinationStats.ino) === job.source.ino
150
+ ) {
151
+ throw new FsError(`"${job.source.requested}" and destination are the same file.`, "invalid");
152
+ }
153
+ if (
154
+ job.source.referent !== undefined &&
155
+ destinationStats !== undefined &&
156
+ job.source.referent.dev === num(destinationStats.dev) &&
157
+ job.source.referent.ino === num(destinationStats.ino)
158
+ ) {
159
+ throw new FsError(
160
+ `"${job.source.requested}" refers to the destination file itself.`,
161
+ "invalid",
162
+ );
163
+ }
103
164
  }
104
165
 
105
166
  const entries = [];
@@ -113,14 +174,16 @@ export const cpTool: ToolSpec<Input> = {
113
174
  });
114
175
  }
115
176
  for (const job of jobs) {
116
- const target = await ctx.sandbox.resolveForCreate(job.destination);
117
- entries.push({ target, boundary: path.dirname(target.full) });
177
+ entries.push({ target: job.destination, boundary: path.dirname(job.destination.full) });
118
178
  }
119
179
  await ctx.permission.assert(entries);
120
180
 
121
- const copied = await Promise.all(
122
- jobs.map((job) =>
123
- copyTree(job.source.full, job.destination, {
181
+ const limiter = createLimiter(ctx.concurrency);
182
+ const copied = await mapLimit(
183
+ jobs,
184
+ ctx.concurrency,
185
+ (job) =>
186
+ copyTree(job.source.full, job.destination.full, {
124
187
  recursive,
125
188
  dereference,
126
189
  preserve,
@@ -128,12 +191,13 @@ export const cpTool: ToolSpec<Input> = {
128
191
  update: input.update === true,
129
192
  signal: ctx.signal,
130
193
  concurrency: ctx.concurrency,
194
+ limiter,
131
195
  }),
132
- ),
196
+ ctx.signal,
133
197
  );
134
198
  const total = copied.reduce((sum, value) => sum + value, 0);
135
199
  const output = input.verbose === true
136
- ? jobs.map((job) => `'${job.source.requested}' -> '${job.destination}'`).join("\n")
200
+ ? jobs.map((job) => `'${job.source.requested}' -> '${job.destination.full}'`).join("\n")
137
201
  : "";
138
202
  return textResult(output, { copied: total, jobs: jobs.length, force: input.force === true });
139
203
  },
package/src/tools/cpio.ts CHANGED
@@ -8,6 +8,22 @@ import * as path from "node:path";
8
8
  import { Type, type Static } from "@sinclair/typebox";
9
9
  import { FsError, fromErrno } from "../core/errors.js";
10
10
  import { num, walkAll } from "../core/fsutil.js";
11
+ import { mapLimit } from "../core/parallel.js";
12
+ import {
13
+ archiveSourceName,
14
+ assertArchivePlan,
15
+ assertArchiveSymlinkPlan,
16
+ assertSafeLinkTarget,
17
+ chmodDirectoryNoFollow,
18
+ finalDirectoryPlans,
19
+ outputBoundary,
20
+ resolveArchiveTarget,
21
+ resolveOutputTarget,
22
+ safeDirectoryMode,
23
+ safeMode,
24
+ throwIfAborted,
25
+ writeOutput,
26
+ } from "../core/safe-output.js";
11
27
  import { collect } from "../core/stream.js";
12
28
  import { textResult, type ToolSpec } from "../core/types.js";
13
29
 
@@ -47,19 +63,14 @@ export const cpioTool: ToolSpec<Input> = {
47
63
  mutates: true,
48
64
  async run(ctx, input, io) {
49
65
  const archive = input.mode === "create"
50
- ? await ctx.sandbox.resolveForCreate(input.archive)
66
+ ? await resolveOutputTarget(ctx.sandbox, input.archive)
51
67
  : await ctx.sandbox.resolveFollow(input.archive);
52
- await ctx.permission.assert([{ target: archive, boundary: archive.full }]);
68
+ await ctx.permission.assert([{ target: archive, boundary: outputBoundary(archive.full) }]);
53
69
 
54
70
  if (input.mode === "create") {
55
71
  const entries = await collectEntries(ctx, input, io);
56
- const buffer = encode(entries);
57
- /* v8 ignore next 4 -- write errors are environment-dependent */
58
- try {
59
- await fs.writeFile(archive.full, buffer);
60
- } catch (error) {
61
- throw fromErrno(error);
62
- }
72
+ throwIfAborted(ctx.signal);
73
+ await writeOutput(archive.full, encode(entries), false, 0o666, ctx.signal);
63
74
  return textResult(input.verbose === true ? `${entries.map((entry) => entry.name).join("\n")}\n` : "", {
64
75
  archive: input.archive,
65
76
  members: entries.length,
@@ -81,34 +92,65 @@ export const cpioTool: ToolSpec<Input> = {
81
92
  return textResult(`${selected.map((entry) => entry.name).join("\n")}\n`, { members: selected.length });
82
93
  }
83
94
 
84
- const base = input.directory === undefined
85
- ? (await ctx.sandbox.resolveForCreate(".")).full
86
- : (await ctx.sandbox.resolveForCreate(input.directory)).full;
87
- for (const entry of selected) {
88
- const target = path.join(base, safeName(entry.name));
89
- await ctx.permission.assert([{
90
- target: { full: target, outside: false, requested: target, realAncestor: base },
91
- boundary: target,
92
- }]);
93
- }
94
- for (const entry of selected) {
95
- const target = path.join(base, safeName(entry.name));
96
- /* v8 ignore next -- extraction write errors are environment-dependent */
97
- try {
98
- if ((entry.mode & 0o170000) === 0o040000) {
99
- await fs.mkdir(target, { recursive: true });
100
- } else if ((entry.mode & 0o170000) === 0o120000) {
101
- await fs.mkdir(path.dirname(target), { recursive: true });
102
- await fs.symlink(entry.data.toString("utf8"), target);
103
- } else {
104
- await fs.mkdir(path.dirname(target), { recursive: true });
105
- await fs.writeFile(target, entry.data);
106
- await fs.chmod(target, entry.mode & 0o7777);
95
+ const root = input.directory === undefined
96
+ ? await resolveOutputTarget(ctx.sandbox, ".")
97
+ : await resolveOutputTarget(ctx.sandbox, input.directory);
98
+
99
+ const plan = await mapLimit(selected, ctx.concurrency, async (entry) => {
100
+ throwIfAborted(ctx.signal);
101
+ const name = safeName(entry.name);
102
+ const kind: "file" | "directory" | "symlink" = (entry.mode & 0o170000) === 0o040000
103
+ ? "directory"
104
+ : (entry.mode & 0o170000) === 0o120000
105
+ ? "symlink"
106
+ : "file";
107
+ if (kind === "symlink") assertSafeLinkTarget(entry.data.toString("utf8"));
108
+ const target = await resolveArchiveTarget(
109
+ ctx.sandbox,
110
+ root.full,
111
+ path.join(root.full, name),
112
+ kind,
113
+ );
114
+ return { entry, name, kind, target };
115
+ }, ctx.signal);
116
+ throwIfAborted(ctx.signal);
117
+ assertArchiveSymlinkPlan(plan);
118
+ await assertArchivePlan(ctx.permission, plan, { target: root, boundary: root.full });
119
+ for (const { entry, kind, target } of plan) {
120
+ throwIfAborted(ctx.signal);
121
+ if (kind === "directory") {
122
+ try {
123
+ await fs.mkdir(target.full, { recursive: true });
124
+ } catch (error) {
125
+ throw fromErrno(error);
107
126
  }
108
- } catch (error) {
109
- throw fromErrno(error);
127
+ } else if (kind === "symlink") {
128
+ /* v8 ignore next 3 -- extraction write errors are environment-dependent */
129
+ try {
130
+ await fs.mkdir(path.dirname(target.full), { recursive: true });
131
+ await fs.symlink(entry.data.toString("utf8"), target.full);
132
+ } catch (error) {
133
+ throw fromErrno(error);
134
+ }
135
+ } else {
136
+ /* v8 ignore next 3 -- extraction write errors are environment-dependent */
137
+ try {
138
+ await fs.mkdir(path.dirname(target.full), { recursive: true });
139
+ } catch (error) {
140
+ throw fromErrno(error);
141
+ }
142
+ const mode = safeMode(entry.mode);
143
+ await writeOutput(target.full, entry.data, false, mode, ctx.signal, mode);
110
144
  }
111
145
  }
146
+ const directories = finalDirectoryPlans(plan);
147
+ for (const item of directories) {
148
+ throwIfAborted(ctx.signal);
149
+ await chmodDirectoryNoFollow(
150
+ item.target.full,
151
+ safeDirectoryMode(item.entry.mode),
152
+ );
153
+ }
112
154
  return textResult(input.verbose === true ? `${selected.map((entry) => entry.name).join("\n")}\n` : "", {
113
155
  extracted: selected.length,
114
156
  });
@@ -136,10 +178,15 @@ async function collectEntries(
136
178
  : (await ctx.sandbox.resolveExisting(input.directory, { allowRoot: true })).full;
137
179
  const entries: Entry[] = [];
138
180
  for (const requested of input.paths) {
181
+ throwIfAborted(ctx.signal);
139
182
  const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
140
- await ctx.permission.assert([{ target, boundary: target.full }]);
141
183
  const stats = await ctx.sandbox.lstat(target.full, requested);
142
- entries.push(await entryFor(target.full, path.relative(base, target.full), stats));
184
+ await ctx.permission.assert([{
185
+ target,
186
+ boundary: ctx.sandbox.boundaryFor(target.full, stats.isDirectory() ? "directory" : "file"),
187
+ }]);
188
+ const name = archiveSourceName(requested, target.full, base, ctx.sandbox.root);
189
+ entries.push(await entryFor(target.full, name, stats));
143
190
  if (stats.isDirectory()) {
144
191
  for (const child of await walkAll(target.full, {
145
192
  recursive: true,
@@ -147,7 +194,9 @@ async function collectEntries(
147
194
  concurrency: ctx.concurrency,
148
195
  signal: ctx.signal,
149
196
  })) {
150
- entries.push(await entryFor(child.path, path.relative(base, child.path), child.stats));
197
+ throwIfAborted(ctx.signal);
198
+ const childName = path.join(name, path.relative(target.full, child.path));
199
+ entries.push(await entryFor(child.path, childName, child.stats));
151
200
  }
152
201
  }
153
202
  }
@@ -181,56 +230,142 @@ function encode(entries: readonly Entry[]): Buffer {
181
230
  const name = Buffer.from(`${entry.name}\0`, "utf8");
182
231
  const header = [
183
232
  "070701",
184
- octal(inode++),
185
- octal(entry.mode),
186
- octal(entry.uid),
187
- octal(entry.gid),
188
- octal(1),
189
- octal(entry.mtime),
190
- octal(entry.data.length),
191
- octal(0),
192
- octal(0),
193
- octal(0),
194
- octal(0),
195
- octal(name.length),
196
- octal(0),
233
+ hexField(inode++),
234
+ hexField(entry.mode),
235
+ hexField(entry.uid),
236
+ hexField(entry.gid),
237
+ hexField(1),
238
+ hexField(entry.mtime),
239
+ hexField(entry.data.length),
240
+ hexField(0),
241
+ hexField(0),
242
+ hexField(0),
243
+ hexField(0),
244
+ hexField(name.length),
245
+ hexField(0),
197
246
  ].join("");
198
- chunks.push(Buffer.from(header, "ascii"), name, pad4(name.length), entry.data, pad4(entry.data.length));
247
+ chunks.push(Buffer.from(header, "ascii"), name, pad4(110 + name.length), entry.data, pad4(entry.data.length));
199
248
  }
200
249
  const trailer = Buffer.from("TRAILER!!!\0", "utf8");
201
250
  chunks.push(
202
251
  Buffer.from(
203
- ["070701", octal(0), octal(0), octal(0), octal(0), octal(1), octal(now()), octal(0), octal(0), octal(0), octal(0), octal(0), octal(trailer.length), octal(0)].join(""),
252
+ ["070701", hexField(0), hexField(0), hexField(0), hexField(0), hexField(1), hexField(now()), hexField(0), hexField(0), hexField(0), hexField(0), hexField(0), hexField(trailer.length), hexField(0)].join(""),
204
253
  "ascii",
205
254
  ),
206
255
  trailer,
207
- pad4(trailer.length),
256
+ pad4(110 + trailer.length),
208
257
  );
209
258
  return Buffer.concat(chunks);
210
259
  }
211
260
 
212
261
  function decode(data: Buffer): Entry[] {
262
+ let firstError: unknown;
263
+ try {
264
+ return decodeWithPadding(data, false);
265
+ } catch (error) {
266
+ firstError = error;
267
+ }
268
+ try {
269
+ return decodeWithPadding(data, true);
270
+ } catch {
271
+ throw firstError;
272
+ }
273
+ }
274
+
275
+ function decodeWithPadding(data: Buffer, legacyNamePadding: boolean): Entry[] {
213
276
  const entries: Entry[] = [];
214
277
  let offset = 0;
278
+ let radix: 8 | 16 | undefined;
215
279
  for (;;) {
216
280
  if (offset + 110 > data.length) throw new FsError("Truncated cpio header.", "archive");
217
281
  if (data.subarray(offset, offset + 6).toString("ascii") !== "070701") {
218
282
  throw new FsError("Unsupported cpio format.", "archive");
219
283
  }
220
- const field = (index: number): number => Number.parseInt(data.subarray(offset + 6 + index * 8, offset + 14 + index * 8).toString("ascii"), 8);
221
- const mode = field(1);
222
- const uid = field(2);
223
- const gid = field(3);
224
- const mtime = field(5);
225
- const size = field(6);
226
- const nameSize = field(11);
284
+ const decoded = decodeFields(data, offset, radix);
285
+ radix ??= decoded.radix;
286
+ const fields = decoded.fields;
287
+ const mode = fields[1] as number;
288
+ const uid = fields[2] as number;
289
+ const gid = fields[3] as number;
290
+ const mtime = fields[5] as number;
291
+ const size = fields[6] as number;
292
+ const nameSize = fields[11] as number;
227
293
  const nameStart = offset + 110;
294
+ if (nameSize < 1 || nameStart + nameSize > data.length || data[nameStart + nameSize - 1] !== 0) {
295
+ throw new FsError("Truncated cpio name.", "archive");
296
+ }
297
+ const namePadding = legacyNamePadding ? align4(nameSize) : align4(nameStart + nameSize);
298
+ const dataStart = nameStart + nameSize + namePadding;
299
+ if (dataStart > data.length || dataStart + size > data.length) {
300
+ throw new FsError("Truncated cpio member.", "archive");
301
+ }
228
302
  const name = data.subarray(nameStart, nameStart + nameSize - 1).toString("utf8");
229
- const dataStart = nameStart + nameSize + align4(nameSize);
230
- if (name === "TRAILER!!!") return entries;
303
+ const dataPadding = legacyNamePadding ? align4(size) : align4(dataStart + size);
304
+ if (name === "TRAILER!!!") {
305
+ const trailerEnd = dataStart + size + dataPadding;
306
+ if (data.subarray(trailerEnd).some((byte) => byte !== 0)) {
307
+ throw new FsError("Trailing cpio data.", "archive");
308
+ }
309
+ return entries;
310
+ }
311
+ if ((mode & 0o170000) === 0) throw new FsError("Invalid cpio mode field.", "archive");
312
+ const next = dataStart + size + dataPadding;
313
+ if (next > data.length || next <= offset) throw new FsError("Truncated cpio member.", "archive");
231
314
  entries.push({ name, mode, uid, gid, mtime, data: data.subarray(dataStart, dataStart + size) });
232
- offset = dataStart + size + align4(size);
315
+ offset = next;
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Newc stores every numeric field as eight hexadecimal digits. Archives written
321
+ * by earlier releases of this plugin used octal, so a header whose hexadecimal
322
+ * mode has no file-type bits is parsed as legacy octal instead.
323
+ */
324
+ function decodeFields(
325
+ data: Buffer,
326
+ offset: number,
327
+ preferred?: 8 | 16,
328
+ ): { fields: number[]; radix: 8 | 16 } {
329
+ const raw = (index: number): string =>
330
+ data.subarray(offset + 6 + index * 8, offset + 14 + index * 8).toString("ascii");
331
+ let radix = preferred;
332
+ if (radix === undefined) {
333
+ const modeText = raw(1);
334
+ const hexMode = parseField(modeText, 16);
335
+ radix = 16;
336
+ if ((hexMode & 0xf000) === 0) {
337
+ const octalMode = parseField(modeText, 8);
338
+ if (hexMode === 0 && octalMode === 0) {
339
+ const nameText = raw(11);
340
+ const hexName = parseField(nameText, 16);
341
+ const octalName = /^[0-7]{8}$/.test(nameText) ? Number.parseInt(nameText, 8) : undefined;
342
+ if (nameFits(data, offset, hexName)) {
343
+ radix = 16;
344
+ } else if (octalName !== undefined && nameFits(data, offset, octalName)) {
345
+ radix = 8;
346
+ } else {
347
+ throw new FsError("Truncated cpio name.", "archive");
348
+ }
349
+ } else if ((octalMode & 0o170000) !== 0) {
350
+ radix = 8;
351
+ } else {
352
+ throw new FsError("Invalid cpio mode field.", "archive");
353
+ }
354
+ }
233
355
  }
356
+ const fields = Array.from({ length: 13 }, (_, index) => parseField(raw(index), radix as 8 | 16));
357
+ return { fields, radix };
358
+ }
359
+
360
+ function nameFits(data: Buffer, offset: number, size: number): boolean {
361
+ const start = offset + 110;
362
+ return size >= 1 && start + size <= data.length && data[start + size - 1] === 0;
363
+ }
364
+
365
+ function parseField(text: string, radix: 8 | 16): number {
366
+ const valid = radix === 16 ? /^[0-9a-fA-F]{8}$/.test(text) : /^[0-7]{8}$/.test(text);
367
+ if (!valid) throw new FsError("Invalid cpio numeric field.", "archive");
368
+ return Number.parseInt(text, radix);
234
369
  }
235
370
 
236
371
  function safeName(name: string): string {
@@ -242,8 +377,12 @@ function safeName(name: string): string {
242
377
  return parts.join("/");
243
378
  }
244
379
 
245
- function octal(value: number): string {
246
- return value.toString(8).padStart(8, "0").slice(-8);
380
+ /** Encode one newc numeric field, rejecting values the format cannot hold. */
381
+ export function hexField(value: number): string {
382
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {
383
+ throw new FsError(`cpio field out of range: ${value}`, "invalid");
384
+ }
385
+ return value.toString(16).padStart(8, "0");
247
386
  }
248
387
 
249
388
  function align4(value: number): number {