mockforge-registry-server 0.3.131

Plugin registry server for MockForge
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Authentication handlers

use axum::{extract::State, Json};
use chrono::{Duration, Utc};
use serde::{Deserialize, Serialize};

use crate::{
    auth::{
        create_token_pair, hash_password, verify_password, verify_refresh_token,
        REFRESH_TOKEN_EXPIRY_DAYS,
    },
    error::{ApiError, ApiResult},
    middleware::AuthUser,
    models::organization::Plan,
    AppState,
};

#[derive(Debug, Deserialize)]
pub struct RegisterRequest {
    pub username: String,
    pub email: String,
    pub password: String,
}

#[derive(Debug, Deserialize)]
pub struct LoginRequest {
    pub email: String,
    pub password: String,
    pub two_factor_code: Option<String>, // Optional 2FA code (required if 2FA is enabled)
}

/// Legacy auth response (for backwards compatibility)
#[derive(Debug, Serialize)]
pub struct AuthResponse {
    pub token: String,
    pub user_id: String,
    pub username: String,
}

/// New auth response with both access and refresh tokens
#[derive(Debug, Serialize)]
pub struct AuthResponseV2 {
    pub access_token: String,
    pub refresh_token: String,
    pub access_token_expires_at: i64,
    pub refresh_token_expires_at: i64,
    pub user_id: String,
    pub username: String,
}

pub async fn register(
    State(state): State<AppState>,
    Json(request): Json<RegisterRequest>,
) -> ApiResult<Json<AuthResponseV2>> {
    // Validate input
    if request.username.len() < 3 {
        return Err(ApiError::InvalidRequest("Username must be at least 3 characters".to_string()));
    }

    if request.password.len() < 8 {
        return Err(ApiError::InvalidRequest("Password must be at least 8 characters".to_string()));
    }

    // Check if user already exists
    if state.store.find_user_by_email(&request.email).await?.is_some() {
        return Err(ApiError::InvalidRequest("Email already registered".to_string()));
    }

    if state.store.find_user_by_username(&request.username).await?.is_some() {
        return Err(ApiError::InvalidRequest("Username already taken".to_string()));
    }

    // Hash password
    let password_hash = hash_password(&request.password).map_err(ApiError::Internal)?;

    // Create user
    let user = state
        .store
        .create_user(&request.username, &request.email, &password_hash)
        .await?;

    // Auto-create a personal organization for the user
    let org_slug = format!("{}-personal", request.username.to_lowercase().replace(' ', "-"));
    if let Err(e) = state
        .store
        .create_organization(&format!("{}'s Org", request.username), &org_slug, user.id, Plan::Free)
        .await
    {
        tracing::warn!("Failed to create personal org for user {}: {}", user.id, e);
    }

    // Generate token pair (access + refresh)
    let (token_pair, jti) = create_token_pair(&user.id.to_string(), &state.config.jwt_secret)
        .map_err(ApiError::Internal)?;

    // Store refresh token JTI in database for revocation support
    let expires_at = Utc::now()
        .checked_add_signed(Duration::days(REFRESH_TOKEN_EXPIRY_DAYS))
        .ok_or_else(|| ApiError::Internal(anyhow::anyhow!("Failed to calculate token expiry")))?;

    state.db.store_refresh_token_jti(&jti, user.id, expires_at).await.map_err(|e| {
        tracing::warn!("Failed to store refresh token JTI: {}", e);
        ApiError::Internal(e)
    })?;

    Ok(Json(AuthResponseV2 {
        access_token: token_pair.access_token,
        refresh_token: token_pair.refresh_token,
        access_token_expires_at: token_pair.access_token_expires_at,
        refresh_token_expires_at: token_pair.refresh_token_expires_at,
        user_id: user.id.to_string(),
        username: user.username,
    }))
}

