better-auth-api 1.0.0-alpha.5

Plugin implementations for better-auth
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
mod callbacks;
mod fields;
pub use callbacks::OrganizationCallbacks;
pub mod handlers;
pub mod hooks;
mod input;
mod native_json;
mod policy;
mod request;
mod server_api;
pub use better_auth_core::organization_fields::OrganizationFields;
pub use server_api::{AddMemberInput, OrganizationApi};
pub mod rbac;
pub mod types;

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use better_auth_core::entity::AuthSession;
use better_auth_core::error::AuthResult;
use better_auth_core::plugin::{AuthContext, AuthPlugin, AuthRoute};
use better_auth_core::types::{AuthRequest, AuthResponse, HttpMethod};

/// Data supplied when an invitation is created or resent.
#[derive(Clone)]
pub struct InvitationEmail {
    /// The projected invitation, including its current expiration and declared fields.
    pub invitation: better_auth_core::wire::InvitationView,
    /// The organization receiving the invited member.
    pub organization: types::OrganizationResponse,
    /// The member sending the invitation.
    pub member: better_auth_core::types::Member,
    /// The user sending the invitation.
    pub inviter: better_auth_core::FieldValue,
    /// HTTP request that initiated delivery, absent for requestless server calls.
    pub request: Option<AuthRequest>,
}

/// Application callback for invitation email delivery.
#[async_trait]
pub trait SendInvitationEmail: Send + Sync {
    /// Send the invitation email. The plugin logs delivery errors without failing the request.
    async fn send(&self, email: &InvitationEmail) -> AuthResult<()>;
}

/// Permission definitions for a role
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct RolePermissions {
    pub organization: Vec<String>,
    pub member: Vec<String>,
    pub invitation: Vec<String>,
    /// Actions this role may perform on organization-owned API keys. Upstream's
    /// default statements define none, so only the creator role can manage them
    /// until an application grants this explicitly.
    #[serde(rename = "apiKey", alias = "api_key")]
    pub api_key: Vec<String>,
    pub team: Vec<String>,
    pub ac: Vec<String>,
    #[serde(flatten)]
    pub additional: HashMap<String, Vec<String>>,
}

/// Team creation and membership limits.
#[derive(Clone)]
pub struct OrganizationTeamsConfig {
    pub enabled: bool,
    pub default_team: bool,
    pub allow_removing_all_teams: bool,
    pub maximum_teams: Option<usize>,
    pub maximum_members_per_team: Option<usize>,
    /// Dynamic capacity. Trusted server calls require a session when this callback is configured.
    pub maximum_members_per_team_callback: Option<Arc<dyn hooks::TeamMemberLimitPolicy>>,
}

impl std::fmt::Debug for OrganizationTeamsConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OrganizationTeamsConfig")
            .field("enabled", &self.enabled)
            .field("default_team", &self.default_team)
            .field("allow_removing_all_teams", &self.allow_removing_all_teams)
            .field("maximum_teams", &self.maximum_teams)
            .field("maximum_members_per_team", &self.maximum_members_per_team)
            .field(
                "maximum_members_per_team_callback",
                &self
                    .maximum_members_per_team_callback
                    .as_ref()
                    .map(|_| "custom"),
            )
            .finish()
    }
}

impl Default for OrganizationTeamsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            default_team: true,
            allow_removing_all_teams: false,
            maximum_teams: None,
            maximum_members_per_team: None,
            maximum_members_per_team_callback: None,
        }
    }
}

/// Configuration for the Organization plugin
#[derive(Clone, better_auth_core::PluginConfig)]
#[plugin(name = "OrganizationPlugin")]
pub struct OrganizationConfig {
    /// Application fields for organization entities.
    #[config(default = better_auth_core::organization_fields::OrganizationFields::default(), skip)]
    pub schema: OrganizationFields,

