Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phones: pair through the relay instead of waiting on a removed HTTPS address (#5923)
Milind Soni58237ca8b75f
diff --git a/electron/companion-account-documents.mjs b/electron/companion-account-documents.mjsnew file mode 100644index 0000000000..995f0fbf2d--- /dev/null+++ b/electron/companion-account-documents.mjs@@ -0,0 +1,152 @@+// The account's fields in the secure credential document, and the pure reads and writes of them. Nothing here+// talks to the control plane or logs.+import { normalizeAccountEmail } from "./control-plane-client.mjs";+import {+ managedCompanionTunnelAccess,+ withManagedCompanionTunnelAccess,+ withoutManagedCompanionTunnelAccess,+} from "./managed-companion-tunnel.mjs";++export const COMPANION_CLIENT_INSTANCE_FIELD = "companionClientInstanceId";+export const COMPANION_ACCOUNT_TOKEN_FIELD = "companionAccountToken";+export const COMPANION_ACCOUNT_USER_ID_FIELD = "companionAccountUserId";+export const COMPANION_ACCOUNT_EMAIL_FIELD = "companionAccountEmail";+export const COMPANION_INSTALLATION_ID_FIELD = "companionInstallationId";+export const COMPANION_INSTALLATION_CREDENTIAL_FIELD = "companionInstallationCredential";+export const COMPANION_INSTALLATION_EXPIRY_FIELD = "companionInstallationCredentialExpiresAt";+export const COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD = "companionAccountCleanupPending";+export const COMPANION_ENDPOINT_RELEASE_PENDING_FIELD = "companionEndpointReleasePending";+/** The address was given back while phones were paired but unused; the control plane keeps its hostname. */+export const COMPANION_ENDPOINT_PAUSED_FIELD = "companionEndpointPaused";+/** The control plane ended this computer's secure address for old phone apps: phones connect through the relay only. */+export const COMPANION_TUNNEL_RETIRED_FIELD = "companionTunnelRetired";+/** The control plane holds no address for this computer although an old phone would use one (ended for old phone+ * apps, or every account full): the watchdog keeps asking, so the address returns when the relay is switched off+ * or room frees up. */+export const COMPANION_TUNNEL_WAITING_FIELD = "companionTunnelWaiting";++export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;+const INSTALLATION_ID = UUID;+const INSTALLATION_CREDENTIAL = /^omb_install_[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/;+export const ownString = (document, field) =>+ typeof document?.[field] === "string" ? document[field] : "";++export function companionAccountCleanupPending(credentials) {+ return credentials?.[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD] === true;+}+/** The control plane ended this signed-in computer's secure address for old phone apps ("retired"), and none came back. */ export const companionTunnelRetired = (credentials) => Boolean(storedAccount(credentials)) && !managedCompanionTunnelAccess(credentials) && credentials?.[COMPANION_TUNNEL_RETIRED_FIELD] === true;++export function storedAccount(credentials) {+ const email = normalizeAccountEmail(ownString(credentials, COMPANION_ACCOUNT_EMAIL_FIELD));+ const userId = ownString(credentials, COMPANION_ACCOUNT_USER_ID_FIELD);+ if (!email || !userId || userId.length > 256) return null;+ return {+ email,+ userId,+ accountToken: ownString(credentials, COMPANION_ACCOUNT_TOKEN_FIELD),+ installationId: INSTALLATION_ID.test(ownString(credentials, COMPANION_INSTALLATION_ID_FIELD))+ ? credentials[COMPANION_INSTALLATION_ID_FIELD]+ : "",+ installationCredential: INSTALLATION_CREDENTIAL.test(+ ownString(credentials, COMPANION_INSTALLATION_CREDENTIAL_FIELD),+ )+ ? credentials[COMPANION_INSTALLATION_CREDENTIAL_FIELD]+ : "",+ };+}++export function withoutCompanionAccount(credentials) {+ const next = withoutManagedCompanionTunnelAccess(credentials);+ for (const field of [+ COMPANION_ACCOUNT_TOKEN_FIELD,+ COMPANION_ACCOUNT_USER_ID_FIELD,+ COMPANION_ACCOUNT_EMAIL_FIELD,+ COMPANION_INSTALLATION_ID_FIELD,+ COMPANION_INSTALLATION_CREDENTIAL_FIELD,+ COMPANION_INSTALLATION_EXPIRY_FIELD,+ COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD,+ COMPANION_ENDPOINT_RELEASE_PENDING_FIELD,+ COMPANION_ENDPOINT_PAUSED_FIELD,+ COMPANION_TUNNEL_RETIRED_FIELD,+ COMPANION_TUNNEL_WAITING_FIELD,+ ]) {+ delete next[field];+ }+ // The installation UUID survives sign-out so a same-account recovery adopts the existing server record.+ return next;+}++export function withInstallationCredentials(credentials, installation) {+ const next = {+ ...credentials,+ [COMPANION_INSTALLATION_ID_FIELD]: installation.installation.id,+ [COMPANION_INSTALLATION_CREDENTIAL_FIELD]: installation.credential,+ };+ if (Number.isSafeInteger(installation.credentialExpiresAt)) {+ next[COMPANION_INSTALLATION_EXPIRY_FIELD] = installation.credentialExpiresAt;+ } else {+ delete next[COMPANION_INSTALLATION_EXPIRY_FIELD];+ }+ return next;+}++export function withProvisionedAccount(credentials, { accountToken, user, installation, provision }) {+ const next = {+ ...withInstallationCredentials(withManagedCompanionTunnelAccess(credentials, provision), installation),+ [COMPANION_ACCOUNT_TOKEN_FIELD]: accountToken,+ [COMPANION_ACCOUNT_USER_ID_FIELD]: user.id,+ [COMPANION_ACCOUNT_EMAIL_FIELD]: user.email,+ };+ delete next[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD];+ delete next[COMPANION_ENDPOINT_RELEASE_PENDING_FIELD];+ delete next[COMPANION_ENDPOINT_PAUSED_FIELD];+ delete next[COMPANION_TUNNEL_RETIRED_FIELD];+ delete next[COMPANION_TUNNEL_WAITING_FIELD];+ return next;+}++export function withAuthenticatedAccount(+ credentials,+ { accountToken, user, clientInstanceId, preserveCleanupPending = false },+) {+ const next = {+ ...credentials,+ [COMPANION_ACCOUNT_TOKEN_FIELD]: accountToken,+ [COMPANION_ACCOUNT_USER_ID_FIELD]: user.id,+ [COMPANION_ACCOUNT_EMAIL_FIELD]: user.email,+ };+ if (!UUID.test(ownString(next, COMPANION_CLIENT_INSTANCE_FIELD))) {+ next[COMPANION_CLIENT_INSTANCE_FIELD] = clientInstanceId;+ }+ if (preserveCleanupPending) {+ next[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD] = true;+ } else {+ delete next[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD];+ }+ return next;+}++export function publicState({ available, status, email, endpoint, message, paused, tunnelRetired }) {+ const state = { available: Boolean(available), status };+ if (paused === true) state.paused = true;+ if (tunnelRetired === true) state.tunnelRetired = true;+ const normalizedEmail = normalizeAccountEmail(email);+ if (normalizedEmail) state.email = normalizedEmail;+ const accessEndpoint = (() => {+ if (typeof endpoint !== "string") return "";+ try {+ const parsed = new URL(endpoint);+ return parsed.protocol === "https:" && parsed.pathname === "/" && !parsed.search && !parsed.hash+ ? parsed.origin+ : "";+ } catch {+ return "";+ }+ })();+ if (accessEndpoint) state.endpoint = accessEndpoint;+ const safeMessage = typeof message === "string" && message.length >= 1 && message.length <= 280+ ? message+ : null;+ if (safeMessage) state.message = safeMessage;+ return Object.freeze(state);+}diff --git a/electron/companion-account-ipc.node-test.mjs b/electron/companion-account-ipc.node-test.mjsindex 19631d2d0b..21196c24fa 100644--- a/electron/companion-account-ipc.node-test.mjs+++ b/electron/companion-account-ipc.node-test.mjs@@ -19,6 +19,7 @@ test("the desktop holds its address on demand, read from the running companion",let running = false;let answer = async () => ({ enabled: true, devices: [], pairing: null });const stateReads = [];+ const primed = [];const context = vm.createContext({companionAccountService: null,resolveCompanionControlPlaneURL: () => "",@@ -45,6 +46,7 @@ test("the desktop holds its address on demand, read from the running companion",return answer();},managedEndpointNeed,+ companionE2E: { prime: async () => { primed.push(1); } },});vm.runInContext(`${slice("function ensureCompanionAccountService()", "// Everything the bug-report bundle needs")}globalThis.ensure = ensureCompanionAccountService;`, context);@@ -54,6 +56,9 @@ test("the desktop holds its address on demand, read from the running companion",assert.equal(options.autoRecover, true);assert.equal(await options.managedEndpointNeeded(), null);assert.equal(stateReads.length, 0);+ // A new installation credential asks for the relay token at once.+ options.installationChanged();+ assert.equal(primed.length, 1);running = true;assert.equal(await options.managedEndpointNeeded(), false);@@ -72,6 +77,7 @@ test("prepare is local-only, takes nothing from the page, and an organisation caconst handlers = new Map();const prepared = [];const routes = [];+ const primed = [];let refusal = null;localOrigin.setLocalOrigin(origin);const context = vm.createContext({@@ -79,6 +85,7 @@ test("prepare is local-only, takes nothing from the page, and an organisation calocalOnly: localOrigin.localOnly,managedRemoteAccessRefusal: () => refusal,rememberCompanionRoute: async (route, on) => { routes.push([route, on]); },+ companionE2E: { prime: async () => { primed.push(1); } },ensureCompanionAccountService: () => ({state: () => ({ status: "ready" }),requestCode: () => ({}),@@ -99,9 +106,75 @@ test("prepare is local-only, takes nothing from the page, and an organisation caassert.deepEqual(await prepare(local, { endpoint: "https://evil.example.test" }), { available: true, status: "ready" });assert.deepEqual(prepared, [[]]);assert.deepEqual(routes, [["https", true]], "setting up the secure address is the person turning the HTTPS address on");+ assert.equal(primed.length, 1, "a person pairing asks for the relay token before a code opens");assert.throws(() => prepare({ senderFrame: { url: "https://remote.example.test/" } }), /only available/);refusal = "Example Org does not allow remote access to this computer.";assert.throws(() => prepare(local), /Example Org does not allow remote access/);assert.equal(prepared.length, 1);+ assert.equal(primed.length, 1);+});++test("the connector reports every status to the account service", () => {+ let options;+ const reported = [];+ const context = vm.createContext({+ managedCompanionConnector: null,+ createManagedCompanionTunnel: (passed) => {+ options = passed;+ return { fixture: true };+ },+ resolveCloudflaredBinary: () => "/fixture/cloudflared",+ resolveManagedCompanionGuardian: () => "/fixture/guardian.mjs",+ app: { isPackaged: true, getAppPath: () => "/fixture", getPath: () => "/fixture" },+ process: { resourcesPath: "/fixture", execPath: "/fixture/node" },+ path: { join: (...parts) => parts.join("/") },+ slog: () => {},+ companionAccountService: { connectorChanged: (status) => reported.push(status.status) },+ companionDesiredThisLaunch: false,+ });+ vm.runInContext(`${slice("function ensureManagedCompanionConnector()", "function reconcileCompanionAdvertisement(")}+ globalThis.ensure = ensureManagedCompanionConnector;`, context);+ context.ensure();+ for (const status of ["starting", "retrying", "ready"]) options.onChange({ status, ready: status === "ready" });+ assert.deepEqual(reported, ["starting", "retrying", "ready"]);+});++test("starting the phone link checks a stored address first and waits on it only without Anywhere", async () => {+ const starts = [];+ const routesOn = new Set();+ const context = vm.createContext({+ managedRemoteAccessRefusal: () => null,+ companionDesiredThisLaunch: false,+ companionLaunchGeneration: 0,+ startCompanion: async () => ({ enabled: true }),+ companionLaunchOptions: () => ({}),+ rememberCompanionRoute: async (route, on) => { if (on) routesOn.add(route); },+ phoneLinkRoutes: { touched: () => {} },+ companionRouteOn: (route) => routesOn.has(route),+ managedCompanionTunnelAccess: () => ({ endpoint: "https://c-fixture.example.test", token: "fixture" }),+ secureCredentials: {},+ companionAccountService: { checkStoredAddress: async () => null },+ startManagedCompanionConnection: async () => ({}),+ startCheckedManagedConnection: async (options) => { starts.push(options); },+ desktopCompanionState: async () => ({ enabled: true }),+ });+ vm.runInContext(`${slice("async function startDesktopCompanion(", "async function stopDesktopCompanion(")}+ globalThis.start = startDesktopCompanion;`, context);++ // Pairing's start turns Same Wi-Fi and Anywhere on: it never waits on the HTTPS address.+ await context.start();+ // A Wi-Fi or Tailscale start (explicit, no routes) does not wait either.+ await context.start({ routes: [] });+ // Only a start without Anywhere that turns a route on still waits for the address to verify.+ routesOn.clear();+ await context.start({ routes: ["wifi"] });+ await context.start({ waitForHosted: false, remember: false });+ assert.deepEqual(starts.map((options) => options.wait), [false, false, true, false]);+ // The check asks the account service only while the HTTPS address is on and stored.+ assert.equal(starts[0].check(), null);+ routesOn.add("https");+ assert.equal(typeof starts[0].check()?.then, "function");+ assert.equal(starts[0].start, context.startManagedCompanionConnection);+ assert.equal(starts[0].desired(), true);});diff --git a/electron/companion-account-service.d.mts b/electron/companion-account-service.d.mtsindex bed332edda..2e70fcc620 100644--- a/electron/companion-account-service.d.mts+++ b/electron/companion-account-service.d.mts@@ -51,6 +51,10 @@ export interface CompanionAccountService {retry(): Promise<CompanionAccountState>;/** On demand: create or repair the address because a person is pairing. */prepare(): Promise<CompanionAccountState>;+ /** Before the connector dials a stored address: asks whether it still exists (null when nothing changed). */+ checkStoredAddress(): Promise<CompanionAccountState | null>;+ /** The managed connector's status as it changes: verify failures check the address with the control plane. */+ connectorChanged(status: { status: string } | null | undefined): void;signOut(): Promise<CompanionAccountState>;restore(): Promise<CompanionAccountState>;/** Cancels background recovery timers (autoRecover only). */@@ -88,6 +92,10 @@ export declare function createCompanionAccountService(options: {relay?: { capable: () => boolean; legacyDevices: () => Promise<number | null> };releaseGraceMs?: number;releaseJitterMs?: number;+ /** The first wait between two out-of-turn checks of an address that does not answer (then 3x, then 12x). */+ forcedCheckIntervalMs?: number;+ /** A new installation credential was stored. */+ installationChanged?: () => void;/** One line per failed setup step: code, HTTP status, request id, retry delay. */log?: (line: string) => void;}): CompanionAccountService;diff --git a/electron/companion-account-service.mjs b/electron/companion-account-service.mjsindex edaaa1ad7d..a612a01771 100644--- a/electron/companion-account-service.mjs+++ b/electron/companion-account-service.mjs@@ -8,9 +8,42 @@ import {MANAGED_COMPANION_RELEASE_AT_FIELD,managedCompanionTunnelAccess,normalizeManagedCompanionEndpoint,- withManagedCompanionTunnelAccess,withoutManagedCompanionTunnelAccess,} from "./managed-companion-tunnel.mjs";+import {+ COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD,+ COMPANION_CLIENT_INSTANCE_FIELD,+ COMPANION_ENDPOINT_PAUSED_FIELD,+ COMPANION_ENDPOINT_RELEASE_PENDING_FIELD,+ COMPANION_TUNNEL_RETIRED_FIELD,+ COMPANION_TUNNEL_WAITING_FIELD,+ UUID,+ companionAccountCleanupPending,+ companionTunnelRetired,+ ownString,+ publicState,+ storedAccount,+ withAuthenticatedAccount,+ withInstallationCredentials,+ withoutCompanionAccount,+ withProvisionedAccount,+} from "./companion-account-documents.mjs";+export {+ COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD,+ COMPANION_ACCOUNT_EMAIL_FIELD,+ COMPANION_ACCOUNT_TOKEN_FIELD,+ COMPANION_ACCOUNT_USER_ID_FIELD,+ COMPANION_CLIENT_INSTANCE_FIELD,+ COMPANION_ENDPOINT_PAUSED_FIELD,+ COMPANION_ENDPOINT_RELEASE_PENDING_FIELD,+ COMPANION_INSTALLATION_CREDENTIAL_FIELD,+ COMPANION_INSTALLATION_EXPIRY_FIELD,+ COMPANION_INSTALLATION_ID_FIELD,+ COMPANION_TUNNEL_RETIRED_FIELD,+ COMPANION_TUNNEL_WAITING_FIELD,+ companionAccountCleanupPending,+ companionTunnelRetired,+} from "./companion-account-documents.mjs";import { MANAGED_ENDPOINT_PHONES_UNUSED } from "./companion-endpoint-need.mjs";import { FRIENDLY_MESSAGES, friendlyCompanionAccountError } from "./companion-account-messages.mjs";export { friendlyCompanionAccountError };@@ -19,27 +52,6 @@ export { managedEndpointNeed, PHONE_UNUSED_RELEASE_MS } from "./companion-endpoiexport const DEFAULT_COMPANION_CONTROL_PLANE_URL = "https://accounts.openmausbot.com";-export const COMPANION_CLIENT_INSTANCE_FIELD = "companionClientInstanceId";-export const COMPANION_ACCOUNT_TOKEN_FIELD = "companionAccountToken";-export const COMPANION_ACCOUNT_USER_ID_FIELD = "companionAccountUserId";-export const COMPANION_ACCOUNT_EMAIL_FIELD = "companionAccountEmail";-export const COMPANION_INSTALLATION_ID_FIELD = "companionInstallationId";-export const COMPANION_INSTALLATION_CREDENTIAL_FIELD = "companionInstallationCredential";-export const COMPANION_INSTALLATION_EXPIRY_FIELD = "companionInstallationCredentialExpiresAt";-export const COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD = "companionAccountCleanupPending";-export const COMPANION_ENDPOINT_RELEASE_PENDING_FIELD = "companionEndpointReleasePending";-/** The address was given back while phones were paired but unused; the control plane keeps its hostname. */-export const COMPANION_ENDPOINT_PAUSED_FIELD = "companionEndpointPaused";-/** The control plane ended this computer's secure address for old phone apps: phones connect through the relay only. */-export const COMPANION_TUNNEL_RETIRED_FIELD = "companionTunnelRetired";-/** The control plane holds no address for this computer although an old phone would use one (ended for old phone- * apps, or every account full): the watchdog keeps asking, so the address returns when the relay is switched off- * or room frees up. */-export const COMPANION_TUNNEL_WAITING_FIELD = "companionTunnelWaiting";--const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;-const INSTALLATION_ID = UUID;-const INSTALLATION_CREDENTIAL = /^omb_install_[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/;const DEFAULT_HEALTH_CACHE_MS = 30_000;const DEFAULT_AUTO_RETRY_BASE_MS = 10 * 60_000;const DEFAULT_AUTO_RETRY_MAX_MS = 6 * 60 * 60_000;@@ -69,15 +81,18 @@ const WATCHDOG_CHECK_STATES = new Set(["starting", "ready", "retrying", "error"]const CONNECTOR_FAILING_STATES = new Set(["retrying", "error"]);+/** Verify failures in a row after which a stored address is checked with the control plane. */+const FORCED_CHECK_AFTER_FAILURES = 2;+const DEFAULT_FORCED_CHECK_INTERVAL_MS = 10 * 60_000;+/** Each such check waits longer (10 min, 30 min, then 2 h with the default), until a connection verifies. */+const FORCED_CHECK_STEPS = [1, 3, 12];+const defaultSetTimer = (callback, milliseconds) => {const timer = setTimeout(callback, milliseconds);timer.unref?.();return timer;};-const ownString = (document, field) =>- typeof document?.[field] === "string" ? document[field] : "";-/** Development must name an exact origin so an OTP or bearer never reaches an accidental host; an invalid override disables the feature. */export function resolveCompanionControlPlaneURL({isPackaged,@@ -89,126 +104,6 @@ export function resolveCompanionControlPlaneURL({return isPackaged ? DEFAULT_COMPANION_CONTROL_PLANE_URL : "";}-export function companionAccountCleanupPending(credentials) {- return credentials?.[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD] === true;-}-/** The control plane ended this signed-in computer's secure address for old phone apps ("retired"), and none came back. */ export const companionTunnelRetired = (credentials) => Boolean(storedAccount(credentials)) && !managedCompanionTunnelAccess(credentials) && credentials?.[COMPANION_TUNNEL_RETIRED_FIELD] === true;--function storedAccount(credentials) {- const email = normalizeAccountEmail(ownString(credentials, COMPANION_ACCOUNT_EMAIL_FIELD));- const userId = ownString(credentials, COMPANION_ACCOUNT_USER_ID_FIELD);- if (!email || !userId || userId.length > 256) return null;- return {- email,- userId,- accountToken: ownString(credentials, COMPANION_ACCOUNT_TOKEN_FIELD),- installationId: INSTALLATION_ID.test(ownString(credentials, COMPANION_INSTALLATION_ID_FIELD))- ? credentials[COMPANION_INSTALLATION_ID_FIELD]- : "",- installationCredential: INSTALLATION_CREDENTIAL.test(- ownString(credentials, COMPANION_INSTALLATION_CREDENTIAL_FIELD),- )- ? credentials[COMPANION_INSTALLATION_CREDENTIAL_FIELD]- : "",- };-}--function withoutCompanionAccount(credentials) {- const next = withoutManagedCompanionTunnelAccess(credentials);- for (const field of [- COMPANION_ACCOUNT_TOKEN_FIELD,- COMPANION_ACCOUNT_USER_ID_FIELD,- COMPANION_ACCOUNT_EMAIL_FIELD,- COMPANION_INSTALLATION_ID_FIELD,- COMPANION_INSTALLATION_CREDENTIAL_FIELD,- COMPANION_INSTALLATION_EXPIRY_FIELD,- COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD,- COMPANION_ENDPOINT_RELEASE_PENDING_FIELD,- COMPANION_ENDPOINT_PAUSED_FIELD,- COMPANION_TUNNEL_RETIRED_FIELD,- COMPANION_TUNNEL_WAITING_FIELD,- ]) {- delete next[field];- }- // The installation UUID survives sign-out so a same-account recovery adopts the existing server record.- return next;-}--function withInstallationCredentials(credentials, installation) {- const next = {- ...credentials,- [COMPANION_INSTALLATION_ID_FIELD]: installation.installation.id,- [COMPANION_INSTALLATION_CREDENTIAL_FIELD]: installation.credential,- };- if (Number.isSafeInteger(installation.credentialExpiresAt)) {- next[COMPANION_INSTALLATION_EXPIRY_FIELD] = installation.credentialExpiresAt;- } else {- delete next[COMPANION_INSTALLATION_EXPIRY_FIELD];- }- return next;-}--function withProvisionedAccount(credentials, { accountToken, user, installation, provision }) {- const next = {- ...withInstallationCredentials(withManagedCompanionTunnelAccess(credentials, provision), installation),- [COMPANION_ACCOUNT_TOKEN_FIELD]: accountToken,- [COMPANION_ACCOUNT_USER_ID_FIELD]: user.id,- [COMPANION_ACCOUNT_EMAIL_FIELD]: user.email,- };- delete next[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD];- delete next[COMPANION_ENDPOINT_RELEASE_PENDING_FIELD];- delete next[COMPANION_ENDPOINT_PAUSED_FIELD];- delete next[COMPANION_TUNNEL_RETIRED_FIELD];- delete next[COMPANION_TUNNEL_WAITING_FIELD];- return next;-}--function withAuthenticatedAccount(- credentials,- { accountToken, user, clientInstanceId, preserveCleanupPending = false },-) {- const next = {- ...credentials,- [COMPANION_ACCOUNT_TOKEN_FIELD]: accountToken,- [COMPANION_ACCOUNT_USER_ID_FIELD]: user.id,- [COMPANION_ACCOUNT_EMAIL_FIELD]: user.email,- };- if (!UUID.test(ownString(next, COMPANION_CLIENT_INSTANCE_FIELD))) {- next[COMPANION_CLIENT_INSTANCE_FIELD] = clientInstanceId;- }- if (preserveCleanupPending) {- next[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD] = true;- } else {- delete next[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD];- }- return next;-}--function publicState({ available, status, email, endpoint, message, paused, tunnelRetired }) {- const state = { available: Boolean(available), status };- if (paused === true) state.paused = true;- if (tunnelRetired === true) state.tunnelRetired = true;- const normalizedEmail = normalizeAccountEmail(email);- if (normalizedEmail) state.email = normalizedEmail;- const accessEndpoint = (() => {- if (typeof endpoint !== "string") return "";- try {- const parsed = new URL(endpoint);- return parsed.protocol === "https:" && parsed.pathname === "/" && !parsed.search && !parsed.hash- ? parsed.origin- : "";- } catch {- return "";- }- })();- if (accessEndpoint) state.endpoint = accessEndpoint;- const safeMessage = typeof message === "string" && message.length >= 1 && message.length <= 280- ? message- : null;- if (safeMessage) state.message = safeMessage;- return Object.freeze(state);-}-/** Nothing this service returns may contain an account bearer, installation credential, connector token or Cloudflare resource id. */export function createCompanionAccountService({client,@@ -236,6 +131,9 @@ export function createCompanionAccountService({relay = { capable: () => false, legacyDevices: async () => null },releaseGraceMs = DEFAULT_RELEASE_GRACE_MS,releaseJitterMs = DEFAULT_RELEASE_JITTER_MS,+ forcedCheckIntervalMs = DEFAULT_FORCED_CHECK_INTERVAL_MS,+ /** A new installation credential was stored: the relay token can be asked for now. */+ installationChanged = () => {},// Only the code, HTTP status, request id and retry delay: never an email, token, credential or address.log = () => {},} = {}) {@@ -251,6 +149,9 @@ export function createCompanionAccountService({let lastEndpointCheck = null;let requestedAt = null;let disposed = false;+ let connectorFailures = 0;+ let forcedChecks = 0;+ let nextForcedCheckAt = null;const serialize = (work) => {const next = transition.then(work, work);@@ -500,7 +401,8 @@ export function createCompanionAccountService({});};- const provision = async ({ accountToken, user }) => {+ /** `addressGone`: the control plane said the stored address is gone, so it is forgotten even when no tunnel is asked for. */+ const provision = async ({ accountToken, user, addressGone = false }) => {const clientInstanceId = await ensureClientIdentity();await finishPendingRelease();const before = credentials();@@ -524,7 +426,20 @@ export function createCompanionAccountService({}throw error;}+ if (previous?.installationCredential !== installation.credential) {+ try {+ installationChanged();+ } catch {+ }+ }+ // The control plane answers for the address below: no separate check is due.+ lastEndpointCheck = now();const withoutTunnel = async () => {+ if (addressGone && managedCompanionTunnelAccess(credentials())) {+ await stopManagedEndpoint();+ await updateCredentials(withoutManagedCompanionTunnelAccess);+ writeLog("companion account: forgot a secure address that is gone; phones connect through the relay");+ }await updateCredentials((document) => withAuthenticatedAccount(document, { accountToken, user, clientInstanceId }));resetAutoRetry();return (phase = null), settledState();@@ -693,7 +608,7 @@ export function createCompanionAccountService({}});- const retryWork = async () => {+ const retryWork = async ({ addressGone = false } = {}) => {if (!configured) return settledState();const account = storedAccount(credentials());if (!account) {@@ -716,6 +631,7 @@ export function createCompanionAccountService({return await provision({accountToken: account.accountToken,user: { id: account.userId, email: account.email },+ addressGone: addressGone === true,});} catch (error) {failAction(error, { email: account.email, expiredSessionIsSignedOut: true });@@ -729,32 +645,33 @@ export function createCompanionAccountService({return retryWork();});- /** Re-provisions only on a definitive "no endpoint" answer; a network or service failure keeps everything as is. */- const reconcileIfEndpointGone = async ({ onGone = retryWork } = {}) => {+ /** Re-provisions only on a definitive "no endpoint" answer; a network or service failure keeps everything as is.+ * `gone`: the control plane no longer holds this address (none, deleted, another one, or this credential refused). */+ const reconcileIfEndpointGone = async ({ onGone = ({ gone } = {}) => retryWork({ addressGone: gone === true }) } = {}) => {const document = credentials();const account = storedAccount(document);const access = managedCompanionTunnelAccess(document);- if (- !account ||- !access ||- !account.installationCredential ||- companionAccountCleanupPending(document) ||- typeof client.getEndpoint !== "function"- ) {- return null;- }+ if (!account || !access || companionAccountCleanupPending(document)) return null;+ // A stored address without a usable installation credential can never be checked, released or given a relay+ // token: provisioning again (with the account) is the only way it is ever asked about.+ if (!account.installationCredential) {+ // Counted as a check, so a provisioning that keeps failing is tried once per check interval, not per event.+ lastEndpointCheck = now();+ return onGone({ gone: false });+ }+ if (typeof client.getEndpoint !== "function") return null;lastEndpointCheck = now();let endpoint;try {endpoint = await client.getEndpoint(account.installationCredential);} catch (error) {- if (error instanceof ControlPlaneError && error.status === 401) return onGone();+ if (error instanceof ControlPlaneError && error.status === 401) return onGone({ gone: true });return null;}if (endpoint && endpoint.url === access.endpoint && !ENDPOINT_NEEDS_RECONCILE.has(endpoint.status)) {return null;}- return onGone();+ return onGone({ gone: !endpoint || endpoint.url !== access.endpoint || endpoint.status !== "error" });};const endpointCheckDue = () =>@@ -909,15 +826,77 @@ export function createCompanionAccountService({if (!managedCompanionTunnelAccess(document)) return retryWork();await cancelRelease();const connection = managedConnectionState?.() ?? {};- if (["stopped", "unconfigured"].includes(connection.status)) {- await activatePersistedEndpoint();- } else if (CONNECTOR_FAILING_STATES.has(connection.status)) {+ // A stored address may have been removed while this computer was away: ask before a pairing waits on it, so a+ // gone one is provisioned again (or forgotten for the relay) instead of being dialled.+ if (connection.status !== "ready" && (CONNECTOR_FAILING_STATES.has(connection.status) || endpointCheckDue())) {const repaired = await reconcileIfEndpointGone();if (repaired) return repaired;}+ if (["stopped", "unconfigured"].includes(managedConnectionState?.()?.status)) {+ await activatePersistedEndpoint();+ }return settledState();});+ /** Before the connector dials a stored address: ask the control plane whether it still exists, at most once per+ * half check interval. A gone address is provisioned again, which on `relay_capable` forgets it. */+ const checkStoredAddress = () => serialize(async () => {+ const document = credentials();+ if (+ !configured ||+ disposed ||+ phase?.status === "signed-out" ||+ !companionIsOn() ||+ !managedCompanionTunnelAccess(document) ||+ !endpointCheckDue()+ ) {+ return null;+ }+ return reconcileIfEndpointGone();+ });++ /** The connector's status, as it changes. Verify failures in a row check the address with the control plane, on a+ * growing, jittered interval that a verified connection resets (the start and prepare() check it when due). A+ * server-listed address is never dropped because this computer cannot reach it: only the control plane's "gone"+ * forgets it. */+ const connectorChanged = (status) => {+ if (disposed || !configured) return;+ if (status?.status === "ready") {+ connectorFailures = 0;+ forcedChecks = 0;+ nextForcedCheckAt = null;+ return;+ }+ if (status?.status === "stopped" || status?.status === "unconfigured") {+ connectorFailures = 0;+ return;+ }+ if (status?.status !== "retrying") return;+ connectorFailures += 1;+ void serialize(async () => {+ const document = credentials();+ if (+ phase?.status === "signed-out" ||+ !companionIsOn() ||+ !storedAccount(document) ||+ !managedCompanionTunnelAccess(document) ||+ companionAccountCleanupPending(document) ||+ autoRetryTimer !== null ||+ !CONNECTOR_FAILING_STATES.has(managedConnectionState?.()?.status)+ ) {+ return null;+ }+ if (connectorFailures < FORCED_CHECK_AFTER_FAILURES || (nextForcedCheckAt !== null && now() < nextForcedCheckAt)) return null;+ const step = forcedCheckIntervalMs * FORCED_CHECK_STEPS[Math.min(forcedChecks, FORCED_CHECK_STEPS.length - 1)];+ nextForcedCheckAt = now() + Math.round(step * (0.8 + 0.4 * random()));+ forcedChecks += 1;+ connectorFailures = 0;+ if (!(await probeControlPlane())) return null;+ writeLog("companion account: the secure address did not answer; checking it with the control plane");+ return reconcileIfEndpointGone();+ }).catch(() => {});+ };+const watchdogTick = () => {watchdogTimer = null;if (disposed) return;@@ -993,6 +972,8 @@ export function createCompanionAccountService({verifyCode,retry,prepare,+ checkStoredAddress,+ connectorChanged,signOut,restore,dispose,diff --git a/electron/companion-account-service.test.mjs b/electron/companion-account-service.test.mjsindex 94213007e9..c92bf6f1e7 100644--- a/electron/companion-account-service.test.mjs+++ b/electron/companion-account-service.test.mjs@@ -1805,11 +1805,19 @@ describe("Companion account on demand", () => {[MANAGED_COMPANION_TOKEN_FIELD]: RECLAIMED_TOKEN,});- const stopped = onDemandFixture({ client: readyClient({ getEndpoint: vi.fn(async () => null) }) });+ // A stopped connector dials its stored address only once the control plane still lists it, and asks once per+ // half check interval.+ const stopped = onDemandFixture({+ client: readyClient({ getEndpoint: vi.fn(async () => ({ url: ENDPOINT, status: "ready" })) }),+ });stopped.companion.connection = { status: "stopped", ready: false };await stopped.service.prepare();+ expect(stopped.client.getEndpoint).toHaveBeenCalledOnce();expect(stopped.activatePersistedEndpoint).toHaveBeenCalledOnce();- for (const call of network) expect(stopped.client[call]).not.toHaveBeenCalled();+ await stopped.service.prepare();+ expect(stopped.client.getEndpoint).toHaveBeenCalledOnce();+ expect(stopped.activatePersistedEndpoint).toHaveBeenCalledTimes(2);+ for (const call of network.filter((name) => name !== "getEndpoint")) expect(stopped.client[call]).not.toHaveBeenCalled();for (const [initial, on] of [[signedInWithoutAddress(), false],@@ -2245,3 +2253,237 @@ describe("Companion account on demand", () => {paired.service.dispose();});});++describe("A stored address the control plane no longer holds", () => {+ const relayCapable = () => new ControlPlaneError("relay_capable", 409);++ it("prepare() asks while the connector is still starting, and forgets a deleted address for the relay", async () => {+ for (const capable of [false, true]) {+ const client = readyClient({+ getEndpoint: vi.fn(async () => ({ url: ENDPOINT, status: "deleted" })),+ ensureEndpoint: vi.fn(async () => Promise.reject(relayCapable())),+ });+ const f = onDemandFixture({ client, relay: { capable: () => capable, legacyDevices: async () => 0 } });+ f.companion.connection = { status: "starting", ready: false };+ const state = await f.service.prepare();+ expect(client.getEndpoint).toHaveBeenCalledOnce();+ expect(state).toEqual({ available: true, status: "ready", email: "[email protected]" });+ for (const field of ADDRESS_FIELDS) expect(f.store.read()).not.toHaveProperty(field);+ expect(f.stopManagedEndpoint).toHaveBeenCalled();+ expect(f.activatePersistedEndpoint).not.toHaveBeenCalled();+ f.service.dispose();+ }+ });++ it("provisions again with the account when the installation credential is missing, instead of dialling", async () => {+ const installationChanged = vi.fn();+ const client = readyClient({+ getEndpoint: vi.fn(async () => ({ url: ENDPOINT, status: "ready" })),+ ensureEndpoint: vi.fn(async () => Promise.reject(relayCapable())),+ });+ const f = onDemandFixture({+ initial: signedCredentials({ [COMPANION_INSTALLATION_CREDENTIAL_FIELD]: undefined }),+ client,+ installationChanged,+ relay: { capable: () => false, legacyDevices: async () => 0 },+ });+ f.companion.connection = { status: "stopped", ready: false };+ const state = await f.service.prepare();+ expect(client.getEndpoint).not.toHaveBeenCalled();+ expect(client.ensureInstallation).toHaveBeenCalledWith(expect.objectContaining({ currentCredential: "" }));+ expect(installationChanged).toHaveBeenCalledOnce();+ expect(f.store.read()[COMPANION_INSTALLATION_CREDENTIAL_FIELD]).toBe(INSTALLATION_CREDENTIAL);+ for (const field of ADDRESS_FIELDS) expect(f.store.read()).not.toHaveProperty(field);+ expect(f.activatePersistedEndpoint).not.toHaveBeenCalled();+ expect(state).toEqual({ available: true, status: "ready", email: "[email protected]" });+ // Nothing secret reaches the log.+ for (const line of f.lines()) {+ expect(line).not.toContain(INSTALLATION_CREDENTIAL);+ expect(line).not.toContain(ACCOUNT_TOKEN);+ expect(line).not.toContain(CONNECTOR_TOKEN);+ expect(line).not.toContain(ENDPOINT);+ }+ f.service.dispose();+ });++ it("checkStoredAddress() asks before the connector dials, once per half check interval", async () => {+ const client = readyClient({+ getEndpoint: vi.fn(async () => null),+ ensureEndpoint: vi.fn(async () => Promise.reject(relayCapable())),+ });+ const f = onDemandFixture({ client, relay: { capable: () => true, legacyDevices: async () => 0 } });+ f.companion.connection = { status: "stopped", ready: false };+ await f.service.checkStoredAddress();+ expect(client.getEndpoint).toHaveBeenCalledOnce();+ for (const field of ADDRESS_FIELDS) expect(f.store.read()).not.toHaveProperty(field);+ expect(f.activatePersistedEndpoint).not.toHaveBeenCalled();+ // Nothing is stored any more: nothing to ask about.+ await expect(f.service.checkStoredAddress()).resolves.toBeNull();+ expect(client.getEndpoint).toHaveBeenCalledOnce();+ f.service.dispose();++ const kept = onDemandFixture({ client: readyClient({ getEndpoint: vi.fn(async () => ({ url: ENDPOINT, status: "ready" })) }) });+ await expect(kept.service.checkStoredAddress()).resolves.toBeNull();+ await expect(kept.service.checkStoredAddress()).resolves.toBeNull();+ expect(kept.client.getEndpoint).toHaveBeenCalledOnce();+ expect(kept.store.read()[MANAGED_COMPANION_ENDPOINT_FIELD]).toBe(ENDPOINT);+ kept.clock.now += WATCHDOG_INTERVAL_MS;+ await kept.service.checkStoredAddress();+ expect(kept.client.getEndpoint).toHaveBeenCalledTimes(2);+ kept.service.dispose();++ const off = onDemandFixture({ client: readyClient({ getEndpoint: vi.fn(async () => null) }) });+ off.companion.on = false;+ await expect(off.service.checkStoredAddress()).resolves.toBeNull();+ expect(off.client.getEndpoint).not.toHaveBeenCalled();+ off.service.dispose();+ });++ it("checks the address after verify failures in a row, on a growing jittered interval a verified connection resets", async () => {+ const client = readyClient({ getEndpoint: vi.fn(async () => ({ url: ENDPOINT, status: "ready" })) });+ const f = onDemandFixture({ client, forcedCheckIntervalMs: 10 * WATCHDOG_INTERVAL_MS });+ f.companion.need = true;+ const failing = { status: "retrying", ready: false };+ f.companion.connection = failing;+ const checks = () => f.lines().filter((line) => line.endsWith("checking it with the control plane")).length;+ const fail = async (times = 1) => {+ for (let attempt = 0; attempt < times; attempt += 1) f.service.connectorChanged(failing);+ await settle();+ };++ await fail();+ expect(client.getEndpoint).not.toHaveBeenCalled();+ await fail();+ expect(client.getEndpoint).toHaveBeenCalledOnce();+ expect(checks()).toBe(1);+ // Listed by the control plane: kept, never re-provisioned, released or deleted because this computer can't reach it.+ for (const call of ["ensureEndpoint", "deleteEndpoint", "ensureInstallation"]) expect(client[call]).not.toHaveBeenCalled();+ expect(f.store.read()[MANAGED_COMPANION_ENDPOINT_FIELD]).toBe(ENDPOINT);+ expect(f.stopManagedEndpoint).not.toHaveBeenCalled();++ await fail(6);+ expect(checks()).toBe(1);+ // 10, then 30 intervals (random() is 0.5 here: no jitter).+ f.clock.now += 10 * WATCHDOG_INTERVAL_MS;+ await fail(2);+ expect(checks()).toBe(2);+ f.clock.now += 10 * WATCHDOG_INTERVAL_MS;+ await fail(2);+ expect(checks()).toBe(2);+ f.clock.now += 20 * WATCHDOG_INTERVAL_MS;+ await fail(2);+ expect(checks()).toBe(3);++ // A verified connection starts over: two failures check at once again.+ f.service.connectorChanged({ status: "ready", ready: true });+ await fail(2);+ expect(checks()).toBe(4);+ expect(client.ensureEndpoint).not.toHaveBeenCalled();+ f.service.dispose();+ });++ it("acts on the control plane's answer after failures: listed is kept, gone is provisioned again or forgotten", async () => {+ for (const [answer, need] of [["listed", true], ["listed", false], ["gone", true], ["gone", false]]) {+ const client = readyClient({+ getEndpoint: vi.fn(async () => (answer === "listed" ? { url: ENDPOINT, status: "ready" } : { url: ENDPOINT, status: "deleted" })),+ ensureEndpoint: vi.fn(async () => ({ endpoint: { url: ENDPOINT }, connectorToken: RECLAIMED_TOKEN })),+ });+ const f = onDemandFixture({ client, relay: { capable: () => true, legacyDevices: async () => (need ? 1 : 0) } });+ f.companion.need = need;+ const failing = { status: "retrying", ready: false };+ f.companion.connection = failing;+ f.service.connectorChanged(failing);+ f.service.connectorChanged(failing);+ await settle();+ const label = `${answer}, need ${need}`;+ expect(client.getEndpoint, label).toHaveBeenCalledOnce();+ expect(client.deleteEndpoint, label).not.toHaveBeenCalled();+ if (answer === "listed") {+ expect(client.ensureEndpoint, label).not.toHaveBeenCalled();+ expect(f.store.read()[MANAGED_COMPANION_TOKEN_FIELD], label).toBe(CONNECTOR_TOKEN);+ expect(f.stopManagedEndpoint, label).not.toHaveBeenCalled();+ } else if (need) {+ expect(client.ensureEndpoint, label).toHaveBeenCalledOnce();+ expect(f.store.read()[MANAGED_COMPANION_TOKEN_FIELD], label).toBe(RECLAIMED_TOKEN);+ expect(f.activatePersistedEndpoint, label).toHaveBeenCalledOnce();+ } else {+ expect(client.ensureEndpoint, label).not.toHaveBeenCalled();+ for (const field of ADDRESS_FIELDS) expect(f.store.read(), label).not.toHaveProperty(field);+ expect(f.stopManagedEndpoint, label).toHaveBeenCalled();+ expect(await f.service.state(), label).toEqual({ available: true, status: "ready", email: "[email protected]" });+ }+ f.service.dispose();+ }+ });++ it("asks at most once per check interval when provisioning keeps failing without an installation credential", async () => {+ const withoutCredential = signedCredentials({ [COMPANION_INSTALLATION_CREDENTIAL_FIELD]: undefined });+ const failing = { status: "retrying", ready: false };+ const storm = async (f, events) => {+ for (let event = 0; event < events; event += 1) f.service.connectorChanged(failing);+ await settle();+ };++ // The account session expired: one attempt, then nothing while signed out, however long the connector retries.+ const expired = onDemandFixture({+ initial: withoutCredential,+ client: readyClient({ ensureInstallation: vi.fn(async () => Promise.reject(new ControlPlaneError("unauthorized", 401))) }),+ forcedCheckIntervalMs: WATCHDOG_INTERVAL_MS,+ });+ expired.companion.connection = failing;+ await storm(expired, 10);+ expect(expired.client.ensureInstallation).toHaveBeenCalledOnce();+ expect(await expired.service.state()).toMatchObject({ status: "signed-out" });+ for (let interval = 0; interval < 3; interval += 1) {+ expired.clock.now += 3 * WATCHDOG_INTERVAL_MS;+ await storm(expired, 10);+ }+ expect(expired.client.ensureInstallation).toHaveBeenCalledOnce();+ expired.service.dispose();++ // An error that schedules no retry, and a credential that cannot be stored: once per interval, never a loop of+ // rotations and revocations.+ for (const [label, overrides] of [+ ["no retry", { client: readyClient({ ensureInstallation: vi.fn(async () => Promise.reject(new ControlPlaneError("invalid_client_identity"))) }) }],+ ["write fails", { client: readyClient() }],+ ]) {+ const f = onDemandFixture({ initial: withoutCredential, forcedCheckIntervalMs: WATCHDOG_INTERVAL_MS, ...overrides });+ if (label === "write fails") {+ const write = f.store.update.getMockImplementation();+ f.store.update.mockImplementation(async (derive) => {+ const probe = derive({ ...f.store.read() });+ if (probe?.[COMPANION_INSTALLATION_CREDENTIAL_FIELD]) throw new Error("credential store unavailable");+ return write(derive);+ });+ }+ f.companion.connection = failing;+ await storm(f, 10);+ expect(f.client.ensureInstallation, label).toHaveBeenCalledOnce();+ await storm(f, 10);+ expect(f.client.ensureInstallation, label).toHaveBeenCalledOnce();+ f.clock.now += WATCHDOG_INTERVAL_MS;+ await storm(f, 10);+ expect(f.client.ensureInstallation, label).toHaveBeenCalledTimes(2);+ expect(f.client.revokeInstallation.mock.calls.length, label).toBeLessThanOrEqual(2);+ f.service.dispose();+ }+ });++ it("leaves a working or a signed-out computer alone", async () => {+ const client = readyClient({ getEndpoint: vi.fn(async () => null) });+ const working = onDemandFixture({ client });+ working.service.connectorChanged({ status: "ready", ready: true });+ working.service.connectorChanged({ status: "starting", ready: false });+ await settle();+ expect(client.getEndpoint).not.toHaveBeenCalled();+ working.service.dispose();++ const signedOut = onDemandFixture({ initial: { [COMPANION_CLIENT_INSTANCE_FIELD]: UUID }, client });+ signedOut.companion.connection = { status: "retrying", ready: false };+ signedOut.service.connectorChanged(signedOut.companion.connection);+ signedOut.service.connectorChanged(signedOut.companion.connection);+ await settle();+ for (const call of ["getEndpoint", "ensureInstallation", "ensureEndpoint"]) expect(client[call]).not.toHaveBeenCalled();+ signedOut.service.dispose();+ });+});diff --git a/electron/companion-e2e.mjs b/electron/companion-e2e.mjsindex ad520beeff..79471e6894 100644--- a/electron/companion-e2e.mjs+++ b/electron/companion-e2e.mjs@@ -94,6 +94,16 @@ export function createCompanionE2E({},/** A pairing window opened or a device changed: the relay may be needed now. */reconcile,+ /** A person is about to pair, or this computer just got a new installation credential: with Anywhere on, ask for+ * the relay token now instead of once a code is open, so the encrypted connection (and its key, the first time)+ * is on before the code shows. The 30 s recheck stops the token again while nothing needs the relay. */+ async prime() {+ lastState = await companionState().catch(() => null);+ onState(lastState);+ if (lastState?.enabled !== true || lastState.error || lastState.routes?.relay?.on !== true) return;+ if (tokens.running) return tokens.refreshNow();+ tokens.start();+ },/** A fresh sidecar knows nothing yet. */spawned: sync,/** The sidecar's relay refused the token (4401). */diff --git a/electron/companion-e2e.test.mjs b/electron/companion-e2e.test.mjsindex 2da94bfff4..68b768e500 100644--- a/electron/companion-e2e.test.mjs+++ b/electron/companion-e2e.test.mjs@@ -150,6 +150,46 @@ describe("the desktop's end-to-end connection", () => {e2e.stop();});+ it("asks for the relay token as soon as a person pairs with Anywhere on, before a code opens, and again on a new credential", async () => {+ let document = {};+ let relayOn = true;+ let answer = Object.assign(new Error("signed out"), { code: "signed_out" });+ const fetchGrant = vi.fn(async () => (answer instanceof Error ? Promise.reject(answer) : answer));+ const e2e = createCompanionE2E({+ readCredentials: () => document,+ updateCredentials: async (derive) => {+ document = derive(document);+ },+ fetchGrant,+ // Nothing paired and no code open: the relay is not needed yet by the usual rule.+ companionState: async () => ({ enabled: true, routes: { relay: { on: relayOn, since: 1 } }, devices: [], pairing: null }),+ post: () => {},+ setTimer: () => 1,+ clearTimer: () => {},+ });+ await e2e.start();+ expect(fetchGrant).not.toHaveBeenCalled();++ relayOn = false;+ await e2e.prime();+ expect(fetchGrant).not.toHaveBeenCalled();++ // No installation credential yet: refused, and the token service waits its half hour.+ relayOn = true;+ await e2e.prime();+ await new Promise((resolve) => setImmediate(resolve));+ expect(fetchGrant).toHaveBeenCalledTimes(1);+ expect(e2e.enabled).toBe(false);++ // The account service stored a new credential: asked again at once, and the key is made.+ answer = grant();+ await e2e.prime();+ await new Promise((resolve) => setImmediate(resolve));+ expect(fetchGrant).toHaveBeenCalledTimes(2);+ expect(e2e.enabled).toBe(true);+ e2e.stop();+ });+it("stays dark while the control plane never admits this computer", async () => {const posted = [];const e2e = createCompanionE2E({diff --git a/electron/main.mjs b/electron/main.mjsindex 711efca3ed..ae23650dfb 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -450,7 +450,7 @@ let logStream = null;let desktopShutdownStarted = false;import { companionAdvertisedHostedUrl, companionEnabledAtRest, companionOriginTarget, companionPairing, companionPairingRenew, companionDeviceRoutes, companionStartsAtLaunch, companionCloudDesktopAccess, companionRouteOn, dismissCompanionNotice, rememberCompanionRoute, setCompanionMigrationFacts,companionBrowserControlAccess, companionRevoke, companionRunning, companionSettings, companionState, rememberCompanionKeepAwake, setCompanionHostedUrl, setCompanionLifecycleListener, startCompanion, stopCompanion } from "./companion.mjs";-import { createDesktopCompanionE2E, deviceCounts } from "./companion-e2e-desktop.mjs";+import { createDesktopCompanionE2E, deviceCounts } from "./companion-e2e-desktop.mjs"; import { startCheckedManagedConnection } from "./managed-companion-start.mjs";import { autoStartCompanion } from "./companion-autostart.mjs";import { createPhoneLinkRoutes } from "./phone-link-routes.mjs";import { createRoutineWakeHold, rememberRoutineWake, routineWakeSettings } from "./routine-wake.mjs";@@ -600,7 +600,7 @@ function ensureManagedCompanionConnector() {runtimeExecutable: process.execPath,runtimeRoot: path.join(app.getPath("userData"), "managed-companion-tunnel"),onChange: (status) => {- slog(`managed companion connection ${status.status}`);+ slog(`managed companion connection ${status.status}`); companionAccountService?.connectorChanged(status);if (!companionDesiredThisLaunch) return;void reconcileCompanionAdvertisement(status.ready ? status.endpoint : null);},@@ -663,7 +663,7 @@ async function startDesktopCompanion({ waitForHosted = true, remember = true, ro}if (remember) for (const route of routes.filter((name) => ["wifi", "relay"].includes(name))) await rememberCompanionRoute(route, true);phoneLinkRoutes.touched();- await startManagedCompanionConnection({ waitForVerification: waitForHosted });+ await startCheckedManagedConnection({ check: () => (companionRouteOn("https") && managedCompanionTunnelAccess(secureCredentials) ? companionAccountService?.checkStoredAddress() : null), start: startManagedCompanionConnection, wait: waitForHosted && routes.length > 0 && !companionRouteOn("relay"), desired: () => companionDesiredThisLaunch });return desktopCompanionState();}@@ -748,7 +748,7 @@ function ensureCompanionAccountService() {onDemand: true,managedEndpointNeeded: async () =>companionRunning() ? managedEndpointNeed(await companionState().catch(() => null)) : null,- relay: { capable: () => companionE2E?.enabled === true, legacyDevices: async () => (companionRunning() ? deviceCounts(await companionState().catch(() => null)).legacy : null) },+ relay: { capable: () => companionE2E?.enabled === true, legacyDevices: async () => (companionRunning() ? deviceCounts(await companionState().catch(() => null)).legacy : null) }, installationChanged: () => void companionE2E?.prime(),log: (line) => slog(line),});return companionAccountService;@@ -2470,8 +2470,8 @@ ipcMain.handle("companion-account:verify-code", localOnly("companion-account:ver));ipcMain.handle("companion-account:retry", localOnly("companion-account:retry", () => ensureCompanionAccountService().retry()));ipcMain.handle("companion-account:prepare", localOnly("companion-account:prepare", () => {- const refusal = managedRemoteAccessRefusal();- if (refusal) throw new Error(refusal);+ const refusal = managedRemoteAccessRefusal(); if (refusal) throw new Error(refusal);+ void companionE2E?.prime(); // a person is pairing: with Anywhere on, the encrypted connection starts before a code opensreturn rememberCompanionRoute("https", true).then(() => ensureCompanionAccountService().prepare());}));ipcMain.handle("companion-account:sign-out", localOnly("companion-account:sign-out", () => ensureCompanionAccountService().signOut()));diff --git a/electron/managed-companion-start.mjs b/electron/managed-companion-start.mjsnew file mode 100644index 0000000000..20de2cb6ef--- /dev/null+++ b/electron/managed-companion-start.mjs@@ -0,0 +1,28 @@+/** How long a start waits for the stored-address check before it dials anyway; the check corrects it afterwards. */+export const STORED_ADDRESS_CHECK_WAIT_MS = 3_000;++/**+ * Starts the managed HTTPS connection when the phone link starts. A stored address may have been removed while this+ * computer was away, so `check` asks the control plane first: a gone one is provisioned again (or forgotten for the+ * relay) rather than dialled for nothing. The check holds the start for at most `checkWaitMs`. `wait` then holds the+ * caller until the address verifies; the desktop sets it only for a start that turns on routes without Anywhere (the+ * relay), since with the relay on pairing never waits on the HTTPS address, and a Wi-Fi or Tailscale start never+ * waits on it at all. The connection starts only while `desired()` still holds.+ */+export async function startCheckedManagedConnection({ check, start, wait, desired, checkWaitMs = STORED_ADDRESS_CHECK_WAIT_MS }) {+ const checked = Promise.resolve().then(check).catch(() => null);+ let timer = null;+ const capped = Promise.race([+ checked,+ new Promise((resolve) => {+ timer = setTimeout(resolve, checkWaitMs);+ timer.unref?.();+ }),+ ]).finally(() => clearTimeout(timer));+ if (wait) {+ await capped;+ if (desired()) await start({ waitForVerification: true });+ return;+ }+ void capped.then(() => (desired() ? start({ waitForVerification: false }) : null)).catch(() => {});+}diff --git a/electron/managed-companion-start.test.mjs b/electron/managed-companion-start.test.mjsnew file mode 100644index 0000000000..488af97108--- /dev/null+++ b/electron/managed-companion-start.test.mjs@@ -0,0 +1,60 @@+import { describe, expect, it, vi } from "vitest";++import { startCheckedManagedConnection } from "./managed-companion-start.mjs";++const settle = () => new Promise((resolve) => setImmediate(resolve));++describe("starting the managed connection with the phone link", () => {+ it("asks about the stored address before dialling it, and waits for it to verify only when asked to", async () => {+ const calls = [];+ const check = vi.fn(async () => { calls.push("check"); return null; });+ const start = vi.fn(async (options) => { calls.push(["start", options]); });+ await startCheckedManagedConnection({ check, start, wait: true, desired: () => true });+ expect(calls).toEqual(["check", ["start", { waitForVerification: true }]]);+ });++ it("starts behind the check without holding the caller, and not once the phone link stopped", async () => {+ let finish = () => {};+ const check = vi.fn(() => new Promise((resolve) => { finish = resolve; }));+ const start = vi.fn(async () => {});+ let desired = true;+ await startCheckedManagedConnection({ check, start, wait: false, desired: () => desired });+ expect(start).not.toHaveBeenCalled();+ finish(null);+ await settle();+ expect(start).toHaveBeenCalledWith({ waitForVerification: false });++ const stopped = vi.fn(async () => {});+ await startCheckedManagedConnection({ check: async () => null, start: stopped, wait: false, desired: () => (desired = false) });+ await settle();+ expect(stopped).not.toHaveBeenCalled();+ });++ it("dials anyway when the check is slow, and lets the check correct it afterwards", async () => {+ const check = vi.fn(() => new Promise(() => {}));+ const start = vi.fn(async () => {});+ const begun = Date.now();+ await startCheckedManagedConnection({ check, start, wait: true, desired: () => true, checkWaitMs: 50 });+ expect(start).toHaveBeenCalledWith({ waitForVerification: true });+ expect(Date.now() - begun).toBeLessThan(2_000);++ const background = vi.fn(async () => {});+ await startCheckedManagedConnection({ check, start: background, wait: false, desired: () => true, checkWaitMs: 50 });+ expect(background).not.toHaveBeenCalled();+ await vi.waitFor(() => expect(background).toHaveBeenCalledWith({ waitForVerification: false }));+ });++ it("does not dial once the phone link stopped during the check", async () => {+ const start = vi.fn(async () => {});+ await startCheckedManagedConnection({ check: async () => null, start, wait: true, desired: () => false });+ expect(start).not.toHaveBeenCalled();+ });++ it("still starts when the check fails or there is nothing to check", async () => {+ for (const check of [vi.fn(async () => Promise.reject(new Error("offline"))), vi.fn(() => { throw new Error("no account"); }), vi.fn(() => undefined)]) {+ const start = vi.fn(async () => {});+ await startCheckedManagedConnection({ check, start, wait: true, desired: () => true });+ expect(start).toHaveBeenCalledWith({ waitForVerification: true });+ }+ });+});diff --git a/src/components/PhoneSetupFlow.onDemand.test.ts b/src/components/PhoneSetupFlow.onDemand.test.tsindex 905e74dba3..5ba04cff4c 100644--- a/src/components/PhoneSetupFlow.onDemand.test.ts+++ b/src/components/PhoneSetupFlow.onDemand.test.ts@@ -21,7 +21,8 @@ const FULL =function desktop() {let companion: CompanionState = { enabled: false, keepAwake: false, port: 8810, devices: [], pairing: null };let account: CompanionAccountState = { available: true, status: "ready", email: "[email protected]" };- let finishPrepare: (outcome: "ready" | "full") => void = () => {};+ let finishPrepare: (outcome: "ready" | "full" | "relay") => void = () => {};+ let wifi = true;const withHosted = () => ({...companion,endpoints: [{ kind: "hosted" as const, url: HOSTED, priority: 0 }],@@ -30,7 +31,7 @@ function desktop() {companion: {state: vi.fn(async () => companion),start: vi.fn(async () => {- companion = { ...companion, enabled: true, endpoints: [], lan: "192.168.1.34" };+ companion = { ...companion, enabled: true, endpoints: [], lan: wifi ? "192.168.1.34" : null };return companion;}),stop: vi.fn(async () => companion),@@ -60,6 +61,9 @@ function desktop() {if (outcome === "ready") {companion = withHosted();account = { ...account, endpoint: HOSTED };+ } else if (outcome === "relay") {+ // 409 relay_capable: the stored address is forgotten and phones connect through the relay.+ account = { available: true, status: "ready", email: "[email protected]" };} else {account = { available: true, status: "error", email: "[email protected]", message: FULL };}@@ -70,7 +74,32 @@ function desktop() {};return {bridge,- finishPrepare: (outcome: "ready" | "full") => finishPrepare(outcome),+ finishPrepare: (outcome: "ready" | "full" | "relay") => finishPrepare(outcome),+ /** Signed in with an address stored from before, which the control plane has since removed. */+ /** No Wi-Fi address on this computer. */+ noWifi() {+ wifi = false;+ },+ /** The first relay token arrived: the encrypted connection is on from now. */+ keyOn() {+ companion = { ...companion, e2e: { enabled: true, relay: "connected" as const, node: null, descriptor: null } };+ },+ staleAddress() {+ account = { ...account, endpoint: HOSTED };+ },+ /** Same Wi-Fi and Anywhere on, as the start without explicit routes turns them on. */+ relayRoute(e2e = false) {+ companion = {+ ...companion,+ routes: {+ wifi: { on: true, since: Date.now() },+ relay: { on: true, since: Date.now() },+ tailscale: { on: false, since: null },+ https: { on: true, since: Date.now() },+ },+ ...(e2e ? { e2e: { enabled: true, relay: "connected" as const, node: null, descriptor: null } } : {}),+ };+ },alreadyHosted() {companion = { ...withHosted(), enabled: true };account = { ...account, endpoint: HOSTED };@@ -209,3 +238,97 @@ describe("pairing on a computer that already holds its HTTPS address", () => {expect(fake.bridge.companion.pairing).toHaveBeenCalledWith(true);});});++describe("pairing on a computer the relay carries", () => {+ const qr = () => host.querySelector('[aria-label="Device pairing QR code"]');++ it("opens the code through the relay at once while a stored address is still being checked", async () => {+ const fake = desktop();+ fake.staleAddress();+ fake.relayRoute(true);+ await startPairing(fake);+ // prepare() has not answered: the stored address is neither verified nor forgotten yet, and nothing waits on it.+ await vi.waitFor(() => expect(qr()).not.toBeNull(), { timeout: 5_000 });+ expect(fake.bridge.companionAccount.prepare).toHaveBeenCalledOnce();+ expect(fake.bridge.companion.pairing).toHaveBeenCalledWith(true);+ expect(text()).not.toContain("Creating secure remote access");++ // The control plane answers that the relay carries this computer: the open code stays.+ fake.finishPrepare("relay");+ await new Promise((resolve) => setTimeout(resolve, 1_200));+ expect(qr()).not.toBeNull();+ expect(text()).not.toContain("Secure access needs attention");+ expect(fake.bridge.companion.pairing).toHaveBeenCalledOnce();+ });++ it("waits for the HTTPS address, with no plain Wi-Fi code, while the encrypted connection is off", async () => {+ const fake = desktop();+ fake.staleAddress();+ fake.relayRoute(false);+ await startPairing(fake);+ await vi.waitFor(() => expect(fake.bridge.companionAccount.prepare).toHaveBeenCalledOnce());+ await new Promise((resolve) => setTimeout(resolve, 1_200));+ expect(fake.bridge.companion.pairing).not.toHaveBeenCalled();+ expect(text()).toContain("Creating secure remote access");++ fake.finishPrepare("ready");+ await vi.waitFor(() => expect(qr()).not.toBeNull(), { timeout: 5_000 });+ flushSync(() => button("Reveal")!.click());+ expect(text()).toContain(`Pairing address${HOSTED}`);+ });++ it("waits instead of failing when this computer has no Wi-Fi address", async () => {+ const fake = desktop();+ fake.noWifi();+ fake.staleAddress();+ fake.relayRoute(true);+ await startPairing(fake);+ await vi.waitFor(() => expect(fake.bridge.companionAccount.prepare).toHaveBeenCalledOnce());+ await new Promise((resolve) => setTimeout(resolve, 1_200));+ expect(fake.bridge.companion.pairing).not.toHaveBeenCalled();+ expect(text()).toContain("Creating secure remote access");+ expect(host.querySelector('[role="alert"]')).toBeNull();+ });++ it("opens through the relay without a second click once the address request switches the encrypted connection on", async () => {+ // A stored address that is gone and no installation credential: the request provisions again, which brings the+ // relay token and so the encrypted connection.+ const during = desktop();+ during.staleAddress();+ during.relayRoute(false);+ await startPairing(during);+ await vi.waitFor(() => expect(during.bridge.companionAccount.prepare).toHaveBeenCalledOnce());+ expect(during.bridge.companion.pairing).not.toHaveBeenCalled();+ during.keyOn();+ during.finishPrepare("relay");+ await vi.waitFor(() => expect(qr()).not.toBeNull(), { timeout: 5_000 });+ expect(during.bridge.companion.pairing).toHaveBeenCalledWith(true);+ expect(text()).not.toContain("Secure access needs attention");+ flushSync(() => root.render(null));++ // The relay token lands only after the request answered: the screen opens the code when it does.+ root = createRoot(host);+ const after = desktop();+ after.staleAddress();+ after.relayRoute(false);+ await startPairing(after);+ await vi.waitFor(() => expect(after.bridge.companionAccount.prepare).toHaveBeenCalledOnce());+ after.finishPrepare("relay");+ await new Promise((resolve) => setTimeout(resolve, 1_200));+ expect(after.bridge.companion.pairing).not.toHaveBeenCalled();+ after.keyOn();+ await vi.waitFor(() => expect(qr()).not.toBeNull(), { timeout: 5_000 });+ expect(after.bridge.companion.pairing).toHaveBeenCalledWith(true);+ expect(text()).not.toContain("Secure access needs attention");+ });++ it("still waits for an HTTPS address when Anywhere is off", async () => {+ const fake = desktop();+ await startPairing(fake);+ await vi.waitFor(() => expect(fake.bridge.companionAccount.prepare).toHaveBeenCalledOnce());+ fake.finishPrepare("relay");+ await new Promise((resolve) => setTimeout(resolve, 1_200));+ expect(fake.bridge.companion.pairing).not.toHaveBeenCalled();+ expect(text()).toContain("Creating secure remote access");+ });+});diff --git a/src/components/PhoneSetupFlow.tsx b/src/components/PhoneSetupFlow.tsxindex 1ba58cb47c..656b71357c 100644--- a/src/components/PhoneSetupFlow.tsx+++ b/src/components/PhoneSetupFlow.tsx@@ -49,6 +49,7 @@ import {preparePhonePairingRoute,queuePhonePairingAttempt,releasePhonePairingAttempt,+ pairThroughRelayWithoutAddress, relayServesPairing,secureAddressRequestLapsed,shouldArmPhoneSetupProvisioningTimeout,shouldPrepareSecureAddress,@@ -321,7 +322,7 @@ export function usePhoneSetupController(profileEmail = ""): PhoneSetupController}setError(null);try {- const started = await preparePhonePairingRoute(+ let started = await preparePhonePairingRoute(routeMode,Boolean(state?.enabled),{@@ -352,18 +353,17 @@ export function usePhoneSetupController(profileEmail = ""): PhoneSetupControllerconst prepare = remote?.prepare && shouldPrepareSecureAddress(routeMode, gate, accountOverride ?? account)? remote.prepare: null;+ let mode = routeMode;if (gate !== "open") {- setProvisioning(gate === "wait" || gate === "start");- if (prepare) {- const next = await mutateCompanionBridgeState(companionMutationEpoch, () => prepare());- if (isCurrent()) setAccount(next);- }- return;- }- if (prepare) void Promise.resolve().then(() => prepare()).catch(() => {});- if (explicitRoute && !companionPairingRoute(started, routeMode)) {+ const relayed = await pairThroughRelayWithoutAddress(gate, accountOverride ?? account, started, { prepare: prepare && (() => mutateCompanionBridgeState(companionMutationEpoch, () => prepare())), latest: () => companion.state(), isCurrent, setAccount, setProvisioning });+ if (!relayed) return;+ setState((started = relayed));+ mode = "local";+ dispatchFlow({ type: "use-local" });+ } else if (prepare) void Promise.resolve().then(() => prepare()).catch(() => {});+ if (mode !== "automatic" && !companionPairingRoute(started, mode)) {setProvisioning(false);- setError(routeMode === "tailscale"+ setError(mode === "tailscale"? t("phone.error.tailscaleUnavailable"): directPairingUnavailable());dispatchFlow({ type: "reset" });@@ -392,7 +392,7 @@ export function usePhoneSetupController(profileEmail = ""): PhoneSetupControllerpaired,started.pairing?.token ?? null,);- const routePin = pairingFailure ? null : companionPairingRoutePin(paired, routeMode);+ const routePin = pairingFailure ? null : companionPairingRoutePin(paired, mode);if (pairingFailure || !routePin || !pairingWindow) {await closePhonePairingIfOwned(paired,@@ -407,9 +407,9 @@ export function usePhoneSetupController(profileEmail = ""): PhoneSetupControllerpublishPairingRoutePin(null);setState({ ...paired, pairing: null });setProvisioning(false);- setError(pairingFailure ?? (routeMode === "local"+ setError(pairingFailure ?? (mode === "local"? directPairingUnavailable()- : routeMode === "tailscale"+ : mode === "tailscale"? t("phone.error.tailscaleUnavailable"): protectedPairingUnavailable()));dispatchFlow({ type: "reset" });@@ -703,7 +703,7 @@ export function usePhoneSetupController(profileEmail = ""): PhoneSetupControllerreturn;}if (- phonePairingGate(account, state, false) === "open"+ phonePairingGate(account, state, false) === "open" || relayServesPairing(account, state)|| (!provisioning && secureAddressRequestLapsed(account, state))) {void openPairing("automatic");diff --git a/src/lib/phone-setup.test.ts b/src/lib/phone-setup.test.tsindex 80305cf83b..56790e9a2b 100644--- a/src/lib/phone-setup.test.ts+++ b/src/lib/phone-setup.test.ts@@ -12,12 +12,14 @@ import {newlyPairedDevice,newlyPairedDeviceForFlow,normalizePhoneSetupActionError,+ pairThroughRelayWithoutAddress,phonePairingGate,phoneSetupBaseline,phoneSetupReducer,preparePhonePairingRoute,invalidatePhonePairingAttempt,queuePhonePairingAttempt,+ relayServesPairing,releasePhonePairingAttempt,secureAddressRequestLapsed,shouldArmPhoneSetupProvisioningTimeout,@@ -222,6 +224,75 @@ describe("phone setup flow", () => {expect(secureAddressRequestLapsed({ ...account("ready"), available: false }, waiting)).toBe(false);});+ it("lets the relay carry a pairing only with the encrypted connection on and a direct route to open on", () => {+ const relayOn = {+ enabled: true, port: 8810, endpoints: [], lan: "192.168.1.34",+ routes: { relay: { on: true } }, e2e: { enabled: true },+ };+ const withAddress = { ...account("ready"), endpoint: "https://c-opaque.openmausbot.com" };+ expect(relayServesPairing(account("ready"), relayOn)).toBe(true);+ // A stored address that has not answered (yet) does not hold the code.+ expect(relayServesPairing(withAddress, relayOn)).toBe(true);+ // Encrypted connection off (never admitted to the relay yet): a plain Wi-Fi code is not opened silently.+ expect(relayServesPairing(withAddress, { ...relayOn, e2e: { enabled: false } })).toBe(false);+ expect(relayServesPairing(account("ready"), { ...relayOn, e2e: undefined })).toBe(false);+ // No Wi-Fi address: nothing to open the code on, so no dead end either.+ expect(relayServesPairing(account("ready"), { ...relayOn, lan: null })).toBe(false);+ expect(relayServesPairing(account("ready"), { ...relayOn, routes: { relay: { on: false } } })).toBe(false);+ expect(relayServesPairing(account("ready"), { ...relayOn, routes: undefined })).toBe(false);+ expect(relayServesPairing(account("ready"), { ...relayOn, enabled: false })).toBe(false);+ for (const status of ["connecting", "error", "signed-out"] as const) {+ expect(relayServesPairing(account(status), relayOn)).toBe(false);+ }+ expect(relayServesPairing({ ...account("ready"), available: false }, relayOn)).toBe(false);+ expect(relayServesPairing(null, relayOn)).toBe(false);+ });++ it("opens through the relay at once, or once the address request switched it on, and otherwise keeps waiting", async () => {+ const relayOn = {+ enabled: true, port: 8810, endpoints: [], lan: "192.168.1.34",+ routes: { relay: { on: true } }, e2e: { enabled: true },+ };+ const keyless = { ...relayOn, e2e: { enabled: false } };+ const relayOff = { ...relayOn, routes: { relay: { on: false } } };+ const actions = (prepare: (() => Promise<CompanionAccountState>) | null, latest = relayOn) => ({+ prepare, latest: vi.fn(async () => latest), isCurrent: () => true, setAccount: vi.fn(), setProvisioning: vi.fn(),+ });++ // Signed in, Anywhere and the encrypted connection on: no spinner, and the address request does not hold the code.+ let finish: (next: CompanionAccountState) => void = () => {};+ const pending = actions(vi.fn(() => new Promise<CompanionAccountState>((resolve) => { finish = resolve; })));+ await expect(pairThroughRelayWithoutAddress("wait", account("ready"), relayOn, pending)).resolves.toBe(relayOn);+ expect(pending.setProvisioning).not.toHaveBeenCalled();+ finish(account("ready"));+ await vi.waitFor(() => expect(pending.setAccount).toHaveBeenCalledWith(account("ready")));++ // Anywhere off: it waits on the address request, as before.+ const off = actions(vi.fn(async () => account("ready")), relayOff);+ await expect(pairThroughRelayWithoutAddress("wait", account("ready"), relayOff, off)).resolves.toBeNull();+ expect(off.setProvisioning).toHaveBeenCalledWith(true);+ expect(off.setAccount).toHaveBeenCalledWith(account("ready"));++ // The request switched the encrypted connection on (a fresh installation credential, then a relay token): the+ // phone link read after it carries the code.+ const keyed = actions(vi.fn(async () => account("ready")), relayOn);+ await expect(pairThroughRelayWithoutAddress("wait", account("ready"), keyless, keyed)).resolves.toBe(relayOn);+ expect(keyed.setProvisioning).toHaveBeenCalledWith(true);+ expect(keyed.latest).toHaveBeenCalledOnce();++ // Still no encrypted connection after it: keeps waiting.+ const still = actions(vi.fn(async () => account("ready")), keyless);+ await expect(pairThroughRelayWithoutAddress("wait", account("ready"), keyless, still)).resolves.toBeNull();++ // Nothing to ask, or the request failed or was overtaken: it keeps waiting, and a failure reaches the caller.+ await expect(pairThroughRelayWithoutAddress("wait", account("connecting"), relayOn, actions(null))).resolves.toBeNull();+ const stale = { ...actions(vi.fn(async () => account("ready"))), isCurrent: () => false };+ await expect(pairThroughRelayWithoutAddress("wait", account("connecting"), relayOn, stale)).resolves.toBeNull();+ expect(stale.setAccount).not.toHaveBeenCalled();+ const failing = actions(vi.fn(async () => Promise.reject(new Error("no route"))));+ await expect(pairThroughRelayWithoutAddress("wait", account("connecting"), relayOn, failing)).rejects.toThrow("no route");+ });+it("opens local pairing only after the explicit Wi-Fi fallback", () => {expect(phonePairingGate(diff --git a/src/lib/phone-setup.ts b/src/lib/phone-setup.tsindex 1557729fcb..65d1fb56e3 100644--- a/src/lib/phone-setup.ts+++ b/src/lib/phone-setup.ts@@ -1,6 +1,6 @@import type { CompanionAccountState } from "../types/ogb";import { t } from "./i18n";-import type { CompanionEndpoint, CompanionPairingRouteMode } from "./companion-pairing";+import { companionPairingRoute, type CompanionEndpoint, type CompanionPairingRouteMode, type CompanionPairingRouteSource } from "./companion-pairing";export type PhoneSetupPhase = "intro" | "sign-in" | "verifying" | "qr" | "success";@@ -192,6 +192,54 @@ export function shouldPrepareSecureAddress(&& (account.status === "ready" || account.status === "connecting");}+export type RelayPairingSnapshot = PhoneSetupCompanionSnapshot & CompanionPairingRouteSource & {+ routes?: CompanionPairingRouteSource["routes"] & { relay?: { on: boolean } };+ e2e?: { enabled: boolean };+};++/** Automatic pairing goes through MausBot Relay instead of waiting on an HTTPS address only when the relay can carry+ * the phone and the code has a direct route to open on: the account is signed in, the phone link runs with Anywhere+ * on and the encrypted connection on (so the QR pins this computer's key and carries the relay), and Same Wi-Fi has+ * an address. Otherwise the pairing waits for the HTTPS address, as before: a plain Wi-Fi code is never opened+ * without the person choosing Wi-Fi. */+export function relayServesPairing(account: CompanionAccountState | null, companion: RelayPairingSnapshot | null): boolean {+ return account?.available === true+ && account.status === "ready"+ && companion?.enabled === true+ && companion.routes?.relay?.on === true+ && companion.e2e?.enabled === true+ && companionPairingRoute(companion, "local") !== null;+}++/** An automatic pairing whose gate is not open. When the relay can carry the phone, the snapshot to open the code on+ * comes back at once and any address repair (`prepare`) runs behind it. Otherwise the pairing waits on `prepare`, then+ * reads the phone link again (`latest`: the request can switch the encrypted connection on), and opens through the+ * relay if that now serves. Null: the pairing keeps waiting. A failing `prepare` rejects, as before. */+export async function pairThroughRelayWithoutAddress<State extends RelayPairingSnapshot>(+ gate: PhonePairingGate,+ account: CompanionAccountState | null,+ companion: State,+ actions: {+ prepare: (() => Promise<CompanionAccountState>) | null;+ latest: () => Promise<State>;+ isCurrent: () => boolean;+ setAccount: (next: CompanionAccountState) => void;+ setProvisioning: (on: boolean) => void;+ },+): Promise<State | null> {+ if (relayServesPairing(account, companion)) {+ if (actions.prepare) void actions.prepare().then((next) => { if (actions.isCurrent()) actions.setAccount(next); }, () => {});+ return companion;+ }+ actions.setProvisioning(gate === "wait" || gate === "start");+ if (!actions.prepare) return null;+ const next = await actions.prepare();+ if (!actions.isCurrent()) return null;+ actions.setAccount(next);+ const fresh = await actions.latest().catch(() => companion);+ return actions.isCurrent() && relayServesPairing(next, fresh) ? fresh : null;+}+export function secureAddressRequestLapsed(account: CompanionAccountState | null,companion: PhoneSetupCompanionSnapshot | null,