From 57b9b8463b62b35308b2ceb192121dd092cf4a19 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Mon, 16 Nov 2026 17:52:55 +0100 Subject: [PATCH] :bug: Keep app booting when SES bootstrap fails (#13085) * :bug: Keep app booting when SES bootstrap fails Wrap repairIntrinsics in a guarded bootstrap so a SES Temporal check failure no longer aborts bundle evaluation and blanks the whole app. When it fails, plugins and MCP stay unavailable for that session, a telemetry event reports the error, and trying to open a plugin shows an environment warning. Add vitest coverage for both bootstrap paths and a CLJS regression test for the runtime-unavailable toast. Closes #12924 AI-assisted-by: hy4-flash-free * :bug: Fix CI format check and plugin test entry point Wrap the long Prettier line in bootstrap.spec.ts so `pnpm run format:check` passes again in the plugins module, and document that the duplicated SES options are an intentional contract snapshot. Switch the runtime-unavailable CLJS test to the public open-plugin! entry point instead of the private load-plugin! function. The M2 test for signal-runtime-ready was dropped: loading app.plugins in the Node test runner needs packaging and DOM shim changes outside this fix. Closes #12924 AI-assisted-by: hy4-flash-free --- .../frontend/plugin-api-to-cljs-binding.md | 3 + .serena/memories/plugins/core.md | 1 + frontend/src/app/main/data/plugins.cljs | 3 +- frontend/src/app/plugins.cljs | 23 ++- .../plugins/runtime_unavailable_test.cljs | 57 ++++++++ frontend/test/frontend_tests/runner.cljs | 2 + frontend/translations/en.po | 7 + frontend/translations/es.po | 7 + plugins/CHANGELOG.md | 6 + plugins/libs/plugins-runtime/src/index.ts | 25 ++-- .../plugins-runtime/src/lib/bootstrap.spec.ts | 131 ++++++++++++++++++ .../libs/plugins-runtime/src/lib/bootstrap.ts | 27 ++++ 12 files changed, 279 insertions(+), 13 deletions(-) create mode 100644 frontend/test/frontend_tests/plugins/runtime_unavailable_test.cljs create mode 100644 plugins/libs/plugins-runtime/src/lib/bootstrap.spec.ts create mode 100644 plugins/libs/plugins-runtime/src/lib/bootstrap.ts diff --git a/.serena/memories/frontend/plugin-api-to-cljs-binding.md b/.serena/memories/frontend/plugin-api-to-cljs-binding.md index 8536ad245c..e6f3fef853 100644 --- a/.serena/memories/frontend/plugin-api-to-cljs-binding.md +++ b/.serena/memories/frontend/plugin-api-to-cljs-binding.md @@ -15,6 +15,9 @@ ## Runtime initialization and permissions - The frontend initializes `@penpot/plugins-runtime` only after `features/initialize` and only when feature `plugins/runtime` is active. It also installs the runtime `isPluginError` predicate into frontend error handling. +- `app.plugins/init-plugins-runtime` returns whether `ɵloadPlugin` was installed. It calls `preg/signal-runtime-ready` even on failure: `workspace.cljs` waits on that promise before `mcp/init`, so skipping it hangs MCP initialization forever. +- When SES bootstrap fails, `app.plugins` emits one `plugins-runtime-unavailable` telemetry event (with the SES error message), and `app.main.data.plugins/load-plugin!` shows the lazy `plugins.runtime-unavailable` toast when the user opens a plugin. `start-plugin!` (MCP path) stays silent by design. +- Runtime availability is detected by the existing `(fn? (unchecked-get global "ɵloadPlugin"))` check; do not add a second mechanism. - Manifest parsing expands write permissions to read permissions (`content:write` => `content:read`, etc.). Permission checks also allow the all-zero plugin id and the hard-coded MCP plugin id. - Manifest URL origin differs by manifest version: v1 clears the path; v2 joins `.` to the plugin URL. Existing plugin ids are reused by matching manifest name and host. - The MCP plugin id is defined in `app.plugins.register` to avoid a circular dependency with workspace MCP code. diff --git a/.serena/memories/plugins/core.md b/.serena/memories/plugins/core.md index 64f4643860..16ec5165bf 100644 --- a/.serena/memories/plugins/core.md +++ b/.serena/memories/plugins/core.md @@ -18,6 +18,7 @@ ## Sandbox and global cleanup +- `src/index.ts` calls `bootstrapSES()` (in `src/lib/bootstrap.ts`) at module load. If `repairIntrinsics` throws (e.g. SES 2.2+ rejects a `Temporal` wrapped by a browser extension), the error is caught, `getPluginsRuntimeError()` exposes it, and `initPluginsRuntime` installs no `ɵ*` globals: the frontend app still boots, plugins and MCP are unavailable in that environment. On failure, `Function.prototype.toString` has already been replaced but no intrinsics are hardened and no compartment/sandbox is created — never run plugins on that path. - The runtime uses SES compartments. Public API return values are passed through `ses.safeReturn` before crossing back to plugin code. - Plugin `fetch` is sanitized: credentials are omitted and Authorization is blanked. The exposed response only includes ok/status/statusText/url/text/json. - Timer callbacks are wrapped to mark plugin-originated errors, and timeout/interval IDs are tracked so plugin close can clear them. diff --git a/frontend/src/app/main/data/plugins.cljs b/frontend/src/app/main/data/plugins.cljs index 33d898cf69..61154aa4a3 100644 --- a/frontend/src/app/main/data/plugins.cljs +++ b/frontend/src/app/main/data/plugins.cljs @@ -109,7 +109,8 @@ (log/warn :hint "Plugin runtime not initialized yet" :plugin-id plugin-id :action "load-plugin!") - (st/emit! (remove-current-plugin plugin-id)))))) + (st/emit! (remove-current-plugin plugin-id) + (ntf/warn (tr "plugins.runtime-unavailable"))))))) (defn open-plugin! [{:keys [url] :as manifest} user-can-edit?] diff --git a/frontend/src/app/plugins.cljs b/frontend/src/app/plugins.cljs index 921cf740b9..f10e4213d4 100644 --- a/frontend/src/app/plugins.cljs +++ b/frontend/src/app/plugins.cljs @@ -8,6 +8,7 @@ "RPC for plugins runtime." (:require ["@penpot/plugins-runtime" :as runtime] + [app.main.data.event :as ev] [app.main.errors :as errors] [app.main.features :as features] [app.main.store :as st] @@ -20,14 +21,26 @@ [app.plugins.register :as preg] [app.plugins.ruler-guides :as rg] [app.plugins.shape :as shape] + [app.util.globals :as ug] [beicon.v2.core :as rx] [potok.v2.core :as ptk])) +(defn- runtime-available? + [] + (fn? (unchecked-get ug/global "ɵloadPlugin"))) + (defn init-plugins-runtime [] (runtime/initPluginsRuntime (fn [plugin-id] (api/create-context plugin-id))) - ;; Signal that runtime is ready - (preg/signal-runtime-ready)) + ;; Signal even when the runtime failed to start: MCP initialization waits + ;; for this promise and would otherwise hang forever. + (preg/signal-runtime-ready) + (runtime-available?)) + +(defn- runtime-unavailable-event + [] + (ev/event {::ev/name "plugins-runtime-unavailable" + :message (some-> (runtime/getPluginsRuntimeError) .-message)})) (defn initialize [] @@ -41,8 +54,10 @@ (rx/observe-on :async) (rx/filter #(features/active-feature? @st/state "plugins/runtime")) (rx/take 1) - (rx/tap init-plugins-runtime) - (rx/ignore))))) + (rx/map (fn [_] + (when-not (init-plugins-runtime) + (runtime-unavailable-event)))) + (rx/filter some?))))) ;; Prevent circular dependency (set! flex/shape-proxy? shape/shape-proxy?) diff --git a/frontend/test/frontend_tests/plugins/runtime_unavailable_test.cljs b/frontend/test/frontend_tests/plugins/runtime_unavailable_test.cljs new file mode 100644 index 0000000000..1c2d16bc56 --- /dev/null +++ b/frontend/test/frontend_tests/plugins/runtime_unavailable_test.cljs @@ -0,0 +1,57 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS SUBSIDIARY SL + +(ns frontend-tests.plugins.runtime-unavailable-test + (:require + [app.main.data.plugins :as dp] + [app.main.store :as st] + [app.util.globals :as ug] + [app.util.object :as obj] + [cljs.test :as t :include-macros true] + [frontend-tests.helpers.mock :as mock] + [potok.v2.core :as ptk] + [promesa.core :as p])) + +(def ^:private test-manifest + {:plugin-id "test-plugin" + :name "Test plugin" + :description "A plugin used by the runtime availability tests" + :host "https://example.com" + :code ""}) + +(defn- with-load-plugin + "Calls dp/open-plugin! with a mocked st/emit! and the given ɵloadPlugin + value on the global object, returning the emitted events." + [load-plugin-fn] + (let [global ug/global + had-plugin? (obj/contains? global "ɵloadPlugin") + previous (obj/get global "ɵloadPlugin") + emitted (atom [])] + (if (fn? load-plugin-fn) + (obj/set! global "ɵloadPlugin" load-plugin-fn) + (obj/unset! global "ɵloadPlugin")) + (-> (mock/with-mocks* + {st/emit! (fn [event & events] (swap! emitted into (cons event events)))} + (dp/open-plugin! test-manifest nil)) + (p/then (fn [_] @emitted)) + (p/finally (fn [] + (if had-plugin? + (obj/set! global "ɵloadPlugin" previous) + (obj/unset! global "ɵloadPlugin"))))))) + +(t/deftest ^:async load-plugin-notifies-when-runtime-is-unavailable + (let [emitted (await (with-load-plugin nil)) + types (mapv ptk/type emitted)] + (t/is (some #{:app.main.data.notifications/show} types) + "emits a notification when the plugin runtime is unavailable") + (t/is (some #{::dp/remove-current-plugin} types) + "still removes the plugin from the open list"))) + +(t/deftest ^:async load-plugin-does-not-notify-when-runtime-is-available + (let [emitted (await (with-load-plugin (fn [_ _] (p/resolved nil)))) + types (mapv ptk/type emitted)] + (t/is (not-any? #{:app.main.data.notifications/show} types) + "does not emit a notification when the plugin runtime is available"))) diff --git a/frontend/test/frontend_tests/runner.cljs b/frontend/test/frontend_tests/runner.cljs index 33f4b6f4f8..3bea068a6b 100644 --- a/frontend/test/frontend_tests/runner.cljs +++ b/frontend/test/frontend_tests/runner.cljs @@ -83,6 +83,7 @@ [frontend-tests.plugins.page-test] [frontend-tests.plugins.parser-test] [frontend-tests.plugins.register-test] + [frontend-tests.plugins.runtime-unavailable-test] [frontend-tests.plugins.shape-bugfixes-test] [frontend-tests.plugins.text-test] [frontend-tests.plugins.tokens-test] @@ -239,6 +240,7 @@ 'frontend-tests.plugins.page-test 'frontend-tests.plugins.parser-test 'frontend-tests.plugins.register-test + 'frontend-tests.plugins.runtime-unavailable-test 'frontend-tests.plugins.shape-bugfixes-test 'frontend-tests.plugins.text-test 'frontend-tests.plugins.tokens-test diff --git a/frontend/translations/en.po b/frontend/translations/en.po index 861862dcc3..10e0dbf6bd 100644 --- a/frontend/translations/en.po +++ b/frontend/translations/en.po @@ -4709,6 +4709,13 @@ msgstr "Start designing" msgid "options.deleted-token-with-name" msgstr "{%s} token does not exist or has been deleted." +#: src/app/main/data/plugins.cljs:113 +msgid "plugins.runtime-unavailable" +msgstr "" +"Plugins are unavailable in this browser. Something in your environment (for " +"example, an extension such as Tampermonkey) is preventing the plugin " +"runtime from starting. Disable extensions or reload the page to try again." + #: src/app/plugins/utils.cljs:555 msgid "plugins.validation.invalid-value" msgstr "expected %s, got %s (%s)" diff --git a/frontend/translations/es.po b/frontend/translations/es.po index 5ebc56901b..14a849f6af 100644 --- a/frontend/translations/es.po +++ b/frontend/translations/es.po @@ -4763,6 +4763,13 @@ msgstr "Empezar a diseñar" msgid "options.deleted-token-with-name" msgstr "El token {%s} no existe o ha sido borrado." +#: src/app/main/data/plugins.cljs:113 +msgid "plugins.runtime-unavailable" +msgstr "" +"Los plugins no están disponibles en este navegador. Algo en tu entorno (por " +"ejemplo, una extensión como Tampermonkey) impide que se inicie el entorno de " +"plugins. Desactiva las extensiones o vuelve a cargar la página." + #: src/app/plugins/utils.cljs:555 msgid "plugins.validation.invalid-value" msgstr "esperado %s, obtenido %s (%s)" diff --git a/plugins/CHANGELOG.md b/plugins/CHANGELOG.md index 8322c3a1f6..5303e424a5 100644 --- a/plugins/CHANGELOG.md +++ b/plugins/CHANGELOG.md @@ -1,3 +1,9 @@ +## 1.6.1 (Unreleased) + +### 🩹 Fixes + +- **plugins-runtime:** A SES `repairIntrinsics` failure at startup (for example, when a browser extension wraps the native `Temporal` global) no longer leaves the whole app blank. Plugins are skipped for that session, the error is logged, and a telemetry event reports the unavailable runtime; the editor, login and sign-up pages load as usual. Plugins work as before in every other environment. When startup fails, SES has already replaced `Function.prototype.toString` in the host realm before throwing, but no intrinsics are hardened and no sandbox is created. Closes #12924. + ## 1.6.0 (2026-11-10) ### 🚀 Features diff --git a/plugins/libs/plugins-runtime/src/index.ts b/plugins/libs/plugins-runtime/src/index.ts index a38203471d..ecb69143b9 100644 --- a/plugins/libs/plugins-runtime/src/index.ts +++ b/plugins/libs/plugins-runtime/src/index.ts @@ -1,6 +1,7 @@ import 'ses'; import './lib/modal/plugin-modal'; +import { bootstrapSES } from './lib/bootstrap.js'; import { ɵloadPlugin, setContextBuilder, @@ -15,19 +16,27 @@ import type { Context } from '@penpot/plugin-types'; console.log('%c[PLUGINS] Loading plugin system', 'color: #008d7c'); -repairIntrinsics({ - evalTaming: 'unsafeEval', - stackFiltering: 'verbose', - errorTaming: 'unsafe', - consoleTaming: 'unsafe', - errorTrapping: 'none', - unhandledRejectionTrapping: 'none', -}); +const sesError = bootstrapSES(); + +if (sesError) { + console.error( + '[PLUGINS] SES bootstrap failed; plugins disabled in this environment.', + sesError, + ); +} + +/** Returns the SES bootstrap error, or null when the runtime can be used. */ +export const getPluginsRuntimeError = (): Error | null => sesError; // eslint-disable-next-line @typescript-eslint/no-explicit-any const globalThisAny$ = globalThis as any; export const initPluginsRuntime = (contextBuilder: (id: string) => Context) => { + if (sesError) { + console.error('[PLUGINS] Skipping plugin runtime initialization.'); + return; + } + try { console.log('%c[PLUGINS] Initialize runtime', 'color: #008d7c'); setContextBuilder(contextBuilder); diff --git a/plugins/libs/plugins-runtime/src/lib/bootstrap.spec.ts b/plugins/libs/plugins-runtime/src/lib/bootstrap.spec.ts new file mode 100644 index 0000000000..d77b3e0803 --- /dev/null +++ b/plugins/libs/plugins-runtime/src/lib/bootstrap.spec.ts @@ -0,0 +1,131 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { bootstrapSES } from './bootstrap.js'; + +// Intentional snapshot of the production options in bootstrap.ts: if they +// change, this test must fail. Do not replace this literal with an import. +const REPAIR_OPTIONS = { + evalTaming: 'unsafeEval', + stackFiltering: 'verbose', + errorTaming: 'unsafe', + consoleTaming: 'unsafe', + errorTrapping: 'none', + unhandledRejectionTrapping: 'none', +}; + +const temporalError = () => + new TypeError('unexpected Temporal __proto__: [object Object]'); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.doUnmock('ses'); + vi.doUnmock('./modal/plugin-modal'); + vi.resetModules(); +}); + +describe('bootstrapSES', () => { + it('repairs intrinsics with the production options and reports success', () => { + const repair = vi.fn(); + vi.stubGlobal('repairIntrinsics', repair); + + expect(bootstrapSES()).toBeNull(); + expect(repair).toHaveBeenCalledWith(REPAIR_OPTIONS); + }); + + it('returns the SES error instead of throwing it', () => { + const error = temporalError(); + vi.stubGlobal('repairIntrinsics', () => { + throw error; + }); + + expect(bootstrapSES()).toBe(error); + }); +}); + +describe('plugins runtime entry point', () => { + it('installs the runtime globals when SES bootstrap succeeds', async () => { + const globalAny = globalThis as unknown as Record; + const context = { theme: 'dark' }; + const runtimeKeys = [ + 'ɵcontext', + 'ɵloadPlugin', + 'ɵloadPluginByUrl', + 'ɵunloadPlugin', + ]; + const previous = runtimeKeys.map((key) => globalAny[key]); + + vi.stubGlobal('repairIntrinsics', vi.fn()); + vi.doMock('ses', () => ({})); + // The custom element is registered at module load; mock it so repeated + // entry-point imports do not redefine it in the same jsdom registry. + vi.doMock('./modal/plugin-modal', () => ({})); + vi.resetModules(); + + try { + const runtime = await import('../index.js'); + runtime.initPluginsRuntime(() => context as never); + + expect(runtime.getPluginsRuntimeError()).toBeNull(); + expect(globalAny['ɵcontext']).toBe(context); + expect(typeof globalAny['ɵloadPlugin']).toBe('function'); + expect(typeof globalAny['ɵloadPluginByUrl']).toBe('function'); + expect(typeof globalAny['ɵunloadPlugin']).toBe('function'); + } finally { + for (const [index, key] of runtimeKeys.entries()) { + if (previous[index] === undefined) { + delete globalAny[key]; + } else { + globalAny[key] = previous[index]; + } + } + } + }); + + it('loads with a broken SES bootstrap without installing runtime globals', async () => { + const error = temporalError(); + const globalAny = globalThis as unknown as Record; + const runtimeKeys = [ + 'ɵcontext', + 'ɵloadPlugin', + 'ɵloadPluginByUrl', + 'ɵunloadPlugin', + ]; + const previous = runtimeKeys.map((key) => globalAny[key]); + + vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.stubGlobal('repairIntrinsics', () => { + throw error; + }); + // Keep the stub in place: `import 'ses'` in index.ts would otherwise + // install a new repairIntrinsics global before bootstrap runs. + vi.doMock('ses', () => ({})); + // The custom element is registered at module load; mock it so repeated + // entry-point imports do not redefine it in the same jsdom registry. + vi.doMock('./modal/plugin-modal', () => ({})); + vi.resetModules(); + + try { + for (const key of runtimeKeys) { + delete globalAny[key]; + } + + const runtime = await import('../index.js'); + + expect(runtime.getPluginsRuntimeError()).toBe(error); + expect(() => + runtime.initPluginsRuntime(() => ({}) as never), + ).not.toThrow(); + for (const key of runtimeKeys) { + expect(globalAny[key]).toBeUndefined(); + } + } finally { + for (const [index, key] of runtimeKeys.entries()) { + if (previous[index] === undefined) { + delete globalAny[key]; + } else { + globalAny[key] = previous[index]; + } + } + } + }); +}); diff --git a/plugins/libs/plugins-runtime/src/lib/bootstrap.ts b/plugins/libs/plugins-runtime/src/lib/bootstrap.ts new file mode 100644 index 0000000000..0057f0f413 --- /dev/null +++ b/plugins/libs/plugins-runtime/src/lib/bootstrap.ts @@ -0,0 +1,27 @@ +/** + * Repairs the JavaScript intrinsics needed by the SES sandbox. + * + * SES can throw during this step when the host page already contains a + * `Temporal` global it does not recognize (for example, one wrapped by a + * browser extension). The exception happens at module load time in + * `index.ts`, so an uncaught failure here takes down the whole app. + * + * Returns the caught error so callers can report it and disable plugins, + * instead of propagating it to the bundle loader. + */ +export function bootstrapSES(): Error | null { + try { + repairIntrinsics({ + evalTaming: 'unsafeEval', + stackFiltering: 'verbose', + errorTaming: 'unsafe', + consoleTaming: 'unsafe', + errorTrapping: 'none', + unhandledRejectionTrapping: 'none', + }); + + return null; + } catch (err) { + return err instanceof Error ? err : new Error(String(err)); + } +}