diff --git a/doc/connections/LINKEDIN.md b/doc/connections/LINKEDIN.md new file mode 100644 index 00000000000..d7dda92e5d4 --- /dev/null +++ b/doc/connections/LINKEDIN.md @@ -0,0 +1,65 @@ +# LinkedIn Connection + +Paperclip connects to LinkedIn through a reviewed native REST adapter (`server/src/services/connectors/linkedin/`) because LinkedIn does not publish an official remote MCP server. + +## Scope & v1 vs. v2 Capabilities + +LinkedIn separates its APIs into two approval tiers: + +- **v1 (Self-Serve — shipped):** Uses *Sign In with LinkedIn using OpenID Connect* (`openid`, `profile`, `email`) and *Share on LinkedIn* (`w_member_social`). + - `linkedin_get_profile` (`read`): Reads the authenticated member's profile and `urn:li:person:`. Also used for health checks (`probe()`). + - `linkedin_create_post` (`destructive`, S4): Publishes a personal text or link/article post via `POST https://api.linkedin.com/rest/posts`. Always derives `author` from the authenticated grant so callers cannot spoof another member. + - `linkedin_delete_post` (`destructive`, S4): Deletes a personal post by URN via `DELETE https://api.linkedin.com/rest/posts/{encoded_urn}`. +- **v2 (Deferred — requires LinkedIn Community Management API commercial review):** Company Page posting, reading posts/comments (`r_member_social` / `r_organization_social`), analytics, and programmatic 365-day refresh tokens. +- **Not supported by LinkedIn public APIs:** DMs/messaging, connection requests, feed browsing, and people search. + +## Service Involvement Statement + +- **Managed method (`managed`, `platform_shared`):** Uses **Paperclip Cloud** (`my.paperclip.app/v1/connector/oauth/linkedin/callback`, profile `linkedin.share`) for the fixed LinkedIn OAuth callback and token exchange. Tokens are immediately sealed to the originating Paperclip instance's X25519 key and stored durably in the instance vault. **Paperclip ID (`id.paperclip.ing`)** never stores LinkedIn tokens. +- **Customer-owned OAuth (`oauth-own-app`, `customer`):** Completely instance-local. Neither Paperclip ID nor Paperclip Cloud participates. + +## Connection Flow + +```mermaid +sequenceDiagram + actor U as Paperclip User + participant P as Paperclip Instance + participant C as Paperclip Cloud Broker + participant L as LinkedIn OAuth and REST API + + U->>P: Connect LinkedIn (managed) + P->>C: Signed session request (profile linkedin.share) + C-->>P: LinkedIn authorize URL + U->>L: Approve openid profile email w_member_social + L-->>C: Callback /v1/connector/oauth/linkedin/callback?code=... + C->>L: POST /oauth/v2/accessToken (code + client_secret) + L-->>C: 60-day access_token + C-->>P: X25519 sealed credential claim + P->>P: Vault user-scoped token ref + P->>L: GET /v2/userinfo (probe) +``` + +### Exact Endpoints +- **Authorize:** `https://www.linkedin.com/oauth/v2/authorization` +- **Token:** `https://www.linkedin.com/oauth/v2/accessToken` +- **Paperclip Cloud managed callback:** `https://my.paperclip.app/v1/connector/oauth/linkedin/callback` +- **Customer-owned callback:** `/api/tools/oauth/callback` +- **REST API base:** `https://api.linkedin.com` (`/v2/userinfo`, `/rest/posts`) +- **Required Rest.li headers:** `X-Restli-Protocol-Version: 2.0.0`, `LinkedIn-Version: 202611` +- **Redirect constraints:** `https-or-loopback-http` (byte-for-byte registered in LinkedIn Developer Portal) + +## Administrator Setup + +### Managed (`paperclip-cloud` operators) +1. Create an app in the [LinkedIn Developer Portal](https://www.linkedin.com/developers/apps) and add **Sign In with LinkedIn using OpenID Connect** and **Share on LinkedIn**. +2. Register `https://my.paperclip.app/v1/connector/oauth/linkedin/callback` (and staging callback) under **Auth → OAuth 2.0 settings**. +3. Store the client secret in AWS Secrets Manager and configure `CLOUD_HARNESS_CONNECTOR_LINKEDIN_CLIENT_ID`, `CLOUD_HARNESS_CONNECTOR_LINKEDIN_CLIENT_SECRET_REF`, and `CLOUD_HARNESS_CONNECTOR_LINKEDIN_ENABLED_PROFILES=linkedin.share` on Paperclip Cloud. + +### Customer-Owned OAuth (`oauth-own-app`) +1. Create an app in the [LinkedIn Developer Portal](https://www.linkedin.com/developers/apps) with **Sign In with LinkedIn using OpenID Connect** and **Share on LinkedIn** enabled. +2. Add `/api/tools/oauth/callback` under **Auth → OAuth 2.0 settings**. +3. Enter the Client ID and Client Secret in Paperclip's LinkedIn **Use your own OAuth app** setup form. + +## Token Lifetime & Revocation +- Standard self-serve LinkedIn access tokens expire after **60 days** and do not include a `refresh_token`. Users reconnect when the token expires. +- LinkedIn does not expose an RFC 7009 revocation endpoint for self-serve OAuth; removing the connection in Paperclip deletes the vaulted token immediately and blocks all subsequent tool calls. diff --git a/doc/connections/README.md b/doc/connections/README.md index 77bd256be5a..51fcd64bbc3 100644 --- a/doc/connections/README.md +++ b/doc/connections/README.md @@ -29,7 +29,7 @@ organization connections where no person signs in). Long-term memory: [Experimental memory connectors](./MEMORY.md). Provider notes: [Google Workspace](./GOOGLE-WORKSPACE.md), -[Gmail](./GMAIL.md), [AWS](./AWS.md), [Asana](./ASANA.md), [Sentry](./SENTRY.md), [PostHog](./POSTHOG.md), [Braintrust](./BRAINTRUST.md), [Neon](./NEON.md), [Superagent](./SUPERAGENT.md), [Gauge](./GAUGE.md), [Ditto](./DITTO.md), [Circleback](./CIRCLEBACK.md), +[Gmail](./GMAIL.md), [AWS](./AWS.md), [Asana](./ASANA.md), [LinkedIn](./LINKEDIN.md), [Sentry](./SENTRY.md), [PostHog](./POSTHOG.md), [Braintrust](./BRAINTRUST.md), [Neon](./NEON.md), [Superagent](./SUPERAGENT.md), [Gauge](./GAUGE.md), [Ditto](./DITTO.md), [Circleback](./CIRCLEBACK.md), [1Password](./1PASSWORD.md), [Unikraft](./UNIKRAFT.md), [AgentMail](./AGENTMAIL.md), [Telem.AI](./TELEM.md), [iMessage Photon](./IMESSAGE-PHOTON.md), [Enterpret](./ENTERPRET.md), [Supabase](./SUPABASE.md), and [Vercel](./vercel.md). Optional credential custody: diff --git a/doc/connections/tool-method-permission-reviews.json b/doc/connections/tool-method-permission-reviews.json index f7a2ebcccac..f7dee72de65 100644 --- a/doc/connections/tool-method-permission-reviews.json +++ b/doc/connections/tool-method-permission-reviews.json @@ -2,6 +2,47 @@ "reviewedAt": "2026-09-30", "evidenceLevel": "Official documentation and public MCP metadata; no account-bound read/write proof. Runtime discovery never expands this allowlist.", "methods": [ + { + "app": "linkedin", + "method": "managed", + "auth": "oauth", + "policy": "explicit", + "requestedScopes": [ + "openid", + "profile", + "email", + "w_member_social" + ], + "capability": "write", + "supportedActions": "Verify connected member identity (linkedin_get_profile) and publish or delete personal LinkedIn posts (linkedin_create_post, linkedin_delete_post) via the reviewed REST adapter. Company Page management, post reading (r_member_social), analytics, and DMs are excluded in v1.", + "evidence": [ + "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin", + "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/sign-in-with-linkedin-v2", + "https://learn.microsoft.com/en-us/linkedin/marketing/community-management/shares/posts-api" + ], + "reviewedAt": "2026-12-01", + "liveProof": "not-run" + }, + { + "app": "linkedin", + "method": "oauth-own-app", + "auth": "oauth", + "policy": "explicit", + "requestedScopes": [ + "openid", + "profile", + "email", + "w_member_social" + ], + "capability": "write", + "supportedActions": "Verify connected member identity (linkedin_get_profile) and publish or delete personal LinkedIn posts (linkedin_create_post, linkedin_delete_post) using a customer-owned LinkedIn Developer App with OIDC Sign In and Share on LinkedIn enabled.", + "evidence": [ + "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin", + "https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow" + ], + "reviewedAt": "2026-12-01", + "liveProof": "not-run" + }, { "app": "google-workspace", "method": "paperclip-workspace", diff --git a/packages/shared/src/app-definitions.generated.ts b/packages/shared/src/app-definitions.generated.ts index e15939b08ef..c8b1c79300c 100644 --- a/packages/shared/src/app-definitions.generated.ts +++ b/packages/shared/src/app-definitions.generated.ts @@ -97,19 +97,20 @@ import a95 from "./app-definitions/google-workspace-search.json" with { type: "j import a96 from "./app-definitions/openai.json" with { type: "json" }; import a97 from "./app-definitions/openrouter.json" with { type: "json" }; import a98 from "./app-definitions/xai.json" with { type: "json" }; -import a99 from "./app-definitions/antigravity.json" with { type: "json" }; -import a100 from "./app-definitions/bedrock.json" with { type: "json" }; -import a101 from "./app-definitions/responses-api.json" with { type: "json" }; -import a102 from "./app-definitions/messages-api.json" with { type: "json" }; -import a103 from "./app-definitions/chat-completions-api.json" with { type: "json" }; -import a104 from "./app-definitions/local.json" with { type: "json" }; -import a105 from "./app-definitions/1password.json" with { type: "json" }; +import a99 from "./app-definitions/bedrock.json" with { type: "json" }; +import a100 from "./app-definitions/responses-api.json" with { type: "json" }; +import a101 from "./app-definitions/messages-api.json" with { type: "json" }; +import a102 from "./app-definitions/chat-completions-api.json" with { type: "json" }; +import a103 from "./app-definitions/local.json" with { type: "json" }; +import a104 from "./app-definitions/1password.json" with { type: "json" }; +import a105 from "./app-definitions/antigravity.json" with { type: "json" }; import a106 from "./app-definitions/aws.json" with { type: "json" }; import a107 from "./app-definitions/daytona.json" with { type: "json" }; import a108 from "./app-definitions/github-copilot.json" with { type: "json" }; -import a109 from "./app-definitions/monday.json" with { type: "json" }; -import a110 from "./app-definitions/paperclip-notebook.json" with { type: "json" }; -import a111 from "./app-definitions/unikraft.json" with { type: "json" }; -import a112 from "./app-definitions/speko.json" with { type: "json" }; +import a109 from "./app-definitions/linkedin.json" with { type: "json" }; +import a110 from "./app-definitions/monday.json" with { type: "json" }; +import a111 from "./app-definitions/paperclip-notebook.json" with { type: "json" }; +import a112 from "./app-definitions/unikraft.json" with { type: "json" }; +import a113 from "./app-definitions/speko.json" with { type: "json" }; import type { AppDefinition } from "./types/app-definition.js"; -export const APP_DEFINITIONS=[a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,a38,a39,a40,a41,a42,a43,a44,a45,a46,a47,a48,a49,a50,a51,a52,a53,a54,a55,a56,a57,a58,a59,a60,a61,a62,a63,a64,a65,a66,a67,a68,a69,a70,a71,a72,a73,a74,a75,a76,a77,a78,a79,a80,a81,a82,a83,a84,a85,a86,a87,a88,a89,a90,a91,a92,a93,a94,a95,a96,a97,a98,a99,a100,a101,a102,a103,a104,a105,a106,a107,a108,a109,a110,a111,a112] as AppDefinition[]; +export const APP_DEFINITIONS=[a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,a38,a39,a40,a41,a42,a43,a44,a45,a46,a47,a48,a49,a50,a51,a52,a53,a54,a55,a56,a57,a58,a59,a60,a61,a62,a63,a64,a65,a66,a67,a68,a69,a70,a71,a72,a73,a74,a75,a76,a77,a78,a79,a80,a81,a82,a83,a84,a85,a86,a87,a88,a89,a90,a91,a92,a93,a94,a95,a96,a97,a98,a99,a100,a101,a102,a103,a104,a105,a106,a107,a108,a109,a110,a111,a112,a113] as AppDefinition[]; diff --git a/packages/shared/src/app-definitions.test.ts b/packages/shared/src/app-definitions.test.ts index 7a4dfd29b44..d346bbae1c7 100644 --- a/packages/shared/src/app-definitions.test.ts +++ b/packages/shared/src/app-definitions.test.ts @@ -948,7 +948,7 @@ describe("AppDefinition catalog", () => { "ticktick", "xero", ]); - expect(APP_STORE_DEFINITIONS).toHaveLength(91); + expect(APP_STORE_DEFINITIONS).toHaveLength(92); const connectableSlugs = new Set( CONNECTABLE_APP_DEFINITIONS.map((entry) => entry.slug), ); diff --git a/packages/shared/src/app-definitions.ts b/packages/shared/src/app-definitions.ts index 8f54fb0e497..94340a2b9c6 100644 --- a/packages/shared/src/app-definitions.ts +++ b/packages/shared/src/app-definitions.ts @@ -26,6 +26,7 @@ export const CONNECTABLE_APP_SLUGS = new Set([ "aws", "posthog", "linear", + "linkedin", "google-sheets", "context7", "shopify", diff --git a/packages/shared/src/app-definitions/linkedin.json b/packages/shared/src/app-definitions/linkedin.json new file mode 100644 index 00000000000..904d05d07e5 --- /dev/null +++ b/packages/shared/src/app-definitions/linkedin.json @@ -0,0 +1,92 @@ +{ + "schemaVersion": 1, + "slug": "linkedin", + "name": "LinkedIn", + "description": "Verify your LinkedIn profile and publish or delete personal LinkedIn posts with explicit governance.", + "categories": [ + "communication" + ], + "featured": false, + "availability": { + "available": true + }, + "branding": { + "logoUrl": "/brands/apps/linkedin.svg" + }, + "urlPatterns": [ + "https://www.linkedin.com/*", + "https://api.linkedin.com/*" + ], + "docsUrl": "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin", + "redirectConstraints": "https-or-loopback-http", + "methods": [ + { + "key": "managed", + "label": "Sign in with LinkedIn", + "transport": "rest_api", + "auth": "oauth", + "ownershipModes": [ + "platform_shared" + ], + "oauthStrategy": "paperclip_cloud_connector", + "connectorProfile": "linkedin.share", + "grantKinds": [ + "user" + ], + "whenToUse": "Connect your personal LinkedIn account with Paperclip's managed LinkedIn app.", + "defaults": { + "serverUrl": "https://api.linkedin.com", + "scopesHint": [ + "openid", + "profile", + "email", + "w_member_social" + ] + }, + "guidanceMd": "Sign in to LinkedIn to verify your profile and allow agents to publish or delete personal posts under your account. Standard self-serve LinkedIn tokens expire every 60 days and require reconnecting. Company Page management, post reading, and DMs are not included in v1.", + "warnings": [ + "LinkedIn posts are public external broadcasts under your personal profile. Keep publish and delete actions governed.", + "Standard self-serve LinkedIn OAuth access tokens expire after 60 days without a refresh token; reconnect when expired." + ], + "consoleLinks": { + "docs": "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin" + }, + "riskTier": "S4" + }, + { + "key": "oauth-own-app", + "label": "Use your own OAuth app", + "transport": "rest_api", + "auth": "oauth", + "ownershipModes": [ + "customer" + ], + "oauthClientSecretRequired": true, + "grantKinds": [ + "user" + ], + "whenToUse": "Register your own LinkedIn Developer App with Sign In with LinkedIn (OIDC) and Share on LinkedIn enabled, then enter its client ID and secret.", + "defaults": { + "serverUrl": "https://api.linkedin.com", + "authorizationEndpoint": "https://www.linkedin.com/oauth/v2/authorization", + "tokenEndpoint": "https://www.linkedin.com/oauth/v2/accessToken", + "scopesHint": [ + "openid", + "profile", + "email", + "w_member_social" + ] + }, + "guidanceMd": "Create an app in the LinkedIn Developer Portal, enable the 'Sign In with LinkedIn using OpenID Connect' and 'Share on LinkedIn' products, and register Paperclip's exact callback URL under Auth → OAuth 2.0 settings.", + "warnings": [ + "LinkedIn posts are public external broadcasts under your personal profile. Keep publish and delete actions governed.", + "Standard self-serve LinkedIn OAuth access tokens expire after 60 days without a refresh token; reconnect when expired." + ], + "consoleLinks": { + "register": "https://www.linkedin.com/developers/apps", + "docs": "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin" + }, + "riskTier": "S4" + } + ] +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 7bf44c13018..56fdc6718a8 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -369,6 +369,7 @@ export * from "./google-workspace-connectors.js"; export * from "./google-sign-in-deployment.js"; export * from "./github-connectors.js"; export * from "./asana-connectors.js"; +export * from "./linkedin-connectors.js"; export { BLOCKED_MCP_PROVIDERS, SELF_SERVE_MCP_CANDIDATES, diff --git a/packages/shared/src/linkedin-connectors.ts b/packages/shared/src/linkedin-connectors.ts new file mode 100644 index 00000000000..017f160d724 --- /dev/null +++ b/packages/shared/src/linkedin-connectors.ts @@ -0,0 +1,16 @@ +export const LINKEDIN_CONNECTOR_PROFILE_ID = "linkedin.share" as const; +export type LinkedInConnectorProfileId = typeof LINKEDIN_CONNECTOR_PROFILE_ID; + +export const LINKEDIN_API_URL = "https://api.linkedin.com"; +export const LINKEDIN_AUTHORIZATION_URL = "https://www.linkedin.com/oauth/v2/authorization"; +export const LINKEDIN_TOKEN_URL = "https://www.linkedin.com/oauth/v2/accessToken"; +export const LINKEDIN_CONNECTOR_SCOPES = [ + "openid", + "profile", + "email", + "w_member_social", +] as const; + +export function isLinkedInConnectorProfileId(value: string): value is LinkedInConnectorProfileId { + return value === LINKEDIN_CONNECTOR_PROFILE_ID; +} diff --git a/scripts/app-definition-overrides/linkedin.json b/scripts/app-definition-overrides/linkedin.json new file mode 100644 index 00000000000..01a4aafc297 --- /dev/null +++ b/scripts/app-definition-overrides/linkedin.json @@ -0,0 +1,65 @@ +{ + "schemaVersion": 1, + "slug": "linkedin", + "name": "LinkedIn", + "description": "Verify your LinkedIn profile and publish or delete personal LinkedIn posts with explicit governance.", + "categories": ["communication"], + "featured": false, + "availability": { "available": true }, + "branding": { "logoUrl": "/brands/apps/linkedin.svg" }, + "urlPatterns": ["https://www.linkedin.com/*", "https://api.linkedin.com/*"], + "docsUrl": "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin", + "redirectConstraints": "https-or-loopback-http", + "methods": [ + { + "key": "managed", + "label": "Sign in with LinkedIn", + "transport": "rest_api", + "auth": "oauth", + "ownershipModes": ["platform_shared"], + "oauthStrategy": "paperclip_cloud_connector", + "connectorProfile": "linkedin.share", + "grantKinds": ["user"], + "whenToUse": "Connect your personal LinkedIn account with Paperclip's managed LinkedIn app.", + "defaults": { + "serverUrl": "https://api.linkedin.com", + "scopesHint": ["openid", "profile", "email", "w_member_social"] + }, + "guidanceMd": "Sign in to LinkedIn to verify your profile and allow agents to publish or delete personal posts under your account. Standard self-serve LinkedIn tokens expire every 60 days and require reconnecting. Company Page management, post reading, and DMs are not included in v1.", + "warnings": [ + "LinkedIn posts are public external broadcasts under your personal profile. Keep publish and delete actions governed.", + "Standard self-serve LinkedIn OAuth access tokens expire after 60 days without a refresh token; reconnect when expired." + ], + "consoleLinks": { + "docs": "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin" + }, + "riskTier": "S4" + }, + { + "key": "oauth-own-app", + "label": "Use your own OAuth app", + "transport": "rest_api", + "auth": "oauth", + "ownershipModes": ["customer"], + "oauthClientSecretRequired": true, + "grantKinds": ["user"], + "whenToUse": "Register your own LinkedIn Developer App with Sign In with LinkedIn (OIDC) and Share on LinkedIn enabled, then enter its client ID and secret.", + "defaults": { + "serverUrl": "https://api.linkedin.com", + "authorizationEndpoint": "https://www.linkedin.com/oauth/v2/authorization", + "tokenEndpoint": "https://www.linkedin.com/oauth/v2/accessToken", + "scopesHint": ["openid", "profile", "email", "w_member_social"] + }, + "guidanceMd": "Create an app in the LinkedIn Developer Portal, enable the 'Sign In with LinkedIn using OpenID Connect' and 'Share on LinkedIn' products, and register Paperclip's exact callback URL under Auth → OAuth 2.0 settings.", + "warnings": [ + "LinkedIn posts are public external broadcasts under your personal profile. Keep publish and delete actions governed.", + "Standard self-serve LinkedIn OAuth access tokens expire after 60 days without a refresh token; reconnect when expired." + ], + "consoleLinks": { + "register": "https://www.linkedin.com/developers/apps", + "docs": "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin" + }, + "riskTier": "S4" + } + ] +} diff --git a/server/src/services/connectors/linkedin/catalog.ts b/server/src/services/connectors/linkedin/catalog.ts new file mode 100644 index 00000000000..9569bb4e1f1 --- /dev/null +++ b/server/src/services/connectors/linkedin/catalog.ts @@ -0,0 +1,134 @@ +import { z } from "zod"; +import { LINKEDIN_API_URL } from "@paperclipai/shared"; +import { descriptorHash, stableHash } from "../../tool-catalog-hash.js"; + +export { LINKEDIN_API_URL }; +export const LINKEDIN_API_VERSION = "202611"; +export const LINKEDIN_METHODS = new Set(["managed", "oauth-own-app"]); + +export const linkedInPostUrnSchema = z + .string() + .regex(/^urn:li:(?:ugcPost|share):[A-Za-z0-9_-]{1,128}$/, "Expected a LinkedIn post URN (urn:li:share:... or urn:li:ugcPost:...)."); + +const httpsUrlSchema = z + .string() + .url() + .max(2048) + .refine((value) => value.startsWith("https://"), "Article source URL must use https://"); + +function operation( + name: string, + title: string, + description: string, + risk: "read" | "write" | "destructive", + schema: z.ZodType, +) { + return { name: `linkedin_${name}`, title, description, risk, schema }; +} + +export const linkedInOperations = [ + operation( + "get_profile", + "Get LinkedIn profile", + "Read the signed-in LinkedIn member's OpenID Connect profile (name, email, picture, and person URN).", + "read", + z.object({}).strict(), + ), + operation( + "create_post", + "Publish LinkedIn post", + "Publish a personal post on LinkedIn under the connected member's account. Supports text posts and optional link/article attachments. Public external broadcast — requires explicit governance.", + "destructive", + z + .object({ + text: z + .string() + .trim() + .min(1, "Post text cannot be empty.") + .max(3000, "LinkedIn post text must be 3,000 characters or fewer.") + .describe("Body text of the LinkedIn post (max 3,000 characters)."), + visibility: z + .enum(["PUBLIC", "CONNECTIONS"]) + .optional() + .describe("Audience visibility on LinkedIn. Defaults to PUBLIC."), + article: z + .object({ + source: httpsUrlSchema.describe("HTTPS URL of the shared article or link."), + title: z.string().trim().min(1).max(200).describe("Title displayed on the link card."), + description: z.string().trim().max(500).optional().describe("Optional summary for the link card."), + }) + .strict() + .optional() + .describe("Optional article/link attachment."), + }) + .strict(), + ), + operation( + "delete_post", + "Delete LinkedIn post", + "Permanently delete a personal LinkedIn post by its URN (urn:li:share:... or urn:li:ugcPost:...).", + "destructive", + z + .object({ + postUrn: linkedInPostUrnSchema.describe("URN of the LinkedIn post to delete."), + }) + .strict(), + ), +] as const; + +export const LINKEDIN_TOOLS = linkedInOperations.map(({ name, title, description, risk, schema }) => ({ + name, + title, + description, + inputSchema: z.toJSONSchema(schema) as Record, + annotations: { + readOnlyHint: risk === "read", + destructiveHint: risk === "destructive", + openWorldHint: true, + }, +})); + +export function linkedInRisk(name: string): "read" | "write" | "destructive" { + return linkedInOperations.find((candidate) => candidate.name === name)?.risk ?? "destructive"; +} + +const currentContracts = new Map( + LINKEDIN_TOOLS.map((tool) => [ + tool.name, + { + versionHash: descriptorHash(tool, linkedInRisk(tool.name)), + schemaHash: stableHash(tool.inputSchema), + riskLevel: linkedInRisk(tool.name), + }, + ]), +); + +export function isCurrentLinkedInCatalogEntry(entry: { + toolName: string; + versionHash: string; + schemaHash: string | null; + riskLevel: string; +}): boolean { + const current = currentContracts.get(entry.toolName); + return Boolean( + current + && current.versionHash === entry.versionHash + && current.schemaHash === entry.schemaHash + && current.riskLevel === entry.riskLevel, + ); +} + +export function isLinkedInConnection(connection: { + transport: string; + config?: Record; +}): boolean { + const methodKey = typeof connection.config?.connectionMethodKey === "string" + ? connection.config.connectionMethodKey + : ""; + return ( + connection.transport === "rest_api" + && connection.config?.sourceTemplateKey === "linkedin" + && LINKEDIN_METHODS.has(methodKey) + && (connection.config.url === LINKEDIN_API_URL || connection.config.url === `${LINKEDIN_API_URL}/`) + ); +} diff --git a/server/src/services/connectors/linkedin/index.test.ts b/server/src/services/connectors/linkedin/index.test.ts new file mode 100644 index 00000000000..2682e95b63c --- /dev/null +++ b/server/src/services/connectors/linkedin/index.test.ts @@ -0,0 +1,368 @@ +import { describe, expect, it, vi } from "vitest"; +import { + LINKEDIN_API_URL, + LINKEDIN_API_VERSION, + LINKEDIN_TOOLS, + isCurrentLinkedInCatalogEntry, + isLinkedInConnection, + linkedInClient, + linkedInRisk, +} from "./index.js"; +import { restConnectorFor } from "../rest-registry.js"; +import { descriptorHash, stableHash } from "../../tool-catalog-hash.js"; + +function jsonResponse(body: unknown, status = 200, headers: Record = {}) { + return new Response(body === null ? null : JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json", ...headers }, + }); +} + +describe("LinkedIn REST connector", () => { + it("matches managed and customer OAuth LinkedIn connections and registers in rest-registry", () => { + const managed = { + transport: "rest_api", + config: { sourceTemplateKey: "linkedin", connectionMethodKey: "managed", url: LINKEDIN_API_URL }, + }; + const customer = { + transport: "rest_api", + config: { sourceTemplateKey: "linkedin", connectionMethodKey: "oauth-own-app", url: `${LINKEDIN_API_URL}/` }, + }; + expect(isLinkedInConnection(managed)).toBe(true); + expect(isLinkedInConnection(customer)).toBe(true); + expect(restConnectorFor(managed)?.sourceTemplateKey).toBe("linkedin"); + expect(isLinkedInConnection({ transport: "mcp_remote", config: managed.config })).toBe(false); + expect(isLinkedInConnection({ transport: "rest_api", config: { ...managed.config, url: "https://evil.example.com" } })).toBe(false); + }); + + it("classifies profile read as read and publish/delete as destructive with matching contract hashes", () => { + expect(linkedInRisk("linkedin_get_profile")).toBe("read"); + expect(linkedInRisk("linkedin_create_post")).toBe("destructive"); + expect(linkedInRisk("linkedin_delete_post")).toBe("destructive"); + expect(linkedInRisk("unknown_tool")).toBe("destructive"); + + for (const tool of LINKEDIN_TOOLS) { + const risk = linkedInRisk(tool.name); + expect( + isCurrentLinkedInCatalogEntry({ + toolName: tool.name, + versionHash: descriptorHash(tool, risk), + schemaHash: stableHash(tool.inputSchema), + riskLevel: risk, + }), + ).toBe(true); + } + expect( + isCurrentLinkedInCatalogEntry({ + toolName: "linkedin_create_post", + versionHash: "stale", + schemaHash: "stale", + riskLevel: "destructive", + }), + ).toBe(false); + }); + + it("probes and reads member profile from /v2/userinfo without leaking bearer token", async () => { + const token = "li-secret-token-12345"; + const request = vi.fn(async (url: string, init: RequestInit) => { + expect(url).toBe("https://api.linkedin.com/v2/userinfo"); + expect(init.method).toBe("GET"); + expect(init.redirect).toBe("error"); + return jsonResponse({ + sub: "abc_123", + name: `Jane Doe ${token}`, + given_name: "Jane", + family_name: "Doe", + email: "jane@example.com", + }); + }); + + const client = linkedInClient({ Authorization: `Bearer ${token}` }, request); + const probeResult = await client.probe(); + expect(probeResult).toEqual({ + personUrn: "urn:li:person:abc_123", + name: "Jane Doe [REDACTED]", + }); + + const profile = await client.invoke("linkedin_get_profile", {}); + expect(profile).toMatchObject({ + sub: "abc_123", + personUrn: "urn:li:person:abc_123", + name: "Jane Doe [REDACTED]", + email: "jane@example.com", + }); + }); + + it("publishes a personal post with server-derived author URN and required Rest.li headers", async () => { + const calls: Array<{ url: string; init: RequestInit }> = []; + const request = vi.fn(async (url: string, init: RequestInit) => { + calls.push({ url, init }); + if (url.endsWith("/v2/userinfo")) { + return jsonResponse({ sub: "member42", name: "Alex" }); + } + if (url.endsWith("/rest/posts")) { + return new Response(null, { status: 201, headers: { "x-restli-id": "urn:li:share:999888" } }); + } + throw new Error(`Unexpected URL: ${url}`); + }); + + const client = linkedInClient({ Authorization: "Bearer tok-xyz" }, request); + const result = await client.invoke("linkedin_create_post", { + text: "Hello LinkedIn from Paperclip!", + visibility: "CONNECTIONS", + article: { + source: "https://paperclip.ing/blog/launch", + title: "Paperclip Launch", + description: "Announcement", + }, + }); + + expect(result).toEqual({ + created: true, + author: "urn:li:person:member42", + visibility: "CONNECTIONS", + postUrn: "urn:li:share:999888", + }); + expect(calls).toHaveLength(2); + const postCall = calls[1]!; + expect(postCall.init.method).toBe("POST"); + expect((postCall.init.headers as Record)["X-Restli-Protocol-Version"]).toBe("2.0.0"); + expect((postCall.init.headers as Record)["LinkedIn-Version"]).toBe(LINKEDIN_API_VERSION); + const parsedBody = JSON.parse(String(postCall.init.body)); + expect(parsedBody.author).toBe("urn:li:person:member42"); + expect(parsedBody.commentary).toBe("Hello LinkedIn from Paperclip!"); + expect(parsedBody.visibility).toBe("CONNECTIONS"); + expect(parsedBody.content.article.source).toBe("https://paperclip.ing/blog/launch"); + }); + + it("deletes a personal post by URL-encoded URN and rejects path traversal or unknown keys", async () => { + const request = vi.fn(async (url: string, init: RequestInit) => { + expect(url).toBe("https://api.linkedin.com/rest/posts/urn%3Ali%3AugcPost%3A123456"); + expect(init.method).toBe("DELETE"); + return new Response(null, { status: 204 }); + }); + + const client = linkedInClient({ Authorization: "Bearer tok-xyz" }, request); + await expect(client.invoke("linkedin_delete_post", { postUrn: "urn:li:ugcPost:123456" })).resolves.toEqual({ + deleted: true, + postUrn: "urn:li:ugcPost:123456", + }); + + await expect( + client.invoke("linkedin_delete_post", { postUrn: "urn:li:share:123/../other" }), + ).rejects.toMatchObject({ status: 422, details: { code: "linkedin_invalid_arguments" } }); + + await expect( + client.invoke("linkedin_create_post", { text: "hi", author: "urn:li:person:spoofed" }), + ).rejects.toMatchObject({ status: 422, details: { code: "linkedin_invalid_arguments" } }); + + await expect( + client.invoke("linkedin_create_post", { + text: "hi", + article: { source: "http://insecure.example.com", title: "Bad" }, + }), + ).rejects.toMatchObject({ status: 422, details: { code: "linkedin_invalid_arguments" } }); + }); + + it("rejects missing credentials and maps 401, 403, 404, and 429 cleanly", async () => { + expect(() => linkedInClient({}, vi.fn())).toThrow(/Reconnect LinkedIn/); + + for (const [status, code, fragment] of [ + [401, "linkedin_auth_failed", /60 days/], + [403, "linkedin_auth_failed", /Sign In with LinkedIn/], + [404, "linkedin_request_failed", /could not find/], + [429, "linkedin_request_failed", /rate limited/], + ] as const) { + const cancel = vi.fn(async () => {}); + const request = vi.fn(async () => ({ + ok: false, + status, + headers: new Headers(), + body: { cancel } as unknown as ReadableStream, + }) as unknown as Response); + const client = linkedInClient({ Authorization: "Bearer tok-status" }, request); + await expect(client.probe()).rejects.toMatchObject({ + status, + details: { code }, + message: expect.stringMatching(fragment), + }); + expect(cancel).toHaveBeenCalledTimes(1); + } + }); + + it("reports uncertain outcome on 5xx, stalled deadline, and interrupted write responses without retrying", async () => { + // 1. POST /rest/posts returns 500 -> linkedin_outcome_unknown, 1 POST attempt + let postAttempts = 0; + const request500 = vi.fn(async (url: string) => { + if (url.endsWith("/v2/userinfo")) return jsonResponse({ sub: "member42", name: "Alex" }); + postAttempts++; + return jsonResponse({ message: "Internal error" }, 500); + }); + const client500 = linkedInClient({ Authorization: "Bearer tok-500" }, request500); + await expect(client500.invoke("linkedin_create_post", { text: "Hello" })).rejects.toMatchObject({ + status: 502, + details: { code: "linkedin_outcome_unknown" }, + message: expect.stringMatching(/inspect LinkedIn before retrying/), + }); + expect(postAttempts).toBe(1); + + // 2. DELETE /rest/posts/{urn} returns 500 -> linkedin_outcome_unknown, 1 DELETE attempt + let deleteAttempts = 0; + const requestDel500 = vi.fn(async () => { + deleteAttempts++; + return jsonResponse({ message: "Internal error" }, 500); + }); + const clientDel500 = linkedInClient({ Authorization: "Bearer tok-del500" }, requestDel500); + await expect( + clientDel500.invoke("linkedin_delete_post", { postUrn: "urn:li:share:12345" }), + ).rejects.toMatchObject({ + status: 502, + details: { code: "linkedin_outcome_unknown" }, + message: expect.stringMatching(/inspect LinkedIn before retrying/), + }); + expect(deleteAttempts).toBe(1); + + // 3. Stalled POST hits deadline -> 504 linkedin_deadline_exceeded, 1 POST attempt + let stalledAttempts = 0; + const requestStalled = vi.fn(async (url: string) => { + if (url.endsWith("/v2/userinfo")) return jsonResponse({ sub: "member42", name: "Alex" }); + stalledAttempts++; + return new Promise(() => {}); + }); + const controller = new AbortController(); + const clientStalled = linkedInClient( + { Authorization: "Bearer tok-stall" }, + requestStalled, + controller.signal, + Date.now() + 25, + ); + await expect(clientStalled.invoke("linkedin_create_post", { text: "Hello" })).rejects.toMatchObject({ + status: 504, + details: { code: "linkedin_deadline_exceeded" }, + message: expect.stringMatching(/inspect LinkedIn before retrying/), + }); + expect(stalledAttempts).toBe(1); + + // 4. Interrupted response stream after POST -> 502 linkedin_outcome_unknown & reader cancelled + const cancel = vi.fn(async () => {}); + const requestInterrupted = vi.fn(async (url: string) => { + if (url.endsWith("/v2/userinfo")) return jsonResponse({ sub: "member42", name: "Alex" }); + return { + ok: true, + status: 201, + headers: new Headers(), + body: { + getReader: () => ({ + read: async () => { + throw new Error("socket reset"); + }, + cancel, + }), + } as unknown as ReadableStream, + } as unknown as Response; + }); + const clientInterrupted = linkedInClient({ Authorization: "Bearer tok-int" }, requestInterrupted); + await expect(clientInterrupted.invoke("linkedin_create_post", { text: "Hello" })).rejects.toMatchObject({ + status: 502, + details: { code: "linkedin_outcome_unknown" }, + }); + expect(cancel).toHaveBeenCalledTimes(1); + + // 5. Oversized response (> 2 MiB) -> 502 linkedin_output_limit & reader cancelled + const oversizeCancel = vi.fn(async () => {}); + const bigChunk = new Uint8Array(2 * 1024 * 1024 + 16); + const requestOversize = vi.fn(async () => ({ + ok: true, + status: 200, + headers: new Headers(), + body: { + getReader: () => ({ + read: async () => ({ done: false, value: bigChunk }), + cancel: oversizeCancel, + }), + } as unknown as ReadableStream, + }) as unknown as Response); + const clientOversize = linkedInClient({ Authorization: "Bearer tok-big" }, requestOversize); + await expect(clientOversize.probe()).rejects.toMatchObject({ + status: 502, + details: { code: "linkedin_output_limit" }, + }); + expect(oversizeCancel).toHaveBeenCalledTimes(1); + + // 6. POST and DELETE returning 408 -> 502 linkedin_outcome_unknown, 1 write attempt each + let post408Attempts = 0; + const requestPost408 = vi.fn(async (url: string) => { + if (url.endsWith("/v2/userinfo")) return jsonResponse({ sub: "member42", name: "Alex" }); + post408Attempts++; + return new Response("Request Timeout", { status: 408 }); + }); + await expect( + linkedInClient({ Authorization: "Bearer tok-408" }, requestPost408).invoke("linkedin_create_post", { + text: "Hello", + }), + ).rejects.toMatchObject({ + status: 502, + details: { code: "linkedin_outcome_unknown" }, + message: expect.stringMatching(/inspect LinkedIn before retrying/), + }); + expect(post408Attempts).toBe(1); + + let delete408Attempts = 0; + const requestDel408 = vi.fn(async () => { + delete408Attempts++; + return new Response("Request Timeout", { status: 408 }); + }); + await expect( + linkedInClient({ Authorization: "Bearer tok-del408" }, requestDel408).invoke("linkedin_delete_post", { + postUrn: "urn:li:share:12345", + }), + ).rejects.toMatchObject({ + status: 502, + details: { code: "linkedin_outcome_unknown" }, + message: expect.stringMatching(/inspect LinkedIn before retrying/), + }); + expect(delete408Attempts).toBe(1); + + // 7. Successful 2xx write with unparseable JSON body -> 502 linkedin_outcome_unknown (reads still fail as linkedin_invalid_response) + let postBadJsonAttempts = 0; + const requestPostBadJson = vi.fn(async (url: string) => { + if (url.endsWith("/v2/userinfo")) return jsonResponse({ sub: "member42", name: "Alex" }); + postBadJsonAttempts++; + return new Response("not-valid-json", { status: 201, headers: { "Content-Type": "application/json" } }); + }); + await expect( + linkedInClient({ Authorization: "Bearer tok-badjson" }, requestPostBadJson).invoke("linkedin_create_post", { + text: "Hello", + }), + ).rejects.toMatchObject({ + status: 502, + details: { code: "linkedin_outcome_unknown" }, + message: expect.stringMatching(/inspect LinkedIn before retrying/i), + }); + expect(postBadJsonAttempts).toBe(1); + + let deleteBadJsonAttempts = 0; + const requestDelBadJson = vi.fn(async () => { + deleteBadJsonAttempts++; + return new Response("not-valid-json", { status: 200, headers: { "Content-Type": "application/json" } }); + }); + await expect( + linkedInClient({ Authorization: "Bearer tok-delbadjson" }, requestDelBadJson).invoke("linkedin_delete_post", { + postUrn: "urn:li:share:12345", + }), + ).rejects.toMatchObject({ + status: 502, + details: { code: "linkedin_outcome_unknown" }, + message: expect.stringMatching(/inspect LinkedIn before retrying/i), + }); + expect(deleteBadJsonAttempts).toBe(1); + + const requestReadBadJson = vi.fn(async () => new Response("not-valid-json", { status: 200 })); + await expect( + linkedInClient({ Authorization: "Bearer tok-readbadjson" }, requestReadBadJson).probe(), + ).rejects.toMatchObject({ + status: 502, + details: { code: "linkedin_invalid_response" }, + }); + }); +}); diff --git a/server/src/services/connectors/linkedin/index.ts b/server/src/services/connectors/linkedin/index.ts new file mode 100644 index 00000000000..82706f66cde --- /dev/null +++ b/server/src/services/connectors/linkedin/index.ts @@ -0,0 +1,215 @@ +import { HttpError } from "../../../errors.js"; +import { createGovernedRestTransport, type GovernedRestRequest } from "../rest-transport.js"; +import { + LINKEDIN_API_URL, + LINKEDIN_API_VERSION, + linkedInOperations, +} from "./catalog.js"; + +export { + LINKEDIN_API_URL, + LINKEDIN_API_VERSION, + LINKEDIN_METHODS, + LINKEDIN_TOOLS, + linkedInRisk, + isCurrentLinkedInCatalogEntry, + isLinkedInConnection, +} from "./catalog.js"; + +export type LinkedInRequest = GovernedRestRequest; + +const MAX_BYTES = 2 * 1024 * 1024; +const record = (value: unknown): Record => + value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; +const failure = (status: number, code: string, message: string) => + new HttpError(status, message, { code }); + +/** + * Reviewed LinkedIn REST adapter (v1: personal OIDC profile + Share on LinkedIn Posts API). + * Credentials come from the connection grant; the gateway owns company, run, policy, approval, + * and audit enforcement. + */ +export function linkedInClient( + headers: Record, + request: LinkedInRequest, + signal: AbortSignal = AbortSignal.timeout(30_000), + deadlineAt: number = Date.now() + 30_000, +) { + const transport = createGovernedRestTransport({ + headers, + request, + baseUrl: LINKEDIN_API_URL, + maxBytes: MAX_BYTES, + signal, + deadlineAt, + defaultHeaders: { "User-Agent": "Paperclip" }, + errors: { + credentialMissing: { + code: "linkedin_credential_missing", + message: "Reconnect LinkedIn to restore its access token.", + }, + invalidEndpoint: { + code: "linkedin_invalid_endpoint", + message: "Unexpected LinkedIn endpoint.", + }, + deadlineExceeded: { + code: "linkedin_deadline_exceeded", + message: + "The LinkedIn request timed out. A submitted post or deletion may still complete; inspect LinkedIn before retrying.", + }, + inputLimit: { + code: "linkedin_input_limit", + message: "The LinkedIn request exceeds 2 MiB.", + }, + outputLimit: { + code: "linkedin_output_limit", + message: "LinkedIn's response exceeded 2 MiB.", + }, + outcomeUnknown: { + code: "linkedin_outcome_unknown", + transportMessage: () => + "LinkedIn did not return a result. A submitted operation may still complete; inspect LinkedIn before retrying.", + serverErrorMessage: + "LinkedIn returned an uncertain server error after the request was sent. A submitted post or deletion may still have completed; inspect LinkedIn before retrying.", + interruptedMessage: + "LinkedIn's response was interrupted. Inspect LinkedIn before retrying.", + unparseableWriteMessage: + "LinkedIn returned an unreadable response after the write was submitted. Inspect LinkedIn before retrying.", + }, + invalidResponse: { + code: "linkedin_invalid_response", + message: "LinkedIn returned an invalid response.", + }, + httpError: (responseStatus) => { + const status = [400, 401, 403, 404, 409, 422, 429].includes(responseStatus) ? responseStatus : 502; + return failure( + status, + status === 401 || status === 403 ? "linkedin_auth_failed" : "linkedin_request_failed", + status === 401 + ? "LinkedIn rejected the access token. Standard self-serve LinkedIn tokens expire after 60 days; reconnect LinkedIn." + : status === 403 + ? "LinkedIn denied access. Confirm the connected app has Sign In with LinkedIn (OIDC) and Share on LinkedIn enabled, then reconnect." + : status === 429 + ? "LinkedIn rate limited this request. Wait before retrying." + : status === 404 + ? "LinkedIn could not find that post." + : "LinkedIn could not complete this operation. Check the arguments and post state before retrying.", + ); + }, + }, + }); + + function send( + path: string, + method: "GET" | "POST" | "DELETE", + options: { body?: unknown; restApi?: boolean } = {}, + ) { + return transport.send({ + path, + method, + jsonBody: options.body, + headers: options.restApi + ? { + "X-Restli-Protocol-Version": "2.0.0", + "LinkedIn-Version": LINKEDIN_API_VERSION, + } + : undefined, + }); + } + + async function fetchProfile() { + const { body } = await send("/v2/userinfo", "GET"); + const info = record(body); + const sub = typeof info.sub === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(info.sub) ? info.sub : null; + if (!sub) { + throw failure(502, "linkedin_invalid_response", "LinkedIn did not return a valid member identifier."); + } + return transport.sanitize({ + sub, + personUrn: `urn:li:person:${sub}`, + name: typeof info.name === "string" ? info.name : undefined, + givenName: typeof info.given_name === "string" ? info.given_name : undefined, + familyName: typeof info.family_name === "string" ? info.family_name : undefined, + email: typeof info.email === "string" ? info.email : undefined, + picture: typeof info.picture === "string" ? info.picture : undefined, + }) as { + sub: string; + personUrn: string; + name?: string; + givenName?: string; + familyName?: string; + email?: string; + picture?: string; + }; + } + + async function probe() { + const profile = await fetchProfile(); + return { personUrn: profile.personUrn, name: profile.name }; + } + + async function invoke(name: string, parameters: unknown): Promise { + const operation = linkedInOperations.find((candidate) => candidate.name === name); + if (!operation) { + throw failure(404, "linkedin_unknown_tool", `Unknown LinkedIn tool: ${name}`); + } + const parsed = operation.schema.safeParse(parameters ?? {}); + if (!parsed.success) { + throw failure(422, "linkedin_invalid_arguments", parsed.error.issues[0]?.message ?? "Invalid LinkedIn arguments."); + } + + if (operation.name === "linkedin_get_profile") { + return fetchProfile(); + } + + if (operation.name === "linkedin_create_post") { + const input = parsed.data as { + text: string; + visibility?: "PUBLIC" | "CONNECTIONS"; + article?: { source: string; title: string; description?: string }; + }; + // Always derive the author URN from the authenticated grant — never accept caller-supplied author URNs. + const profile = await fetchProfile(); + const visibility = input.visibility ?? "PUBLIC"; + const payload: Record = { + author: profile.personUrn, + commentary: input.text, + visibility, + distribution: { + feedDistribution: "MAIN_FEED", + targetEntities: [], + thirdPartyDistributionChannels: [], + }, + lifecycleState: "PUBLISHED", + isReshareDisabledByAuthor: false, + }; + if (input.article) { + payload.content = { + article: { + source: input.article.source, + title: input.article.title, + ...(input.article.description ? { description: input.article.description } : {}), + }, + }; + } + const response = await send("/rest/posts", "POST", { body: payload, restApi: true }); + const postUrn = response.headers.get("x-restli-id") ?? record(response.body).id ?? null; + return transport.sanitize({ + created: true, + author: profile.personUrn, + visibility, + postUrn: typeof postUrn === "string" ? postUrn : null, + }); + } + + if (operation.name === "linkedin_delete_post") { + const { postUrn } = parsed.data as { postUrn: string }; + await send(`/rest/posts/${encodeURIComponent(postUrn)}`, "DELETE", { restApi: true }); + return transport.sanitize({ deleted: true, postUrn }); + } + + throw failure(404, "linkedin_unknown_tool", `Unknown LinkedIn tool: ${name}`); + } + + return { probe, invoke }; +} diff --git a/server/src/services/connectors/rest-registry.ts b/server/src/services/connectors/rest-registry.ts index 9de8d694d71..4ccd1f3997e 100644 --- a/server/src/services/connectors/rest-registry.ts +++ b/server/src/services/connectors/rest-registry.ts @@ -1,4 +1,5 @@ import type { ToolRiskLevel } from "@paperclipai/shared"; +import { LINKEDIN_TOOLS, isLinkedInConnection, isCurrentLinkedInCatalogEntry, linkedInClient, linkedInRisk } from "./linkedin/index.js"; import { SUPABASE_TOOLS, isSupabaseConnection, isCurrentSupabaseCatalogEntry, supabaseClient, supabaseRisk } from "./supabase/index.js"; import { VERCEL_TOOLS, isVercelConnection, isCurrentVercelCatalogEntry, vercelClient, vercelRisk } from "./vercel/index.js"; @@ -40,6 +41,13 @@ export const REST_CONNECTORS: readonly RestConnector[] = [ client: (connection, headers, request, signal, deadlineAt) => vercelClient(headers, request, settings(connection).teamId, signal, deadlineAt), }, + { + sourceTemplateKey: "linkedin", name: "LinkedIn", + matches: isLinkedInConnection, tools: LINKEDIN_TOOLS, + risk: linkedInRisk, isCurrent: isCurrentLinkedInCatalogEntry, + client: (_connection, headers, request, signal, deadlineAt) => + linkedInClient(headers, request, signal, deadlineAt), + }, ]; export function restConnectorFor(connection: Connection): RestConnector | undefined { diff --git a/server/src/services/connectors/rest-transport.test.ts b/server/src/services/connectors/rest-transport.test.ts new file mode 100644 index 00000000000..6cdc35ee57b --- /dev/null +++ b/server/src/services/connectors/rest-transport.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it, vi } from "vitest"; +import { HttpError } from "../../errors.js"; +import { createGovernedRestTransport, extractBearerAuthorization, redactorFor, type GovernedRestRequest } from "./rest-transport.js"; + +function makeTransport( + request: (url: string, init: RequestInit) => Promise, + overrides: { + baseUrl?: string; + headers?: Record; + maxBytes?: number; + signal?: AbortSignal; + deadlineAt?: number; + } = {}, +) { + return createGovernedRestTransport({ + headers: overrides.headers ?? { Authorization: "Bearer test-secret-token" }, + request, + baseUrl: overrides.baseUrl ?? "https://api.example.test", + maxBytes: overrides.maxBytes ?? 1024, + signal: overrides.signal, + deadlineAt: overrides.deadlineAt, + defaultHeaders: { "User-Agent": "Paperclip" }, + errors: { + credentialMissing: { code: "test_credential_missing", message: "Missing bearer credential." }, + invalidEndpoint: { code: "test_invalid_endpoint", message: "Unexpected endpoint." }, + deadlineExceeded: { code: "test_deadline_exceeded", message: "Timed out; inspect before retrying." }, + inputLimit: { code: "test_input_limit", message: "Request too large." }, + outputLimit: { code: "test_output_limit", message: "Response too large." }, + outcomeUnknown: { + code: "test_outcome_unknown", + transportMessage: (isWrite) => (isWrite ? "Write transport failed." : "Read transport failed."), + serverErrorMessage: "Uncertain server error after write.", + interruptedMessage: "Response interrupted.", + unparseableWriteMessage: "Unreadable response after write.", + }, + invalidResponse: { code: "test_invalid_response", message: "Invalid JSON response." }, + httpError: (status) => new HttpError(status >= 500 ? 502 : status, `HTTP ${status}`, { code: "test_http_error" }), + }, + }); +} + +describe("governed REST transport", () => { + it("validates Bearer authorization without echoing rejected credentials", () => { + const secret = "super-secret-value"; + expect(() => + extractBearerAuthorization( + { authorization: `Bearer ${secret}\r\nX-Injected: 1` }, + { code: "cred_missing", message: "Reconnect to restore token." }, + ), + ).toThrow("Reconnect to restore token."); + expect( + extractBearerAuthorization( + { authorization: `Bearer ${secret}` }, + { code: "cred_missing", message: "Reconnect to restore token." }, + ), + ).toEqual({ authorization: `Bearer ${secret}`, token: secret }); + }); + + it("redacts exact tokens in nested strings and object keys", () => { + const token = "tok-canary-9876"; + const sanitize = redactorFor(token); + expect(sanitize({ [token]: [`prefix ${token}`, { nested: token }] })).toEqual({ + "[REDACTED]": ["prefix [REDACTED]", { nested: "[REDACTED]" }], + }); + }); + + it("pins requests to the configured origin and base path prefix", async () => { + const request = vi.fn(async () => Response.json({ ok: true })); + const transport = makeTransport(request, { baseUrl: "https://api.example.test/v1/projects/abc" }); + + await expect(transport.send({ path: "/items", method: "GET" })).resolves.toMatchObject({ body: { ok: true } }); + expect(request.mock.calls[0]?.[0]).toBe("https://api.example.test/v1/projects/abc/items"); + expect(request.mock.calls[0]?.[1]?.redirect).toBe("error"); + + for (const badPath of [ + "https://evil.example.test/v1/projects/abc/items", + "//evil.example.test/items", + "/../other-project/items", + ]) { + await expect(transport.send({ path: badPath, method: "GET" })).rejects.toMatchObject({ + status: 400, + details: { code: "test_invalid_endpoint" }, + }); + } + expect(request).toHaveBeenCalledTimes(1); + }); + + it("maps write 408/5xx and unparseable 2xx write bodies to outcome_unknown while reads fail as invalid_response", async () => { + const request408 = vi.fn(async () => new Response("timeout", { status: 408 })); + const transport408 = makeTransport(request408); + await expect(transport408.send({ path: "/posts", method: "POST", jsonBody: { a: 1 } })).rejects.toMatchObject({ + status: 502, + details: { code: "test_outcome_unknown" }, + }); + await expect(transport408.send({ path: "/posts/1", method: "DELETE" })).rejects.toMatchObject({ + status: 502, + details: { code: "test_outcome_unknown" }, + }); + + const requestBadJson = vi.fn(async () => new Response("not-json", { status: 201 })); + const transportBadJson = makeTransport(requestBadJson); + await expect(transportBadJson.send({ path: "/posts", method: "POST", jsonBody: { a: 1 } })).rejects.toMatchObject({ + status: 502, + details: { code: "test_outcome_unknown" }, + }); + await expect(transportBadJson.send({ path: "/posts", method: "GET" })).rejects.toMatchObject({ + status: 502, + details: { code: "test_invalid_response" }, + }); + }); + + it("never confuses an untrusted 504 HttpError with the local deadline and enforces output byte caps", async () => { + const forged = new HttpError(504, "forged leak", { code: "test_deadline_exceeded" }); + const transportForged = makeTransport(async () => { + throw forged; + }); + await expect(transportForged.send({ path: "/items", method: "POST", jsonBody: {} })).rejects.toMatchObject({ + status: 502, + details: { code: "test_outcome_unknown" }, + }); + + const cancel = vi.fn(async () => {}); + const transportBig = makeTransport( + async () => + ({ + ok: true, + status: 200, + headers: new Headers(), + body: { + getReader: () => ({ + read: async () => ({ done: false, value: new Uint8Array(2048) }), + cancel, + }), + } as unknown as ReadableStream, + }) as unknown as Response, + { maxBytes: 1024 }, + ); + await expect(transportBig.send({ path: "/items", method: "GET" })).rejects.toMatchObject({ + status: 502, + details: { code: "test_output_limit" }, + }); + expect(cancel).toHaveBeenCalledTimes(1); + }); + + it("maps oversized or stalled 2xx write bodies to outcome_unknown instead of retryable errors", async () => { + const cancelOversized = vi.fn(async () => {}); + const transportOversized = makeTransport( + async () => + ({ + ok: true, + status: 201, + headers: new Headers(), + body: { + getReader: () => ({ + read: async () => ({ done: false, value: new Uint8Array(2048) }), + cancel: cancelOversized, + }), + } as unknown as ReadableStream, + }) as unknown as Response, + { maxBytes: 1024 }, + ); + await expect( + transportOversized.send({ path: "/posts", method: "POST", jsonBody: { text: "hello" } }), + ).rejects.toMatchObject({ + status: 502, + message: "Response interrupted.", + details: { code: "test_outcome_unknown" }, + }); + expect(cancelOversized).toHaveBeenCalledTimes(1); + + const cancelStalled = vi.fn(async () => {}); + const transportStalled = makeTransport( + async () => + ({ + ok: true, + status: 200, + headers: new Headers(), + body: { + getReader: () => ({ + read: () => new Promise>(() => {}), + cancel: cancelStalled, + }), + } as unknown as ReadableStream, + }) as unknown as Response, + { deadlineAt: Date.now() + 25 }, + ); + await expect(transportStalled.send({ path: "/posts/1", method: "DELETE" })).rejects.toMatchObject({ + status: 502, + message: "Response interrupted.", + details: { code: "test_outcome_unknown" }, + }); + expect(cancelStalled).toHaveBeenCalledTimes(1); + }); +}); diff --git a/server/src/services/connectors/rest-transport.ts b/server/src/services/connectors/rest-transport.ts new file mode 100644 index 00000000000..5169b2242ae --- /dev/null +++ b/server/src/services/connectors/rest-transport.ts @@ -0,0 +1,264 @@ +import { HttpError } from "../../errors.js"; +import { redactSensitiveText } from "../../redaction.js"; + +export type GovernedRestRequest = (url: string, init: RequestInit) => Promise; + +export interface GovernedRestErrors { + credentialMissing: { code: string; message: string; pattern?: RegExp }; + invalidEndpoint: { code: string; message: string }; + deadlineExceeded: { code: string; message: string }; + inputLimit: { code: string; message: string }; + outputLimit: { code: string; message: string }; + outcomeUnknown: { + code: string; + transportMessage: (isWrite: boolean) => string; + serverErrorMessage: string; + interruptedMessage: string; + unparseableWriteMessage: string; + }; + invalidResponse: { code: string; message: string }; + httpError: (status: number) => HttpError; +} + +export interface GovernedRestTransportOptions { + headers: Record; + request: GovernedRestRequest; + baseUrl: string; + maxBytes: number; + signal?: AbortSignal; + deadlineAt?: number; + defaultHeaders?: Record; + errors: GovernedRestErrors; +} + +export interface GovernedSendOptions { + path: string; + method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; + query?: Record; + jsonBody?: unknown; + rawBody?: BodyInit; + headers?: Record; +} + +export interface GovernedRestResponse { + body: unknown; + headers: Headers; + status: number; +} + +export function extractBearerAuthorization( + headers: Record, + error: { code: string; message: string; pattern?: RegExp }, +): { authorization: string; token: string } { + // Validate Authorization before constructing Headers so rejected tokens cannot echo in exceptions. + const authorization = Object.entries(headers).find(([key]) => key.toLowerCase() === "authorization")?.[1]; + const pattern = error.pattern ?? /^Bearer [^\r\n]+$/; + if (!authorization || !pattern.test(authorization)) { + throw new HttpError(422, error.message, { code: error.code }); + } + return { authorization, token: authorization.slice(7) }; +} + +export function redactorFor(token: string) { + function sanitize(value: unknown): unknown { + if (typeof value === "string") return redactSensitiveText(value.split(token).join("[REDACTED]")); + if (Array.isArray(value)) return value.map(sanitize); + if (value && typeof value === "object") { + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [ + redactSensitiveText(key.split(token).join("[REDACTED]")), + sanitize(item), + ]), + ); + } + return value; + } + return sanitize; +} + +export function createGovernedRestTransport(options: GovernedRestTransportOptions) { + const { + headers, + request, + baseUrl, + maxBytes, + signal = AbortSignal.timeout(30_000), + deadlineAt = Date.now() + 30_000, + defaultHeaders = {}, + errors, + } = options; + + const { authorization, token } = extractBearerAuthorization(headers, errors.credentialMissing); + const sanitize = redactorFor(token); + const base = new URL(baseUrl); + const basePrefix = base.pathname.replace(/\/$/, ""); + + const deadlineError = new HttpError(504, errors.deadlineExceeded.message, { + code: errors.deadlineExceeded.code, + }); + const outputLimitError = new HttpError(502, errors.outputLimit.message, { + code: errors.outputLimit.code, + }); + + async function withinDeadline(work: () => Promise): Promise { + const remaining = deadlineAt - Date.now(); + if (signal.aborted || remaining <= 0) throw deadlineError; + let abort!: () => void; + let timer: ReturnType | undefined; + try { + return await Promise.race([ + Promise.resolve().then(() => { + if (signal.aborted || Date.now() >= deadlineAt) throw deadlineError; + return work(); + }), + new Promise((_resolve, reject) => { + abort = () => reject(deadlineError); + signal.addEventListener("abort", abort, { once: true }); + timer = setTimeout(abort, remaining); + }), + ]); + } finally { + signal.removeEventListener("abort", abort); + if (timer) clearTimeout(timer); + } + } + + async function send(sendOptions: GovernedSendOptions): Promise { + const method = sendOptions.method ?? "GET"; + const isWrite = method !== "GET"; + + let url: URL; + try { + if (sendOptions.path.startsWith("//")) { + throw new HttpError(400, errors.invalidEndpoint.message, { code: errors.invalidEndpoint.code }); + } + if (sendOptions.path.startsWith("http://") || sendOptions.path.startsWith("https://")) { + url = new URL(sendOptions.path); + } else { + const suffix = + sendOptions.path === "" || sendOptions.path.startsWith("/") || sendOptions.path.startsWith("?") + ? sendOptions.path + : `/${sendOptions.path}`; + url = new URL(`${basePrefix}${suffix}`, base.origin); + } + } catch { + throw new HttpError(400, errors.invalidEndpoint.message, { code: errors.invalidEndpoint.code }); + } + + if ( + url.origin !== base.origin + || (basePrefix && url.pathname !== basePrefix && !url.pathname.startsWith(`${basePrefix}/`)) + ) { + throw new HttpError(400, errors.invalidEndpoint.message, { code: errors.invalidEndpoint.code }); + } + + if (sendOptions.query) { + for (const [key, value] of Object.entries(sendOptions.query)) { + if (value !== undefined) url.searchParams.set(key, String(value)); + } + } + + let body: BodyInit | undefined; + let hasJsonBody = false; + if (sendOptions.jsonBody !== undefined) { + const serialized = JSON.stringify(sendOptions.jsonBody); + if (Buffer.byteLength(serialized) > maxBytes) { + throw new HttpError(422, errors.inputLimit.message, { code: errors.inputLimit.code }); + } + body = serialized; + hasJsonBody = true; + } else if (sendOptions.rawBody !== undefined) { + if (typeof sendOptions.rawBody === "string" && Buffer.byteLength(sendOptions.rawBody) > maxBytes) { + throw new HttpError(422, errors.inputLimit.message, { code: errors.inputLimit.code }); + } + if (Buffer.isBuffer(sendOptions.rawBody) && sendOptions.rawBody.byteLength > maxBytes) { + throw new HttpError(422, errors.inputLimit.message, { code: errors.inputLimit.code }); + } + body = sendOptions.rawBody; + } + + const requestHeaders: Record = { + ...defaultHeaders, + ...(hasJsonBody ? { "Content-Type": "application/json" } : {}), + ...sendOptions.headers, + Authorization: authorization, + }; + + let response: Response; + try { + response = await withinDeadline(() => + request(url.href, { + method, + headers: requestHeaders, + redirect: "error", + signal, + ...(body === undefined ? {} : { body }), + }), + ); + } catch (error) { + // The local timer is authoritative even if wall-clock time moved back or + // the timer fired just before Date.now() reaches the absolute deadline. + if (error === deadlineError || signal.aborted || Date.now() >= deadlineAt) throw deadlineError; + throw new HttpError(502, errors.outcomeUnknown.transportMessage(isWrite), { + code: errors.outcomeUnknown.code, + }); + } + + if (!response.ok) { + void response.body?.cancel().catch(() => {}); + if (isWrite && (response.status >= 500 || response.status === 408)) { + throw new HttpError(502, errors.outcomeUnknown.serverErrorMessage, { + code: errors.outcomeUnknown.code, + }); + } + throw errors.httpError(response.status); + } + + if (response.status === 204 || !response.body) { + return { body: null, headers: response.headers, status: response.status }; + } + + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + for (;;) { + const part = await withinDeadline(() => reader.read()); + if (part.done) break; + length += part.value.byteLength; + if (length > maxBytes) throw outputLimitError; + chunks.push(part.value); + } + } catch (error) { + if (!isWrite && (error === deadlineError || error === outputLimitError)) throw error; + throw new HttpError(502, errors.outcomeUnknown.interruptedMessage, { + code: errors.outcomeUnknown.code, + }); + } finally { + void reader.cancel().catch(() => {}); + } + + if (!length) { + return { body: null, headers: response.headers, status: response.status }; + } + + try { + return { + body: JSON.parse(Buffer.concat(chunks).toString("utf8")), + headers: response.headers, + status: response.status, + }; + } catch { + if (isWrite) { + throw new HttpError(502, errors.outcomeUnknown.unparseableWriteMessage, { + code: errors.outcomeUnknown.code, + }); + } + throw new HttpError(502, errors.invalidResponse.message, { + code: errors.invalidResponse.code, + }); + } + } + + return { withinDeadline, sanitize, send }; +} diff --git a/server/src/services/connectors/supabase/index.ts b/server/src/services/connectors/supabase/index.ts index bc54940f180..e9518cceae9 100644 --- a/server/src/services/connectors/supabase/index.ts +++ b/server/src/services/connectors/supabase/index.ts @@ -1,11 +1,11 @@ import { z } from "zod"; import { HttpError } from "../../../errors.js"; -import { redactSensitiveText } from "../../../redaction.js"; import { descriptorHash, stableHash } from "../../tool-catalog-hash.js"; +import { createGovernedRestTransport, type GovernedRestRequest } from "../rest-transport.js"; export const SUPABASE_API_URL = "https://api.supabase.com/v1"; export const SUPABASE_METHOD = "management-api"; -export type SupabaseRequest = (url: string, init: RequestInit) => Promise; +export type SupabaseRequest = GovernedRestRequest; const MAX_BYTES = 2 * 1024 * 1024; const projectRefSchema = z.string().regex(/^[a-z]{20}$/); const slugSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/); @@ -84,35 +84,49 @@ const functionFields = ["id", "slug", "name", "status", "version", "created_at", export function supabaseClient(headers: Record, request: SupabaseRequest, projectRef: unknown, signal: AbortSignal = AbortSignal.timeout(30_000), deadlineAt: number = Date.now() + 30_000) { if (!projectRefSchema.safeParse(projectRef).success) throw fail(422, "supabase_project_invalid", "Reconnect Supabase with a valid project reference."); - const authorization = new Headers(headers).get("Authorization"); - if (!authorization || !/^Bearer \S+$/.test(authorization)) throw fail(422, "supabase_credential_missing", "Reconnect Supabase with a personal access token."); - const secret = authorization.slice(7); - const base = `${SUPABASE_API_URL}/projects/${projectRef}`; - const deadlineError = fail(504, "supabase_deadline_exceeded", "The Supabase action deadline expired. Inspect the provider state before retrying a write."); - const outputLimitError = fail(502, "supabase_output_limit", "Supabase returned an oversized response."); - const expired = () => deadlineError; - async function bounded(work: () => Promise): Promise { - const remaining = deadlineAt - Date.now(); - if (signal.aborted || remaining <= 0) throw expired(); - let timer: ReturnType | undefined; - let abort: () => void = () => {}; - try { - return await Promise.race([ - Promise.resolve().then(() => { if (signal.aborted || Date.now() >= deadlineAt) throw expired(); return work(); }), - new Promise((_resolve, reject) => { - abort = () => reject(expired()); - signal.addEventListener("abort", abort, { once: true }); - timer = setTimeout(abort, remaining); - }), - ]); - } finally { if (timer) clearTimeout(timer); signal.removeEventListener("abort", abort); } - } - function sanitize(value: unknown): unknown { - if (typeof value === "string") return redactSensitiveText(value.split(secret).join("[REDACTED]")); - if (Array.isArray(value)) return value.map(sanitize); - if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [redactSensitiveText(key.split(secret).join("[REDACTED]")), sanitize(item)])); - return value; - } + const transport = createGovernedRestTransport({ + headers, + request, + baseUrl: `${SUPABASE_API_URL}/projects/${projectRef}`, + maxBytes: MAX_BYTES, + signal, + deadlineAt, + defaultHeaders: { Accept: "application/json" }, + errors: { + credentialMissing: { + code: "supabase_credential_missing", + message: "Reconnect Supabase with a personal access token.", + pattern: /^Bearer \S+$/, + }, + invalidEndpoint: { code: "supabase_invalid_endpoint", message: "Unexpected Supabase endpoint." }, + deadlineExceeded: { + code: "supabase_deadline_exceeded", + message: "The Supabase action deadline expired. Inspect the provider state before retrying a write.", + }, + inputLimit: { code: "supabase_input_limit", message: "Supabase source files exceed the upload limit." }, + outputLimit: { code: "supabase_output_limit", message: "Supabase returned an oversized response." }, + outcomeUnknown: { + code: "supabase_outcome_unknown", + transportMessage: (isWrite) => + isWrite + ? "Supabase did not return a result. The operation may have completed; inspect its state before retrying." + : "Supabase could not complete this request.", + serverErrorMessage: "Supabase reported an error after this write. The operation may have completed; inspect its state before retrying.", + interruptedMessage: "Supabase's response was interrupted. Inspect the operation before retrying.", + unparseableWriteMessage: "Supabase returned an unreadable response after this write. The operation may have completed; inspect its state before retrying.", + }, + invalidResponse: { code: "supabase_invalid_response", message: "Supabase returned an invalid response." }, + httpError: (responseStatus) => { + const status = [400, 401, 402, 403, 404, 409, 422, 429].includes(responseStatus) ? responseStatus : 502; + return fail(status, "supabase_request_failed", status === 401 || status === 403 + ? "Supabase denied access. Reconnect with a personal access token authorized for this project and action." + : status === 402 ? "Supabase requires an account or billing change for this operation." + : status === 429 ? "Supabase rate limited this request. Wait before retrying." + : status === 404 ? "Supabase could not find this project or function." : "Supabase could not complete this operation."); + }, + }, + }); + const { withinDeadline: bounded, sanitize } = transport; // Auth and PostgREST responses can include secrets. Positive field selection // happens before the result reaches gateway/audit serialization. function select(value: unknown, fields: readonly string[]) { @@ -120,52 +134,14 @@ export function supabaseClient(headers: Record, request: Supabas return sanitize(Object.fromEntries(fields.filter(key => data[key] === null || ["string", "number", "boolean"].includes(typeof data[key])).map(key => [key, data[key]]))); } - async function send(path: string, method = "GET", body?: BodyInit, contentType?: string): Promise { - let response: Response; - try { - response = await bounded(() => request(base + path, { - method, body, redirect: "error", signal, - headers: { Authorization: authorization!, Accept: "application/json", ...(contentType ? { "Content-Type": contentType } : {}) }, - })); - } catch (error) { - // The local timer is authoritative even if wall-clock time moved back or - // the timer fired just before Date.now() reaches the absolute deadline. - if (error === deadlineError || signal.aborted || Date.now() >= deadlineAt) throw expired(); - throw fail(502, "supabase_outcome_unknown", method === "GET" ? "Supabase could not complete this request." : "Supabase did not return a result. The operation may have completed; inspect its state before retrying."); - } - if (!response.ok) { - void response.body?.cancel().catch(() => {}); - // Configuration may be applied before the provider reports a restart - // failure. A server error is not proof that a write had no effect. - if (method !== "GET" && (response.status >= 500 || response.status === 408)) { - throw fail(502, "supabase_outcome_unknown", "Supabase reported an error after this write. The operation may have completed; inspect its state before retrying."); - } - const status = [400, 401, 402, 403, 404, 409, 422, 429].includes(response.status) ? response.status : 502; - throw fail(status, "supabase_request_failed", status === 401 || status === 403 - ? "Supabase denied access. Reconnect with a personal access token authorized for this project and action." - : status === 402 ? "Supabase requires an account or billing change for this operation." - : status === 429 ? "Supabase rate limited this request. Wait before retrying." - : status === 404 ? "Supabase could not find this project or function." : "Supabase could not complete this operation."); - } - if (response.status === 204 || !response.body) return null; - const reader = response.body.getReader(); - const chunks: Uint8Array[] = []; - let size = 0; - try { - for (;;) { - const part = await bounded(() => reader.read()); - if (part.done) break; - size += part.value.byteLength; - if (size > MAX_BYTES) throw outputLimitError; - chunks.push(part.value); - } - } catch (error) { - if (error === deadlineError || error === outputLimitError) throw error; - throw fail(502, "supabase_outcome_unknown", "Supabase's response was interrupted. Inspect the operation before retrying."); - } finally { void reader.cancel().catch(() => {}); } - if (!size) return null; - try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); } - catch { throw fail(502, "supabase_invalid_response", "Supabase returned an invalid response."); } + async function send(path: string, method: "GET" | "POST" | "PATCH" | "DELETE" = "GET", body?: BodyInit, contentType?: string): Promise { + const response = await transport.send({ + path, + method, + rawBody: body, + headers: contentType ? { "Content-Type": contentType } : undefined, + }); + return response.body; } async function invoke(name: string, parameters: unknown): Promise { const operation = operations.find(candidate => candidate.name === name); diff --git a/server/src/services/connectors/vercel/index.ts b/server/src/services/connectors/vercel/index.ts index ea2ac413cc6..5b4621b83ff 100644 --- a/server/src/services/connectors/vercel/index.ts +++ b/server/src/services/connectors/vercel/index.ts @@ -1,9 +1,9 @@ import { HttpError } from "../../../errors.js"; -import { redactSensitiveText } from "../../../redaction.js"; +import { createGovernedRestTransport, type GovernedRestRequest } from "../rest-transport.js"; import { VERCEL_API_URL, vercelOperations, vercelTeamIdSchema } from "./catalog.js"; export { VERCEL_API_URL, VERCEL_METHOD, VERCEL_TOOLS, vercelRisk, isCurrentVercelCatalogEntry, isVercelConnection } from "./catalog.js"; -export type VercelRequest = (url: string, init: RequestInit) => Promise; +export type VercelRequest = GovernedRestRequest; const MAX_BYTES = 4 * 1024 * 1024; const record = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; const failure = (status: number, code: string, message: string) => new HttpError(status, message, { code }); @@ -22,81 +22,46 @@ function collection(value: Record, key: string): unknown[] { * the gateway owns company, run, policy, approval and audit enforcement. */ export function vercelClient(headers: Record, request: VercelRequest, configuredTeamId: unknown, signal: AbortSignal = AbortSignal.timeout(30_000), deadlineAt: number = Date.now() + 30_000) { - // Do not pass unvalidated credentials through Headers: its validation error - // can echo the rejected value into a logged exception. - const authorization = Object.entries(headers).find(([key]) => key.toLowerCase() === "authorization")?.[1]; - if (!authorization || !/^Bearer [^\r\n]+$/.test(authorization)) throw failure(422, "vercel_credential_missing", "Reconnect Vercel to restore its access token."); + const transport = createGovernedRestTransport({ + headers, + request, + baseUrl: VERCEL_API_URL, + maxBytes: MAX_BYTES, + signal, + deadlineAt, + defaultHeaders: { "Content-Type": "application/json", "User-Agent": "Paperclip" }, + errors: { + credentialMissing: { code: "vercel_credential_missing", message: "Reconnect Vercel to restore its access token." }, + invalidEndpoint: { code: "vercel_invalid_endpoint", message: "Unexpected Vercel endpoint." }, + deadlineExceeded: { code: "vercel_deadline_exceeded", message: "The Vercel request timed out. A submitted operation may still complete; inspect its state before retrying." }, + inputLimit: { code: "vercel_input_limit", message: "The Vercel request exceeds 4 MiB. Use a Git deployment for larger projects." }, + outputLimit: { code: "vercel_output_limit", message: "Vercel's response exceeded 4 MiB. Request a smaller page." }, + outcomeUnknown: { + code: "vercel_outcome_unknown", + transportMessage: () => "Vercel did not return a result. A submitted operation may still complete; inspect its state before retrying.", + serverErrorMessage: "Vercel reported an error after this write. The operation may have completed; inspect its state before retrying.", + interruptedMessage: "Vercel's response was interrupted. Inspect the operation before retrying.", + unparseableWriteMessage: "Vercel returned an unreadable response after the write was submitted. Inspect its state before retrying.", + }, + invalidResponse: { code: "vercel_invalid_response", message: "Vercel returned an invalid response." }, + httpError: (responseStatus) => { + const status = [400, 401, 402, 403, 404, 409, 422, 429].includes(responseStatus) ? responseStatus : 502; + return failure(status, "vercel_request_failed", status === 401 || status === 403 + ? "Vercel denied access. Check the access token's team scope, expiration and role, then reconnect." + : status === 429 ? "Vercel rate limited this request. Wait before retrying." + : status === 404 ? "Vercel could not find this resource in the connected team." + : status === 402 ? "Vercel requires a plan or billing change for this operation." + : "Vercel could not complete this operation. Check the arguments and resource state before retrying."); + }, + }, + }); const parsedTeam = vercelTeamIdSchema.safeParse(configuredTeamId); if (!parsedTeam.success) throw failure(422, "vercel_team_required", "Configure the Vercel team ID for this connection."); const teamId = parsedTeam.data; - const token = authorization.slice(7); - const deadlineError = failure(504, "vercel_deadline_exceeded", "The Vercel request timed out. A submitted operation may still complete; inspect its state before retrying."); - - async function withinDeadline(work: () => Promise): Promise { - if (signal.aborted || Date.now() >= deadlineAt) throw deadlineError; - let abort!: () => void; - let timer: ReturnType | undefined; - try { - return await Promise.race([ - Promise.resolve().then(() => { if (signal.aborted || Date.now() >= deadlineAt) throw deadlineError; return work(); }), - new Promise((_resolve, reject) => { - abort = () => reject(deadlineError); - signal.addEventListener("abort", abort, { once: true }); - timer = setTimeout(abort, Math.max(0, deadlineAt - Date.now())); - }), - ]); - } finally { signal.removeEventListener("abort", abort); if (timer) clearTimeout(timer); } - } - function sanitize(value: unknown): unknown { - if (typeof value === "string") return redactSensitiveText(value.split(token).join("[REDACTED]")); - if (Array.isArray(value)) return value.map(sanitize); - if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key.split(token).join("[REDACTED]"), sanitize(item)])); - return value; - } - async function send(path: string, method = "GET", body?: unknown, query: Record = {}): Promise { - const url = new URL(path, VERCEL_API_URL); - for (const [key, value] of Object.entries(query)) if (value !== undefined) url.searchParams.set(key, String(value)); - url.searchParams.set("teamId", teamId); - const serialized = body === undefined ? undefined : JSON.stringify(body); - if (serialized && Buffer.byteLength(serialized) > MAX_BYTES) throw failure(422, "vercel_input_limit", "The Vercel request exceeds 4 MiB. Use a Git deployment for larger projects."); - let response: Response; - try { - response = await withinDeadline(() => request(url.href, { method, headers: { Authorization: authorization!, "Content-Type": "application/json", "User-Agent": "Paperclip" }, - redirect: "error", signal, ...(serialized === undefined ? {} : { body: serialized }) })); - } catch (error) { - if (error === deadlineError || signal.aborted || Date.now() >= deadlineAt) throw deadlineError; - throw failure(502, "vercel_outcome_unknown", "Vercel did not return a result. A submitted operation may still complete; inspect its state before retrying."); - } - if (!response.ok) { - void response.body?.cancel().catch(() => {}); - const status = [400, 401, 402, 403, 404, 409, 422, 429].includes(response.status) ? response.status : 502; - throw failure(status, "vercel_request_failed", status === 401 || status === 403 - ? "Vercel denied access. Check the access token's team scope, expiration and role, then reconnect." - : status === 429 ? "Vercel rate limited this request. Wait before retrying." - : status === 404 ? "Vercel could not find this resource in the connected team." - : status === 402 ? "Vercel requires a plan or billing change for this operation." - : "Vercel could not complete this operation. Check the arguments and resource state before retrying."); - } - if (response.status === 204 || !response.body) return null; - const reader = response.body.getReader(); - const chunks: Uint8Array[] = []; - let length = 0; - const outputLimitError = failure(502, "vercel_output_limit", "Vercel's response exceeded 4 MiB. Request a smaller page."); - try { - for (;;) { - const part = await withinDeadline(() => reader.read()); - if (part.done) break; - length += part.value.byteLength; - if (length > MAX_BYTES) throw outputLimitError; - chunks.push(part.value); - } - } catch (error) { - if (error === deadlineError || error === outputLimitError) throw error; - throw failure(502, "vercel_outcome_unknown", "Vercel's response was interrupted. Inspect the operation before retrying."); - } finally { void reader.cancel().catch(() => {}); } - if (!length) return null; - try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); } - catch { throw failure(502, "vercel_invalid_response", "Vercel returned an invalid response."); } + const { sanitize } = transport; + async function send(path: string, method: "GET" | "POST" | "PATCH" | "DELETE" = "GET", body?: unknown, query: Record = {}): Promise { + const response = await transport.send({ path, method, jsonBody: body, query: { ...query, teamId } }); + return response.body; } function assertProject(value: unknown, requested?: string) { const project = record(value); diff --git a/server/src/services/paperclip-cloud-connector.test.ts b/server/src/services/paperclip-cloud-connector.test.ts index 43912d96379..b841d353871 100644 --- a/server/src/services/paperclip-cloud-connector.test.ts +++ b/server/src/services/paperclip-cloud-connector.test.ts @@ -474,6 +474,40 @@ describe("Paperclip Cloud connector", () => { else await expect(result).rejects.toMatchObject({ code: "CONNECTOR_BAD_RESPONSE" }); }); + it.each([ + ["https://www.linkedin.com/oauth/v2/authorization?client_id=client&state=broker-state", true], + ["https://api.linkedin.com/oauth/v2/authorization", false], + ["https://www.linkedin.com/other", false], + ])("validates LinkedIn's exact v2 authorization endpoint %s", async (authorizationUrl, accepted) => { + const keys = config(); + const connector = createPaperclipCloudConnector({ + config: keys.config, + request: vi.fn(async (_url, init) => { + const body = JSON.parse(String(init?.body)); + const claims = JSON.parse(Buffer.from(body.request.split(".")[1], "base64url").toString("utf8")); + expect(claims).toMatchObject({ + prv: "linkedin", + prf: "linkedin.share", + scp: ["openid", "profile", "email", "w_member_social"], + }); + return Response.json({ + confirmationUrl: "https://my.example.test/connections/confirm?session=test", + authorizationUrl, + expiresAt: "2099-01-01T00:00:00Z", + }); + }) as typeof fetch, + }); + const result = connector.startAuthorization({ + subject, + companyId, + profile: "linkedin.share", + returnUri: "https://paperclip.example.test/api/tools/oauth/cloud-connector/callback", + returnState: "state", + }); + if (accepted) await expect(result).resolves.toMatchObject({ authorizationUrl }); + else await expect(result).rejects.toMatchObject({ code: "CONNECTOR_BAD_RESPONSE" }); + }); + it("accepts the fixed Google authorization endpoint for Google profiles", async () => { const keys = config(); const connector = createPaperclipCloudConnector({ diff --git a/server/src/services/paperclip-cloud-connector.ts b/server/src/services/paperclip-cloud-connector.ts index 923ed2301d8..74ee8866761 100644 --- a/server/src/services/paperclip-cloud-connector.ts +++ b/server/src/services/paperclip-cloud-connector.ts @@ -1,6 +1,6 @@ import { assertMcpClientMirrorEnvelope } from "./public-mcp/client-mirror-wire.js"; import { providerRetryAt } from "./provider-retry-after.js"; -import { SLACK_MANAGER_SCOPES, ASANA_CONNECTOR_SCOPES, appDefinitionForDeployment, isAsanaConnectorProfileId, type AsanaConnectorProfileId } from "@paperclipai/shared"; +import { SLACK_MANAGER_SCOPES, ASANA_CONNECTOR_SCOPES, LINKEDIN_CONNECTOR_SCOPES, appDefinitionForDeployment, isAsanaConnectorProfileId, isLinkedInConnectorProfileId, type AsanaConnectorProfileId, type LinkedInConnectorProfileId } from "@paperclipai/shared"; import { createDecipheriv, createHash, @@ -39,8 +39,8 @@ export { GOOGLE_WORKSPACE_CONNECTOR_PROFILES }; export type PaperclipCloudConnectorEnvironment = "development" | "test" | "staging" | "production"; export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack" | "github-app" | "slack-events" | "slack-forms" | "mcp-client-mirror" | "mcp-revocation-index"; -export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | "slack.manager" | "github.bot" | "tailscale.tailnet"; -export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack" | "tailscale"; +export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | LinkedInConnectorProfileId | "slack.manager" | "github.bot" | "tailscale.tailnet"; +export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "linkedin" | "slack" | "tailscale"; export type PaperclipCloudConnectorConfig = { baseUrl: string; @@ -1070,6 +1070,9 @@ function connectorProfileDefinition(profile: PaperclipCloudConnectorProfileId): if (isAsanaConnectorProfileId(profile)) { return { provider: "asana", scopes: ASANA_CONNECTOR_SCOPES }; } + if (isLinkedInConnectorProfileId(profile)) { + return { provider: "linkedin", scopes: LINKEDIN_CONNECTOR_SCOPES }; + } if (isGitHubConnectorProfileId(profile)) { return { provider: "github", scopes: GITHUB_CONNECTOR_PROFILES[profile].scopes }; } @@ -1085,6 +1088,9 @@ function isExpectedProviderAuthorizationUrl( if (isAsanaConnectorProfileId(profile)) { return url.origin === "https://app.asana.com" && url.pathname === "/-/oauth_authorize"; } + if (isLinkedInConnectorProfileId(profile)) { + return url.origin === "https://www.linkedin.com" && url.pathname === "/oauth/v2/authorization"; + } if (isGitHubConnectorProfileId(profile)) { return url.origin === "https://github.com" && url.pathname === "/login/oauth/authorize"; } @@ -1092,7 +1098,7 @@ function isExpectedProviderAuthorizationUrl( } function isPaperclipCloudConnectorProfileId(value: string): value is PaperclipCloudConnectorProfileId { - return value === "tailscale.tailnet" || value === "slack.manager" || isGoogleWorkspaceConnectorProfileId(value) || isGitHubConnectorProfileId(value) || isAsanaConnectorProfileId(value); + return value === "tailscale.tailnet" || value === "slack.manager" || isGoogleWorkspaceConnectorProfileId(value) || isGitHubConnectorProfileId(value) || isAsanaConnectorProfileId(value) || isLinkedInConnectorProfileId(value); } async function sha256Base64Url(value: string): Promise { diff --git a/server/src/services/tool-access/oauth/authorization-start.ts b/server/src/services/tool-access/oauth/authorization-start.ts index 3faef1f6e1c..84b7171096b 100644 --- a/server/src/services/tool-access/oauth/authorization-start.ts +++ b/server/src/services/tool-access/oauth/authorization-start.ts @@ -1,6 +1,6 @@ import { notifyIssueReviewState } from "../../issue-review-state-notifications.js"; import { vercelConnectHttpError, vercelCredentialFor, vercelConnectResourcesFor } from "../vercel-credentials.js"; -import { credentialScope, managedConnectorProfile } from "./client-settings.js"; +import { credentialScope, managedConnectorIssuer, managedConnectorProfile } from "./client-settings.js"; import { assertOAuthClientBindingUnchanged, createOAuthClientRegistration } from "./client-registration.js"; import type { ActorInfo } from "../types.js"; import { createOAuthEndpointPolicy } from "./endpoint-policy.js"; @@ -469,12 +469,7 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies authorizationUrl: session.authorizationUrl, expiresAt: expiresAt.toISOString(), ...(session.handoff ? { handoff: session.handoff } : {}), - issuer: - managedProfile.provider === "github" - ? "https://github.com" - : managedProfile.provider === "asana" - ? "https://app.asana.com" - : "https://accounts.google.com", + issuer: managedConnectorIssuer(managedProfile.provider), resource: galleryMethod.defaults?.serverUrl ?? null, registrationSource: null, }; diff --git a/server/src/services/tool-access/oauth/client-settings.test.ts b/server/src/services/tool-access/oauth/client-settings.test.ts index 2225abb7024..969cb020e96 100644 --- a/server/src/services/tool-access/oauth/client-settings.test.ts +++ b/server/src/services/tool-access/oauth/client-settings.test.ts @@ -1,7 +1,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import type { toolConnections } from "@paperclipai/db"; -import { APP_DEFINITIONS } from "@paperclipai/shared"; -import { configuredOAuthClientForConnection } from "./client-settings.js"; +import { APP_DEFINITIONS, LINKEDIN_CONNECTOR_SCOPES } from "@paperclipai/shared"; +import { + configuredOAuthClientForConnection, + managedConnectorIssuer, + managedConnectorProfile, +} from "./client-settings.js"; type Connection = typeof toolConnections.$inferSelect; @@ -128,6 +132,7 @@ describe("instance OAuth clients", () => { it.each([ ["asana", "mcp-own-oauth", "https://app.asana.com/-/oauth_token"], + ["linkedin", "oauth-own-app", "https://www.linkedin.com/oauth/v2/accessToken"], ["railway", "mcp-oauth", "https://backboard.railway.com/oauth/token"], ])("allows the token endpoint that the %s definition pins", (slug, methodKey, tokenUrl) => { vi.stubEnv(`PAPERCLIP_TOOL_OAUTH_${slug.toUpperCase()}_CLIENT_ID`, "instance-id"); @@ -138,6 +143,19 @@ describe("instance OAuth clients", () => { expect(configuredOAuthClientForConnection(pinned, slug, "https://attacker.example/token").clientId).toBeNull(); }); + it("maps managed connector profiles to their exact provider and OAuth issuer", () => { + const linkedIn = managedConnectorProfile("linkedin.share"); + expect(linkedIn).toEqual({ + id: "linkedin.share", + provider: "linkedin", + scopes: LINKEDIN_CONNECTOR_SCOPES, + }); + expect(managedConnectorIssuer(linkedIn!.provider)).toBe("https://www.linkedin.com/oauth"); + expect(managedConnectorIssuer("asana")).toBe("https://app.asana.com"); + expect(managedConnectorIssuer("github")).toBe("https://github.com"); + expect(managedConnectorIssuer("google")).toBe("https://accounts.google.com"); + }); + it("makes every customer OAuth method pin its token endpoint or name its same-host fallback", () => { const sameHostFallback = new Set(["box:mcp-own-oauth", "notion:mcp-oauth", "posthog:mcp-oauth", "sentry:mcp-oauth", "xero:mcp-own-oauth"]); const noFixedEndpoint = new Set(["oauth-generic:oauth"]); diff --git a/server/src/services/tool-access/oauth/client-settings.ts b/server/src/services/tool-access/oauth/client-settings.ts index 3a7ed566909..f8055bc2041 100644 --- a/server/src/services/tool-access/oauth/client-settings.ts +++ b/server/src/services/tool-access/oauth/client-settings.ts @@ -2,7 +2,7 @@ import type { ActorInfo } from "../types.js"; import { oauthConfig, isSmokeLabOAuthFixture } from "./metadata.js"; import { connectionMethodForConnection } from "../connection-methods.js"; import { stableHash } from "../../tool-catalog-hash.js"; -import { ASANA_CONNECTOR_SCOPES, isAsanaConnectorProfileId, type AsanaConnectorProfileId } from "@paperclipai/shared"; +import { ASANA_CONNECTOR_SCOPES, LINKEDIN_CONNECTOR_SCOPES, isAsanaConnectorProfileId, isLinkedInConnectorProfileId, type AsanaConnectorProfileId, type LinkedInConnectorProfileId } from "@paperclipai/shared"; import { connectionGrants, toolConnections } from "@paperclipai/db"; import { GITHUB_CONNECTOR_PROFILES, GOOGLE_WORKSPACE_CONNECTOR_PROFILES, getConnectableAppDefinition, isGitHubConnectorProfileId, isGoogleWorkspaceConnectorProfileId, type GitHubConnectorProfileId, type GoogleWorkspaceConnectorProfileId } from "@paperclipai/shared"; import { unprocessable } from "../../../errors.js"; @@ -187,7 +187,7 @@ export async function oauthGalleryEntryForConnection( } export type ManagedConnectorProfileId = - GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId; + GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | LinkedInConnectorProfileId; export function managedConnectorSubject( grant: { kind: string; subjectUserId: string | null; subjectAgentId: string | null }, @@ -206,14 +206,30 @@ export function managedConnectorConsentSubject( return typeof consentSubject === "string" && consentSubject ? consentSubject : managedConnectorSubject(grant, oauth); } +export type ManagedConnectorProvider = "google" | "github" | "asana" | "linkedin"; + +const MANAGED_CONNECTOR_ISSUERS: Record = { + google: "https://accounts.google.com", + github: "https://github.com", + asana: "https://app.asana.com", + linkedin: "https://www.linkedin.com/oauth", +}; + +export function managedConnectorIssuer(provider: ManagedConnectorProvider): string { + return MANAGED_CONNECTOR_ISSUERS[provider]; +} + export function managedConnectorProfile(value: string | undefined): { id: ManagedConnectorProfileId; - provider: "google" | "github" | "asana"; + provider: ManagedConnectorProvider; scopes: readonly string[]; } | null { if (value && isAsanaConnectorProfileId(value)) { return { id: value, provider: "asana", scopes: ASANA_CONNECTOR_SCOPES }; } + if (value && isLinkedInConnectorProfileId(value)) { + return { id: value, provider: "linkedin", scopes: LINKEDIN_CONNECTOR_SCOPES }; + } if (value && isGoogleWorkspaceConnectorProfileId(value)) { return { id: value, diff --git a/server/src/services/tool-access/oauth/grant-refresh.test.ts b/server/src/services/tool-access/oauth/grant-refresh.test.ts new file mode 100644 index 00000000000..dee1c9cec0f --- /dev/null +++ b/server/src/services/tool-access/oauth/grant-refresh.test.ts @@ -0,0 +1,164 @@ +import { describe, expect, it, vi } from "vitest"; +import type { Db } from "@paperclipai/db"; +import type { connectionGrants, toolConnections } from "@paperclipai/db"; +import { createOAuthGrantRefresh } from "./grant-refresh.js"; + +type ConnectionRow = typeof toolConnections.$inferSelect; +type GrantRow = typeof connectionGrants.$inferSelect; + +function makeManagedLinkedInConnection(): ConnectionRow { + return { + id: "conn-linkedin-1", + companyId: "company-1", + key: "linkedin", + name: "LinkedIn", + authKind: "oauth", + credentialSource: "paperclip_vault", + config: { + oauth: { + strategy: "paperclip_cloud_connector", + provider: "linkedin", + connectorProfile: "linkedin.share", + }, + }, + } as unknown as ConnectionRow; +} + +function makeGrant(overrides: { + refreshedAt?: string; + accessTokenExpiresAt: string; + includeRefreshToken?: boolean; +}): GrantRow { + const credentialSecretRefs = [ + { configPath: "oauth.access_token", secretId: "sec-access-1" }, + ...(overrides.includeRefreshToken + ? [{ configPath: "oauth.refresh_token", secretId: "sec-refresh-1" }] + : []), + ]; + return { + id: "grant-linkedin-1", + companyId: "company-1", + connectionId: "conn-linkedin-1", + status: "active", + credentialSecretRefs, + providerTenant: { + oauth: { + connectorSubject: "urn:li:person:abc", + accessTokenExpiresAt: overrides.accessTokenExpiresAt, + ...(overrides.refreshedAt ? { refreshedAt: overrides.refreshedAt } : {}), + }, + }, + } as unknown as GrantRow; +} + +describe("createOAuthGrantRefresh managed grant rotation", () => { + it("skips 30-day age rotation for managed grants without a refresh token while the access token is still valid", async () => { + const fixedNow = new Date("2026-12-04T12:00:00.000Z"); + const grant = makeGrant({ + refreshedAt: new Date(fixedNow.getTime() - 40 * 24 * 60 * 60_000).toISOString(), + accessTokenExpiresAt: new Date(fixedNow.getTime() + 20 * 24 * 60 * 60_000).toISOString(), + includeRefreshToken: false, + }); + const acquireOAuthGrantRefreshLease = vi.fn(); + const refresh = createOAuthGrantRefresh({} as Db, { + now: () => fixedNow, + getConnectionRow: vi.fn(async () => makeManagedLinkedInConnection()), + currentCloudConnector: () => null, + exchangeOAuthToken: vi.fn(), + store: { + getOAuthGrantRow: vi.fn(async () => grant), + resolveOAuthGrantSecret: vi.fn(), + createOrRotateOAuthSecret: vi.fn(), + oauthClientForConnection: vi.fn(), + syncCredentialBindings: vi.fn(), + }, + leases: { + acquireOAuthGrantRefreshLease, + clearOAuthGrantRefreshLease: vi.fn(), + }, + }); + + const result = await refresh({ + companyId: "company-1", + connectionId: "conn-linkedin-1", + grantId: "grant-linkedin-1", + }); + + expect(result).toBe(grant); + expect(acquireOAuthGrantRefreshLease).not.toHaveBeenCalled(); + }); + + it("requires reconnect when a managed grant without a refresh token approaches expiry", async () => { + const fixedNow = new Date("2026-12-04T12:00:00.000Z"); + const grant = makeGrant({ + refreshedAt: new Date(fixedNow.getTime() - 59 * 24 * 60 * 60_000).toISOString(), + accessTokenExpiresAt: new Date(fixedNow.getTime() + 30 * 60_000).toISOString(), + includeRefreshToken: false, + }); + const clearOAuthGrantRefreshLease = vi.fn(async () => grant); + const refresh = createOAuthGrantRefresh({} as Db, { + now: () => fixedNow, + getConnectionRow: vi.fn(async () => makeManagedLinkedInConnection()), + currentCloudConnector: () => ({} as never), + exchangeOAuthToken: vi.fn(), + store: { + getOAuthGrantRow: vi.fn(async () => grant), + resolveOAuthGrantSecret: vi.fn(), + createOrRotateOAuthSecret: vi.fn(), + oauthClientForConnection: vi.fn(), + syncCredentialBindings: vi.fn(), + }, + leases: { + acquireOAuthGrantRefreshLease: vi.fn(async () => ({ leaseId: "lease-1", grant })), + clearOAuthGrantRefreshLease, + }, + }); + + await expect( + refresh({ + companyId: "company-1", + connectionId: "conn-linkedin-1", + grantId: "grant-linkedin-1", + }), + ).rejects.toMatchObject({ + status: 422, + details: { code: "oauth_reauthorization_required" }, + }); + expect(clearOAuthGrantRefreshLease).toHaveBeenCalledTimes(1); + }); + + it("still triggers 30-day rotation when a managed grant has a refresh token", async () => { + const fixedNow = new Date("2026-12-04T12:00:00.000Z"); + const grant = makeGrant({ + refreshedAt: new Date(fixedNow.getTime() - 40 * 24 * 60 * 60_000).toISOString(), + accessTokenExpiresAt: new Date(fixedNow.getTime() + 20 * 24 * 60 * 60_000).toISOString(), + includeRefreshToken: true, + }); + const acquireOAuthGrantRefreshLease = vi.fn(async () => ({ leaseId: null, grant })); + const refresh = createOAuthGrantRefresh({} as Db, { + now: () => fixedNow, + getConnectionRow: vi.fn(async () => makeManagedLinkedInConnection()), + currentCloudConnector: () => null, + exchangeOAuthToken: vi.fn(), + store: { + getOAuthGrantRow: vi.fn(async () => grant), + resolveOAuthGrantSecret: vi.fn(), + createOrRotateOAuthSecret: vi.fn(), + oauthClientForConnection: vi.fn(), + syncCredentialBindings: vi.fn(), + }, + leases: { + acquireOAuthGrantRefreshLease, + clearOAuthGrantRefreshLease: vi.fn(), + }, + }); + + await refresh({ + companyId: "company-1", + connectionId: "conn-linkedin-1", + grantId: "grant-linkedin-1", + }); + + expect(acquireOAuthGrantRefreshLease).toHaveBeenCalledTimes(1); + }); +}); diff --git a/server/src/services/tool-access/oauth/grant-refresh.ts b/server/src/services/tool-access/oauth/grant-refresh.ts index cd6b56fdd04..639feac8a81 100644 --- a/server/src/services/tool-access/oauth/grant-refresh.ts +++ b/server/src/services/tool-access/oauth/grant-refresh.ts @@ -99,12 +99,21 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo typeof grantOauth.refreshedAt === "string" ? Date.parse(grantOauth.refreshedAt) : Number.NaN; + const nowMs = now().getTime(); + const hasRefreshToken = initialGrant.credentialSecretRefs.some( + (ref) => ref.configPath === "oauth.refresh_token", + ); + // Managed providers without a refresh token (such as LinkedIn's 60-day + // self-serve access tokens) cannot rotate ahead of expiry; skip + // age-based rotation and require reconnect only when the access token + // approaches expiry. const rotationDue = + hasRefreshToken && Number.isFinite(expiresAt) && (!Number.isFinite(refreshedAt) || - refreshedAt <= Date.now() - 30 * 24 * 60 * 60_000); + refreshedAt <= nowMs - 30 * 24 * 60 * 60_000); const refreshDue = - Number.isFinite(expiresAt) && expiresAt <= Date.now() + 60 * 60_000; + Number.isFinite(expiresAt) && expiresAt <= nowMs + 60 * 60_000; // A GitHub App can deliberately issue a non-expiring ghu_ token. Its // continuity is checked against /user below; only an expiring token pair // enters this rotation path. diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index a689033509c..81063a7bced 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -77,10 +77,10 @@ "packages/shared/src/antigravity-runtime.test.ts": "f9ebcc9430be51c342b42644b735f1434b405ec7", "packages/shared/src/api.ts": "1d61cdff51433c4136368d52ee7cf2f16aa820ed", "packages/shared/src/app-definitions-url.test.ts": "56792d6745a5bc7eafc36e7403f4c9bbd671ae99", - "packages/shared/src/app-definitions.generated.ts": "e15939b08ef267165456fb01bfd8df05d0d245e7", + "packages/shared/src/app-definitions.generated.ts": "c8b1c79300c650ffee5703901775c7b7c9616ec6", "packages/shared/src/app-definitions.ingestion-report.json": "a7b60c7c16a484a411989315e9f08d48258fa647", - "packages/shared/src/app-definitions.test.ts": "7a4dfd29b443fed3f9677b2e853d1c04be332f76", - "packages/shared/src/app-definitions.ts": "8f54fb0e497bff04885d43fcb54e97def98ec4f3", + "packages/shared/src/app-definitions.test.ts": "d346bbae1c7fc870da2bc970482fb0f61a272b92", + "packages/shared/src/app-definitions.ts": "94340a2b9c6c2aa72a9abe0302fb84d0c3d0e27f", "packages/shared/src/app-definitions/1password.json": "c11a4777de2c78805b2d391da5eb075a9511e0f8", "packages/shared/src/app-definitions/agentmail.json": "edd0799b1980d0f5f43b89c8f7a1173dc623f7fa", "packages/shared/src/app-definitions/airtable.json": "c9b216a2bbe693bc6167413255d41c33512d418d", @@ -141,6 +141,7 @@ "packages/shared/src/app-definitions/kernel.json": "bdf3d17edd364d4cc127edbcfc4bc907c994f48a", "packages/shared/src/app-definitions/klaviyo.json": "839d800d676aa97ba3b4538302dcebe30096ab75", "packages/shared/src/app-definitions/linear.json": "552c1ea4ef8a0ef122b9250a4ff3132752b010fc", + "packages/shared/src/app-definitions/linkedin.json": "904d05d07e55a42ddedd95be36447739f69fa7bb", "packages/shared/src/app-definitions/local-falcon.json": "f069afe88ca681da8b51c221c83b5333589720d9", "packages/shared/src/app-definitions/local.json": "c9cd6dab3631b349be94d7ea05541a13ac9613a0", "packages/shared/src/app-definitions/make.json": "a8cd0bce733ee384a60d2fef1da55f5b6f518a99", @@ -290,7 +291,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "7bf44c1301810437c498310577d3fe62206505b5", + "packages/shared/src/index.ts": "56fdc6718a8af98006752d587afea8a1cd53d790", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -307,6 +308,7 @@ "packages/shared/src/leading-user-command.ts": "d4bea3d1d76fcbf721f846f5adb47a58004a0497", "packages/shared/src/link-preview.test.ts": "136041c928343ad6272f43701b39cf95be255f3e", "packages/shared/src/link-preview.ts": "b7431d4c30a12067e80e6806728b3ae7c7541f8f", + "packages/shared/src/linkedin-connectors.ts": "017f160d724d5a982d5e38b5a061dbc7f09e9df0", "packages/shared/src/markdown-work-products.test.ts": "7293d14ad45ec2b11b5deaab4ce070c36f7c9010", "packages/shared/src/markdown-work-products.ts": "16a88cfb717f325c247a516e78b47d53871b52ed", "packages/shared/src/mcp-apps.test.ts": "848f3247bdc98af398daa144b0e44991a3f352b3", diff --git a/ui/public/brands/apps/linkedin.svg b/ui/public/brands/apps/linkedin.svg new file mode 100644 index 00000000000..399871359ff --- /dev/null +++ b/ui/public/brands/apps/linkedin.svg @@ -0,0 +1,4 @@ + + + + diff --git a/ui/public/brands/apps/manifest.json b/ui/public/brands/apps/manifest.json index 04c90a3c927..63b2c119cc5 100644 --- a/ui/public/brands/apps/manifest.json +++ b/ui/public/brands/apps/manifest.json @@ -317,6 +317,12 @@ "localAsset": "/brands/apps/linear.svg", "darkAsset": "/brands/apps/linear-dark.svg" }, + { + "slug": "linkedin", + "provider": "LinkedIn", + "catalogVisible": true, + "localAsset": "/brands/apps/linkedin.svg" + }, { "slug": "local-falcon", "provider": "Local Falcon",