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): validate shared authorization owners before credential commit

zqchrisf9ee4a0bffce
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
index 90222e82db..9ec70b0136 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
@@ -753,7 +753,7 @@ describe('missingAuthScopes(快照推断)', () => {
});
describe('connectAccount', () => {
- it('does not commit OAuth tokens when the card is invalidated during identity lookup', async () => {
+ it.each(['boundary', 'policy'] as const)('does not commit OAuth tokens when %s becomes invalid during identity lookup', async (reason) => {
const vault = memoryVault({ [`${KEY}-client-id`]: 'cid' });
const before = new Map(vault.data);
let current = true;
@@ -767,7 +767,8 @@ describe('connectAccount', () => {
}) as typeof fetch,
});
await expect(mgr.connectAccount(GHOST, KEY, DECL, {
- assertCurrent: () => { if (!current) throw new Error('card withdrawn'); },
+ assertCurrent: () => { if (reason === 'boundary' && !current) throw new Error('card withdrawn'); },
+ beforeCommit: async () => { if (reason === 'policy' && !current) throw new Error('card withdrawn'); },
})).rejects.toThrow('card withdrawn');
expect(vault.data).toEqual(before);
expect(mgr.listAccounts(GHOST, KEY)).toHaveLength(0);
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
index 2ff243174d..a16119eee4 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
@@ -875,6 +875,7 @@ export class GhostOauthAccountManager {
onAuthorizationUrl?: (url: string) => void;
/** Main-only caller boundary, checked inside the credential mutation lock. */
assertCurrent?: () => void;
+ beforeCommit?: () => Promise<void>;
},
): Promise<GhostOauthConnectResult> {
if (decl.tokenBroker !== undefined && !this.isTokenBrokerAuthorized(ghostId)) {
@@ -974,6 +975,7 @@ export class GhostOauthAccountManager {
}
return this.withMutationLock(ghostId, async () => {
+ await opts?.beforeCommit?.();
opts?.assertCurrent?.();
// Identity/avatar fetches are asynchronous as well. Recheck inside the
// same strict mutation lock as the first vault read/write so a package
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 23fbe1d764..6a603af345 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -4978,6 +4978,7 @@ export async function executeGhostSetupAction(args: {
responseTarget?: GhostSetupInteractionResponseTarget;
onAuthorizationUrl?: (url: string) => void;
assertCurrent?: () => void;
+ beforeCommit?: () => Promise<void>;
}): Promise<GhostSetupActionResult> {
const ghost = findAvailableGhost(args.ghostId);
if (!ghost) {
@@ -5014,7 +5015,7 @@ export async function executeGhostSetupAction(args: {
args.ghostId,
secretKey,
decl,
- { deliveryHosts: runtimeManifest.network?.hosts, onAuthorizationUrl: args.onAuthorizationUrl, assertCurrent: args.assertCurrent },
+ { deliveryHosts: runtimeManifest.network?.hosts, onAuthorizationUrl: args.onAuthorizationUrl, assertCurrent: args.assertCurrent, beforeCommit: args.beforeCommit },
);
return connected.ok
? { ok: true }
diff --git a/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts
index 0a4ceaa023..dc0bae1e99 100644
--- a/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts
@@ -347,7 +347,7 @@ describe('recoverGrokAuthAfterRejection', () => {
});
});
-it('preserves credentials when the authorizing card is withdrawn during token exchange', async () => {
+it.each(['boundary', 'policy'] as const)('preserves credentials when %s becomes invalid during token exchange', async (reason) => {
seedCredentials();
const before = store.get(SECRET_ID);
const generation = getGrokOAuthCredentialGeneration();
@@ -362,7 +362,8 @@ it('preserves credentials when the authorizing card is withdrawn during token ex
return tokenResponse(200, {});
}));
const result = await runGrokOAuthLogin({
- assertCurrent: () => { if (!current) throw new Error('card withdrawn'); },
+ assertCurrent: () => { if (reason === 'boundary' && !current) throw new Error('card withdrawn'); },
+ beforeCommit: async () => { if (reason === 'policy' && !current) throw new Error('card withdrawn'); },
});
expect(result).toMatchObject({ ok: false, reason: 'card withdrawn' });
expect(store.get(SECRET_ID)).toBe(before);
diff --git a/apps/desktop/src/main/maker-host/grok-oauth-login.ts b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
index 188708a7d8..b1f4a39734 100644
--- a/apps/desktop/src/main/maker-host/grok-oauth-login.ts
+++ b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
@@ -511,6 +511,7 @@ export async function runGrokOAuthLogin(opts?: {
onAuthorizationUrl?: (url: string) => void;
/** Main-only caller boundary, rechecked after token exchange before persistence. */
assertCurrent?: () => void;
+ beforeCommit?: () => Promise<void>;
}): Promise<GrokOAuthLoginResult> {
cancelGrokOAuthLogin(); // 同一时刻只允许一个登录流
@@ -588,6 +589,7 @@ export async function runGrokOAuthLogin(opts?: {
// token exchange 的 fetch 带 signal,但 res.json() / nonce 校验期间到达的 abort
// 不会中断已 resolve 的响应体 —— 落盘前最后检查,保证"已取消"的登录绝不写凭证。
+ await opts?.beforeCommit?.();
if (abort.signal.aborted) throw new Error('login_cancelled');
opts?.assertCurrent?.();
writeBlob(blobFromTokenResponse(tok));
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts
index 53113bfbca..c06fb23c54 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
BotAuthorizationService,
+ resolveBotAuthorizationDelivery,
buildBotAuthorizationContinuation,
commitBotAuthorizationInput,
type BotAuthorizationAdapter,
@@ -677,3 +678,56 @@ it('reassesses after saving the subscribed card when readiness changed before su
expect(h.card().snapshot.terminal).toBe(true);
await h.service.dispose();
});
+
+it.each(['first-cancelled', 'all-cancelled', 'all-policy-revoked'] as const)(
+ 'validates every shared OAuth participant at commit (%s)', async (scenario) => {
+ const h = harness();
+ let finish!: () => void;
+ const committed = vi.fn();
+ h.adapter.execute = vi.fn(async (_action, _sender, _value, _url, assertCurrent, beforeCommit) => {
+ await new Promise<void>((resolve) => { finish = resolve; });
+ await beforeCommit?.();
+ assertCurrent?.();
+ committed();
+ h.complete();
+ return { ok: true as const };
+ });
+ const a = await h.service.request('a', { kind: 'plugin', id: 'p' });
+ const b = await h.service.request('b', { kind: 'plugin', id: 'p' });
+ if (a.ok || b.ok) throw new Error('cards expected');
+ for (const requestId of [a.requestId, b.requestId]) {
+ await h.service.resolve(requestId, { kind: 'plugin_setup', action: 'run_action', actionId: 'connect',
+ expectedRevision: h.stored.get(requestId)!.snapshot.revision }, h.sender);
+ await flush();
+ }
+ expect(h.adapter.execute).toHaveBeenCalledTimes(1);
+ if (scenario === 'all-policy-revoked') {
+ h.deps.adapter.mockRejectedValue(new Error('teammate paused or plugin revoked'));
+ } else {
+ const ids = scenario === 'all-cancelled' ? [a.requestId, b.requestId] : [a.requestId];
+ for (const requestId of ids) await h.service.resolve(requestId, {
+ kind: 'plugin_setup', action: 'cancel', expectedRevision: h.stored.get(requestId)!.snapshot.revision,
+ });
+ }
+ finish();
+ await flush();
+ expect(committed).toHaveBeenCalledTimes(scenario === 'first-cancelled' ? 1 : 0);
+ if (scenario === 'first-cancelled') {
+ expect(h.deps.resume).toHaveBeenCalledTimes(1);
+ expect(h.deps.resume.mock.calls[0][0].sessionId).toBe('b');
+ }
+ await h.service.dispose();
+ },
+);
+
+it('retries hidden continuation rows with a stable unused id and only acknowledges visible rows', async () => {
+ const rows = new Map([
+ ['resume', { id: 'old', createdAt: 10, rewindAt: 20 as number | null, clearedAt: null as number | null }],
+ ]);
+ const read = async (id: string) => rows.get(id) ?? null;
+ expect(await resolveBotAuthorizationDelivery('resume', read)).toEqual({ clientId: 'resume:retry:old', delivered: false });
+ rows.set('resume:retry:old', { id: 'new', createdAt: 30, rewindAt: null, clearedAt: null });
+ expect(await resolveBotAuthorizationDelivery('resume', read)).toEqual({ clientId: 'resume:retry:old', delivered: true });
+ rows.get('resume:retry:old')!.clearedAt = 40;
+ expect(await resolveBotAuthorizationDelivery('resume', read)).toEqual({ clientId: 'resume:retry:new', delivered: false });
+});
diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
index 09ed2544d2..19b4cd7264 100644
--- a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
@@ -156,11 +156,11 @@ export function initializeBotAuthorizationHost(
};
},
subscribe: (wake) => bus.subscribe('host:grok', wake),
- async execute(_action, _sender, _value, onAuthorizationUrl, assertCurrent) {
+ async execute(_action, _sender, _value, onAuthorizationUrl, assertCurrent, beforeCommit) {
await assertSession(sessionId);
assertCurrent?.();
- const result = await runGrokOAuthLogin({ onAuthorizationUrl, assertCurrent });
- await assertSession(sessionId);
+ const result = await runGrokOAuthLogin({ onAuthorizationUrl, assertCurrent, beforeCommit });
+ assertCurrent?.();
if (result.ok) {
bus.emit('host:grok', { source: 'oauth' });
return { ok: true as const };
@@ -225,7 +225,7 @@ export function initializeBotAuthorizationHost(
if (event.source === 'oauth') reconnected = true;
wake();
}),
- async execute(action, sender, value, onAuthorizationUrl, assertCurrent) {
+ async execute(action, sender, value, onAuthorizationUrl, assertCurrent, beforeCommit) {
await validate();
assertCurrent?.();
const release = acquireGhostMutationLeaseForMcp(captureGhostMutationOwnerForMcp());
@@ -246,6 +246,7 @@ export function initializeBotAuthorizationHost(
responseTarget: sender,
onAuthorizationUrl,
assertCurrent,
+ beforeCommit,
});
if (result.ok && action.kind === 'oauth_connect') reconnected = true;
return result;
diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts
index f16e47c6ce..49d62f8046 100644
--- a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts
@@ -29,6 +29,22 @@ export function buildBotAuthorizationContinuation(card: BotAuthorizationCard) {
};
}
+/** Rewound/cleared deliveries do not acknowledge a still-visible card. A new
+ * deterministic id avoids both the message unique key and the queue's old id. */
+export async function resolveBotAuthorizationDelivery(
+ baseId: string,
+ read: (clientId: string) => Promise<{ id: string; createdAt: number; rewindAt: number | null; clearedAt: number | null } | null>,
+): Promise<{ clientId: string; delivered: boolean }> {
+ let clientId = baseId;
+ while (true) {
+ const row = await read(clientId);
+ if (!row) return { clientId, delivered: false };
+ if (row.rewindAt === null && (row.clearedAt === null || row.createdAt > row.clearedAt))
+ return { clientId, delivered: true };
+ clientId = `${baseId}:retry:${row.id}`;
+ }
+}
+
export interface BotAuthorizationInputGuard {
validate(): Promise<void>;
assertCurrent(): void;
@@ -55,6 +71,7 @@ export interface BotAuthorizationAdapter {
value?: string,
onAuthorizationUrl?: (url: string) => void,
assertCurrent?: () => void,
+ beforeCommit?: () => Promise<void>,
): Promise<GhostSetupActionResult>;
}
export interface BotAuthorizationDeps {
@@ -100,6 +117,7 @@ export class BotAuthorizationService {
promise: Promise<GhostSetupActionResult>;
url?: string;
listeners: Set<(url: string) => void>;
+ participants: Map<(url: string) => void, { assertCurrent: () => void; validate: () => Promise<void> }>;
}
>();
private restoring = new Map<string, Promise<Entry | null>>();
@@ -406,6 +424,14 @@ export class BotAuthorizationService {
): Promise<GhostSetupActionResult> {
assertCurrent();
if (action.kind !== 'oauth_connect') return entry.adapter.execute(action, sender, value, onUrl, assertCurrent);
+ const participant = {
+ assertCurrent,
+ validate: async () => {
+ await this.deps.adapter(entry.card.sessionId, entry.card.target);
+ if (!(await this.isVisible(entry))) throw new Error('Authorization card is no longer visible');
+ assertCurrent();
+ },
+ };
const key = `${entry.card.target.kind}:${entry.card.target.id}:${action.id}`;
let flight = this.oauthFlights.get(key);
if (!flight) {
@@ -413,25 +439,43 @@ export class BotAuthorizationService {
const next = {
promise: Promise.resolve({ ok: true } as GhostSetupActionResult),
listeners,
+ participants: new Map([[onUrl, participant]]),
url: undefined as string | undefined,
};
// Install the flight before execute() can report its browser handoff.
this.oauthFlights.set(key, next);
+ let validated: Set<typeof participant> | null = null;
+ const assertAnyCurrent = () => {
+ for (const candidate of validated ?? next.participants.values()) {
+ if (![...next.participants.values()].includes(candidate)) continue;
+ try { candidate.assertCurrent(); return; } catch { /* another card may still own the flow */ }
+ }
+ throw new Error('No active authorization card remains');
+ };
+ const beforeCommit = async () => {
+ validated = new Set();
+ for (const candidate of next.participants.values()) {
+ try { await candidate.validate(); validated.add(candidate); } catch { /* validate every remaining owner */ }
+ }
+ assertAnyCurrent();
+ };
next.promise = entry.adapter
.execute(action, sender, value, (url) => {
next.url = url;
for (const listener of next.listeners) listener(url);
- }, assertCurrent)
+ }, assertAnyCurrent, beforeCommit)
.finally(() => this.oauthFlights.delete(key));
flight = next;
} else {
flight.listeners.add(onUrl);
+ flight.participants.set(onUrl, participant);
if (flight.url) onUrl(flight.url);
}
try {
return await flight.promise;
} finally {
flight.listeners.delete(onUrl);
+ flight.participants.delete(onUrl);
}
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 46ddc0d484..b1c3af23e6 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1,5 +1,5 @@
import { initializeBotAuthorizationHost } from './botAuthorizationHost.js';
-import { buildBotAuthorizationContinuation, commitBotAuthorizationInput, type BotAuthorizationInputGuard, getBotAuthorizationService } from './botAuthorizationService.js';
+import { resolveBotAuthorizationDelivery, buildBotAuthorizationContinuation, commitBotAuthorizationInput, type BotAuthorizationInputGuard, getBotAuthorizationService } from './botAuthorizationService.js';
import { registerSessionSetModelHandler } from './sessionSetModelHandler.js';
import { projectRemoteBotDelegations } from './remoteBotDelegations.js';
/**
@@ -8926,7 +8926,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
onAccepted?: () => void | Promise<void>;
onAcceptedRollback?: () => void | Promise<void>;
}) => {
- if (params.clientId) {
+ if (params.clientId && params.authorizationGuard) {
+ const delivery = await resolveBotAuthorizationDelivery(params.clientId, async (clientId) => {
+ const [row] = await getDbClient().drizzle
+ .select({ id: messages.id, createdAt: messages.createdAt, rewindAt: messages.rewindAt, clearedAt: sessions.clearedAt })
+ .from(messages).innerJoin(sessions, eq(sessions.id, messages.sessionId))
+ .where(and(eq(messages.sessionId, params.targetSessionId), eq(messages.clientId, clientId)))
+ .limit(1);
+ return row ?? null;
+ });
+ params = { ...params, clientId: delivery.clientId };
+ if (delivery.delivered) {
+ await params.authorizationGuard!.validate();
+ params.authorizationGuard!.assertCurrent();
+ await params.onAccepted?.();
+ return { ok: true as const, targetSessionId: params.targetSessionId, wakeKind: 'already-active' as const };
+ }
+ } else if (params.clientId) {
const [persisted] = await getDbClient()
.drizzle.select({ id: messages.id })
.from(messages)