mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The chat evaluation catalog checks agent replies and then the human step that follows, such as a person who reveals a key or approves a device > - Some human steps run in a separate private browser process, because they handle credentials. CI keeps the output of that process private on purpose > - Four cases failed only in that private step, so CI showed one fixed message and no cause > - I ran each private step locally against a dev server, where its output is visible, and found the cause of three failures > - This pull request fixes the harness and two product defects, and adds a closed failure record so that the next CI failure names its step > - The benefit is that these human steps work, and a private-step failure is diagnosable without any credential in logs ## Linked Issues or Issue Description Bug report (following `.github/ISSUE_TEMPLATE/bug_report.yml`). **What happened?** - `routines.webhook-trigger`: the private person opens the routine overview. The trigger cards are only in the Triggers section, so the step waits for a missing button. An unhandled response wait then stops the process. - `connection-setup.secure-api-key`: a key-protected MCP server answers 401 without a challenge header. Paperclip shows "Remote app returned HTTP 401" and does not ask for a key. The person cannot enter the key in the normal flow. - `assistant-connections.device-login`: an expired device code page shows "This item doesn't exist or was moved." The server sends "This code is expired, already decided, or invalid." in the OAuth `error_description` field, and the UI drops it. - `onboarding.new-company`: the private step reads back all saved state and then fails one proof check. CI does not say which check. **Expected behavior** - The person reveals the webhook key in the Triggers section and sends authenticated events. - A pasted MCP link that answers 401 shows the key field. - An expired device code says that the code is expired. - A private-step failure names its fixed step and error class, with no value. **Steps to reproduce** 1. Start a local dev server. 2. Create a routine with a bearer webhook, and run the private webhook worker. It times out on the "Edit webhook" button. 3. Paste the address of an MCP server that answers a plain 401 into Connectors > Add by link. No key field appears. 4. Open `/mcp-device?user_code=<expired code>`. The page shows generic not-found text. **Paperclip version or commit** `master` (reproduced on origin/master before this change) **Deployment mode** Local dev server (embedded PGlite) and the CI chat-eval runner **Installation method** Source checkout (`pnpm dev`) ## What Changed - `integrator-webhook-private-worker.ts`: open `<routine>/triggers` (also for the setup-resume link), and attach a handler to the early response wait so a failed click reports its real step. - `server/.../catalog/discovery.ts`: a 401 with no `WWW-Authenticate` header, to a connection that sends no credential, is handled like a challenge without discoverable sign-in (`oauth_challenge`). The existing UI guidance then asks for a key. A 401 to a connection that already sends a credential keeps the old error. - `ui/src/api/errors.ts`: read the OAuth `error_description` field as a readable server message. - New `private-child-failure.ts`: a private child records only a fixed step name and an error class from a fixed list. The parent echoes a step only when it is in the caller's closed list. Error text, stdout and stderr stay private. - The webhook, private browser and identity children use it. Each has a closed step list file. - `identity-new-company-native-proof.ts`: each proof check has a fixed reason name. The private child reports `new-company-proof-<reason>` when a check fails. The accepted conditions do not change. - Tests: server red/green test for the bare 401, UI red/green test for `error_description`, unit tests for the failure record (no text leaks, closed list only, extra fields dropped). ## Verification - Local dev server (embedded PostgreSQL), private workers run directly with the real child process: - Webhook, ready and setup-pending triggers: before, timeout on "Edit webhook". After, receipt with invalid status 401, valid status 202 and a linked task. - Secure key entry with the synthetic notes provider: before, timeout on the key field. After, an active connection with health `ok` and 2 authorized `tools/list` calls. - Expired device page: before, `at step device-expired-page (TimeoutError)`. After, `expiredPageVisible: true`. - `server`: `vitest run src/__tests__/tool-access-service.test.ts -t "pasted link answers"` (fails before the discovery change with 502, passes after). - `ui`: `vitest run src/api/errors.test.ts` (fails before, passes after). - `pnpm test:e2e:runner:typecheck`, `pnpm test:e2e:runner:unit`, server `tsc --noEmit`. - `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD sha> --check`: unchanged. - One paid run of the four cases on this branch. Results are in a PR comment. ## Risks - A plain 401 from an MCP link now returns 422 `oauth_challenge` instead of 502. The draft connection is removed, as for other challenges. Agents that call the connect API see the "needs sign-in" answer instead of a raw status. This only applies when the connection sends no credential. - Some API errors that carry `error_description` now show that text instead of generic copy. That text is written for people. - The failure record is opt-in per child and contains only constants. The parent ignores a record with any other field. - `onboarding.new-company` is not fixed here. Its native hello probe cannot start locally on macOS, so the failing check is not yet known. This change makes the next run name it. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file edits, local browser automation through Playwright). Extended reasoning was on. ## 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>
50 lines
6.5 KiB
TypeScript
50 lines
6.5 KiB
TypeScript
import { readFile, writeFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { createHmac } from "node:crypto";
|
|
import { chromium, test, type Cookie } from "@playwright/test";
|
|
import { recordPrivateChildFailure } from "./private-child-failure.js";
|
|
import { WEBHOOK_PRIVATE_STEPS, type WebhookPrivateStep } from "./integrator-webhook-private-steps.js";
|
|
interface Request { baseURL: string; route: string; routineId: string; triggerId: string; setupPending: boolean; signingMode: string; nonce: string; cookies: Cookie[]; executablePath?: string; channel?: string }
|
|
let step: WebhookPrivateStep = WEBHOOK_PRIVATE_STEPS[0];
|
|
async function main() {
|
|
let attached = false; try { test.info(); attached = true; } catch { /* no Test worker */ } if (attached) throw new Error("Private webhook driver must be outside Test");
|
|
const request = process.argv[2]!; const input = JSON.parse(await readFile(request, "utf8")) as Request; const base = new URL(input.baseURL);
|
|
if (base.protocol !== "http:" || base.hostname !== "127.0.0.1" || !/^[a-f0-9-]{36}$/i.test(input.triggerId) || !/^[a-f0-9-]{36}$/i.test(input.routineId) || !input.route.endsWith(`/routines/${input.routineId}`)) throw new Error("Private webhook target is outside its exact disposable scope");
|
|
step = "launch"; const browser = await chromium.launch({ headless: true, ...(input.executablePath ? { executablePath: input.executablePath } : {}), ...(input.channel ? { channel: input.channel } : {}) });
|
|
try {
|
|
const context = await browser.newContext({ baseURL: base.origin }); await context.addCookies(input.cookies); const page = await context.newPage(); page.setDefaultTimeout(30_000);
|
|
// Triggers live in their own routine section; the overview has no trigger cards.
|
|
step = "open-triggers"; const url = new URL(`${input.route}/triggers`, base); if (input.setupPending) url.searchParams.set("triggerSetup", input.triggerId);
|
|
await page.goto(url.href, { waitUntil: "domcontentloaded" });
|
|
const rotated = page.waitForResponse(response => new URL(response.url()).pathname === `/api/routine-triggers/${input.triggerId}/rotate-secret` && response.request().method() === "POST" && response.ok()); rotated.catch(() => undefined);
|
|
step = "reveal-key"; if (input.setupPending) await page.getByRole("button", { name: "Generate new key", exact: true }).click();
|
|
else { const card = page.getByRole("region", { name: "Webhook trigger", exact: true }); await card.getByRole("button", { name: "Edit webhook", exact: true }).click(); await card.getByRole("button", { name: "Replace key", exact: true }).click(); await page.getByRole("dialog").getByRole("button", { name: "Replace key", exact: true }).click(); }
|
|
const material = await (await rotated).json() as { secretMaterial: { webhookSecret: string; webhookUrl: string } };
|
|
const secret = material.secretMaterial.webhookSecret; const endpoint = new URL(material.secretMaterial.webhookUrl);
|
|
if (!/^[a-f0-9]{48}$/i.test(secret) || endpoint.origin !== base.origin || !/^\/api\/routine-triggers\/public\/[^/]+\/fire$/.test(endpoint.pathname)) throw new Error("Unexpected one-time scoped webhook credential");
|
|
await page.locator("code").filter({ hasText: secret }).first().waitFor({ state: "visible" });
|
|
step = "finish-setup"; if (input.setupPending) { await page.getByRole("button", { name: "Check connection", exact: true }).click();
|
|
const finished = page.waitForResponse(response => new URL(response.url()).pathname === `/api/routine-triggers/${input.triggerId}` && response.request().method() === "PATCH" && response.ok());
|
|
await page.getByRole("button", { name: /^Finish (?:setup|without checking)$/ }).click(); await finished; }
|
|
const cookie = input.cookies.map(value => `${value.name}=${value.value}`).join("; ");
|
|
const readRuns = async () => { const response = await fetch(new URL(`/api/routines/${input.routineId}/runs`, base), { redirect: "error", headers: cookie ? { cookie } : {}, signal: AbortSignal.timeout(15_000) }); if (!response.ok) throw new Error("Invocation proof unavailable"); return await response.json() as Array<{ id: string }>; };
|
|
step = "invalid-delivery"; const before = await readRuns(); const payload = JSON.stringify({ event: "synthetic.test-service", delivery: input.nonce });
|
|
const bad = await fetch(endpoint, { method: "POST", redirect: "error", headers: { "content-type": "application/json", authorization: "Bearer deliberately-invalid-eval-key", "idempotency-key": `${input.nonce}-bad` }, body: payload, signal: AbortSignal.timeout(15_000) }); const invalidStatus = bad.status; await bad.body?.cancel();
|
|
const afterInvalid = await readRuns();
|
|
const headers: Record<string, string> = { "content-type": "application/json", "idempotency-key": `${input.nonce}-valid` };
|
|
if (["bearer", "app_webhook"].includes(input.signingMode)) headers.authorization = `Bearer ${secret}`;
|
|
else if (["github_hmac", "fireflies_hmac"].includes(input.signingMode)) headers[input.signingMode === "github_hmac" ? "x-hub-signature-256" : "x-hub-signature"] = `sha256=${createHmac("sha256", secret).update(payload).digest("hex")}`;
|
|
else if (input.signingMode === "hmac_sha256") { const timestamp = String(Math.floor(Date.now() / 1000)); headers["x-paperclip-timestamp"] = timestamp; headers["x-paperclip-signature"] = `sha256=${createHmac("sha256", secret).update(`${timestamp}.${payload}`).digest("hex")}`; }
|
|
else throw new Error("Webhook did not require authenticated delivery");
|
|
step = "valid-delivery"; const accepted = await fetch(endpoint, { method: "POST", redirect: "error", headers, body: payload, signal: AbortSignal.timeout(15_000) });
|
|
const validStatus = accepted.status; if (validStatus !== 202) throw new Error("Authenticated synthetic delivery was not accepted");
|
|
const result = await accepted.json() as { id?: string; linkedIssueId?: string };
|
|
await writeFile(path.join(path.dirname(request), "secret.txt"), secret, { mode: 0o600 });
|
|
return { processIsolation: true, testRunnerAttached: false, credentialVisibleInHumanUI: true, setupFinished: true, invalidStatus, validStatus, invalidCreatedInvocation: afterInvalid.length !== before.length, invocationId: result.id, linkedIssueId: result.linkedIssueId, triggerId: input.triggerId };
|
|
} finally { await browser.close(); }
|
|
}
|
|
main().then(receipt => process.stdout.write(JSON.stringify(receipt))).catch(async (error: unknown) => {
|
|
await recordPrivateChildFailure(path.dirname(process.argv[2]!), step, error);
|
|
process.stderr.write("Private webhook operation failed; diagnostics withheld"); process.exitCode = 1;
|
|
});
|