Files
openbot/scripts/remote-connect-analytics-e2e.ts
NB e3bf089107 Send the Signal home on system_remote_connect (#12919)
* Send the Signal home on system_remote_connect

China users report that they cannot connect, but the connect event does
not tell which Signal machine a client used. Thus we cannot see whether
the CN=us rule helps, or which machine fails.

- The desktop records the Signal home of the ticket: a, b, us, au, sg,
  entry, or other. It sends only this name, never the address.
- Host analytics generation 21.
- ANALYTICS.md, PRIVACY.md and the architecture notes tell about the
  new property. The Signal deployment steps now say to add a new home
  to the desktop list.
- The host country is not added: the Worker does not store it.

* Read the Signal home from the ticket claim

The local review found that a host-name list in the desktop must change
with each new home, and that the old attempt check was missing.

- signal_home is now the `signal` claim of the ticket, or `entry` when
  the ticket has no claim. A claim that is not a short lowercase name is
  `other`. The desktop list and the new deployment step are removed.
- Record the home only while the attempt is current.
- The E2E test records the home after the ticket step, with real ticket
  shapes.
- ANALYTICS.md says that the entry name can move at failover.

* Do not export signalHomeOf

Knip found that only remote-connect-trace.ts uses it.
2026-11-19 18:19:20 +01:00

217 lines
7.6 KiB
TypeScript

import { mkdir, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { REMOTE_TICKET_AUDIENCE, type RemoteTicketClaims } from "@openbot/contracts/signal-protocol/ticket";
import { createOpenBotLogger } from "@openbot/logging";
import { ANALYTICS_GENERATIONS } from "@openbot/telemetry";
import { HostAnalytics, type HostOpenPanelClient } from "../src/main/analytics";
import { REMOTE_CONNECT_PHASES, RemoteConnectTrace } from "../src/main/remote-connect-trace";
const ROOT = resolve(import.meta.dirname, "..");
const OUT = join(ROOT, ".openbot-build", "remote-connect-analytics-e2e");
const HOST = "host-7f3a-marker";
const OTHER_HOST = "host-91c2-marker";
const LAST_HOST = "host-55d0-marker";
const PHASE_PROPERTIES = [
"session_ms",
"ticket_ms",
"bridge_ms",
"signal_socket_ms",
"signal_ms",
"channels_ms",
"auth_ms",
"compatibility_ms",
"first_request_ms",
];
function ticket(claims: Pick<RemoteTicketClaims, "signal">): string {
const payload = Buffer.from(JSON.stringify({ aud: REMOTE_TICKET_AUDIENCE, ...claims })).toString("base64url");
return `${Buffer.from('{"alg":"EdDSA"}').toString("base64url")}.${payload}.signature`;
}
const US_TICKET = ticket({ signal: "us" });
const ENTRY_TICKET = ticket({});
type Sent = { name: string; properties: NonNullable<Parameters<HostOpenPanelClient["track"]>[1]> };
const sent: Sent[] = [];
const globals: Parameters<HostOpenPanelClient["setGlobalProperties"]>[0] = {};
const waiters: { count: number; resolve: () => void }[] = [];
function sentCount(count: number): Promise<void> {
if (sent.length >= count) return Promise.resolve();
return new Promise((resolve) => waiters.push({ count, resolve }));
}
const client: HostOpenPanelClient = {
setGlobalProperties: (properties) => Object.assign(globals, properties),
identify: async () => {},
clear: () => {},
track: async (name, properties = {}) => {
sent.push({ name, properties: { ...properties } });
for (const waiter of waiters.filter((item) => sent.length >= item.count)) {
waiters.splice(waiters.indexOf(waiter), 1);
waiter.resolve();
}
},
};
const checks: { name: string; passed: boolean; detail?: unknown }[] = [];
function check(name: string, passed: boolean, detail?: unknown) {
checks.push({ name, passed, ...(detail === undefined ? {} : { detail }) });
}
async function run() {
const analytics = new HostAnalytics(
{
enabled: true,
trackingEnabled: true,
appVersion: "0.0.0",
platform: "darwin",
resolveOwner: () => ({ id: "account-1", email: "owner@example.test" }),
resolveAgent: () => null,
},
() => client,
);
const trace = new RemoteConnectTrace(
() => {},
(summary) => analytics.handleRemoteConnect(summary),
);
const connect = (
hostId: string,
session: string,
firstRequest: "ok" | "error",
hostedWaitMs?: number,
afterBegin = () => {},
signalTicket = US_TICKET,
) => {
trace.begin(hostId);
afterBegin();
for (const phase of REMOTE_CONNECT_PHASES) {
if (phase === "compatibility" && hostedWaitMs !== undefined) trace.hostedStart(hostId, hostedWaitMs);
trace.mark(hostId, phase, phase === "session" ? session : phase === "first-request" ? firstRequest : "ok");
if (phase === "ticket") trace.signalHome(hostId, signalTicket);
}
};
const remoteEvents = () => sent.filter((event) => event.name === "system_remote_connect");
connect(HOST, "ok", "ok", 61_234);
await sentCount(1);
const first = remoteEvents()[0]?.properties ?? {};
check(
"a first connection sends its outcome, session, Signal home and every phase time",
first.outcome === "connected" &&
first.connection === "first" &&
first.session_kind === "new" &&
first.last_phase === "first-request" &&
first.first_request === "ok" &&
first.failed_attempts === 0 &&
first.signal_home === "us" &&
PHASE_PROPERTIES.every((key) => Number.isInteger(first[key])) &&
Number.isInteger(first.total_ms) &&
first.wait_ms === first.total_ms,
first,
);
check("the hosted start wait has two significant digits", first.hosted_start_wait_ms === 61_000, first);
const stored = trace.begin(HOST);
trace.mark(HOST, "session", "stored");
trace.fail(HOST, stored, "error");
await sentCount(2);
const failed = remoteEvents()[1]?.properties ?? {};
check(
"the first failed attempt sends its last phase",
failed.outcome === "failed" &&
failed.connection === "reconnect" &&
failed.session_kind === "stored" &&
failed.last_phase === "session" &&
Number.isInteger(failed.session_ms) &&
!("ticket_ms" in failed) &&
!("first_request" in failed) &&
!("signal_home" in failed) &&
!("hosted_start_wait_ms" in failed),
failed,
);
for (let attempt = 0; attempt < 2; attempt += 1) {
trace.fail(HOST, trace.begin(HOST), "error");
}
connect(HOST, "reused", "error", undefined, undefined, ENTRY_TICKET);
await sentCount(3);
const retried = remoteEvents()[2]?.properties ?? {};
check(
"later failures send nothing, and the next connection counts them and names the entry",
retried.outcome === "connected" &&
retried.connection === "reconnect" &&
retried.session_kind === "reused" &&
retried.first_request === "error" &&
retried.failed_attempts === 3 &&
retried.signal_home === "entry" &&
Number(retried.wait_ms) >= Number(retried.total_ms),
retried,
);
trace.fail(OTHER_HOST, trace.begin(OTHER_HOST), "cancelled");
const afterTicket = trace.begin(OTHER_HOST);
trace.mark(OTHER_HOST, "session");
trace.mark(OTHER_HOST, "ticket");
trace.signalHome(OTHER_HOST, ticket({ signal: "b" }));
trace.fail(OTHER_HOST, afterTicket, "error");
await sentCount(4);
const afterCancel = remoteEvents()[3]?.properties ?? {};
check(
"a cancel sends nothing, and the next failure after the ticket names its Signal home",
afterCancel.outcome === "failed" &&
afterCancel.connection === "first" &&
afterCancel.last_phase === "ticket" &&
afterCancel.signal_home === "b",
afterCancel,
);
const old = trace.begin(LAST_HOST);
connect(
LAST_HOST,
"ok",
"ok",
undefined,
() => trace.fail(LAST_HOST, old, "cancelled"),
ticket({ signal: "Not A Home!" }),
);
await sentCount(5);
const last = remoteEvents()[4]?.properties ?? {};
check(
"an old attempt that ends late does not stop the newer one, and a home claim that is not a name is other",
last.outcome === "connected" &&
last.connection === "first" &&
last.last_phase === "first-request" &&
last.signal_home === "other",
last,
);
check(
"only these five events were sent",
sent.length === 5,
sent.map((event) => event.name),
);
const body = JSON.stringify({ globals, sent });
check(
"no event names a host or has a ticket",
![HOST, OTHER_HOST, LAST_HOST, US_TICKET, ENTRY_TICKET, "Not A Home"].some((text) => body.includes(text)),
);
check(
"the events go on the host surface with its current generation",
globals.surface === "desktop_host" && globals.event_schema_version === ANALYTICS_GENERATIONS.desktop_host,
globals,
);
}
let passed = false;
try {
await run();
passed = checks.every((item) => item.passed);
} finally {
await mkdir(OUT, { recursive: true });
await writeFile(join(OUT, "report.json"), `${JSON.stringify({ passed, checks }, null, 2)}\n`);
}
const logger = createOpenBotLogger("remote-connect-analytics-e2e");
for (const item of checks) {
if (item.passed) logger.info(`ok ${item.name}`);
else logger.error(`FAIL ${item.name}`);
}
logger.info(`Report: ${join(OUT, "report.json")}`);
if (!passed) process.exit(1);