better-auth-api 1.0.0-alpha.4

Plugin implementations for better-auth
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
//! Shared helpers for plugin implementations.
//!
//! Extracted to avoid duplicating common patterns across plugins (DRY).

use better_auth_core::entity::AuthUser;
use better_auth_core::{AuthContext, AuthError, AuthRequest, AuthResult, CreateUser, UpdateUser};
use chrono::Utc;

mod user_input;
pub(crate) use user_input::apply_user_create_fields;

pub(crate) fn session_is_fresh(
    session: &impl better_auth_core::AuthSession,
    config: &better_auth_core::AuthConfig,
) -> bool {
    let fresh_age = config
        .session
        .fresh_age
        .unwrap_or_else(|| chrono::Duration::hours(24));
    fresh_age.is_zero()
        || Utc::now().timestamp_millis() as f64 - session.created_at().milliseconds()
            < fresh_age.num_milliseconds() as f64
}

/// Convert an `expiresIn` value (**seconds** from now) into an RFC 3339
/// `expires_at` timestamp string.
///
/// Returns `None` when `expires_in_secs` is `None`.
pub fn expires_in_to_at(expires_in_secs: Option<i64>) -> AuthResult<Option<String>> {
    match expires_in_secs {
        Some(secs) => {
            let duration = chrono::Duration::try_seconds(secs)
                .ok_or_else(|| AuthError::bad_request("expiresIn is out of range"))?;
            let dt = chrono::Utc::now()
                .checked_add_signed(duration)
                .ok_or_else(|| AuthError::bad_request("expiresIn is out of range"))?;
            Ok(Some(
                dt.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
            ))
        }
        None => Ok(None),
    }
}

/// Fetch an API key by ID and verify that it belongs to the given user.
///
/// Returns `AuthError::not_found` if the key does not exist or belongs to
/// another user.  This pattern was duplicated in `handle_get`, `handle_update`,
/// and `handle_delete`.
pub async fn get_owned_api_key(
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    config: &crate::plugins::api_key::ApiKeyConfig,
    key_id: &str,
    user_id: &str,
    action: &str,
) -> AuthResult<better_auth_core::ApiKey> {
    use crate::plugins::api_key::{ApiKeyReferences, config_id_matches};

    let api_key = crate::plugins::api_key::storage::get_by_id(config, ctx, key_id)
        .await?
        .ok_or_else(|| AuthError::not_found("API Key not found"))?;

    // A key only exists as far as the configuration that addressed it.
    if !config_id_matches(&api_key.config_id, &config.config_id) {
        return Err(AuthError::not_found("API Key not found"));
    }

    match config.references {
        ApiKeyReferences::User => {
            if api_key.reference_id != user_id {
                return Err(AuthError::not_found("API Key not found"));
            }
        }
        ApiKeyReferences::Organization => {
            require_org_api_key_permission(ctx, user_id, &api_key.reference_id, action).await?;
        }
    }

    Ok(api_key)
}

/// Authorize a user against an organization-owned API key, mirroring
/// upstream's `checkOrgApiKeyPermission`.
pub async fn require_org_api_key_permission(
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    user_id: &str,
    organization_id: &str,
    action: &str,
) -> AuthResult<()> {
    use crate::plugins::api_key::{ApiKeyErrorCode, api_key_error};
    use crate::plugins::organization::rbac::check_permission;
    use crate::plugins::organization::{
        METADATA_AC, METADATA_CREATOR_ROLE, METADATA_DYNAMIC_ACCESS_CONTROL, METADATA_ENABLED,
        METADATA_ROLES, OrganizationConfig, RolePermissions,
    };
    use std::collections::HashMap;

    // Organization-owned keys are meaningless without the organization plugin,
    // which is what supplies the access control below.
    if !ctx
        .get_metadata(METADATA_ENABLED)
        .and_then(|value| value.as_bool())
        .unwrap_or(false)
    {
        return Err(api_key_error(ApiKeyErrorCode::OrganizationPluginRequired));
    }

    let Some(member) = ctx.database.get_member(organization_id, user_id).await? else {
        return Err(api_key_error(ApiKeyErrorCode::UserNotMemberOfOrganization));
    };

    // Upstream passes `allowCreatorAllPermissions`, so the creator role clears
    // every action without consulting the statements. Roles are composite
    // (comma-separated), so holding it alongside others still counts.
    let creator_role = ctx
        .get_metadata(METADATA_CREATOR_ROLE)
        .and_then(|value| value.as_str().map(str::to_string))
        .unwrap_or_else(|| "owner".to_string());
    if member
        .role
        .typed()?
        .split(',')
        .map(str::trim)
        .any(|role| role == creator_role)
    {
        return Ok(());
    }

    let custom_roles: Option<HashMap<String, RolePermissions>> = ctx
        .get_metadata(METADATA_ROLES)
        .map(|value| serde_json::from_value(value.clone()))
        .transpose()?
        .flatten();

    let config = OrganizationConfig {
        roles: custom_roles,
        dynamic_access_control: ctx
            .get_metadata(METADATA_DYNAMIC_ACCESS_CONTROL)
            .and_then(serde_json::Value::as_bool)
            == Some(true),
        ac: ctx
            .get_metadata(METADATA_AC)
            .map(|value| serde_json::from_value(value.clone()))
            .transpose()?
            .flatten(),
        ..Default::default()
    };
    let allowed = check_permission(
        member.role.typed()?,
        organization_id,
        "apikey",
        &[action],
        &config,
        ctx,
    )
    .await?;

    if allowed {
        Ok(())
    } else {
        Err(api_key_error(
            ApiKeyErrorCode::InsufficientApiKeyPermissions,
        ))
    }
}

