A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
fix(vps): never read, resolve, or write engine files as root
Alan Buscaglia162473c54c8d
diff --git a/docs/deploy-vps.md b/docs/deploy-vps.mdindex a483c82..0c939e2 100644--- a/docs/deploy-vps.md+++ b/docs/deploy-vps.md@@ -33,7 +33,9 @@ The image runs in server mode (`GENTLE_DOT_VPS=1`). The assistant has a shell, s| Daemon (`node …/cli.ts`) | `root` in the container, with only the capabilities below | Everything in the volume || Agent, its tools and shell, its subagents, and its memory server | `dot` | Its own folders: `agent`, `home`, `workspace`, `sessions`, `gentle-ai` under `/home/dot/.gentle-dot`, and `/home/dot/.engram` || Connector servers the daemon starts (stdio, for example Discord) | `dotmcp` | Only its own home and working folder, `/home/dot/.gentle-dot/connector-home` |+| Sign-in helper (the daemon's own entry point with `--auth-helper`) | `dot` | The agent's sign-ins: `auth.json`, `models.json`, `settings.json` |+- The daemon never opens the agent's files as `root`. Account sign-in runs in a helper started as `dot`, because a stored key may be a command (`!…`) or a variable (`$…`) that the sign-in code resolves; whatever it runs, it runs as `dot`. Everything else the daemon reads or writes in the agent's folders (settings, profiles, `mcp.json`, history, uploads, the workspace's memory setting) it does with `dot` as its effective user, so a link the agent planted there leads nowhere `dot` could not reach anyway, and what it creates belongs to `dot`.- The data folder `/home/dot/.gentle-dot` is `root`'s with mode `0711`: the agent can reach its own folders by name but cannot list the folder or read the access key (`token`), `connectors.json`, the encrypted secrets (`secrets.enc.json`), or the PIN hash (`web-pin.json`), all `root`'s with mode `0600`. The daemon's code in `/app` is `root`'s and read-only for everyone else.- Connector servers run as `dotmcp`, with their own home and working folder in `connector-home`, so they cannot see the agent's workspace: a server that works on files there (for example a filesystem MCP server pointed at the workspace) does not work on a server. The agent cannot read their environment, where their token is.- Connector secrets (sign-ins, bot tokens, client secrets) are encrypted at rest with AES-256-GCM, each with its own nonce, under `GENTLE_DOT_SECRETS_KEY` (step 3). Only the daemon's environment holds it: it is never written to the volume and never passed to the agent or a connector server. Without it, connectors that need a secret stay off and say why. Secrets an older version kept in plain files move into the encrypted file once, at the first start with the key. Anyone who opens a shell in the container (`docker compose exec`) also gets it in their environment, as with every variable from `.env`.diff --git a/docs/design.md b/docs/design.mdindex 206e638..d459bce 100644--- a/docs/design.md+++ b/docs/design.md@@ -288,7 +288,7 @@ The user changes the main assistant's model from the chat, in the panel and the- The daemon binds `127.0.0.1` only. A random 256-bit token is stored in `~/.gentle-dot/token` (mode 0600). The desktop app reads it; the browser receives it once by URL fragment.- WebSocket upgrades check `Origin` against an allowlist (`http://127.0.0.1:4317`, `tauri://localhost`).- The VPS guide requires HTTPS, a reverse proxy with authentication, and a dedicated Docker container with no access to personal machines.-- Server mode (S25.8, `GENTLE_DOT_VPS=1`, set only by the container image; `daemon/src/vps.ts`): the daemon runs as root in the container with only `SETUID`, `SETGID`, `CHOWN`, `FOWNER`, `DAC_OVERRIDE`, and `KILL` and `no-new-privileges`, and refuses server mode otherwise. It starts the engine as `dot` (`spawn` `uid`/`gid`; its tools, shell, subagents, and memory server inherit it) and its stdio connector servers as `dotmcp` through `setpriv` (no groups, no capabilities), with their own home and working folder in `<data>/connector-home`, so they cannot see the engine's workspace. The data folder is the daemon's (0711); the token, `connectors.json`, the secrets, and the PIN hash are the daemon's (0600); the engine's folders (`agent`, `home`, `workspace`, `sessions`, `gentle-ai`) are `dot`'s, and what the daemon writes there is handed over with `chown -R -P --from=0:0` (no links followed, only the daemon's own files). Without the app, connector secrets live in `<data>/secrets.enc.json`, AES-256-GCM per record (random nonce, the id as additional data) under `GENTLE_DOT_SECRETS_KEY`, which only the daemon's environment holds (removed from `process.env` at start and from every child's environment); without it, connectors that need a secret fail closed and say why; with it, secrets older files still hold move there once (`migrate`). Privileged actions from the web page need a PIN instead of the app: `pin_set` (once; a salted scrypt hash in `<data>/web-pin.json`), `pin_command {pin, command}` for a connector change (the PIN is its confirmation), and `pin_approve {requestId, pin}` for an approval shown as an ask with `method: "pin"` and the full preview (`ui_response confirmed:false` declines without it); 5 wrong tries in a row lock it for 15 minutes, persisted. With the app's channel nothing changes: the WebSocket gets `app_required`, also for the PIN messages, and secrets stay in the app's store.+- Server mode (S25.8, `GENTLE_DOT_VPS=1`, set only by the container image; `daemon/src/vps.ts`): the daemon runs as root in the container with only `SETUID`, `SETGID`, `CHOWN`, `FOWNER`, `DAC_OVERRIDE`, and `KILL` and `no-new-privileges`, and refuses server mode otherwise. It starts the engine as `dot` (`spawn` `uid`/`gid`; its tools, shell, subagents, and memory server inherit it) and its stdio connector servers as `dotmcp` through `setpriv` (no groups, no capabilities), with their own home and working folder in `<data>/connector-home`, so they cannot see the engine's workspace. The data folder is the daemon's (0711); the token, `connectors.json`, the secrets, and the PIN hash are the daemon's (0600); the engine's folders (`agent`, `home`, `workspace`, `sessions`, `gentle-ai`) are `dot`'s. The daemon never acts on them as root (B1): Pi's ModelRuntime (sign-in, providers, the voice key), which runs a `!command` value and expands `$NAME`, lives in a helper started as `dot` (`cli.ts --auth-helper`, `auth-helper.ts`, Node IPC, plain data back); every other read, write, mkdir, chmod, or removal there (profiles and `settings.json`, `mcp.json` and the subagents' guard, the workspace's `.pi` and `.engram`, history and rotation, uploads and the images read for a prompt, the engine's old `mcp-auth.json`) runs in a synchronous `engineAccess` bracket (`engine-access.ts`: `setgroups`, `setegid`, `seteuid` to `dot`, then back to root, or the daemon stops), so the kernel resolves every link with `dot`'s rights and what is made there is `dot`'s. The bracket never starts a process, and the daemon does no asynchronous file work (the ids change on every thread; a test checks the imports, and uploads open their file in the bracket and stream to the open descriptor); the daemon's own files go through `writePrivateFile` (exclusive temporary file, owner checked, refused inside a bracket). Files an older version left as root there are handed over once at start with `chown -R -P --from=0:0`. The root-only checks run in the image (`packages/daemon/test/vps-root.test.ts` with `GENTLE_DOT_TEST_ENGINE_USER=dot GENTLE_DOT_TEST_CONNECTOR_USER=dotmcp`). Without the app, connector secrets live in `<data>/secrets.enc.json`, AES-256-GCM per record (random nonce, the id as additional data) under `GENTLE_DOT_SECRETS_KEY`, which only the daemon's environment holds (removed from `process.env` at start and from every child's environment); without it, connectors that need a secret fail closed and say why; with it, secrets older files still hold move there once (`migrate`). Privileged actions from the web page need a PIN instead of the app: `pin_set` (once; a salted scrypt hash in `<data>/web-pin.json`), `pin_command {pin, command}` for a connector change (the PIN is its confirmation), and `pin_approve {requestId, pin}` for an approval shown as an ask with `method: "pin"` and the full preview (`ui_response confirmed:false` declines without it); 5 wrong tries in a row lock it for 15 minutes, persisted. With the app's channel nothing changes: the WebSocket gets `app_required`, also for the PIN messages, and secrets stay in the app's store.- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Connector changes and approvals come only from the desktop app that launched the daemon, over its private channel, and are answered in native dialogs (§4, App channel); the WebSocket's access key no longer reaches them. Connector secrets (tokens, client secrets, imported headers, sign-ins) are in Keychain items the signed app creates and reach the daemon only in memory over that channel (S25.5, §4 Secrets); without the app, connectors that need one fail closed. What the Keychain cannot check: `security-framework` exposes no item access list, so the app cannot tell an item it created from one a same-user process planted (before the first `put`, or after deleting the app's); the daemon only reads ids it recorded, and every `put` replaces the item. `connectors.json` is signed with a key in the Keychain, and a file changed while Gentle Dot was closed is set aside at the next start with the app (S25.6, §4 Integrity); without the app it is loaded unverified. On Linux the app keeps connector secrets in the Secret Service (GNOME Keyring or KWallet), encrypted at rest; the Secret Service has no per-caller access list, so any same-user process, the agent's shell included, can read the items while the keyring is unlocked (S25.7, documented limit). The app channel, the MCP proxy, and native approvals work as on macOS: no child of the daemon holds the channel (checked in containers by `scripts/package/linux-cargo-check.mjs` and the package smoke). Without a Secret Service at start, the connectors' integrity key cannot be read, so connectors that need a secret stay locked until Gentle Dot restarts (`daemon.log` names the missing keyring; the assistant is told to restart); if the keyring goes away later, the assistant and `daemon.log` (`connector <id> cannot get its secrets: …`) name it. Only the Linux keyring message is passed on this way; other store refusals keep their earlier wording. Still open: the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.## 9. Desktop shell contract (Tauri 2 <-> UI)diff --git a/packages/daemon/src/auth-helper.ts b/packages/daemon/src/auth-helper.tsnew file mode 100644index 0000000..1016aa1--- /dev/null+++ b/packages/daemon/src/auth-helper.ts@@ -0,0 +1,308 @@+/**+ * Sign-in in server mode (S25.8, B1). Pi's ModelRuntime reads the engine's `auth.json`,+ * `models.json`, and `settings.json`, runs a value that starts with `!` as a shell command, and+ * expands `$NAME` from its environment. Those files belong to the engine's user, so the root daemon+ * never runs ModelRuntime itself: it starts this helper as the engine's user (the same user, groups,+ * environment, and working folder as the engine, with no capabilities), and asks it over Node's IPC+ * channel. Whatever a planted value runs, it runs as the engine's user. Every answer is plain data:+ * provider names and statuses, an OpenAI key for voice, and the sign-in's prompts and events.+ *+ * Daemon -> helper: `{kind:"call", id, method, params}`, `{kind:"answer", promptId, value|error}`,+ * `{kind:"abort", id}`. Helper -> daemon: `{kind:"result", id, result|error}`,+ * `{kind:"prompt", id, promptId, request}`, `{kind:"notify", id, event}`.+ * The desktop keeps ModelRuntime in the daemon (`createModelAuthRuntime`), as before.+ */+import { type ChildProcess, spawn } from "node:child_process";+import type { AuthMethod } from "@gentle-dot/protocol";+import { type AuthInteraction, type AuthRuntime, createModelAuthRuntime } from "./auth.ts";+import type { OsUser } from "./vps.ts";++/** The helper's command line: the daemon's own entry point with `--auth-helper`. */+export interface AuthHelperCommand {+ command: string;+ args: string[];+}++export interface AuthHelperOptions extends AuthHelperCommand {+ user: OsUser;+ /** The engine's environment (already without the daemon's secrets). */+ env: NodeJS.ProcessEnv;+ /** The engine's home (`auth.json`, `models.json`, `settings.json`) and working folder. */+ agentHome: string;+ cwd: string;+ log?: (line: string) => void;+}++type Provider = ReturnType<AuthRuntime["getProviders"]>[number];+type Status = ReturnType<AuthRuntime["getProviderAuthStatus"]>;+type Snapshot = { providers: Provider[]; status: Record<string, Status> };++type FromHelper =+ | { kind: "result"; id: number; result?: unknown; error?: string }+ | { kind: "prompt"; id: number; promptId: number; request: Parameters<AuthInteraction["prompt"]>[0] }+ | { kind: "notify"; id: number; event: Parameters<AuthInteraction["notify"]>[0] };++type ToHelper =+ | { kind: "call"; id: number; method: string; params?: Record<string, unknown> }+ | { kind: "answer"; promptId: number; value?: string; error?: string }+ | { kind: "abort"; id: number };++const CALL_TIMEOUT_MS = 60_000;+const HOME_VAR = "GENTLE_DOT_AUTH_HOME";+const CWD_VAR = "GENTLE_DOT_AUTH_CWD";++const isString = (value: unknown): value is string => typeof value === "string";+const named = (value: unknown) =>+ typeof value === "object" && value !== null && isString((value as { name?: unknown }).name)+ ? { name: (value as { name: string }).name }+ : undefined;++/** The helper's answer to `snapshot`, kept only where it has the expected shape. */+function parseSnapshot(value: unknown): Snapshot {+ const raw = (typeof value === "object" && value !== null ? value : {}) as {+ providers?: unknown;+ status?: unknown;+ };+ const providers: Provider[] = [];+ for (const item of Array.isArray(raw.providers) ? raw.providers : []) {+ const p = item as { id?: unknown; name?: unknown; auth?: { apiKey?: unknown; oauth?: unknown } };+ if (!isString(p.id) || !isString(p.name)) continue;+ const apiKey = named(p.auth?.apiKey);+ const oauth = named(p.auth?.oauth);+ providers.push({+ id: p.id,+ name: p.name,+ auth: { ...(apiKey ? { apiKey } : {}), ...(oauth ? { oauth } : {}) },+ });+ }+ const status: Record<string, Status> = {};+ const given = (typeof raw.status === "object" && raw.status !== null ? raw.status : {}) as Record<+ string,+ unknown+ >;+ for (const { id } of providers) {+ const s = given[id] as { configured?: unknown; source?: unknown } | undefined;+ status[id] = { configured: s?.configured === true, ...(isString(s?.source) ? { source: s.source } : {}) };+ }+ return { providers, status };+}++/** The daemon's side: one helper, started on first use and again after it exits. */+export class AuthHelper {+ private child: ChildProcess | undefined;+ private nextId = 0;+ private readonly calls = new Map<+ number,+ { resolve(value: unknown): void; reject(error: Error): void; interaction?: AuthInteraction }+ >();+ private readonly options: AuthHelperOptions;++ constructor(options: AuthHelperOptions) {+ this.options = options;+ }++ /** A runtime over a fresh snapshot, as `createModelAuthRuntime` gives a fresh runtime. */+ async runtime(): Promise<AuthRuntime> {+ const { providers, status } = parseSnapshot(await this.call("snapshot"));+ return {+ getProviders: () => providers,+ getProviderAuthStatus: (providerId) => status[providerId] ?? { configured: false },+ login: async (providerId: string, type: AuthMethod, interaction: AuthInteraction) => {+ await this.call("login", { providerId, type }, interaction);+ },+ logout: async (providerId) => {+ await this.call("logout", { providerId });+ },+ openAIApiKey: async () => {+ const result = (await this.call("openAIApiKey")) as { key?: unknown } | undefined;+ return isString(result?.key) && result.key !== "" ? result.key : undefined;+ },+ };+ }++ close(): void {+ const child = this.child;+ this.child = undefined;+ this.failAll(new Error("The sign-in helper stopped."));+ child?.kill("SIGTERM");+ }++ private call(+ method: string,+ params?: Record<string, unknown>,+ interaction?: AuthInteraction,+ ): Promise<unknown> {+ const id = ++this.nextId;+ return new Promise((resolve, reject) => {+ let timer: NodeJS.Timeout | undefined;+ const done = (settle: () => void) => {+ clearTimeout(timer);+ this.calls.delete(id);+ settle();+ };+ this.calls.set(id, {+ resolve: (value) => done(() => resolve(value)),+ reject: (error) => done(() => reject(error)),+ ...(interaction ? { interaction } : {}),+ });+ // A sign-in waits for the user; it ends when they answer or cancel.+ if (!interaction)+ timer = setTimeout(+ () => this.calls.get(id)?.reject(new Error(`The sign-in helper did not answer ${method} in time.`)),+ CALL_TIMEOUT_MS,+ );+ if (interaction?.signal) {+ const abort = () => this.send({ kind: "abort", id });+ if (interaction.signal.aborted) abort();+ else interaction.signal.addEventListener("abort", abort, { once: true });+ }+ this.send({ kind: "call", id, method, ...(params ? { params } : {}) });+ });+ }++ private send(message: ToHelper): void {+ try {+ const child = this.ensureChild();+ if (!child.connected) throw new Error("The sign-in helper is not running.");+ child.send(message);+ } catch (error) {+ if (message.kind === "call") this.calls.get(message.id)?.reject(error as Error);+ }+ }++ private ensureChild(): ChildProcess {+ if (this.child) return this.child;+ const { command, args, user, env, agentHome, cwd } = this.options;+ const child = spawn(command, args, {+ cwd,+ env: { ...env, [HOME_VAR]: agentHome, [CWD_VAR]: cwd },+ uid: user.uid,+ gid: user.gid,+ stdio: ["ignore", "ignore", "pipe", "ipc"],+ serialization: "json",+ });+ this.child = child;+ child.stderr?.setEncoding("utf8");+ child.stderr?.on("data", (chunk: string) => {+ for (const line of chunk.split("\n"))+ if (line.trim()) this.log(`[sign-in helper] ${line.slice(0, 300)}`);+ });+ child.on("message", (message) => this.receive(message as FromHelper));+ const gone = (why: string) => {+ if (this.child !== child) return;+ this.child = undefined;+ this.log(`the sign-in helper stopped (${why})`);+ this.failAll(new Error("The sign-in helper stopped."));+ };+ child.on("error", (error) => gone(error.message));+ child.on("exit", (code, signal) => gone(signal ?? `code ${code}`));+ return child;+ }++ private receive(message: FromHelper): void {+ if (typeof message !== "object" || message === null || typeof message.id !== "number") return;+ const call = this.calls.get(message.id);+ if (!call) return;+ if (message.kind === "result") {+ if (isString(message.error)) call.reject(new Error(message.error));+ else call.resolve(message.result);+ return;+ }+ const interaction = call.interaction;+ if (!interaction) return;+ if (message.kind === "notify") {+ interaction.notify(message.event);+ return;+ }+ if (message.kind === "prompt" && typeof message.promptId === "number") {+ const { promptId } = message;+ interaction+ .prompt({ ...message.request, ...(interaction.signal ? { signal: interaction.signal } : {}) })+ .then(+ (value) => this.send({ kind: "answer", promptId, value }),+ (error: Error) => this.send({ kind: "answer", promptId, error: error.message }),+ );+ }+ }++ private failAll(error: Error): void {+ for (const call of [...this.calls.values()]) call.reject(error);+ }++ private log(line: string): void {+ this.options.log?.(line);+ }+}++/** The helper's side (`cli.ts --auth-helper`), as the engine's user: ModelRuntime on the engine's home. */+export function serveAuthHelper(): void {+ const agentHome = process.env[HOME_VAR];+ const cwd = process.env[CWD_VAR];+ if (!process.send || !agentHome || !cwd) {+ process.stderr.write("the sign-in helper runs only when the daemon starts it\n");+ process.exit(2);+ }+ const reply = (message: FromHelper) => process.send?.(message);+ const logins = new Map<number, AbortController>();+ const prompts = new Map<number, { resolve(value: string): void; reject(error: Error): void }>();+ let nextPrompt = 0;+ const run = async (id: number, method: string, params: Record<string, unknown>): Promise<unknown> => {+ const runtime = await createModelAuthRuntime(agentHome, cwd);+ switch (method) {+ case "snapshot": {+ const providers = runtime.getProviders().map((p) => ({ id: p.id, name: p.name, auth: p.auth }));+ const status = Object.fromEntries(providers.map((p) => [p.id, runtime.getProviderAuthStatus(p.id)]));+ return { providers, status };+ }+ case "openAIApiKey":+ return { key: (await runtime.openAIApiKey?.()) ?? null };+ case "logout":+ await runtime.logout(String(params.providerId));+ return {};+ case "login": {+ const controller = new AbortController();+ logins.set(id, controller);+ const interaction: AuthInteraction = {+ signal: controller.signal,+ prompt: (request) =>+ new Promise<string>((resolve, reject) => {+ if (controller.signal.aborted) return reject(new Error("cancelled"));+ const promptId = ++nextPrompt;+ prompts.set(promptId, { resolve, reject });+ controller.signal.addEventListener("abort", () => {+ prompts.delete(promptId);+ reject(new Error("cancelled"));+ });+ const { signal: _signal, ...plain } = request;+ reply({ kind: "prompt", id, promptId, request: plain });+ }),+ notify: (event) => reply({ kind: "notify", id, event }),+ };+ try {+ await runtime.login(String(params.providerId), params.type as AuthMethod, interaction);+ } finally {+ logins.delete(id);+ }+ return {};+ }+ default:+ throw new Error(`Unknown request: ${method}`);+ }+ };+ process.on("message", (raw) => {+ const message = raw as ToHelper;+ if (message.kind === "call") {+ run(message.id, message.method, message.params ?? {}).then(+ (result) => reply({ kind: "result", id: message.id, result }),+ (error: Error) => reply({ kind: "result", id: message.id, error: error.message }),+ );+ } else if (message.kind === "answer") {+ const prompt = prompts.get(message.promptId);+ prompts.delete(message.promptId);+ if (isString(message.value)) prompt?.resolve(message.value);+ else prompt?.reject(new Error(message.error ?? "cancelled"));+ } else if (message.kind === "abort") logins.get(message.id)?.abort();+ });+ // The daemon is gone: so is the helper.+ process.on("disconnect", () => process.exit(0));+}diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex c1fc21d..7f44b96 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -1,4 +1,5 @@import { randomBytes, randomUUID } from "node:crypto";+import { readFileSync } from "node:fs";import { join } from "node:path";import {type AgentState,@@ -31,6 +32,7 @@ import {pageHistory,resolveConversation,} from "./conversations.ts";+import { directAccess, type EngineAccess } from "./engine-access.ts";import { DRAFT_STATUS_KEY } from "./extensions/approval-guard.ts";import { describeTool, textOf } from "./presentation.ts";import {@@ -75,8 +77,11 @@ export interface BridgeOptions {pin?: PinGate;/** How long a PIN approval waits for an answer. Default 130 s, like the app's. */approvalWaitMs?: number;- /** Server mode (S25.8): gives a handoff session to the engine's user. */- handOver?: (paths: string[]) => void;+ /**+ * How the engine's session and upload files are read and written; in server mode as the engine's+ * user (S25.8, B1), since the engine can plant links there. Default: as the daemon is.+ */+ engineAccess?: EngineAccess;/** How long switching conversations waits for a running answer to stop. Default 10 s. */stopTimeoutMs?: number;/** Optional parts of the app; by default one continuous chat. */@@ -171,7 +176,7 @@ export class DotBridge {limits: options.rotation ?? DEFAULT_ROTATION,canRotate: () =>supervisor.state === "ready" && !supervisor.busy && this.asks.size === 0 && this.sending === 0,- ...(options.handOver ? { handOver: options.handOver } : {}),+ ...(options.engineAccess ? { access: options.engineAccess } : {}),log: (line) => this.log(line),});supervisor.onEvent((event) => this.onAgentEvent(event));@@ -401,7 +406,11 @@ export class DotBridge {const busy = this.supervisor.busy;const prompt =files.length > 0- ? composePrompt(message.text, files, { images: this.supervisor.modelImages })+ ? composePrompt(message.text, files, {+ images: this.supervisor.modelImages,+ // The stored file may have been swapped for a link since: read it as the engine.+ read: (path) => this.engine(() => readFileSync(path)),+ }): { message: message.text };this.sending += 1;try {@@ -471,7 +480,7 @@ export class DotBridge {return;case "open_conversation": {if (!this.conversationsOn(client)) return;- const path = resolveConversation(this.sessionDir, message.conversationId);+ const path = this.engine(() => resolveConversation(this.sessionDir, message.conversationId));if (!path) {this.deliver(client, {type: "error",@@ -623,7 +632,7 @@ export class DotBridge {this.deliver(client, {type: "earlier",before: message.before,- ...pageHistory(this.chain(), this.pageSize(), message.before),+ ...this.engine(() => pageHistory(this.chain(), this.pageSize(), message.before)),});return;}@@ -1129,7 +1138,7 @@ export class DotBridge {// The engine writes a message to its session file right after announcing it;// one round trip makes sure everything announced so far is on disk.await this.supervisor.request({ type: "get_state" });- const page = pageHistory(this.chain(), this.pageSize());+ const page = this.engine(() => pageHistory(this.chain(), this.pageSize()));if (this.nextMessage === seen || attempt >= 2) return page;}}@@ -1145,7 +1154,11 @@ export class DotBridge {}private conversationsPayload(): ServerPayload {- return { type: "conversations", conversations: listConversations(this.sessionDir), ...this.activeRef() };+ return {+ type: "conversations",+ conversations: this.engine(() => listConversations(this.sessionDir)),+ ...this.activeRef(),+ };}private conversationRef(): { conversationId?: string } {@@ -1378,6 +1391,11 @@ export class DotBridge {client.send(payload);}+ /** Runs `fn` on the engine's files as the engine's user (server mode). */+ private engine<T>(fn: () => T): T {+ return (this.options.engineAccess ?? directAccess)(fn);+ }+private log(line: string): void {this.options.log?.(line);}diff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.tsindex de1b4b1..f06901b 100644--- a/packages/daemon/src/cli.ts+++ b/packages/daemon/src/cli.ts@@ -2,6 +2,7 @@import { existsSync } from "node:fs";import { fileURLToPath } from "node:url";import { inheritedAppSocket } from "./app-channel.ts";+import { serveAuthHelper } from "./auth-helper.ts";import { loadConfig } from "./config.ts";import { APPROVAL_GUARD, bundledMcpCli } from "./connectors.ts";import { startDaemon, startupMessage } from "./daemon.ts";@@ -10,6 +11,8 @@ import { SECRETS_KEY_VAR } from "./secret-file.ts";import { loadVpsOptions } from "./vps.ts";import { IDENTITY_SOURCE } from "./white-label.ts";+/** This file (or the bundled `cli.mjs`), which the sign-in helper runs again. */+const ENTRY = fileURLToPath(import.meta.url);const log = (line: string) => process.stderr.write(`${new Date().toISOString()} ${line}\n`);/**@@ -55,7 +58,10 @@ async function main(): Promise<void> {...(config.agentHome ? { agentHome: config.agentHome } : {}),allowedOrigins: config.allowedOrigins,...(appChannel ? { appChannel } : {}),- ...(vps ? { vps } : {}),+ // Sign-in runs in this same entry point as the engine's user (`--auth-helper`, B1).+ ...(vps+ ? { vps: { ...vps, authHelper: { command: process.execPath, args: [ENTRY, "--auth-helper"] } } }+ : {}),log,});process.stdout.write(`${startupMessage(daemon.url, config.dataDir, process.stdout.isTTY === true)}\n`);@@ -76,9 +82,11 @@ async function main(): Promise<void> {void daemon.closed.then(() => process.exit(0));}-if (process.argv.includes("--self-check")) selfCheck();--main().catch((error: Error) => {- log(`failed to start: ${error.message}`);- process.exit(1);-});+if (process.argv.includes("--auth-helper")) serveAuthHelper();+else {+ if (process.argv.includes("--self-check")) selfCheck();+ main().catch((error: Error) => {+ log(`failed to start: ${error.message}`);+ process.exit(1);+ });+}diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.tsindex 06854c8..5318e5f 100644--- a/packages/daemon/src/connectors.ts+++ b/packages/daemon/src/connectors.ts@@ -38,8 +38,10 @@ import {recordMac,} from "./connector-integrity.ts";import { type OAuthSettings, type SignIn, SignInCancelledError, startSignIn } from "./connector-oauth.ts";+import { directAccess, type EngineAccess } from "./engine-access.ts";import { type ConnectorPolicy, draftSecretProblem, POLICY_ENV } from "./extensions/approval-guard.ts";import type { ProxiedConnector, UpstreamCredentials } from "./mcp-proxy.ts";+import { writePrivateFile } from "./private-file.ts";import { runtimeDir, runtimeModules } from "./runtime.ts";import { NO_APP, type SecretSource, SecretsUnavailableError } from "./secret-source.ts";@@ -631,6 +633,11 @@ export interface ConnectorStoreOptions {* extensions folder, written and put back like `mcp.json` and protected like the guard (S25.4).*/childGuard?: boolean;+ /**+ * How the store reaches the engine's files (`mcp.json`, the subagents' guard, the workspace's+ * `.pi`, the engine's old `mcp-auth.json`); in server mode as the engine's user (S25.8, B1).+ */+ engineAccess?: EngineAccess;log?: (line: string) => void;}@@ -703,6 +710,28 @@ export class ConnectorStore {/** The file that loads the guard into the engine's subagents, when the store keeps one. */readonly childGuard: { file: string; text: string } | undefined;+ /** Runs `fn` on the engine's files as the engine's user; the daemon's own files stay root's. */+ private engine<T>(fn: () => T): T {+ return (this.options.engineAccess ?? directAccess)(fn);+ }++ /** How `path` is reached: as the engine's user when it is in the engine's folders. */+ private io(path: string): EngineAccess {+ const { agentHome, workspace } = this.options;+ const inside = (root: string | undefined) =>+ root !== undefined && (path === root || path.startsWith(`${root}/`));+ return inside(agentHome) || inside(workspace) ? (fn) => this.engine(fn) : directAccess;+ }++ /** Writes the engine's `mcp.json`, as the engine's user. */+ private writeMcp(): void {+ const text = this.engineMcpText();+ this.engine(() => {+ mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });+ writePrivate(this.mcpFile, text);+ });+ }+constructor(options: ConnectorStoreOptions) {this.options = options;this.file = join(options.dataDir, "connectors.json");@@ -719,10 +748,11 @@ export class ConnectorStore {this.saved = state;// A new install has nothing to move.this.migrated =- version >= 2 || (version === 0 && ![this.authFile, this.legacyAuthFile].some((f) => existsSync(f)));+ version >= 2 ||+ (version === 0 && ![this.authFile, this.legacyAuthFile].some((f) => this.io(f)(() => existsSync(f))));if (renamed) {this.edited = true;- writePrivate(this.file, this.recordText());+ writePrivateFile(this.file, this.recordText());}}@@ -748,9 +778,8 @@ export class ConnectorStore {);this.saved = state;this.edited = true;- mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });- writePrivate(this.file, this.recordText());- writePrivate(this.mcpFile, this.engineMcpText());+ writePrivateFile(this.file, this.recordText());+ this.writeMcp();this.onUpdated();}@@ -817,7 +846,7 @@ export class ConnectorStore {const signedBefore = stored !== undefined || (record !== undefined && "mac" in record);if (!signedBefore) {this.edited = true;- writePrivate(this.file, this.recordText());+ writePrivateFile(this.file, this.recordText());this.log("signed connectors.json for the first time");return;}@@ -892,8 +921,7 @@ export class ConnectorStore {const same = endpoint?.url === this.computer?.url && endpoint?.token === this.computer?.token;if (same) return false;this.computer = endpoint ? { ...endpoint } : undefined;- mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });- writePrivate(this.mcpFile, this.engineMcpText());+ this.writeMcp();return true;}@@ -901,8 +929,7 @@ export class ConnectorStore {setProxy(endpoint: ProxyEndpoint): boolean {if (endpoint.url === this.proxy?.url && endpoint.key === this.proxy?.key) return false;this.proxy = { ...endpoint };- mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });- writePrivate(this.mcpFile, this.engineMcpText());+ this.writeMcp();return true;}@@ -1031,18 +1058,20 @@ export class ConnectorStore {// and mcp.json before any connector or the computer helper is in it.const noConnectors = Object.keys(this.saved.connectors).length === 0;const changed: string[] = [];- for (const [file, text, empty] of [- [this.file, this.recordText(), noConnectors],- [this.mcpFile, this.engineMcpText(), noConnectors && !this.computer],- ] as const) {- const current = readOrUndefined(file);- if (current === text || (current === undefined && empty)) continue;- mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });- writePrivate(file, text);- changed.push(file);+ const record = this.recordText();+ const current = readOrUndefined(this.file);+ if (current !== record && !(current === undefined && noConnectors)) {+ writePrivateFile(this.file, record);+ changed.push(this.file);}- if (this.enforceChildGuard()) changed.push(this.childGuard?.file ?? "");- if (this.removeProjectConfig()) changed.push("the workspace's .pi/mcp.json");+ const mcp = this.engineMcpText();+ const currentMcp = this.engine(() => readOrUndefined(this.mcpFile));+ if (currentMcp !== mcp && !(currentMcp === undefined && noConnectors && !this.computer)) {+ this.writeMcp();+ changed.push(this.mcpFile);+ }+ if (this.engine(() => this.enforceChildGuard())) changed.push(this.childGuard?.file ?? "");+ if (this.engine(() => this.removeProjectConfig())) changed.push("the workspace's .pi/mcp.json");this.reportPlanted();if (changed.length === 0 || !report) return changed.length > 0;this.options.log?.(@@ -1073,7 +1102,7 @@ export class ConnectorStore {const folders = [this.options.dataDir, this.options.agentHome, this.options.workspace];for (const folder of folders) {if (!folder) continue;- mkdirSync(folder, { recursive: true, mode: 0o700 });+ this.io(folder)(() => mkdirSync(folder, { recursive: true, mode: 0o700 }));this.watchers.push(watch(folder, check));}this.check = check;@@ -1260,7 +1289,7 @@ export class ConnectorStore {for (const [id, secret] of this.pending) this.cache.set(id, secret);this.pending.clear();this.edited = true;- writePrivate(this.file, this.recordText());+ writePrivateFile(this.file, this.recordText());this.log(`moved ${moved} connector secrets from connectors.json into the app's secure store`);}if (!this.migrated) {@@ -1270,7 +1299,7 @@ export class ConnectorStore {let unread = false;// The daemon's own sign-ins first: they win over the engine's older ones.for (const file of [this.authFile, this.legacyAuthFile]) {- const states = this.readSignIns(file);+ const states = this.io(file)(() => this.readSignIns(file));if (states === "unread") unread = true;if (!states || states === "unread") continue;const refs: Record<string, string> = {};@@ -1297,7 +1326,7 @@ export class ConnectorStore {return;}this.applySignIns(refs);- unlinkSync(file);+ this.io(file)(() => unlinkSync(file));}if (moved > 0) this.log(`moved ${moved} connector sign-ins into the app's secure store`);if (dropped > 0)@@ -1312,7 +1341,7 @@ export class ConnectorStore {this.migrated = true;this.edited = true;mkdirSync(this.options.dataDir, { recursive: true, mode: 0o700 });- writePrivate(this.file, this.recordText());+ writePrivateFile(this.file, this.recordText());}this.reportPlanted();}@@ -1373,7 +1402,7 @@ export class ConnectorStore {private reportPlanted(): void {if (!this.migrated) return;for (const file of [this.authFile, this.legacyAuthFile]) {- if (this.reported.has(file) || !existsSync(file)) continue;+ if (this.reported.has(file) || !this.io(file)(() => existsSync(file))) continue;this.reported.add(file);this.log(`found ${file} after the connector sign-ins moved to the app's secure store; it was not imported and was left as it is`,@@ -1407,7 +1436,7 @@ export class ConnectorStore {this.migrated = true;this.edited = true;mkdirSync(this.options.dataDir, { recursive: true, mode: 0o700 });- writePrivate(this.file, this.recordText());+ writePrivateFile(this.file, this.recordText());this.log(`connectors.json was changed while Gentle Dot was closed (its signature does not match)${moved ? `; moved it to ${target}` : ""} and started with no connectors; the secrets in the app's secure store were not touched`,);@@ -1426,7 +1455,8 @@ export class ConnectorStore {/** `.pi` appears after the watch starts; its folder is watched once it is there. */private watchProjectConfig(): void {const folder = this.options.workspace && join(this.options.workspace, ".pi");- if (this.projectWatcher || !folder || this.watchers.length === 0 || !isFolder(folder)) return;+ if (this.projectWatcher || !folder || this.watchers.length === 0 || !this.engine(() => isFolder(folder)))+ return;try {const watcher = watch(folder, this.check);watcher.on("error", () => {@@ -1441,8 +1471,11 @@ export class ConnectorStore {childGuardReady(): boolean {if (!this.childGuard) return false;const { file, text } = this.childGuard;- return (- isFolder(dirname(file)) && lstatOrUndefined(file)?.isFile() === true && readOrUndefined(file) === text+ return this.engine(+ () =>+ isFolder(dirname(file)) &&+ lstatOrUndefined(file)?.isFile() === true &&+ readOrUndefined(file) === text,);}diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex bec63af..becf6d4 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -1,5 +1,5 @@import { randomBytes, timingSafeEqual } from "node:crypto";-import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";import { createServer, type IncomingMessage, type ServerResponse } from "node:http";import type { AddressInfo } from "node:net";import { extname, join, resolve, sep } from "node:path";@@ -15,6 +15,7 @@ import {import { type WebSocket, WebSocketServer } from "ws";import { AppChannel } from "./app-channel.ts";import { AuthManager, type AuthRuntime, createModelAuthRuntime, resolveAgentHome } from "./auth.ts";+import { AuthHelper } from "./auth-helper.ts";import { type BridgeClient, DotBridge } from "./bridge.ts";import {APPROVAL_GUARD,@@ -23,6 +24,7 @@ import {ConnectorStore,policyEnv,} from "./connectors.ts";+import { directAccess, type EngineAccess, engineAccess } from "./engine-access.ts";import { approvalRequest } from "./extensions/approval-guard.ts";import {claimEngineHome,@@ -32,6 +34,7 @@ import {privateMemory,} from "./isolation.ts";import { MCP_PREFIX, McpProxy, type ProxiedConnector, type UpstreamCredentials } from "./mcp-proxy.ts";+import { writePrivateFile } from "./private-file.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";import { type RotationLimits, rotationLimits } from "./rotation.ts";import { FileSecretSource, SECRETS_FILE, SECRETS_KEY_VAR } from "./secret-file.ts";@@ -135,7 +138,7 @@ export function ensureToken(dataDir: string): string {if (existing.length >= 32) return existing;}const token = randomBytes(32).toString("base64url");- writeFileSync(file, `${token}\n`, { mode: 0o600 });+ writePrivateFile(file, `${token}\n`);return token;}@@ -151,12 +154,17 @@ export function startupMessage(url: string, dataDir: string, interactive: booleaexport async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {const log = options.log ?? (() => {});const token = ensureToken(options.dataDir);+ const vps = options.vps;+ // Server mode (S25.8): the daemon's files stay its own, the engine's folders become the engine's,+ // and from here on the daemon reaches them only as the engine's user (B1, engine-access.ts).+ if (vps) prepareVpsLayout(options.dataDir, vps.handOver ?? chownHandOver(vps.engine, log), vps.connector);+ const access: EngineAccess = vps ? (vps.access ?? engineAccess(vps.engine)) : directAccess;// Before anything is written there: the engine skips its first-run setup in a home it did not// create (S35.3). Only the assistant's default home; a home the user chose is never marked.if (options.agentHome && resolve(options.agentHome) === resolve(options.dataDir, "agent"))- claimEngineHome(options.agentHome, log);- mkdirSync(options.workspace, { recursive: true, mode: 0o700 });- ensureMemoryProject(options.workspace);+ claimEngineHome(options.agentHome, log, access);+ access(() => mkdirSync(options.workspace, { recursive: true, mode: 0o700 }));+ ensureMemoryProject(options.workspace, access);const folderArgs = options.preferredFolder? ["--append-system-prompt",@@ -166,14 +174,12 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {let agentEnv = { ...(options.agentEnv ?? process.env) };// The server's secrets key is the daemon's only, whatever the engine is (S25.8).delete agentEnv[SECRETS_KEY_VAR];- const vps = options.vps;- const handOver = vps ? (vps.handOver ?? chownHandOver(vps.engine, log)) : undefined;const homeArgs: string[] = [];- const memory = options.agentHome ? await privateMemory(agentEnv, options.dataDir, log) : undefined;+ const memory = options.agentHome ? await privateMemory(agentEnv, options.dataDir, log, access) : undefined;if (options.agentHome) {homeArgs.push("--home", options.agentHome);// The engine also writes under the home folder; it gets one of its own.- agentEnv = isolatedAgentEnv(agentEnv, options.dataDir);+ agentEnv = isolatedAgentEnv(agentEnv, options.dataDir, access);agentEnv.GENTLE_PI_CONFIG_HOME = join(options.dataDir, "gentle-ai");}const agentHome = options.agentHome ?? resolveAgentHome(process.env, options.dataDir);@@ -192,6 +198,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {guardPath: APPROVAL_GUARD,// The assistant's own engine: its subagents load the guard from its extensions folder (S25.4)....(options.agentHome ? { childGuard: true } : {}),+ ...(vps ? { engineAccess: access } : {}),env: agentEnv,// On a server without the app, an encrypted file with a key from the daemon's environment (S25.8).secrets:@@ -252,13 +259,6 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {log("subagents are off for this engine start: their approval guard is not in place");env.GENTLE_PI_AGENTS = "0";}- // What the daemon wrote for this launch (mcp.json, sign-ins, settings) becomes the engine's.- handOver?.([- agentHome,- join(options.dataDir, "gentle-ai"),- join(options.dataDir, "home"),- join(options.dataDir, "sessions"),- ]);return env;},// The first start in a new home installs the engine's companion packages.@@ -266,15 +266,33 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {...(options.backoffMs ? { backoffMs: options.backoffMs } : {}),log: (line) => log(`[agent] ${line}`),});+ // In server mode Pi's ModelRuntime runs in a helper as the engine's user, never as root (B1).+ const authHelper =+ vps?.authHelper && !options.authRuntime+ ? new AuthHelper({+ ...vps.authHelper,+ user: vps.engine,+ env: agentEnv,+ agentHome,+ cwd: options.workspace,+ log,+ })+ : undefined;const auth = new AuthManager({- runtime: options.authRuntime ?? (() => createModelAuthRuntime(agentHome, options.workspace)),+ runtime:+ options.authRuntime ??+ (authHelper+ ? () => authHelper.runtime()+ : vps+ ? () => Promise.reject(new Error("sign-in has no helper on this server"))+ : () => createModelAuthRuntime(agentHome, options.workspace)),log,});const profiles = new ProfileStore({configHome: join(options.dataDir, "gentle-ai"),agentHome,importPath: options.profilesImportPath ?? defaultImportPath(process.env),- ...(handOver ? { handOver } : {}),+ ...(vps ? { access } : {}),});const connectors = new ConnectorManager({store: connectorStore,@@ -291,7 +309,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {});const uploads = new UploadStore({workspace: options.workspace,- ...(handOver ? { handOver } : {}),+ ...(vps ? { access } : {}),...(options.uploadLimits ? { limits: options.uploadLimits } : {}),});const historyPage = options.historyPage ?? Number(process.env.GENTLE_DOT_HISTORY_PAGE);@@ -306,7 +324,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {...(app ? { app } : {}),...(vps && !app ? { pin: new PinGate({ file: join(options.dataDir, PIN_FILE) }) } : {}),...(options.approvalWaitMs ? { approvalWaitMs: options.approvalWaitMs } : {}),- ...(handOver ? { handOver } : {}),+ ...(vps ? { engineAccess: access } : {}),features: { conversations: options.conversations ?? process.env.GENTLE_DOT_CONVERSATIONS === "1" },rotation: options.rotation ?? rotationLimits(process.env),...(Number.isInteger(historyPage) && historyPage > 0 ? { historyPage } : {}),@@ -384,6 +402,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {await serverClosed;await supervisor.stop();connectorStore.close();+ authHelper?.close();await memory?.stop();};let stopping: Promise<void> | undefined;@@ -404,8 +423,6 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {void close().catch(() => {});});- // Server mode: the daemon's files stay its own, the engine's folders become the engine's (S25.8).- if (vps && handOver) prepareVpsLayout(options.dataDir, handOver, vps.connector);// Listening first keeps the app's health check answered while its store is asked for the key.await integrity;// Secrets that files still hold move into the app's store, once; on a server, into its encrypted file.diff --git a/packages/daemon/src/engine-access.ts b/packages/daemon/src/engine-access.tsnew file mode 100644index 0000000..60ee7a1--- /dev/null+++ b/packages/daemon/src/engine-access.ts@@ -0,0 +1,84 @@+/**+ * How the daemon touches the engine's own files in server mode (S25.8, B1). The daemon runs as root+ * there, and the engine's folders (`agent`, `home`, `workspace`, `sessions`, `gentle-ai`) belong to+ * the engine's user, who has a shell: any path in them may be a link to a root file, and any file+ * may hold what the engine chose. So every read, write, mkdir, chmod, or removal there runs inside+ * {@link EngineAccess}: the daemon takes the engine's user as its effective user and group (and its+ * group as its only supplementary group) for that synchronous call, and the kernel enforces the+ * engine's own permissions on every path component; what it creates belongs to the engine's user.+ * Then it takes root back. The saved user stays root, and the effective capabilities are dropped+ * while the effective user is not root, so a bracket can neither read nor write a root file.+ *+ * Rules (checked where they can be): the call is synchronous (a returned promise is refused: the+ * work would continue as root), it never starts a process (a child would get root as its real+ * user), and nothing writes a root file meanwhile ({@link insideEngineAccess}; see+ * `private-file.ts`). On Linux the ids change for every thread of the process (glibc broadcasts+ * them), so anything on libuv's thread pool during a bracket runs as the engine's user too: the+ * daemon has no asynchronous file work on root paths (see the static check in the tests). If root+ * cannot be taken back, the daemon stops: it never goes on as the wrong user.+ *+ * On the desktop there is no bracket: {@link directAccess} runs the call as it is.+ */+import type { OsUser } from "./vps.ts";++export type EngineAccess = <T>(fn: () => T) => T;++/** The desktop: the daemon and the engine are the same user. */+export const directAccess: EngineAccess = (fn) => fn();++let depth = 0;++/** True while a bracket runs: a root file must not be written now. */+export function insideEngineAccess(): boolean {+ return depth > 0;+}++function refuseAsync<T>(result: T): T {+ if (typeof (result as { then?: unknown } | null)?.then === "function")+ throw new Error("The engine's files are reached only synchronously.");+ return result;+}++/** Runs `fn` as `user` (see the module comment); nested calls run inside the outer bracket. */+export function engineAccess(user: OsUser, onFatal: (error: Error) => never = fatal): EngineAccess {+ return <T>(fn: () => T): T => {+ if (depth > 0) return refuseAsync(fn());+ const euid = process.geteuid?.() ?? -1;+ if (euid !== 0) {+ // Without root there is nothing to switch to; only the engine's own user may go on.+ if (euid !== user.uid)+ throw new Error(`Server mode: cannot reach the engine's files as uid ${user.uid} without root.`);+ depth++;+ try {+ return refuseAsync(fn());+ } finally {+ depth--;+ }+ }+ const groups = process.getgroups?.() ?? [];+ const egid = process.getegid?.() ?? 0;+ process.setgroups?.([user.gid]);+ process.setegid?.(user.gid);+ process.seteuid?.(user.uid);+ depth++;+ try {+ return refuseAsync(fn());+ } finally {+ depth--;+ try {+ process.seteuid?.(0);+ process.setegid?.(egid);+ process.setgroups?.(groups);+ } catch (error) {+ onFatal(error as Error);+ }+ if (process.geteuid?.() !== 0 || process.getegid?.() !== egid)+ onFatal(new Error("the daemon did not get its own user back"));+ }+ };+}++function fatal(error: Error): never {+ process.stderr.write(`${new Date().toISOString()} stopping: ${error.message}\n`);+ process.exit(70);+}diff --git a/packages/daemon/src/isolation.ts b/packages/daemon/src/isolation.tsindex 849323c..682ac86 100644--- a/packages/daemon/src/isolation.ts+++ b/packages/daemon/src/isolation.ts@@ -1,9 +1,10 @@import { execFile } from "node:child_process";-import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";import { createRequire } from "node:module";import { homedir } from "node:os";import { delimiter, dirname, join } from "node:path";import { bundledGentleShell } from "./config.ts";+import { directAccess, type EngineAccess } from "./engine-access.ts";import { resolveEngramBin, runtimeDir } from "./runtime.ts";/**@@ -50,11 +51,17 @@ function engineVersion(): string | undefined {* checks only that the file exists). One already there is left as it is. Call it only for the* default `<data>/agent`: a home the user chose may be theirs, and is never marked.*/-export function claimEngineHome(agentHome: string, log: (line: string) => void = () => {}): void {- ensurePrivateDir(agentHome);+export function claimEngineHome(+ agentHome: string,+ log: (line: string) => void = () => {},+ access: EngineAccess = directAccess,+): void {const content = `${JSON.stringify({ createdBy: "gentle-shell", version: engineVersion() })}\n`;try {- writeFileSync(join(agentHome, ENGINE_HOME_MARKER), content, { flag: "wx", mode: 0o600 });+ access(() => {+ ensurePrivateDir(agentHome);+ writeFileSync(join(agentHome, ENGINE_HOME_MARKER), content, { flag: "wx", mode: 0o600 });+ });} catch (error) {if ((error as NodeJS.ErrnoException).code !== "EEXIST")log(`could not mark the engine's home as its own: ${(error as Error).message}`);@@ -95,12 +102,15 @@ export const PRIVATE_ENGRAM_PORT = "7438";* Names the memory project of `workspace` through Engram's per-folder setting* (`.engram/config.json`), which Engram reads before any other detection.*/-export function ensureMemoryProject(workspace: string): void {- ensurePrivateDir(join(workspace, ".engram"));- writeFileSync(- join(workspace, ".engram", "config.json"),- `${JSON.stringify({ project_name: MEMORY_PROJECT })}\n`,- );+export function ensureMemoryProject(workspace: string, access: EngineAccess = directAccess): void {+ const file = join(workspace, ".engram", "config.json");+ access(() => {+ ensurePrivateDir(join(workspace, ".engram"));+ // Written next to it and renamed over it: a link planted at its place is replaced, never followed.+ const temp = `${file}.${process.pid}.tmp`;+ writeFileSync(temp, `${JSON.stringify({ project_name: MEMORY_PROJECT })}\n`);+ renameSync(temp, file);+ });}/**@@ -126,9 +136,13 @@ export function ensureMemoryProject(workspace: string): void {* An installed app (`GENTLE_DOT_RUNTIME`) also names the Engram binary* (`ENGRAM_BIN`, see `resolveEngramBin`), since its PATH has no user folders.*/-export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): NodeJS.ProcessEnv {+export function isolatedAgentEnv(+ base: NodeJS.ProcessEnv,+ dataDir: string,+ access: EngineAccess = directAccess,+): NodeJS.ProcessEnv {const home = join(dataDir, "home");- ensurePrivateDir(home);+ access(() => ensurePrivateDir(home));const realHome = base.HOME || homedir();const env: NodeJS.ProcessEnv = {...base,@@ -140,8 +154,9 @@ export function isolatedAgentEnv(base: NodeJS.ProcessEnv, dataDir: string): Node};for (const key of [...INHERITED_HOMES, ...SUBAGENT_VARIABLES, ...DAEMON_ONLY]) delete env[key];if (!base.TMPDIR) {- env.TMPDIR = join(home, ".cache", "tmp");- ensurePrivateDir(env.TMPDIR);+ const tmp = join(home, ".cache", "tmp");+ env.TMPDIR = tmp;+ access(() => ensurePrivateDir(tmp));}const bin = bundledBinDir(base);if (bin) {@@ -176,6 +191,7 @@ export async function privateMemory(base: NodeJS.ProcessEnv,dataDir: string,log: (line: string) => void,+ access: EngineAccess = directAccess,): Promise<{ stop(): Promise<void> } | undefined> {if (base.GENTLE_DOT_ENGRAM !== "private") return undefined;const port = base.GENTLE_DOT_ENGRAM_PORT || PRIVATE_ENGRAM_PORT;@@ -186,7 +202,8 @@ export async function privateMemory(if (pid === undefined) return;let expected: string;try {- expected = readFileSync(join(dataDir, "home", ".engram", ".instance-id"), "utf8").trim();+ const file = join(dataDir, "home", ".engram", ".instance-id");+ expected = access(() => readFileSync(file, "utf8")).trim();} catch {return;}diff --git a/packages/daemon/src/private-file.ts b/packages/daemon/src/private-file.tsnew file mode 100644index 0000000..9cc4d1e--- /dev/null+++ b/packages/daemon/src/private-file.ts@@ -0,0 +1,32 @@+/**+ * Writes one of the daemon's own files (the access key, `state.json`, `connectors.json`, the+ * encrypted secrets, the PIN hash): a new temporary file next to it, created exclusively (a link or+ * an older file there is never followed), checked to belong to the daemon's real user before+ * anything is written, then renamed over the old one. Refused inside an engine-access bracket+ * (`engine-access.ts`), where it would be created as the engine's user. Fails closed: a temporary+ * file that is not the daemon's is removed and the write throws.+ */+import { randomBytes } from "node:crypto";+import { closeSync, fstatSync, openSync, renameSync, unlinkSync, writeFileSync } from "node:fs";+import { basename, dirname, join } from "node:path";+import { insideEngineAccess } from "./engine-access.ts";++export function writePrivateFile(path: string, text: string, mode = 0o600): void {+ if (insideEngineAccess())+ throw new Error(`${path} is the daemon's and is not written as the engine's user.`);+ const temp = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}.tmp`);+ const fd = openSync(temp, "wx", mode);+ try {+ const owner = fstatSync(fd).uid;+ const self = process.getuid?.();+ if (self !== undefined && owner !== self)+ throw new Error(`${temp} was created as uid ${owner}, not the daemon's ${self}.`);+ writeFileSync(fd, text);+ } catch (error) {+ closeSync(fd);+ unlinkSync(temp);+ throw error;+ }+ closeSync(fd);+ renameSync(temp, path);+}diff --git a/packages/daemon/src/profiles.ts b/packages/daemon/src/profiles.tsindex 86f2caf..6ea5c89 100644--- a/packages/daemon/src/profiles.ts+++ b/packages/daemon/src/profiles.ts@@ -30,6 +30,7 @@ import {THINKING_LEVELS,type ThinkingLevel,} from "@gentle-dot/protocol";+import { directAccess, type EngineAccess } from "./engine-access.ts";import { presentText } from "./white-label.ts";// The engine's profile store format (gentle-pi lib/agent-profiles.ts), reimplemented@@ -209,29 +210,35 @@ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));* a `<file>.lock` directory, stale after 10 seconds), so the engine never* interleaves its own settings write with ours.*/-async function withFileLock<T>(path: string, fn: () => T): Promise<T> {- mkdirSync(dirname(path), { recursive: true });+async function withFileLock<T>(path: string, fn: () => T, access: EngineAccess = directAccess): Promise<T> {const lock = `${path}.lock`;for (let attempt = 0; ; attempt++) {- try {- mkdirSync(lock);- break;- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;- let stale = false;+ const taken = access(() => {+ mkdirSync(dirname(path), { recursive: true });try {- stale = Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS;- } catch {}- if (stale) rmSync(lock, { recursive: true, force: true });- else if (attempt >= LOCK_ATTEMPTS) throw new Error(`${path} stayed locked`);- else await sleep(LOCK_RETRY_MS);- }- }- try {- return fn();- } finally {- rmSync(lock, { recursive: true, force: true });+ mkdirSync(lock);+ return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;+ let stale = false;+ try {+ stale = Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS;+ } catch {}+ if (stale) rmSync(lock, { recursive: true, force: true });+ return false;+ }+ });+ if (taken) break;+ if (attempt >= LOCK_ATTEMPTS) throw new Error(`${path} stayed locked`);+ await sleep(LOCK_RETRY_MS);}+ return access(() => {+ try {+ return fn();+ } finally {+ rmSync(lock, { recursive: true, force: true });+ }+ });}export function splitModel(model: string): { provider: string; modelId: string } | undefined {@@ -252,8 +259,8 @@ export interface ProfileStoreOptions {agentHome: string;/** Another setup's `profiles.json`, only ever read, for the one-time import. */importPath: string;- /** Server mode (S25.8): gives what a write left in the engine's folders to the engine's user. */- handOver?: (paths: string[]) => void;+ /** How the store reaches its files and the engine's; in server mode as the engine's user (S25.8, B1). */+ access?: EngineAccess;}export interface ImportResult {@@ -274,6 +281,11 @@ export class ProfileStore {this.options = options;}+ /** The store's files and the engine's are reached as the engine's user (the import source is not). */+ private access<T>(fn: () => T): T {+ return (this.options.access ?? directAccess)(fn);+ }+private get storePath(): string {return join(this.options.configHome, "profiles.json");}@@ -291,7 +303,7 @@ export class ProfileStore {}list(): { profiles: Profile[]; active?: string } {- const file = this.read();+ const file = this.access(() => this.read());const profiles = Object.entries(file.profiles).map(([name, roles]) => ({ name, roles })).sort((a, b) => a.name.localeCompare(b.name));@@ -300,8 +312,10 @@ export class ProfileStore {/** Roles the user can route, including any a saved profile routes without an agent file. */roles(): ProfileRole[] {- const routed = Object.values(this.read().profiles).flatMap((roles) => Object.keys(roles));- return discoverRoles(this.options.agentHome, routed);+ return this.access(() => {+ const routed = Object.values(this.read().profiles).flatMap((roles) => Object.keys(roles));+ return discoverRoles(this.options.agentHome, routed);+ });}/** Creates or replaces a profile. */@@ -369,25 +383,31 @@ export class ProfileStore {*/apply(name: string): Promise<RoleRoute | undefined> {return this.enqueue(async () => {- const file = this.read();- const roles = requireExisting(file, name);- const paths = [this.storePath, this.modelsPath, this.subagentsPath, this.settingsPath];- const agents = ownAgentFiles(this.options.agentHome);- const saved = new Map([...paths, ...agents.map((agent) => agent.path)].map((p) => [p, snapshot(p)]));+ const saved = new Map<string, Snapshot>();try {- writeFileAtomic(this.storePath, serializeProfilesFile({ ...file, active: name }));- writeFileAtomic(this.modelsPath, jsonText(roles));- this.writeAgentRoutes(roles);- for (const agent of agents) {- const next = updateFrontmatterRouting(agent.text, roles[agent.name]);- if (next !== agent.text) writeFileAtomic(agent.path, next, agent.mode);- }- const orchestrator = roles[ORCHESTRATOR];+ const orchestrator = this.access(() => {+ const file = this.read();+ const roles = requireExisting(file, name);+ const paths = [this.storePath, this.modelsPath, this.subagentsPath, this.settingsPath];+ const agents = ownAgentFiles(this.options.agentHome);+ for (const path of [...paths, ...agents.map((agent) => agent.path)])+ saved.set(path, snapshot(path));+ writeFileAtomic(this.storePath, serializeProfilesFile({ ...file, active: name }));+ writeFileAtomic(this.modelsPath, jsonText(roles));+ this.writeAgentRoutes(roles);+ for (const agent of agents) {+ const next = updateFrontmatterRouting(agent.text, roles[agent.name]);+ if (next !== agent.text) writeFileAtomic(agent.path, next, agent.mode);+ }+ return roles[ORCHESTRATOR];+ });if (!orchestrator?.model) return undefined;await this.writeOrchestrator(orchestrator);return { ...orchestrator };} catch (error) {- for (const [path, before] of saved) restore(path, before);+ this.access(() => {+ for (const [path, before] of saved) restore(path, before);+ });throw error;}});@@ -415,8 +435,15 @@ export class ProfileStore {*/import(providers: AuthProvider[] = []): Promise<ImportResult> {return this.enqueue(() => {+ // The other setup is the daemon's user's own, never the engine's: read as it is.const source = this.importable() ? this.readSource() : undefined;if (!source) throw new ProfileError("nothing_to_import");+ return this.access(() => this.importInto(source, providers));+ });+ }++ private importInto(source: ProfilesFile, providers: AuthProvider[]): ImportResult {+ {const file = this.read();const imported: ImportResult["imported"] = [];const used = new Set<string>();@@ -436,7 +463,7 @@ export class ProfileStore {.map((id) => providers.find((p) => p.id === id)?.name ?? id).sort();return { imported, missingProviders };- });+ }}private writeAgentRoutes(roles: ProfileRoles): void {@@ -459,17 +486,21 @@ export class ProfileStore {private writeOrchestrator(route: RoleRoute, clearThinking = true): Promise<void> {const target = route.model ? splitModel(route.model) : undefined;if (!target) throw new ProfileError("settings_invalid");- return withFileLock(this.settingsPath, () => {- const settings = readObject(this.settingsPath, "settings_invalid");- const next: Record<string, unknown> = {- ...settings,- defaultProvider: target.provider,- defaultModel: target.modelId,- };- if (route.thinking) next.defaultThinkingLevel = route.thinking;- else if (clearThinking) delete next.defaultThinkingLevel;- writeFileAtomic(this.settingsPath, jsonText(next));- });+ return withFileLock(+ this.settingsPath,+ () => {+ const settings = readObject(this.settingsPath, "settings_invalid");+ const next: Record<string, unknown> = {+ ...settings,+ defaultProvider: target.provider,+ defaultModel: target.modelId,+ };+ if (route.thinking) next.defaultThinkingLevel = route.thinking;+ else if (clearThinking) delete next.defaultThinkingLevel;+ writeFileAtomic(this.settingsPath, jsonText(next));+ },+ (fn) => this.access(fn),+ );}private read(): ProfilesFile {@@ -486,23 +517,17 @@ export class ProfileStore {}private mutate(change: (file: ProfilesFile) => void): Promise<void> {- return this.enqueue(() => {- const file = this.read();- change(file);- writeFileAtomic(this.storePath, serializeProfilesFile(file));- });+ return this.enqueue(() =>+ this.access(() => {+ const file = this.read();+ change(file);+ writeFileAtomic(this.storePath, serializeProfilesFile(file));+ }),+ );}private enqueue<T>(task: () => T | Promise<T>): Promise<T> {- const { handOver, configHome, agentHome } = this.options;- const write = async () => {- try {- return await task();- } finally {- handOver?.([configHome, agentHome]);- }- };- const run = this.queue.then(write, write);+ const run = this.queue.then(task, task);this.queue = run.catch(() => {});return run;}diff --git a/packages/daemon/src/rotation.ts b/packages/daemon/src/rotation.tsindex e999663..ba526b6 100644--- a/packages/daemon/src/rotation.ts+++ b/packages/daemon/src/rotation.ts@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";import { closeSync, existsSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";import { readSessionMessages } from "./conversations.ts";+import { directAccess, type EngineAccess } from "./engine-access.ts";import { textOf } from "./presentation.ts";import type { AgentSupervisor } from "./supervisor.ts";@@ -92,11 +93,12 @@ export async function writeHandoffSession(previousFile: string,text: string,cwd = process.cwd(),+ access: EngineAccess = directAccess,): Promise<string> {const { uuidv7 } = await import("@earendil-works/pi-ai");const id = uuidv7();const timestamp = new Date().toISOString();- const previousCwd = entries(previousFile, '"session"')[0]?.cwd;+ const previousCwd = access(() => entries(previousFile, '"session"'))[0]?.cwd;const header = {type: "session",version: SESSION_VERSION,@@ -115,7 +117,12 @@ export async function writeHandoffSession(timestamp,};const file = join(dirname(previousFile), `${timestamp.replace(/[:.]/g, "-")}_${id}.jsonl`);- writeFileSync(file, `${JSON.stringify(header)}\n${JSON.stringify(handoff)}\n`, { flag: "wx", mode: 0o600 });+ access(() =>+ writeFileSync(file, `${JSON.stringify(header)}\n${JSON.stringify(handoff)}\n`, {+ flag: "wx",+ mode: 0o600,+ }),+ );return file;}@@ -125,8 +132,8 @@ export interface RotatorOptions {canRotate: () => boolean;/** The engine's working folder, for a previous session without one. */cwd?: string;- /** Server mode (S25.8): gives the handoff session to the engine's user, which opens and extends it. */- handOver?: (paths: string[]) => void;+ /** How the engine's session files are reached; in server mode as the engine's user (S25.8, B1). */+ access?: EngineAccess;log?: (line: string) => void;}@@ -151,10 +158,15 @@ export class SessionRotator {async maybeRotate(): Promise<boolean> {if (this.rotating || !this.options.canRotate()) return false;const file = this.supervisor.sessionFile;- if (!file || !existsSync(file)) return false;+ if (!file) return false;+ const access = this.options.access ?? directAccess;const { limits } = this.options;- const { size } = statSync(file);- if (size < limits.bytes && this.compactionsIn(file, size) < limits.compactions) return false;+ const over = access(() => {+ if (!existsSync(file)) return false;+ const { size } = statSync(file);+ return size >= limits.bytes || this.compactionsIn(file, size) >= limits.compactions;+ });+ if (!over) return false;this.rotating = true;try {const state = (await this.supervisor.request({ type: "get_state" })).data as@@ -174,8 +186,13 @@ export class SessionRotator {const previous = [...this.supervisor.previousSessions, file];let seed: string;try {- seed = await writeHandoffSession(file, handoffText(file), this.options.cwd);- this.options.handOver?.([seed]);+ const access = this.options.access ?? directAccess;+ seed = await writeHandoffSession(+ file,+ access(() => handoffText(file)),+ this.options.cwd,+ access,+ );} catch (error) {this.log(`rotation skipped, the chat stays in ${file}: ${(error as Error).message}`);return false;diff --git a/packages/daemon/src/secret-file.ts b/packages/daemon/src/secret-file.tsindex 5ef083a..0c543b2 100644--- a/packages/daemon/src/secret-file.ts+++ b/packages/daemon/src/secret-file.ts@@ -10,7 +10,8 @@* File: `{"version":1,"records":{"<id>":{"nonce":"<base64>","data":"<base64>","tag":"<base64>"}}}`.*/import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";-import { readFileSync, renameSync, writeFileSync } from "node:fs";+import { readFileSync } from "node:fs";+import { writePrivateFile } from "./private-file.ts";import { type SecretSource, SecretsUnavailableError } from "./secret-source.ts";/** The daemon's environment variable with the key. */@@ -148,8 +149,6 @@ export class FileSecretSource implements SecretSource {}private write(records: Record<string, SealedRecord>): void {- const temp = `${this.options.file}.${process.pid}.tmp`;- writeFileSync(temp, `${JSON.stringify({ version: 1, records })}\n`, { mode: 0o600 });- renameSync(temp, this.options.file);+ writePrivateFile(this.options.file, `${JSON.stringify({ version: 1, records })}\n`);}}diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.tsindex 0cbdd21..7a955a5 100644--- a/packages/daemon/src/supervisor.ts+++ b/packages/daemon/src/supervisor.ts@@ -1,7 +1,8 @@import { type ChildProcess, spawn } from "node:child_process";-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, readFileSync } from "node:fs";import { join } from "node:path";import { encodeRecord, JsonlDecoder } from "./jsonl.ts";+import { writePrivateFile } from "./private-file.ts";import type { OsUser } from "./vps.ts";/** A record the agent wrote to stdout that is not a command response. */@@ -358,9 +359,7 @@ export class AgentSupervisor {private persistSession(sessionFile: string): void {mkdirSync(this.options.dataDir, { recursive: true });- const temp = `${this.stateFile}.${process.pid}.tmp`;- writeFileSync(temp, `${JSON.stringify({ sessionFile, chains: this.chains })}\n`, { mode: 0o600 });- renameSync(temp, this.stateFile);+ writePrivateFile(this.stateFile, `${JSON.stringify({ sessionFile, chains: this.chains })}\n`);}private setState(state: SupervisorState): void {diff --git a/packages/daemon/src/uploads.ts b/packages/daemon/src/uploads.tsindex 1a12ed1..cb60790 100644--- a/packages/daemon/src/uploads.ts+++ b/packages/daemon/src/uploads.ts@@ -1,5 +1,13 @@import { randomBytes } from "node:crypto";-import { createWriteStream, existsSync, readFileSync, rmdirSync, rmSync, unlinkSync } from "node:fs";+import {+ createWriteStream,+ existsSync,+ openSync,+ readFileSync,+ rmdirSync,+ rmSync,+ unlinkSync,+} from "node:fs";import { extname, join } from "node:path";import type { Readable } from "node:stream";import {@@ -9,6 +17,7 @@ import {type AttachmentRef,type UploadedFile,} from "@gentle-dot/protocol";+import { directAccess, type EngineAccess } from "./engine-access.ts";import { ensurePrivateDir } from "./isolation.ts";/** A stored file, with its absolute path. */@@ -45,8 +54,11 @@ export interface UploadStoreOptions {/** How long an upload that was never sent is kept. Default one hour. */ttlMs?: number;now?: () => number;- /** Server mode (S25.8): gives the stored files to the engine's user, which reads them. */- handOver?: (paths: string[]) => void;+ /**+ * How the store reaches the workspace; in server mode as the engine's user (S25.8, B1), so a+ * link the engine planted there leads nowhere it could not write itself.+ */+ access?: EngineAccess;}const UNSENT_TTL_MS = 60 * 60 * 1000;@@ -124,12 +136,12 @@ export class UploadStore {private readonly limits: AttachmentLimits;private readonly ttlMs: number;private readonly now: () => number;- private readonly handOver: ((paths: string[]) => void) | undefined;+ private readonly access: EngineAccess;private readonly batches = new Map<string, Batch>();constructor(options: UploadStoreOptions) {this.root = join(options.workspace, "uploads");- this.handOver = options.handOver;+ this.access = options.access ?? directAccess;this.limits = options.limits ?? ATTACHMENT_LIMITS;this.ttlMs = options.ttlMs ?? UNSENT_TTL_MS;this.now = options.now ?? Date.now;@@ -143,7 +155,7 @@ export class UploadStore {body: Readable,request: { name: string; uploadId?: string; length?: number },): Promise<UploadOutcome> {- this.prune();+ this.access(() => this.prune());const limits = this.limits;if (request.length !== undefined && request.length > limits.fileBytes) return tooLarge(limits);const uploadId = request.uploadId ?? `u_${randomBytes(16).toString("base64url")}`;@@ -174,23 +186,39 @@ export class UploadStore {if (request.length !== undefined && batch.bytes + request.length > limits.messageBytes) {return messageTooLarge(limits);}- const name = this.freeName(batch, sanitizeName(request.name));+ const name = this.access(() => this.freeName(batch, sanitizeName(request.name)));+ const path = join(batch.dir, name);+ // The folders and the file are made here, synchronously; the bytes then go to the open file.+ let fd: number;+ try {+ fd = this.access(() => {+ ensurePrivateDir(this.root);+ ensurePrivateDir(batch.dir);+ return openSync(path, "wx", 0o600);+ });+ } catch {+ if (!known) this.access(() => this.dropIfEmpty(uploadId, batch));+ return {+ ok: false,+ status: 500,+ code: "upload_failed",+ message: "The file could not be saved. Try again.",+ };+ }batch.writing.add(name);this.batches.set(uploadId, batch);- ensurePrivateDir(this.root);- ensurePrivateDir(batch.dir);- const path = join(batch.dir, name);- const written = await this.write(body, path, batch);+ const written = await this.write(body, fd, batch);batch.writing.delete(name);if (!written.ok) {batch.bytes -= written.size;- removeQuietly(path);- this.dropIfEmpty(uploadId, batch);+ this.access(() => {+ removeQuietly(path);+ this.dropIfEmpty(uploadId, batch);+ });return written.refusal;}const file: StoredFile = { name, size: written.size, mime: sniffMime(written.head), path };batch.files.set(name, file);- this.handOver?.([this.root]);return {ok: true,file: { uploadId, name, size: file.size, mime: file.mime, path: `uploads/${uploadId}/${name}` },@@ -228,12 +256,13 @@ export class UploadStore {private write(body: Readable,- path: string,+ fd: number,batch: Batch,): Promise<{ ok: true; size: number; head: Buffer } | { ok: false; size: number; refusal: UploadRefusal }> {const limits = this.limits;return new Promise((resolve) => {- const out = createWriteStream(path, { flags: "wx", mode: 0o600 });+ // An open file: nothing on the thread pool opens a path (see engine-access.ts).+ const out = createWriteStream("", { fd, autoClose: true });let size = 0;let head = Buffer.alloc(0);let ended = false;diff --git a/packages/daemon/src/vps.ts b/packages/daemon/src/vps.tsindex 32f7d88..76fa80f 100644--- a/packages/daemon/src/vps.ts+++ b/packages/daemon/src/vps.ts@@ -6,14 +6,17 @@* a third one (`GENTLE_DOT_CONNECTOR_USER`, default `dotmcp`). The data folder is the daemon's* (0711: the engine passes through it to its own folders but cannot list it); the access key,* `connectors.json`, the encrypted secrets, and the PIN hash stay the daemon's (0600), and the- * engine's folders ({@link ENGINE_DIRS}) belong to the engine's user. Files the daemon writes into- * those folders are handed over with `chown -R -P --from=<daemon> <engine>`: GNU chown walks with- * directory descriptors and never follows a link, and `--from` touches only what the daemon itself- * created.+ * engine's folders ({@link ENGINE_DIRS}) belong to the engine's user. The daemon reaches them only+ * as the engine's user (`engine-access.ts`), and signs in through a helper running as that user+ * (`auth-helper.ts`), so what it makes there is the engine's. Files an older version left there as+ * root are handed over once at start with `chown -R -P --from=<daemon> <engine>`: GNU chown walks+ * with directory descriptors and never follows a link, and `--from` touches only the daemon's files.*/import { spawnSync } from "node:child_process";import { chmodSync, lchownSync, lstatSync, mkdirSync, readdirSync, readFileSync } from "node:fs";import { join } from "node:path";+import type { AuthHelperCommand } from "./auth-helper.ts";+import type { EngineAccess } from "./engine-access.ts";import { BAD_SECRETS_KEY, NO_SECRETS_KEY, parseSecretsKey, SECRETS_KEY_VAR } from "./secret-file.ts";export interface OsUser {@@ -29,8 +32,15 @@ export interface VpsOptions {/** The connector secrets key; undefined fails closed with `secretsKeyProblem`. */secretsKey?: Buffer | undefined;secretsKeyProblem?: string;- /** Gives paths the daemon wrote in the engine's folders to the engine's user; default {@link chownHandOver}. */+ /**+ * Gives the files an older version left as root in the engine's folders to the engine's user, once+ * at start; default {@link chownHandOver}. From then on everything there is made as that user.+ */handOver?: (paths: string[]) => void;+ /** How the daemon reaches the engine's files; default `engineAccess(engine)` (tests replace it). */+ access?: EngineAccess;+ /** The sign-in helper's command line (`cli.ts --auth-helper`); without it, sign-in is off (B1). */+ authHelper?: AuthHelperCommand;}/** The engine's own folders in the data folder (`<data>/<name>`). */diff --git a/packages/daemon/src/web-pin.ts b/packages/daemon/src/web-pin.tsindex c241166..a489efe 100644--- a/packages/daemon/src/web-pin.ts+++ b/packages/daemon/src/web-pin.ts@@ -9,8 +9,9 @@* to a log. Forgotten PIN: remove the file on the server (docs/deploy-vps.md), then set a new one.*/import { randomBytes, type ScryptOptions, scrypt, timingSafeEqual } from "node:crypto";-import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { existsSync, readFileSync } from "node:fs";import { PIN_PATTERN, type PinStatus } from "@gentle-dot/protocol";+import { writePrivateFile } from "./private-file.ts";export const PIN_FILE = "web-pin.json";/** Wrong tries in a row before the PIN locks. */@@ -170,8 +171,6 @@ export class PinGate {}private save(saved: Saved): void {- const temp = `${this.file}.${process.pid}.tmp`;- writeFileSync(temp, `${JSON.stringify(saved)}\n`, { mode: 0o600 });- renameSync(temp, this.file);+ writePrivateFile(this.file, `${JSON.stringify(saved)}\n`);}}diff --git a/packages/daemon/test/engine-access.test.ts b/packages/daemon/test/engine-access.test.tsnew file mode 100644index 0000000..55dde56--- /dev/null+++ b/packages/daemon/test/engine-access.test.ts@@ -0,0 +1,100 @@+// How the root daemon reaches the engine's files in server mode (S25.8, B1): synchronously, as the+// engine's user, and never while it writes a file of its own. The root-only half of these checks runs+// in the container (vps-root.test.ts); here, the rules that hold for any user.+import {+ existsSync,+ lstatSync,+ readdirSync,+ readFileSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { engineAccess, insideEngineAccess } from "../src/engine-access.ts";+import { writePrivateFile } from "../src/private-file.ts";+import { tempDir } from "./helpers.ts";++const own = { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };+const SRC = fileURLToPath(new URL("../src/", import.meta.url));++describe("engine access", () => {+ it("runs a synchronous call and says it is inside while it runs", () => {+ const access = engineAccess(own);+ expect(insideEngineAccess()).toBe(false);+ expect(access(() => insideEngineAccess())).toBe(true);+ expect(access(() => access(() => 42))).toBe(42);+ expect(insideEngineAccess()).toBe(false);+ });++ it("refuses a call that would go on asynchronously", async () => {+ const access = engineAccess(own);+ expect(() => access(() => Promise.resolve(1))).toThrow(/synchronously/);+ expect(insideEngineAccess()).toBe(false);+ });++ it.skipIf(own.uid === 0)("refuses, without running it, a call as a user it cannot become", () => {+ let ran = false;+ expect(() =>+ engineAccess({ uid: own.uid + 1, gid: own.gid })(() => {+ ran = true;+ }),+ ).toThrow(/without root/);+ expect(ran).toBe(false);+ });+});++describe("the daemon's own files", () => {+ it("are written whole, private, and replace a link at their place without following it", () => {+ const dir = tempDir();+ const target = join(dir, "target");+ writeFileSync(target, "keep");+ symlinkSync(target, join(dir, "state.json"));+ writePrivateFile(join(dir, "state.json"), "new\n");+ expect(readFileSync(target, "utf8")).toBe("keep");+ expect(lstatSync(join(dir, "state.json")).isFile()).toBe(true);+ expect(readFileSync(join(dir, "state.json"), "utf8")).toBe("new\n");+ expect(statSync(join(dir, "state.json")).mode & 0o777).toBe(0o600);+ expect(readdirSync(dir).sort()).toEqual(["state.json", "target"]);+ });++ it("are never written inside an engine-access call, and nothing is left behind", () => {+ const dir = tempDir();+ expect(() => engineAccess(own)(() => writePrivateFile(join(dir, "token"), "x"))).toThrow(/engine's user/);+ expect(existsSync(join(dir, "token"))).toBe(false);+ expect(readdirSync(dir)).toEqual([]);+ });+});++describe("no file work on libuv's thread pool (S25.8, B1)", () => {+ // A bracket changes the ids of every thread: asynchronous file work in flight meanwhile would run+ // as the engine's user. The daemon does none, apart from the uploads' stream on an open file.+ it("imports no asynchronous file functions", () => {+ const allowed = new Set(["constants", "watch", "FSWatcher", "Stats", "Dirent"]);+ const found: string[] = [];+ for (const name of readdirSync(SRC, { recursive: true }) as string[]) {+ if (!name.endsWith(".ts")) continue;+ const text = readFileSync(join(SRC, name), "utf8");+ if (/["']node:fs\/promises["']|["']fs\/promises["']|\bfs\.promises\b/.test(text))+ found.push(`${name}: fs/promises`);+ for (const match of text.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*["'](?:node:)?fs["']/g)) {+ for (const raw of (match[1] ?? "").split(",")) {+ const imported = raw.trim().replace(/^type\s+/, "");+ if (!imported || imported.endsWith("Sync") || allowed.has(imported)) continue;+ if (imported === "createWriteStream" && name === "uploads.ts") continue;+ found.push(`${name}: ${imported}`);+ }+ }+ }+ expect(found).toEqual([]);+ });++ it("opens every upload synchronously and streams only to the open file", () => {+ const text = readFileSync(join(SRC, "uploads.ts"), "utf8");+ expect(text.match(/createWriteStream\(([^)]*)\)/g)).toEqual([+ 'createWriteStream("", { fd, autoClose: true })',+ ]);+ });+});diff --git a/packages/daemon/test/vps-auth-helper.test.ts b/packages/daemon/test/vps-auth-helper.test.tsnew file mode 100644index 0000000..be117d8--- /dev/null+++ b/packages/daemon/test/vps-auth-helper.test.ts@@ -0,0 +1,180 @@+// Server mode (S25.8, B1): the daemon runs as root, and the engine's sign-in files (`auth.json`,+// `models.json`, `settings.json`) belong to the engine's user. Pi's ModelRuntime runs a value that+// starts with `!` as a shell command, so the daemon never opens those files itself: a helper started+// as the engine's user does, and answers over IPC. On the desktop nothing changes.+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import type { ServerMessage } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import WebSocket from "ws";+import { type DaemonOptions, type DotDaemon, startDaemon } from "../src/daemon.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const CLI = fileURLToPath(new URL("../src/cli.ts", import.meta.url));+const own = { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++/** The engine's environment without a model key from the machine running the tests. */+function cleanEnv(): NodeJS.ProcessEnv {+ const env = { ...process.env };+ for (const key of ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"]) delete env[key];+ return env;+}++/** An API key that is a shell command: it records its parent process (who ran it), then prints a key. */+function plantCommandKey(agentHome: string, marker: string): void {+ mkdirSync(agentHome, { recursive: true });+ writeFileSync(+ join(agentHome, "auth.json"),+ JSON.stringify({ openai: { type: "api_key", key: `!echo $PPID > '${marker}'; echo sk-from-command` } }),+ );+}++async function setup(vps: DaemonOptions["vps"] | undefined, plant?: (agentHome: string) => void) {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ plant?.(agentHome);+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: join(dataDir, "workspace"),+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentHome,+ agentEnv: cleanEnv(),+ backoffMs: [50],+ ...(vps ? { vps } : {}),+ });+ daemons.push(d);+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);+ const messages: ServerMessage[] = [];+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ await new Promise((resolve) => ws.on("open", resolve));+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));+ await waitFor(() => messages.some((m) => m.type === "ready"));+ const send = (m: object) => ws.send(JSON.stringify(m));+ const find = <T extends ServerMessage["type"]>(+ type: T,+ where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,+ after = 0,+ ) =>+ waitFor(+ () =>+ messages+ .slice(after)+ .find(+ (m): m is Extract<ServerMessage, { type: T }> =>+ m.type === type && where(m as Extract<ServerMessage, { type: T }>),+ ),+ 15_000,+ );+ /** Signs in with an API key the way the Accounts screen does. */+ const signIn = async (providerId: string, key: string) => {+ const seen = messages.length;+ send({ type: "auth_login", providerId, method: "api_key" });+ const prompt = await find("auth_prompt", () => true, seen);+ send({ type: "auth_reply", flowId: prompt.prompt.flowId, value: key });+ return find("auth_done", (m) => m.providerId === providerId, seen);+ };+ const accounts = async () => {+ const seen = messages.length;+ send({ type: "auth_list" });+ return find("auth_providers", () => true, seen);+ };+ return { d, dataDir, agentHome, messages, send, find, signIn, accounts };+}++/** Server mode with the test's own user standing in for the engine's, and a helper the daemon starts. */+const vpsAs = (engine: { uid: number; gid: number }): NonNullable<DaemonOptions["vps"]> => ({+ engine,+ connector: own,+ handOver: () => {},+ // The daemon's own files: with the test's user there is nothing to switch to.+ access: (fn) => fn(),+ authHelper: { command: process.execPath, args: [CLI, "--auth-helper"] },+});++describe("server mode: sign-in runs as the engine's user (S25.8, B1)", () => {+ it("never runs a planted `!command` API key in the daemon's own process", async () => {+ const marker = join(tempDir(), "who-ran-it");+ const s = await setup(vpsAs(own), (home) => plantCommandKey(home, marker));+ const listed = await s.accounts();+ // The key resolved, so voice is on, but in the helper: the shell's parent is not the daemon.+ expect(listed.providers.find((p) => p.id === "openai")).toMatchObject({ configured: true });+ expect(listed.voice).toMatchObject({ transcribe: true });+ await waitFor(() => existsSync(marker));+ const parent = Number(readFileSync(marker, "utf8").trim());+ expect(parent).toBeGreaterThan(0);+ expect(parent).not.toBe(process.pid);+ });++ it("fails closed when the helper cannot start as the engine's user: nothing runs", async () => {+ // A user the test cannot become: the helper's spawn is refused, like a broken engine user.+ const marker = join(tempDir(), "who-ran-it");+ const s = await setup(vpsAs({ uid: own.uid + 1, gid: own.gid }), (home) => plantCommandKey(home, marker));+ const seen = s.messages.length;+ s.send({ type: "auth_list" });+ await waitFor(+ () => s.messages.slice(seen).find((m) => m.type === "error" || m.type === "auth_providers"),+ 15_000,+ );+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(existsSync(marker)).toBe(false);+ });++ it("signs in, lists, uses the key for voice, and signs out through the helper", async () => {+ const s = await setup(vpsAs(own));+ expect((await s.signIn("openai", "sk-helper-test-not-real")).ok).toBe(true);+ const auth = JSON.parse(readFileSync(join(s.agentHome, "auth.json"), "utf8"));+ expect(auth.openai).toMatchObject({ type: "api_key", key: "sk-helper-test-not-real" });+ const listed = await s.accounts();+ expect(listed.providers.find((p) => p.id === "openai")).toMatchObject({+ configured: true,+ source: "stored",+ });+ expect(listed.voice).toMatchObject({ transcribe: true });+ s.send({ type: "auth_logout", providerId: "openai" });+ await waitFor(() => !JSON.parse(readFileSync(join(s.agentHome, "auth.json"), "utf8")).openai);+ expect((await s.accounts()).providers.find((p) => p.id === "openai")).toMatchObject({+ configured: false,+ });+ });++ it("cancels a sign-in waiting in the helper", async () => {+ const s = await setup(vpsAs(own));+ const seen = s.messages.length;+ s.send({ type: "auth_login", providerId: "openai", method: "api_key" });+ const prompt = await s.find("auth_prompt", () => true, seen);+ s.send({ type: "auth_reply", flowId: prompt.prompt.flowId, cancelled: true });+ expect(await s.find("auth_done", () => true, seen)).toMatchObject({+ ok: false,+ message: "Sign-in cancelled.",+ });+ expect(+ existsSync(join(s.agentHome, "auth.json")) && readFileSync(join(s.agentHome, "auth.json"), "utf8"),+ ).not.toContain("openai");+ });+});++describe("on the desktop, sign-in stays in the daemon (regression)", () => {+ it("signs in with an API key, turns voice on, and signs out, with no helper", async () => {+ const s = await setup(undefined);+ expect((await s.signIn("openai", "sk-desktop-test-not-real")).ok).toBe(true);+ const listed = await s.accounts();+ expect(listed.providers.find((p) => p.id === "openai")).toMatchObject({+ configured: true,+ source: "stored",+ });+ expect(listed.voice).toMatchObject({ transcribe: true });+ s.send({ type: "auth_logout", providerId: "openai" });+ await waitFor(() => !JSON.parse(readFileSync(join(s.agentHome, "auth.json"), "utf8")).openai);+ expect((await s.accounts()).voice).toMatchObject({ transcribe: false });+ });+});diff --git a/packages/daemon/test/vps-gateway.test.ts b/packages/daemon/test/vps-gateway.test.tsindex b2b0fc6..4b3ba35 100644--- a/packages/daemon/test/vps-gateway.test.ts+++ b/packages/daemon/test/vps-gateway.test.ts@@ -52,6 +52,7 @@ async function setup(options: Setup = {}) {const stdinFile = join(dataDir, "..", `${randomBytes(6).toString("hex")}-stdin.jsonl`);const key = randomBytes(32);const handedOver: string[][] = [];+ const engineAccesses = { count: 0 };const logs: string[] = [];const notionCalls: string[] = [];const notionUrl = await fakeNotion(notionCalls);@@ -65,6 +66,11 @@ async function setup(options: Setup = {}) {connector: own,secretsKey: key,handOver: (paths: string[]) => handedOver.push(paths),+ // With the test's own user there is no one to switch to; count what goes through it.+ access: <T>(fn: () => T): T => {+ engineAccesses.count++;+ return fn();+ },...options.vps,};const d = await startDaemon({@@ -123,6 +129,7 @@ async function setup(options: Setup = {}) {app,logs,handedOver,+ engineAccesses,notionCalls,engineProcess,stdin,@@ -213,13 +220,13 @@ describe("server mode: the engine as another user (S25.8)", () => {await waitFor(() => d.supervisor.state === "ready");expect(engineProcess()).toMatchObject({ uid: own.uid });// A uid this test process cannot take: the spawn itself is refused, so the uid is applied.- const other = await setup({ vps: { engine: { uid: own.uid + 1, gid: own.gid } } });+ const other = await setup({ vps: { engine: { uid: own.uid + 1, gid: own.gid }, access: (fn) => fn() } });await waitFor(() => other.logs.some((line) => /EPERM|agent failed to start/.test(line)));expect(other.d.supervisor.state).not.toBe("ready");});- it("keeps the daemon's files private and hands the engine's folders to the engine user", async () => {- const { d, dataDir, agentHome, handedOver, send, find } = await setup();+ it("keeps the daemon's files private and reaches the engine's folders only as the engine user", async () => {+ const { d, dataDir, handedOver, engineAccesses, send, find } = await setup();await waitFor(() => d.supervisor.state === "ready");// The engine may pass through the data folder to its own folders, but not list it.expect(statSync(dataDir).mode & 0o777).toBe(0o711);@@ -227,26 +234,24 @@ describe("server mode: the engine as another user (S25.8)", () => {// The engine reads its identity prompt by name.expect(statSync(join(dataDir, "identity.md")).mode & 0o777).toBe(0o644);for (const dir of ENGINE_DIRS) expect(statSync(join(dataDir, dir)).isDirectory(), dir).toBe(true);- // At start every engine folder, and before every launch the ones the daemon writes into.+ // Only at start, for files an older version left as root; from then on the engine's user makes them.+ expect(handedOver).toHaveLength(1);expect(handedOver[0]?.slice().sort()).toEqual(ENGINE_DIRS.map((dir) => join(dataDir, dir)).sort());- expect(- handedOver.some((paths) => paths.includes(agentHome) && paths.includes(join(dataDir, "sessions"))),- ).toBe(true);- const launches = handedOver.length;await d.supervisor.restart();- expect(handedOver.length).toBeGreaterThan(launches);- // An uploaded file is the engine's to read.+ expect(handedOver).toHaveLength(1);+ // An upload and a profile change reach the engine's folders only through the engine's user (B1).+ let before = engineAccesses.count;const upload = await fetch(`http://127.0.0.1:${d.port}/upload`, {method: "POST",headers: { authorization: `Bearer ${d.token}`, "x-file-name": "notes.txt" },body: "hello",});expect(upload.status).toBe(200);- expect(handedOver.at(-1)).toEqual([join(dataDir, "workspace", "uploads")]);- // So is what a profile change writes into its store and the engine's home.+ expect(engineAccesses.count).toBeGreaterThan(before);+ before = engineAccesses.count;send({ type: "profile_save", name: "work", roles: {} });await find("profiles");- expect(handedOver.at(-1)).toEqual([join(dataDir, "gentle-ai"), agentHome]);+ expect(engineAccesses.count).toBeGreaterThan(before);// Nothing of the daemon's own is ever handed over.const handed = handedOver.flat();for (const name of [diff --git a/packages/daemon/test/vps-root.test.ts b/packages/daemon/test/vps-root.test.tsnew file mode 100644index 0000000..807f54a--- /dev/null+++ b/packages/daemon/test/vps-root.test.ts@@ -0,0 +1,221 @@+// Server mode as it runs in the container (S25.8, B1): these tests need root and real engine and+// connector users, so they run only inside the image (docs/design.md §8, server mode):+// GENTLE_DOT_TEST_ENGINE_USER=dot GENTLE_DOT_TEST_CONNECTOR_USER=dotmcp vitest run <this file>+// Everywhere else they are skipped. The engine's user plants links and commands in its own files+// before the daemon starts; the root daemon must never run, read, or write through them.+import { randomBytes } from "node:crypto";+import {+ chmodSync,+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import type { ServerMessage } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import WebSocket from "ws";+import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { engineAccess } from "../src/engine-access.ts";+import { writePrivateFile } from "../src/private-file.ts";+import { lookupUser } from "../src/vps.ts";+import { FAKE_AGENT, waitFor } from "./helpers.ts";++const CLI = fileURLToPath(new URL("../src/cli.ts", import.meta.url));+const ENGINE_USER = process.env.GENTLE_DOT_TEST_ENGINE_USER;+const CONNECTOR_USER = process.env.GENTLE_DOT_TEST_CONNECTOR_USER;+const asRoot = process.getuid?.() === 0 && ENGINE_USER !== undefined && CONNECTOR_USER !== undefined;+const ENGINE_DIRS = ["agent", "home", "workspace", "sessions", "gentle-ai"];++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++/** A folder only root can enter, with a root file in it that must never change or leak. */+function rootSecret(name: string, content: object) {+ const dir = mkdtempSync(join(tmpdir(), "root-only-"));+ chmodSync(dir, 0o700);+ const file = join(dir, name);+ writeFileSync(file, JSON.stringify(content), { mode: 0o600 });+ return { dir, file, text: readFileSync(file, "utf8") };+}++/** Every regular file in the engine's folders, with its owner and text. */+function engineFiles(dataDir: string): { path: string; uid: number; text: string }[] {+ const out: { path: string; uid: number; text: string }[] = [];+ const walk = (dir: string) => {+ for (const name of readdirSync(dir)) {+ const path = join(dir, name);+ const stat = lstatSync(path);+ if (stat.isDirectory()) walk(path);+ else if (stat.isFile()) out.push({ path, uid: stat.uid, text: readFileSync(path, "latin1") });+ }+ };+ for (const name of ENGINE_DIRS) if (existsSync(join(dataDir, name))) walk(join(dataDir, name));+ return out;+}++async function setup(plant: (dataDir: string, engineUid: number) => void = () => {}) {+ const engine = lookupUser(ENGINE_USER ?? "", readFileSync("/etc/passwd", "utf8"));+ const connector = lookupUser(CONNECTOR_USER ?? "", readFileSync("/etc/passwd", "utf8"));+ const dataDir = mkdtempSync(join(tmpdir(), "gentle-dot-root-"));+ for (const name of ENGINE_DIRS) mkdirSync(join(dataDir, name), { recursive: true });+ plant(dataDir, engine.uid);+ const env = { ...process.env };+ delete env.OPENAI_API_KEY;+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: join(dataDir, "workspace"),+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentHome: join(dataDir, "agent"),+ agentEnv: env,+ backoffMs: [50],+ vps: {+ engine,+ connector,+ secretsKey: randomBytes(32),+ authHelper: { command: process.execPath, args: [CLI, "--auth-helper"] },+ },+ });+ daemons.push(d);+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);+ const messages: ServerMessage[] = [];+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ await new Promise((resolve) => ws.on("open", resolve));+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));+ await waitFor(() => messages.some((m) => m.type === "ready"));+ const send = (m: object) => ws.send(JSON.stringify(m));+ const after = (seen: number, pick: (m: ServerMessage) => boolean) =>+ waitFor(() => messages.slice(seen).find(pick), 20_000);+ return { d, dataDir, engine, messages, send, after };+}++const settle = (ms = 500) => new Promise((resolve) => setTimeout(resolve, ms));++describe.runIf(asRoot)("engine access as root: the kernel enforces the engine's user", () => {+ const capEff = () => /^CapEff:\s*(\S+)$/m.exec(readFileSync("/proc/self/status", "utf8"))?.[1];++ it("cannot read a root file, makes files as the engine's user, and gets root and its capabilities back", () => {+ const engine = lookupUser(ENGINE_USER ?? "", readFileSync("/etc/passwd", "utf8"));+ const secret = rootSecret("secret.json", { root: "only" });+ const open = mkdtempSync(join(tmpdir(), "engine-"));+ chmodSync(open, 0o1777);+ const before = capEff();+ const access = engineAccess(engine);+ const seen = access(() => {+ let read: string;+ try {+ read = readFileSync(secret.file, "utf8");+ } catch (error) {+ read = (error as NodeJS.ErrnoException).code ?? "error";+ }+ writeFileSync(join(open, "made"), "x");+ return { read, euid: process.geteuid?.(), capEff: capEff() };+ });+ expect(seen).toEqual({ read: "EACCES", euid: engine.uid, capEff: "0000000000000000" });+ expect(statSync(join(open, "made")).uid).toBe(engine.uid);+ expect(process.geteuid?.()).toBe(0);+ expect(capEff()).toBe(before);+ });++ it("refuses to write a root file inside a bracket, and leaves nothing behind", () => {+ const engine = lookupUser(ENGINE_USER ?? "", readFileSync("/etc/passwd", "utf8"));+ const dir = mkdtempSync(join(tmpdir(), "root-files-"));+ chmodSync(dir, 0o1777);+ expect(() => engineAccess(engine)(() => writePrivateFile(join(dir, "token"), "x"))).toThrow();+ expect(readdirSync(dir)).toEqual([]);+ writePrivateFile(join(dir, "token"), "x");+ expect(statSync(join(dir, "token")).uid).toBe(0);+ });+});++describe.runIf(asRoot)("server mode as root: the daemon never acts on the engine's files as root", () => {+ it("a planted `!command` API key runs only as the engine's user, never as root", async () => {+ const drop = mkdtempSync(join(tmpdir(), "drop-"));+ chmodSync(drop, 0o1777);+ const marker = join(drop, "who");+ const s = await setup((dataDir) =>+ writeFileSync(+ join(dataDir, "agent", "auth.json"),+ JSON.stringify({ openai: { type: "api_key", key: `!id -u > '${marker}'; echo sk-x` } }),+ ),+ );+ await waitFor(() => s.d.supervisor.state === "ready", 20_000);+ const seen = s.messages.length;+ s.send({ type: "auth_list" });+ await s.after(seen, (m) => m.type === "auth_providers" || m.type === "error");+ await settle();+ // It ran (the helper resolved the key for voice), and as the engine's user, never as root.+ await waitFor(() => existsSync(marker), 5000);+ expect(readFileSync(marker, "utf8").trim()).toBe(String(s.engine.uid));+ expect(statSync(marker).uid).toBe(s.engine.uid);+ // Nothing the daemon wrote in the engine's folders is root's.+ expect(+ engineFiles(s.dataDir)+ .filter((f) => f.uid === 0)+ .map((f) => f.path),+ ).toEqual([]);+ });++ it("a link at auth.json never makes root write through it or copy the target", async () => {+ const target = rootSecret("auth.json", { anthropic: { type: "api_key", key: "root-only-auth-secret" } });+ const s = await setup((dataDir) => symlinkSync(target.file, join(dataDir, "agent", "auth.json")));+ await waitFor(() => s.d.supervisor.state === "ready", 20_000);+ const seen = s.messages.length;+ s.send({ type: "auth_login", providerId: "openai", method: "api_key" });+ const prompt = await s.after(seen, (m) => m.type === "auth_prompt");+ if (prompt.type !== "auth_prompt") throw new Error("no prompt");+ s.send({ type: "auth_reply", flowId: prompt.prompt.flowId, value: "sk-new-not-real" });+ await s.after(seen, (m) => m.type === "auth_done");+ await settle();+ expect(readFileSync(target.file, "utf8")).toBe(target.text);+ expect(statSync(target.file).uid).toBe(0);+ expect(engineFiles(s.dataDir).filter((f) => f.text.includes("root-only-auth-secret"))).toEqual([]);+ });++ it("a link at settings.json never makes root copy its target when the model changes", async () => {+ const target = rootSecret("settings.json", { rootOnly: "root-only-settings-secret" });+ const s = await setup((dataDir) => symlinkSync(target.file, join(dataDir, "agent", "settings.json")));+ await waitFor(() => s.d.supervisor.state === "ready", 20_000);+ const seen = s.messages.length;+ s.send({ type: "model_set", provider: "fake", id: "fake-fast" });+ await s.after(seen, (m) => m.type === "models" || m.type === "error");+ await settle();+ expect(readFileSync(target.file, "utf8")).toBe(target.text);+ expect(engineFiles(s.dataDir).filter((f) => f.text.includes("root-only-settings-secret"))).toEqual([]);+ });++ it("a link at the workspace's memory setting never makes root write through it", async () => {+ const target = rootSecret("config.json", { keep: "root-only-config" });+ await setup((dataDir) => {+ mkdirSync(join(dataDir, "workspace", ".engram"), { recursive: true });+ symlinkSync(target.file, join(dataDir, "workspace", ".engram", "config.json"));+ });+ expect(readFileSync(target.file, "utf8")).toBe(target.text);+ });++ it("an uploads folder that is a link never makes root write into its target", async () => {+ const target = rootSecret("keep.json", {});+ const s = await setup((dataDir) => symlinkSync(target.dir, join(dataDir, "workspace", "uploads")));+ const response = await fetch(`http://127.0.0.1:${s.d.port}/upload`, {+ method: "POST",+ headers: { authorization: `Bearer ${s.d.token}`, "x-file-name": "notes.txt" },+ body: "hello",+ });+ expect(response.ok).toBe(false);+ expect(readdirSync(target.dir)).toEqual(["keep.json"]);+ expect(statSync(target.dir).mode & 0o777).toBe(0o700);+ });+});