@edjbarron/ux-guard 0.6.1 → 0.7.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,409 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { ConfigError } from './yaml.mjs';
3
+ import {
4
+ DEFAULT_REVIEW_PATHS,
5
+ adoptReview,
6
+ adoptionCommand,
7
+ evaluateReview,
8
+ loadReviewContext,
9
+ prepareCandidate,
10
+ } from './review-store.mjs';
11
+ import { LOOPBACK_HOST, startReviewServer } from './review-server.mjs';
12
+
13
+ export const REVIEW_AGENT_PROMPTS = Object.freeze([
14
+ 'Help me discover and review the important use cases in this repository. Populate every required definition field that repository evidence supports. If a field cannot be supported, mark the item as an incomplete draft, add a focused unresolved question, and never invent a goal. Open ux-guard’s local review experience, explain the proposals and drafts in plain language, and do not activate policy without my explicit approval.',
15
+ 'Continue my ux-guard use-case review.',
16
+ 'Open the ux-guard review app for this repository.',
17
+ 'Help me resolve the remaining unmapped workflows and exclusions. Do not approve or activate anything.',
18
+ ]);
19
+
20
+ export const REVIEW_HELP = `usage: ux-guard review [prepare|audit|adopt] [options]
21
+
22
+ Review proposed use cases in a local app bound to ${LOOPBACK_HOST}. Saving
23
+ records an unapproved review; it never changes active policy, baselines,
24
+ targets, waivers, or enforcement.
25
+
26
+ commands:
27
+ review open the local review app (default)
28
+ review --format json report review status without starting the app
29
+ review prepare validate an assessment draft and stamp it with
30
+ repository identity as an unapproved candidate
31
+ review audit assess the exact saved unapproved preview against an
32
+ explicit trusted base without adopting or enforcing it
33
+ review adopt write the owner-approved catalog; requires a saved,
34
+ current, conflict-free review and approval details
35
+
36
+ options:
37
+ --root <dir> repository root (default: current directory)
38
+ --candidate <path> candidate (default: ${DEFAULT_REVIEW_PATHS.candidate})
39
+ --review <path> review decisions (default: ${DEFAULT_REVIEW_PATHS.review})
40
+ --preview <path> generated preview (default: ${DEFAULT_REVIEW_PATHS.preview})
41
+ --draft <path> prepare input (default: ${DEFAULT_REVIEW_PATHS.draft})
42
+ --port <number> loopback port (default: any free port)
43
+ --no-open print the address instead of opening a browser
44
+ --format text|json human-readable or machine-readable output
45
+
46
+ audit options:
47
+ --base <ref> required trusted policy/baseline revision
48
+ --journey-report <path>
49
+ optional repository-local current evidence path
50
+ --visual-candidate <path>
51
+ optional repository-local current visual manifest
52
+ --format json|markdown
53
+ machine-readable audit or human review document
54
+
55
+ adopt options:
56
+ --reviewer <id> --reviewed-at <UTC> --rationale <text>
57
+ required record of the owner's explicit approval
58
+ --catalog <path> catalog path when no active policy names one
59
+ --replace-catalog-sha256 <hash>
60
+ confirm replacing exactly the current catalog
61
+ `;
62
+
63
+ // reviewCommand returns a promise because the default command keeps the local
64
+ // server running until the owner closes the review.
65
+ export async function reviewCommand(options, io, { openBrowser = openInBrowser, signals = process } = {}) {
66
+ const [, sub, extra] = options.positional;
67
+ if (extra) throw new ConfigError(`unexpected argument ${extra}`);
68
+ if (options.base) throw new ConfigError('review uses the working tree; do not pass --base');
69
+ if (options.format === 'markdown') throw new ConfigError('--format markdown is not valid with review; use text or json');
70
+ if (
71
+ options.strict ||
72
+ options.acceptGrowth ||
73
+ options.baseline ||
74
+ options.typescript ||
75
+ options.shards ||
76
+ options.visuals ||
77
+ options.candidateSha ||
78
+ options.journeyReport ||
79
+ options.visualCandidate
80
+ ) {
81
+ throw new ConfigError('review accepts only review options; run ux-guard review --help');
82
+ }
83
+ const paths = {
84
+ candidatePath: options.candidate ?? DEFAULT_REVIEW_PATHS.candidate,
85
+ reviewPath: options.review ?? DEFAULT_REVIEW_PATHS.review,
86
+ previewPath: options.preview ?? DEFAULT_REVIEW_PATHS.preview,
87
+ explicitCandidate: options.candidate !== null,
88
+ };
89
+ const approvals = [options.reviewer, options.reviewedAt, options.rationale];
90
+ if (sub === 'prepare') {
91
+ rejectOptions(options, ['review', 'preview', 'catalog', 'replaceCatalogSha256', 'port', 'noOpen'], 'review prepare');
92
+ if (approvals.some(Boolean)) throw new ConfigError('approval options are only valid with review adopt');
93
+ return prepare(options, paths, io);
94
+ }
95
+ if (sub === 'adopt') {
96
+ rejectOptions(options, ['draft', 'port', 'noOpen'], 'review adopt');
97
+ return adopt(options, paths, io);
98
+ }
99
+ if (sub !== undefined) throw new ConfigError(`unknown review command ${sub}`);
100
+ rejectOptions(options, ['draft', 'catalog', 'replaceCatalogSha256'], 'review');
101
+ if (approvals.some(Boolean)) throw new ConfigError('approval options are only valid with review adopt');
102
+ if (options.format === 'json') rejectOptions(options, ['port', 'noOpen'], 'review --format json');
103
+
104
+ const context = loadReviewContext(options.root, paths);
105
+ if (context.status === 'no-candidate') {
106
+ writeNoCandidate(context, options.format, io);
107
+ return 0;
108
+ }
109
+ const state = evaluateReview(context);
110
+ if (options.format === 'json') {
111
+ io.out.write(`${JSON.stringify(statusDocument(context, state), null, 2)}\n`);
112
+ return 0;
113
+ }
114
+
115
+ const server = await startReviewServer(context, {
116
+ port: options.port ?? 0,
117
+ log: (message) => io.err.write(`${message}\n`),
118
+ });
119
+ const stop = () => server.close();
120
+ signals.once?.('SIGINT', stop);
121
+ signals.once?.('SIGTERM', stop);
122
+ io.out.write(
123
+ [
124
+ 'ux-guard review',
125
+ '',
126
+ ` Candidate ${context.candidatePath} (${identityLabel(context.identity)})`,
127
+ ` Review decisions ${context.reviewPath} (${context.reviewSha256 ? `saved revision ${context.review.revision}` : 'not saved yet'})`,
128
+ ` Catalog ${state.catalog.path}${state.catalog.exists ? '' : ' (not created yet)'}`,
129
+ ` Definitions ${state.summary.definitions.completeProposals} complete proposals, ${state.summary.definitions.incompleteDrafts} incomplete drafts`,
130
+ ` Still to decide ${state.summary.unresolvedDecisions} decisions, ${state.summary.blockingIssues} blocking issues`,
131
+ '',
132
+ ` Open ${server.url}`,
133
+ '',
134
+ ` Bound to ${server.address} only, with no external assets or telemetry. The link holds a private`,
135
+ ' session token; do not share it. Saving records an unapproved review. Nothing is approved,',
136
+ ' adopted, checked in, or enforced from the app.',
137
+ '',
138
+ ' Press Ctrl+C or choose Close review in the app to stop.',
139
+ '',
140
+ ].join('\n'),
141
+ );
142
+ if (!options.noOpen && !process.env.CI) openBrowser(server.url);
143
+ await server.closed;
144
+ signals.off?.('SIGINT', stop);
145
+ signals.off?.('SIGTERM', stop);
146
+ io.out.write('ux-guard review: closed. Saved decisions remain unapproved.\n');
147
+ return 0;
148
+ }
149
+
150
+ function rejectOptions(options, names, command) {
151
+ const flags = {
152
+ review: '--review',
153
+ preview: '--preview',
154
+ draft: '--draft',
155
+ catalog: '--catalog',
156
+ replaceCatalogSha256: '--replace-catalog-sha256',
157
+ port: '--port',
158
+ noOpen: '--no-open',
159
+ };
160
+ for (const name of names) {
161
+ if (options[name] !== null && options[name] !== false) {
162
+ throw new ConfigError(`${flags[name]} is not valid with ${command}`);
163
+ }
164
+ }
165
+ }
166
+
167
+ function identityLabel(identity) {
168
+ return {
169
+ current: 'current',
170
+ moved: 'assessed files unchanged since the assessment commit',
171
+ stale: 'stale: assessed files changed',
172
+ unverified: 'repository identity unverified',
173
+ }[identity.status];
174
+ }
175
+
176
+ function statusDocument(context, state) {
177
+ return {
178
+ kind: 'ux-guard-review-result',
179
+ version: 1,
180
+ command: 'review',
181
+ status: state.summary.readyForOwnerApproval ? 'ready-for-owner-approval' : 'review-in-progress',
182
+ exitCode: 0,
183
+ paths: {
184
+ candidate: context.candidatePath,
185
+ review: context.reviewPath,
186
+ preview: context.previewPath,
187
+ catalog: state.catalog.path,
188
+ },
189
+ review: { saved: context.reviewSha256 !== null, revision: context.review.revision },
190
+ identity: state.identity,
191
+ summary: state.summary,
192
+ unresolved: state.unresolved,
193
+ issues: state.issues,
194
+ catalog: {
195
+ path: state.catalog.path,
196
+ exists: state.catalog.exists,
197
+ activeSha256: state.catalog.activeSha256,
198
+ inventory: state.catalog.inventory,
199
+ entries: state.catalog.entries,
200
+ unbound: state.catalog.unbound,
201
+ omitted: state.catalog.omitted,
202
+ diff: state.catalog.diff,
203
+ },
204
+ adoptCommand: adoptionCommand(context, state),
205
+ safety: {
206
+ approved: false,
207
+ policyChanged: false,
208
+ filesWritten: [],
209
+ },
210
+ };
211
+ }
212
+
213
+ function writeNoCandidate(context, format, io) {
214
+ const prepareStep = 'npx ux-guard review prepare';
215
+ const nextAction = context.draftPresent
216
+ ? `A draft exists at ${DEFAULT_REVIEW_PATHS.draft}. Validate and stamp it with: ${prepareStep}`
217
+ : 'Ask your agent to draft the assessment with the prompt below, or write a draft by hand using docs/use-case-review.md in the installed package, then run: ' +
218
+ prepareStep;
219
+ if (format === 'json') {
220
+ io.out.write(
221
+ `${JSON.stringify(
222
+ {
223
+ kind: 'ux-guard-review-result',
224
+ version: 1,
225
+ command: 'review',
226
+ status: 'no-candidate',
227
+ exitCode: 0,
228
+ candidate: { path: context.candidatePath, present: false },
229
+ draft: { path: DEFAULT_REVIEW_PATHS.draft, present: context.draftPresent },
230
+ missing: [
231
+ 'navigation surfaces and workflows discovered in this repository',
232
+ 'proposed use cases grouped by user outcome',
233
+ 'proposed mappings and exclusions with rationale',
234
+ ],
235
+ agentPrompt: REVIEW_AGENT_PROMPTS[0],
236
+ nextAction,
237
+ safety: { approved: false, policyChanged: false, filesWritten: [] },
238
+ },
239
+ null,
240
+ 2,
241
+ )}\n`,
242
+ );
243
+ return;
244
+ }
245
+ const lines = [
246
+ 'ux-guard review',
247
+ '',
248
+ `No use-case candidate was found at ${context.candidatePath}.`,
249
+ '',
250
+ 'The review app needs an assessment of this repository: its navigation surfaces and',
251
+ 'workflows, proposed use cases grouped by user outcome, and proposed mappings or',
252
+ 'exclusions. ux-guard does not guess these; an agent or a person drafts them, and',
253
+ 'ux-guard validates the draft and stamps it with repository identity.',
254
+ '',
255
+ ];
256
+ if (context.draftPresent) {
257
+ lines.push('Next safe action', ` A draft exists at ${DEFAULT_REVIEW_PATHS.draft}. Validate and stamp it with:`, ` ${prepareStep}`);
258
+ } else {
259
+ lines.push(
260
+ 'Next safe action',
261
+ ' Ask your agent (copy this prompt):',
262
+ '',
263
+ ` ${REVIEW_AGENT_PROMPTS[0]}`,
264
+ '',
265
+ ` Or write ${DEFAULT_REVIEW_PATHS.draft} by hand using docs/use-case-review.md in the`,
266
+ ' installed package, then run:',
267
+ ` ${prepareStep}`,
268
+ );
269
+ }
270
+ lines.push('', 'Nothing was written.');
271
+ io.out.write(`${lines.join('\n')}\n`);
272
+ }
273
+
274
+ function prepare(options, paths, io) {
275
+ const draftPath = options.draft ?? DEFAULT_REVIEW_PATHS.draft;
276
+ const result = prepareCandidate(options.root, { draftPath, candidatePath: paths.candidatePath });
277
+ const { candidate } = result;
278
+ if (options.format === 'json') {
279
+ io.out.write(
280
+ `${JSON.stringify(
281
+ {
282
+ kind: 'ux-guard-review-prepare-result',
283
+ version: 1,
284
+ command: 'review prepare',
285
+ status: 'unapproved',
286
+ exitCode: 0,
287
+ draft: draftPath,
288
+ candidate: paths.candidatePath,
289
+ counts: {
290
+ outcomes: candidate.outcomes.length,
291
+ proposals: candidate.proposals.length,
292
+ completeProposals: result.completeProposals.length,
293
+ incompleteDrafts: result.incompleteDrafts.length,
294
+ surfaces: candidate.surfaces.length,
295
+ workflows: candidate.workflows.length,
296
+ inputs: result.inputs,
297
+ },
298
+ identity: { commit: candidate.source.commit, rootCommits: candidate.source.repository.rootCommits },
299
+ completeProposals: result.completeProposals,
300
+ incompleteDrafts: result.incompleteDrafts,
301
+ warning: result.allDefinitionsIncomplete
302
+ ? 'Every discovered use-case definition is an incomplete draft; none can be approved as proposed.'
303
+ : null,
304
+ notAssessed: result.notAssessed,
305
+ safety: { approved: false, policyChanged: false, filesWritten: [paths.candidatePath] },
306
+ },
307
+ null,
308
+ 2,
309
+ )}\n`,
310
+ );
311
+ return 0;
312
+ }
313
+ const lines = [
314
+ 'ux-guard review prepare',
315
+ '',
316
+ ` Stamped ${paths.candidatePath} from ${draftPath}.`,
317
+ ` ${result.completeProposals.length} complete proposal${result.completeProposals.length === 1 ? '' : 's'}, ${result.incompleteDrafts.length} incomplete draft${result.incompleteDrafts.length === 1 ? '' : 's'}, ${candidate.surfaces.length} surfaces, ${candidate.workflows.length} workflows, ${result.inputs} assessed input files.`,
318
+ ` Repository identity: ${candidate.source.commit ? `commit ${candidate.source.commit.slice(0, 12)}` : 'unavailable (no Git history)'}.`,
319
+ ];
320
+ if (result.allDefinitionsIncomplete) {
321
+ lines.push(
322
+ ' WARNING: Every discovered use-case definition is an incomplete draft; none can be approved as proposed.',
323
+ );
324
+ }
325
+ if (result.notAssessed.length) {
326
+ lines.push(
327
+ ` ${result.notAssessed.length} navigation surfaces were found in source but not in the draft; they will appear as unresolved:`,
328
+ ...result.notAssessed.map(({ id, route }) => ` - ${id} ${route}`),
329
+ );
330
+ }
331
+ if (result.incompleteDrafts.length) {
332
+ lines.push(
333
+ ` ${result.incompleteDrafts.length} incomplete draft${result.incompleteDrafts.length === 1 ? '' : 's'} ${
334
+ result.incompleteDrafts.length === 1 ? 'needs' : 'need'
335
+ } definition fields before acceptance:`,
336
+ ...result.incompleteDrafts.map(
337
+ ({ id, missingLabels }) => ` - ${id}: ${missingLabels.join(', ')}`,
338
+ ),
339
+ ' Focused unresolved questions were added. Use only repository evidence; never invent missing goals.',
340
+ );
341
+ }
342
+ lines.push('', ' Status: unapproved. Nothing else was written.', '', 'Next safe action', ' npx ux-guard review');
343
+ io.out.write(`${lines.join('\n')}\n`);
344
+ return 0;
345
+ }
346
+
347
+ function adopt(options, paths, io) {
348
+ const context = loadReviewContext(options.root, { ...paths, explicitCandidate: true });
349
+ const record = adoptReview(context, {
350
+ reviewer: options.reviewer,
351
+ reviewedAt: options.reviewedAt,
352
+ rationale: options.rationale,
353
+ catalogPath: options.catalog,
354
+ replaceSha256: options.replaceCatalogSha256,
355
+ });
356
+ if (options.format === 'json') {
357
+ io.out.write(`${JSON.stringify(record, null, 2)}\n`);
358
+ return 0;
359
+ }
360
+ io.out.write(
361
+ [
362
+ 'ux-guard review adopt',
363
+ '',
364
+ ` ${record.catalog.previousSha256 ? 'Replaced' : 'Created'} ${record.catalog.path} with ${record.catalog.useCases} use cases (inventory ${record.catalog.inventory}).`,
365
+ ` Approved by ${record.approval.reviewer} at ${record.approval.reviewedAt}.`,
366
+ record.unresolved.length
367
+ ? ` ${record.unresolved.length} items are still unresolved and remain unknown; they were not reported as covered.`
368
+ : ' No unresolved review items remain.',
369
+ ' Configuration, baselines, targets, waivers, and enforcement were not changed.',
370
+ '',
371
+ 'Next safe action',
372
+ ` ${record.nextAction}`,
373
+ '',
374
+ ].join('\n'),
375
+ );
376
+ return 0;
377
+ }
378
+
379
+ export function reviewErrorGuidance(message) {
380
+ if (message.includes('does not exist') && message.includes('candidate')) {
381
+ return 'Next: run ux-guard review without --candidate for guidance, or correct the candidate path.';
382
+ }
383
+ if (message.includes('stale')) {
384
+ return 'Next: refresh the assessment draft, run ux-guard review prepare with a new candidate path, and review it.';
385
+ }
386
+ if (message.includes('different candidate')) {
387
+ return 'Next: reopen the review with its original candidate, or pass a new --review path to start a fresh review.';
388
+ }
389
+ if (message.includes('draft')) {
390
+ return 'Next: correct the draft (see docs/use-case-review.md in the installed package) and run ux-guard review prepare again.';
391
+ }
392
+ return 'Next: run ux-guard review --help, correct the reported input, and retry. The review never changes active policy on its own.';
393
+ }
394
+
395
+ function openInBrowser(url) {
396
+ const [command, args] =
397
+ process.platform === 'darwin'
398
+ ? ['open', [url]]
399
+ : process.platform === 'win32'
400
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
401
+ : ['xdg-open', [url]];
402
+ try {
403
+ const child = spawn(command, args, { stdio: 'ignore', detached: true, shell: false });
404
+ child.on('error', () => {});
405
+ child.unref();
406
+ } catch {
407
+ // The printed address remains the fallback.
408
+ }
409
+ }
@@ -0,0 +1,233 @@
1
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { createServer } from 'node:http';
4
+ import { ConfigError } from './yaml.mjs';
5
+ import {
6
+ ReviewConflictError,
7
+ adoptionCommand,
8
+ evaluateReview,
9
+ parseReviewDraft,
10
+ refreshContext,
11
+ saveReview,
12
+ } from './review-store.mjs';
13
+
14
+ export const LOOPBACK_HOST = '127.0.0.1';
15
+ const MAX_BODY_BYTES = 4 * 1024 * 1024;
16
+ const ASSETS = {
17
+ '/': ['index.html', 'text/html; charset=utf-8'],
18
+ '/app.js': ['app.js', 'text/javascript; charset=utf-8'],
19
+ '/app.css': ['app.css', 'text/css; charset=utf-8'],
20
+ };
21
+ const SECURITY_HEADERS = {
22
+ 'Content-Security-Policy':
23
+ "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; " +
24
+ "base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
25
+ 'Cache-Control': 'no-store',
26
+ 'Cross-Origin-Opener-Policy': 'same-origin',
27
+ 'Cross-Origin-Resource-Policy': 'same-origin',
28
+ 'Referrer-Policy': 'no-referrer',
29
+ 'X-Content-Type-Options': 'nosniff',
30
+ 'X-Frame-Options': 'DENY',
31
+ };
32
+
33
+ // startReviewServer serves the review app on the loopback interface only.
34
+ // Every API call needs the per-session token, a loopback Host header, and a
35
+ // same-origin request, which blocks other local sites and DNS rebinding.
36
+ export async function startReviewServer(context, { port = 0, token = randomBytes(32).toString('hex'), log = () => {} } = {}) {
37
+ if (!Number.isSafeInteger(port) || port < 0 || port > 65535) {
38
+ throw new ConfigError('--port must be an integer from 0 to 65535');
39
+ }
40
+ const assets = Object.fromEntries(
41
+ Object.entries(ASSETS).map(([path, [file, type]]) => [
42
+ path,
43
+ { type, body: readFileSync(new URL(`./review-app/${file}`, import.meta.url)) },
44
+ ]),
45
+ );
46
+ const expectedToken = Buffer.from(token, 'utf8');
47
+ let origin = '';
48
+ let allowedHosts = new Set();
49
+ let allowedOrigins = new Set();
50
+ let resolveClosed;
51
+ const closed = new Promise((resolve) => {
52
+ resolveClosed = resolve;
53
+ });
54
+
55
+ const server = createServer(async (request, response) => {
56
+ try {
57
+ await handle(request, response);
58
+ } catch (error) {
59
+ if (error instanceof ReviewConflictError) send(response, 409, { error: error.message });
60
+ else if (error instanceof ConfigError) send(response, 400, { error: error.message });
61
+ else if (error instanceof RequestError) send(response, error.status, { error: error.message });
62
+ else {
63
+ log(`ux-guard review: internal error: ${error?.message ?? error}`);
64
+ send(response, 500, { error: 'internal error; see the terminal running ux-guard review' });
65
+ }
66
+ }
67
+ });
68
+ server.requestTimeout = 30_000;
69
+ server.headersTimeout = 10_000;
70
+ server.on('close', () => resolveClosed());
71
+
72
+ async function handle(request, response) {
73
+ if (!allowedHosts.has(request.headers.host ?? '')) {
74
+ throw new RequestError(403, 'requests must use the loopback review address');
75
+ }
76
+ const { pathname } = new URL(request.url ?? '/', origin);
77
+ const asset = assets[pathname];
78
+ if (asset) {
79
+ if (request.method !== 'GET' && request.method !== 'HEAD') throw new RequestError(405, 'method not allowed');
80
+ response.writeHead(200, { ...SECURITY_HEADERS, 'Content-Type': asset.type, 'Content-Length': asset.body.length });
81
+ response.end(request.method === 'HEAD' ? undefined : asset.body);
82
+ return;
83
+ }
84
+ if (!pathname.startsWith('/api/')) throw new RequestError(404, 'not found');
85
+ authorize(request);
86
+ if (pathname === '/api/state' && request.method === 'GET') {
87
+ refreshContext(context);
88
+ send(response, 200, payload(evaluateReview(context)));
89
+ return;
90
+ }
91
+ if (request.method !== 'POST') throw new RequestError(405, 'method not allowed');
92
+ if (pathname === '/api/evaluate') {
93
+ const body = await readJson(request);
94
+ refreshContext(context);
95
+ send(response, 200, payload(evaluateReview(context, parseReviewDraft(context, body.review))));
96
+ return;
97
+ }
98
+ if (pathname === '/api/save') {
99
+ const body = await readJson(request);
100
+ refreshContext(context);
101
+ const saved = saveReview(context, body.review);
102
+ send(response, 200, {
103
+ ...payload(saved.state),
104
+ saved: { revision: saved.revision, savedAt: new Date().toISOString(), path: context.reviewPath },
105
+ });
106
+ return;
107
+ }
108
+ if (pathname === '/api/close') {
109
+ await readJson(request);
110
+ send(response, 200, { closed: true });
111
+ setImmediate(() => server.close());
112
+ server.closeIdleConnections?.();
113
+ return;
114
+ }
115
+ throw new RequestError(404, 'not found');
116
+ }
117
+
118
+ function authorize(request) {
119
+ const supplied = Buffer.from(String(request.headers['x-ux-guard-token'] ?? ''), 'utf8');
120
+ if (supplied.length !== expectedToken.length || !timingSafeEqual(supplied, expectedToken)) {
121
+ throw new RequestError(401, 'missing or invalid review session token');
122
+ }
123
+ const requestOrigin = request.headers.origin;
124
+ if (requestOrigin !== undefined && !allowedOrigins.has(requestOrigin)) {
125
+ throw new RequestError(403, 'cross-origin requests are not allowed');
126
+ }
127
+ const site = request.headers['sec-fetch-site'];
128
+ if (site !== undefined && site !== 'same-origin' && site !== 'none') {
129
+ throw new RequestError(403, 'cross-site requests are not allowed');
130
+ }
131
+ }
132
+
133
+ function payload(state) {
134
+ return {
135
+ paths: {
136
+ candidate: context.candidatePath,
137
+ review: context.reviewPath,
138
+ preview: context.previewPath,
139
+ catalog: state.catalog.path,
140
+ },
141
+ review: context.review,
142
+ saved: context.reviewSha256 !== null,
143
+ configured: context.configured,
144
+ adoptCommand: adoptionCommand(context, state),
145
+ state,
146
+ };
147
+ }
148
+
149
+ await new Promise((resolve, reject) => {
150
+ server.once('error', reject);
151
+ server.listen({ host: LOOPBACK_HOST, port, exclusive: true }, () => {
152
+ server.off('error', reject);
153
+ resolve();
154
+ });
155
+ });
156
+ const address = server.address();
157
+ if (!address || typeof address === 'string' || address.address !== LOOPBACK_HOST) {
158
+ server.close();
159
+ throw new ConfigError('review server did not bind to the loopback interface');
160
+ }
161
+ origin = `http://${LOOPBACK_HOST}:${address.port}`;
162
+ allowedHosts = new Set([`${LOOPBACK_HOST}:${address.port}`, `localhost:${address.port}`]);
163
+ allowedOrigins = new Set([origin, `http://localhost:${address.port}`]);
164
+ return {
165
+ address: address.address,
166
+ port: address.port,
167
+ origin,
168
+ url: `${origin}/#token=${token}`,
169
+ token,
170
+ closed,
171
+ close: () =>
172
+ new Promise((resolve) => {
173
+ server.close(() => resolve());
174
+ server.closeAllConnections?.();
175
+ }),
176
+ };
177
+ }
178
+
179
+ class RequestError extends Error {
180
+ constructor(status, message) {
181
+ super(message);
182
+ this.status = status;
183
+ }
184
+ }
185
+
186
+ function send(response, status, body) {
187
+ if (response.headersSent) {
188
+ response.end();
189
+ return;
190
+ }
191
+ const text = JSON.stringify(body);
192
+ response.writeHead(status, {
193
+ ...SECURITY_HEADERS,
194
+ 'Content-Type': 'application/json; charset=utf-8',
195
+ 'Content-Length': Buffer.byteLength(text),
196
+ });
197
+ response.end(text);
198
+ }
199
+
200
+ // readJson drains an oversized body before rejecting it so the client receives
201
+ // the 413 instead of a reset; a body far past the limit is cut off.
202
+ function readJson(request) {
203
+ const type = String(request.headers['content-type'] ?? '');
204
+ if (!/^application\/json(?:;|$)/i.test(type)) {
205
+ request.resume();
206
+ return Promise.reject(new RequestError(415, 'requests must be application/json'));
207
+ }
208
+ return new Promise((resolve, reject) => {
209
+ const chunks = [];
210
+ let size = 0;
211
+ let tooLarge = Number(request.headers['content-length'] ?? 0) > MAX_BODY_BYTES;
212
+ request.on('data', (chunk) => {
213
+ size += chunk.length;
214
+ if (size > MAX_BODY_BYTES) tooLarge = true;
215
+ if (size > MAX_BODY_BYTES * 4) request.destroy();
216
+ if (!tooLarge) chunks.push(chunk);
217
+ });
218
+ request.on('error', reject);
219
+ request.on('end', () => {
220
+ if (tooLarge) {
221
+ reject(new RequestError(413, 'request body is too large'));
222
+ return;
223
+ }
224
+ try {
225
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
226
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('not an object');
227
+ resolve(value);
228
+ } catch {
229
+ reject(new RequestError(400, 'request body must be a JSON object'));
230
+ }
231
+ });
232
+ });
233
+ }