tuitbot-server 0.1.49

HTTP API server for Tuitbot autonomous X growth assistant
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Account management endpoints.
//!
//! CRUD for the account registry, role management, and per-account
//! configuration overrides.

use std::sync::Arc;

use axum::extract::{Path, State};
use axum::Json;
use serde::Deserialize;
use serde_json::{json, Value};
use tuitbot_core::config::{effective_config, validate_override_keys, Config};
use tuitbot_core::storage::accounts::{
    self, account_scraper_session_path, account_token_path, UpdateAccountParams, DEFAULT_ACCOUNT_ID,
};
use tuitbot_core::x_api::{XApiClient, XApiHttpClient};

use crate::account::{require_mutate, AccountContext, Role};
use crate::error::ApiError;
use crate::state::AppState;

/// `GET /api/accounts` — list all active accounts (admin only).
pub async fn list_accounts(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;
    let accs = accounts::list_accounts(&state.db).await?;
    Ok(Json(json!(accs)))
}

/// `GET /api/accounts/{id}` — get account details.
pub async fn get_account(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<String>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;
    let account = accounts::get_account(&state.db, &id)
        .await?
        .ok_or_else(|| ApiError::NotFound(format!("account not found: {id}")))?;
    Ok(Json(json!(account)))
}

#[derive(Deserialize)]
pub struct CreateAccountRequest {
    pub label: String,
}

/// `POST /api/accounts` — create a new account (admin only).
///
/// Sets `token_path` to `accounts/{id}/tokens.json` so each account
/// has an isolated credential file.
pub async fn create_account(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Json(body): Json<CreateAccountRequest>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;
    let id = uuid::Uuid::new_v4().to_string();
    accounts::create_account(&state.db, &id, &body.label).await?;

    // Set token_path for credential isolation.
    let token_path = format!("accounts/{}/tokens.json", id);
    accounts::update_account(
        &state.db,
        &id,
        UpdateAccountParams {
            token_path: Some(&token_path),
            ..Default::default()
        },
    )
    .await?;

    // Migrate credentials from the default account when this is the first
    // non-default account.  This handles the common onboarding path where the
    // user configures a browser session on the default account and then creates
    // a named account — without this, the session would be orphaned.
    migrate_default_credentials(&state, &id).await;

    let account = accounts::get_account(&state.db, &id)
        .await?
        .ok_or_else(|| ApiError::Internal("account creation failed".to_string()))?;

    Ok(Json(json!(account)))
}

#[derive(Deserialize)]
pub struct UpdateAccountRequest {
    pub label: Option<String>,
    pub config_overrides: Option<String>,
}

/// `PATCH /api/accounts/{id}` — update account config/label (admin only).
///
/// When `config_overrides` is provided, validates that:
/// 1. The JSON only contains account-scoped keys.
/// 2. Merging with the base config produces a valid effective config.
pub async fn update_account(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<String>,
    Json(body): Json<UpdateAccountRequest>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;

    // Verify account exists.
    accounts::get_account(&state.db, &id)
        .await?
        .ok_or_else(|| ApiError::NotFound(format!("account not found: {id}")))?;

    // Validate config_overrides if provided.
    if let Some(ref overrides_str) = body.config_overrides {
        let trimmed = overrides_str.trim();
        if !trimmed.is_empty() && trimmed != "{}" {
            let overrides: serde_json::Value = serde_json::from_str(trimmed)
                .map_err(|e| ApiError::BadRequest(format!("invalid config_overrides JSON: {e}")))?;

            validate_override_keys(&overrides).map_err(|e| ApiError::BadRequest(e.to_string()))?;

            // Validate the effective config by merging with base.
            let base_config = load_base_config(&state.config_path)?;
            effective_config(&base_config, trimmed)
                .map_err(|e| ApiError::BadRequest(format!("invalid effective config: {e}")))?;
        }
    }

    accounts::update_account(
        &state.db,
        &id,
        UpdateAccountParams {
            label: body.label.as_deref(),
            config_overrides: body.config_overrides.as_deref(),
            ..Default::default()
        },
    )
    .await?;

    let updated = accounts::get_account(&state.db, &id)
        .await?
        .ok_or_else(|| ApiError::Internal("account disappeared".to_string()))?;

    Ok(Json(json!(updated)))
}

