Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ hypr-agc = { path = "crates/agc", package = "agc" }
hypr-am = { path = "crates/am", package = "am" }
hypr-am2 = { path = "crates/am2", package = "am2" }
hypr-analytics = { path = "crates/analytics", package = "analytics" }
hypr-api-integration = { path = "crates/api-integration", package = "api-integration" }
hypr-api-subscription = { path = "crates/api-subscription", package = "api-subscription" }
hypr-apple-note = { path = "crates/apple-note", package = "apple-note" }
hypr-askama-utils = { path = "crates/askama-utils", package = "askama-utils" }
Expand Down
20 changes: 20 additions & 0 deletions crates/api-integration/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "api-integration"
version = "0.1.0"
edition = "2024"

[dependencies]
hypr-nango = { workspace = true }
hypr-supabase-auth = { workspace = true }

utoipa = { workspace = true }

axum = { workspace = true }
reqwest = { workspace = true, features = ["json"] }
sentry = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }

serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
23 changes: 23 additions & 0 deletions crates/api-integration/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use std::sync::Arc;

#[derive(Clone)]
pub struct IntegrationConfig {
pub nango_api_base: String,
pub nango_api_key: String,
pub auth: Option<Arc<hypr_supabase_auth::SupabaseAuth>>,
}

impl IntegrationConfig {
pub fn new(nango_api_base: impl Into<String>, nango_api_key: impl Into<String>) -> Self {
Self {
nango_api_base: nango_api_base.into(),
nango_api_key: nango_api_key.into(),
auth: None,
}
}

pub fn with_auth(mut self, auth: Arc<hypr_supabase_auth::SupabaseAuth>) -> Self {
self.auth = Some(auth);
self
}
}
7 changes: 7 additions & 0 deletions crates/api-integration/src/env.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use serde::Deserialize;

#[derive(Deserialize)]
pub struct Env {
pub nango_api_base: String,
pub nango_api_key: String,
}
66 changes: 66 additions & 0 deletions crates/api-integration/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Serialize;
use thiserror::Error;

pub type Result<T> = std::result::Result<T, IntegrationError>;

#[derive(Debug, Serialize)]
pub struct ErrorResponse {
pub error: String,
}

#[derive(Debug, Error)]
pub enum IntegrationError {
#[error("Authentication error: {0}")]
Auth(String),

#[error("Nango error: {0}")]
Nango(String),

#[error("Invalid request: {0}")]
BadRequest(String),

#[error("Internal error: {0}")]
Internal(String),
}

impl From<hypr_supabase_auth::Error> for IntegrationError {
fn from(err: hypr_supabase_auth::Error) -> Self {
Self::Auth(err.to_string())
}
}

impl From<hypr_nango::Error> for IntegrationError {
fn from(err: hypr_nango::Error) -> Self {
Self::Nango(err.to_string())
}
}

impl IntoResponse for IntegrationError {
fn into_response(self) -> Response {
let (status, error_code) = match &self {
Self::Auth(_) => (StatusCode::UNAUTHORIZED, "unauthorized"),
Self::BadRequest(_) => (StatusCode::BAD_REQUEST, "bad_request"),
Self::Nango(msg) => {
tracing::error!(error = %msg, "nango_error");
sentry::capture_message(msg, sentry::Level::Error);
(StatusCode::INTERNAL_SERVER_ERROR, "nango_error")
}
Self::Internal(msg) => {
tracing::error!(error = %msg, "internal_error");
sentry::capture_message(msg, sentry::Level::Error);
(StatusCode::INTERNAL_SERVER_ERROR, "internal_server_error")
}
};

let body = Json(ErrorResponse {
error: error_code.to_string(),
});

(status, body).into_response()
}
}
11 changes: 11 additions & 0 deletions crates/api-integration/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
mod config;
mod env;
mod error;
mod routes;
mod state;

pub use config::IntegrationConfig;
pub use env::Env;
pub use error::{IntegrationError, Result};
pub use routes::{openapi, router};
pub use state::AppState;
76 changes: 76 additions & 0 deletions crates/api-integration/src/routes/connect.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use axum::{Json, extract::State, http::HeaderMap};
use serde::Serialize;
use utoipa::ToSchema;

use crate::error::{IntegrationError, Result};
use crate::state::AppState;

#[derive(Debug, Serialize, ToSchema)]
pub struct ConnectSessionResponse {
pub token: String,
pub expires_at: String,
}

#[utoipa::path(
post,
path = "/connect-session",
responses(
(status = 200, description = "Connect session created", body = ConnectSessionResponse),
(status = 401, description = "Unauthorized"),
(status = 500, description = "Internal server error"),
),
tag = "integration",
security(
("bearer_auth" = [])
)
)]
pub async fn create_connect_session(
State(state): State<AppState>,
headers: HeaderMap,
) -> Result<Json<ConnectSessionResponse>> {
let auth_token = extract_token(&headers)?;

let auth = state
.config
.auth
.as_ref()
.ok_or_else(|| IntegrationError::Auth("Auth not configured".to_string()))?;

let claims = auth
.verify_token(auth_token)
.await
.map_err(|e| IntegrationError::Auth(e.to_string()))?;
let user_id = claims.sub;

let req = hypr_nango::NangoConnectSessionRequest {
end_user: hypr_nango::NangoConnectSessionRequestUser {
id: user_id,
display_name: None,
email: None,
},
organization: None,
allowed_integrations: vec![],
integrations_config_defaults: None,
};

let res = state.nango.create_connect_session(req).await?;

match res {
hypr_nango::NangoConnectSessionResponse::Ok { token, expires_at } => {
Ok(Json(ConnectSessionResponse { token, expires_at }))
}
hypr_nango::NangoConnectSessionResponse::Error { code } => {
Err(IntegrationError::Nango(code))
}
}
}

fn extract_token(headers: &HeaderMap) -> Result<&str> {
let auth_header = headers
.get("Authorization")
.and_then(|h| h.to_str().ok())
.ok_or_else(|| IntegrationError::Auth("Missing Authorization header".to_string()))?;

hypr_supabase_auth::SupabaseAuth::extract_token(auth_header)
.ok_or_else(|| IntegrationError::Auth("Invalid Authorization header".to_string()))
}
34 changes: 34 additions & 0 deletions crates/api-integration/src/routes/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
mod connect;

use axum::{Router, routing::post};
use utoipa::OpenApi;

use crate::state::AppState;

pub use connect::ConnectSessionResponse;

#[derive(OpenApi)]
#[openapi(
paths(
connect::create_connect_session,
),
components(
schemas(
ConnectSessionResponse,
)
),
tags(
(name = "integration", description = "Integration management via Nango")
)
)]
pub struct ApiDoc;

pub fn openapi() -> utoipa::openapi::OpenApi {
ApiDoc::openapi()
}

pub fn router(state: AppState) -> Router {
Router::new()
.route("/connect-session", post(connect::create_connect_session))
.with_state(state)
}
22 changes: 22 additions & 0 deletions crates/api-integration/src/state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use hypr_nango::NangoClient;

use crate::config::IntegrationConfig;
use crate::error::IntegrationError;

#[derive(Clone)]
pub struct AppState {
pub config: IntegrationConfig,
pub nango: NangoClient,
}

impl AppState {
pub fn new(config: IntegrationConfig) -> Result<Self, IntegrationError> {
let nango = hypr_nango::NangoClientBuilder::default()
.api_base(&config.nango_api_base)
.api_key(&config.nango_api_key)
.build()
.map_err(|e| IntegrationError::Nango(e.to_string()))?;

Ok(Self { config, nango })
}
}
Loading