Add an oauth-discovery connection provider type

Closed
CH
8d ago
+1820-89

Why

We want the workspace AI to call tools on remote MCP servers (Linear, GitHub, Notion, ...). Most of them require OAuth. Twenty's connection providers can't sign in to them today, because the existing oauth type assumes the app developer already has an OAuth client at the provider.

How oauth works today

The app developer does the OAuth setup by hand, once, outside Twenty:

  1. Register an OAuth app in the provider's developer console and get a client id and secret.
  2. Copy the provider's endpoints and scopes into the manifest:
    defineConnectionProvider({
      type: 'oauth',
      oauth: {
        authorizationEndpoint: 'https://linear.app/oauth/authorize',
        tokenEndpoint: 'https://api.linear.app/oauth/token',
        scopes: ['read', 'write'],
        clientIdVariable: 'LINEAR_CLIENT_ID',
        clientSecretVariable: 'LINEAR_CLIENT_SECRET',
      },
    });
    
  3. Ship the client id and secret as serverVariables, set by the admin.

At connect time, Twenty runs a plain authorization code flow (RFC 6749, with PKCE, RFC 7636): redirect to authorizationEndpoint with the client id, then exchange the code at tokenEndpoint with the client secret.

That works for a few providers an app developer integrates on purpose. It doesn't work for MCP servers: anyone can point Twenty at any server URL, so there is nobody to register a client in advance, and nothing to copy the endpoints from.

How oauth-discovery works

The MCP authorization spec solves exactly this, by chaining standard OAuth extensions so a client needs only the server URL. Twenty now does the same at connect time:

StepWhat Twenty doesStandard
1. Find the authorization serverPings the resource unauthenticated; the 401 WWW-Authenticate header points to the resource's metadata, which names its authorization server(s).RFC 9728 OAuth 2.0 Protected Resource Metadata
2. Find its endpointsReads /.well-known/oauth-authorization-server (falls back to OpenID discovery) for the authorize, token and registration endpoints.RFC 8414 Authorization Server Metadata
3a. Identify Twenty, preferredUses https://<twenty>/auth/apps/client-metadata.json as the client_id; the server fetches that document to learn Twenty's name and redirect URI. No registration call, nothing per workspace on the server side. Only over HTTPS.OAuth Client ID Metadata Document (IETF draft, the MCP spec's preferred method)
3b. Identify Twenty, fallbackRegisters a client through the server's registration endpoint.RFC 7591 Dynamic Client Registration
4. Sign inAuthorization code flow with PKCE (S256) and no client secret (token_endpoint_auth_method: none, a public client).RFC 6749, RFC 7636
5. Bind tokens to the serverSends resource=<server URL> on authorize, token and refresh requests, so a token can't be replayed against another resource.RFC 8707 Resource Indicators

So the manifest shrinks to:

defineConnectionProvider({
  type: 'oauth-discovery',
  oauthDiscovery: { resourceUrl: 'https://mcp.linear.app/mcp' },
});

No endpoints, no client id or secret, and no serverVariables. What Twenty discovered and registered is stored per workspace (see Database), so later sign-ins and refreshes reuse it instead of rediscovering.

The protocol work is delegated to the official MCP TypeScript SDK (@modelcontextprotocol/sdk, auth() and refreshAuthorization()). Twenty provides the storage, the SSRF-safe fetch and the redirect handling.

This PR only adds the provider type. It is the base for MCP sign-in (next PR), but it stands on its own: an app can declare one today, and nothing changes for existing providers or for users.

Why MCP can skip the setup, and is it less secure?

Why the shortcut exists

The manual setup of the oauth type is not what makes OAuth secure. Copying endpoints and creating a client in a console are ways to agree on configuration, and that configuration isn't secret:

  • Endpoints are public facts. Every authorization server already publishes them; RFC 8414 and RFC 9728 just put them at a well-known URL instead of in a developer's docs page. Reading them from the server is equivalent to copying them by hand.
  • Registration is bookkeeping. In the console flow, the provider records "client X may redirect to URL Y". Dynamic registration (RFC 7591) and the Client ID Metadata Document do the same thing over HTTP.
  • What protects the account is unchanged: the user signs in and consents on the authorization server's own domain, the code is sent only to a pre-agreed redirect URI, and the token is bound to one resource.