pub async fn login(
    State(state): State<AppState>,
    Json(request): Json<LoginRequest>,
) -> ApiResult<Json<AuthResponseV2>> {
    // Find user
    let user = state
        .store
        .find_user_by_email(&request.email)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("Invalid email or password".to_string()))?;

    // Verify password
    let valid =
        verify_password(&request.password, &user.password_hash).map_err(ApiError::Internal)?;

    if !valid {
        return Err(ApiError::InvalidRequest("Invalid email or password".to_string()));
    }

    // Check if 2FA is enabled
    if user.two_factor_enabled {
        // Require 2FA code
        let code = request
            .two_factor_code
            .ok_or_else(|| ApiError::InvalidRequest("2FA code is required".to_string()))?;

        // Get secret
        let secret = user.two_factor_secret.ok_or_else(|| {
            ApiError::Internal(anyhow::anyhow!("2FA enabled but no secret found"))
        })?;

        // Verify TOTP code
        use crate::two_factor::verify_totp_code;
        let totp_valid = verify_totp_code(&secret, &code, Some(1))
            .map_err(|e| ApiError::Internal(anyhow::anyhow!("TOTP verification error: {}", e)))?;

        if !totp_valid {
            // Try backup codes
            let mut backup_valid = false;
            if let Some(backup_codes) = &user.two_factor_backup_codes {
                use crate::two_factor::verify_backup_code;
                for (index, hashed_code) in backup_codes.iter().enumerate() {
                    if verify_backup_code(&code, hashed_code).map_err(|e| {
                        ApiError::Internal(anyhow::anyhow!("Backup code verification error: {}", e))
                    })? {
                        // Remove used backup code
                        state.store.remove_user_backup_code(user.id, index).await?;
                        backup_valid = true;
                        break;
                    }
                }
            }

            if !backup_valid {
                return Err(ApiError::InvalidRequest("Invalid 2FA code".to_string()));
            }
        }

        // Update 2FA verified timestamp
        state.store.update_user_2fa_verified(user.id).await?;
    }

    // Generate token pair (access + refresh)
    let (token_pair, jti) = create_token_pair(&user.id.to_string(), &state.config.jwt_secret)
        .map_err(ApiError::Internal)?;

    // Store refresh token JTI in database for revocation support
    let expires_at = Utc::now()
        .checked_add_signed(Duration::days(REFRESH_TOKEN_EXPIRY_DAYS))
        .ok_or_else(|| ApiError::Internal(anyhow::anyhow!("Failed to calculate token expiry")))?;

    state.db.store_refresh_token_jti(&jti, user.id, expires_at).await.map_err(|e| {
        tracing::warn!("Failed to store refresh token JTI: {}", e);
        ApiError::Internal(e)
    })?;

    Ok(Json(AuthResponseV2 {
        access_token: token_pair.access_token,
        refresh_token: token_pair.refresh_token,
        access_token_expires_at: token_pair.access_token_expires_at,
        refresh_token_expires_at: token_pair.refresh_token_expires_at,
        user_id: user.id.to_string(),
        username: user.username,
    }))
}

#[derive(Debug, Deserialize)]
pub struct RefreshTokenRequest {
    pub refresh_token: String,
}

/// Response for refresh token endpoint
#[derive(Debug, Serialize)]
pub struct RefreshTokenResponse {
    pub access_token: String,
    pub refresh_token: String,
    pub access_token_expires_at: i64,
    pub refresh_token_expires_at: i64,
}

pub async fn refresh_token(
    State(state): State<AppState>,
    Json(request): Json<RefreshTokenRequest>,
) -> ApiResult<Json<RefreshTokenResponse>> {
    // Verify the refresh token (not just any token)
    let (claims, old_jti) = verify_refresh_token(&request.refresh_token, &state.config.jwt_secret)
        .map_err(|e| {
            tracing::debug!("Refresh token validation failed: {}", e);
            ApiError::InvalidRequest("Invalid or expired refresh token".to_string())
        })?;

    // Check if the JTI has been revoked in the database
    let is_revoked = state.db.is_token_revoked(&old_jti).await.map_err(|e| {
        tracing::warn!("Failed to check token revocation status: {}", e);
        ApiError::Internal(e)
    })?;

    if is_revoked {
        tracing::warn!("Attempt to use revoked refresh token: jti={}", old_jti);
        return Err(ApiError::InvalidRequest("Refresh token has been revoked".to_string()));
    }

    // Parse user ID from claims
    let user_id = uuid::Uuid::parse_str(&claims.sub)
        .map_err(|_| ApiError::InvalidRequest("Invalid user ID".to_string()))?;

    // Find user to ensure they still exist and are active
    let user = state
        .store
        .find_user_by_id(user_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("User not found".to_string()))?;

    // Revoke old refresh token JTI (token rotation for security)
    state.db.revoke_token(&old_jti, "refresh").await.map_err(|e| {
        tracing::warn!("Failed to revoke old refresh token: {}", e);
        ApiError::Internal(e)
    })?;

    // Generate new token pair
    let (token_pair, new_jti) = create_token_pair(&user.id.to_string(), &state.config.jwt_secret)
        .map_err(ApiError::Internal)?;

    // Store new refresh token JTI in database
    let expires_at = Utc::now()
        .checked_add_signed(Duration::days(REFRESH_TOKEN_EXPIRY_DAYS))
        .ok_or_else(|| ApiError::Internal(anyhow::anyhow!("Failed to calculate token expiry")))?;

    state
        .db
        .store_refresh_token_jti(&new_jti, user.id, expires_at)
        .await
        .map_err(|e| {
            tracing::warn!("Failed to store new refresh token JTI: {}", e);
            ApiError::Internal(e)
        })?;

    Ok(Json(RefreshTokenResponse {
        access_token: token_pair.access_token,
        refresh_token: token_pair.refresh_token,
        access_token_expires_at: token_pair.access_token_expires_at,
        refresh_token_expires_at: token_pair.refresh_token_expires_at,
    }))
}

