Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Published apps: a page of everything bots put online, a preview beside the chat, and Delete (#5477)
Milind Soni11b0208f4b60
diff --git a/docs/verification/README.md b/docs/verification/README.mdindex 6fc9e57778..9f204098a5 100644--- a/docs/verification/README.md+++ b/docs/verification/README.md@@ -70,6 +70,7 @@ Use only mapped, tested commands:- [A new Cloud's first hour](first-hour.md)- [Chat widgets](widgets.md)- [Pages and apps in a room](room-pages.md)+- [Published apps](published-apps.md)- [The Inbox on every plan](inbox.md)- [Reactions](reactions.md)- [Chat widgets: prompts to try with a real bot](widget-prompts.md)diff --git a/docs/verification/published-apps.md b/docs/verification/published-apps.mdnew file mode 100644index 0000000000..1f0dc617d7--- /dev/null+++ b/docs/verification/published-apps.md@@ -0,0 +1,73 @@+# Published apps++The Published apps page (Tools → Published apps) lists what bots put online: the pages this server published to a+MausBot link, and the sites bots published to the person's own Netlify account, found from the `.netlify-site.json`+records in the bots' own folders (`skills/publish-to-netlify/site-record.md`). A card's Preview, and a published link+in a bot's message, open the app in a sandboxed frame beside the conversation. Delete takes an app down for good.++## The list, who sees what, and Delete++```sh+pnpm exec vitest run server/host/netlify-sites.test.ts server/host/published-apps.test.ts server/routes/published-apps.test.ts+```++- Records are found at most four folders deep, never in hidden folders or `node_modules`, never through a link, never+ over 16 KB, at most 50 a bot; the person's home folder and anything above it is never searched.+- A record belongs to the bot whose folder holds it, whatever bot it names. Its address must be plain https, and its+ Netlify account page must be on `app.netlify.com`.+- On a Team Cloud a person is shown an app only through a conversation they can read in which the bot published it (a+ page's card, or the bot's own message carrying the site's link). An admin sees what shared bots published in shared+ conversations and nobody's private project. An id or address of an app someone is not shown answers 404.+- Delete: a page is unpublished; a Netlify site is deleted with `DELETE /sites/<id>` using the token saved for that+ bot, a 404 from Netlify counts as deleted, and the record is removed. Without a usable token nothing is called and+ the answer offers the site's Netlify page. The token is in no answer and no log line.++A real Team Cloud with four people (two members, an Admin, the Owner) and real turns:++```sh+pnpm exec vitest run server/cloud-team-published-apps.e2e.test.ts+```++A site whose record is in a conversation's own folder (`task-workspaces/<bot>/<thread>`) is that conversation's; one in+a folder the bot's conversations share is listed where the bot's own message carries its link, and nowhere when it+never said it. Another member, an Admin and the Owner get 404 for a member's private project by id. Delete answers+`no_token` with the site's Netlify page until a token is saved; with the team's shared token an Admin deletes the+shared chat's site and a member their own, on the loopback stand-in. A member's own saved token is used only on that+member's own click (`savedNetlifyToken`, in `server/host/netlify-sites.test.ts`).++## The page, the cards and the preview++```sh+pnpm exec vitest run src/components/published-apps src/lib/published-links.test.ts+```++`src/components/published-apps/preview.security.test.ts` holds the frame's sandbox (`allow-scripts allow-same-origin allow-forms allow-popups`, a+card's picture only the first two), that the app's own origin and anything but a plain web address is never framed,+that the preview registers no message listener and passes nothing into the frame, and that the desktop window keeps+its preload out of frames.++## Renderer and server, end to end++```sh+OMB_UI_EVIDENCE_DIR=evidence/published-apps pnpm exec vitest run scripts/testing/published-apps-ui.e2e.test.ts+```++It runs when an agent-browser binary resolves, as in [Chat UI, driven headlessly](chat-ui.md), and is skipped+otherwise; `OMB_UI_E2E=1` forces the verified download. The fixture's server gets `OMB_NETLIFY_API_URL`, the loopback+stand-in (`server/testing/fake-netlify.ts`), which the launcher lets cross only when it is `http://127.0.0.1:PORT/api/v1`.++- The real publish helper deploys two sites from Pepper's folder to the stand-in; one is then made to ask for a login.+- The page shows the empty state first, then both cards: the public site drawn live and small, the other as a tile.+ Its header matches the Automations page's, with the sidebar still there.+- Preview opens Pepper's chat with the site beside it. The site's own script tries the bridge, the parent's document+ and storage, and navigating the window: each is undefined or blocked, while its own storage works.+- The link in Pepper's message opens the same preview. The login-only site shows the fallback with Open in browser.+- Delete is refused with a plain line while no token is saved, then, with one saved in the Vault, deletes the site on+ the stand-in and its record. The token appears in no answer, page or server log.+- At 390 px wide the page is one column and the preview covers the screen.++`OMB_PUBLISHED_APPS_REAL_SITES="https://one.netlify.app https://two.netlify.app"` also frames those public sites from a+link in a message, read-only.++Not proven here: a real Netlify account, the desktop app's own window (the Electron rules are asserted from source),+and a Team Cloud in the renderer.diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex cc8fdd5c69..3174611326 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -103,6 +103,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-privacy-holes.e2e.test.ts","server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts",+ "server/cloud-team-published-apps.e2e.test.ts","server/cloud-team-requests.e2e.test.ts","server/cloud-team-routines.e2e.test.ts","server/cloud-team-setup-request.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 4cdb4ee9a4..d0815e9397 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -243,6 +243,7 @@ describe("CI outputs", () => {"server/cloud-team-privacy-holes.e2e.test.ts","server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts",+ "server/cloud-team-published-apps.e2e.test.ts","server/cloud-team-requests.e2e.test.ts","server/cloud-team-routines.e2e.test.ts","server/cloud-team-setup-request.e2e.test.ts",diff --git a/scripts/control-omb.test.ts b/scripts/control-omb.test.tsindex cc3a681e67..1f97eed9ee 100644--- a/scripts/control-omb.test.ts+++ b/scripts/control-omb.test.ts@@ -27,6 +27,15 @@ describe("the fixture's fake engine knobs", () => {});});+describe("the fixture's Netlify stand-in", () => {+ it("lets only a loopback stand-in's API address cross, so a fixture never lists or deletes on Netlify", () => {+ expect(childEnv({ OMB_NETLIFY_API_URL: " http://127.0.0.1:4010/api/v1 " }).OMB_NETLIFY_API_URL).toBe("http://127.0.0.1:4010/api/v1");+ for (const url of ["https://api.netlify.com/api/v1", "http://localhost:4010/api/v1", "http://127.0.0.1:4010", "http://127.0.0.1:4010/api/[email protected]", "http://192.0.2.1:4010/api/v1", ""]) {+ expect(childEnv({ OMB_NETLIFY_API_URL: url }), url).not.toHaveProperty("OMB_NETLIFY_API_URL");+ }+ });+});+describe("the fixture's Live call environment", () => {it("passes a loopback fake GPT-Live and its key through", () => {expect(childEnv({ OMB_OPENAI_LIVE_URL: " http://127.0.0.1:4100 ", OMB_OPENAI_LIVE_KEY: "sk-fake" }))diff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex 7a1f460b72..b71488282f 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -189,6 +189,10 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, data// A loopback stand-in for Postiz Cloud only (server/testing/fake-postiz.ts): no test signs in to the real one.const postizUrl = parentEnv.OMB_POSTIZ_CLOUD_URL?.trim() ?? "";if (/^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(postizUrl)) childEnv.OMB_POSTIZ_CLOUD_URL = postizUrl;+ // A loopback stand-in for Netlify only (server/testing/fake-netlify.ts): the Published apps page then lists and+ // deletes sites there, never on Netlify.+ const netlifyUrl = parentEnv.OMB_NETLIFY_API_URL?.trim() ?? "";+ if (/^http:\/\/127\.0\.0\.1:\d{1,5}\/api\/v1$/.test(netlifyUrl)) childEnv.OMB_NETLIFY_API_URL = netlifyUrl;// A loopback connected-apps service only (server/testing/broker-fake.ts): its token never reaches the real one.const brokerUrl = parentEnv.OMB_COMPOSIO_BROKER_URL?.trim() ?? "";if (/^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(brokerUrl) && parentEnv.OMB_COMPOSIO_BROKER_TOKEN) {diff --git a/scripts/testing/published-apps-ui.e2e.test.ts b/scripts/testing/published-apps-ui.e2e.test.tsnew file mode 100644index 0000000000..2961baee80--- /dev/null+++ b/scripts/testing/published-apps-ui.e2e.test.ts@@ -0,0 +1,298 @@+// The Published apps page and the preview beside the chat, in the real renderer against a launched server. A bot's+// folder gets two sites from the real publish helper, on a loopback stand-in for Netlify that also serves them. The+// page lists them, the preview frames one beside the chat (from its card and from a link in the bot's message), the+// framed site reports what it could reach of the app (nothing), and Delete removes the site on the stand-in and its+// record. Needs the pinned agent-browser binary: runs when one resolves (tools directory, OMB_AGENT_BROWSER_PATH or+// PATH) or OMB_UI_E2E=1 asks for the verified download; otherwise skipped.+import { spawn } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { afterAll, expect, it } from "vitest";++import { resolveAgentBrowserBinary } from "../../server/browser-engine.ts";+import { NETLIFY_TOKEN_LABEL, SITE_FILE } from "../../server/host/netlify-sites.ts";+import { removeTempDir, waitForExit } from "../../server/testing/cleanup.ts";+import { startFakeNetlify } from "../../server/testing/fake-netlify.ts";+// @ts-expect-error the skill's helper is plain JavaScript with no types+import { publish } from "../../skills/publish-to-netlify/deploy.mjs";+import { runControlOmb } from "../control-omb.ts";+import { agentBrowser, sessionEnv, UI_TOOLS_DIR, type UiHandle } from "./control-omb-ui.ts";+import { fixtureApi } from "./preview-fixture.ts";++const ROOT = fileURLToPath(new URL("../..", import.meta.url));+const forced = process.env.OMB_UI_E2E === "1";+const enabled = forced || Boolean(resolveAgentBrowserBinary({ dataDir: UI_TOOLS_DIR, env: process.env }));+if (!enabled) console.log("skipping published apps ui e2e: no agent-browser binary resolves; set OMB_UI_E2E=1 to install the pinned release");+const LAUNCH_TIMEOUT_MS = forced ? 600_000 : 180_000;+const TOKEN = "nfp_published_apps_ui_token_0123456789abcdef";++const evidenceDir = process.env.OMB_UI_EVIDENCE_DIR ? resolve(ROOT, process.env.OMB_UI_EVIDENCE_DIR) : mkdtempSync(join(tmpdir(), "omb-ui-evidence-"));+afterAll(async () => { if (!process.env.OMB_UI_EVIDENCE_DIR) await removeTempDir(evidenceDir); });++/** What a hostile site would try first, written into the page so the frame's own text says how each attempt went. */+const SITE = (name: string, color: string) => `<!DOCTYPE html><html><head><meta charset="utf-8"><title>${name}</title><style>+body{margin:0;font:16px/1.5 system-ui,sans-serif;background:${color};color:#1c1917}+header{padding:28px 32px;font-size:30px;font-weight:700}main{padding:0 32px}li{margin:4px 0}+</style></head><body><header>${name}</header><main><p>Order before noon for same-day pickup.</p><ul id="probe"></ul></main><script>+const tries = {+ bridge: () => typeof window.ogb,+ parentBridge: () => typeof parent.ogb,+ mausbot: () => typeof window.mausbot,+ parentDocument: () => parent.document.title,+ parentStorage: () => parent.localStorage.length,+ topAddress: () => top.location.href,+ navigateTop: () => { top.location = "https://example.com/"; return "navigated"; },+ ownStorage: () => { localStorage.setItem("probe", "1"); return localStorage.getItem("probe") === "1" ? "works" : "broken"; },+ referrer: () => document.referrer || "none",+};+for (const [name, attempt] of Object.entries(tries)) {+ let outcome;+ try { outcome = String(attempt()); } catch (error) { outcome = "blocked"; }+ const line = document.createElement("li");+ line.textContent = "probe " + name + ": " + outcome;+ document.getElementById("probe").append(line);+}+</script></body></html>`;++async function launch(env: NodeJS.ProcessEnv): Promise<{ child: ReturnType<typeof spawn>; info: { ui: string; url: string; botId: string; dataDir: string; logPath: string } }> {+ const child = spawn(process.execPath, ["--experimental-strip-types", join(ROOT, "scripts", "control-omb.ts"), "ui", "launch"], {+ cwd: ROOT, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32",+ });+ let stdout = "", stderr = "";+ child.stdout!.on("data", (chunk) => { stdout += String(chunk); });+ child.stderr!.on("data", (chunk) => { stderr += String(chunk); });+ const deadline = Date.now() + LAUNCH_TIMEOUT_MS;+ for (;;) {+ if (child.exitCode !== null) throw new Error(`ui launch exited ${child.exitCode}: ${stderr}`);+ const start = stdout.indexOf("{");+ if (start !== -1) {+ try { return { child, info: JSON.parse(stdout.slice(start)) }; } catch { /* not all of it yet */ }+ }+ if (Date.now() > deadline) throw new Error(`ui launch printed no handle: ${stderr}`);+ await new Promise((done) => setTimeout(done, 250));+ }+}++async function until<T>(probe: () => Promise<T> | T, what: string, timeoutMs = 30_000): Promise<NonNullable<T>> {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ const value = await probe();+ if (value) return value as NonNullable<T>;+ if (Date.now() > deadline) throw new Error(`${what} did not happen within ${timeoutMs}ms`);+ await new Promise((done) => setTimeout(done, 250));+ }+}++(enabled ? it : it.skip)("lists what a bot published, previews it beside the chat in a sandbox that reaches nothing, and deletes it", async () => {+ const scratch = mkdtempSync(join(tmpdir(), "omb-published-apps-"));+ const replyFile = join(scratch, "reply.txt"), tokenFile = join(scratch, "netlify-token");+ writeFileSync(tokenFile, TOKEN);+ const fake = await startFakeNetlify(TOKEN);+ const { child, info } = await launch({ ...process.env, OMB_NETLIFY_API_URL: fake.url, FAKE_CLAUDE_REPLY_FILE: replyFile });+ try {+ const api = fixtureApi(info.url, { headers: { origin: info.url } });+ const ui = (verb: string, ...args: string[]) => runControlOmb(["ui", verb, "--ui", info.ui, ...args]) as Promise<Record<string, any>>;+ const evaluate = async (js: string) => (await ui("eval", "--js", js)).result;+ const browser = JSON.parse(readFileSync(info.ui, "utf8")) as UiHandle;+ const viewport = (width: number, height: number) => agentBrowser(browser.binary, sessionEnv(browser), ["set", "viewport", String(width), String(height)]);+ /** The accessibility tree reaches into the frames: what a framed site shows is readable here. */+ const shows = async (text: string) => JSON.stringify(await ui("snapshot")).includes(JSON.stringify(text).slice(1, -1));+ const shot = async (name: string) => { await new Promise((done) => setTimeout(done, 500)); await ui("screenshot", "--out", join(evidenceDir, `${name}.png`)); };+ const press = (selector: string) => evaluate(`(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return false; el.click(); return true; })()`);+ const openPage = async () => {+ if (!await press('[data-sidebar-nav="published-apps"]')) throw new Error("the Tools section has no Published apps entry");+ await until(() => evaluate(`Boolean(document.querySelector('[data-published-apps]:not([data-published-apps="loading"])'))`), "the Published apps page to load");+ };+ const cards = () => evaluate(`[...document.querySelectorAll('[data-published-app]')].map((card) => card.querySelector('h2').textContent)`) as Promise<string[]>;+ mkdirSync(evidenceDir, { recursive: true });+ await viewport(1280, 860);+ // Advanced mode keeps the Tools section in the sidebar; Simple mode has the same entry in the account menu.+ await evaluate(`localStorage.setItem("omb-advanced-mode", "1"); window.dispatchEvent(new StorageEvent("storage", { key: "omb-advanced-mode" })); true`);++ // Nothing published yet: the page says what it is and how to get the first app.+ await until(() => evaluate(`Boolean(document.querySelector('[data-sidebar-nav="published-apps"]'))`), "the Tools section's Published apps entry");+ await shot("tools-menu-desktop");+ await openPage();+ expect(await cards()).toEqual([]);+ expect(await evaluate(`document.querySelector('main[aria-label="Published apps"]').textContent`)).toContain("Ask a bot to build a site or app and publish it.");+ await shot("empty-desktop");++ // The bot publishes two sites from its own folder with the real helper; the second one asks for a Netlify login.+ const workspace = join(info.dataDir, "workspaces", info.botId);+ const deploy = async (folder: string, title: string, color: string, extra: string[] = []) => {+ const project = join(workspace, folder);+ mkdirSync(join(project, "dist"), { recursive: true });+ writeFileSync(join(project, "dist", "index.html"), SITE(title, color));+ const env = { OMB_NETLIFY_API_URL: fake.url, OMB_BOT_ID: info.botId };+ const result = await publish(["--dir", join(project, "dist"), "--project", project, "--token-file", tokenFile, "--title", title, "--bot-name", "Pepper", ...extra], env, { pollMs: 50, privateAfterMs: 200 });+ expect(result, JSON.stringify(result)).toMatchObject({ ok: true, state: "ready" });+ return { project, env, siteId: result.siteId as string, url: result.url as string };+ };+ const bakery = await deploy("bakery", "Bakery order page", "#fde68a");+ const rota = await deploy("rota", "Staff rota", "#bfdbfe");+ fake.sites.get(rota.siteId)!.teamLogin = true;+ expect(await publish(["--check", "--project", rota.project, "--token-file", tokenFile], rota.env, { pollMs: 50, privateAfterMs: 200, linkWaitMs: 2_000 })).toMatchObject({ access: "private" });+ expect(JSON.parse(readFileSync(join(rota.project, SITE_FILE), "utf8"))).toMatchObject({ access: "private", botId: info.botId });++ const listed = await until(async () => { const { apps } = await api("GET", "/api/published-apps"); return apps.length === 2 ? apps as Array<Record<string, any>> : null; }, "both sites to be listed");+ expect(listed.map((app) => [app.title, app.source, app.bot.name, app.access, app.url, app.canDelete]).sort()).toEqual([+ ["Bakery order page", "netlify", "Pepper", "public", bakery.url, true],+ ["Staff rota", "netlify", "Pepper", "netlify-team", rota.url, true],+ ]);+ expect(JSON.stringify(listed)).not.toContain(TOKEN);++ // The page: one card each, the public one drawn live and small, the login-only one as a plain tile.+ await press('button[aria-label="Back"]');+ await openPage();+ expect((await cards()).sort()).toEqual(["Bakery order page", "Staff rota"]);+ const card = (id: string) => `[data-published-app="netlify-${info.botId}-${id}"]`;+ await until(() => evaluate(`document.querySelector('${card(bakery.siteId)} [data-app-thumb]').getAttribute("data-app-thumb") === "live"`), "the bakery card's live picture");+ expect(await evaluate(`document.querySelector('${card(rota.siteId)} [data-app-thumb]').getAttribute("data-app-thumb")`)).toBe("tile");+ expect(await evaluate(`[...document.querySelectorAll('${card(bakery.siteId)} iframe')].map((frame) => [frame.getAttribute("sandbox"), frame.getAttribute("tabindex"), getComputedStyle(frame).pointerEvents])`))+ .toEqual([["allow-scripts allow-same-origin", "-1", "none"]]);+ expect(await evaluate(`[document.querySelector('${card(bakery.siteId)} [data-app-access]').textContent, document.querySelector('${card(rota.siteId)} [data-app-access]').textContent]`))+ .toEqual(["Public", "Only your Netlify team"]);+ await shot("page-desktop");++ // The same page chrome as Automations and its calendar: the sidebar stays, and the header is the one they share.+ const chrome = () => evaluate(`(() => { const header = document.querySelector("main > header"), title = header.querySelector("h1"), back = header.querySelector("button"), style = getComputedStyle(title);+ const box = (el) => { const r = el.getBoundingClientRect(); return [Math.round(r.left), Math.round(r.top), Math.round(r.height)]; };+ return { header: box(header), back: box(back), title: box(title).slice(0, 2), font: [style.fontSize, style.fontWeight], sidebar: Boolean(document.querySelector('[data-sidebar-nav="automations"]')),+ main: getComputedStyle(header.parentElement).backgroundColor }; })()`);+ const appsChrome = await chrome();+ await press('[data-sidebar-nav="automations"]');+ await until(() => evaluate(`document.querySelector("main > header h1")?.textContent === "Automations"`), "the Automations page");+ await shot("automations-desktop");+ expect(appsChrome).toEqual(await chrome());+ expect(appsChrome.sidebar).toBe(true);+ await openPage();++ // Preview: the bot's chat on the left, the site on the right, in the sandbox.+ await press(`${card(bakery.siteId)} button[aria-label="Preview Bakery order page"]`);+ await until(() => evaluate(`Boolean(document.querySelector('aside[data-app-preview] iframe[data-app-preview-frame]') && document.querySelector('textarea[aria-label="Message Pepper"]'))`), "the preview beside Pepper's chat");+ expect(await evaluate(`(() => { const frame = document.querySelector('aside[data-app-preview] iframe'); return [frame.getAttribute("src"), frame.getAttribute("sandbox"), frame.getAttribute("referrerpolicy")]; })()`))+ .toEqual([bakery.url, "allow-scripts allow-same-origin allow-forms allow-popups", "no-referrer"]);+ await until(() => shows("probe referrer: none"), "the framed site to report its probes");+ const probes = [...new Set(JSON.stringify(await ui("snapshot")).match(/probe \w+: [\w ]+/g))].sort();+ expect(probes).toEqual(["probe bridge: undefined", "probe mausbot: undefined", "probe navigateTop: blocked", "probe ownStorage: works", "probe parentBridge: blocked", "probe parentDocument: blocked",+ "probe parentStorage: blocked", "probe referrer: none", "probe topAddress: blocked"]);+ expect(await evaluate("location.href")).toContain("127.0.0.1");+ await shot("preview-desktop");++ // Reload gives a new frame of the same site; Close gives the side back.+ await evaluate(`window.__firstFrame = document.querySelector('aside[data-app-preview] iframe'); true`);+ await press('aside[data-app-preview] button[aria-label="Reload"]');+ await until(() => evaluate(`document.querySelector('aside[data-app-preview] iframe') !== window.__firstFrame`), "a reloaded frame");+ await press('aside[data-app-preview] button[aria-label="Close preview"]');+ await until(() => evaluate(`!document.querySelector('aside[data-app-preview]')`), "the preview to close");++ // A published link in the bot's message opens the same preview.+ writeFileSync(replyFile, `Published your bakery page: ${bakery.url} The link is public.`);+ await ui("type", "--name", "Message Pepper", "--text", "publish the bakery page");+ await ui("press", "--keys", "Enter");+ const link = `a[href="${bakery.url}"]`;+ await until(() => evaluate(`Boolean(document.querySelector('${link}'))`), "the bot's message with the link", 60_000);+ await ui("wait-settle", "--timeout", "60");+ await press(link);+ await until(() => evaluate(`document.querySelector('aside[data-app-preview] iframe')?.getAttribute("src") === ${JSON.stringify(bakery.url)}`), "the link to open the preview");+ expect(await evaluate(`document.querySelector('aside[data-app-preview] h2').textContent`)).toBe("Bakery order page");+ await shot("preview-from-link-desktop");+ await press('aside[data-app-preview] button[aria-label="Close preview"]');++ // With OMB_PUBLISHED_APPS_REAL_SITES (addresses separated by spaces) the same link click frames real public sites,+ // read-only: nothing is deployed and Netlify's API is never called.+ for (const [index, site] of (process.env.OMB_PUBLISHED_APPS_REAL_SITES ?? "").split(/\s+/).filter(Boolean).entries()) {+ writeFileSync(replyFile, `Here it is: ${site}`);+ await ui("type", "--name", "Message Pepper", "--text", `show me site ${index + 1}`);+ await ui("press", "--keys", "Enter");+ await until(() => evaluate(`Boolean(document.querySelector('a[href="${site}"]'))`), `the message linking ${site}`, 60_000);+ await ui("wait-settle", "--timeout", "60");+ await press(`a[href="${site}"]`);+ await until(() => evaluate(`document.querySelector('aside[data-app-preview] iframe')?.getAttribute("src") === ${JSON.stringify(site)}`), `${site} in the preview`);+ await new Promise((done) => setTimeout(done, 5_000));+ await shot(`real-site-${index + 1}-desktop`);+ await press('aside[data-app-preview] button[aria-label="Close preview"]');+ }++ // A site that asks for a login is not framed: a plain line and Open in browser.+ await openPage();+ await press(`${card(rota.siteId)} button[aria-label="Preview Staff rota"]`);+ await until(() => evaluate(`Boolean(document.querySelector('aside[data-app-preview] [data-app-preview-fallback]'))`), "the fallback for a login-only site");+ expect(await evaluate(`[Boolean(document.querySelector('aside[data-app-preview] iframe')), document.querySelector('aside[data-app-preview] [data-app-preview-fallback]').textContent]`))+ .toEqual([false, expect.stringContaining("This site asks for a Netlify login.")]);+ await shot("preview-fallback-desktop");+ await press('aside[data-app-preview] button[aria-label="Close preview"]');++ // Phone width: the page, and the preview over the chat.+ await viewport(390, 844);+ // The fixture's own offer card sits over the corner at this width.+ await evaluate(`[...document.querySelectorAll("button")].find((button) => button.textContent.trim() === "Not now")?.click(); true`);+ await evaluate(`(document.querySelector('[data-sidebar-nav="published-apps"]') ?? document.querySelector('button[aria-label="Tools"], [data-sidebar-phone-bar] button'))?.click(); true`);+ if (!await evaluate(`Boolean(document.querySelector('[data-published-apps]'))`)) {+ await shot("tools-menu-phone");+ await evaluate(`[...document.querySelectorAll('[role="menuitem"], button')].find((item) => item.textContent.trim() === "Published apps")?.click(); true`);+ }+ await until(() => evaluate(`Boolean(document.querySelector('[data-published-apps]:not([data-published-apps="loading"])'))`), "the page at phone width");+ await shot("page-phone");+ const phoneChrome = await chrome();+ await evaluate(`document.querySelector('[data-sidebar-phone-bar] button')?.click(); true`);+ await evaluate(`[...document.querySelectorAll('[role="menuitem"], button')].find((item) => item.textContent.trim() === "Automations")?.click(); true`);+ await until(() => evaluate(`document.querySelector("main > header h1")?.textContent === "Automations"`), "the Automations page at phone width");+ await shot("automations-phone");+ // Automations' own controls wrap under its title at this width, so only its header is taller.+ expect({ ...phoneChrome, sidebar: null, header: null }).toEqual({ ...await chrome(), sidebar: null, header: null });+ await evaluate(`document.querySelector('[data-sidebar-phone-bar] button')?.click(); true`);+ await evaluate(`[...document.querySelectorAll('[role="menuitem"], button')].find((item) => item.textContent.trim() === "Published apps")?.click(); true`);+ await until(() => evaluate(`Boolean(document.querySelector('[data-published-apps]:not([data-published-apps="loading"])'))`), "the page at phone width again");+ await press(`${card(bakery.siteId)} button[aria-label="Preview Bakery order page"]`);+ await until(() => evaluate(`Boolean(document.querySelector('aside[data-app-preview] iframe'))`), "the preview at phone width");+ await until(() => evaluate(`(() => { const box = document.querySelector('aside[data-app-preview]').getBoundingClientRect(); return Math.round(box.left) === 0 && Math.round(box.width) === 390; })()`), "the preview to cover the phone's screen");+ await shot("preview-phone");+ await press('aside[data-app-preview] button[aria-label="Close preview"]');+ await viewport(1280, 860);++ // Delete: refused with a plain line while no token is saved, then done with the Vault's token.+ await openPage();+ const confirmDelete = async (id: string, title: string) => {+ await press(`${card(id)} button[aria-label="Delete ${title}"]`);+ await until(() => evaluate(`Boolean(document.querySelector('[role="alertdialog"]'))`), "the delete confirmation");+ };+ await confirmDelete(rota.siteId, "Staff rota");+ expect(await evaluate(`document.querySelector('[role="alertdialog"]').textContent`)).toContain("Delete “Staff rota”?Its link will stop working for everyone. This can't be undone.");+ await shot("delete-confirm-desktop");+ await evaluate(`[...document.querySelectorAll('[role="alertdialog"] button')].find((button) => button.textContent === "Delete").click(); true`);+ await until(() => evaluate(`document.querySelector('${card(rota.siteId)} [role="alert"]')?.textContent`), "why it could not be deleted");+ expect(await evaluate(`document.querySelector('${card(rota.siteId)} [role="alert"]').textContent`)).toContain("there is no saved Netlify token to use. Delete it on Netlify instead. Manage on Netlify");+ expect(fake.sites.has(rota.siteId)).toBe(true);+ expect(fake.requests.filter((request) => request.startsWith("DELETE"))).toEqual([]);+ await shot("delete-no-token-desktop");++ await api("POST", "/api/vault/secrets", { name: NETLIFY_TOKEN_LABEL, value: TOKEN, bots: "all" });+ await confirmDelete(rota.siteId, "Staff rota");+ await evaluate(`[...document.querySelectorAll('[role="alertdialog"] button')].find((button) => button.textContent === "Delete").click(); true`);+ await until(async () => (await cards()).length === 1, "the deleted card to go");+ expect(await cards()).toEqual(["Bakery order page"]);+ expect(fake.sites.has(rota.siteId)).toBe(false);+ expect(fake.requests.filter((request) => request.startsWith("DELETE"))).toEqual([`DELETE /api/v1/sites/${rota.siteId}`]);+ expect(fake.refused).toEqual([]);+ expect(existsSync(join(rota.project, SITE_FILE))).toBe(false);+ expect(existsSync(join(bakery.project, SITE_FILE))).toBe(true);+ expect(((await api("GET", "/api/published-apps")).apps as unknown[]).length).toBe(1);++ // The token went to the stand-in and nowhere else: not into an answer, the page or the server's log.+ const answer = await fetch(`${info.url}/api/published-apps/delete`, { method: "POST", headers: { "content-type": "application/json", origin: info.url }, body: JSON.stringify({ id: `netlify-${info.botId}-${rota.siteId}` }) });+ expect({ status: answer.status, body: await answer.json() }).toEqual({ status: 404, body: { error: "No such published app.", code: "gone" } });+ expect(await evaluate("document.documentElement.outerHTML.includes(" + JSON.stringify(TOKEN) + ")")).toBe(false);+ expect(readFileSync(info.logPath, "utf8")).not.toContain(TOKEN);+ const logs = await ui("console");+ expect(JSON.stringify(logs)).not.toContain(TOKEN);+ expect((logs.messages as Array<{ type: string; text: string }>).filter((message) => message.type === "error" && !message.text.includes("401"))).toEqual([]);+ } finally {+ await waitForExit(child, { signal: "SIGINT", graceMs: 30_000 });+ await fake.stop();+ expect(existsSync(info.dataDir)).toBe(false);+ await removeTempDir(scratch);+ }+}, LAUNCH_TIMEOUT_MS + 300_000);diff --git a/server/cloud-team-published-apps.e2e.test.ts b/server/cloud-team-published-apps.e2e.test.tsnew file mode 100644index 0000000000..995eec4c08--- /dev/null+++ b/server/cloud-team-published-apps.e2e.test.ts@@ -0,0 +1,185 @@+// Published apps on a real Team Cloud (OMB_CLOUD_ROLE=team) with the synthetic Claude CLI, tried as the people the+// rule must hold against: two members, an Admin and the Owner. A shared bot's Netlify site is listed for whoever can+// read the conversation it was published in (the conversation's own folder holds its record, or the bot's own message+// carries its link), a member's own MausBot's site for that member alone, and nobody's private project for anyone+// else, by list or by id. Delete uses the team's saved Netlify token against a loopback stand-in for Netlify.+import { randomBytes } from "node:crypto";+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import type { PublishedApp } from "../shared/published-apps.ts";+import { SITE_FILE } from "./host/netlify-sites.ts";+import { removeTempDir } from "./testing/cleanup.ts";+import { startFakeNetlify, type FakeNetlify } from "./testing/fake-netlify.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const OWNER = { email: "[email protected]", role: "owner" as const };+const ADMIN = { email: "[email protected]", role: "admin" as const };+const ADA = { email: "[email protected]", role: "member" as const };+const BEN = { email: "[email protected]", role: "member" as const };+const GONE = { status: 404, body: { error: "No such published app.", code: "gone" } };+const TOKEN = "nfp_team_shared_token_0123456789abcdef0123";++type Bot = { id: string; name: string; threadId: string; mainThreadId?: string; defaultBot?: { person?: string }; tasks?: Array<{ threadId: string }> };++let fx: CloudSendFixture, team: CloudTeamFixture;+let scratch = "", replyFile = "";+let owner = "", admin = "", ada = "", ben = "";+let mira: Bot, adaMaus: Bot;+let adaThread = "", benThread = "", mainThread = "";+let fake: FakeNetlify, shopId = "", teamSiteId = "";++const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms));+async function until(done: () => Promise<boolean> | boolean, timeoutMs = 60_000): Promise<void> {+ const end = Date.now() + timeoutMs;+ while (!(await done())) {+ if (Date.now() > end) throw new Error("timed out waiting");+ await sleep(150);+ }+}+const botsOf = async (token: string) => (await team.as(token, "GET", "/api/bots")).body.bots as Bot[];+/** One turn in a conversation, answered by the bot with `reply`. */+async function turn(token: string, bot: Bot, threadId: string, reply: string): Promise<void> {+ const ended = async () => ((await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=50`)).body.messages as Array<{ turnTerminal?: boolean }>).filter((message) => message.turnTerminal).length;+ const before = await ended();+ writeFileSync(replyFile, reply);+ expect((await team.as(token, "POST", `/api/bots/${bot.id}/messages`, { text: "publish it", threadId })).status).toBe(202);+ await until(async () => (await ended()) > before);+}+const site = (name: string, siteId = `id-${name}`) => ({ version: 1, siteId, name, url: `https://${name}.netlify.app`, adminUrl: `https://app.netlify.com/projects/${name}`, title: `${name} site`,+ createdAt: "2026-11-10T10:00:00.000Z", publishedAt: "2026-11-10T10:05:00.000Z", access: "public" });+function record(folder: string, name: string, siteId?: string): string {+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, SITE_FILE), JSON.stringify(site(name, siteId)));+ return join(folder, SITE_FILE);+}+const listOf = async (token: string) => {+ const answer = await team.as(token, "GET", "/api/published-apps");+ expect(answer.status, JSON.stringify(answer.body)).toBe(200);+ return answer.body.apps as PublishedApp[];+};+const titles = async (token: string) => (await listOf(token)).map((app) => app.title).sort();++beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), "published-apps-team-"));+ replyFile = join(scratch, "reply.txt");+ writeFileSync(replyFile, "Hello.");+ fake = await startFakeNetlify(TOKEN);+ const onNetlify = async () => ((await (await fetch(`${fake.url}/sites`, { method: "POST", headers: { authorization: `Bearer ${TOKEN}` }, body: "{}" })).json()) as { id: string }).id;+ shopId = await onNetlify();+ teamSiteId = await onNetlify();+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`,+ team: { id: "team-acme-apps", name: "Acme", env: { OMB_NETLIFY_API_URL: fake.url }, engine: `process.env.FAKE_CLAUDE_REPLY_FILE = ${JSON.stringify(replyFile)};` } });+ team = fx.team!;+ owner = (await team.pair(OWNER)).token!;+ admin = (await team.pair(ADMIN)).token!;+ ada = (await team.pair(ADA)).token!;+ ben = (await team.pair(BEN)).token!;+ mira = (await team.as(owner, "POST", "/api/bots", { name: "Mira" })).body.bot;+ adaMaus = (await botsOf(ada)).find((bot) => bot.defaultBot?.person === ADA.email)!;+ expect(adaMaus, "Ada has a MausBot of her own").toBeTruthy();+ mainThread = mira.mainThreadId ?? mira.threadId;+ adaThread = (await team.as(ada, "POST", `/api/bots/${mira.id}/tasks`, { title: "Ada's shop" })).body.task.threadId;+ benThread = (await team.as(ben, "POST", `/api/bots/${mira.id}/tasks`, { title: "Ben's plan" })).body.task.threadId;++ // Each conversation's turn says its own link, as the publish guide has the bot do.+ await turn(ada, mira, adaThread, "Published: https://adas-notes.netlify.app The link is public.");+ await turn(ben, mira, benThread, "Published: https://bens-plan.netlify.app The link is public.");+ await turn(owner, mira, mainThread, "The team site is live: https://team-site.netlify.app");+ await turn(ada, adaMaus, adaMaus.threadId, "Your diary is at https://adas-diary.netlify.app");++ const data = join(team.home, ".openmausbot");+ // Ada's shop was published from her conversation's own folder; the bot never wrote its link anywhere.+ expect(existsSync(join(data, "task-workspaces", mira.id, adaThread)), "a conversation's turns work in its own folder").toBe(true);+ record(join(data, "task-workspaces", mira.id, adaThread, "shop"), "adas-shop", shopId);+ // The rest sit in folders every conversation of the bot shares: the bot's message says whose they are.+ record(join(data, "workspaces", mira.id, "notes"), "adas-notes");+ record(join(data, "workspaces", mira.id, "plan"), "bens-plan");+ record(join(data, "workspaces", mira.id, "team-site"), "team-site", teamSiteId);+ record(join(data, "workspaces", mira.id, "unsaid"), "never-mentioned");+ record(join(data, "workspaces", adaMaus.id, "diary"), "adas-diary");+ await sleep(2_100);+}, hostTimeout(300_000));++afterAll(async () => {+ await fx?.close();+ await fake?.stop();+ if (scratch) await removeTempDir(scratch);+});++it("shows each member their own projects and the team's, and none of another member's", async () => {+ expect(await titles(ada)).toEqual(["adas-diary site", "adas-notes site", "adas-shop site", "team-site site"]);+ expect(await titles(ben)).toEqual(["bens-plan site", "team-site site"]);+ const toldBen = JSON.stringify(await listOf(ben));+ for (const secret of ["adas-", adaThread, adaMaus.id, adaMaus.threadId]) expect(toldBen, secret).not.toContain(secret);+ const toldAda = JSON.stringify(await listOf(ada));+ for (const secret of ["bens-plan", benThread]) expect(toldAda, secret).not.toContain(secret);+ expect((await listOf(ada)).find((app) => app.title === "adas-shop site")).toMatchObject({ source: "netlify", bot: { id: mira.id, name: "Mira" }, threadId: adaThread, canDelete: true });+});++it("shows an Admin and the Owner what the shared bot published in the shared chat, and nobody's private project", async () => {+ for (const [who, token] of [["an Admin", admin], ["the Owner", owner]] as const) {+ const seen = await listOf(token);+ expect(seen.map((app) => app.title), who).toEqual(["team-site site"]);+ expect(seen[0], who).toMatchObject({ threadId: mainThread, canDelete: true });+ expect(JSON.stringify(seen), who).not.toMatch(/adas-|bens-|never-mentioned/);+ }+});++it("lists nothing the bot never said in a conversation, for anyone", async () => {+ for (const token of [owner, admin, ada, ben]) expect(await titles(token)).not.toContain("never-mentioned site");+});++it("answers another member, an Admin and the Owner guessing at a private project as if it did not exist", async () => {+ for (const [who, token] of [["Ben", ben], ["an Admin", admin], ["the Owner", owner]] as const) {+ for (const id of [`netlify-${mira.id}-${shopId}`, `netlify-${mira.id}-id-adas-notes`, `netlify-${adaMaus.id}-id-adas-diary`]) {+ expect(await team.as(token, "POST", "/api/published-apps/delete", { id }), `${who}: ${id}`).toEqual(GONE);+ }+ }+ const data = join(team.home, ".openmausbot");+ expect(existsSync(join(data, "task-workspaces", mira.id, adaThread, "shop", SITE_FILE))).toBe(true);+ expect(existsSync(join(data, "workspaces", adaMaus.id, "diary", SITE_FILE))).toBe(true);+ expect(await titles(ada)).toEqual(["adas-diary site", "adas-notes site", "adas-shop site", "team-site site"]);+});++it("refuses a member who only chats with the shared bot for what it published in the shared chat", async () => {+ expect((await listOf(ben)).find((app) => app.title === "team-site site")?.canDelete).toBe(false);+ expect(await team.as(ben, "POST", "/api/published-apps/delete", { id: `netlify-${mira.id}-${teamSiteId}` }))+ .toEqual({ status: 403, body: { error: "This app isn't yours to delete.", code: "forbidden" } });+});++it("checks framing only for an address the asker is shown or a public hosting address, and refuses anything else", async () => {+ const framing = (token: string, url: string) => team.as(token, "GET", `/api/published-apps/framing?url=${encodeURIComponent(url)}&origin=${encodeURIComponent("https://acme.mausbot.cloud")}`);+ for (const url of ["http://169.254.169.254/latest/meta-data", "http://127.0.0.1:8799/api/bots", "https://example.com/", `${team.base}/api/bots`]) {+ expect((await framing(ben, url)).status, url).toBe(404);+ }+ expect(await team.as(ben, "GET", "/api/web-panels/framing?url=https%3A%2F%2Fexample.com&origin=https%3A%2F%2Facme.mausbot.cloud")).toMatchObject({ status: 403 });+});++it("deletes with the team's saved token for whoever may delete, says so plainly without one, and never for someone else's project", async () => {+ const data = join(team.home, ".openmausbot");+ const shop = join(data, "task-workspaces", mira.id, adaThread, "shop", SITE_FILE), teamSite = join(data, "workspaces", mira.id, "team-site", SITE_FILE);+ const withoutToken = await team.as(ada, "POST", "/api/published-apps/delete", { id: `netlify-${mira.id}-${shopId}` });+ expect(withoutToken).toEqual({ status: 409, body: { error: expect.stringContaining("can't be deleted from here"), code: "no_token", manageUrl: "https://app.netlify.com/projects/adas-shop" } });++ const saved = await team.as(owner, "POST", "/api/vault/secrets", { name: "Netlify personal access token", value: TOKEN, bots: "all" });+ expect(saved.status, JSON.stringify(saved.body)).toBe(201);+ expect(await team.as(ben, "POST", "/api/published-apps/delete", { id: `netlify-${mira.id}-${shopId}` })).toEqual(GONE);+ expect(await team.as(ben, "POST", "/api/published-apps/delete", { id: `netlify-${mira.id}-${teamSiteId}` })).toMatchObject({ status: 403, body: { code: "forbidden" } });+ expect(fake.requests.filter((request) => request.startsWith("DELETE"))).toEqual([]);++ const byAdmin = await team.as(admin, "POST", "/api/published-apps/delete", { id: `netlify-${mira.id}-${teamSiteId}` });+ expect(byAdmin).toEqual({ status: 200, body: { ok: true } });+ const byAda = await team.as(ada, "POST", "/api/published-apps/delete", { id: `netlify-${mira.id}-${shopId}` });+ expect(byAda).toEqual({ status: 200, body: { ok: true } });+ expect(fake.requests.filter((request) => request.startsWith("DELETE"))).toEqual([`DELETE /api/v1/sites/${teamSiteId}`, `DELETE /api/v1/sites/${shopId}`]);+ expect([fake.sites.has(teamSiteId), fake.sites.has(shopId), existsSync(teamSite), existsSync(shop)]).toEqual([false, false, false, false]);+ expect(fake.refused).toEqual([]);+ await sleep(2_100);+ expect(await titles(ada)).toEqual(["adas-diary site", "adas-notes site"]);+ expect(await titles(owner)).toEqual([]);+ expect(JSON.stringify([withoutToken, byAdmin, byAda])).not.toContain(TOKEN);+});diff --git a/server/host/netlify-sites.test.ts b/server/host/netlify-sites.test.tsnew file mode 100644index 0000000000..c739105418--- /dev/null+++ b/server/host/netlify-sites.test.ts@@ -0,0 +1,226 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync, existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++// @ts-expect-error the skill's helper is plain JavaScript with no types+import { apiBase, publish } from "../../skills/publish-to-netlify/deploy.mjs";+import { startFakeNetlify } from "../testing/fake-netlify.ts";+import { TEAM_READER, VaultStore } from "../vault-store.ts";+import { deleteNetlifySite, findNetlifySites, forgetSiteRecord, netlifyApiBase, parseSiteRecord, savedNetlifyToken, SCAN_LIMITS, SITE_FILE } from "./netlify-sites.ts";++const dirs: string[] = [];+const scratch = () => { const dir = mkdtempSync(join(tmpdir(), "published-apps-sites-")); dirs.push(dir); return dir; };+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++const RECORD = {+ version: 1, siteId: "3f2a6c1e-8a55-4b0c-9a50-1c2f6c1d9e11", name: "bright-bakery-4f2a1c", url: "https://bright-bakery-4f2a1c.netlify.app",+ adminUrl: "https://app.netlify.com/projects/bright-bakery-4f2a1c", title: "Bakery order page", botId: "bot_1a2b3c", botName: "Mira",+ createdAt: "2026-11-11T20:41:07.512Z", publishedAt: "2026-11-11T20:44:30.108Z", deployId: "6913a0c2e4b0a1000812f3aa", deployState: "ready", access: "public",+};+const put = (folder: string, record: unknown) => {+ mkdirSync(folder, { recursive: true });+ const file = join(folder, SITE_FILE);+ writeFileSync(file, typeof record === "string" ? record : JSON.stringify(record));+ return file;+};+const find = (roots: string[], home = "/nowhere/home") => findNetlifySites(roots, { home, env: {} });++describe("reading a site record", () => {+ it("takes the documented record as it is written", () => {+ expect(parseSiteRecord(JSON.stringify(RECORD), "/w/site/.netlify-site.json", 5, {})).toEqual({+ siteId: RECORD.siteId, file: "/w/site/.netlify-site.json", title: "Bakery order page", url: "https://bright-bakery-4f2a1c.netlify.app/",+ manageUrl: RECORD.adminUrl, publishedAt: Date.parse(RECORD.publishedAt), access: "public",+ });+ });++ it("reads a record from before version 1, and a private site as the Netlify team's", () => {+ const old = parseSiteRecord(JSON.stringify({ siteId: "abc", name: "old-site", url: "https://old-site.netlify.app", adminUrl: RECORD.adminUrl }), "f", 1234, {});+ expect(old).toMatchObject({ title: "old-site", publishedAt: 1234, access: "unknown" });+ expect(parseSiteRecord(JSON.stringify({ ...RECORD, access: "private", publishedAt: undefined }), "f", 1, {})).toMatchObject({ access: "netlify-team", publishedAt: Date.parse(RECORD.createdAt) });+ });++ it("refuses what is not a record, and an address a browser should not be sent to", () => {+ for (const bad of ["", "not json", "[]", "null", JSON.stringify({ url: RECORD.url }), JSON.stringify({ ...RECORD, siteId: "../../etc" }), JSON.stringify({ ...RECORD, siteId: 7 }),+ JSON.stringify({ ...RECORD, url: "javascript:alert(1)" }), JSON.stringify({ ...RECORD, url: "http://bright-bakery.netlify.app" }), JSON.stringify({ ...RECORD, url: "http://127.0.0.1:8080/" }),+ JSON.stringify({ ...RECORD, url: "https://user:[email protected]" }), JSON.stringify({ ...RECORD, url: "file:///etc/passwd" }), JSON.stringify({ ...RECORD, url: `https://a.test/${"x".repeat(3000)}` })]) {+ expect(parseSiteRecord(bad, "f", 1, {}), bad.slice(0, 60)).toBeNull();+ }+ });++ it("offers Manage on Netlify only for Netlify's own account pages", () => {+ for (const adminUrl of ["https://app.netlify.com.evil.test/projects/x", "https://evil.test/login", "http://app.netlify.com/projects/x", "javascript:alert(1)", 42]) {+ expect(parseSiteRecord(JSON.stringify({ ...RECORD, adminUrl }), "f", 1, {}), String(adminUrl)).not.toHaveProperty("manageUrl");+ }+ });++ it("keeps a title to one plain line, and ignores a field of the wrong kind", () => {+ expect(parseSiteRecord(JSON.stringify({ ...RECORD, title: "Bakery\n\u0007 order" }), "f", 1, {})?.title).toBe("Bakery order");+ expect(parseSiteRecord(JSON.stringify({ ...RECORD, title: { a: 1 }, publishedAt: "soon", createdAt: 5, access: ["public"] }), "f", 99, {}))+ .toMatchObject({ title: RECORD.name, publishedAt: 99, access: "unknown" });+ });++ it("accepts a loopback address only for the stand-in that replaces Netlify", () => {+ const env = { OMB_NETLIFY_API_URL: "http://127.0.0.1:4010/api/v1" };+ const record = JSON.stringify({ ...RECORD, url: "http://127.0.0.1:4010/live/abc/", adminUrl: "http://127.0.0.1:4010/admin/abc" });+ expect(parseSiteRecord(record, "f", 1, env)).toMatchObject({ url: "http://127.0.0.1:4010/live/abc/", manageUrl: "http://127.0.0.1:4010/admin/abc" });+ expect(parseSiteRecord(record, "f", 1, { OMB_NETLIFY_API_URL: "http://127.0.0.1:4011/api/v1" })).toBeNull();+ expect(parseSiteRecord(record, "f", 1, { OMB_NETLIFY_API_URL: "http://evil.test/api/v1" })).toBeNull();+ });+});++describe("finding site records in a bot's folders", () => {+ it("finds records at any depth up to the limit, one per site", async () => {+ const root = scratch();+ put(root, { ...RECORD, siteId: "top" });+ put(join(root, "projects", "bakery"), { ...RECORD, siteId: "nested" });+ put(join(root, "copy"), { ...RECORD, siteId: "nested" });+ put(join(root, "a", "b", "c", "d"), { ...RECORD, siteId: "deepest-allowed" });+ put(join(root, "a", "b", "c", "d", "e"), { ...RECORD, siteId: "too-deep" });+ expect((await find([root, root])).map((site) => site.siteId).sort()).toEqual(["deepest-allowed", "nested", "top"]);+ });++ it("skips hidden folders, installed packages, links, and records that are malformed or too big", async () => {+ const root = scratch(), elsewhere = scratch();+ put(join(root, ".git"), { ...RECORD, siteId: "hidden" });+ put(join(root, "node_modules", "pkg"), { ...RECORD, siteId: "package" });+ put(join(root, "broken"), "{ not json");+ put(join(root, "huge"), JSON.stringify({ ...RECORD, siteId: "huge", padding: "x".repeat(SCAN_LIMITS.recordBytes) }));+ const other = put(join(elsewhere, "theirs"), { ...RECORD, siteId: "someone-elses" });+ mkdirSync(join(root, "linked-file"));+ symlinkSync(other, join(root, "linked-file", SITE_FILE));+ symlinkSync(join(elsewhere, "theirs"), join(root, "linked-folder"));+ put(join(root, "good"), { ...RECORD, siteId: "good" });+ expect((await find([root])).map((site) => site.siteId)).toEqual(["good"]);+ });++ it("stops at its limits however many folders and records there are", async () => {+ const many = scratch(), wide = scratch();+ for (let at = 0; at < SCAN_LIMITS.sites + 20; at += 1) put(join(many, `site-${at}`), { ...RECORD, siteId: `site-${at}` });+ expect(await find([many])).toHaveLength(SCAN_LIMITS.sites);+ for (let at = 0; at < SCAN_LIMITS.folders + 50; at += 1) mkdirSync(join(wide, `folder-${String(at).padStart(4, "0")}`));+ put(join(wide, "zzz-last", "deep"), { ...RECORD, siteId: "past-the-limit" });+ expect(await find([wide])).toEqual([]);+ });++ it("never searches the person's home folder or anything above it, and survives a folder that is gone", async () => {+ const home = scratch();+ put(join(home, "Documents"), { ...RECORD, siteId: "in-home" });+ put(join(home, "data", "workspaces", "mira"), { ...RECORD, siteId: "in-workspace" });+ expect(await find([home, join(home, ".."), "/"], home)).toEqual([]);+ expect((await find([join(home, "data", "workspaces", "mira"), join(home, "missing")], home)).map((site) => site.siteId)).toEqual(["in-workspace"]);+ });+});++describe("deleting a site on Netlify", () => {+ const TOKEN = "nfp_published_apps_test_token_0123456789";++ it("uses the token the publish guide's card saved for that bot", () => {+ const vault = new VaultStore({ dataDir: scratch() });+ expect(savedNetlifyToken(vault, "mira", TEAM_READER, null)).toBeNull();+ vault.saveSecret({ name: "Netlify personal access token", value: TOKEN, source: "card", bots: ["mira"] });+ vault.saveSecret({ name: "Some other key", value: "other-value", source: "card", bots: "all" });+ expect(savedNetlifyToken(vault, "mira", TEAM_READER, null)).toBe(TOKEN);+ expect(savedNetlifyToken(vault, "another-bot", TEAM_READER, null)).toBeNull();+ expect(savedNetlifyToken(vault, "mira", null, null)).toBeNull();+ expect(readFileSync(new URL("../../skills/publish-to-netlify/SKILL.md", import.meta.url), "utf8")).toContain("label `Netlify personal access token`");+ });++ it("uses a member's own token only on that member's own click, and the team's shared one for a shared conversation", () => {+ const ADA = "p_adaadaadaadaadaadaada1", BEN = "p_benbenbenbenbenbenben1", ADAS = "nfp_adas_own_token_000000000000000000000";+ const vault = new VaultStore({ dataDir: scratch() });+ vault.saveSecret({ name: "Netlify personal access token", value: ADAS, source: "card", bots: ["mira"], person: ADA });+ const adasChat = { person: ADA, team: true }, bensChat = { person: BEN, team: true };+ expect(savedNetlifyToken(vault, "mira", adasChat, ADA)).toBe(ADAS);+ for (const [conversation, person] of [[adasChat, BEN], [adasChat, null], [bensChat, BEN], [TEAM_READER, ADA], [TEAM_READER, null], [bensChat, ADA]] as const) {+ expect(savedNetlifyToken(vault, "mira", conversation, person), JSON.stringify([conversation, person])).toBeNull();+ }+ vault.saveSecret({ name: "Netlify personal access token", value: TOKEN, source: "settings", bots: "all" });+ expect(savedNetlifyToken(vault, "mira", adasChat, ADA)).toBe(ADAS);+ for (const [conversation, person] of [[adasChat, BEN], [bensChat, BEN], [TEAM_READER, ADA], [TEAM_READER, null]] as const) {+ expect(savedNetlifyToken(vault, "mira", conversation, person), JSON.stringify([conversation, person])).toBe(TOKEN);+ }+ });++ it("uses the same API address guard as the publish helper", () => {+ for (const override of [undefined, "", "http://127.0.0.1:4010/api/v1", "http://127.0.0.1:4010/api/v1/", "http://127.0.0.1:4010", "https://127.0.0.1:4010/api/v1", "http://localhost:4010/api/v1",+ "http://127.0.0.1.evil.test/api/v1", "http://evil.test/api/v1", "http://127.0.0.1:4010/api/[email protected]", "http://127.0.0.1:[email protected]/"]) {+ const env = override === undefined ? {} : { OMB_NETLIFY_API_URL: override };+ expect(netlifyApiBase(env), String(override)).toBe(apiBase(env));+ }+ expect(netlifyApiBase({ OMB_NETLIFY_API_URL: "http://evil.test/api/v1" })).toBe("https://api.netlify.com/api/v1");+ });++ it("sends one DELETE for that site to Netlify with the token, and nothing else", async () => {+ const calls: Array<{ url: string; init: RequestInit }> = [];+ const fetch = vi.fn(async (url: string | URL | Request, init?: RequestInit) => { calls.push({ url: String(url), init: init! }); return new Response(null, { status: 204 }); });+ expect(await deleteNetlifySite("site-1", TOKEN, { env: {}, fetch: fetch as typeof globalThis.fetch })).toEqual({ ok: true });+ expect(calls).toHaveLength(1);+ expect(calls[0]!.url).toBe("https://api.netlify.com/api/v1/sites/site-1");+ expect(calls[0]!.init).toMatchObject({ method: "DELETE", headers: { authorization: `Bearer ${TOKEN}` }, redirect: "error" });+ });++ it("treats a site Netlify no longer has as deleted, and says why any other answer failed without the token", async () => {+ const answer = (status: number) => deleteNetlifySite("site-1", TOKEN, { env: {}, fetch: (async () => new Response(`denied ${TOKEN}`, { status })) as typeof fetch });+ expect(await answer(404)).toEqual({ ok: true });+ expect(await answer(401)).toEqual({ ok: false, reason: "token_refused", status: 401 });+ expect(await answer(403)).toEqual({ ok: false, reason: "token_refused", status: 403 });+ expect(await answer(500)).toEqual({ ok: false, reason: "failed", status: 500 });+ const thrown = await deleteNetlifySite("site-1", TOKEN, { env: {}, fetch: (async () => { throw new Error(`connect failed for Bearer ${TOKEN}`); }) as typeof fetch });+ expect(thrown).toEqual({ ok: false, reason: "failed", status: 0 });+ expect(JSON.stringify([await answer(401), await answer(500), thrown])).not.toContain(TOKEN);+ });++ it("deletes on the loopback stand-in, which refuses any other token", async () => {+ const fake = await startFakeNetlify(TOKEN);+ try {+ const env = { OMB_NETLIFY_API_URL: fake.url };+ const made = await (await fetch(`${fake.url}/sites`, { method: "POST", headers: { authorization: `Bearer ${TOKEN}` }, body: "{}" })).json() as { id: string };+ expect(await deleteNetlifySite(made.id, "wrong-token", { env })).toEqual({ ok: false, reason: "token_refused", status: 401 });+ expect(fake.sites.has(made.id)).toBe(true);+ expect(await deleteNetlifySite(made.id, TOKEN, { env })).toEqual({ ok: true });+ expect(fake.sites.has(made.id)).toBe(false);+ expect(await deleteNetlifySite(made.id, TOKEN, { env })).toEqual({ ok: true });+ } finally { await fake.stop(); }+ });++ it("does what the publish helper's own --delete does: the same call, a missing site counts as gone, the record goes", async () => {+ const fake = await startFakeNetlify(TOKEN);+ try {+ const env = { OMB_NETLIFY_API_URL: fake.url }, root = scratch(), tokenFile = join(scratch(), "token");+ writeFileSync(tokenFile, TOKEN);+ const made = async (name: string) => {+ const project = join(root, name);+ mkdirSync(join(project, "dist"), { recursive: true });+ writeFileSync(join(project, "dist", "index.html"), "<h1>hi</h1>");+ const result = await publish(["--dir", join(project, "dist"), "--project", project, "--token-file", tokenFile], env, { pollMs: 20 });+ return { project, siteId: result.siteId as string };+ };+ const byHelper = await made("helper"), byServer = await made("server");+ await publish(["--delete", "--project", byHelper.project, "--token-file", tokenFile], env, { pollMs: 20 });+ const [site] = await findNetlifySites([byServer.project], { home: "/nowhere/home", env });+ expect(site).toMatchObject({ siteId: byServer.siteId, file: join(byServer.project, SITE_FILE) });+ expect(await deleteNetlifySite(site!.siteId, TOKEN, { env })).toEqual({ ok: true });+ expect(await forgetSiteRecord(site!, [root], env)).toBe(true);+ expect(fake.requests.filter((request) => request.startsWith("DELETE"))).toEqual([`DELETE /api/v1/sites/${byHelper.siteId}`, `DELETE /api/v1/sites/${byServer.siteId}`]);+ expect([existsSync(join(byHelper.project, SITE_FILE)), existsSync(join(byServer.project, SITE_FILE)), fake.sites.size]).toEqual([false, false, 0]);++ const again = await made("again");+ fake.sites.delete(again.siteId);+ expect(await publish(["--delete", "--project", again.project, "--token-file", tokenFile], env, { pollMs: 20 })).toMatchObject({ deleted: true, alreadyGone: true });+ expect(await deleteNetlifySite(again.siteId, TOKEN, { env })).toEqual({ ok: true });+ expect(fake.refused).toEqual([]);+ } finally { await fake.stop(); }+ });++ it("removes the record of the deleted site only, and only inside the bot's folders", async () => {+ const root = scratch(), outside = scratch();+ const file = put(join(root, "site"), RECORD), far = put(join(outside, "site"), RECORD);+ expect(await forgetSiteRecord({ file: far, siteId: RECORD.siteId }, [root], {})).toBe(false);+ expect(await forgetSiteRecord({ file, siteId: "another-site" }, [root], {})).toBe(false);+ expect(existsSync(file) && existsSync(far)).toBe(true);+ expect(await forgetSiteRecord({ file, siteId: RECORD.siteId }, [root], {})).toBe(true);+ expect(existsSync(file)).toBe(false);+ expect(JSON.parse(readFileSync(far, "utf8")).siteId).toBe(RECORD.siteId);+ });+});diff --git a/server/host/netlify-sites.ts b/server/host/netlify-sites.tsnew file mode 100644index 0000000000..ebc6351710--- /dev/null+++ b/server/host/netlify-sites.ts@@ -0,0 +1,156 @@+// Finds the sites a bot published to Netlify from the records its publish helper leaves in the bot's own folders+// (skills/publish-to-netlify/site-record.md), and deletes one on Netlify.+//+// Security: a record is whatever a bot wrote. Whose it is comes from the folder it was found in, never from what it+// says; it is read only as a small regular file (never through a link); and its addresses are shown only when they are+// plain https ones, the account page only on Netlify's own host.+import type { Dirent } from "node:fs";+import { lstat, readdir, readFile, unlink } from "node:fs/promises";+import { dirname, join, resolve, sep } from "node:path";+import { z } from "zod";++import type { VaultReader, VaultStore } from "../vault-store.ts";++export const SITE_FILE = ".netlify-site.json";+export const NETLIFY_TOKEN_LABEL = "Netlify personal access token";+const NETLIFY_API = "https://api.netlify.com/api/v1";+const NETLIFY_ADMIN_HOST = "app.netlify.com";++export const SCAN_LIMITS = { depth: 4, folders: 400, sites: 50, recordBytes: 16_384 } as const;+const SKIPPED_FOLDERS = new Set(["node_modules"]);+const DELETE_TIMEOUT_MS = 20_000;++export interface NetlifySite {+ siteId: string;+ /** The record's file, inside one of the folders that were searched. */+ file: string;+ title: string;+ url: string;+ manageUrl?: string;+ publishedAt: number;+ access: "public" | "netlify-team" | "unknown";+}++const text = (max: number) => z.string().max(max).optional().catch(undefined);+const recordSchema = z.object({+ siteId: z.string().regex(/^[\w-]{1,80}$/),+ url: z.string().max(2_000),+ name: text(200), adminUrl: text(2_000), title: text(200), createdAt: text(40), publishedAt: text(40), access: text(20),+});++/** Must match skills/publish-to-netlify/deploy.mjs `apiBase`: only a loopback stand-in may replace Netlify's address,+ * so a token can never be pointed at another host. */+export function netlifyApiBase(env: NodeJS.ProcessEnv): string {+ const override = env.OMB_NETLIFY_API_URL;+ return override && /^http:\/\/127\.0\.0\.1:\d{1,5}(\/[\w/.-]*)?$/.test(override) ? override.replace(/\/$/, "") : NETLIFY_API;+}++/** The loopback stand-in's origin while one replaces Netlify (tests and fixtures), else null. */+function standInOrigin(env: NodeJS.ProcessEnv): string | null {+ const base = netlifyApiBase(env);+ return base === NETLIFY_API ? null : new URL(base).origin;+}++function webAddress(value: string | undefined, standIn: string | null, host?: string): string | null {+ if (!value) return null;+ let url: URL;+ try { url = new URL(value); } catch { return null; }+ if (url.username || url.password) return null;+ if (standIn && url.origin === standIn) return url.href;+ return url.protocol === "https:" && (!host || url.hostname === host) ? url.href : null;+}++const oneLine = (value: string | undefined) => value?.replace(/[\p{Cc}\s]+/gu, " ").trim() ?? "";+const time = (value: string | undefined) => { const at = value ? Date.parse(value) : NaN; return Number.isFinite(at) ? at : null; };++export function parseSiteRecord(raw: string, file: string, modifiedAt: number, env: NodeJS.ProcessEnv): NetlifySite | null {+ let value: unknown;+ try { value = JSON.parse(raw); } catch { return null; }+ const parsed = recordSchema.safeParse(value);+ if (!parsed.success) return null;+ const record = parsed.data, standIn = standInOrigin(env);+ const url = webAddress(record.url, standIn);+ if (!url) return null;+ const manageUrl = webAddress(record.adminUrl, standIn, NETLIFY_ADMIN_HOST);+ return {+ siteId: record.siteId, file, url, ...(manageUrl ? { manageUrl } : {}),+ title: oneLine(record.title) || oneLine(record.name) || new URL(url).host,+ publishedAt: time(record.publishedAt) ?? time(record.createdAt) ?? modifiedAt,+ access: record.access === "public" ? "public" : record.access === "private" ? "netlify-team" : "unknown",+ };+}++export const within = (folder: string, root: string) => folder === root || folder.startsWith(root + sep);++/** The site records under these folders: at most `SCAN_LIMITS` deep and wide, no hidden folders, nothing through a+ * link. A folder that holds the person's whole home (or more) is not searched: listing it would read far outside+ * anything a bot was given. */+export async function findNetlifySites(roots: readonly string[], options: { home: string; env: NodeJS.ProcessEnv }): Promise<NetlifySite[]> {+ const home = resolve(options.home);+ const sites: NetlifySite[] = [], seen = new Set<string>();+ let folders = 0;+ const queue = [...new Set(roots.map((root) => resolve(root)))].filter((root) => !within(home, root)).map((folder) => ({ folder, depth: 0 }));+ for (let next = queue.shift(); next && folders < SCAN_LIMITS.folders && sites.length < SCAN_LIMITS.sites; next = queue.shift()) {+ if (seen.has(next.folder)) continue;+ seen.add(next.folder);+ folders += 1;+ let entries: Dirent[];+ try { entries = await readdir(next.folder, { withFileTypes: true }); } catch { continue; }+ for (const entry of entries) {+ if (entry.name === SITE_FILE && entry.isFile()) {+ const site = await readSite(join(next.folder, entry.name), options.env);+ if (site && !sites.some((other) => other.siteId === site.siteId)) sites.push(site);+ } else if (entry.isDirectory() && next.depth < SCAN_LIMITS.depth && !entry.name.startsWith(".") && !SKIPPED_FOLDERS.has(entry.name)) {+ queue.push({ folder: join(next.folder, entry.name), depth: next.depth + 1 });+ }+ }+ }+ return sites.slice(0, SCAN_LIMITS.sites);+}++async function readSite(file: string, env: NodeJS.ProcessEnv): Promise<NetlifySite | null> {+ try {+ const info = await lstat(file);+ if (!info.isFile() || info.size > SCAN_LIMITS.recordBytes) return null;+ return parseSiteRecord(await readFile(file, "utf8"), file, info.mtimeMs, env);+ } catch {+ return null;+ }+}++/** Security: the saved Netlify token a person's Delete may use for this bot: what a turn in the app's conversation+ * could use (`conversation`), with a member's own secret only when the person deleting is that member. One person's+ * token never acts on another person's click; the team's shared one is the team's to use. */+export function savedNetlifyToken(vault: Pick<VaultStore, "usableSecret">, botId: string, conversation: VaultReader | null, person: string | null): string | null {+ if (!conversation) return null;+ const reader = conversation.person && conversation.person !== person ? { person: null, team: conversation.team } : conversation;+ return vault.usableSecret(NETLIFY_TOKEN_LABEL, botId, "file", reader)?.value ?? null;+}++export type NetlifyDelete = { ok: true } | { ok: false; reason: "token_refused" | "failed"; status: number };++/** DELETE /sites/<id> on Netlify with the person's token. A site Netlify no longer has counts as deleted. The token goes+ * only to Netlify (or its loopback stand-in) and never into the answer. */+export async function deleteNetlifySite(siteId: string, token: string, options: { env: NodeJS.ProcessEnv; fetch?: typeof fetch }): Promise<NetlifyDelete> {+ let status = 0;+ try {+ const response = await (options.fetch ?? fetch)(`${netlifyApiBase(options.env)}/sites/${encodeURIComponent(siteId)}`, {+ method: "DELETE", headers: { authorization: `Bearer ${token}` }, redirect: "error", signal: AbortSignal.timeout(DELETE_TIMEOUT_MS),+ });+ status = response.status;+ await response.body?.cancel().catch(() => {});+ } catch {+ return { ok: false, reason: "failed", status: 0 };+ }+ if ((status >= 200 && status < 300) || status === 404) return { ok: true };+ return { ok: false, reason: status === 401 || status === 403 ? "token_refused" : "failed", status };+}++/** Removes a deleted site's record, when it still names that site, so the next publish from the project makes a new one. */+export async function forgetSiteRecord(site: Pick<NetlifySite, "file" | "siteId">, roots: readonly string[], env: NodeJS.ProcessEnv): Promise<boolean> {+ const folder = dirname(resolve(site.file));+ if (!roots.some((root) => within(folder, resolve(root)))) return false;+ const current = await readSite(site.file, env);+ if (current?.siteId !== site.siteId) return false;+ try { await unlink(site.file); return true; } catch { return false; }+}diff --git a/server/host/published-apps.test.ts b/server/host/published-apps.test.tsnew file mode 100644index 0000000000..a56048a296--- /dev/null+++ b/server/host/published-apps.test.ts@@ -0,0 +1,311 @@+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { VisibleSet, type Viewer } from "../bot-visibility.ts";+import type { PublishedPageRecord } from "../pages/store.ts";+import type { RequestAuth } from "../request-auth.ts";+import { SITE_FILE } from "./netlify-sites.ts";+import { createPublishedApps, linkPattern, type PublishedAppsDeps } from "./published-apps.ts";++const KEYS: Record<string, string> = { [ADA]: "p_adaadaadaadaadaadaada1", [BEN]: "p_benbenbenbenbenbenben1", [OLIVE]: "p_oliveoliveoliveolive01" };+const TOKEN = "nfp_published_apps_host_token_0123456789";++const bots = [+ { id: "mira", name: "Mira", threadId: "main", tasks: [{ threadId: "main" }, { threadId: "ada-chat" }, { threadId: "ben-chat" }] },+ { id: "adas-maus", name: "Ada's MausBot", threadId: "ada-maus-chat", defaultBot: { person: ADA }, tasks: [{ threadId: "ada-maus-chat" }] },+ { id: "bens-own", name: "Ledger", threadId: "ledger-main", createdBy: BEN, tasks: [{ threadId: "ledger-main" }] },+];+const rooms = [{ id: "launch", threadId: "room-thread", memberIds: ["mira"] }];+const audienceOf = (threadId: string) => threadId.startsWith("ada-") ? `member:${KEYS[ADA]}` as const : threadId.startsWith("ben-") ? `member:${KEYS[BEN]}` as const+ : threadId === "room-thread" ? "room:launch" as const : "team" as const;++const session = (email: string, admin = false) => ({ kind: "session", scopes: admin ? ["admin", "client"] : ["client"], session: { id: `s-${email}`, email } }) as unknown as RequestAuth;+const OWNER = { kind: "loopback", trust: "owner", scopes: ["admin", "client"] } as unknown as RequestAuth;+const emailOf = (auth: RequestAuth) => (auth.kind === "session" ? auth.session.email ?? "" : "");++function visibleFor(auth: RequestAuth, team: boolean): VisibleSet {+ const email = emailOf(auth);+ const viewer: Viewer = auth.kind !== "session" ? { kind: "all" } : auth.scopes.includes("admin") ? { kind: "all", email } : { kind: "member", email };+ return new VisibleSet(bots, rooms, viewer, undefined, team ? { of: audienceOf, person: KEYS[email] ?? null } : undefined);+}++const site = (name: string, extra: Record<string, unknown> = {}) => ({+ version: 1, siteId: `id-${name}`, name, url: `https://${name}.netlify.app`, adminUrl: `https://app.netlify.com/projects/${name}`, title: `${name} site`,+ createdAt: "2026-11-10T10:00:00.000Z", publishedAt: "2026-11-10T10:05:00.000Z", access: "public", ...extra,+});+const page = (pageId: string, botId: string, threadId: string, updatedAt: number): PublishedPageRecord => ({+ pageId, url: `https://${pageId}.mausbot.page/`, title: `Page ${pageId.slice(0, 3)}`, botId, source: `/w/${pageId}`, cards: [{ threadId, messageId: `m-${pageId}` }], createdAt: updatedAt, updatedAt,+});+const PAGE_ADA = "adapage0000000000000000", PAGE_TEAM = "teampage000000000000000", PAGE_BEN = "benpage0000000000000000";++let dataDir = "";+let messages: Record<string, Array<{ role: string; text?: string; from?: { botId?: string } }>>;+let pages: PublishedPageRecord[];+let tokenAsks: Array<{ botId: string; email: string; threadId?: string }>;+const calls: Array<{ url: string; auth: string | undefined; method: string | undefined }> = [];+let netlifyStatus = 204;+const workspace = (botId: string) => join(dataDir, "workspaces", botId);+const ownFolder = (botId: string, threadId: string) => join(dataDir, "task-workspaces", botId, threadId);+const record = (botId: string, folder: string, value: unknown) => {+ const dir = join(workspace(botId), folder);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, SITE_FILE), JSON.stringify(value));+ return join(dir, SITE_FILE);+};++function apps(over: Partial<PublishedAppsDeps> = {}) {+ return createPublishedApps({+ bots: () => bots, rooms: () => rooms, messages: (threadId) => messages[threadId] ?? [],+ folders: (bot) => [workspace(bot.id), ...[bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)].map((threadId) => ownFolder(bot.id, threadId))],+ ownFolder,+ pages: () => pages,+ unpublishPage: async (pageId) => { pages = pages.filter((one) => one.pageId !== pageId); return { status: 200, text: "Unpublished." }; },+ netlifyToken: (botId, auth, threadId) => { tokenAsks.push({ botId, email: emailOf(auth), ...(threadId ? { threadId } : {}) }); return TOKEN; },+ ownChat: (auth, threadId) => audienceOf(threadId) === `member:${KEYS[emailOf(auth)]}`,+ home: "/nowhere/home", env: {}, now: () => Date.now(),+ fetch: (async (url: string | URL | Request, init?: RequestInit) => {+ calls.push({ url: String(url), auth: (init?.headers as Record<string, string> | undefined)?.authorization, method: init?.method });+ return new Response(netlifyStatus === 204 ? null : `{"message":"${TOKEN}"}`, { status: netlifyStatus });+ }) as typeof fetch,+ ...over,+ });+}++beforeEach(() => {+ dataDir = mkdtempSync(join(tmpdir(), "published-apps-host-"));+ record("mira", "adas-shop", site("adas-shop"));+ record("mira", "team-site", site("team-site", { publishedAt: "2026-11-11T09:00:00.000Z", access: "private" }));+ record("mira", "bens-plan", site("bens-plan"));+ record("mira", "room-site", site("room-site"));+ record("adas-maus", "diary", site("adas-diary"));+ messages = {+ "ada-chat": [{ role: "user", text: "publish my shop" }, { role: "bot", text: "Published: https://adas-shop.netlify.app. The link is public." }],+ main: [{ role: "bot", text: "Team site is live at [team-site](https://team-site.netlify.app/)" }],+ "ben-chat": [{ role: "bot", text: "Done: https://bens-plan.netlify.app" }],+ "room-thread": [{ role: "bot", from: { botId: "mira" }, text: "Here: https://room-site.netlify.app/index.html" }],+ "ada-maus-chat": [{ role: "bot", text: "https://adas-diary.netlify.app" }],+ };+ pages = [page(PAGE_ADA, "mira", "ada-chat", 300), page(PAGE_TEAM, "mira", "main", 200), page(PAGE_BEN, "mira", "ben-chat", 100)];+ tokenAsks = [];+ calls.length = 0;+ netlifyStatus = 204;+});+afterEach(() => { rmSync(dataDir, { recursive: true, force: true }); vi.restoreAllMocks(); });++const titles = async (auth: RequestAuth, team = true, made = apps()) => (await made.list(visibleFor(auth, team), auth)).map((app) => app.title).sort();+const TEAM_SHARED = ["Page tea", "room-site site", "team-site site"];++describe("the list on a person's own server", () => {+ it("has every bot's Netlify sites and published pages, newest first, each under the bot whose folder or page it is", async () => {+ const listed = await apps().list(visibleFor(OWNER, false), OWNER);+ expect(listed.map((app) => app.title)).toEqual(["team-site site", "adas-shop site", "bens-plan site", "room-site site", "adas-diary site", "Page ada", "Page tea", "Page ben"]+ .sort((a, b) => listed.find((app) => app.title === b)!.publishedAt - listed.find((app) => app.title === a)!.publishedAt));+ expect(listed[0]).toEqual({+ id: "netlify-mira-id-team-site", source: "netlify", title: "team-site site", url: "https://team-site.netlify.app/", bot: { id: "mira", name: "Mira" },+ publishedAt: Date.parse("2026-11-11T09:00:00.000Z"), access: "netlify-team", manageUrl: "https://app.netlify.com/projects/team-site", canDelete: true,+ });+ expect(listed.find((app) => app.id === `page-${PAGE_ADA}`)).toEqual({+ id: `page-${PAGE_ADA}`, source: "page", title: "Page ada", url: `https://${PAGE_ADA}.mausbot.page/`, bot: { id: "mira", name: "Mira" }, threadId: "ada-chat",+ publishedAt: 300, access: "link", canDelete: true,+ });+ expect(listed.every((app) => app.canDelete)).toBe(true);+ });++ it("lists a page whose bot is gone, without a name", async () => {+ pages = [page("orphanpage0000000000000", "deleted-bot", "gone-thread", 5)];+ expect((await apps().list(visibleFor(OWNER, false), OWNER)).find((app) => app.source === "page")?.bot).toEqual({ id: "deleted-bot", name: "" });+ });++ it("puts a record under the bot whose folder holds it, whatever bot the record claims to be", async () => {+ record("adas-maus", "forged", site("forged", { botId: "mira", botName: "Mira" }));+ const forged = (await apps().list(visibleFor(OWNER, false), OWNER)).find((app) => app.title === "forged site")!;+ expect(forged).toMatchObject({ id: "netlify-adas-maus-id-forged", bot: { id: "adas-maus", name: "Ada's MausBot" } });+ });++ it("reads each bot's folders once for requests that come together", async () => {+ const folders = vi.fn((bot: { id: string }) => [workspace(bot.id)]);+ const made = apps({ folders });+ await Promise.all([made.list(visibleFor(OWNER, false), OWNER), made.list(visibleFor(OWNER, false), OWNER), made.lists(visibleFor(OWNER, false), OWNER, "https://adas-shop.netlify.app/")]);+ expect(folders).toHaveBeenCalledTimes(bots.length);+ });++ it("names the conversation whose own folder holds a site's record, so the card opens it", async () => {+ mkdirSync(join(ownFolder("mira", "ada-chat"), "portfolio"), { recursive: true });+ writeFileSync(join(ownFolder("mira", "ada-chat"), "portfolio", SITE_FILE), JSON.stringify(site("portfolio")));+ const listed = await apps().list(visibleFor(OWNER, false), OWNER);+ expect(listed.find((app) => app.title === "portfolio site")?.threadId).toBe("ada-chat");+ expect(listed.find((app) => app.title === "adas-shop site")).not.toHaveProperty("threadId");+ });+});++describe("the list on a Team Cloud", () => {+ it("shows a member what a shared bot published for them and in shared conversations, and their own bot's", async () => {+ expect(await titles(session(ADA))).toEqual(["Page ada", "adas-diary site", "adas-shop site", ...TEAM_SHARED].sort());+ });++ it("shows another member none of that person's private projects", async () => {+ const seen = await apps().list(visibleFor(session(BEN), true), session(BEN));+ expect(seen.map((app) => app.title).sort()).toEqual(["Page ben", "bens-plan site", ...TEAM_SHARED].sort());+ const told = JSON.stringify(seen);+ for (const secret of ["adas-shop", "adas-diary", PAGE_ADA, "ada-chat", "ada-maus-chat", "adas-maus"]) expect(told, secret).not.toContain(secret);+ });++ it("shows an admin what shared bots published in shared conversations, and no member's private project", async () => {+ const seen = await apps().list(visibleFor(session(OLIVE, true), true), session(OLIVE, true));+ expect(seen.map((app) => app.title).sort()).toEqual(TEAM_SHARED);+ expect(JSON.stringify(seen)).not.toMatch(/adas-|bens-|ada-chat|ben-chat|adapage|benpage/);+ expect(seen.every((app) => app.canDelete)).toBe(true);+ });++ it("names the conversation the viewer can read, so the card opens it", async () => {+ const seen = await apps().list(visibleFor(session(ADA), true), session(ADA));+ expect(Object.fromEntries(seen.map((app) => [app.title, app.threadId]))).toEqual({+ "adas-shop site": "ada-chat", "team-site site": "main", "room-site site": "room-thread", "adas-diary site": "ada-maus-chat", "Page ada": "ada-chat", "Page tea": "main",+ });+ });++ it("lists a site only where the bot itself wrote its link: not a person's line, another bot's, a longer address, or no line at all", async () => {+ record("mira", "quiet", site("quiet"));+ record("mira", "typed", site("typed"));+ record("mira", "lookalike", site("shop"));+ messages.main!.push({ role: "user", text: "is https://typed.netlify.app yours?" }, { role: "bot", from: { botId: "other-bot" }, text: "https://typed.netlify.app" },+ { role: "bot", text: "see https://shop.netlify.app.evil.test and https://shop.netlify.application and https://shop.netlify.app-x.test" });+ messages["room-thread"]!.push({ role: "bot", from: { botId: "other-bot" }, text: "https://quiet.netlify.app" }, { role: "bot", text: "https://quiet.netlify.app" });+ const seen = await titles(session(ADA));+ for (const hidden of ["quiet site", "typed site", "shop site"]) expect(seen, hidden).not.toContain(hidden);+ });++ it("keeps a site whose record is in a conversation's own folder to that conversation, whatever any message says", async () => {+ mkdirSync(join(ownFolder("mira", "ada-chat"), "portfolio"), { recursive: true });+ writeFileSync(join(ownFolder("mira", "ada-chat"), "portfolio", SITE_FILE), JSON.stringify(site("portfolio")));+ messages.main!.push({ role: "bot", text: "Ada's is at https://portfolio.netlify.app" });+ messages["ben-chat"]!.push({ role: "bot", text: "https://portfolio.netlify.app" });+ expect(await titles(session(ADA))).toContain("portfolio site");+ expect(await titles(session(BEN))).not.toContain("portfolio site");+ expect(await titles(session(OLIVE, true))).not.toContain("portfolio site");+ const ben = session(BEN);+ expect((await apps().remove(visibleFor(ben, true), ben, "netlify-mira-id-portfolio")).status).toBe(404);+ });++ it("does not let a record planted in a bot's folder show a member someone else's site", async () => {+ record("bens-own", "planted", site("adas-shop", { botId: "mira" }));+ expect(await titles(session(BEN))).not.toContain("adas-shop site");+ });++ it("answers a hostile member's guesses at another person's project as if it did not exist", async () => {+ const made = apps(), ben = session(BEN), visible = () => visibleFor(ben, true);+ for (const id of ["netlify-mira-id-adas-shop", "netlify-adas-maus-id-adas-diary", `page-${PAGE_ADA}`, "netlify-mira-id-missing"]) {+ expect(await made.remove(visible(), ben, id), id).toEqual({ status: 404, body: { error: "No such published app.", code: "gone" } });+ }+ for (const url of ["https://adas-shop.netlify.app/", "https://adas-diary.netlify.app/", `https://${PAGE_ADA}.mausbot.page/`]) expect(await made.lists(visible(), ben, url), url).toBe(false);+ expect(await made.lists(visible(), ben, "https://bens-plan.netlify.app/pricing")).toBe(true);+ expect(calls).toEqual([]);+ expect(tokenAsks).toEqual([]);+ expect(existsSync(join(workspace("mira"), "adas-shop", SITE_FILE))).toBe(true);+ expect(pages).toHaveLength(3);+ });+});++describe("the address in a message", () => {+ it("matches the site's own address and its pages, never a longer host or name", () => {+ const link = linkPattern("https://bright-bakery.netlify.app/");+ for (const text of ["https://bright-bakery.netlify.app", "at https://bright-bakery.netlify.app.", "[site](https://bright-bakery.netlify.app/menu)", "HTTPS://Bright-Bakery.netlify.app/"]) expect(link.test(text), text).toBe(true);+ for (const text of ["https://bright-bakery.netlify.app.evil.test", "https://bright-bakery.netlify.apps", "https://bright-bakery-2.netlify.app", "http://bright-bakery.netlify.app", "bright-bakery.netlify.app"]) expect(link.test(text), text).toBe(false);+ const standIn = linkPattern("http://127.0.0.1:4010/live/abc/");+ expect(standIn.test("http://127.0.0.1:4010/live/abc/index.html")).toBe(true);+ expect(standIn.test("http://127.0.0.1:4010/live/abcd/")).toBe(false);+ });+});++describe("deleting a published app", () => {+ it("deletes the owner's Netlify site with the saved token and removes its record, so the card is gone", async () => {+ const made = apps(), file = join(workspace("mira"), "adas-shop", SITE_FILE);+ expect(await made.remove(visibleFor(OWNER, false), OWNER, "netlify-mira-id-adas-shop")).toEqual({ status: 200, body: { ok: true } });+ expect(calls).toEqual([{ url: "https://api.netlify.com/api/v1/sites/id-adas-shop", auth: `Bearer ${TOKEN}`, method: "DELETE" }]);+ expect(existsSync(file)).toBe(false);+ expect((await made.list(visibleFor(OWNER, false), OWNER)).map((app) => app.title)).not.toContain("adas-shop site");+ expect(existsSync(join(workspace("mira"), "team-site", SITE_FILE))).toBe(true);+ });++ it("counts a site Netlify no longer has as deleted", async () => {+ netlifyStatus = 404;+ expect((await apps().remove(visibleFor(OWNER, false), OWNER, "netlify-mira-id-adas-shop")).status).toBe(200);+ expect(existsSync(join(workspace("mira"), "adas-shop", SITE_FILE))).toBe(false);+ });++ it("says so and offers Manage on Netlify when no saved token can be used, and deletes nothing", async () => {+ const answer = await apps({ netlifyToken: () => null }).remove(visibleFor(OWNER, false), OWNER, "netlify-mira-id-adas-shop");+ expect(answer).toEqual({ status: 409, body: { error: expect.stringContaining("can't be deleted from here"), code: "no_token", manageUrl: "https://app.netlify.com/projects/adas-shop" } });+ expect(calls).toEqual([]);+ expect(existsSync(join(workspace("mira"), "adas-shop", SITE_FILE))).toBe(true);+ });++ it("keeps the record and offers Manage on Netlify when Netlify refuses the token, and says only that it failed otherwise", async () => {+ netlifyStatus = 401;+ expect(await apps().remove(visibleFor(OWNER, false), OWNER, "netlify-mira-id-adas-shop")).toMatchObject({ status: 409, body: { code: "token_refused", manageUrl: "https://app.netlify.com/projects/adas-shop" } });+ netlifyStatus = 500;+ expect(await apps().remove(visibleFor(OWNER, false), OWNER, "netlify-mira-id-adas-shop")).toEqual({ status: 502, body: { error: "The app could not be deleted. Try again.", code: "failed" } });+ expect(existsSync(join(workspace("mira"), "adas-shop", SITE_FILE))).toBe(true);+ });++ it("never puts the token in an answer or a log line", async () => {+ const logged: unknown[] = [];+ for (const method of ["log", "info", "warn", "error", "debug"] as const) vi.spyOn(console, method).mockImplementation((...args) => { logged.push(...args); });+ const answers = [];+ for (const status of [204, 404, 401, 403, 500]) {+ netlifyStatus = status;+ record("mira", "adas-shop", site("adas-shop"));+ answers.push(await apps().remove(visibleFor(OWNER, false), OWNER, "netlify-mira-id-adas-shop"));+ }+ answers.push(await apps({ fetch: (async () => { throw new Error(`socket closed sending Bearer ${TOKEN}`); }) as typeof fetch }).remove(visibleFor(OWNER, false), OWNER, "netlify-mira-id-team-site"));+ expect(answers.map((answer) => answer.status)).toEqual([200, 200, 409, 409, 502, 502]);+ expect(JSON.stringify(answers) + logged.map(String).join("\n")).not.toContain(TOKEN);+ });++ it("lets a member delete what a bot published in their own private chat, with a token asked for as them", async () => {+ const ada = session(ADA);+ expect((await apps().remove(visibleFor(ada, true), ada, "netlify-mira-id-adas-shop")).status).toBe(200);+ expect(tokenAsks).toEqual([{ botId: "mira", email: ADA, threadId: "ada-chat" }]);+ expect((await apps().remove(visibleFor(ada, true), ada, `page-${PAGE_ADA}`)).status).toBe(200);+ expect(pages.map((one) => one.pageId)).toEqual([PAGE_TEAM, PAGE_BEN]);+ });++ it("refuses a member who only chats with a shared bot for what it published in a shared conversation", async () => {+ const ben = session(BEN), made = apps();+ const shared = (await made.list(visibleFor(ben, true), ben)).filter((app) => TEAM_SHARED.includes(app.title));+ expect(shared.map((app) => app.canDelete)).toEqual([false, false, false]);+ for (const id of ["netlify-mira-id-team-site", `page-${PAGE_TEAM}`]) {+ expect(await made.remove(visibleFor(ben, true), ben, id), id).toEqual({ status: 403, body: { error: "This app isn't yours to delete.", code: "forbidden" } });+ }+ expect(calls).toEqual([]);+ expect(tokenAsks).toEqual([]);+ expect(pages).toHaveLength(3);+ });++ it("lets the person a bot belongs to delete what it published", async () => {+ record("bens-own", "ledger", site("ledger"));+ messages["ledger-main"] = [{ role: "bot", text: "https://ledger.netlify.app" }];+ const ben = session(BEN), ada = session(ADA), made = apps();+ expect((await made.list(visibleFor(ada, true), ada)).find((app) => app.title === "ledger site")?.canDelete).toBe(false);+ expect((await made.remove(visibleFor(ben, true), ben, "netlify-bens-own-id-ledger")).status).toBe(200);+ });++ it("lets an admin delete a shared bot's app from a shared conversation, with a token asked for as the admin", async () => {+ const olive = session(OLIVE, true), made = apps();+ expect((await made.remove(visibleFor(olive, true), olive, "netlify-mira-id-team-site")).status).toBe(200);+ expect(tokenAsks).toEqual([{ botId: "mira", email: OLIVE, threadId: "main" }]);+ expect(calls).toHaveLength(1);+ expect((await made.remove(visibleFor(olive, true), olive, `page-${PAGE_TEAM}`)).status).toBe(200);+ expect((await made.remove(visibleFor(olive, true), olive, "netlify-mira-id-adas-shop")).status).toBe(404);+ expect((await made.remove(visibleFor(olive, true), olive, `page-${PAGE_ADA}`)).status).toBe(404);+ expect(calls).toHaveLength(1);+ });++ it("says a page could not be deleted when the pages service refuses", async () => {+ const answer = await apps({ unpublishPage: async () => ({ status: 502, text: "The pages service did not answer." }) }).remove(visibleFor(OWNER, false), OWNER, `page-${PAGE_TEAM}`);+ expect(answer).toEqual({ status: 502, body: { error: "The app could not be deleted. Try again.", code: "failed" } });+ });+});diff --git a/server/host/published-apps.ts b/server/host/published-apps.tsnew file mode 100644index 0000000000..dd9c8969e9--- /dev/null+++ b/server/host/published-apps.ts@@ -0,0 +1,190 @@+// What the Published apps page lists and deletes: the pages this server published to a MausBot link, and the sites+// bots published to the person's own Netlify account.+//+// Security: everything here answers for one viewer. An app is theirs to see only through a bot they can see and, where+// conversations have audiences of their own (a Team Cloud), a conversation they can read in which that bot published+// it: a page's own cards; for a Netlify site the conversation whose own folder holds its record, or, for a record in+// a folder the bot's conversations share, the bot's message carrying its link. So the list never names an app, or its+// address, from a conversation the viewer cannot read.+import type { PublishedApp, PublishedAppDeleteFailure, PublishedAppDeleteRefusal } from "../../shared/published-apps.ts";+import type { VisibleSet } from "../bot-visibility.ts";+import type { PublishedPageRecord } from "../pages/store.ts";+import type { RequestAuth } from "../request-auth.ts";+import { dirname, resolve } from "node:path";+import { deleteNetlifySite, findNetlifySites, forgetSiteRecord, within, type NetlifySite } from "./netlify-sites.ts";++interface AppBot { id: string; name: string; threadId: string; tasks?: ReadonlyArray<{ threadId: string }> }+interface AppRoom { threadId: string; memberIds: readonly string[]; tasks?: ReadonlyArray<{ threadId: string }> }+interface AppMessage { role: string; text?: string; from?: { botId?: string } }++export interface PublishedAppsDeps {+ bots(): readonly AppBot[];+ rooms(): readonly AppRoom[];+ messages(threadId: string): readonly AppMessage[];+ /** The bot's own folders, the ones its turns work in. */+ folders(bot: AppBot): readonly string[];+ /** The folder that is one conversation's alone: only its own turns work there. */+ ownFolder(botId: string, threadId: string): string;+ pages(): readonly PublishedPageRecord[];+ unpublishPage(pageId: string): Promise<{ status: number; text: string }>;+ /** Security: the Netlify token this person's own action may use for this bot's app from this conversation, or null.+ * Never another person's. */+ netlifyToken(botId: string, auth: RequestAuth, threadId: string | undefined): string | null;+ /** True when the conversation is this person's own private one (a Team Cloud). */+ ownChat(auth: RequestAuth, threadId: string): boolean;+ home: string;+ env: NodeJS.ProcessEnv;+ fetch?: typeof fetch;+ now?: () => number;+}++export const MAX_LISTED = 500;+const MAX_THREADS_SEARCHED = 300;+/** Long enough for the list and the framing checks a page sends together to share one read of the folders. */+const SCAN_FRESH_MS = 2_000;++/** One source of published apps. A second kind of hosting adds an entry here: how its apps are found, and how one is+ * deleted for the person asking. */+interface Entry {+ app: Omit<PublishedApp, "canDelete" | "threadId">;+ /** The conversations the bot published it in; the viewer needs one of them. */+ threads(): readonly string[];+ /** The one conversation it certainly came from, when where it is kept says so. */+ home?: string;+ /** A page has only its conversations; a site in a bot's folder is the bot's where conversations share one audience. */+ needsThread: boolean;+ remove(auth: RequestAuth, threadId: string | undefined): Promise<PublishedAppDeleteRefusal | null>;+}++type Shown = { app: PublishedApp; entry: Entry };+export type DeleteAnswer = { status: 200; body: { ok: true } } | { status: 403 | 404 | 409 | 502; body: PublishedAppDeleteFailure };++const REFUSALS: Record<PublishedAppDeleteRefusal, { status: 403 | 404 | 409 | 502; error: string }> = {+ gone: { status: 404, error: "No such published app." },+ forbidden: { status: 403, error: "This app isn't yours to delete." },+ no_token: { status: 409, error: "No saved Netlify token can be used for this, so the app can't be deleted from here. Delete it on Netlify." },+ token_refused: { status: 409, error: "Netlify refused the saved token, so the app can't be deleted from here. Delete it on Netlify." },+ failed: { status: 502, error: "The app could not be deleted. Try again." },+};++const escaped = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++/** Matches the site's address in a message, and not a longer host or path that only starts with it. */+export function linkPattern(url: string): RegExp {+ const { origin, pathname } = new URL(url);+ return new RegExp(`${escaped(origin + pathname.replace(/\/+$/, ""))}(?![\\w-]|\\.[\\w-])`, "i");+}++export function createPublishedApps(deps: PublishedAppsDeps) {+ const now = deps.now ?? Date.now;+ const scans = new Map<string, { at: number; sites: Promise<NetlifySite[]> }>();++ function sitesOf(bot: AppBot): Promise<NetlifySite[]> {+ const fresh = scans.get(bot.id);+ if (fresh && now() - fresh.at < SCAN_FRESH_MS) return fresh.sites;+ const sites = findNetlifySites(deps.folders(bot), { home: deps.home, env: deps.env }).catch(() => []);+ scans.set(bot.id, { at: now(), sites });+ return sites;+ }++ function botThreads(bot: AppBot): string[] {+ const own = [bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)];+ const shared = deps.rooms().filter((room) => room.memberIds.includes(bot.id)).flatMap((room) => [room.threadId, ...(room.tasks ?? []).map((task) => task.threadId)]);+ return [...new Set([...own, ...shared])].slice(-MAX_THREADS_SEARCHED);+ }++ /** The conversations in which this bot itself wrote the site's link. */+ function postedIn(bot: AppBot, site: NetlifySite): string[] {+ const link = linkPattern(site.url), own = new Set([bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)]);+ return botThreads(bot).filter((threadId) => deps.messages(threadId).some((message) =>+ message.role === "bot" && typeof message.text === "string" && (own.has(threadId) ? !message.from?.botId || message.from.botId === bot.id : message.from?.botId === bot.id) && link.test(message.text)));+ }++ async function removeSite(bot: AppBot, site: NetlifySite, auth: RequestAuth, threadId: string | undefined): Promise<PublishedAppDeleteRefusal | null> {+ const token = deps.netlifyToken(bot.id, auth, threadId);+ if (!token) return "no_token";+ const deleted = await deleteNetlifySite(site.siteId, token, { env: deps.env, ...(deps.fetch ? { fetch: deps.fetch } : {}) });+ if (!deleted.ok) return deleted.reason;+ await forgetSiteRecord(site, deps.folders(bot), deps.env);+ scans.delete(bot.id);+ return null;+ }++ function pageEntries(): Entry[] {+ const names = new Map(deps.bots().map((bot) => [bot.id, bot.name]));+ return deps.pages().map((page) => ({+ app: { id: `page-${page.pageId}`, source: "page" as const, title: page.title || page.pageId, url: page.url, bot: { id: page.botId, name: names.get(page.botId) ?? "" },+ publishedAt: page.updatedAt, access: "link" as const },+ threads: () => page.cards.map((card) => card.threadId).reverse(),+ needsThread: true,+ remove: async () => ((await deps.unpublishPage(page.pageId)).status === 200 ? null : "failed"),+ }));+ }++ async function siteEntries(bots: readonly AppBot[]): Promise<Entry[]> {+ const found = await Promise.all(bots.map(async (bot) => ({ bot, sites: await sitesOf(bot) })));+ return found.flatMap(({ bot, sites }) => sites.map((site) => {+ let posted: string[] | undefined;+ const folder = dirname(resolve(site.file));+ const home = [bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)].find((threadId) => within(folder, resolve(deps.ownFolder(bot.id, threadId))));+ return {+ app: { id: `netlify-${bot.id}-${site.siteId}`, source: "netlify" as const, title: site.title, url: site.url, bot: { id: bot.id, name: bot.name },+ publishedAt: site.publishedAt, access: site.access, ...(site.manageUrl ? { manageUrl: site.manageUrl } : {}) },+ threads: () => (home ? [home] : (posted ??= postedIn(bot, site))),+ ...(home ? { home } : {}),+ needsThread: false,+ remove: (auth: RequestAuth, threadId: string | undefined) => removeSite(bot, site, auth, threadId),+ };+ }));+ }++ function mayDelete(visible: VisibleSet, auth: RequestAuth, botId: string, threadId: string | undefined): boolean {+ if (!visible.member) return true;+ return visible.filtersThreads && ((threadId !== undefined && deps.ownChat(auth, threadId)) || visible.level(botId) === "edit");+ }++ async function shown(visible: VisibleSet, auth: RequestAuth): Promise<Shown[]> {+ const entries = [...pageEntries(), ...await siteEntries(deps.bots().filter((bot) => visible.bot(bot.id)))];+ const out: Shown[] = [];+ for (const entry of entries) {+ const botId = entry.app.bot.id;+ let threadId: string | undefined;+ if (!visible.everything) {+ if (!visible.bot(botId)) continue;+ if (entry.needsThread || visible.filtersThreads) {+ threadId = entry.threads().find((candidate) => visible.thread(candidate));+ if (threadId === undefined) continue;+ }+ } else {+ threadId = entry.home ?? (entry.needsThread ? entry.threads()[0] : undefined);+ }+ out.push({ entry, app: { ...entry.app, ...(threadId ? { threadId } : {}), canDelete: mayDelete(visible, auth, botId, threadId) } });+ }+ return out.sort((a, b) => b.app.publishedAt - a.app.publishedAt).slice(0, MAX_LISTED);+ }++ return {+ async list(visible: VisibleSet, auth: RequestAuth): Promise<PublishedApp[]> {+ return (await shown(visible, auth)).map((one) => one.app);+ },+ /** True for an address inside an app this viewer is shown. */+ async lists(visible: VisibleSet, auth: RequestAuth, url: string): Promise<boolean> {+ let asked: URL;+ try { asked = new URL(url); } catch { return false; }+ return (await shown(visible, auth)).some(({ app }) => {+ const base = new URL(app.url);+ return asked.origin === base.origin && asked.pathname.startsWith(base.pathname);+ });+ },+ async remove(visible: VisibleSet, auth: RequestAuth, id: string): Promise<DeleteAnswer> {+ const found = (await shown(visible, auth)).find((one) => one.app.id === id);+ const refusal = !found ? "gone" : !found.app.canDelete ? "forbidden" : await found.entry.remove(auth, found.app.threadId);+ if (!refusal) return { status: 200, body: { ok: true } };+ const { status, error } = REFUSALS[refusal];+ const manageUrl = refusal === "no_token" || refusal === "token_refused" ? found?.app.manageUrl : undefined;+ return { status, body: { error, code: refusal, ...(manageUrl ? { manageUrl } : {}) } };+ },+ };+}++export type PublishedApps = ReturnType<typeof createPublishedApps>;diff --git a/server/index.ts b/server/index.tsindex 34a2babf52..1d07a34678 100644--- a/server/index.ts+++ b/server/index.ts@@ -627,7 +627,7 @@ import { findAntigravityLeftovers, removeAntigravityLeftovers } from "./drivers/import { createLiveRoutes } from "./routes/live.ts";import { createNotificationRoutes, notificationListedFor } from "./routes/notifications.ts";import { createTodayRoutes } from "./routes/today.ts"; import { createInboxRoutes } from "./routes/inbox.ts"; import { createSidebarSectionRoutes } from "./routes/sidebar-sections.ts";-import { createToolTimingRoute, createUsageRoutes } from "./routes/usage.ts"; import { createPrivateRecords } from "./host/private-records.ts";+import { createToolTimingRoute, createUsageRoutes } from "./routes/usage.ts"; import { createPrivateRecords } from "./host/private-records.ts"; import { createPublishedApps } from "./host/published-apps.ts"; import { savedNetlifyToken } from "./host/netlify-sites.ts"; import { createPublishedAppsRoutes } from "./routes/published-apps.ts";import { createBotMessageRoutes } from "./routes/bot-messages.ts";import { clearInternalTurn, isInternalTurn, markInternalTurn } from "./internal-turns.ts"; import { createFirstReplyRescue } from "./first-reply-rescue.ts";import { createReactionRoutes } from "./routes/reactions.ts";@@ -12326,7 +12326,7 @@ ROUTES.push(createBrowserSiteRoutes({}));ROUTES.push(createBrowserEvidenceRoutes({ evidence: browserEvidence.attach({ onChange: (listener) => store.onChange(listener), threadExists: (id) => Boolean(threadOwner(id)) }), threadExists: (id) => Boolean(threadOwner(id)) }));const loginRoutes = botLogins.routes((id) => Boolean(store.bot(id))); ROUTES.push(createLoginRoutes(loginRoutes), createVaultRoutes({ logins: loginRoutes, secrets: logins, linked: () => botLogins.linkedSecrets(), keys: mcpKeys, reader: vaultReaders.viewer }));-const privateRecords = createPrivateRecords({ visibleFor: (auth) => visibleTo(viewerFor(auth)), botExists: (id) => Boolean(store.bot(id)), routine: (id) => routines?.listRoutines().find((routine) => routine.id === id) }); ROUTES.push(createUsageRoutes({+const privateRecords = createPrivateRecords({ visibleFor: (auth) => visibleTo(viewerFor(auth)), botExists: (id) => Boolean(store.bot(id)), routine: (id) => routines?.listRoutines().find((routine) => routine.id === id) }); ROUTES.push(createPublishedAppsRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), apps: createPublishedApps({ bots: () => store.bots, rooms: () => store.groups, messages: (threadId) => store.messagesFor(threadId), folders: (bot) => [...new Set([bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)].flatMap((threadId) => liveRoots(threadId, bot.id) ?? []))], ownFolder: (botId, threadId) => join(TASK_WORKSPACES_DIR, botId, threadId), pages: () => publishedPages.store.list(), unpublishPage: (pageId) => publishedPages.publisher.unpublish({ pageId }), netlifyToken: (botId, auth, threadId) => savedNetlifyToken(logins, botId, CLOUD_TEAM && !threadId ? null : vaultReaders.turn(threadId ?? ""), auth.kind === "session" ? actorKey(auth) : null), ownChat: (auth, threadId) => auth.kind === "session" && teamHost.privateTo(threadId) === personKey(auth.session), home: homedir(), env: process.env }) })); ROUTES.push(createUsageRoutes({dataDir: DATA_DIR, prices: operatorPrices,budget: () => spendState(cfg, DATA_DIR),currency: () => cfg.billing?.currency ?? "USD",diff --git a/server/request-auth.ts b/server/request-auth.tsindex 9d40b979be..a55bed6622 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -466,6 +466,9 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/bot-api\/new-key$/ },// asking to chat with a team bot one can view: the handler puts a card in the inbox of whoever can let them in{ methods: ["POST"], path: /^\/api\/bots\/[\w-]+\/access-request$/ },+ // what the viewer's own bots put online, from conversations they can read; the handler deletes only what is theirs+ { methods: ["GET"], path: /^\/api\/published-apps(?:\/framing)?$/ },+ { methods: ["POST"], path: /^\/api\/published-apps\/delete$/ },];export function requiredScope(method: string, path: string, features: { sharedComputers?: boolean } = {}): Scope {diff --git a/server/routes/published-apps.test.ts b/server/routes/published-apps.test.tsnew file mode 100644index 0000000000..5bd8f390ac--- /dev/null+++ b/server/routes/published-apps.test.ts@@ -0,0 +1,93 @@+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { PublishedApp } from "../../shared/published-apps.ts";+import type { VisibleSet } from "../bot-visibility.ts";+import { json, readBody } from "../harness/http.ts";+import type { PublishedApps } from "../host/published-apps.ts";+import { requiredScope, type RequestAuth } from "../request-auth.ts";+import { createPublishedAppsRoutes } from "./published-apps.ts";+import { dispatchRoutes } from "./table.ts";++const servers: Server[] = [];+afterEach(async () => { await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done)))); });++const APP: PublishedApp = { id: "netlify-mira-s1", source: "netlify", title: "Bakery", url: "https://bakery.netlify.app/", bot: { id: "mira", name: "Mira" }, publishedAt: 5, access: "public", canDelete: true };+const AUTH = { kind: "session", scopes: ["client"], session: { id: "s1", email: "[email protected]" } } as unknown as RequestAuth;+const VISIBLE = { marker: "ada's view" } as unknown as VisibleSet;++async function fixture() {+ const apps = {+ list: vi.fn(async () => [APP]),+ lists: vi.fn(async (_visible: VisibleSet, _auth: RequestAuth, url: string) => url.startsWith(APP.url)),+ remove: vi.fn(async (_visible: VisibleSet, _auth: RequestAuth, id: string) => id === APP.id+ ? { status: 200 as const, body: { ok: true as const } } : { status: 404 as const, body: { error: "No such published app.", code: "gone" as const } }),+ };+ const framing = vi.fn(async () => "allowed" as const);+ const routes = [createPublishedAppsRoutes({ apps: apps as unknown as PublishedApps, visibleFor: (auth) => (auth === AUTH ? VISIBLE : (undefined as never)), framing })];+ const server = createServer((req, res) => {+ const url = new URL(req.url ?? "/", "http://127.0.0.1");+ void dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth: AUTH, json, readBody })+ .then((answered) => { if (!answered) json(res, 404, { error: "not routed" }); }, (error: { status?: number; message: string }) => json(res, error.status ?? 500, { error: error.message }));+ });+ servers.push(server);+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ const call = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(`${base}${path}`, { method, ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: typeof body === "string" ? body : JSON.stringify(body) }) });+ return { status: response.status, body: await response.json() as Record<string, unknown> };+ };+ return { apps, framing, call };+}++describe("the Published apps routes", () => {+ it("are open to a member's session, and nothing beside them is", () => {+ for (const [method, path] of [["GET", "/api/published-apps"], ["GET", "/api/published-apps/framing"], ["POST", "/api/published-apps/delete"]] as const) {+ expect(requiredScope(method, path), `${method} ${path}`).toBe("client");+ }+ for (const [method, path] of [["POST", "/api/published-apps"], ["DELETE", "/api/published-apps/delete"], ["GET", "/api/published-apps/delete"], ["POST", "/api/published-apps/framing"],+ ["GET", "/api/published-apps/anything"], ["POST", "/api/published-pages/abcdefghijklmnopqrstuvwxyz/unpublish"], ["GET", "/api/web-panels/framing"]] as const) {+ expect(requiredScope(method, path), `${method} ${path}`).toBe("admin");+ }+ });++ it("lists what the asking viewer is shown", async () => {+ const { apps, call } = await fixture();+ expect(await call("GET", "/api/published-apps")).toEqual({ status: 200, body: { apps: [APP] } });+ expect(apps.list).toHaveBeenCalledWith(VISIBLE, AUTH);+ });++ it("checks framing only for an address in the viewer's own list", async () => {+ const { framing, call } = await fixture();+ const origin = encodeURIComponent("http://127.0.0.1:5173");+ expect(await call("GET", `/api/published-apps/framing?url=${encodeURIComponent("https://bakery.netlify.app/menu")}&origin=${origin}`)).toEqual({ status: 200, body: { framing: "allowed" } });+ expect(framing).toHaveBeenCalledWith("https://bakery.netlify.app/menu", "http://127.0.0.1:5173");+ for (const other of ["https://example.com/", "http://169.254.169.254/latest/meta-data", "http://127.0.0.1:8080/", "http://someone.netlify.app/", "https://netlify.app.evil.test/",+ "https://app.netlify.com/", "https://upload.mausbot.page/", "file:///etc/passwd", "not a url"]) {+ expect((await call("GET", `/api/published-apps/framing?url=${encodeURIComponent(other)}&origin=${origin}`)).status, other).toBe(404);+ }+ expect((await call("GET", "/api/published-apps/framing?url=https%3A%2F%2Fbakery.netlify.app%2F")).status).toBe(400);+ expect(framing).toHaveBeenCalledTimes(1);+ for (const hosted of ["https://linked-in-a-message.netlify.app/", "https://abcdefghijklmnopqrstuvwxyz.mausbot.page/report"]) {+ expect((await call("GET", `/api/published-apps/framing?url=${encodeURIComponent(hosted)}&origin=${origin}`)).status, hosted).toBe(200);+ }+ expect(framing).toHaveBeenCalledTimes(3);+ });++ it("deletes by id, passes the host's refusal through, and refuses a malformed request", async () => {+ const { apps, call } = await fixture();+ expect(await call("POST", "/api/published-apps/delete", { id: APP.id })).toEqual({ status: 200, body: { ok: true } });+ expect(apps.remove).toHaveBeenCalledWith(VISIBLE, AUTH, APP.id);+ expect(await call("POST", "/api/published-apps/delete", { id: "netlify-mira-other" })).toEqual({ status: 404, body: { error: "No such published app.", code: "gone" } });+ for (const bad of [{}, { id: "" }, { id: 7 }, { id: APP.id, token: "x" }, { id: "x".repeat(301) }]) expect((await call("POST", "/api/published-apps/delete", bad)).status, JSON.stringify(bad).slice(0, 40)).toBe(400);+ expect(apps.remove).toHaveBeenCalledTimes(2);+ });++ it("passes on anything else", async () => {+ const { call } = await fixture();+ for (const [method, path] of [["GET", "/api/published-apps/delete"], ["POST", "/api/published-apps"], ["GET", "/api/published-pages"]] as const) {+ expect(await call(method, path), `${method} ${path}`).toEqual({ status: 404, body: { error: "not routed" } });+ }+ });+});diff --git a/server/routes/published-apps.ts b/server/routes/published-apps.tsnew file mode 100644index 0000000000..32d85a0852--- /dev/null+++ b/server/routes/published-apps.ts@@ -0,0 +1,53 @@+import { z } from "zod";+import { isNetlifySiteUrl, type PublishedAppsList } from "../../shared/published-apps.ts";+import { PAGE_ID } from "../../shared/published-page.ts";+import type { VisibleSet } from "../bot-visibility.ts";+import type { PublishedApps } from "../host/published-apps.ts";+import type { RequestAuth } from "../request-auth.ts";+import { checkFraming, type Framing } from "../web-panel-framing.ts";+import { PASS, type RouteHandler } from "./table.ts";++export interface PublishedAppsRouteDeps {+ apps: PublishedApps;+ /** The same filter the GET /api/bots listing applies to this caller. */+ visibleFor(auth: RequestAuth): VisibleSet;+ framing?: (url: string, origin: string) => Promise<Framing>;+}++/** Must match src/lib/page-open.ts `isPublishedPageUrl`. */+function isPageUrl(value: string): boolean {+ let url: URL;+ try { url = new URL(value); } catch { return false; }+ const host = url.hostname.toLowerCase();+ return url.protocol === "https:" && !url.username && !url.password && !url.port && host.endsWith(".mausbot.page") && PAGE_ID.test(host.slice(0, -".mausbot.page".length));+}++const deleteBody = z.object({ id: z.string().min(1).max(300) }).strict();++/** GET /api/published-apps: what this viewer's bots put online. POST /api/published-apps/delete `{ id }`: takes one of+ * them down for good. GET /api/published-apps/framing?url=…&origin=…: whether one of them lets the app at `origin`+ * frame it.+ * Security: the list and the delete answer from the viewer's own list (host/published-apps.ts), so an id of an app they+ * are not shown reads as one that does not exist. The framing check reaches only an address in that list or a public+ * hosting address (a Netlify site's, a published page's), and answers with a verdict, never a page's content. */+export function createPublishedAppsRoutes(deps: PublishedAppsRouteDeps): RouteHandler {+ const framing = deps.framing ?? checkFraming;+ return async ({ req, res, url, path, method, auth, json, readBody }) => {+ if (path === "/api/published-apps" && method === "GET") {+ return json(res, 200, { apps: await deps.apps.list(deps.visibleFor(auth), auth) } satisfies PublishedAppsList);+ }+ if (path === "/api/published-apps/framing" && method === "GET") {+ const page = url.searchParams.get("url"), origin = url.searchParams.get("origin");+ if (!page || !origin) return json(res, 400, { error: "url and origin are required." });+ if (!isNetlifySiteUrl(page) && !isPageUrl(page) && !await deps.apps.lists(deps.visibleFor(auth), auth, page)) return json(res, 404, { error: "No such published app." });+ return json(res, 200, { framing: await framing(page, origin) });+ }+ if (path === "/api/published-apps/delete" && method === "POST") {+ const body = deleteBody.safeParse(await readBody(req, 4_096));+ if (!body.success) return json(res, 400, { error: "Delete takes id, the published app to delete." });+ const answer = await deps.apps.remove(deps.visibleFor(auth), auth, body.data.id);+ return json(res, answer.status, answer.body);+ }+ return PASS;+ };+}diff --git a/shared/published-apps.ts b/shared/published-apps.tsnew file mode 100644index 0000000000..850a564427--- /dev/null+++ b/shared/published-apps.ts@@ -0,0 +1,40 @@+/** One thing a bot put online, as the Published apps page shows it (GET /api/published-apps). */+export interface PublishedApp {+ id: string;+ /** `page`: a page published from this server to a MausBot link. `netlify`: a site on the person's own Netlify account. */+ source: "page" | "netlify";+ title: string;+ url: string;+ /** The bot whose folder or conversation it came from; `name` is empty once that bot is gone. */+ bot: { id: string; name: string };+ /** A conversation the viewer can read where the bot published it, when one is known. */+ threadId?: string;+ publishedAt: number;+ /** `link`: anyone who has the link. `public`: the site answered without a login. `netlify-team`: it asked for a+ * Netlify login when last checked. */+ access: "link" | "public" | "netlify-team" | "unknown";+ /** The site's page in the person's Netlify account. */+ manageUrl?: string;+ canDelete: boolean;+}++export interface PublishedAppsList {+ apps: PublishedApp[];+}++/** Why POST /api/published-apps/delete did not delete. `no_token` and `token_refused` come with `manageUrl`. */+export type PublishedAppDeleteRefusal = "gone" | "forbidden" | "no_token" | "token_refused" | "failed";++export interface PublishedAppDeleteFailure {+ error: string;+ code: PublishedAppDeleteRefusal;+ manageUrl?: string;+}++/** A site's own address on Netlify: https://<name>.netlify.app, with nothing but a path after it. */+export function isNetlifySiteUrl(value: string | null | undefined): value is string {+ if (typeof value !== "string") return false;+ let url: URL;+ try { url = new URL(value); } catch { return false; }+ return url.protocol === "https:" && !url.username && !url.password && !url.port && /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.netlify\.app$/.test(url.hostname.toLowerCase());+}diff --git a/src/App.tsx b/src/App.tsxindex 17c1730701..916f826b01 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -22,7 +22,7 @@ import { SIDEBAR_AND_PANEL_FIT, SIDEBAR_INLINE, TWO_SIDE_PANELS_FIT, useMediaQueimport { preloadConnectedApps } from "@/lib/connected-apps";import {ActivityPanel, BotSettingsDialog, CloudAddDialog, ComputerPanel, FilesView, InspectorPanel, KeyboardShortcutsModal, LocalVmWorkspace,- PluginsPanel, preloadScreens, RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamMapPage, TriggersPage,+ PluginsPanel, preloadScreens, PublishedAppsPage, RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamMapPage, TriggersPage,} from "@/components/lazy-screens";import { useAdvancedMode } from "@/lib/interface-mode";import { useRoomPanelShown } from "@/lib/room-panel";@@ -78,6 +78,7 @@ import { useChiefStepOpen } from "@/lib/default-bot";import { useSessionEnded } from "@/lib/session-ended";import { PairPage } from "./pair/PairPage";import { WebPanelPage } from "@/components/WebPanelPage";+import { AppPreviewPanel } from "@/components/published-apps/AppPreviewPanel";function Shell({ viewer }: { viewer: WelcomeViewer | null }) {const { state, dispatch } = useStore();@@ -376,6 +377,8 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {<FilesView />) : state.activeView === "web-panel" ? (<WebPanelPage />+ ) : state.activeView === "published-apps" ? (+ <PublishedAppsPage />) : state.activeView === "routines" ? (<TriggersPage onBack={closeCalendar} onOpenRoom={openCalendarRoom} />) : !remoteClient && localVmWorkspaceBotId ? (@@ -431,6 +434,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {/>))}+ <AppPreviewPanel />{roomPanelOpen && group && (<RoomPanel key={`room:${group.id}`} group={group} overlay={notificationFeed && state.notificationsOpen && !twoSidePanelsFit} />)}diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsxindex 1a7c8f68ca..5933853ca4 100644--- a/src/components/ChatMarkdown.tsx+++ b/src/components/ChatMarkdown.tsx@@ -630,7 +630,7 @@ function MarkdownLink({ href, children, ...rest }: { href?: string; children?: R// SAFETY: react-markdown hands hast data-* attributes through as string propsconst props = rest as Record<string, unknown>;const { threads, currentBotId, message, delivered, originals } = useContext(MessageScopeContext);- const linkMenu = useThreadLinkMenu(href), openPage = usePageOpener();+ const linkMenu = useThreadLinkMenu(href), openPage = usePageOpener({ beside: true });if (!href) return <span className="break-words">{children}</span>;if (isUseMyComputerUrl(href)) return <UseMyComputerLink>{children}</UseMyComputerLink>;const address = parseThreadRefUrl(href);diff --git a/src/components/SidebarFooterNav.test.ts b/src/components/SidebarFooterNav.test.tsindex d66973722b..4d3b47dcb7 100644--- a/src/components/SidebarFooterNav.test.ts+++ b/src/components/SidebarFooterNav.test.ts@@ -262,6 +262,8 @@ describe("toolbar tools layout", () => {expect(html).toContain('data-tour="tools"');expect(html).toMatch(/data-tour="nav-automations" data-sidebar-nav="automations"/);expect(html).toMatch(/data-tour="team-tools" data-sidebar-nav="team-map"/);+ expect(html).toContain('data-sidebar-nav="published-apps"');+ expect(html.indexOf('data-sidebar-nav="published-apps"')).toBeGreaterThan(html.indexOf('data-sidebar-nav="team-map"'));const place = (id: string) => {const at = html.indexOf(`data-sidebar-nav="${id}"`);const next = html.indexOf("data-sidebar-nav=", at + 1);@@ -279,9 +281,9 @@ describe("toolbar tools layout", () => {expect(render("comfortable", { toolsLayout: "toolbar" }).html).not.toContain('data-testid="routines-attention"');});- it("toolbar applies to Advanced mode's two places; Simple mode keeps them in the bottom bar instead", () => {+ it("toolbar applies to Advanced mode's three places; Simple mode keeps them in the bottom bar instead", () => {fixture.advanced = true;- expect(render("comfortable", { toolsLayout: "toolbar" }).html.match(/data-sidebar-nav="/g)).toHaveLength(2);+ expect(render("comfortable", { toolsLayout: "toolbar" }).html.match(/data-sidebar-nav="/g)).toHaveLength(3);fixture.advanced = false;expect(render("comfortable", { toolsLayout: "toolbar" }).html).toBe("");});diff --git a/src/components/SidebarFooterNav.tsx b/src/components/SidebarFooterNav.tsxindex d57f6e20b6..6b285d9c95 100644--- a/src/components/SidebarFooterNav.tsx+++ b/src/components/SidebarFooterNav.tsx@@ -1,4 +1,4 @@-import { AppWindow, FolderOpen, Globe, Puzzle, UsersRound, Zap } from "lucide-react";+import { AppWindow, FolderOpen, Globe, Puzzle, Rocket, UsersRound, Zap } from "lucide-react";import { useMemo, type ReactNode } from "react";import { useAppTriggers } from "@/lib/app-triggers";@@ -173,6 +173,14 @@ export function SidebarFooterNav({/>)}{filesRow}+ <NavRow+ id="published-apps"+ label={t("sidebar.nav.publishedApps")}+ iconsOnly={iconsOnly || toolbar}+ active={state.activeView === "published-apps"}+ icon={(active) => <Rocket size={iconSize} className={tone(active)} />}+ onClick={() => dispatch({ type: "showPublishedApps" })}+ />{advanced && webPanels.map((panel) => (<NavRowkey={panel.id}diff --git a/src/components/SidebarPhoneBar.tsx b/src/components/SidebarPhoneBar.tsxindex c5b92245ff..4168360bdd 100644--- a/src/components/SidebarPhoneBar.tsx+++ b/src/components/SidebarPhoneBar.tsx@@ -1,4 +1,4 @@-import { FolderOpen, LayoutGrid, Puzzle, Search, UsersRound, X, Zap } from "lucide-react";+import { FolderOpen, LayoutGrid, Puzzle, Rocket, Search, UsersRound, X, Zap } from "lucide-react";import { useCloudFilesReady } from "@/lib/cloud-files";import { t } from "@/lib/i18n";@@ -38,6 +38,13 @@ export function SidebarPhoneBar({ query, onQuery }: { query: string; onQuery: (qactive: state.activeView === "files",onSelect: () => dispatch({ type: "showFiles" }),}] : []),+ {+ key: "published-apps",+ label: t("sidebar.nav.publishedApps"),+ icon: <Rocket size={18} />,+ active: state.activeView === "published-apps",+ onSelect: () => dispatch({ type: "showPublishedApps" }),+ },{key: "apps",label: t("sidebar.nav.apps"),diff --git a/src/components/SidebarProfileMenu.test.ts b/src/components/SidebarProfileMenu.test.tsindex 5b1e4cd513..def016502b 100644--- a/src/components/SidebarProfileMenu.test.ts+++ b/src/components/SidebarProfileMenu.test.ts@@ -473,6 +473,15 @@ describe("Simple mode's account menu", () => {expect(toolMenuItems({ activeView: "chat", automationsNeedYou: false, onAutomations: noop, onTeamMap: noop, archived: { count: 0, open } }).map((item) => item.key)).toEqual(["automations", "team-map"]);});+ it("has Published apps among the tools, after Files and before Archived bots, lit while its page is open", () => {+ const openApps = vi.fn();+ const items = toolMenuItems({ activeView: "published-apps", automationsNeedYou: false, onAutomations: noop, onTeamMap: noop, onFiles: noop, onPublishedApps: openApps, archived: { count: 1, open: noop } });+ expect(items.map((item) => [item.key, item.label, item.active])).toEqual([["automations", "Automations", false], ["team-map", "Team map", false], ["files", "Files", false],+ ["published-apps", "Published apps", true], ["archived", "Archived bots", undefined]]);+ items[3]!.onSelect();+ expect(openApps).toHaveBeenCalledOnce();+ });+it("names the account button after the person and whatever its dot is raised for", () => {expect(accountLabel("You", { automationsNeedYou: false, update: null })).toBe("You");expect(accountLabel("Ada", { automationsNeedYou: true, update: "Update failed. Try again." })).toBe("Ada · Automations need you · Update failed. Try again.");diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsxindex edb263184f..125bc674fa 100644--- a/src/components/SidebarProfileMenu.tsx+++ b/src/components/SidebarProfileMenu.tsx@@ -15,6 +15,7 @@ import {LifeBuoy,Loader2,RefreshCw,+ Rocket,Settings as SettingsIcon,Smartphone,UserRound,@@ -321,19 +322,21 @@ export function phoneMenuItems({} satisfies SidebarMenuItem));}-export function toolMenuItems({ activeView, automationsNeedYou, onAutomations, onTeamMap, onFiles, archived }: {+export function toolMenuItems({ activeView, automationsNeedYou, onAutomations, onTeamMap, onFiles, onPublishedApps, archived }: {activeView: string;automationsNeedYou: boolean;onAutomations: () => void;onTeamMap: () => void;/** set once My Cloud's files are ready to open */onFiles?: () => void;+ onPublishedApps?: () => void;archived?: ArchivedBots;}): SidebarMenuItem[] {return [{ key: "automations", label: t("sidebar.nav.automations"), icon: <Zap size={16} />, active: activeView === "routines", attention: automationsNeedYou, onSelect: onAutomations },{ key: "team-map", label: t("sidebar.nav.teamMap"), icon: <UsersRound size={16} />, active: activeView === "team-map", onSelect: onTeamMap },...(onFiles ? [{ key: "files", label: t("sidebar.nav.files"), icon: <FolderOpen size={16} />, active: activeView === "files", onSelect: onFiles }] : []),+ ...(onPublishedApps ? [{ key: "published-apps", label: t("sidebar.nav.publishedApps"), icon: <Rocket size={16} />, active: activeView === "published-apps", onSelect: onPublishedApps }] : []),...(archived?.count ? [{ key: "archived", label: t("sidebar.archived.title"), icon: <Archive size={16} />, value: String(archived.count), onSelect: archived.open }] : []),];}@@ -611,6 +614,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = faonAutomations: () => dispatch({ type: "showRoutines", view: "list" }),onTeamMap: () => dispatch({ type: "showTeamMap" }),onFiles: filesReady ? () => dispatch({ type: "showFiles" }) : undefined,+ onPublishedApps: () => dispatch({ type: "showPublishedApps" }),archived: account.archived,}),places: placeMenuItems(account.place, { owner: account.owner, name: state.config?.team?.name, besideRail, onCloudSettings: openCloudAccount }),diff --git a/src/components/ToolPageShell.tsx b/src/components/ToolPageShell.tsxnew file mode 100644index 0000000000..2c3da61570--- /dev/null+++ b/src/components/ToolPageShell.tsx@@ -0,0 +1,46 @@+import type { CSSProperties, ReactNode, Ref } from "react";+import { ArrowLeft } from "lucide-react";++import { useDesktopCapabilities, windowFramed } from "@/components/DesktopCapabilities";+import { cn } from "@/lib/cn";++// The page a Tools entry opens in place of the chat (Automations and its calendar, Published apps): one header with+// Back, the title and the page's own controls, over the page's body.++export const TOOL_PAGE_TITLE = "mr-1 text-[18px] font-semibold tracking-tight text-ink";++// SAFETY: Electron's -webkit-app-region is not in React's CSSProperties type; the renderer accepts it as an inline style.+const DRAG = { WebkitAppRegion: "drag" } as CSSProperties, NO_DRAG = { WebkitAppRegion: "no-drag" } as CSSProperties;++function useMacInset(): boolean {+ return useDesktopCapabilities().capabilities.windowChrome === "mac-inset";+}++export function ToolPage({ label, children }: { label?: string; children: ReactNode }) {+ return <main aria-label={label} className="flex h-full min-w-0 flex-1 flex-col bg-app animate-workspace-in">{children}</main>;+}++/** `besideSidebar` is false while the page has the whole window (the calendar), so the title clears the Mac window+ * buttons instead of the phone's drawer button. */+export function ToolPageHeader({ backLabel, onBack, backRef, besideSidebar = true, children }: {+ backLabel: string;+ onBack: () => void;+ backRef?: Ref<HTMLButtonElement>;+ besideSidebar?: boolean;+ children: ReactNode;+}) {+ const { capabilities } = useDesktopCapabilities();+ const macInset = useMacInset();+ return (+ <header className={cn("shrink-0 border-b border-hairline/35 bg-app py-3 pr-4", macInset && !windowFramed(capabilities) && !besideSidebar ? "pl-[86px]" : besideSidebar ? "pl-12 md:pl-4" : "pl-4")} style={macInset ? DRAG : undefined}>+ <div className="flex flex-wrap items-center gap-2">+ <button type="button" ref={backRef} onClick={onBack} aria-label={backLabel} title={backLabel} className="flex size-9 shrink-0 items-center justify-center rounded-lg text-ink-secondary hover:bg-raised hover:text-ink" style={macInset ? NO_DRAG : undefined}><ArrowLeft size={18} /></button>+ {children}+ </div>+ </header>+ );+}++export function ToolPageActions({ children }: { children: ReactNode }) {+ return <div className="ml-auto flex items-center gap-3" style={useMacInset() ? NO_DRAG : undefined}>{children}</div>;+}diff --git a/src/components/TriggersPage.tsx b/src/components/TriggersPage.tsxindex c03359138d..b2b2ccfa51 100644--- a/src/components/TriggersPage.tsx+++ b/src/components/TriggersPage.tsx@@ -1,7 +1,6 @@-import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react";-import { ArrowLeft, Plus, Zap } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { Plus, Zap } from "lucide-react";-import { useDesktopCapabilities, windowFramed } from "@/components/DesktopCapabilities";import { automationsFrom, automationSentence, automationStatus, orderAutomations, runLine, statusLine, type Automation } from "@/lib/automations";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";@@ -20,6 +19,7 @@ import { FixButton, StatusMark } from "./automations/parts";import { RoutineEditor } from "./RoutineCalendarPage";import { Select } from "./Select";import { Switch } from "./SettingsPrimitives";+import { TOOL_PAGE_TITLE, ToolPage, ToolPageActions, ToolPageHeader } from "./ToolPageShell";import { WebhookEditor } from "./WebhookTrigger";import { schedulableBots, useTeamPeople } from "@/state/team-people";@@ -29,7 +29,6 @@ const FILTER_FROM = 9;/** Automations: every schedule and every "when another app sends something", each as one plain sentence. */export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpenRoom: (id: string) => void }) {const { state, dispatch } = useStore();- const { capabilities } = useDesktopCapabilities();const actions = useAllAutomationActions();const appTriggers = useAppTriggers();const backButtonRef = useRef<HTMLButtonElement>(null);@@ -69,20 +68,15 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpeconst open = all.find((automation) => automation.id === openId) ?? null;const sentenceOf = (automation: Automation) => automationSentence(automation, botName(automation.botId));- const macInset = capabilities.windowChrome === "mac-inset";- const windowDragStyle = macInset ? ({ WebkitAppRegion: "drag" } as CSSProperties) : undefined;- const windowNoDragStyle = macInset ? ({ WebkitAppRegion: "no-drag" } as CSSProperties) : undefined;const editRoutine = editing?.kind === "schedule" ? state.routines.find((routine) => routine.id === editing.id) : undefined;const editWebhook = editing?.kind === "webhook" ? state.webhooks.find((webhook) => webhook.id === editing.id) : undefined;const editApp = editing?.kind === "app" ? appTriggers.triggers.find((trigger) => trigger.id === editing.id) : undefined;return (- <main className="flex h-full min-w-0 flex-1 flex-col bg-app animate-workspace-in">- <header className={cn("shrink-0 border-b border-hairline/35 bg-app py-3 pr-4", macInset && !windowFramed(capabilities) && view === "calendar" ? "pl-[86px]" : view === "list" ? "pl-12 md:pl-4" : "pl-4")} style={windowDragStyle}>- <div className="flex flex-wrap items-center gap-2">- <button type="button" ref={backButtonRef} onClick={onBack} aria-label={t("automations.back")} title={t("automations.back")} className="flex size-9 shrink-0 items-center justify-center rounded-lg text-ink-secondary hover:bg-raised hover:text-ink" style={windowNoDragStyle}><ArrowLeft size={18} /></button>- <h1 data-tour="automations-page" className="mr-1 text-[18px] font-semibold tracking-tight text-ink">{t("automations.title")}</h1>- <div className="ml-auto flex items-center gap-3" style={windowNoDragStyle}>+ <ToolPage>+ <ToolPageHeader backLabel={t("automations.back")} onBack={onBack} backRef={backButtonRef} besideSidebar={view === "list"}>+ <h1 data-tour="automations-page" className={TOOL_PAGE_TITLE}>{t("automations.title")}</h1>+ <ToolPageActions>{showDepartments && (<Select size="sm" aria-label={t("automations.allDepartments")} value={activeDepartment} onChange={(event) => { setDepartment(event.target.value); setBotFilter("all"); }} className="max-w-[180px]"><option value="all">{t("automations.allDepartments")}</option>@@ -105,9 +99,8 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe))}</div><button type="button" onClick={() => setNewText("")} className="flex items-center gap-1.5 rounded-lg bg-accent px-3.5 py-2 text-[13px] font-semibold text-accent-ink hover:brightness-110"><Plus size={15} aria-hidden="true" />{t("automations.new")}</button>- </div>- </div>- </header>+ </ToolPageActions>+ </ToolPageHeader><div className="relative flex min-h-0 flex-1">{view === "calendar" ? <AutomationsCalendar botFilter={botFilter} department={activeDepartment} selectedAutomationId={openId} onOpenAutomation={setOpenId} onOpenRoom={onOpenRoom} /> : (@@ -169,7 +162,7 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe<WebhookEditor webhook={editWebhook} bots={visibleBots} initialBotId={editing.botId} onClose={() => setEditing(null)} onCredential={(credential, id) => { saveWebhookCredential(webhookCredentialStore(), id, credential); setOpenId(id); }} />)}{editing?.kind === "app" && (editApp || !editing.id) && <AppEventEditor trigger={editApp} bots={visibleBots} initialBotId={editing.botId} onClose={() => setEditing(null)} onSaved={(trigger) => setOpenId(trigger.id)} />}- </main>+ </ToolPage>);}diff --git a/src/components/WebPanelPage.tsx b/src/components/WebPanelPage.tsxindex 6426a0a7b9..f7e8abf9ee 100644--- a/src/components/WebPanelPage.tsx+++ b/src/components/WebPanelPage.tsx@@ -8,6 +8,7 @@ import { useEffect, useRef, useState } from "react";import { openExternalLink } from "@/lib/app-links";import { t } from "@/lib/i18n";+import { SITE_FRAME_SANDBOX } from "@/lib/published-apps";import { setWebPanels, useWebPanels } from "@/lib/web-panel-preferences";import { isAppOrigin, type PinnedChatPage, type WebPanel } from "@/lib/web-panels";import { api } from "@/state/api";@@ -85,7 +86,7 @@ export function WebPanelPage() {key={`${panel.id}:${reloads}`}src={panel.url}title={panel.name}- sandbox="allow-scripts allow-same-origin allow-forms allow-popups"+ sandbox={SITE_FRAME_SANDBOX}referrerPolicy="no-referrer"onLoad={() => setStatus("loaded")}onError={() => setStatus("failed")}diff --git a/src/components/lazy-screens.test.ts b/src/components/lazy-screens.test.tsindex 07495b93f9..927dab103f 100644--- a/src/components/lazy-screens.test.ts+++ b/src/components/lazy-screens.test.ts@@ -155,7 +155,7 @@ describe("preloadScreens", () => {it("a page on this machine fetches nothing ahead: each screen loads when it opens", () => {vi.useFakeTimers();const preloads = stubPreloads();- expect(preloads.length).toBe(20);+ expect(preloads.length).toBe(21);for (const host of ["127.0.0.1", "localhost", "[::1]"]) preloadScreens(host);vi.runAllTimers();for (const preload of preloads) expect(preload).not.toHaveBeenCalled();@@ -262,7 +262,7 @@ describe("launch bundle", () => {expect(reached.has("components/Sidebar.tsx")).toBe(true);const deferred = ["ActivityPanel", "BotSettingsDialog", "CloudAddDialog", "ComputerPanel", "InspectorPanel", "KeyboardShortcutsModal",- "LocalVmWorkspace", "NewBotDialog", "PhoneAppDialog", "PhoneSetupFlow", "PluginsPanel", "RemoteAgentSettingsPanel", "remote-desktop-panel", "RoutineCalendarPage",+ "LocalVmWorkspace", "NewBotDialog", "PhoneAppDialog", "PhoneSetupFlow", "PluginsPanel", "published-apps/PublishedAppsPage", "RemoteAgentSettingsPanel", "remote-desktop-panel", "RoutineCalendarPage","RoutinesPage", "SettingsModal", "ShareTeamDialog", "TeamLibraryPanel", "TeamMapPage", "TriggersPage", "WebhookTrigger", "room-panel/RoomPanel",].map((name) => `components/${name}.tsx`);expect(deferred.filter((file) => reached.has(file))).toEqual([]);diff --git a/src/components/lazy-screens.tsx b/src/components/lazy-screens.tsxindex 7cc2c03fda..67917d9626 100644--- a/src/components/lazy-screens.tsx+++ b/src/components/lazy-screens.tsx@@ -80,6 +80,7 @@ export const RemoteDesktopPanel = lazyScreen("RemoteDesktopPanel", async () => (export const TriggersPage = lazyScreen("TriggersPage", async () => (await import("./TriggersPage")).TriggersPage);export const SettingsModal = lazyScreen("SettingsModal", async () => (await import("./SettingsModal")).SettingsModal);export const TeamMapPage = lazyScreen("TeamMapPage", async () => (await import("./TeamMapPage")).TeamMapPage);+export const PublishedAppsPage = lazyScreen("PublishedAppsPage", async () => (await import("./published-apps/PublishedAppsPage")).PublishedAppsPage);// Rarely opened, so never fetched ahead. The team library is what brings the YAML parser in.export const CloudAddDialog = lazyScreen("CloudAddDialog", async () => (await import("./CloudAddDialog")).CloudAddDialog);@@ -91,7 +92,7 @@ export const TeamLibraryPanel = lazyScreen("TeamLibraryPanel", async () => (awai// Most opened first: a Cloud page fetches these in this order.const SCREENS = [SettingsModal, BotSettingsDialog, PluginsPanel, ComputerPanel, TriggersPage, ActivityPanel, FilesView, InspectorPanel, KeyboardShortcutsModal,- LocalVmWorkspace, NewBotDialog, RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, TeamMapPage,+ LocalVmWorkspace, NewBotDialog, RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, TeamMapPage, PublishedAppsPage,];if (typeof location !== "undefined" && new URLSearchParams(location.search).has("desktop-settings")) {diff --git a/src/components/published-apps/AppPreviewPanel.tsx b/src/components/published-apps/AppPreviewPanel.tsxnew file mode 100644index 0000000000..ade0c70b2c--- /dev/null+++ b/src/components/published-apps/AppPreviewPanel.tsx@@ -0,0 +1,66 @@+import { useEffect, useRef, useState } from "react";+import { ExternalLink, RotateCw, X } from "lucide-react";++import { useCaptionChrome } from "@/components/DesktopCapabilities";+import { openExternalLink } from "@/lib/app-links";+import { closeAppPreview, useAppPreview } from "@/lib/app-preview";+import { t } from "@/lib/i18n";+import { useStore } from "@/state/store";+import { PANEL_MAX_WIDTH, PANEL_MIN_WIDTH, useComputerPanelResize } from "../computer-panel-resize";+import { SiteFrame } from "./SiteFrame";++/** The published app a card's Preview or a link in a message opened, beside the conversation where the Computer panel+ * sits. One panel has that side at a time: it gives way when another one opens. */+export function AppPreviewPanel() {+ const preview = useAppPreview();+ const { state } = useStore();+ const otherPanel = state.computerOpen || state.settingsOpen || state.inspectorOpen || state.activityOpen;+ const hadOtherPanel = useRef(otherPanel);+ useEffect(() => {+ if (otherPanel && !hadOtherPanel.current) closeAppPreview();+ hadOtherPanel.current = otherPanel;+ }, [otherPanel]);+ if (!preview || otherPanel || state.activeView !== "chat") return null;+ return <PreviewPanel key={preview.url} url={preview.url} title={preview.title} loginOnly={preview.loginOnly === true} />;+}++function PreviewPanel({ url, title, loginOnly }: { url: string; title: string; loginOnly: boolean }) {+ const { dragProps } = useCaptionChrome();+ const { panelWidth, separatorRef, separatorWidth, onSeparatorKeyDown, onResizeStart, onResizeMove, onResizeEnd } = useComputerPanelResize();+ const [attempt, setAttempt] = useState(0);+ const [dragging, setDragging] = useState(false);+ return (+ <aside aria-label={t("publishedApps.preview.aria", { name: title })} data-app-preview={url} style={{ width: panelWidth }}+ className="animate-panel-in relative flex h-full shrink-0 flex-col border-l border-hairline/40 bg-panel max-md:absolute max-md:inset-0 max-md:z-40 max-md:w-full!">+ <div+ ref={separatorRef}+ role="separator"+ aria-orientation="vertical"+ aria-label={t("computer.resizeAria")}+ aria-valuemin={PANEL_MIN_WIDTH}+ aria-valuemax={PANEL_MAX_WIDTH}+ aria-valuenow={separatorWidth ?? undefined}+ tabIndex={0}+ onKeyDown={onSeparatorKeyDown}+ onPointerDown={(event) => { setDragging(true); onResizeStart(event); }}+ onPointerMove={onResizeMove}+ onPointerUp={(event) => { setDragging(false); onResizeEnd(event); }}+ onPointerCancel={(event) => { setDragging(false); onResizeEnd(event); }}+ className="absolute inset-y-0 left-0 z-10 w-1.5 cursor-col-resize hover:bg-accent/40 focus-visible:bg-accent/60 max-md:hidden"+ />+ <header {...dragProps} className="ml-1.5 flex items-center gap-1 py-2.5 pl-2.5 pr-3">+ <div className="min-w-0 flex-1">+ <h2 dir="auto" className="truncate text-[14px] font-semibold text-ink">{title}</h2>+ <p dir="ltr" className="truncate text-[12px] text-ink-secondary" title={url}>{new URL(url).host}</p>+ </div>+ <button type="button" className="ui-icon-button shrink-0" aria-label={t("webPanels.page.reload")} title={t("webPanels.page.reload")} onClick={() => setAttempt((n) => n + 1)}><RotateCw size={16} /></button>+ <button type="button" className="ui-icon-button shrink-0" aria-label={t("webPanels.page.openInBrowser")} title={t("webPanels.page.openInBrowser")} onClick={() => void openExternalLink(url).catch(() => undefined)}><ExternalLink size={16} /></button>+ <button type="button" className="ui-icon-button shrink-0" aria-label={t("publishedApps.preview.close")} title={t("publishedApps.preview.close")} onClick={closeAppPreview}><X size={18} /></button>+ </header>+ {/* A cross-origin frame swallows the pointer, so the resize drag would stop the moment it crossed the site. */}+ <div className={dragging ? "pointer-events-none flex min-h-0 flex-1 flex-col" : "flex min-h-0 flex-1 flex-col"}>+ <SiteFrame url={url} title={title} loginOnly={loginOnly} attempt={attempt} />+ </div>+ </aside>+ );+}diff --git a/src/components/published-apps/PublishedAppCard.tsx b/src/components/published-apps/PublishedAppCard.tsxnew file mode 100644index 0000000000..60a1b8a2cf--- /dev/null+++ b/src/components/published-apps/PublishedAppCard.tsx@@ -0,0 +1,82 @@+import { useState } from "react";+import { ArrowUpRight, Check, Copy, Eye, MessageSquare, Settings2, Trash2 } from "lucide-react";++import type { PublishedApp } from "../../../shared/published-apps";+import { useCopyFeedback } from "@/lib/copy-text";+import { t } from "@/lib/i18n";+import type { LocaleKey } from "@/locales";+import { relativeTime } from "@/lib/memory";+import { ConfirmDialog } from "../ConfirmDialog";+import { SiteThumb } from "./SiteThumb";++const ACCESS: Record<PublishedApp["access"], LocaleKey | null> = {+ public: "publishedApps.access.public", "netlify-team": "publishedApps.access.netlifyTeam", link: "publishedApps.access.link", unknown: null,+};++export type DeleteProblem = { text: string; manageUrl?: string };++export function PublishedAppCard({ app, onOpen, onPreview, onAsk, onDelete }: {+ app: PublishedApp;+ onOpen: (url: string) => void;+ onPreview: () => void;+ /** Absent when the bot is gone. */+ onAsk?: () => void;+ /** Resolves with what went wrong, or null once the app is deleted. */+ onDelete: () => Promise<DeleteProblem | null>;+}) {+ const { state: copied, copy } = useCopyFeedback(app.url);+ const [confirming, setConfirming] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const [problem, setProblem] = useState<DeleteProblem | null>(null);+ const access = ACCESS[app.access];+ const facts = [app.bot.name, relativeTime(app.publishedAt)].filter(Boolean).join(" · ");+ const confirmDelete = async () => {+ setDeleting(true);+ const failed = await onDelete();+ setDeleting(false);+ setConfirming(false);+ setProblem(failed);+ };+ const icon = "ui-icon-button shrink-0 hover:bg-raised hover:text-ink";+ return (+ <li data-published-app={app.id} data-source={app.source} className="flex flex-col overflow-hidden rounded-2xl border border-hairline/40 bg-card">+ <button type="button" onClick={onPreview} aria-label={t("publishedApps.card.previewOf", { name: app.title })} className="block w-full border-b border-hairline/30 text-left focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus">+ <SiteThumb url={app.url} title={app.title} loginOnly={app.access === "netlify-team"} />+ </button>+ <div className="flex min-w-0 flex-1 flex-col gap-2 p-3.5">+ <div className="min-w-0">+ <h2 dir="auto" className="truncate text-[15px] font-semibold text-ink" title={app.title}>{app.title}</h2>+ <p dir="auto" className="mt-0.5 truncate text-[13px] text-ink-secondary">{facts}</p>+ {access && <p data-app-access={app.access} className="mt-1.5 inline-block rounded-full bg-inset px-2 py-0.5 text-[12px] text-ink-secondary">{t(access)}</p>}+ </div>+ <div className="mt-auto flex flex-wrap items-center gap-1.5 pt-1">+ <button type="button" className="ui-button ui-button-md" onClick={onPreview}><Eye size={14} aria-hidden="true" />{t("publishedApps.card.preview")}</button>+ <button type="button" className="ui-button ui-button-md" onClick={() => onOpen(app.url)}><ArrowUpRight size={14} aria-hidden="true" />{t("chat.page.open")}</button>+ <span className="ml-auto flex items-center">+ <button type="button" className={icon} onClick={copy} aria-label={t("chat.page.copyLink")} title={t(copied === "copied" ? "chat.page.copied" : "chat.page.copyLink")}>+ {copied === "copied" ? <Check size={15} /> : <Copy size={15} />}+ </button>+ {onAsk && <button type="button" className={icon} onClick={onAsk} aria-label={t("publishedApps.card.ask", { bot: app.bot.name })} title={t("publishedApps.card.ask", { bot: app.bot.name })}><MessageSquare size={15} /></button>}+ {app.manageUrl && <button type="button" className={icon} onClick={() => onOpen(app.manageUrl!)} aria-label={t("publishedApps.card.manage")} title={t("publishedApps.card.manage")}><Settings2 size={15} /></button>}+ {app.canDelete && <button type="button" className={`${icon} hover:text-danger`} onClick={() => { setProblem(null); setConfirming(true); }} aria-label={t("publishedApps.card.delete", { name: app.title })} title={t("common.delete")}><Trash2 size={15} /></button>}+ </span>+ </div>+ {problem && (+ <p role="alert" className="text-[12px] leading-snug text-danger">+ {problem.text}{" "}+ {problem.manageUrl && <button type="button" className="font-medium underline underline-offset-2" onClick={() => onOpen(problem.manageUrl!)}>{t("publishedApps.card.manage")}</button>}+ </p>+ )}+ </div>+ <ConfirmDialog+ open={confirming}+ title={t("publishedApps.delete.title", { name: app.title })}+ body={t("publishedApps.delete.body")}+ confirmLabel={t("common.delete")}+ pending={deleting}+ onCancel={() => { if (!deleting) setConfirming(false); }}+ onConfirm={() => void confirmDelete()}+ />+ </li>+ );+}diff --git a/src/components/published-apps/PublishedAppsPage.test.ts b/src/components/published-apps/PublishedAppsPage.test.tsnew file mode 100644index 0000000000..b155f6b9c7--- /dev/null+++ b/src/components/published-apps/PublishedAppsPage.test.ts@@ -0,0 +1,211 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { PublishedApp } from "../../../shared/published-apps";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const fixture = vi.hoisted(() => ({+ state: {+ bots: [{ id: "mira", name: "Mira", threadId: "main", tasks: [{ threadId: "main" }, { threadId: "ada-chat" }] }],+ groups: [{ id: "launch", threadId: "room-thread", tasks: [] }],+ },+ dispatch: vi.fn(),+ api: vi.fn(),+ opened: [] as string[],+ previews: [] as unknown[],+}));+class FakeApiError extends Error {+ status: number; body?: Record<string, unknown>;+ constructor(message: string, status: number, body?: Record<string, unknown>) { super(message); this.status = status; this.body = body; }+}+vi.mock("@/state/store", () => ({ useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch }) }));+vi.mock("@/state/api", () => ({ api: fixture.api, ApiError: FakeApiError }));+vi.mock("@/lib/app-links", () => ({ openExternalLink: async (url: string) => { fixture.opened.push(url); } }));+vi.mock("@/lib/app-preview", () => ({ openAppPreview: (preview: unknown) => { fixture.previews.push(preview); }, closeAppPreview: () => {}, useAppPreview: () => null }));++const { chatFor, PublishedAppsPage } = await import("./PublishedAppsPage");++const NOW = Date.parse("2026-11-11T12:00:00Z");+const SITE: PublishedApp = {+ id: "netlify-mira-s1", source: "netlify", title: "Bakery order page", url: "https://bright-bakery.netlify.app/", bot: { id: "mira", name: "Mira" }, threadId: "ada-chat",+ publishedAt: NOW - 2 * 3_600_000, access: "public", manageUrl: "https://app.netlify.com/projects/bright-bakery", canDelete: true,+};+const PAGE: PublishedApp = {+ id: "page-abcdefghijklmnopqrstuvwxyz", source: "page", title: "Sales report", url: "https://abcdefghijklmnopqrstuvwxyz.mausbot.page/", bot: { id: "mira", name: "Mira" }, threadId: "main",+ publishedAt: NOW - 3 * 86_400_000, access: "link", canDelete: true,+};+const TEAM_ONLY: PublishedApp = { ...SITE, id: "netlify-mira-s2", title: "Staff rota", url: "https://staff-rota.netlify.app/", access: "netlify-team", canDelete: false, threadId: "room-thread" };+const ORPHAN: PublishedApp = { ...PAGE, id: "page-orphan00000000000000000", title: "Old page", bot: { id: "gone", name: "" }, threadId: "gone-thread" };++let root: Root;+let host: HTMLElement;+let apps: PublishedApp[];+let deleteAnswer: () => Promise<unknown>;+const deletes: string[] = [];++beforeEach(() => {+ vi.useFakeTimers({ now: NOW, toFake: ["Date"] });+ apps = [SITE, PAGE, TEAM_ONLY, ORPHAN];+ deleteAnswer = async () => ({ ok: true });+ deletes.length = 0;+ fixture.opened.length = 0;+ fixture.previews.length = 0;+ fixture.dispatch.mockReset();+ fixture.api.mockReset();+ fixture.api.mockImplementation(async (path: string, init?: { method?: string; body?: string }) => {+ if (path === "/api/published-apps") return { apps };+ if (path === "/api/published-apps/delete" && init?.method === "POST") {+ const { id } = JSON.parse(init.body!) as { id: string };+ deletes.push(id);+ const answer = await deleteAnswer();+ apps = apps.filter((app) => app.id !== id);+ return answer;+ }+ if (path.startsWith("/api/published-apps/framing")) return { framing: "allowed" };+ throw new Error(`unexpected ${path}`);+ });+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => { act(() => root.unmount()); host.remove(); vi.useRealTimers(); });++const show = () => act(async () => root.render(createElement(PublishedAppsPage)));+const card = (id: string) => host.querySelector<HTMLElement>(`[data-published-app="${id}"]`)!;+const button = (within: ParentNode, name: string) => [...within.querySelectorAll("button")].find((one) => (one.getAttribute("aria-label") ?? one.textContent) === name)!;+const dialog = () => document.body.querySelector<HTMLElement>('[role="alertdialog"]');++describe("the Published apps page", () => {+ it("says what it is for and how to get the first app when nothing is published", async () => {+ apps = [];+ await show();+ expect(host.querySelector("h1")?.textContent).toBe("Published apps");+ expect(host.textContent).toContain("Nothing published yet");+ expect(host.textContent).toContain("Ask a bot to build a site or app and publish it.");+ expect(host.querySelector("[data-published-app]")).toBeNull();+ });++ it("shows one card for each app from both sources, with its name, bot, when it was published and who can see it", async () => {+ await show();+ expect([...host.querySelectorAll("[data-published-app]")].map((one) => `${one.getAttribute("data-source")}:${one.querySelector("h2")?.textContent}`))+ .toEqual(["netlify:Bakery order page", "page:Sales report", "netlify:Staff rota", "page:Old page"]);+ expect(card(SITE.id).textContent).toContain("Mira · 2 hr ago");+ expect(card(SITE.id).querySelector("[data-app-access]")?.textContent).toBe("Public");+ expect(card(TEAM_ONLY.id).querySelector("[data-app-access]")?.textContent).toBe("Only your Netlify team");+ expect(card(PAGE.id).querySelector("[data-app-access]")?.textContent).toBe("Anyone with the link");+ expect(card(PAGE.id).textContent).toContain("Mira · 3 days ago");+ });++ it("offers Manage on Netlify only for a Netlify site, Delete only where the viewer may, and no chat for a bot that is gone", async () => {+ await show();+ const labels = (id: string) => [...card(id).querySelectorAll("button")].map((one) => one.getAttribute("aria-label") ?? one.textContent);+ expect(labels(SITE.id)).toEqual(["Preview Bakery order page", "Preview", "Open", "Copy link", "Ask Mira to change it", "Manage on Netlify", "Delete Bakery order page"]);+ expect(labels(PAGE.id)).toEqual(["Preview Sales report", "Preview", "Open", "Copy link", "Ask Mira to change it", "Delete Sales report"]);+ expect(labels(TEAM_ONLY.id)).toEqual(["Preview Staff rota", "Preview", "Open", "Copy link", "Ask Mira to change it", "Manage on Netlify"]);+ expect(labels(ORPHAN.id)).toEqual(["Preview Old page", "Preview", "Open", "Copy link", "Delete Old page"]);+ });++ it("opens the app and its Netlify page outside the app, and copies its link", async () => {+ const writeText = vi.fn(async () => {});+ vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });+ await show();+ act(() => button(card(SITE.id), "Open").click());+ act(() => button(card(SITE.id), "Manage on Netlify").click());+ expect(fixture.opened).toEqual([SITE.url, SITE.manageUrl]);+ await act(async () => button(card(SITE.id), "Copy link").click());+ expect(writeText).toHaveBeenCalledWith(SITE.url);+ vi.unstubAllGlobals();+ });++ it("opens the bot's conversation about the app from Ask, and the room for one published in a room", async () => {+ await show();+ act(() => button(card(SITE.id), "Ask Mira to change it").click());+ act(() => button(card(TEAM_ONLY.id), "Ask Mira to change it").click());+ expect(fixture.dispatch.mock.calls.map(([action]) => action)).toEqual([{ type: "switchTask", botId: "mira", threadId: "ada-chat" }, { type: "select", id: "launch" }]);+ expect(chatFor({ ...SITE, threadId: undefined }, fixture.state as never)).toEqual({ type: "select", id: "mira" });+ expect(chatFor({ ...SITE, threadId: "someone-elses" }, fixture.state as never)).toEqual({ type: "select", id: "mira" });+ expect(chatFor(ORPHAN, fixture.state as never)).toBeNull();+ });++ it("opens the preview beside that bot's conversation, in place of any other side panel", async () => {+ await show();+ act(() => button(card(SITE.id), "Preview").click());+ expect(fixture.dispatch.mock.calls.map(([action]) => action)).toEqual([+ { type: "switchTask", botId: "mira", threadId: "ada-chat" },+ { type: "toggleComputer", open: false }, { type: "toggleSettings", open: false }, { type: "toggleInspector", open: false }, { type: "toggleActivity", open: false },+ ]);+ expect(fixture.previews).toEqual([{ url: SITE.url, title: "Bakery order page" }]);+ act(() => button(card(TEAM_ONLY.id), "Preview Staff rota").click());+ expect(fixture.previews[1]).toEqual({ url: TEAM_ONLY.url, title: "Staff rota", loginOnly: true });+ fixture.dispatch.mockReset();+ act(() => button(card(ORPHAN.id), "Preview").click());+ expect(fixture.dispatch.mock.calls[0]![0]).toEqual({ type: "showChat" });+ });++ it("deletes only after a confirmation that names the app and says the link stops working for everyone for good", async () => {+ await show();+ act(() => button(card(SITE.id), "Delete Bakery order page").click());+ expect(dialog()?.textContent).toContain("Delete “Bakery order page”?");+ expect(dialog()?.textContent).toContain("Its link will stop working for everyone. This can't be undone.");+ expect(document.activeElement?.textContent).toBe("Cancel");+ act(() => button(dialog()!, "Cancel").click());+ expect(dialog()).toBeNull();+ expect(deletes).toEqual([]);++ act(() => button(card(SITE.id), "Delete Bakery order page").click());+ await act(async () => button(dialog()!, "Delete").click());+ expect(deletes).toEqual([SITE.id]);+ expect(dialog()).toBeNull();+ expect(host.querySelector(`[data-published-app="${SITE.id}"]`)).toBeNull();+ expect(host.querySelectorAll("[data-published-app]")).toHaveLength(3);+ });++ it("says why a Netlify site could not be deleted from here and offers Manage on Netlify, keeping the card", async () => {+ deleteAnswer = async () => { throw new FakeApiError("No saved Netlify token", 409, { error: "No saved Netlify token", code: "no_token", manageUrl: SITE.manageUrl }); };+ await show();+ act(() => button(card(SITE.id), "Delete Bakery order page").click());+ await act(async () => button(dialog()!, "Delete").click());+ const alert = card(SITE.id).querySelector('[role="alert"]')!;+ expect(alert.textContent).toContain("This app can't be deleted from here: there is no saved Netlify token to use. Delete it on Netlify instead.");+ act(() => button(alert, "Manage on Netlify").click());+ expect(fixture.opened).toEqual([SITE.manageUrl]);+ expect(host.querySelectorAll("[data-published-app]")).toHaveLength(4);+ });++ it("never offers a Manage link the list did not give, and says plainly when a delete is refused or fails", async () => {+ await show();+ for (const [code, text] of [["token_refused", "Netlify refused the saved token"], ["forbidden", "This app isn't yours to delete."], ["failed", "This app couldn't be deleted. Try again."], ["surprise", "This app couldn't be deleted. Try again."]] as const) {+ deleteAnswer = async () => { throw new FakeApiError("x", 409, { code, manageUrl: "https://evil.test/login" }); };+ act(() => button(card(SITE.id), "Delete Bakery order page").click());+ await act(async () => button(dialog()!, "Delete").click());+ const alert = card(SITE.id).querySelector('[role="alert"]')!;+ expect(alert.textContent, code).toContain(text);+ expect(alert.querySelector("button"), code).toBeNull();+ }+ });++ it("drops a card whose app was already gone", async () => {+ deleteAnswer = async () => { apps = apps.filter((app) => app.id !== PAGE.id); throw new FakeApiError("No such published app.", 404, { code: "gone" }); };+ await show();+ act(() => button(card(PAGE.id), "Delete Sales report").click());+ await act(async () => button(dialog()!, "Delete").click());+ expect(host.querySelector(`[data-published-app="${PAGE.id}"]`)).toBeNull();+ });++ it("says the list could not be loaded and loads it on Try again", async () => {+ fixture.api.mockRejectedValueOnce(new Error("offline"));+ await show();+ expect(host.querySelector('[role="alert"]')?.textContent).toContain("Your published apps couldn't be loaded.");+ await act(async () => button(host, "Try again").click());+ expect(host.querySelectorAll("[data-published-app]")).toHaveLength(4);+ });++ it("goes back to the chat from the header's Back", async () => {+ await show();+ act(() => button(host, "Back").click());+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "showChat" });+ });+});diff --git a/src/components/published-apps/PublishedAppsPage.tsx b/src/components/published-apps/PublishedAppsPage.tsxnew file mode 100644index 0000000000..4fd3ff9f72--- /dev/null+++ b/src/components/published-apps/PublishedAppsPage.tsx@@ -0,0 +1,108 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { Globe } from "lucide-react";++import type { PublishedApp, PublishedAppDeleteRefusal, PublishedAppsList } from "../../../shared/published-apps";+import { openExternalLink } from "@/lib/app-links";+import { t } from "@/lib/i18n";+import type { LocaleKey } from "@/locales";+import { showAppBesideChat } from "@/lib/page-open";+import { rememberPublishedApps } from "@/lib/published-apps";+import { api, ApiError } from "@/state/api";+import { useStore, type AppState } from "@/state/store";+import { TOOL_PAGE_TITLE, ToolPage, ToolPageHeader } from "../ToolPageShell";+import { PublishedAppCard, type DeleteProblem } from "./PublishedAppCard";++const DELETE_PROBLEMS: Record<PublishedAppDeleteRefusal, LocaleKey> = {+ gone: "publishedApps.delete.failed", failed: "publishedApps.delete.failed", forbidden: "publishedApps.delete.forbidden",+ no_token: "publishedApps.delete.noToken", token_refused: "publishedApps.delete.tokenRefused",+};++/** Where the bot's chat about this app opens: the conversation it was published in when the bot still has it, else+ * the bot's chat, else the room that conversation belongs to. Null when the bot and the room are gone. */+export function chatFor(app: PublishedApp, state: Pick<AppState, "bots" | "groups">): { type: "switchTask"; botId: string; threadId: string } | { type: "select"; id: string } | null {+ const bot = state.bots.find((candidate) => candidate.id === app.bot.id);+ const holds = (owner: { threadId: string; tasks?: ReadonlyArray<{ threadId: string }> }) => owner.threadId === app.threadId || (owner.tasks ?? []).some((task) => task.threadId === app.threadId);+ if (bot && app.threadId && holds(bot)) return { type: "switchTask", botId: bot.id, threadId: app.threadId };+ const room = app.threadId ? state.groups.find(holds) : undefined;+ return room ? { type: "select", id: room.id } : bot ? { type: "select", id: bot.id } : null;+}++/** Everything the person's bots put online, as cards. */+export function PublishedAppsPage() {+ const { state, dispatch } = useStore();+ const [apps, setApps] = useState<PublishedApp[] | null>(null);+ const [failed, setFailed] = useState(false);+ const back = useRef<HTMLButtonElement>(null);+ const loading = useRef<AbortController | null>(null);++ const load = useCallback(async () => {+ loading.current?.abort();+ const controller = new AbortController();+ loading.current = controller;+ try {+ const list = await api<PublishedAppsList>("/api/published-apps", { signal: controller.signal });+ if (controller.signal.aborted) return;+ rememberPublishedApps(list.apps);+ setApps(list.apps);+ setFailed(false);+ } catch {+ if (!controller.signal.aborted) setFailed(true);+ }+ }, []);+ useEffect(() => { void load(); return () => loading.current?.abort(); }, [load]);+ useEffect(() => { back.current?.focus({ preventScroll: true }); }, []);++ const open = (url: string) => void openExternalLink(url).catch(() => undefined);+ const openChat = (app: PublishedApp): boolean => {+ const action = chatFor(app, state);+ if (action) dispatch(action);+ return action !== null;+ };+ const preview = (app: PublishedApp) => {+ if (!openChat(app)) dispatch({ type: "showChat" });+ showAppBesideChat(dispatch, { url: app.url, title: app.title, ...(app.access === "netlify-team" ? { loginOnly: true } : {}) });+ };+ const remove = async (app: PublishedApp): Promise<DeleteProblem | null> => {+ try {+ await api("/api/published-apps/delete", { method: "POST", body: JSON.stringify({ id: app.id }) });+ } catch (error) {+ const body = error instanceof ApiError ? error.body : undefined;+ const code = typeof body?.code === "string" && Object.hasOwn(DELETE_PROBLEMS, body.code) ? body.code as PublishedAppDeleteRefusal : "failed";+ if (code !== "gone") return { text: t(DELETE_PROBLEMS[code]), ...(typeof body?.manageUrl === "string" && body.manageUrl === app.manageUrl ? { manageUrl: app.manageUrl } : {}) };+ }+ setApps((current) => current?.filter((one) => one.id !== app.id) ?? current);+ void load();+ return null;+ };++ return (+ <ToolPage label={t("publishedApps.title")}>+ <ToolPageHeader backLabel={t("automations.back")} onBack={() => dispatch({ type: "showChat" })} backRef={back}>+ <h1 className={TOOL_PAGE_TITLE}>{t("publishedApps.title")}</h1>+ </ToolPageHeader>+ <div className="min-h-0 flex-1 overflow-y-auto" data-published-apps={apps ? apps.length : "loading"}>+ <div className="mx-auto w-full max-w-5xl p-4 sm:p-6">+ {failed && !apps ? (+ <section role="alert" className="px-6 py-16 text-center">+ <p className="text-[14px] text-ink-secondary">{t("publishedApps.loadFailed")}</p>+ <button type="button" className="ui-button mt-4" onClick={() => void load()}>{t("common.tryAgain")}</button>+ </section>+ ) : apps && apps.length === 0 ? (+ <section aria-label={t("publishedApps.empty.title")} className="px-6 py-16 text-center">+ <div className="mx-auto mb-4 flex size-12 items-center justify-center rounded-2xl bg-accent/10 text-accent"><Globe size={22} /></div>+ <h2 className="text-[17px] font-semibold text-ink">{t("publishedApps.empty.title")}</h2>+ <p className="mx-auto mt-2 max-w-sm text-[14px] leading-relaxed text-ink-secondary">{t("publishedApps.empty.body")}</p>+ </section>+ ) : apps ? (+ <ul aria-label={t("publishedApps.title")} className="grid grid-cols-[repeat(auto-fill,minmax(min(340px,100%),1fr))] gap-4">+ {apps.map((app) => (+ <PublishedAppCard key={app.id} app={app} onOpen={open} onPreview={() => preview(app)}+ onAsk={app.bot.name && chatFor(app, state) ? () => void openChat(app) : undefined} onDelete={() => remove(app)} />+ ))}+ </ul>+ ) : null}+ </div>+ </div>+ </ToolPage>+ );+}diff --git a/src/components/published-apps/SiteFrame.tsx b/src/components/published-apps/SiteFrame.tsxnew file mode 100644index 0000000000..e727017614--- /dev/null+++ b/src/components/published-apps/SiteFrame.tsx@@ -0,0 +1,47 @@+import { useEffect, useState } from "react";++import { openExternalLink } from "@/lib/app-links";+import { t } from "@/lib/i18n";+import { showable, SITE_FRAME_ALLOW, SITE_FRAME_SANDBOX } from "@/lib/published-apps";+import { useFramingRefused } from "./use-framing";++const LOAD_TIMEOUT_MS = 10_000;++/** A published site, live, in a sandboxed frame; or, when it can't be shown here (it refuses framing, asks for a login,+ * never loads, or is not a plain web address), a line saying so and Open in browser. */+export function SiteFrame({ url, title, loginOnly = false, attempt }: { url: string; title: string; loginOnly?: boolean; attempt: number }) {+ const canFrame = showable(url, window.location.origin) && !loginOnly;+ const refused = useFramingRefused(canFrame ? url : null, attempt);+ const [timedOut, setTimedOut] = useState(false);+ const [loaded, setLoaded] = useState(false);++ useEffect(() => {+ setTimedOut(false);+ setLoaded(false);+ const timer = setTimeout(() => setTimedOut(true), LOAD_TIMEOUT_MS);+ return () => clearTimeout(timer);+ }, [url, attempt]);++ if (!canFrame || refused || (timedOut && !loaded)) {+ return (+ <div data-app-preview-fallback="" className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-6 text-center">+ <p className="text-[14px] font-medium text-ink">{t("publishedApps.preview.cantShow")}</p>+ <p className="max-w-sm text-[13px] text-ink-secondary">{t(loginOnly ? "publishedApps.preview.loginBody" : "publishedApps.preview.cantShowBody")}</p>+ <button type="button" className="ui-button ui-button-primary" onClick={() => void openExternalLink(url).catch(() => undefined)}>{t("webPanels.page.openInBrowser")}</button>+ </div>+ );+ }+ return (+ <iframe+ key={`${url}:${attempt}`}+ data-app-preview-frame=""+ src={url}+ title={title}+ sandbox={SITE_FRAME_SANDBOX}+ allow={SITE_FRAME_ALLOW}+ referrerPolicy="no-referrer"+ onLoad={() => setLoaded(true)}+ className="min-h-0 w-full flex-1 border-0 bg-white"+ />+ );+}diff --git a/src/components/published-apps/SiteThumb.tsx b/src/components/published-apps/SiteThumb.tsxnew file mode 100644index 0000000000..0563777cb1--- /dev/null+++ b/src/components/published-apps/SiteThumb.tsx@@ -0,0 +1,58 @@+import { useEffect, useRef, useState } from "react";++import { appInitial, showable, SITE_FRAME_ALLOW, SITE_THUMB_SANDBOX } from "@/lib/published-apps";+import { useFramingRefused } from "./use-framing";++const SITE_WIDTH = 1280, SITE_HEIGHT = 800;+const LOAD_TIMEOUT_MS = 12_000;++/** A card's picture: the live site drawn small, loaded only once the card is on screen and never taking a click or+ * the keyboard; until it has loaded, and whenever it can't be shown, a plain tile with the app's initial. */+export function SiteThumb({ url, title, loginOnly }: { url: string; title: string; loginOnly: boolean }) {+ const box = useRef<HTMLDivElement>(null);+ const [onScreen, setOnScreen] = useState(false);+ const [scale, setScale] = useState(0.25);+ const [loaded, setLoaded] = useState(false);+ const [gaveUp, setGaveUp] = useState(false);+ const canFrame = showable(url, window.location.origin) && !loginOnly;+ const refused = useFramingRefused(canFrame && onScreen ? url : null);++ useEffect(() => {+ const element = box.current;+ if (!element) return;+ const size = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => setScale(element.clientWidth / SITE_WIDTH));+ size?.observe(element);+ if (typeof IntersectionObserver === "undefined") { setOnScreen(true); return () => size?.disconnect(); }+ const seen = new IntersectionObserver((entries) => { if (entries.some((entry) => entry.isIntersecting)) { setOnScreen(true); seen.disconnect(); } }, { rootMargin: "200px" });+ seen.observe(element);+ return () => { size?.disconnect(); seen.disconnect(); };+ }, []);++ const framed = canFrame && onScreen && !refused && !gaveUp;+ useEffect(() => {+ if (!framed || loaded) return;+ const timer = setTimeout(() => setGaveUp(true), LOAD_TIMEOUT_MS);+ return () => clearTimeout(timer);+ }, [framed, loaded]);++ return (+ <div ref={box} data-app-thumb={framed && loaded ? "live" : "tile"} className="relative aspect-[16/10] w-full overflow-hidden bg-inset">+ <div aria-hidden="true" className="absolute inset-0 flex items-center justify-center text-[44px] font-semibold text-ink-tertiary">{appInitial(title)}</div>+ {framed && (+ <iframe+ src={url}+ title=""+ aria-hidden="true"+ tabIndex={-1}+ loading="lazy"+ sandbox={SITE_THUMB_SANDBOX}+ allow={SITE_FRAME_ALLOW}+ referrerPolicy="no-referrer"+ onLoad={() => setLoaded(true)}+ style={{ width: SITE_WIDTH, height: SITE_HEIGHT, transform: `scale(${scale})`, transformOrigin: "0 0", opacity: loaded ? 1 : 0 }}+ className="pointer-events-none absolute left-0 top-0 select-none border-0 bg-white transition-opacity duration-300"+ />+ )}+ </div>+ );+}diff --git a/src/components/published-apps/preview.security.test.ts b/src/components/published-apps/preview.security.test.tsnew file mode 100644index 0000000000..79f0dfa2ac--- /dev/null+++ b/src/components/published-apps/preview.security.test.ts@@ -0,0 +1,207 @@+// @vitest-environment happy-dom+import { readFileSync } from "node:fs";+import { resolve } from "node:path";+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const fixture = vi.hoisted(() => ({+ state: { computerOpen: false, settingsOpen: false, inspectorOpen: false, activityOpen: false, activeView: "chat" },+ api: vi.fn(async (_path: string, _init?: unknown): Promise<unknown> => ({ framing: "allowed" })),+ opened: [] as string[],+}));+vi.mock("@/state/store", () => ({ useStore: () => ({ state: fixture.state, dispatch: () => {} }) }));+vi.mock("@/state/api", () => ({ api: fixture.api }));+vi.mock("@/lib/app-links", () => ({ openExternalLink: async (url: string) => { fixture.opened.push(url); } }));++const { closeAppPreview, openAppPreview } = await import("@/lib/app-preview");+const { SITE_FRAME_ALLOW, SITE_FRAME_SANDBOX, SITE_THUMB_SANDBOX, showable } = await import("@/lib/published-apps");+const { AppPreviewPanel } = await import("./AppPreviewPanel");+const { SiteFrame } = await import("./SiteFrame");+const { SiteThumb } = await import("./SiteThumb");++const SITE = "https://bright-bakery.netlify.app/";+const source = (file: string) => readFileSync(resolve(process.cwd(), file), "utf8");+let root: Root;+let host: HTMLElement;+beforeEach(() => {+ fixture.api.mockReset();+ fixture.api.mockResolvedValue({ framing: "allowed" });+ fixture.opened.length = 0;+ Object.assign(fixture.state, { computerOpen: false, settingsOpen: false, inspectorOpen: false, activityOpen: false, activeView: "chat" });+ // happy-dom's observer never reports, so every card counts as on screen.+ vi.stubGlobal("IntersectionObserver", undefined);+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => { act(() => { closeAppPreview(); root.unmount(); }); host.remove(); vi.useRealTimers(); vi.unstubAllGlobals(); });++const frame = (props: { url: string; loginOnly?: boolean }) => act(async () => root.render(createElement(SiteFrame, { title: "Bakery", attempt: 0, ...props })));+const tokens = (value: string | null) => (value ?? "").split(/\s+/).filter(Boolean).sort();++describe("the sandbox a published site runs in", () => {+ it("gives the preview scripts, its own origin, forms and new tabs, and nothing that reaches the window around it", async () => {+ await frame({ url: SITE });+ const iframe = host.querySelector("iframe")!;+ expect(tokens(iframe.getAttribute("sandbox"))).toEqual(["allow-forms", "allow-popups", "allow-same-origin", "allow-scripts"]);+ for (const reach of ["allow-top-navigation", "allow-top-navigation-by-user-activation", "allow-top-navigation-to-custom-protocols", "allow-popups-to-escape-sandbox",+ "allow-downloads", "allow-modals", "allow-pointer-lock", "allow-presentation", "allow-storage-access-by-user-activation", "allow-orientation-lock"]) {+ expect(SITE_FRAME_SANDBOX, reach).not.toContain(reach);+ expect(SITE_THUMB_SANDBOX, reach).not.toContain(reach);+ }+ expect(iframe.getAttribute("src")).toBe(SITE);+ expect(iframe.getAttribute("referrerpolicy")).toBe("no-referrer");+ expect(iframe.hasAttribute("srcdoc")).toBe(false);+ expect(iframe.hasAttribute("name")).toBe(false);+ for (const feature of ["camera", "microphone", "geolocation", "display-capture", "clipboard-read"]) expect(iframe.getAttribute("allow")).toContain(`${feature} 'none'`);+ expect(SITE_FRAME_ALLOW).not.toMatch(/\*|'self'|'src'/);+ });++ it("gives a card's picture less still: no forms, no new tabs, no pointer, no keyboard, nothing read aloud", async () => {+ await act(async () => root.render(createElement(SiteThumb, { url: SITE, title: "Bakery", loginOnly: false })));+ const iframe = host.querySelector("iframe")!;+ expect(tokens(iframe.getAttribute("sandbox"))).toEqual(["allow-same-origin", "allow-scripts"]);+ expect(iframe.getAttribute("tabindex")).toBe("-1");+ expect(iframe.getAttribute("aria-hidden")).toBe("true");+ expect(iframe.getAttribute("loading")).toBe("lazy");+ expect(iframe.className).toContain("pointer-events-none");+ expect(iframe.getAttribute("referrerpolicy")).toBe("no-referrer");+ expect(iframe.getAttribute("allow")).toContain("camera 'none'");+ });++ it("never frames the app's own origin or anything that is not a plain web address", async () => {+ const own = window.location.origin;+ for (const url of [`${own}/`, `${own}/api/bots`, "javascript:alert(document.cookie)", "data:text/html,<script>parent.ogb</script>", "file:///etc/passwd", "blob:https://x.test/1",+ "about:srcdoc", "openmausbot://bot/pepper", "https://user:[email protected]/", "not a url", ""]) {+ expect(showable(url, own), url).toBe(false);+ await frame({ url });+ expect(host.querySelector("iframe"), url).toBeNull();+ expect(host.querySelector("[data-app-preview-fallback]"), url).not.toBeNull();+ await act(async () => root.render(createElement(SiteThumb, { url, title: "Bakery", loginOnly: false })));+ expect(host.querySelector("iframe"), url).toBeNull();+ expect(host.querySelector("[data-app-thumb]")?.getAttribute("data-app-thumb")).toBe("tile");+ }+ expect(fixture.api).not.toHaveBeenCalled();+ });++ it("hands the site no bridge: no message listener, no window name, no script of the app's in its frame", async () => {+ const listen = vi.spyOn(window, "addEventListener");+ openAppPreview({ url: SITE, title: "Bakery" });+ await act(async () => root.render(createElement(AppPreviewPanel)));+ expect(host.querySelector("iframe")).not.toBeNull();+ expect(listen.mock.calls.filter(([type]) => type === "message")).toEqual([]);+ listen.mockRestore();+ for (const file of ["SiteFrame.tsx", "SiteThumb.tsx", "AppPreviewPanel.tsx", "use-framing.ts"]) {+ const text = source(`src/components/published-apps/${file}`);+ for (const bridge of ["postMessage", "contentWindow", "contentDocument", "window.ogb", "srcDoc", "mausbot.", "<webview"]) expect(text, `${file}: ${bridge}`).not.toContain(bridge);+ }+ });++ it("runs in a window whose preload never loads into a frame and which never frames the app's own server", () => {+ const main = source("electron/main.mjs");+ const preferences = main.slice(main.indexOf('preload: path.join(__dirname, "preload.cjs")') - 200, main.indexOf('preload: path.join(__dirname, "preload.cjs")') + 600);+ expect(preferences).toContain("contextIsolation: true");+ for (const opening of ["nodeIntegrationInSubFrames", "webviewTag", "nodeIntegration: true", "contextIsolation: false", "webSecurity: false", "allowRunningInsecureContent"]) expect(main, opening).not.toContain(opening);+ expect(main).toMatch(/will-frame-navigate[\s\S]{0,700}target === rendererOrigin\(\) \|\| allowedOrigins\(environmentsState, rendererOrigin\(\)\)\.has\(target\)[\s\S]{0,80}preventDefault/);+ expect(main).toMatch(/setWindowOpenHandler\(\(\{ url \}\) => \{[\s\S]{0,300}return \{ action: "deny" \};/);+ });++ it("is the rule the app's pinned web pages already use", () => {+ const pinned = source("src/components/WebPanelPage.tsx");+ expect(pinned).toContain("sandbox={SITE_FRAME_SANDBOX}");+ expect(pinned).not.toMatch(/sandbox="/);+ });+});++describe("a site that can't be shown in the preview", () => {+ it("gets a plain line and Open in browser when it refuses to be framed", async () => {+ fixture.api.mockResolvedValue({ framing: "blocked" });+ await frame({ url: SITE });+ expect(fixture.api).toHaveBeenCalledWith(`/api/published-apps/framing?url=${encodeURIComponent(SITE)}&origin=${encodeURIComponent(window.location.origin)}`, expect.objectContaining({ background: true }));+ expect(host.querySelector("iframe")).toBeNull();+ expect(host.textContent).toContain("This app can't be shown here");+ expect(host.textContent).toContain("Some sites don't let other apps show them. Open it in your browser instead.");+ act(() => [...host.querySelectorAll("button")].find((one) => one.textContent === "Open in browser")!.click());+ expect(fixture.opened).toEqual([SITE]);+ });++ it("is not framed at all when it asks for a Netlify login", async () => {+ await frame({ url: SITE, loginOnly: true });+ expect(host.querySelector("iframe")).toBeNull();+ expect(host.textContent).toContain("This site asks for a Netlify login. Open it in your browser instead.");+ expect(fixture.api).not.toHaveBeenCalled();+ });++ it("falls back when it never loads, and stays when it did", async () => {+ vi.useFakeTimers();+ await frame({ url: SITE });+ await act(async () => { vi.advanceTimersByTime(10_500); });+ expect(host.querySelector("iframe")).toBeNull();+ expect(host.querySelector("[data-app-preview-fallback]")).not.toBeNull();++ await act(async () => root.render(createElement(SiteFrame, { url: "https://other-site.netlify.app/", title: "Other", attempt: 0 })));+ act(() => { host.querySelector("iframe")!.dispatchEvent(new Event("load")); });+ await act(async () => { vi.advanceTimersByTime(10_500); });+ expect(host.querySelector("iframe")).not.toBeNull();+ });++ it("stays a tile on the card when the site refuses framing, asks for a login or is still loading", async () => {+ const thumb = (loginOnly = false) => act(async () => root.render(createElement(SiteThumb, { url: SITE, title: " bakery", loginOnly })));+ await thumb();+ expect(host.querySelector("[data-app-thumb]")?.getAttribute("data-app-thumb")).toBe("tile");+ expect(host.textContent).toBe("B");+ act(() => { host.querySelector("iframe")!.dispatchEvent(new Event("load")); });+ expect(host.querySelector("[data-app-thumb]")?.getAttribute("data-app-thumb")).toBe("live");+ await thumb(true);+ expect(host.querySelector("iframe")).toBeNull();+ fixture.api.mockResolvedValue({ framing: "blocked" });+ act(() => root.unmount());+ root = createRoot(host);+ await thumb();+ expect(host.querySelector("iframe")).toBeNull();+ });+});++describe("the preview beside the chat", () => {+ const panel = () => act(async () => root.render(createElement(AppPreviewPanel)));+ const press = (name: string) => act(() => [...host.querySelectorAll("button")].find((one) => one.getAttribute("aria-label") === name)!.click());++ it("shows the app with its name and address, Reload, Open in browser and Close", async () => {+ await panel();+ expect(host.querySelector("aside")).toBeNull();+ act(() => openAppPreview({ url: `${SITE}menu`, title: "Bakery order page" }));+ await panel();+ const aside = host.querySelector("aside")!;+ expect(aside.getAttribute("aria-label")).toBe("Preview of Bakery order page");+ expect(aside.querySelector("h2")?.textContent).toBe("Bakery order page");+ expect(aside.textContent).toContain("bright-bakery.netlify.app");+ const first = host.querySelector("iframe")!;+ press("Reload");+ expect(host.querySelector("iframe")).not.toBe(first);+ expect(host.querySelector("iframe")?.getAttribute("src")).toBe(`${SITE}menu`);+ press("Open in browser");+ expect(fixture.opened).toEqual([`${SITE}menu`]);+ press("Close preview");+ expect(host.querySelector("aside")).toBeNull();+ });++ it("gives the side to another panel that opens, and is not shown over another page", async () => {+ act(() => openAppPreview({ url: SITE, title: "Bakery" }));+ await panel();+ expect(host.querySelector("aside")).not.toBeNull();+ fixture.state.activeView = "published-apps";+ await panel();+ expect(host.querySelector("aside")).toBeNull();+ fixture.state.activeView = "chat";+ await panel();+ expect(host.querySelector("aside")).not.toBeNull();+ fixture.state.computerOpen = true;+ await panel();+ fixture.state.computerOpen = false;+ await panel();+ expect(host.querySelector("aside")).toBeNull();+ });+});diff --git a/src/components/published-apps/use-framing.ts b/src/components/published-apps/use-framing.tsnew file mode 100644index 0000000000..9c0f72f443--- /dev/null+++ b/src/components/published-apps/use-framing.ts@@ -0,0 +1,17 @@+import { useEffect, useState } from "react";++import { api } from "@/state/api";++/** Whether the site refuses to be framed by this app, as its own headers say: the browser fires `load` on a frame it+ * refused, so nothing in the page can tell. Unknown (still asking, offline, not allowed to ask) reads as not refused. */+export function useFramingRefused(url: string | null, attempt = 0): boolean {+ const [refused, setRefused] = useState<string | null>(null);+ useEffect(() => {+ if (!url) return;+ const check = new AbortController();+ api<{ framing?: string }>(`/api/published-apps/framing?url=${encodeURIComponent(url)}&origin=${encodeURIComponent(window.location.origin)}`, { background: true, signal: check.signal })+ .then(({ framing }) => { if (!check.signal.aborted) setRefused(framing === "blocked" ? url : null); }, () => undefined);+ return () => check.abort();+ }, [url, attempt]);+ return url !== null && refused === url;+}diff --git a/src/lib/app-preview.ts b/src/lib/app-preview.tsnew file mode 100644index 0000000000..386d3af9ab--- /dev/null+++ b/src/lib/app-preview.ts@@ -0,0 +1,25 @@+import { useSyncExternalStore } from "react";++/** The published app shown beside the chat. Renderer-only: nothing about it is stored or sent anywhere. */+export interface AppPreview {+ url: string;+ title: string;+ /** The site asked for a login when last checked, so a frame would only show a sign-in it refuses to draw. */+ loginOnly?: boolean;+}++let current: AppPreview | null = null;+const listeners = new Set<() => void>();++function set(next: AppPreview | null): void {+ if (next === current) return;+ current = next;+ for (const listener of listeners) listener();+}++export const openAppPreview = (preview: AppPreview): void => set({ ...preview });+export const closeAppPreview = (): void => set(null);++export function useAppPreview(): AppPreview | null {+ return useSyncExternalStore((listener) => { listeners.add(listener); return () => { listeners.delete(listener); }; }, () => current, () => null);+}diff --git a/src/lib/page-open.ts b/src/lib/page-open.tsindex dfb765d49d..24725f344c 100644--- a/src/lib/page-open.ts+++ b/src/lib/page-open.ts@@ -1,9 +1,12 @@import { useCallback, useEffect, useRef, type MouseEvent } from "react";+import { isNetlifySiteUrl } from "../../shared/published-apps";import { PAGE_ID } from "../../shared/published-page";import type { Bot } from "@/state/store";import { useOptionalStoreRef } from "@/state/store-ref";import { openExternalLink } from "./app-links";+import { openAppPreview, type AppPreview } from "./app-preview";import { browserAvailable, builtInBrowserEnabled, type FeatureFlagConfig } from "./feature-flags";+import { knownPublishedApp, showable } from "./published-apps";export const PAGES_DOMAIN = "mausbot.page";@@ -68,29 +71,54 @@ export function usePanelPage(botId: string, open: (page: PanelPage) => void): vo}, [botId]);}+/** A link to something a bot put online: an app in the loaded Published apps list, a Netlify site's own address, or a+ * published page. */+export function publishedLink(href: string | null | undefined): AppPreview | null {+ if (typeof href !== "string") return null;+ const app = knownPublishedApp(href);+ if (app) return { url: href, title: app.title, ...(app.access === "netlify-team" ? { loginOnly: true } : {}) };+ return isNetlifySiteUrl(href) || isPublishedPageUrl(href) ? { url: href, title: new URL(href).host } : null;+}++const SIDE_PANELS = ["toggleComputer", "toggleSettings", "toggleInspector", "toggleActivity"] as const;++/** Shows a published app beside the open conversation, in place of any other panel on that side. */+export function showAppBesideChat(dispatch: (action: { type: (typeof SIDE_PANELS)[number]; open: false }) => void, preview: AppPreview): void {+ for (const type of SIDE_PANELS) dispatch({ type, open: false });+ openAppPreview(preview);+}+/** Opens a link the way a published page's Open does: a page in the bot's browser panel when the desktop app has one,- * anything else outside the chat. It never sends a message, starts a turn or opens a chat. */-export function usePageOpener(): (url: string) => void {+ * anything else outside the chat. It never sends a message, starts a turn or opens a chat. With `beside`, a link in a+ * message to something a bot put online opens in the preview beside the chat instead of leaving it. */+export function usePageOpener(options: { beside?: boolean } = {}): (url: string) => void {// Outside the app's store (a message drawn on its own) there is no panel: the page opens outside the chat.const store = useOptionalStoreRef();const latest = useRef(store);latest.current = store;+ const beside = options.beside === true;return useCallback((url: string) => {const app = latest.current, state = app?.state();const botId = app && state ? pagePanelBot(url, { selectedId: state.selectedId, bots: state.bots ?? [], groups: state.groups ?? [], config: state.config, desktop: window.ogb }) : null;- if (!app || !botId) { void openExternalLink(url).catch(() => {}); return; }- requestPanelPage(botId, url);- app.dispatch({ type: "toggleComputer", open: true });- }, []);+ if (app && botId) {+ requestPanelPage(botId, url);+ app.dispatch({ type: "toggleComputer", open: true });+ return;+ }+ const preview = app && beside && showable(url, window.location.origin) ? publishedLink(url) : null;+ if (app && preview) return showAppBesideChat(app.dispatch, preview);+ void openExternalLink(url).catch(() => {});+ }, [beside]);}/** A page link's click opens it like the card's Open; a click its hover card already took stays taken. */export function withPageOpen<T extends { onClick?: (event: MouseEvent<HTMLElement>) => void }>(href: string | undefined, open: (url: string) => void, anchor: T): T {- if (!isPublishedPageUrl(href)) return anchor;+ if (!publishedLink(href)) return anchor;+ const link = href as string;return { ...anchor, onClick: (event: MouseEvent<HTMLElement>) => {anchor.onClick?.(event);if (event.defaultPrevented) return;event.preventDefault();- open(href);+ open(link);} };}diff --git a/src/lib/published-apps.ts b/src/lib/published-apps.tsnew file mode 100644index 0000000000..fca3fcd0df--- /dev/null+++ b/src/lib/published-apps.ts@@ -0,0 +1,41 @@+import type { PublishedApp } from "../../shared/published-apps";+import { isAppOrigin } from "./web-panels";++/** Security: a published site is untrusted content. Its frame keeps the site's own origin (so it runs like a normal+ * site, with its own storage) and gets scripts, forms and new tabs, never the top window, downloads, pointer lock or+ * a way out of the sandbox. A site on the app's own origin is never framed (`showable`). */+export const SITE_FRAME_SANDBOX = "allow-scripts allow-same-origin allow-forms allow-popups";+/** A card's small picture of the site: it only has to draw itself. */+export const SITE_THUMB_SANDBOX = "allow-scripts allow-same-origin";+/** What neither frame may ask the browser for. */+export const SITE_FRAME_ALLOW = "camera 'none'; microphone 'none'; geolocation 'none'; display-capture 'none'; clipboard-read 'none'; autoplay 'none'";++/** A plain web address that is not the app itself. */+export function showable(url: string, appOrigin: string): boolean {+ let parsed: URL;+ try { parsed = new URL(url); } catch { return false; }+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return false;+ return !parsed.username && !parsed.password && !isAppOrigin(parsed.href, appOrigin);+}++export function appInitial(title: string): string {+ const first = [...title.trim()].find((character) => /[\p{L}\p{N}]/u.test(character));+ return first ? first.toLocaleUpperCase() : "·";+}++let known: readonly PublishedApp[] = [];++/** The list the Published apps page last loaded: a link to one of these opens beside the chat. */+export function rememberPublishedApps(apps: readonly PublishedApp[]): void {+ known = apps;+}++/** The app in the loaded list that this address is inside. */+export function knownPublishedApp(href: string): PublishedApp | undefined {+ let url: URL;+ try { url = new URL(href); } catch { return undefined; }+ return known.find((app) => {+ const base = new URL(app.url);+ return url.origin === base.origin && url.pathname.startsWith(base.pathname);+ });+}diff --git a/src/lib/published-links.test.ts b/src/lib/published-links.test.tsnew file mode 100644index 0000000000..17b2ce6b53--- /dev/null+++ b/src/lib/published-links.test.ts@@ -0,0 +1,94 @@+// @vitest-environment happy-dom+import { createElement, type MouseEvent } from "react";+import { flushSync } from "react-dom";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";++import { isNetlifySiteUrl, type PublishedApp } from "../../shared/published-apps";++const opened = vi.hoisted(() => [] as string[]);+const store = vi.hoisted(() => ({ ref: null as null | { dispatch: (action: unknown) => void; state: () => unknown } }));+vi.mock("./app-links", () => ({ openExternalLink: async (url: string) => { opened.push(url); } }));+vi.mock("@/state/store-ref", () => ({ useOptionalStoreRef: () => store.ref }));++const { closeAppPreview, useAppPreview } = await import("./app-preview");+const { publishedLink, usePageOpener, withPageOpen } = await import("./page-open");+const { appInitial, rememberPublishedApps } = await import("./published-apps");++const PAGE = "https://abcdefghijklmnopqrstuvwxyz.mausbot.page/";+const STAND_IN: PublishedApp = { id: "netlify-mira-s1", source: "netlify", title: "Bakery order page", url: "http://127.0.0.1:4010/live/abc/", bot: { id: "mira", name: "Mira" }, publishedAt: 1, access: "netlify-team", canDelete: true };++afterEach(() => { rememberPublishedApps([]); closeAppPreview(); opened.length = 0; store.ref = null; });++describe("a link to something a bot put online", () => {+ it("is a Netlify site's own address, a published page, or an app in the loaded list, and nothing that only looks like one", () => {+ for (const link of ["https://bright-bakery.netlify.app", "https://bright-bakery.netlify.app/menu?x=1#top", "https://6913a0c2e4b0a1000812f3aa--bright-bakery.netlify.app/", PAGE]) expect(publishedLink(link), link).not.toBeNull();+ for (const link of ["http://bright-bakery.netlify.app/", "https://netlify.app/", "https://app.netlify.com/projects/x", "https://bright-bakery.netlify.app.evil.test/", "https://evil.test/bright-bakery.netlify.app",+ "https://a.b.netlify.app/", "https://user:[email protected]/", "https://bright-bakery.netlify.app:8443/", "https://-x.netlify.app/", "https://example.com/", STAND_IN.url, "javascript:alert(1)", "", undefined, null]) {+ expect(publishedLink(link), String(link)).toBeNull();+ }+ expect(isNetlifySiteUrl("https://Bright-Bakery.Netlify.App/")).toBe(true);+ });++ it("is named by the app's own title once the list has it, and marked when the site asks for a login", () => {+ expect(publishedLink("https://bright-bakery.netlify.app/menu")).toEqual({ url: "https://bright-bakery.netlify.app/menu", title: "bright-bakery.netlify.app" });+ rememberPublishedApps([STAND_IN]);+ expect(publishedLink(`${STAND_IN.url}index.html`)).toEqual({ url: `${STAND_IN.url}index.html`, title: "Bakery order page", loginOnly: true });+ expect(publishedLink("http://127.0.0.1:4010/live/abcd/")).toBeNull();+ expect(publishedLink("http://127.0.0.1:4011/live/abc/")).toBeNull();+ });++ it("gets the click in a message; any other link keeps its own", () => {+ const open = vi.fn();+ const click = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; } };+ type Anchor = { href?: string; onClick?: (event: MouseEvent<HTMLElement>) => void };+ withPageOpen<Anchor>("https://bright-bakery.netlify.app/", open, {}).onClick!(click as unknown as MouseEvent<HTMLElement>);+ expect(open).toHaveBeenCalledWith("https://bright-bakery.netlify.app/");+ expect(click.defaultPrevented).toBe(true);+ const plain: Anchor = { href: "https://example.com/" };+ expect(withPageOpen("https://example.com/", open, plain)).toBe(plain);+ });++ it("uses the app's first letter or digit for its tile", () => {+ expect([appInitial("bakery"), appInitial(" “Élan” site"), appInitial("3 cups"), appInitial("🎂 cake"), appInitial("—")]).toEqual(["B", "É", "3", "C", "·"]);+ });+});++describe("where a published link in a message opens", () => {+ const roots: Array<{ unmount(): void }> = [];+ afterEach(() => { for (const root of roots.splice(0)) root.unmount(); });+ function mount(options?: { beside?: boolean }) {+ const seen: { open?: (url: string) => void; preview?: unknown } = {};+ const root = createRoot(document.createElement("div"));+ roots.push(root);+ function Probe() { seen.open = usePageOpener(options); seen.preview = useAppPreview(); return null; }+ flushSync(() => root.render(createElement(Probe)));+ return seen;+ }+ const chat = () => {+ const actions: unknown[] = [];+ store.ref = { dispatch: (action) => actions.push(action), state: () => ({ selectedId: "mira", bots: [{ id: "mira" }], groups: [], config: null }) };+ return actions;+ };++ it("beside the chat, in place of the other side panels, without leaving the app", () => {+ const actions = chat(), seen = mount({ beside: true });+ flushSync(() => seen.open!("https://bright-bakery.netlify.app/menu"));+ expect(seen.preview).toEqual({ url: "https://bright-bakery.netlify.app/menu", title: "bright-bakery.netlify.app" });+ expect(actions).toEqual([{ type: "toggleComputer", open: false }, { type: "toggleSettings", open: false }, { type: "toggleInspector", open: false }, { type: "toggleActivity", open: false }]);+ expect(opened).toEqual([]);+ });++ it("outside the app for any other link, for a card's own Open, and where there is no chat around it", () => {+ chat();+ const beside = mount({ beside: true });+ flushSync(() => beside.open!("https://example.com/"));+ const button = mount();+ flushSync(() => button.open!("https://bright-bakery.netlify.app/"));+ store.ref = null;+ const alone = mount({ beside: true });+ flushSync(() => alone.open!(PAGE));+ expect(opened).toEqual(["https://example.com/", "https://bright-bakery.netlify.app/", PAGE]);+ expect(beside.preview).toBeNull();+ });+});diff --git a/src/locales/en.json b/src/locales/en.jsonindex a7c82852d6..4c94882652 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6924,6 +6924,30 @@"webPanels.page.cantEmbedBody": "Some sites refuse to be embedded. Open it in your browser instead.","webPanels.page.pageGone": "This page can't be shown right now","webPanels.page.refusedBody": "{site} doesn't allow other apps to show it. Open it in your browser instead.",+ "sidebar.nav.publishedApps": "Published apps",+ "publishedApps.title": "Published apps",+ "publishedApps.empty.title": "Nothing published yet",+ "publishedApps.empty.body": "Sites and apps your bots put online show up here. Ask a bot to build a site or app and publish it.",+ "publishedApps.loadFailed": "Your published apps couldn't be loaded.",+ "publishedApps.access.public": "Public",+ "publishedApps.access.netlifyTeam": "Only your Netlify team",+ "publishedApps.access.link": "Anyone with the link",+ "publishedApps.card.preview": "Preview",+ "publishedApps.card.previewOf": "Preview {name}",+ "publishedApps.card.ask": "Ask {bot} to change it",+ "publishedApps.card.manage": "Manage on Netlify",+ "publishedApps.card.delete": "Delete {name}",+ "publishedApps.delete.title": "Delete “{name}”?",+ "publishedApps.delete.body": "Its link will stop working for everyone. This can't be undone.",+ "publishedApps.delete.failed": "This app couldn't be deleted. Try again.",+ "publishedApps.delete.forbidden": "This app isn't yours to delete.",+ "publishedApps.delete.noToken": "This app can't be deleted from here: there is no saved Netlify token to use. Delete it on Netlify instead.",+ "publishedApps.delete.tokenRefused": "This app can't be deleted from here: Netlify refused the saved token. Delete it on Netlify instead.",+ "publishedApps.preview.aria": "Preview of {name}",+ "publishedApps.preview.close": "Close preview",+ "publishedApps.preview.cantShow": "This app can't be shown here",+ "publishedApps.preview.cantShowBody": "Some sites don't let other apps show them. Open it in your browser instead.",+ "publishedApps.preview.loginBody": "This site asks for a Netlify login. Open it in your browser instead.","botAccess.tools.budget": "Its last turn listed {listed} of the {limit} tools its AI takes at once.","botAccess.tools.budgetSearched": "Found through tool search instead: {names}","botAccess.tools.title": "Tool selection",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 958596f954..9d58aaa297 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -6594,6 +6594,30 @@"webPanels.page.cantEmbedBody": "Alguns sites não permitem isso. Abra no navegador.","webPanels.page.pageGone": "Esta página não pode ser mostrada agora","webPanels.page.refusedBody": "O site {site} não permite que outros apps mostrem seu conteúdo. Abra-o no navegador.",+ "sidebar.nav.publishedApps": "Apps publicados",+ "publishedApps.title": "Apps publicados",+ "publishedApps.empty.title": "Nada publicado ainda",+ "publishedApps.empty.body": "Os sites e apps que seus bots colocam no ar aparecem aqui. Peça a um bot para criar um site ou app e publicá-lo.",+ "publishedApps.loadFailed": "Não foi possível carregar seus apps publicados.",+ "publishedApps.access.public": "Público",+ "publishedApps.access.netlifyTeam": "Só sua equipe da Netlify",+ "publishedApps.access.link": "Qualquer pessoa com o link",+ "publishedApps.card.preview": "Pré-visualizar",+ "publishedApps.card.previewOf": "Pré-visualizar {name}",+ "publishedApps.card.ask": "Pedir a {bot} para alterar",+ "publishedApps.card.manage": "Gerenciar na Netlify",+ "publishedApps.card.delete": "Excluir {name}",+ "publishedApps.delete.title": "Excluir “{name}”?",+ "publishedApps.delete.body": "O link vai parar de funcionar para todo mundo. Não dá para desfazer.",+ "publishedApps.delete.failed": "Não foi possível excluir este app. Tente de novo.",+ "publishedApps.delete.forbidden": "Você não pode excluir este app.",+ "publishedApps.delete.noToken": "Não dá para excluir este app por aqui: não há um token da Netlify salvo para usar. Exclua-o na Netlify.",+ "publishedApps.delete.tokenRefused": "Não dá para excluir este app por aqui: a Netlify recusou o token salvo. Exclua-o na Netlify.",+ "publishedApps.preview.aria": "Pré-visualização de {name}",+ "publishedApps.preview.close": "Fechar pré-visualização",+ "publishedApps.preview.cantShow": "Não é possível mostrar este app aqui",+ "publishedApps.preview.cantShowBody": "Alguns sites não deixam outros apps mostrá-los. Abra no navegador.",+ "publishedApps.preview.loginBody": "Este site pede login na Netlify. Abra no navegador.","botAccess.tools.budget": "Ferramentas listadas na última sessão: {listed} de {limit}, o limite que a IA dele aceita de uma vez.","botAccess.tools.budgetSearched": "Disponíveis pela busca de ferramentas: {names}","botAccess.tools.title": "Seleção de ferramentas",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 4eeb7922c5..0848c83882 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -30029,6 +30029,30 @@"webPanels.page.cantEmbed": "9390535d5c547b4a2b08ed1bd6aed30249abc611b9827015553ee212c0810e7f","webPanels.page.cantEmbedBody": "f635b0abe680ddb9dba8df3525b444475e7f40cd496b4739ce817207d325a957","webPanels.page.refusedBody": "adb3d5a6354f61ab786fed7b45d74f877dbbffe298dba56231e619b60d04f138",+ "sidebar.nav.publishedApps": "9ddfc0e18af9ac5e94dc674948c4bdc642014ec0c7be79b1d74168859d83e038",+ "publishedApps.title": "9ddfc0e18af9ac5e94dc674948c4bdc642014ec0c7be79b1d74168859d83e038",+ "publishedApps.empty.title": "b377a1d634cec4382fe65bede8fc5241513aa25b4aa873a87c8edfa1a2955178",+ "publishedApps.empty.body": "f22e77fd77039538f047fd73e5eca39d2f65b54a085501d6d72e6c2de5837046",+ "publishedApps.loadFailed": "f6e98abf5beb8325fb57b5124cb38be254b0447d2c9bf0cbef1d65385659d982",+ "publishedApps.access.public": "591935b15b1c88e2d5f6be0a054604fcf36f0585a6f51098fa3803826fff278c",+ "publishedApps.access.netlifyTeam": "169d3f849a1ecdddc1ac473366dacd96f5a755407b7a0583f1f5e7aeb0c4a77a",+ "publishedApps.access.link": "5b7f701785be58f468f02335ce1cf992f11bd06d5be6ca4d926375207e360c82",+ "publishedApps.card.preview": "324b134f57c70c729ae3dc4d298bb451656717d70523e942c1ce667b8024ea07",+ "publishedApps.card.previewOf": "46f4453356a0d51b135491e9ea80f2d917e8fae656b275dd5b7d705d4026f440",+ "publishedApps.card.ask": "1cf212b25e2a75d90d4085054ffb884d26ef34d7632aef02bfa624e1a6cfe150",+ "publishedApps.card.manage": "681d72e94c5ad3211b2240549a5b31cc981477211d148a027daa14bf85741176",+ "publishedApps.card.delete": "3cf8146e529f1e4296d40d7ea32ffc63bc2647d416851ed43921bfedf3097cb3",+ "publishedApps.delete.title": "8e13216a05b75255681daa6d0da8938db3480ee79257419a088bb3b3a4c6f6c2",+ "publishedApps.delete.body": "8731ec4061b3ff877ba1c60dde7220c5cd79c3585e90893c1050dc47f3cf7e86",+ "publishedApps.delete.failed": "807d070d40046e6771fce4a497e1d0561ea737d5ff6c1e12b79063c133eb49d9",+ "publishedApps.delete.forbidden": "8b4977d75a0ce656ef3c39f75e9050c6f2435ba02f487ee089094fc72b857b1c",+ "publishedApps.delete.noToken": "ec8e3bb984a525b38bc5d25d0d53b0e2aa62e7f3e70d4e0da957009dd3988c23",+ "publishedApps.delete.tokenRefused": "fbf0973d4b2f23f3355e36d84a933179a774a3e31c814b7a1cb49e25ecc0ecbd",+ "publishedApps.preview.aria": "e8371112eb46143f26117e124b725328cd37d525887883dbfa7689c4ae74daa7",+ "publishedApps.preview.close": "7d8ab368210c5ae8d2cec7bb577afe1e7cf9489c88f031e0f9de7555c9f20b66",+ "publishedApps.preview.cantShow": "8679095cc69e8ee3b90e1174085cd09eac16a5859e7b5b49a79f6750aa5c53ce",+ "publishedApps.preview.cantShowBody": "f6dd70f3e85f76260cff7359482156defe7fed55b654eaad6f209798d719ef66",+ "publishedApps.preview.loginBody": "5ab274fd292e49d19d4b354727d90bb5359d55cd5d02af89a53d588c679ac9ad","botAccess.tools.budget": "b984e581763989cac85c22212d2e2884d91d1db8acf44e0a68d1b8e686da8f63","botAccess.tools.budgetSearched": "fc7961953b805c38a2158ee455f14b33768724a21fa961a16dd0cd64f2fa4d5e","botAccess.tools.title": "b304cd56adc233aa9da1866096a1406777c293eb519bb9cb4386167fd82e3524",diff --git a/src/state/store.tsx b/src/state/store.tsxindex 6a105f88a8..ae4ff8f794 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -563,7 +563,7 @@ export interface AppState {liveCallVersion: number;liveCallLookupSeq: number;selectedId: string;- activeView: "chat" | "team-map" | "routines" | "files" | "web-panel";+ activeView: "chat" | "team-map" | "routines" | "files" | "web-panel" | "published-apps";/** Folders a finished move left on this computer, for Files to offer sharing. */filesSuggest: string[] | null; webPanelId?: string;routines: Routine[];@@ -645,7 +645,7 @@ export type Action =| { type: "botsOrdered"; botIds: string[] }| { type: "sectionDeleted"; section: string; sections: string[] }| { type: "showRoutines"; section?: "schedule" | "logs"; view?: "calendar" | "list"; botId?: string; routineId?: string; runStatus?: RoutineRunStatusFilter }- | { type: "showTeamMap" } | { type: "showWebPanel"; id: string }+ | { type: "showTeamMap" } | { type: "showPublishedApps" } | { type: "showWebPanel"; id: string }| { type: "showFiles"; suggest?: string[] }| { type: "showChat" }| { type: "routinesHydrated"; routines: Routine[]; runs: RoutineRun[]; since?: number }@@ -991,10 +991,10 @@ export function reducer(state: AppState, action: Action): AppState {case "showChat":return state.activeView === "chat" ? state : { ...state, activeView: "chat" };case "showTeamMap":- case "showFiles": case "showWebPanel":+ case "showFiles": case "showWebPanel": case "showPublishedApps":return {...state,- activeView: action.type === "showFiles" ? "files" : action.type === "showWebPanel" ? "web-panel" : "team-map",+ activeView: action.type === "showFiles" ? "files" : action.type === "showWebPanel" ? "web-panel" : action.type === "showPublishedApps" ? "published-apps" : "team-map",filesSuggest: action.type === "showFiles" && action.suggest?.length ? action.suggest : null, webPanelId: action.type === "showWebPanel" ? action.id : state.webPanelId,settingsOpen: false, computerOpen: false, inspectorOpen: false, activityOpen: false, appSettingsOpen: false, pluginsOpen: false,};@@ -2253,7 +2253,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {};const wrapped: React.Dispatch<Action> = (action) => {- if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles", "showWebPanel"].includes(action.type)) selectionRevision.current++;+ if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles", "showWebPanel", "showPublishedApps"].includes(action.type)) selectionRevision.current++;// Pin before any await or optimistic state change.action = pinBotThreadAction(action, stateRef.current.bots);if (action.type === "taskSwitched") action = { ...action, bot: withTaskWrites(action.bot) as Bot };