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 const { bytesRead } = yield* Effect.tryPromise({
409 try: () => handle.read(buffer, 0, bytesToRead, 0),
410 catch: (cause) =>
411 new WorkspaceFileSystemOperationError({
412 workspaceRoot: input.cwd,
413 relativePath: input.relativePath,
414 resolvedPath: realTargetPath,
415 operationPath: realTargetPath,
416 operation: "read",
417 cause,
418 }),
419 });
420 const fileBytes = buffer.subarray(0, bytesRead);
421 if (fileBytes.includes(0)) {
422 return yield* new WorkspaceBinaryFileError({
423 workspaceRoot: input.cwd,
424 relativePath: input.relativePath,
425 resolvedPath: realTargetPath,
426 });
427 }
428
429 const truncated = stat.size > PROJECT_READ_FILE_MAX_BYTES;
430 return {
431 relativePath: target.relativePath,
432 // Streaming decode drops a character the byte limit split, instead of ending in U+FFFD.
433 contents: new TextDecoder("utf-8").decode(fileBytes, { stream: truncated }),
434 byteLength: stat.size,
435 truncated,
436 };
437 }),
438 (handle) =>
439 handle === null
440 ? Effect.void
441 : Effect.tryPromise({
442 try: () => handle.close(),
443 catch: (cause) =>
444 new WorkspaceFileSystemOperationError({
445 workspaceRoot: input.cwd,
446 relativePath: input.relativePath,
447 resolvedPath: realTargetPath,
448 operationPath: realTargetPath,
449 operation: "close",
450 cause,
451 }),
452 }),
453 );
454 });
455
456 // Resolve existing ancestors and reject dangling links so creation cannot follow symlinks outside root.
457 const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* (
458 input: ProjectWriteFileInput,
459 ) {
460 const target = yield* workspacePaths.resolveRelativePathWithinRoot({
461 workspaceRoot: input.cwd,
462 relativePath: input.relativePath,
463 });
464 const realWorkspaceRoot = yield* Effect.tryPromise({
465 // Resolve `..` in cwd the way the relative path was resolved, before following links.
466 try: () => NodeFSP.realpath(path.resolve(input.cwd)),
467 catch: (cause) =>
468 new WorkspaceFileSystemOperationError({
469 workspaceRoot: input.cwd,
470 relativePath: input.relativePath,
471 resolvedPath: target.absolutePath,
472 operationPath: input.cwd,
473 operation: "realpath-workspace-root",
474 cause,
475 }),
476 });
477
478 // Split the host path, not the display relativePath: on POSIX `\` is a file name character.
479 const segments = path.relative(input.cwd, target.absolutePath).split(path.sep);
480 const realTargetPath = yield* Effect.tryPromise({
481 try: async () => {
482 for (let depth = segments.length; depth > 0; depth--) {
483 const candidate = path.join(realWorkspaceRoot, ...segments.slice(0, depth));
484 try {
485 return path.join(await NodeFSP.realpath(candidate), ...segments.slice(depth));
486 } catch (error) {
487 // Only a missing entry is skipped; one that exists but cannot resolve is a dangling link.
488 const exists = await NodeFSP.lstat(candidate).then(
489 () => true,
490 () => false,
491 );
492 if ((error as NodeJS.ErrnoException).code !== "ENOENT" || exists) throw error;
493 }
494 }
495 return path.join(realWorkspaceRoot, ...segments);
496 },
497 catch: (cause) =>
498 new WorkspaceFileSystemOperationError({
499 workspaceRoot: input.cwd,
500 relativePath: input.relativePath,
501 resolvedPath: target.absolutePath,
502 operationPath: target.absolutePath,
503 operation: "realpath-target",
504 cause,
505 }),
506 });
507 // The path as named is checked too: a `.git/config` symlink resolves away the `.git`.
508 const namedTargetPath = path.join(realWorkspaceRoot, ...segments);
509 const inGitFolder = Effect.fn("WorkspaceFileSystem.inGitFolder")((checkedPath: string) =>
510 Effect.tryPromise({
511 try: () => isInGitFolder(checkedPath),
512 catch: (cause) =>
513 new WorkspaceFileSystemOperationError({
514 workspaceRoot: input.cwd,
515 relativePath: input.relativePath,
516 resolvedPath: realTargetPath,
517 operationPath: checkedPath,
518 operation: "stat",
519 cause,
520 }),
521 }),
522 );
523 if (
524 !isInsideRealRoot(realWorkspaceRoot, realTargetPath) ||
525 (yield* inGitFolder(realTargetPath)) ||
526 (yield* inGitFolder(namedTargetPath))
527 ) {
528 return yield* new WorkspaceFilePathEscapeError({
529 workspaceRoot: input.cwd,
530 relativePath: input.relativePath,
531 resolvedWorkspaceRoot: realWorkspaceRoot,
532 resolvedPath: realTargetPath,
533 });
534 }
535 return { relativePath: target.relativePath, realTargetPath };
536 });
537
538 const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
539 "WorkspaceFileSystem.writeFile",
540 )(function* (input) {
541 yield* knownWorkspaces.assertContains(input.cwd);
542 const target = yield* resolveWriteTarget(input);
543 const realTargetPath = target.realTargetPath;
544 const replacesFile = yield* fileSystem
545 .exists(realTargetPath)
546 .pipe(Effect.orElseSucceed(() => false));
547
548 yield* fileSystem.makeDirectory(path.dirname(realTargetPath), { recursive: true }).pipe(
549 Effect.mapError(
550 (cause) =>
551 new WorkspaceFileSystemOperationError({
552 workspaceRoot: input.cwd,
553 relativePath: input.relativePath,
554 resolvedPath: realTargetPath,
555 operationPath: path.dirname(realTargetPath),
556 operation: "make-directory",
557 cause,
558 }),
559 ),
560 );
561 yield* Effect.tryPromise({
562 // A symlink swapped in after the check is not followed. Windows lacks O_NOFOLLOW.
563 try: () =>
564 NodeFSP.writeFile(realTargetPath, input.contents, {
565 flag:
566 NodeFS.constants.O_WRONLY |
567 NodeFS.constants.O_CREAT |
568 NodeFS.constants.O_TRUNC |
569 (NodeFS.constants.O_NOFOLLOW ?? 0),
570 }),
571 catch: (cause) =>
572 new WorkspaceFileSystemOperationError({
573 workspaceRoot: input.cwd,
574 relativePath: input.relativePath,
575 resolvedPath: realTargetPath,
576 operationPath: realTargetPath,
577 operation: "write-file",
578 cause,
579 }),
580 });
581 // Editor autosave overwrites existing files, which leaves the indexed paths unchanged, and
582 // fff's watcher applies the new contents on its own. A forced rescan re-walks the whole
583 // workspace, and the save would wait for it.
584 if (!replacesFile) {
585 yield* workspaceEntries.refresh(input.cwd);
586 }
587 return { relativePath: target.relativePath };
588 });
589
590 return WorkspaceFileSystem.of({ getMetadata, readFile, writeFile });
591});
592
593export const layer = Layer.effect(WorkspaceFileSystem, make);