/// Migrate credential files from the default account to a newly created account.
///
/// Only runs when the default account has credential files (scraper session
/// and/or OAuth tokens) and there are no other non-default active accounts —
/// i.e. this is the user's first named account.  Files are *moved* so the
/// default account no longer shows stale "Linked" status.
async fn migrate_default_credentials(state: &AppState, new_account_id: &str) {
    // Only migrate when this is the first non-default account.
    let active = match accounts::list_accounts(&state.db).await {
        Ok(list) => list,
        Err(_) => return,
    };
    let non_default_count = active.iter().filter(|a| a.id != DEFAULT_ACCOUNT_ID).count();
    if non_default_count != 1 {
        return;
    }

    let default_session = account_scraper_session_path(&state.data_dir, DEFAULT_ACCOUNT_ID);
    let default_tokens = account_token_path(&state.data_dir, DEFAULT_ACCOUNT_ID);

    let has_session = default_session.exists();
    let has_tokens = default_tokens.exists();

    if !has_session && !has_tokens {
        return;
    }

    let new_dir = state.data_dir.join("accounts").join(new_account_id);
    if let Err(e) = std::fs::create_dir_all(&new_dir) {
        tracing::warn!("failed to create account dir for migration: {e}");
        return;
    }

    if has_session {
        let dest = account_scraper_session_path(&state.data_dir, new_account_id);
        if let Err(e) = std::fs::rename(&default_session, &dest) {
            tracing::warn!("failed to migrate scraper session: {e}");
        } else {
            tracing::info!(
                account_id = %new_account_id,
                "migrated scraper session from default account"
            );
        }
    }

    if has_tokens {
        let dest = account_token_path(&state.data_dir, new_account_id);
        if let Err(e) = std::fs::rename(&default_tokens, &dest) {
            tracing::warn!("failed to migrate OAuth tokens: {e}");
        } else {
            tracing::info!(
                account_id = %new_account_id,
                "migrated OAuth tokens from default account"
            );
        }
    }
}

/// Load and parse the base config from the TOML file.
fn load_base_config(config_path: &std::path::Path) -> Result<Config, ApiError> {
    let contents = std::fs::read_to_string(config_path).map_err(|e| {
        ApiError::BadRequest(format!(
            "could not read config file {}: {e}",
            config_path.display()
        ))
    })?;

    toml::from_str(&contents)
        .map_err(|e| ApiError::BadRequest(format!("failed to parse config: {e}")))
}

/// `DELETE /api/accounts/{id}` — archive an account (admin only).
pub async fn delete_account(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<String>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;
    accounts::delete_account(&state.db, &id)
        .await
        .map_err(|_| ApiError::BadRequest("cannot delete this account".to_string()))?;
    Ok(Json(json!({"status": "archived"})))
}

// ---- Role management ----

/// `GET /api/accounts/{id}/roles` — list roles for an account.
pub async fn list_roles(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<String>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;
    let roles = accounts::list_roles(&state.db, &id).await?;
    Ok(Json(json!(roles)))
}

#[derive(Deserialize)]
pub struct SetRoleRequest {
    pub actor: String,
    pub role: String,
}

/// `POST /api/accounts/{id}/roles` — set a role for an actor on an account.
pub async fn set_role(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<String>,
    Json(body): Json<SetRoleRequest>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;

    // Validate role string.
    let _role: Role = body
        .role
        .parse()
        .map_err(|e: String| ApiError::BadRequest(e))?;

    accounts::set_role(&state.db, &id, &body.actor, &body.role).await?;
    Ok(Json(json!({"status": "ok"})))
}

#[derive(Deserialize)]
pub struct RemoveRoleRequest {
    pub actor: String,
}

/// `DELETE /api/accounts/{id}/roles` — remove a role assignment.
pub async fn remove_role(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<String>,
    Json(body): Json<RemoveRoleRequest>,
) -> Result<Json<Value>, ApiError> {
    require_mutate(&ctx)?;
    accounts::remove_role(&state.db, &id, &body.actor).await?;
    Ok(Json(json!({"status": "ok"})))
}

