Files
cindy/scripts/device-link/interop.test.ts
Dash c584982c5f feat(device-link): compress pushes with a preset-dictionary deflate (push-deflate-v1)
Pushes from the controlled desktop (maker:event batches, messages:created,
status) were always plain JSON; only invoke results >= 4 KB were gzipped.

- Controllers with a synchronous inflateRawBase64 codec declare
  push-deflate-v1 in link-open. The host encodes pushes of 256 B..512 KiB
  for same-account reliable peers that declared it (link not explicitly
  closed): raw DEFLATE level 4 primed with PUSH_TRANSFER_DICTIONARY_V1
  (field names / enum values only, printable ASCII, guarded at load),
  base64, kept only when >= 10% smaller than the escaped wire form.
  channel and ownerStamp stay plain so reliable-queue drop/coalesce rules
  are unchanged. The 512 KiB cap keeps the existing oversize fallback and
  bounds synchronous inflate on the controller.
- Every push is independently decodable (no cross-message state), decoded
  synchronously at emitFrame so delivery order is preserved. An
  undecodable push is treated like a handler failure (not acknowledged),
  and the controller stops declaring the capability to that peer, so the
  existing reset/re-link/resync path recovers with plain pushes.
- Capability follows only the latest inbound link-open; a downgraded peer,
  an outbound accept showing a restarted peer, or an accept without a
  matching offer stops encoding and turns queued compressed pushes into
  transport skip placeholders (sent now when the link can send).
- Desktop/Node Host use Node zlib (separate "push deflate summary" debug
  stats, cached dictionary bytes); Mobile uses existing pako on the JS
  thread (no native change). Relays forward push frames unchanged; interop
  now asserts a compressed push crosses a real self-hosted relay with
  device signatures.

Measured with pnpm transfer:baseline over all stages (wire bytes without
ACKs), together with transport-ack-v2 and the 1 KiB invoke gzip threshold
of this series and without the other transfer changes: phone downlink
-17.4%, desktop downlink -22.1% excluding the 1 MiB running-result stage.

Test value
- Production entry / observable result: DeviceLinkClient.sendPush ->
  MemoryRelay -> controller onFrame; wire shape per peer capability,
  delivered payload/order identical; Mobile pako decodes Node output.
- Rule: protocol-compatibility/device-link-push-deflate.md (old peers unchanged,
  downgrade safety, shared dictionary bytes, no silent gaps).
- Gap: new protocol behaviour, no existing coverage.
- Minimal failing input: encoding without capability check, capability not
  reset on re-open / outbound restart, no size cap, no skip retirement, or
  re-declaring after a decode failure (each mutation verified red).
- Tier: unit (in-memory relay); interop covers the real relay.
- Time: client.test.ts push cases ~0.3 s; gzipBase64.test.ts ~0.03 s.

