From dc29f45d47d0ba08d55a1cb0293a1578f858d032 Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 14 Nov 2026 14:30:49 -0600 Subject: [PATCH] feat(local): let the local board require an operator credential In local_trusted mode, board access for uncredentialed loopback requests can now require an operator credential (PAPERCLIP_LOCAL_OPERATOR_CREDENTIAL=required). Browsers sign in once through a one-time link from `paperclipai open` or onboarding and keep an HttpOnly, SameSite=Strict cookie; the CLI and local assistants use board keys from `paperclipai auth login`. Agent environments never receive the credential, and the process-boundary check still applies. Co-Authored-By: Claude Opus 5.5 --- cli/src/__tests__/open.test.ts | 26 +++ cli/src/commands/open.ts | 54 +++++ cli/src/index.ts | 2 + doc/DEPLOYMENT-MODES.md | 6 + .../shared/src/local-operator-credential.ts | 109 +++++++++ .../local-operator-credential.test.ts | 213 ++++++++++++++++++ server/src/app.ts | 2 + server/src/index.ts | 13 +- server/src/middleware/auth.ts | 14 +- server/src/middleware/board-mutation-guard.ts | 5 +- .../middleware/local-operator-credential.ts | 129 +++++++++++ server/src/realtime/live-events-ws.ts | 13 ++ server/src/routes/health.ts | 10 + server/src/types/express.d.ts | 2 + skills/paperclip-board/SKILL.md | 2 +- ui/src/api/health.ts | 2 + ui/src/components/CloudAccessGate.test.tsx | 11 + ui/src/components/CloudAccessGate.tsx | 21 ++ 18 files changed, 626 insertions(+), 8 deletions(-) create mode 100644 cli/src/__tests__/open.test.ts create mode 100644 cli/src/commands/open.ts create mode 100644 packages/shared/src/local-operator-credential.ts create mode 100644 server/src/__tests__/local-operator-credential.test.ts create mode 100644 server/src/middleware/local-operator-credential.ts diff --git a/cli/src/__tests__/open.test.ts b/cli/src/__tests__/open.test.ts new file mode 100644 index 00000000000..bcf71e5a5ba --- /dev/null +++ b/cli/src/__tests__/open.test.ts @@ -0,0 +1,26 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { readLocalOperatorKey, verifyLocalOperatorSignInLink } from "@paperclipai/shared/local-operator-credential"; +import { buildLocalBoardSignInUrl } from "../commands/open.js"; + +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 }); + } + }); + + 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/); + }); +}); diff --git a/cli/src/commands/open.ts b/cli/src/commands/open.ts new file mode 100644 index 00000000000..ce05a126b6d --- /dev/null +++ b/cli/src/commands/open.ts @@ -0,0 +1,54 @@ +import type { Command } from "commander"; +import pc from "picocolors"; +import { + createLocalOperatorSignInLink, + ensureLocalOperatorKey, + localOperatorSignInUrl, + resolveLocalOperatorKeyPath, +} from "@paperclipai/shared/local-operator-credential"; +import { openUrl } from "../client/board-auth.js"; +import { readContext, resolveProfile } from "../client/context.js"; +import { resolveApiBase, type BaseClientOptions } from "./client/common.js"; + +interface OpenOptions extends Pick { + browser?: boolean; +} + +function isLoopbackBase(apiBase: string): boolean { + try { + const host = new URL(apiBase).hostname.replace(/^\[|\]$/g, "").toLowerCase(); + return host === "localhost" || host === "::1" || host.startsWith("127."); + } catch { + return false; + } +} + +/** Builds a one-time link that signs this computer's browser in to the local board. */ +export function buildLocalBoardSignInUrl(apiBase: string, keyPath = resolveLocalOperatorKeyPath()): 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))); +} + +export function registerOpenCommand(program: Command): void { + program + .command("open") + .description("Open the local Paperclip board in your browser, signed in as the operator") + .option("-c, --config ", "Path to Paperclip config file") + .option("-d, --data-dir ", "Paperclip data directory root (isolates state from ~/.paperclip)") + .option("--context ", "Path to CLI context file") + .option("--profile ", "CLI context profile name") + .option("--api-base ", "Base URL of the local Paperclip server") + .option("--no-browser", "Print the sign-in link instead of opening a browser") + .action(async (opts: OpenOptions) => { + const { profile } = resolveProfile(readContext(opts.context), opts.profile); + const url = buildLocalBoardSignInUrl(resolveApiBase(opts, profile)); + 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.log(url); + }); +} diff --git a/cli/src/index.ts b/cli/src/index.ts index 61cc6e54039..f4e16b364e3 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -34,6 +34,7 @@ import { initTelemetryFromConfigFile, flushTelemetry } from "./telemetry.js"; import { registerWorktreeCommands } from "./commands/worktree.js"; import { registerPluginCommands } from "./commands/client/plugin.js"; import { registerClientAuthCommands } from "./commands/client/auth.js"; +import { registerOpenCommand } from "./commands/open.js"; import { registerConnectCommand } from "./commands/client/connect.js"; import { registerTokenCommands } from "./commands/client/token.js"; import { registerPromptCommands } from "./commands/client/prompt.js"; @@ -278,6 +279,7 @@ auth .action(bootstrapCeoInvite); registerClientAuthCommands(auth); +registerOpenCommand(program); registerMcpCommands(program); async function main(): Promise { diff --git a/doc/DEPLOYMENT-MODES.md b/doc/DEPLOYMENT-MODES.md index eb8791aaf2a..b14e2abedc0 100644 --- a/doc/DEPLOYMENT-MODES.md +++ b/doc/DEPLOYMENT-MODES.md @@ -84,6 +84,12 @@ 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. + - the operator credential is a key in `/secrets/local-operator.key`. The server creates it with owner-only permissions on first use, and 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, or prints it with `--no-browser`. The link sets a long-lived `HttpOnly`, `SameSite=Strict` cookie. A browser without the cookie sees a screen that asks the operator to run `paperclipai open`. + - a signed-in browser's changes must come from the board's own origin. A page served on another local port cannot use that browser's cookie to make changes or to open the live-events socket. + - 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. ## `authenticated + private` diff --git a/packages/shared/src/local-operator-credential.ts b/packages/shared/src/local-operator-credential.ts new file mode 100644 index 00000000000..48586ad1d90 --- /dev/null +++ b/packages/shared/src/local-operator-credential.ts @@ -0,0 +1,109 @@ +import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { resolvePaperclipInstanceRoot } from "./home-paths.js"; + +/** + * The local operator credential proves that a request to a `local_trusted` + * instance comes from the human operator rather than from agent-run code on + * the same machine. It is derived from a key file in the instance directory + * that agent environments never receive. + */ +export const LOCAL_OPERATOR_COOKIE_NAME = "paperclip_local_operator"; +export const LOCAL_OPERATOR_SIGN_IN_PATH = "/api/local-operator/sign-in"; +export const LOCAL_OPERATOR_SIGN_IN_TTL_MS = 10 * 60 * 1000; +export const LOCAL_OPERATOR_CREDENTIAL_ENV = "PAPERCLIP_LOCAL_OPERATOR_CREDENTIAL"; + +const KEY_BYTES = 32; +const COOKIE_PURPOSE = "paperclip-local-operator-browser-v1"; + +export function resolveLocalOperatorKeyPath(input: { homeDir?: string; instanceId?: string } = {}): string { + return path.resolve(resolvePaperclipInstanceRoot(input), "secrets", "local-operator.key"); +} + +function sign(key: Buffer, purpose: string): string { + return createHmac("sha256", key).update(purpose).digest("base64url"); +} + +function sameValue(a: string, b: string): boolean { + const left = Buffer.from(a); + const right = Buffer.from(b); + return left.length === right.length && timingSafeEqual(left, right); +} + +export function readLocalOperatorKey(keyPath: string): Buffer | null { + try { + const key = Buffer.from(fs.readFileSync(keyPath, "utf8").trim(), "base64url"); + return key.length === KEY_BYTES ? key : null; + } catch { + return null; + } +} + +/** Returns the operator key, creating it with owner-only permissions on first use. */ +export function ensureLocalOperatorKey(keyPath: string): Buffer { + const existing = readLocalOperatorKey(keyPath); + if (existing) return existing; + fs.mkdirSync(path.dirname(keyPath), { recursive: true, mode: 0o700 }); + const key = randomBytes(KEY_BYTES); + try { + fs.writeFileSync(keyPath, `${key.toString("base64url")}\n`, { mode: 0o600, flag: "wx" }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + const winner = readLocalOperatorKey(keyPath); + if (!winner) throw new Error(`The local operator key at ${keyPath} is unreadable`); + return winner; + } + return key; +} + +export function localOperatorCookieValue(key: Buffer): string { + return `v1.${sign(key, COOKIE_PURPOSE)}`; +} + +export function verifyLocalOperatorCookieValue(key: Buffer, value: string | null | undefined): boolean { + return typeof value === "string" && sameValue(value, localOperatorCookieValue(key)); +} + +export interface LocalOperatorSignInLink { + nonce: string; + expiresAt: number; + signature: string; +} + +export function createLocalOperatorSignInLink(key: Buffer, now = Date.now()): LocalOperatorSignInLink { + const nonce = randomBytes(16).toString("base64url"); + const expiresAt = now + LOCAL_OPERATOR_SIGN_IN_TTL_MS; + return { nonce, expiresAt, signature: sign(key, `sign-in:${nonce}:${expiresAt}`) }; +} + +export function localOperatorSignInUrl(baseUrl: string, link: LocalOperatorSignInLink, next = "/"): string { + const url = new URL(LOCAL_OPERATOR_SIGN_IN_PATH, baseUrl); + url.searchParams.set("n", link.nonce); + url.searchParams.set("e", String(link.expiresAt)); + url.searchParams.set("s", link.signature); + if (next !== "/") url.searchParams.set("next", next); + return url.toString(); +} + +export function verifyLocalOperatorSignInLink( + key: Buffer, + link: { nonce: unknown; expiresAt: unknown; signature: unknown }, + now = Date.now(), +): boolean { + const { nonce, signature } = link; + const expiresAt = Number(link.expiresAt); + if (typeof nonce !== "string" || typeof signature !== "string" || !Number.isSafeInteger(expiresAt)) return false; + if (expiresAt < now || expiresAt > now + LOCAL_OPERATOR_SIGN_IN_TTL_MS) return false; + return sameValue(signature, sign(key, `sign-in:${nonce}:${expiresAt}`)); +} + +export type LocalOperatorCredentialMode = "required" | "off"; + +export function parseLocalOperatorCredentialMode(value: string | undefined): LocalOperatorCredentialMode | null { + const normalized = value?.trim().toLowerCase(); + if (!normalized) return null; + if (normalized === "required" || normalized === "on" || normalized === "true") return "required"; + if (normalized === "off" || normalized === "false") return "off"; + return null; +} diff --git a/server/src/__tests__/local-operator-credential.test.ts b/server/src/__tests__/local-operator-credential.test.ts new file mode 100644 index 00000000000..3dd14a7af7c --- /dev/null +++ b/server/src/__tests__/local-operator-credential.test.ts @@ -0,0 +1,213 @@ +import { spawn } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, statSync, existsSync } from "node:fs"; +import type { AddressInfo } from "node:net"; +import type { Server } from "node:http"; +import os from "node:os"; +import path from "node:path"; +import express from "express"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import type { Db } from "@paperclipai/db"; +import { + LOCAL_OPERATOR_COOKIE_NAME, + ensureLocalOperatorKey, + readLocalOperatorKey, +} from "@paperclipai/shared/local-operator-credential"; +import { actorMiddleware } from "../middleware/auth.js"; +import { boardMutationGuard } from "../middleware/board-mutation-guard.js"; +import { createLocalAgentProcessBoundary } from "../middleware/local-agent-process-boundary.js"; +import { + createLocalOperatorCredential, + type LocalOperatorCredential, +} from "../middleware/local-operator-credential.js"; + +const supported = process.platform === "linux" || process.platform === "darwin"; +const AGENT_MARKERS = ["PAPERCLIP_RUN_ID", "PAPERCLIP_AGENT_ID", "PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_RUNNER_INSTANCE_ID"]; + +function startServer(operator: LocalOperatorCredential): Promise<{ server: Server; base: string }> { + const serverEnvironment = { ...process.env }; + for (const key of AGENT_MARKERS) delete serverEnvironment[key]; + const app = express(); + app.use("/api", operator.signInRoutes()); + app.use(actorMiddleware({} as Db, { + deploymentMode: "local_trusted", + localAgentProcessBoundary: createLocalAgentProcessBoundary({ serverEnvironment }), + localOperatorCredential: operator, + })); + app.use(boardMutationGuard()); + const whoami = (req: express.Request, res: express.Response) => { + res.json({ type: req.actor.type, source: req.actor.source ?? null }); + }; + app.get("/api/whoami", whoami); + app.post("/api/whoami", whoami); + return new Promise((resolve) => { + const server = app.listen(0, "127.0.0.1", () => { + const { port } = server.address() as AddressInfo; + resolve({ server, base: `http://127.0.0.1:${port}` }); + }); + }); +} + +/** + * Starts a process that looks like an agent run, then has it launch a fully + * detached child (its own session, re-parented once the run exits) with an + * empty environment. Only that detached child calls the server. + */ +function callFromDetachedEnvClearedAgentChild(url: string, outFile: string): Promise<{ type: string; source: string | null }> { + const detachedChild = [ + "fetch(process.argv[1]).then(r => r.text())", + ".then(t => require('fs').writeFileSync(process.argv[2], t))", + ".catch(e => require('fs').writeFileSync(process.argv[2], JSON.stringify({ error: String(e) })))", + ].join(""); + const agentRun = [ + "const { spawn } = require('child_process');", + "const child = spawn(process.execPath, ['-e', process.argv[1], process.argv[2], process.argv[3]],", + " { detached: true, stdio: 'ignore', env: {} });", + "child.unref();", + ].join("\n"); + return new Promise((resolve, reject) => { + const run = spawn(process.execPath, ["-e", agentRun, detachedChild, url, outFile], { + env: { ...process.env, PAPERCLIP_RUN_ID: "run-1", PAPERCLIP_AGENT_ID: "agent-1" }, + stdio: "ignore", + }); + run.on("error", reject); + run.on("exit", () => { + const deadline = Date.now() + 20_000; + const poll = () => { + if (existsSync(outFile)) { + const text = readFileSync(outFile, "utf8"); + if (text) { + resolve(JSON.parse(text)); + return; + } + } + if (Date.now() > deadline) reject(new Error("detached child never answered")); + else setTimeout(poll, 50); + }; + poll(); + }); + }); +} + +describe.skipIf(!supported)("local board access for a detached agent child with a cleared environment", () => { + let dir: string; + beforeAll(() => { + dir = mkdtempSync(path.join(os.tmpdir(), "paperclip-operator-")); + }); + afterAll(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + it("is granted board access when only the process check guards the board (the gap)", async () => { + const operator = createLocalOperatorCredential({ mode: "off", keyPath: path.join(dir, "off.key") }); + const { server, base } = await startServer(operator); + try { + const result = await callFromDetachedEnvClearedAgentChild(`${base}/api/whoami`, path.join(dir, "off.json")); + expect(result).toEqual({ type: "board", source: "local_implicit" }); + } finally { + server.close(); + } + }); + + it("is refused once the board requires the operator credential", async () => { + const operator = createLocalOperatorCredential({ mode: "required", keyPath: path.join(dir, "required.key") }); + const { server, base } = await startServer(operator); + try { + const result = await callFromDetachedEnvClearedAgentChild(`${base}/api/whoami`, path.join(dir, "required.json")); + expect(result).toEqual({ type: "none", source: "none" }); + } finally { + server.close(); + } + }); +}); + +describe.skipIf(!supported)("operator browser sign-in", () => { + let dir: string; + let operator: LocalOperatorCredential; + let server: Server; + let base: string; + + beforeAll(async () => { + dir = mkdtempSync(path.join(os.tmpdir(), "paperclip-operator-")); + operator = createLocalOperatorCredential({ mode: "required", keyPath: path.join(dir, "secrets", "local-operator.key") }); + ({ server, base } = await startServer(operator)); + }); + afterAll(() => { + server.close(); + rmSync(dir, { recursive: true, force: true }); + }); + + async function signIn(): Promise { + const response = await fetch(operator.signInUrl(base), { redirect: "manual" }); + expect(response.status).toBe(303); + expect(response.headers.get("location")).toBe("/"); + const setCookie = response.headers.get("set-cookie") ?? ""; + expect(setCookie).toMatch(/HttpOnly/i); + expect(setCookie).toMatch(/SameSite=Strict/i); + return setCookie.split(";")[0]!; + } + + it("keeps the operator key private to the operator's account", () => { + operator.signInUrl(base); + expect(statSync(path.join(dir, "secrets", "local-operator.key")).mode & 0o077).toBe(0); + }); + + it("refuses a request that carries no operator credential", async () => { + const response = await fetch(`${base}/api/whoami`); + expect(await response.json()).toEqual({ type: "none", source: "none" }); + }); + + it("grants board access to a browser that signed in through the operator's link", async () => { + const cookie = await signIn(); + const response = await fetch(`${base}/api/whoami`, { headers: { cookie } }); + expect(await response.json()).toEqual({ type: "board", source: "local_implicit" }); + }); + + it("accepts each sign-in link only once", async () => { + const url = operator.signInUrl(base); + expect((await fetch(url, { redirect: "manual" })).status).toBe(303); + expect((await fetch(url, { redirect: "manual" })).status).toBe(403); + }); + + it("refuses a forged or stale browser credential and a tampered link", async () => { + const forged = await fetch(`${base}/api/whoami`, { headers: { cookie: `${LOCAL_OPERATOR_COOKIE_NAME}=v1.forged` } }); + expect(await forged.json()).toEqual({ type: "none", source: "none" }); + const tampered = new URL(operator.signInUrl(base)); + tampered.searchParams.set("e", String(Date.now() + 60_000)); + expect((await fetch(tampered, { redirect: "manual" })).status).toBe(403); + }); + + it("only accepts the signed-in browser's changes from the board's own pages", async () => { + const cookie = await signIn(); + const sameOrigin = await fetch(`${base}/api/whoami`, { method: "POST", headers: { cookie, origin: base } }); + expect(sameOrigin.status).toBe(200); + const otherLocalPage = await fetch(`${base}/api/whoami`, { + method: "POST", + headers: { cookie, origin: "http://localhost:5173" }, + }); + expect(otherLocalPage.status).toBe(403); + }); + + it("returns to a page on the board after signing in, never another site", async () => { + const next = new URL(operator.signInUrl(base, "/issues")); + expect((await fetch(next, { redirect: "manual" })).headers.get("location")).toBe("/issues"); + const offsite = new URL(operator.signInUrl(base)); + offsite.searchParams.set("next", "//evil.example"); + // The signature covers only the nonce and expiry, so the redirect target is sanitized instead. + expect((await fetch(offsite, { redirect: "manual" })).headers.get("location")).toBe("/"); + }); +}); + +describe("operator key file", () => { + it("is created once and reused", () => { + const dir = mkdtempSync(path.join(os.tmpdir(), "paperclip-operator-")); + try { + const keyPath = path.join(dir, "secrets", "local-operator.key"); + expect(readLocalOperatorKey(keyPath)).toBeNull(); + const first = ensureLocalOperatorKey(keyPath); + expect(ensureLocalOperatorKey(keyPath).equals(first)).toBe(true); + expect(readLocalOperatorKey(keyPath)?.equals(first)).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/server/src/app.ts b/server/src/app.ts index a3682ea2a26..8135fb9b21a 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -79,6 +79,7 @@ import type { StorageService } from "./storage/types.js"; import { httpLogger, errorHandler } from "./middleware/index.js"; import { skillAccessRequestContext } from "./services/skill-access.js"; import { actorMiddleware } from "./middleware/auth.js"; +import { localOperatorCredential } from "./middleware/local-operator-credential.js"; import { boardMutationGuard } from "./middleware/board-mutation-guard.js"; import { privateHostnameGuard, @@ -614,6 +615,7 @@ export async function createApp( // board/agent bearer authentication. Mount before actorMiddleware so its // per-session Bearer cannot be mistaken for an agent API key. app.use(voiceWebhookRoutes(db, chatChannels.voice)); + if (opts.deploymentMode === "local_trusted") app.use("/api", localOperatorCredential().signInRoutes()); app.use( actorMiddleware(db, { deploymentMode: opts.deploymentMode, diff --git a/server/src/index.ts b/server/src/index.ts index 340b576632c..bd2503f02d6 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -155,6 +155,7 @@ import { import { getOperatorSettingDefaults } from "./services/setting-defaults.js"; import { setupEnvironmentCustomImageTerminalWebSocketServer } from "./realtime/environment-custom-image-terminal-ws.js"; import { setupLiveEventsWebSocketServer } from "./realtime/live-events-ws.js"; +import { localOperatorCredential } from "./middleware/local-operator-credential.js"; import { cloudActorHeaderSourceFromHeaders, resolveCloudTenantActor } from "./middleware/auth.js"; import { feedbackService, @@ -2162,14 +2163,16 @@ async function startServerWithDatabaseTeardown( }); if (process.env.PAPERCLIP_OPEN_ON_LISTEN === "true") { const openHost = config.host === "0.0.0.0" || config.host === "::" ? "127.0.0.1" : config.host; - const url = `http://${openHost}:${listenPort}`; + const boardUrl = `http://${openHost}:${listenPort}`; + const operator = config.deploymentMode === "local_trusted" ? localOperatorCredential() : null; + const url = operator?.required ? operator.signInUrl(boardUrl) : boardUrl; void import("open") .then((mod) => mod.default(url)) .then(() => { - logger.info(`Opened browser at ${url}`); + logger.info(`Opened browser at ${boardUrl}`); }) .catch((err) => { - logger.warn({ err, url }, "Failed to open browser on startup"); + logger.warn({ err, url: boardUrl }, "Failed to open browser on startup"); }); } printStartupBanner({ @@ -2190,6 +2193,10 @@ async function startServerWithDatabaseTeardown( databaseBackupRetentionDays: config.databaseBackupRetentionDays, databaseBackupDir: config.databaseBackupDir, }); + if (config.deploymentMode === "local_trusted" && localOperatorCredential().required + && process.env.PAPERCLIP_OPEN_ON_LISTEN !== "true") { + console.log(" Open the board from this computer with `paperclipai open`."); + } const boardClaimUrl = getBoardClaimWarningUrl(config.host, listenPort); if (boardClaimUrl) { const red = "\x1b[41m\x1b[30m"; diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts index b8106d6fdb3..16a58eb55cc 100644 --- a/server/src/middleware/auth.ts +++ b/server/src/middleware/auth.ts @@ -29,6 +29,7 @@ import { isUuidLike, normalizeAgentApiKeyScope, type DeploymentMode } from "@pap import type { BetterAuthSessionResult } from "../auth/better-auth.js"; import { logger } from "./logger.js"; import { localAgentProcessBoundary, type LocalAgentProcessBoundary } from "./local-agent-process-boundary.js"; +import { localOperatorCredential, type LocalOperatorCredential } from "./local-operator-credential.js"; import { resolveRequestRunIdentity } from "../services/run-identity.js"; import { boardAuthService } from "../services/board-auth.js"; import { retryIdempotentDatabaseOperation } from "../database-retry.js"; @@ -192,6 +193,7 @@ interface ActorMiddlewareOptions { deploymentMode: DeploymentMode; resolveSession?: (req: Request) => Promise; localAgentProcessBoundary?: LocalAgentProcessBoundary | null; + localOperatorCredential?: LocalOperatorCredential | null; } const publicRoutineWebhookPath = /^\/api\/routine-triggers\/public\/[a-f0-9]{24}\/fire\/?$/i; @@ -203,6 +205,9 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa const localBoundary = opts.deploymentMode === "local_trusted" ? opts.localAgentProcessBoundary === undefined ? localAgentProcessBoundary() : opts.localAgentProcessBoundary : null; + const operatorCredential = opts.deploymentMode === "local_trusted" + ? opts.localOperatorCredential === undefined ? localOperatorCredential() : opts.localOperatorCredential + : null; const authenticate: RequestHandler = async (req, _res, next) => { req.actor = opts.deploymentMode === "local_trusted" @@ -288,9 +293,12 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa return; } } - if (req.actor.source === "local_implicit" - && !(await localBoundary?.grantsImplicitBoard(req.socket))) { - req.actor = { type: "none", source: "none" }; + if (req.actor.source === "local_implicit") { + const operatorBrowser = operatorCredential?.hasOperatorCookie(req.headers) ?? false; + const granted = (operatorBrowser || !operatorCredential?.required) + && (await localBoundary?.grantsImplicitBoard(req.socket)) === true; + if (!granted) req.actor = { type: "none", source: "none" }; + else if (operatorBrowser) req.actor.localOperatorBrowser = true; } if (runIdHeader) req.actor.runId = runIdHeader; next(); diff --git a/server/src/middleware/board-mutation-guard.ts b/server/src/middleware/board-mutation-guard.ts index b357d91cfa2..66f5d8921c9 100644 --- a/server/src/middleware/board-mutation-guard.ts +++ b/server/src/middleware/board-mutation-guard.ts @@ -88,8 +88,11 @@ export function boardMutationGuard(): RequestHandler { // Local-trusted mode, board bearer keys, trusted Cloud tenant calls, and // signed Cloud control assertions are not browser-session requests. // In these modes, origin/referer headers can be absent; do not block those mutations. + // A browser that signed in with the local operator cookie is a browser + // session: it keeps the same-origin requirement so another local page + // cannot ride its cookie. if ( - req.actor.source === "local_implicit" + (req.actor.source === "local_implicit" && !req.actor.localOperatorBrowser) || req.actor.source === "board_key" || req.actor.source === "mcp_oauth" || req.actor.source === "cloud_tenant" diff --git a/server/src/middleware/local-operator-credential.ts b/server/src/middleware/local-operator-credential.ts new file mode 100644 index 00000000000..88112282a95 --- /dev/null +++ b/server/src/middleware/local-operator-credential.ts @@ -0,0 +1,129 @@ +import type { IncomingHttpHeaders } from "node:http"; +import { Router, type Request, type Response } from "express"; +import { + LOCAL_OPERATOR_COOKIE_NAME, + LOCAL_OPERATOR_CREDENTIAL_ENV, + LOCAL_OPERATOR_SIGN_IN_TTL_MS, + createLocalOperatorSignInLink, + ensureLocalOperatorKey, + localOperatorCookieValue, + localOperatorSignInUrl, + parseLocalOperatorCredentialMode, + resolveLocalOperatorKeyPath, + verifyLocalOperatorCookieValue, + verifyLocalOperatorSignInLink, + type LocalOperatorCredentialMode, +} from "@paperclipai/shared/local-operator-credential"; +import { logger } from "./logger.js"; + +const COOKIE_MAX_AGE_SECONDS = 400 * 24 * 60 * 60; +const DEFAULT_MODE: LocalOperatorCredentialMode = "off"; + +export function readCookie(headers: IncomingHttpHeaders, name: string): string | null { + const header = headers.cookie; + if (!header) return null; + for (const part of header.split(";")) { + const separator = part.indexOf("="); + if (separator < 0 || part.slice(0, separator).trim() !== name) continue; + try { + return decodeURIComponent(part.slice(separator + 1).trim()); + } catch { + return null; + } + } + return null; +} + +function safeNextPath(value: unknown): string { + if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//") || value.includes("\\")) return "/"; + return value; +} + +export interface LocalOperatorCredentialOptions { + mode?: LocalOperatorCredentialMode; + keyPath?: string; + key?: Buffer; +} + +export function createLocalOperatorCredential(options: LocalOperatorCredentialOptions = {}) { + const configured = parseLocalOperatorCredentialMode(process.env[LOCAL_OPERATOR_CREDENTIAL_ENV]); + const mode = options.mode ?? configured ?? DEFAULT_MODE; + let key = options.key ?? null; + const usedNonces = new Map(); + + function operatorKey(): Buffer { + key ??= ensureLocalOperatorKey(options.keyPath ?? resolveLocalOperatorKeyPath()); + return key; + } + + function hasOperatorCookie(headers: IncomingHttpHeaders): boolean { + const value = readCookie(headers, LOCAL_OPERATOR_COOKIE_NAME); + if (!value) return false; + try { + return verifyLocalOperatorCookieValue(operatorKey(), value); + } catch (err) { + logger.warn({ err }, "Could not read the local operator key; refusing the operator browser credential"); + return false; + } + } + + function signInUrl(baseUrl: string, next = "/"): string { + return localOperatorSignInUrl(baseUrl, createLocalOperatorSignInLink(operatorKey()), next); + } + + function consumeSignIn(query: Record, now = Date.now()): boolean { + for (const [nonce, expiresAt] of usedNonces) if (expiresAt < now) usedNonces.delete(nonce); + const link = { nonce: query.n, expiresAt: query.e, signature: query.s }; + if (!verifyLocalOperatorSignInLink(operatorKey(), link, now)) return false; + const nonce = link.nonce as string; + if (usedNonces.has(nonce)) return false; + usedNonces.set(nonce, now + LOCAL_OPERATOR_SIGN_IN_TTL_MS); + return true; + } + + function signInRoutes() { + const router = Router(); + router.get("/local-operator/sign-in", (req: Request, res: Response) => { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("Referrer-Policy", "no-referrer"); + let accepted = false; + try { + accepted = consumeSignIn(req.query as Record); + } catch (err) { + logger.warn({ err }, "Could not read the local operator key during browser sign-in"); + } + if (!accepted) { + res.status(403).type("text/plain").send( + "This sign-in link has expired or was already used. Run `paperclipai open` in your terminal to get a new one.", + ); + return; + } + res.cookie(LOCAL_OPERATOR_COOKIE_NAME, localOperatorCookieValue(operatorKey()), { + httpOnly: true, + sameSite: "strict", + path: "/", + maxAge: COOKIE_MAX_AGE_SECONDS * 1000, + }); + res.redirect(303, safeNextPath(req.query.next)); + }); + return router; + } + + return { + mode, + required: mode === "required", + hasOperatorCookie, + signInUrl, + consumeSignIn, + signInRoutes, + }; +} + +export type LocalOperatorCredential = ReturnType; + +let shared: LocalOperatorCredential | null = null; + +export function localOperatorCredential(): LocalOperatorCredential { + shared ??= createLocalOperatorCredential(); + return shared; +} diff --git a/server/src/realtime/live-events-ws.ts b/server/src/realtime/live-events-ws.ts index e5d3d23031b..b39bf4a4d52 100644 --- a/server/src/realtime/live-events-ws.ts +++ b/server/src/realtime/live-events-ws.ts @@ -1,5 +1,6 @@ import { createLiveEventDelivery, sharedDeliveryRead, type LiveDeliveryReads } from "./live-event-delivery.js"; import { localAgentProcessBoundary } from "../middleware/local-agent-process-boundary.js"; +import { localOperatorCredential } from "../middleware/local-operator-credential.js"; import { skillAccessService } from "../services/skill-access.js"; import { createHash } from "node:crypto"; import type { IncomingMessage, Server as HttpServer } from "node:http"; @@ -137,6 +138,16 @@ function headersFromIncomingMessage(req: IncomingMessage): Headers { return headers; } +function sameOriginUpgrade(req: IncomingMessage): boolean { + const origin = req.headers.origin; + if (!origin) return true; + try { + return new URL(origin).host.toLowerCase() === (req.headers.host ?? "").toLowerCase(); + } catch { + return false; + } +} + async function authorizeUpgrade( db: Db, req: IncomingMessage, @@ -155,6 +166,8 @@ async function authorizeUpgrade( // Browser board context has no bearer token in local_trusted and authenticated modes. if (!token) { if (opts.deploymentMode === "local_trusted") { + const operator = localOperatorCredential(); + if (operator.required && (!operator.hasOperatorCookie(req.headers) || !sameOriginUpgrade(req))) return null; if (!(await localAgentProcessBoundary().grantsImplicitBoard(req.socket))) return null; return { companyId, diff --git a/server/src/routes/health.ts b/server/src/routes/health.ts index b641a98ac82..5dce05496e7 100644 --- a/server/src/routes/health.ts +++ b/server/src/routes/health.ts @@ -1,5 +1,6 @@ import { supportsLocalAiLogin } from "../services/local-ai-login-policy.js"; import { randomUUID, timingSafeEqual } from "node:crypto"; +import { localOperatorCredential } from "../middleware/local-operator-credential.js"; import { Router } from "express"; import type { Db } from "@paperclipai/db"; import { and, count, eq, gt, inArray, isNull, sql } from "drizzle-orm"; @@ -246,6 +247,10 @@ export function healthRoutes( // fuller-detail fetch. Omitted entirely when nothing is hidden, so // deployments without the env var keep today's byte-identical responses. const hiddenSettings = [...getHiddenSettings(runtimeEnv)]; + // A local board that requires the operator credential tells a browser + // without it how to sign in, instead of failing every request. + const operatorSignIn = opts.deploymentMode === "local_trusted" && actorType !== "board" + && localOperatorCredential().required ? { localOperatorSignInRequired: true } : {}; // serverInfo (git SHA + process start) rides on the full-details responses // only, so it reaches board/agent actors in authenticated mode or any caller // in local_trusted dev — never anonymous authenticated callers. The @@ -282,6 +287,7 @@ export function healthRoutes( serverInfo, ...(cloud ? { cloud } : {}), ...(hiddenSettings.length ? { hiddenSettings } : {}), + ...operatorSignIn, } : { status: healthStatus, @@ -289,6 +295,7 @@ export function healthRoutes( commit, ...(cloud ? { cloud } : {}), ...(hiddenSettings.length ? { hiddenSettings } : {}), + ...operatorSignIn, }, ); return; @@ -307,6 +314,7 @@ export function healthRoutes( warmStandby: true, ...(cloud ? { cloud } : {}), ...(hiddenSettings.length ? { hiddenSettings } : {}), + ...operatorSignIn, }); return; } @@ -423,6 +431,7 @@ export function healthRoutes( ...(workspaceReadiness ? { workspace: workspaceReadiness } : {}), ...(cloud ? { cloud } : {}), ...(hiddenSettings.length ? { hiddenSettings } : {}), + ...operatorSignIn, }); return; } @@ -450,6 +459,7 @@ export function healthRoutes( ...(workspaceReadiness ? { workspace: workspaceReadiness } : {}), ...(cloud ? { cloud } : {}), ...(hiddenSettings.length ? { hiddenSettings } : {}), + ...operatorSignIn, }); }); diff --git a/server/src/types/express.d.ts b/server/src/types/express.d.ts index d3ae48c4c6f..a33a9be30c7 100644 --- a/server/src/types/express.d.ts +++ b/server/src/types/express.d.ts @@ -32,6 +32,8 @@ declare global { onBehalfOfUserId?: string | null; authorizingUserId?: string; identityContextId?: string | null; + /** Set when a local_trusted browser proved operator presence with the operator cookie. */ + localOperatorBrowser?: boolean; source?: "local_implicit" | "session" | "board_key" | "agent_key" | "agent_jwt" | "mcp_oauth" | "cloud_tenant" | "cloud_control" | "none"; }; } diff --git a/skills/paperclip-board/SKILL.md b/skills/paperclip-board/SKILL.md index 7147a09b486..decf3cc8c21 100644 --- a/skills/paperclip-board/SKILL.md +++ b/skills/paperclip-board/SKILL.md @@ -16,7 +16,7 @@ You are a board-level assistant helping a human manage their AI-agent company th - `PAPERCLIP_API_URL` — base URL of the Paperclip server (e.g., `http://localhost:3100`) - `PAPERCLIP_COMPANY_ID` — the active company ID (may be empty if no company exists yet) -**Auth mode:** If `PAPERCLIP_API_KEY` is set, include `Authorization: Bearer $PAPERCLIP_API_KEY` on all requests. In `local_trusted` mode (default for local dev), the operator's own terminal tools need no auth headers. +**Auth mode:** If `PAPERCLIP_API_KEY` is set, include `Authorization: Bearer $PAPERCLIP_API_KEY` on all requests. In `local_trusted` mode (default for local dev), the operator's own terminal tools need no auth headers unless the local board requires an operator sign-in. In that case a request without credentials gets 401 or 403. Ask the user to run `paperclipai auth login` and approve the request in their signed-in browser, then run `paperclipai token board create --name claude-board --json`. Use the returned key as `PAPERCLIP_API_KEY`. Never read Paperclip's key files under `~/.paperclip` to make your own credential. If the user's browser shows "Open Paperclip from your terminal", tell them to run `paperclipai open`. **Inside a Paperclip agent run:** you act with that run's own credentials only — your Paperclip tools or `PAPERCLIP_API_KEY`. Requests from an agent run never receive board access. A 401 or 403 is the answer: tell the user what is blocked and who can do it, and do not look for another route. diff --git a/ui/src/api/health.ts b/ui/src/api/health.ts index ee38beb85fd..8ffafa48476 100644 --- a/ui/src/api/health.ts +++ b/ui/src/api/health.ts @@ -33,6 +33,8 @@ export type HealthStatus = { deploymentMode?: "local_trusted" | "authenticated"; deploymentExposure?: "private" | "public"; localAiLoginSupported?: boolean; + /** This local board opens only through a sign-in link from `paperclipai open`. */ + localOperatorSignInRequired?: boolean; authReady?: boolean; bootstrapStatus?: "ready" | "bootstrap_pending"; bootstrapInviteActive?: boolean; diff --git a/ui/src/components/CloudAccessGate.test.tsx b/ui/src/components/CloudAccessGate.test.tsx index 932f74a7f0d..dfc5f61cf7c 100644 --- a/ui/src/components/CloudAccessGate.test.tsx +++ b/ui/src/components/CloudAccessGate.test.tsx @@ -225,6 +225,17 @@ describe("CloudAccessGate restart recovery", () => { expect(container.textContent).not.toContain("Reconnecting"); }); + it("asks a browser that has not signed in to a protected local board to open it from the terminal", async () => { + fetchMock.mockResolvedValueOnce(Response.json({ + status: "ok", + deploymentMode: "local_trusted", + localOperatorSignInRequired: true, + })); + await render(); + expect(container.querySelector("textarea")).toBeNull(); + expect(container.textContent).toContain("paperclipai open"); + }); + it("supports manual retry while startup health is pending", async () => { fetchMock.mockResolvedValueOnce(Response.json({ status: "starting", deploymentMode: "local_trusted" })); await render(); diff --git a/ui/src/components/CloudAccessGate.tsx b/ui/src/components/CloudAccessGate.tsx index d6e8a85aacf..62ae56e8f28 100644 --- a/ui/src/components/CloudAccessGate.tsx +++ b/ui/src/components/CloudAccessGate.tsx @@ -72,6 +72,23 @@ function NoBoardAccessPage() { ); } +function LocalOperatorSignIn() { + return ( +
+ +

Open Paperclip from your terminal

+

+ This board only opens in a browser you signed in from this computer. Run this command in a terminal: +

+
paperclipai open
+

+ It opens the board here and keeps this browser signed in. +

+
+
+ ); +} + export function CloudAccessGate({ allowMembershipRequest = false }: { allowMembershipRequest?: boolean } = {}) { const location = useLocation(); const queryClient = useQueryClient(); @@ -190,6 +207,10 @@ export function CloudAccessGate({ allowMembershipRequest = false }: { allowMembe return ; } + if (healthQuery.data?.localOperatorSignInRequired) { + return ; + } + if (isAuthenticatedMode && healthQuery.data?.cloud && !sessionQuery.data) { return ; }