AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(ui): confirm changes inside a frame once the browser reports the question seen (#635)
ladislav-urban9d9ca16d0a95
diff --git a/docs/auth.md b/docs/auth.mdindex 49ef99b0..331e37d0 100644--- a/docs/auth.md+++ b/docs/auth.md@@ -456,17 +456,44 @@ parent window, and every `init` field is validated. In a frame:framed, and a sign-in button under a page this app doesn't control can be pressed by alured click. So `/signin` in a frame shows no sign-in forms, only a link that opens it ina new tab; when the person comes back signed in, the frame goes on to where it was headed.-- **Changes are refused, in any frame** (embedded or not, since a host page can frame- these pages without saying so). The page around a frame can make it invisible and lay- its own buttons over it, so a confirmation drawn inside the frame can be beaten with- lured clicks. So approving, rejecting or cancelling a card, a proposal, a workflow- sign-off or a roster request, every chat message sent from the frame (the host's are- read-only, but one sent from this app's page is the person's own turn), and any other- change the host list doesn't already allow with the same effect (a setting, Handle it- for me, People, an upload) made within 10 seconds of a click, key, drop or paste in the- frame, is not sent: the page says to do it in Open Executive itself. The frame checks- every request it sends (`lib/cardActions.ts`), so no button can skip it. Each approval- card has its own page, `/cards/<id>`, which a host can open in a new tab for that.+- **Changes ask inside the frame, and the browser must have seen the question, in any+ frame** (embedded or not, since a host page can frame these pages without saying so).+ Approving, rejecting or cancelling a card, a proposal, a workflow sign-off or a roster+ request, every chat message sent from the frame (the host's are read-only, but one sent+ from this app's page is the person's own turn), and any other change the host list+ doesn't already allow with the same effect (a setting, Handle it for me, People, an+ upload) made within 10 seconds of a click, key, drop or paste in the frame, or of a Yes,+ first asks in a panel inside the frame naming what will happen (for a chat message, the+ message). The frame checks every request it sends (`lib/cardActions.ts`), so no button+ can skip it. The page around a frame can make it invisible, cover it and lure clicks,+ so the panel's Yes counts only when all of these hold (`lib/seen.ts`):+ - IntersectionObserver v2 (`trackVisibility: true`) has reported the panel whole on+ screen, uncovered, untransformed, unfiltered and at full opacity, without a break, for+ at least 700 ms. The browser computes that answer; the page around can't fake it. A+ cover that lets clicks through (`pointer-events: none`) and a frame cropped to show the+ Yes without the words above it fail it too. The browser reports at most every 100 ms;+ reports it hasn't delivered yet are read at each look (`takeRecords`);+ - the real pointer has been inside the panel, without leaving, for at least 500 ms, and+ has moved there (a cursor drawn by the page around doesn't move it). A frame slid under+ the pointer between the two clicks of a lured double-click fails this. Leaving the+ panel, or the frame losing focus, starts it again;+ - the press began on Yes after all of that held, and the click that follows is trusted+ and on Yes too. A key press on a focused Yes has no pointer press, so it never counts;+ - 250 ms after the click, the panel is still in the same unbroken run of "seen" and the+ pointer still inside, so a cover laid on just before the click shows up first.++ The panel keeps Open Executive's own colours and face (`.consent` in `globals.css`),+ whatever the host's theme: otherwise a host could draw the question white on white, or in+ a symbol font, while the browser still reports it seen. Anyone who can't point (a+ keyboard, a touch screen) answers on this app's own page, which the panel links to.++ A browser without v2 (Firefox, Safari) can't tell, so the panel offers no Yes there: it+ links to this app's own page for it, top level in the same tab (the card's page,+ `/cards/<id>`, or else the page that asked, without `embed`), where nothing can frame+ it; Back returns to the host. It never fails open. The answer stays in the browser:+ what it guards against is code on the host's origin, which can't run in this app's+ origin, and the change itself is still this app's same-origin request with its usual+ checks.`make embed-outputs` writes what a host app checks itself against without running thisapp or holding its secrets: `embed-manifest.json` (the navigation and routes),@@ -488,7 +515,9 @@ arrive marked as outside content, as any watch's do. A framed page reports its pevery navigation, which on a page about one record (a person, a run) names it, and on asearch page carries what was searched for.It can lure clicks onto a framed page it has made invisible, but every change beyond the-host list is refused in a frame, so the person makes it in Open Executive itself. Every host origin you list is+host list asks inside the frame, and its Yes counts only once the browser has seen the+question and the person pointed at it (or, in a browser that can't tell, on this app's+own page). Every host origin you list istrusted that far: list only apps whose administrators you would trust with it, and read every changeto the host list, the `host` surface's tools and these policies with a security review.diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 4a69cd60..0c408c54 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -8044,8 +8044,8 @@ auth:loops, style, notes, review, Honcho), and attunement.style skipssender_surface rows. sessions.host_wrote makes the mark sticky across arewind (Try again / Edit). Frame input also counts drop, paste and a- Yes in the window; chat sends always ask in a frame, and the window- shows the message. A host turn marks a new conversation as soon as its+ Yes in the in-frame confirm; chat sends always ask in a frame, and the+ confirm shows the message. A host turn marks a new conversation as soon as itssession row exists (session_store.mark_host_wrote), so an own-page turnrunning alongside is held too; briefing.live_signals leaves suchconversations' titles (the host's words) out of the brief. The@@ -8058,9 +8058,20 @@ auth:host-written chats' titles (fail closed); the Markdown export labelshost lines "(from another app's page)".In any frame, card actions, chat messages, and any other change off the- host list made within 10 s of a trusted click/key/drop/paste are refused- (CardActionRefusedInFrame): an in-frame dialog can be beaten by lured- clicks on an invisible frame.+ host list made within 10 s of a trusted click/key/drop/paste ask in+ FrameConfirm, inside the frame. A lured click on an invisible frame+ beats a plain dialog, so its Yes counts only under lib/seen.ts:+ IntersectionObserver v2 (trackVisibility) reported the panel whole,+ uncovered, untransformed and at full opacity for an unbroken 700 ms+ (pending reports read with takeRecords); the real pointer rested inside+ for 500 ms (reset on pointerleave and the frame's blur); the press began+ on Yes after that and a trusted click on Yes followed; and 250 ms later+ the same run of "seen" holds with the pointer inside. The panel wears+ .consent (the app's own colour tokens and a system font, never the+ host's). Without v2 (Firefox, Safari), or for keyboard and touch, it+ offers no Yes: a link to this app's own page, target _top (the card's+ /cards/<id>, else the asking page without embed); it never fails open.+ A No throws CardActionNotConfirmed.Pages (all, host origins set or not): Content-Security-Policyscript-src 'self' 'nonce-…' 'strict-dynamic' (+ 'unsafe-eval' on the@@ -8080,9 +8091,9 @@ auth:once /api/auth/session has a user. In ANY frame card actions(decisions approve/reject/cancel, alerts approve, workflow decisions,roster requests), chat messages, and other changes off the host list- after a click are refused (fetch is checked against- lib/cardActions.ts); each card has /cards/<id>, which a host can open- in a new tab.+ after a click ask in FrameConfirm under lib/seen.ts's rule (fetch is+ checked against lib/cardActions.ts); each card has /cards/<id>, where a+ browser without IntersectionObserver v2 answers it.What remains (docs/auth.md): a host's scripts can read what thehost list allows (briefing, conversations and replies, watch list)diff --git a/packages/ui/scripts/cardActions.test.mjs b/packages/ui/scripts/cardActions.test.mjsindex 11617720..b4970fe3 100644--- a/packages/ui/scripts/cardActions.test.mjs+++ b/packages/ui/scripts/cardActions.test.mjs@@ -1,10 +1,17 @@// In a frame, a card action, a chat message, and any other change off the-// host list that follows a click, is refused (lib/cardActions.ts,-// components/embed/EmbedProvider.tsx).+// host list that follows a click, asks inside the frame under lib/seen.ts's+// rule (lib/cardActions.ts, components/embed/EmbedProvider.tsx,+// FrameConfirm.tsx).import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";-import { CardActionRefusedInFrame, messageOf, cardActionFor, frameActionFor } from "../src/lib/cardActions.ts";+import {+ CardActionNotConfirmed,+ cardActionFor,+ frameActionFor,+ messageOf,+ ownPageFor,+} from "../src/lib/cardActions.ts";const API = readFileSync(new URL("../src/lib/api.ts", import.meta.url), "utf8");const CALLS = JSON.parse(readFileSync(new URL("../src/lib/host-list.json", import.meta.url), "utf8")).calls;@@ -32,6 +39,7 @@ test("what each card action says will happen", () => {decisionId: 7,what: "Approve card 7: what it shows is carried out now, as you.",card: true,+ page: "/cards/7",});assert.equal(cardActionFor("post", "/api/backend/decisions/7/reject").verb, "reject");assert.equal(cardActionFor("POST", "http://this.app/api/backend/decisions/7/cancel").verb, "cancel");@@ -90,13 +98,24 @@ test("a send's message, from JSON or a form", () => {assert.equal(messageOf(undefined), "");});-test("a refusal says what wasn't done and where to do it", () => {- const error = new CardActionRefusedInFrame(cardActionFor("POST", "/api/backend/decisions/7/approve"));- assert.equal(error.name, "CardActionRefusedInFrame");- assert.match(error.message, /^Not done in this frame\. Approve card 7: .* To do it, open Open Executive itself\.$/);+test("a No says nothing was done", () => {+ const error = new CardActionNotConfirmed();+ assert.equal(error.name, "CardActionNotConfirmed");+ assert.equal(error.message, "Not confirmed, so nothing was done.");});-test("the frame checks every request, in any frame, and refuses what may have been lured", () => {+test("a browser that can't tell the frame is seen answers on this app's own page", () => {+ // A card's own page.+ assert.equal(ownPageFor(cardActionFor("POST", "/api/backend/decisions/7/approve"), "/today", "?embed=1"), "/cards/7");+ // Anything else: the page that asked, without `embed`, keeping the rest.+ const send = frameActionFor("POST", "/api/backend/chat", '{"message":"hi"}', CALLS);+ assert.equal(ownPageFor(send, "/chats/abc", "?embed=1&q=x"), "/chats/abc?q=x");+ assert.equal(ownPageFor(send, "/chats/abc", "?embed=1"), "/chats/abc");+ // Never another site: a path that isn't this app's own becomes /.+ assert.equal(ownPageFor(send, "//evil.example/x", ""), "/");+});++test("the frame checks every request, in any frame, and asks about what may have been lured", () => {const provider = read("../src/components/embed/EmbedProvider.tsx");assert.match(provider, /if \(window\.top === window\.self\) return;/);assert.match(provider, /const action = frameActionFor\(method, url, init\?\.body, HOST_CALLS\);/);@@ -104,5 +123,8 @@ test("the frame checks every request, in any frame, and refuses what may have be// A drop or a paste is input too: a page over the frame can put its own// file in a drag.assert.match(provider, /const INPUT_EVENTS = \["pointerdown", "keydown", "drop", "paste"\] as const;/);- assert.match(provider, /if \(refused\) throw new CardActionRefusedInFrame\(action\);/);+ assert.match(provider, /if \(asks && !\(await confirm\(action\)\)\) throw new CardActionNotConfirmed\(\);/);+ // It asks inside the frame, and never opens a window.+ assert.match(provider, /<FrameConfirm action=\{pending\.action\} onAnswer=\{answer\} \/>/);+ assert.doesNotMatch(provider, /window\.open\(/);});diff --git a/packages/ui/scripts/seen.test.mjs b/packages/ui/scripts/seen.test.mjsnew file mode 100644index 00000000..e4ff97b2--- /dev/null+++ b/packages/ui/scripts/seen.test.mjs@@ -0,0 +1,291 @@+// A Yes inside a frame counts only once the browser reported it seen and the+// person pointed at it (lib/seen.ts): FrameConfirm.tsx uses it, with the+// observer and events faked here.+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import {+ DWELL_MS,+ OBSERVE_DELAY_MS,+ SEEN_MS,+ SETTLE_MS,+ SeenGate,+ tracksVisibility,+ watchPanel,+} from "../src/lib/seen.ts";++const read = (path) => readFileSync(new URL(path, import.meta.url), "utf8");++const seen = (time, extra = {}) => ({ isIntersecting: true, intersectionRatio: 1, isVisible: true, time, ...extra });+const real = (now, extra = {}) => ({ isTrusted: true, onYes: true, now, ...extra });+const T = SEEN_MS + DWELL_MS;++/** Seen from 0, the pointer in from 0 and moved: armed from max(SEEN_MS, DWELL_MS). */+function pointedGate() {+ const gate = new SeenGate();+ gate.observe(seen(0));+ gate.pointerInside(true, 0, false);+ gate.pointerInside(true, 10, true);+ return gate;+}++/** A press then a click on Yes at `at`: whether the click counts. */+function pressAndClick(gate, at, press = {}, click = {}) {+ gate.pressed(real(at, press));+ return gate.clickCounts(real(at + 80, click));+}++test("a Yes counts once seen long enough, pointed at for a moment, pressed and clicked for real", () => {+ assert.equal(pressAndClick(pointedGate(), T), true);+ assert.ok(SEEN_MS >= 700);+ assert.ok(DWELL_MS >= 500, "longer than a double-click");+});++test("a Yes is refused when the panel was seen for under SEEN_MS", () => {+ const gate = new SeenGate();+ gate.observe(seen(1000));+ gate.pointerInside(true, 0, false);+ gate.pointerInside(true, 1001, true);+ assert.equal(pressAndClick(gate, 1000 + SEEN_MS - 100), false);+});++test("a Yes is refused while the panel is covered, see-through, transformed, cropped or hidden", () => {+ // The browser reports all of these as not visible; off screen or cropped as not whole.+ for (const report of [+ { isVisible: false },+ { isIntersecting: false, intersectionRatio: 0 },+ { intersectionRatio: 0.5 },+ { isVisible: undefined },+ ]) {+ const gate = pointedGate();+ gate.observe(seen(100, report));+ assert.equal(pressAndClick(gate, 5_000), false, JSON.stringify(report));+ }+});++test("a break starts the run again, and the pointer must move again after it", () => {+ const gate = pointedGate();+ gate.observe(seen(400, { isVisible: false }));+ gate.observe(seen(500));+ assert.equal(pressAndClick(gate, 500 + T), false, "no move since the break");+ gate.pointerInside(true, 600, true);+ assert.equal(pressAndClick(gate, 500 + SEEN_MS - 1), false, "the run counts from the break");+ assert.equal(pressAndClick(gate, 500 + SEEN_MS + 1), true);++ // A break also puts the pointer outside: it must come in again.+ const off = pointedGate();+ off.observe(seen(400, { isVisible: false }));+ off.observe(seen(500));+ // Without a break the pointer would have been in since 0; now it counts from 1000.+ off.pointerInside(true, 1000, true);+ assert.equal(pressAndClick(off, 500 + SEEN_MS + 1), false, "in for under DWELL_MS since the break");+ assert.equal(pressAndClick(off, 1000 + DWELL_MS), true);+});++test("a press counts for one click only", () => {+ const gate = pointedGate();+ assert.equal(pressAndClick(gate, T), true);+ gate.pressUsed();+ assert.equal(gate.clickCounts(real(T + 200)), false, "Enter afterwards, no new press");+});++test("a Yes is refused without pointer movement, or with an untrusted one", () => {+ const still = new SeenGate();+ still.observe(seen(0));+ still.pointerInside(true, 0, false);+ assert.equal(pressAndClick(still, 5_000), false);++ const fake = new SeenGate();+ fake.observe(seen(0));+ fake.pointerInside(false, 0, false);+ fake.pointerInside(false, 10, true);+ assert.equal(pressAndClick(fake, 5_000), false);+});++test("a frame slid under the pointer between a double-click's two clicks doesn't count", () => {+ // Seen for minutes, pointed at long ago, then the pointer left.+ const gate = pointedGate();+ gate.pointerGone();+ // The frame moves under the resting pointer: it enters now, jitters, and the second click lands.+ gate.pointerInside(true, 60_000, false);+ gate.pointerInside(true, 60_002, true);+ assert.equal(pressAndClick(gate, 60_000 + 250), false);+ assert.equal(pressAndClick(gate, 60_000 + DWELL_MS - 1), false);+ assert.equal(pressAndClick(gate, 60_000 + DWELL_MS), true, "a pointer that rests there long enough counts");+});++test("the frame losing focus, or the pointer leaving, starts the pointer's part again", () => {+ const gate = pointedGate();+ gate.pointerGone();+ assert.equal(pressAndClick(gate, 5_000), false);+});++test("a press must begin after it armed, on Yes, trusted; a click alone (a key) never counts", () => {+ const early = pointedGate();+ early.pressed(real(T - DWELL_MS - 300));+ assert.equal(early.clickCounts(real(T + 50)), false, "pressed before it armed, released after");++ assert.equal(pressAndClick(pointedGate(), T, { onYes: false }), false, "pressed elsewhere");+ assert.equal(pressAndClick(pointedGate(), T, { isTrusted: false }), false);+ assert.equal(pressAndClick(pointedGate(), T, {}, { onYes: false }), false, "released elsewhere");+ assert.equal(pressAndClick(pointedGate(), T, {}, { isTrusted: false }), false);+ assert.equal(pointedGate().clickCounts(real(T)), false, "Enter on a focused Yes: no press");+});++test("still seen after the click only in the same run, with the pointer still in", () => {+ const ok = pointedGate();+ assert.equal(pressAndClick(ok, T), true);+ assert.equal(ok.stillSeen(T + SETTLE_MS), true);++ const covered = pointedGate();+ pressAndClick(covered, T);+ covered.observe(seen(T + 50, { isVisible: false }));+ covered.observe(seen(T + 150));+ assert.equal(covered.stillSeen(T + SETTLE_MS), false, "a break and a new run is not the same run");++ const left = pointedGate();+ pressAndClick(left, T);+ left.pointerGone();+ assert.equal(left.stillSeen(T + SETTLE_MS), false);+});++test("only an observer that reports visibility counts as v2", () => {+ class IO {}+ assert.equal(tracksVisibility({ IntersectionObserver: IO, IntersectionObserverEntry: { prototype: { isVisible: false } } }), true);+ assert.equal(tracksVisibility({ IntersectionObserver: IO, IntersectionObserverEntry: { prototype: {} } }), false);+ assert.equal(tracksVisibility({ IntersectionObserver: IO }), false);+ assert.equal(tracksVisibility({}), false);+ assert.equal(tracksVisibility(null), false);+});++test("without v2 nothing is watched, so nothing can arm", () => {+ class IO {}+ const gate = new SeenGate();+ const win = { IntersectionObserver: IO, IntersectionObserverEntry: { prototype: {} } };+ assert.equal(watchPanel(win, {}, () => true, gate, () => {}), null);+ assert.equal(pressAndClick(gate, 5_000), false);+});++/** A fake window and panel: a clock, the observer, timers and listeners. */+function fakeWorld() {+ const world = { clock: 0, listeners: {}, winListeners: {}, timers: [], observer: null };+ class IO {+ constructor(cb, options) {+ world.observer = { cb, options, observed: [], pending: [], stopped: false };+ }+ observe(el) {+ world.observer.observed.push(el);+ }+ disconnect() {+ world.observer.stopped = true;+ }+ takeRecords() {+ const out = world.observer.pending;+ world.observer.pending = [];+ return out;+ }+ }+ const on = (table) => ({+ addEventListener: (type, fn) => {+ table[type] = fn;+ },+ removeEventListener: (type) => {+ delete table[type];+ },+ });+ world.win = {+ IntersectionObserver: IO,+ IntersectionObserverEntry: { prototype: { isVisible: true } },+ performance: { now: () => world.clock },+ setTimeout: (fn, ms) => world.timers.push({ fn, at: world.clock + ms }),+ ...on(world.winListeners),+ };+ world.panel = on(world.listeners);+ world.yes = { button: true };+ world.fire = (type, event = {}) => world.listeners[type]({ isTrusted: true, target: world.yes, ...event });+ world.runTimers = async (until) => {+ world.clock = until;+ for (const t of world.timers.splice(0)) t.fn();+ await new Promise((resolve) => setImmediate(resolve));+ };+ return world;+}++test("with v2 the panel and the pointer are watched, and a click is judged again after it settles", async () => {+ const world = fakeWorld();+ const gate = new SeenGate();+ let changes = 0;+ const watch = watchPanel(world.win, world.panel, (t) => t === world.yes, gate, () => changes++);+ assert.deepEqual(world.observer.options, { threshold: [1.0], trackVisibility: true, delay: OBSERVE_DELAY_MS });+ assert.deepEqual(world.observer.observed, [world.panel]);+ world.observer.cb([seen(0)]);+ world.fire("pointerenter");+ world.clock = 10;+ world.fire("pointermove");+ world.clock = T;+ assert.equal(watch.armed(), true);+ world.fire("pointerdown");+ const judged = watch.judge({ isTrusted: true, target: world.yes });+ await world.runTimers(T + SETTLE_MS);+ assert.equal(await judged, true);+ assert.ok(changes >= 1);++ // Covered just after the click, not yet delivered: the second look takes it and refuses.+ world.clock = T + 1000;+ world.fire("pointerdown");+ const second = watch.judge({ isTrusted: true, target: world.yes });+ world.observer.pending.push(seen(T + 1010, { isVisible: false }));+ await world.runTimers(T + 1000 + SETTLE_MS);+ assert.equal(await second, false);++ // The press is used up: a second click with no new press doesn't count.+ assert.equal(await watch.judge({ isTrusted: true, target: world.yes }), false);+ // A press released off Yes counts for nothing.+ world.clock = T + 3000;+ world.fire("pointerdown");+ world.fire("pointerup", { target: {} });+ assert.equal(await watch.judge({ isTrusted: true, target: world.yes }), false);++ watch.stop();+ assert.equal(world.observer.stopped, true);+ assert.deepEqual(Object.keys(world.listeners), []);+ assert.deepEqual(Object.keys(world.winListeners), []);+});++test("the frame losing focus disarms it", () => {+ const world = fakeWorld();+ const gate = new SeenGate();+ const watch = watchPanel(world.win, world.panel, (t) => t === world.yes, gate, () => {});+ world.observer.cb([seen(0)]);+ world.fire("pointerenter");+ world.fire("pointermove");+ world.clock = T;+ assert.equal(watch.armed(), true);+ world.winListeners.blur();+ assert.equal(watch.armed(), false);+});++test("the in-frame confirm opens no window, is judged by the gate, and offers this app's own page", () => {+ const src = read("../src/components/embed/FrameConfirm.tsx");+ assert.doesNotMatch(src, /window\.open\(/);+ assert.match(src, /watchPanel\(/);+ assert.match(src, /if \(judged && \(await judged\)\) finish\(true\);/);+ assert.match(src, /target="_top"/);+});++test("the host's colours and font never reach a Yes asked in a frame", () => {+ const css = read("../src/app/globals.css");+ // The app's own tokens are declared again on .consent, for light and dark.+ assert.match(css, /:root\[data-theme="dark"\],\s*\[data-theme="dark"\] \.consent \{/);+ assert.match(css, /:root\[data-theme="light"\],\s*\[data-theme="light"\] \.consent \{/);+ // On every element inside too, so a heading never takes the host's display face.+ assert.match(css, /\.consent,\s*\.consent \* \{\s*font-family: system-ui/);+ // Every token a host may set is among them.+ const embed = read("../src/lib/embed.ts");+ const tokens = [...embed.match(/THEME_TOKENS = \[([^\]]*)\]/)[1].matchAll(/"([a-z-]+)"/g)].map((m) => m[1]);+ const light = css.slice(css.indexOf('[data-theme="light"] .consent'));+ for (const token of tokens) assert.match(light, new RegExp(`--${token}:`), token);+ // And the place that asks wears it.+ assert.match(read("../src/components/embed/FrameConfirm.tsx"), /className="consent /);+});diff --git a/packages/ui/src/app/globals.css b/packages/ui/src/app/globals.cssindex d4c9578a..0a1049b1 100644--- a/packages/ui/src/app/globals.css+++ b/packages/ui/src/app/globals.css@@ -68,8 +68,20 @@/* A host's frame (embedded mode, components/embed/EmbedProvider.tsx) says* light or dark on <html data-theme>, whatever the system prefers; its own- * colours, when it sends them, are set inline on top. */-:root[data-theme="dark"] {+ * colours, when it sends them, are set inline on top.+ *+ * A `.consent` surface (a Yes asked inside a frame: FrameConfirm, the inline+ * Approve) declares this app's own colours and face again on itself, so the+ * host's colours and font never reach it: a host could otherwise draw the+ * question white on white, or in a symbol font, while the browser still+ * reports it seen (lib/seen.ts). The host's light or dark stays. */+.consent,+.consent * {+ font-family: system-ui, -apple-system, "Segoe UI", sans-serif;+}++:root[data-theme="dark"],+[data-theme="dark"] .consent {--surface-base: 9 9 11; /* zinc-950 */--surface-elevated: 17 17 19;--surface-overlay: 24 24 27; /* zinc-900 */@@ -92,7 +104,8 @@--scrollbar-thumb-hover: #52525b;}-:root[data-theme="light"] {+:root[data-theme="light"],+[data-theme="light"] .consent {--surface-base: 250 250 250;--surface-elevated: 255 255 255;--surface-overlay: 244 244 245;diff --git a/packages/ui/src/components/embed/EmbedProvider.tsx b/packages/ui/src/components/embed/EmbedProvider.tsxindex 217d0983..c13f03e2 100644--- a/packages/ui/src/components/embed/EmbedProvider.tsx+++ b/packages/ui/src/components/embed/EmbedProvider.tsx@@ -2,7 +2,8 @@import { createContext, useContext, useEffect, useRef, useState } from "react";-import { CardActionRefusedInFrame, frameActionFor } from "@/lib/cardActions";+import FrameConfirm from "@/components/embed/FrameConfirm";+import { CardActionNotConfirmed, frameActionFor, type CardAction } from "@/lib/cardActions";import HOST_LIST from "@/lib/host-list.json";import {acceptsEvent,@@ -21,12 +22,14 @@ import {//// Apart from that, in ANY frame (embedded or not, since a page on a host// origin can frame these pages without saying so), a card action, a chat-// message, and any other change off the host list that follows a click, is-// refused (lib/cardActions.ts): a page over the frame could have lured it.+// message, and any other change off the host list that follows a click,+// waits for a Yes asked inside the frame that counts only once the browser+// reports it seen (lib/cardActions.ts, lib/seen.ts, FrameConfirm): a page+// over the frame could have lured it.const HOST_CALLS = HOST_LIST.calls.map(([method, pattern]) => [method, pattern] as const);// A change made this soon after a click or a key in the frame may have been-// lured, so it is refused; later than that, the page made it on its own.+// lured, so it asks; later than that, the page made it on its own.const AFTER_INPUT_MS = 10_000;// What counts as input: a click, a key, a drop or a paste (a page over the// frame can lure any of them, and put its own file in a drag).@@ -46,6 +49,8 @@ export function useEmbed(): EmbedState {return useContext(EmbedContext);}+type Pending = { action: CardAction; resolve: (ok: boolean) => void };+function applyTheme(theme: EmbedTheme, font: string | null): void {const root = document.documentElement;root.dataset.theme = theme.mode;@@ -67,6 +72,8 @@ export default function EmbedProvider({children: React.ReactNode;}) {const [state, setState] = useState<EmbedState>(NOT_EMBEDDED);+ const [pending, setPending] = useState<Pending | null>(null);+ const pendingRef = useRef<Pending | null>(null);const lastInput = useRef(0);// The handshake: `ready` to the parent, addressed to each listed host@@ -98,7 +105,7 @@ export default function EmbedProvider({}, [hostOrigins, version]);// In any frame: every card action and chat message, and any change off- // the host list that follows a click, is refused.+ // the host list that follows a click, waits for a Yes in FrameConfirm.useEffect(() => {if (window.top === window.self) return;const onInput = (event: Event) => {@@ -106,12 +113,20 @@ export default function EmbedProvider({};for (const type of INPUT_EVENTS) window.addEventListener(type, onInput, true);const original = window.fetch;+ const confirm = (action: CardAction) =>+ new Promise<boolean>((resolve) => {+ // One at a time: a second action while one is asked about is refused.+ if (pendingRef.current) return resolve(false);+ const next = { action, resolve };+ pendingRef.current = next;+ setPending(next);+ });window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {const method = init?.method ?? (input instanceof Request ? input.method : "GET");const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;const action = frameActionFor(method, url, init?.body, HOST_CALLS);- const refused = action !== null && (action.card || Date.now() - lastInput.current < AFTER_INPUT_MS);- if (refused) throw new CardActionRefusedInFrame(action);+ const asks = action !== null && (action.card || Date.now() - lastInput.current < AFTER_INPUT_MS);+ if (asks && !(await confirm(action))) throw new CardActionNotConfirmed();return original(input, init);};return () => {@@ -120,9 +135,19 @@ export default function EmbedProvider({};}, []);+ const answer = (ok: boolean) => {+ const current = pendingRef.current;+ pendingRef.current = null;+ // A Yes is input too: what the confirmed change sets off next asks again.+ lastInput.current = Date.now();+ setPending(null);+ current?.resolve(ok);+ };+return (<EmbedContext.Provider value={state}>{children}+ {pending && <FrameConfirm action={pending.action} onAnswer={answer} />}</EmbedContext.Provider>);}diff --git a/packages/ui/src/components/embed/FrameConfirm.tsx b/packages/ui/src/components/embed/FrameConfirm.tsxnew file mode 100644index 00000000..05b1d2df--- /dev/null+++ b/packages/ui/src/components/embed/FrameConfirm.tsx@@ -0,0 +1,126 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++import { buttonClass } from "@/components/ui/Button";+import { ownPageFor, type CardAction } from "@/lib/cardActions";+import { SeenGate, tracksVisibility, watchPanel, type Watch } from "@/lib/seen";++// In a frame, a card action, a chat message or another change asks here,+// inside the frame, naming what will happen. The page around the frame+// could hide, cover or move it and lure clicks, so its Yes counts only under+// lib/seen.ts's rule: seen, pointed at for a moment, pressed and clicked for+// real, and still seen a moment later. A browser that can't report that+// offers no Yes: the person opens this app's own page for it, top level in+// the same tab, as can anyone who can't point (a keyboard, a touch screen).+// The panel keeps this app's own colours and face (`.consent`, globals.css),+// whatever the host's theme. Cancel is No.++const YES: Record<CardAction["verb"], string> = {+ approve: "Yes, approve",+ reject: "Yes, dismiss",+ cancel: "Yes, cancel it",+ change: "Yes, go ahead",+};++export default function FrameConfirm({+ action,+ onAnswer,+}: {+ action: CardAction;+ onAnswer: (ok: boolean) => void;+}) {+ const panel = useRef<HTMLDivElement | null>(null);+ const yes = useRef<HTMLButtonElement | null>(null);+ const gate = useRef(new SeenGate());+ const watch = useRef<Watch | null>(null);+ const answered = useRef(false);+ // Shown only in the browser (EmbedProvider asks from a request), so+ // `window` is there. False where the browser can't tell it is seen.+ const [supported] = useState(() => tracksVisibility(window));+ const [ownPage] = useState(() => ownPageFor(action, window.location.pathname, window.location.search));+ const [ready, setReady] = useState(false);++ const finish = useCallback(+ (ok: boolean) => {+ if (answered.current) return;+ answered.current = true;+ onAnswer(ok);+ },+ [onAnswer],+ );++ useEffect(() => {+ const check = () => setReady(watch.current?.armed() ?? false);+ const watching = panel.current+ ? watchPanel(window, panel.current, (target) => target !== null && target === yes.current, gate.current, check)+ : null;+ if (!watching) return;+ watch.current = watching;+ // The runs of "seen" and "inside" grow without an event, so look again meanwhile.+ const timer = window.setInterval(check, 100);+ return () => {+ window.clearInterval(timer);+ watching.stop();+ watch.current = null;+ };+ }, []);++ const onYes = async (event: React.MouseEvent<HTMLButtonElement>) => {+ const judged = watch.current?.judge({ isTrusted: event.nativeEvent.isTrusted, target: event.target });+ if (judged && (await judged)) finish(true);+ };++ const danger = action.verb === "reject" || action.verb === "cancel";++ return (+ <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 px-4">+ <div+ ref={panel}+ role="alertdialog"+ aria-modal="true"+ aria-labelledby="frame-confirm-title"+ className="consent w-full max-w-md rounded-2xl border border-line bg-surface-elevated p-5 shadow-xl"+ >+ <h2 id="frame-confirm-title" className="text-base font-semibold text-fg">+ Are you sure?+ </h2>+ <p className="mt-2 text-sm text-fg">{action.what}</p>+ {!supported && (+ <p className="mt-2 text-xs text-fg-subtle">+ This page is shown inside another one, and this browser can’t tell whether this question is really+ on screen, so answer it on Open Executive’s own page. Your browser’s Back brings you here again.+ </p>+ )}+ <div className="mt-5 flex justify-end gap-2">+ <button type="button" onClick={() => finish(false)} className={buttonClass("secondary", "sm")}>+ Cancel+ </button>+ {!supported ? (+ <a href={ownPage} target="_top" rel="noopener" className={buttonClass("primary", "sm")}>+ Open it here+ </a>+ ) : (+ <button+ ref={yes}+ type="button"+ onClick={(event) => void onYes(event)}+ disabled={!ready}+ className={buttonClass(danger ? "danger" : "primary", "sm")}+ >+ {YES[action.verb]}+ </button>+ )}+ </div>+ {supported && (+ <p className="mt-2 text-right text-xs text-fg-subtle">+ {!ready && "Hold the pointer on this box to answer. "}+ <a href={ownPage} target="_top" rel="noopener" className="text-accent hover:underline">+ Answer on its own page+ </a>+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/lib/cardActions.ts b/packages/ui/src/lib/cardActions.tsindex 13c937c0..3cce0cfb 100644--- a/packages/ui/src/lib/cardActions.ts+++ b/packages/ui/src/lib/cardActions.ts@@ -1,15 +1,16 @@-// In a frame, what the page changes beyond the host list is refused-// (components/embed/EmbedProvider.tsx).+// In a frame, what the page changes beyond the host list asks first+// (components/embed/EmbedProvider.tsx, FrameConfirm.tsx).//// A page that frames this one (a host origin, or any page frame-ancestors// lets in) can't read or click inside the frame, but it can make the frame-// invisible, lay its own buttons over it and catch clicks meant for those:-// a lured click beats any confirmation drawn inside the frame. So in a-// frame, approving, rejecting or cancelling a card, sending a chat message-// as the person, and any other change the host list doesn't already let the-// host make itself (a setting, Handle it for me, People) that follows a click-// is not sent: the page says to do it in Open Executive itself. Outside a-// frame nothing changes.+// invisible, lay its own buttons over it and catch clicks meant for those.+// So in a frame, approving, rejecting or cancelling a card, sending a chat+// message as the person, and any other change the host list doesn't already+// let the host make itself (a setting, Handle it for me, People) that follows+// a click, first asks inside the frame, naming what will happen; its Yes+// counts only once the browser has reported the question seen (lib/seen.ts).+// A browser that can't report it gets no Yes: the person goes to `page`, this+// app's own, top level. Outside a frame nothing changes.//// The embedded shell checks every request the page sends against// `frameActionFor`, so no call site can forget.@@ -24,10 +25,13 @@ export type CardAction = {decisionId: number | null;// What will happen, in a sentence.what: string;- // A card action is always refused in a frame. Any other change only when- // it follows a click (it could have been lured); one the page makes on its+ // A card action always asks in a frame. Any other change only when it+ // follows a click (it could have been lured); one the page makes on its// own can't have been.card: boolean;+ // The card's own page, where a browser that can't tell the frame is seen+ // answers it instead (null: the page that asked, opened on its own).+ page: string | null;};type HostCall = readonly [method: string, pattern: string];@@ -87,7 +91,7 @@ export function cardActionFor(method: string, url: string, body?: unknown): Card: verb === "reject"? `Dismiss card ${id}: nothing on it will happen.`: `Cancel card ${id}: what it started stops, and nothing more on it will happen.`;- return { verb, decisionId: id, what, card: true };+ return { verb, decisionId: id, what, card: true, page: `/cards/${id}` };}m = /^\/alerts\/(\d+)\/approve$/.exec(path);if (m) {@@ -96,6 +100,7 @@ export function cardActionFor(method: string, url: string, body?: unknown): CarddecisionId: null,what: `Approve the proposal on alert ${m[1]}: what it proposes is carried out now, as you.`,card: true,+ page: null,};}m = /^\/workflows\/runs\/([^/]+)\/decision$/.exec(path);@@ -110,13 +115,14 @@ export function cardActionFor(method: string, url: string, body?: unknown): Card? `Sign off workflow run ${run}: it carries on with what it was waiting to do.`: `Turn down workflow run ${run}: it stops where it is waiting.`,card: true,+ page: null,};}m = /^\/people\/requests\/(\d+)\/(approve|decline)$/.exec(path);if (m) {return m[2] === "approve"- ? { verb: "approve", decisionId: null, what: `Add the person in request ${m[1]} to People, as you answered it.`, card: true }- : { verb: "reject", decisionId: null, what: `Decline request ${m[1]}: they are not added to People.`, card: true };+ ? { verb: "approve", decisionId: null, what: `Add the person in request ${m[1]} to People, as you answered it.`, card: true, page: null }+ : { verb: "reject", decisionId: null, what: `Decline request ${m[1]}: they are not added to People.`, card: true, page: null };}return null;}@@ -183,6 +189,7 @@ export function frameActionFor(// Always: a queued message or Try again may carry words that weren't// typed here.card: true,+ page: null,};}if (onHostList(hostCalls, verb, path)) return null;@@ -192,12 +199,27 @@ export function frameActionFor(decisionId: null,what: `${named ? named[1] : "Make this change in Open Executive, as you."} (${verb} ${path.slice(0, 120)})`,card: false,+ page: null,};}-export class CardActionRefusedInFrame extends Error {- constructor(action: CardAction) {- super(`Not done in this frame. ${action.what} To do it, open Open Executive itself.`);- this.name = "CardActionRefusedInFrame";+/**+ * Where a browser that can't tell the frame is seen answers `action`: the+ * card's own page, or else the page that asked (`pathname` + `search`), in+ * both cases without `embed`, so it opens as this app's own page.+ */+export function ownPageFor(action: CardAction, pathname: string, search: string): string {+ if (action.page) return action.page;+ const params = new URLSearchParams(search);+ params.delete("embed");+ const query = params.toString();+ const path = pathname.startsWith("/") && !pathname.startsWith("//") ? pathname : "/";+ return query ? `${path}?${query}` : path;+}++export class CardActionNotConfirmed extends Error {+ constructor() {+ super("Not confirmed, so nothing was done.");+ this.name = "CardActionNotConfirmed";}}diff --git a/packages/ui/src/lib/seen.ts b/packages/ui/src/lib/seen.tsnew file mode 100644index 00000000..c5f1a09a--- /dev/null+++ b/packages/ui/src/lib/seen.ts@@ -0,0 +1,224 @@+// Whether a button inside a frame was really seen when it was clicked+// (components/embed/FrameConfirm.tsx).+//+// A page that frames this app (a host origin; frame-ancestors lets no other+// site) can't read or script the frame, but it can place it, move it, make+// it invisible, cover it and lure clicks onto it. IntersectionObserver v2+// (`trackVisibility: true`, Chromium) answers, from inside the frame, whether+// an element is on screen uncovered, at full opacity, untransformed and+// unfiltered, and the page around can't fake that answer: the browser+// computes it. So a Yes in a frame counts only when:+//+// - the panel holding it has been reported whole on screen and visible,+// without a break, for at least SEEN_MS. A lured second click on a hidden+// frame fails this; so does a cover that lets clicks through+// (`pointer-events: none`), and a frame cropped to show the Yes without+// the words that say what it does;+// - the real pointer has been inside the panel, without leaving, for at+// least DWELL_MS, and has moved there (a cursor drawn by the page+// elsewhere doesn't move it). A frame slid under the pointer between the+// two clicks of a lured double-click fails this: the pointer has only just+// entered. Leaving the panel, or the frame losing focus, starts it again;+// - the press began on Yes itself after all of that held, and the click that+// follows is trusted and on Yes too. A key press on a focused Yes has no+// pointer press, so it never counts; the panel offers this app's own page+// instead;+// - the panel is still seen, and the pointer still inside, SETTLE_MS after+// the click. The browser reports a change at most every OBSERVE_DELAY_MS,+// so a cover laid on just before the click shows up by then; reports not+// yet delivered are taken at each look (`takeRecords`).+//+// A browser without v2 (Firefox, Safari) can't tell, so the frame never+// offers a Yes there: it sends the person to this app's own page, top level+// in the same tab, where nothing can frame it. Never fail open.+//+// The answer stays in the browser. It guards against code on the host's+// origin, which can't run in this one; the approval is still this app's own+// same-origin request with its usual checks.+//+// No imports, so `npm test` can exercise this with faked entries and events.++export const SEEN_MS = 700;+// Longer than a double-click's interval.+export const DWELL_MS = 500;+// The smallest delay trackVisibility accepts.+export const OBSERVE_DELAY_MS = 100;+// Two of the browser's reporting rounds, and a frame.+export const SETTLE_MS = 2 * OBSERVE_DELAY_MS + 50;++/** What the gate reads from an IntersectionObserverEntry. */+export type SeenEntry = { isIntersecting: boolean; intersectionRatio: number; isVisible?: boolean; time: number };++// Whole on screen, allowing for rounding.+const WHOLE = 0.99;++/** Whether this browser's IntersectionObserver can report visibility (v2). */+export function tracksVisibility(win: unknown): boolean {+ const w = win as { IntersectionObserver?: unknown; IntersectionObserverEntry?: { prototype?: object } } | null;+ if (!w || typeof w.IntersectionObserver !== "function") return false;+ const proto = w.IntersectionObserverEntry?.prototype;+ return typeof proto === "object" && proto !== null && "isVisible" in proto;+}++/** Times are on the observer's clock (`performance.now()`). */+export class SeenGate {+ // When the panel was last reported visible after a break, or null.+ private visibleSince: number | null = null;+ // When the pointer last came into the panel, or null while it's outside.+ private insideSince: number | null = null;+ // Whether it has moved in the panel, while seen, since it came in.+ private moved = false;+ // When a press on Yes began while armed, and the run it began in.+ private pressedAt: number | null = null;+ private pressRun: number | null = null;++ /** An observer entry for the panel: anything short of whole and visible breaks the run. */+ observe(entry: SeenEntry): void {+ if (entry.isIntersecting && entry.intersectionRatio >= WHOLE && entry.isVisible === true) {+ if (this.visibleSince === null) this.visibleSince = entry.time;+ } else {+ this.visibleSince = null;+ this.insideSince = null;+ this.moved = false;+ this.pressedAt = null;+ }+ }++ /** The pointer came into the panel (`pointerenter`), or moved in it. */+ pointerInside(isTrusted: boolean, now: number, moving: boolean): void {+ if (!isTrusted) return;+ if (this.insideSince === null) this.insideSince = now;+ if (moving && this.visibleSince !== null) this.moved = true;+ }++ /** The pointer left the panel, or the frame lost focus: start again. */+ pointerGone(): void {+ this.insideSince = null;+ this.moved = false;+ this.pressedAt = null;+ }++ /** Whether the panel has been visible for long enough. */+ seenFor(now: number): boolean {+ return this.visibleSince !== null && now - this.visibleSince >= SEEN_MS;+ }++ /** Whether a press on Yes would count now. */+ armed(now: number): boolean {+ return this.moved && this.seenFor(now) && this.insideSince !== null && now - this.insideSince >= DWELL_MS;+ }++ /** A press began (`pointerdown`): it counts only on Yes, trusted, while armed. */+ pressed(press: { isTrusted: boolean; onYes: boolean; now: number }): void {+ const counts = press.isTrusted && press.onYes && this.armed(press.now);+ this.pressedAt = counts ? press.now : null;+ this.pressRun = counts ? this.visibleSince : null;+ }++ /** Whether a click counts: trusted, on Yes, after a press that counted, still armed. */+ clickCounts(click: { isTrusted: boolean; onYes: boolean; now: number }): boolean {+ return click.isTrusted && click.onYes && this.pressedAt !== null && this.armed(click.now);+ }++ /** After SETTLE_MS: the same run of "seen" as at the press, and the pointer still in. */+ stillSeen(now: number): boolean {+ return this.pressRun !== null && this.visibleSince === this.pressRun && this.armed(now);+ }++ /** A press counts for one click at most; one released off Yes counts for none. */+ pressUsed(): void {+ this.pressedAt = null;+ this.pressRun = null;+ }+}++type Observer = { observe(el: unknown): void; disconnect(): void; takeRecords(): SeenEntry[] };+type ObserverCtor = new (+ cb: (entries: SeenEntry[]) => void,+ options: { threshold: number[]; trackVisibility: boolean; delay: number },+) => Observer;+type Listener = (event: PointerLike) => void;+type Target = {+ addEventListener(type: string, listener: Listener): void;+ removeEventListener(type: string, listener: Listener): void;+};+type PointerLike = { isTrusted: boolean; target: unknown };+type Win = {+ IntersectionObserver: ObserverCtor;+ performance: { now(): number };+ setTimeout(fn: () => void, ms: number): unknown;+} & Target;++export type Watch = {+ /** Whether `armed` now (for showing Yes as ready). */+ armed: () => boolean;+ /** Judge a click on Yes: resolves true only if it counts and still holds SETTLE_MS later. */+ judge: (click: PointerLike) => Promise<boolean>;+ stop: () => void;+};++/**+ * Watch `panel` with v2 and the pointer, feeding `gate`; `changed` is called+ * on every report. `isYes` says whether an event's target is the Yes button.+ * Null where v2 is missing: then nothing can arm.+ */+export function watchPanel(+ win: unknown,+ panel: Target,+ isYes: (target: unknown) => boolean,+ gate: SeenGate,+ changed: () => void,+): Watch | null {+ if (!tracksVisibility(win)) return null;+ const w = win as Win;+ const now = () => w.performance.now();+ const feed = (entries: SeenEntry[]) => {+ for (const entry of entries) gate.observe(entry);+ changed();+ };+ const observer = new w.IntersectionObserver(feed, { threshold: [1.0], trackVisibility: true, delay: OBSERVE_DELAY_MS });+ observer.observe(panel);+ const flush = () => feed(observer.takeRecords());++ const onEnter = (e: PointerLike) => gate.pointerInside(e.isTrusted, now(), false);+ const onMove = (e: PointerLike) => gate.pointerInside(e.isTrusted, now(), true);+ const onGone = () => {+ gate.pointerGone();+ changed();+ };+ const onDown = (e: PointerLike) => {+ flush();+ gate.pressed({ isTrusted: e.isTrusted, onYes: isYes(e.target), now: now() });+ };+ const onUp = (e: PointerLike) => {+ if (!isYes(e.target)) gate.pressUsed();+ };+ const panelEvents: [string, Listener][] = [+ ["pointerenter", onEnter],+ ["pointermove", onMove],+ ["pointerleave", onGone],+ ["pointercancel", onGone],+ ["pointerdown", onDown],+ ["pointerup", onUp],+ ];+ for (const [type, fn] of panelEvents) panel.addEventListener(type, fn);+ w.addEventListener("blur", onGone);++ return {+ armed: () => gate.armed(now()),+ judge: async (click) => {+ flush();+ if (!gate.clickCounts({ isTrusted: click.isTrusted, onYes: isYes(click.target), now: now() })) return false;+ await new Promise<void>((resolve) => w.setTimeout(resolve, SETTLE_MS));+ flush();+ const still = gate.stillSeen(now());+ gate.pressUsed();+ return still;+ },+ stop: () => {+ observer.disconnect();+ for (const [type, fn] of panelEvents) panel.removeEventListener(type, fn);+ w.removeEventListener("blur", onGone);+ },+ };+}