@replaystage/cli 2.1.1 → 2.1.2

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,10 +1,28 @@
1
1
  import { readFile, stat } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { DEFAULT_PORTAL_ORIGIN, findPlatformWorkspaceRoot, requireAuthToken, resolveApiBase, } from '../config.js';
3
+ import { DEFAULT_PORTAL_ORIGIN, findPlatformWorkspaceRoot, requireAuthToken, resolveApiBase, resolveAuthToken, } from '../config.js';
4
4
  import { apiRequestJson } from '../http.js';
5
5
  import { SLUG_RE, VALID_ADMIN_VISIBILITIES } from '../manifest.js';
6
6
  import { CliError, assertNoUnknownFlags, emitSuccess, extractBoolFlag, extractFlag, } from '../output.js';
7
7
  const DATE_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;
8
+ function parseStrictInt(raw, flagName, min, max) {
9
+ if (!/^-?\d+$/.test(raw.trim())) {
10
+ throw new CliError('INVALID_ARGUMENTS', `Invalid ${flagName} "${raw}". Expected an integer between ${min} and ${max}.`);
11
+ }
12
+ const n = Number(raw.trim());
13
+ if (!Number.isSafeInteger(n) || n < min || n > max) {
14
+ throw new CliError('INVALID_ARGUMENTS', `Invalid ${flagName} "${raw}". Expected an integer between ${min} and ${max}.`);
15
+ }
16
+ return n;
17
+ }
18
+ function parseStrictBool(raw, flagName) {
19
+ const lower = raw.trim().toLowerCase();
20
+ if (lower === 'true' || lower === '1')
21
+ return true;
22
+ if (lower === 'false' || lower === '0')
23
+ return false;
24
+ throw new CliError('INVALID_ARGUMENTS', `Invalid ${flagName} "${raw}". Expected true or false.`);
25
+ }
8
26
  async function exists(targetPath) {
9
27
  try {
10
28
  await stat(targetPath);
@@ -66,10 +84,12 @@ export async function cmdCatalog(args, opts) {
66
84
  }
67
85
  body.visibility = visFlag.value;
68
86
  }
69
- if (orderFlag.value !== undefined)
70
- body.featuredOrder = Number(orderFlag.value);
71
- if (dailyFlag.value !== undefined)
72
- body.dailyEligible = dailyFlag.value === 'true' || dailyFlag.value === '1';
87
+ if (orderFlag.value !== undefined) {
88
+ body.featuredOrder = parseStrictInt(orderFlag.value, '--order', 0, 100_000);
89
+ }
90
+ if (dailyFlag.value !== undefined) {
91
+ body.dailyEligible = parseStrictBool(dailyFlag.value, '--daily');
92
+ }
73
93
  if (noteFlag.value !== undefined)
74
94
  body.moderationNote = noteFlag.value;
75
95
  if (manifestFlag.value) {
@@ -117,7 +137,33 @@ export async function cmdDaily(args, opts) {
117
137
  if (sub === 'show' || !sub) {
118
138
  assertNoUnknownFlags(rest);
119
139
  const apiBase = await resolveApiBase(opts.apiBase);
120
- const data = await apiRequestJson({ apiBase, method: 'GET', path: '/v1/catalog' });
140
+ const token = await resolveAuthToken({
141
+ flagToken: opts.token,
142
+ allowAdminEnvFallback: true,
143
+ cwd: opts.cwd,
144
+ });
145
+ let data;
146
+ if (token) {
147
+ try {
148
+ data = await apiRequestJson({
149
+ apiBase,
150
+ method: 'GET',
151
+ path: '/v1/admin/daily',
152
+ token,
153
+ });
154
+ }
155
+ catch (err) {
156
+ if (err instanceof CliError && (err.status === 401 || err.status === 403)) {
157
+ data = await apiRequestJson({ apiBase, method: 'GET', path: '/v1/catalog' });
158
+ }
159
+ else {
160
+ throw err;
161
+ }
162
+ }
163
+ }
164
+ else {
165
+ data = await apiRequestJson({ apiBase, method: 'GET', path: '/v1/catalog' });
166
+ }
121
167
  emitSuccess(opts, data, () => [
122
168
  `ReplayStage Daily Stage Schedule (UTC today: ${data.utcDate})`,
123
169
  ...(data.upcoming ?? []).map(entry => {
@@ -199,10 +245,12 @@ export async function cmdAdmin(args, opts) {
199
245
  const daysFlag = extractFlag(rem, ['--days']);
200
246
  rem = daysFlag.rest;
201
247
  assertNoUnknownFlags(rem);
248
+ const maxUses = usesFlag.value !== undefined ? parseStrictInt(usesFlag.value, '--max-uses', 1, 1000) : 1;
249
+ const expiresInDays = daysFlag.value !== undefined ? parseStrictInt(daysFlag.value, '--days', 1, 365) : 30;
202
250
  const res = await adminApi(opts, 'POST', '/v1/admin/invites', {
203
251
  note: noteFlag.value || '',
204
- maxUses: usesFlag.value ? Number(usesFlag.value) : 1,
205
- expiresInDays: daysFlag.value ? Number(daysFlag.value) : 30,
252
+ maxUses,
253
+ expiresInDays,
206
254
  });
207
255
  emitSuccess(opts, res, () => [
208
256
  `Created invite code: ${res.invite.code} (id=${res.invite.id}, uses=${res.invite.maxUses})`,
@@ -391,7 +439,7 @@ export async function cmdAudit(args, opts) {
391
439
  if (liveFlag.present) {
392
440
  let liveGames = [];
393
441
  try {
394
- const catRes = await fetch(`${apiBase}/v1/catalog`);
442
+ const catRes = await fetch(`${apiBase}/v1/catalog`, { signal: AbortSignal.timeout(12_000) });
395
443
  if (catRes.ok) {
396
444
  const catData = (await catRes.json());
397
445
  liveGames = catData.games ?? [];
@@ -433,9 +481,15 @@ export async function cmdAudit(args, opts) {
433
481
  extra: unknownProbe.status === 404 ? '' : `expected HTTP 404, got ${unknownProbe.status}`,
434
482
  });
435
483
  }
436
- const failures = checks.filter(c => !c.ok).length + probes.filter(p => !p.ok).length;
484
+ const failedChecks = checks.filter(c => !c.ok);
485
+ const failedProbes = probes.filter(p => !p.ok);
486
+ const failures = failedChecks.length + failedProbes.length;
437
487
  if (failures > 0) {
438
- throw new CliError('AUDIT_FAILED', `ReplayStage audit failed with ${failures} issue(s).`, { details: { checks, probes, failures } });
488
+ const errors = [
489
+ ...failedChecks.map(c => `[${c.name}] ${c.detail}`),
490
+ ...failedProbes.map(p => `[${p.label}] ${p.url} -> HTTP ${p.status} (${p.ms}ms)${p.extra ? ` ${p.extra}` : ''}`),
491
+ ];
492
+ throw new CliError('AUDIT_FAILED', `ReplayStage audit failed with ${failures} issue(s).`, { details: { checks, probes, failures, errors } });
439
493
  }
440
494
  emitSuccess(opts, { checks, probes, failures: 0 }, () => [
441
495
  'ReplayStage Platform Audit',
@@ -114,6 +114,18 @@ export async function cmdPublish(args, opts) {
114
114
  manifestPath: manifestFlag.value,
115
115
  versionOverride: versionFlag.value,
116
116
  });
117
+ // 1b. Fail fast if a non-canonical local artwork reference (neither https:// nor /media/<slug>/) is missing on disk
118
+ for (const slot of ['icon', 'cover', 'poster']) {
119
+ const ref = report.manifest.artwork[slot];
120
+ if (!ref)
121
+ continue;
122
+ const isExternal = ref.startsWith('https://') || ref.startsWith('http://');
123
+ const isCanonical = ref.startsWith(`/media/${report.slug}/`);
124
+ const wasDiscovered = report.media.some(m => m.slot === slot);
125
+ if (!isExternal && !isCanonical && !wasDiscovered) {
126
+ throw new CliError('ARTWORK_MISSING', `Local artwork.${slot} ("${ref}") was not found on disk. Place the file in your repo or reference /media/${report.slug}/${slot}.png.`, { details: { slot, ref } });
127
+ }
128
+ }
117
129
  if (dryRunFlag.present) {
118
130
  emitSuccess(opts, {
119
131
  dryRun: true,
@@ -157,20 +169,45 @@ export async function cmdPublish(args, opts) {
157
169
  });
158
170
  const existsInAccount = (owned.games ?? []).some(g => g.slug === slug);
159
171
  if (!existsInAccount) {
160
- await apiRequestJson({
161
- apiBase,
162
- method: 'POST',
163
- path: '/v1/creator/games',
164
- token,
165
- body: {
166
- slug,
167
- titleEn: report.manifest.locales.en.title,
168
- titleZh: report.manifest.locales['zh-Hans'].title,
169
- genre: report.manifest.genre,
170
- accentColor: report.manifest.accentColor,
171
- },
172
- });
173
- createdSlot = true;
172
+ try {
173
+ await apiRequestJson({
174
+ apiBase,
175
+ method: 'POST',
176
+ path: '/v1/creator/games',
177
+ token,
178
+ body: {
179
+ slug,
180
+ titleEn: report.manifest.locales.en.title,
181
+ titleZh: report.manifest.locales['zh-Hans'].title,
182
+ genre: report.manifest.genre,
183
+ accentColor: report.manifest.accentColor,
184
+ },
185
+ });
186
+ createdSlot = true;
187
+ }
188
+ catch (err) {
189
+ // Admins may legitimately publish releases for games owned by another creator.
190
+ if (err instanceof CliError && err.status === 409) {
191
+ let existsInAdminCatalog = false;
192
+ try {
193
+ const allGames = await apiRequestJson({
194
+ apiBase,
195
+ method: 'GET',
196
+ path: '/v1/admin/games',
197
+ token,
198
+ });
199
+ existsInAdminCatalog = (allGames.games ?? []).some(g => g.slug === slug);
200
+ }
201
+ catch {
202
+ existsInAdminCatalog = false;
203
+ }
204
+ if (!existsInAdminCatalog)
205
+ throw err;
206
+ }
207
+ else {
208
+ throw err;
209
+ }
210
+ }
174
211
  }
175
212
  }
176
213
  // 3. Upload immutable bundle files concurrently
@@ -1,7 +1,7 @@
1
1
  import { cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { DEFAULT_PORTAL_ORIGIN, findPlatformWorkspaceRoot } from '../config.js';
4
- import { HEX_COLOR_RE, SLUG_RE, VALID_GENRES, buildStarterManifest, slugToTitle, writeStarterManifest, } from '../manifest.js';
4
+ import { HEX_COLOR_RE, RESERVED_GAME_SLUGS, SLUG_RE, VALID_GENRES, buildStarterManifest, slugToTitle, writeStarterManifest, } from '../manifest.js';
5
5
  import { CliError, assertNoUnknownFlags, emitSuccess, extractBoolFlag, extractFlag, } from '../output.js';
6
6
  async function exists(targetPath) {
7
7
  try {
@@ -12,6 +12,14 @@ async function exists(targetPath) {
12
12
  return false;
13
13
  }
14
14
  }
15
+ function escapeXml(value) {
16
+ return value
17
+ .replace(/&/g, '&amp;')
18
+ .replace(/</g, '&lt;')
19
+ .replace(/>/g, '&gt;')
20
+ .replace(/"/g, '&quot;')
21
+ .replace(/'/g, '&#39;');
22
+ }
15
23
  export function formatBytes(bytes) {
16
24
  if (bytes < 1024)
17
25
  return `${bytes} B`;
@@ -38,6 +46,9 @@ export async function cmdInit(args, opts) {
38
46
  if (!slug || !SLUG_RE.test(slug) || slug.length < 2 || slug.length > 40) {
39
47
  throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage init <slug> [--dir <path>] [--title "<English>"] [--zh "<中文>"] [--genre arcade|puzzle|mystery|strategy] [--accent "#0F62FE"] [--force]');
40
48
  }
49
+ if (RESERVED_GAME_SLUGS.has(slug)) {
50
+ throw new CliError('INVALID_ARGUMENTS', `Slug "${slug}" is reserved by ReplayStage. Choose a different slug.`);
51
+ }
41
52
  const genre = (genreFlag.value || 'arcade');
42
53
  if (!VALID_GENRES.includes(genre)) {
43
54
  throw new CliError('INVALID_ARGUMENTS', `Invalid --genre "${genre}". Expected one of: ${VALID_GENRES.join(', ')}`);
@@ -80,6 +91,9 @@ export async function cmdCreateGame(args, opts) {
80
91
  if (!slug || !SLUG_RE.test(slug) || slug.length < 2 || slug.length > 40) {
81
92
  throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage create-game <slug> [--dir <path>] [--title "<English>"] [--zh "<中文>"] [--genre arcade|puzzle|mystery|strategy]');
82
93
  }
94
+ if (RESERVED_GAME_SLUGS.has(slug)) {
95
+ throw new CliError('INVALID_ARGUMENTS', `Slug "${slug}" is reserved by ReplayStage. Choose a different slug.`);
96
+ }
83
97
  const titleEn = titleFlag.value?.trim() || slugToTitle(slug);
84
98
  const titleZh = zhFlag.value?.trim() || titleEn;
85
99
  const genre = (genreFlag.value || 'arcade');
@@ -108,7 +122,7 @@ export async function cmdCreateGame(args, opts) {
108
122
  await cp(templateDir, targetDir, { recursive: true });
109
123
  const replacements = [
110
124
  ['package.json', [['"name": "replaystage-starter-game"', `"name": "${slug}"`]]],
111
- ['index.html', [['<title>ReplayStage Starter Game</title>', `<title>${titleEn}</title>`]]],
125
+ ['index.html', [['<title>ReplayStage Starter Game</title>', `<title>${escapeXml(titleEn)}</title>`]]],
112
126
  ['.github/workflows/publish-replaystage.yml', [['slug: starter-game', `slug: ${slug}`]]],
113
127
  [
114
128
  'replaystage.manifest.json',
@@ -131,7 +145,7 @@ export async function cmdCreateGame(args, opts) {
131
145
  ["title: '节拍点按'", `title: ${JSON.stringify(titleZh)}`],
132
146
  ],
133
147
  ],
134
- ['public/cover.svg', [['PULSE TAP', titleEn.toUpperCase()]]],
148
+ ['public/cover.svg', [['PULSE TAP', escapeXml(titleEn.toUpperCase())]]],
135
149
  ];
136
150
  for (const [relFile, pairs] of replacements) {
137
151
  const full = path.join(targetDir, relFile);
@@ -139,7 +153,7 @@ export async function cmdCreateGame(args, opts) {
139
153
  continue;
140
154
  let content = await readFile(full, 'utf8');
141
155
  for (const [from, to] of pairs) {
142
- content = content.replace(from, to);
156
+ content = content.replace(from, () => to);
143
157
  }
144
158
  await writeFile(full, content, 'utf8');
145
159
  }
@@ -155,7 +169,7 @@ export async function cmdCreateGame(args, opts) {
155
169
  <head>
156
170
  <meta charset="utf-8" />
157
171
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
158
- <title>${titleEn}</title>
172
+ <title>${escapeXml(titleEn)}</title>
159
173
  <style>
160
174
  :root { color-scheme: light dark; --bg: #f4f7fb; --card: #ffffff; --ink: #0f172a; --muted: #475569; --accent: #0f62fe; --accent-ink: #ffffff; }
161
175
  :root[data-theme='dark'] { --bg: #0b111b; --card: #111a29; --ink: #f1f5f9; --muted: #94a3b8; --accent: #38bdf8; --accent-ink: #061826; }
@@ -171,7 +185,7 @@ export async function cmdCreateGame(args, opts) {
171
185
  </head>
172
186
  <body>
173
187
  <main>
174
- <h1 id="title">${titleEn}</h1>
188
+ <h1 id="title">${escapeXml(titleEn)}</h1>
175
189
  <p id="score">Score: 0</p>
176
190
  <div class="row">
177
191
  <button id="start" type="button">Start</button>
@@ -184,7 +198,7 @@ export async function cmdCreateGame(args, opts) {
184
198
  </main>
185
199
  <script type="module">
186
200
  import { initReplayStageGame } from 'https://replaystage.com/sdk/v1/replaystage.esm.js';
187
- const titleMap = { en: ${JSON.stringify(titleEn)}, 'zh-Hans': ${JSON.stringify(titleZh)} };
201
+ const titleMap = { en: ${JSON.stringify(titleEn).replace(/</g, '\\u003c')}, 'zh-Hans': ${JSON.stringify(titleZh).replace(/</g, '\\u003c')} };
188
202
  let score = 0;
189
203
  let playing = false;
190
204
 
@@ -266,7 +280,7 @@ jobs:
266
280
  manifest_path: replaystage.manifest.json
267
281
  dist_dir: dist
268
282
  build_command: "true"
269
- package_manager: npm
283
+ package_manager: none
270
284
  secrets:
271
285
  REPLAYSTAGE_PUBLISH_TOKEN: \${{ secrets.REPLAYSTAGE_PUBLISH_TOKEN }}
272
286
  `, 'utf8');
@@ -55,6 +55,11 @@ export async function cmdUpdate(args, opts) {
55
55
  nextManifest.artwork[slot] = canonicalUrl;
56
56
  mediaUploaded.push(canonicalUrl);
57
57
  }
58
+ else if (!rawRef.startsWith('https://') &&
59
+ !rawRef.startsWith('http://') &&
60
+ !rawRef.startsWith(`/media/${slug}/`)) {
61
+ throw new CliError('ARTWORK_MISSING', `Local artwork.${slot} ("${rawRef}") was not found on disk. Add the file or reference /media/${slug}/${slot}.png.`, { details: { slot, ref: rawRef } });
62
+ }
58
63
  }
59
64
  const res = await apiRequestJson({
60
65
  apiBase,
@@ -224,7 +229,14 @@ export async function cmdStats(args, opts) {
224
229
  if (!slug || !SLUG_RE.test(slug)) {
225
230
  throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage stats <slug> [--days 7] [--json]');
226
231
  }
227
- const days = Math.min(90, Math.max(1, Number(daysFlag.value || '7') || 7));
232
+ let days = 7;
233
+ if (daysFlag.value !== undefined) {
234
+ const parsedDays = Number(daysFlag.value);
235
+ if (!Number.isInteger(parsedDays) || parsedDays < 1 || parsedDays > 30) {
236
+ throw new CliError('INVALID_ARGUMENTS', 'Invalid --days value. Expected an integer between 1 and 30.');
237
+ }
238
+ days = parsedDays;
239
+ }
228
240
  const apiBase = await resolveApiBase(opts.apiBase);
229
241
  const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
230
242
  const data = await apiRequestJson({
package/dist/config.js CHANGED
@@ -1,4 +1,5 @@
1
- import { chmod, mkdir, readFile, stat, writeFile } from 'node:fs/promises';
1
+ import { chmod, mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
2
+ import { randomBytes } from 'node:crypto';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
4
5
  import { CliError } from './output.js';
@@ -24,14 +25,23 @@ export async function readStoredConfig() {
24
25
  }
25
26
  export async function writeStoredConfig(next) {
26
27
  const filePath = getConfigFilePath();
27
- await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
28
+ const dir = path.dirname(filePath);
29
+ await mkdir(dir, { recursive: true, mode: 0o700 });
28
30
  const payload = `${JSON.stringify({ ...next, updatedAt: new Date().toISOString() }, null, 2)}\n`;
29
- await writeFile(filePath, payload, { encoding: 'utf8', mode: 0o600 });
31
+ const tmpPath = path.join(dir, `.config.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
30
32
  try {
31
- await chmod(filePath, 0o600);
33
+ await writeFile(tmpPath, payload, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
34
+ try {
35
+ await chmod(tmpPath, 0o600);
36
+ }
37
+ catch {
38
+ // ignore chmod failures on filesystems that don't support POSIX modes
39
+ }
40
+ await rename(tmpPath, filePath);
32
41
  }
33
- catch {
34
- // ignore chmod failures on filesystems that don't support POSIX modes
42
+ catch (err) {
43
+ await unlink(tmpPath).catch(() => { });
44
+ throw err;
35
45
  }
36
46
  return filePath;
37
47
  }
@@ -100,13 +110,15 @@ export async function resolveAuthToken(options) {
100
110
  if (pubEnv)
101
111
  return pubEnv;
102
112
  }
103
- const stored = await readStoredConfig();
104
- if (stored.token?.trim())
105
- return stored.token.trim();
106
113
  if (options.allowAdminEnvFallback) {
107
114
  const adminEnv = process.env.REPLAYSTAGE_ADMIN_TOKEN?.trim();
108
115
  if (adminEnv)
109
116
  return adminEnv;
117
+ }
118
+ const stored = await readStoredConfig();
119
+ if (stored.token?.trim())
120
+ return stored.token.trim();
121
+ if (options.allowAdminEnvFallback) {
110
122
  const fromDotEnv = await readLocalAdminEnvToken(options.cwd);
111
123
  if (fromDotEnv)
112
124
  return fromDotEnv;
package/dist/http.js CHANGED
@@ -33,24 +33,31 @@ export async function apiRequestJson(opts) {
33
33
  const maxRetries = opts.retries ?? (opts.method === 'POST' ? 0 : 2);
34
34
  for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
35
35
  let res;
36
+ let text = '';
37
+ let shouldRetryStatus = false;
38
+ let retryMs = 350 * 2 ** attempt;
39
+ const controller = new AbortController();
40
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
36
41
  try {
37
- const controller = new AbortController();
38
- const timer = setTimeout(() => controller.abort(), timeoutMs);
39
- try {
40
- res = await fetch(url, {
41
- method: opts.method,
42
- headers,
43
- body: requestBody,
44
- signal: controller.signal,
45
- });
42
+ res = await fetch(url, {
43
+ method: opts.method,
44
+ headers,
45
+ body: requestBody,
46
+ signal: controller.signal,
47
+ });
48
+ if (!res.ok && RETRYABLE_STATUSES.has(res.status) && attempt < maxRetries) {
49
+ shouldRetryStatus = true;
50
+ retryMs = parseRetryAfterMs(res.headers.get('retry-after')) ?? retryMs;
51
+ await res.body?.cancel().catch(() => { });
46
52
  }
47
- finally {
48
- clearTimeout(timer);
53
+ else {
54
+ text = await res.text();
49
55
  }
50
56
  }
51
57
  catch (err) {
52
58
  const isTimeout = err instanceof Error && err.name === 'AbortError';
53
59
  if (attempt < maxRetries) {
60
+ clearTimeout(timer);
54
61
  await delay(350 * 2 ** attempt);
55
62
  continue;
56
63
  }
@@ -58,12 +65,13 @@ export async function apiRequestJson(opts) {
58
65
  ? `Request timed out after ${timeoutMs}ms: ${opts.method} ${url}`
59
66
  : `Failed to reach ${url}: ${err instanceof Error ? err.message : String(err)}`);
60
67
  }
61
- if (!res.ok && RETRYABLE_STATUSES.has(res.status) && attempt < maxRetries) {
62
- const retryMs = parseRetryAfterMs(res.headers.get('retry-after')) ?? 350 * 2 ** attempt;
68
+ finally {
69
+ clearTimeout(timer);
70
+ }
71
+ if (shouldRetryStatus) {
63
72
  await delay(retryMs);
64
73
  continue;
65
74
  }
66
- const text = await res.text();
67
75
  let parsed = {};
68
76
  if (text) {
69
77
  try {
@@ -90,7 +98,19 @@ export async function apiRequestJson(opts) {
90
98
  method: opts.method,
91
99
  path: opts.path,
92
100
  };
93
- if (Array.isArray(parsed.details)) {
101
+ if (Array.isArray(parsed.issues)) {
102
+ details.issues = parsed.issues;
103
+ details.errors = parsed.issues.map(item => {
104
+ if (item && typeof item === 'object') {
105
+ const rec = item;
106
+ if (typeof rec.field === 'string' && typeof rec.message === 'string') {
107
+ return `${rec.field}: ${rec.message}`;
108
+ }
109
+ }
110
+ return String(item);
111
+ });
112
+ }
113
+ else if (Array.isArray(parsed.details)) {
94
114
  details.errors = parsed.details;
95
115
  }
96
116
  else if (parsed.details && typeof parsed.details === 'object') {
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { cmdCreateGame, cmdDelete, cmdGames, cmdInit, cmdPublish, cmdReleases, c
5
5
  import { CliError, DEFAULT_STREAMS, emitError, emitSuccess, extractBoolFlag, extractFlag, } from './output.js';
6
6
  const require = createRequire(import.meta.url);
7
7
  const pkgJson = require('../package.json');
8
- export const CLI_VERSION = pkgJson.version ?? '2.1.1';
8
+ export const CLI_VERSION = pkgJson.version ?? '2.1.2';
9
9
  export { CliError } from './output.js';
10
10
  export { validateManifestObject, buildStarterManifest } from './manifest.js';
11
11
  export { validateProjectBundle } from './validate.js';
@@ -64,14 +64,12 @@ export async function runCli(rawArgs, runtime = {}) {
64
64
  const tokenParsed = extractFlag(rest, ['--token', '-t', '--auth-token']);
65
65
  opts.token = tokenParsed.value;
66
66
  rest = tokenParsed.rest;
67
- const versionFlag = extractBoolFlag(rest, ['-v', '--version']);
68
- rest = versionFlag.rest;
69
- const helpFlag = extractBoolFlag(rest, ['-h', '--help']);
70
- rest = helpFlag.rest;
71
- if (versionFlag.present && rest.length === 0) {
67
+ if (rest.length === 1 && (rest[0] === '-v' || rest[0] === '--version')) {
72
68
  emitSuccess(opts, { version: CLI_VERSION }, () => [`replaystage v${CLI_VERSION}`]);
73
69
  return 0;
74
70
  }
71
+ const helpFlag = extractBoolFlag(rest, ['-h', '--help']);
72
+ rest = helpFlag.rest;
75
73
  const [command, ...cmdArgs] = rest;
76
74
  if (!command || helpFlag.present) {
77
75
  emitSuccess(opts, {
@@ -57,12 +57,16 @@ export interface ReplayStageManifest {
57
57
  };
58
58
  }
59
59
  export declare const SLUG_RE: RegExp;
60
+ export declare const VERSION_RE: RegExp;
61
+ export declare const ENTRY_PATH_RE: RegExp;
60
62
  export declare const HEX_COLOR_RE: RegExp;
61
63
  export declare const ASPECT_RATIO_RE: RegExp;
64
+ export declare const RESERVED_GAME_SLUGS: Set<string>;
62
65
  export declare const VALID_GENRES: readonly GameGenre[];
63
66
  export declare const VALID_CREATOR_VISIBILITIES: readonly ["live", "beta", "unlisted", "hidden"];
64
67
  export declare const VALID_ADMIN_VISIBILITIES: readonly GameVisibility[];
65
68
  export declare function slugToTitle(slug: string): string;
69
+ export declare function isSafeEntryPath(val: unknown): val is string;
66
70
  export declare function validateManifestObject(raw: unknown): {
67
71
  valid: boolean;
68
72
  errors: string[];
package/dist/manifest.js CHANGED
@@ -2,9 +2,49 @@ import { readFile, stat, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { CliError } from './output.js';
4
4
  export const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5
+ export const VERSION_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,47}$/;
6
+ export const ENTRY_PATH_RE = /^\/(?:[a-zA-Z0-9._-]+\/)*[a-zA-Z0-9._-]+$/;
5
7
  export const HEX_COLOR_RE = /^#[0-9a-fA-F]{6}$/;
6
8
  export const ASPECT_RATIO_RE = /^\d+:\d+$/;
9
+ export const RESERVED_GAME_SLUGS = new Set([
10
+ 'admin',
11
+ 'api',
12
+ 'assets',
13
+ 'auth',
14
+ 'c',
15
+ 'catalog',
16
+ 'constructor',
17
+ 'creator',
18
+ 'creators',
19
+ 'daily',
20
+ 'emulator',
21
+ 'favicon',
22
+ 'health',
23
+ 'icons',
24
+ 'login',
25
+ 'manifest',
26
+ 'media',
27
+ 'og',
28
+ 'platform',
29
+ 'play',
30
+ 'privacy',
31
+ 'prototype',
32
+ 'register',
33
+ 'replaystage',
34
+ 'robots',
35
+ 'schemas',
36
+ 'sdk',
37
+ 'sitemap',
38
+ 'skill',
39
+ 'stats',
40
+ 'studio',
41
+ 'support',
42
+ 'sw',
43
+ 'system',
44
+ 'www',
45
+ ]);
7
46
  export const VALID_GENRES = ['arcade', 'puzzle', 'mystery', 'strategy'];
47
+ const VALID_LOCALES = ['en', 'zh-Hans'];
8
48
  export const VALID_CREATOR_VISIBILITIES = ['live', 'beta', 'unlisted', 'hidden'];
9
49
  export const VALID_ADMIN_VISIBILITIES = [
10
50
  'featured',
@@ -21,11 +61,30 @@ export function slugToTitle(slug) {
21
61
  .map(part => (part[0] ? part[0].toUpperCase() + part.slice(1) : part))
22
62
  .join(' ');
23
63
  }
24
- function isNonEmptyString(val) {
25
- return typeof val === 'string' && val.trim().length > 0;
64
+ function isNonEmptyString(val, maxLen = 600) {
65
+ return typeof val === 'string' && val.trim().length > 0 && val.length <= maxLen;
26
66
  }
27
- function isSafeHttpUrl(val) {
28
- if (val.length === 0 || val.length > 300)
67
+ export function isSafeEntryPath(val) {
68
+ if (typeof val !== 'string')
69
+ return false;
70
+ if (val.length < 2 || val.length > 256)
71
+ return false;
72
+ if (!val.startsWith('/') || val.startsWith('//'))
73
+ return false;
74
+ if (val.includes('..') || val.includes('\\'))
75
+ return false;
76
+ return ENTRY_PATH_RE.test(val);
77
+ }
78
+ function isSafeAspectRatio(val) {
79
+ if (typeof val !== 'string' || val.length > 9 || !ASPECT_RATIO_RE.test(val))
80
+ return false;
81
+ const [rawW, rawH] = val.split(':');
82
+ const w = Number(rawW);
83
+ const h = Number(rawH);
84
+ return Number.isInteger(w) && Number.isInteger(h) && w >= 1 && w <= 100 && h >= 1 && h <= 100;
85
+ }
86
+ function isSafeHttpUrl(val, maxLen = 300) {
87
+ if (val.length === 0 || val.length > maxLen)
29
88
  return false;
30
89
  try {
31
90
  const u = new URL(val);
@@ -36,13 +95,13 @@ function isSafeHttpUrl(val) {
36
95
  }
37
96
  }
38
97
  function isSafeArtworkRef(val) {
39
- if (!isNonEmptyString(val) || val.length > 256)
98
+ if (!isNonEmptyString(val, 256))
40
99
  return false;
41
100
  const trimmed = val.trim();
42
101
  if (/[\u0000-\u001f\u007f]/.test(trimmed))
43
102
  return false;
44
103
  if (trimmed.startsWith('https://'))
45
- return isSafeHttpUrl(trimmed);
104
+ return isSafeHttpUrl(trimmed, 256);
46
105
  if (trimmed.startsWith('//') || trimmed.includes('..') || trimmed.includes('\\'))
47
106
  return false;
48
107
  if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed))
@@ -55,11 +114,17 @@ export function validateManifestObject(raw) {
55
114
  return { valid: false, errors: ['Manifest must be a JSON object'] };
56
115
  }
57
116
  const m = raw;
58
- if (!isNonEmptyString(m.slug) || !SLUG_RE.test(m.slug) || m.slug.length < 2 || m.slug.length > 40) {
117
+ if (m.schemaVersion !== 1) {
118
+ errors.push('schemaVersion must be 1');
119
+ }
120
+ if (!isNonEmptyString(m.slug, 40) || !SLUG_RE.test(m.slug) || m.slug.length < 2 || m.slug.length > 40) {
59
121
  errors.push('slug must be 2-40 chars lowercase kebab-case (e.g. "neon-stack")');
60
122
  }
61
- if (!isNonEmptyString(m.version) || m.version.length > 64) {
62
- errors.push('version must be a non-empty string (e.g. "1.0.0")');
123
+ else if (RESERVED_GAME_SLUGS.has(m.slug)) {
124
+ errors.push(`slug "${m.slug}" is reserved`);
125
+ }
126
+ if (!isNonEmptyString(m.version, 48) || !VERSION_RE.test(m.version)) {
127
+ errors.push('version must match /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,47}$/ (e.g. "1.0.0")');
63
128
  }
64
129
  if (m.tier !== 0 && m.tier !== 1 && m.tier !== 2) {
65
130
  errors.push('tier must be 0, 1, or 2');
@@ -70,49 +135,80 @@ export function validateManifestObject(raw) {
70
135
  if (!isNonEmptyString(m.accentColor) || !HEX_COLOR_RE.test(m.accentColor)) {
71
136
  errors.push('accentColor must be a 6-digit hex color (e.g. "#0F62FE")');
72
137
  }
73
- if (!isNonEmptyString(m.aspectRatio) || !ASPECT_RATIO_RE.test(m.aspectRatio)) {
74
- errors.push('aspectRatio must match "<w>:<h>" (e.g. "9:16")');
138
+ if (!isSafeAspectRatio(m.aspectRatio)) {
139
+ errors.push('aspectRatio must match "<w>:<h>" with 1..100 integers (e.g. "9:16")');
75
140
  }
76
- if (!isNonEmptyString(m.sessionMinutes)) {
77
- errors.push('sessionMinutes must be a non-empty string (e.g. "1–3 min")');
141
+ if (!isNonEmptyString(m.sessionMinutes, 40)) {
142
+ errors.push('sessionMinutes must be a non-empty string <= 40 chars (e.g. "1–3 min")');
78
143
  }
79
- if (!isNonEmptyString(m.ageRating)) {
80
- errors.push('ageRating must be a non-empty string (e.g. "6+")');
144
+ if (!isNonEmptyString(m.ageRating, 16)) {
145
+ errors.push('ageRating must be a non-empty string <= 16 chars (e.g. "6+")');
146
+ }
147
+ if (m.gameLanguages !== undefined) {
148
+ if (!Array.isArray(m.gameLanguages) ||
149
+ m.gameLanguages.length === 0 ||
150
+ m.gameLanguages.length > 2 ||
151
+ !m.gameLanguages.every(item => VALID_LOCALES.includes(item))) {
152
+ errors.push('gameLanguages must be an array of 1..2 supported locales ("en", "zh-Hans")');
153
+ }
81
154
  }
82
155
  const locales = m.locales;
83
156
  for (const loc of ['en', 'zh-Hans']) {
84
157
  const copy = locales?.[loc];
85
- if (!copy || typeof copy !== 'object') {
158
+ if (!copy || typeof copy !== 'object' || Array.isArray(copy)) {
86
159
  errors.push(`locales.${loc} is required`);
87
160
  continue;
88
161
  }
89
- if (!isNonEmptyString(copy.title))
90
- errors.push(`locales.${loc}.title is required`);
91
- if (!isNonEmptyString(copy.tagline))
92
- errors.push(`locales.${loc}.tagline is required`);
93
- if (!isNonEmptyString(copy.description))
94
- errors.push(`locales.${loc}.description is required`);
95
- if (!Array.isArray(copy.howToPlay) || copy.howToPlay.length === 0 || !copy.howToPlay.every(isNonEmptyString)) {
96
- errors.push(`locales.${loc}.howToPlay must be a non-empty string array`);
162
+ if (!isNonEmptyString(copy.title, 80))
163
+ errors.push(`locales.${loc}.title is required (<= 80 chars)`);
164
+ if (!isNonEmptyString(copy.tagline, 160))
165
+ errors.push(`locales.${loc}.tagline is required (<= 160 chars)`);
166
+ if (!isNonEmptyString(copy.description, 600))
167
+ errors.push(`locales.${loc}.description is required (<= 600 chars)`);
168
+ if (!Array.isArray(copy.howToPlay) ||
169
+ copy.howToPlay.length === 0 ||
170
+ copy.howToPlay.length > 6 ||
171
+ !copy.howToPlay.every(item => isNonEmptyString(item, 240))) {
172
+ errors.push(`locales.${loc}.howToPlay must be an array of 1..6 non-empty strings (<= 240 chars)`);
97
173
  }
98
- if (!Array.isArray(copy.tags) || !copy.tags.every(isNonEmptyString)) {
99
- errors.push(`locales.${loc}.tags must be an array of strings`);
174
+ if (copy.tags !== undefined) {
175
+ if (!Array.isArray(copy.tags) ||
176
+ copy.tags.length > 8 ||
177
+ !copy.tags.every(item => isNonEmptyString(item, 32))) {
178
+ errors.push(`locales.${loc}.tags must be an array of <= 8 strings (<= 32 chars)`);
179
+ }
100
180
  }
101
181
  }
102
182
  const runtime = m.runtime;
103
- if (!runtime || typeof runtime !== 'object') {
183
+ if (!runtime || typeof runtime !== 'object' || Array.isArray(runtime)) {
104
184
  errors.push('runtime is required');
105
185
  }
106
186
  else {
107
- if (!isNonEmptyString(runtime.originSlug) || !SLUG_RE.test(runtime.originSlug)) {
108
- errors.push('runtime.originSlug must be lowercase kebab-case');
187
+ if (runtime.originSlug !== undefined) {
188
+ if (!isNonEmptyString(runtime.originSlug, 40) ||
189
+ !SLUG_RE.test(runtime.originSlug) ||
190
+ runtime.originSlug.length < 2 ||
191
+ runtime.originSlug.length > 40) {
192
+ errors.push('runtime.originSlug must be 2-40 chars lowercase kebab-case');
193
+ }
194
+ else if (RESERVED_GAME_SLUGS.has(runtime.originSlug)) {
195
+ errors.push(`runtime.originSlug "${runtime.originSlug}" is reserved`);
196
+ }
109
197
  }
110
- if (!isNonEmptyString(runtime.entryPath) || !runtime.entryPath.startsWith('/')) {
111
- errors.push('runtime.entryPath must start with "/" (e.g. "/index.html")');
198
+ if (!isSafeEntryPath(runtime.entryPath)) {
199
+ errors.push('runtime.entryPath must be a clean relative path starting with "/" (e.g. "/index.html")');
200
+ }
201
+ if (runtime.productionOrigin !== undefined &&
202
+ (typeof runtime.productionOrigin !== 'string' || !isSafeHttpUrl(runtime.productionOrigin))) {
203
+ errors.push('runtime.productionOrigin must be a valid http(s) URL');
204
+ }
205
+ if (runtime.challengeOrigin !== undefined &&
206
+ (typeof runtime.challengeOrigin !== 'string' || !isSafeHttpUrl(runtime.challengeOrigin))) {
207
+ errors.push('runtime.challengeOrigin must be a valid http(s) URL');
112
208
  }
113
209
  }
114
210
  const artwork = m.artwork;
115
- if (!artwork || typeof artwork !== 'object') {
211
+ if (!artwork || typeof artwork !== 'object' || Array.isArray(artwork)) {
116
212
  errors.push('artwork is required');
117
213
  }
118
214
  else {
@@ -125,10 +221,13 @@ export function validateManifestObject(raw) {
125
221
  }
126
222
  }
127
223
  const platforms = m.platforms;
128
- if (!platforms || typeof platforms.web !== 'boolean') {
129
- errors.push('platforms.web must be a boolean');
224
+ if (!platforms || typeof platforms !== 'object' || Array.isArray(platforms)) {
225
+ errors.push('platforms must be an object');
130
226
  }
131
227
  else {
228
+ if (platforms.web !== undefined && typeof platforms.web !== 'boolean') {
229
+ errors.push('platforms.web must be a boolean');
230
+ }
132
231
  for (const key of ['ios', 'android']) {
133
232
  const store = platforms[key];
134
233
  if (store && typeof store === 'object' && !Array.isArray(store)) {
@@ -144,7 +243,20 @@ export function validateManifestObject(raw) {
144
243
  if (errors.length > 0) {
145
244
  return { valid: false, errors };
146
245
  }
147
- return { valid: true, errors: [], manifest: raw };
246
+ const normalized = {
247
+ ...raw,
248
+ runtime: {
249
+ ...runtime,
250
+ originSlug: typeof runtime?.originSlug === 'string' && runtime.originSlug
251
+ ? runtime.originSlug
252
+ : m.slug,
253
+ },
254
+ platforms: {
255
+ ...platforms,
256
+ web: typeof platforms?.web === 'boolean' ? platforms.web : true,
257
+ },
258
+ };
259
+ return { valid: true, errors: [], manifest: normalized };
148
260
  }
149
261
  export async function loadAndValidateManifest(manifestPath) {
150
262
  const resolved = path.resolve(manifestPath);
package/dist/validate.js CHANGED
@@ -1,11 +1,12 @@
1
- import { readFile, readdir, stat } from 'node:fs/promises';
1
+ import { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { loadAndValidateManifest } from './manifest.js';
3
+ import { VERSION_RE, loadAndValidateManifest } from './manifest.js';
4
4
  import { CliError } from './output.js';
5
5
  export const MAX_FILE_BYTES = 25 * 1024 * 1024; // 25 MB
6
6
  export const MAX_TOTAL_BYTES = 50 * 1024 * 1024; // 50 MB
7
7
  export const MAX_FILE_COUNT = 1000;
8
8
  export const MAX_MEDIA_BYTES = 2 * 1024 * 1024; // 2 MB
9
+ const MEDIA_FILENAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}\.(?:png|jpg|jpeg|webp|svg)$/;
9
10
  const AUTO_SKIP_DIRS = new Set(['.git', 'node_modules', '__MACOSX']);
10
11
  const AUTO_SKIP_FILES = new Set(['.DS_Store', 'Thumbs.db']);
11
12
  const PROHIBITED_EXTENSIONS = new Set(['.exe', '.dll', '.sh', '.bat', '.cmd', '.msi', '.com', '.scr']);
@@ -47,64 +48,109 @@ export function guessContentType(filePath) {
47
48
  function isEnvFile(name) {
48
49
  return name === '.env' || name.startsWith('.env.');
49
50
  }
50
- async function fileExists(target) {
51
+ function isPathWithinRoot(targetReal, rootReal) {
52
+ return targetReal === rootReal || targetReal.startsWith(`${rootReal}${path.sep}`);
53
+ }
54
+ async function resolveSafeRegularFile(candidate, allowedRealRoots) {
51
55
  try {
52
- const info = await stat(target);
53
- return info.isFile();
56
+ const linkInfo = await lstat(candidate);
57
+ if (linkInfo.isSymbolicLink()) {
58
+ throw new CliError('SYMLINK_NOT_ALLOWED', `Symlink artwork path is not permitted: ${candidate}`, { details: { path: candidate } });
59
+ }
60
+ if (!linkInfo.isFile())
61
+ return null;
62
+ const realTarget = await realpath(candidate);
63
+ const contained = allowedRealRoots.some(root => isPathWithinRoot(realTarget, root));
64
+ if (!contained) {
65
+ throw new CliError('PATH_ESCAPE_BLOCKED', `Artwork file escapes repository boundary: ${candidate}`, { details: { path: candidate } });
66
+ }
67
+ return { absPath: realTarget, size: linkInfo.size };
54
68
  }
55
- catch {
56
- return false;
69
+ catch (err) {
70
+ if (err instanceof CliError)
71
+ throw err;
72
+ return null;
57
73
  }
58
74
  }
59
75
  export async function discoverMediaFile(slot, artworkUrl, slug, repoDir, distDir) {
60
76
  // Expected format: `/media/<slug>/<filename>` or local repo-relative path (e.g. `public/icon.svg`)
61
77
  const expectedPrefix = `/media/${slug}/`;
62
- let filename = '';
78
+ const isCanonicalMedia = artworkUrl.startsWith(expectedPrefix);
79
+ let baseFilename = '';
63
80
  const directCandidates = [];
64
- if (artworkUrl.startsWith(expectedPrefix)) {
65
- filename = artworkUrl.slice(expectedPrefix.length);
81
+ if (isCanonicalMedia) {
82
+ baseFilename = artworkUrl.slice(expectedPrefix.length);
66
83
  }
67
84
  else if (artworkUrl.startsWith('/')) {
68
- filename = path.basename(artworkUrl);
85
+ const cleanRel = artworkUrl.replace(/^\/+/, '');
86
+ if (cleanRel && !cleanRel.includes('..') && !cleanRel.includes('\\')) {
87
+ directCandidates.push(path.join(repoDir, cleanRel));
88
+ if (distDir)
89
+ directCandidates.push(path.join(distDir, cleanRel));
90
+ }
91
+ baseFilename = path.basename(cleanRel);
69
92
  }
70
93
  else if (!artworkUrl.startsWith('http://') && !artworkUrl.startsWith('https://')) {
71
94
  const cleanRel = artworkUrl.replace(/^\.\/+/, '');
72
- if (!cleanRel.includes('..')) {
95
+ if (cleanRel && !cleanRel.includes('..') && !cleanRel.includes('\\')) {
73
96
  directCandidates.push(path.join(repoDir, cleanRel));
74
97
  if (distDir)
75
98
  directCandidates.push(path.join(distDir, cleanRel));
76
99
  }
77
- filename = path.basename(cleanRel);
100
+ baseFilename = path.basename(cleanRel);
78
101
  }
79
102
  else {
80
103
  return null;
81
104
  }
82
- if (!filename || filename.includes('..') || filename.includes('/')) {
105
+ if (!baseFilename || baseFilename.includes('..') || baseFilename.includes('/') || baseFilename.includes('\\')) {
83
106
  return null;
84
107
  }
108
+ const allowedRealRoots = [];
109
+ try {
110
+ allowedRealRoots.push(await realpath(repoDir));
111
+ }
112
+ catch {
113
+ allowedRealRoots.push(path.resolve(repoDir));
114
+ }
115
+ if (distDir) {
116
+ try {
117
+ allowedRealRoots.push(await realpath(distDir));
118
+ }
119
+ catch {
120
+ allowedRealRoots.push(path.resolve(distDir));
121
+ }
122
+ }
85
123
  const candidates = [
86
124
  ...directCandidates,
87
- path.join(repoDir, 'public', 'media', slug, filename),
88
- path.join(repoDir, 'media', slug, filename),
89
- path.join(repoDir, 'media', filename),
90
- path.join(repoDir, 'public', filename),
91
- path.join(repoDir, filename),
125
+ path.join(repoDir, 'public', 'media', slug, baseFilename),
126
+ path.join(repoDir, 'media', slug, baseFilename),
127
+ path.join(repoDir, 'media', baseFilename),
128
+ path.join(repoDir, 'public', baseFilename),
129
+ path.join(repoDir, baseFilename),
92
130
  ...(distDir
93
- ? [path.join(distDir, 'media', slug, filename), path.join(distDir, filename)]
131
+ ? [path.join(distDir, 'media', slug, baseFilename), path.join(distDir, baseFilename)]
94
132
  : []),
95
133
  ];
96
134
  for (const candidate of candidates) {
97
- if (await fileExists(candidate)) {
98
- const info = await stat(candidate);
99
- if (info.size > MAX_MEDIA_BYTES) {
100
- throw new CliError('MEDIA_TOO_LARGE', `Artwork file "${filename}" (${info.size} bytes) exceeds the 2 MB media limit.`, { details: { slot, filename, bytes: info.size, maxBytes: MAX_MEDIA_BYTES } });
135
+ const safeFile = await resolveSafeRegularFile(candidate, allowedRealRoots);
136
+ if (safeFile) {
137
+ const ext = path.extname(safeFile.absPath).toLowerCase();
138
+ const normalizedFilename = isCanonicalMedia ? baseFilename : `${slot}${ext}`;
139
+ if (normalizedFilename.includes('..') || !MEDIA_FILENAME_RE.test(normalizedFilename)) {
140
+ throw new CliError('INVALID_MEDIA_FILENAME', `Unsupported artwork filename "${normalizedFilename}". Use .png, .jpg, .jpeg, .webp, or .svg.`, { details: { slot, filename: normalizedFilename } });
141
+ }
142
+ if (safeFile.size === 0) {
143
+ throw new CliError('EMPTY_MEDIA_FILE', `Artwork file "${normalizedFilename}" is empty (0 bytes).`, { details: { slot, filename: normalizedFilename } });
144
+ }
145
+ if (safeFile.size > MAX_MEDIA_BYTES) {
146
+ throw new CliError('MEDIA_TOO_LARGE', `Artwork file "${normalizedFilename}" (${safeFile.size} bytes) exceeds the 2 MB media limit.`, { details: { slot, filename: normalizedFilename, bytes: safeFile.size, maxBytes: MAX_MEDIA_BYTES } });
101
147
  }
102
148
  return {
103
149
  slot,
104
- filename,
105
- absPath: candidate,
106
- bytes: info.size,
107
- contentType: guessContentType(candidate),
150
+ filename: normalizedFilename,
151
+ absPath: safeFile.absPath,
152
+ bytes: safeFile.size,
153
+ contentType: guessContentType(safeFile.absPath),
108
154
  };
109
155
  }
110
156
  }
@@ -222,7 +268,11 @@ export async function validateProjectBundle(options) {
222
268
  media.push(posterMedia);
223
269
  }
224
270
  }
225
- const version = options.versionOverride?.trim() || manifest.version;
271
+ const versionOverride = options.versionOverride?.trim();
272
+ if (versionOverride && !VERSION_RE.test(versionOverride)) {
273
+ throw new CliError('INVALID_VERSION', `Invalid --version override "${versionOverride}". Must match /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,47}$/.`, { details: { version: versionOverride } });
274
+ }
275
+ const version = versionOverride || manifest.version;
226
276
  return {
227
277
  slug: manifest.slug,
228
278
  version,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@replaystage/cli",
3
- "version": "2.1.1",
3
+ "version": "2.1.2",
4
4
  "description": "Unified agent-native CLI for building, validating, previewing, publishing, and operating ReplayStage portrait games.",
5
5
  "type": "module",
6
6
  "license": "MIT",