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。

feat(ghost): 插件新增权限后引导用户重新授权 (#1695)

fmfsaisai102d4c6ca4fd
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 6075650101..cbbdcf7d1a 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
@@ -9,6 +9,7 @@ import {
GHOST_OAUTH_INVALID_GRANT_RECHECK_DELAY_MS,
GHOST_OAUTH_MAX_ACCOUNTS,
GhostOauthAccountManager,
+ missingAuthScopes,
type GhostOauthDecl,
type GhostOauthVault,
} from '../ghostOauthAccounts.js';
@@ -26,8 +27,12 @@ const DECL: GhostOauthDecl = {
identity: { url: 'https://api.example.com/userinfo', labelPath: 'email' },
};
-function memoryVault(seed?: Record<string, string>): GhostOauthVault & { data: Map<string, string> } {
- const data = new Map<string, string>(Object.entries(seed ?? {}).map(([k, v]) => [`${GHOST}\u0000${k}`, v]));
+function memoryVault(
+ seed?: Record<string, string>,
+): GhostOauthVault & { data: Map<string, string> } {
+ const data = new Map<string, string>(
+ Object.entries(seed ?? {}).map(([k, v]) => [`${GHOST}\u0000${k}`, v]),
+ );
return {
data,
read: (ghostId, key) => data.get(`${ghostId}\u0000${key}`) ?? null,
@@ -42,7 +47,10 @@ function memoryVault(seed?: Record<string, string>): GhostOauthVault & { data: M
}
function jsonResponse(body: unknown, status = 200): Response {
- return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
}
/** 模拟浏览器:从授权 URL 提取回调地址与 state 并回打 code。 */
@@ -71,6 +79,267 @@ function seededVault(rt = 'rt-seed'): ReturnType<typeof memoryVault> {
});
}
+describe('missingAuthScopes(快照推断)', () => {
+ it.each([
+ ['全量快照没有新增 scope', ['scope.a'], { authFace: 'full', authScopes: ['scope.a'] }, false],
+ [
+ '全量快照存在新增 scope',
+ ['scope.a', 'scope.b'],
+ { authFace: 'full', authScopes: ['scope.a'] },
+ true,
+ ],
+ [
+ '主动降面账号不猜',
+ ['scope.a', 'scope.b'],
+ { authFace: 'subset', authScopes: ['scope.a'] },
+ false,
+ ],
+ ['老账号无快照不猜', ['scope.a', 'scope.b'], {}, false],
+ ['只有 scope 面没有 full 标记不猜', ['scope.a', 'scope.b'], { authScopes: ['scope.a'] }, false],
+ ] as const)('%s', (_name, declScopes, row, expected) => {
+ expect(missingAuthScopes(declScopes, row).length > 0).toBe(expected);
+ });
+
+ it('老清单与非法快照继续宽松读取,不误报陈旧授权', () => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-old',
+ accounts: [
+ { id: 'acc-old', label: '[email protected]', status: 'connected', createdAt: 1 },
+ {
+ id: 'acc-bad',
+ label: '[email protected]',
+ status: 'connected',
+ createdAt: 2,
+ authScopes: ['scope.a', 42],
+ authFace: 'unknown',
+ },
+ ],
+ }),
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+ const expanded = { ...DECL, scopes: ['scope.a', 'scope.b'] };
+
+ expect(mgr.listAccounts(GHOST, KEY, expanded)).toMatchObject([
+ { id: 'acc-old', scopeStale: false },
+ { id: 'acc-bad', scopeStale: false },
+ ]);
+ expect(mgr.defaultMissingScopes(GHOST, KEY, expanded)).toEqual([]);
+ });
+
+ it('老账号无快照但有真实错误证据时触发建议与详情页角标', () => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-old',
+ accounts: [
+ {
+ id: 'acc-old',
+ label: '[email protected]',
+ status: 'connected',
+ createdAt: 1,
+ insufficientScopes: ['scope.b'],
+ },
+ ],
+ }),
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+ const expanded = { ...DECL, scopes: ['scope.a', 'scope.b'] };
+
+ expect(mgr.defaultMissingScopes(GHOST, KEY, expanded)).toEqual(['scope.b']);
+ expect(mgr.listAccounts(GHOST, KEY, expanded)[0]?.scopeStale).toBe(true);
+ });
+
+ it('真实错误证据优先于快照推断;无证据时回退快照', () => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [
+ {
+ id: 'acc-1',
+ label: '[email protected]',
+ status: 'connected',
+ createdAt: 1,
+ authScopes: ['scope.a'],
+ authFace: 'full',
+ insufficientScopes: ['scope.c'],
+ },
+ ],
+ }),
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+ const expanded = { ...DECL, scopes: ['scope.a', 'scope.b', 'scope.c'] };
+
+ expect(mgr.defaultMissingScopes(GHOST, KEY, expanded)).toEqual(['scope.c']);
+ const manifest = JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}');
+ delete manifest.accounts[0].insufficientScopes;
+ vault.store(GHOST, `${KEY}-accounts`, JSON.stringify(manifest));
+ expect(mgr.defaultMissingScopes(GHOST, KEY, expanded)).toEqual(['scope.b', 'scope.c']);
+ });
+
+ it('非法错误证据按 undefined 宽松读取,并回退快照推断', () => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [
+ {
+ id: 'acc-1',
+ label: '[email protected]',
+ status: 'connected',
+ createdAt: 1,
+ authScopes: ['scope.a'],
+ authFace: 'full',
+ insufficientScopes: ['scope.b', 42],
+ },
+ ],
+ }),
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+
+ expect(
+ mgr.defaultMissingScopes(GHOST, KEY, { ...DECL, scopes: ['scope.a', 'scope.b'] }),
+ ).toEqual(['scope.b']);
+ });
+
+ it.each([
+ ['纯空白', [' ']],
+ ['单项超长', ['x'.repeat(257)]],
+ ['条数超限', Array.from({ length: 65 }, (_, index) => `scope.${index}`)],
+ ])('%s 的持久化坏证据对判定惰性(按当前声明过滤,不整包丢弃)', (_name, insufficientScopes) => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [
+ {
+ id: 'acc-1',
+ label: '[email protected]',
+ status: 'connected',
+ createdAt: 1,
+ insufficientScopes,
+ },
+ ],
+ }),
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+
+ expect(mgr.defaultMissingScopes(GHOST, KEY, DECL)).toEqual([]);
+ });
+
+ it('历史证据已不在当前声明时忽略,并回退快照推断', () => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [
+ {
+ id: 'acc-1',
+ label: '[email protected]',
+ status: 'connected',
+ createdAt: 1,
+ authScopes: ['scope.a'],
+ authFace: 'full',
+ insufficientScopes: ['scope.removed'],
+ },
+ ],
+ }),
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+
+ expect(
+ mgr.defaultMissingScopes(GHOST, KEY, { ...DECL, scopes: ['scope.a', 'scope.b'] }),
+ ).toEqual(['scope.b']);
+ });
+
+ it('错误证据只合并到默认账号,重复上报去重', () => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-2',
+ accounts: [
+ { id: 'acc-1', label: '[email protected]', status: 'connected', createdAt: 1 },
+ {
+ id: 'acc-2',
+ label: '[email protected]',
+ status: 'connected',
+ createdAt: 2,
+ insufficientScopes: ['scope.a'],
+ },
+ ],
+ }),
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+
+ const decl = ['scope.a', 'scope.b'];
+ expect(mgr.reportInsufficientScopes(GHOST, KEY, ['scope.a', 'scope.b', 'scope.b'], decl)).toBe(
+ 'stored',
+ );
+ expect(mgr.reportInsufficientScopes(GHOST, KEY, ['scope.b'], decl)).toBe('unchanged');
+ const accounts = JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}').accounts;
+ expect(accounts[0]).not.toHaveProperty('insufficientScopes');
+ expect(accounts[1].insufficientScopes).toEqual(['scope.a', 'scope.b']);
+ expect(
+ new GhostOauthAccountManager({
+ vault: memoryVault(),
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ }).reportInsufficientScopes(GHOST, KEY, ['scope.a'], decl),
+ ).toBe(false);
+ });
+
+ it('合并时按当前声明面裁剪,清单换代后的过期证据被淘汰,条数不越积越多', () => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [
+ {
+ id: 'acc-1',
+ label: '[email protected]',
+ status: 'connected',
+ createdAt: 1,
+ insufficientScopes: ['scope.old', 'scope.b'],
+ },
+ ],
+ }),
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+
+ expect(mgr.reportInsufficientScopes(GHOST, KEY, ['scope.c'], ['scope.b', 'scope.c'])).toBe(
+ 'stored',
+ );
+ const accounts = JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}').accounts;
+ expect(accounts[0].insufficientScopes).toEqual(['scope.b', 'scope.c']);
+ });
+});
+
describe('connectAccount', () => {
it('端口回收器只对第一方官方意识放行(第三方 redirectPort 不许借刀杀进程)', async () => {
const blocker = http.createServer();
@@ -138,13 +407,20 @@ describe('connectAccount', () => {
expect(result.account.label).toBe('[email protected]');
expect(result.account.isDefault).toBe(true);
expect(result.account.status).toBe('connected');
+ expect(result.account.scopeStale).toBe(false);
- const listed = mgr.listAccounts(GHOST, KEY);
+ const listed = mgr.listAccounts(GHOST, KEY, DECL);
expect(listed).toHaveLength(1);
expect(vault.read(GHOST, `${KEY}-rt-${result.account.id}`)).toBe('rt-1');
// 清单里不落任何令牌字节。
expect(vault.read(GHOST, `${KEY}-accounts`)).not.toContain('rt-1');
expect(vault.read(GHOST, `${KEY}-accounts`)).not.toContain('at-1');
+ const persistedAccount = JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}').accounts[0];
+ expect(persistedAccount).toMatchObject({
+ authScopes: ['scope.a'],
+ authFace: 'full',
+ });
+ expect(persistedAccount).not.toHaveProperty('insufficientScopes');
// 授权余温:access token 已进缓存,取用不再走网络。
const fetchCalls = fetchImpl.mock.calls.length;
@@ -159,7 +435,11 @@ describe('connectAccount', () => {
const fetchImpl = vi.fn(async (input: string | URL | Request) => {
const url = String(input);
if (url === DECL.tokenUrl) {
- return jsonResponse({ access_token: 'at-stale', refresh_token: 'rt-stale', expires_in: 3600 });
+ return jsonResponse({
+ access_token: 'at-stale',
+ refresh_token: 'rt-stale',
+ expires_in: 3600,
+ });
}
if (url === DECL.identity?.url) {
return jsonResponse({ email: '[email protected]' });
@@ -187,7 +467,11 @@ describe('connectAccount', () => {
it('声明 avatarPath → 连接时下载头像存库(不带凭证),listAccounts 带 avatarDataUrl,断开清掉', async () => {
const avatarDecl: GhostOauthDecl = {
...DECL,
- identity: { url: 'https://api.example.com/userinfo', labelPath: 'email', avatarPath: 'picture' },
+ identity: {
+ url: 'https://api.example.com/userinfo',
+ labelPath: 'email',
+ avatarPath: 'picture',
+ },
};
const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
const expectedDataUrl = `data:image/png;base64,${pngBytes.toString('base64')}`;
@@ -198,12 +482,18 @@ describe('connectAccount', () => {
return jsonResponse({ access_token: 'at-1', refresh_token: 'rt-1', expires_in: 3600 });
}
if (url === 'https://api.example.com/userinfo') {
- return jsonResponse({ email: '[email protected]', picture: 'https://cdn.example.com/a.png' });
+ return jsonResponse({
+ email: '[email protected]',
+ picture: 'https://cdn.example.com/a.png',
+ });
}
if (url === 'https://cdn.example.com/a.png') {
// 头像下载绝不带 Authorization(CDN 域名不在凭证注入白名单)。
expect(new Headers(init?.headers).get('Authorization')).toBeNull();
- return new Response(new Uint8Array(pngBytes), { status: 200, headers: { 'Content-Type': 'image/png' } });
+ return new Response(new Uint8Array(pngBytes), {
+ status: 200,
+ headers: { 'Content-Type': 'image/png' },
+ });
}
throw new Error(`unexpected fetch ${url}`);
});
@@ -231,7 +521,11 @@ describe('connectAccount', () => {
const avatarDecl: GhostOauthDecl = {
...DECL,
clientId: 'cid-baked',
- identity: { url: 'https://api.example.com/userinfo', labelPath: 'email', avatarPath: 'picture' },
+ identity: {
+ url: 'https://api.example.com/userinfo',
+ labelPath: 'email',
+ avatarPath: 'picture',
+ },
};
const fetchImpl = vi.fn(async (input: string | URL | Request) => {
const url = String(input);
@@ -239,7 +533,10 @@ describe('connectAccount', () => {
return jsonResponse({ access_token: 'at-1', refresh_token: 'rt-1', expires_in: 3600 });
}
if (url === 'https://api.example.com/userinfo') {
- return jsonResponse({ email: '[email protected]', picture: 'https://internal.example/secret.png' });
+ return jsonResponse({
+ email: '[email protected]',
+ picture: 'https://internal.example/secret.png',
+ });
}
throw new Error(`unexpected fetch ${url}`);
});
@@ -253,13 +550,19 @@ describe('connectAccount', () => {
if (!result.ok) return;
expect(result.account.avatarDataUrl).toBeNull();
// 头像地址从未被主机请求过(fetch 只打过 token 与身份端点)。
- expect(fetchImpl.mock.calls.map((c) => String(c[0]))).not.toContain('https://internal.example/secret.png');
+ expect(fetchImpl.mock.calls.map((c) => String(c[0]))).not.toContain(
+ 'https://internal.example/secret.png',
+ );
});
it('头像下载失败 → 连接照常成功,avatarDataUrl 为 null(best-effort)', async () => {
const avatarDecl: GhostOauthDecl = {
...DECL,
- identity: { url: 'https://api.example.com/userinfo', labelPath: 'email', avatarPath: 'picture' },
+ identity: {
+ url: 'https://api.example.com/userinfo',
+ labelPath: 'email',
+ avatarPath: 'picture',
+ },
};
const fetchImpl = vi.fn(async (input: string | URL | Request) => {
const url = String(input);
@@ -267,7 +570,10 @@ describe('connectAccount', () => {
return jsonResponse({ access_token: 'at-1', refresh_token: 'rt-1', expires_in: 3600 });
}
if (url === 'https://api.example.com/userinfo') {
- return jsonResponse({ email: '[email protected]', picture: 'https://cdn.example.com/a.png' });
+ return jsonResponse({
+ email: '[email protected]',
+ picture: 'https://cdn.example.com/a.png',
+ });
}
throw new Error('avatar cdn down');
});
@@ -310,7 +616,11 @@ describe('connectAccount', () => {
});
const fetchImpl = vi.fn(async (input: string | URL | Request) => {
if (String(input) === DECL.tokenUrl) {
- return jsonResponse({ access_token: 'at-full', refresh_token: 'rt-full', expires_in: 3600 });
+ return jsonResponse({
+ access_token: 'at-full',
+ refresh_token: 'rt-full',
+ expires_in: 3600,
+ });
}
return jsonResponse({ email: '[email protected]' });
});
@@ -360,6 +670,10 @@ describe('connectAccount', () => {
const listed = mgr.listAccounts(GHOST, KEY);
expect(listed).toHaveLength(2);
expect(vault.read(GHOST, `${KEY}-rt-acc-1`)).toBe('rt-fresh');
+ expect(JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}').accounts[0]).toMatchObject({
+ authScopes: ['scope.a'],
+ authFace: 'full',
+ });
// 授权余温:合并账号的 access token 已进缓存。
await expect(mgr.getFreshAccessToken(GHOST, KEY, DECL, 'acc-1')).resolves.toMatchObject({
ok: true,
@@ -384,7 +698,11 @@ describe('connectAccount', () => {
});
expect((await mgrNew.connectAccount(GHOST, KEY, DECL)).ok).toBe(true);
expect(onNew).toHaveBeenCalledTimes(1);
- expect(onNew).toHaveBeenCalledWith({ ghostId: GHOST, secretKey: KEY, label: '[email protected]' });
+ expect(onNew).toHaveBeenCalledWith({
+ ghostId: GHOST,
+ secretKey: KEY,
+ label: '[email protected]',
+ });
// 同身份重连(合并):同样触发;钩子抛错不影响 ok 结果
const onMerge = vi.fn(() => {
@@ -557,7 +875,9 @@ describe('getFreshAccessToken', () => {
const onAccountStatusChanged = vi.fn();
const mgr = new GhostOauthAccountManager({
vault,
- fetchImpl: vi.fn(async () => jsonResponse({ error: 'invalid_grant' }, 400)) as unknown as typeof fetch,
+ fetchImpl: vi.fn(async () =>
+ jsonResponse({ error: 'invalid_grant' }, 400),
+ ) as unknown as typeof fetch,
openExternal: vi.fn(),
sleep: instantSleep,
onAccountStatusChanged,
@@ -629,7 +949,9 @@ describe('getFreshAccessToken', () => {
it('瞬时刷新失败 → REFRESH_FAILED,账号不标过期', async () => {
const mgr = new GhostOauthAccountManager({
vault: seededVault(),
- fetchImpl: vi.fn(async () => jsonResponse({ error: 'server_error' }, 500)) as unknown as typeof fetch,
+ fetchImpl: vi.fn(async () =>
+ jsonResponse({ error: 'server_error' }, 500),
+ ) as unknown as typeof fetch,
openExternal: vi.fn(),
});
await expect(mgr.getFreshAccessToken(GHOST, KEY, DECL)).resolves.toMatchObject({
@@ -822,7 +1144,12 @@ describe('多实例共库的 RT 轮换竞态(invalid_grant 防误删)', () => {
expect(params.refreshToken).toBe('rt-winner');
return {
ok: true as const,
- bundle: { accessToken: 'at-bk2', refreshToken: null, expiresAt: Date.now() + 60_000, grantedScope: null },
+ bundle: {
+ accessToken: 'at-bk2',
+ refreshToken: null,
+ expiresAt: Date.now() + 60_000,
+ grantedScope: null,
+ },
};
});
const mgr = new GhostOauthAccountManager({
@@ -947,7 +1274,12 @@ describe('tokenBroker 模式', () => {
const fetchImpl = vi.fn();
const exchange = vi.fn(async () => ({
ok: true as const,
- bundle: { accessToken: 'at-bk', refreshToken: 'rt-bk', expiresAt: Date.now() + 60_000, grantedScope: null },
+ bundle: {
+ accessToken: 'at-bk',
+ refreshToken: 'rt-bk',
+ expiresAt: Date.now() + 60_000,
+ grantedScope: null,
+ },
}));
const mgr = new GhostOauthAccountManager({
vault,
@@ -1075,7 +1407,9 @@ describe('brokerBounce(双地址弹跳回调)', () => {
openExternal: openExternal1,
broker: { exchange: vi.fn(), refresh: vi.fn() },
});
- await expect(mgrNoResolver.connectAccount(GHOST, KEY, bounceDecl(53699))).resolves.toMatchObject({
+ await expect(
+ mgrNoResolver.connectAccount(GHOST, KEY, bounceDecl(53699)),
+ ).resolves.toMatchObject({
ok: false,
error: 'INVALID_CONFIG',
});
@@ -1090,7 +1424,9 @@ describe('brokerBounce(双地址弹跳回调)', () => {
broker: { exchange: vi.fn(), refresh: vi.fn() },
resolveBrokerPublicUrl: vi.fn(() => null),
});
- await expect(mgrNullResolver.connectAccount(GHOST, KEY, bounceDecl(53699))).resolves.toMatchObject({
+ await expect(
+ mgrNullResolver.connectAccount(GHOST, KEY, bounceDecl(53699)),
+ ).resolves.toMatchObject({
ok: false,
error: 'INVALID_CONFIG',
});
@@ -1117,7 +1453,12 @@ describe('brokerBounce(双地址弹跳回调)', () => {
expect(params.redirectUri).toBe(PUBLIC_URI);
return {
ok: true as const,
- bundle: { accessToken: 'at-bb', refreshToken: 'rt-bb', expiresAt: Date.now() + 60_000, grantedScope: null },
+ bundle: {
+ accessToken: 'at-bb',
+ refreshToken: 'rt-bb',
+ expiresAt: Date.now() + 60_000,
+ grantedScope: null,
+ },
};
});
const mgr = new GhostOauthAccountManager({
@@ -1153,8 +1494,9 @@ describe('connectAccount · opts.scopes 收窄', () => {
it('声明子集 → 授权 URL 的 scope 面收窄为子集', async () => {
let capturedScope: string | null = null;
+ const vault = memoryVault();
const mgr = new GhostOauthAccountManager({
- vault: memoryVault(),
+ vault,
fetchImpl: vi.fn(async () =>
jsonResponse({ access_token: 'at-narrow', refresh_token: 'rt-narrow', expires_in: 3600 }),
) as unknown as typeof fetch,
@@ -1167,6 +1509,16 @@ describe('connectAccount · opts.scopes 收窄', () => {
mgr.connectAccount(GHOST, KEY, NARROW_DECL, { scopes: ['read:x'] }),
).resolves.toMatchObject({ ok: true });
expect(capturedScope).toBe('read:x');
+ expect(JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}').accounts[0]).toMatchObject({
+ authScopes: ['read:x'],
+ authFace: 'subset',
+ });
+ expect(
+ mgr.listAccounts(GHOST, KEY, {
+ ...NARROW_DECL,
+ scopes: ['read:x', 'write:y', 'admin:z'],
+ })[0]?.scopeStale,
+ ).toBe(false);
});
it('含未声明条目 / 空数组 → INVALID_CONFIG,不拉浏览器', async () => {
@@ -1214,7 +1566,11 @@ describe('identity.displayTemplate 展示名', () => {
const onConnected = vi.fn();
const mgr = new GhostOauthAccountManager({
vault,
- fetchImpl: slackFetch({ team: 'acme', user: 'devuser', user_id: 'U0EXAMPLE1' }) as unknown as typeof fetch,
+ fetchImpl: slackFetch({
+ team: 'acme',
+ user: 'devuser',
+ user_id: 'U0EXAMPLE1',
+ }) as unknown as typeof fetch,
openExternal: autoBrowser(),
onAccountConnected: onConnected,
});
@@ -1227,9 +1583,16 @@ describe('identity.displayTemplate 展示名', () => {
const manifest = JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}') as {
accounts: Array<{ label: string; displayLabel: string }>;
};
- expect(manifest.accounts[0]).toMatchObject({ label: 'U0EXAMPLE1', displayLabel: 'acme · devuser' });
+ expect(manifest.accounts[0]).toMatchObject({
+ label: 'U0EXAMPLE1',
+ displayLabel: 'acme · devuser',
+ });
// 授权成功提示用展示名。
- expect(onConnected).toHaveBeenCalledWith({ ghostId: GHOST, secretKey: KEY, label: 'acme · devuser' });
+ expect(onConnected).toHaveBeenCalledWith({
+ ghostId: GHOST,
+ secretKey: KEY,
+ label: 'acme · devuser',
+ });
});
it('同身份重连:按稳定键合并到老账号(旧行 label 是 user_id),并补上展示名', async () => {
@@ -1237,13 +1600,25 @@ describe('identity.displayTemplate 展示名', () => {
[`${KEY}-client-id`]: 'cid',
[`${KEY}-accounts`]: JSON.stringify({
defaultAccountId: 'acc-legacy',
- accounts: [{ id: 'acc-legacy', label: 'U0EXAMPLE1', status: 'connected', createdAt: 1 }],
+ accounts: [
+ {
+ id: 'acc-legacy',
+ label: 'U0EXAMPLE1',
+ status: 'connected',
+ createdAt: 1,
+ insufficientScopes: ['scope.a'],
+ },
+ ],
}),
[`${KEY}-rt-acc-legacy`]: 'rt-old',
});
const mgr = new GhostOauthAccountManager({
vault,
- fetchImpl: slackFetch({ team: 'acme', user: 'devuser', user_id: 'U0EXAMPLE1' }) as unknown as typeof fetch,
+ fetchImpl: slackFetch({
+ team: 'acme',
+ user: 'devuser',
+ user_id: 'U0EXAMPLE1',
+ }) as unknown as typeof fetch,
openExternal: autoBrowser(),
});
const result = await mgr.connectAccount(GHOST, KEY, SLACK_DECL);
@@ -1253,6 +1628,52 @@ describe('identity.displayTemplate 展示名', () => {
expect(result.account.id).toBe('acc-legacy');
expect(result.account.label).toBe('acme · devuser');
expect(mgr.listAccounts(GHOST, KEY)).toHaveLength(1);
+ expect(JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}').accounts[0]).not.toHaveProperty(
+ 'insufficientScopes',
+ );
+ expect(mgr.defaultMissingScopes(GHOST, KEY, SLACK_DECL)).toEqual([]);
+ });
+
+ it('同身份重连清除证据时账号清单写失败,返回 VAULT_WRITE_FAILED 而不假报成功', async () => {
+ const baseVault = memoryVault({
+ [`${KEY}-client-id`]: 'cid',
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-legacy',
+ accounts: [
+ {
+ id: 'acc-legacy',
+ label: 'U0EXAMPLE1',
+ status: 'connected',
+ createdAt: 1,
+ insufficientScopes: ['scope.a'],
+ },
+ ],
+ }),
+ [`${KEY}-rt-acc-legacy`]: 'rt-old',
+ });
+ const vault: GhostOauthVault = {
+ read: baseVault.read,
+ remove: baseVault.remove,
+ store: (ghostId, storageKey, value) =>
+ storageKey === `${KEY}-accounts` ? false : baseVault.store(ghostId, storageKey, value),
+ };
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: slackFetch({
+ team: 'acme',
+ user: 'devuser',
+ user_id: 'U0EXAMPLE1',
+ }) as unknown as typeof fetch,
+ openExternal: autoBrowser(),
+ });
+
+ await expect(mgr.connectAccount(GHOST, KEY, SLACK_DECL)).resolves.toMatchObject({
+ ok: false,
+ error: 'VAULT_WRITE_FAILED',
+ });
+ expect(JSON.parse(baseVault.read(GHOST, `${KEY}-accounts`) ?? '{}').accounts[0]).toMatchObject({
+ insufficientScopes: ['scope.a'],
+ });
});
it('模板占位符取不到值 → 展示名降级,view.label 回落稳定身份键', async () => {
@@ -1278,10 +1699,16 @@ describe('identity.displayTemplate 展示名', () => {
});
const mgr = new GhostOauthAccountManager({
vault,
- fetchImpl: slackFetch({ team: 'acme', user: 'devuser', user_id: 'U0EXAMPLE1' }) as unknown as typeof fetch,
+ fetchImpl: slackFetch({
+ team: 'acme',
+ user: 'devuser',
+ user_id: 'U0EXAMPLE1',
+ }) as unknown as typeof fetch,
openExternal: vi.fn(),
});
- await expect(mgr.getFreshAccessToken(GHOST, KEY, SLACK_DECL)).resolves.toMatchObject({ ok: true });
+ await expect(mgr.getFreshAccessToken(GHOST, KEY, SLACK_DECL)).resolves.toMatchObject({
+ ok: true,
+ });
// 回填是 fire-and-forget,轮询等它落库。
await vi.waitFor(() => {
expect(mgr.listAccounts(GHOST, KEY)[0]?.label).toBe('acme · devuser');
@@ -1294,7 +1721,13 @@ describe('identity.displayTemplate 展示名', () => {
[`${KEY}-accounts`]: JSON.stringify({
defaultAccountId: 'acc-1',
accounts: [
- { id: 'acc-1', label: 'U0EXAMPLE1', displayLabel: 'acme · devuser', status: 'connected', createdAt: 1 },
+ {
+ id: 'acc-1',
+ label: 'U0EXAMPLE1',
+ displayLabel: 'acme · devuser',
+ status: 'connected',
+ createdAt: 1,
+ },
],
}),
[`${KEY}-rt-acc-1`]: 'rt-old',
@@ -1305,7 +1738,9 @@ describe('identity.displayTemplate 展示名', () => {
fetchImpl: fetchImpl as unknown as typeof fetch,
openExternal: vi.fn(),
});
- await expect(mgr.getFreshAccessToken(GHOST, KEY, SLACK_DECL)).resolves.toMatchObject({ ok: true });
+ await expect(mgr.getFreshAccessToken(GHOST, KEY, SLACK_DECL)).resolves.toMatchObject({
+ ok: true,
+ });
// 给潜在的异步回填一个宏任务窗口,再断言没有第二次网络调用。
await new Promise((r) => setTimeout(r, 20));
expect(fetchImpl).toHaveBeenCalledTimes(1);
@@ -1316,7 +1751,11 @@ describe('identity.displayTemplate 展示名', () => {
describe('identity.avatarPath 头像回填', () => {
const AVATAR_DECL: GhostOauthDecl = {
...DECL,
- identity: { url: 'https://api.example.com/userinfo', labelPath: 'email', avatarPath: 'picture' },
+ identity: {
+ url: 'https://api.example.com/userinfo',
+ labelPath: 'email',
+ avatarPath: 'picture',
+ },
};
const PNG_BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
const PNG_DATA_URL = `data:image/png;base64,${PNG_BYTES.toString('base64')}`;
@@ -1338,10 +1777,16 @@ describe('identity.avatarPath 头像回填', () => {
const url = String(input);
if (url === DECL.tokenUrl) return jsonResponse({ access_token: 'at-2', expires_in: 3600 });
if (url === 'https://api.example.com/userinfo') {
- return jsonResponse({ email: '[email protected]', picture: 'https://cdn.example.com/a.png' });
+ return jsonResponse({
+ email: '[email protected]',
+ picture: 'https://cdn.example.com/a.png',
+ });
}
if (url === 'https://cdn.example.com/a.png') {
- return new Response(new Uint8Array(PNG_BYTES), { status: 200, headers: { 'Content-Type': 'image/png' } });
+ return new Response(new Uint8Array(PNG_BYTES), {
+ status: 200,
+ headers: { 'Content-Type': 'image/png' },
+ });
}
throw new Error(`unexpected fetch ${url}`);
});
@@ -1354,7 +1799,9 @@ describe('identity.avatarPath 头像回填', () => {
fetchImpl: avatarFetch() as unknown as typeof fetch,
openExternal: vi.fn(),
});
- await expect(mgr.getFreshAccessToken(GHOST, KEY, AVATAR_DECL)).resolves.toMatchObject({ ok: true });
+ await expect(mgr.getFreshAccessToken(GHOST, KEY, AVATAR_DECL)).resolves.toMatchObject({
+ ok: true,
+ });
// 回填是 fire-and-forget,轮询等它落库。
await vi.waitFor(() => {
expect(vault.read(GHOST, `${KEY}-avatar-acc-1`)).toBe(PNG_DATA_URL);
@@ -1389,12 +1836,16 @@ describe('identity.avatarPath 头像回填', () => {
fetchImpl: fetchImpl as unknown as typeof fetch,
openExternal: vi.fn(),
});
- await expect(mgr.getFreshAccessToken('evil-tools', KEY, decl)).resolves.toMatchObject({ ok: true });
+ await expect(mgr.getFreshAccessToken('evil-tools', KEY, decl)).resolves.toMatchObject({
+ ok: true,
+ });
// 等展示名回填落库,证明身份端点确实拉过了(而不是回填整体没跑)。
await vi.waitFor(() => {
expect(mgr.listAccounts('evil-tools', KEY)[0]?.label).toBe('[email protected]·bf');
});
- expect(fetchImpl.mock.calls.map((c) => String(c[0]))).not.toContain('https://cdn.example.com/a.png');
+ expect(fetchImpl.mock.calls.map((c) => String(c[0]))).not.toContain(
+ 'https://cdn.example.com/a.png',
+ );
expect(vault.read('evil-tools', `${KEY}-avatar-acc-1`)).toBeNull();
});
@@ -1412,12 +1863,18 @@ describe('identity.avatarPath 头像回填', () => {
const url = String(input);
if (url === DECL.tokenUrl) return jsonResponse({ access_token: 'at-2', expires_in: 3600 });
if (url === 'https://api.example.com/userinfo') {
- return jsonResponse({ email: '[email protected]', picture: 'https://cdn.example.com/a.png' });
+ return jsonResponse({
+ email: '[email protected]',
+ picture: 'https://cdn.example.com/a.png',
+ });
}
if (url === 'https://cdn.example.com/a.png') {
avatarRequestedResolve();
await gate;
- return new Response(new Uint8Array(PNG_BYTES), { status: 200, headers: { 'Content-Type': 'image/png' } });
+ return new Response(new Uint8Array(PNG_BYTES), {
+ status: 200,
+ headers: { 'Content-Type': 'image/png' },
+ });
}
throw new Error(`unexpected fetch ${url}`);
});
@@ -1426,7 +1883,9 @@ describe('identity.avatarPath 头像回填', () => {
fetchImpl: fetchImpl as unknown as typeof fetch,
openExternal: vi.fn(),
});
- await expect(mgr.getFreshAccessToken(GHOST, KEY, AVATAR_DECL)).resolves.toMatchObject({ ok: true });
+ await expect(mgr.getFreshAccessToken(GHOST, KEY, AVATAR_DECL)).resolves.toMatchObject({
+ ok: true,
+ });
// 等回填走到头像下载(此时被 gate 卡住),断开账号后再放行下载。
await avatarRequested;
mgr.disconnectAccount(GHOST, KEY, 'acc-1');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthScopeStaleness.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthScopeStaleness.test.ts
new file mode 100644
index 0000000000..04bb93a1cd
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthScopeStaleness.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+
+import type { GhostManifest, GhostSetupAssessment } from '../../../shared/ghost.js';
+import {
+ appendReadyGhostOauthReauthSuggest,
+ findGhostOauthReauthSuggest,
+} from '../ghostOauthScopeStaleness.js';
+
+const MANIFEST: GhostManifest = {
+ schemaVersion: 2,
+ id: 'xd-feishu',
+ name: 'XD Feishu',
+ version: '2.3.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['network'],
+ network: {
+ hosts: ['open.feishu.cn'],
+ secrets: [
+ {
+ key: 'feishu_account',
+ label: 'Feishu account',
+ source: 'oauth',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ oauth: {
+ authorizeUrl: 'https://accounts.feishu.cn/authorize',
+ tokenUrl: 'https://open.feishu.cn/token',
+ scopes: ['scope.old', 'scope.new'],
+ },
+ },
+ ],
+ },
+};
+
+const READY: GhostSetupAssessment = { state: 'ready', revision: 7, groups: [] };
+
+describe('OAuth scope stale runtime assessment', () => {
+ it('ready + 默认账号陈旧时附加非阻塞 reauthSuggest', () => {
+ const suggest = findGhostOauthReauthSuggest(MANIFEST, () => ['scope.new']);
+
+ expect(appendReadyGhostOauthReauthSuggest(READY, suggest)).toEqual({
+ ...READY,
+ reauthSuggest: {
+ ghostId: 'xd-feishu',
+ secretKey: 'feishu_account',
+ missingScopes: ['scope.new'],
+ missingScopeCount: 1,
+ requirement: {
+ ref: 'secret:feishu_account',
+ kind: 'oauth',
+ label: 'Feishu account',
+ action: {
+ id: 'oauth_connect:secret:feishu_account',
+ kind: 'oauth_connect',
+ },
+ },
+ },
+ });
+ });
+
+ it('缺失面为空(非 stale / 老账号判不准)时不附建议', () => {
+ const suggest = findGhostOauthReauthSuggest(MANIFEST, () => []);
+ expect(appendReadyGhostOauthReauthSuggest(READY, suggest)).toBe(READY);
+ });
+
+ it('setup required 时不附建议,不改变既有 gate 语义', () => {
+ const required: GhostSetupAssessment = {
+ state: 'required',
+ revision: 8,
+ groups: [],
+ };
+ const suggest = findGhostOauthReauthSuggest(MANIFEST, () => ['scope.new']);
+
+ expect(appendReadyGhostOauthReauthSuggest(required, suggest)).toBe(required);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts
index 2d280cae78..833a4bbff8 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts
@@ -54,6 +54,42 @@ function ready(revision = 1): GhostSetupAssessment {
};
}
+function readyWithReauth(revision = 7): GhostSetupAssessment {
+ return {
+ ...ready(revision),
+ reauthSuggest: {
+ ghostId: 'gmail',
+ secretKey: 'google',
+ missingScopes: ['scope.new'],
+ missingScopeCount: 1,
+ requirement: {
+ ref: 'secret:google',
+ kind: 'oauth',
+ label: 'Google 账号',
+ action: {
+ id: 'oauth_connect:secret:google',
+ kind: 'oauth_connect',
+ },
+ },
+ },
+ };
+}
+
+function reauthPlan(revision = 7): GhostSetupPlan {
+ return {
+ assessmentRevision: revision,
+ steps: [
+ {
+ id: 'reauth-google',
+ title: '重新连接账号',
+ description: '补齐新增权限',
+ requirementRefs: ['secret:google'],
+ actionId: 'oauth_connect:secret:google',
+ },
+ ],
+ };
+}
+
function requiredInline(revision = 0): GhostSetupAssessment {
return {
state: 'required',
@@ -212,6 +248,131 @@ describe('GhostSetupCoordinator', () => {
expect(h.bridge.pendingSnapshots()).toEqual([]);
});
+ it('ready + reauthSuggest + 匹配 plan 复用交互卡,重连清除建议后放行调用', async () => {
+ const h = harness(readyWithReauth());
+ const waiting = h.coordinator.ensureReady({
+ sessionId: 'session-1',
+ ghostId: 'gmail',
+ tool: 'search',
+ plan: reauthPlan(),
+ });
+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));
+ const snapshot = h.bridge.pendingSnapshots()[0].request;
+ expect(snapshot.steps).toHaveLength(1);
+ expect(snapshot.steps[0]).toMatchObject({
+ title: '重新连接账号',
+ action: { id: 'oauth_connect:secret:google', kind: 'oauth_connect' },
+ });
+ h.executeAction.mockImplementationOnce(async () => {
+ h.setAssessment(ready(8));
+ h.changeBus.emit('gmail', { source: 'oauth', ref: 'google' });
+ return { ok: true };
+ });
+ h.bridge.resolve(snapshot.requestId, {
+ kind: 'plugin_setup',
+ action: 'run_action',
+ actionId: 'oauth_connect:secret:google',
+ expectedRevision: snapshot.revision,
+ });
+
+ await expect(waiting).resolves.toMatchObject({
+ ok: true,
+ assessment: { state: 'ready', revision: 8 },
+ });
+ expect(h.executeAction).toHaveBeenCalledOnce();
+ });
+
+ it('ready 重连卡取消沿用 SETUP_CANCELLED,本次调用不执行', async () => {
+ const h = harness(readyWithReauth());
+ const waiting = h.coordinator.ensureReady({
+ sessionId: 'session-1',
+ ghostId: 'gmail',
+ tool: 'search',
+ plan: reauthPlan(),
+ });
+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));
+ const snapshot = h.bridge.pendingSnapshots()[0].request;
+ h.bridge.resolve(snapshot.requestId, {
+ kind: 'plugin_setup',
+ action: 'cancel',
+ expectedRevision: snapshot.revision,
+ });
+
+ await expect(waiting).resolves.toEqual({
+ ok: false,
+ errorCode: 'SETUP_CANCELLED',
+ message: '用户取消了插件设置,本次调用未执行。',
+ });
+ expect(h.executeAction).not.toHaveBeenCalled();
+ });
+
+ it('ready + reauthSuggest 但未带 plan 时不弹卡直接放行(建议非阻塞)', async () => {
+ const h = harness(readyWithReauth());
+ await expect(
+ h.coordinator.ensureReady({ sessionId: 'session-1', ghostId: 'gmail', tool: 'search' }),
+ ).resolves.toMatchObject({ ok: true, assessment: { state: 'ready' } });
+ expect(h.bridge.pendingSnapshots()).toEqual([]);
+ });
+
+ it('ready + reauthSuggest + plan 但无交互面(IM/定时任务)时丢弃 plan 放行,不拦成 SETUP_REQUIRED', async () => {
+ const h = harness(readyWithReauth());
+ await expect(
+ h.coordinator.ensureReady({
+ sessionId: null,
+ ghostId: 'gmail',
+ tool: 'search',
+ plan: reauthPlan(),
+ }),
+ ).resolves.toMatchObject({ ok: true, assessment: { state: 'ready' } });
+ expect(h.bridge.pendingSnapshots()).toEqual([]);
+ });
+
+ it('ready 无 reauthSuggest 时忽略随调用携带的 plan,直接放行', async () => {
+ const h = harness(ready(7));
+ await expect(
+ h.coordinator.ensureReady({
+ sessionId: 'session-1',
+ ghostId: 'gmail',
+ tool: 'search',
+ plan: reauthPlan(),
+ }),
+ ).resolves.toMatchObject({ ok: true, assessment: { state: 'ready' } });
+ expect(h.bridge.pendingSnapshots()).toEqual([]);
+ });
+
+ it('ready 重连 plan 引用不匹配时拒绝 Agent 编排,回落 Host 默认单步卡', async () => {
+ const h = harness(readyWithReauth());
+ const invalidPlan: GhostSetupPlan = {
+ ...reauthPlan(),
+ steps: [
+ {
+ ...reauthPlan().steps[0],
+ requirementRefs: ['secret:other'],
+ actionId: 'oauth_connect:secret:other',
+ },
+ ],
+ };
+ const waiting = h.coordinator.ensureReady({
+ sessionId: 'session-1',
+ ghostId: 'gmail',
+ tool: 'search',
+ plan: invalidPlan,
+ });
+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));
+ const snapshot = h.bridge.pendingSnapshots()[0].request;
+ expect(snapshot.steps).toHaveLength(1);
+ expect(snapshot.steps[0]).toMatchObject({
+ title: 'Google 账号',
+ action: { id: 'oauth_connect:secret:google', kind: 'oauth_connect' },
+ });
+ h.bridge.resolve(snapshot.requestId, {
+ kind: 'plugin_setup',
+ action: 'cancel',
+ expectedRevision: snapshot.revision,
+ });
+ await waiting;
+ });
+
it('submits inline Secret per request, re-assesses on change, and never snapshots the value', async () => {
const h = harness(requiredInline());
const waiting = h.coordinator.ensureReady({
@@ -305,10 +466,7 @@ describe('GhostSetupCoordinator', () => {
const terminalSnapshots = h.broadcast.mock.calls
.filter(([channel]) => channel === MAKER_PUSH.INTERACTION_REQUEST)
- .map(
- ([, payload]) =>
- (payload as { request: GhostSetupInteractionSnapshot }).request,
- )
+ .map(([, payload]) => (payload as { request: GhostSetupInteractionSnapshot }).request)
.filter((request) => request.terminal === true);
expect(terminalSnapshots).toHaveLength(1);
expect(terminalSnapshots[0].steps).toEqual([
@@ -566,9 +724,7 @@ describe('GhostSetupCoordinator', () => {
for (const release of releases) release();
await vi.waitFor(() =>
- expect(h.bridge.pendingSnapshots()[0].request.steps[0]?.phase).toBe(
- 'waiting_external',
- ),
+ expect(h.bridge.pendingSnapshots()[0].request.steps[0]?.phase).toBe('waiting_external'),
);
const current = h.bridge.pendingSnapshots()[0].request;
h.bridge.resolve(current.requestId, {
@@ -1031,13 +1187,13 @@ describe('GhostSetupCoordinator', () => {
let disabledWorkdir: string | null = null;
const validateTarget = vi.fn(
(_ghostId: string, _tool: string | undefined, workingDir?: string | null) =>
- workingDir === disabledWorkdir
- ? ({
- ok: false,
- errorCode: 'GHOST_DISABLED_IN_WORKDIR',
- message: '用户已在当前工作目录停用该插件;不要重试。',
- } as const)
- : ({ ok: true } as const),
+ workingDir === disabledWorkdir
+ ? ({
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: '用户已在当前工作目录停用该插件;不要重试。',
+ } as const)
+ : ({ ok: true } as const),
);
const coordinator = new GhostSetupCoordinator({
changeBus,
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index afd672800b..24f4ce3a58 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -26,10 +26,7 @@ import {
validateGhostManifest,
type GhostManifest,
} from '../../shared/ghost.js';
-import {
- GHOST_MANIFEST_MAX_BYTES,
- readBoundedFileNoFollow,
-} from '../utils/readBoundedFile.js';
+import { GHOST_MANIFEST_MAX_BYTES, readBoundedFileNoFollow } from '../utils/readBoundedFile.js';
import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
import { GHOST_SIGNATURE_FILE } from './ghostSignature.js';
import { checkSkillMdConsistency } from './skillSlot.js';
@@ -426,7 +423,11 @@ export async function scaffoldGhostDir(
const resolved = path.resolve(input.dir);
const workdir = options?.sessionWorkdir;
if (!workdir) {
- return { ok: false, errorCode: 'INVALID_INPUT', message: '没有会话工作目录,无法确定骨架输出位置' };
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: '没有会话工作目录,无法确定骨架输出位置',
+ };
}
// 字面 startsWith 不设防软链:工作目录里若有 out -> /tmp/out 之类的
// 软链祖先,字面在内、实际在外。两边都按 realpath 对账——目标还不存在,
@@ -435,7 +436,11 @@ export async function scaffoldGhostDir(
try {
realWorkdir = await fs.promises.realpath(path.resolve(workdir));
} catch {
- return { ok: false, errorCode: 'INVALID_INPUT', message: '会话工作目录不存在,无法确定骨架输出位置' };
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: '会话工作目录不存在,无法确定骨架输出位置',
+ };
}
let realAncestor = resolved;
const pendingSegments: string[] = [];
@@ -725,7 +730,10 @@ async function buildGhostPackage(
const maxFiles = manifest.node ? MAX_NODE_FILES : MAX_BASIC_FILES;
const maxTotalBytes = manifest.node ? MAX_NODE_TOTAL_BYTES : MAX_BASIC_TOTAL_BYTES;
const seenPackPaths = new Set<string>();
- const walk = async (cur: string, relBase: string): Promise<Exclude<ForgePackResult, { ok: true }> | null> => {
+ const walk = async (
+ cur: string,
+ relBase: string,
+ ): Promise<Exclude<ForgePackResult, { ok: true }> | null> => {
const entries = await fs.promises.readdir(cur, { withFileTypes: true });
for (const e of entries) {
if (shouldSkip(e.name)) continue;
@@ -780,7 +788,8 @@ async function buildGhostPackage(
return {
ok: false,
errorCode: 'MANIFEST_INVALID',
- message: '已签名插件不能使用 AI 图标覆盖;请保留原图标,或先修改源码图标再由正式发布流水线重新签名',
+ message:
+ '已签名插件不能使用 AI 图标覆盖;请保留原图标,或先修改源码图标再由正式发布流水线重新签名',
};
}
const foldedAiIconPath = FORGE_AI_ICON_PATH.toLowerCase();
@@ -1258,7 +1267,7 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它
"clientId": "xxx.apps.example.com", // 可选:内置 OAuth 客户端 ID(用户零配置开箱即用;用户在设置页自填的覆盖内置,清除自填即回落)
"clientIdAlternatives": ["xxx-global.apps.example.com"], // 可选 ≤8 条:仅 tokenBroker 模式;意识按 app-context 选 App 时,connect 只接受默认值或这里声明的公开 ID
"clientSecret": "xxx", // 可选(须与 clientId 成对):内置 client 的 secret;桌面应用的 client 凭证本非机密,纯 PKCE 服务商可省略
- "scopes": ["read.a", "write.b"], // 可选 ≤32 条:申请的权限范围(确认框逐条展示给用户)
+ "scopes": ["read.a", "write.b"], // 可选 ≤48 条:申请的权限范围(确认框逐条展示给用户)
"scopeDelimiter": ",", // 可选:authorize URL 的 scope 拼接分隔符;缺省空格(OAuth 标准),Slack 这类逗号分隔的服务商声明 ","(目前只认这一个值)
"pkce": true, // 可选:PKCE(S256)开关,缺省 true
"extraAuthorizeParams": { "access_type": "offline", "prompt": "consent" }, // 可选 ≤8 条:服务商特有授权参数(协议保留参数禁写)
@@ -2119,8 +2128,9 @@ settingsHtml 里自填**(用户用自己注册的 OAuth 应用,配额风控归
\`\`\`js
// 状态回查(哪些 oauth 凭证槽、client 配没配、连了哪些账号;零令牌字节):
const list = await (await fetch('/oauth')).json();
-// → [{ key:'acct', clientConfigured:true, clientCustom:false, accounts:[{ id, label, status:'connected'|'expired', isDefault, createdAt, avatarDataUrl }] }]
+// → [{ key:'acct', clientConfigured:true, clientCustom:false, accounts:[{ id, label, status:'connected'|'expired', isDefault, createdAt, avatarDataUrl, scopeStale }] }]
// avatarDataUrl = 头像 data URL(声明了 identity.avatarPath 且主机下载成功才有,否则 null;<img src> 直接用)
+// scopeStale = true 表示该账号有真实权限错误证据,或其全量授权快照未包含插件后来新增的 scope;账号仍可用,设置页应显示非阻塞提示并复用现有重新连接动作
// clientConfigured = 自填或内置任一在场;clientCustom = 用户自填过(UI 显示"内置应用身份/已自定义")
// client 凭证只写入库(和 /secrets 同纪律,存入后拿不回;clientSecret 可省略 = 纯 PKCE):
await fetch('/oauth/acct/client', { method:'PUT', body: JSON.stringify({ clientId, clientSecret }) }); // 204 即入库
@@ -2138,6 +2148,11 @@ const r = await (await fetch('/oauth/acct/connect', connectInit)).json();
// 断开账号 / 设默认账号:
await fetch('/oauth/acct/accounts/<accountId>', { method:'DELETE' }); // 204(幂等)
await fetch('/oauth/acct/default', { method:'POST', body: JSON.stringify({ accountId }) }); // 204
+// 真实 API 返回缺失 scope 时可 fire-and-forget 上报;只接受清单 oauth.scopes 内的值,
+// 任一越界整包 400 拒绝。主机会据此在对话流与详情页非阻塞引导用户重新连接。
+// 证据只记默认账号:带 authAccount 指定非默认账号的调用报错时不要上报,
+// 否则会引导用户重连错账号:
+await fetch('/oauth/acct/insufficient-scopes', { method:'POST', body: JSON.stringify({ scopes:['write.b'] }) }); // 204
\`\`\`
多账号:每个 oauth 凭证槽最多 8 个账号;cindy.fetch 可带 \`authAccount: '<账号id>'\`
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
index 5d0b961a8b..faf33872eb 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
@@ -86,6 +86,11 @@ export interface GhostOauthAccountView {
* 上下文(networkSlot 只走 getFreshAccessToken)。
*/
avatarDataUrl: string | null;
+ /**
+ * 当前账号有经宿主校验的真实缺权证据,或当前清单新增了该账号全量授权
+ * 时未申请的 scope。没有证据时,老账号与主动降面账号仍不猜。
+ */
+ scopeStale: boolean;
}
/** 保险库最小面(providerSecretStore 在接线处适配;测试喂内存假体)。 */
@@ -118,7 +123,7 @@ export interface GhostOauthAccountManagerDeps {
* 授权成功钩子(2026-07-14):新连与同身份重连两个成功出口都触发,调用方
* 拿它广播"授权成功"的主机代言 tips(label = 账号展示标签,声明 identity
* 且拉取成功才有)。抛错不许影响连接结果,实现侧自兜。
- */
+ */
onAccountConnected?: (info: { ghostId: string; secretKey: string; label: string | null }) => void;
/**
* Refresh-path status transition hook. It deliberately carries no token,
@@ -135,11 +140,7 @@ export interface GhostOauthAccountManagerDeps {
* verifies that the plugin and the exact OAuth declaration still exist
* before any callback result is persisted.
*/
- isConnectTargetCurrent?: (
- ghostId: string,
- secretKey: string,
- decl: GhostOauthDecl,
- ) => boolean;
+ isConnectTargetCurrent?: (ghostId: string, secretKey: string, decl: GhostOauthDecl) => boolean;
/** 延时器(仅 invalid_grant 轮换探测用;测试注入即时假体,生产缺省 setTimeout)。 */
sleep?: (ms: number) => Promise<void>;
}
@@ -177,6 +178,12 @@ interface AccountRow {
displayLabel: string | null;
status: GhostOauthAccountStatus;
createdAt: number;
+ /** 本次浏览器授权 URL 实际携带的 scope 面;旧账号没有该快照。 */
+ authScopes?: string[];
+ /** full = 当时清单全量;subset = 用户主动选择了降面授权。 */
+ authFace?: 'full' | 'subset';
+ /** 插件从真实 API 权限错误中上报、且已由宿主按当前声明校验的缺失 scope。 */
+ insufficientScopes?: string[];
}
interface AccountsManifest {
@@ -217,13 +224,27 @@ function parseManifest(raw: string | null): AccountsManifest {
accounts.push({
id: r.id,
label: typeof r.label === 'string' && r.label.length > 0 ? r.label : null,
- displayLabel: typeof r.displayLabel === 'string' && r.displayLabel.length > 0 ? r.displayLabel : null,
+ displayLabel:
+ typeof r.displayLabel === 'string' && r.displayLabel.length > 0 ? r.displayLabel : null,
status: r.status === 'expired' ? 'expired' : 'connected',
- createdAt: typeof r.createdAt === 'number' && Number.isFinite(r.createdAt) ? r.createdAt : 0,
+ createdAt:
+ typeof r.createdAt === 'number' && Number.isFinite(r.createdAt) ? r.createdAt : 0,
+ ...(Array.isArray(r.authScopes) && r.authScopes.every((scope) => typeof scope === 'string')
+ ? { authScopes: [...r.authScopes] }
+ : {}),
+ ...(r.authFace === 'full' || r.authFace === 'subset' ? { authFace: r.authFace } : {}),
+ // 与 authScopes 同风格宽松读取:上限由写侧(端点校验 + 合并裁剪)钳制,
+ // 库里的坏值对消费方惰性(判定前先按当前声明过滤),不整包丢弃证据。
+ ...(Array.isArray(r.insufficientScopes) &&
+ r.insufficientScopes.length > 0 &&
+ r.insufficientScopes.every((scope) => typeof scope === 'string')
+ ? { insufficientScopes: [...new Set(r.insufficientScopes)] }
+ : {}),
});
}
const defaultAccountId =
- typeof parsed.defaultAccountId === 'string' && accounts.some((a) => a.id === parsed.defaultAccountId)
+ typeof parsed.defaultAccountId === 'string' &&
+ accounts.some((a) => a.id === parsed.defaultAccountId)
? parsed.defaultAccountId
: accounts.length > 0
? accounts[0].id
@@ -238,6 +259,7 @@ function toView(
row: AccountRow,
defaultAccountId: string | null,
avatarDataUrl: string | null,
+ declScopes: readonly string[] = [],
): GhostOauthAccountView {
return {
id: row.id,
@@ -246,9 +268,40 @@ function toView(
isDefault: row.id === defaultAccountId,
createdAt: row.createdAt,
avatarDataUrl,
+ scopeStale: accountMissingScopes(declScopes, row).length > 0,
};
}
+/**
+ * 快照推断分量:仅在可证明“当时拿的是全量面”时列出新增 scope;老数据与
+ * 降面授权不猜(返回空数组)。合并后的判定入口是 accountMissingScopes
+ * (真实错误证据优先,本函数只做无证据时的兜底)。
+ */
+export function missingAuthScopes(
+ declScopes: readonly string[],
+ row: { authScopes?: readonly string[]; authFace?: 'full' | 'subset' },
+): string[] {
+ if (row.authFace !== 'full' || row.authScopes === undefined) return [];
+ const granted = new Set(row.authScopes);
+ return declScopes.filter((scope) => !granted.has(scope));
+}
+
+/** 真实错误证据优先;没有证据时才退回授权面快照推断。 */
+function accountMissingScopes(declScopes: readonly string[], row: AccountRow): string[] {
+ if (row.insufficientScopes?.length) {
+ const declared = new Set(declScopes);
+ const currentEvidence = row.insufficientScopes.filter((scope) => declared.has(scope));
+ if (currentEvidence.length > 0) return currentEvidence;
+ }
+ return missingAuthScopes(declScopes, row);
+}
+
+function sameScopeFace(left: readonly string[], right: readonly string[]): boolean {
+ if (left.length !== right.length) return false;
+ const expected = new Set(left);
+ return expected.size === new Set(right).size && right.every((scope) => expected.has(scope));
+}
+
interface CachedAccessToken {
accessToken: string;
/** null = 服务商没给 expires_in,视为会话内长期有效,401 时经 invalidate 作废。 */
@@ -295,7 +348,12 @@ export class GhostOauthAccountManager {
* 可省略——纯 PKCE 公共客户端)。改 client 后既有 access token 缓存作废
* (旧 client 换的令牌不该再续命)。
*/
- setClientConfig(ghostId: string, secretKey: string, clientId: string, clientSecret?: string): boolean {
+ setClientConfig(
+ ghostId: string,
+ secretKey: string,
+ clientId: string,
+ clientSecret?: string,
+ ): boolean {
if (!this.deps.vault.store(ghostId, clientIdKey(secretKey), clientId)) return false;
if (clientSecret !== undefined && clientSecret.length > 0) {
if (!this.deps.vault.store(ghostId, clientSecretKey(secretKey), clientSecret)) return false;
@@ -334,7 +392,9 @@ export class GhostOauthAccountManager {
// client 无意义且必错(自填 id 配服务端 secret = invalid_client),
// 一律忽略自填。缺省用内置 clientId;connect 可传已经过清单白名单
// 复验的备用 clientId,供同一意识按 region 选择不同 OAuth App。
- const customId = decl.tokenBroker ? null : this.deps.vault.read(ghostId, clientIdKey(secretKey));
+ const customId = decl.tokenBroker
+ ? null
+ : this.deps.vault.read(ghostId, clientIdKey(secretKey));
let clientId: string | null;
let clientSecret: string | null | undefined;
if (clientIdOverride !== undefined) {
@@ -374,11 +434,46 @@ export class GhostOauthAccountManager {
/* ------------------------------ 账号清单 ------------------------------ */
- listAccounts(ghostId: string, secretKey: string): GhostOauthAccountView[] {
+ listAccounts(ghostId: string, secretKey: string, decl?: GhostOauthDecl): GhostOauthAccountView[] {
const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
return manifest.accounts.map((a) =>
- toView(a, manifest.defaultAccountId, this.readAvatar(ghostId, secretKey, a.id)),
+ toView(a, manifest.defaultAccountId, this.readAvatar(ghostId, secretKey, a.id), decl?.scopes),
+ );
+ }
+
+ /** 默认账号相对当前声明缺失的 scope;空数组 = 无需重连或判不准。 */
+ defaultMissingScopes(ghostId: string, secretKey: string, decl: GhostOauthDecl): string[] {
+ const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ const row = manifest.accounts.find((account) => account.id === manifest.defaultAccountId);
+ return row ? accountMissingScopes(decl.scopes ?? [], row) : [];
+ }
+
+ /**
+ * 把真实权限错误证据合并到当前默认账号,并按当前声明面裁剪——顺手淘汰清单
+ * 换代后的过期证据,恒有条数 ≤ 声明上限(GHOST_OAUTH_SCOPES_MAX)。返回
+ * 'unchanged' = 证据已在库未重写(调用方据此跳过广播);false = 无默认账号
+ * 或写失败。
+ */
+ reportInsufficientScopes(
+ ghostId: string,
+ secretKey: string,
+ scopes: readonly string[],
+ declScopes: readonly string[],
+ ): 'stored' | 'unchanged' | false {
+ const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ const row = manifest.accounts.find((account) => account.id === manifest.defaultAccountId);
+ if (!row) return false;
+ const declared = new Set(declScopes);
+ const merged = [...new Set([...(row.insufficientScopes ?? []), ...scopes])].filter((scope) =>
+ declared.has(scope),
);
+ if (row.insufficientScopes && sameScopeFace(row.insufficientScopes, merged)) {
+ return 'unchanged';
+ }
+ row.insufficientScopes = merged;
+ return this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest))
+ ? 'stored'
+ : false;
}
/** 头像 data URL 读取(形状校验兜底:库里的坏值当无头像,不喂给 <img>)。 */
@@ -473,10 +568,18 @@ export class GhostOauthAccountManager {
if (opts?.scopes !== undefined) {
const declared = new Set(decl.scopes ?? []);
if (opts.scopes.length === 0 || opts.scopes.some((sc) => !declared.has(sc))) {
- return { ok: false, error: 'INVALID_CONFIG', detail: '申请的 scope 必须是清单声明的非空子集' };
+ return {
+ ok: false,
+ error: 'INVALID_CONFIG',
+ detail: '申请的 scope 必须是清单声明的非空子集',
+ };
}
config.scopes = [...opts.scopes];
}
+ const authScopes = [...config.scopes];
+ const authFace: AccountRow['authFace'] = sameScopeFace(decl.scopes ?? [], authScopes)
+ ? 'full'
+ : 'subset';
const flow = await startGhostOauthFlow({
config,
@@ -524,7 +627,10 @@ export class GhostOauthAccountManager {
// 等于给第三方意识一个"主机代发 GET + 小图字节回沙箱"的 SSRF 读原语。
// 下载本身不带任何凭证(CDN 域名不在注入白名单);失败降级无头像。
if (identity.avatarUrl !== null && isOfficialGhostId(ghostId)) {
- avatar = await fetchGhostOauthAvatar({ url: identity.avatarUrl, fetchImpl: this.deps.fetchImpl });
+ avatar = await fetchGhostOauthAvatar({
+ url: identity.avatarUrl,
+ fetchImpl: this.deps.fetchImpl,
+ });
}
}
@@ -549,7 +655,13 @@ export class GhostOauthAccountManager {
const existing = label !== null ? manifest.accounts.find((a) => a.label === label) : undefined;
if (existing) {
if (flow.bundle.refreshToken !== null) {
- if (!this.deps.vault.store(ghostId, refreshTokenKey(secretKey, existing.id), flow.bundle.refreshToken)) {
+ if (
+ !this.deps.vault.store(
+ ghostId,
+ refreshTokenKey(secretKey, existing.id),
+ flow.bundle.refreshToken,
+ )
+ ) {
return { ok: false, error: 'VAULT_WRITE_FAILED' };
}
}
@@ -564,8 +676,23 @@ export class GhostOauthAccountManager {
existing.displayLabel = display;
manifestDirty = true;
}
- if (manifestDirty) {
- this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest));
+ if (existing.authScopes === undefined || !sameScopeFace(existing.authScopes, authScopes)) {
+ existing.authScopes = authScopes;
+ manifestDirty = true;
+ }
+ if (existing.authFace !== authFace) {
+ existing.authFace = authFace;
+ manifestDirty = true;
+ }
+ if (existing.insufficientScopes !== undefined) {
+ delete existing.insufficientScopes;
+ manifestDirty = true;
+ }
+ if (
+ manifestDirty &&
+ !this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest))
+ ) {
+ return { ok: false, error: 'VAULT_WRITE_FAILED' };
}
// 重连顺带刷新头像(用户可能换过头像;写失败不影响连接结果)。
if (avatar !== null) {
@@ -575,7 +702,11 @@ export class GhostOauthAccountManager {
accessToken: flow.bundle.accessToken,
expiresAt: flow.bundle.expiresAt,
});
- this.deps.logger?.info('ghost oauth 账号已重连(同身份合并)', { ghostId, secretKey, accountId: existing.id });
+ this.deps.logger?.info('ghost oauth 账号已重连(同身份合并)', {
+ ghostId,
+ secretKey,
+ accountId: existing.id,
+ });
this.notifyConnected(ghostId, secretKey, existing.displayLabel ?? existing.label);
return {
ok: true,
@@ -583,6 +714,7 @@ export class GhostOauthAccountManager {
existing,
manifest.defaultAccountId,
avatar ?? this.readAvatar(ghostId, secretKey, existing.id),
+ decl.scopes,
),
};
}
@@ -599,13 +731,21 @@ export class GhostOauthAccountManager {
displayLabel: display,
status: 'connected',
createdAt: Date.now(),
+ authScopes,
+ authFace,
};
// refresh token 先落库再挂清单:清单是"账号存在"的事实源,顺序反了
// 可能出现"清单有账号但无 rt"的半身位。没有 rt 的服务商(罕见)照样
// 挂账号,access token 走内存缓存,过期后 AUTH_EXPIRED 引导重连。
if (flow.bundle.refreshToken !== null) {
- if (!this.deps.vault.store(ghostId, refreshTokenKey(secretKey, account.id), flow.bundle.refreshToken)) {
+ if (
+ !this.deps.vault.store(
+ ghostId,
+ refreshTokenKey(secretKey, account.id),
+ flow.bundle.refreshToken,
+ )
+ ) {
return { ok: false, error: 'VAULT_WRITE_FAILED' };
}
}
@@ -628,7 +768,10 @@ export class GhostOauthAccountManager {
});
this.deps.logger?.info('ghost oauth 账号已连接', { ghostId, secretKey, accountId: account.id });
this.notifyConnected(ghostId, secretKey, account.displayLabel ?? account.label);
- return { ok: true, account: toView(account, nextManifest.defaultAccountId, avatar) };
+ return {
+ ok: true,
+ account: toView(account, nextManifest.defaultAccountId, avatar, decl.scopes),
+ };
}
/** 授权成功通知(自兜异常:提示挂了不影响连接结果)。 */
@@ -720,7 +863,11 @@ export class GhostOauthAccountManager {
// 已被服务商作废,下一次刷新注定 invalid_grant → 重新授权。
if (result.bundle.refreshToken !== null && result.bundle.refreshToken !== refreshToken) {
if (
- !this.deps.vault.store(ghostId, refreshTokenKey(secretKey, accountId), result.bundle.refreshToken)
+ !this.deps.vault.store(
+ ghostId,
+ refreshTokenKey(secretKey, accountId),
+ result.bundle.refreshToken,
+ )
) {
this.deps.logger?.warn(
'ghost oauth 轮换后的新 refresh token 落库失败——新令牌仅存内存,重启后需要重新授权',
@@ -736,7 +883,13 @@ export class GhostOauthAccountManager {
this.markConnected(ghostId, secretKey, accountId);
// 展示名/头像回填(fire-and-forget,不拖累令牌热路径):displayTemplate /
// avatarPath 上线前连的老账号缺这些,借下一次令牌刷新顺路补上,无需重连。
- void this.backfillIdentityExtras(ghostId, secretKey, decl, accountId, result.bundle.accessToken);
+ void this.backfillIdentityExtras(
+ ghostId,
+ secretKey,
+ decl,
+ accountId,
+ result.bundle.accessToken,
+ );
return { ok: true, accessToken: result.bundle.accessToken, accountId };
}
@@ -748,7 +901,12 @@ export class GhostOauthAccountManager {
}
if (attempt === 0) {
- const rotated = await this.readRotatedRefreshToken(ghostId, secretKey, accountId, refreshToken);
+ const rotated = await this.readRotatedRefreshToken(
+ ghostId,
+ secretKey,
+ accountId,
+ refreshToken,
+ );
if (rotated !== null) {
this.deps.logger?.info(
'ghost oauth invalid_grant 后检测到 refresh token 已被其它实例轮换,用新令牌重试',
@@ -839,7 +997,10 @@ export class GhostOauthAccountManager {
this.deps.logger?.info('ghost oauth 账号展示名已回填', { ghostId, secretKey, accountId });
}
if (needAvatar && identity.avatarUrl !== null) {
- const avatar = await fetchGhostOauthAvatar({ url: identity.avatarUrl, fetchImpl: this.deps.fetchImpl });
+ const avatar = await fetchGhostOauthAvatar({
+ url: identity.avatarUrl,
+ fetchImpl: this.deps.fetchImpl,
+ });
// 存前重验账号仍在清单(拉取期间可能被断开;断开后不再写孤儿头像键)。
if (avatar !== null) {
const fresh = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
@@ -873,11 +1034,7 @@ export class GhostOauthAccountManager {
const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
const row = manifest.accounts.find((a) => a.id === accountId);
if (!row || !mutator(row)) return false;
- return this.deps.vault.store(
- ghostId,
- accountsKey(secretKey),
- JSON.stringify(manifest),
- );
+ return this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest));
}
private markExpired(ghostId: string, secretKey: string, accountId: string): void {
@@ -906,15 +1063,12 @@ export class GhostOauthAccountManager {
try {
this.deps.onAccountStatusChanged?.({ ghostId, secretKey, status });
} catch (err) {
- this.deps.logger?.warn?.(
- 'ghost oauth onAccountStatusChanged 通知失败(不影响状态写入)',
- {
- ghostId,
- secretKey,
- status,
- err: String(err),
- },
- );
+ this.deps.logger?.warn?.('ghost oauth onAccountStatusChanged 通知失败(不影响状态写入)', {
+ ghostId,
+ secretKey,
+ status,
+ err: String(err),
+ });
}
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthScopeStaleness.ts b/apps/desktop/src/main/cindy-brain/ghostOauthScopeStaleness.ts
new file mode 100644
index 0000000000..654554a25d
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthScopeStaleness.ts
@@ -0,0 +1,46 @@
+import type {
+ GhostManifest,
+ GhostSecretOauthDecl,
+ GhostSetupAssessment,
+ GhostSetupReauthSuggest,
+} from '../../shared/ghost.js';
+import { oauthConnectActionId, requirementRef } from './ghostSetupStatus.js';
+
+/** 从清单顺序中挑首个陈旧 OAuth 凭证槽,生成有界且不含凭证明文的建议。 */
+export function findGhostOauthReauthSuggest(
+ manifest: GhostManifest,
+ resolveMissingScopes: (secretKey: string, decl: GhostSecretOauthDecl) => readonly string[],
+): GhostSetupReauthSuggest | undefined {
+ for (const secret of manifest.network?.secrets ?? []) {
+ if (secret.source !== 'oauth' || !secret.oauth) continue;
+ const missing = resolveMissingScopes(secret.key, secret.oauth);
+ if (missing.length === 0) continue;
+ const ref = requirementRef({ kind: 'secret', key: secret.key });
+ return {
+ ghostId: manifest.id,
+ secretKey: secret.key,
+ missingScopes: [...missing],
+ missingScopeCount: missing.length,
+ requirement: {
+ ref,
+ kind: 'oauth',
+ label: secret.label,
+ action: {
+ id: oauthConnectActionId(ref),
+ kind: 'oauth_connect',
+ },
+ },
+ };
+ }
+ return undefined;
+}
+
+/** required 保持原样;只有整体 ready 时才附加非阻塞建议。 */
+export function appendReadyGhostOauthReauthSuggest(
+ assessment: GhostSetupAssessment,
+ suggest: GhostSetupReauthSuggest | undefined,
+): GhostSetupAssessment {
+ return assessment.state === 'ready' && suggest
+ ? { ...assessment, reauthSuggest: suggest }
+ : assessment;
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts b/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts
index a932590f10..8f0e931352 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts
@@ -160,10 +160,17 @@ export class GhostSetupCoordinator {
unsubscribe();
return this.internalFailure('插件配置状态读取失败', error);
}
- if (assessment.state === 'ready') {
+ // ready 态的重连建议是非阻塞的:仅 Agent 主动带 plan 且本回合有交互面时才进
+ // 卡流程;无 sessionId 的回合(IM/定时任务)丢弃 plan 直接放行,绝不把 ready
+ // 插件拦成 SETUP_REQUIRED。
+ const reauthAssessment =
+ request.plan && request.sessionId ? toReauthInteractionAssessment(assessment) : null;
+ const reauthMode = reauthAssessment !== null;
+ if (assessment.state === 'ready' && !reauthMode) {
unsubscribe();
return { ok: true, assessment };
}
+ if (reauthAssessment) assessment = reauthAssessment;
if (!request.sessionId) {
unsubscribe();
return {
@@ -186,7 +193,10 @@ export class GhostSetupCoordinator {
const sessionId = request.sessionId;
const requestId = this.deps.createRequestId?.() ?? randomUUID();
- let plan = validatePlan(request.plan, assessment) ?? defaultPlan(assessment);
+ let plan =
+ (reauthMode
+ ? validateReauthPlan(request.plan, assessment)
+ : validatePlan(request.plan, assessment)) ?? defaultPlan(assessment);
let snapshot = toSnapshot(requestId, identity, assessment, plan);
let settled = false;
let verifying: Promise<void> | null = null;
@@ -297,12 +307,13 @@ export class GhostSetupCoordinator {
return;
}
const next = current.assessment;
- if (next.state === 'ready') {
+ const nextReauthAssessment = reauthMode ? toReauthInteractionAssessment(next) : null;
+ if (next.state === 'ready' && !nextReauthAssessment) {
publishSatisfied(next);
settle({ ok: true, assessment: next }, 'ready');
return;
}
- publish(next, requiredPhase);
+ publish(nextReauthAssessment ?? next, requiredPhase);
})().finally(() => {
verifying = null;
if (assessmentDirty && !settled) wakeVerify?.();
@@ -567,6 +578,47 @@ function validatePlan(
return plan;
}
+/**
+ * ready 态的非阻塞重连建议只允许一张卡、一步、一个引用、一个动作。
+ * 其余校验仍复用 required 态 validatePlan,非法 Agent plan 同样回落 Host 默认卡。
+ */
+function validateReauthPlan(
+ plan: GhostSetupPlan | undefined,
+ assessment: GhostSetupAssessment,
+): GhostSetupPlan | null {
+ if (!plan || plan.steps.length !== 1 || plan.steps[0]?.requirementRefs.length !== 1) {
+ return null;
+ }
+ return validatePlan(plan, assessment);
+}
+
+/** 把 ready assessment 的建议映射成现有卡流程可消费的单项 expired assessment。 */
+function toReauthInteractionAssessment(
+ assessment: GhostSetupAssessment,
+): GhostSetupAssessment | null {
+ if (assessment.state !== 'ready' || !assessment.reauthSuggest) return null;
+ const requirement = assessment.reauthSuggest.requirement;
+ return {
+ state: 'required',
+ revision: assessment.revision,
+ groups: [
+ {
+ id: `reauth:${assessment.reauthSuggest.secretKey}`,
+ mode: 'any_of',
+ items: [
+ {
+ ref: requirement.ref,
+ kind: requirement.kind,
+ label: requirement.label,
+ state: 'expired',
+ actions: [requirement.action],
+ },
+ ],
+ },
+ ],
+ };
+}
+
function defaultPlan(assessment: GhostSetupAssessment): GhostSetupPlan {
const steps = assessment.groups.flatMap((group, index) => {
if (group.items.some((item) => item.state === 'satisfied')) return [];
@@ -635,9 +687,7 @@ function toSnapshot(
? (override?.phase ?? 'pending')
: ('pending' as const),
...(action && !satisfied ? { action } : {}),
- ...(!satisfied && active && override?.errorCode
- ? { errorCode: override.errorCode }
- : {}),
+ ...(!satisfied && active && override?.errorCode ? { errorCode: override.errorCode } : {}),
};
});
return {
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts
index 0e64cb6230..1278aeec5d 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts
@@ -115,10 +115,25 @@ function deriveRequirementGroups(manifest: GhostManifest): GhostSetupRequirement
}
/** 需求条目 → 展示项(label 取声明原文;kind 决定弹窗文案口径)。 */
-function requirementRef(req: GhostSetupRequirement): string {
+export function requirementRef(req: GhostSetupRequirement): string {
return `${req.kind}:${req.key}`;
}
+/**
+ * oauth_connect 动作 id 的唯一编解码对:actionFor 与 reauthSuggest 生产、
+ * executeGhostSetupAction 反解共用。改动作 id 格式只能改这两个函数,
+ * 任何一侧散落的字面量都会造成"点重连拿 ACTION_STALE"的静默失配。
+ */
+export function oauthConnectActionId(ref: string): string {
+ return `oauth_connect:${ref}`;
+}
+
+export function parseOauthConnectSecretKey(actionId: string): string | null {
+ const prefix = oauthConnectActionId('secret:');
+ const key = actionId.startsWith(prefix) ? actionId.slice(prefix.length) : '';
+ return key.length > 0 ? key : null;
+}
+
function actionFor(
kind: GhostSetupAssessmentItem['kind'],
ref: string,
@@ -134,7 +149,12 @@ function actionFor(
: kind === 'client_config'
? 'open_client_settings'
: 'open_plugin_settings';
- return [{ id: `${actionKind}:${ref}`, kind: actionKind }];
+ return [
+ {
+ id: actionKind === 'oauth_connect' ? oauthConnectActionId(ref) : `${actionKind}:${ref}`,
+ kind: actionKind,
+ },
+ ];
}
function inlineSecretAction(
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 4d0ed9a6c8..2b4a274287 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -28,6 +28,7 @@ import {
type GhostManifest,
type GhostSetupAllowedAction,
type GhostSetupAssessment,
+ type GhostSetupReauthSuggest,
type GhostVideoRefMode,
type GhostVideoResultParams,
type InstalledGhost,
@@ -88,6 +89,7 @@ import {
import {
evaluateGhostSetupAssessment,
handleGhostSetupStatusRequest,
+ parseOauthConnectSecretKey,
} from './ghostSetupStatus.js';
import { getGhostSetupChangeBus } from './ghostSetupChangeBus.js';
import { GhostSetupManifestTracker } from './ghostSetupManifestTracker.js';
@@ -98,6 +100,10 @@ import { handleGhostSecretsRequest } from './runtime/ghostSecretsEndpoint.js';
import { handleGhostOauthRequest } from './runtime/ghostOauthEndpoint.js';
import { handleGhostConnectionsRequest } from './runtime/ghostConnectionsEndpoint.js';
import { GhostOauthAccountManager, type GhostOauthDecl } from './ghostOauthAccounts.js';
+import {
+ appendReadyGhostOauthReauthSuggest,
+ findGhostOauthReauthSuggest,
+} from './ghostOauthScopeStaleness.js';
import { mapGhostOauthConnectError } from './ghostOauthSetupError.js';
import { reclaimLoopbackPort } from './portReclaim.js';
import { GhostConnectionManager } from './ghostConnections.js';
@@ -595,6 +601,30 @@ function availableGhosts(): InstalledGhost[] {
);
}
+function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {
+ try {
+ const suggest = getGhostOauthReauthSuggest(withRuntimeFiloGoogleClient(ghost.manifest));
+ return {
+ ...ghost,
+ ...(suggest
+ ? {
+ oauthScopeStale: {
+ secretKey: suggest.secretKey,
+ missingScopeCount: suggest.missingScopeCount,
+ },
+ }
+ : {}),
+ };
+ } catch (error) {
+ // 详情页角标是提示面,保险库异常不能让插件清单整体消失。
+ log.warn('ghost oauth scope stale projection omitted', {
+ ghostId: ghost.manifest.id,
+ errorType: error instanceof Error ? error.name : typeof error,
+ });
+ return ghost;
+ }
+}
+
function findAvailableGhost(id: string): InstalledGhost | null {
if (!isGhostAvailableForActiveSession(id)) return null;
return getGhostManager().list().find((ghost) => ghost.manifest.id === id) ?? null;
@@ -2772,6 +2802,7 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
// 展示标签时报"已连接 xxx",没有时报通用授权成功)。
onAccountConnected: ({ ghostId, label }) => {
getGhostSetupChangeBus().emit(ghostId, { source: 'oauth' });
+ broadcastGhostsChanged(getGhostManager().list(), false, { projectionOnly: true });
broadcastGhostHostNotice(
ghostId,
label
@@ -2784,6 +2815,7 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
source: 'oauth',
ref: secretKey,
});
+ broadcastGhostsChanged(getGhostManager().list(), false, { projectionOnly: true });
},
isConnectTargetCurrent: (ghostId, secretKey, decl) => {
const ghost = findAvailableGhost(ghostId);
@@ -2822,6 +2854,14 @@ function getGhostConnectionManager(): GhostConnectionManager {
let ghostSetupKvStore: GhostKvStore | null = null;
+/** 默认 OAuth 账号的授权面陈旧建议;只返回首个凭证槽,保持 envelope 有界。 */
+function getGhostOauthReauthSuggest(runtimeManifest: GhostManifest): GhostSetupReauthSuggest | undefined {
+ const oauthManager = getGhostOauthAccountManager();
+ return findGhostOauthReauthSuggest(runtimeManifest, (secretKey, decl) =>
+ oauthManager.defaultMissingScopes(runtimeManifest.id, secretKey, decl),
+ );
+}
+
/**
* Runtime-authoritative setup assessment used by ghost_list and ghost_call.
* Unlike the legacy plugin-page projection this path is strict: storage or
@@ -2836,7 +2876,7 @@ export function getGhostSetupAssessment(ghostId: string): GhostSetupAssessment {
const oauthManager = getGhostOauthAccountManager();
const connectionManager = getGhostConnectionManager();
let kvSnapshot: Record<string, unknown> | null = null;
- return evaluateGhostSetupAssessment(
+ const assessment = evaluateGhostSetupAssessment(
runtimeManifest,
{
secretSaved: (key) => ghostSecretSaved(ghostId, key),
@@ -2864,6 +2904,13 @@ export function getGhostSetupAssessment(ghostId: string): GhostSetupAssessment {
}),
},
);
+ // 性能短路:required 时建议注定被丢弃,不再为它读保险库。
+ // "required 绝不带建议"的契约不变量仍由 appendReadyGhostOauthReauthSuggest 守着。
+ if (assessment.state !== 'ready') return assessment;
+ return appendReadyGhostOauthReauthSuggest(
+ assessment,
+ getGhostOauthReauthSuggest(runtimeManifest),
+ );
}
/**
@@ -2885,11 +2932,10 @@ export async function executeGhostSetupAction(args: {
};
}
if (args.action.kind === 'oauth_connect') {
- const prefix = 'oauth_connect:secret:';
- if (!args.action.id.startsWith(prefix)) {
+ const secretKey = parseOauthConnectSecretKey(args.action.id);
+ if (!secretKey) {
return { ok: false, errorCode: 'ACTION_STALE', message: '授权动作已失效' };
}
- const secretKey = args.action.id.slice(prefix.length);
const runtimeManifest = withRuntimeFiloGoogleClient(ghost.manifest);
const decl = runtimeManifest.network?.secrets?.find(
(secret) => secret.key === secretKey && secret.source === 'oauth',
@@ -3735,6 +3781,7 @@ export function registerGhostIpc(): void {
ghostId,
onChanged: (secretKey) => {
getGhostSetupChangeBus().emit(ghostId, { source: 'oauth', ref: secretKey });
+ broadcastGhostsChanged(getGhostManager().list(), false, { projectionOnly: true });
},
log,
});
@@ -4248,7 +4295,7 @@ export function registerGhostIpc(): void {
});
ipcMain.on('ghosts:list', (event) => {
- event.returnValue = { ghosts: availableGhosts() };
+ event.returnValue = { ghosts: availableGhosts().map(projectGhostForRenderer) };
});
// Plugin 页的已安装快捷行按最近成功使用排序。历史是主机 UI 状态,不写入
@@ -4995,10 +5042,22 @@ function broadcastGhostProvisioning(active: boolean): void {
function broadcastGhostsChanged(
ghosts: InstalledGhost[],
rosterAuthoritative = false,
+ opts?: {
+ /**
+ * true = 花名册没变,只是 renderer 投影字段(OAuth 陈旧角标)需要刷新。
+ * 跳过清单指纹、未读扫尾与 skill 链接对账这些只对装/卸/启停/换版有
+ * 意义的花名册侧效应,OAuth 账号操作不再连带两趟全量磁盘扫描。
+ */
+ projectionOnly?: boolean;
+ },
): void {
- getGhostSetupManifestTracker().note(ghosts);
- sweepRevokedGhostUnread(ghosts, rosterAuthoritative);
- const visible = ghosts.filter((ghost) => isGhostAvailableForActiveSession(ghost.manifest.id));
+ if (!opts?.projectionOnly) {
+ getGhostSetupManifestTracker().note(ghosts);
+ sweepRevokedGhostUnread(ghosts, rosterAuthoritative);
+ }
+ const visible = ghosts
+ .filter((ghost) => isGhostAvailableForActiveSession(ghost.manifest.id))
+ .map(projectGhostForRenderer);
BrowserWindow.getAllWindows().forEach((window) => {
if (window.isDestroyed()) return;
window.webContents.send('ghosts:changed', { ghosts: visible });
@@ -5017,7 +5076,7 @@ function broadcastGhostsChanged(
// skill 槽共享链接对账:装/卸/启停/换版全走本广播,一处挂接全覆盖。
// 异步合并执行,不阻塞广播;用全量 list() 而非 per-session 过滤后的 visible
// (链接对账关心"装了什么",与当前会话可见性无关)。
- scheduleGhostSkillReconcile();
+ if (!opts?.projectionOnly) scheduleGhostSkillReconcile();
}
// —— skill 槽链接对账调度:合并突发广播(in-flight + pending 双标志),
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
index 78bddb128a..50a174e772 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
@@ -7,10 +7,7 @@ import { describe, expect, it, vi } from 'vitest';
import { GhostKvError } from '../../ghostKvStore.js';
import { GHOST_SECRET_VALUE_MAX_CHARS } from '../ghostSecretsEndpoint.js';
-import {
- handleGhostOauthRequest,
- type GhostOauthEndpointManager,
-} from '../ghostOauthEndpoint.js';
+import { handleGhostOauthRequest, type GhostOauthEndpointManager } from '../ghostOauthEndpoint.js';
import type { GhostOauthDecl } from '../../ghostOauthAccounts.js';
const GHOST = 'g-oauth';
@@ -21,7 +18,9 @@ const DECL: GhostOauthDecl = {
};
const SECRETS = new Map<string, GhostOauthDecl>([['acct', DECL]]);
-function fakeManager(overrides: Partial<GhostOauthEndpointManager> = {}): GhostOauthEndpointManager {
+function fakeManager(
+ overrides: Partial<GhostOauthEndpointManager> = {},
+): GhostOauthEndpointManager {
return {
clientConfigured: vi.fn(() => true),
clientCustomized: vi.fn(() => false),
@@ -35,6 +34,7 @@ function fakeManager(overrides: Partial<GhostOauthEndpointManager> = {}): GhostO
isDefault: true,
createdAt: 1,
avatarDataUrl: null,
+ scopeStale: true,
},
]),
connectAccount: vi.fn(async () => ({
@@ -46,10 +46,12 @@ function fakeManager(overrides: Partial<GhostOauthEndpointManager> = {}): GhostO
isDefault: false,
createdAt: 2,
avatarDataUrl: null,
+ scopeStale: false,
},
})),
disconnectAccount: vi.fn(),
setDefaultAccount: vi.fn(() => true),
+ reportInsufficientScopes: vi.fn(() => 'stored' as const),
...overrides,
};
}
@@ -76,12 +78,18 @@ function call(params: {
describe('GET /oauth', () => {
it('回全部 oauth 凭证槽状态,零令牌字节', async () => {
- const outcome = await call({ method: 'GET', pathname: '/oauth' });
+ const manager = fakeManager();
+ const outcome = await call({ method: 'GET', pathname: '/oauth', manager });
expect(outcome.status).toBe(200);
const parsed = JSON.parse(outcome.body ?? '[]') as Array<Record<string, unknown>>;
expect(parsed).toHaveLength(1);
expect(parsed[0]).toMatchObject({ key: 'acct', clientConfigured: true, clientCustom: false });
- expect((parsed[0].accounts as unknown[])[0]).toMatchObject({ id: 'acc-1', isDefault: true });
+ expect((parsed[0].accounts as unknown[])[0]).toMatchObject({
+ id: 'acc-1',
+ isDefault: true,
+ scopeStale: true,
+ });
+ expect(manager.listAccounts).toHaveBeenCalledWith(GHOST, 'acct', DECL);
// 端点契约:响应体里不可能出现 token 类字段。
expect(outcome.body).not.toMatch(/token|secret/i);
});
@@ -106,7 +114,12 @@ describe('PUT /oauth/<key>/client', () => {
it('clientSecret 省略/空串 = 纯 PKCE(undefined 传入)', async () => {
const manager = fakeManager();
- await call({ method: 'PUT', pathname: '/oauth/acct/client', body: JSON.stringify({ clientId: 'cid' }), manager });
+ await call({
+ method: 'PUT',
+ pathname: '/oauth/acct/client',
+ body: JSON.stringify({ clientId: 'cid' }),
+ manager,
+ });
expect(manager.setClientConfig).toHaveBeenCalledWith(GHOST, 'acct', 'cid', undefined);
await call({
method: 'PUT',
@@ -118,9 +131,17 @@ describe('PUT /oauth/<key>/client', () => {
});
it('坏 body / 空 clientId → 400;超长 → 413;写失败 → 500;DELETE 清除 → 204', async () => {
- expect((await call({ method: 'PUT', pathname: '/oauth/acct/client', body: '{broken' })).status).toBe(400);
expect(
- (await call({ method: 'PUT', pathname: '/oauth/acct/client', body: JSON.stringify({ clientId: '' }) })).status,
+ (await call({ method: 'PUT', pathname: '/oauth/acct/client', body: '{broken' })).status,
+ ).toBe(400);
+ expect(
+ (
+ await call({
+ method: 'PUT',
+ pathname: '/oauth/acct/client',
+ body: JSON.stringify({ clientId: '' }),
+ })
+ ).status,
).toBe(400);
expect(
(
@@ -152,7 +173,9 @@ describe('PUT /oauth/<key>/client', () => {
).status,
).toBe(500);
const manager = fakeManager();
- expect((await call({ method: 'DELETE', pathname: '/oauth/acct/client', manager })).status).toBe(204);
+ expect((await call({ method: 'DELETE', pathname: '/oauth/acct/client', manager })).status).toBe(
+ 204,
+ );
expect(manager.clearClientConfig).toHaveBeenCalledWith(GHOST, 'acct');
});
});
@@ -168,7 +191,9 @@ describe('POST /oauth/<key>/connect', () => {
const outcome = await call({
method: 'POST',
pathname: '/oauth/acct/connect',
- manager: fakeManager({ connectAccount: vi.fn(async () => ({ ok: false as const, error: 'TIMEOUT' as const })) }),
+ manager: fakeManager({
+ connectAccount: vi.fn(async () => ({ ok: false as const, error: 'TIMEOUT' as const })),
+ }),
});
expect(outcome.status).toBe(200);
expect(JSON.parse(outcome.body ?? '{}')).toMatchObject({ ok: false, error: 'TIMEOUT' });
@@ -215,7 +240,9 @@ describe('POST /oauth/<key>/connect · scopes body(降面授权)', () => {
const manager = fakeManager();
const outcome = await connectWith(JSON.stringify({ scopes: ['read.a', 'read.a'] }), manager);
expect(outcome.status).toBe(200);
- expect(manager.connectAccount).toHaveBeenCalledWith(GHOST, 'acct', SCOPED, { scopes: ['read.a'] });
+ expect(manager.connectAccount).toHaveBeenCalledWith(GHOST, 'acct', SCOPED, {
+ scopes: ['read.a'],
+ });
});
it('无 body / 空 body / 无 scopes 字段的对象 = 不传 opts(申请全量声明面)', async () => {
@@ -246,10 +273,141 @@ describe('POST /oauth/<key>/connect · scopes body(降面授权)', () => {
});
});
+describe('POST /oauth/<key>/insufficient-scopes', () => {
+ const DECLARED_SCOPES = Array.from({ length: 64 }, (_, index) => `scope.${index}`);
+ const SCOPED: GhostOauthDecl = {
+ authorizeUrl: 'https://accounts.example.com/authorize',
+ tokenUrl: 'https://accounts.example.com/token',
+ scopes: DECLARED_SCOPES,
+ };
+ const SCOPED_SECRETS = new Map<string, GhostOauthDecl>([['acct', SCOPED]]);
+
+ function report(
+ body: string,
+ manager = fakeManager(),
+ onChanged = vi.fn(),
+ pathname = '/oauth/acct/insufficient-scopes',
+ ) {
+ return handleGhostOauthRequest({
+ method: 'POST',
+ pathname,
+ readBodyText: async () => body,
+ oauthSecrets: SCOPED_SECRETS,
+ manager,
+ ghostId: GHOST,
+ onChanged,
+ });
+ }
+
+ it('合法证据落默认账号并广播变更(重复条目由存取层去重),成功 204', async () => {
+ const manager = fakeManager();
+ const onChanged = vi.fn();
+ const outcome = await report(
+ JSON.stringify({ scopes: ['scope.1', 'scope.1', 'scope.2'] }),
+ manager,
+ onChanged,
+ );
+ expect(outcome.status).toBe(204);
+ expect(manager.reportInsufficientScopes).toHaveBeenCalledWith(
+ GHOST,
+ 'acct',
+ ['scope.1', 'scope.1', 'scope.2'],
+ DECLARED_SCOPES,
+ );
+ expect(onChanged).toHaveBeenCalledWith('acct');
+ });
+
+ it('证据未变时成功 204 但不广播,重复上报不空转投影与配置卡重评估', async () => {
+ const manager = fakeManager({ reportInsufficientScopes: vi.fn(() => 'unchanged' as const) });
+ const onChanged = vi.fn();
+ const outcome = await report(JSON.stringify({ scopes: ['scope.1'] }), manager, onChanged);
+ expect(outcome.status).toBe(204);
+ expect(onChanged).not.toHaveBeenCalled();
+ });
+
+ it('64 条边界放行;65 条拒绝', async () => {
+ const accepted = fakeManager();
+ expect((await report(JSON.stringify({ scopes: DECLARED_SCOPES }), accepted)).status).toBe(204);
+ expect(accepted.reportInsufficientScopes).toHaveBeenCalledWith(
+ GHOST,
+ 'acct',
+ DECLARED_SCOPES,
+ DECLARED_SCOPES,
+ );
+
+ const rejected = fakeManager();
+ expect(
+ (await report(JSON.stringify({ scopes: [...DECLARED_SCOPES, DECLARED_SCOPES[0]] }), rejected))
+ .status,
+ ).toBe(400);
+ expect(rejected.reportInsufficientScopes).not.toHaveBeenCalled();
+ });
+
+ it('任一未声明 scope 越界时整包 400,不落任何数据', async () => {
+ const manager = fakeManager();
+ const outcome = await report(
+ JSON.stringify({ scopes: ['scope.1', 'scope.not-declared'] }),
+ manager,
+ );
+ expect(outcome.status).toBe(400);
+ expect(manager.reportInsufficientScopes).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['非数组', { scopes: 'scope.1' }],
+ ['空数组', { scopes: [] }],
+ ['空字符串', { scopes: [''] }],
+ ['空白字符串', { scopes: [' '] }],
+ ['超长字符串', { scopes: ['x'.repeat(257)] }],
+ ['非字符串', { scopes: [42] }],
+ ])('%s → 400 且不入库', async (_name, body) => {
+ const manager = fakeManager();
+ expect((await report(JSON.stringify(body), manager)).status).toBe(400);
+ expect(manager.reportInsufficientScopes).not.toHaveBeenCalled();
+ });
+
+ it('未知 key 404;非 POST 405;持久化失败 500', async () => {
+ expect(
+ (
+ await report(
+ JSON.stringify({ scopes: ['scope.1'] }),
+ fakeManager(),
+ vi.fn(),
+ '/oauth/unknown/insufficient-scopes',
+ )
+ ).status,
+ ).toBe(404);
+ expect(
+ (
+ await handleGhostOauthRequest({
+ method: 'GET',
+ pathname: '/oauth/acct/insufficient-scopes',
+ readBodyText: async () => '',
+ oauthSecrets: SCOPED_SECRETS,
+ manager: fakeManager(),
+ ghostId: GHOST,
+ })
+ ).status,
+ ).toBe(405);
+ expect(
+ (
+ await report(
+ JSON.stringify({ scopes: ['scope.1'] }),
+ fakeManager({ reportInsufficientScopes: vi.fn(() => false as const) }),
+ )
+ ).status,
+ ).toBe(500);
+ });
+});
+
describe('账号操作', () => {
it('DELETE /oauth/<key>/accounts/<id> 断开 → 204', async () => {
const manager = fakeManager();
- const outcome = await call({ method: 'DELETE', pathname: '/oauth/acct/accounts/acc-1', manager });
+ const outcome = await call({
+ method: 'DELETE',
+ pathname: '/oauth/acct/accounts/acc-1',
+ manager,
+ });
expect(outcome.status).toBe(204);
expect(manager.disconnectAccount).toHaveBeenCalledWith(GHOST, 'acct', 'acc-1');
});
@@ -277,7 +435,9 @@ describe('账号操作', () => {
})
).status,
).toBe(404);
- expect((await call({ method: 'POST', pathname: '/oauth/acct/default', body: '{}' })).status).toBe(400);
+ expect(
+ (await call({ method: 'POST', pathname: '/oauth/acct/default', body: '{}' })).status,
+ ).toBe(400);
});
});
@@ -296,7 +456,10 @@ describe('路径与 key 准入', () => {
const outcome2 = await call({ method: 'PUT', pathname, body: '{}' });
expect([404, 405]).toContain(outcome2.status);
}
- expect((await call({ method: 'PUT', pathname: '/oauth/unknown/client', body: '{"clientId":"x"}' })).status).toBe(404);
+ expect(
+ (await call({ method: 'PUT', pathname: '/oauth/unknown/client', body: '{"clientId":"x"}' }))
+ .status,
+ ).toBe(404);
});
});
@@ -330,8 +493,12 @@ describe('tokenBroker 门控', () => {
it('brokered 凭证的 client 自填/清除通道一律 405', async () => {
const manager = fakeManager();
- await expect(callAs('xd-atlassian', 'PUT', '/oauth/acct/client', manager)).resolves.toMatchObject({ status: 405 });
- await expect(callAs('xd-atlassian', 'DELETE', '/oauth/acct/client', manager)).resolves.toMatchObject({ status: 405 });
+ await expect(
+ callAs('xd-atlassian', 'PUT', '/oauth/acct/client', manager),
+ ).resolves.toMatchObject({ status: 405 });
+ await expect(
+ callAs('xd-atlassian', 'DELETE', '/oauth/acct/client', manager),
+ ).resolves.toMatchObject({ status: 405 });
expect(manager.setClientConfig).not.toHaveBeenCalled();
expect(manager.clearClientConfig).not.toHaveBeenCalled();
});
@@ -345,32 +512,27 @@ describe('tokenBroker 门控', () => {
const blockedManager = fakeManager();
const blocked = await callAs('third-party', 'POST', '/oauth/acct/connect', blockedManager);
expect(blocked.status).toBe(200);
- expect(JSON.parse(blocked.body ?? '{}')).toMatchObject({ ok: false, error: 'BROKER_FORBIDDEN' });
+ expect(JSON.parse(blocked.body ?? '{}')).toMatchObject({
+ ok: false,
+ error: 'BROKER_FORBIDDEN',
+ });
expect(blockedManager.connectAccount).not.toHaveBeenCalled();
});
it('connect:可选择清单声明的备用 clientId;未声明值在端点拒绝', async () => {
const manager = fakeManager();
- const selected = await callAs(
- 'xd-atlassian',
- 'POST',
- '/oauth/acct/connect',
- manager,
- { clientId: 'global-cid' },
- );
+ const selected = await callAs('xd-atlassian', 'POST', '/oauth/acct/connect', manager, {
+ clientId: 'global-cid',
+ });
expect(selected.status).toBe(200);
expect(manager.connectAccount).toHaveBeenCalledWith('xd-atlassian', 'acct', BROKERED, {
clientId: 'global-cid',
});
const rejectedManager = fakeManager();
- const rejected = await callAs(
- 'xd-atlassian',
- 'POST',
- '/oauth/acct/connect',
- rejectedManager,
- { clientId: 'foreign-cid' },
- );
+ const rejected = await callAs('xd-atlassian', 'POST', '/oauth/acct/connect', rejectedManager, {
+ clientId: 'foreign-cid',
+ });
expect(rejected.status).toBe(400);
expect(rejectedManager.connectAccount).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
index af26e291b1..d3ddb386ec 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
@@ -6,7 +6,8 @@
* 协议(意识 settingsHtml 页面用,`fetch('/oauth')`):
* - GET /oauth → 200 + [{ key, clientConfigured, accounts }]
* (仅 source:'oauth' 的凭证;accounts 只含 {id,label,status,isDefault,
- * avatarDataUrl},零令牌字节——avatarDataUrl 是主机下载转码的头像小图);
+ * avatarDataUrl,scopeStale},零令牌字节——avatarDataUrl 是主机下载转码
+ * 的头像小图,scopeStale 是宿主据真实缺权证据或授权面快照计算的非阻塞提示);
* - PUT /oauth/<key>/client → body {"clientId":"...","clientSecret":"..."}
* 写入用户自填的 OAuth 客户端凭证(clientSecret 可省略 = 纯 PKCE),204;
* - DELETE /oauth/<key>/client → 清除 client 凭证,204(幂等);
@@ -18,6 +19,8 @@
* - DELETE /oauth/<key>/accounts/<id> → 断开账号,204(幂等);
* - POST /oauth/<key>/default → body {"accountId":"..."} 设默认账号,
* 204;账号不存在 404;
+ * - POST /oauth/<key>/insufficient-scopes → body {"scopes":[...]} 上报真实 API
+ * 返回的缺失权限证据;只接受当前清单声明内的 scope,成功 204;
* - 未声明 / 非 oauth 的 key → 404;坏 body / 空值 → 400;值超长 → 413;
* 其它 method → 405;保险库写失败 → 500(不外泄细节)。
*
@@ -46,9 +49,14 @@ export interface GhostOauthEndpointManager {
clientConfigured(ghostId: string, secretKey: string, decl?: GhostOauthDecl): boolean;
/** 用户是否自填过(UI 区分"内置应用身份 / 已自定义")。 */
clientCustomized(ghostId: string, secretKey: string): boolean;
- setClientConfig(ghostId: string, secretKey: string, clientId: string, clientSecret?: string): boolean;
+ setClientConfig(
+ ghostId: string,
+ secretKey: string,
+ clientId: string,
+ clientSecret?: string,
+ ): boolean;
clearClientConfig(ghostId: string, secretKey: string): void;
- listAccounts(ghostId: string, secretKey: string): GhostOauthAccountView[];
+ listAccounts(ghostId: string, secretKey: string, decl?: GhostOauthDecl): GhostOauthAccountView[];
connectAccount(
ghostId: string,
secretKey: string,
@@ -61,6 +69,13 @@ export interface GhostOauthEndpointManager {
): Promise<GhostOauthConnectResult>;
disconnectAccount(ghostId: string, secretKey: string, accountId: string): void;
setDefaultAccount(ghostId: string, secretKey: string, accountId: string): boolean;
+ /** 'unchanged' = 证据已在库未重写(调用方跳过广播);false = 无默认账号或写失败。 */
+ reportInsufficientScopes(
+ ghostId: string,
+ secretKey: string,
+ scopes: readonly string[],
+ declScopes: readonly string[],
+ ): 'stored' | 'unchanged' | false;
}
export async function handleGhostOauthRequest(args: {
@@ -79,7 +94,8 @@ export async function handleGhostOauthRequest(args: {
onChanged?: (secretKey: string) => void;
log?: { warn(message: string, meta?: Record<string, unknown>): void };
}): Promise<GhostOauthRequestOutcome> {
- const { method, pathname, readBodyText, oauthSecrets, networkHosts, manager, ghostId, log } = args;
+ const { method, pathname, readBodyText, oauthSecrets, networkHosts, manager, ghostId, log } =
+ args;
const notifyChanged = (secretKey: string): void => {
try {
args.onChanged?.(secretKey);
@@ -100,7 +116,7 @@ export async function handleGhostOauthRequest(args: {
clientConfigured: manager.clientConfigured(ghostId, key, keyDecl),
// 自填与内置分开报:settingsHtml 据此显示"内置应用身份 / 已自定义"。
clientCustom: manager.clientCustomized(ghostId, key),
- accounts: manager.listAccounts(ghostId, key),
+ accounts: manager.listAccounts(ghostId, key, keyDecl),
}));
return { status: 200, body: JSON.stringify(list) };
} catch (err) {
@@ -125,7 +141,8 @@ export async function handleGhostOauthRequest(args: {
try {
text = await readBodyText();
} catch (err) {
- if (err instanceof GhostKvError && err.code === 'TOO_LARGE') return { ok: false, status: 413 };
+ if (err instanceof GhostKvError && err.code === 'TOO_LARGE')
+ return { ok: false, status: 413 };
return { ok: false, status: 400 };
}
try {
@@ -188,7 +205,11 @@ export async function handleGhostOauthRequest(args: {
if (decl.tokenBroker !== undefined && !isOfficialGhostId(ghostId)) {
return {
status: 200,
- body: JSON.stringify({ ok: false, error: 'BROKER_FORBIDDEN', detail: 'tokenBroker 仅第一方官方意识可用' }),
+ body: JSON.stringify({
+ ok: false,
+ error: 'BROKER_FORBIDDEN',
+ detail: 'tokenBroker 仅第一方官方意识可用',
+ }),
};
}
// 可选 body {"scopes":[...],"clientId":"..."}:scopes 是本次授权申请
@@ -201,7 +222,8 @@ export async function handleGhostOauthRequest(args: {
const text = await readBodyText();
if (text.trim().length > 0) {
const parsed = JSON.parse(text) as unknown;
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return { status: 400 };
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
+ return { status: 400 };
const rawScopes = (parsed as Record<string, unknown>).scopes;
if (rawScopes !== undefined) {
if (!Array.isArray(rawScopes) || rawScopes.length === 0) return { status: 400 };
@@ -256,6 +278,40 @@ export async function handleGhostOauthRequest(args: {
}
}
+ if (action === 'insufficient-scopes' && segments.length === 2) {
+ if (method !== 'POST') return { status: 405 };
+ const parsed = await readJsonBody();
+ if (!parsed.ok) return { status: parsed.status };
+ const rawScopes = parsed.body.scopes;
+ if (!Array.isArray(rawScopes) || rawScopes.length === 0 || rawScopes.length > 64) {
+ return { status: 400 };
+ }
+ // 逐字属于声明面即形状合法(清单校验已保证声明 scope ≤200 字符、无空白),
+ // 任一越界整包 400;重复条目由存取层合并去重。
+ const declared = new Set(decl.scopes ?? []);
+ const scopes: string[] = [];
+ for (const scope of rawScopes) {
+ if (typeof scope !== 'string' || !declared.has(scope)) return { status: 400 };
+ scopes.push(scope);
+ }
+ try {
+ const stored = manager.reportInsufficientScopes(
+ ghostId,
+ secretKey,
+ scopes,
+ decl.scopes ?? [],
+ );
+ if (stored === false) return { status: 500 };
+ // 证据未变时不广播:插件在用户重连前会反复撞同一权限错误并 fire-and-forget
+ // 重报,无变更广播只会空转投影与在途配置卡的重评估循环。
+ if (stored === 'stored') notifyChanged(secretKey);
+ return { status: 204 };
+ } catch (err) {
+ log?.warn('ghost oauth 缺失 scope 证据入库失败', { ghostId, secretKey, err: String(err) });
+ return { status: 500 };
+ }
+ }
+
if (action === 'accounts' && segments.length === 3) {
if (method !== 'DELETE') return { status: 405 };
const accountId = segments[2];
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
index b850bae5e4..8a0df18cfd 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -382,6 +382,40 @@ describe('ghost_call 兜底拒绝', () => {
const deps = makeDeps();
const r = await deps.callGhostTool({ ghostId: 'art', tool: 'run', args: {} });
expect(r).toMatchObject({ ok: true, result: 'done' });
+ expect(r).not.toHaveProperty('setup');
+ expect(dispatchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('ready + scope stale 时成功 envelope 附非阻塞 reauthSuggest', async () => {
+ const assessment = {
+ state: 'ready' as const,
+ revision: 3,
+ groups: [],
+ reauthSuggest: {
+ ghostId: 'art',
+ secretKey: 'account',
+ missingScopes: ['scope.new'],
+ missingScopeCount: 1,
+ requirement: {
+ ref: 'secret:account',
+ kind: 'oauth' as const,
+ label: 'Account',
+ action: {
+ id: 'oauth_connect:secret:account',
+ kind: 'oauth_connect' as const,
+ },
+ },
+ },
+ };
+ setupAssessmentMock.mockReturnValue(assessment);
+
+ const result = await makeDeps().callGhostTool({ ghostId: 'art', tool: 'run', args: {} });
+
+ expect(result).toMatchObject({
+ ok: true,
+ result: 'done',
+ setup: { state: 'ready', reauthSuggest: { secretKey: 'account' } },
+ });
expect(dispatchMock).toHaveBeenCalledTimes(1);
});
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 55e3423b25..4964c2a75b 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -50,7 +50,11 @@ import {
import { classifyLocalAttachmentPath } from '../cindy-brain/ghostLocalPathGrant.js';
import { toolNotFoundMessage } from '../cindy-brain/pipeDispatcher.js';
import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
-import { deriveGhostSessionContext, type GhostSessionContextInjected } from '../../shared/ghost.js';
+import {
+ deriveGhostSessionContext,
+ type GhostSessionContextInjected,
+ type GhostSetupAssessment,
+} from '../../shared/ghost.js';
import { withCardToken } from '../cindy-brain/cardService.js';
import { drainGhostCallMedia } from '../cindy-brain/ghostMediaLedger.js';
import {
@@ -1110,8 +1114,9 @@ export function getCindyGhostsMcpDeps(
message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
};
}
+ let postGrantAssessment: GhostSetupAssessment;
try {
- const postGrantAssessment = getGhostSetupAssessment(ghostId);
+ postGrantAssessment = getGhostSetupAssessment(ghostId);
if (postGrantAssessment.state !== 'ready') {
return {
ok: false,
@@ -1130,6 +1135,7 @@ export function getCindyGhostsMcpDeps(
log.info('ghost grant-only: batch pre-granted', { ghostId, count: grant.hashes.length });
return {
ok: true,
+ ...(postGrantAssessment.reauthSuggest ? { setup: postGrantAssessment } : {}),
result: {
ok: true,
granted_count: grant.hashes.length,
@@ -1314,8 +1320,9 @@ export function getCindyGhostsMcpDeps(
message: toolNotFoundMessage(ghostId, tool, postCtx.manifest.tools),
};
}
+ let postCtxAssessment: GhostSetupAssessment;
try {
- const postCtxAssessment = getGhostSetupAssessment(ghostId);
+ postCtxAssessment = getGhostSetupAssessment(ghostId);
if (postCtxAssessment.state !== 'ready') {
return {
ok: false,
@@ -1358,7 +1365,12 @@ export function getCindyGhostsMcpDeps(
// 在意识未声明媒体字段时以 xdt_media_produced 注入,兜底 IM/hook 送达。
const producedMedia = drainGhostCallMedia(ghostId, callId);
const finalized = withCardToken(result, cardService.finalizeCall(callId), callId);
- return finalized.ok && producedMedia.length > 0 ? { ...finalized, producedMedia } : finalized;
+ if (!finalized.ok) return finalized;
+ // 附最后一道 gate(postCtx)的快照:它是派发前最新的 ready 判定。
+ const advisory = postCtxAssessment.reauthSuggest ? { setup: postCtxAssessment } : {};
+ return producedMedia.length > 0
+ ? { ...finalized, ...advisory, producedMedia }
+ : { ...finalized, ...advisory };
},
async forgeGuide(): Promise<string> {
return FORGE_GUIDE;
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index f8798d5742..b467b380cb 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -11,6 +11,7 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import {
AppWindow,
+ AlertTriangle,
ArrowUp,
Bot,
ChevronDown,
@@ -416,11 +417,14 @@ export function GhostPluginDetailView({
<div className={cn(DETAIL_SECTION_CONTENT_CLASS, 'space-y-3')}>
{detail.hasSettingsUi ? (
ghost ? (
- <GhostSettingsWebview
- ghost={ghost}
- title={t('settings.ghosts.detail.settingsTitle', { name: detail.name })}
- appearance="plugin"
- />
+ <>
+ {ghost.oauthScopeStale ? <OauthScopeStaleBadge /> : null}
+ <GhostSettingsWebview
+ ghost={ghost}
+ title={t('settings.ghosts.detail.settingsTitle', { name: detail.name })}
+ appearance="plugin"
+ />
+ </>
) : (
<div
className={cn(
@@ -468,6 +472,24 @@ export function GhostPluginDetailView({
);
}
+/** 宿主侧非阻塞角标;重新连接动作继续复用插件设置区已有入口。 */
+export function OauthScopeStaleBadge() {
+ const { t } = useTranslation();
+ return (
+ <div
+ role="status"
+ className="inline-flex w-fit max-w-full items-center gap-1.5 rounded-full bg-[var(--warning-bg-soft)] px-3 py-1.5 text-12 leading-5 text-[var(--text-secondary)]"
+ >
+ <AlertTriangle
+ size={13}
+ className="shrink-0 text-[var(--warning-fg)]"
+ aria-hidden="true"
+ />
+ <span>{t('settings.ghosts.detail.oauthScopeStale')}</span>
+ </div>
+ );
+}
+
/** Compact factual metadata with one shared color and stable product order. */
export function GhostPluginMetadata({
author,
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index eaf746cb1a..4e1e0e15c8 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -10,6 +10,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
const toastMocks = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
vi.mock('@/lib/toast', () => ({ toast: toastMocks }));
+vi.mock('@/cindy-brain/GhostSettingsWebview', () => ({
+ GhostSettingsWebview: () => <div data-testid="ghost-settings-webview" />,
+}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
@@ -46,6 +49,8 @@ vi.mock('react-i18next', () => ({
'settings.ghosts.detail.collapseInfoValue': `Collapse ${String(options?.label ?? '')}`,
'settings.ghosts.detail.panelNotDocked': 'Not docked',
'settings.ghosts.detail.cindyPrefs.noModels': 'No models available',
+ 'settings.ghosts.detail.oauthScopeStale':
+ 'This authorization does not include newly added permissions. Reconnect to enable them.',
};
return labels[key] ?? key;
},
@@ -127,6 +132,50 @@ afterEach(() => {
});
describe('Ghost plugin detail sections', () => {
+ it('shows a non-blocking stale OAuth scope badge inside the configuration section', () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ render(
+ <GhostPluginDetailView
+ ghost={{
+ manifest: {
+ schemaVersion: 2,
+ id: detail.id,
+ name: detail.name,
+ version: detail.version,
+ kind: 'chip',
+ entry: 'main.js',
+ slots: [],
+ settingsHtml: 'settings.html',
+ },
+ dir: detail.installDir ?? '/tmp/plugin',
+ enabled: true,
+ oauthScopeStale: { secretKey: 'account', missingScopeCount: 2 },
+ }}
+ detail={{ ...detail, hasSettingsUi: true }}
+ panelStatus="Docked"
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ const badge = screen.getByRole('status');
+ expect(badge.textContent).toContain('newly added permissions');
+ expect(badge.className).toContain('bg-[var(--warning-bg-soft)]');
+ expect(screen.getByTestId('ghost-settings-webview')).toBeTruthy();
+ });
+
it('keeps the detail surface on one centered content grid', () => {
vi.stubGlobal(
'ResizeObserver',
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fe7fba4006..e4aa0e0251 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3536,6 +3536,7 @@
"exportFileType": "Cindy Plugin",
"settingsTitle": "{{name}} Settings",
"settingsUnavailableUntilRestore": "Restore the plugin to use this configuration again.",
+ "oauthScopeStale": "This authorization does not include newly added permissions. Reconnect to grant them.",
"configurationTitle": "Configuration",
"openTool": "View details for Tool {{name}}",
"noToolDescription": "No description is available for this Tool.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e8d85717c8..9e814fb821 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3535,6 +3535,7 @@
"exportFileType": "Cindy プラグイン",
"settingsTitle": "{{name}} の設定",
"settingsUnavailableUntilRestore": "この設定を再び使用するには、プラグインを復元してください。",
+ "oauthScopeStale": "現在の認証には新しく追加された権限が含まれていません。再接続して権限を取得してください。",
"configurationTitle": "設定",
"openTool": "Tool {{name}} の詳細を表示",
"noToolDescription": "この Tool には説明がありません。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b1d2196d91..d53d78864d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3535,6 +3535,7 @@
"exportFileType": "Cindy 플러그인",
"settingsTitle": "{{name}} 설정",
"settingsUnavailableUntilRestore": "이 설정을 다시 사용하려면 플러그인을 복원하세요.",
+ "oauthScopeStale": "현재 인증에 새로 추가된 권한이 포함되어 있지 않습니다. 다시 연결해 권한을 받으세요.",
"configurationTitle": "설정",
"openTool": "Tool {{name}} 세부 정보 보기",
"noToolDescription": "이 Tool에는 설명이 없습니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 309dd0b3c6..bc8b196f3b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3535,6 +3535,7 @@
"exportFileType": "Cindy 插件",
"settingsTitle": "{{name}} 设置",
"settingsUnavailableUntilRestore": "恢复插件后可继续使用这项配置。",
+ "oauthScopeStale": "当前授权未包含插件新增权限,请重新连接补齐授权。",
"configurationTitle": "配置",
"openTool": "查看 Tool {{name}} 的详情",
"noToolDescription": "该 Tool 暂无描述。",
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 9f51f8178d..1db625652f 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -582,8 +582,19 @@ export interface GhostSecretExchangeDecl {
ttlSeconds?: number;
}
-/** OAuth 凭证:scopes 条数上限(超出拒装;确认框逐条展示要可读)。 */
-export const GHOST_OAUTH_SCOPES_MAX = 32;
+/**
+ * OAuth 凭证:scopes 条数上限(超出拒装;确认框逐条展示要可读)。
+ * 32→48(2026-08):原值按当时最大存量顶格(xd-feishu 老登录链全集 32 条),
+ * xd-feishu 补审批/表情/导入等能力到 41 条后,上限随最大存量演进。注意本校验
+ * 取值级"严出"(plugin-security-and-authoring.md §7):超 32 条的包在旧版客户端
+ * 拒装,插件市场铺开须等携带本值的客户端先行发布。
+ *
+ * 涨过 64 前必须同步两处只留了防御余量的 64 上限,否则会拒绝合法的缺权上报
+ * /静默判废 assessment:insufficient-scopes 端点的整包条数上限
+ * (runtime/ghostOauthEndpoint.ts)与 cindy-tools 的 SETUP_REAUTH_SCOPE_MAX
+ * (ghost/mcpServer.ts,包依赖方向不允许直接引用本常量)。
+ */
+export const GHOST_OAUTH_SCOPES_MAX = 48;
/** OAuth broker 模式可声明的备用 clientId 上限(默认 clientId 不计入)。 */
export const GHOST_OAUTH_CLIENT_ID_ALTERNATIVES_MAX = 8;
/** OAuth 凭证:extraAuthorizeParams 条数上限。 */
@@ -635,7 +646,7 @@ export interface GhostSecretOauthDecl {
clientIdAlternatives?: string[];
/** 可选:内置 client 的 secret(与 clientId 成对;纯 PKCE 服务商可省略)。 */
clientSecret?: string;
- /** 申请的 scope 列表(0–32 条,确认框逐条展示;缺省 = 不带 scope 参数)。 */
+ /** 申请的 scope 列表(0–48 条,确认框逐条展示;缺省 = 不带 scope 参数)。 */
scopes?: string[];
/**
* 可选:authorize URL 里 scope 参数的拼接分隔符。OAuth 标准是空格(缺省),
@@ -1075,6 +1086,26 @@ export interface GhostSetupAssessmentGroup {
items: GhostSetupAssessmentItem[];
}
+/**
+ * 插件仍可调用、但默认 OAuth 账号的全量授权面落后于当前清单时的非阻塞建议。
+ * 只含 scope 名称与 Host 生成的动作引用,不含令牌或 client 凭证。
+ */
+export interface GhostSetupReauthSuggest {
+ ghostId: string;
+ secretKey: string;
+ missingScopes: string[];
+ missingScopeCount: number;
+ requirement: {
+ ref: string;
+ kind: 'oauth';
+ label: string;
+ action: {
+ id: string;
+ kind: 'oauth_connect';
+ };
+ };
+}
+
/**
* Setup Runtime 的完整判定结果。groups 之间 all-of,组内 any-of;
* revision 由 Host 变更总线维护,用于丢弃过期卡片更新。
@@ -1083,6 +1114,8 @@ export interface GhostSetupAssessment {
state: 'ready' | 'required';
revision: number;
groups: GhostSetupAssessmentGroup[];
+ /** ready 语义不变;Agent 可据此建议用户重新连接,但不得拦截当前调用。 */
+ reauthSuggest?: GhostSetupReauthSuggest;
}
/** Agent 可选提供的展示编排;身份、Action 和完成状态仍由 Host 决定。 */
@@ -1314,6 +1347,11 @@ export interface InstalledGhost {
* 文件缺失或超限时缺省)。renderer 直接作 <img src> 用,无需 loading 态。
*/
iconDataUrl?: string;
+ /** 插件详情页宿主角标所需的最小陈旧授权投影;不含账号或 scope 明细。 */
+ oauthScopeStale?: {
+ secretKey: string;
+ missingScopeCount: number;
+ };
}
/** 插件包的来源与审核等级;决定 UI 徽标,不改变运行时 slot 权限。 */
diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
index 5418af1cc7..d4c08570a9 100644
--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
@@ -60,6 +60,27 @@ function parsePayload(result: {
return JSON.parse(result.content[0].text) as Record<string, unknown>;
}
+const READY_WITH_REAUTH_SUGGEST = {
+ state: "ready" as const,
+ revision: 9,
+ groups: [],
+ reauthSuggest: {
+ ghostId: "xd-feishu",
+ secretKey: "feishu_account",
+ missingScopes: ["approval:task:read"],
+ missingScopeCount: 1,
+ requirement: {
+ ref: "secret:feishu_account",
+ kind: "oauth" as const,
+ label: "飞书账号",
+ action: {
+ id: "oauth_connect:secret:feishu_account",
+ kind: "oauth_connect" as const,
+ },
+ },
+ },
+};
+
describe("cindy_ghosts · ghost_list(总机接线簿,现查现报)", () => {
it("返回唤醒中的意识与工具,附调用提示", async () => {
const result = await handleGhostList(fakeDeps());
@@ -74,6 +95,23 @@ describe("cindy_ghosts · ghost_list(总机接线簿,现查现报)", () => {
expect(String(payload.hint)).toContain("ghost_call");
});
+ it("ready assessment 的非阻塞重连建议随 ghost_list 透传", async () => {
+ const result = await handleGhostList(
+ fakeDeps({
+ listAwakeGhosts: async () => [
+ {
+ id: "xd-feishu",
+ name: "XD Feishu",
+ tools: [],
+ setup: READY_WITH_REAUTH_SUGGEST,
+ },
+ ],
+ }),
+ );
+ const ghosts = parsePayload(result).ghosts as Array<{ setup?: unknown }>;
+ expect(ghosts[0].setup).toEqual(READY_WITH_REAUTH_SUGGEST);
+ });
+
it("setup assessment 由 Host 脱敏生成并原样透传", async () => {
const setup = {
state: "required" as const,
@@ -250,7 +288,9 @@ describe("cindy_ghosts · ghost_call(派活透传)", () => {
ghost_id: "art",
tool: "gen_image",
});
- expect(parsePayload(result).ok).toBe(true);
+ const payload = parsePayload(result);
+ expect(payload.ok).toBe(true);
+ expect(payload).not.toHaveProperty("setup");
expect(callGhostTool).toHaveBeenCalledWith({
ghostId: "art",
tool: "gen_image",
@@ -258,6 +298,24 @@ describe("cindy_ghosts · ghost_call(派活透传)", () => {
});
});
+ it("成功调用可附 setup.reauthSuggest,仍保持 ok:true", async () => {
+ const result = await handleGhostCall(
+ fakeDeps({
+ callGhostTool: async () => ({
+ ok: true,
+ result: { done: true },
+ setup: READY_WITH_REAUTH_SUGGEST,
+ }),
+ }),
+ { ghost_id: "xd-feishu", tool: "call_tool" },
+ );
+ expect(parsePayload(result)).toMatchObject({
+ ok: true,
+ result: { done: true },
+ setup: { state: "ready", reauthSuggest: { secretKey: "feishu_account" } },
+ });
+ });
+
it("setup_plan 从 MCP snake_case 转成 Host camelCase,且绝不进入插件 args", async () => {
const callGhostTool = vi
.fn()
diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.ts
index 238aec414a..7a9df11ffb 100644
--- a/packages/cindy-tools/src/ghost/mcpServer.ts
+++ b/packages/cindy-tools/src/ghost/mcpServer.ts
@@ -113,8 +113,9 @@ const SETUP_PLAN_MAX_TITLE_LENGTH = 120;
const SETUP_PLAN_MAX_DESCRIPTION_LENGTH = 500;
/**
- * ghost_call 顶层 setup_plan schema。snake_case 仅存在于 Agent/MCP 边界;
- * handleGhostCall 会转成 camelCase 后单独交给 Host,绝不混入插件 args。
+ * ghost_call 顶层 setup_plan schema。required 配置卡与 ready 态 reauthSuggest
+ * 重连卡共用该形状;snake_case 仅存在于 Agent/MCP 边界,handleGhostCall
+ * 会转成 camelCase 后单独交给 Host,绝不混入插件 args。
* 导出仅供边界单测,未从 package root 暴露。
*/
export const ghostSetupPlanInputSchema = z
@@ -216,6 +217,9 @@ const SETUP_REQUIREMENT_KINDS = new Set([
"client_config",
]);
const SETUP_REQUIREMENT_STATES = new Set(["missing", "expired", "satisfied"]);
+// 对主机声明上限 GHOST_OAUTH_SCOPES_MAX(desktop shared/ghost.ts,当前 48;包依赖
+// 方向不允许引用)只留防御余量;该值涨过 64 时必须同步,否则整份 assessment 判废。
+const SETUP_REAUTH_SCOPE_MAX = 64;
function sanitizeSetupAction(
raw: unknown,
@@ -352,10 +356,68 @@ export function sanitizeGhostSetupAssessment(
}
groups.push({ id: group.id, mode: "any_of", items });
}
+ let reauthSuggest: CindyGhostSetupAssessment["reauthSuggest"];
+ if (value.reauthSuggest !== undefined) {
+ // 在场即严:非法 reauthSuggest 判废整份 assessment,与缺省合法互补。
+ reauthSuggest = sanitizeSetupReauthSuggest(value.reauthSuggest) ?? undefined;
+ if (!reauthSuggest) return null;
+ }
return {
state: value.state as CindyGhostSetupAssessment["state"],
revision: value.revision as number,
groups,
+ ...(reauthSuggest ? { reauthSuggest } : {}),
+ };
+}
+
+/**
+ * reauthSuggest 的独立 sanitize(与 sanitizeSetupAction 等"一形状一函数"
+ * 同款)。action 部分复用 sanitizeSetupAction —— 由它统一收 id 非空 + 256
+ * 上界与 kind 白名单,再钉死本形状只认 oauth_connect。
+ */
+function sanitizeSetupReauthSuggest(
+ raw: unknown,
+): NonNullable<CindyGhostSetupAssessment["reauthSuggest"]> | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const suggest = raw as Record<string, unknown>;
+ const requirement = suggest.requirement;
+ if (!requirement || typeof requirement !== "object" || Array.isArray(requirement)) return null;
+ const req = requirement as Record<string, unknown>;
+ const action = sanitizeSetupAction(req.action);
+ if (!action || action.kind !== "oauth_connect") return null;
+ if (
+ typeof suggest.ghostId !== "string" ||
+ suggest.ghostId.length === 0 ||
+ suggest.ghostId.length > 128 ||
+ typeof suggest.secretKey !== "string" ||
+ suggest.secretKey.length === 0 ||
+ suggest.secretKey.length > 128 ||
+ !Array.isArray(suggest.missingScopes) ||
+ suggest.missingScopes.length === 0 ||
+ suggest.missingScopes.length > SETUP_REAUTH_SCOPE_MAX ||
+ !suggest.missingScopes.every(
+ (scope) => typeof scope === "string" && scope.length > 0 && scope.length <= 256,
+ ) ||
+ suggest.missingScopeCount !== suggest.missingScopes.length ||
+ typeof req.ref !== "string" ||
+ req.ref.length === 0 ||
+ req.kind !== "oauth" ||
+ typeof req.label !== "string" ||
+ req.label.length === 0
+ ) {
+ return null;
+ }
+ return {
+ ghostId: suggest.ghostId,
+ secretKey: suggest.secretKey,
+ missingScopes: [...suggest.missingScopes] as string[],
+ missingScopeCount: suggest.missingScopes.length,
+ requirement: {
+ ref: req.ref,
+ kind: "oauth",
+ label: req.label,
+ action: { id: action.id, kind: "oauth_connect" },
+ },
};
}
@@ -570,7 +632,9 @@ export async function handleGhostCall(
// IM/hook 出站消费它,保证"意识画卡后删字段"也不影响媒体送达 IM 用户。
// 声明了媒体字段(含 xdt_audio_tracks)时以声明为准,账本不注入
// (声明是意图表达,能覆盖 render:false 抑制等语义)。
- const { producedMedia, ...resultForModel } = result;
+ const { producedMedia, setup: unsafeSetup, ...resultForModel } = result;
+ const setup = sanitizeGhostSetupAssessment(unsafeSetup);
+ const advisory = setup?.state === "ready" && setup.reauthSuggest ? { setup } : {};
const declaredMedia = [
"xdt_image_urls",
"xdt_video_urls",
@@ -611,6 +675,7 @@ export async function handleGhostCall(
: {};
return textResult({
...resultForModel,
+ ...advisory,
...hoisted,
...producedFallback,
...mediaHint,
@@ -789,7 +854,7 @@ export function createCindyGhostsMcpServer(
setup_plan: ghostSetupPlanInputSchema
.optional()
.describe(
- "可选:当 ghost_list 对目标插件返回 setup.state=required 时,基于该 assessment 编排 Ask 风格配置卡。assessment_revision 必须原样带回;requirement_refs 与 action_id 只能选 Host 给出的引用和动作。每个未满足 any_of 组里的所有可执行选项都必须保留为独立 step,让用户看到完整选择;Host 会拒绝隐藏任一合法配置路径的 plan。文案保持克制:单字段配置只写一句必要说明,不要在 intro、step title、description 中重复插件名、字段 label 或 Host hint。Host 会校验并执行动作,配置完成后继续本次 ghost_call;本字段不会进入插件 args。不要提供插件名、icon、URL、凭证值或完成状态。用户取消会返回 SETUP_CANCELLED;无交互面返回 SETUP_REQUIRED + 脱敏 setup,都不要自动重试。",
+ "可选:当 ghost_list 对目标插件返回 setup.state=required 时,基于该 assessment 编排 Ask 风格配置卡。assessment_revision 必须原样带回;requirement_refs 与 action_id 只能选 Host 给出的引用和动作。每个未满足 any_of 组里的所有可执行选项都必须保留为独立 step,让用户看到完整选择;Host 会拒绝隐藏任一合法配置路径的 plan。成功结果若带 setup.reauthSuggest,插件仍可用,但当前授权未含插件新增权限;通常只在插件返回权限或 scope 错误后,下一次 ghost_call 可携带只引用该 requirement 的单步 setup_plan 弹出重新连接卡,未报错时不要主动打断用户。文案保持克制:单字段配置只写一句必要说明,不要在 intro、step title、description 中重复插件名、字段 label 或 Host hint。Host 会校验并执行动作,配置完成后继续本次 ghost_call;本字段不会进入插件 args。不要提供插件名、icon、URL、凭证值或完成状态。用户取消会返回 SETUP_CANCELLED;无交互面返回 SETUP_REQUIRED + 脱敏 setup,都不要自动重试。",
),
},
async (input, extra) =>
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index 8ae9c5a7b0..df402f0454 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -83,6 +83,22 @@ export interface CindyGhostSetupAssessment {
actions: CindyGhostSetupAllowedAction[];
}>;
}>;
+ /** 插件仍 ready 时的非阻塞重连建议;不得解释为 SETUP_REQUIRED。 */
+ reauthSuggest?: {
+ ghostId: string;
+ secretKey: string;
+ missingScopes: string[];
+ missingScopeCount: number;
+ requirement: {
+ ref: string;
+ kind: 'oauth';
+ label: string;
+ action: {
+ id: string;
+ kind: 'oauth_connect';
+ };
+ };
+ };
}
/** Agent 为 Ask 风格配置卡编排的展示步骤;Host 校验后才可采用。 */
@@ -133,6 +149,8 @@ export type CindyGhostCallResult =
| {
ok: true;
result: unknown;
+ /** ready 语义不变;只在有非阻塞重连建议时由 Host 附加。 */
+ setup?: CindyGhostSetupAssessment;
/**
* 本次调用期间由主机实际入库(cindy-media)的媒体地址账本(可选,
* host 按 ghostId+callId 记账后随结果带回)。这是**主机侧事实**,