Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Owner-only pages: the <base> is allowed by the page's policy, every desktop open gets the one-time link, and the code has its own name
milind-soni6e2969fd6ac7
diff --git a/server/pages/owner-links.test.ts b/server/pages/owner-links.test.tsindex e724f1ef96..c25e1a6d03 100644--- a/server/pages/owner-links.test.ts+++ b/server/pages/owner-links.test.ts@@ -4,7 +4,7 @@ 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, OWNER_PAGE_COOKIE } from "./owner-links.ts";+import { createOwnerPageLinks, OWNER_PAGE_CODE, OWNER_PAGE_COOKIE } from "./owner-links.ts";const PAGE = "abcdefghijklmnopqrstuvwxyz";const STABLE = `/api/published-pages/${PAGE}/`;@@ -67,6 +67,7 @@ describe("an owner-only page's stable link", () => {expect(sent.headers).not.toHaveProperty("access-control-allow-origin");expect(String(sent.headers!["content-security-policy"])).toContain("sandbox allow-scripts");expect(String(sent.headers!["content-security-policy"])).toContain("https://cloud.example.test");+ expect(String(sent.headers!["content-security-policy"])).toContain("base-uri https://cloud.example.test/api/owner-page-files/;");expect(baseOf(sent.body)).toMatch(/^\/api\/owner-page-files\/[A-Za-z0-9_-]{43}\/$/);expect(String(sent.body)).toContain("<h1>Traffic</h1>");expect(String(sent.body)).not.toContain("<!doctype html><h1>");@@ -127,18 +128,17 @@ describe("an owner-only page's token folder", () => {});describe("opening an owner-only page in a browser that is not signed in", () => {- const codeOf = (url: string) => new URL(url).searchParams.get("code")!;+ const codeOf = (url: string) => new URL(url).searchParams.get(OWNER_PAGE_CODE)!;it("spends a one-time code for a page cookie, and moves the browser to the link without the code", () => {const links = linksFor();const url = links.openUrl(PAGE, OWNER);- expect(url).toMatch(new RegExp(`^https://cloud\\.example\\.test${STABLE}\\?code=[A-Za-z0-9_-]{43}$`));- const spent = early(links, `${STABLE}?code=${codeOf(url)}&period=2026-11`, { host: "cloud.example.test", "x-forwarded-proto": "https" });+ expect(url).toMatch(new RegExp(`^https://cloud\\.example\\.test${STABLE}\\?${OWNER_PAGE_CODE}=[A-Za-z0-9_-]{43}$`));+ const spent = early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(url)}&period=2026-11`, { host: "cloud.example.test", "x-forwarded-proto": "https" });expect(spent).toMatchObject({ handled: true, status: 303, headers: { location: `${STABLE}?period=2026-11` } });const cookie = String(spent.headers!["set-cookie"]);expect(cookie).toMatch(new RegExp(`^${OWNER_PAGE_COOKIE}=[A-Za-z0-9_-]{43}; Path=${STABLE}; HttpOnly; SameSite=Lax; Max-Age=86400; Secure$`));- const again = early(links, `${STABLE}?code=${codeOf(url)}`);- expect(again).toMatchObject({ handled: true, status: 404 });+ expect(early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(url)}`).handled, "a spent code leaves the request to the gate").toBe(false);const held = cookie.split(";")[0]!;const opened = early(links, STABLE, { cookie: `other=1; ${held}`, host: "cloud.example.test" });@@ -146,9 +146,10 @@ describe("opening an owner-only page in a browser that is not signed in", () =>expect(baseOf(opened.body)).toMatch(/^\/api\/owner-page-files\//);});- it("leaves the gate to answer a browser with no code and no cookie, or a cookie for nothing", () => {+ it("leaves the gate to answer a browser with no code and no cookie, a cookie for nothing, or a page's own code query", () => {const links = linksFor();expect(early(links, STABLE).handled).toBe(false);+ expect(early(links, `${STABLE}?code=abc`).handled).toBe(false);expect(early(links, STABLE, { cookie: `${OWNER_PAGE_COOKIE}=${"a".repeat(43)}` }).handled).toBe(false);});@@ -157,9 +158,9 @@ describe("opening an owner-only page in a browser that is not signed in", () =>const links = linksFor({ now: () => now });const stale = links.openUrl(PAGE, OWNER);now += 2 * 60_000 + 1;- expect(early(links, `${STABLE}?code=${codeOf(stale)}`)).toMatchObject({ handled: true, status: 404 });+ expect(early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(stale)}`).handled).toBe(false);const fresh = links.openUrl(PAGE, { key: "session:s1", allowed: () => live });- const cookie = String(early(links, `${STABLE}?code=${codeOf(fresh)}`).headers!["set-cookie"]).split(";")[0]!;+ const cookie = String(early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(fresh)}`).headers!["set-cookie"]).split(";")[0]!;expect(early(links, STABLE, { cookie }).handled).toBe(true);live = false;expect(early(links, STABLE, { cookie }).handled).toBe(false);@@ -168,7 +169,7 @@ describe("opening an owner-only page in a browser that is not signed in", () =>it("stops answering a cookie once the page is no longer owner-only", () => {let owner = true;const links = linksFor({ ownerPage: () => owner });- const cookie = String(early(links, `${STABLE}?code=${codeOf(links.openUrl(PAGE, OWNER))}`).headers!["set-cookie"]).split(";")[0]!;+ const cookie = String(early(links, `${STABLE}?${OWNER_PAGE_CODE}=${codeOf(links.openUrl(PAGE, OWNER))}`).headers!["set-cookie"]).split(";")[0]!;owner = false;expect(early(links, STABLE, { cookie }).handled).toBe(false);});diff --git a/server/pages/owner-links.ts b/server/pages/owner-links.tsindex b52a5f8dc3..3cc6cd05d0 100644--- a/server/pages/owner-links.ts+++ b/server/pages/owner-links.ts@@ -2,7 +2,7 @@// - The page's address is its stable link, /api/published-pages/<id>/. It answers only the owner: a request the sign-in// gate vouches for (an admin session, or this computer's own app), or a browser holding the page's own cookie.// - That cookie comes from a one-time code. The owner's app asks for one (POST .../open) and opens the stable link with-// `?code=` in a browser; the code is spent on first use, two minutes at most, and the answer moves the browser to the+// `?omb_page_code=` in a browser; the code is spent on first use, two minutes at most, and the answer moves the browser to the// link without it. The cookie is HttpOnly, scoped to that page's path, and answers only while the page is still// owner-only and the session that asked for it is still signed in.// - The page runs in an opaque-origin sandbox, which sends no cookie with its own files, so its relative URLs resolve to@@ -22,6 +22,8 @@ import type { PublishedPageFiles } from "./owner-files.ts";export const OWNER_PAGE_FILES_PREFIX = "/api/owner-page-files/";export const OWNER_PAGE_PREFIX = "/api/published-pages/";export const OWNER_PAGE_COOKIE = "omb_owner_page";+/** The one-time code's query name: one a page is unlikely to use for itself. */+export const OWNER_PAGE_CODE = "omb_page_code";const OWNER_PAGE_PATH = /^\/api\/published-pages\/([a-z0-9]{20,63})(\/.*)?$/;const TOKEN = /^[A-Za-z0-9_-]{43}$/;const DAY_MS = 24 * 60 * 60_000;@@ -34,6 +36,8 @@ const MAX_CODES = 200;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}`;+ // The page's relative URLs resolve to its token folder through the <base> written ahead of it.+ if (directive === "base-uri 'none'") return `base-uri ${origin}${OWNER_PAGE_FILES_PREFIX}`;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");}@@ -146,7 +150,7 @@ export function createOwnerPageLinks(deps: {sweep(codes, CODE_MS, MAX_CODES);const code = token();codes.set(code, { pageId, viewer: viewer.key, allowed: viewer.allowed, used: now() });- return `${(deps.pageOrigin?.() ?? "").replace(/\/+$/, "")}${OWNER_PAGE_PREFIX}${pageId}/?code=${code}`;+ return `${(deps.pageOrigin?.() ?? "").replace(/\/+$/, "")}${OWNER_PAGE_PREFIX}${pageId}/?${OWNER_PAGE_CODE}=${code}`;},/** Ahead of the sign-in gate: the token folders, a code being spent, and the stable link for a browser holding the@@ -200,18 +204,16 @@ export function createOwnerPageLinks(deps: {if (!page || (method !== "GET" && method !== "HEAD") || !deps.ownerPage(page[1]!)) return false;const pageId = page[1]!;const params = new URLSearchParams(search);- const code = params.get("code");- if (code !== null) {- const grant = codes.get(code);- codes.delete(code);- if (!live(grant, pageId, CODE_MS)) {- answer(res, 404, "This link has expired. Open the page again from the app.");- return true;- }+ const code = params.get(OWNER_PAGE_CODE);+ const granted = code === null ? undefined : codes.get(code);+ if (code !== null) codes.delete(code);+ // A spent or unknown code is ignored: the page's cookie, or the owner's sign-in at the gate, may still open it.+ if (code !== null && live(granted, pageId, CODE_MS)) {+ const grant = granted;sweep(cookies, DAY_MS, MAX_TOKENS);const cookie = token();cookies.set(cookie, { ...grant, used: now() });- params.delete("code");+ params.delete(OWNER_PAGE_CODE);const rest = params.toString();const secure = requestOrigin(req)?.startsWith("https://") === true;redirect(res, 303, `${OWNER_PAGE_PREFIX}${pageId}${page[2] ?? "/"}${rest ? `?${rest}` : ""}`, {diff --git a/server/published-pages.e2e.test.ts b/server/published-pages.e2e.test.tsindex 0e57990872..c23f684ca4 100644--- a/server/published-pages.e2e.test.ts+++ b/server/published-pages.e2e.test.ts@@ -156,7 +156,8 @@ it("keeps an owner-only page on this server, serves its stable link to the ownerexpect(spent.status).toBe(303);expect(spent.headers.get("location")).toBe(link.pathname);const cookie = spent.headers.get("set-cookie")!.split(";")[0]!;- expect((await realFetch(new URL(once), { redirect: "manual" })).status).toBe(404);+ const browserHeaders = { "sec-fetch-site": "none", "sec-fetch-dest": "document", "sec-fetch-mode": "navigate" };+ expect((await realFetch(new URL(once), { redirect: "manual", headers: browserHeaders })).status, "a spent code opens nothing").not.toBe(200);const browser = await realFetch(new URL(link.pathname, fixture.info.url), { headers: { cookie, "sec-fetch-site": "none", "sec-fetch-dest": "document", "sec-fetch-mode": "navigate" } });expect(browser.status).toBe(200);expect(await browser.text()).toContain("<h1>Traffic</h1>");diff --git a/src/components/PublishedPageCard.tsx b/src/components/PublishedPageCard.tsxindex 8a2e5c4cb0..e3349b16f5 100644--- a/src/components/PublishedPageCard.tsx+++ b/src/components/PublishedPageCard.tsx@@ -8,7 +8,6 @@ import { usePageOpener } from "@/lib/page-open";import { t } from "@/lib/i18n";import { api, useStore, type Message } from "@/state/store";import { ASK_CHIP, ASK_CHIP_IDLE, ASK_PRIMARY_BUTTON } from "./AskCard";-import { openOwnerPage } from "./app/app-api";const usageLine = (card: Card) => card.usage ? t("chat.page.usage", { pages: card.usage.pages, limit: card.usage.limit }) : null;@@ -38,7 +37,6 @@ export function PublishedPageCard({ message }: { message: Message }) {finally { setBusy(false); }};const usage = usageLine(card), owner = card.visibility === "owner";- const open = () => (owner && card.pageId ? void openOwnerPage(card.pageId, card.url!) : openPage(card.url!));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">@@ -49,14 +47,14 @@ export function PublishedPageCard({ message }: { message: Message }) {</div>{card.state === "live" && card.url && <>{card.uncertain && <p role="status" className="mt-1 text-[13px] text-ink-secondary">{t("chat.page.uncertain")}</p>}- <a href={card.url} dir="ltr" onClick={(event) => { event.preventDefault(); open(); }}+ <a href={card.url} dir="ltr" onClick={(event) => { event.preventDefault(); openPage(card.url!); }}className="mt-1 block truncate text-[13px] text-accent-text hover:underline">{card.url}</a><div className="mt-2 flex flex-wrap gap-1.5"><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>- <button type="button" onClick={open} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>+ <button type="button" onClick={() => openPage(card.url!)} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}><ArrowUpRight size={14} />{t("chat.page.open")}</button><button type="button" onClick={() => void unpublish()} disabled={busy} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>diff --git a/src/components/app/PageTools.tsx b/src/components/app/PageTools.tsxindex 8145bbdaa8..ff027804bb 100644--- a/src/components/app/PageTools.tsx+++ b/src/components/app/PageTools.tsx@@ -16,7 +16,7 @@ import type { AppDocument, AppPayload } from "../../../shared/app";import { marksMessage, pointMessage, readPointEvent } from "../../../shared/app-frame/point";import type { PublishedPageCard, PublishedPageVisibility } from "../../../shared/published-page";import { canonicalDownloadFilename } from "../AttachmentPreview";-import { appDownloadPath, openOwnerPage, publishAppPage, unpublishPage } from "./app-api";+import { appDownloadPath, publishAppPage, unpublishPage } from "./app-api";import { AppFrame, type AppFrameHandle } from "./AppFrame";import type { AppSelection } from "./app-frame-host";import { ASK_CHIP, ASK_CHIP_IDLE, ASK_CHIP_PICKED, ASK_PRIMARY_BUTTON } from "../AskCard";@@ -87,7 +87,7 @@ export function usePageShare(threadId: string, messageId: string, published: PubsetAgain(false);};const toggleVisibility = () => setVisibility((current) => (current === "owner" ? "public" : "owner"));- return { share, url: live?.url, pageId: live?.pageId, visibility, again, unpublished: published?.state === "unpublished", run, unpublish, toggleVisibility };+ 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. */@@ -264,7 +264,7 @@ export function PageToolbar({ version, point, share, save, ready, fullScreen, roaria-label={t("chat.preview.save")} title={t("chat.preview.save")}>{save.busy ? <Loader2 size={15} className="animate-spin" /> : <Download size={15} />}</button>- <button type="button" className={TOOL} disabled={!share.url} onClick={() => share.url && void (owner && share.pageId ? openOwnerPage(share.pageId, share.url) : openExternalLink(share.url))}+ <button type="button" className={TOOL} disabled={!share.url} onClick={() => share.url && void openExternalLink(share.url)}aria-label={t("chat.preview.openTab")} title={share.url ? t("chat.preview.openTab") : t("chat.preview.openTabNeedsLink")}><ArrowUpRight size={15} /></button>@@ -291,7 +291,7 @@ export function PageNotes({ version, point, share, save, room, className }: Pick<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]">{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 (owner && share.pageId ? openOwnerPage(share.pageId, share.url!) : openExternalLink(share.url!)); }}+ <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")}diff --git a/src/components/app/app-api.ts b/src/components/app/app-api.tsindex bca1baabc2..f1c33317d0 100644--- a/src/components/app/app-api.ts+++ b/src/components/app/app-api.ts@@ -1,4 +1,3 @@-import { openExternalLink } from "@/lib/app-links";import { t } from "@/lib/i18n";import { api, ApiError } from "@/state/store";import type { AppBlockedReason, AppDocument } from "../../../shared/app";@@ -145,12 +144,3 @@ export async function unpublishPage(pageId: string): Promise<boolean> {return false;}}--/** Opens an owner-only page. A browser signed in to this server opens its link as it is; the desktop app's system browser- * is not signed in, so it gets a one-time link that lets that browser in for this page alone. */-export async function openOwnerPage(pageId: string, url: string): Promise<void> {- if (!window.ogb?.openExternal) return openExternalLink(url);- let once = url;- try { once = (await api<{ url: string }>(`/api/published-pages/${encodeURIComponent(pageId)}/open`, { method: "POST", body: "{}" })).url; } catch { /* the plain link still opens where the owner is signed in */ }- await openExternalLink(once);-}diff --git a/src/lib/app-links.test.ts b/src/lib/app-links.test.tsnew file mode 100644index 0000000000..fa381441ce--- /dev/null+++ b/src/lib/app-links.test.ts@@ -0,0 +1,46 @@+import { afterEach, describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({ api: vi.fn() }));+vi.mock("@/state/api", () => ({ api: fixture.api }));++import { openExternalLink } from "./app-links";++const PAGE = "abcdefghijklmnopqrstuvwxyz";+const LINK = `http://127.0.0.1:4100/api/published-pages/${PAGE}/`;++function desktop() {+ const opened: string[] = [];+ vi.stubGlobal("window", { ogb: { openExternal: async (url: string) => { opened.push(url); } }, open: vi.fn() });+ return opened;+}++afterEach(() => {+ vi.unstubAllGlobals();+ fixture.api.mockReset();+});++describe("opening a link from the desktop app", () => {+ it("opens an owner-only page's link with a one-time code, since the system browser is not signed in", async () => {+ const opened = desktop();+ fixture.api.mockResolvedValue({ url: `${LINK}?code=${"c".repeat(43)}` });+ await openExternalLink(LINK);+ expect(fixture.api).toHaveBeenCalledWith(`/api/published-pages/${PAGE}/open`, { method: "POST", body: "{}" });+ expect(opened).toEqual([`${LINK}?code=${"c".repeat(43)}`]);+ });++ it("keeps the link as it is when the server refuses, or answers for another address", async () => {+ const opened = desktop();+ fixture.api.mockRejectedValueOnce(new Error("Not found."));+ await openExternalLink(LINK);+ fixture.api.mockResolvedValueOnce({ url: `https://elsewhere.example/api/published-pages/${PAGE}/?code=x` });+ await openExternalLink(LINK);+ expect(opened).toEqual([LINK, LINK]);+ });++ it("asks nothing for any other link, including a file of the page", async () => {+ const opened = desktop();+ for (const url of ["https://example.com/", `${LINK}data.csv`, `${LINK}?period=1`, "not a url"]) await openExternalLink(url);+ expect(fixture.api).not.toHaveBeenCalled();+ expect(opened).toEqual(["https://example.com/", `${LINK}data.csv`, `${LINK}?period=1`, "not a url"]);+ });+});diff --git a/src/lib/app-links.ts b/src/lib/app-links.tsindex 87052fc25e..c22a6ba7c7 100644--- a/src/lib/app-links.ts+++ b/src/lib/app-links.ts@@ -44,7 +44,7 @@ export function platformLabel(platform?: string): string | null {export async function openExternalLink(url: string): Promise<void> {if (window.ogb?.openExternal) {- await window.ogb.openExternal(url);+ await window.ogb.openExternal(await ownerPageOnce(url));return;}window.open(url, "_blank", "noopener,noreferrer");@@ -55,3 +55,20 @@ export async function openEmailDraft(url: string): Promise<void> {if (window.ogb) return openExternalLink(url);window.location.href = url;}++/** An owner-only page's link, `/api/published-pages/<id>/`, opens only where the owner is signed in, and the system browser+ * the desktop app hands links to is not. It gets the same link with a one-time code instead, which lets that browser in+ * for this page alone; anything else, or a server that refuses, keeps the link as it was. */+async function ownerPageOnce(url: string): Promise<string> {+ let link: URL;+ try { link = new URL(url); } catch { return url; }+ const pageId = /^\/api\/published-pages\/([a-z0-9]{20,63})\/$/.exec(link.pathname)?.[1];+ if (!pageId || link.search || link.hash) return url;+ try {+ const { api } = await import("@/state/api");+ const once = new URL((await api<{ url: string }>(`/api/published-pages/${pageId}/open`, { method: "POST", body: "{}" })).url);+ return once.origin === link.origin && once.pathname === link.pathname ? once.href : url;+ } catch {+ return url;+ }+}