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