Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Vault page, and "Use a saved one" on the secret and sign-in cards (#5073)

Milind Soni0784929459c4
diff --git a/apps/docs/content/docs/computers/index.mdx b/apps/docs/content/docs/computers/index.mdx
index 8b8dc189ee..9b3aae9bdc 100644
--- a/apps/docs/content/docs/computers/index.mdx
+++ b/apps/docs/content/docs/computers/index.mdx
@@ -25,7 +25,7 @@ The Screen panel can show live frames while an agent works. Supported cloud desk
When a bot needs you to sign in to a website, it asks with a **Sign in needed** card instead of asking for a password in chat. **Open** goes to the computer or browser the bot is working in, with **Take control**; **Done** hands it back and resumes the bot. See [Website sign-in](/docs/security/permissions-and-secrets#website-sign-in).
-In the built-in browser (and in My Chrome) a bot can also sign in with a login you saved, from the card's **Save a login** or **Settings → Logins**, or with one from a connected 1Password vault: it calls `fill_login` on the site's login page, and MausBot types the username, password and any one-time code into the page itself and submits the form, only on that login's own site. The bot never sees the password. See [Saved logins](/docs/security/permissions-and-secrets#saved-logins), including what a screenshot can still show.
+In the built-in browser (and in My Chrome) a bot can also sign in with a login you saved, from the card's **Save a login** or **Settings → Vault**, or with one from a connected 1Password vault: it calls `fill_login` on the site's login page, and MausBot types the username, password and any one-time code into the page itself and submits the form, only on that login's own site. The bot never sees the password. See [Saved logins](/docs/security/permissions-and-secrets#saved-logins), including what a screenshot can still show.
<Callout type="warn" title="Preview is not permission">
Starting a screen preview does not grant the bot control. Local input requires a separate opt-in and remains subject to the computer-use safety boundary.
diff --git a/apps/docs/content/docs/security/permissions-and-secrets.mdx b/apps/docs/content/docs/security/permissions-and-secrets.mdx
index d46fb1f1cc..808b7261c6 100644
--- a/apps/docs/content/docs/security/permissions-and-secrets.mdx
+++ b/apps/docs/content/docs/security/permissions-and-secrets.mdx
@@ -53,6 +53,15 @@ freshly QR-paired phone can enter either kind; an AI provider key needs the
computer or My Cloud. MausBot masks every saved value if it appears in a
transcript, an event or a log.
+When the card appears and the [Vault](#the-vault) holds a secret that could fit
+(its name shares a telling word with what the bot asked for, such as
+`STRIPE_LIVE_KEY` for "Stripe secret key"), the card lists it by name under
+**Use a saved one**. Picking it lets that bot use it from then on and answers
+the card, so nothing is typed; typing a new value still works as above. The
+list shows names only, and only to an owner or an admin. A secret given only
+to MausBot's own tools is never offered for a file, and a 1Password secret
+only to a bot its vault is open to.
+
## Connected-app tool grants
Connected apps are scoped per bot on the desktop: a bot without a grant to a service's tool cannot call it, the ungranted tool is never offered to the model, and every allow/deny is written to the decision log. New and upgraded bots keep all tools until someone assigns grants, and imported bots always land with none, so a shared persona cannot reach your Gmail on turn one. Paired phones see grants read-only; grant editing requires the computer.
@@ -120,16 +129,38 @@ snapshots are refused, and its live preview pauses. Saved sign-ins persist per
browser profile, encrypted. None of this overrides your provider's own
restrictions, and approval modes are unchanged.
+## The Vault
+
+**Settings → Vault** is one list of the passwords and keys your bots can use:
+saved logins, saved secrets, and the items of a linked password manager. Search
+it, or show only **Logins** or **Keys & secrets**. **Add** adds a login, a
+secret, or a pasted `.env` file, where each `NAME=value` line becomes a secret
+called `NAME`. Each row shows where it came from, which bots may use it and when
+it was last used. **Change** renames a secret, replaces its value or changes
+which bots may use it; **Delete** removes it. A saved value is never shown
+again, and no screen or API returns it: it can only be replaced. Only an owner
+or an admin sees the Vault, and a Vault link (such as the Keys page's 1Password
+row, **Set up in Vault**) opens it.
+
+Keys MausBot uses itself (an AI provider's key, Composio, voice, the Boat key)
+stay in **Settings → API keys**, which the Vault's **AI and app keys** row
+opens.
+
## Saved logins
A saved login lets a bot sign in to a site without you. Save one from a **Sign
-in needed** card (**Save a login**), or in **Settings → Logins** (**Add
-login**). Settings lists every saved login by site, username, whether it has a
+in needed** card (**Save a login**), or in **Settings → Vault** (**Add → Add a
+login**). The Vault lists every saved login by site, username, whether it has a
2FA key, where it came from, which bots may use it and when it was last used.
**Change** replaces the password or 2FA key or changes who may use it;
**Delete** removes it. A saved password is never shown again, and no screen or
API returns it: it can only be replaced.
+When a bot asks you to sign in on its own browser and the Vault has a login for
+that site the bot may not use yet, the card lists it by username under **Use a
+saved login**. Picking it lets the bot (and any bot sharing its browser) use it
+from then on and answers the card as **Save a login** does.
+
- **Who may use it.** A login saved from a card is for the bot that asked. One
added in Settings is for every bot unless you pick bots. Bots see which sites
they have a login for (site and username), never more.
@@ -177,14 +208,14 @@ API returns it: it can only be replaced.
### Logins from 1Password
-**Settings → Logins → Connect 1Password** lets bots use the logins in a
-1Password vault. In 1Password, create a
+**Settings → Vault → Password manager → Connect 1Password** lets bots use the
+logins in a 1Password vault. In 1Password, create a
[service account](https://developer.1password.com/docs/service-accounts/)
that can read one vault only, such as "Shared with OMB", and paste its token.
MausBot checks the token reaches 1Password before keeping it, keeps it in
the same encrypted file as saved logins, and never shows it again. 1Password
itself enforces which vaults the token reaches. It works the same way on My
-Cloud: connect it in My Cloud's own **Settings → Logins**.
+Cloud: connect it in My Cloud's own **Settings → Vault**.
A bot that needs it asks with a secure card (`request_credential` with
`onePasswordToken`), never in chat; what you paste there goes to the same
@@ -194,10 +225,10 @@ Key is refused with a message saying so, and a token 1Password refuses (revoked,
expired, or without its vault) is told apart from one that is incomplete.
Every Login item in those vaults that has a website and a password appears
-in the Logins list, marked **From 1Password**, by the website's site (an
+in the Vault, marked **From 1Password**, by the website's site (an
item with websites on two sites is listed under both). Each vault is for
-every bot until you pick bots for it under **1Password** in **Settings →
-Logins**; a bot not picked does not see that vault's logins at all, neither
+every bot until you pick bots for it under **Password manager** in **Settings →
+Vault**; a bot not picked does not see that vault's logins at all, neither
in its list of logins nor when it calls `fill_login`. These rows are
read-only here: change or remove them in 1Password. `fill_login` uses them the
same way as saved logins, with the same site rule, the same one-time
@@ -213,7 +244,7 @@ called Notion token the same way as a secret saved from a card, by one-use
reference or private file, and with no card. The main value is an API
Credential's credential, a Password's password or a Secure Note's text; any
other field is asked for as the title and the field's name, such as "Acme OAuth
-client_secret". The value is read from 1Password at the moment the bot gets it,
+client_secret". They are listed in the Vault by name, read-only. The value is read from 1Password at the moment the bot gets it,
never kept in the Vault, and scrubbed like a filled password. The same vault
choice of bots applies, and a secret saved in the Vault under the same name
comes first.
diff --git a/docs/localization-pt-br.md b/docs/localization-pt-br.md
index aa37fc9456..0df26549b9 100644
--- a/docs/localization-pt-br.md
+++ b/docs/localization-pt-br.md
@@ -287,6 +287,7 @@ the whole catalog in the same change.
| turn (a bot's turn) | sessão | Feminine. Use “sessão de trabalho” only when the sentence also mentions a browser, sign-in or provider session. For calls, use “Um de cada vez” as the mode label and “falas alternadas” when describing it. |
| turn on, turn off | ligar, desligar | Follow the English verb. |
| upload | enviar | Never `upload` or `carregar`. |
+| Vault (Settings section) | Cofre | “Settings → Vault” → “Configurações → Cofre”. A saved key there is a `segredo`. |
| wake, asleep | acordar, dormindo | Used for desktops and computers. |
| webhook | webhook | Masculine. |
| workspace | (do not use) | Say `instalação`, or leave it out. |
diff --git a/docs/verification/browser-live.md b/docs/verification/browser-live.md
index b15ade7ede..94c63baa7d 100644
--- a/docs/verification/browser-live.md
+++ b/docs/verification/browser-live.md
@@ -89,7 +89,7 @@ UI and harness, then removes its temporary data; the server log remains.
account (fake values) for the test page's site. Pepper resumes and calls
`fill_login`; the page's username and password boxes fill, the form is
submitted, the tool result names only what was filled and where the page
- went, and **Settings → Logins** lists the login by site without its
+ went, and **Settings → Vault** lists the login by site without its
password. Open the same page under a subdomain: `fill_login` fills it
too. Under another site, or plain http on a non-local address, it refuses
and types nothing. Call `fill_login` with `submit: false`, then ask Pepper
@@ -100,7 +100,7 @@ UI and harness, then removes its temporary data; the server log remains.
connect a service account limited to one vault holding a test Login item
for the test page's site. Its row appears read-only, marked From
1Password; `fill_login` fills it like a saved login. Pick another bot for
- the vault under 1Password in Settings → Logins: Pepper no longer lists or
+ the vault under 1Password in Settings → Vault: Pepper no longer lists or
fills it. Unit tests use a fake SDK and reach no network.
11. Page dialogs: give the test page a button that calls `confirm()`, take control and press it. The question shows over
@@ -140,7 +140,7 @@ pnpm exec vitest run server/browser-engine.test.ts server/browser-runtime.test.t
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/vault-store.test.ts \
- server/totp.test.ts server/routes/logins.test.ts src/components/LoginsSettings.test.ts \
+ server/totp.test.ts server/routes/logins.test.ts src/components/VaultSettings.test.ts \
server/saved-login.e2e.test.ts server/onepassword.test.ts scripts/prepare-duckdb.test.mjs
```
diff --git a/docs/verification/images/vault-page/card-used.png b/docs/verification/images/vault-page/card-used.png
new file mode 100644
index 0000000000..4d95c53c80
Binary files /dev/null and b/docs/verification/images/vault-page/card-used.png differ
diff --git a/docs/verification/images/vault-page/card.png b/docs/verification/images/vault-page/card.png
new file mode 100644
index 0000000000..4d952abf3f
Binary files /dev/null and b/docs/verification/images/vault-page/card.png differ
diff --git a/docs/verification/images/vault-page/vault-add.png b/docs/verification/images/vault-page/vault-add.png
new file mode 100644
index 0000000000..ca5560f2ab
Binary files /dev/null and b/docs/verification/images/vault-page/vault-add.png differ
diff --git a/docs/verification/images/vault-page/vault-bottom.png b/docs/verification/images/vault-page/vault-bottom.png
new file mode 100644
index 0000000000..5254833a3b
Binary files /dev/null and b/docs/verification/images/vault-page/vault-bottom.png differ
diff --git a/docs/verification/images/vault-page/vault.png b/docs/verification/images/vault-page/vault.png
new file mode 100644
index 0000000000..61768ea64f
Binary files /dev/null and b/docs/verification/images/vault-page/vault.png differ
diff --git a/server/host/secret-cards.test.ts b/server/host/secret-cards.test.ts
index 3a9e9a65bd..9261e4d7c4 100644
--- a/server/host/secret-cards.test.ts
+++ b/server/host/secret-cards.test.ts
@@ -157,6 +157,39 @@ describe("a secret a card saves to the Vault", () => {
});
});
+describe("Use a saved one on a secret card", () => {
+ const KEY = "sk_test_fake-picked-1";
+ const card = async (one: ReturnType<typeof fixture>, extra: Record<string, unknown> = {}) =>
+ String((await one.cards.requestCredential(one.bot, "t1", { label: "Stripe secret key", reason: "For test charges.", delivery: "ref", ...extra })).body.messageId);
+
+ it("offers saved secrets whose names could fit, by name only; picking one lets the bot use it and answers the card", async () => {
+ const one = fixture();
+ const kept = one.vaultStore.saveSecret({ name: "STRIPE_LIVE_KEY", value: KEY, source: "settings", bots: ["quill"] });
+ one.vaultStore.saveSecret({ name: "GitHub token", value: "ghp_fake-unrelated", source: "settings", bots: "all" });
+ const id = await card(one);
+ expect(one.cards.savedChoices("ledger", "t1", id)).toEqual([{ id: kept.id, name: "STRIPE_LIVE_KEY" }]);
+ expect(await one.cards.useSavedSecret("ledger", "t1", id, kept.id)).toMatchObject({ status: 200, body: { provided: true, resumed: true } });
+ expect(one.vaultStore.listSecrets().find((secret) => secret.id === kept.id)).toMatchObject({ bots: ["quill", "ledger"], lastUsedAt: expect.any(Number) });
+ const ref = /secret-ref:[0-9a-f]{32}/u.exec(one.resumed[0]!)?.[0];
+ const used = one.cards.redeemMcpServer({ env: { STRIPE: ref } }, "ledger", "t1");
+ expect(used.ok && used.value).toEqual({ env: { STRIPE: KEY } });
+ expect(one.cards.savedChoices("ledger", "t1", id)).toEqual([]);
+ expect(await one.cards.useSavedSecret("ledger", "t1", id, kept.id)).toMatchObject({ status: 409 });
+ expect(JSON.stringify([one.lines, one.resumed])).not.toContain(KEY);
+ });
+
+ it("never offers one given only to the app's own tools for a file, the same-named one the bot already has, or one not offered", async () => {
+ const one = fixture();
+ one.vaultStore.saveSecret({ name: "Stripe test key", value: "fake-ref-only", source: "card", bots: ["quill"], refOnly: true });
+ expect(one.cards.savedChoices("ledger", "t1", await card(one, { delivery: "file" }))).toEqual([]);
+ one.vaultStore.saveSecret({ name: "Stripe secret key", value: "fake-wrong-one", source: "settings", bots: ["ledger"] });
+ const replace = await card(one, { replace: true });
+ expect(one.cards.savedChoices("ledger", "t1", replace).map((choice) => choice.name)).toEqual(["Stripe test key"]);
+ expect(await one.cards.useSavedSecret("ledger", "t1", replace, "not-offered")).toMatchObject({ status: 404 });
+ expect(one.resumed).toEqual([]);
+ });
+});
+
describe("the mailbox card", () => {
const PASSWORD = "fake-mailbox-password";
const ACCOUNT = { address: "[email protected]", imapHost: "imap.shop.example", smtpHost: "smtp.shop.example", connectedAt: "2026-11-04T00:00:00.000Z" };
@@ -422,6 +455,20 @@ describe("a secret a linked 1Password holds", () => {
expect(one.held).toEqual([]);
});
+ it("is offered on a card asking under another name, read from 1Password only when picked", async () => {
+ const one = linked();
+ const id = String((await ask(one, { label: "Notion workspace key" })).body.messageId);
+ expect(one.held).toEqual([]);
+ const choices = one.cards.savedChoices("ledger", "t1", id);
+ expect(choices).toEqual([{ id: expect.any(String), name: "Notion token", provider: "1password" }]);
+ expect(await one.cards.useSavedSecret("ledger", "t1", id, choices[0]!.id)).toMatchObject({ status: 200 });
+ expect(one.held).toEqual([NOTION]);
+ const ref = /secret-ref:[0-9a-f]{32}/u.exec(one.resumed[0]!)?.[0];
+ const used = one.cards.redeemMcpServer({ env: { NOTION_TOKEN: ref } }, "ledger", "t1");
+ expect(used.ok && used.value).toEqual({ env: { NOTION_TOKEN: NOTION } });
+ expect(one.vaultStore.listSecrets()).toEqual([]);
+ });
+
it("tells the bot in plain words when 1Password can't be read, with no card", async () => {
let failure: Error | null = null;
const one = linked({ fail: () => failure });
diff --git a/server/host/secret-cards.ts b/server/host/secret-cards.ts
index 23388a38fc..9743b6bd22 100644
--- a/server/host/secret-cards.ts
+++ b/server/host/secret-cards.ts
@@ -38,6 +38,10 @@ import {
} from "../phone-secret.ts";
import type { BotLogins } from "../bot-logins.ts";
import type { VaultStore } from "../vault-store.ts";
+import { loginUsableBy } from "../../shared/logins.ts";
+import { vaultNameKey, type VaultChoice } from "../../shared/vault.ts";
+import { fittingChoices } from "../vault/choices.ts";
+import { linkedSecretNames } from "../vault/providers.ts";
import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";
import { serverLine } from "../server-lines.ts";
@@ -55,9 +59,9 @@ export const phoneSecretEnvelopeSchema = z.object({
export interface SecretCardsDeps {
store: Pick<Store, "activePath" | "appendMessage" | "patchMessage" | "messagesFor" | "botByThread" | "groupByThread" | "onChange">;
cfg: AppConfig;
- botLogins: Pick<BotLogins, "credentialConfig" | "linkedSecret">;
+ botLogins: Pick<BotLogins, "credentialConfig" | "linkedSecret"> & Partial<Pick<BotLogins, "linkedSecrets">>;
/** 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">;
+ vaultStore: Pick<VaultStore, "saveSecret" | "usableSecret" | "markUsed" | "listSecrets" | "secret" | "updateSecret">;
phoneSecrets: Pick<PhoneSecretBridge, "provide" | "open">;
phoneSecretSubmissions: PhoneSecretSubmissionRegistry;
connectorThread(botId: string, threadId: string): { bot: BotRecord; group: GroupRecord | undefined } | null;
@@ -219,12 +223,16 @@ export function createSecretCards(deps: SecretCardsDeps) {
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. */
+ /** Saves a custom card's value to the Vault for the asking bot, then hands it over. */
function storeCustomSecret(message: Message, botId: string, threadId: string, value: string): void {
+ vaultStore.saveSecret({ name: message.secret!.label, value, source: "card", bots: [botId], refOnly: message.secret!.delivery !== "file" });
+ handOver(message, botId, threadId, value);
+ }
+
+ /** Hands a custom card's value over as its delivery says, and marks when; never touches the card's other fields. */
+ function handOver(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") {
vault.saveFile(owner, message.id, value, fileHome(botId, threadId, secret.vm));
} else {
@@ -233,8 +241,8 @@ export function createSecretCards(deps: SecretCardsDeps) {
store.patchMessage(threadId, message.id, { secret: { ...secret, savedAt: Date.now() } });
}
- /** A value typed into a custom card in the app: kept, then the paused turn resumes. */
- function saveCustomSecret(botId: string, threadId: string, messageId: string, raw: unknown): { status: number; body: Record<string, unknown> } {
+ /** A custom card still waiting for its value, or why it can't take one. */
+ function openCustomCard(botId: string, threadId: string, messageId: string): Message | { status: number; body: Record<string, unknown> } {
const message = secretMessage(botId, threadId, messageId);
if (!message?.secret) return { status: 404, body: { ...userError("serverError.secret.missing") } };
const secret = message.secret;
@@ -246,6 +254,13 @@ export function createSecretCards(deps: SecretCardsDeps) {
if (secret.superseded) return { status: 409, body: { ...userError("serverError.secret.replaced") } };
if (secret.stopped) return { status: 409, body: { ...userError("serverError.secret.taskStopped") } };
if (secret.provided || secret.savedAt !== undefined) return { status: 409, body: { ...userError("serverError.secret.alreadySaved") } };
+ return message;
+ }
+
+ /** A value typed into a custom card in the app: kept, then the paused turn resumes. */
+ function saveCustomSecret(botId: string, threadId: string, messageId: string, raw: unknown): { status: number; body: Record<string, unknown> } {
+ const message = openCustomCard(botId, threadId, messageId);
+ if ("status" in message) return message;
const value = typeof raw === "string" ? raw.trim() : "";
if (!value || Buffer.byteLength(value) > SECRET_VALUE_MAX_BYTES) {
return { status: 400, body: { ...userError("serverError.secret.valueSize", { bytes: SECRET_VALUE_MAX_BYTES }) } };
@@ -260,6 +275,55 @@ export function createSecretCards(deps: SecretCardsDeps) {
return { status: 200, body: currentSecretState(botId, threadId, message.id) ?? { provided: true, resumed: false } };
}
+ /** "Use a saved one" on a custom card: saved secrets and the bot's linked ones whose names could fit, never the one by
+ * this very name the bot may already use (it would have had it with no card, so the bot wants a new value). A secret
+ * given only to OpenMausBot's own tools is never offered for a file. */
+ function savedChoices(botId: string, threadId: string, messageId: string): Array<VaultChoice & { use(): Promise<string> }> {
+ const message = openCustomCard(botId, threadId, messageId);
+ if ("status" in message || message.secret!.delivery === "email") return [];
+ const card = message.secret!;
+ const asked = vaultNameKey(card.label);
+ const fresh = (name: string, usable: boolean) => !(usable && vaultNameKey(name) === asked);
+ const saved = vaultStore.listSecrets().filter((one) => !(card.delivery === "file" && one.refOnly) && fresh(one.name, loginUsableBy(one, botId)))
+ .map((one) => ({ id: one.id, name: one.name, use: async () => {
+ // Picking it is the person letting this bot use it.
+ if (one.bots !== "all" && !one.bots.includes(botId)) vaultStore.updateSecret(one.id, { bots: [...one.bots, botId] });
+ const value = vaultStore.secret(one.id)?.value;
+ if (!value) throw new Error(`${one.name} is no longer in the Vault.`);
+ vaultStore.markUsed(one.id);
+ return value;
+ } }));
+ const linked = (botLogins.linkedSecrets?.() ?? []).filter((one) => loginUsableBy(one, botId)).flatMap((one) => linkedSecretNames(one)
+ .filter(({ name }) => fresh(name, true)).map(({ name }) => ({ id: `${one.id}#${name}`, name, provider: one.provider, use: async () => {
+ const read = await botLogins.linkedSecret(name, botId);
+ if (!read) throw new Error(`${name} is no longer in the linked password manager.`);
+ return read.value;
+ } })));
+ return fittingChoices(card.label, [...saved, ...linked]);
+ }
+
+ /** The person picked a saved secret on the card: the bot may use it from now on, gets it as the card's delivery says,
+ * and its paused turn resumes. */
+ async function useSavedSecret(botId: string, threadId: string, messageId: string, itemId: unknown): Promise<{ status: number; body: Record<string, unknown> }> {
+ const open = openCustomCard(botId, threadId, messageId);
+ if ("status" in open) return open;
+ const choice = savedChoices(botId, threadId, messageId).find((one) => one.id === itemId);
+ if (!choice) return { status: 404, body: { ...userError("serverError.secret.unavailableLower") } };
+ let value: string;
+ try { value = await choice.use(); }
+ catch (error) { return { status: 502, body: { error: error instanceof Error ? error.message : String(error) } }; }
+ const message = openCustomCard(botId, threadId, messageId);
+ if ("status" in message) return message;
+ try {
+ handOver(message, botId, threadId, value);
+ } 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") } };
+ }
+ if (!resumeSecretCard(botId, threadId, message.id, "provided")) return { status: 409, body: { ...userError("serverError.secret.unavailableLower") } };
+ return { status: 200, body: currentSecretState(botId, threadId, message.id) ?? { provided: true, resumed: false } };
+ }
+
/** The mailbox card: the password goes to the Email connector, which reads a real header before keeping it. A wrong one
* leaves the card open with why, so the person isn't sent back to a new card. */
async function saveEmailSecret(botId: string, threadId: string, messageId: string, fields: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }> {
@@ -617,6 +681,9 @@ export function createSecretCards(deps: SecretCardsDeps) {
return {
phoneSecretSubmissionKey, secretMessage, currentSecretState, resumeSecretCard, provideSecretFromPhone, requestCredential, saveCustomSecret, saveEmailSecret,
- secretSaved, updateText, redeemMcpServer,
+ secretSaved, updateText, redeemMcpServer, useSavedSecret,
+ /** Names only: what the card shows under "Use a saved one". */
+ savedChoices: (botId: string, threadId: string, messageId: string): VaultChoice[] =>
+ savedChoices(botId, threadId, messageId).map(({ id, name, provider }) => ({ id, name, ...(provider ? { provider } : {}) })),
};
}
diff --git a/server/index.ts b/server/index.ts
index 2aee79bbd3..7d43a47388 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -447,7 +447,7 @@ 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 { createVaultRoutes } from "./routes/vault.ts";
+import { parseLoginFields, parseTotpField, createLoginRoutes } from "./routes/logins.ts"; import { createVaultRoutes } from "./routes/vault.ts"; import { createSignInVaultChoices } from "./vault/choices.ts";
import { loginSite } from "../shared/logins.ts";
import { browserRestartRefusal } from "./browser-live.ts";
import { browserEngineStatus } from "./browser-engine.ts";
@@ -12222,7 +12222,7 @@ ROUTES.push(createBotMemoryRoutes({
const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (auth, threadId) => { if (ownerOrAdmin(auth) && store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
- createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));
+ createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) }));
ROUTES.push(createRoomHoldRoutes({
group: (id) => store.group(id),
groupFor: personRooms.groupForAuth,
diff --git a/server/request-auth.test.ts b/server/request-auth.test.ts
index 87b1b68e67..82aa4acf89 100644
--- a/server/request-auth.test.ts
+++ b/server/request-auth.test.ts
@@ -106,6 +106,15 @@ describe("scopes", () => {
] as const) expect(requiredScope(method, path), `${method} ${path}`).toBe("admin");
});
+ it("keeps a card's \"Use a saved one\" an admin's, since picking one lets a bot use a Vault item", () => {
+ for (const [method, path] of [
+ ["GET", "/api/bots/bot-1/secret-cards/card-1/saved"],
+ ["POST", "/api/bots/bot-1/secret-cards/card-1/use"],
+ ["GET", "/api/bots/bot-1/sign-in-cards/card-1/saved-logins"],
+ ["POST", "/api/bots/bot-1/sign-in-cards/card-1/use-login"],
+ ] as const) expect(requiredScope(method, path), `${method} ${path}`).toBe("admin");
+ });
+
it("keeps the attachments clear to the owner: a client may read one file, never empty the store", () => {
for (const method of ["GET", "POST"]) expect(requiredScope(method, "/api/attachment-storage"), method).toBe("admin");
expect(requiredScope("GET", "/api/attachments/a1b2.png")).toBe("client");
diff --git a/server/routes/secret-cards.test.ts b/server/routes/secret-cards.test.ts
index 4040ce35f2..3bdbd8750b 100644
--- a/server/routes/secret-cards.test.ts
+++ b/server/routes/secret-cards.test.ts
@@ -84,3 +84,42 @@ describe("POST /api/bots/<bot>/secret-cards/<card>/save", () => {
expect(JSON.stringify(vi.mocked(ctx.json).mock.calls)).not.toContain("sk_live_canary");
});
});
+
+describe("Use a saved one: GET .../saved and POST .../use", () => {
+ const BASE = "/api/bots/atlas/secret-cards/card-1";
+ function route(over: Partial<{ visible: boolean; context: SecretAnswerContext }> = {}) {
+ const savedChoices = vi.fn(() => [{ id: "s1", name: "Stripe secret key" }]);
+ const useSavedSecret = vi.fn(async () => ({ status: 200, body: { provided: true, resumed: true } }));
+ const cards = { secretMessage: vi.fn(() => ({ id: "card-1" })), savedChoices, useSavedSecret } as unknown as SecretCards;
+ const handler = createSecretCardRoutes({
+ cards, phoneSecretSubmissions: { has: () => false }, threadVisible: () => over.visible ?? true, answerContext: () => over.context ?? team(null, "p:boss"),
+ });
+ return { handler, savedChoices, useSavedSecret };
+ }
+ const context = (method: "GET" | "POST", end: string, body: unknown = {}, contentType = "application/json"): RouteContext => ({
+ req: { headers: { "content-type": contentType } } as unknown as IncomingMessage, res: { setHeader: vi.fn() } as unknown as ServerResponse,
+ path: `${BASE}/${end}`, method, url: new URL(`${BASE}/${end}?threadId=thread-1`, "http://fixture.invalid"), auth: ADMIN,
+ readBody: vi.fn(async () => body), json: vi.fn(),
+ });
+
+ it("names the choices and uses the one picked", async () => {
+ const { handler, useSavedSecret } = route();
+ const list = context("GET", "saved");
+ await handler(list);
+ expect(list.json).toHaveBeenCalledExactlyOnceWith(list.res, 200, { choices: [{ id: "s1", name: "Stripe secret key" }] });
+ const use = context("POST", "use", { threadId: "thread-1", itemId: "s1" });
+ await handler(use);
+ expect(useSavedSecret).toHaveBeenCalledExactlyOnceWith("atlas", "thread-1", "card-1", "s1");
+ expect(use.json).toHaveBeenCalledExactlyOnceWith(use.res, 200, { provided: true, resumed: true });
+ });
+
+ it("refuses a form post, a hidden conversation and someone else's card before anything is used", async () => {
+ for (const [over, contentType, status] of [[{}, "text/plain", 415], [{ visible: false }, "application/json", 404], [{ context: team("p:ada", "p:bob") }, "application/json", 403]] as const) {
+ const { handler, useSavedSecret } = route(over);
+ const use = context("POST", "use", { threadId: "thread-1", itemId: "s1" }, contentType);
+ await handler(use);
+ expect(useSavedSecret).not.toHaveBeenCalled();
+ expect(vi.mocked(use.json).mock.calls[0]?.[1]).toBe(status);
+ }
+ });
+});
diff --git a/server/routes/secret-cards.ts b/server/routes/secret-cards.ts
index ae3639bdb3..15bfb27336 100644
--- a/server/routes/secret-cards.ts
+++ b/server/routes/secret-cards.ts
@@ -1,6 +1,7 @@
import { userError } from "../user-errors.ts";
// POST /api/bots/<bot>/secret-cards/<message>/provide with a phone's sealed envelope, .../save with {threadId, value}
-// for a custom secret typed in the app, and .../(provided|resume|dismiss) with {threadId}; and the agents tool's
+// for a custom secret typed in the app, .../use with {threadId, itemId} for one picked from the Vault (GET .../saved
+// lists those by name), and .../(provided|resume|dismiss) with {threadId}; and the agents tool's
// /api/internal/request-credential. A value is never echoed back, logged or added to the card.
import { CUSTOM_SECRET_TARGET, credentialResumeOutcome, isCredentialTargetId } from "../../shared/credential-request.ts";
import { phoneSecretEnvelopeSchema, type SecretCards } from "../host/secret-cards.ts";
@@ -46,8 +47,24 @@ export interface SecretCardRouteDeps {
export function createSecretCardRoutes(deps: SecretCardRouteDeps): RouteHandler {
const { phoneSecretSubmissions } = deps;
const { secretMessage, currentSecretState, resumeSecretCard, provideSecretFromPhone, phoneSecretSubmissionKey, secretSaved } = deps.cards;
- return async ({ req, res, path, method, auth, json, readBody }) => {
+ return async ({ req, res, url, path, method, auth, json, readBody }) => {
let m: RegExpMatchArray | null;
+ // Picking a saved secret lets the bot use it, so these are an admin's (not in CLIENT_ALLOW) like the Vault itself.
+ m = path.match(/^\/api\/bots\/([\w-]+)\/secret-cards\/([\w-]+)\/(saved|use)$/);
+ if (m && method === (m[3] === "saved" ? "GET" : "POST")) {
+ const mediaType = String(req.headers["content-type"] ?? "").split(";", 1)[0]!.trim().toLowerCase();
+ if (m[3] === "use" && mediaType !== "application/json") return json(res, 415, { error: "content-type must be application/json" });
+ const raw = m[3] === "use" ? await readBody(req, 16_384) : null;
+ const fields = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : {};
+ const threadId = m[3] === "saved" ? url.searchParams.get("threadId") ?? "" : String(fields.threadId ?? "");
+ if (!deps.threadVisible(auth, threadId) || !secretMessage(m[1]!, threadId, m[2]!)) return json(res, 404, { ...userError("serverError.secret.missing") });
+ const refusal = codedSecretAnswerRefusal(auth, deps.answerContext(auth, m[1]!, threadId));
+ if (refusal) return json(res, 403, refusal);
+ res.setHeader("cache-control", "no-store");
+ if (m[3] === "saved") return json(res, 200, { choices: deps.cards.savedChoices(m[1]!, threadId, m[2]!) });
+ const result = await deps.cards.useSavedSecret(m[1]!, threadId, m[2]!, fields.itemId);
+ return json(res, result.status, result.body);
+ }
m = path.match(/^\/api\/bots\/([\w-]+)\/secret-cards\/([\w-]+)\/save$/);
if (m && method === "POST") {
// JSON only, so a form posted from another local page cannot save one.
diff --git a/server/routes/sign-in-cards.test.ts b/server/routes/sign-in-cards.test.ts
index 6a2e4bc300..b0acbc9fea 100644
--- a/server/routes/sign-in-cards.test.ts
+++ b/server/routes/sign-in-cards.test.ts
@@ -16,7 +16,12 @@ async function serve() {
const settled: Array<{ botId: string; threadId: string; messageId: string; outcome: SignInOutcome }> = [];
const saved: Array<{ botId: string; threadId: string; messageId: string; body: Record<string, unknown> }> = [];
const targets: Array<{ botId: string; threadId: string; messageId: string }> = [];
+ const used: unknown[] = [];
const routes = [createSignInCardRoutes({
+ vault: {
+ list: () => ({ status: 200, body: { choices: [{ id: "l1", name: "alice" }] } }),
+ use: (...args) => { used.push(args); return { status: 200, body: { done: true, resumed: true, saved: true, site: "example.com" } }; },
+ },
settle: (botId, threadId, messageId, outcome) => {
settled.push({ botId, threadId, messageId, outcome });
return messageId === "gone" ? { status: 404, body: { error: "no such sign-in request" } } : { status: 200, body: { resumed: true } };
@@ -40,7 +45,7 @@ async function serve() {
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 post = (path: string, body: unknown, type = "application/json") => fetch(`${base}${path}`, { method: "POST", headers: { "content-type": type }, body: JSON.stringify(body) });
- return { base, settled, saved, targets, post };
+ return { base, settled, saved, targets, used, post };
}
describe("sign-in card routes", () => {
@@ -102,6 +107,17 @@ describe("sign-in card routes", () => {
expect([settled, saved, targets]).toEqual([[], [], []]);
});
+ it("names the saved logins a card could use, and uses one only as JSON and only in a thread the caller can see", async () => {
+ const { base, used, post } = await serve();
+ expect(await (await fetch(`${base}/api/bots/scout/sign-in-cards/m1/saved-logins?threadId=t1`)).json()).toEqual({ choices: [{ id: "l1", name: "alice" }] });
+ expect(await (await fetch(`${base}/api/bots/scout/sign-in-cards/m1/saved-logins?threadId=hidden`)).json()).toEqual({ choices: [] });
+ expect((await post("/api/bots/scout/sign-in-cards/m1/use-login", { threadId: "t1", loginId: "l1" }, "text/plain")).status).toBe(415);
+ expect((await post("/api/bots/scout/sign-in-cards/m1/use-login", { threadId: "hidden", loginId: "l1" })).status).toBe(404);
+ expect(used).toEqual([]);
+ expect(await (await post("/api/bots/scout/sign-in-cards/m1/use-login", { threadId: "t1", loginId: "l1" })).json()).toMatchObject({ done: true, saved: true });
+ expect(used).toEqual([["scout", "t1", "m1", "l1"]]);
+ });
+
it("takes a login as JSON only, so another page's form cannot post one", async () => {
const { saved, post } = await serve();
expect((await post("/api/bots/scout/sign-in-cards/m1/save-login", { threadId: "t1", password: "fake-card-pass" }, "text/plain")).status).toBe(415);
diff --git a/server/routes/sign-in-cards.ts b/server/routes/sign-in-cards.ts
index e1d271c762..e6d6155c0b 100644
--- a/server/routes/sign-in-cards.ts
+++ b/server/routes/sign-in-cards.ts
@@ -1,7 +1,9 @@
// POST /api/bots/<bot>/sign-in-cards/<message>/(done|cancel|save-login) with {threadId}, and GET .../save-login?threadId=
-// for where a login saved from the card would fill. A saved password goes into the encrypted store and no route ever
-// returns it.
+// for where a login saved from the card would fill. GET .../saved-logins?threadId= names the saved logins for the card's
+// site its bot may not use yet, and POST .../use-login with {threadId, loginId} lets it use one and answers the card.
+// A saved password goes into the encrypted store and no route ever returns it.
import type { RequestAuth } from "../request-auth.ts";
+import type { SignInVaultChoices } from "../vault/choices.ts";
import { PASS, type RouteHandler } from "./table.ts";
export type SignInOutcome = "done" | "cancelled";
@@ -14,11 +16,13 @@ export interface SignInCardRouteDeps {
saveTarget(botId: string, threadId: string, messageId: string): Promise<Answer>;
/** A member reaches a card only in a thread shown to them, which in a room can be narrower than the bot. */
threadVisible(auth: RequestAuth, threadId: string): boolean;
+ /** "Use a saved login". Its paths are an admin's (not in CLIENT_ALLOW), like the Vault itself. */
+ vault?: SignInVaultChoices;
}
const HIDDEN: Answer = { status: 404, body: { error: "no such sign-in request" } };
-const CARD = /^\/api\/bots\/([\w-]+)\/sign-in-cards\/([\w-]+)\/(done|cancel|save-login)$/u;
+const CARD = /^\/api\/bots\/([\w-]+)\/sign-in-cards\/([\w-]+)\/(done|cancel|save-login|saved-logins|use-login)$/u;
export function createSignInCardRoutes(deps: SignInCardRouteDeps): RouteHandler {
return async ({ req, res, url, path, method, auth, json, readBody }) => {
@@ -29,14 +33,24 @@ export function createSignInCardRoutes(deps: SignInCardRouteDeps): RouteHandler
const result = deps.threadVisible(auth, threadId) ? await deps.saveTarget(m[1]!, threadId, m[2]!) : HIDDEN;
return json(res, result.status, result.body);
}
- if (method !== "POST") return PASS;
- if (m[3] === "save-login") {
+ if (m[3] === "saved-logins" && method === "GET") {
+ const threadId = url.searchParams.get("threadId") ?? "";
+ res.setHeader("cache-control", "no-store");
+ const result = deps.vault && deps.threadVisible(auth, threadId) ? deps.vault.list(m[1]!, threadId, m[2]!) : { status: 200, body: { choices: [] } };
+ return json(res, result.status, result.body);
+ }
+ if (method !== "POST" || m[3] === "saved-logins") return PASS;
+ if (m[3] === "save-login" || m[3] === "use-login") {
// JSON only, so a form posted from another local page cannot save one.
const mediaType = String(req.headers["content-type"] ?? "").split(";", 1)[0]!.trim().toLowerCase();
if (mediaType !== "application/json") return json(res, 415, { error: "content-type must be application/json" });
const body = await readBody(req, 16_384);
const fields = body && typeof body === "object" && !Array.isArray(body) ? body as Record<string, unknown> : {};
const threadId = String(fields.threadId ?? "");
+ if (m[3] === "use-login") {
+ const used = deps.vault && deps.threadVisible(auth, threadId) ? deps.vault.use(m[1]!, threadId, m[2]!, fields.loginId) : HIDDEN;
+ return json(res, used.status, used.body);
+ }
const result = deps.threadVisible(auth, threadId) ? await deps.saveLogin(m[1]!, threadId, m[2]!, fields, auth) : HIDDEN;
return json(res, result.status, result.body);
}
diff --git a/server/vault-store.ts b/server/vault-store.ts
index 531ab52bc4..1ad24b5859 100644
--- a/server/vault-store.ts
+++ b/server/vault-store.ts
@@ -283,6 +283,11 @@ export class VaultStore {
}
}
+ /** One saved secret with its value, for handing to a bot. */
+ secret(id: string): StoredSecret | null {
+ return this.read().secrets?.find((secret) => secret.id === id) ?? null;
+ }
+
listSecrets(): VaultSecret[] {
return (this.read().secrets ?? []).map(summarizeSecret).sort((a, b) => a.name.localeCompare(b.name));
}
diff --git a/server/vault/choices.test.ts b/server/vault/choices.test.ts
new file mode 100644
index 0000000000..cf95c76d88
--- /dev/null
+++ b/server/vault/choices.test.ts
@@ -0,0 +1,57 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { VaultStore } from "../vault-store.ts";
+import { createSignInVaultChoices, fittingChoices, nameFit } from "./choices.ts";
+
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+describe("which saved names could fit what a bot asked for", () => {
+ it("counts the telling words two names share, never words like key or token alone", () => {
+ expect(nameFit("Stripe secret key", "STRIPE_LIVE_KEY")).toBe(1);
+ expect(nameFit("OpenAI API key", "openai-org-key")).toBe(1);
+ expect(nameFit("API key", "GitHub API token")).toBe(0);
+ expect(fittingChoices("Acme Stripe key", [{ name: "GitHub token" }, { name: "Stripe" }, { name: "Acme Stripe secret" }]).map((one) => one.name))
+ .toEqual(["Acme Stripe secret", "Stripe"]);
+ });
+});
+
+describe("Use a saved login on a sign-in card", () => {
+ function fixture(open = true) {
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-vault-choices-"));
+ dirs.push(dataDir);
+ const logins = new VaultStore({ dataDir });
+ const settled: unknown[] = [];
+ const choices = createSignInVaultChoices({
+ logins, cardBots: (id) => [id, "mate"], openCard: () => (open ? { url: "https://accounts.example.com/login" } : null),
+ settle: (...args) => { settled.push(args); return { status: 200, body: { done: true, resumed: true } }; },
+ });
+ const save = (site: string, username: string, bots: "all" | string[]) =>
+ logins.create({ site, hosts: [site], exactHost: false, username, password: "fake-saved-pass", source: "settings", bots });
+ return { logins, settled, choices, save };
+ }
+
+ it("offers the site's logins the bot may not use yet, by username; picking one lets it and its browser mates use it and answers the card", () => {
+ const one = fixture();
+ const kept = one.save("example.com", "[email protected]", ["quill"]);
+ one.save("example.com", "shared", "all");
+ one.save("example.org", "elsewhere", ["quill"]);
+ expect(one.choices.list("pepper", "t1", "m1")).toEqual({ status: 200, body: { choices: [{ id: kept.id, name: "[email protected]" }] } });
+ expect(one.choices.use("pepper", "t1", "m1", kept.id)).toEqual({ status: 200, body: { done: true, resumed: true } });
+ expect(one.logins.list().find((login) => login.id === kept.id)!.bots).toEqual(["quill", "pepper", "mate"]);
+ expect(one.settled).toEqual([["pepper", "t1", "m1", "done", { site: "example.com" }]]);
+ expect(JSON.stringify(one.choices.list("pepper", "t1", "m1"))).not.toContain("fake-saved-pass");
+ });
+
+ it("offers nothing once the card is answered, and refuses a login it did not offer", () => {
+ const one = fixture(false);
+ const kept = one.save("example.com", "ops", ["quill"]);
+ expect(one.choices.list("pepper", "t1", "m1").body).toEqual({ choices: [] });
+ expect(one.choices.use("pepper", "t1", "m1", kept.id).status).toBe(404);
+ expect(one.settled).toEqual([]);
+ expect(one.logins.list()[0]!.bots).toEqual(["quill"]);
+ });
+});
diff --git a/server/vault/choices.ts b/server/vault/choices.ts
new file mode 100644
index 0000000000..20053d78e7
--- /dev/null
+++ b/server/vault/choices.ts
@@ -0,0 +1,66 @@
+// What a secure card offers under "Use a saved one": Vault items whose names could fit what the bot asked for, by name
+// only. Picking one lets the asking bot use it from then on and answers the card, so nobody types it again.
+import { loginMatchesHost, loginUsableBy, type LoginSummary } from "../../shared/logins.ts";
+import { vaultNameKey, type VaultChoice } from "../../shared/vault.ts";
+import type { VaultStore } from "../vault-store.ts";
+
+/** Words that say what kind of thing it is, not whose: alone they would make every key fit every card. */
+const KIND_WORDS = new Set(["a", "an", "the", "my", "of", "for", "to", "and", "api", "key", "keys", "token", "tokens", "secret", "secrets",
+ "password", "passwords", "access", "value", "id", "auth", "app", "live", "test", "prod"]);
+
+const CHOICES_MAX = 5;
+
+function nameWords(name: string): Set<string> {
+ return new Set(vaultNameKey(name).split(" ").filter((word) => word.length > 1 && !KIND_WORDS.has(word)));
+}
+
+/** How many telling words two names share: "Stripe secret key" and STRIPE_LIVE_KEY share one. */
+export function nameFit(asked: string, name: string): number {
+ const wanted = nameWords(asked);
+ let shared = 0;
+ for (const word of nameWords(name)) if (wanted.has(word)) shared++;
+ return shared;
+}
+
+/** The few items that share a telling word with what was asked, closest first. */
+export function fittingChoices<T extends { name: string }>(asked: string, items: readonly T[]): T[] {
+ return items.map((item) => ({ item, fit: nameFit(asked, item.name) })).filter(({ fit }) => fit > 0)
+ .sort((a, b) => b.fit - a.fit || a.item.name.localeCompare(b.item.name)).slice(0, CHOICES_MAX).map(({ item }) => item);
+}
+
+type Answer = { status: number; body: Record<string, unknown> };
+
+export interface SignInVaultDeps {
+ /** The sign-in card while it still waits in the bot's own browser, else null. */
+ openCard(botId: string, threadId: string, messageId: string): { url: string } | null;
+ logins: Pick<VaultStore, "list" | "update">;
+ /** The bot and every bot that shares its browser: a sign-in there reaches all of them. */
+ cardBots(botId: string): string[];
+ settle(botId: string, threadId: string, messageId: string, outcome: "done", saved: { site: string }): Answer;
+}
+
+/** The sign-in card's "Use a saved login": saved logins for the card's site that the bot may not use yet. */
+export function createSignInVaultChoices(deps: SignInVaultDeps) {
+ const choices = (botId: string, threadId: string, messageId: string): LoginSummary[] => {
+ const card = deps.openCard(botId, threadId, messageId);
+ let host = "";
+ try { host = card ? new URL(card.url).hostname.toLowerCase() : ""; } catch {}
+ if (!host) return [];
+ const bots = deps.cardBots(botId);
+ return deps.logins.list().filter((login) => loginMatchesHost(login, host) && !loginUsableBy(login, bots)).slice(0, CHOICES_MAX);
+ };
+ return {
+ list(botId: string, threadId: string, messageId: string): Answer {
+ const found: VaultChoice[] = choices(botId, threadId, messageId).map((login) => ({ id: login.id, name: login.username || login.site }));
+ return { status: 200, body: { choices: found } };
+ },
+ use(botId: string, threadId: string, messageId: string, loginId: unknown): Answer {
+ const login = choices(botId, threadId, messageId).find((one) => one.id === loginId);
+ if (!login) return { status: 404, body: { error: "That saved login is gone, or this sign-in request was already answered." } };
+ if (login.bots !== "all") deps.logins.update(login.id, { bots: [...new Set([...login.bots, ...deps.cardBots(botId)])] });
+ return deps.settle(botId, threadId, messageId, "done", { site: login.site });
+ },
+ };
+}
+
+export type SignInVaultChoices = ReturnType<typeof createSignInVaultChoices>;
diff --git a/shared/vault.ts b/shared/vault.ts
index 13a18bbf2a..c9d6e98e56 100644
--- a/shared/vault.ts
+++ b/shared/vault.ts
@@ -45,3 +45,11 @@ export interface LinkedSecret {
readOnly: true;
lastUsedAt?: number;
}
+
+/** A saved item a secure card offers under "Use a saved one": its name only. Picking it lets the asking bot use it. */
+export interface VaultChoice {
+ id: string;
+ name: string;
+ /** Who it is linked from, such as 1password; absent for one saved in the Vault. */
+ provider?: string;
+}
diff --git a/src/components/LoginsSettings.tsx b/src/components/LoginsSettings.tsx
deleted file mode 100644
index 1849796a66..0000000000
--- a/src/components/LoginsSettings.tsx
+++ /dev/null
@@ -1,302 +0,0 @@
-import { useEffect, useState, type FormEvent } from "react";
-import { KeyRound, Loader2, LockKeyhole, Plus, RefreshCw, ShieldCheck, Trash2 } from "lucide-react";
-
-import { loginHeldBackFor, type LoginBots, type LoginSummary, type OnePasswordStatus, type OnePasswordVault } from "../../shared/logins";
-import { t } from "@/lib/i18n";
-import { addLogin, changeLogin, connectOnePassword, deleteLogin, disconnectOnePassword, grantVault, listLogins, refreshOnePassword } from "@/lib/logins";
-import { relativeTime } from "@/lib/memory";
-import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
-import { useStore } from "@/state/store";
-import { LoginBotPicker, LoginForm } from "./LoginForm";
-import { Card } from "./SettingsPrimitives";
-
-// Security: a row never shows the password, which no route returns.
-
-const SOURCE_KEYS = {
- card: "settings.logins.source.card",
- settings: "settings.logins.source.settings",
- "1password": "settings.logins.source.1password",
-} as const;
-
-const ROW_BUTTON = "flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50";
-
-export function LoginsSettings() {
- const { state } = useStore();
- const ownerOrAdmin = useOwnerOrAdmin();
- const bots = state.bots.map((bot) => ({ id: bot.id, name: bot.name }));
- const [logins, setLogins] = useState<LoginSummary[] | null>(null);
- const [onePassword, setOnePassword] = useState<OnePasswordStatus>({ connected: false });
- const [error, setError] = useState<string | null>(null);
- const [adding, setAdding] = useState(false);
- const [site, setSite] = useState("");
- const [addBots, setAddBots] = useState<LoginBots>("all");
- const [addExact, setAddExact] = useState(false);
- const [editing, setEditing] = useState<string | null>(null);
- const [editBots, setEditBots] = useState<LoginBots>("all");
- const [editExact, setEditExact] = useState(false);
- const [removeTotp, setRemoveTotp] = useState(false);
- const [deleting, setDeleting] = useState<string | null>(null);
- const [busy, setBusy] = useState(false);
-
- const load = async () => {
- try {
- const answer = await listLogins();
- setLogins(answer.logins);
- setOnePassword(answer.onePassword ?? { connected: false });
- setError(null);
- }
- catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.logins.loadError")); }
- };
- useEffect(() => { if (ownerOrAdmin) void load(); }, [ownerOrAdmin]);
-
- if (ownerOrAdmin === false) {
- return <Card title={t("settings.logins.title")} subtitle={t("settings.logins.adminOnly")} />;
- }
-
- const botNames = (value: LoginBots) => {
- if (value === "all") return t("settings.logins.allBots");
- const names = value.flatMap((id) => bots.find((bot) => bot.id === id)?.name ?? []);
- return names.length ? names.join(", ") : t("settings.logins.noBots");
- };
- const startEdit = (login: LoginSummary) => {
- setAdding(false);
- setDeleting(null);
- setRemoveTotp(false);
- setEditBots(login.bots);
- setEditExact(login.exactHost);
- setEditing(login.id);
- };
- const remove = async (id: string) => {
- if (deleting !== id) { setDeleting(id); return; }
- setBusy(true);
- try { await deleteLogin(id); setDeleting(null); await load(); }
- catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.logins.deleteError")); }
- finally { setBusy(false); }
- };
-
- return (
- <Card title={t("settings.logins.title")} subtitle={t("settings.logins.subtitle")}>
- <div className="flex flex-col gap-3" aria-busy={logins === null || busy}>
- {state.config?.cloudHome === true && <p className="text-[12px] leading-relaxed text-ink-secondary" data-logins-cloud-own>{t("settings.logins.cloudOwn")}</p>}
- {logins === null && !error && <p className="text-[12px] text-ink-secondary">{t("settings.logins.loading")}</p>}
- {logins?.length === 0 && !adding && <p className="text-[12px] leading-relaxed text-ink-secondary">{t("settings.logins.empty")}</p>}
- {!!logins?.length && (
- <ul className="divide-y divide-hairline/30" data-logins-list>
- {logins.map((login) => (
- <li key={login.id} className="flex flex-col gap-2 py-2.5" data-login-row={login.site}>
- <div className="flex min-w-0 items-start gap-2">
- <KeyRound size={14} aria-hidden="true" className="mt-[3px] shrink-0 text-ink-tertiary" />
- <div className="min-w-0 flex-1">
- <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5">
- <span dir="ltr" className="truncate text-[13px] font-medium text-ink" title={login.site}>{login.site}</span>
- {login.hasTotp && (
- <span className="inline-flex items-center gap-0.5 rounded-full bg-ink/[0.07] px-1.5 text-[11px] text-ink-secondary">
- <ShieldCheck size={11} aria-hidden="true" />{t("settings.logins.twoFactor")}
- </span>
- )}
- </div>
- <div dir="auto" className="truncate text-[12px] text-ink-secondary">{login.username || t("settings.logins.noUsername")}</div>
- {signInHostsLine(login) && <div dir="ltr" className="truncate text-[12px] text-ink-tertiary" data-login-hosts>{signInHostsLine(login)}</div>}
- <div className="mt-0.5 text-[12px] leading-snug text-ink-tertiary">
- {[t(SOURCE_KEYS[login.source]), botNames(login.bots),
- login.lastUsedAt ? t("settings.logins.used", { when: relativeTime(login.lastUsedAt) }) : t("settings.logins.neverUsed")].join(" · ")}
- </div>
- {loginHeldBackFor(login, state.bots).length > 0 && (
- <div className="mt-0.5 text-[12px] leading-snug text-warning" data-login-held-back>
- {t("settings.logins.sharedBrowser", { bots: botNames(loginHeldBackFor(login, state.bots)) })}
- </div>
- )}
- </div>
- {login.source !== "1password" && (
- <div className="flex shrink-0 gap-1">
- <button type="button" className={ROW_BUTTON} disabled={busy} onClick={() => startEdit(login)}
- aria-label={t("settings.logins.changeFor", { site: login.site })}>{t("settings.logins.change")}</button>
- <button type="button" className={ROW_BUTTON} disabled={busy} onClick={() => void remove(login.id)}
- aria-label={deleting === login.id ? t("settings.logins.deleteConfirm") : t("settings.logins.deleteFor", { site: login.site })}>
- <Trash2 size={13} />{deleting === login.id ? t("settings.logins.deleteConfirm") : t("settings.logins.delete")}
- </button>
- </div>
- )}
- </div>
- {editing === login.id && (
- <div className="ms-6 rounded-lg bg-inset/60 p-3">
- <LoginForm username={false} replacing submitLabel={t("settings.logins.saveChange")} autoFocus
- onCancel={() => setEditing(null)}
- onSubmit={async (fields) => {
- await changeLogin(login.id, { password: fields.password, totp: fields.totp, removeTotp, bots: editBots, ...(editExact === login.exactHost ? {} : { exactHost: editExact }) });
- setEditing(null);
- await load();
- }}>
- {login.hasTotp && (
- <label className="flex items-center gap-2 text-[13px] text-ink">
- <input type="checkbox" checked={removeTotp} onChange={(event) => setRemoveTotp(event.target.checked)} />
- {t("settings.logins.removeTotp")}
- </label>
- )}
- <ExactHostChoice checked={editExact} onChange={setEditExact}
- label={t("settings.logins.exactHostFor", { hosts: login.hosts.join(", "), site: login.site })} />
- <LoginBotPicker value={editBots} onChange={setEditBots} bots={bots} />
- </LoginForm>
- </div>
- )}
- </li>
- ))}
- </ul>
- )}
- {adding ? (
- <div className="rounded-lg bg-inset/60 p-3">
- <LoginForm site={{ value: site, onChange: setSite }} submitLabel={t("settings.logins.save")} autoFocus
- onCancel={() => setAdding(false)}
- onSubmit={async (fields) => {
- await addLogin(site, fields, addBots, addExact);
- setAdding(false);
- setSite("");
- setAddBots("all");
- setAddExact(false);
- await load();
- }}>
- <ExactHostChoice checked={addExact} onChange={setAddExact} label={t("settings.logins.exactHost")} />
- <LoginBotPicker value={addBots} onChange={setAddBots} bots={bots} />
- </LoginForm>
- </div>
- ) : (
- <button type="button" className="ui-button ui-button-md self-start" disabled={logins === null}
- onClick={() => { setEditing(null); setDeleting(null); setAdding(true); }}>
- <Plus size={14} />{t("settings.logins.add")}
- </button>
- )}
- <p className="text-[12px] leading-relaxed text-ink-tertiary">{t("settings.logins.limits")}</p>
- {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
- <OnePasswordConnection status={onePassword} disabled={logins === null} bots={bots} botNames={botNames}
- onChange={async (next) => { setOnePassword(next); await load(); }} />
- </div>
- </Card>
- );
-}
-
-/** Where a login signs in beyond its site's own pages, or that it is kept to those hosts. */
-function signInHostsLine(login: LoginSummary): string | null {
- if (login.exactHost) return t("settings.logins.onlyOn", { hosts: login.hosts.join(", ") });
- const elsewhere = login.hosts.filter((host) => host !== login.site);
- return elsewhere.length ? t("settings.logins.signsInOn", { hosts: elsewhere.join(", ") }) : null;
-}
-
-function ExactHostChoice({ checked, onChange, label }: { checked: boolean; onChange: (checked: boolean) => void; label: string }) {
- return (
- <label className="flex items-start gap-2 text-[13px] leading-snug text-ink">
- <input type="checkbox" name="exactHost" className="mt-[2px]" checked={checked} onChange={(event) => onChange(event.target.checked)} />
- {label}
- </label>
- );
-}
-
-function VaultAccess({ vault, bots, botNames, disabled, onChange }: {
- vault: OnePasswordVault;
- bots: ReadonlyArray<{ id: string; name: string }>;
- botNames: (value: LoginBots) => string;
- disabled: boolean;
- onChange: (status: OnePasswordStatus) => Promise<void>;
-}) {
- const [editing, setEditing] = useState(false);
- const [value, setValue] = useState<LoginBots>(vault.bots);
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const save = async () => {
- setBusy(true);
- setError(null);
- try { await onChange(await grantVault(vault.id, value)); setEditing(false); }
- catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.logins.onePassword.error")); }
- finally { setBusy(false); }
- };
- return (
- <li className="flex flex-col gap-2 py-2" data-vault={vault.title}>
- <div className="flex min-w-0 items-start gap-2">
- <div className="min-w-0 flex-1">
- <div className="truncate text-[13px] font-medium text-ink">{vault.title}</div>
- <div className="text-[12px] text-ink-tertiary">{t("settings.logins.onePassword.vaultUse", { count: String(vault.items), who: botNames(vault.bots) })}</div>
- </div>
- {!editing && (
- <button type="button" className={ROW_BUTTON} disabled={disabled || busy} onClick={() => { setValue(vault.bots); setEditing(true); }}
- aria-label={t("settings.logins.onePassword.changeVault", { vault: vault.title })}>{t("settings.logins.change")}</button>
- )}
- </div>
- {editing && (
- <div className="flex flex-col gap-2 rounded-lg bg-inset/60 p-3">
- <LoginBotPicker value={value} onChange={setValue} bots={bots} disabled={busy} />
- {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
- <div className="flex flex-wrap justify-end gap-2">
- <button type="button" className="ui-button ui-button-md" disabled={busy} onClick={() => setEditing(false)}>{t("logins.cancel")}</button>
- <button type="button" className="ui-button ui-button-md ui-button-primary" disabled={busy} onClick={() => void save()}>{t("settings.logins.saveChange")}</button>
- </div>
- </div>
- )}
- </li>
- );
-}
-
-function OnePasswordConnection({ status, disabled, bots, botNames, onChange }: {
- status: OnePasswordStatus;
- disabled: boolean;
- bots: ReadonlyArray<{ id: string; name: string }>;
- botNames: (value: LoginBots) => string;
- onChange: (status: OnePasswordStatus) => Promise<void>;
-}) {
- const [token, setToken] = useState("");
- const [busy, setBusy] = useState<"connect" | "refresh" | "disconnect" | null>(null);
- const [error, setError] = useState<string | null>(null);
- const run = async (kind: NonNullable<typeof busy>, work: () => Promise<OnePasswordStatus>) => {
- if (busy) return;
- setBusy(kind);
- setError(null);
- try { await onChange(await work()); if (kind === "connect") setToken(""); }
- catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.logins.onePassword.error")); }
- finally { setBusy(null); }
- };
- const connect = (event: FormEvent) => {
- event.preventDefault();
- if (token.trim()) void run("connect", () => connectOnePassword(token.trim()));
- };
- return (
- <section className="mt-1 flex flex-col gap-2 border-t border-hairline/30 pt-3" aria-label={t("settings.logins.onePassword.title")} data-onepassword>
- <div className="text-[13px] font-medium text-ink">{t("settings.logins.onePassword.title")}</div>
- {status.connected ? (
- <>
- <p className="text-[13px] leading-snug text-ink-secondary">
- {t("settings.logins.onePassword.connected", { vaults: (status.vaults ?? []).map((vault) => vault.title).join(", ") || "—", count: String(status.items ?? 0) })}
- </p>
- {status.error && <p role="alert" className="text-[12px] text-danger">{status.error}</p>}
- {!!status.vaults?.length && (
- <ul className="divide-y divide-hairline/30" aria-label={t("settings.logins.onePassword.vaults")}>
- {status.vaults.map((vault) => <VaultAccess key={vault.id} vault={vault} bots={bots} botNames={botNames} disabled={disabled} onChange={onChange} />)}
- </ul>
- )}
- <div className="flex flex-wrap gap-2">
- <button type="button" className="ui-button ui-button-md" disabled={disabled || busy !== null} onClick={() => void run("refresh", refreshOnePassword)}>
- {busy === "refresh" ? <Loader2 size={13} className="animate-spin" /> : <RefreshCw size={13} />}{t("settings.logins.onePassword.refresh")}
- </button>
- <button type="button" className="ui-button ui-button-md" disabled={disabled || busy !== null} onClick={() => void run("disconnect", disconnectOnePassword)}>
- {t("settings.logins.onePassword.disconnect")}
- </button>
- </div>
- </>
- ) : (
- <form className="flex flex-col gap-2" onSubmit={connect}>
- <p className="text-[12px] leading-relaxed text-ink-secondary">{t("settings.logins.onePassword.guide")}</p>
- <div className="flex flex-wrap gap-2">
- <input name="onePasswordToken" type="password" autoComplete="off" spellCheck={false} maxLength={8192} value={token}
- onChange={(event) => setToken(event.target.value)} disabled={disabled || busy !== null}
- aria-label={t("settings.logins.onePassword.token")} placeholder={t("settings.logins.onePassword.token")}
- className="min-w-0 flex-1 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5 text-[13px] text-ink outline-none placeholder:text-ink-tertiary focus:border-accent disabled:opacity-60" />
- <button type="submit" className="ui-button ui-button-md ui-button-primary" disabled={disabled || busy !== null || !token.trim()}>
- {busy === "connect" && <Loader2 size={13} className="animate-spin" />}{t("settings.logins.onePassword.connect")}
- </button>
- </div>
- </form>
- )}
- <p className="flex items-start gap-1 text-[12px] leading-snug text-ink-tertiary">
- <LockKeyhole size={11} aria-hidden="true" className="mt-[3px] shrink-0" /> {t("settings.logins.onePassword.note")}
- </p>
- {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
- </section>
- );
-}
diff --git a/src/components/SecretRequestCard.test.ts b/src/components/SecretRequestCard.test.ts
index 7f0da81ec8..50a898e72c 100644
--- a/src/components/SecretRequestCard.test.ts
+++ b/src/components/SecretRequestCard.test.ts
@@ -25,6 +25,7 @@ vi.mock("@/state/store", async (original) => ({
vi.mock("@/lib/analytics", () => ({ track: fixture.track }));
import { SecretRequestCard } from "./SecretRequestCard";
+import { VaultChoices } from "./VaultChoices";
import { setLocale } from "@/lib/i18n";
import { CREDENTIAL_TARGETS } from "../../shared/credential-request";
@@ -399,3 +400,20 @@ describe("SecretRequestCard custom secrets", () => {
expect(ref).toContain("MausBot keeps it for one use by its own tools. Your bot never sees it");
});
});
+
+describe("SecretRequestCard saved secrets", () => {
+ type Props = { children?: ReactNode };
+ const nodes = (tree: ReactNode): Array<ReactElement<Props>> =>
+ Children.toArray(tree).flatMap((child) => isValidElement<Props>(child) ? [child, ...nodes(child.props.children)] : []);
+ const offered = (secret: Record<string, unknown>) => {
+ Object.assign(fixture, { counting: true, index: 0, values: [] });
+ try { return nodes(SecretRequestCard({ botId: "bot-1", threadId: "thread-1", message: secretCard(secret) })).some((node) => node.type === VaultChoices); }
+ finally { fixture.counting = false; }
+ };
+
+ it("offers the Vault's secrets on a card for any other secret, never for a key the app keeps or a mailbox", () => {
+ expect(offered({ target: "customSecret", label: "Stripe secret key", delivery: "ref", helpUrl: "" })).toBe(true);
+ expect(offered({})).toBe(false);
+ expect(offered({ target: "customSecret", label: "Connect your mailbox", delivery: "email", helpUrl: "" })).toBe(false);
+ });
+});
diff --git a/src/components/SecretRequestCard.tsx b/src/components/SecretRequestCard.tsx
index 9581c65905..9effa958e4 100644
--- a/src/components/SecretRequestCard.tsx
+++ b/src/components/SecretRequestCard.tsx
@@ -12,6 +12,7 @@ import { EmailConnectForm, type EmailConnectRefusal } from "./EmailCard";
import { EmailOutgoingRequestForm, EmailRequestSettled } from "./EmailRequestCard";
import type { EmailConnectRequest, EmailOutgoingFields } from "../../shared/email";
import { productName } from "@/lib/brand";
+import { VaultChoices } from "./VaultChoices";
// Security: the value goes straight to the host's settings, never into the chat.
@@ -263,7 +264,8 @@ export function SecretRequestCard({
submitStyle={askPrimary(color).style}
footer={<span className="flex items-center gap-1 text-[12px] text-ink-tertiary"><LockKeyhole size={11} /> {t("secretCard.email")}</span>}
/>
- ) : (
+ ) : (<>
+ {custom && <VaultChoices kind="secret" botId={botId} botName={authorName} threadId={threadId} messageId={message.id} />}
<form onSubmit={(event) => void save(event)}>
<div className="flex flex-wrap gap-2">
<input
@@ -300,7 +302,7 @@ export function SecretRequestCard({
)}
</div>
</form>
- )}
+ </>)}
{error && <p role="alert" className="mt-2 text-[12px] text-danger">{error}</p>}
</AskCard>
);
diff --git a/src/components/SettingsModal.keys.dom.test.ts b/src/components/SettingsModal.keys.dom.test.ts
index 31b612aebf..af479dbe3b 100644
--- a/src/components/SettingsModal.keys.dom.test.ts
+++ b/src/components/SettingsModal.keys.dom.test.ts
@@ -49,7 +49,7 @@ vi.mock("./PeopleSection", () => ({ PeopleSection: marker("people") }));
vi.mock("./ActivitySection", () => ({ ActivitySection: marker("activity") }));
vi.mock("./UsageSection", () => ({ UsageSection: marker("usage") }));
vi.mock("./ImportSettings", () => ({ ImportSettings: marker("import") }));
-vi.mock("./LoginsSettings", () => ({ LoginsSettings: marker("logins") }));
+vi.mock("./VaultSettings", () => ({ VaultSettings: marker("logins") }));
vi.mock("./BrowserSettingsRows", () => ({ BuiltInBrowserRow: marker("browser"), ServerSitesRow: () => null }));
const { SettingsModal } = await import("./SettingsModal");
diff --git a/src/components/SettingsModal.search.test.ts b/src/components/SettingsModal.search.test.ts
index 6c28d34f30..c6eab3409f 100644
--- a/src/components/SettingsModal.search.test.ts
+++ b/src/components/SettingsModal.search.test.ts
@@ -25,7 +25,7 @@ for (const [path, name] of [
["./EnginesSettings", "EnginesSettings"], ["./RemoteComputerSection", "RemoteComputerSection"], ["./PhoneDevicesSection", "PhoneDevicesSection"],
["./ServerPairingCard", "ServerPairingCard"], ["./LocalComputerSection", "LocalComputerSection"], ["./CloudAccountSettings", "CloudAccountSettings"],
["./PeopleSection", "PeopleSection"], ["./ActivitySection", "ActivitySection"], ["./UsageSection", "UsageSection"], ["./ImportSettings", "ImportSettings"],
- ["./CustomDomainSettings", "CustomDomainSettings"], ["./LoginsSettings", "LoginsSettings"], ["./PlanUsage", "PlanUsageSummary"],
+ ["./CustomDomainSettings", "CustomDomainSettings"], ["./VaultSettings", "VaultSettings"], ["./PlanUsage", "PlanUsageSummary"],
] as const) vi.doMock(path, async (importOriginal) => ({ ...await importOriginal<Record<string, unknown>>(), [name]: () => null }));
const { SettingsModal } = await import("./SettingsModal");
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index eb16c07ec3..eb9ec642cb 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -29,7 +29,7 @@ import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { currentPhonePairingTarget, phonePairingSettingsAction } from "@/lib/phone-pairing";
import { CustomDomainSettings } from "./CustomDomainSettings";
import { BuiltInBrowserRow, ServerSitesRow } from "./BrowserSettingsRows";
-import { LoginsSettings } from "./LoginsSettings";
+import { VaultSettings } from "./VaultSettings";
import { RemoteComputerSection } from "./RemoteComputerSection";
import { ConnectedWorkspacesSettings } from "./ConnectedWorkspacesSettings";
import { PlaceLookCard } from "./PlaceLookCard";
@@ -99,7 +99,7 @@ export const SECTIONS: Array<{
{ id: "skills", group: "ai", labelKey: "settings.section.skills", icon: BookOpen, keywords: ["skills", "library", "assign", "agent skills", "skill md"] },
{ id: "desktopWorkspaces", group: "computers", labelKey: "settings.section.desktopWorkspaces", icon: Building2, keywords: ["workspace", "cloud", "hosted", "vps", "server", "servers", "connect", "pair", "switch", "local"] },
{ id: "computer", group: "computers", labelKey: "settings.section.computer", icon: Monitor, keywords: ["vm", "virtual", "desktop", "browser", "built-in browser", "profiles", "browser profiles"] },
- { id: "logins", group: "computers", labelKey: "settings.section.logins", icon: LockKeyhole, keywords: ["logins", "login", "passwords", "password", "sign in", "2fa", "one-time code", "totp", "fill_login", "1password", "vault"] },
+ { id: "logins", group: "computers", labelKey: "settings.section.vault", icon: LockKeyhole, keywords: ["vault", "logins", "login", "passwords", "password", "sign in", "2fa", "one-time code", "totp", "fill_login", "1password", "password manager", "secrets", "secret", "token", ".env", "env"] },
{ id: "cloudAccount", group: "account", labelKey: "settings.section.cloudAccount", icon: Cloud, keywords: ["cloud", "my cloud", "account", "personal", "sign in", "pro", "subscription", "billing", "sync", "send", "this computer", "bots", "logins", "1password"] },
{ id: "organization", group: "account", labelKey: "settings.section.organization", icon: Building2, keywords: ["company", "organization", "organisation", "sign in", "enroll", "managed", "models", "disconnect"] },
{ id: "usage", group: "account", labelKey: "settings.section.usage", icon: Coins, keywords: ["tokens", "cost", "billing", "plan", "quota", "remaining", "weekly", "5-hour", "model", "used"] },
@@ -425,7 +425,7 @@ export function SettingsModal() {
case "computer":
return <><BuiltInBrowserRow /><ServerSitesRow /><BrowserProfilesRow /><AdminOnly><LocalComputerSection /></AdminOnly></>;
case "logins":
- return <LoginsSettings />;
+ return <VaultSettings />;
case "usage":
return <AdminOnly note="settings.adminOnly.usage"><UsageSection /></AdminOnly>;
case "skills":
diff --git a/src/components/SettingsSimplePages.member.test.ts b/src/components/SettingsSimplePages.member.test.ts
index fa4cefee8f..7221ae8fd2 100644
--- a/src/components/SettingsSimplePages.member.test.ts
+++ b/src/components/SettingsSimplePages.member.test.ts
@@ -15,7 +15,7 @@ vi.mock("./CloudUsageMeter", () => ({ useCloudUsageSettings: () => ({ usage: nul
vi.mock("./ProIntroduction", () => ({ useCloudPlan: () => null, CloudPlanRow: () => null, CloudPlanFootnote: () => null }));
vi.mock("./BrowserSettingsRows", () => ({ BuiltInBrowserRow: () => null, ServerSitesRow: () => null }));
vi.mock("./AppSettingsRows", async (original) => ({ ...await original<object>(), BrowserProfilesRow: () => null }));
-vi.mock("./LoginsSettings", () => ({ LoginsSettings: () => null }));
+vi.mock("./VaultSettings", () => ({ VaultSettings: () => null }));
const { SimpleAiPage, SimpleBillingPage, SimpleComputerPage } = await import("./SettingsSimplePages");
diff --git a/src/components/SettingsSimplePages.tsx b/src/components/SettingsSimplePages.tsx
index 4579356e2d..7489bed875 100644
--- a/src/components/SettingsSimplePages.tsx
+++ b/src/components/SettingsSimplePages.tsx
@@ -18,7 +18,7 @@ import { LocalComputerSection } from "./LocalComputerSection";
import { PeopleSection } from "./PeopleSection";
import { ActivitySection } from "./ActivitySection";
import { BuiltInBrowserRow, ServerSitesRow } from "./BrowserSettingsRows";
-import { LoginsSettings } from "./LoginsSettings";
+import { VaultSettings } from "./VaultSettings";
import { OrganizationSettings } from "./OrganizationSettings";
import { CloudPlanRow, CloudPlanFootnote, useCloudPlan } from "./ProIntroduction";
import { CloudUsageDetails, CloudUsageSummaryView, useCloudUsageSettings } from "./CloudUsageMeter";
@@ -225,7 +225,7 @@ export function SimpleComputerPage({ has, remoteAccess, servers, disclose }: { h
<BrowserProfilesRow />
</SettingsGroup>
)}
- {has("logins") && <div data-settings-block="logins" className="scroll-mt-4"><LoginsSettings /></div>}
+ {has("logins") && <div data-settings-block="logins" className="scroll-mt-4"><VaultSettings /></div>}
{(has("companion") || has("desktopWorkspaces")) && (
<SettingsDisclosureRow title={t("settings.simple.computer.elsewhere")} block="elsewhere" {...disclose("computer-elsewhere")}>
{has("desktopWorkspaces") && <div data-settings-block="desktopWorkspaces" className="flex scroll-mt-4 flex-col gap-4">{servers}</div>}
diff --git a/src/components/SignInRequestCard.test.ts b/src/components/SignInRequestCard.test.ts
index 3f6a7e1fae..3a0acc4516 100644
--- a/src/components/SignInRequestCard.test.ts
+++ b/src/components/SignInRequestCard.test.ts
@@ -30,6 +30,7 @@ vi.mock("@/lib/logins", () => ({
import { LoginForm } from "./LoginForm";
import { SignInBanner, SignInRequestCard } from "./SignInRequestCard";
+import { VaultChoices } from "./VaultChoices";
const card = (signIn: Record<string, unknown> = {}): Message => ({
id: "card-1",
@@ -235,3 +236,13 @@ describe("SignInBanner", () => {
expect(takeControl.onClick).toHaveBeenCalledOnce();
});
});
+
+describe("SignInRequestCard saved logins", () => {
+ it("offers the Vault's logins only where they can be filled, the bot's own browser, and not while one is being typed", () => {
+ const offered = (signIn?: Record<string, unknown>) => tree(signIn).some((node) => node.type === VaultChoices);
+ expect(offered()).toBe(true);
+ expect(offered({ place: "vm" })).toBe(false);
+ fixture.setters = []; fixture.states = { 2: true };
+ expect(offered()).toBe(false);
+ });
+});
diff --git a/src/components/SignInRequestCard.tsx b/src/components/SignInRequestCard.tsx
index f126511712..25932d4a0a 100644
--- a/src/components/SignInRequestCard.tsx
+++ b/src/components/SignInRequestCard.tsx
@@ -11,6 +11,7 @@ import { answerSignIn, signInHostIsHere } from "@/lib/sign-in";
import { useStore, type Bot, type Message } from "@/state/store";
import { ASK_CHIP, ASK_CHIP_IDLE, askPrimary, ASK_QUIET_BUTTON, AskCard, AskSettledLine, returnFocusToComposer } from "./AskCard";
import { LoginForm } from "./LoginForm";
+import { VaultChoices } from "./VaultChoices";
// Security: a saved login is encrypted on the server and filled by fill_login; neither the bot nor any screen ever gets
// it back.
@@ -158,6 +159,7 @@ export function SignInRequestCard({
<bdi dir="auto">“{card.reason}”</bdi> <span className="text-ink-tertiary">— {botName}</span>
</blockquote>
)}
+ {canSave && !saving && <div className="mt-2.5"><VaultChoices kind="login" botId={botId} botName={botName} threadId={threadId} messageId={message.id} /></div>}
{saving ? (
<div className="mt-2.5" data-testid="sign-in-save">
<p className="mb-2 text-[13px] leading-snug text-ink-secondary">{mates.length
diff --git a/src/components/VaultChoices.test.ts b/src/components/VaultChoices.test.ts
new file mode 100644
index 0000000000..5ccf704edd
--- /dev/null
+++ b/src/components/VaultChoices.test.ts
@@ -0,0 +1,63 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({ api: vi.fn() }));
+vi.mock("@/state/store", async (importOriginal) => ({ ...await importOriginal<typeof import("@/state/store")>(), api: fixture.api }));
+const { VaultChoices } = await import("./VaultChoices");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement;
+let root: Root;
+beforeEach(() => {
+ fixture.api.mockReset();
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+});
+
+async function render(kind: "secret" | "login") {
+ await act(async () => root.render(createElement(VaultChoices, { kind, botId: "pepper", botName: "Pepper", threadId: "t 1", messageId: "m1" })));
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+}
+
+describe("Use a saved one on a secure card", () => {
+ it("lists what could fit by name, and picking one answers the card with it", async () => {
+ fixture.api.mockResolvedValueOnce({ choices: [{ id: "s1", name: "STRIPE_LIVE_KEY" }, { id: "1password:v1:i1#Stripe", name: "Stripe", provider: "1password" }] }).mockResolvedValueOnce({ provided: true });
+ await render("secret");
+ expect(fixture.api).toHaveBeenCalledWith("/api/bots/pepper/secret-cards/m1/saved?threadId=t%201");
+ const box = host.querySelector('[data-vault-choices="secret"]')!;
+ expect(box.textContent).toBe("Use a saved oneSTRIPE_LIVE_KEYStripe· 1PasswordPepper can use the one you pick from now on.");
+ await act(async () => host.querySelector<HTMLButtonElement>('[data-vault-choice="s1"]')!.click());
+ expect(fixture.api).toHaveBeenNthCalledWith(2, "/api/bots/pepper/secret-cards/m1/use", { method: "POST", body: JSON.stringify({ threadId: "t 1", itemId: "s1" }) });
+ });
+
+ it("asks the sign-in card's own paths for a saved login", async () => {
+ fixture.api.mockResolvedValueOnce({ choices: [{ id: "l1", name: "[email protected]" }] }).mockResolvedValueOnce({ done: true });
+ await render("login");
+ expect(host.textContent).toContain("Use a saved login");
+ await act(async () => host.querySelector<HTMLButtonElement>('[data-vault-choice="l1"]')!.click());
+ expect(fixture.api).toHaveBeenNthCalledWith(2, "/api/bots/pepper/sign-in-cards/m1/use-login", { method: "POST", body: JSON.stringify({ threadId: "t 1", loginId: "l1" }) });
+ });
+
+ it("shows nothing when nothing fits or this person may not change the Vault", async () => {
+ fixture.api.mockResolvedValueOnce({ choices: [] });
+ await render("secret");
+ expect(host.innerHTML).toBe("");
+ fixture.api.mockRejectedValueOnce(new Error("admin only"));
+ await render("login");
+ expect(host.innerHTML).toBe("");
+ });
+
+ it("says why a pick failed, so the person can type it instead", async () => {
+ fixture.api.mockResolvedValueOnce({ choices: [{ id: "s1", name: "Stripe" }] }).mockRejectedValueOnce(new Error("That saved secret is gone."));
+ await render("secret");
+ await act(async () => host.querySelector<HTMLButtonElement>('[data-vault-choice="s1"]')!.click());
+ expect(host.querySelector("[role=alert]")!.textContent).toBe("That saved secret is gone.");
+ });
+});
diff --git a/src/components/VaultChoices.tsx b/src/components/VaultChoices.tsx
new file mode 100644
index 0000000000..9e23f133d2
--- /dev/null
+++ b/src/components/VaultChoices.tsx
@@ -0,0 +1,61 @@
+import { useEffect, useState } from "react";
+import { KeyRound, Loader2 } from "lucide-react";
+
+import type { VaultChoice } from "../../shared/vault";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { savedChoices, useSaved, type ChoiceKind } from "@/lib/vault";
+import { ASK_CHIP, ASK_CHIP_IDLE, returnFocusToComposer } from "./AskCard";
+
+// Security: names only. Picking one never brings its value here: the server hands it to the bot and answers the card.
+
+/** "Use a saved one" on a secure card: shown only when the Vault holds something that could fit and this person may
+ * change the Vault. */
+export function VaultChoices({ kind, botId, botName, threadId, messageId }: {
+ kind: ChoiceKind;
+ botId: string;
+ botName?: string;
+ threadId: string;
+ messageId: string;
+}) {
+ const [choices, setChoices] = useState<VaultChoice[]>([]);
+ const [using, setUsing] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => {
+ let live = true;
+ savedChoices(kind, { botId, threadId, messageId }).then((found) => { if (live) setChoices(found); }, () => { if (live) setChoices([]); });
+ return () => { live = false; };
+ }, [kind, botId, threadId, messageId]);
+
+ if (!choices.length) return null;
+ const use = async (choice: VaultChoice) => {
+ if (using) return;
+ setUsing(choice.id);
+ setError(null);
+ try {
+ await useSaved(kind, { botId, threadId, messageId }, choice.id);
+ returnFocusToComposer();
+ } catch (cause) {
+ setError(cause instanceof Error && cause.message ? cause.message : t("vault.choices.error"));
+ } finally {
+ setUsing(null);
+ }
+ };
+ return (
+ <div className="mb-2.5 flex flex-col gap-1.5" data-vault-choices={kind}>
+ <div className="text-[12px] font-medium text-ink-secondary">{t(kind === "login" ? "vault.choices.login" : "vault.choices.secret")}</div>
+ <div className="flex flex-wrap gap-1.5">
+ {choices.map((choice) => (
+ <button key={choice.id} type="button" disabled={using !== null} onClick={() => void use(choice)} data-vault-choice={choice.id}
+ className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>
+ {using === choice.id ? <Loader2 size={13} className="animate-spin" /> : <KeyRound size={13} aria-hidden="true" />}
+ <bdi dir="auto" className="truncate">{choice.name}</bdi>
+ {choice.provider === "1password" && <span className="text-ink-tertiary">· 1Password</span>}
+ </button>
+ ))}
+ </div>
+ {botName && <p className="text-[12px] leading-snug text-ink-tertiary">{t("vault.choices.note", { bot: botName })}</p>}
+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
+ </div>
+ );
+}
diff --git a/src/components/VaultSecretForms.tsx b/src/components/VaultSecretForms.tsx
new file mode 100644
index 0000000000..506bf392c0
--- /dev/null
+++ b/src/components/VaultSecretForms.tsx
@@ -0,0 +1,122 @@
+import { useState, type FormEvent, type ReactNode } from "react";
+import { Loader2, LockKeyhole } from "lucide-react";
+
+import type { LoginBots } from "../../shared/logins";
+import { VAULT_SECRET_NAME_MAX, type VaultSecret } from "../../shared/vault";
+import { t } from "@/lib/i18n";
+import { addSecret, changeSecret, importEnv, parseEnv } from "@/lib/vault";
+import { LoginBotPicker } from "./LoginForm";
+
+// Security: what was typed is dropped once saved, and a saved value is never shown: it can only be replaced.
+
+const FIELD = "w-full min-w-0 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5 text-[13px] text-ink outline-none placeholder:text-ink-tertiary focus:border-accent disabled:opacity-60";
+const LABEL = "flex flex-col gap-1 text-[12px] font-medium text-ink-secondary";
+
+type Bots = ReadonlyArray<{ id: string; name: string }>;
+
+function Shell({ onSubmit, onCancel, pending, error, submitLabel, children, form }: {
+ onSubmit: (event: FormEvent) => void;
+ onCancel: () => void;
+ pending: boolean;
+ error: string | null;
+ submitLabel: string;
+ children: ReactNode;
+ form: string;
+}) {
+ return (
+ <form onSubmit={onSubmit} className="flex flex-col gap-2.5" aria-busy={pending} {...{ [`data-${form}`]: "" }}>
+ {children}
+ <p className="flex items-start gap-1 text-[12px] leading-snug text-ink-tertiary">
+ <LockKeyhole size={11} aria-hidden="true" className="mt-[3px] shrink-0" /> {t("settings.vault.secret.private")}
+ </p>
+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
+ <div className="flex flex-wrap justify-end gap-2">
+ <button type="button" onClick={onCancel} disabled={pending} className="ui-button ui-button-md">{t("logins.cancel")}</button>
+ <button type="submit" disabled={pending} className="ui-button ui-button-md ui-button-primary inline-flex items-center gap-1.5">
+ {pending && <Loader2 size={13} className="animate-spin" />}{submitLabel}
+ </button>
+ </div>
+ </form>
+ );
+}
+
+/** Adds a secret, or changes one: its name, its value (empty keeps the saved one) and who may use it. */
+export function SecretForm({ secret, bots, onCancel, onSaved }: { secret?: VaultSecret; bots: Bots; onCancel: () => void; onSaved: () => Promise<void> }) {
+ const [name, setName] = useState(secret?.name ?? "");
+ const [value, setValue] = useState("");
+ const [who, setWho] = useState<LoginBots>(secret?.bots ?? "all");
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const submit = async (event: FormEvent) => {
+ event.preventDefault();
+ if (pending) return;
+ setPending(true);
+ setError(null);
+ try {
+ if (secret) await changeSecret(secret.id, { ...(name.trim() !== secret.name ? { name: name.trim() } : {}), value, bots: who });
+ else await addSecret(name.trim(), value, who);
+ setValue("");
+ await onSaved();
+ } catch (cause) {
+ setError(cause instanceof Error && cause.message ? cause.message : t("settings.vault.secret.saveError"));
+ } finally {
+ setPending(false);
+ }
+ };
+ return (
+ <Shell form="secret-form" onSubmit={(event) => void submit(event)} onCancel={onCancel} pending={pending} error={error}
+ submitLabel={t(secret ? "settings.logins.saveChange" : "settings.vault.secret.save")}>
+ <label className={LABEL}>
+ {t("settings.vault.secret.name")}
+ <input name="secretName" type="text" autoComplete="off" spellCheck={false} required maxLength={VAULT_SECRET_NAME_MAX} value={name} autoFocus
+ placeholder={t("settings.vault.secret.namePlaceholder")} onChange={(event) => setName(event.target.value)} disabled={pending} className={FIELD} />
+ <span className="text-[12px] font-normal leading-snug text-ink-tertiary">{t("settings.vault.secret.nameHint")}</span>
+ </label>
+ <label className={LABEL}>
+ {t(secret ? "settings.vault.secret.valueKeep" : "settings.vault.secret.value")}
+ <input name="secretValue" type="password" autoComplete="new-password" spellCheck={false} required={!secret} value={value} placeholder="••••••••"
+ onChange={(event) => setValue(event.target.value)} disabled={pending} className={FIELD} />
+ </label>
+ <LoginBotPicker value={who} onChange={setWho} bots={bots} disabled={pending} />
+ </Shell>
+ );
+}
+
+/** A pasted .env file: each NAME=value line becomes a secret named NAME. */
+export function EnvImportForm({ bots, onCancel, onSaved }: { bots: Bots; onCancel: () => void; onSaved: () => Promise<void> }) {
+ const [text, setText] = useState("");
+ const [who, setWho] = useState<LoginBots>("all");
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [done, setDone] = useState<number | null>(null);
+ const submit = async (event: FormEvent) => {
+ event.preventDefault();
+ if (pending) return;
+ const lines = parseEnv(text);
+ if (!lines.length) { setError(t("settings.vault.env.none")); return; }
+ setPending(true);
+ setError(null);
+ setDone(null);
+ try {
+ setDone(await importEnv(lines, who));
+ setText("");
+ } catch (cause) {
+ setError(cause instanceof Error && cause.message ? cause.message : t("settings.vault.secret.saveError"));
+ } finally {
+ setPending(false);
+ await onSaved().catch(() => {});
+ }
+ };
+ return (
+ <Shell form="env-form" onSubmit={(event) => void submit(event)} onCancel={onCancel} pending={pending} error={error} submitLabel={t("settings.vault.env.submit")}>
+ <label className={LABEL}>
+ {t("settings.vault.env.label")}
+ <textarea name="envText" rows={5} autoComplete="off" spellCheck={false} autoFocus value={text} onChange={(event) => setText(event.target.value)}
+ disabled={pending} placeholder="STRIPE_SECRET_KEY=…" dir="ltr" className={`${FIELD} font-mono`} />
+ <span className="text-[12px] font-normal leading-snug text-ink-tertiary">{t("settings.vault.env.hint")}</span>
+ </label>
+ <LoginBotPicker value={who} onChange={setWho} bots={bots} disabled={pending} />
+ {done !== null && <p role="status" className="text-[12px] text-ink-secondary">{t("settings.vault.env.done", { count: String(done) })}</p>}
+ </Shell>
+ );
+}
diff --git a/src/components/LoginsSettings.test.ts b/src/components/VaultSettings.test.ts
similarity index 65%
rename from src/components/LoginsSettings.test.ts
rename to src/components/VaultSettings.test.ts
index 4bafcc722e..96f349bd32 100644
--- a/src/components/LoginsSettings.test.ts
+++ b/src/components/VaultSettings.test.ts
@@ -3,14 +3,14 @@ import { act, createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const fixture = vi.hoisted(() => ({ api: vi.fn(), admin: true as boolean | null, config: null as { cloudHome?: boolean } | null }));
+const fixture = vi.hoisted(() => ({ api: vi.fn(), dispatch: vi.fn(), admin: true as boolean | null, config: null as { cloudHome?: boolean } | null }));
vi.mock("@/state/store", async (importOriginal) => ({
...await importOriginal<typeof import("@/state/store")>(),
api: fixture.api,
- useStore: () => ({ state: { bots: [{ id: "pepper", name: "Pepper" }, { id: "quill", name: "Quill" }], config: fixture.config }, dispatch: vi.fn() }),
+ useStore: () => ({ state: { bots: [{ id: "pepper", name: "Pepper" }, { id: "quill", name: "Quill" }], config: fixture.config }, dispatch: fixture.dispatch }),
}));
vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.admin }));
-const { LoginsSettings } = await import("./LoginsSettings");
+const { VaultSettings } = await import("./VaultSettings");
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let host: HTMLDivElement;
@@ -24,6 +24,7 @@ const OFF = { connected: false };
beforeEach(() => {
fixture.api.mockReset();
+ fixture.dispatch.mockReset();
fixture.admin = true;
fixture.config = null;
host = document.createElement("div");
@@ -36,7 +37,7 @@ afterEach(() => {
});
async function render() {
- await act(async () => root.render(createElement(LoginsSettings)));
+ await act(async () => root.render(createElement(VaultSettings)));
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
}
const button = (label: string) => [...host.querySelectorAll("button")].find((candidate) => (candidate.getAttribute("aria-label") ?? candidate.textContent) === label)!;
@@ -53,11 +54,11 @@ async function submit() {
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
}
-describe("Settings → Logins", () => {
+describe("Settings → Vault: logins", () => {
it("lists each login by site, the sign-in hosts it also fills on, username, 2FA, source, who may use it and last use", async () => {
fixture.api.mockResolvedValueOnce({ logins: [CARD_LOGIN, SHARED_LOGIN, TENANT_LOGIN], onePassword: OFF });
await render();
- expect(fixture.api).toHaveBeenCalledWith("/api/logins");
+ expect(fixture.api).toHaveBeenCalledWith("/api/vault");
const rows = [...host.querySelectorAll("[data-login-row]")].map((row) => row.textContent);
expect(rows[0]).toContain("example.com");
expect(rows[0]).toContain("[email protected]");
@@ -73,8 +74,9 @@ describe("Settings → Logins", () => {
it("adds a login for the bots chosen, and keeps nothing it was typed once saved", async () => {
fixture.api.mockResolvedValueOnce({ logins: [], onePassword: OFF }).mockResolvedValueOnce({ login: SHARED_LOGIN }).mockResolvedValueOnce({ logins: [SHARED_LOGIN], onePassword: OFF });
await render();
- expect(host.textContent).toContain("No saved logins yet.");
- await click("Add login");
+ expect(host.textContent).toContain("Nothing saved yet.");
+ await click("Add");
+ await click("Add a login");
await type("site", "crm.example.org");
await type("username", "team");
await type("password", "fake-typed-pass");
@@ -89,7 +91,8 @@ describe("Settings → Logins", () => {
it("keeps a new login to its exact address when asked", async () => {
fixture.api.mockResolvedValueOnce({ logins: [], onePassword: OFF }).mockResolvedValueOnce({ login: TENANT_LOGIN }).mockResolvedValueOnce({ logins: [TENANT_LOGIN], onePassword: OFF });
await render();
- await click("Add login");
+ await click("Add");
+ await click("Add a login");
await type("site", "acme.okta.com");
await type("password", "fake-tenant-pass");
const exact = host.querySelector<HTMLInputElement>('input[name="exactHost"]')!;
@@ -192,11 +195,101 @@ describe("Settings → Logins", () => {
fixture.admin = false;
await render();
expect(fixture.api).not.toHaveBeenCalled();
- expect(host.textContent).toContain("Only an admin of this installation can see and change saved logins.");
+ expect(host.textContent).toContain("Only an admin of this installation can see and change the Vault.");
});
});
-describe("Settings → Logins with My Cloud", () => {
+describe("Settings → Vault: keys and secrets", () => {
+ const SAVED = { id: "s1", name: "Stripe secret key", source: "card", bots: ["pepper"], createdAt: 1, updatedAt: 1 };
+ const LINKED = { id: "1password:v1:i9", name: "Notion token", fields: [], source: "linked", provider: "1password", bots: "all", readOnly: true };
+ const listed = (secrets: unknown[] = [SAVED, LINKED]) => ({ logins: [CARD_LOGIN], secrets, onePassword: OFF });
+ const shown = () => [...host.querySelectorAll("[data-login-row], [data-secret-row]")].map((row) => row.getAttribute("data-login-row") ?? row.getAttribute("data-secret-row"));
+ async function fill(selector: string, value: string) {
+ const field = host.querySelector<HTMLInputElement | HTMLTextAreaElement>(selector)!;
+ const proto = field instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(proto, "value")!.set!.call(field, value);
+ field.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ }
+ async function send(form: string) {
+ await act(async () => { host.querySelector<HTMLFormElement>(`[data-${form}]`)!.requestSubmit(); });
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+ }
+
+ it("lists saved and linked secrets beside logins by name only, and finds them by search and by kind", async () => {
+ fixture.api.mockResolvedValueOnce(listed());
+ await render();
+ expect(shown()).toEqual(["example.com", "Notion token", "Stripe secret key"]);
+ expect(host.querySelector('[data-secret-row="Stripe secret key"]')!.textContent).toContain("Saved from a chat · Pepper · Not used yet");
+ const linked = host.querySelector('[data-secret-row="Notion token"]')!;
+ expect(linked.textContent).toContain("From 1Password · All bots");
+ expect(linked.querySelectorAll("button")).toHaveLength(0);
+ expect(host.querySelector("[data-logins-list]")!.querySelectorAll("input")).toHaveLength(0);
+ await fill("[data-vault-search]", "notion");
+ expect(shown()).toEqual(["Notion token"]);
+ await fill("[data-vault-search]", "nothing like it");
+ expect(host.querySelector("[data-vault-none]")!.textContent).toBe("Nothing matches your search.");
+ await fill("[data-vault-search]", "");
+ await act(async () => host.querySelector<HTMLButtonElement>('[data-vault-filter="logins"]')!.click());
+ expect(shown()).toEqual(["example.com"]);
+ await act(async () => host.querySelector<HTMLButtonElement>('[data-vault-filter="secrets"]')!.click());
+ expect(shown()).toEqual(["Notion token", "Stripe secret key"]);
+ });
+
+ it("adds a secret for the bots chosen, and keeps nothing it was typed once saved", async () => {
+ fixture.api.mockResolvedValueOnce(listed([])).mockResolvedValueOnce({ secret: SAVED }).mockResolvedValueOnce(listed());
+ await render();
+ await click("Add");
+ await click("Add a secret");
+ await fill('input[name="secretName"]', " Stripe secret key ");
+ await fill('input[name="secretValue"]', "sk_test_fake-typed-secret");
+ expect(host.querySelector<HTMLInputElement>('input[name="secretValue"]')!.type).toBe("password");
+ await send("secret-form");
+ expect(fixture.api).toHaveBeenNthCalledWith(2, "/api/vault/secrets", { method: "POST", body: JSON.stringify({ name: "Stripe secret key", value: "sk_test_fake-typed-secret", bots: "all" }) });
+ expect(host.querySelector("[data-secret-form]")).toBeNull();
+ expect(host.innerHTML).not.toContain("sk_test_fake-typed-secret");
+ });
+
+ it("renames a secret and changes who may use it without touching its value, and deletes it on a second click", async () => {
+ fixture.api.mockResolvedValueOnce(listed()).mockResolvedValueOnce({ secret: SAVED }).mockResolvedValueOnce(listed())
+ .mockResolvedValueOnce({ ok: true }).mockResolvedValueOnce(listed([LINKED]));
+ await render();
+ await click("Change Stripe secret key");
+ expect(host.querySelector<HTMLInputElement>('input[name="secretValue"]')!.value).toBe("");
+ await fill('input[name="secretName"]', "Stripe live key");
+ await act(async () => { host.querySelector<HTMLInputElement>('[data-secret-form] input[type="radio"]')!.click(); });
+ await send("secret-form");
+ expect(fixture.api).toHaveBeenNthCalledWith(2, "/api/vault/secrets/s1", { method: "PATCH", body: JSON.stringify({ name: "Stripe live key", bots: "all" }) });
+ await click("Delete Stripe secret key");
+ expect(fixture.api).toHaveBeenCalledTimes(3);
+ await click("Delete for good");
+ expect(fixture.api).toHaveBeenNthCalledWith(4, "/api/vault/secrets/s1", { method: "DELETE" });
+ });
+
+ it("imports a pasted .env file as one secret per line", async () => {
+ fixture.api.mockImplementation(async (path: string) => (path === "/api/vault" ? listed([]) : { secret: SAVED }));
+ await render();
+ await click("Add");
+ await click("Paste a .env file");
+ await fill('textarea[name="envText"]', "# keys\nexport STRIPE_SECRET_KEY=sk_test_fake-one\nNOTION_TOKEN=\"fake two\"\n");
+ await send("env-form");
+ const posts = fixture.api.mock.calls.filter(([, init]) => (init as RequestInit | undefined)?.method === "POST").map(([, init]) => JSON.parse(String((init as RequestInit).body)));
+ expect(posts).toEqual([{ name: "STRIPE_SECRET_KEY", value: "sk_test_fake-one", bots: "all" }, { name: "NOTION_TOKEN", value: "fake two", bots: "all" }]);
+ expect(host.querySelector<HTMLTextAreaElement>('textarea[name="envText"]')!.value).toBe("");
+ expect(host.querySelector("[data-env-form] [role=status]")!.textContent).toBe("Saved to the Vault: 2.");
+ });
+
+ it("sends keys the app uses itself to API keys", async () => {
+ fixture.api.mockResolvedValueOnce(listed([]));
+ await render();
+ expect(host.querySelector("[data-vault-keys]")!.textContent).toContain("AI and app keys");
+ await act(async () => host.querySelector<HTMLButtonElement>("[data-vault-keys] button")!.click());
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "toggleAppSettings", open: true, section: "connections" });
+ });
+});
+
+describe("Settings → Vault with My Cloud", () => {
afterEach(() => { delete (window as { ogb?: unknown }).ogb; });
const where = (site: string) => host.querySelector(`[data-login-row="${site}"] [data-login-where]`)?.textContent;
diff --git a/src/components/VaultSettings.tsx b/src/components/VaultSettings.tsx
new file mode 100644
index 0000000000..17a12b8e1c
--- /dev/null
+++ b/src/components/VaultSettings.tsx
@@ -0,0 +1,396 @@
+import { useEffect, useState, type FormEvent } from "react";
+import { ChevronDown, KeyRound, Loader2, LockKeyhole, Plus, RefreshCw, Search, ShieldCheck, Trash2 } from "lucide-react";
+
+import { loginHeldBackFor, type LoginBots, type LoginSummary, type OnePasswordStatus, type OnePasswordVault } from "../../shared/logins";
+import type { LinkedSecret, VaultSecret } from "../../shared/vault";
+import { t } from "@/lib/i18n";
+import { addLogin, changeLogin, connectOnePassword, deleteLogin, disconnectOnePassword, grantVault, refreshOnePassword } from "@/lib/logins";
+import { relativeTime } from "@/lib/memory";
+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
+import { deleteSecret, listVault } from "@/lib/vault";
+import { useStore } from "@/state/store";
+import { Segmented } from "./bot-panel/rows";
+import { LoginBotPicker, LoginForm } from "./LoginForm";
+import { Card } from "./SettingsPrimitives";
+import { EnvImportForm, SecretForm } from "./VaultSecretForms";
+
+// Security: a row never shows a password or a secret, which no route returns. A saved value can only be replaced.
+
+const SOURCE_KEYS = {
+ card: "settings.logins.source.card",
+ settings: "settings.logins.source.settings",
+ "1password": "settings.logins.source.1password",
+ linked: "settings.logins.source.1password",
+} as const;
+
+const ROW_BUTTON = "flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50";
+
+type Filter = "all" | "logins" | "secrets";
+type Adding = "login" | "secret" | "env" | null;
+type Row = { kind: "login"; key: string; login: LoginSummary } | { kind: "secret"; key: string; secret: VaultSecret | LinkedSecret };
+
+const ADD_CHOICES = [["login", "settings.vault.addLogin"], ["secret", "settings.vault.addSecret"], ["env", "settings.vault.importEnv"]] as const;
+
+function rowsOf(logins: LoginSummary[], secrets: Array<VaultSecret | LinkedSecret>, filter: Filter, query: string): Row[] {
+ const q = query.trim().toLowerCase();
+ const rows: Row[] = [
+ ...(filter === "secrets" ? [] : logins.map((login): Row => ({ kind: "login", key: [login.site, login.username, ...login.hosts].join(" "), login }))),
+ ...(filter === "logins" ? [] : secrets.map((secret): Row => ({ kind: "secret", key: secret.name, secret }))),
+ ];
+ return rows.filter((row) => !q || row.key.toLowerCase().includes(q)).sort((a, b) => a.key.localeCompare(b.key));
+}
+
+export function VaultSettings() {
+ const { state, dispatch } = useStore();
+ const ownerOrAdmin = useOwnerOrAdmin();
+ const bots = state.bots.map((bot) => ({ id: bot.id, name: bot.name }));
+ const [logins, setLogins] = useState<LoginSummary[] | null>(null);
+ const [secrets, setSecrets] = useState<Array<VaultSecret | LinkedSecret>>([]);
+ const [onePassword, setOnePassword] = useState<OnePasswordStatus>({ connected: false });
+ const [error, setError] = useState<string | null>(null);
+ const [query, setQuery] = useState("");
+ const [filter, setFilter] = useState<Filter>("all");
+ const [menu, setMenu] = useState(false);
+ const [adding, setAdding] = useState<Adding>(null);
+ const [site, setSite] = useState("");
+ const [addBots, setAddBots] = useState<LoginBots>("all");
+ const [addExact, setAddExact] = useState(false);
+ const [editing, setEditing] = useState<string | null>(null);
+ const [editBots, setEditBots] = useState<LoginBots>("all");
+ const [editExact, setEditExact] = useState(false);
+ const [removeTotp, setRemoveTotp] = useState(false);
+ const [deleting, setDeleting] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ const load = async () => {
+ try {
+ const answer = await listVault();
+ setLogins(answer.logins ?? []);
+ setSecrets(answer.secrets ?? []);
+ setOnePassword(answer.onePassword ?? { connected: false });
+ setError(null);
+ }
+ catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.vault.loadError")); }
+ };
+ useEffect(() => { if (ownerOrAdmin) void load(); }, [ownerOrAdmin]);
+
+ if (ownerOrAdmin === false) {
+ return <Card title={t("settings.vault.title")} subtitle={t("settings.vault.adminOnly")} />;
+ }
+
+ const botNames = (value: LoginBots) => {
+ if (value === "all") return t("settings.logins.allBots");
+ const names = value.flatMap((id) => bots.find((bot) => bot.id === id)?.name ?? []);
+ return names.length ? names.join(", ") : t("settings.logins.noBots");
+ };
+ const used = (at: number | undefined) => at ? t("settings.logins.used", { when: relativeTime(at) }) : t("settings.logins.neverUsed");
+ const startEdit = (id: string, login?: LoginSummary) => {
+ setAdding(null);
+ setDeleting(null);
+ setRemoveTotp(false);
+ if (login) { setEditBots(login.bots); setEditExact(login.exactHost); }
+ setEditing(id);
+ };
+ const startAdding = (kind: Adding) => {
+ setMenu(false);
+ setEditing(null);
+ setDeleting(null);
+ setAdding(kind);
+ };
+ const remove = async (id: string, kind: "login" | "secret") => {
+ if (deleting !== id) { setDeleting(id); return; }
+ setBusy(true);
+ try { await (kind === "login" ? deleteLogin(id) : deleteSecret(id)); setDeleting(null); await load(); }
+ catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.logins.deleteError")); }
+ finally { setBusy(false); }
+ };
+ const rowButtons = (id: string, kind: "login" | "secret", name: string, onChange: () => void) => (
+ <div className="flex shrink-0 gap-1">
+ <button type="button" className={ROW_BUTTON} disabled={busy} onClick={onChange}
+ aria-label={kind === "login" ? t("settings.logins.changeFor", { site: name }) : t("settings.vault.secret.changeFor", { name })}>{t("settings.logins.change")}</button>
+ <button type="button" className={ROW_BUTTON} disabled={busy} onClick={() => void remove(id, kind)}
+ aria-label={deleting === id ? t("settings.logins.deleteConfirm") : kind === "login" ? t("settings.logins.deleteFor", { site: name }) : t("settings.vault.secret.deleteFor", { name })}>
+ <Trash2 size={13} />{deleting === id ? t("settings.logins.deleteConfirm") : t("settings.logins.delete")}
+ </button>
+ </div>
+ );
+ const rows = rowsOf(logins ?? [], secrets, filter, query);
+ const empty = logins !== null && logins.length === 0 && secrets.length === 0;
+
+ const loginRow = (login: LoginSummary) => (
+ <li key={login.id} className="flex flex-col gap-2 py-2.5" data-login-row={login.site}>
+ <div className="flex min-w-0 items-start gap-2">
+ <LockKeyhole size={14} aria-hidden="true" className="mt-[3px] shrink-0 text-ink-tertiary" />
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5">
+ <span dir="ltr" className="truncate text-[13px] font-medium text-ink" title={login.site}>{login.site}</span>
+ {login.hasTotp && (
+ <span className="inline-flex items-center gap-0.5 rounded-full bg-ink/[0.07] px-1.5 text-[11px] text-ink-secondary">
+ <ShieldCheck size={11} aria-hidden="true" />{t("settings.logins.twoFactor")}
+ </span>
+ )}
+ </div>
+ <div dir="auto" className="truncate text-[12px] text-ink-secondary">{login.username || t("settings.logins.noUsername")}</div>
+ {signInHostsLine(login) && <div dir="ltr" className="truncate text-[12px] text-ink-tertiary" data-login-hosts>{signInHostsLine(login)}</div>}
+ <div className="mt-0.5 text-[12px] leading-snug text-ink-tertiary">
+ {[t(SOURCE_KEYS[login.source]), botNames(login.bots), used(login.lastUsedAt)].join(" · ")}
+ </div>
+ {loginHeldBackFor(login, state.bots).length > 0 && (
+ <div className="mt-0.5 text-[12px] leading-snug text-warning" data-login-held-back>
+ {t("settings.logins.sharedBrowser", { bots: botNames(loginHeldBackFor(login, state.bots)) })}
+ </div>
+ )}
+ </div>
+ {login.source !== "1password" && rowButtons(login.id, "login", login.site, () => startEdit(login.id, login))}
+ </div>
+ {editing === login.id && (
+ <div className="ms-6 rounded-lg bg-inset/60 p-3">
+ <LoginForm username={false} replacing submitLabel={t("settings.logins.saveChange")} autoFocus
+ onCancel={() => setEditing(null)}
+ onSubmit={async (fields) => {
+ await changeLogin(login.id, { password: fields.password, totp: fields.totp, removeTotp, bots: editBots, ...(editExact === login.exactHost ? {} : { exactHost: editExact }) });
+ setEditing(null);
+ await load();
+ }}>
+ {login.hasTotp && (
+ <label className="flex items-center gap-2 text-[13px] text-ink">
+ <input type="checkbox" checked={removeTotp} onChange={(event) => setRemoveTotp(event.target.checked)} />
+ {t("settings.logins.removeTotp")}
+ </label>
+ )}
+ <ExactHostChoice checked={editExact} onChange={setEditExact}
+ label={t("settings.logins.exactHostFor", { hosts: login.hosts.join(", "), site: login.site })} />
+ <LoginBotPicker value={editBots} onChange={setEditBots} bots={bots} />
+ </LoginForm>
+ </div>
+ )}
+ </li>
+ );
+
+ const secretRow = (secret: VaultSecret | LinkedSecret) => (
+ <li key={secret.id} className="flex flex-col gap-2 py-2.5" data-secret-row={secret.name}>
+ <div className="flex min-w-0 items-start gap-2">
+ <KeyRound size={14} aria-hidden="true" className="mt-[3px] shrink-0 text-ink-tertiary" />
+ <div className="min-w-0 flex-1">
+ <div dir="auto" className="truncate text-[13px] font-medium text-ink" title={secret.name}>{secret.name}</div>
+ <div className="mt-0.5 text-[12px] leading-snug text-ink-tertiary">
+ {[t(SOURCE_KEYS[secret.source]), botNames(secret.bots), used(secret.lastUsedAt)].join(" · ")}
+ </div>
+ </div>
+ {secret.source !== "linked" && rowButtons(secret.id, "secret", secret.name, () => startEdit(secret.id))}
+ </div>
+ {editing === secret.id && secret.source !== "linked" && (
+ <div className="ms-6 rounded-lg bg-inset/60 p-3">
+ <SecretForm secret={secret} bots={bots} onCancel={() => setEditing(null)} onSaved={async () => { setEditing(null); await load(); }} />
+ </div>
+ )}
+ </li>
+ );
+
+ return (
+ <Card title={t("settings.vault.title")} subtitle={t("settings.vault.subtitle")}>
+ <div className="flex flex-col gap-3" aria-busy={logins === null || busy} data-vault>
+ {state.config?.cloudHome === true && <p className="text-[12px] leading-relaxed text-ink-secondary" data-logins-cloud-own>{t("settings.logins.cloudOwn")}</p>}
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="flex h-8 min-w-[12rem] flex-1 items-center gap-2 rounded-lg bg-ink/[0.05] px-[9px] focus-within:ring-2 focus-within:ring-focus/60">
+ <Search size={15} aria-hidden="true" className="shrink-0 text-ink-secondary" />
+ <input data-vault-search type="text" value={query} onChange={(event) => setQuery(event.target.value)} autoComplete="off" spellCheck={false}
+ placeholder={t("settings.vault.search")} aria-label={t("settings.vault.search")}
+ className="w-full min-w-0 bg-transparent text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none" />
+ </div>
+ <div className="relative">
+ <button type="button" className="ui-button ui-button-md" disabled={logins === null} aria-expanded={menu} onClick={() => setMenu(!menu)}
+ onKeyDown={(event) => { if (event.key === "Escape") setMenu(false); }}>
+ <Plus size={14} />{t("settings.vault.add")}<ChevronDown size={13} aria-hidden="true" />
+ </button>
+ {menu && (
+ <div className="absolute end-0 top-full z-10 mt-1 flex min-w-[11rem] flex-col rounded-lg border border-hairline/60 bg-menu p-1 shadow-lg" data-vault-add>
+ {ADD_CHOICES.map(([kind, key]) => (
+ <button key={kind} type="button" className="rounded-md px-2.5 py-1.5 text-start text-[13px] text-ink hover:bg-control" onClick={() => startAdding(kind)}>{t(key)}</button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ <Segmented label={t("settings.vault.filter")} attr="data-vault-filter" value={filter} onChange={setFilter}
+ options={[{ value: "all", label: t("settings.vault.filter.all") }, { value: "logins", label: t("settings.vault.filter.logins") }, { value: "secrets", label: t("settings.vault.filter.secrets") }]} />
+ {adding === "login" && (
+ <div className="rounded-lg bg-inset/60 p-3">
+ <LoginForm site={{ value: site, onChange: setSite }} submitLabel={t("settings.logins.save")} autoFocus
+ onCancel={() => setAdding(null)}
+ onSubmit={async (fields) => {
+ await addLogin(site, fields, addBots, addExact);
+ setAdding(null);
+ setSite("");
+ setAddBots("all");
+ setAddExact(false);
+ await load();
+ }}>
+ <ExactHostChoice checked={addExact} onChange={setAddExact} label={t("settings.logins.exactHost")} />
+ <LoginBotPicker value={addBots} onChange={setAddBots} bots={bots} />
+ </LoginForm>
+ </div>
+ )}
+ {adding === "secret" && (
+ <div className="rounded-lg bg-inset/60 p-3">
+ <SecretForm bots={bots} onCancel={() => setAdding(null)} onSaved={async () => { setAdding(null); await load(); }} />
+ </div>
+ )}
+ {adding === "env" && (
+ <div className="rounded-lg bg-inset/60 p-3">
+ <EnvImportForm bots={bots} onCancel={() => setAdding(null)} onSaved={load} />
+ </div>
+ )}
+ {logins === null && !error && <p className="text-[12px] text-ink-secondary">{t("settings.vault.loading")}</p>}
+ {empty && !adding && <p className="text-[12px] leading-relaxed text-ink-secondary">{t("settings.vault.empty")}</p>}
+ {!empty && logins !== null && rows.length === 0 && <p className="text-[12px] text-ink-secondary" data-vault-none>{t("settings.vault.noMatch")}</p>}
+ {rows.length > 0 && (
+ <ul className="divide-y divide-hairline/30" data-logins-list>
+ {rows.map((row) => row.kind === "login" ? loginRow(row.login) : secretRow(row.secret))}
+ </ul>
+ )}
+ <p className="text-[12px] leading-relaxed text-ink-tertiary">{t("settings.logins.limits")}</p>
+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-hairline/30 pt-3" data-vault-keys>
+ <div className="min-w-0 flex-1">
+ <div className="text-[13px] font-medium text-ink">{t("settings.vault.keys.title")}</div>
+ <div className="text-[12px] leading-snug text-ink-tertiary">{t("settings.vault.keys.hint")}</div>
+ </div>
+ <button type="button" className="ui-button ui-button-md shrink-0" onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: "connections" })}>
+ {t("keys.row.open")}
+ </button>
+ </div>
+ <OnePasswordConnection status={onePassword} disabled={logins === null} bots={bots} botNames={botNames}
+ onChange={async (next) => { setOnePassword(next); await load(); }} />
+ </div>
+ </Card>
+ );
+}
+
+/** Where a login signs in beyond its site's own pages, or that it is kept to those hosts. */
+function signInHostsLine(login: LoginSummary): string | null {
+ if (login.exactHost) return t("settings.logins.onlyOn", { hosts: login.hosts.join(", ") });
+ const elsewhere = login.hosts.filter((host) => host !== login.site);
+ return elsewhere.length ? t("settings.logins.signsInOn", { hosts: elsewhere.join(", ") }) : null;
+}
+
+function ExactHostChoice({ checked, onChange, label }: { checked: boolean; onChange: (checked: boolean) => void; label: string }) {
+ return (
+ <label className="flex items-start gap-2 text-[13px] leading-snug text-ink">
+ <input type="checkbox" name="exactHost" className="mt-[2px]" checked={checked} onChange={(event) => onChange(event.target.checked)} />
+ {label}
+ </label>
+ );
+}
+
+function VaultAccess({ vault, bots, botNames, disabled, onChange }: {
+ vault: OnePasswordVault;
+ bots: ReadonlyArray<{ id: string; name: string }>;
+ botNames: (value: LoginBots) => string;
+ disabled: boolean;
+ onChange: (status: OnePasswordStatus) => Promise<void>;
+}) {
+ const [editing, setEditing] = useState(false);
+ const [value, setValue] = useState<LoginBots>(vault.bots);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const save = async () => {
+ setBusy(true);
+ setError(null);
+ try { await onChange(await grantVault(vault.id, value)); setEditing(false); }
+ catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.logins.onePassword.error")); }
+ finally { setBusy(false); }
+ };
+ return (
+ <li className="flex flex-col gap-2 py-2" data-vault={vault.title}>
+ <div className="flex min-w-0 items-start gap-2">
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13px] font-medium text-ink">{vault.title}</div>
+ <div className="text-[12px] text-ink-tertiary">{t("settings.logins.onePassword.vaultUse", { count: String(vault.items), who: botNames(vault.bots) })}</div>
+ </div>
+ {!editing && (
+ <button type="button" className={ROW_BUTTON} disabled={disabled || busy} onClick={() => { setValue(vault.bots); setEditing(true); }}
+ aria-label={t("settings.logins.onePassword.changeVault", { vault: vault.title })}>{t("settings.logins.change")}</button>
+ )}
+ </div>
+ {editing && (
+ <div className="flex flex-col gap-2 rounded-lg bg-inset/60 p-3">
+ <LoginBotPicker value={value} onChange={setValue} bots={bots} disabled={busy} />
+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
+ <div className="flex flex-wrap justify-end gap-2">
+ <button type="button" className="ui-button ui-button-md" disabled={busy} onClick={() => setEditing(false)}>{t("logins.cancel")}</button>
+ <button type="button" className="ui-button ui-button-md ui-button-primary" disabled={busy} onClick={() => void save()}>{t("settings.logins.saveChange")}</button>
+ </div>
+ </div>
+ )}
+ </li>
+ );
+}
+
+function OnePasswordConnection({ status, disabled, bots, botNames, onChange }: {
+ status: OnePasswordStatus;
+ disabled: boolean;
+ bots: ReadonlyArray<{ id: string; name: string }>;
+ botNames: (value: LoginBots) => string;
+ onChange: (status: OnePasswordStatus) => Promise<void>;
+}) {
+ const [token, setToken] = useState("");
+ const [busy, setBusy] = useState<"connect" | "refresh" | "disconnect" | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const run = async (kind: NonNullable<typeof busy>, work: () => Promise<OnePasswordStatus>) => {
+ if (busy) return;
+ setBusy(kind);
+ setError(null);
+ try { await onChange(await work()); if (kind === "connect") setToken(""); }
+ catch (cause) { setError(cause instanceof Error && cause.message ? cause.message : t("settings.logins.onePassword.error")); }
+ finally { setBusy(null); }
+ };
+ const connect = (event: FormEvent) => {
+ event.preventDefault();
+ if (token.trim()) void run("connect", () => connectOnePassword(token.trim()));
+ };
+ return (
+ <section className="mt-1 flex flex-col gap-2 border-t border-hairline/30 pt-3" aria-label={t("settings.vault.manager")} data-onepassword>
+ <div className="text-[13px] font-medium text-ink">{t("settings.vault.manager")}</div>
+ <div className="text-[12px] font-medium text-ink-secondary">{t("settings.logins.onePassword.title")}</div>
+ {status.connected ? (
+ <>
+ <p className="text-[13px] leading-snug text-ink-secondary">
+ {t("settings.logins.onePassword.connected", { vaults: (status.vaults ?? []).map((vault) => vault.title).join(", ") || "—", count: String(status.items ?? 0) })}
+ </p>
+ {status.error && <p role="alert" className="text-[12px] text-danger">{status.error}</p>}
+ {!!status.vaults?.length && (
+ <ul className="divide-y divide-hairline/30" aria-label={t("settings.logins.onePassword.vaults")}>
+ {status.vaults.map((vault) => <VaultAccess key={vault.id} vault={vault} bots={bots} botNames={botNames} disabled={disabled} onChange={onChange} />)}
+ </ul>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <button type="button" className="ui-button ui-button-md" disabled={disabled || busy !== null} onClick={() => void run("refresh", refreshOnePassword)}>
+ {busy === "refresh" ? <Loader2 size={13} className="animate-spin" /> : <RefreshCw size={13} />}{t("settings.logins.onePassword.refresh")}
+ </button>
+ <button type="button" className="ui-button ui-button-md" disabled={disabled || busy !== null} onClick={() => void run("disconnect", disconnectOnePassword)}>
+ {t("settings.logins.onePassword.disconnect")}
+ </button>
+ </div>
+ </>
+ ) : (
+ <form className="flex flex-col gap-2" onSubmit={connect}>
+ <p className="text-[12px] leading-relaxed text-ink-secondary">{t("settings.logins.onePassword.guide")}</p>
+ <div className="flex flex-wrap gap-2">
+ <input name="onePasswordToken" type="password" autoComplete="off" spellCheck={false} maxLength={8192} value={token}
+ onChange={(event) => setToken(event.target.value)} disabled={disabled || busy !== null}
+ aria-label={t("settings.logins.onePassword.token")} placeholder={t("settings.logins.onePassword.token")}
+ className="min-w-0 flex-1 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5 text-[13px] text-ink outline-none placeholder:text-ink-tertiary focus:border-accent disabled:opacity-60" />
+ <button type="submit" className="ui-button ui-button-md ui-button-primary" disabled={disabled || busy !== null || !token.trim()}>
+ {busy === "connect" && <Loader2 size={13} className="animate-spin" />}{t("settings.logins.onePassword.connect")}
+ </button>
+ </div>
+ </form>
+ )}
+ <p className="flex items-start gap-1 text-[12px] leading-snug text-ink-tertiary">
+ <LockKeyhole size={11} aria-hidden="true" className="mt-[3px] shrink-0" /> {t("settings.logins.onePassword.note")}
+ </p>
+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
+ </section>
+ );
+}
diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.ts
index a8d61b78ba..ae05b8219a 100644
--- a/src/components/keys/key-catalog.ts
+++ b/src/components/keys/key-catalog.ts
@@ -153,7 +153,7 @@ export const KEY_CATALOG: readonly KeyEntry[] = [
status: (config) => ({ configured: config.vps?.configured === true }) },
{ id: "onePassword", section: "computers", labelKey: "settings.logins.onePassword.title", purposeKey: "keys.purpose.onePassword", name: "1Password", env: [],
words: ["1password", "one password", "logins", "passwords", "vault", "service account"], mark: { icon: LockKeyhole }, kind: "elsewhere",
- opens: "logins", whereKey: "keys.where.logins" },
+ opens: "logins", whereKey: "keys.where.vault" },
{ id: "composio", section: "apps", labelKey: "keys.composio.label", purposeKey: "keys.purpose.composio", name: "Composio", env: ["COMPOSIO_API_KEY"],
words: ["composio", "connected apps", "apps", "gmail", "slack", "github", "notion", "self-host"], mark: { icon: Blocks }, kind: "key",
target: { patch: (value) => ({ composio: { apiKey: value } }), slot: "composioApiKey", verifiedOnSave: true,
diff --git a/src/lib/vault.test.ts b/src/lib/vault.test.ts
new file mode 100644
index 0000000000..a3908b27c4
--- /dev/null
+++ b/src/lib/vault.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+
+import { parseEnv } from "./vault";
+
+describe("a pasted .env file", () => {
+ it("keeps each NAME=value line, dropping export, quotes, comments and empty values; a later line wins", () => {
+ expect(parseEnv([
+ "# Stripe",
+ "export STRIPE_SECRET_KEY=sk_test_fake-1 # test mode",
+ "NOTION_TOKEN=\"fake \\\"two\\\"\\nline\"",
+ "SINGLE='a # b'",
+ "EMPTY=",
+ "not a line",
+ " SPACED = fake-3 ",
+ "STRIPE_SECRET_KEY=sk_test_fake-4",
+ ].join("\r\n"))).toEqual([
+ { name: "STRIPE_SECRET_KEY", value: "sk_test_fake-4" },
+ { name: "NOTION_TOKEN", value: "fake \"two\"\nline" },
+ { name: "SINGLE", value: "a # b" },
+ { name: "SPACED", value: "fake-3" },
+ ]);
+ });
+});
diff --git a/src/lib/vault.ts b/src/lib/vault.ts
new file mode 100644
index 0000000000..34a26011e6
--- /dev/null
+++ b/src/lib/vault.ts
@@ -0,0 +1,74 @@
+import type { LoginBots, LoginSummary, OnePasswordStatus } from "../../shared/logins";
+import type { LinkedSecret, VaultChoice, VaultSecret } from "../../shared/vault";
+import type { ComputerHelpRef } from "../../shared/wire";
+import { api } from "@/state/store";
+
+// A saved value is sent once and never comes back: every answer here is names, sites and who may use them.
+
+export interface VaultList {
+ logins: LoginSummary[];
+ secrets: Array<VaultSecret | LinkedSecret>;
+ onePassword: OnePasswordStatus;
+}
+
+export async function listVault(): Promise<VaultList> {
+ return await api<VaultList>("/api/vault");
+}
+
+export async function addSecret(name: string, value: string, bots: LoginBots): Promise<VaultSecret> {
+ return (await api<{ secret: VaultSecret }>("/api/vault/secrets", { method: "POST", body: JSON.stringify({ name, value, bots }) })).secret;
+}
+
+/** An empty value keeps the saved one. */
+export async function changeSecret(id: string, change: { name?: string; value?: string; bots?: LoginBots }): Promise<VaultSecret> {
+ return (await api<{ secret: VaultSecret }>(`/api/vault/secrets/${encodeURIComponent(id)}`, {
+ method: "PATCH",
+ body: JSON.stringify({ ...(change.name ? { name: change.name } : {}), ...(change.value?.trim() ? { value: change.value } : {}), ...(change.bots ? { bots: change.bots } : {}) }),
+ })).secret;
+}
+
+export async function deleteSecret(id: string): Promise<void> {
+ await api(`/api/vault/secrets/${encodeURIComponent(id)}`, { method: "DELETE" });
+}
+
+/** The NAME=value lines of a pasted .env file. `export`, quotes and trailing comments are dropped; a later line with the
+ * same name wins, and a line with no value is skipped. */
+export function parseEnv(text: string): Array<{ name: string; value: string }> {
+ const found = new Map<string, string>();
+ for (const line of text.split(/\r?\n/u)) {
+ const match = /^\s*(?:export\s+)?([A-Za-z_][\w.-]*)\s*=\s*(.*?)\s*$/u.exec(line);
+ if (!match) continue;
+ const raw = match[2]!;
+ const quoted = /^(["'`])(.*)\1$/su.exec(raw);
+ const value = quoted ? (quoted[1] === '"' ? quoted[2]!.replace(/\\n/gu, "\n").replace(/\\(["\\])/gu, "$1") : quoted[2]!) : raw.replace(/\s+#.*$/u, "").trim();
+ if (value) found.set(match[1]!, value);
+ }
+ return [...found].map(([name, value]) => ({ name, value }));
+}
+
+/** Saves each line as a secret; stops at the first one the server refuses, naming it. */
+export async function importEnv(lines: ReadonlyArray<{ name: string; value: string }>, bots: LoginBots): Promise<number> {
+ let saved = 0;
+ for (const { name, value } of lines) {
+ try { await addSecret(name, value, bots); saved++; }
+ catch (cause) { throw new Error(`${name}: ${cause instanceof Error ? cause.message : String(cause)}`); }
+ }
+ return saved;
+}
+
+type CardRef = Pick<ComputerHelpRef, "botId" | "threadId" | "messageId">;
+export type ChoiceKind = "secret" | "login";
+
+const cardPath = (kind: ChoiceKind, ref: CardRef, end: "list" | "use") =>
+ `/api/bots/${encodeURIComponent(ref.botId)}/${kind === "secret" ? "secret-cards" : "sign-in-cards"}/${encodeURIComponent(ref.messageId)}/${
+ kind === "secret" ? (end === "list" ? "saved" : "use") : (end === "list" ? "saved-logins" : "use-login")}`;
+
+/** What a secure card offers under "Use a saved one", by name only. Empty where this person can't change the Vault. */
+export async function savedChoices(kind: ChoiceKind, ref: CardRef): Promise<VaultChoice[]> {
+ return (await api<{ choices: VaultChoice[] }>(`${cardPath(kind, ref, "list")}?threadId=${encodeURIComponent(ref.threadId)}`)).choices;
+}
+
+/** The bot may use the one picked from now on, and the card is answered with it. */
+export async function useSaved(kind: ChoiceKind, ref: CardRef, id: string): Promise<void> {
+ await api(cardPath(kind, ref, "use"), { method: "POST", body: JSON.stringify({ threadId: ref.threadId, ...(kind === "secret" ? { itemId: id } : { loginId: id }) }) });
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 1354da1a07..1ef7e852a9 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -1683,6 +1683,7 @@
"settings.section.companion": "Remote access",
"settings.section.computer": "Bot desktops",
"settings.section.logins": "Logins",
+ "settings.section.vault": "Vault",
"settings.section.usage": "Usage",
"settings.section.people": "People",
"settings.section.activity": "Activity",
@@ -3763,6 +3764,40 @@
"settings.logins.onePassword.error": "Couldn't reach 1Password. Check your internet connection and the token, then try again.",
"settings.logins.onePassword.note": "The token is encrypted on the computer {app} runs on and never shown again. 1Password logins appear in the list above, filled the same way, and are changed in 1Password. A vault is for every bot unless you choose bots for it.",
"settings.logins.cloudOwn": "These are the Cloud's own logins. Your computer's logins come here by themselves when the {app} app on that computer moves your bots here.",
+ "settings.vault.title": "Vault",
+ "settings.vault.subtitle": "Passwords and keys your bots can use. Bots never see them: {app} types a password into the login page for a bot, and gives a key to its tools without showing it.",
+ "settings.vault.adminOnly": "Only an admin of this installation can see and change the Vault.",
+ "settings.vault.loading": "Loading the Vault…",
+ "settings.vault.loadError": "Could not load the Vault.",
+ "settings.vault.empty": "Nothing saved yet. Add a login or a secret here, or save one when a bot asks for it.",
+ "settings.vault.noMatch": "Nothing matches your search.",
+ "settings.vault.search": "Search the Vault",
+ "settings.vault.filter": "Show",
+ "settings.vault.filter.all": "All",
+ "settings.vault.filter.logins": "Logins",
+ "settings.vault.filter.secrets": "Keys & secrets",
+ "settings.vault.add": "Add",
+ "settings.vault.addLogin": "Add a login",
+ "settings.vault.addSecret": "Add a secret",
+ "settings.vault.importEnv": "Paste a .env file",
+ "settings.vault.secret.name": "Name",
+ "settings.vault.secret.namePlaceholder": "Stripe secret key",
+ "settings.vault.secret.nameHint": "Bots ask for it by this name.",
+ "settings.vault.secret.value": "Secret",
+ "settings.vault.secret.valueKeep": "New secret (leave empty to keep the saved one)",
+ "settings.vault.secret.save": "Save secret",
+ "settings.vault.secret.changeFor": "Change {name}",
+ "settings.vault.secret.deleteFor": "Delete {name}",
+ "settings.vault.secret.saveError": "Could not save the secret.",
+ "settings.vault.secret.private": "Encrypted on the computer {app} runs on and never shown again. Bots never see it: {app} hands it to their tools.",
+ "settings.vault.env.label": ".env file",
+ "settings.vault.env.hint": "Each NAME=value line becomes a secret called NAME. Lines starting with # are skipped.",
+ "settings.vault.env.submit": "Import",
+ "settings.vault.env.none": "No NAME=value lines found.",
+ "settings.vault.env.done": "Saved to the Vault: {count}.",
+ "settings.vault.keys.title": "AI and app keys",
+ "settings.vault.keys.hint": "Keys {app} uses itself, such as your AI provider's, are kept in API keys.",
+ "settings.vault.manager": "Password manager",
"settings.sites.loading": "Checking…",
"settings.sites.none": "Not signed in to any site.",
"settings.sites.shared": "{names} share this browser: signing out here signs all of them out.",
@@ -7642,6 +7677,7 @@
"keys.label.imageOpenai": "OpenAI key for pictures",
"keys.label.imageCustom": "Custom picture service key",
"keys.where.logins": "Set up in Logins.",
+ "keys.where.vault": "Set up in Vault.",
"keys.where.decisions": "Set up with its account ID under Decision and extraction.",
"keys.where.pictures": "Set up in a bot's picture maker, with the service's address and model.",
"keys.label.imageGemini": "Gemini key for pictures",
@@ -8519,6 +8555,10 @@
"chat.secret.save": "Save securely",
"chat.secret.storedHint": "Stored securely by {app} and never added to chat.",
"chat.secret.whereToGet": "Where to get this key",
+ "vault.choices.secret": "Use a saved one",
+ "vault.choices.login": "Use a saved login",
+ "vault.choices.note": "{bot} can use the one you pick from now on.",
+ "vault.choices.error": "Couldn't use that one. Try again, or type it below.",
"skills.request.legacyUpdate": "This proposal was created by an older build and cannot be safely applied. Deny it, then ask the bot to propose the update again.",
"skills.request.legacyCreate": "This proposal was created by an older build and cannot be safely applied. Deny it, then ask the bot to create the skill again.",
"skills.request.reviewEnable": "Review the complete SKILL.md before enabling",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 3cc07ce43b..74ca442bd6 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -1560,6 +1560,7 @@
"settings.section.companion": "Acesso remoto",
"settings.section.computer": "Desktops dos bots",
"settings.section.logins": "Logins",
+ "settings.section.vault": "Cofre",
"settings.section.usage": "Uso",
"settings.section.people": "Pessoas",
"settings.section.activity": "Atividade",
@@ -3629,6 +3630,40 @@
"settings.logins.onePassword.error": "Não foi possível acessar o 1Password. Confira a conexão com a internet e o token e tente novamente.",
"settings.logins.onePassword.note": "O token é criptografado no computador onde o app {app} roda e nunca mais é exibido. Os logins do 1Password aparecem na lista acima e são preenchidos da mesma forma. Edite-os no 1Password. Um cofre fica disponível para todos os bots, a menos que você escolha quais podem usá-lo.",
"settings.logins.cloudOwn": "Estes são os logins do próprio Cloud. Os logins do seu computador vêm automaticamente quando o app {app} instalado nele move os bots para cá.",
+ "settings.vault.title": "Cofre",
+ "settings.vault.subtitle": "Senhas e chaves que seus bots podem usar. Os bots nunca as veem: o app {app} digita a senha na página de login pelo bot e entrega a chave às ferramentas dele sem mostrá-la.",
+ "settings.vault.adminOnly": "Só um admin desta instalação pode ver e alterar o Cofre.",
+ "settings.vault.loading": "Carregando o Cofre…",
+ "settings.vault.loadError": "Não foi possível carregar o Cofre.",
+ "settings.vault.empty": "Nada salvo ainda. Adicione um login ou um segredo aqui, ou salve um quando um bot pedir.",
+ "settings.vault.noMatch": "Nada corresponde à sua busca.",
+ "settings.vault.search": "Buscar no Cofre",
+ "settings.vault.filter": "Mostrar",
+ "settings.vault.filter.all": "Tudo",
+ "settings.vault.filter.logins": "Logins",
+ "settings.vault.filter.secrets": "Chaves e segredos",
+ "settings.vault.add": "Adicionar",
+ "settings.vault.addLogin": "Adicionar um login",
+ "settings.vault.addSecret": "Adicionar um segredo",
+ "settings.vault.importEnv": "Colar um arquivo .env",
+ "settings.vault.secret.name": "Nome",
+ "settings.vault.secret.namePlaceholder": "Chave secreta do Stripe",
+ "settings.vault.secret.nameHint": "Os bots pedem pelo segredo usando este nome.",
+ "settings.vault.secret.value": "Segredo",
+ "settings.vault.secret.valueKeep": "Novo segredo (deixe vazio para manter o salvo)",
+ "settings.vault.secret.save": "Salvar segredo",
+ "settings.vault.secret.changeFor": "Alterar {name}",
+ "settings.vault.secret.deleteFor": "Excluir {name}",
+ "settings.vault.secret.saveError": "Não foi possível salvar o segredo.",
+ "settings.vault.secret.private": "Criptografado no computador onde o app {app} roda e nunca mais exibido. Os bots nunca o veem: o app {app} o entrega às ferramentas deles.",
+ "settings.vault.env.label": "Arquivo .env",
+ "settings.vault.env.hint": "Cada linha NOME=valor vira um segredo chamado NOME. Linhas que começam com # são ignoradas.",
+ "settings.vault.env.submit": "Importar",
+ "settings.vault.env.none": "Nenhuma linha NOME=valor encontrada.",
+ "settings.vault.env.done": "Salvos no Cofre: {count}.",
+ "settings.vault.keys.title": "Chaves de IA e de apps",
+ "settings.vault.keys.hint": "As chaves que o próprio app {app} usa, como a do seu provedor de IA, ficam em Chaves de API.",
+ "settings.vault.manager": "Gerenciador de senhas",
"settings.sites.loading": "Verificando…",
"settings.sites.none": "Sem login em nenhum site.",
"settings.sites.shared": "{names} compartilham este navegador: sair aqui desconecta todos eles.",
@@ -7092,6 +7127,7 @@
"keys.label.imageOpenai": "Chave da OpenAI para imagens",
"keys.label.imageCustom": "Chave do serviço de imagens personalizado",
"keys.where.logins": "Configure em Logins.",
+ "keys.where.vault": "Configure no Cofre.",
"keys.where.decisions": "Configure com o ID da conta em Decisão e extração.",
"keys.where.pictures": "Configure no criador de imagens de um bot, com o endereço e o modelo do serviço.",
"keys.label.imageGemini": "Chave do Gemini para imagens",
@@ -8502,6 +8538,10 @@
"chat.secret.save": "Salvar com segurança",
"chat.secret.storedHint": "Guardada com segurança pelo app {app} e nunca adicionada ao chat.",
"chat.secret.whereToGet": "Onde conseguir esta chave",
+ "vault.choices.secret": "Usar um salvo",
+ "vault.choices.login": "Usar um login salvo",
+ "vault.choices.note": "{bot} poderá usar o que você escolher daqui em diante.",
+ "vault.choices.error": "Não foi possível usar esse. Tente de novo ou digite abaixo.",
"skills.request.legacyUpdate": "Esta proposta foi criada por uma versão mais antiga e não pode ser aplicada com segurança. Recuse-a e peça ao bot para propor a atualização novamente.",
"skills.request.legacyCreate": "Esta proposta foi criada por uma versão mais antiga e não pode ser aplicada com segurança. Recuse-a e peça ao bot para criar a habilidade novamente.",
"skills.request.reviewEnable": "Revise o SKILL.md completo antes de ativar",