Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bitwarden in the Vault: logins and secrets through the open-source CLI (#6353)
Milind Soni09805bb19905
diff --git a/docs/bitwarden.md b/docs/bitwarden.mdnew file mode 100644index 0000000000..578917c1e5--- /dev/null+++ b/docs/bitwarden.md@@ -0,0 +1,86 @@+# Bitwarden in the Vault++Settings → Vault can connect a Bitwarden account (Password Manager, not Secrets Manager) beside 1Password. Its logins fill+on their sites like any saved login, and its items serve bots as secrets, read from Bitwarden at the moment a bot uses+one. On a desktop, a personal Cloud and a Team Cloud alike (`server/host/bitwarden-vault.ts`).++## Connecting++An admin picks the server (bitwarden.com, bitwarden.eu, or a self-hosted Bitwarden or Vaultwarden at any `https://`+address) and pastes the account's personal API key (`client_id`, which starts with `user.`, and `client_secret`, from the+account's Account settings → Security → Keys → View API key) and its master password. The row says the setup to use: *Use a+dedicated Bitwarden account that can only see one collection.* The account's collections are the boundary: every bot may+use what the account sees, so the account should see only what bots should.++The three are checked before anything is kept: a wrong master password, a refused API key, a server that can't be reached+and a tool that didn't answer in time each say so in plain words. Once Bitwarden accepts them they are sealed in the+Vault's file (`logins.json.enc`, never backed up or moved) and never shown again.++## How it runs++- `bw login --apikey` with `BW_CLIENTID` and `BW_CLIENTSECRET`, then `bw unlock --passwordenv BW_PASSWORD --raw`. Every+ secret reaches the tool in its environment, never its arguments, and of the server's own environment the tool gets+ only `PATH` (and `SystemRoot` on Windows). The session key is kept in the server's memory only; when it ends ("Vault is locked", or the tool was+ signed out) the server unlocks again, once, and retries.+- `bw sync` runs before the list is read (every 10 minutes at most, or on Refresh) and before a value is read, at most+ once a minute. Every call has a timeout (60 s).+- `bw list items` gives the list; every value in it is dropped at once. `bw get item <id>` reads one item when a bot uses+ it, and the value is masked wherever text crosses to a bot or a transcript.+- The tool keeps its settings and the account's encrypted copy of the vault in `<data>/tools/bitwarden/account`, which+ no backup or move carries. Disconnect signs the tool out and deletes that folder.++## Logins and secrets++- **Logins**: Login items with a password and a website (their URIs), by site, filled with their password and their+ one-time code when the item has a TOTP key. Read-only here: they are changed in Bitwarden.+- **Secrets by name**: a Secure Note (its text), and a Login item with custom fields (its first hidden custom field by the+ item's name, every other one as "<name> <field>"). These names are what a bot's prompt lists.+- **References**: `bw://<item id or name>[/<field>]`, where the field is `password`, `username`, `totp` (the current+ one-time code), `notes` or a custom field's name; with no field, a Login's password or a Secure Note's text. A+ reference reaches any Login or Secure Note the account sees, and is resolved where 1Password's `op://` references are:+ `request_credential` with the reference as the label hands the value over as a ref or a file, never as text. A name two+ items share is refused (use the id); a field the item lacks is refused. A bot that may use Bitwarden is told a+ reference works as a label. Bitwarden's own field names win over a custom field of the same name.++## Team Clouds++Only an admin connects, refreshes or disconnects it (`/api/logins/bitwarden*` answers a member 403), for the whole team:+its logins and secrets serve the team's bots in shared, group and private chats, as an admin's saved secrets and team+1Password do. A member's Vault shows `bitwarden: { connected: false }` and none of its items. The Admin's signed report+lists it in `vault.providers` as `{ kind: "bitwarden", connected, label: <server host>, lastError? }`, never a value,+the API key or the master password.++## The tool, and why OpenMausBot stays Apache-2.0++The tool is Bitwarden's own command line client, built from github.com/bitwarden/clients, whose code is GPL-3.0 except+the `bitwarden_license/` folder. OpenMausBot uses its **open-source build** (`bw-oss-*`, made with `build:oss` from the+GPL code alone) and never bundles, ships or imports it:++- It is downloaded on first use from Bitwarden's GitHub release+ `https://github.com/bitwarden/clients/releases/download/cli-v2026.10.1/<asset>-2026.10.1.zip`, checked against the+ pinned size and SHA-256 below, and unpacked to `<data>/tools/bitwarden/2026.10.1/bw` (`bw.exe` on Windows). A download+ that fails the check installs nothing.+- It runs only as a separate process: arguments and environment in, text out (`server/host/bitwarden-cli.ts`). Two+ programs talking that way are separate works; OpenMausBot links nothing of Bitwarden's and copies none of its source.+- No `@bitwarden/` package is a dependency: `scripts/testing/no-bitwarden-dependency.test.ts` fails if one enters a+ manifest, a lockfile or an import. (Bitwarden's Secrets Manager SDK, `@bitwarden/sdk-napi`, is under Bitwarden's own+ SDK license, which forbids offering an app built with it to others; `@bitwarden/sdk-internal` is GPL-3.0. Neither is+ used.)++| Platform | Asset | Bytes | SHA-256 |+|---|---|---|---|+| macOS arm64 | `bw-oss-macos-arm64` | 41861655 | `8b64bc7887f03c8d3ee10be2d720f3904ab632553434a47703f428d8ece9c9f2` |+| macOS x64 | `bw-oss-macos` | 44129496 | `faa5c6ec794bb2b3c969e2f08cba04a0f0ff8f1b2c10c5cf7b88911eaa0c1f4b` |+| Linux x64 | `bw-oss-linux` | 45802496 | `53384064abe7555039281bc2e6fe51846368ba60db9b7ba89de183409d7f6738` |+| Linux arm64 | `bw-oss-linux-arm64` | 44326018 | `9413e412ba2f8d3b179c54314c3d2d51c0b2ec25ed17b96a98b7c2d404b6d2a7` |+| Windows x64 | `bw-oss-windows` | 39074173 | `8ec2a4235c6c8db93cf42b444161882842e28f14dd6116369dea61efde8a418f` |++Windows on Arm has no build, and says so when connecting. The digests are GitHub's own for the release assets; the+macOS arm64 one was also checked against a download.++## Tests++`server/host/bitwarden-vault.test.ts` and `server/host/bitwarden-cli.test.ts` (an in-process fake `bw`,+`server/testing/fake-bw.ts`, and a fake download), and `server/cloud-team-bitwarden.e2e.test.ts` (a real Team Cloud with+the fake installed where the real one would be, `server/testing/fake-bw-process.ts`). None touches the network or a real+Bitwarden account.diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 010e16c936..4338ed2f7e 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -97,6 +97,10 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes tA 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 Vaultshows only their own secrets and `onePassword: { connected: false }`, and every `/api/logins` route answers them 403.+- **Bitwarden for the team** ([bitwarden.md](bitwarden.md)). The same rules: an Admin connects a dedicated Bitwarden+ account (*Use a dedicated Bitwarden account that can only see one collection.*) for the whole team, its logins and+ secrets serve the team's bots in every chat, by name or by `bw://<item>/<field>` reference, and a member sees and+ changes none of it (`bitwarden: { connected: false }`).- **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@@ -276,9 +280,10 @@ this server shares with every bot. It exists only on a Team Cloud.connections: 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+ providers: [{ kind: "1password" | "bitwarden", connected, label, lastError? }] }`. `secrets` are the team's saved secrets (anAdmin'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`+ member's own MausBot left out). `label` is the 1Password vaults the token reads, or Bitwarden's server host ("" while+ not connected); `lastError`a fixed class (`refused`, `rate-limited`, `cant-connect`, `unavailable`, `unreadable`). 1Password's own items andsaved 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).diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 14dee46739..2dce8522e2 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -87,6 +87,7 @@ export const VITEST_SUBSETS = {"server/cloud-sync.e2e.test.ts","server/cloud-team-asker-owns.e2e.test.ts","server/cloud-team-away.e2e.test.ts",+ "server/cloud-team-bitwarden.e2e.test.ts","server/cloud-team-box-audience.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-connections.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 618082a782..c384e6cbdb 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -227,6 +227,7 @@ describe("CI outputs", () => {"server/cloud-sync.e2e.test.ts","server/cloud-team-asker-owns.e2e.test.ts","server/cloud-team-away.e2e.test.ts",+ "server/cloud-team-bitwarden.e2e.test.ts","server/cloud-team-box-audience.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-connections.e2e.test.ts",diff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.tsindex e5869d77ea..b3b4d4c9ab 100644--- a/scripts/testing/cloud-send-fixture.ts+++ b/scripts/testing/cloud-send-fixture.ts@@ -18,7 +18,9 @@ import { installOneHome } from "../../electron/one-home-main.mjs";import type { OneHomeView } from "../../electron/one-home.mjs";import { cloudPairingSignature, cloudRequestSignature } from "../../server/cloud-home.ts";import type { TeamMember } from "../../server/cloud-team.ts";+import { bitwardenCliPath } from "../../server/host/bitwarden-cli.ts";import { removeTempDir, waitForExit } from "../../server/testing/cleanup.ts";+import type { FakeBwAccount } from "../../server/testing/fake-bw.ts";import { freePortBlock } from "../../server/testing/ports.ts";const SERVER_DIR = fileURLToPath(new URL("../../server/", import.meta.url));@@ -149,6 +151,18 @@ export interface CloudTeamFixture {const TEAM_MACHINE_ID = "0d9e8f7a-6b5c-4d3e-9f8a-7b6c5d4e3f2a";+/** The fake `bw` where the server installs the real one (server/host/bitwarden-cli.ts), so it is used as installed. */+function installFakeBw(dataDir: string, account: FakeBwAccount): void {+ const tool = bitwardenCliPath(dataDir, { asset: "fake", bytes: 0, sha256: "", executable: process.platform === "win32" ? "bw.exe" : "bw" });+ mkdirSync(join(tool, ".."), { recursive: true });+ const vault = join(tool, "..", "fake-bw-vault.json");+ writeFileSync(vault, JSON.stringify(account));+ writeFileSync(tool, `#!/usr/bin/env node+process.env.FAKE_BW_VAULT = ${JSON.stringify(vault)};+import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-bw-process.ts")).href)});+`, { mode: 0o755 });+}+/** 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 }> }@@ -178,8 +192,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, onePasswordItems = [], toolCalls = 0, broker, env = {}, cloudEnv = {}, cloudEngine = "", desktopEngine = "", space, cloudSignedIn = true, team }: {+export async function launchCloudSendFixture({ onePasswordToken, cloudOnePasswordToken = onePasswordToken, onePasswordItems = [], bitwarden, toolCalls = 0, broker, env = {}, cloudEnv = {}, cloudEngine = "", desktopEngine = "", space, cloudSignedIn = true, team }: {onePasswordToken: string; cloudOnePasswordToken?: string; toolCalls?: number;+ /** A fake Bitwarden tool already in each server's data folder, holding this one account (no download, no network). */+ bitwarden?: FakeBwAccount;/** 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. */@@ -212,6 +228,7 @@ export async function launchCloudSendFixture({ onePasswordToken, cloudOnePassworconst home = join(root, name);const dataDir = join(home, ".openmausbot");mkdirSync(dataDir, { recursive: true });+ if (bitwarden) installFakeBw(dataDir, bitwarden);const cli = join(home, "fixture-claude.mjs");const tools = calls ? JSON.stringify(Array.from({ length: calls }, (_, i) => ({ name: "Bash", input: { command: `echo step ${i}` } }))) : "";writeFileSync(cli, `#!/usr/bin/env nodediff --git a/scripts/testing/no-bitwarden-dependency.test.ts b/scripts/testing/no-bitwarden-dependency.test.tsnew file mode 100644index 0000000000..3657a1e784--- /dev/null+++ b/scripts/testing/no-bitwarden-dependency.test.ts@@ -0,0 +1,24 @@+// OpenMausBot stays Apache-2.0: Bitwarden's tool (GPL-3.0) and SDKs (GPL-3.0, or Bitwarden's own SDK license) are never a+// dependency, never bundled and never imported. The Vault downloads Bitwarden's `bw` at run time and runs it as a separate+// process (server/host/bitwarden-cli.ts). This fails the moment any `@bitwarden/` package enters a manifest, a lockfile+// or the code.+import { execFileSync } from "node:child_process";+import { readFileSync } from "node:fs";+import { expect, it } from "vitest";++const ROOT = new URL("../../", import.meta.url);+const SELF = "scripts/testing/no-bitwarden-dependency.test.ts";+const tracked = (...patterns: string[]) => execFileSync("git", ["ls-files", "-z", "--", ...patterns], { cwd: ROOT, encoding: "utf8" }).split("\0").filter(Boolean);++it("no package.json or lockfile names a @bitwarden/ package", () => {+ const files = tracked("package.json", "*/package.json", "**/package.json", "pnpm-lock.yaml", "**/pnpm-lock.yaml", "package-lock.json", "**/package-lock.json", "yarn.lock", "**/yarn.lock");+ expect(files).toContain("package.json");+ expect(files).toContain("pnpm-lock.yaml");+ expect(files.filter((file) => readFileSync(new URL(file, ROOT), "utf8").includes("@bitwarden/"))).toEqual([]);+});++it("no code imports or requires a @bitwarden/ package", () => {+ const code = tracked("*.ts", "*.tsx", "*.mts", "*.cts", "*.js", "*.mjs", "*.cjs").filter((file) => file !== SELF && !file.startsWith("third_party/"));+ const reaches = /(?:from\s*|import\s*\(\s*|require\s*\(\s*|import\s+)["']@bitwarden\//u;+ expect(code.filter((file) => reaches.test(readFileSync(new URL(file, ROOT), "utf8")))).toEqual([]);+});diff --git a/server/bot-logins.test.ts b/server/bot-logins.test.tsindex a30b81d158..e0ab3956a2 100644--- a/server/bot-logins.test.ts+++ b/server/bot-logins.test.ts@@ -140,8 +140,10 @@ 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(logins.secretsPrompt("payroll", TEAM_READER), "a manager with no references").not.toContain("://");+ const onePassword = { ...provider, id: "1password", resolve: () => null };+ expect(new BotLogins(store, onePassword as unknown as OnePasswordLogins).secretsPrompt("payroll", TEAM_READER), "a bot that may use the manager's secrets").toContain("op://vault/item/field");+ const none = new BotLogins(store, { ...onePassword, 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 d5edad11ed..88cb8c54f3 100644--- a/server/bot-logins.ts+++ b/server/bot-logins.ts@@ -1,6 +1,6 @@import { createHash } from "node:crypto";-import { browserMatesOf, loginPageCheck, loginPlace, loginSite, type LoginBots, type LoginPlace } from "../shared/logins.ts";+import { browserMatesOf, loginPageCheck, loginPlace, loginSite, loginUsableBy, type LoginBots, type LoginPlace, type LoginSummary } from "../shared/logins.ts";import type { LinkedSecret } from "../shared/vault.ts";import type { FillCandidate } from "./login-fill.ts";import { receiveLoginHandoff, type ConnectionHandoffAnswer, type ConnectionHandoffWhat, type LoginHandoffResult } from "./login-handoff.ts";@@ -8,7 +8,8 @@ import 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";+import { findLinkedSecret, linkedCandidates, linkedSecretNames, linkedSecrets, linkedSites, readLinkedSecret, type LinkedSecretUse, type VaultProvider } from "./vault/providers.ts";+import type { BitwardenLogins } from "./host/bitwarden-vault.ts";const linkedItemId = (secretId: string, field: string | undefined) => `linked-${createHash("sha256").update(`${secretId}\0${field ?? ""}`).digest("hex").slice(0, 32)}`;@@ -54,16 +55,20 @@ export function cardLoginPlace(cardHost: string, observed: ObservedPage | null,export class BotLogins {readonly store: VaultStore;readonly onePassword: OnePasswordLogins;+ readonly bitwarden: BitwardenLogins | null;readonly providers: readonly VaultProvider[];private readonly bots: () => ReadonlyArray<{ id: string; browserProfile?: string | null }>;private readonly hold: (value: string) => void;+ /** Secrets a reference named, which the list may not show by name: `linkedById` finds them again by the id they got. */+ private readonly referenced = new Map<string, LinkedSecretUse>();/** `hold` masks a value read from a linked manager wherever text crosses to a bot or a transcript. */constructor(store: VaultStore, onePassword: OnePasswordLogins, bots: () => ReadonlyArray<{ id: string; browserProfile?: string | null }> = () => [],- hold: (value: string) => void = () => {}) {+ hold: (value: string) => void = () => {}, bitwarden: BitwardenLogins | null = null) {this.store = store;this.onePassword = onePassword;- this.providers = [onePassword];+ this.bitwarden = bitwarden;+ this.providers = bitwarden ? [onePassword, bitwarden] : [onePassword];this.bots = bots;this.hold = hold;}@@ -120,7 +125,8 @@ export class BotLogins {/** 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);+ const references = this.providers.filter((provider) => provider.resolve && provider.items().some((item) => loginUsableBy(item, botId))).map((provider) => provider.id);+ return savedSecretsPrompt(this.secretNamesFor(botId, reader), references);}/** A secret a linked manager holds for the bot by this name, read from it now; its id is safe as a file name. */@@ -130,11 +136,15 @@ export class BotLogins {if (!use) return null;const value = await readLinkedSecret(use);this.hold(value);- return { id: linkedItemId(use.secret.id, use.field), name: use.field ? `${use.secret.name} ${use.field}` : use.secret.name, value };+ const id = linkedItemId(use.secret.id, use.field);+ this.referenced.set(id, use);+ return { id, name: use.field ? `${use.secret.name} ${use.field}` : use.secret.name, value };}/** The linked secret `linkedSecret` gave this id: who may use it, and its value read from the manager when asked. */linkedById(id: string): { bots: LoginBots; read(): Promise<string> } | null {+ const referenced = this.referenced.get(id);+ if (referenced) return { bots: referenced.secret.bots, read: async () => { const value = await readLinkedSecret(referenced); this.hold(value); return value; } };for (const provider of this.providers) {for (const secret of linkedSecrets(provider)) {const name = linkedSecretNames(secret).find(({ field }) => linkedItemId(secret.id, field) === id);@@ -192,6 +202,26 @@ export class BotLogins {// Kept whole, even for an item not loaded here yet: it then opens no wider than the computer that chose it.setItemGrants: (grants, keep) => this.store.setOnePasswordItemGrants(keep ? { ...this.store.onePasswordItemGrants(), ...grants } : grants),},+ bitwarden: this.bitwarden ? bitwardenRoutes(this.store, this.bitwarden) : undefined,};}}++/** Connecting checks the credentials first and keeps them only once Bitwarden accepted them. */+function bitwardenRoutes(store: VaultStore, bitwarden: BitwardenLogins): NonNullable<LoginRouteDeps["bitwarden"]> {+ return {+ status: () => bitwarden.status(),+ list: () => { void bitwarden.fresh(); return bitwarden.items().flatMap(({ kind, ...item }) => (kind === "login" ? [item as LoginSummary] : [])); },+ connect: async (credentials) => {+ await bitwarden.refresh(credentials);+ store.setBitwardenCredentials(credentials);+ return bitwarden.status();+ },+ refresh: () => bitwarden.refresh(),+ disconnect: async () => {+ store.setBitwardenCredentials(null);+ await bitwarden.disconnect();+ return bitwarden.status();+ },+ };+}diff --git a/server/browser/chrome/install.ts b/server/browser/chrome/install.tsindex 666195b995..84fab3a2bd 100644--- a/server/browser/chrome/install.ts+++ b/server/browser/chrome/install.ts@@ -62,8 +62,9 @@ export async function downloadArchive(url: string,destination: string,bytes: number,- options: { fetchImpl?: typeof fetch; onProgress?: (progress: DownloadProgress) => void; timeoutMs?: number } = {},+ options: { fetchImpl?: typeof fetch; onProgress?: (progress: DownloadProgress) => void; timeoutMs?: number; label?: string } = {},): Promise<string> {+ const what = options.label ?? "Chrome";const controller = new AbortController();const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? DOWNLOAD_TIMEOUT_MS);timer.unref?.();@@ -72,15 +73,15 @@ export async function downloadArchive(try {const response = await (options.fetchImpl ?? fetch)(url, { redirect: "follow", signal: controller.signal });const body = response.body;- if (!response.ok || !body) throw new Error(`the Chrome download failed (HTTP ${response.status})`);+ if (!response.ok || !body) throw new Error(`the ${what} download failed (HTTP ${response.status})`);const declared = Number(response.headers.get("content-length") ?? NaN);- if (Number.isFinite(declared) && declared !== bytes) throw new Error("the Chrome download did not match its pinned size; nothing was installed");+ if (Number.isFinite(declared) && declared !== bytes) throw new Error(`the ${what} download did not match its pinned size; nothing was installed`);const file = createWriteStream(destination, { mode: 0o600 });file.once("error", () => controller.abort());await pipeline(async function* () {for await (const chunk of body) {received += chunk.byteLength;- if (received > bytes) throw new Error("the Chrome download was larger than its pinned size; nothing was installed");+ if (received > bytes) throw new Error(`the ${what} download was larger than its pinned size; nothing was installed`);hash.update(chunk);yield chunk;options.onProgress?.({ received, total: bytes });@@ -92,7 +93,7 @@ export async function downloadArchive(} finally {clearTimeout(timer);}- if (received !== bytes) throw new Error("the Chrome download ended early; nothing was installed");+ if (received !== bytes) throw new Error(`the ${what} download ended early; nothing was installed`);return hash.digest("hex");}diff --git a/server/cloud-team-admin.ts b/server/cloud-team-admin.tsindex 5bd1baa611..b29373a77f 100644--- a/server/cloud-team-admin.ts+++ b/server/cloud-team-admin.ts@@ -33,10 +33,10 @@ export type PersonConnectionState = "connected" | "needs-sign-in" | "not-connect/** 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. */+ * `label`: 1Password's vaults the token reads, or Bitwarden's server; "" 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 }[];+ providers: { kind: "1password" | "bitwarden"; connected: boolean; label: string; lastError?: VaultProviderFailure }[];}/** The wire shape of `GET /api/cloud/team/admin` (signed by the Admin). */diff --git a/server/cloud-team-bitwarden.e2e.test.ts b/server/cloud-team-bitwarden.e2e.test.tsnew file mode 100644index 0000000000..701194be01--- /dev/null+++ b/server/cloud-team-bitwarden.e2e.test.ts@@ -0,0 +1,114 @@+// Bitwarden on a real Team Cloud (OMB_CLOUD_ROLE=team), its tool a fake `bw` already where the server installs the real+// one: 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 bw:// reference with no card; a member neither sees nor manages it; the Admin's signed report+// names it with its server, never a value, the API key or the master password. 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 CLIENT_SECRET = `fake-bw-client-secret-${randomBytes(8).toString("hex")}`;+const MASTER = `fake-bw-master-${randomBytes(8).toString("hex")}`;+const STRIPE = `sk_test_fake-bw-${randomBytes(12).toString("hex")}`;+const GITHUB = `fake-github-${randomBytes(12).toString("hex")}`;+const NOTE = `fake-oauth-note-${randomBytes(12).toString("hex")}`;+const CREDENTIALS = { serverUrl: "https://vault.bitwarden.eu", clientId: "user.5b0e2c1a-fake", clientSecret: CLIENT_SECRET, password: MASTER };+const ACCOUNT = {+ clientId: CREDENTIALS.clientId, clientSecret: CLIENT_SECRET, password: MASTER, email: "[email protected]",+ items: [+ { id: "i-github", name: "GitHub", type: 1 as const, login: { uris: [{ uri: "https://github.com/login" }], username: "deploy-bot", password: GITHUB } },+ { id: "i-stripe", name: "Stripe", type: 1 as const, login: { username: "acct_fake", password: `fake-dashboard-${randomBytes(6).toString("hex")}` },+ fields: [{ name: "secret key", value: STRIPE, type: 1 as const }] },+ { id: "i-oauth", name: "Acme OAuth", type: 2 as const, notes: NOTE },+ ],+};++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;+};+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) };+}+const leaked = (value: string) => [...said, ...fx.answers, fx.logs()].some((text) => text.includes(value));++beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-${randomBytes(8).toString("hex")}`, bitwarden: ACCOUNT, team: { id: "team-acme-bitwarden", 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 Bitwarden for the whole team; a wrong master password keeps nothing", async () => {+ const wrong = await as(admin, "POST", "/api/logins/bitwarden", { ...CREDENTIALS, password: "fake-wrong-master" });+ expect([wrong.status, wrong.body.error]).toEqual([400, "Bitwarden did not accept the master password. Check it and connect again."]);+ expect((await as(admin, "GET", "/api/vault")).body.bitwarden).toEqual({ connected: false });+ const connected = await as(admin, "POST", "/api/logins/bitwarden", CREDENTIALS);+ expect(connected.status, JSON.stringify(connected.body)).toBe(200);+ expect(connected.body.bitwarden).toEqual({ connected: true, server: "vault.bitwarden.eu", account: "[email protected]", items: 3 });+ const vault = (await as(admin, "GET", "/api/vault")).body;+ expect(vault.secrets.map((one: { name: string }) => one.name).sort()).toEqual(["Acme OAuth", "Stripe"]);+ expect(vault.logins.map((one: { site: string; source: string }) => [one.site, one.source])).toEqual([["github.com", "bitwarden"]]);+}, hostTimeout(60_000));++it("a member's private chat and the shared chat get it by name and by bw:// reference with no card", async () => {+ for (const [where, threadId] of [["Ada's private chat", adaThread], ["the shared chat", ledger.threadId]] as const) {+ for (const label of ["Stripe", "Acme OAuth", "bw://Stripe/secret key", "bw://GitHub/password", "bw://i-github/username", "bw://Acme OAuth"]) {+ 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);+ }+ }+ expect((await ask(adaThread, "bw://Nothing/password")).status, "an item the account doesn't see").toBe(201);+ for (const value of [STRIPE, GITHUB, NOTE, CLIENT_SECRET, MASTER]) expect(leaked(value), "a value in an answer or log").toBe(false);+}, hostTimeout(60_000));++it("a member neither sees nor manages the team's Bitwarden", async () => {+ const mine = (await as(ada, "GET", "/api/vault")).body;+ expect([mine.bitwarden, mine.secrets, mine.logins]).toEqual([{ connected: false }, [], []]);+ for (const [method, path, body] of [["POST", "/api/logins/bitwarden", CREDENTIALS], ["POST", "/api/logins/bitwarden/refresh", {}], ["DELETE", "/api/logins/bitwarden", undefined],+ ["DELETE", "/api/logins/bitwarden:i-github:github.com", undefined]] as const) {+ expect((await as(ada, method, path, body)).status, `${method} ${path}`).toBe(403);+ }+ expect((await as(admin, "GET", "/api/vault")).body.bitwarden.connected, "still connected").toBe(true);+}, hostTimeout(30_000));++it("the Admin's signed report names Bitwarden and its server, never a value or a credential", async () => {+ 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: false, label: "" }, { kind: "bitwarden", connected: true, label: "vault.bitwarden.eu" }]);+ const text = JSON.stringify(report.body);+ for (const value of [STRIPE, GITHUB, NOTE, CLIENT_SECRET, MASTER, CREDENTIALS.clientId]) expect(text.includes(value), "a value or credential in the report").toBe(false);+}, hostTimeout(30_000));++it("an Admin disconnects it: the Vault lists none of it, and a reference asks with a card again", async () => {+ expect((await as(admin, "DELETE", "/api/logins/bitwarden")).body.bitwarden).toEqual({ connected: false });+ expect((await as(admin, "GET", "/api/vault")).body.secrets).toEqual([]);+ expect((await ask(adaThread, "bw://Stripe/secret key")).status).toBe(201);+}, hostTimeout(30_000));diff --git a/server/cloud-team-onepassword.e2e.test.ts b/server/cloud-team-onepassword.e2e.test.tsindex 07c2cf4933..3d25da81ad 100644--- a/server/cloud-team-onepassword.e2e.test.ts+++ b/server/cloud-team-onepassword.e2e.test.ts@@ -111,7 +111,7 @@ it("the Admin's signed report names the team's secrets and 1Password's state, neconst 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.providers).toEqual([{ kind: "1password", connected: true, label: VAULT }, { kind: "bitwarden", connected: false, label: "" }]);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) {diff --git a/server/host/bitwarden-cli.test.ts b/server/host/bitwarden-cli.test.tsnew file mode 100644index 0000000000..5b2df66c44--- /dev/null+++ b/server/host/bitwarden-cli.test.ts@@ -0,0 +1,72 @@+import { createHash } from "node:crypto";+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { buildZip } from "../testing/zip-fixture.ts";+import { BITWARDEN_CLI_VERSION, BitwardenCliUnavailable, bitwardenCliPath, bitwardenCliPin, bitwardenCliUrl, bitwardenRunner, installBitwardenCli } from "./bitwarden-cli.ts";++const dirs: string[] = [];+const temp = () => { const dir = mkdtempSync(join(tmpdir(), "omb-bitwarden-cli-")); dirs.push(dir); return dir; };+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++const TOOL = "#!/bin/sh\necho fake bw\n";+const ARCHIVE = buildZip([{ name: "bw", data: TOOL, mode: 0o100755 }]);+const PIN = { asset: "bw-oss-test", bytes: ARCHIVE.length, sha256: createHash("sha256").update(ARCHIVE).digest("hex"), executable: "bw" };+const serve = (body: Buffer, seen: string[] = []) => (async (url: string) => { seen.push(String(url)); return new Response(new Uint8Array(body), { headers: { "content-length": String(body.length) } }); }) as unknown as typeof fetch;++describe("Bitwarden's command line tool, fetched on first use", () => {+ it("is the open-source build of a pinned release, from Bitwarden's own GitHub releases, for each platform it publishes", () => {+ expect(BITWARDEN_CLI_VERSION).toBe("2026.10.1");+ expect(bitwardenCliUrl(bitwardenCliPin("linux", "x64")!)).toBe("https://github.com/bitwarden/clients/releases/download/cli-v2026.10.1/bw-oss-linux-2026.10.1.zip");+ for (const [platform, arch, asset] of [["darwin", "arm64", "bw-oss-macos-arm64"], ["darwin", "x64", "bw-oss-macos"], ["linux", "arm64", "bw-oss-linux-arm64"], ["win32", "x64", "bw-oss-windows"]] as const) {+ const pin = bitwardenCliPin(platform, arch)!;+ expect(pin.asset).toBe(asset);+ expect(pin.sha256).toMatch(/^[0-9a-f]{64}$/u);+ expect(pin.executable).toBe(platform === "win32" ? "bw.exe" : "bw");+ }+ expect(bitwardenCliPin("win32", "arm64")).toBeNull();+ });++ it("downloads once, checks its SHA-256, and puts only the tool in the data folder", async () => {+ const dataDir = temp(), seen: string[] = [];+ const path = await installBitwardenCli({ dataDir, pin: PIN, fetchImpl: serve(ARCHIVE, seen), url: "https://example.test/bw.zip" });+ expect(path).toBe(bitwardenCliPath(dataDir, PIN));+ expect(path).toBe(join(dataDir, "tools", "bitwarden", BITWARDEN_CLI_VERSION, "bw"));+ expect(readFileSync(path, "utf8")).toBe(TOOL);+ if (process.platform !== "win32") expect(statSync(path).mode & 0o777).toBe(0o700);+ expect(await installBitwardenCli({ dataDir, pin: PIN, fetchImpl: serve(ARCHIVE, seen) })).toBe(path);+ expect(seen).toEqual(["https://example.test/bw.zip"]);+ });++ it("installs nothing from a download that fails its checksum or holds no tool", async () => {+ const dataDir = temp();+ const tampered = Buffer.from(ARCHIVE);+ tampered[tampered.length - 30] ^= 1;+ await expect(installBitwardenCli({ dataDir, pin: PIN, fetchImpl: serve(tampered) })).rejects.toThrow(BitwardenCliUnavailable);+ await expect(installBitwardenCli({ dataDir, pin: PIN, fetchImpl: serve(tampered) })).rejects.toThrow("SHA-256");+ const empty = buildZip([{ name: "README.txt", data: "no tool here" }]);+ await expect(installBitwardenCli({ dataDir, pin: { ...PIN, bytes: empty.length, sha256: createHash("sha256").update(empty).digest("hex") }, fetchImpl: serve(empty) }))+ .rejects.toThrow("did not hold the tool");+ expect(existsSync(bitwardenCliPath(dataDir, PIN))).toBe(false);+ await expect(installBitwardenCli({ dataDir, pin: null })).rejects.toThrow("Bitwarden publishes none");+ });++ it.skipIf(process.platform === "win32")("runs it as a separate process with secrets in its environment only, and none of the server's own", async () => {+ const dir = temp();+ const tool = join(dir, "bw");+ writeFileSync(tool, `#!/bin/sh\necho "args=$*"\necho "secret=$BW_PASSWORD"\necho "dir=$BITWARDENCLI_APPDATA_DIR"\necho "server=$OMB_FAKE_SERVER_SECRET"\nexit 3\n`, { mode: 0o755 });+ process.env.OMB_FAKE_SERVER_SECRET = "never-passed";+ try {+ const run = bitwardenRunner({ executable: async () => tool, appDataDir: join(dir, "account") });+ const result = await run(["unlock", "--passwordenv", "BW_PASSWORD", "--raw"], { BW_PASSWORD: "fake-master" });+ expect(result).toEqual({ code: 3, timedOut: false, stderr: "",+ stdout: `args=unlock --passwordenv BW_PASSWORD --raw\nsecret=fake-master\ndir=${join(dir, "account")}\nserver=\n` });+ const missing = bitwardenRunner({ executable: async () => join(dir, "nothing"), appDataDir: join(dir, "account") });+ expect((await missing(["status"])).code).toBe(127);+ } finally {+ delete process.env.OMB_FAKE_SERVER_SECRET;+ }+ });+});diff --git a/server/host/bitwarden-cli.ts b/server/host/bitwarden-cli.tsnew file mode 100644index 0000000000..d773839b01--- /dev/null+++ b/server/host/bitwarden-cli.ts@@ -0,0 +1,122 @@+// Bitwarden's own command line tool, `bw` (GPL-3.0, github.com/bitwarden/clients), is never bundled, imported or shipped+// with OpenMausBot: it is downloaded on first use from Bitwarden's GitHub release, checked against the size and SHA-256+// pinned here, kept in the data folder, and only ever run as a separate process. The "oss" build is the one made from+// the GPL code alone. Security: every secret reaches it in its environment, never its arguments, which any local user+// can list.+import { execFile } from "node:child_process";+import { randomBytes } from "node:crypto";+import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";+import { join } from "node:path";++import { downloadArchive } from "../browser/chrome/install.ts";+import { extractZipMember, readZipDirectory } from "../zip-archive.ts";++export const BITWARDEN_CLI_VERSION = "2026.10.1";++export interface BitwardenCliPin { asset: string; bytes: number; sha256: string; executable: string }++/** The release's own digests (GitHub's `sha256:` for each asset of cli-v2026.10.1). */+const PINS: Record<string, BitwardenCliPin> = {+ "darwin-arm64": { asset: "bw-oss-macos-arm64", bytes: 41_861_655, sha256: "8b64bc7887f03c8d3ee10be2d720f3904ab632553434a47703f428d8ece9c9f2", executable: "bw" },+ "darwin-x64": { asset: "bw-oss-macos", bytes: 44_129_496, sha256: "faa5c6ec794bb2b3c969e2f08cba04a0f0ff8f1b2c10c5cf7b88911eaa0c1f4b", executable: "bw" },+ "linux-x64": { asset: "bw-oss-linux", bytes: 45_802_496, sha256: "53384064abe7555039281bc2e6fe51846368ba60db9b7ba89de183409d7f6738", executable: "bw" },+ "linux-arm64": { asset: "bw-oss-linux-arm64", bytes: 44_326_018, sha256: "9413e412ba2f8d3b179c54314c3d2d51c0b2ec25ed17b96a98b7c2d404b6d2a7", executable: "bw" },+ "win32-x64": { asset: "bw-oss-windows", bytes: 39_074_173, sha256: "8ec2a4235c6c8db93cf42b444161882842e28f14dd6116369dea61efde8a418f", executable: "bw.exe" },+};++const DOWNLOAD_TIMEOUT_MS = 10 * 60_000;+const DEFAULT_CALL_TIMEOUT_MS = 60_000;+const OUTPUT_MAX = 32 * 1024 * 1024;++export function bitwardenCliPin(platform: string = process.platform, arch: string = process.arch): BitwardenCliPin | null {+ return PINS[`${platform}-${arch}`] ?? null;+}++export function bitwardenCliUrl(pin: BitwardenCliPin): string {+ return `https://github.com/bitwarden/clients/releases/download/cli-v${BITWARDEN_CLI_VERSION}/${pin.asset}-${BITWARDEN_CLI_VERSION}.zip`;+}++export function bitwardenCliPath(dataDir: string, pin: BitwardenCliPin): string {+ return join(dataDir, "tools", "bitwarden", BITWARDEN_CLI_VERSION, pin.executable);+}++/** The tool could not be put in place on this computer: never the person's account or password. */+export class BitwardenCliUnavailable extends Error {+ constructor(reason: string) {+ super(`Bitwarden's command line tool could not be set up on this computer (${reason}). Try again in a few minutes.`);+ this.name = "BitwardenCliUnavailable";+ }+}++const installs = new Map<string, Promise<string>>();++/** The tool's path, downloading it the first time; one download per folder at a time. */+export function installBitwardenCli(options: { dataDir: string; pin?: BitwardenCliPin | null; fetchImpl?: typeof fetch; url?: string }): Promise<string> {+ const pin = options.pin === undefined ? bitwardenCliPin() : options.pin;+ if (!pin) return Promise.reject(new BitwardenCliUnavailable(`Bitwarden publishes none for ${process.platform} ${process.arch}`));+ const executable = bitwardenCliPath(options.dataDir, pin);+ if (existsSync(executable)) return Promise.resolve(executable);+ let running = installs.get(executable);+ if (!running) {+ running = install(executable, pin, options).finally(() => installs.delete(executable));+ installs.set(executable, running);+ }+ return running;+}++async function install(executable: string, pin: BitwardenCliPin, options: { fetchImpl?: typeof fetch; url?: string }): Promise<string> {+ const root = join(executable, "..");+ mkdirSync(root, { recursive: true, mode: 0o700 });+ for (const name of readdirSync(root)) {+ const part = join(root, name);+ if (name.endsWith(".part") && Date.now() - statSync(part).mtimeMs > DOWNLOAD_TIMEOUT_MS) rmSync(part, { force: true });+ }+ const tag = randomBytes(6).toString("hex");+ const archive = join(root, `${pin.asset}.${tag}.zip.part`);+ const staged = join(root, `${pin.executable}.${tag}.part`);+ try {+ const digest = await downloadArchive(options.url ?? bitwardenCliUrl(pin), archive, pin.bytes,+ { fetchImpl: options.fetchImpl, timeoutMs: DOWNLOAD_TIMEOUT_MS, label: "Bitwarden command line tool" });+ if (digest !== pin.sha256) throw new Error("the download failed its SHA-256 check; nothing was installed");+ const member = (await readZipDirectory(archive, 4)).find((entry) => entry.name === pin.executable);+ if (!member) throw new Error("the archive did not hold the tool; nothing was installed");+ await extractZipMember(archive, member, staged, 0o700);+ renameSync(staged, executable);+ return executable;+ } catch (error) {+ throw new BitwardenCliUnavailable(error instanceof Error ? error.message : String(error));+ } finally {+ rmSync(archive, { force: true });+ rmSync(staged, { force: true });+ }+}++export interface BwResult { code: number; stdout: string; stderr: string; timedOut: boolean }+/** One `bw` call: `env` carries every secret (BW_CLIENTID, BW_CLIENTSECRET, BW_PASSWORD, BW_SESSION). */+export type BwRun = (args: readonly string[], env?: Record<string, string>, timeoutMs?: number) => Promise<BwResult>;++/** Runs the tool with only what it needs: its own settings folder, no prompts, and nothing of the server's environment. */+export function bitwardenRunner(options: { executable: () => Promise<string>; appDataDir: string }): BwRun {+ return async (args, env = {}, timeoutMs = DEFAULT_CALL_TIMEOUT_MS) => {+ const file = await options.executable();+ mkdirSync(options.appDataDir, { recursive: true, mode: 0o700 });+ return new Promise((resolve) => {+ execFile(file, [...args], {+ env: {+ PATH: process.env.PATH ?? "", ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),+ HOME: options.appDataDir, BITWARDENCLI_APPDATA_DIR: options.appDataDir, BW_NOINTERACTION: "true", NODE_OPTIONS: "", ...env,+ },+ timeout: timeoutMs, maxBuffer: OUTPUT_MAX, windowsHide: true, encoding: "utf8",+ }, (error, stdout, stderr) => {+ const failed = error as (NodeJS.ErrnoException & { killed?: boolean; code?: number | string }) | null;+ if (failed?.code === "ENOENT") { resolve({ code: 127, stdout: "", stderr: "ENOENT", timedOut: false }); return; }+ resolve({ code: failed ? (typeof failed.code === "number" ? failed.code : 1) : 0, stdout: String(stdout), stderr: String(stderr), timedOut: Boolean(failed?.killed) });+ });+ });+ };+}++/** Leaves the folder clean when the person disconnects: the tool's own settings and cached vault go with the account. */+export function forgetBitwardenAppData(appDataDir: string): void {+ rmSync(appDataDir, { recursive: true, force: true });+}diff --git a/server/host/bitwarden-vault.test.ts b/server/host/bitwarden-vault.test.tsnew file mode 100644index 0000000000..ed5d7bb7c5--- /dev/null+++ b/server/host/bitwarden-vault.test.ts@@ -0,0 +1,155 @@+import { describe, expect, it } from "vitest";++import { fakeBw, type FakeBwItem } from "../testing/fake-bw.ts";+import { parseTotpKey, totpCode } from "../totp.ts";+import { findLinkedSecret, linkedCandidates, linkedSecrets, linkedSites, readLinkedSecret } from "../vault/providers.ts";+import { parseBitwardenCredentials } from "../routes/logins.ts";+import { BITWARDEN_BAD_KEY, BITWARDEN_WRONG_PASSWORD, BitwardenLogins, bitwardenServerUrl, parseBitwardenReference } from "./bitwarden-vault.ts";+import { teamVaultReport } from "./team-vault-report.ts";++// Obvious fakes only; no network.+const CREDENTIALS = { serverUrl: "https://vault.bitwarden.com", clientId: "user.0f3c1a2b-fake", clientSecret: "fake-client-secret-xyz", password: "fake-Master-Passw0rd" };+const GITHUB_PASSWORD = "fake-github-Passw0rd";+const TOTP = "otpauth://totp/GitHub:bot?secret=JBSWY3DPEHPK3PXP&issuer=GitHub";+const STRIPE_KEY = "sk_test_fake-bw-stripe-123";+const NOTE = "fake-note-text-456";+const OAUTH_SECRET = "fake-oauth-client-secret-789";+const ITEMS: FakeBwItem[] = [+ { id: "i-github", name: "GitHub", type: 1, login: { uris: [{ uri: "https://github.com/login" }], username: "deploy-bot", password: GITHUB_PASSWORD, totp: TOTP } },+ { id: "i-stripe", name: "Stripe", type: 1, login: { username: "acct_fake", password: "fake-stripe-dashboard-pass" },+ fields: [{ name: "secret key", value: STRIPE_KEY, type: 1 }, { name: "password", value: "fake-custom-named-password", type: 1 }] },+ { id: "i-note", name: "Acme OAuth", type: 2, notes: NOTE, fields: [{ name: "client_secret", value: OAUTH_SECRET, type: 1 }] },+ { id: "i-dup-1", name: "Deploy", type: 1, login: { password: "fake-deploy-1" } },+ { id: "i-dup-2", name: "Deploy", type: 1, login: { password: "fake-deploy-2" } },+];++function setup(options: { credentials?: typeof CREDENTIALS | null; now?: () => number } = {}) {+ const fake = fakeBw({ ...CREDENTIALS, email: "[email protected]", items: ITEMS });+ let saved = options.credentials === undefined ? CREDENTIALS : options.credentials;+ let forgotten = 0;+ const vault = new BitwardenLogins({ credentials: () => saved, run: fake.run, now: options.now, forgetAppData: () => { forgotten++; } });+ return { vault, fake, setSaved: (value: typeof CREDENTIALS | null) => { saved = value; }, forgotten: () => forgotten };+}++describe("Bitwarden through its command line tool", () => {+ it("signs in with the API key, unlocks with the master password, and lists names and sites, never a value", async () => {+ const { vault, fake } = setup();+ expect(await vault.refresh(CREDENTIALS)).toEqual({ connected: true, server: "vault.bitwarden.com", account: "[email protected]", items: 3 });+ expect(fake.calls).toEqual(["status", "config server https://vault.bitwarden.com", "login --apikey", "unlock --passwordenv BW_PASSWORD --raw", "status [session]",+ "sync [session]", "list items [session]"]);+ expect(fake.secretsInArgs, "a secret in an argument").toEqual([]);+ const text = JSON.stringify(vault.items());+ for (const value of [GITHUB_PASSWORD, STRIPE_KEY, NOTE, OAUTH_SECRET, "JBSWY3DPEHPK3PXP", CREDENTIALS.password]) expect(text).not.toContain(value);+ expect(linkedSites(vault, "pepper")).toEqual([{ site: "github.com", hosts: ["github.com"], exactHost: false, username: "deploy-bot" }]);+ // A secret by name: a Secure Note's text, and a Login's custom field; never a custom field named like a built-in one.+ expect(linkedSecrets(vault).map((secret) => [secret.name, secret.fields, secret.provider])).toEqual([["Acme OAuth", ["client_secret"], "bitwarden"], ["Stripe", [], "bitwarden"]]);+ });++ it("fills a login on its site with its password and 2FA key, read from Bitwarden at fill time", async () => {+ const { vault, fake } = setup();+ await vault.refresh();+ expect(linkedCandidates(vault, "evil-github.com.example", "pepper")).toEqual([]);+ const [candidate] = linkedCandidates(vault, "github.com", "pepper");+ expect(candidate).toMatchObject({ site: "github.com", username: "deploy-bot", source: "bitwarden" });+ fake.calls.length = 0;+ expect(await candidate!.secrets()).toEqual({ password: GITHUB_PASSWORD, totp: parseTotpKey(TOTP) });+ expect(fake.calls).toEqual(["get item i-github [session]"]);+ });++ it("reads a secret by name or by bw:// reference: password, username, totp, notes or a custom field", async () => {+ const now = Date.UTC(2026, 10, 17, 12);+ const { vault } = setup({ now: () => now });+ await vault.refresh();+ const read = async (label: string) => { const use = findLinkedSecret([vault], label, "pepper"); return use ? readLinkedSecret(use) : null; };+ expect(await read("Stripe")).toBe(STRIPE_KEY);+ expect(await read("Acme OAuth")).toBe(NOTE);+ expect(await read("Acme OAuth client_secret")).toBe(OAUTH_SECRET);+ expect(await read("bw://GitHub/password")).toBe(GITHUB_PASSWORD);+ expect(await read("bw://GitHub")).toBe(GITHUB_PASSWORD);+ expect(await read("bw://i-github/username")).toBe("deploy-bot");+ expect(await read("bw://github/totp")).toBe(totpCode(parseTotpKey(TOTP)!, now));+ expect(await read("bw://Acme OAuth")).toBe(NOTE);+ expect(await read("bw://Acme OAuth/client_secret")).toBe(OAUTH_SECRET);+ expect(await read("bw://Stripe/secret key")).toBe(STRIPE_KEY);+ expect(await read("bw://Stripe/password"), "the built-in field wins over a custom one of the same name").toBe("fake-stripe-dashboard-pass");+ for (const label of ["bw://Deploy/password", "bw://Nothing/password", "bw://GitHub/nothing", "bw://Acme OAuth/totp", "Deploy", "GitHub"]) {+ expect(findLinkedSecret([vault], label, "pepper"), label).toBeNull();+ }+ expect(await read("bw://i-dup-2/password"), "two of a name: by id").toBe("fake-deploy-2");+ });++ it("parses bw:// references and checks the server address", () => {+ expect(parseBitwardenReference("bw://GitHub/totp")).toEqual({ item: "GitHub", field: "totp" });+ expect(parseBitwardenReference(" bw://Acme OAuth ")).toEqual({ item: "Acme OAuth" });+ for (const other of ["GitHub", "bw://", "bw://a/b/c", "bw://a/b?x=1", "op://a/b"]) expect(parseBitwardenReference(other), other).toBeNull();+ expect(bitwardenServerUrl("https://vault.bitwarden.eu/")).toBe("https://vault.bitwarden.eu");+ expect(bitwardenServerUrl("https://vw.example.test/bitwarden/")).toBe("https://vw.example.test/bitwarden");+ for (const bad of ["http://vault.example.test", "https://user:[email protected]", "https://vault.example.test/?a=1", "vault.bitwarden.com", 7]) expect(bitwardenServerUrl(bad), String(bad)).toBeNull();+ expect(parseBitwardenCredentials({ ...CREDENTIALS, clientId: "user.abc" })).toMatchObject({ ok: true });+ expect(parseBitwardenCredentials({ ...CREDENTIALS, clientId: "organization.abc" })).toMatchObject({ ok: false });+ expect(parseBitwardenCredentials({ ...CREDENTIALS, serverUrl: "http://vault.example.test" })).toMatchObject({ ok: false });+ expect(parseBitwardenCredentials({ ...CREDENTIALS, password: "" })).toMatchObject({ ok: false });+ });++ it("unlocks again by itself when the session ended, and signs in again when the tool was signed out", async () => {+ const { vault, fake } = setup();+ await vault.refresh();+ fake.expire();+ fake.calls.length = 0;+ expect(await readLinkedSecret(findLinkedSecret([vault], "Stripe", "pepper")!)).toBe(STRIPE_KEY);+ expect(fake.calls).toEqual(["get item i-stripe [session]", "status", "unlock --passwordenv BW_PASSWORD --raw", "status [session]", "get item i-stripe [session]"]);+ fake.state.signedIn = null;+ fake.state.sessions.clear();+ expect(await readLinkedSecret(findLinkedSecret([vault], "Stripe", "pepper")!)).toBe(STRIPE_KEY);+ expect(fake.calls).toContain("login --apikey");+ expect(fake.secretsInArgs).toEqual([]);+ });++ it("asks Bitwarden's server for the vault at most once a minute", async () => {+ let now = 1_000_000;+ const { vault, fake } = setup({ now: () => now });+ await vault.refresh();+ fake.calls.length = 0;+ await readLinkedSecret(findLinkedSecret([vault], "Stripe", "pepper")!);+ await readLinkedSecret(findLinkedSecret([vault], "Acme OAuth", "pepper")!);+ expect(fake.calls.filter((call) => call.startsWith("sync"))).toEqual([]);+ now += 61_000;+ await readLinkedSecret(findLinkedSecret([vault], "Stripe", "pepper")!);+ expect(fake.calls.filter((call) => call.startsWith("sync"))).toEqual(["sync [session]"]);+ });++ it("says plainly why it can't connect: the master password, the API key, the server or the time, and keeps nothing", async () => {+ const wrongPassword = setup({ credentials: null });+ await expect(wrongPassword.vault.refresh({ ...CREDENTIALS, password: "fake-wrong" })).rejects.toThrow(BITWARDEN_WRONG_PASSWORD);+ const wrongKey = setup({ credentials: null });+ await expect(wrongKey.vault.refresh({ ...CREDENTIALS, clientSecret: "fake-wrong" })).rejects.toThrow(BITWARDEN_BAD_KEY);+ const away = setup({ credentials: null });+ away.fake.state.unreachable = true;+ await expect(away.vault.refresh({ ...CREDENTIALS, serverUrl: "https://vw.example.test" })).rejects.toThrow("Could not reach the Bitwarden server at vw.example.test.");+ const slow = setup({ credentials: null });+ slow.fake.state.slow = true;+ await expect(slow.vault.refresh(CREDENTIALS)).rejects.toThrow("Bitwarden did not answer in time.");+ // Connected, then the server goes away: the status says so, with its class for the Admin's report.+ const { vault, fake } = setup();+ await vault.refresh();+ fake.state.unreachable = true;+ expect((await vault.refresh()).error).toMatch(/^Could not reach the Bitwarden server at vault\.bitwarden\.com\./u);+ expect(vault.failure()).toBe("cant-connect");+ expect(teamVaultReport({ secrets: [], bots: [], onePassword: { connected: false }, bitwarden: { status: vault.status(), failure: vault.failure() } }).providers)+ .toEqual([{ kind: "1password", connected: false, label: "" }, { kind: "bitwarden", connected: true, label: "vault.bitwarden.com", lastError: "cant-connect" }]);+ });++ it("connecting another account signs the tool out first; disconnecting signs out and forgets its folder", async () => {+ const { vault, fake, setSaved, forgotten } = setup();+ await vault.refresh();+ fake.calls.length = 0;+ await vault.refresh(CREDENTIALS);+ expect(fake.calls.slice(0, 4)).toEqual(["status", "logout", "config server https://vault.bitwarden.com", "login --apikey"]);+ setSaved(null);+ await vault.disconnect();+ expect(fake.calls.at(-1)).toBe("logout");+ expect(forgotten()).toBe(1);+ expect(vault.status()).toEqual({ connected: false });+ expect(vault.items()).toEqual([]);+ });+});diff --git a/server/host/bitwarden-vault.ts b/server/host/bitwarden-vault.tsnew file mode 100644index 0000000000..c43fcc24b3--- /dev/null+++ b/server/host/bitwarden-vault.ts@@ -0,0 +1,403 @@+// Bitwarden in the Vault, through its own command line tool (bitwarden-cli.ts). Its logins and secrets join the Vault's+// list by name and site only; every value is read from Bitwarden at the moment a bot uses it and never kept. The+// session key lives in this process's memory alone. Bitwarden has no per-collection bots here: the account's own+// collections are the boundary, so its items are for every bot.+import { join } from "node:path";++import type { BitwardenCredentials, BitwardenStatus, LoginPlace } from "../../shared/logins.ts";+import { loginSite, normalizeLoginHost } from "../../shared/logins.ts";+import type { LinkedSecret } from "../../shared/vault.ts";+import type { VaultProviderFailure } from "../onepassword.ts";+import { parseTotpKey, totpCode } from "../totp.ts";+import type { LinkedItem, LinkedValue, VaultProvider } from "../vault/providers.ts";+import { bitwardenRunner, forgetBitwardenAppData, installBitwardenCli, type BwResult, type BwRun } from "./bitwarden-cli.ts";++const ID_PREFIX = "bitwarden:";+const STALE_MS = 10 * 60_000;+/** `bw sync` asks Bitwarden's server for the whole vault, so it runs at most this often. */+const SYNC_EVERY_MS = 60_000;+const MAX_ITEMS = 1_000;+const FIELDS_MAX = 20;+const LOGIN = 1;+const SECURE_NOTE = 2;+/** What a reference may name besides a custom field: Bitwarden's own fields of an item. */+const BUILT_IN = ["password", "username", "totp", "notes"] as const;+type BuiltIn = typeof BUILT_IN[number];+const DEFAULT_SERVER = "https://vault.bitwarden.com";++interface BwField { name?: string | null; value?: string | null; type?: number }+interface BwItem {+ id: string; name?: string | null; type: number; notes?: string | null; fields?: BwField[] | null;+ login?: { uris?: Array<{ uri?: string | null }> | null; username?: string | null; password?: string | null; totp?: string | null } | null;+}++/** One item, without a single value: what its name and a reference may read. */+interface ItemEntry {+ itemId: string;+ name: string;+ type: number;+ /** Custom fields by name, never one named like a built-in field (a reference reads the built-in). */+ custom: string[];+ /** The custom field the item's name alone reads. */+ main?: string;+ has: Record<BuiltIn, boolean>;+}++interface LoginEntry extends LoginPlace { id: string; itemId: string; username: string; hasTotp: boolean }++export const BITWARDEN_WRONG_PASSWORD = "Bitwarden did not accept the master password. Check it and connect again.";+export const BITWARDEN_BAD_KEY = "Bitwarden did not accept the API key. Copy client_id and client_secret again in Bitwarden's Account settings → Security → Keys → View API key, then connect again.";+const TIMEOUT = "Bitwarden did not answer in time. Try again in a moment.";+const LIMITED = "Bitwarden is limiting requests right now. Try again in a few minutes.";+const LOCKED = "Bitwarden stayed locked. Connect it again with the master password.";+const UNREADABLE = "Bitwarden could not be read. Try again, or connect it again.";+const unreachable = (host: string) => `Could not reach the Bitwarden server at ${host}. Check the address and the internet connection, then try again.`;++/** Words for the person and a fixed class for the Admin's report; never what the tool printed. */+export class BitwardenProblem extends Error {+ readonly failure: VaultProviderFailure;+ /** The session ended or the account was signed out: unlocking again may fix it. */+ readonly relock: boolean;+ /** The item is not in the vault the account sees. */+ readonly gone: boolean;+ constructor(message: string, failure: VaultProviderFailure, options: { relock?: boolean; gone?: boolean } = {}) {+ super(message);+ this.name = "BitwardenProblem";+ this.failure = failure;+ this.relock = options.relock ?? false;+ this.gone = options.gone ?? false;+ }+}++export function bitwardenProblem(result: Pick<BwResult, "code" | "stdout" | "stderr" | "timedOut">, host: string): BitwardenProblem {+ const text = `${result.stderr}\n${result.stdout}`;+ if (result.timedOut) return new BitwardenProblem(TIMEOUT, "cant-connect");+ if (result.code === 127) return new BitwardenProblem("Bitwarden's command line tool is missing on this computer. Connect again to set it up.", "unavailable");+ if (/invalid master password/iu.test(text)) return new BitwardenProblem(BITWARDEN_WRONG_PASSWORD, "refused");+ if (/client_id or client_secret|invalid_client|invalid client/iu.test(text)) return new BitwardenProblem(BITWARDEN_BAD_KEY, "refused");+ if (/vault is locked|not logged in|unauthenticated/iu.test(text)) return new BitwardenProblem(LOCKED, "unreadable", { relock: true });+ if (/^\s*not found\.?\s*$/imu.test(text)) return new BitwardenProblem("That item is no longer in Bitwarden.", "unreadable", { gone: true });+ if (/too many requests|rate limit|\b429\b/iu.test(text)) return new BitwardenProblem(LIMITED, "rate-limited");+ if (/ECONNREFUSED|ENOTFOUND|EAI_AGAIN|getaddrinfo|fetch failed|ETIMEDOUT|ECONNRESET|socket hang up|network|certificate|UNABLE_TO_VERIFY/iu.test(text)) {+ return new BitwardenProblem(unreachable(host), "cant-connect");+ }+ return new BitwardenProblem(UNREADABLE, "unreadable");+}++/** A Bitwarden reference, `bw://<item id or name>[/<field>]`: the field is password, username, totp, notes or a custom+ * field's name. Null for anything else. */+export function parseBitwardenReference(reference: string): { item: string; field?: string } | null {+ const match = /^bw:\/\/([^/?#]+)(?:\/([^/?#]+))?$/u.exec(reference.trim());+ if (!match) return null;+ return { item: match[1]!.trim(), ...(match[2] ? { field: match[2].trim() } : {}) };+}++/** An https address with no path, query or credentials; null for anything else. */+export function bitwardenServerUrl(raw: unknown): string | null {+ if (typeof raw !== "string" || raw.length > 2048) return null;+ try {+ const url = new URL(raw.trim());+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) return null;+ return `${url.origin}${url.pathname.replace(/\/+$/u, "")}`;+ } catch {+ return null;+ }+}++const sameText = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();+const hostOf = (serverUrl: string) => { try { return new URL(serverUrl).host; } catch { return serverUrl; } };+const credentialKey = (credentials: BitwardenCredentials) => `${credentials.serverUrl}\0${credentials.clientId}`;++function bySite(hosts: Iterable<string>): Map<string, string[]> {+ const sites = new Map<string, string[]>();+ for (const host of hosts) {+ const site = loginSite(host);+ sites.set(site, [...(sites.get(site) ?? []), host]);+ }+ return sites;+}++function entryOf(item: BwItem): ItemEntry {+ const usable = (item.fields ?? []).filter((field) => field.name?.trim() && field.value && (field.type ?? 0) <= 2);+ const custom: string[] = [];+ for (const field of usable) {+ const name = field.name!.trim();+ if (!BUILT_IN.some((one) => sameText(one, name)) && !custom.some((one) => sameText(one, name)) && custom.length < FIELDS_MAX) custom.push(name);+ }+ const hidden = usable.find((field) => field.type === 1 && custom.includes(field.name!.trim()));+ const notes = Boolean(item.notes?.trim());+ const main = item.type === SECURE_NOTE && notes ? undefined : (hidden?.name?.trim() ?? custom[0]);+ return {+ itemId: item.id, name: item.name?.trim() || "Untitled", type: item.type, custom, ...(main ? { main } : {}),+ has: { password: Boolean(item.login?.password), username: Boolean(item.login?.username), totp: Boolean(item.login?.totp), notes },+ };+}++/** Whether the item's name alone reads something: a Secure Note's text, or a custom field. */+const listedAsSecret = (entry: ItemEntry) => (entry.type === SECURE_NOTE && entry.has.notes) || entry.main !== undefined;++function valueOf(item: BwItem, entry: ItemEntry, field: string | undefined, now: number): string | undefined {+ if (!field) return item.type === SECURE_NOTE && item.notes?.trim() ? item.notes : customValue(item, entry.main);+ const builtIn = BUILT_IN.find((one) => sameText(one, field));+ if (builtIn === "password") return item.login?.password ?? undefined;+ if (builtIn === "username") return item.login?.username ?? undefined;+ if (builtIn === "notes") return item.notes ?? undefined;+ if (builtIn === "totp") {+ const key = parseTotpKey(item.login?.totp);+ return key ? totpCode(key, now) : undefined;+ }+ return customValue(item, field);+}++function customValue(item: BwItem, name: string | undefined): string | undefined {+ if (!name) return undefined;+ return (item.fields ?? []).find((field) => field.name && sameText(field.name, name) && field.value)?.value ?? undefined;+}++export class BitwardenLogins implements VaultProvider {+ readonly id = "bitwarden";+ readonly label = "Bitwarden";+ private readonly credentials: () => BitwardenCredentials | null;+ private readonly run: BwRun;+ private readonly now: () => number;+ private readonly forgetAppData: () => void;+ private session: { key: string; credentials: string } | null = null;+ /** The client_id the tool is signed in with; null once signed out, or when this process has not signed it in yet. */+ private signedInAs: string | null = null;+ private unlocking: Promise<string> | null = null;+ private account: string | undefined;+ private logins: LoginEntry[] = [];+ private entries = new Map<string, ItemEntry>();+ private refreshedAt: number | null = null;+ private syncedAt: number | null = null;+ private error: BitwardenProblem | undefined;+ private refreshing: Promise<BitwardenStatus> | null = null;+ private readonly lastUsed = new Map<string, number>();++ constructor(options: { credentials: () => BitwardenCredentials | null; run: BwRun; now?: () => number; forgetAppData?: () => void }) {+ this.credentials = options.credentials;+ this.run = options.run;+ this.now = options.now ?? Date.now;+ this.forgetAppData = options.forgetAppData ?? (() => {});+ }++ status(): BitwardenStatus {+ const credentials = this.credentials();+ if (!credentials) return { connected: false };+ return {+ connected: true, server: hostOf(credentials.serverUrl), ...(this.account ? { account: this.account } : {}),+ items: this.logins.length + [...this.entries.values()].filter(listedAsSecret).length, ...(this.error ? { error: this.error.message } : {}),+ };+ }++ /** Why it is not working, as the Admin's report says it. */+ failure(): VaultProviderFailure | undefined {+ return this.credentials() ? this.error?.failure : undefined;+ }++ refresh(candidate?: BitwardenCredentials): Promise<BitwardenStatus> {+ if (!candidate && this.refreshing) return this.refreshing;+ const run = this.load(candidate).finally(() => { if (this.refreshing === run) this.refreshing = null; });+ if (!candidate) this.refreshing = run;+ return run;+ }++ async fresh(): Promise<void> {+ if (!this.credentials()) return;+ if (this.refreshedAt === null || this.now() - this.refreshedAt > STALE_MS) await this.refresh();+ }++ /** Signs the tool out and forgets its settings folder: the account's cached vault goes with it. */+ async disconnect(): Promise<void> {+ if (this.signedInAs !== null || this.session) await this.run(["logout"]).catch(() => null);+ this.clear();+ this.signedInAs = null;+ this.forgetAppData();+ }++ clear(): void {+ this.session = null;+ this.account = undefined;+ this.logins = [];+ this.entries = new Map();+ this.refreshedAt = null;+ this.syncedAt = null;+ this.error = undefined;+ this.lastUsed.clear();+ }++ private async load(candidate?: BitwardenCredentials): Promise<BitwardenStatus> {+ const credentials = candidate ?? this.credentials();+ if (!credentials) { this.clear(); return this.status(); }+ try {+ if (candidate) { this.session = null; await this.unlock(candidate, true); }+ await this.sync(credentials, true);+ // Every value in this answer is dropped here and read again when a bot uses it.+ const listed = JSON.parse(await this.call(credentials, ["list", "items"])) as unknown;+ const items = (Array.isArray(listed) ? listed as BwItem[] : []).filter((item) => typeof item?.id === "string" && (item.type === LOGIN || item.type === SECURE_NOTE)).slice(0, MAX_ITEMS);+ const logins: LoginEntry[] = [];+ const entries = new Map<string, ItemEntry>();+ for (const item of items) {+ const entry = entryOf(item);+ entries.set(item.id, entry);+ if (item.type !== LOGIN || !item.login?.password) continue;+ const hosts = new Set((item.login.uris ?? []).flatMap((uri) => normalizeLoginHost(uri.uri) ?? []));+ for (const [site, siteHosts] of bySite(hosts)) {+ logins.push({ id: `${ID_PREFIX}${item.id}:${site}`, itemId: item.id, site, hosts: siteHosts, exactHost: false,+ username: item.login.username ?? "", hasTotp: Boolean(parseTotpKey(item.login.totp)) });+ }+ }+ this.logins = logins.sort((a, b) => a.site.localeCompare(b.site) || a.username.localeCompare(b.username));+ this.entries = entries;+ this.refreshedAt = this.now();+ this.error = undefined;+ return this.status();+ } catch (error) {+ const problem = error instanceof BitwardenProblem ? error : new BitwardenProblem(error instanceof Error ? error.message : UNREADABLE, "unavailable");+ if (candidate) throw problem;+ this.error = problem;+ return this.status();+ }+ }++ /** Signs in with the API key when the tool is signed out (or signed in elsewhere), then unlocks with the master password.+ * `again`: a new connection, so whatever account the tool holds is signed out first. */+ private unlock(credentials: BitwardenCredentials, again = false): Promise<string> {+ if (!again && this.unlocking) return this.unlocking;+ const running = this.unlockNow(credentials, again).finally(() => { if (this.unlocking === running) this.unlocking = null; });+ this.unlocking = running;+ return running;+ }++ private async unlockNow(credentials: BitwardenCredentials, again: boolean): Promise<string> {+ const host = hostOf(credentials.serverUrl);+ const check = (result: BwResult) => { if (result.code !== 0 || result.timedOut) throw bitwardenProblem(result, host); return result.stdout; };+ const before = this.statusOf(check(await this.run(["status"])));+ let signedOut = before.status === "unauthenticated";+ const server = bitwardenServerUrl(before.serverUrl ?? DEFAULT_SERVER);+ const elsewhere = server !== bitwardenServerUrl(credentials.serverUrl) || (this.signedInAs !== null && this.signedInAs !== credentials.clientId);+ if (!signedOut && (again || elsewhere)) {+ await this.run(["logout"]);+ this.signedInAs = null;+ signedOut = true;+ }+ if (signedOut) {+ check(await this.run(["config", "server", credentials.serverUrl]));+ check(await this.run(["login", "--apikey"], { BW_CLIENTID: credentials.clientId, BW_CLIENTSECRET: credentials.clientSecret }));+ this.signedInAs = credentials.clientId;+ }+ const key = check(await this.run(["unlock", "--passwordenv", "BW_PASSWORD", "--raw"], { BW_PASSWORD: credentials.password })).trim();+ if (!key) throw new BitwardenProblem(LOCKED, "unreadable");+ this.session = { key, credentials: credentialKey(credentials) };+ this.signedInAs = credentials.clientId;+ const after = await this.run(["status"], { BW_SESSION: key });+ if (after.code === 0) this.account = this.statusOf(after.stdout).userEmail ?? undefined;+ return key;+ }++ private statusOf(text: string): { status?: string; serverUrl?: string | null; userEmail?: string | null } {+ try { return JSON.parse(text) as { status?: string; serverUrl?: string | null; userEmail?: string | null }; }+ catch { return {}; }+ }++ /** One call with the session, unlocking again once if the session ended. */+ private async call(credentials: BitwardenCredentials, args: string[]): Promise<string> {+ for (let attempt = 0; ; attempt++) {+ const key = this.session?.credentials === credentialKey(credentials) ? this.session.key : await this.unlock(credentials);+ const result = await this.run(args, { BW_SESSION: key });+ if (result.code === 0 && !result.timedOut) return result.stdout;+ const problem = bitwardenProblem(result, hostOf(credentials.serverUrl));+ if (!problem.relock || attempt > 0) throw problem;+ this.session = null;+ }+ }++ private async sync(credentials: BitwardenCredentials, force = false): Promise<void> {+ if (!force && this.syncedAt !== null && this.now() - this.syncedAt < SYNC_EVERY_MS) return;+ await this.call(credentials, ["sync"]);+ this.syncedAt = this.now();+ }++ private async item(itemId: string): Promise<BwItem | null> {+ const credentials = this.credentials();+ if (!credentials) return null;+ await this.sync(credentials);+ try { return JSON.parse(await this.call(credentials, ["get", "item", itemId])) as BwItem; }+ catch (error) {+ if (error instanceof BitwardenProblem && !error.gone) throw error;+ return null;+ }+ }++ private secretOf(entry: ItemEntry): LinkedSecret {+ const used = this.lastUsed.get(entry.itemId);+ return { id: `${ID_PREFIX}${entry.itemId}`, name: entry.name, fields: entry.custom.filter((name) => name !== entry.main), source: "linked", provider: this.id,+ bots: "all", readOnly: true, ...(used === undefined ? {} : { lastUsedAt: used }) };+ }++ items(): LinkedItem[] {+ if (!this.credentials()) return [];+ return [+ ...this.logins.map((entry): LinkedItem => {+ const used = this.lastUsed.get(entry.itemId);+ return { kind: "login", id: entry.id, site: entry.site, hosts: [...entry.hosts], exactHost: false, username: entry.username, hasTotp: entry.hasTotp,+ source: "bitwarden", bots: "all", createdAt: 0, ...(used === undefined ? {} : { lastUsedAt: used }) };+ }),+ ...[...this.entries.values()].filter(listedAsSecret).sort((a, b) => a.name.localeCompare(b.name)).map((entry): LinkedItem => ({ kind: "secret", ...this.secretOf(entry) })),+ ];+ }++ /** The item a `bw://` reference names, by id or by name: null for one that names no item, more than one (two items of+ * the same name), or a field the item does not have. */+ resolve(reference: string): { secret: LinkedSecret; field: string } | null {+ const ref = this.credentials() ? parseBitwardenReference(reference) : null;+ if (!ref) return null;+ const all = [...this.entries.values()];+ const byId = all.filter((entry) => entry.itemId === ref.item);+ const found = byId.length ? byId : all.filter((entry) => sameText(entry.name, ref.item));+ if (found.length !== 1) return null;+ const entry = found[0]!;+ const asked = ref.field ?? (entry.type === LOGIN ? "password" : "notes");+ const builtIn = BUILT_IN.find((one) => sameText(one, asked));+ if (builtIn) return entry.has[builtIn] ? { secret: this.secretOf(entry), field: builtIn } : null;+ const custom = entry.custom.find((name) => sameText(name, asked));+ return custom ? { secret: this.secretOf(entry), field: custom } : null;+ }++ async read(itemId: string, field?: string): Promise<LinkedValue> {+ const login = this.logins.find((entry) => entry.id === itemId);+ if (login) {+ const item = await this.item(login.itemId);+ if (!item?.login?.password) return {};+ return { password: item.login.password, totp: parseTotpKey(item.login.totp) };+ }+ const id = itemId.startsWith(ID_PREFIX) ? itemId.slice(ID_PREFIX.length) : "";+ const entry = this.entries.get(id);+ if (!entry) return {};+ const item = await this.item(id);+ const value = item ? valueOf(item, entry, field, this.now()) : undefined;+ return value ? { value } : {};+ }++ markUsed(id: string): void {+ const itemId = this.logins.find((entry) => entry.id === id)?.itemId ?? (id.startsWith(ID_PREFIX) ? id.slice(ID_PREFIX.length) : "");+ if (this.entries.has(itemId)) this.lastUsed.set(itemId, this.now());+ }+}++export function isBitwardenLoginId(id: string): boolean {+ return id.startsWith(ID_PREFIX);+}++/** Bitwarden for this server: the tool is fetched into `<data>/tools/bitwarden` the first time it is needed, and keeps+ * its own settings and the account's encrypted copy of the vault beside it, which no backup or move carries. */+export function createBitwardenVault(options: { dataDir: string; credentials: () => BitwardenCredentials | null }): BitwardenLogins {+ const appDataDir = join(options.dataDir, "tools", "bitwarden", "account");+ const vault = new BitwardenLogins({+ credentials: options.credentials,+ run: bitwardenRunner({ executable: () => installBitwardenCli({ dataDir: options.dataDir }), appDataDir }),+ forgetAppData: () => forgetBitwardenAppData(appDataDir),+ });+ if (options.credentials()) void vault.refresh();+ return vault;+}diff --git a/server/host/team-vault-report.ts b/server/host/team-vault-report.tsindex 8b1318a4a1..0ff3b0429e 100644--- a/server/host/team-vault-report.ts+++ b/server/host/team-vault-report.ts@@ -1,9 +1,9 @@// 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 { BitwardenStatus, LoginBots, OnePasswordStatus } from "../../shared/logins.ts";import type { TeamVaultSummary } from "../cloud-team-admin.ts";-import { onePasswordFailure } from "../onepassword.ts";+import { onePasswordFailure, type VaultProviderFailure } from "../onepassword.ts";import { isTeamBot } from "./connection-health-host.ts";const SECRETS_MAX = 500;@@ -15,6 +15,8 @@ export function teamVaultReport(input: {secrets: ReadonlyArray<{ name: string; createdAt: number; bots: LoginBots }>;bots: readonly ReportBot[];onePassword: OnePasswordStatus;+ /** Absent where Bitwarden is not offered. */+ bitwarden?: { status: BitwardenStatus; failure?: VaultProviderFailure };}): 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);@@ -25,6 +27,9 @@ export function teamVaultReport(input: {kind: "1password", connected: onePassword.connected,label: onePassword.connected ? (onePassword.vaults ?? []).map((vault) => vault.title).join(", ") : "",...(onePassword.connected && onePassword.error ? { lastError: onePasswordFailure(onePassword.error) } : {}),- }],+ }, ...(input.bitwarden ? [{+ kind: "bitwarden" as const, connected: input.bitwarden.status.connected, label: input.bitwarden.status.connected ? input.bitwarden.status.server ?? "" : "",+ ...(input.bitwarden.status.connected && input.bitwarden.failure ? { lastError: input.bitwarden.failure } : {}),+ }] : [])],};}diff --git a/server/index.ts b/server/index.tsindex b684a1bf05..963d592123 100644--- a/server/index.ts+++ b/server/index.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 { teamVaultReport } from "./host/team-vault-report.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 { createBitwardenVault } from "./host/bitwarden-vault.ts";import { createSetupImportRoutes } from "./routes/setup-import.ts";import { createComputerRoutes } from "./routes/computers.ts";import { createStatusRoutes } from "./routes/status.ts";@@ -745,7 +745,7 @@ const onePassword = new OnePasswordLogins({},});if (logins.onePasswordToken()) void onePassword.refresh();-const botLogins = new BotLogins(logins, onePassword, () => store.bots, (value) => heldSecrets.remember(value, "password")); const mcpKeys = createMcpKeys({ store: logins, linked: { fresh: () => botLogins.fresh(), byId: (id) => botLogins.linkedById(id) } });+const bitwardenVault = createBitwardenVault({ dataDir: DATA_DIR, credentials: () => logins.bitwardenCredentials() }), botLogins = new BotLogins(logins, onePassword, () => store.bots, (value) => heldSecrets.remember(value, "password"), bitwardenVault); const mcpKeys = createMcpKeys({ store: logins, linked: { fresh: () => botLogins.fresh(), byId: (id) => botLogins.linkedById(id) } });const SESSION_COOKIE = sessionCookieName(PORT, ENVIRONMENT_ID);const HOSTED_WORKSPACE = hostedWorkspaceConfigured();let workspaceAccess: WorkspaceAccess | null = null;@@ -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(), vault: teamVaultReport({ secrets: logins.listSecrets(TEAM_READER), bots: store.bots, onePassword: onePassword.status() }) }),+ }), ...await teamConnections.adminExtras(), vault: teamVaultReport({ secrets: logins.listSecrets(TEAM_READER), bots: store.bots, onePassword: onePassword.status(), bitwarden: { status: bitwardenVault.status(), failure: bitwardenVault.failure() } }) }),};}diff --git a/server/onepassword.ts b/server/onepassword.tsindex 99ed5d6089..fea6f769d4 100644--- a/server/onepassword.ts+++ b/server/onepassword.ts@@ -5,6 +5,7 @@import type { LoginBots, LoginPlace, LoginSummary, OnePasswordItemRef, OnePasswordStatus, OnePasswordVault } from "../shared/logins.ts";import { loginSite, normalizeLoginHost } from "../shared/logins.ts";import { parseTotpKey } from "./totp.ts";+import type { LinkedSecret } from "../shared/vault.ts";import type { LinkedItem, LinkedValue, VaultProvider } from "./vault/providers.ts";export interface OnePasswordItemFields {@@ -431,16 +432,19 @@ export class OnePasswordLogins implements VaultProvider {/** 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 {+ resolve(reference: string): { secret: LinkedSecret; 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 secret = this.items().find((item): item is { kind: "secret" } & LinkedSecret => item.kind === "secret" && item.id === entry.id);+ if (!secret) return null;+ const { kind: _kind, ...listed } = secret;+ if (!ref.field || (entry.main && same(entry.main, ref.field))) return { secret: listed };const field = entry.fields.find((one) => same(one, ref.field!));- return field ? { id: entry.id, field } : null;+ return field ? { secret: listed, field } : null;}markUsed(id: string): void {diff --git a/server/routes/logins.ts b/server/routes/logins.tsindex efd3f52168..cffb458eb0 100644--- a/server/routes/logins.ts+++ b/server/routes/logins.ts@@ -1,5 +1,6 @@// No answer ever carries a password, a 2FA key or the token: a saved secret is only ever replaced.-import { LOGIN_FIELD_MAX, loginPlace, normalizeLoginHost, type LoginBots, type LoginSummary, type OnePasswordStatus } from "../../shared/logins.ts";+import { LOGIN_FIELD_MAX, loginPlace, normalizeLoginHost, type BitwardenCredentials, type BitwardenStatus, type LoginBots, type LoginSummary, type OnePasswordStatus } from "../../shared/logins.ts";+import { bitwardenServerUrl } from "../host/bitwarden-vault.ts";import type { LoginPatch, NewLogin } from "../vault-store.ts";import { parseTotpKey, type TotpKey } from "../totp.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -25,6 +26,30 @@ export interface LoginRouteDeps {* unless `keep` leaves the items not named as they are. */setItemGrants(grants: Record<string, LoginBots>, keep?: boolean): void;};+ /** Absent where Bitwarden is not offered. */+ bitwarden?: {+ status(): BitwardenStatus;+ list(): LoginSummary[];+ /** Rejects with words for the person when Bitwarden refuses them; nothing is kept then. */+ connect(credentials: BitwardenCredentials): Promise<BitwardenStatus>;+ refresh(): Promise<BitwardenStatus>;+ disconnect(): Promise<BitwardenStatus>;+ };+}++const BITWARDEN = "/api/logins/bitwarden";++/** What an admin pastes to connect Bitwarden, checked; a message for the first thing that is not right. */+export function parseBitwardenCredentials(body: unknown): { ok: true; value: BitwardenCredentials } | { ok: false; error: string } {+ const field = (name: string) => (body && typeof body === "object" && typeof (body as Record<string, unknown>)[name] === "string" ? ((body as Record<string, string>)[name]).trim() : "");+ const serverUrl = bitwardenServerUrl(field("serverUrl"));+ if (!serverUrl) return { ok: false, error: LOGIN_ERRORS.bitwardenServer };+ const clientId = field("clientId"), clientSecret = field("clientSecret");+ if (!/^user\.[\w-]{1,100}$/u.test(clientId)) return { ok: false, error: LOGIN_ERRORS.bitwardenClientId };+ if (!clientSecret || clientSecret.length > 256 || /\s/u.test(clientSecret)) return { ok: false, error: LOGIN_ERRORS.bitwardenClientSecret };+ const password = body && typeof body === "object" && typeof (body as Record<string, unknown>).password === "string" ? (body as Record<string, string>).password : "";+ if (!password || password.length > 1024) return { ok: false, error: LOGIN_ERRORS.bitwardenPassword };+ return { ok: true, value: { serverUrl, clientId, clientSecret, password } };}const ONE_PASSWORD = "/api/logins/1password";@@ -47,6 +72,11 @@ export const LOGIN_ERRORS = {exactHost: "exactHost must be true or false.",readOnly: "This login is in 1Password. Change or remove it there.",taken: "A login with this username is already saved for that site. Change or delete that one instead.",+ bitwardenReadOnly: "This login is in Bitwarden. Change or remove it there.",+ bitwardenServer: "Enter the Bitwarden server's address, starting with https://, such as https://vault.bitwarden.com.",+ bitwardenClientId: "Paste the account's client_id from Bitwarden's Account settings → Security → Keys → View API key. It starts with user.",+ bitwardenClientSecret: "Paste the account's client_secret from the same place, on its own.",+ bitwardenPassword: "Enter the account's master password.",} as const;type Parsed<T> = { ok: true; value: T } | { ok: false; error: string };@@ -88,7 +118,8 @@ export function createLoginRoutes(deps: LoginRouteDeps): RouteHandler {if (path !== "/api/logins" && !path.startsWith("/api/logins/")) return PASS;res.setHeader("cache-control", "no-store");if (path === "/api/logins" && method === "GET") {- return json(res, 200, { logins: [...deps.list(), ...deps.onePassword.list()], onePassword: deps.onePassword.status() });+ return json(res, 200, { logins: [...deps.list(), ...deps.onePassword.list(), ...(deps.bitwarden?.list() ?? [])], onePassword: deps.onePassword.status(),+ ...(deps.bitwarden ? { bitwarden: deps.bitwarden.status() } : {}) });}// JSON only, so a form posted from another local page cannot add or change one.if (method !== "GET" && method !== "DELETE" && !isJson(req)) return json(res, 415, { error: "content-type must be application/json" });@@ -102,6 +133,16 @@ export function createLoginRoutes(deps: LoginRouteDeps): RouteHandler {catch (error) { return json(res, 400, { error: error instanceof Error && error.message ? error.message : LOGIN_ERRORS.token }); }}if (path === `${ONE_PASSWORD}/refresh` && method === "POST") return json(res, 200, { onePassword: await deps.onePassword.refresh() });+ if (path === BITWARDEN || path.startsWith(`${BITWARDEN}/`)) {+ if (!deps.bitwarden) return json(res, 404, { error: "not found" });+ if (path === `${BITWARDEN}/refresh` && method === "POST") return json(res, 200, { bitwarden: await deps.bitwarden.refresh() });+ if (path === BITWARDEN && method === "DELETE") return json(res, 200, { bitwarden: await deps.bitwarden.disconnect() });+ if (path !== BITWARDEN || method !== "POST") return json(res, 405, { error: "method not allowed" });+ const parsed = parseBitwardenCredentials(await readBody(req, 16_384));+ if (!parsed.ok) return json(res, 400, { error: parsed.error });+ try { return json(res, 200, { bitwarden: await deps.bitwarden.connect(parsed.value) }); }+ catch (error) { return json(res, 400, { error: error instanceof Error && error.message ? error.message : LOGIN_ERRORS.bitwardenPassword }); }+ }if (path === ONE_PASSWORD && method === "DELETE") return json(res, 200, { onePassword: deps.onePassword.disconnect() });const vault = VAULT.exec(path);if (vault && method === "PATCH") {@@ -156,6 +197,7 @@ export function createLoginRoutes(deps: LoginRouteDeps): RouteHandler {}const id = path.slice("/api/logins/".length);if (/^1password(?::|%3a)/iu.test(id)) return json(res, 409, { error: LOGIN_ERRORS.readOnly });+ if (/^bitwarden(?::|%3a)/iu.test(id)) return json(res, 409, { error: LOGIN_ERRORS.bitwardenReadOnly });if (!ID.test(id)) return json(res, 404, { error: "no such login" });if (method === "DELETE") {return deps.remove(id) ? json(res, 200, { ok: true }) : json(res, 404, { error: "no such login" });diff --git a/server/routes/vault.ts b/server/routes/vault.tsindex 2880984a02..74bec22ff8 100644--- a/server/routes/vault.ts+++ b/server/routes/vault.ts@@ -8,7 +8,7 @@ import { isJson, parseBots, type LoginRouteDeps } from "./logins.ts";import { PASS, type RouteHandler } from "./table.ts";export interface VaultRouteDeps {- logins: Pick<LoginRouteDeps, "list" | "botExists" | "onePassword">;+ logins: Pick<LoginRouteDeps, "list" | "botExists" | "onePassword" | "bitwarden">;secrets: Pick<VaultStore, "listSecrets" | "saveSecret" | "receiveSecret" | "updateSecret" | "removeSecret">;/** A linked password manager's secrets, listed beside the saved ones and changed only in the manager. */linked?: () => LinkedSecret[];@@ -49,8 +49,10 @@ export function createVaultRoutes(deps: VaultRouteDeps): RouteHandler {const readable = (id: string) => deps.secrets.listSecrets(reader).some((secret) => secret.id === id);if (path === "/api/vault") {if (method !== "GET") return json(res, 405, { error: "method not allowed" });- if (!reader.team) return json(res, 200, { logins: [], secrets: deps.secrets.listSecrets(reader), onePassword: { connected: false } });- return json(res, 200, { logins: [...deps.logins.list(), ...deps.logins.onePassword.list()], secrets: [...deps.secrets.listSecrets(reader), ...(deps.linked?.() ?? [])], onePassword: deps.logins.onePassword.status() });+ const bitwarden = deps.logins.bitwarden;+ if (!reader.team) return json(res, 200, { logins: [], secrets: deps.secrets.listSecrets(reader), onePassword: { connected: false }, ...(bitwarden ? { bitwarden: { connected: false } } : {}) });+ return json(res, 200, { logins: [...deps.logins.list(), ...deps.logins.onePassword.list(), ...(bitwarden?.list() ?? [])], secrets: [...deps.secrets.listSecrets(reader), ...(deps.linked?.() ?? [])],+ onePassword: deps.logins.onePassword.status(), ...(bitwarden ? { bitwarden: bitwarden.status() } : {}) });}if (path !== SECRETS && !path.startsWith(`${SECRETS}/`)) return json(res, 404, { error: "not found" });if (!reader.team && method !== "DELETE") return json(res, 403, { error: "Only an admin can add or change a secret in the Vault." });diff --git a/server/system-prompt.test.ts b/server/system-prompt.test.tsindex 78cc404295..820279fc78 100644--- a/server/system-prompt.test.ts+++ b/server/system-prompt.test.ts@@ -307,7 +307,9 @@ 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" }], ["1password"])).toMatch(/value\. A 1Password reference \(op:\/\/vault\/item\/field\) the person gives you works as the label too\.$/u);+ expect(savedSecretsPrompt([{ name: "Stripe key" }], ["1password", "bitwarden"]))+ .toMatch(/ A 1Password reference \(op:\/\/vault\/item\/field\) or a Bitwarden reference \(bw:\/\/item\/field\) the person gives you 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 aac87ff35f..51de35e62f 100644--- a/server/system-prompt.ts+++ b/server/system-prompt.ts@@ -161,8 +161,10 @@ const SECRET_NAMES_SHOWN = 40;const SECRET_NAME_SHOWN_MAX = 80;/** Names only, never a value. */-/** `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 REFERENCE_FORMS: Record<string, string> = { "1password": "a 1Password reference (op://vault/item/field)", bitwarden: "a Bitwarden reference (bw://item/field)" };++/** `references`: the password managers whose secrets the bot may use, so a reference a person gives works as a label too. */+export function savedSecretsPrompt(secrets: ReadonlyArray<{ name: string; refOnly?: true }>, references: readonly string[] = []): 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);@@ -172,7 +174,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` : "";- const reference = references ? " A 1Password reference the person gives you (op://vault/item/field) works as the label too." : "";+ const forms = references.flatMap((id) => REFERENCE_FORMS[id] ?? []);+ const reference = forms.length ? ` ${forms.join(" or ").replace(/^a/u, "A")} the person gives you 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}`;}diff --git a/server/testing/fake-bw-process.ts b/server/testing/fake-bw-process.tsnew file mode 100644index 0000000000..9ec5fc5f0d--- /dev/null+++ b/server/testing/fake-bw-process.ts@@ -0,0 +1,23 @@+// The fake `bw` as its own process, for a server that runs the tool it installed: the launcher a test writes at the+// tool's path sets FAKE_BW_VAULT to a JSON account (fake-bw.ts FakeBwAccount) and imports this. What the tool keeps+// between calls (its server, who is signed in, the open sessions) lives in its settings folder, as the real one's does.+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { fakeBw, type FakeBwAccount } from "./fake-bw.ts";++const account = JSON.parse(readFileSync(process.env.FAKE_BW_VAULT!, "utf8")) as FakeBwAccount;+const folder = process.env.BITWARDENCLI_APPDATA_DIR!;+const stateFile = join(folder, "fake-bw-state.json");+const fake = fakeBw(account);+const saved = existsSync(stateFile) ? JSON.parse(readFileSync(stateFile, "utf8")) as { server?: string | null; signedIn?: string | null; sessions?: string[] } : {};+fake.state.server = saved.server ?? null;+fake.state.signedIn = saved.signedIn ?? null;+for (const session of saved.sessions ?? []) fake.state.sessions.add(session);+const env = Object.fromEntries(Object.entries(process.env).filter((entry): entry is [string, string] => entry[0].startsWith("BW_") && typeof entry[1] === "string"));+const result = await fake.run(process.argv.slice(2), env);+mkdirSync(folder, { recursive: true });+writeFileSync(stateFile, JSON.stringify({ server: fake.state.server, signedIn: fake.state.signedIn, sessions: [...fake.state.sessions] }));+process.stdout.write(result.stdout);+process.stderr.write(result.stderr);+process.exitCode = result.code;diff --git a/server/testing/fake-bw.ts b/server/testing/fake-bw.tsnew file mode 100644index 0000000000..41d759c2f6--- /dev/null+++ b/server/testing/fake-bw.ts@@ -0,0 +1,68 @@+// A stand-in for Bitwarden's `bw` command line tool, answering as `bw` 2026.10 does for the calls the Vault makes+// (status, config server, login --apikey, unlock --passwordenv, sync, list items, get item, logout), with its own+// messages for the failures. No network: it holds one account and its items in memory. Every call is recorded, and+// whether any secret ever reached an argument is too.+import { randomUUID } from "node:crypto";++import type { BwResult, BwRun } from "../host/bitwarden-cli.ts";++export interface FakeBwItem {+ id: string; name: string; type: 1 | 2; notes?: string | null; collectionIds?: string[];+ fields?: Array<{ name: string; value: string; type: 0 | 1 | 2 }>;+ login?: { uris?: Array<{ uri: string }>; username?: string | null; password?: string | null; totp?: string | null };+}++export interface FakeBwAccount { clientId: string; clientSecret: string; password: string; email: string; items: FakeBwItem[] }++export function fakeBw(account: FakeBwAccount) {+ const state = { server: null as string | null, signedIn: null as string | null, sessions: new Set<string>(), unreachable: false, slow: false, limited: false };+ const calls: string[] = [];+ const secretsInArgs: string[] = [];+ const ok = (stdout: string): BwResult => ({ code: 0, stdout, stderr: "", timedOut: false });+ const fail = (stderr: string): BwResult => ({ code: 1, stdout: "", stderr, timedOut: false });+ const run: BwRun = async (args, env = {}) => {+ calls.push(`${args.join(" ")}${env.BW_SESSION ? " [session]" : ""}`);+ for (const secret of [account.clientSecret, account.password]) if (args.some((arg) => arg.includes(secret))) secretsInArgs.push(args.join(" "));+ if (state.slow) return { code: 1, stdout: "", stderr: "", timedOut: true };+ const [command] = args;+ if (command === "status") {+ const status = !state.signedIn ? "unauthenticated" : env.BW_SESSION && state.sessions.has(env.BW_SESSION) ? "unlocked" : "locked";+ return ok(JSON.stringify({ serverUrl: state.server, lastSync: null, userEmail: state.signedIn ? account.email : null, userId: state.signedIn ? "u1" : null, status }));+ }+ if (command === "config") {+ if (state.signedIn) return fail("Logout required before server config update.");+ state.server = args[2] ?? null;+ return ok("Saved setting `config`.");+ }+ if (command === "logout") {+ if (!state.signedIn) return fail("You are not logged in.");+ state.signedIn = null;+ state.sessions.clear();+ return ok("You have logged out.");+ }+ if (command === "login") {+ if (state.unreachable) return fail("request to https://identity.bitwarden.com/connect/token failed, reason: getaddrinfo ENOTFOUND identity.bitwarden.com");+ if (state.limited) return fail("Too many requests. Try again later.");+ if (env.BW_CLIENTID !== account.clientId || env.BW_CLIENTSECRET !== account.clientSecret) return fail("client_id or client_secret is incorrect. Try again.");+ state.signedIn = env.BW_CLIENTID;+ return ok("You are logged in!\n\nTo unlock your vault, use the `unlock` command.");+ }+ if (command === "unlock") {+ if (!state.signedIn) return fail("You are not logged in.");+ if (env.BW_PASSWORD !== account.password) return fail("Invalid master password.");+ const key = `fake-session-${randomUUID()}`;+ state.sessions.add(key);+ return ok(key);+ }+ if (!state.signedIn) return fail("You are not logged in.");+ if (!env.BW_SESSION || !state.sessions.has(env.BW_SESSION)) return fail("Vault is locked.");+ if (command === "sync") return state.unreachable ? fail("fetch failed: connect ECONNREFUSED 203.0.113.7:443") : ok("Syncing complete.");+ if (command === "list" && args[1] === "items") return ok(JSON.stringify(account.items.map((item) => ({ object: "item", ...item }))));+ if (command === "get" && args[1] === "item") {+ const item = account.items.find((one) => one.id === args[2]);+ return item ? ok(JSON.stringify({ object: "item", ...item })) : fail("Not found.");+ }+ return fail(`Invalid command: ${command}`);+ };+ return { run, state, calls, secretsInArgs, expire: () => state.sessions.clear() };+}diff --git a/server/vault-store.ts b/server/vault-store.tsindex 1e46a8482f..f2622345d3 100644--- a/server/vault-store.ts+++ b/server/vault-store.ts@@ -8,7 +8,7 @@ import { join } from "node:path";import { z } from "zod";import { HELD_SECRET_MASK } from "../shared/redact.ts";-import { LOGIN_FIELD_MAX, LOGIN_HOSTS_MAX, loginMatchesHost, loginPlace, loginSite, loginUsableBy, type LoginBots, type LoginPlace, type LoginSummary } from "../shared/logins.ts";+import { LOGIN_FIELD_MAX, LOGIN_HOSTS_MAX, loginMatchesHost, loginPlace, loginSite, loginUsableBy, type BitwardenCredentials, type LoginBots, type LoginPlace, type LoginSummary } from "../shared/logins.ts";import { SECRET_VALUE_MAX_BYTES, VAULT_SECRET_NAME_MAX, vaultNameKey, type VaultSecret } from "../shared/vault.ts";import { writeFileAtomic } from "./atomic.ts";import { decryptBrowserState, encryptBrowserState } from "./browser-sites.ts";@@ -65,6 +65,8 @@ const fileSchema = z.object({logins: z.array(diskLoginSchema),secrets: z.array(diskSecretSchema).optional(),onePassword: z.object({ token: z.string().min(1), connectedAt: z.number() }).optional(),+ /** Bitwarden's server address, API key and master password, read only by its command line tool's environment. */+ bitwarden: z.object({ serverUrl: z.string().min(1), clientId: z.string().min(1), clientSecret: z.string().min(1), password: z.string().min(1), connectedAt: z.number() }).optional(),/** Vault id → the bots that may use its logins; a vault not named here is for every bot. Kept across reconnects. */onePasswordGrants: z.record(z.string(), botsSchema).optional(),/** 1Password item (`<vault id>:<item id>`) → the bots that may use it, ahead of its vault's choice. Kept across reconnects. */@@ -492,6 +494,16 @@ export class VaultStore {this.write(token ? { ...rest, onePassword: { token, connectedAt: this.now() } } : rest);}+ bitwardenCredentials(): BitwardenCredentials | null {+ const saved = this.read().bitwarden;+ return saved ? { serverUrl: saved.serverUrl, clientId: saved.clientId, clientSecret: saved.clientSecret, password: saved.password } : null;+ }++ setBitwardenCredentials(credentials: BitwardenCredentials | null): void {+ const { bitwarden: _previous, ...rest } = this.read();+ this.write(credentials ? { ...rest, bitwarden: { ...credentials, connectedAt: this.now() } } : rest);+ }+onePasswordGrants(): Record<string, LoginBots> {return this.read().onePasswordGrants ?? {};}@@ -526,6 +538,7 @@ export class VaultStore {return [...data.logins.flatMap((login) => [login.password, ...(login.totp ? [login.totp.secret] : [])]),...(data.onePassword ? [data.onePassword.token] : []),+ ...(data.bitwarden ? [data.bitwarden.clientSecret, data.bitwarden.password] : []),...(data.secrets ?? []).map((secret) => secret.value),];}diff --git a/server/vault/providers.ts b/server/vault/providers.tsindex ea70474007..d780eda81b 100644--- a/server/vault/providers.ts+++ b/server/vault/providers.ts@@ -24,8 +24,9 @@ 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;+ /** The secret a reference in the manager's own form names (1Password's `op://…`, Bitwarden's `bw://…`) and the field it+ * reads; the secret may be one the list does not show by name. */+ resolve?(reference: string): { secret: LinkedSecret; field?: string } | null;}function logins(provider: VaultProvider, bots: string | readonly string[]): LoginSummary[] {@@ -70,11 +71,10 @@ 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.+ // Security: a reference reaches only a secret this bot may use, by the same bots 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 } : {}) };+ if (named && loginUsableBy(named.secret, botId)) return { provider, secret: named.secret, ...(named.field ? { field: named.field } : {}) };}return null;}diff --git a/shared/logins.ts b/shared/logins.tsindex d6a199446d..dad27b4058 100644--- a/shared/logins.ts+++ b/shared/logins.ts@@ -7,8 +7,8 @@import { getDomain } from "tldts";/** Where a login came from: the sign-in card's Save, Settings, or the person's- * 1Password vault (read-only here). */-export type LoginSource = "card" | "settings" | "1password";+ * 1Password or Bitwarden vault (read-only here). */+export type LoginSource = "card" | "settings" | "1password" | "bitwarden";/** Which bots may use a login: every bot, or the ones named. */export type LoginBots = "all" | string[];@@ -67,6 +67,29 @@ export interface OnePasswordStatus {error?: string;}+/** Bitwarden, connected through its command line tool with an account's API key and master password, none of which+ * leaves the server. `server`: the Bitwarden server's host; `account`: the address the account signs in with. */+export interface BitwardenStatus {+ connected: boolean;+ server?: string;+ account?: string;+ /** How many logins and secrets it lists. */+ items?: number;+ error?: string;+}++/** What an admin connects Bitwarden with: the server's https address, the account's personal API key and its master+ * password. Sent once, kept sealed on the server, never sent back. */+export interface BitwardenCredentials {+ serverUrl: string;+ clientId: string;+ clientSecret: string;+ password: string;+}++/** The Bitwarden servers an admin picks from; anything else is a self-hosted (or Vaultwarden) address. */+export const BITWARDEN_SERVERS = ["https://vault.bitwarden.com", "https://vault.bitwarden.eu"] as const;+/** The longest username or password a form takes. */export const LOGIN_FIELD_MAX = 512;diff --git a/src/components/BitwardenConnection.tsx b/src/components/BitwardenConnection.tsxnew file mode 100644index 0000000000..a0ab21f547--- /dev/null+++ b/src/components/BitwardenConnection.tsx@@ -0,0 +1,106 @@+import { useState, type FormEvent } from "react";+import { Loader2 } from "lucide-react";++import { BITWARDEN_SERVERS, type BitwardenStatus } from "../../shared/logins";+import { t } from "@/lib/i18n";+import { connectBitwarden, disconnectBitwarden, refreshBitwarden } from "@/lib/logins";+import { Select } from "./Select";+import { SETTINGS_INPUT, SettingsField } from "./SettingsPrimitives";+import { SettingsDialog } from "./settings/SettingsDialog";++// Security: the API key and master password are typed here once and never come back; the form forgets them once sent.++const SELF_HOSTED = "self-hosted";++/** Bitwarden in Settings → Vault, beside 1Password: one row with its state, and a small dialog to connect it. */+export function BitwardenConnection({ status, disabled, team, onChange }: {+ status: BitwardenStatus;+ disabled: boolean;+ /** On a Team Cloud an admin connects it for the whole team. */+ team: boolean;+ onChange: (status: BitwardenStatus) => Promise<void>;+}) {+ const [open, setOpen] = useState(false);+ const [server, setServer] = useState<string>(BITWARDEN_SERVERS[0]);+ const [ownServer, setOwnServer] = useState("");+ const [clientId, setClientId] = useState("");+ const [clientSecret, setClientSecret] = useState("");+ const [password, setPassword] = useState("");+ const [busy, setBusy] = useState<"connect" | "refresh" | "disconnect" | null>(null);+ const [error, setError] = useState<string | null>(null);+ const forget = () => { setClientId(""); setClientSecret(""); setPassword(""); };+ const run = async (kind: NonNullable<typeof busy>, work: () => Promise<BitwardenStatus>) => {+ if (busy) return;+ setBusy(kind);+ setError(null);+ try { await onChange(await work()); if (kind === "connect") { forget(); setOpen(false); } }+ catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.vault.bitwarden.error")); }+ finally { setBusy(null); }+ };+ const serverUrl = server === SELF_HOSTED ? ownServer.trim() : server;+ const ready = Boolean(serverUrl && clientId.trim() && clientSecret.trim() && password);+ const connect = (event: FormEvent) => {+ event.preventDefault();+ if (ready) void run("connect", () => connectBitwarden({ serverUrl, clientId: clientId.trim(), clientSecret: clientSecret.trim(), password }));+ };+ const line = status.connected+ ? t("settings.vault.bitwarden.connected", { account: status.account ?? status.server ?? "Bitwarden", count: String(status.items ?? 0) })+ : t("settings.vault.bitwarden.line");+ return (+ <section className="flex flex-col gap-2 px-4 py-3" aria-label={t("settings.vault.bitwarden.title")} data-bitwarden>+ <div className="flex items-center gap-6">+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="text-[14px] leading-5 text-ink">{t("settings.vault.bitwarden.title")}</span>+ <span className="text-[13px] leading-[18px] text-ink-secondary" data-bitwarden-line>{line}</span>+ </div>+ {status.connected ? <>+ <button type="button" className="settings-quiet cursor-pointer" disabled={disabled || busy !== null} onClick={() => void run("refresh", refreshBitwarden)}>{t("settings.logins.onePassword.refresh")}</button>+ <button type="button" className="ui-button" disabled={disabled || busy !== null} aria-label={t("settings.vault.bitwarden.disconnect")}+ onClick={() => void run("disconnect", disconnectBitwarden)}>{t("settings.logins.onePassword.disconnect")}</button>+ </> : <button type="button" className="ui-button" disabled={disabled} onClick={() => setOpen(true)}>{t("settings.vault.bitwarden.connect")}</button>}+ </div>+ {team && <p className="text-[12px] leading-4 text-ink-tertiary" data-bitwarden-team>{t("settings.vault.bitwarden.team")}</p>}+ {status.connected && status.error && <p role="alert" className="text-[12px] leading-4 text-danger">{status.error}</p>}+ {error && !open && <p role="alert" className="text-[12px] leading-4 text-danger">{error}</p>}+ {open && !status.connected && (+ <SettingsDialog title={t("settings.vault.bitwarden.connect")} onClose={() => { forget(); setOpen(false); }}+ footer={<>+ <button type="button" className="ui-button" onClick={() => { forget(); setOpen(false); }}>{t("common.cancel")}</button>+ <button type="submit" form="bitwarden-connect" className="ui-button ui-button-primary gap-1.5" disabled={disabled || busy !== null || !ready}>+ {busy === "connect" && <Loader2 size={13} className="animate-spin" />}{t("settings.vault.bitwarden.connect")}+ </button>+ </>}>+ <form id="bitwarden-connect" className="flex flex-col gap-3" onSubmit={connect}>+ <p className="text-[13px] leading-[18px] text-ink-secondary" data-bitwarden-guide>{t("settings.vault.bitwarden.guide")}</p>+ <SettingsField label={t("settings.vault.bitwarden.server")}>+ <Select name="bitwardenServer" value={server} onChange={(event) => setServer(event.target.value)} disabled={busy !== null}>+ <option value={BITWARDEN_SERVERS[0]}>bitwarden.com</option>+ <option value={BITWARDEN_SERVERS[1]}>bitwarden.eu</option>+ <option value={SELF_HOSTED}>{t("settings.vault.bitwarden.selfHosted")}</option>+ </Select>+ </SettingsField>+ {server === SELF_HOSTED && (+ <SettingsField label={t("settings.vault.bitwarden.address")}>+ <input name="bitwardenServerUrl" type="url" autoComplete="off" spellCheck={false} placeholder="https://vault.example.com" maxLength={2048}+ value={ownServer} onChange={(event) => setOwnServer(event.target.value)} disabled={busy !== null} className={SETTINGS_INPUT} />+ </SettingsField>+ )}+ <SettingsField label="client_id">+ <input name="bitwardenClientId" type="text" autoComplete="off" spellCheck={false} maxLength={200} value={clientId}+ onChange={(event) => setClientId(event.target.value)} disabled={busy !== null} className={SETTINGS_INPUT} />+ </SettingsField>+ <SettingsField label="client_secret">+ <input name="bitwardenClientSecret" type="password" autoComplete="off" spellCheck={false} maxLength={256} value={clientSecret}+ onChange={(event) => setClientSecret(event.target.value)} disabled={busy !== null} className={SETTINGS_INPUT} />+ </SettingsField>+ <SettingsField label={t("settings.vault.bitwarden.password")} hint={t("settings.vault.bitwarden.note")}>+ <input name="bitwardenPassword" type="password" autoComplete="off" spellCheck={false} maxLength={1024} value={password}+ onChange={(event) => setPassword(event.target.value)} disabled={busy !== null} className={SETTINGS_INPUT} />+ </SettingsField>+ {error && <p role="alert" className="text-[12px] leading-4 text-danger">{error}</p>}+ </form>+ </SettingsDialog>+ )}+ </section>+ );+}diff --git a/src/components/VaultSettings.test.ts b/src/components/VaultSettings.test.tsindex 65de31e2c9..6da1111d44 100644--- a/src/components/VaultSettings.test.ts+++ b/src/components/VaultSettings.test.ts@@ -266,6 +266,57 @@ describe("Settings → Vault: logins", () => {expect(host.textContent, "off a team").not.toContain(hint);});+ it("connects Bitwarden with its server, API key and master password, sent once and forgotten, with the setup to use in one line", async () => {+ const on = { connected: true, server: "vw.example.test", account: "[email protected]", items: 2 };+ const linked = { id: "bitwarden:i1", name: "Stripe", fields: [], source: "linked", provider: "bitwarden", bots: "all", readOnly: true };+ const login = { ...VAULT_LOGIN, id: "bitwarden:i2:github.com", site: "github.com", hosts: ["github.com"], source: "bitwarden" };+ fixture.config = { team: { id: "acme", name: "Acme" } };+ fixture.api+ .mockResolvedValueOnce({ logins: [], secrets: [], onePassword: OFF, bitwarden: OFF })+ .mockResolvedValueOnce({ bitwarden: on })+ .mockResolvedValueOnce({ logins: [login], secrets: [linked], onePassword: OFF, bitwarden: on })+ .mockResolvedValueOnce({ bitwarden: OFF })+ .mockResolvedValueOnce({ logins: [], secrets: [], onePassword: OFF, bitwarden: OFF });+ await render();+ expect(host.querySelector("[data-bitwarden-team]")!.textContent).toContain("Use a dedicated Bitwarden account that can only see one collection.");+ await click("Connect Bitwarden");+ const dialog = () => document.body.querySelector("[data-settings-dialog]")!;+ expect(dialog().querySelector("[data-bitwarden-guide]")!.textContent).toMatch(/^Use a dedicated Bitwarden account that can only see one collection\./u);+ expect(dialog().querySelector('input[name="bitwardenServerUrl"]'), "no address field for bitwarden.com").toBeNull();+ await act(async () => {+ const select = dialog().querySelector<HTMLSelectElement>('select[name="bitwardenServer"]')!;+ select.value = "self-hosted";+ select.dispatchEvent(new Event("change", { bubbles: true }));+ });+ await type("bitwardenServerUrl", "https://vw.example.test");+ await type("bitwardenClientId", "user.fake-id");+ await type("bitwardenClientSecret", "fake-client-secret");+ await type("bitwardenPassword", "fake-master");+ for (const name of ["bitwardenClientSecret", "bitwardenPassword"]) expect(document.body.querySelector<HTMLInputElement>(`input[name="${name}"]`)!.type).toBe("password");+ await act(async () => [...dialog().querySelectorAll("button")].find((one) => one.textContent === "Connect Bitwarden")!.click());+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+ expect(fixture.api).toHaveBeenNthCalledWith(2, "/api/logins/bitwarden", { method: "POST",+ body: JSON.stringify({ serverUrl: "https://vw.example.test", clientId: "user.fake-id", clientSecret: "fake-client-secret", password: "fake-master" }) });+ expect(host.querySelector("[data-bitwarden-line]")!.textContent).toBe("Connected as [email protected] · 2 logins and secrets");+ expect(host.innerHTML).not.toContain("fake-master");+ expect(host.querySelector('[data-secret-row="Stripe"]')!.textContent).toContain("From Bitwarden · All bots");+ const row = host.querySelector('[data-login-row="github.com"]')!;+ expect(row.textContent).toContain("From Bitwarden");+ expect(row.querySelectorAll("button"), "read-only here").toHaveLength(0);+ await click("Disconnect Bitwarden");+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+ expect(fixture.api).toHaveBeenNthCalledWith(4, "/api/logins/bitwarden", { method: "DELETE" });+ await click("Connect Bitwarden");+ expect(document.body.querySelector<HTMLInputElement>('input[name="bitwardenPassword"]')!.value).toBe("");+ });++ it("shows no Bitwarden row where the server does not offer it", async () => {+ fixture.api.mockResolvedValueOnce({ logins: [], secrets: [], onePassword: OFF });+ await render();+ expect(host.querySelector("[data-onepassword]")).not.toBeNull();+ expect(host.querySelector("[data-bitwarden]")).toBeNull();+ });+it("is for admins only", async () => {fixture.admin = false;await render();diff --git a/src/components/VaultSettings.tsx b/src/components/VaultSettings.tsxindex e17761ec48..e0c8b9d4d6 100644--- a/src/components/VaultSettings.tsx+++ b/src/components/VaultSettings.tsx@@ -1,7 +1,7 @@import { useEffect, useState, type FormEvent } from "react";import { ChevronDown, KeyRound, Loader2, LockKeyhole, ShieldCheck, Trash2 } from "lucide-react";-import { loginHeldBackFor, normalizeLoginHost, type LoginBots, type LoginSummary, type OnePasswordItemRef, type OnePasswordStatus, type OnePasswordVault } from "../../shared/logins";+import { loginHeldBackFor, normalizeLoginHost, type BitwardenStatus, type LoginBots, type LoginSummary, type OnePasswordItemRef, type OnePasswordStatus, type OnePasswordVault } from "../../shared/logins";import type { LinkedSecret, VaultSecret } from "../../shared/vault";import { t } from "@/lib/i18n";import { productName } from "@/lib/brand";@@ -15,6 +15,7 @@ import { LoginBotPicker, LoginForm } from "./LoginForm";import { Card, LearnMore, SETTINGS_INPUT, SettingsEmptyRow, SettingsField, SettingsGroup, SettingsLinkRow, SettingsRows } from "./SettingsPrimitives";import { SettingsDialog } from "./settings/SettingsDialog";import { EnvImportForm, SecretForm } from "./VaultSecretForms";+import { BitwardenConnection } from "./BitwardenConnection";// Security: a row never shows a password or a secret, which no route returns. A saved value can only be replaced.@@ -22,8 +23,11 @@ const SOURCE_KEYS = {card: "settings.logins.source.card",settings: "settings.logins.source.settings","1password": "settings.logins.source.1password",+ bitwarden: "settings.logins.source.bitwarden",linked: "settings.logins.source.1password",} as const;+/** A linked secret's line says which password manager it is in. */+const sourceKey = (secret: VaultSecret | LinkedSecret) => secret.source === "linked" && secret.provider === "bitwarden" ? SOURCE_KEYS.bitwarden : SOURCE_KEYS[secret.source];const ROW_BUTTON = "flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50";@@ -50,6 +54,7 @@ export function VaultSettings() {const [logins, setLogins] = useState<LoginSummary[] | null>(null);const [secrets, setSecrets] = useState<Array<VaultSecret | LinkedSecret>>([]);const [onePassword, setOnePassword] = useState<OnePasswordStatus>({ connected: false });+ const [bitwarden, setBitwarden] = useState<BitwardenStatus | null>(null);const [error, setError] = useState<string | null>(null);const [query, setQuery] = useState("");const [filter, setFilter] = useState<Filter>("all");@@ -74,6 +79,7 @@ export function VaultSettings() {setLogins(answer.logins ?? []);setSecrets(answer.secrets ?? []);setOnePassword(answer.onePassword ?? { connected: false });+ setBitwarden(answer.bitwarden ?? null);setError(null);}catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.vault.loadError")); }@@ -164,7 +170,7 @@ export function VaultSettings() {</div>)}</div>- {login.source !== "1password" && rowButtons(login.id, "login", login.site, () => startEdit(login.id, login))}+ {login.source !== "1password" && login.source !== "bitwarden" && rowButtons(login.id, "login", login.site, () => startEdit(login.id, login))}{login.onePassword && itemButton(login.id, login.site)}</div>{editing === login.id && login.onePassword && itemEditor(login.onePassword, login.bots)}@@ -200,7 +206,7 @@ export function VaultSettings() {<div className="min-w-0 flex-1"><div dir="auto" className="truncate text-[13px] font-medium text-ink" title={secret.name}>{secret.name}</div><div className="mt-0.5 text-[12px] leading-snug text-ink-tertiary">- {[t(SOURCE_KEYS[secret.source]), whoLine(secret.bots, secret.source === "linked" ? secret.onePassword : undefined), used(secret.lastUsedAt)].join(" · ")}+ {[t(sourceKey(secret)), whoLine(secret.bots, secret.source === "linked" ? secret.onePassword : undefined), used(secret.lastUsedAt)].join(" · ")}</div></div>{secret.source !== "linked" && rowButtons(secret.id, "secret", secret.name, () => startEdit(secret.id))}@@ -280,6 +286,8 @@ export function VaultSettings() {</div><OnePasswordConnection status={onePassword} disabled={logins === null} bots={bots} botNames={botNames} team={Boolean(state.config?.team)}onChange={async (next) => { setOnePassword(next); await load(); }} />+ {bitwarden && <BitwardenConnection status={bitwarden} disabled={logins === null} team={Boolean(state.config?.team)}+ onChange={async (next) => { setBitwarden(next); await load(); }} />}</SettingsRows></SettingsGroup>}</div>diff --git a/src/lib/logins.ts b/src/lib/logins.tsindex e1e49348f4..22320362ac 100644--- a/src/lib/logins.ts+++ b/src/lib/logins.ts@@ -1,4 +1,4 @@-import type { LoginBots, LoginSummary, OnePasswordStatus } from "../../shared/logins";+import type { BitwardenCredentials, BitwardenStatus, LoginBots, LoginSummary, OnePasswordStatus } from "../../shared/logins";import type { ComputerHelpRef } from "../../shared/wire";import { api } from "@/state/store";@@ -26,6 +26,18 @@ export async function disconnectOnePassword(): Promise<OnePasswordStatus> {return (await api<{ onePassword: OnePasswordStatus }>("/api/logins/1password", { method: "DELETE" })).onePassword;}+export async function connectBitwarden(credentials: BitwardenCredentials): Promise<BitwardenStatus> {+ return (await api<{ bitwarden: BitwardenStatus }>("/api/logins/bitwarden", { method: "POST", body: JSON.stringify(credentials) })).bitwarden;+}++export async function refreshBitwarden(): Promise<BitwardenStatus> {+ return (await api<{ bitwarden: BitwardenStatus }>("/api/logins/bitwarden/refresh", { method: "POST", body: "{}" })).bitwarden;+}++export async function disconnectBitwarden(): Promise<BitwardenStatus> {+ return (await api<{ bitwarden: BitwardenStatus }>("/api/logins/bitwarden", { method: "DELETE" })).bitwarden;+}+export async function addLogin(site: string, fields: LoginFieldsInput, bots: LoginBots, exactHost = false): Promise<LoginSummary> {return (await api<{ login: LoginSummary }>("/api/logins", {method: "POST",diff --git a/src/lib/vault.ts b/src/lib/vault.tsindex f6748d3887..4738e283a2 100644--- a/src/lib/vault.ts+++ b/src/lib/vault.ts@@ -1,4 +1,4 @@-import type { LoginBots, LoginSummary, OnePasswordStatus } from "../../shared/logins";+import type { BitwardenStatus, LoginBots, LoginSummary, OnePasswordStatus } from "../../shared/logins";import type { LinkedSecret, VaultChoice, VaultSecret } from "../../shared/vault";import type { ComputerHelpRef } from "../../shared/wire";import { api } from "@/state/store";@@ -9,6 +9,8 @@ export interface VaultList {logins: LoginSummary[];secrets: Array<VaultSecret | LinkedSecret>;onePassword: OnePasswordStatus;+ /** Absent from a server that does not offer Bitwarden. */+ bitwarden?: BitwardenStatus;}export async function listVault(): Promise<VaultList> {diff --git a/src/locales/en.json b/src/locales/en.jsonindex 22544d8d8c..bea8bf2a48 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -11064,5 +11064,19 @@"templateImport.remove": "Remove {name}","sidebar.addDepartment": "Add department","sidebar.import": "Import…",- "team.shareDepartment": "Share"+ "team.shareDepartment": "Share",+ "settings.logins.source.bitwarden": "From Bitwarden",+ "settings.vault.bitwarden.title": "Bitwarden",+ "settings.vault.bitwarden.line": "Let bots use logins and secrets from a Bitwarden account.",+ "settings.vault.bitwarden.connected": "Connected as {account} · {count} logins and secrets",+ "settings.vault.bitwarden.connect": "Connect Bitwarden",+ "settings.vault.bitwarden.disconnect": "Disconnect Bitwarden",+ "settings.vault.bitwarden.team": "For the whole team: its bots use it in shared and private chats. Use a dedicated Bitwarden account that can only see one collection.",+ "settings.vault.bitwarden.guide": "Use a dedicated Bitwarden account that can only see one collection. In that account, open Account settings → Security → Keys → View API key, then paste its client_id and client_secret here with its master password. Bitwarden's own command line tool is downloaded from Bitwarden the first time.",+ "settings.vault.bitwarden.server": "Server",+ "settings.vault.bitwarden.selfHosted": "Self-hosted or Vaultwarden",+ "settings.vault.bitwarden.address": "Server address",+ "settings.vault.bitwarden.password": "Master password",+ "settings.vault.bitwarden.note": "Kept encrypted on the computer this runs on and never shown again. Bitwarden's logins appear in the list above, filled the same way, and are changed in Bitwarden.",+ "settings.vault.bitwarden.error": "Bitwarden could not be connected. Try again."}diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 6faf23b590..487275462f 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -11064,5 +11064,19 @@"templateImport.remove": "Remover {name}","sidebar.addDepartment": "Adicionar equipe","sidebar.import": "Importar…",- "team.shareDepartment": "Compartilhar"+ "team.shareDepartment": "Compartilhar",+ "settings.logins.source.bitwarden": "Do Bitwarden",+ "settings.vault.bitwarden.title": "Bitwarden",+ "settings.vault.bitwarden.line": "Deixe os bots usarem logins e segredos de uma conta do Bitwarden.",+ "settings.vault.bitwarden.connected": "Conectado como {account} · {count} logins e segredos",+ "settings.vault.bitwarden.connect": "Conectar o Bitwarden",+ "settings.vault.bitwarden.disconnect": "Desconectar o Bitwarden",+ "settings.vault.bitwarden.team": "Para toda a equipe: os bots usam em chats compartilhados e privados. Use uma conta do Bitwarden dedicada que só veja uma coleção.",+ "settings.vault.bitwarden.guide": "Use uma conta do Bitwarden dedicada que só veja uma coleção. Nessa conta, abra Configurações da conta → Segurança → Chaves → Ver chave de API e cole aqui o client_id e o client_secret, com a senha mestra. A ferramenta de linha de comando do próprio Bitwarden é baixada do Bitwarden na primeira vez.",+ "settings.vault.bitwarden.server": "Servidor",+ "settings.vault.bitwarden.selfHosted": "Auto-hospedado ou Vaultwarden",+ "settings.vault.bitwarden.address": "Endereço do servidor",+ "settings.vault.bitwarden.password": "Senha mestra",+ "settings.vault.bitwarden.note": "Guardada criptografada no computador onde isto roda e nunca mais exibida. Os logins do Bitwarden aparecem na lista acima, são preenchidos da mesma forma e editados no Bitwarden.",+ "settings.vault.bitwarden.error": "Não foi possível conectar o Bitwarden. Tente de novo."}