The MCP spec can make this the default because of what MCP servers are: servers that many unknown clients (Claude, Cursor, Twenty, ...) connect to, where a per-client console registration can't scale. It's the same reason native and desktop apps have long used public clients (RFC 8252).

What changes compared to oauth

oauth (today)oauth-discovery
Who chooses the serverThe app developer, at build timeWhoever declares the provider: an app manifest in this PR; a workspace admin adding an MCP server in the next PR
Client authentication at the token endpointClient secret (confidential client)None (public client); PKCE proves the code exchange comes from whoever started the sign-in
Client identityRegistered by hand, vetted by the providerClient ID Metadata Document: the client_id is a URL on Twenty's domain, so the server can check the redirect URI belongs to it. Dynamic registration: self-asserted
Redirect URIPre-registeredPre-registered through the metadata document or registration, then checked exactly
Token scopeWhatever the provider issuesAlso bound to the server with resource (RFC 8707)

Is it less secure?

Not in the way that matters for the account: the OAuth 2.0 Security Best Current Practice (RFC 9700) and OAuth 2.1 accept a public client with PKCE and exact redirect URI matching as safe. A leaked code can't be redeemed without the verifier, and the verifier never leaves Twenty (this PR also moves it out of the redirect URL for every provider type).

What you do give up, and how it's handled:

  • No secret authenticates Twenty to the server. A dynamically registered client could be any program calling itself "Twenty". This is why the Client ID Metadata Document is preferred: it ties the client to Twenty's domain. Dynamic registration is only the fallback, for servers that don't support it.
  • Trust moves to the choice of server. With oauth, a developer vetted the provider. Here, whatever URL is configured gets the user's consent screen. That decision stays with whoever configures it (app developer, or an admin with the API keys & webhooks permission in the next PR), and the consent screen is always on the authorization server's real domain, so the user sees who they are signing in to.
  • Twenty fetches URLs chosen by someone else. Discovery follows URLs from the server's responses. Every request goes through the SSRF-safe HTTP client, which blocks private and internal addresses, with a 15-second timeout.
  • A malicious server could point to another authorization server. Tokens are requested with resource set to the configured server, and stored only for that provider, so a token issued for one resource isn't sent to another.

In short: the shortcut removes setup steps, not security properties. What remains is the same question as any integration: do you trust the server you connect to?

What a provider looks like

App manifest (twenty-sdk, twenty-shared)

defineConnectionProvider({
  universalIdentifier: '...',
  name: 'linear',
  displayName: 'Linear',
  type: 'oauth-discovery',
  scope: 'USER', // or 'WORKSPACE'
  oauthDiscovery: {
    resourceUrl: 'https://mcp.linear.app/mcp',
  },
});
type ConnectionProviderType = 'oauth' | 'oauth-discovery' | 'custom';

type OAuthDiscoveryConnectionProviderConfig = {
  resourceUrl: string; // http(s), checked by the SDK and the server validator
};

No serverVariables. Apps declaring this type need "engines": { "twenty": ">=2.58.0" }.

Database

The provider stores its declaration; the client Twenty negotiates is per workspace runtime state, so it lives in its own table.

erDiagram
  connectionProvider ||--o| connectionProviderOAuthClient : "has one per workspace"
  connectionProvider {
    uuid id PK
    varchar type "oauth | oauth-discovery | custom"
    jsonb oauthConfig "oauth only"
    jsonb customConfig "custom only"
    jsonb oauthDiscoveryConfig "NEW: { resourceUrl }"
  }
  connectionProviderOAuthClient {
    uuid id PK
    uuid workspaceId FK "cascade"
    uuid connectionProviderId FK "cascade, unique"
    varchar registrationMethod "CLIENT_ID_METADATA_DOCUMENT | DYNAMIC_CLIENT_REGISTRATION"
    varchar clientId
    varchar clientSecret "nullable, encrypted (CHECK enc:v2:)"
    timestamptz clientSecretExpiresAt "nullable"
    varchar tokenEndpointAuthMethod "nullable"
    varchar redirectUri
    jsonb discoveryState "authorization server URL and metadata"
  }
  • One client per provider and workspace (unique connectionProviderId): every member's tokens come from the same client, so refreshes keep working whoever signed in first.
  • discoveryState caches what discovery found, so a refresh does not rediscover.
  • Added by the fast instance command 2-58 add-oauth-discovery-to-connection-provider.

