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            allowed_request_params: Vec::new(),
94            authorization_params: Vec::new(),
95            account_subject: Some(subject),
96            map_user_info: None,
97            get_user_info: Some(std::sync::Arc::new(FigmaUserInfo {
98                endpoint,
99                mapper: options.map_profile_to_user,
100            })),
101            refresh_access_token: None,
102            verify_id_token: None,
103            id_token: None,
104            disable_id_token_sign_in: false,
105            disable_implicit_sign_up: false,
106            disable_sign_up: false,
107            allow_idp_initiated: false,
108            override_user_info_on_sign_in: false,
109        }
110    }
111}
112struct FigmaUserInfo {
113    endpoint: String,
114    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
115}
116#[async_trait]
117impl OAuthUserInfoHandler for FigmaUserInfo {
118    async fn get_user_info(
119        &self,
120        request: OAuthUserInfoRequest,
121    ) -> Result<OAuthUserInfoResponse, String> {
122        let access_token = request.access_token.ok_or("Missing Figma access token")?;
123        let profile: Value = reqwest::Client::new()
124            .get(&self.endpoint)
125            .bearer_auth(access_token)
126            .send()
127            .await
128            .map_err(|error| error.to_string())?
129            .error_for_status()
130            .map_err(|error| error.to_string())?
131            .json()
132            .await
133            .map_err(|error| error.to_string())?;
134        let mapped = self
135            .mapper
136            .map(|mapper| mapper(profile.clone()))
137            .transpose()?;
138        let user_output = mapped.as_ref().map(|user| user.public_profile(true));
139        let user = match mapped {
140            Some(user) => user,
141            None => OAuthUserInfo {
142                additional_fields: Map::default(),
143                id: scalar(profile.get("id"))?.unwrap_or_default(),
144                name: scalar(profile.get("handle"))?,
145                email: profile
146                    .get("email")
147                    .and_then(Value::as_str)
148                    .unwrap_or_default()
149                    .into(),
150                image: scalar(profile.get("img_url"))?,
151                email_verified: false,
152            },
153        };
154        Ok(OAuthUserInfoResponse {
155            user_output,
156            user,
157            data: profile,
158        })
159    }
160}
161fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
162    match value {
163        None | Some(Value::Null) => Ok(None),
164        Some(Value::String(value)) => Ok(Some(value.clone())),
165        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
166            .map(Some)
167            .map_err(|error| error.to_string()),
168        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
169        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Figma profile field".into()),
170    }
171}
172fn subject(profile: &Value) -> Result<String, String> {
173    let id = scalar(profile.get("id"))?.ok_or("Missing Figma id")?;
174    if id
175        .trim_matches(|character: char| {
176            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
177        })
178        .is_empty()
179        || id == "null"
180        || id == "undefined"
181    {
182        return Err("Invalid Figma id".into());
183    }
184    Ok(id)
185}