Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(companions): mask decoded Basic credentials

Chris72d4119527b6
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index aebbd5ea1a..3bb9f39458 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -607,7 +607,12 @@ publication treats stdin and credential-named options as private literals and
examines other arguments for structured credential fields and capability URLs.
Credential-named header literals (including X-API-Key and X-Auth-Token) mask
their payload; Authorization/Proxy-Authorization additionally mask the credential
-after the scheme. MCP and commands share Cookie decomposition: every nonempty
+after the scheme. For Basic authentication, canonical standard Base64 (padded or
+unpadded) also supplies the decoded userinfo and the entire password after its
+first colon; UTF-8 and legacy single-byte text are preserved. Invalid encoding
+or userinfo without a colon adds no decoded guesses; usernames alone and the
+empty `:` pair do not become masks. Original headers are never rewritten.
+MCP and commands share Cookie decomposition: every nonempty
cookie value, including quoted and percent-decoded forms, stays private because
cookie names are application-defined. This does not make scheme names or ordinary
Accept/Content-Type values global masks. This covers
diff --git a/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts b/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts
index f8056298e3..739a9954e7 100644
--- a/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts
@@ -379,6 +379,30 @@ it.each(['stdin', 'argv', 'assignment', 'env', 'inherited-env'])('masks form cre
expect(shared.message.mock.calls[0]![1].content).toBe(result!.direct);
});
+it.each(['Authorization', 'Proxy-Authorization'])('masks decoded Basic %s credentials from command output, caches and final chat', async name => {
+ const userinfo = 'alice:fixture-basic:password';
+ const header = `${name}: Basic ${Buffer.from(userinfo).toString('base64')}`;
+ const code = 'const u=Buffer.from(process.argv[1].split(/\\s+/).at(-1),"base64").toString();process.stdout.write(u+" | "+u.slice(u.indexOf(":")+1)+" | alice | public report");';
+ const original = { payload: { kind: 'command', argv: [process.execPath, '-e', code, header], cwd: root } };
+ const output = `${userinfo} | fixture-basic:password | alice | public report`;
+ const routine = { id: 'routine', botId: 'bot', prompt: 'Fixture Basic report' } as Routine;
+ await shared.store.write(root, 'bot', { version: 1, env: {}, mcp: [], credentials: [], automations: {
+ routine: { kind: 'openclaw', handover: 'ready', original, sourceRoot: root },
+ } }, () => {});
+ const signal = new AbortController().signal;
+ const result = await prepareImportedAutomation(root, routine, 'basic-run', signal, () => {});
+ expect(result!.direct).toMatch(/^(?:\[command_literal_\w+\] \| ){2}alice \| public report$/);
+ const saved = (await shared.store.read(root, 'bot', () => {}))!;
+ expect(saved.automations!.routine!.original).toEqual(original);
+ expect(saved.automations!.routine!.prepared?.direct).toBe(result!.direct);
+ await shared.store.update(root, 'bot', () => {}, env => { env.automations!.routine!.prepared = { runId: 'basic-run', prompt: '', direct: output }; });
+ expect((await prepareImportedAutomation(root, routine, 'basic-run', signal, () => {}))?.direct).toBe(result!.direct);
+ await shared.store.update(root, 'bot', () => {}, env => { env.automations!.routine!.deliveryProgress = { runId: 'basic-run', text: output, direct: true, deliveries: [], next: 0 }; });
+ expect((await prepareImportedAutomation(root, routine, 'retry-run', signal, () => {}))?.direct).toBe(result!.direct);
+ await finishImportedAutomation(root, routine, 'chat', 'retry-run', output, true, signal, () => {});
+ expect(shared.message.mock.calls[0]![1].content).toBe(result!.direct);
+});
+
it.each(['X-API-Key', 'X-Auth-Token', 'Cookie'])('masks independently echoed %s header values through command execution and retry publication', async name => {
const header = `${name}: ${name === 'Cookie' ? 'session=fixture-session%2Fsecret; second="fixture-second-cookie"' : 'fixture-header-secret'}`;
const code = 'const h=process.argv[1];const v=h.slice(h.indexOf(":")+1).trim();process.stdout.write((/^cookie:/i.test(h)?v.split(";").map(p=>decodeURIComponent(p.slice(p.indexOf("=")+1).trim().replace(/^"|"$/g,""))).join(" | "):v)+" | public report");';
diff --git a/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts b/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts
index 15c52027c1..c87d1e88ac 100644
--- a/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts
@@ -312,11 +312,14 @@ it.each([true, false])('preserves MCP response syntax and isError=%s when enviro
it('redacts resolved catalog credentials without changing schema syntax, tool dispatch or connection configuration', async () => {
const env = { TOKEN: 'fixture-global-token', TYPE: 'object' };
+ const basicUserinfo = 'alice:fixture-mcp-basic:password';
+ const basicEncoded = Buffer.from(basicUserinfo).toString('base64');
const connection = { name: 'fixture-server', url: 'https://fixture-user:[email protected]/mcp/fixture-path%2Ftoken?key=fixture-url-key#access_token=fixture%2Ffragment%2Bsecret',
env: { TOKEN: 'fixture-local-token' }, headers: { Authorization: 'Bearer fixture-header-token', 'X-Api-Key': 'fixture-api-key',
+ 'Proxy-Authorization': `Basic ${basicEncoded}`,
cOoKiE: 'session=fixture-cookie-session; alternate="fixture-cookie%2Fquoted=="; preference=dark' } };
const secrets = [env.TOKEN, connection.env.TOKEN, connection.headers.Authorization, 'fixture-header-token', connection.headers['X-Api-Key'], connection.url, 'fixture-user', 'fixture-password', 'fixture-url-key', 'fixture-path%2Ftoken', 'fixture-path/token', 'fixture/fragment+secret', 'fixture%2Ffragment%2Bsecret',
- 'fixture-cookie-session', 'fixture-cookie%2Fquoted==', 'fixture-cookie/quoted==', 'dark'];
+ 'fixture-cookie-session', 'fixture-cookie%2Fquoted==', 'fixture-cookie/quoted==', 'dark', basicUserinfo, basicEncoded, 'fixture-mcp-basic:password'];
const echo = secrets.join(' ');
const secretKey = 'argument_fixture-path/token';
const tool: Tool = { name: `read_${connection.env.TOKEN}`, title: echo, description: echo,
diff --git a/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts b/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts
index 253c1668a6..c892fd81c6 100644
--- a/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts
@@ -3,6 +3,52 @@ import { previewImportRedactions, resolveImportReferences, retainedImportRedacti
import { redactEnvironmentValues } from '../process.js';
import type { ImportItem } from '../types.js';
import { commandArgumentRedactions } from '../commandRedactions.js';
+import { headerCredentialValues } from '../connectionCatalog.js';
+
+it.each(['command', 'mcp'])('masks decoded Basic userinfo and passwords in %s publication masks', source => {
+ const userinfo = 'alice:fixture-basic:password';
+ const encoded = Buffer.from(userinfo).toString('base64');
+ for (const name of ['Authorization', 'Proxy-Authorization']) {
+ const header = `bAsIc ${encoded}`;
+ const items: ImportItem[] = [{ view: { id: 'source', name: 'Data', category: 'connections', selected: true },
+ ...(source === 'mcp' ? { mcp: { name: 'data', headers: { [name]: header } } }
+ : { automation: { sourceId: 'job', fingerprint: 'fixture', original: { payload: { kind: 'command', argv: ['curl', '--header=' + name + ': ' + header] } } } }) }];
+ const before = structuredClone(items);
+ for (const collect of [previewImportRedactions, selectedImportRedactions]) {
+ const result = redactEnvironmentValues(`${header}\n${encoded}\n${userinfo}\nfixture-basic:password\nalice Basic ordinary data`, collect(items));
+ expect(result).toMatch(/^(?:\[[^\]]+\]\n){4}alice Basic ordinary data$/);
+ }
+ expect(items).toEqual(before);
+ }
+});
+
+it.each([
+ ['alice:fixture-pass:with:colons', 'utf8'], ['alice: 密码🔑 ', 'utf8'], ['alice:pässwörd', 'latin1'],
+ [':fixture-empty-user-password', 'utf8'], ['alice:', 'utf8'],
+] as const)('decodes canonical Basic text %j (%s) without trimming passwords or masking usernames', (userinfo, encoding) => {
+ const encoded = Buffer.from(userinfo, encoding).toString('base64');
+ const password = userinfo.slice(userinfo.indexOf(':') + 1);
+ for (const wire of new Set([encoded, encoded.replace(/=+$/, '')])) {
+ const values = headerCredentialValues('Authorization', `Basic ${wire}`);
+ expect(values).toContain(userinfo);
+ if (password) expect(values).toContain(password);
+ expect(values).not.toContain('alice');
+ expect(values).not.toContain('');
+ }
+});
+
+it.each(['YWxpY2U6eB==', 'YWxpY2U6eA=', 'YWxpY2U6eA===', 'YWxpY2U6 eA==', 'YWxpY2U6eA==!',
+ 'YWxpY2U6__8=', 'YW=x', 'A', Buffer.from('alice-without-password').toString('base64')])
+('does not derive plaintext masks from invalid Basic userinfo %j', encoded => {
+ expect(headerCredentialValues('Authorization', `Basic ${encoded}`)).toEqual([`Basic ${encoded}`, encoded]);
+});
+
+it('does not decode other schemes or introduce a colon mask for empty Basic credentials', () => {
+ const encoded = Buffer.from('alice:fixture-basic-password').toString('base64');
+ expect(headerCredentialValues('Authorization', `Bearer ${encoded}`)).toEqual([`Bearer ${encoded}`, encoded]);
+ expect(headerCredentialValues('X-API-Key', `Basic ${encoded}`)).toEqual([`Basic ${encoded}`]);
+ expect(headerCredentialValues('Authorization', 'Basic Og==')).toEqual(['Basic Og==', 'Og==']);
+});
it('retains matched credentials across selected strings and buffers with one matcher', () => {
let reads = 0;
diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
index 2deda3b06c..23b8c08958 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -436,7 +436,8 @@ it.each(['hermes', 'openclaw'] as const)('masks %s names from real source files
});
it.each([false, true])('redacts all known credentials from profile/memory copies while importing only selected connections (deselected: %s)', async deselected => {
- const secrets = ['fake-env-key', 'fake-local-key', 'fake-header-token', 'fake/url+key', 'fake-access-token', 'fake-refresh-token', '123:fake-telegram-token', 'fixture-cookie-session', 'fixture-cookie/second'];
+ const basic = `Basic ${Buffer.from('alice:fixture-mcp-basic:password').toString('base64')}`;
+ const secrets = ['fake-env-key', 'fake-local-key', 'fake-header-token', 'fake/url+key', 'fake-access-token', 'fake-refresh-token', '123:fake-telegram-token', 'fixture-cookie-session', 'fixture-cookie/second', 'alice:fixture-mcp-basic:password', 'fixture-mcp-basic:password'];
const text = `简短一点,带点幽默。status en us true 3000\n${secrets.join('\n')}\nfake-unselected-key`;
const documents: ImportSnapshot['items'] = [
{ view: { id: 'soul', name: 'SOUL.md', category: 'personality', selected: true }, role: 'identity', text },
@@ -447,7 +448,7 @@ it.each([false, true])('redacts all known credentials from profile/memory copies
];
h.snapshot.items = [...documents,
{ view: { id: 'env', name: 'env', category: 'connections', selected: true }, env: { DATA_TOKEN: secrets[0]!, LANG: 'en', REGION: 'us', DEBUG: 'true', PORT: '3000' } },
- { view: { id: 'mcp', name: 'Data', category: 'connections', selected: true }, mcp: { name: 'Data', url: 'https://example.invalid/mcp?token=fake%2Furl%2Bkey', env: { KEY: secrets[1]!, REFERENCED: '${DATA_TOKEN}' }, headers: { Authorization: `Bearer ${secrets[2]}`, Cookie: 'session=fixture-cookie-session; another="fixture-cookie%2Fsecond"' } } },
+ { view: { id: 'mcp', name: 'Data', category: 'connections', selected: true }, mcp: { name: 'Data', url: 'https://example.invalid/mcp?token=fake%2Furl%2Bkey', env: { KEY: secrets[1]!, REFERENCED: '${DATA_TOKEN}' }, headers: { Authorization: `Bearer ${secrets[2]}`, 'Proxy-Authorization': basic, Cookie: 'session=fixture-cookie-session; another="fixture-cookie%2Fsecond"' } } },
{ view: { id: 'oauth', name: 'Auth', category: 'connections', selected: true }, credential: { format: 'native-auth', value: { value: { access_token: secrets[4], nested: { refreshToken: secrets[5] } } } } },
{ view: { id: 'telegram', name: 'Telegram', category: 'connections', selected: true }, credential: { format: 'telegram', value: { token: secrets[6], account: 'default' } } },
{ view: { id: 'excluded', name: 'Excluded', category: 'connections', selected: false }, env: { EXCLUDED: 'fake-unselected-key', UNUSED_ONLY: 'fake-absent-from-selected-content' } },
@@ -472,6 +473,7 @@ it.each([false, true])('redacts all known credentials from profile/memory copies
expect(stored.env.DATA_TOKEN).toBe(secrets[0]);
expect(stored.mcp[0]?.env?.REFERENCED).toBe(secrets[0]);
expect(stored.mcp[0]?.headers?.Authorization).toBe(`Bearer ${secrets[2]}`);
+ expect(stored.mcp[0]?.headers?.['Proxy-Authorization']).toBe(basic);
expect(stored.mcp[0]?.headers?.Cookie).toBe('session=fixture-cookie-session; another="fixture-cookie%2Fsecond"');
}
expect(stored.env).not.toHaveProperty('EXCLUDED');
@@ -485,7 +487,7 @@ it.each([false, true])('redacts all known credentials from profile/memory copies
it.each([false, true])('publishes command env/argv/stdin credentials safely (command selected: %s)', async selected => {
const secret = 'fixture-command-json-token';
const nested = 'fixture-command-json-nested';
- const literalSecrets = ['fixture-argv-token', 'fixture-stdin-token', 'fixture-plain-token', 'fixture-header-token', 'fixture-form argv', 'fixture-form%20argv', 'fixture-form/env', 'fixture-form%2Fenv', 'fixture-curl-password', 'fixture-custom-header-key', 'fixture-command-cookie'];
+ const literalSecrets = ['fixture-argv-token', 'fixture-stdin-token', 'fixture-plain-token', 'fixture-header-token', 'fixture-form argv', 'fixture-form%20argv', 'fixture-form/env', 'fixture-form%2Fenv', 'fixture-curl-password', 'fixture-custom-header-key', 'fixture-command-cookie', 'alice:fixture-basic:password', 'fixture-basic:password'];
const urlSecrets = ['fixture-hook-token', 'fixture-fragment token', 'fixture-fragment%20token',
'fixture-raw token', 'fixture-raw%20token', 'fixture-raw-query', 'fixture-raw-fragment'];
const config = JSON.stringify({ token: secret, credentials: [{ key: nested }],
@@ -493,7 +495,7 @@ it.each([false, true])('publishes command env/argv/stdin credentials safely (com
unused: { password: 'fixture-unused-command-secret' }, city: 'Paris', count: 7 });
const text = `Keep node --mode -e, Paris and 7. ${secret} ${nested} ${urlSecrets.join(' ')} ${literalSecrets.join(' ')}`;
const skill = `---\nname: report\ndescription: ${text}\n---\n${text}\n`;
- const original = { enabled: false, payload: { kind: 'command', argv: ['curl', '-u', 'alice:fixture-curl-password', '--config=' + JSON.stringify({ token: literalSecrets[0], city: 'Paris' }), '--token=' + literalSecrets[2], '-H', 'Authorization: Bearer ' + literalSecrets[3], '-H', 'X-API-Key: fixture-custom-header-key', '-HCookie: session=fixture-command-cookie', '--data', 'access_token=fixture-form%20argv&city=Paris'], input: JSON.stringify({ credentials: [{ privateKeyPem: literalSecrets[1] }], count: 7 }), env: { CONFIG: config, FORM: 'password=fixture-form%2Fenv&days=7', WEBHOOK_URL: 'https://host/hooks/fixture-raw%20token?token=fixture-raw-query#access_token=fixture-raw-fragment' } } };
+ const original = { enabled: false, payload: { kind: 'command', argv: ['curl', '-u', 'alice:fixture-curl-password', '--config=' + JSON.stringify({ token: literalSecrets[0], city: 'Paris' }), '--token=' + literalSecrets[2], '-H', 'Authorization: Bearer ' + literalSecrets[3], '--proxy-header', 'Proxy-Authorization: Basic ' + Buffer.from('alice:fixture-basic:password').toString('base64'), '-H', 'X-API-Key: fixture-custom-header-key', '-HCookie: session=fixture-command-cookie', '--data', 'access_token=fixture-form%20argv&city=Paris'], input: JSON.stringify({ credentials: [{ privateKeyPem: literalSecrets[1] }], count: 7 }), env: { CONFIG: config, FORM: 'password=fixture-form%2Fenv&days=7', WEBHOOK_URL: 'https://host/hooks/fixture-raw%20token?token=fixture-raw-query#access_token=fixture-raw-fragment' } } };
h.sourceEnabled = false;
h.snapshot.items = [
{ view: { id: 'task', name: text, category: 'automations', selected, enabled: false }, automation: { sourceId: 'task', fingerprint: 'fixture', original,
diff --git a/apps/desktop/src/main/bot-import/connectionCatalog.ts b/apps/desktop/src/main/bot-import/connectionCatalog.ts
index 604973dffa..72ce086b40 100644
--- a/apps/desktop/src/main/bot-import/connectionCatalog.ts
+++ b/apps/desktop/src/main/bot-import/connectionCatalog.ts
@@ -15,6 +15,23 @@ const CREDENTIAL_FIELD = /^(?:keys?|.*(?:api|private|signing|encryption|decrypti
export function isImportedCredentialField(name: string): boolean { return CREDENTIAL_FIELD.test(name); }
+function basicCredentialValues(encoded: string): string[] {
+ // Buffer's decoder ignores invalid characters and padding. Accept only a
+ // canonical standard-base64 payload (with or without its complete padding).
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return [];
+ const bytes = Buffer.from(encoded, 'base64');
+ const canonical = bytes.toString('base64');
+ if (encoded !== canonical && encoded !== canonical.replace(/=+$/, '')) return [];
+ // Preserve UTF-8 text and legacy single-byte Basic credentials without
+ // producing replacement characters that were never part of the password.
+ const utf8 = bytes.toString('utf8');
+ const userinfo = Buffer.from(utf8, 'utf8').equals(bytes) ? utf8 : bytes.toString('latin1');
+ const separator = userinfo.indexOf(':');
+ if (separator < 0 || userinfo.length === 1) return [];
+ const password = userinfo.slice(separator + 1);
+ return password ? [userinfo, password] : [userinfo];
+}
+
/** Shared transport-header decomposition for MCP and imported commands. Cookie
* names are application-defined, so every nonempty cookie value stays private. */
export function headerCredentialValues(name: string, value: string): string[] {
@@ -25,6 +42,7 @@ export function headerCredentialValues(name: string, value: string): string[] {
if (authorization) {
const credential = /^\S+\s+(.+)$/.exec(payload)?.[1];
if (credential) values.push(credential);
+ if (credential && /^Basic[\t ]/i.test(payload)) values.push(...basicCredentialValues(credential));
}
if (/^cookie$/i.test(header)) for (const part of payload.split(';')) {
const separator = part.indexOf('=');