🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor: inject Canvas previews from project source (#21388)
Innei2f05b98da9e1
diff --git a/apps/desktop/src/main/const/__tests__/protocol.test.ts b/apps/desktop/src/main/const/__tests__/protocol.test.tsindex 3d5902188d7..36f4a3cbdc8 100644--- a/apps/desktop/src/main/const/__tests__/protocol.test.ts+++ b/apps/desktop/src/main/const/__tests__/protocol.test.ts@@ -16,15 +16,9 @@ describe('isBackendPath', () => {});});-describe('canvas previews', () => {- it('proxies canvas preview pages and the canvas runtime', () => {- expect(isBackendPath('/canvas-preview/token/index.html')).toBe(true);- expect(isBackendPath('/canvas-runtime/v1/canvas-runtime.js')).toBe(true);- });-- it('keeps sandboxed canvas pages away from authenticated backend paths', () => {- expect(isSandboxedBackendRequestAllowed('/trpc/lambda/user.getUserState', 'null')).toBe(false);- expect(isSandboxedBackendRequestAllowed('/canvas-preview/token/data.json', 'null')).toBe(true);- expect(isSandboxedBackendRequestAllowed('/trpc/lambda/user.getUserState', null)).toBe(true);+describe('isSandboxedBackendRequestAllowed', () => {+ it('blocks opaque origins from authenticated backend paths', () => {+ expect(isSandboxedBackendRequestAllowed('null')).toBe(false);+ expect(isSandboxedBackendRequestAllowed(null)).toBe(true);});});diff --git a/apps/desktop/src/main/const/protocol.ts b/apps/desktop/src/main/const/protocol.tsindex 70db9565922..683bb6662a5 100644--- a/apps/desktop/src/main/const/protocol.ts+++ b/apps/desktop/src/main/const/protocol.ts@@ -18,12 +18,8 @@ export const BACKEND_PATH_PREFIXES = ['/api/auth','/api/agent/llm-relay','/market',- '/canvas-preview',- '/canvas-runtime',];-const SANDBOXED_PATH_PREFIXES = ['/canvas-preview', '/canvas-runtime'];-const matchesPrefix = (pathname: string, prefixes: string[]) =>prefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));@@ -31,5 +27,4 @@ export const isBackendPath = (pathname: string) => matchesPrefix(pathname, BACKE// Canvas previews run in an opaque-origin sandbox (Origin: null); the proxy would otherwise// attach the user's access token to whatever backend path their scripts fetch.-export const isSandboxedBackendRequestAllowed = (pathname: string, origin: string | null) =>- origin !== 'null' || matchesPrefix(pathname, SANDBOXED_PATH_PREFIXES);+export const isSandboxedBackendRequestAllowed = (origin: string | null) => origin !== 'null';diff --git a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.tsindex 27e7d804cd2..348978015a4 100644--- a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts+++ b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts@@ -211,7 +211,7 @@ export class BackendProxyProtocolManager {return async (request) => {const url = new URL(request.url);if (!isBackendPath(url.pathname)) return null;- if (!isSandboxedBackendRequestAllowed(url.pathname, request.headers.get('origin')))+ if (!isSandboxedBackendRequestAllowed(request.headers.get('origin')))return new Response('Forbidden', { status: 403 });const session = electronSession.defaultSession;diff --git a/apps/server/src/routers/lambda/__tests__/canvas.test.ts b/apps/server/src/routers/lambda/__tests__/canvas.test.tsindex 32e9c70e49a..468e2dab59d 100644--- a/apps/server/src/routers/lambda/__tests__/canvas.test.ts+++ b/apps/server/src/routers/lambda/__tests__/canvas.test.ts@@ -4,7 +4,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { WorkModel } from '@/database/models/work';import { users, workspaceMembers, workspaces } from '@/database/schemas';-import { verifyCanvasPreviewToken } from '@/server/services/canvas/serve';import { canvasRouter } from '../canvas';@@ -20,6 +19,9 @@ vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {const publishing = vi.hoisted(() => ({enabled: true,+ runtime: vi.fn(+ async () => 'https://static.test/canvas-runtime/v1/' + 'a'.repeat(64) + '/canvas-runtime.js',+ ),publish: vi.fn(async (_params: any) => ({deploymentId: 'dep_1',url: 'https://cost.lobehub.sites',@@ -27,11 +29,25 @@ const publishing = vi.hoisted(() => ({}));vi.mock('@/business/server/canvasPublish', () => ({+ getCanvasPublishRuntimeUrl: publishing.runtime,isCanvasPublishEnabled: () => publishing.enabled,publishCanvasSite: publishing.publish,}));const committed = vi.hoisted(() => ({ calls: 0 }));+const snapshots = vi.hoisted(() => ({+ read: vi.fn(async (key: string, owner: string) => ({+ entry: 'index.html',+ files: [+ {+ path: 'index.html',+ content: `${owner}:${key}`,+ contentType: 'text/html',+ encoding: 'utf8',+ },+ ],+ })),+}));vi.mock('@/server/services/canvas', () => ({createCanvasStorageService: (_db: unknown, ownerId: string) => ({@@ -50,6 +66,7 @@ vi.mock('@/server/services/canvas', () => ({};},ownerId,+ readSnapshot: (key: string) => snapshots.read(key, ownerId),readFile: async () => ({bytes: new TextEncoder().encode('<html><head></head><body>hi</body></html>'),contentType: 'text/html; charset=utf-8',@@ -100,7 +117,7 @@ beforeEach(async () => {});describe('canvasRouter.getVersion', () => {- it('returns the latest version with a signed preview URL for its manifest', async () => {+ it('returns the latest version metadata', async () => {const result = await caller().getVersion({ canvasId: 'cvs_1' });expect(result).toMatchObject({@@ -110,25 +127,16 @@ describe('canvasRouter.getVersion', () => {title: 'Cost report',version: 2,});- const token = result!.previewUrl.split('/')[2];- expect(verifyCanvasPreviewToken(token)).toMatchObject({- manifestKey: metadata('b').manifestKey,- userId,- });- expect(result!.runtimeUrl).toBe('/canvas-runtime/v1/canvas-runtime.js');- expect(result!.previewUrl).toBe(`/canvas-preview/${token}/index.html`);});it('returns a pinned version', async () => {const result = await caller().getVersion({ canvasId: 'cvs_1', version: 1 });expect(result).toMatchObject({ latestVersion: 2, version: 1 });- expect(verifyCanvasPreviewToken(result!.previewUrl.split('/')[2])?.manifestKey).toBe(- metadata('a').manifestKey,- );+ expect(result!.metadata.manifestKey).toBe(metadata('a').manifestKey);});- it('signs a teammate preview with the owner so the owner-scoped manifest resolves', async () => {+ it('loads a teammate project from its owner-scoped manifest', async () => {const workspaceId = 'canvas-router-ws';await serverDB.insert(workspaces)@@ -149,12 +157,9 @@ describe('canvasRouter.getVersion', () => {const result = await canvasRouter.createCaller({ serverDB, userId: 'stranger', workspaceId } as any)- .getVersion({ canvasId: 'cvs_ws' });+ .getProject({ canvasId: 'cvs_ws', version: 1 });- expect(verifyCanvasPreviewToken(result!.previewUrl.split('/')[2])).toMatchObject({- userId,- workspaceId,- });+ expect(result.files[0].content).toBe(`${userId}:${metadata('ws').manifestKey}`);});it('returns null for another user or a missing version', async () => {@@ -163,6 +168,25 @@ describe('canvasRouter.getVersion', () => {});});+describe('canvasRouter.getProject', () => {+ it('returns the requested immutable snapshot through authenticated access', async () => {+ const result = await caller().getProject({ canvasId: 'cvs_1', version: 1 });+ expect(result).toMatchObject({+ entry: 'index.html',+ files: [{ content: `${userId}:${metadata('a').manifestKey}` }],+ });+ });++ it('refuses another user and a version outside the canvas', async () => {+ snapshots.read.mockClear();+ await expect(+ caller('stranger').getProject({ canvasId: 'cvs_1', version: 1 }),+ ).rejects.toThrow();+ await expect(caller().getProject({ canvasId: 'cvs_1', version: 99 })).rejects.toThrow();+ expect(snapshots.read).not.toHaveBeenCalled();+ });+});+describe('canvasRouter.publish', () => {beforeEach(() => {vi.stubEnv('CANVAS_RUNTIME_BASE_URL', 'https://cdn.test/canvas-runtime');@@ -184,7 +208,7 @@ describe('canvasRouter.publish', () => {userId,});expect(publishing.publish.mock.calls[0][0].bundle.html).toContain(- 'https://cdn.test/canvas-runtime/v1/canvas-runtime.js',+ 'https://static.test/canvas-runtime/v1/' + 'a'.repeat(64) + '/canvas-runtime.js',);expect(publishing.publish.mock.calls[1][0].deploymentId).toBe('dep_1');expect(await caller().getVersion({ canvasId: 'cvs_1' })).toMatchObject({@@ -194,6 +218,16 @@ describe('canvasRouter.publish', () => {});});+ it('reports an unavailable publication runtime without publishing or exposing the fetch error', async () => {+ publishing.runtime.mockRejectedValueOnce(new Error('private upstream failure'));+ await expect(caller().publish({ canvasId: 'cvs_1' })).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: 'The publication host has no compatible Canvas runtime',+ });+ expect(publishing.publish).not.toHaveBeenCalled();+ expect((await caller().getVersion({ canvasId: 'cvs_1' }))?.publishedVersion).toBeNull();+ });+it('refuses when publishing is unavailable or the canvas is not visible', async () => {await expect(caller('stranger').publish({ canvasId: 'cvs_1' })).rejects.toThrow();publishing.enabled = false;diff --git a/apps/server/src/routers/lambda/canvas.ts b/apps/server/src/routers/lambda/canvas.tsindex 8fa029e811d..ae94be4f018 100644--- a/apps/server/src/routers/lambda/canvas.ts+++ b/apps/server/src/routers/lambda/canvas.ts@@ -3,26 +3,21 @@ import type { BuiltinServerRuntimeOutput, WorkRegistrationIntent } from '@lobechimport { TRPCError } from '@trpc/server';import { z } from 'zod';-import { isCanvasPublishEnabled, publishCanvasSite } from '@/business/server/canvasPublish';+import {+ getCanvasPublishRuntimeUrl,+ isCanvasPublishEnabled,+ publishCanvasSite,+} from '@/business/server/canvasPublish';import {requireWorkspaceRoleWhenScoped,wsCompatProcedure,} from '@/business/server/trpc-middlewares/workspaceAuth';import { WorkModel } from '@/database/models/work';-import { appEnv } from '@/envs/app';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { createCanvasStorageService } from '@/server/services/canvas';import { createCanvasAgentRuntime } from '@/server/services/canvas/agentRuntime';-import {- buildCanvasPublishBundle,- resolveCanvasPublicRuntimeUrl,-} from '@/server/services/canvas/publish';-import {- buildCanvasPreviewUrl,- resolveCanvasRuntimeUrl,-} from '@/server/services/canvas/runtimeUrl';-import { signCanvasPreviewToken } from '@/server/services/canvas/serve';+import { buildCanvasPublishBundle } from '@/server/services/canvas/publish';const canvasProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -34,6 +29,24 @@ const canvasProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =});export const canvasRouter = router({+ getProject: canvasProcedure+ .input(z.object({ canvasId: z.string(), version: z.number().int().positive() }))+ .query(async ({ ctx, input }) => {+ const current = await ctx.workModel.findCanvas(input.canvasId);+ if (!current) throw new TRPCError({ code: 'NOT_FOUND' });+ const version =+ input.version === current.version.version+ ? current.version+ : await ctx.workModel.findCanvasVersion(current.work.id, input.version);+ const canvas = version?.metadata?.canvas;+ if (!canvas) throw new TRPCError({ code: 'NOT_FOUND' });+ return createCanvasStorageService(+ ctx.serverDB,+ current.work.userId,+ ctx.workspaceId,+ ).readSnapshot(canvas.manifestKey);+ }),+getVersion: canvasProcedure.input(z.object({ canvasId: z.string(), version: z.number().int().positive().optional() })).query(async ({ ctx, input }) => {@@ -47,12 +60,6 @@ export const canvasRouter = router({const canvas = version?.metadata?.canvas;if (!version || !canvas) return null;- const token = signCanvasPreviewToken({- manifestKey: canvas.manifestKey,- userId: current.work.userId,- workspaceId: ctx.workspaceId,- });-return {canPublish: isCanvasPublishEnabled() && current.work.userId === ctx.userId,canvasId: input.canvasId,@@ -60,10 +67,8 @@ export const canvasRouter = router({description: version.description ?? current.work.description,latestVersion: current.version.version,metadata: canvas,- previewUrl: buildCanvasPreviewUrl(token, canvas.entry),publishedUrl: current.work.url,publishedVersion: current.work.metadata?.canvasPublish?.publishedVersion ?? null,- runtimeUrl: resolveCanvasRuntimeUrl(canvas.runtimeMajor),title: version.title ?? current.work.title,version: version.version,workId: current.work.id,@@ -86,14 +91,17 @@ export const canvasRouter = router({if (!current || !canvas) throw new TRPCError({ code: 'NOT_FOUND' });if (current.work.userId !== ctx.userId) throw new TRPCError({ code: 'FORBIDDEN' });- const runtimeUrl = resolveCanvasPublicRuntimeUrl(canvas.runtimeMajor, {- appUrl: appEnv.APP_URL,- baseUrl: process.env.CANVAS_RUNTIME_BASE_URL,+ const runtimeUrl = await getCanvasPublishRuntimeUrl(canvas.runtimeMajor).catch((cause) => {+ throw new TRPCError({+ cause,+ code: 'PRECONDITION_FAILED',+ message: 'The publication host has no compatible Canvas runtime',+ });});if (!runtimeUrl) {throw new TRPCError({code: 'PRECONDITION_FAILED',- message: 'Publishing needs APP_URL or an absolute CANVAS_RUNTIME_BASE_URL',+ message: 'The publication host has no compatible Canvas runtime',});}diff --git a/apps/server/src/services/canvas/__tests__/publish.test.ts b/apps/server/src/services/canvas/__tests__/publish.test.tsindex 069d12a3612..7925dd9eb5a 100644--- a/apps/server/src/services/canvas/__tests__/publish.test.ts+++ b/apps/server/src/services/canvas/__tests__/publish.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { buildCanvasPublishBundle, resolveCanvasPublicRuntimeUrl } from '../publish';import type { CanvasStorageService } from '../storage';@@ -54,16 +54,34 @@ describe('buildCanvasPublishBundle', () => {});describe('resolveCanvasPublicRuntimeUrl', () => {- it('needs an absolute runtime URL because published sites live on another origin', () => {- expect(resolveCanvasPublicRuntimeUrl(1, { appUrl: 'https://app.test/' })).toBe(- 'https://app.test/canvas-runtime/v1/canvas-runtime.js',+ afterEach(() => vi.unstubAllGlobals());++ it('pins a published page to the immutable runtime revision hosted by Market', async () => {+ const revision = 'a'.repeat(64);+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => Response.json({ major: 1, revision })),+ );+ expect(await resolveCanvasPublicRuntimeUrl(1, 'https://static.test/canvas-runtime/')).toBe(+ `https://static.test/canvas-runtime/v1/${revision}/canvas-runtime.js`,+ );+ expect(await resolveCanvasPublicRuntimeUrl(1)).toBeUndefined();+ });++ it('refuses a missing or incompatible runtime release before publishing a broken site', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response('missing', { status: 404 })),+ );+ await expect(+ resolveCanvasPublicRuntimeUrl(1, 'https://static.test/canvas-runtime'),+ ).rejects.toThrow();+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => Response.json({ major: 2, revision: '../bad' })),);- expect(- resolveCanvasPublicRuntimeUrl(1, {- appUrl: 'https://app.test',- baseUrl: 'https://cdn.test/rt/',- }),- ).toBe('https://cdn.test/rt/v1/canvas-runtime.js');- expect(resolveCanvasPublicRuntimeUrl(1, {})).toBeUndefined();+ await expect(+ resolveCanvasPublicRuntimeUrl(1, 'https://static.test/canvas-runtime'),+ ).rejects.toThrow();});});diff --git a/apps/server/src/services/canvas/__tests__/serve.test.ts b/apps/server/src/services/canvas/__tests__/serve.test.tsdeleted file mode 100644index 1a8ba6c402b..00000000000--- a/apps/server/src/services/canvas/__tests__/serve.test.ts+++ /dev/null@@ -1,190 +0,0 @@-// @vitest-environment node-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import {- CANVAS_PREVIEW_TTL_BUCKET_SECONDS,- CANVAS_PREVIEW_TTL_SECONDS,- injectCanvasRuntime,- serveCanvasFile,- signCanvasPreviewToken,- verifyCanvasPreviewToken,-} from '../serve';-import type { CanvasStorageService } from '../storage';--const manifest = {- entry: 'index.html',- files: {- 'data.json': { contentType: 'application/json; charset=utf-8', hash: 'h2', size: 5 },- 'index.html': { contentType: 'text/html; charset=utf-8', hash: 'h1', size: 40 },- },- runtimeMajor: 1,- schemaVersion: 1 as const,-};--const storageFor = (files: Record<string, string>) =>- ({- readFile: vi.fn(async (_manifest: unknown, path: string) =>- path in files- ? {- bytes: new TextEncoder().encode(files[path]),- contentType: manifest.files[path as keyof typeof manifest.files].contentType,- }- : undefined,- ),- readManifest: vi.fn(async () => manifest),- }) as unknown as CanvasStorageService;--beforeEach(() => {- vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');-});--afterEach(() => {- vi.unstubAllEnvs();- vi.useRealTimers();-});--describe('canvas preview tokens', () => {- it('round-trips a signed token', () => {- const token = signCanvasPreviewToken({- manifestKey: 'canvas/u/c/manifests/a.json',- userId: 'u',- });-- expect(verifyCanvasPreviewToken(token)).toMatchObject({- manifestKey: 'canvas/u/c/manifests/a.json',- userId: 'u',- });- });-- it('rejects a tampered or expired token', () => {- const token = signCanvasPreviewToken({ manifestKey: 'k', userId: 'u' });- const [body, signature] = token.split('.');- const forged = `${Buffer.from(JSON.stringify({ e: 9_999_999_999, k: 'k', u: 'other' })).toString('base64url')}.${signature}`;-- expect(verifyCanvasPreviewToken(forged)).toBeUndefined();- expect(verifyCanvasPreviewToken(`${body}.`)).toBeUndefined();-- vi.useFakeTimers();- vi.setSystemTime(- Date.now() + (CANVAS_PREVIEW_TTL_SECONDS + CANVAS_PREVIEW_TTL_BUCKET_SECONDS + 5) * 1000,- );- expect(verifyCanvasPreviewToken(token)).toBeUndefined();- });-- it('keeps the token stable within a time bucket so the preview frame does not reload', () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-10-20T10:00:00Z'));- const first = signCanvasPreviewToken({ manifestKey: 'k', userId: 'u' });- vi.setSystemTime(new Date('2026-10-20T10:04:00Z'));-- expect(signCanvasPreviewToken({ manifestKey: 'k', userId: 'u' })).toBe(first);- });-});--describe('injectCanvasRuntime', () => {- it('adds the publication runtime right after <head>', () => {- const html = injectCanvasRuntime(- '<!doctype html><html><head><title>x</title></head><body></body></html>',- {- runtimeUrl: '/canvas-runtime/v1/canvas-runtime.js',- },- );-- expect(html).toContain('<head><script defer');- expect(html).toContain('<script defer src="/canvas-runtime/v1/canvas-runtime.js"></script>');- expect(html.indexOf('canvas-runtime.js')).toBeLessThan(html.indexOf('<title>'));- });-- it('wraps a fragment that has no <head>', () => {- const html = injectCanvasRuntime('<lobe-tag>x</lobe-tag>', { runtimeUrl: '/r.js' });-- expect(html.startsWith('<!doctype html>')).toBe(true);- expect(html).toContain('<lobe-tag>x</lobe-tag>');- expect(html).toContain('<script defer src="/r.js"></script>');- });-});--describe('serveCanvasFile', () => {- const token = () =>- signCanvasPreviewToken({ manifestKey: 'canvas/u/c/manifests/a.json', userId: 'u' });-- it('serves the entry page with the runtime injected and a locked-down CSP', async () => {- const storage = storageFor({ 'index.html': '<html><head></head><body>hi</body></html>' });-- const response = await serveCanvasFile({- createStorage: () => storage,- path: '',- runtimeUrl: '/canvas-runtime/v1/canvas-runtime.js',- token: token(),- });-- expect(response.status).toBe(200);- expect(response.headers.get('content-type')).toContain('text/html');- expect(response.headers.get('content-security-policy')).toContain("connect-src 'self'");- expect(response.headers.get('content-security-policy')).toContain("default-src 'none'");- const html = await response.text();- expect(html).toContain('data-lobe-canvas-bridge');- expect(html).not.toContain('<script defer src=');- expect(response.headers.get('content-security-policy')).toContain(- "script-src 'self' 'unsafe-inline' blob:",- );- });-- it('sandboxes every response into an opaque origin even when opened top-level', async () => {- const response = await serveCanvasFile({- createStorage: () => storageFor({ 'data.json': '[1,2]' }),- path: 'data.json',- runtimeUrl: '/r.js',- token: token(),- });- const csp = response.headers.get('content-security-policy')!;-- expect(csp).toMatch(- /(^|; )sandbox allow-scripts allow-popups allow-forms allow-downloads(;|$)/,- );- expect(csp).not.toContain('allow-same-origin');- });-- it('serves project files as-is and allows the opaque sandbox origin to read them', async () => {- const response = await serveCanvasFile({- createStorage: () => storageFor({ 'data.json': '[1,2]' }),- path: 'data.json',- runtimeUrl: '/r.js',- token: token(),- });-- expect(await response.text()).toBe('[1,2]');- expect(response.headers.get('access-control-allow-origin')).toBe('*');- });-- it('answers 403 for a bad token and 404 for a missing file', async () => {- const createStorage = () => storageFor({});-- expect(- (await serveCanvasFile({ createStorage, path: '', runtimeUrl: '/r.js', token: 'nope' }))- .status,- ).toBe(403);- expect(- (- await serveCanvasFile({- createStorage,- path: 'missing.css',- runtimeUrl: '/r.js',- token: token(),- })- ).status,- ).toBe(404);- });-- it('answers 404 instead of the entry page for a path that escapes the project', async () => {- const response = await serveCanvasFile({- createStorage: () =>- storageFor({ 'index.html': '<html><head></head><body>hi</body></html>' }),- path: '../../package.json',- runtimeUrl: '/r.js',- token: token(),- });-- expect(response.status).toBe(404);- });-});diff --git a/apps/server/src/services/canvas/__tests__/storage.test.ts b/apps/server/src/services/canvas/__tests__/storage.test.tsindex d6c668c1b7f..c260a93f943 100644--- a/apps/server/src/services/canvas/__tests__/storage.test.ts+++ b/apps/server/src/services/canvas/__tests__/storage.test.ts@@ -45,6 +45,29 @@ describe('isOwnCanvasManifestKey', () => {});describe('CanvasStorageService', () => {+ it('returns complete text and binary snapshots while refusing a foreign manifest', async () => {+ const { store } = createMemoryStore();+ const service = new CanvasStorageService({ db: serverDB, store, userId });+ const result = await service.commit('cvs_snapshot', [+ { content: page('<img src="a.png">'), path: 'index.html' },+ { content: new Uint8Array([0, 127, 255]), path: 'a.png' },+ ]);+ if (!result.ok) throw new Error('commit failed');+ const snapshot = await service.readSnapshot(result.metadata.manifestKey);+ expect(snapshot.entry).toBe('index.html');+ expect(snapshot.files.find((file) => file.path === 'index.html')).toMatchObject({+ content: page('<img src="a.png">'),+ encoding: 'utf8',+ });+ expect(snapshot.files.find((file) => file.path === 'a.png')).toMatchObject({+ content: Buffer.from([0, 127, 255]).toString('base64'),+ encoding: 'base64',+ });+ await expect(+ service.readSnapshot('canvas/another-user/cvs_snapshot/manifests/a.json'),+ ).rejects.toThrow(/owned/);+ });+it('stores a project as content-addressed blobs plus a manifest and counts it toward usage', async () => {const { store } = createMemoryStore();const service = new CanvasStorageService({ db: serverDB, store, userId });diff --git a/apps/server/src/services/canvas/publish.ts b/apps/server/src/services/canvas/publish.tsindex db2ec42be3b..8b5a0e8d196 100644--- a/apps/server/src/services/canvas/publish.ts+++ b/apps/server/src/services/canvas/publish.ts@@ -5,21 +5,34 @@ import {isCanvasTextPath,} from '@lobechat/canvas';import type { CanvasPublishBundle, CanvasPublishFile } from '@lobechat/types';+import { z } from 'zod';-import { CANVAS_RUNTIME_FILE } from './runtimeUrl';-import { injectCanvasRuntime } from './serve';import type { CanvasStorageService } from './storage';-const isAbsoluteUrl = (value: string) => /^https?:\/\//.test(value);--export const resolveCanvasPublicRuntimeUrl = (+export const resolveCanvasPublicRuntimeUrl = async (major: number,- env: { appUrl?: string; baseUrl?: string },-): string | undefined => {- const base = env.baseUrl?.replace(/\/$/, '');- if (base && isAbsoluteUrl(base)) return `${base}/v${major}/${CANVAS_RUNTIME_FILE}`;- if (!env.appUrl || !isAbsoluteUrl(env.appUrl)) return;- return new URL(`${base ?? '/canvas-runtime'}/v${major}/${CANVAS_RUNTIME_FILE}`, env.appUrl).href;+ baseUrl?: string,+): Promise<string | undefined> => {+ if (!baseUrl || !/^https?:\/\//.test(baseUrl)) return;+ const base = `${baseUrl.replace(/\/+$/, '')}/v${major}`;+ const response = await fetch(`${base}/manifest.json`, {+ cache: 'no-store',+ signal: AbortSignal.timeout(15_000),+ });+ if (!response.ok) throw new Error(`Canvas runtime v${major} has not been published`);+ const manifest = z+ .object({ major: z.literal(major), revision: z.string().regex(/^[\da-f]{64}$/) })+ .parse(await response.json());+ return `${base}/${manifest.revision}/canvas-runtime.js`;+};++const injectCanvasRuntime = (html: string, runtimeUrl: string) => {+ const injection = `<script defer src="${runtimeUrl}"></script>`;+ const head = /<head(?:\s[^>]*)?>/i.exec(html);+ if (!head)+ return `<!doctype html><html><head><meta charset="utf-8">${injection}</head><body>${html}</body></html>`;+ const at = head.index + head[0].length;+ return html.slice(0, at) + injection + html.slice(at);};export const buildCanvasPublishBundle = async (@@ -37,7 +50,7 @@ export const buildCanvasPublishBundle = async (if (!file) throw new Error(`Canvas file ${path} is missing`);if (getCanvasFileExtension(path) === 'html') {- const page = injectCanvasRuntime(decoder.decode(file.bytes), { runtimeUrl });+ const page = injectCanvasRuntime(decoder.decode(file.bytes), runtimeUrl);if (path === entry) html = page;elsefiles.push({diff --git a/apps/server/src/services/canvas/runtimeUrl.ts b/apps/server/src/services/canvas/runtimeUrl.tsdeleted file mode 100644index 6731b5ba441..00000000000--- a/apps/server/src/services/canvas/runtimeUrl.ts+++ /dev/null@@ -1,13 +0,0 @@-import { CANVAS_ENTRY, CANVAS_RUNTIME_MAJOR } from '@lobechat/canvas';--export const CANVAS_RUNTIME_FILE = 'canvas-runtime.js';--export const resolveCanvasRuntimeUrl = (major = CANVAS_RUNTIME_MAJOR) => {- const base = process.env.CANVAS_RUNTIME_BASE_URL?.replace(/\/$/, '') ?? '/canvas-runtime';- return `${base}/v${major}/${CANVAS_RUNTIME_FILE}`;-};--// Next redirects a trailing-slash URL to its slashless form, which would resolve the-// project's relative file references one directory too high; address the entry file instead.-export const buildCanvasPreviewUrl = (token: string, entry = CANVAS_ENTRY) =>- `/canvas-preview/${token}/${entry}`;diff --git a/apps/server/src/services/canvas/serve.ts b/apps/server/src/services/canvas/serve.tsdeleted file mode 100644index 594e5d0b0a7..00000000000--- a/apps/server/src/services/canvas/serve.ts+++ /dev/null@@ -1,142 +0,0 @@-import { createHmac, timingSafeEqual } from 'node:crypto';--import { CANVAS_ENTRY, getCanvasFileExtension, normalizeCanvasPath } from '@lobechat/canvas';-import { installCanvasBridge } from '@lobechat/canvas/runtime';--import type { CanvasStorageService } from './storage';--export const CANVAS_PREVIEW_TTL_SECONDS = 60 * 60;-export const CANVAS_PREVIEW_TTL_BUCKET_SECONDS = 15 * 60;--export interface CanvasPreviewTokenPayload {- manifestKey: string;- userId: string;- workspaceId?: string;-}--interface EncodedPayload {- e: number;- k: string;- u: string;- w?: string;-}--const secret = () => {- const value = process.env.KEY_VAULTS_SECRET;- if (!value) throw new Error('`KEY_VAULTS_SECRET` is required to sign canvas preview URLs');- return value;-};--const sign = (body: string) =>- createHmac('sha256', secret()).update(`canvas-preview:${body}`).digest('base64url');--export const signCanvasPreviewToken = (- payload: CanvasPreviewTokenPayload,- ttlSeconds = CANVAS_PREVIEW_TTL_SECONDS,-) => {- const bucket = CANVAS_PREVIEW_TTL_BUCKET_SECONDS;- const encoded: EncodedPayload = {- e: (Math.floor(Date.now() / 1000 / bucket) + 1) * bucket + ttlSeconds,- k: payload.manifestKey,- u: payload.userId,- ...(payload.workspaceId && { w: payload.workspaceId }),- };- const body = Buffer.from(JSON.stringify(encoded)).toString('base64url');- return `${body}.${sign(body)}`;-};--export const verifyCanvasPreviewToken = (token: string): CanvasPreviewTokenPayload | undefined => {- const [body, signature] = token.split('.');- if (!body || !signature) return;-- const expected = Buffer.from(sign(body));- const actual = Buffer.from(signature);- if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return;-- try {- const payload = JSON.parse(Buffer.from(body, 'base64url').toString()) as EncodedPayload;- if (payload.e * 1000 < Date.now()) return;- return { manifestKey: payload.k, userId: payload.u, workspaceId: payload.w };- } catch {- return;- }-};--const injectHead = (html: string, injection: string) => {- const head = /<head(?:\s[^>]*)?>/i.exec(html);- if (head) {- const at = head.index + head[0].length;- return `${html.slice(0, at)}${injection}${html.slice(at)}`;- }- return `<!doctype html><html><head><meta charset="utf-8">${injection}</head><body>${html}</body></html>`;-};--export const injectCanvasRuntime = (html: string, options: { runtimeUrl: string }) =>- injectHead(html, `<script defer src="${options.runtimeUrl}"></script>`);--const injectCanvasPreview = (html: string, runtimeUrl: string) => {- const fallback = JSON.stringify(runtimeUrl).replaceAll('<', String.raw`\u003c`);- return injectHead(- html,- `<script data-lobe-canvas-bridge>(${installCanvasBridge.toString()})(${fallback});</script>`,- );-};--const contentSecurityPolicy = (runtimeUrl: string) => {- const runtimeOrigin = /^https?:\/\//.test(runtimeUrl) ? ` ${new URL(runtimeUrl).origin}` : '';- return [- 'sandbox allow-scripts allow-popups allow-forms allow-downloads',- "default-src 'none'",- `script-src 'self' 'unsafe-inline' blob:${runtimeOrigin}`,- "style-src 'self' 'unsafe-inline'",- "img-src 'self' data: blob:",- "font-src 'self' data:",- "media-src 'self' data: blob:",- "connect-src 'self'",- "form-action 'none'",- "base-uri 'none'",- ].join('; ');-};--export interface ServeCanvasFileParams {- createStorage: (- payload: CanvasPreviewTokenPayload,- ) => Pick<CanvasStorageService, 'readFile' | 'readManifest'>;- path: string;- runtimeUrl: string;- token: string;-}--export const serveCanvasFile = async ({- createStorage,- path,- runtimeUrl,- token,-}: ServeCanvasFileParams): Promise<Response> => {- const payload = verifyCanvasPreviewToken(token);- if (!payload) return new Response('Forbidden', { status: 403 });-- const requested = path ? normalizeCanvasPath(path) : undefined;- if (path && !requested) return new Response('Not found', { status: 404 });-- const storage = createStorage(payload);- const manifest = await storage.readManifest(payload.manifestKey);- const target = requested || manifest.entry || CANVAS_ENTRY;- const file = await storage.readFile(manifest, target);- if (!file) return new Response('Not found', { status: 404 });-- const headers = new Headers({- 'access-control-allow-origin': '*',- 'cache-control': 'private, max-age=300',- 'content-security-policy': contentSecurityPolicy(runtimeUrl),- 'content-type': file.contentType,- 'x-content-type-options': 'nosniff',- });-- if (getCanvasFileExtension(target) === 'html') {- const html = injectCanvasPreview(new TextDecoder().decode(file.bytes), runtimeUrl);- return new Response(html, { headers, status: 200 });- }-- return new Response(new Blob([file.bytes as Uint8Array<ArrayBuffer>]), { headers, status: 200 });-};diff --git a/apps/server/src/services/canvas/storage.ts b/apps/server/src/services/canvas/storage.tsindex ab197ba287f..f11c543e2c5 100644--- a/apps/server/src/services/canvas/storage.ts+++ b/apps/server/src/services/canvas/storage.ts@@ -6,6 +6,7 @@ import {type CanvasIssue,type CanvasManifest,type CanvasProjectFile,+ type CanvasProjectSnapshot,getCanvasContentType,isCanvasTextPath,normalizeCanvasPath,@@ -103,6 +104,26 @@ export class CanvasStorageService {};}+ async readSnapshot(key: string): Promise<CanvasProjectSnapshot> {+ const manifest = await this.readManifest(key);+ const files = await pMap(+ Object.keys(manifest.files),+ async (path) => {+ const file = await this.readFile(manifest, path);+ if (!file) throw new Error(`Canvas file ${path} is missing`);+ const text = isCanvasTextPath(path);+ return {+ content: text ? decoder.decode(file.bytes) : Buffer.from(file.bytes).toString('base64'),+ contentType: file.contentType,+ encoding: text ? ('utf8' as const) : ('base64' as const),+ path,+ };+ },+ { concurrency: BLOB_READ_CONCURRENCY },+ );+ return { entry: manifest.entry, files };+ }+async loadProject(manifest: CanvasManifest): Promise<Map<string, CanvasCommitFile>> {const entries = await pMap(Object.entries(manifest.files),diff --git a/locales/en-US/portal.json b/locales/en-US/portal.jsonindex 7c49d955563..57114eae891 100644--- a/locales/en-US/portal.json+++ b/locales/en-US/portal.json@@ -32,7 +32,6 @@"artifacts.svg.download.svg": "Download as SVG","canvas.frameTitle": "Canvas preview","canvas.generating": "Generating v{{version}}…",- "canvas.menu.openInTab": "Open in new tab","canvas.menu.openPublic": "Open public link","canvas.menu.publish": "Publish v{{version}} to a public link","canvas.menu.publishing": "Publishing…",diff --git a/locales/zh-CN/portal.json b/locales/zh-CN/portal.jsonindex 2fb401fd5c7..0b166e1af63 100644--- a/locales/zh-CN/portal.json+++ b/locales/zh-CN/portal.json@@ -32,7 +32,6 @@"artifacts.svg.download.svg": "下载为 SVG","canvas.frameTitle": "画布预览","canvas.generating": "正在生成 v{{version}}…",- "canvas.menu.openInTab": "在新标签页打开","canvas.menu.openPublic": "打开公开链接","canvas.menu.publish": "将 v{{version}} 发布到公开链接","canvas.menu.publishing": "发布中…",diff --git a/package.json b/package.jsonindex 607626f1332..9ebdc1a82af 100644--- a/package.json+++ b/package.json@@ -45,13 +45,13 @@"alint": "alint","alint:audit": "alint --config alint.audit.toml --format json --rule-concurrency 48 src packages","alint:setup": "bun packages/alint/setup.ts",- "build": "bun run build:canvas-runtime && bun run build:spa && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next",+ "build": "bun run build:spa && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next","build:analyze": "cross-env NODE_OPTIONS=--max-old-space-size=81920 next experimental-analyze","build:canvas-runtime": "pnpm --filter @lobechat/canvas-runtime build",- "build:docker": "pnpm run build:canvas-runtime && pnpm run build:spa && pnpm run build:spa:mobile && pnpm run build:spa:auth && pnpm run build:spa:workbench && pnpm run build:spa:share && cross-env WORKBENCH_REQUIRED=1 SHARE_REQUIRED=1 pnpm run build:spa:copy && cross-env NODE_OPTIONS=--max-old-space-size=8192 DOCKER=true next build",+ "build:docker": "pnpm run build:spa && pnpm run build:spa:mobile && pnpm run build:spa:auth && pnpm run build:spa:workbench && pnpm run build:spa:share && cross-env WORKBENCH_REQUIRED=1 SHARE_REQUIRED=1 pnpm run build:spa:copy && cross-env NODE_OPTIONS=--max-old-space-size=8192 DOCKER=true next build","build:next": "cross-env NODE_OPTIONS=--max-old-space-size=7168 bun run build:next:raw","build:next:raw": "next build",- "build:raw": "bun run build:canvas-runtime && bun run build:spa:raw && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next:raw",+ "build:raw": "bun run build:spa:raw && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next:raw","build:spa": "cross-env NODE_OPTIONS=--max-old-space-size=8192 pnpm run build:spa:raw","build:spa:auth": "rm -rf public/_spa public/_spa-auth && cross-env NODE_OPTIONS=--max-old-space-size=8192 AUTH=true vite build","build:spa:copy": "tsx scripts/copySpaBuild.mts && tsx scripts/generateSpaTemplates.mts",diff --git a/packages/business-server/src/canvasPublish.ts b/packages/business-server/src/canvasPublish.tsindex 01cb3682cad..1348c4f5091 100644--- a/packages/business-server/src/canvasPublish.ts+++ b/packages/business-server/src/canvasPublish.ts@@ -18,6 +18,9 @@ export interface PublishCanvasSiteResult {export const isCanvasPublishEnabled = () => false;+export const getCanvasPublishRuntimeUrl = async (_major: number): Promise<string | undefined> =>+ undefined;+export const publishCanvasSite = async (_params: PublishCanvasSiteParams,): Promise<PublishCanvasSiteResult> => {diff --git a/packages/canvas-runtime/scripts/finalize.mjs b/packages/canvas-runtime/scripts/finalize.mjsindex 86d5c2c292c..3de3e59cdb7 100644--- a/packages/canvas-runtime/scripts/finalize.mjs+++ b/packages/canvas-runtime/scripts/finalize.mjs@@ -1,39 +1,51 @@-import fs from 'node:fs';+import { createHash } from 'node:crypto';+import { readdir, readFile, rm, writeFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';-const here = path.dirname(fileURLToPath(import.meta.url));-const dist = path.resolve(here, '../dist');-const jsFile = path.join(dist, 'canvas-runtime.js');-const cssFiles = fs.readdirSync(dist).filter((file) => file.endsWith('.css'));-const addonCss = cssFiles.filter((file) => file !== 'canvas-runtime.css');-if (addonCss.length > 0) {- throw new Error(- `Canvas add-ons must not emit CSS; style them in base.css: ${addonCss.join(', ')}`,+export const finalizeCanvasRuntime = async (dist, major) => {+ const entries = await readdir(dist);+ const cssFiles = entries.filter((file) => file.endsWith('.css'));+ if (cssFiles.some((file) => file !== 'canvas-runtime.css'))+ throw new Error('Canvas add-ons must not emit CSS; style them in base.css');+ if (cssFiles.length) {+ const css = (+ await Promise.all(cssFiles.map((file) => readFile(path.join(dist, file), 'utf8')))+ ).join('\n');+ const literal = JSON.stringify(css)+ .replaceAll('<', String.raw`\u003c`)+ .replaceAll('\u2028', String.raw`\u2028`)+ .replaceAll('\u2029', String.raw`\u2029`);+ const file = path.join(dist, 'canvas-runtime.js');+ const inject = `(function(){if(document.getElementById('lobe-canvas-style'))return;var s=document.createElement('style');s.id='lobe-canvas-style';s.textContent=${literal};(document.head||document.documentElement).appendChild(s)})();\n`;+ await writeFile(file, inject + (await readFile(file, 'utf8')));+ await Promise.all(cssFiles.map((file) => rm(path.join(dist, file))));+ }+ const files = await Promise.all(+ ['canvas-runtime.js', 'canvas-runtime-highlight.js', 'canvas-runtime-mermaid.js']+ .sort()+ .map(async (file) => {+ const bytes = await readFile(path.join(dist, file));+ return {+ path: file,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ size: bytes.length,+ };+ }),);-}-const css = cssFiles.map((file) => fs.readFileSync(path.join(dist, file), 'utf8')).join('\n');-const cssLiteral = JSON.stringify(css)- .replaceAll('<', String.raw`\u003c`)- .replaceAll('\u2028', String.raw`\u2028`)- .replaceAll('\u2029', String.raw`\u2029`);-const inject = `(function(){if(document.getElementById('lobe-canvas-style'))return;var s=document.createElement('style');s.id='lobe-canvas-style';s.textContent=${cssLiteral};(document.head||document.documentElement).appendChild(s)})();\n`;--fs.writeFileSync(jsFile, inject + fs.readFileSync(jsFile, 'utf8'));-for (const file of cssFiles) fs.rmSync(path.join(dist, file));+ // Tuples keep the cross-repository digest independent of JSON object key order.+ const revision = createHash('sha256')+ .update(JSON.stringify([major, files.map((file) => [file.path, file.sha256, file.size])]))+ .digest('hex');+ const manifest = { major, revision, files };+ await writeFile(path.join(dist, 'manifest.json'), JSON.stringify(manifest));+ return manifest;+};-const manifestSource = fs.readFileSync(- path.resolve(here, '../../canvas/src/project/manifest.ts'),- 'utf8',-);-const CANVAS_RUNTIME_MAJOR = Number(/CANVAS_RUNTIME_MAJOR = (\d+)/.exec(manifestSource)[1]);-const target = path.resolve(here, `../../../public/canvas-runtime/v${CANVAS_RUNTIME_MAJOR}`);-fs.rmSync(target, { force: true, recursive: true });-fs.mkdirSync(target, { recursive: true });-const bytes = {};-for (const file of fs.readdirSync(dist).filter((name) => name.endsWith('.js'))) {- fs.copyFileSync(path.join(dist, file), path.join(target, file));- bytes[file] = fs.statSync(path.join(dist, file)).size;+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const here = path.dirname(fileURLToPath(import.meta.url));+ const source = await readFile(path.resolve(here, '../../canvas/src/project/manifest.ts'), 'utf8');+ const major = Number(/CANVAS_RUNTIME_MAJOR = (\d+)/.exec(source)?.[1]);+ if (!Number.isInteger(major) || major < 1) throw new Error('Missing Canvas runtime major');+ console.log(JSON.stringify(await finalizeCanvasRuntime(path.resolve(here, '../dist'), major)));}--console.log(JSON.stringify({ bytes, target }));diff --git a/packages/canvas-runtime/scripts/finalize.test.ts b/packages/canvas-runtime/scripts/finalize.test.tsnew file mode 100644index 00000000000..402e71e71b8--- /dev/null+++ b/packages/canvas-runtime/scripts/finalize.test.ts@@ -0,0 +1,37 @@+import { createHash } from 'node:crypto';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { expect, it } from 'vitest';++import { finalizeCanvasRuntime } from './finalize.mjs';++it('emits a content-addressed release without copying assets to the app public directory', async () => {+ const dist = await mkdtemp(path.join(tmpdir(), 'canvas-release-'));+ try {+ for (const file of [+ 'canvas-runtime.js',+ 'canvas-runtime-highlight.js',+ 'canvas-runtime-mermaid.js',+ ])+ await writeFile(path.join(dist, file), 'window.runtime=true;');+ await writeFile(path.join(dist, 'canvas-runtime.css'), 'body{color:inherit}');+ const first = await finalizeCanvasRuntime(dist, 1);+ expect(first.revision).toMatch(/^[\da-f]{64}$/);+ expect(first.files).toHaveLength(3);+ expect(first.revision).toBe(+ createHash('sha256')+ .update(JSON.stringify([1, first.files.map((file) => [file.path, file.sha256, file.size])]))+ .digest('hex'),+ );+ expect(await readFile(path.join(dist, 'canvas-runtime.js'), 'utf8')).toContain(+ 'body{color:inherit}',+ );+ expect(JSON.parse(await readFile(path.join(dist, 'manifest.json'), 'utf8'))).toEqual(first);+ const second = await finalizeCanvasRuntime(dist, 1);+ expect(second.revision).toBe(first.revision);+ } finally {+ await rm(dist, { force: true, recursive: true });+ }+});diff --git a/packages/canvas-runtime/src/element.test.tsx b/packages/canvas-runtime/src/element.test.tsxindex 883c4978627..977cdb18384 100644--- a/packages/canvas-runtime/src/element.test.tsx+++ b/packages/canvas-runtime/src/element.test.tsx@@ -52,6 +52,24 @@ const mount = async (html: string) => {};describe('canvas elements', () => {+ it('keeps business DOM addressable while component rendering is pending', async () => {+ const main = document.createElement('main');+ main.innerHTML = '<lobe-card><button id="project-action">Run</button></lobe-card>';+ const button = main.querySelector('button')!;+ const listener = vi.fn();+ button.addEventListener('click', listener);++ await act(async () => {+ document.body.append(main);+ expect(document.getElementById('project-action')).toBe(button);+ });++ expect(main.querySelectorAll('#project-action')).toHaveLength(1);+ expect(document.getElementById('project-action')).toBe(button);+ button.click();+ expect(listener).toHaveBeenCalledOnce();+ });+it('renders every element through one shared React root and keeps light-DOM children', async () => {const main = await mount('<lobe-card title="Cost"><p>Body <lobe-tag color="green">ok</lobe-tag></p></lobe-card><lobe-tag>second</lobe-tag>',diff --git a/packages/canvas-runtime/src/element.ts b/packages/canvas-runtime/src/element.tsindex 52d8563cfec..b7d5297e2b8 100644--- a/packages/canvas-runtime/src/element.ts+++ b/packages/canvas-runtime/src/element.ts@@ -76,7 +76,8 @@ export const defineCanvasElement = (this.#value = Number(this.#value);}this.#checked = this.#readChecked();- this.replaceChildren();+ // Keep business nodes in the document until the React slot adopts them.+ if (spec.children !== 'content') this.replaceChildren();for (const source of sources) this.#loadSource(source);}getHosts().register(this, () => view(this.#context()));diff --git a/packages/canvas/package.json b/packages/canvas/package.jsonindex 4a68aa5af91..e1be1e531fb 100644--- a/packages/canvas/package.json+++ b/packages/canvas/package.json@@ -6,6 +6,7 @@"exports": {".": "./src/index.ts","./mermaid": "./src/mermaid.ts",+ "./preview": "./src/preview/index.ts","./runtime": "./src/runtime/index.ts"},"main": "./src/index.ts",@@ -15,7 +16,10 @@"test:coverage": "vitest --coverage --silent='passed-only'"},"dependencies": {+ "acorn": "^8.19.0",+ "acorn-walk": "^8.3.5","htmlparser2": "^10.1.0",- "pele": "^1.6.0"+ "pele": "^1.6.0",+ "postcss-value-parser": "^4.2.0"}}diff --git a/packages/canvas/src/index.ts b/packages/canvas/src/index.tsindex 5345203af2a..c439398bc5e 100644--- a/packages/canvas/src/index.ts+++ b/packages/canvas/src/index.ts@@ -2,6 +2,7 @@ export * from './project/changes';export * from './project/limits';export * from './project/manifest';export * from './project/path';+export type * from './project/snapshot';export * from './schema/components';export * from './schema/reference';export type * from './schema/types';diff --git a/packages/canvas/src/preview/index.ts b/packages/canvas/src/preview/index.tsnew file mode 100644index 00000000000..6601502efb0--- /dev/null+++ b/packages/canvas/src/preview/index.ts@@ -0,0 +1,23 @@+import type { CanvasPreviewProject } from '../project/snapshot';+import { installCanvasBridge } from '../runtime/bridge';+import { installCanvasProject, installCanvasProjectGlobals } from './install';++export { prepareCanvasProject } from './prepare';++export const createCanvasPreviewDocument = (+ project: CanvasPreviewProject,+ page = project.entry,+ hash = '',+) => {+ const args = JSON.stringify([+ project,+ page,+ installCanvasBridge.toString(),+ installCanvasProjectGlobals.toString(),+ hash,+ ]).replaceAll('<', '\\u003c');+ const bootstrap = installCanvasProject+ .toString()+ .replaceAll(/<\/script/gi, '<' + '\\' + '/script');+ return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; media-src data: blob:; connect-src blob:; form-action 'none'; base-uri 'none'"><script>(${bootstrap})(...${args});</script></head><body></body></html>`;+};diff --git a/packages/canvas/src/preview/install.test.ts b/packages/canvas/src/preview/install.test.tsnew file mode 100644index 00000000000..6d9f73dda4a--- /dev/null+++ b/packages/canvas/src/preview/install.test.ts@@ -0,0 +1,98 @@+// @vitest-environment happy-dom+import { afterEach, expect, it, vi } from 'vitest';++import { createCanvasPreviewDocument } from './index';+import { installCanvasProject, installCanvasProjectGlobals } from './install';+import { prepareCanvasProject } from './prepare';++afterEach(() => {+ window.dispatchEvent(new Event('lobe-canvas-dispose'));+ vi.restoreAllMocks();+});++it('keeps HTML and closing script tags inside the serialized bootstrap until it runs', () => {+ const html = createCanvasPreviewDocument(+ prepareCanvasProject({+ entry: 'index.html',+ files: [+ {+ path: 'index.html',+ content: '<script>document.title="safe"</script><h1>Canvas</h1>',+ contentType: 'text/html',+ encoding: 'utf8',+ },+ ],+ }),+ );+ const document = new DOMParser().parseFromString(html, 'text/html');+ expect(document.querySelectorAll('script')).toHaveLength(1);+ expect(document.querySelector('h1')).toBeNull();+ expect(() => new Function(document.querySelector('script')!.textContent!)).not.toThrow();+});++it.each(['lowercase', 'uppercase'])(+ 'renders %s HTML/CSS resources with iframe-owned blobs and a complete import map',+ async (casing) => {+ const htmlPath = casing === 'uppercase' ? 'INDEX.HTML' : 'index.html';+ const cssPath = casing === 'uppercase' ? 'css/APP.CSS' : 'css/app.css';+ const blobs: Blob[] = [];+ vi.spyOn(URL, 'createObjectURL').mockImplementation((blob) => {+ blobs.push(blob as Blob);+ return `blob:null/${blobs.length}`;+ });+ const write = vi.spyOn(document, 'write').mockImplementation(() => {});+ vi.spyOn(document, 'open').mockImplementation(() => document);+ vi.spyOn(document, 'close').mockImplementation(() => {});+ installCanvasProject(+ prepareCanvasProject({+ entry: htmlPath,+ files: [+ {+ path: htmlPath,+ content: `<html><head><link rel="stylesheet" href="${cssPath}"></head><body><img src="img/a.svg#icon"><script type="module" src="app.js"></script></body></html>`,+ contentType: 'text/html',+ encoding: 'utf8',+ },+ {+ path: cssPath,+ content: 'body{background:url(../img/a.svg)}',+ contentType: 'text/css',+ encoding: 'utf8',+ },+ { path: 'img/a.svg', content: '<svg/>', contentType: 'image/svg+xml', encoding: 'utf8' },+ {+ path: 'app.js',+ content: 'export const a=1',+ contentType: 'text/javascript',+ encoding: 'utf8',+ },+ ],+ }),+ htmlPath,+ 'function bridge(){}',+ 'function globals(){}',+ );++ const html = String(write.mock.calls[0][0]);+ expect(blobs).toHaveLength(3);+ expect(html).toContain('type="importmap"');+ expect(html).toContain('lobe-canvas-project/app.js');+ expect(html).toContain('src="blob:null/1#icon"');+ expect(html).not.toContain('href="css/app.css"');+ expect(await blobs.find((blob) => blob.type === 'text/css')!.text()).toContain('blob:null/1');+ },+);++it('resolves dynamic resource URLs and releases each project URL once on disposal', () => {+ const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});+ installCanvasProjectGlobals({ 'img/a.svg': 'blob:null/image' }, 'index.html', [+ 'blob:null/image',+ ]);+ const resolve = Reflect.get(window, '__LOBE_CANVAS_URL__');+ expect(resolve('js/main.js', '../img/a.svg#icon').href).toBe('blob:null/image#icon');+ expect(() => resolve('js/main.js', 'https://example.com/a.svg')).toThrow();+ window.dispatchEvent(new Event('lobe-canvas-dispose'));+ window.dispatchEvent(new Event('lobe-canvas-dispose'));+ expect(revoke).toHaveBeenCalledExactlyOnceWith('blob:null/image');+ expect(Reflect.get(window, '__LOBE_CANVAS_URL__')).toBeUndefined();+});diff --git a/packages/canvas/src/preview/install.ts b/packages/canvas/src/preview/install.tsnew file mode 100644index 00000000000..0921fbfd024--- /dev/null+++ b/packages/canvas/src/preview/install.ts@@ -0,0 +1,156 @@+import type { CanvasPreviewProject } from '../project/snapshot';++// These functions are serialized into srcdoc; keep them independent of module scope.+export function installCanvasProjectGlobals(+ urls: Record<string, string>,+ page: string,+ owned: string[],+) {+ let disposed = false;+ const resolve = (from: string, target: string) => {+ const url = new URL(target, `https://canvas.invalid/${from}`);+ const path = decodeURIComponent(url.pathname.slice(1));+ if (url.origin !== 'https://canvas.invalid' || !urls[path])+ throw new Error(`Missing Canvas resource: ${target}`);+ return urls[path] + url.hash;+ };+ let load: ((url: string, options?: unknown) => Promise<unknown>) | undefined;+ let reject: ((cause: Error) => void) | undefined;+ const ready = new Promise<(url: string, options?: unknown) => Promise<unknown>>(+ (resolve, onError) => {+ reject = onError;+ window.addEventListener(+ 'lobe-canvas-project-import',+ (event) => {+ load = (event as CustomEvent).detail;+ resolve(load!);+ },+ { once: true },+ );+ },+ );+ // Disposal may happen before any project module requests an import.+ void ready.catch(() => {});+ Reflect.set(+ window,+ '__LOBE_CANVAS_IMPORT__',+ async (from: string, target: string, options?: unknown) => {+ const url = resolve(from, String(target));+ const importModule = load ?? (await ready);+ if (disposed) throw new Error('Canvas project disposed');+ return importModule(url, options);+ },+ );+ Reflect.set(+ window,+ '__LOBE_CANVAS_URL__',+ (from: string, target: string) => new URL(resolve(from, String(target))),+ );+ const navigate = (event: MouseEvent) => {+ const anchor = event.composedPath().find((node) => node instanceof HTMLAnchorElement);+ const href = anchor instanceof HTMLAnchorElement ? anchor.getAttribute('href') : undefined;+ if (href?.startsWith('#')) {+ event.preventDefault();+ document.getElementById(decodeURIComponent(href.slice(1)))?.scrollIntoView();+ return;+ }+ if (!href?.startsWith('lobe-canvas-page/')) return;+ event.preventDefault();+ const target = href.slice('lobe-canvas-page/'.length);+ window.parent.postMessage(+ {+ source: 'lobe-canvas',+ type: 'navigate',+ path: decodeURIComponent(target.split('#')[0]),+ hash: target.includes('#') ? target.slice(target.indexOf('#')) : '',+ },+ '*',+ );+ };+ document.addEventListener('click', navigate);+ const dispose = () => {+ if (disposed) return;+ disposed = true;+ document.removeEventListener('click', navigate);+ for (const url of owned) URL.revokeObjectURL(url);+ owned.length = 0;+ for (const name of ['__LOBE_CANVAS_IMPORT__', '__LOBE_CANVAS_URL__'])+ Reflect.deleteProperty(window, name);+ reject?.(new Error('Canvas project disposed'));+ window.removeEventListener('lobe-canvas-dispose', dispose);+ };+ window.addEventListener('lobe-canvas-dispose', dispose);+ // Expose the original page only as a base for project-owned resource resolution.+ document.documentElement.dataset.canvasPage = page;+}++export function installCanvasProject(+ project: CanvasPreviewProject,+ page: string,+ bridgeSource: string,+ globalsSource: string,+ hash = '',+) {+ const urls: Record<string, string> = {};+ const owned: string[] = [];+ const visiting = new Set<string>();+ const serialize = (value: unknown) => JSON.stringify(value).replaceAll('<', '\\u003c');+ const create = (content: BlobPart, contentType: string) => {+ const url = URL.createObjectURL(new Blob([content], { type: contentType }));+ owned.push(url);+ return url;+ };+ const fileUrl = (path: string): string => {+ if (urls[path]) return urls[path];+ const file = project.files[path];+ if (!file) throw new Error(`Missing Canvas file: ${path}`);+ if (visiting.has(path)) return create('', 'text/css');+ visiting.add(path);+ let content: BlobPart = file.content;+ if (file.encoding === 'base64')+ content = Uint8Array.from(atob(file.content), (char) => char.charCodeAt(0));+ else if (path.toLowerCase().endsWith('.css')) content = replace(file.content);+ const url = create(content, file.contentType);+ urls[path] = url;+ visiting.delete(path);+ return url;+ };+ const replace = (source: string) =>+ source.replaceAll(/lobe-canvas-file\/([\w%.@-]+)/g, (_match, path: string) =>+ fileUrl(decodeURIComponent(path)),+ );+ try {+ for (const path of Object.keys(project.files))+ if (!path.toLowerCase().endsWith('.html')) fileUrl(path);+ const entry = project.files[page];+ if (!entry || !page.toLowerCase().endsWith('.html'))+ throw new Error(`Missing Canvas page: ${page}`);+ const imports = Object.fromEntries(+ Object.entries(urls).map(([path, url]) => [`lobe-canvas-project/${path}`, url]),+ );+ const injection =+ `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; media-src data: blob:; connect-src blob:; form-action 'none'; base-uri 'none'">` ++ `<script>(${bridgeSource})();(${globalsSource})(${serialize(urls)},${serialize(page)},${serialize(owned)});</script>` ++ `<script type="importmap">${serialize({ imports })}</script>` ++ `<script type="module">window.dispatchEvent(new CustomEvent('lobe-canvas-project-import',{detail:(url,options)=>import(url,options)}));</script>` ++ (hash+ ? `<script>window.addEventListener('load',()=>document.getElementById(${serialize(decodeURIComponent(hash.slice(1)))})?.scrollIntoView(),{once:true});</script>`+ : '');+ let html = replace(entry.content);+ const head = /<head(?:\s[^>]*)?>/i.exec(html);+ if (head) {+ const at = head.index + head[0].length;+ html = html.slice(0, at) + injection + html.slice(at);+ } else+ html = `<!doctype html><html><head><meta charset="utf-8">${injection}</head><body>${html}</body></html>`;+ document.open();+ document.write(html);+ document.close();+ } catch (cause) {+ for (const url of owned) URL.revokeObjectURL(url);+ window.parent.postMessage(+ { source: 'lobe-canvas', type: 'error', message: String(cause) },+ '*',+ );+ }+}diff --git a/packages/canvas/src/preview/prepare.test.ts b/packages/canvas/src/preview/prepare.test.tsnew file mode 100644index 00000000000..b1e8baf153d--- /dev/null+++ b/packages/canvas/src/preview/prepare.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from 'vitest';++import { prepareCanvasProject } from './prepare';++const project = (files: Record<string, string>) => ({+ entry: 'index.html',+ files: Object.entries(files).map(([path, content]) => ({+ content,+ contentType: 'text/plain',+ encoding: 'utf8' as const,+ path,+ })),+});++describe('prepareCanvasProject', () => {+ it.each([+ ['with', 'var result; with ({value: 7}) { result=value; }', 7],+ ['legacy octal', 'var result=010;', 8],+ ['await binding', 'var await=42; var result=await;', 42],+ ])('preserves classic %s scripts inline and in files', (_name, source, expected) => {+ const result = prepareCanvasProject(+ project({+ 'index.html': `<script>${source}</script><script src="classic.js"></script>`,+ 'classic.js': String(source),+ }),+ );++ expect(result.files['index.html'].content).toContain(source);+ expect(new Function(`${result.files['classic.js'].content}; return result;`)()).toBe(expected);+ });++ it('resolves resources against their own file, including CSS imports and component JSON', () => {+ const result = prepareCanvasProject(+ project({+ 'index.html':+ '<link href="css/app.css" rel="stylesheet"><img src="img/a.svg#icon"><lobe-chart data-src="data/chart.json"></lobe-chart>',+ 'css/app.css': '@import "theme.css"; .hero{background:url(../img/a.svg)}',+ 'css/theme.css': 'body{color:inherit}',+ 'img/a.svg': '<svg/>',+ 'data/chart.json': '[]',+ }),+ );++ expect(result.files['index.html'].content).toContain('lobe-canvas-file/css%2Fapp.css');+ expect(result.files['index.html'].content).toContain('lobe-canvas-file/img%2Fa.svg#icon');+ expect(result.files['index.html'].content).toContain('lobe-canvas-file/data%2Fchart.json');+ expect(result.files['css/app.css'].content).toContain('lobe-canvas-file/css%2Ftheme.css');+ expect(result.files['css/app.css'].content).toContain('lobe-canvas-file/img%2Fa.svg');+ });++ it('links cyclic modules, dynamic imports and import.meta resource URLs without changing text', () => {+ const result = prepareCanvasProject(+ project({+ 'index.html': '<script type="module" src="js/main.js"></script>',+ 'js/main.js':+ 'import {value} from "./other.js"; const text="import ./other.js"; export const load=p=>import(p); const image=new URL("../img/a.svg", import.meta.url);',+ 'js/other.js': 'export {load} from "./main.js"; export const value=1;',+ 'img/a.svg': '<svg/>',+ }),+ );++ expect(result.files['js/main.js'].content).toContain('"lobe-canvas-project/js/other.js"');+ expect(result.files['js/main.js'].content).toContain('text="import ./other.js"');+ expect(result.files['js/main.js'].content).toContain('__LOBE_CANVAS_IMPORT__("js/main.js",p)');+ expect(result.files['js/main.js'].content).toContain(+ '__LOBE_CANVAS_URL__("js/main.js","../img/a.svg")',+ );+ expect(result.files['js/other.js'].content).toContain('"lobe-canvas-project/js/main.js"');+ });++ it('keeps anchors and external links while routing project pages inside the preview', () => {+ const result = prepareCanvasProject(+ project({+ 'index.html':+ '<a href="pages/detail.html#title">Detail</a><a href="#here">Here</a><a href="https://example.com">External</a>',+ 'pages/detail.html': '<h1 id="title">Detail</h1>',+ }),+ );+ expect(result.files['index.html'].content).toContain(+ 'lobe-canvas-page/pages%2Fdetail.html#title',+ );+ expect(result.files['index.html'].content).toContain('href="#here"');+ expect(result.files['index.html'].content).toContain('href="https://example.com"');+ });++ it('rejects missing local imports rather than requesting them from the app origin', () => {+ expect(() =>+ prepareCanvasProject(+ project({+ 'index.html': '<script type="module">import "./missing.js"</script>',+ }),+ ),+ ).toThrow(/missing.js/);+ });++ it('preserves data URLs in srcset while resolving file candidates', () => {+ const result = prepareCanvasProject(+ project({+ 'index.html': '<img srcset="data:image/png;base64,aGVsbG8= 1x, image.png 2x">',+ 'image.png': 'image',+ }),+ );+ expect(result.files['index.html'].content).toContain('data:image/png;base64,aGVsbG8= 1x');+ expect(result.files['index.html'].content).toContain('lobe-canvas-file/image.png 2x');+ });+});diff --git a/packages/canvas/src/preview/prepare.ts b/packages/canvas/src/preview/prepare.tsnew file mode 100644index 00000000000..978ece1e894--- /dev/null+++ b/packages/canvas/src/preview/prepare.ts@@ -0,0 +1,178 @@+import { parse } from 'acorn';+import { simple } from 'acorn-walk';+import { DomUtils, parseDocument } from 'htmlparser2';+import valueParser from 'postcss-value-parser';++import { getCanvasFileExtension, resolveCanvasHref } from '../project/path';+import type { CanvasPreviewProject, CanvasProjectSnapshot } from '../project/snapshot';++export const prepareCanvasProject = (snapshot: CanvasProjectSnapshot): CanvasPreviewProject => {+ const files = Object.fromEntries(snapshot.files.map(({ path, ...file }) => [path, { ...file }]));+ const resolve = (from: string, href: string) => {+ const ref = resolveCanvasHref(from, href);+ if (ref.kind !== 'local') return;+ if (!ref.path || !files[ref.path]) throw new Error(`${from}: missing project file ${href}`);+ return ref.path;+ };+ const resource = (from: string, href: string, page = false) => {+ const path = resolve(from, href);+ if (!path) return href;+ const hash = href.includes('#') ? href.slice(href.indexOf('#')) : '';+ const prefix = page && getCanvasFileExtension(path) === 'html' ? 'page' : 'file';+ return `lobe-canvas-${prefix}/${encodeURIComponent(path)}${hash}`;+ };+ const css = (from: string, source: string) => {+ const value = valueParser(source);+ value.walk((node) => {+ if (node.type === 'function' && node.value.toLowerCase() === 'url') {+ const url = node.nodes.find((child) => child.type === 'word' || child.type === 'string');+ if (url) url.value = resource(from, url.value);+ return false;+ }+ });+ for (let i = 0; i < value.nodes.length; i++) {+ const node = value.nodes[i];+ if (node.type !== 'word' || node.value.toLowerCase() !== '@import') continue;+ const next = value.nodes+ .slice(i + 1)+ .find((child) => child.type !== 'space' && child.type !== 'comment');+ if (next?.type === 'string') next.value = resource(from, next.value);+ }+ return value.toString();+ };+ const script = (from: string, source: string) => {+ const edits: { start: number; end: number; text: string }[] = [];+ const special: { start: number; end: number }[] = [];+ let ast: ReturnType<typeof parse>;+ try {+ ast = parse(source, { ecmaVersion: 'latest', sourceType: 'module' });+ } catch {+ // Classic scripts permit non-strict syntax that module parsing rejects.+ ast = parse(source, { ecmaVersion: 'latest', sourceType: 'script' });+ }+ const moduleRef = (node: { start: number; end: number; value?: unknown }) => {+ if (typeof node.value !== 'string') return;+ const path = resolve(from, node.value);+ if (!path) throw new Error(`${from}: imports must reference project files`);+ edits.push({+ start: node.start,+ end: node.end,+ text: JSON.stringify(`lobe-canvas-project/${path}`),+ });+ };+ simple(ast, {+ ImportDeclaration: (node) => moduleRef(node.source),+ ExportAllDeclaration: (node) => moduleRef(node.source),+ ExportNamedDeclaration: (node) => {+ if (node.source) moduleRef(node.source);+ },+ ImportExpression: (node) => {+ edits.push({+ start: node.start,+ end: node.source.start,+ text: `window.__LOBE_CANVAS_IMPORT__(${JSON.stringify(from)},`,+ });+ },+ NewExpression: (node) => {+ const base = node.arguments[1];+ if (+ node.callee.type !== 'Identifier' ||+ node.callee.name !== 'URL' ||+ !base ||+ base.type !== 'MemberExpression' ||+ base.object.type !== 'MetaProperty' ||+ base.property.type !== 'Identifier' ||+ base.property.name !== 'url'+ )+ return;+ special.push({ start: node.start, end: node.end });+ edits.push({+ start: node.start,+ end: node.end,+ text: `window.__LOBE_CANVAS_URL__(${JSON.stringify(from)},${source.slice(node.arguments[0].start, node.arguments[0].end)})`,+ });+ },+ MemberExpression: (node) => {+ if (+ node.object.type === 'MetaProperty' &&+ node.property.type === 'Identifier' &&+ node.property.name === 'url'+ )+ edits.push({+ start: node.start,+ end: node.end,+ text: JSON.stringify(`https://canvas.invalid/${from}`),+ });+ },+ });+ for (const edit of edits+ .filter((edit) => !special.some((range) => edit.start > range.start && edit.end <= range.end))+ .sort((a, b) => b.start - a.start))+ source = source.slice(0, edit.start) + edit.text + source.slice(edit.end);+ return source;+ };+ const srcset = (from: string, source: string) => {+ const edits: { start: number; end: number; text: string }[] = [];+ let i = 0;+ while (i < source.length) {+ while (i < source.length && /[\s,]/.test(source[i])) i++;+ const start = i;+ const data = source.slice(i, i + 5).toLowerCase() === 'data:';+ while (i < source.length && !/\s/.test(source[i]) && (data || source[i] !== ',')) i++;+ let end = i;+ while (source[end - 1] === ',') end--;+ if (end > start) edits.push({ start, end, text: resource(from, source.slice(start, end)) });+ if (end < i || source[i] === ',') continue;+ while (i < source.length && source[i] !== ',') i++;+ }+ for (const edit of edits.reverse())+ source = source.slice(0, edit.start) + edit.text + source.slice(edit.end);+ return source;+ };++ for (const [path, file] of Object.entries(files)) {+ if (file.encoding !== 'utf8') continue;+ switch (getCanvasFileExtension(path)) {+ case 'js':+ case 'mjs': {+ file.content = script(path, file.content);+ break;+ }+ case 'css': {+ file.content = css(path, file.content);+ break;+ }+ case 'html': {+ const doc = parseDocument(file.content);+ const elements = DomUtils.getElementsByTagName('*', doc.children, true);+ for (const element of elements) {+ for (const [name, href] of Object.entries(element.attribs)) {+ if (name === 'style') element.attribs[name] = css(path, href);+ else if (name === 'srcset') element.attribs[name] = srcset(path, href);+ else if (+ ['src', 'href', 'poster', 'xlink:href'].includes(name) ||+ name.endsWith('-src')+ )+ element.attribs[name] = resource(path, href, element.name === 'a');+ }+ for (const child of element.children) {+ if (child.type !== 'text') continue;+ if (element.name === 'style') child.data = css(path, child.data);+ if (+ element.name === 'script' &&+ !element.attribs.src &&+ (!element.attribs.type ||+ element.attribs.type === 'module' ||+ element.attribs.type.includes('javascript'))+ )+ child.data = script(path, child.data);+ }+ }+ file.content = DomUtils.getOuterHTML(doc);+ break;+ }+ }+ }+ if (!files[snapshot.entry]) throw new Error(`Missing Canvas entry ${snapshot.entry}`);+ return { entry: snapshot.entry, files };+};diff --git a/packages/canvas/src/project/snapshot.ts b/packages/canvas/src/project/snapshot.tsnew file mode 100644index 00000000000..2c01702c98d--- /dev/null+++ b/packages/canvas/src/project/snapshot.ts@@ -0,0 +1,16 @@+export interface CanvasSnapshotFile {+ content: string;+ contentType: string;+ encoding: 'base64' | 'utf8';+ path: string;+}++export interface CanvasProjectSnapshot {+ entry: string;+ files: CanvasSnapshotFile[];+}++export interface CanvasPreviewProject {+ entry: string;+ files: Record<string, Omit<CanvasSnapshotFile, 'path'>>;+}diff --git a/packages/canvas/src/runtime/bridge.test.ts b/packages/canvas/src/runtime/bridge.test.tsindex 20218cf0bb1..f1ac49c09c4 100644--- a/packages/canvas/src/runtime/bridge.test.ts+++ b/packages/canvas/src/runtime/bridge.test.ts@@ -10,21 +10,20 @@ afterEach(() => {vi.unstubAllGlobals();});-it('initializes standalone previews without secure-context UUID support', () => {+it('initializes without secure-context UUID support or an HTTP runtime fallback', () => {vi.stubGlobal('crypto', { randomUUID: undefined });- expect(() => installCanvasBridge('/runtime.js')).not.toThrow();- expect(document.querySelector('script')?.src).toContain('/runtime.js');+ expect(() => installCanvasBridge()).not.toThrow();+ expect(document.querySelector('script')).toBeNull();});it('keeps a BFCache preview alive and disposes only on a final pagehide', () => {const disposed = vi.fn();window.addEventListener('lobe-canvas-dispose', disposed, { once: true });- installCanvasBridge('/runtime.js');+ installCanvasBridge();const cached = new PageTransitionEvent('pagehide');Object.defineProperty(cached, 'persisted', { value: true });window.dispatchEvent(cached);expect(disposed).not.toHaveBeenCalled();- expect(document.querySelector('script')).not.toBeNull();window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: false }));expect(disposed).toHaveBeenCalledOnce();expect(document.querySelector('script')).toBeNull();diff --git a/packages/canvas/src/runtime/bridge.ts b/packages/canvas/src/runtime/bridge.tsindex 4aa45c332ed..8919b848658 100644--- a/packages/canvas/src/runtime/bridge.ts+++ b/packages/canvas/src/runtime/bridge.ts@@ -1,7 +1,7 @@import type { CanvasRuntimeBundle } from './types';// Serialized into preview HTML: keep this function self-contained.-export function installCanvasBridge(fallbackRuntimeUrl: string) {+export function installCanvasBridge() {const host = window.parent;const instanceId = `${Date.now()}-${Math.random()}`;const urls = new Set<string>();@@ -179,11 +179,4 @@ window.parent.postMessage({ source: 'lobe-canvas', type: 'runtime-loaded', insta},{ once: true },);- if (host === window) {- // A private preview opened directly reuses the publication runtime.- const script = document.createElement('script');- script.defer = true;- script.src = fallbackRuntimeUrl;- append(script);- }}diff --git a/packages/locales/src/default/portal.ts b/packages/locales/src/default/portal.tsindex c8bbb15e541..f1d14e1b721 100644--- a/packages/locales/src/default/portal.ts+++ b/packages/locales/src/default/portal.ts@@ -40,7 +40,6 @@ export default {'artifacts.svg.download.svg': 'Download as SVG','canvas.frameTitle': 'Canvas preview','canvas.generating': 'Generating v{{version}}…',- 'canvas.menu.openInTab': 'Open in new tab','canvas.menu.versionItem': 'v{{version}} · {{date}}','canvas.menu.versions': 'Version history','canvas.menu.openPublic': 'Open public link',diff --git a/packages/trpc/src/client/lambda.test.ts b/packages/trpc/src/client/lambda.test.tsindex cfbc0b8be9f..e050bbcb22e 100644--- a/packages/trpc/src/client/lambda.test.ts+++ b/packages/trpc/src/client/lambda.test.ts@@ -1,3 +1,5 @@+import { initTRPC } from '@trpc/server';+import { fetchRequestHandler } from '@trpc/server/adapters/fetch';import superjson from 'superjson';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -106,6 +108,44 @@ describe('lambdaClient transport lanes', () => {fetchMock.mockReset();});+ it('streams a large Canvas snapshot without buffering it with ordinary reads', async () => {+ const t = initTRPC.create({ transformer: superjson });+ const snapshot = { entry: 'index.html', files: [{ content: 'a'.repeat(6 * 1024 * 1024) }] };+ const router = t.router({+ agent: t.router({ getAgentConfigById: t.procedure.query(() => null) }),+ canvas: t.router({ getProject: t.procedure.query(() => snapshot) }),+ });+ const transports: { streaming: boolean; url: string }[] = [];+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init: RequestInit) => {+ const req = new Request(new URL(String(input), 'http://localhost'), init);+ const streaming = req.headers.get('trpc-accept') === 'application/jsonl';+ transports.push({ streaming, url: req.url });+ const response = await fetchRequestHandler({+ createContext: () => ({}),+ endpoint: '/trpc/lambda',+ req,+ router,+ });+ if (streaming) return response;+ const text = await response.text();+ return text.length > 4_500_000+ ? new Response('Response payload too large', { status: 500 })+ : new Response(text, { headers: response.headers });+ });++ const [result] = await Promise.all([+ lambdaClient.canvas.getProject.query({ canvasId: 'cvs_large', version: 1 }),+ lambdaClient.agent.getAgentConfigById.query({ agentId: 'agt_test' }),+ ]);++ expect(result).toEqual(snapshot);+ expect(transports).toHaveLength(2);+ expect(transports.find((item) => item.streaming)?.url).toContain('/canvas.getProject?');+ expect(transports.find((item) => item.streaming)?.url).not.toContain(+ 'agent.getAgentConfigById',+ );+ });+// Regression: every `device.*` read hops from the server to one of the user's// own machines and is capped by a 10-60s RPC timeout. Batched with ordinary// lambda reads, one sleeping laptop held the whole batch's response — opening adiff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 4e746c032b7..77c43a1036b 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -3,6 +3,7 @@ import { type TRPCClientError, type TRPCLink } from '@trpc/client';import {createTRPCClient,httpBatchLink,+ httpBatchStreamLink,httpLink,httpSubscriptionLink,splitLink,@@ -284,7 +285,12 @@ const buildBatchedHttpLinks = (options: typeof linkOptions) =>const buildHttpLinks = (options: typeof linkOptions) =>splitLink({condition: (op) => !!getLlmRelayHeaders(op),- false: buildBatchedHttpLinks(options),+ false: splitLink({+ // Source snapshots can exceed the serverless buffered-response limit.+ condition: (op) => op.path === 'canvas.getProject',+ false: buildBatchedHttpLinks(options),+ true: httpBatchStreamLink({ ...options, maxItems: 1 }),+ }),true: httpLink({...options,headers: async ({ op }) => ({diff --git a/src/app/(backend)/canvas-preview/[token]/[[...path]]/route.ts b/src/app/(backend)/canvas-preview/[token]/[[...path]]/route.tsdeleted file mode 100644index b2f66f4adc0..00000000000--- a/src/app/(backend)/canvas-preview/[token]/[[...path]]/route.ts+++ /dev/null@@ -1,24 +0,0 @@-import { getServerDB } from '@/database/server';-import { createCanvasStorageService } from '@/server/services/canvas';-import { resolveCanvasRuntimeUrl } from '@/server/services/canvas/runtimeUrl';-import { serveCanvasFile } from '@/server/services/canvas/serve';--type Params = Promise<{ path?: string[]; token: string }>;--export const GET = async (_req: Request, segmentData: { params: Params }) => {- const { path, token } = await segmentData.params;- const db = await getServerDB();-- try {- return await serveCanvasFile({- createStorage: (payload) =>- createCanvasStorageService(db, payload.userId, payload.workspaceId),- path: path?.join('/') ?? '',- runtimeUrl: resolveCanvasRuntimeUrl(),- token,- });- } catch (error) {- console.error('Canvas preview error:', error);- return new Response('Internal server error', { status: 500 });- }-};diff --git a/src/features/CanvasModal/index.tsx b/src/features/CanvasModal/index.tsxnew file mode 100644index 00000000000..c9dbf047eac--- /dev/null+++ b/src/features/CanvasModal/index.tsx@@ -0,0 +1,52 @@+'use client';++import { createModal, Empty } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import CanvasFrame from '@/features/Conversation/WorkingSidebar/Canvas/CanvasFrame';+import { useClientDataSWR } from '@/libs/swr';+import { canvasService } from '@/services/canvas';++interface CanvasModalProps {+ canvasId: string;+ version?: number;+}++const CanvasModalContent = ({ canvasId, version }: CanvasModalProps) => {+ const { t } = useTranslation('portal');+ const { data, error, isLoading, mutate } = useClientDataSWR(+ ['canvas-modal-version', canvasId, version ?? 'latest'],+ () => canvasService.getVersion(canvasId, version),+ );++ return (+ <AsyncBoundary+ data={data}+ empty={<Empty description={t('canvas.notFound')} />}+ error={error}+ isEmpty={data === null}+ isLoading={isLoading}+ onRetry={() => {+ void mutate();+ }}+ >+ {data && <CanvasFrame canvasId={data.canvasId} version={data.version} />}+ </AsyncBoundary>+ );+};++const CanvasModalTitle = () => {+ const { t } = useTranslation('portal');+ return t('canvas.frameTitle');+};++export const createCanvasModal = (canvasId: string, version?: number) =>+ createModal({+ content: <CanvasModalContent canvasId={canvasId} version={version} />,+ footer: null,+ maskClosable: true,+ styles: { content: { display: 'flex', height: '75vh', minHeight: 0, padding: 0 } },+ title: <CanvasModalTitle />,+ width: 'min(95vw, 1200px)',+ });diff --git a/src/features/CanvasModal/loader.ts b/src/features/CanvasModal/loader.tsnew file mode 100644index 00000000000..6c42db1e0a6--- /dev/null+++ b/src/features/CanvasModal/loader.ts@@ -0,0 +1,4 @@+export const openCanvasModal = async (canvasId: string, version?: number) => {+ const { createCanvasModal } = await import('.');+ return createCanvasModal(canvasId, version);+};diff --git a/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsx b/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsxindex cbbf3b2e498..60fd65bb3df 100644--- a/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsx+++ b/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsx@@ -1,13 +1,18 @@+import type { CanvasPreviewProject } from '@lobechat/canvas';+import { createCanvasPreviewDocument } from '@lobechat/canvas/preview';import { Alert, useThemeMode } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { SWRConfig } from 'swr';+import AsyncBoundary from '@/components/AsyncBoundary';import { useUserStore } from '@/store/user';import { userGeneralSettingsSelectors } from '@/store/user/selectors';import { attachCanvasRuntime } from './runtime/host';+import { useFetchCanvasProject } from './useFetchCanvasProject';const styles = stylex.create({details: {@@ -34,13 +39,19 @@ interface CanvasError {const MAX_ERRORS = 10;-const CanvasFrame = memo<{ src: string }>(({ src }) => {+const CanvasDocumentFrame = memo<{ project: CanvasPreviewProject }>(({ project }) => {const { t } = useTranslation('portal');const ref = useRef<HTMLIFrameElement>(null);const { isDarkMode } = useThemeMode();const primaryColor = useUserStore(userGeneralSettingsSelectors.primaryColor);const neutralColor = useUserStore(userGeneralSettingsSelectors.neutralColor);const [errors, setErrors] = useState<CanvasError[]>([]);+ const [location, setLocation] = useState({ path: project.entry, hash: '' });+ // Serializing a project can include megabytes of assets; themes and errors must not rebuild it.+ const srcDoc = useMemo(+ () => createCanvasPreviewDocument(project, location.path, location.hash),+ [project, location],+ );const theme = useMemo(() => ({ appearance: isDarkMode ? 'dark' : 'light', neutralColor, primaryColor }),@@ -56,7 +67,7 @@ const CanvasFrame = memo<{ src: string }>(({ src }) => {useEffect(postTheme, [postTheme]);- useEffect(() => setErrors([]), [src]);+ useEffect(() => setErrors([]), [srcDoc]);useEffect(() => {const frame = ref.current;@@ -65,13 +76,23 @@ const CanvasFrame = memo<{ src: string }>(({ src }) => {console.error('[lobe-canvas]', error);setErrors((current) => [...current, { message: String(error) }].slice(-MAX_ERRORS));});- }, [src]);+ }, [project]);useEffect(() => {const onMessage = (event: MessageEvent) => {if (event.source !== ref.current?.contentWindow || event.data?.source !== 'lobe-canvas')return;if (event.data.type === 'ready') postTheme();+ if (+ event.data.type === 'navigate' &&+ typeof event.data.path === 'string' &&+ event.data.path.toLowerCase().endsWith('.html') &&+ project.files[event.data.path]+ )+ setLocation({+ path: event.data.path,+ hash: typeof event.data.hash === 'string' ? event.data.hash : '',+ });if (event.data.type === 'error') {setErrors((current) =>current.length >= MAX_ERRORS@@ -85,7 +106,7 @@ const CanvasFrame = memo<{ src: string }>(({ src }) => {};window.addEventListener('message', onMessage);return () => window.removeEventListener('message', onMessage);- }, [postTheme]);+ }, [postTheme, project]);return (<>@@ -109,7 +130,7 @@ const CanvasFrame = memo<{ src: string }>(({ src }) => {{...stylex.props(styles.frame)}ref={ref}sandbox="allow-scripts allow-popups allow-forms allow-downloads"- src={src}+ srcDoc={srcDoc}title={t('canvas.frameTitle')}onLoad={postTheme}/>@@ -117,6 +138,30 @@ const CanvasFrame = memo<{ src: string }>(({ src }) => {);});-CanvasFrame.displayName = 'CanvasFrame';+CanvasDocumentFrame.displayName = 'CanvasDocumentFrame';++const CanvasProjectFrame = ({ canvasId, version }: { canvasId: string; version: number }) => {+ const { data, error, isLoading, mutate } = useFetchCanvasProject(canvasId, version);+ return (+ <AsyncBoundary+ data={data}+ error={error}+ isLoading={isLoading}+ onRetry={() => {+ void mutate();+ }}+ >+ {data && <CanvasDocumentFrame project={data} />}+ </AsyncBoundary>+ );+};++// Project bytes belong to this mounted preview, rather than the application's long-lived SWR cache.+const previewCache = { provider: () => new Map() };+const CanvasFrame = (props: { canvasId: string; version: number }) => (+ <SWRConfig value={previewCache}>+ <CanvasProjectFrame {...props} />+ </SWRConfig>+);export default CanvasFrame;diff --git a/src/features/Conversation/WorkingSidebar/Canvas/CanvasPane.tsx b/src/features/Conversation/WorkingSidebar/Canvas/CanvasPane.tsxindex 9035ab3f82b..91b5d4d1910 100644--- a/src/features/Conversation/WorkingSidebar/Canvas/CanvasPane.tsx+++ b/src/features/Conversation/WorkingSidebar/Canvas/CanvasPane.tsx@@ -112,7 +112,11 @@ const CanvasPane = memo<CanvasPaneProps>(({ canvasId }) => {</Flexbox>)}<Flexbox flex={1} {...stylex.props(styles.content, showPending && styles.dimmed)}>- <CanvasFrame src={data.previewUrl} />+ <CanvasFrame+ canvasId={data.canvasId}+ key={data.metadata.manifestKey}+ version={data.version}+ /></Flexbox></Flexbox>);diff --git a/src/features/Conversation/WorkingSidebar/Canvas/useCanvasMoreMenu.tsx b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasMoreMenu.tsxindex b515678df1e..7872c3d885e 100644--- a/src/features/Conversation/WorkingSidebar/Canvas/useCanvasMoreMenu.tsx+++ b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasMoreMenu.tsx@@ -20,14 +20,7 @@ export const useCanvasMoreMenu = (if (!data) return;- const extraItems: DropdownItem[] = [- ...publishItems,- {- key: 'open-in-tab',- label: t('canvas.menu.openInTab'),- onClick: () => window.open(data.previewUrl, '_blank', 'noopener,noreferrer'),- },- ];+ const extraItems: DropdownItem[] = [...publishItems];if (versions && versions.length > 1) {extraItems.unshift({diff --git a/src/features/Conversation/WorkingSidebar/Canvas/useFetchCanvasProject.ts b/src/features/Conversation/WorkingSidebar/Canvas/useFetchCanvasProject.tsnew file mode 100644index 00000000000..6e37bb5fbb2--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Canvas/useFetchCanvasProject.ts@@ -0,0 +1,16 @@+import { prepareCanvasProject } from '@lobechat/canvas/preview';++import { useClientDataSWR } from '@/libs/swr';+import { canvasService } from '@/services/canvas';++export const useFetchCanvasProject = (canvasId: string, version: number) =>+ useClientDataSWR(+ ['canvas-project', canvasId, version],+ async () => prepareCanvasProject(await canvasService.getProject(canvasId, version)),+ {+ dedupingInterval: Infinity,+ revalidateIfStale: false,+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ },+ );diff --git a/src/features/WorkGallery/useOpenWork.test.ts b/src/features/WorkGallery/useOpenWork.test.tsnew file mode 100644index 00000000000..2a2e1088901--- /dev/null+++ b/src/features/WorkGallery/useOpenWork.test.ts@@ -0,0 +1,49 @@+import type { WorkSummaryItem } from '@lobechat/types';+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useOpenWork } from './useOpenWork';++const { createModal, getVersion } = vi.hoisted(() => ({+ createModal: vi.fn(),+ getVersion: vi.fn(),+}));++vi.mock('@lobehub/ui', () => ({ createModal }));+vi.mock('@/services/canvas', () => ({ canvasService: { getVersion } }));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => vi.fn(),+}));+vi.mock('@/features/Work/descriptors', () => ({+ getWorkTypeDescriptor: () => ({+ getOpenTarget: (item: WorkSummaryItem) => ({+ canvasId: item.resourceId,+ kind: 'canvas',+ }),+ }),+ isSafeExternalUrl: () => true,+}));+vi.mock('@/features/DocumentModal/loader', () => ({ openDocumentModal: vi.fn() }));+vi.mock('@/components/AsyncBoundary', () => ({ default: () => null }));+vi.mock('@/libs/swr', () => ({ useClientDataSWR: vi.fn() }));+vi.mock('@/features/Conversation/WorkingSidebar/Canvas/CanvasFrame', () => ({+ default: () => null,+}));++describe('useOpenWork Canvas entry', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(window, 'open').mockImplementation(() => null);+ getVersion.mockResolvedValue({ canvasId: 'cvs_gallery', version: 2 });+ });++ it('opens an in-app preview without depending on a private preview URL', async () => {+ const { result } = renderHook(() => useOpenWork());+ await act(async () => {+ result.current({ resourceId: 'cvs_gallery', type: 'canvas' } as WorkSummaryItem);+ });++ await waitFor(() => expect(createModal).toHaveBeenCalledOnce());+ expect(window.open).not.toHaveBeenCalled();+ });+});diff --git a/src/features/WorkGallery/useOpenWork.ts b/src/features/WorkGallery/useOpenWork.tsindex ad30ba87774..b2ad8cff633 100644--- a/src/features/WorkGallery/useOpenWork.ts+++ b/src/features/WorkGallery/useOpenWork.ts@@ -2,10 +2,10 @@ import type { WorkSummaryItem } from '@lobechat/types';import { useCallback } from 'react';import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';+import { openCanvasModal } from '@/features/CanvasModal/loader';import { openDocumentModal } from '@/features/DocumentModal/loader';import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { canvasService } from '@/services/canvas';/*** Open a Work summary item at its canonical target (document modal, external@@ -22,11 +22,7 @@ export const useOpenWork = () => {switch (openTarget.kind) {case 'canvas': {- void canvasService- .getVersion(openTarget.canvasId, openTarget.version)- .then(- (detail) => detail && window.open(detail.previewUrl, '_blank', 'noopener,noreferrer'),- );+ void openCanvasModal(openTarget.canvasId, openTarget.version);return;}case 'document': {diff --git a/src/services/canvas.ts b/src/services/canvas.tsindex 379429dbe6e..d948028bec4 100644--- a/src/services/canvas.ts+++ b/src/services/canvas.ts@@ -10,6 +10,9 @@ export type CanvasVersionSummary = Awaited<>[number];class CanvasService {+ getProject = (canvasId: string, version: number) =>+ lambdaClient.canvas.getProject.query({ canvasId, version });+getVersion = (canvasId: string, version?: number) =>lambdaClient.canvas.getVersion.query({ canvasId, version });diff --git a/vite.config.ts b/vite.config.tsindex 033d495ddf0..054be6b7437 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -125,7 +125,8 @@ export default defineConfig({__dirname,isAuth ? 'index.auth.html' : isMobile ? 'index.mobile.html' : 'index.html',),- ...(!isAuth && canvasRuntimeEntries),+ // Mobile/auth have no Canvas consumer, so the plugin emits no runtime entries.+ ...(!isAuth && !isMobile && canvasRuntimeEntries),},strictExecutionOrder: true,}),