Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(browser): tell sign-ins apart from ad and tracker cookies in Signed-in sites
Diaz Guntur Febriand640edf79f89
diff --git a/server/browser-sites.test.ts b/server/browser-sites.test.tsindex 276fd82d9d..e8232064c8 100644--- a/server/browser-sites.test.ts+++ b/server/browser-sites.test.ts@@ -56,8 +56,8 @@ describe("a profile's signed-in sites, from its saved session", () => {expect(await listSignedInSites(target, stopped)).toEqual({running: false,sites: [- { site: "example.com", cookies: 1, storage: 1 },- { site: "wikipedia.org", cookies: 2, storage: 0 },+ { site: "example.com", cookies: 1, storage: 1, direct: true },+ { site: "wikipedia.org", cookies: 2, storage: 0, direct: true },],});});@@ -74,10 +74,34 @@ describe("a profile's signed-in sites, from its saved session", () => {[cookie(".google.com"), cookie("accounts.google.com"), cookie("mail.google.com"), cookie("www.bbc.co.uk"), cookie("app.example.org"), cookie("127.0.0.1")],[{ origin: "https://docs.google.com", localStorage: [{ name: "a", value: "b" }] }, { origin: "https://empty.example.org", localStorage: [] }],)).toEqual([- { site: "127.0.0.1", cookies: 1, storage: 0 },- { site: "app.example.org", cookies: 1, storage: 0 },- { site: "google.com", cookies: 3, storage: 1 },- { site: "www.bbc.co.uk", cookies: 1, storage: 0 },+ { site: "127.0.0.1", cookies: 1, storage: 0, direct: true },+ { site: "app.example.org", cookies: 1, storage: 0, direct: true },+ { site: "google.com", cookies: 3, storage: 1, direct: true },+ { site: "www.bbc.co.uk", cookies: 1, storage: 0, direct: true },+ ]);+ });++ it("tells a site the browser opened from ads and trackers that only set cookies from other sites' pages", () => {+ const cookie = (domain: string, sameSite?: string) => ({ name: "id", value: "1", domain, path: "/", ...(sameSite ? { sameSite } : {}) });+ expect(signedInSites(+ [+ cookie(".doubleclick.net", "None"),+ cookie(".pubmatic.com", "None"), cookie("pubmatic.com", "None"),+ cookie("github.com", "Lax"), cookie(".github.com", "None"),+ cookie("slack.com", "Strict"),+ cookie("legacy.example", undefined),+ cookie(".linkedin.com", "None"),+ cookie(".youtube.com", "none"),+ ],+ [{ origin: "https://www.linkedin.com", localStorage: [{ name: "a", value: "b" }] }],+ )).toEqual([+ { site: "doubleclick.net", cookies: 1, storage: 0, direct: false },+ { site: "github.com", cookies: 2, storage: 0, direct: true },+ { site: "legacy.example", cookies: 1, storage: 0, direct: true },+ { site: "linkedin.com", cookies: 1, storage: 1, direct: true },+ { site: "pubmatic.com", cookies: 2, storage: 0, direct: false },+ { site: "slack.com", cookies: 1, storage: 0, direct: true },+ { site: "youtube.com", cookies: 1, storage: 0, direct: false },]);});@@ -95,7 +119,7 @@ describe("signing a stopped browser out", () => {writeFileSync(join(directory, "work-work.json.enc"), SAVED_BY_ENGINE);writeFileSync(`${current}.previous`, SAVED_BY_ENGINE);const result = await signOutOfSites(target, "wikipedia.org", stopped);- expect(result).toEqual({ running: false, sites: [{ site: "example.com", cookies: 1, storage: 1 }] });+ expect(result).toEqual({ running: false, sites: [{ site: "example.com", cookies: 1, storage: 1, direct: true }] });for (const path of [current, join(directory, "work-work.json.enc")]) {const state = saved(path);expect(state.cookies.map((cookie: { domain: string }) => cookie.domain)).toEqual(["www.example.com"]);@@ -181,7 +205,7 @@ describe("signing a running browser out", () => {const chrome = await fakeChrome([cookie("SID", ".google.com"), cookie("sid", "www.example.com")], { "https://mail.google.com": "t" });expect(await listSignedInSites(target, { engine: chrome.engine })).toEqual({running: true,- sites: [{ site: "google.com", cookies: 1, storage: 1 }, { site: "www.example.com", cookies: 1, storage: 0 }],+ sites: [{ site: "google.com", cookies: 1, storage: 1, direct: true }, { site: "www.example.com", cookies: 1, storage: 0, direct: true }],});expect(chrome.calls).toEqual([]);});@@ -194,7 +218,7 @@ describe("signing a running browser out", () => {{ "https://en.wikipedia.org": "w", "https://example.com": "e" },);const result = await signOutOfSites(target, "wikipedia.org", { engine: chrome.engine });- expect(result).toEqual({ running: true, sites: [{ site: "example.com", cookies: 1, storage: 1 }, { site: "google.com", cookies: 1, storage: 0 }] });+ expect(result).toEqual({ running: true, sites: [{ site: "example.com", cookies: 1, storage: 1, direct: true }, { site: "google.com", cookies: 1, storage: 0, direct: true }] });expect(chrome.jar.map((entry) => entry.domain)).toEqual(["www.example.com", ".google.com"]);expect(chrome.calls.filter((call) => call.method === "Network.deleteCookies").map((call) => call.params)).toEqual([{ name: "sid", domain: ".wikipedia.org", path: "/" }, { name: "sid", domain: "en.wikipedia.org", path: "/" }]);@@ -234,7 +258,7 @@ describe("signing a running browser out", () => {const withProfile = { ...target, env: { ...target.env, AGENT_BROWSER_PROFILE: kept } };expect(await listSignedInSites(withProfile, deps)).toMatchObject({ running: false });expect(lifecycle).toEqual([]);- expect(await signOutOfSites(withProfile, "wikipedia.org", deps)).toEqual({ running: false, sites: [{ site: "www.example.com", cookies: 1, storage: 0 }] });+ expect(await signOutOfSites(withProfile, "wikipedia.org", deps)).toEqual({ running: false, sites: [{ site: "www.example.com", cookies: 1, storage: 0, direct: true }] });expect(lifecycle).toEqual(["start", "stop"]);expect(chrome.jar.map((entry) => entry.domain)).toEqual(["www.example.com"]);expect(saved().cookies.map((entry: { domain: string }) => entry.domain)).toEqual(["www.example.com"]);diff --git a/server/browser-sites.ts b/server/browser-sites.tsindex 7e4b836af9..9f808a5f5a 100644--- a/server/browser-sites.ts+++ b/server/browser-sites.ts@@ -14,6 +14,12 @@ export interface SignedInSite {site: string;cookies: number;storage: number;+ /**+ * The site kept a cookie only a page of its own could set, or kept storage: one the bot opened+ * itself, where a sign-in can live. False when every cookie is SameSite=None, the kind ads,+ * trackers and embeds set from other sites' pages.+ */+ direct: boolean;}export interface SignedInSites {@@ -44,7 +50,7 @@ export interface BrowserSitesDeps {stop?: (target: BrowserSitesTarget) => Promise<boolean>;}-interface Cookie { name: string; domain: string; path: string; partitionKey?: unknown }+interface Cookie { name: string; domain: string; path: string; partitionKey?: unknown; sameSite?: unknown }interface SavedOrigin { origin: string; localStorage?: unknown; sessionStorage?: unknown }interface SavedState { cookies: unknown[]; origins: unknown[] }@@ -84,6 +90,12 @@ function hostOfCookie(cookie: Cookie): string {return cookie.domain.replace(/^\./u, "").toLowerCase();}+// Chrome refuses a SameSite=Lax or Strict cookie from a cross-site subresource, and treats a cookie+// without the attribute as Lax: only SameSite=None can come from another site's page.+function firstParty(cookie: Cookie): boolean {+ return typeof cookie.sameSite !== "string" || cookie.sameSite.toLowerCase() !== "none";+}+function hostOfOrigin(origin: string): string | null {try { return new URL(origin).hostname.toLowerCase().replace(/^\[|\]$/gu, "") || null; }catch { return null; }@@ -109,18 +121,26 @@ function inSite(host: string, site: string): boolean {}export function signedInSites(cookies: readonly unknown[], origins: readonly unknown[]): SignedInSite[] {- const cookieHosts = cookies.filter(isCookie).map(hostOfCookie);+ const saved = cookies.filter(isCookie).filter((cookie) => hostOfCookie(cookie));const storageHosts = origins.filter(isOrigin).filter(hasStorage).flatMap((origin) => hostOfOrigin(origin.origin) ?? []);- const hosts = new Set([...cookieHosts, ...storageHosts].filter(Boolean));+ const hosts = new Set([...saved.map(hostOfCookie), ...storageHosts]);const sites = new Map<string, SignedInSite>();const entry = (host: string) => {const site = siteOf(host, hosts);let found = sites.get(site);- if (!found) sites.set(site, found = { site, cookies: 0, storage: 0 });+ if (!found) sites.set(site, found = { site, cookies: 0, storage: 0, direct: false });return found;};- for (const host of cookieHosts) if (host) entry(host).cookies += 1;- for (const host of storageHosts) entry(host).storage += 1;+ for (const cookie of saved) {+ const found = entry(hostOfCookie(cookie));+ found.cookies += 1;+ if (firstParty(cookie)) found.direct = true;+ }+ for (const host of storageHosts) {+ const found = entry(host);+ found.storage += 1;+ found.direct = true;+ }return [...sites.values()].sort((a, b) => a.site.localeCompare(b.site));}diff --git a/src/components/SignedInSites.test.ts b/src/components/SignedInSites.test.tsindex 3d511e9976..4b59f56542 100644--- a/src/components/SignedInSites.test.ts+++ b/src/components/SignedInSites.test.ts@@ -11,8 +11,9 @@ const { SignedInSites } = await import("./SignedInSites");(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;let host: HTMLDivElement;let root: Root;-const google = { site: "google.com", cookies: 4, storage: 1 };-const example = { site: "example.com", cookies: 1, storage: 0 };+const google = { site: "google.com", cookies: 4, storage: 1, direct: true };+const example = { site: "example.com", cookies: 1, storage: 0, direct: true };+const tracker = { site: "doubleclick.net", cookies: 2, storage: 0, direct: false };beforeEach(() => {fixture.api.mockReset();@@ -93,6 +94,36 @@ describe("signed-in sites", () => {expect(host.querySelector("button")).toBeNull();});+ it("keeps cookies other sites left apart from sign-ins, folded, and clears them one by one", async () => {+ fixture.api.mockResolvedValueOnce({ running: true, sites: [tracker, google] }).mockResolvedValueOnce({ running: true, sites: [google] });+ await render({ bare: true, target: { bot: "pepper" }, sharedBy: ["Pepper"] });+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+ const fold = host.querySelector<HTMLDetailsElement>('[data-testid="third-party-sites"]')!;+ expect(fold.open).toBe(false);+ expect(fold.querySelector("summary")?.textContent).toBe("Cookies from other sites (1)");+ expect([...fold.querySelectorAll("li span")].map((span) => span.textContent)).toEqual(["doubleclick.net"]);+ expect(listed()).toEqual(["google.com", "doubleclick.net"]);+ await click("Clear cookies of doubleclick.net");+ expect(fixture.api).toHaveBeenLastCalledWith("/api/browser-sites/sign-out", { method: "POST", body: JSON.stringify({ bot: "pepper", site: "doubleclick.net" }) });+ expect(host.querySelector('[data-testid="third-party-sites"]')).toBeNull();+ });++ it("says it is signed in nowhere when only other sites left cookies", async () => {+ fixture.api.mockResolvedValueOnce({ running: false, sites: [tracker] });+ await render({ bare: true, target: { bot: "pepper" }, sharedBy: ["Pepper"] });+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+ expect(host.textContent).toContain("Not signed in to any site.");+ expect(button("Sign out of all")).toBeDefined();+ });++ it("lists a site from a server that does not tell them apart as a sign-in", async () => {+ fixture.api.mockResolvedValueOnce({ running: false, sites: [{ site: "example.com", cookies: 1, storage: 0 }] });+ await render({ bare: true, target: { bot: "pepper" }, sharedBy: ["Pepper"] });+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+ expect(listed()).toEqual(["example.com"]);+ expect(host.querySelector('[data-testid="third-party-sites"]')).toBeNull();+ });+it("shows the server's reason when it cannot read the browser, and keeps buttons off while disabled", async () => {fixture.api.mockRejectedValueOnce(new Error("The browser did not answer. Try again when the bot has finished."));await render({ target: { profile: "profile-work" }, sharedBy: [] });diff --git a/src/components/SignedInSites.tsx b/src/components/SignedInSites.tsxindex c68cff7337..260e55e787 100644--- a/src/components/SignedInSites.tsx+++ b/src/components/SignedInSites.tsx@@ -2,8 +2,9 @@ import { useEffect, useState } from "react";import { LogOut } from "lucide-react";import { api } from "@/state/store";import { t } from "@/lib/i18n";+import type { LocaleKey } from "@/locales";-interface SignedInSite { site: string; cookies: number; storage: number }+interface SignedInSite { site: string; cookies: number; storage: number; direct?: boolean }interface SignedInSitesAnswer { running: boolean; sites: SignedInSite[] }/** Security: the server reads and clears the browser itself, running or not, and keeps the key. */@@ -40,22 +41,32 @@ export function SignedInSites({ target, scope = {}, sharedBy, disabled = false,const locked = disabled || busy;const buttonClass = "flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50";+ const direct = sites?.filter((entry) => entry.direct !== false) ?? [];+ const others = sites?.filter((entry) => entry.direct === false) ?? [];+ const rows = (entries: SignedInSite[], label: LocaleKey, labelOf: LocaleKey) => (+ <ul className="divide-y divide-hairline/30">+ {entries.map((entry) => (+ <li key={entry.site} className="flex min-w-0 items-center gap-2 py-1.5">+ <span className="min-w-0 flex-1 truncate text-[13px] text-ink" title={entry.site}>{entry.site}</span>+ <button type="button" disabled={locked} onClick={() => void signOut(entry.site)} aria-label={t(labelOf, { site: entry.site })} className={buttonClass}>+ <LogOut size={13} />{t(label)}+ </button>+ </li>+ ))}+ </ul>+ );const list = (<div className={bare ? "flex min-w-0 flex-col gap-2" : "mt-2 flex flex-col gap-2"} aria-busy={busy}>{sharedBy.length > 1 && <p className="text-[11px] leading-relaxed text-ink-secondary">{t("settings.sites.shared", { names: sharedBy.join(", ") })}</p>}{sites === null && !error && <p className="text-[12px] text-ink-secondary">{t("settings.sites.loading")}</p>}- {sites?.length === 0 && <p className="text-[12px] text-ink-secondary">{t("settings.sites.none")}</p>}- {!!sites?.length && (- <ul className="divide-y divide-hairline/30">- {sites.map((entry) => (- <li key={entry.site} className="flex min-w-0 items-center gap-2 py-1.5">- <span className="min-w-0 flex-1 truncate text-[13px] text-ink" title={entry.site}>{entry.site}</span>- <button type="button" disabled={locked} onClick={() => void signOut(entry.site)} aria-label={t("settings.sites.signOutOf", { site: entry.site })} className={buttonClass}>- <LogOut size={13} />{t("settings.sites.signOut")}- </button>- </li>- ))}- </ul>+ {sites !== null && direct.length === 0 && <p className="text-[12px] text-ink-secondary">{t("settings.sites.none")}</p>}+ {direct.length > 0 && rows(direct, "settings.sites.signOut", "settings.sites.signOutOf")}+ {others.length > 0 && (+ <details className="min-w-0" data-testid="third-party-sites">+ <summary className="cursor-pointer text-[12px] text-ink-secondary hover:text-ink">{t("settings.sites.others", { count: others.length })}</summary>+ <p className="mt-1 text-[11px] leading-relaxed text-ink-secondary">{t("settings.sites.othersHelp")}</p>+ {rows(others, "settings.sites.clear", "settings.sites.clearOf")}+ </details>)}{!!sites?.length && (<button type="button" disabled={locked} onClick={() => void signOut()} className={`${buttonClass} self-start`}>diff --git a/src/locales/en.json b/src/locales/en.jsonindex 0efb4ccdd6..6f165c4ac1 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4091,6 +4091,10 @@"settings.sites.signOutOf": "Sign out of {site}","settings.sites.signOutAll": "Sign out of all","settings.sites.error": "Couldn't read this browser's sign-ins. Try again in a moment.",+ "settings.sites.others": "Cookies from other sites ({count})",+ "settings.sites.othersHelp": "Ads, trackers and embeds on pages this browser opened left these. They are usually not sign-ins.",+ "settings.sites.clear": "Clear",+ "settings.sites.clearOf": "Clear cookies of {site}","settings.connections.title": "API keys","settings.connections.subtitle": "Keys for AI providers and optional services. Paste a key and it saves and checks itself.","settings.connections.ready": "Connected apps service is ready",