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(plugins): guard sync mutations and restore peer grants

zqchrisf98f25b1aaca
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.ts
index b123bfca96..ec61cfe15f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.ts
@@ -1,5 +1,6 @@
import { afterEach, expect, it, vi } from 'vitest';
import { PluginDeviceSync } from '../deviceSyncSlot.js';
+import { PluginSyncAccess } from '../../device-link/pluginSyncAccess.js';
import { generateContactsSyncIdentity } from '../../contacts-sync/crypto.js';
import {
ghostPermissionItems,
@@ -67,13 +68,20 @@ function pair() {
listGhosts: () => ghosts,
deliver,
});
+ const remoteBlocked = new Set<string>();
+ const access = new PluginSyncAccess({
+ eligible: peer => sides.has(peer) && peer !== id && !blocked.has(peer),
+ revokedByRemote: peer => remoteBlocked.has(peer),
+ invalidate: peer => svc.invalidatePeer(peer),
+ send: (to, data) => { frames.push({ from: id, to, data }); },
+ });
svc.connect({
self: () => id,
peers: () =>
[...sides.keys()]
- .filter((x) => x !== id)
+ .filter(x => { access.probe(x); return access.allowed(x); })
.map((deviceId) => ({ deviceId, deviceName: deviceId })),
- allowed: (peer) => sides.has(peer) && peer !== id && !blocked.has(peer),
+ allowed: peer => access.allowed(peer),
send: (to, data) => {
frames.push({ from: id, to, data });
},
@@ -82,6 +90,8 @@ function pair() {
cleanups.push(() => svc.reset());
return {
svc,
+ access,
+ remoteBlocked,
keys,
deliver,
addPlugin: (id: string) => ghosts.push({ ...g, manifest: { ...manifest, id }, instanceKey: id } as InstalledGhost),
@@ -100,7 +110,8 @@ function pair() {
async function flush() {
while (frames.length) {
const f = frames.shift()!;
- await sides.get(f.to)!.svc.receive(f.from, f.data);
+ const side = sides.get(f.to)!;
+ if (!side.access.receive(f.from, f.data)) await side.svc.receive(f.from, f.data);
}
}
async function ready() {
@@ -397,3 +408,92 @@ it('does not revive old inbound or outbound requests when peer access is restore
expect(b.delivered.map(m => m.data)).toEqual([{ fresh: true }]);
a.svc.invalidatePeer('b'); expect(await fresh).toMatchObject({ errorCode: 'SYNC_RESULT_UNKNOWN' });
});
+
+// Review #6569: earlier epoch tests missed admission during the mutation itself.
+// Real handler + wire (unit); the approved catalog remains visible while work is pending.
+it('denies new and queued frames for the entire plugin mutation, including rollback', async () => {
+ const { a, b, frames, ready, flush } = pair(); await ready();
+ let releaseKeys!: () => void, entered!: () => void;
+ const started = new Promise<void>(resolve => { entered = resolve; });
+ b.keys.prepare.mockImplementationOnce(() => { entered(); return new Promise<void>(resolve => { releaseKeys = resolve; }); });
+ const stale = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: 'stale' });
+ await Promise.resolve(); await Promise.resolve();
+ const frame = frames.shift()!;
+ const receiving = b.svc.receive(frame.from, frame.data); await started;
+ const release = b.svc.beginMutation('example-sync');
+ const nested = b.svc.beginMutation('example-sync'); release();
+ const during = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: 'during' });
+ await Promise.resolve(); await Promise.resolve();
+ const next = frames.shift()!;
+ const queued = b.svc.receive(next.from, next.data);
+ expect(await b.svc.handle('example-sync', { op: 'request', peer: 'a', data: {} }))
+ .toMatchObject({ errorCode: 'SYNC_NOT_ALLOWED' });
+ // Rollback can leave the same approval; neither old nor during-mutation frames can run.
+ nested(); releaseKeys(); await receiving; await queued;
+ expect(b.delivered).toHaveLength(0);
+ a.svc.reset(); a.svc.setActive(true); await Promise.all([stale, during]);
+ const fresh = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: 'fresh' });
+ await Promise.resolve(); await Promise.resolve(); await flush();
+ expect(b.delivered.map(m => m.data)).toEqual(['fresh']);
+ a.svc.reset(); await fresh;
+});
+
+// Unit: actual admission controller + encrypted RPC; restore must work without control open.
+// Existing tests used a mutable boolean and missed both handshake and persistence windows.
+it('restores sync through a fresh authenticated challenge without restoring control access', async () => {
+ const { a, b, ready, flush, frames } = pair(); await ready();
+ b.blocked.add('a'); a.remoteBlocked.add('b'); a.access.invalidate('b');
+ expect(await a.svc.handle('example-sync', { op: 'status' })).toMatchObject({ peers: [] });
+ await flush(); // B still denies access and must not acknowledge.
+ expect(a.access.allowed('b')).toBe(false);
+ b.blocked.delete('a');
+ await vi.advanceTimersByTimeAsync(30001);
+ await a.svc.handle('example-sync', { op: 'status' });
+ const probe = frames.shift()!;
+ b.access.receive(probe.from, probe.data);
+ const ack = frames.shift()!;
+ // An old acknowledgement cannot cross another revoke/restore or come from another peer.
+ a.access.invalidate('b'); a.access.receive('b', ack.data);
+ expect(a.access.allowed('b')).toBe(false);
+ await a.svc.handle('example-sync', { op: 'status' });
+ const freshProbe = frames.shift()!;
+ await vi.advanceTimersByTimeAsync(5001);
+ b.access.receive(freshProbe.from, freshProbe.data);
+ const freshAck = frames.shift()!;
+ a.access.receive('unknown', freshAck.data);
+ expect(a.access.allowed('b')).toBe(false);
+ a.access.receive('b', freshAck.data);
+ expect(a.remoteBlocked.has('b')).toBe(true);
+ expect(await a.svc.handle('example-sync', { op: 'status' })).toMatchObject({ peers: [{ deviceId: 'b' }] });
+ const request = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: 'restored' });
+ await Promise.resolve(); await Promise.resolve(); await flush();
+ expect(b.delivered.map(m => m.data)).toEqual(['restored']);
+ await b.svc.handle('example-sync', { op: 'reply', requestId: b.delivered[0].requestId, data: 'stored' });
+ await flush(); expect(await request).toEqual({ ok: true, data: 'stored' });
+ a.access.reset(); a.access.receive('b', freshAck.data);
+ expect(a.access.allowed('b')).toBe(false);
+});
+
+it('denies sync during revoke persistence and releases the temporary deny on failure', async () => {
+ const { a, b, ready, flush, frames } = pair(); await ready();
+ const release = b.access.beginRevocation('a'); // Disk still reports allowed.
+ const secondRelease = b.access.beginRevocation('a'); release();
+ expect(b.access.allowed('a')).toBe(false);
+ const request = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: 'during-write' });
+ await Promise.resolve(); await Promise.resolve(); await flush();
+ expect(b.delivered).toHaveLength(0);
+ a.remoteBlocked.add('b'); a.access.invalidate('b');
+ await a.svc.handle('example-sync', { op: 'status' }); await flush();
+ expect(a.access.allowed('b')).toBe(false); expect(frames).toHaveLength(0);
+ secondRelease(); // Failed write: only fresh frames can proceed.
+ expect(b.access.allowed('a')).toBe(true);
+ a.svc.reset(); a.svc.setActive(true); await request;
+ await vi.advanceTimersByTimeAsync(30001);
+ await a.svc.handle('example-sync', { op: 'status' }); await flush();
+ const fresh = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: 'after-rollback' });
+ await Promise.resolve(); await Promise.resolve(); await flush();
+ expect(b.delivered.map(m => m.data)).toEqual(['after-rollback']);
+ a.svc.reset(); await fresh;
+ const committed = b.access.beginRevocation('a'); b.blocked.add('a'); committed();
+ expect(b.access.allowed('a')).toBe(false);
+});
diff --git a/apps/desktop/src/main/cindy-brain/deviceSyncSlot.ts b/apps/desktop/src/main/cindy-brain/deviceSyncSlot.ts
index 7347c9e4aa..ed545adc35 100644
--- a/apps/desktop/src/main/cindy-brain/deviceSyncSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/deviceSyncSlot.ts
@@ -84,6 +84,7 @@ export class PluginDeviceSync {
private receivingCount = 0;
private readonly epochs = new Map<string, number>();
private readonly peerEpochs = new Map<string, number>();
+ private readonly mutations = new Map<string, number>();
constructor(private readonly deps: Deps) {}
connect(transport: PluginSyncTransport): void {
this.reset();
@@ -123,6 +124,20 @@ export class PluginDeviceSync {
this.incoming.delete(id);
}
}
+ /** Hold admission closed from before stop through package/receipt commit or rollback. */
+ beginMutation(instance: string): () => void {
+ this.mutations.set(instance, (this.mutations.get(instance) ?? 0) + 1);
+ this.invalidate(instance);
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ const remaining = (this.mutations.get(instance) ?? 1) - 1;
+ if (remaining) this.mutations.set(instance, remaining);
+ else this.mutations.delete(instance);
+ this.invalidate(instance);
+ };
+ }
invalidatePeer(peer: string): void {
this.peerEpochs.set(peer, (this.peerEpochs.get(peer) ?? 0) + 1);
this.keyReplies.delete(peer);
@@ -139,7 +154,7 @@ export class PluginDeviceSync {
}
private capture(instance: string): (() => boolean) | null {
const ghost = this.deps.getGhost(instance);
- if (!identity(ghost)) return null;
+ if (this.mutations.has(instance) || !identity(ghost)) return null;
const epoch = this.epochs.get(instance) ?? 0;
const plugin = identity(ghost)!;
const approval = ghostInstallApprovalToken(ghost!.approval);
@@ -149,6 +164,7 @@ export class PluginDeviceSync {
const current = this.deps.getGhost(instance);
return (
this.active &&
+ !this.mutations.has(instance) &&
generation === this.generation &&
epoch === (this.epochs.get(instance) ?? 0) &&
scope === this.deps.scope() &&
@@ -165,7 +181,7 @@ export class PluginDeviceSync {
async handle(instance: string, raw: unknown): Promise<unknown> {
if (this.scope !== this.deps.scope()) this.reset();
const plugin = identity(this.deps.getGhost(instance));
- if (!plugin) return error('SYNC_NOT_ALLOWED');
+ if (!plugin || this.mutations.has(instance)) return error('SYNC_NOT_ALLOWED');
if (!record(raw)) return error('INVALID_PARAMS');
if (raw.op === 'status')
return {
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index d8f33e48f7..9388ba1302 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -7045,96 +7045,101 @@ async function updateLocalGhostPackageLocked(
);
if (sourceChanged) assertGhostRelocationIdle(instanceId);
rejectUnauthorizedTokenBroker(inspected.canonicalManifest, authorizationOverrides);
- runtime.stop(instanceId);
- // 等待失败表示旧进程仍可能存活;此时不能恢复 resident,否则会产生
- // 两份后台进程。仅在确认退出后的更新阶段失败时恢复旧版本。
- await getGhostNodeRuntimeBroker().stopAndWait(instanceId);
- // 用户已明确选择了这份本地真实包:同 id 可以原位替换,市场来源不是永久所有权。
- // 替换前先切断旧市场更新路由;用户状态由安装事务隔离归档,落位失败再恢复。
- const detachMarketRecord = Boolean(marketRecord?.installed);
- const restoreMarketRecord = (): void => {
- if (!detachMarketRecord || !marketRecord) return;
- try {
- // 来源解绑不触碰 opt-out,失败恢复同样只恢复旧路由;用户过去的显式
- // 卸载决定因此既不会被新增,也不会被清除。
- marketLedger.restoreInstallation(marketRecord);
- } catch (error) {
- // 恢复失败时保持路由失效是安全降级:不能让旧市场自动覆盖用户明确选择的本地包。
- log.error('failed to restore Plugin market provenance after local update failure', {
- ghostId: inspected.manifest.id,
- error: error instanceof Error ? error.message : String(error),
- });
+ const releaseSync = pluginDeviceSync.beginMutation(instanceId);
+ try {
+ runtime.stop(instanceId);
+ // 等待失败表示旧进程仍可能存活;此时不能恢复 resident,否则会产生
+ // 两份后台进程。仅在确认退出后的更新阶段失败时恢复旧版本。
+ await getGhostNodeRuntimeBroker().stopAndWait(instanceId);
+ // 用户已明确选择了这份本地真实包:同 id 可以原位替换,市场来源不是永久所有权。
+ // 替换前先切断旧市场更新路由;用户状态由安装事务隔离归档,落位失败再恢复。
+ const detachMarketRecord = Boolean(marketRecord?.installed);
+ const restoreMarketRecord = (): void => {
+ if (!detachMarketRecord || !marketRecord) return;
+ try {
+ // 来源解绑不触碰 opt-out,失败恢复同样只恢复旧路由;用户过去的显式
+ // 卸载决定因此既不会被新增,也不会被清除。
+ marketLedger.restoreInstallation(marketRecord);
+ } catch (error) {
+ // 恢复失败时保持路由失效是安全降级:不能让旧市场自动覆盖用户明确选择的本地包。
+ log.error('failed to restore Plugin market provenance after local update failure', {
+ ghostId: inspected.manifest.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ };
+ if (detachMarketRecord && marketRecord) {
+ try {
+ // 先持久化切断自动更新路由,再改真实包。普通本地/Forge 换源不是
+ // 用户显式卸载,不得产生 default-install opt-out。
+ marketLedger.markRemovedRecord(marketRecord, null);
+ } catch (error) {
+ restoreMarketRecord();
+ spawnIfResident(previousGhost);
+ log.warn('failed to detach Plugin market provenance before local update', {
+ ghostId: inspected.manifest.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');
+ }
}
- };
- if (detachMarketRecord && marketRecord) {
+ getGhostAgentSlot().clearGhost(instanceId);
+ getGhostErrandSlot().clearGhost(instanceId);
+ let result: Awaited<ReturnType<typeof manager.update>>;
+ let packagePlaced = false;
try {
- // 先持久化切断自动更新路由,再改真实包。普通本地/Forge 换源不是
- // 用户显式卸载,不得产生 default-install opt-out。
- marketLedger.markRemovedRecord(marketRecord, null);
- } catch (error) {
- restoreMarketRecord();
- spawnIfResident(previousGhost);
- log.warn('failed to detach Plugin market provenance before local update', {
+ result = await withActiveOwnerGhostOauthMutationLock(
+ instanceId,
+ () =>
+ manager.update(cindyFilePath, {
+ taskCapabilityApproved: confirmedTaskCapability(consent, previousGhost, inspected.manifest),
+ expectedPackageSha256,
+ expectedInstalledApproval,
+ installOrigin: installOrigin ?? 'manual',
+ ...(sourceChanged ? { sourceStateArchiveId: ghostSourceStateArchiveId(previousGhost) } : {}),
+ ...deliveryNamespaceFields(previousGhost),
+ beforePackageCommit: () => {
+ if (isCurrent?.() === false) throwIpcError('PRECONDITION_FAILED', 'Plugin operation is no longer current');
+ return getGhostOauthAccountManager().prepareAccountsForChangedClients(
+ previousGhost.manifest, inspected.canonicalManifest, instanceId,
+ );
+ },
+ onPackagePlaced: () => {
+ packagePlaced = true;
+ },
+ }),
+ );
+ } catch (err) {
+ if (!packagePlaced) {
+ restoreMarketRecord();
+ spawnIfResident(previousGhost);
+ throw err;
+ }
+ const placed = findInstalledGhostByInstanceId(manager.list(), instanceId) ??
+ manager.list().find((ghost) => ghost.dir === previousGhost.dir);
+ if (!placed) throw err;
+ log.warn('local ghost post-placement notification failed', {
ghostId: inspected.manifest.id,
- error: error instanceof Error ? error.message : String(error),
+ error: err instanceof Error ? err.message : String(err),
});
- throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');
+ result = { ghost: placed };
}
- }
- getGhostAgentSlot().clearGhost(instanceId);
- getGhostErrandSlot().clearGhost(instanceId);
- let result: Awaited<ReturnType<typeof manager.update>>;
- let packagePlaced = false;
- try {
- result = await withActiveOwnerGhostOauthMutationLock(
- instanceId,
- () =>
- manager.update(cindyFilePath, {
- taskCapabilityApproved: confirmedTaskCapability(consent, previousGhost, inspected.manifest),
- expectedPackageSha256,
- expectedInstalledApproval,
- installOrigin: installOrigin ?? 'manual',
- ...(sourceChanged ? { sourceStateArchiveId: ghostSourceStateArchiveId(previousGhost) } : {}),
- ...deliveryNamespaceFields(previousGhost),
- beforePackageCommit: () => {
- if (isCurrent?.() === false) throwIpcError('PRECONDITION_FAILED', 'Plugin operation is no longer current');
- return getGhostOauthAccountManager().prepareAccountsForChangedClients(
- previousGhost.manifest, inspected.canonicalManifest, instanceId,
- );
- },
- onPackagePlaced: () => {
- packagePlaced = true;
- },
- }),
- );
- } catch (err) {
- if (!packagePlaced) {
- restoreMarketRecord();
- spawnIfResident(previousGhost);
- throw err;
- }
- const placed = findInstalledGhostByInstanceId(manager.list(), instanceId) ??
- manager.list().find((ghost) => ghost.dir === previousGhost.dir);
- if (!placed) throw err;
- log.warn('local ghost post-placement notification failed', {
- ghostId: inspected.manifest.id,
- error: err instanceof Error ? err.message : String(err),
- });
- result = { ghost: placed };
- }
- if ('rejection' in result) {
- // 回滚失败时安装目录可能已是新字节或缺失,不能恢复旧 runtime 或旧市场来源路由。
- if (!(result.rejection.code === 'io' && result.rejection.rollbackFailed)) {
- restoreMarketRecord();
- spawnIfResident(previousGhost);
+ if ('rejection' in result) {
+ // 回滚失败时安装目录可能已是新字节或缺失,不能恢复旧 runtime 或旧市场来源路由。
+ if (!(result.rejection.code === 'io' && result.rejection.rollbackFailed)) {
+ restoreMarketRecord();
+ spawnIfResident(previousGhost);
+ }
+ throwInstallError(result.rejection);
}
- throwInstallError(result.rejection);
+ runtime.resetFuse(instanceId);
+ await bindPluginUsage(result.ghost,
+ !detachMarketRecord && previousGhost?.approval.state === 'approved' ? previousGhost.approval.revision : undefined);
+ spawnIfResident(result.ghost);
+ return result.ghost;
+ } finally {
+ releaseSync();
}
- runtime.resetFuse(instanceId);
- await bindPluginUsage(result.ghost,
- !detachMarketRecord && previousGhost?.approval.state === 'approved' ? previousGhost.approval.revision : undefined);
- spawnIfResident(result.ghost);
- return result.ghost;
}
/**
@@ -7401,6 +7406,7 @@ async function installOrUpdateMarketGhostPackageLocked(
): Promise<InstalledGhost> {
const mutationOwner = captureGhostMutationOwner();
let releaseMutation: (() => void) | null = null;
+ let releaseSync: (() => void) | undefined;
try {
const manager = getGhostManager();
const registryError = blockedInstanceRegistryMarketError(manager.isInstanceRegistryBlocked());
@@ -7525,6 +7531,7 @@ async function installOrUpdateMarketGhostPackageLocked(
expected.beforeCommitInLock?.();
if (expected.sourceChanged) assertGhostRelocationIdle(installedGhostStoragePart(installed));
const runtime = getGhostRuntime();
+ releaseSync = pluginDeviceSync.beginMutation(installedGhostStoragePart(installed));
runtime.stop(installedGhostStoragePart(installed));
// 无法确认旧进程已退出时保持停止态,不能启动第二份 resident。只有旧进程
// 已确认退出、后续目录更新失败时,才恢复原版本。
@@ -7595,6 +7602,7 @@ async function installOrUpdateMarketGhostPackageLocked(
await bindPluginUsage(result.ghost);
return result.ghost;
} finally {
+ releaseSync?.();
releaseMutation?.();
}
}
@@ -7642,6 +7650,7 @@ async function uninstallGhostAndCleanupLocked(
options?: { skipMarketLedger?: boolean; assertCurrent?: () => void },
): Promise<void> {
const releaseMutation = beginGhostMutation();
+ let releaseSync: (() => void) | undefined;
try {
options?.assertCurrent?.();
requireGhostAvailableForActiveSession(id);
@@ -7660,6 +7669,7 @@ async function uninstallGhostAndCleanupLocked(
const runtime = getGhostRuntime();
// Library 的 orphaned 标记要在 uninstall 之前取显示名(收走后 list 里就没了)。
const libraryDisplayName = ghost.manifest.name;
+ releaseSync = pluginDeviceSync.beginMutation(storagePart);
runtime.stop(storagePart);
await getGhostNodeRuntimeBroker().stopAndWait(storagePart);
getGhostAgentSlot().clearGhost(storagePart);
@@ -7771,6 +7781,7 @@ async function uninstallGhostAndCleanupLocked(
});
}
} finally {
+ releaseSync?.();
releaseMutation();
}
}
@@ -7835,6 +7846,7 @@ async function setGhostEnabledForUser(id: string, enabled: boolean, expectedInst
// 安装目录)再动态写 receipt —— 不持租约,这个异步窗口里切号落定会拿 A 的镜像
// 状态改 B 的 receipt(启停同时落在两个 owner 的两半)。
const releaseMutation = beginGhostMutation(captureGhostMutationOwner());
+ const releaseSync = pluginDeviceSync.beginMutation(storagePart);
try {
if (!enabled) {
runtime.stop(storagePart); // 沉睡立即熄灯
@@ -7880,6 +7892,7 @@ async function setGhostEnabledForUser(id: string, enabled: boolean, expectedInst
return { ok: true };
} finally {
releaseMutation();
+ releaseSync();
}
}
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 47b2ccd664..1dfdb0c5ee 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -1,5 +1,6 @@
import { pluginDeviceSync } from '../cindy-brain/index.js';
import { PLUGIN_SYNC_CHANNEL } from '../cindy-brain/deviceSyncSlot.js';
+import { PluginSyncAccess } from './pluginSyncAccess.js';
/**
* device-link host —— 跨设备远程控制的 main 进程接线层。
*
@@ -576,6 +577,20 @@ function isDeviceRevoked(deviceId: string): boolean {
return readDeviceLinkSettings().revokedControllers.includes(deviceId);
}
+const pluginSyncAccess = new PluginSyncAccess({
+ eligible: deviceId => !!client && !isAppSessionBoundaryPending() && !isScopedPeer(deviceId) &&
+ deviceId !== client.getSelfDeviceId() && shouldExchangeDictionaryWith({
+ online: presenceOnlineByDevice.get(deviceId) === true,
+ platform: getControllerPlatform(deviceId), revoked: isDeviceRevoked(deviceId),
+ }),
+ revokedByRemote: deviceId => revokedByRemote.has(deviceId),
+ invalidate: deviceId => pluginDeviceSync.invalidatePeer(deviceId),
+ send: (deviceId, frame) => {
+ if (!client) throw new Error('device link unavailable');
+ client.sendPush(deviceId, PLUGIN_SYNC_CHANNEL, frame);
+ },
+});
+
/**
* relay 连续报 auth-failed 时,两次主动 refresh 之间的最小间隔。
* refresh 是 token-rotating 端点,不节流会在「refresh 成功但 relay 仍拒」的
@@ -1036,7 +1051,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
// 撤权后在途请求会陆续超时——那不是「设备无响应」,是访问被收回。清熔断并
// 作废在途结果(翻代),避免 unresponsive 状态与撤权状态并存(对齐 mobile 语义)。
revokedByRemote.add(env.src);
- pluginDeviceSync.invalidatePeer(env.src);
+ pluginSyncAccess.invalidate(env.src);
responsivenessTracker?.clearDevice(env.src);
broadcast(DEVICE_LINK_PUSH.ACCESS_REVOKED, { deviceId: env.src });
}
@@ -1063,6 +1078,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
return;
}
if (p?.channel === PLUGIN_SYNC_CHANNEL) {
+ if (pluginSyncAccess.receive(env.src, p.payload)) return;
void pluginDeviceSync.receive(env.src, p.payload);
return;
}
@@ -1133,11 +1149,13 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
});
pluginDeviceSync.connect({
self: () => client?.getSelfDeviceId() ?? null,
- peers: () => [...presenceOnlineByDevice.entries()]
- .filter(([deviceId, online]) => !isScopedPeer(deviceId) && !revokedByRemote.has(deviceId) && deviceId !== client?.getSelfDeviceId() && shouldExchangeDictionaryWith({ online, platform: getControllerPlatform(deviceId), revoked: isDeviceRevoked(deviceId) }))
- .map(([deviceId]) => ({ deviceId, deviceName: presenceNameByDevice.get(deviceId) ?? deviceId.slice(0, 8) })),
- allowed: deviceId => !isScopedPeer(deviceId) && !revokedByRemote.has(deviceId) && deviceId !== client?.getSelfDeviceId() &&
- shouldExchangeDictionaryWith({ online: presenceOnlineByDevice.get(deviceId) === true, platform: getControllerPlatform(deviceId), revoked: isDeviceRevoked(deviceId) }),
+ peers: () => [...presenceOnlineByDevice.keys()]
+ .filter(deviceId => {
+ pluginSyncAccess.probe(deviceId);
+ return pluginSyncAccess.allowed(deviceId);
+ })
+ .map(deviceId => ({ deviceId, deviceName: presenceNameByDevice.get(deviceId) ?? deviceId.slice(0, 8) })),
+ allowed: deviceId => pluginSyncAccess.allowed(deviceId),
send: (deviceId, frame) => { if (!client) throw new Error('device link unavailable'); client.sendPush(deviceId, PLUGIN_SYNC_CHANNEL, frame); },
});
initContactsDeviceSync({
@@ -1376,6 +1394,7 @@ export function getMobileNotifyGeneration(): number {
*/
function teardownActiveLink(): void {
pluginDeviceSync.reset();
+ pluginSyncAccess.reset();
invalidatePluginOauth();
void stopSharedTaskRuntime().catch((error) => log.warn('sharedTask runtime teardown failed', error));
stopProviderShareRuntime();
@@ -1527,30 +1546,34 @@ export function disconnectAllControllers(): void {
*/
export async function revokeController(deviceId: string): Promise<void> {
invalidatePluginOauth(deviceId);
- pluginDeviceSync.invalidatePeer(deviceId);
- // 先消化并 enforce 盘上的外部变化,避免快照刷新吞掉别的实例刚写入的撤销(见 setRemoteControlEnabled)
- pollExternalSettingsChange();
- // updater 在写锁内基于盘上最新名单追加,不能锁外算好整数组再整值写
- // (两个实例并发撤销不同控制端时,后写者的旧数组会覆盖掉先写者刚加的那条)
- await updateDeviceLinkSetting('revokedControllers', (latest) =>
- latest.includes(deviceId) ? latest : [...latest, deviceId],
- );
- pluginDeviceSync.invalidatePeer(deviceId);
- // 在线连着的:发 link-close('revoked'),控制端据此立即移除本机项目/对话 + 标记「已撤销」。
+ const releaseRevocation = pluginSyncAccess.beginRevocation(deviceId);
try {
- client?.closeLink(deviceId, 'revoked', 'inbound');
- } catch (err) {
- log.warn(`closeLink failed while revoking ${deviceId.slice(0, 8)}: ${String(err)}`);
+ // 先消化并 enforce 盘上的外部变化,避免快照刷新吞掉别的实例刚写入的撤销(见 setRemoteControlEnabled)
+ pollExternalSettingsChange();
+ // updater 在写锁内基于盘上最新名单追加,不能锁外算好整数组再整值写
+ // (两个实例并发撤销不同控制端时,后写者的旧数组会覆盖掉先写者刚加的那条)
+ await updateDeviceLinkSetting('revokedControllers', (latest) =>
+ latest.includes(deviceId) ? latest : [...latest, deviceId],
+ );
+ pluginSyncAccess.invalidate(deviceId);
+ // 在线连着的:发 link-close('revoked'),控制端据此立即移除本机项目/对话 + 标记「已撤销」。
+ try {
+ client?.closeLink(deviceId, 'revoked', 'inbound');
+ } catch (err) {
+ log.warn(`closeLink failed while revoking ${deviceId.slice(0, 8)}: ${String(err)}`);
+ }
+ forgetControllerInvokeState(deviceId);
+ // 踢掉它的订阅 registry + 重算转发/横幅(复用对等下线的单设备清理路径)。
+ handleControllerOffline(deviceId);
+ purgeRevokedController(deviceId);
+ // 末尾再 poll 一次(而非仅刷新基线):写锁释放到这里之间,别的实例可能已插入
+ // 新授权变更,仅刷新基线会把它静默记为已生效、永不 enforce;poll 是幂等的,
+ // 本地刚做过的动作重复 enforce 无害,同时能捕获这条竞态窗口里的外部变更。
+ pollExternalSettingsChange();
+ log.info(`access revoked for controller ${deviceId.slice(0, 8)}`);
+ } finally {
+ releaseRevocation();
}
- forgetControllerInvokeState(deviceId);
- // 踢掉它的订阅 registry + 重算转发/横幅(复用对等下线的单设备清理路径)。
- handleControllerOffline(deviceId);
- purgeRevokedController(deviceId);
- // 末尾再 poll 一次(而非仅刷新基线):写锁释放到这里之间,别的实例可能已插入
- // 新授权变更,仅刷新基线会把它静默记为已生效、永不 enforce;poll 是幂等的,
- // 本地刚做过的动作重复 enforce 无害,同时能捕获这条竞态窗口里的外部变更。
- pollExternalSettingsChange();
- log.info(`access revoked for controller ${deviceId.slice(0, 8)}`);
}
/**
@@ -1631,7 +1654,7 @@ function pollExternalSettingsChange(): void {
const newlyRevoked = revokedControllers.filter((id) => !prev.revokedControllers.includes(id));
for (const deviceId of newlyRevoked) {
- pluginDeviceSync.invalidatePeer(deviceId);
+ pluginSyncAccess.invalidate(deviceId);
try {
client.closeLink(deviceId, 'revoked', 'inbound');
} catch (err) {
diff --git a/apps/desktop/src/main/device-link/pluginSyncAccess.ts b/apps/desktop/src/main/device-link/pluginSyncAccess.ts
new file mode 100644
index 0000000000..891b2fe732
--- /dev/null
+++ b/apps/desktop/src/main/device-link/pluginSyncAccess.ts
@@ -0,0 +1,85 @@
+import { randomUUID } from 'node:crypto';
+
+interface Deps {
+ /** Same-account, online desktop, not locally revoked. Independent of control links. */
+ eligible(peer: string): boolean;
+ revokedByRemote(peer: string): boolean;
+ send(peer: string, frame: unknown): void;
+ invalidate(peer: string): void;
+}
+
+/** Sync-only grants over the authenticated same-account relay. Never restores remote control.
+ * A fresh challenge must be answered by the peer after its local deny check.
+ */
+export class PluginSyncAccess {
+ private readonly grants = new Set<string>();
+ private readonly probes = new Map<string, { nonce: string; expires: number }>();
+ private readonly replies = new Map<string, number>();
+ private readonly revoking = new Map<string, number>();
+ constructor(private readonly deps: Deps) {}
+
+ private eligible(peer: string): boolean {
+ return !this.revoking.has(peer) && this.deps.eligible(peer);
+ }
+ allowed(peer: string): boolean {
+ return this.eligible(peer) && (!this.deps.revokedByRemote(peer) || this.grants.has(peer));
+ }
+ invalidate(peer: string): void {
+ this.grants.delete(peer);
+ this.probes.delete(peer);
+ this.replies.delete(peer);
+ this.deps.invalidate(peer);
+ }
+ beginRevocation(peer: string): () => void {
+ this.revoking.set(peer, (this.revoking.get(peer) ?? 0) + 1);
+ this.invalidate(peer);
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ const remaining = (this.revoking.get(peer) ?? 1) - 1;
+ if (remaining) this.revoking.set(peer, remaining);
+ else this.revoking.delete(peer);
+ this.invalidate(peer);
+ };
+ }
+ reset(): void {
+ this.grants.clear();
+ this.probes.clear();
+ this.replies.clear();
+ // An outstanding disk write still denies admission after a relay reconnect.
+ }
+ /** Called by the existing plugin status polling; no additional background timer. */
+ probe(peer: string): void {
+ if (!this.eligible(peer) || !this.deps.revokedByRemote(peer) || this.grants.has(peer)) return;
+ const now = Date.now();
+ for (const [id, probe] of this.probes) if (probe.expires <= now) this.probes.delete(id);
+ if (this.probes.has(peer) || this.probes.size >= 64) return;
+ const nonce = randomUUID();
+ this.probes.set(peer, { nonce, expires: now + 30_000 });
+ try { this.deps.send(peer, { version: 1, kind: 'authorize', nonce }); }
+ catch { this.probes.delete(peer); }
+ }
+ /** Consume only metadata handshakes. Data/key frames must still pass allowed(). */
+ receive(peer: string, raw: unknown): boolean {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return false;
+ const frame = raw as Record<string, unknown>;
+ if (frame.kind !== 'authorize' && frame.kind !== 'authorized') return false;
+ if (frame.version !== 1 || typeof frame.nonce !== 'string' ||
+ !/^[a-f0-9-]{36}$/.test(frame.nonce) || !this.eligible(peer)) return true;
+ if (frame.kind === 'authorize') {
+ const now = Date.now();
+ for (const [id, time] of this.replies) if (now - time >= 5000) this.replies.delete(id);
+ if (this.replies.has(peer) || this.replies.size >= 64) return true;
+ this.replies.set(peer, now);
+ try { this.deps.send(peer, { version: 1, kind: 'authorized', nonce: frame.nonce }); }
+ catch { /* A later bounded probe can retry. */ }
+ } else {
+ const pending = this.probes.get(peer);
+ if (!pending || pending.nonce !== frame.nonce || pending.expires <= Date.now()) return true;
+ this.probes.delete(peer);
+ this.grants.add(peer);
+ }
+ return true;
+ }
+}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 942bad19e4..8d4084fc1e 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -2758,6 +2758,8 @@ namespace + id 下同一插件的有界 JSON 请求;`deviceSync: true` 是独
排队、密钥准备和沙箱启动共享从帧入站起计算的 30 秒截止时间;超时释放该 peer 队列,迟到的启动不能再投递。
入站等待前捕获各候选插件安装状态;更新后的插件不接收旧帧。撤权翻转 peer 授权代次并清理双向在途请求,重新授权只放行新请求。
显式断开远程控制后此通道可走 unlinked legacy;不重新打开控制链路,仍执行同账号与撤权检查。
+同步可用设备查询会向被对端撤权的在线电脑发出有界 `authorize` nonce 探测;对端仅在本机仍允许该设备时通过同账号认证 relay 回复 `authorized`。匹配本连接代、peer 与未过期 nonce 后只恢复同步准入,不清除远控撤权标记,也不打开控制链。撤权和连接重置清除旧探测及同步授权;旧客户端忽略这两类增量帧。
+撤权写盘前立即关闭同步准入,成功后由持久黑名单接替,失败后释放临时拒绝但不恢复旧在途请求。插件本地/Forge/市场更新、卸载和启停从停止前到提交或回滚结束全程阻断该实例同步;嵌套变更须全部结束才恢复准入。
账号/owner、安装 revision、插件启停和撤权每次重新核验,旧请求失效只影响其调用,
不重连共享 relay。恢复由插件持久状态对账,不恢复失效请求。
实现与 unit 回归:`cindy-brain/deviceSyncSlot.ts` / `__tests__/deviceSyncSlot.test.ts`。
diff --git a/packages/device-link/src/pluginSyncProtocol.ts b/packages/device-link/src/pluginSyncProtocol.ts
index 4d3c3db902..93533a11c2 100644
--- a/packages/device-link/src/pluginSyncProtocol.ts
+++ b/packages/device-link/src/pluginSyncProtocol.ts
@@ -1,9 +1,10 @@
-/** Opaque same-account Desktop plugin exchange. Relay carries only key frames and ciphertext.
+/** Opaque same-account Desktop plugin exchange. Relay carries grant/key metadata and ciphertext.
* Older clients ignore this channel; absence of a reply never implies execution failure.
*/
export const PLUGIN_SYNC_CHANNEL = "device-link:plugin-sync:v1";
export const PLUGIN_SYNC_MAX_BYTES = 64 * 1024;
export type PluginSyncWireFrame =
+ | { version: 1; kind: "authorize" | "authorized"; nonce: string }
| { version: 1; kind: "key"; publicKey: string }
| {
version: 1;