ravensight-playtest 0.12.0 → 0.13.1

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,316 @@
1
+ import { classifyRequest } from './network.js';
2
+ import { addSecret } from '../redaction.js';
3
+
4
+ /**
5
+ * The browser half of a live URL playtest (CONTRACT.md 6.2 and 6.3): the
6
+ * scripted sign-in in a context of its own, and the masking every played
7
+ * page gets. Nothing here writes a file or a log line: the sign-in context has
8
+ * no video, no tracing, no screenshot and no step log, and the outcome it
9
+ * answers carries a code and a host, never a value.
10
+ */
11
+
12
+ /** How long the sign-in waits for a signed-in page after submitting. */
13
+ export const SIGN_IN_TIMEOUT_MS = 30000;
14
+ /** How long it waits for the sign-in form to appear. */
15
+ export const FIELD_WAIT_MS = 10000;
16
+ /** How long the site's start page may take to answer. */
17
+ export const LOAD_TIMEOUT_MS = 30000;
18
+
19
+ /** What a masked email and password read as on screen. */
20
+ export const MASKED_EMAIL = 'test account';
21
+ export const MASKED_PASSWORD = '••••••';
22
+
23
+ /**
24
+ * A live site run that could not start: the sign-in failed or the site did
25
+ * not load. Its message is the plain sentence the report and the run's reason
26
+ * carry; `code` is the contract's outcome code.
27
+ */
28
+ export class LiveSiteError extends Error {
29
+ constructor(code, message, signIn = null) {
30
+ super(message);
31
+ this.name = 'LiveSiteError';
32
+ this.code = code;
33
+ this.liveSite = true;
34
+ this.plainReason = true;
35
+ this.signIn = signIn;
36
+ }
37
+ }
38
+
39
+ /** The plain sentence for each outcome: what happened and what to change. */
40
+ export function outcomeMessage(code, { url = '', host = '', detail = '' } = {}) {
41
+ switch (code) {
42
+ case 'sign_in_fields_not_found':
43
+ return `Sign in failed: no email and password fields were found on ${url}. Pass --sign-in-url with the page that has the sign-in form, or --sign-in-selectors naming its fields. Nothing was played.`;
44
+ case 'sign_in_refused':
45
+ return 'Sign in failed: the site kept its sign-in form after the test account\'s email and password were sent, so it did not accept them. Check the test account signs in by hand, and that --login-password-env names the variable that holds its password. Nothing was played.';
46
+ case 'sign_in_timeout':
47
+ return 'Sign in failed: the site showed no signed-in page within 30 seconds, twice. Pass --sign-in-selectors with a "signedIn" selector that only the signed-in page shows, such as {"signedIn": "text=Sign out"}. Nothing was played.';
48
+ case 'sign_in_left_verified_hosts':
49
+ return `Sign in failed: signing in went to ${host || 'another host'}, which is not the site's own host (an outside sign-in service). Sign in with a test user's session instead: --session-cookie-env or --session-header-env. Nothing was played.`;
50
+ case 'session_expired':
51
+ return 'Sign in failed: the test user\'s session has expired. Paste a fresh one and run this again. Nothing was played.';
52
+ case 'site_unreachable':
53
+ return `The site did not load: ${url}${detail ? ` (${detail})` : ''}. Check it is up and reachable from this machine, then run this again. Nothing was played.`;
54
+ default:
55
+ return 'Signed in.';
56
+ }
57
+ }
58
+
59
+ /** The first line of an error, without the call log Playwright appends. */
60
+ function shortError(error) {
61
+ return String((error && error.message) || error || '').split('\n')[0].replace(/^page\.goto:\s*/, '').slice(0, 160);
62
+ }
63
+
64
+ /**
65
+ * Load an address the way the sign-in and the play context do. A failed load
66
+ * or a server error is `site_unreachable`.
67
+ *
68
+ * @returns {Promise<{ok: boolean, detail?: string}>}
69
+ */
70
+ export async function loadSite(page, url, timeout = LOAD_TIMEOUT_MS) {
71
+ try {
72
+ const response = await page.goto(url, { waitUntil: 'domcontentloaded', timeout });
73
+ if (response && response.status() >= 500) return { ok: false, detail: `it answered ${response.status()}` };
74
+ return { ok: true };
75
+ } catch (error) {
76
+ return { ok: false, detail: shortError(error) };
77
+ }
78
+ }
79
+
80
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
81
+
82
+ async function firstVisible(page, selectors) {
83
+ for (const selector of selectors) {
84
+ try {
85
+ const locator = typeof selector === 'string' ? page.locator(selector) : selector(page);
86
+ const visible = locator.filter({ visible: true }).first();
87
+ if (await visible.count() > 0) return visible;
88
+ } catch {
89
+ // A selector this page cannot parse is skipped.
90
+ }
91
+ }
92
+ return null;
93
+ }
94
+
95
+ const EMAIL_SELECTORS = Object.freeze([
96
+ 'input[type=email]',
97
+ 'input[autocomplete=username]', 'input[autocomplete=email]',
98
+ 'input[name*=email i]', 'input[id*=email i]',
99
+ 'input[name*=user i]:not([type=password]):not([type=hidden])', 'input[id*=user i]:not([type=password]):not([type=hidden])',
100
+ 'input[name*=login i]:not([type=password]):not([type=hidden])', 'input[id*=login i]:not([type=password]):not([type=hidden])',
101
+ page => page.getByLabel(/email|user|login/i)
102
+ ]);
103
+
104
+ /** The email and password fields, waited for up to `waitMs`. */
105
+ async function findFields(page, selectors, waitMs) {
106
+ const deadline = Date.now() + waitMs;
107
+ for (;;) {
108
+ const password = await firstVisible(page, selectors.password ? [selectors.password] : ['input[type=password]']);
109
+ const email = await firstVisible(page, selectors.email ? [selectors.email] : EMAIL_SELECTORS);
110
+ if (password && email) return { email, password };
111
+ if (Date.now() >= deadline) return null;
112
+ await sleep(250);
113
+ }
114
+ }
115
+
116
+ async function passwordVisible(page, selectors) {
117
+ return Boolean(await firstVisible(page, selectors.password ? [selectors.password] : ['input[type=password]']));
118
+ }
119
+
120
+ const ERROR_SELECTORS = Object.freeze(['[role=alert]', '[aria-live=assertive]', '[aria-invalid=true]', '.error', '.errors', '.alert-danger', '.invalid-feedback', '.form-error']);
121
+ const ERROR_TEXT = /(invalid|incorrect|wrong|unknown|not recognised|not recognized|does not match|did not match)[^.\n]{0,40}(email|password|credentials|user|login|account)|(email|password|credentials|login)[^.\n]{0,40}(invalid|incorrect|wrong|does not match|did not match)|(sign.?in|log.?in) failed|try again/i;
122
+
123
+ /** Whether the page shows a sign-in error near its form. */
124
+ async function errorShown(page) {
125
+ for (const selector of ERROR_SELECTORS) {
126
+ try {
127
+ const shown = page.locator(selector).filter({ visible: true });
128
+ const count = await shown.count();
129
+ for (let i = 0; i < Math.min(count, 5); i += 1) {
130
+ const text = (await shown.nth(i).innerText({ timeout: 500 }).catch(() => '')).trim();
131
+ if (text || selector === '[aria-invalid=true]') return true;
132
+ }
133
+ } catch {
134
+ // Not on this page.
135
+ }
136
+ }
137
+ const body = await page.locator('body').innerText({ timeout: 1000 }).catch(() => '');
138
+ return ERROR_TEXT.test(body);
139
+ }
140
+
141
+ function pathOf(url) {
142
+ try { return new URL(url).pathname; } catch { return ''; }
143
+ }
144
+
145
+ /**
146
+ * Wait for the signed-in page after a submit. Answers `signed_in`,
147
+ * `sign_in_refused`, `sign_in_left_verified_hosts` (with the host), or
148
+ * `stuck` when no signal came in time.
149
+ */
150
+ async function waitForSignedIn(page, { selectors, pathBefore, timeoutMs, watch, rules }) {
151
+ const deadline = Date.now() + timeoutMs;
152
+ for (;;) {
153
+ const current = page.url();
154
+ // An error page (a navigation that never reached a server) is neither the site nor a success.
155
+ const onWeb = /^https?:/.test(current);
156
+ const landed = classifyRequest(rules, { url: current, method: 'GET' });
157
+ if (onWeb && landed.action === 'block') return { code: 'sign_in_left_verified_hosts', host: landed.host };
158
+ // Success first: a signed-in page may itself load things from other hosts, which are blocked and are no failure.
159
+ if (onWeb && selectors.signedIn && await firstVisible(page, [selectors.signedIn])) return { code: 'signed_in' };
160
+ const formShown = await passwordVisible(page, selectors);
161
+ if (onWeb && !formShown && pathOf(current) !== pathBefore) return { code: 'signed_in' };
162
+ // Anything the route blocked since the submit, with no signed-in page: the sign-in went to another host
163
+ // (a redirect, or the form posting by script to a company-wide sign-in service).
164
+ if (watch.blocked) return { code: 'sign_in_left_verified_hosts', host: watch.blocked };
165
+ if (formShown && await errorShown(page)) {
166
+ // A blocked call can be what made the page show its error: name the host, not a refusal.
167
+ if (watch.blocked) return { code: 'sign_in_left_verified_hosts', host: watch.blocked };
168
+ return { code: 'sign_in_refused' };
169
+ }
170
+ if (Date.now() >= deadline) {
171
+ if (watch.blocked) return { code: 'sign_in_left_verified_hosts', host: watch.blocked };
172
+ return formShown && pathOf(page.url()) === pathBefore ? { code: 'sign_in_refused' } : { code: 'stuck' };
173
+ }
174
+ await sleep(250);
175
+ }
176
+ }
177
+
178
+ /**
179
+ * The scripted sign-in, in a context of its own with no recording of any
180
+ * kind. Answers the storage state the recorded play context starts from, or
181
+ * throws a LiveSiteError. The credential is read once and dropped when this
182
+ * returns.
183
+ *
184
+ * @param {Object} args
185
+ * @param {any} args.browser
186
+ * @param {Object} args.contextOptions viewport, touch and so on; never recordVideo
187
+ * @param {(context: any, hooks: {onBlocked: (host: string) => void}) => Promise<void>} args.prepareContext installs the route and the page's playtest identity
188
+ * @param {Object} args.liveSite from ./options.js
189
+ * @param {Object} args.rules from ./network.js networkRules
190
+ * @returns {Promise<{storageState: Object, outcome: Object}>}
191
+ */
192
+ export async function performSignIn({ browser, contextOptions = {}, prepareContext, liveSite, rules, timeoutMs = SIGN_IN_TIMEOUT_MS, fieldWaitMs = FIELD_WAIT_MS, loadTimeoutMs = LOAD_TIMEOUT_MS, now = () => Date.now() }) {
193
+ const started = now();
194
+ const { method, kind, selectors: given } = liveSite.signIn;
195
+ const selectors = given || { email: null, password: null, submit: null, signedIn: null };
196
+ const outcome = (code, extra = {}) => ({ method, ...(kind ? { kind } : {}), ok: code === 'signed_in', code, seconds: Math.round((now() - started) / 100) / 10, ...extra });
197
+ const fail = (code, details = {}) => {
198
+ const result = outcome(code, details.host ? { blockedHost: details.host } : {});
199
+ throw new LiveSiteError(code, outcomeMessage(code, details), result);
200
+ };
201
+ // Everything after a submit that the route blocks is the sign-in leaving the site's hosts.
202
+ const watch = { armed: false, blocked: null };
203
+ let credential = liveSite.signIn.credential();
204
+ const context = await browser.newContext({ ...contextOptions });
205
+ try {
206
+ await prepareContext(context, { onBlocked: host => { if (watch.armed && !watch.blocked) watch.blocked = host; } });
207
+ if (kind === 'cookie') {
208
+ const secure = new URL(liveSite.startUrl).protocol === 'https:';
209
+ await context.addCookies(credential.cookies.map(cookie => ({ name: cookie.name, value: cookie.value, domain: liveSite.startHost, path: '/', secure, httpOnly: true, sameSite: 'Lax' })));
210
+ }
211
+ const page = await context.newPage();
212
+ if (method === 'session') {
213
+ const loaded = await loadSite(page, liveSite.startUrl, loadTimeoutMs);
214
+ if (!loaded.ok) fail('site_unreachable', { url: liveSite.startUrl, detail: loaded.detail });
215
+ } else {
216
+ let lastStuck = false;
217
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
218
+ watch.armed = false;
219
+ watch.blocked = null;
220
+ const loaded = await loadSite(page, liveSite.signIn.signInUrl, loadTimeoutMs);
221
+ if (!loaded.ok) fail('site_unreachable', { url: liveSite.signIn.signInUrl, detail: loaded.detail });
222
+ const landed = classifyRequest(rules, { url: page.url(), method: 'GET' });
223
+ if (landed.action === 'block') fail('sign_in_left_verified_hosts', { host: landed.host });
224
+ const fields = await findFields(page, selectors, fieldWaitMs);
225
+ if (!fields) {
226
+ // The form was there the first time: a page without it now is a sign-in that went somewhere this step cannot see.
227
+ if (lastStuck) fail('sign_in_timeout');
228
+ fail('sign_in_fields_not_found', { url: liveSite.signIn.signInUrl });
229
+ }
230
+ await fields.email.fill(credential.email);
231
+ await fields.password.fill(credential.password);
232
+ const pathBefore = pathOf(page.url());
233
+ watch.armed = true;
234
+ if (selectors.submit) await page.locator(selectors.submit).filter({ visible: true }).first().click({ timeout: 10000 });
235
+ else await fields.password.press('Enter');
236
+ const result = await waitForSignedIn(page, { selectors, pathBefore, timeoutMs, watch, rules });
237
+ if (result.code === 'signed_in') break;
238
+ if (result.code !== 'stuck') fail(result.code, { host: result.host });
239
+ if (attempt === 2) fail('sign_in_timeout');
240
+ lastStuck = true;
241
+ }
242
+ }
243
+ const storageState = await context.storageState();
244
+ // The cookies the sign-in left are the test account's session: a credential too, so a page that
245
+ // prints one never puts it in a file or a model request (../redaction.js).
246
+ for (const cookie of storageState.cookies || []) addSecret(cookie.value);
247
+ return { storageState, outcome: outcome('signed_in') };
248
+ } finally {
249
+ credential = null;
250
+ await context.close().catch(() => {});
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Runs in every played page, before its own scripts: any text node, input
256
+ * value or readable attribute holding the test account's email (any case) is
257
+ * rewritten to "test account", and the password to six dots, and kept so by a
258
+ * MutationObserver and the input value setters, so the screen, the video and
259
+ * the page text the playtester reads never show them. Text drawn into a canvas
260
+ * or an image is not rewritten. Serialised by Playwright: it must not close
261
+ * over anything.
262
+ *
263
+ * @param {{email?: string|null, password?: string|null, emailLabel: string, passwordLabel: string}} secrets
264
+ */
265
+ export function maskSecretsInit(secrets) {
266
+ const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
267
+ const rules = [];
268
+ if (secrets.email) rules.push([new RegExp(escape(secrets.email), 'gi'), secrets.emailLabel]);
269
+ if (secrets.password) rules.push([new RegExp(escape(secrets.password), 'g'), secrets.passwordLabel]);
270
+ if (rules.length === 0) return;
271
+ const has = text => typeof text === 'string' && text.length > 0 && rules.some(([pattern]) => { pattern.lastIndex = 0; return pattern.test(text); });
272
+ const fix = text => rules.reduce((out, [pattern, label]) => out.replace(pattern, label), text);
273
+ const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE']);
274
+ const ATTRIBUTES = ['value', 'title', 'aria-label', 'aria-description', 'aria-valuetext', 'placeholder', 'alt'];
275
+ for (const proto of [globalThis.HTMLInputElement && HTMLInputElement.prototype, globalThis.HTMLTextAreaElement && HTMLTextAreaElement.prototype]) {
276
+ const descriptor = proto && Object.getOwnPropertyDescriptor(proto, 'value');
277
+ if (!descriptor || !descriptor.set) continue;
278
+ Object.defineProperty(proto, 'value', { ...descriptor, set(value) { descriptor.set.call(this, has(value) ? fix(value) : value); } });
279
+ }
280
+ function maskNode(node) {
281
+ if (!node) return;
282
+ if (node.nodeType === 3) {
283
+ if (node.parentNode && SKIP.has(node.parentNode.nodeName)) return;
284
+ if (has(node.data)) node.data = fix(node.data);
285
+ return;
286
+ }
287
+ if (node.nodeType !== 1 || SKIP.has(node.nodeName)) return;
288
+ for (const name of ATTRIBUTES) {
289
+ const value = node.getAttribute(name);
290
+ if (has(value)) node.setAttribute(name, fix(value));
291
+ }
292
+ if ((node.nodeName === 'INPUT' || node.nodeName === 'TEXTAREA') && has(node.value)) node.value = node.value;
293
+ if (node.shadowRoot) walk(node.shadowRoot);
294
+ }
295
+ function walk(root) {
296
+ if (!root) return;
297
+ if (root.nodeType === 1 || root.nodeType === 3) maskNode(root);
298
+ if (typeof root.querySelectorAll !== 'function' && root.nodeType !== 9 && root.nodeType !== 11) return;
299
+ const walker = document.createTreeWalker(root, 5 /* SHOW_ELEMENT | SHOW_TEXT */);
300
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) maskNode(node);
301
+ }
302
+ const observer = new MutationObserver(records => {
303
+ for (const record of records) {
304
+ if (record.type === 'childList') record.addedNodes.forEach(walk);
305
+ else maskNode(record.target);
306
+ }
307
+ });
308
+ observer.observe(document, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ATTRIBUTES });
309
+ const sweep = event => maskNode(event && event.target);
310
+ document.addEventListener('input', sweep, true);
311
+ document.addEventListener('change', sweep, true);
312
+ document.addEventListener('DOMContentLoaded', () => walk(document), { once: true });
313
+ walk(document);
314
+ }
315
+
316
+ export default { performSignIn, maskSecretsInit, loadSite, outcomeMessage, LiveSiteError, MASKED_EMAIL, MASKED_PASSWORD };
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Host rules for a live URL playtest: the CLI's copy of the platform's
3
+ * `src/services/urlPlaytest/hosts.js`, held to the same shared test vectors
4
+ * (../__fixtures__/host-vectors.json). Change the vectors first, then all three
5
+ * copies (server, cloud runner, this file).
6
+ *
7
+ * A host is a lower-case DNS name: ASCII, 2 to 127 labels of 1 to 63
8
+ * `[a-z0-9-]` characters not starting or ending with `-`, at most 253
9
+ * characters, no trailing dot, no port, no IP literal. Reserved and private
10
+ * names, and our own names, are refused.
11
+ */
12
+
13
+ const RESERVED_SUFFIXES = Object.freeze(['localhost', 'local', 'internal', 'test', 'example', 'invalid', 'home.arpa', 'arpa', 'onion']);
14
+ const OUR_NAMES = Object.freeze(['ravensight.io', 'realityse.com']);
15
+ const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
16
+ const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
17
+
18
+ const under = (host, name) => host === name || host.endsWith(`.${name}`);
19
+
20
+ /**
21
+ * The host in its one stored form, or null when it is not a host a playtest may
22
+ * be pointed at.
23
+ *
24
+ * @param {unknown} input
25
+ * @returns {string|null}
26
+ */
27
+ export function normalizeHost(input) {
28
+ if (typeof input !== 'string') return null;
29
+ let host = input.trim().toLowerCase();
30
+ if (host.endsWith('.')) host = host.slice(0, -1);
31
+ if (!host || host.length > 253) return null;
32
+ if (/[:[\]/@\s]/.test(host)) return null;
33
+ const labels = host.split('.');
34
+ if (labels.length < 2 || labels.length > 127) return null;
35
+ if (!labels.every(label => LABEL.test(label))) return null;
36
+ // An IP literal, or a name whose last label is all digits (no such top level domain exists).
37
+ if (/^\d+$/.test(labels[labels.length - 1])) return null;
38
+ if (RESERVED_SUFFIXES.some(suffix => under(host, suffix))) return null;
39
+ if (OUR_NAMES.some(name => under(host, name))) return null;
40
+ return host;
41
+ }
42
+
43
+ /** The refused IPv4 ranges (contract section 2), as [first octets as a number, prefix length]. */
44
+ const REFUSED_V4 = Object.freeze([
45
+ ['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16],
46
+ ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.0.2.0', 24], ['192.88.99.0', 24], ['192.168.0.0', 16],
47
+ ['198.18.0.0', 15], ['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4],
48
+ ['255.255.255.255', 32]
49
+ ].map(([base, bits]) => [ipv4Number(base), bits]));
50
+
51
+ function ipv4Number(ip) {
52
+ const match = IPV4.exec(String(ip));
53
+ if (!match) return null;
54
+ const parts = match.slice(1).map(Number);
55
+ if (parts.some(part => part > 255)) return null;
56
+ return ((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3];
57
+ }
58
+
59
+ /**
60
+ * Whether an address is a public IPv4 address. IPv6 is never used, so it is
61
+ * never public here.
62
+ *
63
+ * @param {unknown} ip
64
+ * @returns {boolean}
65
+ */
66
+ export function isPublicAddress(ip) {
67
+ const value = ipv4Number(ip);
68
+ if (value === null) return false;
69
+ return !REFUSED_V4.some(([base, bits]) => {
70
+ const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
71
+ return ((value & mask) >>> 0) === ((base & mask) >>> 0);
72
+ });
73
+ }
74
+
75
+ /**
76
+ * Whether a verified row covers a host: an exact row only itself, a wildcard
77
+ * row every name under its parent and never the parent.
78
+ *
79
+ * @param {string} host
80
+ * @param {Array<{host: string, wildcard: boolean}>} rows
81
+ * @returns {boolean}
82
+ */
83
+ export function coveredBy(host, rows = []) {
84
+ const name = normalizeHost(host);
85
+ if (!name) return false;
86
+ return rows.some(row => row && (row.wildcard ? name.endsWith(`.${row.host}`) : name === row.host));
87
+ }
88
+
89
+ /**
90
+ * Whether a URL's host is a local dev server on this machine or its network:
91
+ * loopback, a private or other non-public IPv4 address, IPv6 loopback or a
92
+ * unique local or link local address, or a `localhost`, `.localhost`, `.local`
93
+ * or `.test` name. Such a start URL needs no domain check.
94
+ *
95
+ * @param {unknown} hostname
96
+ * @returns {boolean}
97
+ */
98
+ export function isLocalHost(hostname) {
99
+ if (typeof hostname !== 'string' || !hostname) return false;
100
+ const host = hostname.trim().toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
101
+ if (!host) return false;
102
+ if (ipv4Number(host) !== null) return !isPublicAddress(host);
103
+ if (host.includes(':')) return host === '::1' || /^f[cd][0-9a-f]{0,2}:/.test(host) || /^fe[89ab][0-9a-f]?:/.test(host);
104
+ return ['localhost', 'local', 'test'].some(suffix => under(host, suffix));
105
+ }
106
+
107
+ export default { normalizeHost, isPublicAddress, coveredBy, isLocalHost };
@@ -0,0 +1,117 @@
1
+ import { isLocalHost } from './hosts.js';
2
+
3
+ /**
4
+ * The browser's network rules on a live site (CONTRACT.md 6.1, the local
5
+ * column). One route handler, for the sign-in context and the play context,
6
+ * decides every request:
7
+ *
8
+ * 1. the start URL's host continues (https only on a public host; a local dev
9
+ * server may also reach loopback and private addresses);
10
+ * 2. a documented ingest call to a Ravensight origin continues, and every
11
+ * `POST /api/v1/session` gets the run's `X-Ravensight-Playtest` header;
12
+ * 3. any other path on a Ravensight origin is answered 403 `sandbox_refused`
13
+ * and counted by path: a playtest is never a website visitor;
14
+ * 4. anything else is aborted (a top-level navigation is answered 204 so the
15
+ * page stays) and counted by host for the report.
16
+ *
17
+ * Rules 2 and 3 are decided before rule 1, so a Ravensight API running on
18
+ * loopback beside a local dev server is still held to them.
19
+ */
20
+
21
+ /** Our ingest origin. The CLI's own API origin is added beside it for a run against another API. */
22
+ export const RAVENSIGHT_INGEST_ORIGIN = 'https://api.ravensight.io';
23
+
24
+ /** The documented ingest calls: method and exact path, no query. */
25
+ const INGEST_CALLS = Object.freeze([['GET', '/api/v1/settings'], ['POST', '/api/v1/session'], ['POST', '/api/v1/track'], ['POST', '/api/v1/track/batch']]);
26
+
27
+ /**
28
+ * @param {string} method
29
+ * @param {URL} url
30
+ * @returns {boolean}
31
+ */
32
+ export function isIngestCall(method, url) {
33
+ if (url.search) return false;
34
+ const verb = String(method || 'GET').toUpperCase();
35
+ // A browser's CORS preflight for one of them is part of the same call.
36
+ if (verb === 'OPTIONS') return INGEST_CALLS.some(([, path]) => path === url.pathname);
37
+ return INGEST_CALLS.some(([m, path]) => m === verb && path === url.pathname);
38
+ }
39
+
40
+ /**
41
+ * @param {{startUrl: string, local: boolean, extraOrigins?: Array<string>}} options
42
+ * @returns {{startHost: string, local: boolean, ravensightOrigins: Set<string>}}
43
+ */
44
+ export function networkRules({ startUrl, local, extraOrigins = [] }) {
45
+ const start = new URL(startUrl);
46
+ const origins = new Set([RAVENSIGHT_INGEST_ORIGIN]);
47
+ for (const origin of extraOrigins) {
48
+ try { origins.add(new URL(origin).origin); } catch { /* not an origin */ }
49
+ }
50
+ return { startHost: start.hostname, local: Boolean(local), ravensightOrigins: origins };
51
+ }
52
+
53
+ /**
54
+ * What the route does with one request.
55
+ *
56
+ * @param {ReturnType<typeof networkRules>} rules
57
+ * @param {{url: string, method: string}} request
58
+ * @returns {{action: 'continue'|'ingest'|'refuse'|'block', host: string|null, path: string|null, startHost: boolean, playtestHeader: boolean}}
59
+ */
60
+ export function classifyRequest(rules, { url, method }) {
61
+ let parsed;
62
+ try { parsed = new URL(url); } catch { return { action: 'block', host: 'an address that is not a web page', path: null, startHost: false, playtestHeader: false }; }
63
+ const answer = { host: parsed.hostname, path: parsed.pathname, startHost: false, playtestHeader: false };
64
+ // data:, blob: and the browser's own pages never leave the machine.
65
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return { ...answer, action: 'continue' };
66
+ if (rules.ravensightOrigins.has(parsed.origin)) {
67
+ if (isIngestCall(method, parsed)) {
68
+ return { ...answer, action: 'ingest', playtestHeader: String(method).toUpperCase() === 'POST' && parsed.pathname === '/api/v1/session' };
69
+ }
70
+ return { ...answer, action: 'refuse' };
71
+ }
72
+ if (parsed.hostname === rules.startHost && (rules.local || parsed.protocol === 'https:')) return { ...answer, action: 'continue', startHost: true };
73
+ if (rules.local && isLocalHost(parsed.hostname)) return { ...answer, action: 'continue' };
74
+ return { ...answer, action: 'block' };
75
+ }
76
+
77
+ /** The most distinct hosts and paths one run keeps counts for. */
78
+ const MAX_KEYS = 200;
79
+
80
+ /** Counts of blocked hosts and refused Ravensight paths, for usage.json `safety` and the report. */
81
+ export function createSafetyCounts() {
82
+ const hosts = new Map();
83
+ const paths = new Map();
84
+ const bump = (map, key) => {
85
+ if (!map.has(key) && map.size >= MAX_KEYS) return;
86
+ map.set(key, (map.get(key) || 0) + 1);
87
+ };
88
+ return {
89
+ block(host) { bump(hosts, String(host || 'unknown')); },
90
+ refuse(path) { bump(paths, String(path || '/')); },
91
+ toJSON() {
92
+ const sorted = map => [...map].sort((a, b) => b[1] - a[1]);
93
+ return {
94
+ blockedHosts: sorted(hosts).map(([host, requests]) => ({ host, requests })),
95
+ refusedPaths: sorted(paths).map(([path, requests]) => ({ path, requests }))
96
+ };
97
+ }
98
+ };
99
+ }
100
+
101
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
102
+
103
+ /**
104
+ * The report's lines for what the route kept from the site.
105
+ *
106
+ * @param {{blockedHosts: Array, refusedPaths: Array}} safety
107
+ * @returns {Array<string>}
108
+ */
109
+ export function safetyLines(safety) {
110
+ if (!safety) return [];
111
+ return [
112
+ ...(safety.blockedHosts || []).map(entry => `Not a verified host: ${entry.host} (${plural(entry.requests, 'request')}). Verify it to let playtests load it.`),
113
+ ...(safety.refusedPaths || []).map(entry => `Refused a Ravensight call that is not game analytics: ${entry.path} (${plural(entry.requests, 'request')}). A playtest is never counted as a website visitor or a form response.`)
114
+ ];
115
+ }
116
+
117
+ export default { classifyRequest, networkRules, isIngestCall, createSafetyCounts, safetyLines, RAVENSIGHT_INGEST_ORIGIN };