@koishi-ce/plugin-explorer 1.2.4 → 1.2.6

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/lib/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { mkdir, readdir, readlink, rename, rm } from "node:fs/promises";
2
- import { join, relative, resolve } from "node:path";
1
+ import { lstat, mkdir, readdir, readlink, realpath, rename, rm } from "node:fs/promises";
2
+ import { isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
3
3
  import { DataService, clientEntry } from "@koishi-ce/console";
4
4
  import { Schema } from "@koishi-ce/koishi";
5
5
  import { fileTypeFromBuffer } from "file-type";
@@ -82,7 +82,7 @@ function detectEncoding(buffer) {
82
82
  *
83
83
  * 以 DataService 形式向控制台客户端推送根目录的完整文件树(Entry[]),
84
84
  * 并注册 explorer/read、write、mkdir、remove、rename、refresh 六个
85
- * RPC 事件(均要求 authority >= 4),供浏览器端执行实际的文件操作。
85
+ * RPC 事件(均要求启用鉴权且 authority >= 4),供浏览器端执行文件操作。
86
86
  * 浏览器端对应实现在 ../client/(index.vue 文件树 + CodeMirror 编辑器)。
87
87
  */
88
88
  /**
@@ -115,13 +115,20 @@ var Explorer = class extends DataService {
115
115
  /** 文件树的根目录(ctx.baseDir + 配置的 root 解析出的绝对路径) */
116
116
  root;
117
117
  constructor(ctx, config) {
118
- super(ctx, "explorer", { authority: 4 });
118
+ const access = {
119
+ authority: 4,
120
+ requireAuth: true
121
+ };
122
+ super(ctx, "explorer", access);
119
123
  ctx.console.addEntry(clientEntry(import.meta.url));
120
- this.globFilter = picomatch(config.ignored ?? [], { windows: process.platform === "win32" });
124
+ this.globFilter = picomatch(config.ignored ?? [], {
125
+ windows: process.platform === "win32",
126
+ nocase: process.platform === "win32"
127
+ });
121
128
  this.root = resolve(ctx.baseDir, config.root ?? "");
122
129
  ctx.console.addListener("explorer/read", async (filename) => {
123
- filename = join(this.root, filename);
124
- const buffer = Buffer.from(await Bun.file(filename).arrayBuffer());
130
+ const { realPath } = await this.resolvePath(filename);
131
+ const buffer = Buffer.from(await Bun.file(realPath).arrayBuffer());
125
132
  const result = await fileTypeFromBuffer(readHead(buffer));
126
133
  const file = { base64: buffer.toString("base64") };
127
134
  if (result) file.mime = result.mime;
@@ -130,34 +137,107 @@ var Explorer = class extends DataService {
130
137
  if (encoding) file.encoding = encoding;
131
138
  }
132
139
  return file;
133
- }, { authority: 4 });
140
+ }, access);
134
141
  ctx.console.addListener("explorer/write", async (filename, content, binary) => {
135
- filename = join(this.root, filename);
142
+ const { realPath } = await this.resolvePath(filename, true);
136
143
  if (binary) {
137
144
  const buffer = Buffer.from(content, "base64");
138
- await Bun.write(filename, buffer);
139
- } else await Bun.write(filename, content);
145
+ await Bun.write(realPath, buffer);
146
+ } else await Bun.write(realPath, content);
140
147
  this.refresh();
141
- }, { authority: 4 });
148
+ }, access);
142
149
  ctx.console.addListener("explorer/mkdir", async (filename) => {
143
- filename = join(this.root, filename);
144
- await mkdir(filename);
150
+ const { path } = await this.resolvePath(filename, true);
151
+ await mkdir(path);
145
152
  this.refresh();
146
- }, { authority: 4 });
153
+ }, access);
147
154
  ctx.console.addListener("explorer/remove", async (filename) => {
148
- filename = join(this.root, filename);
149
- await rm(filename, { recursive: true });
155
+ const source = await this.resolvePath(filename);
156
+ await this.checkDirectoryContents(source);
157
+ await rm(source.path, { recursive: true });
150
158
  this.refresh();
151
- }, { authority: 4 });
159
+ }, access);
152
160
  ctx.console.addListener("explorer/rename", async (oldValue, newValue) => {
153
- oldValue = join(this.root, oldValue);
154
- newValue = join(this.root, newValue);
155
- await rename(oldValue, newValue);
161
+ const source = await this.resolvePath(oldValue);
162
+ const destination = await this.resolvePath(newValue, true);
163
+ await this.checkDirectoryContents(source, destination);
164
+ await rename(source.path, destination.path);
156
165
  this.refresh();
157
- }, { authority: 4 });
166
+ }, access);
158
167
  ctx.console.addListener("explorer/refresh", () => {
159
168
  this.refresh();
160
- }, { authority: 4 });
169
+ }, access);
170
+ }
171
+ checkIgnored(segments) {
172
+ let path = "";
173
+ for (const segment of segments) {
174
+ path = join(path, segment);
175
+ if (this.globFilter(path)) throw new Error("文件路径受保护。");
176
+ }
177
+ }
178
+ checkPath(root, target) {
179
+ const path = relative(root, target);
180
+ if (path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path)) throw new Error("文件路径超出根目录。");
181
+ const segments = path ? path.split(sep) : [];
182
+ this.checkIgnored(segments);
183
+ return segments;
184
+ }
185
+ async resolvePath(filename, allowMissing = false) {
186
+ if (typeof filename !== "string" || filename.includes("\0") || win32.isAbsolute(filename) || /^[a-z]:/i.test(filename)) throw new Error("需要根目录内的相对文件路径。");
187
+ const logical = resolve(this.root, filename);
188
+ const segments = this.checkPath(this.root, logical);
189
+ if (!segments.length) throw new Error("不能直接操作根目录。");
190
+ if (process.platform === "win32" && segments.some((segment) => /[. ]$|:/.test(segment) || /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$) *(?:\.|$)/i.test(segment))) throw new Error("文件路径包含无效的 Windows 路径段。");
191
+ const root = await realpath(this.root);
192
+ let realPath = root;
193
+ let path = root;
194
+ for (const [index, segment] of segments.entries()) {
195
+ path = join(realPath, segment);
196
+ this.checkPath(root, path);
197
+ try {
198
+ await lstat(path);
199
+ } catch (error) {
200
+ if (!allowMissing || error.code !== "ENOENT") throw error;
201
+ path = join(path, ...segments.slice(index + 1));
202
+ this.checkPath(root, path);
203
+ return {
204
+ path,
205
+ realPath: path,
206
+ logical,
207
+ root
208
+ };
209
+ }
210
+ realPath = await realpath(path);
211
+ this.checkPath(root, realPath);
212
+ }
213
+ return {
214
+ path,
215
+ realPath,
216
+ logical,
217
+ root
218
+ };
219
+ }
220
+ async checkDirectoryContents(source, destination) {
221
+ if (!(await lstat(source.path)).isDirectory()) return;
222
+ for (const entry of await readdir(source.path, { withFileTypes: true })) {
223
+ const child = {
224
+ ...source,
225
+ path: join(source.path, entry.name),
226
+ logical: join(source.logical, entry.name)
227
+ };
228
+ this.checkPath(source.root, child.path);
229
+ this.checkPath(this.root, child.logical);
230
+ const target = destination && {
231
+ ...destination,
232
+ path: join(destination.path, entry.name),
233
+ logical: join(destination.logical, entry.name)
234
+ };
235
+ if (target) {
236
+ this.checkPath(target.root, target.path);
237
+ this.checkPath(this.root, target.logical);
238
+ }
239
+ if (entry.isDirectory()) await this.checkDirectoryContents(child, target);
240
+ }
161
241
  }
