✨ Forward frontend audit events to host callbacks (#13175)

Hosts need a vendor-agnostic way to react to named audit events in the
browser (for example SaaS config.js). Penpot exposes
penpotAddEventCallback / penpotEventCallbacks, loads an early stub before
config.js, and invokes matching callbacks after make-event, without
coupling to any analytics SDK.

Closes #13091

AI-assisted-by: Composer
This commit is contained in:
Alejandro Alonso 2026-11-19 16:02:45 +01:00 committed by GitHub
parent ca1da39a35
commit 3e697c2794
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 186 additions and 1 deletions

View File

@ -13,7 +13,7 @@ Frontend: CLJS SPA; React/Rumext; Potok; RxJS; okulary refs; SCSS modules; share
- `app.util.*`: DOM, HTTP, i18n, keyboard, codegen, and general frontend utilities.
- `frontend/packages/*` and `frontend/text-editor`: JS/TS workspace packages consumed by the app.
- Nitrate subscription/organization UI and flows live under `app.main.data.nitrate` and `app.main.ui.nitrate*`; backend/API behavior is covered by backend memories, and shared organization permission rules (`allowed?`, `can-send-invitations?`) are in `common/src/app/common/types/organization.cljc`.
- `app.config` external bridges (`external-feature-flag`, `external-session-id`, `external-context-info`, `external-notify-register-success`, `initialize-external-context-info`) delegate to `globalThis` hooks injected by the SaaS host. Never delete `external-feature-flag`, even with zero call sites: it is the seam for future A/B tests.
- `app.config` external bridges (`external-feature-flag`, `external-session-id`, `external-context-info`, `external-notify-register-success`, `initialize-external-context-info`, `add-event-callback` / `get-event-callbacks` via `penpotEventCallbacks` + `penpotAddEventCallback`) delegate to `globalThis` hooks injected by the SaaS host. Never delete `external-feature-flag`, even with zero call sites: it is the seam for future A/B tests. Frontend audit events are forwarded to named host callbacks from `app.main.data.event` after `make-event` (vendor-agnostic; no analytics SDK in Penpot). `resources/js/event-callbacks.js` is copied to `public/js/` and loaded in `index.mustache` **before** `config.js` so hosts can call `penpotAddEventCallback` at config parse time.
## Lint and Format

View File

@ -0,0 +1,32 @@
/**
* Early registry for host-facing frontend audit event callbacks.
*
* Loaded before config.js so SaaS / local config can call
* `penpotAddEventCallback(name, fn)` at parse time. The ClojureScript
* app reads `penpotEventCallbacks` when prepared audit events fire and
* leaves a host-provided `penpotAddEventCallback` alone when present.
*/
(function (g) {
"use strict";
if (!(g.penpotEventCallbacks instanceof Map)) {
g.penpotEventCallbacks = new Map();
}
if (typeof g.penpotAddEventCallback !== "function") {
g.penpotAddEventCallback = function (name, callback) {
var m = g.penpotEventCallbacks;
var entry = m.get(name);
if (entry == null) {
m.set(name, [callback]);
} else if (Array.isArray(entry)) {
entry.push(callback);
} else if (typeof entry === "function") {
m.set(name, [entry, callback]);
} else {
m.set(name, [callback]);
}
};
}
})(globalThis);

View File

@ -41,6 +41,7 @@
</script>
{{# manifest}}
<script src="{{& event_callbacks}}"></script>
<script src="{{& config}}"></script>
<script src="{{& polyfills}}"></script>
{{/manifest}}

View File

@ -223,6 +223,7 @@ async function generateManifest() {
render_main: "./js/render.js",
rasterizer_main: "./js/rasterizer.js",
event_callbacks: "./js/event-callbacks.js?version=" + VERSION_TAG,
config: "./js/config.js?version=" + VERSION_TAG,
config_render: "./js/config-render.js?version=" + VERSION_TAG,
polyfills: "./js/polyfills.js?version=" + VERSION_TAG,
@ -658,6 +659,13 @@ export async function compilePolyfills() {
await fs.mkdir("./resources/public/js", { recursive: true });
fs.writeFile("resources/public/js/polyfills.js", result.join("\n"));
// Host event-callback registry must load before config.js (see
// index.mustache). Keep the public copy in sync with the source file.
await fs.copyFile(
"resources/js/event-callbacks.js",
"resources/public/js/event-callbacks.js",
);
const end = process.hrtime(start);
log.info("done: compile polyfills", `(${ppt(end)})`);
}

View File

@ -243,6 +243,65 @@
(let [f (obj/get global "initializeExternalConfigInfo")]
(when (fn? f) (f))))
(defn- get-or-create-event-callbacks-map
"Return the host-facing Map of event-name → callback(s), creating it
on globalThis when absent."
[]
(let [existing (obj/get global "penpotEventCallbacks")]
(if (instance? js/Map existing)
existing
(let [m (js/Map.)]
(obj/set! global "penpotEventCallbacks" m)
m))))
(defn add-event-callback
"Register a callback for a named frontend audit event.
Hosts (config.js / SaaS shell) call this as
`globalThis.penpotAddEventCallback(name, fn)`. Multiple callbacks per
name are kept in registration order."
[event-name callback]
(let [m (get-or-create-event-callbacks-map)
entry (.get m event-name)]
(cond
(nil? entry)
(.set m event-name #js [callback])
(array? entry)
(.push entry callback)
(fn? entry)
(.set m event-name #js [entry callback])
:else
(.set m event-name #js [callback]))
nil))
(defn get-event-callbacks
"Return the callbacks registered for `event-name`, or nil.
Accepts a single function or a JS array of functions under that name
on `globalThis.penpotEventCallbacks`."
[event-name]
(let [m (obj/get global "penpotEventCallbacks")]
(when (instance? js/Map m)
(let [entry (.get m event-name)]
(cond
(fn? entry)
[entry]
(array? entry)
(array-seq entry)
:else
nil)))))
;; Fallback install when the early `js/event-callbacks.js` stub (loaded
;; before config.js) is missing. Leave a host- or stub-provided function
;; alone so registrations from config.js stay on the same Map.
(when-not (fn? (obj/get global "penpotAddEventCallback"))
(obj/set! global "penpotAddEventCallback" add-event-callback))
(def mcp-server-url (-> public-uri u/ensure-path-slash (u/join "mcp/stream") str))
(def mcp-help-center-uri "https://help.penpot.app/mcp/")

View File

@ -8,6 +8,7 @@
(:require
["@penpot/ua-parser" :as ua]
[app.common.data :as d]
[app.common.exceptions :as ex]
[app.common.json :as json]
[app.common.logging :as l]
[app.common.math :as math]
@ -375,6 +376,18 @@
(or (contains? flags :audit-log)
(contains? flags :telemetry)))
(defn- run-event-callbacks
"Invoke host callbacks registered for this prepared audit event's
`:name`. Errors in a callback are swallowed so the audit pipeline
keeps running."
[event]
(let [name (:name event)
cbs (some-> name cf/get-event-callbacks)
js-event (when (seq cbs) (json/->js event))]
(when js-event
(doseq [f cbs]
(ex/ignoring (f js-event))))))
(defn initialize
[]
(ptk/reify ::initialize
@ -478,6 +491,8 @@
(assoc :timestamp (ct/now))
(assoc :context context)))))
(rx/tap run-event-callbacks)
(rx/tap (fn [event]
(l/debug :hint "event enqueued")
(swap! buffer append-to-buffer event)))

View File

@ -7,14 +7,84 @@
(ns frontend-tests.data.event-test
(:require
[app.common.uuid :as uuid]
[app.config :as cf]
[app.main.data.event :as ev]
[app.main.repo :as rp]
[app.util.globals :refer [global]]
[app.util.object :as obj]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
[frontend-tests.helpers.async :as async]
[frontend-tests.helpers.mock :as mock]
[potok.v2.core :as ptk]))
(defn- with-event-callbacks
"Install a fresh penpotEventCallbacks Map for the body, then restore."
[setup-fn body-fn]
(let [prev-map (obj/get global "penpotEventCallbacks")
m (js/Map.)]
(setup-fn m)
(obj/set! global "penpotEventCallbacks" m)
(try
(body-fn)
(finally
(if (some? prev-map)
(obj/set! global "penpotEventCallbacks" prev-map)
(obj/unset! global "penpotEventCallbacks"))))))
(t/deftest run-event-callbacks-invokes-matching-name
(let [calls (atom [])]
(with-event-callbacks
(fn [m]
(.set m "disable-webgl-rendering"
#js [(fn [e] (swap! calls conj e))]))
(fn []
(#'ev/run-event-callbacks {:name "disable-webgl-rendering"
:type "action"
:props {:origin "settings"}})
(t/is (= 1 (count @calls)))
(let [payload (first @calls)]
(t/is (= "disable-webgl-rendering" (unchecked-get payload "name")))
(t/is (= "action" (unchecked-get payload "type")))
(t/is (= "settings" (unchecked-get (unchecked-get payload "props") "origin"))))))))
(t/deftest run-event-callbacks-ignores-unknown-name
(let [calls (atom [])]
(with-event-callbacks
(fn [m]
(.set m "disable-webgl-rendering"
#js [(fn [e] (swap! calls conj e))]))
(fn []
(#'ev/run-event-callbacks {:name "enable-webgl-rendering"
:type "action"
:props {}})
(t/is (empty? @calls))))))
(t/deftest run-event-callbacks-swallows-callback-errors
(let [calls (atom [])]
(with-event-callbacks
(fn [m]
(.set m "disable-webgl-rendering"
#js [(fn [_] (throw (js/Error. "host boom")))
(fn [e] (swap! calls conj e))]))
(fn []
(#'ev/run-event-callbacks {:name "disable-webgl-rendering"
:type "action"
:props {}})
(t/is (= 1 (count @calls)))
(t/is (= "disable-webgl-rendering"
(unchecked-get (first @calls) "name")))))))
(t/deftest add-event-callback-registers-on-global-map
(with-event-callbacks
(fn [_m])
(fn []
(let [calls (atom [])]
(cf/add-event-callback "navigate" (fn [e] (swap! calls conj e)))
(#'ev/run-event-callbacks {:name "navigate" :type "action" :props {}})
(t/is (= 1 (count @calls)))
(t/is (= "navigate" (unchecked-get (first @calls) "name")))))))
(t/deftest events-enabled?-truth-table
(t/testing "enabled when audit-log is present"
(t/is (true? (ev/events-enabled? #{:audit-log}))))