Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(pages): let a published page be owner-only
erywim135d809796c7
diff --git a/packages/phone-protocol/src/published-page.ts b/packages/phone-protocol/src/published-page.tsindex 560d4a86aa..cdf52742db 100644--- a/packages/phone-protocol/src/published-page.ts+++ b/packages/phone-protocol/src/published-page.ts@@ -1,5 +1,9 @@-/** A page a bot published to a public link, as its chat card shows it (WireMessage.publishedPage). The message's `text`- * says the same in words, with the link, for every client that does not draw the card. */+/** Who may open a published page: anyone with its link, or only the owner's own signed-in devices. Absent on a page+ * published before this setting existed means public. */+export type PublishedPageVisibility = "public" | "owner";++/** A page a bot published to a link, as its chat card shows it (WireMessage.publishedPage). The message's `text` says the+ * same in words, with the link, for every client that does not draw the card. */export interface PublishedPageCard {/** live: the link works, or may work when `uncertain` is true. unpublished: its owner took it down. limit: the plan's* pages are used up, so nothing was published; `message` says so and `upgrade` offers a bigger plan. */@@ -9,6 +13,8 @@ export interface PublishedPageCard {title: string;pageId?: string;url?: string;+ /** Absent means public. `owner`: the page is kept on this server and only the owner's signed-in devices can open it. */+ visibility?: PublishedPageVisibility;/** This account's pages and its plan's limit after this publish, as "3 of 5 pages". */usage?: { pages: number; limit: number };message?: string;diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.jsonindex 6f0b9f5cfd..a7f6b93b92 100644--- a/server/drivers/agents-catalog-goldens/full.tools-list.json+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json@@ -680,7 +680,7 @@},{"name": "publish_page",- "description": "Publish a page you made to a public link anyone with it can open, when the person wants others to open it (share, send to someone, post) or asks to publish it: an .html file, or a folder with an index.html (static files and data too, up to 5 MB). Publishing the same path again, or passing page_id, updates the same link. Never publish secrets, or money, health, ID or customer details the person didn't ask to make public; give the file instead. For a data dashboard, follow the data-dashboards skill.",+ "description": "Publish a page you made to a link, when the person wants to open it later or others to open it (share, send to someone, post) or asks to publish it: an .html file, or a folder with an index.html (static files and data too, up to 5 MB). visibility \"public\" (the default) is a link anyone with it can open; visibility \"owner\" keeps an internal report or dashboard for the person's own signed-in devices only, never on the public web. Publishing the same path again, or passing page_id, updates the same link. Never publish secrets, or money, health, ID or customer details the person didn't ask to make public; give the file instead. For a data dashboard, follow the data-dashboards skill.","inputSchema": {"type": "object","additionalProperties": false,@@ -701,6 +701,14 @@"live": {"type": "boolean","description": "True republishes it when its folder changes; open copies reload."+ },+ "visibility": {+ "type": "string",+ "enum": [+ "public",+ "owner"+ ],+ "description": "public: anyone with the link (the default). owner: only the person's own signed-in devices; it stays on this server."}},"required": [diff --git a/server/drivers/agents-pages-tools.ts b/server/drivers/agents-pages-tools.tsindex 50860c5308..242896323c 100644--- a/server/drivers/agents-pages-tools.ts+++ b/server/drivers/agents-pages-tools.ts@@ -17,7 +17,7 @@ export const PAGE_TOOL_DEFINITIONS = [{name: "publish_page",description:- "Publish a page you made to a public link anyone with it can open, when the person wants others to open it (share, send to someone, post) or asks to publish it: an .html file, or a folder with an index.html (static files and data too, up to 5 MB). Publishing the same path again, or passing page_id, updates the same link. Never publish secrets, or money, health, ID or customer details the person didn't ask to make public; give the file instead. For a data dashboard, follow the data-dashboards skill.",+ "Publish a page you made to a link, when the person wants to open it later or others to open it (share, send to someone, post) or asks to publish it: an .html file, or a folder with an index.html (static files and data too, up to 5 MB). visibility \"public\" (the default) is a link anyone with it can open; visibility \"owner\" keeps an internal report or dashboard for the person's own signed-in devices only, never on the public web. Publishing the same path again, or passing page_id, updates the same link. Never publish secrets, or money, health, ID or customer details the person didn't ask to make public; give the file instead. For a data dashboard, follow the data-dashboards skill.",inputSchema: {type: "object",additionalProperties: false,@@ -26,6 +26,7 @@ export const PAGE_TOOL_DEFINITIONS = [title: { type: "string", maxLength: 200, description: "A short name for the page." },page_id: PAGE_ID,live: { type: "boolean", description: "True republishes it when its folder changes; open copies reload." },+ visibility: { type: "string", enum: ["public", "owner"], description: "public: anyone with the link (the default). owner: only the person's own signed-in devices; it stays on this server." },},required: ["path", "title"],},diff --git a/server/host/published-apps.test.ts b/server/host/published-apps.test.tsindex a56048a296..bcb23ec222 100644--- a/server/host/published-apps.test.ts+++ b/server/host/published-apps.test.ts@@ -114,6 +114,11 @@ describe("the list on a person's own server", () => {expect(listed.every((app) => app.canDelete)).toBe(true);});+ it("lists an owner-only page as only the owner's, not as anyone with the link", async () => {+ pages = [{ ...page(PAGE_ADA, "mira", "ada-chat", 400), visibility: "owner" }];+ expect((await apps().list(visibleFor(OWNER, false), OWNER)).find((app) => app.source === "page")?.access).toBe("owner");+ });+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: "" });diff --git a/server/host/published-apps.ts b/server/host/published-apps.tsindex c09167e855..e676c97ef2 100644--- a/server/host/published-apps.ts+++ b/server/host/published-apps.ts@@ -132,7 +132,7 @@ export function createPublishedApps(deps: PublishedAppsDeps) {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 },+ publishedAt: page.updatedAt, access: page.visibility === "owner" ? "owner" as const : "link" as const },threads: () => page.cards.map((card) => card.threadId).reverse(),needsThread: true,remove: async () => ((await deps.unpublishPage(page.pageId)).status === 200 ? null : "failed"),diff --git a/server/index.ts b/server/index.tsindex 2d5930c9d1..946a32576e 100644--- a/server/index.ts+++ b/server/index.ts@@ -11948,7 +11948,7 @@ const roomReactionNotes = createRoomReactionNotes({ store }), { react } = createstore, noted: roomReactionNotes.noted, inboxAnswer: (input) => teamMessages.reactedIn(input.auth, input.threadId, input.target.id, input.answer, { sendId: input.sendId, sender: messageSender(input.auth) }), reply: (input) => personReplies.deliver({ ...input, about: "message" }),answerCard: (input) => respondToCard({ ...input, via: "reaction" }), withdraw: personReplies.withdraw,});-const publishedPages = createPublishedPages({ dataDir: DATA_DIR, cloudHome: CLOUD_HOME, selfHosted: !CLOUD_HOME && !HOSTED_WORKSPACE && utilityParentPort === undefined, patch: (threadId, messageId, text, publishedPage) => void store.patchMessage(threadId, messageId, { text, publishedPage }), liveRoots: (botId, threadId) => liveRoots(threadId, botId), paused: () => workspaceMaintenance.active || moveFreeze.frozen(), apps: { chat: chatApps, store } }); ROUTES.push(createReactionRoutes({ react, reactorFor, cloudGuestSendRefusal }), publishedPages.routes, createBotLibraryRoutes({ bot: (id) => store.bot(id), visibleFor: (auth) => visibleTo(viewerFor(auth)), pages: () => publishedPages.store.list() }), savedSteps.routes, createPlacesElsewhereRoutes({ elsewhere: placesElsewhere, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (auth.kind === "loopback" || ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }));+const publishedPages = createPublishedPages({ dataDir: DATA_DIR, cloudHome: CLOUD_HOME, selfHosted: !CLOUD_HOME && !HOSTED_WORKSPACE && utilityParentPort === undefined, patch: (threadId, messageId, text, publishedPage) => void store.patchMessage(threadId, messageId, { text, publishedPage }), liveRoots: (botId, threadId) => liveRoots(threadId, botId), pageOrigin: () => publicUrl() ?? `http://127.0.0.1:${PORT}`, sessionLive: (id) => sessions.isLive(id), paused: () => workspaceMaintenance.active || moveFreeze.frozen(), apps: { chat: chatApps, store } }); ROUTES.push(createReactionRoutes({ react, reactorFor, cloudGuestSendRefusal }), publishedPages.routes, createBotLibraryRoutes({ bot: (id) => store.bot(id), visibleFor: (auth) => visibleTo(viewerFor(auth)), pages: () => publishedPages.store.list() }), savedSteps.routes, createPlacesElsewhereRoutes({ elsewhere: placesElsewhere, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (auth.kind === "loopback" || ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }));// `let` slots are read per request.const engineEnvironments = () => [process.env, ...Object.values(providerConfigs()).map((instance) => instanceEnvironment(process.env, instance))].flatMap((env) => engineHomes.everyHome(env)); const folderCleanup = CLOUD_HOME && (deleteTimeCleanup(process.env, true, () => true) || orphanSweepMode() !== "off" || idleReclaimMode() !== "off") ? createConversationFolderCleanup({ dataDir: DATA_DIR, records: () => store, heldText: () => routines ? JSON.stringify([cfg, routines.listRoutines()]) : null, mentions: (words) => threadsMentioning(join(DATA_DIR, "messages.db"), words), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), processFolders: linuxProcessPaths, processPaths: linuxProcessPaths }) : undefined; const keptAttachments = () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles, ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; }; createDeleteLeftovers({ dataDir: DATA_DIR, store, checkpointsQuiet: checkpoints.quiet, references: attachmentReferences, keptAttachments, deleteAttachments: (names) => deleteAttachments(names.map((name) => join(ATTACHMENTS_DIR, name))), engineFolders: () => engineSessionFolders(DATA_DIR, engineEnvironments()), layers: memoryLayerRecords, folders: deleteTimeCleanup(process.env, Boolean(folderCleanup), () => folderCleanup!) }); startEngineSessionSweep({ cloudHome: CLOUD_HOME !== null, env: process.env, dataDir: DATA_DIR, bots: () => store.bots, folders: () => engineSessionFolders(DATA_DIR, engineEnvironments()), environments: engineEnvironments, paused: () => moveFreeze.frozen() || workspaceMaintenance.active, turnsRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()) });ROUTES.push(createThreadRoutes({@@ -12439,7 +12439,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}if (await emailSignInRoute({ cloudHome: Boolean(CLOUD_HOME), emailSignIn, sessions, cookieName: SESSION_COOKIE, target: (r) => signInMailTarget(publicUrl(), requestOrigin(r)),environment: () => environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: true, sharedComputers: lendingEnabled() }) }, req, res, path, method)) return;- if ((cloudSigned && await cloudSigned({ req, res, url, path, method })) || chatApps.serveFile(req, res, path, method) || localApps.serveFile(req, res, path, method) || await cliLogin.open(req, res, path, method)) return;+ if ((cloudSigned && await cloudSigned({ req, res, url, path, method })) || chatApps.serveFile(req, res, path, method) || localApps.serveFile(req, res, path, method) || publishedPages.serveFile(req, res, path, method) || await cliLogin.open(req, res, path, method)) return;if (method === "POST" && path === "/api/auth/pair") {// JSON only: a cross-site HTML form cannot send this content type without a preflight, so no unused code is planted as a session.if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) {diff --git a/server/pages/owner-files.ts b/server/pages/owner-files.tsnew file mode 100644index 0000000000..72f24fa4fb--- /dev/null+++ b/server/pages/owner-files.ts@@ -0,0 +1,66 @@+// An owner-only page's files, kept in the data folder and served only behind the owner's sign-in (routes/published-pages.ts).+// Each page is written to a fresh folder and swapped in whole, so a reader never sees half an update; files and folders+// are owner-only, and only paths a page may carry are read back.+import { randomBytes } from "node:crypto";+import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { dirname, join, relative, resolve, sep } from "node:path";++import { renameWithRetry } from "../atomic.ts";+import { pageFilePath } from "../page-files.ts";+import type { PageFile } from "./bundle.ts";++const DIR_MODE = 0o700, FILE_MODE = 0o600;++export class PublishedPageFiles {+ private readonly dir: string;++ constructor(dir: string) {+ this.dir = dir;+ }++ save(pageId: string, files: readonly PageFile[]): void {+ const target = join(this.dir, pageId), staging = `${target}.${randomBytes(6).toString("hex")}.tmp`;+ rmSync(staging, { recursive: true, force: true });+ try {+ mkdirSync(staging, { recursive: true, mode: DIR_MODE });+ for (const file of files) {+ const path = pageFilePath(file.path);+ if (path === null) throw new Error(`invalid page file: ${file.path}`);+ const full = join(staging, path);+ mkdirSync(dirname(full), { recursive: true, mode: DIR_MODE });+ writeFileSync(full, file.data, { mode: FILE_MODE });+ }+ if (!existsSync(join(staging, "index.html"))) throw new Error("the page has no index.html");+ rmSync(target, { recursive: true, force: true });+ renameWithRetry(staging, target);+ } catch (error) {+ rmSync(staging, { recursive: true, force: true });+ throw error;+ }+ }++ /** The bytes of one file of the page, or null for a path the page cannot hold, a link, a folder, or a missing file. */+ read(pageId: string, path: string): Buffer | null {+ const file = pageFilePath(path);+ if (file === null) return null;+ const target = join(this.dir, pageId), full = resolve(target, file), inside = relative(target, full);+ if (!inside || inside === ".." || inside.startsWith(`..${sep}`) || inside.includes(`${sep}..`)) return null;+ try {+ return lstatSync(full).isFile() ? readFileSync(full) : null;+ } catch {+ return null;+ }+ }++ has(pageId: string): boolean {+ try {+ return lstatSync(join(this.dir, pageId, "index.html")).isFile();+ } catch {+ return false;+ }+ }++ remove(pageId: string): void {+ rmSync(join(this.dir, pageId), { recursive: true, force: true });+ }+}diff --git a/server/pages/owner-links.test.ts b/server/pages/owner-links.test.tsnew file mode 100644index 0000000000..0bdcb03f03--- /dev/null+++ b/server/pages/owner-links.test.ts@@ -0,0 +1,88 @@+import type { IncomingMessage, ServerResponse } from "node:http";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { PublishedPageFiles } from "./owner-files.ts";+import { createOwnerPageLinks } from "./owner-links.ts";++const PAGE = "abcdefghijklmnopqrstuvwxyz";+let dir: string;+let files: PublishedPageFiles;++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "omb-owner-links-"));+ files = new PublishedPageFiles(join(dir, "owner-pages"));+ files.save(PAGE, [{ path: "index.html", data: Buffer.from("<!doctype html><h1>Traffic</h1>") }, { path: "data.csv", data: Buffer.from("a,1") }]);+});+afterEach(() => rmSync(dir, { recursive: true, force: true }));++function request(headers: Record<string, string> = {}): IncomingMessage {+ // SAFETY: the route reads only headers.+ return { headers } as unknown as IncomingMessage;+}++function response() {+ const sent: { status?: number; headers?: Record<string, string>; body?: unknown } = {};+ const res = {+ writeHead: (status: number, headers: Record<string, string>) => { sent.status = status; sent.headers = headers; },+ end: (body?: unknown) => { sent.body = body; },+ } as unknown as ServerResponse;+ return { res, sent };+}++const linksFor = (options: { ownerPage?: boolean; now?: () => number } = {}) =>+ createOwnerPageLinks({ files, ownerPage: () => options.ownerPage ?? true, ...(options.now ? { now: options.now } : {}) });++describe("an owner-only page's token folder", () => {+ it("serves its index and files with a sandboxed policy and no cache, to GET and HEAD", () => {+ const links = linksFor(), folder = links.folder(PAGE, { key: "session:s1", allowed: () => true });+ const index = response();+ expect(links.serve(request({ host: "cloud.example.test", "x-forwarded-proto": "https" }), index.res, folder, "GET")).toBe(true);+ expect(index.sent).toMatchObject({ status: 200, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "private, no-store",+ "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", "access-control-allow-origin": "*" } });+ expect(String(index.sent.headers!["content-security-policy"])).toContain("sandbox allow-scripts");+ expect(String(index.sent.headers!["content-security-policy"])).toContain("https://cloud.example.test");+ expect(String(index.sent.body)).toBe("<!doctype html><h1>Traffic</h1>");+ const csv = response();+ links.serve(request(), csv.res, `${folder}data.csv`, "HEAD");+ expect(csv.sent).toMatchObject({ status: 200, headers: { "content-type": "text/csv; charset=utf-8" } });+ expect(csv.sent.body).toBeUndefined();+ });++ it("refuses a token whose page is gone, whose viewer may no longer see it, or that was never minted", () => {+ let allowed = true, pageExists = true;+ const links = createOwnerPageLinks({ files, ownerPage: () => pageExists });+ const folder = links.folder(PAGE, { key: "session:s1", allowed: () => allowed });+ allowed = false;+ const refused = response();+ links.serve(request(), refused.res, folder, "GET");+ expect(refused.sent).toMatchObject({ status: 404 });+ allowed = true;+ const unknown = response();+ links.serve(request(), unknown.res, "/api/owner-page-files/not-a-token/index.html", "GET");+ expect(unknown.sent).toMatchObject({ status: 404 });+ pageExists = false;+ const gone = response();+ links.serve(request(), gone.res, folder, "GET");+ expect(gone.sent).toMatchObject({ status: 404 });+ pageExists = true;+ const traversal = response();+ links.serve(request(), traversal.res, `${folder}../secret.txt`, "GET");+ expect(traversal.sent).toMatchObject({ status: 400 });+ });++ it("gives one viewer the same folder while it is in use, another viewer its own, and forgets both after a day unused", () => {+ let now = 1_000;+ const links = linksFor({ now: () => now });+ const viewer = { key: "session:s1", allowed: () => true };+ const first = links.folder(PAGE, viewer);+ expect(links.folder(PAGE, viewer)).toBe(first);+ const other = links.folder(PAGE, { key: "session:s2", allowed: () => true });+ expect(other).not.toBe(first);+ now += 24 * 60 * 60_000 + 1;+ const answer = response();+ links.serve(request(), answer.res, first, "GET");+ expect(answer.sent).toEqual({ status: 404, headers: expect.any(Object), body: "Not found." });+ });+});diff --git a/server/pages/owner-links.ts b/server/pages/owner-links.tsnew file mode 100644index 0000000000..84e4a366aa--- /dev/null+++ b/server/pages/owner-links.ts@@ -0,0 +1,110 @@+// The URL an owner-only page loads from inside its sandboxed frame. Its sandbox gives the page an opaque origin, which+// sends no session cookie with the page's own files, so the open page's files carry a token instead: minted only for an+// owner who opened the page's stable link, for that page and that viewer, and dropped after a day unused. A token is+// therefore a bearer for one page; the stable link itself never carries one.+import { randomBytes } from "node:crypto";+import type { IncomingMessage, ServerResponse } from "node:http";+import { extname } from "node:path";+import { BOT_HTML_CSP } from "../../shared/app-frame/csp.ts";+import { PAGE_FILE_TYPES } from "../../shared/published-page.ts";+import { pageFilePath } from "../page-files.ts";+import { requestOrigin } from "../request-auth.ts";+import type { PublishedPageFiles } from "./owner-files.ts";++export const OWNER_PAGE_FILES_PREFIX = "/api/owner-page-files/";+const TOKEN = /^[A-Za-z0-9_-]{43}$/;+const DAY_MS = 24 * 60 * 60_000;+const MAX_TOKENS = 2_000;++/** An owner-only page opened directly: its own files load, inline code runs, and it stays in an opaque origin, so it can+ * reach neither the app's cookies nor its API. */+export function ownerPageCsp(origin: string): string {+ return BOT_HTML_CSP.split("; ").map((directive) => {+ if (/^(script|style|font|img|media|connect|worker)-src /.test(directive)) return `${directive} ${origin}`;+ return directive === "default-src 'none'" ? `default-src ${origin}` : directive;+ }).join("; ").concat("; sandbox allow-scripts allow-forms allow-modals allow-downloads allow-top-navigation-by-user-activation");+}++/** Who a token was minted for: `key` names them, and `allowed()` is asked again on every file. */+export interface OwnerPageViewer {+ key: string;+ allowed(): boolean;+}++export function createOwnerPageLinks(deps: {+ files: Pick<PublishedPageFiles, "read">;+ /** True while the page is still an owner-only page this server keeps. */+ ownerPage(pageId: string): boolean;+ now?(): number;+}) {+ const now = deps.now ?? Date.now;+ const tokens = new Map<string, { pageId: string; viewer: string; allowed?: () => boolean; used: number }>();+ const byViewer = new Map<string, string>();+ const keyOf = (pageId: string, viewer: string) => `${pageId}\n${viewer}`;+ const forget = (token: string) => {+ const known = tokens.get(token);+ tokens.delete(token);+ if (known) byViewer.delete(keyOf(known.pageId, known.viewer));+ };+ const answer = (res: ServerResponse, status: number, text: string) => {+ res.writeHead(status, { "content-type": "text/plain; charset=utf-8", "cache-control": "private, no-store", "x-content-type-options": "nosniff" });+ res.end(text);+ };++ return {+ /** The folder URL this viewer's copy of the page loads from; the same token while it is in use. */+ folder(pageId: string, viewer: OwnerPageViewer): string {+ const at = now();+ for (const [token, known] of tokens) if (at - known.used > DAY_MS) forget(token);+ const existing = byViewer.get(keyOf(pageId, viewer.key));+ if (existing) {+ tokens.set(existing, { pageId, viewer: viewer.key, allowed: viewer.allowed, used: at });+ return `${OWNER_PAGE_FILES_PREFIX}${existing}/`;+ }+ while (tokens.size >= MAX_TOKENS) forget(tokens.keys().next().value!);+ const token = randomBytes(32).toString("base64url");+ tokens.set(token, { pageId, viewer: viewer.key, allowed: viewer.allowed, used: at });+ byViewer.set(keyOf(pageId, viewer.key), token);+ return `${OWNER_PAGE_FILES_PREFIX}${token}/`;+ },++ /** True when the request was this route's. */+ serve(req: IncomingMessage, res: ServerResponse, path: string, method: string): boolean {+ if (!path.startsWith(OWNER_PAGE_FILES_PREFIX)) return false;+ const rest = path.slice(OWNER_PAGE_FILES_PREFIX.length), slash = rest.indexOf("/");+ const token = slash === -1 ? rest : rest.slice(0, slash);+ if (method !== "GET" && method !== "HEAD") {+ answer(res, 405, "Read only.");+ return true;+ }+ const target = TOKEN.test(token) ? tokens.get(token) : undefined;+ if (!target || now() - target.used > DAY_MS || slash === -1 || (target.allowed && !target.allowed()) || !deps.ownerPage(target.pageId)) {+ answer(res, 404, "Not found.");+ return true;+ }+ target.used = now();+ const file = pageFilePath(rest.slice(slash + 1));+ if (file === null) {+ answer(res, 400, "Not a file of this page.");+ return true;+ }+ const body = deps.files.read(target.pageId, file);+ if (!body) {+ answer(res, 404, "Not found.");+ return true;+ }+ res.writeHead(200, {+ "content-type": PAGE_FILE_TYPES[extname(file).slice(1).toLowerCase()] ?? "application/octet-stream",+ "content-length": String(body.byteLength),+ "content-security-policy": ownerPageCsp(requestOrigin(req) ?? "http://127.0.0.1"),+ "x-content-type-options": "nosniff",+ "referrer-policy": "no-referrer",+ "cache-control": "private, no-store",+ "access-control-allow-origin": "*",+ });+ res.end(method === "HEAD" ? undefined : body);+ return true;+ },+ };+}+export type OwnerPageLinks = ReturnType<typeof createOwnerPageLinks>;diff --git a/server/pages/published-pages.test.ts b/server/pages/published-pages.test.tsindex b59591b129..4fbc873af0 100644--- a/server/pages/published-pages.test.ts+++ b/server/pages/published-pages.test.ts@@ -7,7 +7,7 @@ import { FAKE_DESKTOP_TOKEN, FAKE_HOME, FAKE_TOKEN_URL, fakePagesService } fromimport { applyIncludedPagesMessage, pagesHomeSignature } from "./access.ts";import { PageBundleError, readPageBundle, skippedNote } from "./bundle.ts";import * as bundle from "./bundle.ts";-import { PublishedPagesStore } from "./store.ts";+import { PagesStore, PublishedPagesStore } from "./store.ts";import { createPublishedPages } from "./service.ts";import { createPagesInternalRoutes, createPublishedPageRoutes, type AppPages } from "../routes/published-pages.ts";import { PASS } from "../routes/table.ts";@@ -43,14 +43,17 @@ function setup(options: { home?: boolean; quota?: number; selfHosted?: boolean;const cards: Array<{ threadId: string; id: string; text: string; card: PublishedPageCard }> = [];let ids = 0;const pages = createPublishedPages({ dataDir: data, cloudHome: options.home ? FAKE_HOME : null, selfHosted: options.selfHosted, fetch: (input, init) => service.fetch(input, init),+ pageOrigin: () => "https://cloud.example.test",...(options.liveRoots ? { liveRoots: options.liveRoots } : {}), ...(options.paused ? { paused: options.paused } : {}),patch: (threadId, messageId, text, card) => { const shown = cards.find((each) => each.id === messageId && each.threadId === threadId); if (shown) Object.assign(shown, { text, card }); } });const post = (threadId: string) => (text: string, card: PublishedPageCard) => { const id = `m${++ids}`; cards.push({ threadId, id, text, card }); return id; };- const publish = (input: { path: string; title?: string; pageId?: string; botId?: string; threadId?: string }) => pages.publisher.publish({+ const publish = (input: { path: string; title?: string; pageId?: string; botId?: string; threadId?: string; live?: boolean; visibility?: "public" | "owner" }) => pages.publisher.publish({botId: input.botId ?? "bot-1", threadId: input.threadId ?? "thread-1", path: input.path, title: input.title ?? "Bake sale",- ...(input.pageId ? { pageId: input.pageId } : {}), roots: [work], post: post(input.threadId ?? "thread-1") });+ ...(input.pageId ? { pageId: input.pageId } : {}), ...(input.live !== undefined ? { live: input.live } : {}),+ ...(input.visibility ? { visibility: input.visibility } : {}), roots: [work], post: post(input.threadId ?? "thread-1") });return { service, pages, work, data, cards, publish };}+const ownerUrl = (pageId: string) => `https://cloud.example.test/api/published-pages/${pageId}/`;describe("publishing a page", () => {it("asks the person to sign in to MausBot when this app has no account, and publishes nothing", async () => {@@ -287,6 +290,118 @@ describe("publishing a page", () => {});});+describe("an owner-only published page", () => {+ it("is kept on this server without asking the pages service for anything, even with no MausBot account", async () => {+ const f = setup();+ writeSite(join(f.work, "report"), { "index.html": "<!doctype html><h1>Traffic</h1>", "data.csv": "day,hits\nmon,3\n" });+ const outcome = await f.publish({ path: "report", title: "Traffic", visibility: "owner" });+ expect(outcome.status).toBe(200);+ const [record] = f.pages.store.list();+ const url = ownerUrl(record!.pageId);+ expect(outcome.text).toContain(`Published “Traffic” for you only: ${url}`);+ expect(outcome.text).toContain("Only you can open it");+ expect(f.service.minted).toEqual([]);+ expect(f.service.pages.size).toBe(0);+ expect(f.cards).toEqual([{ threadId: "thread-1", id: "m1", text: `“Traffic” is published for you: ${url}. Only you can open it.`,+ card: { state: "live", title: "Traffic", pageId: record!.pageId, url, visibility: "owner" } }]);+ expect(f.pages.files.read(record!.pageId, "")?.toString()).toBe("<!doctype html><h1>Traffic</h1>");+ expect(f.pages.files.read(record!.pageId, "data.csv")?.toString()).toBe("day,hits\nmon,3\n");+ expect(new PublishedPagesStore(join(f.data, "owner-pages.json")).get(record!.pageId)).toMatchObject({ url, visibility: "owner" });+ expect(new PublishedPagesStore(join(f.data, "published-pages.json")).list()).toEqual([]);+ });++ it("keeps its link when published again, and takes its files away with Unpublish", async () => {+ const f = setup();+ writeSite(join(f.work, "report"));+ await f.publish({ path: "report", visibility: "owner" });+ const [record] = f.pages.store.list();+ writeFileSync(join(f.work, "report", "style.css"), "h1{color:blue}");+ const again = await f.publish({ path: "report", visibility: "owner" });+ expect(again.text).toContain(`Updated “Bake sale” at the same link: ${ownerUrl(record!.pageId)}`);+ expect(f.pages.store.list()).toHaveLength(1);+ expect(f.pages.files.read(record!.pageId, "style.css")?.toString()).toBe("h1{color:blue}");+ expect(await f.pages.publisher.unpublish({ pageId: record!.pageId })).toMatchObject({ status: 200, card: { state: "unpublished", visibility: "owner" } });+ expect(f.pages.files.has(record!.pageId)).toBe(false);+ expect(f.pages.store.list()).toEqual([]);+ expect(f.service.minted).toEqual([]);+ expect(f.cards.map(({ card }) => [card.state, card.visibility])).toEqual([["unpublished", "owner"], ["unpublished", "owner"]]);+ });++ it("takes the public copy down when a published page becomes owner-only, and updates its cards", async () => {+ const f = setup();+ signIn();+ writeSite(join(f.work, "report"));+ await f.publish({ path: "report" });+ const [publicRecord] = f.pages.store.list();+ expect(f.service.pages.size).toBe(1);+ const switched = await f.publish({ path: "report", visibility: "owner" });+ expect(switched.status).toBe(200);+ expect(f.service.minted.map((call) => call.action)).toEqual(["create", "delete"]);+ expect(f.service.pages.size).toBe(0);+ expect(f.pages.store.get(publicRecord!.pageId)).toMatchObject({ visibility: "owner" });+ expect(new PublishedPagesStore(join(f.data, "published-pages.json")).list()).toEqual([]);+ // The card that showed the old public link now carries the owner-only one.+ expect(f.cards.map(({ card }) => [card.pageId, card.visibility])).toEqual([[publicRecord!.pageId, "owner"], [publicRecord!.pageId, "owner"]]);+ expect(f.cards[0]!.card).toMatchObject({ state: "live", visibility: "owner", url: ownerUrl(publicRecord!.pageId) });+ });++ it("publishes again to the pages Worker with a new link when an owner-only page becomes public", async () => {+ const f = setup();+ signIn();+ writeSite(join(f.work, "report"));+ await f.publish({ path: "report", visibility: "owner" });+ const [local] = f.pages.store.list();+ const switched = await f.publish({ path: "report", visibility: "public" });+ expect(switched.status).toBe(200);+ const [remote] = [...f.service.pages.keys()];+ expect(remote).not.toBe(local!.pageId);+ expect(f.service.minted).toEqual([{ action: "create", caller: "desktop" }]);+ expect(f.pages.files.has(local!.pageId)).toBe(false);+ expect(new PublishedPagesStore(join(f.data, "owner-pages.json")).list()).toEqual([]);+ expect(f.cards.map(({ card }) => [card.pageId, card.visibility])).toEqual([[remote, undefined], [remote, undefined]]);+ expect(f.cards[0]!.card).toMatchObject({ state: "live", url: `https://${remote}.mausbot.page/` });+ });++ it("republishes a live owner-only page from its folder without touching the pages Worker", async () => {+ const f = setup();+ const site = writeSite(join(f.work, "report"));+ await f.publish({ path: "report", visibility: "owner", live: true });+ const [record] = f.pages.store.list();+ writeFileSync(join(site, "style.css"), "h1{color:red}");+ expect(await f.pages.publisher.refreshLive(Date.now() + 61_000)).toBe(1);+ expect(f.pages.files.read(record!.pageId, "style.css")?.toString()).toBe("h1{color:red}");+ expect(f.service.minted).toEqual([]);+ expect(f.pages.store.get(record!.pageId)).toMatchObject({ live: true, visibility: "owner" });+ });+});++describe("pages stored before the visibility setting", () => {+ it("read as public, and keep no visibility once published again", async () => {+ const data = join(dir, "legacy-data");+ mkdirSync(data, { recursive: true });+ const source = await bundle.pageSource(writeSite(join(dir, "legacy-work", "site")), [join(dir, "legacy-work")]);+ const pageId = "a".repeat(32), url = `https://${pageId}.mausbot.page/`;+ writeFileSync(join(data, "published-pages.json"), JSON.stringify({ version: 1, pages: [{ pageId, url, title: "Old report", botId: "bot-1", source,+ cards: [], createdAt: 1, updatedAt: 2, live: true }] }));+ const store = new PagesStore(data);+ expect(store.get(pageId)).toMatchObject({ url, title: "Old report" });+ expect(store.get(pageId)).not.toHaveProperty("visibility");+ expect(store.list()).toHaveLength(1);+ // A service opened on that data publishes the same folder to the Worker, exactly as before the setting existed.+ const service = fakePagesService();+ service.pages.set(pageId, { title: "Old report", files: new Map() });+ signIn();+ const pages = createPublishedPages({ dataDir: data, cloudHome: null, fetch: (input, init) => service.fetch(input, init),+ pageOrigin: () => "https://cloud.example.test", patch: () => {} });+ const outcome = await pages.publisher.publish({ botId: "bot-1", threadId: "thread-1", path: join(dir, "legacy-work", "site"), title: "Old report",+ roots: [join(dir, "legacy-work")], post: () => "m1" });+ expect(outcome.status).toBe(200);+ expect(service.minted).toEqual([{ action: "update", pageId, caller: "desktop" }]);+ expect(new PublishedPagesStore(join(data, "published-pages.json")).get(pageId)).not.toHaveProperty("visibility");+ expect(new PublishedPagesStore(join(data, "owner-pages.json")).list()).toEqual([]);+ });+});+describe("a page tool call whose turn ends", () => {function tool(f: ReturnType<typeof setup>, options: { stopDuringFolders?: boolean; stopAfterToken?: boolean; signal?: AbortSignal } = {}) {const turn = { active: true };@@ -517,10 +632,15 @@ describe("unpublishing a page", () => {};const fromSite = f.publish({ path: "site" });await stored;+ // The draft's folder is read before it queues, so its read resolving proves the update below is queued ahead of the+ // unpublish.+ const read = vi.spyOn(bundle, "readPageBundle");const fromDraft = f.publish({ path: "draft", pageId: page });- await new Promise((resolve) => setTimeout(resolve, 20));+ await vi.waitFor(() => expect(read).toHaveBeenCalled());+ await read.mock.results[0]!.value;+ await new Promise((resolve) => setTimeout(resolve));+ read.mockRestore();const unpublished = f.pages.publisher.unpublish({ pageId: page });- await new Promise((resolve) => setTimeout(resolve, 20));release();expect((await Promise.all([fromSite, fromDraft, unpublished])).map((outcome) => outcome.status)).toEqual([200, 200, 200]);expect(f.service.pages.size).toBe(0);diff --git a/server/pages/publisher.ts b/server/pages/publisher.tsindex ad13d2a348..40618c5d17 100644--- a/server/pages/publisher.ts+++ b/server/pages/publisher.ts@@ -1,9 +1,11 @@-import { PAGE_ID, type PublishedPageCard } from "../../shared/published-page.ts";+import { randomBytes } from "node:crypto";+import { PAGE_ID, type PublishedPageCard, type PublishedPageVisibility } from "../../shared/published-page.ts";import { redactSecretsInText } from "../../shared/redact.ts";import { PageBundleError, pageSignature, pageSource, readPageBundle, skippedNote, stillReadable, type PageBundle } from "./bundle.ts";import { liveFiles } from "./live.ts";import type { PagesCall, PagesClient, PagesFailure, PageUsage } from "./client.ts";-import type { PublishedPagesStore } from "./store.ts";+import type { PublishedPageFiles } from "./owner-files.ts";+import type { PagesStore } from "./store.ts";/** What a publish or unpublish comes to: the sentence for the bot (or the person's card), and whether it failed. */export interface PageOutcome { status: number; text: string; card?: PublishedPageCard }@@ -24,6 +26,8 @@ export interface PublishInput {call?: PagesCall;/** Publish it again by itself whenever its folder changes; kept as it was for a page published before when omitted. */live?: boolean;+ /** Who may open it; kept as it was for a page published before when omitted, and public for a new page. */+ visibility?: PublishedPageVisibility;}const TITLE_MAX = 200;@@ -36,11 +40,15 @@ export function cardText(card: PublishedPageCard): string {if (card.state === "limit") return card.message ?? "This account's pages are used up.";if (card.state === "unpublished") return `Unpublished “${card.title}”. Its link no longer opens.`;if (card.uncertain) return `“${card.title}” may be live: ${card.url}. Unpublish it to remove it.`;+ if (card.visibility === "owner") return `“${card.title}” is published for you: ${card.url}. Only you can open it.`;return `Published “${card.title}”: ${card.url}${card.usage ? ` (${usageWords(card.usage)})` : ""}`;}/** A publish, with the folder's fingerprint when a live republish took it before reading the files. */-type LivePublish = Pick<PublishInput, "botId" | "threadId" | "title" | "pageId" | "post" | "call" | "live"> & { signature?: string | null; refresh?: true };+type LivePublish = Pick<PublishInput, "botId" | "threadId" | "title" | "pageId" | "post" | "call" | "live" | "visibility"> & { signature?: string | null; refresh?: true };++/** Owner-only pages are kept on this server, under the owner's sign-in, instead of being uploaded to the pages Worker. */+const ownerPageId = () => randomBytes(16).toString("hex");/** A live page is published again at most this often, however often its folder changes. */const LIVE_MIN_MS = 60_000;@@ -51,7 +59,11 @@ const failureStatus: Record<PagesFailure["reason"], number> = { sign_in: 403, liexport function createPagePublisher(deps: {client: PagesClient;- store: PublishedPagesStore;+ store: PagesStore;+ /** The owner-only pages' files, kept on this server. */+ files: PublishedPageFiles;+ /** The address this server answers at, which an owner-only page's link names; a path alone when there is none. */+ pageOrigin?: () => string | null;/** Re-draws a card already in a conversation (an unpublished page's). */patch: (threadId: string, messageId: string, text: string, card: PublishedPageCard) => void;/** The folders the bot may read in the conversation of the page's latest card; null once the bot is gone. */@@ -80,7 +92,8 @@ export function createPagePublisher(deps: {const markUnpublished = (pageId: string, usage: PageUsage | null): PublishedPageCard | null => {const record = store.forget(pageId);if (!record) return null;- const card: PublishedPageCard = { state: "unpublished", title: record.title, pageId, url: record.url, ...(usage ? { usage } : {}) };+ const card: PublishedPageCard = { state: "unpublished", title: record.title, pageId, url: record.url,+ ...(record.visibility ? { visibility: record.visibility } : {}), ...(usage ? { usage } : {}) };for (const shown of record.cards) {try { deps.patch(shown.threadId, shown.messageId, cardText(card), card); } catch { /* A conversation deleted since keeps nothing to re-draw. */ }}@@ -107,7 +120,7 @@ export function createPagePublisher(deps: {/** A page built here rather than read from a folder (a chat page the person publishes from the preview); `source`* keeps its link across publishes. */- async publishFiles(input: Pick<PublishInput, "botId" | "threadId" | "title" | "pageId" | "post"> & { source: string; files: PageBundle["files"] }): Promise<PageOutcome> {+ async publishFiles(input: Pick<PublishInput, "botId" | "threadId" | "title" | "pageId" | "post" | "visibility"> & { source: string; files: PageBundle["files"] }): Promise<PageOutcome> {return publishBundle(input, { source: input.source, files: input.files, bytes: input.files.reduce((sum, file) => sum + file.data.byteLength, 0), skipped: [] });},@@ -128,9 +141,56 @@ export function createPagePublisher(deps: {// A republish that waited its turn behind an unpublish, or a publish that turned live off, is no longer wanted.if (input.refresh && !(input.pageId && store.get(input.pageId)?.live)) return { status: 409, text: "The page is no longer live." };const remembered = target ? store.get(target) : null;+ const visibility = input.visibility ?? remembered?.visibility ?? "public";const live = input.live ?? remembered?.live === true;const signature = live ? input.signature ?? null : null;const files = live ? liveFiles(bundle.files) : bundle.files;+ const ownerUrl = (pageId: string) => `${(deps.pageOrigin?.() ?? "").replace(/\/+$/, "")}/api/published-pages/${pageId}/`;+ // A page whose link moved (a visibility switch, or a public page that was replaced) updates every card that shows it.+ const patchOtherCards = (card: PublishedPageCard, messageId: string | null) => {+ for (const shown of remembered?.cards ?? []) {+ if (shown.threadId === input.threadId && shown.messageId === messageId) continue;+ try { deps.patch(shown.threadId, shown.messageId, cardText(card), card); } catch { /* A conversation deleted since keeps nothing to re-draw. */ }+ }+ };+ if (visibility === "owner") {+ const pageId = target ?? ownerPageId(), url = ownerUrl(pageId);+ try {+ deps.files.save(pageId, files);+ } catch {+ return { status: 500, text: "The page couldn't be saved on this server. Check that its data folder has room, then ask again." };+ }+ // A public page becomes owner-only only once its public copy is gone; until then the request is refused and the page+ // stays as it was.+ if (remembered && remembered.visibility !== "owner") {+ let taken: Awaited<ReturnType<PagesClient["unpublish"]>>;+ try {+ taken = await client.unpublish(remembered.pageId, input.call);+ } catch (error) {+ deps.files.remove(pageId);+ throw error;+ }+ if (!taken.ok && taken.reason !== "gone") {+ deps.files.remove(pageId);+ return { status: failureStatus[taken.reason], text: `The page could not be made owner-only: ${taken.message}` };+ }+ store.forgetPublic(remembered.pageId);+ }+ const card: PublishedPageCard = { state: "live", title, pageId, url, visibility: "owner" };+ const messageId = input.post(cardText(card), card, bundle);+ store.published({ pageId, url, title, botId: remembered?.botId ?? input.botId, source: bundle.source,+ card: messageId ? { threadId: input.threadId, messageId } : null, visibility: "owner", live, signature });+ if (remembered?.pageId !== pageId || remembered?.visibility !== "owner") patchOtherCards(card, messageId);+ const updated = Boolean(target) && remembered?.visibility === "owner";+ const lines = [+ updated ? `Updated “${title}” at the same link: ${url}` : `Published “${title}” for you only: ${url}`,+ "Only you can open it, on a device signed in to this server; anyone else who asks finds nothing. It is not on the public web and doesn't use this account's page limit.",+ "A card with the link, Copy link and Unpublish is in the chat. Publishing the same file or folder again updates this same link.",+ ...(live ? ["It is live: when a file in its folder changes, it is published again by itself (at most once a minute)."] : []),+ skippedNote(bundle.skipped),+ ];+ return { status: 200, text: lines.filter(Boolean).join("\n"), card };+ }// A page that may be public is recorded before its upload, so it can always be taken down. Its old fingerprint// stays, so a live page whose upload is uncertain is published again.const uncertainRecord = (page: { pageId: string; url: string }, card: { threadId: string; messageId: string } | null) => store.published({@@ -141,10 +201,12 @@ export function createPagePublisher(deps: {uncertainRecord(page, null);pending = page.pageId;};- let result = await client.publish({ title, files, ...(target ? { pageId: target } : {}), beforeUpload }, input.call);+ // An owner-only page's id means nothing to the pages Worker: it is a public page from here on, with a new link.+ const remoteTarget = remembered?.visibility === "owner" ? undefined : target;+ let result = await client.publish({ title, files, ...(remoteTarget ? { pageId: remoteTarget } : {}), beforeUpload }, input.call);// The page this folder was published to before is gone (unpublished, or taken down): it gets a new link.- if (!result.ok && result.reason === "gone" && !input.pageId && target) {- store.forget(target);+ if (!result.ok && result.reason === "gone" && !input.pageId && remoteTarget) {+ store.forget(remoteTarget);result = await client.publish({ title, files, beforeUpload }, input.call);}if (!result.ok) {@@ -170,6 +232,12 @@ export function createPagePublisher(deps: {const messageId = input.post(cardText(card), card, bundle);store.published({ pageId: result.pageId, url: result.url, title, botId: remembered?.botId ?? input.botId, source: bundle.source,card: messageId ? { threadId: input.threadId, messageId } : null, live, signature });+ // The local copy of a page that was owner-only is gone now that the public page is live.+ if (remembered?.visibility === "owner" && target) {+ deps.files.remove(target);+ store.forgetOwner(target);+ patchOtherCards(card, messageId);+ }const updated = Boolean(target) && result.pageId === target;const lines = [updated ? `Updated “${title}” at the same link: ${result.url}` : `Published “${title}” at ${result.url}`,@@ -183,7 +251,14 @@ export function createPagePublisher(deps: {}async function unpublishNow(pageId: string, call: PagesCall | undefined): Promise<PageOutcome> {- const title = store.get(pageId)?.title;+ const record = store.get(pageId);+ if (record?.visibility === "owner" || (!record && deps.files.has(pageId))) {+ deps.files.remove(pageId);+ const card = markUnpublished(pageId, null)+ ?? { state: "unpublished" as const, title: pageId, pageId, visibility: "owner" as const };+ return { status: 200, text: `Unpublished${record ? ` “${record.title}”` : ""}. Its link no longer opens.`, card };+ }+ const title = record?.title;const result = await client.unpublish(pageId, call);if (!result.ok && result.reason !== "gone") return { status: failureStatus[result.reason], text: result.message };const card = markUnpublished(pageId, result.ok ? result.usage : null)diff --git a/server/pages/service.ts b/server/pages/service.tsindex 49f662a32d..2daf7cbec6 100644--- a/server/pages/service.ts+++ b/server/pages/service.ts@@ -1,3 +1,4 @@+import type { IncomingMessage, ServerResponse } from "node:http";import { join } from "node:path";import type { PublishedPageCard } from "../../shared/published-page.ts";import type { ChatApps } from "../chat-apps.ts";@@ -5,8 +6,10 @@ import { createPagesInternalRoutes, createPublishedPageRoutes } from "../routes/import type { Store } from "../store.ts";import { applyIncludedPagesMessage, pagesAccess, pagesNotOffered } from "./access.ts";import { createPagesClient } from "./client.ts";+import { PublishedPageFiles } from "./owner-files.ts";+import { createOwnerPageLinks } from "./owner-links.ts";import { createPagePublisher } from "./publisher.ts";-import { PublishedPagesStore } from "./store.ts";+import { PagesStore } from "./store.ts";/** How often live published pages' folders are checked for changes. */const LIVE_EVERY_MS = 15_000;@@ -19,6 +22,10 @@ export function createPublishedPages(options: {cloudHome: { adminOrigin: string; machineId: string; bootstrapSecret: string } | null;/** True for `openmausbot serve`: no desktop app hands over a MausBot sign-in and there is no Cloud home. */selfHosted?: boolean;+ /** The address this server answers at, which an owner-only page's link names; a path alone when omitted. */+ pageOrigin?: () => string | null;+ /** True while a paired session is still signed in: an owner-only page's open copy stops answering when it ends. */+ sessionLive?: (sessionId: string) => boolean;patch: (threadId: string, messageId: string, text: string, card: PublishedPageCard) => void;/** Live pages stop when their bot can no longer read the folder, and wait while the workspace is backed up or moved. */liveRoots?(botId: string, threadId: string): readonly string[] | null;@@ -29,7 +36,9 @@ export function createPublishedPages(options: {store: Pick<Store, "botByThread" | "groupByThread" | "messagesFor" | "patchMessage">;};}) {- const store = new PublishedPagesStore(join(options.dataDir, "published-pages.json"));+ const store = new PagesStore(options.dataDir);+ const files = new PublishedPageFiles(join(options.dataDir, "owner-pages"));+ const links = createOwnerPageLinks({ files, ownerPage: (pageId) => store.get(pageId)?.visibility === "owner" });const client = createPagesClient({ access: () => pagesAccess(options.cloudHome), notOffered: () => pagesNotOffered(options.cloudHome),selfHosted: options.selfHosted === true,...(options.fetch ? { fetch: options.fetch } : {}) });@@ -40,7 +49,7 @@ export function createPublishedPages(options: {if (pageRow(threadId, messageId)) apps!.store.patchMessage(threadId, messageId, { publishedPage: card });else options.patch(threadId, messageId, text, card);};- const publisher = createPagePublisher({ client, store, patch, liveRoots: options.liveRoots, paused: options.paused });+ const publisher = createPagePublisher({ client, store, files, patch, liveRoots: options.liveRoots, paused: options.paused, pageOrigin: options.pageOrigin });// Live pages whose folders changed are published again; each at most once a minute (the publisher's own limit).const liveTimer = setInterval(() => { void publisher.refreshLive(); }, LIVE_EVERY_MS);liveTimer.unref?.();@@ -55,7 +64,11 @@ export function createPublishedPages(options: {(pageRow(threadId, messageId) && apps.store.patchMessage(threadId, messageId, { publishedPage }) ? messageId : null),} : undefined;return {- store, publisher, internal: createPagesInternalRoutes(publisher), routes: createPublishedPageRoutes(publisher, appPages), receive: applyIncludedPagesMessage,+ store, files, publisher, internal: createPagesInternalRoutes(publisher),+ routes: createPublishedPageRoutes(publisher, appPages, {+ folder: links.folder, ownerOnly: (pageId) => store.get(pageId)?.visibility === "owner", ...(options.sessionLive ? { sessionLive: options.sessionLive } : {}) }),+ serveFile: (req: IncomingMessage, res: ServerResponse, path: string, method: string) => links.serve(req, res, path, method),+ receive: applyIncludedPagesMessage,/** publish_page's card as the page itself, inline; null when it can't be shown so (the caller posts the link). */show: (args: Parameters<ChatApps["showPublishedPage"]>[0]) => apps?.chat.showPublishedPage(args) ?? null,};diff --git a/server/pages/store.ts b/server/pages/store.tsindex 58319bdd35..5dcb2d7ed1 100644--- a/server/pages/store.ts+++ b/server/pages/store.ts@@ -1,6 +1,6 @@import { mkdirSync, readFileSync } from "node:fs";-import { dirname } from "node:path";-import { PAGE_ID } from "../../shared/published-page.ts";+import { dirname, join } from "node:path";+import { PAGE_ID, type PublishedPageVisibility } from "../../shared/published-page.ts";import { writeFileAtomic } from "../atomic.ts";/** One page this server published: its link, the bot that owns it, the file or folder it came from, and the chat cards@@ -14,6 +14,9 @@ export interface PublishedPageRecord {cards: Array<{ threadId: string; messageId: string }>;createdAt: number;updatedAt: number;+ /** Absent means public. An owner-only page is kept in `owner-pages.json` and served by this server behind the owner's+ * sign-in, never uploaded to the pages Worker. */+ visibility?: PublishedPageVisibility;/** Published again by itself whenever its folder changes (publish_page `live`). */live?: true;/** The folder's fingerprint when it was last published, for a live page. */@@ -63,13 +66,15 @@ export class PublishedPagesStore {return this.records;}- /** Records a publish (a new page or an update) and the card that shows it. */+ /** Records a publish (a new page or an update) and the card that shows it. `visibility` is "owner" only for the separate+ * owner-only file; a public record carries no field, so a page from before the setting reads as public. */published(input: { pageId: string; url: string; title: string; botId: string; source: string; card: { threadId: string; messageId: string } | null;- live?: boolean; signature?: string | null; uncertain?: boolean }, now = Date.now()): PublishedPageRecord {+ live?: boolean; signature?: string | null; uncertain?: boolean; visibility?: PublishedPageVisibility }, now = Date.now()): PublishedPageRecord {const existing = this.get(input.pageId);const cards = [...(existing?.cards ?? []), ...(input.card ? [input.card] : [])].slice(-MAX_CARDS);const record: PublishedPageRecord = { pageId: input.pageId, url: input.url, title: input.title, botId: input.botId, source: input.source, cards,createdAt: existing?.createdAt ?? now, updatedAt: now,+ ...(input.visibility === "owner" ? { visibility: "owner" as const } : {}),...(input.live ? { live: true as const, ...(input.signature ? { signature: input.signature } : {}) } : {}), ...(input.uncertain ? { uncertain: true } : {}) };this.records = [...this.records.filter((each) => each.pageId !== input.pageId), record].slice(-MAX_RECORDS);this.save();@@ -84,3 +89,47 @@ export class PublishedPagesStore {return existing;}}++/** Both files: pages anyone with the link can open (`published-pages.json`, the one every release reads) and owner-only+ * pages (`owner-pages.json`, which a release before this one never opens). Keeping them apart means a rollback leaves an+ * owner-only page untouched and cannot republish it to the public Worker. */+export class PagesStore {+ private readonly publicPages: PublishedPagesStore;+ private readonly ownerPages: PublishedPagesStore;++ constructor(dataDir: string) {+ this.publicPages = new PublishedPagesStore(join(dataDir, "published-pages.json"));+ this.ownerPages = new PublishedPagesStore(join(dataDir, "owner-pages.json"));+ }++ get(pageId: string): PublishedPageRecord | null {+ return this.publicPages.get(pageId) ?? this.ownerPages.get(pageId);+ }++ fromSource(botId: string, source: string): PublishedPageRecord | null {+ return this.publicPages.fromSource(botId, source) ?? this.ownerPages.fromSource(botId, source);+ }++ list(): readonly PublishedPageRecord[] {+ return [...this.publicPages.list(), ...this.ownerPages.list()];+ }++ /** Records an owner-only publish; every other publish is a public page. */+ published(input: Parameters<PublishedPagesStore["published"]>[0], now = Date.now()): PublishedPageRecord {+ return (input.visibility === "owner" ? this.ownerPages : this.publicPages).published(input, now);+ }++ forget(pageId: string): PublishedPageRecord | null {+ return this.publicPages.forget(pageId) ?? this.ownerPages.forget(pageId);+ }++ /** Takes the record from one file only, for a page whose visibility changes: the other file's record stays until the+ * switch has gone through. */+ forgetPublic(pageId: string): PublishedPageRecord | null {+ return this.publicPages.forget(pageId);+ }++ forgetOwner(pageId: string): PublishedPageRecord | null {+ return this.ownerPages.forget(pageId);+ }+}diff --git a/server/published-pages.e2e.test.ts b/server/published-pages.e2e.test.tsindex bd05085e7a..6b0a0881d3 100644--- a/server/published-pages.e2e.test.ts+++ b/server/published-pages.e2e.test.ts@@ -115,6 +115,44 @@ it("publishes a bot's page to a link shown inline, keeps the link and the card o.toEqual([["app", "[App] Bake sale\nBake sale, Saturday", "unpublished"]]);}, 120_000);+it("keeps an owner-only page on this server, opens its stable link through a token folder, and never asks the Worker", async () => {+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: fixture.info.url } }) as Promise<any>;+ const api = async (path: string, init: RequestInit = {}) => (await fetch(`${fixture.info.url}${path}`, { ...init, headers: { "content-type": "application/json" } })).json() as Promise<any>;+ const bot = (await cli("new-bot", "--name", "Private publisher")).bot;+ const site = join(fixture.info.dataDir, "workspaces", bot.id, "private-site");+ mkdirSync(site, { recursive: true });+ writeFileSync(join(site, "index.html"), "<!doctype html><h1>Traffic</h1>");+ writeFileSync(join(site, "data.csv"), "day,hits\nmon,3\n");+ const planPath = join(fixture.info.dataDir, "room-plan.json");+ const before = { pages: stub.service.pages.size, mints: stub.service.minted.length };+ writeFileSync(planPath, JSON.stringify({ [bot.id]: { steps: [{ tool: "publish_page", arguments: { path: "private-site", title: "Traffic", visibility: "owner" } }], reply: "Done." } }));+ await cli("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", "Publish the traffic report for me only.");+ expect((await cli("wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "30")).status).toBe("settled");+ expect(stub.service.pages.size).toBe(before.pages);+ expect(stub.service.minted.length).toBe(before.mints);++ const thread = await api(`/api/threads/${bot.activeTaskId}/messages?limit=50`);+ const card = thread.messages.find((message: any) => message.publishedPage?.visibility === "owner")?.publishedPage;+ expect(card).toMatchObject({ state: "live", title: "Traffic" });+ const link = new URL(card.url);+ expect(link.pathname).toMatch(new RegExp(`^/api/published-pages/${card.pageId}/$`));++ // The owner's own request is moved to the token folder; the token alone opens the page and its files.+ const redirect = await fetch(`${fixture.info.url}${link.pathname}`, { redirect: "manual" });+ expect(redirect.status).toBe(303);+ const folder = redirect.headers.get("location")!;+ expect(folder).toMatch(/^\/api\/owner-page-files\/[A-Za-z0-9_-]{43}\/$/);+ const opened = await realFetch(new URL(folder, fixture.info.url));+ expect(opened.status).toBe(200);+ expect(await opened.text()).toContain("<h1>Traffic</h1>");+ const csv = await realFetch(new URL(`${folder}data.csv`, fixture.info.url));+ expect(csv.status).toBe(200);+ expect(await csv.text()).toBe("day,hits\nmon,3\n");++ expect(await api(`/api/published-pages/${card.pageId}/unpublish`, { method: "POST", body: "{}" })).toMatchObject({ ok: true, card: { state: "unpublished", visibility: "owner" } });+ expect((await realFetch(new URL(folder, fixture.info.url))).status).toBe(404);+}, 120_000);+it.each([false, true])("keeps an Unpublish card when Stop aborts an upload whose Worker committed: %s", async (committed) => {const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: fixture.info.url } }) as Promise<any>;const api = async (path: string, init: RequestInit & { headers?: Record<string, string> } = {}) =>diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 2f7bbe4f19..877717a9e1 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -294,6 +294,16 @@ describe("resolveRequestAuth", () => {});afterEach(() => rmSync(dir, { recursive: true, force: true }));+ it("keeps an owner-only page to the owner's own admin session: an anonymous or client-only request is refused", () => {+ const path = `/api/published-pages/${"a".repeat(32)}/`;+ expect(requiredScope("GET", path)).toBe("admin");+ expect(resolve({ host: "bots.example.com" }, path)).toMatchObject({ auth: null, status: 403 });+ const client = sessions.issue({ label: "phone", scopes: ["client"] });+ expect(resolve({ host: "bots.example.com", authorization: `Bearer ${client.token}` }, path)).toMatchObject({ auth: null, status: 403 });+ const owner = sessions.issue({ label: "owner", scopes: ["admin", "client"] });+ expect(resolve({ host: "bots.example.com", authorization: `Bearer ${owner.token}` }, path).auth).toMatchObject({ kind: "session", scopes: ["admin", "client"] });+ });+it("treats a request the companion carries for a web session as remote: only its own session counts", () => {// The companion's real headers (companion/src/session-route.ts), however the device dressed the request.const carried = (headers: Record<string, string>) =>diff --git a/server/routes/published-pages.test.ts b/server/routes/published-pages.test.tsindex ba851e6206..f9d4d07c6b 100644--- a/server/routes/published-pages.test.ts+++ b/server/routes/published-pages.test.ts@@ -1,7 +1,8 @@import { join } from "node:path";import { describe, expect, it, vi } from "vitest";import type { PagePublisher } from "../pages/publisher.ts";-import { createPagesInternalRoutes, createPublishedPageRoutes, type PagesInternalContext } from "./published-pages.ts";+import type { RequestAuth } from "../request-auth.ts";+import { createPagesInternalRoutes, createPublishedPageRoutes, type OwnerPages, type PagesInternalContext } from "./published-pages.ts";import { PASS, type RouteContext } from "./table.ts";function fakePublisher() {@@ -90,3 +91,46 @@ describe("the card's Unpublish", () => {expect((await call(handler, "/api/published-pages/short/unpublish")).out).toBe(PASS);});});++describe("an owner-only page's stable link", () => {+ const PAGE = "abcdefghijklmnopqrstuvwxyz";+ const HOME: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };+ // The route reads only the kind and scopes through ownerOrAdmin; a real session record is the gate's business.+ const OWNER = { kind: "session", scopes: ["admin", "client"], via: "bearer", session: { id: "s1" } } as unknown as RequestAuth;+ const MEMBER = { kind: "session", scopes: ["client"], via: "bearer", session: { id: "s2" } } as unknown as RequestAuth;++ function ownerPage(only = true, sessionLive?: (id: string) => boolean): OwnerPages {+ return { ownerOnly: () => only, sessionLive, folder: (pageId, viewer) => `/api/owner-page-files/${pageId}-${viewer.key}/` };+ }++ function serve(ownerPages: OwnerPages | undefined, path = `/api/published-pages/${PAGE}/`, method = "GET", auth: RequestAuth = OWNER) {+ const sent: { status?: number; body?: any; headers?: Record<string, string>; written?: unknown; out?: typeof PASS | void } = {};+ const res = {+ headersSent: false, writableEnded: false,+ writeHead: (status: number, headers: Record<string, string>) => { sent.status = status; sent.headers = headers; },+ end: (body?: unknown) => { sent.written = body; },+ };+ return createPublishedPageRoutes(fakePublisher(), undefined, ownerPages)({ req: {} as never, res: res as never,+ url: new URL(path, "https://cloud.example.test"), path, method, auth,+ json: ((_res: unknown, status: number, body: unknown) => { sent.status = status; sent.body = body; }) as never,+ readBody: async () => ({}) } as RouteContext).then((out) => Object.assign(sent, { out }));+ }++ it("moves the owner to the token folder the page loads from, at any file of it", async () => {+ expect(await serve(ownerPage())).toMatchObject({ status: 303, headers: { location: `/api/owner-page-files/${PAGE}-session:s1/`,+ "cache-control": "private, no-store" } });+ expect(await serve(ownerPage(), `/api/published-pages/${PAGE}/data.csv`, "HEAD", HOME)).toMatchObject({ status: 303,+ headers: { location: `/api/owner-page-files/${PAGE}-loopback/data.csv` } });+ });++ it("refuses a viewer who is not the owner, and any page that is not owner-only", async () => {+ expect(await serve(ownerPage(), undefined, "GET", MEMBER)).toMatchObject({ status: 404, body: { error: "Not found." } });+ expect(await serve(ownerPage(), undefined, "GET", { kind: "loopback", scopes: ["client"], trust: "service" })).toMatchObject({ status: 404 });+ expect((await serve(ownerPage(false))).out).toBe(PASS);+ expect((await serve(undefined)).out).toBe(PASS);+ });++ it("moves a page opened without its trailing slash to the folder its files are relative to", async () => {+ expect(await serve(ownerPage(), `/api/published-pages/${PAGE}`)).toMatchObject({ status: 308, headers: { location: `/api/published-pages/${PAGE}/` } });+ });+});diff --git a/server/routes/published-pages.ts b/server/routes/published-pages.tsindex c495d56606..786bd9132c 100644--- a/server/routes/published-pages.ts+++ b/server/routes/published-pages.ts@@ -11,7 +11,9 @@ import { guestWorkspaceToHost } from "../bot-attachment.ts";import { VM_WORKSPACE_GUEST } from "../container-computer.ts";import type { json as sendJson } from "../harness/http.ts";import type { PageBundle } from "../pages/bundle.ts";+import type { OwnerPageViewer } from "../pages/owner-links.ts";import type { PagePublisher } from "../pages/publisher.ts";+import { ownerOrAdmin } from "../request-auth.ts";import { refusalBody, userError } from "../user-errors.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -37,10 +39,12 @@ export interface PagesInternalContext {const PUBLISH = "/api/internal/pages/publish", UNPUBLISH = "/api/internal/pages/unpublish";const UNPUBLISH_ROUTE = /^\/api\/published-pages\/([a-z0-9]{20,63})\/unpublish$/;+const OWNER_PAGE_ROUTE = /^\/api\/published-pages\/([a-z0-9]{20,63})(\/.*)?$/;const APP_PUBLISH_ROUTE = /^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/app\/publish$/;-const appPublishBody = z.object({ rev: z.number().int().min(0).max(1_000_000).optional() }).strict();+const visibility = z.enum(["public", "owner"]).optional();+const appPublishBody = z.object({ rev: z.number().int().min(0).max(1_000_000).optional(), visibility }).strict();const pageId = z.string().max(63).optional();-const publishBody = z.object({ path: z.string().max(4096), title: z.string().max(1000), page_id: pageId, live: z.boolean().optional() });+const publishBody = z.object({ path: z.string().max(4096), title: z.string().max(1000), page_id: pageId, live: z.boolean().optional(), visibility });const unpublishBody = z.object({ page_id: pageId, path: z.string().max(4096).optional() });/** A path inside the bot's Local VM workspace means the same file on this computer. */@@ -57,9 +61,10 @@ export function createPagesInternalRoutes(publisher: PagePublisher) {let outcome;if (ctx.path === PUBLISH) {const body = publishBody.safeParse(raw ?? {});- if (!body.success) return void ctx.json(ctx.res, 400, { error: "publish_page takes path, title and optionally page_id (text) and live (true or false)." });+ if (!body.success) return void ctx.json(ctx.res, 400, { error: "publish_page takes path, title and optionally page_id (text), live (true or false) and visibility (public or owner)." });outcome = await publisher.publish({ botId: ctx.botId, threadId: ctx.threadId, path: hostPath(body.data.path, vmWorkspace), title: body.data.title,...(body.data.page_id ? { pageId: body.data.page_id } : {}), ...(body.data.live !== undefined ? { live: body.data.live } : {}),+ ...(body.data.visibility ? { visibility: body.data.visibility } : {}),roots: folders, post: ctx.post, call });} else {const body = unpublishBody.safeParse(raw ?? {});@@ -84,28 +89,57 @@ export interface AppPages {/** A chat page keeps one link however often it is published again: a folder page shares its folder's with publish_page. */export const appPageSource = (threadId: string, messageId: string) => `app:${threadId}/${messageId}`;-/** POST /api/published-pages/<pageId>/unpublish: the card's Unpublish. POST .../messages/<id>/app/publish: a page card's- * Share. Both admin-scope routes, so only the owner's own app. */-export function createPublishedPageRoutes(publisher: PagePublisher, apps?: AppPages): RouteHandler {- return async ({ req, res, path, method, json, readBody }) => {+export interface OwnerPages {+ /** The token folder the page loads from for this viewer (pages/owner-links.ts). */+ folder(pageId: string, viewer: OwnerPageViewer): string;+ /** True for a page this server keeps for the owner alone (`owner-pages.json`); never for a public page. */+ ownerOnly(pageId: string): boolean;+ /** True while the session that opened the page is still signed in; absent trusts the token's own lifetime. */+ sessionLive?(sessionId: string): boolean;+}++/** GET /api/published-pages/<pageId>/: an owner-only page's stable link, which moves a viewer the owner's own sign-in+ * vouches for to the token folder the sandboxed page loads from. Anonymous requests never reach it: the sign-in gate+ * answers first. POST /api/published-pages/<pageId>/unpublish: the card's Unpublish. POST .../messages/<id>/app/publish: a+ * page card's Share. All admin-scope routes, so only the owner's own app. */+export function createPublishedPageRoutes(publisher: PagePublisher, apps?: AppPages, ownerPages?: OwnerPages): RouteHandler {+ return async ({ req, res, path, method, auth, json, readBody }) => {const match = UNPUBLISH_ROUTE.exec(path);if (match && method === "POST") {const outcome = await publisher.unpublish({ pageId: match[1] });return void json(res, outcome.status, outcome.status === 200 ? { ok: true, card: outcome.card } : { error: outcome.text });}+ if ((method === "GET" || method === "HEAD") && ownerPages) {+ const page = OWNER_PAGE_ROUTE.exec(path);+ if (page && ownerPages.ownerOnly(page[1]!)) {+ // Security: a member, a guest and a service-trust bot shell read this as a page that does not exist.+ if (!ownerOrAdmin(auth)) return void json(res, 404, { error: "Not found." });+ if (page[2] === undefined) {+ res.writeHead(308, { location: `${path}/`, "cache-control": "private, no-store" });+ res.end();+ return;+ }+ // Its sandbox sends no cookie with the page's own files, so it loads from a token folder minted for this viewer.+ const viewer: OwnerPageViewer = { key: auth.kind === "session" ? `session:${auth.session.id}` : auth.kind,+ allowed: () => auth.kind !== "session" || (ownerPages.sessionLive?.(auth.session.id) ?? true) };+ res.writeHead(303, { location: `${ownerPages.folder(page[1]!, viewer)}${page[2].slice(1)}`, "cache-control": "private, no-store" });+ res.end();+ return;+ }+ }const page = apps ? APP_PUBLISH_ROUTE.exec(path) : null;if (!apps || !page || method !== "POST") return PASS;const [, threadId, messageId] = page as unknown as [string, string, string];const bot = apps.botOf(threadId);if (!bot) return void json(res, 404, userError("serverError.page.roomOrClosed"));const body = appPublishBody.safeParse(await readBody(req, 4_096) ?? {});- if (!body.success) return void json(res, 400, { error: "Publish takes an optional rev, the version to publish." });+ if (!body.success) return void json(res, 400, { error: "Publish takes an optional rev, the version to publish, and visibility, public or owner." });const built = apps.page(threadId, messageId, body.data.rev);if (!built.ok) return void json(res, built.status, refusalBody(built));const pageId = apps.published(threadId, messageId);const outcome = await publisher.publishFiles({botId: bot.id, threadId, source: built.folder ?? appPageSource(threadId, messageId), title: built.title, files: built.files,- ...(pageId ? { pageId } : {}),+ ...(pageId ? { pageId } : {}), ...(body.data.visibility ? { visibility: body.data.visibility } : {}),post: (_text, card) => (card.state === "live" ? apps.show(threadId, messageId, card) : null),});json(res, outcome.status, outcome.status === 200 ? { ok: true, card: outcome.card } : { error: outcome.text, ...(outcome.card ? { card: outcome.card } : {}) });diff --git a/shared/published-apps.ts b/shared/published-apps.tsindex 1d6fd3afc4..fe53fd328e 100644--- a/shared/published-apps.ts+++ b/shared/published-apps.ts@@ -13,9 +13,9 @@ export interface PublishedApp {/** 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";+ /** `link`: anyone who has the link. `owner`: only the owner's own signed-in devices. `public`: the site answered+ * without a login. `netlify-team`: it asked for a Netlify login when last checked. */+ access: "link" | "owner" | "public" | "netlify-team" | "unknown";/** The site's page in the person's Netlify account. */manageUrl?: string;/** An included app that can't be opened: `taken_down` by MausBot, or `not_live` because no publish of it hasdiff --git a/src/components/PublishedPageCard.test.ts b/src/components/PublishedPageCard.test.tsindex f976c222da..4e4ad3c3ec 100644--- a/src/components/PublishedPageCard.test.ts+++ b/src/components/PublishedPageCard.test.ts@@ -98,6 +98,16 @@ describe("a published page's card", () => {}});+ it("marks an owner-only page as only you, with no page usage", () => {+ const { container, root } = render(page({ ...live.publishedPage!, visibility: "owner", usage: undefined }));+ try {+ expect(container.textContent).toContain("Bake sale");+ expect(container.querySelector("[data-page-owner-only]")?.textContent).toBe("Only you");+ expect(container.textContent).not.toContain("of 5 pages");+ expect(buttons(container).map((button) => button.textContent)).toEqual(["Copy link", "Open", "Unpublish"]);+ } finally { root.unmount(); }+ });+it("says when the page was unpublished, with no buttons", () => {const { container, root } = render(page({ state: "unpublished", title: "Bake sale", pageId: "abcdefghijklmnopqrstuvwxyz", url: URL, usage: { pages: 2, limit: 5 } }));try {diff --git a/src/components/PublishedPageCard.tsx b/src/components/PublishedPageCard.tsxindex 1f9b00f380..e3349b16f5 100644--- a/src/components/PublishedPageCard.tsx+++ b/src/components/PublishedPageCard.tsx@@ -1,5 +1,5 @@import { useState } from "react";-import { ArrowUpRight, Check, Copy, Globe, Loader2, X } from "lucide-react";+import { ArrowUpRight, Check, Copy, Globe, Loader2, Lock, X } from "lucide-react";import type { PublishedPageCard as Card } from "../../shared/published-page";import { cloudPlanLabel } from "@/lib/cloud-plan";import { cn } from "@/lib/cn";@@ -36,12 +36,13 @@ export function PublishedPageCard({ message }: { message: Message }) {catch { setFailed(true); }finally { setBusy(false); }};- const usage = usageLine(card);+ const usage = usageLine(card), owner = card.visibility === "owner";return (<div data-published-page={card.pageId ?? "limit"} className="w-full max-w-md overflow-hidden rounded-xl border border-hairline/40 bg-panel px-3 py-2.5 text-sm"><div className="flex min-w-0 items-center gap-2">- <Globe size={16} className="shrink-0 text-ink-tertiary" aria-hidden="true" />+ {owner ? <Lock size={16} className="shrink-0 text-ink-tertiary" aria-hidden="true" /> : <Globe size={16} className="shrink-0 text-ink-tertiary" aria-hidden="true" />}<span dir="auto" className="min-w-0 truncate font-medium text-ink" title={card.title}>{card.title}</span>+ {owner && <span data-page-owner-only className="shrink-0 rounded-full bg-ink/[0.06] px-2 py-px text-xs text-ink-secondary">{t("chat.page.ownerOnly")}</span>}{usage && <span className="ms-auto shrink-0 text-xs text-ink-tertiary">{usage}</span>}</div>{card.state === "live" && card.url && <>diff --git a/src/components/app/PageTools.test.ts b/src/components/app/PageTools.test.tsindex 4b02a980ca..ec19c638d5 100644--- a/src/components/app/PageTools.test.ts+++ b/src/components/app/PageTools.test.ts@@ -33,6 +33,8 @@ const openExternal = vi.fn(async () => true);const store = { state: {}, dispatch: vi.fn(), flushBotPatches: vi.fn(async () => null) } as unknown as ReturnType<typeof useStore>;const LINK = "https://page000000000000000000001.mausbot.page/";const LIVE: PublishedPageCard = { state: "live", title: "Pricing", pageId: "page000000000000000000001", url: LINK, usage: { pages: 1, limit: 5 } };+const OWNER: PublishedPageCard = { state: "live", title: "Pricing", pageId: "page000000000000000000001",+ url: "https://cloud.example.test/api/published-pages/page000000000000000000001/", visibility: "owner" };let host: HTMLDivElement;let root: Root;@@ -70,9 +72,12 @@ const PICK = { jsonrpc: "2.0", method: POINTED_METHOD, params: { tag: "button",beforeEach(() => {fetchMock.mockReset();- fetchMock.mockImplementation(async (path) => {+ fetchMock.mockImplementation(async (path, init) => {const url = new URL(path, "http://omb.test");- if (url.pathname.endsWith("/app/publish")) return json(200, { ok: true, card: LIVE });+ if (url.pathname.endsWith("/app/publish")) {+ const asked = JSON.parse(String(init?.body ?? "{}")) as { visibility?: string };+ return json(200, { ok: true, card: asked.visibility === "owner" ? OWNER : LIVE });+ }if (url.pathname.endsWith("/unpublish")) return json(200, { ok: true, card: { ...LIVE, state: "unpublished" } });const rev = url.searchParams.get("rev");return json(200, botHtmlDocument({ messageId: "a1", rev: rev === null ? 0 : Number(rev), html: `<p>${rev === null ? "newest" : `version ${Number(rev) + 1}`}</p>` }));@@ -188,6 +193,32 @@ describe("a bot's page in the chat", () => {expect(button("Open in new tab", card()).disabled).toBe(true);});+ it("chooses only you before sharing, and shares it that way", async () => {+ await render(row(payload()));+ await click("Anyone with the link", card());+ expect(button("Only you", card()).getAttribute("aria-pressed")).toBe("true");+ await click("Share", card());+ await settle();+ expect(posts("/app/publish")).toEqual([{ rev: 0, visibility: "owner" }]);+ });++ it("switches a published page between anyone with the link and only you", async () => {+ await render(row(payload(), LIVE));+ const chip = () => card().querySelector<HTMLElement>("[data-page-visibility]")!;+ expect(chip().textContent).toContain("Anyone with the link");+ expect(chip().getAttribute("aria-pressed")).toBe("false");+ await click("Anyone with the link", card());+ await settle();+ expect(posts("/app/publish")).toEqual([{ rev: 0, visibility: "owner" }]);+ expect(chip().textContent).toContain("Only you");+ expect(chip().getAttribute("aria-pressed")).toBe("true");+ await render(row(payload(), OWNER));+ expect(card().querySelector("[data-page-link]")?.textContent).toContain("Published for you");+ await click("Only you", card());+ await settle();+ expect(posts("/app/publish")).toEqual([{ rev: 0, visibility: "owner" }, { rev: 0 }]);+ });+it("shows publish_page's link on the page it published", async () => {await render(row(payload(), LIVE));expect(card().querySelector("[data-page-link]")?.textContent).toContain("Published");diff --git a/src/components/app/PageTools.tsx b/src/components/app/PageTools.tsxindex b47304affe..ff027804bb 100644--- a/src/components/app/PageTools.tsx+++ b/src/components/app/PageTools.tsx@@ -1,7 +1,7 @@// A bot's page in the chat, artifact-style: its version stepper, Point, Share, Open in new tab and Full screen.import { createContext, useCallback, useEffect, useRef, useState, type MutableRefObject, type ReactNode } from "react";import { createPortal } from "react-dom";-import { ArrowUpRight, Check, ChevronLeft, ChevronRight, Copy, Crosshair, Download, Globe, Loader2, Maximize2, Pin, PinOff, Share2, Trash2, X } from "lucide-react";+import { ArrowUpRight, Check, ChevronLeft, ChevronRight, Copy, Crosshair, Download, Globe, Loader2, Lock, Maximize2, Pin, PinOff, Share2, Trash2, X } from "lucide-react";import { useStore } from "@/state/store";import { openExternalLink } from "@/lib/app-links";import { cn } from "@/lib/cn";@@ -14,7 +14,7 @@ import { latestWebPanels, setWebPanels, useWebPanels } from "@/lib/web-panel-preimport { findPinnedPage, MAX_WEB_PANELS, togglePinnedPage, type PinnedChatPage } from "@/lib/web-panels";import type { AppDocument, AppPayload } from "../../../shared/app";import { marksMessage, pointMessage, readPointEvent } from "../../../shared/app-frame/point";-import type { PublishedPageCard } from "../../../shared/published-page";+import type { PublishedPageCard, PublishedPageVisibility } from "../../../shared/published-page";import { canonicalDownloadFilename } from "../AttachmentPreview";import { appDownloadPath, publishAppPage, unpublishPage } from "./app-api";import { AppFrame, type AppFrameHandle } from "./AppFrame";@@ -61,18 +61,24 @@ type Share =| { kind: "unpublishing" }| { kind: "unpublish-failed" };-/** The page's public link, as the row's published card says (publish_page's, or this card's own Share), and Share and- * Unpublish. The server patches the card, so every window sees the same link. */+/** The page's link, as the row's published card says (publish_page's, or this card's own Share), who may open it, and+ * Share and Unpublish. The server patches the card, so every window sees the same link. */export function usePageShare(threadId: string, messageId: string, published: PublishedPageCard | undefined) {const [share, setShare] = useState<Share>({ kind: "idle" });const [again, setAgain] = useState(false);+ const [visibility, setVisibility] = useState<PublishedPageVisibility>(published?.visibility ?? "public");+ useEffect(() => { setVisibility(published?.visibility ?? "public"); }, [published?.visibility]);const live = published?.state === "live" && published.url ? published : null;- const run = async (rev: number) => {+ const run = async (rev: number, next: PublishedPageVisibility = visibility) => {+ const sameLink = next === (published?.visibility ?? "public");setShare({ kind: "busy" });- const outcome = await publishAppPage(threadId, messageId, rev);- setAgain(Boolean(live) && outcome.ok);- if (outcome.ok) setShare({ kind: "idle" });- else setShare({ kind: "refused", text: outcome.card?.message ?? outcome.error, ...(outcome.card ? { card: outcome.card } : {}) });+ const outcome = await publishAppPage(threadId, messageId, rev, next);+ // A visibility switch publishes to a new link: "updated at the same link" would be false.+ setAgain(Boolean(live) && outcome.ok && sameLink);+ if (outcome.ok) {+ setVisibility(next);+ setShare({ kind: "idle" });+ } else setShare({ kind: "refused", text: outcome.card?.message ?? outcome.error, ...(outcome.card ? { card: outcome.card } : {}) });};const unpublish = async () => {if (!live?.pageId) return;@@ -80,7 +86,8 @@ export function usePageShare(threadId: string, messageId: string, published: PubsetShare(await unpublishPage(live.pageId) ? { kind: "idle" } : { kind: "unpublish-failed" });setAgain(false);};- return { share, url: live?.url, again, unpublished: published?.state === "unpublished", run, unpublish };+ const toggleVisibility = () => setVisibility((current) => (current === "owner" ? "public" : "owner"));+ return { share, url: live?.url, visibility, again, unpublished: published?.state === "unpublished", run, unpublish, toggleVisibility };}/** On a phone the OS share sheet (Save to Files, Share); elsewhere a download, which Electron turns into its save dialog. */@@ -217,7 +224,7 @@ export interface PageToolsProps {/** The card's toolbar: ‹ v2 › and Updated on the left; Point, Share, Open in new tab and Full screen on the right. */export function PageToolbar({ version, point, share, save, ready, fullScreen, room, pin, saveApp, className }: PageToolsProps & { className?: string }) {const label = version.latest ? t("chat.preview.version", { n: version.rev + 1 }) : t("chat.preview.versionOf", { n: version.rev + 1, count: version.last + 1 });- const busy = share.share.kind === "busy";+ const busy = share.share.kind === "busy", owner = share.visibility === "owner";return (<div data-page-tools className={cn("flex flex-wrap items-center gap-x-1.5 gap-y-2", className)}><div className="flex items-center gap-0.5 text-[13px] text-ink-secondary">@@ -235,6 +242,12 @@ export function PageToolbar({ version, point, share, save, ready, fullScreen, ro<Crosshair size={14} />{t("chat.preview.point")}</button>{!room && <>+ {!share.url && (+ <button type="button" data-page-visibility aria-pressed={owner} onClick={share.toggleVisibility} disabled={busy}+ title={t(owner ? "chat.page.makePublicHint" : "chat.page.makeOwnerHint")} className={cn(ASK_CHIP, owner ? ASK_CHIP_PICKED : ASK_CHIP_IDLE)}>+ {owner ? <Lock size={14} /> : <Globe size={14} />}{t(owner ? "chat.page.ownerOnly" : "chat.page.anyoneLink")}+ </button>+ )}<button type="button" onClick={() => void share.run(version.rev)} disabled={busy} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>{busy ? <Loader2 size={14} className="animate-spin" /> : <Share2 size={14} />}{t("chat.preview.share")}</button>@@ -271,18 +284,25 @@ export function PageToolbar({ version, point, share, save, ready, fullScreen, roexport function PageNotes({ version, point, share, save, room, className }: Pick<PageToolsProps, "version" | "point" | "share" | "save" | "room"> & { className?: string }) {const { dispatch } = useStore();const { state: copied, copy } = useCopyFeedback(share.url ?? "");- const state = share.share;+ const state = share.share, owner = share.visibility === "owner";const rows: ReactNode[] = [];if (share.url) {rows.push(<div key="link" data-page-link className="flex min-w-0 flex-wrap items-center gap-2 rounded-2xl bg-inset px-3 py-2 text-[13px]">- <Globe size={14} className="shrink-0 text-ink-tertiary" aria-hidden="true" />- <span className="shrink-0 font-medium text-ink">{share.again ? t("chat.preview.updatedLink") : t("chat.preview.published")}</span>+ {owner ? <Lock size={14} className="shrink-0 text-ink-tertiary" aria-hidden="true" /> : <Globe size={14} className="shrink-0 text-ink-tertiary" aria-hidden="true" />}+ <span className="shrink-0 font-medium text-ink">{share.again ? t("chat.preview.updatedLink") : t(owner ? "chat.page.ownerPublished" : "chat.preview.published")}</span><a href={share.url} dir="ltr" onClick={(event) => { event.preventDefault(); void openExternalLink(share.url!); }}className="min-w-0 flex-1 truncate text-accent-text hover:underline">{share.url}</a><button type="button" onClick={copy} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>{copied === "copied" ? <Check size={14} /> : <Copy size={14} />}{t(copied === "copied" ? "chat.page.copied" : "chat.page.copyLink")}</button>+ {!room && (+ <button type="button" data-page-visibility aria-pressed={owner} disabled={state.kind === "busy"}+ title={t(owner ? "chat.page.makePublicHint" : "chat.page.makeOwnerHint")}+ onClick={() => void share.run(version.rev, owner ? "public" : "owner")} className={cn(ASK_CHIP, owner ? ASK_CHIP_PICKED : ASK_CHIP_IDLE)}>+ {owner ? <Lock size={14} /> : <Globe size={14} />}{t(owner ? "chat.page.ownerOnly" : "chat.page.anyoneLink")}+ </button>+ )}{!room && (<button type="button" onClick={() => void share.run(version.rev)} disabled={state.kind === "busy"} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>{t("chat.preview.republish")}diff --git a/src/components/app/app-api.ts b/src/components/app/app-api.tsindex fd62073bfc..df7e70962f 100644--- a/src/components/app/app-api.ts+++ b/src/components/app/app-api.ts@@ -1,7 +1,7 @@import { t } from "@/lib/i18n";import { api, ApiError } from "@/state/store";import type { AppBlockedReason, AppDocument } from "../../../shared/app";-import type { PublishedPageCard } from "../../../shared/published-page";+import type { PublishedPageCard, PublishedPageVisibility } from "../../../shared/published-page";import { RPC_HOST_REFUSED, type AppContextUpdate, type AppRpcMethod, type JsonRpcError, type PageRpcMethod } from "../../../shared/app-frame/bridge";import { randomUuid } from "@/lib/random-uuid";@@ -121,10 +121,12 @@ export async function sendAppMessage(args: { botId: string; threadId: string; meexport type PagePublishOutcome = { ok: true; card: PublishedPageCard } | { ok: false; error: string; card?: PublishedPageCard };-/** Publishes the version on screen to a public link, the same link every time. */-export async function publishAppPage(threadId: string, messageId: string, rev: number): Promise<PagePublishOutcome> {+/** Publishes the version on screen to a public link, or one only the owner's signed-in devices can open, the same link+ * every time while its visibility stays the same. */+export async function publishAppPage(threadId: string, messageId: string, rev: number, visibility?: PublishedPageVisibility): Promise<PagePublishOutcome> {try {- const body = await api<{ card: PublishedPageCard }>(`${appDocumentPath(threadId, messageId)}/publish`, { method: "POST", body: JSON.stringify({ rev }) });+ const body = await api<{ card: PublishedPageCard }>(`${appDocumentPath(threadId, messageId)}/publish`, {+ method: "POST", body: JSON.stringify(visibility === "owner" ? { rev, visibility } : { rev }) });return { ok: true, card: body.card };} catch (error) {if (!(error instanceof ApiError)) return { ok: false, error: OFFLINE_ERROR.message };diff --git a/src/components/published-apps/PublishedAppCard.tsx b/src/components/published-apps/PublishedAppCard.tsxindex 467a9b0086..95fd036228 100644--- a/src/components/published-apps/PublishedAppCard.tsx+++ b/src/components/published-apps/PublishedAppCard.tsx@@ -10,7 +10,7 @@ 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,+ public: "publishedApps.access.public", "netlify-team": "publishedApps.access.netlifyTeam", link: "publishedApps.access.link", owner: "publishedApps.access.owner", unknown: null,};const SOURCE: Record<PublishedApp["source"], LocaleKey> = {diff --git a/src/locales/en.json b/src/locales/en.jsonindex cf38252006..2b672cbe72 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7382,6 +7382,7 @@"publishedApps.access.public": "Public","publishedApps.access.netlifyTeam": "Only your Netlify team","publishedApps.access.link": "Anyone with the link",+ "publishedApps.access.owner": "Only you","publishedApps.card.preview": "Preview","publishedApps.card.previewOf": "Preview {name}","publishedApps.card.ask": "Ask {bot} to change it",@@ -8221,6 +8222,11 @@"chat.page.freeLimit": "You’ve used your {limit} free pages. MausBot Cloud gives you more, and pages without the badge.","chat.page.planLimit": "You’ve used all {limit} pages on your {plan} plan. Unpublish a page to make room.","chat.page.morePages": "Get more pages",+ "chat.page.ownerOnly": "Only you",+ "chat.page.anyoneLink": "Anyone with the link",+ "chat.page.ownerPublished": "Published for you",+ "chat.page.makeOwnerHint": "Only you can open it",+ "chat.page.makePublicHint": "Anyone with the link can open it","chat.preview.older": "Earlier version","chat.preview.newer": "Later version","chat.preview.version": "v{n}",