ravensight-playtest 0.13.3 → 0.17.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.
Files changed (41) hide show
  1. package/README.md +82 -1
  2. package/addons/ravensight_driver/driver.gd +472 -28
  3. package/docs/godot-driver.md +66 -2
  4. package/package.json +4 -4
  5. package/src/api/README.md +8 -1
  6. package/src/api/client.js +24 -1
  7. package/src/cli.js +19 -0
  8. package/src/commands/check.js +5 -2
  9. package/src/commands/run.js +40 -5
  10. package/src/commands/setup.js +176 -0
  11. package/src/packs/index.js +37 -5
  12. package/src/packs/keys.json +11 -0
  13. package/src/packs/pack-signing-hashes.json +7 -0
  14. package/src/packs/pack-signing-vectors.json +119 -0
  15. package/src/packs/signature.js +186 -0
  16. package/src/run/anygame/gamenotes.js +74 -12
  17. package/src/run/anygame/index.js +97 -34
  18. package/src/run/anygame/language.js +100 -10
  19. package/src/run/anygame/memory.js +70 -13
  20. package/src/run/anygame/shared-hashes.json +9 -8
  21. package/src/run/anygame/shared.js +6 -5
  22. package/src/run/anygame/sound.js +59 -16
  23. package/src/run/args.js +5 -0
  24. package/src/run/claimwords.js +43 -7
  25. package/src/run/drivers/godot-cursor.js +96 -0
  26. package/src/run/drivers/godot-observation.js +29 -5
  27. package/src/run/drivers/godot.js +60 -5
  28. package/src/run/drivers/web.js +181 -10
  29. package/src/run/egress.js +282 -0
  30. package/src/run/eventclaims.js +102 -6
  31. package/src/run/events.js +64 -6
  32. package/src/run/gameMemory.js +14 -5
  33. package/src/run/honesty.js +49 -2
  34. package/src/run/judge.js +22 -10
  35. package/src/run/liveFeed.js +254 -0
  36. package/src/run/networkRun.js +54 -0
  37. package/src/run/personaLoop.js +70 -20
  38. package/src/run/pixels.js +491 -2
  39. package/src/run/replay.js +11 -0
  40. package/src/run/resume.js +3 -1
  41. package/src/run/tools.js +2 -2
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { pngFingerprint, screenDelta, significant } from '../pixels.js';
2
+ import { pngFingerprint, screenDelta, significant, motionBlocks, bracketMask, bracketVerdict, BRACKET_MS, MASK_MAX_SHARE, decodePng, motionMoves, sweepMask, scrollMotionBlocks, scrollShift, steadyScroll, scrollJudge } from '../pixels.js';
3
3
  import { findRegions } from '../regions.js';
4
4
  import { createMarker, isMarkTarget, marksFor, marksText, resolveMark } from '../marks.js';
5
5
  import { gameTime, timeFreezeInit } from '../timeFreeze.js';