    /// Application lifecycle hooks.
    #[config(default = None, skip)]
    pub hooks: Option<Arc<dyn hooks::OrganizationHooks>>,
    /// Asynchronous organization configuration.
    #[config(default = None, skip)]
    pub policy: Option<Arc<dyn hooks::OrganizationPolicy>>,
    /// Enable teams and configure team limits.
    #[config(default = OrganizationTeamsConfig::default(), skip)]
    pub teams: OrganizationTeamsConfig,
    /// Enable persisted organization roles.
    #[config(default = false)]
    pub dynamic_access_control: bool,
    /// Maximum persisted roles per organization.
    #[config(default = None)]
    pub maximum_roles_per_organization: Option<usize>,
    /// Resource statements for dynamic access control.
    #[config(default = None, skip)]
    pub ac: Option<HashMap<String, Vec<String>>>,
    /// Allow users to create organizations (default: true)
    #[config(default = true)]
    pub allow_user_to_create_organization: bool,
    /// Maximum organizations per user (None = unlimited)
    #[config(default = None)]
    pub organization_limit: Option<usize>,
    /// Maximum members per organization (None or zero uses upstream default 100)
    #[config(default = Some(100))]
    pub membership_limit: Option<usize>,
    /// Dynamic membership capacity, replacing the static admission limit.
    #[config(default = None, skip)]
    pub membership_limit_callback: Option<Arc<dyn hooks::MembershipLimitPolicy>>,
    /// Role assigned to organization creator (default: "owner")
    #[config(default = "owner".to_string())]
    pub creator_role: String,
    /// Invitation expiration in seconds, including fractions (default: 48 hours).
    #[config(default = 172800.0)]
    pub invitation_expires_in: f64,
    /// Maximum pending invitations per organization (None uses upstream default 100)
    #[config(default = Some(100))]
    pub invitation_limit: Option<usize>,
    /// Cancel the previous pending invitation before creating a replacement.
    #[config(default = false)]
    pub cancel_pending_invitations_on_re_invite: bool,
    /// Require a verified recipient email for invitation lookup, acceptance, and rejection.
    #[config(default = false)]
    pub require_email_verification_on_invitation: bool,
    /// Disable organization deletion (default: false)
    #[config(default = false)]
    pub disable_organization_deletion: bool,
    /// Static role definitions. An explicit map, including an empty map, replaces defaults.
    #[config(default = None, skip)]
    pub roles: Option<HashMap<String, RolePermissions>>,
    /// Optional delivery callback used for new and resent invitations.
    #[config(default = None, skip)]
    pub send_invitation_email: Option<Arc<dyn SendInvitationEmail>>,
}

impl std::fmt::Debug for OrganizationConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OrganizationConfig")
            .field(
                "allow_user_to_create_organization",
                &self.allow_user_to_create_organization,
            )
            .field("organization_limit", &self.organization_limit)
            .field("membership_limit", &self.membership_limit)
            .field("creator_role", &self.creator_role)
            .field("invitation_expires_in", &self.invitation_expires_in)
            .field("invitation_limit", &self.invitation_limit)
            .field(
                "cancel_pending_invitations_on_re_invite",
                &self.cancel_pending_invitations_on_re_invite,
            )
            .field(
                "require_email_verification_on_invitation",
                &self.require_email_verification_on_invitation,
            )
            .field(
                "disable_organization_deletion",
                &self.disable_organization_deletion,
            )
            .field("roles", &self.roles)
            .field("teams", &self.teams)
            .field("dynamic_access_control", &self.dynamic_access_control)
            .field(
                "maximum_roles_per_organization",
                &self.maximum_roles_per_organization,
            )
            .field("ac", &self.ac)
            .field(
                "send_invitation_email",
                &self.send_invitation_email.as_ref().map(|_| "custom"),
            )
            .finish()
    }
}

/// Organization plugin for multi-tenancy support
#[derive(Clone)]
pub struct OrganizationPlugin {
    config: OrganizationConfig,
}

impl OrganizationPlugin {
    /// Configure dynamic organization capacity. Listing retains the upstream default page size.
    pub fn membership_limit_callback(
        mut self,
        callback: Arc<dyn hooks::MembershipLimitPolicy>,
    ) -> Self {
        self.config.membership_limit_callback = Some(callback);
        self
    }
    /// Configure application lifecycle hooks.
    pub fn hooks(mut self, hooks: Arc<dyn hooks::OrganizationHooks>) -> Self {
        self.config.hooks = Some(hooks);
        self
    }
    /// Configure asynchronous organization options.
    pub fn policy(mut self, policy: Arc<dyn hooks::OrganizationPolicy>) -> Self {
        self.config.policy = Some(policy);
        self
    }
    /// Configure organization teams.
    pub fn teams(mut self, teams: OrganizationTeamsConfig) -> Self {
        self.config.teams = teams;
        self
    }
    /// Configure access-control resource statements.
    pub fn access_control(mut self, ac: HashMap<String, Vec<String>>) -> Self {
        self.config.ac = Some(ac);
        self
    }
    /// Configure delivery for new and resent invitations.
    pub fn custom_send_invitation_email(mut self, sender: Arc<dyn SendInvitationEmail>) -> Self {
        self.config.send_invitation_email = Some(sender);
        self
    }
}

