Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat: preview public and internal links in Markdown editors (#366)

Ahmad Othman Ammar Adif18e60ea5de5
diff --git a/apps/api/package.json b/apps/api/package.json
index f66c055b..60b2f42f 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -34,6 +34,7 @@
"@repo/mailer": "workspace:*",
"@repo/net": "workspace:*",
"croner": "^10.0.1",
+ "decode-named-character-reference": "^1.3.0",
"drizzle-orm": "^0.45.2",
"elysia": "^1.4.29",
"exceljs": "^4.4.0",
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 1d78fe36..5906130b 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -134,6 +134,7 @@ export const app = new Elysia()
{ name: 'Agent Schedules', description: 'Recurring tasks for internal agents' },
{ name: 'Dashboards', description: 'Saved analytics dashboards' },
{ name: 'Documents', description: 'Shared project Docs pages' },
+ { name: 'Link previews', description: 'Public web link metadata' },
{ name: 'Note boards', description: 'Freeform canvases of sticky notes' },
{ name: 'Notifications', description: "The session user's inbox notifications" },
{ name: 'Sync', description: 'Change markers a client polls for live refresh' },
diff --git a/apps/api/src/modules/link-previews/__tests__/integration/link-previews.test.ts b/apps/api/src/modules/link-previews/__tests__/integration/link-previews.test.ts
new file mode 100644
index 00000000..3443a164
--- /dev/null
+++ b/apps/api/src/modules/link-previews/__tests__/integration/link-previews.test.ts
@@ -0,0 +1,32 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+
+describe('link previews', () => {
+ beforeEach(resetDb);
+
+ it('refuses invalid, credential-bearing and private URLs for authenticated users', async () => {
+ const { cookie } = await signUpTestUser();
+ const client = authedApi(cookie);
+ for (const url of [
+ 'not a URL',
+ 'file:///etc/passwd',
+ 'https://user:[email protected]',
+ 'http://127.0.0.1',
+ 'https://169.254.169.254',
+ ]) {
+ const result = await client['link-previews'].get({ query: { url } });
+ expect(result.status).toBe(400);
+ }
+ });
+
+ it('bounds the URL query before attempting an outbound request', async () => {
+ const { cookie } = await signUpTestUser();
+ const client = authedApi(cookie);
+ for (const url of ['', `https://example.com/${'x'.repeat(4096)}`]) {
+ const result = await client['link-previews'].get({ query: { url } });
+ expect(result.status).toBe(400);
+ }
+ });
+});
diff --git a/apps/api/src/modules/link-previews/__tests__/unit/metadata.test.ts b/apps/api/src/modules/link-previews/__tests__/unit/metadata.test.ts
new file mode 100644
index 00000000..a080557c
--- /dev/null
+++ b/apps/api/src/modules/link-previews/__tests__/unit/metadata.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from 'bun:test';
+import { parseLinkMetadata } from '../../metadata';
+
+describe('parseLinkMetadata', () => {
+ it('prefers Open Graph metadata and resolves relative images', () => {
+ expect(
+ parseLinkMetadata(
+ `
+ <title>Document title</title>
+ <meta name="description" content="Document description">
+ <meta property="og:title" content="Open &amp; Graph">
+ <meta property="og:description" content="A public page">
+ <meta property="og:image" content="/photo.png?one=1&amp;two=2">
+ <meta property="og:site_name" content="Example">
+ `,
+ 'https://example.com/article',
+ ),
+ ).toEqual({
+ url: 'https://example.com/article',
+ title: 'Open & Graph',
+ description: 'A public page',
+ image: 'https://example.com/photo.png?one=1&two=2',
+ siteName: 'Example',
+ });
+ });
+
+ it('falls back to title and description, including named and numeric entities', () => {
+ expect(
+ parseLinkMetadata(
+ '<title> A &copy; &#x1F30F; &#169; </title><meta name="DESCRIPTION" content=" two\n lines ">',
+ 'https://example.com',
+ ),
+ ).toMatchObject({
+ title: 'A © 🌏 ©',
+ description: 'two lines',
+ image: null,
+ });
+ });
+
+ it('supports Twitter metadata and keeps the first duplicate', () => {
+ expect(
+ parseLinkMetadata(
+ '<meta name="twitter:title" content="First"><meta name="twitter:title" content="Second">',
+ 'https://example.com',
+ ).title,
+ ).toBe('First');
+ });
+
+ it('ignores fake metadata inside scripts and comments', () => {
+ expect(
+ parseLinkMetadata(
+ '<script>"<meta property=og:title content=Fake>"</script><!-- <title>Fake</title> -->',
+ 'https://example.com',
+ ).title,
+ ).toBeNull();
+ });
+
+ it('rejects image schemes and embedded credentials', () => {
+ for (const image of [
+ 'javascript:alert(1)',
+ 'data:image/png;base64,AA',
+ 'https://user:[email protected]/image',
+ ]) {
+ expect(
+ parseLinkMetadata(`<meta property="og:image" content="${image}">`, 'https://example.com')
+ .image,
+ ).toBeNull();
+ }
+ });
+
+ it('bounds text and ignores document base URLs', () => {
+ expect(
+ parseLinkMetadata(
+ `<base href="http://localhost/"><meta property="og:title" content="${'x'.repeat(1000)}"><meta property="og:image" content="relative.png">`,
+ 'https://example.com/',
+ ),
+ ).toMatchObject({
+ title: 'x'.repeat(300),
+ image: 'https://example.com/relative.png',
+ });
+ });
+
+ it('returns empty fields for a page without metadata', () => {
+ expect(parseLinkMetadata('<html><body>Content</body></html>', 'https://example.com')).toEqual({
+ url: 'https://example.com',
+ title: null,
+ description: null,
+ image: null,
+ siteName: null,
+ });
+ });
+});
diff --git a/apps/api/src/modules/link-previews/index.ts b/apps/api/src/modules/link-previews/index.ts
new file mode 100644
index 00000000..3b92d73c
--- /dev/null
+++ b/apps/api/src/modules/link-previews/index.ts
@@ -0,0 +1,27 @@
+import { Elysia } from 'elysia';
+import { authContext } from '#shared/auth-context';
+import { errors } from '#shared/responses';
+import { linkPreviewQuery, LinkPreviewResponse } from './model';
+import { getLinkPreview } from './service';
+
+export const linkPreviewRoutes = new Elysia({
+ name: 'link-previews',
+ detail: { tags: ['Link previews'] },
+})
+ .use(authContext)
+ .get(
+ '/link-previews',
+ ({ query, set }) => {
+ set.headers['Cache-Control'] = 'private, max-age=300';
+ return getLinkPreview(query.url);
+ },
+ {
+ query: linkPreviewQuery,
+ response: { 200: LinkPreviewResponse, ...errors(400, 401) },
+ detail: {
+ summary: 'Preview a public web link',
+ description:
+ 'Read public HTML metadata without sending account cookies or credentials to the destination.',
+ },
+ },
+ );
diff --git a/apps/api/src/modules/link-previews/metadata.ts b/apps/api/src/modules/link-previews/metadata.ts
new file mode 100644
index 00000000..02d14bb6
--- /dev/null
+++ b/apps/api/src/modules/link-previews/metadata.ts
@@ -0,0 +1,76 @@
+export interface LinkPreview {
+ url: string;
+ title: string | null;
+ description: string | null;
+ image: string | null;
+ siteName: string | null;
+}
+
+function text(value: string | undefined, limit: number): string | null {
+ return value ? decodeEntities(value).replace(/\s+/g, ' ').trim().slice(0, limit) || null : null;
+}
+
+function decodeEntities(value: string): string {
+ return value.replace(/&(#x[0-9a-f]+|#\d+|[a-z][a-z\d]+);/gi, (match, entity: string) => {
+ if (!entity.startsWith('#')) return decodeNamedCharacterReference(entity) || match;
+ const hex = entity[1]?.toLowerCase() === 'x';
+ const point = parseInt(entity.slice(hex ? 2 : 1), hex ? 16 : 10);
+ if (point === 0 || point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff)) return '\ufffd';
+ return String.fromCodePoint(point);
+ });
+}
+
+export function parseLinkMetadata(html: string, url: string): LinkPreview {
+ const metadata = new Map<string, string>();
+ let title = '';
+ new HTMLRewriter()
+ .on('title', {
+ text(chunk) {
+ if (title.length < 1000) title += chunk.text;
+ },
+ })
+ .on('meta', {
+ element(element) {
+ const name = (
+ element.getAttribute('property') ?? element.getAttribute('name')
+ )?.toLowerCase();
+ const content = element.getAttribute('content');
+ if (name && content && !metadata.has(name)) metadata.set(name, content);
+ },
+ })
+ .transform(html);
+
+ let image: string | null = null;
+ const imageValue =
+ metadata.get('og:image:secure_url') ??
+ metadata.get('og:image') ??
+ metadata.get('twitter:image');
+ if (imageValue && imageValue.length <= 4096) {
+ try {
+ const candidate = new URL(decodeEntities(imageValue), url);
+ if (
+ ['http:', 'https:'].includes(candidate.protocol) &&
+ !candidate.username &&
+ !candidate.password
+ ) {
+ image = candidate.href;
+ }
+ } catch {
+ image = null;
+ }
+ }
+
+ return {
+ url,
+ title: text(metadata.get('og:title') ?? metadata.get('twitter:title') ?? title, 300),
+ description: text(
+ metadata.get('og:description') ??
+ metadata.get('twitter:description') ??
+ metadata.get('description'),
+ 600,
+ ),
+ image,
+ siteName: text(metadata.get('og:site_name'), 100),
+ };
+}
+import { decodeNamedCharacterReference } from 'decode-named-character-reference';
diff --git a/apps/api/src/modules/link-previews/model.ts b/apps/api/src/modules/link-previews/model.ts
new file mode 100644
index 00000000..43330ce8
--- /dev/null
+++ b/apps/api/src/modules/link-previews/model.ts
@@ -0,0 +1,11 @@
+import { t } from 'elysia';
+
+export const linkPreviewQuery = t.Object({ url: t.String({ minLength: 1, maxLength: 4096 }) });
+
+export const LinkPreviewResponse = t.Object({
+ url: t.String(),
+ title: t.Nullable(t.String()),
+ description: t.Nullable(t.String()),
+ image: t.Nullable(t.String()),
+ siteName: t.Nullable(t.String()),
+});
diff --git a/apps/api/src/modules/link-previews/service.ts b/apps/api/src/modules/link-previews/service.ts
new file mode 100644
index 00000000..96077a4a
--- /dev/null
+++ b/apps/api/src/modules/link-previews/service.ts
@@ -0,0 +1,91 @@
+import { assertPublicHttpUrl, pinnedFetch, UrlNotAllowedError } from '@repo/net';
+import { HttpError } from '#shared/lib';
+import { parseLinkMetadata, type LinkPreview } from './metadata';
+
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+
+async function fetchPublic(
+ url: URL,
+ signal: AbortSignal,
+ maxBytes: number,
+ accept: string,
+ truncateBody = false,
+) {
+ for (let redirects = 0; redirects <= 3; redirects++) {
+ const response = await pinnedFetch(url.href, {
+ publicOnly: true,
+ signal,
+ maxBytes,
+ truncateBody,
+ headers: { Accept: accept, 'Accept-Encoding': 'identity' },
+ });
+ if (!REDIRECT_STATUSES.has(response.status)) return { response, url };
+ const location = response.headers.get('location');
+ if (!location || redirects === 3) return null;
+ url = new URL(location, url);
+ }
+ return null;
+}
+
+function rasterType(bytes: Buffer): string | null {
+ if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
+ return 'image/png';
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
+ if (bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP')
+ return 'image/webp';
+ return null;
+}
+
+async function fetchImage(raw: string, signal: AbortSignal): Promise<string | null> {
+ try {
+ const result = await fetchPublic(
+ new URL(raw),
+ signal,
+ 2 * 1024 * 1024,
+ 'image/png, image/jpeg, image/webp',
+ );
+ if (!result?.response.ok) return null;
+ const bytes = Buffer.from(await result.response.arrayBuffer());
+ const type = rasterType(bytes);
+ return type ? `data:${type};base64,${bytes.toString('base64')}` : null;
+ } catch {
+ return null;
+ }
+}
+
+export async function getLinkPreview(raw: string): Promise<LinkPreview> {
+ const signal = AbortSignal.timeout(5000);
+ let url: URL;
+ try {
+ url = await assertPublicHttpUrl(raw, { publicOnly: true, signal });
+ } catch (error) {
+ if (error instanceof UrlNotAllowedError) throw new HttpError(400, error.message);
+ throw new HttpError(400, 'The link could not be resolved');
+ }
+ url.hash = '';
+ const fallback: LinkPreview = {
+ url: url.href,
+ title: null,
+ description: null,
+ image: null,
+ siteName: null,
+ };
+ try {
+ const result = await fetchPublic(
+ url,
+ signal,
+ 512 * 1024,
+ 'text/html, application/xhtml+xml',
+ true,
+ );
+ if (!result) return fallback;
+ const { response } = result;
+ const type = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
+ if (!response.ok || (type !== 'text/html' && type !== 'application/xhtml+xml')) return fallback;
+ const preview = parseLinkMetadata(await response.text(), result.url.href);
+ if (preview.image) preview.image = await fetchImage(preview.image, signal);
+ return preview;
+ } catch {
+ return fallback;
+ }
+}
diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.ts
index 396d083f..43c28c18 100644
--- a/apps/api/src/planner.ts
+++ b/apps/api/src/planner.ts
@@ -43,6 +43,7 @@ import { notificationPreferenceRoutes } from './modules/notification-preferences
import { userPreferenceRoutes } from './modules/user-preferences';
import { telegramRoutes } from './modules/telegram';
import { syncRoutes } from './modules/sync';
+import { linkPreviewRoutes } from './modules/link-previews';
// The planner API: projects and their columns, issue types, labels, AI agents,
// custom fields, issues, attachments, saved views, and actions. Mounted on the
@@ -123,5 +124,6 @@ export const planner = new Elysia({ name: 'planner' })
.use(userPreferenceRoutes)
.use(telegramRoutes)
.use(syncRoutes)
+ .use(linkPreviewRoutes)
.use(settingsRoutes)
.use(godRoutes);
diff --git a/apps/web/messages/ar/common.json b/apps/web/messages/ar/common.json
index 0b3a3542..74d5b661 100644
--- a/apps/web/messages/ar/common.json
+++ b/apps/web/messages/ar/common.json
@@ -177,7 +177,18 @@
"insertImage": "إدراج صورة",
"insertNamed": "إدراج {name}",
"noImages": "مفيش صور مرفقة لسه. ارفع صورة من لوحة المرفقات، أو ارميها على المحرر على طول.",
- "image": "صورة"
+ "image": "صورة",
+ "linkPreview": "Link preview",
+ "openPreviewLink": "Open {name} in a new tab",
+ "loadingPreview": "Loading preview…",
+ "previewUnavailable": "A preview is not available. Open the link to view this page.",
+ "internalPage": "ItsAPlan page",
+ "internalPreviewUnavailable": "This page is unavailable or you do not have access.",
+ "previewNoteCount": "{count, plural, one {# note} other {# notes}}",
+ "previewCustomField": "Custom field",
+ "previewAllWorkItems": "All work items",
+ "previewUpdated": "Updated {date}",
+ "previewOtherValues": "({count} more)"
},
"chart": {
"download": "احفظ الرسم البياني",
diff --git a/apps/web/messages/en/common.json b/apps/web/messages/en/common.json
index 7af47b23..1f511990 100644
--- a/apps/web/messages/en/common.json
+++ b/apps/web/messages/en/common.json
@@ -177,7 +177,18 @@
"insertImage": "Insert image",
"insertNamed": "Insert {name}",
"noImages": "No images attached yet. Upload one from the Attachments panel, or drop it straight onto the editor.",
- "image": "Image"
+ "image": "Image",
+ "linkPreview": "Link preview",
+ "openPreviewLink": "Open {name} in a new tab",
+ "loadingPreview": "Loading preview…",
+ "previewUnavailable": "A preview is not available. Open the link to view this page.",
+ "internalPage": "ItsAPlan page",
+ "internalPreviewUnavailable": "This page is unavailable or you do not have access.",
+ "previewNoteCount": "{count, plural, one {# note} other {# notes}}",
+ "previewCustomField": "Custom field",
+ "previewAllWorkItems": "All work items",
+ "previewUpdated": "Updated {date}",
+ "previewOtherValues": "({count} more)"
},
"chart": {
"download": "Save chart",
diff --git a/apps/web/messages/fr/common.json b/apps/web/messages/fr/common.json
index a4f14f6c..198b67d4 100644
--- a/apps/web/messages/fr/common.json
+++ b/apps/web/messages/fr/common.json
@@ -177,7 +177,18 @@
"insertImage": "Insérer une image",
"insertNamed": "Insérer {name}",
"noImages": "Aucune image jointe pour l'instant. Envoyez-en une depuis le panneau Pièces jointes, ou déposez-la directement dans l'éditeur.",
- "image": "Image"
+ "image": "Image",
+ "linkPreview": "Link preview",
+ "openPreviewLink": "Open {name} in a new tab",
+ "loadingPreview": "Loading preview…",
+ "previewUnavailable": "A preview is not available. Open the link to view this page.",
+ "internalPage": "ItsAPlan page",
+ "internalPreviewUnavailable": "This page is unavailable or you do not have access.",
+ "previewNoteCount": "{count, plural, one {# note} other {# notes}}",
+ "previewCustomField": "Custom field",
+ "previewAllWorkItems": "All work items",
+ "previewUpdated": "Updated {date}",
+ "previewOtherValues": "({count} more)"
},
"chart": {
"download": "Enregistrer le graphique",
diff --git a/apps/web/messages/id/common.json b/apps/web/messages/id/common.json
index de971497..bf685384 100644
--- a/apps/web/messages/id/common.json
+++ b/apps/web/messages/id/common.json
@@ -177,7 +177,18 @@
"insertImage": "Sisipkan gambar",
"insertNamed": "Sisipkan {name}",
"noImages": "Belum ada gambar yang dilampirkan. Unggah gambar dari panel Lampiran, atau seret langsung ke editor.",
- "image": "Gambar"
+ "image": "Gambar",
+ "linkPreview": "Pratinjau tautan",
+ "openPreviewLink": "Buka {name} di tab baru",
+ "loadingPreview": "Memuat pratinjau…",
+ "previewUnavailable": "Pratinjau tidak tersedia. Buka tautan untuk melihat halaman ini.",
+ "internalPage": "Halaman ItsAPlan",
+ "internalPreviewUnavailable": "Halaman ini tidak tersedia atau Anda tidak memiliki akses.",
+ "previewNoteCount": "{count, plural, one {# catatan} other {# catatan}}",
+ "previewCustomField": "Bidang kustom",
+ "previewAllWorkItems": "Semua item pekerjaan",
+ "previewUpdated": "Diperbarui {date}",
+ "previewOtherValues": "({count} lainnya)"
},
"chart": {
"download": "Simpan grafik",
diff --git a/apps/web/messages/pt-BR/common.json b/apps/web/messages/pt-BR/common.json
index b03488e2..88de1346 100644
--- a/apps/web/messages/pt-BR/common.json
+++ b/apps/web/messages/pt-BR/common.json
@@ -177,7 +177,18 @@
"insertImage": "Inserir imagem",
"insertNamed": "Inserir {name}",
"noImages": "Nenhuma imagem anexada ainda. Envie uma pelo painel de Anexos, ou solte-a direto no editor.",
- "image": "Imagem"
+ "image": "Imagem",
+ "linkPreview": "Link preview",
+ "openPreviewLink": "Open {name} in a new tab",
+ "loadingPreview": "Loading preview…",
+ "previewUnavailable": "A preview is not available. Open the link to view this page.",
+ "internalPage": "ItsAPlan page",
+ "internalPreviewUnavailable": "This page is unavailable or you do not have access.",
+ "previewNoteCount": "{count, plural, one {# note} other {# notes}}",
+ "previewCustomField": "Custom field",
+ "previewAllWorkItems": "All work items",
+ "previewUpdated": "Updated {date}",
+ "previewOtherValues": "({count} more)"
},
"chart": {
"download": "Salvar gráfico",
diff --git a/apps/web/messages/ru/common.json b/apps/web/messages/ru/common.json
index 0ff0fc54..3f94cef9 100644
--- a/apps/web/messages/ru/common.json
+++ b/apps/web/messages/ru/common.json
@@ -177,7 +177,18 @@
"insertImage": "Вставить изображение",
"insertNamed": "Вставить {name}",
"noImages": "Изображений пока нет. Загрузите из панели вложений или перетащите прямо в редактор.",
- "image": "Изображение"
+ "image": "Изображение",
+ "linkPreview": "Link preview",
+ "openPreviewLink": "Open {name} in a new tab",
+ "loadingPreview": "Loading preview…",
+ "previewUnavailable": "A preview is not available. Open the link to view this page.",
+ "internalPage": "ItsAPlan page",
+ "internalPreviewUnavailable": "This page is unavailable or you do not have access.",
+ "previewNoteCount": "{count, plural, one {# note} other {# notes}}",
+ "previewCustomField": "Custom field",
+ "previewAllWorkItems": "All work items",
+ "previewUpdated": "Updated {date}",
+ "previewOtherValues": "({count} more)"
},
"chart": {
"download": "Сохранить график",
diff --git a/apps/web/messages/uk/common.json b/apps/web/messages/uk/common.json
index 13becbe2..6a9b0bfb 100644
--- a/apps/web/messages/uk/common.json
+++ b/apps/web/messages/uk/common.json
@@ -177,7 +177,18 @@
"insertImage": "Вставити зображення",
"insertNamed": "Вставити {name}",
"noImages": "Зображень ще немає. Завантажте з панелі вкладень або перетягніть просто в редактор.",
- "image": "Зображення"
+ "image": "Зображення",
+ "linkPreview": "Link preview",
+ "openPreviewLink": "Open {name} in a new tab",
+ "loadingPreview": "Loading preview…",
+ "previewUnavailable": "A preview is not available. Open the link to view this page.",
+ "internalPage": "ItsAPlan page",
+ "internalPreviewUnavailable": "This page is unavailable or you do not have access.",
+ "previewNoteCount": "{count, plural, one {# note} other {# notes}}",
+ "previewCustomField": "Custom field",
+ "previewAllWorkItems": "All work items",
+ "previewUpdated": "Updated {date}",
+ "previewOtherValues": "({count} more)"
},
"chart": {
"download": "Зберегти графік",
diff --git a/apps/web/messages/zh-CN/common.json b/apps/web/messages/zh-CN/common.json
index 5b695e42..0660efc5 100644
--- a/apps/web/messages/zh-CN/common.json
+++ b/apps/web/messages/zh-CN/common.json
@@ -177,7 +177,18 @@
"insertImage": "插入图片",
"insertNamed": "插入 {name}",
"noImages": "暂无已附加图片。请从附件面板上传,或直接拖入编辑器。",
- "image": "图片"
+ "image": "图片",
+ "linkPreview": "Link preview",
+ "openPreviewLink": "Open {name} in a new tab",
+ "loadingPreview": "Loading preview…",
+ "previewUnavailable": "A preview is not available. Open the link to view this page.",
+ "internalPage": "ItsAPlan page",
+ "internalPreviewUnavailable": "This page is unavailable or you do not have access.",
+ "previewNoteCount": "{count, plural, one {# note} other {# notes}}",
+ "previewCustomField": "Custom field",
+ "previewAllWorkItems": "All work items",
+ "previewUpdated": "Updated {date}",
+ "previewOtherValues": "({count} more)"
},
"chart": {
"download": "保存图表",
diff --git a/apps/web/package.json b/apps/web/package.json
index 922f832b..44c712bf 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -9,7 +9,7 @@
"start": "next start -p 3001",
"lint": "eslint .",
"typecheck": "tsc --noEmit",
- "test": "bun test"
+ "test": "bun test --preload ./test/setup.ts"
},
"dependencies": {
"@base-ui/react": "^1.7.0",
diff --git a/apps/web/src/components/common/editor/EditorLinkPreview.module.css b/apps/web/src/components/common/editor/EditorLinkPreview.module.css
new file mode 100644
index 00000000..243313c0
--- /dev/null
+++ b/apps/web/src/components/common/editor/EditorLinkPreview.module.css
@@ -0,0 +1,42 @@
+.preview {
+ box-shadow:
+ 0 0 0 1px color-mix(in oklch, var(--foreground) 8%, transparent),
+ 0 2px 4px rgb(0 0 0 / 5%),
+ 0 12px 36px -8px rgb(0 0 0 / 20%);
+ transform-origin: var(--radix-popover-content-transform-origin);
+}
+
+.preview[data-state='open'] {
+ animation: preview-in 180ms cubic-bezier(0.2, 0, 0, 1);
+}
+
+.preview[data-state='closed'] {
+ animation: preview-out 120ms ease-in;
+}
+
+@keyframes preview-in {
+ from {
+ opacity: 0;
+ filter: blur(4px);
+ transform: scale(0.96);
+ }
+ to {
+ opacity: 1;
+ filter: blur(0);
+ transform: scale(1);
+ }
+}
+
+@keyframes preview-out {
+ to {
+ opacity: 0;
+ filter: blur(2px);
+ transform: scale(0.985);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .preview[data-state] {
+ animation: none;
+ }
+}
diff --git a/apps/web/src/components/common/editor/EditorLinkPreview.tsx b/apps/web/src/components/common/editor/EditorLinkPreview.tsx
new file mode 100644
index 00000000..0fe301f6
--- /dev/null
+++ b/apps/web/src/components/common/editor/EditorLinkPreview.tsx
@@ -0,0 +1,47 @@
+import { useRef } from 'react';
+import type { Editor } from '@tiptap/react';
+import { useTranslations } from 'next-intl';
+import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
+import { useEditorLinkPreview } from './useEditorLinkPreview';
+import { useLinkPreviewQuery } from './useLinkPreviewQuery';
+import EditorLinkPreviewCard from './EditorLinkPreviewCard';
+import styles from './EditorLinkPreview.module.css';
+
+export default function EditorLinkPreview({ editor }: { editor: Editor }) {
+ const t = useTranslations('common.editor');
+ const { anchor, candidateAnchor, open, close, keepOpen, leave } = useEditorLinkPreview(editor);
+ const virtualRef = useRef({ getBoundingClientRect: () => new DOMRect() });
+ virtualRef.current.getBoundingClientRect = () => anchor?.getBoundingClientRect() ?? new DOMRect();
+ useLinkPreviewQuery(candidateAnchor?.href);
+ const { data, isPending } = useLinkPreviewQuery(anchor?.href);
+ if (!anchor) return null;
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) close();
+ }}
+ >
+ <PopoverAnchor virtualRef={virtualRef} />
+ <PopoverContent
+ side="top"
+ align="start"
+ sideOffset={10}
+ collisionPadding={12}
+ aria-label={t('linkPreview')}
+ className={`${styles.preview} w-80 max-w-[calc(100vw-24px)] rounded-2xl border-0 bg-popover p-1 text-popover-foreground`}
+ onOpenAutoFocus={(event) => event.preventDefault()}
+ onCloseAutoFocus={(event) => event.preventDefault()}
+ onPointerEnter={keepOpen}
+ onPointerLeave={leave}
+ onFocusCapture={keepOpen}
+ onBlurCapture={(event) => {
+ if (!event.currentTarget.contains(event.relatedTarget)) leave();
+ }}
+ >
+ <EditorLinkPreviewCard url={anchor.href} preview={data} loading={isPending} />
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/components/common/editor/EditorLinkPreviewCard.tsx b/apps/web/src/components/common/editor/EditorLinkPreviewCard.tsx
new file mode 100644
index 00000000..e16ff215
--- /dev/null
+++ b/apps/web/src/components/common/editor/EditorLinkPreviewCard.tsx
@@ -0,0 +1,92 @@
+import {
+ ArrowUpRight,
+ CircleDot,
+ FileText,
+ FolderKanban,
+ Globe,
+ LayoutList,
+ LoaderCircle,
+ StickyNote,
+} from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import type { ResolvedLinkPreview } from './resolveLinkPreview';
+import EditorLinkPreviewImage from './EditorLinkPreviewImage';
+import EditorLinkPreviewDetails from './EditorLinkPreviewDetails';
+
+const previewIcons = {
+ project: FolderKanban,
+ issue: CircleDot,
+ document: FileText,
+ notes: StickyNote,
+ view: LayoutList,
+};
+
+export default function EditorLinkPreviewCard({
+ url,
+ preview,
+ loading,
+}: {
+ url: string;
+ preview: ResolvedLinkPreview | undefined;
+ loading: boolean;
+}) {
+ const t = useTranslations('common.editor');
+ const host = new URL(url).hostname.replace(/^www\./, '');
+ const internal = typeof window !== 'undefined' && new URL(url).origin === window.location.origin;
+ const Icon = preview?.kind ? previewIcons[preview.kind] : Globe;
+ const fallbackTitle = internal ? t('internalPage') : host;
+ return (
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ referrerPolicy="no-referrer"
+ className="block rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={t('openPreviewLink', { name: preview?.title || fallbackTitle })}
+ >
+ {preview?.image && <EditorLinkPreviewImage key={preview.image} src={preview.image} />}
+ <div className="space-y-2 p-3 text-start">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Icon className="size-3.5 shrink-0" aria-hidden="true" />
+ <span className="min-w-0 truncate" dir="auto">
+ {preview?.siteName || fallbackTitle}
+ </span>
+ <ArrowUpRight className="ms-auto size-3.5 shrink-0" aria-hidden="true" />
+ </div>
+ {loading ? (
+ <div className="space-y-2 py-1" role="status">
+ <div className="h-3 w-4/5 animate-pulse rounded bg-muted motion-reduce:animate-none" />
+ <div className="h-3 w-3/5 animate-pulse rounded bg-muted motion-reduce:animate-none" />
+ <span className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <LoaderCircle
+ className="size-3 animate-spin motion-reduce:animate-none"
+ aria-hidden="true"
+ />
+ {t('loadingPreview')}
+ </span>
+ </div>
+ ) : (
+ <>
+ <p className="line-clamp-2 text-sm font-medium text-pretty" dir="auto">
+ {preview?.title || fallbackTitle}
+ </p>
+ {preview?.description && (
+ <p className="line-clamp-3 text-xs text-pretty text-muted-foreground" dir="auto">
+ {preview.description}
+ </p>
+ )}
+ {!preview?.title && !preview?.description && (
+ <p className="text-xs text-pretty text-muted-foreground">
+ {internal ? t('internalPreviewUnavailable') : t('previewUnavailable')}
+ </p>
+ )}
+ {preview?.kind && <EditorLinkPreviewDetails preview={preview} />}
+ </>
+ )}
+ <p className="truncate pt-1 text-xs text-muted-foreground" dir="ltr" title={url}>
+ {url}
+ </p>
+ </div>
+ </a>
+ );
+}
diff --git a/apps/web/src/components/common/editor/EditorLinkPreviewDetails.tsx b/apps/web/src/components/common/editor/EditorLinkPreviewDetails.tsx
new file mode 100644
index 00000000..224b4fb7
--- /dev/null
+++ b/apps/web/src/components/common/editor/EditorLinkPreviewDetails.tsx
@@ -0,0 +1,47 @@
+import { useFormatter, useTranslations } from 'next-intl';
+import { colorDot } from '@/components/common/fields/colorDot';
+import { byKey } from '@/utils/messageKey';
+import type { ResolvedLinkPreview } from './resolveLinkPreview';
+
+export default function EditorLinkPreviewDetails({ preview }: { preview: ResolvedLinkPreview }) {
+ const t = useTranslations('common.editor');
+ const filters = useTranslations('filters');
+ const display = useTranslations('display');
+ const format = useFormatter();
+ const updated = preview.updatedAt ? new Date(preview.updatedAt) : null;
+ return (
+ <div className="space-y-1.5 text-xs text-muted-foreground">
+ {preview.status && (
+ <div className="flex items-center gap-1.5">
+ {colorDot(preview.status.color)}
+ <span dir="auto">{preview.status.name}</span>
+ </div>
+ )}
+ {preview.noteCount !== undefined && (
+ <p>{t('previewNoteCount', { count: preview.noteCount })}</p>
+ )}
+ {preview.layout && <p>{byKey(display)(`layouts.${preview.layout}`)}</p>}
+ {preview.filters?.map((filter, index) => (
+ <p key={index} className="line-clamp-2" dir="auto">
+ {filter.label ||
+ (filter.field === 'custom'
+ ? t('previewCustomField')
+ : byKey(filters)(`fields.${filter.field}`))}{' '}
+ {byKey(filters)(`operators.${filter.op}`)} {filter.values.join(', ')}
+ {filter.remainingValues > 0 && (
+ <>
+ {' '}
+ {filter.values.length > 0
+ ? t('previewOtherValues', { count: filter.remainingValues })
+ : filters('selected', { count: filter.remainingValues })}
+ </>
+ )}
+ </p>
+ ))}
+ {preview.filters?.length === 0 && <p>{t('previewAllWorkItems')}</p>}
+ {updated && Number.isFinite(updated.getTime()) && (
+ <p>{t('previewUpdated', { date: format.dateTime(updated, { dateStyle: 'medium' }) })}</p>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/common/editor/EditorLinkPreviewImage.tsx b/apps/web/src/components/common/editor/EditorLinkPreviewImage.tsx
new file mode 100644
index 00000000..0e544c30
--- /dev/null
+++ b/apps/web/src/components/common/editor/EditorLinkPreviewImage.tsx
@@ -0,0 +1,17 @@
+import { useState } from 'react';
+
+export default function EditorLinkPreviewImage({ src }: { src: string }) {
+ const [failed, setFailed] = useState(false);
+ if (failed) return null;
+ return (
+ // Preview images are bounded raster data URLs returned by the API.
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={src}
+ alt=""
+ referrerPolicy="no-referrer"
+ onError={() => setFailed(true)}
+ className="aspect-[1.91] w-full rounded-xl bg-muted object-cover outline -outline-offset-1 outline-black/10 dark:outline-white/10"
+ />
+ );
+}
diff --git a/apps/web/src/components/common/editor/MarkdownEditor.test.ts b/apps/web/src/components/common/editor/MarkdownEditor.test.ts
index 64ababca..0e20cca8 100644
--- a/apps/web/src/components/common/editor/MarkdownEditor.test.ts
+++ b/apps/web/src/components/common/editor/MarkdownEditor.test.ts
@@ -7,15 +7,23 @@ import { Markdown } from 'tiptap-markdown';
import { JSDOM } from 'jsdom';
import { editorStarterKitOptions } from './MarkdownEditor';
import { openLinkOnModifierClick } from './modifierClickLink';
+import { createLinkKeyboardHandlers } from './linkKeyboardHandlers';
let dom: JSDOM;
let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;
beforeEach(() => {
originalGlobalDescriptors = new Map(
- ['window', 'document', 'navigator', 'DOMParser', 'Node', 'Element', 'HTMLElement'].map(
- (name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)],
- ),
+ [
+ 'window',
+ 'document',
+ 'navigator',
+ 'DOMParser',
+ 'Node',
+ 'Element',
+ 'HTMLElement',
+ 'HTMLAnchorElement',
+ ].map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
);
dom = new JSDOM('<!doctype html><div></div>');
Object.defineProperties(globalThis, {
@@ -26,6 +34,7 @@ beforeEach(() => {
Node: { configurable: true, value: dom.window.Node },
Element: { configurable: true, value: dom.window.Element },
HTMLElement: { configurable: true, value: dom.window.HTMLElement },
+ HTMLAnchorElement: { configurable: true, value: dom.window.HTMLAnchorElement },
});
});
@@ -38,6 +47,43 @@ afterEach(() => {
});
describe('MarkdownEditor extensions', () => {
+ it('does not edit the document when Enter activates a focused link', () => {
+ const opened: unknown[] = [];
+ dom.window.open = (...args: Parameters<typeof window.open>) => {
+ opened.push(args);
+ return null;
+ };
+ const editor = new Editor({
+ element: dom.window.document.querySelector('div')!,
+ extensions: [
+ StarterKit.configure(editorStarterKitOptions),
+ Link.configure({ openOnClick: false, HTMLAttributes: { tabindex: '0' } }),
+ ],
+ content: '<p><a href="https://example.com/docs">Docs</a> content</p>',
+ editorProps: {
+ handleDOMEvents: createLinkKeyboardHandlers(),
+ handleScrollToSelection: () => true,
+ },
+ });
+ const before = editor.getHTML();
+ const link = editor.view.dom.querySelector('a')!;
+ link.focus();
+ editor.view.dom.focus();
+ editor.view.dom.dispatchEvent(
+ new dom.window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }),
+ );
+ assert.equal(editor.getHTML(), before);
+ assert.deepEqual(opened, [['https://example.com/docs', '_blank', 'noopener,noreferrer']]);
+ link.focus();
+ link.dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true }));
+ editor.view.dom.focus();
+ editor.view.dom.dispatchEvent(
+ new dom.window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }),
+ );
+ assert.notEqual(editor.getHTML(), before);
+ assert.equal(opened.length, 1);
+ editor.destroy();
+ });
it('registers the configured link extension once', () => {
const editor = new Editor({
extensions: [
diff --git a/apps/web/src/components/common/editor/MarkdownEditor.tsx b/apps/web/src/components/common/editor/MarkdownEditor.tsx
index e2e3dd8b..450adcd3 100644
--- a/apps/web/src/components/common/editor/MarkdownEditor.tsx
+++ b/apps/web/src/components/common/editor/MarkdownEditor.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { useEditor, EditorContent, type Editor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
@@ -15,9 +15,11 @@ import { MarkdownTable } from './tiptap-table';
import { Video } from './tiptap-video';
import { attachmentHtml, type Embeddable } from './attachmentEmbed';
import { openLinkOnModifierClick } from './modifierClickLink';
+import { createLinkKeyboardHandlers } from './linkKeyboardHandlers';
import EditorImagePicker from './EditorImagePicker';
import EditorSelectionMenu from './EditorSelectionMenu';
import EditorTableMenu from './EditorTableMenu';
+import EditorLinkPreview from './EditorLinkPreview';
import { useMentionCandidates } from '@/hooks/useMentionCandidates';
import { useTranslations } from 'next-intl';
@@ -65,6 +67,7 @@ export default function MarkdownEditor({
}) {
const t = useTranslations('common.editor');
const editorRef = useRef<Editor | null>(null);
+ const linkKeyboardHandlers = useMemo(createLinkKeyboardHandlers, []);
// Held in a ref because the extensions are built once: the "@" menu reads the
// roster through it, so a list that arrives later is still offered.
const mentionCandidates = useMentionCandidates();
@@ -101,7 +104,11 @@ export default function MarkdownEditor({
StarterKit.configure(editorStarterKitOptions),
CodeBlockLowlight.configure({ lowlight }),
Placeholder.configure({ placeholder }),
- Link.configure({ openOnClick: false, autolink: true }),
+ Link.configure({
+ openOnClick: false,
+ autolink: true,
+ HTMLAttributes: { class: 'cursor-pointer', tabindex: '0' },
+ }),
// Renders ![](url) markdown inline.
ResizableImage,
// Renders an @username in the text as a mention chip, and offers the project's
@@ -138,6 +145,7 @@ export default function MarkdownEditor({
handleClick(view, _pos, event) {
return openLinkOnModifierClick(event, view.dom);
},
+ handleDOMEvents: linkKeyboardHandlers,
// Files dropped from the OS are uploaded, then inserted at the drop
// position. Internal moves and attachment-card drags (which carry
// text/html, not files) fall through to tiptap's default handling.
@@ -188,6 +196,7 @@ export default function MarkdownEditor({
{/* Grows with the text rather than being pinned to the container's height,
so a container that scrolls measures the overflow and shows a bar. */}
<EditorContent editor={editor} className="flex min-h-full flex-col" />
+ <EditorLinkPreview editor={editor} />
{imageAttachments && (
<EditorImagePicker
open={imagePickerOpen}
diff --git a/apps/web/src/components/common/editor/internalLinkTarget.test.ts b/apps/web/src/components/common/editor/internalLinkTarget.test.ts
new file mode 100644
index 00000000..c42bc6e6
--- /dev/null
+++ b/apps/web/src/components/common/editor/internalLinkTarget.test.ts
@@ -0,0 +1,45 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { internalLinkTarget } from './internalLinkTarget';
+import { previewExcerpt } from './previewExcerpt';
+
+describe('internal link targets', () => {
+ it('recognizes exact routes, encoded keys, aliases and query/hash decorations', () => {
+ const examples = [
+ ['/project/SYR', { kind: 'project', projectKey: 'SYR' }],
+ ['/project/S%59R/issue/13?mode=full#details', { kind: 'issue', projectKey: 'SYR', id: 13 }],
+ ['/issue/732', { kind: 'issueId', id: 732 }],
+ ['/SYR-13', { kind: 'issue', projectKey: 'SYR', id: 13 }],
+ ['/project/SYR/notes/18/', { kind: 'notes', projectKey: 'SYR', id: 18 }],
+ ['/project/SYR/docs/9', { kind: 'document', projectKey: 'SYR', id: 9 }],
+ ['/project/SYR/view/41', { kind: 'view', projectKey: 'SYR', id: 41 }],
+ ] as const;
+ for (const [path, expected] of examples)
+ assert.deepEqual(internalLinkTarget(new URL(path, 'https://planner.test')), expected);
+ });
+
+ it('rejects unsupported, malformed and unsafe numeric routes', () => {
+ for (const path of [
+ '/account/profile',
+ '/project/SYR/settings/general',
+ '/project/SYR/issue/0',
+ '/project/SYR/issue/-2',
+ '/issue/1.5',
+ '/issue/9007199254740992',
+ '/project/SYR%2Fother/notes/1',
+ '/project/%E0%A4%A',
+ '/project/SYR/issue/1/extra',
+ ]) {
+ assert.equal(internalLinkTarget(new URL(path, 'https://planner.test')), null, path);
+ }
+ });
+
+ it('extracts bounded plain text without markdown or HTML payloads', () => {
+ assert.equal(
+ previewExcerpt('# Plan\n\nA **clear** [task](https://example.com).\n\n- First\n- Second'),
+ 'Plan A clear task. First Second',
+ );
+ assert.equal(previewExcerpt('<script>alert(1)</script>\n\nSafe'), 'Safe');
+ assert.equal(previewExcerpt('x'.repeat(500)).length, 281);
+ });
+});
diff --git a/apps/web/src/components/common/editor/internalLinkTarget.ts b/apps/web/src/components/common/editor/internalLinkTarget.ts
new file mode 100644
index 00000000..bc4cc87b
--- /dev/null
+++ b/apps/web/src/components/common/editor/internalLinkTarget.ts
@@ -0,0 +1,47 @@
+export type InternalLinkTarget =
+ | { kind: 'project'; projectKey: string }
+ | { kind: 'issueId'; id: number }
+ | { kind: 'issue' | 'notes' | 'document' | 'view'; projectKey: string; id: number };
+
+function positiveId(value: string | undefined) {
+ if (!value || !/^[1-9]\d*$/.test(value)) return null;
+ const id = Number(value);
+ return Number.isSafeInteger(id) ? id : null;
+}
+
+export function internalLinkTarget(url: URL): InternalLinkTarget | null {
+ let parts: string[];
+ try {
+ parts = url.pathname.replace(/\/$/, '').split('/').slice(1).map(decodeURIComponent);
+ } catch {
+ return null;
+ }
+ if (parts.some((part) => /[/\\?#\p{Cc}]/u.test(part))) return null;
+ if (parts.length === 1) {
+ const match = /^(.+)-(\d+)$/.exec(parts[0]!);
+ const id = positiveId(match?.[2]);
+ return match && id ? { kind: 'issue', projectKey: match[1]!, id } : null;
+ }
+ if (parts[0] === 'issue' && parts.length === 2) {
+ const id = positiveId(parts[1]);
+ return id ? { kind: 'issueId', id } : null;
+ }
+ if (parts[0] !== 'project' || !parts[1]) return null;
+ const projectKey = parts[1];
+ if (parts.length === 2) return { kind: 'project', projectKey };
+ if (parts.length !== 4) return null;
+ const id = positiveId(parts[3]);
+ if (!id) return null;
+ switch (parts[2]) {
+ case 'issue':
+ return { kind: 'issue', projectKey, id };
+ case 'notes':
+ return { kind: 'notes', projectKey, id };
+ case 'docs':
+ return { kind: 'document', projectKey, id };
+ case 'view':
+ return { kind: 'view', projectKey, id };
+ default:
+ return null;
+ }
+}
diff --git a/apps/web/src/components/common/editor/linkKeyboardHandlers.ts b/apps/web/src/components/common/editor/linkKeyboardHandlers.ts
new file mode 100644
index 00000000..3975359e
--- /dev/null
+++ b/apps/web/src/components/common/editor/linkKeyboardHandlers.ts
@@ -0,0 +1,43 @@
+import type { EditorProps } from '@tiptap/pm/view';
+import { openLinkOnEnter } from './modifierClickLink';
+
+export function createLinkKeyboardHandlers(): EditorProps['handleDOMEvents'] {
+ let focusedLink: HTMLAnchorElement | null = null;
+ let pointerFocus = false;
+
+ return {
+ focusin(view, event) {
+ const target = event.target;
+ if (target instanceof HTMLAnchorElement && !pointerFocus) focusedLink = target;
+ else if (target !== view.dom) focusedLink = null;
+ return false;
+ },
+ focusout(view, event) {
+ if (event.relatedTarget !== view.dom) {
+ focusedLink = null;
+ pointerFocus = false;
+ }
+ return false;
+ },
+ pointerdown() {
+ focusedLink = null;
+ pointerFocus = true;
+ return false;
+ },
+ pointerup() {
+ pointerFocus = false;
+ return false;
+ },
+ pointercancel() {
+ pointerFocus = false;
+ return false;
+ },
+ keydown(view, event) {
+ // Chromium can focus the editing host before delivering Enter to a focused link.
+ const link = focusedLink;
+ focusedLink = null;
+ pointerFocus = false;
+ return openLinkOnEnter(event, view.dom, link);
+ },
+ };
+}
diff --git a/apps/web/src/components/common/editor/modifierClickLink.ts b/apps/web/src/components/common/editor/modifierClickLink.ts
index a1979357..0aa25992 100644
--- a/apps/web/src/components/common/editor/modifierClickLink.ts
+++ b/apps/web/src/components/common/editor/modifierClickLink.ts
@@ -2,7 +2,25 @@ const OPENABLE_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:']);
export function openLinkOnModifierClick(event: MouseEvent, root: HTMLElement): boolean {
if (event.button !== 0 || (!event.metaKey && !event.ctrlKey)) return false;
- const target = event.target as Element | null;
+ return openLink(event, root);
+}
+
+export function openLinkOnEnter(
+ event: KeyboardEvent,
+ root: HTMLElement,
+ focusedLink: HTMLAnchorElement | null = null,
+): boolean {
+ if (event.key !== 'Enter' || event.target !== document.activeElement) return false;
+ if (event.target === root && focusedLink) return openLink(event, root, focusedLink);
+ if (!(event.target instanceof Element) || event.target.tagName !== 'A') return false;
+ return openLink(event, root);
+}
+
+function openLink(
+ event: MouseEvent | KeyboardEvent,
+ root: HTMLElement,
+ target = event.target as Element | null,
+): boolean {
if (!target || typeof target.closest !== 'function') return false;
const link = target.closest<HTMLAnchorElement>('a[href]');
if (!link || !root.contains(link)) return false;
diff --git a/apps/web/src/components/common/editor/previewExcerpt.ts b/apps/web/src/components/common/editor/previewExcerpt.ts
new file mode 100644
index 00000000..ff74b22a
--- /dev/null
+++ b/apps/web/src/components/common/editor/previewExcerpt.ts
@@ -0,0 +1,23 @@
+import { marked, type Token } from 'marked';
+
+function tokenText(token: Token): string {
+ if (token.type === 'html') return '';
+ if ('tokens' in token && token.tokens) return token.tokens.map(tokenText).join('');
+ if (token.type === 'list')
+ return token.items.flatMap((item: { tokens: Token[] }) => item.tokens.map(tokenText)).join(' ');
+ if (token.type === 'table')
+ return [...token.header, ...token.rows.flat()]
+ .map((cell) => cell.tokens.map(tokenText).join(' '))
+ .join(' ');
+ return 'text' in token && typeof token.text === 'string' ? token.text : '';
+}
+
+export function previewExcerpt(markdown: string, limit = 280): string {
+ const text = marked
+ .lexer(markdown.slice(0, 12_000))
+ .map(tokenText)
+ .join(' ')
+ .replace(/\s+/g, ' ')
+ .trim();
+ return text.length > limit ? `${text.slice(0, limit).trimEnd()}…` : text;
+}
diff --git a/apps/web/src/components/common/editor/previewableLink.ts b/apps/web/src/components/common/editor/previewableLink.ts
new file mode 100644
index 00000000..e483090f
--- /dev/null
+++ b/apps/web/src/components/common/editor/previewableLink.ts
@@ -0,0 +1,12 @@
+export function previewableLink(target: EventTarget | null, root: HTMLElement) {
+ if (!(target instanceof Element)) return null;
+ const link = target.closest<HTMLAnchorElement>('a[href]');
+ if (!link || !root.contains(link) || link.hasAttribute('download')) return null;
+ try {
+ const url = new URL(link.href);
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return null;
+ return link;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/web/src/components/common/editor/resolveLinkPreview.test.ts b/apps/web/src/components/common/editor/resolveLinkPreview.test.ts
new file mode 100644
index 00000000..83a47842
--- /dev/null
+++ b/apps/web/src/components/common/editor/resolveLinkPreview.test.ts
@@ -0,0 +1,163 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { resolveLinkPreview } from './resolveLinkPreview';
+
+const origin = 'https://planner.test';
+const scaffold = {
+ project: { id: 1, key: 'SYR', name: 'Research', description: '**Project** overview' },
+ columns: [{ id: 4, name: 'In progress', color: '#999999' }],
+ issueTypes: [],
+ labels: [],
+ assignees: [],
+ customFields: [],
+};
+let fetchOriginal: typeof fetch;
+let calls: { url: URL; signal: AbortSignal | null | undefined }[];
+let responses: Map<string, { status?: number; body: unknown }>;
+
+beforeEach(() => {
+ fetchOriginal = globalThis.fetch;
+ calls = [];
+ responses = new Map([['/projects/SYR', { body: scaffold }]]);
+ globalThis.fetch = (async (input, init) => {
+ const url = new URL(String(input));
+ calls.push({ url, signal: init?.signal });
+ const response = responses.get(url.pathname);
+ return Response.json(response?.body ?? { error: 'Not found' }, {
+ status: response?.status ?? (response ? 200 : 404),
+ });
+ }) as typeof fetch;
+});
+afterEach(() => {
+ globalThis.fetch = fetchOriginal;
+});
+
+describe('authorized internal link previews', () => {
+ it('reads project metadata through the authenticated endpoint', async () => {
+ const signal = new AbortController().signal;
+ const result = await resolveLinkPreview('/project/SYR?view=all#top', origin, signal);
+ assert.equal(result.title, 'Research');
+ assert.equal(result.description, 'Project overview');
+ assert.equal(result.kind, 'project');
+ assert.deepEqual(
+ calls.map((call) => call.url.pathname),
+ ['/projects/SYR'],
+ );
+ assert.equal(calls[0]!.signal, signal);
+ });
+
+ it('uses project sequence numbers and keeps legacy database IDs separate', async () => {
+ const issue = {
+ identifier: 'SYR-13',
+ title: 'Check evidence',
+ description: 'Read **sources**',
+ columnId: 4,
+ updatedAt: '2026-09-09T12:00:00Z',
+ };
+ responses.set('/projects/SYR/issues/13', { body: issue });
+ responses.set('/issues/732', { body: issue });
+ for (const path of ['/project/SYR/issue/13', '/SYR-13', '/issue/732']) {
+ const result = await resolveLinkPreview(path, origin, new AbortController().signal);
+ assert.equal(result.title, 'SYR-13 · Check evidence');
+ assert.equal(result.status?.name, 'In progress');
+ assert.equal(result.image, null);
+ }
+ assert.equal(calls.filter((call) => call.url.pathname === '/projects/SYR/issues/13').length, 2);
+ assert.equal(calls.filter((call) => call.url.pathname === '/issues/732').length, 1);
+ });
+
+ it('reads document and bounded note board overviews', async () => {
+ responses.set('/projects/SYR/documents/9', {
+ body: { title: 'Plan', content: '# Outline\n\nNext step', updatedAt: '2026-09-09' },
+ });
+ responses.set('/projects/SYR/note-boards/18', {
+ body: {
+ name: 'Options',
+ canvas: {
+ nodes: Array.from({ length: 9 }, (_, id) => ({
+ data: { title: `Note ${id}`, body: 'Some detail' },
+ })),
+ },
+ updatedAt: '2026-09-09',
+ },
+ });
+ const document = await resolveLinkPreview(
+ '/project/SYR/docs/9',
+ origin,
+ new AbortController().signal,
+ );
+ assert.equal(document.description, 'Outline Next step');
+ const notes = await resolveLinkPreview(
+ '/project/SYR/notes/18',
+ origin,
+ new AbortController().signal,
+ );
+ assert.equal(notes.title, 'Options');
+ assert.equal(notes.noteCount, 9);
+ assert.match(notes.description!, /Note 2/);
+ assert.doesNotMatch(notes.description!, /Note 3/);
+ });
+
+ it('resolves saved view names, layout and named filters', async () => {
+ responses.set('/projects/SYR/views', {
+ body: [
+ {
+ id: 41,
+ name: 'Compare eight',
+ display: { layout: 'table' },
+ filters: { conditions: [{ field: 'status', op: 'is', values: [4] }] },
+ },
+ ],
+ });
+ const result = await resolveLinkPreview(
+ '/project/SYR/view/41',
+ origin,
+ new AbortController().signal,
+ );
+ assert.equal(result.title, 'Compare eight');
+ assert.equal(result.layout, 'table');
+ assert.deepEqual(result.filters?.[0]?.values, ['In progress']);
+ await assert.rejects(
+ resolveLinkPreview('/project/SYR/view/43', origin, new AbortController().signal),
+ { status: 404 },
+ );
+ });
+
+ it('never falls back to public metadata for private, missing or unsupported internal pages', async () => {
+ responses.set('/projects/SYR/note-boards/18', { status: 403, body: { error: 'Forbidden' } });
+ await assert.rejects(
+ resolveLinkPreview('/project/SYR/notes/18', origin, new AbortController().signal),
+ { status: 403 },
+ );
+ await assert.rejects(
+ resolveLinkPreview('/project/MISSING', origin, new AbortController().signal),
+ { status: 404 },
+ );
+ const before = calls.length;
+ for (const path of ['/account/profile', '/project/SYR/issue/0', '/project/%E0%A4%A']) {
+ const result = await resolveLinkPreview(path, origin, new AbortController().signal);
+ assert.equal(result.title, null);
+ }
+ assert.equal(calls.length, before);
+ assert.ok(calls.every((call) => call.url.pathname !== '/link-previews'));
+ });
+
+ it('keeps foreign origins external even when their path matches a private route', async () => {
+ responses.set('/link-previews', {
+ body: { title: 'External', description: null, image: null, siteName: null },
+ });
+ const external = 'https://planner.test.example.com/project/SYR';
+ await resolveLinkPreview(external, origin, new AbortController().signal);
+ assert.equal(calls[0]!.url.pathname, '/link-previews');
+ assert.equal(calls[0]!.url.searchParams.get('url'), external);
+ assert.throws(
+ () =>
+ resolveLinkPreview(
+ 'https://user:[email protected]/project/SYR',
+ origin,
+ new AbortController().signal,
+ ),
+ { status: 400 },
+ );
+ });
+});
diff --git a/apps/web/src/components/common/editor/resolveLinkPreview.ts b/apps/web/src/components/common/editor/resolveLinkPreview.ts
new file mode 100644
index 00000000..72cd14e9
--- /dev/null
+++ b/apps/web/src/components/common/editor/resolveLinkPreview.ts
@@ -0,0 +1,117 @@
+import { ApiError } from '@/lib/api/core/client';
+import { getLinkPreview, type LinkPreview } from '@/lib/api/endpoints/link-previews';
+import { getProject } from '@/lib/api/endpoints/projects';
+import { getIssue, getIssueBySeq } from '@/lib/api/endpoints/issues';
+import { getNoteBoard } from '@/lib/api/endpoints/noteBoards';
+import { getDocument } from '@/lib/api/endpoints/documents';
+import { listViews } from '@/lib/api/endpoints/views';
+import { normalizeSavedDisplay } from '@/utils/viewSettings';
+import { internalLinkTarget } from './internalLinkTarget';
+import { previewExcerpt } from './previewExcerpt';
+import { viewPreviewFilters, type PreviewFilter } from './viewPreviewFilters';
+
+export type ResolvedLinkPreview = LinkPreview & {
+ kind?: 'project' | 'issue' | 'notes' | 'document' | 'view';
+ status?: { name: string; color: string };
+ updatedAt?: string;
+ noteCount?: number;
+ layout?: string;
+ filters?: PreviewFilter[];
+};
+
+async function resolveInternalLinkPreview(
+ url: URL,
+ signal: AbortSignal,
+): Promise<ResolvedLinkPreview> {
+ const empty: LinkPreview = {
+ url: url.href,
+ title: null,
+ description: null,
+ image: null,
+ siteName: null,
+ };
+ const target = internalLinkTarget(url);
+ if (!target) return empty;
+ if (target.kind === 'issue' || target.kind === 'issueId') {
+ const issue =
+ target.kind === 'issue'
+ ? await getIssueBySeq(target.projectKey, target.id, signal)
+ : await getIssue(target.id, signal);
+ const projectKey = issue.identifier.replace(/-\d+$/, '');
+ const project = await getProject(projectKey, signal);
+ return {
+ ...empty,
+ kind: 'issue',
+ title: `${issue.identifier} · ${issue.title}`,
+ description: previewExcerpt(issue.description),
+ siteName: project.project.name,
+ status: project.columns.find((column) => column.id === issue.columnId),
+ updatedAt: issue.updatedAt,
+ };
+ }
+ const project = await getProject(target.projectKey, signal);
+ const base = { ...empty, siteName: project.project.name };
+ switch (target.kind) {
+ case 'project':
+ return {
+ ...base,
+ kind: 'project',
+ title: project.project.name,
+ description: previewExcerpt(project.project.description),
+ siteName: project.project.key,
+ };
+ case 'document': {
+ const document = await getDocument(target.projectKey, target.id, signal);
+ return {
+ ...base,
+ kind: 'document',
+ title: document.title,
+ description: previewExcerpt(document.content),
+ updatedAt: document.updatedAt,
+ };
+ }
+ case 'notes': {
+ const board = await getNoteBoard(target.projectKey, target.id, signal);
+ const notes = Array.isArray(board.canvas?.nodes) ? board.canvas.nodes : [];
+ const summary = notes
+ .slice(0, 3)
+ .map((node) =>
+ [node.data?.title, node.data?.body].filter((part) => typeof part === 'string').join(' '),
+ )
+ .join('\n');
+ return {
+ ...base,
+ kind: 'notes',
+ title: board.name,
+ description: previewExcerpt(summary),
+ noteCount: notes.length,
+ updatedAt: board.updatedAt,
+ };
+ }
+ case 'view': {
+ const views = await listViews(target.projectKey, signal);
+ const view = views.find((item) => item.id === target.id);
+ if (!view) throw new ApiError(404, 'View not found');
+ return {
+ ...base,
+ kind: 'view',
+ title: view.name,
+ description: null,
+ layout: normalizeSavedDisplay(view.display).layout,
+ filters: viewPreviewFilters(view, project),
+ };
+ }
+ }
+}
+
+export function resolveLinkPreview(
+ url: string,
+ origin: string,
+ signal: AbortSignal,
+): Promise<ResolvedLinkPreview> {
+ const target = new URL(url, origin);
+ if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password)
+ throw new ApiError(400, 'Invalid preview URL');
+ if (target.origin === origin) return resolveInternalLinkPreview(target, signal);
+ return getLinkPreview(target.href, signal);
+}
diff --git a/apps/web/src/components/common/editor/useEditorLinkPreview.test.ts b/apps/web/src/components/common/editor/useEditorLinkPreview.test.ts
new file mode 100644
index 00000000..06958a4c
--- /dev/null
+++ b/apps/web/src/components/common/editor/useEditorLinkPreview.test.ts
@@ -0,0 +1,151 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import type { Editor } from '@tiptap/react';
+import { JSDOM } from 'jsdom';
+import { useEditorLinkPreview } from './useEditorLinkPreview';
+import { previewableLink } from './previewableLink';
+
+let dom: JSDOM;
+let reactRoot: Root;
+let editorRoot: HTMLElement;
+let state: ReturnType<typeof useEditorLinkPreview>;
+let originals: Map<string, PropertyDescriptor | undefined>;
+const wait = (ms: number) => act(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
+
+function Harness({ editor }: { editor: Editor }) {
+ state = useEditorLinkPreview(editor);
+ return null;
+}
+
+beforeEach(async () => {
+ dom = new JSDOM('<div id="react"></div><div id="editor"></div>', { url: 'https://planner.test' });
+ const globals = {
+ window: dom.window,
+ document: dom.window.document,
+ Element: dom.window.Element,
+ Node: dom.window.Node,
+ PointerEvent: dom.window.MouseEvent,
+ IS_REACT_ACT_ENVIRONMENT: true,
+ };
+ originals = new Map(
+ Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
+ );
+ for (const [key, value] of Object.entries(globals))
+ Object.defineProperty(globalThis, key, { configurable: true, value });
+ editorRoot = dom.window.document.getElementById('editor')!;
+ editorRoot.innerHTML =
+ '<a href="https://example.com/a">A</a><a href="https://example.com/b">B</a>';
+ reactRoot = createRoot(dom.window.document.getElementById('react')!);
+ await act(() =>
+ reactRoot.render(createElement(Harness, { editor: { view: { dom: editorRoot } } as Editor })),
+ );
+});
+
+afterEach(async () => {
+ await act(() => reactRoot.unmount());
+ dom.window.close();
+ for (const [key, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+});
+
+async function point(link: Element, type: 'pointerover' | 'pointerout') {
+ await act(() => {
+ link.dispatchEvent(new dom.window.MouseEvent(type, { bubbles: true }));
+ });
+}
+
+describe('editor link preview interaction', () => {
+ it('keeps the outgoing anchor while every new link waits its full hover delay', async () => {
+ const [first, second] = editorRoot.querySelectorAll('a');
+ await point(first!, 'pointerover');
+ await wait(670);
+ assert.equal(state.open, true);
+ await point(first!, 'pointerout');
+ await point(second!, 'pointerover');
+ assert.equal(state.anchor, first);
+ assert.equal(state.candidateAnchor, second);
+ assert.equal(state.open, false);
+ await wait(500);
+ assert.equal(state.anchor, first);
+ assert.equal(state.open, false);
+ const third = dom.window.document.createElement('a');
+ third.href = 'https://example.com/c';
+ editorRoot.append(third);
+ await point(second!, 'pointerout');
+ await point(third, 'pointerover');
+ await wait(500);
+ assert.equal(state.anchor, first);
+ assert.equal(state.candidateAnchor, third);
+ assert.equal(state.open, false);
+ await wait(170);
+ assert.equal(state.anchor, third);
+ assert.equal(state.open, true);
+ await point(third, 'pointerout');
+ await wait(140);
+ assert.equal(state.open, false);
+ });
+ it('waits for deliberate hover and can reopen after leaving before the delay', async () => {
+ const link = editorRoot.querySelector('a')!;
+ await point(link, 'pointerover');
+ assert.equal(state.candidateAnchor, link);
+ assert.equal(state.anchor, null);
+ assert.equal(state.open, false);
+ await point(link, 'pointerout');
+ await wait(140);
+ await point(link, 'pointerover');
+ await wait(670);
+ assert.equal(state.open, true);
+ let parentEscapes = 0;
+ const parentEscape = () => {
+ parentEscapes += 1;
+ };
+ dom.window.addEventListener('keydown', parentEscape);
+ await act(() => {
+ dom.window.document.dispatchEvent(
+ new dom.window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
+ );
+ });
+ assert.equal(state.open, false);
+ assert.equal(parentEscapes, 0);
+ dom.window.removeEventListener('keydown', parentEscape);
+ await wait(180);
+ assert.equal(state.anchor, null);
+ });
+
+ it('keeps the preview open when the pointer enters the card and cancels stale openings', async () => {
+ const [first, second] = editorRoot.querySelectorAll('a');
+ await point(first!, 'pointerover');
+ await wait(400);
+ await point(second!, 'pointerover');
+ await wait(300);
+ assert.equal(state.open, false);
+ assert.equal(state.candidateAnchor, second);
+ assert.equal(state.anchor, null);
+ await wait(370);
+ assert.equal(state.open, true);
+ await point(second!, 'pointerout');
+ await act(() => state.keepOpen());
+ await wait(300);
+ assert.equal(state.open, true);
+ });
+
+ it('accepts relative internal links and rejects unsafe, credential-bearing or download links', () => {
+ editorRoot.innerHTML = '<a href="/project/EX">Project</a>';
+ const internal = editorRoot.querySelector('a');
+ assert.equal(previewableLink(internal, editorRoot), internal);
+ for (const href of [
+ 'javascript:alert(1)',
+ 'mailto:[email protected]',
+ 'https://user:[email protected]',
+ ]) {
+ editorRoot.innerHTML = `<a href="${href}">Link</a>`;
+ assert.equal(previewableLink(editorRoot.querySelector('a'), editorRoot), null);
+ }
+ editorRoot.innerHTML = '<a href="https://example.com" download>File</a>';
+ assert.equal(previewableLink(editorRoot.querySelector('a'), editorRoot), null);
+ });
+});
diff --git a/apps/web/src/components/common/editor/useEditorLinkPreview.ts b/apps/web/src/components/common/editor/useEditorLinkPreview.ts
new file mode 100644
index 00000000..2ac1032f
--- /dev/null
+++ b/apps/web/src/components/common/editor/useEditorLinkPreview.ts
@@ -0,0 +1,92 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import type { Editor } from '@tiptap/react';
+import { previewableLink } from './previewableLink';
+
+export function useEditorLinkPreview(editor: Editor) {
+ const [anchor, setAnchor] = useState<HTMLAnchorElement | null>(null);
+ const [candidateAnchor, setCandidateAnchor] = useState<HTMLAnchorElement | null>(null);
+ const [open, setOpen] = useState(false);
+ const anchorRef = useRef<HTMLAnchorElement | null>(null);
+ const visibleRef = useRef(false);
+ const openTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const closeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const clearTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+
+ const keepOpen = useCallback(() => {
+ clearTimeout(closeTimer.current);
+ clearTimeout(clearTimer.current);
+ }, []);
+ const close = useCallback(() => {
+ if (!anchorRef.current) return;
+ clearTimeout(openTimer.current);
+ openTimer.current = undefined;
+ clearTimeout(closeTimer.current);
+ clearTimeout(clearTimer.current);
+ visibleRef.current = false;
+ setOpen(false);
+ clearTimer.current = setTimeout(() => {
+ anchorRef.current = null;
+ setAnchor(null);
+ setCandidateAnchor(null);
+ }, 160);
+ }, []);
+ const leave = useCallback(() => {
+ clearTimeout(openTimer.current);
+ openTimer.current = undefined;
+ clearTimeout(closeTimer.current);
+ closeTimer.current = setTimeout(close, 120);
+ }, [close]);
+
+ useEffect(() => {
+ const root = editor.view.dom;
+ const enter = (event: Event) => {
+ if (event instanceof PointerEvent && event.pointerType === 'touch') return;
+ const link = previewableLink(event.target, root);
+ if (!link) return;
+ keepOpen();
+ if (anchorRef.current === link && (visibleRef.current || openTimer.current)) return;
+ clearTimeout(openTimer.current);
+ anchorRef.current = link;
+ setCandidateAnchor(link);
+ visibleRef.current = false;
+ setOpen(false);
+ openTimer.current = setTimeout(() => {
+ openTimer.current = undefined;
+ setAnchor(link);
+ visibleRef.current = true;
+ setOpen(true);
+ }, 650);
+ };
+ const exit = (event: MouseEvent | FocusEvent) => {
+ if (anchorRef.current?.contains(event.relatedTarget as Node | null)) return;
+ leave();
+ };
+ const escape = (event: KeyboardEvent) => {
+ if (event.key !== 'Escape' || !anchorRef.current) return;
+ if (visibleRef.current) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ close();
+ };
+ root.addEventListener('pointerover', enter);
+ root.addEventListener('pointerout', exit);
+ root.addEventListener('focusin', enter);
+ root.addEventListener('focusout', exit);
+ document.addEventListener('keydown', escape, true);
+ window.addEventListener('scroll', close, true);
+ return () => {
+ root.removeEventListener('pointerover', enter);
+ root.removeEventListener('pointerout', exit);
+ root.removeEventListener('focusin', enter);
+ root.removeEventListener('focusout', exit);
+ document.removeEventListener('keydown', escape, true);
+ window.removeEventListener('scroll', close, true);
+ clearTimeout(openTimer.current);
+ clearTimeout(closeTimer.current);
+ clearTimeout(clearTimer.current);
+ };
+ }, [editor, close, leave, keepOpen]);
+
+ return { anchor, candidateAnchor, open, keepOpen, leave, close };
+}
diff --git a/apps/web/src/components/common/editor/useLinkPreviewQuery.ts b/apps/web/src/components/common/editor/useLinkPreviewQuery.ts
new file mode 100644
index 00000000..fde2cc53
--- /dev/null
+++ b/apps/web/src/components/common/editor/useLinkPreviewQuery.ts
@@ -0,0 +1,52 @@
+import { useQuery } from '@tanstack/react-query';
+import { useSession } from '@/lib/auth-client';
+import { resolveLinkPreview } from './resolveLinkPreview';
+
+async function preloadImage(src: string, signal: AbortSignal) {
+ await new Promise<void>((resolve) => {
+ const image = new Image();
+ const finish = () => {
+ clearTimeout(timer);
+ signal.removeEventListener('abort', finish);
+ image.onload = null;
+ image.onerror = null;
+ if (signal.aborted) image.removeAttribute('src');
+ resolve();
+ };
+ const timer = setTimeout(finish, 800);
+ image.referrerPolicy = 'no-referrer';
+ image.onload = finish;
+ image.onerror = finish;
+ signal.addEventListener('abort', finish, { once: true });
+ image.src = src;
+ });
+}
+
+export function useLinkPreviewQuery(url: string | undefined) {
+ const { data: session, isPending: sessionPending } = useSession();
+ const internal =
+ !!url && typeof window !== 'undefined' && new URL(url).origin === window.location.origin;
+ const enabled = !!url && !!session?.user.id;
+ const query = useQuery({
+ queryKey: ['link-preview', session?.user.id, url],
+ enabled,
+ queryFn: async ({ signal }) => {
+ const preview = await resolveLinkPreview(url!, window.location.origin, signal);
+ if (preview.image && !signal.aborted) {
+ await preloadImage(preview.image, signal);
+ }
+ signal.throwIfAborted();
+ return preview;
+ },
+ staleTime: internal ? 0 : 5 * 60_000,
+ gcTime: internal ? 0 : 2 * 60_000,
+ retry: false,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ });
+ return {
+ ...query,
+ data: query.isError ? undefined : query.data,
+ isPending: sessionPending || (enabled && query.isPending),
+ };
+}
diff --git a/apps/web/src/components/common/editor/viewPreviewFilters.ts b/apps/web/src/components/common/editor/viewPreviewFilters.ts
new file mode 100644
index 00000000..0c694783
--- /dev/null
+++ b/apps/web/src/components/common/editor/viewPreviewFilters.ts
@@ -0,0 +1,59 @@
+import type { ProjectScaffold } from '@/lib/api/endpoints/projects';
+import type { View } from '@/lib/api/endpoints/views';
+import { BUILTIN_FILTER_FIELDS, OPERATORS_BY_KIND } from '@/utils/filterFields';
+import { isEffectiveCondition, type FilterOperator } from '@/utils/filters';
+
+export type PreviewFilter = {
+ field: string;
+ label?: string;
+ op: FilterOperator;
+ values: string[];
+ remainingValues: number;
+};
+
+const operators = new Set(Object.values(OPERATORS_BY_KIND).flat());
+
+export function viewPreviewFilters(view: View, project: ProjectScaffold): PreviewFilter[] {
+ const conditions = Array.isArray(view.filters?.conditions) ? view.filters.conditions : [];
+ return conditions
+ .filter(
+ (condition) =>
+ condition &&
+ typeof condition.field === 'string' &&
+ operators.has(condition.op) &&
+ isEffectiveCondition(condition),
+ )
+ .slice(0, 3)
+ .map((condition) => {
+ const field = condition.field;
+ const custom = project.customFields.find((item) => `cf:${item.id}` === field);
+ const known = BUILTIN_FILTER_FIELDS.some((item) => item === field);
+ const values = (Array.isArray(condition.values) ? condition.values : [])
+ .slice(0, 3)
+ .map((value) => {
+ if (value === null) return '—';
+ if (field === 'status') return project.columns.find((item) => item.id === value)?.name;
+ if (field === 'type') return project.issueTypes.find((item) => item.id === value)?.name;
+ if (field === 'labels') return project.labels.find((item) => item.id === value)?.name;
+ if (field === 'assignee' || field === 'delegate')
+ return project.assignees.find((item) => item.userId === value)?.name;
+ if (custom?.fieldType === 'select' || custom?.fieldType === 'multi_select')
+ return custom.options.find((option) => option.id === value)?.value;
+ if (custom?.fieldType === 'member')
+ return project.assignees.find((item) => item.userId === value)?.name;
+ if (custom?.fieldType === 'number' && typeof value === 'number') return String(value);
+ if (typeof value !== 'string' && typeof value !== 'boolean') return undefined;
+ return String(value)
+ .replace(/^status:/, '')
+ .slice(0, 80);
+ })
+ .filter((value): value is string => value !== undefined);
+ return {
+ field: known ? field : 'custom',
+ label: custom?.name,
+ op: condition.op,
+ values,
+ remainingValues: Math.max(0, (condition.values?.length ?? 0) - values.length),
+ };
+ });
+}
diff --git a/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
index 47e03c55..ce155f5b 100644
--- a/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
+++ b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useEffect, useLayoutEffect, useRef } from 'react';
+import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import type { JSONContent } from '@tiptap/core';
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
import Color from '@tiptap/extension-color';
@@ -19,6 +19,9 @@ import { useTranslations } from 'next-intl';
import { Markdown } from 'tiptap-markdown';
import EditorSelectionMenu from '@/components/common/editor/EditorSelectionMenu';
import EditorTableMenu from '@/components/common/editor/EditorTableMenu';
+import EditorLinkPreview from '@/components/common/editor/EditorLinkPreview';
+import { createLinkKeyboardHandlers } from '@/components/common/editor/linkKeyboardHandlers';
+import { openLinkOnModifierClick } from '@/components/common/editor/modifierClickLink';
import { ResizableImage } from '@/components/common/editor/tiptap-image';
import { MarkdownTable } from '@/components/common/editor/tiptap-table';
import { pasteMarkdown } from '@/components/common/editor/pasteMarkdown';
@@ -82,6 +85,7 @@ export function documentEditorExtensions(labels: EditorLabels) {
autolink: true,
defaultProtocol: 'https',
openOnClick: true,
+ HTMLAttributes: { class: 'cursor-pointer', tabindex: '0' },
isAllowedUri: safeDocumentLinkHref,
}),
ResizableImage,
@@ -132,6 +136,7 @@ export default function DocumentMarkdownEditor({
}) {
const t = useTranslations('documents.toolbar');
const editorRef = useRef<Editor | null>(null);
+ const linkKeyboardHandlers = useMemo(createLinkKeyboardHandlers, []);
const editableRef = useRef(editable);
editableRef.current = editable;
@@ -161,6 +166,10 @@ export default function DocumentMarkdownEditor({
}),
content: defaultJson ?? defaultValue,
editorProps: {
+ handleDOMEvents: linkKeyboardHandlers,
+ handleClick(view, _pos, event) {
+ return openLinkOnModifierClick(event, view.dom);
+ },
attributes: {
class: 'md-content flex-1 focus:outline-none selection:bg-primary/15',
},
@@ -222,6 +231,7 @@ export default function DocumentMarkdownEditor({
{editable && <EditorSelectionMenu editor={editor} />}
{editable && <EditorTableMenu editor={editor} />}
<EditorContent editor={editor} className="flex min-h-full flex-col" />
+ <EditorLinkPreview editor={editor} />
</div>
);
}
diff --git a/apps/web/src/features/notes/components/StickerEditor.tsx b/apps/web/src/features/notes/components/StickerEditor.tsx
index 1e6de3e6..442425f6 100644
--- a/apps/web/src/features/notes/components/StickerEditor.tsx
+++ b/apps/web/src/features/notes/components/StickerEditor.tsx
@@ -6,6 +6,7 @@ import TaskList from '@tiptap/extension-task-list';
import TaskItem from '@tiptap/extension-task-item';
import { Markdown } from 'tiptap-markdown';
import { useTranslations } from 'next-intl';
+import EditorLinkPreview from '@/components/common/editor/EditorLinkPreview';
// The markdown body of a sticky note. Unlike the issue editor there is no bubble
// menu — a persistent toolbar (StickerToolbar) drives the commands — and task
@@ -42,5 +43,10 @@ export default function StickerEditor({
}, [editor, onReady]);
if (!editor) return null;
- return <EditorContent editor={editor} />;
+ return (
+ <>
+ <EditorContent editor={editor} />
+ <EditorLinkPreview editor={editor} />
+ </>
+ );
}
diff --git a/apps/web/src/lib/api/endpoints/documents.ts b/apps/web/src/lib/api/endpoints/documents.ts
index 6a10dcea..480dfb2a 100644
--- a/apps/web/src/lib/api/endpoints/documents.ts
+++ b/apps/web/src/lib/api/endpoints/documents.ts
@@ -121,8 +121,10 @@ export const listDocuments = (projectKey: string, q?: string, archived = false)
return request<ProjectDocumentSummary[]>(`/projects/${projectKey}/documents${suffix}`);
};
-export const getDocument = (projectKey: string, documentId: number) =>
- request<ProjectDocument>(`/projects/${projectKey}/documents/${documentId}`);
+export const getDocument = (projectKey: string, documentId: number, signal?: AbortSignal) =>
+ request<ProjectDocument>(`/projects/${encodeURIComponent(projectKey)}/documents/${documentId}`, {
+ signal,
+ });
export const listDocumentIssueLinks = (projectKey: string, documentId: number) =>
request<DocumentIssueLink[]>(`/projects/${projectKey}/documents/${documentId}/issues`);
diff --git a/apps/web/src/lib/api/endpoints/issues.ts b/apps/web/src/lib/api/endpoints/issues.ts
index 019e32ec..ce7ace43 100644
--- a/apps/web/src/lib/api/endpoints/issues.ts
+++ b/apps/web/src/lib/api/endpoints/issues.ts
@@ -296,11 +296,14 @@ export const createIssue = (projectKey: string, input: NewIssueInput) =>
body: JSON.stringify(input),
});
-export const getIssue = (id: number) => request<IssueWithWatchers>(`/issues/${id}`);
+export const getIssue = (id: number, signal?: AbortSignal) =>
+ request<IssueWithWatchers>(`/issues/${id}`, { signal });
// Resolve an issue by its project-scoped number (the human "42" in the URL).
-export const getIssueBySeq = (projectKey: string, seq: number) =>
- request<IssueWithWatchers>(`/projects/${projectKey}/issues/${seq}`);
+export const getIssueBySeq = (projectKey: string, seq: number, signal?: AbortSignal) =>
+ request<IssueWithWatchers>(`/projects/${encodeURIComponent(projectKey)}/issues/${seq}`, {
+ signal,
+ });
export const listIssueCycles = (id: number) => request<IssueCycleEntry[]>(`/issues/${id}/cycles`);
diff --git a/apps/web/src/lib/api/endpoints/link-previews.ts b/apps/web/src/lib/api/endpoints/link-previews.ts
new file mode 100644
index 00000000..95f09321
--- /dev/null
+++ b/apps/web/src/lib/api/endpoints/link-previews.ts
@@ -0,0 +1,13 @@
+import { request } from '../core/client';
+
+export type LinkPreview = {
+ url: string;
+ title: string | null;
+ description: string | null;
+ image: string | null;
+ siteName: string | null;
+};
+
+export function getLinkPreview(url: string, signal: AbortSignal) {
+ return request<LinkPreview>(`/link-previews?${new URLSearchParams({ url })}`, { signal });
+}
diff --git a/apps/web/src/lib/api/endpoints/noteBoards.ts b/apps/web/src/lib/api/endpoints/noteBoards.ts
index c7e752a0..0a9f5681 100644
--- a/apps/web/src/lib/api/endpoints/noteBoards.ts
+++ b/apps/web/src/lib/api/endpoints/noteBoards.ts
@@ -97,8 +97,10 @@ export const listNoteBoards = (projectKey: string, params: { q?: string } = {})
`/projects/${projectKey}/note-boards${params.q ? `?q=${encodeURIComponent(params.q)}` : ''}`,
);
-export const getNoteBoard = (projectKey: string, boardId: number) =>
- request<NoteBoard>(`/projects/${projectKey}/note-boards/${boardId}`);
+export const getNoteBoard = (projectKey: string, boardId: number, signal?: AbortSignal) =>
+ request<NoteBoard>(`/projects/${encodeURIComponent(projectKey)}/note-boards/${boardId}`, {
+ signal,
+ });
export const listNoteBoardAccessCandidates = (projectKey: string) =>
request<NoteBoardAccessCandidate[]>(`/projects/${projectKey}/note-boards/access-candidates`);
diff --git a/apps/web/src/lib/api/endpoints/projects.ts b/apps/web/src/lib/api/endpoints/projects.ts
index 2c1df8a6..356ac491 100644
--- a/apps/web/src/lib/api/endpoints/projects.ts
+++ b/apps/web/src/lib/api/endpoints/projects.ts
@@ -124,8 +124,8 @@ export const updateProject = (projectKey: string, patch: { name?: string; descri
request<Project>(`/projects/${projectKey}`, { method: 'PATCH', body: JSON.stringify(patch) });
// The board scaffold (no issues). The issues come from getBoardIssues.
-export const getProject = (projectKey: string) =>
- request<ProjectScaffold>(`/projects/${projectKey}`);
+export const getProject = (projectKey: string, signal?: AbortSignal) =>
+ request<ProjectScaffold>(`/projects/${encodeURIComponent(projectKey)}`, { signal });
// The board's issues and their relations.
export const getBoardIssues = (projectKey: string) =>
diff --git a/apps/web/src/lib/api/endpoints/views.ts b/apps/web/src/lib/api/endpoints/views.ts
index a352d5a2..92ef5c0d 100644
--- a/apps/web/src/lib/api/endpoints/views.ts
+++ b/apps/web/src/lib/api/endpoints/views.ts
@@ -39,7 +39,8 @@ export interface ViewPatch {
display?: SavedViewDisplay;
}
-export const listViews = (projectKey: string) => request<View[]>(`/projects/${projectKey}/views`);
+export const listViews = (projectKey: string, signal?: AbortSignal) =>
+ request<View[]>(`/projects/${encodeURIComponent(projectKey)}/views`, { signal });
export const createView = (projectKey: string, input: NewViewInput) =>
request<View>(`/projects/${projectKey}/views`, { method: 'POST', body: JSON.stringify(input) });
diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.ts
index 2b2f7635..ac772349 100644
--- a/apps/web/src/proxy.test.ts
+++ b/apps/web/src/proxy.test.ts
@@ -1,10 +1,21 @@
import assert from 'node:assert/strict';
-import { describe, it } from 'node:test';
+import { afterEach, beforeEach, describe, it } from 'node:test';
import { NextRequest } from 'next/server';
import { proxy } from './proxy';
const COOKIE = 'better-auth.session_token=stale.signature';
+let originalApiUrl: string | undefined;
+
+beforeEach(() => {
+ originalApiUrl = process.env.API_URL;
+});
+
+afterEach(() => {
+ if (originalApiUrl === undefined) delete process.env.API_URL;
+ else process.env.API_URL = originalApiUrl;
+});
+
function run(path: string, cookie?: string) {
return proxy(
new NextRequest(`http://localhost${path}`, {
diff --git a/apps/web/src/utils/contentSecurityPolicy.test.ts b/apps/web/src/utils/contentSecurityPolicy.test.ts
index 38f2a289..62ba416c 100644
--- a/apps/web/src/utils/contentSecurityPolicy.test.ts
+++ b/apps/web/src/utils/contentSecurityPolicy.test.ts
@@ -1,7 +1,18 @@
import assert from 'node:assert/strict';
-import { describe, it } from 'node:test';
+import { afterEach, beforeEach, describe, it } from 'node:test';
import { contentSecurityPolicy } from './contentSecurityPolicy';
+let originalApiUrl: string | undefined;
+
+beforeEach(() => {
+ originalApiUrl = process.env.API_URL;
+});
+
+afterEach(() => {
+ if (originalApiUrl === undefined) delete process.env.API_URL;
+ else process.env.API_URL = originalApiUrl;
+});
+
describe('contentSecurityPolicy', () => {
it('allows requests to the api origin only, without its path', () => {
process.env.API_URL = 'https://api.example.com/base/';
diff --git a/apps/web/test/setup.ts b/apps/web/test/setup.ts
new file mode 100644
index 00000000..0caafbb3
--- /dev/null
+++ b/apps/web/test/setup.ts
@@ -0,0 +1 @@
+process.env.API_URL ??= 'http://api.test';
diff --git a/bun.lock b/bun.lock
index 7f15895e..c8a0aad6 100644
--- a/bun.lock
+++ b/bun.lock
@@ -36,6 +36,7 @@
"@repo/mailer": "workspace:*",
"@repo/net": "workspace:*",
"croner": "^10.0.1",
+ "decode-named-character-reference": "^1.3.0",
"drizzle-orm": "^0.45.2",
"elysia": "^1.4.29",
"exceljs": "^4.4.0",
diff --git a/packages/net/src/__tests__/bounded-fetch.test.ts b/packages/net/src/__tests__/bounded-fetch.test.ts
new file mode 100644
index 00000000..c09bb370
--- /dev/null
+++ b/packages/net/src/__tests__/bounded-fetch.test.ts
@@ -0,0 +1,145 @@
+import { afterEach, describe, expect, it } from 'bun:test';
+import { createServer, type RequestListener } from 'node:http';
+import { assertPublicHttpUrl, pinnedFetch, UrlNotAllowedError } from '../index';
+
+describe('public-only URL policy', () => {
+ const environment = process.env.NODE_ENV;
+ const allowedHosts = process.env.SSRF_ALLOWED_HOSTS;
+ afterEach(() => {
+ process.env.NODE_ENV = environment;
+ if (allowedHosts === undefined) delete process.env.SSRF_ALLOWED_HOSTS;
+ else process.env.SSRF_ALLOWED_HOSTS = allowedHosts;
+ });
+
+ it('rejects private, reserved and local addresses even in development with an allowlist', async () => {
+ process.env.NODE_ENV = 'development';
+ process.env.SSRF_ALLOWED_HOSTS = '127.0.0.1,localhost';
+ for (const host of [
+ '127.0.0.1',
+ 'localhost',
+ '10.0.0.1',
+ '169.254.169.254',
+ '224.0.0.1',
+ '255.255.255.255',
+ '[::1]',
+ '[fe90::1]',
+ '[fea0::1]',
+ '[feb0::1]',
+ '[::ffff:127.0.0.1]',
+ '[2001:db8::1]',
+ '[2002:7f00:1::]',
+ ]) {
+ await expect(
+ assertPublicHttpUrl(`http://${host}/`, { publicOnly: true }),
+ ).rejects.toBeInstanceOf(UrlNotAllowedError);
+ }
+ });
+
+ it('rejects credentials and non-HTTP schemes', async () => {
+ for (const url of [
+ 'https://user:[email protected]/',
+ 'file:///etc/passwd',
+ 'javascript:alert(1)',
+ ]) {
+ await expect(assertPublicHttpUrl(url, { publicOnly: true })).rejects.toBeInstanceOf(
+ UrlNotAllowedError,
+ );
+ }
+ });
+
+ it('refuses a hostname resolving privately despite its allowlist entry', async () => {
+ process.env.NODE_ENV = 'development';
+ process.env.SSRF_ALLOWED_HOSTS = 'localtest.me';
+ await expect(
+ assertPublicHttpUrl('https://localtest.me/', { publicOnly: true }),
+ ).rejects.toBeInstanceOf(UrlNotAllowedError);
+ });
+
+ it('honors an already aborted signal before DNS or HTTP', async () => {
+ await expect(
+ pinnedFetch('https://example.com', { publicOnly: true, signal: AbortSignal.abort() }),
+ ).rejects.toBeDefined();
+ });
+});
+
+describe('bounded pinned fetch', () => {
+ const environment = process.env.NODE_ENV;
+ afterEach(() => {
+ process.env.NODE_ENV = environment;
+ });
+
+ async function withServer(handler: RequestListener, run: (url: string) => Promise<void>) {
+ const server = createServer(handler);
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Missing test port');
+ process.env.NODE_ENV = 'development';
+ try {
+ await run(`http://127.0.0.1:${address.port}`);
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ }
+
+ it('accepts exactly the byte limit and rejects a larger response', async () => {
+ await withServer(
+ (_req, res) => res.end('12345'),
+ async (url) => {
+ expect(await (await pinnedFetch(url, { maxBytes: 5 })).text()).toBe('12345');
+ await expect(pinnedFetch(url, { maxBytes: 4 })).rejects.toThrow('byte limit');
+ },
+ );
+ });
+
+ it('aborts a response that keeps sending bytes before its inactivity timeout', async () => {
+ await withServer(
+ (_req, res) => {
+ const timer = setInterval(() => res.write('x'), 10);
+ res.on('close', () => clearInterval(timer));
+ },
+ async (url) => {
+ await expect(
+ pinnedFetch(url, { timeoutMs: 500, signal: AbortSignal.timeout(80) }),
+ ).rejects.toThrow('aborted');
+ },
+ );
+ });
+
+ it('returns only the bounded prefix when requested for document metadata', async () => {
+ await withServer(
+ (_req, res) => res.end('123456789'),
+ async (url) => {
+ expect(await (await pinnedFetch(url, { maxBytes: 5, truncateBody: true })).text()).toBe(
+ '12345',
+ );
+ },
+ );
+ });
+
+ it('returns a redirect without following its target', async () => {
+ await withServer(
+ (_req, res) => {
+ res.writeHead(302, { Location: 'http://169.254.169.254/' });
+ res.end();
+ },
+ async (url) => {
+ expect((await pinnedFetch(url, { maxBytes: 512 })).status).toBe(302);
+ },
+ );
+ });
+
+ it('rejects invalid upstream status codes without leaving the request pending', async () => {
+ await withServer(
+ (_req, res) => {
+ res.writeHead(600);
+ res.end();
+ },
+ async (url) => {
+ await expect(pinnedFetch(url, { signal: AbortSignal.timeout(100) })).rejects.toThrow(
+ 'invalid HTTP status',
+ );
+ },
+ );
+ });
+});
diff --git a/packages/net/src/index.ts b/packages/net/src/index.ts
index 216d1ef0..6b808715 100644
--- a/packages/net/src/index.ts
+++ b/packages/net/src/index.ts
@@ -1,6 +1,6 @@
import { lookup } from 'node:dns/promises';
import { request as httpRequest } from 'node:http';
-import type { LookupFunction } from 'node:net';
+import { isIP, type LookupFunction } from 'node:net';
import { request as httpsRequest } from 'node:https';
// SSRF guards for server-side fetches of a user/agent-supplied URL. A URL that
@@ -88,9 +88,37 @@ interface Pin {
family: number;
}
+interface UrlPolicy {
+ // Public content never uses development or configured private-host exceptions.
+ publicOnly?: boolean;
+ signal?: AbortSignal;
+}
+
+function isNonPublicIp(ip: string): boolean {
+ const normalized = toIpv4(ip.toLowerCase());
+ if (isPrivateIp(normalized)) return true;
+ if (isIP(normalized) === 4) {
+ const [a, b, c] = normalized.split('.').map(Number);
+ return (
+ a! >= 224 ||
+ (a === 192 && b === 0) ||
+ (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||
+ (a === 203 && b === 0 && c === 113)
+ );
+ }
+ return (
+ !/^[23][0-9a-f]{3}:/.test(normalized) ||
+ (normalized.startsWith('2001:') && parseInt(normalized.split(':')[1] || '0', 16) < 0x200) ||
+ normalized.startsWith('2001:db8:') ||
+ normalized.startsWith('3fff:') ||
+ normalized.startsWith('2002:')
+ );
+}
+
// Validates the URL and resolves its hostname once. `pin` is the address the caller
// must connect to; it is absent only when the host is already an IP literal.
-async function vet(raw: string): Promise<{ url: URL; pin?: Pin }> {
+async function vet(raw: string, policy: UrlPolicy = {}): Promise<{ url: URL; pin?: Pin }> {
+ policy.signal?.throwIfAborted();
let url: URL;
try {
url = new URL(raw);
@@ -98,14 +126,22 @@ async function vet(raw: string): Promise<{ url: URL; pin?: Pin }> {
throw new UrlNotAllowedError('url must be a valid URL');
}
- const devRelaxed = process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';
- if (url.protocol !== 'https:' && !(devRelaxed && url.protocol === 'http:')) {
+ const devRelaxed =
+ !policy.publicOnly && process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';
+ if (
+ url.protocol !== 'https:' &&
+ !((devRelaxed || policy.publicOnly) && url.protocol === 'http:')
+ ) {
throw new UrlNotAllowedError('url must use https');
}
+ if (policy.publicOnly && (url.username || url.password)) {
+ throw new UrlNotAllowedError('url must not include credentials');
+ }
const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
- const allowed = isAllowedHost(host);
- if (isLocalHostname(host) || isPrivateIp(host)) {
+ const allowed = !policy.publicOnly && isAllowedHost(host);
+ const blockedIp = policy.publicOnly ? isNonPublicIp : isPrivateIp;
+ if (isLocalHostname(host) || (isIP(host) && blockedIp(host))) {
if (!devRelaxed && !allowed) {
throw new UrlNotAllowedError('url must not point to a private or local address');
}
@@ -113,12 +149,29 @@ async function vet(raw: string): Promise<{ url: URL; pin?: Pin }> {
}
let addrs: Pin[];
+ let abort: (() => void) | undefined;
try {
- addrs = await lookup(host, { all: true });
+ const resolution = lookup(host, { all: true });
+ if (policy.signal) {
+ const signal = policy.signal;
+ addrs = await Promise.race([
+ resolution,
+ new Promise<never>((_resolve, reject) => {
+ abort = () => reject(signal.reason);
+ signal.addEventListener('abort', abort, { once: true });
+ if (signal.aborted) abort();
+ }),
+ ]);
+ } else {
+ addrs = await resolution;
+ }
} catch {
+ policy.signal?.throwIfAborted();
throw new UrlNotAllowedError('url host could not be resolved');
+ } finally {
+ if (abort) policy.signal?.removeEventListener('abort', abort);
}
- if (addrs.some((a) => isPrivateIp(a.address)) && !devRelaxed && !allowed) {
+ if ((!addrs.length || addrs.some((a) => blockedIp(a.address))) && !devRelaxed && !allowed) {
throw new UrlNotAllowedError('url must not point to a private or local address');
}
return { url, pin: addrs[0] };
@@ -126,10 +179,10 @@ async function vet(raw: string): Promise<{ url: URL; pin?: Pin }> {
// Validates a user/agent-supplied URL for a server-side fetch: http(s) only, and it
// must not resolve to a local/private address. Returns the parsed URL. http is
-// allowed only in local development; production and tests require https. Throws
-// UrlNotAllowedError on any failure.
-export async function assertPublicHttpUrl(raw: string): Promise<URL> {
- return (await vet(raw)).url;
+// allowed in local development or under the public-only policy. Throws
+// UrlNotAllowedError when the URL or its resolved addresses are refused.
+export async function assertPublicHttpUrl(raw: string, policy?: UrlPolicy): Promise<URL> {
+ return (await vet(raw, policy)).url;
}
// node's http client sends no User-Agent of its own, and GitHub answers 403 with an
@@ -137,11 +190,14 @@ export async function assertPublicHttpUrl(raw: string): Promise<URL> {
// one, so callers never had to.
const DEFAULT_USER_AGENT = 'itsaplan/1';
-export interface PinnedRequestInit {
+export interface PinnedRequestInit extends UrlPolicy {
method?: string;
headers?: Record<string, string> | Headers;
body?: string | Buffer;
timeoutMs?: number;
+ maxBytes?: number;
+ // Keep a document prefix for metadata; binary downloads must reject oversized bodies.
+ truncateBody?: boolean;
}
// Validates the URL, then connects to the address that validation resolved instead of
@@ -151,7 +207,8 @@ export interface PinnedRequestInit {
// certificate check. Redirects are never followed: the 3xx is returned as-is, so a
// caller cannot be steered to an address that was never validated.
export async function pinnedFetch(raw: string, init: PinnedRequestInit = {}): Promise<Response> {
- const { url, pin } = await vet(raw);
+ const { url, pin } = await vet(raw, init);
+ init.signal?.throwIfAborted();
const send = url.protocol === 'https:' ? httpsRequest : httpRequest;
const headers =
init.headers instanceof Headers
@@ -178,12 +235,14 @@ export async function pinnedFetch(raw: string, init: PinnedRequestInit = {}): Pr
},
(res) => {
const chunks: Buffer[] = [];
- res.on('data', (chunk: Buffer) => chunks.push(chunk));
- res.on('error', reject);
- res.on('end', () => {
+ let bytes = 0;
+ const complete = () => {
const status = res.statusCode ?? 502;
- // Response rejects a body on these statuses; the receiver sent none anyway.
- const empty = status < 200 || status === 204 || status === 205 || status === 304;
+ if (status < 200 || status > 599) {
+ reject(new Error('response has an invalid HTTP status'));
+ return;
+ }
+ const empty = status === 204 || status === 205 || status === 304;
resolve(
new Response(empty ? null : Buffer.concat(chunks), {
status,
@@ -192,10 +251,33 @@ export async function pinnedFetch(raw: string, init: PinnedRequestInit = {}): Pr
),
}),
);
+ };
+ res.on('data', (chunk: Buffer) => {
+ if (init.maxBytes !== undefined && bytes + chunk.length > init.maxBytes) {
+ if (init.truncateBody) {
+ chunks.push(chunk.subarray(0, init.maxBytes - bytes));
+ complete();
+ res.destroy();
+ req.destroy();
+ return;
+ }
+ const error = new Error('response exceeds the byte limit');
+ res.destroy(error);
+ req.destroy(error);
+ return;
+ }
+ bytes += chunk.length;
+ chunks.push(chunk);
});
+ res.on('error', reject);
+ res.on('end', complete);
},
);
req.on('error', reject);
+ const abort = () => req.destroy(new Error('request aborted'));
+ init.signal?.addEventListener('abort', abort, { once: true });
+ req.on('close', () => init.signal?.removeEventListener('abort', abort));
+ if (init.signal?.aborted) abort();
if (init.timeoutMs) {
req.setTimeout(init.timeoutMs, () => req.destroy(new Error('request timed out')));
}