fix(auth): agent shells can only reach the local API with their own run credentials (#21181)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - In `local_trusted` mode, the server gives board access to local
requests that carry no credentials, so the operator can use the app
without a login
> - Agent runs execute on the same machine, so their tools can also send
local requests
> - An agent run must act only with its own run credentials and
permissions
> - This pull request makes implicit board access belong only to the
operator's own local processes
> - The benefit is that agent shells and tools can only reach the API
with their own run credentials

## Linked Issues or Issue Description

**What happened?**
In `local_trusted` mode, a process inside an agent run could receive the
board identity for an API request that had no credentials. A permission
denial for the agent then did not stop the change.

**Expected behavior**
A request from inside an agent run uses the run's own credentials and
permissions. Implicit board access stays available to the operator's
browser and terminal tools.

**Deployment mode**
`local_trusted` (private, loopback). Authenticated deployments do not
use implicit board access and do not change.

**Additional context**
Found by the chat feature evals. The bundled board skill also described
implicit board access in words that an agent could follow.

## What Changed

- Add `server/src/middleware/local-agent-process-boundary.ts`. For a
request without credentials, it identifies the local process behind the
TCP connection (Linux: `/proc`; macOS: `netstat -anv` and `ps`). If that
process or one of its ancestors belongs to an agent run, the request
gets no implicit board access. An agent run is a descendant of
`paperclip-runnerd`, or a process that carries a run identity variable
(`PAPERCLIP_RUN_ID`, `PAPERCLIP_AGENT_ID`, `PAPERCLIP_AGENT_KEY_ID`,
`PAPERCLIP_RUNNER_INSTANCE_ID`) with a value that is different from the
server's own value.
- The walk stops at the server process and its ancestors. Requests from
the server process itself, and from an operator whose own development
server runs inside the same agent execution, keep board access.
- The result is cached for each connection. Only one process lookup runs
at a time. Connections that arrive during a lookup wait for the next
lookup, which handles all of them together (one `netstat` and two `ps`
calls on macOS, one `/proc` walk on Linux). All lookups are
asynchronous, so they do not block other work in the server.
- `actorMiddleware` and the live events WebSocket upgrade apply the
check in `local_trusted` mode. A refused request is unauthenticated
(`actor.type = "none"`), the same as an anonymous request in
authenticated mode.
- Platforms where the server cannot identify the process (for example
Windows) keep the previous behavior and log one warning.
- Rewrite the `paperclip-board` skill authentication section. It no
longer describes implicit board access to agents, and it says that a 401
or 403 inside an agent run is final.
- Document the behavior in `doc/DEPLOYMENT-MODES.md`.

## Verification

- `cd server && npx vitest run
src/__tests__/local-agent-process-boundary.test.ts`. The test starts a
real `local_trusted` server and real child processes:
- an operator process without credentials gets board access (green
before and after);
  - an in-process request gets board access;
- a process with a run identity gets no board access (red before this
change, green after);
- an agent process that starts a tool with an empty environment gets no
board access (red before, green after);
- an operator inside the same execution as its own server keeps board
access.
- A burst test with a slow inspector: 12 parallel connections and 2
connections that close early. It checks that only one lookup is active
at a time, that the burst needs at most two lookups, that the event loop
stays responsive, and that later requests still work.
- Parser tests for the Linux TCP table and the macOS `netstat` format,
and a test that the runner daemon itself is not treated as an agent
process.
- Ran `agent-auth-middleware`, `agent-identity`, `live-events-ws`,
`live-events-toast`, `live-events-run-read` and
`issue-create-deduplication-routes` tests locally. `npx tsc --noEmit -p
server/tsconfig.json` passes.
- Paid runner E2E evidence for the affected chat cases is linked in a
comment.

## Risks

- Medium. The check runs once for each new local connection without
credentials. On macOS it starts `netstat` and `ps` (about 30 to 80 ms).
On Linux it reads `/proc`. Bearer requests do not run it.
- If a process can not be identified on a supported platform, the
request gets no implicit board access. On Linux, when a same-user
process hides its sockets, the check keeps the previous behavior so that
the operator's browser continues to work.
- This is a boundary for the documented path, not a sandbox. Agent runs
use the operator's OS account. A process that intentionally leaves its
run's process tree, or reads the instance files directly, is outside
this check. The broader option is a product decision: bind implicit
board access to a capability that only the operator's browser and CLI
hold, or run agents under an OS sandbox that blocks the server port.
This pull request does not change `local_trusted` semantics for the
operator.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-12 15:05:15 -06:00
1 parent 2168f50741
commit f95bbe081e
6 files changed
+675 -1

No files matched your search

+1
View File
@@ -83,6 +83,7 @@ Paperclip now treats **bind** as a separate concern from auth:
- loopback-only host binding
- 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. Other platforms keep the previous behavior.
## `authenticated + private`
@@ -0,0 +1,232 @@
import { execFile } from "node:child_process";
import http from "node:http";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
import express from "express";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Db } from "@paperclipai/db";
import { actorMiddleware } from "../middleware/auth.js";
import {
chainBelongsToAgentRun,
createLocalAgentProcessBoundary,
type LocalProcessInspector,
findPeerPidInDarwinNetstat,
findSocketInodeInProcNet,
} from "../middleware/local-agent-process-boundary.js";
const supported = process.platform === "linux" || process.platform === "darwin";
function startServer(serverEnvironment: NodeJS.ProcessEnv): Promise<{ server: Server; url: string }> {
const app = express();
app.use(actorMiddleware({} as Db, {
deploymentMode: "local_trusted",
localAgentProcessBoundary: createLocalAgentProcessBoundary({ serverEnvironment }),
}));
app.get("/api/whoami", (req, res) => {
res.json({ type: req.actor.type, source: req.actor.source ?? null });
});
return new Promise((resolve) => {
const server = app.listen(0, "127.0.0.1", () => {
const { port } = server.address() as AddressInfo;
resolve({ server, url: `http://127.0.0.1:${port}/api/whoami` });
});
});
}
const fetchScript = "fetch(process.argv[1]).then(r => r.text()).then(t => process.stdout.write(t))";
function runChild(command: string, args: string[], env: NodeJS.ProcessEnv): Promise<{ type: string; source: string | null }> {
return new Promise((resolve, reject) => {
execFile(command, args, { env, timeout: 20_000 }, (error, stdout) => {
if (error) reject(error);
else resolve(JSON.parse(stdout));
});
});
}
function operatorEnvironment(): NodeJS.ProcessEnv {
const env = { ...process.env };
for (const key of ["PAPERCLIP_RUN_ID", "PAPERCLIP_AGENT_ID", "PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_RUNNER_INSTANCE_ID"]) {
delete env[key];
}
return env;
}
describe.skipIf(!supported)("implicit local board access from local processes", () => {
let server: Server;
let url: string;
beforeAll(async () => {
({ server, url } = await startServer({}));
});
afterAll(async () => {
await new Promise((resolve) => server.close(resolve));
});
it("keeps board access for an operator process without credentials", async () => {
await expect(runChild(process.execPath, ["-e", fetchScript, url], operatorEnvironment()))
.resolves.toEqual({ type: "board", source: "local_implicit" });
});
it("keeps board access for requests from the server process itself", async () => {
const body = await fetch(url).then((response) => response.json());
expect(body).toEqual({ type: "board", source: "local_implicit" });
});
it("refuses board access to an agent-run process calling without credentials", async () => {
await expect(runChild(process.execPath, ["-e", fetchScript, url], {
...operatorEnvironment(),
PAPERCLIP_RUN_ID: "11111111-1111-4111-8111-111111111111",
})).resolves.toEqual({ type: "none", source: "none" });
});
it("refuses board access when an agent's tool clears its environment before calling", async () => {
const agentProcess = [
"const { execFileSync } = require('node:child_process');",
"process.stdout.write(execFileSync(process.execPath, ['-e', process.argv[1], process.argv[2]], { env: {} }));",
].join("\n");
await expect(runChild(process.execPath, ["-e", agentProcess, fetchScript, url], {
...operatorEnvironment(),
PAPERCLIP_AGENT_ID: "22222222-2222-4222-8222-222222222222",
})).resolves.toEqual({ type: "none", source: "none" });
});
it("keeps board access for an operator whose own server runs inside the same agent execution", async () => {
const runId = "33333333-3333-4333-8333-333333333333";
const nested = await startServer({ PAPERCLIP_RUN_ID: runId });
try {
await expect(runChild(process.execPath, ["-e", fetchScript, nested.url], {
...operatorEnvironment(),
PAPERCLIP_RUN_ID: runId,
})).resolves.toEqual({ type: "board", source: "local_implicit" });
} finally {
await new Promise((resolve) => nested.server.close(resolve));
}
});
});
describe("local process identification", () => {
it("finds the client socket inode in a Linux TCP table", () => {
const table = [
" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode",
" 0: 0100007F:0C1C 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 111 1 0 100 0 0 10 0",
" 1: 0100007F:D431 0100007F:0C1C 01 00000000:00000000 00:00000000 00000000 1000 0 222 1 0 20 4 30 10 -1",
" 2: 0100007F:0C1C 0100007F:D431 01 00000000:00000000 00:00000000 00000000 1000 0 333 1 0 20 4 30 10 -1",
].join("\n");
expect(findSocketInodeInProcNet(table, { address: "127.0.0.1", port: 54321 }, { address: "127.0.0.1", port: 3100 }))
.toBe("222");
});
it("finds the client process in macOS netstat output and refuses unknown formats", () => {
const output = [
"Active Internet connections (including servers)",
"Proto Recv-Q Send-Q Local Address Foreign Address (state) rxbytes txbytes rhiwat shiwat process:pid state options",
"tcp4 0 0 127.0.0.1.3100 127.0.0.1.54321 ESTABLISHED 0 0 408300 146988 node:100 00002 00000000",
"tcp4 0 0 127.0.0.1.54321 127.0.0.1.3100 ESTABLISHED 0 0 408300 146988 Google Chrome He:200 00002 00000000",
].join("\n");
const peer = { address: "127.0.0.1", port: 54321 };
const server = { address: "127.0.0.1", port: 3100 };
expect(findPeerPidInDarwinNetstat(output, peer, server)).toBe(200);
expect(findPeerPidInDarwinNetstat(output.replace("process:pid", "pid"), peer, server)).toBe("unsupported");
});
it("treats processes under the runner daemon as an agent run but not the daemon itself", () => {
const daemon = { pid: 10, ppid: 1, executable: "/opt/paperclip/paperclip-runnerd", environment: new Map() };
const shell = { pid: 11, ppid: 10, executable: "/bin/bash", environment: new Map() };
expect(chainBelongsToAgentRun([daemon], {})).toBe(false);
expect(chainBelongsToAgentRun([shell, daemon], {})).toBe(true);
});
});
describe("process lookups under connection bursts", () => {
it("shares one lookup at a time across parallel connections and keeps the server responsive", async () => {
let active = 0;
let maxActive = 0;
let scans = 0;
const scannedSockets: number[] = [];
const inspector: LocalProcessInspector = {
async findPeerPids(sockets) {
scans += 1;
active += 1;
maxActive = Math.max(maxActive, active);
scannedSockets.push(sockets.length);
await new Promise((resolve) => setTimeout(resolve, 300));
active -= 1;
return sockets.map(() => 4242);
},
async ancestries(pids) {
return new Map(pids.map((pid) => [pid, [{ pid, ppid: 1, executable: "/usr/bin/browser", environment: new Map() }]]));
},
async ancestorPids(pid) {
return [pid];
},
};
const app = express();
app.use(actorMiddleware({} as Db, {
deploymentMode: "local_trusted",
localAgentProcessBoundary: createLocalAgentProcessBoundary({ inspector, serverEnvironment: {} }),
}));
app.get("/api/whoami", (req, res) => { res.json({ type: req.actor.type }); });
const server = await new Promise<Server>((resolve) => {
const started = app.listen(0, "127.0.0.1", () => resolve(started));
});
const { port } = server.address() as AddressInfo;
const request = (abortAfterMs?: number) => new Promise<string>((resolve) => {
const req = http.get({ host: "127.0.0.1", port, path: "/api/whoami", agent: false }, (res) => {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => resolve(body));
});
req.on("error", () => resolve("aborted"));
if (abortAfterMs !== undefined) setTimeout(() => req.destroy(), abortAfterMs);
});
try {
const timerStarted = Date.now();
const timerDelay = new Promise<number>((resolve) => setTimeout(() => resolve(Date.now() - timerStarted - 50), 50));
const first = await Promise.all([
...Array.from({ length: 12 }, () => request()),
request(20),
request(20),
timerDelay,
]);
const bodies = first.slice(0, 12);
expect(bodies.every((body) => JSON.parse(body as string).type === "board")).toBe(true);
expect(first.slice(12, 14)).toEqual(["aborted", "aborted"]);
expect(first[14] as number).toBeLessThan(250);
expect(maxActive).toBe(1);
expect(scans).toBeLessThanOrEqual(2);
const scanned = scannedSockets.reduce((sum, count) => sum + count, 0);
expect(scanned).toBeGreaterThanOrEqual(12);
expect(scanned).toBeLessThanOrEqual(14);
expect(JSON.parse(await request())).toEqual({ type: "board" });
} finally {
await new Promise((resolve) => server.close(resolve));
}
});
});
describe("process lookups for a mixed batch", () => {
it("keeps an identified agent process refused when another connection in the batch cannot be identified", async () => {
const inspector: LocalProcessInspector = {
async findPeerPids(sockets) {
return sockets.map((socket) => socket.remotePort === 1001 ? "unsupported" : 2002);
},
async ancestries(pids) {
return new Map(pids.map((pid) => [pid, [{
pid, ppid: 1, executable: "/usr/bin/agent", environment: new Map([["PAPERCLIP_RUN_ID", "run-1"]]),
}]]));
},
async ancestorPids(pid) {
return [pid];
},
};
const boundary = createLocalAgentProcessBoundary({ inspector, serverEnvironment: {} });
const hidden = { remoteAddress: "127.0.0.1", remotePort: 1001, localAddress: "127.0.0.1", localPort: 3100 };
const agent = { remoteAddress: "127.0.0.1", remotePort: 1002, localAddress: "127.0.0.1", localPort: 3100 };
const [hiddenResult, agentResult] = await Promise.all([boundary.classify(hidden), boundary.classify(agent)]);
expect(hiddenResult).toBe("unsupported");
expect(agentResult).toBe("agent_run");
expect(await boundary.grantsImplicitBoard(agent)).toBe(false);
});
});
+9
View File
@@ -28,6 +28,7 @@ import { loadAgentRunAuthentication } from "./agent-run-authentication.js";
import { isUuidLike, normalizeAgentApiKeyScope, type DeploymentMode } from "@paperclipai/shared";
import type { BetterAuthSessionResult } from "../auth/better-auth.js";
import { logger } from "./logger.js";
import { localAgentProcessBoundary, type LocalAgentProcessBoundary } from "./local-agent-process-boundary.js";
import { captureRunIdentity } from "../services/run-identity.js";
import { boardAuthService } from "../services/board-auth.js";
import { retryIdempotentDatabaseOperation } from "../database-retry.js";
@@ -210,6 +211,7 @@ async function auditAgentKeyMissingResponsibleUser(
interface ActorMiddlewareOptions {
deploymentMode: DeploymentMode;
resolveSession?: (req: Request) => Promise<BetterAuthSessionResult | null>;
localAgentProcessBoundary?: LocalAgentProcessBoundary | null;
}
const publicRoutineWebhookPath = /^\/api\/routine-triggers\/public\/[a-f0-9]{24}\/fire\/?$/i;
@@ -218,6 +220,9 @@ const publicMcpGatewayProtocolPath = /^\/mcp\/gateways\/gw_[a-f0-9]{32}\/?$/i;
export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHandler {
const boardAuth = boardAuthService(db);
const localBoundary = opts.deploymentMode === "local_trusted"
? opts.localAgentProcessBoundary === undefined ? localAgentProcessBoundary() : opts.localAgentProcessBoundary
: null;
const authenticate: RequestHandler = async (req, _res, next) => {
req.actor =
opts.deploymentMode === "local_trusted"
@@ -303,6 +308,10 @@ 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 (runIdHeader) req.actor.runId = runIdHeader;
next();
return;
@@ -0,0 +1,428 @@
import { execFile } from "node:child_process";
import { readdir, readFile, readlink } from "node:fs/promises";
import path from "node:path";
import { logger } from "./logger.js";
export const AGENT_RUN_ENVIRONMENT_MARKERS = [
"PAPERCLIP_RUN_ID",
"PAPERCLIP_AGENT_ID",
"PAPERCLIP_AGENT_KEY_ID",
"PAPERCLIP_RUNNER_INSTANCE_ID",
] as const;
const RUNNER_DAEMON_EXECUTABLE = "paperclip-runnerd";
const MAX_ANCESTRY_DEPTH = 64;
const COMMAND_TIMEOUT_MS = 5_000;
export type LocalPeerClassification = "operator" | "agent_run" | "unsupported";
export interface LocalPeerSocket {
remoteAddress?: string | null;
remotePort?: number | null;
localAddress?: string | null;
localPort?: number | null;
}
export interface LocalPeerEndpoints {
remoteAddress: string;
remotePort: number;
localAddress: string;
localPort: number;
}
export interface LocalProcessInfo {
pid: number;
ppid: number;
executable: string | null;
environment: Map<string, string>;
}
export interface LocalProcessInspector {
findPeerPids(sockets: readonly LocalPeerEndpoints[]): Promise<(number | null | "unsupported")[] | "unsupported">;
ancestries(pids: readonly number[], stopAt: ReadonlySet<number>): Promise<Map<number, LocalProcessInfo[] | null>>;
ancestorPids(pid: number): Promise<number[] | null>;
}
export function normalizeLoopbackAddress(address: string): string {
const lower = address.toLowerCase();
if (lower.startsWith("::ffff:") && lower.includes(".")) return lower.slice("::ffff:".length);
if (lower === "0:0:0:0:0:0:0:1") return "::1";
return lower;
}
function decodeProcNetAddress(hex: string): string | null {
if (hex.length === 8) {
const bytes = Buffer.from(hex, "hex");
return `${bytes[3]}.${bytes[2]}.${bytes[1]}.${bytes[0]}`;
}
if (hex.length !== 32) return null;
const bytes = Buffer.alloc(16);
for (let word = 0; word < 4; word += 1) {
const value = Buffer.from(hex.slice(word * 8, word * 8 + 8), "hex");
bytes[word * 4] = value[3]!;
bytes[word * 4 + 1] = value[2]!;
bytes[word * 4 + 2] = value[1]!;
bytes[word * 4 + 3] = value[0]!;
}
if (bytes.subarray(0, 10).every((byte) => byte === 0) && bytes[10] === 0xff && bytes[11] === 0xff) {
return `${bytes[12]}.${bytes[13]}.${bytes[14]}.${bytes[15]}`;
}
if (bytes.subarray(0, 15).every((byte) => byte === 0) && bytes[15] === 1) return "::1";
const groups: string[] = [];
for (let index = 0; index < 16; index += 2) groups.push(bytes.readUInt16BE(index).toString(16));
return groups.join(":");
}
export function findSocketInodeInProcNet(
table: string,
peer: { address: string; port: number },
server: { address: string; port: number },
): string | null {
for (const line of table.split("\n").slice(1)) {
const fields = line.trim().split(/\s+/);
if (fields.length < 10) continue;
const [localHex, localPortHex] = fields[1]!.split(":");
const [remoteHex, remotePortHex] = fields[2]!.split(":");
if (!localHex || !localPortHex || !remoteHex || !remotePortHex) continue;
if (Number.parseInt(localPortHex, 16) !== peer.port || Number.parseInt(remotePortHex, 16) !== server.port) continue;
if (decodeProcNetAddress(localHex) !== peer.address || decodeProcNetAddress(remoteHex) !== server.address) continue;
const inode = fields[9];
if (inode && inode !== "0") return inode;
}
return null;
}
export function findPeerPidInDarwinNetstat(
output: string,
peer: { address: string; port: number },
server: { address: string; port: number },
): number | null | "unsupported" {
const lines = output.split("\n");
const header = lines.find((line) => line.includes("Local Address"));
if (!header || !header.includes("process:pid")) return "unsupported";
const local = `${peer.address}.${peer.port}`;
const remote = `${server.address}.${server.port}`;
for (const line of lines) {
const fields = line.trim().split(/\s+/);
if (fields.length < 7 || !fields[0]!.startsWith("tcp")) continue;
if (normalizeLoopbackAddress(fields[3]!) !== local || normalizeLoopbackAddress(fields[4]!) !== remote) continue;
for (const field of fields.slice(6)) {
const match = /:(\d+)$/.exec(field);
if (match) return Number(match[1]);
}
}
return null;
}
function parseEnvironmentBlock(entries: string[]): Map<string, string> {
const environment = new Map<string, string>();
for (const entry of entries) {
const separator = entry.indexOf("=");
if (separator <= 0) continue;
environment.set(entry.slice(0, separator), entry.slice(separator + 1));
}
return environment;
}
function runCommand(command: string, args: string[]): Promise<string | null> {
return new Promise((resolve) => {
execFile(command, args, { encoding: "utf8", timeout: COMMAND_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 },
(error, stdout) => resolve(error ? null : stdout));
});
}
function linuxParentPid(stat: string): number {
return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
}
async function ownedByServerUser(pid: string): Promise<boolean> {
const status = await readFile(`/proc/${pid}/status`, "utf8").catch(() => "");
const realUid = /^Uid:\s+(\d+)/m.exec(status)?.[1];
return realUid !== undefined && Number(realUid) === process.getuid?.();
}
function endpoints(socket: LocalPeerEndpoints) {
return {
peer: { address: normalizeLoopbackAddress(socket.remoteAddress), port: socket.remotePort },
server: { address: normalizeLoopbackAddress(socket.localAddress), port: socket.localPort },
};
}
async function linuxProcessInfo(pid: number): Promise<LocalProcessInfo | null> {
const stat = await readFile(`/proc/${pid}/stat`, "utf8").catch(() => null);
if (!stat) return null;
const [cmdline, environ] = await Promise.all([
readFile(`/proc/${pid}/cmdline`, "utf8").catch(() => ""),
readFile(`/proc/${pid}/environ`, "utf8").catch(() => ""),
]);
return {
pid,
ppid: linuxParentPid(stat),
executable: cmdline.split("\0")[0] || null,
environment: parseEnvironmentBlock(environ.split("\0")),
};
}
const linuxInspector: LocalProcessInspector = {
async findPeerPids(sockets) {
const tables = await Promise.all(["/proc/net/tcp", "/proc/net/tcp6"].map((file) =>
readFile(file, "utf8").catch(() => null)));
if (tables.every((table) => table === null)) return "unsupported";
const inodes = sockets.map((socket) => {
const { peer, server } = endpoints(socket);
return tables.map((table) => table ? findSocketInodeInProcNet(table, peer, server) : null)
.find((value) => value !== null) ?? null;
});
const wanted = new Map<string, number>();
for (const inode of inodes) if (inode) wanted.set(`socket:[${inode}]`, 0);
const owners = new Map<string, number>();
let unreadable = false;
if (wanted.size) {
const others = (await readdir("/proc").catch(() => [] as string[]))
.filter((entry) => /^\d+$/.test(entry) && Number(entry) !== process.pid);
for (const pid of [String(process.pid), ...others]) {
if (owners.size === wanted.size) break;
const fds = await readdir(`/proc/${pid}/fd`).catch(async (error: NodeJS.ErrnoException) => {
if ((error.code === "EACCES" || error.code === "EPERM") && await ownedByServerUser(pid)) unreadable = true;
return [] as string[];
});
for (const fd of fds) {
const link = await readlink(`/proc/${pid}/fd/${fd}`).catch(() => null);
if (link && wanted.has(link) && !owners.has(link)) owners.set(link, Number(pid));
}
}
}
return inodes.map((inode) => {
if (!inode) return null;
return owners.get(`socket:[${inode}]`) ?? (unreadable ? "unsupported" : null);
});
},
async ancestorPids(pid) {
const pids: number[] = [];
let current = pid;
for (let depth = 0; depth < MAX_ANCESTRY_DEPTH && current > 1; depth += 1) {
pids.push(current);
const stat = await readFile(`/proc/${current}/stat`, "utf8").catch(() => null);
if (!stat) return null;
current = linuxParentPid(stat);
if (!Number.isInteger(current)) return null;
}
return pids;
},
async ancestries(pids, stopAt) {
const known = new Map<number, LocalProcessInfo | null>();
const result = new Map<number, LocalProcessInfo[] | null>();
for (const pid of pids) {
const chain: LocalProcessInfo[] = [];
let current = pid;
for (let depth = 0; depth < MAX_ANCESTRY_DEPTH && current > 1 && !stopAt.has(current); depth += 1) {
if (!known.has(current)) known.set(current, await linuxProcessInfo(current));
const info = known.get(current);
if (!info) break;
chain.push(info);
current = info.ppid;
}
result.set(pid, chain.length || stopAt.has(pid) ? chain : null);
}
return result;
},
};
async function darwinParentTable(): Promise<Map<number, number> | null> {
const output = await runCommand("ps", ["-axo", "pid=,ppid="]);
if (output === null) return null;
const parents = new Map<number, number>();
for (const line of output.split("\n")) {
const [pid, ppid] = line.trim().split(/\s+/).map(Number);
if (Number.isInteger(pid) && Number.isInteger(ppid)) parents.set(pid!, ppid!);
}
return parents;
}
function darwinChain(parents: Map<number, number>, pid: number, stopAt: ReadonlySet<number>): number[] {
const chain: number[] = [];
let current = pid;
for (let depth = 0; depth < MAX_ANCESTRY_DEPTH && current > 1 && !stopAt.has(current); depth += 1) {
chain.push(current);
const parent = parents.get(current);
if (parent === undefined) break;
current = parent;
}
return chain;
}
export function parseDarwinProcessEnvironmentLine(command: string): {
executable: string | null;
environment: Map<string, string>;
} {
const tokens = command.trim().split(/\s+/);
const environment = new Map<string, string>();
for (const token of tokens.slice(1)) {
const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(token);
if (match) environment.set(match[1]!, match[2]!);
}
return { executable: tokens[0] || null, environment };
}
const darwinInspector: LocalProcessInspector = {
async findPeerPids(sockets) {
const output = await runCommand("netstat", ["-anv", "-p", "tcp"]);
if (output === null) return "unsupported";
return sockets.map((socket) => {
const { peer, server } = endpoints(socket);
return findPeerPidInDarwinNetstat(output, peer, server);
});
},
async ancestorPids(pid) {
const parents = await darwinParentTable();
return parents ? darwinChain(parents, pid, new Set()) : null;
},
async ancestries(pids, stopAt) {
const result = new Map<number, LocalProcessInfo[] | null>();
const parents = await darwinParentTable();
if (!parents) {
for (const pid of pids) result.set(pid, null);
return result;
}
const chains = new Map(pids.map((pid) => [pid, darwinChain(parents, pid, stopAt)]));
const members = [...new Set([...chains.values()].flat())];
const details = new Map<number, ReturnType<typeof parseDarwinProcessEnvironmentLine>>();
if (members.length) {
const output = await runCommand("ps", ["-E", "-ww", "-o", "pid=,command=", "-p", members.join(",")]);
if (output === null) {
for (const pid of pids) result.set(pid, null);
return result;
}
for (const line of output.split("\n")) {
const match = /^\s*(\d+)\s+(.*)$/.exec(line);
if (match) details.set(Number(match[1]), parseDarwinProcessEnvironmentLine(match[2]!));
}
}
for (const [pid, chain] of chains) {
result.set(pid, chain.map((entry) => ({
pid: entry,
ppid: parents.get(entry) ?? 0,
executable: details.get(entry)?.executable ?? null,
environment: details.get(entry)?.environment ?? new Map(),
})));
}
return result;
},
};
export function defaultLocalProcessInspector(platform: NodeJS.Platform = process.platform): LocalProcessInspector | null {
if (platform === "linux") return linuxInspector;
if (platform === "darwin") return darwinInspector;
return null;
}
export function chainBelongsToAgentRun(
chain: readonly LocalProcessInfo[],
serverEnvironment: NodeJS.ProcessEnv,
): boolean {
return chain.some((entry, index) => {
if (entry.executable !== null && path.basename(entry.executable) === RUNNER_DAEMON_EXECUTABLE) return index > 0;
return AGENT_RUN_ENVIRONMENT_MARKERS.some((key) => {
const value = entry.environment.get(key);
return value !== undefined && value !== "" && value !== serverEnvironment[key];
});
});
}
export interface LocalAgentProcessBoundaryOptions {
inspector?: LocalProcessInspector | null;
serverPid?: number;
serverEnvironment?: NodeJS.ProcessEnv;
}
export function createLocalAgentProcessBoundary(options: LocalAgentProcessBoundaryOptions = {}) {
const inspector = options.inspector === undefined ? defaultLocalProcessInspector() : options.inspector;
const serverPid = options.serverPid ?? process.pid;
const serverEnvironment = options.serverEnvironment ?? process.env;
const classifications = new WeakMap<object, Promise<LocalPeerClassification>>();
let serverAncestors: Promise<ReadonlySet<number>> | null = null;
let warnedUnsupported = false;
let queued: { socket: LocalPeerEndpoints; resolve: (result: LocalPeerClassification) => void }[] = [];
let scanning = false;
function stopSet(): Promise<ReadonlySet<number>> {
serverAncestors ??= (inspector?.ancestorPids(serverPid) ?? Promise.resolve(null))
.then((pids) => new Set([serverPid, ...(pids ?? [])]));
return serverAncestors;
}
async function classifyBatch(sockets: readonly LocalPeerEndpoints[]): Promise<LocalPeerClassification[]> {
if (!inspector) return sockets.map(() => "unsupported");
const peerPids = await inspector.findPeerPids(sockets);
if (peerPids === "unsupported") return sockets.map(() => "unsupported");
const stopAt = await stopSet();
const outside = [...new Set(peerPids.filter((pid): pid is number => typeof pid === "number" && !stopAt.has(pid)))];
const chains = outside.length ? await inspector.ancestries(outside, stopAt) : new Map<number, LocalProcessInfo[] | null>();
return peerPids.map((pid): LocalPeerClassification => {
if (pid === "unsupported") return "unsupported";
if (pid === null) return "agent_run";
if (stopAt.has(pid)) return "operator";
const chain = chains.get(pid);
if (!chain) return "agent_run";
return chainBelongsToAgentRun(chain, serverEnvironment) ? "agent_run" : "operator";
});
}
async function drain() {
if (scanning) return;
scanning = true;
try {
while (queued.length) {
const batch = queued;
queued = [];
const results = await classifyBatch(batch.map((entry) => entry.socket)).catch((err) => {
logger.warn({ err }, "Could not identify the local process behind a request; refusing implicit board access");
return batch.map(() => "agent_run" as const);
});
batch.forEach((entry, index) => entry.resolve(results[index]!));
}
} finally {
scanning = false;
}
}
function classifyUncached(socket: LocalPeerSocket): Promise<LocalPeerClassification> {
if (!inspector) return Promise.resolve("unsupported");
const { remoteAddress, remotePort, localAddress, localPort } = socket;
if (!remoteAddress || !remotePort || !localAddress || !localPort) return Promise.resolve("agent_run");
return new Promise((resolve) => {
queued.push({ socket: { remoteAddress, remotePort, localAddress, localPort }, resolve });
void drain();
});
}
async function classify(socket: LocalPeerSocket & object): Promise<LocalPeerClassification> {
let pending = classifications.get(socket);
if (!pending) {
pending = classifyUncached(socket);
classifications.set(socket, pending);
}
const result = await pending;
if (result === "unsupported" && !warnedUnsupported) {
warnedUnsupported = true;
logger.warn("This platform cannot identify the local process behind a request, so implicit local board access is not limited to operator processes");
}
return result;
}
async function grantsImplicitBoard(socket: (LocalPeerSocket & object) | null | undefined): Promise<boolean> {
if (!socket) return false;
return await classify(socket) !== "agent_run";
}
return { classify, grantsImplicitBoard };
}
export type LocalAgentProcessBoundary = ReturnType<typeof createLocalAgentProcessBoundary>;
let sharedBoundary: LocalAgentProcessBoundary | null = null;
export function localAgentProcessBoundary(): LocalAgentProcessBoundary {
sharedBoundary ??= createLocalAgentProcessBoundary();
return sharedBoundary;
}
+2
View File
@@ -1,4 +1,5 @@
import { createLiveEventDelivery, sharedDeliveryRead, type LiveDeliveryReads } from "./live-event-delivery.js";
import { localAgentProcessBoundary } from "../middleware/local-agent-process-boundary.js";
import { skillAccessService } from "../services/skill-access.js";
import { createHash } from "node:crypto";
import type { IncomingMessage, Server as HttpServer } from "node:http";
@@ -154,6 +155,7 @@ async function authorizeUpgrade(
// Browser board context has no bearer token in local_trusted and authenticated modes.
if (!token) {
if (opts.deploymentMode === "local_trusted") {
if (!(await localAgentProcessBoundary().grantsImplicitBoard(req.socket))) return null;
return {
companyId,
actorType: "board",
+3 -1
View File
@@ -16,7 +16,9 @@ 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:** In `local_trusted` mode (default for local dev), no auth headers are needed — the server auto-grants board access to all local requests. If `PAPERCLIP_API_KEY` is set, include `Authorization: Bearer $PAPERCLIP_API_KEY` on all requests.
**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.
**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.
**Making API calls:** Use `curl -sS` via bash. All endpoints are under `/api`. All request/response bodies are JSON. Always use `Content-Type: application/json` on POST/PATCH/PUT requests.