mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-06 23:37:19 +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>
650 lines
24 KiB
TypeScript
650 lines
24 KiB
TypeScript
import assert from 'node:assert/strict';
|
|
import { createHash } from 'node:crypto';
|
|
import { crc32, deflateRawSync } from 'node:zlib';
|
|
import {
|
|
GAME_BUNDLE_OBJECT_PREFIX,
|
|
GAME_TEMPLATE_ID_PATTERN,
|
|
isTopEarningGameTags,
|
|
TOP_EARNING_GAME_TAG,
|
|
WITHDRAWN_GAME_TEMPLATES,
|
|
} from './game-contract.ts';
|
|
import { mediaOrigin } from './repository-media.ts';
|
|
|
|
export { GAME_BUNDLE_OBJECT_PREFIX, isTopEarningGameTags };
|
|
|
|
/**
|
|
* Shared contract and pure utilities for OpenGame Stage 1 static playable hosting
|
|
* and unified R2 template zip packaging.
|
|
*
|
|
* All production domains are configured dynamically via environment variables:
|
|
* - `GAME_PLAY_PUBLIC_ORIGIN`: independent cookieless static playable domain
|
|
* (distinct host from `APP_PUBLIC_ORIGIN`, zero main-site cookies/auth).
|
|
* - `GAME_BUNDLE_PUBLIC_ORIGIN`: optional R2/CDN origin for immutable template
|
|
* zips (defaults to `mediaOrigin` from `shared/repository-media.ts`).
|
|
*/
|
|
|
|
export const GAME_PLAY_ENV_VAR = 'GAME_PLAY_PUBLIC_ORIGIN';
|
|
export const GAME_BUNDLE_ORIGIN_ENV_VAR = 'GAME_BUNDLE_PUBLIC_ORIGIN';
|
|
export const GAME_PLAY_PATH_PREFIX = 'games';
|
|
export const MAX_GAME_BUNDLE_BYTES = 150 * 1024 * 1024;
|
|
export const TOP_EARNING_TAG = TOP_EARNING_GAME_TAG;
|
|
export const OFFLINE_STARTER_GAME_ID = 'tidebreaker';
|
|
|
|
const LFS_POINTER_PREFIX = 'version https://git-lfs.github.com/spec/v1';
|
|
const SHA256_RE = /^[a-f0-9]{64}$/;
|
|
|
|
/** Official templates withdrawn from the Stage 1 catalog and static playable routes (same set as the catalog). */
|
|
export const WITHDRAWN_GAME_TEMPLATE_IDS: ReadonlySet<string> = WITHDRAWN_GAME_TEMPLATES;
|
|
|
|
/**
|
|
* Historical 503 community games (external Vercel deployments returning HTTP 503
|
|
* `x-vercel-error: DEPLOYMENT_PAUSED`), excluded from the catalog per opengame #182.
|
|
*/
|
|
export const HISTORICAL_503_COMMUNITY_GAME_IDS: ReadonlySet<string> = new Set([
|
|
'what-the-water-keeps',
|
|
'evensong',
|
|
'gilt-and-gutter',
|
|
]);
|
|
|
|
export type GameBundleLock = {
|
|
sha256: string;
|
|
bytes: number;
|
|
};
|
|
|
|
export type GameDownloadManifest = {
|
|
schemaVersion: 1;
|
|
games: Record<string, GameBundleLock>;
|
|
};
|
|
|
|
export type StaticGameManifestEntry = {
|
|
id: string;
|
|
source: 'in-repo' | 'r2-hosted';
|
|
sha256: string;
|
|
bytes: number;
|
|
fileCount: number;
|
|
unpackedBytes: number;
|
|
topEarning: boolean;
|
|
orientation: 'portrait' | 'landscape';
|
|
entryPath: string;
|
|
playUrl: string | null;
|
|
bundleUrl: string;
|
|
injectedViewport: boolean;
|
|
injectedCocosGuard: boolean;
|
|
injectedTouchGuard: boolean;
|
|
};
|
|
|
|
export type StaticGameDeployManifest = {
|
|
schemaVersion: 1;
|
|
generatedAt: string;
|
|
playOrigin: string | null;
|
|
playPathPrefix: string;
|
|
bundleOrigin: string;
|
|
totalTemplates: number;
|
|
inRepoCount: number;
|
|
hostedCount: number;
|
|
topEarningCount: number;
|
|
withdrawnExcluded: string[];
|
|
games: StaticGameManifestEntry[];
|
|
};
|
|
|
|
export type StaticGameAuditResult = {
|
|
id: string;
|
|
ok: boolean;
|
|
errors: string[];
|
|
warnings: string[];
|
|
stats: {
|
|
fileCount: number;
|
|
totalBytes: number;
|
|
hasViewport: boolean;
|
|
hasCocosSystemJs: boolean;
|
|
isTopEarning: boolean;
|
|
orientation: 'portrait' | 'landscape';
|
|
};
|
|
};
|
|
|
|
export function isValidGameTemplateId(id: string): boolean {
|
|
return typeof id === 'string' && GAME_TEMPLATE_ID_PATTERN.test(id);
|
|
}
|
|
|
|
export function isListedStaticGameTemplate(id: string): boolean {
|
|
return isValidGameTemplateId(id) && !WITHDRAWN_GAME_TEMPLATE_IDS.has(id);
|
|
}
|
|
|
|
export function sha256Hex(bytes: Buffer | Uint8Array): string {
|
|
return createHash('sha256').update(bytes).digest('hex');
|
|
}
|
|
|
|
export function isLfsPointerBuffer(data: Buffer): boolean {
|
|
return data.length >= 45 && data.length <= 1024 && data.subarray(0, 45).toString('utf8').startsWith(LFS_POINTER_PREFIX);
|
|
}
|
|
|
|
export function parseLfsPointer(data: Buffer): { sha256: string; bytes: number } | null {
|
|
if (!isLfsPointerBuffer(data)) return null;
|
|
const text = data.toString('utf8');
|
|
const match = /oid sha256:([a-f0-9]{64})\nsize (\d+)/.exec(text);
|
|
if (!match) return null;
|
|
const bytes = Number(match[2]);
|
|
if (!Number.isSafeInteger(bytes) || bytes <= 0) return null;
|
|
return { sha256: match[1], bytes };
|
|
}
|
|
|
|
function isLoopbackHost(hostname: string): boolean {
|
|
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]';
|
|
}
|
|
|
|
export function normalizeStaticPlayOrigin(raw: string | undefined | null): string | null {
|
|
const trimmed = raw?.trim();
|
|
if (!trimmed) return null;
|
|
const parsed = new URL(trimmed);
|
|
assert(
|
|
parsed.protocol === 'https:' || (parsed.protocol === 'http:' && isLoopbackHost(parsed.hostname)),
|
|
`GAME_PLAY_PUBLIC_ORIGIN must use https (or loopback http for local dev): ${trimmed}`,
|
|
);
|
|
assert(!parsed.username && !parsed.password, 'GAME_PLAY_PUBLIC_ORIGIN must not contain credentials');
|
|
assert(
|
|
(parsed.pathname === '/' || parsed.pathname === '') && !parsed.search && !parsed.hash,
|
|
`GAME_PLAY_PUBLIC_ORIGIN must be an origin without path, query, or hash: ${trimmed}`,
|
|
);
|
|
return parsed.origin;
|
|
}
|
|
|
|
/**
|
|
* Validate that the static playable origin is an independent, cookieless host
|
|
* separate from `APP_PUBLIC_ORIGIN` (no shared host; rejects parent/same host
|
|
* cookie bleed when appOrigin is provided on non-loopback hosts).
|
|
*/
|
|
export function assertDistinctCookielessPlayOrigin(
|
|
playOrigin: string,
|
|
appOrigin?: string | null,
|
|
): URL {
|
|
const normalizedPlay = normalizeStaticPlayOrigin(playOrigin);
|
|
assert(normalizedPlay, 'Missing static playable origin');
|
|
const playUrl = new URL(normalizedPlay);
|
|
if (appOrigin?.trim()) {
|
|
const appUrl = new URL(appOrigin.trim());
|
|
const playHost = playUrl.hostname.toLowerCase();
|
|
const appHost = appUrl.hostname.toLowerCase();
|
|
if (isLoopbackHost(playHost) && isLoopbackHost(appHost)) {
|
|
assert(
|
|
playUrl.origin !== appUrl.origin,
|
|
`Static playable origin (${playUrl.origin}) must differ from APP_PUBLIC_ORIGIN (${appUrl.origin})`,
|
|
);
|
|
} else {
|
|
assert(
|
|
playHost !== appHost,
|
|
`Static playable host (${playHost}) must be distinct from APP_PUBLIC_ORIGIN host (${appHost}) to guarantee zero main-site cookies`,
|
|
);
|
|
assert(
|
|
!playHost.endsWith(`.${appHost}`),
|
|
`Static playable host (${playHost}) must not be a subdomain of APP_PUBLIC_ORIGIN (${appHost}) because parent-domain cookies would leak`,
|
|
);
|
|
}
|
|
}
|
|
return playUrl;
|
|
}
|
|
|
|
export function resolveStaticPlayOriginFromEnv(env: Record<string, string | undefined> = process.env): string | null {
|
|
return normalizeStaticPlayOrigin(env[GAME_PLAY_ENV_VAR]);
|
|
}
|
|
|
|
export function resolveGameBundleOriginFromEnv(env: Record<string, string | undefined> = process.env): string {
|
|
const configured = env[GAME_BUNDLE_ORIGIN_ENV_VAR]?.trim();
|
|
if (!configured) return mediaOrigin;
|
|
const parsed = new URL(configured);
|
|
assert(
|
|
parsed.protocol === 'https:' || (parsed.protocol === 'http:' && isLoopbackHost(parsed.hostname)),
|
|
`GAME_BUNDLE_PUBLIC_ORIGIN must use https (or loopback http for local dev): ${configured}`,
|
|
);
|
|
assert(!parsed.username && !parsed.password && !parsed.search && !parsed.hash, 'Invalid GAME_BUNDLE_PUBLIC_ORIGIN');
|
|
return parsed.origin;
|
|
}
|
|
|
|
export function buildStaticGameEntryPath(id: string, prefix = GAME_PLAY_PATH_PREFIX): string {
|
|
assert(isValidGameTemplateId(id), `Invalid game template id: ${id}`);
|
|
assert(isListedStaticGameTemplate(id), `Withdrawn game template cannot be published for static play: ${id}`);
|
|
const cleanPrefix = prefix.replace(/^\/+|\/+$/g, '');
|
|
const encoded = encodeURIComponent(id);
|
|
return cleanPrefix ? `${cleanPrefix}/${encoded}/index.html` : `${encoded}/index.html`;
|
|
}
|
|
|
|
/**
|
|
* Canonical static playable URL for an official template:
|
|
* `${GAME_PLAY_PUBLIC_ORIGIN}/games/${encodeURIComponent(id)}/index.html`
|
|
*/
|
|
export function buildStaticGamePlayUrl(
|
|
playOrigin: string,
|
|
id: string,
|
|
options?: { prefix?: string; appOrigin?: string | null },
|
|
): string {
|
|
const originUrl = assertDistinctCookielessPlayOrigin(playOrigin, options?.appOrigin);
|
|
const entryPath = buildStaticGameEntryPath(id, options?.prefix ?? GAME_PLAY_PATH_PREFIX);
|
|
return `${originUrl.origin}/${entryPath}`;
|
|
}
|
|
|
|
export function buildGameBundleObjectKey(sha256: string): string {
|
|
assert(SHA256_RE.test(sha256), `Invalid game bundle sha256: ${sha256}`);
|
|
return `${GAME_BUNDLE_OBJECT_PREFIX}${sha256}.zip`;
|
|
}
|
|
|
|
export function buildGameBundleUrl(sha256: string, bundleOrigin = mediaOrigin): string {
|
|
const cleanOrigin = bundleOrigin.replace(/\/+$/, '');
|
|
return `${cleanOrigin}/${buildGameBundleObjectKey(sha256)}`;
|
|
}
|
|
|
|
/** Exclude hidden dotfiles and local publish/trailer artifacts from packaged/deployed game templates. */
|
|
export function includedGameBundlePath(relative: string): boolean {
|
|
const normalized = relative.replace(/\\/g, '/').replace(/^\/+/, '');
|
|
if (!normalized) return false;
|
|
const parts = normalized.split('/');
|
|
if (parts.some(part => !part || part === '.' || part === '..' || part.startsWith('.'))) return false;
|
|
if (/^(?:publish|trailer)$/i.test(parts[0])) return false;
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Deterministic ZIP writer matching `opengame/scripts/zip.mjs` and round-trip
|
|
* compatible with `shared/project-zip.ts` (`readProjectZip`).
|
|
*/
|
|
export function deflateZip(
|
|
entries: readonly { name: string; data: Buffer }[],
|
|
options: { deflate?: boolean } = {},
|
|
): Buffer {
|
|
const deflate = options.deflate ?? true;
|
|
const sorted = [...entries].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
const local: Buffer[] = [];
|
|
const central: Buffer[] = [];
|
|
let offset = 0;
|
|
let directorySize = 0;
|
|
for (const entry of sorted) {
|
|
const name = Buffer.from(entry.name, 'utf8');
|
|
const crc = crc32(entry.data);
|
|
const compressed = deflate && entry.data.length >= 128 ? deflateRawSync(entry.data) : entry.data;
|
|
const useDeflate = compressed.length < entry.data.length;
|
|
const payload = useDeflate ? compressed : entry.data;
|
|
|
|
const header = Buffer.alloc(30);
|
|
header.writeUInt32LE(0x04034b50, 0);
|
|
header.writeUInt16LE(20, 4);
|
|
header.writeUInt16LE(0x800, 6);
|
|
header.writeUInt16LE(useDeflate ? 8 : 0, 8);
|
|
header.writeUInt16LE(33, 12);
|
|
header.writeUInt32LE(crc, 14);
|
|
header.writeUInt32LE(payload.length, 18);
|
|
header.writeUInt32LE(entry.data.length, 22);
|
|
header.writeUInt16LE(name.length, 26);
|
|
|
|
const dir = Buffer.alloc(46);
|
|
dir.writeUInt32LE(0x02014b50, 0);
|
|
dir.writeUInt16LE(20, 4);
|
|
dir.writeUInt16LE(20, 6);
|
|
dir.writeUInt16LE(0x800, 8);
|
|
dir.writeUInt16LE(useDeflate ? 8 : 0, 10);
|
|
dir.writeUInt16LE(33, 14);
|
|
dir.writeUInt32LE(crc, 16);
|
|
dir.writeUInt32LE(payload.length, 20);
|
|
dir.writeUInt32LE(entry.data.length, 24);
|
|
dir.writeUInt16LE(name.length, 28);
|
|
dir.writeUInt32LE(offset, 42);
|
|
|
|
local.push(header, name, payload);
|
|
central.push(dir, name);
|
|
offset += header.length + name.length + payload.length;
|
|
directorySize += dir.length + name.length;
|
|
}
|
|
|
|
const end = Buffer.alloc(22);
|
|
end.writeUInt32LE(0x06054b50, 0);
|
|
end.writeUInt16LE(sorted.length, 8);
|
|
end.writeUInt16LE(sorted.length, 10);
|
|
end.writeUInt32LE(directorySize, 12);
|
|
end.writeUInt32LE(offset, 16);
|
|
return Buffer.concat([...local, ...central, end]);
|
|
}
|
|
|
|
const STATIC_MIME_TYPES: Record<string, string> = {
|
|
'.html': 'text/html; charset=utf-8',
|
|
'.htm': 'text/html; charset=utf-8',
|
|
'.js': 'text/javascript; charset=utf-8',
|
|
'.mjs': 'text/javascript; charset=utf-8',
|
|
'.cjs': 'text/javascript; charset=utf-8',
|
|
'.css': 'text/css; charset=utf-8',
|
|
'.json': 'application/json; charset=utf-8',
|
|
'.map': 'application/json; charset=utf-8',
|
|
'.svg': 'image/svg+xml',
|
|
'.png': 'image/png',
|
|
'.jpg': 'image/jpeg',
|
|
'.jpeg': 'image/jpeg',
|
|
'.webp': 'image/webp',
|
|
'.avif': 'image/avif',
|
|
'.gif': 'image/gif',
|
|
'.ico': 'image/x-icon',
|
|
'.woff': 'font/woff',
|
|
'.woff2': 'font/woff2',
|
|
'.ttf': 'font/ttf',
|
|
'.otf': 'font/otf',
|
|
'.mp3': 'audio/mpeg',
|
|
'.ogg': 'audio/ogg',
|
|
'.wav': 'audio/wav',
|
|
'.m4a': 'audio/mp4',
|
|
'.mp4': 'video/mp4',
|
|
'.webm': 'video/webm',
|
|
'.wasm': 'application/wasm',
|
|
'.glb': 'model/gltf-binary',
|
|
'.gltf': 'model/gltf+json',
|
|
'.bin': 'application/octet-stream',
|
|
'.cconb': 'application/octet-stream',
|
|
'.txt': 'text/plain; charset=utf-8',
|
|
'.md': 'text/markdown; charset=utf-8',
|
|
'.csv': 'text/csv; charset=utf-8',
|
|
'.xml': 'application/xml; charset=utf-8',
|
|
'.atlas': 'text/plain; charset=utf-8',
|
|
'.fnt': 'text/plain; charset=utf-8',
|
|
'.plist': 'application/xml; charset=utf-8',
|
|
'.glsl': 'text/plain; charset=utf-8',
|
|
'.vert': 'text/plain; charset=utf-8',
|
|
'.frag': 'text/plain; charset=utf-8',
|
|
};
|
|
|
|
export function contentTypeForStaticGamePath(relativePath: string): string {
|
|
const lower = relativePath.toLowerCase();
|
|
if (/\.part\d+$/.test(lower)) return 'application/octet-stream';
|
|
const dot = lower.lastIndexOf('.');
|
|
if (dot < 0) return 'application/octet-stream';
|
|
return STATIC_MIME_TYPES[lower.slice(dot)] ?? 'application/octet-stream';
|
|
}
|
|
|
|
export function cacheControlForStaticGamePath(relativePath: string): string {
|
|
const normalized = relativePath.replace(/\\/g, '/').replace(/^\/+/, '');
|
|
if (normalized === 'index.html' || normalized.endsWith('/index.html') || normalized === 'manifest.json') {
|
|
return 'public, max-age=300, must-revalidate';
|
|
}
|
|
if (/[-.][a-f0-9]{8,}\.[a-z0-9]+$/i.test(normalized) || /\/(?:import|native)\/[a-f0-9]{2}\//i.test(normalized)) {
|
|
return 'public, max-age=31536000, immutable';
|
|
}
|
|
return 'public, max-age=86400';
|
|
}
|
|
|
|
/**
|
|
* Lightweight SystemJS wait-guard so cross-bundle Cocos `chunks:///` modules
|
|
* resolve reliably over real CDN latency when bundles arrive out of order.
|
|
*/
|
|
const COCOS_CHUNK_GUARD_SCRIPT = `<script data-om-cocos-chunk-guard="1">(() => {
|
|
const sys = typeof System !== 'undefined' ? System : null;
|
|
if (!sys || sys.__omChunkGuard) return;
|
|
sys.__omChunkGuard = true;
|
|
const proto = Object.getPrototypeOf(sys);
|
|
if (!proto || typeof proto.register !== 'function' || typeof proto.instantiate !== 'function') return;
|
|
const origRegister = proto.register;
|
|
const origInstantiate = proto.instantiate;
|
|
const waiters = new Map();
|
|
proto.register = function (name) {
|
|
const res = origRegister.apply(this, arguments);
|
|
if (typeof name === 'string' && name.indexOf('chunks://') === 0) {
|
|
const pending = waiters.get(name);
|
|
if (pending && pending.length) {
|
|
waiters.delete(name);
|
|
const reg = this.registerRegistry && this.registerRegistry[name];
|
|
if (this.registerRegistry && reg) this.registerRegistry[name] = null;
|
|
for (let i = 0; i < pending.length; i++) pending[i](reg);
|
|
}
|
|
}
|
|
return res;
|
|
};
|
|
proto.instantiate = function (url, parent) {
|
|
if (typeof url === 'string' && url.indexOf('chunks://') === 0 && (!this.registerRegistry || !this.registerRegistry[url])) {
|
|
const self = this;
|
|
return new Promise((resolve, reject) => {
|
|
let settled = false;
|
|
const done = reg => {
|
|
if (settled) return;
|
|
settled = true;
|
|
clearTimeout(timer);
|
|
if (reg) resolve(reg);
|
|
else Promise.resolve().then(() => origInstantiate.call(self, url, parent)).then(resolve, reject);
|
|
};
|
|
const timer = setTimeout(() => {
|
|
const list = waiters.get(url);
|
|
if (list) {
|
|
const idx = list.indexOf(done);
|
|
if (idx >= 0) list.splice(idx, 1);
|
|
if (!list.length) waiters.delete(url);
|
|
}
|
|
done(null);
|
|
}, 8000);
|
|
const list = waiters.get(url) || [];
|
|
list.push(done);
|
|
waiters.set(url, list);
|
|
});
|
|
}
|
|
return origInstantiate.call(this, url, parent);
|
|
};
|
|
})();</script>`;
|
|
|
|
const MOBILE_VIEWPORT_META =
|
|
'<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" data-om-static-viewport="1" />';
|
|
|
|
const MOBILE_TOUCH_STYLE =
|
|
'<style data-om-static-touch-guard="1">html,body{overscroll-behavior:none;-webkit-tap-highlight-color:transparent;touch-action:manipulation;}</style>';
|
|
|
|
function insertAfterHeadOpen(html: string, snippet: string): string {
|
|
if (/<head\b[^>]*>/i.test(html)) {
|
|
return html.replace(/<head\b[^>]*>/i, match => `${match}\n${snippet}`);
|
|
}
|
|
if (/<html\b[^>]*>/i.test(html)) {
|
|
return html.replace(/<html\b[^>]*>/i, match => `${match}\n<head>\n${snippet}\n</head>`);
|
|
}
|
|
if (/^\s*<!doctype[^>]*>/i.test(html)) {
|
|
return html.replace(/^\s*<!doctype[^>]*>/i, match => `${match}\n${snippet}`);
|
|
}
|
|
return `${snippet}\n${html}`;
|
|
}
|
|
|
|
/**
|
|
* Prepare a game's `index.html` for pure-static hosting on an independent
|
|
* cookieless playable domain (desktop iframe + direct mobile browser play).
|
|
* Idempotent: running twice produces byte-identical output.
|
|
*/
|
|
export function prepareStaticPlayHtml(rawHtml: string | Buffer): {
|
|
html: Buffer;
|
|
injectedViewport: boolean;
|
|
injectedCocosGuard: boolean;
|
|
injectedTouchGuard: boolean;
|
|
} {
|
|
let html = Buffer.isBuffer(rawHtml) ? rawHtml.toString('utf8') : rawHtml;
|
|
let injectedViewport = false;
|
|
let injectedCocosGuard = false;
|
|
let injectedTouchGuard = false;
|
|
|
|
if (!/<meta\b[^>]*\bname=["']viewport["']/i.test(html)) {
|
|
html = insertAfterHeadOpen(html, MOBILE_VIEWPORT_META);
|
|
injectedViewport = true;
|
|
}
|
|
|
|
if (!html.includes('data-om-static-touch-guard') && !/overscroll-behavior\s*:/i.test(html)) {
|
|
if (/<\/head>/i.test(html)) {
|
|
html = html.replace(/<\/head>/i, `${MOBILE_TOUCH_STYLE}\n</head>`);
|
|
} else {
|
|
html = insertAfterHeadOpen(html, MOBILE_TOUCH_STYLE);
|
|
}
|
|
injectedTouchGuard = true;
|
|
}
|
|
|
|
if (!html.includes('data-om-cocos-chunk-guard')) {
|
|
const sysMatch = /<script\b[^>]*\bsrc=["'][^"']*system\.bundle\.js["'][^>]*>\s*<\/script>/i.exec(html);
|
|
if (sysMatch) {
|
|
const insertAt = sysMatch.index + sysMatch[0].length;
|
|
html = html.slice(0, insertAt) + '\n' + COCOS_CHUNK_GUARD_SCRIPT + html.slice(insertAt);
|
|
injectedCocosGuard = true;
|
|
}
|
|
}
|
|
|
|
return {
|
|
html: Buffer.from(html, 'utf8'),
|
|
injectedViewport,
|
|
injectedCocosGuard,
|
|
injectedTouchGuard,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Build Cloudflare Pages / static edge `_headers` rules enforcing cookieless
|
|
* static delivery while permitting desktop iframe embeds and mobile direct open.
|
|
*/
|
|
export function buildStaticPlayHeadersFile(): string {
|
|
return [
|
|
'# Independent cookieless static playable domain headers (OpenGame Stage 1)',
|
|
'/*',
|
|
' X-Content-Type-Options: nosniff',
|
|
' Referrer-Policy: no-referrer',
|
|
' Cross-Origin-Resource-Policy: cross-origin',
|
|
' Access-Control-Allow-Origin: *',
|
|
'',
|
|
'/games/*/index.html',
|
|
' Cache-Control: public, max-age=300, must-revalidate',
|
|
'',
|
|
'/manifest.json',
|
|
' Cache-Control: public, max-age=300, must-revalidate',
|
|
'',
|
|
].join('\n');
|
|
}
|
|
|
|
function extractInlineChunkKeys(html: string): Set<string> {
|
|
const keys = new Set<string>();
|
|
const mapMatches = html.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 of Object.keys(parsed)) keys.add(key.replace(/^\.\//, ''));
|
|
} catch {
|
|
// Ignore non-JSON object literals.
|
|
}
|
|
}
|
|
return keys;
|
|
}
|
|
|
|
/**
|
|
* Audit an unpacked game template file map for pure-static hosting readiness:
|
|
* valid entrypoint, valid `game.json`, zero LFS pointers, intact local assets,
|
|
* no broken root-absolute or internal API paths, no CSP/iframe blockers, and
|
|
* mobile viewport readiness.
|
|
*/
|
|
export function auditStaticGameFiles(
|
|
id: string,
|
|
files: ReadonlyMap<string, Buffer>,
|
|
options: { checkCover?: boolean; requireViewport?: boolean } = {},
|
|
): StaticGameAuditResult {
|
|
const errors: string[] = [];
|
|
const warnings: string[] = [];
|
|
const checkCover = options.checkCover ?? true;
|
|
const requireViewport = options.requireViewport ?? true;
|
|
|
|
if (!isValidGameTemplateId(id)) {
|
|
errors.push(`Invalid template id: ${id}`);
|
|
}
|
|
|
|
let totalBytes = 0;
|
|
for (const [relative, data] of files) {
|
|
totalBytes += data.length;
|
|
if (isLfsPointerBuffer(data)) {
|
|
errors.push(`Unhydrated Git LFS pointer file: ${relative}`);
|
|
}
|
|
}
|
|
|
|
const cardBuf = files.get('game.json');
|
|
let isTopEarning = false;
|
|
let orientation: 'portrait' | 'landscape' = 'landscape';
|
|
if (!cardBuf) {
|
|
errors.push('Missing game.json');
|
|
} else {
|
|
try {
|
|
const card = JSON.parse(cardBuf.toString('utf8')) as {
|
|
id?: unknown;
|
|
cover?: unknown;
|
|
tags?: unknown;
|
|
orientation?: unknown;
|
|
};
|
|
if (card.id !== id) errors.push(`game.json id mismatch: expected "${id}", got "${String(card.id)}"`);
|
|
if (isTopEarningGameTags(card.tags as readonly string[] | null | undefined)) isTopEarning = true;
|
|
if (card.orientation === 'portrait') orientation = 'portrait';
|
|
if (checkCover && typeof card.cover === 'string' && card.cover && !/^(?:https?:|data:|\/)/i.test(card.cover)) {
|
|
const coverKey = card.cover.replace(/^\.\//, '');
|
|
if (!files.has(coverKey)) errors.push(`Missing cover referenced by game.json: ${card.cover}`);
|
|
}
|
|
} catch (error) {
|
|
errors.push(`Malformed game.json: ${(error as Error).message}`);
|
|
}
|
|
}
|
|
|
|
const indexBuf = files.get('index.html');
|
|
let hasViewport = false;
|
|
let hasCocosSystemJs = false;
|
|
if (!indexBuf || indexBuf.length === 0) {
|
|
errors.push('Missing or empty index.html');
|
|
} else {
|
|
const html = indexBuf.toString('utf8');
|
|
const htmlNoComments = html.replace(/<!--[\s\S]*?-->/g, '');
|
|
hasViewport = /<meta\b[^>]*\bname=["']viewport["']/i.test(htmlNoComments);
|
|
hasCocosSystemJs = /<script\b[^>]*\bsrc=["'][^"']*system\.bundle\.js["']/i.test(htmlNoComments);
|
|
|
|
if (requireViewport && !hasViewport) {
|
|
errors.push('Missing <meta name="viewport"> for mobile compatibility');
|
|
}
|
|
|
|
const xfoMeta = /<meta\b[^>]*http-equiv=["']x-frame-options["'][^>]*>/i.exec(htmlNoComments);
|
|
if (xfoMeta) {
|
|
errors.push(`HTML contains X-Frame-Options meta blocker: ${xfoMeta[0]}`);
|
|
}
|
|
|
|
const cspMeta = /<meta\b[^>]*http-equiv=["']content-security-policy["'][^>]*content=["']([^"']+)["'][^>]*>/i.exec(htmlNoComments);
|
|
if (cspMeta && /frame-ancestors\s+['"]?(?:none|self)['"]?/i.test(cspMeta[1])) {
|
|
errors.push(`HTML CSP meta blocks iframe embedding: ${cspMeta[1]}`);
|
|
}
|
|
|
|
if (/\b(?:top|parent)\.location(?:\.href)?\s*=|\bwindow\.top\s*!==?\s*window\.self\b/i.test(htmlNoComments)) {
|
|
errors.push('HTML contains frame-busting script incompatible with desktop iframe play');
|
|
}
|
|
|
|
const internalApiMatches = [...htmlNoComments.matchAll(/\/(?:motion-api|api\/games|api\/assets)\/[^"'\s)]+/gi)].map(m => m[0]);
|
|
if (internalApiMatches.length) {
|
|
errors.push(`HTML references non-static internal API path(s): ${internalApiMatches.slice(0, 5).join(', ')}`);
|
|
}
|
|
|
|
// Check HTML <script src>, <link href>, <img src>, <audio src>, <source src> references.
|
|
const chunkKeys = extractInlineChunkKeys(htmlNoComments);
|
|
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) continue;
|
|
if (cleanRef.startsWith('/')) {
|
|
errors.push(`Broken root-absolute asset path in index.html: ${rawRef}`);
|
|
continue;
|
|
}
|
|
const normalized = cleanRef.replace(/^\.\//, '');
|
|
if (files.has(normalized) || chunkKeys.has(normalized)) continue;
|
|
errors.push(`Missing local asset referenced by index.html: ${rawRef}`);
|
|
}
|
|
|
|
const externalScripts = [...htmlNoComments.matchAll(/<script\b[^>]*\bsrc=["'](https?:\/\/[^"']+)["']/gi)].map(m => m[1]);
|
|
if (externalScripts.length) {
|
|
warnings.push(`External script dependency: ${externalScripts.join(', ')}`);
|
|
}
|
|
}
|
|
|
|
return {
|
|
id,
|
|
ok: errors.length === 0,
|
|
errors,
|
|
warnings,
|
|
stats: {
|
|
fileCount: files.size,
|
|
totalBytes,
|
|
hasViewport,
|
|
hasCocosSystemJs,
|
|
isTopEarning,
|
|
orientation,
|
|
},
|
|
};
|
|
}
|