diff --git a/docs/self-host/hybrid.md b/docs/self-host/hybrid.md index ec9299e3f..1f618cba9 100644 --- a/docs/self-host/hybrid.md +++ b/docs/self-host/hybrid.md @@ -162,8 +162,9 @@ The Setup checks show the link as `hybrid_jira` (in Settings, Setup and the inst | GitHub | yes | relay and token broker | | Jira (Forge app) | yes | install CoderHelm's Jira app and enter your install id as the team id, or link a hosted team's site ([Jira through CoderHelm](#jira-through-coderhelm)) | | Notion, Confluence, Google Drive | yes | one-click sign-in through CoderHelm; tokens brokered | +| Figma | yes | one-click sign-in through CoderHelm's public Figma app (read-only); tokens brokered, your install calls Figma's API | | Slack and Teams notifications | not needed | your install posts to the incoming webhook you paste | -| Figma, Linear, Sentry, Sanity and other sign-in apps | not needed | your install registers itself with each provider; Figma signs in only apps it approved, so Figma uses your own Figma app or a key | +| Linear, Sentry, Sanity and other sign-in apps | not needed | your install registers itself with each provider | | Slack and Teams commands | no | there is no shared Slack or Teams app: each team uses its own app's signing secret, as today | | Sign in with GitHub | yes | CoderHelm's app carries the trip to GitHub; your install checks the account with GitHub and applies its own rules ([Sign in with GitHub through CoderHelm](#sign-in-with-github-through-coderhelm)) | | Sign in with Google | no | a self-hosted install has no Google sign-in, through CoderHelm or its own ([Sign-in and people](./sign-in.md#no-google-sign-in)) | @@ -176,6 +177,8 @@ The Setup checks show the link as `hybrid_jira` (in Settings, Setup and the inst The hosted side runs in the hosted deployment's API stack when `hybrid.zone` is set in its config (the parent zone is configurable, so moving customer addresses to a separate domain later is a config change). It needs `hybrid_master_key` (32 or more random characters) in the hosted secret, the callback URL `https://api.coderhelm.com/auth/github/callback/hybrid` on CoderHelm's GitHub App, and the GitHub App's setup page (the dashboard's Settings, GitHub) to forward `state=hyb_…` returns. The same callback URL takes installs' GitHub sign-ins (`state=hsi_…`): installs call `POST /hybrid/github/sign-in/start` and `POST /hybrid/github/sign-in/exchange` (signed), and the audit log has `github_sign_in` and `github_sign_in_refused`; no other GitHub App setting is needed. A hosted team links its Jira site with `GET` and `POST /api/hybrid/jira-link/:state` (team admins, from the dashboard's Settings, Integrations, Jira, which opens with `?hybrid_link=hyj_…`); sees and removes the link with `GET` and `DELETE /api/hybrid/jira-link`; installs call `POST /hybrid/jira/link-start`, `DELETE /hybrid/jira/link` and `POST /hybrid/jira/config` (signed), and the Jira proxy at `POST /hybrid/jira/trigger///`. Platform admins see every install and the audit log (`jira_link_start`, `link_jira`, `unlink_jira`, `jira_link_refused`, `jira_link_declined`) at `GET /api/admin/hybrid`, and revoke one with `POST /api/admin/hybrid/:install_id/revoke`. +**CoderHelm's Figma app.** A public Figma OAuth app owned by CoderHelm's own Figma team, with the one redirect URL `https://app.coderhelm.com/settings/integrations/mcp-callback/` and the scopes `current_user:read` and `file_content:read`. Its client id and secret go in the hosted secret as `figma_client_id` and `figma_client_secret`; until both are there, hosted teams see no Sign in with Figma and installs aren't offered Figma. Installs sign in through `GET /hybrid/oauth/figma/authorize` like Notion, Confluence and Google Drive: Figma returns to the hosted callback page, the hosted side finishes the sign-in in a holding partition and sends the browser to the install's own callback page with a one-time code, and the code becomes the install's only when the install redeems it with its registration secret and PKCE verifier. + **Approving an install for the mail relay.** An install with a GitHub link may use the relay already. To approve one without, set `relay_approved` to `true` on its `HYBRID#` / `INSTALL` record in the hosted settings table, after checking who runs it. **Relay brake.** The alarms `-relay-bouncebrake` and `-relay-complaintbrake` turn sending off for the configuration set `-relay` through the function `-relay-brake`. To turn it back on after finding the cause (the Deliveries of the install that sent the bounces): `aws sesv2 put-configuration-set-sending-options --configuration-set-name -relay --sending-enabled`. diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index e0107349e..9e246cc05 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -101,9 +101,12 @@ New Relic, Confluence, OpenSearch, REST APIs, SQL databases, CloudWatch metrics - **What you need**\ Nothing. Servers that support OAuth dynamic client registration register your install by themselves the first time someone signs in. The redirect URI is your install's `https://coderhelm.example.com/settings/integrations/mcp-callback/`, and the add flow shows it for servers that need an app registered by hand. - **Figma**\ - Figma's MCP server signs in only apps Figma approved, so CoderHelm runs Figma's tools with your own Figma app (or a personal access token). Create the app at https://www.figma.com/developers/apps under your Figma team or organization, add the redirect URI above, give it the `current_user:read` and `file_content:read` scopes, and publish it as a private app (no review from Figma; people in that team or organization can sign in). Paste its client id and secret in Settings, Integrations, Figma, Use my own Figma app, then select Connect. + Figma's MCP server signs in only apps Figma approved, so CoderHelm runs Figma's tools against Figma's API with a sign-in (or a personal access token). Three ways, in Settings, Integrations, Figma: + - **Sign in with Figma** (CoderHelm's app): with hybrid, choose CoderHelm's app for Figma (Settings, Version and updates, Hybrid, or on the Figma card) and sign in. Nothing to create. CoderHelm keeps the sign-in (encrypted) and hands your install access tokens that expire within ten minutes; agents call Figma from your install. + - **Use my own Figma app**: create the app at https://www.figma.com/developers/apps under your Figma team or organization, add the redirect URI above, give it the `current_user:read` and `file_content:read` scopes, and publish it as a private app (no review from Figma; people in that team or organization can sign in). Paste its client id and secret there, then select Connect. + - **For every team on the install**: put a Figma app's `figma_client_id` and `figma_client_secret` in the install's secret. The card's Sign in with Figma then uses it, with no hybrid. - **With hybrid**\ - No change: MCP sign-ins always go to your install directly. + MCP sign-ins go to your install directly, except Figma when CoderHelm's app is chosen for it (above). ## Knowledge sources diff --git a/services/common/src/hybrid/integrations.rs b/services/common/src/hybrid/integrations.rs index 158117115..8229efe39 100644 --- a/services/common/src/hybrid/integrations.rs +++ b/services/common/src/hybrid/integrations.rs @@ -80,6 +80,14 @@ pub const CATALOG: &[Entry] = &[ stays_with_you: "The files your install reads and the index it builds.", reason: "", }, + Entry { + id: "figma", + name: "Figma", + mode: Mode::Hosted, + through_coderhelm: "You sign in through CoderHelm's Figma app (read-only: your profile and file contents). CoderHelm keeps the sign-in (encrypted) and hands your install access tokens that expire within ten minutes.", + stays_with_you: "The designs your install reads. Agents call Figma's API from your install with those tokens.", + reason: "", + }, Entry { id: "slack_notifications", name: "Slack and Teams notifications", @@ -90,9 +98,9 @@ pub const CATALOG: &[Entry] = &[ }, Entry { id: "mcp_apps", - name: "Figma, Linear, Sentry, Sanity and other sign-in apps", + name: "Linear, Sentry, Sanity and other sign-in apps", mode: Mode::Direct, - through_coderhelm: "Nothing: your install registers itself with each provider's sign-in server and keeps its own tokens. Figma signs in only apps it approved, so Figma uses your own Figma app or a key.", + through_coderhelm: "Nothing: your install registers itself with each provider's sign-in server and keeps its own tokens.", stays_with_you: "Everything.", reason: "", }, @@ -161,11 +169,18 @@ mod tests { let ids: Vec<_> = hosted_ids().collect(); assert_eq!( ids, - vec!["github", "jira", "notion", "confluence", "google_drive"] + vec![ + "github", + "jira", + "notion", + "confluence", + "google_drive", + "figma" + ] ); assert_eq!( app_choice_ids().collect::>(), - vec!["jira", "notion", "confluence", "google_drive"] + vec!["jira", "notion", "confluence", "google_drive", "figma"] ); assert!(entry("github").is_some() && entry("nope").is_none()); let j = serde_json::to_value(entry("slack_commands").unwrap()).unwrap(); diff --git a/services/common/src/mcp_catalog.rs b/services/common/src/mcp_catalog.rs index 2dc1b2dbb..88b36af2a 100644 --- a/services/common/src/mcp_catalog.rs +++ b/services/common/src/mcp_catalog.rs @@ -589,15 +589,22 @@ pub struct OwnApp { pub console: &'static str, /// The vendor's guide to creating one. pub guide: &'static str, + /// The keys in the deployment's secret holding CoderHelm's own public + /// app with the vendor (client id, client secret): the one-click + /// sign-in every team gets, and what the hosted broker signs in a + /// self-hosted install with. Never in code. + #[serde(skip)] + pub coderhelm_keys: (&'static str, &'static str), } /// The own-app sign-in for a catalog server, when its package takes an /// OAuth token. pub fn own_app(id: &str) -> Option { match id { - // Figma's REST API takes tokens from any OAuth app, and a private - // app needs no review from Figma for people on the team or - // organization that owns it. The token endpoint wants the client in + // Figma's REST API takes tokens from any OAuth app. A private app + // needs no review from Figma for people on the team or organization + // that owns it; CoderHelm's own public app (`coderhelm_keys`) was + // reviewed by Figma and signs in anyone. The token endpoint wants the client in // an HTTP Basic header; refreshing has its own address and never // rotates the refresh token. The package calls GET /v1/files, // /v1/files/:key/nodes, /v1/images and /v1/files/:key/images (all @@ -612,6 +619,7 @@ pub fn own_app(id: &str) -> Option { check: "https://api.figma.com/v1/me", console: "https://www.figma.com/developers/apps", guide: "https://developers.figma.com/docs/rest-api/oauth-apps/", + coderhelm_keys: ("figma_client_id", "figma_client_secret"), }), _ => None, } @@ -687,6 +695,10 @@ mod tests { assert!(u.starts_with("https://"), "{}: {u}", p.id); } assert!(app.refresh.is_empty() || app.refresh.starts_with("https://")); + // CoderHelm's app is read from two keys named after the vendor. + let (id, secret) = app.coderhelm_keys; + assert_eq!(id, format!("{}_client_id", p.id)); + assert_eq!(secret, format!("{}_client_secret", p.id)); } assert!(own_app("sentry").is_none()); } diff --git a/services/common/src/mcp_remote/own_app.rs b/services/common/src/mcp_remote/own_app.rs index 8acd2f582..657c4165a 100644 --- a/services/common/src/mcp_remote/own_app.rs +++ b/services/common/src/mcp_remote/own_app.rs @@ -13,6 +13,15 @@ //! never listed or used as an MCP server ([`super::store::is_token_only`]). //! The token goes only to the vendor's API, through the vendor's package, //! exactly where a key for it would go. +//! +//! The same record also holds a sign-in with CoderHelm's own public app with +//! the vendor ([`use_coderhelm_app`]): on the hosted service (and on an +//! install with that app in its own secret) the app's client id and secret +//! come from the deployment's secret ([`crate::mcp_catalog::OwnApp::coderhelm_keys`]); +//! on a hybrid install that chose CoderHelm's app, the hosted broker is the +//! authorization server ([`brokered_record`]), exactly as for Notion, +//! Confluence and Google Drive. One record per server: the team uses +//! CoderHelm's app or its own, never both. use super::http::HttpRequest; use super::oauth::ClientAuth; @@ -74,6 +83,157 @@ pub fn record( s } +/// The record for a sign-in through CoderHelm's broker (a hybrid install +/// that chose CoderHelm's app): the hosted side is the authorization server, +/// the install id the client id and its registration secret the client +/// secret. The vendor's app, scopes and refresh token stay on the hosted +/// side; the install gets short-lived access tokens and renews them with a +/// grant handle at the hosted token endpoint. +pub fn brokered_record( + catalog_id: &str, + name: &str, + hosted: &str, + install_id: &str, + sealed_secret: &str, +) -> ServerRecord { + let hosted = hosted.trim_end_matches('/'); + let mut s = ServerRecord::new(&connection_id(catalog_id), name, hosted); + s.catalog_id = tag(catalog_id); + s.auth = AuthKind::OAuth; + s.sharing = Sharing::Shared; + s.oauth = Some(OAuthSettings { + issuer: hosted.into(), + authorization_endpoint: format!("{hosted}/hybrid/oauth/{catalog_id}/authorize"), + token_endpoint: format!("{hosted}{BROKER_TOKEN_PATH}"), + revocation_endpoint: Some(format!("{hosted}/hybrid/oauth/revoke")), + token_auth_methods: vec![ClientAuth::ClientSecretPost.as_str().into()], + client_id: install_id.into(), + client_auth: ClientAuth::ClientSecretPost, + client_secret_sealed: sealed_secret.into(), + registration: super::oauth::Registration::Manual.as_str().into(), + ..Default::default() + }); + s +} + +/// The hosted broker's token endpoint path. +const BROKER_TOKEN_PATH: &str = "/hybrid/oauth/token"; + +/// Whose app a sign-in record uses. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + /// CoderHelm's public app (directly, or through the hosted broker). + Coderhelm, + /// The team's own app. + Own, +} + +impl Source { + pub fn as_str(self) -> &'static str { + match self { + Source::Coderhelm => "coderhelm", + Source::Own => "own", + } + } +} + +/// Whose app `s` signs in with: CoderHelm's when it goes through the broker, +/// or when its client id is CoderHelm's (`coderhelm_client_id`, from the +/// deployment's secret; empty where there is none). +pub fn source(s: &ServerRecord, coderhelm_client_id: &str) -> Source { + let Some(o) = s.oauth.as_ref() else { + return Source::Own; + }; + let id = coderhelm_client_id.trim(); + if o.token_endpoint.ends_with(BROKER_TOKEN_PATH) || (!id.is_empty() && o.client_id == id) { + Source::Coderhelm + } else { + Source::Own + } +} + +/// Puts `rec` in place of the team's sign-in record for its server: the same +/// app (same client id at the same token endpoint) keeps its sign-in, any +/// other app ends the old one first (its tokens belong to that app). +async fn replace( + rt: &Runtime, + mut rec: ServerRecord, + by: &str, + at: &str, +) -> Result { + let old = rt + .store + .get_server(&rt.team, &rec.id) + .await + .map_err(SaveError::Internal)?; + rec.added_by = by.to_ascii_lowercase(); + rec.added_at = at.to_string(); + rec.status = Status::NotConnected; + if let Some(old) = &old { + let key = |s: &ServerRecord| { + s.oauth + .as_ref() + .map(|o| (o.client_id.clone(), o.token_endpoint.clone())) + }; + if key(old).is_some() && key(old) == key(&rec) { + rec.status = old.status; + rec.status_reason = old.status_reason.clone(); + } else if let Err(e) = rt.disconnect(old, &Owner::Team).await { + return Err(SaveError::Internal(e)); + } + rec.added_by = old.added_by.clone(); + rec.added_at = old.added_at.clone(); + rec.custom_prompt = old.custom_prompt.clone(); + } + rt.store + .put_server(&rt.team, &rec) + .await + .map_err(SaveError::Internal)?; + Ok(rec) +} + +/// Makes CoderHelm's app the team's sign-in for `catalog_id`: directly with +/// the app from the deployment's secret, or through the hosted broker on a +/// hybrid install that chose it. Replaces the team's own app, if one was +/// saved. The caller then starts the sign-in on the returned record. +pub async fn use_coderhelm_app( + rt: &Runtime, + catalog_id: &str, + via: crate::knowledge::sources::oauth::Via<'_>, + by: &str, + at: &str, +) -> Result { + use crate::knowledge::sources::oauth::Via; + let app = crate::mcp_catalog::own_app(catalog_id).ok_or(SaveError::NoOwnApp)?; + let def = crate::mcp_catalog::find(catalog_id).ok_or(SaveError::NoOwnApp)?; + let id = connection_id(catalog_id); + let rec = match via { + Via::App(a) if a.is_set() => { + let sealed = rt + .seal_client_secret(&id, a.client_secret.trim()) + .await + .map_err(SaveError::Internal)?; + record(catalog_id, def.name, &app, a.client_id.trim(), &sealed) + } + Via::Broker { + hosted, + install_id, + secret, + } if !hosted.trim().is_empty() + && !install_id.trim().is_empty() + && !secret.trim().is_empty() => + { + let sealed = rt + .seal_client_secret(&id, secret.trim()) + .await + .map_err(SaveError::Internal)?; + brokered_record(catalog_id, def.name, hosted, install_id.trim(), &sealed) + } + _ => return Err(SaveError::NotSetUp), + }; + replace(rt, rec, by, at).await +} + fn origin(u: &str) -> String { url::Url::parse(u) .map(|p| p.origin().ascii_serialization()) @@ -87,6 +247,8 @@ pub enum SaveError { NoOwnApp, /// Something the person pasted isn't usable; the message says what. Invalid(&'static str), + /// CoderHelm's app for this server isn't set up on this deployment. + NotSetUp, Internal(String), } @@ -128,27 +290,13 @@ pub async fn save( .await .map_err(SaveError::Internal)?, }; - let mut rec = record(catalog_id, def.name, &app, client_id, &sealed); - rec.added_by = by.to_ascii_lowercase(); - rec.added_at = at.to_string(); - rec.status = Status::NotConnected; - if let Some(old) = &old { - let same_app = old_oauth.as_ref().is_some_and(|o| o.client_id == client_id); - if same_app { - rec.status = old.status; - rec.status_reason = old.status_reason.clone(); - } else if let Err(e) = rt.disconnect(old, &Owner::Team).await { - return Err(SaveError::Internal(e)); - } - rec.added_by = old.added_by.clone(); - rec.added_at = old.added_at.clone(); - rec.custom_prompt = old.custom_prompt.clone(); - } - rt.store - .put_server(&rt.team, &rec) - .await - .map_err(SaveError::Internal)?; - Ok(rec) + replace( + rt, + record(catalog_id, def.name, &app, client_id, &sealed), + by, + at, + ) + .await } /// The team's own-app record for `catalog_id`, when one is saved. @@ -512,4 +660,272 @@ mod tests { assert!(e.contains("published for your team"), "{e}"); assert!(!connected(&rt, "figma").await); } + + fn coderhelm_app() -> crate::knowledge::sources::oauth::App { + crate::knowledge::sources::oauth::App { + client_id: "ch-client".into(), + client_secret: "ch-secret".into(), + } + } + + /// The hosted service (or an install with CoderHelm's app in its secret) + /// signs in with CoderHelm's public Figma app at Figma itself, and the + /// package gets the token exactly as with the team's own app. + #[tokio::test] + async fn coderhelm_app_signs_in_at_figma_with_its_own_client() { + use crate::knowledge::sources::oauth::Via; + let http = Arc::new(Fake::default()); + let rt = rt_with(http.clone(), 1_000_000); + let app = coderhelm_app(); + let mut s = use_coderhelm_app(&rt, "figma", Via::App(&app), "Ada@Example.com", "t0") + .await + .unwrap(); + assert_eq!(s.id, "app-figma"); + assert_eq!(source(&s, "ch-client"), Source::Coderhelm); + assert_eq!(source(&s, ""), Source::Own); + let url = rt + .start_sign_in( + &mut s, + &Owner::Team, + "sub-1", + "ada@example.com", + REDIRECT, + None, + ) + .await + .unwrap(); + let q = query(&url); + assert!(url.starts_with("https://www.figma.com/oauth?")); + assert_eq!(q["client_id"], "ch-client"); + assert_eq!(q["redirect_uri"], REDIRECT); + assert_eq!(q["scope"], "current_user:read file_content:read"); + http.on( + Method::Post, + "https://api.figma.com/v1/oauth/token", + fjson( + 200, + json!({"access_token": "at-1", "expires_in": 7_776_000, "refresh_token": "rt-1"}), + ), + ); + rt.finish_sign_in( + &q["state"], + Some("code-1"), + None, + None, + "sub-1", + "ada@example.com", + ) + .await + .unwrap(); + assert_eq!( + token_env(&rt, "figma").await.unwrap(), + Some(("FIGMA_OAUTH_TOKEN", "at-1".to_string())) + ); + // A state from another sign-in, or used twice, finishes nothing. + assert!(rt + .finish_sign_in( + &q["state"], + Some("code-1"), + None, + None, + "sub-1", + "ada@example.com" + ) + .await + .is_err()); + assert!(rt + .finish_sign_in( + "forged", + Some("code-2"), + None, + None, + "sub-1", + "ada@example.com" + ) + .await + .is_err()); + } + + /// Without CoderHelm's app in the secret and without the broker, there + /// is nothing to sign in with: no authorize address is ever built. + #[tokio::test] + async fn coderhelm_app_needs_a_client_or_the_broker() { + use crate::knowledge::sources::oauth::{App, Via}; + let rt = rt_with(Arc::new(Fake::default()), 1); + let none = App::default(); + assert_eq!( + use_coderhelm_app(&rt, "figma", Via::App(&none), "a@example.com", "t0") + .await + .unwrap_err(), + SaveError::NotSetUp + ); + let blank = Via::Broker { + hosted: "https://api.coderhelm.com", + install_id: "", + secret: "s", + }; + assert_eq!( + use_coderhelm_app(&rt, "figma", blank, "a@example.com", "t0") + .await + .unwrap_err(), + SaveError::NotSetUp + ); + assert_eq!( + use_coderhelm_app( + &rt, + "sentry", + Via::App(&coderhelm_app()), + "a@example.com", + "t0" + ) + .await + .unwrap_err(), + SaveError::NoOwnApp + ); + assert!(rt + .store + .get_server(&rt.team, "app-figma") + .await + .unwrap() + .is_none()); + } + + /// A hybrid install that chose CoderHelm's app signs in through the + /// hosted broker: the broker is the authorization server, the install + /// id and its registration secret are the client, the redirect is the + /// install's own callback page, and the token is renewed at the broker + /// with the grant handle (never at Figma: the install has no Figma + /// refresh token or secret). + #[tokio::test] + async fn a_hybrid_install_signs_in_through_the_broker_and_renews_there() { + use crate::knowledge::sources::oauth::Via; + let http = Arc::new(Fake::default()); + let rt = rt_with(http.clone(), 3_000_000); + let via = Via::Broker { + hosted: "https://api.coderhelm.com/", + install_id: "in_abc", + secret: "reg-secret", + }; + let mut s = use_coderhelm_app(&rt, "figma", via, "a@example.com", "t0") + .await + .unwrap(); + assert_eq!(source(&s, ""), Source::Coderhelm); + let o = s.oauth.clone().unwrap(); + assert_eq!( + o.authorization_endpoint, + "https://api.coderhelm.com/hybrid/oauth/figma/authorize" + ); + assert_eq!( + o.token_endpoint, + "https://api.coderhelm.com/hybrid/oauth/token" + ); + assert_eq!(o.refresh_endpoint, ""); + assert!(o.scopes.is_empty()); + let url = rt + .start_sign_in( + &mut s, + &Owner::Team, + "sub-1", + "a@example.com", + REDIRECT, + None, + ) + .await + .unwrap(); + let q = query(&url); + assert!(url.starts_with("https://api.coderhelm.com/hybrid/oauth/figma/authorize?")); + assert_eq!(q["client_id"], "in_abc"); + assert_eq!(q["redirect_uri"], REDIRECT); + assert_eq!(q["code_challenge_method"], "S256"); + assert!(!q.contains_key("client_secret")); + http.on( + Method::Post, + "https://api.coderhelm.com/hybrid/oauth/token", + fjson(200, json!({"access_token": "fig-at-1", "token_type": "Bearer", "expires_in": 600, "refresh_token": "hr_handle"})), + ); + rt.finish_sign_in( + &q["state"], + Some("hc_code"), + None, + None, + "sub-1", + "a@example.com", + ) + .await + .unwrap(); + let sent = http.sent_to("https://api.coderhelm.com/hybrid/oauth/token"); + let body = sent[0].body_text(); + assert!(body.contains("client_id=in_abc") && body.contains("client_secret=reg-secret")); + assert!(body.contains("code_verifier=") && body.contains("code=hc_code")); + assert_eq!( + token_env(&rt, "figma").await.unwrap(), + Some(("FIGMA_OAUTH_TOKEN", "fig-at-1".to_string())) + ); + // Renewed at the broker with the handle. + http.on( + Method::Post, + "https://api.coderhelm.com/hybrid/oauth/token", + fjson(200, json!({"access_token": "fig-at-2", "expires_in": 600, "refresh_token": "hr_handle"})), + ); + let s = load(&rt, "figma").await.unwrap().unwrap(); + rt.auth_header(&s, &Owner::Team, true).await.unwrap(); + let sent = http.sent_to("https://api.coderhelm.com/hybrid/oauth/token"); + assert!(sent[1].body_text().contains("grant_type=refresh_token")); + assert!(sent[1].body_text().contains("refresh_token=hr_handle")); + assert!(http + .sent_to("https://api.figma.com/v1/oauth/refresh") + .is_empty()); + } + + /// Switching between the team's own app and CoderHelm's ends the old + /// sign-in; signing in again with the same app keeps it. + #[tokio::test] + async fn switching_apps_ends_the_old_sign_in() { + use crate::knowledge::sources::oauth::Via; + let rt = rt_with(Arc::new(Fake::default()), 1); + save(&rt, "figma", "own-1", "own-secret", "a@example.com", "t0") + .await + .unwrap(); + sign_in( + &rt, + "app-figma", + &Owner::Team, + "at", + Some("rt"), + None, + "a@example.com", + ) + .await; + rt.store + .set_status(&rt.team, "app-figma", Status::Connected, "") + .await + .unwrap(); + assert!(connected(&rt, "figma").await); + let app = coderhelm_app(); + let s = use_coderhelm_app(&rt, "figma", Via::App(&app), "b@example.com", "t1") + .await + .unwrap(); + assert!(!connected(&rt, "figma").await); + assert_eq!(s.added_by, "a@example.com"); + sign_in( + &rt, + "app-figma", + &Owner::Team, + "at2", + Some("rt2"), + None, + "b@example.com", + ) + .await; + rt.store + .set_status(&rt.team, "app-figma", Status::Connected, "") + .await + .unwrap(); + // Same app again (a reconnect): the sign-in stays until the new one lands. + let s = use_coderhelm_app(&rt, "figma", Via::App(&app), "b@example.com", "t2") + .await + .unwrap(); + assert_eq!(s.status, Status::Connected); + assert!(connected(&rt, "figma").await); + } } diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index fea043c49..868dda969 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1069,6 +1069,10 @@ async fn main() -> Result<(), Error> { "/mcp-servers/apps/:catalog_id", put(routes::mcp_servers::save_own_app), ) + .route( + "/mcp-servers/apps/:catalog_id/coderhelm", + post(routes::mcp_servers::connect_coderhelm_app), + ) .route( "/mcp-servers/:id/client", put(routes::mcp_servers::set_client), diff --git a/services/gateway/src/models.rs b/services/gateway/src/models.rs index a48cb46ed..2c51c9c4e 100644 --- a/services/gateway/src/models.rs +++ b/services/gateway/src/models.rs @@ -156,6 +156,14 @@ pub struct Secrets { pub google_drive_client_id: Option, #[serde(default)] pub google_drive_client_secret: Option, + /// Figma: CoderHelm's public Figma OAuth app on the hosted side (or an + /// install's own app for every team on it). Its package then reads + /// Figma's API with a sign-in instead of a key; hybrid installs sign in + /// through the hosted broker with it. + #[serde(default)] + pub figma_client_id: Option, + #[serde(default)] + pub figma_client_secret: Option, /// Hosted side of hybrid only: the key every install's registration /// secret and relay key are derived from (common::hybrid::sign). Absent /// on self-hosted installs, which then never serve `/hybrid/*`. @@ -172,8 +180,9 @@ pub struct Secrets { } impl Secrets { - /// A knowledge source sign-in key by its name in the secret - /// (`oauth::Provider::id_key` / `secret_key`). Only those keys answer. + /// An OAuth app key by its name in the secret: a knowledge source's + /// (`oauth::Provider::id_key` / `secret_key`) or a catalog server's + /// (`mcp_catalog::OwnApp::coderhelm_keys`). Only those keys answer. pub fn oauth_key(&self, key: &str) -> Option { match key { "notion_client_id" => self.notion_client_id.clone(), @@ -182,6 +191,8 @@ impl Secrets { "atlassian_client_secret" => self.atlassian_client_secret.clone(), "google_drive_client_id" => self.google_drive_client_id.clone(), "google_drive_client_secret" => self.google_drive_client_secret.clone(), + "figma_client_id" => self.figma_client_id.clone(), + "figma_client_secret" => self.figma_client_secret.clone(), _ => None, } } diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 79223c4d8..df44c6fff 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -555,6 +555,7 @@ pub const CAPABILITIES: &[Capability] = &[ "mcp_servers::remove", "mcp_servers::set_client", "mcp_servers::save_own_app", + "mcp_servers::connect_coderhelm_app", "mcp_servers::set_key", "mcp_servers::set_tools", "mcp_servers::approve", diff --git a/services/gateway/src/routes/hybrid.rs b/services/gateway/src/routes/hybrid.rs index 5978604d5..3f57464f4 100644 --- a/services/gateway/src/routes/hybrid.rs +++ b/services/gateway/src/routes/hybrid.rs @@ -2742,33 +2742,92 @@ pub async fn share( Ok(Json(json!({ "ok": true }))) } -// ── OAuth broker (Notion, Confluence, Google Drive) ────────────────────── +// ── OAuth broker (Notion, Confluence, Google Drive, Figma) ─────────────── -fn kind_of(raw: &str) -> Option { +/// A provider the broker signs installs in to with CoderHelm's app: a +/// knowledge source, or a catalog server whose package takes a token (Figma). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Brokered { + Source(common::knowledge::sources::Kind), + App(&'static str), +} + +impl Brokered { + /// The id installs and the hybrid settings name it by. + pub fn key(self) -> &'static str { + match self { + Brokered::Source(k) => k.key(), + Brokered::App(id) => id, + } + } + + /// The id of its sign-in record (the same on both sides). + pub fn connection_id(self) -> String { + match self { + Brokered::Source(k) => common::knowledge::sources::oauth::connection_id(k), + Brokered::App(id) => common::mcp_remote::own_app::connection_id(id), + } + } + + /// The sign-in record with CoderHelm's app `client_id` (its secret + /// already sealed for the record). + pub fn record( + self, + client_id: &str, + sealed: &str, + ) -> Option { + match self { + Brokered::Source(k) => { + let p = common::knowledge::sources::oauth::provider(k)?; + Some(common::knowledge::sources::oauth::connection_record( + k, &p, client_id, sealed, + )) + } + Brokered::App(id) => { + let app = common::mcp_catalog::own_app(id)?; + let def = common::mcp_catalog::find(id)?; + Some(common::mcp_remote::own_app::record( + id, def.name, &app, client_id, sealed, + )) + } + } + } +} + +/// The provider an id names, when the broker serves it. +pub fn brokered_of(raw: &str) -> Option { use common::knowledge::sources::Kind; match raw { - "notion" => Some(Kind::Notion), - "confluence" => Some(Kind::Confluence), - "google_drive" | "google-drive" => Some(Kind::GoogleDrive), + "notion" => Some(Brokered::Source(Kind::Notion)), + "confluence" => Some(Brokered::Source(Kind::Confluence)), + "google_drive" | "google-drive" => Some(Brokered::Source(Kind::GoogleDrive)), + "figma" => Some(Brokered::App("figma")), _ => None, } } -/// The hosted integrations this side can actually serve: a knowledge +/// CoderHelm's app for a brokered provider, from the hosted secret. +fn broker_app(state: &AppState, b: Brokered) -> common::knowledge::sources::oauth::App { + match b { + Brokered::Source(k) => super::knowledge_sources::app(state, k), + Brokered::App(id) => super::mcp_servers::coderhelm_app(state, id), + } +} + +/// The hosted integrations this side can actually serve: a brokered /// provider only when CoderHelm's own app for it is set up (Google Drive /// needs `google_drive_client_id` and `google_drive_client_secret`, never -/// the Google sign-in client). Installs see this as `offered` and can't -/// choose the rest. +/// the Google sign-in client; Figma `figma_client_id` and +/// `figma_client_secret`). Installs see this as `offered` and can't choose +/// the rest. pub fn offered_ids(state: &AppState) -> Vec<&'static str> { - offered_from(|k| super::knowledge_sources::app(state, k).is_set()) + offered_from(|b| broker_app(state, b).is_set()) } /// [`offered_ids`] for a given "is this provider's app set up" (pure; tested). -pub fn offered_from( - app_set: impl Fn(common::knowledge::sources::Kind) -> bool, -) -> Vec<&'static str> { +pub fn offered_from(app_set: impl Fn(Brokered) -> bool) -> Vec<&'static str> { common::hybrid::integrations::hosted_ids() - .filter(|id| kind_of(id).is_none_or(&app_set)) + .filter(|id| brokered_of(id).is_none_or(&app_set)) .collect() } @@ -2825,7 +2884,7 @@ pub async fn oauth_authorize( ) .into_response(); } - let Some(k) = kind_of(&kind) else { + let Some(k) = brokered_of(&kind) else { return (StatusCode::NOT_FOUND, "Unknown provider.").into_response(); }; let install_id = q.client_id.unwrap_or_default(); @@ -2856,10 +2915,7 @@ pub async fn oauth_authorize( let flow = broker::new_handle("fl"); let team = signin_team(&install.id, &flow); let rt = super::mcp_servers::runtime(&state, &team); - let a = super::knowledge_sources::app(&state, k); - let Some(p) = common::knowledge::sources::oauth::provider(k) else { - return StatusCode::NOT_FOUND.into_response(); - }; + let a = broker_app(&state, k); if !a.is_set() { return ( StatusCode::SERVICE_UNAVAILABLE, @@ -2867,12 +2923,13 @@ pub async fn oauth_authorize( ) .into_response(); } - let id = common::knowledge::sources::oauth::connection_id(k); + let id = k.connection_id(); let Ok(sealed) = rt.seal_client_secret(&id, a.client_secret.trim()).await else { return StatusCode::SERVICE_UNAVAILABLE.into_response(); }; - let mut rec = - common::knowledge::sources::oauth::connection_record(k, &p, a.client_id.trim(), &sealed); + let Some(mut rec) = k.record(a.client_id.trim(), &sealed) else { + return StatusCode::NOT_FOUND.into_response(); + }; rec.added_by = format!("hybrid:{}", install.id); rec.added_at = now(); if rt.store.put_server(&team, &rec).await.is_err() { @@ -3018,19 +3075,19 @@ async fn adopt_provider_sign_in( if !is_flow(flow) { return Err("no holding partition".into()); } - let k = kind_of(kind).ok_or("unknown provider")?; - let p = common::knowledge::sources::oauth::provider(k).ok_or("unknown provider")?; - let a = super::knowledge_sources::app(state, k); + let k = brokered_of(kind).ok_or("unknown provider")?; + let a = broker_app(state, k); if !a.is_set() { return Err("CoderHelm's app for this provider isn't set up".into()); } let team = hosted_team(install_id); let rt = super::mcp_servers::runtime(state, &team); let hold = super::mcp_servers::runtime(state, &signin_team(install_id, flow)); - let id = common::knowledge::sources::oauth::connection_id(k); + let id = k.connection_id(); let sealed = rt.seal_client_secret(&id, a.client_secret.trim()).await?; - let mut rec = - common::knowledge::sources::oauth::connection_record(k, &p, a.client_id.trim(), &sealed); + let mut rec = k + .record(a.client_id.trim(), &sealed) + .ok_or("unknown provider")?; rec.added_by = format!("hybrid:{install_id}"); rec.added_at = now(); rt.store.put_server(&team, &rec).await?; @@ -3170,12 +3227,12 @@ pub async fn oauth_token(State(state): State>, body: Bytes) -> Rep "CoderHelm's app for this provider was turned off for this install.", )); } - let k = kind_of(&kind).ok_or_else(|| token_error("invalid_grant", "Unknown provider."))?; + let k = brokered_of(&kind).ok_or_else(|| token_error("invalid_grant", "Unknown provider."))?; let team = hosted_team(&install.id); let rt = super::mcp_servers::runtime(&state, &team); let rec = rt .store - .get_server(&team, &common::knowledge::sources::oauth::connection_id(k)) + .get_server(&team, &k.connection_id()) .await .ok() .flatten() @@ -3354,12 +3411,61 @@ mod tests { use common::knowledge::sources::Kind; let none = offered_from(|_| false); assert_eq!(none, vec!["github", "jira"]); - let no_drive = offered_from(|k| k != Kind::GoogleDrive); + let no_drive = offered_from(|k| k != Brokered::Source(Kind::GoogleDrive)); assert!(!no_drive.contains(&"google_drive")); assert!(no_drive.contains(&"notion") && no_drive.contains(&"confluence")); assert!(offered_from(|_| true).contains(&"google_drive")); } + /// Figma is offered only once CoderHelm's Figma app is in the hosted + /// secret, like every other brokered provider. + #[test] + fn figma_is_offered_only_with_coderhelms_figma_app() { + assert!(!offered_from(|b| b != Brokered::App("figma")).contains(&"figma")); + assert!(offered_from(|_| true).contains(&"figma")); + } + + /// The broker serves Figma with the same record an install keeps (id + /// `app-figma`), signed in at Figma itself with CoderHelm's client. + #[test] + fn figma_is_brokered_with_its_own_app_record() { + let b = brokered_of("figma").unwrap(); + assert_eq!(b.key(), "figma"); + assert_eq!(b.connection_id(), "app-figma"); + let r = b.record("ch-client", "sealed").unwrap(); + assert_eq!(r.id, "app-figma"); + assert_eq!(r.catalog_id, "app:figma"); + let o = r.oauth.unwrap(); + assert_eq!(o.authorization_endpoint, "https://www.figma.com/oauth"); + assert_eq!(o.token_endpoint, "https://api.figma.com/v1/oauth/token"); + assert_eq!(o.refresh_endpoint, "https://api.figma.com/v1/oauth/refresh"); + assert_eq!(o.client_id, "ch-client"); + assert_eq!(o.scopes, vec!["current_user:read", "file_content:read"]); + // Knowledge sources keep their ids; anything else isn't brokered. + assert_eq!(brokered_of("notion").unwrap().connection_id(), "ks-notion"); + assert!(brokered_of("sentry").is_none() && brokered_of("github").is_none()); + } + + /// The broker hands a sign-in back only to the install's own callback + /// page (the one redirect Figma knows is the hosted page; the install's + /// is checked here, never sent to Figma). + #[test] + fn a_figma_sign_in_returns_only_to_the_installs_callback() { + let origins = vec!["https://acme.coderhelm.com".to_string()]; + assert!(broker::redirect_allowed( + "https://acme.coderhelm.com/settings/integrations/mcp-callback/", + &origins + )); + for bad in [ + "https://other.coderhelm.com/settings/integrations/mcp-callback/", + "https://acme.coderhelm.com/settings/integrations/mcp-callback/?next=https://evil.example", + "https://acme.coderhelm.com/settings/integrations/figma/", + "http://acme.coderhelm.com/settings/integrations/mcp-callback/", + ] { + assert!(!broker::redirect_allowed(bad, &origins), "{bad}"); + } + } + use super::*; /// Linking writes the install's link and the installation's reverse diff --git a/services/gateway/src/routes/hybrid_install.rs b/services/gateway/src/routes/hybrid_install.rs index b8dbd1bae..f07cd06c9 100644 --- a/services/gateway/src/routes/hybrid_install.rs +++ b/services/gateway/src/routes/hybrid_install.rs @@ -711,6 +711,7 @@ fn strings(v: &Value) -> Option> { fn own_app_set(state: &AppState, id: &str) -> bool { common::knowledge::sources::Kind::parse(id) .is_some_and(|k| super::knowledge_sources::app(state, k).is_set()) + || super::mcp_servers::coderhelm_app(state, id).is_set() } /// Does `id` use CoderHelm's app: as chosen, or by default (CoderHelm's, @@ -2234,9 +2235,23 @@ pub async fn brokered( creds_now().await } +/// [`brokered`] for a catalog server signed in with an app (Figma), by its +/// catalog id (the same id the hybrid settings list it under). +pub async fn brokered_id(state: &AppState, id: &str) -> Option { + let l = local(state).await; + if !brokers_id(&l, id) { + return None; + } + creds_now().await +} + /// Whether the hybrid settings route `kind` through CoderHelm's app. fn brokers(l: &Local, kind: common::knowledge::sources::Kind) -> bool { - l.integrations.iter().any(|i| i == kind.key()) + brokers_id(l, kind.key()) +} + +fn brokers_id(l: &Local, id: &str) -> bool { + l.integrations.iter().any(|i| i == id) } /// For the public GitHub checks: is GitHub going through CoderHelm's app? @@ -2269,14 +2284,16 @@ mod tests { assert!(migrate_apps(&mut l, None) && l.apps.is_empty()); assert_eq!( wanted_integrations(&l, no_own_apps), - vec!["jira", "notion", "confluence", "google_drive"] + vec!["jira", "notion", "confluence", "google_drive", "figma"] ); // An explicit "my own app" is kept; the rest stay on the default. l.apps.insert("notion".into(), "own".into()); assert!(!uses_coderhelm(&l, "notion", no_own_apps)); assert!(uses_coderhelm(&l, "confluence", no_own_apps)); // A tool nobody chose, with the install's own app set up, keeps it. - let own_drive = |id: &str| id == "google_drive"; + let own_drive = |id: &str| id == "google_drive" || id == "figma"; + // An install with its own Figma app in its secret keeps it too. + assert!(!uses_coderhelm(&l, "figma", own_drive)); assert!(!uses_coderhelm(&l, "google_drive", own_drive)); // Chosen CoderHelm's app explicitly: wins over an own app set up. l.apps.insert("google_drive".into(), "coderhelm".into()); @@ -2284,7 +2301,7 @@ mod tests { l.github_mode = "hosted".into(); assert_eq!( wanted_integrations(&l, no_own_apps), - vec!["github", "jira", "confluence", "google_drive"] + vec!["github", "jira", "confluence", "google_drive", "figma"] ); // Unrecorded: the serde default of a record from before is unset. let old: Local = serde_json::from_str(r#"{"integrations":["github"]}"#).unwrap(); @@ -2303,7 +2320,14 @@ mod tests { assert!(l.apps.is_empty()); assert_eq!( wanted_integrations(&l, no_own_apps), - vec!["github", "jira", "notion", "confluence", "google_drive"] + vec![ + "github", + "jira", + "notion", + "confluence", + "google_drive", + "figma" + ] ); assert!(!migrate_apps(&mut l, None), "only once"); // Chose Notion only, while Google Drive wasn't offered: Jira and @@ -2322,7 +2346,7 @@ mod tests { assert!(!l.apps.contains_key("google_drive")); assert_eq!( wanted_integrations(&l, no_own_apps), - vec!["notion", "google_drive"] + vec!["notion", "google_drive", "figma"] ); assert!(offered_by(Some(&serde_json::json!({}))).is_none()); } @@ -2357,7 +2381,7 @@ mod tests { apply_settings(&mut l, &b).unwrap(); assert_eq!( wanted_integrations(&l, no_own_apps), - vec!["jira", "confluence", "google_drive"] + vec!["jira", "confluence", "google_drive", "figma"] ); let bad = |id: &str, v: &str| SettingsBody { apps: Some([(id.to_string(), v.to_string())].into()), diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index 40fe76383..8d9febf7f 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -131,19 +131,24 @@ pub fn plugin_state( /// in yet) the key's state stands, saying a sign-in is waiting. pub fn own_app_state(own_app: &Value, key: &CardState) -> CardState { let reason = own_app["status_reason"].as_str().unwrap_or("").to_string(); + let coderhelm = own_app["source"] == "coderhelm"; match own_app["status"].as_str().unwrap_or("") { + "connected" if coderhelm => cs("connected", "Signed in with Coderhelm's app.", "manage"), "connected" => cs("connected", "Signed in with your own app.", "manage"), "needs_reconnect" => cs( "needs_reconnect", - if reason.is_empty() { - "Your own app's sign-in has to be renewed.".to_string() - } else { + if !reason.is_empty() { reason + } else if coderhelm { + "The sign-in has to be renewed.".to_string() + } else { + "Your own app's sign-in has to be renewed.".to_string() }, "reconnect", ), "failed" => cs("error", reason, "check_again"), _ if key.status == "connected" => key.clone(), + _ if coderhelm => cs("not_connected", "", "connect"), _ => cs( "not_connected", "Your own app is saved. Connect it to sign in.", @@ -709,7 +714,7 @@ pub async fn list( } }; let own_json = match &own { - Some(o) => Some(super::mcp_servers::own_app_json(&rt, o, &state.config.stage).await), + Some(o) => Some(super::mcp_servers::own_app_json(&state, &rt, o).await), None => None, }; let st = match own_json.as_ref().map(|o| own_app_state(o, &st)) { @@ -719,9 +724,13 @@ pub async fn list( // Where the team's own app sends people back, for its setup steps. let own_redirect = common::mcp_catalog::own_app(&id) .map(|_| super::mcp_servers::redirect_uri(&state.config.stage)); + // The one-click sign-in with CoderHelm's app, where it works here. + let coderhelm_app = + own_redirect.is_some() && super::mcp_servers::coderhelm_app_ready(&state, &id).await; let detail = json!({ "own_app": own_json, "own_app_redirect_uri": own_redirect, + "coderhelm_app": coderhelm_app, "remote": remote.map(|r| r.public_json(my_tokens.get(&r.id), can_edit)), "plugin": p, "enabled": enabled.unwrap_or(false), @@ -967,6 +976,21 @@ mod tests { let st = own_app_state(&own("not_connected", ""), &key_off); assert_eq!((st.status, st.action), ("not_connected", "connect")); } + + #[test] + fn a_sign_in_with_coderhelms_app_says_so() { + let key_off = plugin_state(None, false, None, "", false); + let ours = + |status: &str| json!({ "status": status, "status_reason": "", "source": "coderhelm" }); + let st = own_app_state(&ours("connected"), &key_off); + assert_eq!(st.reason, "Signed in with Coderhelm's app."); + let st = own_app_state(&ours("needs_reconnect"), &key_off); + assert_eq!((st.status, st.action), ("needs_reconnect", "reconnect")); + assert!(!st.reason.contains("own app")); + // Started but not finished: nothing of "your own app" on the card. + let st = own_app_state(&ours("not_connected"), &key_off); + assert_eq!((st.status, st.reason.as_str()), ("not_connected", "")); + } use common::live::identity::RoleCheck; fn account() -> AwsAccount { diff --git a/services/gateway/src/routes/mcp_servers.rs b/services/gateway/src/routes/mcp_servers.rs index 30000c280..4066f89f7 100644 --- a/services/gateway/src/routes/mcp_servers.rs +++ b/services/gateway/src/routes/mcp_servers.rs @@ -566,16 +566,18 @@ pub async fn save_own_app( "This server can't use your own app. Use a key instead.", ), own_app::SaveError::Invalid(m) => fail(StatusCode::BAD_REQUEST, m), + own_app::SaveError::NotSetUp => fail(StatusCode::BAD_REQUEST, "Paste the app's client id."), own_app::SaveError::Internal(e) => internal("save own app", e), })?; info!(team = %rt.team, server = %s.id, by = %claims.email, "Own app saved"); Ok(Json( - json!({ "own_app": own_app_json(&rt, &s, &state.config.stage).await }), + json!({ "own_app": own_app_json(&state, &rt, &s).await }), )) } -/// A team's own app for a catalog server, for its card: never the secret. -pub async fn own_app_json(rt: &Runtime, s: &ServerRecord, stage: &str) -> Value { +/// A catalog server's sign-in, for its card: never the secret. `source` is +/// whose app it uses (`coderhelm` or `own`). +pub async fn own_app_json(state: &AppState, rt: &Runtime, s: &ServerRecord) -> Value { let token = rt .store .get_token(&rt.team, &s.id, &Owner::Team) @@ -587,18 +589,136 @@ pub async fn own_app_json(rt: &Runtime, s: &ServerRecord, stage: &str) -> Value None => (Status::NotConnected, String::new()), }; let o = s.oauth.as_ref(); + let coderhelm_id = own_app::catalog_of(&s.catalog_id) + .map(|c| coderhelm_app(state, c).client_id) + .unwrap_or_default(); + let source = own_app::source(s, &coderhelm_id); json!({ "id": s.id, - "client_id": o.map(|o| o.client_id.as_str()).unwrap_or(""), - "has_secret": o.is_some_and(|o| !o.client_secret_sealed.is_empty()), + "source": source.as_str(), + // CoderHelm's client id is no secret, but it is no business of the card's. + "client_id": match source { + own_app::Source::Own => o.map(|o| o.client_id.as_str()).unwrap_or(""), + own_app::Source::Coderhelm => "", + }, + "has_secret": source == own_app::Source::Own && o.is_some_and(|o| !o.client_secret_sealed.is_empty()), "status": status.as_str(), "status_reason": reason, "connected_by": token.as_ref().map(|t| t.connected_by.as_str()).unwrap_or(""), "connected_at": token.as_ref().map(|t| t.connected_at.as_str()).unwrap_or(""), - "redirect_uri": redirect_uri(stage), + "redirect_uri": redirect_uri(&state.config.stage), }) } +/// CoderHelm's own public app with the vendor of `catalog_id`, from this +/// deployment's secret (`mcp_catalog::OwnApp::coderhelm_keys`). Not set where +/// the secret has no such keys. +pub(crate) fn coderhelm_app( + state: &AppState, + catalog_id: &str, +) -> common::knowledge::sources::oauth::App { + coderhelm_app_from(&state.secrets, catalog_id) +} + +pub(crate) fn coderhelm_app_from( + secrets: &crate::models::Secrets, + catalog_id: &str, +) -> common::knowledge::sources::oauth::App { + let Some(app) = common::mcp_catalog::own_app(catalog_id) else { + return Default::default(); + }; + let read = |k: &str| { + secrets + .oauth_key(k) + .map(|v| v.trim().to_string()) + .unwrap_or_default() + }; + common::knowledge::sources::oauth::App { + client_id: read(app.coderhelm_keys.0), + client_secret: read(app.coderhelm_keys.1), + } +} + +/// Whether the one-click sign-in with CoderHelm's app works here for +/// `catalog_id`: through the hosted broker on a hybrid install that chose +/// it, or with the app in this deployment's secret. +pub async fn coderhelm_app_ready(state: &AppState, catalog_id: &str) -> bool { + common::mcp_catalog::own_app(catalog_id).is_some() + && (coderhelm_app(state, catalog_id).is_set() + || super::hybrid_install::brokered_id(state, catalog_id) + .await + .is_some()) +} + +/// POST /api/mcp-servers/apps/:catalog_id/coderhelm — sign in with +/// CoderHelm's app for a catalog server whose package takes a token (Figma). +/// Makes it the team's sign-in (in place of the team's own app, if one was +/// saved) and answers where to send the browser; the dashboard's callback +/// page finishes it as for any other sign-in. +pub async fn connect_coderhelm_app( + State(state): State>, + Extension(claims): Extension, + Path(catalog_id): Path, +) -> Reply { + claims.require_role(3).map_err(forbidden)?; + if common::mcp_catalog::own_app(&catalog_id).is_none() { + return Err(fail( + StatusCode::NOT_FOUND, + "This server can't sign in with CoderHelm's app. Use a key instead.", + )); + } + // A hybrid install that chose CoderHelm's app signs in through the + // hosted broker; anywhere else, with the app in this deployment's secret. + let brokered = super::hybrid_install::brokered_id(&state, &catalog_id).await; + let app = coderhelm_app(&state, &catalog_id); + let hosted = common::hybrid::hosted_url(); + let via = match &brokered { + Some(c) => common::knowledge::sources::oauth::Via::Broker { + hosted: &hosted, + install_id: &c.install_id, + secret: &c.secret, + }, + None => common::knowledge::sources::oauth::Via::App(&app), + }; + let rt = runtime(&state, &claims.team_id); + let mut s = own_app::use_coderhelm_app( + &rt, + &catalog_id, + via, + &claims.email, + &chrono::Utc::now().to_rfc3339(), + ) + .await + .map_err(|e| match e { + own_app::SaveError::NotSetUp => fail( + StatusCode::BAD_REQUEST, + "CoderHelm's app isn't set up on this install. Use your own app or a key instead.", + ), + own_app::SaveError::NoOwnApp => fail(StatusCode::NOT_FOUND, "This server has no sign-in."), + own_app::SaveError::Invalid(m) => fail(StatusCode::BAD_REQUEST, m), + own_app::SaveError::Internal(e) => internal("use coderhelm app", e), + })?; + let url = rt + .start_sign_in( + &mut s, + &Owner::Team, + &claims.sub, + &claims.email, + &redirect_uri(&state.config.stage), + None, + ) + .await + .map_err(|e| { + warn!(team = %rt.team, server = %s.id, error = %e, "CoderHelm app sign-in could not start"); + fail(StatusCode::BAD_REQUEST, &e) + })?; + info!(team = %rt.team, server = %s.id, brokered = brokered.is_some(), "CoderHelm app sign-in started"); + Ok(Json(json!({ + "authorize_url": url, + "own_app": own_app_json(&state, &rt, &s).await, + }))) +} + /// PUT /api/mcp-servers/:id/key { header_name?, header_value } — replace a /// static key (checked against the server before it is saved). pub async fn set_key(