// Password reset handlers (moved here to avoid axum version conflicts)
use crate::email::EmailService;

#[derive(Debug, Deserialize)]
pub struct PasswordResetRequest {
    pub email: String,
}

#[derive(Debug, Serialize)]
pub struct PasswordResetRequestResponse {
    pub success: bool,
    pub message: String,
}

/// Request password reset (sends email with reset token)
pub async fn request_password_reset(
    State(state): State<AppState>,
    Json(request): Json<PasswordResetRequest>,
) -> ApiResult<Json<PasswordResetRequestResponse>> {
    // Find user by email
    let user = match state.store.find_user_by_email(&request.email).await? {
        Some(user) => user,
        None => {
            // Don't reveal if email exists or not (security best practice)
            return Ok(Json(PasswordResetRequestResponse {
                success: true,
                message:
                    "If an account with that email exists, a password reset link has been sent."
                        .to_string(),
            }));
        }
    };

    // Create password reset token (reusing VerificationToken model).
    // Token expires in 1 hour instead of the default 24.
    let reset_token = state.store.create_verification_token(user.id).await?;
    state.store.set_verification_token_expiry_hours(reset_token.id, 1).await?;

    // Send password reset email (non-blocking)
    let email_service = match EmailService::from_env() {
        Ok(service) => service,
        Err(e) => {
            tracing::warn!("Failed to create email service: {}", e);
            return Ok(Json(PasswordResetRequestResponse {
                success: true,
                message:
                    "If an account with that email exists, a password reset link has been sent."
                        .to_string(),
            }));
        }
    };
    let reset_email = EmailService::generate_password_reset_email(
        &user.username,
        &user.email,
        &reset_token.token,
    );

    tokio::spawn(async move {
        if let Err(e) = email_service.send(reset_email).await {
            tracing::warn!("Failed to send password reset email: {}", e);
        }
    });

    tracing::info!("Password reset requested: user_id={}, email={}", user.id, user.email);

    Ok(Json(PasswordResetRequestResponse {
        success: true,
        message: "If an account with that email exists, a password reset link has been sent."
            .to_string(),
    }))
}

#[derive(Debug, Deserialize)]
pub struct PasswordResetConfirmRequest {
    pub token: String,
    pub new_password: String,
}

#[derive(Debug, Serialize)]
pub struct PasswordResetConfirmResponse {
    pub success: bool,
    pub message: String,
}

/// Confirm password reset (with token and new password)
pub async fn confirm_password_reset(
    State(state): State<AppState>,
    Json(request): Json<PasswordResetConfirmRequest>,
) -> ApiResult<Json<PasswordResetConfirmResponse>> {
    // Validate password
    if request.new_password.len() < 8 {
        return Err(ApiError::InvalidRequest("Password must be at least 8 characters".to_string()));
    }

    // Find token
    let reset_token = state
        .store
        .find_verification_token_by_token(&request.token)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("Invalid or expired reset token".to_string()))?;

    // Check if token is valid (not expired and not used)
    if !reset_token.is_valid() {
        return Err(ApiError::InvalidRequest(
            "Reset token has expired or already been used".to_string(),
        ));
    }

    // Get user
    let user = state
        .store
        .find_user_by_id(reset_token.user_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("User not found".to_string()))?;

    // Hash new password
    let password_hash = hash_password(&request.new_password).map_err(ApiError::Internal)?;

    // Update user password
    state.store.update_user_password_hash(user.id, &password_hash).await?;

    // Revoke all existing refresh tokens for security (password changed)
    let revoked_count =
        state.db.revoke_all_user_tokens(user.id, "password_reset").await.map_err(|e| {
            tracing::warn!("Failed to revoke user tokens on password reset: {}", e);
            ApiError::Internal(e)
        })?;

    tracing::info!(
        "Revoked {} refresh tokens for user {} on password reset",
        revoked_count,
        user.id
    );

    // Mark token as used
    state.store.mark_verification_token_used(reset_token.id).await?;

    tracing::info!("Password reset completed: user_id={}, email={}", user.id, user.email);

    Ok(Json(PasswordResetConfirmResponse {
        success: true,
        message: "Password has been reset successfully. You can now log in with your new password."
            .to_string(),
    }))
}

