agent-canvas 0.9.0-dev.13 → 0.9.0-dev.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +28 -0
  2. package/bin/agent-canvas.ts +8 -1
  3. package/bin/lib/cli-auth.ts +31 -0
  4. package/bin/lib/commands/daemon.ts +2 -1
  5. package/bin/lib/commands/exec.ts +5 -4
  6. package/bin/lib/commands/fetch.ts +4 -4
  7. package/bin/lib/commands/push.ts +3 -2
  8. package/bin/lib/commands/reply.ts +45 -0
  9. package/bin/lib/commands/review.ts +4 -2
  10. package/bin/lib/commands/watch.ts +100 -5
  11. package/bin/lib/helpers.ts +121 -43
  12. package/bin/lib/instructions/component-download.md +28 -0
  13. package/bin/lib/instructions/component-filedrop.md +50 -0
  14. package/bin/lib/instructions/overview.md +41 -1
  15. package/bin/lib/instructions/template-dashboard.md +177 -0
  16. package/bin/lib/instructions/template-slides.md +196 -0
  17. package/bin/lib/instructions/theming.md +25 -0
  18. package/daemon/client/App.tsx +17 -5
  19. package/daemon/client/clientApi.ts +64 -5
  20. package/daemon/client/components/Download.tsx +28 -0
  21. package/daemon/client/components/FileDrop.tsx +164 -0
  22. package/daemon/client/components/index.ts +3 -1
  23. package/daemon/client/threadStore.ts +70 -0
  24. package/daemon/dist/client.css +1 -1
  25. package/daemon/dist/client.js +57 -56
  26. package/daemon/dist/components.js +52 -49
  27. package/daemon/src/admission.ts +102 -0
  28. package/daemon/src/assets.ts +16 -0
  29. package/daemon/src/components.ts +6 -1
  30. package/daemon/src/handlers/api.ts +7 -4
  31. package/daemon/src/handlers/assets.ts +126 -0
  32. package/daemon/src/handlers/files.ts +124 -19
  33. package/daemon/src/handlers/static.ts +65 -1
  34. package/daemon/src/handlers/theme.ts +150 -0
  35. package/daemon/src/handlers/threads.ts +93 -0
  36. package/daemon/src/review/server.ts +1 -1
  37. package/daemon/src/server.ts +81 -47
  38. package/daemon/src/threads.ts +132 -0
  39. package/package.json +4 -4
  40. package/skills/canvas/SKILL.md +5 -0
  41. package/types/bin/lib/cli-auth.d.ts +9 -0
  42. package/types/bin/lib/commands/reply.d.ts +2 -0
  43. package/types/bin/lib/commands/watch.d.ts +3 -1
  44. package/types/bin/lib/helpers.d.ts +102 -0
  45. package/types/daemon/client/clientApi.d.ts +14 -1
  46. package/types/daemon/client/components/Download.d.ts +9 -0
  47. package/types/daemon/client/components/FileDrop.d.ts +12 -0
  48. package/types/daemon/client/components/index.d.ts +2 -0
  49. package/types/daemon/client/threadStore.d.ts +15 -0
  50. package/types/daemon/src/admission.d.ts +24 -0
  51. package/types/daemon/src/assets.d.ts +23 -0
  52. package/types/daemon/src/components.d.ts +3 -1
  53. package/types/daemon/src/handlers/assets.d.ts +14 -0
  54. package/types/daemon/src/handlers/files.d.ts +8 -2
  55. package/types/daemon/src/handlers/static.d.ts +16 -0
  56. package/types/daemon/src/handlers/theme.d.ts +18 -0
  57. package/types/daemon/src/handlers/threads.d.ts +19 -0
  58. package/types/daemon/src/review/model.d.ts +24 -24
  59. package/types/daemon/src/review/remote.d.ts +8 -8
  60. package/types/daemon/src/review/server.d.ts +2 -0
  61. package/types/daemon/src/threads.d.ts +109 -0
