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
fix(editor): gate project platform profiles behind the same trust prompt as plugins
esenginedcb25eaa4552
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 0656d318d..295fc80dd 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -44,7 +44,7 @@ import {} from './pluginHost';import { checkForUpdate } from './updateCheck';import {- listPlatforms, loadProjectPlatform, createProjectPlatform,+ listPlatforms, loadProjectPlatform, createProjectPlatform, setPlatformTrustGate,listPlayableNetworks, loadPlayableProfile,type PlatformRuntimeDirs, type ProjectPlatformKind,} from './platformCatalog';@@ -938,6 +938,12 @@ ipcMain.handle('recents:remove', (_e, root: string) => removeRecent(root));// main never decides to run it. —const userData = (): string => app.getPath('userData');+// Project platform profiles are imported into THIS process with full Node, so they+// pass the same approval the plugin host applies. Injected rather than threaded+// through the catalog's signatures (the setAssetRefProblemResolver pattern), which+// also keeps the catalog unit-testable with no gate installed.+setPlatformTrustGate((id, file) => isTrusted(userData(), id, '0.0.0', file));+ipcMain.handle('plugins:list', async () => {const found = await discoverPlugins(projectRoot, userData());return found.map((p) => ({ ...p, disabled: isDisabled(userData(), p.id) }));@@ -955,6 +961,14 @@ ipcMain.handle('plugins:load', async (_e, id: string) => {// The renderer says only "the user approved this id" — main resolves which version// and folder that means, so the approval can't be recorded against a stale pair.+// Trust WITHOUT compiling — what a project platform profile needs, since it has no+// renderer entry to build and approving it only permits a main-process import.+ipcMain.handle('plugins:trustState', async (_e, id: string) => {+ const found = await discoverPlugins(projectRoot, userData());+ const entry = found.find((p) => p.id === id && p.manifest);+ return !!entry && isTrusted(userData(), id, entry.manifest!.version, entry.dir);+});+ipcMain.handle('plugins:trust', async (_e, id: string) => {const found = await discoverPlugins(projectRoot, userData());const plugin = found.find((p) => p.id === id && p.manifest);diff --git a/desktop/electron/platformCatalog.ts b/desktop/electron/platformCatalog.tsindex 7621e1c81..f4a77884d 100644--- a/desktop/electron/platformCatalog.ts+++ b/desktop/electron/platformCatalog.ts@@ -61,6 +61,10 @@ export interface PlatformStatus {/** Project platforms only — the module failed to load, and why. The row still* appears (silently dropping a file the user wrote is worse than naming it). */error?: string;+ /** Project platforms only — the profile hasn't been approved yet, so it was NOT+ * imported. The row appears so the user can see it exists and go approve it,+ * rather than wondering why the target never showed up. */+ needsTrust?: boolean;}// =============================================================================@@ -421,11 +425,37 @@ function playableIdProblem(id: unknown): string | null {}/**- * Import one project platform module. Returns its raw export, or an error string- * — never throws: a project that ships a broken profile must still be able to- * open the dialog and package for every other target.+ * Whether the user has approved a project platform profile. Injected (rather than+ * threading a userData path through every catalog signature) the same way+ * setAssetRefProblemResolver injects the editor's registry into the control surface.+ *+ * Unset means "not gated" — the pure-Node tests and any caller that has no user to+ * ask see the pre-gate behaviour, which is what keeps this module unit-testable.+ */+let trustGate: ((id: string, file: string) => boolean) | null = null;++export function setPlatformTrustGate(fn: ((id: string, file: string) => boolean) | null): void {+ trustGate = fn;+}++/** Id a platform profile file is approved under (shared with the Plugins panel). */+export const platformTrustId = (file: string): string => `platform.${path.basename(file, '.mjs')}`;++/**+ * Import one project platform module. Returns its raw export, an error string, or+ * `untrusted` when the user hasn't approved it — never throws: a project that ships+ * a broken profile must still be able to open the dialog and package for every+ * other target.+ *+ * The trust check comes FIRST and is the whole reason it exists here: this import+ * runs project-supplied code in the MAIN process, with full Node — strictly more+ * privileged than a renderer plugin, which the editor already gates. Leaving it open+ * while gating the plugin would have the protection backwards.*/-async function importPlatformModule(file: string): Promise<{ mod?: ProjectPlatformModule; error?: string }> {+async function importPlatformModule(+ file: string,+): Promise<{ mod?: ProjectPlatformModule; error?: string; untrusted?: boolean }> {+ if (trustGate && !trustGate(platformTrustId(file), file)) return { untrusted: true };try {// Cache-busted so editing the profile and re-opening the dialog picks it up// without restarting the editor.@@ -521,10 +551,18 @@ export async function listPlayableNetworks(root: string | null): Promise<Playabl.map((p) => ({ id: p.id, label: p.label, source: 'builtin' as const }));if (!root) return out;for (const file of await projectPlatformFiles(root)) {- const { mod, error } = await importPlatformModule(file);+ const { mod, error, untrusted } = await importPlatformModule(file);// A broken profile is NAMED rather than dropped — a project that wrote a file// and sees nothing cannot tell the difference between "not loaded" and "typo".+ // The same applies to one awaiting approval.const rel = posix(path.relative(root, file));+ if (untrusted) {+ const id = path.basename(file, '.mjs');+ if (!out.some((p) => p.id === id)) {+ out.push({ id, label: path.basename(file), source: 'project', file: rel, error: 'awaiting approval in the Plugins panel' });+ }+ continue;+ }if (error) {const id = path.basename(file, '.mjs');if (!out.some((p) => p.id === id)) out.push({ id, label: path.basename(file), source: 'project', file: rel, error });@@ -585,7 +623,17 @@ export async function listPlatforms(root: string | null, dirs: PlatformRuntimeDiif (!root) return out;for (const file of await projectPlatformFiles(root)) {- const { mod, error } = await importPlatformModule(file);+ const { mod, error, untrusted } = await importPlatformModule(file);+ if (untrusted) {+ out.push({+ id: path.basename(file, '.mjs'),+ source: 'project',+ ready: false,+ label: path.basename(file),+ needsTrust: true,+ });+ continue;+ }if (error || !mod) {out.push({id: path.basename(file, '.mjs'),diff --git a/desktop/electron/pluginHost.ts b/desktop/electron/pluginHost.tsindex df67f0e6b..d2f448523 100644--- a/desktop/electron/pluginHost.ts+++ b/desktop/electron/pluginHost.ts@@ -21,24 +21,19 @@* reload to be trustworthy.** 3. TRUST. A renderer plugin runs in the editor's own realm, so loading one is a- * decision only the user can make. Approval is keyed by `<id>@<version>` AND- * the folder it was approved from: publishing a new version re-asks, and so- * does a different folder claiming the same id.- *- * Deliberately NOT keyed by a hash of the code. That would re-prompt on every- * save, which is fatal to the loop of actually writing a plugin — and it buys- * little, since the threat model here is "code I did not write", not "code I- * just edited". This is the same bargain every extension ecosystem strikes:- * approval is per identity, and an update rides on it.+ * decision only the user can make. The record itself lives in pluginTrust.ts,+ * shared with the platform catalog so every kind of project-supplied code+ * passes one gate.** Pure Node apart from the userData path (injected), so it stays unit-testable.*/-import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { existsSync } from 'node:fs';import { readdir, readFile } from 'node:fs/promises';import path from 'node:path';import { loadEsbuild } from './esbuildRuntime';import { validateManifest, type PluginManifest } from '../src/plugins/manifest';import { PROJECT_PLUGIN_REL } from '../src/plugins/paths';+import { PROJECT_PLATFORM_DIR, platformTrustId } from './platformCatalog';/** Where a project keeps its own plugins (sibling of `.esengine/platforms/`),* resolved to this OS's separator from the one shared spelling. */@@ -49,11 +44,23 @@ export const USER_PLUGIN_DIR = 'plugins';/** Which scope a plugin was found in. Project shadows user on an id collision. */export type PluginScope = 'project' | 'user';+/**+ * What kind of project-supplied code an entry is.+ * - `plugin` — a folder with a plugin.json, compiled and run in the renderer.+ * - `project-platform` — a `.esengine/platforms/<id>.mjs` packaging profile,+ * imported into the MAIN process by the export pipeline. It has no activation+ * of its own; listing it here is what puts it behind the same trust gate and in+ * the same "what is this project asking the editor to run?" list.+ */+export type PluginKind = 'plugin' | 'project-platform';+/** What the renderer needs to list one plugin. Serializable by construction. */export interface DiscoveredPlugin {id: string;+ kind: PluginKind;scope: PluginScope;- /** Absolute plugin folder — shown in the UI and opened by "Reveal". */+ /** Absolute plugin folder — shown in the UI and opened by "Reveal". For a+ * project platform, the profile FILE (it has no folder of its own). */dir: string;/** Present when the manifest parsed and validated. */manifest?: PluginManifest;@@ -97,35 +104,75 @@ async function readPluginDir(dir: string, scope: PluginScope): Promise<Discovereconst pluginDir = path.join(dir, name);const manifestFile = path.join(pluginDir, 'plugin.json');if (!existsSync(manifestFile)) {- out.push({ id: name, scope, dir: pluginDir, error: 'folder has no plugin.json' });+ out.push({ id: name, kind: 'plugin', scope, dir: pluginDir, error: 'folder has no plugin.json' });continue;}try {const parsed: unknown = JSON.parse(await readFile(manifestFile, 'utf8'));const result = validateManifest(parsed);if ('error' in result) {- out.push({ id: name, scope, dir: pluginDir, error: result.error });+ out.push({ id: name, kind: 'plugin', scope, dir: pluginDir, error: result.error });} else {- out.push({ id: result.manifest.id, scope, dir: pluginDir, manifest: result.manifest });+ out.push({ id: result.manifest.id, kind: 'plugin', scope, dir: pluginDir, manifest: result.manifest });}} catch (e) {- out.push({ id: name, scope, dir: pluginDir, error: `plugin.json is not valid JSON (${String(e)})` });+ out.push({ id: name, kind: 'plugin', scope, dir: pluginDir, error: `plugin.json is not valid JSON (${String(e)})` });}}return out;}/**- * Every plugin visible right now, project scope first. A user plugin whose id a- * project plugin also claims is listed with `shadowedBy`, so the UI can explain- * why it isn't running instead of leaving the user wondering.+ * Project platform profiles, as entries in the same list. They are not plugins and+ * gain no lifecycle from being listed — the point is that "project code the editor+ * will run" is ONE list with ONE trust decision, and this is the most privileged+ * member of it (a main-process import, full Node).+ *+ * A synthesized manifest gives the row a name and version to display and to key+ * approval by; there is no plugin.json to read because the file form predates+ * plugins and keeping it is what spares every existing project a migration.+ */+async function readPlatformProfiles(root: string): Promise<DiscoveredPlugin[]> {+ const dir = path.join(root, PROJECT_PLATFORM_DIR);+ if (!existsSync(dir)) return [];+ let files: string[];+ try {+ files = (await readdir(dir)).filter((n) => n.endsWith('.mjs')).sort();+ } catch {+ return [];+ }+ return files.map((name) => {+ const file = path.join(dir, name);+ const id = platformTrustId(file);+ return {+ id,+ kind: 'project-platform' as const,+ scope: 'project' as const,+ dir: file,+ manifest: {+ id,+ name: `${path.basename(name, '.mjs')} (platform)`,+ version: '0.0.0',+ main: { node: name },+ capabilities: ['process'],+ },+ };+ });+}++/**+ * Every piece of project-supplied code visible right now, project scope first. A+ * user plugin whose id a project plugin also claims is listed with `shadowedBy`, so+ * the UI can explain why it isn't running instead of leaving the user wondering.*/export async function discoverPlugins(root: string | null, userDataDir: string): Promise<DiscoveredPlugin[]> {const project = root ? await readPluginDir(path.join(root, PROJECT_PLUGIN_DIR), 'project') : [];+ const platforms = root ? await readPlatformProfiles(root) : [];const user = await readPluginDir(path.join(userDataDir, USER_PLUGIN_DIR), 'user');const claimed = new Set(project.map((p) => p.id));return [...project,+ ...platforms,...user.map((p) => (claimed.has(p.id) ? { ...p, shadowedBy: 'project' as PluginScope } : p)),];}@@ -182,74 +229,9 @@ export async function compilePlugin(dir: string, entryRel: string): Promise<Comp}}-// =============================================================================-// Trust + enablement (per-user, in userData)-// =============================================================================--interface TrustFile {- /** `<id>@<version>` → the absolute folder it was approved from. */- trusted: Record<string, string>;- /** ids the user switched off (independent of trust). */- disabled: string[];-}--/** Approval identity: a version bump or a different folder re-asks. */-const trustKey = (id: string, version: string): string => `${id}@${version}`;--const EMPTY: TrustFile = { trusted: {}, disabled: [] };--const trustFile = (userDataDir: string): string => path.join(userDataDir, 'estella-plugin-trust.json');--function readTrust(userDataDir: string): TrustFile {- try {- const raw: unknown = JSON.parse(readFileSync(trustFile(userDataDir), 'utf8'));- const f = raw as Partial<TrustFile>;- return {- trusted: f.trusted && typeof f.trusted === 'object' ? f.trusted : {},- disabled: Array.isArray(f.disabled) ? f.disabled : [],- };- } catch {- return { ...EMPTY };- }-}--function writeTrust(userDataDir: string, next: TrustFile): void {- try {- writeFileSync(trustFile(userDataDir), `${JSON.stringify(next, null, 2)}\n`);- } catch {- /* read-only profile — trust simply won't persist this session */- }-}--/** Whether the user approved this plugin id + version, from this folder. */-export function isTrusted(userDataDir: string, id: string, version: string, dir: string): boolean {- return readTrust(userDataDir).trusted[trustKey(id, version)] === dir;-}--export function trustPlugin(userDataDir: string, id: string, version: string, dir: string): void {- const f = readTrust(userDataDir);- f.trusted[trustKey(id, version)] = dir;- writeTrust(userDataDir, f);-}--/** Withdraw approval for every version of a plugin; it stops loading until re-approved. */-export function revokeTrust(userDataDir: string, id: string): void {- const f = readTrust(userDataDir);- for (const key of Object.keys(f.trusted)) {- if (key.startsWith(`${id}@`)) delete f.trusted[key];- }- writeTrust(userDataDir, f);-}--export function isDisabled(userDataDir: string, id: string): boolean {- return readTrust(userDataDir).disabled.includes(id);-}--export function setPluginEnabled(userDataDir: string, id: string, enabled: boolean): void {- const f = readTrust(userDataDir);- const set = new Set(f.disabled);- if (enabled) set.delete(id);- else set.add(id);- f.disabled = [...set].sort();- writeTrust(userDataDir, f);-}+// Trust + enablement live in pluginTrust.ts — shared with the project platform+// catalog, which imports project code into the MAIN process and must pass the same+// gate. Re-exported here so the plugin-facing call sites read as one host API.+export {+ isTrusted, trustPlugin, revokeTrust, isDisabled, setPluginEnabled,+} from './pluginTrust';diff --git a/desktop/electron/pluginTrust.ts b/desktop/electron/pluginTrust.tsnew file mode 100644index 000000000..934f3975b--- /dev/null+++ b/desktop/electron/pluginTrust.ts@@ -0,0 +1,90 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The record of which project-supplied code the user approved.+ *+ * Its own module because there is more than one kind of such code, and they must+ * share ONE gate: an editor plugin (renderer or node entry) and a project platform+ * profile are both "code this project asked the editor to run". A platform profile+ * is in fact the more privileged of the two — it is imported into the MAIN process,+ * with full Node — so gating the plugin while leaving that open would have the+ * protection exactly backwards.+ *+ * Approval is keyed by `<id>@<version>` AND the folder it was approved from: a new+ * version re-asks, and so does a different folder claiming the same id. Deliberately+ * NOT keyed by a hash of the code — that would re-prompt on every save, which is+ * fatal to actually writing a plugin, and the threat model here is "code I did not+ * write", not "code I just edited".+ *+ * Pure Node apart from the userData path (injected), so it stays unit-testable.+ */+import { readFileSync, writeFileSync } from 'node:fs';+import path from 'node:path';++interface TrustFile {+ /** `<id>@<version>` → the absolute folder it was approved from. */+ trusted: Record<string, string>;+ /** ids the user switched off (independent of trust). */+ disabled: string[];+}++const EMPTY: TrustFile = { trusted: {}, disabled: [] };++const trustFile = (userDataDir: string): string => path.join(userDataDir, 'estella-plugin-trust.json');++/** Approval identity. A profile with no version of its own passes `''`. */+const trustKey = (id: string, version: string): string => `${id}@${version}`;++function readTrust(userDataDir: string): TrustFile {+ try {+ const raw: unknown = JSON.parse(readFileSync(trustFile(userDataDir), 'utf8'));+ const f = raw as Partial<TrustFile>;+ return {+ trusted: f.trusted && typeof f.trusted === 'object' ? f.trusted : {},+ disabled: Array.isArray(f.disabled) ? f.disabled : [],+ };+ } catch {+ return { ...EMPTY };+ }+}++function writeTrust(userDataDir: string, next: TrustFile): void {+ try {+ writeFileSync(trustFile(userDataDir), `${JSON.stringify(next, null, 2)}\n`);+ } catch {+ /* read-only profile — trust simply won't persist this session */+ }+}++/** Whether the user approved this id + version, from this folder. */+export function isTrusted(userDataDir: string, id: string, version: string, dir: string): boolean {+ return readTrust(userDataDir).trusted[trustKey(id, version)] === dir;+}++export function trustPlugin(userDataDir: string, id: string, version: string, dir: string): void {+ const f = readTrust(userDataDir);+ f.trusted[trustKey(id, version)] = dir;+ writeTrust(userDataDir, f);+}++/** Withdraw approval for every version of an id; it stops loading until re-approved. */+export function revokeTrust(userDataDir: string, id: string): void {+ const f = readTrust(userDataDir);+ for (const key of Object.keys(f.trusted)) {+ if (key.startsWith(`${id}@`)) delete f.trusted[key];+ }+ writeTrust(userDataDir, f);+}++export function isDisabled(userDataDir: string, id: string): boolean {+ return readTrust(userDataDir).disabled.includes(id);+}++export function setPluginEnabled(userDataDir: string, id: string, enabled: boolean): void {+ const f = readTrust(userDataDir);+ const set = new Set(f.disabled);+ if (enabled) set.delete(id);+ else set.add(id);+ f.disabled = [...set].sort();+ writeTrust(userDataDir, f);+}diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 0bf2f057c..9a4a9abd8 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -210,6 +210,9 @@ const api = {/** Compile a plugin's renderer entry and report whether the user approved this* id+version from this folder. Compiling never runs the plugin. */load: (id: string): Promise<CompiledPlugin & { trusted: boolean }> => ipcRenderer.invoke('plugins:load', id),+ /** Whether this entry is approved, without compiling anything — a project+ * platform profile has no renderer entry to build. */+ trustState: (id: string): Promise<boolean> => ipcRenderer.invoke('plugins:trustState', id),/** Record the user's approval; main resolves the version + folder it applies to. */trust: (id: string): Promise<void> => ipcRenderer.invoke('plugins:trust', id),revokeTrust: (id: string): Promise<void> => ipcRenderer.invoke('plugins:revokeTrust', id),diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsxindex ce9664c99..da560ace5 100644--- a/desktop/src/components/BuildDialog.tsx+++ b/desktop/src/components/BuildDialog.tsx@@ -256,7 +256,9 @@ export function BuildDialog() {ready: r.ready,category: 'custom',custom: true,- loadError: r.error,+ // An unapproved profile was NOT imported, so say why rather than+ // showing an unexplained not-ready row.+ loadError: r.needsTrust ? t('build.platformNeedsTrust') : r.error,icon: <Package size={17} />,blurb: r.blurb ?? t('build.customHint'),defaultOut: r.defaultOut ?? `dist-${r.id}`,diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex 3fd60be04..868ce3a6d 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -56,6 +56,10 @@ export const projectMessages = defineMessages({'build.copyCommand': { en: 'Copy command', zh: '复制命令' },'build.copied': { en: 'Copied', zh: '已复制' },'build.platformBroken': { en: 'This platform profile failed to load', zh: '该平台配置加载失败' },+ 'build.platformNeedsTrust': {+ en: 'Not approved yet — this profile runs with full system access. Approve it in the Plugins panel.',+ zh: '尚未批准 —— 该配置以完整系统权限运行。请在插件面板中批准。',+ },'build.customHint': {en: 'Defined by this project in .esengine/platforms/ — it rides the same mini-game pipeline as the built-in targets.',zh: '由本项目在 .esengine/platforms/ 中定义,与内置目标走同一条小游戏导出管线。',diff --git a/desktop/src/plugins/PluginHost.ts b/desktop/src/plugins/PluginHost.tsindex 039329e71..1fdf9eab1 100644--- a/desktop/src/plugins/PluginHost.ts+++ b/desktop/src/plugins/PluginHost.ts@@ -65,6 +65,9 @@ export interface PluginRecord {name: string;description: string;version: string;+ /** What kind of project-supplied code this is. A `project-platform` row has no+ * activation — approving it only permits the export pipeline to import it. */+ kind: 'plugin' | 'project-platform';scope: 'project' | 'user';dir: string;phase: PluginPhase;@@ -131,12 +134,6 @@ class PluginHostImpl {this.changed();}- /**- * Wrap a plugin callback. Returns `fallback` if it throws, so the caller — a- * menu building its rows, a panel mounting — is never broken by a plugin bug.- * Timed through PerfMonitor so a slow plugin shows up in the profiler beside the- * editor's own work, under `plugin.<id>.<what>`.- *//*** Run one overlay's per-frame draw. Exposed because the overlay renderer's rAF* calls plugin code directly, and a throw there must be attributed and counted@@ -146,6 +143,12 @@ class PluginHostImpl {this.guard(id, 'overlay render', draw, undefined);}+ /**+ * Wrap a plugin callback. Returns `fallback` if it throws, so the caller — a+ * menu building its rows, a panel mounting — is never broken by a plugin bug.+ * Timed through PerfMonitor so a slow plugin shows up in the profiler beside the+ * editor's own work, under `plugin.<id>.<what>`.+ */private guard<T>(id: string, what: string, fn: () => T, fallback: T): T {try {return PerfMonitor.measure(`plugin.${id}.${what}`, fn);@@ -193,6 +196,7 @@ class PluginHostImpl {name,description: manifest ? resolveLocalized(manifest.description, editorLocale) : '',version: manifest?.version ?? '',+ kind: p.kind,scope: p.scope,dir: p.dir,phase: 'discovered',@@ -225,6 +229,19 @@ class PluginHostImpl {continue;}}+ // A platform profile is not activated — approving it only permits the export+ // pipeline to import it, so its phase IS its trust state and there is nothing+ // to compile, evaluate, or reload.+ if (p.kind === 'project-platform') {+ const trusted = await window.estella.plugins.trustState(p.id);+ this.records.set(p.id, {+ ...base,+ phase: trusted ? 'active' : 'needs-trust',+ detail: trusted ? undefined : 'imported by the export pipeline with full system access',+ });+ continue;+ }+const changed = force.has(dirName(p.dir));// Already running and unchanged — leave it alone (refresh is idempotent).if (!changed && this.loaded.has(p.id) && this.records.get(p.id)?.phase === 'active') continue;diff --git a/desktop/tests/platform-trust.test.ts b/desktop/tests/platform-trust.test.tsnew file mode 100644index 000000000..ca6fe8125--- /dev/null+++ b/desktop/tests/platform-trust.test.ts@@ -0,0 +1,122 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The trust gate on project platform profiles.+ *+ * These profiles are `await import()`ed into the MAIN process with full Node — the+ * most privileged thing a project can ask the editor to run, and for a long time the+ * only one with no approval step while renderer plugins had one. The gate closes+ * that; these tests pin the two halves that matter: an unapproved profile is NOT+ * imported, and it is still REPORTED so the user can find out it exists.+ */+import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import {+ listPlatforms, listPlayableNetworks, loadProjectPlatform, setPlatformTrustGate,+ platformTrustId, PROJECT_PLATFORM_DIR,+} from '../electron/platformCatalog';+import { discoverPlugins } from '../electron/pluginHost';++let root: string;+let userData: string;+const dirs = { web: '/nonexistent-web', wechat: '/nonexistent-wechat' };++/** Set by a loaded profile, so a test can prove whether the import actually ran. */+const IMPORT_MARKER = 'estella-platform-trust-test-imported';++beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-platform-'));+ userData = mkdtempSync(path.join(tmpdir(), 'estella-userdata-'));+ mkdirSync(path.join(root, PROJECT_PLATFORM_DIR), { recursive: true });+ writeFileSync(+ path.join(root, PROJECT_PLATFORM_DIR, 'acme.mjs'),+ `globalThis[${JSON.stringify(IMPORT_MARKER)}] = (globalThis[${JSON.stringify(IMPORT_MARKER)}] ?? 0) + 1;\n` ++ `export default { id: 'acme', label: 'Acme', emitConfigFiles: () => [] };\n`,+ );+});++afterAll(() => {+ setPlatformTrustGate(null);+ rmSync(root, { recursive: true, force: true });+ rmSync(userData, { recursive: true, force: true });+});++afterEach(() => {+ setPlatformTrustGate(null);+ delete (globalThis as Record<string, unknown>)[IMPORT_MARKER];+});++const acmeRow = async () => (await listPlatforms(root, dirs)).find((p) => p.id === 'acme');++describe('project platform trust gate', () => {+ it('does not import an unapproved profile', async () => {+ setPlatformTrustGate(() => false);+ const row = await acmeRow();++ expect(row?.needsTrust).toBe(true);+ expect(row?.ready).toBe(false);+ // The label is the FILE name, not the profile's own — proof the module body+ // never ran. This is the assertion that actually catches a bypass.+ expect(row?.label).toBe('acme.mjs');+ expect((globalThis as Record<string, unknown>)[IMPORT_MARKER]).toBeUndefined();+ });++ it('imports an approved profile and uses its own metadata', async () => {+ setPlatformTrustGate(() => true);+ const row = await acmeRow();++ expect(row?.needsTrust).toBeUndefined();+ expect(row?.label).toBe('Acme');+ expect((globalThis as Record<string, unknown>)[IMPORT_MARKER]).toBe(1);+ });++ it('keeps reporting an unapproved profile rather than hiding it', async () => {+ setPlatformTrustGate(() => false);+ // Silently dropping it would leave the user unable to tell "I never wrote it"+ // from "the editor refused to run it".+ expect(await acmeRow()).toBeDefined();++ const networks = await listPlayableNetworks(root);+ const acme = networks.find((n) => n.id === 'acme');+ expect(acme?.error).toMatch(/approval/i);+ });++ it('refuses to resolve an unapproved profile for an actual export', async () => {+ setPlatformTrustGate(() => false);+ // The listing is cosmetic; THIS is the path that would have run the code.+ expect(await loadProjectPlatform(root, 'acme', dirs)).toBeNull();+ expect((globalThis as Record<string, unknown>)[IMPORT_MARKER]).toBeUndefined();++ setPlatformTrustGate(() => true);+ expect(await loadProjectPlatform(root, 'acme', dirs)).not.toBeNull();+ });++ it('gates on the id the Plugins panel approves under', async () => {+ const seen: string[] = [];+ setPlatformTrustGate((id) => {+ seen.push(id);+ return false;+ });+ await acmeRow();+ // The panel records approval under this id, so the gate must ask for the same one.+ expect(seen).toContain(platformTrustId(path.join(root, PROJECT_PLATFORM_DIR, 'acme.mjs')));+ expect(seen[0]).toBe('platform.acme');+ });++ it('lists the profile as project-supplied code alongside plugins', async () => {+ const found = await discoverPlugins(root, userData);+ const entry = found.find((p) => p.id === 'platform.acme');+ expect(entry?.kind).toBe('project-platform');+ expect(entry?.scope).toBe('project');+ // A synthesized manifest gives the row something to display and to key approval by.+ expect(entry?.manifest?.version).toBe('0.0.0');+ expect(entry?.manifest?.capabilities).toContain('process');+ });++ it('leaves the catalog ungated when no gate is installed (unit-test posture)', async () => {+ const row = await acmeRow();+ expect(row?.label).toBe('Acme');+ });+});