mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-11 05:31:46 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - AI Connections store reusable provider credentials with company and owner boundaries. > - Self-hosted instances can require board authentication while running agents on the local server. > - The login UI treated those instances as unsupported and displayed instructions without a command. > - Removing that restriction must not expose the server operator's existing CLI account. > - This pull request enables owner-scoped login attempts and reuses the existing login UI. > - Users can connect Codex and Claude subscriptions on an authenticated self-hosted instance. ## Linked Issues or Issue Description **What happened?** On an authenticated self-hosted instance, OpenAI subscription setup displayed terminal instructions with no command and a disabled Connect button. Claude also could not complete the local connection flow. **Expected behavior** An authorized board user can prepare an isolated sign-in attempt, sign in on the server, and save the verified account as a Connection. This must not import another user's or the operator's ambient credentials. **Steps to reproduce** Run Paperclip in authenticated mode with a local environment. Open Connections, choose OpenAI or Anthropic, and select Subscription. The previous UI never enabled local login preparation. Related: #13247, #13248, and #10751. This fix preserves the restriction on remote access to the operator's ambient Claude login. ## What Changed - Allow company-authorized users to create, check, cancel, and complete their own isolated local login attempts. - Keep ambient Claude credential import restricted to the local operator. - Support isolated Claude credential files without falling back to the host account or mutating process-wide environment variables. - Use Codex device authorization so sign-in does not depend on a browser callback to the remote server's localhost. - Gate server-host login on authenticated public deployments unless a trusted runtime host is configured. Publish the capability through health so setup shows supported alternatives. - Read isolated Claude credential files through bounded, descriptor-bound opens with ownership, permission, and symlink checks. Try the alternate filename after malformed JSON. - Reuse shared login instructions and lifecycle hooks in onboarding, agent setup, and Connections. Show health-query failures explicitly. - Document authenticated self-hosted behavior and add authorization, isolation, lifecycle, and UI regression tests. ## Verification - Passed 71 focused tests across connection routes, credential isolation, legacy compatibility, the shared login hook, and agent setup. - Passed 89 onboarding regression tests. - Passed `pnpm -r typecheck`, `pnpm build`, Storybook build, and `pnpm check:token-gates`. - Completed real Codex device authorization and Claude browser authorization on an authenticated Linux self-hosted instance. Both accounts were detected automatically and saved as Connected. Both completed attempt directories were removed. - These live checks cover login, credential validation, and connection creation. They do not establish a new model execution or long-running refresh result. - Review follow-up: 68 focused checks passed after rerunning one route socket error; the full route/health rerun passed all 49 tests. The 70-test onboarding suite also passed. Final workspace typecheck, production build, and Storybook build passed again. - The broad local run exposed an instance-name assumption in two new assertions. The fixture now uses an explicit non-default instance, and all 32 connection tests passed with a different inherited instance name. The superseded broad run was stopped; this is not a claim that the full local suite completed. Full CI results will be recorded before merge. ## Risks - The server must have the provider CLI installed. Users still run the displayed command on the server that hosts Paperclip. - Authorization checks must keep login attempts scoped to the company, owner, provider, and reconnect target. Regression tests cover cross-user and cross-company access. - Existing local-trusted Claude behavior stays available. Authenticated remote users cannot use its ambient import path. - No database migration, dependency change, agent binding change, or provider routing change is included. ## Model Used OpenAI GPT-6 through Codex, with reasoning, code execution, and browser tools. The runtime does not expose a more specific model version or context-window size. ## 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 - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
276 lines
9.2 KiB
TypeScript
276 lines
9.2 KiB
TypeScript
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { healthRoutes } from "../routes/health.js";
|
|
import * as devServerStatus from "../dev-server-status.js";
|
|
import { resolveHotRestartIntentPath } from "../services/hot-restart.js";
|
|
|
|
const tempDirs: string[] = [];
|
|
|
|
function createDevServerStatusFile(payload: unknown) {
|
|
const dir = mkdtempSync(path.join(os.tmpdir(), "paperclip-health-dev-server-"));
|
|
tempDirs.push(dir);
|
|
const filePath = path.join(dir, "dev-server-status.json");
|
|
writeFileSync(filePath, `${JSON.stringify(payload)}\n`, "utf8");
|
|
return filePath;
|
|
}
|
|
|
|
afterEach(() => {
|
|
vi.restoreAllMocks();
|
|
for (const dir of tempDirs.splice(0)) {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
describe("GET /health dev-server supervisor access", () => {
|
|
it("exposes dev-server metadata to the supervising dev runner in authenticated mode", async () => {
|
|
const previousFile = process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
|
const previousToken = process.env.PAPERCLIP_DEV_SERVER_STATUS_TOKEN;
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = createDevServerStatusFile({
|
|
dirty: true,
|
|
lastChangedAt: "2026-03-20T12:00:00.000Z",
|
|
changedPathCount: 1,
|
|
changedPathsSample: ["server/src/routes/health.ts"],
|
|
pendingMigrations: [],
|
|
lastRestartAt: "2026-03-20T11:30:00.000Z",
|
|
});
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_TOKEN = "dev-runner-token";
|
|
|
|
let selectCall = 0;
|
|
const db = {
|
|
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
|
|
select: vi.fn(() => {
|
|
selectCall += 1;
|
|
if (selectCall === 1) {
|
|
return {
|
|
from: vi.fn(() => ({
|
|
where: vi.fn().mockResolvedValue([{ count: 1 }]),
|
|
})),
|
|
};
|
|
}
|
|
if (selectCall === 2) {
|
|
return {
|
|
from: vi.fn(() => ({
|
|
where: vi.fn().mockResolvedValue([
|
|
{
|
|
id: "settings-1",
|
|
general: {},
|
|
experimental: { autoRestartDevServerWhenIdle: true },
|
|
createdAt: new Date("2026-03-20T11:00:00.000Z"),
|
|
updatedAt: new Date("2026-03-20T11:00:00.000Z"),
|
|
},
|
|
]),
|
|
})),
|
|
};
|
|
}
|
|
return {
|
|
from: vi.fn(() => ({
|
|
where: vi.fn().mockResolvedValue([{ count: 0 }]),
|
|
})),
|
|
};
|
|
}),
|
|
} as unknown as Db;
|
|
|
|
try {
|
|
const app = express();
|
|
app.use((req, _res, next) => {
|
|
(req as any).actor = { type: "none", source: "none" };
|
|
next();
|
|
});
|
|
app.use(
|
|
"/health",
|
|
healthRoutes(db, {
|
|
deploymentMode: "authenticated",
|
|
deploymentExposure: "private",
|
|
authReady: true,
|
|
companyDeletionEnabled: true,
|
|
// Pin server info so the commit field is deterministic (null)
|
|
// instead of picking up the checkout's real git metadata.
|
|
serverInfo: {
|
|
processStartedAt: "2026-03-20T11:00:00.000Z",
|
|
git: { available: false, unavailableReason: "git_unavailable" },
|
|
},
|
|
}),
|
|
);
|
|
|
|
const res = await request(app)
|
|
.get("/health")
|
|
.set("X-Paperclip-Dev-Server-Status-Token", "dev-runner-token");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body).toEqual({
|
|
status: "ok",
|
|
deploymentMode: "authenticated",
|
|
deploymentExposure: "private",
|
|
localAiLoginSupported: true,
|
|
commit: null,
|
|
bootstrapStatus: "ready",
|
|
bootstrapInviteActive: false,
|
|
devServer: {
|
|
enabled: true,
|
|
restartRequired: true,
|
|
reason: "backend_changes",
|
|
lastChangedAt: "2026-03-20T12:00:00.000Z",
|
|
changedPathCount: 1,
|
|
changedPathsSample: ["server/src/routes/health.ts"],
|
|
pendingMigrations: [],
|
|
autoRestartEnabled: true,
|
|
activeRunCount: 0,
|
|
waitingForIdle: false,
|
|
lastRestartAt: "2026-03-20T11:30:00.000Z",
|
|
},
|
|
});
|
|
} finally {
|
|
if (previousFile === undefined) {
|
|
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
|
} else {
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = previousFile;
|
|
}
|
|
if (previousToken === undefined) {
|
|
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_TOKEN;
|
|
} else {
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_TOKEN = previousToken;
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("POST /health/dev-server/restart", () => {
|
|
it("records a manual restart request for the dev runner", async () => {
|
|
const previousFile = process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
|
const previousHome = process.env.PAPERCLIP_HOME;
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = createDevServerStatusFile({
|
|
dirty: true,
|
|
lastChangedAt: "2026-03-20T12:00:00.000Z",
|
|
changedPathCount: 1,
|
|
changedPathsSample: ["server/src/routes/health.ts"],
|
|
pendingMigrations: [],
|
|
lastRestartAt: "2026-03-20T11:30:00.000Z",
|
|
});
|
|
process.env.PAPERCLIP_HOME = path.dirname(
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE,
|
|
);
|
|
|
|
try {
|
|
const app = express();
|
|
const db = {
|
|
select: vi.fn(() => ({
|
|
from: vi.fn(() => ({
|
|
where: vi.fn().mockResolvedValue([]),
|
|
})),
|
|
})),
|
|
} as unknown as Db;
|
|
app.use("/health", healthRoutes(db));
|
|
|
|
const res = await request(app).post("/health/dev-server/restart");
|
|
|
|
expect(res.status).toBe(202);
|
|
expect(res.body).toMatchObject({
|
|
status: "restart_requested",
|
|
mode: "hot",
|
|
requestId: expect.any(String),
|
|
});
|
|
|
|
const requestPath = path.join(
|
|
path.dirname(process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE),
|
|
"dev-server-restart-request.json",
|
|
);
|
|
expect(existsSync(requestPath)).toBe(true);
|
|
expect(JSON.parse(readFileSync(requestPath, "utf8"))).toMatchObject({
|
|
reason: "manual_restart_now",
|
|
mode: "hot",
|
|
requestId: res.body.requestId,
|
|
});
|
|
} finally {
|
|
if (previousFile === undefined) {
|
|
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
|
} else {
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = previousFile;
|
|
}
|
|
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME;
|
|
else process.env.PAPERCLIP_HOME = previousHome;
|
|
}
|
|
});
|
|
|
|
it("rolls back the hot intent when the supervisor request cannot be written", async () => {
|
|
const previousFile = process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
|
const previousHome = process.env.PAPERCLIP_HOME;
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = createDevServerStatusFile({
|
|
dirty: true,
|
|
changedPathCount: 1,
|
|
changedPathsSample: ["server/src/routes/health.ts"],
|
|
pendingMigrations: [],
|
|
});
|
|
const home = mkdtempSync(path.join(os.tmpdir(), "paperclip-health-restart-home-"));
|
|
tempDirs.push(home);
|
|
process.env.PAPERCLIP_HOME = home;
|
|
vi.spyOn(devServerStatus, "writeDevServerRestartRequest").mockReturnValue(false);
|
|
|
|
try {
|
|
const app = express();
|
|
const db = {
|
|
select: vi.fn(() => ({
|
|
from: vi.fn(() => ({ where: vi.fn().mockResolvedValue([]) })),
|
|
})),
|
|
} as unknown as Db;
|
|
app.use("/health", healthRoutes(db));
|
|
|
|
const res = await request(app).post("/health/dev-server/restart");
|
|
|
|
expect(res.status).toBe(404);
|
|
expect(res.body).toEqual({ error: "dev_server_supervisor_unavailable" });
|
|
expect(existsSync(resolveHotRestartIntentPath(home))).toBe(false);
|
|
} finally {
|
|
if (previousFile === undefined) {
|
|
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
|
} else {
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = previousFile;
|
|
}
|
|
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME;
|
|
else process.env.PAPERCLIP_HOME = previousHome;
|
|
}
|
|
});
|
|
|
|
it("rejects unauthenticated manual restarts in authenticated mode", async () => {
|
|
const previousFile = process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = createDevServerStatusFile({
|
|
dirty: true,
|
|
changedPathCount: 1,
|
|
changedPathsSample: ["server/src/routes/health.ts"],
|
|
pendingMigrations: [],
|
|
});
|
|
|
|
try {
|
|
const app = express();
|
|
app.use((req, _res, next) => {
|
|
(req as any).actor = { type: "none", source: "none" };
|
|
next();
|
|
});
|
|
app.use(
|
|
"/health",
|
|
healthRoutes(undefined, {
|
|
deploymentMode: "authenticated",
|
|
deploymentExposure: "private",
|
|
authReady: true,
|
|
companyDeletionEnabled: true,
|
|
}),
|
|
);
|
|
|
|
const res = await request(app).post("/health/dev-server/restart");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body).toEqual({ error: "board_access_required" });
|
|
} finally {
|
|
if (previousFile === undefined) {
|
|
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
|
|
} else {
|
|
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = previousFile;
|
|
}
|
|
}
|
|
});
|
|
});
|