/// Metadata key announcing that the organization plugin is installed.
pub(crate) const METADATA_DYNAMIC_ACCESS_CONTROL: &str = "organization.dynamic_access_control";
pub(crate) const METADATA_AC: &str = "organization.ac";
pub(crate) const METADATA_ENABLED: &str = "organization.enabled";
/// Metadata key carrying the configured custom roles, so other plugins can run
/// the organization's access control without depending on this plugin's config.
pub(crate) const METADATA_ROLES: &str = "organization.roles";
/// Metadata key carrying the creator role, which is allowed every action.
pub(crate) const METADATA_CREATOR_ROLE: &str = "organization.creator_role";

#[async_trait]
impl<S: better_auth_core::AuthSchema> AuthPlugin<S> for OrganizationPlugin {
    fn name(&self) -> &'static str {
        "organization"
    }

    fn openapi(
        &self,
    ) -> better_auth_core::AuthResult<better_auth_core::openapi::OpenApiPluginMetadata> {
        better_auth_core::openapi::OpenApiPluginMetadata::from_routes(
            <Self as better_auth_core::AuthPlugin<S>>::name(self),
            <Self as better_auth_core::AuthPlugin<S>>::routes(self),
        )?
        .organization_fields(&self.config.schema)
    }

    fn schema(
        &self,
        fields: &mut better_auth_core::plugin_runtime::ModelFields,
    ) -> better_auth_core::AuthResult<()> {
        fields.register_organization_schema(
            &self.config.schema,
            self.config.teams.enabled,
            self.config.dynamic_access_control,
        );
        fields.register_native_session_fields(METADATA_ENABLED)?;
        if self.config.teams.enabled {
            fields.register_native_session_fields("organization.teams_enabled")?;
        }
        Ok(())
    }

    async fn on_init(
        &self,
        ctx: &mut better_auth_core::AuthInitContext<S>,
    ) -> better_auth_core::AuthResult<()> {
        ctx.extensions
            .insert(self.config.schema.initialized_options());
        ctx.extensions.insert(self.clone());

        S::Session::require_plugin_fields("organization", &["active_organization_id"])?;
        if self.config.teams.enabled {
            S::Session::require_plugin_fields("organization", &["active_team_id"])?;
        }
        ctx.set_metadata(
            METADATA_DYNAMIC_ACCESS_CONTROL,
            serde_json::json!(self.config.dynamic_access_control),
        );
        ctx.set_metadata(METADATA_AC, serde_json::json!(self.config.ac));
        ctx.set_metadata(
            "organization.teams_enabled",
            serde_json::json!(self.config.teams.enabled),
        );
        ctx.set_metadata(METADATA_ENABLED, serde_json::Value::Bool(true));
        ctx.set_metadata(
            METADATA_ROLES,
            serde_json::to_value(&self.config.roles).unwrap_or_default(),
        );
        ctx.set_metadata(
            METADATA_CREATOR_ROLE,
            serde_json::Value::String(self.config.creator_role.clone()),
        );
        Ok(())
    }

    fn routes(&self) -> Vec<AuthRoute> {
        let mut routes = vec![
            // Organization CRUD
            AuthRoute::post("/organization/create", "createOrganization"),
            AuthRoute::post("/organization/update", "updateOrganization").require_headers(true),
            AuthRoute::post("/organization/delete", "deleteOrganization").require_headers(true),
            AuthRoute::get("/organization/list", "listOrganizations").require_headers(true),
            AuthRoute::get("/organization/get-organization", "getOrganization")
                .require_headers(true)
                .query_validator(crate::plugins::query_input::organization),
            AuthRoute::get("/organization/get-full-organization", "getFullOrganization")
                .require_headers(true)
                .query_validator(crate::plugins::query_input::full_organization),
            AuthRoute::post("/organization/check-slug", "checkOrganizationSlug"),
            AuthRoute::post("/organization/set-active", "setActiveOrganization")
                .require_headers(true),
            AuthRoute::post("/organization/leave", "leaveOrganization").require_headers(true),
            // Member management
            AuthRoute::get("/organization/get-active-member", "getActiveMember")
                .require_headers(true),
            AuthRoute::get(
                "/organization/get-active-member-role",
                "getActiveMemberRole",
            )
            .require_headers(true)
            .query_validator(crate::plugins::query_input::active_member_role),
            AuthRoute::get("/organization/list-members", "listMembers")
                .require_headers(true)
                .query_validator(crate::plugins::query_input::list_members),
            AuthRoute::post("/organization/remove-member", "removeMember").require_headers(true),
            AuthRoute::post(
                "/organization/update-member-role",
                "updateOrganizationMemberRole",
            )
            .require_headers(true),
            // Invitations
            AuthRoute::post(
                "/organization/invite-member",
                "createOrganizationInvitation",
            )
            .require_headers(true),
            AuthRoute::get("/organization/get-invitation", "getInvitation")
                .require_headers(true)
                .query_validator(crate::plugins::query_input::invitation),
            AuthRoute::get("/organization/list-invitations", "listInvitations")
                .require_headers(true)
                .query_validator(crate::plugins::query_input::organization_id),
            AuthRoute::get("/organization/list-user-invitations", "listUserInvitations")
                .query_validator(crate::plugins::query_input::user_invitations),
            AuthRoute::post("/organization/accept-invitation", "acceptInvitation")
                .require_headers(true),
            AuthRoute::post("/organization/reject-invitation", "rejectInvitation")
                .require_headers(true),
            AuthRoute::post("/organization/cancel-invitation", "cancelInvitation")
                .require_headers(true),
            // Permission check
            AuthRoute::post("/organization/has-permission", "hasPermission").require_headers(true),
        ];
        if self.config.teams.enabled {
            routes.extend(handlers::team::routes());
        }
        if self.config.dynamic_access_control {
            for (path, method) in [
                ("create-role", HttpMethod::Post),
                ("get-role", HttpMethod::Get),
                ("list-roles", HttpMethod::Get),
                ("update-role", HttpMethod::Post),
                ("delete-role", HttpMethod::Post),
            ] {
                routes.push(
                    match method {
                        HttpMethod::Get => AuthRoute::get(format!("/organization/{path}"), path)
                            .query_validator(if path == "get-role" {
                                crate::plugins::query_input::organization_role
                            } else {
                                crate::plugins::query_input::organization_id
                            }),
                        _ => AuthRoute::post(format!("/organization/{path}"), path),
                    }
                    .require_headers(true),
                );
            }
        }
        routes
            .into_iter()
            .map(|route| {
                if route.method == HttpMethod::Post {
                    let schema = request::prepared_schema(&route.path, &self.config.schema);
                    route.body_validator(move |req| request::validate(req, &schema))
                } else {
                    route
                }
            })
            .collect()
    }

    async fn on_request(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<S>,
    ) -> AuthResult<Option<AuthResponse>> {
        if self.config.teams.enabled
            && handlers::team::routes()
                .iter()
                .any(|route| route.path == req.path())
        {
            return handlers::team::handle_team_request(req, ctx, &self.config).await;
        }
        if self.config.dynamic_access_control
            && matches!(
                req.path(),
                "/organization/create-role"
                    | "/organization/get-role"
                    | "/organization/list-roles"
                    | "/organization/update-role"
                    | "/organization/delete-role"
            )
        {
            return handlers::roles::handle_role_request(req, ctx, &self.config).await;
        }
        let response: AuthResult<Option<AuthResponse>> = match (req.method(), req.path()) {
            // Organization CRUD
            (HttpMethod::Post, "/organization/create") => Ok(Some(
                handlers::org::handle_create_organization(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/update") => Ok(Some(
                handlers::org::handle_update_organization(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/delete") => Ok(Some(
                handlers::org::handle_delete_organization(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Get, "/organization/list") => Ok(Some(
                handlers::org::handle_list_organizations(req, ctx).await?,
            )),
            (HttpMethod::Get, "/organization/get-organization") => Ok(Some(
                handlers::org::handle_get_organization(req, ctx).await?,
            )),
            (HttpMethod::Get, "/organization/get-full-organization") => Ok(Some(
                handlers::org::handle_get_full_organization(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/check-slug") => {
                Ok(Some(handlers::org::handle_check_slug(req, ctx).await?))
            }
            (HttpMethod::Post, "/organization/set-active") => Ok(Some(
                handlers::org::handle_set_active_organization(req, ctx).await?,
            )),
            (HttpMethod::Post, "/organization/leave") => Ok(Some(
                handlers::org::handle_leave_organization(req, ctx, &self.config).await?,
            )),
            // Member management
            (HttpMethod::Get, "/organization/get-active-member") => Ok(Some(
                handlers::member::handle_get_active_member(req, ctx).await?,
            )),
            (HttpMethod::Get, "/organization/get-active-member-role") => Ok(Some(
                handlers::member::handle_get_active_member_role(req, ctx).await?,
            )),
            (HttpMethod::Get, "/organization/list-members") => Ok(Some(
                handlers::member::handle_list_members(req, &self.config, ctx).await?,
            )),
            (HttpMethod::Post, "/organization/remove-member") => Ok(Some(
                handlers::member::handle_remove_member(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/update-member-role") => Ok(Some(
                handlers::member::handle_update_member_role(req, ctx, &self.config).await?,
            )),
            // Invitations
            (HttpMethod::Post, "/organization/invite-member") => Ok(Some(
                handlers::invitation::handle_invite_member(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Get, "/organization/get-invitation") => Ok(Some(
                handlers::invitation::handle_get_invitation(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Get, "/organization/list-invitations") => Ok(Some(
                handlers::invitation::handle_list_invitations(req, ctx).await?,
            )),
            (HttpMethod::Get, "/organization/list-user-invitations") => Ok(Some(
                handlers::invitation::handle_list_user_invitations(req, ctx).await?,
            )),
            (HttpMethod::Post, "/organization/accept-invitation") => Ok(Some(
                handlers::invitation::handle_accept_invitation(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/reject-invitation") => Ok(Some(
                handlers::invitation::handle_reject_invitation(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/cancel-invitation") => Ok(Some(
                handlers::invitation::handle_cancel_invitation(req, ctx, &self.config).await?,
            )),
            // Permission check
            (HttpMethod::Post, "/organization/has-permission") => Ok(Some(
                handlers::handle_has_permission(req, ctx, &self.config).await?,
            )),
            _ => Ok(None),
        };
        response?
            .map(|mut response| {
                shape_invitation_output(req.path(), &mut response, &self.config)?;
                Ok(response)
            })
            .transpose()
    }
}

fn shape_invitation_output(
    path: &str,
    response: &mut AuthResponse,
    config: &OrganizationConfig,
) -> AuthResult<()> {
    if response.status >= 400
        || fields::invitation_team_id_is_declared(config)
        || !matches!(
            path,
            "/organization/invite-member"
                | "/organization/get-invitation"
                | "/organization/list-invitations"
                | "/organization/list-user-invitations"
                | "/organization/accept-invitation"
                | "/organization/reject-invitation"
                | "/organization/cancel-invitation"
                | "/organization/get-full-organization"
        )
    {
        return Ok(());
    }
    fn shape(invitation: &better_auth_core::FieldValue) -> AuthResult<()> {
        if let Some(object) = invitation.as_object() {
            let _ = object.delete("teamId")?;
        }
        Ok(())
    }
    fn shape_list(value: &better_auth_core::FieldValue) -> AuthResult<()> {
        if let Some(invitations) = value.as_array() {
            for invitation in invitations.iter()? {
                shape(&invitation?)?;
            }
        }
        Ok(())
    }
    let value = response.body.field_value()?;
    match path {
        "/organization/list-invitations" | "/organization/list-user-invitations" => {
            shape_list(&value)?;
        }
        "/organization/get-full-organization" => {
            if let Some(object) = value.as_object()
                && let Some(invitations) = object.get("invitations")?
            {
                shape_list(&invitations)?;
            }
        }
        "/organization/accept-invitation" | "/organization/reject-invitation" => {
            if let Some(object) = value.as_object()
                && let Some(invitation) = object.get("invitation")?
            {
                shape(&invitation)?;
            }
        }
        _ => shape(&value)?,
    }
    if matches!(response.body, better_auth_core::ResponseBody::Bytes(_)) {
        response.body = better_auth_core::ResponseBody::Bytes(
            value.stringify()?.unwrap_or_default().into_bytes(),
        );
    }
    Ok(())
}