Add an oauth-discovery connection provider type
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:
- Register an OAuth app in the provider's developer console and get a client id and secret.
- 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', }, }); - 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:
| Step | What Twenty does | Standard |
|---|---|---|
| 1. Find the authorization server | Pings 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 endpoints | Reads /.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, preferred | Uses 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, fallback | Registers a client through the server's registration endpoint. | RFC 7591 Dynamic Client Registration |
| 4. Sign in | Authorization 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 server | Sends 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.
Discovery is a step in front of the existing oauth flow, not a parallel one. ConnectionProviderOAuthClientResolverService answers "which endpoints, client id, scopes and resource does this provider use?": for oauth from the manifest and server variables, for oauth-discovery from the stored client or by running discovery and registration with the MCP SDK's lower-level functions (discoverOAuthProtectedResourceMetadata, discoverAuthorizationServerMetadata, registerClient). From there both types share the same authorize, code-exchange and refresh code, which now takes an optional client secret (public clients) and a resource parameter. A client the authorization server rejects at the token endpoint (invalid_client) is dropped, so the next sign-in registers a new one.
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.
Architecture
Discovery only resolves which client to use; after that, both provider types run the same authorize, exchange and refresh code.
flowchart LR
Browser -->|GET /auth/apps/authorize| Controller[ConnectionProviderOAuthController]
Browser -->|GET /auth/apps/callback + flow cookie| Controller
Controller --> Cookie[ConnectionProviderFlowCookieService<br/>browser nonce cookie]
Controller --> Flow[ConnectionProviderOAuthFlowService<br/>authorize URL, callback, code exchange]
Flow --> State[ConnectionProviderAuthorizationStateService<br/>state JWT, flow secrets in Redis]
Flow --> Resolver[ConnectionProviderOAuthClientResolverService<br/>resolveForAuthorization / resolveForTokenRequest]
Resolver -->|oauth| Manifest[ConnectionProviderService<br/>manifest + server variables]
Resolver -->|oauth-discovery| Discovery[ConnectionProviderOAuthDiscoveryService<br/>probe, discover, register]
Discovery --> Store[ConnectionProviderOAuthClientService<br/>connectionProviderOAuthClient table]
Discovery -->|RFC 9728, 8414, 7591| AS[(Authorization server)]
Flow -->|exchangeCodeForToken| AS
Flow --> Accounts[ConnectionProviderConnectedAccountService]
Refresh[AppOAuthRefreshAccessTokenService] --> Resolver
Refresh -->|exchangeRefreshTokenForToken| AS
| Service | Owns |
|---|---|
ConnectionProviderOAuthFlowService | The authorization code flow for every provider type: builds the authorize URL from a ResolvedOAuthClient, verifies state, browser nonce, client and token endpoint at callback, exchanges the code, persists the account. |
ConnectionProviderOAuthClientResolverService | Answers "endpoints, client id, secret, scopes, resource for this provider": manifest for oauth, stored client or discovery for oauth-discovery. Forgets a discovered client the token endpoint rejects with invalid_client. |
ConnectionProviderOAuthDiscoveryService | Probes the resource, reads RFC 9728 and RFC 8414 documents, identifies Twenty by its Client ID Metadata Document or registers a client (RFC 7591), reuses or refreshes the stored client. |
ConnectionProviderOAuthClientService | Reads and writes the per-workspace connectionProviderOAuthClient row, client secret encrypted. |
ConnectionProviderFlowCookieService | The __Host- cookie that binds a sign-in to the browser that started it; holds the last five nonces so concurrent sign-ins work. |
AppOAuthRefreshAccessTokenService | Refresh for both types through the resolver and exchangeRefreshTokenForToken. |
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 server | The app developer, at build time | Whoever 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 endpoint | Client secret (confidential client) | None (public client); PKCE proves the code exchange comes from whoever started the sign-in |
| Client identity | Registered by hand, vetted by the provider | Client 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 URI | Pre-registered | Pre-registered through the metadata document or registration, then checked exactly |
| Token scope | Whatever the provider issues | Also 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
resourceset 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. discoveryStatecaches what discovery found, so a refresh does not rediscover.- Added by the fast instance command
2-58 add-oauth-discovery-to-connection-provider.
HTTP
| Route | Change |
|---|---|
GET /auth/apps/client-metadata.json | New, 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/callback | Unchanged 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 carrycodeVerifierand 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_SUPPORTEDinstead of being retried as a network error.
Code map
| Piece | Role |
|---|---|
ConnectionProviderOAuthDiscoveryService | discovery, client choice, authorization URL |
ConnectionProviderOAuthDiscoveryTokenService | code exchange and refresh |
ConnectionProviderOAuthClientService | client table reads and writes |
OAuthDiscoveryClientProvider | adapter between the MCP SDK's auth() and Twenty's storage |
ConnectionProviderAuthorizationStateService | state JWT and single-use flow secrets |
probeProtectedResource, isOAuthClientRejected | small fetch helpers, the probe is reused by the MCP PR |
Sequencing
- This PR: the provider type, its table and the flow. No UI, nothing created unless an app declares a provider.
- Next: Twenty generates an
oauth-discoveryprovider for an MCP server that answers 401, and uses the signed-in account for tool sync and calls (split out of #29669, closed). - Then: the MCP servers settings UI behind
IS_MCP_SERVERS_ENABLED. - Later: MCP tools as a workflow step (#29668).
Rollout
- Fast instance command, no backfill.
- Sign-ins started before the deploy keep working through the legacy
codeVerifierfallback.
Test
- Unit: connection-provider, manifest converter, validators, flat-entity constants and
probeProtectedResource(71 tests in twenty-server),defineConnectionProvider(21 tests in twenty-sdk). - Integration on a fresh DB:
suites/connection-provider, 9 suites, 79 tests. tsgoclean in twenty-server,lint:diff-with-mainclean in twenty-server, twenty-shared and twenty-sdk, SDK metadata client regenerated against this branch.