From 003c520cbbff0e12a769b009f8042e0449f4ec8d Mon Sep 17 00:00:00 2001 From: TheAnimatrix Date: Tue, 1 Dec 2026 09:11:37 +0530 Subject: [PATCH 1/7] feat(secrets): read /secform's named fields in the composer (email plain, password and API keys masked) --- src/shared/secform.ts | 139 +++++++++++++++++++++++++++++++++++ tests/shared/secform.test.ts | 66 +++++++++++++++++ 2 files changed, 205 insertions(+) create mode 100644 src/shared/secform.ts create mode 100644 tests/shared/secform.test.ts diff --git a/src/shared/secform.ts b/src/shared/secform.ts new file mode 100644 index 0000000000..60b4d12523 --- /dev/null +++ b/src/shared/secform.ts @@ -0,0 +1,139 @@ +/** + * `/secform`: the person opens a secure form for secrets from the composer (asks i121 and i125). This file only reads + * what they typed after the command, in the composer, so no model is asked to build the form: + * + * - `/secform` gives one blank field, `/secform 3` three blank fields. + * - `/secform for email, password and openrouterkey` gives three named fields: Email (plain text, EMAIL), + * Password (masked, PASSWORD) and Openrouter API key (masked, OPENROUTER_API_KEY). + * + * A field is masked unless its name is one of a few plain words (email, username, host, url...). The name is what the + * agent or bot is told; it never sees a value. + */ + +import { isKeyName, keyNameOf } from './automationKeys' + +export const SECFORM_COMMAND = 'secform' + +/** The most fields one form opens with. */ +export const SECFORM_MAX_FIELDS = 20 + +export interface SecformField { + /** What the form shows above the field; empty for a blank field the person names in the form. */ + label: string + /** The secret's name in the store; empty for a blank field. */ + name: string + /** Shown as dots, with show/hide. False only for plain words such as email or username. */ + masked: boolean +} + +export interface SecformSpec { + fields: SecformField[] +} + +/** Words whose value is shown as typed, compared without spaces, dashes or underscores. */ +const PLAIN_WORDS = new Set([ + 'email', + 'emailaddress', + 'mail', + 'username', + 'user', + 'userid', + 'login', + 'account', + 'accountid', + 'clientid', + 'projectid', + 'orgid', + 'host', + 'hostname', + 'server', + 'url', + 'endpoint', + 'domain', + 'port', + 'region' +]) + +/** Kinds of key that are not a service's API key ("ssh key" stays SSH_KEY). */ +const NOT_API_KEYS = new Set(['ssh', 'private', 'public', 'gpg', 'pgp', 'license', 'licence', 'deploy', 'signing', 'encryption', 'master', 'access', 'secret']) + +const COMMAND = /^\/secform(?:\s+([\s\S]*))?$/i +const SEPARATORS = /\s*(?:,|;|&|\+|\band\b)\s*/i + +/** + * What the composer opens for a `/secform` message, or null when the text is not that command. Parsed here, never by + * a model. + */ +export function parseSecform(text: string): SecformSpec | null { + const match = COMMAND.exec(text.trim()) + if (!match) return null + const rest = (match[1] ?? '').trim().replace(/[.!?]+$/, '').trim() + if (rest === '') return { fields: blankFields(1) } + if (/^\d+$/.test(rest)) return { fields: blankFields(Math.max(1, Number(rest))) } + + const counted = /^(\d+)\s+(?:fields?\s+)?([\s\S]+)$/i.exec(rest) + const count = counted ? Number(counted[1]) : 0 + const list = (counted ? counted[2] : rest).replace(/^(?:for|with)\s+/i, '') + const fields: SecformField[] = [] + const used = new Set() + for (const part of list.split(SEPARATORS)) { + const label = part.trim() + if (!label || fields.length >= SECFORM_MAX_FIELDS) continue + const field = secformField(label) + field.name = uniqueName(field.name, used) + fields.push(field) + } + if (fields.length === 0) return { fields: blankFields(count || 1) } + return { fields: [...fields, ...blankFields(Math.min(count, SECFORM_MAX_FIELDS) - fields.length)] } +} + +/** One named field from what the person typed: its label, its secret name and whether it is masked. */ +export function secformField(typed: string): SecformField { + const words = typed + .replace(/[^A-Za-z0-9 _.-]+/g, ' ') + .trim() + .split(/[\s_.-]+/) + .filter(Boolean) + const compact = words.join('').toLowerCase() + const masked = !PLAIN_WORDS.has(compact) + if (isKeyName(typed.trim())) return { label: typed.trim(), name: typed.trim(), masked } + + const service = apiKeyService(words) + if (service) { + return { label: `${capitalise(service.join(' '))} API key`, name: `${service.join('_').toUpperCase()}_API_KEY`, masked } + } + const label = capitalise(words.join(' ') || typed.trim()) + return { label, name: keyNameOf(words.join(' ')) ?? 'SECRET', masked } +} + +/** "openrouterkey", "openrouter key" and "openrouter api key" are OpenRouter's API key: the service's words. */ +function apiKeyService(words: string[]): string[] | undefined { + const lower = words.map((word) => word.toLowerCase()) + let service: string[] + if (lower.length >= 3 && lower.at(-2) === 'api' && lower.at(-1) === 'key') service = words.slice(0, -2) + else if (lower.length >= 2 && (lower.at(-1) === 'key' || lower.at(-1) === 'apikey')) service = words.slice(0, -1) + else if (lower.length === 1 && /^[a-z0-9]+?(?:api)?key$/.test(lower[0]) && !/^(?:api)?key$/.test(lower[0])) { + service = [words[0].replace(/(?:api)?key$/i, '')] + } else return undefined + if (service.length === 0) return undefined + if (service.length === 1 && (service[0].toLowerCase() === 'api' || NOT_API_KEYS.has(service[0].toLowerCase()))) { + return undefined + } + return service.every((word) => /^[A-Za-z0-9]+$/.test(word)) && /^[A-Za-z]/.test(service[0]) ? service : undefined +} + +function blankFields(count: number): SecformField[] { + const n = Math.max(0, Math.min(SECFORM_MAX_FIELDS, Number.isFinite(count) ? Math.floor(count) : 0)) + return Array.from({ length: n }, () => ({ label: '', name: '', masked: true })) +} + +function uniqueName(name: string, used: Set): string { + let candidate = name + for (let n = 2; used.has(candidate); n += 1) candidate = `${name}_${n}` + used.add(candidate) + return candidate +} + +function capitalise(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1) +} diff --git a/tests/shared/secform.test.ts b/tests/shared/secform.test.ts new file mode 100644 index 0000000000..dfb5a42ca4 --- /dev/null +++ b/tests/shared/secform.test.ts @@ -0,0 +1,66 @@ +/** + * `/secform` read in the composer: a count gives blank fields, a plain-words list gives named, typed fields, and + * nothing else is taken for the command. + * + * Inputs: no argument, a count (0, 1, 3, past the cap), a list with commas / "and" / "&", a leading "for", a count and + * a list, plain words (email, username), API keys typed joined, spaced or with "api", keys that are not API keys + * (ssh key), a name typed as a key name, repeats, punctuation, case of the command, other commands and plain text. + */ +import { describe, expect, it } from 'vitest' +import { parseSecform, SECFORM_MAX_FIELDS } from '../../src/shared/secform' + +const shape = (text: string) => parseSecform(text)?.fields.map((field) => [field.name, field.masked ? 'masked' : 'plain']) + +describe('parseSecform', () => { + it.each([ + ['/secform', 1], + ['/secform 3', 3], + ['/secform 1', 1], + ['/secform 0', 1], + ['/SECFORM 2', 2], + ['/secform 500', SECFORM_MAX_FIELDS] + ])('%s opens %i blank masked field(s)', (text, count) => { + const fields = parseSecform(text)?.fields + expect(fields).toHaveLength(count) + expect(fields?.every((field) => field.name === '' && field.label === '' && field.masked)).toBe(true) + }) + + it.each([ + [ + '/secform for email, password and openrouterkey', + [ + ['EMAIL', 'plain'], + ['PASSWORD', 'masked'], + ['OPENROUTER_API_KEY', 'masked'] + ] + ], + ['/secform email & password.', [['EMAIL', 'plain'], ['PASSWORD', 'masked']]], + ['/secform for openrouter key', [['OPENROUTER_API_KEY', 'masked']]], + ['/secform for OpenRouter API key', [['OPENROUTER_API_KEY', 'masked']]], + ['/secform for github token, username', [['GITHUB_TOKEN', 'masked'], ['USERNAME', 'plain']]], + ['/secform for ssh key', [['SSH_KEY', 'masked']]], + ['/secform for DB_PASS', [['DB_PASS', 'masked']]], + ['/secform for password, password', [['PASSWORD', 'masked'], ['PASSWORD_2', 'masked']]], + ['/secform for host; port; api key', [['HOST', 'plain'], ['PORT', 'plain'], ['API_KEY', 'masked']]], + ['/secform 3 for email', [['EMAIL', 'plain'], ['', 'masked'], ['', 'masked']]] + ])('%s names and types each field', (text, expected) => { + expect(shape(text)).toEqual(expected) + }) + + it('labels the fields in plain words', () => { + expect(parseSecform('/secform for email, password and openrouterkey')?.fields.map((field) => field.label)).toEqual([ + 'Email', + 'Password', + 'Openrouter API key' + ]) + }) + + it('caps a long list', () => { + const list = Array.from({ length: 30 }, (_, i) => `field${i}`).join(', ') + expect(parseSecform(`/secform for ${list}`)?.fields).toHaveLength(SECFORM_MAX_FIELDS) + }) + + it.each(['/secformx', '/secrets 3', 'secform 3', 'please /secform 3', ''])('%j is not the command', (text) => { + expect(parseSecform(text)).toBeNull() + }) +}) From f5656dfbb0138b88eb05f03819436db2f5d0561b Mon Sep 17 00:00:00 2001 From: TheAnimatrix Date: Tue, 1 Dec 2026 14:39:18 +0530 Subject: [PATCH 2/7] feat(secrets): /secform opens a form of named secrets in threads and bot chats, with expiry, who may use them, single use and a chip to revoke --- src/main/mms/protocolEventBridge.ts | 5 + src/mms/MmsProfileServices.ts | 18 +- src/mms/MousseMainService.ts | 17 ++ src/mms/bots/chat/BotChatService.ts | 9 + src/mms/bots/chat/projection.ts | 5 +- src/mms/bridge/routed/OwnerRoutes.ts | 6 +- src/mms/orchestrator/OrchestratorService.ts | 21 +- src/mms/protocol/server.ts | 7 + src/mms/protocol/types.ts | 2 + src/mms/secrets/SecretShares.ts | 255 +++++++++++++++++ src/mms/secrets/SecretVault.ts | 43 ++- src/mms/secrets/registerMethods.ts | 78 ++++++ src/mms/secrets/secretShareNote.ts | 18 ++ src/mms/secrets/secretToolHost.ts | 4 +- src/preload/index.ts | 6 + src/renderer/chat/adapters/mousseToUI.ts | 10 + .../agent-elements/message-list.tsx | 7 +- src/renderer/components/ChatComposer.tsx | 4 +- src/renderer/components/OrchestratorChat.tsx | 36 ++- src/renderer/components/bots/BotChatView.tsx | 40 ++- src/renderer/components/bots/botChatShape.ts | 4 +- src/renderer/components/bots/botCommands.ts | 15 +- src/renderer/components/bots/runBotCommand.ts | 8 + .../components/secrets/SecformCard.tsx | 259 ++++++++++++++++++ .../components/secrets/SecretShareChip.tsx | 107 ++++++++ .../components/settings/IconButtons.tsx | 7 + .../components/settings/SecretsSettings.tsx | 44 +-- src/renderer/lib/slashCommands.ts | 13 + src/renderer/services/secretsClient.ts | 21 +- src/renderer/styles/app.css | 150 ++++++++++ src/shared/bots/personal/chat.ts | 2 + src/shared/bridge/routed.ts | 16 +- src/shared/composerCommands.ts | 21 +- src/shared/secform.ts | 86 ++++++ src/shared/secretRequests.ts | 7 + src/shared/types.ts | 5 + tests/renderer/boundSecretsSettings.test.ts | 4 +- 37 files changed, 1315 insertions(+), 45 deletions(-) create mode 100644 src/mms/secrets/SecretShares.ts create mode 100644 src/mms/secrets/secretShareNote.ts create mode 100644 src/renderer/components/secrets/SecformCard.tsx create mode 100644 src/renderer/components/secrets/SecretShareChip.tsx diff --git a/src/main/mms/protocolEventBridge.ts b/src/main/mms/protocolEventBridge.ts index a47b36cef9..d983c8e284 100644 --- a/src/main/mms/protocolEventBridge.ts +++ b/src/main/mms/protocolEventBridge.ts @@ -275,6 +275,11 @@ export function bridgeProtocolEvent( if (threadId != null) broadcast('secrets:requestsChanged', { threadId }) return true } + case 'secrets.shares.changed': { + // Only the thread id: a window reads the thread's shared secrets (`/secform`) itself. + if (threadId != null) broadcast('secrets:sharesChanged', { threadId }) + return true + } case 'computerUse.setupRequest.changed': { // Only the thread id: a window reads the thread's setup card itself. if (threadId != null) broadcast('computerUse:setupRequestChanged', { threadId }) diff --git a/src/mms/MmsProfileServices.ts b/src/mms/MmsProfileServices.ts index b78d0c198a..d3ed3b0b68 100644 --- a/src/mms/MmsProfileServices.ts +++ b/src/mms/MmsProfileServices.ts @@ -12,6 +12,7 @@ import { BugReportService } from './bugReports/BugReportService' import { WebPictures } from './webPictures/WebPictures' import { createGhFallbackRunner, execRunner } from './git/ghRunner' import { userAction } from './git/gitPolicy' +import { SecretShares } from './secrets/SecretShares' import { SecretRequests } from './secrets/SecretRequests' import { createSecretToolHost } from './secrets/secretToolHost' import { forgetWorktreeFolders, refreshWorktreeFolders, setWorktreeFolders } from './worktree/worktreeLayout' @@ -1607,9 +1608,23 @@ export class MmsProfileServices { // A subagent's thread is masked with its parents' secrets: their agents may hand it the value. ancestorsOf: (threadId) => threadAncestors(this.threads, threadId), threadBusy: (threadId) => secretThreadBusy(threadId, this.orchestrator, this.runEngine), - changed: () => this.secretsChanged.emit('changed') + changed: () => { + this.secretsChanged.emit('changed') + this.secretShares?.storeChanged() + }, + usedUp: (name, shareId) => this.secretShares?.usedUp(name, shareId) }) this.secretRequests = new SecretRequests(this.secretVault) + // Secrets a person shares with /secform (asks i121, i125): kept in the same store, for the thread or bot chosen. + this.secretShares = new SecretShares({ + profileRoot: homeDir, + vault: this.secretVault, + threadAlive: (threadId) => Boolean(this.threads.getThread(threadId)), + botHome: (botId) => { + if (!this.personalBots) throw new Error('Bots are not available.') + return this.personalBots.service.secretHome(botId) + } + }) const vault = this.secretVault // Bug reports (Settings → General → Error reports): the Report button's and report_bug's filing. const runner = createGhFallbackRunner(execRunner) @@ -2504,6 +2519,7 @@ export class MmsProfileServices { automationKeys!: { list(): string[]; set(name: string, value: string): void; has(name: string): boolean } /** Secrets agents asked for in threads, over the profile's secret store (#595). */ secretVault!: SecretVault + secretShares?: SecretShares secretRequests!: SecretRequests /** Emits `changed` when a secret is added, used, removed or expires (Settings → Secrets refreshes). */ readonly secretsChanged = new EventEmitter() diff --git a/src/mms/MousseMainService.ts b/src/mms/MousseMainService.ts index 6d32ef96c6..4d0d54ab5e 100644 --- a/src/mms/MousseMainService.ts +++ b/src/mms/MousseMainService.ts @@ -40,6 +40,7 @@ import { registerComputerUseMethods } from './computerUse/registerMethods' import { registerSourceControlMethods } from './sourceControl/registerMethods' import { GitHubAccount } from './git/GitHubAccount' import { registerSecretMethods } from './secrets/registerMethods' +import { secretShareNote } from './secrets/secretShareNote' import { registerBugReportMethods } from './bugReports/registerMethods' import { registerWorkflowDefinitionMethods } from './workflows/registerDefinitionMethods' import { registerWorkflowRunMethods } from './workflows/registerRunMethods' @@ -414,6 +415,22 @@ export class MousseMainService extends MmsProfileServices { if (!services.personalBots) throw new Error('Bots are not available.') return services.personalBots.service.secretHome(botId) } }, + shares: services.secretShares ? { + share: (input) => { + const { usableIn, ...share } = services.secretShares!.share(input) + const text = secretShareNote(share, Date.now()) + const bot = share.botId ? services.personalBots?.service : undefined + // A bot's chat keeps a quiet line the bot reads next turn, drawn as the chip there. + if (share.botId && bot) bot.postSecretShare(share.botId, share.shareId, text) + // An agent thread shows the chip, and its agent (when it may use them) gets the names with its next turn. + if (share.threadId !== usableIn || !share.botId) { + services.orchestrator.recordSecretShare(share.threadId, share, share.botId ? undefined : { threadId: usableIn, text }) + } + return share + }, + list: (threadId) => services.secretShares!.list(threadId), + revoke: (threadId, shareId) => services.secretShares!.revoke(threadId, shareId) + } : undefined, list: () => services.secretVault.list(), delete: (name) => services.secretVault.delete(name) } diff --git a/src/mms/bots/chat/BotChatService.ts b/src/mms/bots/chat/BotChatService.ts index f1a78acb11..9ef0193611 100644 --- a/src/mms/bots/chat/BotChatService.ts +++ b/src/mms/bots/chat/BotChatService.ts @@ -44,6 +44,7 @@ import { pictureInfos, pictureThumbs, type PictureInfos } from '../../pictures/P import type { PictureThumbs } from '../../pictures/PictureThumbs' import { describedInOrder, localPictureFiles, withMessagePictures, type PictureFiles } from './messagePictures' import { turnTimingBegin, turnTimingBotMark, turnTimingForget } from '../../diagnostics/turnTiming' +import { SECFORM_LINE_PREFIX } from '../../../shared/secform' /** * The Bot UI's daemon side (Bot Phase 1 §5.3, §5.11): create a bot from a look and a sentence, @@ -491,6 +492,14 @@ export class BotChatService { * The local vault resolves its recipient here, never from a window's thread id. Every bot may be given secrets: one * with an approved grant may keep a pasted key. */ + /** + * `/secform` in the bot's chat: a quiet line from Mousse that names the secrets, which the bot reads with its next turn + * and the chat shows as the chip. It wakes nothing. + */ + postSecretShare(botId: string, shareId: string, text: string): void { + this.engine.chat.post({ id: `${SECFORM_LINE_PREFIX}${shareId}`, botId, author: 'bot', kind: 'notice', text, quiet: true, lane: 'chat' }) + } + secretHome(botId: string): { threadId: string; allowed: boolean } { this.engine.definitionOf(botId) const threadId = this.store.registry(botId)?.homeThreadId diff --git a/src/mms/bots/chat/projection.ts b/src/mms/bots/chat/projection.ts index 3e4c70a17e..5a802b9417 100644 --- a/src/mms/bots/chat/projection.ts +++ b/src/mms/bots/chat/projection.ts @@ -29,9 +29,10 @@ import { takeToolImages } from './toolImages' import { takeReplyCards } from './replyCards' import { readSilentReply, WAKE_LINE_PREFIX, wakeEventLabel } from '../../../shared/bots/personal/wakes' import { BOT_FOLD_LINE_PREFIX, BOT_FOLD_LINE_TITLE } from '../../../shared/bots/personal/memory' +import { SECFORM_LINE_PREFIX } from '../../../shared/secform' function isServiceLine(id: string): boolean { - return ['bm_asks_first_', 'bm_permission_', 'bm_schedule_ended_', 'bm_schedule_done_', WAKE_LINE_PREFIX, BOT_FOLD_LINE_PREFIX].some(prefix => id.startsWith(prefix)) + return ['bm_asks_first_', 'bm_permission_', 'bm_schedule_ended_', 'bm_schedule_done_', WAKE_LINE_PREFIX, BOT_FOLD_LINE_PREFIX, SECFORM_LINE_PREFIX].some(prefix => id.startsWith(prefix)) } import type { AppletReference } from '../../../shared/applets' import { BOT_USAGE_WINDOW_MS, botContextSummary, turnUsageSummary } from '../activation/turnUsage' @@ -448,6 +449,8 @@ export class BotChatProjection { ...(row.kind === 'notice' && isServiceLine(row.id) ? { systemLine: true as const } : {}), // A fold's line says what happened on hover (docs/plans/bot-context.md §14). ...(row.kind === 'notice' && row.id.startsWith(BOT_FOLD_LINE_PREFIX) ? { systemTitle: BOT_FOLD_LINE_TITLE } : {}), + // Secrets shared with /secform: the chat shows the form's chip instead of the words the bot reads. + ...(row.kind === 'notice' && row.id.startsWith(SECFORM_LINE_PREFIX) ? { secretShare: { shareId: row.id.slice(SECFORM_LINE_PREFIX.length) } } : {}), text: plain ? (said ? `${said}\n\n${plain}` : plain) : said, ...(plain ? { plainFrom: said.length } : {}), ...(cards.length ? { cards } : {}), diff --git a/src/mms/bridge/routed/OwnerRoutes.ts b/src/mms/bridge/routed/OwnerRoutes.ts index 9f28452d20..d13e074a01 100644 --- a/src/mms/bridge/routed/OwnerRoutes.ts +++ b/src/mms/bridge/routed/OwnerRoutes.ts @@ -8,6 +8,7 @@ import type { NodeCapability } from '../../../shared/net' import { ROUTED_AGENT_BOT_KEY, ROUTED_DISPLAY_ONLY_KEYS, + ROUTED_SECRET_KEYS, ROUTED_AGENT_CHAIN_KEY, ROUTED_AGENT_KEY, routedKeyForbidden, @@ -724,7 +725,10 @@ export class OwnerRoutes { } : {}), // A display-only key (a bot's name and face) is no part of what a retry is matched on (#2010). - ...(ROUTED_DISPLAY_ONLY_KEYS[method] ? { ledgerMatch: (params: unknown) => withoutKeys(params, ROUTED_DISPLAY_ONLY_KEYS[method]!) } : {}), + // Nor is a secret value (`/secform`): the ledger keeps no hash of one. + ...(ROUTED_DISPLAY_ONLY_KEYS[method] || ROUTED_SECRET_KEYS[method] + ? { ledgerMatch: (params: unknown) => withoutKeys(params, [...(ROUTED_DISPLAY_ONLY_KEYS[method] ?? []), ...(ROUTED_SECRET_KEYS[method] ?? [])]) } + : {}), handle: (params, context) => this.options.track(this.run(method, row, params as Record, context)) } diff --git a/src/mms/orchestrator/OrchestratorService.ts b/src/mms/orchestrator/OrchestratorService.ts index dafbf8c66d..dcacd42c34 100644 --- a/src/mms/orchestrator/OrchestratorService.ts +++ b/src/mms/orchestrator/OrchestratorService.ts @@ -6310,6 +6310,24 @@ export class OrchestratorService extends EventEmitter { } } + /** + * `/secform`: the person shared secrets in this thread. The chat gets the chip's row (`secretShare`); the agent that + * may use them (`usableIn`: this thread, or a thread a bot works in) gets `note`, quiet, with its next turn. Both name + * the secrets only: their values never pass through here. + */ + recordSecretShare(threadId: string, share: { shareId: string; names: string[] }, note: { threadId: string; text: string } | undefined): void { + this.sessionAls.run(this.getOrCreateSession(threadId), () => this.addSystemMessage(`Shared ${share.names.join(', ')} with /secform.`, undefined, undefined, undefined, share)) + if (!note) return + const payload: AgentNotePayload = { + kind: 'agent_note', senderThreadId: threadId, senderRunId: '', senderTitle: null, senderAccess: 'agent', from: 'relay', attention: 'none', text: note.text + } + try { + postNote(this.requireRunEngine(), `secform:${share.shareId}`, payload, note.threadId) + } catch (error) { + console.warn('the agent could not be told the names of shared secrets', { shareId: share.shareId, error: error instanceof Error ? error.message : String(error) }) + } + } + /** Tells a held message's sender what became of it, with a quiet note from Mousse it reads with its next turn. */ private tellHoldSender(hold: ChainHoldRecord, outcome: string): void { // A sender on another computer has no thread here to tell: it was told its message is held, and ended its turn. @@ -14301,12 +14319,13 @@ export class OrchestratorService extends EventEmitter { * `kind` `warning`: a line the thread shows, quiet, as Mousse's own (`ThreadNotice`). Others are not shown, the note * of a launched thread (`launchedThread`) among them. */ - private addSystemMessage(content: string, end?: { turnId?: string; turnEnd: TurnEnd }, kind?: 'warning', launchedThread?: ChatMessage['launchedThread']): void { + private addSystemMessage(content: string, end?: { turnId?: string; turnEnd: TurnEnd }, kind?: 'warning', launchedThread?: ChatMessage['launchedThread'], secretShare?: ChatMessage['secretShare']): void { const msg: ChatMessage = { id: uuidv4(), role: 'system', ...(kind ? { kind } : {}), ...(launchedThread ? { launchedThread } : {}), + ...(secretShare ? { secretShare: { shareId: secretShare.shareId, names: [...secretShare.names] } } : {}), content, timestamp: new Date().toISOString(), ...(end?.turnId ? { turnId: end.turnId } : {}), diff --git a/src/mms/protocol/server.ts b/src/mms/protocol/server.ts index b1e167724a..b5ca383f56 100644 --- a/src/mms/protocol/server.ts +++ b/src/mms/protocol/server.ts @@ -875,6 +875,13 @@ export class MmsProtocolServer { emitToSubscribers(this.ring.push('secrets.requests.changed', { threadId: payload.threadId }, payload.threadId)) }) } + // Secrets shared with /secform: only the thread id travels; a window reads the thread's chips itself. + const secretShares = services.secretShares + if (secretShares) { + onEmitter(secretShares, 'changed', (payload: { threadId: string }) => { + emitToSubscribers(this.ring.push('secrets.shares.changed', { threadId: payload.threadId }, payload.threadId)) + }) + } // Computer use setup cards: only the thread id travels; a window of this computer reads the card itself. Nothing // waits on one, so the thread's state stays as it is. const computerSetup = typeof services.orchestrator.computerUseSetup === 'function' ? services.orchestrator.computerUseSetup() : undefined diff --git a/src/mms/protocol/types.ts b/src/mms/protocol/types.ts index c00ed996ef..ace728c624 100644 --- a/src/mms/protocol/types.ts +++ b/src/mms/protocol/types.ts @@ -703,6 +703,7 @@ export type ProtocolEventType = | 'questions.pending' | 'questions.cleared' | 'secrets.requests.changed' + | 'secrets.shares.changed' | 'computerUse.setupRequest.changed' | 'secrets.changed' | 'pty.data' @@ -732,6 +733,7 @@ export type ProtocolEventType = | 'questions.pending' | 'questions.cleared' | 'secrets.requests.changed' + | 'secrets.shares.changed' | 'computerUse.setupRequest.changed' | 'secrets.changed' | 'pty.data' diff --git a/src/mms/secrets/SecretShares.ts b/src/mms/secrets/SecretShares.ts new file mode 100644 index 0000000000..e43e3a46e8 --- /dev/null +++ b/src/mms/secrets/SecretShares.ts @@ -0,0 +1,255 @@ +import { EventEmitter } from 'node:events' +import { randomUUID } from 'node:crypto' +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { isKeyName } from '../../shared/automationKeys' +import { secretValueProblem } from '../../shared/secretRequests' +import { + SECFORM_EXPIRIES, + SECFORM_MAX_FIELDS, + secformExpiresAt, + type SecformAudience, + type SecformExpiry, + type SecretShareState, + type SecretShareView +} from '../../shared/secform' +import { atomicWriteJsonSync } from '../data/AtomicFs' +import { ensurePrivateDirectory } from '../data/privateAcl' +import { SecretRequestError } from './SecretRequests' +import type { SecretVault } from './SecretVault' + +/** One form's record in `secrets/shares.json`: names and times, never a value. */ +interface ShareRecord { + /** The thread the form was opened in: its chat shows the chip. */ + threadId: string + /** The thread whose agents may use the secrets: the same thread, or a bot's chat. */ + usableIn: string + botId?: string + names: string[] + createdAt: string + expiresAt?: string + singleUse?: true + revokedAt?: string + /** Single-use names that were used, and so deleted. */ + usedUp?: string[] +} + +/** How long an ended form's record stays, so its chip still says what happened. */ +const ENDED_RECORD_KEEP_MS = 30 * 24 * 60 * 60 * 1000 + +export interface SecretSharesOptions { + profileRoot: string + vault: SecretVault + /** Whether a thread exists and is not archived. */ + threadAlive(threadId: string): boolean + /** A bot's chat thread, when the bot may keep secrets. */ + botHome?(botId: string): { threadId: string; allowed: boolean } + now?(): number +} + +/** + * The secrets a person shares with `/secform` (asks i121, i125). Each field's value goes once into the vault, the + * profile's secret store, kept as long as the form chose and usable by the thread or bot it chose; this service keeps + * which names one form gave and whether they are still kept, expired or revoked, for the chip the chat shows. The + * service sees values only inside `share`, which hands them straight to the vault. + */ +export class SecretShares extends EventEmitter { + private readonly path: string + private readonly now: () => number + + constructor(private readonly options: SecretSharesOptions) { + super() + this.path = join(options.profileRoot, 'secrets', 'shares.json') + this.now = options.now ?? Date.now + } + + /** Save securely: stores every field or none, and returns the chip's view with the names they are kept under. */ + share(input: { threadId: string; fields: unknown; expiry: unknown; singleUse: unknown; audience: unknown }): SecretShareView & { usableIn: string } { + const { threadId } = input + if (!this.options.threadAlive(threadId)) throw new SecretRequestError('not_found', 'This thread is gone.') + const fields = this.fieldsOf(input.fields) + if (typeof input.expiry !== 'string' || !(SECFORM_EXPIRIES as readonly string[]).includes(input.expiry)) throw new SecretRequestError('invalid', 'Choose when it expires.') + const expiry = input.expiry as SecformExpiry + const singleUse = input.singleUse === true + const audience = this.audienceOf(input.audience) + const usableIn = audience.kind === 'bot' ? this.botThread(audience.botId) : threadId + const now = this.now() + const expiresAt = secformExpiresAt(expiry, now) + const shareId = randomUUID() + const vault = this.options.vault + const names: string[] = [] + try { + for (const field of fields) { + const name = vault.freeName(field.name) + vault.store(name, field.value, { + keep: expiresAt ? 'day' : 'saved', + ...(expiresAt ? { expiresAt } : {}), + threadId: usableIn, + ...(field.label ? { label: field.label } : {}), + shareId, + singleUse + }) + names.push(name) + } + } catch (error) { + // All or nothing: a field that failed takes back the ones before it. + for (const name of names) vault.delete(name) + throw error + } + const record: ShareRecord = { + threadId, + usableIn, + ...(audience.kind === 'bot' ? { botId: audience.botId } : {}), + names, + createdAt: new Date(now).toISOString(), + ...(expiresAt ? { expiresAt } : {}), + ...(singleUse ? { singleUse: true as const } : {}) + } + this.write({ ...this.prune(this.read()), [shareId]: record }) + this.changed(record) + return { ...this.view(shareId, record), usableIn } + } + + /** The forms given in a thread, or for it (a bot's chat: forms whose secrets it may use), oldest first. */ + list(threadId: string): SecretShareView[] { + return Object.entries(this.read()) + .filter(([, record]) => record.threadId === threadId || record.usableIn === threadId) + .sort(([, a], [, b]) => a.createdAt.localeCompare(b.createdAt)) + .map(([shareId, record]) => this.view(shareId, record)) + } + + /** Revoke: every secret of the form still kept is deleted now. */ + revoke(threadId: string, shareId: string): SecretShareView { + const records = this.read() + const record = records[shareId] + if (!record || (record.threadId !== threadId && record.usableIn !== threadId)) throw new SecretRequestError('not_found', 'These secrets are no longer listed.') + for (const name of record.names) if (this.options.vault.shareOf(name) === shareId) this.options.vault.delete(name) + const next = record.revokedAt ? record : { ...record, revokedAt: new Date(this.now()).toISOString() } + this.write({ ...records, [shareId]: next }) + this.changed(next) + return this.view(shareId, next) + } + + /** A single-use secret was used: its form remembers it, so the chip reads expired rather than revoked. */ + usedUp(name: string, shareId: string | undefined): void { + if (!shareId) return + const records = this.read() + const record = records[shareId] + if (!record || record.usedUp?.includes(name)) return + this.write({ ...records, [shareId]: { ...record, usedUp: [...(record.usedUp ?? []), name] } }) + this.changed(record) + } + + /** The store changed (Settings removed one, a sweep expired one): every chip that may read differently is told. */ + storeChanged(): void { + const threads = new Set(Object.values(this.read()).filter((record) => !record.revokedAt).flatMap((record) => [record.threadId, record.usableIn])) + for (const threadId of threads) this.emit('changed', { threadId }) + } + + /** Both chats that show a form's chip are told: where it was filled in, and the bot chat that may use it. */ + private changed(record: ShareRecord): void { + this.emit('changed', { threadId: record.threadId }) + if (record.usableIn !== record.threadId) this.emit('changed', { threadId: record.usableIn }) + } + + private view(shareId: string, record: ShareRecord): SecretShareView { + return { + shareId, + threadId: record.threadId, + names: [...record.names], + createdAt: record.createdAt, + ...(record.expiresAt ? { expiresAt: record.expiresAt } : {}), + ...(record.singleUse ? { singleUse: true } : {}), + ...(record.botId ? { botId: record.botId } : {}), + state: this.stateOf(shareId, record) + } + } + + /** + * Revoked when taken back on the chip; expired when its time passed or every single-use secret was used; revoked as + * well when the secrets were deleted some other way (Settings → Secrets). + */ + private stateOf(shareId: string, record: ShareRecord): SecretShareState { + if (record.revokedAt) return 'revoked' + if (record.expiresAt && Date.parse(record.expiresAt) <= this.now()) return 'expired' + const kept = record.names.filter((name) => this.options.vault.shareOf(name) === shareId) + if (kept.length) return 'saved' + return record.usedUp?.length ? 'expired' : 'revoked' + } + + private fieldsOf(raw: unknown): Array<{ name: string; label?: string; value: string }> { + if (!Array.isArray(raw) || raw.length === 0) throw new SecretRequestError('invalid', 'Add a secret.') + if (raw.length > SECFORM_MAX_FIELDS) throw new SecretRequestError('invalid', `A form holds at most ${SECFORM_MAX_FIELDS} secrets.`) + const seen = new Set() + return raw.map((field, index) => { + const entry = (field && typeof field === 'object' ? field : {}) as Record + const where = raw.length > 1 ? ` (field ${index + 1})` : '' + if (!isKeyName(entry.name)) throw new SecretRequestError('invalid', `Name it with a word like GITHUB_TOKEN${where}.`) + if (seen.has(entry.name)) throw new SecretRequestError('invalid', `${entry.name} is named twice.`) + seen.add(entry.name) + const problem = secretValueProblem(entry.value) + // The problem never repeats the value. + if (problem) throw new SecretRequestError('invalid', `${entry.name}: ${problem}`) + const label = typeof entry.label === 'string' && entry.label.trim() ? entry.label.trim().slice(0, 120) : undefined + return { name: entry.name, value: entry.value as string, ...(label ? { label } : {}) } + }) + } + + private audienceOf(raw: unknown): SecformAudience { + if (raw === undefined || raw === null) return { kind: 'thread' } + const entry = (typeof raw === 'object' ? raw : {}) as Record + if (entry.kind === 'thread') return { kind: 'thread' } + if (entry.kind === 'bot' && typeof entry.botId === 'string' && entry.botId && entry.botId.length <= 256) return { kind: 'bot', botId: entry.botId } + throw new SecretRequestError('invalid', 'Choose who can use it.') + } + + private botThread(botId: string): string { + const home = this.options.botHome?.(botId) + if (!home?.allowed) throw new SecretRequestError('invalid', "That bot is not set up yet, so it can't use secrets.") + return home.threadId + } + + /** Ended forms older than a month are forgotten. */ + private prune(records: Record): Record { + const now = this.now() + const out: Record = {} + for (const [shareId, record] of Object.entries(records)) { + const ended = this.stateOf(shareId, record) !== 'saved' + if (ended && now - Date.parse(record.createdAt) > ENDED_RECORD_KEEP_MS) continue + out[shareId] = record + } + return out + } + + private read(): Record { + if (!existsSync(this.path)) return {} + try { + const parsed = JSON.parse(readFileSync(this.path, 'utf8')) as unknown + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {} + const out: Record = {} + for (const [shareId, raw] of Object.entries(parsed as Record)) { + const entry = (raw && typeof raw === 'object' ? raw : {}) as Partial + if (typeof entry.threadId !== 'string' || typeof entry.usableIn !== 'string' || typeof entry.createdAt !== 'string' || !Array.isArray(entry.names)) continue + out[shareId] = { + threadId: entry.threadId, + usableIn: entry.usableIn, + ...(typeof entry.botId === 'string' ? { botId: entry.botId } : {}), + names: entry.names.filter(isKeyName), + createdAt: entry.createdAt, + ...(typeof entry.expiresAt === 'string' ? { expiresAt: entry.expiresAt } : {}), + ...(entry.singleUse === true ? { singleUse: true as const } : {}), + ...(typeof entry.revokedAt === 'string' ? { revokedAt: entry.revokedAt } : {}), + ...(Array.isArray(entry.usedUp) ? { usedUp: entry.usedUp.filter(isKeyName) } : {}) + } + } + return out + } catch { + return {} + } + } + + private write(records: Record): void { + ensurePrivateDirectory(join(this.options.profileRoot, 'secrets')) + atomicWriteJsonSync(this.path, records, { mode: 0o600 }) + } +} diff --git a/src/mms/secrets/SecretVault.ts b/src/mms/secrets/SecretVault.ts index b89fa8adf3..7b91d28f2c 100644 --- a/src/mms/secrets/SecretVault.ts +++ b/src/mms/secrets/SecretVault.ts @@ -21,6 +21,10 @@ interface SecretMeta { lastUsedAt?: string /** The threads whose agents may use it by name: the one that asked, and any thread the person gave it to later. */ threads: string[] + /** The `/secform` form that gave it (`SecretShares`). */ + shareId?: string + /** Deleted after its first use; never given as a file, so every use goes through Mousse and is counted. */ + singleUse?: true } type MetaFile = Record @@ -84,6 +88,8 @@ export interface SecretVaultOptions { removePath?(path: string): void /** The store changed (a secret added, used, deleted or expired). */ changed?(): void + /** A single-use secret was used and deleted. */ + usedUp?(name: string, shareId: string | undefined): void } /** @@ -189,7 +195,8 @@ export class SecretVault { isSaved(name: string, binding?: SecretBinding): boolean { if (!this.hasValue(name)) return false const meta = this.readMeta()[name] - return (!meta || meta.keep === 'saved') && sameSecretBinding(this.bindingFor(name), binding) + // A /secform secret kept with no end is for the thread or bot it was shared with, not offered to others. + return (!meta || (meta.keep === 'saved' && !meta.shareId)) && sameSecretBinding(this.bindingFor(name), binding) } /** `base`, or `base_2`, `base_3`… when the store already holds `base`. */ @@ -204,8 +211,11 @@ export class SecretVault { throw new Error('Too many secrets share this name.') } - /** Keeps a value the person typed, for the thread that asked. The name must be free (`freeName`). */ - store(name: string, value: string, input: { keep: SecretKeep; threadId: string; label?: string; binding?: SecretBinding }): void { + /** + * Keeps a value the person typed, for the thread that asked. The name must be free (`freeName`). A `/secform` + * secret comes with its own end (`expiresAt`, kept as `day`), its form and whether it is single use. + */ + store(name: string, value: string, input: { keep: SecretKeep; threadId: string; label?: string; binding?: SecretBinding; expiresAt?: string; shareId?: string; singleUse?: boolean }): void { if (!isKeyName(name)) throw new Error('A secret name is a word like GITHUB_TOKEN.') if (this.hasValue(name)) throw new Error(`A secret named ${name} already exists.`) const now = this.now() @@ -217,10 +227,12 @@ export class SecretVault { [name]: { ...(input.label ? { label: input.label.slice(0, 200) } : {}), keep: input.keep, - ...(input.keep === 'day' ? { expiresAt: new Date(now + SECRET_DAY_MS).toISOString() } : {}), + ...(input.keep === 'day' ? { expiresAt: input.expiresAt ?? new Date(now + SECRET_DAY_MS).toISOString() } : {}), threadId: input.threadId, createdAt: new Date(now).toISOString(), - threads: [input.threadId] + threads: [input.threadId], + ...(input.shareId ? { shareId: input.shareId } : {}), + ...(input.singleUse ? { singleUse: true as const } : {}) } }) this.didChange() @@ -287,7 +299,7 @@ export class SecretVault { /** The private file that holds the secret for the thread's agents to read; undefined when the thread may not use it. */ fileFor(name: string, threadId: string): string | undefined { - if (!isKeyName(name) || !FOLDER_ID.test(threadId) || !this.usableIn(name, threadId) || this.bindingFor(name)) return undefined + if (!isKeyName(name) || !FOLDER_ID.test(threadId) || !this.usableIn(name, threadId) || this.bindingFor(name) || this.readMeta()[name]?.singleUse) return undefined const path = join(this.filesRoot, threadId, name) return existsSync(path) ? path : undefined } @@ -301,13 +313,24 @@ export class SecretVault { return this.bindings.get(name) } + /** A command or a read used the secret. A single-use secret is deleted now: the use that called this has its value. */ markUsed(name: string): void { const meta = this.readMeta() if (!meta[name]) return + if (meta[name].singleUse) { + this.delete(name) + this.options.usedUp?.(name, meta[name].shareId) + return + } this.writeMeta({ ...meta, [name]: { ...meta[name], lastUsedAt: new Date(this.now()).toISOString() } }) this.options.changed?.() } + /** The `/secform` form a secret came from, while it is still kept. */ + shareOf(name: string): string | undefined { + return this.hasValue(name) ? this.readMeta()[name]?.shareId : undefined + } + /** * What masks a thread's text: every secret its agents may use, and its parents' when it is a subagent's, in * every form it can take; while a turn that had a removed or changed value settles, that value too. Undefined when @@ -402,6 +425,8 @@ export class SecretVault { ...(entry.threadId ? { threadId: entry.threadId } : {}), ...(entry.threads?.length ? { threads: [...entry.threads] } : {}), ...(title ? { threadTitle: title } : {}), + ...(entry.shareId ? { shareId: entry.shareId } : {}), + ...(entry.singleUse ? { singleUse: true } : {}), createdAt: entry.createdAt, ...(entry.lastUsedAt ? { lastUsedAt: entry.lastUsedAt } : {}) } @@ -411,7 +436,7 @@ export class SecretVault { /** The names a saved key list shows: secrets given in a thread for a while are not saved keys. */ savedKeyNames(): string[] { const meta = this.readMeta() - return listProfileKeyNames(this.options.profileRoot).filter((name) => !this.bindingFor(name) && (!meta[name] || meta[name].keep === 'saved')) + return listProfileKeyNames(this.options.profileRoot).filter((name) => !this.bindingFor(name) && (!meta[name] || (meta[name].keep === 'saved' && !meta[name].shareId))) } /** Removes a secret and its record; false when there was none. */ @@ -493,7 +518,7 @@ export class SecretVault { try { const wanted = new Map>() for (const [name, entry] of Object.entries(this.readMeta())) { - if (this.bindingFor(name)) continue + if (this.bindingFor(name) || entry.singleUse) continue const threads = entry.threads.filter((threadId) => FOLDER_ID.test(threadId) && this.copyThreads.has(threadId) && !this.holds.has(threadId) && this.options.threadAlive(threadId)) const value = threads.length ? this.value(name) : undefined if (!value) continue @@ -555,6 +580,8 @@ export class SecretVault { ...(typeof entry.threadId === 'string' ? { threadId: entry.threadId } : {}), createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : new Date(0).toISOString(), ...(typeof entry.lastUsedAt === 'string' ? { lastUsedAt: entry.lastUsedAt } : {}), + ...(typeof entry.shareId === 'string' ? { shareId: entry.shareId } : {}), + ...(entry.singleUse === true ? { singleUse: true as const } : {}), threads: Array.isArray(entry.threads) ? entry.threads.filter((id): id is string => typeof id === 'string') : [] } } diff --git a/src/mms/secrets/registerMethods.ts b/src/mms/secrets/registerMethods.ts index 4ac99ce388..e7aec12a8e 100644 --- a/src/mms/secrets/registerMethods.ts +++ b/src/mms/secrets/registerMethods.ts @@ -7,6 +7,7 @@ import type { SecretEntryView, SecretRequestView } from '../../shared/secretRequ import { DomainRpcError, domainObject, type DomainHandlerRegistry } from '../protocol/domainRegistry' import type { HandlerContext } from '../protocol/handlers' import { SecretRequestError } from './SecretRequests' +import type { SecretShareView } from '../../shared/secform' export const SECRETS_CAPABILITY = 'secrets.v1' @@ -19,6 +20,12 @@ export interface SecretsDomain { decline(threadId: string, requestId: string): void } pasted?: { vault: SecretVault; homeFor(botId: string): { threadId: string; allowed: boolean } } + /** `/secform`: the secrets a person shares in a thread or a bot's chat. */ + shares?: { + share(input: { threadId: string; fields: unknown; expiry: unknown; singleUse: unknown; audience: unknown }): SecretShareView + list(threadId: string): SecretShareView[] + revoke(threadId: string, shareId: string): SecretShareView + } list(): SecretEntryView[] delete(name: string): boolean } @@ -33,6 +40,16 @@ function fromWindow(context: HandlerContext): void { if (context.connection?.clientType !== 'gui') throw new DomainRpcError('forbidden', 'Answer it in a Mousse window on the computer that runs the thread.') } +/** + * `/secform` is filled in by a person at a Mousse window: on this computer, or on another of the user's computers for a + * thread this one runs (a routed call, sent over the encrypted link between them). Never an agent or a CLI. + */ +function fromPerson(context: HandlerContext): void { + const connection = context.connection + if (connection?.clientType === 'gui' || (connection?.clientType === 'bridge' && connection.bridgeCaller)) return + throw new DomainRpcError('forbidden', 'Share secrets from a Mousse window.') +} + /** A refusal in words that never repeat what was typed. */ function refusal(error: unknown): never { if (error instanceof DomainRpcError) throw error @@ -154,6 +171,67 @@ export function registerSecretMethods(domains: DomainHandlerRegistry, domainFor: } } }) + domains.register({ + method: 'secrets.share', + scope: 'profile', + capability: SECRETS_CAPABILITY, + validate: (params) => { + // Unknown fields are refused without naming them: even a malformed form may hold a value there. + if (!params || typeof params !== 'object' || Array.isArray(params) || Object.keys(params).some((key) => !['profileId', 'threadId', 'fields', 'values', 'expiry', 'singleUse', 'audience'].includes(key))) { + throw new DomainRpcError('invalid_params', 'Fill in the form again.') + } + const p = params as Record + id(p.threadId, 'A thread id') + if (!Array.isArray(p.fields) || !Array.isArray(p.values) || p.fields.length !== p.values.length) throw new DomainRpcError('invalid_params', 'Fill in the form again.') + return p + }, + async handle(context, params, binding) { + fromPerson(context) + const domain = await bound(binding) + if (!domain.shares) throw new DomainRpcError('not_found', 'Secrets cannot be shared here.') + // The values travel apart from the names (`values`), so a routed call's ledger never matches a retry on them. + const fields = (params.fields as unknown[]).map((field, index) => ({ ...(field && typeof field === 'object' ? field : {}), value: (params.values as unknown[])[index] })) + try { + return { share: domain.shares.share({ threadId: params.threadId as string, fields, expiry: params.expiry, singleUse: params.singleUse, audience: params.audience }) } + } catch (error) { + refusal(error) + } + } + }) + domains.register({ + method: 'secrets.shares.list', + scope: 'profile', + capability: SECRETS_CAPABILITY, + validate: (params) => { + const p = domainObject(params ?? {}, ['profileId', 'threadId']) + id(p.threadId, 'A thread id') + return p + }, + async handle(_context, params, binding) { + return { shares: (await bound(binding)).shares?.list(params.threadId as string) ?? [] } + } + }) + domains.register({ + method: 'secrets.shares.revoke', + scope: 'profile', + capability: SECRETS_CAPABILITY, + validate: (params) => { + const p = domainObject(params ?? {}, ['profileId', 'threadId', 'shareId']) + id(p.threadId, 'A thread id') + id(p.shareId, 'A share id') + return p + }, + async handle(context, params, binding) { + fromPerson(context) + const domain = await bound(binding) + if (!domain.shares) throw new DomainRpcError('not_found', 'These secrets are no longer listed.') + try { + return { share: domain.shares.revoke(params.threadId as string, params.shareId as string) } + } catch (error) { + refusal(error) + } + } + }) domains.register({ method: 'secrets.list', scope: 'profile', diff --git a/src/mms/secrets/secretShareNote.ts b/src/mms/secrets/secretShareNote.ts new file mode 100644 index 0000000000..a5a7f502ef --- /dev/null +++ b/src/mms/secrets/secretShareNote.ts @@ -0,0 +1,18 @@ +import { timeLeft, type SecretShareView } from '../../shared/secform' + +/** + * What the agent (or bot) that may use secrets shared with `/secform` is told, quietly, with its next turn: their names, + * how long they last and how to use them. Never a value. The agent-facing wording; changes go through council review. + */ +export function secretShareNote(share: Pick, now: number): string { + const [first] = share.names + const many = share.names.length > 1 + const lasting = share.expiresAt ? `${many ? 'They expire' : 'It expires'} in ${timeLeft(Date.parse(share.expiresAt) - now)}` : `${many ? 'They stay' : 'It stays'} until the user revokes ${many ? 'them' : 'it'}` + return [ + `The user shared ${many ? `${share.names.length} secrets` : 'a secret'} with you in a secure form: ${share.names.join(', ')}.`, + `Mousse keeps the ${many ? 'values' : 'value'} out of the chat; you have the ${many ? 'names' : 'name'} only.`, + `${lasting}${share.singleUse ? `, and ${many ? 'each' : 'it'} is deleted after its first use` : ''}.`, + `Use ${many ? 'one' : 'it'} by name with secret_run: secrets [{ "name": "${first}" }] gives it to one command as the environment variable ${first} (or a file whose path is in ${first}_FILE), and its output comes back masked. \${secret:${first}} reads it in an MCP server's settings.`, + `Use ${many ? 'them' : 'it'} for what the user asks. Never print, echo or write ${many ? 'a value' : 'the value'} into a reply, a message or a file.` + ].join(' ') +} diff --git a/src/mms/secrets/secretToolHost.ts b/src/mms/secrets/secretToolHost.ts index 46e445a891..69d0779226 100644 --- a/src/mms/secrets/secretToolHost.ts +++ b/src/mms/secrets/secretToolHost.ts @@ -26,12 +26,14 @@ export function createSecretToolHost(input: { vault: SecretVault; requests: Secr if (value === undefined) throw new Error(`The secret ${entry.name} is gone (it expired or was removed).`) return { ...entry, value } }) + // Built before the use is counted: a single-use secret is deleted then, and its output must still be masked. + const mask = vault.maskerFor(run.threadId) ?? ((text: string) => text) for (const entry of secrets) vault.markUsed(entry.name) return runWithSecrets({ command: run.command, cwd: run.cwd, secrets, - mask: vault.maskerFor(run.threadId) ?? ((text) => text), + mask, scratchRoot: input.scratchRoot, timeoutMs: run.timeoutMs, signal: run.signal, diff --git a/src/preload/index.ts b/src/preload/index.ts index 84b5cb0564..6fa898c92d 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -351,6 +351,12 @@ const api = { ipcRenderer.on('secrets:requestsChanged', handler) return () => ipcRenderer.removeListener('secrets:requestsChanged', handler) }, + /** A thread's secrets shared with `/secform` changed; read them with `secrets.shares.list`. Carries no value. */ + onSecretSharesChanged: (cb: (payload: { threadId: string }) => void): (() => void) => { + const handler = (_: Electron.IpcRendererEvent, payload: { threadId: string }) => cb(payload) + ipcRenderer.on('secrets:sharesChanged', handler) + return () => ipcRenderer.removeListener('secrets:sharesChanged', handler) + }, /** A thread's computer use setup card changed; read it with `computerUse.setupRequest.get`. */ onComputerUseSetupRequestChanged: (cb: (payload: { threadId: string }) => void): (() => void) => { const handler = (_: Electron.IpcRendererEvent, payload: { threadId: string }) => cb(payload) diff --git a/src/renderer/chat/adapters/mousseToUI.ts b/src/renderer/chat/adapters/mousseToUI.ts index 8d4c73302d..a2e0379d67 100644 --- a/src/renderer/chat/adapters/mousseToUI.ts +++ b/src/renderer/chat/adapters/mousseToUI.ts @@ -555,6 +555,16 @@ export function mousseToUIMessages(messages: ChatMessage[], senders?: TurnSender continue } + // Secrets the person shared with /secform: a chip of Mousse's own (names only), apart from the agent's answer. + if (msg.role === 'system' && msg.secretShare) { + base.metadata = { ...base.metadata as object, notice: true, secretShare: msg.secretShare } + base.parts = [{ type: 'text', text: msg.content } as unknown as UIMessage['parts'][number]] + base.role = 'assistant' + out.push(base) + lastAssistantText = null + continue + } + if (msg.kind === 'progress' || msg.kind === 'warning' || msg.kind === 'context_compaction' || msg.kind === 'context_cleared') { if (msg.kind === 'context_cleared') base.metadata = { ...base.metadata as object, contextCleared: true } if (msg.kind === 'context_compaction') base.metadata = { ...base.metadata as object, compaction: true, compacting: msg.streaming === true, diff --git a/src/renderer/chat/components/agent-elements/message-list.tsx b/src/renderer/chat/components/agent-elements/message-list.tsx index 22e1d387a9..6aeef8ba90 100644 --- a/src/renderer/chat/components/agent-elements/message-list.tsx +++ b/src/renderer/chat/components/agent-elements/message-list.tsx @@ -57,6 +57,7 @@ import { SubagentCardGroup } from "./tools/SubagentCard"; import { isCardRunning } from "./tools/subagent-card-logic"; import type { SubagentCardModel } from "../../adapters/subagentCards"; import { SecretRequestInline, isSecretRequestPart, isWaitingSecretRequest } from "../../../components/secrets/secretRequestPart"; +import { SecretShareChip } from "../../../components/secrets/SecretShareChip"; import { BackgroundNotice, SettleNotice, SubagentNotice } from "./tools/SubagentNotice"; import { SteerGroup } from "./steer-group"; import { isRunningSubagent } from "../../../../shared/subagents"; @@ -3620,7 +3621,11 @@ const AssistantParts = memo(function AssistantParts({ toolRenderers, ]); - if (isThreadNotice(msg)) return part.text).join('')} />; + if (isThreadNotice(msg)) { + const share = (msg.metadata as { secretShare?: { shareId: string; names: string[] } } | undefined)?.secretShare; + if (share) return ; + return part.text).join('')} />; + } const handoff = (msg.metadata as { contextHandoff?: HandoffMarker } | undefined)?.contextHandoff; if (handoff) return part.text).join('')} />; if ((msg.metadata as { contextCleared?: boolean } | undefined)?.contextCleared) diff --git a/src/renderer/components/ChatComposer.tsx b/src/renderer/components/ChatComposer.tsx index df800768b9..408a43778a 100644 --- a/src/renderer/components/ChatComposer.tsx +++ b/src/renderer/components/ChatComposer.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { SECFORM_COMMAND } from '../../shared/secform' import type { ComponentProps, CSSProperties, ReactNode } from 'react' import { File as FileIcon, IconPhoto, MessageSquare, Mic, RefreshCw, Reply, X } from '../lib/icons' import type { @@ -1398,7 +1399,8 @@ export function ChatComposer({ const suggestion = item.command // An exact command that needs no text is already complete: execute it instead of // making users press Enter twice (first to re-apply the same suggestion). - if (e.key === 'Enter' && suggestion.argument !== 'required' && input.trim().toLowerCase() === `/${suggestion.name}`) { + // `/secform for email, password` too: its row stays while its fields are typed, and Enter opens the form. + if (e.key === 'Enter' && suggestion.argument !== 'required' && (input.trim().toLowerCase() === `/${suggestion.name}` || (suggestion.name === SECFORM_COMMAND && /^\/secform\s/i.test(input)))) { submit() } else { applySuggestion(suggestion) diff --git a/src/renderer/components/OrchestratorChat.tsx b/src/renderer/components/OrchestratorChat.tsx index aa749cc6a1..8b559efd5e 100644 --- a/src/renderer/components/OrchestratorChat.tsx +++ b/src/renderer/components/OrchestratorChat.tsx @@ -149,6 +149,10 @@ import { SecretRequestActionsContext, useSecretRequestsElsewhere, withSecretRequ import { SecretRequestRow } from './secrets/SecretRequestRow' import { usePendingSecretRequests } from '../hooks/usePendingSecretRequests' import { createSecretsClient } from '../services/secretsClient' +import { SecformCard, type SecformAudienceOption } from './secrets/SecformCard' +import { SecretSharesContext, useSecretShares } from './secrets/SecretShareChip' +import { useBotsStore } from '../stores/botsStore' +import type { SecformField } from '../../shared/secform' /** The chat's custom tool rows: drafts and run reports, and a secret request's row (#595). */ const THREAD_TOOL_RENDERERS = { ...CHAT_TOOL_RENDERERS, secret_request: SecretRequestRow } @@ -555,6 +559,15 @@ export function OrchestratorChat() { // The open thread's secret cards (#595): an agent asked for a secret; the value goes only to this computer's daemon. const secretsClient = useMemo(() => createSecretsClient(window.mousse?.platformRequest), []) const { requests: secretRequests, refresh: refreshSecretRequests } = usePendingSecretRequests(activeThreadId, secretsClient) + // `/secform`: the open form (its thread and the fields it opened with), and the chips of the forms given here. + const [secform, setSecform] = useState<{ threadId: string; fields: SecformField[] } | null>(null) + const secretShares = useSecretShares(activeThreadId, secretsClient) + const bots = useBotsStore((state) => state.bots) + // Who may use them: this thread, or a bot of this computer (a thread of another computer offers only itself). + const secformAudiences = useMemo(() => [ + { value: 'thread', label: 'This thread' }, + ...(activeThreadId && isQualifiedId(activeThreadId) ? [] : bots.filter((bot) => !bot.lives).map((bot) => ({ value: `bot:${bot.id}`, label: `${bot.name} only` }))) + ], [activeThreadId, bots]) const [connectionFailed, setConnectionFailed] = useState(false) const [sendFailure, setSendFailure] = useState(null) const sendError = sendFailure?.message ?? null @@ -1622,7 +1635,8 @@ export function OrchestratorChat() { rename: async (threadId, title) => { await window.mousse.threads.rename(threadId, title) }, // The sidebar cancels the event when it opened the thread's rename box. openRename: (threadId) => !window.dispatchEvent(new CustomEvent('mousse:rename-thread', { detail: { threadId }, cancelable: true })), - goal: (threadId, action, text) => window.mousse.platformRequest.request<{ text?: string }>('threads.goal', { threadId, action, ...(text !== undefined ? { text } : {}) }) + goal: (threadId, action, text) => window.mousse.platformRequest.request<{ text?: string }>('threads.goal', { threadId, action, ...(text !== undefined ? { text } : {}) }), + openSecform: (threadId, spec) => setSecform({ threadId, fields: spec.fields }) }) // A message sent from the warm start (WarmChat) while the window was connecting goes once, as an ordinary send of the @@ -2433,6 +2447,7 @@ export function OrchestratorChat() { entry.id === selectedProviderId)?.instanceId} snapshots={providerSnapshots} /> + + {/* /secform: the values go once to the computer that runs the thread, never into the composer or the chat. */} + {secform && secform.threadId === activeThreadId && ( +
+ setSecform(null)} + onSave={async (save) => { + const audience = save.audience.startsWith('bot:') ? { kind: 'bot' as const, botId: save.audience.slice(4) } : { kind: 'thread' as const } + await secretsClient.share({ threadId: secform.threadId, fields: save.fields, expiry: save.expiry, singleUse: save.singleUse, audience }) + secretShares.refresh() + setSecform(null) + }} + /> +
+ )} @@ -2647,6 +2680,7 @@ export function OrchestratorChat() { )} /> +
diff --git a/src/renderer/components/bots/BotChatView.tsx b/src/renderer/components/bots/BotChatView.tsx index 948486da58..e3f2c05a76 100644 --- a/src/renderer/components/bots/BotChatView.tsx +++ b/src/renderer/components/bots/BotChatView.tsx @@ -40,6 +40,11 @@ import { BotReminderReplies } from './BotReminderReplies' import { BotQuestionReplies } from './BotQuestionReplies' import { onBotMessageRequest, takeBotMessage } from '../../lib/botMessageLink' import { BotSecretRequests } from './BotSecretRequests' +import { SecformCard } from '../secrets/SecformCard' +import { SecretShareChip, SecretSharesContext, useSecretShares } from '../secrets/SecretShareChip' +import { createSecretsClient } from '../../services/secretsClient' +import { SECFORM_OPEN_EVENT } from './runBotCommand' +import type { SecformField } from '../../../shared/secform' import { ComputerUseSetupCard } from '../ComputerUseSetupCard' import { BotCards, galleryPaths } from './BotCards' import { BotActivitySticker, BotPresenceLine } from './BotPresence' @@ -975,6 +980,19 @@ export function BotChatView({ bot }: { bot: BotSummary }) { // About, Resume and the rest of its setup: always for this computer's bots; for a bot of another computer only with // Full bot access there while that computer is reached (`botSetupBlock`). const canSetup = !botSetupBlock(bot) + // `/secform` in this chat: the open form's fields, and the chips of what was shared with the bot. + const [secform, setSecform] = useState(null) + const secretsClient = useMemo(() => createSecretsClient(window.mousse?.platformRequest), []) + const secretShares = useSecretShares(remote ? undefined : bot.homeThreadId, secretsClient) + useEffect(() => { + setSecform(null) + const open = (event: Event): void => { + const detail = (event as CustomEvent<{ botId: string; fields: SecformField[] }>).detail + if (detail?.botId === bot.id) setSecform(detail.fields) + } + window.addEventListener(SECFORM_OPEN_EVENT, open) + return () => window.removeEventListener(SECFORM_OPEN_EVENT, open) + }, [bot.id]) const transcript = useRef(null) useReclampOpenTools(transcript) const messages = chat?.messages ?? EMPTY @@ -1319,7 +1337,7 @@ export function BotChatView({ bot }: { bot: BotSummary }) { const [voiceState, setVoiceState] = useState(null) const faceState: BotFaceState = voiceFaceState(voiceState) ?? botFaceState(bot, happy) - return + return {/* The chat pane: the conversation, and an applet beside it. The side panel docks outside it. */}
{/* The bot's colour tints the quotes of its messages. */} @@ -1393,7 +1411,8 @@ export function BotChatView({ bot }: { bot: BotSummary }) { {row.text} {row.expiredReviews.map(message => )} - : row.cut ? : } + : row.cut ? + : row.secretShare ? : } const message = row.message const key = replyKeys.keys.get(message.id) ?? message.id // Another bot's message, in its run's fold: the line sits on the first row of the run that is drawn, the @@ -1431,6 +1450,21 @@ export function BotChatView({ bot }: { bot: BotSummary }) { {unreachable && bot.lives &&

