rtl-analyzer 0.2.0 → 0.4.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 +90 -56
- package/dist/cli.js +18 -1
- package/dist/codemod.js +50 -12
- package/dist/companion-security.js +2 -0
- package/dist/contextual-preview-bridge.js +118 -0
- package/dist/contextual-preview.js +74 -0
- package/dist/controlled-apply.js +222 -0
- package/dist/css-configured-proposal.js +98 -0
- package/dist/css-directional.js +60 -0
- package/dist/css-icons.js +51 -0
- package/dist/css-spacing.js +65 -0
- package/dist/dashboard-batch-review.js +37 -0
- package/dist/dashboard-client.js +73 -50
- package/dist/dashboard-contextual-preview.js +127 -0
- package/dist/dashboard-data.js +4 -4
- package/dist/dashboard-embedded-preview.js +202 -0
- package/dist/dashboard-html.js +13 -10
- package/dist/dashboard-operation-flow.js +47 -0
- package/dist/dashboard-review-details.js +175 -0
- package/dist/dashboard-review-navigation.js +19 -0
- package/dist/dashboard-review-workflow.js +219 -0
- package/dist/dashboard-themes.js +34 -0
- package/dist/directional-properties.js +53 -0
- package/dist/discovery.js +1 -2
- package/dist/eligibility.js +8 -8
- package/dist/evidence-store.js +110 -0
- package/dist/example-preview-mappings.js +98 -0
- package/dist/manual-change-store.js +27 -0
- package/dist/migration-lifecycle.js +19 -0
- package/dist/original-preview-runtime.js +78 -0
- package/dist/output-path.js +65 -0
- package/dist/page-navigation.js +17 -0
- package/dist/policy-validation.js +7 -4
- package/dist/preview-cli.js +22 -0
- package/dist/preview-companion.js +649 -0
- package/dist/preview-configuration.js +171 -0
- package/dist/preview-runtime.js +102 -0
- package/dist/project-configuration.js +48 -0
- package/dist/project-root.js +12 -0
- package/dist/react-inline.js +65 -0
- package/dist/report-publisher.js +4 -7
- package/dist/review-approval.js +9 -0
- package/dist/review-session.js +211 -56
- package/dist/review-store.js +175 -0
- package/dist/review-workflow.js +820 -0
- package/dist/rules.js +27 -17
- package/dist/runtime-process.js +35 -0
- package/dist/scan-history.js +35 -0
- package/dist/scan-manifest-store.js +26 -0
- package/dist/scan.js +55 -4
- package/dist/scoped-direction-evidence.js +117 -0
- package/dist/serialization.js +1 -0
- package/dist/source-context.js +93 -0
- package/dist/source-snippets.js +3 -3
- package/dist/standalone-cli.js +14 -1
- package/dist/tailwind.js +3 -1
- package/dist/transformations.js +34 -0
- package/dist/validation.js +75 -0
- package/dist/workflow-validation.js +46 -0
- package/package.json +17 -8
|
@@ -0,0 +1,649 @@
|
|
|
1
|
+
import { initializeOriginalPreview, signalOwnedOriginalPreviews, stopOwnedOriginalPreviews } from './original-preview-runtime.js';
|
|
2
|
+
import { loadPreviewConfiguration } from './preview-configuration.js';
|
|
3
|
+
import { contextualPreview } from './contextual-preview.js';
|
|
4
|
+
import { verifiedSourceTransition, reconcileSourceRuntimes, reconcileSelectedFinding } from './source-context.js';
|
|
5
|
+
import { scan } from './scan.js';
|
|
6
|
+
import { directionRequirement, proposeTransformation, sameSupportedPatch } from './transformations.js';
|
|
7
|
+
import { toSchemaV2Presentation } from './presentation-adapter.js';
|
|
8
|
+
import { toDashboardData } from './dashboard-data.js';
|
|
9
|
+
import { extractSourceSnippets } from './source-snippets.js';
|
|
10
|
+
import { ReviewWorkflowStore } from './review-workflow.js';
|
|
11
|
+
import { createServer } from 'node:http';
|
|
12
|
+
import { homedir } from 'node:os';
|
|
13
|
+
import { join, relative, resolve, sep } from 'node:path';
|
|
14
|
+
import { createHash } from 'node:crypto';
|
|
15
|
+
import { lstat, readFile } from 'node:fs/promises';
|
|
16
|
+
import { PREVIEW_COMPANION_ORIGIN, previewManifest, validatedPreviewRoute } from './preview-manifest.js';
|
|
17
|
+
import { applyReviewPatch, createReviewSession, disposeReviewSession, signalAllCandidateRuntimes, stopAllCandidateRuntimes, reviewSessionComparison, reviewSessionDiff, startCandidateRuntime, stopCandidateRuntime, validateProjectSourcePath, validateReviewIdentity, REVIEW_SOURCE } from './review-session.js';
|
|
18
|
+
import { DEFAULT_REVIEW_STORE_PATH, ReviewRecordStore } from './review-store.js';
|
|
19
|
+
import { DEFAULT_EVIDENCE_STORE_PATH, EvidenceSnapshotStore } from './evidence-store.js';
|
|
20
|
+
import { ApplyAuditStore, ControlledApplyService } from './controlled-apply.js';
|
|
21
|
+
import { DASHBOARD_ORIGIN, isAllowedDashboardOrigin } from './companion-security.js';
|
|
22
|
+
import { analyzeBidiIsolation } from './codemod.js';
|
|
23
|
+
import { recoverCandidateSessionId } from './review-approval.js';
|
|
24
|
+
import { validateCandidate } from './validation.js';
|
|
25
|
+
import { projectLifecycle } from './migration-lifecycle.js';
|
|
26
|
+
import { ManualChangeStore } from './manual-change-store.js';
|
|
27
|
+
import { ScanManifestStore } from './scan-manifest-store.js';
|
|
28
|
+
import { resolveTrustedProjectRoot } from './project-root.js';
|
|
29
|
+
const host = '127.0.0.1';
|
|
30
|
+
const port = Number(process.env.RTL_PREVIEW_PORT ?? 4318);
|
|
31
|
+
const applicationOrigin = 'http://127.0.0.1:4200';
|
|
32
|
+
const sessions = new Map();
|
|
33
|
+
const reviewStore = new ReviewRecordStore();
|
|
34
|
+
await reviewStore.load();
|
|
35
|
+
const evidenceStore = new EvidenceSnapshotStore();
|
|
36
|
+
await evidenceStore.load();
|
|
37
|
+
const projectRoot = await resolveTrustedProjectRoot();
|
|
38
|
+
const cwd = () => projectRoot;
|
|
39
|
+
const applyService = new ControlledApplyService(projectRoot);
|
|
40
|
+
const auditStore = new ApplyAuditStore(process.env.RTL_AUDIT_STORE_PATH || join(homedir(), '.rtl-migration-analyzer', 'apply-audit-v1.json'));
|
|
41
|
+
const workflowStore = new ReviewWorkflowStore(projectRoot, join(process.env.RTL_APPLY_BACKUP_ROOT || join(homedir(), '.rtl-migration-analyzer'), 'review-workflows-v1.json'), applyService, applicationOrigin);
|
|
42
|
+
await workflowStore.load();
|
|
43
|
+
const validations = new Map();
|
|
44
|
+
const manualChangeStore = new ManualChangeStore();
|
|
45
|
+
await manualChangeStore.load();
|
|
46
|
+
const scanManifestStore = new ScanManifestStore();
|
|
47
|
+
await scanManifestStore.load();
|
|
48
|
+
const screenshotRoot = join(homedir(), '.rtl-migration-analyzer');
|
|
49
|
+
const screenshotPath = (reference) => {
|
|
50
|
+
if (reference.length > 1000 || reference.startsWith('/') || reference.split(/[\\/]/).includes('..'))
|
|
51
|
+
throw new Error('INVALID_SCREENSHOT_REFERENCE');
|
|
52
|
+
const target = resolve(screenshotRoot, reference);
|
|
53
|
+
const rel = relative(screenshotRoot, target);
|
|
54
|
+
if (rel === '..' || rel.startsWith('..' + sep) || resolve(target) !== target)
|
|
55
|
+
throw new Error('INVALID_SCREENSHOT_REFERENCE');
|
|
56
|
+
return target;
|
|
57
|
+
};
|
|
58
|
+
async function assertScreenshotFile(path, expectedDigest) {
|
|
59
|
+
const stat = await lstat(path);
|
|
60
|
+
if (!stat.isFile())
|
|
61
|
+
throw new Error('SCREENSHOT_NOT_REGULAR_FILE');
|
|
62
|
+
const bytes = await readFile(path);
|
|
63
|
+
if (createHash('sha256').update(bytes).digest('hex') !== expectedDigest)
|
|
64
|
+
throw new Error('SCREENSHOT_INTEGRITY_MISMATCH');
|
|
65
|
+
return bytes;
|
|
66
|
+
}
|
|
67
|
+
function normalizeBidiFinding(input, source) { if (input.id !== 'RTL.BIDI.ISOLATION:741d2ce2aec3a86cf2db37ea' || input.path !== 'apps/invoicing/src/components/InvoiceTable.tsx')
|
|
68
|
+
throw new Error('UNSUPPORTED_FINDING_IDENTITY'); if (input.range?.start?.offset !== undefined)
|
|
69
|
+
return input; const line = Number(input.line); const column = Number(input.column); if (!Number.isInteger(line) || !Number.isInteger(column) || line < 1 || column < 1)
|
|
70
|
+
throw new Error('INVALID_FINDING_RANGE'); const lines = source.split(/\r?\n/); const offset = lines.slice(0, line - 1).reduce((n, value) => n + value.length + 1, 0) + column - 1; if (source.slice(offset, offset + 6) !== '{i.id}')
|
|
71
|
+
throw new Error('SOURCE_RANGE_MISMATCH'); return { ...input, range: { start: { offset, line, column }, end: { offset: offset + 6, line, column: column + 6 } }, original: '{i.id}' }; }
|
|
72
|
+
async function previewCapabilities() { try {
|
|
73
|
+
const configuration = await loadPreviewConfiguration(projectRoot), configured = Object.keys(configuration.applications), applications = configured.length ? configured : ['invoicing', 'procurement'];
|
|
74
|
+
return { application: applications[0], applications, applicationOrigin: configuration.applications[applications[0]]?.originalOrigin ?? applicationOrigin, previewConfigurationError: null };
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
return { application: null, applications: [], applicationOrigin: null, previewConfigurationError: error instanceof Error ? error.message : 'PREVIEW_CONFIGURATION_INVALID' };
|
|
78
|
+
} }
|
|
79
|
+
function send(response, status, body) { response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'access-control-allow-origin': DASHBOARD_ORIGIN, 'vary': 'Origin' }); response.end(JSON.stringify(body)); }
|
|
80
|
+
async function body(request) { let value = ''; for await (const chunk of request)
|
|
81
|
+
value += chunk; if (value.length > 100_000)
|
|
82
|
+
throw new Error('REQUEST_TOO_LARGE'); return JSON.parse(value || '{}'); }
|
|
83
|
+
function requestUrl(request) { return new URL(request.url ?? '/', PREVIEW_COMPANION_ORIGIN); }
|
|
84
|
+
const server = createServer(async (request, response) => {
|
|
85
|
+
const url = requestUrl(request);
|
|
86
|
+
if (shuttingDown)
|
|
87
|
+
return send(response, 503, { error: 'COMPANION_SHUTTING_DOWN' });
|
|
88
|
+
if (request.method === 'OPTIONS') {
|
|
89
|
+
if (!isAllowedDashboardOrigin(request.headers.origin))
|
|
90
|
+
return send(response, 403, { error: 'ORIGIN_NOT_ALLOWED' });
|
|
91
|
+
response.writeHead(204, { 'access-control-allow-origin': DASHBOARD_ORIGIN, 'access-control-allow-methods': 'GET,POST,OPTIONS', 'access-control-allow-headers': 'content-type', 'access-control-max-age': '300', vary: 'Origin' });
|
|
92
|
+
return response.end();
|
|
93
|
+
}
|
|
94
|
+
const isReviewWrite = url.pathname === '/contextual-preview/original' || url.pathname.startsWith('/review/workflows') || url.pathname === '/review/sessions' || url.pathname === '/review/records' || url.pathname === '/review/decisions' || url.pathname === '/review/evidence' || url.pathname === '/review/manual-changes' || url.pathname === '/review/rescan' || url.pathname === '/review/apply' || url.pathname === '/review/rollback' || url.pathname === '/review/codemod/analyze' || /^\/review\/sessions\/[^/]+\/(patch|cleanup|runtime\/(start|stop)|codemod\/apply|validate|validation\/archive)$/.test(url.pathname);
|
|
95
|
+
const dashboardRequest = isAllowedDashboardOrigin(request.headers.origin) || (!request.headers.origin && request.headers.referer?.startsWith(`${DASHBOARD_ORIGIN}/`));
|
|
96
|
+
if (isReviewWrite && request.method === 'POST' && !dashboardRequest)
|
|
97
|
+
return send(response, 403, { error: 'ORIGIN_NOT_ALLOWED' });
|
|
98
|
+
if (request.method !== 'GET' && !(isReviewWrite && request.method === 'POST'))
|
|
99
|
+
return send(response, 405, { error: 'GET_OR_REVIEW_POST_REQUIRED' });
|
|
100
|
+
if (url.pathname === '/review/manual-changes' && request.method === 'POST') {
|
|
101
|
+
try {
|
|
102
|
+
const input = await body(request);
|
|
103
|
+
const identity = input;
|
|
104
|
+
validateReviewIdentity(identity);
|
|
105
|
+
if (typeof input.beforeText !== 'string' || typeof input.afterText !== 'string' || input.beforeText.length > 200_000 || input.afterText.length > 200_000)
|
|
106
|
+
throw new Error('MANUAL_CHANGE_TEXT_INVALID');
|
|
107
|
+
const current = await readFile(await validateProjectSourcePath(cwd(), identity.sourcePath), 'utf8');
|
|
108
|
+
const beforeHash = createHash('sha256').update(input.beforeText).digest('hex');
|
|
109
|
+
const afterHash = createHash('sha256').update(input.afterText).digest('hex');
|
|
110
|
+
if (input.afterText !== current)
|
|
111
|
+
throw new Error('STALE_MANUAL_SOURCE');
|
|
112
|
+
if (beforeHash === afterHash)
|
|
113
|
+
throw new Error('MANUAL_CHANGE_UNCHANGED');
|
|
114
|
+
const item = await manualChangeStore.append({ ...identity, beforeSourceSha256: beforeHash, afterSourceSha256: afterHash, beforeText: input.beforeText, afterText: input.afterText });
|
|
115
|
+
return send(response, 201, { change: item, validation: { state: 'Passed', sourceMatches: true, changed: true } });
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'MANUAL_CHANGE_FAILED' });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (url.pathname === '/review/lifecycle' && request.method === 'GET') {
|
|
122
|
+
try {
|
|
123
|
+
const identity = { findingId: url.searchParams.get('findingId') ?? '', sourcePath: url.searchParams.get('sourcePath') ?? '', inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: Number(url.searchParams.get('schemaVersion') ?? '') };
|
|
124
|
+
const source = await readFile(await validateProjectSourcePath(cwd(), identity.sourcePath), 'utf8');
|
|
125
|
+
const sourceSha256 = createHash('sha256').update(source).digest('hex');
|
|
126
|
+
const evidence = evidenceStore.list(identity);
|
|
127
|
+
const audit = (await auditStore.list()).filter(event => event.path === identity.sourcePath);
|
|
128
|
+
return send(response, 200, { lifecycle: projectLifecycle({ decision: reviewStore.getDecision(identity), review: reviewStore.get(identity), evidence, audit, currentSourceSha256: sourceSha256 }), decision: reviewStore.getDecision(identity), review: reviewStore.get(identity), manualChanges: manualChangeStore.list(identity), sourceSha256 });
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'LIFECYCLE_UNAVAILABLE' });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (url.pathname === '/review/manual-changes') {
|
|
135
|
+
try {
|
|
136
|
+
const identity = { findingId: url.searchParams.get('findingId') ?? '', sourcePath: url.searchParams.get('sourcePath') ?? '', inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: Number(url.searchParams.get('schemaVersion') ?? '') };
|
|
137
|
+
if (request.method === 'GET')
|
|
138
|
+
return send(response, 200, { changes: manualChangeStore.list(identity) });
|
|
139
|
+
const input = await body(request);
|
|
140
|
+
if (input.findingId !== identity.findingId || input.sourcePath !== identity.sourcePath || input.inputDigest !== identity.inputDigest || input.policyDigest !== identity.policyDigest || input.schemaVersion !== identity.schemaVersion)
|
|
141
|
+
throw new Error('MANUAL_CHANGE_IDENTITY_MISMATCH');
|
|
142
|
+
if (typeof input.beforeText !== 'string' || typeof input.afterText !== 'string' || input.beforeText.length > 200_000 || input.afterText.length > 200_000)
|
|
143
|
+
throw new Error('MANUAL_CHANGE_TEXT_INVALID');
|
|
144
|
+
const current = await readFile(await validateProjectSourcePath(cwd(), identity.sourcePath), 'utf8');
|
|
145
|
+
const beforeHash = createHash('sha256').update(input.beforeText).digest('hex');
|
|
146
|
+
const afterHash = createHash('sha256').update(input.afterText).digest('hex');
|
|
147
|
+
if (input.afterText !== current)
|
|
148
|
+
throw new Error('STALE_MANUAL_SOURCE');
|
|
149
|
+
if (beforeHash === afterHash)
|
|
150
|
+
throw new Error('MANUAL_CHANGE_UNCHANGED');
|
|
151
|
+
const item = await manualChangeStore.append({ ...identity, beforeSourceSha256: beforeHash, afterSourceSha256: afterHash, beforeText: input.beforeText, afterText: input.afterText });
|
|
152
|
+
return send(response, 201, { change: item, validation: { state: 'Passed', sourceMatches: true, changed: true } });
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'MANUAL_CHANGE_FAILED' });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (url.pathname === '/review/rescan') {
|
|
159
|
+
try {
|
|
160
|
+
if (request.method === 'GET')
|
|
161
|
+
return send(response, 200, { scans: scanManifestStore.list() });
|
|
162
|
+
const input = await body(request);
|
|
163
|
+
if (input.project !== 'invoicing' || !input.manifest)
|
|
164
|
+
throw new Error('INVALID_SCAN_IDENTITY');
|
|
165
|
+
if (input.manifest.sourceCoverage && (input.manifest.sourceCoverage.filesAnalyzed < 0 || input.manifest.sourceCoverage.filesExpected !== undefined && input.manifest.sourceCoverage.filesAnalyzed > input.manifest.sourceCoverage.filesExpected))
|
|
166
|
+
throw new Error('INVALID_SCAN_COVERAGE');
|
|
167
|
+
const item = await scanManifestStore.append(input.manifest);
|
|
168
|
+
return send(response, 201, item);
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'RESCAN_FAILED' });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (url.pathname === '/review/progress' && request.method === 'GET') {
|
|
175
|
+
try {
|
|
176
|
+
const latest = scanManifestStore.latest();
|
|
177
|
+
if (!latest)
|
|
178
|
+
return send(response, 200, { totalFindings: 0, recommendationDistribution: {}, lifecycleDistribution: {}, reconciliationDistribution: {}, validated: 0, outstanding: 0, failed: 0, stale: 0, progressPercent: 0, findings: [] });
|
|
179
|
+
const recommendations = {};
|
|
180
|
+
const lifecycle = {};
|
|
181
|
+
const reconciliation = {};
|
|
182
|
+
let validated = 0;
|
|
183
|
+
const audit = await auditStore.list();
|
|
184
|
+
const findings = await Promise.all(latest.manifest.findings.map(async (f) => { const recommendation = f.category === 'RUNTIME_CONFIG' ? 'Assisted' : f.category === 'INFORMATIONAL' || f.category === 'INTENTIONAL_LTR' ? 'Automated' : 'Manual'; recommendations[recommendation] = (recommendations[recommendation] ?? 0) + 1; const identity = { findingId: f.id, sourcePath: f.path, inputDigest: latest.manifest.inputDigest, policyDigest: latest.manifest.policyDigest, schemaVersion: 2 }; const evidence = evidenceStore.list(identity); const manuals = manualChangeStore.list(identity); if (evidence.length || manuals.length)
|
|
185
|
+
validated += 1; const state = projectLifecycle({ decision: reviewStore.getDecision(identity), review: reviewStore.get(identity), evidence, audit: audit.filter(event => event.path === f.path), currentSourceSha256: await (async () => { try {
|
|
186
|
+
return createHash('sha256').update(await readFile(await validateProjectSourcePath(cwd(), f.path))).digest('hex');
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return undefined;
|
|
190
|
+
} })() }); lifecycle[state] = (lifecycle[state] ?? 0) + 1; const rec = latest.reconciliation.find(x => x.findingId === f.id); if (rec)
|
|
191
|
+
reconciliation[rec.status] = (reconciliation[rec.status] ?? 0) + 1; return { findingId: f.id, recommendation, lifecycle: state, validated: Boolean(evidence.length || manuals.length), reconciliation: rec?.status ?? 'Unresolved', evidenceCount: evidence.length, manualChangeCount: manuals.length }; }));
|
|
192
|
+
const stale = reconciliation.Stale ?? 0;
|
|
193
|
+
const failed = lifecycle['Validation Failed'] ?? 0;
|
|
194
|
+
const totalFindings = findings.length;
|
|
195
|
+
return send(response, 200, { totalFindings, recommendationDistribution: recommendations, lifecycleDistribution: lifecycle, reconciliationDistribution: reconciliation, validated, outstanding: Math.max(0, totalFindings - validated), failed, stale, progressPercent: totalFindings ? Math.round(validated / totalFindings * 100) : 0, findings });
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'PROGRESS_UNAVAILABLE' });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (url.pathname === '/review/source-context' && request.method === 'GET') {
|
|
202
|
+
try {
|
|
203
|
+
const context = await workflowStore.exclusive(async () => {
|
|
204
|
+
const input = url.searchParams.get('inputDigest') ?? '', policy = url.searchParams.get('policyDigest') ?? '';
|
|
205
|
+
const workflow = url.searchParams.get('workflowId') ? workflowStore.get(url.searchParams.get('workflowId')) : workflowStore.find(input, policy, url.searchParams.get('mode') || 'one-by-one');
|
|
206
|
+
if (workflow && (workflow.inputDigest !== input || workflow.policyDigest !== policy))
|
|
207
|
+
throw Error('DASHBOARD_SOURCE_IDENTITY_MISMATCH');
|
|
208
|
+
const closed = workflow && ['Applied', 'Rolled Back'].includes(workflow.state);
|
|
209
|
+
const report = closed ? await verifiedSourceTransition(projectRoot, workflow) : await scan(projectRoot);
|
|
210
|
+
if (!closed && (report.inputDigest !== input || report.policyDigest !== policy))
|
|
211
|
+
throw Error('DASHBOARD_SOURCE_IDENTITY_MISMATCH');
|
|
212
|
+
if (closed)
|
|
213
|
+
await reconcileSourceRuntimes(projectRoot);
|
|
214
|
+
let anchor;
|
|
215
|
+
const selection = url.searchParams.get('selection');
|
|
216
|
+
if (selection && selection.length < 8000) {
|
|
217
|
+
const value = JSON.parse(selection);
|
|
218
|
+
if (typeof value.path === 'string' && typeof value.ruleId === 'string' && Number.isInteger(value.line) && value.line > 0 && Number.isInteger(value.column) && value.column > 0)
|
|
219
|
+
anchor = value;
|
|
220
|
+
}
|
|
221
|
+
const previous = anchor ? workflow?.entries.find(e => e.finding.path === anchor.path && e.finding.ruleId === anchor.ruleId && e.finding.range.start.line === anchor.line && e.finding.range.start.column === anchor.column)?.finding ?? anchor : workflow?.entries.find(e => e.finding.id === url.searchParams.get('findingId'))?.finding;
|
|
222
|
+
return { data: toDashboardData(toSchemaV2Presentation(report), await extractSourceSnippets(projectRoot, report.findings)), transition: closed ? { workflowId: workflow.id, state: workflow.state, historicalInputDigest: workflow.inputDigest, currentInputDigest: report.inputDigest, sessionId: workflow.session?.id ?? null, selection: reconcileSelectedFinding(previous, report, workflow.scope) } : null };
|
|
223
|
+
});
|
|
224
|
+
return send(response, 200, context);
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
return send(response, 409, { error: error instanceof Error ? error.message : 'SOURCE_CONTEXT_UNAVAILABLE' });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (url.pathname === '/contextual-preview/original' && request.method === 'POST') {
|
|
231
|
+
try {
|
|
232
|
+
const result = await workflowStore.exclusive(async () => {
|
|
233
|
+
const workflow = url.searchParams.get('workflowId') ? workflowStore.get(url.searchParams.get('workflowId')) : undefined;
|
|
234
|
+
const before = await contextualPreview(projectRoot, url.searchParams, workflow);
|
|
235
|
+
if (before.route && !before.original.available)
|
|
236
|
+
await initializeOriginalPreview(projectRoot, before.route.application);
|
|
237
|
+
return contextualPreview(projectRoot, url.searchParams, workflow);
|
|
238
|
+
});
|
|
239
|
+
return send(response, 200, result);
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
return send(response, 409, { error: error instanceof Error ? error.message : 'ORIGINAL_PREVIEW_FAILED' });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (url.pathname === '/contextual-preview' && request.method === 'GET') {
|
|
246
|
+
try {
|
|
247
|
+
const result = await workflowStore.exclusive(() => contextualPreview(projectRoot, url.searchParams, url.searchParams.get('workflowId') ? workflowStore.get(url.searchParams.get('workflowId')) : undefined));
|
|
248
|
+
return send(response, 200, result);
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
return send(response, 409, { error: error instanceof Error ? error.message : 'CONTEXTUAL_PREVIEW_FAILED' });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (url.pathname.startsWith('/review/workflows')) {
|
|
255
|
+
try {
|
|
256
|
+
if (request.method === 'GET' && url.pathname === '/review/workflows' && url.searchParams.get('history') === '1')
|
|
257
|
+
return send(response, 200, { workflows: await workflowStore.exclusive(async () => workflowStore.list().map(w => workflowStore.view(w))), projectRoot });
|
|
258
|
+
const match = url.pathname.match(/^\/review\/workflows(?:\/([^/]+)(?:\/(change|runtime|validate|apply|rollback|preview|resume|remaining|prepare-preview|prepare-batch|approve-batch))?)?$/);
|
|
259
|
+
if (!match)
|
|
260
|
+
throw new Error('WORKFLOW_ROUTE_NOT_FOUND');
|
|
261
|
+
const id = match[1], action = match[2];
|
|
262
|
+
if (request.method === 'GET') {
|
|
263
|
+
if (action === 'preview' && id)
|
|
264
|
+
return send(response, 200, await workflowStore.exclusive(() => workflowStore.preview(id, url.searchParams.get('findingId') ?? '', url.searchParams.get('mode') ?? '')));
|
|
265
|
+
const snapshot = await workflowStore.exclusive(async () => { const w = id ? workflowStore.get(id) : workflowStore.find(url.searchParams.get('inputDigest') ?? '', url.searchParams.get('policyDigest') ?? '', url.searchParams.get('mode') ?? ''); return w ? workflowStore.view(w) : null; });
|
|
266
|
+
return send(response, 200, { workflow: snapshot, projectRoot });
|
|
267
|
+
}
|
|
268
|
+
const input = await body(request);
|
|
269
|
+
const w = await workflowStore.exclusive(async () => {
|
|
270
|
+
if (!id)
|
|
271
|
+
return workflowStore.begin(input);
|
|
272
|
+
if (action === 'change')
|
|
273
|
+
return workflowStore.change(id, input.findingId, input);
|
|
274
|
+
if (action === 'prepare-batch')
|
|
275
|
+
return workflowStore.prepareBatch(id);
|
|
276
|
+
if (action === 'approve-batch')
|
|
277
|
+
return workflowStore.approveBatch(id, input.findingIds);
|
|
278
|
+
if (action === 'prepare-preview')
|
|
279
|
+
return workflowStore.preparePreview(id, input);
|
|
280
|
+
if (action === 'runtime') {
|
|
281
|
+
return workflowStore.runtime(id, input.application);
|
|
282
|
+
}
|
|
283
|
+
if (action === 'validate')
|
|
284
|
+
return input.operationId ? workflowStore.runOperation(id, 'validate', input.operationId, () => workflowStore.validate(id)) : workflowStore.validate(id);
|
|
285
|
+
if (action === 'apply')
|
|
286
|
+
return input.operationId ? workflowStore.runOperation(id, 'apply', input.operationId, () => workflowStore.apply(id, input.confirmation)) : workflowStore.apply(id, input.confirmation);
|
|
287
|
+
if (action === 'rollback')
|
|
288
|
+
return workflowStore.rollback(id, input.confirmation);
|
|
289
|
+
if (action === 'remaining')
|
|
290
|
+
return workflowStore.reviewRemaining(id);
|
|
291
|
+
if (action === 'resume')
|
|
292
|
+
return workflowStore.resumeAfterRollback(id);
|
|
293
|
+
throw new Error('WORKFLOW_ACTION_REQUIRED');
|
|
294
|
+
});
|
|
295
|
+
return send(response, 200, { workflow: workflowStore.view(w), projectRoot });
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
return send(response, 409, { error: error instanceof Error ? error.message : 'WORKFLOW_FAILED' });
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (url.pathname === '/review/apply/eligibility' && request.method === 'GET') {
|
|
302
|
+
try {
|
|
303
|
+
const identity = { findingId: url.searchParams.get('findingId') ?? '', sourcePath: url.searchParams.get('sourcePath') ?? '', inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: Number(url.searchParams.get('schemaVersion') ?? '') };
|
|
304
|
+
validateReviewIdentity(identity);
|
|
305
|
+
const record = reviewStore.get(identity);
|
|
306
|
+
const evidence = evidenceStore.list(identity).find(x => (x.decision === 'Approved' || x.decision === 'Ready for Review') && !!x.patch && !x.scannerAfter.findingPresent);
|
|
307
|
+
const currentSourceSha256 = createHash('sha256').update(await readFile(await validateProjectSourcePath(cwd(), identity.sourcePath))).digest('hex');
|
|
308
|
+
const stale = !!evidence && currentSourceSha256 !== evidence.originalSourceSha256 && currentSourceSha256 !== evidence.candidateSourceSha256;
|
|
309
|
+
const ready = !!record && record.status === 'Approved' && !!evidence && !stale;
|
|
310
|
+
return send(response, 200, { ready, reason: stale ? 'STALE_SOURCE' : ready ? null : 'APPROVED_REVIEW_REQUIRED', findingId: identity.findingId, sourcePath: identity.sourcePath, reviewStatus: record?.status ?? null, currentSourceSha256, evidence: evidence ? { snapshotId: evidence.snapshotId, originalSourceSha256: evidence.originalSourceSha256, candidateSourceSha256: evidence.candidateSourceSha256, codeDiff: evidence.codeDiff, patch: evidence.patch } : null });
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'APPLY_ELIGIBILITY_FAILED' });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (url.pathname === '/health')
|
|
317
|
+
return send(response, 200, { ok: true, service: 'rtl-preview-companion', projectRoot, manifestVersion: previewManifest.version, ...await previewCapabilities(), contextualPreviewVersion: 2, configuredMappingVersion: 1, reviewPersistence: { available: !reviewStore.loadError, path: DEFAULT_REVIEW_STORE_PATH }, evidencePersistence: { available: !evidenceStore.loadError, path: DEFAULT_EVIDENCE_STORE_PATH } });
|
|
318
|
+
if (url.pathname === '/capabilities')
|
|
319
|
+
return send(response, 200, { manifestVersion: previewManifest.version, ...await previewCapabilities(), contextualPreviewVersion: 2, configuredMappingVersion: 1, modes: ['ltr', 'rtl'], mappingLookup: true });
|
|
320
|
+
if (url.pathname === '/review/sessions' && request.method === 'POST') {
|
|
321
|
+
try {
|
|
322
|
+
const session = await createReviewSession(cwd());
|
|
323
|
+
sessions.set(session.id, session);
|
|
324
|
+
return send(response, 201, { id: session.id, state: session.state, classification: session.classification, source: session.sourcePath, originalSha256: session.originalSha256, candidateOrigin: null });
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'REVIEW_SESSION_FAILED' });
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (url.pathname === '/review/codemod/analyze' && request.method === 'POST') {
|
|
331
|
+
try {
|
|
332
|
+
const input = await body(request);
|
|
333
|
+
const source = await readFile(await validateProjectSourcePath(cwd(), input.finding.path), 'utf8');
|
|
334
|
+
const finding = normalizeBidiFinding(input.finding, source);
|
|
335
|
+
const digest = createHash('sha256').update(source).digest('hex');
|
|
336
|
+
if (input.sourceSha256 && input.sourceSha256 !== digest)
|
|
337
|
+
return send(response, 409, { error: 'STALE_SOURCE' });
|
|
338
|
+
const proposal = analyzeBidiIsolation(finding, source);
|
|
339
|
+
return send(response, 200, { analyzed: true, sourceSha256: digest, transformationId: proposal.transformationId, reason: proposal.reason, patch: proposal.patch });
|
|
340
|
+
}
|
|
341
|
+
catch (error) {
|
|
342
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'CODEMOD_ANALYSIS_FAILED' });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (url.pathname.match(/^\/review\/sessions\/[^/]+\/validate$/) && request.method === 'POST') {
|
|
346
|
+
const id = decodeURIComponent(url.pathname.split('/')[3] ?? '');
|
|
347
|
+
const session = sessions.get(id);
|
|
348
|
+
if (!session)
|
|
349
|
+
return send(response, 404, { error: 'REVIEW_SESSION_NOT_FOUND' });
|
|
350
|
+
if (validations.has(id))
|
|
351
|
+
return send(response, 409, { error: 'VALIDATION_ALREADY_EXISTS', result: validations.get(id) });
|
|
352
|
+
try {
|
|
353
|
+
const input = await body(request);
|
|
354
|
+
const original = await readFile(join(cwd(), REVIEW_SOURCE), 'utf8');
|
|
355
|
+
const finding = normalizeBidiFinding(input.finding, original);
|
|
356
|
+
const result = await validateCandidate(session, finding, input.patch, async (candidate) => { const next = await startCandidateRuntime(candidate); sessions.set(id, next); return next; });
|
|
357
|
+
validations.set(id, result);
|
|
358
|
+
return send(response, 200, { result });
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'VALIDATION_FAILED', state: 'Failed' });
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (url.pathname.match(/^\/review\/sessions\/[^/]+\/validation$/) && request.method === 'GET') {
|
|
365
|
+
const id = decodeURIComponent(url.pathname.split('/')[3] ?? '');
|
|
366
|
+
return send(response, 200, { state: validations.has(id) ? validations.get(id)?.state : 'Idle', result: validations.get(id) ?? null });
|
|
367
|
+
}
|
|
368
|
+
if (url.pathname.match(/^\/review\/sessions\/[^/]+\/validation\/archive$/) && request.method === 'POST') {
|
|
369
|
+
const id = decodeURIComponent(url.pathname.split('/')[3] ?? '');
|
|
370
|
+
const session = sessions.get(id);
|
|
371
|
+
const result = validations.get(id);
|
|
372
|
+
if (!session || !result)
|
|
373
|
+
return send(response, 404, { error: 'VALIDATION_NOT_FOUND' });
|
|
374
|
+
if (result.state !== 'Passed')
|
|
375
|
+
return send(response, 400, { error: 'VALIDATION_NOT_PASSED' });
|
|
376
|
+
try {
|
|
377
|
+
const snapshot = await evidenceStore.append({ findingId: result.patch.findingId, sourcePath: result.patch.path, inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: 2, candidatePatchIdentity: { path: result.patch.path, expectedSha256: result.patch.expectedSha256, replacementSha256: createHash('sha256').update(result.patch.replacement).digest('hex') }, originalSourceSha256: result.originalSourceSha256, candidateSourceSha256: result.candidateSourceSha256, codeDiff: await reviewSessionDiff(session), scannerBefore: result.scannerBefore, scannerAfter: result.scannerAfter, browserDomValidation: result.browserDomValidation, screenshotReferences: result.screenshotReferences, screenshotDigests: await Promise.all(result.screenshotReferences.map(async (reference) => createHash('sha256').update(await readFile(screenshotPath(reference))).digest('hex'))), timestamp: result.finishedAt, decision: 'Ready for Review', patch: result.patch });
|
|
378
|
+
return send(response, 201, { snapshot });
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'EVIDENCE_ARCHIVE_FAILED' });
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (url.pathname === '/review/records') {
|
|
385
|
+
try {
|
|
386
|
+
if (request.method === 'GET') {
|
|
387
|
+
const identity = { findingId: url.searchParams.get('findingId') ?? '', sourcePath: url.searchParams.get('sourcePath') ?? '', inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: Number(url.searchParams.get('schemaVersion') ?? '') };
|
|
388
|
+
return send(response, 200, { record: reviewStore.get(identity) });
|
|
389
|
+
}
|
|
390
|
+
const input = await body(request);
|
|
391
|
+
const current = reviewStore.get(input);
|
|
392
|
+
const candidateSessionId = (input.status === 'Approved' || input.status === 'Ready for Review') ? recoverCandidateSessionId(input, current) : input.candidateSessionId;
|
|
393
|
+
if ((input.status === 'Approved' || input.status === 'Ready for Review') && (!input.evidenceReferences.length || !input.reviewerNotes.trim()))
|
|
394
|
+
return send(response, 400, { error: 'REVIEW_EVIDENCE_REQUIRED' });
|
|
395
|
+
if (input.status === 'Approved' && (sessions.get(candidateSessionId)?.runtime?.status !== 'healthy'))
|
|
396
|
+
return send(response, 400, { error: 'HEALTHY_CANDIDATE_REQUIRED' });
|
|
397
|
+
const record = await reviewStore.saveAndPersist((input.status === 'Approved' || input.status === 'Ready for Review') ? { ...input, candidateSessionId } : input);
|
|
398
|
+
return send(response, 200, { record });
|
|
399
|
+
}
|
|
400
|
+
catch (error) {
|
|
401
|
+
const message = error instanceof Error ? error.message : 'REVIEW_RECORD_FAILED';
|
|
402
|
+
return send(response, message.startsWith('REVIEW_STORE_UNAVAILABLE') ? 503 : 400, { error: message });
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
if (url.pathname === '/review/decisions' && request.method === 'POST') {
|
|
406
|
+
try {
|
|
407
|
+
const input = await body(request);
|
|
408
|
+
validateReviewIdentity(input);
|
|
409
|
+
const source = await readFile(await validateProjectSourcePath(cwd(), input.sourcePath), 'utf8');
|
|
410
|
+
const sourceDigest = createHash('sha256').update(source).digest('hex');
|
|
411
|
+
if (sourceDigest !== input.sourceDigest)
|
|
412
|
+
throw new Error('STALE_DECISION_SOURCE');
|
|
413
|
+
const decision = await reviewStore.saveDecision(input);
|
|
414
|
+
return send(response, 200, { decision });
|
|
415
|
+
}
|
|
416
|
+
catch (error) {
|
|
417
|
+
const message = error instanceof Error ? error.message : 'MIGRATION_DECISION_FAILED';
|
|
418
|
+
return send(response, message.startsWith('REVIEW_STORE_UNAVAILABLE') ? 503 : 400, { error: message });
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
if (url.pathname === '/review/decisions') {
|
|
422
|
+
try {
|
|
423
|
+
const identity = { findingId: url.searchParams.get('findingId') ?? '', sourcePath: url.searchParams.get('sourcePath') ?? '', inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: Number(url.searchParams.get('schemaVersion') ?? '') };
|
|
424
|
+
const source = await readFile(await validateProjectSourcePath(cwd(), identity.sourcePath), 'utf8');
|
|
425
|
+
const sourceDigest = createHash('sha256').update(source).digest('hex');
|
|
426
|
+
if (request.method === 'GET')
|
|
427
|
+
return send(response, 200, { decision: reviewStore.getDecision(identity), sourceDigest });
|
|
428
|
+
const input = await body(request);
|
|
429
|
+
if (input.findingId !== identity.findingId || input.sourcePath !== identity.sourcePath || input.inputDigest !== identity.inputDigest || input.policyDigest !== identity.policyDigest || input.schemaVersion !== identity.schemaVersion)
|
|
430
|
+
throw new Error('DECISION_IDENTITY_MISMATCH');
|
|
431
|
+
if (sourceDigest !== input.sourceDigest)
|
|
432
|
+
throw new Error('STALE_DECISION_SOURCE');
|
|
433
|
+
const decision = await reviewStore.saveDecision(input);
|
|
434
|
+
return send(response, 200, { decision });
|
|
435
|
+
}
|
|
436
|
+
catch (error) {
|
|
437
|
+
const message = error instanceof Error ? error.message : 'MIGRATION_DECISION_FAILED';
|
|
438
|
+
return send(response, message.startsWith('REVIEW_STORE_UNAVAILABLE') ? 503 : 400, { error: message });
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
if (url.pathname === '/review/evidence') {
|
|
442
|
+
try {
|
|
443
|
+
const identity = { findingId: url.searchParams.get('findingId') ?? '', sourcePath: url.searchParams.get('sourcePath') ?? '', inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: Number(url.searchParams.get('schemaVersion') ?? '') };
|
|
444
|
+
if (request.method === 'GET')
|
|
445
|
+
return send(response, 200, { snapshots: evidenceStore.list(identity) });
|
|
446
|
+
const input = await body(request);
|
|
447
|
+
if (Array.isArray(input.screenshotReferences))
|
|
448
|
+
input.screenshotDigests = await Promise.all(input.screenshotReferences.map(async (reference) => createHash('sha256').update(await readFile(screenshotPath(reference))).digest('hex')));
|
|
449
|
+
if (input.patch?.replacement && input.candidatePatchIdentity?.replacementSha256 === null)
|
|
450
|
+
input.candidatePatchIdentity.replacementSha256 = createHash('sha256').update(input.patch.replacement).digest('hex');
|
|
451
|
+
const snapshot = await evidenceStore.append(input);
|
|
452
|
+
return send(response, 201, { snapshot });
|
|
453
|
+
}
|
|
454
|
+
catch (error) {
|
|
455
|
+
const message = error instanceof Error ? error.message : 'EVIDENCE_SNAPSHOT_FAILED';
|
|
456
|
+
return send(response, message.includes('UNAVAILABLE') ? 503 : 400, { error: message });
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
const screenshotMatch = url.pathname.match(/^\/review\/evidence\/([^/]+)\/screenshot\/(.+)$/);
|
|
460
|
+
if (screenshotMatch && request.method === 'GET') {
|
|
461
|
+
try {
|
|
462
|
+
const identity = { findingId: url.searchParams.get('findingId') ?? '', sourcePath: url.searchParams.get('sourcePath') ?? '', inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: Number(url.searchParams.get('schemaVersion') ?? '') };
|
|
463
|
+
const snapshot = evidenceStore.list(identity).find(x => x.snapshotId === decodeURIComponent(screenshotMatch[1]));
|
|
464
|
+
if (!snapshot)
|
|
465
|
+
return send(response, 404, { error: 'EVIDENCE_NOT_FOUND' });
|
|
466
|
+
const reference = decodeURIComponent(screenshotMatch[2]);
|
|
467
|
+
const index = snapshot.screenshotReferences.indexOf(reference);
|
|
468
|
+
const expectedDigest = snapshot.screenshotDigests?.[index];
|
|
469
|
+
if (index < 0 || !expectedDigest)
|
|
470
|
+
return send(response, 404, { error: 'SCREENSHOT_NOT_AVAILABLE' });
|
|
471
|
+
const bytes = await assertScreenshotFile(screenshotPath(reference), expectedDigest);
|
|
472
|
+
const type = reference.toLowerCase().endsWith('.jpg') || reference.toLowerCase().endsWith('.jpeg') ? 'image/jpeg' : reference.toLowerCase().endsWith('.webp') ? 'image/webp' : 'image/png';
|
|
473
|
+
response.writeHead(200, { 'content-type': type, 'cache-control': 'private, no-store', 'content-disposition': 'inline', 'x-content-type-options': 'nosniff', 'content-security-policy': "default-src 'none'; sandbox" });
|
|
474
|
+
return response.end(bytes);
|
|
475
|
+
}
|
|
476
|
+
catch (error) {
|
|
477
|
+
const message = error instanceof Error ? error.message : 'SCREENSHOT_UNAVAILABLE';
|
|
478
|
+
return send(response, message === 'SCREENSHOT_INTEGRITY_MISMATCH' ? 409 : 404, { error: message });
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
if (url.pathname === '/review/apply/eligibility' && request.method === 'GET') {
|
|
482
|
+
try {
|
|
483
|
+
const identity = { findingId: url.searchParams.get('findingId') ?? '', sourcePath: url.searchParams.get('sourcePath') ?? '', inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: Number(url.searchParams.get('schemaVersion') ?? '') };
|
|
484
|
+
const record = reviewStore.get(identity);
|
|
485
|
+
const evidence = evidenceStore.list(identity);
|
|
486
|
+
const approved = evidence.find(x => (x.decision === 'Approved' || x.decision === 'Ready for Review') && !!x.patch && !x.scannerAfter.findingPresent && x.browserDomValidation.length > 0);
|
|
487
|
+
const ready = !!record && record.status === 'Approved' && !!approved;
|
|
488
|
+
return send(response, 200, { ready, reason: ready ? null : (!record ? 'APPROVED_REVIEW_REQUIRED' : record.status !== 'Approved' ? 'APPROVED_REVIEW_REQUIRED' : !approved ? 'VALIDATION_EVIDENCE_REQUIRED' : 'APPLY_NOT_ELIGIBLE'), findingId: identity.findingId, sourcePath: identity.sourcePath, reviewStatus: record?.status ?? null, evidence: approved ? { snapshotId: approved.snapshotId, originalSourceSha256: approved.originalSourceSha256, candidateSourceSha256: approved.candidateSourceSha256, codeDiff: approved.codeDiff, patch: approved.patch } : null });
|
|
489
|
+
}
|
|
490
|
+
catch (error) {
|
|
491
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'APPLY_ELIGIBILITY_FAILED' });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (url.pathname === '/review/audit' && request.method === 'GET') {
|
|
495
|
+
try {
|
|
496
|
+
const events = await auditStore.list();
|
|
497
|
+
const path = url.searchParams.get('sourcePath');
|
|
498
|
+
return send(response, 200, { events: path ? events.filter(x => x.path === path) : events });
|
|
499
|
+
}
|
|
500
|
+
catch (error) {
|
|
501
|
+
return send(response, 503, { error: error instanceof Error ? error.message : 'APPLY_AUDIT_UNREADABLE' });
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (url.pathname === '/review/rollback/eligibility' && request.method === 'GET') {
|
|
505
|
+
try {
|
|
506
|
+
const identity = { findingId: url.searchParams.get('findingId') ?? '', sourcePath: url.searchParams.get('sourcePath') ?? '', inputDigest: url.searchParams.get('inputDigest') ?? '', policyDigest: url.searchParams.get('policyDigest') ?? '', schemaVersion: Number(url.searchParams.get('schemaVersion') ?? '') };
|
|
507
|
+
const record = reviewStore.get(identity);
|
|
508
|
+
const evidence = evidenceStore.list(identity).find(x => (x.decision === 'Approved' || x.decision === 'Ready for Review') && x.patch && x.sourcePath === identity.sourcePath);
|
|
509
|
+
const receipt = record?.status === 'Approved' && evidence ? await applyService.recoverRollbackReceipt(identity.sourcePath, evidence.originalSourceSha256, evidence.candidateSourceSha256) : null;
|
|
510
|
+
return send(response, 200, { eligible: !!receipt, receipt: receipt ?? null, reason: receipt ? null : 'ROLLBACK_NOT_ELIGIBLE' });
|
|
511
|
+
}
|
|
512
|
+
catch (error) {
|
|
513
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'ROLLBACK_ELIGIBILITY_FAILED' });
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
if (url.pathname === '/review/apply' && request.method === 'POST') {
|
|
517
|
+
try {
|
|
518
|
+
const report = await scan(cwd());
|
|
519
|
+
const input = await body(request);
|
|
520
|
+
if (!report.complete)
|
|
521
|
+
throw new Error('INCOMPLETE_SCAN_REQUIRES_MANUAL_RESOLUTION');
|
|
522
|
+
if (report.inputDigest !== input.identity.inputDigest || report.policyDigest !== input.identity.policyDigest)
|
|
523
|
+
throw new Error('STALE_PROJECT_IDENTITY');
|
|
524
|
+
const currentFinding = report.findings.find(f => f.id === input.identity.findingId && f.path === input.identity.sourcePath);
|
|
525
|
+
if (!currentFinding || directionRequirement(currentFinding) !== 'independent')
|
|
526
|
+
throw new Error('LEGACY_DIRECTION_DEPENDENT_APPLY_UNSUPPORTED');
|
|
527
|
+
const record = reviewStore.get(input.identity);
|
|
528
|
+
if (!record)
|
|
529
|
+
return send(response, 400, { error: 'APPROVED_REVIEW_REQUIRED' });
|
|
530
|
+
const evidence = evidenceStore.list(input.identity);
|
|
531
|
+
const approved = evidence.find(x => (x.decision === 'Approved' || x.decision === 'Ready for Review') && x.patch);
|
|
532
|
+
if (!approved?.patch)
|
|
533
|
+
return send(response, 400, { error: 'PATCH_METADATA_REQUIRED' });
|
|
534
|
+
const proposal = proposeTransformation(currentFinding, await readFile(await validateProjectSourcePath(cwd(), currentFinding.path), 'utf8'));
|
|
535
|
+
if (!sameSupportedPatch(proposal.patch, approved.patch))
|
|
536
|
+
throw new Error('UNSUPPORTED_CANDIDATE_PATCH');
|
|
537
|
+
const receipt = await applyService.apply({ identity: input.identity, confirmation: input.confirmation, reviewRecord: record, evidence, patch: approved.patch });
|
|
538
|
+
return send(response, 200, { receipt, state: 'APPLIED' });
|
|
539
|
+
}
|
|
540
|
+
catch (error) {
|
|
541
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'CONTROLLED_APPLY_FAILED', state: 'APPLY_FAILED' });
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (url.pathname === '/review/rollback' && request.method === 'POST') {
|
|
545
|
+
try {
|
|
546
|
+
await applyService.rollback(await body(request));
|
|
547
|
+
return send(response, 200, { state: 'ROLLED_BACK' });
|
|
548
|
+
}
|
|
549
|
+
catch (error) {
|
|
550
|
+
return send(response, 409, { error: error instanceof Error ? error.message : 'ROLLBACK_FAILED', state: 'ROLLBACK_FAILED' });
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const diffMatch = url.pathname.match(/^\/review\/sessions\/([^/]+)\/diff$/);
|
|
554
|
+
if (diffMatch && request.method === 'GET') {
|
|
555
|
+
const session = sessions.get(decodeURIComponent(diffMatch[1]));
|
|
556
|
+
if (!session)
|
|
557
|
+
return send(response, 404, { error: 'REVIEW_SESSION_NOT_FOUND' });
|
|
558
|
+
const comparison = await reviewSessionComparison(session);
|
|
559
|
+
return send(response, 200, { ...comparison, source: session.sourcePath, candidateSessionId: session.id });
|
|
560
|
+
}
|
|
561
|
+
const reviewMatch = url.pathname.match(/^\/review\/sessions\/([^/]+)(?:\/(patch|cleanup|diff|codemod\/apply))?$/);
|
|
562
|
+
if (reviewMatch) {
|
|
563
|
+
const session = sessions.get(decodeURIComponent(reviewMatch[1]));
|
|
564
|
+
if (!session)
|
|
565
|
+
return send(response, 404, { error: 'REVIEW_SESSION_NOT_FOUND' });
|
|
566
|
+
try {
|
|
567
|
+
if (reviewMatch[2] === 'patch' && request.method === 'POST') {
|
|
568
|
+
const next = await applyReviewPatch(session, await body(request));
|
|
569
|
+
sessions.set(next.id, next);
|
|
570
|
+
return send(response, 200, { id: next.id, state: next.state, candidateSha256: next.candidateSha256, candidateOrigin: session.runtime?.origin ?? null });
|
|
571
|
+
}
|
|
572
|
+
if (reviewMatch[2] === 'cleanup' && request.method === 'POST') {
|
|
573
|
+
await disposeReviewSession(session);
|
|
574
|
+
sessions.delete(session.id);
|
|
575
|
+
return send(response, 200, { ok: true });
|
|
576
|
+
}
|
|
577
|
+
if (url.pathname.endsWith('/codemod/apply') && request.method === 'POST') {
|
|
578
|
+
const input = await body(request);
|
|
579
|
+
if (input.confirmation !== 'CANDIDATE_APPLY_CONFIRMED')
|
|
580
|
+
throw new Error('CANDIDATE_CONFIRMATION_REQUIRED');
|
|
581
|
+
const source = await readFile(await validateProjectSourcePath(cwd(), input.finding.path), 'utf8');
|
|
582
|
+
const digest = createHash('sha256').update(source).digest('hex');
|
|
583
|
+
if (input.sourceSha256 && input.sourceSha256 !== digest)
|
|
584
|
+
throw new Error('STALE_SOURCE');
|
|
585
|
+
const proposal = analyzeBidiIsolation(normalizeBidiFinding(input.finding, source), source);
|
|
586
|
+
const next = await applyReviewPatch(session, proposal.patch);
|
|
587
|
+
sessions.set(next.id, next);
|
|
588
|
+
return send(response, 200, { id: next.id, state: next.state, candidateSha256: next.candidateSha256, transformationId: proposal.transformationId, patch: proposal.patch, candidateOrigin: session.runtime?.origin ?? null });
|
|
589
|
+
}
|
|
590
|
+
if (url.pathname.endsWith('/diff'))
|
|
591
|
+
return send(response, 200, { diff: await reviewSessionDiff(session), source: session.sourcePath, candidateSessionId: session.id });
|
|
592
|
+
return send(response, 200, { id: session.id, state: session.state, classification: session.classification, source: session.sourcePath, candidateOrigin: session.runtime?.origin ?? null, runtime: session.runtime, originalSha256: session.originalSha256, candidateSha256: session.candidateSha256, findingId: session.patch?.findingId });
|
|
593
|
+
}
|
|
594
|
+
catch (error) {
|
|
595
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'REVIEW_REQUEST_FAILED' });
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
const runtimeMatch = url.pathname.match(/^\/review\/sessions\/([^/]+)\/runtime\/(start|stop)$/);
|
|
599
|
+
if (runtimeMatch) {
|
|
600
|
+
const session = sessions.get(decodeURIComponent(runtimeMatch[1]));
|
|
601
|
+
if (!session)
|
|
602
|
+
return send(response, 404, { error: 'REVIEW_SESSION_NOT_FOUND' });
|
|
603
|
+
try {
|
|
604
|
+
const next = runtimeMatch[2] === 'start' ? await startCandidateRuntime(session) : await stopCandidateRuntime(session);
|
|
605
|
+
sessions.set(next.id, next);
|
|
606
|
+
return send(response, 200, { id: next.id, runtime: next.runtime, candidateOrigin: next.runtime?.origin ?? null, urls: { ltr: next.runtime ? `${next.runtime.origin}/invoices` : null, rtl: next.runtime ? `${next.runtime.origin}/invoices?demo=unmigrated-rtl&lang=ar` : null } });
|
|
607
|
+
}
|
|
608
|
+
catch (error) {
|
|
609
|
+
return send(response, 400, { error: error instanceof Error ? error.message : 'RUNTIME_REQUEST_FAILED' });
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const match = url.pathname.match(/^\/mappings\/([^/]+)\/preview$/);
|
|
613
|
+
if (match) {
|
|
614
|
+
const result = validatedPreviewRoute(decodeURIComponent(match[1]), url.searchParams.get('mode') ?? '');
|
|
615
|
+
if (!result)
|
|
616
|
+
return send(response, 404, { error: 'APPROVED_PREVIEW_NOT_FOUND' });
|
|
617
|
+
const sessionId = url.searchParams.get('session');
|
|
618
|
+
const session = sessionId ? sessions.get(sessionId) : undefined;
|
|
619
|
+
if (sessionId && (!session || session.sourcePath !== result.mapping.source || (url.searchParams.has('findingId') && url.searchParams.get('findingId') !== session.patch?.findingId)))
|
|
620
|
+
return send(response, 404, { error: 'PREVIEW_SESSION_IDENTITY_MISMATCH' });
|
|
621
|
+
const sourceSha256 = createHash('sha256').update(await readFile(await validateProjectSourcePath(cwd(), result.mapping.source))).digest('hex');
|
|
622
|
+
let originalAvailable = false;
|
|
623
|
+
try {
|
|
624
|
+
const probe = await fetch(applicationOrigin + '/__rtl_preview_identity', { signal: AbortSignal.timeout(1500) });
|
|
625
|
+
const identity = await probe.json();
|
|
626
|
+
originalAvailable = probe.ok && identity.role === 'original' && identity.sourceSha256 === sourceSha256;
|
|
627
|
+
}
|
|
628
|
+
catch { /* optional original runtime */ }
|
|
629
|
+
const candidateOrigin = session?.runtime?.status === 'healthy' ? session.runtime.origin : null;
|
|
630
|
+
return send(response, 200, { manifestVersion: previewManifest.version, mappingId: result.mapping.id, source: result.mapping.source, application: result.mapping.application, owningRoute: result.mapping.owningRoute, mode: result.mode, route: result.route, url: `${candidateOrigin ?? applicationOrigin}${result.route}`, originalUrl: `${applicationOrigin}${result.route}`, originalAvailable, originalSourceSha256: sourceSha256, candidateOrigin, candidateSessionId: session?.id ?? null, candidateSourceSha256: session?.candidateSha256 ?? null, findingId: session?.patch?.findingId ?? null });
|
|
631
|
+
}
|
|
632
|
+
return send(response, 404, { error: 'NOT_FOUND' });
|
|
633
|
+
});
|
|
634
|
+
let shuttingDown = false;
|
|
635
|
+
// Idempotent: npm/npx forward the terminal's SIGINT, so the companion routinely receives it twice. A second signal must not abort the first shutdown.
|
|
636
|
+
const shutdown = async () => {
|
|
637
|
+
if (shuttingDown)
|
|
638
|
+
return;
|
|
639
|
+
shuttingDown = true;
|
|
640
|
+
setTimeout(() => process.exit(1), 8000).unref();
|
|
641
|
+
await Promise.allSettled([stopOwnedOriginalPreviews(), workflowStore.shutdown(), stopAllCandidateRuntimes(), ...[...sessions.values()].map(session => disposeReviewSession(session))]);
|
|
642
|
+
server.close(() => process.exit(0));
|
|
643
|
+
setTimeout(() => process.exit(1), 3000).unref();
|
|
644
|
+
};
|
|
645
|
+
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'])
|
|
646
|
+
process.on(signal, shutdown);
|
|
647
|
+
// Last resort for any exit path: never leave an owned runtime process group behind.
|
|
648
|
+
process.on('exit', () => { signalOwnedOriginalPreviews(); signalAllCandidateRuntimes(); });
|
|
649
|
+
server.listen(port, host, () => console.log(`RTL preview companion listening on ${host}:${port}`));
|