refactor: purge Node.js, Rust is the one true backend

- Moved boosapi-rs/* to repo root
- Deleted all Node.js source (src/server/, src/web/, scripts/)
- Deleted node_modules, package.json, tsconfig, vite.config
- Updated .gitignore and AGENTS.md for Rust-only stack
- Fixed static file path for frontend dist/web/
- Dockerfile stays the same (already Rust-only)
- Kept dist/web/ for Rust static serving
This commit is contained in:
boos
2026-05-18 09:11:29 +08:00
parent 725f44699a
commit 5d29f03d50
1165 changed files with 271 additions and 323571 deletions
+207
View File
@@ -0,0 +1,207 @@
use crate::error::{AppError, AppResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::{FromRow, SqlitePool};
use std::sync::Arc;
#[derive(Clone)]
pub struct OAuthService {
db: Arc<SqlitePool>,
client: reqwest::Client,
}
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct OAuthRouteUnit {
pub id: i64,
pub site_id: i64,
pub provider: String,
pub name: String,
pub strategy: String,
pub enabled: Option<bool>,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefreshedToken {
pub account_id: i64,
pub access_token: String,
pub expires_at: Option<String>,
}
impl OAuthService {
pub fn new(db: Arc<SqlitePool>) -> Self {
Self {
db,
client: reqwest::Client::new(),
}
}
pub async fn refresh_token(&self, account_id: i64, site_id: i64) -> AppResult<RefreshedToken> {
let row: Option<(String, Option<String>, Option<String>)> = sqlx::query_as(
"SELECT access_token, api_token, extra_config
FROM accounts
WHERE id = ? AND site_id = ? AND oauth_provider IS NOT NULL",
)
.bind(account_id)
.bind(site_id)
.fetch_optional(&*self.db)
.await?;
let (current_access_token, refresh_token, extra_config) =
row.ok_or_else(|| AppError::NotFound("OAuth account not found".into()))?;
if !self.token_expired(extra_config.as_deref()) {
return Ok(RefreshedToken {
account_id,
access_token: current_access_token,
expires_at: token_expiry(extra_config.as_deref()),
});
}
let refresh_token = refresh_token
.filter(|token| !token.trim().is_empty())
.ok_or_else(|| AppError::BadRequest("OAuth account has no refresh token".into()))?;
let mut refreshed = self.perform_refresh(site_id, &refresh_token).await?;
refreshed.account_id = account_id;
sqlx::query(
"UPDATE accounts
SET access_token = ?, extra_config = ?, updated_at = datetime('now')
WHERE id = ? AND site_id = ?",
)
.bind(&refreshed.access_token)
.bind(
serde_json::to_string(&serde_json::json!({
"expires_at": refreshed.expires_at,
"refreshed_at": chrono::Utc::now().to_rfc3339(),
}))
.map_err(|err| AppError::Internal(err.into()))?,
)
.bind(account_id)
.bind(site_id)
.execute(&*self.db)
.await?;
Ok(refreshed)
}
pub fn token_expired(&self, extra_config: Option<&str>) -> bool {
token_expired(extra_config)
}
pub async fn list_route_units(&self, site_id: Option<i64>) -> AppResult<Vec<OAuthRouteUnit>> {
if let Some(site_id) = site_id {
sqlx::query_as("SELECT * FROM oauth_route_units WHERE site_id = ? ORDER BY id")
.bind(site_id)
.fetch_all(&*self.db)
.await
.map_err(Into::into)
} else {
sqlx::query_as("SELECT * FROM oauth_route_units ORDER BY id")
.fetch_all(&*self.db)
.await
.map_err(Into::into)
}
}
pub async fn create_route_unit(
&self,
site_id: i64,
provider: &str,
name: &str,
strategy: Option<&str>,
) -> AppResult<OAuthRouteUnit> {
let result = sqlx::query(
"INSERT INTO oauth_route_units (site_id, provider, name, strategy)
VALUES (?, ?, ?, ?)",
)
.bind(site_id)
.bind(provider)
.bind(name)
.bind(strategy.unwrap_or("round_robin"))
.execute(&*self.db)
.await?;
sqlx::query_as("SELECT * FROM oauth_route_units WHERE id = ?")
.bind(result.last_insert_rowid())
.fetch_one(&*self.db)
.await
.map_err(Into::into)
}
async fn perform_refresh(
&self,
site_id: i64,
refresh_token: &str,
) -> AppResult<RefreshedToken> {
let token_endpoint: Option<String> = sqlx::query_scalar(
"SELECT json_extract(custom_headers, '$.oauth_token_url') FROM sites WHERE id = ?",
)
.bind(site_id)
.fetch_optional(&*self.db)
.await?;
let Some(token_endpoint) = token_endpoint.filter(|url| !url.trim().is_empty()) else {
return Err(AppError::BadRequest(
"OAuth token endpoint is not configured for this site".into(),
));
};
let response: Value = self
.client
.post(token_endpoint)
.form(&[
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
])
.send()
.await
.map_err(|err| AppError::UpstreamError(format!("OAuth refresh failed: {err}")))?
.json()
.await
.map_err(|err| AppError::UpstreamError(format!("Invalid OAuth response: {err}")))?;
let access_token = response
.get("access_token")
.and_then(Value::as_str)
.ok_or_else(|| AppError::UpstreamError("OAuth response missing access_token".into()))?
.to_string();
let expires_at = response
.get("expires_at")
.and_then(Value::as_str)
.map(str::to_string);
Ok(RefreshedToken {
account_id: 0,
access_token,
expires_at,
})
}
}
fn token_expired(extra_config: Option<&str>) -> bool {
let Some(extra_config) = extra_config else {
return true;
};
let Ok(value) = serde_json::from_str::<Value>(extra_config) else {
return true;
};
let Some(expires_at) = value.get("expires_at").and_then(Value::as_str) else {
return true;
};
chrono::DateTime::parse_from_rfc3339(expires_at)
.map(|expires_at| expires_at <= chrono::Utc::now() + chrono::Duration::minutes(5))
.unwrap_or(true)
}
fn token_expiry(extra_config: Option<&str>) -> Option<String> {
extra_config
.and_then(|config| serde_json::from_str::<Value>(config).ok())
.and_then(|value| {
value
.get("expires_at")
.and_then(Value::as_str)
.map(str::to_string)
})
}