Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(local-installation): give the local identity key to TeamHub only

claude-opus-5-5-medium37ed8fd796cf
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index 51bcee7c..6ad9594d 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -87,8 +87,10 @@ Gateway and runs Agents. The daemon exits with the app.
32-byte nonce to TeamHub's own port (`POST /v0/local/identity` on
`127.0.0.1:<source.ports.teamhub>` from `instance.json`) and compares,
in constant time, its HMAC-SHA256 under `TEAMHUB_LOCAL_IDENTITY_KEY` (the
- instance's private `services.env`, read by `readLocalIdentity`) over the
- nonce and the window's origin. It asks TeamHub's port rather than the web
+ instance's private `local-identity.key`, read by `readLocalIdentity`) over
+ the nonce and the window's origin. The installer puts the key only in
+ TeamHub's process environment, never in `services.env`, `native.env` or
+ another service's environment, so no other local service can answer. It asks TeamHub's port rather than the web
port, which a program could take and relay through. "Sign in with this
computer's account": `localAccount.signIn()` reads the file in the main
process and signs the window's session in with `signInWithPassword`,
@@ -98,7 +100,16 @@ Gateway and runs Agents. The daemon exits with the app.
with a reason (never the key, nonce or proof) and says "Linger on this
computer is not responding."; the page gets only `{ ok }` or the reason it
failed (mapped by status and error kind by `signInFailure`), never the
- password. The default AI runtime is the
+ password. Known gap: the proof covers TeamHub, not the web listener. If
+ the web process dies and another program takes the web port while
+ TeamHub stays up, the proof still passes and the sign-in sets the session
+ cookies for the web origin, which that program then receives. The
+ password never leaves for it, but the session does. Asking the web origin
+ for a proof would not help, because the web server forwards `/v0` to
+ TeamHub and a relay forwards it the same way; a fix needs a check that
+ the web port belongs to the web process the installer started. Every
+ existing session cookie for the origin has the same exposure.
+ The default AI runtime is the
installer's recommendation, or Codex when the installer cannot inspect the
computer. It records the install location, source, origin and engine in
`desktop/local-server.json` under the default home and, while the window
diff --git a/packages/local-installation/src/account.test.ts b/packages/local-installation/src/account.test.ts
index f5ba9a02..720dd0c4 100644
--- a/packages/local-installation/src/account.test.ts
+++ b/packages/local-installation/src/account.test.ts
@@ -272,20 +272,24 @@ it("reads the server identity from the private instance files", async () => {
JSON.stringify({ source: { ports: { teamhub: 4100, web: 3000 } } }),
{ mode: 0o600 },
);
- const services = path.join(f.instance.root, "services.env");
- await writeFile(services, "SIMPLEX_SECRET_SEED=x\n", { mode: 0o600 });
- // An instance the installer has not upgraded yet has no key.
- await expect(readLocalIdentity(f.instance)).rejects.toThrow(/identity/);
+ // An instance the installer has not upgraded yet has no key; one left in
+ // services.env by an earlier version is not used until the installer
+ // moves it.
await writeFile(
- services,
+ path.join(f.instance.root, "services.env"),
`TEAMHUB_LOCAL_IDENTITY_KEY=${key.toString("base64")}\n`,
{ mode: 0o600 },
);
+ await expect(readLocalIdentity(f.instance)).rejects.toThrow(/identity/);
+ const keyFile = path.join(f.instance.root, "local-identity.key");
+ await writeFile(keyFile, "not a key\n", { mode: 0o600 });
+ await expect(readLocalIdentity(f.instance)).rejects.toThrow(/identity/);
+ await writeFile(keyFile, `${key.toString("base64")}\n`, { mode: 0o600 });
expect(await readLocalIdentity(f.instance)).toEqual({
teamhub: "http://127.0.0.1:4100",
key,
});
const { chmod } = await import("node:fs/promises");
- await chmod(services, 0o644);
+ await chmod(keyFile, 0o644);
await expect(readLocalIdentity(f.instance)).rejects.toThrow(/private/);
});
diff --git a/packages/local-installation/src/account.ts b/packages/local-installation/src/account.ts
index 07a05e2b..09a51724 100644
--- a/packages/local-installation/src/account.ts
+++ b/packages/local-installation/src/account.ts
@@ -2,8 +2,7 @@ import { windowsPrivatePath } from "./windows-private.js";
import { randomBytes } from "node:crypto";
import { lstat, readFile } from "node:fs/promises";
import path from "node:path";
-import { parseEnv } from "node:util";
-import type { Instance } from "./instance.js";
+import { readLocalIdentityKey, type Instance } from "./instance.js";
import { atomicPrivate, readPrivate } from "./private-files.js";
export function validateLocalCredentials(options: {
@@ -59,7 +58,7 @@ export async function readLocalLogin(
}
// How the desktop app checks that the server it sends the owner password to
// is this instance's TeamHub: TeamHub's own loopback address and the key
-// only it and this file's owner hold (see TeamHub's /v0/local/identity).
+// only TeamHub's process and this file's owner hold (see TeamHub's /v0/local/identity).
export interface LocalIdentity {
teamhub: string;
key: Buffer;
@@ -69,28 +68,24 @@ export async function readLocalIdentity(
): Promise<LocalIdentity> {
const unavailable = () =>
new Error("Linger on this computer has no server identity yet.");
- const [settings, services] = await Promise.all([
+ const [settings, encoded] = await Promise.all([
readPrivate(path.join(instance.root, "instance.json")),
- readPrivate(path.join(instance.root, "services.env")),
+ readLocalIdentityKey(instance.root),
]);
- if (settings === undefined || services === undefined) throw unavailable();
+ if (settings === undefined || encoded === undefined) throw unavailable();
let port: unknown;
try {
port = (JSON.parse(settings) as Partial<Instance>).source?.ports?.teamhub;
} catch {
throw unavailable();
}
- const key = Buffer.from(
- parseEnv(services).TEAMHUB_LOCAL_IDENTITY_KEY ?? "",
- "base64",
- );
if (
!Number.isSafeInteger(port) ||
(port as number) < 1024 ||
- (port as number) > 65535 ||
- key.length !== 32
+ (port as number) > 65535
)
throw unavailable();
+ const key = Buffer.from(encoded, "base64");
return { teamhub: `http://127.0.0.1:${port as number}`, key };
}
interface LocalAccount {
diff --git a/packages/local-installation/src/instance.test.ts b/packages/local-installation/src/instance.test.ts
index 94de704d..78b811a1 100644
--- a/packages/local-installation/src/instance.test.ts
+++ b/packages/local-installation/src/instance.test.ts
@@ -8,6 +8,7 @@ import {
type Instance,
initializeInstance,
loadInstance,
+ readLocalIdentityKey,
withInstanceLock,
writeModelConfig,
} from "./instance.js";
@@ -39,47 +40,76 @@ it("persists stable private settings and credentials across repeated initializat
expect((await stat(first.root)).mode & 0o777).toBe(0o700);
});
// Without the encryption key TeamHub cannot save a Composio key from the Apps
-// page; without the identity key the app cannot tell TeamHub from another
-// process on its port.
-const generatedKeys = [
- "TEAMHUB_SECRET_ENCRYPTION_KEY",
- "TEAMHUB_LOCAL_IDENTITY_KEY",
-] as const;
-it.each(generatedKeys)("gives every instance its own %s", async (name) => {
+// page.
+it("gives every instance its own TEAMHUB_SECRET_ENCRYPTION_KEY", async () => {
const root = await home();
const one = await initializeInstance({ name: "one", home: root });
const two = await initializeInstance({ name: "two", home: root });
const env = async (instance: Instance) =>
- parseEnv(await readFile(path.join(instance.root, "services.env"), "utf8"));
- const first = (await env(one))[name];
+ parseEnv(await readFile(path.join(instance.root, "services.env"), "utf8"))
+ .TEAMHUB_SECRET_ENCRYPTION_KEY;
+ const first = await env(one);
expect(Buffer.from(first!, "base64")).toHaveLength(32);
expect(Buffer.from(first!, "base64").toString("base64")).toBe(first);
- expect((await env(two))[name]).not.toBe(first);
- const others = generatedKeys.filter((other) => other !== name);
- for (const other of others) expect((await env(one))[other]).not.toBe(first);
+ expect(await env(two)).not.toBe(first);
+});
+// Instances installed before the key existed get it on their next install or start.
+it("adds a missing TEAMHUB_SECRET_ENCRYPTION_KEY once and keeps every other credential", async () => {
+ const name = "TEAMHUB_SECRET_ENCRYPTION_KEY";
+ const root = await home();
+ const instance = await initializeInstance({ name: "older", home: root });
+ const file = path.join(instance.root, "services.env");
+ const older = (await readFile(file, "utf8"))
+ .split("\n")
+ .filter((line) => !line.startsWith(`${name}=`))
+ .join("\n");
+ await writeFile(file, older);
+ await initializeInstance({ name: "older", home: root });
+ const upgraded = await readFile(file, "utf8");
+ expect(upgraded.startsWith(older)).toBe(true);
+ const key = parseEnv(upgraded)[name];
+ expect(Buffer.from(key!, "base64")).toHaveLength(32);
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
+ await initializeInstance({ name: "older", home: root });
+ expect(await readFile(file, "utf8")).toBe(upgraded);
+});
+// Without the identity key the app cannot tell TeamHub from another process
+// on its port. It stays out of services.env, which the services' env is
+// built from.
+it("gives every instance its own private identity key outside services.env", async () => {
+ const root = await home();
+ const one = await initializeInstance({ name: "one", home: root });
+ const two = await initializeInstance({ name: "two", home: root });
+ const first = await readLocalIdentityKey(one.root);
+ expect(Buffer.from(first!, "base64")).toHaveLength(32);
+ expect(await readLocalIdentityKey(two.root)).not.toBe(first);
+ const file = path.join(one.root, "local-identity.key");
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
+ expect(
+ await readFile(path.join(one.root, "services.env"), "utf8"),
+ ).not.toContain("TEAMHUB_LOCAL_IDENTITY_KEY");
+ await initializeInstance({ name: "one", home: root });
+ expect(await readLocalIdentityKey(one.root)).toBe(first);
+});
+// An earlier version kept the key in services.env; it moves unchanged so the
+// app and the TeamHub it already trusts keep matching.
+it("moves an identity key from services.env without changing it", async () => {
+ const root = await home();
+ const instance = await initializeInstance({ name: "older", home: root });
+ const file = path.join(instance.root, "services.env");
+ const others = await readFile(file, "utf8");
+ const legacy = Buffer.alloc(32, 9).toString("base64");
+ await rm(path.join(instance.root, "local-identity.key"));
+ await writeFile(file, `TEAMHUB_LOCAL_IDENTITY_KEY=${legacy}\n${others}`);
+ await initializeInstance({ name: "older", home: root });
+ expect(await readLocalIdentityKey(instance.root)).toBe(legacy);
+ expect(await readFile(file, "utf8")).toBe(others);
+ // Interrupted after the key file was written: the copy left behind goes.
+ await writeFile(file, `${others}TEAMHUB_LOCAL_IDENTITY_KEY=${legacy}\n`);
+ await initializeInstance({ name: "older", home: root });
+ expect(await readLocalIdentityKey(instance.root)).toBe(legacy);
+ expect(await readFile(file, "utf8")).toBe(others);
});
-// Instances installed before a key existed get it on their next install or start.
-it.each(generatedKeys)(
- "adds a missing %s once and keeps every other credential",
- async (name) => {
- const root = await home();
- const instance = await initializeInstance({ name: "older", home: root });
- const file = path.join(instance.root, "services.env");
- const older = (await readFile(file, "utf8"))
- .split("\n")
- .filter((line) => !line.startsWith(`${name}=`))
- .join("\n");
- await writeFile(file, older);
- await initializeInstance({ name: "older", home: root });
- const upgraded = await readFile(file, "utf8");
- expect(upgraded.startsWith(older)).toBe(true);
- const key = parseEnv(upgraded)[name];
- expect(Buffer.from(key!, "base64")).toHaveLength(32);
- expect((await stat(file)).mode & 0o777).toBe(0o600);
- await initializeInstance({ name: "older", home: root });
- expect(await readFile(file, "utf8")).toBe(upgraded);
- },
-);
it("rejects path traversal names and invalid ports", async () => {
const root = await home();
await expect(
diff --git a/packages/local-installation/src/instance.ts b/packages/local-installation/src/instance.ts
index 6e89ad7b..59946c60 100644
--- a/packages/local-installation/src/instance.ts
+++ b/packages/local-installation/src/instance.ts
@@ -50,10 +50,21 @@ const credentials: Record<string, () => string> = {
LINGER_SECRET_SEED: () => randomBytes(32).toString("hex"),
// TeamHub requires 32 bytes in standard base64.
TEAMHUB_SECRET_ENCRYPTION_KEY: () => randomBytes(32).toString("base64"),
- // Only TeamHub and the desktop app read it: TeamHub proves with it that it
- // is this instance's server before the app sends the saved password.
- TEAMHUB_LOCAL_IDENTITY_KEY: () => randomBytes(32).toString("base64"),
};
+// TeamHub proves with this key that it is this instance's server before the
+// desktop app sends the saved password. It has its own file, not services.env
+// or native.env, so only TeamHub's process (native-source.ts) and the
+// desktop app read it.
+export const localIdentityKeyFile = (root: string) =>
+ path.join(root, "local-identity.key");
+export async function readLocalIdentityKey(
+ root: string,
+): Promise<string | undefined> {
+ const key = (await readPrivate(localIdentityKeyFile(root)))?.trim();
+ return key && validIdentityKey(key) ? key : undefined;
+}
+const validIdentityKey = (key: string) =>
+ /^[A-Za-z0-9+/]{43}=$/.test(key) && Buffer.from(key, "base64").length === 32;
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export { atomicPrivate, privateDirectory, readPrivate };
const missing = (error: unknown) =>
@@ -184,6 +195,7 @@ export async function initializeInstance(
"Instance port is already configured; select a different instance",
);
await writeMissingCredentials(root);
+ await writeLocalIdentityKey(root);
return existing;
}
const reserved = new Set<number>();
@@ -246,6 +258,7 @@ export async function initializeInstance(
};
await privateDirectory(path.dirname(instance.computerConfig));
await writeMissingCredentials(root);
+ await writeLocalIdentityKey(root);
await atomicPrivate(
path.join(root, "instance.json"),
JSON.stringify(instance, null, 2) + "\n",
@@ -277,6 +290,27 @@ async function writeMissingCredentials(root: string): Promise<void> {
`${current}${current && !current.endsWith("\n") ? "\n" : ""}${added.join("")}`,
);
}
+// Writes the identity key once. An earlier version kept it in services.env,
+// which the services were started with; it moves from there unchanged, so a
+// desktop app and TeamHub already paired by it stay paired.
+async function writeLocalIdentityKey(root: string): Promise<void> {
+ const services = path.join(root, "services.env");
+ const current = (await readPrivate(services)) ?? "";
+ const legacy = parseEnv(current).TEAMHUB_LOCAL_IDENTITY_KEY;
+ if (!(await readLocalIdentityKey(root)))
+ await atomicPrivate(
+ localIdentityKeyFile(root),
+ `${legacy && validIdentityKey(legacy) ? legacy : randomBytes(32).toString("base64")}\n`,
+ );
+ if (legacy !== undefined)
+ await atomicPrivate(
+ services,
+ current
+ .split(/(?<=\n)/)
+ .filter((line) => !line.startsWith("TEAMHUB_LOCAL_IDENTITY_KEY="))
+ .join(""),
+ );
+}
export async function withInstanceLock<T>(
instance: Instance,
callback: () => Promise<T>,
diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.ts
index 8ba0e530..7ed179f8 100644
--- a/packages/local-installation/src/native-source-flow.test.ts
+++ b/packages/local-installation/src/native-source-flow.test.ts
@@ -9,7 +9,7 @@ vi.mock("./model-gateway.js", () => ({
}));
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import os from "node:os";
import { afterEach, expect, test, vi } from "vitest";
@@ -194,6 +194,57 @@ test("native services and owner creation continue while selected Runtime authent
expect(JSON.stringify(owner?.[1])).not.toContain(owner?.[2]?.input?.trim());
expect(events.join("\n")).not.toContain(owner?.[2]?.input?.trim());
});
+test("only TeamHub's process gets the server identity key", async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ // Not even a key the installer itself was started with reaches the others.
+ vi.stubEnv("TEAMHUB_LOCAL_IDENTITY_KEY", "inherited");
+ const events: string[] = [];
+ try {
+ await installNativeSource({
+ home: f.home,
+ repo: f.repo,
+ name: "native-identity",
+ setupChoice: "pi",
+ signal: new AbortController().signal,
+ onEvent: (event) => events.push(event.message),
+ });
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ const root = path.join(f.home, "instances", "native-identity");
+ const key = (
+ await readFile(path.join(root, "local-identity.key"), "utf8")
+ ).trim();
+ const services = vi
+ .mocked(startNativeProcess)
+ .mock.calls.map(([options]) => options);
+ expect(
+ services.find((options) => options.name === "teamhub")!.env
+ .TEAMHUB_LOCAL_IDENTITY_KEY,
+ ).toBe(key);
+ const others = services.filter((options) => options.name !== "teamhub");
+ expect(others.map((options) => options.name)).toEqual(
+ expect.arrayContaining(["node-services", "web"]),
+ );
+ for (const options of others)
+ expect(options.env).not.toHaveProperty("TEAMHUB_LOCAL_IDENTITY_KEY");
+ const commands = vi.mocked(runProcess).mock.calls;
+ expect(commands.some((row) => row[1].includes("migrate"))).toBe(true);
+ for (const [, , options] of commands)
+ expect(options?.env ?? {}).not.toHaveProperty("TEAMHUB_LOCAL_IDENTITY_KEY");
+ // Compose and the services load native.env; the installer's own secrets
+ // file no longer holds the key either.
+ for (const file of ["native.env", "services.env"])
+ expect(await readFile(path.join(root, file), "utf8")).not.toContain(
+ "TEAMHUB_LOCAL_IDENTITY_KEY",
+ );
+ expect(events.join("\n")).not.toContain(key);
+});
test("an external Computer skips the Go Computer release and enrollment", async () => {
const f = await fixture();
vi.mocked(prepareRuntime).mockResolvedValue({
diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.ts
index 7517bd8b..5b5ef39e 100644
--- a/packages/local-installation/src/native-source.ts
+++ b/packages/local-installation/src/native-source.ts
@@ -15,6 +15,7 @@ import {
atomicPrivate,
loadInstance,
privateDirectory,
+ readLocalIdentityKey,
withInstanceLock,
type Instance,
} from "./instance.js";
@@ -436,6 +437,10 @@ async function runNativeSource(
/secret|password|token|key|credential|database_url/i.test(key)
)
secrets.push(value);
+ const identityKey = await readLocalIdentityKey(instance.root);
+ if (!identityKey)
+ throw new Error("The instance has no server identity key.");
+ secrets.push(identityKey);
for (const message of configured.warnings)
emit({ kind: "log", stage, message });
const current = instance;
@@ -590,6 +595,9 @@ async function runNativeSource(
? { SONIOX_API_KEY: "", XAI_API_KEY: "" }
: {}),
};
+ // Only TeamHub gets the identity key (serviceOptions); no other
+ // service may prove itself as this instance's server.
+ delete env.TEAMHUB_LOCAL_IDENTITY_KEY;
// The services read user.env, the credentials and the voice tools from
// their environment, which their command line does not cover: a
// change restarts them.
@@ -799,7 +807,10 @@ async function runNativeSource(
name,
],
cwd: current.source!.repo,
- env,
+ env:
+ name === "teamhub"
+ ? { ...env, TEAMHUB_LOCAL_IDENTITY_KEY: identityKey }
+ : env,
signal,
redactions: secrets,
// A changed user.env, port, credential or voice tool restarts it.
diff --git a/packages/local-installation/src/source-checkout.ts b/packages/local-installation/src/source-checkout.ts
index 2cc56d61..25bdf54b 100644
--- a/packages/local-installation/src/source-checkout.ts
+++ b/packages/local-installation/src/source-checkout.ts
@@ -206,7 +206,6 @@ export async function prepareSourceConfiguration(
AGENT_RUNNER_PUBLIC_GATEWAY_URL: `ws://127.0.0.1:${ports.nodeServices}/v1/runner-gateway`,
LINGER_SECRET_SEED: secrets.LINGER_SECRET_SEED!,
TEAMHUB_SECRET_ENCRYPTION_KEY: secrets.TEAMHUB_SECRET_ENCRYPTION_KEY!,
- TEAMHUB_LOCAL_IDENTITY_KEY: secrets.TEAMHUB_LOCAL_IDENTITY_KEY!,
TEAMHUB_DATABASE_URL: `postgres://simplexai:${encodeURIComponent(secrets.LINGER_POSTGRES_PASSWORD!)}@127.0.0.1:${ports.postgres}/simplexai?sslmode=disable`,
TEAMHUB_HTTP_ADDRESS: `127.0.0.1:${ports.teamhub}`,
TEAMHUB_BASE_URL: `http://127.0.0.1:${ports.teamhub}`,
diff --git a/scripts/env-inventory.json b/scripts/env-inventory.json
index 8c22d6b8..d76d2f32 100644
--- a/scripts/env-inventory.json
+++ b/scripts/env-inventory.json
@@ -136,7 +136,7 @@
},
"local-identity": {
"owner": "out-of-env",
- "description": "Per-instance key the local installer generates into the instance's private services.env and passes to TeamHub, which proves with it (POST /v0/local/identity) that it is the installation's server before the desktop app sends the owner password. Unset everywhere else, which turns the endpoint off. Not part of .env.",
+ "description": "Per-instance key the local installer generates into the instance's private local-identity.key and passes to the TeamHub process only (not native.env, which every service and Compose load), which proves with it (POST /v0/local/identity) that it is the installation's server before the desktop app sends the owner password. Unset everywhere else, which turns the endpoint off. Not part of .env.",
"names": ["TEAMHUB_LOCAL_IDENTITY_KEY"]
}
}