@@ -17,7 +17,9 @@ import { recordingLimits, recordingViewport, recordingDirectory, recordingMetada
17
17
  import path from 'node:path';
18
18
  import { gameRefusal, runnerGone } from '../gameRefusal.js';
19
19
  import { createAvoidGuard } from '../avoid.js';
20
- import { classifyRequest, createSafetyCounts, networkRules } from '../livesite/network.js';
20
+ import { classifyRequest, createSafetyCounts, networkRules, isIngestCall } from '../livesite/network.js';
21
+ // A run's network access to the game's listed servers (the platform's docs/playtest-network/CONTRACT.md).
22
+ import { createEgress, egressBrowserArgs, hostLabel, parseEntries } from '../egress.js';
21
23
  import { hostResolverRules, ravensightHosts } from '../livesite/resolver.js';
22
24
  import { LiveSiteError, MASKED_EMAIL, MASKED_PASSWORD, maskSecretsInit, outcomeMessage, performSignIn } from '../livesite/browser.js';
23
25
  import {
@@ -350,6 +352,9 @@ export async function fieldValue(locator) {
350
352
  /** How long `act` waits once for a late change (a navigation still starting) before it says the screen did not change. */
351
353
  export const SETTLE_MS = 300;
352
354
 
355
+ /** What the persona reads when an input's whole change lay inside what moves by itself on the screen. */
356
+ export const SELF_ONLY_NOTE = 'Part of the screen changed, but only what moves on its own.';
357
+
353
358
  /**
354
359
  * Whether an action changed anything: the URL, the document (a navigation or
355
360
  * a reload), the compacted tree (which carries every field's value), or for
@@ -1107,6 +1112,15 @@ export function textOnScreen(nodes, target) {
1107
1112
  /** What a target that is none of a ref, coordinates or visible text is told. */
1108
1113
  export const NOT_A_TARGET_MESSAGE = 'is not a ref, coordinates or text on the current screen; use the ref the snapshot shows, such as e12';
1109
1114
 
1115
+ /**
1116
+ * What a select on a game's canvas is told (the cloud runner says the same): a dropdown a
1117
+ * game engine draws (a Godot OptionButton in a web export) has no options in the page, so it
1118
+ * is opened and chosen with two clicks where the picture shows it. Before, the select clicked
1119
+ * the middle of the game, an input nobody asked for, then waited the full action timeout for
1120
+ * an option the page never holds.
1121
+ */
1122
+ export const CANVAS_SELECT_MESSAGE = 'a dropdown drawn on the game\'s canvas has no options in the page, so select cannot choose from it. Click the dropdown where the picture shows it to open it, then click the option the same way: its grid cell, its mark, or x and y read off the screenshot. This is a limit of the runner, not of the game';
1123
+
1110
1124
  /**
1111
1125
  * How long a click by words on a canvas game looks for those words in the page before it is refused. The words of a game drawn
1112
1126
  * on a canvas are in the picture, not in the page, so there is nothing to wait for: the paid local run of 2026-11-20 waited the
@@ -1225,15 +1239,35 @@ export function tapSdkEvents(request, log) {
1225
1239
  export const CHECK_PLAYTEST_IDENTITY = Object.freeze({ token: 'check', runId: null, jobId: null, persona: 'check' });
1226
1240
 
1227
1241
  /**
1228
- * Chromium's arguments. A recorded run is muted; a live site run can resolve
1229
- * only the names its rules allow (../livesite/resolver.js), because the route
1230
- * never sees a redirect's next hop or a WebSocket.
1242
+ * Chromium's arguments. A recorded run is muted; a headless run gets a fake
1243
+ * audio device (`--disable-audio-output`), so the game's sound is measured
1244
+ * (../anygame/sound.js) and never reaches this machine's speakers, where
1245
+ * nobody is watching; a headed run keeps the real device for the person who
1246
+ * is. A live site run can resolve only the names its rules allow
1247
+ * (../livesite/resolver.js), because the route never sees a redirect's next
1248
+ * hop or a WebSocket.
1231
1249
  *
1232
- * @param {{video: boolean, liveSite: Object|null}} args
1250
+ * @param {{video: boolean, liveSite: Object|null, headless?: boolean}} args
1251
+ * @returns {Array<string>}
1252
+ */
1253
+ /**
1254
+ * The build's own origin as `host:port`, which a run with network access lets the browser reach directly, as it
1255
+ * always did: the build is the game's own. Every other address, another port on this machine included, meets the proxy.
1256
+ * @param {string} url
1233
1257
  * @returns {Array<string>}
1234
1258
  */
1235
- export function browserLaunchArgs({ video, liveSite }) {
1236
- const args = video ? ['--mute-audio'] : [];
1259
+ export function buildHostsOf(url) {
1260
+ try {
1261
+ const u = new URL(String(url));
1262
+ if (!/^https?:$/.test(u.protocol) || !u.hostname) return [];
1263
+ return [`${u.hostname.toLowerCase()}:${u.port || (u.protocol === 'https:' ? '443' : '80')}`];
1264
+ } catch {
1265
+ return [];
1266
+ }
1267
+ }
1268
+
1269
+ export function browserLaunchArgs({ video, liveSite, headless = false }) {
1270
+ const args = [...(headless ? ['--disable-audio-output'] : []), ...(video ? ['--mute-audio'] : [])];
1237
1271
  if (liveSite) {
1238
1272
  args.push(`--host-resolver-rules=${hostResolverRules({ startHost: liveSite.startHost, local: liveSite.local, addresses: liveSite.addresses || [], ravensightHosts: ravensightHosts(liveSite.ravensightOrigins || []) })}`);
1239
1273
  }
@@ -1444,7 +1478,15 @@ export async function needsFrame(page, text) {
1444
1478
  try { return (await page.evaluate(pageHasLargeCanvas, LARGE_CANVAS_SHARE)) === true; } catch { return false; }
1445
1479
  }
1446
1480
 
1447
- export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo, freezeTime = true, touch = false, frameStrip = true, liveSite = null, ingestOrigins = null } = {}) {
1481
+ /** The share of the screen a block mask covers: 1 for no mask at all (nothing could be judged by it). */
1482
+ function maskShare(mask) {
1483
+ if (!mask) return 1;
1484
+ let n = 0;
1485
+ for (let i = 0; i < mask.length; i += 1) n += mask[i];
1486
+ return mask.length ? n / mask.length : 1;
1487
+ }
1488
+
1489
+ export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo, freezeTime = true, touch = false, frameStrip = true, liveSite = null, ingestOrigins = null, network = null, egressTest = null } = {}) {
1448
1490
  const editModifier = modifier === 'Meta' || modifier === 'Control' ? modifier : platformModifier(platform);
1449
1491
  // What the brief asks the run to stay out of (../avoid.js): an input on such a control is never sent (setAvoid).
1450
1492
  let avoidGuard = createAvoidGuard([]);
@@ -1458,6 +1500,11 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1458
1500
  const sdkSessionReads = new Set();
1459
1501
  // Only a POST to one of these origins is the game's Ravensight session; the game's own backend at the same path is not.
1460
1502
  const sessionOrigins = Array.isArray(ingestOrigins) && ingestOrigins.length > 0 ? ingestOrigins : ingestOriginsFor();
1503
+ // Network access (`network: { hosts }`, the hosts recorded on the job at register): off when null. On, every request
1504
+ // off the build goes through `networkRoute` and every outside connection through the run's proxy (../egress.js).
1505
+ // `egressTest` is test-only (`{ resolve, connect, allowPrivate, browserArgs }`), handed in code, never read from a flag or a file.
1506
+ const netEntries = network && Array.isArray(network.hosts) ? parseEntries(network.hosts).entries.slice(0, 9) : [];
1507
+ let egress = null;
1461
1508
  let target = null;
1462
1509
  let runDirectory = null;
1463
1510
  let videoRequested = false;
@@ -1488,7 +1535,16 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1488
1535
  // from the first action on: loading before it runs as it always did.
1489
1536
  const clock = gameTime(() => page);
1490
1537
  let clockParked = false;
1538
+ // How long game time last ran between a release and a park (it stands still otherwise): how far what moves by itself
1539
+ // travelled during an input.
1540
+ let clockRanFrom = 0;
1541
+ let lastRanMs = 0;
1491
1542
  let canvasPlay = false;
1543
+ // A canvas game that moves by itself (the cloud runner's docs/playtest/MOVING_SCREENS.md): the frame and page text the
1544
+ // last observation measured, and the last input's after sample, for the next input's bracket.
1545
+ let lastObservedPrint = null;
1546
+ let lastObservedText = null;
1547
+ let motionChain = null;
1492
1548
  /** The compacted lines of the last observation, so a cut can prefer what is new. */
1493
1549
  let lastObservedLines = null;
1494
1550
  /** The kept nodes of the last observation: refs, names and hints, for a target that matches twice. */
@@ -1595,6 +1651,34 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1595
1651
  }
1596
1652
  }
1597
1653
 
1654
+ /**
1655
+ * The one route of a run with network access (docs/playtest-network/CONTRACT.md section 6): the build itself and what
1656
+ * the page makes in memory go on; the game's Ravensight SDK reaches its documented ingest calls and nothing else of
1657
+ * ours; a listed host over https or wss goes on, through the run's proxy; anything else is blocked and counted by
1658
+ * host. What goes on falls back to the build guard, so a navigation off the build is still kept on it.
1659
+ * @param {any} route
1660
+ */
1661
+ function networkRoute(route) {
1662
+ const request = route.request();
1663
+ const address = request.url();
1664
+ let parsed = null;
1665
+ try { parsed = new URL(address); } catch { parsed = null; }
1666
+ if (!parsed || !/^(?:https?|wss?):$/.test(parsed.protocol) || onBuild(address)) return route.fallback();
1667
+ if (sessionOrigins.includes(parsed.origin) || ravensightHosts(sessionOrigins).includes(parsed.hostname)) {
1668
+ if (isIngestCall(request.method(), parsed)) return route.fallback();
1669
+ return route.fulfill({ status: 403, contentType: 'application/json', body: '{"error":"sandbox_refused"}' });
1670
+ }
1671
+ if (egress.allows(address)) return route.fallback();
1672
+ egress.noteBlocked(hostLabel(address));
1673
+ let topLevel = false;
1674
+ try { topLevel = request.isNavigationRequest() ? isTopLevel(request) : false; } catch { topLevel = false; }
1675
+ if (topLevel !== false) {
1676
+ if (guardArmed) recordOffSite(address, topLevel === null ? 'new window' : 'navigation');
1677
+ return route.fulfill({ status: 204, body: '' });
1678
+ }
1679
+ return route.abort('blockedbyclient');
1680
+ }
1681
+
1598
1682
  /** @param {string} candidate */
1599
1683
  function onBuild(candidate) {
1600
1684
  return buildTargets.some(base => isNavigationAllowed(candidate, base));
@@ -1907,6 +1991,8 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1907
1991
  async function parkClock(park) {
1908
1992
  if (!freezeTime || clockParked === park) return;
1909
1993
  clockParked = park;
1994
+ if (park) lastRanMs = Date.now() - clockRanFrom;
1995
+ else clockRanFrom = Date.now();
1910
1996
  try {
1911
1997
  await (park ? clock.pause() : clock.resume());
1912
1998
  } catch {
@@ -1931,6 +2017,64 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1931
2017
  return (await documentToken(current)) === lastNodesDocument;
1932
2018
  }
1933
2019
 
2020
+ /**
2021
+ * After an input on a canvas game whose time is parked between inputs: one more frame BRACKET_MS of game time later
2022
+ * with no input, and what moved between the two masked with the last input's sample (../pixels.js). A shape the
2023
+ * input's game time carried off the edge is swept to it; on a screen that scrolls by itself the samples follow the
2024
+ * scroll, and the input is judged on what is left once the screen's own scroll is taken out. Answers the verdict when
2025
+ * the whole change lay inside what moves by itself, else null. The page text must not have changed: a change of the
2026
+ * words is the game answering. Never fails an input.
2027
+ */
2028
+ async function selfMotionCheck(current, before) {
2029
+ const chain = motionChain && before && !significant(screenDelta(motionChain.print, before)) ? motionChain : null;
2030
+ const ranMs = lastRanMs;
2031
+ motionChain = null;
2032
+ try {
2033
+ const snap = await snapshotText();
2034
+ const sameText = hashText(snap, shownText(snap)) === lastObservedText;
2035
+ const firstPng = await probeFrame(current);
2036
+ const first = pngFingerprint(firstPng);
2037
+ await parkClock(false);
2038
+ await new Promise(resolve => setTimeout(resolve, BRACKET_MS));
2039
+ await parkClock(true);
2040
+ const sampleMs = lastRanMs;
2041
+ const laterPng = await probeFrame(current);
2042
+ const later = pngFingerprint(laterPng);
2043
+ let after = motionBlocks(first, later);
2044
+ let firstImg = null;
2045
+ let laterImg = null;
2046
+ // Too much moved to judge by (a scroll): followed instead once the scroll is taken out.
2047
+ if (later && maskShare(after) > MASK_MAX_SHARE) {
2048
+ firstImg = decodePng(firstPng);
2049
+ laterImg = decodePng(laterPng);
2050
+ after = scrollMotionBlocks(firstImg, laterImg, first, { ms: sampleMs }) || after;
2051
+ }
2052
+ if (after && !after.scroll) after.moves = motionMoves(first, later, { ms: sampleMs });
2053
+ if (after) motionChain = { print: later, mask: after, image: after.scroll ? laterImg : null };
2054
+ const prev = chain ? chain.mask : null;
2055
+ // A chain holds only across samples of one kind: both of a still screen, or both of a scroll.
2056
+ if (!after || !prev || !sameText || Boolean(prev.scroll) !== Boolean(after.scroll)) return null;
2057
+ let seen;
2058
+ if (!after.scroll) {
2059
+ const mask = bracketMask([sweepMask(prev, prev.moves, ranMs, { dir: 1 }), sweepMask(after, after.moves, ranMs, { dir: -1 })]);
2060
+ if (!mask) return null;
2061
+ seen = significant(screenDelta(before, first, undefined, mask));
2062
+ } else {
2063
+ // The scroll during the input is taken out only when it is the screen's own: a camera that follows the player
2064
+ // scrolls because of the input.
2065
+ const shift = scrollShift(chain.image, firstImg);
2066
+ if (!shift || !steadyScroll(shift, ranMs, [prev.scroll, after.scroll])) return null;
2067
+ const judged = scrollJudge(chain.image, firstImg, shift, chain.print, { prev, sample: after });
2068
+ if (!judged) return null;
2069
+ seen = judged.seen;
2070
+ }
2071
+ const verdict = bracketVerdict(true, seen);
2072
+ return verdict.selfOnly ? verdict : null;
2073
+ } catch {
2074
+ return null;
2075
+ }
2076
+ }
2077
+
1934
2078
  /** The hash of the screen as it is now, on observe()'s basis. */
1935
2079
  async function currentHash(current) {
1936
2080
  const snap = await snapshotText();
@@ -2400,6 +2544,7 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2400
2544
  const after = await resolved.evaluate(readChoiceControl, undefined, { timeout: ACTION_TIMEOUT_MS });
2401
2545
  return `Moved the slider from ${control.value} to ${after.value} with the arrow keys.`;
2402
2546
  }
2547
+ if (control.tag === 'CANVAS') throw new TargetError(CANVAS_SELECT_MESSAGE);
2403
2548
  if (action.option === undefined) throw new TargetError('that control is not a slider: pass option, the text of the option to choose');
2404
2549
  // A dropdown the game draws itself: open it, then press the option.
2405
2550
  await resolved.click({ timeout: ACTION_TIMEOUT_MS });
@@ -2469,6 +2614,7 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2469
2614
  if (marker) await marker.close().catch(() => {});
2470
2615
  marker = null;
2471
2616
  try { if (browser) await withTimeout(browser.close(), 15000); } catch { /* already closed or unavailable */ }
2617
+ if (egress) await egress.close().catch(() => {});
2472
2618
  if (captureDirectory) await rm(captureDirectory, { recursive: true, force: true });
2473
2619
  if (metadata) await saveRecording(runDirectory, metadata);
2474
2620
  page = null;
@@ -2811,12 +2957,15 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2811
2957
  let token = null;
2812
2958
  lastMarks = null;
2813
2959
  canvasPlay = false;
2960
+ lastObservedPrint = null;
2961
+ lastObservedText = hashText(snap, shown);
2814
2962
  if (await needsFrame(current, text)) {
2815
2963
  canvasPlay = true;
2816
2964
  try {
2817
2965
  const plain = await current.screenshot({ type: OBSERVATION_FRAME.type, quality: OBSERVATION_FRAME.quality, timeout: ACTION_TIMEOUT_MS });
2818
2966
  const measured = frameToken(await probeFrame(current));
2819
2967
  token = measured.token;
2968
+ lastObservedPrint = measured.fingerprint;
2820
2969
  // The persona's copy carries a grid and marks to click by; the page
2821
2970
  // itself is never drawn on.
2822
2971
  const shownFrame = await markedFrame(plain, measured.fingerprint);
@@ -2915,7 +3064,16 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2915
3064
  try {
2916
3065
  const playwright = await loadPlaywright(importer);
2917
3066
  await mkdir(runDir, { recursive: true });
2918
- const launchArgs = browserLaunchArgs({ video: videoRequested, liveSite });
3067
+ const launchArgs = browserLaunchArgs({ video: videoRequested, liveSite, headless: headless !== false });
3068
+ if (network && !liveSite) {
3069
+ // The game's own Ravensight SDK reaches its documented ingest calls (the route holds it to those paths); every
3070
+ // other outside host is the list's, and the build's own host stays the browser's own.
3071
+ const passthrough = sessionOrigins.map(origin => { try { return new URL(origin).hostname; } catch { return null; } }).filter(Boolean);
3072
+ const { browserArgs: testArgs = [], ...testEgress } = egressTest || {};
3073
+ egress = createEgress({ entries: netEntries, passthrough, ...testEgress });
3074
+ const proxy = await egress.start();
3075
+ launchArgs.push(...egressBrowserArgs(proxy.url, { direct: buildHostsOf(url) }), ...testArgs);
3076
+ }
2919
3077
  browser = await playwright.chromium.launch({ headless, ...(launchArgs.length ? { args: launchArgs } : {}) });
2920
3078
  const contextBase = { viewport, ...(touch ? { hasTouch: true, isMobile: true, deviceScaleFactor: 1, userAgent: PHONE_USER_AGENT } : {}) };
2921
3079
  // A live site's sign-in happens first, in a context of its own with no recording of any kind; the
@@ -2934,6 +3092,8 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2934
3092
  context = await browser.newContext({
2935
3093
  ...contextBase,
2936
3094
  ...(storageState ? { storageState } : {}),
3095
+ // A run with access registers no service worker: what the page reaches stays the page's own requests.
3096
+ ...(egress ? { serviceWorkers: 'block' } : {}),
2937
3097
  ...(videoRequested ? { recordVideo: { dir: captureDirectory, size: viewport }, permissions: [] } : {})
2938
3098
  });
2939
3099
  // The playtest identity goes in as an init script, not as
@@ -2998,6 +3158,8 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2998
3158
  }
2999
3159
  // Registered after the build guard, so it decides first and hands what it allows back to the guard.
3000
3160
  if (liveSite && typeof context.route === 'function') await context.route('**/*', route => liveRoute(route, { play: true }));
3161
+ // Network access: registered after the build guard as well, so it decides first and hands what it allows back.
3162
+ if (egress && typeof context.route === 'function') await context.route('**/*', route => networkRoute(route));
3001
3163
  captureStartedAt = videoRequested ? now() : null;
3002
3164
  page = await context.newPage();
3003
3165
  // A new window that did get a document (one on the build, or a blank
@@ -3285,6 +3447,12 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
3285
3447
  if (!outcome.ok && /Timeout \d+ms exceeded/i.test(String(outcome.error || ''))) await assertAlive(current);
3286
3448
  if (canvasPlay) await parkClock(true);
3287
3449
  if (outcome.refused) return outcome;
3450
+ // A change on a canvas game that moves by itself may be the game's own: said, never turned into "nothing changed",
3451
+ // since this runner does not know where the player is (../pixels.js bracketVerdict).
3452
+ if (canvasPlay && freezeTime && outcome.ok && outcome.changed && action.kind !== 'wait') {
3453
+ const verdict = await selfMotionCheck(current, lastObservedPrint);
3454
+ if (verdict) outcome = { ...outcome, selfOnly: true, detail: outcome.detail ? `${outcome.detail}\n${SELF_ONLY_NOTE}` : SELF_ONLY_NOTE };
3455
+ } else motionChain = null;
3288
3456
  // A click, a key, a submit or a script that tried to leave the build:
3289
3457
  // the page stayed (or was brought back), and the persona is told the
3290
3458
  // same as for a refused `navigate`. A step that changed nothing.
@@ -3307,6 +3475,9 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
3307
3475
  /** A live site run's blocked hosts and refused Ravensight paths, or null for any other run. */
3308
3476
  liveSiteSafety() { return liveSite ? liveSafety.toJSON() : null; },
3309
3477
 
3478
+ /** A run with network access: the hosts it could reach, those it reached and the blocked attempts by host; else null. */
3479
+ networkSummary() { return egress ? egress.summary() : null; },
3480
+
3310
3481
  /** The controls an input was refused on because the brief asks to stay out of them, by name. */
3311
3482
  avoidedControls() { return avoidGuard.list(); },
3312
3483
 
@@ -0,0 +1,282 @@
1
+ // A playtest run's network access to the hosts a studio listed for its game (decision N3,
2
+ // docs/playtest-network/CONTRACT.md in the platform repo). The same code in the hosted runner and the local CLI.
3
+ //
4
+ // Off unless the run asked for it. On, the browser reaches the build's own origin and the listed hosts only, each
5
+ // over https or wss on the default port. Every connection to the outside goes through a small proxy in this process
6
+ // (`createEgress`): it sees the host of every request the page, a worker, a redirect hop, a WebSocket or a popup
7
+ // makes, because the browser sends each as one CONNECT naming its host. It refuses any host not on the list, resolves
8
+ // a listed name itself, refuses the connection when any answer is private, loopback or link-local, and connects to
9
+ // the address it checked, so a name that rebinds between the check and the connection reaches nothing else.
10
+ import net from 'node:net';
11
+ import http from 'node:http';
12
+ import dns from 'node:dns';
13
+
14
+ /** At most nine entries and 580 characters joined by spaces: the hosts ride in the cloud machine's start data. */
15
+ export const MAX_ENTRIES = 9;
16
+ export const MAX_JOINED_CHARS = 580;
17
+ export const LIMITS = Object.freeze({ tunnels: 64, connections: 5000, connectMs: 10000, idleMs: 120000, hostsTracked: 200 });
18
+
19
+ // Names that are never a studio's server: special-use and private suffixes, and our own.
20
+ const REFUSED_SUFFIXES = ['localhost', 'local', 'internal', 'test', 'example', 'invalid', 'home.arpa', 'arpa', 'onion', 'ravensight.io', 'realityse.com'];
21
+ // A wildcard on a name many unrelated owners share would open far more than one game's servers.
22
+ // Country second levels, and the shared site hosts studios most often publish a web build on.
23
+ const SHARED_PARENTS = ['co.uk', 'org.uk', 'ac.uk', 'gov.uk', 'com.au', 'net.au', 'org.au', 'co.jp', 'co.nz', 'co.kr', 'co.in', 'com.br', 'com.cn', 'com.mx', 'com.tr', 'com.tw',
24
+ 'github.io', 'gitlab.io', 'itch.io', 'itch.zone', 'newgrounds.com', 'vercel.app', 'netlify.app', 'pages.dev', 'workers.dev', 'herokuapp.com',
25
+ 'web.app', 'firebaseapp.com', 'appspot.com', 'onrender.com', 'fly.dev', 'glitch.me', 'repl.co', 'ngrok.io', 'ngrok-free.app',
26
+ // Wildcard DNS services: every name under them answers whatever address it spells.
27
+ 'nip.io', 'sslip.io', 'xip.io', 'traefik.me', 'localtest.me', 'lvh.me'];
28
+ const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
29
+ const under = (host, suffix) => host === suffix || host.endsWith(`.${suffix}`);
30
+
31
+ /** A host as it is stored (lower case, no trailing dot), or null: not an IP literal, not private, not ours, no port. */
32
+ export function normalizeHost(raw) {
33
+ if (typeof raw !== 'string') return null;
34
+ let h = raw.trim().toLowerCase();
35
+ if (h.endsWith('.')) h = h.slice(0, -1);
36
+ if (!h || h.length > 253) return null;
37
+ const labels = h.split('.');
38
+ if (labels.length < 2 || labels.length > 127) return null;
39
+ if (!labels.every(l => LABEL.test(l))) return null;
40
+ // An IP literal, or a name whose last label is all digits (no such top level name exists).
41
+ if (/^\d+$/.test(labels[labels.length - 1])) return null;
42
+ if (REFUSED_SUFFIXES.some(s => under(h, s))) return null;
43
+ return h;
44
+ }
45
+
46
+ /** One entry of a game's list: `{ host, wildcard }` (`*.example.com` is `example.com` with wildcard true), or null. */
47
+ export function parseEntry(raw) {
48
+ if (typeof raw !== 'string') return null;
49
+ const t = raw.trim().toLowerCase();
50
+ const wildcard = t.startsWith('*.');
51
+ const host = normalizeHost(wildcard ? t.slice(2) : t);
52
+ if (!host || (wildcard && SHARED_PARENTS.includes(host))) return null;
53
+ return { host, wildcard };
54
+ }
55
+
56
+ export const entryText = e => (e.wildcard ? `*.${e.host}` : e.host);
57
+
58
+ /**
59
+ * A whole list: `{ entries, invalid }`, the entries de-duplicated in their first order and `invalid` the indexes of
60
+ * those refused. A list over MAX_ENTRIES or MAX_JOINED_CHARS answers `tooMany` or `tooLong`.
61
+ */
62
+ export function parseEntries(list) {
63
+ const entries = [], invalid = [];
64
+ if (!Array.isArray(list)) return { entries, invalid: [-1], tooMany: false, tooLong: false };
65
+ list.forEach((raw, i) => {
66
+ const e = parseEntry(raw);
67
+ if (!e) invalid.push(i);
68
+ else if (!entries.some(x => x.host === e.host && x.wildcard === e.wildcard)) entries.push(e);
69
+ });
70
+ return { entries, invalid, tooMany: entries.length > MAX_ENTRIES, tooLong: entries.map(entryText).join(' ').length > MAX_JOINED_CHARS };
71
+ }
72
+
73
+ /** Whether a host is on the list: an exact entry is only itself, a wildcard one label under its name (never the name). */
74
+ export function allowedHost(raw, entries) {
75
+ const h = normalizeHost(raw);
76
+ if (!h || !Array.isArray(entries)) return false;
77
+ return entries.some(e => {
78
+ if (!e || typeof e.host !== 'string') return false;
79
+ if (!e.wildcard) return h === e.host;
80
+ if (!h.endsWith(`.${e.host}`)) return false;
81
+ return !h.slice(0, -(e.host.length + 1)).includes('.');
82
+ });
83
+ }
84
+
85
+ /** A request's host as the report names it: the host and any port, or the scheme and host when it is not https or wss. */
86
+ export function hostLabel(raw) {
87
+ let u;
88
+ try { u = new URL(String(raw)); } catch { return 'unknown'; }
89
+ const tls = u.protocol === 'https:' || u.protocol === 'wss:';
90
+ const label = tls ? u.host : `${u.protocol}//${u.host}`;
91
+ return label.toLowerCase().replace(/[^a-z0-9.:/\[\]-]/g, '').slice(0, 120) || 'unknown';
92
+ }
93
+
94
+ /** Whether the browser may ask for a URL at all: https or wss, the default port, no user info, a listed host. */
95
+ export function allowedUrl(raw, entries) {
96
+ let u;
97
+ try { u = new URL(String(raw)); } catch { return false; }
98
+ if (u.protocol !== 'https:' && u.protocol !== 'wss:') return false;
99
+ if (u.port || u.username || u.password) return false;
100
+ return allowedHost(u.hostname, entries);
101
+ }
102
+
103
+ // Refused IPv4 ranges: unspecified, private, shared, loopback, link-local (the metadata address), documentation,
104
+ // benchmarking, multicast and reserved.
105
+ const REFUSED_RANGES = [
106
+ ['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], ['172.16.0.0', 12],
107
+ ['192.0.0.0', 24], ['192.0.2.0', 24], ['192.88.99.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['198.51.100.0', 24],
108
+ ['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4], ['255.255.255.255', 32]
109
+ ];
110
+ function ipv4(raw) {
111
+ if (typeof raw !== 'string' || !/^\d{1,3}(?:\.\d{1,3}){3}$/.test(raw)) return null;
112
+ const parts = raw.split('.').map(Number);
113
+ if (parts.some(p => p > 255)) return null;
114
+ return ((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3];
115
+ }
116
+ /** Whether an address is a public IPv4 address. IPv6 is never used, so it is never public here. */
117
+ export function isPublicAddress(raw) {
118
+ const n = ipv4(raw);
119
+ if (n === null) return false;
120
+ return !REFUSED_RANGES.some(([base, bits]) => {
121
+ const mask = (0xffffffff << (32 - bits)) >>> 0;
122
+ return ((n & mask) >>> 0) === ((ipv4(base) & mask) >>> 0);
123
+ });
124
+ }
125
+
126
+ /** A fresh lookup of a name's IPv4 answers on this machine. */
127
+ export async function lookupAddresses(host, { lookup = dns.promises.lookup } = {}) {
128
+ const answers = await lookup(host, { all: true, family: 4 });
129
+ return [...new Set((answers || []).map(a => a && a.address).filter(Boolean))];
130
+ }
131
+
132
+ /**
133
+ * Chromium's arguments for a run with access: every outside connection through the proxy, and nothing else resolved.
134
+ * `direct` names the build itself as `host:port` (the runner's own server, a local run's --build-url): only that
135
+ * origin's host and port go direct. `<-loopback>` takes away Chromium's own bypass for loopback and link-local
136
+ * addresses, so a socket to another local port or the metadata address meets the proxy too, which refuses it.
137
+ */
138
+ export function egressBrowserArgs(proxyUrl, { direct = [] } = {}) {
139
+ const own = [...new Set((direct || []).map(h => String(h || '').toLowerCase()).filter(h => /^(?:\[[0-9a-f:]+\]|[a-z0-9.-]+):\d{1,5}$/.test(h)))];
140
+ // The resolver rules reach an address literal too, so the build's own host is excluded whatever it is.
141
+ const names = [...new Set(own.map(h => h.replace(/:\d+$/, '')).filter(h => !h.startsWith('[')))];
142
+ return [`--proxy-server=${proxyUrl}`, `--proxy-bypass-list=${['<-loopback>', ...own].join(';')}`,
143
+ `--host-resolver-rules=${['MAP * ~NOTFOUND', 'EXCLUDE localhost', ...names.map(h => `EXCLUDE ${h}`)].join(', ')}`,
144
+ '--disable-quic', '--force-webrtc-ip-handling-policy=disable_non_proxied_udp'];
145
+ }
146
+
147
+ /** A host's spelling only (lower case, no brackets or trailing dot), before any rule refuses it: how passthrough is matched. */
148
+ const spelled = raw => String(raw || '').trim().toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
149
+
150
+ const bump = (map, key, max) => { if (map.size < max || map.has(key)) map.set(key, Math.min(1e6, (map.get(key) || 0) + 1)); };
151
+ const listed = map => [...map.entries()].map(([host, count]) => ({ host, count })).sort((a, b) => b.count - a.count || a.host.localeCompare(b.host));
152
+
153
+ /**
154
+ * One run's access. `entries` are the run's listed hosts (parseEntries). `resolve(host)` answers the addresses to
155
+ * try (a fresh lookup on this machine, or the addresses the cloud machine opened at boot). `passthrough` names hosts
156
+ * let through that are not the studio's (the game's own analytics calls on a local run), never counted as reached.
157
+ * `allowPrivate` is a test-only option handed in code. `start()` opens the proxy on 127.0.0.1 and answers its URL.
158
+ */
159
+ export function createEgress({ entries, resolve = host => lookupAddresses(host), passthrough = [], allowPrivate = false, limits = LIMITS, connect = net.connect } = {}) {
160
+ const list = Array.isArray(entries) ? entries.filter(e => e && typeof e.host === 'string') : [];
161
+ const through = new Set((passthrough || []).map(spelled).filter(Boolean));
162
+ const reached = new Map(), blocked = new Map(), refused = { notListed: 0, notHttps: 0, privateAddress: 0, unresolved: 0, unreachable: 0, limit: 0 };
163
+ let server = null, tunnels = 0, total = 0, passed = 0;
164
+ const sockets = new Set();
165
+
166
+ const noteBlocked = (label, reason = 'notListed') => {
167
+ if (Object.hasOwn(refused, reason)) refused[reason] = Math.min(1e6, refused[reason] + 1);
168
+ // Only what a host can spell reaches the report.
169
+ bump(blocked, String(label || 'unknown').toLowerCase().replace(/[^a-z0-9.:/\[\]-]/g, '').slice(0, 120) || 'unknown', limits.hostsTracked);
170
+ };
171
+
172
+ /** What the proxy does with one CONNECT target: `{ host, port, pass }` to go on, or `{ reason, label }` to refuse. */
173
+ function decide(target) {
174
+ const m = /^\[?([^\]\s]+?)\]?:(\d{1,5})$/.exec(String(target || ''));
175
+ if (!m) return { reason: 'notListed', label: String(target || 'unknown').toLowerCase().slice(0, 120) };
176
+ const rawHost = m[1].toLowerCase(), port = Number(m[2]);
177
+ const label = port === 443 ? rawHost : `${rawHost}:${port}`;
178
+ // Our own ingest host is refused by the list rules, so a passthrough is matched by its spelling, never an address.
179
+ const pass = through.has(spelled(rawHost)) && !/^[\d.]+$|:/.test(spelled(rawHost));
180
+ const host = pass ? spelled(rawHost) : normalizeHost(rawHost);
181
+ if (!host || (!pass && !allowedHost(host, list))) return { reason: 'notListed', label };
182
+ if (port !== 443) return { reason: 'notHttps', label };
183
+ return { host, port, pass };
184
+ }
185
+
186
+ async function onConnect(req, client, head) {
187
+ client.on('error', () => {});
188
+ const d = decide(req.url);
189
+ const deny = (status, reason, label) => {
190
+ noteBlocked(label, reason);
191
+ try { client.end(`HTTP/1.1 ${status} Blocked\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`); } catch { /* gone */ }
192
+ };
193
+ if (d.reason) return deny(403, d.reason, d.label);
194
+ if (tunnels >= limits.tunnels || total >= limits.connections) return deny(429, 'limit', d.host);
195
+ total++;
196
+ let addresses;
197
+ try { addresses = await resolve(d.host); } catch { addresses = []; }
198
+ addresses = Array.isArray(addresses) ? addresses.filter(a => typeof a === 'string') : [];
199
+ if (!addresses.length) return deny(502, 'unresolved', d.host);
200
+ // One private answer refuses the name: a rebinding name mixes a public answer with an internal one.
201
+ if (!allowPrivate && addresses.some(a => !isPublicAddress(a))) return deny(403, 'privateAddress', d.host);
202
+ tunnels++;
203
+ let closed = false;
204
+ const done = () => { if (!closed) { closed = true; tunnels--; } };
205
+ const attempt = i => {
206
+ if (i >= addresses.length || client.destroyed) { done(); return deny(502, 'unreachable', d.host); }
207
+ const upstream = connect({ host: addresses[i], port: d.port });
208
+ sockets.add(upstream);
209
+ const timer = setTimeout(() => upstream.destroy(new Error('connect_timeout')), limits.connectMs);
210
+ upstream.once('error', () => { clearTimeout(timer); sockets.delete(upstream); if (!upstream.rsOpen) attempt(i + 1); else { done(); client.destroy(); } });
211
+ upstream.once('connect', () => {
212
+ clearTimeout(timer);
213
+ upstream.rsOpen = true;
214
+ // The page gave up while the address was dialled: nothing was reached.
215
+ if (client.destroyed) { done(); upstream.destroy(); sockets.delete(upstream); return; }
216
+ if (d.pass) passed++; else bump(reached, d.host, limits.hostsTracked);
217
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
218
+ if (head && head.length) upstream.write(head);
219
+ upstream.setTimeout(limits.idleMs, () => upstream.destroy());
220
+ client.setTimeout(limits.idleMs, () => client.destroy());
221
+ upstream.pipe(client);
222
+ client.pipe(upstream);
223
+ const end = () => { done(); upstream.destroy(); client.destroy(); sockets.delete(upstream); };
224
+ upstream.once('close', end);
225
+ client.once('close', end);
226
+ });
227
+ };
228
+ attempt(0);
229
+ }
230
+
231
+ // A plain http request through the proxy: never sent, counted by host.
232
+ function onRequest(req, res) {
233
+ let label = 'unknown';
234
+ try { label = hostLabel(req.url); } catch { label = 'unknown'; }
235
+ noteBlocked(label, 'notHttps');
236
+ res.writeHead(403, { 'content-type': 'text/plain', connection: 'close' });
237
+ res.end('blocked');
238
+ }
239
+
240
+ return {
241
+ entries: list,
242
+ noteBlocked,
243
+ /** Whether the page may ask for a URL (the route's own check, before the proxy sees it). */
244
+ allows: raw => allowedUrl(raw, list),
245
+ async start() {
246
+ server = http.createServer(onRequest);
247
+ server.on('connect', (req, socket, head) => { sockets.add(socket); socket.once('close', () => sockets.delete(socket)); onConnect(req, socket, head).catch(() => socket.destroy()); });
248
+ server.on('clientError', (_e, socket) => socket.destroy());
249
+ await new Promise((ok, fail) => { server.once('error', fail); server.listen(0, '127.0.0.1', ok); });
250
+ const port = server.address().port;
251
+ return { port, url: `http://127.0.0.1:${port}` };
252
+ },
253
+ async close() {
254
+ for (const s of sockets) s.destroy();
255
+ sockets.clear();
256
+ if (server) await new Promise(ok => server.close(() => ok()));
257
+ server = null;
258
+ },
259
+ summary() {
260
+ return { on: true, hosts: list.map(entryText), reached: listed(reached), blocked: listed(blocked), refused: { ...refused }, passthrough: passed };
261
+ }
262
+ };
263
+ }
264
+
265
+ /** A run's summary when it had no access: the hosts the page asked for, blocked, by host. */
266
+ export function offSummary(blockedHosts = []) {
267
+ return { on: false, hosts: [], reached: [], blocked: (blockedHosts || []).map(b => ({ host: String(b.host), count: Number(b.count) || 0 })), refused: null, passthrough: 0 };
268
+ }
269
+
270
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
271
+
272
+ /**
273
+ * The report's Network line, in plain words, for a run that had access: the hosts it could reach, those it did
274
+ * (connections) and the blocked attempts by host. `notes` are lines the runner adds (what was not enforced).
275
+ */
276
+ export function networkLines(summary, { notes = [] } = {}) {
277
+ if (!summary || !summary.on) return [];
278
+ const hosts = summary.hosts.length ? summary.hosts.join(', ') : 'none';
279
+ const reached = summary.reached.length ? summary.reached.slice(0, 10).map(r => `${r.host} (${plural(r.count, 'connection')})`).join(', ') : 'none';
280
+ const blocked = summary.blocked.length ? summary.blocked.slice(0, 10).map(b => `${b.host} (${plural(b.count, 'attempt')})`).join(', ') : 'none';
281
+ return [`**Network:** this run could reach your game's servers: ${hosts}. Reached: ${reached}. Blocked: ${blocked}.`, ...notes];
282
+ }