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(desktop): harden one-click sign-in with this computer's account
claude-opus-5-5-medium465c08ebb686
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex da814d5e..e8224864 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -74,15 +74,20 @@ Gateway and runs Agents. The daemon exits with the app.to the server and enrolls this computer, so setup ends on "Linger isready". That screen shows the owner account from the instance'sowner-only `local-account.json` (`setup-account.ts`): the email, the- password masked until Show, Copy (the main process writes the clipboard)- and "Open account file location" (`shell.showItemInFolder`); an unreadable- file shows why instead. 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 offers "Sign in+ password masked until Show, Copy (the main process writes the clipboard+ and clears it after 60 s if it still holds the password) and "Open account+ file location" (`shell.showItemInFolder`); an unreadable file shows why+ instead. Only the email and file are kept; Show and Copy read the file+ again, 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 inwith this computer's account": `localAccount.signIn()` reads the file inthe main process and signs the window's session in with- `signInWithPassword`; the page gets only `{ ok }` or the reason it failed,- never the password. The default AI runtime is the+ `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 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/local-server.test.ts b/apps/desktop/src/main/local-server.test.tsindex 4c44706c..27e9614d 100644--- a/apps/desktop/src/main/local-server.test.ts+++ b/apps/desktop/src/main/local-server.test.ts@@ -30,6 +30,8 @@ import {hasNativePostgres,installLocation,parseSetCookie,+ SignInRejectedError,+ signInFailure,signInWithPassword,type LocalServerOptions,} from "./local-server.js";@@ -1976,9 +1978,10 @@ describe("signInWithPassword", () => {set,fetcher as typeof fetch,);- expect(String((fetcher.mock.calls[0] as unknown[])[0])).toBe(- "http://localhost:3000/v0/auth/login",- );+ 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" });expect(set).toHaveBeenCalledWith(expect.objectContaining({name: "linger_session",@@ -1999,7 +2002,36 @@ describe("signInWithPassword", () => {async () => {},(async () => new Response("{}", { status: 401 })) as typeof fetch,),- ).rejects.toThrow(/401/);+ ).rejects.toEqual(new SignInRejectedError(401));+ });+});++describe("signInFailure", () => {+ it("says what to do by status and error kind, not by message", () => {+ expect(signInFailure(new SignInRejectedError(401))).toBe(+ "The saved password no longer works. Log in with your email and password.",+ );+ const refused = new TypeError("fetch failed", {+ cause: Object.assign(new Error("connect"), { code: "ECONNREFUSED" }),+ });+ expect(signInFailure(refused)).toBe(+ "Linger on this computer is not responding.",+ );+ expect(+ signInFailure(+ new DOMException("The operation timed out", "TimeoutError"),+ ),+ ).toBe("Linger on this computer is not responding.");+ expect(signInFailure(new DOMException("aborted", "AbortError"))).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)",+ );+ expect(signInFailure(new SignInRejectedError(500))).toBe(+ "Signing in to Linger failed (500)",+ );});});@@ -2197,6 +2229,41 @@ describe("LocalServerModule owner account", () => {await f.host.stop("quit");});+ it("does not offer the account while the services are not running", async () => {+ const f = fixture({}, { serverUrl: ORIGIN }, (home) => {+ installed(OWNER)(home);+ writeFileSync(path.join(home, "resume-fails"), "");+ });+ // Not started yet: nothing is serving the window.+ expect(await f.module.servesWindow()).toBe(false);+ await f.host.start();+ await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));+ expect(await f.module.servesWindow()).toBe(false);+ await expect(f.module.signInWithAccount()).rejects.toThrow(+ "This window is not showing the Linger on this computer.",+ );+ expect(f.signIn).not.toHaveBeenCalled();+ await f.host.stop("quit");+ });++ it.each([+ [+ new SignInRejectedError(401),+ "The saved password no longer works. Log in with your email and password.",+ ],+ [+ new TypeError("fetch failed"),+ "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);+ await f.host.start();+ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await expect(f.module.signInWithAccount()).rejects.toThrow(message);+ 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 3f7b6f5d..cc740af1 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -795,9 +795,10 @@ export class LocalServerModule implements Module {this.#opened = undefined;}- // Whether the window shows the Linger this app installed here; only then- // can its owner account sign the window in.+ // 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.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);@@ -822,7 +823,15 @@ export class LocalServerModule implements Module {"This window is not showing the Linger on this computer.",);const account = await this.account();- await this.#options.signIn(record.origin, account.email, account.password);+ try {+ await this.#options.signIn(+ record.origin,+ account.email,+ account.password,+ );+ } catch (error) {+ throw new Error(signInFailure(error), { cause: error });+ }}// Starts the runtime's own login (the installer runs it), or hands it the@@ -2286,8 +2295,43 @@ export async function readLocalAccount(root: string): Promise<LocalAccount> {}}+// A sign-in the local server answered with an error status.+export class SignInRejectedError extends Error {+ readonly status: number;++ constructor(status: number) {+ super(`Signing in to Linger failed (${status})`);+ this.name = "SignInRejectedError";+ this.status = status;+ }+}++// What a person can do about a failed sign-in with this computer's account.+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.+ if (+ error instanceof TypeError ||+ (error instanceof Error &&+ (error.name === "TimeoutError" || error.name === "AbortError"))+ )+ return "Linger on this computer is not responding.";+ 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;+};+// 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.+// 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.export const signInWithPassword = async (origin: string,email: string,@@ -2295,20 +2339,22 @@ export const signInWithPassword = async (setCookie: (cookie: SetCookie) => Promise<void>,fetcher: typeof fetch = fetch,): Promise<void> => {- const response = await fetcher(new URL("/v0/auth/login", origin), {- method: "POST",- headers: {- accept: "application/json",- "content-type": "application/json",- origin,+ 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),},- body: JSON.stringify({ identifier: email, password }),- redirect: "error",- signal: AbortSignal.timeout(30_000),- });+ );await response.body?.cancel();- if (!response.ok)- throw new Error(`Signing in to Linger failed (${response.status})`);+ if (!response.ok) throw new SignInRejectedError(response.status);const cookies = response.headers.getSetCookie().map(parseSetCookie)diff --git a/apps/desktop/src/main/setup-account.test.ts b/apps/desktop/src/main/setup-account.test.tsindex a910d349..22ba047d 100644--- a/apps/desktop/src/main/setup-account.test.ts+++ b/apps/desktop/src/main/setup-account.test.ts@@ -1,6 +1,6 @@-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";-import { SetupAccount } from "./setup-account.js";+import { CLIPBOARD_CLEAR_MS, SetupAccount } from "./setup-account.js";const ACCOUNT = {email: "[email protected]",@@ -9,54 +9,126 @@ const ACCOUNT = {};const setupAccount = (read = vi.fn(async () => ACCOUNT)) => {- const copy = vi.fn();+ let text = "";+ const clipboard = {+ writeText: vi.fn(async (value: string) => {+ text = value;+ }),+ readText: vi.fn(async () => text),+ clear: vi.fn(() => {+ text = "";+ }),+ };const showFile = vi.fn();return {- account: new SetupAccount({ read, copy, showFile }),- copy,+ account: new SetupAccount({ read, clipboard, showFile }),+ clipboard,showFile,+ read,};};+afterEach(() => {+ vi.useRealTimers();+});+describe("SetupAccount", () => {it("shows the email and keeps the password back until asked", async () => {const { account } = setupAccount();expect(account.view()).toBeUndefined();await account.refresh();expect(account.view()).toEqual({ email: ACCOUNT.email });- account.show(true);+ await account.show(true);expect(account.view()).toEqual({email: ACCOUNT.email,password: ACCOUNT.password,});- account.show(false);+ await account.show(false);+ expect(account.view()).toEqual({ email: ACCOUNT.email });+ });++ it("reads the password from the file when it is shown or copied", async () => {+ const { account, clipboard, read } = setupAccount();+ await account.refresh();+ const changed = { ...ACCOUNT, password: "a-new-password" };+ read.mockResolvedValue(changed);+ await account.show(true);+ expect(account.view()).toEqual({+ email: ACCOUNT.email,+ password: changed.password,+ });+ await account.copy();+ expect(clipboard.writeText).toHaveBeenCalledWith(changed.password);+ expect(read).toHaveBeenCalledTimes(3);+ });++ it("hides the password again when the setup window closes", async () => {+ const { account } = setupAccount();+ await account.refresh();+ await account.show(true);+ account.hide();+ expect(account.view()).toEqual({ email: ACCOUNT.email });+ await account.refresh();expect(account.view()).toEqual({ email: ACCOUNT.email });});it("copies the password and reveals the file without the page", async () => {- const { account, copy, showFile } = setupAccount();+ const { account, clipboard, showFile } = setupAccount();await account.refresh();- account.copy();+ await account.copy();account.reveal();- expect(copy).toHaveBeenCalledWith(ACCOUNT.password);+ expect(clipboard.writeText).toHaveBeenCalledWith(ACCOUNT.password);expect(showFile).toHaveBeenCalledWith(ACCOUNT.file);expect(account.view()).not.toHaveProperty("password");});+ it("clears the copied password after a minute", async () => {+ vi.useFakeTimers();+ const { account, clipboard } = setupAccount();+ await account.copy();+ await vi.advanceTimersByTimeAsync(CLIPBOARD_CLEAR_MS - 1);+ expect(clipboard.clear).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(clipboard.clear).toHaveBeenCalledOnce();+ expect(await clipboard.readText()).toBe("");+ });++ it("leaves the clipboard alone once something else was copied", async () => {+ vi.useFakeTimers();+ const { account, clipboard } = setupAccount();+ await account.copy();+ await clipboard.writeText("something else");+ await vi.advanceTimersByTimeAsync(CLIPBOARD_CLEAR_MS);+ expect(clipboard.clear).not.toHaveBeenCalled();+ expect(await clipboard.readText()).toBe("something else");+ });++ it("counts the minute from the latest copy", async () => {+ vi.useFakeTimers();+ const { account, clipboard } = setupAccount();+ await account.copy();+ await vi.advanceTimersByTimeAsync(CLIPBOARD_CLEAR_MS / 2);+ await account.copy();+ await vi.advanceTimersByTimeAsync(CLIPBOARD_CLEAR_MS / 2);+ expect(clipboard.clear).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(CLIPBOARD_CLEAR_MS / 2);+ expect(clipboard.clear).toHaveBeenCalledOnce();+ });+it("says why the file could not be read and offers nothing else", async () => {- const { account, copy, showFile } = setupAccount(+ const { account, clipboard, showFile } = setupAccount(vi.fn(async () => {throw new Error("The local account file must be private");}),);await account.refresh();- account.show(true);- account.copy();+ await account.show(true);+ await account.copy();account.reveal();expect(account.view()).toEqual({error: "The local account file must be private",});- expect(copy).not.toHaveBeenCalled();+ expect(clipboard.writeText).not.toHaveBeenCalled();expect(showFile).not.toHaveBeenCalled();});@@ -64,7 +136,7 @@ describe("SetupAccount", () => {const read = vi.fn(async () => ACCOUNT);const { account } = setupAccount(read);await account.refresh();- account.show(true);+ await account.show(true);read.mockRejectedValueOnce(new Error("gone"));await account.refresh();read.mockResolvedValueOnce(ACCOUNT);diff --git a/apps/desktop/src/main/setup-account.ts b/apps/desktop/src/main/setup-account.tsindex ea5d5ec8..9666a760 100644--- a/apps/desktop/src/main/setup-account.ts+++ b/apps/desktop/src/main/setup-account.ts@@ -1,34 +1,38 @@import type { SetupLocalAccount } from "../shared/setup.js";import type { LocalAccount } from "./local-server.js";+// How long a copied password may stay on the clipboard.+export const CLIPBOARD_CLEAR_MS = 60_000;+export interface SetupAccountOptions {// Reads the installation's local-account.json.readonly read: () => Promise<LocalAccount>;- readonly copy: (text: string) => void;+ readonly clipboard: {+ writeText(text: string): Promise<void>;+ readText(): Promise<string>;+ clear(): void;+ };readonly showFile: (file: string) => void;}-// The owner account the setup page shows once Linger is installed. The page-// gets the password only while the person chose to show it; copying and-// revealing the file happen here.+type Cached = Pick<LocalAccount, "email" | "file"> | { readonly error: string };++// The owner account the setup page shows once Linger is installed. Only the+// email and the file are kept; the password is read from the file when the+// person shows or copies it, and is held only while it is shown.export class SetupAccount {readonly #options: SetupAccountOptions;- #account: LocalAccount | { readonly error: string } | undefined;- #shown = false;+ #account: Cached | undefined;+ #shown: string | undefined;+ #clear: ReturnType<typeof setTimeout> | undefined;constructor(options: SetupAccountOptions) {this.#options = options;}async refresh(): Promise<void> {- try {- this.#account = await this.#options.read();- } catch (error) {- this.#account = {- error: error instanceof Error ? error.message : String(error),- };- this.#shown = false;- }+ const account = await this.#read();+ if (this.#shown !== undefined) this.#shown = account?.password;}view(): SetupLocalAccount | undefined {@@ -36,26 +40,54 @@ export class SetupAccount {if (!account || "error" in account) return account;return {email: account.email,- ...(this.#shown ? { password: account.password } : {}),+ ...(this.#shown !== undefined ? { password: this.#shown } : {}),};}- show(on: boolean): void {- this.#shown = on && this.#readable() !== undefined;+ async show(on: boolean): Promise<void> {+ this.#shown = on ? (await this.#read())?.password : undefined;}- copy(): void {- const account = this.#readable();- if (account) this.#options.copy(account.password);+ // The setup window closed: whatever was shown is hidden again.+ hide(): void {+ this.#shown = undefined;}- reveal(): void {- const account = this.#readable();- if (account) this.#options.showFile(account.file);+ async copy(): Promise<void> {+ const password = (await this.#read())?.password;+ if (password === undefined) return;+ const clipboard = this.#options.clipboard;+ await clipboard.writeText(password);+ clearTimeout(this.#clear);+ this.#clear = setTimeout(() => {+ this.#clear = undefined;+ // Something copied since is left alone.+ void clipboard+ .readText()+ .then((text) => {+ if (text === password) clipboard.clear();+ })+ .catch(() => undefined);+ }, CLIPBOARD_CLEAR_MS);+ this.#clear.unref?.();}- #readable(): LocalAccount | undefined {+ reveal(): void {const account = this.#account;- return account && !("error" in account) ? account : undefined;+ if (account && !("error" in account)) this.#options.showFile(account.file);+ }++ async #read(): Promise<LocalAccount | undefined> {+ try {+ const account = await this.#options.read();+ this.#account = { email: account.email, file: account.file };+ return account;+ } catch (error) {+ this.#account = {+ error: error instanceof Error ? error.message : String(error),+ };+ this.#shown = undefined;+ return undefined;+ }}}diff --git a/apps/desktop/src/main/setup-window.ts b/apps/desktop/src/main/setup-window.tsindex 53074925..5382cc64 100644--- a/apps/desktop/src/main/setup-window.ts+++ b/apps/desktop/src/main/setup-window.ts@@ -90,7 +90,7 @@ export class SetupWindowModule implements Module {const local = ctx.get<LocalServerModule>("LocalServer");this.#account = new SetupAccount({read: () => local.account(),- copy: (text) => clipboard.writeText(text),+ clipboard,showFile: (file) => shell.showItemInFolder(file),});const pages = this.#session();@@ -193,6 +193,7 @@ export class SetupWindowModule implements Module {);window.on("closed", () => {if (this.#window === window) this.#window = undefined;+ this.#account?.hide();});this.#window = window;void window.loadURL(SETUP_URL).catch(() => undefined);@@ -252,10 +253,10 @@ export class SetupWindowModule implements Module {.switchRuntime(command.runtime);return;case "local.account.show":- this.#account?.show(command.on);+ await this.#account?.show(command.on);return;case "local.account.copy":- this.#account?.copy();+ await this.#account?.copy();return;case "local.account.reveal":this.#account?.reveal();