ravensight-playtest 0.12.0 → 0.13.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 +82 -0
- package/docs/MOBILE.md +1 -1
- package/package.json +3 -3
- package/src/api/client.js +10 -1
- package/src/cli.js +29 -2
- package/src/commands/hosted.js +15 -0
- package/src/commands/run.js +89 -8
- package/src/run/anygame/index.js +1 -1
- package/src/run/args.js +24 -0
- package/src/run/budgetReserve.js +70 -8
- package/src/run/choiceCheck.js +26 -7
- package/src/run/drivers/web.js +118 -5
- package/src/run/livesite/browser.js +316 -0
- package/src/run/livesite/hosts.js +107 -0
- package/src/run/livesite/network.js +117 -0
- package/src/run/livesite/options.js +167 -0
- package/src/run/livesite/resolver.js +78 -0
- package/src/run/livesite/run.js +113 -0
- package/src/run/personaLoop.js +207 -24
- package/src/run/proxyClient.js +5 -1
- package/src/run/redaction.js +191 -0
- package/src/run/report.js +5 -2
- package/src/run/resume.js +30 -3
- package/src/run/state.js +3 -1
- package/src/run/tooFast.js +116 -0
- package/src/run/transcript.js +3 -1
- package/src/run/usage.js +3 -1
|
@@ -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 };
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { addSecret, MIN_SECRET_CHARS } from '../redaction.js';
|
|
2
|
+
import { isLocalHost, normalizeHost } from './hosts.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A live URL playtest's options (CONTRACT.md section 7), read and checked
|
|
6
|
+
* before anything is priced or registered.
|
|
7
|
+
*
|
|
8
|
+
* Every secret is read from an environment variable whose name is on the
|
|
9
|
+
* command line, never from the command line itself, and joins the run's
|
|
10
|
+
* redaction list (../redaction.js) the moment it is read. What this answers
|
|
11
|
+
* holds no secret in any enumerable field: the values are behind
|
|
12
|
+
* `signIn.credential()`, so the options object can be logged or saved
|
|
13
|
+
* without carrying them.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** The sign-in selector keys the sign-in step reads. */
|
|
17
|
+
export const SELECTOR_KEYS = Object.freeze(['email', 'password', 'submit', 'signedIn']);
|
|
18
|
+
|
|
19
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
20
|
+
const MAX_SESSION_CHARS = 4096;
|
|
21
|
+
const MAX_PASSWORD_CHARS = 256;
|
|
22
|
+
const SIGN_IN_FLAGS = Object.freeze([
|
|
23
|
+
['loginEmail', '--login-email'], ['loginPasswordEnv', '--login-password-env'], ['sessionCookieEnv', '--session-cookie-env'],
|
|
24
|
+
['sessionHeaderEnv', '--session-header-env'], ['signInUrl', '--sign-in-url'], ['signInSelectors', '--sign-in-selectors']
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
const fail = error => ({ error });
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Read one secret from the environment by name, or say why not (never with the value).
|
|
31
|
+
*
|
|
32
|
+
* @returns {{value?: string, error?: string}}
|
|
33
|
+
*/
|
|
34
|
+
function fromEnv(env, name, flag) {
|
|
35
|
+
if (!ENV_NAME.test(String(name || ''))) return { error: `${flag} takes an environment variable name, such as ${flag} MY_VAR, not a value.` };
|
|
36
|
+
if (!Object.prototype.hasOwnProperty.call(env || {}, name) || env[name] === undefined) return { error: `${flag}: the environment variable ${name} is not set.` };
|
|
37
|
+
if (String(env[name]) === '') return { error: `${flag}: the environment variable ${name} is empty.` };
|
|
38
|
+
return { value: String(env[name]) };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The start URL's place: local (a dev server) or public, or a refusal.
|
|
43
|
+
*
|
|
44
|
+
* @param {string} raw
|
|
45
|
+
* @returns {{url?: URL, local?: boolean, error?: string}}
|
|
46
|
+
*/
|
|
47
|
+
export function startUrl(raw) {
|
|
48
|
+
let url;
|
|
49
|
+
try { url = new URL(String(raw)); } catch { return { error: `--url ${JSON.stringify(String(raw))} is not a web address. Give the page to start on, such as --url https://play.example.com/.` }; }
|
|
50
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return { error: '--url must be an http or https address.' };
|
|
51
|
+
if (url.username || url.password) return { error: '--url must not carry a user name or password. Use --login-email and --login-password-env.' };
|
|
52
|
+
if (isLocalHost(url.hostname)) return { url, local: true };
|
|
53
|
+
if (!normalizeHost(url.hostname)) return { error: `--url ${url.hostname} is not a host a playtest can be pointed at. Use a public host name your game has verified, or a local dev server on localhost or a private address.` };
|
|
54
|
+
if (url.protocol !== 'https:') return { error: `--url on a public host must be https (${url.hostname}).` };
|
|
55
|
+
return { url, local: false };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function parseSelectors(raw) {
|
|
59
|
+
if (raw === undefined) return { selectors: Object.fromEntries(SELECTOR_KEYS.map(key => [key, null])) };
|
|
60
|
+
let value;
|
|
61
|
+
try { value = JSON.parse(String(raw)); } catch { return { error: '--sign-in-selectors must be JSON, such as {"submit": "button[type=submit]", "signedIn": "text=Sign out"}.' }; }
|
|
62
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return { error: '--sign-in-selectors must be a JSON object.' };
|
|
63
|
+
const extra = Object.keys(value).filter(key => !SELECTOR_KEYS.includes(key));
|
|
64
|
+
if (extra.length > 0) return { error: `--sign-in-selectors takes only email, password, submit and signedIn, not ${extra.join(', ')}.` };
|
|
65
|
+
const selectors = {};
|
|
66
|
+
for (const key of SELECTOR_KEYS) {
|
|
67
|
+
const entry = value[key];
|
|
68
|
+
if (entry === undefined || entry === null) { selectors[key] = null; continue; }
|
|
69
|
+
if (typeof entry !== 'string' || !entry.trim() || entry.length > 200) return { error: `--sign-in-selectors ${key} must be a CSS or text= selector of at most 200 characters.` };
|
|
70
|
+
selectors[key] = entry;
|
|
71
|
+
}
|
|
72
|
+
return { selectors };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** `a=b; c=d` as name and value pairs. */
|
|
76
|
+
export function parseCookieHeader(text) {
|
|
77
|
+
const cookies = [];
|
|
78
|
+
for (const part of String(text).split(';')) {
|
|
79
|
+
const trimmed = part.trim();
|
|
80
|
+
if (!trimmed) continue;
|
|
81
|
+
const at = trimmed.indexOf('=');
|
|
82
|
+
const name = at > 0 ? trimmed.slice(0, at).trim() : '';
|
|
83
|
+
if (!name || /[\s,;=]/.test(name)) return null;
|
|
84
|
+
cookies.push({ name, value: trimmed.slice(at + 1).trim() });
|
|
85
|
+
}
|
|
86
|
+
return cookies.length > 0 ? cookies : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The live site a run plays, from the parsed options and the environment, or
|
|
91
|
+
* the reason it cannot. `{ liveSite: null }` when no live URL flag was given.
|
|
92
|
+
*
|
|
93
|
+
* @param {Object} options
|
|
94
|
+
* @param {Object} env
|
|
95
|
+
* @returns {{liveSite?: Object|null, error?: string}}
|
|
96
|
+
*/
|
|
97
|
+
export function readLiveSite(options = {}, env = process.env) {
|
|
98
|
+
const signInFlags = SIGN_IN_FLAGS.filter(([key]) => options[key] !== undefined);
|
|
99
|
+
if (options.url === undefined) {
|
|
100
|
+
if (signInFlags.length > 0) return fail(`${signInFlags.map(([, flag]) => flag).join(', ')} sign${signInFlags.length === 1 ? 's' : ''} in to a live site: pass --url with the page to start on.`);
|
|
101
|
+
return { liveSite: null };
|
|
102
|
+
}
|
|
103
|
+
if (options.buildUrl !== undefined) return fail('Pass --url or --build-url, not both: --url plays a live site, --build-url a build.');
|
|
104
|
+
if (options.buildDir !== undefined) return fail('Pass --url or --build-dir, not both: --url plays a live site, --build-dir serves a build from this machine.');
|
|
105
|
+
const start = startUrl(options.url);
|
|
106
|
+
if (start.error) return fail(start.error);
|
|
107
|
+
const { url, local } = start;
|
|
108
|
+
|
|
109
|
+
const password = options.loginEmail !== undefined || options.loginPasswordEnv !== undefined;
|
|
110
|
+
const methods = [password, options.sessionCookieEnv !== undefined, options.sessionHeaderEnv !== undefined].filter(Boolean).length;
|
|
111
|
+
if (methods > 1) return fail('Choose one way to sign in: --login-email with --login-password-env, or --session-cookie-env, or --session-header-env.');
|
|
112
|
+
if (!password && options.signInUrl !== undefined) return fail('--sign-in-url is the page with the email and password form; it goes with --login-email and --login-password-env.');
|
|
113
|
+
if (!password && options.signInSelectors !== undefined) return fail('--sign-in-selectors names the sign-in form\'s fields; it goes with --login-email and --login-password-env.');
|
|
114
|
+
|
|
115
|
+
const base = { startUrl: url.toString(), startHost: url.hostname, startOrigin: url.origin, local };
|
|
116
|
+
if (password) {
|
|
117
|
+
if (options.loginEmail === undefined) return fail('--login-password-env needs --login-email with the test account\'s email.');
|
|
118
|
+
if (options.loginPasswordEnv === undefined) return fail('--login-email needs --login-password-env naming the environment variable that holds the test account\'s password.');
|
|
119
|
+
const email = String(options.loginEmail).trim();
|
|
120
|
+
if (!/^[^\s@]{1,64}@[^\s@]{1,253}$/.test(email)) return fail('--login-email must be the test account\'s email address.');
|
|
121
|
+
const read = fromEnv(env, options.loginPasswordEnv, '--login-password-env');
|
|
122
|
+
if (read.error) return fail(read.error);
|
|
123
|
+
if (read.value.length < MIN_SECRET_CHARS) return fail(`--login-password-env: use a test account password of at least ${MIN_SECRET_CHARS} characters, so it can be kept out of every file and model request.`);
|
|
124
|
+
if (read.value.length > MAX_PASSWORD_CHARS) return fail(`--login-password-env: the password is longer than ${MAX_PASSWORD_CHARS} characters.`);
|
|
125
|
+
let signInUrl = url.toString();
|
|
126
|
+
if (options.signInUrl !== undefined) {
|
|
127
|
+
let parsed;
|
|
128
|
+
try { parsed = new URL(String(options.signInUrl)); } catch { return fail('--sign-in-url is not a web address.'); }
|
|
129
|
+
if (parsed.hostname !== url.hostname || parsed.protocol !== url.protocol) return fail(`--sign-in-url must be on the same host as --url (${url.protocol}//${url.hostname}).`);
|
|
130
|
+
signInUrl = parsed.toString();
|
|
131
|
+
}
|
|
132
|
+
const parsedSelectors = parseSelectors(options.signInSelectors);
|
|
133
|
+
if (parsedSelectors.error) return fail(parsedSelectors.error);
|
|
134
|
+
// On the redaction list at once, before any other use.
|
|
135
|
+
addSecret(email, { insensitive: true });
|
|
136
|
+
addSecret(read.value);
|
|
137
|
+
const secret = { email, password: read.value };
|
|
138
|
+
return { liveSite: { ...base, signIn: { method: 'password', kind: null, signInUrl, selectors: parsedSelectors.selectors, credential: () => ({ ...secret }) } } };
|
|
139
|
+
}
|
|
140
|
+
if (options.sessionCookieEnv !== undefined) {
|
|
141
|
+
const read = fromEnv(env, options.sessionCookieEnv, '--session-cookie-env');
|
|
142
|
+
if (read.error) return fail(read.error);
|
|
143
|
+
if (read.value.length > MAX_SESSION_CHARS) return fail(`--session-cookie-env: the cookie is longer than ${MAX_SESSION_CHARS} characters.`);
|
|
144
|
+
const cookies = parseCookieHeader(read.value);
|
|
145
|
+
if (!cookies) return fail('--session-cookie-env: the variable must hold a Cookie header value, name=value pairs separated by semicolons.');
|
|
146
|
+
for (const cookie of cookies) addSecret(cookie.value);
|
|
147
|
+
return { liveSite: { ...base, signIn: { method: 'session', kind: 'cookie', signInUrl: null, selectors: null, credential: () => ({ cookies: cookies.map(cookie => ({ ...cookie })) }) } } };
|
|
148
|
+
}
|
|
149
|
+
if (options.sessionHeaderEnv !== undefined) {
|
|
150
|
+
const read = fromEnv(env, options.sessionHeaderEnv, '--session-header-env');
|
|
151
|
+
if (read.error) return fail(read.error);
|
|
152
|
+
const at = read.value.indexOf(':');
|
|
153
|
+
if (at <= 0) return fail('--session-header-env: the variable must hold one header as Name: value.');
|
|
154
|
+
const name = read.value.slice(0, at).trim();
|
|
155
|
+
const value = read.value.slice(at + 1).trim();
|
|
156
|
+
if (!/^[A-Za-z0-9-]+$/.test(name) || !(name.toLowerCase() === 'authorization' || /^x-/i.test(name))) return fail('--session-header-env: the header must be Authorization or a name starting X-.');
|
|
157
|
+
if (!value || value.length > MAX_SESSION_CHARS) return fail(`--session-header-env: the header value must be 1 to ${MAX_SESSION_CHARS} characters.`);
|
|
158
|
+
addSecret(value);
|
|
159
|
+
// A bearer value's token alone, as a page may print it without the scheme.
|
|
160
|
+
const token = /^\S+\s+(\S.*)$/.exec(value);
|
|
161
|
+
if (token) addSecret(token[1]);
|
|
162
|
+
return { liveSite: { ...base, signIn: { method: 'session', kind: 'header', signInUrl: null, selectors: null, credential: () => ({ header: { name, value } }) } } };
|
|
163
|
+
}
|
|
164
|
+
return { liveSite: { ...base, signIn: { method: 'none', kind: null, signInUrl: null, selectors: null, credential: () => ({}) } } };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export default { readLiveSite, startUrl, parseCookieHeader, SELECTOR_KEYS };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { lookup as dnsLookup } from 'node:dns/promises';
|
|
2
|
+
import { isPublicAddress } from './hosts.js';
|
|
3
|
+
import { RAVENSIGHT_INGEST_ORIGIN } from './network.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The browser's own name resolution on a live site run (CONTRACT.md 6.1).
|
|
7
|
+
*
|
|
8
|
+
* The route decides every request it sees, but Playwright never routes the
|
|
9
|
+
* next hop of an HTTP redirect, and never routes a WebSocket. So Chromium is
|
|
10
|
+
* started with `--host-resolver-rules` as well, and can resolve only:
|
|
11
|
+
*
|
|
12
|
+
* - a verified public host: the start host, pinned to an address a fresh A
|
|
13
|
+
* lookup found public (the domain check's own rule), so a redirect or a
|
|
14
|
+
* socket to any other name, or a DNS answer that changed to an internal
|
|
15
|
+
* address, finds nothing;
|
|
16
|
+
* - a local dev server: localhost, 127.0.0.1 and the dev server's own host;
|
|
17
|
+
* - in both, the Ravensight hosts the ingest rules let through (ours, and the
|
|
18
|
+
* API this CLI talks to).
|
|
19
|
+
*
|
|
20
|
+
* Every other name is `~NOTFOUND`. IP literals are not names and are not
|
|
21
|
+
* resolved at all, so they are left to the route.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The start host's public IPv4 addresses, from a fresh lookup.
|
|
26
|
+
*
|
|
27
|
+
* @param {string} host
|
|
28
|
+
* @param {{lookup?: Function}} [options] test seam: dns.promises.lookup's shape
|
|
29
|
+
* @returns {Promise<{addresses: Array<string>, refused: Array<string>, error?: string}>}
|
|
30
|
+
*/
|
|
31
|
+
export async function publicAddresses(host, { lookup = dnsLookup } = {}) {
|
|
32
|
+
let answers;
|
|
33
|
+
try {
|
|
34
|
+
answers = await lookup(host, { all: true, family: 4 });
|
|
35
|
+
} catch (error) {
|
|
36
|
+
return { addresses: [], refused: [], error: String((error && error.code) || (error && error.message) || error) };
|
|
37
|
+
}
|
|
38
|
+
const all = [...new Set((answers || []).map(answer => String(answer && answer.address)))];
|
|
39
|
+
return { addresses: all.filter(isPublicAddress), refused: all.filter(address => !isPublicAddress(address)) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The hosts of the Ravensight origins, ours always included. */
|
|
43
|
+
export function ravensightHosts(origins = []) {
|
|
44
|
+
const hosts = new Set([new URL(RAVENSIGHT_INGEST_ORIGIN).hostname]);
|
|
45
|
+
for (const origin of origins) {
|
|
46
|
+
try { hosts.add(new URL(origin).hostname); } catch { /* not an origin */ }
|
|
47
|
+
}
|
|
48
|
+
return [...hosts];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const plainHost = host => String(host).replace(/^\[|\]$/g, '');
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The `--host-resolver-rules` value. Rules apply in order and the first that
|
|
55
|
+
* matches a name decides it, so the exclusions and the pin come before the
|
|
56
|
+
* final `MAP * ~NOTFOUND`.
|
|
57
|
+
*
|
|
58
|
+
* @param {{startHost: string, local: boolean, addresses?: Array<string>, ravensightHosts?: Array<string>}} args
|
|
59
|
+
* @returns {string}
|
|
60
|
+
*/
|
|
61
|
+
export function hostResolverRules({ startHost, local, addresses = [], ravensightHosts: hosts = [] }) {
|
|
62
|
+
const rules = [];
|
|
63
|
+
const exclude = host => { const rule = `EXCLUDE ${plainHost(host)}`; if (!rules.includes(rule)) rules.push(rule); };
|
|
64
|
+
if (local) {
|
|
65
|
+
exclude('localhost');
|
|
66
|
+
exclude('127.0.0.1');
|
|
67
|
+
exclude(startHost);
|
|
68
|
+
for (const host of hosts) exclude(host);
|
|
69
|
+
} else {
|
|
70
|
+
if (!addresses.length) throw new Error(`${startHost} has no public address to play`);
|
|
71
|
+
for (const host of hosts) exclude(host);
|
|
72
|
+
rules.push(`MAP ${startHost} ${addresses[0]}`);
|
|
73
|
+
}
|
|
74
|
+
rules.push('MAP * ~NOTFOUND');
|
|
75
|
+
return rules.join(', ');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export default { publicAddresses, hostResolverRules, ravensightHosts };
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { RUN_FILES } from '../paths.js';
|
|
4
|
+
import { redactDirectory, redactText, redactValue } from '../redaction.js';
|
|
5
|
+
import { safetyLines } from './network.js';
|
|
6
|
+
import { publicAddresses } from './resolver.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The parts of `run --url` around the browser (CONTRACT.md 1.5, 6.2, 6.3, 7):
|
|
10
|
+
* the domain check before anything is priced, the report's "Live site"
|
|
11
|
+
* section, and the scan of the run directory before upload.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** What a studio adds for a public host that is not verified yet. */
|
|
15
|
+
export function txtInstruction(host) {
|
|
16
|
+
return `To verify it, add a TXT record on ${host} with the value shown on the Playtest page, Test a live URL, then run this again.`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Ask the server whether a public host is verified for the game. Answers null
|
|
21
|
+
* when it is, or the lines that refuse the run (before any estimate,
|
|
22
|
+
* registration or charge).
|
|
23
|
+
*
|
|
24
|
+
* @param {{api: Object, gameId: string, host: string}} args
|
|
25
|
+
* @returns {Promise<Array<string>|null>}
|
|
26
|
+
*/
|
|
27
|
+
export async function domainCheckRefusal({ api, gameId, host }) {
|
|
28
|
+
const nothing = 'Nothing was registered or charged.';
|
|
29
|
+
const unverified = [`${host} is not a verified host for this game, so a playtest cannot be pointed at it. ${txtInstruction(host)}`, nothing];
|
|
30
|
+
if (!api || !api.url || typeof api.url.checkDomain !== 'function') return unverified;
|
|
31
|
+
let answer;
|
|
32
|
+
try {
|
|
33
|
+
answer = await api.url.checkDomain(gameId, host);
|
|
34
|
+
} catch (error) {
|
|
35
|
+
// An older server without the route cannot say the host is verified.
|
|
36
|
+
if (error && error.status === 404) return unverified;
|
|
37
|
+
return [`The domain check for ${host} did not answer (${String((error && error.message) || error).slice(0, 200)}). Run this again in a minute.`, nothing];
|
|
38
|
+
}
|
|
39
|
+
if (answer && answer.verified === true) return null;
|
|
40
|
+
if (answer && answer.code === 'dns_unavailable') return [`We could not check the DNS record for ${host} just now. Run this again in a minute.`, nothing];
|
|
41
|
+
return unverified;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Look the public start host up again and keep its public addresses on the
|
|
46
|
+
* live site, for the browser's resolver rules (./resolver.js). Answers null,
|
|
47
|
+
* or the lines that refuse the run when no public address is left (before any
|
|
48
|
+
* charge, the same rule as the domain check).
|
|
49
|
+
*
|
|
50
|
+
* @param {Object} liveSite
|
|
51
|
+
* @param {{lookup?: Function}} [options]
|
|
52
|
+
* @returns {Promise<Array<string>|null>}
|
|
53
|
+
*/
|
|
54
|
+
export async function pinRefusal(liveSite, { lookup } = {}) {
|
|
55
|
+
const found = await publicAddresses(liveSite.startHost, lookup ? { lookup } : {});
|
|
56
|
+
if (found.addresses.length === 0) {
|
|
57
|
+
const why = found.error ? `the lookup failed (${found.error})` : found.refused.length ? 'it resolves only to private or reserved addresses' : 'it has no IPv4 address';
|
|
58
|
+
return [`${liveSite.startHost} has no public address a playtest can reach: ${why}.`, 'Nothing was registered or charged.'];
|
|
59
|
+
}
|
|
60
|
+
liveSite.addresses = found.addresses;
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** How a sign-in reads in the report. Never a value. */
|
|
65
|
+
export function signInLine(signIn, method = 'none') {
|
|
66
|
+
if (!signIn) {
|
|
67
|
+
return method === 'none' ? 'Sign in: none; the site was played signed out.' : 'Sign in: not reached; the run stopped before it.';
|
|
68
|
+
}
|
|
69
|
+
const how = signIn.method === 'password' ? 'the test account\'s email and password'
|
|
70
|
+
: signIn.kind === 'header' ? 'a session header' : 'a session cookie';
|
|
71
|
+
const seconds = Number.isFinite(signIn.seconds) ? ` in ${signIn.seconds} seconds` : '';
|
|
72
|
+
if (signIn.ok) return `Sign in: signed in with ${how}${seconds}.`;
|
|
73
|
+
return `Sign in: failed (${signIn.code})${Number.isFinite(signIn.seconds) ? ` after ${signIn.seconds} seconds` : ''}${signIn.blockedHost ? `; it went to ${signIn.blockedHost}` : ''}.`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* After a live site run, before it is delivered: add the "Live site" section
|
|
78
|
+
* to report.md, scan every text file in the run directory for the sign-in
|
|
79
|
+
* secrets (redacting in place and counting), record `signIn` and `safety` in
|
|
80
|
+
* usage.json, and redact what the run hands the API. A run on any other
|
|
81
|
+
* target is left alone.
|
|
82
|
+
*
|
|
83
|
+
* @param {{directory: string, driver: Object, outcome: Object, liveSite: Object|null}} args
|
|
84
|
+
* @returns {Promise<{signIn: Object|null, safety: Object|null, redactions: number}|null>}
|
|
85
|
+
*/
|
|
86
|
+
export async function finishLiveSiteRun({ directory, driver, outcome, liveSite }) {
|
|
87
|
+
if (!liveSite) return null;
|
|
88
|
+
const signIn = driver && typeof driver.signInOutcome === 'function' ? driver.signInOutcome() : null;
|
|
89
|
+
const safety = driver && typeof driver.liveSiteSafety === 'function' ? driver.liveSiteSafety() : null;
|
|
90
|
+
const section = ['', '## Live site', '', `Start page: ${liveSite.startUrl}`, signInLine(signIn, liveSite.signIn ? liveSite.signIn.method : 'none'), ...safetyLines(safety)].join('\n');
|
|
91
|
+
const markdownPath = path.join(directory, RUN_FILES.reportMd);
|
|
92
|
+
const markdown = await readFile(markdownPath, 'utf8').catch(() => null);
|
|
93
|
+
if (markdown !== null) await writeFile(markdownPath, `${markdown.replace(/\s*$/, '')}\n${section}\n`, 'utf8');
|
|
94
|
+
if (outcome && typeof outcome.reportMarkdown === 'string') outcome.reportMarkdown = `${outcome.reportMarkdown.replace(/\s*$/, '')}\n${section}\n`;
|
|
95
|
+
|
|
96
|
+
const scanned = await redactDirectory(directory);
|
|
97
|
+
const usagePath = path.join(directory, RUN_FILES.usageJson);
|
|
98
|
+
const usage = await readFile(usagePath, 'utf8').then(JSON.parse).catch(() => ({}));
|
|
99
|
+
usage.signIn = signIn
|
|
100
|
+
? { method: signIn.method, ...(signIn.kind ? { kind: signIn.kind } : {}), ok: signIn.ok, code: signIn.code, seconds: signIn.seconds, ...(signIn.blockedHost ? { blockedHost: signIn.blockedHost } : {}), redactions: scanned.redactions }
|
|
101
|
+
: { method: liveSite.signIn ? liveSite.signIn.method : 'none', ok: null, code: null, seconds: null, redactions: scanned.redactions };
|
|
102
|
+
if (safety) usage.safety = safety;
|
|
103
|
+
await writeFile(usagePath, redactText(`${JSON.stringify(usage, null, 2)}\n`), 'utf8');
|
|
104
|
+
|
|
105
|
+
if (outcome) {
|
|
106
|
+
for (const key of ['report', 'reportMarkdown', 'quitDetail', 'gameMemory', 'capabilityNotes']) {
|
|
107
|
+
if (outcome[key] !== undefined) outcome[key] = redactValue(outcome[key]);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { signIn, safety, redactions: scanned.redactions };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export default { domainCheckRefusal, finishLiveSiteRun, signInLine, txtInstruction };
|