Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion apps/desktop/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,22 @@ Gateway and runs Agents. The daemon exits with the app.
ComputerDaemon, Status, PowerGuard, WindowManager, Tray, DesktopIpc). `status.ts`, `tray-menu.ts` and `tray-icon.ts` hold the pure
status summary, tray menu and tray icons, drawn from the logo PNGs in
`resources/tray/` with a status badge.
- `src/main/enrollment.ts`: Enrollment. Every enrollment names this
machine's Daemon ID, read from the public key in
`<userData>/computer/state/daemon-identity.json`, which outlives
unenrolling, when the server's `/v0/me` lists the
`local_computer_enrollment_daemon_id` server capability; a TeamHub older
than the desktop omits it and gets the request without `daemon_id`, which
it would reject. TeamHub then renews the signed-in owner's Computer that holds
that Daemon Identity, with its Agents, instead of pairing a new one, and
removes the Computer the request named if it never connected and has no
Agents (the orphan an earlier Set Up Again left). Another account's
Computer holding it refuses with `DAEMON_IDENTITY_IN_USE`, shown as "This
computer is connected to another Linger account". The config keeps the
Daemon ID the enrollment named; at start an enrollment that named none or
another one is renewed once the server lists the capability, which heals a
computer stuck behind its own Daemon Identity. The Runner Gateway closes a Computer whose Daemon Identity
another Computer holds with 1008 `daemon_identity_in_use:`.
- `src/main/local-server.ts`: LocalServer, the setup page's Quick Install
path. It fetches the pinned Node runtime and unpacks the linger source package
into the install location (the default home, or a folder picked under
Expand Down Expand Up @@ -190,7 +206,8 @@ Gateway and runs Agents. The daemon exits with the app.
finishes it, reusing a finished job only while its origin answers (a stopped
server gets a new job, which starts the services again). The start failure
page's Set Up Again forgets the record, unenrolls the computer, clears the
server address and shows setup; the instance and its data stay. Before installing or resuming it moves the
server address and shows setup; the instance and its data stay, and the
next enrollment gets the same Computer back (see `src/main/enrollment.ts`). Before installing or resuming it moves the
`COMPOSIO_API_KEY`, `SONIOX_API_KEY`, `XAI_API_KEY` and `TZ` of an unpacked
source package's `.env` into `<home>/instances/desktop/user.env` once and
deletes that `.env` (never a `LINGER_CHECKOUT`'s), logging only the names
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src/main/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ const desktopConfig = z.object({
computerId: z.string().optional(),
tenantId: z.string().optional(),
ownerActorId: z.string().optional(),
// The Daemon ID this computer's enrollment named; an enrollment that named
// none or another one is renewed at start.
daemonId: z.string().optional(),
workspaceGrants: z.array(workspaceGrant).default([]),
// Always-on mode: keep the system awake even when idle.
preventSleep: z.boolean().default(false),
Expand Down
226 changes: 222 additions & 4 deletions apps/desktop/src/main/enrollment.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import { createHash } from "node:crypto";
import { writeFileSync } from "node:fs";
import path from "node:path";

import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";

import { EnrollmentError, enrollComputer } from "./enrollment.js";
import { CredentialStore } from "./computer-credential.js";
import type { DesktopConfig } from "./config.js";
import {
EnrollmentError,
EnrollmentModule,
enrollComputer,
readDaemonId,
} from "./enrollment.js";
import { stubModule, tempDirectory, testHost } from "./test-support.js";

const claims = (value: object): string =>
Buffer.from(JSON.stringify(value)).toString("base64url");
Expand All @@ -19,7 +29,13 @@ interface Call {
}

const fakeServer = (
overrides: { exchangeStatus?: number; bundle?: Record<string, unknown> } = {},
overrides: {
capabilities?: readonly string[];
createStatus?: number;
createError?: string;
exchangeStatus?: number;
bundle?: Record<string, unknown>;
} = {},
): { fetch: typeof fetch; calls: Call[] } => {
const calls: Call[] = [];
let challenge = "";
Expand All @@ -37,8 +53,24 @@ const fakeServer = (
const json = (value: unknown, status = 200): Response =>
new Response(JSON.stringify(value), { status });
if (input.pathname === "/v0/me")
return json({ actors: [{ kind: "human", tenant_id: "tenant_acme" }] });
return json({
actors: [{ kind: "human", tenant_id: "tenant_acme" }],
...(overrides.capabilities
? { server_capabilities: overrides.capabilities }
: {}),
});
if (input.pathname.endsWith("/local-computer-enrollments")) {
if (overrides.createStatus)
return json(
{
error: {
code: overrides.createError ?? "INTERNAL_ERROR",
message: "Refused",
request_id: "request_1",
},
},
overrides.createStatus,
);
challenge = String(body?.code_challenge);
return json({
enrollment_id: "enr_1",
Expand Down Expand Up @@ -134,6 +166,44 @@ describe("enrollComputer", () => {
).rejects.toMatchObject({ code: "INVALID_RESPONSE" });
});

it("names the machine's Daemon so TeamHub can renew the Computer it holds", async () => {
const server = fakeServer({ capabilities: DAEMON_CAPABLE });
const enrolled = await enrollComputer({
...input,
daemonId: DAEMON_ID,
fetch: server.fetch,
});
expect(server.calls[1]?.body).toMatchObject({ daemon_id: DAEMON_ID });
expect(enrolled.daemonId).toBe(DAEMON_ID);
});

it("enrolls without the Daemon on a server that does not accept it", async () => {
// A team server older than the desktop rejects fields it does not know.
const server = fakeServer({ capabilities: [] });
const enrolled = await enrollComputer({
...input,
daemonId: DAEMON_ID,
fetch: server.fetch,
});
expect(server.calls[1]?.body).not.toHaveProperty("daemon_id");
expect(enrolled).toMatchObject({ computerId: "computer_1" });
expect(enrolled.daemonId).toBeUndefined();
});

it("reports a Daemon another account's Computer holds", async () => {
const failure = await enrollComputer({
...input,
daemonId: DAEMON_ID,
fetch: fakeServer({
capabilities: DAEMON_CAPABLE,
createStatus: 409,
createError: "DAEMON_IDENTITY_IN_USE",
}).fetch,
}).catch((error: unknown) => error);
expect(failure).toBeInstanceOf(EnrollmentError);
expect(failure).toMatchObject({ code: "DAEMON_IDENTITY_IN_USE" });
});

it("reports a removed enrollment", async () => {
const failure = await enrollComputer({
...input,
Expand All @@ -158,3 +228,151 @@ describe("enrollComputer", () => {
).rejects.toMatchObject({ code: "INVALID_RESPONSE" });
});
});

// The daemon keeps its identity key (public and private) here; the Daemon ID
// is the SHA-256 of the raw public key, as the daemon derives it.
const PUBLIC_KEY = Buffer.alloc(32, 7);
const DAEMON_CAPABLE = ["local_computer_enrollment_daemon_id"];
const DAEMON_ID = createHash("sha256").update(PUBLIC_KEY).digest("base64url");

const daemonIdentityFile = (): string => {
const file = path.join(tempDirectory(), "daemon-identity.json");
writeFileSync(
file,
JSON.stringify({
public_key: PUBLIC_KEY.toString("base64").replace(/=+$/, ""),
private_key: Buffer.alloc(64, 9).toString("base64").replace(/=+$/, ""),
}),
);
return file;
};

const startEnrollment = async (
config: Partial<DesktopConfig>,
options: {
credentialFor?: string;
capabilities?: readonly string[];
} = {},
) => {
const server = fakeServer({
capabilities: options.capabilities ?? DAEMON_CAPABLE,
});
const credentials = new CredentialStore(
path.join(tempDirectory(), "credential.json"),
);
if (options.credentialFor)
credentials.write({
computerId: options.credentialFor,
gatewayUrl: "wss://linger.example.com/v1/runner",
token: TOKEN,
});
const module = new EnrollmentModule({
sessionCookie: async () => "teamhub_session=abc",
defaultDisplayName: "Laptop",
credentials,
daemonIdentityFile: daemonIdentityFile(),
fetch: server.fetch,
});
const host = testHost([stubModule("Config"), module], {
serverUrl: "https://linger.example.com",
...config,
});
await host.start();
return { host, module, server };
};

describe("readDaemonId", () => {
it("derives the Daemon ID from the stored public key", () => {
expect(readDaemonId(daemonIdentityFile())).toBe(DAEMON_ID);
});

it("has none before the daemon first ran", () => {
expect(
readDaemonId(path.join(tempDirectory(), "daemon-identity.json")),
).toBeUndefined();
});
});

describe("EnrollmentModule", () => {
it("pairs the Computer the daemon holds after Set Up Again forgot it", async () => {
const { host, module, server } = await startEnrollment({});
await module.enroll();
const create = server.calls.find((call) =>
call.url.endsWith("/local-computer-enrollments"),
);
expect(create?.body).toMatchObject({ daemon_id: DAEMON_ID });
expect(create?.body).not.toHaveProperty("computer_id");
expect(host.ctx.config.get()).toMatchObject({
computerId: "computer_1",
daemonId: DAEMON_ID,
});
});

it("renews once an enrollment made without the daemon's identity", async () => {
// Set Up Again in an earlier release paired the orphan computer_9 while
// the daemon's identity stayed with computer_1.
const { host, server } = await startEnrollment(
{
computerId: "computer_9",
tenantId: "tenant_acme",
ownerActorId: "actor_ann",
},
{ credentialFor: "computer_9" },
);
await vi.waitFor(() =>
expect(host.ctx.config.get().computerId).toBe("computer_1"),
);
expect(
server.calls.find((call) =>
call.url.endsWith("/local-computer-enrollments"),
)?.body,
).toMatchObject({ computer_id: "computer_9", daemon_id: DAEMON_ID });
expect(host.ctx.config.get().daemonId).toBe(DAEMON_ID);
});

it("enrolls without the daemon's identity on a server that does not accept it", async () => {
const { host, module, server } = await startEnrollment(
{},
{ capabilities: [] },
);
await module.enroll();
expect(
server.calls.find((call) =>
call.url.endsWith("/local-computer-enrollments"),
)?.body,
).not.toHaveProperty("daemon_id");
expect(host.ctx.config.get()).toMatchObject({ computerId: "computer_1" });
expect(host.ctx.config.get().daemonId).toBeUndefined();
});

it("does not renew at start only to name the daemon to a server that cannot take it", async () => {
const { host, server } = await startEnrollment(
{
computerId: "computer_9",
tenantId: "tenant_acme",
ownerActorId: "actor_ann",
},
{ credentialFor: "computer_9", capabilities: [] },
);
await vi.waitFor(() =>
expect(server.calls.map((call) => call.url)).toEqual(["/v0/me"]),
);
await new Promise((resolve) => setTimeout(resolve, 20));
expect(server.calls.map((call) => call.url)).toEqual(["/v0/me"]);
expect(host.ctx.config.get().computerId).toBe("computer_9");
});

it("does not renew an enrollment made with the daemon's identity", async () => {
const { server } = await startEnrollment(
{
computerId: "computer_1",
tenantId: "tenant_acme",
ownerActorId: "actor_ann",
daemonId: DAEMON_ID,
},
{ credentialFor: "computer_1" },
);
await new Promise((resolve) => setTimeout(resolve, 20));
expect(server.calls).toEqual([]);
});
});
Loading
Loading