Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team keys and passwords: team 1Password (Bitwarden not included) (#6342)
Milind Sonif43a6930ae95
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex ce7ca2bef7..26f2b5db5b 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -86,6 +86,17 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes tsee and delete it in Settings → Vault, which shows a member their own secrets only; an Admin's Vault, exports andbackups never list it, and leaving the team deletes it. A secret an Admin saves in Settings → Vault, or one typed into acard in a shared chat or a group chat, is the team's. One saved before this rule is the team's.+- **1Password for the team.** An Admin connecting 1Password in Settings → Vault connects it for the whole team: the row+ says so, with the setup to use (*Use a dedicated vault and a read-only service account.*). Its secrets serve every+ team bot the vault (or item) is kept to, in shared, group and private chats alike, the same way a secret an Admin+ saved does: a bot asks `request_credential` by the item's name ("Stripe secret key", "Acme OAuth client_secret") or+ by its 1Password reference, `op://<vault>/<item>[/<section>]/<field>`, with vault and item by title or id (a bot that+ may use any 1Password secret is told a reference works as a label; references longer than a label's 80 characters+ don't resolve). The value+ is read from 1Password at that moment and handed over as a ref or a file, never as text, and masked in transcripts.+ A reference reaches only what a name does: a Login's username, password and one-time code never, an item two items'+ titles fit is refused, and one kept to other bots is not found. A member sees and changes none of it: their Vault+ shows only their own secrets and `onePassword: { connected: false }`, and every `/api/logins` route answers them 403.- **Browsers.** Each private chat with a bot drives that person's own browser of the bot, each group chat the groupchat's, and the bot's main chat the team's: separate Chrome profiles, saved sign-ins and live views, so a site onemember signed in to in their chat never opens signed in for another member. The live view shows the browser of the@@ -264,6 +275,13 @@ this server shares with every bot. It exists only on a Team Cloud.`state` `connected` | `needs-sign-in` | `not-connected`, for every member the Admin paired here and only for thoseconnections: whether they connected what an admin asked everyone to connect, never when or how they used it, norany other connection of theirs. A member who left is not listed.+- **The team's Vault** (`server/host/team-vault-report.ts`), additive: `vault: { secrets: [{ name, addedAt, usedBy }],+ providers: [{ kind: "1password", connected, label, lastError? }] }`. `secrets` are the team's saved secrets (an+ Admin's, or a shared or group chat's card), never a member's own; `usedBy` names the team bots that may use each (each+ member's own MausBot left out). `label` is the 1Password vaults the token reads ("" while not connected); `lastError`+ a fixed class (`refused`, `rate-limited`, `cant-connect`, `unavailable`, `unreadable`). 1Password's own items and+ saved logins are not listed. Never a value, the token or a header. The Admin's Apps page shows it as *Keys &+ passwords*, read-only, with *Manage in the app* opening Settings → Vault here (`/?connect=vault`, an admin's only).- Changes are never signed calls of their own. The Admin pairs as the admin making the change (the usual signed pairingwith their `member` claim: an `owner` or `admin` gets the admin scope) and uses that session with the routes the appuses: `PATCH /api/config` for a key, `/api/mcp/servers` to add, test, sign in to and remove a server,diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 72f88ee34f..ecd79d035f 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -98,6 +98,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-mausbot-reach.e2e.test.ts","server/cloud-team-member-secrets.e2e.test.ts","server/cloud-team-new-chat-private.e2e.test.ts",+ "server/cloud-team-onepassword.e2e.test.ts","server/cloud-team-open-reach.e2e.test.ts","server/cloud-team-own-key-apps.e2e.test.ts","server/cloud-team-owners.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 0ba47bb8a0..b2397b5bb4 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -238,6 +238,7 @@ describe("CI outputs", () => {"server/cloud-team-mausbot-reach.e2e.test.ts","server/cloud-team-member-secrets.e2e.test.ts","server/cloud-team-new-chat-private.e2e.test.ts",+ "server/cloud-team-onepassword.e2e.test.ts","server/cloud-team-open-reach.e2e.test.ts","server/cloud-team-own-key-apps.e2e.test.ts","server/cloud-team-owners.e2e.test.ts",diff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.tsindex 2ed0e80c75..e5869d77ea 100644--- a/scripts/testing/cloud-send-fixture.ts+++ b/scripts/testing/cloud-send-fixture.ts@@ -149,16 +149,23 @@ export interface CloudTeamFixture {const TEAM_MACHINE_ID = "0d9e8f7a-6b5c-4d3e-9f8a-7b6c5d4e3f2a";-function fakeOnePassword(at: string, token: string): string {+/** One item in the fake 1Password's one vault, in the SDK's shapes (no website: a secret, not a login). */+export interface FakeOnePasswordItem { id: string; title: string; category: string; fields: Array<{ id: string; title: string; fieldType: string; value: string }> }++function fakeOnePassword(at: string, token: string, items: readonly FakeOnePasswordItem[] = []): string {const sdk = join(at, "node_modules", "@1password", "sdk");mkdirSync(sdk, { recursive: true });writeFileSync(join(sdk, "package.json"), JSON.stringify({ name: "@1password/sdk", version: "0.5.0", main: "index.js" }));writeFileSync(join(sdk, "index.js"), `"use strict";+const ITEMS = ${JSON.stringify(items)};exports.createClient = async ({ auth }) => {if (auth !== ${JSON.stringify(token)}) throw new Error("error authenticating: invalid service account token");return {vaults: { list: async () => [{ id: "v1", title: "Shared with OpenMausBot" }] },- items: { list: async () => [], getAll: async () => ({ individualResponses: [] }) },+ items: {+ list: async () => ITEMS.map(({ id, title, category }) => ({ id, title, category, websites: [] })),+ getAll: async (vaultId, ids) => ({ individualResponses: ITEMS.filter((item) => ids.includes(item.id)).map(({ id, fields }) => ({ content: { id, fields } })) }),+ },};};`);@@ -171,8 +178,10 @@ exports.createClient = async ({ auth }) => {* with an installation of its own as the desktop app registers one, My Cloud registering itself as a Cloud home does.* `env`: more of both servers' environment. `cloudEngine`: lines run at the start of My Cloud's synthetic Claude CLI, to* script its turns (fake-claude-cli.ts). */-export async function launchCloudSendFixture({ onePasswordToken, cloudOnePasswordToken = onePasswordToken, toolCalls = 0, broker, env = {}, cloudEnv = {}, cloudEngine = "", desktopEngine = "", space, cloudSignedIn = true, team }: {+export async function launchCloudSendFixture({ onePasswordToken, cloudOnePasswordToken = onePasswordToken, onePasswordItems = [], toolCalls = 0, broker, env = {}, cloudEnv = {}, cloudEngine = "", desktopEngine = "", space, cloudSignedIn = true, team }: {onePasswordToken: string; cloudOnePasswordToken?: string; toolCalls?: number;+ /** What every server's fake 1Password vault ("Shared with OpenMausBot") holds; empty by default. */+ onePasswordItems?: readonly FakeOnePasswordItem[];/** A Team Cloud too (OMB_CLOUD_ROLE=team), with its own environment and synthetic Claude CLI lines. */team?: { id: string; name: string; env?: NodeJS.ProcessEnv; engine?: string; noAi?: boolean;/** Scopes of this checkout's node_modules (`@duckdb`) linked into the Team Cloud's native tree before it starts: the@@ -221,7 +230,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-clconst child = spawn(process.execPath, ["--import", offline, ...extra, join(SERVER_DIR, "index.ts")], {cwd: join(SERVER_DIR, ".."),env: { PATH: process.env.PATH, ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}), HOME: home, USERPROFILE: home, OMB_DATA_DIR: dataDir,- OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1), OMB_DUCKDB_DIR: fakeOnePassword(join(home, "native"), acceptedToken), ...env, ...own },+ OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1), OMB_DUCKDB_DIR: fakeOnePassword(join(home, "native"), acceptedToken, onePasswordItems), ...env, ...own },stdio: ["ignore", "pipe", "pipe", ...(ipc ? ["ipc" as const] : [])],});children.add(child);diff --git a/server/bot-logins.test.ts b/server/bot-logins.test.tsindex 8523a042fe..a30b81d158 100644--- a/server/bot-logins.test.ts+++ b/server/bot-logins.test.ts@@ -140,5 +140,8 @@ describe("the secrets a bot may use", () => {expect(deploy!.id).toMatch(/^linked-[0-9a-f]{32}$/u);expect(reads).toEqual(["fake:1/user"]);expect(held).toEqual(["value-of-fake:1-user"]);+ expect(logins.secretsPrompt("payroll", TEAM_READER), "a bot that may use the manager's secrets").toContain("op://vault/item/field");+ const none = new BotLogins(store, { ...provider, items: () => [] } as unknown as OnePasswordLogins);+ expect(none.secretsPrompt("notes", TEAM_READER), "nothing from the manager for this bot").not.toContain("op://");});});diff --git a/server/bot-logins.ts b/server/bot-logins.tsindex 7228b1c5a3..d5edad11ed 100644--- a/server/bot-logins.ts+++ b/server/bot-logins.ts@@ -7,6 +7,7 @@ import { receiveLoginHandoff, type ConnectionHandoffAnswer, type ConnectionHandoimport type { VaultReader, VaultStore } from "./vault-store.ts";import type { OnePasswordLogins } from "./onepassword.ts";import type { LoginRouteDeps } from "./routes/logins.ts";+import { savedSecretsPrompt } from "./system-prompt.ts";import { findLinkedSecret, linkedCandidates, linkedSecretNames, linkedSecrets, linkedSites, readLinkedSecret, type VaultProvider } from "./vault/providers.ts";const linkedItemId = (secretId: string, field: string | undefined) => `linked-${createHash("sha256").update(`${secretId}\0${field ?? ""}`).digest("hex").slice(0, 32)}`;@@ -117,6 +118,11 @@ export class BotLogins {return [...this.store.secretNamesFor(botId, reader), ...linked];}+ /** The Vault's sentence in the bot's prompt: the names it may ask for, and that 1Password references work while it may use any. */+ secretsPrompt(botId: string, reader: VaultReader): string {+ return savedSecretsPrompt(this.secretNamesFor(botId, reader), linkedSecrets(this.onePassword, botId).length > 0);+ }+/** A secret a linked manager holds for the bot by this name, read from it now; its id is safe as a file name. */async linkedSecret(name: string, botId: string): Promise<{ id: string; name: string; value: string } | null> {await this.fresh();diff --git a/server/cloud-team-admin.ts b/server/cloud-team-admin.tsindex 3e720ea0cf..5bd1baa611 100644--- a/server/cloud-team-admin.ts+++ b/server/cloud-team-admin.ts@@ -3,6 +3,7 @@// environment value, nor any part of an MCP URL but its host.import type { ConnectorServiceState } from "./composio.ts";import type { ProviderSnapshot } from "./contracts.ts";+import type { VaultProviderFailure } from "./onepassword.ts";export const CLOUD_TEAM_ADMIN_PATH = "/api/cloud/team/admin";@@ -30,6 +31,14 @@ export interface ConnectionStatus {export type PersonConnectionState = "connected" | "needs-sign-in" | "not-connected";+/** The team's Vault, by name only: the secrets an Admin saved or a shared chat's card kept (never a member's own), and the+ * password managers linked to it. `usedBy`: the team bots that may use it (each member's own MausBot is left out).+ * `label`: the manager's vaults the token reads, "" while not connected. `lastError`: a fixed class, never the manager's words. */+export interface TeamVaultSummary {+ secrets: { name: string; addedAt: string; usedBy?: string[] }[];+ providers: { kind: "1password"; connected: boolean; label: string; lastError?: VaultProviderFailure }[];+}+/** The wire shape of `GET /api/cloud/team/admin` (signed by the Admin). */export interface TeamAdminSummary {v: 1;@@ -53,6 +62,7 @@ export interface TeamAdminSummary {apps: Record<string, string[]>; mcp: Record<string, string[]>;states?: { apps: Record<string, Record<string, PersonConnectionState>>; mcp: Record<string, Record<string, PersonConnectionState>> };};+ vault?: TeamVaultSummary;}type ListedMcp = { name: string; enabled?: boolean; url?: string; type?: string; command?: string; headerKeys?: string[]; envKeys?: string[]; auth?: string };diff --git a/server/cloud-team-onepassword.e2e.test.ts b/server/cloud-team-onepassword.e2e.test.tsnew file mode 100644index 0000000000..07c2cf4933--- /dev/null+++ b/server/cloud-team-onepassword.e2e.test.ts@@ -0,0 +1,120 @@+// 1Password on a real Team Cloud (OMB_CLOUD_ROLE=team) with a fake SDK: an Admin connects it in Settings → Vault for the+// whole team; a member's private chat and the bot's shared chat get its secrets by name and by op:// reference with no+// card, never a Login's password; a member neither sees nor manages it; the Admin's signed report names the team's secrets+// and 1Password's state, never a value, the token or a member's own secret. No value is ever printed.+import { randomBytes } from "node:crypto";+import { afterAll, beforeAll, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { CLOUD_TEAM_ADMIN_PATH } from "./cloud-team-admin.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const OWNER = { email: "[email protected]", role: "owner" as const };+const ADMIN = { email: "[email protected]", role: "admin" as const };+const ADA = { email: "[email protected]", role: "member" as const };+const TOKEN = `ops_fake-team-${randomBytes(12).toString("hex")}`;+const STRIPE = `sk_test_fake-1p-${randomBytes(12).toString("hex")}`;+const BANK_PASSWORD = `fake-bank-${randomBytes(12).toString("hex")}`;+const TEAM_VALUE = `fake-team-deploy-${randomBytes(12).toString("hex")}`;+const ADA_VALUE = `fake-ada-own-${randomBytes(12).toString("hex")}`;+const VAULT = "Shared with OpenMausBot";+const ITEMS = [+ { id: "i1", title: "Stripe secret key", category: "ApiCredentials", fields: [{ id: "credential", title: "credential", fieldType: "Concealed", value: STRIPE }] },+ { id: "i2", title: "Bank", category: "Login", fields: [{ id: "username", title: "username", fieldType: "Text", value: "treasurer" },+ { id: "password", title: "password", fieldType: "Concealed", value: BANK_PASSWORD }] },+];++type Asked = { status: number; body: { messageId?: string; text?: string } };++let fx: CloudSendFixture, team: CloudTeamFixture;+let admin = "", ada = "";+let ledger: { id: string; threadId: string };+let adaThread = "";+const said: string[] = [];++const as = async (token: string, method: string, path: string, body?: unknown) => {+ const answer = await team.as(token, method, path, body);+ said.push(JSON.stringify(answer.body));+ return answer;+};+/** request_credential from Ledger's turn in this conversation, as its agents tools send it. */+async function ask(threadId: string, label: string): Promise<Asked> {+ const bearer = await team.capability(ledger.id, threadId);+ const answer = await fetch(`${team.base}/api/internal/request-credential`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" },+ body: JSON.stringify({ label, reason: "For test charges.", delivery: "ref" }) });+ const text = await answer.text();+ said.push(text);+ return { status: answer.status, body: JSON.parse(text) };+}+/** Whether any answer, or the servers' logs, holds this value: never the value itself in a failure. */+const leaked = (value: string) => [...said, ...fx.answers, fx.logs()].some((text) => text.includes(value));++beforeAll(async () => {+ // Only the Team Cloud's own token matters here; the other servers' fakes accept another one.+ fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, onePasswordItems: ITEMS, team: { id: "team-acme-1password", name: "Acme" } });+ team = fx.team!;+ const owner = (await team.pair(OWNER)).token!;+ admin = (await team.pair(ADMIN)).token!;+ ada = (await team.pair(ADA)).token!;+ ledger = (await as(owner, "POST", "/api/bots", { name: "Ledger", visibility: "everyone" })).body.bot;+ adaThread = (await as(ada, "POST", `/api/bots/${ledger.id}/tasks`, { title: "Billing" })).body.task.threadId;+}, hostTimeout(300_000));++afterAll(async () => {+ await fx?.close();+});++it("an Admin connects 1Password in Settings → Vault for the whole team", async () => {+ const connected = await as(admin, "POST", "/api/logins/1password", { token: TOKEN });+ expect(connected.status, JSON.stringify(connected.body)).toBe(200);+ expect(connected.body.onePassword).toMatchObject({ connected: true, vaults: [{ id: "v1", title: VAULT, bots: "all" }] });+ const vault = (await as(admin, "GET", "/api/vault")).body;+ expect(vault.onePassword.connected).toBe(true);+ expect(vault.secrets.map((one: { name: string }) => one.name)).toEqual(["Stripe secret key"]);+}, hostTimeout(30_000));++it("a member's private chat and the shared chat get it by name and by op:// reference with no card, never a Login's password", async () => {+ for (const [where, threadId] of [["Ada's private chat", adaThread], ["the shared chat", ledger.threadId]] as const) {+ for (const label of ["Stripe secret key", `op://${VAULT}/Stripe secret key`, `op://${VAULT}/Stripe secret key/credential`, "op://v1/i1"]) {+ const asked = await ask(threadId, label);+ expect([asked.status, asked.body.messageId], `${where}: ${label}`).toEqual([200, undefined]);+ expect(asked.body.text, `${where}: ${label}`).toMatch(/secret-ref:[0-9a-f]{32}/u);+ }+ }+ for (const label of [`op://${VAULT}/Bank/password`, `op://${VAULT}/Bank`, `op://${VAULT}/Bank/username`]) {+ expect((await ask(adaThread, label)).status, label).toBe(201);+ }+ expect(leaked(STRIPE), "the 1Password value in any answer or log").toBe(false);+ expect(leaked(BANK_PASSWORD), "the Login's password in any answer or log").toBe(false);+}, hostTimeout(60_000));++it("a member neither sees nor manages the team's 1Password", async () => {+ const mine = (await as(ada, "GET", "/api/vault")).body;+ expect(mine.onePassword).toEqual({ connected: false });+ expect(mine.secrets).toEqual([]);+ for (const [method, path, body] of [+ ["POST", "/api/logins/1password", { token: TOKEN }], ["POST", "/api/logins/1password/refresh", {}], ["DELETE", "/api/logins/1password", undefined],+ ["PATCH", "/api/logins/1password/vaults/v1", { bots: [] }], ["PATCH", "/api/logins/1password/items/v1/i1", { bots: [] }],+ ["PUT", "/api/logins/1password/items", { items: {} }], ["GET", "/api/logins", undefined],+ ] as const) {+ expect((await as(ada, method, path, body)).status, `${method} ${path}`).toBe(403);+ }+ expect((await as(admin, "GET", "/api/vault")).body.onePassword.connected, "still connected").toBe(true);+}, hostTimeout(30_000));++it("the Admin's signed report names the team's secrets and 1Password's state, never a value, the token or a member's own secret", async () => {+ expect((await as(admin, "POST", "/api/vault/secrets", { name: "Team deploy key", value: TEAM_VALUE, bots: "all" })).status).toBe(201);+ const card = await ask(adaThread, "Ada's own key");+ expect(card.status).toBe(201);+ expect((await as(ada, "POST", `/api/bots/${ledger.id}/secret-cards/${card.body.messageId}/save`, { threadId: adaThread, value: ADA_VALUE })).status).toBe(200);+ expect((await as(ada, "GET", "/api/vault")).body.secrets.map((one: { name: string }) => one.name)).toEqual(["Ada's own key"]);++ const report = await team.signed("GET", CLOUD_TEAM_ADMIN_PATH);+ expect(report.status, JSON.stringify(report.body)).toBe(200);+ expect(report.body.vault.providers).toEqual([{ kind: "1password", connected: true, label: VAULT }]);+ expect(report.body.vault.secrets).toEqual([{ name: "Team deploy key", addedAt: expect.stringMatching(/^\d{4}-\d\d-\d\dT/u), usedBy: expect.arrayContaining(["Ledger"]) }]);+ const text = JSON.stringify(report.body);+ for (const [what, value] of [["a member's own secret", "Ada's own key"], ["the token", TOKEN], ["the team's value", TEAM_VALUE], ["1Password's value", STRIPE], ["her value", ADA_VALUE]] as const) {+ expect(text.includes(value), what).toBe(false);+ }+}, hostTimeout(60_000));diff --git a/server/host/connection-health-host.ts b/server/host/connection-health-host.tsindex ecb74680d2..a21a3c38f7 100644--- a/server/host/connection-health-host.ts+++ b/server/host/connection-health-host.ts@@ -26,6 +26,9 @@ type Bot = {};type OAuth = Pick<McpOAuthManager, "authState" | "tokenRefused" | "endsAt">;+/** A bot the team shares, as the Admin's report names them: not hidden, not moved away, not a member's own MausBot. */+export const isTeamBot = (bot: Pick<Bot, "hidden" | "movedTo" | "defaultBot">): boolean => !bot.hidden && !bot.movedTo && !bot.defaultBot?.person;+export interface ConnectionHealthHostDeps<B extends Bot = Bot> {/** Where health is kept: a Team Cloud's data folder. Null elsewhere, where only the sign-in check runs. */dataDir: string | null;@@ -106,7 +109,7 @@ export function createConnectionHealthHost<B extends Bot>(deps: ConnectionHealthnow,}) : null;- const teamBots = () => deps.bots().filter((bot) => !bot.hidden && !bot.movedTo && !bot.defaultBot?.person);+ const teamBots = () => deps.bots().filter(isTeamBot);const usesApp = (bot: B, slug: string) => bot.composio !== false&& (!bot.connectorScopes || Object.hasOwn(bot.connectorScopes.apps, slug))&& (bot.connectorTools === undefined || Object.hasOwn(bot.connectorTools, slug));diff --git a/server/host/team-vault-report.test.ts b/server/host/team-vault-report.test.tsnew file mode 100644index 0000000000..ef62dae059--- /dev/null+++ b/server/host/team-vault-report.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest";++import { ONE_PASSWORD_REFUSED, OnePasswordUnavailableError, onePasswordFailure, onePasswordProblem } from "../onepassword.ts";+import { teamVaultReport } from "./team-vault-report.ts";++const BOTS = [+ { id: "b1", name: "Ledger" },+ { id: "b2", name: "Scout" },+ { id: "b3", name: "Hidden", hidden: true },+ { id: "b4", name: "Ada's MausBot", defaultBot: { person: "p_ada" } },+];++describe("the team's Vault in the Admin's report", () => {+ it("names each secret, when it was added and the team bots that may use it, never a member's own MausBot", () => {+ const report = teamVaultReport({+ secrets: [{ name: "Stripe key", createdAt: Date.UTC(2026, 10, 1), bots: "all" }, { name: "Deploy key", createdAt: Date.UTC(2026, 10, 2), bots: ["b2", "b4", "gone"] }],+ bots: BOTS, onePassword: { connected: false },+ });+ expect(report).toEqual({+ secrets: [+ { name: "Stripe key", addedAt: "2026-11-01T00:00:00.000Z", usedBy: ["Ledger", "Scout"] },+ { name: "Deploy key", addedAt: "2026-11-02T00:00:00.000Z", usedBy: ["Scout"] },+ ],+ providers: [{ kind: "1password", connected: false, label: "" }],+ });+ });++ it("says 1Password's vaults and why it is not working as a fixed class, never its words or token", () => {+ const report = teamVaultReport({ secrets: [], bots: BOTS, onePassword: { connected: true, items: 2, error: ONE_PASSWORD_REFUSED,+ vaults: [{ id: "v1", title: "Team keys", items: 2, bots: "all" }, { id: "v2", title: "Finance", items: 0, bots: ["b1"] }] } });+ expect(report.providers).toEqual([{ kind: "1password", connected: true, label: "Team keys, Finance", lastError: "refused" }]);+ expect(JSON.stringify(report)).not.toContain(ONE_PASSWORD_REFUSED);+ });++ it("classes every 1Password problem", () => {+ const failure = (error: unknown) => onePasswordFailure(onePasswordProblem(error));+ expect(failure(new Error("error authenticating: invalid service account token"))).toBe("refused");+ expect(failure(new Error("service account token had invalid format"))).toBe("refused");+ expect(failure(Object.assign(new Error("slow down"), { name: "RateLimitExceededError" }))).toBe("rate-limited");+ expect(failure(new Error("getaddrinfo ENOTFOUND my.1password.com"))).toBe("cant-connect");+ expect(failure(new OnePasswordUnavailableError())).toBe("unavailable");+ expect(failure(new SyntaxError("Unexpected token"))).toBe("unreadable");+ });+});diff --git a/server/host/team-vault-report.ts b/server/host/team-vault-report.tsnew file mode 100644index 0000000000..8b1318a4a1--- /dev/null+++ b/server/host/team-vault-report.ts@@ -0,0 +1,30 @@+// The team's Vault as its admins see it on the Admin's Apps page (`GET /api/cloud/team/admin` `vault`).+// Security invariant: names and states only; never a value, a token or a header, and never a member's own secret, which+// the caller leaves out by reading the Vault as the team (TEAM_READER).+import type { LoginBots, OnePasswordStatus } from "../../shared/logins.ts";+import type { TeamVaultSummary } from "../cloud-team-admin.ts";+import { onePasswordFailure } from "../onepassword.ts";+import { isTeamBot } from "./connection-health-host.ts";++const SECRETS_MAX = 500;+const BOTS_MAX = 200;++type ReportBot = { id: string; name: string; hidden?: boolean; movedTo?: unknown; defaultBot?: { person?: string } };++export function teamVaultReport(input: {+ secrets: ReadonlyArray<{ name: string; createdAt: number; bots: LoginBots }>;+ bots: readonly ReportBot[];+ onePassword: OnePasswordStatus;+}): TeamVaultSummary {+ const team = input.bots.filter(isTeamBot);+ const usedBy = (bots: LoginBots) => team.filter((bot) => bots === "all" || bots.includes(bot.id)).map((bot) => bot.name).slice(0, BOTS_MAX);+ const { onePassword } = input;+ return {+ secrets: input.secrets.slice(0, SECRETS_MAX).map((secret) => ({ name: secret.name, addedAt: new Date(secret.createdAt).toISOString(), usedBy: usedBy(secret.bots) })),+ providers: [{+ kind: "1password", connected: onePassword.connected,+ label: onePassword.connected ? (onePassword.vaults ?? []).map((vault) => vault.title).join(", ") : "",+ ...(onePassword.connected && onePassword.error ? { lastError: onePasswordFailure(onePassword.error) } : {}),+ }],+ };+}diff --git a/server/index.ts b/server/index.tsindex a2b21f8a21..ac2e5ef3e7 100644--- a/server/index.ts+++ b/server/index.ts@@ -414,7 +414,7 @@ import {ROUTINE_EXECUTION_PROMPT, READ_ONLY_ROUTINE_EXECUTION_PROMPT,WEBHOOK_PROMPT, BOT_API_PROMPT, BOT_API_OWNER_PROMPT, AUTOMATION_REPLY_PROMPT,resolveComputerPromptKind,- savedLoginsPrompt, savedSecretsPrompt, heavyPrompt,+ savedLoginsPrompt, heavyPrompt,teamAvailabilityPart, teamRosterPart,} from "./system-prompt.ts";import { shellTimeoutHookResult } from "./shell-timeout-hint.ts";@@ -625,7 +625,7 @@ import { createConfigRoutes } from "./routes/config.ts";import { createInstanceRoutes } from "./routes/instances.ts";import { createMcpConfig } from "./host/mcp-config.ts";import { createMcpServerRoutes } from "./routes/mcp-servers.ts";-import { teamAdminSummary } from "./cloud-team-admin.ts"; import { createConnectionHealthHost } from "./host/connection-health-host.ts";+import { teamAdminSummary } from "./cloud-team-admin.ts"; import { createConnectionHealthHost } from "./host/connection-health-host.ts"; import { teamVaultReport } from "./host/team-vault-report.ts";import { createSetupImportRoutes } from "./routes/setup-import.ts";import { createComputerRoutes } from "./routes/computers.ts";import { createStatusRoutes } from "./routes/status.ts";@@ -2955,7 +2955,7 @@ function previewSystemPrompt(bot: BotRecord) {{ id: "mcp", label: "MCP servers", text: caps?.customMcp ? customMcpPrompt(Object.keys(engineMcpServers(bot)), mcpServersHost.off(bot)) : "" }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(bot) },{ id: "browser", label: "Browser", text: previewPlan.browser ? browserPromptFor(bot, agentsMounted) : "" },{ id: "coordination", label: "Team", text: agentsMounted && coordination ? ` ${coordination}` : "" },- { id: "credential", label: "Credentials", text: agentsMounted ? CREDENTIAL_PROMPT + savedSecretsPrompt(botLogins.secretNamesFor(bot.id, TEAM_READER)) : "" },+ { id: "credential", label: "Credentials", text: agentsMounted ? CREDENTIAL_PROMPT + botLogins.secretsPrompt(bot.id, TEAM_READER) : "" },{ id: "routine", label: "Triggers", text: agentsMounted ? TRIGGER_PROMPT : "" },{ id: "profile", label: "Profile changes", text: agentsMounted ? PROFILE_PROMPT : "" },{ id: "section-context", label: "Section context", text: sectionContextSystemPrompt(bot.section) },@@ -8246,7 +8246,7 @@ async function beginTurn(: integrations.agents && sectionPeers.length > 0? peerRosterPrompt(sectionPeers, bot): { rules: "", roster: "" }; const coordinationPrompt = teamPrompt.rules + (integrations.agents ? personalReach.prompt(bot, threadId, sectionPeers) : "");- const credentialPrompt = integrations.agents ? CREDENTIAL_PROMPT + savedSecretsPrompt(botLogins.secretNamesFor(bot.id, vaultReaders.turn(threadId))) + THREADS_PROMPT + WIDGET_PROMPT : "";+ const credentialPrompt = integrations.agents ? CREDENTIAL_PROMPT + botLogins.secretsPrompt(bot.id, vaultReaders.turn(threadId)) + THREADS_PROMPT + WIDGET_PROMPT : "";const routinePrompt = integrations.agents ? TRIGGER_PROMPT : "";const profilePrompt = integrations.agents ? PROFILE_PROMPT : "";const recallPrompt = integrations.agents && bot.memoryEnabled !== false ? SESSION_SEARCH_SYSTEM_PROMPT : "";@@ -10048,7 +10048,7 @@ async function runClaimedGroupMemberTurn(readyGroup.bulletin.trim() && `Room bulletin (shared instructions for everyone):\n${readyGroup.bulletin.trim()}`,`Reply as yourself, briefly and conversationally. To bring a teammate in, mention them like @Name — they'll see the conversation and respond.${readyGroup.dm ? "" : ` To get ${typeof userName === "string" ? `${userName}'s` : "a person's"} attention or ask them something blocking, write @you.`} A "[reacted 👍 to …]" line is that person's whole reply to the message it names: 👍 means yes, go ahead when that message asked them something or offered to do something, and only got it (start no new work) when it just told them something; 👎 means no.`,outsideRoom.length > 0 && roomPeerRosterSystemPrompt(outsideRoom), sharedNamesNote(roomMembers.filter((member) => member.id !== bot.id), Boolean(integrations.agents)),- integrations.agents && (CREDENTIAL_PROMPT + savedSecretsPrompt(botLogins.secretNamesFor(bot.id, vaultReaders.turn(threadId))) + (orchestration && !orchestration.roomHandoffId ? THREADS_PROMPT : "")).trim(),+ integrations.agents && (CREDENTIAL_PROMPT + botLogins.secretsPrompt(bot.id, vaultReaders.turn(threadId)) + (orchestration && !orchestration.roomHandoffId ? THREADS_PROMPT : "")).trim(),integrations.agents && (!orchestration || orchestration.roomHandoffId) && "For actual OpenMausBot teamwork, discover IDs with list_room_targets and use coordinate_bots for advice or work in this or another room. Do not substitute native coding helpers for these named bots. Consult only when needed to make a decision; no discussion step is mandatory. Give concrete responsibilities, exact accessible paths and acceptance checks. End your turn after assigning; busy teammates queue and results automatically resume you. When they return, finish the requested verification and give the user one final answer. Native helper names are not evidence that an OpenMausBot teammate participated. Plain @mentions are only for conversational replies in this room." + requesterRule,integrations.agents && TRIGGER_PROMPT.trim(),integrations.agents && PROFILE_PROMPT.trim(),@@ -11779,7 +11779,7 @@ function teamAdminHost() {status: configStatus(),voice: { key: Boolean(cfg.tts?.key?.trim()), included: tts.describeVoice(cfg).included === true },engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, name: instance.displayName ?? instance.driverKind, snapshot: registry.lastSnapshot(instance.instanceId) })),- }), ...await teamConnections.adminExtras() }),+ }), ...await teamConnections.adminExtras(), vault: teamVaultReport({ secrets: logins.listSecrets(TEAM_READER), bots: store.bots, onePassword: onePassword.status() }) }),};}diff --git a/server/onepassword.test.ts b/server/onepassword.test.tsindex 341d37331b..e8c1606ab6 100644--- a/server/onepassword.test.ts+++ b/server/onepassword.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";import type { LoginBots } from "../shared/logins.ts";import { fillLogin, type FillCandidate } from "./login-fill.ts";-import { loginExtraFields, loginFields, ONE_PASSWORD_MALFORMED, ONE_PASSWORD_REFUSED, OnePasswordLogins, onePasswordProblem, onePasswordUnavailable, OnePasswordUnavailableError, sdkOnePasswordClient, secretFields } from "./onepassword.ts";+import { loginExtraFields, loginFields, ONE_PASSWORD_MALFORMED, ONE_PASSWORD_REFUSED, OnePasswordLogins, onePasswordProblem, onePasswordUnavailable, OnePasswordUnavailableError, parseOnePasswordReference, sdkOnePasswordClient, secretFields } from "./onepassword.ts";import { FakeLoginPage, LOGIN_FORM } from "./testing/fake-login-page.ts";import { fakeOnePasswordSdk } from "./testing/fake-onepassword.ts";import { parseTotpKey, totpCode } from "./totp.ts";@@ -350,4 +350,50 @@ describe("1Password secrets", () => {failure = null;await expect(readLinkedSecret({ ...deploy, field: "nothing" })).rejects.toThrow("Deploy is no longer in 1Password, or has no value there.");});++ it("reads a secret by its op:// reference, by vault and item title or id, through the same bots as its name", async () => {+ const { source } = setup({ itemGrants: { "v1:i8": ["quill"] } });+ await source.refresh();+ const read = async (reference: string, bot = "pepper") => {+ const use = findLinkedSecret([source], reference, bot);+ return use ? readLinkedSecret(use) : null;+ };+ expect(await read("op://Shared with OMB/Stripe secret key")).toBe(STRIPE);+ expect(await read("op://shared with omb/stripe secret key/credential")).toBe(STRIPE);+ expect(await read("op://v1/i6")).toBe(STRIPE);+ expect(await read("op://Shared with OMB/Plain token/token")).toBe(PLAIN_TOKEN);+ expect(await read("op://Shared with OMB/Partner API/Client ID")).toBe(CLIENT_ID);+ expect(await read("op://Shared with OMB/Partner API/Section/Client Secret")).toBe(CLIENT_SECRET);+ expect(await read("op://Shared with OMB/Acme OAuth/client_secret", "quill")).toBe(ACME_SECRET);+ expect(await read("op://Shared with OMB/Acme OAuth/client_secret"), "an item kept to other bots").toBeNull();+ expect(await read("op://Shared with OMB/Stripe secret key/nothing")).toBeNull();+ expect(await read("op://Finance/Stripe secret key")).toBeNull();+ });++ it("never reads a Login's username, password or one-time code by reference", async () => {+ const { source } = setup();+ await source.refresh();+ for (const reference of ["op://Shared with OMB/Partner API/password", "op://Shared with OMB/Partner API/username", "op://Shared with OMB/Example/password",+ "op://Shared with OMB/Example/one-time password", "op://Shared with OMB/Example/password?attribute=otp", "op://Finance/Bank/password"]) {+ expect(findLinkedSecret([source], reference, "pepper"), reference).toBeNull();+ }+ });++ it("refuses a reference that two items fit, rather than picking one", async () => {+ const { sdk } = fakeOnePasswordSdk({ token: TOKEN, vaults: { v1: { title: "Team", items: [+ { id: "a", title: "Deploy key", category: "Password", urls: [], password: "fake-deploy-a" },+ { id: "b", title: "Deploy key", category: "Password", urls: [], password: "fake-deploy-b" },+ ] } } });+ const source = new OnePasswordLogins({ token: () => TOKEN, connect: (value) => sdkOnePasswordClient(sdk, value, "9.9.9") });+ await source.refresh();+ expect(findLinkedSecret([source], "op://Team/Deploy key", "pepper")).toBeNull();+ expect(await readLinkedSecret(findLinkedSecret([source], "op://Team/b", "pepper")!)).toBe("fake-deploy-b");+ });++ it("parses op:// references with or without a section, and nothing else", () => {+ expect(parseOnePasswordReference("op://Team/Stripe")).toEqual({ vault: "Team", item: "Stripe" });+ expect(parseOnePasswordReference(" op://Team/Stripe/credential ")).toEqual({ vault: "Team", item: "Stripe", field: "credential" });+ expect(parseOnePasswordReference("op://Team/Stripe/API/credential")).toEqual({ vault: "Team", item: "Stripe", field: "credential" });+ for (const other of ["Stripe", "op://Team", "op://Team/Stripe/a/b/c", "op://Team/Stripe/password?attribute=otp", "https://Team/Stripe"]) expect(parseOnePasswordReference(other), other).toBeNull();+ });});diff --git a/server/onepassword.ts b/server/onepassword.tsindex dce6e88c47..99ed5d6089 100644--- a/server/onepassword.ts+++ b/server/onepassword.ts@@ -57,10 +57,9 @@ const FIELDS_MAX = 20;* password, a Secure Note's text, or else its first concealed field, or else its first field. */export function secretFields(category: string, content: OnePasswordItemContent): Map<string, string> {const values = new Map<string, string>();- const usable = content.fields.filter((field) => field.value && (field.fieldType === "Concealed" || field.fieldType === "Text"));+ const usable = usableFields(content);const note = category === "SecureNote" ? content.notes : undefined;- const main = note ? undefined- : usable.find((field) => field.id === MAIN_FIELD[category]) ?? usable.find((field) => field.fieldType === "Concealed") ?? usable[0];+ const main = secretMain(category, content);const mainValue = note || main?.value;if (mainValue) values.set("", mainValue);for (const field of usable) {@@ -70,14 +69,28 @@ export function secretFields(category: string, content: OnePasswordItemContent):return values;}+const usableFields = (content: OnePasswordItemContent) =>+ content.fields.filter((field) => field.value && (field.fieldType === "Concealed" || field.fieldType === "Text"));++/** The field a secret item's name alone reads: none for a Secure Note with text, which its text is. */+function secretMain(category: string, content: OnePasswordItemContent): SdkField | undefined {+ if (category === "SecureNote" && content.notes) return undefined;+ const usable = usableFields(content);+ return usable.find((field) => field.id === MAIN_FIELD[category]) ?? usable.find((field) => field.fieldType === "Concealed") ?? usable[0];+}++/** Security: a Login's username and password are never among these, so no name or reference reaches them as a secret. */+function loginExtras(content: OnePasswordItemContent): { extra: SdkField[]; main: SdkField | undefined } {+ const { username, password } = loginFieldsOf(content.fields);+ const extra = usableFields(content).filter((field) => field !== username && field !== password && field.title.trim());+ return { extra, main: extra.find((field) => field.fieldType === "Concealed") ?? extra[0] };+}+/** A Login item's own extra fields, such as a client ID and secret, by title, never its username, password or one-time* code; "" is the first concealed one, or else the first, so the item's name alone reads it too. */export function loginExtraFields(content: OnePasswordItemContent): Map<string, string> {- const { username, password } = loginFieldsOf(content.fields);- const extra = content.fields.filter((field) => field !== username && field !== password- && field.value && field.title.trim() && (field.fieldType === "Concealed" || field.fieldType === "Text"));+ const { extra, main } = loginExtras(content);const values = new Map<string, string>();- const main = extra.find((field) => field.fieldType === "Concealed") ?? extra[0];if (main) values.set("", main.value);for (const field of extra) if (!values.has(field.title.trim()) && values.size <= FIELDS_MAX) values.set(field.title.trim(), field.value);return values;@@ -88,6 +101,19 @@ function secretValues(category: string, content: OnePasswordItemContent): Map<streturn category === "Login" ? loginExtraFields(content) : secretFields(category, content);}+/** The title of the field an item's name alone reads, which a reference may also name. */+function mainTitle(category: string, content: OnePasswordItemContent): string | undefined {+ return (category === "Login" ? loginExtras(content).main : secretMain(category, content))?.title.trim() || undefined;+}++/** A 1Password secret reference, `op://<vault>/<item>[/<section>]/<field>`, by name or id; null for anything else,+ * such as one with a query (`?attribute=otp`). */+export function parseOnePasswordReference(reference: string): { vault: string; item: string; field?: string } | null {+ const match = /^op:\/\/([^/?]+)\/([^/?]+)(?:\/(?:[^/?]+\/)?([^/?]+))?$/u.exec(reference.trim());+ if (!match) return null;+ return { vault: match[1]!, item: match[2]!, ...(match[3] ? { field: match[3] } : {}) };+}+/** The SDK did not load: a fault in this installation, never in the person's token, which was not even checked. */export class OnePasswordUnavailableError extends Error {constructor() {@@ -133,10 +159,12 @@ interface Entry extends LoginPlace {interface SecretEntry {id: string;vaultId: string;+ vault: string;itemId: string;category: string;name: string;fields: string[];+ main?: string;}const isLogin = (item: { category: string; urls: string[] }) => item.category === "Login" && item.urls.length > 0;@@ -167,16 +195,31 @@ function bySite(hosts: Iterable<string>): Map<string, string[]> {export const ONE_PASSWORD_MALFORMED = "That is not a whole 1Password service account token. Copy all of it (it starts with ops_ and is very long), or make a new one in 1Password under Developer → Service accounts.";export const ONE_PASSWORD_REFUSED = "1Password did not accept the token: it may have been revoked, expired, or lost access to its vault. Make a new service account token in 1Password and paste it here.";+const ONE_PASSWORD_LIMITED = "1Password is limiting requests right now. Try again in a few minutes.";+const ONE_PASSWORD_UNREACHABLE = "Could not reach 1Password. Check the internet connection and try again.";+const ONE_PASSWORD_UNREADABLE = "1Password could not be read. Try again, or connect it again with a new token.";+/** Words for the person, never the token. A fault of this installation is never blamed on the token. */export function onePasswordProblem(error: unknown): string {if (error instanceof OnePasswordUnavailableError) return error.message;const name = error instanceof Error ? error.name : "";const text = error instanceof Error ? error.message : String(error);- if (name === "RateLimitExceededError" || /rate limit/iu.test(text)) return "1Password is limiting requests right now. Try again in a few minutes.";+ if (name === "RateLimitExceededError" || /rate limit/iu.test(text)) return ONE_PASSWORD_LIMITED;if (/invalid format|deserializ/iu.test(text)) return ONE_PASSWORD_MALFORMED;if (name === "AuthExpiredError" || /invalid|unauthori[sz]ed|authenticat|service account token|forbidden|\b40[13]\b/iu.test(text)) return ONE_PASSWORD_REFUSED;- if (/fetch|network|ENOTFOUND|ECONN|timed? ?out|dns/iu.test(text)) return "Could not reach 1Password. Check the internet connection and try again.";- return "1Password could not be read. Try again, or connect it again with a new token.";+ if (/fetch|network|ENOTFOUND|ECONN|timed? ?out|dns/iu.test(text)) return ONE_PASSWORD_UNREACHABLE;+ return ONE_PASSWORD_UNREADABLE;+}++/** Why 1Password is not working, as a fixed class for the Admin's report: never the words, which may grow. */+export type VaultProviderFailure = "refused" | "rate-limited" | "cant-connect" | "unavailable" | "unreadable";++export function onePasswordFailure(problem: string): VaultProviderFailure {+ if (problem === ONE_PASSWORD_REFUSED || problem === ONE_PASSWORD_MALFORMED) return "refused";+ if (problem === ONE_PASSWORD_LIMITED) return "rate-limited";+ if (problem === ONE_PASSWORD_UNREACHABLE) return "cant-connect";+ if (problem === new OnePasswordUnavailableError().message) return "unavailable";+ return "unreadable";}export class OnePasswordLogins implements VaultProvider {@@ -288,8 +331,9 @@ export class OnePasswordLogins implements VaultProvider {if (content === null) unreadable.add(onePasswordItemKey(vault.id, item.id));if (!content) continue;const fields = secretValues(item.category, content);- if (fields.has("")) secrets.push({ id: `${ID_PREFIX}${vault.id}:${item.id}`, vaultId: vault.id, itemId: item.id, category: item.category, name: item.title.trim() || item.category,- fields: [...fields.keys()].filter(Boolean) });+ const main = mainTitle(item.category, content);+ if (fields.has("")) secrets.push({ id: `${ID_PREFIX}${vault.id}:${item.id}`, vaultId: vault.id, vault: vault.title, itemId: item.id, category: item.category,+ name: item.title.trim() || item.category, fields: [...fields.keys()].filter(Boolean), ...(main ? { main } : {}) });if (!isLogin(item)) continue;const found = loginFields(content.fields);if (!found.password) continue;@@ -385,6 +429,20 @@ export class OnePasswordLogins implements VaultProvider {return value ? { value } : {};}+ /** The secret an `op://` reference names, by vault and item title or id: null for one that names no secret, or more+ * than one (two items of the same title), or a field the secret does not offer. */+ resolve(reference: string): { id: string; field?: string } | null {+ const ref = this.token() ? parseOnePasswordReference(reference) : null;+ if (!ref) return null;+ const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();+ const found = this.secrets.filter((entry) => (entry.vaultId === ref.vault || same(entry.vault, ref.vault)) && (entry.itemId === ref.item || same(entry.name, ref.item)));+ if (found.length !== 1) return null;+ const entry = found[0]!;+ if (!ref.field || (entry.main && same(entry.main, ref.field))) return { id: entry.id };+ const field = entry.fields.find((one) => same(one, ref.field!));+ return field ? { id: entry.id, field } : null;+ }+markUsed(id: string): void {const entry = this.entries.find((candidate) => candidate.id === id) ?? this.secrets.find((candidate) => candidate.id === id);if (entry) this.lastUsed.set(entry.itemId, this.now());diff --git a/server/system-prompt.test.ts b/server/system-prompt.test.tsindex 6e43be3973..78cc404295 100644--- a/server/system-prompt.test.ts+++ b/server/system-prompt.test.ts@@ -307,6 +307,8 @@ describe("computerPrompt", () => {const many = Array.from({ length: 45 }, (_, index) => ({ name: `key ${index}` }));expect(savedSecretsPrompt(many)).toContain('"key 39" and 5 more.');expect(savedSecretsPrompt([{ name: "x".repeat(200) }])).toContain(`"${"x".repeat(80)}"`);+ expect(savedSecretsPrompt([{ name: "Stripe key" }], true)).toMatch(/ A 1Password reference the person gives you \(op:\/\/vault\/item\/field\) works as the label too\.$/u);+ expect(savedSecretsPrompt([{ name: "Stripe key" }])).not.toContain("op://");});});diff --git a/server/system-prompt.ts b/server/system-prompt.tsindex 8003a1be09..aac87ff35f 100644--- a/server/system-prompt.ts+++ b/server/system-prompt.ts@@ -161,7 +161,8 @@ const SECRET_NAMES_SHOWN = 40;const SECRET_NAME_SHOWN_MAX = 80;/** Names only, never a value. */-export function savedSecretsPrompt(secrets: ReadonlyArray<{ name: string; refOnly?: true }>): string {+/** `references`: the bot may use secrets from 1Password, so a reference a person gives works as a label too. */+export function savedSecretsPrompt(secrets: ReadonlyArray<{ name: string; refOnly?: true }>, references = false): string {const names = new Map<string, string>();for (const secret of [...secrets].sort((a, b) => Number(Boolean(a.refOnly)) - Number(Boolean(b.refOnly)))) {const name = secret.name.replace(/[\p{Cc}\s]+/gu, " ").trim().slice(0, SECRET_NAME_SHOWN_MAX);@@ -171,7 +172,8 @@ export function savedSecretsPrompt(secrets: ReadonlyArray<{ name: string; refOnlif (!names.size) return "";const shown = [...names.values()].slice(0, SECRET_NAMES_SHOWN);const more = names.size > shown.length ? ` and ${names.size - shown.length} more` : "";- return ` Secrets in the Vault you may use: ${shown.join(", ")}${more}. To use one, call request_credential with its name as the label: OpenMausBot hands it over at once with no card, and you never see the value.`;+ const reference = references ? " A 1Password reference the person gives you (op://vault/item/field) works as the label too." : "";+ return ` Secrets in the Vault you may use: ${shown.join(", ")}${more}. To use one, call request_credential with its name as the label: OpenMausBot hands it over at once with no card, and you never see the value.${reference}`;}export function computerPrompt(kind: ComputerPromptKind | null): string {diff --git a/server/vault/providers.ts b/server/vault/providers.tsindex 2f9d235237..ea70474007 100644--- a/server/vault/providers.ts+++ b/server/vault/providers.ts@@ -24,6 +24,8 @@ export interface VaultProvider {/** A login's password and 2FA key, or a secret's main value (or its `field`), read from the manager now. */read(itemId: string, field?: string): Promise<LinkedValue>;markUsed(itemId: string): void;+ /** The secret a reference in the manager's own form names (1Password's `op://…`), as an item id and field. */+ resolve?(reference: string): { id: string; field?: string } | null;}function logins(provider: VaultProvider, bots: string | readonly string[]): LoginSummary[] {@@ -68,6 +70,12 @@ export function findLinkedSecret(providers: readonly VaultProvider[], name: striif (found) return { provider, secret, ...(found.field ? { field: found.field } : {}) };}}+ // Security: a reference reaches only a secret this bot may use, through the same list a name does.+ for (const provider of providers) {+ const named = provider.resolve?.(name);+ const secret = named && linkedSecrets(provider, botId).find((one) => one.id === named.id);+ if (secret) return { provider, secret, ...(named.field ? { field: named.field } : {}) };+ }return null;}diff --git a/src/components/VaultSettings.test.ts b/src/components/VaultSettings.test.tsindex 453c667cf5..65de31e2c9 100644--- a/src/components/VaultSettings.test.ts+++ b/src/components/VaultSettings.test.ts@@ -249,6 +249,23 @@ describe("Settings → Vault: logins", () => {expect(document.body.querySelector("[data-settings-dialog] [role=alert]")?.textContent).toBe("1Password did not accept the token.");});+ it("on a Team Cloud, has an admin connect 1Password for the whole team, with the setup to use in one line", async () => {+ const hint = "Use a dedicated vault and a read-only service account.";+ fixture.config = { team: { id: "acme", name: "Acme" } };+ fixture.api.mockResolvedValueOnce({ logins: [], secrets: [], onePassword: OFF });+ await render();+ expect(host.querySelector("[data-onepassword-team]")!.textContent).toBe(`For the whole team: its bots use it in shared and private chats. ${hint}`);+ await click("Connect 1Password");+ expect(document.body.querySelector("[data-settings-dialog]")!.textContent).toContain(hint);+ await act(async () => root.unmount());+ root = createRoot(host);+ fixture.config = null;+ fixture.api.mockResolvedValueOnce({ logins: [], secrets: [], onePassword: OFF });+ await render();+ expect(host.querySelector("[data-onepassword]"), "off a team: the same row").not.toBeNull();+ expect(host.textContent, "off a team").not.toContain(hint);+ });+it("is for admins only", async () => {fixture.admin = false;await render();diff --git a/src/components/VaultSettings.tsx b/src/components/VaultSettings.tsxindex 65762ba1dd..e17761ec48 100644--- a/src/components/VaultSettings.tsx+++ b/src/components/VaultSettings.tsx@@ -278,7 +278,7 @@ export function VaultSettings() {<div data-vault-keys className="contents"><SettingsLinkRow title={t("settings.vault.keys.title")} subtitle={t("settings.vault.keys.hintShort", { app: productName() })} onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: "connections" })} /></div>- <OnePasswordConnection status={onePassword} disabled={logins === null} bots={bots} botNames={botNames}+ <OnePasswordConnection status={onePassword} disabled={logins === null} bots={bots} botNames={botNames} team={Boolean(state.config?.team)}onChange={async (next) => { setOnePassword(next); await load(); }} /></SettingsRows></SettingsGroup>}@@ -380,9 +380,11 @@ function VaultAccess({ vault, bots, botNames, disabled, onChange }: {);}-function OnePasswordConnection({ status, disabled, bots, botNames, onChange }: {+/** `team`: on a Team Cloud an admin connects it for the whole team, and the row says how to keep that narrow. */+function OnePasswordConnection({ status, disabled, bots, botNames, team, onChange }: {status: OnePasswordStatus;disabled: boolean;+ team: boolean;bots: ReadonlyArray<{ id: string; name: string }>;botNames: (value: LoginBots) => string;onChange: (status: OnePasswordStatus) => Promise<void>;@@ -417,6 +419,7 @@ function OnePasswordConnection({ status, disabled, bots, botNames, onChange }: {<button type="button" className="ui-button" disabled={disabled || busy !== null} onClick={() => void run("disconnect", disconnectOnePassword)}>{t("settings.logins.onePassword.disconnect")}</button></> : <button type="button" className="ui-button" disabled={disabled} onClick={() => setOpen(true)}>{t("settings.logins.onePassword.connect")}</button>}</div>+ {team && <p className="text-[12px] leading-4 text-ink-tertiary" data-onepassword-team>{t("settings.logins.onePassword.team")}</p>}{status.connected && status.error && <p role="alert" className="text-[12px] leading-4 text-danger">{status.error}</p>}{status.connected && !!status.vaults?.length && (<ul className="divide-y-[0.5px] divide-(--settings-edge)" aria-label={t("settings.logins.onePassword.vaults")}>@@ -434,6 +437,7 @@ function OnePasswordConnection({ status, disabled, bots, botNames, onChange }: {</>}><form id="onepassword-connect" className="flex flex-col gap-3" onSubmit={(event) => { connect(event); }}><p className="text-[13px] leading-[18px] text-ink-secondary">{t("settings.logins.onePassword.guide")}</p>+ {team && <p className="text-[13px] leading-[18px] text-ink-secondary">{t("settings.logins.onePassword.team")}</p>}<SettingsField label={t("settings.logins.onePassword.token")} hint={t("settings.logins.onePassword.note")}><input name="onePasswordToken" type="password" autoComplete="off" spellCheck={false} maxLength={8192} value={token}onChange={(event) => setToken(event.target.value)} disabled={disabled || busy !== null} className={SETTINGS_INPUT} />diff --git a/src/lib/connect-link.test.ts b/src/lib/connect-link.test.tsindex 2696a169f1..d23daab6a6 100644--- a/src/lib/connect-link.test.ts+++ b/src/lib/connect-link.test.ts@@ -15,5 +15,6 @@ it("a Team admin link from the Admin opens a Team Cloud's apps, MCP servers, keyexpect(takeConnectRequest("https://omb-t-1.fly.dev/?connect=keys")).toEqual({ rest: "/", section: "connections" });expect(takeConnectRequest("https://omb-t-1.fly.dev/?connect=ai")).toEqual({ rest: "/", section: "engines" });expect(takeConnectRequest("https://omb-t-1.fly.dev/?connect=bots&x=1")).toEqual({ rest: "/?x=1", teamAdminSection: "botAccess" });+ expect(takeConnectRequest("https://omb-t-1.fly.dev/?connect=vault")).toEqual({ rest: "/", teamAdminSection: "logins" });expect(takeConnectRequest("https://omb-t-1.fly.dev/?connect=mcp%3ABad%20Name")).toEqual({ rest: "/", surface: "apps" });});diff --git a/src/lib/connect-link.ts b/src/lib/connect-link.tsindex a67286213e..b301e3e3eb 100644--- a/src/lib/connect-link.ts+++ b/src/lib/connect-link.ts@@ -1,15 +1,18 @@+export type TeamAdminSection = "botAccess" | "logins";+/** A bot on My Cloud links to `/?connect=<id>` for a connection that needs the person there: an MCP server's sign-in* opens the MCP servers, where its Sign in is; any other id opens the apps. The Admin's Team admin pages link a team's- * admins to `/?connect=mcp`, `keys` (the keys in Settings), `ai` (the engines in Settings) or `bots` (Bot access in- * Settings, which only a team's admin is shown). It only opens the page; it never signs in by itself. Null for any- * other address. */-export function takeConnectRequest(href: string): ({ rest: string } & ({ surface: "mcp" | "apps" } | { section: "connections" | "engines" } | { teamAdminSection: "botAccess" })) | null {+ * admins to `/?connect=mcp`, `keys` (the keys in Settings), `ai` (the engines in Settings), or `bots` (Bot access) and+ * `vault` (the Vault, the team's keys and passwords) in Settings, which only a team's admin is shown there. It only opens+ * the page; it never signs in by itself. Null for any other address. */+export function takeConnectRequest(href: string): ({ rest: string } & ({ surface: "mcp" | "apps" } | { section: "connections" | "engines" } | { teamAdminSection: TeamAdminSection })) | null {const url = new URL(href);const id = url.searchParams.get("connect");if (id === null) return null;url.searchParams.delete("connect");const rest = `${url.pathname}${url.search}${url.hash}`;if (id === "bots") return { rest, teamAdminSection: "botAccess" };+ if (id === "vault") return { rest, teamAdminSection: "logins" };if (id === "keys" || id === "ai") return { rest, section: id === "keys" ? "connections" : "engines" };return { rest, surface: /^mcp(?::[a-z][a-z0-9_-]{0,31})?$/u.test(id) ? "mcp" : "apps" };}diff --git a/src/lib/use-connect-link.ts b/src/lib/use-connect-link.tsindex 22da4470eb..1eab804c5c 100644--- a/src/lib/use-connect-link.ts+++ b/src/lib/use-connect-link.ts@@ -1,14 +1,14 @@import { useEffect, useState } from "react";import type { Action } from "@/state/store";-import { takeConnectRequest } from "./connect-link";+import { takeConnectRequest, type TeamAdminSection } from "./connect-link";import { useOwnerOrAdmin } from "./use-owner-or-admin";/** Opens the page a `/?connect=` link asks for, once, and leaves the address clean. A page only a team's admin is* shown opens when this person is known to be one, and never for anyone else. */export function useConnectLink(dispatch: (action: Action) => void, team: boolean): void {const admin = useOwnerOrAdmin();- const [adminSection, setAdminSection] = useState<"botAccess" | null>(null);+ const [adminSection, setAdminSection] = useState<TeamAdminSection | null>(null);useEffect(() => {const request = takeConnectRequest(window.location.href);if (!request) return;diff --git a/src/locales/en.json b/src/locales/en.jsonindex df830f83c3..3cd4ae1bec 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -3895,6 +3895,7 @@"settings.logins.signsInOn": "Also signs in on {hosts}","settings.logins.removeTotp": "Remove the saved 2FA key","settings.logins.limits": "Bots get the password typed into the page, never as text, and it is hidden from anything they read back. A screenshot of the page can still show what a site displays, so save logins only for sites you trust your bots with.",+ "settings.logins.onePassword.team": "For the whole team: its bots use it in shared and private chats. Use a dedicated vault and a read-only service account.","settings.logins.onePassword.title": "1Password","settings.logins.onePassword.guide": "Let bots use logins, keys and secrets from 1Password. In 1Password, create a service account that can read one vault only, such as “Shared with {app}”, then paste its token here.","settings.logins.onePassword.token": "Service account token",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex fce9262a73..d1ec2b17d6 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -3708,6 +3708,7 @@"settings.logins.signsInOn": "Também faz login em {hosts}","settings.logins.removeTotp": "Remover a chave de 2FA salva","settings.logins.limits": "Os bots recebem a senha digitada na página, nunca como texto, e ela fica oculta em tudo o que eles conseguem ler. Uma captura de tela da página ainda pode mostrar o que o site exibe. Por isso, só salve o login de um site se confiar nos bots para usá-lo.",+ "settings.logins.onePassword.team": "Para toda a equipe: os bots usam em chats compartilhados e privados. Use um cofre dedicado e uma conta de serviço só de leitura.","settings.logins.onePassword.title": "1Password","settings.logins.onePassword.guide": "Deixe os bots usarem logins, chaves e segredos do 1Password. No 1Password, crie uma conta de serviço que só possa ler um cofre, como “Compartilhado com o app {app}”, e cole o token aqui.","settings.logins.onePassword.token": "Token da conta de serviço",