feat(apps): add secure remote MCP and PostHog setup (#12339)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Apps give those agents governed access to external tools.
> - Remote MCP setup needs secure endpoint validation and durable
credentials.
> - PostHog needs both browser sign-in and personal API key setup paths.
> - This pull request adds the shared remote MCP foundation and the
PostHog definition.
> - The benefit is a secure and reusable base for later app connection
work.

## Linked Issues or Issue Description

Refs #11965

This is stack 1 of 11. It replaces the first reviewable part of #11965.

## What Changed

- Add guarded remote MCP setup and credential handling.
- Add PostHog OAuth and API key connection methods.
- Add focused server, shared contract, and UI coverage.
- Keep the migration replay-safe and idempotent.
- Give the late-close security regression the same 10-second CI headroom
as the adjacent real-timer handshake test.
- Synchronize fake-timer handshake tests at the exact ensure-session
boundary so real filesystem setup cannot race the fake deadline.
- Drive PTY overflow coverage only after listener registration so
scheduling cannot reorder the test fixture.

## Verification

- pnpm exec vitest run
packages/adapter-utils/src/acpx-engine/execute.test.ts
server/src/__tests__/plugin-worker-manager.test.ts (220 passed; affected
cases also passed five focused stress repetitions)
- `pnpm exec vitest run
packages/adapter-utils/src/acpx-engine/execute.test.ts -t "never leaks a
sandbox-provided value from a late close rejection into logs or the
result"` (1 passed)
- `pnpm exec vitest run
packages/adapter-utils/src/acpx-engine/execute.test.ts -t "never
promotes a late ensureSession resolution|closes a late-resolving real
handle exactly once"` (2 passed)
- `pnpm -r typecheck`
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/tool-access-service.test.ts`
- `pnpm --filter @paperclipai/db check:migrations`
- `pnpm build`

## Risks

- Remote endpoint validation can reject configurations that previously
passed without checks.
- OAuth configuration errors can block setup until the operator corrects
the provider settings.
- The migration uses guarded statements so repeated execution is safe.
- The test-only synchronization changes do not affect runtime behavior;
they remove filesystem/fake-clock and listener-registration races
observed under parallel CI load.

> I checked `ROADMAP.md`. This stack continues the existing app
connection work from #11965 and does not duplicate another planned item.

## Model Used

OpenAI Codex, GPT-5. The runtime model ID and context window were not
exposed. The model used reasoning, 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 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
- [x] 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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-08-29 12:08:32 -05:00
1 parent 6154e00f26
commit cabc9146d0
93 files changed
+55543 -868

No files matched your search

+10 -1
View File
@@ -3,11 +3,20 @@ const root=process.cwd(); const corpus=process.env.PAPERCLIP_CONTENT_TEMPLATES??
const out=path.join(root,"packages/shared/src/app-definitions"); const favicon=d=>`https://www.google.com/s2/favicons?domain=${d}&sz=128`;
const field=(key,label,placeholder)=>({key,label,type:"password",required:true,placeholder,secret:true});
const method=(key,transport,auth,defaults,riskTier,guidanceMd,extra={})=>({key,transport,auth,ownershipModes:auth==="oauth"?["customer","dcr"]:["customer"],whenToUse:transport==="mcp_remote"?"Use the provider-hosted connection for the quickest setup.":"Use credentials from your provider account.",defaults,guidanceMd,riskTier,...extra});
const posthogConfigFields=()=>[
{key:"projectId",label:"Project ID",type:"text",required:true,placeholder:"12345",helperMd:"Find the numeric project ID in PostHog project settings.",validation:{pattern:"^[0-9]+$",maxLength:32},transport:{location:"header",name:"x-posthog-project-id"}},
{key:"readOnly",label:"Read-only mode",type:"checkbox",defaultValue:false,helperMd:"Turn on to hide tools that can change PostHog data.",transport:{location:"query",name:"readonly",format:"boolean",omitFalse:true}},
{key:"features",label:"Feature groups",type:"textarea",advanced:true,placeholder:"Optional comma-separated feature groups",helperMd:"Leave blank to expose every feature group, or enter a comma-separated list to narrow access.",validation:{maxLength:500},transport:{location:"query",name:"features",format:"csv"}},
{key:"tools",label:"Individual tools",type:"textarea",advanced:true,placeholder:"Optional comma-separated tool names",helperMd:"Leave blank to expose all tools. Exact names here are combined with any feature groups.",validation:{maxLength:2000},transport:{location:"query",name:"tools",format:"csv"}},
{key:"mode",label:"Tool response mode",type:"select",advanced:true,required:true,placeholder:"Individual tools",defaultValue:"tools",options:[{value:"tools",label:"Individual tools"}],helperMd:"Paperclip uses individual tools so every action can be governed. CLI mode remains unavailable until nested execution is governed.",transport:{location:"query",name:"mode"}},
];
const posthogMethod=(key,auth,extra={})=>method(key,"mcp_remote",auth,{serverUrl:"https://mcp.posthog.com/mcp"},"S3","Pin the connection to one PostHog project and expose the full tool catalog by default. Narrow feature groups or tools only when needed.",{tenantFields:posthogConfigFields(),requiredResourceFilters:["project"],...extra});
const apps=[
["zapier","Zapier","Reach thousands of apps through your Zapier account.","productivity","zapier.com",["https://mcp.zapier.com/*"],method("mcp-key","mcp_remote","api_key",{serverUrl:"https://mcp.zapier.com/api/mcp"},"S3","Create a Zapier MCP connection, then paste its token here.",{credentialFields:[field("authorization","Zapier MCP token","Paste your Zapier token")],keyPlacement:{location:"header",name:"Authorization",prefix:"Bearer "}})],
["github","GitHub","Read code and pull requests, and coordinate repository work.","developer","github.com",["https://api.githubcopilot.com/mcp/*"],method("mcp-key","mcp_remote","api_key",{serverUrl:"https://api.githubcopilot.com/mcp/"},"S3","Create a fine-grained token limited to the repositories agents should use.",{credentialFields:[field("authorization","GitHub token","github_pat_...")],keyPlacement:{location:"header",name:"Authorization",prefix:"Bearer "},requiredResourceFilters:["organization","repository"]})],
["slack","Slack","Search channels and coordinate team communication.","communication","slack.com",["https://mcp.slack.com/*"],method("mcp-oauth","mcp_remote","oauth",{serverUrl:"https://mcp.slack.com/mcp",authorizationEndpoint:"https://slack.com/oauth/v2/authorize",tokenEndpoint:"https://slack.com/api/oauth.v2.access",scopesHint:["channels:read","chat:write","search:read"]},"S3","Connect a Slack workspace and limit access to the channels agents need.",{requiredResourceFilters:["workspace","channel"]})],
["notion","Notion","Read and update pages in your Notion workspace.","content","notion.so",["https://mcp.notion.com/*"],method("mcp-oauth","mcp_remote","oauth",{serverUrl:"https://mcp.notion.com/mcp"},"S3","Connect Notion for workspace content. Share only the pages and databases agents should use.",{requiredResourceFilters:["workspace","page","database"]}),{redirectConstraints:"https-or-loopback-http"}],
["posthog","PostHog","Analyze product usage, errors, feature flags, and experiments in a pinned PostHog project.","analytics","posthog.com",["https://mcp.posthog.com/*"],[posthogMethod("mcp-oauth","oauth",{label:"Sign in with PostHog",ownershipModes:["customer","dcr"],whenToUse:"Sign in with PostHog in the browser. Recommended for hosted PostHog accounts.",consoleLinks:{docs:"https://posthog.com/docs/model-context-protocol"}}),posthogMethod("mcp-api-key","api_key",{label:"Use a personal API key",whenToUse:"Use a PostHog personal API key when browser sign-in is not suitable.",credentialFields:[field("authorization","PostHog personal API key","phx_...")],keyPlacement:{location:"header",name:"Authorization",prefix:"Bearer "},consoleLinks:{keys:"https://posthog.com/docs/model-context-protocol/faq",docs:"https://posthog.com/docs/model-context-protocol/faq"}})],{featured:true}],
["linear","Linear","Create, update, and read Linear issues.","productivity","linear.app",["https://mcp.linear.app/*"],method("mcp-oauth","mcp_remote","oauth",{serverUrl:"https://mcp.linear.app/mcp",authorizationEndpoint:"https://linear.app/oauth/authorize",tokenEndpoint:"https://api.linear.app/oauth/token",scopesHint:["read","write"]},"S2","Register a Linear OAuth app and add Paperclip's redirect URI before connecting.",{requiredResourceFilters:["workspace","team","project"]})],
["google-sheets","Google Sheets","Read and update selected spreadsheets.","data","sheets.google.com",["https://docs.google.com/spreadsheets/*","https://sheets.google.com/*"],method("local","local_stdio","none",{templateKey:"paperclip.google-sheets"},"S3","Share each spreadsheet with the Paperclip robot email, then paste the sheet links.",{requiredResourceFilters:["spreadsheet"]})],
["context7","Context7","Look up current documentation for software libraries.","developer","context7.com",["https://mcp.context7.com/*"],method("mcp","mcp_remote","none",{serverUrl:"https://mcp.context7.com/mcp"},"S1","Connect Context7 to give agents current library documentation.")],
@@ -16,7 +25,7 @@ const apps=[
["sentry","Sentry","Investigate errors, releases, and production issues.","developer","sentry.io",["https://mcp.sentry.dev/*"],method("mcp-oauth","mcp_remote","oauth",{serverUrl:"https://mcp.sentry.dev/mcp",discoveryUrl:"https://sentry.io/.well-known/oauth-authorization-server"},"S2","Connect the Sentry organization and projects agents need for incident work.",{requiredResourceFilters:["organization","project","environment"]})],
["vercel","Vercel","Inspect projects, deployments, and runtime logs.","developer","vercel.com",["https://mcp.vercel.com/*"],method("mcp-oauth","mcp_remote","oauth",{serverUrl:"https://mcp.vercel.com/mcp"},"S3","Connect the Vercel team and projects agents should operate.",{requiredResourceFilters:["team","project","environment"]})],
["anthropic","Anthropic","Use Anthropic APIs with a restricted key.","ai","anthropic.com",["https://api.anthropic.com/*"],method("api-key","rest_api","api_key",{serviceHost:"api.anthropic.com"},"S3","Create a key in the Anthropic Console and rotate it if it has been exposed.",{credentialFields:[field("apiKey","API key","sk-ant-api03-...")],keyPlacement:{location:"header",name:"x-api-key"}})],
].map(([slug,name,description,category,domain,urlPatterns,m,extra={}])=>({schemaVersion:1,slug,name,description,categories:[category],featured:["zapier","github","slack","notion","linear"].includes(slug),branding:{logoUrl:favicon(domain)},urlPatterns,methods:[m],...extra}));
].map(([slug,name,description,category,domain,urlPatterns,m,extra={}])=>({schemaVersion:1,slug,name,description,categories:[category],featured:["zapier","github","slack","notion","posthog","linear"].includes(slug),branding:{logoUrl:favicon(domain)},urlPatterns,methods:Array.isArray(m)?m:[m],...extra}));
const parseTableRow=(line)=>line.slice(1,-1).split("|").map((cell)=>cell.trim());
const parseCapture=(fileName)=>{
const markdown=fs.readFileSync(path.join(corpus,fileName),"utf8");
+469
View File
@@ -0,0 +1,469 @@
const REQUIRED_ENVIRONMENT = [
"PAPERCLIP_E2E_BASE_URL",
"PAPERCLIP_E2E_EMAIL",
"PAPERCLIP_DEV_LOGIN_PASSWORD",
"PAPERCLIP_API_URL",
"PAPERCLIP_API_KEY",
"PAPERCLIP_RUN_ID",
"PAPERCLIP_TASK_ID",
];
// Agent secret APIs expose access.notion_generic_flow_test_account under this
// normalized delivery key; the live harness never reads any other binding.
export const NOTION_SECRET_BINDING_KEY = "generic-flow-test-account";
const NOTION_LOGIN_MAIL_DOMAINS = ["notion.so", "makenotion.com"];
export class NotionGenericLivePreflightError extends Error {
constructor(code, details = {}) {
super(code);
this.name = "NotionGenericLivePreflightError";
this.code = code;
this.details = details;
}
}
function emailDomain(value) {
const match = String(value ?? "").match(/@([A-Za-z0-9.-]+)/);
return match?.[1]?.toLowerCase().replace(/\.$/, "") ?? "";
}
function notionMailDomain(value) {
const domain = emailDomain(value);
return NOTION_LOGIN_MAIL_DOMAINS.some((allowed) => domain === allowed || domain.endsWith(`.${allowed}`));
}
export function isFreshNotionVerificationMessage(message, { notBefore }) {
const timestamp = new Date(message?.timestamp ?? message?.createdAt ?? Number.NaN).getTime();
const lowerSubject = String(message?.subject ?? "").toLowerCase();
const challengeSubject = /(?:login|verification|one[-\s]?time|temporary|security).*(?:code|pin)|(?:code|pin).*(?:login|verification|one[-\s]?time|temporary|security)/i.test(lowerSubject);
return notionMailDomain(message?.from)
&& challengeSubject
&& Number.isFinite(timestamp)
&& timestamp >= new Date(notBefore).getTime();
}
export function notionVerificationAuthenticationPassed(message) {
const headers = message?.headers && typeof message.headers === "object" && !Array.isArray(message.headers)
? message.headers
: {};
const authentication = Object.entries(headers)
.filter(([key]) => key.toLowerCase().includes("authentication-results"))
.map(([, value]) => String(value).toLowerCase())
.join(" ");
return authentication.includes("dkim=pass")
&& (authentication.includes("dmarc=pass")
|| authentication.includes("spf=pass")
|| authentication.includes("arc=pass"));
}
export function extractNotionVerificationCode(message) {
const content = [
message?.subject,
message?.extractedText,
message?.text,
message?.extractedHtml,
message?.html,
]
.filter((value) => typeof value === "string")
.join("\n")
.replace(/<[^>]+>/g, " ");
const digitSequence = "([0-9](?:[\\s-]?[0-9]){5})";
const patterns = [
new RegExp(`(?:login|verification|one[-\\s]?time|temporary|security)[^\\n]{0,40}(?:code|pin)[^0-9]{0,40}${digitSequence}`, "gi"),
new RegExp(`(?:code|pin)[^0-9]{0,40}${digitSequence}`, "gi"),
new RegExp(`${digitSequence}[^\\n]{0,40}(?:login|verification|one[-\\s]?time|temporary|security)?[^\\n]{0,20}(?:code|pin)`, "gi"),
];
const codes = new Set();
for (const pattern of patterns) {
for (const match of content.matchAll(pattern)) {
const code = match[1].replace(/[^0-9]/g, "");
if (code.length === 6) codes.add(code);
}
}
for (const label of content.matchAll(/(?:code|pin)/gi)) {
const window = content.slice(label.index, label.index + 120);
for (const match of window.matchAll(/(^|[^0-9])([0-9](?:[\s-]?[0-9]){5})(?![0-9])/g)) {
codes.add(match[2].replace(/[^0-9]/g, ""));
}
}
return codes.size === 1 ? [...codes][0] : null;
}
function requiredValue(environment, key) {
const value = environment[key];
return typeof value === "string" ? value.trim() : "";
}
function explicitHttpsOrigin(raw, code) {
let value;
try {
value = new URL(raw);
} catch {
throw new NotionGenericLivePreflightError(code);
}
if (value.protocol !== "https:"
|| value.username
|| value.password
|| value.search
|| value.hash
|| (value.pathname !== "/" && value.pathname !== "/api" && value.pathname !== "/api/")) {
throw new NotionGenericLivePreflightError(code);
}
return value;
}
export function preflightNotionGenericLive(environment = process.env) {
const missing = REQUIRED_ENVIRONMENT.filter((key) => requiredValue(environment, key) === "");
if (missing.length > 0) {
throw new NotionGenericLivePreflightError("missing_environment", { missing });
}
const base = explicitHttpsOrigin(requiredValue(environment, "PAPERCLIP_E2E_BASE_URL"), "unsafe_base_url");
const api = explicitHttpsOrigin(requiredValue(environment, "PAPERCLIP_API_URL"), "unsafe_api_url");
const email = requiredValue(environment, "PAPERCLIP_E2E_EMAIL");
if (!email.includes("@")) throw new NotionGenericLivePreflightError("invalid_paperclip_email");
return {
baseUrl: base.origin,
apiBaseUrl: `${api.origin}/api`,
callbackUrl: `${base.origin}/api/tools/oauth/callback`,
paperclipEmail: email,
paperclipPassword: environment.PAPERCLIP_DEV_LOGIN_PASSWORD,
agentApiKey: environment.PAPERCLIP_API_KEY,
runId: environment.PAPERCLIP_RUN_ID,
taskId: environment.PAPERCLIP_TASK_ID,
secretBindingKey: NOTION_SECRET_BINDING_KEY,
};
}
async function responseJson(response, code) {
try {
return await response.json();
} catch {
throw new NotionGenericLivePreflightError(code);
}
}
async function fetchWithTimeout(fetchImpl, url, init) {
try {
return await fetchImpl(url, { ...init, signal: AbortSignal.timeout(15_000) });
} catch {
throw new NotionGenericLivePreflightError("request_failed");
}
}
export async function prepareNotionGenericLiveSmoke({
environment = process.env,
fetchImpl = globalThis.fetch,
loadBrowser,
}) {
const config = preflightNotionGenericLive(environment);
const healthResponse = await fetchWithTimeout(
fetchImpl,
new URL("/api/health", config.baseUrl),
{ headers: { accept: "application/json" } },
);
if (!healthResponse.ok) {
throw new NotionGenericLivePreflightError("health_http_error", { status: healthResponse.status });
}
const health = await responseJson(healthResponse, "health_invalid_json");
if (health?.status !== "ok") throw new NotionGenericLivePreflightError("health_not_ok");
const secretsResponse = await fetchWithTimeout(
fetchImpl,
`${config.apiBaseUrl}/agents/me/secrets`,
{
headers: {
accept: "application/json",
authorization: `Bearer ${config.agentApiKey}`,
},
},
);
if (!secretsResponse.ok) {
throw new NotionGenericLivePreflightError("secret_metadata_http_error", { status: secretsResponse.status });
}
const secretMetadata = await responseJson(secretsResponse, "secret_metadata_invalid_json");
const available = Array.isArray(secretMetadata?.secrets)
&& secretMetadata.secrets.some((entry) => entry?.key === config.secretBindingKey && entry?.delivery === "api");
if (!available) throw new NotionGenericLivePreflightError("secret_binding_unavailable");
return { config, browserModule: await loadBrowser() };
}
export async function fetchNotionTestCredentials(config, fetchImpl = globalThis.fetch) {
const response = await fetchWithTimeout(
fetchImpl,
`${config.apiBaseUrl}/agents/me/secrets/${encodeURIComponent(config.secretBindingKey)}/value`,
{
method: "POST",
headers: {
accept: "application/json",
authorization: `Bearer ${config.agentApiKey}`,
},
},
);
if (!response.ok) {
throw new NotionGenericLivePreflightError("secret_value_http_error", { status: response.status });
}
const body = await responseJson(response, "secret_value_invalid_json");
if (typeof body?.value !== "string") {
throw new NotionGenericLivePreflightError("secret_value_missing");
}
let credential;
try {
credential = JSON.parse(body.value);
} catch {
throw new NotionGenericLivePreflightError("secret_value_invalid_shape");
}
const username = [credential?.email, credential?.username, credential?.login]
.find((value) => typeof value === "string" && value.trim());
const password = typeof credential?.password === "string" ? credential.password : "";
if (!username || !password) {
throw new NotionGenericLivePreflightError("secret_value_invalid_shape");
}
return { username: username.trim(), password };
}
export function assertAutomaticRegistrationSource(source) {
if (source !== "cimd" && source !== "dcr") {
throw new NotionGenericLivePreflightError("unexpected_registration_source");
}
return source;
}
export function persistedOAuthStartResult(connection, authorizationUrl) {
const cleanAuthorizationUrl = typeof authorizationUrl === "string" ? authorizationUrl.trim() : "";
const oauth = connection?.config?.oauth;
if (!connection?.id || !cleanAuthorizationUrl || !oauth || typeof oauth !== "object" || Array.isArray(oauth)) {
return null;
}
return {
connectionId: connection.id,
authorizationUrl: cleanAuthorizationUrl,
registrationSource: oauth.clientRegistrationSource ?? null,
issuer: oauth.issuer ?? null,
resource: oauth.resource ?? null,
};
}
function nonNegativeInteger(value) {
return Number.isInteger(value) && value >= 0;
}
/**
* Normalize the server's sanitized removal receipt. Partial-flow cleanup may
* legitimately remove zero installs or credentials; the completed smoke uses
* the stricter mode to prove the installed/authenticated state was revoked.
*/
export function connectionRemovalFacts(receipt, { requireInstalled = false } = {}) {
if (!receipt || typeof receipt !== "object" || Array.isArray(receipt)) return null;
const numericFields = [
"installsRemoved",
"appProfileBindingsRemoved",
"credentialRefsCleared",
"secretsRevoked",
"secretBindingsRemoved",
"grantsRevoked",
"oauthStatesDiscarded",
"runtimeSlotsStopped",
];
if (numericFields.some((key) => !nonNegativeInteger(receipt[key]))) return null;
const credentialsRemoved = receipt.credentialRefsCleared + receipt.secretsRevoked;
if (!["absent", "deleted", "archived"].includes(receipt.appProfile)) return null;
if (requireInstalled && (
receipt.installsRemoved !== 1
|| receipt.appProfileBindingsRemoved < 1
|| credentialsRemoved < 1
|| !["deleted", "archived"].includes(receipt.appProfile)
)) return null;
return {
credentialsRemoved,
secretBindingsRemoved: receipt.secretBindingsRemoved,
grantsRevoked: receipt.grantsRevoked,
accessBindingsRemoved: receipt.appProfileBindingsRemoved,
installsRemoved: receipt.installsRemoved,
oauthStatesDiscarded: receipt.oauthStatesDiscarded,
runtimeSlotsStopped: receipt.runtimeSlotsStopped,
appProfile: receipt.appProfile,
};
}
export function safeEndpointSummary(raw, label) {
let endpoint;
try {
endpoint = new URL(raw);
} catch {
throw new NotionGenericLivePreflightError(`unsafe_${label}_endpoint`);
}
if (endpoint.protocol !== "https:"
|| endpoint.username
|| endpoint.password
|| endpoint.search
|| endpoint.hash) {
throw new NotionGenericLivePreflightError(`unsafe_${label}_endpoint`);
}
return { origin: endpoint.origin, path: endpoint.pathname };
}
export function inspectAuthorizationUrl(raw, {
callbackUrl,
resource,
registrationSource,
baseUrl,
}) {
let target;
try {
target = new URL(raw);
} catch {
throw new NotionGenericLivePreflightError("unsafe_authorization_endpoint");
}
if (target.protocol !== "https:" || target.username || target.password || target.hash) {
throw new NotionGenericLivePreflightError("unsafe_authorization_endpoint");
}
const required = ["client_id", "state", "code_challenge", "redirect_uri", "resource"];
if (required.some((key) => !target.searchParams.get(key))) {
throw new NotionGenericLivePreflightError("authorization_parameter_missing");
}
if (target.searchParams.get("code_challenge_method") !== "S256") {
throw new NotionGenericLivePreflightError("pkce_s256_missing");
}
if (target.searchParams.get("redirect_uri") !== callbackUrl) {
throw new NotionGenericLivePreflightError("callback_uri_mismatch");
}
if (target.searchParams.get("resource") !== resource) {
throw new NotionGenericLivePreflightError("resource_mismatch");
}
if (target.searchParams.get("response_type") !== "code") {
throw new NotionGenericLivePreflightError("response_type_mismatch");
}
if (registrationSource === "cimd") {
const expectedClientId = new URL("/api/tools/oauth/client-metadata", baseUrl).toString();
if (target.searchParams.get("client_id") !== expectedClientId) {
throw new NotionGenericLivePreflightError("cimd_client_id_mismatch");
}
}
return {
endpoint: { origin: target.origin, path: target.pathname },
parameters: {
clientId: true,
state: true,
pkceS256: true,
callbackUri: true,
resource: true,
},
};
}
function parsedJsonString(value) {
const trimmed = value.trim();
if (trimmed.length === 0 || trimmed.length > 200_000) return null;
const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
for (const candidate of fenced ? [fenced[1], trimmed] : [trimmed]) {
if (!candidate.startsWith("{") && !candidate.startsWith("[")) continue;
try {
return JSON.parse(candidate);
} catch {
// A later recursive branch may still contain structured content.
}
}
return null;
}
export function extractNotionIdentity(value) {
const seen = new Set();
const facts = { workspaceId: null, workspaceName: null, botId: null };
const visit = (candidate, depth) => {
if (depth > 12 || candidate === null || candidate === undefined) return;
if (typeof candidate === "string") {
const parsed = parsedJsonString(candidate);
if (parsed !== null) visit(parsed, depth + 1);
return;
}
if (typeof candidate !== "object" || seen.has(candidate)) return;
seen.add(candidate);
if (!Array.isArray(candidate)) {
const workspaceId = candidate.workspace_id ?? candidate.workspaceId;
const workspaceName = candidate.workspace_name ?? candidate.workspaceName;
if (!facts.workspaceId && typeof workspaceId === "string" && workspaceId.trim()) facts.workspaceId = workspaceId.trim();
if (!facts.workspaceName && typeof workspaceName === "string" && workspaceName.trim()) facts.workspaceName = workspaceName.trim();
if (!facts.botId && candidate.type === "bot" && typeof candidate.id === "string" && candidate.id.trim()) {
facts.botId = candidate.id.trim();
}
}
for (const child of Array.isArray(candidate) ? candidate : Object.values(candidate)) visit(child, depth + 1);
};
visit(value, 0);
return (facts.workspaceId || facts.botId) && facts.workspaceName ? facts : null;
}
export function parseSanitizedAgentProof(commentBody, expectedIdentity) {
if (typeof commentBody !== "string") return null;
const trimmed = commentBody.trim();
const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
let parsed;
try {
parsed = JSON.parse(fenced ? fenced[1] : trimmed);
} catch {
return null;
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
if (Object.keys(parsed).sort().join(",") !== "invocationId,workspaceId,workspaceName") return null;
if (parsed.workspaceId !== expectedIdentity.workspaceId || parsed.workspaceName !== expectedIdentity.workspaceName) return null;
if (typeof parsed.invocationId !== "string" || !parsed.invocationId.trim()) return null;
return {
workspaceId: parsed.workspaceId,
workspaceName: parsed.workspaceName,
invocationId: parsed.invocationId.trim(),
};
}
export function parseRuntimeAbsenceProof(commentBody, connectionId) {
if (typeof commentBody !== "string") return null;
let parsed;
try {
parsed = JSON.parse(commentBody.trim());
} catch {
return null;
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
if (Object.keys(parsed).sort().join(",") !== "connectionId,toolPresent") return null;
return parsed.connectionId === connectionId && parsed.toolPresent === false
? { connectionId, toolPresent: false }
: null;
}
const FORBIDDEN_EVIDENCE_KEYS = /(?:password|access[_-]?token|refresh[_-]?token|authorization|cookie|oauth[_-]?code|client[_-]?secret|session)/i;
const FORBIDDEN_EVIDENCE_TEXT = /(?:authorization:\s*bearer|cookie:|[?&](?:code|state|token|access_token|refresh_token)=)/i;
export function assertSanitizedEvidence(value) {
const seen = new Set();
const visit = (candidate, path) => {
if (candidate === null || candidate === undefined) return;
if (typeof candidate === "string") {
if (FORBIDDEN_EVIDENCE_TEXT.test(candidate)) throw new Error(`unsafe_evidence_text:${path}`);
return;
}
if (typeof candidate !== "object" || seen.has(candidate)) return;
seen.add(candidate);
for (const [key, child] of Object.entries(candidate)) {
if (FORBIDDEN_EVIDENCE_KEYS.test(key)) throw new Error(`unsafe_evidence_key:${path}.${key}`);
visit(child, `${path}.${key}`);
}
};
visit(value, "$");
}
export function preflightFailureMessage(error) {
if (!(error instanceof NotionGenericLivePreflightError)) {
return "Notion generic live smoke preflight failed.";
}
if (error.code === "missing_environment") {
return `Notion generic live smoke preflight failed: missing ${error.details.missing.join(", ")}.`;
}
if (error.code === "health_http_error") {
return `Notion generic live smoke preflight failed: /api/health returned HTTP ${error.details.status}.`;
}
return `Notion generic live smoke preflight failed: ${error.code}.`;
}
File diff suppressed because it is too large. Load diff
+286
View File
@@ -0,0 +1,286 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
assertAutomaticRegistrationSource,
assertSanitizedEvidence,
connectionRemovalFacts,
extractNotionIdentity,
extractNotionVerificationCode,
inspectAuthorizationUrl,
isFreshNotionVerificationMessage,
NotionGenericLivePreflightError,
notionVerificationAuthenticationPassed,
parseRuntimeAbsenceProof,
parseSanitizedAgentProof,
persistedOAuthStartResult,
preflightNotionGenericLive,
prepareNotionGenericLiveSmoke,
safeEndpointSummary,
} from "./notion-generic-live-lib.mjs";
const COMPLETE_ENV = {
PAPERCLIP_E2E_BASE_URL: "https://paperclip.example.test",
PAPERCLIP_E2E_EMAIL: "operator@example.test",
PAPERCLIP_DEV_LOGIN_PASSWORD: "not-a-real-password",
PAPERCLIP_API_URL: "https://paperclip.example.test/api",
PAPERCLIP_API_KEY: "not-a-real-agent-key",
PAPERCLIP_RUN_ID: "run-123",
PAPERCLIP_TASK_ID: "issue-123",
};
test("preflight reports binding names without exposing supplied values", () => {
assert.throws(
() => preflightNotionGenericLive({ PAPERCLIP_DEV_LOGIN_PASSWORD: "present" }),
(error) => {
assert.ok(error instanceof NotionGenericLivePreflightError);
assert.equal(error.code, "missing_environment");
assert.deepEqual(error.details.missing, [
"PAPERCLIP_E2E_BASE_URL",
"PAPERCLIP_E2E_EMAIL",
"PAPERCLIP_API_URL",
"PAPERCLIP_API_KEY",
"PAPERCLIP_RUN_ID",
"PAPERCLIP_TASK_ID",
]);
assert.doesNotMatch(error.message, /present/);
return true;
},
);
});
test("preflight requires explicit credential-free HTTPS target and control-plane URLs", () => {
for (const baseUrl of [
"http://127.0.0.1:3100",
"http://paperclip.example.test",
"https://user:secret@paperclip.example.test",
"https://paperclip.example.test/?code=secret",
]) {
assert.throws(
() => preflightNotionGenericLive({ ...COMPLETE_ENV, PAPERCLIP_E2E_BASE_URL: baseUrl }),
(error) => error instanceof NotionGenericLivePreflightError && error.code === "unsafe_base_url",
);
}
const split = preflightNotionGenericLive({
...COMPLETE_ENV,
PAPERCLIP_API_URL: "https://control-plane.example.test/api",
});
assert.equal(split.baseUrl, "https://paperclip.example.test");
assert.equal(split.apiBaseUrl, "https://control-plane.example.test/api");
});
test("health and binding metadata pass before browser loading, without fetching the value", async () => {
const requests = [];
let browserLoaded = false;
const prepared = await prepareNotionGenericLiveSmoke({
environment: COMPLETE_ENV,
fetchImpl: async (url, init = {}) => {
requests.push({ url: String(url), method: init.method ?? "GET" });
if (String(url).endsWith("/api/health")) {
return { ok: true, json: async () => ({ status: "ok" }) };
}
return {
ok: true,
json: async () => ({ secrets: [{ key: "generic-flow-test-account", delivery: "api" }] }),
};
},
loadBrowser: async () => {
browserLoaded = true;
return { chromium: {} };
},
});
assert.equal(prepared.config.callbackUrl, "https://paperclip.example.test/api/tools/oauth/callback");
assert.equal(browserLoaded, true);
assert.deepEqual(requests.map((entry) => entry.method), ["GET", "GET"]);
assert.equal(requests.some((entry) => entry.url.includes("/value")), false);
});
test("an unavailable secret binding fails before browser or credential entry", async () => {
let browserLoaded = false;
await assert.rejects(
prepareNotionGenericLiveSmoke({
environment: COMPLETE_ENV,
fetchImpl: async (url) => String(url).endsWith("/api/health")
? { ok: true, json: async () => ({ status: "ok" }) }
: { ok: true, json: async () => ({ secrets: [] }) },
loadBrowser: async () => {
browserLoaded = true;
},
}),
(error) => error instanceof NotionGenericLivePreflightError && error.code === "secret_binding_unavailable",
);
assert.equal(browserLoaded, false);
});
test("selects only fresh authenticated Notion verification mail and extracts one code", () => {
const notBefore = new Date("2026-08-18T12:00:00.000Z");
const message = {
timestamp: new Date("2026-08-18T12:00:05.000Z"),
from: "Notion <login@mail.notion.so>",
subject: "Your Notion login code",
extractedText: "Your temporary login code is 123 456.",
headers: {
"authentication-results": "dkim=pass; spf=pass; dmarc=pass",
},
};
assert.equal(isFreshNotionVerificationMessage(message, { notBefore }), true);
assert.equal(notionVerificationAuthenticationPassed(message), true);
assert.equal(extractNotionVerificationCode(message), "123456");
assert.equal(isFreshNotionVerificationMessage({
...message,
timestamp: new Date("2026-08-18T11:59:59.000Z"),
}, { notBefore }), false);
assert.equal(isFreshNotionVerificationMessage({
...message,
from: "Notion <login@example.test>",
}, { notBefore }), false);
assert.equal(notionVerificationAuthenticationPassed({
...message,
headers: { "authentication-results": "dkim=fail; spf=pass" },
}), false);
assert.equal(extractNotionVerificationCode({ ...message, extractedText: "Codes 123456 and 654321" }), null);
});
test("authorization proof requires automatic registration, PKCE, callback, resource, and safe endpoints", () => {
assert.equal(assertAutomaticRegistrationSource("cimd"), "cimd");
assert.equal(assertAutomaticRegistrationSource("dcr"), "dcr");
for (const source of ["manual", "preconfigured", null]) {
assert.throws(
() => assertAutomaticRegistrationSource(source),
(error) => error instanceof NotionGenericLivePreflightError && error.code === "unexpected_registration_source",
);
}
const baseUrl = "https://paperclip.example.test";
const callbackUrl = `${baseUrl}/api/tools/oauth/callback`;
const resource = "https://mcp.notion.com/mcp";
const url = new URL("https://mcp.notion.com/authorize");
url.searchParams.set("response_type", "code");
url.searchParams.set("client_id", `${baseUrl}/api/tools/oauth/client-metadata`);
url.searchParams.set("redirect_uri", callbackUrl);
url.searchParams.set("state", "not-recorded");
url.searchParams.set("code_challenge", "not-recorded");
url.searchParams.set("code_challenge_method", "S256");
url.searchParams.set("resource", resource);
assert.deepEqual(inspectAuthorizationUrl(url.toString(), {
callbackUrl,
resource,
registrationSource: "cimd",
baseUrl,
}), {
endpoint: { origin: "https://mcp.notion.com", path: "/authorize" },
parameters: { clientId: true, state: true, pkceS256: true, callbackUri: true, resource: true },
});
assert.deepEqual(safeEndpointSummary("https://mcp.notion.com/token", "token"), {
origin: "https://mcp.notion.com",
path: "/token",
});
assert.throws(
() => safeEndpointSummary("http://mcp.notion.com/token", "token"),
(error) => error instanceof NotionGenericLivePreflightError && error.code === "unsafe_token_endpoint",
);
});
test("authorization proof rejects a provider login page after OAuth parameters were consumed", () => {
assert.throws(
() => inspectAuthorizationUrl("https://id.notion.test/login", {
callbackUrl: "https://paperclip.example/api/tools/oauth/callback",
resource: "https://mcp.notion.com/mcp",
registrationSource: "dcr",
baseUrl: "https://paperclip.example",
}),
(error) => error instanceof NotionGenericLivePreflightError
&& error.code === "authorization_parameter_missing",
);
});
test("reconstructs the inline OAuth start from durable connection state and provider navigation", () => {
assert.deepEqual(persistedOAuthStartResult({
id: "connection-123",
config: {
oauth: {
clientRegistrationSource: "cimd",
issuer: "https://mcp.notion.com",
resource: "https://mcp.notion.com/mcp",
},
},
}, " https://mcp.notion.com/authorize?state=not-recorded "), {
connectionId: "connection-123",
authorizationUrl: "https://mcp.notion.com/authorize?state=not-recorded",
registrationSource: "cimd",
issuer: "https://mcp.notion.com",
resource: "https://mcp.notion.com/mcp",
});
assert.equal(persistedOAuthStartResult({ id: "connection-123", config: {} }, "https://example.test"), null);
});
test("accepts zero-count cleanup before setup but requires full revocation after install", () => {
const partial = {
installsRemoved: 0,
appProfileBindingsRemoved: 0,
credentialRefsCleared: 0,
secretsRevoked: 0,
secretBindingsRemoved: 0,
grantsRevoked: 0,
oauthStatesDiscarded: 1,
runtimeSlotsStopped: 0,
appProfile: "absent",
};
assert.deepEqual(connectionRemovalFacts(partial), {
credentialsRemoved: 0,
secretBindingsRemoved: 0,
grantsRevoked: 0,
accessBindingsRemoved: 0,
installsRemoved: 0,
oauthStatesDiscarded: 1,
runtimeSlotsStopped: 0,
appProfile: "absent",
});
assert.equal(connectionRemovalFacts(partial, { requireInstalled: true }), null);
assert.ok(connectionRemovalFacts({
...partial,
installsRemoved: 1,
appProfileBindingsRemoved: 1,
secretsRevoked: 1,
appProfile: "deleted",
}, { requireInstalled: true }));
});
test("workspace proof extraction and fresh-run comments retain only sanitized identity", () => {
const identity = extractNotionIdentity({
result: {
content: [{
type: "text",
text: JSON.stringify({
id: "bot-123",
type: "bot",
bot: { workspace_id: "workspace-123", workspace_name: "Paperclip" },
token: "discard-me",
}),
}],
},
});
assert.deepEqual(identity, {
workspaceId: "workspace-123",
workspaceName: "Paperclip",
botId: "bot-123",
});
assert.deepEqual(
parseSanitizedAgentProof(
'{"workspaceId":"workspace-123","workspaceName":"Paperclip","invocationId":"inv-123"}',
identity,
),
{ workspaceId: "workspace-123", workspaceName: "Paperclip", invocationId: "inv-123" },
);
assert.deepEqual(
parseRuntimeAbsenceProof('{"connectionId":"conn-123","toolPresent":false}', "conn-123"),
{ connectionId: "conn-123", toolPresent: false },
);
});
test("sanitized evidence rejects credential fields, sessions, and OAuth query values", () => {
assert.doesNotThrow(() => assertSanitizedEvidence({ workspaceId: "workspace-123", invocationId: "inv-123" }));
assert.throws(() => assertSanitizedEvidence({ accessToken: "secret" }), /unsafe_evidence_key/);
assert.throws(() => assertSanitizedEvidence({ sessionId: "secret" }), /unsafe_evidence_key/);
assert.throws(() => assertSanitizedEvidence({ note: "callback?code=secret" }), /unsafe_evidence_text/);
});
+247
View File
@@ -0,0 +1,247 @@
const REQUIRED_ENVIRONMENT = [
"INTEGRATIONS_POSTHOG_PAPERCLIP_E2E_EMAIL",
"INTEGRATIONS_POSTHOG_PAPERCLIP_DEV_LOGIN_PASSWORD",
"INTEGRATIONS_POSTHOG_POSTHOG_PROJECT_ID",
];
const REQUIRED_PROJECT_ID = "483530";
export class PosthogLivePreflightError extends Error {
constructor(code, details = {}) {
super(code);
this.name = "PosthogLivePreflightError";
this.code = code;
this.details = details;
}
}
function requiredValue(environment, key) {
const value = environment[key];
return typeof value === "string" ? value.trim() : "";
}
export function parsePosthogLiveArguments(args = []) {
if (args.length === 0) return {};
if (args.length === 1 && !args[0].startsWith("-")) return { baseUrl: args[0] };
if (args.length === 2 && args[0] === "--base-url" && args[1].trim()) {
return { baseUrl: args[1] };
}
throw new PosthogLivePreflightError("invalid_arguments");
}
export function preflightPosthogLive(environment = process.env, options = {}) {
const missing = REQUIRED_ENVIRONMENT.filter((key) => requiredValue(environment, key) === "");
if (missing.length > 0) {
throw new PosthogLivePreflightError("missing_environment", { missing });
}
const baseUrlValue = typeof options.baseUrl === "string" && options.baseUrl.trim()
? options.baseUrl.trim()
: requiredValue(environment, "PAPERCLIP_API_URL");
if (!baseUrlValue) {
throw new PosthogLivePreflightError("missing_base_url");
}
let baseUrl;
try {
baseUrl = new URL(baseUrlValue);
} catch {
throw new PosthogLivePreflightError("invalid_base_url");
}
const loopback = baseUrl.hostname === "127.0.0.1" || baseUrl.hostname === "localhost" || baseUrl.hostname === "[::1]";
if ((baseUrl.protocol !== "https:" && !(loopback && baseUrl.protocol === "http:"))
|| baseUrl.username
|| baseUrl.password
|| baseUrl.search
|| baseUrl.hash) {
throw new PosthogLivePreflightError("unsafe_base_url");
}
baseUrl.pathname = baseUrl.pathname.replace(/\/+$/, "") || "/";
const projectId = requiredValue(environment, "INTEGRATIONS_POSTHOG_POSTHOG_PROJECT_ID");
if (!/^\d+$/.test(projectId)) {
throw new PosthogLivePreflightError("invalid_project_id");
}
if (projectId !== REQUIRED_PROJECT_ID) {
throw new PosthogLivePreflightError("unexpected_project_id");
}
const email = requiredValue(environment, "INTEGRATIONS_POSTHOG_PAPERCLIP_E2E_EMAIL");
if (!email.includes("@")) {
throw new PosthogLivePreflightError("invalid_email");
}
return {
baseUrl: baseUrl.origin,
email,
password: environment.INTEGRATIONS_POSTHOG_PAPERCLIP_DEV_LOGIN_PASSWORD,
projectId,
};
}
export async function preparePosthogLiveSmoke({
environment = process.env,
baseUrl,
fetchImpl = globalThis.fetch,
loadBrowser,
}) {
const config = preflightPosthogLive(environment, { baseUrl });
let response;
try {
response = await fetchImpl(new URL("/api/health", config.baseUrl), {
headers: { accept: "application/json" },
signal: AbortSignal.timeout(15_000),
});
} catch {
throw new PosthogLivePreflightError("health_unreachable");
}
if (!response.ok) {
throw new PosthogLivePreflightError("health_http_error", { status: response.status });
}
let body;
try {
body = await response.json();
} catch {
throw new PosthogLivePreflightError("health_invalid_json");
}
if (body?.status !== "ok") {
throw new PosthogLivePreflightError("health_not_ok");
}
return { config, browserModule: await loadBrowser() };
}
function projectIdFrom(candidate) {
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return null;
for (const key of ["projectId", "project_id", "projectID", "id"]) {
const value = candidate[key];
if (typeof value === "string" || typeof value === "number") return String(value);
}
return null;
}
function projectNameFrom(candidate) {
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return null;
for (const key of ["projectName", "project_name", "name"]) {
const value = candidate[key];
if (typeof value === "string" && value.trim()) return value.trim();
}
return null;
}
function parsedJsonString(value) {
const trimmed = value.trim();
if (trimmed.length === 0 || trimmed.length > 200_000) return null;
const candidates = [trimmed];
const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
if (fenced) candidates.unshift(fenced[1]);
for (const candidate of candidates) {
if (!candidate.startsWith("{") && !candidate.startsWith("[")) continue;
try {
return JSON.parse(candidate);
} catch {
// Some MCP servers wrap structured JSON in prose; the regex fallback below
// handles the small project summary without retaining that prose.
}
}
return null;
}
export function extractProjectSummary(value, expectedProjectId) {
const seen = new Set();
const visit = (candidate, depth) => {
if (depth > 12 || candidate === null || candidate === undefined) return null;
if (typeof candidate === "string") {
const parsed = parsedJsonString(candidate);
if (parsed !== null) {
const nested = visit(parsed, depth + 1);
if (nested) return nested;
}
if (candidate.length <= 200_000) {
const idMatch = candidate.match(/(?:project[_\s-]*id|\bid\b)["'\s:=]+([0-9]+)/i);
if (idMatch?.[1] === expectedProjectId) {
const nameMatch = candidate.match(/(?:project[_\s-]*name|\bname\b)["'\s:=]+["']?([^"'\n,}\]]+)/i);
return { id: expectedProjectId, name: nameMatch?.[1]?.trim() || null };
}
}
return null;
}
if (typeof candidate !== "object" || seen.has(candidate)) return null;
seen.add(candidate);
if (!Array.isArray(candidate)) {
const id = projectIdFrom(candidate);
if (id === expectedProjectId) {
return { id, name: projectNameFrom(candidate) };
}
}
const children = Array.isArray(candidate) ? candidate : Object.values(candidate);
for (const child of children) {
const found = visit(child, depth + 1);
if (found) return found;
}
return null;
};
return visit(value, 0);
}
export function parseSanitizedAgentProof(commentBody, expectedProjectId) {
if (typeof commentBody !== "string") return null;
const trimmed = commentBody.trim();
const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
let parsed;
try {
parsed = JSON.parse(fenced ? fenced[1] : trimmed);
} catch {
return null;
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
if (Object.keys(parsed).sort().join(",") !== "invocationId,projectId,projectName") return null;
if (String(parsed.projectId ?? "") !== expectedProjectId) return null;
if (typeof parsed.projectName !== "string" || !parsed.projectName.trim()) return null;
if (typeof parsed.invocationId !== "string" || !parsed.invocationId.trim()) return null;
return {
projectId: expectedProjectId,
projectName: parsed.projectName.trim(),
invocationId: parsed.invocationId.trim(),
};
}
const FORBIDDEN_EVIDENCE_KEYS = /(?:password|access[_-]?token|refresh[_-]?token|authorization|cookie|oauth[_-]?code|client[_-]?secret)/i;
const FORBIDDEN_EVIDENCE_TEXT = /(?:authorization:\s*bearer|cookie:|[?&](?:code|state|token|access_token|refresh_token)=)/i;
export function assertSanitizedEvidence(value) {
const seen = new Set();
const visit = (candidate, path) => {
if (candidate === null || candidate === undefined) return;
if (typeof candidate === "string") {
if (FORBIDDEN_EVIDENCE_TEXT.test(candidate)) {
throw new Error(`unsafe_evidence_text:${path}`);
}
return;
}
if (typeof candidate !== "object" || seen.has(candidate)) return;
seen.add(candidate);
for (const [key, child] of Object.entries(candidate)) {
if (FORBIDDEN_EVIDENCE_KEYS.test(key)) {
throw new Error(`unsafe_evidence_key:${path}.${key}`);
}
visit(child, `${path}.${key}`);
}
};
visit(value, "$");
}
export function preflightFailureMessage(error) {
if (!(error instanceof PosthogLivePreflightError)) return "PostHog live smoke preflight failed.";
if (error.code === "missing_environment") {
return `PostHog live smoke preflight failed: missing ${error.details.missing.join(", ")}.`;
}
if (error.code === "health_http_error") {
return `PostHog live smoke preflight failed: /api/health returned HTTP ${error.details.status}.`;
}
if (error.code === "missing_base_url") {
return "PostHog live smoke preflight failed: pass the target Paperclip URL or run inside a Paperclip heartbeat.";
}
if (error.code === "invalid_arguments") {
return "PostHog live smoke preflight failed: expected an optional Paperclip URL or --base-url <url>.";
}
return `PostHog live smoke preflight failed: ${error.code}.`;
}
+801
View File
@@ -0,0 +1,801 @@
#!/usr/bin/env node
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import {
assertSanitizedEvidence,
extractProjectSummary,
parsePosthogLiveArguments,
parseSanitizedAgentProof,
PosthogLivePreflightError,
preflightFailureMessage,
preparePosthogLiveSmoke,
} from "./posthog-live-lib.mjs";
const TARGET_COMPANY_PREFIX = "PAP";
const TARGET_AGENT_NAME = "CodexCoderPro";
const PROJECT_GET = "project-get";
const PROJECT_SETTINGS_UPDATE = "project-settings-update";
const EXCLUDED_PROJECT_SWITCHERS = new Set(["switch-project", "switch-organization"]);
const DEFAULT_AGENT_TIMEOUT_MS = 15 * 60_000;
class SmokeFailure extends Error {
constructor(checkpoint, code) {
super(`${checkpoint}:${code}`);
this.name = "SmokeFailure";
this.checkpoint = checkpoint;
this.code = code;
}
}
function fail(checkpoint, code) {
throw new SmokeFailure(checkpoint, code);
}
function asArray(value, key) {
if (Array.isArray(value)) return value;
if (value && typeof value === "object" && Array.isArray(value[key])) return value[key];
return [];
}
function escapeRegex(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function screenshotFile(outputDirectory, name) {
return path.join(outputDirectory, name);
}
function safeConnectionConfig(connection, expectedProjectId) {
const methodConfig = connection?.config?.methodConfig;
if (!methodConfig || typeof methodConfig !== "object" || Array.isArray(methodConfig)) {
fail("C.connection-detail", "method_config_missing");
}
if (connection.config?.connectionMethodKey !== "mcp-oauth") {
fail("C.connection-detail", "oauth_method_not_recorded");
}
if (String(methodConfig.projectId ?? "") !== expectedProjectId) {
fail("C.connection-detail", "wrong_project_pin");
}
if (methodConfig.readOnly !== false || methodConfig.mode !== "tools") {
fail("C.connection-detail", "unexpected_posthog_scope");
}
if ((methodConfig.features ?? "") !== "" || (methodConfig.tools ?? "") !== "") {
fail("C.connection-detail", "unexpected_tool_filter");
}
if (!connection.config?.oauth?.connectedAt) {
fail("B.oauth-callback", "oauth_not_connected");
}
}
function assertNoCredentialMaterial(value, secrets, checkpoint) {
const serialized = JSON.stringify(value);
for (const secret of secrets) {
if (secret && serialized.includes(secret)) fail(checkpoint, "credential_material_visible");
}
if (/[?&](?:code|state|access_token|refresh_token)=/i.test(serialized)) {
fail(checkpoint, "oauth_query_material_visible");
}
const forbiddenValueKey = /^(?:password|accessToken|access_token|refreshToken|refresh_token|oauthCode|oauth_code|clientSecret|client_secret|cookie|authorizationHeader)$/i;
const visit = (candidate, seen = new Set()) => {
if (!candidate || typeof candidate !== "object" || seen.has(candidate)) return;
seen.add(candidate);
for (const [key, child] of Object.entries(candidate)) {
if (forbiddenValueKey.test(key) && child !== null && child !== "") {
fail(checkpoint, "raw_credential_field_visible");
}
visit(child, seen);
}
};
visit(value);
}
async function apiJson(request, baseUrl, method, pathname, data, checkpoint, expectedStatuses = [200]) {
let response;
try {
response = await request.fetch(new URL(pathname, baseUrl).toString(), {
method,
...(data === undefined ? {} : { data }),
headers: { accept: "application/json" },
timeout: 30_000,
});
} catch {
fail(checkpoint, "request_failed");
}
if (!expectedStatuses.includes(response.status())) {
fail(checkpoint, `http_${response.status()}`);
}
try {
return await response.json();
} catch {
fail(checkpoint, "invalid_json");
}
}
async function waitFor(checkpoint, fn, { timeoutMs = 120_000, intervalMs = 2_000 } = {}) {
const deadline = Date.now() + timeoutMs;
let lastValue;
while (Date.now() < deadline) {
lastValue = await fn();
if (lastValue) return lastValue;
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
fail(checkpoint, "timed_out");
return lastValue;
}
async function expectVisible(locator, checkpoint, code, timeout = 30_000) {
try {
await locator.waitFor({ state: "visible", timeout });
} catch {
fail(checkpoint, code);
}
}
async function clickVisibleButton(page, names) {
for (const name of names) {
const button = page.getByRole("button", { name, exact: false }).filter({ visible: true }).first();
if (await button.count()) {
try {
await button.click({ timeout: 2_000 });
return true;
} catch {
// Provider pages often replace their form between locator creation and
// click. The next loop re-reads the current DOM.
}
}
}
return false;
}
async function completePosthogAuthorization(page, config) {
const paperclipOrigin = new URL(config.baseUrl).origin;
const deadline = Date.now() + 4 * 60_000;
while (Date.now() < deadline) {
let current;
try {
current = new URL(page.url());
} catch {
fail("B.oauth-callback", "invalid_navigation_url");
}
if (current.origin === paperclipOrigin && current.pathname.includes("/apps/")) return;
const emailInput = page.locator('input[type="email"], input[name="email"], input[autocomplete="username"]').filter({ visible: true }).first();
if (await emailInput.count()) {
const currentValue = await emailInput.inputValue().catch(() => "");
if (!currentValue) await emailInput.fill(config.email);
}
const passwordInput = page.locator('input[type="password"], input[name="password"], input[autocomplete="current-password"]').filter({ visible: true }).first();
if (await passwordInput.count()) {
const currentValue = await passwordInput.inputValue().catch(() => "");
if (!currentValue) await passwordInput.fill(config.password);
await clickVisibleButton(page, [/^sign in$/i, /^log in$/i, /^continue$/i, /sign in with email/i]);
} else if (await emailInput.count()) {
await clickVisibleButton(page, [/^continue$/i, /^next$/i, /continue with email/i, /sign in with email/i]);
} else {
await clickVisibleButton(page, [
/^authorize$/i,
/^allow$/i,
/^approve$/i,
/^grant access$/i,
/^accept$/i,
/^continue$/i,
/^sign in$/i,
/^log in$/i,
]);
}
await page.waitForTimeout(500);
}
fail("B.oauth-callback", "provider_authorization_timed_out");
}
async function safeScreenshot(page, outputPath, config, checkpoint) {
const current = new URL(page.url());
if (current.origin !== new URL(config.baseUrl).origin) fail(checkpoint, "screenshot_not_on_paperclip");
for (const queryKey of ["code", "state", "token", "access_token", "refresh_token"]) {
if (current.searchParams.has(queryKey)) fail(checkpoint, "credential_query_in_screenshot_url");
}
const bodyText = await page.locator("body").innerText();
if (bodyText.includes(config.password) || /[?&](?:code|state|access_token|refresh_token)=/i.test(bodyText)) {
fail(checkpoint, "credential_material_in_screenshot");
}
await page.screenshot({
path: outputPath,
fullPage: true,
animations: "disabled",
mask: [page.getByText(config.email, { exact: false })],
});
}
function catalogFacts(catalog, checkpoint) {
const active = catalog.filter((entry) => entry.status !== "removed");
const projectGet = active.find((entry) => entry.toolName === PROJECT_GET);
const projectSettings = active.find((entry) => entry.toolName === PROJECT_SETTINGS_UPDATE);
if (!projectGet || !projectGet.isReadOnly) fail(checkpoint, "project_get_missing_or_not_read_only");
if (!projectSettings || projectSettings.isReadOnly) fail(checkpoint, "project_settings_update_missing_or_not_write");
for (const excluded of EXCLUDED_PROJECT_SWITCHERS) {
if (active.some((entry) => entry.toolName === excluded)) fail(checkpoint, `excluded_${excluded}_present`);
}
return { active, projectGet, projectSettings };
}
async function finishAgentOnlySetup(request, config, companyId, connectionId, catalog, agentId) {
const { active } = catalogFacts(catalog, "C.catalog-policy");
const enabledCatalogEntryIds = active.filter((entry) => entry.isReadOnly).map((entry) => entry.id);
await apiJson(
request,
config.baseUrl,
"POST",
`/api/companies/${companyId}/tools/apps/${connectionId}/finish`,
{
enabledCatalogEntryIds,
askFirstCatalogEntryIds: [],
reviewedCatalogEntryIds: active.filter((entry) => entry.status === "quarantined").map((entry) => entry.id),
access: { agentIds: [agentId] },
},
"C.catalog-policy",
);
await apiJson(
request,
config.baseUrl,
"PUT",
`/api/tool-connections/${connectionId}/installs`,
{ installs: [{ targetType: "agent", targetId: agentId }] },
"C.agent-install",
);
}
async function cleanupConnection(request, config, companyId, connectionId, connectionName) {
const removed = await apiJson(
request,
config.baseUrl,
"DELETE",
`/api/tool-connections/${connectionId}`,
undefined,
"F.cleanup",
);
const receipt = removed.removal;
if (!receipt
|| receipt.installsRemoved < 1
|| receipt.appProfileBindingsRemoved < 1
|| receipt.credentialRefsCleared + receipt.secretsRevoked < 1
|| !["deleted", "archived"].includes(receipt.appProfile)) {
fail("F.cleanup", "incomplete_removal_receipt");
}
const connectionsResponse = await apiJson(
request,
config.baseUrl,
"GET",
`/api/companies/${companyId}/tools/connections`,
undefined,
"F.cleanup-verification",
);
const remaining = asArray(connectionsResponse, "connections").filter(
(connection) => connection.name === connectionName && connection.status !== "archived",
);
if (remaining.length > 0) fail("F.cleanup-verification", "test_connection_remains");
const profilesResponse = await apiJson(
request,
config.baseUrl,
"GET",
`/api/companies/${companyId}/tools/profiles`,
undefined,
"F.cleanup-verification",
);
if (asArray(profilesResponse, "profiles").some((profile) => profile.profileKey === `app:${connectionId}` && profile.status === "active")) {
fail("F.cleanup-verification", "active_profile_remains");
}
const pendingResponse = await apiJson(
request,
config.baseUrl,
"GET",
`/api/companies/${companyId}/tools/action-requests?status=pending`,
undefined,
"F.cleanup-verification",
);
if (asArray(pendingResponse, "actionRequests").some((item) => (item.connectionId ?? item.request?.connectionId) === connectionId)) {
fail("F.cleanup-verification", "pending_action_remains");
}
return {
credentialsTornDown: receipt.credentialRefsCleared + receipt.secretsRevoked > 0,
accessBindingsRemoved: receipt.appProfileBindingsRemoved,
installsRemoved: receipt.installsRemoved,
appProfile: receipt.appProfile,
pendingActions: 0,
remainingConnections: 0,
};
}
async function runSmoke({ config, chromium }) {
const startedAt = new Date();
const runKey = startedAt.toISOString().replace(/[:.]/g, "-");
const connectionName = `PostHog live self-test ${startedAt.toISOString()}`;
const outputDirectory = process.env.POSTHOG_EVIDENCE_DIR
? path.resolve(process.env.POSTHOG_EVIDENCE_DIR)
: path.join(process.env.PAPERCLIP_RUN_SCRATCH_DIR || process.cwd(), `posthog-live-${runKey}`);
await mkdir(outputDirectory, { recursive: true });
const summary = {
schemaVersion: 1,
smoke: "posthog_mcp_live",
passed: false,
startedAt: startedAt.toISOString(),
completedAt: null,
target: { companyPrefix: TARGET_COMPANY_PREFIX, projectId: config.projectId },
connection: null,
catalog: null,
boardTest: null,
freshRun: null,
cleanup: null,
screenshots: [],
failure: null,
};
let browser;
let context;
let connectionId = null;
let companyId = null;
let cleanupComplete = false;
let caughtFailure = null;
try {
browser = await chromium.launch({ headless: process.env.POSTHOG_SMOKE_HEADED !== "1" });
context = await browser.newContext({
viewport: { width: 1440, height: 1000 },
acceptDownloads: false,
serviceWorkers: "block",
});
const page = await context.newPage();
await page.goto(new URL("/auth?next=/", config.baseUrl).toString(), { waitUntil: "domcontentloaded" });
await expectVisible(page.locator("#email"), "A.paperclip-login", "email_field_missing");
await page.locator("#email").fill(config.email);
await page.locator("#password").fill(config.password);
const loginResponsePromise = page.waitForResponse((response) =>
response.request().method() === "POST" && new URL(response.url()).pathname === "/api/auth/sign-in/email",
);
await page.getByRole("button", { name: /^sign in$/i }).click();
const loginResponse = await loginResponsePromise;
if (!loginResponse.ok()) fail("A.paperclip-login", `http_${loginResponse.status()}`);
await page.waitForURL((url) => url.pathname !== "/auth", { timeout: 30_000 }).catch(() => {
fail("A.paperclip-login", "login_redirect_missing");
});
const companiesResponse = await apiJson(context.request, config.baseUrl, "GET", "/api/companies", undefined, "A.company-selection");
const company = asArray(companiesResponse, "companies").find((candidate) => candidate.issuePrefix === TARGET_COMPANY_PREFIX);
if (!company) fail("A.company-selection", "pap_company_missing");
companyId = company.id;
const agentsResponse = await apiJson(
context.request,
config.baseUrl,
"GET",
`/api/companies/${companyId}/agents`,
undefined,
"C.agent-scope",
);
const agent = asArray(agentsResponse, "agents").find((candidate) => candidate.name === TARGET_AGENT_NAME);
if (!agent) fail("C.agent-scope", "codex_coder_pro_missing");
const setupUrl = new URL(`/${TARGET_COMPANY_PREFIX}/apps/connect?byo=1&appKey=posthog&stage=setup`, config.baseUrl);
await page.goto(setupUrl.toString(), { waitUntil: "domcontentloaded" });
await expectVisible(page.getByRole("heading", { name: "Connect PostHog" }), "A.setup-route", "posthog_setup_missing");
await expectVisible(page.getByRole("button", { name: "Sign in with PostHog" }), "A.setup-route", "oauth_method_missing");
await expectVisible(page.getByRole("button", { name: "Use a personal API key" }), "A.setup-route", "api_key_method_missing");
await page.getByRole("button", { name: "Sign in with PostHog" }).click();
const nameInput = page.locator('input[placeholder="My app"]');
await nameInput.fill(connectionName);
await page.locator('input[placeholder="12345"]').fill(config.projectId);
const readOnlyScope = page.locator("div").filter({ hasText: /^Read-only mode/ }).filter({ has: page.getByRole("switch") }).first();
const readOnlySwitch = readOnlyScope.getByRole("switch");
if (await readOnlySwitch.getAttribute("aria-checked") !== "false") fail("B.oauth-setup", "read_only_default_changed");
await page.getByText("Advanced", { exact: true }).click();
const featuresInput = page.locator("label", { hasText: "Feature groups" }).locator("..").locator("textarea");
const toolsInput = page.locator("label", { hasText: "Individual tools" }).locator("..").locator("textarea");
if (await featuresInput.inputValue() !== "" || await toolsInput.inputValue() !== "") {
fail("B.oauth-setup", "tool_filters_not_blank");
}
const responseMode = page.locator("label", { hasText: "Tool response mode" }).locator("..").locator("select");
if (await responseMode.inputValue() !== "tools") fail("B.oauth-setup", "individual_tools_mode_not_selected");
const connectResponsePromise = page.waitForResponse((response) => {
const target = new URL(response.url());
return response.request().method() === "POST"
&& target.pathname === `/api/companies/${companyId}/tools/apps/connect`;
});
await page.getByRole("button", { name: "Continue to sign in" }).click();
const connectResponse = await connectResponsePromise;
if (!connectResponse.ok()) fail("B.oauth-start", `http_${connectResponse.status()}`);
let connectResult;
try {
connectResult = await connectResponse.json();
} catch {
fail("B.oauth-start", "invalid_json");
}
connectionId = connectResult.connectionId;
if (typeof connectionId !== "string" || !connectionId) fail("B.oauth-start", "connection_id_missing");
await completePosthogAuthorization(page, config);
const cleanSetupPath = `/${TARGET_COMPANY_PREFIX}/apps/${connectionId}/setup`;
await page.goto(new URL(cleanSetupPath, config.baseUrl).toString(), { waitUntil: "domcontentloaded" });
await expectVisible(page.getByText("PostHog connected", { exact: true }), "B.oauth-callback", "connected_state_missing", 45_000);
let connection = await apiJson(
context.request,
config.baseUrl,
"GET",
`/api/tool-connections/${connectionId}`,
undefined,
"C.connection-detail",
);
safeConnectionConfig(connection, config.projectId);
assertNoCredentialMaterial(connection, [config.password], "C.connection-detail");
summary.connection = {
id: connectionId,
name: connectionName,
authentication: "oauth",
projectId: config.projectId,
status: connection.status,
healthStatus: connection.healthStatus,
};
const connectedShot = "01-connected-setup.png";
await safeScreenshot(page, screenshotFile(outputDirectory, connectedShot), config, "F.connected-screenshot");
summary.screenshots.push(connectedShot);
let catalogResponse = await apiJson(
context.request,
config.baseUrl,
"GET",
`/api/tool-connections/${connectionId}/catalog`,
undefined,
"C.catalog-policy",
);
let catalog = asArray(catalogResponse, "catalog");
let facts = catalogFacts(catalog, "C.catalog-policy");
await finishAgentOnlySetup(context.request, config, companyId, connectionId, catalog, agent.id);
const health = await apiJson(
context.request,
config.baseUrl,
"POST",
`/api/tool-connections/${connectionId}/health-check`,
{},
"C.health-check",
);
if (health.connection?.healthStatus !== "healthy") fail("C.health-check", "connection_not_healthy");
const refreshed = await apiJson(
context.request,
config.baseUrl,
"POST",
`/api/tool-connections/${connectionId}/catalog/refresh`,
{},
"C.catalog-refresh",
);
catalog = asArray(refreshed, "catalog");
facts = catalogFacts(catalog, "C.catalog-refresh");
await finishAgentOnlySetup(context.request, config, companyId, connectionId, catalog, agent.id);
connection = await apiJson(context.request, config.baseUrl, "GET", `/api/tool-connections/${connectionId}`, undefined, "C.connection-detail");
safeConnectionConfig(connection, config.projectId);
if (connection.status !== "active" || connection.healthStatus !== "healthy") {
fail("C.connection-detail", "connection_not_active_and_healthy");
}
assertNoCredentialMaterial(connection, [config.password], "C.connection-detail");
summary.connection.status = connection.status;
summary.connection.healthStatus = connection.healthStatus;
const uniqueConnections = await apiJson(
context.request,
config.baseUrl,
"GET",
`/api/companies/${companyId}/tools/connections`,
undefined,
"C.connection-detail",
);
if (asArray(uniqueConnections, "connections").filter((candidate) => candidate.name === connectionName).length !== 1) {
fail("C.connection-detail", "duplicate_connection_detected");
}
const installs = await apiJson(
context.request,
config.baseUrl,
"GET",
`/api/tool-connections/${connectionId}/installs`,
undefined,
"C.agent-install",
);
const installRows = asArray(installs, "installs");
if (installRows.length !== 1 || installRows[0].targetType !== "agent" || installRows[0].targetId !== agent.id) {
fail("C.agent-install", "install_not_agent_only");
}
const testAgents = await apiJson(
context.request,
config.baseUrl,
"GET",
`/api/tool-connections/${connectionId}/test-agents`,
undefined,
"C.effective-policy",
);
const testAgent = asArray(testAgents, "agents").find((candidate) => candidate.id === agent.id);
const projectGetAccess = testAgent?.effectiveAccess?.tools?.find((tool) => tool.toolName === PROJECT_GET);
const projectSettingsAccess = testAgent?.effectiveAccess?.tools?.find((tool) => tool.toolName === PROJECT_SETTINGS_UPDATE);
if (projectGetAccess?.decision !== "allowed" || projectSettingsAccess?.decision !== "off") {
fail("C.effective-policy", "unexpected_effective_decision");
}
summary.catalog = {
discoveredCount: refreshed.discoveredCount,
projectGet: { catalogEntryId: facts.projectGet.id, toolName: PROJECT_GET, decision: "allowed" },
projectSettingsUpdate: { catalogEntryId: facts.projectSettings.id, toolName: PROJECT_SETTINGS_UPDATE, decision: "off" },
excludedToolsAbsent: [...EXCLUDED_PROJECT_SWITCHERS],
accessAgentId: agent.id,
installAgentId: agent.id,
healthCheck: "healthy",
catalogRefresh: "succeeded",
};
await page.goto(new URL(`/${TARGET_COMPANY_PREFIX}/apps/${connectionId}/permissions`, config.baseUrl).toString(), { waitUntil: "domcontentloaded" });
await expectVisible(page.getByText("Who can use it", { exact: true }), "C.permissions-ui", "permissions_panel_missing");
const projectGetPermission = page.locator(`[data-action-id="${facts.projectGet.id}"] select`);
const projectSettingsPermission = page.locator(`[data-action-id="${facts.projectSettings.id}"] select`);
await expectVisible(projectGetPermission, "C.permissions-ui", "project_get_permission_missing");
await expectVisible(projectSettingsPermission, "C.permissions-ui", "project_settings_permission_missing");
if (await projectGetPermission.inputValue() !== "allowed" || await projectSettingsPermission.inputValue() !== "off") {
fail("C.permissions-ui", "permissions_ui_mismatch");
}
const permissionsShot = "02-scoped-permissions.png";
await safeScreenshot(page, screenshotFile(outputDirectory, permissionsShot), config, "F.permissions-screenshot");
summary.screenshots.push(permissionsShot);
await page.goto(new URL(`/${TARGET_COMPANY_PREFIX}/apps/${connectionId}/test`, config.baseUrl).toString(), { waitUntil: "domcontentloaded" });
await expectVisible(page.getByLabel("Choose which agent to test as"), "D.test-panel", "agent_picker_missing");
await page.getByLabel("Choose which agent to test as").click();
await page.getByLabel("Search agents").fill(TARGET_AGENT_NAME);
await page.getByRole("button", { name: new RegExp(`^${escapeRegex(TARGET_AGENT_NAME)}`) }).click();
await page.getByLabel("Find an action").fill(PROJECT_GET);
const projectGetTitle = facts.projectGet.title ?? facts.projectGet.toolName;
const actionRow = page.locator("button").filter({ hasText: projectGetTitle }).filter({ hasText: "Allowed" }).first();
await expectVisible(actionRow, "D.test-panel", "project_get_allowed_row_missing");
await actionRow.click();
await expectVisible(page.getByText("This action takes no inputs."), "D.test-panel", "empty_input_form_missing");
const boardTestStartedAt = Date.now();
const testCallResponsePromise = page.waitForResponse((response) =>
response.request().method() === "POST"
&& new URL(response.url()).pathname === `/api/tool-connections/${connectionId}/test-calls`,
);
await page.getByRole("button", { name: /^run$/i }).click();
const testCallResponse = await testCallResponsePromise;
if (!testCallResponse.ok()) fail("D.project-get", `http_${testCallResponse.status()}`);
let testCall;
try {
testCall = await testCallResponse.json();
} catch {
fail("D.project-get", "invalid_json");
}
let testCallInput;
try {
testCallInput = testCallResponse.request().postDataJSON();
} catch {
fail("D.project-get", "request_body_unavailable");
}
if (testCallInput?.agentId !== agent.id
|| testCallInput?.toolName !== PROJECT_GET
|| !testCallInput.parameters
|| typeof testCallInput.parameters !== "object"
|| Array.isArray(testCallInput.parameters)
|| Object.keys(testCallInput.parameters).length !== 0) {
fail("D.project-get", "nonempty_or_unexpected_input");
}
if (testCall.decision !== "allowed" || testCall.error || typeof testCall.invocationId !== "string") {
fail("D.project-get", "gateway_call_not_allowed");
}
const boardProject = extractProjectSummary(testCall.result, config.projectId);
if (!boardProject?.name) fail("D.project-get", "project_result_missing");
await expectVisible(page.getByText(/^Worked\./), "D.project-get", "success_result_missing");
const boardShot = "03-board-project-get.png";
await safeScreenshot(page, screenshotFile(outputDirectory, boardShot), config, "F.board-test-screenshot");
summary.screenshots.push(boardShot);
summary.boardTest = {
catalogEntryId: facts.projectGet.id,
toolName: PROJECT_GET,
invocationId: testCall.invocationId,
decision: testCall.decision,
httpStatus: testCallResponse.status(),
resultStatus: "succeeded",
project: boardProject,
durationMs: Date.now() - boardTestStartedAt,
};
const parentIssueId = process.env.POSTHOG_PROOF_PARENT_ISSUE_ID || process.env.PAPERCLIP_TASK_ID;
if (!parentIssueId) fail("E.create-proof-issue", "parent_issue_id_missing");
const child = await apiJson(
context.request,
config.baseUrl,
"POST",
`/api/issues/${parentIssueId}/children`,
{
title: `PostHog installed-tool proof ${startedAt.toISOString()}`,
description: [
"Invoke exactly one installed PostHog action: the read-only upstream `project-get` tool, with an empty `{}` input.",
`Verify the returned project ID is exactly ${config.projectId} and make no PostHog mutations.`,
"Then post exactly one JSON object with keys `projectId`, `projectName`, and `invocationId` (the Paperclip invocation ID), and mark this issue done.",
"Do not report tokens, cookies, authorization data, request headers, raw tool payloads, or any other fields.",
].join("\n\n"),
status: "todo",
workMode: "standard",
priority: "medium",
assigneeAgentId: agent.id,
acceptanceCriteria: [
`The installed PostHog project-get action returns project ${config.projectId}.`,
"The comment contains only sanitized project ID/name and Paperclip invocation ID.",
"No mutation is attempted.",
],
},
"E.create-proof-issue",
[201],
);
if (child.status !== "todo") fail("E.create-proof-issue", "child_not_created_todo");
const observedStatuses = new Set(["todo"]);
const finishedChild = await waitFor("E.fresh-agent-run", async () => {
const issue = await apiJson(context.request, config.baseUrl, "GET", `/api/issues/${child.id}`, undefined, "E.fresh-agent-run");
observedStatuses.add(issue.status);
if (["blocked", "cancelled"].includes(issue.status)) fail("E.fresh-agent-run", `child_${issue.status}`);
return issue.status === "done" ? issue : null;
}, {
timeoutMs: Number(process.env.POSTHOG_AGENT_TIMEOUT_MS || DEFAULT_AGENT_TIMEOUT_MS),
intervalMs: 3_000,
});
if (!finishedChild.startedAt || !finishedChild.completedAt) fail("E.fresh-agent-run", "transition_timestamps_missing");
const commentsResponse = await apiJson(
context.request,
config.baseUrl,
"GET",
`/api/issues/${child.id}/comments`,
undefined,
"E.agent-proof-comment",
);
const comments = asArray(commentsResponse, "comments");
for (const comment of comments) assertNoCredentialMaterial(comment.body, [config.password], "E.agent-proof-comment");
const agentComments = comments.filter((comment) =>
comment.authorAgentId === agent.id || comment.derivedAuthorAgentId === agent.id,
);
const proofs = agentComments.map((comment) => parseSanitizedAgentProof(comment.body, config.projectId)).filter(Boolean);
if (agentComments.length !== 1 || proofs.length !== 1) {
fail("E.agent-proof-comment", "single_sanitized_proof_missing");
}
const [proof] = proofs;
let finalConnectionActivity;
const agentEvent = await waitFor("E.agent-audit", async () => {
const activity = await apiJson(
context.request,
config.baseUrl,
"GET",
`/api/tool-connections/${connectionId}/activity?limit=100`,
undefined,
"E.agent-audit",
);
assertNoCredentialMaterial(activity, [config.password], "E.agent-audit");
finalConnectionActivity = activity;
return asArray(activity, "events").find((event) =>
event.issueId === child.id
&& event.agentId === agent.id
&& event.toolName === PROJECT_GET
&& event.invocationId === proof.invocationId
&& event.outcome === "success",
) ?? null;
}, { timeoutMs: 60_000, intervalMs: 2_000 });
if (!agentEvent.runId) fail("E.agent-audit", "run_id_missing");
if (agentEvent.requestSummary?.summary !== "{}") fail("E.agent-audit", "project_get_input_not_empty");
const childToolEvents = asArray(finalConnectionActivity, "events").filter((event) => event.issueId === child.id && event.invocationId);
if (childToolEvents.length === 0 || childToolEvents.some((event) => event.toolName !== PROJECT_GET)) {
fail("E.agent-audit", "unexpected_upstream_action");
}
if (new Set(childToolEvents.map((event) => event.invocationId)).size !== 1) {
fail("E.agent-audit", "project_get_invoked_more_than_once");
}
if (proof.projectName !== boardProject.name) fail("E.agent-proof-comment", "project_name_mismatch");
const agentRun = await waitFor("E.agent-run-status", async () => {
const run = await apiJson(
context.request,
config.baseUrl,
"GET",
`/api/heartbeat-runs/${agentEvent.runId}`,
undefined,
"E.agent-run-status",
);
if (["failed", "cancelled", "timed_out"].includes(run.status)) fail("E.agent-run-status", `run_${run.status}`);
return run.status === "succeeded" ? run : null;
}, { timeoutMs: 60_000, intervalMs: 2_000 });
summary.freshRun = {
issueId: child.id,
issueIdentifier: child.identifier,
transition: {
created: "todo",
enteredInProgress: observedStatuses.has("in_progress") || Boolean(finishedChild.startedAt),
completed: "done",
},
runId: agentEvent.runId,
runStatus: agentRun.status,
invocationId: proof.invocationId,
project: { id: proof.projectId, name: proof.projectName },
auditOutcome: agentEvent.outcome,
durationMs: agentEvent.latencyMs,
};
await page.goto(new URL(`/${TARGET_COMPANY_PREFIX}/issues/${child.identifier}`, config.baseUrl).toString(), { waitUntil: "domcontentloaded" });
await expectVisible(page.getByText(child.title, { exact: true }).first(), "F.child-screenshot", "child_issue_missing");
const childShot = "04-fresh-agent-proof.png";
await safeScreenshot(page, screenshotFile(outputDirectory, childShot), config, "F.child-screenshot");
summary.screenshots.push(childShot);
await page.goto(new URL(`/${TARGET_COMPANY_PREFIX}/apps/${connectionId}/activity`, config.baseUrl).toString(), { waitUntil: "domcontentloaded" });
await expectVisible(page.getByText(PROJECT_GET, { exact: false }).first(), "F.activity-screenshot", "project_get_activity_missing");
const activityShot = "05-redacted-activity.png";
await safeScreenshot(page, screenshotFile(outputDirectory, activityShot), config, "F.activity-screenshot");
summary.screenshots.push(activityShot);
summary.cleanup = await cleanupConnection(context.request, config, companyId, connectionId, connectionName);
cleanupComplete = true;
summary.passed = true;
} catch (error) {
caughtFailure = error instanceof SmokeFailure ? error : new SmokeFailure("unexpected", "unexpected_error");
} finally {
if (connectionId && companyId && context && !cleanupComplete) {
try {
summary.cleanup = await cleanupConnection(context.request, config, companyId, connectionId, connectionName);
cleanupComplete = true;
} catch {
summary.cleanup = { completed: false, code: "cleanup_failed" };
if (!caughtFailure) caughtFailure = new SmokeFailure("F.cleanup", "cleanup_failed");
}
}
await context?.close().catch(() => {});
await browser?.close().catch(() => {});
}
summary.completedAt = new Date().toISOString();
if (caughtFailure) {
summary.failure = { checkpoint: caughtFailure.checkpoint, code: caughtFailure.code };
}
assertSanitizedEvidence(summary);
const summaryPath = path.join(outputDirectory, "summary.json");
await writeFile(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, { mode: 0o600 });
if (caughtFailure) throw caughtFailure;
return { outputDirectory, summaryPath, screenshots: summary.screenshots };
}
async function main() {
let prepared;
try {
const options = parsePosthogLiveArguments(process.argv.slice(2));
prepared = await preparePosthogLiveSmoke({
baseUrl: options.baseUrl,
loadBrowser: () => import("@playwright/test"),
});
} catch (error) {
process.stderr.write(`${preflightFailureMessage(error)}\n`);
process.exitCode = error instanceof PosthogLivePreflightError ? 2 : 1;
return;
}
try {
const result = await runSmoke({ config: prepared.config, chromium: prepared.browserModule.chromium });
process.stdout.write(`PostHog live smoke passed. Sanitized evidence: ${result.outputDirectory}\n`);
} catch (error) {
const failure = error instanceof SmokeFailure ? error : new SmokeFailure("unexpected", "unexpected_error");
process.stderr.write(`PostHog live smoke failed at ${failure.checkpoint} (${failure.code}).\n`);
process.exitCode = 1;
}
}
await main();
+161
View File
@@ -0,0 +1,161 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
assertSanitizedEvidence,
extractProjectSummary,
parsePosthogLiveArguments,
parseSanitizedAgentProof,
PosthogLivePreflightError,
preflightPosthogLive,
preparePosthogLiveSmoke,
} from "./posthog-live-lib.mjs";
const COMPLETE_ENV = {
PAPERCLIP_API_URL: "https://paperclip.example.test/api",
INTEGRATIONS_POSTHOG_PAPERCLIP_E2E_EMAIL: "operator@example.test",
INTEGRATIONS_POSTHOG_PAPERCLIP_DEV_LOGIN_PASSWORD: "not-a-real-password",
INTEGRATIONS_POSTHOG_POSTHOG_PROJECT_ID: "483530",
};
test("preflight reports only missing binding names", () => {
assert.throws(
() => preflightPosthogLive({
PAPERCLIP_API_URL: "https://paperclip.example.test/api",
INTEGRATIONS_POSTHOG_PAPERCLIP_DEV_LOGIN_PASSWORD: "present",
}),
(error) => {
assert.ok(error instanceof PosthogLivePreflightError);
assert.equal(error.code, "missing_environment");
assert.deepEqual(error.details.missing, [
"INTEGRATIONS_POSTHOG_PAPERCLIP_E2E_EMAIL",
"INTEGRATIONS_POSTHOG_POSTHOG_PROJECT_ID",
]);
assert.doesNotMatch(error.message, /present/);
return true;
},
);
});
test("preflight rejects credential-bearing and non-HTTPS remote URLs", () => {
for (const baseUrl of [
"https://user:secret@example.test",
"https://example.test/?code=secret",
"http://example.test",
]) {
assert.throws(
() => preflightPosthogLive({ ...COMPLETE_ENV, PAPERCLIP_API_URL: baseUrl }),
(error) => error instanceof PosthogLivePreflightError && error.code === "unsafe_base_url",
);
}
assert.equal(
preflightPosthogLive(COMPLETE_ENV, { baseUrl: "http://127.0.0.1:3100" }).baseUrl,
"http://127.0.0.1:3100",
);
});
test("preflight derives the current Paperclip origin and accepts an explicit target", () => {
assert.equal(preflightPosthogLive(COMPLETE_ENV).baseUrl, "https://paperclip.example.test");
assert.equal(
preflightPosthogLive(COMPLETE_ENV, { baseUrl: "https://other-paperclip.example.test" }).baseUrl,
"https://other-paperclip.example.test",
);
assert.throws(
() => preflightPosthogLive({ ...COMPLETE_ENV, PAPERCLIP_API_URL: "" }),
(error) => error instanceof PosthogLivePreflightError && error.code === "missing_base_url",
);
});
test("preflight fails closed unless the PostHog project is exactly 483530", () => {
assert.throws(
() => preflightPosthogLive({
...COMPLETE_ENV,
INTEGRATIONS_POSTHOG_POSTHOG_PROJECT_ID: "42",
}),
(error) => error instanceof PosthogLivePreflightError && error.code === "unexpected_project_id",
);
});
test("live smoke arguments accept a target URL without another environment binding", () => {
assert.deepEqual(parsePosthogLiveArguments([]), {});
assert.deepEqual(
parsePosthogLiveArguments(["https://paperclip.example.test"]),
{ baseUrl: "https://paperclip.example.test" },
);
assert.deepEqual(
parsePosthogLiveArguments(["--base-url", "https://paperclip.example.test"]),
{ baseUrl: "https://paperclip.example.test" },
);
assert.throws(
() => parsePosthogLiveArguments(["--unknown"]),
(error) => error instanceof PosthogLivePreflightError && error.code === "invalid_arguments",
);
});
test("browser loading happens only after binding and health preflight", async () => {
let fetchCalled = false;
let browserLoaded = false;
await assert.rejects(
preparePosthogLiveSmoke({
environment: {},
fetchImpl: async () => {
fetchCalled = true;
},
loadBrowser: async () => {
browserLoaded = true;
},
}),
(error) => error instanceof PosthogLivePreflightError && error.code === "missing_environment",
);
assert.equal(fetchCalled, false);
assert.equal(browserLoaded, false);
await assert.rejects(
preparePosthogLiveSmoke({
environment: COMPLETE_ENV,
fetchImpl: async () => ({ ok: false, status: 503 }),
loadBrowser: async () => {
browserLoaded = true;
},
}),
(error) => error instanceof PosthogLivePreflightError && error.code === "health_http_error",
);
assert.equal(browserLoaded, false);
});
test("project proof extraction retains only the expected id and name", () => {
const result = {
data: {
content: [{ type: "text", text: JSON.stringify({ id: 483530, name: "Paperclip", token: "discard-me" }) }],
},
};
assert.deepEqual(extractProjectSummary(result, "483530"), { id: "483530", name: "Paperclip" });
assert.equal(extractProjectSummary(result, "42"), null);
assert.deepEqual(
parseSanitizedAgentProof(
'{"projectId":"483530","projectName":"Paperclip","invocationId":"inv-123"}',
"483530",
),
{ projectId: "483530", projectName: "Paperclip", invocationId: "inv-123" },
);
assert.equal(
parseSanitizedAgentProof(
'Done: {"projectId":"483530","projectName":"Paperclip","invocationId":"inv-123"}',
"483530",
),
null,
);
assert.equal(
parseSanitizedAgentProof(
'{"projectId":"483530","projectName":"Paperclip","invocationId":"inv-123","token":"unsafe"}',
"483530",
),
null,
);
});
test("sanitized evidence rejects credential fields and OAuth query values", () => {
assert.doesNotThrow(() => assertSanitizedEvidence({ projectId: "483530", invocationId: "inv-123" }));
assert.throws(() => assertSanitizedEvidence({ accessToken: "secret" }), /unsafe_evidence_key/);
assert.throws(() => assertSanitizedEvidence({ note: "callback?code=secret" }), /unsafe_evidence_text/);
});