coauthored 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/PRIVACY.md +107 -0
- package/README.md +113 -3
- package/THIRD_PARTY_LICENSES.md +105 -0
- package/dist/cli/analytics/anchors.js +39 -0
- package/dist/cli/analytics/archetypes.js +193 -0
- package/dist/cli/analytics/content/analyzer.js +945 -0
- package/dist/cli/analytics/content/classify.js +115 -0
- package/dist/cli/analytics/content/demo-corpus.js +301 -0
- package/dist/cli/analytics/content/sketch.js +54 -0
- package/dist/cli/analytics/dataset.js +321 -0
- package/dist/cli/analytics/demo-fixtures.js +531 -0
- package/dist/cli/analytics/fdr.js +183 -0
- package/dist/cli/analytics/helicorder.js +66 -0
- package/dist/cli/analytics/insights.js +589 -0
- package/dist/cli/analytics/models.js +75 -0
- package/dist/cli/analytics/pricing.js +121 -0
- package/dist/cli/analytics/probable-cause.js +115 -0
- package/dist/cli/analytics/report-builder.js +162 -0
- package/dist/cli/analytics/statistics.js +91 -0
- package/dist/cli/analytics/time.js +252 -0
- package/dist/cli/cli/args.js +105 -0
- package/dist/cli/cli/browser.js +71 -0
- package/dist/cli/cli/index.js +20 -0
- package/dist/cli/cli/main.js +520 -0
- package/dist/cli/cli/phrase-review.js +78 -0
- package/dist/cli/cli/server.js +481 -0
- package/dist/cli/cli/terminal.js +363 -0
- package/dist/cli/ingest/adapters/aider.js +116 -0
- package/dist/cli/ingest/adapters/claude-code.js +139 -0
- package/dist/cli/ingest/adapters/cline-roo.js +89 -0
- package/dist/cli/ingest/adapters/codex-cli.js +240 -0
- package/dist/cli/ingest/adapters/content.js +99 -0
- package/dist/cli/ingest/adapters/cursor-ide.js +149 -0
- package/dist/cli/ingest/adapters/gemini-cli.js +208 -0
- package/dist/cli/ingest/adapters/index.js +18 -0
- package/dist/cli/ingest/adapters/opencode.js +203 -0
- package/dist/cli/ingest/adapters/pi-agent.js +85 -0
- package/dist/cli/ingest/adapters/shared.js +484 -0
- package/dist/cli/ingest/content-sink.js +31 -0
- package/dist/cli/ingest/discovery.js +50 -0
- package/dist/cli/ingest/message-digests.js +61 -0
- package/dist/cli/ingest/pipeline.js +155 -0
- package/dist/cli/ingest/safe-fs.js +284 -0
- package/dist/cli/ingest/sqlite-stage.js +139 -0
- package/dist/cli/ingest/time-window.js +34 -0
- package/dist/cli/ingest/tool-map.js +24 -0
- package/dist/cli/ingest/types.js +1 -0
- package/dist/cli/ingest/worker.js +97 -0
- package/dist/cli/report/content/emoji-names.js +3956 -0
- package/dist/cli/report/content/insights.js +41 -0
- package/dist/cli/report/content/lexicons.js +112 -0
- package/dist/cli/report/content/policy.js +77 -0
- package/dist/cli/report/content/redact.js +164 -0
- package/dist/cli/report/content/stopwords.js +8848 -0
- package/dist/cli/report/content/suppression.js +2617 -0
- package/dist/cli/report/content/validate.js +152 -0
- package/dist/cli/report/copy-lint.js +105 -0
- package/dist/cli/report/share.js +132 -0
- package/dist/cli/report/types.js +1 -0
- package/dist/cli/report/validators.js +334 -0
- package/dist/web/assets/Archivo-VF-BohoA-Sn.woff2 +0 -0
- package/dist/web/assets/DelaGothicOne-subset-CpoJGhTq.woff2 +0 -0
- package/dist/web/assets/Film-Dq8Xxn7U.css +1 -0
- package/dist/web/assets/MartianMono-VF-CmJ1nXx9.woff2 +0 -0
- package/dist/web/assets/app-DEQgytaq.js +38 -0
- package/dist/web/assets/bricolage-grotesque-latin-700-normal-gtcctNPv.woff2 +0 -0
- package/dist/web/assets/bricolage-grotesque-latin-800-normal-J50vIsBe.woff2 +0 -0
- package/dist/web/assets/chorus-D7bfON5Z.ogg +0 -0
- package/dist/web/assets/chorus-bass-CBTKpMv_.ogg +0 -0
- package/dist/web/assets/chorus-drums-BOzgLSoq.ogg +0 -0
- package/dist/web/assets/chorus-harmony-DnJYs_tp.ogg +0 -0
- package/dist/web/assets/chorus-lead-CFpg5DC1.ogg +0 -0
- package/dist/web/assets/chunk-BNfsY4o8.js +1 -0
- package/dist/web/assets/chunk-BSm8IhPY.js +1 -0
- package/dist/web/assets/chunk-Bi6EQAkf.js +1 -0
- package/dist/web/assets/chunk-BmDwUWlX.js +1 -0
- package/dist/web/assets/chunk-Ds4joAI5.js +46 -0
- package/dist/web/assets/chunk-V3YGpFIw.js +1 -0
- package/dist/web/assets/chunk-XGhNFWse.js +1 -0
- package/dist/web/assets/dialogue-card-A5zmbNhu.ogg +0 -0
- package/dist/web/assets/groove-bass-BFNelLKi.ogg +0 -0
- package/dist/web/assets/groove-drums-BY1SBntR.ogg +0 -0
- package/dist/web/assets/groove-harmony-C0CrBzu3.ogg +0 -0
- package/dist/web/assets/groove-lead-CEYPzm5U.ogg +0 -0
- package/dist/web/assets/groove-ln-zQmTb.ogg +0 -0
- package/dist/web/assets/guess-high-CL6mF18x.ogg +0 -0
- package/dist/web/assets/guess-low-C3UnKayZ.ogg +0 -0
- package/dist/web/assets/higher-BevsMIWl.ogg +0 -0
- package/dist/web/assets/identity-0EPS3msD.ogg +0 -0
- package/dist/web/assets/index-DpT0dtHc.css +1 -0
- package/dist/web/assets/intro-DeRh6kUx.ogg +0 -0
- package/dist/web/assets/intro-bass-D63IPU0H.ogg +0 -0
- package/dist/web/assets/intro-drums-Dt9QO534.ogg +0 -0
- package/dist/web/assets/intro-harmony-DBsMG9jJ.ogg +0 -0
- package/dist/web/assets/intro-lead-DWcWS1ia.ogg +0 -0
- package/dist/web/assets/jar-coin-rtCvspuq.ogg +0 -0
- package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/web/assets/ledger-tick-C1rQgQGX.ogg +0 -0
- package/dist/web/assets/night-B_bMOZcf.ogg +0 -0
- package/dist/web/assets/night-bass-B-7Ay9ME.ogg +0 -0
- package/dist/web/assets/night-drums-zEtqWXX3.ogg +0 -0
- package/dist/web/assets/night-harmony-C5Ix2yce.ogg +0 -0
- package/dist/web/assets/night-lead-B7KMlRyj.ogg +0 -0
- package/dist/web/assets/ourturn-DX78hTEz.ogg +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-400-normal-Dhut76fR.woff2 +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-500-normal-Bf-nb4oT.woff2 +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-600-normal-DLTa1BUW.woff2 +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-700-normal-CfpNZvy6.woff2 +0 -0
- package/dist/web/assets/reveal-BmWAGHih.ogg +0 -0
- package/dist/web/assets/review-split-Dac4zagw.ogg +0 -0
- package/dist/web/assets/shutter-uhz2Y9S9.ogg +0 -0
- package/dist/web/assets/soclose-CiUFR5St.ogg +0 -0
- package/dist/web/assets/stinger-TnnzHAMN.ogg +0 -0
- package/dist/web/assets/stomp-mzIk4cGm.ogg +0 -0
- package/dist/web/assets/syne-latin-700-normal-AF3Rs61n.woff2 +0 -0
- package/dist/web/assets/syne-latin-800-normal-EehdNYzx.woff2 +0 -0
- package/dist/web/assets/tension-BHvWG5ru.ogg +0 -0
- package/dist/web/assets/tension-bass-4G-2qA9W.ogg +0 -0
- package/dist/web/assets/tension-drums-D7sdehJr.ogg +0 -0
- package/dist/web/assets/tension-harmony-FyPldmLb.ogg +0 -0
- package/dist/web/assets/tension-lead-C5uoFMR8.ogg +0 -0
- package/dist/web/assets/why-clock-Dzs1A_ym.ogg +0 -0
- package/dist/web/favicon.svg +1 -0
- package/dist/web/index.html +16 -0
- package/dist/web/licenses/OFL-Archivo.txt +93 -0
- package/dist/web/licenses/OFL-DelaGothic.txt +93 -0
- package/dist/web/licenses/OFL-MartianMono.txt +93 -0
- package/package.json +63 -6
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
import { buildDemoContent } from '../analytics/content/demo-corpus.js';
|
|
2
|
+
import { PhraseReview } from './phrase-review.js';
|
|
3
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
4
|
+
import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
|
|
5
|
+
import { createServer, STATUS_CODES } from 'node:http';
|
|
6
|
+
import { extname, join } from 'node:path';
|
|
7
|
+
import { assertNoPollutedKeys, isPlainObject, validateApiScanRequest, validateDiscoveryPlan, validateWrappedReport, } from '../report/validators.js';
|
|
8
|
+
const LOOPBACK = '127.0.0.1';
|
|
9
|
+
const TOKEN_BYTES = 32;
|
|
10
|
+
const BODY_LIMIT = 8 * 1024;
|
|
11
|
+
const REPORT_LIMIT = 16 * 1024 * 1024;
|
|
12
|
+
// The browser content UI: word counting chosen with the one-click start (scan request `countWords`), word stats in the
|
|
13
|
+
// film, and the phrase routes. In local mode the worker strips phrase candidates, so /api/content/phrases lists [].
|
|
14
|
+
const BROWSER_CONTENT_UI = true;
|
|
15
|
+
const SECURITY_HEADERS = {
|
|
16
|
+
'Content-Security-Policy': "default-src 'self'; script-src 'self'; script-src-attr 'none'; style-src 'self'; style-src-attr 'none'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self'; object-src 'none'; frame-ancestors 'none'; frame-src 'none'; worker-src 'none'; media-src 'none'; manifest-src 'none'; base-uri 'none'; form-action 'none'",
|
|
17
|
+
'Referrer-Policy': 'no-referrer',
|
|
18
|
+
'Cross-Origin-Opener-Policy': 'same-origin',
|
|
19
|
+
'Cross-Origin-Resource-Policy': 'same-origin',
|
|
20
|
+
'X-Content-Type-Options': 'nosniff',
|
|
21
|
+
'X-Frame-Options': 'DENY',
|
|
22
|
+
'X-DNS-Prefetch-Control': 'off',
|
|
23
|
+
'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',
|
|
24
|
+
'Cache-Control': 'no-store',
|
|
25
|
+
};
|
|
26
|
+
const MEDIA_TYPES = new Map([
|
|
27
|
+
['.html', 'text/html; charset=utf-8'],
|
|
28
|
+
['.js', 'text/javascript; charset=utf-8'],
|
|
29
|
+
['.css', 'text/css; charset=utf-8'],
|
|
30
|
+
['.woff2', 'font/woff2'],
|
|
31
|
+
['.svg', 'image/svg+xml'],
|
|
32
|
+
['.png', 'image/png'],
|
|
33
|
+
['.ico', 'image/x-icon'],
|
|
34
|
+
// The film's score: fetched with fetch() and decoded by Web Audio, so media-src stays 'none'.
|
|
35
|
+
['.ogg', 'audio/ogg'],
|
|
36
|
+
]);
|
|
37
|
+
const API_PATHS = new Set(['/api/session', '/api/scan', '/api/status', '/api/report', '/api/cancel', '/api/close',
|
|
38
|
+
'/api/content/sample', '/api/content/phrases', '/api/content/forget']);
|
|
39
|
+
// /api/scan accepts exactly these keys. `countWords` (required, strict boolean; see validateApiScanRequest) is the
|
|
40
|
+
// word-count choice, made with the same click that starts the scan; there is no separate consent round trip.
|
|
41
|
+
const SCAN_KEYS = new Set(['planId', 'candidateIds', 'investigatorInitials', 'countWords']);
|
|
42
|
+
const EMPTY_PROGRESS = {
|
|
43
|
+
currentHarness: null,
|
|
44
|
+
channelLabel: null,
|
|
45
|
+
filesDone: 0,
|
|
46
|
+
filesTotal: 0,
|
|
47
|
+
eventsProcessed: 0,
|
|
48
|
+
};
|
|
49
|
+
function loadStaticFiles(directory) {
|
|
50
|
+
const files = new Map();
|
|
51
|
+
function visit(dir, prefix) {
|
|
52
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
53
|
+
const absPath = join(dir, entry.name);
|
|
54
|
+
const urlPath = `${prefix}/${encodeURIComponent(entry.name)}`;
|
|
55
|
+
if (entry.isDirectory()) {
|
|
56
|
+
visit(absPath, urlPath);
|
|
57
|
+
}
|
|
58
|
+
else if (entry.isFile()) {
|
|
59
|
+
const contentType = MEDIA_TYPES.get(extname(entry.name));
|
|
60
|
+
if (contentType)
|
|
61
|
+
files.set(urlPath, { contentType, bytes: readFileSync(absPath) });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (!lstatSync(directory).isDirectory())
|
|
66
|
+
throw new Error('INVALID_STATIC_DIRECTORY');
|
|
67
|
+
visit(realpathSync(directory), '');
|
|
68
|
+
const index = files.get('/index.html');
|
|
69
|
+
if (index)
|
|
70
|
+
files.set('/', index);
|
|
71
|
+
if (!files.has('/favicon.ico')) {
|
|
72
|
+
const faviconSvg = files.get('/favicon.svg');
|
|
73
|
+
if (faviconSvg)
|
|
74
|
+
files.set('/favicon.ico', faviconSvg);
|
|
75
|
+
}
|
|
76
|
+
return files;
|
|
77
|
+
}
|
|
78
|
+
function singleHeader(request, name) {
|
|
79
|
+
const values = request.headersDistinct[name];
|
|
80
|
+
return values?.length === 1 ? values[0] : undefined;
|
|
81
|
+
}
|
|
82
|
+
function matchesBearer(request, token) {
|
|
83
|
+
const match = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(singleHeader(request, 'authorization') ?? '');
|
|
84
|
+
if (!match?.[1])
|
|
85
|
+
return false;
|
|
86
|
+
const bytes = Buffer.from(match[1], 'base64url');
|
|
87
|
+
return bytes.length === TOKEN_BYTES && bytes.toString('base64url') === match[1] && timingSafeEqual(bytes, token);
|
|
88
|
+
}
|
|
89
|
+
class BodyError extends Error {
|
|
90
|
+
status;
|
|
91
|
+
constructor(status, code) {
|
|
92
|
+
super(code);
|
|
93
|
+
this.status = status;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async function readJsonBody(request) {
|
|
97
|
+
const tooLarge = new BodyError(413, 'BODY_TOO_LARGE');
|
|
98
|
+
if (Number(singleHeader(request, 'content-length')) > BODY_LIMIT)
|
|
99
|
+
throw tooLarge;
|
|
100
|
+
const chunks = [];
|
|
101
|
+
let size = 0;
|
|
102
|
+
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
103
|
+
size += chunk.length;
|
|
104
|
+
if (size > BODY_LIMIT)
|
|
105
|
+
throw tooLarge;
|
|
106
|
+
chunks.push(chunk);
|
|
107
|
+
}
|
|
108
|
+
const body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)));
|
|
109
|
+
assertNoPollutedKeys(body);
|
|
110
|
+
if (!isPlainObject(body))
|
|
111
|
+
throw new Error('INVALID_BODY');
|
|
112
|
+
return body;
|
|
113
|
+
}
|
|
114
|
+
function serializeReport(report) {
|
|
115
|
+
const json = JSON.stringify(validateWrappedReport(report));
|
|
116
|
+
if (Buffer.byteLength(json) > REPORT_LIMIT)
|
|
117
|
+
throw new Error('REPORT_TOO_LARGE');
|
|
118
|
+
return json;
|
|
119
|
+
}
|
|
120
|
+
function sendJson(response, status, body) {
|
|
121
|
+
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
122
|
+
response.end(JSON.stringify(body));
|
|
123
|
+
}
|
|
124
|
+
function reject(response, status, errorCode, allow) {
|
|
125
|
+
response.setHeader('Connection', 'close');
|
|
126
|
+
if (allow)
|
|
127
|
+
response.setHeader('Allow', allow);
|
|
128
|
+
sendJson(response, status, { errorCode });
|
|
129
|
+
}
|
|
130
|
+
export function reissueBootstrapToken(server) {
|
|
131
|
+
return server.reissueBootstrapToken();
|
|
132
|
+
}
|
|
133
|
+
export async function startLocalServer(options) {
|
|
134
|
+
const { mode, demoProfileId, onExecuteScan, onClose, bootstrapTtlMs = 120_000, idleTtlMs = 15 * 60_000, absoluteTtlMs = 60 * 60_000, } = options;
|
|
135
|
+
const files = loadStaticFiles(options.staticDir);
|
|
136
|
+
const plan = validateDiscoveryPlan(options.plan);
|
|
137
|
+
const allowedIds = new Set(plan.candidates.map(({ candidateId }) => candidateId));
|
|
138
|
+
const harnessLabels = new Set(plan.candidates.flatMap(({ harness, displayName }) => [harness, displayName]));
|
|
139
|
+
const channelLabels = new Set(plan.candidates.map(({ channelLabel }) => channelLabel));
|
|
140
|
+
const review = new PhraseReview();
|
|
141
|
+
let demoSource = mode === 'demo' ? options.initialDemoReport : undefined;
|
|
142
|
+
let report;
|
|
143
|
+
let status = { state: 'awaiting-consent', progress: EMPTY_PROGRESS };
|
|
144
|
+
let scan;
|
|
145
|
+
let bootstrap;
|
|
146
|
+
let session;
|
|
147
|
+
let bootstrapDeadline = 0;
|
|
148
|
+
let idleDeadline = 0;
|
|
149
|
+
let absoluteDeadline = 0;
|
|
150
|
+
let bootstrapTimer;
|
|
151
|
+
let idleTimer;
|
|
152
|
+
let absoluteTimer;
|
|
153
|
+
let forceCloseTimer;
|
|
154
|
+
let closing = false;
|
|
155
|
+
let port = 0;
|
|
156
|
+
let authority = '';
|
|
157
|
+
let origin = '';
|
|
158
|
+
const server = createServer({
|
|
159
|
+
requireHostHeader: false,
|
|
160
|
+
headersTimeout: 10_000,
|
|
161
|
+
requestTimeout: 15_000,
|
|
162
|
+
connectionsCheckingInterval: 1_000,
|
|
163
|
+
});
|
|
164
|
+
server.maxConnections = 32;
|
|
165
|
+
server.setTimeout(15_000);
|
|
166
|
+
const closed = new Promise((resolve) => {
|
|
167
|
+
server.once('close', () => {
|
|
168
|
+
clearTimeout(forceCloseTimer);
|
|
169
|
+
resolve();
|
|
170
|
+
onClose?.();
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
function clearBootstrap() {
|
|
174
|
+
clearTimeout(bootstrapTimer);
|
|
175
|
+
bootstrap?.fill(0);
|
|
176
|
+
bootstrap = undefined;
|
|
177
|
+
}
|
|
178
|
+
function cancelScan() {
|
|
179
|
+
const active = scan;
|
|
180
|
+
scan = undefined;
|
|
181
|
+
active?.abort();
|
|
182
|
+
}
|
|
183
|
+
function clearSession() {
|
|
184
|
+
clearTimeout(idleTimer);
|
|
185
|
+
session?.fill(0);
|
|
186
|
+
session = undefined;
|
|
187
|
+
report = undefined;
|
|
188
|
+
review.clear();
|
|
189
|
+
status = { state: 'awaiting-consent', progress: EMPTY_PROGRESS };
|
|
190
|
+
cancelScan();
|
|
191
|
+
}
|
|
192
|
+
function close() {
|
|
193
|
+
if (!closing) {
|
|
194
|
+
closing = true;
|
|
195
|
+
clearTimeout(absoluteTimer);
|
|
196
|
+
clearBootstrap();
|
|
197
|
+
clearSession();
|
|
198
|
+
demoSource = undefined;
|
|
199
|
+
server.close();
|
|
200
|
+
server.closeIdleConnections();
|
|
201
|
+
forceCloseTimer = setTimeout(() => server.closeAllConnections(), 250);
|
|
202
|
+
forceCloseTimer.unref();
|
|
203
|
+
}
|
|
204
|
+
return closed;
|
|
205
|
+
}
|
|
206
|
+
function launchUrl() {
|
|
207
|
+
return bootstrap ? `${origin}/#token=${bootstrap.toString('base64url')}` : `${origin}/`;
|
|
208
|
+
}
|
|
209
|
+
function issueBootstrap() {
|
|
210
|
+
if (closing || performance.now() >= absoluteDeadline)
|
|
211
|
+
throw new Error('SERVER_CLOSED');
|
|
212
|
+
clearBootstrap();
|
|
213
|
+
clearSession();
|
|
214
|
+
if (demoSource) {
|
|
215
|
+
installReport(demoSource);
|
|
216
|
+
demoSource = report;
|
|
217
|
+
status = { state: 'ready', progress: EMPTY_PROGRESS };
|
|
218
|
+
}
|
|
219
|
+
bootstrap = randomBytes(TOKEN_BYTES);
|
|
220
|
+
bootstrapDeadline = performance.now() + bootstrapTtlMs;
|
|
221
|
+
bootstrapTimer = setTimeout(clearBootstrap, bootstrapTtlMs);
|
|
222
|
+
return launchUrl();
|
|
223
|
+
}
|
|
224
|
+
function refreshIdle() {
|
|
225
|
+
clearTimeout(idleTimer);
|
|
226
|
+
idleDeadline = performance.now() + idleTtlMs;
|
|
227
|
+
idleTimer = setTimeout(() => void close(), idleTtlMs);
|
|
228
|
+
}
|
|
229
|
+
const count = (value) => Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
|
230
|
+
function installReport(value) {
|
|
231
|
+
serializeReport(value);
|
|
232
|
+
report = review.take(value);
|
|
233
|
+
}
|
|
234
|
+
function forgetContent() {
|
|
235
|
+
review.clear();
|
|
236
|
+
if (!report?.content)
|
|
237
|
+
return;
|
|
238
|
+
const { content: _, ...metadata } = report;
|
|
239
|
+
const { content: __, ...receipt } = metadata.receipt;
|
|
240
|
+
report = { ...metadata, receipt };
|
|
241
|
+
if (mode === 'demo')
|
|
242
|
+
demoSource = report;
|
|
243
|
+
}
|
|
244
|
+
function beginScan(response, request, content) {
|
|
245
|
+
scan = new AbortController();
|
|
246
|
+
status = { state: 'scanning', progress: content ? { ...EMPTY_PROGRESS, label: 'Counting words…' } : EMPTY_PROGRESS };
|
|
247
|
+
sendJson(response, 202, status);
|
|
248
|
+
void executeScan(request, scan, content);
|
|
249
|
+
}
|
|
250
|
+
async function executeScan(request, controller, content) {
|
|
251
|
+
try {
|
|
252
|
+
const result = await onExecuteScan(request, (progress) => {
|
|
253
|
+
if (scan !== controller)
|
|
254
|
+
return;
|
|
255
|
+
status = {
|
|
256
|
+
state: 'scanning',
|
|
257
|
+
progress: {
|
|
258
|
+
currentHarness: progress.currentHarness && harnessLabels.has(progress.currentHarness) ? progress.currentHarness : null,
|
|
259
|
+
channelLabel: progress.channelLabel && channelLabels.has(progress.channelLabel) ? progress.channelLabel : null,
|
|
260
|
+
filesDone: count(progress.filesDone),
|
|
261
|
+
filesTotal: count(progress.filesTotal),
|
|
262
|
+
eventsProcessed: count(progress.eventsProcessed),
|
|
263
|
+
...(content ? { label: 'Counting words…' } : {}),
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}, controller.signal, content);
|
|
267
|
+
if (scan !== controller)
|
|
268
|
+
return;
|
|
269
|
+
installReport(result);
|
|
270
|
+
if (mode === 'local' && !content)
|
|
271
|
+
forgetContent();
|
|
272
|
+
status = { state: 'ready', progress: status.progress };
|
|
273
|
+
}
|
|
274
|
+
catch {
|
|
275
|
+
if (scan === controller)
|
|
276
|
+
status = { state: 'error', progress: status.progress, errorCode: 'SCAN_FAILED' };
|
|
277
|
+
}
|
|
278
|
+
finally {
|
|
279
|
+
if (scan === controller)
|
|
280
|
+
scan = undefined;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function validTarget(request) {
|
|
284
|
+
return request.socket.remoteAddress === LOOPBACK && singleHeader(request, 'host') === authority &&
|
|
285
|
+
!['x-forwarded-host', 'x-forwarded-port', 'x-forwarded-proto', 'forwarded'].some((name) => name in request.headersDistinct) &&
|
|
286
|
+
request.url?.startsWith('/') === true && !request.url.startsWith('//') && !request.url.includes('\\');
|
|
287
|
+
}
|
|
288
|
+
async function handle(request, response) {
|
|
289
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS))
|
|
290
|
+
response.setHeader(name, value);
|
|
291
|
+
if (!validTarget(request))
|
|
292
|
+
return reject(response, 403, 'FORBIDDEN_AUTHORITY');
|
|
293
|
+
if (closing || performance.now() >= absoluteDeadline)
|
|
294
|
+
return reject(response, 503, 'SERVER_CLOSED');
|
|
295
|
+
if ('expect' in request.headersDistinct)
|
|
296
|
+
return reject(response, 417, 'EXPECTATION_FAILED');
|
|
297
|
+
const path = request.url;
|
|
298
|
+
if (!BROWSER_CONTENT_UI && path.startsWith('/api/content/'))
|
|
299
|
+
return reject(response, 404, 'NOT_FOUND');
|
|
300
|
+
if (!path.startsWith('/api/')) {
|
|
301
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
302
|
+
return reject(response, 405, 'METHOD_NOT_ALLOWED', 'GET, HEAD');
|
|
303
|
+
}
|
|
304
|
+
const file = files.get(path);
|
|
305
|
+
if (!file || 'service-worker' in request.headersDistinct)
|
|
306
|
+
return reject(response, 404, 'NOT_FOUND');
|
|
307
|
+
response.writeHead(200, { 'Content-Type': file.contentType, 'Content-Length': file.bytes.length });
|
|
308
|
+
response.end(request.method === 'HEAD' ? undefined : file.bytes);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (request.method !== 'POST')
|
|
312
|
+
return reject(response, 405, 'METHOD_NOT_ALLOWED', 'POST');
|
|
313
|
+
if (singleHeader(request, 'origin') !== origin || singleHeader(request, 'sec-fetch-site') !== 'same-origin') {
|
|
314
|
+
return reject(response, 403, 'FORBIDDEN_ORIGIN');
|
|
315
|
+
}
|
|
316
|
+
if (!/^application\/json(?:\s*;.*)?$/i.test(singleHeader(request, 'content-type') ?? '')) {
|
|
317
|
+
return reject(response, 415, 'UNSUPPORTED_MEDIA_TYPE');
|
|
318
|
+
}
|
|
319
|
+
if (!API_PATHS.has(path))
|
|
320
|
+
return reject(response, 404, 'NOT_FOUND');
|
|
321
|
+
const isBootstrap = path === '/api/session';
|
|
322
|
+
const token = isBootstrap ? bootstrap : session;
|
|
323
|
+
const currentToken = () => isBootstrap ? bootstrap : session;
|
|
324
|
+
const expired = () => performance.now() >= Math.min(isBootstrap ? bootstrapDeadline : idleDeadline, absoluteDeadline);
|
|
325
|
+
if (!token || expired() || !matchesBearer(request, token))
|
|
326
|
+
return reject(response, 401, 'INVALID_TOKEN');
|
|
327
|
+
let body;
|
|
328
|
+
let scanRequest;
|
|
329
|
+
try {
|
|
330
|
+
body = await readJsonBody(request);
|
|
331
|
+
if (path === '/api/scan') {
|
|
332
|
+
scanRequest = validateApiScanRequest(body, plan.planId, allowedIds);
|
|
333
|
+
if (Object.keys(body).some((key) => !SCAN_KEYS.has(key))) {
|
|
334
|
+
throw new BodyError(400, 'INVALID_SCAN_REQUEST');
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
if (response.destroyed)
|
|
340
|
+
return;
|
|
341
|
+
if (error instanceof BodyError)
|
|
342
|
+
return reject(response, error.status, error.message);
|
|
343
|
+
return reject(response, 400, 'INVALID_REQUEST');
|
|
344
|
+
}
|
|
345
|
+
if (token !== currentToken() || expired())
|
|
346
|
+
return reject(response, 401, 'INVALID_TOKEN');
|
|
347
|
+
if (isBootstrap) {
|
|
348
|
+
clearBootstrap();
|
|
349
|
+
session = randomBytes(TOKEN_BYTES);
|
|
350
|
+
refreshIdle();
|
|
351
|
+
const result = {
|
|
352
|
+
sessionToken: session.toString('base64url'), mode, demoProfileId, plan, demoReportReady: mode === 'demo' && report !== undefined,
|
|
353
|
+
contentUi: BROWSER_CONTENT_UI,
|
|
354
|
+
};
|
|
355
|
+
return sendJson(response, 200, result);
|
|
356
|
+
}
|
|
357
|
+
refreshIdle();
|
|
358
|
+
switch (path) {
|
|
359
|
+
case '/api/scan': {
|
|
360
|
+
if (status.state === 'scanning')
|
|
361
|
+
return sendJson(response, 202, status);
|
|
362
|
+
const canStart = status.state === 'awaiting-consent' || status.state === 'cancelled' || status.state === 'error';
|
|
363
|
+
if (!canStart || !scanRequest)
|
|
364
|
+
return reject(response, 409, 'SCAN_NOT_AVAILABLE');
|
|
365
|
+
// the choice travels with the scan request; only `=== true` counts, and never with the browser UI off
|
|
366
|
+
if (scanRequest.countWords === true) {
|
|
367
|
+
if (!BROWSER_CONTENT_UI)
|
|
368
|
+
return reject(response, 404, 'NOT_FOUND');
|
|
369
|
+
// demo mode never reads files: the choice is ignored there
|
|
370
|
+
if (mode === 'local')
|
|
371
|
+
return beginScan(response, scanRequest, true);
|
|
372
|
+
}
|
|
373
|
+
return beginScan(response, scanRequest);
|
|
374
|
+
}
|
|
375
|
+
case '/api/status':
|
|
376
|
+
return sendJson(response, 200, status);
|
|
377
|
+
case '/api/report':
|
|
378
|
+
if (status.state !== 'ready' || report === undefined)
|
|
379
|
+
return reject(response, 409, 'REPORT_NOT_READY');
|
|
380
|
+
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
381
|
+
response.end(serializeReport(review.withKept(report)));
|
|
382
|
+
return;
|
|
383
|
+
case '/api/content/sample': {
|
|
384
|
+
if (Object.keys(body).length)
|
|
385
|
+
return reject(response, 400, 'INVALID_SAMPLE_REQUEST');
|
|
386
|
+
const { private: _, ...content } = buildDemoContent(demoProfileId ?? 'night-owl', plan.timezone);
|
|
387
|
+
return sendJson(response, 200, { content });
|
|
388
|
+
}
|
|
389
|
+
case '/api/content/phrases': {
|
|
390
|
+
if (!report?.content || status.state !== 'ready')
|
|
391
|
+
return reject(response, 409, 'CONTENT_NOT_READY');
|
|
392
|
+
const { action, id } = body;
|
|
393
|
+
if ((action === 'list' || action === 'hide-all' || action === 'finalize') && Object.keys(body).length === 1) {
|
|
394
|
+
if (action === 'list')
|
|
395
|
+
return sendJson(response, 200, { candidates: review.list() });
|
|
396
|
+
if (action === 'finalize') {
|
|
397
|
+
review.finalize();
|
|
398
|
+
return sendJson(response, 200, { ok: true });
|
|
399
|
+
}
|
|
400
|
+
review.clear();
|
|
401
|
+
return sendJson(response, 200, { ok: true });
|
|
402
|
+
}
|
|
403
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(id) || Object.keys(body).length !== 2) {
|
|
404
|
+
return reject(response, 400, 'INVALID_PHRASE_REQUEST');
|
|
405
|
+
}
|
|
406
|
+
if (action === 'reveal') {
|
|
407
|
+
const candidate = review.reveal(id);
|
|
408
|
+
return candidate ? sendJson(response, 200, { candidate }) : reject(response, 404, 'PHRASE_NOT_FOUND');
|
|
409
|
+
}
|
|
410
|
+
if (action === 'keep')
|
|
411
|
+
return review.keep(id) ? sendJson(response, 200, { ok: true }) : reject(response, 409, 'PHRASE_NOT_REVEALED');
|
|
412
|
+
if (action === 'hide')
|
|
413
|
+
return review.hide(id) ? sendJson(response, 200, { ok: true }) : reject(response, 404, 'PHRASE_NOT_FOUND');
|
|
414
|
+
return reject(response, 400, 'INVALID_PHRASE_REQUEST');
|
|
415
|
+
}
|
|
416
|
+
case '/api/content/forget':
|
|
417
|
+
if (Object.keys(body).length)
|
|
418
|
+
return reject(response, 400, 'INVALID_FORGET_REQUEST');
|
|
419
|
+
if (scan && status.progress.label) {
|
|
420
|
+
cancelScan();
|
|
421
|
+
status = { state: 'cancelled', progress: EMPTY_PROGRESS };
|
|
422
|
+
}
|
|
423
|
+
forgetContent();
|
|
424
|
+
return sendJson(response, 200, { ok: true });
|
|
425
|
+
case '/api/cancel':
|
|
426
|
+
if (scan) {
|
|
427
|
+
cancelScan();
|
|
428
|
+
status = { state: 'cancelled', progress: status.progress };
|
|
429
|
+
}
|
|
430
|
+
return sendJson(response, 200, { ok: true });
|
|
431
|
+
case '/api/close':
|
|
432
|
+
response.setHeader('Connection', 'close');
|
|
433
|
+
sendJson(response, 200, { ok: true });
|
|
434
|
+
void close();
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function dispatch(request, response) {
|
|
438
|
+
void handle(request, response).catch(() => {
|
|
439
|
+
if (!response.headersSent && !response.destroyed)
|
|
440
|
+
reject(response, 500, 'SERVER_ERROR');
|
|
441
|
+
else
|
|
442
|
+
response.destroy();
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
server.on('request', dispatch);
|
|
446
|
+
server.on('checkContinue', dispatch);
|
|
447
|
+
server.on('checkExpectation', dispatch);
|
|
448
|
+
const rawError = (code) => [
|
|
449
|
+
`HTTP/1.1 ${code} ${STATUS_CODES[code]}`,
|
|
450
|
+
...Object.entries(SECURITY_HEADERS).map(([name, value]) => `${name}: ${value}`),
|
|
451
|
+
'Connection: close',
|
|
452
|
+
'Content-Length: 0',
|
|
453
|
+
'',
|
|
454
|
+
'',
|
|
455
|
+
].join('\r\n');
|
|
456
|
+
server.on('clientError', (error, socket) => {
|
|
457
|
+
if (socket.writable && error.code !== 'ECONNRESET')
|
|
458
|
+
socket.end(rawError(400));
|
|
459
|
+
else
|
|
460
|
+
socket.destroy();
|
|
461
|
+
});
|
|
462
|
+
server.on('upgrade', (request, socket) => socket.end(rawError(validTarget(request) ? 405 : 403)));
|
|
463
|
+
server.on('connect', (request, socket) => socket.end(rawError(validTarget(request) ? 405 : 403)));
|
|
464
|
+
await new Promise((resolve, rejectListen) => {
|
|
465
|
+
server.once('error', rejectListen);
|
|
466
|
+
server.listen({ host: LOOPBACK, port: options.port ?? 0, exclusive: true }, () => {
|
|
467
|
+
server.off('error', rejectListen);
|
|
468
|
+
resolve();
|
|
469
|
+
});
|
|
470
|
+
});
|
|
471
|
+
const address = server.address();
|
|
472
|
+
if (address === null || typeof address === 'string')
|
|
473
|
+
throw new Error('INVALID_LISTENER_ADDRESS');
|
|
474
|
+
port = address.port;
|
|
475
|
+
authority = `${LOOPBACK}:${port}`;
|
|
476
|
+
origin = `http://${authority}`;
|
|
477
|
+
absoluteDeadline = performance.now() + absoluteTtlMs;
|
|
478
|
+
absoluteTimer = setTimeout(() => void close(), absoluteTtlMs);
|
|
479
|
+
issueBootstrap();
|
|
480
|
+
return { port, get launchUrl() { return launchUrl(); }, closed, close, reissueBootstrapToken: issueBootstrap };
|
|
481
|
+
}
|