ravensight-playtest 0.17.0 → 0.18.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ravensight-playtest",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "Local AI playtests and seeded game simulations with reports in Ravensight.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://ravensight.io/docs/playtest/",
@@ -327,7 +327,7 @@ export function fakeCore({
327
327
  },
328
328
  async uploads(gameId, jobId, body) {
329
329
  record('uploads', { jobId, body });
330
- return { urls: body.files.map(file => ({ path: file.path, put_url: 'https://storage.test/x', tagging: null })) };
330
+ return { urls: body.files.map(file => ({ path: file.path, put_url: 'https://files.ravensight.io/artifacts/x', tagging: null })) };
331
331
  },
332
332
  async findings(gameId, query) {
333
333
  record('findings', { gameId, query });
@@ -12,6 +12,7 @@ import { buildPack, HOSTED_GODOT, PACK_NAME } from '../simulation/godotPack.js';
12
12
  import { defaultBase } from './validate.js';
13
13
  import { DIMENSION_3D, dimensionGate } from '../run/dimension.js';
14
14
  import { queueInfo, queueLine } from '../hosted/status.js';
15
+ import { uploadHostAllowed } from '../upload/host.js';
15
16
 
16
17
  /**
17
18
  * `ravensight-playtest validate <branch> --hosted`: two uploaded Godot builds, the
@@ -96,7 +97,9 @@ async function ensureBuild({ api, gameId, built, sleep, fetchImpl, log, label, c
96
97
  }, `pack-${createHash('sha256').update(`${gameId}:${built.sha256}`).digest('hex').slice(0, 40)}`);
97
98
  createdIds.push(created.build);
98
99
  log(`Uploading ${label}: ${(built.bytes / 1e6).toFixed(1)} MB. Holding ${money(capabilities.reservationOffer.amountCents)} of the price as its deposit.`);
99
- const put = await fetchImpl(created.upload.url, { method: created.upload.method || 'PUT', headers: created.upload.headers, body: built.zip });
100
+ // Our own file host only (or today's storage host until the switch), a PUT, and never a redirect: checked before a byte is sent.
101
+ if (created.upload?.method !== 'PUT' || !uploadHostAllowed(created.upload?.url)) throw new Error(`The server did not return a supported private upload destination for ${label}.`);
102
+ const put = await fetchImpl(created.upload.url, { method: 'PUT', headers: created.upload.headers, body: built.zip, redirect: 'error' });
100
103
  if (!put.ok) throw new Error(`The upload of ${label} was refused (${put.status}).`);
101
104
  await api.hosted.completeBuild(gameId, created.build.buildId);
102
105
  build = await find() || created.build;
@@ -6,19 +6,20 @@ import { CliError } from '../errors.js';
6
6
  import { ApiError } from '../api/errors.js';
7
7
  import { writeJson } from '../fsutil.js';
8
8
  import { printable } from '../ui/index.js';
9
+ import { uploadHostAllowed } from '../upload/host.js';
9
10
  import { openBuildArchive, inspectBuildArchive, buildLimits, limitsFromProfile, chooseEntrypoint } from './archivePreflight.js';
10
11
 
11
12
  const fail = message => { throw new CliError(message); };
12
13
  const base = game => `/api/v1/games/${encodeURIComponent(game)}/playtest/hosted`;
13
14
  const body = answer => answer.body;
14
15
  const money = cents => `$${(cents / 100).toFixed(2)}`;
15
- // The storage host the API signs uploads for; moves to files.ravensight.io.
16
- const STORAGE_HOST = /^[a-z0-9.-]+\.s3\.[a-z0-9-]+\.amazonaws\.com$/;
17
16
 
18
- export function singlePut(upload, { size, sha256, uploadExpiresAt }, now = Date.now()) {
19
- const url = new URL(upload?.url), headers = upload?.headers;
20
- if (upload.method !== 'PUT' || url.protocol !== 'https:' || url.port || url.username || url.password || url.hash
21
- || !STORAGE_HOST.test(url.hostname)) fail('The server did not return a supported private upload destination. Preserve the original upload journal.');
17
+ // `hosts` replaces the upload host check's lists (tests only).
18
+ export function singlePut(upload, { size, sha256, uploadExpiresAt }, now = Date.now(), hosts = undefined) {
19
+ // Our own file host only (or today's storage host until the switch): checked before anything is sent.
20
+ if (!uploadHostAllowed(upload?.url, hosts)) fail('The server did not return a supported private upload destination. Preserve the original upload journal.');
21
+ const url = new URL(upload.url), headers = upload?.headers;
22
+ if (upload.method !== 'PUT' || url.protocol !== 'https:' || url.port || url.username || url.password || url.hash) fail('The server did not return a supported private upload destination. Preserve the original upload journal.');
22
23
  const expected = { 'content-type': 'application/zip', 'if-none-match': '*', 'x-amz-checksum-sha256': Buffer.from(sha256, 'hex').toString('base64'), 'x-amz-server-side-encryption': 'AES256' };
23
24
  if (!headers || Object.keys(headers).sort().join(',') !== Object.keys(expected).sort().join(',')
24
25
  || Object.entries(expected).some(([key, value]) => headers[key] !== value)) fail('The upload headers do not match the inspected archive. Preserve the original upload journal.');
@@ -51,10 +52,11 @@ export const PART_TRIES = 4;
51
52
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
52
53
 
53
54
  /** One part of a multipart upload as the server signed it: its number, exact length and private upload URL. */
54
- function signedPart(part, { number, bytes, uploadId }) {
55
+ function signedPart(part, { number, bytes, uploadId }, hosts = undefined) {
55
56
  let url;
56
- try { url = new URL(part?.url); } catch { fail('The server did not return a supported private upload destination. Preserve the original upload journal.'); }
57
- if (part.partNumber !== number || part.bytes !== bytes || url.protocol !== 'https:' || url.port || url.username || url.password || url.hash || !STORAGE_HOST.test(url.hostname)
57
+ if (!uploadHostAllowed(part?.url, hosts)) fail('The upload parts do not match the inspected archive. Preserve the original upload journal.');
58
+ try { url = new URL(part.url); } catch { fail('The server did not return a supported private upload destination. Preserve the original upload journal.'); }
59
+ if (part.partNumber !== number || part.bytes !== bytes || url.protocol !== 'https:' || url.port || url.username || url.password || url.hash
58
60
  || url.searchParams.get('partNumber') !== String(number) || url.searchParams.get('uploadId') !== uploadId
59
61
  || !/^\d{8}T\d{6}Z$/.test(url.searchParams.get('X-Amz-Date') || '')) fail('The upload parts do not match the inspected archive. Preserve the original upload journal.');
60
62
  return { number, bytes, url: url.href };
@@ -66,7 +68,7 @@ function signedPart(part, { number, bytes, uploadId }) {
66
68
  * archive's exact length. A build over the server's single upload size (300
67
69
  * MiB today) is sent this way, up to 4 GiB.
68
70
  */
69
- export function multipartPlan(upload, { size, uploadExpiresAt }, now = Date.now()) {
71
+ export function multipartPlan(upload, { size, uploadExpiresAt }, now = Date.now(), hosts = undefined) {
70
72
  const partBytes = upload?.partBytes, uploadId = upload?.uploadId, until = Date.parse(uploadExpiresAt);
71
73
  if (upload?.method !== 'MULTIPART' || !Number.isSafeInteger(partBytes) || partBytes < 5 * 1024 * 1024 || typeof uploadId !== 'string' || !uploadId || uploadId.length > 2048
72
74
  || !Number.isSafeInteger(size) || size < 1 || !Array.isArray(upload.parts)) fail('The server did not return a supported multipart upload. Preserve the original upload journal.');
@@ -74,7 +76,7 @@ export function multipartPlan(upload, { size, uploadExpiresAt }, now = Date.now(
74
76
  if (upload.parts.length !== count || count > 10000) fail('The upload parts do not match the inspected archive. Preserve the original upload journal.');
75
77
  if (!Number.isFinite(until) || until <= now) fail('The original upload window has expired. Do not create a replacement reservation automatically.');
76
78
  const bytesOf = number => (number < count ? partBytes : size - partBytes * (count - 1));
77
- return { uploadId, partBytes, count, expiresAt: until, bytesOf, parts: upload.parts.map((part, i) => signedPart(part, { number: i + 1, bytes: bytesOf(i + 1), uploadId })) };
79
+ return { uploadId, partBytes, count, expiresAt: until, bytesOf, parts: upload.parts.map((part, i) => signedPart(part, { number: i + 1, bytes: bytesOf(i + 1), uploadId }, hosts)) };
78
80
  }
79
81
 
80
82
  /**
@@ -83,7 +85,7 @@ export function multipartPlan(upload, { size, uploadExpiresAt }, now = Date.now(
83
85
  * that fails is sent again (the same bytes; storage keeps the last), and a part
84
86
  * whose URL storage refuses is signed again by `resign(partNumber)`, once.
85
87
  */
86
- export async function putParts(archive, plan, { fetchImpl = globalThis.fetch, signal, onProgress, resign, sleepImpl = sleep } = {}) {
88
+ export async function putParts(archive, plan, { fetchImpl = globalThis.fetch, signal, onProgress, resign, sleepImpl = sleep, hosts } = {}) {
87
89
  await archive.check();
88
90
  const done = [];
89
91
  let sent = 0;
@@ -106,7 +108,7 @@ export async function putParts(archive, plan, { fetchImpl = globalThis.fetch, si
106
108
  } finally { stream.destroy(); }
107
109
  if (status >= 200 && status < 300 && typeof etag === 'string' && /^"?[A-Za-z0-9+/=_-]{1,128}"?$/.test(etag)) { done.push({ partNumber: part.number, etag }); sent += part.bytes; break; }
108
110
  // Refused: most often a URL that outlived the credentials that signed it. Ask for a fresh one, once.
109
- if (status === 403 && typeof resign === 'function' && !resigned) { resigned = true; part = signedPart(await resign(part.number), { number: part.number, bytes: part.bytes, uploadId: plan.uploadId }); continue; }
111
+ if (status === 403 && typeof resign === 'function' && !resigned) { resigned = true; part = signedPart(await resign(part.number), { number: part.number, bytes: part.bytes, uploadId: plan.uploadId }, hosts); continue; }
110
112
  const again = network || status >= 500 || status === 429 || status === 408;
111
113
  if (!again || attempt >= PART_TRIES) fail(`Part ${part.number} of ${plan.count} of the original archive upload ${network ? 'could not be sent' : `returned HTTP ${status}`}. Preserve the journal; no replacement reservation was requested.`);
112
114
  await sleepImpl(Math.min(30000, 1000 * 2 ** (attempt - 1)));
@@ -27,7 +27,7 @@
27
27
  // Nothing here calls a model, and nothing changes what a run costs to
28
28
  // register. The pure parts (memory, control book, language, kinds, the sound
29
29
  // record) are the same files the hosted runner carries.
30
- import { createMemory, cleanNote, MEMORY_MAX_CHARS } from './memory.js';
30
+ import { createMemory, cleanNote, MEMORY_MAX_CHARS, MISREAD_NOT_OVER, STUCK_NOTE_AFTER, createStuckWatch } from './memory.js';
31
31
  import { createControlBook } from './controlbook.js';
32
32
  import { createGenre, KIND_IDS, KINDS } from './genre.js';
33
33
  import { detectLanguage, reportLanguage, QUOTE_AS_WRITTEN } from './language.js';
@@ -82,6 +82,13 @@ const KEEP = [
82
82
  [/^\s*where\s*[::]\s*/i, 'place']
83
83
  ];
84
84
  const KIND_NOTE = /^\s*kind\s*[::]\s*([\w -]+)/i;
85
+ // The persona believes the game is over: its own note says it lost, or the input says it expects a restart.
86
+ const OVER_NOTE = /\bgame ?over\b|\byou (?:died|lost|lose)\b|\bout of (?:lives|hearts)\b/i;
87
+ const OVER_EXPECT = /\bgame ?over\b|\brestart|\bretry\b|\btry again\b|\bplay again\b|\bnew game\b/i;
88
+
89
+ // Self-learning within the run (level 1 of the playtester's notes on its own play), as the hosted runner keeps it: the
90
+ // note texts and the stuck watch are the shared ./memory.js. Re-exported for callers and tests.
91
+ export { MISREAD_NOT_OVER, STUCK_NOTE_AFTER };
85
92
  const ABOUT_NOTE = /^\s*(?:game|about)\s*[::]\s*/i;
86
93
 
87
94
  /**
@@ -113,8 +120,12 @@ export function actionOf(tool, input = {}) {
113
120
  * it; `controls` the studio's own words about its controls, when the brief
114
121
  * has them; `touch` whether the run is played with a finger (--phone).
115
122
  */
116
- export function createLocalAnyGame({ briefText = '', controls = null, touch = false, continuousTime = false, reportLanguageHint = null, driverName = '' } = {}) {
123
+ export function createLocalAnyGame({ briefText = '', controls = null, touch = false, continuousTime = false, reportLanguageHint = null, driverName = '', selfNotes = true } = {}) {
117
124
  const memory = createMemory();
125
+ // The playtester's notes on its own play within the run (a misread game over, what got past a stuck stretch), unless
126
+ // the studio switched them off for this game (the run memory answer's `self: false`, ../gameMemory.js readRunNotes).
127
+ const stuckWatch = createStuckWatch();
128
+ let overSaid = false;
118
129
  const book = createControlBook({ touch, given: controls });
119
130
  const genre = createGenre();
120
131
  const briefLanguage = detectLanguage(briefText);
@@ -122,7 +133,7 @@ export function createLocalAnyGame({ briefText = '', controls = null, touch = fa
122
133
  let sound = null, soundTest = null;
123
134
  let soundControl = false;
124
135
  let gameText = '', gameLanguage = null, styleSaid = false, shownAt = -Infinity, shownText = '', droppedSeen = 0, actionsSeen = 0, eventsSeen = 0;
125
- const stats = { asides: 0, asideChars: 0, maxAsideChars: 0, kept: 0 };
136
+ const stats = { asides: 0, asideChars: 0, maxAsideChars: 0, kept: 0, misreadsKept: 0, stuckPastKept: 0 };
126
137
 
127
138
  /** The lines added to the system prompt once: fixed for the run, so the cache holds them. */
128
139
  function systemText() {
@@ -181,6 +192,16 @@ export function createLocalAnyGame({ briefText = '', controls = null, touch = fa
181
192
  book.record({ action: a, changed, expect: typeof input.expect === 'string' ? input.expect : '', step: action });
182
193
  const what = cleanNote(label || tool, 60);
183
194
  if (changed) memory.worked(memory.place, what); else memory.failed(memory.place, what, action);
195
+ // Enter on a screen the persona took for a game over, and nothing happened: the game was not over.
196
+ const expect = typeof input.expect === 'string' ? input.expect : '';
197
+ if (tool === 'key' && !changed && /^enter$/i.test(a.args?.name || '') && (overSaid || OVER_EXPECT.test(expect))) {
198
+ overSaid = false;
199
+ if (selfNotes && memory.learn({ t: 'rule', s: MISREAD_NOT_OVER }, { step: action })) stats.misreadsKept++;
200
+ }
201
+ if (changed) overSaid = false;
202
+ // What got it past a stretch where nothing responded: the input itself, without the run's own points.
203
+ const past = stuckWatch.input(memory.place, what, changed);
204
+ if (past && selfNotes && memory.learn({ t: 'control', s: past }, { step: action })) stats.stuckPastKept++;
184
205
  }
185
206
 
186
207
  /** One note the persona wrote. A marked reaction note is kept; a note about the game is remembered as reported. */
@@ -191,8 +212,10 @@ export function createLocalAnyGame({ briefText = '', controls = null, touch = fa
191
212
  const kind = KIND_NOTE.exec(text);
192
213
  if (kind) { genre.read(kind[1].trim(), action); genre.read(kind[1].trim(), action); return 'kind'; }
193
214
  if (ABOUT_NOTE.test(text)) { memory.setAbout(text.replace(ABOUT_NOTE, ''), action); return 'about'; }
215
+ if (OVER_NOTE.test(text)) overSaid = true;
194
216
  for (const [re, t] of KEEP) {
195
217
  if (!re.test(text)) continue;
218
+ if (t === 'death') overSaid = true;
196
219
  stats.kept++;
197
220
  memory.learn({ t, s: text.replace(re, '') }, { step: action });
198
221
  return t;
@@ -318,7 +341,7 @@ export function createLocalAnyGame({ briefText = '', controls = null, touch = fa
318
341
  }
319
342
 
320
343
  function digest() {
321
- return { language: { brief: briefLanguage, game: gameLanguage, report }, kind: genre.digest(), timing: { continuous: continuousTime, source: continuousTime ? 'native driver capability' : 'not asserted by this runner' }, controls: book.digest(), memory: memory.digest(), sound: sound ? sound.summary() : null, soundControl, stats: { ...stats } };
344
+ return { language: { brief: briefLanguage, game: gameLanguage, report }, kind: genre.digest(), timing: { continuous: continuousTime, source: continuousTime ? 'native driver capability' : 'not asserted by this runner' }, controls: book.digest(), memory: memory.digest(), sound: sound ? sound.summary() : null, soundControl, selfNotes: Boolean(selfNotes), stats: { ...stats } };
322
345
  }
323
346
 
324
347
  return { systemText, seeScreen, seeEvents, afterAction, afterNote, aside, notebook, soundAvailable, afterSound, soundFindings, soundEvidence, capabilityNotes, reportLines, digest, memory, book, genre, get report() { return report; } };
@@ -61,6 +61,37 @@ export const OBSERVE_MAX_CHARS = 4000;
61
61
  export const OBSERVE_MAX_TEXTS = 60;
62
62
  export const OBSERVE_MAX_EVENTS = 200;
63
63
 
64
+ // Self-learning within a run (level 1 of the playtester's notes on its own play): a moment the playtester misread, and
65
+ // what got it past a stretch where nothing responded, go into the run's memory, so a plan or a turn much later still
66
+ // knows them. Neither states a number, so the memory's record rule never holds them back. Both are off when the
67
+ // studio switched the game's self notes off (the run memory answer's `self: false`).
68
+ export const MISREAD_NOT_OVER = 'Misread: a screen read as game over was not one; Enter did nothing and play went on';
69
+ // Inputs in a row that changed nothing on one place before the input that changed it is worth remembering.
70
+ export const STUCK_NOTE_AFTER = 4;
71
+
72
+ /**
73
+ * A stretch of inputs that changed nothing on one place, followed input by input. `input(place, label, changed)`
74
+ * answers the note to keep when an input changed the screen after at least STUCK_NOTE_AFTER on the same place that did
75
+ * not, else null. The input is kept without the run's own points; one that still names a number is not kept.
76
+ */
77
+ export function createStuckWatch() {
78
+ let run = 0, at = null;
79
+ return {
80
+ input(place, label, changed) {
81
+ if (changed === false) {
82
+ if (at !== place) { at = place; run = 0; }
83
+ run++;
84
+ return null;
85
+ }
86
+ if (changed !== true) return null;
87
+ const what = String(label || '').replace(/\s*(?:at\s*)?\(?\d{1,4}\s*,\s*\d{1,4}\)?/g, '').replace(/\s+/g, ' ').trim();
88
+ const note = run >= STUCK_NOTE_AFTER && at === place && what && !/\d/.test(what) ? `Got past a stuck stretch${place ? ` on ${place}` : ''} with ${what}` : null;
89
+ run = 0;
90
+ return note;
91
+ }
92
+ };
93
+ }
94
+
64
95
  const norm = s => String(s ?? '').normalize('NFKC');
65
96
  /** A note's text made safe to carry: one line, no braces or quotes that could be read as structure. */
66
97
  export function cleanNote(text, max = FACT_MAX_CHARS) {
@@ -2,7 +2,7 @@
2
2
  "comment": "Hashes of the files shared by the hosted runner (lib/anygame/*.mjs including gamenotes, and lib/claimwords.mjs, lib/events.mjs, lib/eventclaims.mjs, lib/egress.mjs) and the local CLI (src/run/anygame/*.js, and src/run/claimwords.js, src/run/events.js, src/run/eventclaims.js, src/run/egress.js), taken over the code both carry (see shared.mjs or shared.js). The same file in both repos: update it in both, after copying the change.",
3
3
  "files": {
4
4
  "language": "2b95828c77a8e82440c53d330381b7ba830796312d2ae9b7edc8fd95ff72e1ef",
5
- "memory": "7cab932cd9e23ee84aa4f60d14b89e4ce2e4b0b9fc6e87c963b2d04e084256b8",
5
+ "memory": "76ad175baeb3f066ff566f76460d4b414c545f683fe4fe0ab16b0125a63d3fce",
6
6
  "controlbook": "1b388c0dd0c60f332131a095cf89eb4ee181671c60a2b4e45750a0a918c6ea9e",
7
7
  "genre": "a52359537d277a59976bc6ce77fbc1e21303f10861ff77226164a9884d2b543b",
8
8
  "sound": "bc1264cb971417f4c6c6966ecba217721e59bc30dc069b48ade0bf8174e1444e",
@@ -94,8 +94,9 @@ export async function buildIdentity({ driverName, target, projectDir = null, bui
94
94
  }
95
95
 
96
96
  /**
97
- * The notes earlier playtests of this game kept, for this build: `{ save, notes }`
98
- * from the server, or null when the server has no memory route, memory could not
97
+ * The notes earlier playtests of this game kept, for this build: `{ save, notes, self }`
98
+ * from the server (`self`: whether the studio lets the playtester keep notes on its own
99
+ * play, on when a server that predates the switch does not say), or null when the server has no memory route, memory could not
99
100
  * be read, or the answer is not one. Never throws: a run never waits on memory.
100
101
  */
101
102
  export async function readRunNotes(api, gameId, buildSha256, { log = () => {} } = {}) {
@@ -103,7 +104,7 @@ export async function readRunNotes(api, gameId, buildSha256, { log = () => {} }
103
104
  try {
104
105
  const answer = await api.memory.runNotes(gameId, buildSha256);
105
106
  if (!answer || typeof answer.save !== 'boolean' || !Array.isArray(answer.notes)) return null;
106
- return { save: answer.save, notes: answer.notes };
107
+ return { save: answer.save, notes: answer.notes, self: answer.self !== false };
107
108
  } catch (error) {
108
109
  log(`this game's playtest memory could not be read (${String(error && error.message ? error.message : error).slice(0, 120)}); the run plays without it and hands nothing on.`);
109
110
  return null;
@@ -930,7 +930,7 @@ async function playLoop({
930
930
  const noisePatterns = (localBrief && Array.isArray(localBrief.expected_noise)) ? localBrief.expected_noise : [];
931
931
  // any-game hook: one notebook a run, on the honesty record so the report step reads the same one.
932
932
  const briefFields = brief && brief.fields && typeof brief.fields === 'object' ? brief.fields : brief || {};
933
- const anyGame = honesty.anygame || (honesty.anygame = createLocalAnyGame({ briefText: briefForPrompt(brief), controls: briefFields.build_notes && typeof briefFields.build_notes.controls === 'string' ? briefFields.build_notes.controls : null, touch: Boolean(driver && driver.touch), reportLanguageHint: briefFields.play && typeof briefFields.play.report_language === 'string' ? briefFields.play.report_language : null, continuousTime: driver?.inputProfile === 'native-mobile' && driver.frozenBetweenActions === false, driverName: typeof driver.soundSelfTest === 'function' ? '' : driverName }));
933
+ const anyGame = honesty.anygame || (honesty.anygame = createLocalAnyGame({ briefText: briefForPrompt(brief), controls: briefFields.build_notes && typeof briefFields.build_notes.controls === 'string' ? briefFields.build_notes.controls : null, touch: Boolean(driver && driver.touch), reportLanguageHint: briefFields.play && typeof briefFields.play.report_language === 'string' ? briefFields.play.report_language : null, continuousTime: driver?.inputProfile === 'native-mobile' && driver.frozenBetweenActions === false, driverName: typeof driver.soundSelfTest === 'function' ? '' : driverName, selfNotes: Boolean(earlierMemory) && earlierMemory.self !== false }));
934
934
  system.push({ type: 'text', text: anyGame.systemText() });
935
935
  // The intent check (./intent.js): one watch a run, on the honesty record so the report step reads the same one. Every answer,
936
936
  // miss and refused repeat is a line of the step log.
@@ -0,0 +1,40 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ /*
4
+ * The upload host check, version 1: the same eight steps as the platform's
5
+ * reference and every Ravensight SDK (shared cases in
6
+ * test/fixtures/upload-host-vectors.json). An upload address the API returns
7
+ * must pass before a byte of a run or a build is sent.
8
+ */
9
+ export const UPLOAD_HOST_CHECK_VERSION = 1;
10
+ export const MAX_UPLOAD_URL_LENGTH = 8192;
11
+ export const UPLOAD_ALLOWED_HOSTS = Object.freeze(['files.ravensight.io']);
12
+ // The storage hosts the API signs for today, kept until our own files host is
13
+ // switched on; see the platform's files domain plan.
14
+ export const UPLOAD_LEGACY_HOST_SHA256 = Object.freeze([
15
+ '122a74a5f5c4b2117d5164b9ee95b65acdcf84a07cd7f61f9c7866e77dce5d3b',
16
+ '06c38eaa529f42579c9f1c736ab9dedcb576ed537a927fc107ba49db7ba6e5b6',
17
+ 'd6659f726f4a58691c4004f477056bc8ea49bbc3a2e5215b7fea69cb0224a649'
18
+ ]);
19
+
20
+ /**
21
+ * Whether an upload address may be sent to. Never throws.
22
+ * @param {unknown} url
23
+ * @param {{allowedHosts?: readonly string[], legacyHostSha256?: readonly string[]}} [lists]
24
+ */
25
+ export function uploadHostAllowed(url, { allowedHosts = UPLOAD_ALLOWED_HOSTS, legacyHostSha256 = UPLOAD_LEGACY_HOST_SHA256 } = {}) {
26
+ if (typeof url !== 'string' || url.length < 1 || url.length > MAX_UPLOAD_URL_LENGTH) return false;
27
+ for (let i = 0; i < url.length; i += 1) {
28
+ const code = url.charCodeAt(i);
29
+ if (code < 0x21 || code > 0x7e) return false;
30
+ }
31
+ if (url.includes('@') || url.includes('\\') || url.includes('#')) return false;
32
+ if (!url.startsWith('https://')) return false;
33
+ const rest = url.slice('https://'.length);
34
+ const slash = rest.indexOf('/');
35
+ const host = slash === -1 ? rest : rest.slice(0, slash);
36
+ if (!/^[A-Za-z0-9.-]+$/.test(host)) return false;
37
+ const lower = host.toLowerCase();
38
+ if (allowedHosts.includes(lower)) return true;
39
+ return legacyHostSha256.includes(createHash('sha256').update(lower, 'utf8').digest('hex'));
40
+ }
@@ -14,6 +14,7 @@ import {
14
14
  skipReason
15
15
  } from './allowlist.js';
16
16
  import { STATUS, record, uploadedKeys, keyFor } from './queue.js';
17
+ import { uploadHostAllowed } from './host.js';
17
18
 
18
19
  const PUT_RETRIES = 4;
19
20
 
@@ -178,6 +179,18 @@ export async function putFile(options) {
178
179
  random = Math.random
179
180
  } = options;
180
181
 
182
+ // Our own file host only (or today's storage host until the switch), checked
183
+ // before anything is sent; the refusal never names the signed address.
184
+ if (!uploadHostAllowed(entry.put_url)) {
185
+ throw new ApiError({
186
+ status: 0,
187
+ code: 'upload_host_refused',
188
+ message: `PUT ${entry.path} refused: the server returned an upload address that is not Ravensight's own file host.`,
189
+ method: 'PUT',
190
+ path: entry.path
191
+ });
192
+ }
193
+
181
194
  const headers = { 'content-type': contentType };
182
195
  const tagging = taggingHeader(entry.tagging);
183
196
  if (tagging) headers['x-amz-tagging'] = tagging;
@@ -189,7 +202,8 @@ export async function putFile(options) {
189
202
  for (let attempt = 1; attempt <= retries + 1; attempt += 1) {
190
203
  let response = null;
191
204
  try {
192
- response = await fetchImpl(entry.put_url, { method: 'PUT', headers, body });
205
+ // A redirect is never followed: the signed address is the only destination.
206
+ response = await fetchImpl(entry.put_url, { method: 'PUT', headers, body, redirect: 'error' });
193
207
  } catch (cause) {
194
208
  lastError = new ApiError({
195
209
  status: 0,