Files
punktfunk/plugin-kit
enricobuehler defdfbdb58
ci / web (pull_request) Successful in 1m2s
apple / swift (pull_request) Successful in 1m33s
apple / screenshots (pull_request) Skipped
ci / rust-arm64 (pull_request) Successful in 2m4s
ci / docs-site (pull_request) Successful in 2m13s
android / android (pull_request) Successful in 3m16s
ci / rust (pull_request) Failing after 3m36s
fix(security): plugin UIs get their own origin
Closes H-3 of the 2026-08-05 review, the last of its six highs. A plugin's
interface was reverse-proxied onto the console's own origin and framed with
`allow-same-origin`, so plugin JS ran as first-party code on that origin: one
`fetch('/api/**', {credentials:'same-origin'})` and the BFF attached the
operator's ADMIN bearer. That reached everything `plugin_may_access` withholds
— arm pairing, read the host PIN, approve a device, read `/hooks`. The "open
in new tab" link was the same escalation with no iframe involved at all.

The fix is not a sandbox attribute, and it is worth writing down why, because
the obvious change is the one that does not work. Dropping `allow-same-origin`
gives the frame an OPAQUE origin; its subresource requests are then cross-site;
the `SameSite=Lax` session cookie stops being sent; every plugin asset 302s to
/login and the frame is blank. Nothing about the new-tab link is helped either.