/// Fetch the user's credential account, if present.
pub async fn get_credential_account<S: better_auth_core::AuthSchema>(
    ctx: &AuthContext<S>,
    user_id: impl Into<better_auth_core::SchemaValue<String>>,
) -> AuthResult<Option<better_auth_core::wire::AccountView>> {
    let user_id = user_id.into();
    let Some(user_id) = user_id.as_str() else {
        return Ok(None);
    };
    ctx.database.get_credential_account(user_id).await
}

/// Resolve the user's stored password hash from the credential account.
pub async fn get_credential_password_hash(
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    user: &impl AuthUser,
) -> AuthResult<Option<String>> {
    let Some(account) = get_credential_account(ctx, user.id().into_owned()).await? else {
        return Ok(None);
    };
    if !account.password.is_truthy()? {
        return Ok(None);
    }
    Ok(account.password.typed()?.clone())
}

/// Whether the user currently has a password set.
pub async fn user_has_password(
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    user: &impl AuthUser,
) -> AuthResult<bool> {
    Ok(get_credential_password_hash(ctx, user).await?.is_some())
}

/// Apply the configured default admin role to a new user when the caller
/// didn't set an explicit role.
pub fn apply_default_role(
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    create_user: &mut CreateUser,
) {
    if create_user.role.is_some() {
        return;
    }

    if let Some(default_role) = ctx
        .get_metadata("admin.default_role")
        .and_then(|value| value.as_str())
    {
        create_user.role = Some(default_role.to_string());
    }
}

/// Result of issuing a real session for a user.
pub struct IssuedSession {
    pub user: better_auth_core::wire::UserView,
    pub session: better_auth_core::wire::SessionView,
}

/// Session issuance failures that callers may need to surface differently from
/// a generic auth error (for example OAuth callback redirects).
pub enum SessionIssueError {
    Auth(AuthError),
    Banned { message: String },
}

impl SessionIssueError {
    pub fn into_auth_error(self) -> AuthError {
        match self {
            Self::Auth(error) => error,
            Self::Banned { message } => AuthError::banned_user(message),
        }
    }

    pub fn banned_message(&self) -> Option<&str> {
        match self {
            Self::Banned { message } => Some(message.as_str()),
            Self::Auth(_) => None,
        }
    }
}

impl From<AuthError> for SessionIssueError {
    fn from(value: AuthError) -> Self {
        Self::Auth(value)
    }
}

/// Whether the admin plugin is active for this auth instance.
pub fn admin_plugin_enabled(ctx: &AuthContext<impl better_auth_core::AuthSchema>) -> bool {
    ctx.get_metadata("admin.enabled")
        .and_then(|value| value.as_bool())
        .unwrap_or(false)
}

/// Resolve the configured message shown when a banned user attempts to create
/// a session.
pub async fn admin_banned_user_message(
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    user: &impl AuthUser,
) -> AuthResult<String> {
    let message = ctx
        .extensions
        .get::<super::admin::BannedUserMessage>()
        .cloned()
        .unwrap_or_default();
    message.resolve(&ctx.internal_user_view(user).await?).await
}

/// Issue a session for the given user, applying admin-plugin ban semantics
/// when the admin plugin is enabled.
pub async fn issue_user_session<S: better_auth_core::AuthSchema>(
    ctx: &AuthContext<S>,
    user_id: &str,
    ip_address: Option<String>,
    user_agent: Option<String>,
) -> Result<IssuedSession, SessionIssueError> {
    issue_user_session_with_lifetime(
        ctx,
        user_id,
        ip_address,
        user_agent,
        ctx.config.session.expires_in(),
    )
    .await
}