HTTP

RouteChange
GET /auth/apps/client-metadata.jsonNew, public. Twenty's Client ID Metadata Document: name, redirect URI, token_endpoint_auth_method: none. Authorization servers that support it read this instead of making Twenty register.
GET /auth/apps/authorize, GET /auth/apps/callbackUnchanged routes, now also serve oauth-discovery providers.

GraphQL is unchanged; the only generated diff is the SDK metadata client.

How a sign-in runs

sequenceDiagram
  participant M as Member
  participant T as Twenty
  participant R as Resource (MCP server)
  participant A as Authorization server
  M->>T: GET /auth/apps/authorize
  T->>R: unauthenticated ping
  R-->>T: 401 + WWW-Authenticate (resource metadata, scope)
  T->>R: protected resource metadata (RFC 9728)
  T->>A: authorization server metadata
  alt stored client still usable
    T->>T: reuse it
  else HTTPS and server accepts metadata documents
    T->>T: client_id = /auth/apps/client-metadata.json
  else
    T->>A: dynamic client registration
  end
  T->>T: save client (insert if absent / replace if unchanged)
  T->>T: store PKCE verifier + client id in Redis (single use, 10 min)
  T-->>M: redirect to A with PKCE S256, resource, state = signed JWT { flowSecretId }
  M->>A: consent
  A-->>M: redirect to /auth/apps/callback?code&state
  M->>T: callback
  T->>T: verify state, claim flow secrets atomically, check client unchanged
  T->>A: exchange code with verifier
  T->>T: save ConnectedAccount

Refresh goes through AppOAuthRefreshAccessTokenService like any app connection and uses the stored discoveryState. If the authorization server says the client is unknown, the stored client is deleted and the next sign-in registers a new one.

Notable choices

  • The PKCE verifier stays server-side, for every OAuth provider. The state is a signed but readable JWT in the redirect URL. With a public client (no secret), the verifier sitting next to the code there would defeat PKCE. States now carry only a flowSecretId, and the secrets are claimed once, atomically. States signed before the deploy still carry codeVerifier and are accepted until 2.58 is out (marked TODO).
  • Concurrent sign-ins converge on one client. The first sign-in inserts the client only if none exists; later ones replace it only if it is still the one they read. The loser reuses the winner's client, and a callback whose client changed mid sign-in is rejected instead of deleting the replacement.
  • A rejected client is replaced only if the replacement is accepted, so other members' refresh tokens are not stranded on a client Twenty no longer has.
  • A provider that cannot refresh reports PROVIDER_NOT_SUPPORTED instead of being retried as a network error.

Code map

PieceRole
ConnectionProviderOAuthDiscoveryServicediscovery, client choice, authorization URL
ConnectionProviderOAuthDiscoveryTokenServicecode exchange and refresh
ConnectionProviderOAuthClientServiceclient table reads and writes
OAuthDiscoveryClientProvideradapter between the MCP SDK's auth() and Twenty's storage
ConnectionProviderAuthorizationStateServicestate JWT and single-use flow secrets
probeProtectedResource, isOAuthClientRejectedsmall fetch helpers, the probe is reused by the MCP PR

Sequencing

  1. This PR: the provider type, its table and the flow. No UI, nothing created unless an app declares a provider.
  2. Next: Twenty generates an oauth-discovery provider for an MCP server that answers 401 (split out of #29669, closed for now).
  3. Then: the MCP servers settings UI behind IS_MCP_SERVERS_ENABLED.

Rollout

  • Fast instance command, no backfill.
  • Sign-ins started before the deploy keep working through the legacy codeVerifier fallback.

Test

  • Unit: connection-provider, manifest converter, validators, flat-entity constants, plus probeProtectedResource.
  • Integration on a fresh DB: suites/connection-provider (79 tests) and the MCP OAuth sign-in spec end to end with the next PR on top.
  • tsgo clean in twenty-server, oxlint and oxfmt clean, generated clients in sync.