@@ -0,0 +1,102 @@
1
+ import { jsonResponse } from '@fabrika/daemon-kit'
2
+ import { timingSafeEqual } from 'crypto'
3
+
4
+ /** The header the CLI sends its capability in; the daemon writes the capability to `CLI_AUTH_FILE`. */
5
+ export const CLI_TOKEN_HEADER = 'X-Agent-Canvas-CLI-Token'
6
+
7
+ /**
8
+ * The query parameter a CLI WebSocket upgrade carries the capability in. Bun's client sends headers on an upgrade, but
9
+ * the CLI is typed against the DOM `WebSocket`, whose constructor takes none.
10
+ */
11
+ export const CLI_TOKEN_QUERY = 'cli_token'
12
+
13
+ const LOOPBACK_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]']
14
+
15
+ /** Routes only the daemon owner's CLI calls: they require the CLI capability. WebSocket upgrades arrive as GET. */
16
+ const CLI_ROUTES: ReadonlyArray<{ method: string; pattern: URLPattern }> = [
17
+ { method: 'POST', pattern: new URLPattern({ pathname: '/api/session/:id/plan' }) },
18
+ { method: 'POST', pattern: new URLPattern({ pathname: '/api/session/:id/feedback/consume' }) },
19
+ { method: 'POST', pattern: new URLPattern({ pathname: '/api/session/:id/secrets/resolve' }) },
20
+ { method: 'POST', pattern: new URLPattern({ pathname: '/api/session/:id/threads/claim' }) },
21
+ { method: 'POST', pattern: new URLPattern({ pathname: '/api/session/:id/threads/:thread/reply' }) },
22
+ { method: 'GET', pattern: new URLPattern({ pathname: '/ws/wait/:id' }) },
23
+ { method: 'GET', pattern: new URLPattern({ pathname: '/ws/review-wait/:project' }) },
24
+ { method: 'POST', pattern: new URLPattern({ pathname: '/api/review/:project/claim' }) },
25
+ { method: 'POST', pattern: new URLPattern({ pathname: '/api/review/:project/proxy' }) },
26
+ { method: 'POST', pattern: new URLPattern({ pathname: '/api/review/:project/threads/:thread/reply' }) },
27
+ ]
28
+
29
+ export interface AdmissionOptions {
30
+ port: number
31
+ cliAuthToken: string
32
+ }
33
+
34
+ /** The Host values a browser or the CLI sends to this daemon. Anything else is a request for another name, e.g. a rebound one. */
35
+ function allowedHosts(port: number): Set<string> {
36
+ const hosts = new Set(LOOPBACK_HOSTNAMES.map((hostname) => `${hostname}:${port}`))
37
+ if (port === 80) { for (const hostname of LOOPBACK_HOSTNAMES) hosts.add(hostname) }
38
+ return hosts
39
+ }
40
+
41
+ /** The origins of the daemon's own browser UI. */
42
+ function daemonOrigins(port: number): Set<string> {
43
+ return new Set(LOOPBACK_HOSTNAMES.map((hostname) => `http://${hostname}${port === 80 ? '' : `:${port}`}`))
44
+ }
45
+
46
+ export function hasCliToken(req: Request, cliAuthToken: string): boolean {
47
+ return matchesToken(req.headers.get(CLI_TOKEN_HEADER), cliAuthToken)
48
+ }
49
+
50
+ function matchesToken(presented: string | null, cliAuthToken: string): boolean {
51
+ if (presented === null) return false
52
+ const expected = Buffer.from(cliAuthToken)
53
+ const actual = Buffer.from(presented)
54
+ return actual.length === expected.length && timingSafeEqual(actual, expected)
55
+ }
56
+
57
+ function isCliRoute(req: Request, url: URL): boolean {
58
+ return CLI_ROUTES.some((route) => route.method === req.method && route.pattern.test(url))
59
+ }
60
+
61
+ /** Review mode answers browsers on other loopback ports (the application under review) and checks their origin itself. */
62
+ function isReviewPath(pathname: string): boolean {
63
+ return pathname.startsWith('/api/review/') || pathname.startsWith('/ws/review/')
64
+ }
65
+
66
+ /**
67
+ * Admission for every request the daemon receives, before any route or WebSocket upgrade:
68
+ * - the Host must name the daemon on loopback, which refuses DNS-rebound pages;
69
+ * - a request that changes state, and every WebSocket upgrade, must come from the daemon's own UI or from a client that
70
+ * sends no `Origin` (the CLI); browsers send `Origin` on such requests, so a cross-site page is refused whatever the
71
+ * content type;
72
+ * - every API request and upgrade a browser sends must be same-origin (`Sec-Fetch-Site`), reads included;
73
+ * - CLI routes require the CLI capability.
74
+ *
75
+ * Returns the refusal, or null when the request is admitted.
76
+ */
77
+ export function admitRequest(req: Request, url: URL, options: AdmissionOptions): Response | null {
78
+ const host = req.headers.get('Host')
79
+ if (host === null || !allowedHosts(options.port).has(host.toLowerCase())) {
80
+ return jsonResponse({ error: 'Host not allowed' }, 403)
81
+ }
82
+
83
+ const isUpgrade = req.headers.get('Upgrade')?.toLowerCase() === 'websocket' || url.pathname.startsWith('/ws/')
84
+ const isApi = url.pathname.startsWith('/api/') || url.pathname.startsWith('/ws/')
85
+ // A no-cors read (an <img> of /api/image) sends no Origin; from another port it is same-site, not same-origin.
86
+ const fetchSite = req.headers.get('Sec-Fetch-Site')
87
+ if (isApi && !isReviewPath(url.pathname) && fetchSite !== null && fetchSite !== 'same-origin' && fetchSite !== 'none') {
88
+ return jsonResponse({ error: 'Origin not allowed' }, 403)
89
+ }
90
+ const changesState = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS'
91
+ if ((changesState || isUpgrade) && !isReviewPath(url.pathname)) {
92
+ const origin = req.headers.get('Origin')
93
+ if (origin !== null && !daemonOrigins(options.port).has(origin)) return jsonResponse({ error: 'Origin not allowed' }, 403)
94
+ }
95
+
96
+ const presented = req.headers.get(CLI_TOKEN_HEADER) ?? (isUpgrade ? url.searchParams.get(CLI_TOKEN_QUERY) : null)
97
+ if (isCliRoute(req, url) && !matchesToken(presented, options.cliAuthToken)) {
98
+ return jsonResponse({ error: 'This endpoint is available only to the local CLI' }, 401)
99
+ }
100
+
101
+ return null
102
+ }
@@ -0,0 +1,16 @@
1
+ import { z } from 'zod'
2
+
3
+ /** Shared by the daemon's asset routes and `<FileDrop>`; this module stays free of Node APIs so the client can load it. */
4
+ /** The daemon's per-file limit; a canvas may set a lower one. */
5
+ export const MAX_ASSET_BYTES = 25 * 1024 * 1024
6
+
7
+ export const ASSET_FIELD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
8
+
9
+ export const storedAssetSchema = z.object({
10
+ /** The stored file's name: a time-ordered random prefix and the sanitised original name. */
11
+ id: z.string(),
12
+ name: z.string(),
13
+ path: z.string(),
14
+ size: z.number().int(),
15
+ })
16
+ export type StoredAsset = z.infer<typeof storedAssetSchema>
@@ -6,8 +6,13 @@
6
6
  * through `#canvas/components`. A name here with no matching export renders as
