Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(companions): reuse import redaction matchers
Chris96093dd11724
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.mdindex d6044cf7c2..aebbd5ea1a 100644--- a/apps/desktop/src/main/bot-import/README.md+++ b/apps/desktop/src/main/bot-import/README.md@@ -200,7 +200,13 @@ omitting it retains normal companion defaults, and a rejected request can be corsecretly copy its expanded value into another selected connection.Public profile/memory/Skill text and routine names/prompts redact all knownsource credentials, including unchecked accounts; memory titles use the same- mask. URL paths use an explicit transport-route allowlist; unknown segments are+ mask. Preview, entry-caption and selected-content traversals compile a local+ matcher once and reuse it for their strings; nested structured-data redaction+ likewise compiles once per traversal. No global credential matcher is retained.+ Repaired manifests adding new credentials refresh the import's matcher before+ publishing recovered content.+ Matching still prefers longer values, bounds short tokens, and never rescans+ replacement labels. URL paths use an explicit transport-route allowlist; unknown segments areprivate regardless of length or case, including encoded forms and subsequentroute-looking values. Named local endpoints are exempt only as single loopbackpaths; explicit credential fields always take precedence. Routine publication happens before createOnce persists the definition,diff --git a/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts b/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.tsindex 5dd4dd726a..253c1668a6 100644--- a/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts@@ -1,9 +1,20 @@import { expect, it } from 'vitest';-import { previewImportRedactions, resolveImportReferences, selectedImportRedactions } from '../environmentSelection.js';+import { previewImportRedactions, resolveImportReferences, retainedImportRedactions, selectedImportRedactions } from '../environmentSelection.js';import { redactEnvironmentValues } from '../process.js';import type { ImportItem } from '../types.js';import { commandArgumentRedactions } from '../commandRedactions.js';+it('retains matched credentials across selected strings and buffers with one matcher', () => {+ let reads = 0;+ const secrets = { get SECRET() { reads++; return 'fixture-selected-secret'; }, UNUSED: 'fixture-unselected-secret' };+ const items: ImportItem[] = [{ view: { id: 'memory', category: 'memory', name: 'fixture-selected-secret', selected: true },+ text: 'Ordinary text', files: [{ name: 'fixture.txt', bytes: Buffer.from('fixture-selected-secret'), executable: false }] }];+ expect(retainedImportRedactions(items, secrets)).toEqual({ SECRET: 'fixture-selected-secret' });+ // One matcher snapshot and one final mask selection, independent of string count.+ expect(reads).toBe(2);+ expect(items[0]!.files![0]!.bytes.toString()).toBe('fixture-selected-secret');+});+it('resolves mixed-case Windows references throughout selected MCP and delivery settings', () => {const env = { api_key: 'fixture-key', Empty: '' };const value = { headers: { Authorization: 'Bearer ${API_KEY}' }, args: ['${Api_Key}', '${EMPTY}'], token: '${api_KEY}', number: 1 };diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.tsindex 3ad2a3c3bd..2deda3b06c 100644--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts@@ -109,6 +109,43 @@ beforeEach(async () => {});afterEach(async () => { vi.restoreAllMocks(); await fs.rm(h.root, { recursive: true, force: true }); });+it('compiles credential matching once for a large preview and preserves all entries', async () => {+ const secret = (index: number) => `fixture-compiled-secret-${index.toString().padStart(5, '0')}`;+ h.snapshot.items = [+ ...Array.from({ length: 2_000 }, (_, index) => ({+ view: { id: `env-${index}`, category: 'connections' as const, selected: true, name: `Account ${index}` },+ env: { [`TOKEN_${index}`]: secret(index) },+ })),+ ...Array.from({ length: 10_000 }, (_, index) => ({+ view: { id: `skill-${index}`, category: 'skills' as const, selected: true,+ name: `Skill ${index} ${secret(index % 2_000)}`, description: `Ordinary description ${secret(1_999)}` },+ })),+ ];+ const [source] = await listCompanionImportSources('fixture');+ let compilations = 0;+ const NativeRegExp = RegExp;+ vi.stubGlobal('RegExp', new Proxy(NativeRegExp, {+ construct(target, args) {+ if (String(args[0]).includes('fixture-compiled-secret-')) {+ compilations += 1;+ // Fail before the regression can allocate thousands of large matchers.+ if (compilations > 1) throw new Error('Repeated preview credential matcher compilation');+ }+ return Reflect.construct(target, args);+ },+ }));+ try {+ const preview = await previewCompanionImport(source!.id, 'fixture');+ expect(compilations).toBe(1);+ expect(preview.entries).toHaveLength(12_000);+ for (const entry of preview.entries.slice(2_000)) {+ expect(entry.name).toMatch(/^Skill \d+ \[preview_credential_\d+\]$/);+ expect(entry.description).toMatch(/^Ordinary description \[preview_credential_\d+\]$/);+ }+ expect(h.snapshot.items[2_000]!.view.name).toBe(`Skill 0 ${secret(0)}`);+ } finally { vi.unstubAllGlobals(); }+}, 10_000);+it('bounds actual receipt writes with long entry names while retaining retryable failures', async () => {const count = 1_000;h.snapshot.items = Array.from({ length: count }, (_, index) => ({@@ -1123,7 +1160,9 @@ it.each([false, true])('keeps the original deferred setup choice across retriesit.each(['hermes', 'openclaw'] as const)('restores disabled %s skill metadata and private settings after an unreadable manifest is repaired', async kind => {const actual = await vi.importActual<typeof import('../sources.js')>('../sources.js');- vi.mocked(createImportSourceReader).mockImplementation(actual.createImportSourceReader);+ // The repaired manifest supplies a new mask during validateItems, after the+ // initial redactor was created; the source-wide scan need not know that mask.+ vi.mocked(createImportSourceReader).mockImplementation((...args) => ({ ...actual.createImportSourceReader(...args), readRedactions: async () => ({}) }));h.snapshot.source.kind = kind;const secret = 'fixture-repaired-skill-secret';const config = { skills: { disabled: ['report'], entries: { 'report-auth': { enabled: false, apiKey: secret, env: { REPORT_REGION: 'fixture' } } } } };@@ -1138,17 +1177,22 @@ it.each(['hermes', 'openclaw'] as const)('restores disabled %s skill metadata anh.snapshot.items = await discoverImportSkills(h.snapshot.source, config, h.root, {}, createImportBudget());expect(h.snapshot.items[0]?.captureIssue).toBe('SOURCE_FILE_TOO_LARGE');const entryId = h.snapshot.items[0]!.view.id;+ h.snapshot.items.push({ view: { id: 'role', name: 'USER.md', category: 'memory', selected: true }, text: `Private value ${secret}`, role: 'user' });+ h.importDocument.mockRejectedValue(new Error('fixture write failure'));const [source] = await listCompanionImportSources('fixture');const preview = await previewCompanionImport(source!.id, 'fixture');- const selection = { requestId: 'fixture-repair-manifest', previewId: preview.id, name: 'Ada', entryIds: [entryId], takeover: false, deferSetup: true };+ const selection = { requestId: 'fixture-repair-manifest', previewId: preview.id, name: 'Ada', entryIds: [entryId, 'role'], takeover: false, deferSetup: true };await startCompanionImport(selection, 'fixture');await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.status).toBe('needs-attention'));const first = (await getCompanionImportResult(selection.requestId))!;- await fs.writeFile(manifest, `---\nname: report\ndescription: Recovered report\nmetadata:\n openclaw:\n skillKey: report-auth\n primaryEnv: REPORT_TOKEN\n---\n# Report\nPrivate value ${secret}`);+ await fs.writeFile(manifest, `---\nname: report\ndescription: Recovered report ${secret}\nmetadata:\n openclaw:\n skillKey: report-auth\n primaryEnv: REPORT_TOKEN\n---\n# Report\nPrivate value ${secret}`);+ h.importDocument.mockResolvedValue(undefined);await startCompanionImport(selection, 'reconnected');await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.status).toBe('complete'));const result = (await getCompanionImportResult(selection.requestId))!;- expect(result).toMatchObject({ botId: first.botId, savedEntryIds: [entryId] });+ expect(result).toMatchObject({ botId: first.botId, savedEntryIds: [entryId, 'role'] });+ expect(h.importDocument.mock.lastCall?.[3]).toMatch(/^Private value \[[^\]]+\]$/);+ expect(h.profile.userContextSource).toMatch(/^Private value \[[^\]]+\]$/);const environment = (await h.store.read(h.root, first.botId, () => {}))!;expect(environment.env).toMatchObject({ REPORT_TOKEN: secret, REPORT_REGION: 'fixture' });const readable = await fs.readFile(path.join(h.root, 'bots', first.botId, 'disabled-skills', 'report', 'SKILL.md'), 'utf8');@@ -1156,6 +1200,8 @@ it.each(['hermes', 'openclaw'] as const)('restores disabled %s skill metadata anexpect(readable).not.toContain(secret);await expect(fs.stat(path.join(h.root, 'bots', first.botId, 'skills', 'report'))).rejects.toMatchObject({ code: 'ENOENT' });expect(JSON.stringify(result)).not.toContain(secret);+ const receipt = JSON.parse(await fs.readFile(path.join(h.root, 'companion-imports', `${selection.requestId}.json`), 'utf8'));+ expect(JSON.stringify(receipt.entryNames)).not.toContain(secret);});it.each(['short-legacy-document', `memory-${'a'.repeat(20)}-${'b'.repeat(20)}`])('resumes saved recovered documents with stable storage IDs across lost acknowledgements: %s', async originalId => {diff --git a/apps/desktop/src/main/bot-import/__tests__/process.test.ts b/apps/desktop/src/main/bot-import/__tests__/process.test.tsindex 3cc2909471..532840e4ee 100644--- a/apps/desktop/src/main/bot-import/__tests__/process.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/process.test.ts@@ -1,8 +1,33 @@import { expect, it } from 'vitest';-import { importedProcessEnvironment, redactEnvironmentData, redactEnvironmentValues } from '../process.js';+import { createEnvironmentRedactor, importedProcessEnvironment, redactEnvironmentData, redactEnvironmentValues } from '../process.js';import { previewImportRedactions } from '../environmentSelection.js';import { connectionRedactions, importedContentRedactions, redactImportedResult } from '../connectionCatalog.js';+it('reuses a local matcher without changing longest matches, boundaries, callbacks or replacement text', () => {+ const env = { FIRST: 'overlap-secret', LAST: 'overlap-secret', LONG: 'overlap-secret-extended',+ SPECIAL: 'a.*[private]+?', SHORT: 'us', UNICODE: '密钥', COLLISION: 'LAST', LANG: 'en' };+ const matched: string[] = [];+ const redact = createEnvironmentRedactor(env, value => { matched.push(value); });+ const text = 'overlap-secret-extended overlap-secret a.*[private]+? status us 密钥库 密钥 LAST en';+ const expected = '[LONG] [LAST] [SPECIAL] status [SHORT] 密钥库 [UNICODE] [COLLISION] en';+ expect(redact(text)).toBe(expected);+ expect(redact('ordinary words')).toBe('ordinary words');+ expect(redact(text)).toBe(expected);+ expect(matched).toEqual(Array(2).fill(['overlap-secret-extended', 'overlap-secret', 'a.*[private]+?', 'us', '密钥', 'LAST']).flat());+ expect(createEnvironmentRedactor({ OTHER: 'overlap-secret' })('overlap-secret')).toBe('[OTHER]');+ expect(createEnvironmentRedactor({ LANG: 'en', EMPTY: '' })('en ordinary words')).toBe('en ordinary words');+ expect(env.LAST).toBe('overlap-secret');+});++it('reads credentials once while traversing nested keys and values', () => {+ let reads = 0;+ const env = { get API_KEY() { reads++; return 'fixture-private-value'; } };+ const value = { 'fixture-private-value': ['fixture-private-value', { text: 'fixture-private-value', count: 7, enabled: false }] };+ expect(redactEnvironmentData(value, env)).toEqual({ '[API_KEY]': ['[API_KEY]', { text: '[API_KEY]', count: 7, enabled: false }] });+ expect(reads).toBe(1);+ expect(value['fixture-private-value'][0]).toBe('fixture-private-value');+});+it.each(['json', 'command-env'])('limits structured URL decomposition to command env, preserving provider paths (%s)', format => {const masks = importedContentRedactions({ env: {}, mcp: [], credentials: [{ id: 'fixture', format,value: { base_url: 'https://model.example/codex', api_key: 'fixture-private-key' } }] });diff --git a/apps/desktop/src/main/bot-import/environmentSelection.ts b/apps/desktop/src/main/bot-import/environmentSelection.tsindex d8c4974a25..b7a3f49794 100644--- a/apps/desktop/src/main/bot-import/environmentSelection.ts+++ b/apps/desktop/src/main/bot-import/environmentSelection.ts@@ -2,7 +2,7 @@ import { fingerprint } from './files.js';import { commandArgumentRedactions, commandLiteralRedactions } from './commandRedactions.js';import { CompanionImportError, object, type ImportItem } from './types.js';import { importedContentRedactions } from './connectionCatalog.js';-import { environmentRedactions, redactEnvironmentValues } from './process.js';+import { createEnvironmentRedactor, environmentRedactions } from './process.js';const variableName = (name: string, platform = process.platform) => platform === 'win32' ? name.toUpperCase() : name;@@ -57,7 +57,7 @@ export function previewImportRedactions(items: ImportItem[]): Record<string, str/** Retain masks only for values already present in selected content, never discarded accounts. */export function retainedImportRedactions(items: ImportItem[], secrets: Record<string, string>): Record<string, string> {const matched = new Set<string>();- const text = (value: string) => { redactEnvironmentValues(value, secrets, value => { matched.add(value); }); };+ const text = createEnvironmentRedactor(secrets, value => { matched.add(value); });const visit = (value: unknown): void => {if (typeof value === 'string') text(value);else if (Buffer.isBuffer(value)) {diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.tsindex f7da85b455..85b40256f0 100644--- a/apps/desktop/src/main/bot-import/host.ts+++ b/apps/desktop/src/main/bot-import/host.ts@@ -22,7 +22,7 @@ import { importBotSkillFiles, normalizeBotSkillSlug, validateBotSkillFiles } froimport { withBotProfileLocks } from '../maker-ipc/botProfileLock.js';import { getRoutineEngine, routineTools, updateBotRoutineLifecycle } from '../routines/service.js';import { previewImportRedactions, retainedImportRedactions, resolveImportReferences, selectedImportEnvironment, selectedImportRedactions } from './environmentSelection.js';-import { redactEnvironmentValues } from './process.js';+import { createEnvironmentRedactor } from './process.js';import { importedContentRedactions } from './connectionCatalog.js';import { createImportSourceReader, discoverImportSources, inspectImportSource, type SourceReaderDeps } from './sources.js';import { readOpenClawCronDatabase } from './openclawCron.js';@@ -124,7 +124,7 @@ export async function previewCompanionImport(sourceId: string, controller: strinconst id = randomUUID();await retainPreview(id, { owner: scope.scope, controller, value: snapshot, createdAt: Date.now() }, scope.assert);const secrets = previewImportRedactions(snapshot.items);- const redact = (text: string) => redactEnvironmentValues(text, secrets);+ const redact = createEnvironmentRedactor(secrets);return { id, selectionRanges: true, selectionChunks: true, source: { id: sourceId, kind: source.kind, name: redact(source.name) }, name: redact(source.name),...(snapshot.avatarImageBase64 ? { avatarImageBase64: snapshot.avatarImageBase64 } : {}),entries: snapshot.items.map(({ view }) => ({ ...view, name: redact(view.name),@@ -436,7 +436,7 @@ export async function getCompanionImportSetupStatus(botId: string, root: string,...Object.values(importedContentRedactions(environment)), ...Object.values(previewImportRedactions(snapshot.items)),...Object.values(snapshot.publicationRedactions ?? {}),])].map((value, index) => [`setup_credential_${index}`, value]));- receipt.entryNames = setupEntryNames(snapshot.items, text => redactEnvironmentValues(text, secrets));+ receipt.entryNames = setupEntryNames(snapshot.items, createEnvironmentRedactor(secrets));await saveReceipt(root, receipt); assertOwner();}} else requestId = null;@@ -530,7 +530,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,contentSecrets[`content_retry_${nextMask++}`] = value;knownValues.add(value);}- const redactText = (text: string) => redactEnvironmentValues(text, contentSecrets);+ let redactText = createEnvironmentRedactor(contentSecrets);const publicRoutine = (input: RoutineInput): RoutineInput => ({ ...input, name: redactText(input.name), prompt: redactText(input.prompt) });// Resource capture finishes before saveCheckpoint; retain only selected embedded values.const publicationRedactions = (items: ImportSnapshot['items']) => retainedImportRedactions(items, contentSecrets);@@ -597,11 +597,13 @@ export async function startCompanionImport(selection: CompanionImportSelection,assertOwner: scope.assert,async validateItems(items) {// Repaired manifests can reveal credentials that were unavailable at preview time.+ const previousMaskCount = knownValues.size;for (const value of Object.values(selectedImportRedactions(items))) {if (knownValues.has(value)) continue;while (`content_retry_${nextMask}` in contentSecrets) nextMask++;contentSecrets[`content_retry_${nextMask++}`] = value; knownValues.add(value);}+ if (knownValues.size !== previousMaskCount) redactText = createEnvironmentRedactor(contentSecrets);// Capturing lazily selected resources may grow even a rejected selection.const cached = previews.get(selection.previewId);if (cached?.value === snapshot) await retainPreview(selection.previewId, cached, scope.assert, true);diff --git a/apps/desktop/src/main/bot-import/process.ts b/apps/desktop/src/main/bot-import/process.tsindex 3a7b6f98c6..4fc54c4fb1 100644--- a/apps/desktop/src/main/bot-import/process.ts+++ b/apps/desktop/src/main/bot-import/process.ts@@ -92,24 +92,34 @@ export function environmentRedactions(env: Record<string, string>): Record<strinreturn Object.fromEntries(Object.entries(env).filter(([name, value]) => !isPublicImportSetting(name, value) && value.length > 0));}-export function redactEnvironmentValues(text: string, env: Record<string, string>, onMatch?: (value: string) => void): string {+/** Compile once per projection/traversal; keep credential state local to its caller. */+export function createEnvironmentRedactor(env: Record<string, string>, onMatch?: (value: string) => void): (text: string) => string {// Unknown variable names remain private. Short values match whole tokens so// "us" cannot corrupt "status"; exact short credentials are still masked.// Match in one pass so replacements cannot redact each other.const values = new Map(Object.entries(environmentRedactions(env)).map(([name, value]) => [value, `[${name}]`]));- if (!values.size) return text;+ if (!values.size) return text => text;const pattern = [...values.keys()].sort((a, b) => b.length - a.length).map(value => {const literal = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');return value.length < 8 ? `(?<![\\p{L}\\p{N}])${literal}(?![\\p{L}\\p{N}])` : literal;}).join('|');- return text.replace(new RegExp(pattern, 'gu'), value => { onMatch?.(value); return values.get(value)!; });+ const matcher = new RegExp(pattern, 'gu');+ return text => text.replace(matcher, value => { onMatch?.(value); return values.get(value)!; });+}++export function redactEnvironmentValues(text: string, env: Record<string, string>, onMatch?: (value: string) => void): string {+ return createEnvironmentRedactor(env, onMatch)(text);}/** Redact untrusted keys and string values without corrupting JSON numbers or booleans. */export function redactEnvironmentData<T>(value: T, env: Record<string, string>): T {- if (typeof value === 'string') return redactEnvironmentValues(value, env) as T;- if (Array.isArray(value)) return value.map(child => redactEnvironmentData(child, env)) as T;- if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, child]) => [redactEnvironmentValues(key, env), redactEnvironmentData(child, env)])) as T;- return value;+ const redact = createEnvironmentRedactor(env);+ const visit = (child: unknown): unknown => {+ if (typeof child === 'string') return redact(child);+ if (Array.isArray(child)) return child.map(visit);+ if (child && typeof child === 'object') return Object.fromEntries(Object.entries(child).map(([key, nested]) => [redact(key), visit(nested)]));+ return child;+ };+ return visit(value) as T;}