rig-review 2.0.0 → 2.1.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.
- package/README.md +3 -3
- package/docs/WORKFLOWS.md +159 -35
- package/package.json +1 -1
- package/skills/rig-review/SKILL.md +58 -1
- package/src/build.ts +2 -2
- package/src/cli.ts +57 -2
- package/src/compare-server.ts +48 -10
- package/src/front.ts +1 -1
- package/src/open-workspace-contract.ts +60 -0
- package/src/open-workspace-launch.ts +103 -0
- package/src/open-workspace-state.ts +125 -0
- package/src/open-workspace-worker.ts +33 -0
- package/src/open-workspace.ts +292 -0
- package/src/open.ts +20 -7
- package/src/server.ts +51 -10
- package/web/catalog-en.ts +37 -0
- package/web/catalog-ko.ts +37 -0
- package/web/compare.ts +2 -0
- package/web/main.ts +2 -0
- package/web/owner-workspace.css +14 -0
- package/web/owner-workspace.html +5 -0
- package/web/owner-workspace.ts +124 -0
- package/web/workspace-visibility.ts +21 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type {OpenInputs} from './open.ts';
|
|
2
|
+
|
|
3
|
+
export const WORKSPACE_SCHEMA = 'rig-review-open-workspace/1';
|
|
4
|
+
export const WORKSPACE_TARGETS_SCHEMA = 'rig-review-open-targets/1';
|
|
5
|
+
export const WORKSPACE_VISIBILITY_SCHEMA = 'rig-review-workspace-visibility/1';
|
|
6
|
+
export const WORKSPACE_READY_SCHEMA = 'rig-review-workspace-ready/1';
|
|
7
|
+
export const WORKSPACE_TARGET_DOMAIN = 'rig-review-target/1';
|
|
8
|
+
export const WORKSPACE_TARGET_LIMIT = 32;
|
|
9
|
+
export const WORKSPACE_SOCKET_LIMIT = 64;
|
|
10
|
+
export const WORKSPACE_BODY_LIMIT = 64 * 1024;
|
|
11
|
+
export const WORKSPACE_REGISTRATION_QUEUE = 8;
|
|
12
|
+
|
|
13
|
+
export interface WorkspaceDesignation {
|
|
14
|
+
key: string;
|
|
15
|
+
contentHash: string;
|
|
16
|
+
inputs: OpenInputs;
|
|
17
|
+
cwd: string;
|
|
18
|
+
viewOnly: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface WorkspaceRecord {
|
|
22
|
+
schema: typeof WORKSPACE_SCHEMA;
|
|
23
|
+
incarnation: string;
|
|
24
|
+
pid: number;
|
|
25
|
+
uid: number;
|
|
26
|
+
origin: string;
|
|
27
|
+
installation: string;
|
|
28
|
+
fingerprint: string;
|
|
29
|
+
runtime: string;
|
|
30
|
+
registrationCapability: string;
|
|
31
|
+
ownerCapability: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface WorkspaceStoredTarget {
|
|
35
|
+
designation: WorkspaceDesignation;
|
|
36
|
+
controlToken?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface WorkspaceRegistry {
|
|
40
|
+
schema: typeof WORKSPACE_TARGETS_SCHEMA;
|
|
41
|
+
incarnation: string;
|
|
42
|
+
targets: WorkspaceStoredTarget[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface WorkspaceTargetView {
|
|
46
|
+
key: string;
|
|
47
|
+
contentHash: string;
|
|
48
|
+
title: string;
|
|
49
|
+
mode: 'single' | 'compare';
|
|
50
|
+
animation: string | null;
|
|
51
|
+
viewOnly: boolean;
|
|
52
|
+
unavailable: string | null;
|
|
53
|
+
entry: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface WorkspaceList {
|
|
57
|
+
schema: typeof WORKSPACE_SCHEMA;
|
|
58
|
+
incarnation: string;
|
|
59
|
+
targets: WorkspaceTargetView[];
|
|
60
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import {spawn} from 'node:child_process';
|
|
2
|
+
import {randomUUID} from 'node:crypto';
|
|
3
|
+
import {open, readFile, unlink} from 'node:fs/promises';
|
|
4
|
+
import {join} from 'node:path';
|
|
5
|
+
import {appRoot} from './build.ts';
|
|
6
|
+
import {frontPort} from './front.ts';
|
|
7
|
+
import {acquireClaim, defaultStateDir, openFingerprint, prepareOpenTarget, readOpenStatus, releaseClaim,
|
|
8
|
+
type OpenInputs, type OpenOptions} from './open.ts';
|
|
9
|
+
import {canonicalStatePath} from './state-dir.ts';
|
|
10
|
+
import {assertPrivate, parseRegistry, probeWorkspace, readPrivate, targetCapability, workspaceDirectory, workspaceError, writePrivate} from './open-workspace-state.ts';
|
|
11
|
+
import {WORKSPACE_BODY_LIMIT, WORKSPACE_SCHEMA, type WorkspaceDesignation, type WorkspaceRecord} from './open-workspace-contract.ts';
|
|
12
|
+
|
|
13
|
+
async function register(record: WorkspaceRecord, targets: WorkspaceDesignation[]) {
|
|
14
|
+
const text = JSON.stringify({schema: WORKSPACE_SCHEMA, incarnation: record.incarnation, targets});
|
|
15
|
+
if (Buffer.byteLength(text) > WORKSPACE_BODY_LIMIT) throw workspaceError('WORKSPACE_BODY_LIMIT');
|
|
16
|
+
const response = await fetch(record.origin + '/workspace/api/register', {
|
|
17
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(20_000),
|
|
18
|
+
headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + record.registrationCapability}, body: text,
|
|
19
|
+
});
|
|
20
|
+
const value = await readOpenStatus(response, 20_000) as {error?: string; schema?: string; incarnation?: string};
|
|
21
|
+
if (!response.ok) throw workspaceError(value.error?.startsWith('WORKSPACE_') ? value.error : 'WORKSPACE_REGISTRATION_REFUSED');
|
|
22
|
+
if (value.schema !== WORKSPACE_SCHEMA || value.incarnation !== record.incarnation) throw workspaceError('WORKSPACE_HOST_MISMATCH');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Launchers exchange designated package data, never callbacks or human acts. */
|
|
26
|
+
export async function openWorkspace(inputs: readonly OpenInputs[], options: OpenOptions = {}) {
|
|
27
|
+
const fingerprint = await openFingerprint();
|
|
28
|
+
const prepared = [];
|
|
29
|
+
for (const input of inputs) prepared.push(await prepareOpenTarget(input, options, fingerprint));
|
|
30
|
+
if (!prepared.length || inputs.some(input => input.direct)) throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
31
|
+
const stateDir = canonicalStatePath(options.stateDir ?? defaultStateDir());
|
|
32
|
+
const designations: WorkspaceDesignation[] = prepared.map(target => ({key: target.key,
|
|
33
|
+
contentHash: target.package.contentHash, cwd: target.cwd, viewOnly: target.viewOnly,
|
|
34
|
+
inputs: {...target.package.inputs, viewOnly: target.viewOnly}}));
|
|
35
|
+
if (Buffer.byteLength(JSON.stringify(designations)) > WORKSPACE_BODY_LIMIT - 256) throw workspaceError('WORKSPACE_BODY_LIMIT');
|
|
36
|
+
const directory = await workspaceDirectory(stateDir), port = frontPort(options.frontPort);
|
|
37
|
+
const nonce = randomUUID();
|
|
38
|
+
const reuse = () => probeWorkspace(directory, fingerprint, port);
|
|
39
|
+
const ready = await reuse();
|
|
40
|
+
const acquired = ready ? {row: ready} : await acquireClaim(directory, 'host', nonce, reuse,
|
|
41
|
+
performance.now() + 20_000, 'WORKSPACE_START_BUSY');
|
|
42
|
+
let child: ReturnType<typeof spawn> | undefined, handedOff = false, request: string | undefined;
|
|
43
|
+
try {
|
|
44
|
+
let record: WorkspaceRecord;
|
|
45
|
+
const reused = 'row' in acquired;
|
|
46
|
+
if ('row' in acquired) record = acquired.row;
|
|
47
|
+
else {
|
|
48
|
+
request = join(directory, nonce + '.request.json');
|
|
49
|
+
await writePrivate(request, {schema: WORKSPACE_SCHEMA, stateDir, fingerprint, port,
|
|
50
|
+
...(options.idleMs !== undefined ? {idleMs: options.idleMs} : {}),
|
|
51
|
+
...(options.graceMs !== undefined ? {graceMs: options.graceMs} : {})});
|
|
52
|
+
const logPath = join(directory, nonce + '.log');
|
|
53
|
+
const log = await open(logPath, 'a', 0o600);
|
|
54
|
+
try {
|
|
55
|
+
child = spawn(process.execPath, [join(appRoot, 'src/open-workspace-worker.ts'), request],
|
|
56
|
+
{cwd: directory, detached: true, stdio: ['ignore', log.fd, log.fd], env: process.env});
|
|
57
|
+
child.unref();
|
|
58
|
+
} finally {await log.close();}
|
|
59
|
+
let failure = false;
|
|
60
|
+
child.on('error', () => {failure = true;});
|
|
61
|
+
child.on('exit', () => {failure = true;});
|
|
62
|
+
const deadline = performance.now() + 20_000;
|
|
63
|
+
for (;;) {
|
|
64
|
+
const current = await reuse();
|
|
65
|
+
if (current) {record = current; break;}
|
|
66
|
+
if (failure) {
|
|
67
|
+
const diagnostic = (await readFile(logPath, 'utf8')).trim();
|
|
68
|
+
const occupied = `FRONT_PORT_BUSY: 127.0.0.1:${port} is held by another listener; use --direct (or set RIG_REVIEW_FRONT_PORT)`;
|
|
69
|
+
const safeCodes = ['WORKSPACE_REQUEST_INVALID', 'WORKSPACE_STATE_INVALID', 'WORKSPACE_BODY_LIMIT', 'WORKSPACE_START_REFUSED'];
|
|
70
|
+
throw workspaceError(diagnostic === occupied || safeCodes.includes(diagnostic) ? diagnostic : 'WORKSPACE_START_REFUSED');
|
|
71
|
+
}
|
|
72
|
+
if (performance.now() >= deadline) throw workspaceError('WORKSPACE_START_TIMEOUT');
|
|
73
|
+
await Bun.sleep(30);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
await register(record, designations);
|
|
77
|
+
handedOff = true;
|
|
78
|
+
return {url: record.origin + '/?workspace=' + record.incarnation + '#cap=' + record.ownerCapability, reused, prepared};
|
|
79
|
+
} finally {
|
|
80
|
+
if (child && !handedOff && child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');
|
|
81
|
+
if ('claim' in acquired) await releaseClaim(acquired.claim, nonce);
|
|
82
|
+
if (request) await unlink(request).catch(error => {if (error.code !== 'ENOENT') throw error;});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Trusted control CLI resolves only its exact opted-in target after authenticating the live workspace. */
|
|
87
|
+
export async function workspaceControlLocator(stateDir: string, key: string) {
|
|
88
|
+
const directory = join(canonicalStatePath(stateDir), 'owner-workspace');
|
|
89
|
+
try {await assertPrivate(directory, true);}
|
|
90
|
+
catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error;}
|
|
91
|
+
const value = await readPrivate(join(directory, 'host.json'));
|
|
92
|
+
if (!value) return null;
|
|
93
|
+
const record = await probeWorkspace(directory, await openFingerprint());
|
|
94
|
+
if (!record) return null;
|
|
95
|
+
const registry = await readPrivate(join(directory, 'targets.json'));
|
|
96
|
+
if (!registry) throw workspaceError('WORKSPACE_STATE_INVALID');
|
|
97
|
+
const stored = parseRegistry(registry);
|
|
98
|
+
if (stored.incarnation !== record.incarnation) throw workspaceError('WORKSPACE_HOST_MISMATCH');
|
|
99
|
+
const target = stored.targets.find(target => target.designation.key === key);
|
|
100
|
+
if (!target?.controlToken) return null;
|
|
101
|
+
return {origin: record.origin, prefix: '/instances/' + key, controlToken: target.controlToken,
|
|
102
|
+
capability: targetCapability(record.ownerCapability, record.incarnation, key)};
|
|
103
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import {createHmac, randomUUID} from 'node:crypto';
|
|
2
|
+
import {lstat, mkdir, rename, unlink, writeFile} from 'node:fs/promises';
|
|
3
|
+
import {isAbsolute, join} from 'node:path';
|
|
4
|
+
import {appRoot} from './build.ts';
|
|
5
|
+
import {readOpenStatus, running, smallJson} from './open.ts';
|
|
6
|
+
import {canonicalStatePath} from './state-dir.ts';
|
|
7
|
+
import {capabilityPattern} from './open-protocol.ts';
|
|
8
|
+
import {WORKSPACE_BODY_LIMIT, WORKSPACE_SCHEMA, WORKSPACE_TARGETS_SCHEMA, WORKSPACE_TARGET_DOMAIN, WORKSPACE_TARGET_LIMIT,
|
|
9
|
+
type WorkspaceDesignation, type WorkspaceRecord, type WorkspaceRegistry} from './open-workspace-contract.ts';
|
|
10
|
+
|
|
11
|
+
export function workspaceError(code: string): Error {return new Error(code);}
|
|
12
|
+
|
|
13
|
+
export async function assertPrivate(path: string, directory: boolean) {
|
|
14
|
+
const info = await lstat(path);
|
|
15
|
+
if (!(directory ? info.isDirectory() : info.isFile()) || (info.mode & 0o077) !== 0 ||
|
|
16
|
+
typeof process.getuid === 'function' && info.uid !== process.getuid() || !directory && info.nlink !== 1) throw workspaceError('WORKSPACE_STATE_INVALID');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function workspaceDirectory(stateDir: string) {
|
|
20
|
+
const directory = join(canonicalStatePath(stateDir), 'owner-workspace');
|
|
21
|
+
await mkdir(directory, {recursive: true, mode: 0o700});
|
|
22
|
+
await assertPrivate(directory, true);
|
|
23
|
+
return directory;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function readPrivate(path: string): Promise<unknown | null> {
|
|
27
|
+
try {await assertPrivate(path, false); return await smallJson(path);}
|
|
28
|
+
catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw workspaceError('WORKSPACE_STATE_INVALID');}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function writePrivate(path: string, value: unknown) {
|
|
32
|
+
const text = JSON.stringify(value);
|
|
33
|
+
if (Buffer.byteLength(text) > WORKSPACE_BODY_LIMIT) throw workspaceError('WORKSPACE_BODY_LIMIT');
|
|
34
|
+
await readPrivate(path);
|
|
35
|
+
const temporary = path + '.' + randomUUID() + '.tmp';
|
|
36
|
+
try {
|
|
37
|
+
await writeFile(temporary, text, {flag: 'wx', mode: 0o600});
|
|
38
|
+
await rename(temporary, path);
|
|
39
|
+
} finally {await unlink(temporary).catch(error => {if (error.code !== 'ENOENT') throw error;});}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function targetCapability(ownerCapability: string, incarnation: string, key: string) {
|
|
43
|
+
return createHmac('sha256', ownerCapability).update(WORKSPACE_TARGET_DOMAIN + '\0' + incarnation + '\0' + key).digest('hex');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function object(value: unknown): Record<string, unknown> {
|
|
47
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
48
|
+
return value as Record<string, unknown>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function parseDesignation(value: unknown): WorkspaceDesignation {
|
|
52
|
+
const row = object(value), inputs = object(row.inputs);
|
|
53
|
+
if (Object.keys(row).some(key => !['key', 'contentHash', 'inputs', 'cwd', 'viewOnly'].includes(key)) ||
|
|
54
|
+
!capabilityPattern.test(String(row.key)) || !capabilityPattern.test(String(row.contentHash)) ||
|
|
55
|
+
typeof row.cwd !== 'string' || row.cwd.length > 4096 || !isAbsolute(row.cwd) || typeof row.viewOnly !== 'boolean') {
|
|
56
|
+
throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
57
|
+
}
|
|
58
|
+
const strings = ['input', 'compare', 'reference', 'animation', 'config', 'parts', 'source', 'full', 'head', 'keypoints'];
|
|
59
|
+
for (const [key, item] of Object.entries(inputs)) {
|
|
60
|
+
if (strings.includes(key)) {
|
|
61
|
+
if (typeof item !== 'string' || !item || item.length > 4096) throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
62
|
+
} else if (key === 'control' || key === 'viewOnly') {
|
|
63
|
+
if (typeof item !== 'boolean') throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
64
|
+
} else if (key === 'project') {
|
|
65
|
+
const project = object(item);
|
|
66
|
+
for (const [field, entry] of Object.entries(project)) {
|
|
67
|
+
if (['root', 'picksDir', 'draftId', 'partsVerdictDir'].includes(field)) {
|
|
68
|
+
if (typeof entry !== 'string' || !entry || entry.length > 4096) throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
69
|
+
} else if (field === 'version' || field === 'postVersion') {
|
|
70
|
+
if (!Number.isSafeInteger(entry) || Number(entry) < 1) throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
71
|
+
} else throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
72
|
+
}
|
|
73
|
+
if (typeof project.root !== 'string' || typeof project.picksDir !== 'string') throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
74
|
+
} else throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
75
|
+
}
|
|
76
|
+
if (typeof inputs.input !== 'string' || !isAbsolute(inputs.input)) throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
77
|
+
return row as unknown as WorkspaceDesignation;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function parseRegistry(value: unknown): WorkspaceRegistry {
|
|
81
|
+
const row = object(value);
|
|
82
|
+
if (row.schema !== WORKSPACE_TARGETS_SCHEMA || typeof row.incarnation !== 'string' || !Array.isArray(row.targets) ||
|
|
83
|
+
row.targets.length > WORKSPACE_TARGET_LIMIT) throw workspaceError('WORKSPACE_STATE_INVALID');
|
|
84
|
+
const seen = new Set<string>();
|
|
85
|
+
for (const entry of row.targets) {
|
|
86
|
+
const target = object(entry), designation = parseDesignation(target.designation);
|
|
87
|
+
if (seen.has(designation.key) || target.controlToken !== undefined &&
|
|
88
|
+
(typeof target.controlToken !== 'string' || !/^[a-f0-9-]{36}$/.test(target.controlToken))) throw workspaceError('WORKSPACE_STATE_INVALID');
|
|
89
|
+
seen.add(designation.key);
|
|
90
|
+
}
|
|
91
|
+
return row as unknown as WorkspaceRegistry;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function parseWorkspaceRecord(value: unknown): WorkspaceRecord {
|
|
95
|
+
const row = object(value);
|
|
96
|
+
let origin: URL;
|
|
97
|
+
try {origin = new URL(String(row.origin));} catch {throw workspaceError('WORKSPACE_STATE_INVALID');}
|
|
98
|
+
if (row.schema !== WORKSPACE_SCHEMA || !/^[a-f0-9-]{36}$/.test(String(row.incarnation)) ||
|
|
99
|
+
!Number.isSafeInteger(row.pid) || Number(row.pid) < 1 || !Number.isSafeInteger(row.uid) ||
|
|
100
|
+
typeof row.installation !== 'string' || !isAbsolute(row.installation) || typeof row.runtime !== 'string' ||
|
|
101
|
+
!capabilityPattern.test(String(row.fingerprint)) || !capabilityPattern.test(String(row.registrationCapability)) ||
|
|
102
|
+
!capabilityPattern.test(String(row.ownerCapability)) || origin.origin !== row.origin ||
|
|
103
|
+
origin.protocol !== 'http:' || origin.hostname !== '127.0.0.1' || !origin.port) throw workspaceError('WORKSPACE_STATE_INVALID');
|
|
104
|
+
return row as unknown as WorkspaceRecord;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A live but silent PID remains owned. A timeout never authorizes replacement. */
|
|
108
|
+
export async function probeWorkspace(directory: string, fingerprint: string, port?: number): Promise<WorkspaceRecord | null> {
|
|
109
|
+
await assertPrivate(directory, true);
|
|
110
|
+
const value = await readPrivate(join(directory, 'host.json'));
|
|
111
|
+
if (value === null) return null;
|
|
112
|
+
const record = parseWorkspaceRecord(value);
|
|
113
|
+
if (record.uid !== (process.getuid?.() ?? 0)) throw workspaceError('WORKSPACE_OWNER_MISMATCH');
|
|
114
|
+
if (!running(record.pid)) return null;
|
|
115
|
+
if (record.fingerprint !== fingerprint || record.installation !== appRoot || record.runtime !== Bun.version ||
|
|
116
|
+
port !== undefined && new URL(record.origin).port !== String(port)) throw workspaceError('WORKSPACE_HOST_MISMATCH');
|
|
117
|
+
const response = await fetch(record.origin + '/workspace/api/status', {
|
|
118
|
+
headers: {Authorization: 'Bearer ' + record.registrationCapability}, redirect: 'error', signal: AbortSignal.timeout(1500),
|
|
119
|
+
}).catch(() => null);
|
|
120
|
+
if (!response?.ok) {void response?.body?.cancel(); throw workspaceError('WORKSPACE_HOST_UNRESPONSIVE');}
|
|
121
|
+
const status = object(await readOpenStatus(response));
|
|
122
|
+
if (status.schema !== WORKSPACE_SCHEMA || status.incarnation !== record.incarnation || status.pid !== record.pid ||
|
|
123
|
+
status.fingerprint !== fingerprint || status.runtime !== record.runtime) throw workspaceError('WORKSPACE_HOST_MISMATCH');
|
|
124
|
+
return record;
|
|
125
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {dirname, join} from 'node:path';
|
|
2
|
+
import {realpath, unlink} from 'node:fs/promises';
|
|
3
|
+
import {startOpenWorkspace} from './open-workspace.ts';
|
|
4
|
+
import {openFingerprint} from './open.ts';
|
|
5
|
+
import {readPrivate, workspaceDirectory, workspaceError} from './open-workspace-state.ts';
|
|
6
|
+
import {WORKSPACE_SCHEMA} from './open-workspace-contract.ts';
|
|
7
|
+
|
|
8
|
+
async function main(path: string) {
|
|
9
|
+
const value = await readPrivate(path) as {schema?: unknown; stateDir?: unknown; fingerprint?: unknown;
|
|
10
|
+
port?: unknown; idleMs?: unknown; graceMs?: unknown} | null;
|
|
11
|
+
if (!value || value.schema !== WORKSPACE_SCHEMA || typeof value.stateDir !== 'string' ||
|
|
12
|
+
value.fingerprint !== await openFingerprint() || !Number.isSafeInteger(value.port) ||
|
|
13
|
+
Number(value.port) < 1 || Number(value.port) > 65535 ||
|
|
14
|
+
[value.idleMs, value.graceMs].some(item => item !== undefined && (!Number.isSafeInteger(item) || Number(item) < 100))) {
|
|
15
|
+
throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
16
|
+
}
|
|
17
|
+
const directory = await workspaceDirectory(value.stateDir);
|
|
18
|
+
if (dirname(await realpath(path)) !== directory) throw workspaceError('WORKSPACE_STATE_INVALID');
|
|
19
|
+
await unlink(path).catch(error => {if (error.code !== 'ENOENT') throw error;});
|
|
20
|
+
const host = await startOpenWorkspace({stateDir: value.stateDir, fingerprint: String(value.fingerprint),
|
|
21
|
+
port: Number(value.port), idleMs: value.idleMs as number | undefined, graceMs: value.graceMs as number | undefined});
|
|
22
|
+
const stop = () => {void host.stop().then(() => process.exit(0));};
|
|
23
|
+
process.once('SIGTERM', stop); process.once('SIGINT', stop);
|
|
24
|
+
void host.live.exited.then(info => {if (info) process.exit(0);});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (import.meta.main) main(Bun.argv[2] ?? join(process.cwd(), 'missing.request')).catch(error => {
|
|
28
|
+
const message = error instanceof Error ? error.message : '';
|
|
29
|
+
const occupied = /^FRONT_PORT_BUSY: 127\.0\.0\.1:[1-9]\d{0,4} is held by another listener; use --direct \(or set RIG_REVIEW_FRONT_PORT\)$/.test(message);
|
|
30
|
+
const safeCodes = ['WORKSPACE_REQUEST_INVALID', 'WORKSPACE_STATE_INVALID', 'WORKSPACE_BODY_LIMIT', 'WORKSPACE_START_REFUSED'];
|
|
31
|
+
console.error(occupied || safeCodes.includes(message) ? message : 'WORKSPACE_START_REFUSED');
|
|
32
|
+
process.exitCode = 1;
|
|
33
|
+
});
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import {randomBytes, randomUUID} from 'node:crypto';
|
|
2
|
+
import {join} from 'node:path';
|
|
3
|
+
import {readFile, unlink} from 'node:fs/promises';
|
|
4
|
+
import {appRoot, buildWeb} from './build.ts';
|
|
5
|
+
import {createReviewRequestContext} from './server.ts';
|
|
6
|
+
import {createCompareRequestContext} from './compare-server.ts';
|
|
7
|
+
import {createLiveLifecycle, type UpgradableServer} from './live-lifecycle.ts';
|
|
8
|
+
import {prepareOpenTarget} from './open.ts';
|
|
9
|
+
import {sameSecret} from './open-protocol.ts';
|
|
10
|
+
import {boundedBody, frontRoute, maximumUpstreamStreams, stageFrameQuery} from './front.ts';
|
|
11
|
+
import {assertCompareUnchanged} from './compare.ts';
|
|
12
|
+
import {assertReviewUnchanged} from './reference.ts';
|
|
13
|
+
import {parseDesignation, parseRegistry, readPrivate, targetCapability, workspaceDirectory, workspaceError, writePrivate} from './open-workspace-state.ts';
|
|
14
|
+
import {WORKSPACE_BODY_LIMIT, WORKSPACE_REGISTRATION_QUEUE, WORKSPACE_SCHEMA, WORKSPACE_SOCKET_LIMIT,
|
|
15
|
+
WORKSPACE_TARGET_LIMIT, WORKSPACE_TARGETS_SCHEMA, type WorkspaceDesignation, type WorkspaceList,
|
|
16
|
+
type WorkspaceRecord, type WorkspaceStoredTarget, type WorkspaceTargetView} from './open-workspace-contract.ts';
|
|
17
|
+
|
|
18
|
+
type RequestContext = Awaited<ReturnType<typeof createReviewRequestContext>>;
|
|
19
|
+
interface Target {
|
|
20
|
+
stored: WorkspaceStoredTarget;
|
|
21
|
+
view: WorkspaceTargetView;
|
|
22
|
+
context: RequestContext | null;
|
|
23
|
+
check: (() => Promise<void>) | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const securityHeaders = {
|
|
27
|
+
'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer',
|
|
28
|
+
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; frame-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",
|
|
29
|
+
};
|
|
30
|
+
const json = (value: unknown, status = 200) => {
|
|
31
|
+
const text = JSON.stringify(value);
|
|
32
|
+
if (Buffer.byteLength(text) > WORKSPACE_BODY_LIMIT) throw workspaceError('WORKSPACE_BODY_LIMIT');
|
|
33
|
+
return new Response(text, {status, headers: {...securityHeaders, 'Content-Type': 'application/json'}});
|
|
34
|
+
};
|
|
35
|
+
const refused = (code: string, status = 409) => json({error: code}, status);
|
|
36
|
+
|
|
37
|
+
export interface OpenWorkspaceOptions {
|
|
38
|
+
stateDir: string;
|
|
39
|
+
fingerprint: string;
|
|
40
|
+
port: number;
|
|
41
|
+
idleMs?: number;
|
|
42
|
+
graceMs?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** One actual listener, with package contexts mounted in-process. */
|
|
46
|
+
export async function startOpenWorkspace(options: OpenWorkspaceOptions) {
|
|
47
|
+
const directory = await workspaceDirectory(options.stateDir);
|
|
48
|
+
const incarnation = randomUUID();
|
|
49
|
+
const ownerCapability = randomBytes(32).toString('hex');
|
|
50
|
+
const registrationCapability = randomBytes(32).toString('hex');
|
|
51
|
+
let targets = new Map<string, Target>();
|
|
52
|
+
let activeStreams = 0, registrations = 0, producing = false, accepting = true;
|
|
53
|
+
let pending = Promise.resolve();
|
|
54
|
+
let rawStop: ((close?: boolean) => void | Promise<void>) | undefined;
|
|
55
|
+
let record: WorkspaceRecord;
|
|
56
|
+
let stopPromise: Promise<void> | undefined;
|
|
57
|
+
const bundles = new Map<'single' | 'compare', Promise<Blob>>();
|
|
58
|
+
const ownerBundle = () => buildWeb('workspace');
|
|
59
|
+
let ownerScript: Promise<Blob> | undefined;
|
|
60
|
+
const busy = () => registrations > 0 || activeStreams > 0 || [...targets.values()].some(target => target.context?.busy());
|
|
61
|
+
const live = createLiveLifecycle({label: 'review workspace', graceMs: options.graceMs,
|
|
62
|
+
unopenedTimeoutMs: options.idleMs, busy, stopServer: () => stop(), log: line => console.error(line)});
|
|
63
|
+
|
|
64
|
+
function list(): WorkspaceList {
|
|
65
|
+
return {schema: WORKSPACE_SCHEMA, incarnation, targets: [...targets.values()].map(target => target.view)};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function prepare(designation: WorkspaceDesignation): Promise<Target> {
|
|
69
|
+
const prepared = await prepareOpenTarget(designation.inputs, {
|
|
70
|
+
stateDir: options.stateDir, cwd: designation.cwd, viewOnly: designation.viewOnly,
|
|
71
|
+
}, options.fingerprint);
|
|
72
|
+
const loaded = prepared.package;
|
|
73
|
+
if (prepared.key !== designation.key || loaded.contentHash !== designation.contentHash) throw workspaceError('WORKSPACE_SOURCE_CHANGED');
|
|
74
|
+
let bundle = bundles.get(loaded.mode);
|
|
75
|
+
if (!bundle) {bundle = buildWeb(loaded.mode); bundles.set(loaded.mode, bundle);}
|
|
76
|
+
const controlToken = loaded.inputs.control ? randomUUID() : undefined;
|
|
77
|
+
const contextOptions = {stateDir: options.stateDir, cwd: designation.cwd, lifecycle: live, bundle: await bundle,
|
|
78
|
+
capability: targetCapability(ownerCapability, incarnation, designation.key),
|
|
79
|
+
open: {key: designation.key, contentHash: designation.contentHash, nonce: incarnation, fingerprint: options.fingerprint},
|
|
80
|
+
...(controlToken ? {control: {token: controlToken, instanceKey: designation.key}} : {}),
|
|
81
|
+
};
|
|
82
|
+
const context = loaded.mode === 'single'
|
|
83
|
+
? await createReviewRequestContext(loaded.p, {...contextOptions, joined: loaded.joined,
|
|
84
|
+
initialAnimation: loaded.selection?.name, viewOnly: designation.viewOnly})
|
|
85
|
+
: await createCompareRequestContext(loaded.p, contextOptions);
|
|
86
|
+
const check = () => loaded.mode === 'single' ? assertReviewUnchanged(loaded.p) : assertCompareUnchanged(loaded.p);
|
|
87
|
+
await check();
|
|
88
|
+
return {stored: {designation, ...(controlToken ? {controlToken} : {})}, context, check,
|
|
89
|
+
view: {key: designation.key, contentHash: designation.contentHash,
|
|
90
|
+
title: (loaded.mode === 'single' ? loaded.p.manifest.title : loaded.p.response.title).slice(0, 256),
|
|
91
|
+
mode: loaded.mode, animation: loaded.selection?.name ?? null, viewOnly: designation.viewOnly, unavailable: null,
|
|
92
|
+
entry: `/instances/${designation.key}/?input=${designation.contentHash}&handoff=${designation.key}&workspace=${incarnation}`}};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function persist(next: Map<string, Target>) {
|
|
96
|
+
await writePrivate(join(directory, 'targets.json'), {
|
|
97
|
+
schema: WORKSPACE_TARGETS_SCHEMA, incarnation, targets: [...next.values()].map(target => target.stored),
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function register(values: unknown) {
|
|
102
|
+
if (!accepting) throw workspaceError('WORKSPACE_CLOSING');
|
|
103
|
+
if (!Array.isArray(values) || !values.length || values.length > WORKSPACE_TARGET_LIMIT) throw workspaceError('WORKSPACE_REQUEST_INVALID');
|
|
104
|
+
const designations = values.map(parseDesignation);
|
|
105
|
+
const requested = new Set(designations.map(designation => designation.key));
|
|
106
|
+
if (registrations >= WORKSPACE_REGISTRATION_QUEUE) throw workspaceError('WORKSPACE_BUSY');
|
|
107
|
+
registrations++;
|
|
108
|
+
const operation = pending.then(async () => {
|
|
109
|
+
if (!accepting) throw workspaceError('WORKSPACE_CLOSING');
|
|
110
|
+
const next = new Map(targets), created: Target[] = [];
|
|
111
|
+
try {
|
|
112
|
+
for (const designation of designations) {
|
|
113
|
+
const current = next.get(designation.key);
|
|
114
|
+
if (current) {
|
|
115
|
+
if (JSON.stringify(current.stored.designation) !== JSON.stringify(designation)) throw workspaceError('WORKSPACE_TARGET_OPTIONS_MISMATCH');
|
|
116
|
+
if (current.view.unavailable) throw workspaceError('WORKSPACE_SOURCE_CHANGED');
|
|
117
|
+
await current.check?.();
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (next.size >= WORKSPACE_TARGET_LIMIT) throw workspaceError('WORKSPACE_TARGET_LIMIT');
|
|
121
|
+
const target = await prepare(designation);
|
|
122
|
+
created.push(target); next.set(designation.key, target);
|
|
123
|
+
}
|
|
124
|
+
for (const [key, target] of next) {
|
|
125
|
+
if (requested.has(key)) await target.check?.();
|
|
126
|
+
else if (!target.view.unavailable) {
|
|
127
|
+
try {await target.check?.();}
|
|
128
|
+
catch {next.set(key, {...target, view: {...target.view, unavailable: 'WORKSPACE_SOURCE_CHANGED'}});}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
await persist(next);
|
|
132
|
+
targets = next;
|
|
133
|
+
live.rearmUnopened();
|
|
134
|
+
return {schema: WORKSPACE_SCHEMA, incarnation, count: targets.size};
|
|
135
|
+
} catch (error) {for (const target of created) target.context?.stop(); throw error;}
|
|
136
|
+
});
|
|
137
|
+
pending = operation.then(() => {}, () => {});
|
|
138
|
+
try {return await operation;} finally {registrations--;}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function stream(response: Response, request: Request, release: () => void) {
|
|
142
|
+
if (!response.body || request.method === 'HEAD') {release(); return response;}
|
|
143
|
+
const reader = response.body.getReader();
|
|
144
|
+
const abort = () => {release(); void reader.cancel().catch(() => {});};
|
|
145
|
+
request.signal.addEventListener('abort', abort, {once: true});
|
|
146
|
+
if (request.signal.aborted) abort();
|
|
147
|
+
const done = () => {request.signal.removeEventListener('abort', abort); release();};
|
|
148
|
+
return new Response(new ReadableStream<Uint8Array>({
|
|
149
|
+
async pull(controller) {
|
|
150
|
+
try {const next = await reader.read(); if (next.done) {done(); controller.close();} else controller.enqueue(next.value);}
|
|
151
|
+
catch (error) {done(); controller.error(error);}
|
|
152
|
+
},
|
|
153
|
+
cancel(reason) {done(); return reader.cancel(reason);},
|
|
154
|
+
}), {status: response.status, headers: response.headers});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function route(request: Request, server: UpgradableServer): Promise<Response | undefined> {
|
|
158
|
+
const url = new URL(request.url);
|
|
159
|
+
if (url.origin !== record.origin) return refused('WORKSPACE_LOOPBACK_REQUIRED', 403);
|
|
160
|
+
const sentOrigin = request.headers.get('origin');
|
|
161
|
+
if (request.headers.get('sec-fetch-site') === 'cross-site' || sentOrigin !== null && sentOrigin !== record.origin) {
|
|
162
|
+
return refused('WORKSPACE_SAME_ORIGIN_REQUIRED', 403);
|
|
163
|
+
}
|
|
164
|
+
const launch = sameSecret(request.headers.get('authorization'), 'Bearer ' + registrationCapability);
|
|
165
|
+
const owner = sameSecret(request.headers.get('X-Review-Capability'), ownerCapability);
|
|
166
|
+
if (url.pathname === '/workspace/api/status') {
|
|
167
|
+
if (request.method !== 'GET' || url.search || !launch) return refused('WORKSPACE_CAPABILITY_REQUIRED', 403);
|
|
168
|
+
return json({schema: WORKSPACE_SCHEMA, incarnation, pid: process.pid, fingerprint: options.fingerprint, runtime: Bun.version});
|
|
169
|
+
}
|
|
170
|
+
if (url.pathname === '/workspace/api/register') {
|
|
171
|
+
if (request.method !== 'POST' || url.search || !launch) return refused('WORKSPACE_CAPABILITY_REQUIRED', 403);
|
|
172
|
+
const body: unknown = JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(await boundedBody(request, WORKSPACE_BODY_LIMIT)));
|
|
173
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return refused('WORKSPACE_REQUEST_INVALID', 400);
|
|
174
|
+
const value = body as Record<string, unknown>;
|
|
175
|
+
if (Object.keys(value).some(key => !['schema', 'incarnation', 'targets'].includes(key)) ||
|
|
176
|
+
value.schema !== WORKSPACE_SCHEMA || value.incarnation !== incarnation) return refused('WORKSPACE_REQUEST_INVALID', 400);
|
|
177
|
+
return json(await register(value.targets));
|
|
178
|
+
}
|
|
179
|
+
if (url.pathname === '/workspace/api/targets') {
|
|
180
|
+
if (request.method !== 'GET' || url.search || !owner) return refused('WORKSPACE_CAPABILITY_REQUIRED', 403);
|
|
181
|
+
return json(list());
|
|
182
|
+
}
|
|
183
|
+
if (url.pathname === '/workspace/live') {
|
|
184
|
+
if (request.method !== 'GET' || url.search || sentOrigin !== record.origin) return refused('WORKSPACE_SAME_ORIGIN_REQUIRED', 403);
|
|
185
|
+
if (live.connections >= WORKSPACE_SOCKET_LIMIT) return refused('WORKSPACE_BUSY', 503);
|
|
186
|
+
return live.upgrade(request, server, securityHeaders);
|
|
187
|
+
}
|
|
188
|
+
if (['/', '/workspace.js', '/workspace.css', '/styles.css'].includes(url.pathname)) {
|
|
189
|
+
if (!['GET', 'HEAD'].includes(request.method)) return refused('WORKSPACE_REQUEST_INVALID', 400);
|
|
190
|
+
if (url.pathname === '/') {
|
|
191
|
+
const keys = [...url.searchParams.keys()];
|
|
192
|
+
if (new Set(keys).size !== keys.length || keys.some(key => !['workspace', 'lang'].includes(key)) ||
|
|
193
|
+
url.searchParams.has('lang') && !['en', 'ko'].includes(url.searchParams.get('lang')!)) {
|
|
194
|
+
return refused('WORKSPACE_REQUEST_INVALID', 400);
|
|
195
|
+
}
|
|
196
|
+
if (url.searchParams.has('workspace') && url.searchParams.get('workspace') !== incarnation) {
|
|
197
|
+
return refused('WORKSPACE_HOST_MISMATCH', 409);
|
|
198
|
+
}
|
|
199
|
+
} else if (url.search && !['?lang=en', '?lang=ko'].includes(url.search)) {
|
|
200
|
+
return refused('WORKSPACE_REQUEST_INVALID', 400);
|
|
201
|
+
}
|
|
202
|
+
const body = url.pathname === '/workspace.js' ? await (ownerScript ??= ownerBundle())
|
|
203
|
+
: await readFile(appRoot + (url.pathname === '/' ? 'web/owner-workspace.html' : url.pathname === '/styles.css' ? 'web/styles.css' : 'web/owner-workspace.css'));
|
|
204
|
+
return new Response(request.method === 'HEAD' ? null : body, {headers: {...securityHeaders,
|
|
205
|
+
'Content-Type': url.pathname.endsWith('.js') ? 'text/javascript' : url.pathname.endsWith('.css') ? 'text/css' : 'text/html; charset=utf-8'}});
|
|
206
|
+
}
|
|
207
|
+
const match = /^\/instances\/([a-f0-9]{64})(\/.*)$/.exec(url.pathname);
|
|
208
|
+
const target = match && targets.get(match[1]!);
|
|
209
|
+
if (!match || !target) return refused('WORKSPACE_TARGET_UNKNOWN', 404);
|
|
210
|
+
if (!target.context) return refused(target.view.unavailable ?? 'WORKSPACE_TARGET_UNAVAILABLE');
|
|
211
|
+
const path = match[2]!;
|
|
212
|
+
const agentControl = path === '/api/control' || path === '/api/control/commands' || /^\/api\/control\/receipts\/[a-f0-9-]+$/.test(path);
|
|
213
|
+
if (!frontRoute(target.view.mode, request.method, path) && !(agentControl && target.stored.controlToken)) return refused('WORKSPACE_ROUTE_REFUSED', 404);
|
|
214
|
+
const landing = path === '/' || path === '/index.html';
|
|
215
|
+
const stageFrame = path === '/stage-parts.html' || path === '/stage-interview.html';
|
|
216
|
+
if (stageFrame ? !stageFrameQuery(target.view.mode, url.search) : !landing && !!url.search) return refused('FRONT_QUERY_REFUSED', 400);
|
|
217
|
+
if (request.method !== 'GET' && request.method !== 'HEAD' && sentOrigin !== record.origin) return refused('WORKSPACE_SAME_ORIGIN_REQUIRED', 403);
|
|
218
|
+
if (path === '/api/live' && live.connections >= WORKSPACE_SOCKET_LIMIT) return refused('WORKSPACE_BUSY', 503);
|
|
219
|
+
if (activeStreams >= maximumUpstreamStreams) return refused('WORKSPACE_BUSY', 503);
|
|
220
|
+
const producerRequest = request.method === 'POST' && /^\/api\/(?:compare\/[ab]\/)?(?:rebuild|density-strip|bones-check|requirements|environment-check|readings|strip)(?:\/|$)/.test(path);
|
|
221
|
+
if (producerRequest && (producing || [...targets.values()].some(row => row.context?.busy()))) return refused('WORKSPACE_BUSY', 503);
|
|
222
|
+
if (producerRequest) producing = true;
|
|
223
|
+
activeStreams++;
|
|
224
|
+
let released = false;
|
|
225
|
+
const release = () => {if (!released) {released = true; activeStreams--;}};
|
|
226
|
+
try {
|
|
227
|
+
const normalized = new URL(request.url); normalized.pathname = path;
|
|
228
|
+
const inner = new Request(normalized, request);
|
|
229
|
+
const upgrade: UpgradableServer = {upgrade(_inner, details) {return server.upgrade(request, details);}};
|
|
230
|
+
const response = await target.context.handle(inner, Number(url.port), upgrade);
|
|
231
|
+
if (!response) {release(); return undefined;}
|
|
232
|
+
if ((path === '/api/review' || path === '/api/compare') && response.status === 409) target.view.unavailable = 'WORKSPACE_SOURCE_CHANGED';
|
|
233
|
+
if ((path === '/' || path === '/index.html') && response.headers.get('Content-Type')?.startsWith('text/html')) {
|
|
234
|
+
const policy = response.headers.get('Content-Security-Policy');
|
|
235
|
+
if (policy) response.headers.set('Content-Security-Policy', policy.replace("frame-ancestors 'none'", "frame-ancestors 'self'"));
|
|
236
|
+
}
|
|
237
|
+
return stream(response, request, release);
|
|
238
|
+
} catch (error) {release(); throw error;}
|
|
239
|
+
finally {if (producerRequest) producing = false;}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function stop() {
|
|
243
|
+
stopPromise ??= (async () => {
|
|
244
|
+
accepting = false;
|
|
245
|
+
await pending;
|
|
246
|
+
live.stop();
|
|
247
|
+
for (const target of targets.values()) target.context?.stop();
|
|
248
|
+
await rawStop?.(true);
|
|
249
|
+
const current = await readPrivate(join(directory, 'host.json'));
|
|
250
|
+
if (current && (current as WorkspaceRecord).incarnation === incarnation) await unlink(join(directory, 'host.json'));
|
|
251
|
+
})();
|
|
252
|
+
return stopPromise;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
const previous = await readPrivate(join(directory, 'targets.json'));
|
|
257
|
+
if (previous) {
|
|
258
|
+
for (const stored of parseRegistry(previous).targets) {
|
|
259
|
+
try {targets.set(stored.designation.key, await prepare(stored.designation));}
|
|
260
|
+
catch {
|
|
261
|
+
targets.set(stored.designation.key, {stored, context: null, check: null, view: {
|
|
262
|
+
key: stored.designation.key, contentHash: stored.designation.contentHash, title: stored.designation.inputs.input,
|
|
263
|
+
mode: stored.designation.inputs.compare ? 'compare' : 'single', animation: stored.designation.inputs.animation ?? null,
|
|
264
|
+
viewOnly: stored.designation.viewOnly, unavailable: 'WORKSPACE_SOURCE_CHANGED', entry: '',
|
|
265
|
+
}});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const server = Bun.serve({hostname: '127.0.0.1', port: options.port, websocket: live.websocket,
|
|
270
|
+
async fetch(request, server) {
|
|
271
|
+
try {return await route(request, server) as Response;}
|
|
272
|
+
catch (error) {
|
|
273
|
+
const message = error instanceof Error ? error.message : '';
|
|
274
|
+
if (message === 'FRONT_BODY_LIMIT') return refused('WORKSPACE_BODY_LIMIT', 413);
|
|
275
|
+
if (message === 'FRONT_BODY_TIMEOUT') return refused('WORKSPACE_BODY_TIMEOUT', 408);
|
|
276
|
+
if (message === 'FRONT_JSON_REQUIRED' || error instanceof SyntaxError) return refused('WORKSPACE_REQUEST_INVALID', 400);
|
|
277
|
+
return refused(/^WORKSPACE_[A-Z_]+$/.test(message) ? message : 'WORKSPACE_REQUEST_REFUSED');
|
|
278
|
+
}
|
|
279
|
+
}});
|
|
280
|
+
rawStop = server.stop.bind(server);
|
|
281
|
+
record = {schema: WORKSPACE_SCHEMA, incarnation, pid: process.pid, uid: process.getuid?.() ?? 0,
|
|
282
|
+
origin: `http://127.0.0.1:${server.port}`, installation: appRoot, fingerprint: options.fingerprint,
|
|
283
|
+
runtime: Bun.version, registrationCapability, ownerCapability};
|
|
284
|
+
await persist(targets);
|
|
285
|
+
await writePrivate(join(directory, 'host.json'), record);
|
|
286
|
+
return {record, live, stop};
|
|
287
|
+
} catch (error) {
|
|
288
|
+
await stop();
|
|
289
|
+
if ((error as NodeJS.ErrnoException).code === 'EADDRINUSE') throw workspaceError(`FRONT_PORT_BUSY: 127.0.0.1:${options.port} is held by another listener; use --direct (or set RIG_REVIEW_FRONT_PORT)`);
|
|
290
|
+
throw error;
|
|
291
|
+
}
|
|
292
|
+
}
|