7
7
  * undefined.
8
8
  */
9
- import type { CanvasComponents } from '@fabrika/canvas-kernel/server'
9
+ import type { CanvasComponents, FileReferenceProp } from '@fabrika/canvas-kernel/server'
10
10
 
11
11
  export const HOST_COMPONENTS: CanvasComponents = {
12
12
  SecretInput: { requiredProps: { id: 'string', label: 'string', env: 'string' } },
13
+ Download: { requiredProps: { path: 'string' } },
14
+ FileDrop: { requiredProps: { id: 'string', label: 'string' } },
13
15
  }
16
+
17
+ /** Host component props that name a local file, beside the kernel's; the file routes serve what they name. */
18
+ export const HOST_FILE_REFERENCE_PROPS: readonly FileReferenceProp[] = [['Download', 'path']]
@@ -2,6 +2,7 @@ import { compileJsx, type SessionManager, watchSession } from '@fabrika/canvas-k
2
2
  import { jsonResponse, type Route } from '@fabrika/daemon-kit'
3
3
  import { existsSync, readdirSync, readFileSync } from 'fs'
4
4
  import { errorMessage } from '../../client/errorMessage'
5
+ import { hasCliToken } from '../admission'
5
6
  import { HOST_COMPONENTS } from '../components'
6
7
  import { COMPILE_TEMP_DIR } from '../paths'
7
8
  import { loadShareConfig, revokeShare, shareRevision } from '../share'
@@ -158,10 +159,12 @@ export function createApiHandlers(ctx: ApiContext): Route[] {
158
159
  })
159
160
  }
160
161
 
