mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 21:21:27 +01:00
fix(local): one resolver for the operator key and mode, a rotating read cookie, and fail closed on a blank setting
- The key sits next to the instance's config file, so run, the server and `paperclipai open` always use the same key. - `open` reads the deployment mode like the server (environment, then the selected config) and reports an unreadable config. - A blank PAPERCLIP_LOCAL_OPERATOR_CREDENTIAL now requires the credential. - The read cookie rotates and expires within a day; the board page renews it with its header token. Downloads the page starts with fetch no longer accept it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
539301b99a
commit
3d2cc4a3ec
10 files changed
+302
-112
No files matched your search
+109
-47
@@ -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");
|
||||
});
|
||||
});
|
||||
+52
-30
@@ -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<OpenOptions, "config" | "instance">): 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<OpenOptions, "config" | "instance"> = {}): 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<OpenOptions, "apiBase">, target: Pick<LocalBoardTarget, "instanceId" | "configPath">): 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 <path>", "Paperclip data directory root (isolates state from ~/.paperclip)")
|
||||
.option("-i, --instance <id>", "Local instance id (default: the instance of --config, else default)")
|
||||
.option("--api-base <url>", "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);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user