A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(export): a web build lists the origins its game connects to
yhhaf3fe8b03343
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c9d15fe11..bbf7561ef 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A web build can say which servers its game connects to.** The exported page's Content-Security-Policy let a game talk only to the page it came from, so a game with a server of its own could not reach it: the browser refused the connection and said nothing the game could see. A project now lists the origins in `packaging.platforms.web.connect` (`wss://play.example.com`, `ws://127.0.0.1:*` for any port on a host, or a bare `wss:` for any secure WebSocket) and each becomes a `connect-src` source. An entry is checked rather than pasted in: a path, a wildcard host, a space, a semicolon or a quote fails the export and names the entry, so no entry can end the directive and start another. Web only; a mini-game's server addresses are the platform's own list.- **A session can be told to redial now, and says why its link ended.** `ClientSession.retryNow()` dials at once instead of waiting out the backoff, for a player who pressed "try again"; it does nothing when the session is ready, already dialling, or closed. `lastClose` is the WebSocket close code of the last link that ended (4003, `SessionCloseCode.unavailable`, is the server saying it is full or going away) until the next one is ready, and `attempts` counts dials since the session was last ready, so a screen can tell "reconnecting" from "the server is full" and say which attempt this is.- **A session layer for online games that do not share a tick.** `esengine/session` is the request and reply side of a game played asynchronously over a shared world. A `SessionHost` on the server authenticates each connection before it serves anything, limits frame size and message rate, pings the client, and lets a newer connection for the same player replace the older one. A `ClientSession` on the device dials, redials with backoff and jitter when the link drops, waits for the server before a request goes out, and keeps its event subscriptions across reconnects. Every request carries a key, so one that was lost on the way back and is sent again is answered from memory instead of running twice (a purchase, a departure); `serverNow()` gives the server's clock, corrected for the link's delay. `defineContract` writes every request and event once, with `s.object`, `s.int` and the other validators: the server checks each request against it, the client checks each reply, and both are typed from it; its `fingerprint` lets a server turn away a client built against another contract. `acceptWebSocket` hands a `ws` socket to a host, and `IdempotencyStore` is where a server with several processes keeps the answers in one place. `NetChannel` gained the keyed requests, a heartbeat, a rate limit, a frame size limit and `NetRequestError` (`timeout`, `closed`, `rate-limited`, `retry`, `remote`) for them. Replication is untouched.- **A random generator that gives the same numbers on every host.** `createRng(seed)` returns a seeded generator (`float`, `int`, `chance`, `pick`, `weighted`, `shuffle`) whose sequence is the same on a server, a browser, a mini-game and a phone, because it uses only 32-bit integer arithmetic. `fork(label)` makes a named stream that does not move when another stream draws more, and `hashSeed` turns a number, a string or a list of them into a seed. It is for rules that a server settles and a client previews, which must agree; `Math.random` cannot be seeded and is not the same anywhere.diff --git a/pipeline/src/export/cspConnect.ts b/pipeline/src/export/cspConnect.tsnew file mode 100644index 000000000..3bc13bf47--- /dev/null+++ b/pipeline/src/export/cspConnect.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cspConnect.ts — the addresses a web build may open connections to.+ *+ * The exported page's Content-Security-Policy lets a game talk only to the page it came from, which is+ * right for a game with no server and wrong for one that has. A project lists the origins its game connects+ * to (`packaging.platforms.web.connect`), and each becomes a `connect-src` source. The list is checked+ * rather than pasted in: an entry with a space, a semicolon or a quote could end the directive and start+ * another, so a policy is only ever made of what this accepts.+ */++const SCHEMES = new Set(['http:', 'https:', 'ws:', 'wss:']);++/**+ * One entry as a CSP source: a bare scheme (`wss:`, any secure WebSocket) or an origin+ * (`wss://play.example.com`, with an optional port, or `:*` for any). Anything else — a path, a query, a wildcard host, a+ * different scheme — throws, naming the entry.+ */+export function cspConnectSource(entry: string): string {+ let text = entry.trim();+ if (SCHEMES.has(text)) return text;+ // Any port on a host (a server whose port is not fixed, such as a test one): the one wildcard accepted.+ const anyPort = text.endsWith(':*');+ if (anyPort) text = text.slice(0, -2);+ let url: URL;+ try {+ url = new URL(text);+ } catch {+ throw new Error(`web.connect: "${entry}" is not an origin such as wss://play.example.com`);+ }+ if (!SCHEMES.has(url.protocol)) throw new Error(`web.connect: "${entry}" must start with http://, https://, ws:// or wss://`);+ if (url.hostname === '' || url.username !== '' || url.password !== '') throw new Error(`web.connect: "${entry}" must be a host, with no sign-in in it`);+ // An origin has nothing after the host and port. The URL parser adds a "/" to an empty path.+ if ((url.pathname !== '/' && url.pathname !== '') || url.search !== '' || url.hash !== '' || /[\s;,'"*]/.test(text)) {+ throw new Error(`web.connect: "${entry}" must be only an origin (scheme, host and optional port), with no path, wildcard or extra characters`);+ }+ if (anyPort && /:\d+$/.test(text)) throw new Error(`web.connect: "${entry}" names a port and also asks for any port`);+ return anyPort ? `${url.origin}:*` : url.origin;+}++/** The list as it goes into the policy: each entry checked, duplicates dropped, order kept. */+export function cspConnectSources(entries: readonly string[] | undefined): string[] {+ return [...new Set((entries ?? []).map(cspConnectSource))];+}diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex fdd0abcc9..c3f9e599a 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -65,6 +65,7 @@ import { buildCompiledSystems, type BuildMode } from '../bundle/buildCompiledSysimport { resolveEmcc, runEmcc } from '../bundle/emccPath';import { findHostCC } from '../../../compiler/src/hostCC';import { explainBundleErrors, type BundleMessage } from '../bundle/bundleDiagnostics';+import { cspConnectSources } from './cspConnect';import { orientationCss, orientationOverlayHtml, orientationLockScript, orientationLockCspHash, type ScreenOrientation } from './orientationHtml';import { PAGE_BACKGROUND, splashCss, splashHtml, type SplashLook } from './splash';import { emitIosXcodeProject, type IosProjectSources } from '../../../build-tools/utils/iosProject.js';@@ -339,11 +340,13 @@ function externalEngineImports(metafile: { outputs: Record<string, { imports?: {* for desktop (the Electron shell sizes its own window). */function indexHtml(title: string, map: EngineImportMap, look: SplashLook, orientation?: ScreenOrientation,- debugChannel?: DebugChannelConfig, webChannel?: 'poki' | 'crazygames' | 'youtube',+ debugChannel?: DebugChannelConfig, webChannel?: 'poki' | 'crazygames' | 'youtube', webConnect?: readonly string[],): string {// The editor a development build dials is the one address beyond 'self' the// page may connect to; a build without a channel lists none.- const connect = debugChannel ? ` ${new URL(debugChannel.url).origin}` : '';+ // Beside it, the origins the project says its game connects to (a server of its own).+ const connect = [...(debugChannel ? [new URL(debugChannel.url).origin] : []), ...cspConnectSources(webConnect)]+ .map((origin) => ` ${origin}`).join('');// Every inline script on this page needs its hash listed, or the browser blocks it.const inlineScripts = [map.cspHash, ...(orientation ? [orientationLockCspHash(orientation)] : [])].map((h) => `'${h}'`)@@ -481,6 +484,8 @@ export interface ExportGameOptions {scriptsEntry?: string;/** Browser distribution channel; standalone leaves the original Web policy intact. */webChannel?: 'poki' | 'crazygames' | 'youtube';+ /** Origins the web page's policy lets the game connect to (project: packaging.platforms.web.connect). */+ webConnect?: string[];leaderboardEncryptionKey?: string;sdkDistDir: string;/** The engine runtime to copy. */@@ -1186,7 +1191,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>splashBytes = Buffer.byteLength(splashCss(look.background ?? PAGE_BACKGROUND) + splashHtml(title, look));await writeFile(path.join(payloadDir, 'index.html'),- indexHtml(title, engineMap, look, platform === 'web' ? orientation : undefined, debugChannel, platform === 'web' ? opts.webChannel : undefined),+ indexHtml(title, engineMap, look, platform === 'web' ? orientation : undefined, debugChannel, platform === 'web' ? opts.webChannel : undefined, platform === 'web' ? opts.webConnect : undefined),);}// Typed against the SDK's contract, so a field the runtimes read can never bediff --git a/pipeline/src/export/projectExportOptions.ts b/pipeline/src/export/projectExportOptions.tsindex d19373173..b1a37d0a5 100644--- a/pipeline/src/export/projectExportOptions.ts+++ b/pipeline/src/export/projectExportOptions.ts@@ -108,6 +108,7 @@ export async function projectExportOptions(? { androidKey: () => androidReleaseKey(root, plat.android!.releaseKey!, secrets.androidKeyPassphrase) }: {}),...(platform === 'web' && (plat?.web?.channel === 'poki' || plat?.web?.channel === 'crazygames' || plat?.web?.channel === 'youtube') ? { webChannel: plat.web.channel } : {}),+ ...(platform === 'web' && plat?.web?.connect?.length ? { webConnect: plat.web.connect } : {}),...(platform === 'web' && plat?.web?.channel === 'crazygames' && plat.web.leaderboardEncryptionKey? { leaderboardEncryptionKey: plat.web.leaderboardEncryptionKey } : {}),desktopProductName: plat?.desktop?.productName,diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.tsindex d74d54582..ef6740a74 100644--- a/pipeline/src/project/format.ts+++ b/pipeline/src/project/format.ts@@ -23,6 +23,7 @@ import {type AudioProjectConfig, type QualityConfig,} from 'esengine';import { normalizePlatform, type ExportPlatform } from './platforms';+import { cspConnectSources } from '../export/cspConnect';export const PROJECT_FORMAT_VERSION = '1';export const PROJECT_MANIFEST_FILE = 'project.esproject';@@ -432,7 +433,13 @@ export interface ProjectPackaging {/** Per-platform packaging config: each target's slice of the app identity, plus* whatever only it has (a WeChat appid, an Android versionCode). */platforms?: {- web?: { channel?: 'standalone' | 'poki' | 'crazygames' | 'youtube'; leaderboardEncryptionKey?: string };+ web?: {+ channel?: 'standalone' | 'poki' | 'crazygames' | 'youtube';+ leaderboardEncryptionKey?: string;+ /** Origins the page may open connections to (a game server): `wss://play.example.com`, or a bare `wss:`.+ * The page's Content-Security-Policy allows only its own origin otherwise. */+ connect?: string[];+ };wechat?: WeChatPackaging;douyin?: MiniGamePackaging;bilibili?: MiniGamePackaging;@@ -979,6 +986,13 @@ export function parseManifest(raw: unknown): ProjectManifest {}config.leaderboardEncryptionKey = web.leaderboardEncryptionKey;}+ if (web.connect !== undefined) {+ if (!Array.isArray(web.connect) || !web.connect.every((o) => typeof o === 'string')) {+ throw new Error('packaging.platforms.web.connect must be a list of origins');+ }+ const connect = cspConnectSources(web.connect as string[]);+ if (connect.length) config.connect = connect;+ }if (Object.keys(config).length) platforms.web = config;}const wx = pl.wechat as Record<string, unknown> | undefined;diff --git a/pipeline/tests/csp-connect.test.ts b/pipeline/tests/csp-connect.test.tsnew file mode 100644index 000000000..59db829fd--- /dev/null+++ b/pipeline/tests/csp-connect.test.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { cspConnectSource, cspConnectSources } from '../src/export/cspConnect';++describe('web connect origins', () => {+ it('accepts origins and bare schemes, normalised', () => {+ expect(cspConnectSource('wss://play.example.com')).toBe('wss://play.example.com');+ expect(cspConnectSource(' wss://Play.Example.com:8443/ ')).toBe('wss://play.example.com:8443');+ expect(cspConnectSource('ws://127.0.0.1:8787')).toBe('ws://127.0.0.1:8787');+ expect(cspConnectSource('https://api.example.com')).toBe('https://api.example.com');+ expect(cspConnectSource('wss:')).toBe('wss:');+ expect(cspConnectSource('ws://127.0.0.1:*')).toBe('ws://127.0.0.1:*');+ });++ it('refuses anything that is not only an origin, so no entry can end the directive and start another', () => {+ for (const bad of [+ 'play.example.com', 'ftp://example.com', 'wss://', 'wss://user:[email protected]', 'wss://example.com/play',+ 'wss://example.com?x=1', 'wss://example.com#a', 'wss://*.example.com', "wss://example.com; script-src 'unsafe-inline'",+ 'wss://example.com wss://other.com', 'wss://example.com:8443:*', 'wss://*.example.com:*', 'wss://*', "wss://exa'mple.com", '',+ ]) expect(() => cspConnectSource(bad), JSON.stringify(bad)).toThrow(/web\.connect/);+ });++ it('keeps order, drops duplicates, and treats no list as nothing', () => {+ expect(cspConnectSources(['wss://a.example', 'ws://b.example:1', 'wss://a.example'])).toEqual(['wss://a.example', 'ws://b.example:1']);+ expect(cspConnectSources(undefined)).toEqual([]);+ expect(() => cspConnectSources(['wss://a.example', 'nope'])).toThrow(/nope/);+ });+});++describe('web connect in a project', () => {+ const manifest = (connect: unknown) => ({ formatVersion: '1', name: 'g', packaging: { platforms: { web: { connect } } } });++ it('is read from the project, normalised, and reaches the export options', async () => {+ const { parseManifest } = await import('../src/project/format');+ const { projectExportOptions } = await import('../src/export/projectExportOptions');+ const parsed = parseManifest(manifest(['wss://Play.Example.com/', 'ws://127.0.0.1:*', 'wss://play.example.com']));+ expect(parsed.packaging?.platforms?.web?.connect).toEqual(['wss://play.example.com', 'ws://127.0.0.1:*']);+ const web = await projectExportOptions('/tmp/game', parsed, 'web');+ expect(web.webConnect).toEqual(['wss://play.example.com', 'ws://127.0.0.1:*']);+ // Another target has no page, so no policy to list them in.+ expect((await projectExportOptions('/tmp/game', parsed, 'wechat')).webConnect).toBeUndefined();+ });++ it('refuses a list that is not one, or an entry that is not an origin, when the project is read', async () => {+ const { parseManifest } = await import('../src/project/format');+ expect(() => parseManifest(manifest('wss://play.example.com'))).toThrow(/list of origins/);+ expect(() => parseManifest(manifest([42]))).toThrow(/list of origins/);+ expect(() => parseManifest(manifest(['wss://play.example.com/path']))).toThrow(/web\.connect/);+ });++ it('an empty list says nothing', async () => {+ const { parseManifest } = await import('../src/project/format');+ expect(parseManifest(manifest([])).packaging?.platforms?.web).toBeUndefined();+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 7bd57e6c4..2247302d3 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3018,6 +3018,8 @@ export const NOTED = {{"note":"A session layer for online games that do not share a tick."},'feat(net): a session can be told to redial now and says why its link ended':{"note":"A session can be told to redial now, and says why its link ended."},+ 'feat(export): a web build lists the origins its game connects to':+ {"note":"A web build can say which servers its game connects to."},"perf(sdk): a blank mini-game package no longer carries terrain and water":{"note":"A blank mini-game package no longer carries terrain and water."},"perf(ecs): one stable sort for every component type, 239KB off the engine wasm":