#[cfg(feature = "enterprise")]
mod audit;
mod auth;
pub mod caching;
pub mod catalog;
pub mod datasets;
mod docs;
pub mod documents;
pub mod downloads;
#[cfg(feature = "enterprise")]
mod enterprise_store;
mod graphql;
mod handlers_simple;
mod handlers_swe;
mod handlers_write;
pub mod inbox;
pub mod notes;
#[cfg(feature = "enterprise")]
mod oidc;
mod recording;
pub mod research;
#[cfg(feature = "enterprise")]
mod retention;
pub mod sdk;
#[cfg(feature = "enterprise")]
mod sso;
mod state;
mod sync;
pub mod training;
mod webhooks;
mod websocket;
#[cfg(feature = "enterprise")]
pub use audit::{
configure_audit_routes, AuditAction, AuditCategory, AuditEvent, AuditEventBuilder, AuditService,
};
pub use auth::configure_auth_routes;
pub use catalog::configure_catalog_routes;
pub use datasets::configure_dataset_routes;
pub use docs::configure_docs_routes;
pub use documents::configure_document_routes;
pub use downloads::configure_download_routes;
#[cfg(feature = "enterprise")]
pub use enterprise_store::SqliteEnterpriseStore;
pub use graphql::{configure_graphql_routes, create_schema, IronBridgeSchema};
pub use inbox::{configure_inbox_routes, init_inbox_tables, InboxEmitter};
pub use notes::{configure_notes_routes, init_notes_tables};
#[cfg(feature = "enterprise")]
pub use oidc::{configure_oidc_routes, OidcProviderConfig, OidcService};
pub use recording::{configure_recording_routes, create_recording_state};
pub use research::configure_research_routes;
#[cfg(feature = "enterprise")]
pub use retention::{configure_retention_routes, RetentionPolicy, RetentionService};
#[cfg(feature = "enterprise")]
pub use sso::{configure_sso_routes, SamlIdpConfig, SsoService};
pub use state::AppState;
pub use sync::{configure_sync_routes, create_sync_state};
pub use training::configure_training_routes;
pub use webhooks::{configure_webhook_routes, WebhookState};
pub use websocket::{configure_websocket_routes, WebSocketState};
use actix_cors::Cors;
use actix_web::{middleware, web, App, HttpServer};
use anyhow::Result;
use std::path::PathBuf;
use crate::database::ChatDatabase;
#[derive(Debug, Clone)]
pub struct ServerConfig {
pub host: String,
pub port: u16,
pub database_path: String,
pub cors_origins: Vec<String>,
pub public_base_url: Option<String>,
}
impl ServerConfig {
fn resolved_base_url(&self) -> String {
if let Some(url) = &self.public_base_url {
return url.trim_end_matches('/').to_string();
}
let host = match self.host.as_str() {
"0.0.0.0" | "::" | "[::]" | "" => "127.0.0.1",
other => other,
};
format!("http://{}:{}", host, self.port)
}
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
host: "127.0.0.1".to_string(), port: 8787,
database_path: dirs::data_local_dir()
.map(|p| {
p.join("ironbridge")
.join("ironbridge.db")
.to_string_lossy()
.to_string()
})
.unwrap_or_else(|| "ironbridge.db".to_string()),
cors_origins: vec![
"http://localhost:5173".to_string(),
"http://localhost:3000".to_string(),
"http://127.0.0.1:5173".to_string(),
"http://127.0.0.1:3000".to_string(),
"http://localhost:8081".to_string(), "http://127.0.0.1:8081".to_string(), "http://localhost:19006".to_string(), "http://127.0.0.1:19006".to_string(), ],
public_base_url: std::env::var("IRONBRIDGE_PUBLIC_BASE_URL")
.ok()
.filter(|s| !s.trim().is_empty()),
}
}
}
fn configure_routes(cfg: &mut web::ServiceConfig) {
use handlers_simple::*;
eprintln!("[DEBUG] Configuring routes...");
cfg.service(handlers_write::attach_write_routes(
web::scope("/api")
.route("/health", web::get().to(health_check))
.route("/workspaces", web::get().to(list_workspaces))
.route("/workspaces/{id}", web::get().to(get_workspace))
.route("/sessions", web::get().to(list_sessions))
.route("/sessions/search", web::get().to(search_sessions))
.route("/sessions/{id}", web::get().to(get_session))
.route("/providers", web::get().to(list_providers))
.route("/providers/{id}", web::put().to(update_provider))
.route("/stats", web::get().to(get_stats))
.route("/stats/overview", web::get().to(get_stats))
.route("/agents", web::get().to(list_agents))
.route("/agents", web::post().to(create_agent))
.route("/agents/{id}", web::get().to(get_agent))
.route("/agents/{id}", web::put().to(update_agent))
.route("/agents/{id}", web::delete().to(delete_agent))
.route("/swarms", web::get().to(list_swarms))
.route("/swarms", web::post().to(create_swarm))
.route("/swarms/{id}", web::get().to(get_swarm))
.route("/swarms/{id}", web::delete().to(delete_swarm))
.route("/swarms/{id}/agents", web::post().to(add_swarm_agent))
.route(
"/swarms/{id}/agents/{agent_id}",
web::delete().to(remove_swarm_agent),
)
.route("/settings", web::get().to(get_settings))
.route("/settings", web::put().to(update_settings))
.route("/settings/accounts", web::get().to(list_accounts))
.route("/settings/accounts", web::post().to(create_account))
.route("/settings/accounts/{id}", web::delete().to(delete_account))
.route("/system/info", web::get().to(get_system_info))
.route("/system/health", web::get().to(get_system_health))
.route(
"/system/providers/health",
web::get().to(get_provider_health),
)
.route("/mcp/tools", web::get().to(list_mcp_tools))
.route("/mcp/call", web::post().to(call_mcp_tool))
.route("/mcp/batch", web::post().to(call_mcp_tools_batch))
.route(
"/mcp/system-prompt",
web::get().to(get_ironbridge_system_prompt),
)
.route("/swe/projects", web::get().to(handlers_swe::list_projects))
.route(
"/swe/projects",
web::post().to(handlers_swe::create_project),
)
.route(
"/swe/projects/{id}",
web::get().to(handlers_swe::get_project),
)
.route(
"/swe/projects/{id}",
web::delete().to(handlers_swe::delete_project),
)
.route(
"/swe/projects/{id}/open",
web::post().to(handlers_swe::open_project),
)
.route(
"/swe/projects/{id}/context",
web::get().to(handlers_swe::get_context),
)
.route(
"/swe/projects/{id}/execute",
web::post().to(handlers_swe::execute_tool),
)
.route(
"/swe/projects/{project_id}/memory",
web::get().to(handlers_swe::list_memory),
)
.route(
"/swe/projects/{project_id}/memory",
web::post().to(handlers_swe::create_memory),
)
.route(
"/swe/projects/{project_id}/memory/{id}",
web::get().to(handlers_swe::get_memory),
)
.route(
"/swe/projects/{project_id}/memory/{id}",
web::put().to(handlers_swe::update_memory),
)
.route(
"/swe/projects/{project_id}/memory/{id}",
web::delete().to(handlers_swe::delete_memory),
)
.route(
"/swe/projects/{project_id}/rules",
web::get().to(handlers_swe::list_rules),
)
.route(
"/swe/projects/{project_id}/rules",
web::post().to(handlers_swe::create_rule),
)
.route(
"/swe/projects/{project_id}/rules/{id}",
web::put().to(handlers_swe::update_rule),
)
.route(
"/swe/projects/{project_id}/rules/{id}",
web::delete().to(handlers_swe::delete_rule),
),
));
eprintln!("[DEBUG] Added /api routes");
}
#[cfg(feature = "enterprise")]
#[derive(Clone)]
struct EnterpriseServices {
audit: web::Data<AuditService>,
retention: web::Data<RetentionService>,
sso: web::Data<SsoService>,
oidc: web::Data<OidcService>,
}
#[cfg(feature = "enterprise")]
impl EnterpriseServices {
fn open(db_path: &std::path::Path, base_url: &str) -> Result<Self> {
let store = SqliteEnterpriseStore::open(db_path)
.map_err(|e| anyhow::anyhow!("failed to open the enterprise store: {}", e))?;
let store: audit::Database = std::sync::Arc::new(store);
let audit = web::Data::new(AuditService::new(store.clone()));
let retention =
web::Data::new(RetentionService::new(store.clone()).with_audit(audit.clone()));
let sso = web::Data::new(SsoService::new(store.clone(), base_url));
let oidc = web::Data::new(OidcService::new(store));
Ok(Self {
audit,
retention,
sso,
oidc,
})
}
fn configure(&self, cfg: &mut web::ServiceConfig) {
cfg.app_data(self.audit.clone());
cfg.app_data(self.retention.clone());
cfg.app_data(self.sso.clone());
cfg.app_data(self.oidc.clone());
configure_audit_routes(cfg);
configure_retention_routes(cfg);
configure_sso_routes(cfg);
configure_oidc_routes(cfg);
}
}
pub async fn start_server(config: ServerConfig) -> Result<()> {
let db_path = PathBuf::from(&config.database_path);
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent)?;
}
if let Err(e) = crate::commands::create_harvest_database(&db_path) {
eprintln!("[WARN] Failed to ensure harvest schema: {}", e);
}
let db = ChatDatabase::open(&db_path)?;
{
let conn = rusqlite::Connection::open(&db_path)?;
if let Err(e) = handlers_swe::init_swe_tables(&conn) {
eprintln!("[WARN] Failed to initialize SWE tables: {}", e);
}
}
{
let conn = rusqlite::Connection::open(&db_path)?;
if let Err(e) = auth::init_auth_tables(&conn) {
eprintln!("[WARN] Failed to initialize Auth tables: {}", e);
}
if let Err(e) = inbox::init_inbox_tables(&conn) {
eprintln!("[WARN] Failed to initialize Inbox tables: {}", e);
}
}
#[cfg(feature = "enterprise")]
let enterprise = EnterpriseServices::open(&db_path, &config.resolved_base_url())?;
let state = web::Data::new(AppState::new(db, db_path));
let sync_state = web::Data::new(create_sync_state());
let ws_state = web::Data::new(WebSocketState::new());
let recording_state = web::Data::new(create_recording_state());
let webhook_state = web::Data::new(std::sync::Arc::new(WebhookState::new()));
let graphql_schema = graphql::create_schema(state.clone().into_inner());
let cors_origins = config.cors_origins.clone();
println!("[*] IRONBRIDGE API Server starting...");
println!(" Address: http://{}:{}", config.host, config.port);
println!(" Database: {}", config.database_path);
println!();
println!("[*] Mobile app endpoints:");
println!(" GET /api/workspaces - List workspaces");
println!(" GET /api/sessions - List sessions");
println!(" GET /api/sessions/:id - Get session details");
println!(" GET /api/stats - Database statistics");
println!();
println!("[*] SWE Mode endpoints:");
println!(" GET /api/swe/projects - List SWE projects");
println!(" POST /api/swe/projects - Create SWE project");
println!();
println!("[*] Recording endpoints:");
println!(" POST /recording/events - Send recording events");
println!(" POST /recording/snapshot - Store session snapshot");
println!(" GET /recording/sessions - List active sessions");
println!(" GET /recording/status - Recording status");
println!(" GET /recording/ws - WebSocket for real-time recording");
println!();
println!("[*] Sync endpoints:");
println!(" GET /sync/version - Get current sync version");
println!(" GET /sync/delta?from=N - Get changes since version N");
println!(" POST /sync/event - Push a sync event");
println!(" GET /sync/snapshot - Get full data snapshot");
println!(" GET /sync/subscribe - SSE stream for real-time updates");
println!(" GET /ws - WebSocket for bidirectional updates");
println!();
println!("Press Ctrl+C to stop the server...");
println!();
eprintln!("[DEBUG] Creating HttpServer...");
let server = HttpServer::new(move || {
let origins = cors_origins.clone();
let allow_wildcard_localhost = std::env::var("IRONBRIDGE_CORS_ALLOW_LOCALHOST")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false);
let cors = Cors::default()
.allowed_origin_fn(move |origin, _req_head| {
let origin_str = origin.to_str().unwrap_or("");
origins.iter().any(|allowed| allowed == origin_str)
|| (allow_wildcard_localhost
&& (origin_str.starts_with("http://localhost:")
|| origin_str.starts_with("http://127.0.0.1:")
|| origin_str.starts_with("exp://")))
})
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
.allowed_headers(vec!["Content-Type", "Authorization", "Accept"])
.supports_credentials()
.max_age(3600);
App::new()
.app_data(state.clone())
.app_data(sync_state.clone())
.app_data(ws_state.clone())
.app_data(recording_state.clone())
.wrap(actix_web::middleware::from_fn(auth::require_auth))
.wrap(cors)
.wrap(middleware::Logger::default())
.configure(configure_inbox_routes)
.configure(configure_document_routes)
.configure(configure_dataset_routes)
.configure(configure_catalog_routes)
.configure(configure_download_routes)
.configure(configure_training_routes)
.configure(configure_research_routes)
.configure(configure_notes_routes)
.configure(configure_routes)
.configure(configure_sync_routes)
.configure(configure_auth_routes)
.configure(configure_recording_routes)
.configure(configure_docs_routes)
.configure(|cfg| configure_websocket_routes(cfg, ws_state.clone()))
.configure(|cfg| configure_webhook_routes(cfg, webhook_state.clone()))
.configure(|cfg| configure_graphql_routes(cfg, graphql_schema.clone()))
.configure({
#[cfg(feature = "enterprise")]
let enterprise = enterprise.clone();
move |cfg: &mut web::ServiceConfig| {
#[cfg(feature = "enterprise")]
enterprise.configure(cfg);
#[cfg(not(feature = "enterprise"))]
let _ = cfg;
}
})
});
eprintln!("[DEBUG] Binding to {}:{}...", config.host, config.port);
let server = server.bind((config.host.as_str(), config.port))?;
eprintln!("[DEBUG] Starting server...");
server.run().await?;
eprintln!("[DEBUG] Server stopped.");
Ok(())
}
#[cfg(test)]
mod base_url_tests {
use super::ServerConfig;
fn config(host: &str, public: Option<&str>) -> ServerConfig {
ServerConfig {
host: host.to_string(),
port: 8787,
public_base_url: public.map(str::to_string),
..Default::default()
}
}
#[test]
fn a_wildcard_bind_never_reaches_the_advertised_url() {
for wildcard in ["0.0.0.0", "::", "[::]", ""] {
let url = config(wildcard, None).resolved_base_url();
assert_eq!(
url, "http://127.0.0.1:8787",
"wildcard bind {wildcard:?} leaked into {url}"
);
}
}
#[test]
fn a_real_bind_host_is_kept() {
assert_eq!(
config("192.168.1.10", None).resolved_base_url(),
"http://192.168.1.10:8787"
);
}
#[test]
fn an_explicit_public_url_overrides_the_bind_address() {
assert_eq!(
config("0.0.0.0", Some("https://ironbridge.example.com")).resolved_base_url(),
"https://ironbridge.example.com"
);
}
#[test]
fn a_trailing_slash_is_trimmed() {
assert_eq!(
config("0.0.0.0", Some("https://ironbridge.example.com/")).resolved_base_url(),
"https://ironbridge.example.com"
);
}
}