fix(security): close the findings of GHSA-442p-gxfg-qxv9

- Restricted Mode git: reads run without a signature verifier, hooks
  (including config-defined ones), an external diff, filters or a lazy
  fetch, also inside submodules; every repository and every git starts
  restricted until the project is trusted.
- project.write and plugin quick fixes cannot reach git's own files under
  any spelling or through links; project.write is a high-risk grant.
- Built-in web server: each served root has its own port and token; a
  file outside the project is served with its folder minus dot names, or
  alone when that folder is the home folder or above it; no fixed port.
- Images, references, Markdown links and language-server links reach no
  network share other than the one already open.
- Marketplace: entries whose id or version no manifest may carry are
  dropped; an index read over the network names nothing on this machine;
  network reads are bounded in size and time.
- Agent replies load remote images on a click; the Markdown preview and
  Mermaid configuration no longer fetch from other hosts.
Цей коміт міститься в:
Fabio Nunes Cerqueira authored and l0ng-ai committed 2026-11-11 22:18:48 +08:00
1 джерело 8b179992e8
коміт a497178b3e
53 files changed
+3206 -243

No files matched your search

+19 -2
Переглянути файл
@@ -71,8 +71,25 @@ describe("links and fragments", () => {
const text = Text.of(['<a href="b.html#top">']);
const range = { start: { line: 0, col: 9 }, end: { line: 0, col: 19 } };
const link = { range, path: "/p/b.html", fragment: "top", url: null, tooltip: null };
expect(linkReference(text, [link], 12)).toMatchObject({ kind: "file", path: "/p/b.html", fragment: "top" });
expect(linkReference(text, [link], 2)).toBeNull();
expect(linkReference(text, [link], 12, "/p/a.html")).toMatchObject({
kind: "file",
path: "/p/b.html",
fragment: "top",
});
expect(linkReference(text, [link], 2, "/p/a.html")).toBeNull();
});
// On Windows, opening `//server/share` signs in to that server with the user's credentials.
it("follows no server link to a share the file is not on", () => {
const text = Text.of(['<a href="file:////evil/share/b.html">']);
const range = { start: { line: 0, col: 9 }, end: { line: 0, col: 35 } };
const link = { range, path: "//evil/share/b.html", fragment: null, url: null, tooltip: null };
expect(linkReference(text, [link], 12, "C:/p/a.html")).toBeNull();
expect(linkReference(text, [link], 12, "//nas/work/a.html")).toBeNull();
expect(linkReference(text, [{ ...link, path: "//nas/work/b.html" }], 12, "//NAS/Work/a.html")).toMatchObject({
kind: "file",
path: "//nas/work/b.html",
});
});
it("locates line, element id and Markdown heading fragments", () => {
+10 -2
Переглянути файл
@@ -10,6 +10,7 @@ import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { whenSynced, type EditorDocContext } from "@/editor/api";
import { call, commands, isTauri, type DocumentLink } from "@/platform/ipc";
import { onOtherShare } from "@/platform/paths";
import { openExternalUrl } from "@/platform/openUrl";
import { executeAction } from "@/platform/actions";
import { editorService } from "@/workbench/contributions";
@@ -53,10 +54,17 @@ export function knownLinks(view: EditorView): DocumentLink[] | undefined {
return fetchedLinks.get(view.state.doc);
}
export function linkReference(text: Text, links: readonly DocumentLink[], offset: number): Reference | null {
/** The server's link around `offset` in the document at `path`; none to a network share that document is not on. */
export function linkReference(
text: Text,
links: readonly DocumentLink[],
offset: number,
path: string,
): Reference | null {
for (const l of links) {
const { from, to } = rangeToOffsets(text, l.range);
if (offset < from || offset > to) continue;
if (l.path && onOtherShare(l.path, path)) return null;
if (l.path) return { kind: "file", from, to, path: l.path, fragment: l.fragment };
if (l.url) return { kind: "url", from, to, url: l.url };
}
@@ -195,7 +203,7 @@ export async function followReference(ref: Reference): Promise<void> {
* named by a quoted path. Null when there is none.
*/
export async function referenceAt(view: EditorView, doc: EditorDocContext, offset: number): Promise<Reference | null> {
const link = linkReference(view.state.doc, await documentLinks(view, doc), offset);
const link = linkReference(view.state.doc, await documentLinks(view, doc), offset, doc.path);
const ref = textReference(view.state.doc, offset);
if (link?.kind !== "file") {
if (link) return link;
+25
Переглянути файл
@@ -1,4 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import type { ProjectInfo } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { sourceLink } from "./markdown";
// A fresh module per test: the parser is loaded lazily and cached module-wide.
async function freshMarkdown() {
@@ -56,3 +59,25 @@ describe("markdown rendering", () => {
expect(md.markupToHtml({ kind: "plaintext", value: "<b>" })).toBe('<p class="cm-lsp-plain">&#60;b&#62;</p>');
});
});
// On Windows, opening `//server/share` signs in to that server with the user's credentials.
describe("sourceLink", () => {
const project = (root: string | null) =>
useProject.setState({ project: root === null ? null : ({ root } as ProjectInfo) });
it("reads the file and position a documentation link names", () => {
project("C:/repo");
expect(sourceLink("file:///C:/repo/src/a.py#L12,5")).toEqual({ path: "/C:/repo/src/a.py", line: 11, col: 4 });
expect(sourceLink("https://example.com/a.py")).toBeNull();
});
it("names no share the project is not on", () => {
for (const root of ["C:/repo", "//nas/work/app", null]) {
project(root);
expect(sourceLink("file:////evil/share/a.py#L3"), String(root)).toBeNull();
expect(sourceLink("file:///%5C%5Cevil/share/a.py"), String(root)).toBeNull();
}
project("//nas/work/app");
expect(sourceLink("file:////NAS/work/lib/a.py#L3")).toEqual({ path: "//NAS/work/lib/a.py", line: 2, col: 0 });
});
});
+6 -1
Переглянути файл
@@ -13,6 +13,8 @@ import { classHighlighter, highlightTree } from "@lezer/highlight";
import type { Markup } from "@/bindings";
import { maybeEditorService } from "@/workbench/contributions";
import { isTauri } from "@/platform/ipc";
import { onOtherShare } from "@/platform/paths";
import { useProject } from "@/platform/project";
import { isVirtualUri } from "@/platform/virtualDocs";
import { selectableText } from "@/ui/selectableText";
@@ -203,9 +205,12 @@ export function sourceLink(href: string): { path: string; line: number; col: num
} catch {
return null;
}
const path = decodeURIComponent(url.pathname);
// Documentation is text someone else wrote.
if (onOtherShare(path, useProject.getState().project?.root ?? "")) return null;
const m = /^#?L?(\d+)(?:[,:](\d+))?/.exec(url.hash.slice(1));
return {
path: decodeURIComponent(url.pathname),
path,
line: m ? Math.max(0, Number(m[1]) - 1) : 0,
col: m?.[2] ? Math.max(0, Number(m[2]) - 1) : 0,
};
+2 -1
Переглянути файл
@@ -740,7 +740,8 @@ function linkAt(view: EditorView, x: number, y: number): { from: number; to: num
const pos = view.posAtCoords({ x, y }, false);
if (pos == null) return null;
const links = knownLinks(view);
const ref = (links && linkReference(view.state.doc, links, pos)) ?? textReference(view.state.doc, pos);
const ref =
(links && linkReference(view.state.doc, links, pos, docOf(view)?.path ?? "")) ?? textReference(view.state.doc, pos);
if (ref) return { from: ref.from, to: ref.to, link: true };
const word = navigationWord(view, pos);
return word && word.from < word.to ? { from: word.from, to: word.to, link: false } : null;
+33 -9
Переглянути файл
@@ -155,13 +155,24 @@ it("loads raw HTML images without allowing alternate sources or forged paths", a
expect(container.querySelector("source, [srcset], [onerror]")).toBeNull();
});
it.each([PIXEL, "https://example.com/code.png", "http://localhost:9000/code.png"])(
"keeps an inline or web image: %s",
it("keeps an inline image: a data URL loads without a request", () => {
render(<Markdown text={`![QR](${PIXEL})`} cwd="/repo" />);
expect(screen.getByRole("img")).toHaveAttribute("src", PIXEL);
expect(screen.getByRole("img")).toHaveAttribute("referrerpolicy", "no-referrer");
expect(readImage).not.toHaveBeenCalled();
});
it.each(["https://example.com/code.png", "http://localhost:9000/code.png"])(
"loads a web image in a reply only on a click: %s",
(src) => {
render(<Markdown text={`![QR](${src})`} cwd="/repo" />);
expect(screen.getByRole("img")).toHaveAttribute("src", src);
expect(screen.getByRole("img")).toHaveAttribute("referrerpolicy", "no-referrer");
const { container } = render(<Markdown text={`![QR](${src})`} cwd="/repo" />);
const img = container.querySelector("img")!;
// Not fetched on render: a button stands in, the image is hidden with no src.
expect(img).not.toHaveAttribute("src");
expect(readImage).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: `Load image from ${new URL(src).host}` }));
expect(img).toHaveAttribute("src", src);
expect(img).toHaveAttribute("referrerpolicy", "no-referrer");
},
);
@@ -213,10 +224,23 @@ it.each(["javascript:alert(1)", "data:text/html,test", "/tmp/%ZZ.png", "/tmp/cod
);
it("reports network or decode failures without leaving a broken source", () => {
render(<Markdown text="![QR](https://example.com/gone.png)" cwd="/repo" />);
fireEvent.error(screen.getByRole("img"));
expect(screen.getByRole("img")).not.toHaveAttribute("src");
expect(screen.getByRole("img")).toHaveAttribute("alt", "Unable to load image: https://example.com/gone.png");
const { container } = render(<Markdown text="![QR](https://example.com/gone.png)" cwd="/repo" />);
fireEvent.click(screen.getByRole("button", { name: "Load image from example.com" }));
const img = container.querySelector("img")!;
fireEvent.error(img);
expect(img).not.toHaveAttribute("src");
expect(img).toHaveAttribute("alt", "Unable to load image: https://example.com/gone.png");
});
it("drops a reply attribute that names another host, so nothing fetches on render", () => {
const { container } = render(
<Markdown
text={'<video poster="https://example.com/p.jpg"></video><p background="//evil.test/x">x</p>'}
cwd="/repo"
/>,
);
expect(container.querySelector("[poster]")).toBeNull();
expect(container.querySelector("[background]")).toBeNull();
});
describe("mermaid diagrams in a reply", () => {
+15 -4
Переглянути файл
@@ -19,7 +19,7 @@ import { editorService } from "@/workbench/contributions";
import { hasMermaid, renderMermaidIn } from "@/features/viewers/markdown/mermaid";
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
import { fileHref, pathLink, type PathLink } from "./conversation";
import { loadImages } from "./markdownImages";
import { loadImages, type MessageImages } from "./markdownImages";
import styles from "./Session.module.css";
const escapeHtml = (s: string) =>
@@ -42,9 +42,20 @@ const RENDERED_MAX = 500;
let purifier: ReturnType<typeof DOMPurify> | null = null;
/** Whether the webview would read `value` as an address on another host: it drops blanks and takes `\` for `/`. */
const namesHost = (value: string) =>
/^(https?:|[\\/]{2})/i.test([...value].filter((c) => c.charCodeAt(0) > 32).join(""));
function purify(): ReturnType<typeof DOMPurify> {
if (purifier) return purifier;
const p = DOMPurify(window);
// A reply reaches another host only when the user asks: a link they click, an image `loadImages` holds.
// `poster`, `background` and the `src` of other tags would fetch as soon as the reply renders.
p.addHook("uponSanitizeAttribute", (node, data) => {
if (data.attrName === "alt" || data.attrName === "title") return;
if (data.attrName === "href" && node.tagName === "A") return;
if (namesHost(data.attrValue)) data.keepAttr = false;
});
const sources = new WeakMap<Node, string>();
// Preserve image-only file URLs without relaxing URI sanitizing for links or other tags.
p.addHook("beforeSanitizeAttributes", (node) => {
@@ -176,7 +187,7 @@ export function openPathLink(link: PathLink) {
}
/** Highlighting, Copy buttons and file links over freshly rendered `root`. */
function enhance(root: HTMLElement, cwd: string, images: Map<string, Promise<string>>): () => void {
function enhance(root: HTMLElement, cwd: string, images: MessageImages): () => void {
let alive = true;
const disposeImages = loadImages(root, cwd, images);
const copies: HTMLButtonElement[] = [];
@@ -243,7 +254,7 @@ function paintBlocks(
painted: PaintedBlock[],
sources: string[],
cwd: string,
images: Map<string, Promise<string>>,
images: MessageImages,
) {
let same = 0;
while (same < painted.length && same < sources.length && painted[same]!.source === sources[same]) same++;
@@ -271,7 +282,7 @@ export function Markdown({
onDiagramDrawn?: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
const images = useRef(new Map<string, Promise<string>>());
const images = useRef<MessageImages>({ reads: new Map(), asked: new Set() });
/** The blocks on screen, so a streamed chunk repaints only the blocks it changed. */
const painted = useRef<PaintedBlock[]>([]);
const paintedCwd = useRef(cwd);
+12
Переглянути файл
@@ -540,6 +540,18 @@
.markdown :global(img) {
max-width: 100%;
}
.loadImage {
padding: 2px 8px;
border: 1px solid var(--border);
border-radius: var(--radius-small);
background: var(--bg-elev);
color: var(--fg-secondary);
font: inherit;
cursor: pointer;
}
.loadImage:hover {
background: var(--bg-hover);
}
.markdown :global(li:has(> input[type="checkbox"])) {
margin-left: -20px;
}
+28 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { findAll, findRanges, formatDuration, pathLink, quoteText, withQuote } from "./conversation";
import { fileHref, findAll, findRanges, formatDuration, pathLink, quoteText, withQuote } from "./conversation";
describe("quoting", () => {
it("quotes each line and leaves a line to type on", () => {
@@ -37,6 +37,33 @@ describe("pathLink", () => {
});
});
describe("fileHref", () => {
const cwd = "C:/repo";
it("resolves a link against the task folder", () => {
expect(fileHref("docs/my%20notes.md:3", cwd)).toEqual({ path: "C:/repo/docs/my notes.md", line: 2 });
expect(fileHref("/abs/x.py#L7", cwd)).toEqual({ path: "/abs/x.py", line: 6 });
expect(fileHref("https://x.dev/a.md", cwd)).toBeNull();
expect(fileHref("#top", cwd)).toBeNull();
});
// On Windows, opening `//server/share` signs in to that server with the user's credentials.
it("names no network share, however the link spells it", () => {
for (const href of [
"//evil/share/x.md",
"%2F%2Fevil/share/x.md",
"/%2Fevil/share/x.md",
"/\\evil/share/x.md",
"/%5Cevil/share/x.md",
"%5C%5Cevil%5Cshare%5Cx.md",
]) {
expect(fileHref(href, cwd), href).toBeNull();
}
expect(fileHref("%5Cevil/share/x.md", ""), "no task folder").toBeNull();
});
it("follows links in a task that is on a share", () => {
expect(fileHref("docs/a.md", "//nas/work/app")).toEqual({ path: "//nas/work/app/docs/a.md" });
});
});
describe("formatDuration", () => {
it("scales the unit", () => {
expect(formatDuration(850)).toBe("850ms");
+4 -1
Переглянути файл
@@ -1,5 +1,7 @@
/** Reading an agent conversation: quoting, file links, turn times and finding text. */
import { opensOtherShare } from "@/platform/paths";
/** `text` as a Markdown quote for the composer, followed by an empty line to type in. */
export function quoteText(text: string): string {
const lines = text.replace(/\s+$/, "").split("\n");
@@ -24,7 +26,7 @@ const PATH = /^(?:\.\/)?([\w.@-]+(?:\/[\w.@-]+)*\.[A-Za-z][A-Za-z0-9]*)(?::(\d+)
/** Explicit Markdown links can also name files with spaces or non-ASCII names. */
export function fileHref(href: string, cwd: string): PathLink | null {
if (!href || href.startsWith("#") || href.startsWith("//") || /^[a-z][a-z\d+.-]*:/i.test(href)) return null;
if (!href || href.startsWith("#") || /^[a-z][a-z\d+.-]*:/i.test(href)) return null;
let decoded: string;
try {
decoded = decodeURIComponent(href);
@@ -34,6 +36,7 @@ export function fileHref(href: string, cwd: string): PathLink | null {
const match = /^(.*?)(?::(\d+)(?::(\d+))?|#L(\d+))?$/.exec(decoded);
if (!match?.[1] || [...decoded].some((char) => char.charCodeAt(0) < 32)) return null;
const path = match[1].startsWith("/") ? match[1] : `${cwd.replace(/\/$/, "")}/${match[1]}`;
if (opensOtherShare(path, match[1], cwd)) return null;
const link: PathLink = { path };
const line = match[2] ?? match[4];
if (line) link.line = Math.max(0, Number(line) - 1);
+32 -6
Переглянути файл
@@ -1,6 +1,7 @@
import { call, commands } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
import { tx } from "@/platform/i18n";
import styles from "./Session.module.css";
const hasControl = (text: string) => [...text].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127);
@@ -37,9 +38,12 @@ export function imageTarget(source: string, cwd: string): ImageTarget | null {
}
}
/** Cache belongs to one message: streaming reuses reads, later replies can show a new QR at the same path. */
export function loadImages(root: HTMLElement, cwd: string, cache: Map<string, Promise<string>>): () => void {
/** What one message has loaded: streaming reuses it, later replies read a new QR at the same path and ask again. */
export type MessageImages = { reads: Map<string, Promise<string>>; asked: Set<string> };
export function loadImages(root: HTMLElement, cwd: string, { reads, asked }: MessageImages): () => void {
let alive = true;
const held: HTMLButtonElement[] = [];
const images = [...root.querySelectorAll<HTMLImageElement>("img")];
for (const img of images) {
const source = img.dataset.imageSrc ?? "";
@@ -55,13 +59,34 @@ export function loadImages(root: HTMLElement, cwd: string, cache: Map<string, Pr
if (!target) {
fail();
} else if ("url" in target) {
img.src = target.url;
const { url } = target;
if (/^data:/i.test(url) || asked.has(url)) {
img.hidden = false;
img.src = url;
} else {
// A reply can be steered into naming an address that carries data out: the user decides.
// That holds for this machine too, where a server may pass the request on.
const load = document.createElement("button");
load.type = "button";
load.className = styles.loadImage!;
load.textContent = tx`Load image from ${new URL(url).host}`;
load.title = url;
load.onclick = () => {
asked.add(url);
load.remove();
img.hidden = false;
img.src = url;
};
img.hidden = true;
img.before(load);
held.push(load);
}
} else {
let pending = cache.get(target.path);
let pending = reads.get(target.path);
if (!pending) {
pending = call(commands.fsReadImage(target.path));
cache.set(target.path, pending);
void pending.catch(() => cache.delete(target.path));
reads.set(target.path, pending);
void pending.catch(() => reads.delete(target.path));
}
void pending.then((url) => {
if (alive) img.src = url;
@@ -71,5 +96,6 @@ export function loadImages(root: HTMLElement, cwd: string, cache: Map<string, Pr
return () => {
alive = false;
for (const img of images) img.onerror = null;
for (const load of held) load.remove();
};
}
+2
Переглянути файл
@@ -180,6 +180,8 @@ function configure(mermaid: Mermaid, key: string) {
mermaid.initialize({
startOnLoad: false,
securityLevel: "strict",
// These go into the diagram's stylesheet as written: a diagram setting them could fetch from any host.
secure: ["themeCSS", "fontFamily", "altFontFamily"],
suppressErrorRendering: true,
theme: "base",
// Each diagram type defaults to "neo": the start state is hard-coded
+43
Переглянути файл
@@ -91,6 +91,31 @@ describe("markdown preview rendering", () => {
expect(root.textContent).not.toContain("outline");
});
it("lets only a link name another host", () => {
const at = (name: string) => `https://example.com/${name}`;
const root = document.createElement("div");
root.innerHTML = renderMarkdown(
[
`[A link](${at("link")})`,
`<img src="a.png" srcset="b.png 1x, ${at("srcset")} 2x">`,
`<picture><source srcset="${at("source")}"><img src="a.png"></picture>`,
`<input type="image" src="${at("input")}">`,
`<video poster="${at("poster")}" src="${at("video")}"></video>`,
`<table background="${at("table")}"><tr><td background="${at("cell")}">cell</td></tr></table>`,
'<input type="image" src="//example.com/no-scheme">',
String.raw`<input type="image" src="/\example.com/mixed">`,
].join("\n\n"),
);
const named = [...root.querySelectorAll("*")].flatMap((el) =>
[...el.attributes]
.filter((attr) => attr.value.includes("example.com"))
.map((attr) => `${el.localName}[${attr.name}]`),
);
expect(named).toEqual(["a[href]"]);
expect([...root.querySelectorAll("img")].map((img) => img.dataset.src)).toEqual(["a.png", "a.png"]);
expect(root.querySelector("td")?.textContent).toBe("cell");
});
it("keeps the raw HTML READMEs rely on", () => {
const root = document.createElement("div");
root.innerHTML = renderMarkdown(
@@ -204,6 +229,24 @@ describe("markdown preview rendering", () => {
expect(joinPath("/repo", "../../a.md")).toBe("/a.md");
});
// On Windows, opening `//server/share` signs in to that server with the user's credentials.
it("resolves no link to a network share, however the file spells it", () => {
const file = "C:/repo/docs/guide.md";
for (const href of [
"/\\evil/share/x.png",
"/%5Cevil/share/x.png",
"//evil/share/x.png",
"/%2Fevil/share/x.png",
"file:///%5Cevil/share/x.png",
"file:////evil/share/x.png",
"%5C%5Cevil%5Cshare%5Cx.png",
]) {
expect(resolveLink(file, href), href).toBeNull();
}
expect(resolveLink("/guide.md", "../%5Cevil/share/x.png"), "file at the root").toBeNull();
expect(resolveLink(file, "/docs/a.png")).toEqual({ kind: "file", path: "/docs/a.png" });
});
it("interpolates the preview offset between blocks", () => {
const blocks = [
{ line: 0, top: 0 },
+17 -2
Переглянути файл
@@ -8,6 +8,7 @@
*/
import { Marked, type Token, type TokensList } from "marked";
import DOMPurify from "dompurify";
import { opensOtherShare } from "@/platform/paths";
const escapeHtml = (s: string) =>
s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -26,9 +27,21 @@ const marked = new Marked({
// Own instance: hooks must not leak into the hover / documentation renderer.
let purifier: ReturnType<typeof DOMPurify> | null = null;
/** Whether the webview would read `value` as an address on another host: it drops blanks and takes `\` for `/`. */
const namesHost = (value: string) =>
/^(https?:|[\\/]{2})/i.test([...value].filter((c) => c.charCodeAt(0) > 32).join(""));
function purify(): ReturnType<typeof DOMPurify> {
if (purifier) return purifier;
const p = DOMPurify(window);
// The preview loads nothing from other hosts. Only a link, opened on a click, names one;
// an image keeps its source for the preview to refuse.
p.addHook("uponSanitizeAttribute", (node, data) => {
if (data.attrName === "alt" || data.attrName === "title") return;
if (data.attrName === "href" && node.tagName === "A") return;
if (data.attrName === "src" && node.tagName === "IMG") return;
if (namesHost(data.attrValue)) data.keepAttr = false;
});
p.addHook("afterSanitizeAttributes", (node) => {
if (node.tagName === "IMG") {
const src = node.getAttribute("src");
@@ -165,8 +178,9 @@ export function renderMarkdown(text: string): string {
return purify().sanitize(html, {
USE_PROFILES: { html: true },
ADD_ATTR: ["data-src", "data-line", "data-front-matter"],
FORBID_TAGS: ["style", "form"],
FORBID_ATTR: ["style"],
// `srcset` and `<source>` would pick an image past the one the preview loads.
FORBID_TAGS: ["style", "form", "source"],
FORBID_ATTR: ["style", "srcset"],
});
}
@@ -203,6 +217,7 @@ export function resolveLink(file: string, href: string): LinkTarget | null {
const fragment = hash >= 0 ? decodeURIComponent(rest.slice(hash + 1)) : undefined;
const pathPart = decodeURIComponent((hash >= 0 ? rest.slice(0, hash) : rest).replace(/\?.*$/, ""));
const path = pathPart ? joinPath(dirOf(file), pathPart) : file;
if (pathPart && opensOtherShare(path, pathPart, file)) return null;
const lineMatch = fragment ? /^L(\d+)/.exec(fragment) : null;
if (lineMatch) return { kind: "file", path, line: Math.max(0, Number(lineMatch[1]) - 1) };
return { kind: "file", path, ...(fragment ? { anchor: fragment } : {}) };
+1
Переглянути файл
@@ -349,6 +349,7 @@
"Listening for Xdebug on port {port}": "Listening for Xdebug on port {port}",
"Port {port} is already in use: another IDE or debug session may be listening on it. Stop it or choose another port.": "Port {port} is already in use: another IDE or debug session may be listening on it. Stop it or choose another port.",
"Unable to load image: {path}": "Unable to load image: {path}",
"Load image from {host}": "Load image from {host}",
"Updates": "Updates",
"Update source": "Update source",
"Current version": "Current version",
+1
Переглянути файл
@@ -6820,6 +6820,7 @@
"Stage and Retry": "暂存并重试",
"Show Files": "显示文件",
"Unable to load image: {path}": "无法加载图片:{path}",
"Load image from {host}": "加载来自 {host} 的图片",
"Updates": "更新",
"Update source": "更新源",
"Current version": "当前版本",
+55 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { ipcPath } from "./paths";
import { ipcPath, onOtherShare, opensOtherShare } from "./paths";
const raw = String.raw;
const APPDATA = raw`C:\Users\me\AppData\Roaming\ai.l0ng.openidea`;
@@ -22,3 +22,57 @@ describe("ipcPath", () => {
expect(ipcPath(raw`/home/me/a\b.txt`)).toBe(raw`/home/me/a\b.txt`);
});
});
describe("onOtherShare", () => {
it("is true for a share the base is not on", () => {
for (const base of ["C:/repo/a.md", "", "//nas/work/a.md", "//evil/other/a.md", "//evil"]) {
expect(onOtherShare("//evil/share/a.png", base), base).toBe(true);
expect(onOtherShare(raw`\\evil\share\a.png`, base), base).toBe(true);
}
// A server alone, and spellings with no server to compare.
for (const path of ["//evil", "//evil/", raw`/\\evil/share/a.png`]) {
expect(onOtherShare(path, "//evil/share/a.md"), path).toBe(true);
}
});
// A project on a share gets its paths from the host as `//?/UNC/server/share/…`.
it("reads the server and share of a device path", () => {
const base = "//?/UNC/nas/work/app/a.md";
expect(onOtherShare("//?/UNC/evil/share/a.png", base)).toBe(true);
expect(onOtherShare("//?/UNC/nas/private/a.png", base)).toBe(true);
expect(onOtherShare("//evil/share/a.png", base)).toBe(true);
expect(onOtherShare("//?/UNC", base)).toBe(true);
expect(onOtherShare("//?/C:/a.png", "//?/C:/a.md")).toBe(true);
expect(onOtherShare("//?/unc/NAS/Work/lib/a.png", base)).toBe(false);
expect(onOtherShare("//nas/work/lib/a.png", base)).toBe(false);
expect(onOtherShare("//?/UNC/nas/work/lib/a.png", "//nas/work/app/a.md")).toBe(false);
});
it("is false on the base's own share and off any share", () => {
expect(onOtherShare("//NAS/Work/lib/a.png", "//nas/work/app/a.md")).toBe(false);
expect(onOtherShare(raw`\\nas\work\lib\a.png`, "//nas/work/app/a.md")).toBe(false);
expect(onOtherShare("C:/repo/a.png", "//nas/work/app/a.md")).toBe(false);
expect(onOtherShare("/abs/a.png", "C:/repo/a.md")).toBe(false);
});
});
describe("opensOtherShare", () => {
it("is true for a share the text names itself, in any mix of slashes", () => {
for (const written of ["//evil/share/a.png", raw`\\evil\share\a.png`, raw`/\evil/share/a.png`, raw`\/evil/a.png`]) {
expect(opensOtherShare(written, written, "C:/repo"), written).toBe(true);
expect(opensOtherShare(written, written, "//nas/work"), written).toBe(true);
}
});
it("is true for a share that only appears once the path is resolved", () => {
expect(opensOtherShare(raw`/\evil/share/a.png`, raw`\evil/share/a.png`, "")).toBe(true);
expect(opensOtherShare(raw`/\evil/share/a.png`, raw`../\evil/share/a.png`, "/guide.md")).toBe(true);
expect(opensOtherShare("//evil/share/a.png", "a.png", "//nas/work")).toBe(true);
});
it("is false on a local drive and on the share the text is on", () => {
expect(opensOtherShare("C:/repo/docs/a.png", "docs/a.png", "C:/repo")).toBe(false);
expect(opensOtherShare("/abs/a.png", "/abs/a.png", "C:/repo")).toBe(false);
expect(opensOtherShare("//nas/work/docs/a.png", "docs/a.png", "//nas/work")).toBe(false);
});
});
+33
Переглянути файл
@@ -21,6 +21,39 @@ export function ipcPath(p: string): string {
return DRIVE.test(path) || NETWORK.test(path) ? path.replace(/\\/g, "/") : path;
}
const SHARE = /^[\\/]{2}/;
const SHARE_NAME = /^[\\/]{2}(?:\?[\\/]UNC[\\/])?([^\\/]+)[\\/]([^\\/]+)/i;
/**
* `server/share` of a path on a network share, in lower case; null for any other path. The
* host hands out a share's paths as `//?/UNC/server/share/…`, the dialogs as `//server/share/…`.
*/
function shareOf(path: string): string | null {
const m = SHARE_NAME.exec(path);
// Any other device path (`//?/C:/…`, `//./…`) names no server to compare.
return m && m[1] !== "?" && m[1] !== "." ? `${m[1]}/${m[2]}`.toLowerCase() : null;
}
/**
* Whether `path` is on a network share that `base` is not on. Windows reads `//server/share`,
* `\\server\share` and mixes of the two as a share, and opening one signs in to its server
* with the user's credentials: a path that text someone else wrote leads to is followed to no
* share but the one that text is on.
*/
export function onOtherShare(path: string, base: string): boolean {
if (!SHARE.test(path)) return false;
const share = shareOf(path);
return share === null || share !== shareOf(base);
}
/**
* `onOtherShare` for a path resolved against `base`, the folder or file of the text naming
* it: also true when that text spells a share itself (`written`, decoded).
*/
export function opensOtherShare(path: string, written: string, base: string): boolean {
return SHARE.test(written) || onOtherShare(path, base);
}
/** True when `path` equals `ancestor` or lies below it. */
export function isSameOrInside(path: string, ancestor: string): boolean {
path = ipcPath(path);