Assisted-by: Cindy (https://cindy.app)
Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>
2026-11-11 21:04:43 +13:00

189 lines
8.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { expect, it, vi } from "vitest";
import { nodeRelayAuthCrypto } from "../../packages/device-link/src/nodeRelayCrypto";
import { RelayFrameAuthenticator } from "../../packages/device-link/src/selfHostedRelayAuth";
import { PLUGIN_SYNC_CHANNEL } from "../../packages/device-link/src/pluginSyncProtocol";
import { deflateRawBase64Sync, inflateRawBase64TextBounded } from "../../packages/device-link/src/nodeCompression";
import {
createClient,
createHost,
createMobileRecovery,
} from "./clientHarness";
interface FrameAuthSpec {
relayId: string;
ownerPublicKey: string;
certs: unknown[];
host: { deviceId: string; seed: string };
controller: { deviceId: string; seed: string };
}
/**
* 自建中转的设备签名(可选,由 run-interop 提供测试密钥):主机与控制端都核对全部对端帧,
* 与 Desktop / Mobile 一致。任何绕过签名的发送路径都会让接收端丢帧、恢复流程超时。
*/
function frameAuthFor(spec: FrameAuthSpec, role: "host" | "controller", rejected: string[]) {
const auth = new RelayFrameAuthenticator({
crypto: nodeRelayAuthCrypto,
relayId: spec.relayId,
deviceId: spec[role].deviceId,
seed: spec[role].seed,
ownerPublicKey: spec.ownerPublicKey,
});
auth.setCertificates(spec.certs);
return () => ({
peerChallenge: { session: auth, state: (deviceId: string) => auth.peerChallenge(deviceId) },
sign: (frame: Parameters<RelayFrameAuthenticator["sign"]>[0]) => auth.sign(frame),
verify: (frame: Readonly<Record<string, unknown>>) => {
const verdict = auth.verify(frame);
if (verdict !== "ok") rejected.push(`${String(frame.kind)}:${verdict}`);
return verdict === "ok";
},
});
}
it("interoperates with an explicitly provisioned isolated relay and automatically reconnects", async () => {
const url = process.env.CINDY_TEST_RELAY_URL;
const hostToken = process.env.CINDY_TEST_HOST_TOKEN;
const controllerToken = process.env.CINDY_TEST_CONTROLLER_TOKEN;
if (!url || !hostToken || !controllerToken || hostToken === controllerToken) {
throw new Error(
"Provide a test relay URL and distinct test-device tokens for the same test account.",
);
}
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw new Error("Test relay URL must be a valid ws(s) URL.");
}
if (
!["ws:", "wss:"].includes(parsed.protocol) ||
parsed.username ||
parsed.password ||
parsed.search ||
parsed.hash
) {
throw new Error(
"Test relay URL must be ws(s), without credentials, query or fragment.",
);
}
// 官方测试 relay 用账号 access token(Bearer);自建中转用加入时拿到的设备凭证(CindyRelay)。
const scheme = process.env.CINDY_TEST_AUTH_SCHEME ?? "Bearer";
if (scheme !== "Bearer" && scheme !== "CindyRelay") {
throw new Error("CINDY_TEST_AUTH_SCHEME must be Bearer or CindyRelay.");
}
const timing = {
requestTimeoutMs: 10_000,
pingIntervalMs: 5_000,
transportRetryIntervalMs: 1_000,
reconnectBaseMs: 500,
reconnectMaxMs: 2_000,
};
const frameAuthSpec = process.env.CINDY_TEST_FRAME_AUTH
? (JSON.parse(process.env.CINDY_TEST_FRAME_AUTH) as FrameAuthSpec)
: null;
const rejected: string[] = [];
// push-deflate-v1:两端都注入与 Desktop 相同的 Node 编解码,压缩推送经真实中转(含设备签名)送达。
const transferCodec = {
deflateRawBase64: (text: string, dictionary: string) => deflateRawBase64Sync(text, 4, dictionary).compressed.toString("base64"),
inflateRawBase64: inflateRawBase64TextBounded,
};
const host = createClient(url, "interop-host", true, {
transferCodec,
token: hostToken,
authorizationScheme: scheme,
timing,
frameAuth: frameAuthSpec ? frameAuthFor(frameAuthSpec, "host", rejected) : undefined,
});
const controller = createClient(url, "interop-controller", false, {
transferCodec,
token: controllerToken,
authorizationScheme: scheme,
timing,
frameAuth: frameAuthSpec ? frameAuthFor(frameAuthSpec, "controller", rejected) : undefined,
});
const data = createHost(host.client);
let recovery: ReturnType<typeof createMobileRecovery> | undefined;
try {
host.client.start();
await vi.waitFor(() => expect(host.client.getStatus()).toBe("online"), {
timeout: 10_000,
});
const hostId = host.client.getSelfDeviceId();
if (!hostId) throw new Error("Test relay did not assign host identity");
controller.client.start();
await vi.waitFor(() => expect(controller.client.getStatus()).toBe("online"), { timeout: 10_000 });
if (frameAuthSpec) {
// 首次认证以关闭远控的手机为目标;不能借用会被 relay 拦截的 link-open。
const received: unknown[] = [];
const off = controller.client.onFrame(frame => {
if (frame.kind === "push") received.push(frame.payload);
});
try {
host.client.sendPush(controller.client.getSelfDeviceId()!, PLUGIN_SYNC_CHANNEL, { version: 1, type: "snapshot" });
await vi.waitFor(() => expect(received).toEqual([
{ channel: PLUGIN_SYNC_CHANNEL, payload: { version: 1, type: "snapshot" } },
]), { timeout: 10_000 });
const listing = await controller.client.invoke(hostId, { channel: "local-db:sessions:list", args: [] });
expect(listing.ok).toBe(true);
expect(data.received.some(frame => frame.kind === "link-open")).toBe(false);
} finally { off(); }
}
// Authorization requests and replies remain signed and deliverable with control off.
// They do not open a link or make ordinary invokes admissible.
const consentFrames: unknown[] = [];
const stopConsent = controller.client.onFrame(frame => {
if (frame.kind === "push") consentFrames.push(frame.payload);
});
try {
const request = { version: 1, kind: "request", id: "12345678-1234-1234-1234-123456789abc", purpose: "Download source", ttlMs: 45_000 };
host.client.sendPush(controller.client.getSelfDeviceId()!, "device-link:remote-control-consent", request);
await vi.waitFor(() => expect(consentFrames).toContainEqual({ channel: "device-link:remote-control-consent", payload: request }));
await expect(host.client.invoke(controller.client.getSelfDeviceId()!, { channel: "maker:machine:status", args: [] }))
.rejects.toMatchObject({ code: "REMOTE_DISABLED" });
} finally { stopConsent(); }
recovery = createMobileRecovery(controller.client, hostId);
recovery.foreground();
await vi.waitFor(
() => expect(recovery!.state.completed).toBeGreaterThan(0),
{ timeout: 10_000 },
);
expect(controller.client.getSelfDeviceId()).not.toBe(hostId);
// 链路已建立:较大的事件批走压缩形状,中转原样转发,控制端交给业务前还原。
const batch = { sessionId: "fixture-session", events: Array.from({ length: 8 }, (_, i) => ({
sessionId: "fixture-session", event: { type: "text", data: { text: `弱网流式正文 ${i} ✓`, isFinal: false } },
})) };
const pushes: unknown[] = [];
const stopPushes = controller.client.onFrame(frame => {
if (frame.kind === "push" && (frame.payload as { channel?: string }).channel === "maker:event:batch") pushes.push(frame.payload);
});
const wire: string[] = [];
const socket = controller.sockets.at(-1)!;
const onWire = (data: unknown) => wire.push(String(data));
socket.on("message", onWire);
try {
host.client.sendPush(controller.client.getSelfDeviceId()!, "maker:event:batch", batch);
await vi.waitFor(() => expect(pushes).toEqual([{ channel: "maker:event:batch", payload: batch }]), { timeout: 10_000 });
expect(wire.some(frame => frame.includes("deflateBase64"))).toBe(true);
} finally { stopPushes(); socket.off("message", onWire); }
const before = recovery.state.completed;
data.addMessage("interop-gap");
controller.sockets.at(-1)!.terminate();
await vi.waitFor(
() => expect(recovery!.state.completed).toBeGreaterThan(before),
{ timeout: 10_000 },
);
expect(recovery.state.messages.map((message) => message.id)).toEqual([
"m1",
"interop-gap",
]);
expect(controller.sockets.length).toBeGreaterThan(1);
expect(rejected).toEqual([]);
} finally {
recovery?.close();
data.close();
controller.close();
host.close();
}
}, 40_000);