Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

desktop: end-to-end connection wiring, WIP

milind-soni4752a3c2eca0
diff --git a/electron/companion-account-service.mjs b/electron/companion-account-service.mjs
index 507fa09b4b..fa3f29943e 100644
--- a/electron/companion-account-service.mjs
+++ b/electron/companion-account-service.mjs
@@ -80,11 +80,17 @@ export function companionAccountCleanupPending(credentials) {
return credentials?.[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD] === true;
}
-/** true, false, or null when that cannot be told; only false ever gives an address back. */
-export function managedEndpointNeed(state) {
+/** A phone paired before the encrypted connection still needs the tunnel while it was seen this recently. */
+const LEGACY_DEVICE_WINDOW_MS = 30 * 24 * 60 * 60_000;
+
+/** true, false, or null when that cannot be told; only false ever gives an address back. Once this computer serves
+ * the encrypted connection, only an old phone seen in the last 30 days needs a tunnel: new pairings never make one. */
+export function managedEndpointNeed(state, now = Date.now()) {
if (!state || typeof state !== "object" || state.enabled !== true || state.error) return null;
if (state.devicesUnreadable === true || !Array.isArray(state.devices)) return null;
- return state.devices.length > 0 || Boolean(state.pairing);
+ if (state.e2e?.enabled !== true) return state.devices.length > 0 || Boolean(state.pairing);
+ return state.devices.some((device) =>
+ !Number.isSafeInteger(device?.e2eAt) && now - (Number(device?.lastSeenAt) || 0) < LEGACY_DEVICE_WINDOW_MS);
}
function storedAccount(credentials) {
@@ -258,6 +264,9 @@ export function createCompanionAccountService({
firstEndpointCheckMs = DEFAULT_FIRST_ENDPOINT_CHECK_MS,
onDemand = false,
managedEndpointNeeded = async () => null,
+ /** This computer reaches its phones through MausBot Relay: a "no" from managedEndpointNeeded then holds even right
+ * after sign-in. */
+ relayCapable = () => false,
releaseGraceMs = DEFAULT_RELEASE_GRACE_MS,
releaseJitterMs = DEFAULT_RELEASE_JITTER_MS,
// Only the code, HTTP status, request id and retry delay: never an email, token, credential or address.
@@ -545,6 +554,12 @@ export function createCompanionAccountService({
}
throw error;
}
+ if (onDemand && (await currentNeed()) === false) {
+ await updateCredentials((document) => withAuthenticatedAccount(document, { accountToken, user, clientInstanceId }));
+ resetAutoRetry();
+ phase = null;
+ return settledState();
+ }
const endpoint = await client.ensureEndpoint(installation.credential, {
appVersion: identity.appVersion,
});
@@ -766,13 +781,15 @@ export function createCompanionAccountService({
const savedAddress = (document) => normalizeManagedCompanionEndpoint(document[MANAGED_COMPANION_ENDPOINT_FIELD]);
const currentNeed = async () => {
- if (requestedRecently()) return true;
+ let need = null;
try {
- const need = await managedEndpointNeeded();
- return typeof need === "boolean" ? need : null;
+ const answer = await managedEndpointNeeded();
+ need = typeof answer === "boolean" ? answer : null;
} catch {
- return null;
+ need = null;
}
+ if (need === false && relayCapable()) return false;
+ return requestedRecently() ? true : need;
};
const releaseScheduledAt = () => {
diff --git a/electron/companion-account-service.test.mjs b/electron/companion-account-service.test.mjs
index 21026b8e49..ecabc0592c 100644
--- a/electron/companion-account-service.test.mjs
+++ b/electron/companion-account-service.test.mjs
@@ -1403,6 +1403,34 @@ describe("Companion account on demand", () => {
}
});
+ it("needs a tunnel only for an old phone seen this month once the encrypted connection is on", () => {
+ const now = LAUNCH_AT;
+ const on = (devices, extra = {}) => ({ enabled: true, devices, pairing: null, e2e: { enabled: true }, ...extra });
+ const pairing = { code: "123456", token: `omb_pair_${"a".repeat(43)}`, expiresAt: now };
+ expect(managedEndpointNeed(on([{ id: "old", lastSeenAt: now - HOUR_MS }]), now)).toBe(true);
+ expect(managedEndpointNeed(on([{ id: "new", lastSeenAt: now, e2eAt: now - HOUR_MS }]), now)).toBe(false);
+ expect(managedEndpointNeed(on([{ id: "stale", lastSeenAt: now - 31 * 24 * HOUR_MS }]), now)).toBe(false);
+ expect(managedEndpointNeed(on([], { pairing }), now)).toBe(false);
+ expect(managedEndpointNeed({ ...on([], { pairing }), e2e: { enabled: false } }, now)).toBe(true);
+ });
+
+ it("signs a relay-capable computer in without a tunnel when no phone needs one", async () => {
+ for (const relayCapable of [true, false]) {
+ const f = onDemandFixture({ initial: {}, relayCapable: () => relayCapable });
+ f.companion.need = false;
+ await f.service.requestCode("[email protected]");
+ const state = await f.service.verifyCode("[email protected]", "12345678");
+ expect(f.client.ensureInstallation).toHaveBeenCalledOnce();
+ if (relayCapable) {
+ expect(f.client.ensureEndpoint).not.toHaveBeenCalled();
+ expect(state).toEqual({ available: true, status: "ready", email: "[email protected]" });
+ } else {
+ expect(f.client.ensureEndpoint).toHaveBeenCalledOnce();
+ }
+ f.service.dispose();
+ }
+ });
+
it("never asks for an address at launch or on the watchdog, whatever is paired", async () => {
for (const need of [false, true, null]) {
const f = onDemandFixture({
diff --git a/electron/companion-e2e-desktop.mjs b/electron/companion-e2e-desktop.mjs
new file mode 100644
index 0000000000..b36e0b6182
--- /dev/null
+++ b/electron/companion-e2e-desktop.mjs
@@ -0,0 +1,32 @@
+import { companionState, postCompanionMessage, setCompanionE2EHooks } from "./companion.mjs";
+import { COMPANION_INSTALLATION_CREDENTIAL_FIELD, resolveCompanionControlPlaneURL } from "./companion-account-service.mjs";
+import { createCompanionE2E } from "./companion-e2e.mjs";
+import { createControlPlaneClient } from "./control-plane-client.mjs";
+
+const signedOut = () => Promise.reject(Object.assign(new Error("signed out"), { code: "signed_out" }));
+
+/** The desktop app's end-to-end connection, wired to its sidecar, its account and the power monitor. Dark in a
+ * development build unless OMB_CONTROL_PLANE_URL names a control plane. */
+export function createDesktopCompanionE2E({ isPackaged, appVersion, readCredentials, updateCredentials, powerMonitor, log }) {
+ let client = null;
+ try {
+ const baseURL = resolveCompanionControlPlaneURL({ isPackaged });
+ client = baseURL ? createControlPlaneClient({ baseURL }) : null;
+ } catch {
+ client = null;
+ }
+ const e2e = createCompanionE2E({
+ readCredentials,
+ updateCredentials,
+ fetchGrant: (devices) => {
+ const credential = readCredentials()?.[COMPANION_INSTALLATION_CREDENTIAL_FIELD];
+ return client && credential ? client.relayToken(credential, { appVersion, devices }) : signedOut();
+ },
+ companionState,
+ post: postCompanionMessage,
+ log,
+ });
+ setCompanionE2EHooks({ initialMessage: () => e2e.message(), tokenRejected: e2e.tokenRejected, changed: () => void e2e.reconcile() });
+ powerMonitor?.on("resume", () => e2e.resumed());
+ return e2e;
+}
diff --git a/electron/companion-e2e.mjs b/electron/companion-e2e.mjs
new file mode 100644
index 0000000000..4435c9362d
--- /dev/null
+++ b/electron/companion-e2e.mjs
@@ -0,0 +1,105 @@
+import { companionE2EMessage, createE2EIdentity, readE2EIdentity, withE2EIdentity } from "./e2e-identity.mjs";
+import { createRelayTokenService } from "./relay-token.mjs";
+
+const RECHECK_MS = 30_000;
+/** A legacy phone (paired before the encrypted connection) still needs the tunnel while it was seen this recently. */
+export const LEGACY_DEVICE_WINDOW_MS = 30 * 24 * 60 * 60 * 1_000;
+
+/** What the control plane counts for its adoption gates: no identifiers. */
+export function deviceCounts(state) {
+ const devices = Array.isArray(state?.devices) ? state.devices : [];
+ const e2e = devices.filter((device) => Number.isSafeInteger(device?.e2eAt)).length;
+ return { e2e: Math.min(e2e, 100), legacy: Math.min(devices.length - e2e, 100) };
+}
+
+/** The relay is needed while the companion runs and a phone could use it: one not restricted to Wi-Fi and Tailscale,
+ * or a pairing window. Null when that can't be told. */
+export function relayNeed(state) {
+ if (!state || typeof state !== "object") return null;
+ if (state.enabled !== true) return false;
+ if (state.error) return null;
+ if (state.devicesUnreadable === true || !Array.isArray(state.devices)) return null;
+ return Boolean(state.pairing) || state.devices.some((device) => device?.routes !== "local");
+}
+
+/** The end-to-end connection for the desktop app: the transport key, the relay token, and what the sidecar is told.
+ * The key is made the first time the control plane admits this computer to the relay, and from then on the encrypted
+ * connection stays on, signed in or not, so phones that pinned it never lose Wi-Fi and Tailscale. */
+export function createCompanionE2E({
+ readCredentials,
+ updateCredentials,
+ fetchGrant,
+ companionState,
+ post,
+ setTimer = setInterval,
+ clearTimer = clearInterval,
+ log = () => {},
+}) {
+ let identity = readE2EIdentity(readCredentials());
+ let lastState = null;
+ let interval = null;
+
+ const sync = () => {
+ if (!identity && !tokens.grant) return;
+ post(companionE2EMessage(identity, tokens.grant));
+ };
+
+ async function ensureIdentity() {
+ if (identity) return identity;
+ const existing = readE2EIdentity(readCredentials());
+ if (existing) return (identity = existing);
+ const created = createE2EIdentity();
+ await updateCredentials((credentials) => withE2EIdentity(credentials, created));
+ identity = created;
+ log("e2e: connection key created");
+ return identity;
+ }
+
+ const tokens = createRelayTokenService({
+ fetchGrant: () => fetchGrant(deviceCounts(lastState)),
+ onGrant: (grant) => {
+ if (!grant) return sync();
+ void ensureIdentity().then(sync, (error) => log(`e2e: connection key unavailable: ${error?.message ?? error}`));
+ },
+ log,
+ });
+
+ async function reconcile() {
+ lastState = await companionState().catch(() => null);
+ const need = relayNeed(lastState);
+ if (need === true) tokens.start();
+ else if (need === false) tokens.stop();
+ }
+
+ return {
+ get enabled() {
+ return identity !== null;
+ },
+ get publicKey() {
+ return identity?.publicKey ?? null;
+ },
+ /** For a new sidecar: null while the encrypted connection is off. */
+ message: () => (identity ? companionE2EMessage(identity, tokens.grant) : null),
+ start() {
+ interval ??= setTimer(() => void reconcile(), RECHECK_MS);
+ interval.unref?.();
+ return reconcile();
+ },
+ stop() {
+ if (interval) clearTimer(interval);
+ interval = null;
+ tokens.stop();
+ },
+ /** A pairing window opened or a device changed: the relay may be needed now. */
+ reconcile,
+ /** A fresh sidecar knows nothing yet. */
+ spawned: sync,
+ /** The sidecar's relay refused the token (4401). */
+ tokenRejected: () => void tokens.refreshNow(),
+ /** The computer woke: the sidecar redials now, and the token may have lapsed while asleep. */
+ resumed() {
+ post({ type: "openmausbot:companion-e2e-redial" });
+ void tokens.refreshNow();
+ },
+ };
+}
diff --git a/electron/companion-e2e.test.mjs b/electron/companion-e2e.test.mjs
new file mode 100644
index 0000000000..ac652198ad
--- /dev/null
+++ b/electron/companion-e2e.test.mjs
@@ -0,0 +1,168 @@
+import { createECDH } from "node:crypto";
+import { describe, expect, it, vi } from "vitest";
+
+import { createCompanionE2E, deviceCounts, relayNeed } from "./companion-e2e.mjs";
+import {
+ E2E_TRANSPORT_KEY_FIELD,
+ companionE2EMessage,
+ createE2EIdentity,
+ readE2EIdentity,
+ withE2EIdentity,
+} from "./e2e-identity.mjs";
+import { createRelayTokenService, validRelayGrant } from "./relay-token.mjs";
+
+const HOST_ID = "lz81isB3BuNV6rHgYgG3Wg";
+const grant = (overrides = {}) => ({
+ token: "eyJ2IjoxfQ.c2lnbmF0dXJl",
+ hostId: HOST_ID,
+ nodes: ["relay1.openmausbot.com", "relay2.openmausbot.com"],
+ expiresAt: 10 * 60 * 60_000,
+ refreshAfter: 60 * 60_000,
+ ...overrides,
+});
+
+describe("the connection key", () => {
+ it("is a P-256 key whose public half is rebuilt from the private one before it is trusted", () => {
+ const identity = createE2EIdentity();
+ const curve = createECDH("prime256v1");
+ curve.setPrivateKey(Buffer.from(identity.privateKey, "base64url"));
+ expect(curve.getPublicKey(undefined, "base64url")).toBeDefined();
+ expect(Buffer.from(identity.publicKey, "base64url")).toEqual(curve.getPublicKey(undefined, "uncompressed"));
+ const document = withE2EIdentity({ other: 1 }, identity);
+ expect(readE2EIdentity(document)).toEqual(identity);
+ expect(document.other).toBe(1);
+ const other = createE2EIdentity();
+ expect(readE2EIdentity({ [E2E_TRANSPORT_KEY_FIELD]: { ...identity, publicKey: other.publicKey } })).toBeNull();
+ expect(readE2EIdentity({ [E2E_TRANSPORT_KEY_FIELD]: { ...identity, version: 2 } })).toBeNull();
+ expect(readE2EIdentity({ [E2E_TRANSPORT_KEY_FIELD]: { ...identity, privateKey: `${identity.privateKey}=` } })).toBeNull();
+ });
+
+ it("goes to the sidecar with the relay identity only once the computer holds a token", () => {
+ const identity = createE2EIdentity();
+ expect(companionE2EMessage(identity, null)).toEqual({ type: "openmausbot:companion-e2e", transportKey: identity.privateKey, relay: null });
+ expect(companionE2EMessage(identity, grant()).relay).toEqual({ hostId: HOST_ID, nodes: grant().nodes, relayToken: grant().token });
+ expect(companionE2EMessage(null, grant())).toEqual({ type: "openmausbot:companion-e2e", transportKey: null, relay: null });
+ });
+});
+
+function manualTimers() {
+ const pending = new Map();
+ let next = 1;
+ return {
+ pending,
+ setTimer: (callback, milliseconds) => {
+ const id = next++;
+ pending.set(id, { callback, milliseconds });
+ return id;
+ },
+ clearTimer: (id) => pending.delete(id),
+ async fireAll() {
+ const due = [...pending.entries()];
+ pending.clear();
+ for (const [, timer] of due) timer.callback();
+ await new Promise((resolve) => setImmediate(resolve));
+ },
+ };
+}
+
+describe("relay tokens", () => {
+ it("refuses a grant with any field off", () => {
+ expect(validRelayGrant(grant())).toEqual(grant());
+ for (const bad of [{ token: "no-dot" }, { hostId: "short" }, { nodes: ["relay.example.com"] }, { nodes: [] }, { refreshAfter: 11 * 60 * 60_000 }]) {
+ expect(validRelayGrant(grant(bad))).toBeNull();
+ }
+ });
+
+ it("fetch at once, refresh after refreshAfter, and keep a valid token through a failed refresh", async () => {
+ const timers = manualTimers();
+ const grants = [];
+ const answers = [grant(), Promise.reject(Object.assign(new Error("down"), { code: "network_unavailable" })), grant({ token: "eyJ2IjoyfQ.c2ln" })];
+ const fetchGrant = vi.fn(() => answers.shift());
+ const service = createRelayTokenService({ fetchGrant, onGrant: (next) => grants.push(next), ...timers, now: () => 0, random: () => 0.5 });
+ service.start();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(grants).toEqual([grant()]);
+ expect([...timers.pending.values()][0].milliseconds).toBe(60 * 60_000);
+ await timers.fireAll();
+ expect(grants).toHaveLength(1);
+ expect([...timers.pending.values()][0].milliseconds).toBe(60_000);
+ await timers.fireAll();
+ expect(grants.at(-1).token).toBe("eyJ2IjoyfQ.c2ln");
+ service.stop();
+ expect(grants.at(-1)).toBeNull();
+ });
+
+ it("drop the token and wait half an hour when the relay is off for this computer", async () => {
+ const timers = manualTimers();
+ const grants = [];
+ const answers = [grant(), Promise.reject(Object.assign(new Error("off"), { code: "relay_unavailable", status: 503 }))];
+ const service = createRelayTokenService({ fetchGrant: () => answers.shift(), onGrant: (next) => grants.push(next), ...timers, now: () => 0, random: () => 0.5 });
+ service.start();
+ await new Promise((resolve) => setImmediate(resolve));
+ await service.refreshNow();
+ expect(grants).toEqual([grant(), null]);
+ expect([...timers.pending.values()][0].milliseconds).toBe(30 * 60_000);
+ service.stop();
+ });
+});
+
+describe("the desktop's end-to-end connection", () => {
+ it("counts devices for the adoption gates and knows when the relay is needed", () => {
+ const state = { enabled: true, pairing: null, devices: [{ e2eAt: 1, routes: "local" }, { routes: "any" }] };
+ expect(deviceCounts(state)).toEqual({ e2e: 1, legacy: 1 });
+ expect(relayNeed(state)).toBe(true);
+ expect(relayNeed({ ...state, devices: [{ routes: "local" }] })).toBe(false);
+ expect(relayNeed({ ...state, devices: [], pairing: { token: "t" } })).toBe(true);
+ expect(relayNeed({ enabled: false })).toBe(false);
+ expect(relayNeed({ enabled: true, error: "x" })).toBeNull();
+ });
+
+ it("makes the key on the first relay token, tells the sidecar, and keeps it on after the token goes", async () => {
+ let document = {};
+ const posted = [];
+ let answer = grant();
+ const e2e = createCompanionE2E({
+ readCredentials: () => document,
+ updateCredentials: async (derive) => {
+ document = derive(document);
+ },
+ fetchGrant: async () => (answer instanceof Error ? Promise.reject(answer) : answer),
+ companionState: async () => ({ enabled: true, devices: [], pairing: { token: "t" } }),
+ post: (message) => posted.push(message),
+ setTimer: () => 1,
+ clearTimer: () => {},
+ });
+ expect(e2e.enabled).toBe(false);
+ expect(e2e.message()).toBeNull();
+ await e2e.start();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(e2e.enabled).toBe(true);
+ expect(readE2EIdentity(document)?.publicKey).toBe(e2e.publicKey);
+ expect(posted.at(-1)).toMatchObject({ type: "openmausbot:companion-e2e", relay: { hostId: HOST_ID } });
+ answer = Object.assign(new Error("off"), { code: "relay_unavailable" });
+ e2e.tokenRejected();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(posted.at(-1)).toEqual({ type: "openmausbot:companion-e2e", transportKey: readE2EIdentity(document).privateKey, relay: null });
+ e2e.resumed();
+ expect(posted.at(-1)).toEqual({ type: "openmausbot:companion-e2e-redial" });
+ e2e.stop();
+ });
+
+ it("stays dark while the control plane never admits this computer", async () => {
+ const posted = [];
+ const e2e = createCompanionE2E({
+ readCredentials: () => ({}),
+ updateCredentials: async () => {},
+ fetchGrant: async () => Promise.reject(Object.assign(new Error("off"), { code: "relay_unavailable" })),
+ companionState: async () => ({ enabled: true, devices: [], pairing: { token: "t" } }),
+ post: (message) => posted.push(message),
+ setTimer: () => 1,
+ clearTimer: () => {},
+ });
+ await e2e.start();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(e2e.enabled).toBe(false);
+ expect(posted).toEqual([]);
+ e2e.stop();
+ });
+});
diff --git a/electron/companion.mjs b/electron/companion.mjs
index 1236d8f97e..dcc7caffd4 100644
--- a/electron/companion.mjs
+++ b/electron/companion.mjs
@@ -124,6 +124,25 @@ const serialize = (work) => {
};
/** Resolves with the panel's state; a failed start is a message, never a thrown error. */
+let e2eHooks = { initialMessage: () => null, tokenRejected: () => {}, changed: () => {} };
+
+/** The end-to-end connection's part: its configuration goes to every new sidecar over the port, a refused relay token
+ * comes back the same way, and pairing changes may need the relay. */
+export function setCompanionE2EHooks(hooks) {
+ e2eHooks = { ...e2eHooks, ...hooks };
+}
+
+/** In-memory port only. False when no sidecar runs. */
+export function postCompanionMessage(message) {
+ if (!proc) return false;
+ try {
+ proc.postMessage(message);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
export function startCompanion(options) {
return serialize(() => start(options));
}
@@ -191,11 +210,16 @@ async function start({ resourcesPath, harnessPort, mutationToken, hostedUrl = nu
// Never expose this capability in argv, environment, logs or the renderer.
try {
child.postMessage({ type: "openmausbot:companion-mutation-token", token: mutationToken, controlToken });
+ const e2e = e2eHooks.initialMessage();
+ if (e2e) child.postMessage(e2e);
} catch {
log?.("companion authorization could not be initialized");
child.kill();
}
});
+ child.on("message", (message) => {
+ if (message?.type === "openmausbot:companion-e2e-token-rejected") e2eHooks.tokenRejected();
+ });
child.stdout?.on("data", (d) => log?.(`[companion] ${String(d).trimEnd()}`));
child.stderr?.on("data", (d) => log?.(`[companion err] ${String(d).trimEnd()}`));
@@ -352,6 +376,7 @@ export async function companionPairing(open, expectedToken) {
: "/pairing";
try {
const state = await control(open ? "POST" : "DELETE", path);
+ e2eHooks.changed();
return {
enabled: true,
keepAwake: companionKeepAwakeAtRest(),
@@ -371,6 +396,26 @@ export async function companionRevoke(deviceId) {
// the id came from the renderer, so it does not get to shape a path
if (!/^[\w-]{1,64}$/.test(String(deviceId ?? ""))) return companionState();
await control("DELETE", `/devices/${deviceId}`).catch(() => {});
+ e2eHooks.changed();
+ return companionState();
+}
+
+/** A fresh code while the pairing screen stays open; the previous one keeps its last seconds. */
+export async function companionPairingRenew() {
+ if (!proc) return companionState();
+ try {
+ return { enabled: true, keepAwake: companionKeepAwakeAtRest(), ...(await control("POST", "/pairing/renew")) };
+ } catch {
+ return companionPairing(true);
+ }
+}
+
+/** "any" or "local" (Wi-Fi and Tailscale only). */
+export async function companionDeviceRoutes(deviceId, routes) {
+ if (!proc) return companionState();
+ if (!/^[\w-]{1,64}$/.test(String(deviceId ?? "")) || (routes !== "any" && routes !== "local")) return companionState();
+ await control("PUT", `/devices/${deviceId}/routes`, { routes }).catch(() => {});
+ e2eHooks.changed();
return companionState();
}
diff --git a/electron/control-plane-client.mjs b/electron/control-plane-client.mjs
index 88b9974a5a..b5d9ae21d3 100644
--- a/electron/control-plane-client.mjs
+++ b/electron/control-plane-client.mjs
@@ -381,7 +381,9 @@ export function createControlPlaneClient({
};
},
- async ensureEndpoint(installationCredential, { appVersion } = {}) {
+ /** `legacyDevices`: paired phones that can't use the encrypted connection; a relay-capable desktop with none gets
+ * `409 relay_capable` instead of a new tunnel. */
+ async ensureEndpoint(installationCredential, { appVersion, legacyDevices } = {}) {
if (
typeof installationCredential !== "string" ||
!INSTALLATION_CREDENTIAL.test(installationCredential)
@@ -389,10 +391,12 @@ export function createControlPlaneClient({
throw new ControlPlaneError("signed_out", 401);
}
const version = reportableAppVersion(appVersion);
+ const legacy = Number.isSafeInteger(legacyDevices) && legacyDevices >= 0 && legacyDevices <= 100 ? legacyDevices : null;
+ const body = { ...(version === null ? {} : { appVersion: version }), ...(legacy === null ? {} : { legacyDevices: legacy }) };
const { payload } = await request("/v1/installations/self/endpoint", {
method: "POST",
token: installationCredential,
- ...(version === null ? {} : { body: { appVersion: version } }),
+ ...(Object.keys(body).length ? { body } : {}),
});
const endpoint = validatedEndpoint(payload.endpoint);
const connectorToken = boundedSecret(payload.connectorToken, 16_384);
@@ -400,6 +404,22 @@ export function createControlPlaneClient({
return { endpoint, connectorToken };
},
+ /** MausBot Relay: `{token, hostId, nodes, expiresAt, refreshAfter}`, or `relay_unavailable` (503) while this
+ * computer is outside the rollout. */
+ async relayToken(installationCredential, { appVersion, devices }) {
+ if (typeof installationCredential !== "string" || !INSTALLATION_CREDENTIAL.test(installationCredential)) {
+ throw new ControlPlaneError("signed_out", 401);
+ }
+ const version = reportableAppVersion(appVersion);
+ if (version === null) throw new ControlPlaneError("invalid_request");
+ const { payload } = await request("/v1/installations/self/relay-token", {
+ method: "POST",
+ token: installationCredential,
+ body: { appVersion: version, devices: { e2e: devices.e2e, legacy: devices.legacy } },
+ });
+ return payload;
+ },
+
/** Never returns or requests a connector token. */
async getEndpoint(installationCredential) {
if (
diff --git a/electron/e2e-identity.mjs b/electron/e2e-identity.mjs
new file mode 100644
index 0000000000..2216d42c36
--- /dev/null
+++ b/electron/e2e-identity.mjs
@@ -0,0 +1,67 @@
+import { createECDH } from "node:crypto";
+
+/** The computer's transport key for the end-to-end phone connection, kept in the secure credential document. Separate
+ * from the phone-secret HPKE key: one key, one job. Its presence is what turns the encrypted connection on, and it
+ * never goes away by itself, so phones that pinned it keep reaching this computer on Wi-Fi even signed out. */
+export const E2E_TRANSPORT_KEY_FIELD = "e2eTransportKey";
+export const E2E_IDENTITY_VERSION = 1;
+
+const BASE64URL = /^[A-Za-z0-9_-]+$/;
+
+const encode = (bytes) => Buffer.from(bytes).toString("base64url");
+
+function decode(value, bytes) {
+ if (typeof value !== "string" || !BASE64URL.test(value)) return null;
+ const decoded = Buffer.from(value, "base64url");
+ return decoded.length === bytes && encode(decoded) === value ? decoded : null;
+}
+
+/** The public point is rebuilt from the scalar before the record is trusted, so a torn write never advertises a key
+ * this computer can't use. */
+export function readE2EIdentity(credentials) {
+ const candidate = credentials?.[E2E_TRANSPORT_KEY_FIELD];
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return null;
+ if (candidate.version !== E2E_IDENTITY_VERSION) return null;
+ const scalar = decode(candidate.privateKey, 32);
+ if (!scalar) return null;
+ let publicKey;
+ try {
+ const curve = createECDH("prime256v1");
+ curve.setPrivateKey(scalar);
+ publicKey = encode(curve.getPublicKey(undefined, "uncompressed"));
+ } catch {
+ return null;
+ }
+ if (candidate.publicKey !== publicKey) return null;
+ return { version: E2E_IDENTITY_VERSION, privateKey: candidate.privateKey, publicKey };
+}
+
+export function createE2EIdentity() {
+ const curve = createECDH("prime256v1");
+ curve.generateKeys();
+ const raw = curve.getPrivateKey();
+ const identity = {
+ version: E2E_IDENTITY_VERSION,
+ privateKey: encode(Buffer.concat([Buffer.alloc(32 - raw.length), raw])),
+ publicKey: encode(curve.getPublicKey(undefined, "uncompressed")),
+ };
+ if (!readE2EIdentity({ [E2E_TRANSPORT_KEY_FIELD]: identity })) throw new Error("The connection key could not be verified");
+ return identity;
+}
+
+export function withE2EIdentity(credentials, identity) {
+ const verified = readE2EIdentity({ [E2E_TRANSPORT_KEY_FIELD]: identity });
+ if (!verified) throw new Error("The connection key is invalid");
+ return { ...credentials, [E2E_TRANSPORT_KEY_FIELD]: verified };
+}
+
+/** The private half travels only over Electron's in-memory utility-process port: never argv, env, logs, renderer IPC,
+ * companion state or a QR. `relay` is null until this computer holds a relay token. */
+export function companionE2EMessage(identity, relay) {
+ const verified = identity ? readE2EIdentity({ [E2E_TRANSPORT_KEY_FIELD]: identity }) : null;
+ return {
+ type: "openmausbot:companion-e2e",
+ transportKey: verified?.privateKey ?? null,
+ relay: verified && relay ? { hostId: relay.hostId, nodes: [...relay.nodes], relayToken: relay.token } : null,
+ };
+}
diff --git a/electron/main.mjs b/electron/main.mjs
index cc5d1b815b..2cd3f8fe2f 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -356,6 +356,7 @@ async function stopUtilityServer(proc, timeoutMs = UTILITY_SERVER_STOP_TIMEOUT_M
]).finally(() => clearTimeout(timer));
}
let phoneSecretIdentity = null;
+let companionE2E = null;
let desktopRemoteAccess = null;
let desktopCompanionRelay = null;
@@ -458,24 +459,9 @@ const DESKTOP_CRASH_LOG = path.join(LOG_DIR, "desktop-crashes.log");
const DESKTOP_CRASH_LOG_MAX_BYTES = 512 * 1024;
let logStream = null;
let desktopShutdownStarted = false;
-import {
- companionAdvertisedHostedUrl,
- companionEnabledAtRest,
- companionOriginTarget,
- companionPairing,
- companionRefreshTailscale,
- companionCloudDesktopAccess,
- companionBrowserControlAccess,
- companionRevoke,
- companionRunning,
- companionState,
- rememberCompanionEnabled,
- rememberCompanionKeepAwake,
- setCompanionHostedUrl,
- setCompanionLifecycleListener,
- startCompanion,
- stopCompanion,
-} from "./companion.mjs";
+import { companionAdvertisedHostedUrl, companionEnabledAtRest, companionOriginTarget, companionPairing, companionPairingRenew, companionDeviceRoutes, companionRefreshTailscale, companionCloudDesktopAccess,
+ companionBrowserControlAccess, companionRevoke, companionRunning, companionState, rememberCompanionEnabled, rememberCompanionKeepAwake, setCompanionHostedUrl, setCompanionLifecycleListener, startCompanion, stopCompanion } from "./companion.mjs";
+import { createDesktopCompanionE2E } from "./companion-e2e-desktop.mjs";
import { autoStartCompanion } from "./companion-autostart.mjs";
import { createRoutineWakeHold, rememberRoutineWake, routineWakeSettings } from "./routine-wake.mjs";
import { CREDENTIAL_PATCH, credentialSaveError } from "./credential-patch.mjs";
@@ -775,6 +761,7 @@ function ensureCompanionAccountService() {
onDemand: true,
managedEndpointNeeded: async () =>
companionRunning() ? managedEndpointNeed(await companionState().catch(() => null)) : null,
+ relayCapable: () => companionE2E?.enabled === true,
log: (line) => slog(line),
});
return companionAccountService;
@@ -2462,6 +2449,10 @@ ipcMain.handle("companion:browser-control", localOnly("companion:browser-control
ipcMain.handle("companion:revoke", localOnly("companion:revoke", (_event, deviceId) =>
companionRevoke(deviceId).then(() => desktopCompanionState()),
));
+ipcMain.handle("companion:pairing-renew", localOnly("companion:pairing-renew", () => companionPairingRenew().then(decorateDesktopCompanionState)));
+ipcMain.handle("companion:routes", localOnly("companion:routes", (_event, deviceId, routes) =>
+ companionDeviceRoutes(deviceId, routes === "local" ? "local" : "any").then(() => desktopCompanionState()),
+));
function publicDesktopRemoteState() {
return desktopRemoteAccess
@@ -2969,6 +2960,8 @@ app.whenReady().then(async () => {
});
secureCredentials = secureCredentialState.read();
if (app.isPackaged) await ensurePhoneSecretIdentity();
+ companionE2E = createDesktopCompanionE2E({ isPackaged: app.isPackaged, appVersion: app.getVersion(), readCredentials: () => secureCredentialState?.read() ?? secureCredentials, updateCredentials: updateSecureCredentialDocument, powerMonitor, log: slog });
+ void companionE2E.start();
desktopRemoteAccess = desktopCompanionAccess(secureCredentials);
const hostedAccount = desktopRemoteAccess ? null : ensureCompanionAccountService();
// Display capture needs a one-shot renderer intent from the same frame/origin, no audio, and a user gesture.
diff --git a/electron/preload.cjs b/electron/preload.cjs
index c048e39744..1aeeed1692 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -251,6 +251,8 @@ const bridge = {
cloudDesktop: (deviceId, allowed) => ipcRenderer.invoke("companion:cloud-desktop", deviceId, allowed),
browserControl: (deviceId, allowed) => ipcRenderer.invoke("companion:browser-control", deviceId, allowed),
revoke: (deviceId) => ipcRenderer.invoke("companion:revoke", deviceId),
+ renewPairing: () => ipcRenderer.invoke("companion:pairing-renew"),
+ routes: (deviceId, routes) => ipcRenderer.invoke("companion:routes", deviceId, routes),
},
routines: {
wakeState: () => ipcRenderer.invoke("routines:wake-state"),
diff --git a/electron/relay-token.mjs b/electron/relay-token.mjs
new file mode 100644
index 0000000000..89cb2d06f9
--- /dev/null
+++ b/electron/relay-token.mjs
@@ -0,0 +1,112 @@
+/** Keeps this computer's MausBot Relay token fresh while the relay is needed: fetched at once, again after the control
+ * plane's `refreshAfter` (an hour), and sooner when the relay refuses it. A token that is still valid survives a
+ * failed refresh; the relay keeps spliced sessions through an expired control socket anyway. */
+const MINUTE_MS = 60_000;
+const UNAVAILABLE_RETRY_MS = 30 * MINUTE_MS;
+const BACKOFF_MS = [MINUTE_MS, 2 * MINUTE_MS, 4 * MINUTE_MS, 8 * MINUTE_MS, 16 * MINUTE_MS, 32 * MINUTE_MS, 60 * MINUTE_MS];
+const MIN_REFRESH_MS = MINUTE_MS;
+const RELAY_HOST = /^relay[1-9][0-9]?\.openmausbot\.com$/;
+const HOST_ID = /^[A-Za-z0-9_-]{22}$/;
+const TOKEN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
+
+const defaultSetTimer = (callback, milliseconds) => {
+ const timer = setTimeout(callback, milliseconds);
+ timer.unref?.();
+ return timer;
+};
+
+/** The control plane's 200 body, or null when any field is off. */
+export function validRelayGrant(payload) {
+ if (!payload || typeof payload !== "object") return null;
+ const { token, hostId, nodes, expiresAt, refreshAfter } = payload;
+ if (typeof token !== "string" || token.length > 2_048 || !TOKEN.test(token)) return null;
+ if (typeof hostId !== "string" || !HOST_ID.test(hostId)) return null;
+ if (!Array.isArray(nodes) || nodes.length < 1 || nodes.length > 4 || !nodes.every((node) => typeof node === "string" && RELAY_HOST.test(node))) return null;
+ if (!Number.isSafeInteger(expiresAt) || !Number.isSafeInteger(refreshAfter) || refreshAfter > expiresAt) return null;
+ return { token, hostId, nodes: [...nodes], expiresAt, refreshAfter };
+}
+
+export function createRelayTokenService({
+ fetchGrant,
+ onGrant,
+ setTimer = defaultSetTimer,
+ clearTimer = clearTimeout,
+ now = Date.now,
+ random = Math.random,
+ log = () => {},
+}) {
+ let running = false;
+ let grant = null;
+ let timer = null;
+ let failures = 0;
+ let inFlight = null;
+
+ const jitter = (milliseconds) => Math.round(milliseconds * (0.8 + 0.4 * random()));
+ const schedule = (milliseconds) => {
+ if (timer) clearTimer(timer);
+ timer = running ? setTimer(() => void refresh(), Math.max(0, milliseconds)) : null;
+ };
+ const publish = (next) => {
+ if (next === grant) return;
+ grant = next;
+ onGrant(grant);
+ };
+
+ async function attempt() {
+ try {
+ const next = validRelayGrant(await fetchGrant());
+ if (!next) throw Object.assign(new Error("invalid relay grant"), { code: "invalid_response" });
+ failures = 0;
+ if (!running) return;
+ publish(next);
+ schedule(Math.max(MIN_REFRESH_MS, next.refreshAfter - now()));
+ } catch (error) {
+ if (!running) return;
+ const code = error?.code ?? "";
+ if (code === "relay_unavailable" || code === "signed_out" || error?.status === 401) {
+ log(`relay token ${code || "refused"}`);
+ publish(null);
+ return schedule(jitter(UNAVAILABLE_RETRY_MS));
+ }
+ if (grant && grant.expiresAt <= now()) publish(null);
+ const retryAfter = Number.isSafeInteger(error?.retryAfterMs) ? error.retryAfterMs : 0;
+ schedule(Math.max(retryAfter, jitter(BACKOFF_MS[Math.min(failures, BACKOFF_MS.length - 1)])));
+ failures += 1;
+ log(`relay token failed: ${code || "unknown"}`);
+ }
+ }
+
+ function refresh() {
+ inFlight ??= attempt().finally(() => {
+ inFlight = null;
+ });
+ return inFlight;
+ }
+
+ return {
+ get grant() {
+ return grant;
+ },
+ get running() {
+ return running;
+ },
+ start() {
+ if (running) return;
+ running = true;
+ void refresh();
+ },
+ stop() {
+ running = false;
+ if (timer) clearTimer(timer);
+ timer = null;
+ publish(null);
+ },
+ /** The relay said 4401, or the computer woke up. */
+ refreshNow() {
+ if (!running) return Promise.resolve();
+ if (timer) clearTimer(timer);
+ timer = null;
+ return refresh();
+ },
+ };
+}