161
- function handleHealth(): Response {
162
- const sessions = sessionManager.list().map((s) => s.id)
162
+ function handleHealth(req: Request): Response {
163
163
  // The pid is what the CLI signals to stop us — a pid file it cannot corroborate is not.
164
- return jsonResponse({ ok: true, sessions, version: ctx.version, pid: process.pid })
164
+ const health = { ok: true, version: ctx.version, pid: process.pid }
165
+ // Session ids are listed only to the CLI; liveness and version are what the lifecycle check needs.
166
+ if (!hasCliToken(req, ctx.cliAuthToken)) return jsonResponse(health)
167
+ return jsonResponse({ ...health, sessions: sessionManager.list().map((s) => s.id) })
165
168
  }
166
169
 
167
170
  function handleMeta(_req: Request, _url: URL, match: URLPatternResult): Response {
@@ -300,7 +303,7 @@ export function createApiHandlers(ctx: ApiContext): Route[] {
300
303
  }
301
304
 
302
305
  async function handleSecretResolve(req: Request, _url: URL, match: URLPatternResult): Promise<Response> {
303
- if (req.headers.get('X-Agent-Canvas-CLI-Token') !== ctx.cliAuthToken) {
306
+ if (!hasCliToken(req, ctx.cliAuthToken)) {
304
307
  return secretJsonResponse({ error: 'Secret resolution is available only to the local CLI' }, 403)
305
308
  }
306
309
  const sessionId = match.pathname.groups.id!
@@ -0,0 +1,126 @@
1
+ import type { SessionManager } from '@fabrika/canvas-kernel/server'
2
+ import { jsonResponse, type Route } from '@fabrika/daemon-kit'
3
+ import { existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'fs'
4
+ import { join } from 'path'
5
+ import { ASSET_FIELD_ID_RE, MAX_ASSET_BYTES, type StoredAsset } from '../assets'
6
+
7
+ /**
8
+ * Files the user hands the agent through `<FileDrop>`: `sessions/<id>/assets/<field>/<uuid>-<name>`. The feedback
9
+ * names their absolute paths and the agent reads them with its own tools. Nothing here serves a file back, so an
10
+ * upload is never rendered as a page or a script. Files are kept until the session directory is removed.
11
+ */
12
+
13
+ export { MAX_ASSET_BYTES }
14
+ export const MAX_SESSION_ASSET_BYTES = 250 * 1024 * 1024
15
+ export const MAX_SESSION_ASSETS = 100
16
+
17
+ const ASSET_RE = /^[0-9a-f-]{36}-[A-Za-z0-9._-]{1,100}$/
18
+ const MAX_NAME = 100
19
+ // A multipart body carries the file plus its headers; this much more is plenty.
20
+ const MULTIPART_OVERHEAD = 64 * 1024
21
+
22
+ /** The original name as a file name that is safe on every platform, needs no URL encoding and is never a path. */
23
+ export function safeAssetName(name: string): string {
24
+ const base = name.split(/[\\/]/).pop() ?? ''
25
+ const safe = base.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^\.+/, '').slice(0, MAX_NAME)
26
+ return safe === '' ? 'file' : safe
27
+ }
28
+
29
+ export function createAssetHandlers(sessionManager: SessionManager): Route[] {
30
+ function fieldDir(sessionId: string, field: string): string {
31
+ return join(sessionManager.assetsDir(sessionId), field)
32
+ }
33
+
34
+ function list(dir: string): StoredAsset[] {
35
+ if (!existsSync(dir)) return []
36
+ return readdirSync(dir).filter((id) => ASSET_RE.test(id)).sort().map((id) => {
37
+ const path = join(dir, id)
38
+ return { id, name: id.slice(37), path, size: statSync(path).size }
39
+ })
40
+ }
41
+
42
+ function usage(sessionId: string): { count: number; bytes: number } {
43
+ const root = sessionManager.assetsDir(sessionId)
44
+ if (!existsSync(root)) return { count: 0, bytes: 0 }
45
+ const files = readdirSync(root).filter((field) => ASSET_FIELD_ID_RE.test(field)).flatMap((field) => list(join(root, field)))
46
+ return { count: files.length, bytes: files.reduce((sum, file) => sum + file.size, 0) }
47
+ }
48
+
49
+ /** The refusal when the session cannot take `adding` more bytes in one more file, or null. */
50
+ function sessionFull(sessionId: string, adding: number): Response | null {
51
+ const used = usage(sessionId)
52
+ if (used.count >= MAX_SESSION_ASSETS) return jsonResponse({ error: `This session already holds ${MAX_SESSION_ASSETS} files` }, 507)
53
+ if (used.bytes + adding > MAX_SESSION_ASSET_BYTES) {
54
+ return jsonResponse({ error: `This session's files would exceed ${MAX_SESSION_ASSET_BYTES / 1024 / 1024} MB` }, 507)
55
+ }
56
+ return null
57
+ }
58
+
59
+ /** The session and field of a request, or the refusal. */
60
+ function target(match: URLPatternResult): { sessionId: string; field: string } | Response {
61
+ const sessionId = match.pathname.groups['id'] ?? ''
62
+ const field = match.pathname.groups['field'] ?? ''
63
+ if (!sessionManager.get(sessionId)) return jsonResponse({ error: 'Session not found' }, 404)
64
+ if (!ASSET_FIELD_ID_RE.test(field)) return jsonResponse({ error: 'Invalid field ID' }, 400)
65
+ return { sessionId, field }
66
+ }
67
+
68
+ function handleList(_req: Request, _url: URL, match: URLPatternResult): Response {
69
+ const at = target(match)
70
+ if (at instanceof Response) return at
71
+ return jsonResponse({ files: list(fieldDir(at.sessionId, at.field)) })
72
+ }
73
+
74
+ async function handleUpload(req: Request, _url: URL, match: URLPatternResult): Promise<Response> {
75
+ const at = target(match)
76
+ if (at instanceof Response) return at
77
+ const tooLarge = jsonResponse({ error: `File too large (max ${MAX_ASSET_BYTES / 1024 / 1024} MB)` }, 413)
78
+ // Without a declared length the body would be buffered in full before any limit applies; browsers always send one.
79
+ const declared = Number(req.headers.get('Content-Length') ?? 'NaN')
80
+ if (!Number.isFinite(declared)) return jsonResponse({ error: 'Content-Length required' }, 411)
81
+ if (declared > MAX_ASSET_BYTES + MULTIPART_OVERHEAD) return tooLarge
82
+ // Fails fast before the body is buffered; the check after the read is the one that counts.
83
+ const fullBeforeRead = sessionFull(at.sessionId, 0)
84
+ if (fullBeforeRead) return fullBeforeRead
85
+
86
+ let file: FormDataEntryValue | null
87
+ try {
88
+ file = (await req.formData()).get('file')
89
+ } catch {
90
+ return jsonResponse({ error: 'Expected a multipart form with a file' }, 400)
91
+ }
92
+ if (!(file instanceof File)) return jsonResponse({ error: 'No file provided' }, 400)
93
+ if (file.size > MAX_ASSET_BYTES) return tooLarge
94
+ const bytes = new Uint8Array(await file.arrayBuffer())
95
+
96
+ // No await from here to the write, so concurrent uploads cannot all pass the same check.
97
+ const full = sessionFull(at.sessionId, bytes.byteLength)
98
+ if (full) return full
99
+
100
+ const dir = fieldDir(at.sessionId, at.field)
101
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
102
+ // UUIDv7 sorts by time, so a listing keeps the upload order.
103
+ const id = `${Bun.randomUUIDv7()}-${safeAssetName(file.name)}`
104
+ const path = join(dir, id)
105
+ writeFileSync(path, bytes, { mode: 0o600 })
106
+ const stored: StoredAsset = { id, name: id.slice(37), path, size: bytes.byteLength }
107
+ return jsonResponse({ file: stored })
108
+ }
109
+
110
+ function handleDelete(_req: Request, _url: URL, match: URLPatternResult): Response {
111
+ const at = target(match)
112
+ if (at instanceof Response) return at
113
+ const asset = match.pathname.groups['asset'] ?? ''
114
+ if (!ASSET_RE.test(asset)) return jsonResponse({ error: 'Invalid file ID' }, 400)
115
+ const path = join(fieldDir(at.sessionId, at.field), asset)
116
+ if (!existsSync(path)) return jsonResponse({ error: 'Not found' }, 404)
117
+ rmSync(path)
118
+ return jsonResponse({ ok: true })
119
+ }
120
+
121
+ return [
122
+ { method: 'GET', pattern: new URLPattern({ pathname: '/api/session/:id/assets/:field' }), handler: handleList },
123
+ { method: 'POST', pattern: new URLPattern({ pathname: '/api/session/:id/assets/:field' }), handler: handleUpload },
124
+ { method: 'DELETE', pattern: new URLPattern({ pathname: '/api/session/:id/assets/:field/:asset' }), handler: handleDelete },
125
+ ]
126
+ }
@@ -1,8 +1,10 @@
1
- import type { SessionManager } from '@fabrika/canvas-kernel/server'
1
+ import { canvasFileReferences, type RevisionInfo, type SessionData, type SessionManager } from '@fabrika/canvas-kernel/server'
2
2
  import { jsonResponse, type Route } from '@fabrika/daemon-kit'
3
+ import { realpathSync } from 'fs'
3
4
  import { readdir } from 'fs/promises'
4
- import { isAbsolute, relative, resolve, sep } from 'path'
5
+ import { basename, isAbsolute, relative, resolve, sep } from 'path'
5
6
  import { LANG_MAP } from '../../langMap'
7
+ import { HOST_FILE_REFERENCE_PROPS } from '../components'
6
8
 
7
9
  const IMAGE_MIME: Record<string, string> = {
8
10
  png: 'image/png',
@@ -16,30 +18,108 @@ const IMAGE_MIME: Record<string, string> = {
16
18
  avif: 'image/avif',
17
19
  }
18
20
 
19
- function resolveSessionPath(
20
- sessionManager: SessionManager,
21
- sessionId: string,
22
- relPath: string,
23
- ): { fullPath: string; session: ReturnType<SessionManager['get']> & {} } | Response {
24
- const session = sessionManager.get(sessionId)
25
- if (!session) return jsonResponse({ error: 'Session not found' }, 404)
26
-
27
- const fullPath = resolve(session.projectRoot, relPath)
28
- const relativePath = relative(resolve(session.projectRoot), fullPath)
29
- if (!isAbsolute(relPath) && (relativePath === '..' || relativePath.startsWith(`..${sep}`))) {
30
- return jsonResponse({ error: 'Path traversal rejected' }, 403)
21
+ export interface FileHandlerOptions {
22
+ /** Directories whose contents the file routes never return: the daemon's own state. */
23
+ deniedRoots: readonly string[]
24
+ }
25
+
26
+ /** The path with symlinks resolved, or the path itself when it does not exist (reading it then fails as missing). */
27
+ function realOrSelf(path: string): string {
28
+ try {
29
+ return realpathSync.native(path)
30
+ } catch {
31
+ return path
31
32
  }
33
+ }
34
+
35
+ /** `attachment` with an ASCII fallback name and the exact one in RFC 5987 form. */
36
+ export function attachmentDisposition(name: string): string {
37
+ const fallback = name.replace(/[^A-Za-z0-9._-]/g, '_') || 'download'
38
+ const exact = encodeURIComponent(name).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
39
+ return `attachment; filename="${fallback}"; filename*=UTF-8''${exact}`
40
+ }
41
+
42
+ function isInside(path: string, root: string): boolean {
43
+ const relativePath = relative(root, path)
44
+ return relativePath === '' || (relativePath !== '..' && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath))
45
+ }
46
+
47
+ /** `named-file`: a file a canvas of the session names, wherever it is; inside the project root too. */
48
+ type PathKind = 'file' | 'directory' | 'named-file'
49
+ /** `fullPath` has symlinks resolved; `requestedPath` is the path as asked for, normalised. */
50
+ type SessionPathResolver = (sessionId: string, relPath: string, kind: PathKind) => { fullPath: string; requestedPath: string } | Response
51
+
52
+ /**
53
+ * The files the session's canvases name, in every revision, as written and with symlinks resolved. A push or a new
54
+ * session replaces the revisions array, so the array is the cache key.
55
+ */
56
+ function createNamedFiles(sessionManager: SessionManager): (session: SessionData) => Set<string> {
57
+ const cache = new WeakMap<readonly RevisionInfo[], Set<string>>()
58
+ return (session) => {
59
+ const cached = cache.get(session.revisions)
60
+ if (cached !== undefined) return cached
61
+ const paths = new Set<string>()
62
+ for (const revision of session.revisions) {
63
+ for (const { filename } of revision.canvasFiles) {
64
+ const jsx = sessionManager.readRevisionJsx(session.id, revision.revision, filename)
65
+ if (jsx === null) continue
66
+ for (const reference of canvasFileReferences(jsx, HOST_FILE_REFERENCE_PROPS)) {
67
+ const path = resolve(session.projectRoot, reference)
68
+ paths.add(path)
69
+ paths.add(realOrSelf(path))
70
+ }
71
+ }
72
+ }
73
+ cache.set(session.revisions, paths)
74
+ return paths
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Resolves a path against the session's project root. Outside it, symlinks resolved, only a file a canvas of the session
80
+ * names is served and no directory is listed; nothing in a denied root is. The canvas author controls that list, so it
81
+ * stops computed paths and other clients' reads, not a hostile canvas.
82
+ */
83
+ function createSessionPathResolver(sessionManager: SessionManager, options: FileHandlerOptions): SessionPathResolver {
84
+ const deniedRoots = [...new Set(options.deniedRoots.flatMap((root) => [resolve(root), realOrSelf(resolve(root))]))]
85
+ const namedFiles = createNamedFiles(sessionManager)
86
+
87
+ return (sessionId, relPath, kind) => {
88
+ const session = sessionManager.get(sessionId)
89
+ if (!session) return jsonResponse({ error: 'Session not found' }, 404)
90
+
91
+ const fullPath = resolve(session.projectRoot, relPath)
92
+ const relativePath = relative(resolve(session.projectRoot), fullPath)
93
+ if (!isAbsolute(relPath) && (relativePath === '..' || relativePath.startsWith(`..${sep}`))) {
94
+ return jsonResponse({ error: 'Path traversal rejected' }, 403)
95
+ }
32
96
 
33
- return { fullPath, session }
97
+ const realPath = realOrSelf(fullPath)
98
+ if (deniedRoots.some((root) => isInside(fullPath, root) || isInside(realPath, root))) {
99
+ return jsonResponse({ error: 'Path is not served' }, 403)
100
+ }
101
+ const lexicalRoot = resolve(session.projectRoot)
102
+ // realOrSelf leaves a missing path unresolved, so one under a symlinked root is judged by where it was asked for.
103
+ const insideRoot = isInside(realPath, realOrSelf(lexicalRoot)) || (realPath === fullPath && isInside(fullPath, lexicalRoot))
104
+ const named = () => namedFiles(session).has(fullPath) || namedFiles(session).has(realPath)
105
+ if (kind === 'named-file' && !named()) return jsonResponse({ error: 'Path is not named by a canvas in this session' }, 403)
106
+ if (!insideRoot && (kind === 'directory' || !named())) {
107
+ return jsonResponse({ error: 'Path outside the project root is not named by a canvas in this session' }, 403)
108
+ }
109
+
110
+ return { fullPath: realPath, requestedPath: fullPath }
111
+ }
34
112
  }
35
113
 
36
- export function createFileHandlers(sessionManager: SessionManager): Route[] {
114
+ export function createFileHandlers(sessionManager: SessionManager, options: FileHandlerOptions): Route[] {
115
+ const resolveSessionPath = createSessionPathResolver(sessionManager, options)
116
+
37
117
  async function handleFileServe(_req: Request, url: URL): Promise<Response> {
38
118
  const sessionId = url.searchParams.get('session')
39
119
  const relPath = url.searchParams.get('path')
40
120
  if (!sessionId || !relPath) return jsonResponse({ error: 'Missing session or path' }, 400)
41
121
 
42
- const resolved = resolveSessionPath(sessionManager, sessionId, relPath)
122
+ const resolved = resolveSessionPath(sessionId, relPath, 'file')
43
123
  if (resolved instanceof Response) return resolved
44
124
 
45
125
  try {
@@ -61,7 +141,7 @@ export function createFileHandlers(sessionManager: SessionManager): Route[] {
61
141
  const relPath = url.searchParams.get('path')
62
142
  if (!sessionId || !relPath) return jsonResponse({ error: 'Missing session or path' }, 400)
63
143
 
64
- const resolved = resolveSessionPath(sessionManager, sessionId, relPath)
144
+ const resolved = resolveSessionPath(sessionId, relPath, 'file')
65
145
  if (resolved instanceof Response) return resolved
66
146
 
67
147
  try {
@@ -77,6 +157,9 @@ export function createFileHandlers(sessionManager: SessionManager): Route[] {
77
157
  headers: {
78
158
  'Content-Type': mime,
79
159
  'Cache-Control': 'public, max-age=300',
160
+ // An SVG opened as a document would otherwise run its scripts in the daemon's origin.
161
+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox",
162
+ 'X-Content-Type-Options': 'nosniff',
80
163
  },
81
164
  })
82
165
  } catch {
@@ -84,12 +167,33 @@ export function createFileHandlers(sessionManager: SessionManager): Route[] {
84
167
  }
85
168
  }
86
169
 
170
+ /** A file the agent produced and named in `<Download path>` (or any file reference), as an attachment. */
171
+ async function handleDownload(_req: Request, url: URL): Promise<Response> {
172
+ const sessionId = url.searchParams.get('session')
173
+ const relPath = url.searchParams.get('path')
174
+ if (!sessionId || !relPath) return jsonResponse({ error: 'Missing session or path' }, 400)
175
+
176
+ const resolved = resolveSessionPath(sessionId, relPath, 'named-file')
177
+ if (resolved instanceof Response) return resolved
178
+
179
+ const file = Bun.file(resolved.fullPath)
180
+ if (!(await file.exists())) return jsonResponse({ error: 'File not found' }, 404)
181
+ return new Response(file, {
182
+ headers: {
183
+ 'Content-Type': 'application/octet-stream',
184
+ 'Content-Disposition': attachmentDisposition(basename(resolved.requestedPath)),
185
+ 'Cache-Control': 'no-store',
186
+ 'X-Content-Type-Options': 'nosniff',
187
+ },
188
+ })
189
+ }
190
+
87
191
  async function handleTreeServe(_req: Request, url: URL): Promise<Response> {
88
192
  const sessionId = url.searchParams.get('session')
89
193
  const relPath = url.searchParams.get('path') || ''
90
194
  if (!sessionId) return jsonResponse({ error: 'Missing session' }, 400)
91
195
 
92
- const resolved = resolveSessionPath(sessionManager, sessionId, relPath)
196
+ const resolved = resolveSessionPath(sessionId, relPath, 'directory')
93
197
  if (resolved instanceof Response) return resolved
94
198
 
95
199
  const ignoreDirs = new Set(['.git', 'node_modules', '.next', '__pycache__', 'dist', '.cache'])
@@ -116,5 +220,6 @@ export function createFileHandlers(sessionManager: SessionManager): Route[] {
116
220
  { method: 'GET', pattern: new URLPattern({ pathname: '/api/file' }), handler: handleFileServe },
117
221
  { method: 'GET', pattern: new URLPattern({ pathname: '/api/image' }), handler: handleImageServe },
118
222
  { method: 'GET', pattern: new URLPattern({ pathname: '/api/tree' }), handler: handleTreeServe },
223
+ { method: 'GET', pattern: new URLPattern({ pathname: '/api/download' }), handler: handleDownload },
119
224
  ]
120
225
  }
@@ -1,4 +1,5 @@
1
1
  import type { Route } from '@fabrika/daemon-kit'
2
+ import { createHash } from 'crypto'
2
3
  import { dirname, join } from 'path'
3
4
  import { DATA_DIR } from '../paths'
4
5
 
@@ -23,11 +24,74 @@ async function getDistDir(): Promise<string> {
23
24
  return cachedDistDir
24
25
  }
25
26
 
27
+ /**
28
+ * The canvas page's policy, derived from the page: scripts from the daemon, its inline scripts by hash, its external ones
29
+ * by URL, and connections only to the daemon. Images, fonts, styles, media and navigation can still carry data out.
30
+ */
31
+ export function sessionPageCsp(html: string): string {
32
+ const scripts = ["'self'"]
33
+ for (const [, attributes = '', body = ''] of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)) {
34
+ const src = attributes.match(/\bsrc="([^"]+)"/)?.[1]
35
+ if (src === undefined) scripts.push(`'sha256-${createHash('sha256').update(body).digest('base64')}'`)
36
+ else if (src.startsWith('https://')) scripts.push(src)
37
+ }
38
+ return [
39
+ "default-src 'self'",
40
+ `script-src ${scripts.join(' ')}`,
41
+ "style-src 'self' 'unsafe-inline' https:",
42
+ "img-src 'self' data: blob: https:",
43
+ "font-src 'self' data: https:",
44
+ "media-src 'self' data: blob: https:",
45
+ "frame-src 'none'",
46
+ "connect-src 'self'",
47
+ "object-src 'none'",
48
+ "base-uri 'none'",
49
+ "form-action 'none'",
50
+ "frame-ancestors 'none'",
51
+ ].join('; ')
52
+ }
53
+
54
+ /**
55
+ * Every other response is a document in the daemon's origin when opened in a frame or window. Without a policy of its
56
+ * own it would let canvas JavaScript script it past the page's `connect-src`.
57
+ */
58
+ export const INERT_DOCUMENT_CSP = "default-src 'none'; frame-ancestors 'none'; sandbox"
59
+
60
+ export function withDefaultCsp(response: Response): Response {
61
+ if (response.headers.has('Content-Security-Policy')) return response
62
+ try {
63
+ response.headers.set('Content-Security-Policy', INERT_DOCUMENT_CSP)
64
+ return response
65
+ } catch {
66
+ // A redirect's headers are immutable; a rebuilt file response would lose its length and range support.
67
+ }
68
+ const headers = new Headers(response.headers)
69
+ headers.set('Content-Security-Policy', INERT_DOCUMENT_CSP)
70
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers })
71
+ }
72
+
73
+ /**
74
+ * What `Bun.serve` answers when a handler throws or a body fails to stream (an unreadable named file). Without it Bun
75
+ * serves its own HTML error page, scripted and with no policy, after `withDefaultCsp` has already run.
76
+ */
77
+ function serverErrorResponse(error: Error): Response {
78
+ console.error('[agent-canvas] request failed:', error)
79
+ return Response.json({ error: 'Internal error' }, {
80
+ status: 500,
81
+ headers: { 'Content-Security-Policy': INERT_DOCUMENT_CSP, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store' },
82
+ })
83
+ }
84
+
85
+ /** The daemon's `Bun.serve` error options, shared with the test that holds them to an inert answer. */
86
+ export const serveErrorOptions: { development: false; error: (error: Error) => Response } = { development: false, error: serverErrorResponse }
87
+
26
88
  async function serveSessionPage(): Promise<Response> {
27
89
  const distDir = await getDistDir()
28
90
  const file = Bun.file(join(distDir, 'index.html'))
29
91
  if (await file.exists()) {
30
- return new Response(file, { headers: { 'Content-Type': 'text/html' } })
92
+ // Read on every request: a watch rebuild rewrites the page and its inline scripts.
93
+ const html = await file.text()
94
+ return new Response(html, { headers: { 'Content-Type': 'text/html', 'Content-Security-Policy': sessionPageCsp(html) } })
31
95
  }
32
96
  return new Response('Build not found. Run: bun run daemon/build.ts', { status: 500 })
33
97
  }