Skip to content
TypeScript

Merge commit from fork

Julius Marmingea12d6ed9428d
diff --git a/apps/mobile/src/lib/markdownMedia.test.ts b/apps/mobile/src/lib/markdownMedia.test.ts
index 33fec670e41..ef7cca31114 100644
--- a/apps/mobile/src/lib/markdownMedia.test.ts
+++ b/apps/mobile/src/lib/markdownMedia.test.ts
@@ -38,10 +38,10 @@ describe("resolveMarkdownMediaPreview", () => {
["/tmp/frame%23one.png:12", "/tmp/frame#one.png"],
["/tmp/frame%3Fone.png:12:3", "/tmp/frame?one.png"],
["/tmp/frame%2523one.png:12", "/tmp/frame%23one.png"],
- ["file://server/share/frame.png", "\\\\server\\share\\frame.png"],
- ["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png"],
- ])("keeps encoded filename and UNC semantics for %s", (href, path) => {
- expect(resolveMarkdownMediaPreview(href, input)).toMatchObject({
+ ["file://server/share/frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"],
+ ["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"],
+ ])("keeps encoded filename and UNC semantics for %s", (href, path, workspaceRoot = "/repo") => {
+ expect(resolveMarkdownMediaPreview(href, { ...input, workspaceRoot })).toMatchObject({
kind: "image",
source: {
resource: { path },
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index a5d0a2f6616..05e6e9c3b1b 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -17,6 +17,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as Path from "effect/Path";
+import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientResponse, HttpServerResponse } from "effect/http";
import { vi } from "vite-plus/test";
@@ -359,6 +360,47 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);
+ // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the
+ // Windows user's NTLM credentials to attacker.test.
+ it.effect("never resolves a network media path outside the thread's project", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const resolved: Array<string> = [];
+ const recordingFileSystem = FileSystem.FileSystem.of({
+ ...fs,
+ realPath: (requestedPath) => {
+ resolved.push(requestedPath);
+ return Effect.fail(
+ PlatformError.systemError({
+ _tag: "NotFound",
+ module: "FileSystem",
+ method: "realPath",
+ pathOrDescriptor: requestedPath,
+ }),
+ );
+ },
+ });
+ const share = "//nas.test/share/project";
+ for (const resource of [
+ {
+ _tag: "media-file",
+ threadId: ThreadId.make("thread-1"),
+ path: "//attacker.test/s/a.png",
+ },
+ { _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" },
+ { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` },
+ ] as const) {
+ const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe(
+ Effect.provideService(FileSystem.FileSystem, recordingFileSystem),
+ Effect.flip,
+ );
+ expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
+ }
+ expect(resolved).toEqual([path.resolve(`${share}/a.png`)]);
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect.skipIf(!symlinksSupported)(
"rejects non-previewable files, disguised targets, and directories",
() =>
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index c25dce2494f..853c07435b3 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -36,6 +36,7 @@ import {
isProjectFaviconPath,
PROJECT_FAVICON_FALLBACK_MARKER,
} from "@t3tools/shared/projectFavicon";
+import { isNetworkPath } from "@t3tools/shared/path";
import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
@@ -60,6 +61,7 @@ import * as ServerConfig from "../config.ts";
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
+import { isWithinRoot } from "../workspace/KnownWorkspaces.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
import { extractIcnsPng } from "./icns.ts";
@@ -349,11 +351,27 @@ const readImageDimensionsFromHeader = (filePath: string) =>
const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
function* (input: {
readonly requestedPath: string;
+ readonly workspaceRoot: string | undefined;
readonly resource: AssetResource;
readonly expiresAt: number;
}) {
const path = yield* Path.Path;
- const canonicalFile = yield* resolveCanonicalFile(input.requestedPath).pipe(
+ // Resolving a network path makes Windows sign in to its host with the
+ // user's NTLM credentials, so only the thread's own project may be on a share.
+ // Windows reads a `\\?\` path as written, `..` included, so the lookup gets
+ // the resolved path this check approved.
+ const requestedPath = path.resolve(input.requestedPath);
+ if (
+ isNetworkPath(input.requestedPath) &&
+ (input.workspaceRoot === undefined ||
+ !isWithinRoot(path, requestedPath, path.resolve(input.workspaceRoot)))
+ ) {
+ return yield* new AssetWorkspaceAssetNotFoundError({
+ resource: input.resource,
+ checkedPath: input.requestedPath,
+ });
+ }
+ const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
Effect.mapError(
(cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
),
@@ -524,6 +542,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
}
const finalized = yield* finalizeAbsoluteMediaFileAsset({
requestedPath,
+ workspaceRoot: input.workspaceRoot,
resource: input.resource,
expiresAt,
});
@@ -566,6 +585,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
if (path.isAbsolute(hostPath)) {
const finalized = yield* finalizeAbsoluteMediaFileAsset({
requestedPath: hostPath,
+ workspaceRoot: draftWorkspaceRoot,
resource: input.resource,
expiresAt,
});
diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts
index 35959d91d9b..992e219db91 100644
--- a/apps/server/src/storageCleanup.test.ts
+++ b/apps/server/src/storageCleanup.test.ts
@@ -1299,6 +1299,36 @@ describe("storage cleanup reports and local file policies", () => {
}),
),
);
+ // An agent can write this manifest. Statting its store sent the Windows
+ // user's NTLM credentials to attacker.test during a background sweep.
+ it.live.each([
+ { storeDir: "\\\\attacker.test\\s" },
+ { storeDir: "/local/store", virtualStoreDir: "//attacker.test/s" },
+ ])("never stats a network pnpm store %o", (manifest) =>
+ runCleanupTest(
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const statted: Array<string> = [];
+ const { service, worktree, setPolicy } = yield* cleanupFixture().pipe(
+ Effect.provideService(FileSystem.FileSystem, {
+ ...fs,
+ stat: (target) => {
+ statted.push(target);
+ return fs.stat(target);
+ },
+ }),
+ );
+ setPolicy("tracked-changes");
+ yield* fs.makeDirectory(`${worktree}/node_modules`);
+ yield* fs.writeFileString(
+ `${worktree}/node_modules/.modules.yaml`,
+ JSON.stringify(manifest),
+ );
+ expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" });
+ expect(statted.filter((target) => target.includes("attacker.test"))).toEqual([]);
+ }),
+ ),
+ );
it.live("still removes a worktree when measuring its size fails", () =>
runCleanupTest(
Effect.gen(function* () {
diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts
index 1c4eb714fac..a196321e380 100644
--- a/apps/server/src/storageCleanup.ts
+++ b/apps/server/src/storageCleanup.ts
@@ -50,6 +50,7 @@ import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts";
import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import { isNetworkPath } from "@t3tools/shared/path";
const decodeCleanupThread = Schema.decodeUnknownEffect(
Schema.fromJsonString(OrchestrationV2AppThreadJson),
@@ -265,6 +266,11 @@ const make = Effect.gen(function* () {
const nodeModules = path.join(root, "node_modules");
const text = yield* fs.readFileString(path.join(nodeModules, ".modules.yaml"));
const manifest = yield* decodePnpmModulesManifest(yield* Effect.try(() => parseYaml(text)));
+ // An agent can write this manifest, and statting a network path makes
+ // Windows sign in to its host with the user's NTLM credentials.
+ if (isNetworkPath(manifest.storeDir) || isNetworkPath(manifest.virtualStoreDir ?? "")) {
+ return null;
+ }
const virtualStore = path.resolve(nodeModules, manifest.virtualStoreDir ?? ".pnpm");
const [store, virtual] = yield* Effect.all([
fs.stat(manifest.storeDir),
diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
index 6dc5d4c0857..9eb2ba75804 100644
--- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts
+++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
@@ -1,6 +1,8 @@
-// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO.
+// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO, and reads spy on native realpath.
import * as NodeChildProcess from "node:child_process";
+import * as NodeFSP from "node:fs/promises";
+import * as NodePath from "@effect/platform-node/NodePath";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
@@ -17,6 +19,12 @@ import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
+import { vi } from "vite-plus/test";
+
+vi.mock("node:fs/promises", async (importOriginal) => {
+ const actual = await importOriginal<typeof NodeFSP>();
+ return { ...actual, realpath: vi.fn(actual.realpath) };
+});
// Temp folders count as known workspaces unless named as unknown.
const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-";
@@ -123,6 +131,35 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
]);
}),
);
+
+ // A file chip for `file://attacker.test/s/a.ts` in an agent's message sent
+ // the Windows user's NTLM credentials to attacker.test as it rendered.
+ it.effect("never stats a network path", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const statted: Array<string> = [];
+ const service = yield* WorkspaceFileSystem.make.pipe(
+ Effect.provideService(
+ FileSystem.FileSystem,
+ FileSystem.FileSystem.of({
+ ...fs,
+ stat: (requestedPath) => {
+ statted.push(requestedPath);
+ return fs.stat(requestedPath);
+ },
+ }),
+ ),
+ Effect.provide(layerKnownWorkspacesTest),
+ );
+ const paths = [
+ "\\\\attacker.test\\s\\a.ts",
+ "//attacker.test/s/a.ts",
+ "/\\attacker.test\\s",
+ ];
+ expect((yield* service.getMetadata({ paths })).entries).toEqual([null, null, null]);
+ expect(statted).toEqual([]);
+ }),
+ );
});
describe("readFile", () => {
@@ -199,6 +236,68 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
}),
);
+ it.effect("refuses a network path outside the workspace", () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+
+ const error = yield* workspaceFileSystem
+ .readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" })
+ .pipe(Effect.flip);
+
+ expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
+ }),
+ );
+
+ // This resolves inside the project, but Windows reads `\\?\` paths as
+ // written, so realpath on the raw string signed in to attacker.test.
+ it.effect("reads the network path it checked", () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe(
+ Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)),
+ );
+ // Rejects without touching the filesystem, so a Windows runner never looks the share up.
+ const realpath = vi
+ .mocked(NodeFSP.realpath)
+ .mockClear()
+ .mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
+
+ yield* workspaceFileSystem
+ .readFile({
+ cwd: "\\\\?\\UNC\\nas.test\\share\\project",
+ relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md",
+ })
+ .pipe(Effect.exit);
+
+ expect(realpath.mock.calls.map(([target]) => target)).toEqual([
+ "\\\\?\\UNC\\nas.test\\share\\project\\a.md",
+ ]);
+ }),
+ );
+
+ // Resolving `..` before realpath would read beside the link instead of its target.
+ // Windows collapses `..` before the filesystem sees a path, so it has no such reads.
+ it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")(
+ "reads `..` after a link from the link's target",
+ () =>
+ Effect.gen(function* () {
+ const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* makeTempDir;
+ yield* writeTextFile(root, "target/parent.md", "beside the target\n");
+ yield* writeTextFile(root, "parent.md", "beside the link\n");
+ yield* fs.makeDirectory(path.join(root, "target", "child"));
+ yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link"));
+
+ const result = yield* workspaceFileSystem.readFile({
+ cwd: root,
+ relativePath: `${root}/link/../parent.md`,
+ });
+
+ expect(result.contents).toBe("beside the target\n");
+ }),
+ );
+
it.effect.skipIf(!symlinksSupported)(
"rejects symlinks that resolve outside the workspace root",
() =>
diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts
index ec18f675aae..4e7c8140425 100644
--- a/apps/server/src/workspace/WorkspaceFileSystem.ts
+++ b/apps/server/src/workspace/WorkspaceFileSystem.ts
@@ -13,6 +13,7 @@ import type {
} from "@t3tools/contracts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { isNetworkPath } from "@t3tools/shared/path";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -142,7 +143,9 @@ export const make = Effect.gen(function* () {
const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
- if (!path.isAbsolute(expandedPath)) return null;
+ // Chips ask as soon as an agent's message renders, and touching a network
+ // path makes Windows sign in to its host with the user's NTLM credentials.
+ if (!path.isAbsolute(expandedPath) || isNetworkPath(expandedPath)) return null;
const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
if (stat._tag === "None") return null;
if (stat.value.type === "Directory") return { kind: "directory" } as const;
@@ -222,7 +225,8 @@ export const make = Effect.gen(function* () {
/**
* Workspace-relative paths must stay inside the root, symlinks included. An
* absolute or `~/` path reads a host file in place, such as a report an agent
- * wrote to a temp directory; it gets no root check.
+ * wrote to a temp directory; it gets no root check. A network path does, since
+ * Windows signs in to its host with the user's NTLM credentials.
*/
const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
input: ProjectReadFileInput,
@@ -231,15 +235,28 @@ export const make = Effect.gen(function* () {
const hostPath = requestedPath.startsWith("~/")
? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory)
: requestedPath;
+ if (
+ isNetworkPath(hostPath) &&
+ !KnownWorkspaces.isWithinRoot(path, path.resolve(hostPath), path.resolve(input.cwd))
+ ) {
+ return yield* new WorkspacePaths.WorkspacePathOutsideRootError({
+ workspaceRoot: input.cwd,
+ relativePath: input.relativePath,
+ });
+ }
if (path.isAbsolute(hostPath)) {
+ // Native realpath hands Windows a `\\?\` path as written, `..` included,
+ // so a network path must be the resolved one the check above approved.
+ // Others keep POSIX `link/..` semantics, which resolving first would change.
+ const absolutePath = isNetworkPath(hostPath) ? path.resolve(hostPath) : hostPath;
const realTargetPath = yield* Effect.tryPromise({
- try: () => NodeFSP.realpath(hostPath),
+ try: () => NodeFSP.realpath(absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
- resolvedPath: hostPath,
- operationPath: hostPath,
+ resolvedPath: absolutePath,
+ operationPath: absolutePath,
operation: "realpath-target",
cause,
}),
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 763365ceedd..1ba4ff99ff6 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -246,6 +246,7 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as SessionStore from "./auth/SessionStore.ts";
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
+import { isNetworkPath } from "@t3tools/shared/path";
import * as RelayClient from "@t3tools/shared/relayClient";
import { isTelemetryIdHash } from "@t3tools/shared/telemetryId";
import {
@@ -2721,7 +2722,10 @@ export const layerWsRpc = (
input.resource._tag === "native-app-icon" ||
input.resource._tag === "tool-output-image" ||
input.resource._tag === "github-media" ||
- (input.resource._tag === "media-file" && path.isAbsolute(input.resource.path))
+ // A network path is served only from the thread's project, looked up below.
+ (input.resource._tag === "media-file" &&
+ path.isAbsolute(input.resource.path) &&
+ !isNetworkPath(input.resource.path))
) {
return yield* issueAssetUrl({ resource: input.resource });
}
diff --git a/apps/web/src/hooks/useFileMetadata.ts b/apps/web/src/hooks/useFileMetadata.ts
index bc5940410ce..497cc67d989 100644
--- a/apps/web/src/hooks/useFileMetadata.ts
+++ b/apps/web/src/hooks/useFileMetadata.ts
@@ -1,6 +1,10 @@
import { AuthFilesystemReadScope, type EnvironmentId } from "@t3tools/contracts";
import { resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
-import { normalizeProjectPathForComparison, isAbsolutePath } from "@t3tools/shared/path";
+import {
+ isAbsolutePath,
+ isNetworkPath,
+ normalizeProjectPathForComparison,
+} from "@t3tools/shared/path";
import { useContext } from "react";
import { useEnvironmentScope } from "../state/session";
@@ -21,7 +25,9 @@ export function useFileMetadata(
);
const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/");
return useEnvironmentQuery(
- environmentId && canRead && absolute && targetPath.length <= 512
+ // Servers stat what they are asked about, and a network path leaks the
+ // Windows user's NTLM credentials to its host before any chip is clicked.
+ environmentId && canRead && absolute && !isNetworkPath(targetPath) && targetPath.length <= 512
? projectEnvironment.fileMetadata({
environmentId,
input: {
diff --git a/packages/client-runtime/src/markdownImages.test.ts b/packages/client-runtime/src/markdownImages.test.ts
index 039eb75345c..b34c8bce39d 100644
--- a/packages/client-runtime/src/markdownImages.test.ts
+++ b/packages/client-runtime/src/markdownImages.test.ts
@@ -11,7 +11,7 @@ describe("classifyMarkdownImageSource", () => {
"C:\\Users\\dara\\project\\images\\result.png",
],
["file:///workspace/project/image%20one.png", null, "/workspace/project/image one.png"],
- ["file://server/share/image.png", null, "\\\\server\\share\\image.png"],
+ ["file://server/share/image.png", "\\\\server\\share", "\\\\server\\share\\image.png"],
])("maps %s to a workspace file", (source, workspaceRoot, path) => {
expect(classifyMarkdownImageSource(source, workspaceRoot)).toEqual({
_tag: "WorkspaceFile",
@@ -25,4 +25,17 @@ describe("classifyMarkdownImageSource", () => {
expect(classifyMarkdownImageSource(source)).toEqual({ _tag: "Blocked" });
},
);
+
+ // Loading these makes Windows send the user's NTLM credentials to the named host.
+ it.each([
+ "file://attacker.test/share/cat.jpg",
+ "\\\\attacker.test\\share\\cat.jpg",
+ "/\\attacker.test\\share\\cat.jpg",
+ "file:/%5Cattacker.test%5Cshare%5Ccat.jpg",
+ "\\\\server\\other\\cat.jpg",
+ ])("blocks network path %s outside the project", (source) => {
+ expect(classifyMarkdownImageSource(source, "\\\\server\\share\\project")).toEqual({
+ _tag: "Blocked",
+ });
+ });
});
diff --git a/packages/client-runtime/src/markdownImages.ts b/packages/client-runtime/src/markdownImages.ts
index 55e597f4d3c..924220ec27c 100644
--- a/packages/client-runtime/src/markdownImages.ts
+++ b/packages/client-runtime/src/markdownImages.ts
@@ -1,4 +1,9 @@
-import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "@t3tools/shared/path";
+import {
+ isNetworkPath,
+ isWindowsAbsolutePath,
+ stripSlashPrefixedWindowsDrive,
+ workspaceRelativeFilePath,
+} from "@t3tools/shared/path";
import {
normalizeMarkdownLinkDestination,
@@ -26,6 +31,16 @@ function joinWorkspacePath(workspaceRoot: string, relativePath: string): string
return `${root}${separator}${path}`;
}
+/** Rendering is not a click, so a network path loads only from the project's own share. */
+function hostFileSource(
+ path: string,
+ workspaceRoot: string | null | undefined,
+): MarkdownImageSource {
+ return isNetworkPath(path) && workspaceRelativeFilePath(path, workspaceRoot) === null
+ ? { _tag: "Blocked" }
+ : { _tag: "WorkspaceFile", path };
+}
+
/**
* Filesystem paths belong to the environment host and must never reach a
* browser or native image component without first becoming a signed asset URL.
@@ -48,10 +63,10 @@ export function classifyMarkdownImageSource(
const target = parseFileUrlHref(source);
return target === null
? { _tag: "Blocked" }
- : {
- _tag: "WorkspaceFile",
- path: stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)),
- };
+ : hostFileSource(
+ stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)),
+ workspaceRoot,
+ );
}
const path = stripSlashPrefixedWindowsDrive(
@@ -59,7 +74,7 @@ export function classifyMarkdownImageSource(
);
if (path.length === 0) return { _tag: "Blocked" };
if (path.startsWith("/") || isWindowsAbsolutePath(path)) {
- return { _tag: "WorkspaceFile", path };
+ return hostFileSource(path, workspaceRoot);
}
if (URI_SCHEME_PATTERN.test(path) || path.startsWith("~/") || path.startsWith("~\\")) {
return { _tag: "Blocked" };
diff --git a/packages/client-runtime/src/mediaSource.test.ts b/packages/client-runtime/src/mediaSource.test.ts
index 612008c5be5..1b46b463a83 100644
--- a/packages/client-runtime/src/mediaSource.test.ts
+++ b/packages/client-runtime/src/mediaSource.test.ts
@@ -35,7 +35,6 @@ describe("resolveMediaSource", () => {
it.each([
["/tmp/frame%23one.png:12", "/tmp/frame#one.png"],
["/tmp/frame%2523one.png:12", "/tmp/frame%23one.png"],
- ["file://server/share/frame.png", "\\\\server\\share\\frame.png"],
])("resolves %s through the environment", (href, path) => {
expect(resolveMediaSource(href, { threadId, workspaceRoot: "/repo" })).toEqual({
kind: "image",
diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts
index 01d9192e17e..8693a8d7af4 100644
--- a/packages/shared/src/markdownLinks.test.ts
+++ b/packages/shared/src/markdownLinks.test.ts
@@ -126,10 +126,15 @@ describe("resolveMarkdownFileLinkTarget", () => {
);
});
- it("resolves file uri authorities as windows UNC paths", () => {
- expect(resolveMarkdownFileLinkTarget("file://server/share/workspace-image.svg")).toBe(
+ it("links a network path only inside the project's share", () => {
+ const cwd = "\\\\server\\share";
+ expect(resolveMarkdownFileLinkTarget("file://server/share/workspace-image.svg", cwd)).toBe(
"\\\\server\\share\\workspace-image.svg",
);
+ // Opening these sent the Windows user's NTLM credentials to attacker.test.
+ for (const href of ["file://attacker.test/s/x.ts", "\\\\attacker.test\\s\\x.ts"]) {
+ expect(resolveMarkdownFileLinkTarget(href, cwd)).toBeNull();
+ }
});
it("keeps an encoded final space in the absolute target", () => {
diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts
index 6e985ccdb0f..a0195a84749 100644
--- a/packages/shared/src/markdownLinks.ts
+++ b/packages/shared/src/markdownLinks.ts
@@ -1,4 +1,9 @@
-import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "./path.ts";
+import {
+ isNetworkPath,
+ isWindowsAbsolutePath,
+ stripSlashPrefixedWindowsDrive,
+ workspaceRelativeFilePath,
+} from "./path.ts";
import {
type FilePathPosition,
formatFilePathPosition,
@@ -391,7 +396,13 @@ export function resolveMarkdownFileLinkTarget(
if (!target) return null;
const pathWithPosition = formatFilePathPosition(target);
- if (!isRelativeFilePath(pathWithPosition)) return pathWithPosition;
+ if (!isRelativeFilePath(pathWithPosition)) {
+ // Opening a network path makes Windows sign in to its host with the user's
+ // NTLM credentials, so only the project's own share becomes a file link.
+ return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
+ ? null
+ : pathWithPosition;
+ }
if (!baseDir) return null;
return resolvePathLinkTarget(pathWithPosition, baseDir);
}
diff --git a/packages/shared/src/path.ts b/packages/shared/src/path.ts
index ba06f352cb1..23a8cf3c6d4 100644
--- a/packages/shared/src/path.ts
+++ b/packages/shared/src/path.ts
@@ -6,6 +6,15 @@ export function isUncPath(value: string): boolean {
return value.startsWith("\\\\");
}
+/**
+ * Windows treats `/` and `\` alike, so any two leading separators name a UNC
+ * or device path. Touching one makes Windows sign in to that host with the
+ * user's NTLM credentials, so agent-authored paths must not reach one.
+ */
+export function isNetworkPath(value: string): boolean {
+ return /^[\\/]{2}/.test(value);
+}
+
export function isWindowsAbsolutePath(value: string): boolean {
return isUncPath(value) || isWindowsDrivePath(value);
}