opencode-fs-plugin 3.5.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/zip.ts CHANGED
@@ -9,6 +9,22 @@ import { ZipFile as ZipWriter } from "yazl";
9
9
  import * as yauzl from "yauzl";
10
10
  import { Type, type Static } from "@sinclair/typebox";
11
11
  import { FsError, fromErrno } from "../core/errors.js";
12
+ import { walkAll } from "../core/fsutil.js";
13
+ import { mapLimit } from "../core/parallel.js";
14
+ import {
15
+ assertArchivePlan,
16
+ assertArchiveSymlinkPlan,
17
+ assertSafeLinkTarget,
18
+ chmodDirectoryNoFollow,
19
+ finalDirectoryPlans,
20
+ outputBoundary,
21
+ resolveArchiveTarget,
22
+ resolveOutputTarget,
23
+ safeDirectoryMode,
24
+ safeMode,
25
+ throwIfAborted,
26
+ writeOutput,
27
+ } from "../core/safe-output.js";
12
28
  import { collect } from "../core/stream.js";
13
29
  import { textResult, type ToolSpec } from "../core/types.js";
14
30
 
@@ -48,7 +64,7 @@ export const zipTool: ToolSpec<ZipInput> = {
48
64
  pipeable: "sink",
49
65
  mutates: true,
50
66
  async run(ctx, input, io) {
51
- const archive = await ctx.sandbox.resolveForCreate(input.archive);
67
+ const archive = await resolveOutputTarget(ctx.sandbox, input.archive);
52
68
  const requestedPaths = input.paths ?? [];
53
69
  if (requestedPaths.length === 0) {
54
70
  if (input.input === undefined && io.stdin === undefined) {
@@ -59,7 +75,7 @@ export const zipTool: ToolSpec<ZipInput> = {
59
75
  : await collect(io.stdin);
60
76
  const name = safeName(input.member ?? "stdin");
61
77
  if (name === undefined) throw new FsError("member must not be empty.", "invalid");
62
- await ctx.permission.assert([{ target: archive, boundary: archive.full }]);
78
+ await ctx.permission.assert([{ target: archive, boundary: outputBoundary(archive.full) }]);
63
79
  const writer = new ZipWriter();
64
80
  writer.addBuffer(data, name.split(path.sep).join("/"), {
65
81
  mtime: new Date(),
@@ -69,31 +85,35 @@ export const zipTool: ToolSpec<ZipInput> = {
69
85
  });
70
86
  writer.end();
71
87
  const streamed = await collect(writer.outputStream as AsyncIterable<Buffer>);
72
- /* v8 ignore next */
73
- await fs.writeFile(archive.full, streamed).catch((error) => {
74
- throw fromErrno(error);
75
- });
88
+ await writeOutput(archive.full, streamed, false, 0o666, ctx.signal);
76
89
  return textResult("", { archive: input.archive, members: 1 });
77
90
  }
78
91
 
79
92
  const members: Array<{ name: string; full: string; stats: Awaited<ReturnType<typeof fs.lstat>> }> = [];
80
93
  for (const requested of requestedPaths) {
94
+ throwIfAborted(ctx.signal);
81
95
  const target = await ctx.sandbox.resolveExisting(requested, { allowRoot: true });
82
96
  const stats = await ctx.sandbox.lstat(target.full, requested);
83
97
  const base = path.basename(path.resolve(requested));
84
98
  members.push({ name: base, full: target.full, stats });
85
- if (stats.isDirectory()) await collectMembers(target.full, base, members);
99
+ if (stats.isDirectory()) {
100
+ await collectMembers(target.full, base, members, ctx.concurrency, ctx.signal);
101
+ }
86
102
  }
87
- const entries = await Promise.all(
88
- members.map(async (member) => ({
103
+ const entries = await mapLimit(
104
+ members,
105
+ ctx.concurrency,
106
+ async (member) => ({
89
107
  target: await ctx.sandbox.resolveExisting(member.full, { allowRoot: true }),
90
108
  boundary: member.stats.isDirectory() ? member.full : path.dirname(member.full),
91
- })),
109
+ }),
110
+ ctx.signal,
92
111
  );
93
- await ctx.permission.assert([...entries, { target: archive, boundary: archive.full }]);
112
+ await ctx.permission.assert([...entries, { target: archive, boundary: outputBoundary(archive.full) }]);
94
113
 
95
114
  const writer = new ZipWriter();
96
115
  for (const member of members) {
116
+ throwIfAborted(ctx.signal);
97
117
  const name = member.name.split(path.sep).join("/");
98
118
  if (member.stats.isDirectory()) {
99
119
  /* v8 ignore next */
@@ -118,10 +138,7 @@ export const zipTool: ToolSpec<ZipInput> = {
118
138
  }
119
139
  writer.end();
120
140
  const data = await collect(writer.outputStream as AsyncIterable<Buffer>);
121
- /* v8 ignore next */
122
- await fs.writeFile(archive.full, data).catch((error) => {
123
- throw fromErrno(error);
124
- });
141
+ await writeOutput(archive.full, data, false, 0o666, ctx.signal);
125
142
  return textResult("", { archive: input.archive, members: members.length });
126
143
  },
127
144
  };
@@ -133,8 +150,8 @@ export const unzipTool: ToolSpec<UnzipInput> = {
133
150
  pipeable: false,
134
151
  mutates: true,
135
152
  async run(ctx, input) {
136
- const archive = await ctx.sandbox.resolveExisting(input.archive, { allowRoot: true });
137
- await ctx.permission.assert([{ target: archive, boundary: archive.full }]);
153
+ const archive = await ctx.sandbox.resolveFollow(input.archive);
154
+ await ctx.permission.assert([{ target: archive, boundary: outputBoundary(archive.full) }]);
138
155
  /* v8 ignore next */
139
156
  const buffer = await fs.readFile(archive.full).catch((error) => {
140
157
  throw fromErrno(error);
@@ -142,44 +159,90 @@ export const unzipTool: ToolSpec<UnzipInput> = {
142
159
  const zip = await openZip(buffer);
143
160
  const names: string[] = [];
144
161
  const rootTarget = input.directory === undefined
145
- ? await ctx.sandbox.resolveForCreate(".")
146
- : await ctx.sandbox.resolveForCreate(input.directory);
162
+ ? await resolveOutputTarget(ctx.sandbox, ".")
163
+ : await resolveOutputTarget(ctx.sandbox, input.directory);
147
164
  const root = rootTarget.full;
148
165
  if (input.mode === "list") {
149
- for (const entry of zip.entries) names.push(entry.fileName);
166
+ for (const entry of zip.entries) {
167
+ throwIfAborted(ctx.signal);
168
+ names.push(entry.fileName);
169
+ }
150
170
  return textResult(names.map((name) => `${name}\n`).join(""), { archive: input.archive, members: names });
151
171
  }
152
- await ctx.permission.assert([{ target: rootTarget, boundary: root }]);
153
- await fs.mkdir(root, { recursive: true });
172
+ const planned: Array<{
173
+ entry: yauzl.Entry;
174
+ name: string;
175
+ kind: "file" | "directory" | "symlink";
176
+ target: Awaited<ReturnType<typeof resolveArchiveTarget>>;
177
+ linkname: string | undefined;
178
+ mode: number;
179
+ }> = [];
180
+ const plannedPaths = new Set<string>();
154
181
  for (const entry of zip.entries) {
182
+ throwIfAborted(ctx.signal);
155
183
  const name = safeName(entry.fileName);
156
184
  /* v8 ignore next */
157
185
  if (name === undefined) continue;
158
- const destination = path.join(root, name);
159
- /* v8 ignore next */
160
- if (!isInside(root, destination)) throw new FsError(`Blocked archive path: ${entry.fileName}`, "archive");
161
- if (entry.fileName.endsWith("/")) {
162
- await fs.mkdir(destination, { recursive: true });
163
- continue;
186
+ const unixMode = entry.externalFileAttributes >>> 16;
187
+ const hasUnixMode = unixMode !== 0;
188
+ const kind = entry.fileName.endsWith("/")
189
+ ? "directory"
190
+ : hasUnixMode && (unixMode & 0o170000) === 0o120000
191
+ ? "symlink"
192
+ : "file";
193
+ const mode = hasUnixMode ? unixMode & 0o7777 : kind === "directory" ? 0o755 : 0o644;
194
+ const target = await resolveArchiveTarget(
195
+ ctx.sandbox,
196
+ root,
197
+ path.join(root, name),
198
+ kind,
199
+ );
200
+ if (kind !== "directory") {
201
+ if (input.noOverwrite === true && (plannedPaths.has(target.full) || (await exists(target.full)))) {
202
+ continue;
203
+ }
204
+ if (input.overwrite !== true && (await exists(target.full))) {
205
+ throw new FsError(`File exists: "${target.full}"`, "exists");
206
+ }
164
207
  }
165
- if (input.noOverwrite === true && (await exists(destination))) continue;
166
- if (input.overwrite !== true && (await exists(destination))) {
167
- throw new FsError(`File exists: "${destination}"`, "exists");
208
+ let linkname: string | undefined;
209
+ if (kind === "symlink") {
210
+ linkname = (await collect(await openEntry(zip.file, entry))).toString("utf8");
211
+ assertSafeLinkTarget(linkname);
168
212
  }
169
- await fs.mkdir(path.dirname(destination), { recursive: true });
170
- const mode = (entry.externalFileAttributes >>> 16) & 0o170777;
171
- const data = await collect(await openEntry(zip.file, entry));
172
- if ((mode & 0o170000) === 0o120000) {
173
- const target = data.toString("utf8");
174
- /* v8 ignore next */
175
- if (path.isAbsolute(target) || target.split("/").includes("..")) {
176
- throw new FsError(`Blocked symlink target: ${target}`, "archive");
177
- }
178
- await fs.symlink(target, destination);
213
+ plannedPaths.add(target.full);
214
+ planned.push({ entry, name, kind, target, linkname, mode });
215
+ }
216
+ throwIfAborted(ctx.signal);
217
+ assertArchiveSymlinkPlan(planned);
218
+ await assertArchivePlan(ctx.permission, planned, { target: rootTarget, boundary: root });
219
+ await fs.mkdir(root, { recursive: true });
220
+ for (const item of planned) {
221
+ throwIfAborted(ctx.signal);
222
+ if (item.kind === "directory") {
223
+ await fs.mkdir(item.target.full, { recursive: true });
224
+ } else if (item.kind === "symlink") {
225
+ await fs.mkdir(path.dirname(item.target.full), { recursive: true });
226
+ await fs.symlink(item.linkname as string, item.target.full);
179
227
  } else {
180
- await fs.writeFile(destination, data, { mode: mode & 0o7777 });
228
+ const data = await collect(await openEntry(zip.file, item.entry));
229
+ await fs.mkdir(path.dirname(item.target.full), { recursive: true });
230
+ const mode = safeMode(item.mode);
231
+ await writeOutput(
232
+ item.target.full,
233
+ data,
234
+ false,
235
+ mode,
236
+ ctx.signal,
237
+ mode,
238
+ );
181
239
  }
182
- names.push(name);
240
+ names.push(item.name);
241
+ }
242
+ const directories = finalDirectoryPlans(planned);
243
+ for (const item of directories) {
244
+ throwIfAborted(ctx.signal);
245
+ await chmodDirectoryNoFollow(item.target.full, safeDirectoryMode(item.mode));
183
246
  }
184
247
  zip.file.close();
185
248
  return textResult("", { archive: input.archive, members: names });
@@ -190,14 +253,19 @@ async function collectMembers(
190
253
  full: string,
191
254
  name: string,
192
255
  members: Array<{ name: string; full: string; stats: Awaited<ReturnType<typeof fs.lstat>> }>,
256
+ concurrency: number,
257
+ signal: AbortSignal,
193
258
  ): Promise<void> {
194
- const entries = await fs.readdir(full);
195
- for (const entry of entries) {
196
- const child = path.join(full, entry);
197
- const member = `${name}/${entry}`;
198
- const stats = await fs.lstat(child);
199
- members.push({ name: member, full: child, stats });
200
- if (stats.isDirectory()) await collectMembers(child, member, members);
259
+ throwIfAborted(signal);
260
+ const walked = await walkAll(full, {
261
+ recursive: true,
262
+ includeHidden: true,
263
+ concurrency,
264
+ signal,
265
+ });
266
+ for (const entry of walked) {
267
+ const relative = path.relative(full, entry.path).split(path.sep).join("/");
268
+ members.push({ name: `${name}/${relative}`, full: entry.path, stats: entry.stats });
201
269
  }
202
270
  }
203
271
 
@@ -247,10 +315,7 @@ function safeName(name: string): string | undefined {
247
315
  return parts.length === 0 ? undefined : parts.join(path.sep);
248
316
  }
249
317
 
250
- function isInside(root: string, target: string): boolean {
251
- const rel = path.relative(root, target);
252
- return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
253
- }
318
+
254
319
 
255
320
  async function exists(target: string): Promise<boolean> {
256
321
  try {