Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Swarm chat: remove credentials before they are stored, and tell the sender (#1687)

Dee66589b225cc3
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 49f709d42..dc2150483 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -2064,6 +2064,16 @@ describe('Super Tab chat attachments', () => {
attaching.execute(user, tab, { operationId, command: { type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [], attachmentIds } }, asAgentId)
const objectKey = (url: string) => url.slice('https://cdn.example.test/'.length)
+ it('keeps a credential out of a file\'s name, which the chat shows like the message', async () => {
+ const { tab } = await fixture()
+ const token = ['ghp', 'Fixture0Token1Not2Real3Value4abcdefgh'].join('_')
+ const { status, attachment } = await file(tab, `deploy-${token}.txt`, new Uint8Array([1, 2, 3]), 'text/plain')
+ expect(status).toBe(200)
+ expect(attachment.name).toBe('deploy-[credential removed].txt')
+ expect(attachment.url).not.toContain(token)
+ expect(JSON.stringify(await db.superTabAttachment.findMany({ where: { tabId: tab } }))).not.toContain(token)
+ })
+
it('streams one file into the bucket under a random key and answers its metadata', async () => {
const { tab } = await fixture()
const bytes = new Uint8Array(2 * 1024 * 1024).map((_, i) => i % 251)
@@ -2818,3 +2828,86 @@ describe('Lead mentions', () => {
expect(rows.at(-1)!.mentions).toEqual([])
})
})
+
+describe('credentials in Swarm chat', () => {
+ // Assembled at run time from obviously fake parts, never a credential-shaped literal.
+ const jwt = [{ alg: 'HS256', typ: 'JWT' }, { sub: 'fixture-user' }].map(part => Buffer.from(JSON.stringify(part)).toString('base64url'))
+ .concat('Fixture0Signature1Not2Real3Value4abcdefgh').join('.')
+ const github = ['ghp', 'Fixture0Token1Not2Real3Value4abcdefgh'].join('_')
+ const pasted = `My Harness login: ${jwt} and the deploy token ${github}. Can the Lead use them?`
+ const kept = `My Harness login: [credential removed] and the deploy token [credential removed]. Can the Lead use them?`
+ const notice = 'Removed 2 credentials (JWT, GitHub token) before saving. Revoke or rotate them.'
+ /** Everything stored for the tab, besides a terminal request (whose host must type exactly what was sent). */
+ const stored = async (tab: string) => JSON.stringify(await Promise.all([
+ db.superTab.findMany({ where: { id: tab } }), db.superTabMessage.findMany({ where: { tabId: tab } }),
+ db.superTabOperation.findMany({ where: { tabId: tab } }), db.superTabDelivery.findMany({ where: { tabId: tab } }),
+ db.superTabAttempt.findMany({ where: { tabId: tab } }), db.superTabRouteDecision.findMany({ where: { tabId: tab } }),
+ ]))
+ /** Every line the process writes while `body` runs: console and the raw streams the logger could reach. */
+ async function written(body: () => Promise<void>): Promise<string> {
+ const lines: string[] = []
+ const keep = (...args: unknown[]) => { lines.push(args.map(arg => typeof arg === 'string' ? arg : JSON.stringify(arg)).join(' ')) }
+ const spies = [...(['log', 'info', 'warn', 'error', 'debug'] as const).map(method => vi.spyOn(console, method).mockImplementation(keep)),
+ vi.spyOn(process.stdout, 'write').mockImplementation(chunk => { keep(String(chunk)); return true }),
+ vi.spyOn(process.stderr, 'write').mockImplementation(chunk => { keep(String(chunk)); return true })]
+ try { await body() } finally { for (const spy of spies) spy.mockRestore() }
+ return lines.join('\n')
+ }
+
+ it('stores and delivers a person\'s message without the credentials, tells the sender, logs neither, and replays the same receipt', async () => {
+ const { tab, lead } = await fixture()
+ const operationId = randomUUID()
+ const post = (text: string) => app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`,
+ headers: { authorization: `Bearer ${owner.sub}` }, payload: { operationId, command: message(text) } })
+ let answer: { revision: number; result: Record<string, unknown> } | undefined
+ const output = await written(async () => {
+ const first = await post(pasted)
+ expect(first.statusCode, first.body).toBe(200)
+ answer = first.json().data
+ expect(answer!.result).toEqual({ messageId: expect.any(String), credentialNotice: notice,
+ credentialsRemoved: [{ kind: 'jwt', label: 'JWT', count: 1 }, { kind: 'github', label: 'GitHub token', count: 1 }] })
+ // A retry of the same operation answers its receipt, notice included, and writes nothing more.
+ const before = (await store.messages(owner, tab, 'lead', {})).messages.length
+ const again = await post(pasted)
+ expect(again.statusCode, again.body).toBe(200)
+ expect(again.json().data).toEqual(answer)
+ expect((await store.messages(owner, tab, 'lead', {})).messages).toHaveLength(before)
+ // The receipt is still bound to what was sent: other words under the same operation are refused, as before.
+ const reused = await post('Something else entirely.')
+ expect([reused.statusCode, reused.json().error.code]).toEqual([409, 'OPERATION_REUSED'])
+ })
+ const row = (await store.messages(owner, tab, 'lead', { messageId: answer!.result.messageId as string })).messages[0]!
+ expect(row.text).toBe(kept)
+ const deliveries = await db.superTabDelivery.findMany({ where: { tabId: tab, messageId: row.id } })
+ expect(deliveries.map(d => d.agentId)).toEqual([lead])
+ const everything = await stored(tab)
+ for (const secret of [jwt, github]) {
+ expect(everything).not.toContain(secret)
+ expect(output).not.toContain(secret)
+ }
+ })
+
+ it('treats an agent\'s post the same, and a native terminal transcript too', async () => {
+ const { tab, lead } = await fixture()
+ const posted = await run(tab, message(`gh auth status printed ${github}`), host, lead)
+ expect(posted.result.credentialNotice).toBe('Removed a credential (GitHub token) before saving. Revoke or rotate it.')
+ expect((await store.messages(owner, tab, 'lead', { messageId: posted.result.messageId as string })).messages[0]!.text)
+ .toBe('gh auth status printed [credential removed]')
+ const group = (await run(tab, { type: 'conversation.create', title: 'Release', brief: 'Ship it',
+ checks: [{ description: 'Shipped', independent: false }] })).result.conversationId as string
+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(),
+ name: 'Release Engineer', configuration: config, lead: false })).result.agentId as string
+ const { contextId } = await store.native.open(owner, tab, { operationId: randomUUID(), conversationId: group, agentId: worker })
+ const prompt = { turnId: 'pasted_turn', kind: 'prompt' as const, previousEventId: null, text: `use this: ${jwt}`, truncated: false, interrupted: false }
+ const output = await written(async () => {
+ const recorded = await store.native.append(host, tab, contextId, prompt) as { eventId: string }
+ expect((await db.superTabMessage.findUniqueOrThrow({ where: { id: recorded.eventId } })).text).toBe('use this: [credential removed]')
+ expect(await store.native.append(host, tab, contextId, prompt)).toEqual(recorded)
+ })
+ const everything = await stored(tab)
+ for (const secret of [jwt, github]) {
+ expect(everything).not.toContain(secret)
+ expect(output).not.toContain(secret)
+ }
+ })
+})
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index de1854d53..67e69d42e 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
-import { applyCommand, commandSchema, PAIR_CHAIN_LIMIT, type Command, type CommandContext } from './commands.js'
+import { applyCommand, commandSchema, PAIR_CHAIN_LIMIT, withoutCredentials, type Command, type CommandContext } from './commands.js'
+import { CREDENTIAL_MARKER, type CredentialKind } from './credentials.js'
import { hostLocalGrid, machineSlots, removalPreview, swarmGridRow } from './machines.js'
import { activeWork, agentRole, createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'
import type { RouteDecision } from './routeRecord.js'
@@ -2174,3 +2175,88 @@ describe('Lead mentions', () => {
expect(() => f.run(done, as(lead), { mention })).toThrow('This mention is unavailable.')
})
})
+
+describe('credentials in Swarm chat', () => {
+ // Assembled at run time from obviously fake parts, never a credential-shaped literal.
+ const jwt = [{ alg: 'HS256', typ: 'JWT' }, { sub: 'fixture-user' }].map(part => Buffer.from(JSON.stringify(part)).toString('base64url'))
+ .concat('Fixture0Signature1Not2Real3Value4abcdefgh').join('.')
+ const github = ['ghp', 'Fixture0Token1Not2Real3Value4abcdefgh'].join('_')
+ const notice = 'Removed 2 credentials (JWT, GitHub token) before saving. Revoke or rotate them.'
+ const pasted = `Here is my login: ${jwt}\nand the deploy token ${github} for the release.`
+ const kept = `Here is my login: ${CREDENTIAL_MARKER}\nand the deploy token ${CREDENTIAL_MARKER} for the release.`
+ const send = (text: string, conversationId = 'lead'): Command => ({ type: 'message.send', conversationId, text, replyTo: null, recipientIds: [] })
+
+ it('stores a person\'s message without the credentials, keeps the rest and tells the sender what went', () => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true)
+ const input = send(pasted)
+ const sent = f.run(input)
+ expect(sent.messages).toEqual([expect.objectContaining({ text: kept, recipients: [lead] })])
+ expect(sent.result).toEqual({ messageId: sent.messages[0]!.id, credentialNotice: notice,
+ credentialsRemoved: [{ kind: 'jwt', label: 'JWT', count: 1 }, { kind: 'github', label: 'GitHub token', count: 1 }] })
+ expect(JSON.stringify([sent.messages, f.state])).not.toContain(github)
+ expect(JSON.stringify([sent.messages, f.state])).not.toContain(jwt)
+ // The caller's command is left as it was; only what is stored changes.
+ expect(input).toEqual(send(pasted))
+ })
+
+ it('treats an agent\'s post the same: agents echo credentials from their terminals', () => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group(), worker = f.add('worker', 'owner', group)
+ f.run({ type: 'conversation.agent', conversationId: group, agentId: lead, present: true, lead: true })
+ f.run({ type: 'work.assign', conversationId: group, agentId: worker })
+ const posted = f.run(send(`npm publish failed: //registry.npmjs.org/:_authToken=${github}`, group), { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' })
+ expect(posted.messages).toEqual([expect.objectContaining({ text: `npm publish failed: //registry.npmjs.org/:_authToken=${CREDENTIAL_MARKER}`, recipients: [lead] })])
+ expect(posted.result.credentialNotice).toBe('Removed a credential (GitHub token) before saving. Revoke or rotate it.')
+ })
+
+ it('leaves a message without credentials, and its result, exactly as before', () => {
+ const f = fixture()
+ const text = 'Merged a3f1c9e27b5d4f80916e2c3b7a8d9e0f1a2b3c4d; id 123e4567-e89b-12d3-a456-426614174000, see https://github.com/example/project/pull/1680'
+ const sent = f.run(send(text))
+ expect(sent.messages[0]!.text).toBe(text)
+ expect(sent.result).toEqual({ messageId: sent.messages[0]!.id })
+ })
+
+ it('removes credentials from task words, results, evidence and reports before they reach the state or a row', () => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true)
+ const created = f.run({ type: 'conversation.create', title: 'Deploy', checks: [{ description: `Login works with ${github}`, independent: false }],
+ task: { goal: 'Deploy', changes: `Use ${jwt} to call the API`, constraints: 'None', owns: ['backend'] } })
+ expect(created.result.credentialNotice).toBe(notice)
+ const group = f.state.conversations.find(c => c.id === created.result.conversationId)!
+ expect(group.task!.changes).toBe(`Use ${CREDENTIAL_MARKER} to call the API`)
+ expect(group.brief).toContain(`Use ${CREDENTIAL_MARKER} to call the API`)
+ expect(group.checks[0]!.description).toBe(`Login works with ${CREDENTIAL_MARKER}`)
+ const worker = f.add('worker', 'owner', group.id)
+ const assignmentId = f.run({ type: 'work.assign', conversationId: group.id, agentId: worker }).result.assignmentId as string
+ const as: Actor = { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' }
+ const blocked = f.run({ type: 'work.status', conversationId: group.id, assignmentId, status: 'blocked', result: `Rejected ${github}` }, as)
+ expect(blocked.messages[0]!.text).toBe(`Stuck\n\nRejected ${CREDENTIAL_MARKER}`)
+ f.run({ type: 'work.check', conversationId: group.id, assignmentId, checkId: group.checks[0]!.id, passed: true, evidence: `Signed in as ${jwt}` },
+ { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' })
+ const stored = f.state.conversations.find(c => c.id === group.id)!
+ expect([stored.assignment!.result, stored.checks[0]!.evidence]).toEqual([`Rejected ${CREDENTIAL_MARKER}`, `Signed in as ${CREDENTIAL_MARKER}`])
+ expect(JSON.stringify(f.state)).not.toMatch(new RegExp(`${github}|${jwt.replaceAll('.', '\\.')}`))
+ })
+
+ it('removes a credential from an older message when a person resends it', () => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true)
+ const resent = f.run({ type: 'delivery.resolve', deliveryId: 'd', resolution: 'resend' }, owner,
+ { delivery: { id: 'd', conversationId: 'lead', agentId: lead, messageId: 'm', text: pasted } })
+ expect(resent.messages[0]).toMatchObject({ text: kept, recipients: [lead] })
+ expect(resent.result.credentialNotice).toBe(notice)
+ })
+
+ it('finds the words of every kind of command, nested and in lists', () => {
+ const removed: CredentialKind[] = []
+ const start = withoutCredentials({ type: 'agent.start', overrideReason: `faster with ${github}`, request: { name: `Builder ${github}` } } as Command, removed)
+ expect(start).toMatchObject({ overrideReason: `faster with ${CREDENTIAL_MARKER}`, request: { name: `Builder ${CREDENTIAL_MARKER}` } })
+ const route = withoutCredentials({ type: 'route.record', conversationId: 'lead', decision: { assessment: { why: `needs ${jwt}` }, why: 'ok',
+ excluded: [{ title: 'Mini', reason: `asked for ${github}` }], candidates: [{ title: 'New agent', label: 'plain' }] } } as unknown as Command, removed)
+ expect(route).toMatchObject({ decision: { assessment: { why: `needs ${CREDENTIAL_MARKER}` }, excluded: [{ reason: `asked for ${CREDENTIAL_MARKER}` }] } })
+ const owns = withoutCredentials({ type: 'work.define', conversationId: 'g', checks: [], task: { goal: 'g', changes: 'c', constraints: 'n', owns: ['src', github] } } as unknown as Command, removed)
+ expect(owns).toMatchObject({ task: { owns: ['src', CREDENTIAL_MARKER] } })
+ expect(removed).toEqual(['github', 'github', 'jwt', 'github', 'github'])
+ // Commands with no words of their own are passed through untouched.
+ const pause: Command = { type: 'tab.pause', paused: true }
+ expect(withoutCredentials(pause, removed)).toBe(pause)
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 3a9cf529b..1a6f840a2 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -13,6 +13,7 @@ import { agentTarget, askedInSchema, broken, MAX_RULES, RULE_MESSAGE_MS, ruleSch
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
import { checkMentions, MAX_MENTIONS, type MentionTarget } from './mentions.js'
import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, type TerminalRequest } from './terminal.js'
+import { credentialResult, redactCredentials, type CredentialKind } from './credentials.js'
import { agentKind, agentProjectId, agentSetRole, deleteProject, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
@@ -139,6 +140,57 @@ export const commandSchema = z.discriminatedUnion('type', [
export type Command = z.infer<typeof commandSchema>
export const operationSchema = z.object({ operationId: id, command: commandSchema }).strict()
+/** The words in each command that people and agents read in the Swarm: messages, briefs and tasks, results, evidence,
+ * reasons, errors and names. `[]` is each item of a list. Not `agent.input`: its host types the exact text, and only its
+ * chat row is redacted (terminal.ts). Not a role's skill text, which only its project's owner, Lead and hosts read. */
+const WORDS: Partial<Record<Command['type'], readonly string[]>> = {
+ 'message.send': ['text'],
+ 'agent.add': ['name', 'initialMessage'],
+ 'agent.start': ['request.name', 'overrideReason'],
+ 'agent.startFailed': ['error'],
+ 'agent.startSettled': ['warning'],
+ 'conversation.create': ['title', 'brief', 'task.goal', 'task.changes', 'task.constraints', 'task.owns[]', 'checks[].description'],
+ 'conversation.rename': ['title'],
+ 'work.define': ['brief', 'task.goal', 'task.changes', 'task.constraints', 'task.owns[]', 'checks[].description'],
+ 'work.assign': ['overrideReason'],
+ 'work.status': ['result'],
+ 'work.cancel': ['reason'],
+ 'work.check': ['evidence'],
+ 'project.create': ['name', 'brief'],
+ 'project.rename': ['name'],
+ 'project.report': ['text'],
+ 'rule.set': ['text'],
+ 'route.record': ['decision.assessment.why', 'decision.why', 'decision.excluded[].title', 'decision.excluded[].reason',
+ 'decision.candidates[].title', 'decision.candidates[].label'],
+ 'route.override': ['reason'],
+ 'tab.rename': ['name'],
+ 'machine.contribute': ['name'],
+ 'localModels.status': ['error'],
+}
+
+/** The command with every credential in its words replaced (credentials.ts), adding what went to `removed`. */
+export function withoutCredentials(command: Command, removed: CredentialKind[]): Command {
+ const paths = WORDS[command.type]
+ if (!paths) return command
+ const copy = structuredClone(command)
+ const visit = (holder: Record<string, unknown>, [head, ...rest]: string[]) => {
+ const many = head!.endsWith('[]'), key = many ? head!.slice(0, -2) : head!
+ const redact = (value: unknown, put: (text: string) => void) => {
+ if (rest.length) {
+ if (value && typeof value === 'object') visit(value as Record<string, unknown>, rest)
+ } else if (typeof value === 'string') {
+ const clean = redactCredentials(value)
+ if (clean.removed.length) { put(clean.text); removed.push(...clean.removed) }
+ }
+ }
+ const value = holder[key]
+ if (many && Array.isArray(value)) value.forEach((item, i) => redact(item, text => { value[i] = text }))
+ else if (!many) redact(value, text => { holder[key] = text })
+ }
+ for (const path of paths) visit(copy as Record<string, unknown>, path.split('.'))
+ return copy
+}
+
export interface CommandContext {
operationId: string
now: number
@@ -317,7 +369,10 @@ function open(state: SuperTabState, conversationId: string) {
/** Pure policy/state transition. The store commits its state, messages and delivery records in one transaction. */
export function applyCommand(original: SuperTabState, actor: Actor, input: Command, context: CommandContext): CommandEffects {
- const command = commandSchema.parse(input)
+ // A credential someone pasted, or an agent echoed from its terminal, is gone before anything is stored or delivered
+ // (Oct 2026: a Harness access token in a shared Lead chat). The sender's result says what went.
+ const removed: CredentialKind[] = []
+ const command = withoutCredentials(commandSchema.parse(input), removed)
const state = structuredClone(original)
syncLeads(state)
numberConversations(state)
@@ -551,10 +606,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
switch (command.type) {
case 'agent.screen':
case 'agent.input': {
- const { effect, message } = terminalRequest(state, actor, sender, operationId, context.now, command)
+ const { effect, message, removed: typed } = terminalRequest(state, actor, sender, operationId, context.now, command)
effects.terminal = effect
result.requestId = operationId
if (message) effects.messages.push(message)
+ removed.push(...typed)
break
}
case 'agent.screenResult':
@@ -1439,6 +1495,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// MongoDB limits a document to 16 MiB. Leave room for indexes and metadata, and refuse before losing state.
assignAgentDisplayNames(state.agents)
if (Buffer.byteLength(JSON.stringify(state)) > 8 * 1024 * 1024) fail('TAB_TOO_LARGE', 'This Super Tab has reached its metadata limit.', 413)
+ // Every row this command writes, whatever its words came from: an older message resent, a rule written before this check.
+ for (const draft of effects.messages) {
+ const clean = redactCredentials(draft.text)
+ if (clean.removed.length) { draft.text = clean.text; removed.push(...clean.removed) }
+ }
+ if (removed.length) Object.assign(result, credentialResult(removed))
return effects
}
diff --git a/backend/src/superTabs/credentials.test.ts b/backend/src/superTabs/credentials.test.ts
new file mode 100644
index 000000000..e9d3b9eea
--- /dev/null
+++ b/backend/src/superTabs/credentials.test.ts
@@ -0,0 +1,238 @@
+import { describe, expect, it } from 'vitest'
+import { CREDENTIAL_LABELS, CREDENTIAL_MARKER, credentialResult, findCredentials, redactCredentials, type CredentialKind } from './credentials.js'
+
+// Every credential below is assembled at run time from obviously fake parts, so the repository holds nothing a secret
+// scanner (or a person) could mistake for a real one.
+const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
+const UPPER32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
+const B64 = `${ALNUM}+/`
+const B64URL = `${ALNUM}-_`
+/** Deterministic noise with letters and digits. */
+function noise(length: number, alphabet = ALNUM, seed = 7): string {
+ let out = '', x = seed
+ for (let i = 0; i < length; i++) {
+ x = (Math.imul(x, 1103515245) + 12345) >>> 0
+ out += alphabet[(x >>> 16) % alphabet.length]
+ }
+ return /\d/.test(out) || !/\d/.test(alphabet) ? out : `${out.slice(0, -1)}7`
+}
+const b64url = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url')
+const fake = {
+ jwt: (seed = 1) => [b64url({ alg: 'HS256', typ: 'JWT' }), b64url({ sub: 'fixture-user', exp: 1 }), noise(43, B64URL, seed)].join('.'),
+ jwe: () => [b64url({ alg: 'RSA-OAEP', enc: 'A256GCM' }), noise(40, B64URL, 2), noise(16, B64URL, 3), noise(30, B64URL, 4), noise(22, B64URL, 5)].join('.'),
+ harness: (prefix: string, seed = 11) => `${prefix}_${noise(43, B64URL, seed)}`,
+ github: (prefix: string, seed = 12) => `${prefix}_${noise(36, ALNUM, seed)}`,
+ githubPat: () => ['github', 'pat', `${noise(22, ALNUM, 13)}_${noise(59, ALNUM, 14)}`].join('_'),
+ anthropic: () => ['sk', 'ant', 'api03', noise(93, B64URL, 15)].join('-'),
+ openai: (kind = '') => ['sk', ...(kind ? [kind] : []), noise(48, ALNUM, 16)].join('-'),
+ awsKeyId: (prefix = 'AKIA') => prefix + noise(16, UPPER32, 17),
+ awsSecret: () => noise(40, B64, 18),
+ slack: (kind = 'b') => [`xox${kind}`, '1234567890', '9876543210', noise(24, ALNUM, 19)].join('-'),
+ google: () => ['AI', 'za', noise(35, B64URL, 20)].join(''),
+ pem: (kind = 'RSA PRIVATE') => [`-----BEGIN ${kind} KEY-----`, noise(64, B64, 21), noise(64, B64, 22), `${noise(20, B64, 23)}==`, `-----END ${kind} KEY-----`].join('\n'),
+ password: () => `Fx${noise(16, ALNUM, 24)}`,
+}
+
+describe('findCredentials: every kind it removes', () => {
+ const cases: Array<[CredentialKind, string, string]> = [
+ ['jwt', 'a signed JWT', fake.jwt()],
+ ['jwt', 'an encrypted JWT (five segments)', fake.jwe()],
+ ['harness', 'a Harness access token', fake.harness('hna')],
+ ['harness', 'a Harness refresh token', fake.harness('hnr')],
+ ['harness', 'a Harness handoff code', fake.harness('hnh')],
+ ['harness', 'a Harness sign-in QR code', fake.harness('hnq')],
+ ['harness', 'a Harness QR poll token', fake.harness('hnp')],
+ ['github', 'a GitHub personal access token', fake.github('ghp')],
+ ['github', 'a GitHub OAuth token', fake.github('gho')],
+ ['github', 'a GitHub user-to-server token', fake.github('ghu')],
+ ['github', 'a GitHub server-to-server token', fake.github('ghs')],
+ ['github', 'a GitHub refresh token', fake.github('ghr')],
+ ['github', 'a fine-grained GitHub token', fake.githubPat()],
+ ['anthropic', 'an Anthropic key', fake.anthropic()],
+ ['openai', 'a legacy OpenAI key', fake.openai()],
+ ['openai', 'an OpenAI project key', fake.openai('proj')],
+ ['openai', 'an OpenAI service account key', fake.openai('svcacct')],
+ ['aws-key-id', 'an AWS access key id', fake.awsKeyId()],
+ ['aws-key-id', 'an AWS temporary access key id', fake.awsKeyId('ASIA')],
+ ['slack', 'a Slack bot token', fake.slack('b')],
+ ['slack', 'a Slack user token', fake.slack('p')],
+ ['slack', 'a Slack app token', fake.slack('a')],
+ ['google', 'a Google API key', fake.google()],
+ ['private-key', 'a PEM RSA private key', fake.pem()],
+ ['private-key', 'a PKCS#8 private key', fake.pem('PRIVATE')],
+ ['private-key', 'an OpenSSH private key', fake.pem('OPENSSH PRIVATE')],
+ ['private-key', 'an encrypted private key', fake.pem('ENCRYPTED PRIVATE')],
+ ['private-key', 'an EC private key', fake.pem('EC PRIVATE')],
+ ]
+ for (const [kind, what, secret] of cases) {
+ it(`removes ${what} and keeps the words around it`, () => {
+ const text = `Here it is: ${secret}\nThanks, I will rotate it later.`
+ expect(findCredentials(text).map(f => f.kind)).toEqual([kind])
+ expect(redactCredentials(text)).toEqual({ text: `Here it is: ${CREDENTIAL_MARKER}\nThanks, I will rotate it later.`, removed: [kind] })
+ // On its own, in quotes, in parentheses, after an equals sign, at the end of a sentence.
+ for (const [before, after] of [['', ''], ['"', '"'], ["'", "'"], ['(', ')'], ['TOKEN=', ''], ['`', '`'], ['see ', '.'], ['<', '>']]) {
+ expect(redactCredentials(`${before}${secret}${after}`).text).toBe(`${before}${CREDENTIAL_MARKER}${after}`)
+ }
+ })
+ }
+
+ it('removes an AWS secret access key when it is labelled, keeping the label', () => {
+ const secret = fake.awsSecret()
+ for (const label of ['aws_secret_access_key = ', 'AWS_SECRET_ACCESS_KEY=', '"SecretAccessKey": "', 'aws secret key: ', 'secret_access_key: ']) {
+ expect(redactCredentials(`${label}${secret}`)).toEqual({ text: `${label}${CREDENTIAL_MARKER}`, removed: ['aws-secret'] })
+ }
+ // Unlabelled, 40 base64 characters are as likely a hash: left alone.
+ expect(findCredentials(`checksum ${secret}`)).toEqual([])
+ })
+
+ it('removes a long random value given as a password, token or secret, keeping the key', () => {
+ const value = fake.password()
+ for (const assignment of [`password=${value}`, `DB_PASSWORD="${value}"`, `"token": "${value}"`, `token: ${value}`, `secret=${value}`,
+ `client_secret: '${value}'`, `x-api-key: ${value}`, `apiKey => ${value}`, `access_token=${value}&state=abc`, `--token=${value}`,
+ `export SESSION_SECRET=${value}`, `credentials := ${value}`, `PASSPHRASE=${value}`, `private_key: ${value}`]) {
+ const { text, removed } = redactCredentials(assignment)
+ expect(removed, assignment).toEqual(['password'])
+ expect(text, assignment).toBe(assignment.replace(value, CREDENTIAL_MARKER))
+ }
+ expect(redactCredentials(`The password: ${value}.`).text).toBe(`The password: ${CREDENTIAL_MARKER}.`)
+ })
+
+ it('removes Authorization header values, a bare bearer token and a password in a URL', () => {
+ const value = fake.password()
+ const basic = Buffer.from(`fixture-user:${value}`).toString('base64')
+ expect(redactCredentials(`curl -H "Authorization: Bearer ${value}" https://api.example.test`).text)
+ .toBe(`curl -H "Authorization: Bearer ${CREDENTIAL_MARKER}" https://api.example.test`)
+ expect(redactCredentials(`authorization: Basic ${basic}`).text).toBe(`authorization: Basic ${CREDENTIAL_MARKER}`)
+ expect(redactCredentials(`send it with Bearer ${value}${noise(6, ALNUM, 30)} please`).text).toBe(`send it with Bearer ${CREDENTIAL_MARKER} please`)
+ expect(redactCredentials(`DATABASE_URL=postgres://app:${value}@db.internal:5432/app`).text)
+ .toBe(`DATABASE_URL=postgres://app:${CREDENTIAL_MARKER}@db.internal:5432/app`)
+ })
+
+ it('names a known credential by its own kind when it is also labelled', () => {
+ expect(redactCredentials(`GITHUB_TOKEN=${fake.github('ghp')}`)).toEqual({ text: `GITHUB_TOKEN=${CREDENTIAL_MARKER}`, removed: ['github'] })
+ expect(redactCredentials(`Authorization: Bearer ${fake.jwt()}`)).toEqual({ text: `Authorization: Bearer ${CREDENTIAL_MARKER}`, removed: ['jwt'] })
+ expect(redactCredentials(`git clone https://x-access-token:${fake.github('ghs')}@github.com/example/repo`).removed).toEqual(['github'])
+ expect(redactCredentials(`aws_access_key_id = ${fake.awsKeyId()}`).removed).toEqual(['aws-key-id'])
+ })
+
+ it('removes several credentials of several kinds from one message, in order', () => {
+ const text = `JWT ${fake.jwt()} and ${fake.github('ghp')}, then ${fake.jwt(2)}; keys:\n${fake.pem()}\nend`
+ const { text: redacted, removed } = redactCredentials(text)
+ expect(removed).toEqual(['jwt', 'github', 'jwt', 'private-key'])
+ expect(redacted).toBe(`JWT ${CREDENTIAL_MARKER} and ${CREDENTIAL_MARKER}, then ${CREDENTIAL_MARKER}; keys:\n${CREDENTIAL_MARKER}\nend`)
+ })
+
+ it('keeps a full stop after a JWT and removes the whole of a cut-off private key', () => {
+ expect(redactCredentials(`Token: ${fake.jwt()}. Is it valid?`).text).toBe(`Token: ${CREDENTIAL_MARKER}. Is it valid?`)
+ const cut = fake.pem().split('\n').slice(0, 3).join('\n')
+ expect(redactCredentials(`${cut}\n\nIt stops there, sorry.`).text).toBe(`${CREDENTIAL_MARKER}\n\nIt stops there, sorry.`)
+ // As a JSON string (a service account file): escaped newlines, with and without its END line.
+ const json = fake.pem('PRIVATE').replaceAll('\n', '\\n')
+ expect(redactCredentials(`{"private_key": "${json}\\n", "client_email": "[email protected]"}`).text)
+ .toBe(`{"private_key": "${CREDENTIAL_MARKER}\\n", "client_email": "[email protected]"}`)
+ const cutJson = json.slice(0, json.indexOf('-----END'))
+ expect(redactCredentials(`{"private_key": "${cutJson}", "x": 1}`).text).toBe(`{"private_key": "${CREDENTIAL_MARKER}", "x": 1}`)
+ })
+
+ it('is stable: redacting redacted text removes nothing more', () => {
+ const once = redactCredentials(`a ${fake.jwt()} b password=${fake.password()} c ${fake.pem()}`).text
+ expect(redactCredentials(once)).toEqual({ text: once, removed: [] })
+ })
+})
+
+describe('findCredentials: what it leaves alone', () => {
+ const sha = 'a3f1c9e27b5d4f80916e2c3b7a8d9e0f1a2b3c4d'
+ const sha256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
+ const image = `data:image/png;base64,${noise(24_000, B64, 40)}==`
+ const corpus = [
+ // Commit ids, hashes and identifiers
+ sha, `Merged ${sha.slice(0, 7)} into main.`, `commit ${sha}\nAuthor: Fixture <[email protected]>`,
+ `git cherry-pick ${sha} ${sha.slice(0, 12)}`, `sha256:${sha256}`, `"sha256": "${sha256}"`, `integrity: sha512-${noise(86, B64, 41)}==`,
+ `docker pull ghcr.io/example/app@sha256:${sha256}`, '123e4567-e89b-12d3-a456-426614174000', 'request 0b5f9d38-3c1e-4c55-9f1a-1d2e3f4a5b6c failed',
+ 'ObjectId("64f1a2b3c4d5e6f708192a3b")', '01HF8XKQ4N3T6M9V2B7C5D0E1F', 'stableId swarm-session-7f3a9b2c4d5e6f70', 'sha1-8f14e45fceea167a5a36dedd4bea2543',
+ `md5 d41d8cd98f00b204e9800998ecf8427e`, `etag: "W/\\"5f3a9b2c4d5e6f708192a3b4c5d6e7f8\\""`, 'Version 1.4.37 (build 20261024.3)', 'v2.0.0-rc.1+sha.5114f85',
+ // URLs, with hashes and ids
+ `https://github.com/example/project/commit/${sha}`, `https://github.com/example/project/blob/${sha}/backend/src/app.ts#L10-L24`,
+ 'https://github.com/example/project/pull/1680#discussion_r1789234561', 'https://cdn.example.test/assets/main.4f9a8b7c6d5e.js?v=3f9a8b7c6d5e4f3a',
+ `https://example.test/download?ref=${sha}&page=2`, 'https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=42s',
+ 'https://drive.google.com/file/d/1aBcD3eFgH4iJkL5mNoP6qRsT7uVwX8yZ/view?usp=sharing', 'https://example.test/a/b#section-3.2.1',
+ 'https://[email protected]/repo.git', '[email protected]:example/project.git', 'ssh://[email protected]:22/example/project.git',
+ 'postgres://postgres:postgres@localhost:5432/dev', 'https://hooks.example.test/T000/B000/abc',
+ // Base64 data and public keys
+ image, `![screenshot](${image})`, noise(4096, B64, 42), noise(4096, B64URL, 43),
+ `ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI${noise(43, B64, 44)} [email protected]`, `ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ${noise(300, B64, 45)} me@host`,
+ ['-----BEGIN PUBLIC KEY-----', noise(64, B64, 46), '-----END PUBLIC KEY-----'].join('\n'),
+ ['-----BEGIN CERTIFICATE-----', noise(64, B64, 47), '-----END CERTIFICATE-----'].join('\n'),
+ 'A PEM file starts with -----BEGIN PRIVATE KEY----- and ends with -----END PRIVATE KEY-----.',
+ '-----BEGIN RSA PRIVATE KEY-----\n<paste your key here>\n-----END RSA PRIVATE KEY-----',
+ // Long words, dotted names, emails, paths
+ 'Pneumonoultramicroscopicsilicovolcanoconiosis', 'Supercalifragilisticexpialidocious', 'Donaudampfschifffahrtsgesellschaftskapitän',
+ 'antidisestablishmentarianism and floccinaucinihilipilification', 'www.example.com', 'api.github.com', 'os.path.join(base, name)', 'a.b.c',
+ 'the.quick.brown.fox.jumps', 'config.secrets.production.apiKey', '[email protected]', '/home/dev/code/project/backend/src/app.ts',
+ 'C:\\dev\\AppData\\Local\\Harness', '~/.ssh/id_ed25519', 'aGVsbG8gd29ybGQ.d29ybGQgaGVsbG8.Zm9vYmFy', 'eyJub3QiOiJqc29u.x.y',
+ // Code that names a secret without holding one
+ 'const token = process.env.GITHUB_TOKEN', 'const token = await getToken(); headers.Authorization = `Bearer ${token}`',
+ 'password: z.string().min(12)', 'api_key = os.environ["OPENAI_API_KEY"]', 'export GITHUB_TOKEN=$(gh auth token)',
+ 'let secret = std::env::var("SECRET").unwrap();', 'let token = uuid::Uuid::new_v4().to_string();', 'if (password === confirmPassword) return',
+ 'curl -H "Authorization: Bearer $TOKEN" https://api.github.com/user', 'token: ${{ secrets.GITHUB_TOKEN }}', 'private_key_path: ~/.ssh/id_ed25519',
+ 'access_key: process.env.AWS_ACCESS_KEY_ID', 'max_tokens: 4096', 'max_tokens=128000', 'tokenizer: cl100k_base', '"secret_name": "prod/db/password"',
+ 'password_hash: $2b$12$abcdefghijklmnopqrstuv', 'secret = SECRET_KEY_V2', 'token: Token | null', 'apiKey: config.apiKey,',
+ 'refresh_token_expires_in: 15552000', 'publicKeyToken="6595b64144ccf1df"', 'jwt.sign(payload, secret, { expiresIn: "1h" })',
+ 'def get_secret(name: str) -> str:\n return vault.read(name)', 'SELECT id, password_reset_at FROM users WHERE token_id = $1',
+ 'for (const token of tokens) count += token.length', '<input type="password" name="password" autocomplete="current-password">',
+ // Placeholders and redacted values
+ 'ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'sk-...', 'sk-your-key-here', 'sk-learn and scikit-learn', 'AKIAXXXXXXXXXXXXXXXX',
+ 'xoxb-your-token-here', 'password=changeme', 'password: ********', 'token: <redacted>', 'secret=${SECRET}', 'API_KEY=<your key>',
+ 'password=test-password-123', 'token: e2e-token-agent-client', 'apiKey: gridkey-abc123', `token: ${CREDENTIAL_MARKER}`, 'hna_short',
+ 'Bearer tokens expire after an hour.', 'Basic authentication is disabled.', 'Authorization: Bearer test-access-token',
+ // Prose, in English and Vietnamese
+ 'Please review PR #1680 before the release; the Lead will merge it once CI is green.',
+ 'The token budget for this task is 200k; keep the secret sauce simple.',
+ 'Xin chào, mật khẩu của bạn đã được đổi thành công. Vui lòng đăng nhập lại.',
+ 'Mã xác thực đã hết hạn; hãy yêu cầu mã mới và đừng chia sẻ nó với ai.',
+ 'Nhóm sẽ triển khai bản cập nhật vào thứ Hai, sau khi kiểm thử xong trên máy Mac mini.',
+ 'Tôi đã đẩy nhánh feat/swarm-chat-secrets lên và mở bản nháp PR, nhờ anh xem giúp.',
+ 'Hôm nay là ngày 24/10/2026; cuộc họp lúc 9:30 sáng ở phòng 302.',
+ '| Kind | Count |\n|---|---|\n| JWT | 0 |\n| GitHub | 0 |', '2026-10-24T09:30:00.000Z', '+84 000 000 000',
+ 'Error: ENOENT: no such file or directory, open \'/tmp/harness/config.json\'\n at Object.openSync (node:fs:573:3)',
+ ]
+
+ it(`finds nothing in ${corpus.length} ordinary texts`, () => {
+ for (const text of corpus) expect(findCredentials(text), text.slice(0, 120)).toEqual([])
+ expect(findCredentials(corpus.join('\n'))).toEqual([])
+ expect(redactCredentials(corpus.join(' ')).removed).toEqual([])
+ })
+
+ it('finds nothing hidden by chance in a large base64 image, even with a key-shaped run inside it', () => {
+ const inside = `data:image/png;base64,${noise(1000, B64, 48)}${fake.google()}${noise(1000, B64, 49)}${fake.awsKeyId()}${noise(1000, B64, 50)}`
+ expect(findCredentials(inside)).toEqual([])
+ // A real credential next to the image still goes.
+ expect(redactCredentials(`${image} ${fake.github('ghp')}`).text).toBe(`${image} ${CREDENTIAL_MARKER}`)
+ })
+
+ it('reads a message at the size limit quickly, whatever it holds', () => {
+ for (const text of [noise(32_000, B64URL, 51), 'a'.repeat(32_000), `${'x.'.repeat(16_000)}`, `password=${'A1'.repeat(16_000)}`,
+ `${'-----BEGIN PRIVATE KEY-----'.repeat(1000)}`, `https://${'a'.repeat(31_000)}:`]) {
+ const started = performance.now()
+ findCredentials(text)
+ expect(performance.now() - started).toBeLessThan(500)
+ }
+ })
+})
+
+describe('credentialResult', () => {
+ it('tells the sender what kind of credential went and to revoke or rotate it', () => {
+ expect(credentialResult(['github'])).toEqual({
+ credentialsRemoved: [{ kind: 'github', label: 'GitHub token', count: 1 }],
+ credentialNotice: 'Removed a credential (GitHub token) before saving. Revoke or rotate it.',
+ })
+ expect(credentialResult(['jwt', 'github', 'jwt'])).toEqual({
+ credentialsRemoved: [{ kind: 'jwt', label: 'JWT', count: 2 }, { kind: 'github', label: 'GitHub token', count: 1 }],
+ credentialNotice: 'Removed 3 credentials (JWT, GitHub token) before saving. Revoke or rotate them.',
+ })
+ })
+
+ it('has a plain label for every kind', () => {
+ for (const label of Object.values(CREDENTIAL_LABELS)) expect(label).toMatch(/^[A-Za-z][A-Za-z -]+$/)
+ })
+})
diff --git a/backend/src/superTabs/credentials.ts b/backend/src/superTabs/credentials.ts
new file mode 100644
index 000000000..096c43116
--- /dev/null
+++ b/backend/src/superTabs/credentials.ts
@@ -0,0 +1,186 @@
+import {
+ HARNESS_ACCESS_PREFIX, HARNESS_HANDOFF_PREFIX, HARNESS_QR_POLL_PREFIX, HARNESS_QR_PREFIX, HARNESS_REFRESH_PREFIX,
+} from '../lib/harnessTokenFormat.js'
+
+/**
+ * Credentials pasted into Swarm chat. In the live Swarm of 21–23 Oct 2026 someone pasted their Harness login access token
+ * (a JWT) into a shared Lead chat, where every member and agent could read it. Everything a person or an agent posts passes
+ * through here before it is stored: each credential becomes CREDENTIAL_MARKER and the rest of the text stays.
+ *
+ * Conservative on purpose. A known format must also look random; a generic `password=`, `token:` or `secret=` value must
+ * be long, mix letters and digits, and look random. Commit ids, UUIDs, hashes in URLs, base64 images, code that names a
+ * secret without holding one, and ordinary prose in any language pass unchanged.
+ */
+export type CredentialKind = 'private-key' | 'jwt' | 'harness' | 'github' | 'anthropic' | 'openai' | 'aws-key-id' | 'aws-secret'
+ | 'slack' | 'google' | 'password'
+
+/** What the sender is told was removed. */
+export const CREDENTIAL_LABELS: Record<CredentialKind, string> = {
+ 'private-key': 'private key',
+ jwt: 'JWT',
+ harness: 'Harness sign-in token',
+ github: 'GitHub token',
+ anthropic: 'Anthropic API key',
+ openai: 'OpenAI API key',
+ 'aws-key-id': 'AWS access key ID',
+ 'aws-secret': 'AWS secret access key',
+ slack: 'Slack token',
+ google: 'Google API key',
+ password: 'password or secret',
+}
+
+export const CREDENTIAL_MARKER = '[credential removed]'
+
+export interface FoundCredential { kind: CredentialKind; start: number; end: number }
+
+/** Shannon entropy in bits per character: a placeholder (`xxxx`, `****`) is near 0, a random key above 3.5. */
+function entropy(value: string): number {
+ const counts = new Map<string, number>()
+ for (const char of value) counts.set(char, (counts.get(char) ?? 0) + 1)
+ let bits = 0
+ for (const count of counts.values()) bits -= (count / value.length) * Math.log2(count / value.length)
+ return bits
+}
+const hasLetterAndDigit = (value: string) => /[A-Za-z]/.test(value) && /\d/.test(value)
+/** The random part of a known format: not a placeholder such as `ghp_xxxx…`. */
+const random = (body: string) => entropy(body) >= 2.5
+/** Random characters, not words: one run of 8 or more between separators mixes letters and digits (`Xk9mQ2vL…`, not
+ * `test-password-123`). `mixedCase` also takes 16 or more letters of both cases, as base64 without digits can be. */
+function randomRun(value: string, mixedCase = false): boolean {
+ return value.split(/[-_.:/+=~@]+/).some(run => (run.length >= 8 && hasLetterAndDigit(run))
+ || (mixedCase && run.length >= 16 && /[a-z]/.test(run) && /[A-Z]/.test(run) && entropy(run) >= 3.5))
+}
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+/** A generic value people would call a password, token or secret: long, random characters. Never a UUID, a name that only
+ * refers to one (`process.env.API_TOKEN2`, `SECRET_KEY_V2`, `uuid::Uuid`), a path, a URL or a template. */
+function secretValue(value: string, minimum = 12, mixedCase = false): boolean {
+ if (value.length < minimum || !randomRun(value, mixedCase) || entropy(value) < 3 || UUID.test(value)) return false
+ if (/^[A-Za-z_$][\w$-]*((\.|::)[A-Za-z_$][\w$-]*)+$/.test(value)) return false
+ if (/^[A-Z][A-Z\d]*(_[A-Z\d]+)+$/.test(value)) return false
+ return !/^(\/|~\/|\.\.?\/)|:\/\/|[${}<>]/.test(value)
+}
+
+function jwtHeader(segment: string): boolean {
+ try {
+ const header: unknown = JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'))
+ return !!header && typeof header === 'object' && typeof (header as { alg?: unknown }).alg === 'string'
+ } catch { return false }
+}
+
+interface Rule {
+ kind: CredentialKind
+ /** Global, with indices (`d`) so a capture group can name the secret. Each starts after a boundary, so a long run of
+ * letters is tried once, not at every position. */
+ pattern: RegExp
+ /** The capture group holding the secret; 0 is the whole match. A labelled value keeps its label. */
+ group?: number
+ /** Whether the secret is one, and how much of it to remove (a JWT at the end of a sentence keeps its full stop). */
+ accept: (secret: string) => boolean | number
+}
+
+const HARNESS_PREFIXES = [HARNESS_ACCESS_PREFIX, HARNESS_REFRESH_PREFIX, HARNESS_HANDOFF_PREFIX, HARNESS_QR_PREFIX, HARNESS_QR_POLL_PREFIX]
+// Keys whose value is the secret: DB_PASSWORD, x-api-key, client_secret, access_token, "token": … Not `pwd` (a folder), and
+// nothing public (.NET's publicKeyToken).
+const KEY = String.raw`(?![\w.-]*public)[A-Za-z0-9_.-]*?(?:password|passwd|passphrase|secret|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|credentials?)`
+const ASSIGN = String.raw`["']?[ \t]*(?:=>|:=|[:=])[ \t]*["'\x60]?`
+
+/** Most specific first: a GitHub token inside `token=…` is a GitHub token. */
+const RULES: Rule[] = [
+ { kind: 'jwt', pattern: /(?<![A-Za-z0-9_\-.+/])[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*){2,5}(?![A-Za-z0-9_\-+/=])/dg, accept: token => {
+ // A full stop after the token ends the sentence; three segments are signed (JWS), five encrypted (JWE).
+ const trimmed = token.endsWith('.') ? token.slice(0, -1) : token
+ const segments = trimmed.split('.')
+ return (segments.length === 3 || segments.length === 5) && segments[1]!.length > 0 && jwtHeader(segments[0]!) && trimmed.length
+ } },
+ { kind: 'harness', pattern: new RegExp(String.raw`(?<![A-Za-z0-9_-])(?:${HARNESS_PREFIXES.join('|')})[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])`, 'dg'),
+ accept: token => random(token.slice(4)) },
+ { kind: 'github', pattern: /(?<![A-Za-z0-9_])(?:gh[pousr]_[A-Za-z0-9]{36,251}|github_pat_[A-Za-z0-9_]{50,251})(?![A-Za-z0-9_])/dg,
+ accept: token => random(token.slice(token.indexOf('_') + 1)) },
+ { kind: 'anthropic', pattern: /(?<![A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/dg, accept: token => random(token.slice(7)) && hasLetterAndDigit(token.slice(7)) },
+ { kind: 'openai', pattern: /(?<![A-Za-z0-9_-])sk-(?!ant-)(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/dg,
+ accept: token => entropy(token) >= 3 && hasLetterAndDigit(token.slice(3)) },
+ { kind: 'aws-key-id', pattern: /(?<![A-Za-z0-9])(?:AKIA|ASIA)[A-Z0-9]{16}(?![A-Za-z0-9])/dg, accept: token => random(token.slice(4)) },
+ { kind: 'aws-secret', group: 1, accept: value => entropy(value) >= 3.5,
+ pattern: new RegExp(String.raw`(?<![A-Za-z0-9])(?:aws[_.\- ]?secret[_.\- ]?(?:access[_.\- ]?)?key|secret[_.\- ]?access[_.\- ]?key)${ASSIGN}([A-Za-z0-9/+]{40})(?![A-Za-z0-9/+=])`, 'dgi') },
+ { kind: 'slack', pattern: /(?<![A-Za-z0-9_-])xox[abprs]-\d{6,}-[A-Za-z0-9-]{8,}(?![A-Za-z0-9_-])/dg, accept: token => random(token) },
+ // Base64 data cannot be next to it, so a long image never holds one by chance.
+ { kind: 'google', pattern: /(?<![A-Za-z0-9_\-+/])AIza[A-Za-z0-9_-]{35}(?![A-Za-z0-9_\-+/])/dg, accept: token => random(token.slice(4)) },
+ // Authorization: Bearer|Basic|Token …, which may be letters only (Basic is base64 of user:password).
+ { kind: 'password', group: 1, accept: value => secretValue(value, 12, true),
+ pattern: /(?<![A-Za-z0-9_-])Authorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Bot)\s+([A-Za-z0-9._~+/=-]{12,})/dgi },
+ { kind: 'password', group: 1, accept: value => secretValue(value, 20), pattern: /(?<![A-Za-z0-9])Bearer\s+([A-Za-z0-9._~+/=-]{20,})/dg },
+ // A password in a URL: postgres://app:…@db.
+ { kind: 'password', group: 1, accept: value => randomRun(value) && entropy(value) >= 2.5 && !/[${}<>]/.test(value),
+ pattern: /(?<![A-Za-z0-9+.-])[a-z][a-z0-9+.-]{1,20}:\/\/[^\s/:@]{1,256}:([^\s/@]{8,256})@/dgi },
+ { kind: 'password', group: 1, accept: value => secretValue(value.replace(/[.!?:]+$/, '')) && value.replace(/[.!?:]+$/, '').length,
+ pattern: new RegExp(String.raw`(?<![A-Za-z0-9_.-])${KEY}${ASSIGN}([^\s"'\x60<>()[\]{}$%&,;\\]{12,})`, 'dgi') },
+]
+
+/** Private keys first, by hand: a block may be cut off before its END line, and then its base64 lines still go. */
+function privateKeys(text: string): FoundCredential[] {
+ const found: FoundCredential[] = []
+ const begin = /-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?)-----/g
+ for (let match = begin.exec(text); match; match = begin.exec(text)) {
+ const endLine = `-----END ${match[1]}-----`
+ const end = text.indexOf(endLine, begin.lastIndex)
+ let stop = end >= 0 ? end + endLine.length : begin.lastIndex
+ if (end < 0) {
+ // Cut off: the body on the same line (a JSON string with \n escapes), then the lines that follow while they are
+ // base64 or `Proc-Type: …` headers.
+ const inline = /(?:[A-Za-z0-9+/=]|\\[nr])*/y
+ inline.lastIndex = stop
+ inline.exec(text)
+ stop = inline.lastIndex
+ const lines = /\r?\n(?:[A-Za-z0-9+/]{8,}={0,2}|[A-Za-z0-9+/]{1,7}={1,2}|[A-Za-z-]+: [^\r\n]*)(?=\r?\n|$)/y
+ lines.lastIndex = stop
+ while (lines.exec(text)) stop = lines.lastIndex
+ }
+ // A key has a body; the BEGIN line alone, or an empty template, is only someone talking about the format.
+ if (/[A-Za-z0-9+/]{16,}/.test(text.slice(begin.lastIndex, end >= 0 ? end : stop))) found.push({ kind: 'private-key', start: match.index, end: stop })
+ begin.lastIndex = stop
+ }
+ return found
+}
+
+/** Every credential in the text, in order, none overlapping. */
+export function findCredentials(text: string): FoundCredential[] {
+ const found = privateKeys(text)
+ // A data: URI's base64 is an image or a file, never a credential.
+ const skipped = [...text.matchAll(/data:[\w/+.-]{1,100};base64,[A-Za-z0-9+/=]+/g)].map(m => ({ start: m.index, end: m.index + m[0].length }))
+ const free = (start: number, end: number) => ![...found, ...skipped].some(f => start < f.end && f.start < end)
+ for (const rule of RULES) {
+ for (const match of text.matchAll(rule.pattern)) {
+ const [start, end] = match.indices![rule.group ?? 0]!
+ const verdict = rule.accept(text.slice(start, end))
+ if (verdict === false || verdict === 0) continue
+ const stop = typeof verdict === 'number' ? start + verdict : end
+ if (free(start, stop)) found.push({ kind: rule.kind, start, end: stop })
+ }
+ }
+ return found.sort((a, b) => a.start - b.start)
+}
+
+/** The text with each credential replaced by CREDENTIAL_MARKER, and what was removed, one entry per credential. */
+export function redactCredentials(text: string): { text: string; removed: CredentialKind[] } {
+ const found = findCredentials(text)
+ if (!found.length) return { text, removed: [] }
+ let redacted = '', at = 0
+ for (const { start, end } of found) {
+ redacted += text.slice(at, start) + CREDENTIAL_MARKER
+ at = end
+ }
+ return { text: redacted + text.slice(at), removed: found.map(f => f.kind) }
+}
+
+/** What the sender's command result says: which kinds went, and one line telling them to revoke or rotate it. */
+export function credentialResult(removed: CredentialKind[]) {
+ const kinds = [...new Set(removed)]
+ const what = kinds.map(kind => CREDENTIAL_LABELS[kind]).join(', ')
+ const notice = removed.length === 1
+ ? `Removed a credential (${what}) before saving. Revoke or rotate it.`
+ : `Removed ${removed.length} credentials (${what}) before saving. Revoke or rotate them.`
+ return {
+ credentialsRemoved: kinds.map(kind => ({ kind, label: CREDENTIAL_LABELS[kind], count: removed.filter(k => k === kind).length })),
+ credentialNotice: notice,
+ }
+}
diff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.ts
index bd53fa073..53e3bf2ab 100644
--- a/backend/src/superTabs/native.ts
+++ b/backend/src/superTabs/native.ts
@@ -6,6 +6,7 @@ import { activeWork, agent, appendPullRequestUrls, author, conversation, fail, i
type Actor, type Agent, type Author, type Conversation, type SuperTabState } from './model.js'
import { canReadProject, groupProject, readConversation } from './projects.js'
import { noteProjectReports } from './projectUpdates.js'
+import { redactCredentials } from './credentials.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
export const openNativeSchema = z.object({ operationId: id, conversationId: id, agentId: id }).strict()
@@ -186,8 +187,9 @@ export class SuperTabNativeStore {
const recovery = await this.recovery(tx, tabId, group, target, record, event, eventId, revision)
group.lastMessageSequence = revision
const observedBy = author(state, { kind: 'agent', agentId: target.id, machineOwnerId: user.sub }, true)
+ // What a person typed in the terminal, or the agent answered, is recorded without any credential in it.
const text = recovery?.source.required ? recovery.text : event.kind === 'gap'
- ? 'Some terminal activity could not be recorded. Check the native session for the full conversation.' : event.text
+ ? 'Some terminal activity could not be recorded. Check the native session for the full conversation.' : redactCredentials(event.text).text
// Leave a legacy group's list absent so the next read can recover its older links too.
if (group.pullRequestUrls !== undefined) appendPullRequestUrls(group, [text])
// Inform the coordinating lead without replaying this input into the agent
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 731e3a58d..d38b25ff6 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -6,6 +6,7 @@ import { machineAlive } from '../lib/prisma.js'
import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'
import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
import { applyCommand, authorizeCommandAccess, operationSchema, PAIR_CHAIN_LIMIT, postable, type Command, type CommandContext } from './commands.js'
+import { redactCredentials } from './credentials.js'
import { attachmentMime, attachmentName, AttachmentTooLarge, checkedType, MAX_ATTACHMENT_BYTES, objectKeyFor, publicUrl, type Attachment, type Attachments } from './attachments.js'
import { randomBytes } from 'node:crypto'
import type { Readable } from 'node:stream'
@@ -682,7 +683,8 @@ export class SuperTabStore {
* checked before a byte is stored; the row that makes it sendable is written only once the whole file is. */
async upload(user: AuthUser, tabId: string, conversationId: string, file: { name: string; mime: string; body: Readable }, asAgentId?: string) {
const attachments = this.attachments ?? fail('ATTACHMENTS_UNAVAILABLE', 'File attachments are not available on this server.', 503)
- const name = attachmentName.safeParse(file.name), mime = attachmentMime.safeParse(file.mime)
+ // A file's name is shown in the chat like its message, so it never keeps a credential either.
+ const name = attachmentName.transform(value => redactCredentials(value).text).safeParse(file.name), mime = attachmentMime.safeParse(file.mime)
if (!name.success || !mime.success) fail('INVALID_ATTACHMENT', 'Attach a file with a printable name and a content type.', 400)
const key = await transaction(this.db, async tx => {
const { actor } = await this.poster(tx, user, tabId, conversationId, asAgentId)
diff --git a/backend/src/superTabs/terminal.test.ts b/backend/src/superTabs/terminal.test.ts
index 2f0cdcc85..69df8f63e 100644
--- a/backend/src/superTabs/terminal.test.ts
+++ b/backend/src/superTabs/terminal.test.ts
@@ -66,6 +66,22 @@ describe('reading and typing in an agent terminal', () => {
source: { kind: 'terminal-input', agentId: s.worker, requestId: effects.result.requestId } })])
})
+ it('types a credential as given but never shows it in the group\'s row, even where the row is cut', () => {
+ const s = swarm()
+ s.run({ type: 'work.assign', conversationId: s.group, agentId: s.worker })
+ // Assembled at run time from obviously fake parts.
+ const token = ['ghp', 'Fixture0Token1Not2Real3Value4abcdefgh'].join('_')
+ const text = `${'x'.repeat(150)} gh auth login --with-token ${token} and more words after it`
+ const effects = s.run({ type: 'agent.input', agentId: s.worker, text, keys: ['Enter'] }, as(s.lead))
+ expect(effects.terminal).toMatchObject({ op: 'request', kind: 'input', text })
+ expect(effects.messages).toHaveLength(1)
+ expect(effects.messages[0]!.text).not.toContain(token.slice(0, 12))
+ // Cut at 200 first, the row would have kept the token's first 21 characters.
+ const shown = `${'x'.repeat(150)} gh auth login --with-token [credential removed] and more words after it`.slice(0, 199)
+ expect(effects.messages[0]!.text).toBe(`${name(s, s.lead)} typed \`${shown}…\` + Enter in ${name(s, s.worker)}'s terminal`)
+ expect(effects.result.credentialNotice).toBe('Removed a credential (GitHub token) before saving. Revoke or rotate it.')
+ })
+
it('logs input to the Lead in the project\'s Lead conversation', () => {
const s = swarm()
expect(s.run({ type: 'agent.input', agentId: s.lead, keys: ['Esc', '2'] }).messages[0])
diff --git a/backend/src/superTabs/terminal.ts b/backend/src/superTabs/terminal.ts
index 9565454d0..860c7f733 100644
--- a/backend/src/superTabs/terminal.ts
+++ b/backend/src/superTabs/terminal.ts
@@ -3,6 +3,7 @@ import { activeWork, actorKey, agent, author, conversation, fail, isLeads, stabl
type SuperTabState } from './model.js'
import { downSince } from './machines.js'
import { agentProjectId, projectOf, readAgent } from './projects.js'
+import { redactCredentials } from './credentials.js'
/** The Lead reads and types in an agent's terminal through the host of the agent's machine (spec/2026-10-23-lead-sees-agent-terminal.md).
* The request and its answer live in SuperTabTerminalRequest, never in the tab state or group history, because a screen can show secrets. */
@@ -58,13 +59,15 @@ export function terminalRequest(state: SuperTabState, actor: Actor, sender: Auth
const { type: _type, agentId: _agentId, ...detail } = command
const effect: TerminalEffect = { op: 'request', id, kind: command.type === 'agent.screen' ? 'screen' : 'input', agentId: target.id,
machineId: target.machineId, machineOwnerId: target.machineOwnerId, harnessId: target.harnessId, requesterKey: actorKey(actor), ...detail }
- if (command.type === 'agent.screen') return { effect, message: null }
- const text = command.text && `\`${command.text.length > 200 ? `${command.text.slice(0, 199)}…` : command.text}\``
- const typed = [text, ...command.keys ?? []].filter(Boolean).join(' + ')
+ if (command.type === 'agent.screen') return { effect, message: null, removed: [] }
+ // The host types the exact text; the group's row never shows a credential in it, even one the cut at 200 would split.
+ const typed = redactCredentials(command.text ?? '')
+ const text = command.text && `\`${typed.text.length > 200 ? `${typed.text.slice(0, 199)}…` : typed.text}\``
+ const shown = [text, ...command.keys ?? []].filter(Boolean).join(' + ')
const who = sender.displayName ?? (sender.kind === 'person' ? sender.name.split('@')[0]! : sender.name)
const message: MessageDraft = { id, conversationId: currentGroup(state, target).id, author: sender, replyTo: null, recipients: [],
- text: `${who} typed ${typed} in ${nameOf(target)}'s terminal`, source: { kind: 'terminal-input', agentId: target.id, requestId: id } }
- return { effect, message }
+ text: `${who} typed ${shown} in ${nameOf(target)}'s terminal`, source: { kind: 'terminal-input', agentId: target.id, requestId: id } }
+ return { effect, message, removed: typed.removed }
}
/** Only the host of the agent's current terminal answers, once, a request it claimed. */
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index b024dfe43..081d57cda 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -117,6 +117,10 @@ class SuperTabController extends ChangeNotifier {
String selectedId = 'lead';
int revision = -1;
String? error, operationError, operationErrorCode;
+
+ /// One line for the sender after a command succeeds, from the backend: that a
+ /// credential was removed from what they sent and should be revoked.
+ String? operationNotice;
bool loading = false, saving = false, uploading = false;
bool accessRevoked = false;
bool _disposed = false;
@@ -433,6 +437,7 @@ class SuperTabController extends ChangeNotifier {
if (group.archived) closedOpenProjects.add(group.projectId);
}
selectedId = id;
+ operationNotice = null;
_saveSoon();
_changed();
unawaited(loadMessages(id));
@@ -678,6 +683,7 @@ class SuperTabController extends ChangeNotifier {
saving = true;
operationError = null;
operationErrorCode = null;
+ operationNotice = null;
_changed();
try {
// The receipt ID reaches durable local storage before the request can reach the server.
@@ -687,6 +693,8 @@ class SuperTabController extends ChangeNotifier {
if (_disposed) return null;
final result = superTabMap(answer['result']);
final command = superTabMap(pending['command']);
+ final notice = result['credentialNotice'];
+ operationNotice = notice is String && notice.isNotEmpty ? notice : null;
if (command['type'] == 'message.send') {
final id = command['conversationId'] as String;
if (_drafts[id]?.trim() == command['text']) {
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index dea51c5cc..bfb367c24 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -1369,6 +1369,15 @@ class _SuperTabViewState extends State<SuperTabView>
),
],
),
+ )
+ else if (c.operationNotice != null)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Text(
+ c.operationNotice!,
+ key: const ValueKey('super-operation-notice'),
+ style: DesktopChrome.control(),
+ ),
),
if (reply != null)
Padding(
diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dart
index b39ceea3f..c3918a578 100644
--- a/desktop/test/super_tab_chat_test.dart
+++ b/desktop/test/super_tab_chat_test.dart
@@ -396,6 +396,34 @@ void main() {
},
);
+ testWidgets(
+ 'a sent message whose credential was removed says so in one line above the composer',
+ (tester) async {
+ const notice =
+ 'Removed a credential (JWT) before saving. Revoke or rotate it.';
+ final server = ConversationServer()
+ ..commandResult['credentialNotice'] = notice;
+ await show(tester, server);
+ expect(
+ find.byKey(const ValueKey('super-operation-notice')),
+ findsNothing,
+ );
+ await tester.enterText(
+ find.byKey(const ValueKey('super-message-composer')),
+ 'My login token is in here.',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text(notice), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('super-operation-notice')),
+ findsOneWidget,
+ );
+ // Let the emptied draft's save run.
+ await tester.pump(const Duration(milliseconds: 300));
+ },
+ );
+
testWidgets('the quote of your own message reads You, not your email', (
tester,
) async {
diff --git a/desktop/test/super_tab_controller_test.dart b/desktop/test/super_tab_controller_test.dart
index e7ac030db..79969c4f9 100644
--- a/desktop/test/super_tab_controller_test.dart
+++ b/desktop/test/super_tab_controller_test.dart
@@ -31,6 +31,29 @@ void main() {
},
);
+ test('keeps the backend\'s credential notice for the sender until the next action', () async {
+ const notice =
+ 'Removed a credential (GitHub token) before saving. Revoke or rotate it.';
+ final server = ConversationServer()
+ ..commandResult['credentialNotice'] = notice;
+ final c = server.controller();
+ await c.refresh();
+ c.setDraft('lead', 'Here is the token.');
+ expect(await c.send(), isNotNull);
+ expect(c.operationNotice, notice);
+ expect(c.draft('lead'), isEmpty);
+ server.commandResult.clear();
+ c.setDraft('lead', 'Plain words.');
+ expect(await c.send(), isNotNull);
+ expect(c.operationNotice, isNull);
+ server.commandResult['credentialNotice'] = notice;
+ c.setDraft('lead', 'Again.');
+ await c.send();
+ c.select('offline');
+ expect(c.operationNotice, isNull);
+ c.dispose();
+ });
+
test(
'group terminals keep every member when selecting one and after reopening',
() async {
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index d956c9852..a83e06563 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -41,6 +41,9 @@ class ConversationServer {
Completer<void>? holdReads;
// Makes every command answer with this refusal: {code, message}.
Map<String, String>? refuse;
+ // Added to every successful command's result, as a newer backend adds
+ // fields such as `credentialNotice`.
+ final commandResult = <String, dynamic>{};
final posts = <Map<String, dynamic>>[];
final receipts = <String, Map<String, dynamic>>{};
final messages = <Map<String, dynamic>>[];
@@ -263,6 +266,7 @@ class ConversationServer {
revision++;
}
}
+ output.addAll(commandResult);
final result = {'revision': revision, 'result': output};
receipts[operationId] = result;
if (loseReply) {