pub(crate) async fn issue_user_session_with_lifetime<S: better_auth_core::AuthSchema>(
    ctx: &AuthContext<S>,
    user_id: &str,
    ip_address: Option<String>,
    user_agent: Option<String>,
    expires_in: chrono::Duration,
) -> Result<IssuedSession, SessionIssueError> {
    let user = session_user(ctx, user_id, None).await?;

    let session = ctx
        .session_manager()
        .create_session_with_lifetime(&user, ip_address, user_agent, expires_in)
        .await?;

    Ok(IssuedSession { user, session })
}

/// Issue a session from the selected adapter result, preserving the route's user snapshot.
pub(crate) async fn issue_selected_user_session<S: better_auth_core::AuthSchema>(
    ctx: &AuthContext<S>,
    user: better_auth_core::FieldValue,
    meta: &better_auth_core::RequestMeta,
    expires_in: chrono::Duration,
) -> Result<better_auth_core::session::NativeSessionData, SessionIssueError> {
    let user_id = better_auth_core::SchemaValue::<String>::from_field(
        user.as_object()
            .and_then(|fields| fields.get("id"))
            .cloned()
            .unwrap_or_default(),
    );
    if admin_plugin_enabled(ctx)
        && user_id.is_truthy()?
        && let Some(stored_user) = ctx.database.get_user_by_id_field(&user_id).await?
    {
        apply_session_ban(ctx, &user_id, &stored_user, None).await?;
    }
    let session = ctx
        .session_manager()
        .create_session_for_id_with_lifetime(
            user_id,
            meta.ip_address.clone(),
            meta.user_agent.clone(),
            expires_in,
        )
        .await?;
    Ok(better_auth_core::session::NativeSessionData { user, session })
}

/// Resolve the user and apply session admission through the active transaction.
pub(crate) async fn session_user<S: better_auth_core::AuthSchema>(
    ctx: &AuthContext<S>,
    user_id: &str,
    transaction: Option<&dyn better_auth_core::store::AuthTransaction<S>>,
) -> Result<better_auth_core::wire::UserView, SessionIssueError> {
    let user = match transaction {
        Some(tx) => tx.get_user_by_id(user_id).await?,
        None => ctx.database.get_user_by_id(user_id).await?,
    }
    .ok_or(AuthError::UserNotFound)?;

    apply_session_ban(ctx, &user_id.into(), &user, transaction).await?;
    Ok(user)
}

async fn apply_session_ban<S: better_auth_core::AuthSchema>(
    ctx: &AuthContext<S>,
    user_id: &better_auth_core::SchemaValue<String>,
    user: &better_auth_core::wire::UserView,
    transaction: Option<&dyn better_auth_core::store::AuthTransaction<S>>,
) -> Result<(), SessionIssueError> {
    if admin_plugin_enabled(ctx) && user.banned() {
        if user
            .ban_expires()
            .is_some_and(|expires| expires.milliseconds() < Utc::now().timestamp_millis() as f64)
        {
            let update = UpdateUser {
                banned: Some(false),
                ban_reason: Some(None),
                ban_expires: Some(None),
                ..Default::default()
            };
            // Session admission updates storage without replacing the route's user snapshot.
            let _ = match transaction {
                Some(tx) => {
                    tx.update_user_by_id_value(&user_id.field_value(), update)
                        .await?
                }
                None => {
                    ctx.database
                        .update_user_by_id_value(&user_id.field_value(), update)
                        .await?
                }
            };
        } else {
            return Err(SessionIssueError::Banned {
                message: admin_banned_user_message(ctx, user).await?,
            });
        }
    }

    Ok(())
}

/// Parse a cookie value from the request's `Cookie` header.
pub fn get_cookie(req: &AuthRequest, name: &str) -> Option<String> {
    let header = req.headers.get("cookie")?;
    header
        .split(';')
        .filter_map(|cookie| {
            let trimmed = cookie.trim();
            let (cookie_name, cookie_value) = trimmed.split_once('=')?;
            (cookie_name == name).then_some(cookie_value.to_string())
        })
        .next()
}

/// Clear session cookies, publishing each header before attempting the next cookie.
pub use better_auth_core::utils::cookie_utils::delete_session_cookies;

/// Parse the comma-delimited scopes stored on an OAuth account.
pub(crate) fn parse_stored_scopes(scope: Option<&str>) -> Vec<String> {
    scope
        .unwrap_or_default()
        .split(',')
        .map(|scope| scope.trim_matches(oauth_scope_whitespace))
        .filter(|scope| !scope.is_empty())
        .map(str::to_owned)
        .collect()
}

pub(crate) fn oauth_scope_whitespace(character: char) -> bool {
    (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
}

#[cfg(test)]
#[path = "helpers/response_tests.rs"]
mod response_tests;

#[cfg(test)]
#[path = "helpers/session_tests.rs"]
mod session_tests;