// ---- Profile sync ----

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn create_account_request_deser() {
        let json = r#"{"label": "My Account"}"#;
        let req: CreateAccountRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.label, "My Account");
    }

    #[test]
    fn update_account_request_deser() {
        let json = r#"{"label": "New Label", "config_overrides": "{}"}"#;
        let req: UpdateAccountRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.label.as_deref(), Some("New Label"));
        assert_eq!(req.config_overrides.as_deref(), Some("{}"));
    }

    #[test]
    fn update_account_request_optional_fields() {
        let json = r#"{}"#;
        let req: UpdateAccountRequest = serde_json::from_str(json).unwrap();
        assert!(req.label.is_none());
        assert!(req.config_overrides.is_none());
    }

    #[test]
    fn set_role_request_deser() {
        let json = r#"{"actor": "user@example.com", "role": "admin"}"#;
        let req: SetRoleRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.actor, "user@example.com");
        assert_eq!(req.role, "admin");
    }

    #[test]
    fn remove_role_request_deser() {
        let json = r#"{"actor": "user@example.com"}"#;
        let req: RemoveRoleRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.actor, "user@example.com");
    }

    #[test]
    fn load_base_config_nonexistent() {
        let result = load_base_config(std::path::Path::new("/nonexistent/config.toml"));
        assert!(result.is_err());
    }

    #[test]
    fn load_base_config_valid() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config_path = dir.path().join("config.toml");
        // Write minimal valid config
        std::fs::write(&config_path, "").expect("write");
        let result = load_base_config(&config_path);
        // Parsing empty file may succeed with defaults or fail — either is valid
        let _ = result;
    }

    #[test]
    fn create_account_request_debug() {
        let _req = CreateAccountRequest {
            label: "Test".to_string(),
        };
        // This should not panic (exercises Deserialize derive)
        let json = serde_json::to_string(&serde_json::json!({"label": "Test"})).unwrap();
        let _: CreateAccountRequest = serde_json::from_str(&json).unwrap();
    }

    #[test]
    fn set_role_request_roundtrip() {
        let json = r#"{"actor": "bot", "role": "viewer"}"#;
        let req: SetRoleRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.actor, "bot");
        assert_eq!(req.role, "viewer");
    }
}

/// `POST /api/accounts/{id}/sync-profile` — fetch X profile and update account.
///
/// Tries OAuth tokens first (`/users/me`). If unavailable, falls back to
/// the cookie transport (scraper session) so local no-key mode users can
/// still sync their profile picture, username, and display name.
pub async fn sync_profile(
    State(state): State<Arc<AppState>>,
    ctx: AccountContext,
    Path(id): Path<String>,
) -> Result<Json<Value>, ApiError> {
    tracing::info!(account_id = %id, "sync_profile called");
    require_mutate(&ctx)?;

    let _account = accounts::get_account(&state.db, &id)
        .await?
        .ok_or_else(|| ApiError::NotFound(format!("account not found: {id}")))?;

    // Try OAuth first, fall back to cookie transport.
    let token_path = account_token_path(&state.data_dir, &id);
    let user = match state.get_x_access_token(&token_path, &id).await {
        Ok(access_token) => {
            tracing::info!(account_id = %id, "sync_profile: using OAuth tokens");
            let client = XApiHttpClient::new(access_token);
            client
                .get_me()
                .await
                .map_err(|e| ApiError::Internal(format!("X API error: {e}")))?
        }
        Err(_) => {
            // No OAuth tokens — try the cookie transport.
            tracing::info!(account_id = %id, "sync_profile: no OAuth, falling back to cookie transport");
            let account_dir = accounts::account_data_dir(&state.data_dir, &id);
            // Pass the shared health handle so the sync outcome is reflected in /health.
            let client = if let Some(ref health) = state.scraper_health {
                tuitbot_core::x_api::LocalModeXClient::with_session_and_health(
                    false,
                    &account_dir,
                    health.clone(),
                )
                .await
            } else {
                tuitbot_core::x_api::LocalModeXClient::with_session(false, &account_dir).await
            };
            client
                .get_me()
                .await
                .map_err(|e| {
                    tracing::error!(account_id = %id, error = %e, "sync_profile: cookie transport failed");
                    ApiError::Internal(format!("profile sync failed: {e}"))
                })?
        }
    };

    accounts::update_account(
        &state.db,
        &id,
        UpdateAccountParams {
            x_user_id: Some(&user.id),
            x_username: Some(&user.username),
            x_display_name: Some(&user.name),
            x_avatar_url: user.profile_image_url.as_deref(),
            ..Default::default()
        },
    )
    .await?;

    let updated = accounts::get_account(&state.db, &id)
        .await?
        .ok_or_else(|| ApiError::Internal("account disappeared".to_string()))?;

    Ok(Json(json!(updated)))
}