Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(attachments): generate text preview whitelist (MUL-8248) (#9527)
Ryan Yu802f0894e046
diff --git a/.github/ci-paths.json b/.github/ci-paths.jsonindex fc33ec11cc..351f118591 100644--- a/.github/ci-paths.json+++ b/.github/ci-paths.json@@ -74,6 +74,7 @@".github/ci-paths.json"],"scripts": [+ "scripts/generate-attachment-text-preview.mjs","scripts/generate-reserved-slugs.mjs","scripts/selfhost-config.test.sh","scripts/drop-database.sh",@@ -101,7 +102,9 @@"docker-compose.selfhost.yml","docker-compose.selfhost.build.yml","Makefile",+ "server/internal/handler/attachment_text_preview.json","server/internal/handler/reserved_slugs.json",+ "packages/views/editor/utils/text-preview-whitelist.generated.ts","packages/core/paths/reserved-slugs.ts","server/cmd/server/router.go",".github/workflows/ci.yml",diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b5aab464af..f6f2643480 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -917,6 +917,13 @@ jobs:node scripts/generate-reserved-slugs.mjsgit diff --exit-code -- packages/core/paths/reserved-slugs.ts+ - name: Verify attachment text-preview whitelist is up to date+ # The Go handler embeds the JSON source directly while the shared+ # web/desktop view consumes the checked-in generated TypeScript file.+ run: |+ node scripts/generate-attachment-text-preview.mjs+ git diff --exit-code -- packages/views/editor/utils/text-preview-whitelist.generated.ts+- name: Setup Helmuses: azure/setup-helm@v4diff --git a/package.json b/package.jsonindex 3ffbdd4e42..478bf032c7 100644--- a/package.json+++ b/package.json@@ -28,6 +28,7 @@"check:ui-radii": "node scripts/check-ui-radius-tokens.mjs","clean": "turbo clean && rm -rf node_modules","ui:add": "cd packages/ui && npx shadcn@latest add",+ "generate:attachment-text-preview": "node scripts/generate-attachment-text-preview.mjs","generate:reserved-slugs": "node scripts/generate-reserved-slugs.mjs","dev:ui-lab": "pnpm --filter @multica/ui-lab dev"},diff --git a/packages/views/editor/utils/preview.test.ts b/packages/views/editor/utils/preview.test.tsindex 23bd802da4..893c08b013 100644--- a/packages/views/editor/utils/preview.test.ts+++ b/packages/views/editor/utils/preview.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import {extensionToLanguage,getPreviewKind,@@ -9,6 +9,12 @@ import {wrapsByDefault,type PreviewKind,} from "./preview";+import {+ TEXT_PREVIEW_BASENAMES,+ TEXT_PREVIEW_CONTENT_TYPE_PREFIXES,+ TEXT_PREVIEW_CONTENT_TYPES,+ TEXT_PREVIEW_EXTENSIONS,+} from "./text-preview-whitelist.generated";describe("getPreviewKind", () => {const cases: Array<[string, string, PreviewKind | null]> = [@@ -150,49 +156,126 @@ describe("extensionToLanguage", () => {});});-// Mirror of TestIsTextPreviewable in server/internal/handler/file_test.go,-// the text proxy's whitelist. Keep the two tables identical: a type only the-// client accepts opens to a 415, one only the server accepts never opens.-describe("text preview whitelist (mirrors the server)", () => {+describe("generated text preview whitelist", () => {const TEXT_BACKED = new Set<PreviewKind>(["markdown", "html", "table", "structured", "text"]);- const cases: Array<[string, string, string, boolean]> = [- ["markdown by ext", "application/octet-stream", "README.md", true],- ["markdown by mime", "text/markdown", "README", true],- ["plain text", "text/plain", "log.txt", true],- ["json by mime", "application/json", "data.json", true],- ["yaml by ext", "application/octet-stream", "config.yml", true],- ["csv by ext", "application/octet-stream", "report.csv", true],- ["tsv by ext", "application/octet-stream", "export.tsv", true],- ["json lines by ext", "application/octet-stream", "events.jsonl", true],- ["ndjson by ext", "application/octet-stream", "events.ndjson", true],- ["ndjson by mime", "application/x-ndjson", "events", true],- ["log by ext", "application/octet-stream", "server.log", true],- ["go source", "text/plain", "main.go", true],- ["typescript", "application/octet-stream", "index.ts", true],- ["html", "text/html", "page.html", true],- ["dockerfile no ext", "application/octet-stream", "Dockerfile", true],- ["makefile no ext", "application/octet-stream", "Makefile", true],- ["env dotfile", "application/octet-stream", ".env", true],- ["gitignore dotfile", "application/octet-stream", ".gitignore", true],- ["dockerfile extension", "application/octet-stream", "service.dockerfile", true],- ["makefile extension", "application/octet-stream", "rules.makefile", true],-- ["pdf rejected", "application/pdf", "doc.pdf", false],- ["png rejected", "image/png", "shot.png", false],- ["video rejected", "video/mp4", "clip.mp4", false],- ["binary fallthrough", "application/octet-stream", "blob.bin", false],++ function expectTextBacked(contentType: string, filename: string) {+ const kind = getPreviewKind(contentType, filename);+ expect(kind !== null && TEXT_BACKED.has(kind)).toBe(true);+ }++ it("accepts every generated content-type prefix", () => {+ for (const prefix of TEXT_PREVIEW_CONTENT_TYPE_PREFIXES) {+ expectTextBacked(`${prefix}plain`, "payload.bin");+ }+ });++ it("accepts every generated exact content type", () => {+ for (const contentType of TEXT_PREVIEW_CONTENT_TYPES) {+ expectTextBacked(contentType, "payload");+ }+ });++ it("accepts every generated extension", () => {+ for (const extension of TEXT_PREVIEW_EXTENSIONS) {+ expectTextBacked("application/octet-stream", `source.${extension}`);+ }+ });++ it("accepts every generated basename", () => {+ for (const basename of TEXT_PREVIEW_BASENAMES) {+ expectTextBacked("application/octet-stream", basename);+ }+ });++ it.each([+ ["application/pdf", "doc.pdf"],+ ["image/png", "shot.png"],+ ["video/mp4", "clip.mp4"],+ ["application/octet-stream", "blob.bin"],[- "docx rejected","application/vnd.openxmlformats-officedocument.wordprocessingml.document","report.docx",- false,],- ];+ ])("rejects non-text proxy input (%s, %s)", (contentType, filename) => {+ const kind = getPreviewKind(contentType, filename);+ expect(kind !== null && TEXT_BACKED.has(kind)).toBe(false);+ });+});- for (const [name, contentType, filename, want] of cases) {- it(name, () => {- const kind = getPreviewKind(contentType, filename);- expect(kind !== null && TEXT_BACKED.has(kind)).toBe(want);- });- }+describe("text preview whitelist removals", () => {+ afterEach(() => vi.restoreAllMocks());++ it.each<[string, PreviewKind]>([+ ["md", "markdown"],+ ["markdown", "markdown"],+ ["html", "html"],+ ["htm", "html"],+ ["csv", "table"],+ ["tsv", "table"],+ ["json", "structured"],+ ["jsonl", "structured"],+ ["ndjson", "structured"],+ ["yaml", "structured"],+ ["yml", "structured"],+ ["go", "text"],+ ])("hides .%s previews when the extension is removed", (extension, kind) => {+ const filename = `source.${extension}`;+ expect(getPreviewKind("application/octet-stream", filename)).toBe(kind);++ const remaining = new Set(TEXT_PREVIEW_EXTENSIONS);+ remaining.delete(extension);+ vi.spyOn(TEXT_PREVIEW_EXTENSIONS, "has").mockImplementation((value) => remaining.has(value));++ expect(getPreviewKind("application/octet-stream", filename)).toBeNull();+ // A matching MIME still grants access, just as it does on the server.+ expect(getPreviewKind("text/plain", filename)).toBe(kind);+ });++ it.each([+ "application/json",+ "application/x-ndjson",+ "application/yaml",+ "application/x-yaml",+ ])("hides extension-less %s previews when the MIME is removed", (contentType) => {+ expect(getPreviewKind(contentType, "payload")).toBe("structured");++ const remaining = new Set(TEXT_PREVIEW_CONTENT_TYPES);+ remaining.delete(contentType);+ vi.spyOn(TEXT_PREVIEW_CONTENT_TYPES, "has").mockImplementation((value) => remaining.has(value));++ expect(getPreviewKind(contentType, "payload")).toBeNull();+ expect(getPreviewKind(contentType, "payload.json")).toBe("structured");+ });++ it.each([+ "text/markdown", "text/html", "text/csv", "text/tab-separated-values",+ "text/yaml", "text/x-yaml", "text/plain",+ ])("hides extension-less %s previews when the text/ prefix is removed", (contentType) => {+ const remaining = new Set(TEXT_PREVIEW_CONTENT_TYPE_PREFIXES);+ remaining.delete("text/");+ vi.spyOn(TEXT_PREVIEW_CONTENT_TYPE_PREFIXES, Symbol.iterator)+ .mockImplementation(() => remaining.values());++ expect(getPreviewKind(contentType, "payload")).toBeNull();+ });++ it.each<[string, string, PreviewKind]>([+ ["application/pdf", "page.html", "pdf"],+ ["video/mp4", "report.csv", "video"],+ ["audio/mpeg", "README.md", "audio"],+ ["image/png", "data.json", "image"],+ ["application/octet-stream", "manual.pdf", "pdf"],+ ["application/octet-stream", "clip.mp4", "video"],+ ["application/octet-stream", "note.mp3", "audio"],+ ["application/octet-stream", "shot.png", "image"],+ ])("keeps %s / %s media previews independent of the text whitelist", (contentType, filename, kind) => {+ vi.spyOn(TEXT_PREVIEW_CONTENT_TYPE_PREFIXES, Symbol.iterator)+ .mockImplementation(() => new Set<string>().values());+ vi.spyOn(TEXT_PREVIEW_CONTENT_TYPES, "has").mockReturnValue(false);+ vi.spyOn(TEXT_PREVIEW_EXTENSIONS, "has").mockReturnValue(false);+ vi.spyOn(TEXT_PREVIEW_BASENAMES, "has").mockReturnValue(false);++ expect(getPreviewKind(contentType, filename)).toBe(kind);+ });});diff --git a/packages/views/editor/utils/preview.ts b/packages/views/editor/utils/preview.tsindex 9c69854b54..96a16382e3 100644--- a/packages/views/editor/utils/preview.ts+++ b/packages/views/editor/utils/preview.ts@@ -4,15 +4,20 @@* Add new previewable kinds here. To add a type:* 1. Add a new branch returning a new PreviewKind literal.* 2. Add the corresponding renderer in attachment-preview-modal.tsx's dispatch.- * 3. If the renderer needs the file body as text, also extend isTextPreviewable- * in server/internal/handler/file.go so the proxy endpoint accepts it, and- * add the type to the case table both sides test (preview.test.ts and- * TestIsTextPreviewable in file_test.go).+ * 3. If the renderer needs the file body as text, update+ * server/internal/handler/attachment_text_preview.json and regenerate the+ * TypeScript whitelist so the proxy endpoint accepts it too.* 4. If the renderer fetches a binary, decide whether to use download_url* (CloudFront, no auth on the client side) or a new authenticated proxy.*/import { isImageAttachment } from "@multica/core/attachments/image-sequence";+import {+ TEXT_PREVIEW_BASENAMES,+ TEXT_PREVIEW_CONTENT_TYPE_PREFIXES,+ TEXT_PREVIEW_CONTENT_TYPES,+ TEXT_PREVIEW_EXTENSIONS,+} from "./text-preview-whitelist.generated";export type PreviewKind =| "image"@@ -100,47 +105,6 @@ const BASENAME_LANGUAGE_MAP: Record<string, string> = {".gitignore": "plaintext",};-// IMPORTANT — KEEP IN SYNC with isTextPreviewable() in-// server/internal/handler/file.go. If an extension lands here but the proxy-// rejects it, the user sees a 415 fallback in the modal. If the proxy accepts-// but this set doesn't, the Eye button doesn't appear at all.-//-// TODO(follow-up): extract to a JSON single-source-of-truth + generator-// (mirror reserved-slugs pattern in server/internal/handler/reserved_slugs.json).-const TEXT_EXTENSIONS = new Set<string>([- "md", "markdown", "txt", "log", "csv", "tsv",- "html", "htm", "json", "jsonl", "ndjson", "xml",- "yml", "yaml", "toml", "ini", "conf",- "dockerfile", "makefile", "gitignore",- "sh", "bash", "zsh",- "py", "rb", "go", "rs",- "ts", "tsx", "js", "jsx", "mjs", "cjs",- "css", "scss", "sass", "less",- "sql",- "java", "kt", "swift",- "c", "cc", "cpp", "h", "hpp",- "cs", "php", "lua", "vim",-]);--const TEXT_CONTENT_TYPES = new Set<string>([- "application/json",- "application/x-ndjson",- "application/javascript",- "application/xml",- "application/x-yaml",- "application/yaml",- "application/toml",- "application/x-sh",- "application/x-httpd-php",-]);--const TEXT_BASENAMES = new Set<string>([- "dockerfile",- "makefile",- ".env",- ".gitignore",-]);-const TABLE_CONTENT_TYPES = new Set<string>(["text/csv","text/tab-separated-values",@@ -194,11 +158,13 @@ function normalizeContentType(contentType: string): string {function isTextLike(contentType: string, filename: string): boolean {const ct = normalizeContentType(contentType);- if (ct.startsWith("text/")) return true;- if (TEXT_CONTENT_TYPES.has(ct)) return true;+ for (const prefix of TEXT_PREVIEW_CONTENT_TYPE_PREFIXES) {+ if (ct.startsWith(prefix)) return true;+ }+ if (TEXT_PREVIEW_CONTENT_TYPES.has(ct)) return true;const ext = extOf(filename);- if (ext && TEXT_EXTENSIONS.has(ext)) return true;- return TEXT_BASENAMES.has(baseOf(filename));+ if (ext && TEXT_PREVIEW_EXTENSIONS.has(ext)) return true;+ return TEXT_PREVIEW_BASENAMES.has(baseOf(filename));}// Dispatch on PreviewKind. New cases go in attachment-preview-modal.tsx;@@ -221,6 +187,9 @@ export function getPreviewKind(// that isTextLike would otherwise catch.if (isImageAttachment(contentType, filename)) return "image";+ // Every text-backed renderer fetches through the same allowlisted proxy.+ if (!isTextLike(contentType, filename)) return null;+// Markdown — covers both the well-typed case and the common// server-side sniffer fallback (text/plain for .md).if (ct === "text/markdown" || ext === "md" || ext === "markdown") {@@ -234,8 +203,7 @@ export function getPreviewKind(}if (structuredFormat(contentType, filename)) return "structured";- if (isTextLike(contentType, filename)) return "text";- return null;+ return "text";}/**diff --git a/packages/views/editor/utils/text-preview-whitelist.generated.ts b/packages/views/editor/utils/text-preview-whitelist.generated.tsnew file mode 100644index 0000000000..070f464bcf--- /dev/null+++ b/packages/views/editor/utils/text-preview-whitelist.generated.ts@@ -0,0 +1,80 @@+// AUTO-GENERATED by scripts/generate-attachment-text-preview.mjs.+// Do not edit by hand — edit+// server/internal/handler/attachment_text_preview.json and run+// `pnpm generate:attachment-text-preview`.++export const TEXT_PREVIEW_CONTENT_TYPE_PREFIXES: ReadonlySet<string> = new Set([+ "text/",+]);++export const TEXT_PREVIEW_CONTENT_TYPES: ReadonlySet<string> = new Set([+ "application/json",+ "application/x-ndjson",+ "application/javascript",+ "application/xml",+ "application/x-yaml",+ "application/yaml",+ "application/toml",+ "application/x-sh",+ "application/x-httpd-php",+]);++export const TEXT_PREVIEW_EXTENSIONS: ReadonlySet<string> = new Set([+ "md",+ "markdown",+ "txt",+ "log",+ "csv",+ "tsv",+ "html",+ "htm",+ "json",+ "jsonl",+ "ndjson",+ "xml",+ "yml",+ "yaml",+ "toml",+ "ini",+ "conf",+ "dockerfile",+ "makefile",+ "gitignore",+ "sh",+ "bash",+ "zsh",+ "py",+ "rb",+ "go",+ "rs",+ "ts",+ "tsx",+ "js",+ "jsx",+ "mjs",+ "cjs",+ "css",+ "scss",+ "sass",+ "less",+ "sql",+ "java",+ "kt",+ "swift",+ "c",+ "cc",+ "cpp",+ "h",+ "hpp",+ "cs",+ "php",+ "lua",+ "vim",+]);++export const TEXT_PREVIEW_BASENAMES: ReadonlySet<string> = new Set([+ "dockerfile",+ "makefile",+ ".env",+ ".gitignore",+]);diff --git a/scripts/ci-scope.test.mjs b/scripts/ci-scope.test.mjsindex 90963d0ea8..fcb2995ac0 100644--- a/scripts/ci-scope.test.mjs+++ b/scripts/ci-scope.test.mjs@@ -34,6 +34,8 @@ for (const [name, files, selected] of [["cleanup script", ["scripts/drop-database.sh"], ["scripts"]],["check script regression tests", ["scripts/check.test.sh"], ["scripts"]],["performance harness", ["scripts/perf-compare.test.sh"], ["scripts"]],+ ["attachment preview source", ["server/internal/handler/attachment_text_preview.json"], ["backend", "runtime", "scripts"]],+ ["attachment preview output", ["packages/views/editor/utils/text-preview-whitelist.generated.ts"], ["frontend", "quality", "scripts"]],["reserved slug source", ["server/internal/handler/reserved_slugs.json"], ["backend", "runtime", "scripts"]],["reserved slug output", ["packages/core/paths/reserved-slugs.ts"], ["frontend", "quality", "scripts"]],["integration key gates", ["server/cmd/server/router.go"], ["backend", "runtime", "scripts"]],diff --git a/scripts/generate-attachment-text-preview.mjs b/scripts/generate-attachment-text-preview.mjsnew file mode 100644index 0000000000..1e7a1d85b2--- /dev/null+++ b/scripts/generate-attachment-text-preview.mjs@@ -0,0 +1,76 @@+#!/usr/bin/env node+// Regenerates the TypeScript attachment text-preview whitelist from the JSON+// source embedded by the Go handler.++import { readFileSync, writeFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const jsonPath = resolve(+ repoRoot,+ "server/internal/handler/attachment_text_preview.json",+);+const tsPath = resolve(+ repoRoot,+ "packages/views/editor/utils/text-preview-whitelist.generated.ts",+);++const data = JSON.parse(readFileSync(jsonPath, "utf8"));+const fields = [+ ["content_type_prefixes", "TEXT_PREVIEW_CONTENT_TYPE_PREFIXES"],+ ["content_types", "TEXT_PREVIEW_CONTENT_TYPES"],+ ["extensions", "TEXT_PREVIEW_EXTENSIONS"],+ ["basenames", "TEXT_PREVIEW_BASENAMES"],+];++for (const [jsonName] of fields) {+ validateStringList(jsonName, data[jsonName]);+}++const lines = [+ "// AUTO-GENERATED by scripts/generate-attachment-text-preview.mjs.",+ "// Do not edit by hand — edit",+ "// server/internal/handler/attachment_text_preview.json and run",+ "// `pnpm generate:attachment-text-preview`.",+ "",+];++for (const [jsonName, exportName] of fields) {+ lines.push(`export const ${exportName}: ReadonlySet<string> = new Set([`);+ for (const value of data[jsonName]) {+ lines.push(` ${JSON.stringify(value)},`);+ }+ lines.push("]);");+ lines.push("");+}++writeFileSync(tsPath, lines.join("\n"));++function validateStringList(name, value) {+ if (!Array.isArray(value) || value.length === 0) {+ throw new Error(+ `attachment_text_preview.json: "${name}" must be a non-empty array`,+ );+ }++ const seen = new Set();+ for (const entry of value) {+ if (+ typeof entry !== "string" ||+ entry.length === 0 ||+ entry !== entry.trim() ||+ entry !== entry.toLowerCase()+ ) {+ throw new Error(+ `attachment_text_preview.json: "${name}" entries must be non-empty, trimmed lowercase strings`,+ );+ }+ if (seen.has(entry)) {+ throw new Error(+ `attachment_text_preview.json: duplicate ${name} entry ${JSON.stringify(entry)}`,+ );+ }+ seen.add(entry);+ }+}diff --git a/server/internal/handler/attachment_text_preview.go b/server/internal/handler/attachment_text_preview.gonew file mode 100644index 0000000000..2d77101ae3--- /dev/null+++ b/server/internal/handler/attachment_text_preview.go@@ -0,0 +1,130 @@+package handler++import (+ _ "embed"+ "encoding/json"+ "fmt"+ "path"+ "strings"+)++//go:embed attachment_text_preview.json+var attachmentTextPreviewJSON []byte++var attachmentTextPreview = mustLoadAttachmentTextPreviewWhitelist()++type attachmentTextPreviewFile struct {+ ContentTypePrefixes []string `json:"content_type_prefixes"`+ ContentTypes []string `json:"content_types"`+ Extensions []string `json:"extensions"`+ Basenames []string `json:"basenames"`+}++type attachmentTextPreviewWhitelist struct {+ contentTypePrefixes []string+ contentTypes map[string]struct{}+ extensions map[string]struct{}+ basenames map[string]struct{}+}++func mustLoadAttachmentTextPreviewWhitelist() attachmentTextPreviewWhitelist {+ whitelist, err := parseAttachmentTextPreviewWhitelist(attachmentTextPreviewJSON)+ if err != nil {+ panic("handler: parse attachment_text_preview.json: " + err.Error())+ }+ return whitelist+}++func parseAttachmentTextPreviewWhitelist(raw []byte) (attachmentTextPreviewWhitelist, error) {+ var data attachmentTextPreviewFile+ if err := json.Unmarshal(raw, &data); err != nil {+ return attachmentTextPreviewWhitelist{}, err+ }++ _, err := validateAttachmentTextPreviewEntries(+ "content_type_prefixes",+ data.ContentTypePrefixes,+ func(value string) bool { return strings.HasSuffix(value, "/") },+ )+ if err != nil {+ return attachmentTextPreviewWhitelist{}, err+ }+ contentTypes, err := validateAttachmentTextPreviewEntries(+ "content_types",+ data.ContentTypes,+ func(value string) bool { return strings.Contains(value, "/") && !strings.Contains(value, ";") },+ )+ if err != nil {+ return attachmentTextPreviewWhitelist{}, err+ }+ extensions, err := validateAttachmentTextPreviewEntries(+ "extensions",+ data.Extensions,+ func(value string) bool {+ return !strings.HasPrefix(value, ".") && !strings.ContainsAny(value, `/\`)+ },+ )+ if err != nil {+ return attachmentTextPreviewWhitelist{}, err+ }+ basenames, err := validateAttachmentTextPreviewEntries(+ "basenames",+ data.Basenames,+ func(value string) bool { return path.Base(value) == value },+ )+ if err != nil {+ return attachmentTextPreviewWhitelist{}, err+ }++ return attachmentTextPreviewWhitelist{+ contentTypePrefixes: data.ContentTypePrefixes,+ contentTypes: contentTypes,+ extensions: extensions,+ basenames: basenames,+ }, nil+}++func validateAttachmentTextPreviewEntries(+ name string,+ entries []string,+ valid func(string) bool,+) (map[string]struct{}, error) {+ if len(entries) == 0 {+ return nil, fmt.Errorf("%s must be a non-empty array", name)+ }++ out := make(map[string]struct{}, len(entries))+ for _, entry := range entries {+ if entry == "" || entry != strings.TrimSpace(entry) || entry != strings.ToLower(entry) || !valid(entry) {+ return nil, fmt.Errorf("%s entry %q is invalid", name, entry)+ }+ if _, exists := out[entry]; exists {+ return nil, fmt.Errorf("%s contains duplicate entry %q", name, entry)+ }+ out[entry] = struct{}{}+ }+ return out, nil+}++func (w attachmentTextPreviewWhitelist) allows(contentType, filename string) bool {+ contentType = strings.ToLower(strings.TrimSpace(contentType))+ if idx := strings.Index(contentType, ";"); idx >= 0 {+ contentType = strings.TrimSpace(contentType[:idx])+ }+ for _, prefix := range w.contentTypePrefixes {+ if strings.HasPrefix(contentType, prefix) {+ return true+ }+ }+ if _, ok := w.contentTypes[contentType]; ok {+ return true+ }++ base := strings.ToLower(path.Base(strings.ReplaceAll(filename, `\`, "/")))+ extension := strings.TrimPrefix(path.Ext(base), ".")+ if _, ok := w.extensions[extension]; extension != "" && ok {+ return true+ }+ _, ok := w.basenames[base]+ return ok+}diff --git a/server/internal/handler/attachment_text_preview.json b/server/internal/handler/attachment_text_preview.jsonnew file mode 100644index 0000000000..c272cc4212--- /dev/null+++ b/server/internal/handler/attachment_text_preview.json@@ -0,0 +1,75 @@+{+ "$comment": "Source of truth for attachment types served by the authenticated text-preview endpoint. Edit this file only. The Go handler embeds it directly; packages/views/editor/utils/text-preview-whitelist.generated.ts is regenerated by `pnpm generate:attachment-text-preview`. CI fails when the generated TypeScript output is stale.",+ "content_type_prefixes": [+ "text/"+ ],+ "content_types": [+ "application/json",+ "application/x-ndjson",+ "application/javascript",+ "application/xml",+ "application/x-yaml",+ "application/yaml",+ "application/toml",+ "application/x-sh",+ "application/x-httpd-php"+ ],+ "extensions": [+ "md",+ "markdown",+ "txt",+ "log",+ "csv",+ "tsv",+ "html",+ "htm",+ "json",+ "jsonl",+ "ndjson",+ "xml",+ "yml",+ "yaml",+ "toml",+ "ini",+ "conf",+ "dockerfile",+ "makefile",+ "gitignore",+ "sh",+ "bash",+ "zsh",+ "py",+ "rb",+ "go",+ "rs",+ "ts",+ "tsx",+ "js",+ "jsx",+ "mjs",+ "cjs",+ "css",+ "scss",+ "sass",+ "less",+ "sql",+ "java",+ "kt",+ "swift",+ "c",+ "cc",+ "cpp",+ "h",+ "hpp",+ "cs",+ "php",+ "lua",+ "vim"+ ],+ "basenames": [+ "dockerfile",+ "makefile",+ ".env",+ ".gitignore"+ ]+}diff --git a/server/internal/handler/attachment_text_preview_test.go b/server/internal/handler/attachment_text_preview_test.gonew file mode 100644index 0000000000..d2d6383118--- /dev/null+++ b/server/internal/handler/attachment_text_preview_test.go@@ -0,0 +1,82 @@+package handler++import (+ "fmt"+ "testing"+)++func TestAttachmentTextPreviewEmbeddedWhitelist(t *testing.T) {+ for _, prefix := range attachmentTextPreview.contentTypePrefixes {+ t.Run("prefix/"+prefix, func(t *testing.T) {+ if !isTextPreviewable(prefix+"plain", "payload.bin") {+ t.Fatalf("content type prefix %q was not accepted", prefix)+ }+ })+ }+ for contentType := range attachmentTextPreview.contentTypes {+ t.Run("content-type/"+contentType, func(t *testing.T) {+ if !isTextPreviewable(contentType, "payload") {+ t.Fatalf("content type %q was not accepted", contentType)+ }+ })+ }+ for extension := range attachmentTextPreview.extensions {+ t.Run("extension/"+extension, func(t *testing.T) {+ filename := "source." + extension+ if !isTextPreviewable("application/octet-stream", filename) {+ t.Fatalf("extension %q was not accepted", extension)+ }+ })+ }+ for basename := range attachmentTextPreview.basenames {+ t.Run("basename/"+basename, func(t *testing.T) {+ if !isTextPreviewable("application/octet-stream", basename) {+ t.Fatalf("basename %q was not accepted", basename)+ }+ })+ }+}++func TestAttachmentTextPreviewNormalizesInputs(t *testing.T) {+ for _, tc := range []struct {+ contentType string+ filename string+ }{+ {"Application/JSON; Charset=UTF-8", "payload"},+ {"application/octet-stream", `nested\MAIN.GO`},+ {"application/octet-stream", "nested/Dockerfile"},+ } {+ t.Run(fmt.Sprintf("%s/%s", tc.contentType, tc.filename), func(t *testing.T) {+ if !isTextPreviewable(tc.contentType, tc.filename) {+ t.Fatalf("isTextPreviewable(%q, %q) = false, want true", tc.contentType, tc.filename)+ }+ })+ }+}++func TestParseAttachmentTextPreviewWhitelistRejectsInvalidSources(t *testing.T) {+ for _, tc := range []struct {+ name string+ raw string+ }{+ {"malformed JSON", `{`},+ {+ "missing list",+ `{"content_type_prefixes":["text/"],"content_types":["application/json"],"extensions":["txt"]}`,+ },+ {+ "duplicate entry",+ `{"content_type_prefixes":["text/"],"content_types":["application/json","application/json"],"extensions":["txt"],"basenames":["makefile"]}`,+ },+ {+ "non-normalized entry",+ `{"content_type_prefixes":["text/"],"content_types":["Application/JSON"],"extensions":["txt"],"basenames":["makefile"]}`,+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ if _, err := parseAttachmentTextPreviewWhitelist([]byte(tc.raw)); err == nil {+ t.Fatal("parseAttachmentTextPreviewWhitelist() error = nil, want error")+ }+ })+ }+}diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 5a8d26c597..2282f28e5f 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -1345,70 +1345,11 @@ func (h *Handler) GetAttachmentContent(w http.ResponseWriter, r *http.Request) {// isTextPreviewable is the whitelist for the text preview proxy.//-// IMPORTANT — KEEP IN SYNC with the client-side mirror in-// packages/views/editor/utils/preview.ts (TEXT_EXTENSIONS / TEXT_CONTENT_TYPES-// / TEXT_BASENAMES + extensionToLanguage). If a type is allowed here but not-// mapped client-side the user sees raw unhighlighted text; if mapped client-side-// but rejected here the user sees a 415 fallback.-//-// TODO(follow-up): extract this list to a JSON single-source-of-truth and-// generate the TS side, mirroring the reserved-slugs pattern (see-// server/internal/handler/reserved_slugs.json + scripts/generate-reserved-slugs.mjs).-// Drift severity here is low (worst case: Eye button visible but proxy 415s,-// modal shows the unsupported fallback — still functional, just confusing),-// so it ships as manual hand-sync for v1.-//-// We check both content_type and extension because http.DetectContentType-// regularly returns "text/plain" for Markdown / source code, so a pure-// content-type check would 415 those.+// The Go handler embeds attachment_text_preview.json directly. The client+// imports a generated representation of the same source, and CI rejects stale+// generated output.func isTextPreviewable(contentType, filename string) bool {- ct := strings.ToLower(strings.TrimSpace(contentType))- // Strip params (e.g. "text/plain; charset=utf-8")- if idx := strings.Index(ct, ";"); idx >= 0 {- ct = strings.TrimSpace(ct[:idx])- }- if strings.HasPrefix(ct, "text/") {- return true- }- switch ct {- case "application/json",- "application/x-ndjson",- "application/javascript",- "application/xml",- "application/x-yaml",- "application/yaml",- "application/toml",- "application/x-sh",- "application/x-httpd-php":- return true- }-- ext := strings.ToLower(path.Ext(filename))- switch ext {- case ".md", ".markdown",- ".txt", ".log",- ".csv", ".tsv",- ".html", ".htm",- ".json", ".jsonl", ".ndjson", ".xml",- ".yml", ".yaml", ".toml", ".ini", ".conf",- ".sh", ".bash", ".zsh",- ".py", ".rb", ".go", ".rs",- ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",- ".css", ".scss", ".sass", ".less",- ".sql",- ".java", ".kt", ".swift",- ".c", ".cc", ".cpp", ".h", ".hpp",- ".cs", ".php", ".lua", ".vim",- ".dockerfile", ".makefile", ".gitignore":- return true- }- // Filenames without extension that match well-known build files.- base := strings.ToLower(path.Base(filename))- switch base {- case "dockerfile", "makefile", ".env":- return true- }- return false+ return attachmentTextPreview.allows(contentType, filename)}// DeleteAttachment — DELETE /api/attachments/{id}diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.goindex df2ee4e77d..8bdd4d4b8e 100644--- a/server/internal/handler/file_test.go+++ b/server/internal/handler/file_test.go@@ -1682,10 +1682,8 @@ func TestGetAttachmentContent_NotFound(t *testing.T) {}}-// isTextPreviewable is the whitelist linkpin between the proxy and the-// client-side dispatcher. Regress against the most common content types so-// drifting one of the lists alone fails loud. The same table runs against the-// client in packages/views/editor/utils/preview.test.ts — change both.+// Regress representative text-preview inputs in addition to the exhaustive+// source-driven checks in attachment_text_preview_test.go.func TestIsTextPreviewable(t *testing.T) {t.Helper()cases := []struct {