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(bots): preserve local authorization credential links

zqchrisf93cfcb9f7fc
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts
index a21cc8abbb..d4e1bd7b42 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts
@@ -10,6 +10,7 @@ import {
parseGhostSetupInteractionCommand,
projectInteractionRequestForRemote,
projectPendingInteractionsForRemote,
+ sanitizeGhostSetupSnapshotForDesktop,
sanitizeGhostSetupRequestForRemote,
sanitizeGhostSetupSnapshotForRemote,
type GhostSetupInteractionSnapshot,
@@ -281,7 +282,18 @@ describe('sanitizeGhostSetupSnapshotForRemote', () => {
],
};
- const remote = sanitizeGhostSetupSnapshotForRemote(local);
+ const desktop = sanitizeGhostSetupSnapshotForDesktop(local);
+ expect(desktop.steps[0].action).toMatchObject({
+ form: { fields: [{ externalLink: { url: 'https://desktop-only.example/keys' } }] },
+ });
+ expect(desktop.steps[0]).not.toHaveProperty('errorMessage');
+ for (const url of ['http://unsafe.example/keys', 'https://user:[email protected]/keys', 'javascript:alert(1)']) {
+ const unsafe = structuredClone(local);
+ if (unsafe.steps[0].action?.kind === 'inline_form')
+ unsafe.steps[0].action.form.fields[0].externalLink = { url };
+ expect(JSON.stringify(sanitizeGhostSetupSnapshotForDesktop(unsafe))).not.toContain('externalLink');
+ }
+ const remote = sanitizeGhostSetupSnapshotForRemote(desktop);
expect(remote).not.toBe(local);
expect(remote.steps[0]).toMatchObject({
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
index 0075d93042..976a17e910 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
@@ -1,3 +1,4 @@
+import { readBotAuthorizationCard } from '../../shared/botAuthorization.js';
/**
* Desktop interaction bridge for Host-owned plugin setup cards.
*
@@ -282,6 +283,36 @@ export class GhostSetupInteractionBridge {
}
}
+/** Persist only presentation fields, plus validated Desktop credential-page links. */
+export function sanitizeGhostSetupSnapshotForDesktop(
+ snapshot: GhostSetupInteractionSnapshot,
+): GhostSetupInteractionSnapshot {
+ const safe = sanitizeGhostSetupSnapshotForRemote(snapshot);
+ safe.steps.forEach((step, index) => {
+ const source = snapshot.steps[index].action;
+ if (step.action?.kind !== 'inline_form' || source?.kind !== 'inline_form') return;
+ const url = source.form.fields[0].externalLink?.url;
+ if (!url || url.length > 200) return;
+ try {
+ const parsed = new URL(url);
+ if (parsed.protocol === 'https:' && !parsed.username && !parsed.password)
+ step.action.form.fields[0].externalLink = { url };
+ } catch { /* omit invalid credential-page links */ }
+ });
+ return safe;
+}
+
+/** Local durable cards retain Desktop helpers; every remote message path strips them. */
+export function sanitizeBotAuthorizationMetaForRemote(meta: Record<string, unknown>): Record<string, unknown> {
+ if (!('botAuthorization' in meta)) return meta;
+ const { botAuthorization: raw, ...rest } = meta;
+ const card = readBotAuthorizationCard(raw);
+ return card ? {
+ ...rest,
+ botAuthorization: { ...card, snapshot: sanitizeGhostSetupSnapshotForRemote(card.snapshot) },
+ } : rest;
+}
+
/**
* Device-link only projection of a Host-owned setup snapshot.
*
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
index 0654a72309..8f47642010 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
@@ -80,6 +80,30 @@ beforeEach(() => {
__testing.reset();
});
+it('strips Desktop credential links from authorization history and live metadata pushes', () => {
+ const card = { v: 1, sessionId: 's1', createdAt: 1, target: { kind: 'plugin', id: 'p' },
+ snapshot: { kind: 'plugin_setup', requestId: 'r', revision: 1, ghost: { id: 'p', name: 'Plugin' },
+ steps: [{ id: 'step', groupId: 'group', groupMode: 'any_of', title: 'Key', description: '', phase: 'pending',
+ action: { id: 'inline', kind: 'inline_form', form: { fields: [{ id: 'value', type: 'secret', label: 'Key',
+ required: true, maxLength: 4096, externalLink: { url: 'https://example.com/keys' } }] } } }] } };
+ const row = { id: 'm', clientId: 'm', sessionId: 's1', role: 'assistant', content: 'Configure key', agentMeta: { botAuthorization: card } };
+ subscriptions.subscribe('mobile', ['session:s1'], 'mobile', []);
+ const client = mkClient();
+ __testing.setActiveClient(client as never);
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', message: row });
+ const push = client.sendPush.mock.calls.find((c) => c[1] === 'local-db:messages:created')![2];
+ expect(push.message.agentMeta.botAuthorization.snapshot.steps[0].action.kind).toBe('inline_form');
+ expect(JSON.stringify(push)).not.toContain('externalLink');
+ for (const channel of ['local-db:messages:list', 'local-db:messages:around']) {
+ __testing.sendInvokeResultSafe(client as never, 'mobile', channel, { ok: true, result: [row] }, channel);
+ }
+ for (const call of client.sendInvokeResult.mock.calls) {
+ expect(call[2].result[0].agentMeta.botAuthorization).toBeDefined();
+ expect(JSON.stringify(call[2])).not.toContain('externalLink');
+ }
+ expect(row.agentMeta.botAuthorization.snapshot.steps[0].action.form.fields[0].externalLink.url).toBe('https://example.com/keys');
+});
+
describe('negotiated mobile tool projection', () => {
const input = { command: 'echo ' + 'x'.repeat(40_000) };
const row = { id: 'row', clientId: 'persist', sessionId: 's1', role: 'tool_use',
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index c35f926aac..7c07d1d2c9 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -95,6 +95,7 @@ import { LEGACY_TOPIC, type ActiveController } from './subscriptions';
import { MAKER_PUSH } from '../maker-ipc/channels.js';
import { RECOVERY_CHECKPOINT_MARKER } from '../maker-ipc/recoveryCoordinator.js';
import {
+ sanitizeBotAuthorizationMetaForRemote,
projectInteractionDismissedForRemote,
projectInteractionRequestForRemote,
} from '../cindy-brain/ghostSetupInteractionBridge.js';
@@ -1594,7 +1595,7 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
) {
const msg = (payload as { message: unknown }).message;
if (msg && typeof msg === 'object' && !Array.isArray(msg)) {
- const sanitized = stripRecoveryCheckpointFromMessage(msg as Record<string, unknown>);
+ const sanitized = sanitizeRemoteMessage(msg as Record<string, unknown>);
if (sanitized !== msg) {
remotePayload = { ...payload, message: sanitized };
}
@@ -2586,7 +2587,7 @@ function sanitizeMessageInvokeResult(
let changed = false;
const sanitized = result.result.map((msg: unknown) => {
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return msg;
- const out = stripRecoveryCheckpointFromMessage(msg as Record<string, unknown>);
+ const out = sanitizeRemoteMessage(msg as Record<string, unknown>);
if (out !== msg) changed = true;
return out;
});
@@ -2999,7 +3000,7 @@ function compactRemoteMessageForDeviceLink(message: unknown): unknown {
if (record.role === 'tool_use') {
const compactContent = compactRemoteToolUseContent(record.content, false);
if (compactContent === record.content) {
- return stripRecoveryCheckpointFromMessage(record);
+ return sanitizeRemoteMessage(record);
}
return {
...record,
@@ -3012,7 +3013,7 @@ function compactRemoteMessageForDeviceLink(message: unknown): unknown {
: REMOTE_MESSAGE_CONTENT_LIMIT;
const compactContent = compactRemoteMessageContent(record.content, contentLimit);
if (compactContent === record.content) {
- return stripRecoveryCheckpointFromMessage(record);
+ return sanitizeRemoteMessage(record);
}
return {
...record,
@@ -3045,23 +3046,24 @@ function mergeRemoteAgentMeta(agentMeta: unknown, patch: Record<string, unknown>
return { ...patch };
}
const { recoveryCheckpoint: _, ...safe } = agentMeta as Record<string, unknown>;
- return { ...safe, ...patch };
+ return { ...sanitizeBotAuthorizationMetaForRemote(safe), ...patch };
}
-function stripRecoveryCheckpointFromMessage(record: Record<string, unknown>): Record<string, unknown> {
+function sanitizeRemoteMessage(record: Record<string, unknown>): Record<string, unknown> {
const agentMeta = record.agentMeta;
- const hasCheckpointInMeta = agentMeta && typeof agentMeta === 'object' && !Array.isArray(agentMeta) &&
- 'recoveryCheckpoint' in (agentMeta as Record<string, unknown>);
+ const hasPrivateMetadata = agentMeta && typeof agentMeta === 'object' && !Array.isArray(agentMeta) &&
+ ('recoveryCheckpoint' in (agentMeta as Record<string, unknown>) ||
+ 'botAuthorization' in (agentMeta as Record<string, unknown>));
const content = record.content;
const checkpointIdx = typeof content === 'string'
? (content as string).indexOf(RECOVERY_CHECKPOINT_MARKER)
: -1;
const hasCheckpointInContent = checkpointIdx >= 0;
- if (!hasCheckpointInMeta && !hasCheckpointInContent) return record;
+ if (!hasPrivateMetadata && !hasCheckpointInContent) return record;
const result: Record<string, unknown> = { ...record };
- if (hasCheckpointInMeta) {
+ if (hasPrivateMetadata) {
const { recoveryCheckpoint: _, ...safeMeta } = agentMeta as Record<string, unknown>;
- result.agentMeta = safeMeta;
+ result.agentMeta = sanitizeBotAuthorizationMetaForRemote(safeMeta);
}
if (hasCheckpointInContent) {
result.content = (content as string).slice(0, checkpointIdx);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts
index 9b08cf5a28..00a22232d5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts
@@ -3,6 +3,7 @@ import type { BotAuthorizationCard } from '../../../shared/botAuthorization';
import type { initBotAuthorizationService } from '../botAuthorizationService';
const state = vi.hoisted(() => ({
+ save: vi.fn(),
profileStatus: 'active',
login: vi.fn(async () => ({ ok: true })),
continued: vi.fn(),
@@ -28,7 +29,7 @@ vi.mock('../../localDb/client/current.js', () => ({
} } }),
}));
vi.mock('../../localDb/ipc/messages.js', () => ({
- createMessage: vi.fn(), patchMessageAgentMeta: vi.fn(),
+ createMessage: state.save, patchMessageAgentMeta: vi.fn(),
broadcastMessageAgentMetaUpdate: vi.fn(), updateMessageContent: vi.fn(),
}));
vi.mock('../../device-link/broadcast-tap.js', () => ({
@@ -49,7 +50,6 @@ vi.mock('../../cindy-brain/ghostSetupChangeBus.js', () => ({
getGhostSetupChangeBus: () => ({ subscribe: () => () => {}, currentRevision: () => 1 }),
}));
vi.mock('../../cindy-brain/ghostSetupCoordinator.js', () => ({ toReauthInteractionAssessment: () => null }));
-vi.mock('../../cindy-brain/ghostSetupInteractionBridge.js', () => ({ sanitizeGhostSetupSnapshotForRemote: (v: unknown) => v }));
vi.mock('../../maker-host/grok-oauth-login.js', () => ({
getGrokAccessToken: vi.fn(), hasGrokOAuthLogin: () => false, runGrokOAuthLogin: state.login,
getGrokOAuthCredentialGeneration: () => 0, cancelGrokOAuthLogin: vi.fn(),
@@ -60,6 +60,7 @@ const target = { kind: 'plugin' as const, id: 'art' };
describe('authorization Host frozen plugin policy', () => {
beforeEach(() => {
state.policy = JSON.stringify({ toolsets: ['art'] });
+ state.save.mockClear();
state.profileStatus = 'active';
state.login.mockClear();
state.continued.mockClear();
@@ -70,6 +71,18 @@ describe('authorization Host frozen plugin policy', () => {
});
});
+ it('persists the validated credential-page link for the Desktop card', async () => {
+ await state.deps.adapter('session', target);
+ const card: BotAuthorizationCard = { v: 1, sessionId: 'session', target, createdAt: 1,
+ snapshot: { kind: 'plugin_setup', requestId: 'r', revision: 1, ghost: { id: 'art', name: 'Art' },
+ steps: [{ id: 'step', groupId: 'group', groupMode: 'any_of', title: 'Key', description: '', phase: 'pending',
+ action: { id: 'inline', kind: 'inline_form', form: { fields: [{ id: 'value', type: 'secret', label: 'Key',
+ required: true, maxLength: 4096, externalLink: { url: 'https://example.com/keys' } }] } } }] } };
+ await state.deps.save(card);
+ expect(state.save.mock.calls[0][1].agentMeta.botAuthorization.snapshot.steps[0].action.form.fields[0].externalLink)
+ .toEqual({ url: 'https://example.com/keys' });
+ });
+
it.each(['paused', 'archived', 'deleting', 'error'])('rejects old plugin and Host cards when the Profile is %s', async (status) => {
const plugin = await state.deps.adapter('session', target);
const hostTarget = { kind: 'host' as const, id: 'grok' as const };
diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
index ef9e2dde39..a7139fa927 100644
--- a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
@@ -36,7 +36,7 @@ import { toReauthInteractionAssessment } from '../cindy-brain/ghostSetupCoordina
import { initBotAuthorizationService } from './botAuthorizationService.js';
import { readBotAuthorizationCard } from '../../shared/botAuthorization.js';
import type { BotAuthorizationCard } from '../../shared/botAuthorization.js';
-import { sanitizeGhostSetupSnapshotForRemote } from '../cindy-brain/ghostSetupInteractionBridge.js';
+import { sanitizeGhostSetupSnapshotForDesktop } from '../cindy-brain/ghostSetupInteractionBridge.js';
import { createLogger } from '../logger.js';
const log = createLogger('bot-authorization');
@@ -259,7 +259,7 @@ export function initializeBotAuthorizationHost(
card = {
...card,
snapshot: {
- ...sanitizeGhostSetupSnapshotForRemote(card.snapshot),
+ ...sanitizeGhostSetupSnapshotForDesktop(card.snapshot),
...(card.snapshot.reopenActionId ? { reopenActionId: card.snapshot.reopenActionId } : {}),
},
};