Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off -- FileSystem.realPath uses callback fs.realpath, which folds `..` before following links; only the native promise form resolves it like the kernel.
2import * as NodeFS from "node:fs";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as PlatformError from "effect/PlatformError";
8
9const MAX_SYMLINK_HOPS = 40;
10
11const isNotFound = (error: PlatformError.PlatformError) => error.reason._tag === "NotFound";
12
13const isNotASymlink = (error: PlatformError.PlatformError) =>
14 isNotFound(error) ||
15 (error.cause instanceof Error && "code" in error.cause && error.cause.code === "EINVAL");
16
17/**
18 * Atomic writers rename onto this path so a linked file keeps its link. Fails
19 * on a cycle, an overly long chain, or an unreadable link rather than handing
20 * back a link that a rename would replace.
21 */
22export const resolveSymlinkTarget = Effect.fn("symlink.resolveSymlinkTarget")(function* (
23 filePath: string,
24) {
25 const fs = yield* FileSystem.FileSystem;
26 const path = yield* Path.Path;
27 let current = path.resolve(filePath);
28 // The terminal file needs a probe after the last permitted link is followed.
29 for (let hop = 0; hop <= MAX_SYMLINK_HOPS; hop++) {
30 const link = yield* fs.readLink(current).pipe(
31 Effect.asSome,
32 Effect.catchIf(isNotASymlink, () => Effect.succeedNone),
33 );
34 if (Option.isNone(link)) {
35 return current;
36 }
37 if (path.sep === "/") {
38 const rawTarget = path.isAbsolute(link.value)
39 ? link.value
40 : `${path.dirname(current)}/${link.value}`;
41 const traversal = /^.*\/\.\.(?=\/|$)/s.exec(rawTarget)?.[0];
42 if (traversal !== undefined) {
43 const directory = yield* Effect.tryPromise({
44 try: () => NodeFS.promises.realpath(traversal),
45 catch: (cause) =>
46 PlatformError.systemError({
47 _tag: "Unknown",
48 module: "FileSystem",
49 method: "realPath",
50 pathOrDescriptor: traversal,
51 cause,
52 }),
53 });
54 current = path.resolve(directory, `.${rawTarget.slice(traversal.length)}`);
55 continue;
56 }
57 }
58 // A relative target is relative to where the link really lives, which
59 // differs from its lexical parent when that parent is itself a symlink.
60 const linkDirectory = yield* fs
61 .realPath(path.dirname(current))
62 .pipe(Effect.catchIf(isNotFound, () => Effect.succeed(path.dirname(current))));
63 current = path.resolve(linkDirectory, link.value);
64 }
65 return yield* PlatformError.systemError({
66 _tag: "Unknown",
67 module: "FileSystem",
68 method: "readLink",
69 description: "Too many levels of symbolic links",
70 pathOrDescriptor: filePath,
71 });
72});