Skip to content

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

Companion: a phone's provider key crosses the LAN only inside an encrypted session

milind-sonifc4f079e4deb
diff --git a/companion/src/proxy.ts b/companion/src/proxy.ts
index dab366d2fa..3e7418b96f 100644
--- a/companion/src/proxy.ts
+++ b/companion/src/proxy.ts
@@ -72,6 +72,9 @@ const UPDATE_APP = { error: "update_app" } as const;
const PAIRING_SESSION_PATHS = new Set(["POST /api/pair", "GET /api/health"]);
+/** Requests whose body carries a provider key. */
+const KEY_CARRYING = new Set(["PUT /api/config", "POST /api/keys/test"]);
+
const RELEASE_VERSION = /^[0-9]{1,9}\.[0-9]{1,9}\.[0-9]{1,9}(-[0-9A-Za-z.-]{1,64})?(\+[0-9A-Za-z.-]{1,64})?$/;
/** A token presented inside a session must belong to the device whose psk opened it. */
@@ -436,6 +439,11 @@ export function createProxyHandler(options: ProxyOptions) {
});
if (denial) return sendJson(res, denial.status, { error: denial.error });
+ // A provider key never crosses the LAN in the clear: on the plain listener it must arrive inside an encrypted session.
+ if (!e2e && listener === "lan" && KEY_CARRYING.has(`${method} ${path}`)) {
+ return sendJson(res, 403, { error: "API keys can only be sent over an encrypted connection. Update the app and try again." });
+ }
+
// Pairing grants the ordinary companion surface, not a computer's browser
// session; the owner enables this per device, off by default.
if (isCloudDesktopAccess(method, path) && !device?.cloudDesktopAccess) {
diff --git a/companion/test/provider-key-save.test.ts b/companion/test/provider-key-save.test.ts
index f4b4346688..4a8d7436dd 100644
--- a/companion/test/provider-key-save.test.ts
+++ b/companion/test/provider-key-save.test.ts
@@ -1,9 +1,11 @@
// Inside the desktop app a phone's key goes to the desktop's own save (encrypted store first), never straight to the
-// harness; the standalone companion has no such save and forwards it.
-import { createServer, type Server } from "node:http";
+// harness; the standalone companion has no such save and forwards it. On the plain LAN listener a key must arrive
+// inside an encrypted session.
+import { createServer, request, type Server } from "node:http";
import { afterEach, describe, expect, it } from "vitest";
-import { createProxyHandler, type ProxyOptions } from "../src/proxy.ts";
+import { createE2EOrigin } from "../src/e2e/origin.ts";
+import { createProxyHandler, type ProxyListener, type ProxyOptions } from "../src/proxy.ts";
const TOKEN = "omb_test_token";
const servers: Server[] = [];
@@ -18,7 +20,7 @@ afterEach(async () => {
await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))));
});
-async function companion(saveProviderKey?: ProxyOptions["saveProviderKey"]) {
+async function companion(saveProviderKey?: ProxyOptions["saveProviderKey"], listener: ProxyListener = "origin") {
const harness: Array<{ method: string; url: string; body: string }> = [];
const harnessPort = await listen(createServer((req, res) => {
let body = "";
@@ -28,20 +30,43 @@ async function companion(saveProviderKey?: ProxyOptions["saveProviderKey"]) {
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ from: "harness" }));
});
}));
- const port = await listen(createServer(createProxyHandler({
+ const proxy = createProxyHandler({
harnessPort,
authenticate: (token) => (token === TOKEN ? { id: "phone-1", cloudDesktopAccess: false, browserControlAccess: false } : null),
redeem: () => ({ error: "not used here", code: "pairing_code_wrong" }),
serverName: () => "Test computer",
saveProviderKey,
- })));
- const put = async (body: string, token = TOKEN) => {
- const res = await fetch(`http://127.0.0.1:${port}/api/config?secretStorage=external`, {
- method: "PUT", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body,
+ });
+ const port = await listen(createServer((req, res) => proxy(req, res, listener)));
+ const send = async (method: string, path: string, body: string, token = TOKEN) => {
+ const res = await fetch(`http://127.0.0.1:${port}${path}`, {
+ method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: body || undefined,
});
return { status: res.status, body: await res.json() };
};
- return { harness, put };
+ const put = (body: string, token = TOKEN) => send("PUT", "/api/config?secretStorage=external", body, token);
+ // The same handler, reached through an encrypted session the way index.ts wires it.
+ const e2eOrigin = createE2EOrigin((req, res) => proxy(req, res), (req, socket, head) => proxy.upgrade(req, socket, head));
+ const sendE2E = async (method: string, path: string, body: string) => {
+ const stream = await e2eOrigin.connect({ peer: { kind: "device", id: "phone-1" }, route: "wifi" });
+ return new Promise<{ status: number; body: unknown }>((resolve, reject) => {
+ const req = request({
+ method, path, createConnection: () => stream,
+ headers: { authorization: `Bearer ${TOKEN}`, "content-type": "application/json", "content-length": Buffer.byteLength(body) },
+ }, (res) => {
+ let text = "";
+ res.setEncoding("utf8");
+ res.on("data", (chunk) => { text += chunk; });
+ res.on("end", () => {
+ stream.destroy();
+ resolve({ status: res.statusCode ?? 0, body: JSON.parse(text) });
+ });
+ });
+ req.on("error", reject);
+ req.end(body);
+ });
+ };
+ return { harness, put, send, sendE2E, closeE2E: () => e2eOrigin.close() };
}
describe("a phone's PUT /api/config", () => {
@@ -73,3 +98,48 @@ describe("a phone's PUT /api/config", () => {
expect(harness).toEqual([{ method: "PUT", url: "/api/config?secretStorage=external", body: JSON.stringify({ mistral: { key: "k1" } }) }]);
});
});
+
+describe("a provider key on the plain LAN listener", () => {
+ const key = JSON.stringify({ mistral: { key: "k1" } });
+
+ it("is refused outside an encrypted session, and reaches neither the desktop's save nor the harness", async () => {
+ const patches: unknown[] = [];
+ const { harness, send, closeE2E } = await companion(async (patch) => {
+ patches.push(patch);
+ return { status: 200, body: { mistral: { configured: true } } };
+ }, "lan");
+ for (const [method, path] of [["PUT", "/api/config"], ["PUT", "/api/config?secretStorage=external"], ["POST", "/api/keys/test"]]) {
+ const reply = await send(method, path, key);
+ expect(reply.status, `${method} ${path}`).toBe(403);
+ expect(JSON.stringify(reply.body)).not.toContain("k1");
+ }
+ expect(patches).toEqual([]);
+ expect(harness).toEqual([]);
+ // Unpaired is still unpaired.
+ expect((await send("PUT", "/api/config", key, "not-paired")).status).toBe(401);
+ // Everything else on the plain listener is untouched.
+ expect((await send("GET", "/api/config", "")).status).toBe(200);
+ closeE2E();
+ });
+
+ it("is refused by the standalone companion too, which would forward it", async () => {
+ const { harness, send, closeE2E } = await companion(undefined, "lan");
+ expect((await send("PUT", "/api/config", key)).status).toBe(403);
+ expect((await send("POST", "/api/keys/test", key)).status).toBe(403);
+ expect(harness).toEqual([]);
+ closeE2E();
+ });
+
+ it("is accepted inside an encrypted session", async () => {
+ const patches: unknown[] = [];
+ const { harness, sendE2E, closeE2E } = await companion(async (patch) => {
+ patches.push(patch);
+ return { status: 200, body: { mistral: { configured: true } } };
+ }, "lan");
+ expect(await sendE2E("PUT", "/api/config", key)).toEqual({ status: 200, body: { mistral: { configured: true } } });
+ expect(patches).toEqual([{ mistral: { key: "k1" } }]);
+ expect((await sendE2E("POST", "/api/keys/test", key)).status).toBe(200);
+ expect(harness).toEqual([{ method: "POST", url: "/api/keys/test", body: key }]);
+ closeE2E();
+ });
+});