Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorkspaceFileSystem.ts

575 lines21.2 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeFSP from "node:fs/promises";
4​
5import type {
6 FilesystemEntryMetadata,
7 FilesystemGetMetadataInput,
8 FilesystemGetMetadataResult,
9 ProjectReadFileInput,
10 ProjectReadFileResult,
11 ProjectWriteFileInput,
12 ProjectWriteFileResult,
13} from "@t3tools/contracts";
14import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import { isNetworkPath } from "@t3tools/shared/path";
17import * as Context from "effect/Context";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Path from "effect/Path";
22import * as Schema from "effect/Schema";
23​
24import * as KnownWorkspaces from "./KnownWorkspaces.ts";
25import * as WorkspaceEntries from "./WorkspaceEntries.ts";
26import * as WorkspacePaths from "./WorkspacePaths.ts";
27import { fileHeaderMimeType } from "./fileHeaderMimeType.ts";
28​
29const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
30​
31// NTFS reaches .git through trailing dots/spaces, stream suffixes and GIT~1; compare uppercased names.
32const isGitMetadataName = (segment: string) => {
33 const name = (segment.split(":")[0] ?? "").replace(/[. ]+$/, "").toUpperCase();
34 return name === ".GIT" || name === "GIT~1";
35};
36​
37export class WorkspaceFileSystemOperationError extends Schema.TaggedError<WorkspaceFileSystemOperationError>()(
38 "WorkspaceFileSystemOperationError",
39 {
40 workspaceRoot: Schema.String,
41 relativePath: Schema.String,
42 resolvedPath: Schema.String,
43 operationPath: Schema.String,
44 operation: Schema.Literals([
45 "realpath-workspace-root",
46 "realpath-target",
47 "open",
48 "stat",
49 "read",
50 "close",
51 "make-directory",
52 "write-file",
53 ]),
54 cause: Schema.Defect(),
55 },
56) {
57 override get message(): string {
58 return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;
59 }
61​
62export class WorkspaceFilePathEscapeError extends Schema.TaggedError<WorkspaceFilePathEscapeError>()(
63 "WorkspaceFilePathEscapeError",
64 {
65 workspaceRoot: Schema.String,
66 relativePath: Schema.String,
67 resolvedWorkspaceRoot: Schema.String,
68 resolvedPath: Schema.String,
69 },
70) {
71 override get message(): string {
72 return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;
73 }
75​
76export class WorkspacePathNotFileError extends Schema.TaggedError<WorkspacePathNotFileError>()(
77 "WorkspacePathNotFileError",
78 {
79 workspaceRoot: Schema.String,
80 relativePath: Schema.String,
81 resolvedPath: Schema.String,
82 },
83) {
84 override get message(): string {
85 return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;
86 }
88​
89export class WorkspaceBinaryFileError extends Schema.TaggedError<WorkspaceBinaryFileError>()(
90 "WorkspaceBinaryFileError",
91 {
92 workspaceRoot: Schema.String,
93 relativePath: Schema.String,
94 resolvedPath: Schema.String,
95 },
96) {
97 override get message(): string {
98 return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;
99 }
101​
102export const WorkspaceFileSystemError = Schema.Union([
103 WorkspaceFileSystemOperationError,
104 WorkspaceFilePathEscapeError,
105 WorkspacePathNotFileError,
106 WorkspaceBinaryFileError,
107]);
108export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
109​
110export class WorkspaceFileSystem extends Context.Service<
111 WorkspaceFileSystem,
112 {
113 readonly getMetadata: (
114 input: FilesystemGetMetadataInput,
115 ) => Effect.Effect<FilesystemGetMetadataResult>;
116​
117 readonly readFile: (
118 input: ProjectReadFileInput,
119 ) => Effect.Effect<
120 ProjectReadFileResult,
121 WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError
122 >;
123 /** Writes inside a known workspace only. */
124 readonly writeFile: (
125 input: ProjectWriteFileInput,
126 ) => Effect.Effect<
127 ProjectWriteFileResult,
128 | WorkspaceFileSystemError
129 | WorkspacePaths.WorkspacePathOutsideRootError
130 | KnownWorkspaces.UnknownWorkspaceError
131 >;
132 }
133>()("t3/workspace/WorkspaceFileSystem") {}
134​
135/** @public */
136export const make = Effect.gen(function* () {
137 const fileSystem = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
139 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
140 const knownWorkspaces = yield* KnownWorkspaces.KnownWorkspaces;
141 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
142​
143 const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
144 const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
145 // Chips ask as soon as an agent's message renders, and touching a network
146 // path makes Windows sign in to its host with the user's NTLM credentials.
147 if (!path.isAbsolute(expandedPath) || isNetworkPath(expandedPath)) return null;
148 const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
149 if (stat._tag === "None") return null;
150 if (stat.value.type === "Directory") return { kind: "directory" } as const;
151 if (stat.value.type !== "File") return { kind: "other" } as const;
152 let mimeType: string | undefined;
153 if (path.extname(expandedPath) === "" && stat.value.size > 0) {
154 mimeType = yield* Effect.tryPromise({
155 try: async () => {
156 const handle = await NodeFSP.open(
157 expandedPath,
158 NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK,
159 );
160 try {
161 if (!(await handle.stat()).isFile()) return undefined;
162 const buffer = Buffer.alloc(512);
163 const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
164 return fileHeaderMimeType(buffer.subarray(0, bytesRead));
165 } finally {
166 await handle.close();
167 }
168 },
169 catch: () => undefined,
170 }).pipe(Effect.catch(() => Effect.succeed(undefined)));
171 }
172 return {
173 kind: "file",
174 byteLength: Number(stat.value.size),
175 ...(mimeType === undefined ? {} : { mimeType }),
176 } satisfies FilesystemEntryMetadata;
177 });
178​
179 const getMetadata: WorkspaceFileSystem["Service"]["getMetadata"] = Effect.fn(
180 "WorkspaceFileSystem.getMetadata",
181 )(function* (input) {
182 const paths = [...new Set(input.paths)];
183 const entries = yield* Effect.forEach(paths, metadataForPath, { concurrency: 8 });
184 const byPath = new Map(paths.map((value, index) => [value, entries[index] ?? null]));
185 return { entries: input.paths.map((value) => byPath.get(value) ?? null) };
186 });
187​
188 /** Both paths must already be real paths. */
189 const isInsideRealRoot = (realWorkspaceRoot: string, realPath: string) => {
190 const relative = path.relative(realWorkspaceRoot, realPath);
191 return !(
192 relative.startsWith(`..${path.sep}`) ||
193 relative === ".." ||
194 path.isAbsolute(relative)
195 );
196 };
197​
198 // Reject Git folders, including renamed bare repos whose config/hooks can execute; paths must be normalized.
199 // Stop at linked worktrees' .git files since worktrees can sit inside bare repos.
200 const isInGitFolder = async (absolutePath: string) => {
201 if (absolutePath.split(path.sep).some(isGitMetadataName)) return true;
202 for (let folder = path.dirname(absolutePath); ; folder = path.dirname(folder)) {
203 const [head, commondir, objects, refs, dotGit] = await Promise.all(
204 ["HEAD", "commondir", "objects", "refs", ".git"].map((name) =>
205 NodeFSP.lstat(path.join(folder, name)).catch((error: NodeJS.ErrnoException) => {
206 // Any other failure leaves the folder unknown, so the write is refused.
207 if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
208 throw error;
209 }),
210 ),
211 );
212 // Git recognizes HEAD with commondir or objects/refs as a repository.
213 if (head && (commondir || (objects && refs))) return true;
214 if (dotGit?.isFile() || path.dirname(folder) === folder) return false;
215 }
216 };
217​
218 /**
219 * Workspace-relative paths must stay inside the root, symlinks included. An
220 * absolute or `~/` path reads a host file in place, such as a report an agent
221 * wrote to a temp directory; it gets no root check. A network path does, since
222 * Windows signs in to its host with the user's NTLM credentials.
223 */
224 const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
225 input: ProjectReadFileInput,
226 ) {
227 const requestedPath = input.relativePath.trim();
228 const hostPath = requestedPath.startsWith("~/")
229 ? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory)
230 : requestedPath;
231 if (
232 isNetworkPath(hostPath) &&
233 !KnownWorkspaces.isWithinRoot(path, path.resolve(hostPath), path.resolve(input.cwd))
234 ) {
235 return yield* new WorkspacePaths.WorkspacePathOutsideRootError({
236 workspaceRoot: input.cwd,
237 relativePath: input.relativePath,
238 });
239 }
240 if (path.isAbsolute(hostPath)) {
241 // Native realpath hands Windows a `\\?\` path as written, `..` included,
242 // so a network path must be the resolved one the check above approved.
243 // Others keep POSIX `link/..` semantics, which resolving first would change.
244 const absolutePath = isNetworkPath(hostPath) ? path.resolve(hostPath) : hostPath;
245 const realTargetPath = yield* Effect.tryPromise({
246 try: () => NodeFSP.realpath(absolutePath),
247 catch: (cause) =>
248 new WorkspaceFileSystemOperationError({
249 workspaceRoot: input.cwd,
250 relativePath: input.relativePath,
251 resolvedPath: absolutePath,
252 operationPath: absolutePath,
253 operation: "realpath-target",
254 cause,
255 }),
256 }).pipe(
257 Effect.catchIf(
258 (error) =>
259 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
260 () => Effect.succeed(null),
261 ),
262 );
263 return { relativePath: requestedPath, realTargetPath };
264 }
265​
266 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
267 workspaceRoot: input.cwd,
268 relativePath: input.relativePath,
269 });
270​
271 const realWorkspaceRoot = yield* Effect.tryPromise({
272 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
273 catch: (cause) =>
274 new WorkspaceFileSystemOperationError({
275 workspaceRoot: input.cwd,
276 relativePath: input.relativePath,
277 resolvedPath: target.absolutePath,
278 operationPath: input.cwd,
279 operation: "realpath-workspace-root",
280 cause,
281 }),
282 });
283 const resolved = yield* Effect.tryPromise({
284 try: async () => {
285 let candidate = target.absolutePath;
286 for (;;) {
287 try {
288 return {
289 realTargetPath: path.join(
290 await NodeFSP.realpath(candidate),
291 path.relative(candidate, target.absolutePath),
292 ),
293 exists: candidate === target.absolutePath,
294 };
295 } catch (error) {
296 if (!input.allowMissing || (error as NodeJS.ErrnoException).code !== "ENOENT") {
297 throw error;
298 }
299 // Like writes, missing reads must check the nearest existing ancestor.
300 // An existing entry that cannot resolve is a dangling link, not absence.
301 const exists = await NodeFSP.lstat(candidate).then(
302 () => true,
303 (cause: NodeJS.ErrnoException) => {
304 if (cause.code !== "ENOENT") throw cause;
305 return false;
306 },
307 );
308 if (exists || path.dirname(candidate) === candidate) throw error;
309 candidate = path.dirname(candidate);
310 }
311 }
312 },
313 catch: (cause) =>
314 new WorkspaceFileSystemOperationError({
315 workspaceRoot: input.cwd,
316 relativePath: input.relativePath,
317 resolvedPath: target.absolutePath,
318 operationPath: target.absolutePath,
319 operation: "realpath-target",
320 cause,
321 }),
322 });
323 if (!isInsideRealRoot(realWorkspaceRoot, resolved.realTargetPath)) {
324 return yield* new WorkspaceFilePathEscapeError({
325 workspaceRoot: input.cwd,
326 relativePath: input.relativePath,
327 resolvedWorkspaceRoot: realWorkspaceRoot,
328 resolvedPath: resolved.realTargetPath,
329 });
330 }
331 return {
332 relativePath: target.relativePath,
333 realTargetPath: resolved.exists ? resolved.realTargetPath : null,
334 };
335 });
336​
337 const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
338 "WorkspaceFileSystem.readFile",
339 )(function* (input) {
340 const target = yield* resolveReadTarget(input);
341 const absentResult = {
342 relativePath: target.relativePath,
343 contents: "",
344 byteLength: 0,
345 truncated: false,
346 exists: false,
347 };
348 const realTargetPath = target.realTargetPath;
349 if (realTargetPath === null) return absentResult;
350​
351 return yield* Effect.acquireUseRelease(
352 Effect.tryPromise({
353 // Non-blocking opens prevent FIFO hangs before stat rejects them; Windows lacks the flag.
354 try: () =>
355 NodeFSP.open(
356 realTargetPath,
357 NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
358 ),
359 catch: (cause) =>
360 new WorkspaceFileSystemOperationError({
361 workspaceRoot: input.cwd,
362 relativePath: input.relativePath,
363 resolvedPath: realTargetPath,
364 operationPath: realTargetPath,
365 operation: "open",
366 cause,
367 }),
368 }).pipe(
369 Effect.catchIf(
370 (error) =>
371 input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT",
372 () => Effect.succeed(null),
373 ),
374 ),
375 (handle) =>
376 Effect.gen(function* () {
377 if (handle === null) return absentResult;
378 const stat = yield* Effect.tryPromise({
379 try: () => handle.stat(),
380 catch: (cause) =>
381 new WorkspaceFileSystemOperationError({
382 workspaceRoot: input.cwd,
383 relativePath: input.relativePath,
384 resolvedPath: realTargetPath,
385 operationPath: realTargetPath,
386 operation: "stat",
387 cause,
388 }),
389 });
390 if (!stat.isFile()) {
391 return yield* new WorkspacePathNotFileError({
392 workspaceRoot: input.cwd,
393 relativePath: input.relativePath,
394 resolvedPath: realTargetPath,
395 });
396 }
397​
398 const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
399 const buffer = Buffer.alloc(bytesToRead);
400 const { bytesRead } = yield* Effect.tryPromise({
401 try: () => handle.read(buffer, 0, bytesToRead, 0),
402 catch: (cause) =>
403 new WorkspaceFileSystemOperationError({
404 workspaceRoot: input.cwd,
405 relativePath: input.relativePath,
406 resolvedPath: realTargetPath,
407 operationPath: realTargetPath,
408 operation: "read",
409 cause,
410 }),
411 });
412 const fileBytes = buffer.subarray(0, bytesRead);
413 if (fileBytes.includes(0)) {
414 return yield* new WorkspaceBinaryFileError({
415 workspaceRoot: input.cwd,
416 relativePath: input.relativePath,
417 resolvedPath: realTargetPath,
418 });
419 }
420​
421 return {
422 relativePath: target.relativePath,
423 contents: new TextDecoder("utf-8").decode(fileBytes),
424 byteLength: stat.size,
425 truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
426 };
427 }),
428 (handle) =>
429 handle === null
430 ? Effect.void
431 : Effect.tryPromise({
432 try: () => handle.close(),
433 catch: (cause) =>
434 new WorkspaceFileSystemOperationError({
435 workspaceRoot: input.cwd,
436 relativePath: input.relativePath,
437 resolvedPath: realTargetPath,
438 operationPath: realTargetPath,
439 operation: "close",
440 cause,
441 }),
442 }),
443 );
444 });
445​
446 // Resolve existing ancestors and reject dangling links so creation cannot follow symlinks outside root.
447 const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
448 input: ProjectWriteFileInput,
449 ) {
450 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
451 workspaceRoot: input.cwd,
452 relativePath: input.relativePath,
453 });
454 const realWorkspaceRoot = yield* Effect.tryPromise({
455 // Resolve `..` in cwd the way the relative path was resolved, before following links.
456 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
457 catch: (cause) =>
458 new WorkspaceFileSystemOperationError({
459 workspaceRoot: input.cwd,
460 relativePath: input.relativePath,
461 resolvedPath: target.absolutePath,
462 operationPath: input.cwd,
463 operation: "realpath-workspace-root",
464 cause,
465 }),
466 });
467​
468 // Split the host path, not the display relativePath: on POSIX `\` is a file name character.
469 const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
470 const realTargetPath = yield* Effect.tryPromise({
471 try: async () => {
472 for (let depth = segments.length; depth > 0; depth--) {
473 const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
474 try {
475 return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
476 } catch (error) {
477 // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
478 const exists = await NodeFSP.lstat(candidate).then(
479 () => true,
480 () => false,
481 );
482 if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
483 }
484 }
485 return path.join(realWorkspaceRoot, ...segments);
486 },
487 catch: (cause) =>
488 new WorkspaceFileSystemOperationError({
489 workspaceRoot: input.cwd,
490 relativePath: input.relativePath,
491 resolvedPath: target.absolutePath,
492 operationPath: target.absolutePath,
493 operation: "realpath-target",
494 cause,
495 }),
496 });
497 // The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
498 const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
499 const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
500 Effect.tryPromise({
501 try: () => isInGitFolder(checkedPath),
502 catch: (cause) =>
503 new WorkspaceFileSystemOperationError({
504 workspaceRoot: input.cwd,
505 relativePath: input.relativePath,
506 resolvedPath: realTargetPath,
507 operationPath: checkedPath,
508 operation: "stat",
509 cause,
510 }),
511 }),
512 );
513 if (
514 !isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
515 (yield* inGitFolder(realTargetPath)) ||
516 (yield* inGitFolder(namedTargetPath))
517 ) {
518 return yield* new WorkspaceFilePathEscapeError({
519 workspaceRoot: input.cwd,
520 relativePath: input.relativePath,
521 resolvedWorkspaceRoot: realWorkspaceRoot,
522 resolvedPath: realTargetPath,
523 });
524 }
525 return { relativePath: target.relativePath, realTargetPath };
526 });
527​
528 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
529 "WorkspaceFileSystem.writeFile",
530 )(function* (input) {
531 yield* knownWorkspaces.assertContains(input.cwd);
532 const target = yield* resolveWriteTarget(input);
533 const realTargetPath = target.realTargetPath;
534​
535 yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
536 Effect.mapError(
537 (cause) =>
538 new WorkspaceFileSystemOperationError({
539 workspaceRoot: input.cwd,
540 relativePath: input.relativePath,
541 resolvedPath: realTargetPath,
542 operationPath: path.dirname(realTargetPath),
543 operation: "make-directory",
544 cause,
545 }),
546 ),
547 );
548 yield* Effect.tryPromise({
549 // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
550 try: () =>
551 NodeFSP.writeFile(realTargetPath, input.contents, {
552 flag:
553 NodeFS.constants.O_WRONLY |
554 NodeFS.constants.O_CREAT |
555 NodeFS.constants.O_TRUNC |
556 (NodeFS.constants.O_NOFOLLOW ?? 0),
557 }),
558 catch: (cause) =>
559 new WorkspaceFileSystemOperationError({
560 workspaceRoot: input.cwd,
561 relativePath: input.relativePath,
562 resolvedPath: realTargetPath,
563 operationPath: realTargetPath,
564 operation: "write-file",
565 cause,
566 }),
567 });
568 yield* workspaceEntries.refresh(input.cwd);
569 return { relativePath: target.relativePath };
570 });
571​
572 return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
573});
574​
575export const layer = Layer.effect(WorkspaceFileSystem, make);