/// Verify token response
#[derive(Debug, Serialize)]
pub struct VerifyTokenResponse {
    pub valid: bool,
    pub user_id: String,
    pub username: String,
    pub email: String,
}

/// Verify that the current JWT is valid (GET /api/v1/auth/verify)
pub async fn verify_token(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
) -> ApiResult<Json<VerifyTokenResponse>> {
    let user = state
        .store
        .find_user_by_id(user_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("User not found".to_string()))?;

    Ok(Json(VerifyTokenResponse {
        valid: true,
        user_id: user.id.to_string(),
        username: user.username,
        email: user.email,
    }))
}

/// User info response
#[derive(Debug, Serialize)]
pub struct MeResponse {
    pub user_id: String,
    pub username: String,
    pub email: String,
    pub is_verified: bool,
    pub is_admin: bool,
    pub two_factor_enabled: bool,
    pub email_notifications: bool,
    pub security_alerts: bool,
    pub preferences: serde_json::Value,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Get current user info (GET /api/v1/auth/me)
pub async fn me(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
) -> ApiResult<Json<MeResponse>> {
    let user = state
        .store
        .find_user_by_id(user_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("User not found".to_string()))?;

    Ok(Json(MeResponse {
        user_id: user.id.to_string(),
        username: user.username,
        email: user.email,
        is_verified: user.is_verified,
        is_admin: user.is_admin,
        two_factor_enabled: user.two_factor_enabled,
        email_notifications: user.email_notifications,
        security_alerts: user.security_alerts,
        preferences: user.preferences,
        created_at: user.created_at,
    }))
}

#[derive(Debug, Deserialize)]
pub struct ChangePasswordRequest {
    pub current_password: String,
    pub new_password: String,
}

#[derive(Debug, Serialize)]
pub struct ChangePasswordResponse {
    pub success: bool,
    pub message: String,
}

/// Change password for the authenticated user.
///
/// Verifies the user's current password, stores the new hash, revokes any
/// outstanding refresh tokens (so other sessions are cut off), and — when
/// the user has opted in to security alerts — sends a notification email.
pub async fn change_password(
    State(state): State<AppState>,
    AuthUser(user_id): AuthUser,
    Json(request): Json<ChangePasswordRequest>,
) -> ApiResult<Json<ChangePasswordResponse>> {
    if request.new_password.len() < 8 {
        return Err(ApiError::InvalidRequest("Password must be at least 8 characters".to_string()));
    }
    if request.new_password == request.current_password {
        return Err(ApiError::InvalidRequest(
            "New password must differ from the current password".to_string(),
        ));
    }

    let user = state
        .store
        .find_user_by_id(user_id)
        .await?
        .ok_or_else(|| ApiError::InvalidRequest("User not found".to_string()))?;

    if !verify_password(&request.current_password, &user.password_hash)
        .map_err(ApiError::Internal)?
    {
        return Err(ApiError::InvalidRequest("Current password is incorrect".to_string()));
    }

    let password_hash = hash_password(&request.new_password).map_err(ApiError::Internal)?;
    state.store.update_user_password_hash(user.id, &password_hash).await?;

    let revoked_count = state
        .db
        .revoke_all_user_tokens(user.id, "password_changed")
        .await
        .map_err(|e| {
            tracing::warn!("Failed to revoke user tokens on password change: {}", e);
            ApiError::Internal(e)
        })?;
    tracing::info!(
        "Password changed: user_id={}, revoked {} refresh tokens",
        user.id,
        revoked_count
    );

    // Best-effort security-alert email. Never fails the request.
    if user.security_alerts {
        if let Ok(email_service) = EmailService::from_env() {
            let msg = EmailService::generate_security_alert_email(
                &user.username,
                &user.email,
                "Your password was changed",
                "If you did not perform this change, reset your password immediately and contact support.",
            );
            if let Err(e) = email_service.send(msg).await {
                tracing::warn!("Failed to send password-change security alert: {}", e);
            }
        }
    }

    Ok(Json(ChangePasswordResponse {
        success: true,
        message: "Password changed successfully. Other sessions have been signed out.".to_string(),
    }))
}