AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(api): 修复备份附件恢复引起的 XSS (#701) (#711)
LuoQianhongdc5a55a1c26d
diff --git a/apps/api/package.json b/apps/api/package.jsonindex e2f173a2..4be49132 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -4,6 +4,7 @@"private": true,"type": "module","dependencies": {- "@edgeever/public-network": "workspace:*"+ "@edgeever/public-network": "workspace:*",+ "content-type": "3.1.1"}}diff --git a/apps/api/src/backup-routes.ts b/apps/api/src/backup-routes.tsindex cc62c5cb..e5a67c6e 100644--- a/apps/api/src/backup-routes.ts+++ b/apps/api/src/backup-routes.ts@@ -25,6 +25,7 @@ import {MAX_IMAGE_UPLOAD_BYTES,mapResource,normalizeFilename,+ validateRestoredResourceMimeType,type ResourceRow,} from "./resource-service";import { getWorkspaceId, requireScopes, requireUser } from "./request-auth";@@ -489,6 +490,9 @@ export const registerBackupRoutes = (return apiError(context, "upload_too_large", "Backup resource size is invalid.", 413);}+ const mimeType = metadata.mimeType ?? file.type ?? "application/octet-stream";+ validateRestoredResourceMimeType(metadata.kind, mimeType, file.size);+const filename = normalizeFilename(metadata.filename || file.name) || `${metadata.kind}-${metadata.id}`;const objectKey = `workspaces/${workspaceId}/restores/${metadata.memoId}/${metadata.id}/${Date.now()}-${filename}`;const bytes = new Uint8Array(await file.arrayBuffer());@@ -511,7 +515,7 @@ export const registerBackupRoutes = (const destination = await resolveObjectStorage(context.env);await destination.store.put(objectKey, bytes, {- httpMetadata: { contentType: metadata.mimeType ?? file.type ?? "application/octet-stream" },+ httpMetadata: { contentType: mimeType },customMetadata: { memoId: metadata.memoId, resourceId: metadata.id, restored: "true" },});@@ -547,7 +551,7 @@ export const registerBackupRoutes = (objectKey,destination.configId,metadata.kind,- metadata.mimeType ?? file.type ?? null,+ mimeType,filename,bytes.byteLength,await dependencies.sha256Bytes(bytes),diff --git a/apps/api/src/resource-restore-security.test.mjs b/apps/api/src/resource-restore-security.test.mjsnew file mode 100644index 00000000..2cd6d9f9--- /dev/null+++ b/apps/api/src/resource-restore-security.test.mjs@@ -0,0 +1,424 @@+import { afterEach, describe, expect, test } from "bun:test";+import { Database } from "bun:sqlite";+import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { parseEdgeEverZip, restoreEdgeEverZip } from "@edgeever/shared/backup-archive";+import { createEdgeEverClient } from "../../../packages/client/src/index.ts";+import { fetchEdgeEverApp } from "./index.ts";+import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";++const fixtures = [];+const html = "<!doctype html><p>Untrusted attachment</p>";+const png = Uint8Array.from(Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=", "base64"));+const executionContext = { waitUntil() {}, passThroughOnException() {} };++afterEach(async () => {+ for (const { database, directory, server } of fixtures.splice(0)) {+ server?.stop(true);+ database.close();+ await rm(directory, { recursive: true, force: true });+ }+});++const fixture = async () => {+ const directory = await mkdtemp(join(tmpdir(), "edgeever-701-test-"));+ const database = new Database(":memory:");+ const cleanup = { database, directory };+ fixtures.push(cleanup);+ database.exec("PRAGMA foreign_keys = ON");+ const migrations = new URL("../../../migrations/", import.meta.url);+ for (const name of (await readdir(migrations)).filter((name) => name.endsWith(".sql")).sort()) {+ database.exec(await readFile(new URL(name, migrations), "utf8"));+ }+ database.run("INSERT OR IGNORE INTO workspaces (id, name, is_personal) VALUES ('ws_default', 'Personal', 1)");+ const environment = {+ storage: createSelfHostedStorageAdapter(database, directory),+ EDGE_EVER_ALLOW_UNAUTHENTICATED: "true",+ EDGE_EVER_RUNTIME: "self-hosted-bun",+ };+ const request = (path, init = {}) => fetchEdgeEverApp(new Request(`http://edgeever.test${path}`, init), environment, executionContext);+ const json = async (path, body, method = "POST") => {+ const response = await request(path, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });+ const result = await response.json();+ if (!response.ok) throw new Error(`${response.status}: ${JSON.stringify(result)}`);+ return result;+ };+ const { notebook } = await json("/api/v1/notebooks", { name: "Security regression" });+ const { memo } = await json("/api/v1/memos", { notebookId: notebook.id, title: "Restore regression", contentMarkdown: "Original note" });+ const metadata = (overrides = {}) => ({+ id: "res_security", memoId: memo.id, originalMemoId: null, kind: "image", mimeType: "image/png",+ filename: "resource.png", byteSize: png.length, sha256: null, width: 1, height: 1,+ createdAt: "2026-08-31T00:00:00.000Z", updatedAt: "2026-08-31T00:00:00.000Z",+ archivePath: "resources/resource.png", ...overrides,+ });+ const restore = (resource, bytes = png, type = resource.mimeType ?? "application/octet-stream") => {+ const form = new FormData();+ form.set("metadata", JSON.stringify(resource));+ form.set("file", new File([bytes], resource.filename ?? "resource", { type }));+ return request(`/api/v1/restores/json/resources/${resource.id}`, { method: "PUT", body: form });+ };+ const resourceRow = () => database.query("SELECT * FROM resources WHERE id = 'res_security'").get();+ const serve = () => {+ cleanup.server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: (request) => fetchEdgeEverApp(request, environment, executionContext) });+ return cleanup.server.url.origin;+ };+ return { directory, database, environment, request, json, notebook, memo, metadata, restore, resourceRow, serve };+};++describe("restored resource security", () => {+ for (const mimeType of ["text/html", "application/xhtml+xml", "image/unknown", null]) {+ test(`legacy image restore rejects ${mimeType ?? "HTML file MIME fallback"} without replacing existing bytes`, async () => {+ const f = await fixture();+ expect((await f.restore(f.metadata())).status).toBe(200);+ const previous = f.resourceRow();+ const response = await f.restore(f.metadata({ mimeType, filename: "resource.html", byteSize: html.length }), html, "text/html");+ expect(response.status).toBe(415);+ expect(await response.json()).toMatchObject({ error: { code: "unsupported_media_type" } });+ expect(f.resourceRow()).toEqual(previous);+ expect(new Uint8Array(await readFile(join(f.directory, previous.object_key)))).toEqual(png);+ });+ }++ for (const mimeType of ["text/html", "application/xhtml+xml"]) {+ test(`resumable image restore rejects ${mimeType} before creating a multipart upload`, async () => {+ const f = await fixture();+ const previousObjects = await readdir(f.directory, { recursive: true });+ const response = await f.request("/api/v1/restores/json/resources/res_security/uploads", {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify(f.metadata({ mimeType, filename: "resource.html", byteSize: html.length })),+ });+ expect(response.status).toBe(415);+ expect(await response.json()).toMatchObject({ error: { code: "unsupported_media_type" } });+ expect(f.database.query("SELECT COUNT(*) AS count FROM resource_uploads").get().count).toBe(0);+ expect(f.resourceRow()).toBeNull();+ expect(await readdir(f.directory, { recursive: true })).toEqual(previousObjects);+ });+ }++ for (const mode of ["legacy", "resumable"]) {+ for (const mimeType of [null, "", "application/octet-stream"]) {+ test(`${mode} preserves unknown image MIME ${JSON.stringify(mimeType)} as a download`, async () => {+ const f = await fixture();+ const metadata = f.metadata({ mimeType, filename: "unknown.bin" });+ if (mode === "legacy") {+ expect((await f.restore(metadata, png, "application/octet-stream")).status).toBe(200);+ } else {+ const client = createEdgeEverClient({ baseUrl: f.serve() });+ await client.restoreJsonResource(metadata.id, metadata, new Blob([png]));+ }+ expect(f.resourceRow().mime_type).toBe(mimeType ?? "application/octet-stream");+ const response = await f.request("/api/v1/resources/res_security/blob");+ expect(response.headers.get("Content-Disposition")).toStartWith("attachment;");+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(png);+ });+ }+ }++ for (const mimeType of ["application/pdf", "audio/mpeg", "video/mp4"]) {+ test(`untyped attachments with ${mimeType} object metadata keep their download behavior`, async () => {+ const f = await fixture();+ const token = "s".repeat(43);+ const notebookToken = "n".repeat(43);+ f.database.run("INSERT INTO memo_shares (id, memo_id, workspace_id, token) VALUES ('security_share', ?, 'ws_default', ?)", [f.memo.id, token]);+ f.database.run("INSERT INTO notebook_shares (id, notebook_id, workspace_id, token) VALUES ('security_notebook', ?, 'ws_default', ?)", [f.notebook.id, notebookToken]);+ await f.environment.storage.resources.put("legacy-attachment", Uint8Array.of(65, 66));+ const getObject = f.environment.storage.resources.get.bind(f.environment.storage.resources);+ f.environment.storage.resources.get = async (...args) => {+ const object = await getObject(...args);+ object.writeHttpMetadata = (headers) => headers.set("Content-Type", mimeType);+ return object;+ };+ f.database.run("INSERT INTO resources (id, memo_id, object_key, kind, mime_type, filename, byte_size) VALUES ('res_security', ?, 'legacy-attachment', 'attachment', NULL, 'untitled.bin', 2)", [f.memo.id]);+ for (const path of [+ "/api/v1/resources/res_security/blob",+ `/api/public/shares/${token}/resources/res_security/blob`,+ `/api/public/notebook-shares/${notebookToken}/resources/res_security/blob`,+ ]) {+ const response = await f.request(path);+ expect(response.status).toBe(200);+ expect(response.headers.get("Content-Type")).toBe(mimeType);+ expect(response.headers.get("Content-Disposition")).toStartWith("attachment;");+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(Uint8Array.of(65, 66));+ }+ });+ }++ test("completion rejects an incompatible restore session persisted before the fix, before assembling or overwriting its object", async () => {+ const f = await fixture();+ expect((await f.restore(f.metadata())).status).toBe(200);+ const previous = f.resourceRow();+ const metadata = f.metadata({ kind: "attachment", mimeType: "text/html", filename: "resource.html", byteSize: html.length });+ const { upload } = await f.json("/api/v1/restores/json/resources/res_security/uploads", metadata);+ // This is the exact persisted metadata shape accepted by the old restore path.+ f.database.run("UPDATE resource_uploads SET kind = 'image', restore_metadata_json = ? WHERE id = ?", [JSON.stringify({ ...metadata, kind: "image" }), upload.id]);+ const session = f.database.query("SELECT * FROM resource_uploads WHERE id = ?").get(upload.id);+ const part = await f.request(`/api/v1/resource-uploads/${upload.id}/parts/1`, {+ method: "PUT", headers: { "Content-Type": "application/octet-stream", "Content-Length": String(html.length) }, body: html,+ });+ expect(part.status).toBe(200);+ const response = await f.request(`/api/v1/resource-uploads/${upload.id}/complete`, { method: "POST" });+ expect(response.status).toBe(415);+ expect(await response.json()).toMatchObject({ error: { code: "unsupported_media_type" } });+ expect(f.resourceRow()).toEqual(previous);+ expect(await Bun.file(join(f.directory, session.object_key)).exists()).toBe(false);+ expect(new Uint8Array(await readFile(join(f.directory, previous.object_key)))).toEqual(png);+ });++ for (const mimeType of ["text/html", "application/xhtml+xml", "TEXT/HTML; charset=utf-8", null]) {+ test(`legacy image rows with ${mimeType ?? "HTML object metadata"} download through authenticated and both public routes`, async () => {+ const f = await fixture();+ const token = "s".repeat(43);+ const notebookToken = "n".repeat(43);+ f.database.run("INSERT INTO memo_shares (id, memo_id, workspace_id, token) VALUES ('security_share', ?, 'ws_default', ?)", [f.memo.id, token]);+ f.database.run("INSERT INTO notebook_shares (id, notebook_id, workspace_id, token) VALUES ('security_notebook', ?, 'ws_default', ?)", [f.notebook.id, notebookToken]);+ await f.environment.storage.resources.put("legacy-html", new TextEncoder().encode(html), { httpMetadata: { contentType: "text/html" } });+ // Unlike R2/S3, the filesystem adapter does not persist HTTP metadata.+ const getObject = f.environment.storage.resources.get.bind(f.environment.storage.resources);+ f.environment.storage.resources.get = async (...args) => {+ const object = await getObject(...args);+ object.writeHttpMetadata = (headers) => headers.set("Content-Type", "text/html");+ return object;+ };+ f.database.run("INSERT INTO resources (id, memo_id, object_key, kind, mime_type, filename, byte_size) VALUES ('res_security', ?, 'legacy-html', 'image', ?, 'resource.html', ?)", [f.memo.id, mimeType, html.length]);+ for (const path of [+ "/api/v1/resources/res_security/blob",+ `/api/public/shares/${token}/resources/res_security/blob`,+ `/api/public/notebook-shares/${notebookToken}/resources/res_security/blob`,+ ]) {+ const response = await f.request(path);+ expect(response.status).toBe(200);+ expect(response.headers.get("Content-Disposition")).toStartWith("attachment;");+ expect(response.headers.get("Content-Type")).toBe(mimeType === "TEXT/HTML; charset=utf-8" ? "text/html; charset=utf-8" : mimeType ?? "text/html");+ expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff");+ expect(await response.text()).toBe(html);+ }+ });+ }++ test("legacy image restores accept image MIME parameters and a valid file MIME fallback without rewriting metadata", async () => {+ const f = await fixture();+ for (const mimeType of ["IMAGE/PNG; charset=binary", null]) {+ const response = await f.restore(f.metadata({ mimeType }), png, "image/png");+ expect(response.status).toBe(200);+ expect(f.resourceRow().mime_type).toBe(mimeType ?? "image/png");+ const blob = await f.request("/api/v1/resources/res_security/blob");+ expect(blob.headers.get("Content-Disposition")).toStartWith("inline;");+ expect(new Uint8Array(await blob.arrayBuffer())).toEqual(png);+ }+ });++ test("HTML remains a downloadable attachment through legacy and resumable restores", async () => {+ const f = await fixture();+ const metadata = f.metadata({ kind: "attachment", mimeType: "text/html", filename: "resource.html", byteSize: html.length });+ expect((await f.restore(metadata, html)).status).toBe(200);+ const { upload } = await f.json("/api/v1/restores/json/resources/res_security/uploads", metadata);+ expect((await f.request(`/api/v1/resource-uploads/${upload.id}/parts/1`, {+ method: "PUT", headers: { "Content-Type": "application/octet-stream", "Content-Length": String(html.length) }, body: html,+ })).status).toBe(200);+ await f.json(`/api/v1/resource-uploads/${upload.id}/complete`, {});+ const blob = await f.request("/api/v1/resources/res_security/blob");+ expect(blob.headers.get("Content-Disposition")).toStartWith("attachment;");+ expect(await blob.text()).toBe(html);+ });++ test("resumable image restores validate MIME without rewriting its parameters", async () => {+ const f = await fixture();+ const { upload } = await f.json("/api/v1/restores/json/resources/res_security/uploads", f.metadata({ mimeType: "IMAGE/PNG; charset=binary" }));+ expect(f.database.query("SELECT mime_type FROM resource_uploads WHERE id = ?").get(upload.id).mime_type).toBe("IMAGE/PNG; charset=binary");+ expect((await f.request(`/api/v1/resource-uploads/${upload.id}/parts/1`, {+ method: "PUT", headers: { "Content-Type": "application/octet-stream", "Content-Length": String(png.length) }, body: png,+ })).status).toBe(200);+ await f.json(`/api/v1/resource-uploads/${upload.id}/complete`, {});+ expect(f.resourceRow().mime_type).toBe("IMAGE/PNG; charset=binary");+ expect(new Uint8Array(await readFile(join(f.directory, f.resourceRow().object_key)))).toEqual(png);+ });++ test("SVG encoding parameters and bytes survive both restore paths", async () => {+ const mimeType = "image/svg+xml; charset=utf-16le";+ const bytes = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><text>旧备份</text></svg>', "utf16le");+ for (const mode of ["legacy", "resumable"]) {+ const f = await fixture();+ const metadata = f.metadata({ mimeType, filename: "encoded.svg", byteSize: bytes.length });+ if (mode === "legacy") expect((await f.restore(metadata, bytes)).status).toBe(200);+ else await createEdgeEverClient({ baseUrl: f.serve() }).restoreJsonResource(metadata.id, metadata, new Blob([bytes]));+ expect(f.resourceRow().mime_type).toBe(mimeType);+ const response = await f.request("/api/v1/resources/res_security/blob");+ expect(response.headers.get("Content-Type")).toBe(mimeType);+ expect(response.headers.get("Content-Disposition")).toStartWith("inline;");+ expect(response.headers.get("Content-Security-Policy")).toContain("sandbox");+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(new Uint8Array(bytes));+ }+ });++ for (const mode of ["legacy", "resumable"]) {+ test(`restores a real v2.12.0-exported archive through the patched ${mode} API`, async () => {+ const f = await fixture();+ const fixtureDirectory = new URL("../../../tests/fixtures/restore-resource-security/", import.meta.url);+ const source = JSON.parse(await readFile(new URL("source.json", fixtureDirectory), "utf8"));+ const backup = await parseEdgeEverZip(new Blob([await readFile(new URL("v2.12.0.zip", fixtureDirectory))]));+ expect(backup.manifest.edgeeverVersion).toBe("2.12.0");+ expect(backup.manifest.buildId).toBe(source.commit);+ const client = createEdgeEverClient({ baseUrl: f.serve() });+ await restoreEdgeEverZip(backup, {+ restoreNotebooks: client.restoreJsonNotebooks,+ restoreMemos: client.restoreJsonMemos,+ restorePrompts: client.restoreJsonAiPrompts,+ createResourceRestoreSink: mode === "resumable" ? client.createJsonResourceRestoreSink : async (_id, metadata) => {+ const chunks = [];+ return {+ write: async (chunk) => { chunks.push(chunk); },+ close: async () => {+ const response = await f.restore(metadata, await new Blob(chunks).arrayBuffer());+ expect(response.status).toBe(200);+ },+ abort: async () => {},+ };+ },+ });+ const restoredMemo = await (await f.request("/api/v1/memos/memo_release")).json();+ expect(restoredMemo.memo).toMatchObject(source.memos[0]);+ const notebooks = await (await f.request("/api/v1/notebooks")).json();+ expect(notebooks.notebooks.find((notebook) => notebook.id === "nb_release")).toMatchObject(source.notebooks[0]);+ const revisions = await (await f.request("/api/v1/memos/memo_release/revisions")).json();+ const { contentJson, ...revisionSummary } = source.revisions[0];+ expect(revisions.revisions).toEqual(expect.arrayContaining([expect.objectContaining(revisionSummary)]));+ expect(JSON.parse(f.database.query("SELECT content_json FROM memo_revisions WHERE id = ?").get(revisionSummary.id).content_json)).toEqual(contentJson);+ for (const resource of source.resources) {+ const row = f.database.query("SELECT * FROM resources WHERE id = ?").get(resource.id);+ expect(row).toMatchObject({ memo_id: resource.memoId, kind: resource.kind, mime_type: resource.mimeType ?? "application/octet-stream", filename: resource.filename, byte_size: resource.byteSize, width: resource.width, height: resource.height, created_at: resource.createdAt });+ const response = await f.request(resource.url);+ expect(response.status).toBe(200);+ expect(response.headers.get("Content-Disposition")).toStartWith(resource.kind === "image" && resource.mimeType ? "inline;" : "attachment;");+ if (resource.mimeType === "image/svg+xml") expect(response.headers.get("Content-Security-Policy")).toContain("sandbox");+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(Uint8Array.from(Buffer.from(resource.bytesBase64, "base64")));+ }+ expect((await (await f.request(`/api/v1/memos/${f.memo.id}`)).json()).memo.contentMarkdown).toBe("Original note");+ });+ }+});++const ambiguousTypes = [+ ["image", "image/png; charset=utf-8, text/html"],+ ["image", 'image/png; note="quoted, value", text/html'],+ ["image", "image/png,"],+ ["attachment", "audio/mpeg; ignored=x, text/html"],+ ["attachment", "video/mp4; ignored=x, application/xhtml+xml"],+ ["attachment", "application/pdf, text/html"],+ ["attachment", "not-a-mime"],+ ["attachment", 'text/plain; note="line\nbreak"'],+ ["image", 'image/png; note="ok"\r\n; charset=utf-8'],+ ["attachment", 'audio/mpeg; charset=utf-8; charset="line\nbreak"'],+ ["attachment", "\r\n"],+];++const seedSharedResource = async (f, { kind, mimeType, filename = "resource.bin", objectMimeType = "application/octet-stream", body = html }) => {+ const token = "s".repeat(43);+ const notebookToken = "n".repeat(43);+ f.database.run("INSERT INTO memo_shares (id, memo_id, workspace_id, token) VALUES ('security_share', ?, 'ws_default', ?)", [f.memo.id, token]);+ f.database.run("INSERT INTO notebook_shares (id, notebook_id, workspace_id, token) VALUES ('security_notebook', ?, 'ws_default', ?)", [f.notebook.id, notebookToken]);+ const bytes = typeof body === "string" ? new TextEncoder().encode(body) : body;+ await f.environment.storage.resources.put("header-regression", bytes);+ const getObject = f.environment.storage.resources.get.bind(f.environment.storage.resources);+ f.environment.storage.resources.get = async (...args) => {+ const object = await getObject(...args);+ object.writeHttpMetadata = (headers) => headers.set("Content-Type", objectMimeType);+ return object;+ };+ f.database.run("INSERT INTO resources (id, memo_id, object_key, kind, mime_type, filename, byte_size) VALUES ('res_security', ?, 'header-regression', ?, ?, ?, ?)", [f.memo.id, kind, mimeType, filename, bytes.length]);+ return [+ "/api/v1/resources/res_security/blob",+ `/api/public/shares/${token}/resources/res_security/blob`,+ `/api/public/notebook-shares/${notebookToken}/resources/res_security/blob`,+ ];+};++describe("single-valued resource content types", () => {+ for (const [kind, mimeType] of ambiguousTypes) {+ for (const mode of ["legacy", "resumable"]) {+ test(`${mode} restore rejects the entire ambiguous ${mimeType} declaration`, async () => {+ const f = await fixture();+ const metadata = f.metadata({ kind, mimeType, filename: "resource.bin", byteSize: html.length });+ const previousObjects = await readdir(f.directory, { recursive: true });+ const response = mode === "legacy"+ ? await f.restore(metadata, html, "application/octet-stream")+ : await f.request("/api/v1/restores/json/resources/res_security/uploads", {+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(metadata),+ });+ expect(response.status).toBe(415);+ expect(await response.json()).toMatchObject({ error: { code: "unsupported_media_type" } });+ expect(f.resourceRow()).toBeNull();+ expect(f.database.query("SELECT COUNT(*) AS count FROM resource_uploads").get().count).toBe(0);+ expect(await readdir(f.directory, { recursive: true })).toEqual(previousObjects);+ });+ }++ test(`legacy ${kind} resource with ${mimeType} downloads on all blob routes`, async () => {+ const f = await fixture();+ const paths = await seedSharedResource(f, { kind, mimeType });+ for (const path of paths) {+ const response = await f.request(path);+ expect(response.status).toBe(200);+ expect(response.headers.get("Content-Type")).toBe("application/octet-stream");+ expect(response.headers.get("Content-Disposition")).toStartWith("attachment;");+ expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff");+ expect(await response.text()).toBe(html);+ }+ });+ }++ for (const [kind, mimeType] of [ambiguousTypes[0], ambiguousTypes[3], ambiguousTypes[ambiguousTypes.length - 2]]) {+ test(`completion revalidates an old ${kind} upload with ambiguous MIME before assembly`, async () => {+ const f = await fixture();+ expect((await f.restore(f.metadata())).status).toBe(200);+ const previous = f.resourceRow();+ const metadata = f.metadata({ kind: "attachment", mimeType: "text/plain", filename: "resource.bin", byteSize: html.length });+ const { upload } = await f.json("/api/v1/restores/json/resources/res_security/uploads", metadata);+ f.database.run("UPDATE resource_uploads SET kind = ?, mime_type = ?, restore_metadata_json = ? WHERE id = ?", [kind, mimeType, JSON.stringify({ ...metadata, kind, mimeType }), upload.id]);+ const session = f.database.query("SELECT object_key FROM resource_uploads WHERE id = ?").get(upload.id);+ expect((await f.request(`/api/v1/resource-uploads/${upload.id}/parts/1`, {+ method: "PUT", headers: { "Content-Type": "application/octet-stream", "Content-Length": String(html.length) }, body: html,+ })).status).toBe(200);+ const response = await f.request(`/api/v1/resource-uploads/${upload.id}/complete`, { method: "POST" });+ expect(response.status).toBe(415);+ expect(await response.json()).toMatchObject({ error: { code: "unsupported_media_type" } });+ expect(f.resourceRow()).toEqual(previous);+ expect(await Bun.file(join(f.directory, session.object_key)).exists()).toBe(false);+ expect(new Uint8Array(await readFile(join(f.directory, previous.object_key)))).toEqual(png);+ });+ }++ test("ambiguous object MIME and a misleading PDF filename cannot enable inline rendering", async () => {+ for (const metadata of [+ { kind: "image", mimeType: null, objectMimeType: ambiguousTypes[0][1] },+ { kind: "attachment", mimeType: null, objectMimeType: ambiguousTypes[3][1] },+ { kind: "image", mimeType: ambiguousTypes[0][1], filename: "resource.pdf" },+ ]) {+ const f = await fixture();+ for (const path of await seedSharedResource(f, metadata)) {+ const response = await f.request(path);+ expect(response.headers.get("Content-Type")).toBe("application/octet-stream");+ expect(response.headers.get("Content-Disposition")).toStartWith("attachment;");+ expect(await response.text()).toBe(html);+ }+ }+ });++ test("quoted commas, semicolons, escaped quotes and SVG charset remain one safely serialized type", async () => {+ const mimeType = 'IMAGE/SVG+XML;\tcharset="utf-16le"; note="a,b; text/html; \\"quoted\\""';+ const header = 'image/svg+xml; charset=utf-16le; note="a,b; text/html; \\"quoted\\""';+ const bytes = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><text>旧备份</text></svg>', "utf16le");+ for (const mode of ["legacy", "resumable"]) {+ const f = await fixture();+ const metadata = f.metadata({ mimeType, filename: "encoded.svg", byteSize: bytes.length });+ if (mode === "legacy") expect((await f.restore(metadata, bytes)).status).toBe(200);+ else await createEdgeEverClient({ baseUrl: f.serve() }).restoreJsonResource(metadata.id, metadata, new Blob([bytes]));+ expect(f.resourceRow().mime_type).toBe(mimeType);+ const response = await f.request("/api/v1/resources/res_security/blob");+ expect(response.headers.get("Content-Type")).toBe(header);+ expect(response.headers.get("Content-Disposition")).toStartWith("inline;");+ expect(response.headers.get("Content-Security-Policy")).toContain("sandbox");+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(new Uint8Array(bytes));+ }+ });+});diff --git a/apps/api/src/resource-routes.ts b/apps/api/src/resource-routes.tsindex 24f59c0d..29e5dcbd 100644--- a/apps/api/src/resource-routes.ts+++ b/apps/api/src/resource-routes.ts@@ -1,4 +1,4 @@-import { resolveResourceUploadMimeType, setSvgResourceSecurityHeaders, isPdfAttachment, resolvePlayableMediaMimeType, ResourceUpdateSchema, type MemoDetail, type Resource } from "@edgeever/shared";+import { resolveResourceUploadMimeType, ResourceUpdateSchema, type MemoDetail, type Resource } from "@edgeever/shared";import { zValidator } from "@hono/zod-validator";import type { Hono } from "hono";import { auditStatement } from "./audit";@@ -10,8 +10,7 @@ import { apiError, badRequest, notFound } from "./http-errors";import { resolveObjectStorage } from "./object-storage";import {SUPPORTED_IMAGE_MIME_TYPES,- contentDispositionAttachment,- contentDispositionInline,+ setResourceContentHeaders,mapResource,mapResourceListItem,mapResourceStorageSummary,@@ -294,13 +293,6 @@ export const registerResourceRoutes = (const headers = new Headers();object.writeHttpMetadata(headers);- const playableMimeType = resolvePlayableMediaMimeType(resource.mime_type, resource.filename);- headers.set(- "Content-Type",- isPdfAttachment(resource.mime_type, resource.filename)- ? "application/pdf"- : playableMimeType ?? resource.mime_type ?? headers.get("Content-Type") ?? "application/octet-stream",- );headers.set("Cache-Control", headers.get("Cache-Control") ?? "private, max-age=3600");headers.set("Accept-Ranges", "bytes");if (byteRange.kind === "range") {@@ -313,14 +305,7 @@ export const registerResourceRoutes = (} else {headers.set("Content-Length", String(resource.byte_size));}- headers.set(- "Content-Disposition",- resource.kind === "image" || isPdfAttachment(resource.mime_type, resource.filename) || playableMimeType- ? contentDispositionInline(resource.filename)- : contentDispositionAttachment(resource.filename),- );- headers.set("X-Content-Type-Options", "nosniff");- setSvgResourceSecurityHeaders(headers);+ setResourceContentHeaders(headers, resource);return new Response(object.body, { headers, status: byteRange.kind === "range" ? 206 : 200 });});diff --git a/apps/api/src/resource-service.ts b/apps/api/src/resource-service.tsindex 265f95a9..54b63a86 100644--- a/apps/api/src/resource-service.ts+++ b/apps/api/src/resource-service.ts@@ -1,9 +1,13 @@import {SUPPORTED_IMAGE_MIME_TYPES,+ isPdfAttachment,+ resolvePlayableMediaMimeType,+ setSvgResourceSecurityHeaders,type Resource,type ResourceListItem,type ResourceStorageSummary,} from "@edgeever/shared";+import { format as formatContentType, parse as parseContentType } from "content-type";import { auditStatement } from "./audit";import type { AppContext, AuditActor, Bindings } from "./api-context";import { AppError } from "./app-error";@@ -105,6 +109,30 @@ export const validateImageUpload = (mimeType: string, size: number) => {}};+// HTTP field bytes: HTAB, visible ASCII and obs-text, never other controls or DEL.+const HTTP_FIELD_VALUE_PATTERN = /^[\t\u0020-\u007e\u0080-\u00ff]*$/;++const parseResourceContentType = (value: string) => {+ if (!HTTP_FIELD_VALUE_PATTERN.test(value)) return null;+ if (!value.trim()) return { type: "application/octet-stream", header: "application/octet-stream" };+ try {+ // A top-level comma ends the first type. Never silently accept the remainder.+ const parsed = parseContentType(value, { comma: true });+ if (parsed.index !== value.length) return null;+ return { type: parsed.type, header: formatContentType(parsed) };+ } catch {+ return null;+ }+};++export const validateRestoredResourceMimeType = (kind: Resource["kind"], mimeType: string, size: number) => {+ const parsed = parseResourceContentType(mimeType);+ if (!parsed) {+ throw new AppError("unsupported_media_type", "Resource MIME type must contain a single valid media type.", 415);+ }+ if (kind === "image" && parsed.type !== "application/octet-stream") validateImageUpload(parsed.type, size);+};+export const deleteReleasedResourceObjects = async (env: Bindings,resources: { objectKey: string; storageConfigId: string }[],@@ -472,3 +500,31 @@ const contentDisposition = (kind: "inline" | "attachment", filename: string | nuexport const contentDispositionInline = (filename: string | null) => contentDisposition("inline", filename);export const contentDispositionAttachment = (filename: string | null) => contentDisposition("attachment", filename);++/** One policy for both the browser MIME and the decision to render it inline. */+export const setResourceContentHeaders = (+ headers: Headers,+ resource: Pick<ResourceRow, "kind" | "mime_type" | "filename">,+) => {+ const sourceMimeType = resource.mime_type ?? headers.get("Content-Type") ?? "";+ const parsed = parseResourceContentType(sourceMimeType);+ let contentType = "application/octet-stream";+ let inline = false;++ // Invalid legacy metadata must not be rescued into a preview by its filename.+ if (parsed) {+ const pdf = isPdfAttachment(resource.mime_type, resource.filename);+ const media = resolvePlayableMediaMimeType(resource.mime_type ? parsed.type : null, resource.filename);+ if (pdf) contentType = "application/pdf";+ else if (media) contentType = resource.mime_type && parsed.type === media ? parsed.header : media;+ else contentType = parsed.header;++ inline = pdf || Boolean(media)+ || (resource.kind === "image" && SUPPORTED_IMAGE_MIME_TYPES.has(parsed.type));+ }++ headers.set("Content-Type", contentType);+ headers.set("Content-Disposition", inline ? contentDispositionInline(resource.filename) : contentDispositionAttachment(resource.filename));+ headers.set("X-Content-Type-Options", "nosniff");+ setSvgResourceSecurityHeaders(headers);+};diff --git a/apps/api/src/resource-upload-service.ts b/apps/api/src/resource-upload-service.tsindex 3797ba0d..aeaa81f5 100644--- a/apps/api/src/resource-upload-service.ts+++ b/apps/api/src/resource-upload-service.ts@@ -17,6 +17,7 @@ import {MAX_ATTACHMENT_UPLOAD_BYTES,MAX_IMAGE_UPLOAD_BYTES,normalizeFilename,+ validateRestoredResourceMimeType,validateAttachmentUpload,validateImageUpload,} from "./resource-service";@@ -185,6 +186,8 @@ export const initiateResourceRestoreUpload = async (if (!Number.isSafeInteger(metadata.byteSize) || metadata.byteSize <= 0 || metadata.byteSize > maxBytes) {throw new AppError("upload_too_large", "Backup resource size is invalid.", 413);}+ const mimeType = metadata.mimeType?.trim() || "application/octet-stream";+ validateRestoredResourceMimeType(metadata.kind, metadata.mimeType ?? mimeType, metadata.byteSize);const workspaceId = getWorkspaceId(context);const memo = await context.env.storage.db.prepare(@@ -207,7 +210,6 @@ export const initiateResourceRestoreUpload = async (const uploadId = createId("upload");const filename = normalizeFilename(metadata.filename || "") || `${metadata.kind}-${metadata.id}`;- const mimeType = metadata.mimeType?.trim() || "application/octet-stream";const objectKey = `workspaces/${workspaceId}/restores/${metadata.memoId}/${metadata.id}/${Date.now()}-${filename}`;const destination = await resolveObjectStorage(context.env);const multipart = await destination.store.createMultipartUpload(@@ -300,11 +302,7 @@ export const uploadResourcePart = async (return { partNumber: part.partNumber, byteSize };};-const completeRestoredResourceUpload = async (- context: AppContext,- upload: ResourceUploadRow,- actor: AuditActor,-): Promise<Resource> => {+const parseRestoredResourceMetadata = (upload: ResourceUploadRow): JsonBackupResource => {let metadataInput: unknown;try {metadataInput = JSON.parse(upload.restore_metadata_json ?? "null");@@ -316,6 +314,18 @@ const completeRestoredResourceUpload = async (throw new AppError("invalid_restore_resource", "Restore resource metadata is invalid.", 400);}const metadata = parsed.data as JsonBackupResource;+ validateRestoredResourceMimeType(+ metadata.kind, metadata.mimeType ?? upload.mime_type, upload.byte_size,+ );+ return metadata;+};++const completeRestoredResourceUpload = async (+ context: AppContext,+ upload: ResourceUploadRow,+ actor: AuditActor,+ metadata: JsonBackupResource,+): Promise<Resource> => {const originalMemo = metadata.originalMemoId? await context.env.storage.db.prepare("SELECT id FROM memos WHERE id = ? AND workspace_id = ? LIMIT 1",@@ -430,12 +440,14 @@ export const completeResourceUpload = async (throw new AppError("upload_incomplete", "Resource upload size does not match the expected file size.", 409);}+ // Revalidate sessions persisted by an older server before assembling any bytes.+ const restoredMetadata = upload.restore_metadata_json ? parseRestoredResourceMetadata(upload) : null;const destination = await resolveObjectStorage(context.env, upload.storage_config_id);const multipart = destination.store.resumeMultipartUpload(upload.object_key, upload.provider_upload_id);await multipart.complete(parts);- if (upload.restore_metadata_json) {- return completeRestoredResourceUpload(context, upload, actor);+ if (restoredMetadata) {+ return completeRestoredResourceUpload(context, upload, actor, restoredMetadata);}const now = isoNow();diff --git a/apps/api/src/share-routes.ts b/apps/api/src/share-routes.tsindex aba6d249..0d74aca4 100644--- a/apps/api/src/share-routes.ts+++ b/apps/api/src/share-routes.ts@@ -1,4 +1,4 @@-import { setSvgResourceSecurityHeaders, accountNoteProseFromRow, collectMemoLinkIds, isPdfAttachment, MemoShareUpdateSchema, NoteBodyFontUpdateSchema, NoteProseUpdateSchema, parsePublishedNoteBodyFont, publicNoteProseFromAccount, PublicShareUnlockSchema, resolveMemoContentDoc, resolvePlayableMediaMimeType, sanitizeNoteProseCss, type AccountNoteProse, type ManagedMemoShare, type MemoShare, type NoteProseAccountRow, type PublicMemoShare, type TiptapDoc } from "@edgeever/shared";+import { accountNoteProseFromRow, collectMemoLinkIds, MemoShareUpdateSchema, NoteBodyFontUpdateSchema, NoteProseUpdateSchema, parsePublishedNoteBodyFont, publicNoteProseFromAccount, PublicShareUnlockSchema, resolveMemoContentDoc, sanitizeNoteProseCss, type AccountNoteProse, type ManagedMemoShare, type MemoShare, type NoteProseAccountRow, type PublicMemoShare, type TiptapDoc } from "@edgeever/shared";import { zValidator } from "@hono/zod-validator";import type { Hono } from "hono";import type { AppContext, AppEnv } from "./api-context";@@ -9,7 +9,7 @@ import { createId, isoNow, parseJsonArray } from "./entity-utils";import { apiError, notFound } from "./http-errors";import { resolveObjectStorage } from "./object-storage";import { getAuditActor, getWorkspaceId, requireUser } from "./request-auth";-import { contentDispositionAttachment, contentDispositionInline } from "./resource-service";+import { setResourceContentHeaders } from "./resource-service";import {isShareUnlockBlocked,nextShareUnlockFailure,@@ -74,11 +74,6 @@ const mapMemoShare = (row: MemoShareRow, password?: string): MemoShare => ({...(password ? { password } : {}),});-const contentDisposition = (kind: SharedResourceRow["kind"], mimeType: string | null, filename: string | null) => {- const inline = kind === "image" || isPdfAttachment(mimeType, filename) || Boolean(resolvePlayableMediaMimeType(mimeType, filename));- return inline ? contentDispositionInline(filename) : contentDispositionAttachment(filename);-};-const resolveShareToken = (c: AppContext, value: string) => resolveMemoShareToken(c.env.storage.db, value);const shareSlugTaken = (c: AppContext) =>@@ -141,13 +136,6 @@ export const serveSharedResource = async (c: AppContext, resource: SharedResourcconst headers = new Headers();object.writeHttpMetadata(headers);- const playableMimeType = resolvePlayableMediaMimeType(resource.mime_type, resource.filename);- headers.set(- "Content-Type",- isPdfAttachment(resource.mime_type, resource.filename)- ? "application/pdf"- : playableMimeType ?? resource.mime_type ?? headers.get("Content-Type") ?? "application/octet-stream",- );headers.set("Accept-Ranges", "bytes");if (byteRange.kind === "range") {const length = object.range?.length ?? byteRange.range.length;@@ -159,10 +147,8 @@ export const serveSharedResource = async (c: AppContext, resource: SharedResourc} else {headers.set("Content-Length", String(resource.byte_size));}- headers.set("Content-Disposition", contentDisposition(resource.kind, resource.mime_type, resource.filename));+ setResourceContentHeaders(headers, resource);headers.set("Cache-Control", "private, no-store");- headers.set("X-Content-Type-Options", "nosniff");- setSvgResourceSecurityHeaders(headers);headers.set("X-Robots-Tag", "noindex, nofollow, noarchive");return new Response(object.body, { headers, status: byteRange.kind === "range" ? 206 : 200 });};diff --git a/bun.lock b/bun.lockindex ce05376e..f77ebbf6 100644--- a/bun.lock+++ b/bun.lock@@ -100,6 +100,7 @@"version": "0.1.3","dependencies": {"@edgeever/public-network": "workspace:*",+ "content-type": "3.1.1",},},"apps/desktop": {@@ -2179,6 +2180,8 @@"connect": ["[email protected]", "", { "dependencies": { "debug": "2.6.9", "finalhandler": "1.1.2", "parseurl": "~1.3.3", "utils-merge": "1.0.1" } }, "sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ=="],+ "content-type": ["[email protected]", "", {}, "sha512-GW4qUsfFo59d0HbUibDlWv5wPz+vAAcaTWbKIuKCf0JkC7wWkSyf8f13IpXn5JkeMlB2P8iTSSIjwXljorg2vA=="],+"convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],"cookie": ["[email protected]", "", {}, "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w=="],diff --git a/docs/changes/2026-10-28-restore-resource-xss.md b/docs/changes/2026-10-28-restore-resource-xss.mdnew file mode 100644index 00000000..f288a789--- /dev/null+++ b/docs/changes/2026-10-28-restore-resource-xss.md@@ -0,0 +1,40 @@+# Issue 701: restore resource XSS protection++[简体中文](2026-10-28-restore-resource-xss.zh-CN.md)++## Problem and outcome++[Issue #701](https://github.com/tianma-if/edgeever/issues/701) reports that restore accepts `kind=image` with `mimeType=text/html`, while resource responses trust `kind` to enable inline rendering. Close both the write-time mismatch and the read-time exposure of previously stored resources. Work starts from official `main` at `b8496806` in a separate worktree.++The change affects API resource restore and resource response headers shared by Cloudflare and Docker. Backups explicitly labeling an image as an incompatible type such as HTML are rejected; valid old backups must still restore. The existing nullable MIME contract and unknown/binary fallback remain supported, with unknown types downloading instead of rendering inline. HTML and other arbitrary attachments remain downloadable. There is no migration or deletion of existing data. Rollback reverts the code without rewriting resources; reverting also reintroduces the vulnerability. Native-platform runtime and deployment acceptance are separate from the local checks below.++The backup schema explicitly permits null MIME, the released exporter preserves it, and resumable restore already falls back to `application/octet-stream`. Rejecting that safe fallback would break legitimate old archives without contributing to XSS protection; response-time MIME checks provide the download boundary.++Compare image MIME case-insensitively without parameters, but retain the stored MIME and its parameters as before. Stripping parameters from the stored value is unnecessary for validation and would discard encoding information such as SVG `charset`.++A local browser check found a remaining parser mismatch: a value starting with an image/audio type can contain an unquoted comma and a second HTML type. The old first-semicolon check permits inline delivery, while Chromium interprets the response as HTML even with `nosniff`. Validate and serialize the whole field using the portable `[email protected]` parser/formatter instead of splitting strings. Check the original HTTP-field characters before trimming/parsing: permit HTAB, visible ASCII and obs-text only, rejecting other controls, DEL and non-byte characters even inside ignored or duplicate parameters. The compatibility risk is rejecting multi-valued or unserializable MIME declarations and changing response-header casing/quoting; valid SVG encoding parameters and the stored backup metadata remain intact. Reverting this correction restores the bypass; rollback requires only code/dependency changes, not data migration.++## Allowed changes and acceptance++| ID | Behavior | Acceptance |+| --- | --- | --- |+| S1 | Legacy restore and resumable restore initialization/completion validate the effective MIME of resources marked `image` against the existing PNG/JPEG/GIF/WebP/AVIF/SVG allowlist, while preserving empty/unspecified and `application/octet-stream` MIME accepted by the original restore contract. Explicit incompatible types return the existing `415 unsupported_media_type` error. Legacy restore includes the existing uploaded-file MIME fallback when metadata MIME is null. Image MIME comparison ignores casing and parameters without rewriting stored MIME metadata or parameters; non-image attachment MIME metadata and size limits keep their existing contracts. | First add failing isolated API regressions for explicit HTML/XHTML, null metadata with an HTML file type, and multipart restore including an upload session created before the fix. Assert rejection without a new resource/object, preserving existing resources. Verify empty/null/binary image MIME still restores through both APIs and downloads; include null MIME in the released-exporter archive fixture. Preserve SVG encoding parameters and bytes through both restore paths. |+| S2 | Authenticated, public-note and public-notebook blob responses only use the image-specific inline branch when the effective response MIME is allowlisted. Existing malformed resources, including a null database MIME falling back to HTML object metadata, download instead. PDF/audio/video preview rules still use database MIME and filename, not object-metadata fallbacks; `nosniff`, SVG sandbox CSP, range handling and access checks stay unchanged. | Seed isolated legacy rows and verify the real response headers through all three routes, including storage-metadata fallback and SVG/PDF/media previews. Untyped binary attachments must not gain inline previews solely from PDF/media object metadata. |+| S3 | Add only regressions and compatibility evidence needed for S1/S2. | Verify rejection and ordinary restore through the actual app/database/blob adapter; restore a valid archive produced by the previous released implementation, preserving note/resource data and bytes. Run affected tests, `bun run typecheck`, `bun run typecheck:mobile` and `bun run build:web`. |+| S4 | Parse nonempty restore MIME for both images and attachments with `content-type` in comma-stop mode, require full-field consumption, and require successful MIME formatting. Reject type lists, invalid media types or unserializable parameters with `415 unsupported_media_type` before legacy object writes, multipart initialization or completion. Preserve existing null/empty/binary fallbacks and raw stored MIME metadata. Both resource response implementations share one Content-Type/disposition policy: serialize a single MIME with safe quoting; malformed/multi-valued database or storage metadata becomes `application/octet-stream` plus attachment disposition, even when a filename suggests PDF/media. Valid PDF/media preview classification still uses database MIME/filename, not storage-only MIME. SVG sandbox and `nosniff` apply after serialization. Add only the API dependency `[email protected]` and its lockfile update. | Add failing real-route regressions for image/audio/video type lists, old pending uploads, all three blob routes and storage-MIME fallback. Cover legitimate quoted commas/semicolons, escaped quotes and SVG charset without rewriting stored data. Confirm in the local browser that malformed resources download and valid quoted SVG remains SVG; use harmless content without script execution. Reuse unaffected tests and run affected API tests, typechecks, Web build and Worker bundling. |++## Unchanged boundaries++- No backup-format, schema, migration, authentication, API-token, permission, upload-size, retry or fallback changes beyond S1/S2/S4.+- Do not forbid HTML attachments, sanitize stored note bodies, delete existing resources, or operate on another user's instance/data.+- Deliver through focused commits and the existing contribution branch/PR #711 linked to #701. Keep the PR in Draft; no automatic ready transition, merge, deployment or release. Keep the original #657 checkout and its uncommitted changes untouched.++## Completion check++- S1/S4: all three restore stages reject image/type mismatches, top-level MIME lists, invalid media types and illegal original header characters before object writes or assembly. Hidden/duplicate parameters cannot conceal controls. Null/empty/binary MIME and valid SVG charset/quoted parameters remain supported without rewriting stored metadata.+- S2/S4: both response implementations share one parser/serializer and inline decision; invalid database/storage MIME becomes binary download even with misleading PDF/media filenames. Valid metadata retains the existing PDF/media preview boundary, SVG sandbox, `nosniff`, ranges and access checks.+- Acceptance: 64 security/compatibility regressions pass. The other 87 affected archive/resource/share tests also pass and remain applicable, for 151 distinct tests. The released-exporter [v2.12.0 fixture](../../tests/fixtures/restore-resource-security/README.md) restores through legacy and resumable APIs with notes, revisions and attachment bytes preserved.+- [Chromium acceptance](evidence/2026-10-28-restore-resource-xss/README.md): all three historical image/audio/video type-list samples emit successful binary download events; a quoted UTF-16LE SVG retains its Chinese text, and a quoted PNG decodes at its original width. Content is synthetic and script-free. Other browsers/native engines and live Cloudflare/R2 were not exercised.+- Main/mobile typechecks, Web build, Worker bundling, affected-file oxlint and `git diff --check` pass; frozen-lockfile installation succeeds. The only dependency change is `[email protected]` in the API, with a minimal lockfile entry.+- Scope review: S4 closes the demonstrated browser-parser bypass and rejects raw illegal bytes that the lenient parser can ignore. Removed duplicated Content-Type/disposition decisions from the two handlers. Latest correctness, simplification and design-boundary review has no unresolved substantive findings within this scope.+- PR #711 remains Draft. No deployment or native-platform runtime verification was performed. The original #657 working files were not edited.diff --git a/docs/changes/2026-10-28-restore-resource-xss.zh-CN.md b/docs/changes/2026-10-28-restore-resource-xss.zh-CN.mdnew file mode 100644index 00000000..786a2e0e--- /dev/null+++ b/docs/changes/2026-10-28-restore-resource-xss.zh-CN.md@@ -0,0 +1,40 @@+# Issue 701:备份恢复资源的 XSS 防护++[English](2026-10-28-restore-resource-xss.md)++## 问题与目标++[Issue #701](https://github.com/tianma-if/edgeever/issues/701) 指出恢复接口接受 `kind=image` 与 `mimeType=text/html` 的组合,而资源响应相信 `kind` 并允许内联渲染。修复写入时的不一致,同时阻断已有异常资源的读取风险。在独立工作区基于官方 `main` 的 `b8496806` 实施。++影响范围是 Cloudflare 和 Docker 共用的 API 资源恢复及响应头。旧备份若明确把图片标为 HTML 等不相容类型,会被拒绝;合法旧备份必须仍可恢复。保留既有的可空 MIME 契约和未知/二进制回退,未知类型转为下载而非内联渲染。HTML 等普通附件仍可下载。不迁移或删除现有数据。回滚只需回退代码,无需改写资源;回退也会重新引入漏洞。原生平台运行及部署验收与下述本地检查分开。++备份 Schema 明确允许 MIME 为 null,正式版导出器会保留该值,分片恢复原本回退为 `application/octet-stream`。拒绝这个安全回退会使合法旧备份无法恢复,却无助于阻断 XSS;下载边界由读取时的 MIME 校验保证。++图片 MIME 比较忽略大小写及参数,但入库 MIME 及其参数继续保持原值。校验无需改写存储值,剥离参数反而会丢失 SVG `charset` 等编码信息。++本地浏览器检查发现一个解析差异:以图片/音频类型开头的值,可以在未加引号的逗号后追加 HTML 类型;原先按第一个分号截取的校验会允许内联输出,Chromium 即使收到 `nosniff` 仍会当作 HTML 解析。改用可跨运行时使用的 `[email protected]` 解析和格式化完整字段,不再拆字符串判断。去空白或解析前,先校验原字段只含 HTAB、可见 ASCII 及 obs-text;其他控制字符、DEL 及非字节字符一律拒绝,即使藏在会被忽略或重复的参数中。兼容风险是多类型或无法安全格式化的声明会被拒绝,响应头的大小写和引号形式可能规范化;合法 SVG 编码参数及已存备份元数据保留。回退会恢复这个绕过,回滚只涉及代码及依赖,不需要迁移数据。++## 允许的变更与验收++| 编号 | 行为 | 验收 |+| --- | --- | --- |+| S1 | 旧式恢复与分片恢复的初始化、完成阶段,对标记为 `image` 的资源按既有 PNG/JPEG/GIF/WebP/AVIF/SVG 白名单校验实际生效的 MIME,同时保留原恢复契约接受的空/未指定 MIME 和 `application/octet-stream`。明确不相容的类型返回既有的 `415 unsupported_media_type`。旧式恢复须覆盖元数据 MIME 为 null 时沿用文件 MIME 的路径。图片 MIME 比较忽略大小写及参数,但不改写入库 MIME 元数据或参数;普通附件的 MIME 元数据及大小限制保持原契约。 | 先补充隔离 API 失败用例:显式 HTML/XHTML、元数据为 null 而文件为 HTML、分片恢复及修复前已创建的分片会话。断言拒绝时不新增资源或对象,已有资源不变。验证空/null/二进制图片 MIME 仍可经两条 API 恢复并作为下载输出,正式版导出器生成的备份样例也须包含 null MIME。两条恢复路径均须保留 SVG 编码参数及字节。 |+| S2 | 登录后、公开笔记及公开笔记本的 blob 响应,按图片内联的分支仅在实际响应 MIME 属于白名单时生效。已有异常资源改为下载,覆盖数据库 MIME 为 null 而存储元数据为 HTML 的路径。PDF/音视频预览继续依据数据库 MIME 及文件名判断,不使用对象元数据回退;`nosniff`、SVG sandbox CSP、范围读取和权限检查保持不变。 | 在隔离数据中写入历史异常记录,经三个真实路由核对响应头,并覆盖存储元数据回退、SVG/PDF/音视频预览。未指定类型的二进制附件不得仅因对象元数据为 PDF/音视频而新增内联预览。 |+| S3 | 仅补充 S1/S2 所需的回归及兼容证据。 | 经过真实应用、数据库及 blob 适配器验证拒绝和正常恢复;恢复由上一个正式版本实现生成的合法备份,核对笔记、资源数据及字节。运行受影响测试、`bun run typecheck`、`bun run typecheck:mobile` 和 `bun run build:web`。 |+| S4 | 对图片及普通附件的非空恢复 MIME,使用 `content-type` 的遇逗号停止模式解析,要求完整消费字段且可成功格式化。类型列表、无效媒体类型或无法格式化的参数,须在旧式对象写入、分片初始化或完成前返回 `415 unsupported_media_type`。保留既有 null/空/二进制回退及原始入库 MIME 元数据。两个资源响应实现共用 Content-Type/下载策略:安全序列化单一 MIME;数据库或存储元数据中格式错误/多值的类型统一按 `application/octet-stream` 下载,即使文件名看似 PDF/音视频。合法 PDF/音视频预览仍依据数据库 MIME/文件名,不使用仅存在于对象存储的类型。序列化后继续设置 SVG sandbox 及 `nosniff`。仅新增 API 依赖 `[email protected]` 及对应 lockfile 变化。 | 先补真实路由失败用例,覆盖图片/音频/视频类型列表、旧分片会话、三条 blob 路由及存储 MIME 回退。覆盖合法引号内的逗号/分号、转义引号及 SVG charset,并核对原始存储数据不变。用不含脚本的本地页面验证异常资源触发下载、合法带引号参数的 SVG 仍按 SVG 解析。复用未受影响测试,运行受影响 API 测试、类型检查、Web 构建及 Worker 打包。 |++## 保持不变的边界++- 除 S1/S2/S4 外,不改变备份格式、Schema、Migration、认证、API Token、权限、上传大小、重试或 fallback。+- 不禁止 HTML 附件,不清洗笔记正文,不删除历史资源,不操作他人的实例或数据。+- 通过独立提交及现有贡献分支/PR #711 交付,关联 #701;保持 Draft,不自动转为 Ready、合并、部署或发版。原 #657 工作区及其未提交改动保持原样。++## 完成核对++- S1/S4:三个恢复阶段均在对象写入或合并前拒绝图片/类型不一致、顶层 MIME 列表、无效媒体类型及原字段中的非法头字符。被忽略或重复的参数不能藏入控制字符;null/空/二进制 MIME、合法 SVG charset 和引号参数继续支持,入库元数据不改写。+- S2/S4:两个响应实现共用解析、序列化及内联判断;数据库/存储 MIME 非法时统一下载二进制,即使文件名看似 PDF/音视频。合法元数据保留原 PDF/音视频预览边界、SVG sandbox、`nosniff`、范围读取和权限检查。+- 验收:64 项安全/兼容回归通过;其他 87 项受影响的备份/资源/分享测试也已通过且仍适用,共 151 项。正式版原导出器生成的 [v2.12.0 样例](../../tests/fixtures/restore-resource-security/README.zh-CN.md) 经旧式及分片 API 恢复,笔记、历史版本及附件字节保留。+- [Chromium 验收](evidence/2026-10-28-restore-resource-xss/README.zh-CN.md):三种历史图片/音频/视频类型列表均触发成功的二进制下载事件;带引号参数的 UTF-16LE SVG 保留中文文字,PNG 按原始宽度解码。内容均为无脚本的合成数据,未验证其他浏览器/原生引擎或线上 Cloudflare/R2。+- 主项目/移动端类型检查、Web 构建、Worker 打包、受影响文件的 oxlint 及 `git diff --check` 均通过;冻结 lockfile 安装成功。依赖仅新增 API 的 `[email protected]` 及最小 lockfile 条目。+- 范围核对:S4 阻断已证实的浏览器解析绕过,并拒绝宽松解析器可能忽略的原始非法字节;两个处理器中重复的 Content-Type/下载判断已移除。最新正确性、简化及设计边界复审在本范围内无未处理实质问题。+- PR #711 保持 Draft;未部署,未做原生平台运行验证,没有编辑原 #657 工作区文件。diff --git a/docs/changes/evidence/2026-10-28-restore-resource-xss/README.md b/docs/changes/evidence/2026-10-28-restore-resource-xss/README.mdnew file mode 100644index 00000000..f43a8d6c--- /dev/null+++ b/docs/changes/evidence/2026-10-28-restore-resource-xss/README.md@@ -0,0 +1,13 @@+# Resource MIME browser acceptance++[简体中文](README.zh-CN.md)++[`browser-results.json`](browser-results.json) records Chromium checks through the real EdgeEver API, using isolated SQLite/filesystem storage on loopback. The content was synthetic and contained no scripts or credentials.++- Historical image, audio and video records with multiple declared MIME types produced `application/octet-stream` attachment responses. Chromium emitted successful download events for all three rather than parsing their HTML bodies as pages.+- A quoted UTF-16LE SVG retained its charset and quoted comma/semicolon parameter, remained `image/svg+xml` with sandbox CSP, and exposed the expected `旧备份` text in the SVG document.+- A PNG with a quoted comma parameter remained `image/png` and decoded to its original one-pixel width.++The [API regressions](../../../../apps/api/src/resource-restore-security.test.mjs) additionally cover all three blob routes, rejected legacy/resumable restores, old upload completion, storage metadata, hidden control characters, and unchanged stored metadata. Run `bun test apps/api/src/resource-restore-security.test.mjs` to repeat those checks.++The browser checks do not exercise a deployed Cloudflare/R2 instance or other browser/native engines. The Worker bundle is checked separately. The temporary browser task and fixture service are closed after acceptance.diff --git a/docs/changes/evidence/2026-10-28-restore-resource-xss/README.zh-CN.md b/docs/changes/evidence/2026-10-28-restore-resource-xss/README.zh-CN.mdnew file mode 100644index 00000000..fb97711d--- /dev/null+++ b/docs/changes/evidence/2026-10-28-restore-resource-xss/README.zh-CN.md@@ -0,0 +1,13 @@+# 资源 MIME 浏览器验收++[English](README.md)++[`browser-results.json`](browser-results.json) 保存 Chromium 经真实 EdgeEver API 的检查结果,使用独立的本机回环地址及 SQLite/文件存储。内容均为合成数据,不含脚本或凭据。++- 历史图片、音频、视频记录中声明多个 MIME 类型时,响应统一为 `application/octet-stream` 附件。Chromium 对三者均发出成功的下载事件,没有将 HTML 内容解析为网页。+- 带引号参数的 UTF-16LE SVG 保留 charset 和参数内的逗号/分号,仍按 `image/svg+xml` 解析并带 sandbox CSP;SVG 文档中读到了预期的 `旧备份` 文字。+- 参数内带引号逗号的 PNG 仍按 `image/png` 解析,实际解码宽度为原始的一像素。++[API 回归](../../../../apps/api/src/resource-restore-security.test.mjs) 还覆盖三条 blob 路由、旧式/分片恢复拒绝、旧上传完成阶段、存储元数据、隐藏控制字符,以及入库元数据保持原样。运行 `bun test apps/api/src/resource-restore-security.test.mjs` 可重复这些检查。++浏览器检查未覆盖已部署的 Cloudflare/R2 实例或其他浏览器/原生引擎;Worker 打包单独检查。临时浏览器任务及样例服务在验收后关闭。diff --git a/docs/changes/evidence/2026-10-28-restore-resource-xss/browser-results.json b/docs/changes/evidence/2026-10-28-restore-resource-xss/browser-results.jsonnew file mode 100644index 00000000..0fb04331--- /dev/null+++ b/docs/changes/evidence/2026-10-28-restore-resource-xss/browser-results.json@@ -0,0 +1,72 @@+{+ "engine": "Chromium via ego-browser",+ "content": "Synthetic local data; no script payloads or credentials",+ "results": [+ {+ "id": "bad_image",+ "sourceMime": "image/png; charset=utf-8, text/html",+ "status": 200,+ "contentType": "application/octet-stream",+ "disposition": "attachment; filename=\"image.bin\"; filename*=UTF-8''image.bin",+ "csp": null,+ "download": {+ "filename": "image.bin",+ "failure": null+ }+ },+ {+ "id": "bad_audio",+ "sourceMime": "audio/mpeg; ignored=x, text/html",+ "status": 200,+ "contentType": "application/octet-stream",+ "disposition": "attachment; filename=\"audio.bin\"; filename*=UTF-8''audio.bin",+ "csp": null,+ "download": {+ "filename": "audio.bin",+ "failure": null+ }+ },+ {+ "id": "bad_video",+ "sourceMime": "video/mp4; ignored=x, application/xhtml+xml",+ "status": 200,+ "contentType": "application/octet-stream",+ "disposition": "attachment; filename=\"video.bin\"; filename*=UTF-8''video.bin",+ "csp": null,+ "download": {+ "filename": "video.bin",+ "failure": null+ }+ },+ {+ "id": "quoted_svg",+ "sourceMime": "IMAGE/SVG+XML; charset=\"utf-16le\"; note=\"a,b; text/html\"",+ "status": 200,+ "contentType": "image/svg+xml; charset=utf-16le; note=\"a,b; text/html\"",+ "disposition": "inline; filename=\"encoded.svg\"; filename*=UTF-8''encoded.svg",+ "csp": "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox",+ "document": {+ "contentType": "image/svg+xml",+ "namespace": "http://www.w3.org/2000/svg",+ "svgText": "旧备份",+ "marker": false,+ "imageWidth": null+ }+ },+ {+ "id": "quoted_png",+ "sourceMime": "IMAGE/PNG; note=\"a,b; text/html\"",+ "status": 200,+ "contentType": "image/png; note=\"a,b; text/html\"",+ "disposition": "inline; filename=\"pixel.png\"; filename*=UTF-8''pixel.png",+ "csp": null,+ "document": {+ "contentType": "image/png",+ "namespace": "http://www.w3.org/1999/xhtml",+ "svgText": null,+ "marker": false,+ "imageWidth": 1+ }+ }+ ]+}diff --git a/tests/fixtures/restore-resource-security/README.md b/tests/fixtures/restore-resource-security/README.mdnew file mode 100644index 00000000..9b8f9672--- /dev/null+++ b/tests/fixtures/restore-resource-security/README.md@@ -0,0 +1,9 @@+# Previous-release restore fixture++[简体中文](README.zh-CN.md)++`v2.12.0.zip` was generated with `createEdgeEverZip` extracted using `git archive v2.12.0 packages/shared`, from official release commit `eeaab088f41d0417fbce2266f58ff4adde7f5d76`. The released exporter ran directly under Bun with the installed lockfile dependencies; the patched exporter was not used. `source.json` records its synthetic inputs and attachment bytes.++The archive contains one notebook, one pinned/tagged note, one historical revision, a PNG, an inert SVG, an image with null MIME, and a downloadable HTML attachment. The null-MIME image uses a `.bin` filename to exercise the existing binary fallback without file-extension MIME inference. It has no credentials, user data, scripts, or external requests. The security regression test restores this frozen archive through both legacy and resumable APIs and reads the resulting data and bytes back.++Run: `bun test apps/api/src/resource-restore-security.test.mjs`.diff --git a/tests/fixtures/restore-resource-security/README.zh-CN.md b/tests/fixtures/restore-resource-security/README.zh-CN.mdnew file mode 100644index 00000000..e79eee73--- /dev/null+++ b/tests/fixtures/restore-resource-security/README.zh-CN.md@@ -0,0 +1,9 @@+# 旧版备份恢复样例++[English](README.md)++`v2.12.0.zip` 由 `git archive v2.12.0 packages/shared` 提取的 `createEdgeEverZip` 生成,来源是官方正式版本的提交 `eeaab088f41d0417fbce2266f58ff4adde7f5d76`。旧版导出器在 Bun 下使用已安装的 lockfile 依赖直接运行,没有调用修复后的导出器。`source.json` 保存合成的输入数据及附件字节。++备份含一个笔记本、一篇置顶且带标签的笔记、一条历史版本,以及 PNG、无脚本的 SVG、MIME 为 null 的图片和可下载的 HTML 附件。MIME 为 null 的图片使用 `.bin` 文件名,避免按文件扩展名推断类型,实际覆盖既有二进制回退。不含凭据、用户数据、脚本或外部请求。安全回归测试分别通过旧式和分片 API 恢复这份固定备份,再读回数据及附件字节。++运行:`bun test apps/api/src/resource-restore-security.test.mjs`。diff --git a/tests/fixtures/restore-resource-security/source.json b/tests/fixtures/restore-resource-security/source.jsonnew file mode 100644index 00000000..4bce7a84--- /dev/null+++ b/tests/fixtures/restore-resource-security/source.json@@ -0,0 +1,158 @@+{+ "release": "v2.12.0",+ "commit": "eeaab088f41d0417fbce2266f58ff4adde7f5d76",+ "notebooks": [+ {+ "id": "nb_release",+ "parentId": null,+ "name": "Released backup",+ "slug": "released-backup",+ "icon": "notebook",+ "color": "#07130B",+ "textColor": null,+ "colorTarget": "icon",+ "isBold": false,+ "iconInverted": false,+ "rowInverted": false,+ "sortOrder": 0,+ "memoCount": 1,+ "lastMemoUpdatedAt": "2026-08-31T00:00:00.000Z",+ "createdAt": "2026-08-31T00:00:00.000Z",+ "updatedAt": "2026-08-31T00:00:00.000Z"+ }+ ],+ "memos": [+ {+ "id": "memo_release",+ "notebookId": "nb_release",+ "title": "Previous release backup",+ "excerpt": "Preserved note",+ "tags": [+ "old-release"+ ],+ "isPinned": true,+ "isArchived": false,+ "isDeleted": false,+ "revision": 1,+ "createdAt": "2026-08-31T00:00:00.000Z",+ "updatedAt": "2026-08-31T00:00:00.000Z",+ "deletedAt": null,+ "contentJson": {+ "type": "doc",+ "content": [+ {+ "type": "paragraph",+ "content": [+ {+ "type": "text",+ "text": "Preserved note"+ }+ ]+ }+ ]+ },+ "contentMarkdown": "Preserved note\n\n",+ "contentText": "Preserved note",+ "contentHash": "bce07e2da68d4fd2551bee0658f91f21c5fea020be1c015e2d14ecab29cc4c7c",+ "sourceMemoIds": [],+ "mergeSourceCount": 0,+ "mergedIntoMemoId": null+ }+ ],+ "revisions": [+ {+ "id": "rev_release",+ "memoId": "memo_release",+ "revision": 0,+ "title": "Previous release backup",+ "tags": [+ "old-release"+ ],+ "contentJson": {+ "type": "doc",+ "content": [+ {+ "type": "paragraph",+ "content": [+ {+ "type": "text",+ "text": "Original revision"+ }+ ]+ }+ ]+ },+ "contentMarkdown": "Original revision",+ "contentText": "Original revision",+ "contentHash": "29a61d05034d02dcc6a8808c45edafb2260211fa520813742e04e5a202c37e10",+ "createdBy": "user",+ "createdAt": "2026-08-31T00:00:00.000Z"+ }+ ],+ "resources": [+ {+ "id": "res_release_png",+ "memoId": "memo_release",+ "originalMemoId": null,+ "kind": "image",+ "mimeType": "image/png",+ "filename": "image.png",+ "byteSize": 68,+ "sha256": null,+ "width": 1,+ "height": 1,+ "createdAt": "2026-08-31T00:00:00.000Z",+ "updatedAt": "2026-08-31T00:00:00.000Z",+ "url": "/api/v1/resources/res_release_png/blob",+ "bytesBase64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII="+ },+ {+ "id": "res_release_svg",+ "memoId": "memo_release",+ "originalMemoId": null,+ "kind": "image",+ "mimeType": "image/svg+xml",+ "filename": "diagram.svg",+ "byteSize": 95,+ "sha256": null,+ "width": 1,+ "height": 1,+ "createdAt": "2026-08-31T00:00:00.000Z",+ "updatedAt": "2026-08-31T00:00:00.000Z",+ "url": "/api/v1/resources/res_release_svg/blob",+ "bytesBase64": "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxIiBoZWlnaHQ9IjEiPjxyZWN0IHdpZHRoPSIxIiBoZWlnaHQ9IjEiLz48L3N2Zz4="+ },+ {+ "id": "res_release_html",+ "memoId": "memo_release",+ "originalMemoId": null,+ "kind": "attachment",+ "mimeType": "text/html",+ "filename": "document.html",+ "byteSize": 43,+ "sha256": null,+ "width": null,+ "height": null,+ "createdAt": "2026-08-31T00:00:00.000Z",+ "updatedAt": "2026-08-31T00:00:00.000Z",+ "url": "/api/v1/resources/res_release_html/blob",+ "bytesBase64": "PCFkb2N0eXBlIGh0bWw+PHA+RG93bmxvYWRhYmxlIGRvY3VtZW50PC9wPg=="+ },+ {+ "id": "res_release_unknown",+ "memoId": "memo_release",+ "originalMemoId": null,+ "kind": "image",+ "mimeType": null,+ "filename": "unknown.bin",+ "byteSize": 68,+ "sha256": null,+ "width": 1,+ "height": 1,+ "createdAt": "2026-08-31T00:00:00.000Z",+ "updatedAt": "2026-08-31T00:00:00.000Z",+ "url": "/api/v1/resources/res_release_unknown/blob",+ "bytesBase64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII="+ }+ ]+}diff --git a/tests/fixtures/restore-resource-security/v2.12.0.zip b/tests/fixtures/restore-resource-security/v2.12.0.zipnew file mode 100644index 00000000..8337591bBinary files /dev/null and b/tests/fixtures/restore-resource-security/v2.12.0.zip differ