Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(1password): keep item choices fail-closed on Cloud send
Bugfixer 207ce6132df7e
diff --git a/electron/cloud-send.mjs b/electron/cloud-send.mjsindex 8c5c62113c..700560245a 100644--- a/electron/cloud-send.mjs+++ b/electron/cloud-send.mjs@@ -35,6 +35,7 @@ const MEMORY_FILES = 100;const SCOPED_READ = /^\/api\/cloud-send(?:\?move=1|\/manifest|\/chats(?:\?attachments=1)?|\/files)$/u;const PICTURE_TYPES = { png: "image/png", jpg: "image/jpeg", gif: "image/gif", webp: "image/webp" };const VAULT_ID = /^[\w-]{1,128}$/u;+const ITEM_KEY = /^[\w-]{1,128}:[\w-]{1,128}$/u;/** Whole sends, which carry the chats too; a send of some items (Use this computer's, one login) never does. */const CHAT_REASONS = new Set(["button", "my-cloud", "menu", "move"]);/** Bring newer chats' copy of the whole workspace, for a Cloud too old to take chats by row: never a move, which such a@@ -897,21 +898,29 @@ export function createCloudSend({ local, cloud, handoff, store, onChange = () =>const onePassword = handed?.onePassword;if (!record(onePassword) || typeof onePassword.token !== "string") throw new CloudSendError("local", "1Password is not connected on this computer.");const parts = row.parts ?? ["token", "vaults"];- if (row.state === "only-here" || parts.includes("token")) {+ const connecting = row.state === "only-here" || parts.includes("token");+ if (connecting) {const connected = await ctx.session.call("POST", "/api/logins/1password", { token: onePassword.token });if (!connected.ok) throw onePasswordRefusal(connected);}- for (const [vault, bots] of Object.entries(onePassword.grants ?? {})) {- if (!VAULT_ID.test(vault)) continue;- const granted = await ctx.session.call("PATCH", `/api/logins/1password/vaults/${encodeURIComponent(vault)}`, { bots: botsOnCloud(bots, ctx.cloudBots) });- if (!granted.ok && granted.status !== 404) throw refusedError("refused", granted, "My Cloud connected 1Password but could not keep its vaults to the same bots.");- }- // An item narrowed here must not open to every bot there; a Cloud too old for item choices (405) fails out loud.- for (const [item, bots] of Object.entries(onePassword.itemGrants ?? {})) {- const [vault, id, ...rest] = item.split(":");- if (rest.length || !VAULT_ID.test(vault ?? "") || !VAULT_ID.test(id ?? "")) continue;- const granted = await ctx.session.call("PATCH", `/api/logins/1password/items/${encodeURIComponent(vault)}/${encodeURIComponent(id)}`, { bots: botsOnCloud(bots, ctx.cloudBots) });- if (!granted.ok && granted.status !== 404) throw refusedError("refused", granted, "My Cloud connected 1Password but could not keep its logins to the same bots. Update My Cloud and send again.");+ try {+ for (const [vault, bots] of Object.entries(onePassword.grants ?? {})) {+ if (!VAULT_ID.test(vault)) continue;+ const granted = await ctx.session.call("PATCH", `/api/logins/1password/vaults/${encodeURIComponent(vault)}`, { bots: botsOnCloud(bots, ctx.cloudBots) });+ if (!granted.ok && granted.status !== 404) throw refusedError("refused", granted, "My Cloud connected 1Password but could not keep its vaults to the same bots.");+ }+ // My Cloud's item choices become this computer's, so one handed back to its vault here is handed back there too.+ const items = Object.fromEntries(Object.entries(onePassword.itemGrants ?? {}).filter(([item]) => ITEM_KEY.test(item))+ .map(([item, bots]) => [item, botsOnCloud(bots, ctx.cloudBots)]));+ const granted = await ctx.session.call("PUT", "/api/logins/1password/items", { items });+ // A Cloud too old for item choices has none to undo, but an item narrowed here must not open to every bot there.+ if (!granted.ok && !(granted.status === 405 && !Object.keys(items).length)) {+ throw refusedError("refused", granted, "My Cloud connected 1Password but could not keep its logins to the same bots. Update My Cloud and send again.");+ }+ } catch (error) {+ // Fail closed: a token this send connected is taken off again rather than left open wider than here.+ if (connecting) await ctx.session.call("DELETE", "/api/logins/1password").catch(() => {});+ throw error;}done(ctx, row.key);ctx.result.onePassword = true;diff --git a/electron/cloud-send.node-test.mjs b/electron/cloud-send.node-test.mjsindex d5d9e944b3..7d37e7f00a 100644--- a/electron/cloud-send.node-test.mjs+++ b/electron/cloud-send.node-test.mjs@@ -85,10 +85,12 @@ test("a bot's fields reach My Cloud without Custom approval", () => {function fakeSides({ cloudItems = [], localItems = [], refuse = {} } = {}) {const calls = [];+ const bodies = {};const reply = (status, body) => ({ status, ok: status < 400, body });const session = {- call: async (method, route) => {+ call: async (method, route, body) => {calls.push(`${method} ${route}`);+ bodies[`${method} ${route}`] = body;if (route === "/api/cloud-send" || route === "/api/cloud-send?move=1") return reply(200, summary(cloudItems));if (refuse[route]) return reply(refuse[route].status, { error: refuse[route].error });return reply(200, {});@@ -99,6 +101,7 @@ function fakeSides({ cloudItems = [], localItems = [], refuse = {} } = {}) {const localJson = (value) => new Response(JSON.stringify(value), { status: 200 });return {calls,+ bodies,deps: {local: async (route) => {if (route === "/api/cloud-send" || route === "/api/cloud-send?move=1") return localJson(summary(localItems));@@ -400,15 +403,23 @@ test("1Password items with bots of their own keep them on My Cloud; a Cloud tooconst outcome = await createCloudSend(sides.deps).send();assert.equal(outcome.result.failed.length, 0);assert.ok(sides.calls.includes("PATCH /api/logins/1password/vaults/v1"));- assert.ok(sides.calls.includes("PATCH /api/logins/1password/items/v1/i1"), "the item's own bots go too");- assert.ok(!sides.calls.some((call) => call.includes("/items/bad")), "a malformed item key is skipped");- const old = fakeSides({ localItems: [onePassword], refuse: { "/api/logins/1password/items/v1/i1": { status: 405, error: "method not allowed" } } });+ // All of this computer's item choices in one go, so one handed back to its vault here is handed back there too.+ assert.deepEqual(sides.bodies["PUT /api/logins/1password/items"], { items: { "v1:i1": "all" } }, "a malformed item key is skipped");+ assert.ok(!sides.calls.includes("DELETE /api/logins/1password"));+ const items = { "/api/logins/1password/items": { status: 405, error: "method not allowed" } };+ const old = fakeSides({ localItems: [onePassword], refuse: items });old.deps.handoff = async () => ({ onePassword: { token: "ops_fake", grants: {}, itemGrants: { "v1:i1": [] } } });const refused = await createCloudSend(old.deps).send();assert.deepEqual(refused.result.failed.map((entry) => entry.key), ["1password"], "never left open to every bot there");- const gone = fakeSides({ localItems: [onePassword], refuse: { "/api/logins/1password/items/v1/i1": { status: 404, error: "no such item" } } });- gone.deps.handoff = async () => ({ onePassword: { token: "ops_fake", grants: {}, itemGrants: { "v1:i1": [] } } });- assert.equal((await createCloudSend(gone.deps).send()).result.failed.length, 0, "an item My Cloud's token does not read is skipped");+ assert.ok(old.calls.includes("DELETE /api/logins/1password"), "the token this send connected is taken off again");+ const plain = fakeSides({ localItems: [onePassword], refuse: items });+ plain.deps.handoff = async () => ({ onePassword: { token: "ops_fake", grants: {} } });+ assert.equal((await createCloudSend(plain.deps).send()).result.failed.length, 0, "a Cloud too old for item choices takes a vault-only 1Password");+ assert.ok(!plain.calls.includes("DELETE /api/logins/1password"));+ const vaults = fakeSides({ localItems: [onePassword], refuse: { "/api/logins/1password/vaults/v1": { status: 500, error: "boom" } } });+ vaults.deps.handoff = async () => ({ onePassword: { token: "ops_fake", grants: { v1: [] } } });+ assert.equal((await createCloudSend(vaults.deps).send()).result.failed.length, 1);+ assert.ok(vaults.calls.includes("DELETE /api/logins/1password"), "a vault choice that did not take closes the token too");});test("chats by row: the cursor moves only past what My Cloud took; one removed there is never sent again; one being answered waits", async () => {diff --git a/server/bot-logins.ts b/server/bot-logins.tsindex 73777e42ab..29fbc2c827 100644--- a/server/bot-logins.ts+++ b/server/bot-logins.ts@@ -174,11 +174,17 @@ export class BotLogins {this.store.setOnePasswordGrant(vaultId, bots);return this.onePassword.status();},- grantItem: (item, bots) => {- if (!this.onePassword.hasItem(item)) return false;+ grantItem: async (item, bots) => {+ // Handing an item back to its vault's choice is kept even while 1Password cannot be read.+ if (bots !== null) {+ const read = await this.onePassword.readsItem(item);+ if (read !== true) return read;+ }this.store.setOnePasswordItemGrant(item, bots);return true;},+ // Kept whole, even for an item not loaded here yet: it then opens no wider than the computer that chose it.+ setItemGrants: (grants) => this.store.setOnePasswordItemGrants(grants),},};}diff --git a/server/onepassword.test.ts b/server/onepassword.test.tsindex f300c96fec..d8c117959e 100644--- a/server/onepassword.test.ts+++ b/server/onepassword.test.ts@@ -142,10 +142,10 @@ describe("1Password logins", () => {["example.org", [], { item: "v1:i2", ownBots: false }],]);expect(linkedSecrets(source).map((secret) => [secret.name, secret.onePassword])).toContainEqual(["Deploy", { item: "v1:i7", ownBots: false }]);- expect(source.hasItem("v1:i1")).toBe(true);- expect(source.hasItem("v1:i6")).toBe(true);- expect(source.hasItem("v1:i3")).toBe(false);- expect(source.hasItem("v9:i1")).toBe(false);+ expect(await source.readsItem("v1:i1")).toBe(true);+ expect(await source.readsItem("v1:i6")).toBe(true);+ expect(await source.readsItem("v1:i3")).toBe(false);+ expect(await source.readsItem("v9:i1")).toBe(false);expect(JSON.stringify(source.items())).not.toContain(VAULT_PASSWORD);});diff --git a/server/onepassword.ts b/server/onepassword.tsindex e3df05373a..52593f9883 100644--- a/server/onepassword.ts+++ b/server/onepassword.ts@@ -192,11 +192,19 @@ export class OnePasswordLogins implements VaultProvider {return { bots: own ?? this.botsFor(entry.vaultId), onePassword: { item, ownBots: own !== undefined } };}- /** Whether the token reads this item (`<vault id>:<item id>`) as a login or a secret. */- hasItem(item: string): boolean {+ /** Whether the token reads this item (`<vault id>:<item id>`) as a login or a secret, looking again in 1Password before+ * saying no; null when 1Password could not be read just now, so an item not loaded yet is never taken for one that is gone. */+ async readsItem(item: string): Promise<boolean | null> {+ const loaded = () => this.refreshedAt !== null && !this.error;+ const reads = () => [...this.entries, ...this.secrets].some((entry) => onePasswordItemKey(entry.vaultId, entry.itemId) === item);if (!this.token()) return false;- const reads = (entry: { vaultId: string; itemId: string }) => onePasswordItemKey(entry.vaultId, entry.itemId) === item;- return this.entries.some(reads) || this.secrets.some(reads);+ const before = this.refreshedAt;+ await this.fresh();+ if (loaded() && reads()) return true;+ // One more look, unless the stale check just took it.+ if (this.refreshedAt === before) await this.refresh();+ if (!this.token()) return false;+ return loaded() ? reads() : null;}private connected(): OnePasswordStatus {diff --git a/server/routes/logins.test.ts b/server/routes/logins.test.tsindex 685041d21c..82bd87fc12 100644--- a/server/routes/logins.test.ts+++ b/server/routes/logins.test.ts@@ -31,9 +31,11 @@ async function serve() {const dir = mkdtempSync(join(tmpdir(), "omb-login-routes-"));dirs.push(dir);const store = new VaultStore({ dataDir: dir });- const { sdk } = fakeOnePasswordSdk({ token: TOKEN, vaults: { v1: { title: "Shared with OMB", items: [+ const vaults = { v1: { title: "Shared with OMB", items: [{ id: "i1", title: "Example", urls: ["https://vault.example.com"], username: "vault-user", password: VAULT_PASSWORD },- ] } } });+ ] } };+ let down: Error | null = null;+ const { sdk } = fakeOnePasswordSdk({ token: TOKEN, vaults, fail: () => down });const onePassword = new OnePasswordLogins({ token: () => store.onePasswordToken(), grants: () => store.onePasswordGrants(), itemGrants: () => store.onePasswordItemGrants(),connect: (token) => sdkOnePasswordClient(sdk, token, "0.0.0") });const logins = new BotLogins(store, onePassword);@@ -53,7 +55,7 @@ async function serve() {answers.push(text);return { status: response.status, body: JSON.parse(text), cache: response.headers.get("cache-control") };};- return { store, logins, call, answers };+ return { store, logins, call, answers, vaults, setDown: (error: Error | null) => { down = error; } };}describe("Settings → Logins routes", () => {@@ -62,6 +64,7 @@ describe("Settings → Logins routes", () => {for (const method of ["PATCH", "DELETE"]) expect(requiredScope(method, "/api/logins/abc")).toBe("admin");expect(requiredScope("PATCH", "/api/logins/1password/vaults/v1")).toBe("admin");expect(requiredScope("PATCH", "/api/logins/1password/items/v1/i1")).toBe("admin");+ expect(requiredScope("PUT", "/api/logins/1password/items")).toBe("admin");});it("add, list, change and delete a login, and never return its password or 2FA key", async () => {@@ -153,6 +156,38 @@ describe("Settings → Logins routes", () => {expect((await logins.candidates("pepper", "vault.example.com")).map((login) => login.username)).toEqual(["vault-user"]);});+ it("looks in 1Password again before calling an item gone, and never calls it gone while 1Password cannot be read", async () => {+ const { store, call, vaults, setDown } = await serve();+ await call("POST", "/api/logins/1password", { token: TOKEN });+ // Added in 1Password after the last load: found on a second look, not refused.+ vaults.v1.items.push({ id: "i2", title: "New", urls: ["https://new.example.com"], username: "new-user", password: VAULT_PASSWORD });+ expect((await call("PATCH", "/api/logins/1password/items/v1/i2", { bots: ["pepper"] })).status).toBe(200);+ expect(store.onePasswordItemGrants()).toEqual({ "v1:i2": ["pepper"] });+ // 1Password unreadable: an item not in the last load is "try again", not "no such item".+ setDown(new Error("fetch failed"));+ const unread = await call("PATCH", "/api/logins/1password/items/v1/i3", { bots: [] });+ expect(unread.status).toBe(503);+ // Handing an item back to its vault's choice never waits on 1Password.+ expect((await call("PATCH", "/api/logins/1password/items/v1/i2", { bots: null })).status).toBe(200);+ expect(store.onePasswordItemGrants()).toEqual({});+ });++ it("takes every item's own bots at once from another computer, dropping the ones it no longer has", async () => {+ const { store, call } = await serve();+ await call("POST", "/api/logins/1password", { token: TOKEN });+ await call("PATCH", "/api/logins/1password/items/v1/i1", { bots: "all" });+ // An item not loaded here yet is kept too, so it opens no wider than where it was chosen.+ const sent = await call("PUT", "/api/logins/1password/items", { items: { "v1:i9": [], "v2:x1": ["quill"] } });+ expect(sent).toMatchObject({ status: 200, body: { items: 2 } });+ expect(store.onePasswordItemGrants()).toEqual({ "v1:i9": [], "v2:x1": ["quill"] });+ expect((await call("PUT", "/api/logins/1password/items", { items: { "v1:i1": ["nobody"] } })).status).toBe(400);+ expect((await call("PUT", "/api/logins/1password/items", { items: { "v1/i1": [] } })).status).toBe(400);+ expect((await call("PUT", "/api/logins/1password/items", { items: [] })).status).toBe(400);+ expect(store.onePasswordItemGrants()).toEqual({ "v1:i9": [], "v2:x1": ["quill"] });+ expect((await call("PUT", "/api/logins/1password/items", { items: {} })).status).toBe(200);+ expect(store.onePasswordItemGrants()).toEqual({});+ });+it("keeps one 1Password item to its own bots ahead of its vault's, and hands it back on null", async () => {const { store, logins, call, answers } = await serve();await call("POST", "/api/logins/1password", { token: TOKEN });diff --git a/server/routes/logins.ts b/server/routes/logins.tsindex 8d6cef0402..bcff78fc1f 100644--- a/server/routes/logins.ts+++ b/server/routes/logins.ts@@ -18,14 +18,20 @@ export interface LoginRouteDeps {disconnect(): OnePasswordStatus;/** Null for a vault the token does not read. */grant(vaultId: string, bots: LoginBots): OnePasswordStatus | null;- /** Bots for one item (`<vault id>:<item id>`) ahead of its vault's; null hands it back. False for an item the token does not read. */- grantItem(item: string, bots: LoginBots | null): boolean;+ /** Bots for one item (`<vault id>:<item id>`) ahead of its vault's; null hands it back. False for an item the token does not+ * read, null when 1Password could not be read just now. */+ grantItem(item: string, bots: LoginBots | null): Promise<boolean | null>;+ /** Every item's own bots at once (what My Cloud keeps of another computer's choices); an item left out goes back to its vault's. */+ setItemGrants(grants: Record<string, LoginBots>): void;};}const ONE_PASSWORD = "/api/logins/1password";const VAULT = /^\/api\/logins\/1password\/vaults\/([\w-]{1,128})$/u;+const ITEMS = "/api/logins/1password/items";const ITEM = /^\/api\/logins\/1password\/items\/([\w-]{1,128})\/([\w-]{1,128})$/u;+const ITEM_KEY = /^[\w-]{1,128}:[\w-]{1,128}$/u;+const UNREAD = "1Password could not be read just now. Try again in a moment.";const ID = /^[\w-]{1,128}$/u;@@ -109,9 +115,24 @@ export function createLoginRoutes(deps: LoginRouteDeps): RouteHandler {const value = body && typeof body === "object" ? body.bots : undefined;const bots = value === null ? { ok: true as const, value: null } : parseBots(value, deps.botExists);if (!bots.ok || bots.value === undefined) return json(res, 400, { error: bots.ok ? LOGIN_ERRORS.bots : bots.error });- if (!deps.onePassword.grantItem(`${item[1]!}:${item[2]!}`, bots.value)) return json(res, 404, { error: "no such item" });+ const granted = await deps.onePassword.grantItem(`${item[1]!}:${item[2]!}`, bots.value);+ if (granted === null) return json(res, 503, { error: UNREAD });+ if (!granted) return json(res, 404, { error: "no such item" });return json(res, 200, { logins: deps.onePassword.list(), onePassword: deps.onePassword.status() });}+ if (path === ITEMS && method === "PUT") {+ const body = await readBody(req, 262_144);+ const items = body && typeof body === "object" ? body.items : undefined;+ if (!items || typeof items !== "object" || Array.isArray(items)) return json(res, 400, { error: "send items as an object of item ids to bots" });+ const grants: Record<string, LoginBots> = {};+ for (const [key, value] of Object.entries(items)) {+ const bots = parseBots(value, deps.botExists);+ if (!ITEM_KEY.test(key) || !bots.ok || bots.value === undefined) return json(res, 400, { error: bots.ok ? LOGIN_ERRORS.bots : bots.error });+ grants[key] = bots.value;+ }+ deps.onePassword.setItemGrants(grants);+ return json(res, 200, { items: Object.keys(grants).length });+ }if (path === ONE_PASSWORD || path.startsWith(`${ONE_PASSWORD}/`)) return json(res, 405, { error: "method not allowed" });if (path === "/api/logins" && method === "POST") {const body = await readBody(req, 16_384);diff --git a/server/vault-store.ts b/server/vault-store.tsindex 726ce12cb1..ec340cadf1 100644--- a/server/vault-store.ts+++ b/server/vault-store.ts@@ -503,10 +503,13 @@ export class VaultStore {/** null hands the item back to its vault's choice. */setOnePasswordItemGrant(key: string, bots: LoginBots | null): void {- const data = this.read();- const { [key]: _previous, ...others } = data.onePasswordItemGrants ?? {};- const grants = bots === null ? others : { ...others, [key]: bots };- const { onePasswordItemGrants: _grants, ...rest } = data;+ const { [key]: _previous, ...others } = this.onePasswordItemGrants();+ this.setOnePasswordItemGrants(bots === null ? others : { ...others, [key]: bots });+ }++ /** Every item's own bots at once: an item left out goes back to its vault's choice. */+ setOnePasswordItemGrants(grants: Record<string, LoginBots>): void {+ const { onePasswordItemGrants: _grants, ...rest } = this.read();this.write(Object.keys(grants).length ? { ...rest, onePasswordItemGrants: grants } : rest);}