162
242
  /**
163
243
  * 递归遍历目录,生成排序后的文件树。
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@koishi-ce/plugin-explorer",
3
3
  "description": "File explorer and editor for Koishi",
4
- "version": "1.2.4",
4
+ "version": "1.2.6",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "build:client": "bun ../../../packages/web/builder/src/bin.ts build ."
@@ -66,7 +66,7 @@
66
66
  "@koishi-ce/koishi": "^1.0.0"
67
67
  },
68
68
  "devDependencies": {
69
- "@codemirror/commands": "^6.11.1",
69
+ "@codemirror/commands": "^6.11.2",
70
70
  "@codemirror/lang-css": "^6.3.1",
71
71
  "@codemirror/lang-html": "^6.4.12",
72
72
  "@codemirror/lang-javascript": "^6.2.5",
@@ -82,19 +82,19 @@
82
82
  "@codemirror/legacy-modes": "^6.5.5",
83
83
  "@codemirror/state": "^6.7.5",
84
84
  "@codemirror/theme-one-dark": "^6.1.3",
85
- "@codemirror/view": "^6.43.15",
85
+ "@codemirror/view": "^6.44.2",
86
86
  "@koishi-ce/client": "^1.4.5",
87
- "@koishi-ce/plugin-console": "^1.4.6",
87
+ "@koishi-ce/plugin-console": "^1.4.8",
88
88
  "@koishi-ce/koishi": "^1.0.22",
89
89
  "@types/picomatch": "^4.0.3",
90
- "@vueuse/core": "^15.0.0",
90
+ "@vueuse/core": "^15.1.0",
91
91
  "codemirror": "^6.0.2",
92
92
  "element-plus": "^2.14.8",
93
- "vue": "^3.5.45",
94
- "vue-router": "^5.5.1"
93
+ "vue": "^3.5.46",
94
+ "vue-router": "^5.5.3"
95
95
  },
96
96
  "dependencies": {
97
- "@koishi-ce/console": "^1.1.2",
97
+ "@koishi-ce/console": "^1.1.3",
98
98
  "chardet": "^2.2.0",
99
99
  "file-type": "^22.3.0",
100
100
  "picomatch": "^4.0.7"
package/src/index.ts CHANGED
@@ -7,18 +7,27 @@
7
7
  *
8
8
  * 以 DataService 形式向控制台客户端推送根目录的完整文件树(Entry[]),
9
9
  * 并注册 explorer/read、write、mkdir、remove、rename、refresh 六个
10
- * RPC 事件(均要求 authority >= 4),供浏览器端执行实际的文件操作。
10
+ * RPC 事件(均要求启用鉴权且 authority >= 4),供浏览器端执行文件操作。
11
11
  * 浏览器端对应实现在 ../client/(index.vue 文件树 + CodeMirror 编辑器)。
12
12
  */
