Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(desktop): validate resolved chat references within roots

cauliflower7b63a0db6662
diff --git a/apps/desktop/electron/main/chat-ref-resolve.ts b/apps/desktop/electron/main/chat-ref-resolve.ts
index 208973527..b5ff39093 100644
--- a/apps/desktop/electron/main/chat-ref-resolve.ts
+++ b/apps/desktop/electron/main/chat-ref-resolve.ts
@@ -1,4 +1,4 @@
-import { readdir, realpath, stat } from "node:fs/promises";
+import { lstat, readdir, realpath, stat } from "node:fs/promises";
import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
import type {
FsChatRefMatch,
@@ -6,7 +6,7 @@ import type {
FsChatRefProjectRoot,
FsChatRefRoot,
} from "@pi-desktop/shared";
-import { isAttachmentBlobRef, isIgnoredName } from "@pi-desktop/host-runtime";
+import { isAttachmentBlobRef, isIgnoredName, resolveRealPathWithinRoot } from "@pi-desktop/host-runtime";
import { getWorkspaceFileIndex } from "./fs-index.js";
/**
@@ -155,6 +155,14 @@ async function isRegularFile(target: string): Promise<boolean> {
}
}
+async function isSymbolicLink(target: string): Promise<boolean> {
+ try {
+ return (await lstat(target)).isSymbolicLink();
+ } catch {
+ return false;
+ }
+}
+
/** Root-relative POSIX path, or null when `absolute` is outside `rootPath`. */
function relativeInside(rootPath: string, absolute: string): string | null {
const rel = relative(rootPath, absolute);
@@ -238,30 +246,36 @@ type FuzzyCandidate = { relativePath: string; matchedBy: FsChatRefMatchKind };
* Longest tail first, so a two-segment shorthand beats a bare leaf name.
* Within one tail the shallowest file wins.
*/
-function bestFuzzyCandidate(
+function fuzzyCandidates(
files: readonly string[],
tails: readonly string[][],
-): FuzzyCandidate | null {
+): FuzzyCandidate[] {
const parsedFiles = files.map((file) => ({
file,
segments: segmentsOf(file),
}));
+ const candidates: FuzzyCandidate[] = [];
+ const seen = new Set<string>();
for (const tail of tails) {
- let best: string | null = null;
- for (const entry of parsedFiles) {
- if (!endsWithTail(entry.segments, tail)) continue;
- if (best === null || compareCandidates(entry.file, best) < 0) {
- best = entry.file;
- }
- }
- if (best !== null) {
- return {
- relativePath: best,
+ const matches = parsedFiles
+ .filter((entry) => endsWithTail(entry.segments, tail))
+ .map((entry) => entry.file)
+ .sort(compareCandidates);
+ for (const file of matches) {
+ if (seen.has(file)) continue;
+ seen.add(file);
+ candidates.push({
+ relativePath: file,
matchedBy: tail.length === 1 ? "basename" : "path-suffix",
- };
+ });
}
}
- return null;
+ return candidates;
+}
+
+async function isContainedRegularFile(root: string, relativePath: string): Promise<boolean> {
+ const realPath = await resolveRealPathWithinRoot(root, relativePath);
+ return realPath !== null && isRegularFile(realPath);
}
/** Bounded walk for trees with no git index (session scratch, attachments). */
@@ -370,7 +384,7 @@ export async function resolveChatFileRef(
if (!absolutePath.startsWith(resolvedRoot + sep) && absolutePath !== resolvedRoot) {
return null;
}
- if (!(await isRegularFile(absolutePath))) return null;
+ if (!(await isContainedRegularFile(resolvedRoot, blobHash.toLowerCase()))) return null;
return {
root: "attachments",
relativePath: blobHash.toLowerCase(),
@@ -391,6 +405,7 @@ export async function resolveChatFileRef(
for (const root of rootList) {
const absolutePath = join(root.path, ...parsed.segments);
if (await isRegularFile(absolutePath)) {
+ if (!(await isContainedRegularFile(root.path, parsed.segments.join("/")))) return null;
return {
root: root.kind,
relativePath: parsed.segments.join("/"),
@@ -399,18 +414,21 @@ export async function resolveChatFileRef(
...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
};
}
- const candidate = bestFuzzyCandidate(
+ if (await isSymbolicLink(absolutePath)) return null;
+ const candidates = fuzzyCandidates(
await listRootFiles(root.kind, root.path),
tails,
);
- if (!candidate) continue;
- return {
- root: root.kind,
- relativePath: candidate.relativePath,
- absolutePath: join(root.path, ...segmentsOf(candidate.relativePath)),
- matchedBy: candidate.matchedBy,
- ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
- };
+ for (const candidate of candidates) {
+ if (!(await isContainedRegularFile(root.path, candidate.relativePath))) continue;
+ return {
+ root: root.kind,
+ relativePath: candidate.relativePath,
+ absolutePath: join(root.path, ...segmentsOf(candidate.relativePath)),
+ matchedBy: candidate.matchedBy,
+ ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
+ };
+ }
}
return null;
diff --git a/apps/desktop/test/chat-ref-resolve.test.mjs b/apps/desktop/test/chat-ref-resolve.test.mjs
index 2a99363cc..c1dbec649 100644
--- a/apps/desktop/test/chat-ref-resolve.test.mjs
+++ b/apps/desktop/test/chat-ref-resolve.test.mjs
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, renameSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { register } from "node:module";
@@ -116,6 +116,7 @@ test("an absolute realpath alias resolves under the same registered root", async
const missing = join(workspace, "my project", "missing.md");
assert.equal(await isChatRefOutsideRoots(missing, { project }), false);
assert.equal(await resolveChatFileRef(missing, { project }), null);
+ assert.equal((await resolveChatFileRef("my project/page.md", { project }))?.relativePath, "my project/page.md");
});
test("an in-root symlink cannot resolve a file outside the registered root", async () => {
@@ -128,6 +129,41 @@ test("an in-root symlink cannot resolve a file outside the registered root", asy
assert.equal(await isChatRefOutsideRoots(join(workspace, "linked", "missing.md"), roots({ workspace })), true);
});
+test("an exact relative symlink escape does not fall back to a same-name file", async () => {
+ const workspace = tempTree("relative-escape", ["other/linked/page.md"]);
+ const outside = tempTree("relative-outside", ["page.md"]);
+ symlinkSync(outside, join(workspace, "linked"), process.platform === "win32" ? "junction" : "dir");
+ assert.equal(await resolve("linked/page.md", { workspace }), null);
+
+ const scratch = tempTree("scratch-escape", []);
+ symlinkSync(outside, join(scratch, "linked"), process.platform === "win32" ? "junction" : "dir");
+ assert.equal(await resolve("linked/page.md", { scratch }), null);
+});
+
+test("an exact relative link within its root remains resolvable", async () => {
+ const workspace = tempTree("relative-inside", ["docs/page.md"]);
+ symlinkSync(join(workspace, "docs"), join(workspace, "linked"), process.platform === "win32" ? "junction" : "dir");
+ const match = await resolve("linked/page.md", { workspace });
+ assert.equal(match?.matchedBy, "exact-relative");
+ assert.equal(match?.relativePath, "linked/page.md");
+});
+
+test("a stale fuzzy index skips escaped and missing candidates in priority order", async () => {
+ const workspace = tempTree("stale-index", ["a/page.md", "b/page.md", "c/page.md"]);
+ assert.equal((await resolve("page.md", { workspace }))?.relativePath, "a/page.md");
+ renameSync(join(workspace, "a"), join(workspace, "old-a"));
+ renameSync(join(workspace, "b"), join(workspace, "old-b"));
+ const outside = tempTree("stale-outside", ["page.md"]);
+ symlinkSync(outside, join(workspace, "a"), process.platform === "win32" ? "junction" : "dir");
+ assert.equal((await resolve("page.md", { workspace }))?.relativePath, "c/page.md");
+});
+
+test("a dangling relative link does not report a match", async () => {
+ const workspace = tempTree("dangling-link", ["other/linked"]);
+ symlinkSync(join(workspace, "missing"), join(workspace, "linked"), process.platform === "win32" ? "junction" : "dir");
+ assert.equal(await resolve("linked", { workspace }), null);
+});
+
test("a longer matching tail beats a bare leaf name", async () => {
const workspace = tempTree("ws", ["deep/openimage.js", "src/dir/openimage.js"]);
const match = await resolve("dir/openimage.js", { workspace });
@@ -219,6 +255,22 @@ test("a content-addressed attachment blob resolves against the attachment store"
);
});
+test("an attachment blob symlink cannot escape its store", async (t) => {
+ const digest = "c".repeat(64);
+ const attachments = tempTree("attachment-link", []);
+ const outside = tempTree("attachment-outside", ["page.md"]);
+ try {
+ symlinkSync(join(outside, "page.md"), join(attachments, digest), "file");
+ } catch (error) {
+ if (process.platform === "win32" && error?.code === "EPERM") {
+ t.skip("file symlinks require Windows Developer Mode or elevated privileges");
+ return;
+ }
+ throw error;
+ }
+ assert.equal(await resolve(`attachments/${digest}`, { attachments }), null);
+});
+
test("an attachment blob reference rejects invalid hash formats or non-hex characters", async () => {
const attachments = tempTree("attachments", ["not-a-valid-sha256"]);
assert.equal(
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 10cfe62bf..3094037e3 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1809,7 +1809,10 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:
so a shorthand resolves in a sibling folder as readily as in the primary one,
and the match names the folder that answered. Inside one root an exact path
beats a shorthand; among shorthands the longest matching tail wins, then the
- shallowest path. The files-panel ignore set applies. A reference that matches
+ shallowest path. Relative and indexed candidates must resolve to regular files
+ whose real paths remain inside their answering root; an exact path through an
+ escaping or dangling link cannot fall back to a same-name indexed file. The
+ files-panel ignore set applies. A reference that matches
nothing returns `match: null`; an absolute path outside every allowed root
also returns `reason: "outside-allowed-roots"`, without trying a same-name
file inside a root. Resolving never opens anything (ADR 0262).
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 44a3b2eed..9b6cf880e 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -11912,7 +11912,10 @@ are withdrawn with ADR 0165.
and a `~/` path in chat; confirm only the under-root path becomes a target.
6) Send a user message `使用llama.cpp,给我迁移步骤,只读。`, then a user
message that names the real `apps/desktop/src/App.tsx` as a bare path and as
- `@apps/desktop/src/App.tsx`.
+ `@apps/desktop/src/App.tsx`. 7) Add a workspace directory link to an
+ outside `page.md`, a second in-root `page.md`, and a link to an in-root file;
+ check the exact linked path and a shorthand `page.md`. Repeat with a session
+ scratch directory link, and check a dangling link.
- **Expected**:
- Opening the session paints the transcript without throwing.
- Each chat path opens `apps/desktop/src/App.tsx` in the File Manager
@@ -11929,6 +11932,10 @@ are withdrawn with ADR 0165.
a file chip, when that path does not exist.
- A user-message bare path becomes a chip only after `fs/resolveRef` confirms
a real file; an explicit `@path` chips immediately.
+ - Escaping and dangling exact links do not become file targets or redirect to
+ the same-name in-root file. A shorthand selects the first currently valid
+ in-root file, while an in-root link still opens its target. Scratch links
+ follow the same containment rule.
- **Specs linked**: `04-ux/08-component-spec.md` §8.3,
`08-meta/decisions-log.md` (D322)
- **Acceptance**: C (conversation & stream), D (workspace), Quality