feat(apps): add Composio and Gmail connectors (#12342)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - App connections need both direct providers and managed provider
hubs.
> - The grant layer now defines safe credential ownership.
> - Composio needs parent and child connection lifecycle rules, and
Gmail needs governed setup.
> - This pull request adds both connector families on the grant
foundation.
> - The benefit is broader app access without weakening credential
isolation.

## Linked Issues or Issue Description

Refs #11965

This is stack 4 of 11. It depends on stack 3 and replaces another
reviewable part of #11965.

## What Changed

- Add Composio parent and child connection support.
- Add Gmail connection setup and governance.
- Preserve credential paths and remove duplicate binding declarations.
- Cascade Composio pause and restore actions to child connections.

## Verification

- `pnpm --filter @paperclipai/server typecheck`
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/tool-access-service.test.ts`
- Result: 164 tests passed.
- `pnpm build`

## Risks

- Parent lifecycle changes can affect every Composio child.
- The service restores only children whose provider accounts remain
active.
- Credential binding paths are normalized before secret resolution.

> 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
- [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:33 -05:00
1 parent 20ccf3f476
commit 6244e4cf32
54 files changed
+5110 -91

No files matched your search

@@ -0,0 +1,263 @@
import { createHash, randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { companySecretBindings, toolConnections } from "@paperclipai/db";
import type { ToolCredentialSecretRef } from "@paperclipai/shared";
import { unprocessable } from "../errors.js";
import { createComposioClient, type ComposioClient } from "./composio.js";
import { secretService } from "./secrets.js";
const DEFAULT_SESSION_TTL_MS = 50 * 60 * 1000;
const sessionQueues = new Map<string, Promise<void>>();
type ComposioChildConfig = {
parentConnectionId: string;
toolkitSlug: string;
connectedAccountId?: string;
};
type SessionRef = { name: string; configPath: string; secretId: string };
type CachedSession = {
sessionId: string;
scopeKey: string;
fingerprint: string;
createdAt: string;
urlRef: SessionRef;
headerRefs: SessionRef[];
};
export type ComposioSessionCredentials = {
sessionId: string;
scopeKey: string;
url: string;
headers: Record<string, string>;
};
export type ComposioSessionManagerOptions = {
composioClientFactory?: (apiKey: string) => ComposioClient;
now?: () => Date;
sessionTtlMs?: number;
};
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: {};
}
export function composioChildConfig(connection: typeof toolConnections.$inferSelect): ComposioChildConfig | null {
const config = record(connection.config);
if (config.provider !== "composio") return null;
if (typeof config.parentConnectionId !== "string" || typeof config.toolkitSlug !== "string") return null;
return {
parentConnectionId: config.parentConnectionId,
toolkitSlug: config.toolkitSlug,
...(typeof config.connectedAccountId === "string" ? { connectedAccountId: config.connectedAccountId } : {}),
};
}
function normalizedTools(tools: string[] | undefined): string[] {
return [...new Set((tools ?? []).map((tool) => tool.trim()).filter(Boolean))].sort();
}
function scopeKeyFor(toolkitSlug: string, tools: string[]): string {
return createHash("sha256").update(JSON.stringify({ toolkitSlug, tools })).digest("hex").slice(0, 24);
}
function cacheFrom(connection: typeof toolConnections.$inferSelect): Record<string, CachedSession> {
return record(record(connection.transportConfig).composioSessions) as Record<string, CachedSession>;
}
export function createComposioSessionManager(db: Db, options: ComposioSessionManagerOptions = {}) {
const secrets = secretService(db);
const now = options.now ?? (() => new Date());
const ttlMs = Math.max(1, options.sessionTtlMs ?? DEFAULT_SESSION_TTL_MS);
async function connectionRow(connectionId: string) {
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionId)).limit(1);
if (!connection) throw unprocessable("The Composio toolkit connection no longer exists.", { code: "composio_child_missing" });
return connection;
}
async function parentApiKey(child: typeof toolConnections.$inferSelect, config: ComposioChildConfig) {
const [parent] = await db.select().from(toolConnections).where(and(
eq(toolConnections.id, config.parentConnectionId),
eq(toolConnections.companyId, child.companyId),
)).limit(1);
if (!parent) throw unprocessable("The parent Composio connection is missing.", { code: "composio_parent_missing" });
const headerRef = parent.credentialRefs.find((ref) => ref.placement === "header" && ref.key.toLowerCase() === "x-api-key");
const secretRef = parent.credentialSecretRefs.find((ref) => ref.configPath === "credentials.apiKey")
?? (headerRef
? {
secretId: headerRef.secretId,
versionSelector: headerRef.version ?? "latest",
configPath: headerRef.name.startsWith("credentials.") ? headerRef.name : `credentials.${headerRef.name}`,
}
: undefined);
if (!secretRef) throw unprocessable("The parent Composio API key is missing.", { code: "composio_api_key_missing" });
const apiKey = await secrets.resolveSecretValue(parent.companyId, secretRef.secretId, secretRef.versionSelector ?? "latest", {
consumerType: "tool_connection",
consumerId: parent.id,
configPath: secretRef.configPath,
actorType: "system",
});
const revision = createHash("sha256").update(JSON.stringify({
parentId: parent.id,
updatedAt: parent.updatedAt.toISOString(),
secretId: secretRef.secretId,
versionSelector: secretRef.versionSelector ?? "latest",
})).digest("hex");
return { apiKey, revision };
}
async function resolveRef(child: typeof toolConnections.$inferSelect, ref: SessionRef) {
return secrets.resolveSecretValue(child.companyId, ref.secretId, "latest", {
consumerType: "tool_connection",
consumerId: child.id,
configPath: ref.configPath,
actorType: "system",
});
}
async function resolveCached(child: typeof toolConnections.$inferSelect, cached: CachedSession): Promise<ComposioSessionCredentials> {
const url = await resolveRef(child, cached.urlRef);
const headers = Object.fromEntries(await Promise.all(cached.headerRefs.map(async (ref) => [ref.name, await resolveRef(child, ref)])));
return { sessionId: cached.sessionId, scopeKey: cached.scopeKey, url, headers };
}
async function createOrRotateRef(input: {
child: typeof toolConnections.$inferSelect;
cached?: SessionRef;
name: string;
configPath: string;
value: string;
}): Promise<SessionRef> {
if (input.cached) {
await secrets.rotate(input.cached.secretId, { value: input.value });
return { ...input.cached, name: input.name };
}
const secret = await secrets.create(input.child.companyId, {
name: `${input.child.name} Composio session ${input.name} ${randomUUID().slice(0, 8)}`,
key: `tool_app.${randomUUID()}.${input.configPath.replace(/[^a-z0-9_:-]+/gi, "_")}`,
provider: "local_encrypted",
value: input.value,
description: `Hosted Composio MCP session credential for ${input.child.name}.`,
});
return { name: input.name, configPath: input.configPath, secretId: secret.id };
}
async function mint(
connectionId: string,
tools: string[],
force: boolean,
scopeRevision?: string,
): Promise<ComposioSessionCredentials> {
const child = await connectionRow(connectionId);
const config = composioChildConfig(child);
if (!config) throw unprocessable("This connection is not a Composio toolkit child.", { code: "not_composio_child" });
const { apiKey, revision } = await parentApiKey(child, config);
const scopeKey = scopeKeyFor(config.toolkitSlug, tools);
const fingerprint = createHash("sha256").update(JSON.stringify({
revision,
toolkitSlug: config.toolkitSlug,
connectedAccountId: config.connectedAccountId ?? null,
tools,
scopeRevision: scopeRevision ?? null,
})).digest("hex");
const cache = cacheFrom(child);
const cached = cache[scopeKey];
if (!force && cached?.fingerprint === fingerprint && Date.parse(cached.createdAt) + ttlMs > now().getTime()) {
return resolveCached(child, cached);
}
const client = options.composioClientFactory?.(apiKey) ?? createComposioClient({ apiKey });
const session = await client.createSession(`paperclip:${child.companyId}`, {
mcp: true,
toolkits: [config.toolkitSlug],
...(tools.length > 0 ? { tools: { [config.toolkitSlug]: { enable: tools } } } : {}),
...(config.connectedAccountId ? { connectedAccounts: { [config.toolkitSlug]: [config.connectedAccountId] } } : {}),
});
if (!session.mcp?.url) throw unprocessable("Composio did not return a hosted MCP URL.", { code: "composio_session_invalid" });
const prefix = `composio.session.${scopeKey}`;
const urlRef = await createOrRotateRef({
child,
cached: cached?.urlRef,
name: "url",
configPath: `${prefix}.url`,
value: session.mcp.url,
});
const priorHeaders = new Map((cached?.headerRefs ?? []).map((ref) => [ref.name.toLowerCase(), ref]));
const headerRefs: SessionRef[] = [];
for (const [name, value] of Object.entries(session.mcp.headers ?? {})) {
headerRefs.push(await createOrRotateRef({
child,
cached: priorHeaders.get(name.toLowerCase()),
name,
configPath: `${prefix}.header.${createHash("sha256").update(name.toLowerCase()).digest("hex").slice(0, 16)}`,
value,
}));
}
const nextCached: CachedSession = {
sessionId: session.session_id,
scopeKey,
fingerprint,
createdAt: now().toISOString(),
urlRef,
headerRefs,
};
const nextCache = { ...cache, [scopeKey]: nextCached };
const refsByPath = new Map(child.credentialSecretRefs.map((ref) => [ref.configPath, ref]));
for (const ref of [urlRef, ...headerRefs]) {
refsByPath.set(ref.configPath, {
secretId: ref.secretId,
versionSelector: "latest",
configPath: ref.configPath,
required: true,
label: ref.name === "url" ? "Composio MCP session URL" : `Composio MCP ${ref.name} header`,
keyScope: scopeKey,
} satisfies ToolCredentialSecretRef);
}
const credentialSecretRefs = [...refsByPath.values()];
const updated = await db.transaction(async (tx) => {
const [row] = await tx.update(toolConnections).set({
transportConfig: { ...record(child.transportConfig), composioSessions: nextCache },
credentialSecretRefs,
updatedAt: now(),
}).where(eq(toolConnections.id, child.id)).returning();
await tx.delete(companySecretBindings).where(and(
eq(companySecretBindings.companyId, child.companyId),
eq(companySecretBindings.targetType, "tool_connection"),
eq(companySecretBindings.targetId, child.id),
));
if (credentialSecretRefs.length > 0) {
await tx.insert(companySecretBindings).values(credentialSecretRefs.map((ref) => ({
companyId: child.companyId,
secretId: ref.secretId,
targetType: "tool_connection" as const,
targetId: child.id,
configPath: ref.configPath,
projectionClass: ref.projectionClass ?? "unclassified",
projectionAllowlistKey: ref.projectionAllowlistKey ?? null,
})));
}
return row;
});
return resolveCached(updated, nextCached);
}
return {
ensureSession(connectionId: string, input: { tools?: string[]; force?: boolean; scopeRevision?: string } = {}) {
const tools = normalizedTools(input.tools);
const previous = sessionQueues.get(connectionId) ?? Promise.resolve();
const pending = previous.catch(() => undefined).then(
() => mint(connectionId, tools, input.force === true, input.scopeRevision),
);
const queued = pending.then(() => undefined, () => undefined);
sessionQueues.set(connectionId, queued);
return pending.finally(() => {
if (sessionQueues.get(connectionId) === queued) sessionQueues.delete(connectionId);
});
},
};
}
+198
View File
@@ -0,0 +1,198 @@
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { afterEach, describe, expect, it } from "vitest";
import { ComposioApiError, createComposioClient } from "./composio.js";
type Fixture = {
baseUrl: string;
requests: Array<{ method: string; url: string; apiKey: string | undefined }>;
close(): Promise<void>;
};
async function startFixture(
handle: (request: IncomingMessage, response: ServerResponse) => void,
): Promise<Fixture> {
const requests: Fixture["requests"] = [];
const server = createServer((request, response) => {
requests.push({
method: request.method ?? "GET",
url: request.url ?? "/",
apiKey: Array.isArray(request.headers["x-api-key"])
? request.headers["x-api-key"]?.[0]
: request.headers["x-api-key"],
});
handle(request, response);
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Fixture did not bind a TCP port");
return {
baseUrl: `http://127.0.0.1:${address.port}/api/v3.1`,
requests,
close: () => new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve())),
};
}
const fixtures: Fixture[] = [];
afterEach(async () => {
await Promise.all(fixtures.splice(0).map((fixture) => fixture.close()));
});
describe("Composio REST client", () => {
it("serializes every supported REST operation", async () => {
const requests: Array<{ url: string; method: string; body: unknown }> = [];
const fetchMock = (async (input: string | URL | Request, init?: RequestInit) => {
requests.push({
url: String(input),
method: init?.method ?? "GET",
body: init?.body ? JSON.parse(String(init.body)) : undefined,
});
return new Response(JSON.stringify({ items: [], session_id: "session-1", mcp: { url: "https://mcp.test" } }), {
status: 200,
headers: { "content-type": "application/json" },
});
}) as typeof fetch;
const client = createComposioClient({
apiKey: "ak_fixture",
baseUrl: "https://composio.test/api/v3.1",
fetch: fetchMock,
});
await client.listAuthConfigs({
cursor: "auth-page",
limit: 25,
toolkitSlugs: ["github", "slack"],
showDisabled: true,
});
await client.createConnectLink({
authConfigId: "ac_1",
userId: "user-1",
alias: "primary",
callbackUrl: "https://paperclip.test/callback",
});
await client.listConnectedAccounts({
cursor: "account-page",
limit: 10,
toolkitSlugs: ["github", "slack"],
statuses: ["ACTIVE", "EXPIRED"],
userIds: ["user-1", "user-2"],
authConfigIds: ["ac_1", "ac_2"],
});
await client.deleteConnectedAccount("ca/with spaces");
await client.createSession("user-1", {
mcp: true,
toolkits: ["github"],
tools: { github: { enable: ["GITHUB_LIST_REPOS"] } },
authConfigs: { github: "ac_1" },
connectedAccounts: { github: ["ca_1"] },
});
await client.resumeSession("session/with spaces", { mcp: true });
expect(requests).toEqual([
{
url: "https://composio.test/api/v3.1/auth_configs?cursor=auth-page&limit=25&show_disabled=true&toolkit_slug=github%2Cslack",
method: "GET",
body: undefined,
},
{
url: "https://composio.test/api/v3.1/connected_accounts/link",
method: "POST",
body: {
auth_config_id: "ac_1",
user_id: "user-1",
alias: "primary",
callback_url: "https://paperclip.test/callback",
},
},
{
url: "https://composio.test/api/v3.1/connected_accounts?cursor=account-page&limit=10&toolkit_slugs=github&toolkit_slugs=slack&statuses=ACTIVE&statuses=EXPIRED&user_ids=user-1&user_ids=user-2&auth_config_ids=ac_1&auth_config_ids=ac_2",
method: "GET",
body: undefined,
},
{
url: "https://composio.test/api/v3.1/connected_accounts/ca%2Fwith%20spaces",
method: "DELETE",
body: undefined,
},
{
url: "https://composio.test/api/v3.1/tool_router/session",
method: "POST",
body: {
user_id: "user-1",
mcp: true,
toolkits: { enabled: ["github"] },
tools: { github: { enable: ["GITHUB_LIST_REPOS"] } },
auth_configs: { github: "ac_1" },
connected_accounts: { github: ["ca_1"] },
},
},
{
url: "https://composio.test/api/v3.1/tool_router/session/session%2Fwith%20spaces/attach",
method: "POST",
body: {},
},
]);
});
it("validates an API key with the cheap toolkit-list call", async () => {
const fixture = await startFixture((_request, response) => {
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({ items: [] }));
});
fixtures.push(fixture);
const client = createComposioClient({ apiKey: "ak_fixture", baseUrl: fixture.baseUrl });
await expect(client.validateApiKey()).resolves.toBeUndefined();
expect(fixture.requests).toEqual([{
method: "GET",
url: "/api/v3.1/toolkits?limit=1",
apiKey: "ak_fixture",
}]);
});
it("rejects an invalid key without reflecting the provider response body", async () => {
const fixture = await startFixture((_request, response) => {
response.writeHead(401, { "content-type": "application/json" });
response.end(JSON.stringify({ message: "provider-controlled secret detail" }));
});
fixtures.push(fixture);
const client = createComposioClient({ apiKey: "bad_fixture", baseUrl: fixture.baseUrl });
const error = await client.validateApiKey().catch((caught) => caught);
expect(error).toBeInstanceOf(ComposioApiError);
expect(error).toMatchObject({ status: 401, message: "Composio rejected the API key." });
expect(String(error)).not.toContain("provider-controlled");
});
it("lists typed toolkits from the project behind the key", async () => {
const fixture = await startFixture((_request, response) => {
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({
items: [{
slug: "github",
name: "GitHub",
auth_schemes: ["oauth2"],
meta: { tools_count: 42, logo: "https://example.test/github.png" },
}],
next_cursor: "next-page",
}));
});
fixtures.push(fixture);
const client = createComposioClient({ apiKey: "ak_fixture", baseUrl: fixture.baseUrl });
const result = await client.listToolkits({ limit: 10, cursor: "page-1" });
expect(result).toEqual({
items: [{
slug: "github",
name: "GitHub",
auth_schemes: ["oauth2"],
meta: { tools_count: 42, logo: "https://example.test/github.png" },
}],
next_cursor: "next-page",
});
expect(fixture.requests[0]?.url).toBe("/api/v3.1/toolkits?cursor=page-1&limit=10");
});
});
+216
View File
@@ -0,0 +1,216 @@
const DEFAULT_COMPOSIO_API_BASE_URL = "https://backend.composio.dev/api/v3.1";
export class ComposioApiError extends Error {
constructor(message: string, readonly status: number) {
super(message);
this.name = "ComposioApiError";
}
}
export type ComposioPage<T> = {
items: T[];
next_cursor?: string | null;
total_pages?: number;
current_page?: number;
total_items?: number;
};
export type ComposioToolkit = {
slug: string;
name: string;
type?: string;
auth_schemes?: string[];
composio_managed_auth_schemes?: string[];
no_auth?: boolean;
auth_guide_url?: string | null;
meta?: {
description?: string | null;
logo?: string | null;
app_url?: string | null;
tools_count?: number;
triggers_count?: number;
version?: string;
[key: string]: unknown;
};
[key: string]: unknown;
};
export type ComposioAuthConfig = {
id: string;
uuid?: string;
name?: string;
auth_scheme: string;
is_composio_managed: boolean;
status?: string;
toolkit: { slug: string; logo?: string | null; auth_guide_url?: string | null; auth_hint_url?: string | null };
[key: string]: unknown;
};
export type ComposioConnectLink = {
link_token: string;
redirect_url: string;
expires_at: string;
connected_account_id?: string | null;
[key: string]: unknown;
};
export type ComposioConnectedAccount = {
id: string;
user_id: string;
status: string;
status_reason?: string | null;
is_disabled?: boolean;
toolkit: { slug: string };
auth_config: { id: string; auth_scheme: string; is_composio_managed: boolean; is_disabled?: boolean };
[key: string]: unknown;
};
export type ComposioSession = {
session_id: string;
mcp: { type?: string; url: string; headers?: Record<string, string> };
config?: Record<string, unknown>;
config_version?: number;
warnings?: Array<{ code: string; message: string }>;
[key: string]: unknown;
};
export type ComposioListOptions = { cursor?: string; limit?: number };
export type ComposioSessionOptions = {
mcp: true;
toolkits?: string[];
tools?: Record<string, { enable: string[] }>;
authConfigs?: Record<string, string>;
connectedAccounts?: Record<string, string[]>;
};
export interface ComposioClient {
validateApiKey(): Promise<void>;
listToolkits(options?: ComposioListOptions): Promise<ComposioPage<ComposioToolkit>>;
listAuthConfigs(options?: ComposioListOptions & { toolkitSlugs?: string[]; showDisabled?: boolean }): Promise<ComposioPage<ComposioAuthConfig>>;
createConnectLink(input: { authConfigId: string; userId: string; alias?: string; callbackUrl?: string }): Promise<ComposioConnectLink>;
listConnectedAccounts(options?: ComposioListOptions & { toolkitSlugs?: string[]; statuses?: string[]; userIds?: string[]; authConfigIds?: string[] }): Promise<ComposioPage<ComposioConnectedAccount>>;
deleteConnectedAccount(connectedAccountId: string): Promise<void>;
createSession(userId: string, options: ComposioSessionOptions): Promise<ComposioSession>;
resumeSession(sessionId: string, options: { mcp: true }): Promise<ComposioSession>;
}
type ComposioClientOptions = { apiKey: string; baseUrl?: string; fetch?: typeof globalThis.fetch };
function appendQuery(url: URL, key: string, value: string | number | boolean | undefined) {
if (value !== undefined) url.searchParams.append(key, String(value));
}
function appendQueryList(url: URL, key: string, values: string[] | undefined) {
for (const value of values ?? []) url.searchParams.append(key, value);
}
function errorMessage(status: number): string {
if (status === 401 || status === 403) return "Composio rejected the API key.";
if (status === 429) return "Composio rate-limited the request. Try again shortly.";
return `Composio request failed with HTTP ${status}.`;
}
export function createComposioClient(options: ComposioClientOptions): ComposioClient {
const apiKey = options.apiKey.trim();
if (!apiKey) throw new Error("A Composio API key is required.");
const baseUrl = (options.baseUrl ?? DEFAULT_COMPOSIO_API_BASE_URL).replace(/\/+$/, "");
const fetchImpl = options.fetch ?? globalThis.fetch;
async function request<T>(path: string, init: RequestInit = {}, query?: (url: URL) => void): Promise<T> {
const url = new URL(`${baseUrl}/${path.replace(/^\/+/, "")}`);
query?.(url);
let response: Response;
try {
response = await fetchImpl(url, {
...init,
headers: {
accept: "application/json",
"x-api-key": apiKey,
...(init.body ? { "content-type": "application/json" } : {}),
...init.headers,
},
});
} catch {
throw new ComposioApiError("Could not reach Composio.", 0);
}
if (!response.ok) throw new ComposioApiError(errorMessage(response.status), response.status);
try {
return await response.json() as T;
} catch {
throw new ComposioApiError("Composio returned an invalid response.", response.status);
}
}
return {
async validateApiKey() {
await this.listToolkits({ limit: 1 });
},
listToolkits(options = {}) {
return request<ComposioPage<ComposioToolkit>>("toolkits", {}, (url) => {
appendQuery(url, "cursor", options.cursor);
appendQuery(url, "limit", options.limit);
});
},
listAuthConfigs(options = {}) {
return request<ComposioPage<ComposioAuthConfig>>("auth_configs", {}, (url) => {
appendQuery(url, "cursor", options.cursor);
appendQuery(url, "limit", options.limit);
appendQuery(url, "show_disabled", options.showDisabled);
appendQuery(url, "toolkit_slug", options.toolkitSlugs?.join(","));
});
},
createConnectLink(input) {
return request<ComposioConnectLink>("connected_accounts/link", {
method: "POST",
body: JSON.stringify({
auth_config_id: input.authConfigId,
user_id: input.userId,
...(input.alias ? { alias: input.alias } : {}),
...(input.callbackUrl ? { callback_url: input.callbackUrl } : {}),
}),
});
},
listConnectedAccounts(options = {}) {
return request<ComposioPage<ComposioConnectedAccount>>("connected_accounts", {}, (url) => {
appendQuery(url, "cursor", options.cursor);
appendQuery(url, "limit", options.limit);
appendQueryList(url, "toolkit_slugs", options.toolkitSlugs);
appendQueryList(url, "statuses", options.statuses);
appendQueryList(url, "user_ids", options.userIds);
appendQueryList(url, "auth_config_ids", options.authConfigIds);
});
},
async deleteConnectedAccount(connectedAccountId) {
const url = new URL(`${baseUrl}/connected_accounts/${encodeURIComponent(connectedAccountId)}`);
let response: Response;
try {
response = await fetchImpl(url, {
method: "DELETE",
headers: { accept: "application/json", "x-api-key": apiKey },
});
} catch {
throw new ComposioApiError("Could not reach Composio.", 0);
}
if (!response.ok) throw new ComposioApiError(errorMessage(response.status), response.status);
},
createSession(userId, options) {
return request<ComposioSession>("tool_router/session", {
method: "POST",
body: JSON.stringify({
user_id: userId,
mcp: options.mcp,
...(options.toolkits ? { toolkits: { enabled: options.toolkits } } : {}),
...(options.tools ? { tools: options.tools } : {}),
...(options.authConfigs ? { auth_configs: options.authConfigs } : {}),
...(options.connectedAccounts ? { connected_accounts: options.connectedAccounts } : {}),
}),
});
},
resumeSession(sessionId, _options) {
return request<ComposioSession>(`tool_router/session/${encodeURIComponent(sessionId)}/attach`, {
method: "POST",
body: JSON.stringify({}),
});
},
};
}
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { classifyRisk, isGmailToolPermanentlyBlocked } from "./tool-access.js";
describe("Gmail tool governance", () => {
it("allows reviewed reads and draft creation while keeping delivery and destructive actions blocked", () => {
expect(isGmailToolPermanentlyBlocked({ name: "search_threads" })).toBe(false);
expect(isGmailToolPermanentlyBlocked({ name: "get_message" })).toBe(false);
expect(classifyRisk({ name: "create_draft" }, "gmail")).toBe("write");
expect(isGmailToolPermanentlyBlocked({ name: "create_draft" })).toBe(false);
expect(isGmailToolPermanentlyBlocked({ name: "send_message" })).toBe(true);
expect(isGmailToolPermanentlyBlocked({ name: "trash_thread" })).toBe(true);
expect(isGmailToolPermanentlyBlocked({ name: "mark_as_spam" })).toBe(true);
expect(isGmailToolPermanentlyBlocked({ name: "update_labels" })).toBe(true);
});
});
+1
View File
@@ -91,6 +91,7 @@ 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 { createComposioClient, ComposioApiError, type ComposioClient } from "./composio.js";
export { smokeLabService } from "./smoke-lab.js";
export { backfillLegacyToolOAuthTokens } from "./tool-oauth-legacy-backfill.js";
export { toolAccessPolicyService } from "./tool-access-policy.js";
+19 -3
View File
@@ -6717,6 +6717,11 @@ export function issueService(db: Db) {
...issueData
} = data;
const inheritStrategyOnly = executionWorkspaceInheritanceMode === "strategy_only";
// A child may target another project. Parent workspace identity is only
// valid inside the parent's project, so do not forward it across that
// boundary; create() then resolves the target project's own workspaces.
const childProjectId = issueData.projectId ?? parent.projectId;
const childInheritsParentProject = childProjectId === parent.projectId;
const hasExplicitExecutionWorkspaceOverride =
issueData.executionWorkspaceId !== undefined ||
issueData.executionWorkspacePreference !== undefined ||
@@ -6728,8 +6733,10 @@ export function issueService(db: Db) {
let child = await issueService(db).create(parent.companyId, {
...issueData,
parentId: parent.id,
projectId: issueData.projectId ?? parent.projectId,
projectWorkspaceId: issueData.projectWorkspaceId ?? (inheritStrategyOnly ? parent.projectWorkspaceId : undefined),
projectId: childProjectId,
projectWorkspaceId:
issueData.projectWorkspaceId ??
(inheritStrategyOnly && childInheritsParentProject ? parent.projectWorkspaceId : undefined),
goalId: issueData.goalId ?? parent.goalId,
actorResponsibleUserId: issueData.actorResponsibleUserId ?? null,
trustExplicitResponsibleUserId: issueData.trustExplicitResponsibleUserId === true,
@@ -7162,10 +7169,19 @@ export function issueService(db: Db) {
if (issueData.projectId == null && workspaceSource.projectId) {
issueData.projectId = workspaceSource.projectId;
}
if (projectWorkspaceId == null && workspaceSource.projectWorkspaceId) {
// Workspace linkage is only inheritable inside the source project. A
// cross-project child (for example, a Paperclip ID issue created from
// a Paperclip App parent) must fall through to its own project's
// default workspaces, otherwise the inherited ids fail the
// project-match assertions below and the create is impossible without
// the caller naming the target workspaces explicitly.
const inheritsSourceProject =
issueData.projectId == null || issueData.projectId === workspaceSource.projectId;
if (inheritsSourceProject && projectWorkspaceId == null && workspaceSource.projectWorkspaceId) {
projectWorkspaceId = workspaceSource.projectWorkspaceId;
}
if (
inheritsSourceProject &&
isolatedWorkspacesEnabled &&
!hasExplicitExecutionWorkspaceOverride &&
workspaceSource.executionWorkspaceId
@@ -0,0 +1,160 @@
import {
createCipheriv,
diffieHellman,
generateKeyPairSync,
hkdfSync,
randomBytes,
type KeyObject,
} from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import {
createPaperclipIdGmailConnector,
GMAIL_CONNECTOR_SCOPES,
paperclipIdGmailConnectorConfigFromEnv,
PaperclipIdConnectorError,
type PaperclipIdGmailConnectorConfig,
} from "./paperclip-id-gmail-connector.js";
const instanceId = "inst_test";
const companyId = "company_test";
const subject = "user_test";
function rawPrivateKey(key: KeyObject): string {
const jwk = key.export({ format: "jwk" }) as { d?: string };
if (!jwk.d) throw new Error("missing private key bytes");
return jwk.d;
}
function config() {
const signing = generateKeyPairSync("ed25519");
const sealing = generateKeyPairSync("x25519");
return {
config: {
baseUrl: "https://id.example.test",
instanceId,
environment: "staging",
signPrivateKey: rawPrivateKey(signing.privateKey),
sealPrivateKey: rawPrivateKey(sealing.privateKey),
} satisfies PaperclipIdGmailConnectorConfig,
sealPublicKey: sealing.publicKey,
};
}
describe("Paperclip ID Gmail connector", () => {
it("starts a signed session with exact endpoint audience and scope contract", async () => {
const keys = config();
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).toMatchObject({
iss: instanceId,
aud: "https://id.example.test/api/connect/sessions",
sub: subject,
cid: companyId,
env: "staging",
op: "session",
ruri: "https://paperclip.example.test/api/tools/oauth/paperclip-id/callback",
rst: "state-1",
});
return Response.json({
authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=broker-state",
expiresAt: "2026-08-21T20:00:00.000Z",
scopes: [...GMAIL_CONNECTOR_SCOPES],
}, { status: 201 });
});
const connector = createPaperclipIdGmailConnector({ config: keys.config, request: request as typeof fetch });
await expect(connector.startAuthorization({
subject,
companyId,
returnUri: "https://paperclip.example.test/api/tools/oauth/paperclip-id/callback",
returnState: "state-1",
})).resolves.toMatchObject({ authorizationUrl: expect.stringContaining("accounts.google.com") });
});
it("opens an instance-sealed claim and verifies its user, company, and exact scopes", async () => {
const keys = config();
const credentials = {
v: 1 as const,
accessToken: "access-secret",
refreshToken: "refresh-secret",
tokenType: "Bearer",
accessTokenExpiresAt: "2026-08-21T20:00:00.000Z",
scopes: [...GMAIL_CONNECTOR_SCOPES],
subject,
companyId,
};
const sealed = seal(credentials, keys.sealPublicKey, "gmail-initial-tokens", keys.config);
const request = vi.fn(async () => Response.json({
claimId: "clm_test",
scopes: [...GMAIL_CONNECTOR_SCOPES],
sealed,
}));
const connector = createPaperclipIdGmailConnector({ config: keys.config, request: request as typeof fetch });
await expect(connector.claim({ subject, companyId, claimId: "clm_test" })).resolves.toEqual(credentials);
});
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({
error: "provider rejected access-secret refresh-secret",
}), { status: 502 }));
const connector = createPaperclipIdGmailConnector({ config: keys.config, request: request as typeof fetch });
const error = await connector.refresh({ subject, companyId, refreshToken: "refresh-secret" }).catch((caught) => caught);
expect(error).toBeInstanceOf(PaperclipIdConnectorError);
expect(String(error)).not.toContain("access-secret");
expect(String(error)).not.toContain("refresh-secret");
expect(request).toHaveBeenCalledOnce();
});
it("requires an all-or-nothing environment configuration and loopback for HTTP", () => {
expect(paperclipIdGmailConnectorConfigFromEnv({})).toBeNull();
expect(() => paperclipIdGmailConnectorConfigFromEnv({
PAPERCLIP_ID_CONNECTOR_INSTANCE_ID: instanceId,
})).toThrowError(/incomplete/);
expect(() => paperclipIdGmailConnectorConfigFromEnv({
PAPERCLIP_ID_CONNECTOR_INSTANCE_ID: instanceId,
PAPERCLIP_ID_CONNECTOR_SIGN_PRIVATE_KEY: "key",
PAPERCLIP_ID_CONNECTOR_SEAL_PRIVATE_KEY: "key",
PAPERCLIP_ID_CONNECTOR_ENVIRONMENT: "development",
PAPERCLIP_ID_CONNECTOR_BASE_URL: "http://id.example.test",
})).toThrowError(/HTTPS/);
});
});
function seal(
payload: unknown,
recipientPublicKey: KeyObject,
purpose: "gmail-initial-tokens" | "gmail-access-token",
configValue: PaperclipIdGmailConnectorConfig,
) {
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 key = Buffer.from(hkdfSync(
"sha256",
diffieHellman({ privateKey: ephemeral.privateKey, publicKey: recipientPublicKey }),
Buffer.concat([ephemeralRaw, recipientRaw]),
aad,
32,
));
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", key, iv);
cipher.setAAD(aad);
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final(), cipher.getAuthTag()]);
return {
v: 1,
alg: "X25519-HKDF-SHA256-A256GCM",
purpose,
epk: ephemeralJwk.x,
iv: iv.toString("base64url"),
ct: ciphertext.toString("base64url"),
};
}
@@ -0,0 +1,340 @@
import {
createDecipheriv,
createHash,
createPrivateKey,
createPublicKey,
diffieHellman,
hkdfSync,
randomUUID,
sign,
type KeyObject,
} from "node:crypto";
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 type PaperclipIdConnectorEnvironment = "development" | "staging" | "production";
export type PaperclipIdConnectorOperation = "session" | "claim" | "refresh" | "revoke";
export type PaperclipIdGmailConnectorConfig = {
baseUrl: string;
instanceId: string;
environment: PaperclipIdConnectorEnvironment;
signPrivateKey: string;
sealPrivateKey: string;
};
export type SealedGmailCredentials = {
v: 1;
accessToken: string;
refreshToken: string | null;
tokenType: string;
accessTokenExpiresAt: string;
scopes: string[];
subject: string;
companyId: string;
};
type SealedEnvelope = {
v: 1;
alg: "X25519-HKDF-SHA256-A256GCM";
purpose: "gmail-initial-tokens" | "gmail-access-token";
epk: string;
iv: string;
ct: string;
};
type ConnectorResponse = {
authorizationUrl?: unknown;
expiresAt?: unknown;
scopes?: unknown;
claimId?: unknown;
sealed?: unknown;
};
const ENDPOINTS: Record<PaperclipIdConnectorOperation, string> = {
session: "/api/connect/sessions",
claim: "/api/connect/claims",
refresh: "/api/connect/refresh",
revoke: "/api/connect/revoke",
};
const JWS_TYP = "paperclip-connector-request+jwt";
const SEAL_ALGORITHM = "X25519-HKDF-SHA256-A256GCM";
const AES_TAG_BYTES = 16;
const RAW_PRIVATE_KEY_BYTES = 32;
const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
const X25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b656e04220420", "hex");
const X25519_SPKI_PREFIX = Buffer.from("302a300506032b656e032100", "hex");
/** A stable, intentionally detail-free error for all remote broker failures. */
export class PaperclipIdConnectorError extends Error {
constructor(
message: string,
readonly code: string,
readonly status?: number,
) {
super(message);
this.name = "PaperclipIdConnectorError";
}
}
export function paperclipIdGmailConnectorConfigFromEnv(
env: NodeJS.ProcessEnv = process.env,
): PaperclipIdGmailConnectorConfig | null {
const instanceId = env.PAPERCLIP_ID_CONNECTOR_INSTANCE_ID?.trim();
const signPrivateKey = env.PAPERCLIP_ID_CONNECTOR_SIGN_PRIVATE_KEY?.trim();
const sealPrivateKey = env.PAPERCLIP_ID_CONNECTOR_SEAL_PRIVATE_KEY?.trim();
const environment = env.PAPERCLIP_ID_CONNECTOR_ENVIRONMENT?.trim();
const baseUrl = env.PAPERCLIP_ID_CONNECTOR_BASE_URL?.trim() || "https://id.paperclip.app";
const values = [instanceId, signPrivateKey, sealPrivateKey, environment];
if (values.every((value) => !value)) return null;
if (values.some((value) => !value)) {
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector configuration is incomplete", "CONNECTOR_CONFIG_INCOMPLETE");
}
if (environment !== "development" && environment !== "staging" && environment !== "production") {
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector environment is invalid", "CONNECTOR_CONFIG_INVALID");
}
const parsedBaseUrl = new URL(baseUrl);
if (parsedBaseUrl.protocol !== "https:" && !(parsedBaseUrl.protocol === "http:" && isLoopback(parsedBaseUrl.hostname))) {
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector URL must use HTTPS", "CONNECTOR_CONFIG_INVALID");
}
if (parsedBaseUrl.username || parsedBaseUrl.password || parsedBaseUrl.search || parsedBaseUrl.hash) {
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector URL is invalid", "CONNECTOR_CONFIG_INVALID");
}
parsedBaseUrl.pathname = parsedBaseUrl.pathname.replace(/\/$/, "");
return {
baseUrl: parsedBaseUrl.toString().replace(/\/$/, ""),
instanceId: instanceId!,
environment,
signPrivateKey: signPrivateKey!,
sealPrivateKey: sealPrivateKey!,
};
}
export function createPaperclipIdGmailConnector(input: {
config: PaperclipIdGmailConnectorConfig;
request?: typeof fetch;
now?: () => number;
}) {
const config = input.config;
const request = input.request ?? fetch;
const now = input.now ?? Date.now;
const signingKey = privateKey(config.signPrivateKey, "ed25519");
const sealKey = privateKey(config.sealPrivateKey, "x25519");
async function call(
operation: PaperclipIdConnectorOperation,
claims: { subject: string; companyId: string; returnUri?: string; returnState?: string; claimId?: string },
secret?: { field: "refreshToken" | "token"; value: string },
): Promise<ConnectorResponse> {
const endpoint = new URL(ENDPOINTS[operation], `${config.baseUrl}/`).toString();
const issuedAt = Math.floor(now() / 1000);
const payload: Record<string, unknown> = {
iss: config.instanceId,
aud: endpoint,
sub: claims.subject,
cid: claims.companyId,
env: config.environment,
op: operation,
iat: issuedAt,
exp: issuedAt + 60,
jti: randomUUID(),
};
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 (secret) payload.sh = await sha256Base64Url(secret.value);
const body = {
request: signRequest(payload, signingKey),
...(secret ? { [secret.field]: secret.value } : {}),
};
let response: Response;
try {
response = await request(endpoint, {
method: "POST",
headers: { "content-type": "application/json", accept: "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(15_000),
});
} catch {
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector is unavailable", "CONNECTOR_UNAVAILABLE");
}
if (operation === "revoke" && response.status === 204) return {};
if (!response.ok) {
throw new PaperclipIdConnectorError(
"Paperclip ID Gmail connector rejected the request",
response.status === 409 ? "REAUTHORIZATION_REQUIRED" : "CONNECTOR_REQUEST_FAILED",
response.status,
);
}
try {
return await response.json() as ConnectorResponse;
} catch {
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector returned an invalid response", "CONNECTOR_BAD_RESPONSE");
}
}
function openCredentials(
response: ConnectorResponse,
purpose: SealedEnvelope["purpose"],
subject: string,
companyId: string,
): SealedGmailCredentials {
const envelope = parseEnvelope(response.sealed, purpose);
const credentials = unseal(envelope, sealKey, config.instanceId, config.environment);
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)) {
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);
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)) {
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector returned an invalid scope set", "CONNECTOR_BAD_RESPONSE");
}
const authorizationUrl = new URL(response.authorizationUrl);
if (authorizationUrl.protocol !== "https:" || authorizationUrl.hostname !== "accounts.google.com") {
throw new PaperclipIdConnectorError("Paperclip ID Gmail connector returned an invalid authorization URL", "CONNECTOR_BAD_RESPONSE");
}
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 refresh(values: { subject: string; companyId: string; refreshToken: string }) {
return openCredentials(
await call("refresh", values, { field: "refreshToken", value: values.refreshToken }),
"gmail-access-token",
values.subject,
values.companyId,
);
},
async revoke(values: { subject: string; companyId: string; token: string }) {
await call("revoke", values, { field: "token", value: values.token });
},
};
}
export type PaperclipIdGmailConnector = ReturnType<typeof createPaperclipIdGmailConnector>;
function signRequest(payload: Record<string, unknown>, key: KeyObject): string {
const header = { alg: "EdDSA", typ: JWS_TYP };
const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(payload))}`;
return `${signingInput}.${sign(null, Buffer.from(signingInput, "utf8"), key).toString("base64url")}`;
}
function privateKey(value: string, curve: "ed25519" | "x25519"): KeyObject {
try {
let parsed: KeyObject;
if (value.includes("BEGIN PRIVATE KEY")) {
parsed = createPrivateKey(value);
} else {
const raw = Buffer.from(value, "base64url");
parsed = raw.length === RAW_PRIVATE_KEY_BYTES
? createPrivateKey({
key: Buffer.concat([curve === "ed25519" ? ED25519_PKCS8_PREFIX : X25519_PKCS8_PREFIX, raw]),
format: "der",
type: "pkcs8",
})
: createPrivateKey({ key: raw, format: "der", type: "pkcs8" });
}
if (parsed.asymmetricKeyType !== curve) throw new Error("wrong key type");
return parsed;
} catch {
throw new PaperclipIdConnectorError(`Paperclip ID ${curve} private key is invalid`, "CONNECTOR_CONFIG_INVALID");
}
}
function parseEnvelope(value: unknown, purpose: SealedEnvelope["purpose"]): SealedEnvelope {
if (!value || typeof value !== "object" || Array.isArray(value)) throw badEnvelope();
const candidate = value as Partial<SealedEnvelope>;
if (candidate.v !== 1 || candidate.alg !== SEAL_ALGORITHM || candidate.purpose !== purpose
|| typeof candidate.epk !== "string" || typeof candidate.iv !== "string" || typeof candidate.ct !== "string") {
throw badEnvelope();
}
return candidate as SealedEnvelope;
}
function unseal(
envelope: SealedEnvelope,
recipientPrivateKey: KeyObject,
instanceId: string,
environment: string,
): SealedGmailCredentials {
try {
const ephemeralRaw = Buffer.from(envelope.epk, "base64url");
if (ephemeralRaw.length !== 32) throw badEnvelope();
const ephemeralKey = createPublicKey({
key: Buffer.concat([X25519_SPKI_PREFIX, ephemeralRaw]),
format: "der",
type: "spki",
});
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 key = Buffer.from(hkdfSync(
"sha256",
diffieHellman({ privateKey: recipientPrivateKey, publicKey: ephemeralKey }),
Buffer.concat([ephemeralRaw, recipientRaw]),
aad,
32,
));
const iv = Buffer.from(envelope.iv, "base64url");
const combined = Buffer.from(envelope.ct, "base64url");
if (iv.length !== 12 || combined.length <= AES_TAG_BYTES) throw badEnvelope();
const decipher = createDecipheriv("aes-256-gcm", key, iv, { authTagLength: AES_TAG_BYTES });
decipher.setAAD(aad);
decipher.setAuthTag(combined.subarray(-AES_TAG_BYTES));
const plaintext = Buffer.concat([
decipher.update(combined.subarray(0, -AES_TAG_BYTES)),
decipher.final(),
]);
const parsed = JSON.parse(plaintext.toString("utf8")) as Partial<SealedGmailCredentials>;
if (parsed.v !== 1 || typeof parsed.accessToken !== "string" || parsed.accessToken.length === 0
|| !(parsed.refreshToken === null || typeof parsed.refreshToken === "string")
|| typeof parsed.tokenType !== "string" || typeof parsed.accessTokenExpiresAt !== "string"
|| !Array.isArray(parsed.scopes) || !parsed.scopes.every((scope) => typeof scope === "string")
|| typeof parsed.subject !== "string" || typeof parsed.companyId !== "string") {
throw badEnvelope();
}
return parsed as SealedGmailCredentials;
} catch (error) {
if (error instanceof PaperclipIdConnectorError) throw error;
throw badEnvelope();
}
}
function badEnvelope() {
return new PaperclipIdConnectorError("Paperclip ID Gmail connector returned an invalid sealed credential", "CONNECTOR_BAD_RESPONSE");
}
async function sha256Base64Url(value: string): Promise<string> {
return createHash("sha256").update(value, "utf8").digest("base64url");
}
function base64Url(value: string): string {
return Buffer.from(value, "utf8").toString("base64url");
}
function sameStringSet(value: unknown, expected: readonly string[]): boolean {
return Array.isArray(value)
&& value.every((item) => typeof item === "string")
&& value.length === expected.length
&& expected.every((item) => value.includes(item));
}
function isLoopback(hostname: string): boolean {
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
}
+746 -27
View File
@@ -151,6 +151,14 @@ import {
import { recordToolRuntimeAuditWriteFailure, TOOL_RUNTIME_AUDIT_WRITE_FAILURE_METRIC } from "./tool-runtime-metrics.js";
import { createToolRuntimeSupervisor, ToolRuntimeSupervisorError } from "./tool-runtime-supervisor.js";
import { listConnectionLifecycleEvents } from "./tool-connection-activity.js";
import { ComposioApiError, createComposioClient, type ComposioClient } from "./composio.js";
import { composioChildConfig, createComposioSessionManager } from "./composio-session-manager.js";
import {
createPaperclipIdGmailConnector,
GMAIL_CONNECTOR_SCOPES,
paperclipIdGmailConnectorConfigFromEnv,
type PaperclipIdGmailConnector,
} from "./paperclip-id-gmail-connector.js";
type ActorInfo = {
actorType?: "agent" | "user" | "system" | "plugin";
@@ -483,6 +491,10 @@ type ToolAccessServiceOptions = {
remoteHttpEndpointLookup?: RemoteHttpEndpointLookup;
/** Test seam for protocol fixtures. Production uses the DNS-pinned transport. */
remoteHttpRequest?: (url: string, init: RequestInit) => Promise<Response>;
/** Test seam for Composio without live vendor traffic. */
composioClientFactory?: (apiKey: string) => ComposioClient;
/** Test seam for the centrally registered Gmail OAuth broker. */
paperclipIdGmailConnector?: PaperclipIdGmailConnector | null;
};
type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
@@ -702,6 +714,7 @@ const APPROVED_STDIO_TEMPLATES: Record<string, {
};
const GOOGLE_SHEETS_GALLERY_KEY = "google-sheets";
const COMPOSIO_GALLERY_KEY = "composio";
const GOOGLE_SHEETS_TEMPLATE_ID = "paperclip.google-sheets";
const GOOGLE_SHEETS_ALLOWED_SPREADSHEET_IDS_ENV = "GOOGLE_SHEETS_ALLOWED_SPREADSHEET_IDS";
const CONNECTION_TOKEN_MINT_TOOL_NAME = "connection_token.mint";
@@ -795,6 +808,10 @@ function credentialFieldsFor(app: AppDefinition, methodKey?: string | null) {
}));
}
function credentialRefConfigPath(ref: { name: string }): string {
return ref.name.startsWith("credentials.") ? ref.name : `credentials.${ref.name}`;
}
export function normalizeConnectionMethodConfig(
method: ConnectionMethodDef,
configValues: Record<string, unknown> | undefined,
@@ -1684,6 +1701,12 @@ export function classifyRisk(tool: McpToolDescriptor, sourceTemplateKey?: string
return "read";
}
export function isGmailToolPermanentlyBlocked(tool: McpToolDescriptor): boolean {
const riskLevel = classifyRisk(tool, "gmail");
return verbMatches(tool.name, "send|trash|spam|delete|remove|destroy|execute|run")
|| (normalizedProviderToolName(tool.name).includes("label") && riskLevel !== "read");
}
function descriptorHash(tool: McpToolDescriptor, riskLevel: ToolRiskLevel): string {
return stableHash({
name: tool.name,
@@ -1717,13 +1740,24 @@ function isOAuthEndpointRejection(error: unknown): boolean {
function healthFailureHttpStatus(failure: { status: ToolConnectionHealthStatus; code: string }): number {
if (failure.status === "missing_secret") return 422;
if (failure.code === "composio_api_key_rejected") return 422;
if (failure.code.endsWith("_endpoint_rejected")) return 422;
return 502;
}
function sanitizeHttpFailure(error: unknown): { status: ToolConnectionHealthStatus; message: string; code: string } {
if (error instanceof ComposioApiError) {
return {
status: "error",
message: error.message,
code: error.status === 401 || error.status === 403 ? "composio_api_key_rejected" : "composio_request_failed",
};
}
if (error instanceof HttpError) {
const code = asRecord(error.details).code;
if (code === "composio_connected_account_inactive") {
return { status: "degraded", message: error.message, code };
}
if (typeof code === "string" && code.startsWith("remote_http_")) {
return { status: "error", message: error.message, code };
}
@@ -1800,8 +1834,19 @@ function readStdioTemplateId(config: Record<string, unknown>): string {
export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}) {
const secrets = secretService(db);
const composioSessions = createComposioSessionManager(db, {
composioClientFactory: options.composioClientFactory,
now: options.now,
});
const policySvc = toolAccessPolicyService(db);
const now = options.now ?? (() => new Date());
const gmailConnectorConfig = options.paperclipIdGmailConnector === undefined
? paperclipIdGmailConnectorConfigFromEnv()
: null;
const gmailConnector = options.paperclipIdGmailConnector
?? (gmailConnectorConfig
? createPaperclipIdGmailConnector({ config: gmailConnectorConfig, now: () => now().getTime() })
: null);
const runtimeSupervisor = createToolRuntimeSupervisor(db, options);
// These maps remove duplicate work inside one service instance. OAuth also
// uses the database refresh lease below as its cross-process boundary.
@@ -3530,10 +3575,10 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
eq(companySecretBindings.targetId, connection.id),
),
);
const bindings = [
const rawBindings = [
...connection.credentialRefs.map((ref) => ({
secretId: ref.secretId,
configPath: `credentials.${ref.name}`,
configPath: credentialRefConfigPath(ref),
projectionClass: "unclassified",
projectionAllowlistKey: null,
})),
@@ -3544,6 +3589,10 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
projectionAllowlistKey: ref.projectionAllowlistKey ?? null,
})),
];
const bindings = [...new Map(rawBindings.map((ref) => [
`${ref.secretId}:${ref.configPath}`,
ref,
])).values()];
if (bindings.length === 0) return;
await db.insert(companySecretBindings).values(bindings.map((ref) => ({
companyId: connection.companyId,
@@ -3672,11 +3721,25 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
connectionId: string,
companyId?: string,
actor?: ActorInfo,
removalOptions: { confirmComposioChildren?: boolean } = {},
): Promise<ToolConnectionRemovalResult> {
const connection = await getConnectionRow(connectionId, companyId);
const now = new Date();
const binding = actorBinding(actor);
if (isComposioConnection(connection)) {
const children = (await existingComposioChildren(connection)).filter((child) => child.status !== "archived");
if (children.length > 0 && removalOptions.confirmComposioChildren !== true) {
throw conflict("Deleting this Composio connection also removes its connected services. Confirm child removal to continue.", {
code: "composio_child_removal_confirmation_required",
childConnectionCount: children.length,
});
}
for (const child of children) {
await removeConnection(child.id, child.companyId, actor, { confirmComposioChildren: true });
}
}
// Grants are read before they are revoked: a retried removal must still see
// the credential refs of a grant an earlier pass already marked revoked.
const grantRows = await db
@@ -4016,11 +4079,12 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
const scope = credentialScope(connection);
for (const ref of connection.credentialRefs) {
let value: string;
const configPath = credentialRefConfigPath(ref);
try {
value = await secrets.resolveSecretValue(connection.companyId, ref.secretId, ref.version ?? "latest", {
consumerType: "tool_connection",
consumerId: connection.id,
configPath: `credentials.${ref.name}`,
configPath,
actorType: "system",
});
} catch (error) {
@@ -4059,12 +4123,20 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
return headers;
}
async function remoteTools(connection: typeof toolConnections.$inferSelect): Promise<McpToolDescriptor[]> {
const headers = { ...projectedConnectionHeaders(connection), ...await resolveCredentialHeaders(connection) };
async function remoteTools(
connection: typeof toolConnections.$inferSelect,
credentialHeaders?: Record<string, string>,
): Promise<McpToolDescriptor[]> {
const composioChild = composioChildConfig(connection);
const composioSession = composioChild ? await composioSessions.ensureSession(connection.id) : null;
const headers = composioSession?.headers
?? credentialHeaders
?? { ...projectedConnectionHeaders(connection), ...await resolveCredentialHeaders(connection) };
const endpoint = composioSession?.url ?? remoteEndpoint(connection.config);
// Pinned to the address the guard approved: `config.url` is operator-supplied,
// so a second DNS resolution here would reopen the rebinding window that
// PAP-17098 closed for the OAuth endpoints.
const response = await requestRemoteHttpEndpoint(new URL(remoteEndpoint(connection.config)), {
let response = await requestRemoteHttpEndpoint(new URL(endpoint), {
method: "POST",
// MCP Streamable HTTP requires advertising that we accept both a JSON body
// and an SSE stream; spec-compliant servers 406 without it (see mcp-http.ts).
@@ -4076,6 +4148,19 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
params: {},
}),
});
if (response.status === 401 && composioChild) {
const refreshed = await composioSessions.ensureSession(connection.id, { force: true });
response = await requestRemoteHttpEndpoint(new URL(refreshed.url), {
method: "POST",
headers: mcpHttpRequestHeaders(refreshed.headers),
body: JSON.stringify({
jsonrpc: "2.0",
id: "paperclip-catalog-refresh-retry",
method: "tools/list",
params: {},
}),
});
}
if (!response.ok) {
const authenticate = response.headers.get("www-authenticate") ?? "";
if (response.status === 401 && /bearer|oauth|authorization/i.test(authenticate)) {
@@ -4141,8 +4226,293 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
}));
}
async function discoverTools(connection: typeof toolConnections.$inferSelect): Promise<McpToolDescriptor[]> {
if (connection.transport === "mcp_remote") return remoteTools(connection);
function isComposioConnection(connection: typeof toolConnections.$inferSelect): boolean {
return asRecord(connection.config).sourceTemplateKey === COMPOSIO_GALLERY_KEY;
}
async function composioClientForParent(parent: typeof toolConnections.$inferSelect) {
if (!isComposioConnection(parent) || parent.transport !== "rest_api") {
throw unprocessable("This connection is not a parent Composio connection.", { code: "not_composio_parent" });
}
const headers = await resolveCredentialHeaders(parent);
const apiKey = Object.entries(headers).find(([name]) => name.toLowerCase() === "x-api-key")?.[1];
if (!apiKey) throw unprocessable("The Composio API key secret is missing.", { code: "secret_missing" });
return options.composioClientFactory?.(apiKey) ?? createComposioClient({ apiKey });
}
async function existingComposioChildren(parent: typeof toolConnections.$inferSelect) {
const rows = await db.select().from(toolConnections).where(and(
eq(toolConnections.companyId, parent.companyId),
eq(toolConnections.applicationId, parent.applicationId),
));
return rows.filter((row) => composioChildConfig(row)?.parentConnectionId === parent.id);
}
async function assertComposioConnectedAccountActive(child: typeof toolConnections.$inferSelect) {
const childConfig = composioChildConfig(child);
if (!childConfig) return;
const parent = await getConnectionRow(childConfig.parentConnectionId, child.companyId);
const client = await composioClientForParent(parent);
const accounts = await client.listConnectedAccounts({
toolkitSlugs: [childConfig.toolkitSlug],
userIds: [`paperclip:${child.companyId}`],
limit: 100,
});
const account = childConfig.connectedAccountId
? accounts.items.find((candidate) => candidate.id === childConfig.connectedAccountId)
: accounts.items.find((candidate) => candidate.toolkit.slug === childConfig.toolkitSlug);
if (account?.status.toUpperCase() === "ACTIVE") return;
const status = account?.status.trim().toUpperCase() || "MISSING";
throw unprocessable(
`Composio reports the ${childConfig.toolkitSlug} connected account as ${status}. Reconnect it in Composio.`,
{ code: "composio_connected_account_inactive", connectedAccountStatus: status },
);
}
async function disableComposioChildren(parent: typeof toolConnections.$inferSelect) {
const children = await existingComposioChildren(parent);
for (const child of children) {
if (child.status === "archived") continue;
const config = asRecord(child.config);
await db.update(toolConnections).set({
enabled: false,
config: child.enabled ? { ...config, disabledByComposioParent: true } : config,
updatedAt: now(),
}).where(eq(toolConnections.id, child.id));
}
}
async function restoreComposioChildren(parent: typeof toolConnections.$inferSelect) {
const children = await existingComposioChildren(parent);
const restorable = children.filter((child) =>
child.status !== "archived" && asRecord(child.config).disabledByComposioParent === true,
);
if (restorable.length === 0) return;
let accounts: Awaited<ReturnType<ComposioClient["listConnectedAccounts"]>>["items"] = [];
try {
const client = await composioClientForParent(parent);
accounts = (await client.listConnectedAccounts({
userIds: [`paperclip:${parent.companyId}`],
limit: 1000,
})).items;
} catch {
// Fail closed while Composio is unavailable. A later resume or reconnect
// can retry without exposing a child whose account state is unknown.
return;
}
for (const child of restorable) {
const childConfig = composioChildConfig(child)!;
const account = childConfig.connectedAccountId
? accounts.find((candidate) => candidate.id === childConfig.connectedAccountId)
: accounts.find((candidate) => candidate.toolkit.slug === childConfig.toolkitSlug);
const config = { ...asRecord(child.config) };
delete config.disabledByComposioParent;
const active = account?.status.toUpperCase() === "ACTIVE";
await db.update(toolConnections).set({
enabled: active,
config: active ? config : { ...config, disabledByComposioParent: true },
healthStatus: active ? "unchecked" : "degraded",
healthMessage: active
? null
: `Composio reports the ${childConfig.toolkitSlug} connected account as ${account?.status.toUpperCase() ?? "MISSING"}. Reconnect it in Composio.`,
updatedAt: now(),
}).where(eq(toolConnections.id, child.id));
}
}
async function syncComposioChild(
parent: typeof toolConnections.$inferSelect,
account: { id: string; status: string; toolkit: { slug: string } },
toolkitName: string,
actor?: ActorInfo,
) {
if (account.status.toUpperCase() !== "ACTIVE") return null;
const children = await existingComposioChildren(parent);
const existing = children.find((candidate) => {
const config = composioChildConfig(candidate);
return config?.toolkitSlug === account.toolkit.slug && candidate.status !== "archived";
});
if (existing) {
const config = composioChildConfig(existing)!;
if (config.connectedAccountId !== account.id) {
const nextConfig = { ...existing.config, connectedAccountId: account.id };
const [updated] = await db.update(toolConnections).set({
config: nextConfig,
transportConfig: { ...existing.transportConfig, connectedAccountId: account.id, composioSessions: {} },
updatedAt: now(),
}).where(eq(toolConnections.id, existing.id)).returning();
return updated;
}
return existing;
}
const connectionId = randomUUID();
const binding = actorBinding(actor);
const config = {
provider: "composio",
parentConnectionId: parent.id,
toolkitSlug: account.toolkit.slug,
connectedAccountId: account.id,
};
const [created] = await db.insert(toolConnections).values({
id: connectionId,
companyId: parent.companyId,
applicationId: parent.applicationId,
name: `${toolkitName} (via Composio)`,
uid: connectionUid(`composio:${parent.id}`, account.toolkit.slug, connectionId),
connectionKind: "managed",
ownership: parent.ownership,
transport: "mcp_remote",
authKind: "none",
credentialPolicy: "shared",
status: "active",
enabled: true,
config,
transportConfig: { ...config, composioSessions: {} },
credentialRefs: [],
credentialSecretRefs: [],
createdByAgentId: binding.actorType === "agent" ? binding.actorId : null,
createdByUserId: binding.actorType === "user" ? binding.actorId : null,
}).returning();
if (!created) throw new Error("Failed to create Composio toolkit connection");
await ensureDefaultOrganizationGrant(created);
await syncCredentialBindings(created);
await ensureRuntimeSlot(created);
await audit({
companyId: created.companyId,
connectionId: created.id,
action: "composio.child_created",
outcome: "success",
actor,
details: { parentConnectionId: parent.id, toolkitSlug: account.toolkit.slug },
});
return created;
}
async function syncComposioToolkit(
parent: typeof toolConnections.$inferSelect,
toolkitSlug: string,
actor?: ActorInfo,
) {
const client = await composioClientForParent(parent);
const userId = `paperclip:${parent.companyId}`;
const [toolkits, accounts] = await Promise.all([
client.listToolkits({ limit: 1000 }),
client.listConnectedAccounts({ toolkitSlugs: [toolkitSlug], userIds: [userId], limit: 100 }),
]);
const toolkit = toolkits.items.find((item) => item.slug === toolkitSlug);
if (!toolkit) throw notFound("Composio toolkit not found");
const account = accounts.items.find((item) => item.toolkit.slug === toolkitSlug && item.status.toUpperCase() === "ACTIVE")
?? accounts.items.find((item) => item.toolkit.slug === toolkitSlug)
?? null;
const child = account ? await syncComposioChild(parent, account, toolkit.name, actor) : null;
if (child) await refreshCatalog(child.id, actor, { enableAllByDefault: true });
return { toolkit, account, child: child ? toConnection(await getConnectionRow(child.id)) : null };
}
async function validateComposioConnection(connection: typeof toolConnections.$inferSelect) {
const client = await composioClientForParent(connection);
await client.validateApiKey();
}
async function listComposioServices(parentConnectionId: string, actor?: ActorInfo) {
const parent = await getConnectionRow(parentConnectionId);
const client = await composioClientForParent(parent);
const userId = `paperclip:${parent.companyId}`;
const [toolkits, accounts] = await Promise.all([
client.listToolkits({ limit: 1000 }),
client.listConnectedAccounts({ userIds: [userId], limit: 1000 }),
]);
const children = await existingComposioChildren(parent);
const childByToolkit = new Map(children.filter((child) => child.status !== "archived").map((child) => [
composioChildConfig(child)?.toolkitSlug,
child,
]));
const services = [];
for (const toolkit of toolkits.items) {
const toolkitAccounts = accounts.items.filter((account) => account.toolkit.slug === toolkit.slug);
const account = toolkitAccounts.find((candidate) => candidate.status.toUpperCase() === "ACTIVE")
?? toolkitAccounts[0]
?? null;
let child = childByToolkit.get(toolkit.slug) ?? null;
if (account?.status.toUpperCase() === "ACTIVE" && !child) {
child = await syncComposioChild(parent, account, toolkit.name, actor);
if (child) await refreshCatalog(child.id, actor, { enableAllByDefault: true });
}
services.push({
toolkit,
status: account?.status.toUpperCase() === "ACTIVE"
? "connected"
: account ? "pending" : "not_connected",
connectedAccountId: account?.id ?? null,
connectedAccountStatus: account?.status ?? null,
childConnectionId: child?.id ?? null,
});
}
return { parentConnectionId: parent.id, userId, services };
}
async function startComposioServiceConnect(
parentConnectionId: string,
toolkitSlug: string,
input: { authConfigId?: string; callbackUrl?: string },
) {
const parent = await getConnectionRow(parentConnectionId);
const client = await composioClientForParent(parent);
let authConfigId = input.authConfigId?.trim();
if (!authConfigId) {
const configs = await client.listAuthConfigs({ toolkitSlugs: [toolkitSlug], showDisabled: false, limit: 100 });
authConfigId = configs.items.find((config) => config.toolkit.slug === toolkitSlug && config.status !== "DISABLED")?.id;
}
if (!authConfigId) throw unprocessable("This Composio toolkit has no enabled auth configuration.", { code: "composio_auth_config_missing" });
const link = await client.createConnectLink({
authConfigId,
userId: `paperclip:${parent.companyId}`,
alias: `paperclip-${parent.companyId}-${toolkitSlug}`,
...(input.callbackUrl ? { callbackUrl: input.callbackUrl } : {}),
});
return { toolkitSlug, authConfigId, ...link };
}
async function disconnectComposioService(parentConnectionId: string, toolkitSlug: string, actor?: ActorInfo) {
const parent = await getConnectionRow(parentConnectionId);
const client = await composioClientForParent(parent);
const accounts = await client.listConnectedAccounts({
toolkitSlugs: [toolkitSlug],
userIds: [`paperclip:${parent.companyId}`],
limit: 100,
});
for (const account of accounts.items.filter((candidate) => candidate.toolkit.slug === toolkitSlug)) {
await client.deleteConnectedAccount(account.id);
}
const children = await existingComposioChildren(parent);
const removedChildIds: string[] = [];
for (const child of children) {
if (composioChildConfig(child)?.toolkitSlug !== toolkitSlug || child.status === "archived") continue;
await removeConnection(child.id, child.companyId, actor);
removedChildIds.push(child.id);
}
await audit({
companyId: parent.companyId,
connectionId: parent.id,
action: "composio.service_disconnected",
outcome: "success",
actor,
details: { toolkitSlug, connectedAccountCount: accounts.items.length, removedChildCount: removedChildIds.length },
});
return { toolkitSlug, disconnectedAccountIds: accounts.items.map((account) => account.id), removedChildIds };
}
async function discoverTools(
connection: typeof toolConnections.$inferSelect,
credentialHeaders?: Record<string, string>,
): Promise<McpToolDescriptor[]> {
if (connection.transport === "mcp_remote") return remoteTools(connection, credentialHeaders);
if (isComposioConnection(connection)) {
await validateComposioConnection(connection);
return [];
}
await resolveCredentialHeaders(connection);
return localTools(connection);
}
@@ -4178,14 +4548,23 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
const connection = await getConnectionRow(connectionId);
try {
if (connection.transport === "mcp_remote") {
await assertComposioConnectedAccountActive(connection);
await remoteTools(connection);
} else if (isComposioConnection(connection)) {
await validateComposioConnection(connection);
} else {
await resolveCredentialHeaders(connection);
await stdioTemplateId(connection.companyId, connection.config);
}
const updated = await updateConnectionHealth(connection, "ok", connection.transport === "local_stdio"
? "Approved stdio template is ready."
: "Remote MCP server responded to tools/list.");
const updated = await updateConnectionHealth(
connection,
"ok",
isComposioConnection(connection)
? "Composio accepted the API key and returned its toolkits."
: connection.transport === "local_stdio"
? "Approved stdio template is ready."
: "Remote MCP server responded to tools/list.",
);
const runtimeSlot = await ensureRuntimeSlot(updated);
await audit({
companyId: connection.companyId,
@@ -4222,13 +4601,17 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
async function refreshCatalog(
connectionId: string,
actor?: ActorInfo,
refreshOptions: { enableAllByDefault?: boolean; restoreDraftDefaults?: boolean } = {},
refreshOptions: {
enableAllByDefault?: boolean;
restoreDraftDefaults?: boolean;
credentialHeaders?: Record<string, string>;
} = {},
): Promise<ToolCatalogRefreshResult> {
const connection = await getConnectionRow(connectionId);
const refreshedAt = now();
let descriptors: McpToolDescriptor[];
try {
descriptors = await discoverTools(connection);
descriptors = await discoverTools(connection, refreshOptions.credentialHeaders);
} catch (error) {
const failure = sanitizeHttpFailure(error);
const updated = await updateConnectionHealth(connection, failure.status, failure.message);
@@ -4270,14 +4653,17 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
&& (!existing || changed)
&& existing?.status !== "disabled"
&& (!safeDefault || riskLevel !== "read");
const status = shouldQuarantine
? "quarantined"
: existing?.status === "disabled"
? "disabled"
: quarantineOnRefresh && existing?.status === "quarantined"
? "quarantined"
: "active";
if (shouldQuarantine) quarantinedCount += 1;
const gmailPermanentlyBlocked = sourceTemplateKey === "gmail" && isGmailToolPermanentlyBlocked(descriptor);
const status = gmailPermanentlyBlocked
? "disabled"
: shouldQuarantine
? "quarantined"
: existing?.status === "disabled"
? "disabled"
: quarantineOnRefresh && existing?.status === "quarantined"
? "quarantined"
: "active";
if (shouldQuarantine && !gmailPermanentlyBlocked) quarantinedCount += 1;
if (existing) {
const [updated] = await db
@@ -6530,6 +6916,10 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
throw badRequest("Choose a connection method for this app");
}
const method = galleryEntry ? connectionMethodFor(galleryEntry, input.connectionMethodKey) : null;
const requestedGrantKind = input.grantKind ?? "organization";
if (method?.grantKinds && !method.grantKinds.includes(requestedGrantKind)) {
throw badRequest(`${galleryEntry?.name ?? "This app"} supports only ${method.grantKinds.join(" or ")} credentials`);
}
const transport = method?.transport ?? "mcp_remote";
const normalizedMethodConfig = galleryEntry?.slug === GOOGLE_SHEETS_GALLERY_KEY || !method
? null
@@ -6550,6 +6940,15 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
...(galleryEntry.slug === "posthog" ? { safeDefault: true } : {}),
}
: { ...baseConfig, quarantineNewEntries: false, unverifiedServer: true };
if (method?.oauthStrategy === "paperclip_id_connector") {
config.oauth = {
strategy: method.oauthStrategy,
provider: "gmail",
resource: method.defaults?.serverUrl,
scopes: [...GMAIL_CONNECTOR_SCOPES],
};
config.quarantineNewEntries = true;
}
// A pasted URL may arrive with a client the operator preregistered in the
// provider's own console, because that authorization server supports neither
// CIMD nor dynamic registration. Record the client id now; the secret becomes
@@ -6812,8 +7211,9 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
};
}
let health: ToolConnectionHealthCheckResult;
try {
await checkConnectionHealth(connectionRow.id, actor);
health = await checkConnectionHealth(connectionRow.id, actor);
} catch (error) {
if (!galleryEntry && error instanceof HttpError && asRecord(error.details).code === "oauth_challenge") {
const [oauthConnection] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionRow.id));
@@ -6851,6 +7251,17 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
}
throw error;
}
if (galleryEntry?.slug === COMPOSIO_GALLERY_KEY) {
const [application] = await db.select().from(toolApplications).where(eq(toolApplications.id, applicationRow.id));
return {
connectionId: health.connection.id,
application: toApplication(application),
connection: health.connection,
catalog: [],
actions: { readOnly: [], canMakeChanges: [] },
suggestedDefaults: recommendedDefaultsForApp(galleryEntry, method?.key),
};
}
const restoreDraftDefaults = Boolean(revivedConnectionPrevious);
const refresh = await refreshCatalog(connectionRow.id, actor, {
enableAllByDefault: restoreDraftDefaults,
@@ -7300,6 +7711,9 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
.returning();
await syncCredentialBindings(updated);
const health = await checkConnectionHealth(updated.id, actor);
if (isComposioConnection(updated) && updated.enabled && updated.status === "active") {
await restoreComposioChildren(updated);
}
const catalogBefore = await db
.select({ id: toolCatalogEntries.id, riskLevel: toolCatalogEntries.riskLevel })
.from(toolCatalogEntries)
@@ -7335,6 +7749,66 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
const sourceTemplateKey = typeof connection.config.sourceTemplateKey === "string" ? connection.config.sourceTemplateKey : null;
const galleryEntry = sourceTemplateKey ? getConnectableAppDefinition(sourceTemplateKey) : null;
assertOAuthRedirectConstraints(galleryEntry, input.redirectUri);
const galleryMethod = galleryEntry ? connectionMethodForConnection(galleryEntry, connection) : null;
if (galleryMethod?.oauthStrategy === "paperclip_id_connector") {
if (!gmailConnector) {
throw unprocessable("Gmail connections are not available on this Paperclip instance yet", {
code: "paperclip_id_connector_unavailable",
});
}
const binding = actorBinding(input.actor);
if (!binding.actorType || !binding.actorId) {
throw forbidden("Gmail sign-in requires an authenticated actor");
}
const subjectUserId = input.subjectUserId ?? (binding.actorType === "user" ? binding.actorId : null);
if (!subjectUserId) {
throw forbidden("Agent-started Gmail sign-in requires an authorized user subject");
}
if (binding.actorType === "user" && subjectUserId !== binding.actorId) {
throw forbidden("Board users may only authorize their own Gmail identity");
}
await db.delete(toolOauthStates).where(lt(toolOauthStates.expiresAt, now()));
const state = randomOauthToken();
const returnUri = new URL(input.redirectUri);
returnUri.pathname = "/api/tools/oauth/paperclip-id/callback";
returnUri.search = "";
returnUri.hash = "";
const session = await gmailConnector.startAuthorization({
subject: subjectUserId,
companyId,
returnUri: returnUri.toString(),
returnState: state,
});
const remoteExpiry = new Date(session.expiresAt);
const expiresAt = Number.isFinite(remoteExpiry.getTime())
? new Date(Math.min(remoteExpiry.getTime(), now().getTime() + 10 * 60 * 1000))
: new Date(now().getTime() + 10 * 60 * 1000);
await db.insert(toolOauthStates).values({
state,
companyId,
connectionId: connection.id,
// Paperclip ID owns PKCE for this flow. The local state row remains the
// single-use browser correlator and never stores broker token material.
codeVerifier: "paperclip-id-connector",
createdByActorType: binding.actorType,
createdByActorId: binding.actorId,
createdBySessionId: binding.sessionId,
subjectUserId,
requestedScopes: [...GMAIL_CONNECTOR_SCOPES],
returnTo: input.returnTo,
issueId: input.issueId,
expiresAt,
});
return {
connectionId: connection.id,
provider: "gmail",
authorizationUrl: session.authorizationUrl,
expiresAt: expiresAt.toISOString(),
issuer: "https://accounts.google.com",
resource: galleryMethod.defaults?.serverUrl ?? null,
registrationSource: null,
};
}
const endpoints = await oauthEndpointsForConnection(connection, null, input.redirectUri);
if (endpoints.grantType === "client_credentials") {
throw unprocessable("This app uses shared machine credentials and does not need browser sign in");
@@ -7613,6 +8087,160 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
));
}
async function completePaperclipIdGmailCallback(input: {
state: string;
claimId?: string | null;
error?: string | null;
actor?: ActorInfo;
}): Promise<ConnectToolAppResult> {
const stateRow = await consumeOAuthState(input.state, input.actor);
if (input.error) {
await rejectPendingOAuthInteraction(stateRow, input.actor);
throw new HttpError(400, "Google authorization did not complete. Start a new Gmail connection to try again.", {
code: input.error === "access_denied" ? "oauth_authorization_denied" : "paperclip_id_connector_failed",
});
}
if (!input.claimId) throw badRequest("Gmail callback is missing a claim identifier");
if (!gmailConnector) {
throw unprocessable("Gmail connections are not available on this Paperclip instance yet", {
code: "paperclip_id_connector_unavailable",
});
}
let connection = await getConnectionRow(stateRow.connectionId, stateRow.companyId);
const sourceTemplateKey = typeof connection.config.sourceTemplateKey === "string" ? connection.config.sourceTemplateKey : null;
const galleryEntry = sourceTemplateKey ? getConnectableAppDefinition(sourceTemplateKey) : null;
const method = galleryEntry ? connectionMethodForConnection(galleryEntry, connection) : null;
if (method?.oauthStrategy !== "paperclip_id_connector" || !stateRow.subjectUserId) {
throw badRequest("OAuth state does not belong to a Gmail connector flow");
}
const credentials = await gmailConnector.claim({
subject: stateRow.subjectUserId,
companyId: stateRow.companyId,
claimId: input.claimId,
});
if (!credentials.refreshToken) {
throw unprocessable("Google did not return offline access. Reconnect Gmail and grant both requested scopes.", {
code: "oauth_refresh_missing",
});
}
const [membership] = await db.select({ id: companyMemberships.id }).from(companyMemberships).where(and(
eq(companyMemberships.companyId, connection.companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, stateRow.subjectUserId),
eq(companyMemberships.status, "active"),
)).limit(1);
if (!membership) {
throw forbidden("Your company membership is no longer active. Restore access before you connect Gmail again.");
}
const [existingUserGrant] = await db.select().from(connectionGrants).where(and(
eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
eq(connectionGrants.kind, "user"),
eq(connectionGrants.subjectUserId, stateRow.subjectUserId),
)).limit(1);
const existingRefs = existingUserGrant?.credentialSecretRefs ?? [];
const accessRef = await createOrRotateOAuthSecret({
companyId: connection.companyId,
connection,
configPath: "oauth.access_token",
label: "Gmail access token",
value: credentials.accessToken,
actor: input.actor,
existingRefs,
ownerUserId: stateRow.subjectUserId,
});
const refreshRef = await createOrRotateOAuthSecret({
companyId: connection.companyId,
connection,
configPath: "oauth.refresh_token",
label: "Gmail refresh token",
value: credentials.refreshToken,
actor: input.actor,
existingRefs,
ownerUserId: stateRow.subjectUserId,
});
const credentialSecretRefs = [
...existingRefs.filter((ref) => ref.configPath !== "oauth.access_token" && ref.configPath !== "oauth.refresh_token"),
accessRef,
refreshRef,
];
const grantValues = {
providerTenant: {
name: "Gmail",
externalId: credentials.subject,
oauth: {
strategy: "paperclip_id_connector",
accessTokenExpiresAt: credentials.accessTokenExpiresAt,
scopes: credentials.scopes,
tokenType: credentials.tokenType,
},
},
credentialSecretRefs,
status: "active" as const,
revokedAt: null,
revokedByAgentId: null,
revokedByUserId: null,
updatedAt: now(),
};
if (existingUserGrant) {
await db.update(connectionGrants).set(grantValues).where(eq(connectionGrants.id, existingUserGrant.id));
} else {
await db.insert(connectionGrants).values({
companyId: connection.companyId,
connectionId: connection.id,
kind: "user",
subjectUserId: stateRow.subjectUserId,
...grantValues,
isDefault: false,
createdByUserId: stateRow.subjectUserId,
});
}
const nextConfig = {
...connection.config,
oauth: {
...oauthConfig(connection),
strategy: "paperclip_id_connector",
provider: "gmail",
resource: method.defaults?.serverUrl,
scopes: [...GMAIL_CONNECTOR_SCOPES],
},
};
[connection] = await db.update(toolConnections).set({
status: "active",
enabled: true,
authKind: "oauth",
config: nextConfig,
transportConfig: nextConfig,
updatedAt: now(),
}).where(eq(toolConnections.id, connection.id)).returning();
await db.update(toolApplications).set({ status: "active", updatedAt: now() }).where(eq(toolApplications.id, connection.applicationId));
await syncCredentialBindings(connection, credentialSecretRefs);
if (stateRow.interactionId) {
await db.update(issueThreadInteractions).set({
status: "accepted",
result: { version: 1, outcome: "accepted" },
resolvedByUserId: stateRow.subjectUserId,
resolvedAt: now(),
updatedAt: now(),
}).where(eq(issueThreadInteractions.id, stateRow.interactionId));
}
const refresh = await refreshCatalog(connection.id, input.actor, {
enableAllByDefault: false,
credentialHeaders: { Authorization: `Bearer ${credentials.accessToken}` },
});
const [application] = await db.select().from(toolApplications).where(eq(toolApplications.id, connection.applicationId));
return {
connectionId: connection.id,
application: toApplication(application),
connection: refresh.connection,
catalog: refresh.catalog,
actions: groupedActions(refresh.catalog),
suggestedDefaults: recommendedDefaultsForApp(galleryEntry!, method.key),
auth: null,
};
}
async function completeOAuthCallback(input: {
state: string;
code?: string | null;
@@ -7970,6 +8598,8 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
peekOAuthState,
completePaperclipIdGmailCallback,
completeOAuthCallback,
listExamples: async (companyId: string): Promise<ToolExampleSummary[]> => {
@@ -8244,6 +8874,17 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
return connections;
},
listComposioServices,
startComposioServiceConnect,
pollComposioService: async (parentConnectionId: string, toolkitSlug: string, actor?: ActorInfo) => {
const parent = await getConnectionRow(parentConnectionId);
return syncComposioToolkit(parent, toolkitSlug, actor);
},
disconnectComposioService,
createConnection: async (companyId: string, input: CreateToolConnection, actor?: ActorInfo): Promise<ToolConnection> => {
let applicationId = input.applicationId;
let applicationNamespace = input.applicationName ?? input.name;
@@ -8300,6 +8941,10 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
await ensureDefaultOrganizationGrant(row);
await syncCredentialBindings(row);
await ensureRuntimeSlot(row);
if (isComposioConnection(row) && (input.enabled !== undefined || input.status !== undefined)) {
if (!row.enabled || row.status !== "active") await disableComposioChildren(row);
else await restoreComposioChildren(row);
}
return toConnection(row);
},
@@ -8610,6 +9255,43 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
revokeConnectionGrant: async (idOrUid: string, grantId: string, actor?: ActorInfo) => {
const connection = await getConnectionRow(idOrUid);
const binding = actorBinding(actor);
const [currentGrant] = await db.select().from(connectionGrants).where(and(
eq(connectionGrants.id, grantId),
eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
)).limit(1);
if (!currentGrant) throw notFound("Connection grant not found");
let providerRevocation = "not_applicable";
if (oauthConfig(connection).strategy === "paperclip_id_connector" && currentGrant.subjectUserId && gmailConnector) {
const tokenRef = currentGrant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")
?? currentGrant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.access_token");
if (tokenRef) {
try {
const token = await secrets.resolveSecretValue(
connection.companyId,
tokenRef.secretId,
tokenRef.versionSelector ?? "latest",
{
consumerType: "tool_connection",
consumerId: connection.id,
configPath: tokenRef.configPath,
actorType: binding.actorType ?? "system",
actorId: binding.actorId,
},
);
await gmailConnector.revoke({
subject: currentGrant.subjectUserId,
companyId: connection.companyId,
token,
});
providerRevocation = "success";
} catch {
// Local revocation is authoritative for Paperclip and must not be
// rolled back because Google or the broker is temporarily offline.
providerRevocation = "failed";
}
}
}
const grant = await db.transaction(async (tx) => {
const removedDelegations = await tx.delete(connectionGrantDelegations).where(and(
eq(connectionGrantDelegations.companyId, connection.companyId),
@@ -8651,7 +9333,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
action: "connection_grant.revoked",
outcome: "success",
reasonCode: "grant_revoked",
details: { grantId: grant.id, kind: grant.kind },
details: { grantId: grant.id, kind: grant.kind, providerRevocation },
});
return grant;
},
@@ -8730,10 +9412,43 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
eq(toolConnectionInstalls.connectionId, connection.id),
));
const existingKeys = new Set(existing.map((install) => `${install.targetType}:${install.targetId}`));
const removeIds = existing
.filter((install) => !requested.has(`${install.targetType}:${install.targetId}`))
.map((install) => install.id);
if (removeIds.length > 0) await tx.delete(toolConnectionInstalls).where(inArray(toolConnectionInstalls.id, removeIds));
const removals = existing
.filter((install) => !requested.has(`${install.targetType}:${install.targetId}`));
const removeIds = removals.map((install) => install.id);
if (removeIds.length > 0) {
await tx.delete(toolConnectionInstalls).where(inArray(toolConnectionInstalls.id, removeIds));
// Uninstalling must also drop the binding this path created. Installing
// writes both an install row and a profile binding, so deleting only the
// install row leaves a binding that no surface can see or remove. The
// install row is the reach gate (`mintConnectionTokenForAgent` fails with
// `installation_required`, and the heartbeat only hands over installed
// connections), so a stale binding grants no reach on its own — but it
// still makes `finishApp`, which rebuilds `access` from the bindings,
// read a target the operator already removed.
//
// Only bindings tagged `source: "tool_connection_install"` are removed.
// A binding the operator authored through the access model carries a
// different source and must survive an uninstall.
const [installProfile] = await tx
.select({ id: toolProfiles.id })
.from(toolProfiles)
.where(and(
eq(toolProfiles.companyId, connection.companyId),
eq(toolProfiles.profileKey, `app:${connection.id}`),
))
.limit(1);
if (installProfile) {
for (const install of removals) {
await tx.delete(toolProfileBindings).where(and(
eq(toolProfileBindings.companyId, connection.companyId),
eq(toolProfileBindings.profileId, installProfile.id),
eq(toolProfileBindings.targetType, install.targetType),
eq(toolProfileBindings.targetId, install.targetId),
sql`${toolProfileBindings.metadata}->>'source' = 'tool_connection_install'`,
));
}
}
}
const additions = [...requested.entries()].filter(([key]) => !existingKeys.has(key)).map(([, install]) => install);
if (additions.length > 0) {
await tx.insert(toolConnectionInstalls).values(additions.map((install) => ({
@@ -8823,6 +9538,10 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
.returning();
await syncCredentialBindings(row);
await ensureRuntimeSlot(row);
if (isComposioConnection(row)) {
if (row.enabled) await restoreComposioChildren(row);
else await disableComposioChildren(row);
}
return toConnection(row);
},
+163 -5
View File
@@ -71,6 +71,14 @@ import {
type ToolRuntimeSlotView,
} from "./tool-runtime-supervisor.js";
import { recordToolRuntimeAuditWriteFailure } from "./tool-runtime-metrics.js";
import { composioChildConfig, createComposioSessionManager } from "./composio-session-manager.js";
import type { ComposioClient } from "./composio.js";
import {
createPaperclipIdGmailConnector,
paperclipIdGmailConnectorConfigFromEnv,
PaperclipIdConnectorError,
type PaperclipIdGmailConnector,
} from "./paperclip-id-gmail-connector.js";
import {
canonicalToolArguments,
readSignedToolArgumentsPayload,
@@ -784,6 +792,10 @@ export function createToolGatewayService(
toolActionSigningSecret?: string;
/** Test seam for deterministic remote MCP protocol fixtures. */
remoteHttpRequest?: (url: string, init: RequestInit) => Promise<Response>;
/** Test seam for Composio session creation without vendor traffic. */
composioClientFactory?: (apiKey: string) => ComposioClient;
/** Test seam for refreshing personal Gmail grants. */
paperclipIdGmailConnector?: PaperclipIdGmailConnector | null;
mcpGatewayProtocolLimits?: Partial<{
authFailures: Partial<McpGatewayRateLimitConfig>;
gatewayRequests: Partial<McpGatewayRateLimitConfig>;
@@ -803,6 +815,18 @@ export function createToolGatewayService(
const interactions = issueThreadInteractionService(db);
const policyService = toolAccessPolicyService(db);
const secrets = secretService(db);
const gmailConnectorConfig = options.paperclipIdGmailConnector === undefined
? paperclipIdGmailConnectorConfigFromEnv()
: null;
const gmailConnector = options.paperclipIdGmailConnector
?? (gmailConnectorConfig
? createPaperclipIdGmailConnector({ config: gmailConnectorConfig, now: options.now })
: null);
const gmailRefreshFlights = new Map<string, Promise<typeof connectionGrants.$inferSelect>>();
const composioSessions = createComposioSessionManager(db, {
composioClientFactory: options.composioClientFactory,
now: options.now ? () => new Date(options.now!()) : undefined,
});
const protocolLimits = mcpGatewayProtocolLimits(options.mcpGatewayProtocolLimits);
let nextProtocolRateLimitPruneAt = 0;
@@ -2422,11 +2446,116 @@ export function createToolGatewayService(
);
}
async function maybeRefreshPaperclipIdGmailGrant(
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 grantOauth = asRecord(asRecord(grant.providerTenant)?.oauth);
const expiresAt = typeof grantOauth?.accessTokenExpiresAt === "string"
? Date.parse(grantOauth.accessTokenExpiresAt)
: Number.NaN;
const currentTime = options.now?.() ?? Date.now();
if (Number.isFinite(expiresAt) && expiresAt > currentTime + 60_000) return grant;
const existingFlight = gmailRefreshFlights.get(grant.id);
if (existingFlight) return existingFlight;
const refresh = (async () => {
if (!gmailConnector || !grant.subjectUserId) {
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", {
connectionId: connection.id,
grantId: grant.id,
});
}
const accessRef = grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.access_token");
const refreshRef = grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token");
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", {
connectionId: connection.id,
grantId: grant.id,
});
}
const refreshToken = await secrets.resolveSecretValue(
connection.companyId,
refreshRef.secretId,
refreshRef.versionSelector ?? "latest",
{
accessContext: {
consumerType: "tool_connection",
consumerId: connection.id,
configPath: refreshRef.configPath,
actorType: "system",
actorId: session.agentId,
issueId: session.issueId,
heartbeatRunId: session.runId,
},
},
);
try {
const credentials = await gmailConnector.refresh({
subject: grant.subjectUserId,
companyId: connection.companyId,
refreshToken,
});
await secrets.rotate(accessRef.secretId, { value: credentials.accessToken });
if (credentials.refreshToken) {
await secrets.rotate(refreshRef.secretId, { value: credentials.refreshToken });
}
const providerTenant = {
...(grant.providerTenant ?? {}),
oauth: {
...(grant.providerTenant?.oauth ?? {}),
strategy: "paperclip_id_connector",
accessTokenExpiresAt: credentials.accessTokenExpiresAt,
scopes: credentials.scopes,
tokenType: credentials.tokenType,
},
};
const [updated] = await db.update(connectionGrants).set({ providerTenant, updatedAt: new Date(options.now?.() ?? Date.now()) })
.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", {
connectionId: connection.id,
grantId: grant.id,
});
}
return updated;
} catch (error) {
if (error instanceof ToolGatewayHttpError) throw error;
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", {
connectionId: connection.id,
grantId: grant.id,
});
}
throw new ToolGatewayHttpError(502, "Gmail authorization could not be refreshed", "gmail_refresh_failed", {
connectionId: connection.id,
grantId: grant.id,
});
}
})();
gmailRefreshFlights.set(grant.id, refresh);
try {
return await refresh;
} finally {
if (gmailRefreshFlights.get(grant.id) === refresh) gmailRefreshFlights.delete(grant.id);
}
}
async function resolveCredentialHeaders(
session: ToolGatewaySession,
connection: typeof toolConnections.$inferSelect,
grant: typeof connectionGrants.$inferSelect,
): Promise<Record<string, string>> {
grant = await maybeRefreshPaperclipIdGmailGrant(session, connection, grant);
const headers: Record<string, string> = {};
for (const ref of connection.credentialRefs ?? []) {
if (ref.placement !== "header") continue;
@@ -3406,27 +3535,37 @@ export function createToolGatewayService(
): Promise<RemoteHttpExecutionResult> {
const { entry, connection } = await resolveConnectedRemoteTool(session, tool);
const grant = await resolveConnectionGrant(session, connection);
const endpoint = remoteEndpoint(connection.config ?? {});
const composioScopeRevision = `${grant.id}:${grant.status}:${grant.updatedAt.toISOString()}`;
const composioChild = composioChildConfig(connection);
let composioSession = composioChild
? await composioSessions.ensureSession(connection.id, {
tools: [entry.toolName],
scopeRevision: composioScopeRevision,
})
: null;
let endpoint = composioSession?.url ?? remoteEndpoint(connection.config ?? {});
// 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.
const credentialHeaders = {
let credentialHeaders = composioSession?.headers ?? {
...projectedConnectionHeaders(connection),
...await resolveCredentialHeaders(session, connection, grant),
};
const { headers, summary: headerSummary } = buildRemoteHeaders({
let builtHeaders = buildRemoteHeaders({
session,
connection,
credentialHeaders,
callerHeaders,
});
let headers = builtHeaders.headers;
let headerSummary = builtHeaders.summary;
const requestId = `paperclip-tool-${randomUUID()}`;
const execution: RemoteHttpExecutionAudit = {
transport: "mcp_remote",
request: {
protocol: "MCP JSON-RPC 2.0",
httpMethod: "POST",
endpoint: auditSafeEndpoint(endpoint),
endpoint: composioChild ? `${new URL(endpoint).origin}/[composio-session]` : auditSafeEndpoint(endpoint),
mcpMethod: "tools/call",
requestId,
upstreamToolName: entry.toolName,
@@ -3458,7 +3597,7 @@ export function createToolGatewayService(
},
}),
};
const response = options.remoteHttpRequest
let response = options.remoteHttpRequest
? await options.remoteHttpRequest(endpoint, requestInit)
: await guardedRemoteHttpFetch(endpoint, requestInit, {
...remoteHttpFetchOptions(),
@@ -3467,6 +3606,25 @@ export function createToolGatewayService(
// letting the tighter default cut a legitimately slow tool short.
responseTimeoutMs: ms,
});
if (response.status === 401 && composioChild) {
composioSession = await composioSessions.ensureSession(connection.id, {
tools: [entry.toolName],
scopeRevision: composioScopeRevision,
force: true,
});
endpoint = composioSession.url;
credentialHeaders = composioSession.headers;
builtHeaders = buildRemoteHeaders({ session, connection, credentialHeaders, callerHeaders });
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,
});
}
const body = await readBoundedRemoteResponse(response);
execution.response = {
httpStatus: response.status,