Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions apps/desktop/src/electron/ElectronShell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ describe("ElectronShell", () => {
writeTextMock.mockReset();
});

it.effect("opens only known Wayfinder destinations", () =>
Effect.gen(function* () {
openExternalMock.mockResolvedValue(undefined);
const shell = yield* ElectronShell.ElectronShell;
assert.equal(yield* shell.openExternal("wayfinder://map/I_map"), true);
assert.equal(yield* shell.openExternal("wayfinder://ticket/id?command=run"), false);
assert.deepEqual(openExternalMock.mock.calls, [["wayfinder://map/I_map"]]);
}).pipe(Effect.provide(ElectronShell.layer)),
);

it.effect("opens remote SSH editor URLs", () =>
Effect.gen(function* () {
openExternalMock.mockResolvedValue(undefined);
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/electron/ElectronShell.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { MAC_PERMISSION_SETTINGS_URLS } from "../permissions/MacPermission.ts";
import { isWayfinderLink } from "@t3tools/shared/markdownLinks";
import {
REMOTE_CAPABLE_EDITOR_IDS,
remoteSchemeForEditor,
Expand Down Expand Up @@ -44,7 +45,7 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {

try {
const url = new URL(rawUrl);
return SAFE_WEB_PROTOCOLS.has(url.protocol) || isRemoteEditorUrl(url)
return SAFE_WEB_PROTOCOLS.has(url.protocol) || isRemoteEditorUrl(url) || isWayfinderLink(rawUrl)
? Option.some(url.href)
: Option.none();
} catch {
Expand Down
10 changes: 10 additions & 0 deletions apps/mobile/src/lib/markdownLinks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ import { describe, expect, it } from "vite-plus/test";
import { resolveMarkdownLinkPresentation } from "./markdownLinks";

describe("resolveMarkdownLinkPresentation", () => {
it("allows concrete Wayfinder destinations but not commands", () => {
expect(resolveMarkdownLinkPresentation("wayfinder://map/I_map")).toEqual({
kind: "link",
href: "wayfinder://map/I_map",
});
expect(resolveMarkdownLinkPresentation("wayfinder://ticket/id?command=run")).toEqual({
kind: "link",
href: null,
});
});
it("opens relative directory links as workspace paths", () => {
expect(resolveMarkdownLinkPresentation("src/")).toMatchObject({
kind: "file",
Expand Down
5 changes: 4 additions & 1 deletion apps/mobile/src/lib/markdownLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
parseMarkdownFileLink,
} from "@t3tools/shared/markdownLinks";
import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";
import { isWayfinderLink } from "@t3tools/shared/markdownLinks";
import { videoMimeType } from "@t3tools/shared/video";

import type { MARKDOWN_FILE_ICON_SOURCES } from "./markdownFileIcons.generated";
Expand Down Expand Up @@ -281,7 +282,9 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
return {
kind: "link",
href:
/^(?:mailto|tel):/i.test(normalized) || parseThreadLinkHref(normalized) !== null
/^(?:mailto|tel):/i.test(normalized) ||
parseThreadLinkHref(normalized) !== null ||
isWayfinderLink(normalized)
? normalized
: null,
};
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/ChatMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ import { defaultUrlTransform } from "react-markdown";
import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations";
import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";
import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";
import { isWayfinderLink } from "@t3tools/shared/markdownLinks";
import { AssistantCitationChip } from "./chat/AssistantCitationChip";
import { MarkdownThreadLink } from "./chat/MarkdownThreadLink";
import { mathKind } from "@t3tools/shared/markdownMath";
Expand Down Expand Up @@ -643,6 +644,7 @@ function useChatMarkdownState({
if (parseAssistantCitationHref(href)) return href;
if (parseComposerContextHref(href)) return href;
if (parseThreadLinkHref(href)) return href;
if (isWayfinderLink(href)) return href;
if (isWindowsDrivePathHref(href)) return href;
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
};
Expand Down
2 changes: 2 additions & 0 deletions packages/shared/src/markdownLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
splitFilePathPosition,
} from "./fileLinks.ts";

export { isWayfinderLink } from "./wayfinderLinks.ts";

const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;

// Names may use any script (`線性代數/考試.pdf`). The final segment is optional so an
Expand Down
28 changes: 28 additions & 0 deletions packages/shared/src/markdownPipeline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,34 @@ it("preserves in-app thread links through the shared Markdown sanitizer", () =>
expect(JSON.stringify(tree)).not.toContain("javascript:");
});

it("preserves concrete Wayfinder destinations and drops unknown commands", () => {
const processor = unified()
.use(remarkParse)
.use(CHAT_MARKDOWN_REMARK_PLUGINS)
.use(remarkRehype, { allowDangerousHtml: true })
.use(CHAT_MARKDOWN_REHYPE_PLUGINS);
for (const href of [
"wayfinder://repo/R_repo",
"wayfinder://map/I_map",
"wayfinder://ticket/I_ticket",
"wayfinder://prototype/I_ticket?canvas=prototypes%2Freplies%2Findex.html&rev=" + "a".repeat(40),
"wayfinder://map?repo=owner%2Frepo&number=217",
]) {
const tree = processor.runSync(processor.parse(`[Open in Wayfinder](${href})`));
expect(tree.children[0]).toMatchObject({ children: [{ properties: { href } }] });
}
for (const href of [
"wayfinder://settings",
"wayfinder://ticket/id?command=run",
"wayfinder://user@map/id",
"wayfinder://prototype/id?canvas=prototypes%2F..%2Fprivate.html",
"wayfinder://map?repo=owner%2Frepo&number=217&number=218",
]) {
const tree = processor.runSync(processor.parse(`[Invalid](${href})`));
expect(JSON.stringify(tree)).not.toContain('"href"');
}
});

it("keeps backslashes that CommonMark would read as escapes in prose Windows paths", () => {
const processor = unified()
.use(remarkParse)
Expand Down
21 changes: 21 additions & 0 deletions packages/shared/src/markdownPipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from "./codexMarkdownDirectives.ts";
import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts";
import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
import { isWayfinderLink } from "./wayfinderLinks.ts";

type MarkdownImageHastNode = {
type?: string;
Expand Down Expand Up @@ -157,6 +158,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
"t3-citation",
"t3-context",
THREAD_LINK_PROTOCOL,
"wayfinder",
],
src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
},
Expand Down Expand Up @@ -189,9 +191,28 @@ export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
rehypePreserveBareAnchorPlaceholders,
rehypeRaw,
rehypePreserveImageSourceMeta,
rehypeValidateWayfinderLinks,
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
];

function rehypeValidateWayfinderLinks() {
return (tree: MarkdownImageHastNode) => {
const visit = (node: MarkdownImageHastNode) => {
const href = node.properties?.href;
if (
node.properties &&
typeof href === "string" &&
/^wayfinder:/i.test(href) &&
!isWayfinderLink(href)
) {
delete node.properties.href;
}
node.children?.forEach(visit);
};
visit(tree);
};
}

const isImageNode = (node: PhrasingContent | undefined): boolean =>
node?.type === "image" ||
node?.type === "imageReference" ||
Expand Down
54 changes: 54 additions & 0 deletions packages/shared/src/wayfinderLinks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const validId = (value: string) =>
value.length > 0 &&
value.length <= 512 &&
value !== "." &&
value !== ".." &&
[...value].every((character) => character.charCodeAt(0) > 32 && character.charCodeAt(0) !== 127);

export function isWayfinderLink(value: string): boolean {
try {
const url = new URL(value);
if (url.protocol !== "wayfinder:" || url.username || url.password || url.port || url.hash)
return false;
const kind = url.hostname;
if (kind !== "repo" && kind !== "map" && kind !== "ticket" && kind !== "prototype")
return false;
if (kind === "map" && (url.pathname === "" || url.pathname === "/")) {
const repo = url.searchParams.get("repo") ?? "";
const number = url.searchParams.get("number") ?? "";
return (
[...url.searchParams.keys()].every((key) => key === "repo" || key === "number") &&
url.searchParams.getAll("repo").length === 1 &&
url.searchParams.getAll("number").length === 1 &&
/^[\w.-]+\/[\w.-]+$/.test(repo) &&
repo.split("/").every((part) => part !== "." && part !== "..") &&
/^[1-9]\d*$/.test(number) &&
Number.isSafeInteger(Number(number))
);
}
const parts = url.pathname.split("/");
if (parts.length !== 2 || !validId(decodeURIComponent(parts[1] ?? ""))) return false;
if (kind !== "prototype") return url.search.length === 0;
const allowed = new Set(["canvas", "rev", "page", "item"]);
if (
[...url.searchParams.keys()].some(
(key) => !allowed.has(key) || url.searchParams.getAll(key).length !== 1,
)
)
return false;
const canvas = url.searchParams.get("canvas") ?? "";
const revision = url.searchParams.get("rev");
return (
canvas.length <= 2048 &&
canvas.startsWith("prototypes/") &&
/\.html?$/i.test(canvas) &&
canvas.split("/").every((part) => validId(part) && !/[\\?#%:]/.test(part)) &&
(revision === null || /^[a-f0-9]{40}$/i.test(revision)) &&
["page", "item"].every(
(key) => !url.searchParams.has(key) || validId(url.searchParams.get(key) ?? ""),
)
);
} catch {
return false;
}
}
Loading