{bot.lives.name} is offline

} {/* A secret the bot asked for: typed into its private card, never into the chat. */} {!remote && } + {/* /secform: the values go once to this computer's secret store for the bot, never into the chat. */} + {!remote && secform && bot.homeThreadId && ( +
+ setSecform(null)} + onSave={async (save) => { + await secretsClient.share({ threadId: bot.homeThreadId!, fields: save.fields, expiry: save.expiry, singleUse: save.singleUse, audience: { kind: 'bot', botId: bot.id } }) + secretShares.refresh() + setSecform(null) + }} + /> +
+ )} {/* Computer use one of the bot's turns asked to set up: whatever is chosen applies from its next turn. */} {!remote && } {!remote && pasted.offer} @@ -1489,5 +1523,5 @@ export function BotChatView({ bot }: { bot: BotSummary }) { {/* A bot of another computer: its Agent settings alone; its browser and files folder stay on its computer. */} {memoryOpen && } - + } diff --git a/src/renderer/components/bots/botChatShape.ts b/src/renderer/components/bots/botChatShape.ts index 88225f563c..9181fd0068 100644 --- a/src/renderer/components/bots/botChatShape.ts +++ b/src/renderer/components/bots/botChatShape.ts @@ -50,7 +50,7 @@ export function workSignalsOf(message: BotChatMessage): { titles: string[]; queu */ export type BotChatRow = | { kind: 'message'; message: BotChatMessage } - | { kind: 'system'; id: string; at: string; text: string; title?: string; of?: string; note?: 'info' | 'error'; cut?: true; expiredReviews?: BotChatMessage[]; actionHistory?: BotChatMessage[] } + | { kind: 'system'; id: string; at: string; text: string; title?: string; of?: string; note?: 'info' | 'error'; cut?: true; expiredReviews?: BotChatMessage[]; actionHistory?: BotChatMessage[]; secretShare?: string } /** A row of this window only: a `/` command's line, or (`cut`) the words of a reply its turn stopped before finishing. */ export interface BotWindowLine { id: string; at: string; text: string; error?: true; cut?: true; expiredReviews?: BotChatMessage[]; actionHistory?: BotChatMessage[] } @@ -232,7 +232,7 @@ export function chatRows(messages: readonly BotChatMessage[], botName: string, a // The same quiet line twice in a row ("Older messages summarised" from two folds with nothing between) shows once. const previous = rows.at(-1) if (previous?.kind === 'system' && previous.text === message.text && previous.title === message.systemTitle && message.systemTitle) continue - rows.push({ kind: 'system', id: message.id, at: message.at, text: message.text, of: message.id, ...(message.systemTitle ? { title: message.systemTitle } : {}) }) + rows.push({ kind: 'system', id: message.id, at: message.at, text: message.text, of: message.id, ...(message.systemTitle ? { title: message.systemTitle } : {}), ...(message.secretShare ? { secretShare: message.secretShare.shareId } : {}) }) continue } const signals = workSignalsOf(message) diff --git a/src/renderer/components/bots/botCommands.ts b/src/renderer/components/bots/botCommands.ts index 8c3a526837..92d2d185e0 100644 --- a/src/renderer/components/bots/botCommands.ts +++ b/src/renderer/components/bots/botCommands.ts @@ -1,5 +1,7 @@ import { BOT_CUSTOM_SLOT_NAME, MAX_BOT_CUSTOM_SLOT_DESCRIPTION, type BotModelPick } from '../../../shared/bots/personal/definition' import type { LlmProviderOption } from '../../../shared/settings' +import { parseSecform, type SecformField } from '../../../shared/secform' +import { secformSuggestion } from '../../../shared/composerCommands' /** * The owner's `/` commands in a bot's chat. Mousse runs them itself: they never reach the bot, so they cost no tokens. @@ -13,6 +15,8 @@ export const BOT_BASE_SLOTS: readonly BotBaseSlot[] = ['talk', 'work', 'light', export type BotCommand = | { kind: 'clear' | 'stop' | 'status' | 'pause' | 'resume' | 'memory' | 'reset' | 'model-list' } + /** `/secform`: the form of secrets for the bot, with the fields read from what was typed. */ + | { kind: 'secform'; fields: SecformField[] } | { kind: 'forget'; history: boolean } /** `slot`: lower case; a base slot or a custom one. `description`: everything after the model, for a custom slot. */ | { kind: 'model-set'; slot: string; model: string; description?: string } @@ -33,7 +37,8 @@ const COMMANDS: readonly CommandRow[] = [ { usage: '/forget', action: 'Wipe saved memory', fill: '/forget', complete: true, setup: true }, { usage: '/forget history', action: 'Wipe chat and run notes, keep memory', fill: '/forget history', complete: true, setup: true }, { usage: '/reset', action: 'Start fresh: chat, memory, schedules', fill: '/reset', complete: true, setup: true }, - { usage: '/model', action: 'List models, or set one', fill: '/model ', complete: true, setup: true } + { usage: '/model', action: 'List models, or set one', fill: '/model ', complete: true, setup: true }, + { usage: '/secform [n]', action: 'Share secrets securely', fill: '/secform', complete: true } ] /** @@ -42,7 +47,7 @@ const COMMANDS: readonly CommandRow[] = [ * entry there still needs Full); a wrong command is answered here. */ export function isSetupCommand(command: BotCommand): boolean { - return command.kind !== 'stop' && command.kind !== 'status' && command.kind !== 'memory' && command.kind !== 'invalid' + return command.kind !== 'stop' && command.kind !== 'status' && command.kind !== 'memory' && command.kind !== 'secform' && command.kind !== 'invalid' } const NO_ARGS = new Set(['clear', 'stop', 'status', 'pause', 'resume', 'memory', 'reset']) @@ -59,7 +64,7 @@ export function baseSlotOf(word: string): BotBaseSlot | undefined { /** * What a message asks for, or null when it is an ordinary message for the bot: it does not start with a command's - * word. A `/word` that is no command (`/secform`, a path) goes to the bot as typed; a command written the wrong way + * word. A `/word` that is no command (a path) goes to the bot as typed; a command written the wrong way * is `invalid` and never sent. */ export function parseBotCommand(text: string): BotCommand | null { @@ -74,6 +79,7 @@ export function parseBotCommand(text: string): BotCommand | null { return rest.toLowerCase() === 'history' ? { kind: 'forget', history: true } : { kind: 'invalid', text: 'Use /forget or /forget history.' } } if (name === 'model') return parseModel(rest) + if (name === 'secform') return { kind: 'secform', fields: parseSecform(trimmed)?.fields ?? [] } return null } @@ -153,6 +159,9 @@ export const MAX_MODEL_SUGGESTIONS = 40 export function botCommandSuggestions(input: string, context: BotCommandContext = {}): BotCommandSuggestion[] { if (!input.startsWith('/') || input.includes('\n')) return [] const typed = input.toLowerCase().replace(/\s+/g, ' ') + // `/secform` keeps its row while its fields are typed after it, saying what the form opens with. + const secform = secformSuggestion(input) + if (secform) return [{ key: '/secform', label: '/secform [n]', description: secform.description, fill: input, complete: true }] const blocked = context.setupBlocked if (blocked && typed.startsWith('/model ')) return [] if (blocked) diff --git a/src/renderer/components/bots/runBotCommand.ts b/src/renderer/components/bots/runBotCommand.ts index e8ba415842..bb3f835f5a 100644 --- a/src/renderer/components/bots/runBotCommand.ts +++ b/src/renderer/components/bots/runBotCommand.ts @@ -7,6 +7,9 @@ import { noteBotStopAsked } from '../../stores/botLiveReplies' import { errorText } from '../../services/personalBotsClient' import { baseSlotOf, isSetupCommand, parseBotCommand, resolveModelWord, type BotCommand } from './botCommands' import { botSetupBlock } from './botSetup' + +/** Opens `/secform`'s form in a bot's chat: `detail` is `{ botId, fields }`. */ +export const SECFORM_OPEN_EVENT = 'mousse:bot-secform' import type { VoiceSendOptions } from '../../voice/voiceTarget' /** @@ -46,6 +49,11 @@ export async function runBotCommand(botId: string, command: BotCommand): Promise try { switch (command.kind) { case 'invalid': return fail(botId, command.text) + case 'secform': { + if (bot?.lives) return fail(botId, `Share secrets with this bot in its chat on ${bot.lives.name} for now.`) + window.dispatchEvent(new CustomEvent(SECFORM_OPEN_EVENT, { detail: { botId, fields: command.fields } })) + return + } case 'memory': return store().openMemory(botId) case 'forget': return confirm(botId, command.history ? 'forget-history' : 'forget') case 'reset': return confirm(botId, 'reset') diff --git a/src/renderer/components/secrets/SecformCard.tsx b/src/renderer/components/secrets/SecformCard.tsx new file mode 100644 index 0000000000..e88542a3a3 --- /dev/null +++ b/src/renderer/components/secrets/SecformCard.tsx @@ -0,0 +1,259 @@ +import { useEffect, useId, useRef, useState } from 'react' +import { Eye, EyeOff, Laptop, Lock, Plus, X } from '../../lib/icons' +import { keyNameOf, isKeyName } from '../../../shared/automationKeys' +import { secretValueProblem } from '../../../shared/secretRequests' +import { + DEFAULT_SECFORM_EXPIRY, + SECFORM_EXPIRIES, + SECFORM_MAX_FIELDS, + secformExpiryLabel, + type SecformExpiry, + type SecformField, + type SecformValue +} from '../../../shared/secform' +import { Select } from '../ui/Select' +import { Switch } from '../settings/SettingsRow' +import { errorMessage } from '../../lib/errorText' + +/** Who may use the secrets, as the form offers it: `thread`, or `bot:`. */ +export interface SecformAudienceOption { + value: string + label: string +} + +export interface SecformSave { + fields: SecformValue[] + expiry: SecformExpiry + singleUse: boolean + /** The chosen audience option's value. */ + audience: string +} + +export interface SecformCardProps { + /** The fields `/secform` opened with (`parseSecform`). */ + fields: SecformField[] + audiences: readonly SecformAudienceOption[] + /** The computer that keeps the secrets, when it is not this one. */ + storedOn?: string + /** Save securely. Rejects with a message to show; the typed values are cleared once it resolves. */ + onSave(save: SecformSave): Promise + onCancel(): void +} + +interface Row extends SecformField { + key: number + value: string + shown: boolean +} + +/** A name as typed, made a key name (`openrouter key` → `OPENROUTER_KEY`); empty while there is none. */ +function cleanName(typed: string): string { + const trimmed = typed.trim() + if (!trimmed) return '' + const keyed: boolean = isKeyName(trimmed) + return keyed ? trimmed : keyNameOf(trimmed.replace(/[^A-Za-z0-9 _.-]+/g, ' ')) ?? trimmed.toUpperCase() +} + +/** What a field's value box says while empty: a plain field names what to type, a masked one asks for the secret. */ +function valuePlaceholder(row: Pick): string { + return row.masked ? 'Paste or type the secret' : `Type the ${row.label ? row.label.toLowerCase() : 'value'}` +} + +/** + * The form `/secform` opens (asks i121, i125): named secret fields, when they expire, who may use them and whether + * each is used once. Values live only in this card's state and are sent once, to the computer that keeps them; they + * never go into the composer, the chat or a model. + */ +export function SecformCard({ fields, audiences, storedOn, onSave, onCancel }: SecformCardProps) { + const nextKey = useRef(0) + const makeRow = (field: SecformField): Row => ({ ...field, key: nextKey.current++, value: '', shown: false }) + const [rows, setRows] = useState(() => (fields.length ? fields : [{ label: '', name: '', masked: true }]).map(makeRow)) + const [expiry, setExpiry] = useState(DEFAULT_SECFORM_EXPIRY) + const [audience, setAudience] = useState(audiences[0]?.value ?? 'thread') + const [singleUse, setSingleUse] = useState(false) + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const firstEmpty = useRef(null) + const ids = useId() + const titleId = `${ids}-title` + + // The first box to fill takes the focus when the form opens. + useEffect(() => { + firstEmpty.current?.focus({ preventScroll: true }) + }, []) + + // The values live only here: gone when the card closes. + useEffect(() => () => setRows([]), []) + + const update = (key: number, change: Partial): void => setRows((current) => current.map((row) => (row.key === key ? { ...row, ...change } : row))) + const remove = (key: number): void => setRows((current) => (current.length > 1 ? current.filter((row) => row.key !== key) : current)) + const add = (): void => setRows((current) => (current.length >= SECFORM_MAX_FIELDS ? current : [...current, makeRow({ label: '', name: '', masked: true })])) + + const complete = rows.every((row) => cleanName(row.name) && row.value) + + const save = async (): Promise => { + const names = rows.map((row) => cleanName(row.name)) + const bad = names.findIndex((name) => !isKeyName(name)) + if (bad >= 0) return setError('Name each secret with a word like GITHUB_TOKEN.') + const twice = names.find((name, index) => names.indexOf(name) !== index) + if (twice) return setError(`${twice} is named twice.`) + for (const [index, row] of rows.entries()) { + const problem = secretValueProblem(row.value) + if (problem) return setError(rows.length > 1 ? `${names[index]}: ${problem}` : problem) + } + setBusy(true) + setError(null) + try { + await onSave({ + fields: rows.map((row, index) => ({ name: names[index]!, ...(row.label ? { label: row.label } : {}), value: row.value })), + expiry, + singleUse, + audience + }) + setRows((current) => current.map((row) => ({ ...row, value: '' }))) + } catch (failure) { + setError(errorMessage(failure) || 'That did not work. Try again.') + } finally { + setBusy(false) + } + } + + const named = rows.some((row) => row.label) + let focusTaken = false + return ( +
+
+

+

+
+
{ + event.preventDefault() + if (complete && !busy) void save() + }} + > + {rows.map((row) => { + const takeFocus = !focusTaken && (!row.name || !row.value) + if (takeFocus) focusTaken = true + const nameId = `${ids}-name-${row.key}` + return ( +
+ {named && row.label && } +
+ update(row.key, { name: event.target.value })} + onBlur={() => update(row.key, { name: cleanName(row.name) })} + aria-label="Name" + placeholder="NAME" + autoComplete="off" + autoCorrect="off" + autoCapitalize="characters" + spellCheck={false} + disabled={busy} + /> +
+ update(row.key, { value: event.target.value })} + aria-label={row.label || cleanName(row.name) || 'Secret'} + placeholder={valuePlaceholder(row)} + autoComplete="off" + autoCorrect="off" + autoCapitalize="off" + spellCheck={false} + data-private="true" + disabled={busy} + /> + {row.masked && ( + + )} +
+ {rows.length > 1 && ( + + )} +
+
+ ) + })} + {rows.length < SECFORM_MAX_FIELDS && ( + + )} +
+ + Expires + + variant="menu" + size="small" + ariaLabelledBy={`${ids}-expires`} + value={expiry} + onChange={setExpiry} + options={SECFORM_EXPIRIES.map((value) => ({ value, label: secformExpiryLabel(value) }))} + disabled={busy} + /> + + {audiences.length > 0 && ( + + Who can use it +