Skip to content

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.

feat(openpaas): build and verify native SUD test packages

yhh0bcd0ccc16a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4b30dcd3a..2faa0ed32 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ published separately; it ships inside the editor.
- **SUD OpenPaaS development export.** An opt-in project platform preset exports a `main.js` directory for PinK's third-party builder. Its SDK profile bridges `sud`, package-file WASM loading, XHR, WebSocket and localStorage through the shared 2D/3D mini-game runtime. Headless checks exercise real exported 2D and 3D frames, including a WASM result without `module`; PinK packaging and Android/iOS acceptance remain pending. Login, ads, payment, WebGPU and EmscriptenGLX are not enabled by this initial integration.
The directory includes the initial `manifest.json` emitted by the official web2sp converter. That converter produces a SUD project directory, not a binary `.sp` file; final package generation remains separate from directory export.
+ `package-openpaas` now invokes PinK's official packer directly to generate encrypted, signed `.sp` files and verify all payload files before replacing the output. Real 2D/3D examples pass export → package → verify → decrypt → payload comparison → headless rendering with independent test keys; authorized Hello PinK and device acceptance remain pending. Uploading is user-managed.
- **Plugin filesystem operations.** Editor plugins can read and write binary assets directly, list directories, inspect files, create folders, rename and delete in their own directory or the capability-gated project scope. Moves preserve asset UUID sidecars, deletion uses the OS trash, and project edits join the existing file journal. User-installed plugins outside the project are supported; generated plugin data no longer repeatedly reloads its producer. Addresses [#99](https://github.com/esengine/estella/issues/99).
diff --git a/docs/astro/src/content/docs/publishing/minigame-platforms.mdx b/docs/astro/src/content/docs/publishing/minigame-platforms.mdx
index d93eaeff5..6a35fde3d 100644
--- a/docs/astro/src/content/docs/publishing/minigame-platforms.mdx
+++ b/docs/astro/src/content/docs/publishing/minigame-platforms.mdx
@@ -45,7 +45,8 @@ loader accepts an instance without a compiled `module`, as documented for iOS.
In **PinK → Project → Third-party generated**, choose the exported directory
containing `main.js`, `game-bundle.js` and `wasm/`. Select your platform game ID,
configure orientation and version to match the project, then build and upload.
-PinK produces the `.sp` package; Estella does not upload or submit it for review.
+PinK can produce the `.sp` package; Estella can also invoke its official packer
+directly using the CLI below. Users handle upload, review and publishing.
Open the development version in OpenPaaS and scan its package QR code with
**Hello PinK**. The supplied Unity and Laya guides use this same third-party
directory workflow; their engine-specific converters are not required here.
@@ -54,8 +55,48 @@ The official [web2sp 1.0.0 archive](https://download.sudden.ltd/assets/openpaas/
has been inspected and exercised. It detects Laya HTML, copies the Web directory,
emits `main.js` and `laya_adapter.js`, and creates an empty `manifest.json` when
none exists. It does not contain a binary `.sp` packer. Estella emits its own
-runtime entry and the same initial manifest directly. A final `.sp` still needs
-the platform packer; uploading, review and publishing remain user-managed.
+runtime entry and the same initial manifest directly. Final `.sp` generation uses
+the official packer bundled with PinK; uploading, review and publishing remain user-managed.
+
+### Generate a `.sp` through Estella
+
+PinK 0.0.1.39 bundles the independently callable `sud-package-sign-tool`.
+After installing or extracting the official PinK package, its Windows path is
+`resources/app/extensions/sud-pink-debug/tools/package-sign/win/sud-package-sign-tool.exe`;
+macOS uses `tools/package-sign/mac/sud-package-sign-tool` under that extension.
+Estella does not redistribute this third-party executable. Configure its local
+path without launching the PinK UI.
+
+Keep signing and encryption keys outside the exported directory. The Ed25519
+private key may use raw, hex, base64 or PKCS8 encoding; the AES-128 key file must
+contain 32 hex characters. Paths in this local JSON resolve relative to the config:
+
+```json
+{
+ "mode": "development",
+ "toolPath": "<PinK>/resources/app/extensions/sud-pink-debug/tools/package-sign/win/sud-package-sign-tool.exe",
+ "gameId": "estella-local-test",
+ "version": "0.1.0",
+ "privateKeyPath": "development-private.pem",
+ "encryptionKeyPath": "development-encryption.hex",
+ "orientation": "landscape"
+}
+```
+
+```sh
+node pipeline/bin/estella.mjs package-openpaas output/my-sud-game --config <local.json> --out output/my-sud-game.sp
+```
+
+Estella prepares the manifest in temporary staging, invokes the official tool
+for Deflate compression, AES-128-CTR encryption and Ed25519 signing, then verifies
+all package files. Only a verified result replaces the output; the source export
+remains untouched. Output and key files must be outside the input directory.
+
+`development` means independent test keys, **not an authorized OpenPaaS game or
+proof that Hello PinK accepts the package**. For an existing platform game, use
+`platform` mode with the registered `publicKeyHash`, `contextFile`,
+`contextSignatureFile` and `contextPublicKeyPath`. The context signature and
+public-key hash are checked before packaging. Platform acceptance stays pending.
<Aside type="caution">
**Development integration, device acceptance pending.** The headless contract
@@ -83,6 +124,17 @@ Run the reproducible local contract check without opening an editor:
node tools/tests/openpaas-runtime.e2e.mjs --wasm build/wasm/quickgame --out output/openpaas-runtime
```
+To check the complete package chain with real authored examples:
+
+```sh
+node tools/tests/openpaas-runtime.e2e.mjs --packer <official-tool-path> --project-2d examples/sprite-rendering --project-3d examples/device-quality --out output/openpaas-package-check
+```
+
+This generates temporary test keys, exports both examples, creates encrypted and
+signed `.sp` files, verifies and decrypts every file, compares payload hashes,
+then renders the recovered games in the headless contract host. Temporary keys
+are removed afterwards. Reports and frames do not constitute SUD device acceptance.
+
It writes 2D/3D frames and a report explicitly marking device acceptance pending.
Android Hello PinK exposes vConsole; the supplied guide also names device logs
under `/storage/emulated/0/Android/data/global.sud.hellopink/files/SUD/SUDLogs/SUDGI/`.
diff --git a/docs/astro/src/content/docs/zh-cn/publishing/minigame-platforms.mdx b/docs/astro/src/content/docs/zh-cn/publishing/minigame-platforms.mdx
index 53d1457e1..131574b55 100644
--- a/docs/astro/src/content/docs/zh-cn/publishing/minigame-platforms.mdx
+++ b/docs/astro/src/content/docs/zh-cn/publishing/minigame-platforms.mdx
@@ -38,14 +38,51 @@ iOS 仅返回 instance、没有编译后 module 的结果。
打开 **PinK → 项目 → 第三方生成**,选择导出的目录,其中包含 `main.js`、
`game-bundle.js` 和 `wasm/`。选择平台游戏 ID,按项目设置核对横竖屏和版本,
-然后构建、上传。`.sp` 由 PinK 生成,Estella 不会自动上传或提交审核。
+然后构建,再由用户自行上传。也可以使用下面的命令行流程,直接通过 Estella 生成 `.sp`。
在 OpenPaaS 的开发版本详情中,用 **Hello PinK** 扫描包链接二维码调试。
提供的 Unity / Laya 指南采用的也是这个第三方目录流程;这里不需要安装它们各自的转换插件。
已下载、检查并实际运行官方 [web2sp 1.0.0](https://download.sudden.ltd/assets/openpaas/guide/attachment/web2sp-1.0.0.tgz):
它识别 Laya HTML,复制 Web 目录,生成 `main.js`、`laya_adapter.js`,并在缺失时创建
内容为 `{}` 的 `manifest.json`。工具没有二进制 `.sp` 封装实现。Estella 直接生成自己的
-运行入口及相同的初始 manifest;最终 `.sp` 仍需平台封装工具,上传、审核和发布由用户处理。
+运行入口及相同的初始 manifest。最终封装使用 PinK 提供的官方工具,上传、审核和发布由用户处理。
+
+### 在 Estella 中生成 `.sp`
+
+已验证 PinK 0.0.1.39 内置的 `sud-package-sign-tool`,可通过命令行调用,无需启动 PinK 界面。
+从官方安装包安装或解包后,Windows 工具位于
+`resources/app/extensions/sud-pink-debug/tools/package-sign/win/sud-package-sign-tool.exe`;
+macOS 对应目录是 `tools/package-sign/mac/sud-package-sign-tool`。
+Estella 不分发该第三方二进制,需要在本地配置中指定它的路径。
+
+先在导出目录之外准备 Ed25519 私钥文件和 AES-128 加密密钥文件,再创建本地配置。
+私钥支持官方工具的 raw / hex / base64 / PKCS8 格式;加密密钥文件内容是 32 个十六进制字符。
+配置文件中的路径相对于配置文件解析:
+
+```json
+{
+ "mode": "development",
+ "toolPath": "<PinK目录>/resources/app/extensions/sud-pink-debug/tools/package-sign/win/sud-package-sign-tool.exe",
+ "gameId": "estella-local-test",
+ "version": "0.1.0",
+ "privateKeyPath": "development-private.pem",
+ "encryptionKeyPath": "development-encryption.hex",
+ "orientation": "landscape"
+}
+```
+
+```sh
+node pipeline/bin/estella.mjs package-openpaas output/my-sud-game --config <本地配置.json> --out output/my-sud-game.sp
+```
+
+这一步会在临时目录补齐游戏 manifest,调用官方工具进行 Deflate 压缩、AES-128-CTR 加密、
+Ed25519 签名,然后对全文件执行官方校验。成功后才替换目标 `.sp`,不修改原导出目录。
+输出不能放入输入目录,私钥与加密密钥也不能位于输入目录中。
+
+`development` 表示独立测试密钥,**不表示获得 OpenPaaS 游戏授权,也不保证 Hello PinK 接受该包**。
+已有平台配置时使用 `platform` 模式,并提供注册的 `publicKeyHash`、`contextFile`、
+`contextSignatureFile`、`contextPublicKeyPath`;Estella 会先验签上下文并检查公钥哈希。
+平台的上传、审核、发布及真机验收仍由用户执行。
<Aside type="caution">
**当前为开发接入,真机验收待完成。** 无窗口契约宿主已能加载真实引擎和导出的
@@ -67,6 +104,15 @@ iOS 仅返回 instance、没有编译后 module 的结果。
node tools/tests/openpaas-runtime.e2e.mjs --wasm build/wasm/quickgame --out output/openpaas-runtime
```
+还可以用官方工具验证完整链路;测试密钥临时生成并在结束后清理:
+
+```sh
+node tools/tests/openpaas-runtime.e2e.mjs --packer <官方打包工具路径> --project-2d examples/sprite-rendering --project-3d examples/device-quality --out output/openpaas-package-check
+```
+
+该检查会导出真实 2D / 3D 样例、生成加密签名 `.sp`、校验全部文件、解密还原,
+逐文件比较资源哈希,再在无窗口契约宿主中渲染还原后的项目。报告和截图不等于 SUD 真机验收。
+
结果包含 2D / 3D 截图及报告,并明确标记真机验收待完成。
提供的文档说明 Android Hello PinK 可以打开 vConsole,也可以通过设备日志目录
`/storage/emulated/0/Android/data/global.sud.hellopink/files/SUD/SUDLogs/SUDGI/` 排查启动失败;
diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjs
index f4ba36335..2c49c6a7d 100644
--- a/pipeline/bin/estella.mjs
+++ b/pipeline/bin/estella.mjs
@@ -18,6 +18,7 @@ const USAGE = `usage: node pipeline/bin/estella.mjs export <projectDir> [options
[--specular-map color|orm] [--lightmap-uv]
node pipeline/bin/estella.mjs import-hdr <file.hdr> [outDir] [--face-size <n>]
node pipeline/bin/estella.mjs bake-scene <scene.esscene> [--check]
+ node pipeline/bin/estella.mjs package-openpaas <exportDir> --config <local.json> --out <game.sp>
--platform <id> a built-in (web, desktop, wechat, douyin, kuaishou, bilibili, playable, android, ios)
or a platform the project defines in .esengine/platforms/ (default web)
@@ -86,6 +87,14 @@ function parseArgs(argv) {
}
return { command, source: path.resolve(projectDir), check: rest.includes('--check') };
}
+ if (command === 'package-openpaas') {
+ const config = rest.indexOf('--config'), out = rest.indexOf('--out');
+ if (!projectDir || config < 0 || !rest[config + 1] || out < 0 || !rest[out + 1]) {
+ console.error('package-openpaas requires an exported directory, --config <local.json> and --out <game.sp>');
+ process.exit(2);
+ }
+ return { command, source: path.resolve(projectDir), config: path.resolve(rest[config + 1]), out: path.resolve(rest[out + 1]) };
+ }
if (command === 'import-model' || command === 'import-gltf' || command === 'import-hdr') {
if (!projectDir) {
console.error(USAGE);
@@ -678,6 +687,18 @@ function engineRuntimeDir(platform) {
const opts = parseArgs(process.argv.slice(2));
+if (opts.command === 'package-openpaas') {
+ const { mod, cleanup } = await loadPipeline(path.join(PIPELINE, 'src/export/openpaasPackage.ts'), 'openpaasPackage.mjs');
+ try {
+ console.log(JSON.stringify(await mod.packageOpenPaaS(opts.source, opts.out, opts.config), null, 2));
+ } catch (error) {
+ console.error(error.message);
+ process.exitCode = 1;
+ } finally { cleanup(); }
+ // No export, login or upload follows packaging.
+ process.exit(process.exitCode ?? 0);
+}
+
// `import-gltf` is the name this command shipped under; it reads any of the
// model sources now, and the old spelling keeps working.
if (opts.command === 'import-model' || opts.command === 'import-gltf') {
diff --git a/pipeline/src/export/miniGameExportProfile.ts b/pipeline/src/export/miniGameExportProfile.ts
index c6367d2a2..d4aa2499c 100644
--- a/pipeline/src/export/miniGameExportProfile.ts
+++ b/pipeline/src/export/miniGameExportProfile.ts
@@ -116,9 +116,8 @@ export interface MiniGameEntryContext {
/**
* The generated mini-game entry: require the engine glue + each side module,
- * then boot the bundle. Pure CommonJS with no vendor API in it — every host
- * loads JS the same way — so this is the family default, and a profile only
- * overrides it for an unusual loader.
+ * then boot the bundle. CommonJS is the family default; profiles with a
+ * global-script loader provide an explicit export bridge.
*/
export function defaultMiniGameEntry(ctx: MiniGameEntryContext, load = 'require'): string {
const requires = ctx.sideModules
@@ -175,6 +174,36 @@ if (__task && __task.onProgressUpdate) {
__say('Fetching the engine ' + Math.round(p.progress || 0) + '%');
});
}
+
+`;
+}
+
+/** For script loaders that execute JS but do not promise CommonJS return
+ * values. SUD's client-api/require.html resolves paths from the game entry.
+ * All emitted requires are package-root paths; exports are captured explicitly.
+ * A genuine CommonJS loader can still return its own module exports.
+ */
+export function scriptMiniGameEntry(ctx: MiniGameEntryContext): string {
+ return `(function () {
+const __load = function (file) {
+ const hadModule = Object.prototype.hasOwnProperty.call(globalThis, 'module');
+ const hadExports = Object.prototype.hasOwnProperty.call(globalThis, 'exports');
+ const previousModule = globalThis.module;
+ const previousExports = globalThis.exports;
+ const initial = {};
+ const current = { exports: initial };
+ globalThis.module = current;
+ globalThis.exports = initial;
+ try {
+ const returned = require(file);
+ return current.exports !== initial || Object.keys(initial).length ? current.exports : returned;
+ } finally {
+ if (hadModule) globalThis.module = previousModule; else delete globalThis.module;
+ if (hadExports) globalThis.exports = previousExports; else delete globalThis.exports;
+ }
+};
+${defaultMiniGameEntry(ctx, '__load')}
+})();
`;
}
@@ -291,8 +320,8 @@ export interface MiniGameExportProfile {
}
/** SUD's third-party-generated directory, consumed by PinK to build the .sp.
- * Account, game ID, version and orientation are configured in PinK, not in a
- * fabricated WeChat project.config.json. No upload or review is performed here.
+ * Game ID, version and orientation are configured at package time through
+ * PinK or package-openpaas. No upload or review is performed here.
*/
export const openpaasExportProfile: MiniGameExportProfile = {
id: 'openpaas',
@@ -301,12 +330,21 @@ export const openpaasExportProfile: MiniGameExportProfile = {
runtimeInit: 'initMiniGameRuntime',
runtimeProfileHost: 'openpaasPlatformProfile',
engineGlueCandidates: MINIGAME_ENGINE_GLUE,
+ // Assumed conservative syntax floor, not a certified SUD engine version:
+ // guide/runtime/js-supports.html requires cross-runtime down-leveling.
+ // A wrong floor fails compilation on the device; device acceptance is pending.
esTarget: 'es2016',
wasmBuildHint: 'quickgame',
hostGlobal: 'sud',
sideModuleBuildTargets: {},
+ // Official web2sp emits JS + JSON. No include-suffix config is documented;
+ // this set only classifies generated scripts/config for the shared cook.
nativeSuffixes: new Set(['.js', '.json']),
+ // No published upload whitelist: preserve staged filenames. The official
+ // packer takes a directory; platform upload acceptance remains unverified.
packerSuffixes: null,
+ // The documented instantiateFromFile path names .wasm, not .wasm.br.
+ // Brotli loading is not claimed until the native loader is verified.
wasmBrotli: false,
// A plain third-party directory carries assets in its main package. PinK's
// subpackage manifest format has not been supplied, so do not invent one.
@@ -320,12 +358,13 @@ export const openpaasExportProfile: MiniGameExportProfile = {
return [{ file: 'manifest.json', content: '{}\n' }, { file: 'OPENPAAS.txt', content:
`Estella / SUD OpenPaaS development package\n`
+ `Project: ${ctx.title}\nOrientation: ${ctx.orientation}\n`
- + 'In PinK select Project > Third-party generated and choose this directory.\n'
+ + 'CLI: estella.mjs package-openpaas <directory> --config <local.json> --out <game.sp>.\n'
+ + 'Or in PinK select Project > Third-party generated and choose this directory.\n'
+ 'Select your platform game ID and configure orientation and version in PinK.\n'
+ 'Build and upload, then scan the development version QR code using Hello PinK.\n'
+ 'Android and iOS device acceptance is pending; export success is not platform acceptance.\n' }];
},
- emitEntry: defaultMiniGameEntry,
+ emitEntry: scriptMiniGameEntry,
};
// =============================================================================
diff --git a/pipeline/src/export/openpaasPackage.ts b/pipeline/src/export/openpaasPackage.ts
new file mode 100644
index 000000000..3193f8ec3
--- /dev/null
+++ b/pipeline/src/export/openpaasPackage.ts
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { execFile } from 'node:child_process';
+import { createHash, createPrivateKey, createPublicKey, type KeyObject } from 'node:crypto';
+import { cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { containsPath as inside } from '../fs/pathSandbox';
+
+/** Paths are relative to the config file. Secrets are files, never CLI literals. */
+export interface OpenPaaSPackageConfig {
+ mode: 'development' | 'platform';
+ toolPath: string;
+ gameId: string;
+ version: string;
+ privateKeyPath: string;
+ encryptionKeyPath: string;
+ publicKeyHash?: string;
+ orientation?: 'portrait' | 'landscape';
+ contextFile?: string;
+ contextSignatureFile?: string;
+ contextPublicKeyPath?: string;
+}
+
+export interface OpenPaaSPackageResult {
+ file: string;
+ bytes: number;
+ sha256: string;
+ mode: 'development' | 'platform';
+ signatureAndFilesVerified: true;
+ platformAcceptance: 'pending';
+ toolSha256: string;
+}
+
+const digest = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
+function hashHex(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ if (/^[a-f\d]{64}$/i.test(value)) return value.toLowerCase();
+ const bytes = Buffer.from(value, 'base64');
+ return bytes.length === 32 ? bytes.toString('hex') : null;
+}
+const object = (value: unknown): value is Record<string, unknown> =>
+ value !== null && typeof value === 'object' && !Array.isArray(value);
+
+/** Do not copy links out of the export, or accidentally embed private keys. */
+async function validateTree(dir: string): Promise<void> {
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ const file = path.join(dir, entry.name);
+ const info = await lstat(file);
+ if (info.isSymbolicLink()) throw new Error(`OpenPaaS package input contains a symbolic link: ${entry.name}`);
+ if (info.isDirectory()) await validateTree(file);
+ else if (!info.isFile()) throw new Error(`OpenPaaS package input contains a special file: ${entry.name}`);
+ }
+}
+
+/** execFile keeps shell metacharacters out of command interpretation. Never
+ * expose its Error.message: Node includes the encryption key in that message. */
+function run(tool: string, args: string[], secrets: readonly string[]): Promise<string> {
+ const redact = (text: string): string => secrets.reduce((s, secret) => secret ? s.split(secret).join('[redacted]') : s, text);
+ return new Promise((resolve, reject) => execFile(tool, args,
+ { encoding: 'utf8', windowsHide: true, timeout: 120_000, maxBuffer: 10 * 1024 * 1024 },
+ (error, stdout, stderr) => {
+ if (error) reject(new Error(`SUD packer failed (${error.code ?? 'process error'}): ${redact(stderr || stdout).slice(0, 4000)}`));
+ else resolve(redact(stdout));
+ }));
+}
+
+/** Generate a .sp with PinK's official tool, then verify every file before
+ * replacing the destination. Input exports remain untouched. No network calls,
+ * login, upload, review or publishing happen in this operation.
+ */
+export async function packageOpenPaaS(
+ sourceDir: string, outputFile: string, configFile: string,
+): Promise<OpenPaaSPackageResult> {
+ const configPath = await realpath(configFile);
+ let parsed: unknown;
+ try { parsed = JSON.parse(await readFile(configPath, 'utf8')); }
+ catch { throw new Error('OpenPaaS package config must be valid JSON'); }
+ if (!object(parsed)) throw new Error('OpenPaaS package config must be an object');
+ for (const key of ['toolPath', 'gameId', 'version', 'privateKeyPath', 'encryptionKeyPath']) {
+ if (typeof parsed[key] !== 'string' || !(parsed[key] as string).trim()) {
+ throw new Error(`OpenPaaS package config requires ${key}`);
+ }
+ }
+ if (parsed.mode !== 'development' && parsed.mode !== 'platform') {
+ throw new Error('OpenPaaS package config requires explicit development or platform mode');
+ }
+ if (parsed.orientation !== undefined && !['portrait', 'landscape'].includes(String(parsed.orientation))) {
+ throw new Error('OpenPaaS orientation must be portrait or landscape');
+ }
+ const config = parsed as unknown as OpenPaaSPackageConfig;
+ const resolve = (p: string): string => path.resolve(path.dirname(configPath), p);
+ const source = await realpath(sourceDir);
+ if (!(await stat(source)).isDirectory()) throw new Error('OpenPaaS input must be an exported directory');
+ const output = path.resolve(outputFile);
+ if (!output.endsWith('.sp')) throw new Error('OpenPaaS output must end in .sp');
+ await mkdir(path.dirname(output), { recursive: true });
+ const outputParent = await realpath(path.dirname(output));
+ const destination = path.join(outputParent, path.basename(output));
+ if (inside(source, destination)) throw new Error('OpenPaaS output must be outside the input directory');
+
+ const keyFile = await realpath(resolve(config.privateKeyPath));
+ const encryptionFile = await realpath(resolve(config.encryptionKeyPath));
+ if (inside(source, keyFile) || inside(source, encryptionFile)) {
+ throw new Error('OpenPaaS signing and encryption keys must be outside the package input');
+ }
+ const keyBytes = await readFile(keyFile);
+ // Parse keys before executing a binary; malformed key errors must not echo contents.
+ let privateKey: KeyObject;
+ try {
+ const text = keyBytes.toString('utf8').trim();
+ if (text.startsWith('-----BEGIN')) privateKey = createPrivateKey(keyBytes);
+ else {
+ const seed = keyBytes.length === 32 ? keyBytes
+ : /^[a-f\d]{64}$/i.test(text) ? Buffer.from(text, 'hex') : Buffer.from(text, 'base64');
+ privateKey = seed.length === 32
+ ? createPrivateKey({ key: Buffer.concat([Buffer.from('302e020100300506032b657004220420', 'hex'), seed]), type: 'pkcs8', format: 'der' })
+ : createPrivateKey({ key: keyBytes, type: 'pkcs8', format: 'der' });
+ }
+ } catch { throw new Error('OpenPaaS privateKeyPath must contain a valid Ed25519 private key'); }
+ if (privateKey.asymmetricKeyType !== 'ed25519') throw new Error('OpenPaaS requires an Ed25519 private key');
+ const publicKey = createPublicKey(privateKey).export({ type: 'spki', format: 'der' });
+ const publicRaw = publicKey.subarray(-32);
+ const publicHash = digest(publicRaw);
+ if (config.publicKeyHash !== undefined && hashHex(config.publicKeyHash) !== publicHash) {
+ throw new Error('OpenPaaS publicKeyHash does not match the signing key');
+ }
+ const encryptionKey = (await readFile(encryptionFile, 'utf8')).trim();
+ if (!/^[a-f\d]{32}$/i.test(encryptionKey)) throw new Error('OpenPaaS encryption key must be 16 bytes encoded as 32 hex characters');
+ const secrets = [encryptionKey, keyBytes.toString('utf8').trim()];
+ const tool = await realpath(resolve(config.toolPath));
+ if (!(await stat(tool)).isFile()) throw new Error('OpenPaaS toolPath must name the official package executable');
+
+ await validateTree(source);
+ await stat(path.join(source, 'main.js'));
+ const original: unknown = JSON.parse(await readFile(path.join(source, 'manifest.json'), 'utf8'));
+ if (!object(original)) throw new Error('OpenPaaS manifest must be an object');
+ let context: Record<string, unknown> | undefined;
+ let contextSignature: string | undefined;
+ if (config.mode === 'platform') {
+ if (!config.contextFile || !config.contextSignatureFile || !config.contextPublicKeyPath || !config.publicKeyHash) {
+ throw new Error('Platform packaging requires the OpenPaaS signed context, signature, public key and registered publicKeyHash');
+ }
+ const contextText = (await readFile(resolve(config.contextFile), 'utf8')).trim();
+ const value: unknown = JSON.parse(contextText);
+ if (!object(value) || !object(value.game_info) || hashHex(value.game_info.public_key_hash) !== publicHash) {
+ throw new Error('OpenPaaS context does not name this signing public key');
+ }
+ context = value;
+ contextSignature = (await readFile(resolve(config.contextSignatureFile), 'utf8')).trim();
+ const verified = await run(tool, ['--verify-payload', contextText, '--verify-signature', contextSignature,
+ '--verify-public-key', resolve(config.contextPublicKeyPath)], secrets);
+ // A non-zero status is rejected by run; the official tool owns payload validation.
+ if (!verified.trim()) throw new Error('SUD packer returned no context verification result');
+ }
+
+ const temporaryRoot = await realpath(tmpdir());
+ const temporary = await mkdtemp(path.join(temporaryRoot, 'estella-openpaas-'));
+ const staged = path.join(temporary, 'input');
+ const packageDir = await mkdtemp(path.join(outputParent, '.estella-sud-'));
+ const pending = path.join(packageDir, 'package.sp');
+ try {
+ await cp(source, staged, { recursive: true });
+ const manifest = { ...original,
+ gameId: config.gameId, version: config.version,
+ deviceOrientation: config.orientation ?? original.deviceOrientation ?? 'landscape',
+ minRuntimeVersion: original.minRuntimeVersion ?? '2.0.0',
+ permissions: original.permissions ?? [], networkTimeout: original.networkTimeout ?? {},
+ workers: original.workers ?? '',
+ ...(context ? { context, context_signature: contextSignature } : {}),
+ };
+ // Never leave a stale platform context attached to a local-development build.
+ delete (manifest as Record<string, unknown>).keyPath;
+ if (config.mode === 'development') {
+ delete (manifest as Record<string, unknown>).context;
+ delete (manifest as Record<string, unknown>).context_signature;
+ }
+ await writeFile(path.join(staged, 'manifest.json'), JSON.stringify(manifest, null, 2));
+ await run(tool, ['--input', staged, '--output', pending, '--type', '1', '--compress', 'deflate',
+ '--encrypt', '--global-key', encryptionKey, '--private-key', keyFile, '--public-key-hash', publicHash], secrets);
+ const verification = await run(tool, ['--verify', pending, '--verify-all', '--global-key', encryptionKey,
+ '--verify-public-key', publicRaw.toString('hex')], secrets);
+ if (!/^verify_ok:\s*true\s*$/m.test(verification)) throw new Error('SUD packer did not confirm package verification');
+ const bytes = await readFile(pending);
+ const result: OpenPaaSPackageResult = { file: destination, bytes: bytes.length, sha256: digest(bytes),
+ mode: config.mode, signatureAndFilesVerified: true, platformAcceptance: 'pending',
+ toolSha256: digest(await readFile(tool)) };
+ await rename(pending, destination);
+ return result;
+ } finally {
+ // Verify resolved deletion targets remain direct children of their intended parents.
+ if (path.dirname(path.resolve(temporary)) !== temporaryRoot
+ || path.dirname(path.resolve(packageDir)) !== outputParent
+ || !path.basename(temporary).startsWith('estella-openpaas-')
+ || !path.basename(packageDir).startsWith('.estella-sud-')) {
+ throw new Error('Unexpected OpenPaaS temporary cleanup path');
+ }
+ await rm(temporary, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ await rm(packageDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ }
+}
diff --git a/pipeline/src/index.ts b/pipeline/src/index.ts
index 679e4f819..7b5361ed7 100644
--- a/pipeline/src/index.ts
+++ b/pipeline/src/index.ts
@@ -35,6 +35,7 @@ export * from './export/exportProgress';
export * from './export/platformCatalog';
export * from './export/projectModules';
export * from './export/miniGameExportProfile';
+export * from './export/openpaasPackage';
export * from './export/playableAdProfile';
export * from './export/orientationHtml';
export * from './export/nativeTemplates';
diff --git a/pipeline/tests/export-openpaas.test.ts b/pipeline/tests/export-openpaas.test.ts
index 91ac46207..7d561ff6a 100644
--- a/pipeline/tests/export-openpaas.test.ts
+++ b/pipeline/tests/export-openpaas.test.ts
@@ -54,8 +54,9 @@ describe('OpenPaaS third-party directory export', () => {
expect(result.errors).toEqual([]); expect(result.ok).toBe(true);
expect(result.platform).toBe('openpaas');
const entry = readFileSync(path.join(out, 'main.js'), 'utf8');
- expect(entry).toContain("require('./wasm/esengine.wxgame.js')");
- expect(entry).toContain("require('./game-bundle.js')");
+ expect(entry).toContain("__load('./wasm/esengine.wxgame.js')");
+ expect(entry).toContain("__load('./game-bundle.js')");
+ expect(entry).toContain('globalThis.module = current');
expect(entry).not.toContain('loadSubpackage');
expect(existsSync(path.join(out, 'game.js'))).toBe(false);
expect(existsSync(path.join(out, 'project.config.json'))).toBe(false);
diff --git a/pipeline/tests/openpaas-package.test.ts b/pipeline/tests/openpaas-package.test.ts
new file mode 100644
index 000000000..c113b8043
--- /dev/null
+++ b/pipeline/tests/openpaas-package.test.ts
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
+import { createHash, generateKeyPairSync, randomBytes, sign, type KeyObject } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { packageOpenPaaS, type OpenPaaSPackageConfig } from '../src/export/openpaasPackage';
+
+let root: string, source: string, configFile: string, out: string;
+let config: OpenPaaSPackageConfig;
+let pair: { privateKey: KeyObject; publicKey: KeyObject };
+beforeEach(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'sud-package-test-'));
+ source = path.join(root, 'input'); configFile = path.join(root, 'local.json'); out = path.join(root, 'game.sp');
+ await mkdir(source);
+ await writeFile(path.join(source, 'main.js'), 'console.log("test");');
+ await writeFile(path.join(source, 'manifest.json'), '{"context":{"stale":true},"context_signature":"stale"}');
+ pair = generateKeyPairSync('ed25519');
+ await writeFile(path.join(root, 'private.pem'), pair.privateKey.export({ format: 'pem', type: 'pkcs8' }));
+ await writeFile(path.join(root, 'encryption.hex'), randomBytes(16).toString('hex'));
+ config = { mode: 'development', gameId: 'estella-local-test', version: '0.1.0',
+ toolPath: process.env.ESTELLA_SUD_PACKER ?? process.execPath,
+ privateKeyPath: 'private.pem', encryptionKeyPath: 'encryption.hex' };
+ await save();
+});
+async function save() { await writeFile(configFile, JSON.stringify(config)); }
+afterEach(async () => {
+ const parent = await import('node:fs/promises').then(fs => fs.realpath(tmpdir()));
+ const target = path.resolve(root);
+ if (path.dirname(target) !== parent || !path.basename(target).startsWith('sud-package-test-')) throw Error('Unexpected cleanup root');
+ await rm(target, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+});
+
+describe('OpenPaaS package boundary', () => {
+ it('rejects output inside its input and never overwrites runtime files', async () => {
+ await expect(packageOpenPaaS(source, path.join(source, 'game.sp'), configFile)).rejects.toThrow('outside the input');
+ expect(await readFile(path.join(source, 'main.js'), 'utf8')).toBe('console.log("test");');
+ });
+ it('refuses to embed signing secrets stored inside the package source', async () => {
+ await writeFile(path.join(source, 'secret.hex'), randomBytes(16).toString('hex'));
+ config.encryptionKeyPath = 'input/secret.hex'; await save();
+ await expect(packageOpenPaaS(source, out, configFile)).rejects.toThrow('keys must be outside');
+ });
+ it('checks the registered public key hash before running the packer', async () => {
+ config.publicKeyHash = '0'.repeat(64); await save();
+ await expect(packageOpenPaaS(source, out, configFile)).rejects.toThrow('does not match');
+ });
+ it('requires a platform-signed context for platform mode', async () => {
+ config.mode = 'platform'; await save();
+ await expect(packageOpenPaaS(source, out, configFile)).rejects.toThrow('signed context');
+ });
+ it('does not echo an invalid encryption secret', async () => {
+ await writeFile(path.join(root, 'encryption.hex'), 'SECRET-IN-INVALID-KEY');
+ const error = await packageOpenPaaS(source, out, configFile).catch(e => e);
+ expect(String(error)).toContain('16 bytes'); expect(String(error)).not.toContain('SECRET-IN-INVALID-KEY');
+ });
+});
+
+// Optional because PinK supplies Windows/macOS tools, not the Linux CI host.
+// The actual executable must be explicitly provided; these are not host mocks.
+describe.runIf(Boolean(process.env.ESTELLA_SUD_PACKER))('official SUD executable', () => {
+ it('creates, signs and verifies all files without modifying the source', async () => {
+ const before = await readFile(path.join(source, 'manifest.json'), 'utf8');
+ const result = await packageOpenPaaS(source, out, configFile);
+ expect(result).toMatchObject({ mode: 'development', signatureAndFilesVerified: true, platformAcceptance: 'pending' });
+ expect(result.bytes).toBe((await stat(out)).size);
+ expect(result.sha256).toBe(createHash('sha256').update(await readFile(out)).digest('hex'));
+ expect(await readFile(path.join(source, 'manifest.json'), 'utf8')).toBe(before);
+ });
+ it('supports the raw hex private key format used by the official key generator', async () => {
+ const der = pair.privateKey.export({ format: 'der', type: 'pkcs8' });
+ await writeFile(path.join(root, 'private.hex'), der.subarray(-32).toString('hex'));
+ config.privateKeyPath = 'private.hex'; await save();
+ expect((await packageOpenPaaS(source, out, configFile)).signatureAndFilesVerified).toBe(true);
+ });
+ it('verifies context signatures and rejects corrupt contexts without replacing an existing package', async () => {
+ const publicRaw = pair.publicKey.export({ format: 'der', type: 'spki' }).subarray(-32);
+ config.publicKeyHash = createHash('sha256').update(publicRaw).digest('hex');
+ const context = JSON.stringify({ game_info: { public_key_hash: config.publicKeyHash } });
+ await writeFile(path.join(root, 'context.json'), context);
+ await writeFile(path.join(root, 'context.sig'), sign(null, Buffer.from(context), pair.privateKey).toString('base64'));
+ await writeFile(path.join(root, 'context-public.hex'), publicRaw.toString('hex'));
+ Object.assign(config, { mode: 'platform', contextFile: 'context.json', contextSignatureFile: 'context.sig', contextPublicKeyPath: 'context-public.hex' });
+ await save();
+ const result = await packageOpenPaaS(source, out, configFile);
+ expect(result.platformAcceptance).toBe('pending');
+ const before = await readFile(out);
+ await writeFile(path.join(root, 'context.sig'), Buffer.alloc(64).toString('base64'));
+ await expect(packageOpenPaaS(source, out, configFile)).rejects.toThrow('SUD packer failed');
+ expect(await readFile(out)).toEqual(before);
+ });
+});
diff --git a/sdk/package.json b/sdk/package.json
index 61991986c..8a6f8937b 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -29,6 +29,7 @@
"./dist/quickgame/index.js",
"./dist/alipay/index.js",
"./dist/huawei/index.js",
+ "./dist/openpaas/index.js",
"./dist/index.wechat.cjs.js"
],
"main": "./dist/index.js",
diff --git a/tools/tests/openpaas-runtime.e2e.mjs b/tools/tests/openpaas-runtime.e2e.mjs
index 3a33810bb..9b5b02ad1 100644
--- a/tools/tests/openpaas-runtime.e2e.mjs
+++ b/tools/tests/openpaas-runtime.e2e.mjs
@@ -10,6 +10,7 @@ import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
import { chromium } from 'playwright';
import { HOST_PAGE } from '../launchers/minigameHost.mjs';
import { runTool } from '../lib/runTool.mjs';
@@ -19,15 +20,29 @@ const args = process.argv.slice(2);
const flag = (key, fallback) => args.includes(key) ? args[args.indexOf(key) + 1] : fallback;
const wasm = path.resolve(flag('--wasm', 'build/wasm/quickgame'));
const out = path.resolve(flag('--out', 'output/openpaas-runtime'));
+const packer = flag('--packer', null);
await fs.mkdir(out, { recursive: true });
const project = await fs.mkdtemp(path.join(out, 'fixture-'));
-const report = { status: 'failed', mode: 'headless-contract-host', deviceAcceptance: 'pending', scenes: [], errors: [] };
+const report = { status: 'failed', mode: 'headless-contract-host', deviceAcceptance: 'pending', scenes: [], packages: [], errors: [] };
const sha = data => crypto.createHash('sha256').update(data).digest('hex');
const { PNG } = createRequire(new URL('../../pipeline/package.json', import.meta.url))('pngjs');
const entity = (id, name, components) => ({ id, name, parent: null, children: [], visible: true, components });
const component = (type, data) => ({ type, data });
let browser;
+let secretDir;
try {
+ let packageConfig;
+ let encryptionKey;
+ if (packer) {
+ secretDir = await fs.mkdtemp(path.join(await fs.realpath(tmpdir()), 'estella-sud-test-keys-'));
+ const pair = crypto.generateKeyPairSync('ed25519');
+ await fs.writeFile(path.join(secretDir, 'private.pem'), pair.privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
+ encryptionKey = crypto.randomBytes(16).toString('hex');
+ await fs.writeFile(path.join(secretDir, 'encryption.hex'), encryptionKey, { mode: 0o600 });
+ packageConfig = path.join(secretDir, 'package.json');
+ await fs.writeFile(packageConfig, JSON.stringify({ mode: 'development', toolPath: path.resolve(packer),
+ gameId: 'estella-local-test', version: '0.1.0', privateKeyPath: 'private.pem', encryptionKeyPath: 'encryption.hex' }));
+ }
await fs.mkdir(path.join(project, 'assets/scenes'), { recursive: true });
await fs.mkdir(path.join(project, '.esengine/platforms'), { recursive: true });
await fs.copyFile(path.join(repo, 'pipeline/platforms/openpaas.mjs'), path.join(project, '.esengine/platforms/openpaas.mjs'));
@@ -54,11 +69,47 @@ try {
}
browser = await chromium.launch({ headless: true, args: ['--enable-unsafe-swiftshader', '--use-angle=swiftshader', '--mute-audio'] });
for (const dimension of ['2d', '3d']) {
+ const authoredProject = flag(`--project-${dimension}`, null);
+ let exportProject = project;
+ let sceneArgs = ['--scene', `assets/scenes/${dimension}.esscene`];
+ if (authoredProject) {
+ const original = path.resolve(authoredProject);
+ exportProject = path.join(project, `authored-${dimension}`);
+ await fs.cp(original, exportProject, { recursive: true,
+ filter: file => !path.relative(original, file).split(path.sep).some(part => ['node_modules', '.esengine', 'dist'].includes(part)) });
+ await fs.mkdir(path.join(exportProject, '.esengine/platforms'), { recursive: true });
+ await fs.copyFile(path.join(repo, 'pipeline/platforms/openpaas.mjs'), path.join(exportProject, '.esengine/platforms/openpaas.mjs'));
+ sceneArgs = [];
+ }
const dir = path.join(out, dimension);
- const exported = runTool(process.execPath, [path.join(repo, 'pipeline/bin/estella.mjs'), 'export', project,
- '--platform', 'openpaas', '--wasm', wasm, '--scene', `assets/scenes/${dimension}.esscene`,
+ const exported = runTool(process.execPath, [path.join(repo, 'pipeline/bin/estella.mjs'), 'export', exportProject,
+ '--platform', 'openpaas', '--wasm', wasm, ...sceneArgs,
'--out', dir, '--json', dir + '.json'], { cwd: repo, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
assert.equal(exported.status, 0, `${dimension} export failed: ${exported.stderr ?? exported.stdout}`);
+ let servedDir = dir;
+ if (packageConfig) {
+ const file = path.join(out, dimension + '.sp');
+ const packaged = runTool(process.execPath, [path.join(repo, 'pipeline/bin/estella.mjs'), 'package-openpaas', dir,
+ '--config', packageConfig, '--out', file], { cwd: repo, encoding: 'utf8' });
+ assert.equal(packaged.status, 0, `${dimension} package creation failed: ${packaged.stderr}`);
+ const result = JSON.parse(packaged.stdout);
+ assert.equal(result.signatureAndFilesVerified, true);
+ servedDir = path.join(out, dimension + '-unpacked');
+ const decrypted = runTool(path.resolve(packer), ['--decrypt', file, '--decrypt-all', '--global-key', encryptionKey,
+ '--decrypt-output-dir', servedDir], { cwd: repo, encoding: 'utf8' });
+ assert.equal(decrypted.status, 0, `${dimension} official package decryption failed`);
+ const files = async root => {
+ const walk = async (under = '') => (await Promise.all((await fs.readdir(path.join(root, under), { withFileTypes: true }))
+ .map(entry => entry.isDirectory() ? walk(path.join(under, entry.name)) : path.join(under, entry.name)))).flat();
+ return (await walk()).sort();
+ };
+ const originalFiles = await files(dir);
+ assert.deepEqual(await files(servedDir), originalFiles, 'signed package file list differs from export');
+ for (const relative of originalFiles.filter(name => name !== 'manifest.json')) {
+ assert.equal(sha(await fs.readFile(path.join(servedDir, relative))), sha(await fs.readFile(path.join(dir, relative))), relative);
+ }
+ report.packages.push({ ...result, file: path.basename(file), payloadMatchesExport: true });
+ }
let html = HOST_PAGE('main.js');
const marker = " try {\n log('booting";
assert.ok(html.includes(marker), 'contract host hook changed');
@@ -82,7 +133,26 @@ try {
}
` + marker);
html = html.replace('dirOf(file), wx, globalThis);', 'dirOf(file), undefined, globalThis);');
- const root = realpathSync(dir);
+ // Match the documented SUD loader: paths relative to the game entry,
+ // scripts execute globally and require need not return module exports.
+ // DOM script insertion is only the headless harness's execution seam.
+ const loaderStart = html.indexOf(' function requireFrom(dir, spec) {');
+ const loaderEnd = html.indexOf(" // SUD uses standard XHR", loaderStart);
+ assert.ok(loaderStart >= 0 && loaderEnd > loaderStart, 'script host hook changed');
+ html = html.slice(0, loaderStart) + `
+ const loadedScripts = new Set();
+ function requireFrom(_dir, spec) {
+ const file = normalize(spec);
+ if (loadedScripts.has(file)) return;
+ const script = document.createElement('script');
+ script.textContent = readAsText('/' + file) + '\\n//# sourceURL=' + file;
+ loadedScripts.add(file);
+ document.head.appendChild(script);
+ script.remove();
+ }
+ globalThis.require = spec => requireFrom('', spec);
+` + html.slice(loaderEnd);
+ const root = realpathSync(servedDir);
const server = http.createServer((req, res) => {
try {
const rel = decodeURIComponent(new URL(req.url, 'http://localhost').pathname).slice(1);
@@ -112,7 +182,7 @@ try {
+ Math.abs(image.data[i + 2] - image.data[2]) > 40) different++;
}
assert.ok(different > 200, `${dimension} frame is flat (${different} distinct pixels)`);
- report.scenes.push({ dimension, draws: await page.evaluate(() => __draws), differentPixels: different,
+ report.scenes.push({ dimension, project: authoredProject, draws: await page.evaluate(() => __draws), differentPixels: different,
screenshotSha256: sha(frame), engineSha256: sha(await fs.readFile(path.join(dir, 'wasm/esengine.wxgame.wasm'))) });
} finally {
await context.close();
@@ -127,5 +197,10 @@ try {
const resolved = path.resolve(project);
if (!resolved.startsWith(out + path.sep)) throw Error('Unexpected fixture cleanup path');
await fs.rm(resolved, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ if (secretDir) {
+ if (path.dirname(path.resolve(secretDir)) !== await fs.realpath(tmpdir())
+ || !path.basename(secretDir).startsWith('estella-sud-test-keys-')) throw Error('Unexpected key cleanup path');
+ await fs.rm(secretDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ }
}
-console.log('OpenPaaS: 2D and 3D exported packages rendered in headless contract host; device acceptance pending.');
+console.log(`OpenPaaS: 2D and 3D ${packer ? 'officially packaged, verified and decrypted payloads' : 'exports'} rendered in headless contract host; device acceptance pending.`);