agent-canvas 0.9.0-dev.10 → 0.9.0-dev.12

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.
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "incremental": true,
5
+ "tsBuildInfoFile": "../../.tsbuild/review-widget.tsbuildinfo"
6
+ },
7
+ "references": [
8
+ { "path": "../../../annotations/tsconfig.lib.json" },
9
+ { "path": "../../../canvas-kernel/tsconfig.lib.json" },
10
+ { "path": "../../../daemon-kit/tsconfig.lib.json" }
11
+ ]
12
+ }
@@ -3,17 +3,7 @@ import { jsonResponse, type Route } from '@fabrika/daemon-kit'
3
3
  import { writeFileSync } from 'fs'
4
4
  import { join } from 'path'
5
5
  import { UPLOADS_DIR } from '../paths'
6
-
7
- const IMAGE_MIME: Record<string, string> = {
8
- png: 'image/png',
9
- jpg: 'image/jpeg',
10
- jpeg: 'image/jpeg',
11
- gif: 'image/gif',
12
- svg: 'image/svg+xml',
13
- webp: 'image/webp',
14
- bmp: 'image/bmp',
15
- avif: 'image/avif',
16
- }
6
+ import { parseUploadImage, UPLOAD_IMAGE_REFUSED, uploadImageTypeOfExtension, uploadServeHeaders } from '../upload-image'
17
7
 
