Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(device-link): isolate relay retries and restore retained deployments

MagicLizi1f375185c2f2
diff --git a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
index 4398273804..e15e981dc7 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
@@ -61,7 +61,8 @@ describe('mobile voice credential sync desktop bootstrap path', () => {
it('每个 relay 连接代上线时从设备目录补齐展示名与已在线桌面', () => {
const deviceLinkHost = readFileSync(resolve(mainRoot, 'device-link/index.ts'), 'utf8');
- expect(deviceLinkHost).toContain("serverApiFetch<DeviceDirectoryResponse>('/api/device-link/devices'");
+ // 自建中转必须经统一路由,避免目录刷新把 Cindy 账号 token 发给用户服务器。
+ expect(deviceLinkHost).toContain("deviceLinkApiFetch<DeviceDirectoryResponse>('/api/device-link/devices'");
const onlineBranch = deviceLinkHost.indexOf("if (status === 'online') {");
const seedCachedNames = deviceLinkHost.indexOf(
'seedControllerDisplayNamesFromLastKnown();',
diff --git a/apps/desktop/src/main/device-link/__tests__/deviceLinkApi.test.ts b/apps/desktop/src/main/device-link/__tests__/deviceLinkApi.test.ts
index f3c41be3f7..8be874869b 100644
--- a/apps/desktop/src/main/device-link/__tests__/deviceLinkApi.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/deviceLinkApi.test.ts
@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({
getAccessToken: vi.fn(() => 'account-access-token'),
refresh: vi.fn(async () => true),
invalidateSession: vi.fn(),
+ officialBase: 'https://device-link.official.invalid',
relay: null as null | import('../selfHostedRelayRouting').ActiveSelfHostedRelay,
}));
@@ -28,7 +29,7 @@ vi.mock('../../authManager', () => ({
vi.mock('../../i18n.js', () => ({ getResolvedMainLocale: () => 'zh-CN' }));
vi.mock('../../logger', () => ({ createLogger: () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() }) }));
vi.mock('../../clientEndpointsService.js', () => ({
- getClientEndpoint: () => 'https://device-link.official.invalid',
+ getClientEndpoint: () => mocks.officialBase,
}));
vi.mock('../index.js', () => ({ deviceLinkApiBase: () => 'http://192.168.1.20:47820', remoteBackgroundInvoke: vi.fn() }));
vi.mock('../providerShareGuest.js', () => ({ getReceivedShares: () => [] }));
@@ -50,6 +51,7 @@ describe('deviceLinkApiFetch', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.relay = null;
+ mocks.officialBase = 'https://device-link.official.invalid';
});
// /models 复用真实目录读取与 API 路由;旧 caller 直接用 serverApiFetch 会把官方 token 发到自建中转。
@@ -92,6 +94,33 @@ describe('deviceLinkApiFetch', () => {
expect(mocks.invalidateSession).not.toHaveBeenCalled();
});
+ // #7722 discussion_r4402946273:刷新期间切到自建中转后,官方重试只能跟随官方区域,
+ // 不能把刷新后的账号 token 交给自建服务器。最小输入:官方 401 → 切中转/区域 → refresh 成功。
+ it('keeps an official retry on official endpoints when the selected relay changes during refresh', async () => {
+ mocks.netFetch
+ .mockResolvedValueOnce(new Response(JSON.stringify({ error: { code: 'TOKEN_EXPIRED' } }), { status: 401 }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ devices: [] }), { status: 200 }));
+ mocks.refresh.mockImplementationOnce(async () => {
+ mocks.relay = {
+ baseUrl: 'http://192.168.1.20:47820', credential: 'relay-credential', role: 'member',
+ relayId: 'r', name: 'Home', deviceId: 'pc', signingSeed: 'A'.repeat(43), ownerPublicKey: 'A'.repeat(43),
+ };
+ mocks.officialBase = 'https://device-link.new-region.invalid';
+ return true;
+ });
+
+ await expect(deviceLinkApiFetch('/api/device-link/devices')).resolves.toEqual({ devices: [] });
+
+ expect(mocks.netFetch.mock.calls.map(([url, init]) => ({
+ url, authorization: (init as { headers: Record<string, string> }).headers.Authorization,
+ }))).toEqual([
+ { url: 'https://device-link.official.invalid/api/device-link/devices', authorization: 'Bearer account-access-token' },
+ { url: 'https://device-link.new-region.invalid/api/device-link/devices', authorization: 'Bearer account-access-token' },
+ ]);
+ expect(mocks.refresh).toHaveBeenCalledTimes(1);
+ expect(mocks.invalidateSession).not.toHaveBeenCalled();
+ });
+
it('keeps the official relay on the account token', async () => {
mocks.netFetch.mockResolvedValue(new Response(JSON.stringify({ devices: [] }), { status: 200 }));
diff --git a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts
index 7be7474160..a91d325d1f 100644
--- a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts
@@ -153,6 +153,25 @@ describe('deployRelayToServer', () => {
expect(configure.command).toContain(`'203.0.113.10' '0.0.0.0' 'https://203.0.113.10' '1'`);
});
+ // #7722 discussion_r4402946293:保留数据卸载后 Node 已移除,初次检查无法读取身份。
+ // 先恢复运行环境再读取;匹配身份才能继续,其他主人或仍不可读时不能上传/写配置。tier: unit。
+ it.each([
+ [`2 ${init.relayId} ${init.ownerPublicKey}`, true],
+ [`2 ${init.relayId} ${'R'.repeat(43)}`, false],
+ ['unknown', false],
+ ])('rechecks retained data after restoring Node: %s', async (state, matches) => {
+ let inspections = 0;
+ mocks.responses['relay-deploy-inspect'] = () =>
+ ok(`STATE ${++inspections === 1 ? 'unknown' : state}\n`);
+ const { error } = await run();
+ expect(mocks.commands.some(c => c.label === 'relay-deploy-runtime')).toBe(true);
+ expect(inspections).toBe(2);
+ if (matches) expect(error).toBeNull();
+ else expect(error).toMatchObject({ code: 'RELAY_MISMATCH' });
+ expect(mocks.commands.some(c => c.label === 'relay-deploy-upload')).toBe(matches);
+ expect(mocks.commands.some(c => c.label === 'relay-deploy-configure')).toBe(matches);
+ });
+
it('does not access another account’s SSH connection after the owner changes while connecting', async () => {
let current = true;
mocks.ensureReady.mockImplementationOnce(async () => { current = false; });
diff --git a/apps/desktop/src/main/device-link/deviceLinkApi.ts b/apps/desktop/src/main/device-link/deviceLinkApi.ts
index 45e767031c..7ea77877df 100644
--- a/apps/desktop/src/main/device-link/deviceLinkApi.ts
+++ b/apps/desktop/src/main/device-link/deviceLinkApi.ts
@@ -19,7 +19,11 @@ export function deviceLinkApiFetch<T>(
opts: Omit<ApiFetchOptions, 'baseUrl' | 'token' | 'authorization'> = {},
): Promise<T> {
const relay = activeSelfHostedRelay();
- if (!relay) return serverApiFetch<T>(apiPath, { ...opts, baseUrl: resolveDeviceLinkApiBase });
+ if (!relay) return serverApiFetch<T>(apiPath, {
+ ...opts,
+ // 401 重试可随账号区域更新官方端点,不能随中转选择跨到自建地址。
+ baseUrl: () => getClientEndpoint('deviceLinkApiBaseUrl'),
+ });
return serverApiFetch<T>(apiPath, {
...opts,
baseUrl: relay.baseUrl,
diff --git a/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts b/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts
index 48328a0bed..f604620fd5 100644
--- a/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts
+++ b/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts
@@ -392,11 +392,14 @@ export async function deployRelayToServer(params: DeployParams): Promise<{ relay
const busy = inspected.get('BUSY') ?? [];
if (busy.length > 0) throw new RelayDeployError('PORT_BUSY', busy.join(', '));
const state = first(inspected, 'STATE');
- if (state && !params.replaceExisting) {
- const [, relayId, ownerPublicKey] = state.split(' ');
+ const assertExistingIdentity = (existingState: string) => {
+ const [, relayId, ownerPublicKey] = existingState.split(' ');
if (relayId !== params.init.relayId || ownerPublicKey !== params.init.ownerPublicKey) {
throw new RelayDeployError('RELAY_MISMATCH');
}
+ };
+ if (state && state !== 'unknown' && !params.replaceExisting) {
+ assertExistingIdentity(state);
}
params.onStep('runtime');
@@ -407,6 +410,14 @@ export async function deployRelayToServer(params: DeployParams): Promise<{ relay
});
expectOk(runtime, 'DOWNLOAD_FAILED');
+ // 保留数据卸载会移除 Node。恢复运行环境后重读身份,上传和配置仍须等身份匹配。
+ if (state === 'unknown' && !params.replaceExisting) {
+ const restored = parseLines((await remote.root(INSPECT_SCRIPT, [], { label: 'relay-deploy-inspect' })).stdout);
+ const restoredState = first(restored, 'STATE');
+ if (!restoredState) throw new RelayDeployError('RELAY_MISMATCH');
+ assertExistingIdentity(restoredState);
+ }
+
params.onStep('upload');
const uploaded = expectOk(
await remote.root(UPLOAD_SCRIPT, [], { input: bundle, timeoutMs: 120_000, label: 'relay-deploy-upload' }),
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 085f49bb3b..7edc6ddfac 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -274,7 +274,8 @@ stream 匹配后才处理;信令不进入业务可靠 FIFO,也不走直连
`buildRelayJoinLink` / `parseRelayJoinLink` 生成与解析,Desktop 与 Mobile 共用 `fetchRelayInfo` /
`submitRelayPairRequest` / `waitForRelayApproval`。`DeviceLinkClient.authorizationScheme` 也可传函数,每次建连前取值。
- 客户端:Desktop 的地址与凭证经 `device-link/selfHostedRelayRouting.ts`(零依赖)读取,REST 统一走
- `deviceLinkApi.ts`(自建中转时带 `CindyRelay`、跳过账号刷新与会话失效);Mobile 见 `apps/mobile/src/device-link/selfHostedRelay*.ts`。
+ `deviceLinkApi.ts`(自建中转时带 `CindyRelay`、跳过账号刷新与会话失效;官方请求刷新后的重试只重读官方区域端点,
+ 不随中转选择切到自建地址);Mobile 见 `apps/mobile/src/device-link/selfHostedRelay*.ts`。
兼容:未选择自建中转时,客户端与官方 relay 的行为不变(没有登记中转来源或使用官方中转时一律回到原路径)。
旧客户端没有入口;旧版手机无法加入自建中转。互通验证:`pnpm --filter @cindy/device-link-relay run interop`