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.
feat(desktop): verify the local server before signing in with its account
claude-opus-5-5-medium3c64dc0b4d89
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 4409a1cd..51bcee7c 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -79,15 +79,26 @@ Gateway and runs Agents. The daemon exits with the app.file location" (`shell.showItemInFolder`); an unreadable file shows whyinstead. Only the email and file are kept; Show and Copy read the fileagain, and closing the setup window hides the password. After a logout- the SPA's login page asks `window.lingerDesktop.localAccount.available()`,- which is true only while the window shows the origin in- `local-server.json` and the services are `ready`, and offers "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`, which posts to `127.0.0.1:<port>` (what the- services bind) and sets the cookies for the origin; 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+ the SPA's login page asks `window.lingerDesktop.localAccount.available()`+ on load, every 15 s and when the window comes back into view; it is true+ only while the window shows the origin in `local-server.json`, the+ services are `ready` and TeamHub proves it is this installation's server+ (one check per 2 s at most). The proof: `proveLocalServer` posts a fresh+ 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+ 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`,+ which proves the server first and only then posts the password to the+ same TeamHub port, setting the cookies for the origin; the install-time+ sign-in does the same. A failed proof logs `local_server.identity_unverified`+ 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 theinstaller's recommendation, or Codex when the installer cannot inspect thecomputer. It records the install location, source, origin and engine in`desktop/local-server.json` under the default home and, while the windowdiff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex d806b7f9..2dac6268 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -192,9 +192,9 @@ async function main(): Promise<void> {? { checkout: process.env.LINGER_CHECKOUT }: {}),// The window's session is the default one, which enrollment reads too.- signIn: (origin, email, password) =>- signInWithPassword(origin, email, password, (cookie) =>- session.defaultSession.cookies.set({ url: origin, ...cookie }),+ signIn: (server, email, password) =>+ signInWithPassword(server, email, password, (cookie) =>+ session.defaultSession.cookies.set({ url: server.origin, ...cookie }),),sessionCookie: webSessionCookie,openExternal: (url) => shell.openExternal(url),diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.tsindex 07dc7ed7..c8398b39 100644--- a/apps/desktop/src/main/local-server.test.ts+++ b/apps/desktop/src/main/local-server.test.ts@@ -30,9 +30,13 @@ import {hasNativePostgres,installLocation,parseSetCookie,+ LocalServerUnverifiedError,+ localIdentityProof,+ proveLocalServer,SignInRejectedError,signInFailure,signInWithPassword,+ type LocalServerIdentity,type LocalServerOptions,} from "./local-server.js";import type { DesktopConfig } from "./config.js";@@ -231,6 +235,14 @@ const installerApi = (return { handle, created, retried, runtime };};+const TEAMHUB = "http://127.0.0.1:4100";+const KEY = Buffer.from(Array.from({ length: 32 }, (_, i) => i));+const server = (origin: string): LocalServerIdentity => ({+ origin,+ teamhub: TEAMHUB,+ key: KEY,+});+const fixture = (overrides:| Partial<LocalServerOptions>@@ -273,6 +285,8 @@ const fixture = (const loadServer = vi.fn();const enroll = vi.fn(async () => {});const signIn = vi.fn(async () => {});+ // The installed server proves itself unless a test says otherwise.+ const proveServer = vi.fn(async (_server: LocalServerIdentity) => {});const options = typeof overrides === "function" ? overrides(home) : overrides;const download = options.fetch;const fetcher = (async (@@ -292,6 +306,12 @@ const fixture = (pollMs: 10,freeBytes: 1,signIn,+ serverIdentity: async (_home, origin) => ({+ origin,+ teamhub: TEAMHUB,+ key: KEY,+ }),+ proveServer,...options,fetch: fetcher,});@@ -324,6 +344,7 @@ const fixture = (bus,enroll,signIn,+ proveServer,api,};};@@ -480,7 +501,7 @@ describe("LocalServerModule", () => {},]);expect(f.signIn).toHaveBeenCalledWith(- "http://localhost:3000",+ server("http://localhost:3000"),"pw",);@@ -1959,29 +1980,144 @@ describe("followHttps", () => {});});+// A TeamHub with KEY: it answers challenges for WEB_ORIGIN and logs in.+const WEB_ORIGIN = "http://localhost:3000";+const teamhub = (+ answer: (nonce: string) => Response | Promise<Response> = (nonce) =>+ Response.json({+ proof: localIdentityProof(KEY, nonce, WEB_ORIGIN).toString("base64url"),+ }),+) =>+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = new URL(String(input));+ if (url.pathname === "/v0/local/identity")+ return answer(+ (JSON.parse(String(init?.body)) as { nonce: string }).nonce,+ );+ return new Response("{}", {+ headers: {+ "set-cookie":+ "linger_session=v; Path=/; HttpOnly; SameSite=Lax; Max-Age=60",+ },+ });+ });+const sentPassword = (fetcher: ReturnType<typeof teamhub>, password: string) =>+ fetcher.mock.calls.some(([, init]) => String(init?.body).includes(password));++describe("proveLocalServer", () => {+ // The same vector as TeamHub's internal/localidentity test.+ it("computes TeamHub's proof", () => {+ expect(+ localIdentityProof(KEY, "A".repeat(43), WEB_ORIGIN).toString("base64url"),+ ).toBe("eKUTsEU-NZv-SW4c6jF3nCKa44wHETVelI_1rT6yu9w");+ });++ it("accepts the server that holds the key, asked on its own port", async () => {+ const fetcher = teamhub();+ await proveLocalServer(server(WEB_ORIGIN), fetcher as typeof fetch);+ const [url, init] = fetcher.mock.calls[0]!;+ expect(String(url)).toBe(`${TEAMHUB}/v0/local/identity`);+ const { nonce } = JSON.parse(String(init?.body)) as { nonce: string };+ expect(nonce).toMatch(/^[A-Za-z0-9_-]{43}$/);+ expect(Buffer.from(nonce, "base64url")).toHaveLength(32);+ });++ it.each([+ [+ "another key",+ (nonce: string) =>+ Response.json({+ proof: localIdentityProof(+ Buffer.alloc(32),+ nonce,+ WEB_ORIGIN,+ ).toString("base64url"),+ }),+ "wrong proof",+ ],+ [+ "another origin",+ (nonce: string) =>+ Response.json({+ proof: localIdentityProof(+ KEY,+ nonce,+ "http://localhost:3001",+ ).toString("base64url"),+ }),+ "wrong proof",+ ],+ ["no proof", () => Response.json({}), "wrong proof"],+ ["a page", () => new Response("<html>"), "invalid answer"],+ ["an error", () => new Response("", { status: 404 }), "status 404"],+ ])("rejects a server that answers with %s", async (_case, answer, reason) => {+ await expect(+ proveLocalServer(server(WEB_ORIGIN), teamhub(answer) as typeof fetch),+ ).rejects.toMatchObject({+ name: "LocalServerUnverifiedError",+ reason,+ message: "Linger on this computer is not responding.",+ });+ });++ it("rejects an earlier answer replayed for a new challenge", async () => {+ let first: string | undefined;+ const fetcher = teamhub((nonce) => {+ first ??= localIdentityProof(KEY, nonce, WEB_ORIGIN).toString(+ "base64url",+ );+ return Response.json({ proof: first });+ });+ await proveLocalServer(server(WEB_ORIGIN), fetcher as typeof fetch);+ await expect(+ proveLocalServer(server(WEB_ORIGIN), fetcher as typeof fetch),+ ).rejects.toMatchObject({ reason: "wrong proof" });+ const nonces = fetcher.mock.calls.map(+ ([, init]) => (JSON.parse(String(init?.body)) as { nonce: string }).nonce,+ );+ expect(new Set(nonces).size).toBe(2);+ });++ it("gives up on a server that does not answer", async () => {+ const fetcher = teamhub(+ () => new Promise<Response>(() => {}),+ ).mockImplementation(+ (_input, init) =>+ new Promise((_resolve, reject) =>+ init?.signal?.addEventListener("abort", () =>+ reject(init.signal!.reason),+ ),+ ),+ );+ await expect(+ proveLocalServer(server(WEB_ORIGIN), fetcher as typeof fetch, 20),+ ).rejects.toMatchObject({ reason: "no answer" });+ });++ it("treats nothing listening as no answer", async () => {+ await expect(+ proveLocalServer(server(WEB_ORIGIN), (async () => {+ throw new TypeError("fetch failed");+ }) as typeof fetch),+ ).rejects.toBeInstanceOf(LocalServerUnverifiedError);+ });+});+describe("signInWithPassword", () => {it("hands the session cookies of the local server to the app", async () => {const set = vi.fn(async () => {});- const fetcher = vi.fn(- async () =>- new Response("{}", {- headers: {- "set-cookie":- "linger_session=v; Path=/; HttpOnly; SameSite=Lax; Max-Age=60",- },- }),- );+ const fetcher = teamhub();await signInWithPassword(- "http://localhost:3000",+ server(WEB_ORIGIN),"pw",set,fetcher as typeof fetch,);- const [url, init] = fetcher.mock.calls[0] as unknown as [URL, RequestInit];- // The services bind 127.0.0.1; localhost may resolve to ::1 first.- expect(String(url)).toBe("http://127.0.0.1:3000/v0/auth/login");- expect(init.headers).toMatchObject({ origin: "http://localhost:3000" });+ const [url, init] = fetcher.mock.calls[1]!;+ // The login goes to TeamHub's port, as the window's origin.+ expect(String(url)).toBe(`${TEAMHUB}/v0/auth/login`);+ expect(init?.headers).toMatchObject({ origin: WEB_ORIGIN });expect(set).toHaveBeenCalledWith(expect.objectContaining({name: "linger_session",@@ -1993,14 +2129,42 @@ describe("signInWithPassword", () => {);});+ it.each([+ ["answers wrongly", () => Response.json({ proof: "A".repeat(43) })],+ ["serves a page", () => new Response("<html>login</html>")],+ ])("never sends the password to a server that %s", async (_case, answer) => {+ const fetcher = teamhub(answer);+ await expect(+ signInWithPassword(+ server(WEB_ORIGIN),+ "[email protected]",+ "a-private-password",+ async () => {},+ fetcher as typeof fetch,+ ),+ ).rejects.toBeInstanceOf(LocalServerUnverifiedError);+ expect(fetcher).toHaveBeenCalledOnce();+ expect(sentPassword(fetcher, "a-private-password")).toBe(false);+ });+it("fails without a session", async () => {+ const fetcher = teamhub();+ fetcher.mockImplementationOnce(async (_input, init) => {+ const { nonce } = JSON.parse(String(init?.body)) as { nonce: string };+ return Response.json({+ proof: localIdentityProof(KEY, nonce, WEB_ORIGIN).toString("base64url"),+ });+ });+ fetcher.mockImplementationOnce(+ async () => new Response("{}", { status: 401 }),+ );await expect(signInWithPassword(- "http://localhost:3000",+ server(WEB_ORIGIN),"a","b",async () => {},- (async () => new Response("{}", { status: 401 })) as typeof fetch,+ fetcher as typeof fetch,),).rejects.toEqual(new SignInRejectedError(401));});@@ -2025,6 +2189,9 @@ describe("signInFailure", () => {expect(signInFailure(new DOMException("aborted", "AbortError"))).toBe("Linger on this computer is not responding.",);+ expect(signInFailure(new LocalServerUnverifiedError("wrong proof"))).toBe(+ "Linger on this computer is not responding.",+ );// A message that merely mentions 401 is not a rejected password.expect(signInFailure(new Error("Signing in to Linger failed (401)"))).toBe("Signing in to Linger failed (401)",@@ -2225,7 +2392,11 @@ describe("LocalServerModule owner account", () => {),});await f.module.signInWithAccount();- expect(f.signIn).toHaveBeenCalledWith(ORIGIN, OWNER.email, OWNER.password);+ expect(f.signIn).toHaveBeenCalledWith(+ server(ORIGIN),+ OWNER.email,+ OWNER.password,+ );await f.host.stop("quit");});@@ -2255,6 +2426,10 @@ describe("LocalServerModule owner account", () => {new TypeError("fetch failed"),"Linger on this computer is not responding.",],+ [+ new LocalServerUnverifiedError("wrong proof"),+ "Linger on this computer is not responding.",+ ],])("says what to do when signing in fails (%s)", async (error, message) => {const f = fixture({}, { serverUrl: ORIGIN }, installed(OWNER));f.signIn.mockRejectedValueOnce(error);@@ -2264,6 +2439,57 @@ describe("LocalServerModule owner account", () => {await f.host.stop("quit");});+ it("offers the account only while the server proves it is this installation's", async () => {+ let now = Date.now();+ const clock = vi.spyOn(Date, "now").mockImplementation(() => now);+ try {+ const f = fixture({}, { serverUrl: ORIGIN }, installed(OWNER));+ await f.host.start();+ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ expect(await f.module.servesWindow()).toBe(true);+ expect(f.proveServer).toHaveBeenLastCalledWith(server(ORIGIN));+ // The services stopped, or another program took the port.+ f.proveServer.mockRejectedValue(+ new LocalServerUnverifiedError("no answer"),+ );+ // One check serves the pages for two seconds.+ expect(await f.module.servesWindow()).toBe(true);+ now += 2_000;+ expect(await f.module.servesWindow()).toBe(false);+ expect(await f.module.servesWindow()).toBe(false);+ expect(f.proveServer).toHaveBeenCalledTimes(2);+ // The services are back.+ f.proveServer.mockResolvedValue(undefined);+ now += 2_000;+ expect(await f.module.servesWindow()).toBe(true);+ await f.host.stop("quit");+ } finally {+ clock.mockRestore();+ }+ });++ it("neither offers nor sends the account without the server's identity", async () => {+ const f = fixture(+ {+ serverIdentity: async () => {+ throw new Error(+ "Linger on this computer has no server identity yet.",+ );+ },+ },+ { serverUrl: ORIGIN },+ installed(OWNER),+ );+ await f.host.start();+ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ expect(await f.module.servesWindow()).toBe(false);+ await expect(f.module.signInWithAccount()).rejects.toThrow(+ "Linger on this computer is not responding.",+ );+ expect(f.signIn).not.toHaveBeenCalled();+ await f.host.stop("quit");+ });+it("does not offer the account to another server", async () => {const f = fixture({},diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.tsindex 84616dc9..a5f4c451 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -1,5 +1,11 @@import { spawn } from "node:child_process";-import { createHash, randomUUID } from "node:crypto";+import {+ createHash,+ createHmac,+ randomBytes,+ randomUUID,+ timingSafeEqual,+} from "node:crypto";import { createReadStream, existsSync, readFileSync } from "node:fs";import {constants as fsConstants,@@ -20,7 +26,10 @@ import { pipeline } from "node:stream/promises";import { setTimeout as delay } from "node:timers/promises";import { createZstdDecompress } from "node:zlib";-import { readLocalLogin } from "@linger/local-installation/account";+import {+ readLocalIdentity,+ readLocalLogin,+} from "@linger/local-installation/account";import { downloadVerified } from "@linger/local-installation/download";import { legacyMigrationPending } from "@linger/local-installation/home";import {@@ -244,12 +253,20 @@ export interface LocalServerOptions {// A linger checkout installed instead of the source package, for developers// (LINGER_CHECKOUT).readonly checkout?: string;- // Signs the app's web session in to the local server with its owner.+ // Signs the app's web session in to the local server with its owner, once+ // the server proved it is this installation's (signInWithPassword).readonly signIn: (- origin: string,+ server: LocalServerIdentity,email: string,password: string,) => Promise<void>;+ // The installed server's identity; read from its private files by default.+ readonly serverIdentity?: (+ home: string,+ origin: string,+ ) => Promise<LocalServerIdentity>;+ // Asks the server to prove it; proveLocalServer by default.+ readonly proveServer?: (server: LocalServerIdentity) => Promise<void>;// The cookie header of that web session, to follow the agents it sets up.readonly sessionCookie?: (origin: string) => Promise<string | undefined>;readonly platform?: NodeJS.Platform;@@ -276,6 +293,9 @@ const STARTER_ROOM = "Getting Started";const AGENTS_TIMEOUT_MS = 5 * 60_000;// Each check runs the installer's runtime status, a short process.const SIGN_IN_POLL_MS = 3_000;+// How long one check that the installed server still answers as itself+// serves the pages that ask whether to offer the owner account.+const SERVER_CHECK_TTL_MS = 2_000;// The instance the desktop installs.export const LOCAL_INSTANCE = "desktop";@@ -327,6 +347,10 @@ export class LocalServerModule implements Module {#signInWake: (() => void) | undefined;#switchTo: LocalRuntime | undefined;#opened: string | undefined;+ #serverCheck:+ | { readonly at: number; readonly ok: Promise<boolean> }+ | undefined;+ #serverOk: boolean | undefined;constructor(options: LocalServerOptions) {this.#options = options;@@ -669,7 +693,7 @@ export class LocalServerModule implements Module {});this.#advance("connect", 0, "Connecting this computer…");const login = await installer.login();- await this.#options.signIn(job.origin, login.email, login.password);+ await this.#signInAs(home, job.origin, login.email, login.password);await this.#writeRecord({home,repo,@@ -806,12 +830,17 @@ export class LocalServerModule implements Module {}// Whether the window shows the Linger this app installed here and its- // services are running; only then can its owner account sign the window in.+ // server still answers as itself; only then can its owner account sign the+ // window in. The services can stop while the app runs, and another program+ // can take their port, so the server is asked every time, at most once per+ // SERVER_CHECK_TTL_MS.async servesWindow(): Promise<boolean> {- if (this.#phase !== "ready") return false;- const record = await this.#readRecord();- const serverUrl = this.#ctx?.config.get().serverUrl;- return !!record && !!serverUrl && sameOrigin(record.origin, serverUrl);+ const record = await this.#windowRecord();+ if (!record) return false;+ const now = Date.now();+ if (!this.#serverCheck || now - this.#serverCheck.at >= SERVER_CHECK_TTL_MS)+ this.#serverCheck = { at: now, ok: this.#checkServer(record) };+ return this.#serverCheck.ok;}// The owner account the installer created, read from its private file on@@ -827,14 +856,15 @@ export class LocalServerModule implements Module {// Signs the window in to the installed Linger with its owner account; the// password goes from the file to the server and nowhere else.async signInWithAccount(): Promise<void> {- const record = await this.#readRecord();- if (!record || !(await this.servesWindow()))+ const record = await this.#windowRecord();+ if (!record)throw new Error("This window is not showing the Linger on this computer.",);const account = await this.account();try {- await this.#options.signIn(+ await this.#signInAs(+ record.home,record.origin,account.email,account.password,@@ -844,6 +874,78 @@ export class LocalServerModule implements Module {}}+ // The installation the window shows while its services run.+ async #windowRecord(): Promise<LocalRecord | undefined> {+ if (this.#phase !== "ready") return undefined;+ const record = await this.#readRecord();+ const serverUrl = this.#ctx?.config.get().serverUrl;+ return record && serverUrl && sameOrigin(record.origin, serverUrl)+ ? record+ : undefined;+ }++ async #serverIdentity(+ home: string,+ origin: string,+ ): Promise<LocalServerIdentity> {+ try {+ if (this.#options.serverIdentity)+ return await this.#options.serverIdentity(home, origin);+ const identity = await readLocalIdentity({+ root: path.join(home, "instances", LOCAL_INSTANCE),+ });+ return { origin, ...identity };+ } catch (error) {+ throw new LocalServerUnverifiedError("no identity", { cause: error });+ }+ }++ async #checkServer(record: LocalRecord): Promise<boolean> {+ const prove =+ this.#options.proveServer ??+ ((server) => proveLocalServer(server, this.#options.fetch));+ let ok = true;+ let reason: string | undefined;+ try {+ await prove(await this.#serverIdentity(record.home, record.origin));+ } catch (error) {+ ok = false;+ reason = unverifiedReason(error);+ }+ // Only changes are logged, so the periodic checks stay out of the log.+ if (ok !== this.#serverOk)+ this.#ctx?.log[ok ? "info" : "warn"]("local_server.identity", {+ ok,+ ...(reason ? { reason } : {}),+ });+ this.#serverOk = ok;+ return ok;+ }++ async #signInAs(+ home: string,+ origin: string,+ email: string,+ password: string,+ ): Promise<void> {+ try {+ await this.#options.signIn(+ await this.#serverIdentity(home, origin),+ email,+ password,+ );+ } catch (error) {+ if (error instanceof LocalServerUnverifiedError) {+ this.#ctx?.log.warn("local_server.identity_unverified", {+ reason: error.reason,+ });+ // The next question about the account asks the server again.+ this.#serverCheck = undefined;+ }+ throw error;+ }+ }+// Starts the runtime's own login (the installer runs it), or hands it the// code the vendor's page showed.async startSignIn(code?: string): Promise<void> {@@ -2366,8 +2468,10 @@ export const signInFailure = (error: unknown): string => {if (error instanceof SignInRejectedError && error.status === 401)return "The saved password no longer works. Log in with your email and password.";// fetch rejects with a TypeError when nothing answers, and with a- // TimeoutError or AbortError when the answer takes too long.+ // TimeoutError or AbortError when the answer takes too long. What answers+ // without proving it is this installation's server is not Linger either.if (+ error instanceof LocalServerUnverifiedError ||error instanceof TypeError ||(error instanceof Error &&(error.name === "TimeoutError" || error.name === "AbortError"))@@ -2376,38 +2480,120 @@ export const signInFailure = (error: unknown): string => {return error instanceof Error ? error.message : String(error);};-// The local services listen on 127.0.0.1 only, while the window uses-// localhost, which may resolve to ::1 first.-export const loopbackUrl = (origin: string): URL => {- const url = new URL(origin);- if (url.hostname === "localhost") url.hostname = "127.0.0.1";- return url;+// The installed server as the desktop checks it: the origin the window+// uses, TeamHub's own loopback address and the key only TeamHub and this+// computer's account hold.+export interface LocalServerIdentity {+ readonly origin: string;+ readonly teamhub: string;+ readonly key: Uint8Array;+}++// The installed server did not prove it is this installation's.+export class LocalServerUnverifiedError extends Error {+ // Says what failed, never with what.+ readonly reason: string;++ constructor(reason: string, options?: ErrorOptions) {+ super("Linger on this computer is not responding.", options);+ this.name = "LocalServerUnverifiedError";+ this.reason = reason;+ }+}++const unverifiedReason = (error: unknown): string =>+ error instanceof LocalServerUnverifiedError+ ? error.reason+ : error instanceof Error+ ? error.name+ : "unknown";++export const LOCAL_IDENTITY_TIMEOUT_MS = 5_000;++// What TeamHub answers a challenge with (internal/localidentity).+export const localIdentityProof = (+ key: Uint8Array,+ nonce: string,+ origin: string,+): Buffer =>+ createHmac("sha256", key)+ .update(`linger-local-identity\n${nonce}\n${origin}`)+ .digest();++// Asks TeamHub to prove it holds this installation's identity key, with a+// fresh nonce each time, so an earlier answer proves nothing. The challenge+// goes to TeamHub's own port: a program on the web port could pass it on to+// a TeamHub still running, but whatever answers on TeamHub's port and holds+// the key is TeamHub.+export const proveLocalServer = async (+ server: LocalServerIdentity,+ fetcher: typeof fetch = fetch,+ timeoutMs = LOCAL_IDENTITY_TIMEOUT_MS,+): Promise<void> => {+ const nonce = randomBytes(32).toString("base64url");+ let proof: unknown;+ try {+ const response = await fetcher(+ new URL("/v0/local/identity", server.teamhub),+ {+ method: "POST",+ headers: {+ accept: "application/json",+ "content-type": "application/json",+ },+ body: JSON.stringify({ nonce }),+ redirect: "error",+ signal: AbortSignal.timeout(timeoutMs),+ },+ );+ if (!response.ok) {+ await response.body?.cancel();+ throw new LocalServerUnverifiedError(`status ${response.status}`);+ }+ proof = ((await response.json()) as { proof?: unknown } | null)?.proof;+ } catch (error) {+ if (error instanceof LocalServerUnverifiedError) throw error;+ throw new LocalServerUnverifiedError(+ error instanceof SyntaxError ? "invalid answer" : "no answer",+ { cause: error },+ );+ }+ const expected = localIdentityProof(server.key, nonce, server.origin);+ const actual =+ typeof proof === "string" && /^[A-Za-z0-9_-]{43}$/.test(proof)+ ? Buffer.from(proof, "base64url")+ : undefined;+ if (+ !actual ||+ actual.length !== expected.length ||+ !timingSafeEqual(actual, expected)+ )+ throw new LocalServerUnverifiedError("wrong proof");};// Signs in to the local server with its owner and hands the session cookies-// to the app's web session; the password is never stored. The request goes-// to the loopback address the services bind, the cookies to the origin.+// to the app's web session; the password is never stored, and is sent only+// after the server proved it is this installation's TeamHub. Both requests+// go to TeamHub's own loopback port, the cookies to the window's origin.export const signInWithPassword = async (- origin: string,+ server: LocalServerIdentity,email: string,password: string,setCookie: (cookie: SetCookie) => Promise<void>,fetcher: typeof fetch = fetch,): Promise<void> => {- const response = await fetcher(- new URL("/v0/auth/login", loopbackUrl(origin)),- {- method: "POST",- headers: {- accept: "application/json",- "content-type": "application/json",- origin,- },- body: JSON.stringify({ identifier: email, password }),- redirect: "error",- signal: AbortSignal.timeout(30_000),+ await proveLocalServer(server, fetcher);+ const response = await fetcher(new URL("/v0/auth/login", server.teamhub), {+ method: "POST",+ headers: {+ accept: "application/json",+ "content-type": "application/json",+ origin: server.origin,},- );+ body: JSON.stringify({ identifier: email, password }),+ redirect: "error",+ signal: AbortSignal.timeout(30_000),+ });await response.body?.cancel();if (!response.ok) throw new SignInRejectedError(response.status);const cookies = response.headersdiff --git a/apps/teamhub/internal/app/handlers_local_identity.go b/apps/teamhub/internal/app/handlers_local_identity.gonew file mode 100644index 00000000..cb7ec5eb--- /dev/null+++ b/apps/teamhub/internal/app/handlers_local_identity.go@@ -0,0 +1,31 @@+package app++import (+ "net/http"++ "github.com/gin-gonic/gin"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/localidentity"+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"+)++// proveLocalIdentity answers the desktop app's challenge on a local+// installation; other servers have no key and do not offer it.+func (a *App) proveLocalIdentity(c *gin.Context) {+ if a.cfg.LocalIdentityKey == "" {+ a.writeError(c, http.StatusNotFound, "NOT_FOUND", "not a local installation")+ return+ }+ key, err := localidentity.DecodeKey(a.cfg.LocalIdentityKey)+ if err != nil {+ a.internalError(c, "decode local identity key", err)+ return+ }+ var request httpapi.LocalIdentityChallenge+ if err := decodeJSON(c, &request); err != nil || !localidentity.ValidNonce(request.Nonce) {+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "nonce must be 32 bytes in unpadded base64url")+ return+ }+ c.JSON(http.StatusOK, httpapi.LocalIdentityProof{+ Proof: localidentity.Proof(key, request.Nonce, a.cfg.PublicWebURL),+ })+}diff --git a/apps/teamhub/internal/app/handlers_local_identity_test.go b/apps/teamhub/internal/app/handlers_local_identity_test.gonew file mode 100644index 00000000..e57043dc--- /dev/null+++ b/apps/teamhub/internal/app/handlers_local_identity_test.go@@ -0,0 +1,69 @@+package app++import (+ "encoding/base64"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/config"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/localidentity"+)++func localIdentityServer(key string) *gin.Engine {+ gin.SetMode(gin.TestMode)+ a := &App{cfg: config.ForTest(func(c *config.Config) {+ c.PublicWebURL = "http://localhost:3000"+ c.LocalIdentityKey = key+ })}+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set("request_id", "request") })+ engine.POST("/v0/local/identity", a.proveLocalIdentity)+ return engine+}++func proveLocalIdentity(engine *gin.Engine, body string) *httptest.ResponseRecorder {+ request := httptest.NewRequest(http.MethodPost, "/v0/local/identity", strings.NewReader(body))+ request.Header.Set("Content-Type", "application/json")+ response := httptest.NewRecorder()+ engine.ServeHTTP(response, request)+ return response+}++func TestLocalIdentityAnswersTheNonceForThisOrigin(t *testing.T) {+ raw := make([]byte, 32)+ raw[0] = 7+ engine := localIdentityServer(base64.StdEncoding.EncodeToString(raw))+ nonce := base64.RawURLEncoding.EncodeToString([]byte(strings.Repeat("n", 32)))+ response := proveLocalIdentity(engine, `{"nonce":"`+nonce+`"}`)+ if response.Code != http.StatusOK {+ t.Fatalf("status=%d body=%s", response.Code, response.Body)+ }+ var body struct{ Proof string }+ if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {+ t.Fatal(err)+ }+ if body.Proof != localidentity.Proof(raw, nonce, "http://localhost:3000") {+ t.Fatalf("proof=%s", body.Proof)+ }+}++func TestLocalIdentityRejectsMalformedNonces(t *testing.T) {+ engine := localIdentityServer(base64.StdEncoding.EncodeToString(make([]byte, 32)))+ for _, body := range []string{`{}`, `{"nonce":"short"}`, `{"nonce":"` + strings.Repeat("A", 43) + `","extra":1}`, `not json`} {+ if response := proveLocalIdentity(engine, body); response.Code != http.StatusBadRequest {+ t.Fatalf("body %s: status=%d", body, response.Code)+ }+ }+}++func TestLocalIdentityIsAbsentWithoutAKey(t *testing.T) {+ engine := localIdentityServer("")+ response := proveLocalIdentity(engine, `{"nonce":"`+strings.Repeat("A", 43)+`"}`)+ if response.Code != http.StatusNotFound {+ t.Fatalf("status=%d", response.Code)+ }+}diff --git a/apps/teamhub/internal/app/routes_public.go b/apps/teamhub/internal/app/routes_public.goindex f0fc3723..6153b3bb 100644--- a/apps/teamhub/internal/app/routes_public.go+++ b/apps/teamhub/internal/app/routes_public.go@@ -81,6 +81,7 @@ func (a *App) publicRoutes() []contractRoute {route(http.MethodGet, "/v0/library/documents", httpapi.ListLibraryDocumentsParams{}, session, a.listLibraryDocuments),route(http.MethodGet, "/v0/library/documents/search", httpapi.SearchLibraryDocumentsParams{}, session, a.searchLibraryDocuments),route(http.MethodPost, "/v0/local-computer-enrollments/:enrollmentId/exchange", nil, a.exchangeLocalComputerEnrollment),+ route(http.MethodPost, "/v0/local/identity", nil, a.proveLocalIdentity),route(http.MethodGet, "/v0/me", nil, session, a.getCurrentIdentity),route(http.MethodDelete, "/v0/rooms/:roomId", nil, session, a.deleteRoom),route(http.MethodGet, "/v0/rooms/:roomId", nil, session, a.getRoom),diff --git a/apps/teamhub/internal/config/config.go b/apps/teamhub/internal/config/config.goindex bd17e9ff..8636889a 100644--- a/apps/teamhub/internal/config/config.go+++ b/apps/teamhub/internal/config/config.go@@ -15,6 +15,7 @@ import ("strings""time"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/localidentity""github.com/simplexai-labs/linger/apps/teamhub/internal/secretbox")@@ -68,6 +69,9 @@ type Config struct {CaptureMaxBytes int64SkillPackageMaxArchiveBytes int64PublicWebURL string+ // LocalIdentityKey proves to the desktop app that this server is the+ // Linger installed on this computer; set only on local installations.+ LocalIdentityKey string// The optional features: each is assembled from its own group, and one// whose configuration is missing is not built.ExternalApps ExternalAppsConfig@@ -298,6 +302,7 @@ func applyEnvironment(cfg *Config) {setNonemptyEnvironment(&cfg.ExternalApps.ComposioEnvironmentKey, "TEAMHUB_COMPOSIO_ENVIRONMENT_KEY")setNonemptyEnvironment(&cfg.ExternalApps.ComposioAPIKey, "COMPOSIO_API_KEY")setNonemptyEnvironment(&cfg.ExternalApps.SecretEncryptionKey, "TEAMHUB_SECRET_ENCRYPTION_KEY")+ setNonemptyEnvironment(&cfg.LocalIdentityKey, "TEAMHUB_LOCAL_IDENTITY_KEY")setNonemptyEnvironment(&cfg.Voice.SonioxAPIKey, "SONIOX_API_KEY")setNonemptyEnvironment(&cfg.Voice.XaiAPIKey, "XAI_API_KEY")setNonemptyEnvironment(&cfg.Voice.LiveKitURL, "LIVEKIT_URL")@@ -378,6 +383,11 @@ func validate(cfg *Config) error {return errors.New("TEAMHUB_SECRET_ENCRYPTION_KEY must be 32 bytes in standard base64")}}+ if cfg.LocalIdentityKey != "" {+ if _, err := localidentity.DecodeKey(cfg.LocalIdentityKey); err != nil {+ return err+ }+ }// The judge runs through the Agent Service, which owns the Runtime link.if cfg.PermissionReview.Enabled && (cfg.NodeServicesURL == "" || cfg.NodeServicesInternalToken == "") {return errors.New("TEAMHUB_PERMISSION_REVIEW requires the Agent Service link (LINGER_SECRET_SEED)")diff --git a/apps/teamhub/internal/config/config_test.go b/apps/teamhub/internal/config/config_test.goindex 01fb6e74..b44b2c48 100644--- a/apps/teamhub/internal/config/config_test.go+++ b/apps/teamhub/internal/config/config_test.go@@ -20,6 +20,7 @@ var teamhubEnvironment = []string{"TEAMHUB_ARTIFACT_STORAGE_ROOT","TEAMHUB_DOCUMENT_PREVIEW_PUBLIC_ORIGIN","COMPOSIO_API_KEY",+ "TEAMHUB_LOCAL_IDENTITY_KEY","TEAMHUB_COMPOSIO_ENVIRONMENT_KEY","WEB_PUBLIC_ORIGIN","SONIOX_API_KEY",@@ -313,6 +314,7 @@ func TestLoadRejectsInvalidConfiguration(t *testing.T) {{name: "public URL must be an origin", env: map[string]string{"TEAMHUB_DATABASE_URL": "postgres://example", "WEB_PUBLIC_ORIGIN": "https://[email protected]/path"}},{name: "Artifact storage root required", env: map[string]string{"TEAMHUB_DATABASE_URL": "postgres://example", "TEAMHUB_ARTIFACT_STORAGE_ROOT": " "}},{name: "invalid Composio environment key", env: map[string]string{"TEAMHUB_DATABASE_URL": "postgres://example", "TEAMHUB_COMPOSIO_ENVIRONMENT_KEY": "Shared:Env"}},+ {name: "local identity key must be 32 bytes", env: map[string]string{"TEAMHUB_DATABASE_URL": "postgres://example", "TEAMHUB_LOCAL_IDENTITY_KEY": "c2hvcnQ="}},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {diff --git a/apps/teamhub/internal/localidentity/localidentity.go b/apps/teamhub/internal/localidentity/localidentity.gonew file mode 100644index 00000000..a96ff9cc--- /dev/null+++ b/apps/teamhub/internal/localidentity/localidentity.go@@ -0,0 +1,39 @@+// Package localidentity lets the desktop app check that the server on a local+// installation's port is that installation before it sends the owner's+// password: both sides hold a per-installation key, and the server answers a+// fresh nonce with an HMAC only the key can produce.+package localidentity++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "errors"+ "regexp"+)++const label = "linger-local-identity"++var noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)++// DecodeKey reads TEAMHUB_LOCAL_IDENTITY_KEY: 32 bytes in standard base64.+func DecodeKey(value string) ([]byte, error) {+ key, err := base64.StdEncoding.DecodeString(value)+ if err != nil || len(key) != 32 {+ return nil, errors.New("TEAMHUB_LOCAL_IDENTITY_KEY must be 32 bytes in standard base64")+ }+ return key, nil+}++// ValidNonce reports whether nonce is 32 bytes in unpadded base64url.+func ValidNonce(nonce string) bool {+ return noncePattern.MatchString(nonce)+}++// Proof is the unpadded base64url HMAC-SHA256 of the label, the nonce and the+// server's web origin, joined with newlines.+func Proof(key []byte, nonce, origin string) string {+ mac := hmac.New(sha256.New, key)+ mac.Write([]byte(label + "\n" + nonce + "\n" + origin))+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))+}diff --git a/apps/teamhub/internal/localidentity/localidentity_test.go b/apps/teamhub/internal/localidentity/localidentity_test.gonew file mode 100644index 00000000..74013eec--- /dev/null+++ b/apps/teamhub/internal/localidentity/localidentity_test.go@@ -0,0 +1,48 @@+package localidentity++import (+ "encoding/base64"+ "strings"+ "testing"+)++func TestProofMatchesTheDesktopVector(t *testing.T) {+ key := make([]byte, 32)+ for i := range key {+ key[i] = byte(i)+ }+ nonce := strings.Repeat("A", 43)+ // The desktop app computes the same value (local-server.test.ts).+ const want = "eKUTsEU-NZv-SW4c6jF3nCKa44wHETVelI_1rT6yu9w"+ if got := Proof(key, nonce, "http://localhost:3000"); got != want {+ t.Fatalf("proof=%s want=%s", got, want)+ }+ if Proof(key, nonce, "http://localhost:3001") == want {+ t.Fatal("proof ignores the origin")+ }+ if Proof(key, strings.Repeat("B", 43), "http://localhost:3000") == want {+ t.Fatal("proof ignores the nonce")+ }+}++func TestDecodeKeyRequires32Bytes(t *testing.T) {+ if _, err := DecodeKey(base64.StdEncoding.EncodeToString(make([]byte, 32))); err != nil {+ t.Fatal(err)+ }+ for _, value := range []string{"", "short", base64.StdEncoding.EncodeToString(make([]byte, 31)), base64.RawURLEncoding.EncodeToString(make([]byte, 32))} {+ if _, err := DecodeKey(value); err == nil {+ t.Fatalf("accepted %q", value)+ }+ }+}++func TestValidNonce(t *testing.T) {+ if !ValidNonce(base64.RawURLEncoding.EncodeToString(make([]byte, 32))) {+ t.Fatal("rejected a 32-byte nonce")+ }+ for _, nonce := range []string{"", strings.Repeat("A", 42), strings.Repeat("A", 44), strings.Repeat("+", 43)} {+ if ValidNonce(nonce) {+ t.Fatalf("accepted %q", nonce)+ }+ }+}diff --git a/apps/web/src/features/auth/desktop-local-account.ts b/apps/web/src/features/auth/desktop-local-account.tsindex ccb31120..199234a9 100644--- a/apps/web/src/features/auth/desktop-local-account.ts+++ b/apps/web/src/features/auth/desktop-local-account.ts@@ -20,10 +20,17 @@ function desktopLocalAccount(): DesktopLocalAccount | undefined {.lingerDesktop?.localAccount;}+// How often the page asks again whether the desktop can still sign it in:+// the local services can stop, or another program take their port, while+// the page is open.+export const DESKTOP_LOCAL_ACCOUNT_CHECK_MS = 15_000;+/*** The account sign-in when this page runs in the desktop app and shows the- * Linger installed on this computer; undefined in a browser, in older desktop- * builds and for any other server.+ * Linger installed on this computer, while its server answers as itself;+ * undefined in a browser, in older desktop builds and for any other server.+ * Asked again every DESKTOP_LOCAL_ACCOUNT_CHECK_MS and whenever the window+ * comes back into view.*/export function useDesktopLocalAccount(): DesktopLocalAccount | undefined {const [account, setAccount] = useState<DesktopLocalAccount>();@@ -31,14 +38,29 @@ export function useDesktopLocalAccount(): DesktopLocalAccount | undefined {const api = desktopLocalAccount();if (!api) return;let active = true;- api- .available()- .then((available) => {- if (active && available) setAccount(api);- })- .catch(() => undefined);+ let checking = false;+ const check = () => {+ if (checking || document.visibilityState === "hidden") return;+ checking = true;+ void api+ .available()+ .catch(() => false)+ .then((available) => {+ if (active) setAccount(available ? api : undefined);+ })+ .finally(() => {+ checking = false;+ });+ };+ check();+ const timer = window.setInterval(check, DESKTOP_LOCAL_ACCOUNT_CHECK_MS);+ window.addEventListener("focus", check);+ document.addEventListener("visibilitychange", check);return () => {active = false;+ window.clearInterval(timer);+ window.removeEventListener("focus", check);+ document.removeEventListener("visibilitychange", check);};}, []);return account;diff --git a/apps/web/src/features/auth/teamhub-login-page.test.tsx b/apps/web/src/features/auth/teamhub-login-page.test.tsxindex b8427c90..eb01929a 100644--- a/apps/web/src/features/auth/teamhub-login-page.test.tsx+++ b/apps/web/src/features/auth/teamhub-login-page.test.tsx@@ -16,6 +16,7 @@ import {} from "@/test/teamhub-test-server";import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";+import { DESKTOP_LOCAL_ACCOUNT_CHECK_MS } from "./desktop-local-account";import { TeamHubLoginPage } from "./teamhub-login-page";afterEach(() => vi.useRealTimers());@@ -422,6 +423,49 @@ describe("TeamHubLoginPage in the desktop app", () => {).not.toBeInTheDocument();});+ it("hides the account button while the desktop cannot use it and shows it again", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const available = vi.fn(async () => true);+ desktop({ available, signIn: vi.fn() });+ renderAuthenticationPage({});+ expect(+ await screen.findByRole("button", { name: LOCAL_BUTTON }),+ ).toBeInTheDocument();+ // The local services stopped.+ available.mockResolvedValue(false);+ await act(() =>+ vi.advanceTimersByTimeAsync(DESKTOP_LOCAL_ACCOUNT_CHECK_MS),+ );+ expect(+ screen.queryByRole("button", { name: LOCAL_BUTTON }),+ ).not.toBeInTheDocument();+ // They are back; the window coming into view asks at once.+ available.mockResolvedValue(true);+ await act(async () => {+ window.dispatchEvent(new Event("focus"));+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(+ screen.getByRole("button", { name: LOCAL_BUTTON }),+ ).toBeInTheDocument();+ expect(available).toHaveBeenCalledTimes(3);+ });++ it("hides the account button when asking fails", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const available = vi.fn(async () => true);+ desktop({ available, signIn: vi.fn() });+ renderAuthenticationPage({});+ await screen.findByRole("button", { name: LOCAL_BUTTON });+ available.mockRejectedValue(new Error("Not allowed"));+ await act(() =>+ vi.advanceTimersByTimeAsync(DESKTOP_LOCAL_ACCOUNT_CHECK_MS),+ );+ expect(+ screen.queryByRole("button", { name: LOCAL_BUTTON }),+ ).not.toBeInTheDocument();+ });+it("signs in with one click and confirms the Session the desktop set", async () => {const verified = {id: "local-session",diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.goindex c3358751..1111f522 100644--- a/contracts/generated/go/teamhubpublic/openapi.gen.go+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go@@ -5610,6 +5610,18 @@ type LocalComputerWorkspaceGrant struct {// LocalComputerWorkspaceGrantMode defines model for LocalComputerWorkspaceGrant.Mode.type LocalComputerWorkspaceGrantMode string+// LocalIdentityChallenge defines model for LocalIdentityChallenge.+type LocalIdentityChallenge struct {+ // Nonce 32 fresh random bytes in unpadded base64url.+ Nonce string `json:"nonce"`+}++// LocalIdentityProof defines model for LocalIdentityProof.+type LocalIdentityProof struct {+ // Proof Unpadded base64url HMAC-SHA256 of the challenge.+ Proof string `json:"proof"`+}+// LocalRuntimeDiagnosticErrorCode defines model for LocalRuntimeDiagnosticErrorCode.type LocalRuntimeDiagnosticErrorCode string@@ -8711,6 +8723,9 @@ type CreateExternalConnectionStatusCheckJSONRequestBody = ExternalConnectionStat// ExchangeLocalComputerEnrollmentJSONRequestBody defines body for ExchangeLocalComputerEnrollment for application/json ContentType.type ExchangeLocalComputerEnrollmentJSONRequestBody = LocalComputerEnrollmentExchangeRequest+// ProveLocalIdentityJSONRequestBody defines body for ProveLocalIdentity for application/json ContentType.+type ProveLocalIdentityJSONRequestBody = LocalIdentityChallenge+// UpdateRoomJSONRequestBody defines body for UpdateRoom for application/json ContentType.type UpdateRoomJSONRequestBody = RoomUpdateRequestdiff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.tsindex d5fa16b5..70583169 100644--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts@@ -44,6 +44,26 @@ export interface paths {patch?: never;trace?: never;};+ "/v0/local/identity": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Prove that this server is the Linger installed on this computer.+ * @description Answers only on a local installation that has TEAMHUB_LOCAL_IDENTITY_KEY; elsewhere 404. The proof is the unpadded base64url HMAC-SHA256, keyed with that 32-byte key, of "linger-local-identity", the nonce and the server's web origin, joined with newlines. The desktop app checks it with the key from the installation's private files before it sends the owner's password, so a process that took the port cannot receive it.+ */+ post: operations["proveLocalIdentity"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/v0/session": {parameters: {query?: never;@@ -3971,6 +3991,14 @@ export interface components {ErrorResponse: {error: components["schemas"]["Error"];};+ LocalIdentityChallenge: {+ /** @description 32 fresh random bytes in unpadded base64url. */+ nonce: string;+ };+ LocalIdentityProof: {+ /** @description Unpadded base64url HMAC-SHA256 of the challenge. */+ proof: string;+ };PasswordChangeRequest: {current_password: string;/** @description 8-1024 UTF-8 bytes. TeamHub counts bytes; minLength and maxLength count characters, so they bound the byte rule only loosely. */@@ -7654,6 +7682,32 @@ export interface operations {500: components["responses"]["InternalError"];};};+ proveLocalIdentity: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ "application/json": components["schemas"]["LocalIdentityChallenge"];+ };+ };+ responses: {+ /** @description The proof for this nonce. */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["LocalIdentityProof"];+ };+ };+ 400: components["responses"]["BadRequest"];+ 404: components["responses"]["NotFound"];+ };+ };getSession: {parameters: {query?: never;diff --git a/contracts/openapi/components/domain.yaml b/contracts/openapi/components/domain.yamlindex 47c9fa51..caec2fdd 100644--- a/contracts/openapi/components/domain.yaml+++ b/contracts/openapi/components/domain.yaml@@ -699,6 +699,23 @@ components:minLength: 1maxLength: 1024writeOnly: true+ LocalIdentityChallenge:+ type: object+ additionalProperties: false+ required: [nonce]+ properties:+ nonce:+ type: string+ pattern: "^[A-Za-z0-9_-]{43}$"+ description: 32 fresh random bytes in unpadded base64url.+ LocalIdentityProof:+ type: object+ additionalProperties: false+ required: [proof]+ properties:+ proof:+ type: string+ description: Unpadded base64url HMAC-SHA256 of the challenge.RoomKind:type: stringenum: [room, direct, thread]diff --git a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml b/contracts/openapi/teamhub-public/teamhub-api.openapi.yamlindex 48bc57eb..4fdde98a 100644--- a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml+++ b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml@@ -107,6 +107,35 @@ paths:description: Session revoked or already absent.'500':$ref: '../components/common.yaml#/components/responses/InternalError'+ /v0/local/identity:+ post:+ tags: [Authentication]+ operationId: proveLocalIdentity+ summary: Prove that this server is the Linger installed on this computer.+ description: >-+ Answers only on a local installation that has TEAMHUB_LOCAL_IDENTITY_KEY; elsewhere 404.+ The proof is the unpadded base64url HMAC-SHA256, keyed with that 32-byte key, of+ "linger-local-identity", the nonce and the server's web origin, joined with newlines. The+ desktop app checks it with the key from the installation's private files before it sends+ the owner's password, so a process that took the port cannot receive it.+ security: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '../components/domain.yaml#/components/schemas/LocalIdentityChallenge'+ responses:+ '200':+ description: The proof for this nonce.+ content:+ application/json:+ schema:+ $ref: '../components/domain.yaml#/components/schemas/LocalIdentityProof'+ '400':+ $ref: '../components/common.yaml#/components/responses/BadRequest'+ '404':+ $ref: '../components/common.yaml#/components/responses/NotFound'/v0/session:post:tags: [Authentication]diff --git a/packages/local-installation/src/account.test.ts b/packages/local-installation/src/account.test.tsindex e0d63f7d..f5ba9a02 100644--- a/packages/local-installation/src/account.test.ts+++ b/packages/local-installation/src/account.test.ts@@ -260,3 +260,32 @@ it("uses a source owner provisioner with saved credentials and confirms login",expect(attempts).toBe(2);expect(JSON.parse(await readFile(f.file, "utf8")).provisioned).toBe(true);});+it("reads the server identity from the private instance files", async () => {+ const { readLocalIdentity } = await import("./account.js");+ const f = await fixture();+ const key = Buffer.alloc(32, 7);+ await expect(readLocalIdentity(f.instance)).rejects.toThrow(+ "Linger on this computer has no server identity yet.",+ );+ await writeFile(+ path.join(f.instance.root, "instance.json"),+ 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/);+ await writeFile(+ services,+ `TEAMHUB_LOCAL_IDENTITY_KEY=${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 expect(readLocalIdentity(f.instance)).rejects.toThrow(/private/);+});diff --git a/packages/local-installation/src/account.ts b/packages/local-installation/src/account.tsindex c161f11b..07a05e2b 100644--- a/packages/local-installation/src/account.ts+++ b/packages/local-installation/src/account.ts@@ -2,8 +2,9 @@ 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 { atomicPrivate } from "./private-files.js";+import { atomicPrivate, readPrivate } from "./private-files.js";export function validateLocalCredentials(options: {email?: string;@@ -56,6 +57,42 @@ 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).+export interface LocalIdentity {+ teamhub: string;+ key: Buffer;+}+export async function readLocalIdentity(+ instance: Pick<Instance, "root">,+): Promise<LocalIdentity> {+ const unavailable = () =>+ new Error("Linger on this computer has no server identity yet.");+ const [settings, services] = await Promise.all([+ readPrivate(path.join(instance.root, "instance.json")),+ readPrivate(path.join(instance.root, "services.env")),+ ]);+ if (settings === undefined || services === 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+ )+ throw unavailable();+ return { teamhub: `http://127.0.0.1:${port as number}`, key };+}interface LocalAccount {email: string;password: string;diff --git a/packages/local-installation/src/instance.test.ts b/packages/local-installation/src/instance.test.tsindex 2732e9f9..94de704d 100644--- a/packages/local-installation/src/instance.test.ts+++ b/packages/local-installation/src/instance.test.ts@@ -38,38 +38,48 @@ it("persists stable private settings and credentials across repeated initializat).toBe(0o600);expect((await stat(first.root)).mode & 0o777).toBe(0o700);});-// Without this key TeamHub cannot save a Composio key from the Apps page.-it("gives every instance its own TeamHub secret encryption key", async () => {+// 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) => {const root = await home();const one = await initializeInstance({ name: "one", home: root });const two = await initializeInstance({ name: "two", home: root });- const key = async (instance: Instance) =>- parseEnv(await readFile(path.join(instance.root, "services.env"), "utf8"))- .TEAMHUB_SECRET_ENCRYPTION_KEY;- const first = await key(one);+ const env = async (instance: Instance) =>+ parseEnv(await readFile(path.join(instance.root, "services.env"), "utf8"));+ const first = (await env(one))[name];expect(Buffer.from(first!, "base64")).toHaveLength(32);expect(Buffer.from(first!, "base64").toString("base64")).toBe(first);- expect(await key(two)).not.toBe(first);-});-// Instances installed before the key existed get one on their next install or start.-it("adds a missing TeamHub secret encryption key once and keeps every other credential", async () => {- 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("TEAMHUB_SECRET_ENCRYPTION_KEY="))- .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).TEAMHUB_SECRET_ENCRYPTION_KEY;- 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);+ 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);});+// 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.tsindex 0a918234..6e89ad7b 100644--- a/packages/local-installation/src/instance.ts+++ b/packages/local-installation/src/instance.ts@@ -50,6 +50,9 @@ 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"),};const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));export { atomicPrivate, privateDirectory, readPrivate };diff --git a/packages/local-installation/src/source-checkout.ts b/packages/local-installation/src/source-checkout.tsindex 25bdf54b..2cc56d61 100644--- a/packages/local-installation/src/source-checkout.ts+++ b/packages/local-installation/src/source-checkout.ts@@ -206,6 +206,7 @@ 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.jsonindex 97e83684..8c22d6b8 100644--- a/scripts/env-inventory.json+++ b/scripts/env-inventory.json@@ -133,6 +133,11 @@"owner": "code-default","description": "Where TeamHub calls the LiveKit API when it reaches LiveKit at another address than browsers do. Only the root docker-compose.yml sets it; otherwise TeamHub derives it from LIVEKIT_URL.","names": ["LIVEKIT_API_URL"]+ },+ "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.",+ "names": ["TEAMHUB_LOCAL_IDENTITY_KEY"]}}}