Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a login kept to some bots out of a browser other bots share
Azad Jagtap2dcaf8f63a3d
diff --git a/server/bot-logins.test.ts b/server/bot-logins.test.tsindex ec7d211909..3850ed48c4 100644--- a/server/bot-logins.test.ts+++ b/server/bot-logins.test.ts@@ -1,6 +1,13 @@import { afterEach, describe, expect, it } from "vitest";-import { cardLoginPlace, cardSignInElsewhere, observeSignInPage } from "./bot-logins.ts";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { browserMatesOf, loginHeldBackFor } from "../shared/logins.ts";+import { BotLogins, cardLoginPlace, cardSignInElsewhere, observeSignInPage } from "./bot-logins.ts";+import { LoginStore } from "./login-store.ts";+import type { OnePasswordLogins } from "./onepassword.ts";import { FakeLoginPage, LOGIN_FORM } from "./testing/fake-login-page.ts";let page: FakeLoginPage | null = null;@@ -41,3 +48,43 @@ describe("the bot's open page", () => {expect(await observeSignInPage(async () => { throw new Error("The browser did not answer."); })).toBeNull();});});++describe("a login kept to some bots, and bots that share a browser", () => {+ // Payroll and Infra share the "finance" browser profile; Notes has its own.+ const bots = [{ id: "payroll", browserProfile: "finance" }, { id: "infra", browserProfile: "finance" }, { id: "notes" }, { id: "audit", browserProfile: null }];+ const onePassword = { fresh: async () => {}, sitesFor: () => [], candidates: () => [], markUsed: () => {} } as unknown as OnePasswordLogins;+ const world = () => {+ const store = new LoginStore({ dataDir: mkdtempSync(join(tmpdir(), "omb-bot-logins-")) });+ const logins = new BotLogins(store, onePassword, (botId) => browserMatesOf(bots, botId));+ const place = { site: "capacity.example", hosts: ["capacity.example"], exactHost: false };+ return { store, logins, place };+ };++ it("finds the bots on the same named profile, and none for a bot on its own", () => {+ expect(browserMatesOf(bots, "payroll")).toEqual(["infra"]);+ expect(browserMatesOf(bots, "notes")).toEqual([]);+ expect(browserMatesOf(bots, "audit")).toEqual([]);+ });++ it("is never filled into a browser a bot it isn't kept to also signs in through", async () => {+ const { store, logins, place } = world();+ store.create({ ...place, username: "ops", password: "hunter2", source: "settings", bots: ["payroll"] });+ expect(logins.sitesFor("payroll")).toEqual([]);+ expect(await logins.candidates("payroll", "capacity.example")).toEqual([]);+ expect(logins.sitesFor("infra")).toEqual([]);+ expect(loginHeldBackFor({ bots: ["payroll"] }, bots)).toEqual(["payroll"]);+ });++ it("fills when every bot on the browser may use it, when it is for every bot, and for a bot with its own browser", async () => {+ const { store, logins, place } = world();+ store.create({ ...place, username: "both", password: "a", source: "settings", bots: ["payroll", "infra"] });+ store.create({ ...place, username: "everyone", password: "b", source: "settings", bots: "all" });+ store.create({ ...place, username: "notes-only", password: "c", source: "settings", bots: ["notes"] });+ expect(logins.sitesFor("payroll").map((login) => login.username)).toEqual(["both", "everyone"]);+ expect((await logins.candidates("infra", "capacity.example")).map((login) => login.username)).toEqual(["both", "everyone"]);+ expect(logins.sitesFor("notes").map((login) => login.username)).toEqual(["everyone", "notes-only"]);+ expect(loginHeldBackFor({ bots: ["payroll", "infra"] }, bots)).toEqual([]);+ expect(loginHeldBackFor({ bots: "all" }, bots)).toEqual([]);+ });+});+diff --git a/server/bot-logins.ts b/server/bot-logins.tsindex 5c74fbc03a..9bd955bfc3 100644--- a/server/bot-logins.ts+++ b/server/bot-logins.ts@@ -41,14 +41,22 @@ export function cardLoginPlace(cardHost: string, observed: ObservedPage | null,return loginPlace(cardHost, [onSite, ...(elsewhere && confirmedHost === elsewhere ? [elsewhere] : [])]);}-/** Saved logins and 1Password items, as each bot may use them. */+/** Saved logins and 1Password items, as each bot may use them. A login kept to some bots is filled only where every bot+ * sharing that browser may use it: a sign-in stays in the browser, so a bot sharing it would be signed in as well. */export class BotLogins {readonly store: LoginStore;readonly onePassword: OnePasswordLogins;+ private readonly browserMates: (botId: string) => readonly string[];- constructor(store: LoginStore, onePassword: OnePasswordLogins) {+ constructor(store: LoginStore, onePassword: OnePasswordLogins, browserMates: (botId: string) => readonly string[] = () => []) {this.store = store;this.onePassword = onePassword;+ this.browserMates = browserMates;+ }++ /** The bot and every other bot that signs in through its browser. */+ private signedInTogether(botId: string): string[] {+ return [botId, ...this.browserMates(botId).filter((id) => id !== botId)];}/** The desktop main process's private ask for one login, for Send to My Cloud, or for a connection a move carries. */@@ -58,18 +66,20 @@ export class BotLogins {/** Where each login the bot may use fills, with its username. */sitesFor(botId: string): Array<LoginPlace & { username: string }> {- return [...this.store.sitesFor(botId), ...this.onePassword.sitesFor(botId)];+ const bots = this.signedInTogether(botId);+ return [...this.store.sitesFor(bots), ...this.onePassword.sitesFor(bots)];}/** Secrets are read only when one is filled. */async candidates(botId: string, pageHost: string): Promise<FillCandidate[]> {await this.onePassword.fresh();+ const bots = this.signedInTogether(botId);return [- ...this.store.usableFor(pageHost, botId).map((login): FillCandidate => ({+ ...this.store.usableFor(pageHost, bots).map((login): FillCandidate => ({id: login.id, site: login.site, hosts: login.hosts, exactHost: login.exactHost, username: login.username, source: login.source,secrets: async () => ({ password: login.password, totp: login.totp ?? null }),})),- ...this.onePassword.candidates(pageHost, botId),+ ...this.onePassword.candidates(pageHost, bots),];}diff --git a/server/index.ts b/server/index.tsindex cc977bc83b..66b7c09af2 100644--- a/server/index.ts+++ b/server/index.ts@@ -429,7 +429,7 @@ import { CalendarCallManager, type CalendarCall } from "./calendar-calls.ts";import { BROWSER_UPLOAD_TOOL, browserRuntimeEnv } from "./browser-runtime.ts";import { BrowserUploadRefusal, uploadableFiles } from "./browser-upload.ts";import { listSignedInSites, signOutOfSites } from "./browser-sites.ts";-import { HeldSecrets, LoginStore } from "./login-store.ts";+import { HeldSecrets, LoginStore } from "./login-store.ts"; import { browserMatesOf } from "../shared/logins.ts";import { OnePasswordLogins, onePasswordUnavailable, sdkOnePasswordClient, type OnePasswordSdk } from "./onepassword.ts";import { nativeRequire } from "./data/engine.ts";import { createFillLoginTurn } from "./host/fill-login-turn.ts";@@ -737,7 +737,7 @@ const onePassword = new OnePasswordLogins({},});if (logins.onePasswordToken()) void onePassword.refresh();-const botLogins = new BotLogins(logins, onePassword);+const botLogins = new BotLogins(logins, onePassword, (botId) => browserMatesOf(store.bots, botId));const SESSION_COOKIE = sessionCookieName(PORT, ENVIRONMENT_ID);const HOSTED_WORKSPACE = hostedWorkspaceConfigured();let workspaceAccess: WorkspaceAccess | null = null;diff --git a/server/login-store.ts b/server/login-store.tsindex b9358eefcc..3c21546205 100644--- a/server/login-store.ts+++ b/server/login-store.ts@@ -221,12 +221,12 @@ export class LoginStore {return true;}- usableFor(pageHost: string, botId: string): StoredLogin[] {+ usableFor(pageHost: string, botId: string | readonly string[]): StoredLogin[] {return this.read().logins.filter((login) => loginMatchesHost(login, pageHost) && loginUsableBy(login, botId));}/** Where each login a bot may use fills, and its username, for the bot's prompt. */- sitesFor(botId: string): Array<LoginPlace & { username: string }> {+ sitesFor(botId: string | readonly string[]): Array<LoginPlace & { username: string }> {return this.read().logins.filter((login) => loginUsableBy(login, botId)).map((login) => ({ site: login.site, hosts: [...login.hosts], exactHost: login.exactHost, username: login.username })).sort((a, b) => a.site.localeCompare(b.site) || a.username.localeCompare(b.username));diff --git a/server/onepassword.ts b/server/onepassword.tsindex 5ccc5f14f1..dec7667164 100644--- a/server/onepassword.ts+++ b/server/onepassword.ts@@ -232,15 +232,15 @@ export class OnePasswordLogins {}/** A vault narrowed to other bots is invisible to this one. */- private usable(botId: string): Entry[] {+ private usable(botId: string | readonly string[]): Entry[] {return this.token() ? this.entries.filter((entry) => loginUsableBy({ bots: this.botsFor(entry.vaultId) }, botId)) : [];}- sitesFor(botId: string): Array<LoginPlace & { username: string }> {+ sitesFor(botId: string | readonly string[]): Array<LoginPlace & { username: string }> {return this.usable(botId).map((entry) => ({ site: entry.site, hosts: [...entry.hosts], exactHost: false, username: entry.username }));}- candidates(pageHost: string, botId: string): FillCandidate[] {+ candidates(pageHost: string, botId: string | readonly string[]): FillCandidate[] {const token = this.token();if (!token) return [];return this.usable(botId).filter((entry) => loginMatchesHost(entry, pageHost)).map((entry) => ({diff --git a/server/saved-login.e2e.test.ts b/server/saved-login.e2e.test.tsindex 97fdcd3376..0aa8ba1bfe 100644--- a/server/saved-login.e2e.test.ts+++ b/server/saved-login.e2e.test.ts@@ -203,6 +203,43 @@ it.skipIf(process.platform === "win32")("fills a login saved for example.com on}}, 120_000);+it.skipIf(process.platform === "win32")("keeps a login kept to one bot out of a browser another bot shares, and fills it once that bot has its own", async () => {+ const browser = await browserFixture("https://accounts.example.com/login");+ const { page, api, evidence, answered } = browser;+ try {+ expect((await api("PATCH", "/api/config", { features: { browser: true } })).status).toBe(200);+ const capacity = (await api("POST", "/api/bots", { name: "Capacity" })).body.bot;+ const costs = (await api("POST", "/api/bots", { name: "Costs" })).body.bot;+ for (const bot of [capacity, costs]) expect((await api("PATCH", `/api/bots/${bot.id}`, { computer: "browser", browserProfile: "guest" })).status).toBe(200);+ expect((await api("POST", "/api/logins", { site: "example.com", username: USERNAME, password: PASSWORD, bots: [capacity.id] })).status).toBe(201);+ writeFileSync(browser.planPath, JSON.stringify({ [capacity.id]: { turns: [+ { steps: [{ tool: "fill_login", arguments: { submit: false }, expectError: true }], reply: "No login I may fill here." },+ { steps: [{ tool: "fill_login", arguments: { submit: false } }], reply: "Filled." },+ ] } }));+ const turn = async (count: number) => {+ await runControlOmb(["send", "--bot", capacity.id, "--task", capacity.threadId, "--text", "Sign in to example.com.", "--url", browser.base]);+ await expect.poll(() => evidence().length, { timeout: 20_000 }).toBe(count);+ expect(await runControlOmb(["wait", "--bot", capacity.id, "--task", capacity.threadId, "--timeout", "20", "--url", browser.base])).toMatchObject({ status: "settled" });+ };++ // Costs signs in through the same browser, so a sign-in there would reach it too.+ await turn(1);+ expect(answered(0, "fill_login")[0].isError).toBe(true);+ expect(evidence()[0].system).not.toContain(`example.com (${USERNAME})`);+ expect(page.sent).toEqual([]);++ // Costs goes back to a browser of its own.+ const own = await api("PATCH", `/api/bots/${costs.id}`, { browserProfile: null });+ expect(own.status, JSON.stringify(own.body)).toBe(200);+ await turn(2);+ expect(answered(1, "fill_login")[0].isError).toBeFalsy();+ expect(evidence()[1].system).toContain(`example.com (${USERNAME})`);+ expect(JSON.stringify(evidence())).not.toContain(PASSWORD);+ } finally {+ await browser.close();+ }+}, 120_000);+// Auto mounts this computer only on macOS and Windows, and the stand-in browser is a shebang script.it.runIf(process.platform === "darwin")("on Auto, signs in in the bot's own browser beside this computer, never on the person's screen", async () => {// What the desktop app hands its own server once computer control is ready; the driver itself never runs here.diff --git a/shared/logins.ts b/shared/logins.tsindex daf1fa97e6..285aa9844e 100644--- a/shared/logins.ts+++ b/shared/logins.ts@@ -134,9 +134,23 @@ export function loginOriginCheck(pageUrl: string, login: LoginPlace): { ok: truereturn loginMatchesHost(login, page.pageHost) ? page : { ok: false, pageHost: page.pageHost, reason: "host" };}-/** Whether a bot may use a login. */-export function loginUsableBy(login: { bots: LoginBots }, botId: string): boolean {- return login.bots === "all" || login.bots.includes(botId);+/** The other bots that use this bot's named browser profile, and so share what it is signed in to. */+export function browserMatesOf(bots: ReadonlyArray<{ id: string; browserProfile?: string | null }>, botId: string): string[] {+ const profile = bots.find((bot) => bot.id === botId)?.browserProfile;+ return profile ? bots.filter((bot) => bot.id !== botId && bot.browserProfile === profile).map((bot) => bot.id) : [];+}++/** The bots a login is kept to that it is still not filled for, because they share a browser with a bot it isn't kept to. */+export function loginHeldBackFor(login: { bots: LoginBots }, bots: ReadonlyArray<{ id: string; browserProfile?: string | null }>): string[] {+ const kept = login.bots;+ if (kept === "all") return [];+ return kept.filter((id) => browserMatesOf(bots, id).some((mate) => !kept.includes(mate)));+}++/** Whether a bot may use a login; given several (bots that sign in through one browser), whether every one of them may. */+export function loginUsableBy(login: { bots: LoginBots }, botIds: string | readonly string[]): boolean {+ const bots = login.bots;+ return bots === "all" || (typeof botIds === "string" ? [botIds] : botIds).every((id) => bots.includes(id));}/** A login as a bot hears of it: its site, or its hosts when it is kept todiff --git a/src/components/LoginsSettings.tsx b/src/components/LoginsSettings.tsxindex 1838ecc498..1849796a66 100644--- a/src/components/LoginsSettings.tsx+++ b/src/components/LoginsSettings.tsx@@ -1,7 +1,7 @@import { useEffect, useState, type FormEvent } from "react";import { KeyRound, Loader2, LockKeyhole, Plus, RefreshCw, ShieldCheck, Trash2 } from "lucide-react";-import type { LoginBots, LoginSummary, OnePasswordStatus, OnePasswordVault } from "../../shared/logins";+import { loginHeldBackFor, type LoginBots, type LoginSummary, type OnePasswordStatus, type OnePasswordVault } from "../../shared/logins";import { t } from "@/lib/i18n";import { addLogin, changeLogin, connectOnePassword, deleteLogin, disconnectOnePassword, grantVault, listLogins, refreshOnePassword } from "@/lib/logins";import { relativeTime } from "@/lib/memory";@@ -101,6 +101,11 @@ export function LoginsSettings() {{[t(SOURCE_KEYS[login.source]), botNames(login.bots),login.lastUsedAt ? t("settings.logins.used", { when: relativeTime(login.lastUsedAt) }) : t("settings.logins.neverUsed")].join(" · ")}</div>+ {loginHeldBackFor(login, state.bots).length > 0 && (+ <div className="mt-0.5 text-[12px] leading-snug text-warning" data-login-held-back>+ {t("settings.logins.sharedBrowser", { bots: botNames(loginHeldBackFor(login, state.bots)) })}+ </div>+ )}</div>{login.source !== "1password" && (<div className="flex shrink-0 gap-1">diff --git a/src/locales/en.json b/src/locales/en.jsonindex b29bddd68b..c11698fc84 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -3490,6 +3490,7 @@"settings.logins.noUsername": "No username","settings.logins.source.card": "Saved from a chat","settings.logins.source.settings": "Added here",+ "settings.logins.sharedBrowser": "Not filled for {bots}: that browser is shared with bots this login isn't kept to, and a sign-in there would reach them too. Give each a browser of its own, or keep the login to every bot on it.","settings.logins.source.1password": "From 1Password","settings.logins.used": "Used {when}","settings.logins.neverUsed": "Not used yet",