mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-06 23:07:33 +08:00
* feat(game-static-play): add 274-template R2 zip packaging, cookieless static play deploy, and verification pipeline * feat(game-skill): port 21-section OpenGame skill with dual-mode workflow and fast-play path * feat(onboarding): upgrade Cloud MCP install guide and add shared OpenGame prompt builders * feat(game-catalog): sync 274 official templates, 4 kits, downloads manifest, and game contract * feat(cloud-mcp): add read-only game catalog, free asset search, guest catalog API, redirects, and Docker packaging * feat(opengame): enable Stage 1 Game Studio routing, feature flags, and analytics * feat(opengame): add Stage 1 market, multi-client modal, Cursor HTTP fix, SuperAgent prompt, and i18n * fix(opengame): align nullable GameCardWithMeta fields and add opengame-catalog MCP capability * test(mcp-onboarding): update registered public tool count from 22 to 24 for Stage 1 game tools * chore(game-catalog): register 26 verified live R2 in-repo template bundles in game-downloads.json * fix(opengame): address Stage 1 review feedback and failing CI lanes - Send no play URL when GAME_PLAY_PUBLIC_ORIGIN is unset instead of a main-site path that no route serves; Studio falls back to bundled in-repo templates - Keep legacy-host 301 redirects on the configured origin for network-path inputs - Correct the BlenderKit page host in the asset search allowlist - Reuse the shared withdrawn list, TOP earning tag, curated order and comparator in Studio - Remove the unused shared prompt module; the shipped builders stay covered by Studio tests - Drop the blurred launch backdrop and the in-dialog copy notices in favour of Toasts - Describe the shipped read-only Game Studio boundary and 24-tool MCP contract in the architecture - Schedule the game skill and static play suites in CI and budget the three OpenGame events * fix(game-static-play): retry stalled template bundle downloads before failing the run * fix(game-asset-search): size the pagination cursor limit for every supported query A 200-unit query with non-ASCII, control or lone-surrogate characters produced a cursor longer than the 512-character limit, so nextCursor was rejected by both the decoder and the public schema. Share one limit derived from the worst-case JSON/base64url expansion and add a round-trip test for maximum-length queries. * fix(game-asset-search): accept BlenderKit pages on www.blendkit.com and guide licence checks www.blenderkit.com now redirects to www.blendkit.com and the upstream catalog returns that host, so requiring www.blenderkit.com dropped every BlenderKit result. Restore the live host, pin a real upstream row in tests, and tell Agents to confirm the licence on the source page when a source omits it. * fix(deploy): forward game play origin and legacy redirect hosts to the API deploy/.env.example and deploy/k8s/configmap.yaml declared GAME_PLAY_PUBLIC_ORIGIN and APP_REDIRECT_FROM_HOSTS, but neither the compose api service nor the reference api Deployment passed them to the process. Wire both and assert that every reference ConfigMap key is read by a workload. * Address review: keep legacy-host writes, enforce play-origin isolation, share catalog constants - Legacy-host redirects answer GET/HEAD with 301 and every other method with 308, so MCP and API writes keep their method and body. - parseConfig rejects a GAME_PLAY_PUBLIC_ORIGIN that is not https (loopback http excepted), carries a path, or shares or sits under the APP_PUBLIC_ORIGIN host. - The template id pattern, bundle key prefix, withdrawn set and TOP tag predicate live in shared/game-contract.ts; static play, deploy/verify scripts and the catalog service reuse them and the shared bundle URL builder. - Remove unused game-contract and model-catalog exports. - Update the MCP contract, AGENTS.md, README and docs to the 24-name phase-one surface and document the read-only OpenGame tools and guest catalog routes. * fix(game-static-play): make the full play-site upload resumable Upload through the S3 SDK instead of one aws CLI process per file, skip objects whose ETag already matches the local MD5, retry each request with backoff, and write assets before entry pages and the manifest. Give large bundle downloads time for a slow link. Record the provisioned bucket, domain and remaining header rule in the runbook. * feat(game-static-play): harden live play verification and add manual R2 publish workflow * fix(opengame): raise prompt/remix maxLength for >4k OG-13 test and reset notes on target change * fix(mcp): register resources/templates/list handler for Codex MCP compliance * chore(game-catalog): register uploaded tidebreaker bundle for 274/274 R2 CDN parity --------- Co-authored-by: heggria <bshengtao@gmail.com>
606 lines
24 KiB
TypeScript
606 lines
24 KiB
TypeScript
import assert from 'node:assert/strict';
|
|
import { access, lstat, readdir, readFile } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
import { isMain } from '../shared/entry.ts';
|
|
import {
|
|
assertDistinctCookielessPlayOrigin,
|
|
auditStaticGameFiles,
|
|
buildGameBundleUrl,
|
|
buildStaticGamePlayUrl,
|
|
GAME_PLAY_PATH_PREFIX,
|
|
HISTORICAL_503_COMMUNITY_GAME_IDS,
|
|
includedGameBundlePath,
|
|
isLfsPointerBuffer,
|
|
isValidGameTemplateId,
|
|
resolveGameBundleOriginFromEnv,
|
|
resolveStaticPlayOriginFromEnv,
|
|
isTopEarningGameTags,
|
|
TOP_EARNING_TAG,
|
|
WITHDRAWN_GAME_TEMPLATE_IDS,
|
|
type StaticGameAuditResult,
|
|
} from '../shared/game-static-play.ts';
|
|
import { collectInRepoTemplateFiles, readGameDownloadsManifest } from './package-in-repo-game-templates.ts';
|
|
|
|
export type VerifyStaticGameTemplatesOptions = {
|
|
templatesDir: string;
|
|
downloadsIndexPath: string;
|
|
fallbackSourceDir?: string;
|
|
stagedDir?: string;
|
|
communityManifestPath?: string;
|
|
playOrigin?: string | null;
|
|
appOrigin?: string | null;
|
|
bundleOrigin?: string;
|
|
pathPrefix?: string;
|
|
ids?: string[];
|
|
topOnly?: boolean;
|
|
checkR2?: boolean;
|
|
checkLive?: boolean;
|
|
checkLiveAssets?: boolean;
|
|
checkCommunityLive?: boolean;
|
|
expectListedCount?: number;
|
|
expectTopEarningCount?: number;
|
|
concurrency?: number;
|
|
retries?: number;
|
|
retryDelayMs?: number;
|
|
fetcher?: typeof fetch;
|
|
};
|
|
|
|
export type VerifyStaticGameTemplatesReport = {
|
|
ok: boolean;
|
|
summary: {
|
|
totalDirs: number;
|
|
listedCount: number;
|
|
withdrawnExcluded: string[];
|
|
inRepoCount: number;
|
|
hostedListedCount: number;
|
|
topEarningCount: number;
|
|
auditedInRepoCount: number;
|
|
auditedStagedCount: number;
|
|
checkedR2Count: number;
|
|
checkedLiveCount: number;
|
|
checkedLiveAssetCount: number;
|
|
checkedWithdrawnLiveCount: number;
|
|
checkedCommunityCount: number;
|
|
};
|
|
errors: string[];
|
|
warnings: string[];
|
|
failedTemplates: StaticGameAuditResult[];
|
|
};
|
|
|
|
function isLoopbackHost(hostname: string): boolean {
|
|
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]';
|
|
}
|
|
|
|
async function fetchWithRetry(
|
|
fetcher: typeof fetch,
|
|
url: string,
|
|
init: RequestInit,
|
|
attempts: number,
|
|
baseDelayMs: number,
|
|
timeoutMs: number,
|
|
): Promise<Response> {
|
|
const maxAttempts = Math.max(1, attempts);
|
|
let lastError: unknown;
|
|
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
try {
|
|
const res = await fetcher(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
if (res.status < 500 || attempt === maxAttempts) return res;
|
|
lastError = new Error(`HTTP ${res.status}`);
|
|
} catch (error) {
|
|
lastError = error;
|
|
}
|
|
if (attempt < maxAttempts && baseDelayMs > 0) {
|
|
await sleep(baseDelayMs * attempt);
|
|
}
|
|
}
|
|
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
}
|
|
|
|
function extractLiveReferencedAssets(html: string): string[] {
|
|
const htmlNoComments = html.replace(/<!--[\s\S]*?-->/g, '');
|
|
const assets = new Set<string>();
|
|
const mapMatches = htmlNoComments.matchAll(/\b(?:MAP|chunks)\s*=\s*(\{[\s\S]*?\});/g);
|
|
for (const match of mapMatches) {
|
|
try {
|
|
const parsed = JSON.parse(match[1]) as Record<string, unknown>;
|
|
for (const [key, parts] of Object.entries(parsed)) {
|
|
const cleanKey = key.replace(/^\.\//, '');
|
|
const dir = cleanKey.includes('/') ? cleanKey.slice(0, cleanKey.lastIndexOf('/') + 1) : '';
|
|
if (Array.isArray(parts)) {
|
|
for (const part of parts) {
|
|
if (typeof part === 'string' && part) assets.add(`${dir}${part}`);
|
|
}
|
|
}
|
|
}
|
|
} catch {
|
|
// Ignore non-JSON literals.
|
|
}
|
|
}
|
|
const refPattern = /<(?:script|link|img|audio|video|source)\b[^>]*\b(?:src|href)=["']([^"']+)["']/gi;
|
|
for (const match of htmlNoComments.matchAll(refPattern)) {
|
|
const rawRef = match[1].trim();
|
|
if (!rawRef || /^(?:https?:|data:|blob:|#|\/\/|mailto:|javascript:)/i.test(rawRef)) continue;
|
|
const cleanRef = rawRef.split('?')[0].split('#')[0];
|
|
if (!cleanRef || cleanRef.startsWith('/')) continue;
|
|
assets.add(cleanRef.replace(/^\.\//, ''));
|
|
}
|
|
return [...assets];
|
|
}
|
|
|
|
async function pathExists(target: string): Promise<boolean> {
|
|
return access(target).then(() => true, error => {
|
|
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
|
|
throw error;
|
|
});
|
|
}
|
|
|
|
async function mapConcurrent<T>(
|
|
items: readonly T[],
|
|
concurrency: number,
|
|
worker: (item: T) => Promise<void>,
|
|
): Promise<void> {
|
|
let cursor = 0;
|
|
const count = Math.max(1, Math.min(concurrency, items.length));
|
|
await Promise.all(Array.from({ length: count }, async () => {
|
|
while (cursor < items.length) {
|
|
const index = cursor++;
|
|
await worker(items[index]);
|
|
}
|
|
}));
|
|
}
|
|
|
|
async function readDirectoryFilesMap(rootDir: string): Promise<Map<string, Buffer>> {
|
|
const files = new Map<string, Buffer>();
|
|
async function walk(prefix: string): Promise<void> {
|
|
const entries = (await readdir(path.join(rootDir, prefix), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
|
|
for (const entry of entries) {
|
|
if (entry.name.startsWith('.')) continue;
|
|
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
if (!includedGameBundlePath(relative)) continue;
|
|
const fullPath = path.join(rootDir, relative);
|
|
if (entry.isDirectory()) {
|
|
await walk(relative);
|
|
} else if (entry.isFile()) {
|
|
files.set(relative, await readFile(fullPath));
|
|
}
|
|
}
|
|
}
|
|
await walk('');
|
|
return files;
|
|
}
|
|
|
|
export async function verifyStaticGameTemplates(
|
|
options: VerifyStaticGameTemplatesOptions,
|
|
): Promise<VerifyStaticGameTemplatesReport> {
|
|
const errors: string[] = [];
|
|
const warnings: string[] = [];
|
|
const failedTemplates: StaticGameAuditResult[] = [];
|
|
const concurrency = Math.max(1, options.concurrency ?? 12);
|
|
const fetcher = options.fetcher ?? globalThis.fetch;
|
|
const bundleOrigin = options.bundleOrigin ?? resolveGameBundleOriginFromEnv();
|
|
const pathPrefix = options.pathPrefix ?? GAME_PLAY_PATH_PREFIX;
|
|
|
|
const rawPlayOrigin = options.playOrigin !== undefined ? options.playOrigin : resolveStaticPlayOriginFromEnv();
|
|
let normalizedPlayOrigin: string | null = null;
|
|
if (rawPlayOrigin) {
|
|
try {
|
|
normalizedPlayOrigin = assertDistinctCookielessPlayOrigin(
|
|
rawPlayOrigin,
|
|
options.appOrigin ?? process.env.APP_PUBLIC_ORIGIN,
|
|
).origin;
|
|
} catch (error) {
|
|
errors.push(`Cookieless play origin check failed: ${(error as Error).message}`);
|
|
}
|
|
} else if (options.checkLive) {
|
|
errors.push('--check-live requires --play-origin or GAME_PLAY_PUBLIC_ORIGIN');
|
|
}
|
|
|
|
const hosted = await readGameDownloadsManifest(options.downloadsIndexPath);
|
|
const dirs = (await readdir(options.templatesDir))
|
|
.filter(name => !name.startsWith('.'))
|
|
.sort();
|
|
const dirSet = new Set(dirs);
|
|
|
|
for (const hostedId of Object.keys(hosted)) {
|
|
if (!dirSet.has(hostedId)) {
|
|
errors.push(`Orphan entry in game-downloads.json without templates/games/${hostedId}`);
|
|
}
|
|
}
|
|
|
|
const withdrawnExcluded: string[] = [];
|
|
const listedIds: string[] = [];
|
|
const inRepoIds: string[] = [];
|
|
const hostedListedIds: string[] = [];
|
|
const topEarningIds: string[] = [];
|
|
|
|
for (const id of dirs) {
|
|
if (!isValidGameTemplateId(id)) {
|
|
errors.push(`Invalid template directory name: ${id}`);
|
|
continue;
|
|
}
|
|
const dir = path.join(options.templatesDir, id);
|
|
if (!(await lstat(dir)).isDirectory()) {
|
|
errors.push(`Expected directory under templates/games: ${id}`);
|
|
continue;
|
|
}
|
|
if (WITHDRAWN_GAME_TEMPLATE_IDS.has(id)) {
|
|
withdrawnExcluded.push(id);
|
|
continue;
|
|
}
|
|
|
|
listedIds.push(id);
|
|
const cardPath = path.join(dir, 'game.json');
|
|
if (!await pathExists(cardPath)) {
|
|
errors.push(`Missing game.json for listed template: ${id}`);
|
|
} else {
|
|
const cardBuf = await readFile(cardPath);
|
|
if (isLfsPointerBuffer(cardBuf)) {
|
|
errors.push(`game.json is an unhydrated LFS pointer: ${id}`);
|
|
} else {
|
|
try {
|
|
const card = JSON.parse(cardBuf.toString('utf8')) as {
|
|
id?: unknown;
|
|
cover?: unknown;
|
|
tags?: unknown;
|
|
};
|
|
if (card.id !== id) {
|
|
errors.push(`game.json id mismatch for ${id}: got ${String(card.id)}`);
|
|
}
|
|
if (isTopEarningGameTags(card.tags as readonly string[] | null | undefined)) {
|
|
topEarningIds.push(id);
|
|
}
|
|
if (typeof card.cover === 'string' && card.cover && !/^(?:https?:|data:|\/)/i.test(card.cover)) {
|
|
const coverFile = path.join(dir, card.cover);
|
|
if (!await pathExists(coverFile)) {
|
|
errors.push(`Missing cover image for ${id}: ${card.cover}`);
|
|
} else {
|
|
const coverBuf = await readFile(coverFile);
|
|
if (isLfsPointerBuffer(coverBuf)) {
|
|
errors.push(`Cover image is an unhydrated LFS pointer: ${id}/${card.cover}`);
|
|
}
|
|
}
|
|
}
|
|
} catch (error) {
|
|
errors.push(`Malformed game.json for ${id}: ${(error as Error).message}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
const hasLocalIndex = await pathExists(path.join(dir, 'index.html'));
|
|
const hasHostedLock = Object.hasOwn(hosted, id);
|
|
if (hasLocalIndex && !hasHostedLock) {
|
|
inRepoIds.push(id);
|
|
} else if (hasHostedLock) {
|
|
hostedListedIds.push(id);
|
|
} else {
|
|
errors.push(`Template ${id} has neither local index.html nor an R2 lock in ${options.downloadsIndexPath}`);
|
|
}
|
|
}
|
|
|
|
if (options.expectListedCount !== undefined && listedIds.length !== options.expectListedCount) {
|
|
errors.push(`Expected ${options.expectListedCount} listed official templates, found ${listedIds.length}`);
|
|
}
|
|
if (options.expectTopEarningCount !== undefined && topEarningIds.length !== options.expectTopEarningCount) {
|
|
errors.push(`Expected ${options.expectTopEarningCount} ${TOP_EARNING_TAG} templates, found ${topEarningIds.length}`);
|
|
}
|
|
|
|
const topSet = new Set(topEarningIds);
|
|
const filterSet = options.ids && options.ids.length > 0 ? new Set(options.ids) : null;
|
|
const matchesFilter = (id: string) => {
|
|
if (filterSet && !filterSet.has(id)) return false;
|
|
if (options.topOnly && !topSet.has(id)) return false;
|
|
return true;
|
|
};
|
|
|
|
// 1. Audit in-repo templates locally.
|
|
let auditedInRepoCount = 0;
|
|
for (const id of inRepoIds.filter(matchesFilter)) {
|
|
try {
|
|
const fallbackDir = options.fallbackSourceDir ? path.join(options.fallbackSourceDir, id) : undefined;
|
|
const { entries } = await collectInRepoTemplateFiles(path.join(options.templatesDir, id), id, fallbackDir);
|
|
const fileMap = new Map(entries.map(entry => [entry.name, entry.data]));
|
|
const audit = auditStaticGameFiles(id, fileMap, { checkCover: true, requireViewport: true });
|
|
auditedInRepoCount += 1;
|
|
if (!audit.ok) {
|
|
failedTemplates.push(audit);
|
|
errors.push(`In-repo template ${id} failed audit: ${audit.errors.join('; ')}`);
|
|
}
|
|
for (const warn of audit.warnings) warnings.push(`[in-repo:${id}] ${warn}`);
|
|
} catch (error) {
|
|
errors.push(`In-repo template ${id} read error: ${(error as Error).message}`);
|
|
}
|
|
}
|
|
|
|
// 2. Audit staged static-play templates if --staged-dir is provided.
|
|
let auditedStagedCount = 0;
|
|
if (options.stagedDir) {
|
|
const stagedGamesRoot = path.join(options.stagedDir, pathPrefix);
|
|
if (!await pathExists(stagedGamesRoot)) {
|
|
errors.push(`Staged games directory missing: ${stagedGamesRoot}`);
|
|
} else {
|
|
const stagedIds = (await readdir(stagedGamesRoot))
|
|
.filter(name => !name.startsWith('.'))
|
|
.sort();
|
|
for (const withdrawnId of WITHDRAWN_GAME_TEMPLATE_IDS) {
|
|
if (stagedIds.includes(withdrawnId)) {
|
|
errors.push(`Withdrawn template MUST NOT exist in staged static output: ${withdrawnId}`);
|
|
}
|
|
}
|
|
for (const id of stagedIds.filter(matchesFilter)) {
|
|
const files = await readDirectoryFilesMap(path.join(stagedGamesRoot, id));
|
|
const audit = auditStaticGameFiles(id, files, { checkCover: true, requireViewport: true });
|
|
auditedStagedCount += 1;
|
|
if (!audit.ok) {
|
|
failedTemplates.push(audit);
|
|
errors.push(`Staged template ${id} failed audit: ${audit.errors.join('; ')}`);
|
|
}
|
|
for (const warn of audit.warnings) warnings.push(`[staged:${id}] ${warn}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
const retries = options.retries ?? 3;
|
|
const retryDelayMs = options.retryDelayMs ?? 300;
|
|
|
|
// 3. Verify community catalog excludes the 3 historical 503 Vercel games (and optionally probe live).
|
|
let checkedCommunityCount = 0;
|
|
if (options.communityManifestPath && await pathExists(options.communityManifestPath)) {
|
|
const raw = await readFile(options.communityManifestPath, 'utf8');
|
|
const communityGames = JSON.parse(raw) as { id?: string; url?: string }[];
|
|
assert(Array.isArray(communityGames), `Invalid community manifest: ${options.communityManifestPath}`);
|
|
for (const game of communityGames) {
|
|
if (game.id && HISTORICAL_503_COMMUNITY_GAME_IDS.has(game.id)) {
|
|
errors.push(`Historical 503 community game still listed in ${options.communityManifestPath}: ${game.id} (${game.url ?? ''})`);
|
|
}
|
|
}
|
|
if (options.checkCommunityLive) {
|
|
await mapConcurrent(communityGames, Math.min(8, concurrency), async game => {
|
|
if (!game.url) return;
|
|
checkedCommunityCount += 1;
|
|
try {
|
|
const response = await fetchWithRetry(fetcher, game.url, { method: 'GET', redirect: 'follow' }, retries, retryDelayMs, 15_000);
|
|
if (response.status >= 400) {
|
|
errors.push(`Community game ${game.id ?? game.url} returned HTTP ${response.status} (${game.url})`);
|
|
}
|
|
} catch (error) {
|
|
errors.push(`Community game ${game.id ?? game.url} fetch failed: ${(error as Error).message}`);
|
|
}
|
|
});
|
|
} else {
|
|
checkedCommunityCount = communityGames.length;
|
|
}
|
|
}
|
|
|
|
// 4. Optional live R2 HEAD verification for hosted zip bundles.
|
|
let checkedR2Count = 0;
|
|
if (options.checkR2) {
|
|
const targetIds = hostedListedIds.filter(matchesFilter);
|
|
await mapConcurrent(targetIds, concurrency, async id => {
|
|
const lock = hosted[id];
|
|
const url = buildGameBundleUrl(lock.sha256, bundleOrigin);
|
|
checkedR2Count += 1;
|
|
try {
|
|
const res = await fetchWithRetry(fetcher, url, { method: 'HEAD', redirect: 'error' }, retries, retryDelayMs, 20_000);
|
|
if (res.status !== 200) {
|
|
errors.push(`R2 bundle HEAD failed for ${id}: HTTP ${res.status} (${url})`);
|
|
return;
|
|
}
|
|
const len = res.headers.get('content-length');
|
|
if (len !== null && Number(len) !== lock.bytes) {
|
|
errors.push(`R2 bundle size mismatch for ${id}: expected ${lock.bytes}, got ${len} (${url})`);
|
|
}
|
|
} catch (error) {
|
|
errors.push(`R2 bundle HEAD error for ${id}: ${(error as Error).message}`);
|
|
}
|
|
});
|
|
}
|
|
|
|
// 5. Optional live cookieless static playable domain verification.
|
|
let checkedLiveCount = 0;
|
|
let checkedLiveAssetCount = 0;
|
|
let checkedWithdrawnLiveCount = 0;
|
|
if (options.checkLive && normalizedPlayOrigin) {
|
|
const playUrlObj = new URL(normalizedPlayOrigin);
|
|
const enforceEdgeSecurityHeaders = playUrlObj.protocol === 'https:' && !isLoopbackHost(playUrlObj.hostname);
|
|
const targetIds = listedIds.filter(matchesFilter);
|
|
const liveAssetQueue: { id: string; rel: string }[] = [];
|
|
|
|
await mapConcurrent(targetIds, concurrency, async id => {
|
|
const url = buildStaticGamePlayUrl(normalizedPlayOrigin!, id, { prefix: pathPrefix });
|
|
checkedLiveCount += 1;
|
|
try {
|
|
const res = await fetchWithRetry(fetcher, url, { method: 'GET', redirect: 'error' }, retries, retryDelayMs, 20_000);
|
|
if (res.status !== 200) {
|
|
errors.push(`Live static play failed for ${id}: HTTP ${res.status} (${url})`);
|
|
return;
|
|
}
|
|
const setCookie = res.headers.get('set-cookie');
|
|
if (setCookie) {
|
|
errors.push(`Live static play for ${id} emitted Set-Cookie header (violates cookieless domain isolation): ${url}`);
|
|
}
|
|
const xfo = res.headers.get('x-frame-options');
|
|
if (xfo && /^(?:deny|sameorigin)$/i.test(xfo.trim())) {
|
|
errors.push(`Live static play for ${id} blocks desktop iframe via X-Frame-Options: ${xfo}`);
|
|
}
|
|
const csp = res.headers.get('content-security-policy');
|
|
if (csp && /frame-ancestors\s+['"]?(?:none|self)['"]?/i.test(csp)) {
|
|
errors.push(`Live static play for ${id} blocks desktop iframe via CSP: ${csp}`);
|
|
}
|
|
if (enforceEdgeSecurityHeaders) {
|
|
if ((res.headers.get('x-content-type-options') ?? '').toLowerCase() !== 'nosniff') {
|
|
errors.push(`Live static play for ${id} missing X-Content-Type-Options: nosniff (${url})`);
|
|
}
|
|
if ((res.headers.get('referrer-policy') ?? '').toLowerCase() !== 'no-referrer') {
|
|
errors.push(`Live static play for ${id} missing Referrer-Policy: no-referrer (${url})`);
|
|
}
|
|
if ((res.headers.get('cross-origin-resource-policy') ?? '').toLowerCase() !== 'cross-origin') {
|
|
errors.push(`Live static play for ${id} missing Cross-Origin-Resource-Policy: cross-origin (${url})`);
|
|
}
|
|
}
|
|
const contentType = res.headers.get('content-type') ?? '';
|
|
if (!contentType.toLowerCase().includes('text/html')) {
|
|
errors.push(`Live static play for ${id} returned non-HTML Content-Type (${contentType})`);
|
|
}
|
|
const body = await res.text();
|
|
if (!/<meta\b[^>]*\bname=["']viewport["']/i.test(body)) {
|
|
errors.push(`Live static play HTML for ${id} is missing <meta name="viewport">`);
|
|
}
|
|
if (options.checkLiveAssets) {
|
|
for (const rel of extractLiveReferencedAssets(body)) {
|
|
liveAssetQueue.push({ id, rel });
|
|
}
|
|
}
|
|
} catch (error) {
|
|
errors.push(`Live static play request error for ${id}: ${(error as Error).message}`);
|
|
}
|
|
});
|
|
|
|
if (options.checkLiveAssets && liveAssetQueue.length > 0) {
|
|
const cleanPrefix = pathPrefix.replace(/^\/+|\/+$/g, '');
|
|
await mapConcurrent(liveAssetQueue, Math.max(concurrency, 16), async ({ id, rel }) => {
|
|
checkedLiveAssetCount += 1;
|
|
const encodedRel = rel.split('/').map(encodeURIComponent).join('/');
|
|
const assetPath = cleanPrefix ? `${cleanPrefix}/${encodeURIComponent(id)}/${encodedRel}` : `${encodeURIComponent(id)}/${encodedRel}`;
|
|
const assetUrl = `${normalizedPlayOrigin!}/${assetPath}`;
|
|
try {
|
|
const res = await fetchWithRetry(fetcher, assetUrl, { method: 'HEAD', redirect: 'error' }, retries, retryDelayMs, 15_000);
|
|
if (res.status !== 200) {
|
|
errors.push(`Live static play asset missing for ${id}/${rel}: HTTP ${res.status} (${assetUrl})`);
|
|
}
|
|
} catch (error) {
|
|
errors.push(`Live static play asset HEAD error for ${id}/${rel}: ${(error as Error).message}`);
|
|
}
|
|
});
|
|
}
|
|
|
|
// Confirm withdrawn templates return 404 on the live static play domain.
|
|
const cleanPrefix = pathPrefix.replace(/^\/+|\/+$/g, '');
|
|
await mapConcurrent([...WITHDRAWN_GAME_TEMPLATE_IDS], 3, async withdrawnId => {
|
|
checkedWithdrawnLiveCount += 1;
|
|
const withdrawnPath = cleanPrefix
|
|
? `${cleanPrefix}/${encodeURIComponent(withdrawnId)}/index.html`
|
|
: `${encodeURIComponent(withdrawnId)}/index.html`;
|
|
const withdrawnUrl = `${normalizedPlayOrigin!}/${withdrawnPath}`;
|
|
try {
|
|
const res = await fetchWithRetry(fetcher, withdrawnUrl, { method: 'HEAD', redirect: 'error' }, retries, retryDelayMs, 15_000);
|
|
if (res.status !== 404) {
|
|
errors.push(`Withdrawn template ${withdrawnId} must return HTTP 404 on live play domain, got HTTP ${res.status} (${withdrawnUrl})`);
|
|
}
|
|
} catch (error) {
|
|
errors.push(`Withdrawn template live check error for ${withdrawnId}: ${(error as Error).message}`);
|
|
}
|
|
});
|
|
}
|
|
|
|
return {
|
|
ok: errors.length === 0,
|
|
summary: {
|
|
totalDirs: dirs.length,
|
|
listedCount: listedIds.length,
|
|
withdrawnExcluded: withdrawnExcluded.sort(),
|
|
inRepoCount: inRepoIds.length,
|
|
hostedListedCount: hostedListedIds.length,
|
|
topEarningCount: topEarningIds.length,
|
|
auditedInRepoCount,
|
|
auditedStagedCount,
|
|
checkedR2Count,
|
|
checkedLiveCount,
|
|
checkedLiveAssetCount,
|
|
checkedWithdrawnLiveCount,
|
|
checkedCommunityCount,
|
|
},
|
|
errors,
|
|
warnings,
|
|
failedTemplates,
|
|
};
|
|
}
|
|
|
|
function parseCliArgs(argv: string[]): VerifyStaticGameTemplatesOptions & { json: boolean } {
|
|
let templatesDir = path.resolve('templates/games');
|
|
let downloadsIndexPath = path.resolve('templates/game-downloads.json');
|
|
let fallbackSourceDir: string | undefined;
|
|
let stagedDir: string | undefined;
|
|
let communityManifestPath: string | undefined = path.resolve('studio/src/motion/game/community/more-games.json');
|
|
let playOrigin: string | null | undefined;
|
|
let appOrigin: string | null | undefined;
|
|
let bundleOrigin: string | undefined;
|
|
let pathPrefix: string | undefined;
|
|
let ids: string[] | undefined;
|
|
let topOnly = false;
|
|
let checkR2 = false;
|
|
let checkLive = false;
|
|
let checkLiveAssets = false;
|
|
let checkCommunityLive = false;
|
|
let expectListedCount: number | undefined;
|
|
let expectTopEarningCount: number | undefined;
|
|
let concurrency = 12;
|
|
let json = false;
|
|
|
|
for (let i = 0; i < argv.length; i += 1) {
|
|
const arg = argv[i];
|
|
if (arg === '--templates-dir') templatesDir = path.resolve(argv[++i]);
|
|
else if (arg === '--downloads-index') downloadsIndexPath = path.resolve(argv[++i]);
|
|
else if (arg === '--fallback-source-dir') fallbackSourceDir = path.resolve(argv[++i]);
|
|
else if (arg === '--staged-dir') stagedDir = path.resolve(argv[++i]);
|
|
else if (arg === '--community-manifest') communityManifestPath = path.resolve(argv[++i]);
|
|
else if (arg === '--no-community-check') communityManifestPath = undefined;
|
|
else if (arg === '--play-origin') playOrigin = argv[++i];
|
|
else if (arg === '--app-origin') appOrigin = argv[++i];
|
|
else if (arg === '--bundle-origin') bundleOrigin = argv[++i];
|
|
else if (arg === '--path-prefix') pathPrefix = argv[++i];
|
|
else if (arg === '--ids') ids = argv[++i].split(',').map(s => s.trim()).filter(Boolean);
|
|
else if (arg === '--top-only') topOnly = true;
|
|
else if (arg === '--check-r2') checkR2 = true;
|
|
else if (arg === '--check-live') checkLive = true;
|
|
else if (arg === '--check-live-assets') { checkLive = true; checkLiveAssets = true; }
|
|
else if (arg === '--check-community') checkCommunityLive = true;
|
|
else if (arg === '--expect-listed') expectListedCount = Number(argv[++i]);
|
|
else if (arg === '--expect-top-earning') expectTopEarningCount = Number(argv[++i]);
|
|
else if (arg === '--concurrency') concurrency = Number(argv[++i]);
|
|
else if (arg === '--json') json = true;
|
|
else throw new Error(`Unknown option: ${arg}`);
|
|
}
|
|
|
|
return {
|
|
templatesDir,
|
|
downloadsIndexPath,
|
|
fallbackSourceDir,
|
|
stagedDir,
|
|
communityManifestPath,
|
|
playOrigin,
|
|
appOrigin,
|
|
bundleOrigin,
|
|
pathPrefix,
|
|
ids,
|
|
topOnly,
|
|
checkR2,
|
|
checkLive,
|
|
checkLiveAssets,
|
|
checkCommunityLive,
|
|
expectListedCount,
|
|
expectTopEarningCount,
|
|
concurrency,
|
|
json,
|
|
};
|
|
}
|
|
|
|
if (isMain(import.meta.url)) {
|
|
const cli = parseCliArgs(process.argv.slice(2));
|
|
const report = await verifyStaticGameTemplates(cli);
|
|
if (cli.json) {
|
|
console.log(JSON.stringify(report, null, 2));
|
|
} else {
|
|
const s = report.summary;
|
|
console.log(
|
|
`[VERIFY ${report.ok ? 'PASS' : 'FAIL'}] ` +
|
|
`listed=${s.listedCount} (in-repo=${s.inRepoCount}, r2-hosted=${s.hostedListedCount}, TOP赚钱=${s.topEarningCount}, withdrawn=${s.withdrawnExcluded.length}) ` +
|
|
`auditedInRepo=${s.auditedInRepoCount} auditedStaged=${s.auditedStagedCount} checkedR2=${s.checkedR2Count} ` +
|
|
`checkedLive=${s.checkedLiveCount} checkedLiveAssets=${s.checkedLiveAssetCount} checkedWithdrawn404=${s.checkedWithdrawnLiveCount} community=${s.checkedCommunityCount}`,
|
|
);
|
|
for (const warning of report.warnings) console.warn(`WARN: ${warning}`);
|
|
for (const error of report.errors) console.error(`ERROR: ${error}`);
|
|
}
|
|
if (!report.ok) process.exitCode = 1;
|
|
}
|