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(native): write the Android App Bundle Google Play requires
esengine789c3b603896
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 96611ddf3..4d9458abc 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -134,6 +134,18 @@ jobs:- name: Type-check Desktoprun: pnpm --filter @estella/editor exec tsc --noEmit+ # The Android packaging tests check what we write against implementations that+ # are not ours. androguard decodes the binary manifest; bundletool is the App+ # Bundle format's own authority, and the runner has the JVM it needs — the+ # tests fall back to structural checks where either is absent, so this is the+ # one place they run in full.+ - name: Set up the Android packaging oracles+ run: |+ pip install --quiet androguard+ curl -fsSL -o "$RUNNER_TEMP/bundletool.jar" \+ https://github.com/google/bundletool/releases/download/1.15.6/bundletool-all-1.15.6.jar+ echo "BUNDLETOOL_JAR=$RUNNER_TEMP/bundletool.jar" >> "$GITHUB_ENV"+- name: Run Desktop testsrun: pnpm --filter @estella/editor exec vitest rundiff --git a/build-tools/tests/verify-aab.py b/build-tools/tests/verify-aab.pynew file mode 100644index 000000000..1ab2f91d0--- /dev/null+++ b/build-tools/tests/verify-aab.py@@ -0,0 +1,215 @@+# SPDX-License-Identifier: Apache-2.0+# SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#+# An independent App Bundle verifier — the oracle for build-tools/utils/aab.js.+#+# Same rule as verify-apk.py: we write the format, so checking it with our own+# code proves nothing. This decodes the protobuf wire format generically (field+# numbers and wire types, no schema), reconstructs the manifest tree from the+# bytes, and verifies the JAR signature the way a JAR verifier does — per-entry+# digests in MANIFEST.MF, the manifest's own digest in the signature file, and the+# PKCS#7 signature over that file, checked by hand.+#+# Python 3 standard library only. It cannot tell a wrong FIELD NUMBER from a right+# one — only bundletool knows the schema — so the numbers it reports are asserted+# against the schema in the test, and CI runs `bundletool validate` where a JVM is.+#+# Usage: python3 verify-aab.py <aab> → JSON on stdout, non-zero exit on failure.++import base64+import hashlib+import json+import sys+import zipfile++SHA256_DIGESTINFO = bytes.fromhex("3031300d060960864801650304020105000420")+++def read_varint(buf, at):+ shift = 0+ value = 0+ while True:+ byte = buf[at]+ at += 1+ value |= (byte & 0x7F) << shift+ if not byte & 0x80:+ return value, at+ shift += 7+++def decode_message(buf):+ """{field_number: [value, ...]} — bytes for length-delimited, int for varint."""+ out = {}+ at = 0+ while at < len(buf):+ key, at = read_varint(buf, at)+ field, wire = key >> 3, key & 7+ if wire == 0:+ value, at = read_varint(buf, at)+ elif wire == 2:+ length, at = read_varint(buf, at)+ value = buf[at:at + length]+ at += length+ elif wire == 5:+ value, at = int.from_bytes(buf[at:at + 4], "little"), at + 4+ elif wire == 1:+ value, at = int.from_bytes(buf[at:at + 8], "little"), at + 8+ else:+ raise SystemExit(f"unsupported protobuf wire type {wire}")+ out.setdefault(field, []).append(value)+ return out+++def decode_element(buf):+ """XmlElement { namespace_declaration = 1, name = 3, attribute = 4, child = 5 }."""+ m = decode_message(buf)+ attributes = []+ for raw in m.get(4, []):+ a = decode_message(raw)+ attr = {+ "namespace": a[1][0].decode() if 1 in a else None,+ "name": a[2][0].decode(),+ "value": a[3][0].decode() if 3 in a else "",+ "resourceId": a[5][0] if 5 in a else None,+ }+ if 6 in a:+ item = decode_message(a[6][0])+ if 1 in item: # Item.ref+ attr["compiled"] = {"ref": decode_message(item[1][0]).get(2, [0])[0]}+ elif 7 in item: # Item.prim+ prim = decode_message(item[7][0])+ field = next(iter(prim))+ attr["compiled"] = {"primField": field, "primValue": prim[field][0]}+ attributes.append(attr)+ return {+ "name": m[3][0].decode(),+ "namespaces": [decode_message(n)[1][0].decode() for n in m.get(1, [])],+ "attributes": attributes,+ "children": [decode_element(decode_message(c)[1][0]) for c in m.get(5, [])],+ }+++def jar_verify(zf):+ """The JAR signature: every entry's digest, the manifest's digest, and the+ PKCS#7 signature over the signature file."""+ manifest = zf.read("META-INF/MANIFEST.MF")+ signature_file = zf.read("META-INF/ESTELLA.SF")+ block = zf.read("META-INF/ESTELLA.RSA")++ # Every non-META-INF entry must be digested in the manifest, and match.+ sections = {}+ for section in manifest.split(b"\r\n\r\n")[1:]:+ if not section.strip():+ continue+ body = section if section.endswith(b"\r\n") else section + b"\r\n"+ lines = _unfold(body)+ name = lines["Name"]+ sections[name] = (lines["SHA-256-Digest"], body)++ checked = 0+ for info in zf.infolist():+ if info.filename.startswith("META-INF/"):+ continue+ if info.filename not in sections:+ raise SystemExit(f"{info.filename} is not digested in MANIFEST.MF")+ want, _ = sections[info.filename]+ got = base64.b64encode(hashlib.sha256(zf.read(info.filename)).digest()).decode()+ if got != want:+ raise SystemExit(f"digest mismatch for {info.filename}")+ checked += 1++ sf = _unfold(signature_file.split(b"\r\n\r\n")[0] + b"\r\n")+ want_manifest = sf["SHA-256-Digest-Manifest"]+ got_manifest = base64.b64encode(hashlib.sha256(manifest).digest()).decode()+ if got_manifest != want_manifest:+ raise SystemExit("the signature file does not digest this MANIFEST.MF")++ _verify_pkcs7(block, signature_file)+ return checked+++def _unfold(section):+ """JAR attributes, with continuation lines (a leading space) folded back in."""+ out = {}+ key = None+ for line in section.decode().split("\r\n"):+ if not line:+ continue+ if line.startswith(" "):+ out[key] += line[1:]+ else:+ key, _, value = line.partition(": ")+ out[key] = value+ return out+++def _der_items(buf):+ at = 0+ while at < len(buf):+ start = at+ tag = buf[at]+ length = buf[at + 1]+ at += 2+ if length & 0x80:+ count = length & 0x7F+ length = int.from_bytes(buf[at:at + count], "big")+ at += count+ yield tag, buf[at:at + length], buf[start:at + length]+ at += length+++def _verify_pkcs7(block, signed_content):+ """SignedData with no authenticated attributes: the signature is over the+ content itself, and the certificate inside carries the verifying key."""+ _, content_info, _ = next(_der_items(block))+ explicit = [c for t, c, _ in _der_items(content_info) if t == 0xA0][0]+ _, signed_data, _ = next(_der_items(explicit))+ parts = list(_der_items(signed_data))++ certificate = [c for t, c, _ in parts if t == 0xA0][0]+ signer_infos = [c for t, c, _ in parts if t == 0x31][-1]+ _, signer, _ = next(_der_items(signer_infos))+ signature = [c for t, c, _ in _der_items(signer) if t == 0x04][0]++ # The certificate's SubjectPublicKeyInfo is the last SEQUENCE of the TBS.+ _, cert_body, _ = next(_der_items(certificate))+ tbs = next(c for t, c, _ in _der_items(cert_body) if t == 0x30)+ spki = [f for t, c, f in _der_items(tbs) if t == 0x30][-1]+ _, spki_body, _ = next(_der_items(spki))+ bits = [c for t, c, _ in _der_items(spki_body) if t == 0x03][0]+ _, rsa_key, _ = next(_der_items(bits[1:]))+ n, e = [int.from_bytes(c, "big") for t, c, _ in _der_items(rsa_key) if t == 0x02][:2]++ size = (n.bit_length() + 7) // 8+ decrypted = pow(int.from_bytes(signature, "big"), e, n).to_bytes(size, "big")+ expected = b"\x00\x01" + b"\xff" * (size - 3 - len(SHA256_DIGESTINFO) - 32) + b"\x00" \+ + SHA256_DIGESTINFO + hashlib.sha256(signed_content).digest()+ if decrypted != expected:+ raise SystemExit("the JAR signature does not verify against the certificate")+++def verify(path):+ with zipfile.ZipFile(path) as zf:+ names = zf.namelist()+ for required in ("BundleConfig.pb", "base/manifest/AndroidManifest.xml"):+ if required not in names:+ raise SystemExit(f"the bundle has no {required}")++ signed_entries = jar_verify(zf)+ manifest = decode_element(decode_message(zf.read("base/manifest/AndroidManifest.xml"))[1][0])+ config = decode_message(zf.read("BundleConfig.pb"))++ return {+ "entries": len(names),+ "signedEntries": signed_entries,+ "bundletoolVersion": decode_message(config[1][0])[2][0].decode(),+ "uncompressedGlobs": [g.decode() for g in decode_message(config[3][0])[1]],+ "manifest": manifest,+ "hasDex": any(n.startswith("base/dex/") for n in names),+ "libs": sorted(n for n in names if n.startswith("base/lib/")),+ "assets": sum(1 for n in names if n.startswith("base/assets/")),+ }+++if __name__ == "__main__":+ print(json.dumps(verify(sys.argv[1]), indent=2))diff --git a/build-tools/utils/aab.d.ts b/build-tools/utils/aab.d.tsnew file mode 100644index 000000000..e9c56df7c--- /dev/null+++ b/build-tools/utils/aab.d.ts@@ -0,0 +1,20 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// Types for aab.js — the module is plain ESM so the CLI can run it unbuilt, and+// this is how the editor's TypeScript sees it.++import type { SigningKey } from './androidKeystore';+import type { ApkAppIdentity } from './apk';++export function assembleAab(options: {+ /** An installed android runtime template. */+ templateDir: string;+ /** The export: cooked content plus the two configs. */+ contentDir: string;+ app: ApkAppIdentity;+ key: SigningKey;+ abi: string;+}): Buffer;++export function aabFileName(appId: string): string;diff --git a/build-tools/utils/aab.js b/build-tools/utils/aab.jsnew file mode 100644index 000000000..eb499e4d0--- /dev/null+++ b/build-tools/utils/aab.js@@ -0,0 +1,87 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// The Android App Bundle — what Google Play takes.+//+// Play has required an .aab rather than an .apk for new apps since 2021, so+// without this "you can package for Android" stops at sideloading. It is the same+// content as the APK from the same template, rearranged and encoded differently:+//+// * the manifest is protobuf (androidProtoXml.js) rather than binary XML;+// * everything lives under `base/`, split by kind — Play recompiles it into+// per-device APKs, which is the point of the format;+// * it is a JAR, so it is signed the JAR way rather than with APK Signature+// Scheme v2.+//+// The store's own server does the final packaging, which is why nothing here is+// installable: `bundletool build-apks` (or Play) turns it into APKs.++import path from 'path';+import { existsSync, readFileSync } from 'fs';+import { makeZip } from './zip.js';+import { packageEntries } from './apk.js';+import { message, bytesField } from './protobuf.js';+import { compileProtoManifest } from './androidProtoXml.js';+import { jarSignatureFiles } from './jarSign.js';+import { fillTemplate, androidScreenOrientation } from './nativeApp.js';++/**+ * BundleConfig.pb — `bundletool { version = 2 }`, `compression { uncompressed_glob = 1 }`.+ *+ * The glob is the same posture the APK takes: native libraries stay uncompressed+ * so the OS can map them out of the installed package.+ */+function bundleConfig() {+ return message(+ bytesField(1, message(bytesField(2, '1.15.6'))),+ bytesField(3, message(bytesField(1, '**.so'))),+ );+}++/**+ * Assemble a signed App Bundle from a runtime template and an editor export.+ *+ * @param {object} options Same shape as {@link import('./apk.js').assembleApk}.+ * @returns {Buffer} the signed bundle.+ */+export function assembleAab(options) {+ const { templateDir, contentDir, app, abi } = options;+ const dex = path.join(templateDir, 'classes.dex');+ const hasDex = existsSync(dex);++ const manifest = compileProtoManifest(fillTemplate(+ readFileSync(path.join(templateDir, 'AndroidManifest.xml.in'), 'utf8'), {+ APP_ID: app.id,+ APP_NAME: app.name,+ VERSION_NAME: app.version,+ VERSION_CODE: app.versionCode,+ SCREEN_ORIENTATION: androidScreenOrientation(app.orientation),+ HAS_CODE: hasDex ? 'true' : 'false',+ }));++ const libDir = path.join(templateDir, 'lib', abi);+ if (!existsSync(libDir)) throw new Error(`The runtime template has no lib/${abi}.`);+ const templateAssets = path.join(templateDir, 'assets');++ const entries = [+ { name: 'BundleConfig.pb', data: bundleConfig() },+ { name: 'base/manifest/AndroidManifest.xml', data: manifest },+ // An empty ResourceTable: the app declares no resources of its own, and the+ // one reference its manifest makes is to a framework id.+ { name: 'base/resources.pb', data: Buffer.alloc(0) },+ ...(hasDex ? [{ name: 'base/dex/classes.dex', data: readFileSync(dex) }] : []),+ ...packageEntries(libDir, `base/lib/${abi}`),+ ...(existsSync(templateAssets) ? packageEntries(templateAssets, 'base/assets') : []),+ ...packageEntries(contentDir, 'base/assets'),+ ];++ // The signature covers the entries, so it is computed over them and added+ // afterwards — and it goes FIRST in the archive, where a JAR reader expects the+ // manifest to be.+ return makeZip([...jarSignatureFiles(entries, options.key), ...entries]);+}++/** The bundle is named after the app it holds, like the APK beside it. */+export function aabFileName(appId) {+ return `${appId.split('.').pop() || 'estella'}.aab`;+}diff --git a/build-tools/utils/androidProtoXml.js b/build-tools/utils/androidProtoXml.jsnew file mode 100644index 000000000..acc49107b--- /dev/null+++ b/build-tools/utils/androidProtoXml.js@@ -0,0 +1,95 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// AndroidManifest.xml in aapt2's PROTO form — what an App Bundle carries where an+// APK carries binary XML.+//+// The same manifest, the same parsed tree and the same resource ids as+// androidBinaryXml.js; only the encoding differs. That is why the XML reader and+// the id table live there and are imported here rather than copied: a bundle whose+// manifest disagreed with its APK's would be a bug nobody finds until a store+// rejects the upload.+//+// Field numbers are from aapt2's Resources.proto (XmlNode / XmlElement /+// XmlAttribute / Item / Primitive / Reference). They are part of a published wire+// format, but they are also the one thing here that cannot be inferred from the+// data — `desktop/tests/android-aab.test.ts` decodes what this writes and checks+// every one of them, and validates the finished bundle with bundletool wherever a+// JVM exists.++import { message, bytesField, varintField, boolField } from './protobuf.js';+import { parseXml, ANDROID_NS, ANDROID_ATTR_IDS, ANDROID_STYLE_IDS } from './androidBinaryXml.js';++// Resources.proto — Primitive.oneof_value+const PRIM_INT_DECIMAL = 6;+const PRIM_INT_HEX = 7;+const PRIM_BOOLEAN = 8;++// Resources.proto — Item.value+const ITEM_REF = 1;+const ITEM_STR = 2;+const ITEM_PRIM = 7;++// Resources.proto — Reference+const REF_ID = 2;++/** `Item` for an attribute value, typed the way the platform expects to read it. */+function compiledItem(value) {+ const style = /^@android:style\/(.+)$/.exec(value);+ if (style) {+ const id = ANDROID_STYLE_IDS[style[1]];+ if (id === undefined) throw new Error(`Unknown framework style @android:style/${style[1]}`);+ return bytesField(ITEM_REF, message(varintField(REF_ID, id)));+ }+ if (value === 'true' || value === 'false') {+ return bytesField(ITEM_PRIM, message(boolField(PRIM_BOOLEAN, value === 'true')));+ }+ if (/^0x[0-9a-fA-F]+$/.test(value)) {+ return bytesField(ITEM_PRIM, message(varintField(PRIM_INT_HEX, Number.parseInt(value, 16))));+ }+ if (/^-?\d+$/.test(value)) {+ return bytesField(ITEM_PRIM, message(varintField(PRIM_INT_DECIMAL, Number.parseInt(value, 10))));+ }+ // A plain string: `value` already carries it, and a String item beside it would+ // be the same bytes twice.+ return null;+}++/** XmlAttribute { namespace_uri = 1, name = 2, value = 3, resource_id = 5, compiled_item = 6 } */+function attribute(attr) {+ const framework = attr.prefix === 'android';+ const id = framework ? ANDROID_ATTR_IDS[attr.name] : undefined;+ if (framework && id === undefined) {+ throw new Error(`No public resource id known for android:${attr.name} — add it to ANDROID_ATTR_IDS.`);+ }+ const compiled = framework ? compiledItem(attr.value) : null;+ return message(+ framework ? bytesField(1, ANDROID_NS) : null,+ bytesField(2, attr.name),+ bytesField(3, attr.value),+ id === undefined ? null : varintField(5, id),+ compiled ? bytesField(6, compiled) : null,+ );+}++/** XmlElement { namespace_declaration = 1, namespace_uri = 2, name = 3, attribute = 4, child = 5 } */+function element(node, declareNamespace) {+ return message(+ declareNamespace ? bytesField(1, message(bytesField(1, 'android'), bytesField(2, ANDROID_NS))) : null,+ bytesField(3, node.name),+ ...node.attrs+ .filter((a) => a.name !== 'xmlns' && a.prefix !== 'xmlns')+ .map((a) => bytesField(4, attribute(a))),+ ...node.children.map((child) => bytesField(5, node_(child, false))),+ );+}++/** XmlNode { element = 1 } */+function node_(element_, declareNamespace) {+ return message(bytesField(1, element(element_, declareNamespace)));+}++/** Compile manifest SOURCE to the protobuf XML an App Bundle carries. */+export function compileProtoManifest(xml) {+ return node_(parseXml(xml), true);+}diff --git a/build-tools/utils/apk.d.ts b/build-tools/utils/apk.d.tsindex 87bec3007..166d1bb59 100644--- a/build-tools/utils/apk.d.ts+++ b/build-tools/utils/apk.d.ts@@ -25,4 +25,5 @@ export function assembleApk(options: {}): Buffer;export function signApkV2(zip: Buffer, key: SigningKey): Buffer;+export function packageEntries(dir: string, prefix: string): Array<{ name: string; data: Buffer }>;export function apkFileName(appId: string): string;diff --git a/build-tools/utils/apk.js b/build-tools/utils/apk.jsindex c8c6c572f..d48647823 100644--- a/build-tools/utils/apk.js+++ b/build-tools/utils/apk.js@@ -103,19 +103,22 @@ export function signApkV2(zip, key) {return Buffer.concat([contents, block, centralDir, signedEocd]);}-/** Every file under `dir`, as `{ name, data }` entries named `<prefix>/<rel>`. */-function treeEntries(dir, prefix) {+/**+ * Every file under `dir`, as `{ name, data }` entries named `<prefix>/<rel>`.+ *+ * Dotfiles stay out — build-machine litter (.DS_Store, .gitkeep) is not something+ * to find out about from a shipped package — and so do packages: the finished .apk+ * and .aab land in the export directory, and a re-export must not swallow the last+ * one. Shared with the bundle assembler, which packs the same content.+ */+export function packageEntries(dir, prefix) {const out = [];const walk = (abs, rel) => {for (const e of readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {const child = path.join(abs, e.name);const name = `${rel}/${e.name}`;if (e.isDirectory()) walk(child, name);- // Dotfiles are build-machine litter (.DS_Store, .gitkeep); a package is- // not the place to find out they shipped. Neither is a package: the- // finished APK lands in the export directory, and a re-export must not- // swallow the last one.- else if (e.isFile() && !e.name.startsWith('.') && !e.name.endsWith('.apk')) {+ else if (e.isFile() && !e.name.startsWith('.') && !/\.(apk|aab)$/.test(e.name)) {out.push({ name, data: readFileSync(child) });}}@@ -158,11 +161,11 @@ export function assembleApk(options) {const entries = [{ name: 'AndroidManifest.xml', data: manifest },...(hasDex ? [{ name: 'classes.dex', data: readFileSync(dex) }] : []),- ...treeEntries(libDir, `lib/${abi}`).map((e) => ({ ...e, store: true, align: PAGE_ALIGNMENT })),+ ...packageEntries(libDir, `lib/${abi}`).map((e) => ({ ...e, store: true, align: PAGE_ALIGNMENT })),// The template's assets (the SDK bytecode) first, so a project cannot// shadow them by accident and quietly change what the host boots.- ...(existsSync(templateAssets) ? treeEntries(templateAssets, 'assets') : []),- ...treeEntries(contentDir, 'assets'),+ ...(existsSync(templateAssets) ? packageEntries(templateAssets, 'assets') : []),+ ...packageEntries(contentDir, 'assets'),];const seen = new Set();diff --git a/build-tools/utils/asn1.js b/build-tools/utils/asn1.jsindex 14d486e9f..dff2baf15 100644--- a/build-tools/utils/asn1.js+++ b/build-tools/utils/asn1.js@@ -11,6 +11,46 @@import { createHash } from 'crypto';+/**+ * Walk DER TLVs, yielding `{ tag, content, full }`.+ *+ * Reading is needed for exactly one thing: a JAR signature identifies the signer+ * by the certificate's ISSUER and SERIAL, and those have to come out of whatever+ * certificate the developer handed us — including one we did not write.+ */+export function derItems(buf) {+ const out = [];+ let at = 0;+ while (at < buf.length) {+ const start = at;+ const tag = buf[at];+ let length = buf[at + 1];+ at += 2;+ if (length & 0x80) {+ const count = length & 0x7f;+ length = 0;+ for (let i = 0; i < count; i++) length = (length << 8) | buf[at + i];+ at += count;+ }+ out.push({ tag, content: buf.subarray(at, at + length), full: buf.subarray(start, at + length) });+ at += length;+ }+ return out;+}++/** The issuer name (DER) and serial number of an X.509 certificate — what a+ * SignerInfo names the signer by. */+export function certificateIssuerAndSerial(certificate) {+ const tbs = derItems(derItems(certificate)[0].content)[0].content;+ const children = derItems(tbs);+ const serial = children.find((c) => c.tag === 0x02);+ // version[0], serial, signature, ISSUER, validity, subject, spki — so the+ // issuer is the second SEQUENCE either way, with or without the version tag.+ const issuer = children.filter((c) => c.tag === 0x30)[1];+ if (!serial || !issuer) throw new Error('certificate has no issuer/serial (is it DER?)');+ return { issuer: issuer.full, serial: serial.full };+}+/** A DER TLV: tag, definite length, contents. */export function der(tag, contents) {const body = Buffer.isBuffer(contents) ? contents : Buffer.concat(contents);diff --git a/build-tools/utils/jarSign.js b/build-tools/utils/jarSign.jsnew file mode 100644index 000000000..e41462d41--- /dev/null+++ b/build-tools/utils/jarSign.js@@ -0,0 +1,80 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// JAR signing — the scheme an Android App Bundle is signed with.+//+// An APK gets APK Signature Scheme v2, which signs the archive's bytes and is+// simple because of it. A bundle is not an APK: Play takes it as a JAR, so it is+// signed the JAR way — a manifest of per-entry digests, a signature file digesting+// that manifest, and a PKCS#7 block signing the signature file. Three files and+// one ASN.1 structure, and the only reason `jarsigner` (and the JDK under it) used+// to be required.++import { createHash, sign as cryptoSign } from 'crypto';+import { der, sequence, set, integer, octetString, nullValue, oid, explicit, certificateIssuerAndSerial } from './asn1.js';++const OID_SIGNED_DATA = '1.2.840.113549.1.7.2';+const OID_DATA = '1.2.840.113549.1.7.1';+const OID_SHA256 = '2.16.840.1.101.3.4.2.1';+const OID_RSA = '1.2.840.113549.1.1.1';++/** A JAR manifest line, wrapped at 72 bytes with a leading space — mandated by the+ * format, and reachable here by an asset path a game happens to have. */+function attributeLine(name, value) {+ const line = `${name}: ${value}`;+ let out = line.slice(0, 72);+ for (let at = 72; at < line.length; at += 71) out += `\r\n ${line.slice(at, at + 71)}`;+ return `${out}\r\n`;+}++const base64Digest = (data) => createHash('sha256').update(data).digest('base64');++/**+ * Sign a set of entries the JAR way.+ *+ * @param {ReadonlyArray<{name: string, data: Buffer}>} entries What the archive holds.+ * @param {{privateKey: import('crypto').KeyObject, certificate: Buffer}} key+ * @returns {Array<{name: string, data: Buffer}>} The three META-INF files to add.+ */+export function jarSignatureFiles(entries, key) {+ const manifestHeader = 'Manifest-Version: 1.0\r\nCreated-By: Estella\r\n\r\n';+ // Each entry's section is digested on its own for the signature file, so they+ // are built as sections rather than as one string that would have to be split.+ const sections = entries.map((entry) => attributeLine('Name', entry.name)+ + attributeLine('SHA-256-Digest', base64Digest(entry.data)) + '\r\n');+ const manifest = Buffer.from(manifestHeader + sections.join(''), 'utf8');++ const signatureFile = Buffer.from(+ 'Signature-Version: 1.0\r\nCreated-By: Estella\r\n'+ + attributeLine('SHA-256-Digest-Manifest', base64Digest(manifest))+ + '\r\n'+ + entries.map((entry, n) => attributeLine('Name', entry.name)+ + attributeLine('SHA-256-Digest', base64Digest(Buffer.from(sections[n], 'utf8'))) + '\r\n').join(''),+ 'utf8');++ const { issuer, serial } = certificateIssuerAndSerial(key.certificate);+ const digestAlgorithm = sequence(oid(OID_SHA256), nullValue());+ const signerInfo = sequence(+ integer(1),+ sequence(issuer, serial),+ digestAlgorithm,+ sequence(oid(OID_RSA), nullValue()),+ // No authenticated attributes, so the signature is over the signature+ // file itself — the simplest form the verifier accepts.+ octetString(cryptoSign('sha256', signatureFile, key.privateKey)),+ );+ const signedData = sequence(+ integer(1),+ set(digestAlgorithm),+ sequence(oid(OID_DATA)), // detached: the content is CERT.SF+ der(0xa0, key.certificate), // [0] IMPLICIT certificates+ set(signerInfo),+ );+ const block = sequence(oid(OID_SIGNED_DATA), explicit(0, signedData));++ return [+ { name: 'META-INF/MANIFEST.MF', data: manifest },+ { name: 'META-INF/ESTELLA.SF', data: signatureFile },+ { name: 'META-INF/ESTELLA.RSA', data: block },+ ];+}diff --git a/build-tools/utils/protobuf.js b/build-tools/utils/protobuf.jsnew file mode 100644index 000000000..7e2ead41c--- /dev/null+++ b/build-tools/utils/protobuf.js@@ -0,0 +1,47 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// Protocol-buffer encoding, write side only.+//+// An Android App Bundle is protobuf where an APK is binary XML: the same manifest+// in a different encoding, plus a couple of small config messages. Writing them+// needs the wire format — varints and length-delimited fields — and nothing else:+// no schema compiler, no runtime, no descriptors. Reading is not needed, and a+// dependency that could do both would be far more surface than this.++/** A varint: seven bits per byte, high bit continues. */+export function varint(value) {+ const out = [];+ let n = BigInt(value);+ if (n < 0n) n += 1n << 64n; // negative int32/int64 are sign-extended to 64 bits+ do {+ const byte = Number(n & 0x7fn);+ n >>= 7n;+ out.push(n > 0n ? byte | 0x80 : byte);+ } while (n > 0n);+ return Buffer.from(out);+}++const tag = (field, wireType) => varint((field << 3) | wireType);++/** A length-delimited field: a string, a byte string, or a nested message. */+export function bytesField(field, value) {+ const body = Buffer.isBuffer(value) ? value : Buffer.from(String(value), 'utf8');+ return Buffer.concat([tag(field, 2), varint(body.length), body]);+}++/** A varint field. Omitted when the value is the proto3 default: an encoder that+ * writes zeros produces bytes a decoder cannot tell from "unset", and for a+ * `oneof` that difference is the whole point. */+export function varintField(field, value) {+ return Buffer.concat([tag(field, 0), varint(value)]);+}++export function boolField(field, value) {+ return varintField(field, value ? 1 : 0);+}++/** A message: its fields concatenated, in field order. */+export function message(...fields) {+ return Buffer.concat(fields.flat().filter((f) => f && f.length > 0));+}diff --git a/desktop/tests/android-aab.test.ts b/desktop/tests/android-aab.test.tsnew file mode 100644index 000000000..d25167029--- /dev/null+++ b/desktop/tests/android-aab.test.ts@@ -0,0 +1,212 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// The App Bundle assembler — the format Google Play takes, which is the same app+// as the APK in a different encoding.+//+// Two things are worth pinning down. The first is that the two encodings agree:+// the manifest is parsed once and written twice, so a bundle that described a+// different app than its APK would be a bug found by a store rejection. The+// second is the protobuf FIELD NUMBERS, which are the one thing in this format+// that cannot be inferred from the data — they are asserted against aapt2's+// Resources.proto here, decoded out of the bytes by an implementation that shares+// no code with the writer.+//+// `bundletool validate` is the real authority, and it needs a JVM. Where one+// exists (CI, and any machine with BUNDLETOOL_JAR set) it runs; where it does not,+// the structural checks still do, and they say so rather than passing silently.+import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';+import { execFileSync } from 'node:child_process';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { assembleAab, aabFileName } from '../../build-tools/utils/aab.js';+import { assembleApk } from '../../build-tools/utils/apk.js';+import { debugSigningKey } from '../../build-tools/utils/androidKeystore.js';+import { readZip, makeZip } from '../../build-tools/utils/zip.js';++const REPO = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..');+const VERIFIER = path.join(REPO, 'build-tools', 'tests', 'verify-aab.py');+const MANIFEST_TEMPLATE = path.join(REPO, 'native', 'android', 'host', 'AndroidManifest.xml.in');++const APP = {+ id: 'com.example.demo', name: 'My Game', version: '1.2', versionCode: 7,+ orientation: 'portrait' as const,+};++interface Attribute {+ name: string;+ value: string;+ resourceId: number | null;+ compiled?: { ref?: number; primField?: number; primValue?: number };+}+interface Element { name: string; attributes: Attribute[]; children: Element[] }++let scratch: string;+let templateDir: string;+let contentDir: string;+let hasPython = true;+let hasAndroguard = false;+/** `bundletool validate` — the format's own authority, when a JVM is around. */+let bundletool: string | null = null;++beforeAll(() => {+ try {+ execFileSync('python3', ['-c', 'pass'], { stdio: 'ignore' });+ } catch {+ hasPython = false;+ }+ if (hasPython) {+ try {+ execFileSync('python3', ['-c', 'import androguard'], { stdio: 'ignore' });+ hasAndroguard = true;+ } catch { /* the structural checks still run */ }+ }+ const jar = process.env.BUNDLETOOL_JAR;+ if (jar && existsSync(jar)) {+ try {+ execFileSync('java', ['-version'], { stdio: 'ignore' });+ bundletool = jar;+ } catch { /* no JVM */ }+ }+});++beforeEach(() => {+ scratch = mkdtempSync(path.join(tmpdir(), 'es-aab-'));+ process.env.ESTELLA_ANDROID_KEYS = path.join(scratch, 'keys');++ templateDir = path.join(scratch, 'template');+ mkdirSync(path.join(templateDir, 'lib', 'arm64-v8a'), { recursive: true });+ mkdirSync(path.join(templateDir, 'assets'), { recursive: true });+ writeFileSync(path.join(templateDir, 'AndroidManifest.xml.in'), readFileSync(MANIFEST_TEMPLATE));+ writeFileSync(path.join(templateDir, 'lib/arm64-v8a/libestella_js_host.so'), Buffer.alloc(40_000, 7));+ writeFileSync(path.join(templateDir, 'lib/arm64-v8a/libwebgpu_dawn.so'), Buffer.alloc(30_000, 9));+ writeFileSync(path.join(templateDir, 'classes.dex'), Buffer.from('dex\n035\0stand-in'));+ writeFileSync(path.join(templateDir, 'assets', 'esengine.native.qjsbc'), Buffer.alloc(512, 3));++ contentDir = path.join(scratch, 'dist-android');+ mkdirSync(path.join(contentDir, 'assets', 'scenes'), { recursive: true });+ writeFileSync(path.join(contentDir, 'game.config.json'), '{"entryScene":"main"}');+ writeFileSync(path.join(contentDir, 'assets/scenes/main.esscene'), '{"entities":[]}');+});++afterEach(() => {+ delete process.env.ESTELLA_ANDROID_KEYS;+ rmSync(scratch, { recursive: true, force: true });+});++const assembly = () => ({+ templateDir, contentDir, app: APP, abi: 'arm64-v8a', key: debugSigningKey(),+});++function build(): string {+ const file = path.join(contentDir, aabFileName(APP.id));+ writeFileSync(file, assembleAab(assembly()));+ return file;+}++function verify(aab: string): {+ entries: number; signedEntries: number; bundletoolVersion: string;+ uncompressedGlobs: string[]; manifest: Element; hasDex: boolean;+ libs: string[]; assets: number;+} {+ return JSON.parse(execFileSync('python3', [VERIFIER, aab], { encoding: 'utf8' }));+}++const find = (element: Element, name: string): Element | undefined =>+ element.name === name ? element : element.children.map((c) => find(c, name)).find(Boolean);+const attr = (element: Element, name: string): Attribute | undefined =>+ element.attributes.find((a) => a.name === name);++describe('assembling an App Bundle', () => {+ it('lays the app out the way the format requires, and signs every entry', () => {+ if (!hasPython) return;+ const result = verify(build());++ expect(result.hasDex).toBe(true);+ expect(result.libs).toEqual([+ 'base/lib/arm64-v8a/libestella_js_host.so',+ 'base/lib/arm64-v8a/libwebgpu_dawn.so',+ ]);+ // The template's bytecode plus the export's own files.+ expect(result.assets).toBe(3);+ expect(result.uncompressedGlobs).toEqual(['**.so']);+ expect(result.bundletoolVersion).toMatch(/^\d+\.\d+/);+ // Everything outside META-INF is digested — that is what signing a JAR means.+ expect(result.signedEntries).toBe(result.entries - 3);+ });++ it('describes the app in protobuf, typed the way the platform reads it', () => {+ if (!hasPython) return;+ const { manifest } = verify(build());++ expect(attr(manifest, 'package')?.value).toBe('com.example.demo');+ // Resources.proto: Primitive.int_decimal_value = 6, and the resource id is+ // what the platform actually resolves the attribute by.+ expect(attr(manifest, 'versionCode')).toMatchObject({+ resourceId: 0x0101021b,+ compiled: { primField: 6, primValue: 7 },+ });++ const application = find(manifest, 'application')!;+ // Primitive.boolean_value = 8.+ expect(attr(application, 'extractNativeLibs')).toMatchObject({+ compiled: { primField: 8, primValue: 0 },+ });++ const feature = find(manifest, 'uses-feature')!;+ // Primitive.int_hexadecimal_value = 7.+ expect(attr(feature, 'version')).toMatchObject({ compiled: { primField: 7, primValue: 0x400003 } });++ const activity = find(manifest, 'activity')!;+ // Item.ref → Reference.id = 2, carrying the framework theme.+ expect(attr(activity, 'theme')).toMatchObject({ compiled: { ref: 0x01030007 } });+ expect(attr(activity, 'screenOrientation')?.value).toBe('sensorPortrait');+ expect(find(manifest, 'category')).toBeTruthy();+ });++ it('describes the SAME app its APK does — one manifest, two encodings', () => {+ if (!hasPython || !hasAndroguard) return;+ const apk = path.join(scratch, 'demo.apk');+ writeFileSync(apk, assembleApk(assembly()));+ const binary = JSON.parse(execFileSync('python3', ['-c',+ 'import sys,os,json;os.environ["LOGURU_LEVEL"]="CRITICAL";'+ + 'from androguard.core.apk import APK;a=APK(sys.argv[1]);'+ + 'print(json.dumps({"package":a.get_package(),"label":a.get_app_name(),'+ + '"versionName":a.get_androidversion_name(),"versionCode":a.get_androidversion_code(),'+ + '"minSdk":a.get_min_sdk_version(),"activity":a.get_main_activity()}))', apk,+ ], { encoding: 'utf8' }));++ const { manifest } = verify(build());+ const application = find(manifest, 'application')!;++ expect(attr(manifest, 'package')?.value).toBe(binary.package);+ expect(attr(application, 'label')?.value).toBe(binary.label);+ expect(attr(manifest, 'versionName')?.value).toBe(binary.versionName);+ expect(String(attr(manifest, 'versionCode')?.compiled?.primValue)).toBe(binary.versionCode);+ expect(attr(find(manifest, 'uses-sdk')!, 'minSdkVersion')?.value).toBe(binary.minSdk);+ expect(attr(find(manifest, 'activity')!, 'name')?.value).toBe(binary.activity);+ });++ it('fails verification once an entry changes under the signature', () => {+ if (!hasPython) return;+ // Repacked with one file swapped and the ORIGINAL signature kept — which is+ // exactly what tampering with a signed bundle looks like.+ const entries = readZip(readFileSync(build())).map((e) => (+ e.name.endsWith('main.esscene') ? { ...e, data: Buffer.from('{"entities":[1]}') } : e));+ const file = path.join(scratch, 'tampered.aab');+ writeFileSync(file, makeZip(entries));++ expect(() => verify(file)).toThrow();+ });++ it('passes bundletool, where there is a JVM to run it', () => {+ if (!bundletool) return;+ const file = build();++ const out = execFileSync('java', ['-jar', bundletool, 'validate', `--bundle=${file}`], { encoding: 'utf8' });++ expect(out).toContain('com.example.demo');+ });+});