diff --git a/cli/src/__tests__/open.test.ts b/cli/src/__tests__/open.test.ts index 8ab50fbcc05..5ea609418e3 100644 --- a/cli/src/__tests__/open.test.ts +++ b/cli/src/__tests__/open.test.ts @@ -1,68 +1,130 @@ -import { mkdtempSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { readLocalOperatorKey, verifyLocalOperatorSignInLink } from "@paperclipai/shared/local-operator-credential"; -import { buildLocalBoardSignInUrl } from "../commands/open.js"; +import { + buildLocalBoardSignInUrl, + instanceIdForConfigPath, + localBoardEntryUrl, + resolveLocalBoardTarget, + resolveOpenApiBase, +} from "../commands/open.js"; +import { writeRuntimeInfo } from "../runtime-info.js"; + +let home: string; +const saved = { + home: process.env.PAPERCLIP_HOME, + instance: process.env.PAPERCLIP_INSTANCE_ID, + config: process.env.PAPERCLIP_CONFIG, + mode: process.env.PAPERCLIP_DEPLOYMENT_MODE, +}; + +function writeInstanceConfig(instanceId: string, deploymentMode: "local_trusted" | "authenticated"): string { + const configPath = path.join(home, "instances", instanceId, "config.json"); + mkdirSync(path.dirname(configPath), { recursive: true }); + writeFileSync(configPath, JSON.stringify({ + $meta: { version: 1, updatedAt: "2026-01-01T00:00:00.000Z", source: "configure" }, + database: { + mode: "embedded-postgres", + embeddedPostgresDataDir: "/tmp/paperclip-db", + embeddedPostgresPort: 54329, + backup: { enabled: true, intervalMinutes: 60, retentionDays: 30, dir: "/tmp/paperclip-backups" }, + }, + logging: { mode: "file", logDir: "/tmp/paperclip-logs" }, + server: { deploymentMode, exposure: "private", host: "127.0.0.1", port: 3100, allowedHostnames: [], serveUi: true }, + auth: { baseUrlMode: "auto", disableSignUp: false }, + telemetry: { enabled: true }, + storage: { + provider: "local_disk", + localDisk: { baseDir: "/tmp/paperclip-storage" }, + s3: { bucket: "paperclip", region: "us-east-1", prefix: "", forcePathStyle: false }, + }, + secrets: { provider: "local_encrypted", strictMode: false, localEncrypted: { keyFilePath: "/tmp/paperclip-secrets/master.key" } }, + })); + return configPath; +} + +beforeEach(() => { + home = mkdtempSync(path.join(os.tmpdir(), "paperclip-open-")); + process.env.PAPERCLIP_HOME = home; + delete process.env.PAPERCLIP_INSTANCE_ID; + delete process.env.PAPERCLIP_CONFIG; + delete process.env.PAPERCLIP_DEPLOYMENT_MODE; +}); + +afterEach(() => { + for (const [key, value] of [ + ["PAPERCLIP_HOME", saved.home], + ["PAPERCLIP_INSTANCE_ID", saved.instance], + ["PAPERCLIP_CONFIG", saved.config], + ["PAPERCLIP_DEPLOYMENT_MODE", saved.mode], + ] as const) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(home, { recursive: true, force: true }); +}); describe("paperclipai open", () => { it("builds a sign-in link the local server accepts", () => { - const dir = mkdtempSync(path.join(os.tmpdir(), "paperclip-open-")); - try { - const keyPath = path.join(dir, "local-operator.key"); - const url = new URL(buildLocalBoardSignInUrl("http://localhost:3100", keyPath)); - expect(url.origin).toBe("http://localhost:3100"); - expect(url.pathname).toBe("/api/local-operator/sign-in"); - const link = { nonce: url.searchParams.get("n"), expiresAt: url.searchParams.get("e"), signature: url.searchParams.get("s") }; - expect(verifyLocalOperatorSignInLink(readLocalOperatorKey(keyPath)!, link)).toBe(true); - } finally { - rmSync(dir, { recursive: true, force: true }); - } + const keyPath = path.join(home, "local-operator.key"); + const url = new URL(buildLocalBoardSignInUrl("http://localhost:3100", keyPath)); + expect(url.origin).toBe("http://localhost:3100"); + expect(url.pathname).toBe("/api/local-operator/sign-in"); + const link = { nonce: url.searchParams.get("n"), expiresAt: url.searchParams.get("e"), signature: url.searchParams.get("s") }; + expect(verifyLocalOperatorSignInLink(readLocalOperatorKey(keyPath)!, link)).toBe(true); }); it("refuses to sign in to a Paperclip that is not on this computer", () => { - expect(() => buildLocalBoardSignInUrl("https://paperclip.example.com", "/nonexistent/key")).toThrow(/not local/); - expect(() => buildLocalBoardSignInUrl("http://127.attacker.example:3100", "/nonexistent/key")).toThrow(/not local/); - expect(() => buildLocalBoardSignInUrl("http://localhost.attacker.example:3100", "/nonexistent/key")).toThrow(/not local/); + const keyPath = path.join(home, "unused.key"); + expect(() => buildLocalBoardSignInUrl("https://paperclip.example.com", keyPath)).toThrow(/not local/); + expect(() => buildLocalBoardSignInUrl("http://127.attacker.example:3100", keyPath)).toThrow(/not local/); + expect(() => buildLocalBoardSignInUrl("http://localhost.attacker.example:3100", keyPath)).toThrow(/not local/); }); -}); -describe("paperclipai open instance selection", () => { - it("uses the instance that a config file belongs to", async () => { - const { instanceIdForConfigPath } = await import("../commands/open.js"); + it("uses the instance that a config file belongs to", () => { expect(instanceIdForConfigPath("/home/me/.paperclip/instances/foo/config.json", "/home/me/.paperclip")).toBe("foo"); expect(instanceIdForConfigPath("/elsewhere/config.json", "/home/me/.paperclip")).toBeNull(); }); - it("prefers the running server's address to the configured port", async () => { - const { resolveOpenApiBase } = await import("../commands/open.js"); - const home = mkdtempSync(path.join(os.tmpdir(), "paperclip-open-home-")); - const previous = process.env.PAPERCLIP_HOME; - process.env.PAPERCLIP_HOME = home; - try { - const { writeRuntimeInfo } = await import("../runtime-info.js"); - writeRuntimeInfo({ - schemaVersion: 1, instanceId: "foo", pid: process.pid, host: "127.0.0.1", port: 3191, - dashboardUrl: "http://127.0.0.1:3191", startedAt: new Date().toISOString(), + it("signs a named instance in with that instance's own key and mode", () => { + writeInstanceConfig("default", "authenticated"); + const fooConfig = writeInstanceConfig("foo", "local_trusted"); + for (const target of [resolveLocalBoardTarget({ instance: "foo" }), resolveLocalBoardTarget({ config: fooConfig })]) { + expect(target).toMatchObject({ + instanceId: "foo", + configPath: fooConfig, + keyPath: path.join(home, "instances", "foo", "secrets", "local-operator.key"), + deploymentMode: "local_trusted", }); - expect(resolveOpenApiBase({}, "foo")).toBe("http://127.0.0.1:3191"); - expect(resolveOpenApiBase({ apiBase: "http://localhost:4000/" }, "foo")).toBe("http://localhost:4000"); - } finally { - if (previous === undefined) delete process.env.PAPERCLIP_HOME; - else process.env.PAPERCLIP_HOME = previous; - rmSync(home, { recursive: true, force: true }); + expect(new URL(localBoardEntryUrl("http://127.0.0.1:3100", target)).pathname).toBe("/api/local-operator/sign-in"); } + const defaultTarget = resolveLocalBoardTarget({ instance: "default" }); + expect(defaultTarget.deploymentMode).toBe("authenticated"); + expect(localBoardEntryUrl("http://127.0.0.1:3100", defaultTarget)).toBe("http://127.0.0.1:3100"); }); -}); -describe("paperclipai open on a board with accounts", () => { - it("reads the board's mode from its config", async () => { - const { configDeploymentMode } = await import("../commands/open.js"); - const dir = mkdtempSync(path.join(os.tmpdir(), "paperclip-open-config-")); - try { - expect(configDeploymentMode(path.join(dir, "missing.json"))).toBeNull(); - } finally { - rmSync(dir, { recursive: true, force: true }); - } + it("follows the server's deployment mode override from the environment", () => { + writeInstanceConfig("default", "local_trusted"); + process.env.PAPERCLIP_DEPLOYMENT_MODE = "authenticated"; + expect(resolveLocalBoardTarget({ instance: "default" }).deploymentMode).toBe("authenticated"); + }); + + it("reports a config file it cannot read instead of guessing the mode", () => { + const configPath = path.join(home, "instances", "broken", "config.json"); + mkdirSync(path.dirname(configPath), { recursive: true }); + writeFileSync(configPath, "{ not json"); + expect(() => resolveLocalBoardTarget({ config: configPath })).toThrow(); + }); + + it("prefers the running server's address to the configured port", () => { + writeRuntimeInfo({ + schemaVersion: 1, instanceId: "foo", pid: process.pid, host: "127.0.0.1", port: 3191, + dashboardUrl: "http://127.0.0.1:3191", startedAt: new Date().toISOString(), + }); + const target = { instanceId: "foo", configPath: path.join(home, "instances", "foo", "config.json") }; + expect(resolveOpenApiBase({}, target)).toBe("http://127.0.0.1:3191"); + expect(resolveOpenApiBase({ apiBase: "http://localhost:4000/" }, target)).toBe("http://localhost:4000"); }); }); diff --git a/cli/src/commands/open.ts b/cli/src/commands/open.ts index fa7721fe3d3..a7c878c4add 100644 --- a/cli/src/commands/open.ts +++ b/cli/src/commands/open.ts @@ -2,16 +2,17 @@ import { isIPv4 } from "node:net"; import path from "node:path"; import type { Command } from "commander"; import pc from "picocolors"; +import { DEPLOYMENT_MODES, type DeploymentMode } from "@paperclipai/shared"; import { createLocalOperatorSignInLink, ensureLocalOperatorKey, localOperatorSignInUrl, - resolveLocalOperatorKeyPath, + resolveLocalOperatorKeyPathForConfig, } from "@paperclipai/shared/local-operator-credential"; import { openUrl } from "../client/board-auth.js"; -import { resolvePaperclipHomeDir, resolvePaperclipInstanceId } from "../config/home.js"; +import { resolveDefaultConfigPath, resolvePaperclipHomeDir, resolvePaperclipInstanceId } from "../config/home.js"; +import { readConfig, resolveConfigPath } from "../config/store.js"; import { readRuntimeInfo } from "../runtime-info.js"; -import { readConfig } from "../config/store.js"; import { inferApiBaseFromConfig, normalizeApiBase } from "./client/common.js"; interface OpenOptions { @@ -21,6 +22,13 @@ interface OpenOptions { browser?: boolean; } +export interface LocalBoardTarget { + configPath: string; + instanceId: string; + keyPath: string; + deploymentMode: DeploymentMode; +} + function isLoopbackBase(apiBase: string): boolean { try { const host = new URL(apiBase).hostname.replace(/^\[|\]$/g, "").toLowerCase(); @@ -47,46 +55,59 @@ export function instanceIdForConfigPath(configPath: string, homeDir = resolvePap return path.basename(directory); } -export function resolveOpenInstanceId(opts: Pick): string { - if (opts.instance?.trim()) return resolvePaperclipInstanceId(opts.instance); - const fromConfig = opts.config ? instanceIdForConfigPath(opts.config) : null; - return resolvePaperclipInstanceId(fromConfig ?? undefined); +/** The deployment mode the server resolves: the environment first, then the config file. */ +export function resolveConfigDeploymentMode(configPath: string): DeploymentMode { + const fromEnv = process.env.PAPERCLIP_DEPLOYMENT_MODE; + if (fromEnv && DEPLOYMENT_MODES.includes(fromEnv as DeploymentMode)) return fromEnv as DeploymentMode; + return readConfig(configPath)?.server?.deploymentMode ?? "local_trusted"; +} + +/** + * Resolves the board `open` signs in to, the same way the server finds its own + * config: `--config`, else `--instance`, else the environment and working + * directory. The key sits next to that config file. + */ +export function resolveLocalBoardTarget(opts: Pick = {}): LocalBoardTarget { + const instanceOverride = opts.instance?.trim() ? resolvePaperclipInstanceId(opts.instance) : null; + const configPath = opts.config?.trim() + ? path.resolve(opts.config) + : instanceOverride ? resolveDefaultConfigPath(instanceOverride) : resolveConfigPath(); + const instanceId = instanceOverride ?? instanceIdForConfigPath(configPath) ?? resolvePaperclipInstanceId(); + return { + configPath, + instanceId, + keyPath: resolveLocalOperatorKeyPathForConfig(configPath), + deploymentMode: resolveConfigDeploymentMode(configPath), + }; } /** The running server's address for an instance, or the configured one when it is not running. */ -export function resolveOpenApiBase(opts: OpenOptions, instanceId: string): string { +export function resolveOpenApiBase(opts: Pick, target: Pick): string { if (opts.apiBase?.trim()) return normalizeApiBase(opts.apiBase); - const runtime = readRuntimeInfo(instanceId); + const runtime = readRuntimeInfo(target.instanceId); if (runtime && processIsRunning(runtime.pid)) return normalizeApiBase(runtime.dashboardUrl); - return inferApiBaseFromConfig(opts.config); + return inferApiBaseFromConfig(target.configPath); } /** Builds a one-time link that signs this computer's browser in to the local board. */ -export function buildLocalBoardSignInUrl(apiBase: string, keyPath = resolveLocalOperatorKeyPath()): string { +export function buildLocalBoardSignInUrl(apiBase: string, keyPath: string): string { if (!isLoopbackBase(apiBase)) { throw new Error(`\`paperclipai open\` signs in to a Paperclip running on this computer; ${apiBase} is not local.`); } return localOperatorSignInUrl(apiBase, createLocalOperatorSignInLink(ensureLocalOperatorKey(keyPath))); } -/** The sign-in link for a local board, or the board's plain address when one cannot be made. */ -export function localBoardEntryUrl(dashboardUrl: string, instanceId = resolvePaperclipInstanceId()): string { +/** The sign-in link for a local_trusted board, or the board's plain address when one cannot be made. */ +export function localBoardEntryUrl(dashboardUrl: string, target?: LocalBoardTarget): string { try { - return buildLocalBoardSignInUrl(dashboardUrl, resolveLocalOperatorKeyPath({ instanceId })); + const board = target ?? resolveLocalBoardTarget(); + if (board.deploymentMode !== "local_trusted") return dashboardUrl; + return buildLocalBoardSignInUrl(dashboardUrl, board.keyPath); } catch { return dashboardUrl; } } -/** Boards that use accounts sign in on their own page, so they open without a link. */ -export function configDeploymentMode(configPath?: string): string | null { - try { - return readConfig(configPath)?.server?.deploymentMode ?? null; - } catch { - return null; - } -} - export function registerOpenCommand(program: Command): void { program .command("open") @@ -95,18 +116,19 @@ export function registerOpenCommand(program: Command): void { .option("-d, --data-dir ", "Paperclip data directory root (isolates state from ~/.paperclip)") .option("-i, --instance ", "Local instance id (default: the instance of --config, else default)") .option("--api-base ", "Base URL of the local Paperclip server") - .option("--no-browser", "Print the sign-in link instead of opening a browser") + .option("--no-browser", "Print the link instead of opening a browser") .action(async (opts: OpenOptions) => { - const instanceId = resolveOpenInstanceId(opts); - const apiBase = resolveOpenApiBase(opts, instanceId); - const url = configDeploymentMode(opts.config) === "authenticated" - ? apiBase - : buildLocalBoardSignInUrl(apiBase, resolveLocalOperatorKeyPath({ instanceId })); + const target = resolveLocalBoardTarget(opts); + const apiBase = resolveOpenApiBase(opts, target); + const signIn = target.deploymentMode === "local_trusted"; + const url = signIn ? buildLocalBoardSignInUrl(apiBase, target.keyPath) : apiBase; if (opts.browser !== false && await openUrl(url)) { console.error(pc.dim("Opened the Paperclip board in your browser.")); return; } - console.error("Open this link in your browser within 10 minutes to sign in to the board:"); + console.error(signIn + ? "Open this link in your browser within 10 minutes to sign in to the board:" + : "Open the board in your browser and sign in with your account:"); console.log(url); }); } diff --git a/doc/DEPLOYMENT-MODES.md b/doc/DEPLOYMENT-MODES.md index 4a4d1f1b27c..134c33d9d2f 100644 --- a/doc/DEPLOYMENT-MODES.md +++ b/doc/DEPLOYMENT-MODES.md @@ -84,11 +84,11 @@ Paperclip now treats **bind** as a separate concern from auth: - no human login flow - optimized for fastest local startup - implicit board access belongs to the operator's own local processes. On Linux and macOS, a request that comes from inside an agent run's process tree receives no implicit board access and must authenticate with the run's own credentials. On Linux, a request whose process the server cannot inspect receives implicit board access only when every same-user process that the server cannot inspect has a readable operator parent chain outside any agent run. Requests over IPv4 and IPv6 loopback are covered. If the platform has no process inspection, or `/proc/net/tcp` and `/proc/net/tcp6` cannot be read, the server keeps the previous behavior and logs a warning. Other platforms keep the previous behavior. -- the process check identifies agent runs by their process tree and run markers. A process that an agent run detaches from its tree and starts with an empty environment carries neither, so on its own the check cannot stop it. Set `PAPERCLIP_LOCAL_OPERATOR_CREDENTIAL=required` to close that gap: implicit board access then also requires the operator credential. The process check still applies. Any value other than `off`, `false`, `0` or `no` turns the credential on; the server logs a warning for a value it does not recognize. - - the operator credential is a key in `/secrets/local-operator.key`. The server creates it with owner-only permissions on first use and restores those permissions on an existing key. Agent environments never receive it. +- the process check identifies agent runs by their process tree and run markers. A process that an agent run detaches from its tree and starts with an empty environment carries neither, so on its own the check cannot stop it. Set `PAPERCLIP_LOCAL_OPERATOR_CREDENTIAL=required` to close that gap: implicit board access then also requires the operator credential. The process check still applies. Any value other than `off`, `false`, `0` or `no`, including an empty one, turns the credential on; the server logs a warning for a value it does not recognize. + - the operator credential is a key in `secrets/local-operator.key` next to the instance's config file (`/secrets/local-operator.key` for the standard layout). The server and `paperclipai open` find the same file whether the instance was chosen with `--instance`, `--config` or the environment. The server creates it with owner-only permissions on first use and restores those permissions on an existing key. Agent environments never receive it. - browsers sign in through a one-time link that expires after 10 minutes. `paperclipai onboard`, and any server started with `PAPERCLIP_OPEN_ON_LISTEN=true`, open the board with that link. `paperclipai open` opens a fresh link for the running server, or prints it with `--no-browser`. Use `--instance ` or `--config ` to pick a named instance. A browser that is not signed in sees a screen that asks the operator to run `paperclipai open`. - the link gives the board page a token through the URL fragment. The page keeps the token in its own origin's storage and sends it on its own requests and on its live-events socket. Pages served by other local servers cannot read it, even on the same host name. - - browsers send cookies to every port on a host, so a cookie is never a board credential. The sign-in also sets an `HttpOnly`, `SameSite=Strict` cookie, named per instance, that allows only the downloads and plugin event streams the browser loads directly. + - browsers send cookies to every port on a host, so a cookie never grants board actions. The sign-in also sets an `HttpOnly`, `SameSite=Strict` cookie, named per instance, that only lets the browser read attachments, assets and workspace files it loads directly, and plugin event streams. Any local server the browser visits can receive that cookie. Its value rotates and stops working within a day, and the board page renews it with its header token. - the CLI and local assistants use a board key. Run `paperclipai auth login`, approve the request in the signed-in browser, and the CLI stores the key. - agent-run code running as the same OS user can still read the operator's files. Run agents with a filesystem sandbox that hides `~/.paperclip/instances//secrets`, or as a separate OS user, when you need that boundary to hold against a deliberate attempt. diff --git a/packages/shared/src/local-operator-credential.ts b/packages/shared/src/local-operator-credential.ts index 77a985763fb..9bc59055013 100644 --- a/packages/shared/src/local-operator-credential.ts +++ b/packages/shared/src/local-operator-credential.ts @@ -27,6 +27,15 @@ export function resolveLocalOperatorKeyPath(input: { homeDir?: string; instanceI return path.resolve(resolvePaperclipInstanceRoot(input), "secrets", "local-operator.key"); } +/** + * The key sits next to the instance's config file, so the server and the CLI + * find the same key however the instance was chosen (`--instance`, `--config`, + * or the environment). For the standard layout this is the instance root. + */ +export function resolveLocalOperatorKeyPathForConfig(configPath: string): string { + return path.resolve(path.dirname(configPath), "secrets", "local-operator.key"); +} + function sign(key: Buffer, purpose: string): string { return createHmac("sha256", key).update(purpose).digest("base64url"); } @@ -83,20 +92,33 @@ export function verifyLocalOperatorBrowserToken(key: Buffer, value: string | nul /** * Cookies are not isolated by port, so any local server the browser visits - * receives them. The cookie is therefore a separate, read-only credential for - * the few downloads the browser loads directly. Its name is per instance so - * two local boards do not sign each other out. + * can receive them. The cookie is therefore a separate, read-only credential + * for the files the browser loads directly, and it rotates: a value is valid + * for one window and the next, so a copied cookie stops working within a day. + * The board page refreshes it with its header token. Its name is per instance + * so two local boards do not sign each other out. */ +export const LOCAL_OPERATOR_READ_COOKIE_WINDOW_MS = 12 * 60 * 60 * 1000; export function localOperatorReadCookieName(key: Buffer): string { return `paperclip_local_operator_${sign(key, COOKIE_NAME_PURPOSE).replace(/[^A-Za-z0-9]/g, "").slice(0, 10)}`; } -export function localOperatorReadCookieValue(key: Buffer): string { - return `r1.${sign(key, READ_COOKIE_PURPOSE)}`; +function readCookieWindow(now: number): number { + return Math.floor(now / LOCAL_OPERATOR_READ_COOKIE_WINDOW_MS); } -export function verifyLocalOperatorReadCookieValue(key: Buffer, value: string | null | undefined): boolean { - return typeof value === "string" && sameValue(value, localOperatorReadCookieValue(key)); +function readCookieForWindow(key: Buffer, window: number): string { + return `r2.${window}.${sign(key, `${READ_COOKIE_PURPOSE}:${window}`)}`; +} + +export function localOperatorReadCookieValue(key: Buffer, now = Date.now()): string { + return readCookieForWindow(key, readCookieWindow(now)); +} + +export function verifyLocalOperatorReadCookieValue(key: Buffer, value: string | null | undefined, now = Date.now()): boolean { + if (typeof value !== "string") return false; + const current = readCookieWindow(now); + return sameValue(value, readCookieForWindow(key, current)) || sameValue(value, readCookieForWindow(key, current - 1)); } export interface LocalOperatorSignInLink { @@ -138,15 +160,16 @@ const REQUIRED_VALUES = new Set(["required", "require", "on", "true", "1", "yes" const OFF_VALUES = new Set(["off", "false", "0", "no"]); /** - * Reads the setting. An unset value returns null. Any other value that is not - * an explicit "off" returns "required", so a typo never removes the protection. + * Reads the setting. Only an unset variable returns null. Any other value that + * is not an explicit "off", including a blank one, returns "required", so a + * typo or an empty placeholder never removes the protection. */ export function parseLocalOperatorCredentialMode(value: string | undefined): { mode: LocalOperatorCredentialMode; recognized: boolean; } | null { - const normalized = value?.trim().toLowerCase(); - if (!normalized) return null; + if (value === undefined) return null; + const normalized = value.trim().toLowerCase(); if (OFF_VALUES.has(normalized)) return { mode: "off", recognized: true }; return { mode: "required", recognized: REQUIRED_VALUES.has(normalized) }; } diff --git a/server/src/__tests__/local-operator-credential-wiring.test.ts b/server/src/__tests__/local-operator-credential-wiring.test.ts index cf9c12ab9b6..7631e3ee55b 100644 --- a/server/src/__tests__/local-operator-credential-wiring.test.ts +++ b/server/src/__tests__/local-operator-credential-wiring.test.ts @@ -10,23 +10,36 @@ import { ensureLocalOperatorKey, localOperatorBrowserToken, parseLocalOperatorCredentialMode, - resolveLocalOperatorKeyPath, + localOperatorReadCookieValue, + resolveLocalOperatorKeyPathForConfig, + verifyLocalOperatorReadCookieValue, + LOCAL_OPERATOR_READ_COOKIE_WINDOW_MS, } from "@paperclipai/shared/local-operator-credential"; describe("the local operator credential setting", () => { it("requires the credential for every value except an explicit off, so a typo keeps the protection", () => { - for (const value of ["required", "1", "yes", "true", "on", "requird"]) { + for (const value of ["required", "1", "yes", "true", "on", "requird", "", " "]) { expect(parseLocalOperatorCredentialMode(value)?.mode).toBe("required"); } expect(parseLocalOperatorCredentialMode("requird")?.recognized).toBe(false); for (const value of ["off", "0", "no", "false"]) { expect(parseLocalOperatorCredentialMode(value)?.mode).toBe("off"); } - expect(parseLocalOperatorCredentialMode("")).toBeNull(); expect(parseLocalOperatorCredentialMode(undefined)).toBeNull(); }); }); +describe("the read cookie", () => { + it("stops working within two rotation windows, so a copied cookie expires", () => { + const key = Buffer.alloc(32, 3); + const issued = 1_000 * LOCAL_OPERATOR_READ_COOKIE_WINDOW_MS + 1; + const value = localOperatorReadCookieValue(key, issued); + expect(verifyLocalOperatorReadCookieValue(key, value, issued)).toBe(true); + expect(verifyLocalOperatorReadCookieValue(key, value, issued + LOCAL_OPERATOR_READ_COOKIE_WINDOW_MS)).toBe(true); + expect(verifyLocalOperatorReadCookieValue(key, value, issued + 2 * LOCAL_OPERATOR_READ_COOKIE_WINDOW_MS)).toBe(false); + }); +}); + describe.skipIf(process.platform === "win32")("an existing operator key file", () => { it("is made readable by its owner only", () => { const dir = mkdtempSync(path.join(os.tmpdir(), "paperclip-operator-key-")); @@ -51,6 +64,7 @@ describe.skipIf(process.platform !== "linux" && process.platform !== "darwin")( home: process.env.PAPERCLIP_HOME, instance: process.env.PAPERCLIP_INSTANCE_ID, mode: process.env.PAPERCLIP_LOCAL_OPERATOR_CREDENTIAL, + config: process.env.PAPERCLIP_CONFIG, }; beforeAll(() => { @@ -58,7 +72,9 @@ describe.skipIf(process.platform !== "linux" && process.platform !== "darwin")( process.env.PAPERCLIP_HOME = home; process.env.PAPERCLIP_INSTANCE_ID = "default"; process.env.PAPERCLIP_LOCAL_OPERATOR_CREDENTIAL = "required"; - const keyPath = resolveLocalOperatorKeyPath(); + // The server keeps the key next to the config file it runs from. + process.env.PAPERCLIP_CONFIG = path.join(home, "instances", "default", "config.json"); + const keyPath = resolveLocalOperatorKeyPathForConfig(process.env.PAPERCLIP_CONFIG); mkdirSync(path.dirname(keyPath), { recursive: true }); token = localOperatorBrowserToken(ensureLocalOperatorKey(keyPath)); vi.resetModules(); @@ -69,6 +85,7 @@ describe.skipIf(process.platform !== "linux" && process.platform !== "darwin")( ["PAPERCLIP_HOME", saved.home], ["PAPERCLIP_INSTANCE_ID", saved.instance], ["PAPERCLIP_LOCAL_OPERATOR_CREDENTIAL", saved.mode], + ["PAPERCLIP_CONFIG", saved.config], ] as const) { if (value === undefined) delete process.env[key]; else process.env[key] = value; diff --git a/server/src/__tests__/local-operator-credential.test.ts b/server/src/__tests__/local-operator-credential.test.ts index 4283f8f2d26..a580443138e 100644 --- a/server/src/__tests__/local-operator-credential.test.ts +++ b/server/src/__tests__/local-operator-credential.test.ts @@ -190,13 +190,27 @@ describe.skipIf(!supported)("operator browser sign-in", () => { "/api/attachments/a1/content", "/api/assets/s1/content", "/api/issues/i1/file-resources/content?path=a.txt", - "/api/heartbeat-runs/r1/provider-trace/download", - "/api/companies/c1/audit/agent-actions.csv", "/api/plugins/p1/bridge/stream/updates?companyId=c1", ]) { const response = await fetch(`${base}${file}`, { headers: { cookie } }); expect(await response.json()).toEqual({ type: "board", source: "local_implicit" }); } + // The page downloads these with `fetch`, so they need its header token. + for (const file of ["/api/heartbeat-runs/r1/provider-trace/download", "/api/companies/c1/audit/agent-actions.csv"]) { + const response = await fetch(`${base}${file}`, { headers: { cookie } }); + expect(await response.json()).toEqual({ type: "none", source: "none" }); + } + }); + + it("renews the read cookie only for the board page that holds the header token", async () => { + const { token } = await signIn(); + expect((await fetch(`${base}/api/local-operator/read-cookie`, { method: "POST" })).status).toBe(403); + const renewed = await fetch(`${base}/api/local-operator/read-cookie`, { + method: "POST", + headers: { [LOCAL_OPERATOR_HEADER]: token }, + }); + expect(renewed.status).toBe(204); + expect(renewed.headers.get("set-cookie")).toMatch(/HttpOnly/i); }); it("accepts each sign-in link only once", async () => { diff --git a/server/src/middleware/local-operator-credential.ts b/server/src/middleware/local-operator-credential.ts index 6423a960363..f0c8c78f994 100644 --- a/server/src/middleware/local-operator-credential.ts +++ b/server/src/middleware/local-operator-credential.ts @@ -12,28 +12,29 @@ import { localOperatorReadCookieValue, localOperatorSignInUrl, parseLocalOperatorCredentialMode, - resolveLocalOperatorKeyPath, + LOCAL_OPERATOR_READ_COOKIE_WINDOW_MS, + resolveLocalOperatorKeyPathForConfig, verifyLocalOperatorBrowserToken, verifyLocalOperatorReadCookieValue, verifyLocalOperatorSignInLink, type LocalOperatorCredentialMode, } from "@paperclipai/shared/local-operator-credential"; import { logger } from "./logger.js"; +import { resolvePaperclipConfigPath } from "../paths.js"; -const COOKIE_MAX_AGE_MS = 400 * 24 * 60 * 60 * 1000; +const COOKIE_MAX_AGE_MS = 2 * LOCAL_OPERATOR_READ_COOKIE_WINDOW_MS; const DEFAULT_MODE: LocalOperatorCredentialMode = "off"; /** * Requests the browser makes on its own, without the board page's script: - * file downloads, images and plugin event streams. Only these accept the - * read-only cookie. + * images and file links, and plugin event streams. Only these accept the + * read-only cookie. Downloads the page starts with `fetch` carry the header + * token instead and are not listed. */ -const DIRECT_BROWSER_READ_PATHS = [ +export const DIRECT_BROWSER_READ_PATHS = [ /^\/api\/attachments\/[^/]+\/content$/, /^\/api\/assets\/[^/]+\/content$/, /^\/api\/issues\/[^/]+\/file-resources\/content$/, - /^\/api\/heartbeat-runs\/[^/]+\/provider-trace\/download$/, - /^\/api\/companies\/[^/]+\/audit\/agent-actions\.csv$/, /^\/api\/plugins\/[^/]+\/bridge\/stream\/[^/]+$/, ]; @@ -76,7 +77,9 @@ export function createLocalOperatorCredential(options: LocalOperatorCredentialOp const usedNonces = new Map(); function operatorKey(): Buffer { - key ??= ensureLocalOperatorKey(options.keyPath ?? resolveLocalOperatorKeyPath()); + key ??= ensureLocalOperatorKey( + options.keyPath ?? resolveLocalOperatorKeyPathForConfig(resolvePaperclipConfigPath()), + ); return key; } @@ -124,8 +127,28 @@ export function createLocalOperatorCredential(options: LocalOperatorCredentialOp return true; } + function setReadCookie(res: Response) { + const operator = operatorKey(); + res.cookie(localOperatorReadCookieName(operator), localOperatorReadCookieValue(operator), { + httpOnly: true, + sameSite: "strict", + path: "/api", + maxAge: COOKIE_MAX_AGE_MS, + }); + } + function signInRoutes() { const router = Router(); + // The board page renews its rotating read cookie with its header token. + router.post("/local-operator/read-cookie", (req: Request, res: Response) => { + res.setHeader("Cache-Control", "no-store"); + if (!hasOperatorHeader(req.headers)) { + res.status(403).json({ error: "Local operator sign-in required" }); + return; + } + setReadCookie(res); + res.status(204).end(); + }); router.get("/local-operator/sign-in", (req: Request, res: Response) => { res.setHeader("Cache-Control", "no-store"); res.setHeader("Referrer-Policy", "no-referrer"); @@ -142,12 +165,7 @@ export function createLocalOperatorCredential(options: LocalOperatorCredentialOp return; } const operator = operatorKey(); - res.cookie(localOperatorReadCookieName(operator), localOperatorReadCookieValue(operator), { - httpOnly: true, - sameSite: "strict", - path: "/api", - maxAge: COOKIE_MAX_AGE_MS, - }); + setReadCookie(res); // The fragment never reaches a server. The board page moves the token // into storage that only its own origin can read. const fragment = `${LOCAL_OPERATOR_FRAGMENT_KEY}=${encodeURIComponent(localOperatorBrowserToken(operator))}`; diff --git a/ui/src/lib/local-operator.test.ts b/ui/src/lib/local-operator.test.ts index dbd5a7e411c..d0c45d497b7 100644 --- a/ui/src/lib/local-operator.test.ts +++ b/ui/src/lib/local-operator.test.ts @@ -58,3 +58,20 @@ describe("a board opened on a wildcard address", () => { } }); }); + +describe("the read cookie refresh", () => { + it("renews the cookie for a signed-in board and does nothing otherwise", async () => { + const calls: string[] = []; + const target = { + fetch: vi.fn(async (input: RequestInfo | URL) => { calls.push(String(input)); return new Response(null, { status: 204 }); }), + setInterval: vi.fn(() => 1), + clearInterval: vi.fn(), + } as unknown as typeof globalThis; + const { startLocalOperatorReadCookieRefresh } = await import("./local-operator"); + startLocalOperatorReadCookieRefresh(target)(); + expect(calls).toEqual([]); + window.localStorage.setItem("paperclip.localOperatorToken", "v1.token"); + startLocalOperatorReadCookieRefresh(target)(); + expect(calls).toEqual(["/api/local-operator/read-cookie"]); + }); +}); diff --git a/ui/src/lib/local-operator.ts b/ui/src/lib/local-operator.ts index c11d6bd0a59..df5ee0081e0 100644 --- a/ui/src/lib/local-operator.ts +++ b/ui/src/lib/local-operator.ts @@ -74,3 +74,19 @@ export function withLocalOperatorSocketToken(url: string): string { parsed.searchParams.set(LOCAL_OPERATOR_SOCKET_PARAM, token); return parsed.toString(); } + +const READ_COOKIE_REFRESH_MS = 4 * 60 * 60 * 1000; + +/** + * Keeps the rotating read cookie current for images and file links, which the + * browser loads without this page's header. Runs only for a signed-in board. + */ +export function startLocalOperatorReadCookieRefresh(target: typeof globalThis = globalThis): () => void { + if (!localOperatorToken()) return () => {}; + const refresh = () => { + void target.fetch("/api/local-operator/read-cookie", { method: "POST", credentials: "same-origin" }).catch(() => {}); + }; + refresh(); + const timer = target.setInterval(refresh, READ_COOKIE_REFRESH_MS); + return () => target.clearInterval(timer); +} diff --git a/ui/src/main.tsx b/ui/src/main.tsx index df4968d5ecf..1005f72453d 100644 --- a/ui/src/main.tsx +++ b/ui/src/main.tsx @@ -37,12 +37,13 @@ import { captureQueryException } from "./lib/sentry"; import { startPersistedQueryCache } from "./lib/persisted-query-cache"; import { adoptHardLoadChatBootstrap } from "./lib/issue-chat-bootstrap"; import { hasPendingWrites, subscribePendingWrites } from "./lib/reload-safety"; -import { captureLocalOperatorToken, installLocalOperatorFetch } from "./lib/local-operator"; +import { captureLocalOperatorToken, installLocalOperatorFetch, startLocalOperatorReadCookieRefresh } from "./lib/local-operator"; import "@mdxeditor/editor/style.css"; import "./index.css"; captureLocalOperatorToken(); installLocalOperatorFetch(); +startLocalOperatorReadCookieRefresh(); initPluginBridge(React, ReactDOM); // React 19.2 emits an unbounded stream of performance.measure() entries for its