Merge branch 'staging-2.19.x' into staging

This commit is contained in:
Andrey Antukh 2026-11-17 10:16:51 +01:00
commit 94155508e5
14 changed files with 277 additions and 44 deletions

View File

@ -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.

View File

@ -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.

View File

@ -2330,13 +2330,13 @@
(let [shapes' (filterv #(contains? objects %) shapes)]
(when (not= shapes shapes')
(l/trc :hint "fix dangling children"
:container container-id
:shape-id (:id shape)
:container (str container-id)
:shape-id (str (:id shape))
:removed (remove #(contains? objects %) shapes)))
shapes'))))
(fix-objects [container-id objects]
(update-vals objects (partial fix-shape container-id objects)))
(d/update-vals objects (partial fix-shape container-id objects)))
(update-container [container]
(d/update-when container :objects #(fix-objects (:id container) %)))]

View File

@ -125,7 +125,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?]

View File

@ -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?)

View File

@ -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")))

View File

@ -103,6 +103,7 @@
[frontend-tests.plugins.parser-test]
[frontend-tests.plugins.read-only-test]
[frontend-tests.plugins.register-test]
[frontend-tests.plugins.runtime-unavailable-test]
[frontend-tests.plugins.shape-bugfixes-test]
[frontend-tests.plugins.system-events-test]
[frontend-tests.plugins.text-test]
@ -309,6 +310,7 @@
'frontend-tests.plugins.parser-test
'frontend-tests.plugins.read-only-test
'frontend-tests.plugins.register-test
'frontend-tests.plugins.runtime-unavailable-test
'frontend-tests.plugins.shape-bugfixes-test
'frontend-tests.plugins.system-events-test
'frontend-tests.plugins.text-test

View File

@ -4963,6 +4963,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:129
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:579
msgid "plugins.validation.invalid-value"
msgstr "expected %s, got %s (%s)"

View File

@ -5013,6 +5013,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:129
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:579
msgid "plugins.validation.invalid-value"
msgstr "esperado %s, obtenido %s (%s)"

View File

@ -18,6 +18,7 @@
- **plugins-runtime:** `Shape.componentRoot()` returns the root of the shape's own component tree. It used to return a shape that pointed at nothing when the copy was on another page or file than its main, and threw when the copy's library was not available.
- **plugins-runtime:** `LibraryComponent.mainInstance()` returns `null` for a deleted component, instead of a shape with an empty `id` whose `parent` throws.
- **plugins-runtime**: `TokenFontFamilies.resolvedValue` and the `fontFamilies` member of `TokenTypographyValue` now keep a family whose name has several words (`Hanken Grotesk`) as one entry, instead of splitting it into an array of its words, and keep names with words the resolver would otherwise read as colors or numbers (`Red Hat Display`, `Press Start 2P`) unchanged.
- **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)

View File

@ -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);

View File

@ -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<string, unknown>;
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<string, unknown>;
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];
}
}
}
});
});

View File

@ -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));
}
}

View File

@ -1,28 +0,0 @@
How to trace a bitmap to svg in multiple colors:
Dependencies: imagemagick, netpbm, potrace
Generate the PPM format from PNG:
convert download.png download.ppm
Generate a mask file for each color of the file:
ppmcolormask "#184d47" download.ppm > download-mask1.pbm
ppmcolormask "#66462C" download.ppm > download-mask2.pbm
Then trace the bitmap (bitmap -> svg):
potrace --flat -b svg download-mask1.pbm -o download1.svg
potrace --flat -b svg download-mask2.pbm -o download2.svg
Extract a list of colors from an image:
convert download.png +dither -colors 10 -unique-colors txt:
Articles:
- http://confluence.concord.org/display/CCTR/Removing%20Antialiasing.html
- http://confluence.concord.org/display/CCTR/Tracing%20Color%20Raster%20Images.html