13
13
 
14
14
  import {
15
+ lstat,
15
16
  mkdir,
16
17
  readdir,
17
18
  readlink,
19
+ realpath,
18
20
  rename,
19
21
  rm,
20
22
  } from "node:fs/promises";
21
- import { join, relative, resolve } from "node:path";
23
+ import {
24
+ isAbsolute,
25
+ join,
26
+ relative,
27
+ resolve,
28
+ sep,
29
+ win32,
30
+ } from "node:path";
22
31
  import {
23
32
  clientEntry,
24
33
  DataService,
@@ -93,6 +102,13 @@ export interface Entry {
93
102
  loading?: Promise<File>;
94
103
  }
95
104
 
105
+ interface ResolvedPath {
106
+ path: string;
107
+ realPath: string;
108
+ logical: string;
109
+ root: string;
110
+ }
111
+
96
112
  /**
97
113
  * explorer 数据服务:向客户端广播根目录的文件树。
98
114
  *
@@ -125,7 +141,8 @@ class Explorer extends DataService<Entry[]> {
125
141
  root: string;
126
142
 
127
143
  constructor(ctx: Context, config: Explorer.Config) {
128
- super(ctx, "explorer", { authority: 4 });
144
+ const access = { authority: 4, requireAuth: true };
145
+ super(ctx, "explorer", access);
129
146
 
130
147
  ctx.console.addEntry(clientEntry(import.meta.url));
131
148
 
@@ -134,6 +151,7 @@ class Explorer extends DataService<Entry[]> {
134
151
  // 反斜杠路径全部匹配失败;故 windows 显式声明,不依赖该注入行为
135
152
  this.globFilter = picomatch(config.ignored ?? [], {
136
153
  windows: process.platform === "win32",
154
+ nocase: process.platform === "win32",
137
155
  });
138
156
  this.root = resolve(ctx.baseDir, config.root ?? "");
139
157
 
@@ -145,9 +163,10 @@ class Explorer extends DataService<Entry[]> {
145
163
  ctx.console.addListener(
146
164
  "explorer/read",
147
165
  async (filename) => {
148
- filename = join(this.root, filename);
166
+ const { realPath } =
167
+ await this.resolvePath(filename);
149
168
  const buffer = Buffer.from(
150
- await Bun.file(filename).arrayBuffer(),
169
+ await Bun.file(realPath).arrayBuffer(),
151
170
  );
152
171
  // 只取头部供嗅探:file-type 仅读魔数(对样本长度不敏感,
153
172
  // 实测 4 KB 与 8 MB 均为 10–51 µs),无需扫全量
@@ -169,7 +188,7 @@ class Explorer extends DataService<Entry[]> {
169
188
  }
170
189
  return file;
171
190
  },
172
- { authority: 4 },
191
+ access,
173
192
  );
174
193
 
175
194
  // 写入文件:binary 为 true 时 content 为 base64(上传场景),
@@ -177,47 +196,61 @@ class Explorer extends DataService<Entry[]> {
177
196
  ctx.console.addListener(
178
197
  "explorer/write",
179
198
  async (filename, content, binary) => {
180
- filename = join(this.root, filename);
199
+ const { realPath } = await this.resolvePath(
200
+ filename,
201
+ true,
202
+ );
181
203
  if (binary) {
182
204
  const buffer = Buffer.from(content, "base64");
183
- await Bun.write(filename, buffer);
205
+ await Bun.write(realPath, buffer);
184
206
  } else {
185
- await Bun.write(filename, content);
207
+ await Bun.write(realPath, content);
186
208
  }
187
209
  this.refresh();
188
210
  },
189
- { authority: 4 },
211
+ access,
190
212
  );
191
213
 
192
214
  ctx.console.addListener(
193
215
  "explorer/mkdir",
194
216
  async (filename) => {
195
- filename = join(this.root, filename);
196
- await mkdir(filename);
217
+ const { path } = await this.resolvePath(
218
+ filename,
219
+ true,
220
+ );
221
+ await mkdir(path);
197
222
  this.refresh();
198
223
  },
199
- { authority: 4 },
224
+ access,
200
225
  );
201
226
 
202
227
  ctx.console.addListener(
203
228
  "explorer/remove",
204
229
  async (filename) => {
205
- filename = join(this.root, filename);
206
- await rm(filename, { recursive: true });
230
+ const source = await this.resolvePath(filename);
231
+ await this.checkDirectoryContents(source);
232
+ await rm(source.path, { recursive: true });
207
233
  this.refresh();
208
234
  },
209
- { authority: 4 },
235
+ access,
210
236
  );
211
237
 
212
238
  ctx.console.addListener(
213
239
  "explorer/rename",
214
240
  async (oldValue, newValue) => {
215
- oldValue = join(this.root, oldValue);
216
- newValue = join(this.root, newValue);
217
- await rename(oldValue, newValue);
241
+ const source = await this.resolvePath(oldValue);
242
+ const destination = await this.resolvePath(
243
+ newValue,
244
+ true,
245
+ );
246
+ await this.checkDirectoryContents(
247
+ source,
248
+ destination,
249
+ );
250
+ await rename(source.path, destination.path);
218
251
  this.refresh();
219
252
  },
220
- { authority: 4 },
253
+ access,
221
254
  );
222
255
 
223
256
  ctx.console.addListener(
@@ -225,10 +258,123 @@ class Explorer extends DataService<Entry[]> {
225
258
  () => {
226
259
  this.refresh();
227
260
  },
228
- { authority: 4 },
261
+ access,
229
262
  );
230
263
  }
231
264
 
265
+ private checkIgnored(segments: string[]) {
266
+ let path = "";
267
+ for (const segment of segments) {
268
+ path = join(path, segment);
269
+ if (this.globFilter(path))
270
+ throw new Error("文件路径受保护。");
271
+ }
272
+ }
273
+
274
+ private checkPath(root: string, target: string) {
275
+ const path = relative(root, target);
276
+ if (
277
+ path === ".." ||
278
+ path.startsWith(`..${sep}`) ||
279
+ isAbsolute(path)
280
+ ) {
281
+ throw new Error("文件路径超出根目录。");
282
+ }
283
+ const segments = path ? path.split(sep) : [];
284
+ this.checkIgnored(segments);
285
+ return segments;
286
+ }
287
+
288
+ private async resolvePath(
289
+ filename: string,
290
+ allowMissing = false,
291
+ ): Promise<ResolvedPath> {
292
+ if (
293
+ typeof filename !== "string" ||
294
+ filename.includes("\0") ||
295
+ win32.isAbsolute(filename) ||
296
+ /^[a-z]:/i.test(filename)
297
+ ) {
298
+ throw new Error("需要根目录内的相对文件路径。");
299
+ }
300
+ const logical = resolve(this.root, filename);
301
+ const segments = this.checkPath(this.root, logical);
302
+ if (!segments.length)
303
+ throw new Error("不能直接操作根目录。");
304
+ if (
305
+ process.platform === "win32" &&
306
+ segments.some(
307
+ (segment) =>
308
+ /[. ]$|:/.test(segment) ||
309
+ /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$) *(?:\.|$)/i.test(
310
+ segment,
311
+ ),
312
+ )
313
+ ) {
314
+ throw new Error(
315
+ "文件路径包含无效的 Windows 路径段。",
316
+ );
317
+ }
318
+
319
+ const root = await realpath(this.root);
320
+ let realPath = root;
321
+ let path = root;
322
+ for (const [index, segment] of segments.entries()) {
323
+ path = join(realPath, segment);
324
+ this.checkPath(root, path);
325
+ try {
326
+ await lstat(path);
327
+ } catch (error) {
328
+ if (
329
+ !allowMissing ||
330
+ (error as NodeJS.ErrnoException).code !== "ENOENT"
331
+ )
332
+ throw error;
333
+ path = join(path, ...segments.slice(index + 1));
334
+ this.checkPath(root, path);
335
+ return { path, realPath: path, logical, root };
336
+ }
337
+ // lstat 能区分悬空链接与不存在的目录项。链接即使悬空也必须通过 realpath。
338
+ realPath = await realpath(path);
339
+ this.checkPath(root, realPath);
340
+ }
341
+ // 读写可直接使用真实路径。删除和重命名保留最后一段,以操作链接本身。
342
+ return { path, realPath, logical, root };
343
+ }
344
+
345
+ private async checkDirectoryContents(
346
+ source: Pick<ResolvedPath, "path" | "logical" | "root">,
347
+ destination?: Pick<
348
+ ResolvedPath,
349
+ "path" | "logical" | "root"
350
+ >,
351
+ ) {
352
+ if (!(await lstat(source.path)).isDirectory()) return;
353
+ // 递归删除和目录移动也会改动子项,逐项检查且不跟随目录链接。
354
+ for (const entry of await readdir(source.path, {
355
+ withFileTypes: true,
356
+ })) {
357
+ const child = {
358
+ ...source,
359
+ path: join(source.path, entry.name),
360
+ logical: join(source.logical, entry.name),
361
+ };
362
+ this.checkPath(source.root, child.path);
363
+ this.checkPath(this.root, child.logical);
364
+ const target = destination && {
365
+ ...destination,
366
+ path: join(destination.path, entry.name),
367
+ logical: join(destination.logical, entry.name),
368
+ };
369
+ if (target) {
370
+ this.checkPath(target.root, target.path);
371
+ this.checkPath(this.root, target.logical);
372
+ }
373
+ if (entry.isDirectory())
374
+ await this.checkDirectoryContents(child, target);
375
+ }
376
+ }
377
+
232
378
  /**
233
379
  * 递归遍历目录,生成排序后的文件树。
234
380
  * 排序规则:目录排在最前,其余按名称字母序;被 globFilter