18
8
  export function createUploadHandlers(sessionManager: SessionManager): Route[] {
19
9
  async function handleUpload(req: Request, _url: URL, match: URLPatternResult): Promise<Response> {
@@ -23,17 +13,17 @@ export function createUploadHandlers(sessionManager: SessionManager): Route[] {
23
13
  }
24
14
 
25
15
  const formData = await req.formData()
26
- const file = formData.get('image') as File | null
27
- if (!file) return jsonResponse({ error: 'No image provided' }, 400)
28
- if (!file.type.startsWith('image/')) return jsonResponse({ error: 'Not an image' }, 400)
16
+ const file = formData.get('image')
17
+ if (!(file instanceof File)) return jsonResponse({ error: 'No image provided' }, 400)
29
18
  if (file.size > 10 * 1024 * 1024) return jsonResponse({ error: 'Image too large (max 10MB)' }, 413)
30
19
 
31
- const ext = file.name.split('.').pop()?.toLowerCase() || 'png'
32
- const filename = `${crypto.randomUUID()}.${ext}`
33
- const filepath = join(UPLOADS_DIR, filename)
20
+ const bytes = new Uint8Array(await file.arrayBuffer())
21
+ const image = parseUploadImage(bytes)
22
+ if (!image) return jsonResponse({ error: UPLOAD_IMAGE_REFUSED }, 400)
34
23
 
35
- const buffer = await file.arrayBuffer()
36
- writeFileSync(filepath, Buffer.from(buffer))
24
+ const filename = `${crypto.randomUUID()}.${image.extension}`
25
+ const filepath = join(UPLOADS_DIR, filename)
26
+ writeFileSync(filepath, bytes)
37
27
 
38
28
  return jsonResponse({ path: filepath, filename })
39
29
  }
@@ -48,12 +38,11 @@ export function createUploadHandlers(sessionManager: SessionManager): Route[] {
48
38
  const file = Bun.file(filepath)
49
39
  if (!(await file.exists())) return jsonResponse({ error: 'Not found' }, 404)
50
40
 
51
- const ext = filename.split('.').pop()?.toLowerCase() || ''
52
- const mime = IMAGE_MIME[ext] || 'application/octet-stream'
41
+ const ext = filename.split('.').pop() ?? ''
53
42
 
54
43
  return new Response(file, {
55
44
  headers: {
56
- 'Content-Type': mime,
45
+ ...uploadServeHeaders(uploadImageTypeOfExtension(ext)),
57
46
  'Cache-Control': 'public, max-age=3600',
58
47
  },
59
48
  })
@@ -1,7 +1,7 @@
1
- import type { RemoteAnnotation, RemoteFeedbackEntry, SessionManager } from '@fabrika/canvas-kernel/server'
1
+ import type { RemoteFeedbackEntry, SessionManager } from '@fabrika/canvas-kernel/server'
2
2
  import { errorMessage } from '../client/errorMessage'
3
- import { decryptString, importShareKey } from '../client/shareCrypto'
4
3
  import { loadShareConfig } from './share'
4
+ import { decryptFeedbackEntry, fetchShareFeedback, importShareKey, ShareGoneError } from './share-client'
5
5
 
6
6
  /**
7
7
  * Background polling loop for remote feedback.
@@ -21,72 +21,6 @@ import { loadShareConfig } from './share'
21
21
  const POLL_INTERVAL_MS = 5_000
22
22
  const MAX_BACKOFF_MS = 60_000
23
23
 
24
- /** Wire-format feedback entry as returned by the worker. When the
25
- * reviewer submitted from an encrypted share their browser ciphertexted
26
- * the secret fields and stamped this with `encryption`; the daemon
27
- * decrypts using the key stashed on the local ShareEntry. */
28
- interface WireFeedbackEntry {
29
- id: string
30
- shareId: string
31
- revision: number
32
- submittedAt: string
33
- author: { id: string; name: string }
34
- annotations: Array<{
35
- id: string
36
- snippet: string
37
- note: string
38
- createdAt: string
39
- filePath?: string
40
- canvasFile?: string
41
- context?: unknown
42
- attachments?: Array<{ url: string; mime?: string }>
43
- }>
44
- generalNote?: string
45
- encryption?: { alg: string; v: number }
46
- }
47
-
48
- interface WorkerFeedbackResponse {
49
- entries: WireFeedbackEntry[]
50
- /** Server-reported high water mark — echo back in the next `since` param */
51
- latestAt?: string
52
- }
53
-
54
- /** Decrypt an encrypted-wire feedback entry into the plaintext shape used
55
- * throughout the rest of the daemon. Throws if any field fails to
56
- * decrypt — caller treats that as a transient error so we re-try later. */
57
- async function decryptFeedbackEntry(entry: WireFeedbackEntry, key: CryptoKey): Promise<RemoteFeedbackEntry> {
58
- const annotations: RemoteAnnotation[] = await Promise.all(
59
- entry.annotations.map(async (a) => {
60
- const out: RemoteAnnotation = {
61
- id: a.id,
62
- snippet: await decryptString(key, a.snippet),
63
- note: await decryptString(key, a.note),
64
- createdAt: a.createdAt,
65
- }
66
- if (a.filePath) out.filePath = await decryptString(key, a.filePath)
67
- if (a.canvasFile) out.canvasFile = await decryptString(key, a.canvasFile)
68
- if (typeof a.context === 'string' && a.context.length > 0) {
69
- out.context = JSON.parse(await decryptString(key, a.context))
70
- }
71
- if (a.attachments) out.attachments = a.attachments
72
- return out
73
- }),
74
- )
75
-
76
- return {
77
- id: entry.id,
78
- shareId: entry.shareId,
79
- revision: entry.revision,
80
- submittedAt: entry.submittedAt,
81
- author: {
82
- id: entry.author.id,
83
- name: await decryptString(key, entry.author.name),
84
- },
85
- annotations,
86
- ...(entry.generalNote ? { generalNote: await decryptString(key, entry.generalNote) } : {}),
87
- }
88
- }
89
-
90
24
  export function startRemoteFeedbackPoller(
91
25
  sessionManager: SessionManager,
92
26
  broadcastRemoteFeedback: (sessionId: string, revision: number, entries: RemoteFeedbackEntry[]) => void,
@@ -121,45 +55,30 @@ export function startRemoteFeedbackPoller(
121
55
  endpoint: string,
122
56
  ) {
123
57
  try {
124
- const since = share.lastFeedbackAt ?? ''
125
- const url = `${endpoint}/shares/${share.shareId}/feedback${since ? `?since=${encodeURIComponent(since)}` : ''}`
126
- const res = await fetch(url)
127
- if (!res.ok) {
128
- if (res.status === 404) {
129
- // Share no longer exists on the worker — likely revoked or expired.
130
- // Stop trying so we don't hammer it forever.
131
- errorCounts.set(share.shareId, 99)
132
- return
133
- }
134
- throw new Error(`HTTP ${res.status}`)
135
- }
136
- const data = (await res.json()) as WorkerFeedbackResponse
58
+ const data = await fetchShareFeedback(endpoint, share.shareId, share.lastFeedbackAt ?? '')
137
59
  errorCounts.delete(share.shareId)
138
-
139
- if (!data.entries || data.entries.length === 0) return
60
+ for (const id of data.malformed) console.warn(`[remote-feedback] ${share.shareId}: skipping malformed entry ${id}`)
140
61
 
141
62
  // Decrypt any entries that came in encrypted. Plaintext entries
142
63
  // (legacy submissions from non-encrypted shares) pass through.
143
64
  const decrypted: RemoteFeedbackEntry[] = []
144
65
  for (const e of data.entries) {
145
- if (e.encryption) {
146
- if (!share.encryptionKey) {
147
- console.warn(`[remote-feedback] ${share.shareId}: received encrypted feedback but no local key — skipping entry ${e.id}`)
148
- continue
149
- }
150
- try {
151
- const key = await getKey(share.shareId, share.encryptionKey)
152
- decrypted.push(await decryptFeedbackEntry(e, key))
153
- } catch (err) {
154
- console.warn(`[remote-feedback] ${share.shareId}: failed to decrypt entry ${e.id}: ${errorMessage(err)}`)
66
+ if (e.encryption && !share.encryptionKey) {
67
+ console.warn(`[remote-feedback] ${share.shareId}: received encrypted feedback but no local key — skipping entry ${e.id}`)
68
+ continue
69
+ }
70
+ try {
71
+ const key = e.encryption && share.encryptionKey ? await getKey(share.shareId, share.encryptionKey) : null
72
+ const entry = await decryptFeedbackEntry(e, key)
73
+ if (entry.droppedResponses) {
74
+ console.warn(`[remote-feedback] ${share.shareId}: entry ${e.id}: left out ${entry.droppedResponses} response(s) of an unknown shape`)
155
75
  }
156
- } else {
157
- decrypted.push(e as RemoteFeedbackEntry)
76
+ decrypted.push(entry)
77
+ } catch (err) {
78
+ console.warn(`[remote-feedback] ${share.shareId}: failed to decrypt entry ${e.id}: ${errorMessage(err)}`)
158
79
  }
159
80
  }
160
81
 
161
- if (decrypted.length === 0) return
162
-
163
82
  const byRev = new Map<number, RemoteFeedbackEntry[]>()
164
83
  for (const e of decrypted) {
165
84
  if (!byRev.has(e.revision)) byRev.set(e.revision, [])
@@ -171,12 +90,19 @@ export function startRemoteFeedbackPoller(
171
90
  broadcastRemoteFeedback(sessionId, rev, entries)
172
91
  }
173
92
 
93
+ // The cursor also moves past entries that were skipped: with a fixed key, a refetch fails the same way.
174
94
  const latest = data.latestAt
175
95
  ?? data.entries.reduce((acc, e) => (e.submittedAt > acc ? e.submittedAt : acc), share.lastFeedbackAt ?? '')
176
- if (latest) {
96
+ if (latest && latest !== share.lastFeedbackAt) {
177
97
  sessionManager.updateShareLastFeedback(sessionId, share.shareId, latest)
178
98
  }
179
99
  } catch (e) {
100
+ if (e instanceof ShareGoneError) {
101
+ // Share no longer exists on the worker — likely revoked or expired.
102
+ // Stop trying so we don't hammer it forever.
103
+ errorCounts.set(share.shareId, 99)
104
+ return
105
+ }
180
106
  errorCounts.set(share.shareId, (errorCounts.get(share.shareId) || 0) + 1)
181
107
  console.warn(`[remote-feedback] ${share.shareId}: ${errorMessage(e)} (will retry with backoff)`)
182
108
  }
@@ -84,7 +84,7 @@ export class ReviewProxies {
84
84
  for (const project of this.store.proxiedProjects()) {
85
85
  try {
86
86
  const proxy = this.store.proxyOf(project)
87
- if (proxy !== undefined) this.listen(project, proxy.target, proxy.port)
87
+ if (proxy !== undefined) this.listen(project, new URL(proxy.target).origin, proxy.port)
88
88
  } catch (error) {
89
89
  console.error(`Review proxy for ${project} not restored: ${error instanceof Error ? error.message : String(error)}`)
90
90
  }
@@ -96,6 +96,7 @@ export class ReviewProxies {
96
96
  this.running.clear()
97
97
  }
98
98
 
99
+ /** `target` is an origin: the proxy sets each request's path on it. */
99
100
  private listen(project: string, target: string, port: number | undefined): void {
100
101
  let server: ProxyServer
101
102
  try {
@@ -116,7 +117,10 @@ export class ReviewProxies {
116
117
  hostname: 'localhost',
117
118
  fetch: async (req, server) => {
118
119
  const url = new URL(req.url)
119
- const upstreamUrl = new URL(`${url.pathname}${url.search}`, target)
120
+ // The path is set, not resolved against `target`: a path like `//host/x` stays a path on the application.
121
+ const upstreamUrl = new URL(target)
122
+ upstreamUrl.pathname = url.pathname
123
+ upstreamUrl.search = url.search
120
124
  if (req.headers.get('Upgrade')?.toLowerCase() === 'websocket') {
121
125
  upstreamUrl.protocol = upstreamUrl.protocol === 'https:' ? 'wss:' : 'ws:'
122
126
  return await this.upgrade(project, req, server, upstreamUrl)
@@ -196,7 +200,8 @@ async function forward(req: Request, upstreamUrl: URL, proxyOrigin: string, widg
196
200
  responseHeaders.delete('Content-Encoding')
197
201
  responseHeaders.delete('Content-Length')
198
202
  const location = responseHeaders.get('Location')
199
- if (location?.startsWith(upstreamUrl.origin)) responseHeaders.set('Location', `${proxyOrigin}${location.slice(upstreamUrl.origin.length)}`)
203
+ const redirect = location === null ? null : URL.parse(location, upstreamUrl)
204
+ if (redirect?.origin === upstreamUrl.origin) responseHeaders.set('Location', `${proxyOrigin}${redirect.pathname}${redirect.search}${redirect.hash}`)
200
205
 
201
206
  const init = { status: upstream.status, statusText: upstream.statusText, headers: responseHeaders }
202
207
  if (req.method === 'HEAD' || !(responseHeaders.get('Content-Type') ?? '').startsWith('text/html')) return new Response(upstream.body, init)
@@ -0,0 +1,341 @@
1
+ import { z } from 'zod'
2
+ import {
3
+ decryptString,
4
+ ENCRYPTION_META,
5
+ type EncryptionMeta,
6
+ encryptString,
7
+ exportShareKey,
8
+ generateShareKey,
9
+ importShareKey,
10
+ } from '../client/shareCrypto'
11
+ import { MAX_SHARED_RESPONSES, type SharedResponse, sharedResponseSchema } from './share-responses'
12
+
13
+ /**
14
+ * Client for the canvas share worker, independent of the daemon's sessions.
15
+ *
16
+ * Exported as `agent-canvas/share` so another host can share a compiled
17
+ * canvas and read its feedback with the same wire format and end-to-end
18
+ * encryption the daemon uses. The daemon's own sharing (share.ts), its
19
+ * feedback poller (remote-feedback.ts), the shared page and the worker's
20
+ * validation are built on it.
21
+ *
22
+ * Encryption: see `daemon/client/shareCrypto.ts`; the key travels only in
23
+ * the URL fragment, so the worker stores ciphertext it cannot read.
24
+ */
25
+
26
+ export { decryptString, ENCRYPTION_META, type EncryptionMeta, encryptString, exportShareKey, generateShareKey, importShareKey }
27
+ export {
28
+ answeredResponses,
29
+ MAX_SHARED_RESPONSE_TEXT,
30
+ MAX_SHARED_RESPONSES,
31
+ type SharedResponse,
32
+ sharedResponseSchema,
33
+ sharedResponsesSchema,
34
+ } from './share-responses'
35
+
36
+ export interface SharePayload {
37
+ version: 1
38
+ /** Present iff payload fields below are ciphertext rather than plaintext. */
39
+ encryption?: EncryptionMeta
40
+ origin: {
41
+ sessionId: string
42
+ revision: number
43
+ label?: string
44
+ createdAt: string
45
+ }
46
+ canvasFiles: Array<{
47
+ filename: string
48
+ compiledJs: string
49
+ sourceJsx?: string
50
+ }>
51
+ runtime: {
52
+ componentsVersion: string
53
+ }
54
+ }
55
+
56
+ const shareResponseSchema = z.object({
57
+ shareId: z.string().min(1),
58
+ url: z.string().min(1),
59
+ ownerToken: z.string().optional(),
60
+ expiresAt: z.string().optional(),
61
+ })
62
+ export type ShareResponse = z.infer<typeof shareResponseSchema>
63
+
64
+ export interface ShareEndpoint {
65
+ /** Base URL of the share worker, without a trailing slash. */
66
+ endpoint: string
67
+ /** Bearer token, when the worker sets SHARE_AUTH_TOKEN. */
68
+ authToken?: string
69
+ }
70
+
71
+ /** A created share. `url` carries the `#k=` key when the share is encrypted. */
72
+ export interface CreatedShare extends ShareResponse {
73
+ /** The base64url key, when encrypted; it decrypts the share's feedback. */
74
+ encryptionKey?: string
75
+ }
76
+
77
+ // --- Feedback ---------------------------------------------------------------
78
+
79
+ const annotationContextSchema = z.object({
80
+ before: z.string(),
81
+ after: z.string(),
82
+ hierarchy: z.array(z.string()),
83
+ lineStart: z.number().optional(),
84
+ lineEnd: z.number().optional(),
85
+ })
86
+
87
+ export interface SharedAnnotation {
88
+ id: string
89
+ snippet: string
90
+ note: string
91
+ createdAt: string
92
+ filePath?: string
93
+ canvasFile?: string
94
+ context?: z.infer<typeof annotationContextSchema>
95
+ attachments?: { url: string; mime?: string }[]
96
+ }
97
+
98
+ /** A feedback entry as a reviewer submitted it, decrypted. */
99
+ export interface SharedFeedbackEntry {
100
+ id: string
101
+ shareId: string
102
+ revision: number
103
+ submittedAt: string
104
+ author: { id: string; name: string }
105
+ annotations: SharedAnnotation[]
106
+ generalNote?: string
107
+ /** Structured answers; absent in entries from share pages that predate them. */
108
+ responses?: SharedResponse[]
109
+ /** How many responses did not fit the wire shape (a newer page, or tampering) and were left out. */
110
+ droppedResponses?: number
111
+ }
112
+
113
+ /** A feedback entry as the worker returns it. In an encrypted entry the text
114
+ * fields, the annotation context (as JSON) and `responses` (as one JSON
115
+ * blob) are ciphertext. */
116
+ export const wireFeedbackEntrySchema = z.object({
117
+ id: z.string(),
118
+ shareId: z.string(),
119
+ revision: z.number().int(),
120
+ submittedAt: z.string(),
121
+ author: z.object({ id: z.string(), name: z.string() }),
122
+ annotations: z.array(z.object({
123
+ id: z.string(),
124
+ snippet: z.string(),
125
+ note: z.string(),
126
+ createdAt: z.string(),
127
+ filePath: z.string().optional(),
128
+ canvasFile: z.string().optional(),
129
+ context: z.unknown().optional(),
130
+ attachments: z.array(z.object({ url: z.string(), mime: z.string().optional() })).optional(),
131
+ })),
132
+ generalNote: z.string().optional(),
133
+ // Checked per response in decryptFeedbackEntry: one that does not fit must not cost the whole entry.
134
+ responses: z.unknown().optional(),
135
+ encryption: z.object({ alg: z.string(), v: z.number() }).optional(),
136
+ })
137
+ export type WireFeedbackEntry = z.infer<typeof wireFeedbackEntrySchema>
138
+
139
+ export interface FeedbackPage {
140
+ entries: WireFeedbackEntry[]
141
+ /** Ids of entries that did not match the wire format; they are skipped. */
142
+ malformed: string[]
143
+ /** High-water mark: pass it back as `since` on the next call. */
144
+ latestAt?: string
145
+ }
146
+
147
+ const feedbackPageSchema = z.object({ entries: z.array(z.unknown()), latestAt: z.string().optional() })
148
+
149
+ /** The share no longer exists on the worker (revoked or expired). */
150
+ export class ShareGoneError extends Error {}
151
+
152
+ // --- Requests ---------------------------------------------------------------
153
+
154
+ /**
155
+ * Encrypt a plaintext SharePayload, returning a new payload whose secret
156
+ * fields are ciphertext + the `encryption` marker.
157
+ * Fields kept plaintext (and why):
158
+ * - `version`, `runtime.componentsVersion`: routing
159
+ * - `origin.revision`, `origin.createdAt`: indexing/display
160
+ * - `canvasFiles[].filename`: used as the route key by the worker
161
+ * Everything else (sessionId, label, compiledJs, sourceJsx) is encrypted.
162
+ */
163
+ export async function encryptSharePayload(
164
+ payload: SharePayload,
165
+ key: CryptoKey,
166
+ ): Promise<SharePayload> {
167
+ const canvasFiles = await Promise.all(
168
+ payload.canvasFiles.map(async (cf) => ({
169
+ filename: cf.filename,
170
+ compiledJs: await encryptString(key, cf.compiledJs),
171
+ ...(cf.sourceJsx ? { sourceJsx: await encryptString(key, cf.sourceJsx) } : {}),
172
+ })),
173
+ )
174
+ return {
175
+ version: payload.version,
176
+ encryption: ENCRYPTION_META,
177
+ origin: {
178
+ sessionId: await encryptString(key, payload.origin.sessionId),
179
+ revision: payload.origin.revision,
180
+ ...(payload.origin.label
181
+ ? { label: await encryptString(key, payload.origin.label) }
182
+ : {}),
183
+ createdAt: payload.origin.createdAt,
184
+ },
185
+ canvasFiles,
186
+ runtime: payload.runtime,
187
+ }
188
+ }
189
+
190
+ /**
191
+ * POST the payload to the worker. Returns the `shareId` + public URL
192
+ * assigned by the worker. Throws on any HTTP error or a response that is
193
+ * not a share.
194
+ */
195
+ export async function pushShareToWorker(payload: SharePayload, config: ShareEndpoint): Promise<ShareResponse> {
196
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' }
197
+ if (config.authToken) headers['Authorization'] = `Bearer ${config.authToken}`
198
+
199
+ const res = await fetch(`${config.endpoint}/shares`, {
200
+ method: 'POST',
201
+ headers,
202
+ body: JSON.stringify(payload),
203
+ })
204
+ if (!res.ok) {
205
+ const text = await res.text().catch(() => '')
206
+ throw new Error(`Share endpoint returned ${res.status}: ${text || res.statusText}`)
207
+ }
208
+ const data: unknown = await res.json()
209
+ const parsed = shareResponseSchema.safeParse(data)
210
+ if (!parsed.success) {
211
+ // Only where it failed: the body carries the owner token, which must not reach a log or an error page.
212
+ const where = parsed.error.issues.map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`).join('; ')
213
+ throw new Error(`Share endpoint returned invalid response (${where})`)
214
+ }
215
+ return parsed.data
216
+ }
217
+
218
+ /**
219
+ * Encrypt (unless `encryption` is false) and upload a plaintext payload.
220
+ * The URL of an encrypted share carries the `#k=` fragment, so it can be
221
+ * handed to reviewers as is.
222
+ */
223
+ export async function createShare(
224
+ payload: SharePayload,
225
+ config: ShareEndpoint & { encryption?: boolean },
226
+ ): Promise<CreatedShare> {
227
+ if (config.encryption === false) return pushShareToWorker(payload, config)
228
+ const key = await generateShareKey()
229
+ const encryptionKey = await exportShareKey(key)
230
+ const response = await pushShareToWorker(await encryptSharePayload(payload, key), config)
231
+ return { ...response, url: `${response.url}#k=${encryptionKey}`, encryptionKey }
232
+ }
233
+
234
+ /** Revoke a share with the owner token returned when it was created. */
235
+ export async function revokeShareOnWorker(endpoint: string, shareId: string, ownerToken: string): Promise<void> {
236
+ const res = await fetch(`${endpoint}/shares/${encodeURIComponent(shareId)}/revoke`, {
237
+ method: 'POST',
238
+ headers: { 'Authorization': `Bearer ${ownerToken}` },
239
+ })
240
+ if (!res.ok) {
241
+ const text = await res.text().catch(() => '')
242
+ throw new Error(`Revoke failed: ${res.status} ${text}`)
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Feedback submitted since `since` (the previous `latestAt`, or "" for all).
248
+ * Throws ShareGoneError when the worker no longer serves the share.
249
+ */
250
+ export async function fetchShareFeedback(endpoint: string, shareId: string, since: string): Promise<FeedbackPage> {
251
+ const url = `${endpoint}/shares/${encodeURIComponent(shareId)}/feedback${since ? `?since=${encodeURIComponent(since)}` : ''}`
252
+ const res = await fetch(url)
253
+ if (res.status === 404) throw new ShareGoneError(`Share ${shareId} not found (revoked or expired)`)
254
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
255
+ const page = feedbackPageSchema.safeParse(await res.json())
256
+ if (!page.success) throw new Error('Feedback endpoint returned invalid response')
257
+ const entries: WireFeedbackEntry[] = []
258
+ const malformed: string[] = []
259
+ for (const candidate of page.data.entries) {
260
+ const entry = wireFeedbackEntrySchema.safeParse(candidate)
261
+ if (entry.success) entries.push(entry.data)
262
+ else malformed.push(z.object({ id: z.string() }).safeParse(candidate).data?.id ?? '(no id)')
263
+ }
264
+ return { entries, malformed, ...(page.data.latestAt ? { latestAt: page.data.latestAt } : {}) }
265
+ }
266
+
267
+ // The responses that fit the wire shape; the rest are counted, not fatal.
268
+ function readResponses(value: unknown): Pick<SharedFeedbackEntry, 'responses' | 'droppedResponses'> {
269
+ if (value === undefined) return {}
270
+ if (!Array.isArray(value)) return { droppedResponses: 1 }
271
+ const responses = value.flatMap((candidate) => {
272
+ const parsed = sharedResponseSchema.safeParse(candidate)
273
+ return parsed.success ? [parsed.data] : []
274
+ }).slice(0, MAX_SHARED_RESPONSES)
275
+ const droppedResponses = value.length - responses.length
276
+ return { ...(responses.length > 0 ? { responses } : {}), ...(droppedResponses > 0 ? { droppedResponses } : {}) }
277
+ }
278
+
279
+ async function openResponses(key: CryptoKey, value: unknown): Promise<Pick<SharedFeedbackEntry, 'responses' | 'droppedResponses'>> {
280
+ if (value === undefined) return {}
281
+ if (typeof value !== 'string') return { droppedResponses: 1 }
282
+ try {
283
+ return readResponses(JSON.parse(await decryptString(key, value)))
284
+ } catch {
285
+ return { droppedResponses: 1 }
286
+ }
287
+ }
288
+
289
+ function annotationContext(value: unknown): SharedAnnotation['context'] {
290
+ const parsed = annotationContextSchema.safeParse(value)
291
+ return parsed.success ? parsed.data : undefined
292
+ }
293
+
294
+ /**
295
+ * The plaintext form of a feedback entry. An encrypted entry needs the
296
+ * share's key; a plaintext one (from an unencrypted share) needs none.
297
+ * Throws if a text field fails to decrypt. Responses that do not fit are
298
+ * left out and counted in `droppedResponses`, so the rest of the entry stays.
299
+ */
300
+ export async function decryptFeedbackEntry(entry: WireFeedbackEntry, key: CryptoKey | null): Promise<SharedFeedbackEntry> {
301
+ const { encryption, responses, generalNote, annotations, ...rest } = entry
302
+ if (!encryption) {
303
+ return {
304
+ ...rest,
305
+ annotations: annotations.map(({ context, ...a }) => {
306
+ const parsed = annotationContext(context)
307
+ return parsed ? { ...a, context: parsed } : a
308
+ }),
309
+ ...(generalNote ? { generalNote } : {}),
310
+ ...readResponses(responses),
311
+ }
312
+ }
313
+ if (!key) throw new Error(`Entry ${entry.id} is encrypted and no key was given`)
314
+
315
+ const opened: SharedAnnotation[] = await Promise.all(
316
+ annotations.map(async (a) => {
317
+ const out: SharedAnnotation = {
318
+ id: a.id,
319
+ snippet: await decryptString(key, a.snippet),
320
+ note: await decryptString(key, a.note),
321
+ createdAt: a.createdAt,
322
+ }
323
+ if (a.filePath) out.filePath = await decryptString(key, a.filePath)
324
+ if (a.canvasFile) out.canvasFile = await decryptString(key, a.canvasFile)
325
+ if (typeof a.context === 'string' && a.context.length > 0) {
326
+ const context = annotationContext(JSON.parse(await decryptString(key, a.context)))
327
+ if (context) out.context = context
328
+ }
329
+ if (a.attachments) out.attachments = a.attachments
330
+ return out
331
+ }),
332
+ )
333
+
334
+ return {
335
+ ...rest,
336
+ author: { id: entry.author.id, name: await decryptString(key, entry.author.name) },
337
+ annotations: opened,
338
+ ...(generalNote ? { generalNote: await decryptString(key, generalNote) } : {}),
339
+ ...(await openResponses(key, responses)),
340
+ }
341
+ }
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod'
2
+
3
+ /**
4
+ * Structured answers a reviewer gives on a shared canvas: the wire shape the
5
+ * shared page sends with its feedback and the share worker validates. Kept
6
+ * apart from share-client.ts so the worker can import it without the
7
+ * encryption helpers.
8
+ */
9
+
10
+ export const MAX_SHARED_RESPONSES = 500
11
+ export const MAX_SHARED_RESPONSE_TEXT = 10_000
12
+ const responseText = z.string().max(MAX_SHARED_RESPONSE_TEXT)
13
+
14
+ /** A reviewer's answer to an input component (Choice, MultiChoice, UserInput, RangeInput) on the shared page. */
15
+ export const sharedResponseSchema = z.object({
16
+ id: z.string().min(1).max(200),
17
+ type: z.enum(['select', 'radio', 'checkbox', 'text', 'range']),
18
+ label: z.string().max(1000),
19
+ value: z.union([responseText, z.array(responseText).max(500), z.number(), z.null()]),
20
+ note: responseText.optional(),
21
+ })
22
+ export type SharedResponse = z.infer<typeof sharedResponseSchema>
23
+ export const sharedResponsesSchema = z.array(sharedResponseSchema).max(MAX_SHARED_RESPONSES)
24
+
25
+ /**
26
+ * The answered inputs of a draft, as the shared page sends them. A response
27
+ * that does not fit the wire shape (an unknown type, a label over 1000
28
+ * characters, no `value` key even with a note), or has neither a value nor a
29
+ * note, is left out.
30
+ */
31
+ export function answeredResponses(responses: readonly unknown[]): SharedResponse[] {
32
+ return responses.flatMap((candidate) => {
33
+ const parsed = sharedResponseSchema.safeParse(candidate)
34
+ if (!parsed.success) return []
35
+ const { value, note, ...rest } = parsed.data
36
+ const answered = Array.isArray(value) ? value.length > 0 : typeof value === 'string' ? value.trim() !== '' : value !== null
37
+ const trimmedNote = note?.trim() ?? ''
38
+ if (!answered && !trimmedNote) return []
39
+ return [{ ...rest, value, ...(trimmedNote ? { note: trimmedNote } : {}) }]
40
+ })
41
+ }