So the origin moves instead. A second listener on its own port (default
PORT + 1) serves plugin UIs and nothing else:

  different ORIGIN — scheme+host+PORT — so the same-origin policy separates the
                     plugin from the console: it cannot read the console's DOM,
                     its cross-origin fetch of /api/** is unreadable (no CORS)
                     and cannot mutate (Sec-Fetch-Site sees same-site).
  same SITE        — cookie scope ignores the port and SameSite is computed on
                     the site, so the session cookie still reaches the plugin
                     listener and plugin pages keep working.

Enforcement is two refusals and both are load-bearing: the console origin
refuses /plugin-ui/**, and the plugin origin refuses everything ELSE — above
all /api/**, which would otherwise hand the admin bearer right back to plugin
JS that is now same-origin with that listener. Both are unconditional: if the
plugin port cannot be bound, plugin UIs are DISABLED and the console says so,
rather than falling back to the arrangement this exists to remove.

Two consequences that would otherwise bite in the field:

  The port has to be open. Done for the Windows netsh rule, the firewalld
  service and the ufw profile.

  A browser stores a self-signed-certificate exception per ORIGIN, including
  the port — and a certificate interstitial can never be shown inside an
  iframe, so the frame would just sit blank with nothing on screen explaining
  why. A `no-cors` probe distinguishes it (a TLS failure rejects; any HTTP
  answer, even 401, resolves) and the console renders a card linking the
  operator to open the port once in a real tab.

Also here: the health probe moved server-side to the console origin (it used
to rely on being same-origin with the plugin), the postMessage listener now
verifies `event.origin` — a real check rather than a tautology — and
plugin-kit's `postMessage(..., "*")` is documented as load-bearing, since
narrowing it to `location.origin` would now target the plugin's own origin and
silently drop every message.

Verified against a running console with a fake mgmt API and a fake plugin:
console /plugin-ui/** → 404; plugin-origin /api/v1/hooks, /, /login,
/_auth/logout → 404; plugin page loads 200 through its own origin;
unauthenticated plugin origin → 401 (not a redirect to a /login it does not
serve); a forged x-pf-listener header changes nothing on either listener; the
plugin's own Clear-Site-Data / Access-Control-Allow-Origin / Set-Cookie are
dropped by the proxy allowlist; the plugin origin's CSP names the console as
its only frame-ancestors source; and with the port squatted, ui-config reports
`unavailable`, the console still refuses /plugin-ui/**, and the console itself
keeps working.

Still wants on-glass confirmation in a real browser — the cookie and framing
behaviour is reasoned from spec, not observed.

cargo fmt --all --check clean; cargo check -p punktfunk-host --all-targets
green on Windows; web console builds and typechecks.
2026-08-05 17:50:04 +02:00
..

@punktfunk/plugin-kit

The Effect-based framework punktfunk plugins are built on. It owns everything that is the same in every plugin — lifecycle, config/state, the sync engine, UI serving, the CLI scaffold, logging — so a plugin is just its domain logic, its HttpApi contract, and its UI. The reference consumer (and the blueprint to copy) is punktfunk-plugin-rom-manager.

Built on @punktfunk/host (the SDK stays the low-level host client; the kit is the opinionated plugin layer on top). Effect 4.x and the SDK are peer dependencies — the plugin's own copies are the only copies.

The one rule: async at the boundary, Effect inside

The packaged runner bundles its own effect + SDK; a plugin's imports resolve to the plugin's node_modules. Effect values must therefore never cross the plugin boundary (Context.Tag identity is per-instance). definePluginKit enforces this by construction: you write Effect, it exports a plain async-main PluginDef, and a ManagedRuntime built from your effect instance runs everything. SIGINT/SIGTERM interrupt the plugin fiber (scoped finalizers run: UI deregistration, watcher close), bounded by shutdownGraceMs.

import { definePluginKit, serveUi } from "@punktfunk/plugin-kit";
import { Effect, Layer } from "effect";

export default definePluginKit({
  name: "my-plugin",
  version: "0.1.0",
  layer: MyServices.layer, // over the kit base: HostClient | PluginInfo
  main: Effect.gen(function* () {
    const engine = yield* MySync;
    yield* engine.start;
    yield* serveUi({ title: "My Plugin", icon: "puzzle", staticDir, api: MyApiLive });
    yield* Effect.never;
  }),
});

Modules

Export What it owns
definePluginKit / runPluginKitDirect the async-main boundary + ManagedRuntime + signal handling
HostClient, PluginInfo the pf facade as services (request = the skew-safe untyped seam)
makeConfigService Schema-driven config: raw shape on disk, defaults ONLY in the Schema (withDecodingDefaultKey + encodingStrategy: "omit"), atomic writes, world-writable refusal, changes stream
makeCacheStore disposable derived state (corrupt/absent → empty, write-through)
ProviderClient + wire schemas typed library-provider reconcile over the untyped wire — including the optional detect hint (see below)
makeSyncEngine poll + fs-watch + debounce + single-flight coalescing + fingerprint skip + status feed
serveUi / httpApiEnv an effect/unstable/httpapi HttpApi behind the SDK's servePluginUi, core-only layers
sseRoute the status SSE endpoint (httpapi has no event-stream media type)
runPluginCli <bin> <command> dispatcher reusing the plugin's layer graph (deliberately not effect/unstable/cli — that would drag platform packages into every plugin)
loggingLayer runner-journal line format
@punktfunk/plugin-kit/react browser glue: createPluginRouter (path→hash→fallback deep-link restore + pf-ui:navigate), resolvePluginBase, useIsEmbedded, ResultGate, sseAtom
@punktfunk/plugin-kit/theme.css the console's violet identity for plugin UIs (import first in your Tailwind entry)

Telling the host how to recognize a running title (detect)

A ProviderEntry may carry an optional detect hint:

{ external_id: "playnite:9f2…", title: "Hades",
  launch: { kind: "command", value: "playnite://playnite/start/9f2…" },
  detect: { install_dir: "D:\\Games\\Hades" } }

It is what lets the host tell that the game has exited — which ends the streaming session, so the player's client returns to its library instead of showing a bare desktop — and what lets an operator who opted into it end the game when the session ends.

Omit it and nothing breaks: the host tracks the process it spawns for your launch command. It matters when that command hands off and exits — a launcher client, flatpak run, a front-end that starts an emulator — because then there is nothing left for the host to watch, and both behaviors go quiet for that title. Send whatever you genuinely know; install_dir is the one to send if you send only one, since any process running from under it counts as the game. The host never lets a hint override what it worked out itself, and never adopts a process that was already running before the launch.

Publishing

Tag plugin-kit-vX.Y.Z (matching package.json) — .gitea/workflows/plugin-kit-publish.yml typechecks, tests, builds, and publishes to the Gitea registry.