mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
feat(connections): add managed external MCP connectors (#12346)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Connection intents need secure provider implementations to complete setup. > - Some providers use managed OAuth or external credential brokers. > - Those tokens must stay out of durable Paperclip state and fail closed when refresh fails. > - This pull request adds managed connector backends and the required storage contract. > - The benefit is safer provider setup with governed credential lifecycles. ## Linked Issues or Issue Description Refs #11965 This is stack 8 of 11. It depends on stack 7 and replaces another reviewable part of #11965. ## What Changed - Add managed Google Workspace and external connector backends. - Add Vercel Connect support without storing provider bearer tokens. - Add replay-safe migration 0232 and its generated snapshot. - Fail closed and clear stale token bindings when organization OAuth refresh needs reauthorization. ## Verification - `pnpm --filter @paperclipai/server typecheck` - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/tool-access-service.test.ts` - Result: 194 tests passed. - `pnpm --filter @paperclipai/db check:migrations` - `pnpm build` - `pnpm exec vitest run --project @paperclipai/server server/src/services/remote-url-credentials.test.ts` (5 passed, including URL userinfo vault extraction) ## Risks - Broker metadata errors can block provider setup. - OAuth refresh failure disables the shared organization connection until reauthorization. - Migration 0232 is generated, ordered after 0231, and safe to replay. > 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 linked the public source pull request with `Refs #` - [x] I have not referenced internal or instance-local Paperclip issues or links - [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
This commit is contained in:
1 parent
b3343dbd64
commit
d387cc0ff0
48 files changed
+47681
-352
No files matched your search
@@ -8,9 +8,11 @@ import {
|
||||
issues,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
APP_STORE_DEFINITIONS,
|
||||
CONNECTABLE_APP_DEFINITIONS,
|
||||
connectionIntentPayloadSchema,
|
||||
getAvailableConnectionMethods,
|
||||
getAppStoreDefinition,
|
||||
getConnectableAppDefinition,
|
||||
type ConnectionIntentInteraction,
|
||||
type ConnectionIntentSetupOptions,
|
||||
@@ -219,7 +221,7 @@ export function connectionIntentService(db: Db) {
|
||||
const { run, agent } = await loadRunContext(claims);
|
||||
const normalized = query.trim().toLocaleLowerCase();
|
||||
const inventory = await connectionInventory(run.companyId);
|
||||
const results = await Promise.all(CONNECTABLE_APP_DEFINITIONS
|
||||
const results = await Promise.all(APP_STORE_DEFINITIONS
|
||||
.filter((app) => !normalized
|
||||
|| app.slug.toLocaleLowerCase().includes(normalized)
|
||||
|| app.name.toLocaleLowerCase().includes(normalized)
|
||||
@@ -265,7 +267,7 @@ export function connectionIntentService(db: Db) {
|
||||
serviceSlug: string,
|
||||
): Promise<ConnectionRequestResult> {
|
||||
const context = await loadRunContext(claims);
|
||||
const app = getConnectableAppDefinition(serviceSlug);
|
||||
const app = getAppStoreDefinition(serviceSlug);
|
||||
if (!app || app.availability?.available === false || getAvailableConnectionMethods(app).length === 0) {
|
||||
throw unprocessable(`Connection service ${serviceSlug} is not available`);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { classifyRisk, isGmailToolPermanentlyBlocked } from "./tool-access.js";
|
||||
import {
|
||||
classifyRisk,
|
||||
isGmailToolPermanentlyBlocked,
|
||||
isGoogleWorkspaceToolAllowed,
|
||||
} from "./tool-access.js";
|
||||
|
||||
describe("Gmail tool governance", () => {
|
||||
it("allows reviewed reads and draft creation while keeping delivery and destructive actions blocked", () => {
|
||||
@@ -15,3 +19,22 @@ describe("Gmail tool governance", () => {
|
||||
expect(isGmailToolPermanentlyBlocked({ name: "update_labels" })).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Google Workspace tool governance", () => {
|
||||
it("limits each capability profile to its reviewed reads and writes", () => {
|
||||
expect(isGoogleWorkspaceToolAllowed("drive.read", { name: "search_files" })).toBe(true);
|
||||
expect(isGoogleWorkspaceToolAllowed("drive.read", { name: "create_file" })).toBe(false);
|
||||
expect(isGoogleWorkspaceToolAllowed("drive.write", { name: "create_file" })).toBe(true);
|
||||
|
||||
expect(isGoogleWorkspaceToolAllowed("gmail.draft", { name: "create_draft" })).toBe(true);
|
||||
expect(isGoogleWorkspaceToolAllowed("gmail.draft", { name: "send_message" })).toBe(false);
|
||||
expect(isGoogleWorkspaceToolAllowed("calendar.write", { name: "delete_event" })).toBe(true);
|
||||
expect(isGoogleWorkspaceToolAllowed("calendar.write", { name: "publish_calendar" })).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes namespaced provider tool names and denies unknown preview tools", () => {
|
||||
expect(isGoogleWorkspaceToolAllowed("docs.read", { name: "google.docs/read_doc" })).toBe(true);
|
||||
expect(isGoogleWorkspaceToolAllowed("sheets.write", { name: "sheets.updateValues" })).toBe(true);
|
||||
expect(isGoogleWorkspaceToolAllowed("people.read", { name: "delete_contact" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -91,6 +91,12 @@ export { secretService } from "./secrets.js";
|
||||
export { createRunSecretRedactionRegistry } from "./run-secret-redaction.js";
|
||||
export { createSecretProposalsService } from "./secret-proposals.js";
|
||||
export { googleSheetsRobotEmailFromEnv, toolAccessService } from "./tool-access.js";
|
||||
export {
|
||||
createVercelConnectClient,
|
||||
vercelConnectIntegrationStatus,
|
||||
VercelConnectClientError,
|
||||
type VercelConnectClient,
|
||||
} from "./vercel-connect.js";
|
||||
export { createComposioClient, ComposioApiError, type ComposioClient } from "./composio.js";
|
||||
export { smokeLabService } from "./smoke-lab.js";
|
||||
export { backfillLegacyToolOAuthTokens } from "./tool-oauth-legacy-backfill.js";
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
/** The Accept header value required by the MCP Streamable HTTP transport. */
|
||||
export const MCP_HTTP_ACCEPT = "application/json, text/event-stream";
|
||||
export const MCP_PROTOCOL_VERSION = "2025-06-18";
|
||||
|
||||
/**
|
||||
* Default headers for an MCP Streamable HTTP JSON-RPC POST. Caller-supplied
|
||||
@@ -27,6 +28,89 @@ export function mcpHttpRequestHeaders(extra?: Record<string, string>): Record<st
|
||||
};
|
||||
}
|
||||
|
||||
export class McpHttpInitializationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly stage: "initialize" | "initialized_notification",
|
||||
readonly status: number | null,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "McpHttpInitializationError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Establish the short-lived Streamable HTTP session needed by stateful MCP
|
||||
* servers. The returned headers belong only to the caller's next request; no
|
||||
* session id is persisted with the connection or shared across operations.
|
||||
*/
|
||||
export async function initializeMcpHttpSession(input: {
|
||||
send: (init: RequestInit) => Promise<Response>;
|
||||
headers?: Record<string, string>;
|
||||
requestId: string;
|
||||
}): Promise<Record<string, string>> {
|
||||
const initializeResponse = await input.send({
|
||||
method: "POST",
|
||||
headers: mcpHttpRequestHeaders(input.headers),
|
||||
body: JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: `${input.requestId}-initialize`,
|
||||
method: "initialize",
|
||||
params: {
|
||||
protocolVersion: MCP_PROTOCOL_VERSION,
|
||||
capabilities: {},
|
||||
clientInfo: { name: "paperclip", version: "1" },
|
||||
},
|
||||
}),
|
||||
});
|
||||
if (!initializeResponse.ok) {
|
||||
throw new McpHttpInitializationError(
|
||||
`Remote MCP initialization returned HTTP ${initializeResponse.status}`,
|
||||
"initialize",
|
||||
initializeResponse.status,
|
||||
);
|
||||
}
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = parseMcpHttpResponseBody(
|
||||
await initializeResponse.text(),
|
||||
initializeResponse.headers.get("content-type"),
|
||||
);
|
||||
} catch {
|
||||
throw new McpHttpInitializationError("Remote MCP initialization returned an invalid response", "initialize", null);
|
||||
}
|
||||
const result = payload && typeof payload === "object" && "result" in payload
|
||||
? (payload as { result?: unknown }).result
|
||||
: null;
|
||||
const resultRecord = result && typeof result === "object" ? result as Record<string, unknown> : null;
|
||||
const protocolVersion = typeof resultRecord?.protocolVersion === "string" && resultRecord.protocolVersion
|
||||
? resultRecord.protocolVersion
|
||||
: MCP_PROTOCOL_VERSION;
|
||||
const sessionId = initializeResponse.headers.get("mcp-session-id");
|
||||
const sessionHeaders: Record<string, string> = {
|
||||
...(input.headers ?? {}),
|
||||
"MCP-Protocol-Version": protocolVersion,
|
||||
...(sessionId ? { "Mcp-Session-Id": sessionId } : {}),
|
||||
};
|
||||
const initializedResponse = await input.send({
|
||||
method: "POST",
|
||||
headers: mcpHttpRequestHeaders(sessionHeaders),
|
||||
body: JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
method: "notifications/initialized",
|
||||
params: {},
|
||||
}),
|
||||
});
|
||||
if (!initializedResponse.ok) {
|
||||
throw new McpHttpInitializationError(
|
||||
`Remote MCP initialized notification returned HTTP ${initializedResponse.status}`,
|
||||
"initialized_notification",
|
||||
initializedResponse.status,
|
||||
);
|
||||
}
|
||||
return sessionHeaders;
|
||||
}
|
||||
|
||||
function looksLikeJsonRpcMessage(value: unknown): boolean {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
createPaperclipIdGmailConnector,
|
||||
GMAIL_CONNECTOR_SCOPES,
|
||||
GOOGLE_WORKSPACE_CONNECTOR_PROFILES,
|
||||
paperclipIdGmailConnectorConfigFromEnv,
|
||||
PaperclipIdConnectorError,
|
||||
type PaperclipIdGmailConnectorConfig,
|
||||
@@ -97,6 +98,43 @@ describe("Paperclip ID Gmail connector", () => {
|
||||
await expect(connector.claim({ subject, companyId, claimId: "clm_test" })).resolves.toEqual(credentials);
|
||||
});
|
||||
|
||||
it("binds non-Gmail credentials and requests to their exact connector profile", async () => {
|
||||
const keys = config();
|
||||
const profile = "drive.read" as const;
|
||||
const credentials = {
|
||||
v: 1 as const,
|
||||
accessToken: "drive-access-secret",
|
||||
refreshToken: "drive-refresh-secret",
|
||||
tokenType: "Bearer",
|
||||
accessTokenExpiresAt: "2026-08-21T20:00:00.000Z",
|
||||
scopes: [...GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes],
|
||||
subject,
|
||||
companyId,
|
||||
profile,
|
||||
};
|
||||
const sealed = seal(credentials, keys.sealPublicKey, "google-workspace-initial-tokens", keys.config, profile);
|
||||
const request = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
|
||||
const body = JSON.parse(String(init?.body)) as { request: string };
|
||||
const [, encodedClaims] = body.request.split(".");
|
||||
const claims = JSON.parse(Buffer.from(encodedClaims!, "base64url").toString("utf8"));
|
||||
expect(claims.prf).toBe(profile);
|
||||
return Response.json({ claimId: "clm_drive", scopes: credentials.scopes, sealed });
|
||||
});
|
||||
const connector = createPaperclipIdGmailConnector({ config: keys.config, request: request as typeof fetch });
|
||||
|
||||
await expect(connector.claim({ subject, companyId, profile, claimId: "clm_drive" })).resolves.toEqual(credentials);
|
||||
});
|
||||
|
||||
it("accepts only the current capability protocol and known profiles", async () => {
|
||||
const keys = config();
|
||||
const request = vi.fn(async () => Response.json({
|
||||
protocolVersion: 2,
|
||||
profiles: ["gmail.read", "drive.write", "unknown.profile"],
|
||||
}));
|
||||
const connector = createPaperclipIdGmailConnector({ config: keys.config, request: request as typeof fetch });
|
||||
await expect(connector.getCapabilities()).resolves.toEqual(["gmail.read", "drive.write"]);
|
||||
});
|
||||
|
||||
it("does not expose a broker response body when a request fails", async () => {
|
||||
const keys = config();
|
||||
const request = vi.fn(async () => new Response(JSON.stringify({
|
||||
@@ -129,15 +167,23 @@ describe("Paperclip ID Gmail connector", () => {
|
||||
function seal(
|
||||
payload: unknown,
|
||||
recipientPublicKey: KeyObject,
|
||||
purpose: "gmail-initial-tokens" | "gmail-access-token",
|
||||
purpose: "gmail-initial-tokens" | "gmail-access-token" | "google-workspace-initial-tokens" | "google-workspace-access-token",
|
||||
configValue: PaperclipIdGmailConnectorConfig,
|
||||
profile?: string,
|
||||
) {
|
||||
const ephemeral = generateKeyPairSync("x25519");
|
||||
const ephemeralJwk = ephemeral.publicKey.export({ format: "jwk" }) as { x: string };
|
||||
const recipientJwk = recipientPublicKey.export({ format: "jwk" }) as { x: string };
|
||||
const ephemeralRaw = Buffer.from(ephemeralJwk.x, "base64url");
|
||||
const recipientRaw = Buffer.from(recipientJwk.x, "base64url");
|
||||
const aad = Buffer.from([1, "X25519-HKDF-SHA256-A256GCM", purpose, configValue.instanceId, configValue.environment].join("\n"));
|
||||
const aad = Buffer.from([
|
||||
1,
|
||||
"X25519-HKDF-SHA256-A256GCM",
|
||||
purpose,
|
||||
configValue.instanceId,
|
||||
configValue.environment,
|
||||
...(profile ? [profile] : []),
|
||||
].join("\n"));
|
||||
const key = Buffer.from(hkdfSync(
|
||||
"sha256",
|
||||
diffieHellman({ privateKey: ephemeral.privateKey, publicKey: recipientPublicKey }),
|
||||
|
||||
@@ -9,12 +9,18 @@ import {
|
||||
sign,
|
||||
type KeyObject,
|
||||
} from "node:crypto";
|
||||
import {
|
||||
GOOGLE_WORKSPACE_CONNECTOR_PROFILES,
|
||||
isGoogleWorkspaceConnectorProfileId,
|
||||
type GoogleWorkspaceConnectorProfileId,
|
||||
} from "@paperclipai/shared";
|
||||
|
||||
export const GMAIL_MCP_URL = "https://gmailmcp.googleapis.com/mcp/v1";
|
||||
export const GMAIL_CONNECTOR_SCOPES = [
|
||||
"https://www.googleapis.com/auth/gmail.readonly",
|
||||
"https://www.googleapis.com/auth/gmail.compose",
|
||||
] as const;
|
||||
export { GOOGLE_WORKSPACE_CONNECTOR_PROFILES };
|
||||
|
||||
export type PaperclipIdConnectorEnvironment = "development" | "staging" | "production";
|
||||
export type PaperclipIdConnectorOperation = "session" | "claim" | "refresh" | "revoke";
|
||||
@@ -36,12 +42,15 @@ export type SealedGmailCredentials = {
|
||||
scopes: string[];
|
||||
subject: string;
|
||||
companyId: string;
|
||||
profile?: string;
|
||||
};
|
||||
|
||||
export type SealedGoogleWorkspaceCredentials = SealedGmailCredentials;
|
||||
|
||||
type SealedEnvelope = {
|
||||
v: 1;
|
||||
alg: "X25519-HKDF-SHA256-A256GCM";
|
||||
purpose: "gmail-initial-tokens" | "gmail-access-token";
|
||||
purpose: "gmail-initial-tokens" | "gmail-access-token" | "google-workspace-initial-tokens" | "google-workspace-access-token";
|
||||
epk: string;
|
||||
iv: string;
|
||||
ct: string;
|
||||
@@ -53,6 +62,8 @@ type ConnectorResponse = {
|
||||
scopes?: unknown;
|
||||
claimId?: unknown;
|
||||
sealed?: unknown;
|
||||
profiles?: unknown;
|
||||
protocolVersion?: unknown;
|
||||
};
|
||||
|
||||
const ENDPOINTS: Record<PaperclipIdConnectorOperation, string> = {
|
||||
@@ -127,7 +138,7 @@ export function createPaperclipIdGmailConnector(input: {
|
||||
|
||||
async function call(
|
||||
operation: PaperclipIdConnectorOperation,
|
||||
claims: { subject: string; companyId: string; returnUri?: string; returnState?: string; claimId?: string },
|
||||
claims: { subject: string; companyId: string; profile?: GoogleWorkspaceConnectorProfileId; returnUri?: string; returnState?: string; claimId?: string },
|
||||
secret?: { field: "refreshToken" | "token"; value: string },
|
||||
): Promise<ConnectorResponse> {
|
||||
const endpoint = new URL(ENDPOINTS[operation], `${config.baseUrl}/`).toString();
|
||||
@@ -146,6 +157,7 @@ export function createPaperclipIdGmailConnector(input: {
|
||||
if (claims.returnUri !== undefined) payload.ruri = claims.returnUri;
|
||||
if (claims.returnState !== undefined) payload.rst = claims.returnState;
|
||||
if (claims.claimId !== undefined) payload.cl = claims.claimId;
|
||||
if (claims.profile !== undefined) payload.prf = claims.profile;
|
||||
if (secret) payload.sh = await sha256Base64Url(secret.value);
|
||||
const body = {
|
||||
request: signRequest(payload, signingKey),
|
||||
@@ -182,25 +194,51 @@ export function createPaperclipIdGmailConnector(input: {
|
||||
purpose: SealedEnvelope["purpose"],
|
||||
subject: string,
|
||||
companyId: string,
|
||||
profile: GoogleWorkspaceConnectorProfileId,
|
||||
): SealedGmailCredentials {
|
||||
const envelope = parseEnvelope(response.sealed, purpose);
|
||||
const credentials = unseal(envelope, sealKey, config.instanceId, config.environment);
|
||||
const credentials = unseal(
|
||||
envelope,
|
||||
sealKey,
|
||||
config.instanceId,
|
||||
config.environment,
|
||||
purpose.startsWith("google-workspace-") ? profile : undefined,
|
||||
);
|
||||
if (credentials.subject !== subject || credentials.companyId !== companyId) {
|
||||
throw new PaperclipIdConnectorError("Paperclip ID Gmail credential binding did not match", "CONNECTOR_BINDING_MISMATCH");
|
||||
}
|
||||
if (!sameStringSet(credentials.scopes, GMAIL_CONNECTOR_SCOPES)) {
|
||||
if (credentials.profile && credentials.profile !== profile) {
|
||||
throw new PaperclipIdConnectorError("Paperclip ID connector profile binding did not match", "CONNECTOR_BINDING_MISMATCH");
|
||||
}
|
||||
if (!sameStringSet(credentials.scopes, GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes)) {
|
||||
throw new PaperclipIdConnectorError("Paperclip ID Gmail scope grant did not match", "REAUTHORIZATION_REQUIRED");
|
||||
}
|
||||
return credentials;
|
||||
}
|
||||
|
||||
return {
|
||||
async startAuthorization(values: { subject: string; companyId: string; returnUri: string; returnState: string }) {
|
||||
const response = await call("session", values);
|
||||
async getCapabilities(): Promise<GoogleWorkspaceConnectorProfileId[]> {
|
||||
const endpoint = new URL("/api/connect/capabilities", `${config.baseUrl}/`).toString();
|
||||
let response: Response;
|
||||
try {
|
||||
response = await request(endpoint, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(5_000) });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
if (!response.ok) return [];
|
||||
const payload = await response.json().catch(() => null) as ConnectorResponse | null;
|
||||
if (payload?.protocolVersion !== 2) return [];
|
||||
return Array.isArray(payload?.profiles)
|
||||
? payload.profiles.filter((value): value is GoogleWorkspaceConnectorProfileId => typeof value === "string" && isGoogleWorkspaceConnectorProfileId(value))
|
||||
: [];
|
||||
},
|
||||
async startAuthorization(values: { subject: string; companyId: string; profile?: GoogleWorkspaceConnectorProfileId; returnUri: string; returnState: string }) {
|
||||
const profile = values.profile ?? "gmail.draft";
|
||||
const response = await call("session", { ...values, profile });
|
||||
if (typeof response.authorizationUrl !== "string" || typeof response.expiresAt !== "string") {
|
||||
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector returned an invalid session", "CONNECTOR_BAD_RESPONSE");
|
||||
}
|
||||
if (!sameStringSet(response.scopes, GMAIL_CONNECTOR_SCOPES)) {
|
||||
if (!sameStringSet(response.scopes, GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes)) {
|
||||
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector returned an invalid scope set", "CONNECTOR_BAD_RESPONSE");
|
||||
}
|
||||
const authorizationUrl = new URL(response.authorizationUrl);
|
||||
@@ -209,24 +247,42 @@ export function createPaperclipIdGmailConnector(input: {
|
||||
}
|
||||
return { authorizationUrl: authorizationUrl.toString(), expiresAt: response.expiresAt };
|
||||
},
|
||||
async claim(values: { subject: string; companyId: string; claimId: string }) {
|
||||
return openCredentials(await call("claim", values), "gmail-initial-tokens", values.subject, values.companyId);
|
||||
async claim(values: { subject: string; companyId: string; profile?: GoogleWorkspaceConnectorProfileId; claimId: string }) {
|
||||
const profile = values.profile ?? "gmail.draft";
|
||||
return openCredentials(await call("claim", { ...values, profile }), sealPurpose("initial", profile), values.subject, values.companyId, profile);
|
||||
},
|
||||
async refresh(values: { subject: string; companyId: string; refreshToken: string }) {
|
||||
async refresh(values: { subject: string; companyId: string; profile?: GoogleWorkspaceConnectorProfileId; refreshToken: string }) {
|
||||
const profile = values.profile ?? "gmail.draft";
|
||||
return openCredentials(
|
||||
await call("refresh", values, { field: "refreshToken", value: values.refreshToken }),
|
||||
"gmail-access-token",
|
||||
await call("refresh", { ...values, profile }, { field: "refreshToken", value: values.refreshToken }),
|
||||
sealPurpose("access", profile),
|
||||
values.subject,
|
||||
values.companyId,
|
||||
profile,
|
||||
);
|
||||
},
|
||||
async revoke(values: { subject: string; companyId: string; token: string }) {
|
||||
await call("revoke", values, { field: "token", value: values.token });
|
||||
async revoke(values: { subject: string; companyId: string; profile?: GoogleWorkspaceConnectorProfileId; token: string }) {
|
||||
await call("revoke", { ...values, profile: values.profile ?? "gmail.draft" }, { field: "token", value: values.token });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type PaperclipIdGmailConnector = ReturnType<typeof createPaperclipIdGmailConnector>;
|
||||
export type PaperclipIdGoogleWorkspaceConnector = PaperclipIdGmailConnector;
|
||||
|
||||
let capabilityCache: { key: string; expiresAt: number; profiles: GoogleWorkspaceConnectorProfileId[] } | null = null;
|
||||
|
||||
export async function paperclipIdGoogleConnectorCapabilitiesFromEnv(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Promise<GoogleWorkspaceConnectorProfileId[]> {
|
||||
const config = paperclipIdGmailConnectorConfigFromEnv(env);
|
||||
if (!config) return [];
|
||||
const key = `${config.baseUrl}|${config.instanceId}|${config.environment}`;
|
||||
if (capabilityCache?.key === key && capabilityCache.expiresAt > Date.now()) return capabilityCache.profiles;
|
||||
const profiles = await createPaperclipIdGmailConnector({ config }).getCapabilities();
|
||||
capabilityCache = { key, expiresAt: Date.now() + 60_000, profiles };
|
||||
return profiles;
|
||||
}
|
||||
|
||||
function signRequest(payload: Record<string, unknown>, key: KeyObject): string {
|
||||
const header = { alg: "EdDSA", typ: JWS_TYP };
|
||||
@@ -271,6 +327,7 @@ function unseal(
|
||||
recipientPrivateKey: KeyObject,
|
||||
instanceId: string,
|
||||
environment: string,
|
||||
profile?: GoogleWorkspaceConnectorProfileId,
|
||||
): SealedGmailCredentials {
|
||||
try {
|
||||
const ephemeralRaw = Buffer.from(envelope.epk, "base64url");
|
||||
@@ -283,7 +340,9 @@ function unseal(
|
||||
const recipientJwk = createPublicKey(recipientPrivateKey).export({ format: "jwk" }) as { x?: string };
|
||||
if (!recipientJwk.x) throw badEnvelope();
|
||||
const recipientRaw = Buffer.from(recipientJwk.x, "base64url");
|
||||
const aad = Buffer.from([1, SEAL_ALGORITHM, envelope.purpose, instanceId, environment].join("\n"), "utf8");
|
||||
const aadFields: Array<string | number> = [1, SEAL_ALGORITHM, envelope.purpose, instanceId, environment];
|
||||
if (profile) aadFields.push(profile);
|
||||
const aad = Buffer.from(aadFields.join("\n"), "utf8");
|
||||
const key = Buffer.from(hkdfSync(
|
||||
"sha256",
|
||||
diffieHellman({ privateKey: recipientPrivateKey, publicKey: ephemeralKey }),
|
||||
@@ -320,6 +379,14 @@ function badEnvelope() {
|
||||
return new PaperclipIdConnectorError("Paperclip ID Gmail connector returned an invalid sealed credential", "CONNECTOR_BAD_RESPONSE");
|
||||
}
|
||||
|
||||
function sealPurpose(
|
||||
kind: "initial" | "access",
|
||||
profile: GoogleWorkspaceConnectorProfileId,
|
||||
): SealedEnvelope["purpose"] {
|
||||
if (profile === "gmail.draft") return kind === "initial" ? "gmail-initial-tokens" : "gmail-access-token";
|
||||
return kind === "initial" ? "google-workspace-initial-tokens" : "google-workspace-access-token";
|
||||
}
|
||||
|
||||
async function sha256Base64Url(value: string): Promise<string> {
|
||||
return createHash("sha256").update(value, "utf8").digest("base64url");
|
||||
}
|
||||
|
||||
@@ -281,6 +281,12 @@ async function sendRequest(input: {
|
||||
const body = readRequestBody(init.body);
|
||||
const method = (init.method ?? "GET").toUpperCase();
|
||||
|
||||
// Raw node:http requests do not add the default User-Agent that `fetch` and
|
||||
// curl send. Some provider CDNs reject an absent User-Agent before the MCP or
|
||||
// OAuth service sees the request (Coda returns 403 instead of its 401 OAuth
|
||||
// challenge), so give every guarded request a stable, non-identifying client
|
||||
// token while preserving an explicit caller value.
|
||||
if (!headers.has("user-agent")) headers.set("user-agent", "Paperclip/1.0");
|
||||
if (body !== undefined && !headers.has("content-length") && !headers.has("transfer-encoding")) {
|
||||
headers.set("content-length", String(body.byteLength));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
redactRemoteUrlCredential,
|
||||
remoteUrlCredentialMatchesPublicUrl,
|
||||
splitRemoteUrlCredential,
|
||||
} from "./remote-url-credentials.js";
|
||||
|
||||
describe("remote URL credentials", () => {
|
||||
it("moves token query values out of the stored connection URL", () => {
|
||||
expect(splitRemoteUrlCredential(
|
||||
"https://mcp.zapier.com/api/v1/connect?token=zapier-secret®ion=us",
|
||||
)).toEqual({
|
||||
publicUrl: "https://mcp.zapier.com/api/v1/connect?region=us",
|
||||
secretUrl: "https://mcp.zapier.com/api/v1/connect?token=zapier-secret®ion=us",
|
||||
secretParameterNames: ["token"],
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves non-sensitive URLs inline", () => {
|
||||
expect(splitRemoteUrlCredential("https://example.test/mcp?region=us")).toEqual({
|
||||
publicUrl: "https://example.test/mcp?region=us",
|
||||
secretUrl: null,
|
||||
secretParameterNames: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("moves URL userinfo out of the stored connection URL", () => {
|
||||
expect(splitRemoteUrlCredential(
|
||||
"https://api-key:secret@example.test/mcp?region=us",
|
||||
)).toEqual({
|
||||
publicUrl: "https://example.test/mcp?region=us",
|
||||
secretUrl: "https://api-key:secret@example.test/mcp?region=us",
|
||||
secretParameterNames: [],
|
||||
});
|
||||
expect(remoteUrlCredentialMatchesPublicUrl(
|
||||
"https://example.test/mcp?region=us",
|
||||
"https://api-key:secret@example.test/mcp?region=us",
|
||||
)).toBe(true);
|
||||
});
|
||||
|
||||
it("redacts credentials in activity-log URLs", () => {
|
||||
expect(redactRemoteUrlCredential(
|
||||
"https://user:password@example.test/mcp?token=secret®ion=us",
|
||||
)).toBe("https://REDACTED@example.test/mcp?token=REDACTED®ion=us");
|
||||
});
|
||||
|
||||
it("allows only secret-query differences when materializing a vault URL", () => {
|
||||
expect(remoteUrlCredentialMatchesPublicUrl(
|
||||
"https://example.test/mcp?region=us",
|
||||
"https://example.test/mcp?region=us&token=secret",
|
||||
)).toBe(true);
|
||||
expect(remoteUrlCredentialMatchesPublicUrl(
|
||||
"https://example.test/mcp?region=us",
|
||||
"https://other.test/mcp?region=us&token=secret",
|
||||
)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
const REDACTED_URL_VALUE = "REDACTED";
|
||||
|
||||
const SENSITIVE_URL_FIELD_PATTERN =
|
||||
/^(?:code|state|nonce|key|[A-Za-z0-9_-]*(?:api[-_]?key|access[-_]?token|auth(?:[-_]?token)?|token|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)[A-Za-z0-9_-]*)$/i;
|
||||
|
||||
export const REMOTE_URL_SECRET_CONFIG_PATH = "remote.url";
|
||||
|
||||
export interface SplitRemoteUrlCredential {
|
||||
publicUrl: string;
|
||||
secretUrl: string | null;
|
||||
secretParameterNames: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Separate credential-bearing query values from the URL that is safe to store
|
||||
* on a tool connection. The complete URL is written to the encrypted vault;
|
||||
* only its public origin, path, and non-sensitive query configuration remain
|
||||
* in connection config and API responses.
|
||||
*/
|
||||
export function splitRemoteUrlCredential(value: string): SplitRemoteUrlCredential {
|
||||
const input = value.trim();
|
||||
const url = new URL(input);
|
||||
const hasUserInfo = url.username.length > 0 || url.password.length > 0;
|
||||
if (hasUserInfo) {
|
||||
url.username = "";
|
||||
url.password = "";
|
||||
}
|
||||
const secretParameterNames: string[] = [];
|
||||
for (const key of [...url.searchParams.keys()]) {
|
||||
if (!SENSITIVE_URL_FIELD_PATTERN.test(key)) continue;
|
||||
secretParameterNames.push(key);
|
||||
url.searchParams.delete(key);
|
||||
}
|
||||
return {
|
||||
publicUrl: url.toString(),
|
||||
secretUrl: hasUserInfo || secretParameterNames.length > 0 ? input : null,
|
||||
secretParameterNames,
|
||||
};
|
||||
}
|
||||
|
||||
/** Preserve useful endpoint context in logs without retaining credentials. */
|
||||
export function redactRemoteUrlCredential(value: string): string {
|
||||
const input = value.trim();
|
||||
try {
|
||||
const url = new URL(input);
|
||||
if (url.username || url.password) {
|
||||
url.username = REDACTED_URL_VALUE;
|
||||
url.password = "";
|
||||
}
|
||||
for (const key of [...url.searchParams.keys()]) {
|
||||
if (SENSITIVE_URL_FIELD_PATTERN.test(key)) url.searchParams.set(key, REDACTED_URL_VALUE);
|
||||
}
|
||||
return url.toString();
|
||||
} catch {
|
||||
return "configured remote MCP endpoint";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A vault value may be replaced independently of connection config. Keep that
|
||||
* replacement constrained to the public endpoint the operator originally
|
||||
* reviewed; only credential-bearing query values may differ.
|
||||
*/
|
||||
export function remoteUrlCredentialMatchesPublicUrl(publicValue: string, secretValue: string): boolean {
|
||||
try {
|
||||
return splitRemoteUrlCredential(secretValue).publicUrl === new URL(publicValue).toString();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+1805
-140
File diff suppressed because it is too large.
Load diff
@@ -56,13 +56,25 @@ import type {
|
||||
ToolMcpGatewayWithTokens,
|
||||
UpdateToolMcpGateway,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
isGoogleWorkspaceConnectorProfileId,
|
||||
type GoogleWorkspaceConnectorProfileId,
|
||||
} from "@paperclipai/shared";
|
||||
import type { AgentToolDescriptor, PluginToolDispatcher } from "./plugin-tool-dispatcher.js";
|
||||
import { logActivity, type LogActivityInput } from "./activity-log.js";
|
||||
import { secretService } from "./secrets.js";
|
||||
import { mcpHttpRequestHeaders, parseMcpHttpResponseBody } from "./mcp-http.js";
|
||||
import {
|
||||
initializeMcpHttpSession,
|
||||
mcpHttpRequestHeaders,
|
||||
parseMcpHttpResponseBody,
|
||||
} from "./mcp-http.js";
|
||||
import { projectedConnectionHeaders } from "./tool-access.js";
|
||||
import { parseRemoteHttpEndpoint } from "./remote-http-endpoint-guard.js";
|
||||
import { guardedRemoteHttpFetch, type GuardedRemoteHttpFetchOptions } from "./remote-http-fetch.js";
|
||||
import {
|
||||
REMOTE_URL_SECRET_CONFIG_PATH,
|
||||
remoteUrlCredentialMatchesPublicUrl,
|
||||
} from "./remote-url-credentials.js";
|
||||
import { toolAccessPolicyService } from "./tool-access-policy.js";
|
||||
import { issueThreadInteractionService } from "./issue-thread-interactions.js";
|
||||
import {
|
||||
@@ -80,6 +92,13 @@ import {
|
||||
PaperclipIdConnectorError,
|
||||
type PaperclipIdGmailConnector,
|
||||
} from "./paperclip-id-gmail-connector.js";
|
||||
import {
|
||||
createVercelConnectClient,
|
||||
vercelGrantReference,
|
||||
vercelTokenRequest,
|
||||
VercelConnectClientError,
|
||||
type VercelConnectClient,
|
||||
} from "./vercel-connect.js";
|
||||
import {
|
||||
canonicalToolArguments,
|
||||
readSignedToolArgumentsPayload,
|
||||
@@ -799,6 +818,21 @@ export function createToolGatewayService(
|
||||
composioClientFactory?: (apiKey: string) => ComposioClient;
|
||||
/** Test seam for refreshing personal Gmail grants. */
|
||||
paperclipIdGmailConnector?: PaperclipIdGmailConnector | null;
|
||||
/** Refreshes customer-owned/DCR OAuth grants before remote MCP execution. */
|
||||
oauthGrantRefresher?: (input: {
|
||||
companyId: string;
|
||||
connectionId: string;
|
||||
grantId: string;
|
||||
forceRefresh?: boolean;
|
||||
actor?: {
|
||||
actorType?: "agent" | "user" | "system" | "plugin";
|
||||
actorId?: string | null;
|
||||
};
|
||||
issueId?: string | null;
|
||||
heartbeatRunId?: string | null;
|
||||
}) => Promise<typeof connectionGrants.$inferSelect>;
|
||||
/** Test seam for resolving Vercel Connect credentials. */
|
||||
vercelConnectClient?: VercelConnectClient | null;
|
||||
mcpGatewayProtocolLimits?: Partial<{
|
||||
authFailures: Partial<McpGatewayRateLimitConfig>;
|
||||
gatewayRequests: Partial<McpGatewayRateLimitConfig>;
|
||||
@@ -826,6 +860,9 @@ export function createToolGatewayService(
|
||||
? createPaperclipIdGmailConnector({ config: gmailConnectorConfig, now: options.now })
|
||||
: null);
|
||||
const gmailRefreshFlights = new Map<string, Promise<typeof connectionGrants.$inferSelect>>();
|
||||
const vercelConnect = options.vercelConnectClient === undefined
|
||||
? createVercelConnectClient()
|
||||
: options.vercelConnectClient;
|
||||
const composioSessions = createComposioSessionManager(db, {
|
||||
composioClientFactory: options.composioClientFactory,
|
||||
now: options.now ? () => new Date(options.now!()) : undefined,
|
||||
@@ -2198,6 +2235,44 @@ export function createToolGatewayService(
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
async function resolvedRemoteEndpoint(
|
||||
session: ToolGatewaySession,
|
||||
connection: typeof toolConnections.$inferSelect,
|
||||
grant: typeof connectionGrants.$inferSelect,
|
||||
): Promise<string> {
|
||||
const publicEndpoint = remoteEndpoint(connection.config ?? {});
|
||||
const ref = (connection.credentialRefs ?? []).find((candidate) => candidate.placement === "url");
|
||||
if (!ref) return publicEndpoint;
|
||||
const grantRef = grantRefForCredential(grant, ref);
|
||||
if (!grantRef) {
|
||||
throw new ToolGatewayHttpError(
|
||||
422,
|
||||
"A configured credential secret could not be resolved.",
|
||||
"mcp_remote_missing_secret",
|
||||
{ connectionId: connection.id, credential: REMOTE_URL_SECRET_CONFIG_PATH },
|
||||
);
|
||||
}
|
||||
const value = await resolveGrantSecretValue(
|
||||
session,
|
||||
connection,
|
||||
grant,
|
||||
grantRef,
|
||||
REMOTE_URL_SECRET_CONFIG_PATH,
|
||||
);
|
||||
if (!remoteUrlCredentialMatchesPublicUrl(publicEndpoint, value)) {
|
||||
throw new ToolGatewayHttpError(
|
||||
422,
|
||||
"The stored MCP URL credential no longer matches this connection.",
|
||||
"mcp_remote_url_credential_mismatch",
|
||||
{ connectionId: connection.id },
|
||||
);
|
||||
}
|
||||
return parseRemoteHttpEndpoint(
|
||||
value,
|
||||
(message, code) => new ToolGatewayHttpError(422, message, code),
|
||||
).toString();
|
||||
}
|
||||
|
||||
function allowPrivateRemoteEndpoints() {
|
||||
return options.deploymentMode !== "authenticated" || options.deploymentExposure !== "public";
|
||||
}
|
||||
@@ -2431,7 +2506,7 @@ export function createToolGatewayService(
|
||||
|
||||
async function markRemoteConnectionHealth(
|
||||
connection: typeof toolConnections.$inferSelect,
|
||||
status: "ok" | "error" | "missing_secret",
|
||||
status: "ok" | "error" | "missing_secret" | "degraded",
|
||||
message: string | null,
|
||||
) {
|
||||
const now = new Date();
|
||||
@@ -2448,7 +2523,7 @@ export function createToolGatewayService(
|
||||
.where(eq(toolConnections.id, connection.id));
|
||||
}
|
||||
|
||||
function grantRefForHeader(
|
||||
function grantRefForCredential(
|
||||
grant: typeof connectionGrants.$inferSelect,
|
||||
ref: McpConnectionCredentialRef,
|
||||
): ToolCredentialSecretRef | undefined {
|
||||
@@ -2524,13 +2599,27 @@ export function createToolGatewayService(
|
||||
return resolved.value;
|
||||
}
|
||||
|
||||
async function maybeRefreshPaperclipIdGmailGrant(
|
||||
async function maybeRefreshPaperclipIdGoogleGrant(
|
||||
session: ToolGatewaySession,
|
||||
connection: typeof toolConnections.$inferSelect,
|
||||
grant: typeof connectionGrants.$inferSelect,
|
||||
): Promise<typeof connectionGrants.$inferSelect> {
|
||||
const oauth = asRecord(asRecord(connection.config)?.oauth);
|
||||
if (oauth?.strategy !== "paperclip_id_connector") return grant;
|
||||
const configuredProfile = oauth.connectorProfile;
|
||||
const connectorProfile: GoogleWorkspaceConnectorProfileId = configuredProfile === undefined
|
||||
? "gmail.draft"
|
||||
: typeof configuredProfile === "string" && isGoogleWorkspaceConnectorProfileId(configuredProfile)
|
||||
? configuredProfile
|
||||
: (() => {
|
||||
throw new ToolGatewayHttpError(422, "Google authorization has an invalid connector profile", "google_connector_profile_invalid", {
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
});
|
||||
})();
|
||||
const connectorSubject = typeof oauth.connectorSubjectUserId === "string"
|
||||
? oauth.connectorSubjectUserId
|
||||
: grant.subjectUserId;
|
||||
const grantOauth = asRecord(asRecord(grant.providerTenant)?.oauth);
|
||||
const expiresAt = typeof grantOauth?.accessTokenExpiresAt === "string"
|
||||
? Date.parse(grantOauth.accessTokenExpiresAt)
|
||||
@@ -2540,10 +2629,10 @@ export function createToolGatewayService(
|
||||
const existingFlight = gmailRefreshFlights.get(grant.id);
|
||||
if (existingFlight) return existingFlight;
|
||||
const refresh = (async () => {
|
||||
if (!gmailConnector || !grant.subjectUserId) {
|
||||
if (!gmailConnector || !connectorSubject) {
|
||||
await db.update(connectionGrants).set({ status: "needs_reauthorization", updatedAt: new Date(currentTime) })
|
||||
.where(eq(connectionGrants.id, grant.id));
|
||||
throw new ToolGatewayHttpError(409, "Gmail authorization must be reconnected", "gmail_reauthorization_required", {
|
||||
throw new ToolGatewayHttpError(409, "Google authorization must be reconnected", "google_reauthorization_required", {
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
});
|
||||
@@ -2553,7 +2642,7 @@ export function createToolGatewayService(
|
||||
if (!accessRef || !refreshRef) {
|
||||
await db.update(connectionGrants).set({ status: "needs_reauthorization", updatedAt: new Date(currentTime) })
|
||||
.where(eq(connectionGrants.id, grant.id));
|
||||
throw new ToolGatewayHttpError(409, "Gmail authorization must be reconnected", "gmail_reauthorization_required", {
|
||||
throw new ToolGatewayHttpError(409, "Google authorization must be reconnected", "google_reauthorization_required", {
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
});
|
||||
@@ -2561,8 +2650,9 @@ export function createToolGatewayService(
|
||||
const refreshToken = await resolveGrantSecretValue(session, connection, grant, refreshRef);
|
||||
try {
|
||||
const credentials = await gmailConnector.refresh({
|
||||
subject: grant.subjectUserId,
|
||||
subject: connectorSubject,
|
||||
companyId: connection.companyId,
|
||||
profile: connectorProfile,
|
||||
refreshToken,
|
||||
});
|
||||
await secrets.rotate(accessRef.secretId, { value: credentials.accessToken });
|
||||
@@ -2583,7 +2673,7 @@ export function createToolGatewayService(
|
||||
.where(and(eq(connectionGrants.id, grant.id), eq(connectionGrants.status, "active")))
|
||||
.returning();
|
||||
if (!updated) {
|
||||
throw new ToolGatewayHttpError(409, "Gmail authorization is no longer active", "gmail_reauthorization_required", {
|
||||
throw new ToolGatewayHttpError(409, "Google authorization is no longer active", "google_reauthorization_required", {
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
});
|
||||
@@ -2594,12 +2684,12 @@ export function createToolGatewayService(
|
||||
if (error instanceof PaperclipIdConnectorError && error.code === "REAUTHORIZATION_REQUIRED") {
|
||||
await db.update(connectionGrants).set({ status: "needs_reauthorization", updatedAt: new Date(options.now?.() ?? Date.now()) })
|
||||
.where(eq(connectionGrants.id, grant.id));
|
||||
throw new ToolGatewayHttpError(409, "Gmail authorization must be reconnected", "gmail_reauthorization_required", {
|
||||
throw new ToolGatewayHttpError(409, "Google authorization must be reconnected", "google_reauthorization_required", {
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
});
|
||||
}
|
||||
throw new ToolGatewayHttpError(502, "Gmail authorization could not be refreshed", "gmail_refresh_failed", {
|
||||
throw new ToolGatewayHttpError(502, "Google authorization could not be refreshed", "google_refresh_failed", {
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
});
|
||||
@@ -2617,12 +2707,133 @@ export function createToolGatewayService(
|
||||
session: ToolGatewaySession,
|
||||
connection: typeof toolConnections.$inferSelect,
|
||||
grant: typeof connectionGrants.$inferSelect,
|
||||
resolveOptions: { forceRefresh?: boolean } = {},
|
||||
): Promise<Record<string, string>> {
|
||||
grant = await maybeRefreshPaperclipIdGmailGrant(session, connection, grant);
|
||||
if (connection.credentialSource === "vercel_connect") {
|
||||
if (!connection.externalCredential || !vercelConnect) {
|
||||
throw new ToolGatewayHttpError(503, "Vercel Connect is not configured", "vercel_connect_unavailable", {
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
});
|
||||
}
|
||||
const request = vercelTokenRequest({
|
||||
credential: connection.externalCredential,
|
||||
grant,
|
||||
connectionId: connection.id,
|
||||
companyId: connection.companyId,
|
||||
});
|
||||
try {
|
||||
const token = await vercelConnect.getToken(request, resolveOptions);
|
||||
if (
|
||||
token.connector.id !== connection.externalCredential.connectorId
|
||||
&& token.connector.uid !== connection.externalCredential.connectorUid
|
||||
) {
|
||||
throw new VercelConnectClientError("vercel_connect_request_failed", 502);
|
||||
}
|
||||
await db.update(connectionGrants).set({
|
||||
externalCredential: vercelGrantReference({
|
||||
credential: connection.externalCredential,
|
||||
token,
|
||||
subjectId: grant.externalCredential?.subjectId,
|
||||
verifiedAt: new Date(options.now?.() ?? Date.now()),
|
||||
}),
|
||||
status: "active",
|
||||
revokedAt: null,
|
||||
updatedAt: new Date(options.now?.() ?? Date.now()),
|
||||
}).where(and(
|
||||
eq(connectionGrants.id, grant.id),
|
||||
eq(connectionGrants.companyId, connection.companyId),
|
||||
eq(connectionGrants.connectionId, connection.id),
|
||||
));
|
||||
return {
|
||||
[connection.externalCredential.headerName]:
|
||||
`${connection.externalCredential.headerPrefix ?? ""}${token.token}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof VercelConnectClientError
|
||||
&& error.code === "vercel_connect_authorization_required"
|
||||
) {
|
||||
await db.update(connectionGrants).set({
|
||||
status: "needs_reauthorization",
|
||||
updatedAt: new Date(options.now?.() ?? Date.now()),
|
||||
}).where(and(
|
||||
eq(connectionGrants.id, grant.id),
|
||||
eq(connectionGrants.companyId, connection.companyId),
|
||||
));
|
||||
const responsibleUserId = grant.kind === "user"
|
||||
? grant.subjectUserId
|
||||
: session.responsibleUserId;
|
||||
if (responsibleUserId) {
|
||||
await createUserAuthorizationInteraction(
|
||||
session,
|
||||
connection,
|
||||
responsibleUserId,
|
||||
grant.kind,
|
||||
);
|
||||
}
|
||||
}
|
||||
const code = error instanceof VercelConnectClientError
|
||||
? error.code
|
||||
: "vercel_connect_request_failed";
|
||||
const status = error instanceof VercelConnectClientError ? error.status : 502;
|
||||
const message = error instanceof VercelConnectClientError
|
||||
? error.message
|
||||
: "Vercel Connect could not resolve this credential.";
|
||||
await markRemoteConnectionHealth(
|
||||
connection,
|
||||
code === "vercel_connect_unavailable"
|
||||
|| code === "vercel_connect_auth_failed"
|
||||
|| code === "vercel_connect_installation_required"
|
||||
? "degraded"
|
||||
: "error",
|
||||
message,
|
||||
);
|
||||
throw new ToolGatewayHttpError(status, message, code, {
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
grant = await maybeRefreshPaperclipIdGoogleGrant(session, connection, grant);
|
||||
const oauth = asRecord(asRecord(connection.config)?.oauth);
|
||||
if (
|
||||
connection.authKind === "oauth"
|
||||
&& connection.credentialSource === "paperclip_vault"
|
||||
&& oauth?.strategy !== "paperclip_id_connector"
|
||||
&& options.oauthGrantRefresher
|
||||
) {
|
||||
try {
|
||||
grant = await options.oauthGrantRefresher({
|
||||
companyId: connection.companyId,
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
forceRefresh: resolveOptions.forceRefresh,
|
||||
actor: {
|
||||
actorType: session.actorType ?? (session.agentId ? "agent" : "system"),
|
||||
actorId: session.actorId ?? session.agentId,
|
||||
},
|
||||
issueId: session.issueId,
|
||||
heartbeatRunId: session.runId,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ToolGatewayHttpError) throw error;
|
||||
const record = asRecord(error);
|
||||
const details = asRecord(record?.details) ?? {};
|
||||
const status = typeof record?.status === "number" ? record.status : 502;
|
||||
const reasonCode = typeof details.code === "string" ? details.code : "oauth_refresh_failed";
|
||||
const message = error instanceof Error ? error.message : "OAuth authorization could not be refreshed";
|
||||
throw new ToolGatewayHttpError(status, message, reasonCode, {
|
||||
...details,
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
const headers: Record<string, string> = {};
|
||||
for (const ref of connection.credentialRefs ?? []) {
|
||||
if (ref.placement !== "header") continue;
|
||||
const grantRef = grantRefForHeader(grant, ref);
|
||||
const grantRef = grantRefForCredential(grant, ref);
|
||||
if (!grantRef) continue;
|
||||
try {
|
||||
const value = await resolveGrantSecretValue(
|
||||
@@ -2711,17 +2922,19 @@ export function createToolGatewayService(
|
||||
const credentialSecretVersions: ConnectedCredentialVersionSnapshot[] = [];
|
||||
|
||||
for (const ref of connection.credentialRefs ?? []) {
|
||||
if (ref.placement !== "header") continue;
|
||||
if (ref.placement !== "header" && ref.placement !== "url") continue;
|
||||
const typedRef = ref as McpConnectionCredentialRef;
|
||||
const grantRef = grantRefForHeader(grant, typedRef);
|
||||
const grantRef = grantRefForCredential(grant, typedRef);
|
||||
if (!grantRef) continue;
|
||||
const configPath = `credentials.${typedRef.name}`;
|
||||
const configPath = typedRef.placement === "url"
|
||||
? REMOTE_URL_SECRET_CONFIG_PATH
|
||||
: `credentials.${typedRef.name}`;
|
||||
headerCredentialVersions.push(await resolveConnectedCredentialVersion(connection, {
|
||||
secretId: grantRef.secretId,
|
||||
versionSelector: grantRef.versionSelector,
|
||||
configPath,
|
||||
refHash: credentialVersionRefHash({
|
||||
kind: "header",
|
||||
kind: typedRef.placement === "url" ? "url" : "header",
|
||||
name: typedRef.name,
|
||||
secretId: grantRef.secretId,
|
||||
placement: typedRef.placement,
|
||||
@@ -2757,6 +2970,7 @@ export function createToolGatewayService(
|
||||
session: ToolGatewaySession,
|
||||
connection: typeof toolConnections.$inferSelect,
|
||||
userId: string,
|
||||
grantKind: "organization" | "user" = "user",
|
||||
) {
|
||||
if (!session.issueId || !session.agentId || !session.runId) return;
|
||||
const [company] = await db.select({ issuePrefix: companies.issuePrefix }).from(companies)
|
||||
@@ -2765,10 +2979,14 @@ export function createToolGatewayService(
|
||||
const idempotencyKey = `connection-authorization:${connection.id}:${userId}`;
|
||||
const payload = {
|
||||
version: 1 as const,
|
||||
prompt: `Connect your ${connection.name} account to continue`,
|
||||
acceptLabel: "Connect account",
|
||||
prompt: grantKind === "organization"
|
||||
? `Reconnect the ${connection.name} organization identity to continue`
|
||||
: `Connect your ${connection.name} account to continue`,
|
||||
acceptLabel: grantKind === "organization" ? "Reconnect organization" : "Connect account",
|
||||
rejectLabel: "Not now",
|
||||
detailsMarkdown: "This run needs your personal authorization. Paperclip will not use another user's identity.",
|
||||
detailsMarkdown: grantKind === "organization"
|
||||
? "Vercel Connect reports that the shared organization identity needs authorization."
|
||||
: "This run needs your personal authorization. Paperclip will not use another user's identity.",
|
||||
target: {
|
||||
type: "custom" as const,
|
||||
key: `connection:${connection.uid}:user:${userId}`,
|
||||
@@ -2810,8 +3028,10 @@ export function createToolGatewayService(
|
||||
effectiveResolverPolicySource: "requested",
|
||||
idempotencyKey,
|
||||
sourceRunId: session.runId,
|
||||
title: `Connect your ${connection.name}`,
|
||||
summary: "Personal authorization is required before this run can continue.",
|
||||
title: grantKind === "organization" ? `Reconnect ${connection.name}` : `Connect your ${connection.name}`,
|
||||
summary: grantKind === "organization"
|
||||
? "Organization authorization is required before this run can continue."
|
||||
: "Personal authorization is required before this run can continue.",
|
||||
createdByAgentId: session.agentId,
|
||||
addresseeUserId: userId,
|
||||
payload,
|
||||
@@ -3538,11 +3758,19 @@ export function createToolGatewayService(
|
||||
result: unknown,
|
||||
transport: "mcp_http" | "local_stdio" = "mcp_http",
|
||||
spawnedLocalProcess = false,
|
||||
sourceTemplateKey?: string | null,
|
||||
) {
|
||||
const record = asRecord(result);
|
||||
if (!record) throw malformedRemoteMcpResponse();
|
||||
const providerContent = normalizeMcpContent(record.content);
|
||||
const googleWorkspacePermissionDenied = record.isError === true
|
||||
&& (sourceTemplateKey === "gmail" || sourceTemplateKey?.startsWith("google-") === true)
|
||||
&& /caller does not have permission/i.test(providerContent);
|
||||
const content = googleWorkspacePermissionDenied
|
||||
? "Google rejected this call. Google Workspace MCP is a Developer Preview: enroll the signed-in Workspace account and this OAuth client's Google Cloud project in Google's Developer Preview Program, wait for Google's registration confirmation, then reconnect and try again."
|
||||
: providerContent;
|
||||
return {
|
||||
content: normalizeMcpContent(record.content),
|
||||
content,
|
||||
data: {
|
||||
content: record.content,
|
||||
structuredContent: record.structuredContent ?? null,
|
||||
@@ -3572,7 +3800,7 @@ export function createToolGatewayService(
|
||||
scopeRevision: composioScopeRevision,
|
||||
})
|
||||
: null;
|
||||
let endpoint = composioSession?.url ?? remoteEndpoint(connection.config ?? {});
|
||||
let endpoint = composioSession?.url ?? await resolvedRemoteEndpoint(session, connection, grant);
|
||||
// Method-defined headers are trusted catalog configuration. Treat them as
|
||||
// managed headers so callers cannot override the scope that was reviewed
|
||||
// during tools/list. Credentials remain authoritative on collisions.
|
||||
@@ -3605,6 +3833,27 @@ export function createToolGatewayService(
|
||||
const timer = setTimeout(() => controller.abort(), ms);
|
||||
timer.unref?.();
|
||||
try {
|
||||
const dispatchRemote = (target: string, init: RequestInit) => options.remoteHttpRequest
|
||||
? options.remoteHttpRequest(target, init)
|
||||
: guardedRemoteHttpFetch(target, init, {
|
||||
...remoteHttpFetchOptions(),
|
||||
// This call site owns a caller-set budget that can exceed the
|
||||
// transport's default response deadline, so hand it down rather than
|
||||
// letting the tighter default cut a legitimately slow tool short.
|
||||
responseTimeoutMs: ms,
|
||||
});
|
||||
let requestHeaders = headers;
|
||||
if (connection.config.mcpSessionRequired === true) {
|
||||
requestHeaders = await initializeMcpHttpSession({
|
||||
send: (init) => dispatchRemote(endpoint, {
|
||||
...init,
|
||||
redirect: "manual",
|
||||
signal: controller.signal,
|
||||
}),
|
||||
headers,
|
||||
requestId,
|
||||
});
|
||||
}
|
||||
// The guard runs inside this call and the connection is pinned to the
|
||||
// address it approved, so an operator-supplied hostname cannot be rebound
|
||||
// onto a loopback or metadata address between validation and dispatch
|
||||
@@ -3614,7 +3863,7 @@ export function createToolGatewayService(
|
||||
redirect: "manual",
|
||||
// MCP Streamable HTTP requires the Accept header advertising both a JSON
|
||||
// body and an SSE stream; spec-compliant servers 406 without it.
|
||||
headers: mcpHttpRequestHeaders(headers),
|
||||
headers: mcpHttpRequestHeaders(requestHeaders),
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
@@ -3626,15 +3875,7 @@ export function createToolGatewayService(
|
||||
},
|
||||
}),
|
||||
};
|
||||
let response = options.remoteHttpRequest
|
||||
? await options.remoteHttpRequest(endpoint, requestInit)
|
||||
: await guardedRemoteHttpFetch(endpoint, requestInit, {
|
||||
...remoteHttpFetchOptions(),
|
||||
// This call site owns a caller-set budget that can exceed the
|
||||
// transport's default response deadline, so hand it down rather than
|
||||
// letting the tighter default cut a legitimately slow tool short.
|
||||
responseTimeoutMs: ms,
|
||||
});
|
||||
let response = await dispatchRemote(endpoint, requestInit);
|
||||
if (response.status === 401 && composioChild) {
|
||||
composioSession = await composioSessions.ensureSession(connection.id, {
|
||||
tools: [entry.toolName],
|
||||
@@ -3647,12 +3888,52 @@ export function createToolGatewayService(
|
||||
headers = builtHeaders.headers;
|
||||
headerSummary = builtHeaders.summary;
|
||||
const retryInit = { ...requestInit, headers: mcpHttpRequestHeaders(headers) };
|
||||
response = options.remoteHttpRequest
|
||||
? await options.remoteHttpRequest(endpoint, retryInit)
|
||||
: await guardedRemoteHttpFetch(endpoint, retryInit, {
|
||||
...remoteHttpFetchOptions(),
|
||||
responseTimeoutMs: ms,
|
||||
});
|
||||
response = await dispatchRemote(endpoint, retryInit);
|
||||
}
|
||||
const oauth = asRecord(asRecord(connection.config)?.oauth);
|
||||
if (
|
||||
response.status === 401
|
||||
&& connection.authKind === "oauth"
|
||||
&& connection.credentialSource === "paperclip_vault"
|
||||
&& oauth?.strategy !== "paperclip_id_connector"
|
||||
&& options.oauthGrantRefresher
|
||||
) {
|
||||
credentialHeaders = {
|
||||
...projectedConnectionHeaders(connection),
|
||||
...await resolveCredentialHeaders(session, connection, grant, { forceRefresh: true }),
|
||||
};
|
||||
builtHeaders = buildRemoteHeaders({ session, connection, credentialHeaders, callerHeaders });
|
||||
headers = builtHeaders.headers;
|
||||
headerSummary = builtHeaders.summary;
|
||||
response = await dispatchRemote(endpoint, {
|
||||
...requestInit,
|
||||
headers: mcpHttpRequestHeaders(headers),
|
||||
});
|
||||
}
|
||||
if (response.status === 401 && connection.credentialSource === "vercel_connect") {
|
||||
if (!connection.externalCredential || !vercelConnect) {
|
||||
throw new ToolGatewayHttpError(503, "Vercel Connect is not configured", "vercel_connect_unavailable", {
|
||||
connectionId: connection.id,
|
||||
});
|
||||
}
|
||||
const tokenRequest = vercelTokenRequest({
|
||||
credential: connection.externalCredential,
|
||||
grant,
|
||||
connectionId: connection.id,
|
||||
companyId: connection.companyId,
|
||||
});
|
||||
vercelConnect.evict(tokenRequest);
|
||||
credentialHeaders = {
|
||||
...projectedConnectionHeaders(connection),
|
||||
...await resolveCredentialHeaders(session, connection, grant, { forceRefresh: true }),
|
||||
};
|
||||
builtHeaders = buildRemoteHeaders({ session, connection, credentialHeaders, callerHeaders });
|
||||
headers = builtHeaders.headers;
|
||||
headerSummary = builtHeaders.summary;
|
||||
response = await dispatchRemote(endpoint, {
|
||||
...requestInit,
|
||||
headers: mcpHttpRequestHeaders(headers),
|
||||
});
|
||||
}
|
||||
const body = await readBoundedRemoteResponse(response);
|
||||
execution.response = {
|
||||
@@ -3707,7 +3988,10 @@ export function createToolGatewayService(
|
||||
if (resultElicitation) {
|
||||
await requestElicitationForRecordedToolCall({ session, tool, invocationId, request: resultElicitation });
|
||||
}
|
||||
const result = normalizeMcpToolResult(payloadRecord.result);
|
||||
const sourceTemplateKey = typeof connection.config.sourceTemplateKey === "string"
|
||||
? connection.config.sourceTemplateKey
|
||||
: null;
|
||||
const result = normalizeMcpToolResult(payloadRecord.result, "mcp_http", false, sourceTemplateKey);
|
||||
await markRemoteConnectionHealth(connection, "ok", "Remote MCP server responded to tools/call.");
|
||||
return { result, headerSummary, execution };
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
deriveVercelConnectSubject,
|
||||
vercelConnectCallbackUrl,
|
||||
vercelConnectIntegrationStatus,
|
||||
vercelConnectSdkOptions,
|
||||
vercelGrantReference,
|
||||
vercelTokenRequest,
|
||||
} from "./vercel-connect.js";
|
||||
import type { VercelConnectCredentialReference } from "@paperclipai/shared";
|
||||
|
||||
const credential: VercelConnectCredentialReference = {
|
||||
provider: "vercel_connect",
|
||||
connectorId: "scl_posthog",
|
||||
connectorUid: "posthog-paperclip",
|
||||
service: "posthog",
|
||||
connectorType: "api-key",
|
||||
principalMode: "user",
|
||||
headerName: "Authorization",
|
||||
headerPrefix: "Bearer ",
|
||||
scopes: ["read", "write"],
|
||||
};
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe("Vercel Connect credential adapter", () => {
|
||||
it("canonicalizes Paperclip's loopback callback to Vercel's accepted localhost form", () => {
|
||||
expect(vercelConnectCallbackUrl(
|
||||
"http://127.0.0.1:3200/api/tools/oauth/callback?stale=1#fragment",
|
||||
"one-time-state",
|
||||
)).toBe("http://localhost:3200/api/tools/vercel-connect/callback?state=one-time-state");
|
||||
expect(vercelConnectCallbackUrl(
|
||||
"https://paperclip.example/api/tools/oauth/callback",
|
||||
"one-time-state",
|
||||
)).toBe("https://paperclip.example/api/tools/vercel-connect/callback?state=one-time-state");
|
||||
});
|
||||
|
||||
it("gates new setup separately from runtime credential availability", () => {
|
||||
expect(vercelConnectIntegrationStatus({
|
||||
PAPERCLIP_VERCEL_CONNECT_ENABLED: "false",
|
||||
PAPERCLIP_VERCEL_CONNECT_ACCESS_TOKEN: "bootstrap-token",
|
||||
} as NodeJS.ProcessEnv)).toMatchObject({
|
||||
enabled: false,
|
||||
configured: true,
|
||||
authentication: "access_token",
|
||||
});
|
||||
expect(vercelConnectIntegrationStatus({
|
||||
PAPERCLIP_VERCEL_CONNECT_ENABLED: "true",
|
||||
VERCEL_OIDC_TOKEN: "workload-token",
|
||||
PAPERCLIP_VERCEL_CONNECT_ACCESS_TOKEN: "fallback-token",
|
||||
} as NodeJS.ProcessEnv)).toMatchObject({
|
||||
enabled: true,
|
||||
configured: true,
|
||||
authentication: "workload_oidc",
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers workload OIDC over the access-token fallback", () => {
|
||||
expect(vercelConnectSdkOptions({
|
||||
VERCEL_OIDC_TOKEN: "workload-token",
|
||||
PAPERCLIP_VERCEL_CONNECT_ACCESS_TOKEN: "stale-fallback-token",
|
||||
} as NodeJS.ProcessEnv)).toEqual({});
|
||||
expect(vercelConnectSdkOptions({
|
||||
PAPERCLIP_VERCEL_CONNECT_ACCESS_TOKEN: "fallback-token",
|
||||
} as NodeJS.ProcessEnv, true)).toEqual({
|
||||
vercelToken: "fallback-token",
|
||||
forceRefresh: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("derives stable company- and user-bound subjects without browser input", () => {
|
||||
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "instance-one");
|
||||
const base = {
|
||||
credential,
|
||||
connectionId: "connection-one",
|
||||
companyId: "company-one",
|
||||
grantKind: "user" as const,
|
||||
subjectUserId: "user-one",
|
||||
};
|
||||
const first = deriveVercelConnectSubject(base);
|
||||
expect(first).toEqual(deriveVercelConnectSubject(base));
|
||||
expect(first.subject).toMatchObject({ type: "user", id: expect.stringMatching(/^pc_/) });
|
||||
expect(deriveVercelConnectSubject({ ...base, companyId: "company-two" }).subject).not.toEqual(first.subject);
|
||||
expect(deriveVercelConnectSubject({ ...base, subjectUserId: "user-two" }).subject).not.toEqual(first.subject);
|
||||
});
|
||||
|
||||
it("uses app subjects without reusable browser-provided identifiers", () => {
|
||||
const appCredential = { ...credential, principalMode: "app" as const };
|
||||
expect(deriveVercelConnectSubject({
|
||||
credential: appCredential,
|
||||
connectionId: "connection-one",
|
||||
companyId: "company-one",
|
||||
grantKind: "organization",
|
||||
})).toEqual({ subject: { type: "app" } });
|
||||
expect(vercelTokenRequest({
|
||||
credential: appCredential,
|
||||
connectionId: "connection-one",
|
||||
companyId: "company-one",
|
||||
resources: ["https://mcp.posthog.com/mcp"],
|
||||
grant: { kind: "organization", subjectUserId: null, externalCredential: null },
|
||||
})).toMatchObject({
|
||||
connector: "posthog-paperclip",
|
||||
subject: { type: "app" },
|
||||
resources: ["https://mcp.posthog.com/mcp"],
|
||||
});
|
||||
});
|
||||
|
||||
it("persists only the allow-listed grant summary, never bearer or upstream claims", () => {
|
||||
const reference = vercelGrantReference({
|
||||
credential,
|
||||
subjectId: "pc_subject",
|
||||
verifiedAt: new Date("2026-08-26T12:00:00.000Z"),
|
||||
token: {
|
||||
token: "provider-bearer-must-not-persist",
|
||||
tokenId: "stk_123",
|
||||
expiresAt: Date.parse("2026-08-26T13:00:00.000Z"),
|
||||
connector: { id: "scl_posthog", uid: "posthog-paperclip", type: "api-key" },
|
||||
installationId: "installation-1",
|
||||
tenantId: "project-1",
|
||||
claims: { email: "private@example.com" },
|
||||
metadata: { arbitrary: "private" },
|
||||
},
|
||||
});
|
||||
expect(reference).toEqual({
|
||||
provider: "vercel_connect",
|
||||
subjectType: "user",
|
||||
subjectId: "pc_subject",
|
||||
installationId: "installation-1",
|
||||
tenantId: "project-1",
|
||||
tokenId: "stk_123",
|
||||
expiresAt: "2026-08-26T13:00:00.000Z",
|
||||
lastVerifiedAt: "2026-08-26T12:00:00.000Z",
|
||||
});
|
||||
expect(JSON.stringify(reference)).not.toContain("provider-bearer");
|
||||
expect(JSON.stringify(reference)).not.toContain("private@example.com");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
ConnectError,
|
||||
ConnectorInstallationRequiredError,
|
||||
NoValidTokenError,
|
||||
UserAuthorizationRequiredError,
|
||||
deleteTokenCacheEntry,
|
||||
getConnectorMetadata,
|
||||
getTokenResponse,
|
||||
revokeToken,
|
||||
startAuthorization,
|
||||
type ConnectAuthorizationResponse,
|
||||
type ConnectorMetadata,
|
||||
type ConnectTokenParams,
|
||||
type ConnectTokenResponse,
|
||||
type ConnectTokenSubject,
|
||||
} from "@vercel/connect";
|
||||
import type {
|
||||
ConnectionGrantKind,
|
||||
VercelConnectCredentialReference,
|
||||
VercelConnectGrantReference,
|
||||
} from "@paperclipai/shared";
|
||||
|
||||
export type VercelConnectFailureCode =
|
||||
| "vercel_connect_unavailable"
|
||||
| "vercel_connect_auth_failed"
|
||||
| "vercel_connect_connector_not_found"
|
||||
| "vercel_connect_authorization_required"
|
||||
| "vercel_connect_installation_required"
|
||||
| "vercel_connect_request_failed";
|
||||
|
||||
export class VercelConnectClientError extends Error {
|
||||
constructor(
|
||||
readonly code: VercelConnectFailureCode,
|
||||
readonly status: number,
|
||||
) {
|
||||
super(vercelConnectFailureMessage(code));
|
||||
this.name = "VercelConnectClientError";
|
||||
}
|
||||
}
|
||||
|
||||
export function vercelConnectFailureMessage(code: VercelConnectFailureCode): string {
|
||||
switch (code) {
|
||||
case "vercel_connect_unavailable":
|
||||
return "Vercel Connect is not configured on this Paperclip instance.";
|
||||
case "vercel_connect_auth_failed":
|
||||
return "Paperclip could not authenticate to Vercel Connect. Repair or refresh the instance's Vercel authority.";
|
||||
case "vercel_connect_connector_not_found":
|
||||
return "Vercel Connect could not find an attached connector with that UID.";
|
||||
case "vercel_connect_authorization_required":
|
||||
return "This Vercel Connect identity needs authorization.";
|
||||
case "vercel_connect_installation_required":
|
||||
return "This connector must be installed or attached in Vercel before Paperclip can use it.";
|
||||
default:
|
||||
return "Vercel Connect could not complete the credential request.";
|
||||
}
|
||||
}
|
||||
|
||||
export type VercelConnectTokenRequest = {
|
||||
connector: string;
|
||||
subject: ConnectTokenSubject;
|
||||
scopes: string[];
|
||||
resources?: string[];
|
||||
installationId?: string;
|
||||
};
|
||||
|
||||
export interface VercelConnectClient {
|
||||
getConnectorMetadata(connector: string): Promise<ConnectorMetadata>;
|
||||
getToken(input: VercelConnectTokenRequest, options?: { forceRefresh?: boolean }): Promise<ConnectTokenResponse>;
|
||||
startAuthorization(input: VercelConnectTokenRequest, callbackUrl: string): Promise<ConnectAuthorizationResponse>;
|
||||
revoke(input: VercelConnectTokenRequest): Promise<void>;
|
||||
evict(input: VercelConnectTokenRequest): void;
|
||||
}
|
||||
|
||||
function enabled(value: string | undefined): boolean {
|
||||
return /^(1|true|yes|on)$/i.test(value?.trim() ?? "");
|
||||
}
|
||||
|
||||
export function vercelConnectIntegrationStatus(env: NodeJS.ProcessEnv = process.env): {
|
||||
enabled: boolean;
|
||||
configured: boolean;
|
||||
authentication: "workload_oidc" | "access_token" | null;
|
||||
manageUrl: string;
|
||||
} {
|
||||
const integrationEnabled = enabled(env.PAPERCLIP_VERCEL_CONNECT_ENABLED);
|
||||
const hasAccessToken = Boolean(env.PAPERCLIP_VERCEL_CONNECT_ACCESS_TOKEN?.trim());
|
||||
const hasWorkloadOidc = Boolean(env.VERCEL_OIDC_TOKEN?.trim());
|
||||
return {
|
||||
enabled: integrationEnabled,
|
||||
// Resolution stays available for existing connections when new setup is
|
||||
// disabled. The feature flag gates creation, not already-authorized calls.
|
||||
configured: hasWorkloadOidc || hasAccessToken,
|
||||
authentication: hasWorkloadOidc ? "workload_oidc" : hasAccessToken ? "access_token" : null,
|
||||
manageUrl: "https://vercel.com/connect",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Vercel permits plaintext callbacks only on the literal `localhost` host.
|
||||
* Paperclip's local board commonly runs on 127.0.0.1, which is the same
|
||||
* loopback boundary but Vercel rejects it before authorization starts.
|
||||
*/
|
||||
export function vercelConnectCallbackUrl(redirectUri: string, state: string): string {
|
||||
const callbackUrl = new URL(redirectUri);
|
||||
if (
|
||||
callbackUrl.protocol === "http:"
|
||||
&& (callbackUrl.hostname === "127.0.0.1" || callbackUrl.hostname === "[::1]")
|
||||
) {
|
||||
callbackUrl.hostname = "localhost";
|
||||
}
|
||||
callbackUrl.pathname = "/api/tools/vercel-connect/callback";
|
||||
callbackUrl.search = new URLSearchParams({ state }).toString();
|
||||
callbackUrl.hash = "";
|
||||
return callbackUrl.toString();
|
||||
}
|
||||
|
||||
export function vercelConnectSdkOptions(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
forceRefresh?: boolean,
|
||||
): { vercelToken?: string; forceRefresh?: boolean } {
|
||||
// Passing `vercelToken` makes the SDK use that token instead of workload
|
||||
// OIDC. Keep the configured access token strictly as a fallback so a stale
|
||||
// bootstrap token cannot shadow a healthy Vercel-injected identity.
|
||||
const hasWorkloadOidc = Boolean(env.VERCEL_OIDC_TOKEN?.trim());
|
||||
const vercelToken = hasWorkloadOidc
|
||||
? undefined
|
||||
: env.PAPERCLIP_VERCEL_CONNECT_ACCESS_TOKEN?.trim();
|
||||
return {
|
||||
...(vercelToken ? { vercelToken } : {}),
|
||||
...(forceRefresh ? { forceRefresh: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function tokenParams(input: VercelConnectTokenRequest): ConnectTokenParams {
|
||||
return {
|
||||
subject: input.subject,
|
||||
scopes: input.scopes,
|
||||
...(input.resources?.length ? { resources: input.resources } : {}),
|
||||
...(input.installationId ? { installationId: input.installationId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function mapSdkError(error: unknown): VercelConnectClientError {
|
||||
if (error instanceof UserAuthorizationRequiredError || error instanceof NoValidTokenError) {
|
||||
return new VercelConnectClientError("vercel_connect_authorization_required", 409);
|
||||
}
|
||||
if (error instanceof ConnectorInstallationRequiredError) {
|
||||
return new VercelConnectClientError("vercel_connect_installation_required", 409);
|
||||
}
|
||||
if (error instanceof ConnectError) {
|
||||
if (error.status === 401 || error.status === 403) {
|
||||
return new VercelConnectClientError("vercel_connect_auth_failed", 503);
|
||||
}
|
||||
if (error.status === 404) {
|
||||
return new VercelConnectClientError("vercel_connect_connector_not_found", 422);
|
||||
}
|
||||
}
|
||||
return new VercelConnectClientError("vercel_connect_request_failed", 502);
|
||||
}
|
||||
|
||||
export function createVercelConnectClient(): VercelConnectClient {
|
||||
const flights = new Map<string, Promise<ConnectTokenResponse>>();
|
||||
const assertConfigured = () => {
|
||||
if (!vercelConnectIntegrationStatus().configured) {
|
||||
throw new VercelConnectClientError("vercel_connect_unavailable", 503);
|
||||
}
|
||||
};
|
||||
return {
|
||||
async getConnectorMetadata(connector) {
|
||||
assertConfigured();
|
||||
try {
|
||||
return await getConnectorMetadata(connector, vercelConnectSdkOptions());
|
||||
} catch (error) {
|
||||
throw mapSdkError(error);
|
||||
}
|
||||
},
|
||||
async getToken(input, options = {}) {
|
||||
assertConfigured();
|
||||
const params = tokenParams(input);
|
||||
const key = JSON.stringify([input.connector, params, options.forceRefresh === true]);
|
||||
const existing = flights.get(key);
|
||||
if (existing) return existing;
|
||||
const request = getTokenResponse(
|
||||
input.connector,
|
||||
params,
|
||||
vercelConnectSdkOptions(process.env, options.forceRefresh),
|
||||
).catch((error: unknown) => {
|
||||
throw mapSdkError(error);
|
||||
});
|
||||
flights.set(key, request);
|
||||
try {
|
||||
return await request;
|
||||
} finally {
|
||||
if (flights.get(key) === request) flights.delete(key);
|
||||
}
|
||||
},
|
||||
async startAuthorization(input, callbackUrl) {
|
||||
assertConfigured();
|
||||
try {
|
||||
return await startAuthorization(input.connector, tokenParams(input), {
|
||||
...vercelConnectSdkOptions(),
|
||||
callbackUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
throw mapSdkError(error);
|
||||
}
|
||||
},
|
||||
async revoke(input) {
|
||||
assertConfigured();
|
||||
try {
|
||||
await revokeToken(input.connector, {
|
||||
subject: input.subject,
|
||||
...(input.installationId ? { installationId: input.installationId } : {}),
|
||||
}, vercelConnectSdkOptions());
|
||||
} catch (error) {
|
||||
throw mapSdkError(error);
|
||||
}
|
||||
},
|
||||
evict(input) {
|
||||
deleteTokenCacheEntry(input.connector, tokenParams(input));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function subjectHash(parts: string[]): string {
|
||||
return createHash("sha256").update(parts.join("\0")).digest("base64url").slice(0, 43);
|
||||
}
|
||||
|
||||
/** Subjects are deterministic, company-bound and never accepted from clients. */
|
||||
export function deriveVercelConnectSubject(input: {
|
||||
credential: VercelConnectCredentialReference;
|
||||
connectionId: string;
|
||||
companyId: string;
|
||||
grantKind: ConnectionGrantKind;
|
||||
subjectUserId?: string | null;
|
||||
}): { subject: ConnectTokenSubject; subjectId?: string } {
|
||||
if (input.credential.principalMode === "app") return { subject: { type: "app" } };
|
||||
const instanceId = process.env.PAPERCLIP_INSTANCE_ID
|
||||
?? process.env.PAPERCLIP_DEPLOYMENT_ID
|
||||
?? "paperclip-instance";
|
||||
const subjectId = `pc_${subjectHash([
|
||||
instanceId,
|
||||
input.companyId,
|
||||
input.connectionId,
|
||||
input.grantKind,
|
||||
input.grantKind === "user" ? input.subjectUserId ?? "missing-user" : "organization",
|
||||
])}`;
|
||||
return { subject: { type: "user", id: subjectId }, subjectId };
|
||||
}
|
||||
|
||||
export function vercelTokenRequest(input: {
|
||||
credential: VercelConnectCredentialReference;
|
||||
grant: { kind: ConnectionGrantKind; subjectUserId: string | null; externalCredential?: VercelConnectGrantReference | null };
|
||||
connectionId: string;
|
||||
companyId: string;
|
||||
resources?: string[];
|
||||
}): VercelConnectTokenRequest {
|
||||
const derived = deriveVercelConnectSubject({
|
||||
credential: input.credential,
|
||||
connectionId: input.connectionId,
|
||||
companyId: input.companyId,
|
||||
grantKind: input.grant.kind,
|
||||
subjectUserId: input.grant.subjectUserId,
|
||||
});
|
||||
return {
|
||||
connector: input.credential.connectorUid,
|
||||
subject: derived.subject,
|
||||
scopes: input.credential.scopes,
|
||||
...(input.resources?.length ? { resources: input.resources } : {}),
|
||||
...(input.grant.externalCredential?.installationId
|
||||
? { installationId: input.grant.externalCredential.installationId }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function vercelGrantReference(input: {
|
||||
credential: VercelConnectCredentialReference;
|
||||
token: ConnectTokenResponse;
|
||||
subjectId?: string;
|
||||
verifiedAt?: Date;
|
||||
}): VercelConnectGrantReference {
|
||||
return {
|
||||
provider: "vercel_connect",
|
||||
subjectType: input.credential.principalMode,
|
||||
...(input.subjectId ? { subjectId: input.subjectId } : {}),
|
||||
...(input.token.installationId ? { installationId: input.token.installationId } : {}),
|
||||
...(input.token.tenantId ? { tenantId: input.token.tenantId } : {}),
|
||||
...(input.token.tokenId ? { tokenId: input.token.tokenId } : {}),
|
||||
expiresAt: new Date(input.token.expiresAt).toISOString(),
|
||||
lastVerifiedAt: (input.verifiedAt ?? new Date()).toISOString(),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user