ravensight-playtest 0.8.2 → 0.9.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.
@@ -1,6 +1,8 @@
1
1
  import { createServer } from 'node:http';
2
- import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';
2
+ import { createReadStream } from 'node:fs';
3
+ import { lstat, readdir, realpath, stat } from 'node:fs/promises';
3
4
  import path from 'node:path';
5
+ import { pipeline } from 'node:stream/promises';
4
6
  import { CliError } from '../errors.js';
5
7
 
6
8
  /**
@@ -19,8 +21,11 @@ import { CliError } from '../errors.js';
19
21
  * host, and that should keep working, without cookies.
20
22
  * - `no-store`, so a rebuilt export is never played from a stale cache.
21
23
  *
22
- * It reads only files under the build folder (no symlink out of it), answers
23
- * GET and HEAD only, and listens on the loopback address only.
24
+ * It reads only files under the build folder (no symlink out of it, no
25
+ * dotfile or dot folder), answers GET and HEAD only, listens on the loopback
26
+ * address only and answers only a loopback Host header, so a page elsewhere
27
+ * cannot reach it through a name that resolves to 127.0.0.1. Files are
28
+ * streamed, with a single byte range when one is asked for.
24
29
  */
25
30
 
26
31
  export const CONTENT_TYPES = Object.freeze({
@@ -80,6 +85,29 @@ export function pickEntry(names) {
80
85
  * @param {{entry?: string|null, host?: string}} [options]
81
86
  * @returns {Promise<{url: string, origin: string, entry: string, root: string, close: () => Promise<void>}>}
82
87
  */
88
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
89
+ const hidden = rel => rel.split('/').some(part => part.startsWith('.') && part.length > 0);
90
+
91
+ /** The file a request names inside root, or null: no escape, no dotfile, no symlink out. */
92
+ async function fileIn(root, rel) {
93
+ if (rel.includes('\0') || hidden(rel)) return null;
94
+ const file = path.resolve(root, '.' + (rel.startsWith('/') ? rel : '/' + rel));
95
+ if (file !== root && !file.startsWith(root + path.sep)) return null;
96
+ try {
97
+ const info = await lstat(file);
98
+ const real = await realpath(file);
99
+ const target = await stat(real);
100
+ if (!real.startsWith(root + path.sep) || !target.isFile() || (!info.isFile() && !info.isSymbolicLink())) return null;
101
+ return { real, size: target.size };
102
+ } catch { return null; }
103
+ }
104
+
105
+ /**
106
+ * Start serving a build folder.
107
+ * @param {string} dir
108
+ * @param {{entry?: string|null, host?: string}} [options] entry: the page to open, relative to dir (--build-entry)
109
+ * @returns {Promise<{url: string, origin: string, entry: string, root: string, close: () => Promise<void>}>}
110
+ */
83
111
  export async function serveBuildDir(dir, { entry = null, host = '127.0.0.1' } = {}) {
84
112
  let root;
85
113
  try {
@@ -89,26 +117,58 @@ export async function serveBuildDir(dir, { entry = null, host = '127.0.0.1' } =
89
117
  throw new CliError(`--build-dir ${dir} is not a folder. Point it at the folder your engine exported for the web (the one with the .html page).`);
90
118
  }
91
119
  const names = (await readdir(root, { withFileTypes: true })).filter(item => item.isFile()).map(item => item.name);
92
- const page = entry || pickEntry(names);
120
+ let page = null;
121
+ if (entry !== null && entry !== undefined) {
122
+ const named = String(entry).replace(/\\/g, '/').replace(/^\.\//, '');
123
+ if (!named || path.isAbsolute(named) || !(await fileIn(root, named))) {
124
+ throw new CliError(`--build-entry ${entry} is not a file inside --build-dir ${dir}. Name the page relative to that folder, such as play.html.`);
125
+ }
126
+ page = named;
127
+ } else page = pickEntry(names);
93
128
  if (!page) {
94
- throw new CliError(`--build-dir ${dir} has no index.html and no single .html page. Export the game for the web, or name its page in the folder${names.some(name => /\.html?$/i.test(name)) ? ' (there is more than one .html file: open the right one with --build-url)' : ''}.`);
129
+ throw new CliError(`--build-dir ${dir} has no index.html and no single .html page. Export the game for the web, or name its page in the folder${names.some(name => /\.html?$/i.test(name)) ? ' (there is more than one .html file: choose one with --build-entry <file>)' : ''}.`);
95
130
  }
131
+ let port = 0;
96
132
  const server = createServer((req, res) => {
97
- respond(root, req, res).catch(() => { if (!res.headersSent) res.writeHead(500, ISOLATION_HEADERS); res.end(); });
133
+ respond(root, port, req, res).catch(() => { if (!res.headersSent) res.writeHead(500, ISOLATION_HEADERS); res.end(); });
98
134
  });
99
135
  await new Promise((resolve, reject) => {
100
136
  server.once('error', reject);
101
137
  server.listen(0, host, resolve);
102
138
  });
139
+ port = server.address().port;
103
140
  // The server lives as long as the run that started it, and never keeps the
104
141
  // process alive on its own once the run is over.
105
142
  server.unref();
106
- const origin = `http://${host}:${server.address().port}`;
143
+ const origin = `http://${host}:${port}`;
107
144
  const url = `${origin}/${page.split('/').map(encodeURIComponent).join('/')}`;
108
145
  return { url, origin, entry: page, root, close: () => new Promise(resolve => server.close(() => resolve())) };
109
146
  }
110
147
 
111
- async function respond(root, req, res) {
148
+ /** True when the Host header names a loopback address on this server's port. */
149
+ export function loopbackHost(value, port) {
150
+ if (typeof value !== 'string') return false;
151
+ const match = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(value.trim().toLowerCase());
152
+ return Boolean(match) && LOOPBACK_HOSTS.has(match[1]) && Number(match[2]) === port;
153
+ }
154
+
155
+ /** A single `bytes=` range of a file of `size` bytes: {start, end}, null for none, or false when unsatisfiable. */
156
+ export function byteRange(header, size) {
157
+ if (typeof header !== 'string' || !header.trim()) return null;
158
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
159
+ if (!match || (!match[1] && !match[2])) return null; // several ranges or another unit: the whole file
160
+ let start, end;
161
+ if (!match[1]) { const suffix = Number(match[2]); if (!suffix) return false; start = Math.max(0, size - suffix); end = size - 1; }
162
+ else { start = Number(match[1]); end = match[2] ? Math.min(Number(match[2]), size - 1) : size - 1; }
163
+ if (start >= size || start > end) return false;
164
+ return { start, end };
165
+ }
166
+
167
+ async function respond(root, port, req, res) {
168
+ if (!loopbackHost(req.headers.host, port)) {
169
+ res.writeHead(421, ISOLATION_HEADERS);
170
+ return res.end();
171
+ }
112
172
  if (req.method !== 'GET' && req.method !== 'HEAD') {
113
173
  res.writeHead(405, { ...ISOLATION_HEADERS, allow: 'GET, HEAD' });
114
174
  return res.end();
@@ -120,18 +180,17 @@ async function respond(root, req, res) {
120
180
  }
121
181
  if (rel.includes('\0')) { res.writeHead(400, ISOLATION_HEADERS); return res.end(); }
122
182
  if (rel.endsWith('/')) rel += 'index.html';
123
- const file = path.resolve(root, '.' + rel);
124
- if (file !== root && !file.startsWith(root + path.sep)) { res.writeHead(404, ISOLATION_HEADERS); return res.end(); }
125
- let real;
126
- try {
127
- const info = await lstat(file);
128
- real = await realpath(file);
129
- if (!real.startsWith(root + path.sep) || !(await stat(real)).isFile() || (!info.isFile() && !info.isSymbolicLink())) throw new Error('outside');
130
- } catch {
131
- res.writeHead(404, ISOLATION_HEADERS);
183
+ const found = await fileIn(root, rel);
184
+ if (!found) { res.writeHead(404, ISOLATION_HEADERS); return res.end(); }
185
+ const headers = { ...contentHeaders(found.real), ...ISOLATION_HEADERS, 'accept-ranges': 'bytes' };
186
+ const range = byteRange(req.headers.range, found.size);
187
+ if (range === false) {
188
+ res.writeHead(416, { ...headers, 'content-range': `bytes */${found.size}` });
132
189
  return res.end();
133
190
  }
134
- const body = await readFile(real);
135
- res.writeHead(200, { ...contentHeaders(real), ...ISOLATION_HEADERS, 'content-length': body.length });
136
- res.end(req.method === 'HEAD' ? undefined : body);
191
+ const { start, end } = range || { start: 0, end: found.size - 1 };
192
+ res.writeHead(range ? 206 : 200, { ...headers, 'content-length': Math.max(0, end - start + 1),
193
+ ...(range ? { 'content-range': `bytes ${start}-${end}/${found.size}` } : {}) });
194
+ if (req.method === 'HEAD' || found.size === 0) return res.end();
195
+ await pipeline(createReadStream(found.real, { start, end }), res);
137
196
  }
@@ -8,9 +8,30 @@
8
8
  * Personas used when the developer names none. One since 0.3.2: a first run
9
9
  * should cost one persona run, and a second persona is one `--personas` away.
10
10
  * Spec 17 defaulted to two, which made the default run cost twice what most
11
- * customers expected to pay for a first look.
11
+ * customers expected to pay for a first look. Since 0.9.0 the one is
12
+ * fresh-eyes, the general first time player, the same persona a cloud
13
+ * playtest always includes.
12
14
  */
13
- export const DEFAULT_PERSONAS = Object.freeze(['curious-kid']);
15
+ export const DEFAULT_PERSONAS = Object.freeze(['fresh-eyes']);
16
+
17
+ /** The persona every cloud playtest includes; the customer adds others. */
18
+ export const ALWAYS_INCLUDED_PERSONA = 'fresh-eyes';
19
+
20
+ /** The most personas one cloud playtest may name, fresh-eyes included (the server's own limit). */
21
+ export const MAX_HOSTED_PERSONAS = 10;
22
+
23
+ /**
24
+ * The persona list a cloud playtest asks for: fresh-eyes first, then each
25
+ * persona named once, in the order given.
26
+ *
27
+ * @param {Array<string>|string} [extra]
28
+ * @returns {Array<string>}
29
+ */
30
+ export function hostedPersonas(extra = []) {
31
+ const named = (Array.isArray(extra) ? extra : String(extra || '').split(','))
32
+ .map(slug => String(slug).trim()).filter(Boolean);
33
+ return [...new Set([ALWAYS_INCLUDED_PERSONA, ...named])];
34
+ }
14
35
 
15
36
  /** The modules `run` registers. `aggregate_report` is free and buys the aggregate's steps. */
16
37
  export const RUN_MODULES = Object.freeze(['persona_playtest', 'aggregate_report']);