✨ Expose the instance URL and query params to plugins (#13018)

Plugins and the MCP could not learn which Penpot instance they run on,
so agents guessed the domain when they wrote links to files.

Add penpot.location with the instance base URL (baseUrl), the URL of
the current screen (href) and its query params (params). It works in
the dashboard and the workspace and requires content:read. Params that
carry secrets (share-id, the MCP authorize params, and any key ending
in token, secret or password) are left out, and href is rebuilt from
the remaining params so it never carries one.

The MCP instructions tell agents to use href instead of building links.
The plugin API test suite checks location against the open file, and
its API surface is regenerated from the current types.

Closes #13013

AI-assisted-by: claude-opus-5-5
This commit is contained in:
Alonso Torres 2026-11-19 10:27:04 +01:00 committed by GitHub
parent be7be634d9
commit b6db09e2fb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 290 additions and 0 deletions

View File

@ -43,6 +43,7 @@
[app.plugins.history :as history]
[app.plugins.library :as library]
[app.plugins.local-storage :as local-storage]
[app.plugins.location :as location]
[app.plugins.management :as management]
[app.plugins.page :as page]
[app.plugins.parser :as parser]
@ -114,6 +115,9 @@
{:this true
:get #(.getTheme ^js %)}
:location
{:get (fn [] (clj->js (location/location @st/state)))}
:localStorage
{:this true
:get

View File

@ -0,0 +1,45 @@
;; 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 app.plugins.location
"The app URL as plugins see it: the instance base URL and the current
route's query params, without the params that carry secrets."
(:require
[app.common.data.macros :as dm]
[app.common.uri :as u]
[app.config :as cf]
[app.main.router :as rt]))
(def ^:private secret-params
"Query params that grant access or carry auth state."
#{:share-id :request :code :state})
(defn- secret-param?
[k]
(or (contains? secret-params k)
(some? (re-find #"(?i)(token|secret|password)$" (name k)))))
(defn- public-params
"Return the current route's query params without secrets. A key
repeated in the URL keeps its last value, as the app reads it."
[state]
(let [params (rt/get-params state)]
(into {}
(comp (remove (comp secret-param? key))
(map (fn [[k _]] [k (rt/get-query-param params k)])))
params)))
(defn location
"Return `{:baseUrl :href :params}` for the current route in `state`.
`href` is rebuilt from the public params, so it never carries a secret."
[state]
(let [base-url (dm/str cf/public-uri)
params (public-params state)]
{:baseUrl base-url
:href (if (empty? params)
base-url
(dm/str base-url "?" (u/map->query-string params)))
:params (update-keys params name)}))

View File

@ -0,0 +1,73 @@
;; 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.location-test
(:require
[app.common.data.macros :as dm]
[app.common.uri :as u]
[app.config :as cf]
[app.plugins.location :as location]
[cljs.test :as t :include-macros true]))
(defn- state-with-query
[query-params]
{:route {:data {:name (keyword (:screen query-params))}
:params {:path {} :query query-params}
:query-params query-params}})
(defn- href-params
[href]
(-> (u/uri href) :query u/query-string->map))
(t/deftest base-url-is-the-public-uri
(let [result (location/location (state-with-query {:screen "dashboard-recent"}))]
(t/is (= (dm/str cf/public-uri) (:baseUrl result)))))
(t/deftest workspace-params-are-exposed
(let [query {:screen "workspace"
:team-id "t1"
:file-id "f1"
:page-id "p1"
:layout "layers"}
result (location/location (state-with-query query))]
(t/is (= {"screen" "workspace"
"team-id" "t1"
"file-id" "f1"
"page-id" "p1"
"layout" "layers"}
(:params result)))
(t/is (= query (href-params (:href result))))
(t/is (= (dm/str cf/public-uri) (subs (:href result) 0 (count (dm/str cf/public-uri)))))))
(t/deftest custom-params-are-exposed
(let [result (location/location (state-with-query {:screen "workspace" :my-plugin "on"}))]
(t/is (= "on" (get-in result [:params "my-plugin"])))))
(t/deftest secret-params-are-left-out
(let [query {:screen "workspace"
:file-id "f1"
:token "s1"
:invitation-token "s2"
:share-id "s3"
:request "s4"
:code "s5"
:state "s6"
:client-secret "s7"
:password "s8"}
result (location/location (state-with-query query))]
(t/is (= {"screen" "workspace" "file-id" "f1"} (:params result)))
(t/is (= {:screen "workspace" :file-id "f1"} (href-params (:href result))))
(t/is (not (re-find #"s\d" (:href result))))))
(t/deftest repeated-params-keep-the-last-value
(let [result (location/location (state-with-query {:screen "workspace" :page-id ["p1" "p2"]}))]
(t/is (= "p2" (get-in result [:params "page-id"])))
(t/is (= "p2" (:page-id (href-params (:href result)))))))
(t/deftest no-route-returns-the-base-url
(let [result (location/location {})]
(t/is (= {} (:params result)))
(t/is (= (:baseUrl result) (:href result)))))

View File

@ -97,6 +97,7 @@
[frontend-tests.plugins.interactions-test]
[frontend-tests.plugins.library-test]
[frontend-tests.plugins.local-storage-test]
[frontend-tests.plugins.location-test]
[frontend-tests.plugins.management-test]
[frontend-tests.plugins.page-active-validation-test]
[frontend-tests.plugins.page-test]
@ -307,6 +308,7 @@
'frontend-tests.plugins.interactions-test
'frontend-tests.plugins.library-test
'frontend-tests.plugins.local-storage-test
'frontend-tests.plugins.location-test
'frontend-tests.plugins.page-active-validation-test
'frontend-tests.plugins.page-test
'frontend-tests.plugins.parser-test

View File

@ -206,6 +206,9 @@ A key object for navigating the currently active Penpot file is the `penpot` obj
* `penpot.root` provides the root shape of the currently active page.
* Generation of CSS content for elements via `penpot.generateStyle`
* Generation of HTML/SVG content for elements via `penpot.generateMarkup`
* `penpot.location` gives the Penpot instance URL (`baseUrl`), the link to what the user is viewing (`href`, e.g. the open file and page)
and the query params of that link (`params`, e.g. `params["file-id"]`). Use `href` when you need a link to the open file;
never guess the instance domain or build the link by hand.
Members of `penpot` (e.g. `penpot.currentFile` and `penpot.root`) will be null no Penpot file is currently opened.
You can use `penpotMgmt` to navigate to a file if needed (see below).

View File

@ -5,6 +5,7 @@
- **plugin-types, plugins-runtime:** Added `penpot.waitForSave(timeout?)` to wait until pending file changes are saved (or there is nothing to save). Rejects on save failure, rollback during the wait, timeout (default 60000 ms), or an invalid timeout. The Error `code` property is `save-timeout`, `rolled-back`, `save-retrying` (an earlier failed save Penpot keeps retrying) or the save failure code.
- **plugin-types, plugins-runtime:** `penpotMgmt` returns `Team`, `Project` and `ProjectFile` objects. Assigning `name` renames teams, projects and files, `project.pinned` pins a project and `file.shared` shares a file as a team library; `createProject`, `createFile`, `moveTo`, `duplicate`, `remove` and `restore` live on the objects. Added `penpotMgmt.listTeams`, `penpotMgmt.createTeam`, `penpotMgmt.getFile`, `listDeletedProjects` and `listDeletedFiles`, and the `manage:projects`, `manage:teams` and `manage:delete` permissions. Restoration uses the dashboard's Trash operation; projects need recoverable files and empty projects cannot be restored; the API exposes no permanent deletion method. Team deletion is not exposed.
- **plugins-runtime, plugin-types**: Added global plugins (`scope: "global"`) that remain active across dashboard and workspace navigation until closed or logged out, with `penpotMgmt` for project and file discovery, file navigation and workspace events. Global scope adds the `allow:global` permission, which users must accept when installing the plugin.
- **plugin-types, plugins-runtime:** Added `penpot.location` with the instance base URL (`baseUrl`), the URL of the current screen (`href`) and its query params (`params`), in the dashboard and the workspace. Params that carry secrets are left out. Requires `content:read`. Closes #13013.
- **plugin-types:** Added the `contentrollback` event and the `ContentRollback` type. The event fires after the backend rejected some changes and the workspace undid them, with the ids of the files, pages and shapes affected. It fires once the undone data is in the workspace, also when the workspace has to reload the file to undo the changes.
### 🩹 Fixes

View File

@ -104,6 +104,7 @@
"history",
"library",
"localStorage",
"location",
"openPage",
"openViewer",
"replaceColor",
@ -376,6 +377,7 @@
"Path": ["commands", "d", "fills", "type"],
"PathCommand": ["command", "params"],
"Penpot": ["closePlugin", "off", "on", "ui", "utils"],
"PenpotLocation": ["baseUrl", "href", "params"],
"PenpotMgmt": [
"createTeam",
"getFile",
@ -2253,6 +2255,12 @@
"type": "Theme",
"array": false
},
"location": {
"decl": "Context",
"kind": "get",
"type": "PenpotLocation",
"array": false
},
"localStorage": {
"decl": "Context",
"kind": "get",
@ -6711,6 +6719,12 @@
"type": "Theme",
"array": false
},
"location": {
"decl": "Context",
"kind": "get",
"type": "PenpotLocation",
"array": false
},
"localStorage": {
"decl": "Context",
"kind": "get",
@ -6892,6 +6906,26 @@
"array": false
}
},
"PenpotLocation": {
"baseUrl": {
"decl": "PenpotLocation",
"kind": "get",
"type": null,
"array": false
},
"href": {
"decl": "PenpotLocation",
"kind": "get",
"type": null,
"array": false
},
"params": {
"decl": "PenpotLocation",
"kind": "get",
"type": null,
"array": false
}
},
"PenpotMgmt": {
"workspace": {
"decl": "PenpotMgmt",

View File

@ -45,6 +45,54 @@ describe('Platform', () => {
});
});
describe('Location', () => {
// Parses a query string by hand: the plugin sandbox may not expose `URL`.
function queryParams(href: string): Record<string, string> {
const query = href.split('?')[1] ?? '';
const params: Record<string, string> = {};
for (const pair of query.split('&').filter(Boolean)) {
const [key, value = ''] = pair.split('=');
params[decodeURIComponent(key)] = decodeURIComponent(
value.replace(/\+/g, ' '),
);
}
return params;
}
test('baseUrl is an absolute instance URL ending in a slash', (ctx) => {
const { baseUrl } = ctx.penpot.location;
expect(/^https?:\/\/[^/?#]+(\/[^?#]*)?$/.test(baseUrl)).toBe(true);
expect(baseUrl.endsWith('/')).toBe(true);
});
test('href links to the open file and page', (ctx) => {
const { baseUrl, href } = ctx.penpot.location;
const file = ctx.penpot.currentFile;
const page = ctx.penpot.currentPage;
expect(file).not.toBeNull();
expect(page).not.toBeNull();
expect(href.startsWith(baseUrl + '?')).toBe(true);
const params = queryParams(href);
expect(params['screen']).toBe('workspace');
expect(params['file-id']).toBe(file!.id);
expect(params['page-id']).toBe(page!.id);
expect(params['team-id']).toBe(ctx.penpotMgmt.workspace.teamId);
});
test('params match the query of href', (ctx) => {
const { href, params } = ctx.penpot.location;
expect(params).toEqual(queryParams(href));
});
test('each read returns a new snapshot', (ctx) => {
const first = ctx.penpot.location;
const second = ctx.penpot.location;
expect(first === second).toBe(false);
expect(first).toEqual(second);
});
});
describe('History', () => {
test('undo block begin and finish wrap operations', (ctx) => {
const block = ctx.penpot.history.undoBlockBegin();

View File

@ -1165,6 +1165,19 @@ export interface Context {
*/
readonly theme: Theme;
/**
* The Penpot instance URL and the current address in the app, in the
* dashboard as well as in the workspace. Requires `content:read` permission.
*
* @example
* ```js
* const { baseUrl, href, params } = penpot.location;
* console.log(baseUrl); // "https://design.penpot.app/"
* console.log(params['file-id']);
* ```
*/
readonly location: PenpotLocation;
/**
* Access to the localStorage proxy
*/
@ -3404,6 +3417,33 @@ export interface LibraryTypography extends LibraryElement {
setFont(font: Font, variant?: FontVariant): void;
}
/**
* The Penpot instance URL and the current address in the app.
* Each read of `penpot.location` returns a new snapshot.
*
* Query params that carry secrets (`share-id`, any param ending in
* `token`, `secret` or `password`, and the OAuth params `request`,
* `code` and `state`) are left out of `params` and `href`.
*/
export interface PenpotLocation {
/**
* The public URL of the Penpot instance, ending in `/`,
* e.g. `"https://design.penpot.app/"`.
*/
readonly baseUrl: string;
/**
* The URL of the current screen, e.g. the open file and page:
* `"https://design.penpot.app/?screen=workspace&team-id=…&file-id=…&page-id=…"`.
* Use it to link to what the user is looking at.
*/
readonly href: string;
/**
* The query params of the current URL, e.g. `screen`, `team-id`,
* `file-id` and `page-id`. A param repeated in the URL keeps its last value.
*/
readonly params: Record<string, string>;
}
/**
* Proxy for the local storage. Only elements owned by the plugin
* can be stored and accessed.

View File

@ -19,6 +19,7 @@ import type {
Page,
Path,
Penpot,
PenpotLocation,
PenpotMgmt,
Rectangle,
Shape,
@ -268,6 +269,11 @@ export function createApi(
return plugin.context.theme;
},
get location(): PenpotLocation {
checkPermission('content:read', false);
return plugin.context.location;
},
get localStorage(): LocalStorage {
checkPermission('allow:localstorage');
return plugin.context.localStorage;

View File

@ -276,4 +276,38 @@ describe('Plugin api', () => {
expect(currentSelection).toEqual(selection);
});
});
describe('location', () => {
const location = {
baseUrl: 'https://design.penpot.app/',
href: 'https://design.penpot.app/?screen=dashboard-recent&team-id=t',
params: { screen: 'dashboard-recent', 'team-id': 't' },
};
it('returns the location while no workspace is ready', () => {
const { penpot } = createApi({
...pluginManager,
manifest: { ...pluginManager.manifest, scope: 'global' },
context: {
...pluginManager.context,
location,
management: { workspace: { status: 'none' } },
},
} as any);
expect(penpot.location).toEqual(location);
});
it('requires content:read', () => {
const { penpot } = createApi({
...pluginManager,
manifest: { ...pluginManager.manifest, permissions: [] },
context: { ...pluginManager.context, location },
} as any);
expect(() => penpot.location).toThrow(
'Permission content:read is not granted',
);
});
});
});