Skip to main content

alibi_plugins/oauth/providers/
figma.rs

1//! Figma's ordered scopes, Basic token exchanges and stable raw profile identity.
2use super::{
3    OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4    OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Map;
8use serde_json::Value;
9
10/// Application-owned Figma configuration. Generic signup and asynchronous
11/// user-info/refresh callbacks remain configurable on the returned provider.
12#[derive(Clone)]
13pub struct FigmaOptions {
14    pub client_id: String,
15    pub client_secret: Option<String>,
16    /// Sent only during authorization-code exchange.
17    pub client_key: Option<String>,
18    pub scope: Vec<String>,
19    pub disable_default_scope: bool,
20    pub authorization_endpoint: Option<String>,
21    pub redirect_uri: Option<String>,
22    /// Trusted transport override retaining Figma's actual GET and mapping.
23    pub user_info_endpoint: Option<String>,
24    /// Receives the original profile before its raw account identity is resolved.
25    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
26}
27impl FigmaOptions {
28    #[must_use]
29    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
30        Self {
31            client_id: client_id.into(),
32            client_secret,
33            client_key: None,
34            scope: Vec::new(),
35            disable_default_scope: false,
36            authorization_endpoint: None,
37            redirect_uri: None,
38            user_info_endpoint: None,
39            map_profile_to_user: None,
40        }
41    }
42}
43impl std::fmt::Debug for FigmaOptions {
44    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        formatter
46            .debug_struct("FigmaOptions")
47            .field("client_id", &self.client_id)
48            .field("scope", &self.scope)
49            .field("disable_default_scope", &self.disable_default_scope)
50            .field("authorization_endpoint", &self.authorization_endpoint)
51            .field("redirect_uri", &self.redirect_uri)
52            .finish_non_exhaustive()
53    }
54}
55impl OAuthProvider {
56    #[must_use]
57    pub fn figma(client_id: &str, client_secret: Option<&str>) -> Self {
58        Self::figma_with_options(FigmaOptions::new(
59            client_id,
60            client_secret.map(str::to_owned),
61        ))
62    }
63    #[must_use]
64    pub fn figma_with_options(options: FigmaOptions) -> Self {
65        let secret = options.client_secret.unwrap_or_default();
66        let endpoint = options
67            .user_info_endpoint
68            .unwrap_or_else(|| "https://api.figma.com/v1/me".into());
69        Self {
70            client_id: options.client_id,
71            client_secret: secret,
72            additional_client_ids: Vec::new(),
73            hosted_domain: None,
74            require_email_verification: false,
75            auth_url: options
76                .authorization_endpoint
77                .filter(|value| !value.is_empty())
78                .unwrap_or_else(|| "https://www.figma.com/oauth".into()),
79            token_url: "https://api.figma.com/v1/oauth/token".into(),
80            user_info_url: Some(endpoint.clone()),
81            scopes: vec!["current_user:read".into()],
82            authorization: Some(OAuthAuthorizationPolicy {
83                configured_scopes: options.scope,
84                disable_default_scopes: options.disable_default_scope,
85                require_client_id: true,
86                require_client_secret: true,
87                token_endpoint_auth: Some(OAuthTokenEndpointAuth::ClientSecretBasic),
88                authorization_code_client_key: options.client_key,
89                redirect_uri: options.redirect_uri,
90                login_hint: false,
91                ..OAuthAuthorizationPolicy::default()
92            }),
93            authorization_params: Vec::new(),
94            account_subject: Some(subject),
95            map_user_info: None,
96            get_user_info: Some(std::sync::Arc::new(FigmaUserInfo {
97                endpoint,
98                mapper: options.map_profile_to_user,
99            })),
100            refresh_access_token: None,
101            verify_id_token: None,
102            id_token: None,
103            disable_id_token_sign_in: false,
104            disable_implicit_sign_up: false,
105            disable_sign_up: false,
106            allow_idp_initiated: false,
107            override_user_info_on_sign_in: false,
108        }
109    }
110}
111struct FigmaUserInfo {
112    endpoint: String,
113    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
114}
115#[async_trait]
116impl OAuthUserInfoHandler for FigmaUserInfo {
117    async fn get_user_info(
118        &self,
119        request: OAuthUserInfoRequest,
120    ) -> Result<OAuthUserInfoResponse, String> {
121        let access_token = request.access_token.ok_or("Missing Figma access token")?;
122        let profile: Value = reqwest::Client::new()
123            .get(&self.endpoint)
124            .bearer_auth(access_token)
125            .send()
126            .await
127            .map_err(|error| error.to_string())?
128            .error_for_status()
129            .map_err(|error| error.to_string())?
130            .json()
131            .await
132            .map_err(|error| error.to_string())?;
133        let mapped = self
134            .mapper
135            .map(|mapper| mapper(profile.clone()))
136            .transpose()?;
137        let user_output = mapped.as_ref().map(|user| user.public_profile(true));
138        let user = match mapped {
139            Some(user) => user,
140            None => OAuthUserInfo {
141                additional_fields: Map::default(),
142                id: scalar(profile.get("id"))?.unwrap_or_default(),
143                name: scalar(profile.get("handle"))?,
144                email: profile
145                    .get("email")
146                    .and_then(Value::as_str)
147                    .unwrap_or_default()
148                    .into(),
149                image: scalar(profile.get("img_url"))?,
150                email_verified: false,
151            },
152        };
153        Ok(OAuthUserInfoResponse {
154            user_output,
155            user,
156            data: profile,
157        })
158    }
159}
160fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
161    match value {
162        None | Some(Value::Null) => Ok(None),
163        Some(Value::String(value)) => Ok(Some(value.clone())),
164        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
165            .map(Some)
166            .map_err(|error| error.to_string()),
167        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
168        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Figma profile field".into()),
169    }
170}
171fn subject(profile: &Value) -> Result<String, String> {
172    let id = scalar(profile.get("id"))?.ok_or("Missing Figma id")?;
173    if id
174        .trim_matches(|character: char| {
175            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
176        })
177        .is_empty()
178        || id == "null"
179        || id == "undefined"
180    {
181        return Err("Invalid Figma id".into());
182    }
183    Ok(id)
184}