Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): recover pending link after receiver restart
MagicLizic9fc78ad6b00
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 731e65a177..86425ab682 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -274,6 +274,7 @@ stream 匹配后才处理;信令不进入业务可靠 FIFO,也不走直连- 签名上下文 `cindy-relay-frame/2` 包含接收端启动挑战 `r`,避免接收端重启后旧请求再次执行。共享客户端消费保留的 `device-link:relay-auth` push 请求/响应;仅认证请求允许空挑战,不进入业务分发、不建立控制链路、不改变远控开关。待发队列按稳定签名身份和设备隔离,超时/断线/换身份后不发送旧请求。+ 接收端重启且证书迟到时仅发有界认证探测;验签通过的新挑战只可恢复本机仍有效的原 `link-open`,保持请求 ID、签名身份与期限,不能恢复任意旧业务写操作。中转已有 push 与 opaque auth 转发足够支持,无需新增协议 kind 或修改路由;互通同时覆盖关闭远控的手机接收插件同步与未建链查询。此自建功能尚未发布,开发期间旧的无 `r` 签名客户端需同步更新;官方客户端路径无此交换。- 加入申请必须带 `publicKey` / `proof`,同意必须带证书;`/relay/info` 的 `features` 声明 `device-signatures-v1`。diff --git a/docs/self-hosted-relay-plan.md b/docs/self-hosted-relay-plan.mdindex a5389f0ac2..f797b261c1 100644--- a/docs/self-hosted-relay-plan.md+++ b/docs/self-hosted-relay-plan.md@@ -669,6 +669,8 @@ App 内不加扫码组件:加一个会改变原生指纹,需要冷更。接收端验签后直接消费认证消息,不进入业务 handler、不建立远控链路,也不改变开关、订阅或权限。因而关闭远控的手机仍能接收插件同步;未建链的允许查询沿用原有权限边界。首次业务消息在客户端按设备有界排队,认证重试不重连共享 socket;超时、断线或签名身份变化后不再发送旧请求。+ 电脑重启且证书尚未加载时,只允许有界的无业务认证探测;未验签消息仍丢弃。对端新挑战验签通过后,+ 发送端可重签仍在等待的原 `link-open`,沿用原请求 ID、签名身份和超时期限;不重发任意旧写请求,已取消的建链不会恢复。- `s`:Ed25519 签名。签名对象是以下内容的 SHA-256:- `JSON.stringify(["cindy-relay-frame/2", 中转ID, 发送设备, 收件设备, kind, id, t, b, r, c])`;- 换行;diff --git a/packages/device-link/TESTING.md b/packages/device-link/TESTING.mdindex b478068e12..96d9468420 100644--- a/packages/device-link/TESTING.md+++ b/packages/device-link/TESTING.md@@ -81,7 +81,8 @@ pnpm --filter @cindy/device-link-relay run interop设备签名:主机与控制端都像正式 Desktop / Mobile 一样核对每一条对端消息。任何绕过签名的发送路径都会让接收端丢帧、恢复流程超时(见 docs/self-hosted-relay-plan.md §16)。不设这个变量时行为与官方 relay 的互通完全相同。开启设备签名时,还先验证关闭远控的控制端可通过独立认证挑战接收插件同步,以及未建链的允许查询;-认证 push 不进入业务分发。共享客户端单测另验证重启后旧写请求拒绝、认证期间超时/换身份不再发送及另一设备不受影响。+认证 push 不进入业务分发。共享客户端单测另验证重启后旧写请求拒绝、热发送端遇到冷证书重启接收端时仍完成原建链,+原请求 ID/身份/期限不变,超时/取消/换身份不再发送;未知来源探测有界,未验签业务不分发,另一设备不受影响。仅使用**专用隔离测试环境**签发的两台测试设备身份,不能使用日常账号或正在连接的设备:用例会注册一个允许被控的内存 host,并主动断开自己创建的 socket。脚本不启动、停止、diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 35caaf45a9..8838885f3a 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -526,6 +526,91 @@ describe('self-hosted relay device signatures', () => {} finally { host.stop(); phone.stop(); vi.useRealTimers(); }});+ // #7722 discussion_r4403909690:手机保持热进程、电脑重启后,旧挑战拒绝不能丢掉仍有效的首次建链。+ // 重建真实接收Client与认证器,发送端socket保留;覆盖冷证书,超时/取消/换身份不能补发。tier: unit。+ it.each(['connected', 'cold-certificates', 'expired', 'closed', 'identity-changed'] as const)('handles a receiver restart while the original link request is %s', async mode => {+ vi.useFakeTimers();+ const relay = new MemoryRelay();+ const sockets = vi.spyOn(relay, 'makeWebSocket');+ const signer = signingPeers(['host', 'phone']);+ let hostAuth = signer('host');+ const makeHost = () => makeRelayClient(relay, 'host', { requestTimeoutMs: 2_000 }, { frameAuth: () => frameAuth(hostAuth) });+ let host = makeHost();+ let phoneAuth = signer('phone');+ const phone = makeRelayClient(relay, 'phone', { requestTimeoutMs: 2_000 }, { frameAuth: () => frameAuth(phoneAuth) });+ const received: Envelope[] = [];+ const accept = (client: DeviceLinkClient) => client.onFrame(env => {+ if (env.kind !== 'link-open') return;+ received.push(env);+ client.sendLinkAccept(env.src!, env.id!, { appVersion: '1', allowlistHash: 'hash' });+ });+ const pump = () => relay.settle(async () => { await vi.advanceTimersByTimeAsync(0); });+ const opening = () => phone.openLink('host', { controllerName: 'Phone', protocolVersion: 1, appVersion: '1' });+ accept(host);+ try {+ host.start(); phone.start(); await pump();+ const initial = opening(); await pump(); await initial;+ expect(phoneAuth.peerChallenge('host')).toBe('ready');+ host.stop(); hostAuth = signer('host');+ if (mode === 'cold-certificates') hostAuth.setCertificates([]);+ host = makeHost(); accept(host); host.start(); await pump();+ received.length = 0;+ const settled = vi.fn();+ const restored = opening();+ void restored.then(value => settled(value), error => settled(error));+ if (mode === 'identity-changed') phoneAuth = signer('phone');+ if (mode === 'expired') await vi.advanceTimersByTimeAsync(2_001);+ if (mode === 'closed') phone.closeLink('host', 'user');+ await pump();+ if (mode === 'cold-certificates') {+ expect(settled).not.toHaveBeenCalled();+ expect(received).toHaveLength(0);+ hostAuth.setCertificates(signer.certs);+ await vi.advanceTimersByTimeAsync(1_000);+ await pump();+ }+ expect(settled).toHaveBeenCalledOnce();+ if (mode === 'connected' || mode === 'cold-certificates') {+ await expect(restored).resolves.toMatchObject({ appVersion: '1' });+ expect(received).toHaveLength(1);+ const attempts = (relay.deliveredTo.get('host') ?? []).filter(env => env.kind === 'link-open');+ expect(attempts.at(-1)!.id).toBe(attempts.at(-2)!.id);+ } else {+ await expect(restored).rejects.toMatchObject({ code: mode === 'expired' ? 'INVOKE_TIMEOUT'+ : mode === 'closed' ? 'LINK_NOT_OPEN' : 'NOT_CONNECTED' });+ expect(received).toHaveLength(0);+ }+ expect(sockets.mock.calls.filter(([id]) => id === 'phone')).toHaveLength(1);+ } finally { host.stop(); phone.stop(); vi.useRealTimers(); }+ });++ // 冷证书恢复会探测未知来源;恶意中转不能借此执行未验签业务或无限保留任意来源。tier: unit。+ it('bounds unauthenticated probes without retaining or delivering the rejected business frame', async () => {+ vi.useFakeTimers();+ const signer = signingPeers(['dev-self', 'peer']);+ const signerSelf = signer('dev-self'), peer = signer('peer');+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 1_000 }, frameAuth: () => frameAuth(signerSelf) });+ signerSelf.setCertificates([]);+ const received = vi.fn();+ h.client.onFrame(received);+ try {+ h.client.start(); await vi.advanceTimersByTimeAsync(0); h.current().ack();+ const frame = { v: 1, kind: 'invoke', id: 'rejected', dst: 'dev-self',+ payload: { channel: 'maker:send', args: ['must not execute'] } } as Envelope;+ for (const src of ['', 'x'.repeat(257), ...Array.from({ length: 40 }, (_, i) => `unknown-${i}`)]) {+ h.current().push({ ...frame, src, auth: peer.sign(frame) } as Envelope);+ }+ const probes = h.current().sent.filter(env => env.kind === 'push');+ expect(probes).toHaveLength(32);+ expect(probes.every(env => (env.payload as { channel: string }).channel === RELAY_AUTH_CHANNEL)).toBe(true);+ expect(probes.every(env => env.dst?.startsWith('unknown-'))).toBe(true);+ await vi.advanceTimersByTimeAsync(2_001);+ expect(h.current().sent.filter(env => env.kind === 'push')).toHaveLength(32);+ expect(received).not.toHaveBeenCalled();+ expect(h.sockets).toHaveLength(1);+ } finally { h.client.stop(); vi.useRealTimers(); }+ });+// #7722 discussion_r4403285988:内存计数在接收端重启后消失,旧写请求不能在十分钟内再次执行。// 真实认证器公开握手/验签入口;重放建链和invoke,并验证新的握手仍能恢复正常写请求。tier: unit。it('binds requests to the receiver boot so a restart cannot replay an executed write', () => {diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex ce0c17adb9..d3c76c6e15 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -593,6 +593,8 @@ interface PendingRequest {linkGeneration?: number;/** peer reset 时让 host 快速结束本次等待,由 host 重开后决定是否重试。 */retryAfterPeerReset?: () => void;+ /** 仅自建中转建链可在对端启动挑战更新后重送;沿用原 id、签名身份与请求期限。 */+ relayLinkRetry?: { envelope: Envelope; session: object };}@@ -1895,6 +1897,10 @@ export class DeviceLinkClient {dst: env.dst,linkGeneration: env.dst ? this.getPeerLinkGeneration(env.dst) : undefined,};+ const relaySigningSession = this.opts.frameAuth?.()?.peerChallenge?.session;+ if (env.kind === 'link-open' && relaySigningSession) {+ pendingRequest.relayLinkRetry = { envelope: { ...env, id }, session: relaySigningSession };+ }this.pending.set(id, pendingRequest);if (allowPeerResetRetry@@ -2428,7 +2434,10 @@ export class DeviceLinkClient {if (typeof parsed.src === 'string' && ROUTED_KINDS.has(parsed.kind)) {if (frameAuth && !frameAuth.verify(parsed as unknown as Record<string, unknown>)) {this.noteRejectedSignature(parsed.src, parsed.kind);- if (frameAuth.peerChallenge?.state(parsed.src) === 'needed') {+ // 冷启动证书尚未就绪时也只发有界认证探测;未验签业务仍直接丢弃。+ // 与设备证书相同的短 ID 边界,避免任意长来源占据探测队列。+ if (parsed.src.length > 0 && parsed.src.length <= 256 && frameAuth.peerChallenge+ && frameAuth.peerChallenge.state(parsed.src) !== 'ready') {try { this.probeRelayChallenge(parsed.src, this.ensureRelayChallenge(parsed.src, frameAuth)); }catch { /* 认证重试有界;失败不触发共享 socket 重连。 */ }}@@ -2464,6 +2473,7 @@ export class DeviceLinkClient {this.sendEnvelope({ v: PROTOCOL_VERSION, kind: 'push', id: env.id, dst: env.src,payload: { channel: RELAY_AUTH_CHANNEL, payload: { type: 'response' } } });} catch { /* 对端会在自己的预算内重试。 */ }+ this.recoverRelayLinkOpen(env.src, frameAuth);return;}if (handshake === 'response') {@@ -3828,6 +3838,25 @@ export class DeviceLinkClient {this.rejectedSignatureCount = 0;}+ private recoverRelayLinkOpen(dst: string, auth: DeviceLinkFrameAuth): void {+ const challenge = auth.peerChallenge;+ if (!challenge || challenge.state(dst) === 'ready') return;+ for (const [id, pending] of this.pending) {+ const retry = pending.relayLinkRetry;+ if (!retry || pending.dst !== dst || !pending.hasWritten() || pending.expireIfOverdue()) continue;+ if (retry.session !== challenge.session) {+ this.pending.delete(id);+ this.settleOutboundRouteAttemptsForId(dst, id);+ pending.reject(new DeviceLinkError('NOT_CONNECTED', 'relay signing identity changed'));+ continue;+ }+ try {+ // 先进入原有认证队列,双方挑战确认后再重签发送;首次写入时间不变,不延长预算。+ this.sendRoutedEnvelope(retry.envelope, pending.linkGeneration);+ } catch { /* 保留原请求期限;不扩大到共享 socket 或业务写请求的重试。 */ }+ }+ }+private ensureRelayChallenge(dst: string, auth: DeviceLinkFrameAuth): RelayChallengeQueue {const session = auth.peerChallenge!.session;let queue = this.relayChallenges.get(dst);