Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Save card secrets in the Vault and reuse them without a new card (#4980)
Milind Soniafdc12c9aa67
diff --git a/apps/docs/content/docs/security/permissions-and-secrets.mdx b/apps/docs/content/docs/security/permissions-and-secrets.mdxindex 65a22a3bcb..2029744b17 100644--- a/apps/docs/content/docs/security/permissions-and-secrets.mdx+++ b/apps/docs/content/docs/security/permissions-and-secrets.mdx@@ -29,12 +29,16 @@ key MausBot keeps itself (an AI provider key, the Composio key, voice keys,the Boat key) is saved exactly where **Settings → API keys** saves it.Any other secret (a Stripe or npm token, a webhook signing secret, a Notion key-for an MCP server) the bot names, and the card says what the bot may do with it:--- **For MausBot's own tools.** MausBot keeps the value in memory and- gives the bot a one-use reference instead. Only `add_mcp_server` accepts it,- only for that bot in that conversation, for an hour. The bot never sees the- value; the MCP server's settings hold it.+for an MCP server) the bot names. MausBot saves what you type in its encrypted+vault, beside your saved logins, for that bot only. When the bot asks for a+secret by the same name again, in any conversation, it gets it at once with no+new card. The card says what the bot may do with it:++- **For MausBot's own tools.** The bot gets a one-use reference instead of the+ value. Only `add_mcp_server` accepts it, only for that bot in that+ conversation, for an hour. The bot never sees the value; the MCP server's+ settings hold it. A secret you gave this way is never written to a file for+ the bot's commands without a new card.- **For the bot's own commands.** The value goes into a file only your user canread, in a private `.openmausbot-secrets` folder of the bot's own workspace (orits Local VM's). The bot reads it inside a command. The file is deleted after@@ -44,8 +48,8 @@ for an MCP server) the bot names, and the card says what the bot may do with it:On a Team Cloud only the person the conversation belongs to can enter it. Afreshly QR-paired phone can enter either kind; an AI provider key needs the-computer or My Cloud. While a value lives, MausBot masks it if it appears in-a transcript, an event or a log.+computer or My Cloud. MausBot masks every saved value if it appears in a+transcript, an event or a log.## Connected-app tool grantsdiff --git a/docs/verification/browser-live.md b/docs/verification/browser-live.mdindex 2626298c86..b15ade7ede 100644--- a/docs/verification/browser-live.md+++ b/docs/verification/browser-live.md@@ -139,7 +139,7 @@ pnpm exec vitest run server/browser-engine.test.ts server/browser-runtime.test.tsrc/lib/browser-profiles.test.ts src/components/BrowserProfilesManager.test.ts \src/components/browser/StreamSurface.test.ts server/routes/browser-viewers.test.ts \src/components/BrowserPanel.test.ts src/components/SignInRequestCard.test.ts \- server/sign-in-request.e2e.test.ts server/login-fill.test.ts server/login-store.test.ts \+ server/sign-in-request.e2e.test.ts server/login-fill.test.ts server/vault-store.test.ts \server/totp.test.ts server/routes/logins.test.ts src/components/LoginsSettings.test.ts \server/saved-login.e2e.test.ts server/onepassword.test.ts scripts/prepare-duckdb.test.mjs```diff --git a/scripts/testing/secret-card-descriptions.test.ts b/scripts/testing/secret-card-descriptions.test.tsindex 0abe4ba4b9..ea42d9b8ce 100644--- a/scripts/testing/secret-card-descriptions.test.ts+++ b/scripts/testing/secret-card-descriptions.test.ts@@ -7,6 +7,7 @@ import { DATA_DIR, loadConfig } from "../../server/config.ts";import { createSecretCards } from "../../server/host/secret-cards.ts";import { PhoneSecretSubmissionRegistry } from "../../server/phone-secret.ts";import { Store } from "../../server/store.ts";+import { VaultStore } from "../../server/vault-store.ts";import "../../server/server-line-packs.ts";import { SecretRequestCard } from "../../src/components/SecretRequestCard";import { setLocale } from "../../src/lib/i18n";@@ -28,6 +29,7 @@ function producedCard(target: CredentialTargetId, reason: string, language?: strstore,cfg: loadConfig(),botLogins: { credentialConfig: (config) => ({ ...config, onePassword: { connected: false } }) },+ vaultStore: new VaultStore({ dataDir: DATA_DIR }),phoneSecrets: { provide: vi.fn(), open: vi.fn() },phoneSecretSubmissions: new PhoneSecretSubmissionRegistry(),connectorThread: () => ({ bot, group: undefined }),diff --git a/server/bot-logins.test.ts b/server/bot-logins.test.tsindex dd90830b24..851adffff9 100644--- a/server/bot-logins.test.ts+++ b/server/bot-logins.test.ts@@ -6,7 +6,7 @@ import { join } from "node:path";import { browserMatesOf, loginHeldBackFor } from "../shared/logins.ts";import { BotLogins, cardLoginPlace, cardSignInElsewhere, observeSignInPage } from "./bot-logins.ts";-import { LoginStore } from "./login-store.ts";+import { VaultStore } from "./vault-store.ts";import type { OnePasswordLogins } from "./onepassword.ts";import { FakeLoginPage, LOGIN_FORM } from "./testing/fake-login-page.ts";@@ -58,7 +58,7 @@ describe("a login kept to some bots, and bots that share a browser", () => {];const onePassword = { fresh: async () => {}, sitesFor: () => [], candidates: () => [], markUsed: () => {} } as unknown as OnePasswordLogins;const world = () => {- const store = new LoginStore({ dataDir: mkdtempSync(join(tmpdir(), "omb-bot-logins-")) });+ const store = new VaultStore({ dataDir: mkdtempSync(join(tmpdir(), "omb-bot-logins-")) });const logins = new BotLogins(store, onePassword, () => bots);const place = { site: "capacity.example", hosts: ["capacity.example"], exactHost: false };return { store, logins, place };diff --git a/server/bot-logins.ts b/server/bot-logins.tsindex 108e4c543d..c9b25bda27 100644--- a/server/bot-logins.ts+++ b/server/bot-logins.ts@@ -1,7 +1,7 @@import { browserMatesOf, loginPageCheck, loginPlace, loginSite, type LoginPlace } from "../shared/logins.ts";import type { FillCandidate } from "./login-fill.ts";import { receiveLoginHandoff, type ConnectionHandoffAnswer, type ConnectionHandoffWhat, type LoginHandoffResult } from "./login-handoff.ts";-import type { LoginStore } from "./login-store.ts";+import type { VaultStore } from "./vault-store.ts";import type { OnePasswordLogins } from "./onepassword.ts";import type { LoginRouteDeps } from "./routes/logins.ts";@@ -44,11 +44,11 @@ export function cardLoginPlace(cardHost: string, observed: ObservedPage | null,/** Saved logins and 1Password items, as each bot may use them. A login kept to some bots is filled only where every bot* sharing that browser may use it: a sign-in stays in the browser, so a bot sharing it would be signed in as well. */export class BotLogins {- readonly store: LoginStore;+ readonly store: VaultStore;readonly onePassword: OnePasswordLogins;private readonly bots: () => ReadonlyArray<{ id: string; browserProfile?: string | null }>;- constructor(store: LoginStore, onePassword: OnePasswordLogins, bots: () => ReadonlyArray<{ id: string; browserProfile?: string | null }> = () => []) {+ constructor(store: VaultStore, onePassword: OnePasswordLogins, bots: () => ReadonlyArray<{ id: string; browserProfile?: string | null }> = () => []) {this.store = store;this.onePassword = onePassword;this.bots = bots;diff --git a/server/cloud-send-verify.test.ts b/server/cloud-send-verify.test.tsindex 04f8bf3555..837aab41cf 100644--- a/server/cloud-send-verify.test.ts+++ b/server/cloud-send-verify.test.ts@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from "vitest";import { connectionFingerprints } from "./cloud-connections.ts";import { fingerprint, loginFingerprints } from "./cloud-send-verify.ts";import type { AppConfig } from "./config.ts";-import { LoginStore } from "./login-store.ts";+import { VaultStore } from "./vault-store.ts";import { parseTotpKey } from "./totp.ts";// Obvious fakes only.@@ -14,7 +14,7 @@ const KEY = "sk-or-v1-fakeverify0000";const NONCE = "x".repeat(43);const dirs: string[] = [];afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });-const store = () => { const dir = mkdtempSync(join(tmpdir(), "omb-verify-")); dirs.push(dir); return new LoginStore({ dataDir: dir }); };+const store = () => { const dir = mkdtempSync(join(tmpdir(), "omb-verify-")); dirs.push(dir); return new VaultStore({ dataDir: dir }); };describe("credential fingerprints a move checks by", () => {it("are equal for the same login and token saved on two servers, and change with the secret or the nonce", () => {diff --git a/server/cloud-send-verify.ts b/server/cloud-send-verify.tsindex 8640cc8142..f78eea8a2d 100644--- a/server/cloud-send-verify.ts+++ b/server/cloud-send-verify.ts@@ -7,7 +7,7 @@ import { createHmac } from "node:crypto";import { itemKey } from "../electron/cloud-send-parts.mjs";import { canonicalJson } from "../shared/package-format.ts";-import type { LoginStore } from "./login-store.ts";+import type { VaultStore } from "./vault-store.ts";/** At least 32 random bytes, base64url. */export const VERIFY_NONCE = /^[A-Za-z0-9_-]{43,128}$/u;@@ -15,7 +15,7 @@ export const VERIFY_NONCE = /^[A-Za-z0-9_-]{43,128}$/u;export const fingerprint = (nonce: string, value: unknown): string => createHmac("sha256", nonce).update(canonicalJson(value)).digest("hex");/** Each saved login, by the key Send to My Cloud compares it under, and 1Password's token. */-export function loginFingerprints(nonce: string, store: Pick<LoginStore, "changes" | "get" | "onePasswordToken">): Record<string, string> {+export function loginFingerprints(nonce: string, store: Pick<VaultStore, "changes" | "get" | "onePasswordToken">): Record<string, string> {const out: Record<string, string> = {};for (const { id } of store.changes()) {const login = store.get(id);diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex 27418c7ecf..de223bffa5 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -977,18 +977,16 @@ async function requestEmailCard(args: Json, context: ToolCallContext): Promise<Treturn { text: "A secure card for the mailbox is ready in OpenMausBot, on the computer and on a freshly QR-paired phone. End this turn now and say in one line that you are waiting for it; OpenMausBot resumes you when the person connects it or declines." };}-/** A secret OpenMausBot does not keep: the person agrees to one use, and the bot gets a secretRef or a file path back. */+/** Any other secret: from the Vault at once, or from a card the person answers; the bot gets a secretRef or a file path back. */async function requestCustomSecret(args: Json, context: ToolCallContext): Promise<ToolCallResult> {const r = await context.client.apiResponse("/api/internal/request-credential", {method: "POST",- body: JSON.stringify({ fromBotId: context.botId, fromThreadId: context.threadId, label: args.label, reason: args.reason, placeholder: args.placeholder, delivery: args.delivery }),+ body: JSON.stringify({ fromBotId: context.botId, fromThreadId: context.threadId, label: args.label, reason: args.reason, placeholder: args.placeholder, delivery: args.delivery, replace: args.replace === true }),});const label = typeof r.body.label === "string" ? r.body.label : "the secret";if (!r.ok) return { text: String(r.body.error ?? `request_credential failed (HTTP ${r.status}).`), isError: true };if (typeof r.body.text === "string") return { text: `${r.body.text} Continue the task.` };- const asked = r.body.savedAs === "ref"- ? ` ${label} was saved earlier for OpenMausBot's tools only, not as a file for your commands (not a file request), so this card asks for it again.`- : r.body.savedAs === "file" ? ` ${label} was saved earlier as a file for your commands, not as a secretRef, so this card asks for it again.` : "";+ const asked = r.body.savedAs === "ref" ? ` ${label} was saved earlier for OpenMausBot's tools only, not as a file for your commands (not a file request), so this card asks for it again.` : "";return {text: `A secure card for ${label} is now in this conversation, in the app and on a QR-paired phone, and the person was notified. If they can't find it, tell them it is in this conversation, and the notification opens it.${asked} End this turn now and say in one line that you are waiting for it; OpenMausBot resumes you when the person saves or declines, and tells you how to use it. Never ask for it in chat.`,};diff --git a/server/drivers/agents-catalog-goldens/bridged.profiles.json b/server/drivers/agents-catalog-goldens/bridged.profiles.jsonindex 780528f6a7..f331f6dca3 100644--- a/server/drivers/agents-catalog-goldens/bridged.profiles.json+++ b/server/drivers/agents-catalog-goldens/bridged.profiles.json@@ -1,7 +1,7 @@{"default": {- "bytes": 17658,- "sha256": "9c55b7cf36c333c5c5eedebc032a4f7d1b66e8aa0696a9b476871096d9c1f2e6",+ "bytes": 17777,+ "sha256": "f63dfaf052292736de01cfcb21b220cecfb49345d95162ec32b6dcbfd7d04142","tools": ["tool_result_read","list_room_targets",@@ -22,8 +22,8 @@]},"voice": {- "bytes": 18439,- "sha256": "ab1ad05d945d5869e3f81815bd34faaf4c7b2704e84cc4409ef81e2e6b5b12b6",+ "bytes": 18558,+ "sha256": "740dd90140c81f4f7849307d217d8091e6d0c8b9c0d74a0ba695bafcba0284ea","tools": ["tool_result_read","list_room_targets",@@ -45,8 +45,8 @@]},"shared": {- "bytes": 17698,- "sha256": "f18a7198d6439965ce17dabc1baacdbe7fff9b332dec1d6ce12547435f27e725",+ "bytes": 17817,+ "sha256": "a18d769058db1d3630417da013b5191496cdf39f187d985d649f1e0ad1210e16","tools": ["tool_result_read","list_room_targets",@@ -67,8 +67,8 @@]},"shared+voice": {- "bytes": 18479,- "sha256": "b0d0d451b6cb370aa33be5369bec353b8ab79fa18cba39d8e21e6238014b4413",+ "bytes": 18598,+ "sha256": "813ad5bdc113606b923e9a88c6c396853bd5113807c8f283c00ce985dc871b39","tools": ["tool_result_read","list_room_targets",@@ -90,8 +90,8 @@]},"skills": {- "bytes": 17685,- "sha256": "723445769f27654ffbe2eb35eee563ca9dbc43730657d3d5c6f30e3c5cb18d25",+ "bytes": 17804,+ "sha256": "cd857027dac6a67005f8eecbff82d11ab3c573c855fb6af3f7745c7119d882ad","tools": ["tool_result_read","list_room_targets",@@ -112,8 +112,8 @@]},"skills+voice": {- "bytes": 18466,- "sha256": "a93fe58533fc1bf1586c03830876171de48b02319d9e861d14e2140cb8bac4a9",+ "bytes": 18585,+ "sha256": "49244bebb968e65220cb14f32b7d9062175794cdacd2f6a099bcf96e9bdbe226","tools": ["tool_result_read","list_room_targets",@@ -135,8 +135,8 @@]},"skills+shared": {- "bytes": 17725,- "sha256": "77307d291e8684d424414103922f7c5acef79655ec06cd61e2613bc5d14ebd55",+ "bytes": 17844,+ "sha256": "a8aace8fd2f04b29b1764d4a6426e811f0423c4d8b22920a4ebc35070e52afa3","tools": ["tool_result_read","list_room_targets",@@ -157,8 +157,8 @@]},"skills+shared+voice": {- "bytes": 18506,- "sha256": "1b025dc1fe251b30ca2ef1fe30397d7472f28dc398aa41027cddd50bc21a408f",+ "bytes": 18625,+ "sha256": "28668ba7407aff7b88474c604e81eef47cb543ab507740ed7f0a1617f41d8dd3","tools": ["tool_result_read","list_room_targets",@@ -180,8 +180,8 @@]},"non-chief": {- "bytes": 17541,- "sha256": "d0d452c9250a3ed00ba252b32fb9d1fc09add613bb20e288475eb646da620d39",+ "bytes": 17660,+ "sha256": "d73a93285d5c94a9088dc2069d6f97f03d8dc949845557df15f2ed3ed1c7d2ec","tools": ["tool_result_read","list_room_targets",@@ -202,8 +202,8 @@]},"voice+non-chief": {- "bytes": 18322,- "sha256": "f6bcfc5f1415e59cd8ab645512dee6a3b6f91dceff199bb183ff1c2e0d2cd85b",+ "bytes": 18441,+ "sha256": "f6a428842a33ba6b758189f04e7ed32b8df10812840124d03db8a18b804f22d3","tools": ["tool_result_read","list_room_targets",@@ -225,8 +225,8 @@]},"shared+non-chief": {- "bytes": 17581,- "sha256": "4d4e5bf28132e0c3e14c67f710a106b1b4d15cf4fa8043cba533bce0d0cf5a15",+ "bytes": 17700,+ "sha256": "66769795a599edcd7713ae27622ae79cff49d81c30df63525f7589dd5f6eadd5","tools": ["tool_result_read","list_room_targets",@@ -247,8 +247,8 @@]},"shared+voice+non-chief": {- "bytes": 18362,- "sha256": "090c4ac4167f2957b0130fb219fc54c80ac7fec8ab197e7b2c603b6b20f1a54c",+ "bytes": 18481,+ "sha256": "4e456e06eb72197fba41705aa697944b6d3a7337a7bf3514402fa2463169ad01","tools": ["tool_result_read","list_room_targets",@@ -270,8 +270,8 @@]},"skills+non-chief": {- "bytes": 17568,- "sha256": "de9ff26d987df26fa7ceab7a22c9d22882c6ea7c02e9e74ebf158c054859c713",+ "bytes": 17687,+ "sha256": "3f6bbeed88c60b4d30ce95e36e604f2ea25fb36c52455de7694f722bc7be9a4e","tools": ["tool_result_read","list_room_targets",@@ -292,8 +292,8 @@]},"skills+voice+non-chief": {- "bytes": 18349,- "sha256": "07f42229b4f789d2e6b18786275cedf961725dd09e966984ae4e6d7abb053ff2",+ "bytes": 18468,+ "sha256": "2b4925f489b3c78f358344b8fdbc6254ec396ef104e6e6e81cb13969f387ae84","tools": ["tool_result_read","list_room_targets",@@ -315,8 +315,8 @@]},"skills+shared+non-chief": {- "bytes": 17608,- "sha256": "79c0a3d6ff95d902a8ff653cd500d692754750ddb5e59e0e4c60e6e512349c23",+ "bytes": 17727,+ "sha256": "e84b34c91fb71ee9be1a469dc530686c498e1f3a88844a7d6100805d9c9e553e","tools": ["tool_result_read","list_room_targets",@@ -337,8 +337,8 @@]},"skills+shared+voice+non-chief": {- "bytes": 18389,- "sha256": "8b17ace55bc07bc2465c723f4a06a94d44405d03311f1a7bbc979062d810f398",+ "bytes": 18508,+ "sha256": "46308775511dd2cacc013640a6eee4c34ef6ec36f354919072b8ab4c07ac3188","tools": ["tool_result_read","list_room_targets",@@ -360,8 +360,8 @@]},"skills+shared+voice+cloud-home": {- "bytes": 18522,- "sha256": "0f96c9a51ac6ec45bbe13f7eb385464d875c0e401a51ce8e9fe8cb1f3ffb3ddb",+ "bytes": 18641,+ "sha256": "15b132bf6ed7b7ec8dc69e6c5a4806e0aaeaedda6798cbf5e5b298264d998fd5","tools": ["tool_result_read","list_room_targets",@@ -383,8 +383,8 @@]},"skills+shared+voice+non-chief+cloud-home": {- "bytes": 18405,- "sha256": "03a1e93435cc7532fe6652f7d7828044a5e77f157206e0e4226916bd0c3920a6",+ "bytes": 18524,+ "sha256": "df13c164e48e1d0211ac60a6276f7f90a2605d9f46e5e0c2e2794b6887928ac4","tools": ["tool_result_read","list_room_targets",@@ -406,8 +406,8 @@]},"skills+shared+voice+escalations": {- "bytes": 18524,- "sha256": "5f2318e9195505cf489b272022fc90ff7a507b26baecd4fb7aabf7cca698efe0",+ "bytes": 18643,+ "sha256": "c7715b4ebf8982dfd7f46904336f387cea9d26944699b0dc3d2bbf30344f01e6","tools": ["tool_result_read","list_room_targets",@@ -429,8 +429,8 @@]},"skills+shared+voice+escalations+x": {- "bytes": 18585,- "sha256": "6d527bf7e09adbbd6c1ae59f67c1471e52c3e3f6b8956f5f8d34b7398a47507f",+ "bytes": 18704,+ "sha256": "7c27f7de1c6600ba09c48127e3821ab517520645eaabfbcdc5645fa6436bad68","tools": ["tool_result_read","list_room_targets",@@ -452,8 +452,8 @@]},"skills+shared+voice+escalations+x+team": {- "bytes": 18585,- "sha256": "6d527bf7e09adbbd6c1ae59f67c1471e52c3e3f6b8956f5f8d34b7398a47507f",+ "bytes": 18704,+ "sha256": "7c27f7de1c6600ba09c48127e3821ab517520645eaabfbcdc5645fa6436bad68","tools": ["tool_result_read","list_room_targets",@@ -475,8 +475,8 @@]},"skills+shared+voice+escalations+x+team+images": {- "bytes": 18601,- "sha256": "62f5d9084d604c7f94fa8e264066c0f5fdb8aa634e57bc78e03f989e867d143c",+ "bytes": 18720,+ "sha256": "a0f415ff91af5e3abf1b1c4f096f17b50b75322670896df93967e4f88f2bde99","tools": ["tool_result_read","list_room_targets",@@ -498,8 +498,8 @@]},"default+legacy-switches": {- "bytes": 17658,- "sha256": "9c55b7cf36c333c5c5eedebc032a4f7d1b66e8aa0696a9b476871096d9c1f2e6",+ "bytes": 17777,+ "sha256": "f63dfaf052292736de01cfcb21b220cecfb49345d95162ec32b6dcbfd7d04142","tools": ["tool_result_read","list_room_targets",@@ -520,8 +520,8 @@]},"default+mausbot": {- "bytes": 17710,- "sha256": "53e854ec209705be77b994d046756f75257742ed4ec78564dca4779892916707",+ "bytes": 17829,+ "sha256": "5bfc4911f2f61d0e73da29ec71dac2056879fb374aa386f03d1bad4f44b7240d","tools": ["tool_result_read","list_room_targets",@@ -542,8 +542,8 @@]},"skills+shared+voice+mausbot": {- "bytes": 18558,- "sha256": "deec0d6ac8ee20ca9e5e73c5ae0aca7c2f7f56bb33b9fe78ec929cade198a737",+ "bytes": 18677,+ "sha256": "90583a3635d74d2ce3d324b3d2620cc0324e952ccf40ea6f2ca9ba553712b47b","tools": ["tool_result_read","list_room_targets",@@ -565,8 +565,8 @@]},"default+no-computer-pick": {- "bytes": 16446,- "sha256": "4704ce93e07a7d608a4e917ba6a7113abf7563dceed3f499c6a771c0eaf3ba6a",+ "bytes": 16565,+ "sha256": "d437560538acadddd9bdae63cc2fc842ca5bd39523362c556930e3512e17f075","tools": ["tool_result_read","list_room_targets",@@ -586,8 +586,8 @@]},"default+room": {- "bytes": 16409,- "sha256": "0514c60d828b218c66cffc83c741e059ac4863acfdd5e45e05425f738efcfdfa",+ "bytes": 16528,+ "sha256": "2fe8086909148342568535fd87c625090162bbcc14632139ccec5d36b28ad112","tools": ["tool_result_read","list_room_targets",@@ -607,8 +607,8 @@]},"non-chief+room": {- "bytes": 16292,- "sha256": "3c45b2d533a4b70dc6f4c1cb3fe72f183f369c6eb029f41fe2dafdcc2898de48",+ "bytes": 16411,+ "sha256": "d859f830a67ad59c0bc06d6dd1c0beec524a5775d6cf6fa84f0eddc71425b76d","tools": ["tool_result_read","list_room_targets",@@ -628,8 +628,8 @@]},"default+images": {- "bytes": 17674,- "sha256": "ce5777b7dc3848c0c2eae5e2a57468e8efcec637f00fc3793ced23c8a70de9b4",+ "bytes": 17793,+ "sha256": "928c1effa91e398c4af05fb5ffd9e7ba0149ee13d5b09c07cacfb0f16cfe8e40","tools": ["tool_result_read","list_room_targets",diff --git a/server/drivers/agents-catalog-goldens/bridged.tools-list.json b/server/drivers/agents-catalog-goldens/bridged.tools-list.jsonindex a6896856a9..22194debb2 100644--- a/server/drivers/agents-catalog-goldens/bridged.tools-list.json+++ b/server/drivers/agents-catalog-goldens/bridged.tools-list.json@@ -243,7 +243,7 @@},{"name": "request_credential",- "description": "Ask the person for a secret on a secure card in the app or a QR-paired phone, never in chat. credential_id: a key OpenMausBot keeps (onePasswordToken: a 1Password service account token; email: a mailbox on any mail host, one card for its address and password, or for its outgoing server when it is connected but can't send). Other secrets: label, reason, delivery. You never see the value; end the turn, and you resume when they save or decline.",+ "description": "Ask the person for a secret on a secure card in the app or a QR-paired phone, never in chat. credential_id: a key OpenMausBot keeps (onePasswordToken: a 1Password service account token; email: a mailbox on any mail host, one card for its address and password, or for its outgoing server when it is connected but can't send). Other secrets: label, reason, delivery (a saved one returns at once). You never see the value; end the turn, and you resume when they save or decline.","inputSchema": {"type": "object","properties": {@@ -293,6 +293,10 @@"file"],"description": "ref: a one-use secretRef for mcp_server. file: a private file your commands read."+ },+ "replace": {+ "type": "boolean",+ "description": "true if the saved one is wrong: asks again."}}}diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.jsonindex c142784819..812b48978c 100644--- a/server/drivers/agents-catalog-goldens/full.tools-list.json+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json@@ -847,7 +847,7 @@},{"name": "request_credential",- "description": "Ask the person for a secret on a secure card in the app or a QR-paired phone, never in chat. credential_id: a key OpenMausBot keeps (onePasswordToken: a 1Password service account token; email: a mailbox on any mail host, one card for its address and password, or for its outgoing server when it is connected but can't send). Other secrets: label, reason, delivery. You never see the value; end the turn, and you resume when they save or decline.",+ "description": "Ask the person for a secret on a secure card in the app or a QR-paired phone, never in chat. credential_id: a key OpenMausBot keeps (onePasswordToken: a 1Password service account token; email: a mailbox on any mail host, one card for its address and password, or for its outgoing server when it is connected but can't send). Other secrets: label, reason, delivery (a saved one returns at once). You never see the value; end the turn, and you resume when they save or decline.","inputSchema": {"type": "object","properties": {@@ -897,6 +897,10 @@"file"],"description": "ref: a one-use secretRef for mcp_server. file: a private file your commands read."+ },+ "replace": {+ "type": "boolean",+ "description": "true if the saved one is wrong: asks again."}}}diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.jsonindex 52b082e168..6a56b9b9f7 100644--- a/server/drivers/agents-catalog-goldens/profiles.json+++ b/server/drivers/agents-catalog-goldens/profiles.json@@ -1,7 +1,7 @@{"default": {- "bytes": 60474,- "sha256": "7c7d455ff6768837f45fd49ed8463179deffcfab607b049e89a4b6bc163bc7b0",+ "bytes": 60593,+ "sha256": "55ced026331f1b75fbbba42600c9265a5c361283d556cdf1e90b6c15b63f7344","tools": ["tool_result_read","list_room_targets",@@ -52,8 +52,8 @@]},"voice": {- "bytes": 61255,- "sha256": "9e314a3a38fe6ab643cdcc7466d0c15290f1d43e8cfa683a344d280ded671d3a",+ "bytes": 61374,+ "sha256": "90a6960ff21502a97074b7765e5a8ed5ae46bd40e2cdcc5503eb14528b68d47c","tools": ["tool_result_read","list_room_targets",@@ -105,8 +105,8 @@]},"shared": {- "bytes": 62739,- "sha256": "435a70a209f56915374f7038e810118a93563172a8dbc4629246da6c25874578",+ "bytes": 62858,+ "sha256": "d68681e4be4574fc2af5ceff9b1d72589fef027bd14b1fe216410bd2ba5df437","tools": ["tool_result_read","list_shared_computers",@@ -159,8 +159,8 @@]},"shared+voice": {- "bytes": 63520,- "sha256": "7908844a5311f7beb5cd62f07403c1a576adb7ecb867f4dda05274e329686377",+ "bytes": 63639,+ "sha256": "7a7e5c55a97f9a3484e7aa452e72f0592f4c19118b78b35546a9d9ccdfd2fc24","tools": ["tool_result_read","list_shared_computers",@@ -214,8 +214,8 @@]},"skills": {- "bytes": 63550,- "sha256": "a1a12744686f3b2101252bfbad53412db12b5b6e030964424a57c37ab0f477ed",+ "bytes": 63669,+ "sha256": "08223f4f821765723e1412911d22c3b6d8c8a3fb77480064d6a2f9297cba971f","tools": ["tool_result_read","list_room_targets",@@ -268,8 +268,8 @@]},"skills+voice": {- "bytes": 64331,- "sha256": "aa13535ae313f03e205eecd093f02607f69520a25d273dcb074ec4b0eaa99ffe",+ "bytes": 64450,+ "sha256": "b0bdc6325a9fdcb9fa1c968f4be7f0df41ff125dfc770cf9f7511f1f7eb34391","tools": ["tool_result_read","list_room_targets",@@ -323,8 +323,8 @@]},"skills+shared": {- "bytes": 65815,- "sha256": "1d9a1a49de9f8a1faeb85d2b6db7cbd1fabcaab48b8a5e1dd68cca4a703a36de",+ "bytes": 65934,+ "sha256": "61c4c69356ddb97c25cbd3a4ee4386122c7519b2152d824a9a3b4cd5b7196b25","tools": ["tool_result_read","list_shared_computers",@@ -379,8 +379,8 @@]},"skills+shared+voice": {- "bytes": 66596,- "sha256": "c9a6070614f3db8367f09a88b015fddbc2026cde4b6d527a3f56ec904f525103",+ "bytes": 66715,+ "sha256": "d6f458d442a4e513312fe886a17a5d9c12871141cdc5afc66ff989e16aaa02e8","tools": ["tool_result_read","list_shared_computers",@@ -436,8 +436,8 @@]},"non-chief": {- "bytes": 51258,- "sha256": "4758c6669b39051246769a95f5f948049172bfdd5aadf975797e4dc457d91326",+ "bytes": 51377,+ "sha256": "5f56e88a0db5823f72dd6fb760b83f7a7ee42a5bace969c3475a1f54ee97365a","tools": ["tool_result_read","list_room_targets",@@ -481,8 +481,8 @@]},"voice+non-chief": {- "bytes": 52039,- "sha256": "d7e19cc68f631c11f83ac998d7bb5c91e2343948bd404bfc2140ff017d699b97",+ "bytes": 52158,+ "sha256": "a7cd287606e0e420bb7b6773de9ee94e397b4b8e5948e57a3052c2bcd82779df","tools": ["tool_result_read","list_room_targets",@@ -527,8 +527,8 @@]},"shared+non-chief": {- "bytes": 53523,- "sha256": "a55087f99e748a24e53899546af747f55efa90bcbbbe21d5e1c5f103400c34cd",+ "bytes": 53642,+ "sha256": "6b8904c38bf76abe4298abb4ae78fe72f1da9f7bb3e0f91019bfec6d195674cf","tools": ["tool_result_read","list_shared_computers",@@ -574,8 +574,8 @@]},"shared+voice+non-chief": {- "bytes": 54304,- "sha256": "40d59d8c3543709547f0215d5d29eaf66e0f4c71be9e65cd6a9e9fc1e3de4445",+ "bytes": 54423,+ "sha256": "ce5c212734e8454b9a71c108120faf87b3d5f1b8d5495142b58c1801db2f54be","tools": ["tool_result_read","list_shared_computers",@@ -622,8 +622,8 @@]},"skills+non-chief": {- "bytes": 54334,- "sha256": "437de7b18ba29ab38923d0129a107d03a460e1ba8e7dcf7b5061fb27962adc6d",+ "bytes": 54453,+ "sha256": "c7e062952246a0c2bc4f6760ee557aeb9e108fb55b818c8d041dd61ad37740cb","tools": ["tool_result_read","list_room_targets",@@ -669,8 +669,8 @@]},"skills+voice+non-chief": {- "bytes": 55115,- "sha256": "2ae71347d0371acbfe1c9d93140a98773b068291123e07f88b56bac1c209e5cf",+ "bytes": 55234,+ "sha256": "60d47c6e43b5c6c001058e2d205cbfd732f2528768e5511aced8f88c514ec174","tools": ["tool_result_read","list_room_targets",@@ -717,8 +717,8 @@]},"skills+shared+non-chief": {- "bytes": 56599,- "sha256": "0f3b7d6b413e8d7e9d7825e9515f6f7b7381ec2505f4699c26908c026600d909",+ "bytes": 56718,+ "sha256": "313d0c5da1c27d6235c390149a724d6b7b34e86ab910c284e6a49b0c6771336e","tools": ["tool_result_read","list_shared_computers",@@ -766,8 +766,8 @@]},"skills+shared+voice+non-chief": {- "bytes": 57380,- "sha256": "4de56b0185e196bdb0fb918835695d61b942be7cf5c0335aa8eb0846113be184",+ "bytes": 57499,+ "sha256": "73c3979e2b9ae64255cda1dbb059bc1d2b9a14b663f37c0adeb0b5fa81b68ba5","tools": ["tool_result_read","list_shared_computers",@@ -816,8 +816,8 @@]},"skills+shared+voice+cloud-home": {- "bytes": 66362,- "sha256": "397ec50de251c4482c84bfb71c76db22d650d6fcf5702ec16b0a55f9eed78b66",+ "bytes": 66481,+ "sha256": "20a0f7c84bac83382bbdbd1bbd8dd7df7ad172ff4247c89943df640bfbb53217","tools": ["tool_result_read","list_shared_computers",@@ -873,8 +873,8 @@]},"skills+shared+voice+non-chief+cloud-home": {- "bytes": 57146,- "sha256": "e9f01dc1e43310232e670d312a57db0cfe1a3f5bdf87b851facd1609e6b75f5d",+ "bytes": 57265,+ "sha256": "76c23c7b2cd5b3e01850f594e5eefe6565028b68c356cb9f035762cfe15a744b","tools": ["tool_result_read","list_shared_computers",@@ -923,8 +923,8 @@]},"skills+shared+voice+escalations": {- "bytes": 67426,- "sha256": "853fc7c767b2a5a701fde72af5a259d8ed2fd5b3415844c7a1a8de2a3292dd2a",+ "bytes": 67545,+ "sha256": "873706628daff60d623c17efc4ed8cbc4a93dbd92d3cc944ab7784a038b50f28","tools": ["tool_result_read","list_shared_computers",@@ -981,8 +981,8 @@]},"skills+shared+voice+escalations+x": {- "bytes": 71265,- "sha256": "9036aa94c1d56af9ea0108acfb0f261e4ba87b3f60948bd6eeedae5906f6f86c",+ "bytes": 71384,+ "sha256": "150fbf477009989d1eb78061d99c0be07d81c5fb865dfa94ee7bfa05849572b0","tools": ["tool_result_read","list_shared_computers",@@ -1043,8 +1043,8 @@]},"skills+shared+voice+escalations+x+team": {- "bytes": 71265,- "sha256": "9036aa94c1d56af9ea0108acfb0f261e4ba87b3f60948bd6eeedae5906f6f86c",+ "bytes": 71384,+ "sha256": "150fbf477009989d1eb78061d99c0be07d81c5fb865dfa94ee7bfa05849572b0","tools": ["tool_result_read","list_shared_computers",@@ -1105,8 +1105,8 @@]},"skills+shared+voice+escalations+x+team+images": {- "bytes": 72038,- "sha256": "3449b04bf05bba020ea8f5db6019139f08bd75b688259f2a8bd593e58ca86f54",+ "bytes": 72157,+ "sha256": "49bb2b7ea83243d27f4ae7865ae1de0232e51060b7881361115cb9027fc1bfa4","tools": ["tool_result_read","list_shared_computers",@@ -1168,8 +1168,8 @@]},"default+legacy-switches": {- "bytes": 60474,- "sha256": "7c7d455ff6768837f45fd49ed8463179deffcfab607b049e89a4b6bc163bc7b0",+ "bytes": 60593,+ "sha256": "55ced026331f1b75fbbba42600c9265a5c361283d556cdf1e90b6c15b63f7344","tools": ["tool_result_read","list_room_targets",@@ -1220,8 +1220,8 @@]},"default+mausbot": {- "bytes": 61125,- "sha256": "a5189a9f38f62cb250cae0518b7dc5b5b97d638bbae5a5e47a393006d42492c1",+ "bytes": 61244,+ "sha256": "a0a415783fb518c1d700b3e18c06a8669e875890eec442d7d24261f175ede714","tools": ["tool_result_read","list_room_targets",@@ -1274,8 +1274,8 @@]},"skills+shared+voice+mausbot": {- "bytes": 67247,- "sha256": "cb995853c039451c0e9d8ec1d6e7098e8920a42cbdd054cf0b405dc1bf90ce87",+ "bytes": 67366,+ "sha256": "975adc0f77ca1ca1678b5986a10132e2d34b46e998ad1fd9be6d5cf6cd1f38a6","tools": ["tool_result_read","list_shared_computers",@@ -1333,8 +1333,8 @@]},"default+no-computer-pick": {- "bytes": 59262,- "sha256": "2e4e85bb06d6c3ae939a9c6fdd21963f1b9d13d74ffbb9eaa31a91e06d57ac12",+ "bytes": 59381,+ "sha256": "f5760141459eaf5a8b1464b829825411fb0e2d915ae3bb4a6e69e56dc06cd129","tools": ["tool_result_read","list_room_targets",@@ -1384,8 +1384,8 @@]},"default+room": {- "bytes": 57618,- "sha256": "e09da9f95a5776db046806dec13ab71b9689fad1c73d9b094d1f29fd47c7e21a",+ "bytes": 57737,+ "sha256": "90f5ea3d1da4d17158f347cbbbc2a115a20aacf4057d25b861580a53b51202fa","tools": ["tool_result_read","list_room_targets",@@ -1432,8 +1432,8 @@]},"non-chief+room": {- "bytes": 48402,- "sha256": "13f88330f6f80a6e33ce6f448876fc5538d6507f47e9be0cdf9a7000db16ec85",+ "bytes": 48521,+ "sha256": "80ae2fc40f3f9ecda1804e5d38429c06bae829a9e3b86ea277b1651cc13930e5","tools": ["tool_result_read","list_room_targets",@@ -1473,8 +1473,8 @@]},"default+images": {- "bytes": 61247,- "sha256": "83ea15e46df1bd4452d098aa5d1d7fa69592f7825873db0ab83ca47fb7c3097e",+ "bytes": 61366,+ "sha256": "b0dcf42f3de84a34921166cfad05bce2d5321c3875908ab82b15986629954594","tools": ["tool_result_read","list_room_targets",diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.tsindex ebbe232817..005ea520c3 100644--- a/server/drivers/agents-catalog.ts+++ b/server/drivers/agents-catalog.ts@@ -473,7 +473,7 @@ const TOOL_DEFINITIONS = [{name: "request_credential",description:- "Ask the person for a secret on a secure card in the app or a QR-paired phone, never in chat. credential_id: a key OpenMausBot keeps (onePasswordToken: a 1Password service account token; email: a mailbox on any mail host, one card for its address and password, or for its outgoing server when it is connected but can't send). Other secrets: label, reason, delivery. You never see the value; end the turn, and you resume when they save or decline.",+ "Ask the person for a secret on a secure card in the app or a QR-paired phone, never in chat. credential_id: a key OpenMausBot keeps (onePasswordToken: a 1Password service account token; email: a mailbox on any mail host, one card for its address and password, or for its outgoing server when it is connected but can't send). Other secrets: label, reason, delivery (a saved one returns at once). You never see the value; end the turn, and you resume when they save or decline.",inputSchema: {type: "object",properties: {@@ -490,6 +490,7 @@ const TOOL_DEFINITIONS = [enum: ["ref", "file"],description: "ref: a one-use secretRef for mcp_server. file: a private file your commands read.",},+ replace: { type: "boolean", description: "true if the saved one is wrong: asks again." },},},},diff --git a/server/drivers/agents-proxy.test.ts b/server/drivers/agents-proxy.test.tsindex 7ef653d2bd..95cf6c66a2 100644--- a/server/drivers/agents-proxy.test.ts+++ b/server/drivers/agents-proxy.test.ts@@ -710,7 +710,7 @@ describe("agents-proxy MCP surface", () => {expect(credential.description).toContain("on a secure card in the app or a QR-paired phone, never in chat");expect(credential.description).toContain("onePasswordToken: a 1Password service account token");expect(credential.description).toContain("You never see the value");- expect(Object.keys(credential.inputSchema.properties)).toEqual(["credential_id", "address", "label", "reason", "placeholder", "delivery"]);+ expect(Object.keys(credential.inputSchema.properties)).toEqual(["credential_id", "address", "label", "reason", "placeholder", "delivery", "replace"]);expect(credential.inputSchema.properties.address.description).toMatch(/^credential_id email only/);expect(credential.inputSchema.required).toBeUndefined();});@@ -1210,7 +1210,10 @@ describe("agents-proxy MCP surface", () => {reason: "To create test charges.",placeholder: "sk_test_…",delivery: "file",+ replace: false,});+ await callTool("request_credential", { label: "Stripe secret key", reason: "The saved key was refused.", delivery: "ref", replace: true });+ expect(lastCredentialBody).toMatchObject({ label: "Stripe secret key", delivery: "ref", replace: true });});it("rejects credential ids outside the fixed allowlist locally", async () => {diff --git a/server/email/service.ts b/server/email/service.tsindex 8517ddcffb..cb64bcee9d 100644--- a/server/email/service.ts+++ b/server/email/service.ts@@ -4,7 +4,7 @@import { EMAIL_SLUG, type EmailAccountView, type EmailConnectAnswer, type EmailConnectRequest, type EmailOutgoingAnswer, type EmailOutgoingFields, type EmailSignInHint, type EmailStatus, type EmailTestAnswer } from "../../shared/email.ts";import { boxRefusal } from "../bot-box/egress-gate.ts";import { resolveTarget } from "../browser/egress/gate.ts";-import { secretForms } from "../login-store.ts";+import { secretForms } from "../vault-store.ts";import { HELD_SECRET_MASK } from "../redact.ts";import { EmailError, LASTING_SENDING_FAULTS, openGuard, pinned, sendingError, sendMessage, SendingError, testMailbox, testSending, type EmailGuard, type SendingFault } from "./client.ts";import { discoverMailServers, liveDiscoverDeps, smtpBeside, type DiscoverDeps, type MailCandidates } from "./discover.ts";diff --git a/server/host/fill-login-turn.test.ts b/server/host/fill-login-turn.test.tsindex b79715a8c2..edbb1b80b3 100644--- a/server/host/fill-login-turn.test.ts+++ b/server/host/fill-login-turn.test.ts@@ -4,7 +4,7 @@ import { join } from "node:path";import { describe, expect, it, vi } from "vitest";import { BotLogins } from "../bot-logins.ts";-import { LoginStore } from "../login-store.ts";+import { VaultStore } from "../vault-store.ts";import type { OnePasswordLogins } from "../onepassword.ts";import type { Surface } from "../../shared/wire.ts";@@ -116,7 +116,7 @@ describe("fill_login in the bot's own browser", () => {describe("fill_login and a login kept to some bots on a shared browser", () => {const onePassword = { fresh: async () => {}, sitesFor: () => [], candidates: () => [], markUsed: () => {} } as unknown as OnePasswordLogins;const logins = (bots: ReadonlyArray<{ id: string; browserProfile?: string }>) => {- const store = new LoginStore({ dataDir: mkdtempSync(join(tmpdir(), "omb-fill-shared-")) });+ const store = new VaultStore({ dataDir: mkdtempSync(join(tmpdir(), "omb-fill-shared-")) });store.create({ ...BANK, password: "never-shown", source: "settings", bots: ["b1"] });return new BotLogins(store, onePassword, () => bots);};diff --git a/server/host/secret-cards.test.ts b/server/host/secret-cards.test.tsindex 8ecdf1adf4..596e4ee21f 100644--- a/server/host/secret-cards.test.ts+++ b/server/host/secret-cards.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, rmSync } from "node:fs";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";@@ -10,6 +10,7 @@ import { createSecretCards } from "./secret-cards.ts";import { CREDENTIAL_TARGETS } from "../../shared/credential-request.ts";import { redactBotAuthored } from "../message-redaction.ts";import { redactSecretsInText } from "../redact.ts";+import { VaultStore } from "../vault-store.ts";const dirs: string[] = [];afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });@@ -20,26 +21,28 @@ function fixture(language?: string) {const lines: Message[] = [];let ids = 0;const store = {- activePath: () => lines,+ activePath: () => [...lines],messagesFor: () => lines,appendMessage: (_threadId: string, message: Omit<Message, "id" | "at">) => {const full = { id: `m${++ids}`, at: Date.now(), ...message } as Message;lines.push(full);return full;},- patchMessage: () => null,+ patchMessage: (_threadId: string, id: string, patch: Partial<Message>) => Object.assign(lines.find((one) => one.id === id)!, patch),botByThread: () => null,groupByThread: () => undefined,onChange: () => () => {},};const bot = { id: "ledger", name: "Ledger" } as BotRecord;+ const vaultStore = new VaultStore({ dataDir });+ const resumed: string[] = [];const cards = createSecretCards({- store: store as never, cfg: {} as never, botLogins: { credentialConfig: (config) => ({ ...config, onePassword: { connected: false } }) },- phoneSecrets: { provide: async () => {}, open: () => {} } as never, phoneSecretSubmissions: {} as never,- connectorThread: () => ({ bot, group: undefined }), answerCardNode: () => true, followCard: () => {}, dataDir, providerKeysRefused: false,+ store: store as never, cfg: {} as never, botLogins: { credentialConfig: (config) => ({ ...config, onePassword: { connected: false } }) }, vaultStore,+ phoneSecrets: { provide: async () => {}, open: () => {} } as never, phoneSecretSubmissions: { has: () => false } as never,+ connectorThread: () => ({ bot, group: undefined }), answerCardNode: (_thread, _id, text) => { resumed.push(text); return true; }, followCard: () => {}, dataDir, providerKeysRefused: false,layerFolder: () => dataDir, turnVm: () => undefined, ...(language ? { threadLanguage: () => language } : {}),});- return { cards, lines, bot };+ return { cards, lines, bot, vaultStore, resumed, dataDir };}describe("the card a bot asks for a key or secret with", () => {@@ -81,14 +84,71 @@ describe("the card a bot asks for a key or secret with", () => {]);expect(lines[0]!.secret!.description).toBe("Used by the built-in Grok provider. Ledger kann es verwenden, aber nie auslesen.");expect(lines[1]!.secret!.description)- .toBe("Für Testzahlungen. Die Befehle von Ledger können es 24 Stunden lang aus einer privaten Datei lesen; es wird nie in den Chat übernommen.");+ .toBe("Für Testzahlungen. Die Befehle von Ledger können es 24 Stunden lang aus einer privaten Datei lesen; es wird nie in den Chat übernommen. OpenMausBot bewahrt es sicher auf, damit Ledger es wieder nutzen kann, ohne dich erneut zu fragen.");});it("asks in English where no language is known", () => {const { cards, lines, bot } = fixture();cards.requestCredential(bot, "ledger-main", { label: "Notion token", reason: "For Notion's MCP server.", delivery: "ref" });expect(lines[0]!.text).toBe("Securely provide the Notion token from OpenMausBot on your phone or computer. It is never added to chat.");- expect(lines[0]!.secret!.description).toBe("For Notion's MCP server. Ledger gets a one-use reference for OpenMausBot's own tools and never sees it.");+ expect(lines[0]!.secret!.description).toBe("For Notion's MCP server. Ledger gets a one-use reference for OpenMausBot's own tools and never sees it. OpenMausBot keeps it safely, so Ledger can use it again without asking you.");+ });+});++describe("a secret a card saves to the Vault", () => {+ const KEY = "sk_test_fake-card-vault-1";+ const ask = (one: ReturnType<typeof fixture>, threadId: string, extra: Record<string, unknown> = {}) =>+ one.cards.requestCredential(one.bot, threadId, { label: "Stripe secret key", reason: "For test charges.", delivery: "ref", ...extra });+ const refIn = (text: unknown) => /secret-ref:[0-9a-f]{32}/u.exec(String(text))?.[0];++ it("is kept for the asking bot, and its next ask, in any conversation and after any ref is spent, gets a fresh one with no card", () => {+ const one = fixture();+ const card = ask(one, "t1");+ expect(card.status).toBe(201);+ expect(one.cards.saveCustomSecret("ledger", "t1", String(card.body.messageId), ` ${KEY} `).status).toBe(200);+ expect(one.vaultStore.listSecrets()).toMatchObject([{ name: "Stripe secret key", source: "card", bots: ["ledger"], refOnly: true }]);+ const fromCard = refIn(one.resumed[0]);+ expect(fromCard).toBeDefined();+ const spent = one.cards.redeemMcpServer({ env: { STRIPE_SECRET_KEY: fromCard } }, "ledger", "t1");+ if (spent.ok) spent.commit();+ const again = ask(one, "t2", { label: "stripe-secret-key" });+ expect(again.status).toBe(200);+ const fresh = refIn(again.body.text);+ expect(fresh).toBeDefined();+ expect(fresh).not.toBe(fromCard);+ expect(one.lines.filter((line) => line.kind === "secret")).toHaveLength(1);+ const used = one.cards.redeemMcpServer({ env: { STRIPE_SECRET_KEY: fresh } }, "ledger", "t2");+ expect(used.ok && used.value).toEqual({ env: { STRIPE_SECRET_KEY: KEY } });+ expect(one.vaultStore.listSecrets()[0]!.lastUsedAt).toBeGreaterThan(0);+ expect(JSON.stringify([one.lines, one.resumed, again, one.vaultStore.listSecrets()])).not.toContain(KEY);+ });++ it("is not another bot's, and a file for one saved for OpenMausBot's tools only needs its own card", () => {+ const one = fixture();+ one.vaultStore.saveSecret({ name: "Stripe secret key", value: KEY, source: "card", bots: ["ledger"], refOnly: true });+ expect(one.cards.requestCredential({ ...one.bot, id: "quill", name: "Quill" }, "t9", { label: "Stripe secret key", reason: "r", delivery: "ref" }).status).toBe(201);+ expect(ask(one, "t1", { delivery: "file" })).toMatchObject({ status: 201, body: { savedAs: "ref" } });+ });++ it("is written to a file for the bot's commands, which the Vault remakes when asked again", () => {+ const one = fixture();+ const item = one.vaultStore.saveSecret({ name: "Stripe secret key", value: KEY, source: "settings", bots: "all" });+ const answer = ask(one, "t1", { delivery: "file" });+ const file = join(one.dataDir, ".openmausbot-secrets", "t1", `vault-${item.id}`);+ expect(answer).toMatchObject({ status: 200, body: { text: expect.stringContaining(`to the file ${file}`) } });+ expect(readFileSync(file, "utf8")).toBe(KEY);+ rmSync(file);+ ask(one, "t1", { delivery: "file" });+ expect(readFileSync(file, "utf8")).toBe(KEY);+ });++ it("is asked for again when the bot says the saved one is wrong, and the new value replaces it", () => {+ const one = fixture();+ one.vaultStore.saveSecret({ name: "Stripe secret key", value: KEY, source: "card", bots: ["ledger"], refOnly: true });+ const card = ask(one, "t1", { replace: true });+ expect(card.status).toBe(201);+ one.cards.saveCustomSecret("ledger", "t1", String(card.body.messageId), "sk_test_fake-card-vault-2");+ expect(one.vaultStore.secretValues()).toEqual(["sk_test_fake-card-vault-2"]);});});@@ -114,7 +174,7 @@ describe("the mailbox card", () => {const resumed: string[] = [];const bot = { id: "ledger", name: "Ledger" } as BotRecord;const cards = createSecretCards({- store: store as never, cfg: {} as never, botLogins: { credentialConfig: (config) => ({ ...config, onePassword: { connected: false } }) },+ store: store as never, cfg: {} as never, botLogins: { credentialConfig: (config) => ({ ...config, onePassword: { connected: false } }) }, vaultStore: new VaultStore({ dataDir }),phoneSecrets: { provide: async () => {}, open: async () => PASSWORD } as never, phoneSecretSubmissions: { has: () => false, run: async (_card: unknown, _op: unknown, work: () => Promise<void>) => work() } as never,connectorThread: () => ({ bot, group: undefined }), answerCardNode: (_thread, _id, text) => { resumed.push(text); return true; }, followCard: () => {}, dataDir, providerKeysRefused: false,layerFolder: () => dataDir, turnVm: () => undefined,diff --git a/server/host/secret-cards.ts b/server/host/secret-cards.tsindex e42655eb63..fe2a353620 100644--- a/server/host/secret-cards.ts+++ b/server/host/secret-cards.ts@@ -37,6 +37,7 @@ import {type PhoneSecretSubmissionRegistry,} from "../phone-secret.ts";import type { BotLogins } from "../bot-logins.ts";+import type { VaultStore } from "../vault-store.ts";import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";import { serverLine } from "../server-lines.ts";@@ -55,6 +56,8 @@ export interface SecretCardsDeps {store: Pick<Store, "activePath" | "appendMessage" | "patchMessage" | "messagesFor" | "botByThread" | "groupByThread" | "onChange">;cfg: AppConfig;botLogins: Pick<BotLogins, "credentialConfig">;+ /** Where a custom card's value is saved, and found again the next time the same bot asks for it by name. */+ vaultStore: Pick<VaultStore, "saveSecret" | "usableSecret" | "markUsed">;phoneSecrets: Pick<PhoneSecretBridge, "provide" | "open">;phoneSecretSubmissions: PhoneSecretSubmissionRegistry;connectorThread(botId: string, threadId: string): { bot: BotRecord; group: GroupRecord | undefined } | null;@@ -106,7 +109,7 @@ export function savedSecretText(label: string, saved: SavedSecret | null): strin}function deliveryNote(botName: string, delivery: SecretDelivery, language: string | undefined): string {- return serverLine(language, delivery === "file" ? "server.connect.secretFile" : "server.connect.secretRef", { bot: botName });+ return `${serverLine(language, delivery === "file" ? "server.connect.secretFile" : "server.connect.secretRef", { bot: botName })} ${serverLine(language, "server.connect.secretKept", { bot: botName })}`;}/** Where a file secret goes: the Local VM workspace its card names, else the bot's own folder. */@@ -154,7 +157,7 @@ function outgoingFields(fields: Record<string, unknown>): EmailOutgoingFields {return Object.fromEntries(OUTGOING_FIELDS.flatMap((name) => (server[name] === undefined ? [] : [[name, server[name]]]))) as EmailOutgoingFields;}-function customRequest(body: Record<string, unknown>): { label: string; reason: string; placeholder: string; delivery: SecretDelivery } | { error: string } {+function customRequest(body: Record<string, unknown>): { label: string; reason: string; placeholder: string; delivery: SecretDelivery; replace: boolean } | { error: string } {const text = (value: unknown, max: number) => typeof value === "string"? [...value].map((ch) => (ch.charCodeAt(0) < 0x20 || ch === "\u007f" ? " " : ch)).join("").trim().slice(0, max): "";@@ -165,11 +168,11 @@ function customRequest(body: Record<string, unknown>): { label: string; reason:if (!SECRET_DELIVERIES.includes(body.delivery as SecretDelivery)) {return { error: "request_credential needs delivery: ref for OpenMausBot's own tools such as mcp_server, or file for your own commands." };}- return { label, reason, placeholder: text(body.placeholder, CUSTOM_SECRET_LABEL_MAX), delivery: body.delivery as SecretDelivery };+ return { label, reason, placeholder: text(body.placeholder, CUSTOM_SECRET_LABEL_MAX), delivery: body.delivery as SecretDelivery, replace: body.replace === true };}export function createSecretCards(deps: SecretCardsDeps) {- const { store, cfg, botLogins, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode } = deps;+ const { store, cfg, botLogins, vaultStore, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode } = deps;const vault = new SecretVault();addHeldSecretScrubber((text) => vault.scrub(text));@@ -213,13 +216,17 @@ export function createSecretCards(deps: SecretCardsDeps) {if (change.type === "thread.deleted" || change.type === "bot.deleted" || change.type === "group.deleted") sweep();});- /** Keeps a custom card's value where its delivery says, and marks when; never touches the card's other fields. */+ const fileHome = (botId: string, threadId: string, vm: string | undefined): SecretFileHome =>+ (vm ? vmFileHome(botId, vm) : null) ?? { host: deps.layerFolder(botId, threadId), shown: deps.layerFolder(botId, threadId) };++ /** Saves a custom card's value to the Vault for the asking bot, hands it over as its delivery says, and marks when;+ * never touches the card's other fields. */function storeCustomSecret(message: Message, botId: string, threadId: string, value: string): void {const secret = message.secret!;const owner = { botId, threadId };+ vaultStore.saveSecret({ name: secret.label, value, source: "card", bots: [botId], refOnly: secret.delivery !== "file" });if (secret.delivery === "file") {- const home = (secret.vm ? vmFileHome(botId, secret.vm) : null) ?? { host: deps.layerFolder(botId, threadId), shown: deps.layerFolder(botId, threadId) };- vault.saveFile(owner, message.id, value, home);+ vault.saveFile(owner, message.id, value, fileHome(botId, threadId, secret.vm));} else {vault.saveRef(owner, message.id, secret.label, value);}@@ -554,19 +561,25 @@ export function createSecretCards(deps: SecretCardsDeps) {return { messageId: message.id, label: card.label };}- /** A secret OpenMausBot does not keep: the same bot asking again for one already saved here gets it back, and a newer- * card replaces its pending one with the same name. */+ /** A secret the Vault holds for the bot by this name is handed over at once, with no card; otherwise a card asks for it,+ * replacing the bot's pending card with the same name. */function requestCustomSecret(from: BotRecord, threadId: string, room: boolean, body: Record<string, unknown>): { status: number; body: Record<string, unknown> } {const asked = customRequest(body);if ("error" in asked) return { status: 400, body: asked };- const path = store.activePath(threadId);- const earlier = [...path].reverse().find((message) => message.kind === "secret" && message.secret && custom(message.secret) &&- message.secret.savedAt !== undefined && !message.secret.superseded && message.secret.label.toLowerCase() === asked.label.toLowerCase() &&- (!room || message.from?.botId === from.id));- const kept = earlier ? vault.savedFor(earlier.id) : null;- if (earlier && kept && earlier.secret!.delivery === asked.delivery) return { status: 200, body: { label: asked.label, text: savedSecretText(asked.label, kept) } };- const mismatch = earlier && kept ? earlier.secret!.delivery : undefined;const vm = asked.delivery === "file" ? deps.turnVm(threadId) : undefined;+ const item = asked.replace ? null : vaultStore.usableSecret(asked.label, from.id, asked.delivery);+ if (item) {+ const owner = { botId: from.id, threadId };+ try {+ const saved = asked.delivery === "file" ? { file: vault.mintFile(owner, item.id, item.value, fileHome(from.id, threadId, vm)) } : { ref: vault.mintRef(owner, item.name, item.value) };+ vaultStore.markUsed(item.id);+ return { status: 200, body: { label: asked.label, text: savedSecretText(asked.label, saved) } };+ } catch (error) {+ console.warn(`secret card: could not hand over a saved secret: ${error instanceof Error ? error.message : String(error)}`);+ return { status: 500, body: userError("serverError.secret.notKeptSafely") };+ }+ }+ const path = store.activePath(threadId);const language = deps.threadLanguage?.(threadId);const message = store.appendMessage(threadId, {role: "bot",@@ -590,7 +603,8 @@ export function createSecretCards(deps: SecretCardsDeps) {store.patchMessage(threadId, prior.id, { secret: { ...prior.secret, superseded: true } });deps.followCard(threadId, prior.id, message.id);}- return { status: 201, body: { messageId: message.id, label: asked.label, delivery: asked.delivery, ...(mismatch ? { savedAs: mismatch } : {}) } };+ const savedAs = asked.delivery === "file" && !asked.replace && vaultStore.usableSecret(asked.label, from.id, "ref") ? { savedAs: "ref" } : {};+ return { status: 201, body: { messageId: message.id, label: asked.label, delivery: asked.delivery, ...savedAs } };}return {diff --git a/server/index.ts b/server/index.tsindex 71a9690f74..c6d8a82a4a 100644--- a/server/index.ts+++ b/server/index.ts@@ -440,14 +440,14 @@ import { CalendarCallManager, type CalendarCall } from "./calendar-calls.ts";import { BROWSER_UPLOAD_TOOL, browserRuntimeEnv } from "./browser-runtime.ts";import { BrowserUploadRefusal, uploadableFiles } from "./browser-upload.ts";import { listSignedInSites, signOutOfSites } from "./browser-sites.ts";-import { HeldSecrets, LoginStore } from "./login-store.ts";+import { HeldSecrets, VaultStore } from "./vault-store.ts";import { OnePasswordLogins, onePasswordUnavailable, sdkOnePasswordClient, type OnePasswordSdk } from "./onepassword.ts";import { nativeRequire } from "./data/engine.ts";import { createFillLoginTurn } from "./host/fill-login-turn.ts";import { BotLogins, cardLoginPlace, cardSignInElsewhere, observeSignInPage, type ObservedPage } from "./bot-logins.ts";import { relayFrame } from "./browser-relay.ts";import { browserEvidence, stepContext } from "./browser-steps.ts";-import { parseLoginFields, parseTotpField, createLoginRoutes } from "./routes/logins.ts";+import { parseLoginFields, parseTotpField, createLoginRoutes } from "./routes/logins.ts"; import { createVaultRoutes } from "./routes/vault.ts";import { loginSite } from "../shared/logins.ts";import { browserRestartRefusal } from "./browser-live.ts";import { browserEngineStatus } from "./browser-engine.ts";@@ -733,8 +733,8 @@ if (CLOUD_HOME && Object.keys(CLOUD_SECRETS).length === 0) {}const threadStarters = new ThreadStarters(join(DATA_DIR, "thread-starters.json"));const commandAllowlist = new CommandAllowlistStore(join(DATA_DIR, "command-allowlist.json"));-// Every saved login value is scrubbed from whatever a bot or a transcript can read.-const logins = new LoginStore({ dataDir: DATA_DIR });+// Every value saved in the Vault is scrubbed from whatever a bot or a transcript can read.+const logins = new VaultStore({ dataDir: DATA_DIR });removeRetiredAppFiles(DATA_DIR); const emailService = createEmailService({ dataDir: DATA_DIR, publicOnly: Boolean(CLOUD_HOME), refusal: CLOUD_TEAM ? "Email isn't on a Team Cloud yet: every bot there would read the same mailbox." : null }); addHeldSecretScrubber((text) => emailService.scrub(text));const heldSecrets = new HeldSecrets(logins);addHeldSecretScrubber((text) => heldSecrets.scrub(text));@@ -11542,7 +11542,7 @@ function claimPhoneSecretBotDeletion(botId: string): (() => void) | null {};}-const secretCards = createSecretCards({ store, cfg, botLogins, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode, followCard: (threadId, from, to) => coordinator.followCard(threadId, from, to), threadLanguage, email: { connect: (request, reading) => emailService.connect(request, reading), refusal: () => emailService.status().reason, connected: (address) => { const one = emailService.store.get(address); return Boolean(one && !one.problem); }, sendingProblem: (address) => emailService.sendingProblem(address), account: (address) => emailService.status().accounts.find((one) => one.address.toLowerCase() === address.toLowerCase()), checkOutgoing: (address, fields) => emailService.checkOutgoing(address, fields), profileAddress: () => cfg.profile?.email?.trim() || undefined }, dataDir: DATA_DIR, providerKeysRefused: Boolean(hostedModels), layerFolder: (botId, threadId) => workspaceDir(teamHost.layer(botId, threadId)), turnVm: (threadId) => localVmThreadTargets.get(threadId)?.key });+const secretCards = createSecretCards({ store, cfg, botLogins, vaultStore: logins, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode, followCard: (threadId, from, to) => coordinator.followCard(threadId, from, to), threadLanguage, email: { connect: (request, reading) => emailService.connect(request, reading), refusal: () => emailService.status().reason, connected: (address) => { const one = emailService.store.get(address); return Boolean(one && !one.problem); }, sendingProblem: (address) => emailService.sendingProblem(address), account: (address) => emailService.status().accounts.find((one) => one.address.toLowerCase() === address.toLowerCase()), checkOutgoing: (address, fields) => emailService.checkOutgoing(address, fields), profileAddress: () => cfg.profile?.email?.trim() || undefined }, dataDir: DATA_DIR, providerKeysRefused: Boolean(hostedModels), layerFolder: (botId, threadId) => workspaceDir(teamHost.layer(botId, threadId)), turnVm: (threadId) => localVmThreadTargets.get(threadId)?.key });ROUTES.push(createSecretCardRoutes({ cards: secretCards, phoneSecretSubmissions, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), answerContext: (auth, botId, threadId) => ({ personalCloud: Boolean(CLOUD_PERSONAL), shared: sharedMembership(), owner: (CLOUD_TEAM ? teamOwners.routing.askedPerson(botId, threadId) : null) ?? threadStarters.get(threadId) ?? null, person: auth.kind === "session" ? personKey(auth.session) : null }) }));// By design OpenMausBot never receives a website password: the person signs in where the bot works, and the bot uses that session.@@ -12341,7 +12341,7 @@ ROUTES.push(createBrowserSiteRoutes({signOut: (target, site) => signOutOfSites(target, site),}));ROUTES.push(createBrowserEvidenceRoutes({ evidence: browserEvidence.attach({ onChange: (listener) => store.onChange(listener), threadExists: (id) => Boolean(threadOwner(id)) }), threadExists: (id) => Boolean(threadOwner(id)) }));-ROUTES.push(createLoginRoutes(botLogins.routes((id) => Boolean(store.bot(id)))));+const loginRoutes = botLogins.routes((id) => Boolean(store.bot(id))); ROUTES.push(createLoginRoutes(loginRoutes), createVaultRoutes({ logins: loginRoutes, secrets: logins }));ROUTES.push(createUsageRoutes({dataDir: DATA_DIR, prices: operatorPrices,budget: () => spendState(cfg, DATA_DIR),diff --git a/server/login-handoff.test.ts b/server/login-handoff.test.tsindex 99be273c0c..c518f5d0ab 100644--- a/server/login-handoff.test.ts+++ b/server/login-handoff.test.ts@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { loginFingerprints } from "./cloud-send-verify.ts";import { LOGIN_HANDOFF_REQUEST, LOGIN_HANDOFF_RESULT, ONE_PASSWORD_DEAD_HERE, receiveLoginHandoff, totpAddress, type ConnectionHandoffAnswer, type LoginHandoffResult } from "./login-handoff.ts";-import { LoginStore } from "./login-store.ts";+import { VaultStore } from "./vault-store.ts";import { ONE_PASSWORD_MALFORMED, ONE_PASSWORD_REFUSED } from "./onepassword.ts";import { parseTotpKey } from "./totp.ts";@@ -18,7 +18,7 @@ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: trufunction setup(onePasswordProblem?: () => string | undefined) {const dir = mkdtempSync(join(tmpdir(), "omb-login-handoff-"));dirs.push(dir);- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });const posted: LoginHandoffResult[] = [];const ask = (message: unknown) => receiveLoginHandoff(message, store, (reply) => { posted.push(reply); return true; }, onePasswordProblem);return { store, posted, ask };diff --git a/server/login-handoff.ts b/server/login-handoff.tsindex fa50d93a02..61d79b5630 100644--- a/server/login-handoff.ts+++ b/server/login-handoff.ts@@ -4,7 +4,7 @@// Nothing here is an HTTP answer, a log line or a chat message, and nothing is kept.import type { LoginBots } from "../shared/logins.ts";import { loginFingerprints, VERIFY_NONCE } from "./cloud-send-verify.ts";-import type { LoginStore } from "./login-store.ts";+import type { VaultStore } from "./vault-store.ts";import { ONE_PASSWORD_MALFORMED, ONE_PASSWORD_REFUSED } from "./onepassword.ts";import type { TotpKey } from "./totp.ts";@@ -73,7 +73,7 @@ function parse(raw: unknown): { requestId: string; what: Ask } | null {return null;}-type HandoffStore = Pick<LoginStore, "changes" | "get" | "onePasswordToken" | "onePasswordGrants">;+type HandoffStore = Pick<VaultStore, "changes" | "get" | "onePasswordToken" | "onePasswordGrants">;/** This computer's own 1Password problem, from its last read of the vaults (OnePasswordLogins.status().error). */type OnePasswordProblem = () => string | undefined;diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 2787904536..0b01c579c1 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -166,6 +166,7 @@ describe("scopes", () => {["POST", "/api/bots/x/sign-in-cards/m/provide"], ["POST", "/api/browser-engine/install"],["GET", "/api/logins"], ["POST", "/api/logins"], ["PATCH", "/api/logins/l1"], ["DELETE", "/api/logins/l1"],["POST", "/api/logins/1password"], ["POST", "/api/logins/1password/refresh"], ["DELETE", "/api/logins/1password"],+ ["GET", "/api/vault"], ["POST", "/api/vault/secrets"], ["PATCH", "/api/vault/secrets/s1"], ["DELETE", "/api/vault/secrets/s1"],["POST", "/api/threads/t/messages/m/app"], ["GET", "/api/bots/x/apps/m/rpc"], ["POST", "/api/bots/x/apps/m/delete"],["POST", "/api/bots/x/apps/m/rpc/extra"], ["DELETE", "/api/bots/x/apps/m/context"],["PATCH", "/api/logins/1password/vaults/v1"], ["GET", "/api/bots/x/sign-in-cards/m/done"],diff --git a/server/routes/cloud-send.ts b/server/routes/cloud-send.tsindex 8525875a90..02236da9ec 100644--- a/server/routes/cloud-send.ts+++ b/server/routes/cloud-send.ts@@ -18,7 +18,7 @@ import { cloudSendSummary, partHash, type CloudSendSources } from "../cloud-sendimport { cloudSendChatsRoute, type CloudSendChatsDeps } from "../cloud-send-chats.ts";import { loginFingerprints, VERIFY_NONCE } from "../cloud-send-verify.ts";import type { AppConfig } from "../config.ts";-import type { LoginStore } from "../login-store.ts";+import type { VaultStore } from "../vault-store.ts";import type { MoveAutomations } from "../move-freeze.ts";import { threadHeads } from "../message-db.ts";import type { LineLanguage } from "../server-lines.ts";@@ -29,7 +29,7 @@ import { PASS, type RouteHandler } from "./table.ts";export interface CloudSendRouteDeps extends Pick<CloudSendSources, "appVersion" | "bots" | "skills"> {messagesTail(threadId: string, limit: number): { messages: ReadonlyArray<{ role: string; text?: string }>; hasMore: boolean };- logins: Pick<LoginStore, "changes" | "get" | "onePasswordConnectedAt" | "onePasswordGrants" | "onePasswordToken">;+ logins: Pick<VaultStore, "changes" | "get" | "onePasswordConnectedAt" | "onePasswordGrants" | "onePasswordToken">;config(): Pick<AppConfig, "profile" | "language">;lineLanguage?: LineLanguage;chats?: CloudSendChatsDeps;diff --git a/server/routes/logins.test.ts b/server/routes/logins.test.tsindex 125f727ae5..b5c22c79f2 100644--- a/server/routes/logins.test.ts+++ b/server/routes/logins.test.ts@@ -7,7 +7,7 @@ import { afterEach, describe, expect, it } from "vitest";import { BotLogins } from "../bot-logins.ts";import { json, readBody } from "../harness/http.ts";-import { LoginStore } from "../login-store.ts";+import { VaultStore } from "../vault-store.ts";import { ONE_PASSWORD_REFUSED, OnePasswordLogins, sdkOnePasswordClient } from "../onepassword.ts";import { fakeOnePasswordSdk } from "../testing/fake-onepassword.ts";import { requiredScope, type RequestAuth } from "../request-auth.ts";@@ -30,7 +30,7 @@ afterEach(async () => {async function serve() {const dir = mkdtempSync(join(tmpdir(), "omb-login-routes-"));dirs.push(dir);- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });const { sdk } = fakeOnePasswordSdk({ token: TOKEN, vaults: { v1: { title: "Shared with OMB", items: [{ id: "i1", title: "Example", urls: ["https://vault.example.com"], username: "vault-user", password: VAULT_PASSWORD },] } } });diff --git a/server/routes/logins.ts b/server/routes/logins.tsindex 7f2714bcf8..3cfd004bb8 100644--- a/server/routes/logins.ts+++ b/server/routes/logins.ts@@ -1,6 +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 type { LoginPatch, NewLogin } from "../login-store.ts";+import type { LoginPatch, NewLogin } from "../vault-store.ts";import { parseTotpKey, type TotpKey } from "../totp.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -59,7 +59,7 @@ export function parseLoginFields(body: Record<string, unknown>, options: { passwreturn { ok: true, value: { ...(username === undefined ? {} : { username: username.trim() }), ...(password === undefined ? {} : { password }) } };}-function parseBots(value: unknown, exists: (id: string) => boolean): Parsed<LoginBots | undefined> {+export function parseBots(value: unknown, exists: (id: string) => boolean): Parsed<LoginBots | undefined> {if (value === undefined) return { ok: true, value: undefined };if (value === "all") return { ok: true, value: "all" };if (!Array.isArray(value) || value.length > 500 || !value.every((id) => typeof id === "string" && ID.test(id) && exists(id))) {@@ -68,7 +68,7 @@ function parseBots(value: unknown, exists: (id: string) => boolean): Parsed<Logireturn { ok: true, value: [...new Set(value as string[])] };}-function isJson(req: { headers: Record<string, string | string[] | undefined> }): boolean {+export function isJson(req: { headers: Record<string, string | string[] | undefined> }): boolean {return String(req.headers["content-type"] ?? "").split(";", 1)[0]!.trim().toLowerCase() === "application/json";}diff --git a/server/routes/vault.test.ts b/server/routes/vault.test.tsnew file mode 100644index 0000000000..57216628ee--- /dev/null+++ b/server/routes/vault.test.ts@@ -0,0 +1,94 @@+import { mkdtempSync, rmSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { BotLogins } from "../bot-logins.ts";+import { json, readBody } from "../harness/http.ts";+import { OnePasswordLogins } from "../onepassword.ts";+import type { RequestAuth } from "../request-auth.ts";+import { VaultStore } from "../vault-store.ts";+import { createLoginRoutes } from "./logins.ts";+import { dispatchRoutes } from "./table.ts";+import { createVaultRoutes, VAULT_ERRORS } from "./vault.ts";++const VALUE = "sk_test_fake-route-secret-1";+const NEW_VALUE = "sk_test_fake-route-secret-2";++const servers: Server[] = [];+const dirs: string[] = [];+afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++async function serve() {+ const dir = mkdtempSync(join(tmpdir(), "omb-vault-routes-"));+ dirs.push(dir);+ const store = new VaultStore({ dataDir: dir });+ const onePassword = new OnePasswordLogins({ token: () => null, grants: () => ({}), connect: async () => { throw new Error("not in this test"); } });+ const logins = new BotLogins(store, onePassword).routes((id) => ["pepper", "quill"].includes(id));+ const routes = [createLoginRoutes(logins), createVaultRoutes({ logins, secrets: store })];+ const answers: string[] = [];+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const auth = { kind: "loopback", scopes: ["admin"] } as unknown as RequestAuth;+ if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, {});+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ const call = async (method: string, path: string, body?: unknown, type = "application/json") => {+ const response = await fetch(base + path, { method, headers: { "content-type": type }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ const text = await response.text();+ answers.push(text);+ return { status: response.status, body: JSON.parse(text), cache: response.headers.get("cache-control") };+ };+ return { store, call, answers };+}++describe("the Vault routes", () => {+ it("add, list, change and delete a secret beside the logins, and never return its value", async () => {+ const { store, call, answers } = await serve();+ await call("POST", "/api/logins", { site: "example.com", username: "alice", password: "fake-route-login-pass" });+ const added = await call("POST", "/api/vault/secrets", { name: " Stripe secret key ", value: ` ${VALUE} ` });+ expect(added).toMatchObject({ status: 201, body: { secret: { name: "Stripe secret key", source: "settings", bots: "all" } } });+ const id = added.body.secret.id;+ expect(store.usableSecret("Stripe secret key", "pepper", "file")?.value).toBe(VALUE);++ const listed = await call("GET", "/api/vault");+ expect(listed).toMatchObject({ status: 200, cache: "no-store" });+ expect(listed.body.logins).toMatchObject([{ site: "example.com", username: "alice" }]);+ expect(listed.body.secrets).toEqual([added.body.secret]);+ expect(listed.body.onePassword).toEqual({ connected: false });++ expect((await call("PATCH", `/api/vault/secrets/${id}`, { value: NEW_VALUE, bots: ["quill"] })).body.secret).toMatchObject({ bots: ["quill"], name: "Stripe secret key" });+ expect(store.usableSecret("Stripe secret key", "quill", "ref")?.value).toBe(NEW_VALUE);+ expect(store.usableSecret("Stripe secret key", "pepper", "ref")).toBeNull();+ expect((await call("DELETE", `/api/vault/secrets/${id}`)).body).toEqual({ ok: true });+ expect((await call("DELETE", `/api/vault/secrets/${id}`)).status).toBe(404);+ expect(store.listSecrets()).toEqual([]);+ for (const answer of answers) {+ expect(answer).not.toContain(VALUE);+ expect(answer).not.toContain(NEW_VALUE);+ expect(answer).not.toContain("fake-route-login-pass");+ }+ });++ it("take JSON only, and refuse an empty name or value, bots that don't exist and other methods", async () => {+ const { store, call } = await serve();+ expect((await call("POST", "/api/vault/secrets", { name: "K", value: VALUE }, "text/plain")).status).toBe(415);+ expect(await call("POST", "/api/vault/secrets", { name: " ", value: VALUE })).toMatchObject({ status: 400, body: { error: VAULT_ERRORS.name } });+ expect(await call("POST", "/api/vault/secrets", { name: "K", value: " " })).toMatchObject({ status: 400, body: { error: VAULT_ERRORS.value } });+ expect(await call("POST", "/api/vault/secrets", { name: "K", value: "x".repeat(4_097) })).toMatchObject({ status: 400, body: { error: VAULT_ERRORS.value } });+ expect((await call("POST", "/api/vault/secrets", { name: "K", value: VALUE, bots: ["ghost"] })).status).toBe(400);+ const id = (await call("POST", "/api/vault/secrets", { name: "K", value: VALUE })).body.secret.id;+ expect((await call("PATCH", `/api/vault/secrets/${id}`, { value: "" })).status).toBe(400);+ expect((await call("PATCH", "/api/vault/secrets/missing", { name: "L" })).status).toBe(404);+ expect((await call("POST", "/api/vault")).status).toBe(405);+ expect((await call("PUT", `/api/vault/secrets/${id}`, {})).status).toBe(405);+ expect(store.secretValues()).toEqual([VALUE]);+ });+});diff --git a/server/routes/vault.ts b/server/routes/vault.tsnew file mode 100644index 0000000000..bf1e18c9d9--- /dev/null+++ b/server/routes/vault.ts@@ -0,0 +1,77 @@+// No answer ever carries a saved value: a saved secret is only ever replaced.+import { SECRET_VALUE_MAX_BYTES, VAULT_SECRET_NAME_MAX } from "../../shared/vault.ts";+import type { VaultStore } from "../vault-store.ts";+import { isJson, parseBots, type LoginRouteDeps } from "./logins.ts";+import { PASS, type RouteHandler } from "./table.ts";++export interface VaultRouteDeps {+ logins: Pick<LoginRouteDeps, "list" | "botExists" | "onePassword">;+ secrets: Pick<VaultStore, "listSecrets" | "saveSecret" | "updateSecret" | "removeSecret">;+}++const SECRETS = "/api/vault/secrets";+const ID = /^[\w-]{1,128}$/u;++export const VAULT_ERRORS = {+ name: `Give the secret a name of at most ${VAULT_SECRET_NAME_MAX} characters.`,+ value: `Enter the secret. It can be at most ${SECRET_VALUE_MAX_BYTES} bytes.`,+} as const;++type Parsed<T> = { ok: true; value: T } | { ok: false; error: string };++/** Absent leaves it. */+function parseName(raw: unknown): Parsed<string | undefined> {+ if (raw === undefined) return { ok: true, value: undefined };+ const name = typeof raw === "string" ? [...raw].map((ch) => (ch.charCodeAt(0) < 0x20 || ch === "\u007f" ? " " : ch)).join("").trim() : "";+ return name && name.length <= VAULT_SECRET_NAME_MAX ? { ok: true, value: name } : { ok: false, error: VAULT_ERRORS.name };+}++function parseValue(raw: unknown): Parsed<string | undefined> {+ if (raw === undefined) return { ok: true, value: undefined };+ const value = typeof raw === "string" ? raw.trim() : "";+ return value && Buffer.byteLength(value) <= SECRET_VALUE_MAX_BYTES ? { ok: true, value } : { ok: false, error: VAULT_ERRORS.value };+}++export function createVaultRoutes(deps: VaultRouteDeps): RouteHandler {+ return async ({ req, res, path, method, json, readBody }) => {+ if (path !== "/api/vault" && !path.startsWith("/api/vault/")) return PASS;+ res.setHeader("cache-control", "no-store");+ if (path === "/api/vault") {+ if (method !== "GET") return json(res, 405, { error: "method not allowed" });+ return json(res, 200, { logins: [...deps.logins.list(), ...deps.logins.onePassword.list()], secrets: deps.secrets.listSecrets(), onePassword: deps.logins.onePassword.status() });+ }+ if (path !== SECRETS && !path.startsWith(`${SECRETS}/`)) return json(res, 404, { error: "not found" });+ // 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" });+ if (path === SECRETS) {+ if (method !== "POST") return json(res, 405, { error: "method not allowed" });+ const body = await readBody(req, SECRET_VALUE_MAX_BYTES * 4);+ if (!body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "send the secret as a JSON object" });+ const name = parseName(body.name);+ if (!name.ok || name.value === undefined) return json(res, 400, { error: VAULT_ERRORS.name });+ const value = parseValue(body.value);+ if (!value.ok || value.value === undefined) return json(res, 400, { error: VAULT_ERRORS.value });+ const bots = parseBots(body.bots ?? "all", deps.logins.botExists);+ if (!bots.ok) return json(res, 400, { error: bots.error });+ return json(res, 201, { secret: deps.secrets.saveSecret({ name: name.value, value: value.value, source: "settings", bots: bots.value ?? "all" }) });+ }+ const id = path.slice(`${SECRETS}/`.length);+ if (!ID.test(id)) return json(res, 404, { error: "no such secret" });+ if (method === "DELETE") return deps.secrets.removeSecret(id) ? json(res, 200, { ok: true }) : json(res, 404, { error: "no such secret" });+ if (method !== "PATCH") return json(res, 405, { error: "method not allowed" });+ const body = await readBody(req, SECRET_VALUE_MAX_BYTES * 4);+ if (!body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "send the change as a JSON object" });+ const name = parseName(body.name);+ if (!name.ok) return json(res, 400, { error: name.error });+ const value = parseValue(body.value);+ if (!value.ok) return json(res, 400, { error: value.error });+ const bots = parseBots(body.bots, deps.logins.botExists);+ if (!bots.ok) return json(res, 400, { error: bots.error });+ const secret = deps.secrets.updateSecret(id, {+ ...(name.value === undefined ? {} : { name: name.value }),+ ...(value.value === undefined ? {} : { value: value.value }),+ ...(bots.value === undefined ? {} : { bots: bots.value }),+ });+ return secret ? json(res, 200, { secret }) : json(res, 404, { error: "no such secret" });+ };+}diff --git a/server/secret-requests.e2e.test.ts b/server/secret-requests.e2e.test.tsindex fa5902d44a..b890d60f57 100644--- a/server/secret-requests.e2e.test.ts+++ b/server/secret-requests.e2e.test.ts@@ -1,7 +1,8 @@// A real Cloud home and its agents tools: a bot asks for two secrets OpenMausBot does not keep, the person types each// into its card, and the bot uses them. Each recognisable value is then searched for in everything the server wrote (the// data folder, its events, transcripts, usage spans and logs), every answer it gave, every tool result and its own log.-// The file secret is found only in its private file; the ref secret only in the MCP server settings it was saved into.+// Both are saved to the Vault for the bot, sealed, so asking again needs no card. The file secret is found only in its+// private files; the ref secret only in the MCP server settings it was saved into.import { randomBytes } from "node:crypto";import { type ChildProcess, spawn } from "node:child_process";import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";@@ -151,7 +152,7 @@ it("keeps a file secret and a ref secret out of every record, and the bot uses eexpect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "Set up Stripe test charges and Notion's MCP." })).status).toBe(202);});const listed = (await tools.list()).tools.find((tool: any) => tool.name === "request_credential");- expect(Object.keys(listed.inputSchema.properties)).toEqual(["credential_id", "address", "label", "reason", "placeholder", "delivery"]);+ expect(Object.keys(listed.inputSchema.properties)).toEqual(["credential_id", "address", "label", "reason", "placeholder", "delivery", "replace"]);expect(listed.inputSchema.properties.credential_id.enum).toEqual(expect.arrayContaining(["composioApiKey", "openaiApiKey", "anthropicApiKey"]));const cards = async () => (await api("GET", `/api/threads/${bot.threadId}/messages`)).body.messages.filter((message: any) => message.kind === "secret");const save = (cardId: string, value: unknown) => api("POST", `/api/bots/${bot.id}/secret-cards/${cardId}/save`, { threadId: bot.threadId, value });@@ -162,13 +163,16 @@ it("keeps a file secret and a ref secret out of every record, and the bot uses eexpect(askedFile).toEqual({ isError: false, text: expect.stringMatching(/^A secure card for Stripe secret key is now in this conversation/u) });const fileCard = (await cards()).at(-1);expect(fileCard.secret).toMatchObject({ target: "customSecret", label: "Stripe secret key", placeholder: "sk_test_…", helpUrl: "", delivery: "file", reason: "To create test charges." });- expect(fileCard.secret.description).toBe("To create test charges. Ledger's commands can read it from a private file for 24 hours; it is never added to chat.");+ expect(fileCard.secret.description).toBe("To create test charges. Ledger's commands can read it from a private file for 24 hours; it is never added to chat. OpenMausBot keeps it safely, so Ledger can use it again without asking you.");expect(await save(fileCard.id, "")).toMatchObject({ status: 400 });expect(await save(fileCard.id, FILE_CANARY)).toMatchObject({ status: 200, body: { provided: true } });expect(await save(fileCard.id, FILE_CANARY)).toMatchObject({ status: 409, body: { error: "this secret was already saved" } });+ const cardFile = join(home, ".openmausbot", "workspaces", bot.id, ".openmausbot-secrets", bot.threadId, fileCard.id);+ expect(readFileSync(cardFile, "utf8")).toBe(FILE_CANARY);const fileText = (await tools.call("request_credential", { label: "Stripe secret key", reason: "To create test charges.", delivery: "file" })).text;- const secretFile = join(home, ".openmausbot", "workspaces", bot.id, ".openmausbot-secrets", bot.threadId, fileCard.id);- expect(fileText).toContain(`saved Stripe secret key to the file ${secretFile}`);+ expect((await cards()).at(-1).id, "the Vault answers with no card").toBe(fileCard.id);+ const secretFile = /saved Stripe secret key to the file (\S+vault-[\w-]+)\./u.exec(fileText)?.[1] ?? "";+ expect(secretFile.startsWith(dirname(cardFile)), fileText).toBe(true);expect(fileText).toContain("never print, echo, log or copy it anywhere else");expect(readFileSync(secretFile, "utf8")).toBe(FILE_CANARY);expect(statSync(secretFile).mode & 0o777).toBe(0o600);@@ -176,7 +180,7 @@ it("keeps a file secret and a ref secret out of every record, and the bot uses e// A one-use secretRef for mcp_server.await tools.call("request_credential", { label: "Notion key", reason: "For Notion's MCP server.", delivery: "ref" });const refCard = (await cards()).at(-1);- expect(refCard.secret.description).toBe("For Notion's MCP server. Ledger gets a one-use reference for OpenMausBot's own tools and never sees it.");+ expect(refCard.secret.description).toBe("For Notion's MCP server. Ledger gets a one-use reference for OpenMausBot's own tools and never sees it. OpenMausBot keeps it safely, so Ledger can use it again without asking you.");expect(await save(refCard.id, REF_CANARY)).toMatchObject({ status: 200, body: { provided: true } });const refText = (await tools.call("request_credential", { label: "Notion key", reason: "For Notion's MCP server.", delivery: "ref" })).text;const ref = /secret-ref:[0-9a-f]{32}/u.exec(refText)?.[0];@@ -199,8 +203,8 @@ it("keeps a file secret and a ref secret out of every record, and the bot uses e// A bot that disobeys and writes a value into its memory still leaves it out of every record.expect((await tools.call("memory_update", { action: "append", text: `Stripe test key: ${FILE_CANARY}` })).isError).toBe(false);- // Only the secret file holds one value, and only the MCP server's settings the other.- expect(filesHolding(home, FILE_CANARY)).toEqual([relative(home, secretFile)]);+ // Only the secret files hold one value, and only the MCP server's settings the other: the Vault keeps both sealed.+ expect(filesHolding(home, FILE_CANARY).sort()).toEqual([relative(home, cardFile), relative(home, secretFile)].sort());expect(filesHolding(home, REF_CANARY)).toEqual([join(".openmausbot", "config.json")]);for (const where of [...said, log]) {expect(where).not.toContain(FILE_CANARY);diff --git a/server/secret-vault.test.ts b/server/secret-vault.test.tsindex 6ec80106be..3da4bfb773 100644--- a/server/secret-vault.test.ts+++ b/server/secret-vault.test.ts@@ -58,6 +58,20 @@ describe("secretRef", () => {});});+ it("mints a ref with no card behind it under the same rules: one use, this bot and conversation, an hour", () => {+ const vault = new SecretVault(clock);+ const first = vault.mintRef(ATLAS, "Notion key", "ntn_canary_value");+ const second = vault.mintRef(ATLAS, "Notion key", "ntn_canary_value");+ expect(second).not.toBe(first);+ expect(vault.redeem({ env: { K: first } }, { botId: "pixel", threadId: "thread-1" }, MCP, "env").ok).toBe(false);+ const used = vault.redeem({ env: { K: first } }, ATLAS, MCP, "env");+ expect(used.ok && used.value).toEqual({ env: { K: "ntn_canary_value" } });+ if (used.ok) used.commit();+ expect(vault.redeem({ env: { K: first } }, ATLAS, MCP, "env").ok).toBe(false);+ now += SECRET_REF_TTL_MS;+ expect(vault.redeem({ env: { K: second } }, ATLAS, MCP, "env").ok).toBe(false);+ });+it("names an unknown ref, a ref outside the allowed fields and a secret file path plainly", () => {const vault = new SecretVault(clock);const ref = vault.saveRef(ATLAS, "card-1", "Notion key", "ntn_canary_value");@@ -140,6 +154,24 @@ posix("secret files", () => {expect(vault.savedFor("card-1")).toBeNull();});+ it("writes a Vault item's file once per conversation, replacing it, and keeps it a day from its last write", () => {+ const vault = new SecretVault(clock);+ const shown = vault.mintFile(ATLAS, "item-1", "sk_old", home());+ const file = join(root, "workspaces", "atlas", SECRET_FOLDER, "thread-1", "vault-item-1");+ expect(shown).toBe(file);+ now += SECRET_FILE_TTL_MS / 2;+ expect(vault.mintFile(ATLAS, "item-1", "sk_new", home())).toBe(file);+ expect(readFileSync(file, "utf8")).toBe("sk_new");+ expect(statSync(file).mode & 0o777).toBe(0o600);+ const noCard = () => null;+ now += SECRET_FILE_TTL_MS - 1;+ vault.sweep([join(root, "workspaces", "atlas")], noCard, () => true);+ expect(existsSync(file)).toBe(true);+ now += 1;+ vault.sweep([join(root, "workspaces", "atlas")], noCard, () => true);+ expect(existsSync(file)).toBe(false);+ });+it("removes a link planted in the secrets folder without following it", () => {const vault = new SecretVault(clock);const keep = join(root, "keep");diff --git a/server/secret-vault.ts b/server/secret-vault.tsindex 00d94ad1b8..196e6e063a 100644--- a/server/secret-vault.ts+++ b/server/secret-vault.ts@@ -1,4 +1,4 @@-// Values a person typed into a bot's card for a secret OpenMausBot does not keep itself.+// How a bot is handed a secret from a card or the Vault without seeing it.// Security: a `ref` value stays in this process's memory, behind a one-use reference bound to the asking bot and// conversation that only OpenMausBot's own tools accept. A `file` value goes to an owner-only file in a private folder// of that bot's own workspace (or the Local VM workspace its turn runs in); nothing that syncs, backs up, moves, links,@@ -8,16 +8,16 @@ import { randomBytes } from "node:crypto";import { chmodSync, closeSync, constants, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, rmSync, writeSync } from "node:fs";import { join } from "node:path";-import { secretForms } from "./login-store.ts";+import { SECRET_VALUE_MAX_BYTES } from "../shared/vault.ts";+import { secretForms } from "./vault-store.ts";import { HELD_SECRET_MASK } from "./redact.ts";import { inSecretFolder, SECRET_FOLDER } from "./secret-folder.ts";-export { inSecretFolder, SECRET_FOLDER };+export { inSecretFolder, SECRET_FOLDER, SECRET_VALUE_MAX_BYTES };/** From saving: room for a resume queued behind other work and the tool call after it, short enough that a ref the bot* never used is soon gone. A restart forgets every unused ref. */export const SECRET_REF_TTL_MS = 60 * 60 * 1000;export const SECRET_FILE_TTL_MS = 24 * 60 * 60 * 1000;-export const SECRET_VALUE_MAX_BYTES = 4_096;const REF = /secret-ref:[0-9a-f]{32}/g;const ID = /^[\w-]{1,128}$/;@@ -78,6 +78,8 @@ export class SecretVault {private readonly refs = new Map<string, RefEntry>();private readonly used = new Map<string, number>();private readonly byCard = new Map<string, { ref: string } | { file: string; until: number }>();+ /** "<thread>/<file name>" → until when, for files made from a Vault item rather than a card. */+ private readonly minted = new Map<string, number>();private held: Array<{ forms: string[]; until: number }> = [];private readonly now: () => number;@@ -89,10 +91,16 @@ export class SecretVault {saveRef(owner: SecretOwner, messageId: string, label: string, value: string): string {const existing = this.savedFor(messageId);if (existing && "ref" in existing) return existing.ref;+ const ref = this.mintRef(owner, label, value);+ this.byCard.set(messageId, { ref });+ return ref;+ }++ /** A new one-use ref with no card behind it, for a value the Vault holds. */+ mintRef(owner: SecretOwner, label: string, value: string): string {const ref = `secret-ref:${randomBytes(16).toString("hex")}`;const now = this.now();this.refs.set(ref, { owner: { ...owner }, label, value, expiresAt: now + SECRET_REF_TTL_MS });- this.byCard.set(messageId, { ref });this.hold(value, now + SECRET_FILE_TTL_MS);return ref;}@@ -100,13 +108,28 @@ export class SecretVault {/** Writes the card's value to `<home>/.openmausbot-secrets/<thread>/<card>` (0600, in 0700 folders); returns its path* as the bot's commands see it. */saveFile(owner: SecretOwner, messageId: string, value: string, home: SecretFileHome): string {- if (!ID.test(owner.threadId) || !ID.test(messageId)) throw new Error("invalid conversation or card id");+ const saved = this.writeFile(owner, messageId, value, home);+ this.byCard.set(messageId, saved);+ return saved.file;+ }++ /** Writes a Vault item's value to `<home>/.openmausbot-secrets/<thread>/vault-<item>`, replacing that conversation's+ * earlier copy, for another 24 hours. */+ mintFile(owner: SecretOwner, itemId: string, value: string, home: SecretFileHome): string {+ const name = `vault-${itemId}`;+ const saved = this.writeFile(owner, name, value, home);+ this.minted.set(`${owner.threadId}/${name}`, saved.until);+ return saved.file;+ }++ private writeFile(owner: SecretOwner, name: string, value: string, home: SecretFileHome): { file: string; until: number } {+ if (!ID.test(owner.threadId) || !ID.test(name)) throw new Error("invalid conversation or file name");privateFolder(home.host, "all");const folder = join(home.host, SECRET_FOLDER);privateFolder(folder, "one");const threadFolder = join(folder, owner.threadId);privateFolder(threadFolder, "one");- const file = join(threadFolder, messageId);+ const file = join(threadFolder, name);rmSync(file, { force: true });const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;const fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow, 0o600);@@ -116,11 +139,10 @@ export class SecretVault {} finally {closeSync(fd);}- const shown = home.shown === home.host ? file : [home.shown, SECRET_FOLDER, owner.threadId, messageId].join("/");+ const shown = home.shown === home.host ? file : [home.shown, SECRET_FOLDER, owner.threadId, name].join("/");const until = this.now() + SECRET_FILE_TTL_MS;- this.byCard.set(messageId, { file: shown, until });this.hold(value, until);- return shown;+ return { file: shown, until };}/** What this card's save gave the bot, while it still works; null after a restart, its use or its expiry. */@@ -193,7 +215,8 @@ export class SecretVault {};}- /** Removes every secret file past its day or whose card is gone, and every value whose conversation is gone.+ /** Removes every secret file past its day, or whose card is gone and no Vault item made it, and every value whose+ * conversation is gone.* `savedAt` reads the card, so touching a file never keeps it longer. */sweep(bases: readonly string[], savedAt: (threadId: string, messageId: string) => number | null, threadExists: (threadId: string) => boolean): void {const now = this.now();@@ -221,7 +244,8 @@ export class SecretVault {for (const card of readdirSync(threadFolder)) {const file = join(threadFolder, card);const at = ID.test(card) ? savedAt(thread, card) : null;- if (at === null || now - at >= SECRET_FILE_TTL_MS || !lstatSync(file).isFile()) rmSync(file, { recursive: true, force: true });+ const live = at === null ? (this.minted.get(`${thread}/${card}`) ?? 0) > now : now - at < SECRET_FILE_TTL_MS;+ if (!live || !lstatSync(file).isFile()) rmSync(file, { recursive: true, force: true });}if (readdirSync(threadFolder).length === 0) rmSync(threadFolder, { recursive: true, force: true });} catch {@@ -231,6 +255,7 @@ export class SecretVault {}for (const [ref, entry] of this.refs) if (entry.expiresAt <= now || !threadExists(entry.owner.threadId)) this.refs.delete(ref);for (const [ref, at] of this.used) if (now - at >= SECRET_FILE_TTL_MS) this.used.delete(ref);+ for (const [file, until] of this.minted) if (until <= now) this.minted.delete(file);for (const [card, saved] of this.byCard) if (("until" in saved && saved.until <= now) || ("ref" in saved && !this.refs.has(saved.ref))) this.byCard.delete(card);this.held = this.held.filter((entry) => entry.until > now);}diff --git a/server/login-store.test.ts b/server/vault-store.test.tssimilarity index 70%rename from server/login-store.test.tsrename to server/vault-store.test.tsindex 169d3c5813..ce8cdc7882 100644--- a/server/login-store.test.ts+++ b/server/vault-store.test.ts@@ -7,7 +7,7 @@ import { z } from "zod";import { loginPlace } from "../shared/logins.ts";import { addHeldSecretScrubber, redactSecretsInText } from "../shared/redact.ts";import { decryptBrowserState, encryptBrowserState } from "./browser-sites.ts";-import { HeldSecrets, LOGINS_FILE, LOGINS_KEY_FILE, LoginStore, secretForms } from "./login-store.ts";+import { HeldSecrets, LOGINS_FILE, LOGINS_KEY_FILE, VaultStore, secretForms } from "./vault-store.ts";import { parseTotpKey } from "./totp.ts";// Obvious fakes only: nothing here is anyone's real login.@@ -32,12 +32,12 @@ const previousRelease = z.object({describe("the saved logins store", () => {it("round-trips a login and keeps nothing readable on disk", () => {- const store = new LoginStore({ dataDir: dir, now: () => 1_000 });+ const store = new VaultStore({ dataDir: dir, now: () => 1_000 });const saved = store.create({ ...at("accounts.example.com"), username: "[email protected]", password: PASSWORD, totp: TOTP, source: "settings", bots: "all" });expect(saved).toEqual({ id: saved.id, site: "example.com", hosts: ["accounts.example.com"], exactHost: false, username: "[email protected]", hasTotp: true, source: "settings", bots: "all", createdAt: 1_000 });expect(JSON.stringify(saved)).not.toContain(PASSWORD);- const reopened = new LoginStore({ dataDir: dir });+ const reopened = new VaultStore({ dataDir: dir });expect(reopened.list()).toEqual([saved]);expect(reopened.usableFor("accounts.example.com", "any-bot")[0]).toMatchObject({ password: PASSWORD, totp: TOTP });@@ -53,7 +53,7 @@ describe("the saved logins store", () => {});it("makes no key and no file until something is saved", () => {- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });expect(store.list()).toEqual([]);expect(store.secretValues()).toEqual([]);expect(readdirSync(dir)).toEqual([]);@@ -61,9 +61,9 @@ describe("the saved logins store", () => {it("opens nothing, and says so once, when the key does not fit", () => {const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);- new LoginStore({ dataDir: dir }).create({ ...at("example.com"), username: "a", password: PASSWORD, source: "card", bots: ["b1"] });+ new VaultStore({ dataDir: dir }).create({ ...at("example.com"), username: "a", password: PASSWORD, source: "card", bots: ["b1"] });writeFileSync(join(dir, LOGINS_KEY_FILE), `${"0".repeat(64)}\n`);- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });expect(store.list()).toEqual([]);expect(store.list()).toEqual([]);expect(warn).toHaveBeenCalledTimes(1);@@ -78,7 +78,7 @@ describe("the saved logins store", () => {{ id: "old-2", host: "alice.github.io", username: "alice", password: "fake-pages-pass", source: "settings", bots: "all", createdAt: 6, updatedAt: 6 },{ id: "old-3", host: "login.example.org", username: "ops", password: "fake-org-pass", source: "settings", bots: "all", createdAt: 7, updatedAt: 7 },], onePassword: { token: "ops_fake-token", connectedAt: 7 } }), KEY), { mode: 0o600 });- const store = new LoginStore({ dataDir: dir, now: () => 9 });+ const store = new VaultStore({ dataDir: dir, now: () => 9 });expect(store.list().map(({ id, site, hosts, exactHost }) => ({ id, site, hosts, exactHost }))).toEqual([{ id: "old-2", site: "alice.github.io", hosts: ["alice.github.io"], exactHost: false },{ id: "old-1", site: "example.com", hosts: ["example.com"], exactHost: false },@@ -93,11 +93,11 @@ describe("the saved logins store", () => {const written = JSON.parse(decryptBrowserState(readFileSync(join(dir, LOGINS_FILE)), KEY));expect(written.logins[0]).toMatchObject({ id: "old-1", host: "example.com", site: "example.com", hosts: ["example.com"], exactHost: false, lastUsedAt: 9 });expect(previousRelease.parse(written).logins.map((login) => login.host)).toEqual(["example.com", "alice.github.io", "login.example.org"]);- expect(new LoginStore({ dataDir: dir }).onePasswordToken()).toBe("ops_fake-token");+ expect(new VaultStore({ dataDir: dir }).onePasswordToken()).toBe("ops_fake-token");});it("fills a login on its site and its sign-in hosts, for the bots allowed", () => {- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });store.create({ ...at("example.com", ["example.com", "login.microsoftonline.com"]), username: "card-user", password: PASSWORD, source: "card", bots: ["pepper"] });store.create({ ...at("example.com"), username: "shared", password: "fake-other-1", source: "settings", bots: "all" });store.create({ ...at("acme.okta.com", [], true), username: "tenant", password: "fake-okta-1", source: "settings", bots: "all" });@@ -113,7 +113,7 @@ describe("the saved logins store", () => {});it("saving the same account again replaces the password, adds its sign-in hosts and widens who may use it", () => {- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });const first = store.create({ ...at("example.com"), username: "Alice", password: "fake-old-pass", source: "card", bots: ["pepper"] });const second = store.create({ ...at("example.com", ["accounts.example.com"]), username: "alice", password: "fake-new-pass", source: "card", bots: ["quill"] });expect(second.id).toBe(first.id);@@ -123,7 +123,7 @@ describe("the saved logins store", () => {});it("keeps two tenants of one site apart when either is kept to its exact host", () => {- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });const one = store.create({ ...at("one.okta.com", [], true), username: "alice", password: "fake-one-pass", source: "settings", bots: "all" });const two = store.create({ ...at("two.okta.com", [], true), username: "alice", password: "fake-two-pass", source: "settings", bots: "all" });expect(two.id).not.toBe(one.id);@@ -133,7 +133,7 @@ describe("the saved logins store", () => {});it("replaces a password or 2FA key, changes who may use it, and forgets a deleted login's secrets", () => {- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });const login = store.create({ ...at("example.com"), username: "a", password: "fake-one-pass", totp: TOTP, source: "settings", bots: "all" });expect(store.update(login.id, { password: "fake-two-pass", bots: ["pepper"] })).toMatchObject({ hasTotp: true, bots: ["pepper"] });expect(store.update(login.id, { totp: null })).toMatchObject({ hasTotp: false });@@ -144,24 +144,82 @@ describe("the saved logins store", () => {});it("keeps the 1Password token in the same sealed file, and which bots each vault is for across reconnects", () => {- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });store.setOnePasswordToken("ops_fake-service-account-token");- expect(new LoginStore({ dataDir: dir }).onePasswordToken()).toBe("ops_fake-service-account-token");+ expect(new VaultStore({ dataDir: dir }).onePasswordToken()).toBe("ops_fake-service-account-token");expect(readFileSync(join(dir, LOGINS_FILE)).includes(Buffer.from("ops_fake"))).toBe(false);expect(store.onePasswordGrants()).toEqual({});store.setOnePasswordGrant("v1", ["pepper"]);store.setOnePasswordGrant("v2", []);store.setOnePasswordToken(null);- expect(new LoginStore({ dataDir: dir }).onePasswordToken()).toBeNull();- expect(new LoginStore({ dataDir: dir }).onePasswordGrants()).toEqual({ v1: ["pepper"], v2: [] });+ expect(new VaultStore({ dataDir: dir }).onePasswordToken()).toBeNull();+ expect(new VaultStore({ dataDir: dir }).onePasswordGrants()).toEqual({ v1: ["pepper"], v2: [] });store.setOnePasswordGrant("v1", "all");- expect(new LoginStore({ dataDir: dir }).onePasswordGrants()).toEqual({ v2: [] });+ expect(new VaultStore({ dataDir: dir }).onePasswordGrants()).toEqual({ v2: [] });+ });+});++describe("the Vault's saved secrets", () => {+ const STRIPE = "sk_test_fake-vault-secret-1";++ it("live in the same sealed file beside the logins, still version 1, which the previous release reads without losing a login", () => {+ const store = new VaultStore({ dataDir: dir, now: () => 5 });+ store.create({ ...at("example.com"), username: "alice", password: PASSWORD, source: "settings", bots: "all" });+ const saved = store.saveSecret({ name: "Stripe secret key", value: STRIPE, source: "card", bots: ["pepper"], refOnly: true });+ expect(saved).toEqual({ id: saved.id, name: "Stripe secret key", source: "card", bots: ["pepper"], refOnly: true, createdAt: 5, updatedAt: 5 });+ expect(readdirSync(dir).sort()).toEqual([LOGINS_KEY_FILE, LOGINS_FILE].sort());+ expect(readFileSync(join(dir, LOGINS_FILE)).includes(Buffer.from(STRIPE))).toBe(false);+ const reopened = new VaultStore({ dataDir: dir });+ expect(reopened.listSecrets()).toEqual([saved]);+ expect(JSON.stringify(reopened.listSecrets())).not.toContain(STRIPE);+ const key = readFileSync(join(dir, LOGINS_KEY_FILE), "utf8").trim();+ const written = JSON.parse(decryptBrowserState(readFileSync(join(dir, LOGINS_FILE)), key));+ expect(written.version).toBe(1);+ expect(previousRelease.parse(written).logins.map((login) => login.username)).toEqual(["alice"]);+ });++ it("are always masked, not only while a card's copy lives", () => {+ const store = new VaultStore({ dataDir: dir });+ const held = new HeldSecrets(store);+ expect(held.scrub(`key=${STRIPE}`)).toBe(`key=${STRIPE}`);+ const saved = store.saveSecret({ name: "Stripe secret key", value: STRIPE, source: "settings", bots: "all" });+ expect(held.scrub(`key=${STRIPE}`)).toBe("key=••••••");+ store.updateSecret(saved.id, { value: "sk_test_fake-vault-secret-2" });+ expect(held.scrub("sk_test_fake-vault-secret-2")).toBe("••••••");+ store.removeSecret(saved.id);+ expect(store.secretValues()).toEqual([]);+ });++ it("are found by name for the bots that may use them, one kept to the bot first, and a ref-only one never as a file", () => {+ const store = new VaultStore({ dataDir: dir, now: () => 1 });+ const shared = store.saveSecret({ name: "Stripe secret key", value: "sk_test_fake-shared", source: "settings", bots: "all" });+ expect(store.usableSecret("stripe-secret-key", "pepper", "file")?.id).toBe(shared.id);+ const own = store.saveSecret({ name: "STRIPE secret key", value: "sk_test_fake-own", source: "card", bots: ["pepper"], refOnly: true });+ expect(store.usableSecret("Stripe secret key", "pepper", "ref")?.id).toBe(own.id);+ expect(store.usableSecret("Stripe secret key", "pepper", "file")?.id).toBe(shared.id);+ expect(store.usableSecret("Stripe secret key", "quill", "ref")?.id).toBe(shared.id);+ store.removeSecret(shared.id);+ expect(store.usableSecret("Stripe secret key", "quill", "ref")).toBeNull();+ expect(store.usableSecret("Stripe publishable key", "pepper", "ref")).toBeNull();+ });++ it("saving one name again for the same bots replaces its value; for other bots it is another secret", () => {+ const store = new VaultStore({ dataDir: dir });+ const first = store.saveSecret({ name: "Notion key", value: "ntn_fake-one", source: "card", bots: ["pepper"], refOnly: true });+ const again = store.saveSecret({ name: "notion key", value: "ntn_fake-two", source: "card", bots: ["pepper"] });+ expect(again).toMatchObject({ id: first.id, name: "Notion key" });+ expect(again.refOnly).toBeUndefined();+ expect(store.secretValues()).toEqual(["ntn_fake-two"]);+ expect(store.saveSecret({ name: "Notion key", value: "ntn_fake-three", source: "card", bots: ["quill"] }).id).not.toBe(first.id);+ expect(store.listSecrets()).toHaveLength(2);+ expect(store.updateSecret("missing", { name: "x" })).toBeNull();+ expect(store.removeSecret("missing")).toBe(false);});});describe("the held-secret scrubber", () => {it("masks a saved password in every form a page or a log can show it", () => {- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });store.create({ ...at("example.com"), username: "alice", password: PASSWORD, source: "settings", bots: "all" });const held = new HeldSecrets(store);const shown = [@@ -179,7 +237,7 @@ describe("the held-secret scrubber", () => {});it("masks a password a submitted form carried in a URL, with ! ' ( ) ~ percent-encoded", () => {- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });store.create({ ...at("example.com"), username: "alice", password: "Hunter2!(x)~", source: "settings", bots: "all" });const url = `https://example.com/login?${new URLSearchParams({ user: "alice", password: "Hunter2!(x)~" })}`;expect(new HeldSecrets(store).scrub(url)).toBe("https://example.com/login?user=alice&password=••••••");@@ -187,7 +245,7 @@ describe("the held-secret scrubber", () => {it("masks a one-time code only as a whole number, and only for a few minutes", () => {let now = 0;- const held = new HeldSecrets(new LoginStore({ dataDir: dir }), () => now);+ const held = new HeldSecrets(new VaultStore({ dataDir: dir }), () => now);held.remember("492039", "code");expect(held.scrub("Code 492039 accepted")).toBe("Code •••••• accepted");expect(held.scrub("order 14920391")).toBe("order 14920391");@@ -196,14 +254,14 @@ describe("the held-secret scrubber", () => {});it("masks a password filled from elsewhere for the rest of the run, and ignores values too short to be one", () => {- const held = new HeldSecrets(new LoginStore({ dataDir: dir }));+ const held = new HeldSecrets(new VaultStore({ dataDir: dir }));held.remember("fake-vault-pass", "password");held.remember("abc", "password");expect(held.scrub("x fake-vault-pass y abc")).toBe("x •••••• y abc");});it("runs inside every redaction once registered, short text included", () => {- const store = new LoginStore({ dataDir: dir });+ const store = new VaultStore({ dataDir: dir });store.create({ ...at("example.com"), username: "alice", password: "fake-hunter2", source: "settings", bots: "all" });const held = new HeldSecrets(store);const remove = addHeldSecretScrubber((text) => held.scrub(text));diff --git a/server/login-store.ts b/server/vault-store.tssimilarity index 74%rename from server/login-store.tsrename to server/vault-store.tsindex 81cee6716f..88c3b02695 100644--- a/server/login-store.ts+++ b/server/vault-store.ts@@ -1,6 +1,7 @@-// Sealed under a key of its own (a 0600 file beside it), never the browser engine's, which every browser process gets in-// its environment. Neither file is ever backed up, exported or moved: a saved password stays on its computer, unless the-// person sends that one login to their own Cloud with Also use on My Cloud (login-handoff.ts).+// The Vault: saved logins and saved secrets. Sealed under a key of its own (a 0600 file beside it), never the browser+// engine's, which every browser process gets in its environment. Neither file is ever backed up, exported or moved: a+// saved value stays on its computer, unless the person sends that one login to their own Cloud with Also use on My Cloud+// (login-handoff.ts).import { randomBytes, randomUUID } from "node:crypto";import { existsSync, mkdirSync, readFileSync } from "node:fs";import { join } from "node:path";@@ -8,6 +9,7 @@ import { z } from "zod";import { HELD_SECRET_MASK } from "../shared/redact.ts";import { LOGIN_FIELD_MAX, LOGIN_HOSTS_MAX, loginMatchesHost, loginSite, loginUsableBy, 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";import type { TotpKey } from "./totp.ts";@@ -42,9 +44,23 @@ const diskLoginSchema = z.object({lastUsedAt: z.number().optional(),});+const diskSecretSchema = z.object({+ id: z.string().min(1),+ name: z.string().min(1).max(VAULT_SECRET_NAME_MAX),+ value: z.string().min(1).max(SECRET_VALUE_MAX_BYTES),+ source: z.enum(["card", "settings"]),+ bots: botsSchema,+ refOnly: z.literal(true).optional(),+ createdAt: z.number(),+ updatedAt: z.number(),+ lastUsedAt: z.number().optional(),+});++// The previous release parses this file with a non-strict object, so it reads its logins and skips `secrets`.const fileSchema = z.object({version: z.literal(1),logins: z.array(diskLoginSchema),+ secrets: z.array(diskSecretSchema).optional(),onePassword: z.object({ token: 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(),@@ -56,6 +72,22 @@ type DiskFile = z.infer<typeof fileSchema>;/** One saved login with its secrets. Server-only: no route returns this. */export type StoredLogin = Omit<DiskLogin, "host" | "site" | "hosts" | "exactHost"> & LoginPlace;type StoreFile = Omit<DiskFile, "logins"> & { logins: StoredLogin[] };+/** One saved secret with its value. Server-only: no route returns this. */+export type StoredSecret = z.infer<typeof diskSecretSchema>;++export interface NewSecret {+ name: string;+ value: string;+ source: "card" | "settings";+ bots: LoginBots;+ refOnly?: boolean;+}++export interface SecretPatch {+ name?: string;+ value?: string;+ bots?: LoginBots;+}export interface NewLogin extends LoginPlace {username: string;@@ -92,13 +124,22 @@ export function summarizeLogin(login: StoredLogin): LoginSummary {};}+export function summarizeSecret({ value: _value, ...secret }: StoredSecret): VaultSecret {+ return secret;+}++function sameBots(a: LoginBots, b: LoginBots): boolean {+ if (a === "all" || b === "all") return a === b;+ return a.length === b.length && a.every((id) => b.includes(id));+}+/** The same account: one username on one site, unless either is kept to hosts the other does not share. */function sameAccount(login: StoredLogin, input: NewLogin): boolean {if (login.username.toLowerCase() !== input.username.toLowerCase() || login.site !== input.site) return false;return (!login.exactHost && !input.exactHost) || login.hosts.some((host) => input.hosts.includes(host));}-export class LoginStore {+export class VaultStore {private readonly file: string;private readonly keyFile: string;private readonly now: () => number;@@ -234,9 +275,66 @@ export class LoginStore {markUsed(id: string): void {const data = this.read();- if (!data.logins.some((login) => login.id === id)) return;const at = this.now();- this.write({ ...data, logins: data.logins.map((login) => login.id === id ? { ...login, lastUsedAt: at } : login) });+ if (data.logins.some((login) => login.id === id)) {+ this.write({ ...data, logins: data.logins.map((login) => login.id === id ? { ...login, lastUsedAt: at } : login) });+ } else if (data.secrets?.some((secret) => secret.id === id)) {+ this.write({ ...data, secrets: data.secrets.map((secret) => secret.id === id ? { ...secret, lastUsedAt: at } : secret) });+ }+ }++ listSecrets(): VaultSecret[] {+ return (this.read().secrets ?? []).map(summarizeSecret).sort((a, b) => a.name.localeCompare(b.name));+ }++ /** The secret `botId` may use by this name, as a ref or a file: one kept to some bots before one for every bot, then+ * the newest. */+ usableSecret(name: string, botId: string, delivery: "ref" | "file"): StoredSecret | null {+ const key = vaultNameKey(name);+ const matches = (this.read().secrets ?? []).filter((secret) => vaultNameKey(secret.name) === key && loginUsableBy(secret, botId) &&+ (delivery === "ref" || !secret.refOnly));+ return matches.sort((a, b) => Number(b.bots !== "all") - Number(a.bots !== "all") || b.updatedAt - a.updatedAt)[0] ?? null;+ }++ /** The same name saved again for the same bots replaces its value; otherwise it is a new secret. */+ saveSecret(input: NewSecret): VaultSecret {+ const data = this.read();+ const secrets = data.secrets ?? [];+ const at = this.now();+ const same = secrets.find((secret) => vaultNameKey(secret.name) === vaultNameKey(input.name) && sameBots(secret.bots, input.bots));+ if (same) {+ const { refOnly: _refOnly, ...rest } = same;+ const updated: StoredSecret = { ...rest, value: input.value, updatedAt: at, ...(input.refOnly ? { refOnly: true } : {}) };+ this.write({ ...data, secrets: secrets.map((secret) => secret.id === same.id ? updated : secret) });+ return summarizeSecret(updated);+ }+ const secret: StoredSecret = {+ id: randomUUID(), name: input.name, value: input.value, source: input.source, bots: input.bots, ...(input.refOnly ? { refOnly: true } : {}), createdAt: at, updatedAt: at,+ };+ this.write({ ...data, secrets: [...secrets, secret] });+ return summarizeSecret(secret);+ }++ updateSecret(id: string, patch: SecretPatch): VaultSecret | null {+ const data = this.read();+ const current = data.secrets?.find((secret) => secret.id === id);+ if (!data.secrets || !current) return null;+ const next: StoredSecret = {+ ...current,+ ...(patch.name === undefined ? {} : { name: patch.name }),+ ...(patch.value === undefined ? {} : { value: patch.value }),+ ...(patch.bots === undefined ? {} : { bots: patch.bots }),+ updatedAt: this.now(),+ };+ this.write({ ...data, secrets: data.secrets.map((secret) => secret.id === id ? next : secret) });+ return summarizeSecret(next);+ }++ removeSecret(id: string): boolean {+ const data = this.read();+ if (!data.secrets?.some((secret) => secret.id === id)) return false;+ this.write({ ...data, secrets: data.secrets.filter((secret) => secret.id !== id) });+ return true;}onePasswordToken(): string | null {@@ -267,6 +365,7 @@ export class LoginStore {return [...data.logins.flatMap((login) => [login.password, ...(login.totp ? [login.totp.secret] : [])]),...(data.onePassword ? [data.onePassword.token] : []),+ ...(data.secrets ?? []).map((secret) => secret.value),];}}diff --git a/shared/vault.ts b/shared/vault.tsnew file mode 100644index 0000000000..36d96bd79f--- /dev/null+++ b/shared/vault.ts@@ -0,0 +1,32 @@+/**+ * The Vault: saved logins (shared/logins.ts) and saved secrets, kept+ * encrypted on the computer OpenMausBot runs on. A bot uses a saved secret+ * through a one-use reference or a private file and never sees it. Clients+ * see a saved secret as a list row, never its value.+ */+import { CUSTOM_SECRET_LABEL_MAX } from "./credential-request.ts";+import type { LoginBots } from "./logins.ts";++/** One saved secret as Settings shows it. There is no value field, and no+ * route ever returns one: a saved value is only ever replaced. */+export interface VaultSecret {+ id: string;+ /** What the person or the asking bot called it, such as Stripe secret key. */+ name: string;+ /** A bot's secure card, or Settings. */+ source: "card" | "settings";+ bots: LoginBots;+ /** Given on a card for OpenMausBot's own tools only, so it is never written to a file a bot's commands read. */+ refOnly?: true;+ createdAt: number;+ updatedAt: number;+ lastUsedAt?: number;+}++export const VAULT_SECRET_NAME_MAX = CUSTOM_SECRET_LABEL_MAX;+export const SECRET_VALUE_MAX_BYTES = 4_096;++/** The form two secret names are compared in: "Stripe secret key" and "stripe-secret-key" are one name. */+export function vaultNameKey(name: string): string {+ return name.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();+}diff --git a/src/locales/de.json b/src/locales/de.jsonindex 8091652138..0ef29fb2f3 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -114,6 +114,7 @@"server.connect.secretHandoff": "Gib {label} sicher in OpenMausBot auf deinem Telefon oder Computer ein. Es wird nie in den Chat übernommen.","server.connect.secretFile": "Die Befehle von {bot} können es 24 Stunden lang aus einer privaten Datei lesen; es wird nie in den Chat übernommen.","server.connect.secretRef": "{bot} bekommt für die eigenen Werkzeuge von OpenMausBot einen Verweis, der nur einmal gilt, und sieht es nie.",+ "server.connect.secretKept": "OpenMausBot bewahrt es sicher auf, damit {bot} es wieder nutzen kann, ohne dich erneut zu fragen.","server.connect.secretNeverRead": "{bot} kann es verwenden, aber nie auslesen.","server.connect.emailOutgoingLabel": "Postausgangsserver für {address}","server.connect.emailOutgoingNote": "Gib ein, worüber es Mails versendet. {bot} sieht das Passwort nie.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex fef042199b..7790900f56 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -241,6 +241,7 @@"server.connect.secretHandoff": "Securely provide the {label} from OpenMausBot on your phone or computer. It is never added to chat.","server.connect.secretFile": "{bot}'s commands can read it from a private file for 24 hours; it is never added to chat.","server.connect.secretRef": "{bot} gets a one-use reference for OpenMausBot's own tools and never sees it.",+ "server.connect.secretKept": "OpenMausBot keeps it safely, so {bot} can use it again without asking you.","server.connect.secretNeverRead": "{bot} can use it but never read it back.","server.connect.emailOutgoingLabel": "Outgoing server for {address}","server.connect.emailOutgoingNote": "Enter where it sends mail from. {bot} never sees the password.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 37faadbe34..097ab168e3 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -224,6 +224,7 @@"server.connect.secretHandoff": "Forneça {label} com segurança pelo OpenMausBot no celular ou no computador. O conteúdo nunca é adicionado ao chat.","server.connect.secretFile": "Os comandos de {bot} podem ler o conteúdo em um arquivo privado por 24 horas; esse conteúdo nunca é adicionado ao chat.","server.connect.secretRef": "{bot} recebe uma referência de uso único para as ferramentas do próprio OpenMausBot e nunca vê o valor.",+ "server.connect.secretKept": "O OpenMausBot guarda com segurança, para que {bot} possa usar de novo sem pedir a você.","server.connect.secretNeverRead": "{bot} pode usar o valor, mas nunca consegue lê-lo.","server.connect.emailOutgoingLabel": "Servidor de saída de {address}","server.connect.emailOutgoingNote": "Informe por onde ele envia os e-mails. {bot} nunca vê a senha.",