@rig-c/review 1.16.6 → 1.17.0

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,443 @@
1
+ /** Disjoint live-job routes. The backend receives the original authenticated Request. */
2
+ import type { JobErrorCode, JobHostPorts, JobResult } from './job-contract.ts';
3
+ import { createJobHostPorts } from './job-api.ts';
4
+ import { JobSession } from './job-session.ts';
5
+ import type { JobWorkerOptions } from './job-worker.ts';
6
+ import { JobError } from './job-store.ts';
7
+ import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
8
+ import { serveReference, assertReviewUnchanged } from './reference.ts';
9
+ import { loadPartsView, partsViewJson, servedImage, type PartsViewPackage } from './parts-view.ts';
10
+ import { dirname, join, relative } from 'node:path';
11
+ import { lstat, mkdir, rename, writeFile } from 'node:fs/promises';
12
+ import { randomUUID } from 'node:crypto';
13
+ import { acquireClaim, releaseClaim, running, smallJson } from './open.ts';
14
+ import { canonicalStatePath } from './state-dir.ts';
15
+ const headers = {
16
+ 'Cache-Control': 'no-store',
17
+ 'X-Content-Type-Options': 'nosniff',
18
+ 'Referrer-Policy': 'no-referrer',
19
+ 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self' blob:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",
20
+ };
21
+ function failure(code: string, status: number): Response {
22
+ return Response.json({ ok: false, error: { code, message: code } }, { status, headers });
23
+ }
24
+ const errorStatus: Partial<Record<JobErrorCode, number>> = {
25
+ JOB_REQUEST_INVALID: 400,
26
+ JOB_BODY_LIMIT: 413,
27
+ JOB_LOOPBACK_REQUIRED: 403,
28
+ JOB_SAME_ORIGIN_REQUIRED: 403,
29
+ JOB_CAPABILITY_REQUIRED: 403,
30
+ JOB_AUTHORITY_REFUSED: 403,
31
+ JOB_UNKNOWN: 404,
32
+ JOB_PUBLICATION_UNKNOWN: 404,
33
+ JOB_ACT_UNKNOWN: 404,
34
+ };
35
+ function result<Value>(value: JobResult<Value>): Response {
36
+ const status = value.ok ? 200 : errorStatus[value.error.code] ?? 409;
37
+ return Response.json(value, { status, headers });
38
+ }
39
+ /** A host supplies only shipped web resources. No request becomes a filesystem path. */
40
+ export function createJobFront(options: {
41
+ origin: string;
42
+ ports: JobHostPorts;
43
+ resource: (name: 'index.html' | 'job.js' | 'styles.css') => Promise<BodyInit>;
44
+ publication?: (jobId: string, publicationId: string, instanceKey: string, path: string, request: Request) => Promise<Response>;
45
+ }) {
46
+ const origin = new URL(options.origin);
47
+ if (origin.protocol !== 'http:' || origin.hostname !== '127.0.0.1' ||
48
+ origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash) {
49
+ throw new Error('JOB_LOOPBACK_REQUIRED');
50
+ }
51
+ const streams = new Set<AbortController>();
52
+ async function fetchJob(request: Request): Promise<Response | null> {
53
+ const url = new URL(request.url);
54
+ if (!url.pathname.startsWith('/jobs/'))
55
+ return null;
56
+ if (url.origin !== origin.origin)
57
+ return failure('JOB_LOOPBACK_REQUIRED', 403);
58
+ const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/(.*)$/.exec(url.pathname);
59
+ if (!match)
60
+ return failure('JOB_REQUEST_INVALID', 404);
61
+ const jobId = match[1]!;
62
+ const route = match[2]!;
63
+ const sentOrigin = request.headers.get('origin');
64
+ if (request.headers.get('sec-fetch-site') === 'cross-site' || sentOrigin !== null && sentOrigin !== origin.origin) {
65
+ return failure('JOB_SAME_ORIGIN_REQUIRED', 403);
66
+ }
67
+ const read = request.method === 'GET' || request.method === 'HEAD';
68
+ if (['api', 'ui/displayed', 'ui/acts'].includes(route)) {
69
+ if (request.method !== 'POST' || url.search)
70
+ return failure('JOB_REQUEST_INVALID', 405);
71
+ if (route !== 'api' && sentOrigin !== origin.origin)
72
+ return failure('JOB_SAME_ORIGIN_REQUIRED', 403);
73
+ // Each method owns streaming size bounds and actual capability authentication.
74
+ // A bearer agent request never gets reclassified as an authenticated UI act.
75
+ if (route === 'api')
76
+ return options.ports.handleJobApi(request);
77
+ if (route === 'ui/displayed')
78
+ return result(await options.ports.ackDisplayed(jobId, request));
79
+ return result(await options.ports.commitUIAct(jobId, request));
80
+ }
81
+ if (!read)
82
+ return failure('JOB_REQUEST_INVALID', 405);
83
+ const liveness = await options.ports.jobLiveness(jobId);
84
+ if (!liveness.ok)
85
+ return result(liveness);
86
+ if (route === 'events' && request.method === 'GET') {
87
+ const keys = [...url.searchParams.keys()];
88
+ if (keys.length > 1 || keys.some(key => key !== 'after'))
89
+ return failure('JOB_CURSOR_INVALID', 400);
90
+ const after = url.searchParams.get('after');
91
+ if (after !== null && (!after || after.length > 256))
92
+ return failure('JOB_CURSOR_INVALID', 400);
93
+ const abort = new AbortController();
94
+ streams.add(abort);
95
+ const stop = () => { abort.abort(); streams.delete(abort); request.signal.removeEventListener('abort', stop); };
96
+ request.signal.addEventListener('abort', stop, { once: true });
97
+ if (request.signal.aborted)
98
+ stop();
99
+ const iterator = options.ports.subscribeJob({ jobId, after, signal: abort.signal })[Symbol.asyncIterator]();
100
+ const encoder = new TextEncoder();
101
+ const body = new ReadableStream<Uint8Array>({
102
+ async pull(controller) {
103
+ try {
104
+ const next = await iterator.next();
105
+ if (next.done) {
106
+ stop();
107
+ controller.close();
108
+ }
109
+ else {
110
+ controller.enqueue(encoder.encode(JSON.stringify(next.value) + '\n'));
111
+ if (next.value.type === 'closed') {
112
+ stop();
113
+ controller.close();
114
+ await iterator.return?.();
115
+ }
116
+ }
117
+ }
118
+ catch {
119
+ stop();
120
+ controller.error(new Error('JOB_STREAM_FAILED'));
121
+ }
122
+ },
123
+ async cancel() { stop(); await iterator.return?.(); },
124
+ });
125
+ return new Response(body, { headers: { ...headers, 'Content-Type': 'application/x-ndjson' } });
126
+ }
127
+ if (url.search && !(route === '' && ['?lang=en', '?lang=ko'].includes(url.search)))
128
+ return failure('JOB_REQUEST_INVALID', 400);
129
+ const instance = /^publications\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/instances\/([a-f0-9]{64})\/(.*)$/.exec(route);
130
+ if (instance && options.publication) {
131
+ return options.publication(jobId, instance[1]!, instance[2]!, instance[3]!, request);
132
+ }
133
+ const publication = /^publications\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})$/.exec(route);
134
+ if (publication)
135
+ return result(await options.ports.readPublication(jobId, publication[1]!));
136
+ const name = route === '' ? 'index.html' : route === 'job.js' ? 'job.js' : route === 'styles.css' ? 'styles.css' : null;
137
+ if (!name)
138
+ return failure('JOB_REQUEST_INVALID', 404);
139
+ const type = name === 'index.html' ? 'text/html; charset=utf-8' : name === 'job.js' ? 'text/javascript' : 'text/css';
140
+ return new Response(request.method === 'HEAD' ? null : await options.resource(name), {
141
+ headers: { ...headers, 'Content-Type': type },
142
+ });
143
+ }
144
+ return {
145
+ fetch: fetchJob,
146
+ stop() { for (const stream of streams)
147
+ stream.abort(); streams.clear(); },
148
+ };
149
+ }
150
+ /** Installed files are fixed here. A job request never selects a local pathname. */
151
+ export function jobWindowResources() {
152
+ let bundle: Promise<Blob> | null = null;
153
+ return async (name: 'index.html' | 'job.js' | 'styles.css'): Promise<BodyInit> => {
154
+ if (name === 'index.html') {
155
+ return '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +
156
+ '<title>rig-review</title><link rel="stylesheet" href="styles.css"></head>' +
157
+ '<body data-job-window><script type="module" src="job.js"></script></body></html>';
158
+ }
159
+ if (name === 'styles.css')
160
+ return Bun.file(new URL('../web/styles.css', import.meta.url));
161
+ bundle ??= buildJobWindow();
162
+ return bundle;
163
+ };
164
+ }
165
+ export async function buildJobWindow(): Promise<Blob> {
166
+ const source = new URL('../web/job-session.ts', import.meta.url).pathname;
167
+ const result = await Bun.build({ entrypoints: [source], target: 'browser', format: 'esm', minify: false });
168
+ if (!result.success)
169
+ throw new Error(result.logs.map(log => log.message).join('\n'));
170
+ const output = result.outputs.find(output => output.path.endsWith('.js'));
171
+ if (!output)
172
+ throw new Error('JOB_WINDOW_BUNDLE_MISSING');
173
+ return output;
174
+ }
175
+
176
+ interface RetainedView {
177
+ review: ReviewPackage;
178
+ parts: PartsViewPackage | null;
179
+ }
180
+
181
+ /** The host reads only the committed retained snapshot and its sealed file inventory. */
182
+ function retainedPublicationRoutes(session: JobSession) {
183
+ const views = new Map<string, Promise<RetainedView>>();
184
+ return async (jobId: string, publicationId: string, key: string, path: string, request: Request): Promise<Response> => {
185
+ if (jobId !== session.jobId) return failure('JOB_UNKNOWN', 404);
186
+ try {
187
+ const display = session.displayPublication(publicationId);
188
+ if (key !== display.publication.instanceKey) return failure('JOB_DISPLAY_MISMATCH', 409);
189
+ const retained = session.retainedSource(publicationId);
190
+ let pending = views.get(publicationId);
191
+ if (!pending) {
192
+ pending = (async () => {
193
+ const review = await loadReview(retained.manifestPath);
194
+ const parts = retained.source.parts
195
+ ? await loadPartsView(dirname(join(retained.snapshotRoot, retained.source.parts.manifest.path)))
196
+ : null;
197
+ if (parts) {
198
+ if (parts.items.length !== retained.partIds.length || parts.items.some(item => !retained.partIds.includes(item.name))) {
199
+ throw new JobError('JOB_SOURCE_MISMATCH');
200
+ }
201
+ for (const file of [...parts.files, ...parts.flagFiles]) {
202
+ const path = relative(retained.snapshotRoot, file.abs).split('\\').join('/');
203
+ if (!retained.seals.some(seal => seal.path === path && seal.sha256 === file.sha256)) {
204
+ throw new JobError('JOB_SOURCE_UNRETAINABLE');
205
+ }
206
+ }
207
+ }
208
+ return {review, parts};
209
+ })();
210
+ views.set(publicationId, pending);
211
+ }
212
+ const {review, parts} = await pending;
213
+ await assertReviewUnchanged(review);
214
+ const json = (value: unknown) => new Response(request.method === 'HEAD' ? null : JSON.stringify(value), {
215
+ headers: {...headers, 'Content-Type': 'application/json'},
216
+ });
217
+ const sealedFile = async (relativePath: string) => {
218
+ const seal = retained.seals.find(file => file.path === relativePath);
219
+ if (!seal) return failure('JOB_SOURCE_UNRETAINABLE', 404);
220
+ const file = await safeFile(retained.snapshotRoot, relativePath);
221
+ return serveReference(request, file, seal.sha256, headers);
222
+ };
223
+ if (path === 'api/review') {
224
+ return json({
225
+ manifest: review.manifest,
226
+ sourceHash: retained.source.sourceHash,
227
+ reviewedSource: review.reviewedSource,
228
+ initialAnimation: null,
229
+ setsHash: review.setsHash,
230
+ direction: review.direction,
231
+ referenceHashes: review.referenceHashes,
232
+ sourcePainting: review.sourcePainting && {...review.sourcePainting, url: '/review-painting'},
233
+ feedbackCatalog: review.feedbackCatalog,
234
+ assetsBase: display.routes.assetsBase,
235
+ capabilities: {playback: !!review.manifest.model, interview: retained.questions.length > 0,
236
+ preRig: retained.source.selector?.kind === 'draft', modeling: false, motion: false, feedback: true, audio: false},
237
+ });
238
+ }
239
+ if (path === 'api/interview') {
240
+ return json({questions: retained.questions.map(question => ({...question,
241
+ images: question.images.map((image, index) => ({name: image.name,
242
+ url: `/api/interview/image/${question.ref.sha256}/${index}`})),
243
+ }))});
244
+ }
245
+ const interview = /^api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(path);
246
+ if (interview) {
247
+ const image = retained.questions.find(question => question.ref.sha256 === interview[1])?.images[Number(interview[2])];
248
+ if (!image) return failure('JOB_SOURCE_UNRETAINABLE', 404);
249
+ return await sealedFile(image.ref.path);
250
+ }
251
+ if (path === 'api/stage-parts') {
252
+ if (!parts) return failure('JOB_SOURCE_UNRETAINABLE', 409);
253
+ return json({...partsViewJson(parts, {verdict: null, stale: null}), sourceHash: retained.source.sourceHash,
254
+ inspectionSourceHash: retained.source.sourceHash, readOnly: true});
255
+ }
256
+ const part = /^api\/stage-parts\/(image|page)\/(0|[1-9]\d*)$/.exec(path);
257
+ if (part && parts) {
258
+ const file = servedImage(parts, part[1] as 'image' | 'page', Number(part[2]));
259
+ if (!file) return failure('JOB_SOURCE_UNRETAINABLE', 404);
260
+ return await sealedFile(relative(retained.snapshotRoot, file).split('\\').join('/'));
261
+ }
262
+ if (path === 'review-painting' && review.sourcePainting && review.handoff?.source) {
263
+ return await sealedFile(relative(retained.snapshotRoot, review.handoff.source).split('\\').join('/'));
264
+ }
265
+ if (path.startsWith('assets/')) {
266
+ const asset = packagePath(decodeURIComponent(path.slice('assets/'.length)));
267
+ if (!review.files.has(asset)) return failure('JOB_SOURCE_UNRETAINABLE', 404);
268
+ return await sealedFile(relative(retained.snapshotRoot, join(review.root, asset)).split('\\').join('/'));
269
+ }
270
+ return failure('JOB_REQUEST_INVALID', 404);
271
+ } catch (error) {
272
+ return failure(error instanceof JobError ? error.code : 'JOB_SOURCE_MISMATCH', 409);
273
+ }
274
+ };
275
+ }
276
+
277
+ interface JobHostRecord {
278
+ schema: 'rig-review-job-host/1';
279
+ jobId: string;
280
+ origin: string;
281
+ fingerprint: string;
282
+ pid: number;
283
+ /** Absent on older records whose hook identity cannot be established. */
284
+ readerId?: string | null;
285
+ bindingId?: string | null;
286
+ }
287
+
288
+ /** Callers declare stable hook semantics. Equal IDs permit reuse across processes. */
289
+ export interface JobHostOptions extends JobWorkerOptions {
290
+ readonly readerId?: string;
291
+ readonly bindingId?: string;
292
+ }
293
+
294
+ type JobHostOptionName = 'readPublished' | 'installWriterBinding';
295
+
296
+ class JobHostOptionError extends Error {
297
+ constructor(
298
+ readonly code: 'JOB_HOST_OPTION_ID_INVALID' | 'JOB_HOST_REUSE_MISMATCH',
299
+ readonly option: JobHostOptionName,
300
+ readonly listenerId: string | null | undefined,
301
+ readonly requestedId: string | null | undefined,
302
+ ) {
303
+ const previous = JSON.stringify(listenerId) ?? '<unrecorded>';
304
+ const requested = JSON.stringify(requestedId) ?? '<unrecorded>';
305
+ super(`${code}: ${option} (listener=${previous}, requested=${requested})`);
306
+ this.name = 'JobHostOptionError';
307
+ }
308
+ }
309
+
310
+ function declaredHostId(option: JobHostOptionName, hook: unknown, id: string | undefined): string | null {
311
+ if (hook === undefined && id === undefined) return null;
312
+ if (typeof hook !== 'function' || typeof id !== 'string' || id.length === 0) {
313
+ throw new JobHostOptionError('JOB_HOST_OPTION_ID_INVALID', option, null, id);
314
+ }
315
+ return id;
316
+ }
317
+
318
+ export interface JobOwnerHost {
319
+ readonly session: JobSession;
320
+ readonly ports: JobHostPorts;
321
+ readonly origin: string;
322
+ readonly ownerUrl: string;
323
+ readonly reused: boolean;
324
+ stop(): void;
325
+ }
326
+
327
+ /** Full standing owner host. #489 can publish this seam after its own contract review. */
328
+ export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHost> {
329
+ const startup = {...options};
330
+ const readerId = declaredHostId('readPublished', startup.readPublished, startup.readerId);
331
+ const bindingId = declaredHostId('installWriterBinding', startup.installWriterBinding, startup.bindingId);
332
+ const session = new JobSession(startup);
333
+ async function installBinding(origin: string): Promise<void> {
334
+ try {await startup.installWriterBinding?.({...session.writerGrant(), origin});}
335
+ catch {throw new JobError('JOB_AUTHORITY_REFUSED', 'Writer binding installation failed');}
336
+ }
337
+ const credentials = session.hostCredentials();
338
+ const control = join(canonicalStatePath(startup.stateDir), 'job-ui');
339
+ await mkdir(control, {recursive: true, mode: 0o700}).catch(error => {session.dispose(); throw error;});
340
+ const recordPath = join(control, session.jobId + '.json');
341
+ let previousPort = 0;
342
+ const reuse = async (): Promise<JobHostRecord | null> => {
343
+ try {
344
+ const info = await lstat(recordPath);
345
+ if (!info.isFile() || (info.mode & 0o077) !== 0) throw new JobError('JOB_AUTHORITY_REFUSED');
346
+ const row = await smallJson(recordPath) as JobHostRecord;
347
+ const origin = new URL(row.origin);
348
+ if (row.schema !== 'rig-review-job-host/1' || row.jobId !== session.jobId || row.fingerprint !== startup.fingerprint ||
349
+ origin.origin !== row.origin || origin.protocol !== 'http:' || origin.hostname !== '127.0.0.1' ||
350
+ !Number.isSafeInteger(row.pid) || row.pid <= 0) throw new JobError('JOB_STORAGE_FAILED');
351
+ previousPort = Number(origin.port);
352
+ if (!running(row.pid)) return null;
353
+ const response = await fetch(row.origin + `/jobs/${session.jobId}/host`, {
354
+ headers: {'X-Review-Capability': credentials.ui}, redirect: 'error', signal: AbortSignal.timeout(1500),
355
+ }).catch(() => null);
356
+ if (!response?.ok) {void response?.body?.cancel(); return null;}
357
+ const value = await response.json() as JobHostRecord;
358
+ if (value.schema !== row.schema || value.jobId !== row.jobId || value.fingerprint !== row.fingerprint) return null;
359
+ for (const [option, actual, requested] of [
360
+ ['readPublished', value.readerId, readerId],
361
+ ['installWriterBinding', value.bindingId, bindingId],
362
+ ] as const) {
363
+ if (actual !== requested) {
364
+ throw new JobHostOptionError('JOB_HOST_REUSE_MISMATCH', option, actual, requested);
365
+ }
366
+ }
367
+ return row;
368
+ } catch (error) {
369
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
370
+ throw error;
371
+ }
372
+ };
373
+ const nonce = randomUUID();
374
+ let claim: string | null = null;
375
+ let stop: (() => void) | null = null;
376
+ try {
377
+ const ready = await reuse();
378
+ const acquired = ready ? {row: ready} : await acquireClaim(control, 'job-' + session.jobId, nonce, reuse,
379
+ performance.now() + 20_000, 'JOB_STORAGE_FAILED');
380
+ if ('row' in acquired) {
381
+ const origin = acquired.row.origin;
382
+ const ports = createJobHostPorts(session, origin);
383
+ await installBinding(origin);
384
+ return {session, ports, origin, ownerUrl: origin + `/jobs/${session.jobId}/#cap=${credentials.ui}`,
385
+ reused: true, stop: () => session.dispose()};
386
+ }
387
+ claim = acquired.claim;
388
+ let front: ReturnType<typeof createJobFront>;
389
+ let ports: JobHostPorts;
390
+ const preferredPort = startup.port ?? previousPort;
391
+ const server = Bun.serve({hostname: '127.0.0.1', port: preferredPort, idleTimeout: 0,
392
+ async fetch(request) {
393
+ const url = new URL(request.url);
394
+ if (url.pathname === `/jobs/${session.jobId}/host`) {
395
+ if (url.origin !== origin || request.method !== 'GET' || url.search ||
396
+ request.headers.get('sec-fetch-site') === 'cross-site' ||
397
+ request.headers.get('origin') !== null && request.headers.get('origin') !== origin) return failure('JOB_REQUEST_INVALID', 403);
398
+ try {session.authorize('ui', request.headers.get('X-Review-Capability'));}
399
+ catch {return failure('JOB_CAPABILITY_REQUIRED', 403);}
400
+ return Response.json(record, {headers});
401
+ }
402
+ return await front.fetch(request) ?? failure('JOB_REQUEST_INVALID', 404);
403
+ },
404
+ });
405
+ const origin = `http://127.0.0.1:${server.port}`;
406
+ const record: JobHostRecord = {schema: 'rig-review-job-host/1', jobId: session.jobId, origin,
407
+ fingerprint: startup.fingerprint, pid: process.pid, readerId, bindingId};
408
+ ports = createJobHostPorts(session, origin);
409
+ front = createJobFront({origin, ports, resource: jobWindowResources(),
410
+ publication: retainedPublicationRoutes(session)});
411
+ const closed = new AbortController();
412
+ let stopped = false;
413
+ stop = () => {
414
+ if (stopped) return;
415
+ stopped = true;
416
+ closed.abort();
417
+ front.stop();
418
+ server.stop(true);
419
+ session.dispose();
420
+ };
421
+ await installBinding(origin);
422
+ const temporary = recordPath + '.' + nonce + '.tmp';
423
+ await writeFile(temporary, JSON.stringify(record), {flag: 'wx', mode: 0o600});
424
+ await rename(temporary, recordPath);
425
+ void (async () => {
426
+ try {
427
+ for await (const event of session.subscribe({jobId: session.jobId, after: null, signal: closed.signal})) {
428
+ if (event.type === 'closed') {
429
+ while (session.busy && !closed.signal.aborted) await Bun.sleep(25);
430
+ if (!closed.signal.aborted) setTimeout(() => stop?.(), 250);
431
+ return;
432
+ }
433
+ }
434
+ } catch { /* Shutdown aborts the subscription. */ }
435
+ })();
436
+ return {session, ports, origin, ownerUrl: origin + `/jobs/${session.jobId}/#cap=${credentials.ui}`, reused: false, stop};
437
+ } catch (error) {
438
+ if (stop) stop(); else session.dispose();
439
+ throw error;
440
+ } finally {
441
+ if (claim) await releaseClaim(claim, nonce);
442
+ }
443
+ }