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
//! Typed server operations using the plugins registered on [`BetterAuth`].
use std::any::Any;
use std::collections::HashMap;
use better_auth_core::AuthContext;
use better_auth_core::wire::ApiKeyView;
use serde_json::Value;
use crate::plugins::api_key::{
ApiKeyPlugin, ApiKeyVerificationError, CreateKeyRequest, CreateKeyResponse, UpdateKeyRequest,
VerifyApiKey,
};
use crate::{AuthError, AuthResult, AuthSchema, BetterAuth};
/// Input to a registered endpoint called from trusted server code.
#[derive(Debug, Default)]
pub struct EndpointInput {
/// Original Request for URL resolution and callbacks; native calls still bypass HTTP hooks.
pub request: Option<better_auth_core::AuthRequest>,
/// Preserve omitted headers separately from an explicitly empty header collection.
pub headers: Option<HashMap<String, String>>,
/// JSON input subject to the endpoint's schema.
pub body: Option<Value>,
/// Raw endpoint query. Omission does not import query parameters from `request`.
pub query: Option<Value>,
}
/// Native input to a registered endpoint, retaining dynamic values and object identities.
#[derive(Debug, Default)]
pub struct NativeEndpointInput {
/// Original Request for URL resolution and callbacks; input does not inherit its body or query.
pub request: Option<better_auth_core::AuthRequest>,
/// Preserve omitted headers separately from an explicitly empty header collection.
pub headers: Option<HashMap<String, String>>,
/// Native body consumed by endpoint hooks and the matched schema.
pub body: better_auth_core::FieldValue,
/// Native query consumed by endpoint hooks and the matched schema.
pub query: better_auth_core::FieldValue,
}
impl<S: AuthSchema> BetterAuth<S> {
/// Access the registered server-only organization endpoints.
pub fn organization(&self) -> AuthResult<crate::plugins::organization::OrganizationApi<'_, S>> {
crate::plugins::organization::OrganizationApi::from_context(self.context())
}
/// Access the registered native test helpers. Do not enable this plugin in production.
pub fn test(&self) -> AuthResult<crate::plugins::test_utils::TestUtilsApi<'_, S>> {
crate::plugins::test_utils::TestUtilsApi::from_context(self.context())
}
/// Call a registered endpoint with its plugin hooks, without the HTTP transport phase.
/// API errors retain response headers; ordinary errors retain their original Rust variant.
pub async fn call_endpoint(
&self,
method: better_auth_core::HttpMethod,
path: &str,
input: EndpointInput,
) -> AuthResult<better_auth_core::AuthResponse> {
let mut request =
better_auth_core::AuthRequest::new(method, path).with_optional_headers(input.headers);
if let Some(original) = input.request {
request = request.with_original_request(original);
}
request.body = input.body.as_ref().map(serde_json::to_vec).transpose()?;
request.query = input.query;
self.call_endpoint_request(request).await
}
/// Call a registered endpoint without projecting native body or query before validation.
/// HTTP hooks remain separate. Endpoint hooks, schemas, and errors use the shared dispatcher.
pub async fn call_endpoint_value(
&self,
method: better_auth_core::HttpMethod,
path: &str,
input: NativeEndpointInput,
) -> AuthResult<better_auth_core::AuthResponse> {
let mut request =
better_auth_core::AuthRequest::new(method, path).with_optional_headers(input.headers);
if let Some(original) = input.request {
request = request.with_original_request(original);
}
request.set_endpoint_body(
better_auth_core::endpoint_input::ValidatedInput::unvalidated_native(input.body),
);
request.set_endpoint_query(
better_auth_core::endpoint_input::ValidatedInput::unvalidated_native(input.query),
);
self.call_endpoint_request(request).await
}
async fn call_endpoint_request(
&self,
request: better_auth_core::AuthRequest,
) -> AuthResult<better_auth_core::AuthResponse> {
let source = better_auth_core::NativeRequest {
request: request.original_request(),
headers: request.endpoint_headers(),
};
self.context()
.with_native_context(source, |auth| {
let mut request = request.clone();
async move {
let mut context = better_auth_core::RequestHookContext::from_request(&request)?;
context.body = request.input_field_value()?;
context.meta = better_auth_core::RequestMeta::from_request_with_config(
&request,
&auth.config.advanced.ip_address,
);
let route = crate::core::auth::core_routes()
.into_iter()
.chain(self.plugins().iter().flat_map(|plugin| plugin.routes()))
.find(|route| route.matches(request.method(), request.path()));
better_auth_core::with_request_hook_context_value(context, async {
better_auth_core::hooks::set_request_hook_route(
request.path(),
route.as_ref(),
);
self.dispatch_endpoint(&mut request, false, &auth).await
})
.await
}
})
.await
}
}
/// A nullable field update with an explicit distinction between omission and clearing.
#[derive(Debug, Default)]
pub enum FieldUpdate<T> {
/// Keep the stored value.
#[default]
Unchanged,
/// Remove the stored value.
Clear,
/// Replace the stored value.
Set(T),
}
impl<T> FieldUpdate<T> {
fn into_option(self) -> Option<Option<T>> {
match self {
Self::Unchanged => None,
Self::Clear => Some(None),
Self::Set(value) => Some(Some(value)),
}
}
}
/// Optional API key settings. The acting user is a required argument to [`ApiKeyApi::create`].
#[derive(Debug, Default)]
pub struct CreateKeyOptions {
/// Configuration to use; omission selects the default configuration.
pub config_id: Option<String>,
/// Required by configurations that assign keys to organizations.
pub organization_id: Option<String>,
/// Display name.
pub name: Option<String>,
/// Prefix prepended to the generated key.
pub prefix: Option<String>,
/// Lifetime in seconds; omission uses the configured default.
pub expires_in: Option<f64>,
/// Initial usage quota.
pub remaining: Option<f64>,
/// Override the configuration's rate limiting setting.
pub rate_limit_enabled: Option<bool>,
/// Rate limit window in milliseconds.
pub rate_limit_time_window: Option<f64>,
/// Requests per rate limit window.
pub rate_limit_max: Option<f64>,
/// Refill interval in milliseconds.
pub refill_interval: Option<f64>,
/// Uses restored per refill.
pub refill_amount: Option<f64>,
/// Granted actions for each resource; omission uses the configured defaults.
pub permissions: Option<HashMap<String, Vec<String>>>,
/// Metadata stored when the configuration enables metadata.
pub metadata: Option<Value>,
}
/// Changes to an existing API key. Omitted fields retain their current values.
#[derive(Debug, Default)]
pub struct UpdateKeyOptions {
/// Configuration used to locate the key; omission selects the default configuration.
pub config_id: Option<String>,
/// Replacement display name.
pub name: Option<String>,
/// Set to false to revoke authentication with this key.
pub enabled: Option<bool>,
/// Replacement usage quota.
pub remaining: Option<f64>,
/// Enable or disable rate limiting.
pub rate_limit_enabled: Option<bool>,
/// Replacement rate limit window in milliseconds.
pub rate_limit_time_window: Option<f64>,
/// Replacement requests per rate limit window.
pub rate_limit_max: Option<f64>,
/// Replacement refill interval in milliseconds.
pub refill_interval: Option<f64>,
/// Replacement uses restored per refill.
pub refill_amount: Option<f64>,
/// Replace or clear granted actions.
pub permissions: FieldUpdate<HashMap<String, Vec<String>>>,
/// Replace or clear metadata when the configuration enables metadata.
pub metadata: FieldUpdate<Value>,
/// Set the lifetime in seconds from now, or clear expiration.
pub expires_in: FieldUpdate<f64>,
}
/// Constraints checked before verification consumes quota or rate limit capacity.
#[derive(Debug, Default)]
pub struct VerifyKeyOptions {
/// Restrict verification to this configuration.
pub config_id: Option<String>,
/// Require every listed action for every requested resource.
pub permissions: Option<HashMap<String, Vec<String>>>,
}
/// Server API bound to the registered API key plugin and initialized auth context.
/// The typed business operations require a fallback for requestless dynamic base URLs.
pub struct ApiKeyApi<'a, S: AuthSchema> {
plugin: &'a ApiKeyPlugin,
context: &'a AuthContext<S>,
}
impl<S: AuthSchema> BetterAuth<S> {
/// Access the API key plugin registered on this auth instance.
///
/// Returns a configuration error when [`ApiKeyPlugin`] is not registered.
pub fn api_keys(&self) -> AuthResult<ApiKeyApi<'_, S>> {
let plugin = self
.plugins()
.iter()
.find_map(|plugin| (plugin.as_ref() as &dyn Any).downcast_ref::<ApiKeyPlugin>())
.ok_or_else(|| AuthError::config("ApiKeyPlugin is not registered"))?;
Ok(ApiKeyApi {
plugin,
context: self.context(),
})
}
}
impl<S: AuthSchema> ApiKeyApi<'_, S> {
/// Delete expired database keys through the registered server-only endpoint.
///
/// Endpoint hooks receive the native input. The complete result retains hook replacements
/// and any original Logger error returned by the endpoint's cleanup catch.
pub async fn delete_all_expired(
&self,
input: NativeEndpointInput,
) -> AuthResult<better_auth_core::FieldValue> {
self.plugin
.delete_all_expired_api_keys(
self.context,
better_auth_core::NativeRequest {
request: input.request.as_ref(),
headers: input.headers.as_ref(),
},
input.body,
input.query,
)
.await
}
/// Issue a key on behalf of a user from trusted server code.
///
/// Organization configurations check the acting user's organization permissions.
/// The response returns the plaintext key once; later operations cannot retrieve it.
pub async fn create(
&self,
user_id: &str,
options: CreateKeyOptions,
) -> AuthResult<CreateKeyResponse> {
self.context
.with_native_context(Default::default(), |context| async move {
self.plugin
.create_key(
&context,
&CreateKeyRequest {
config_id: options.config_id,
user_id: Some(user_id.to_owned()),
organization_id: options.organization_id,
name: options.name,
prefix: options.prefix,
expires_in: options.expires_in,
remaining: options.remaining,
rate_limit_enabled: options.rate_limit_enabled,
rate_limit_time_window: options.rate_limit_time_window,
rate_limit_max: options.rate_limit_max,
refill_interval: options.refill_interval,
refill_amount: options.refill_amount,
permissions: options.permissions,
metadata: options.metadata,
},
)
.await
})
.await
}
/// Update a key on behalf of its owner or an authorized organization member.
///
/// The caller must authorize the acting user before calling this server API.
pub async fn update(
&self,
user_id: &str,
key_id: &str,
options: UpdateKeyOptions,
) -> AuthResult<ApiKeyView> {
self.context
.with_native_context(Default::default(), |context| async move {
self.plugin
.update_key(
&context,
&UpdateKeyRequest {
config_id: options.config_id,
key_id: key_id.to_owned(),
user_id: Some(user_id.to_owned()),
name: options.name,
enabled: options.enabled,
remaining: options.remaining,
rate_limit_enabled: options.rate_limit_enabled,
rate_limit_time_window: options.rate_limit_time_window,
rate_limit_max: options.rate_limit_max,
refill_interval: options.refill_interval,
refill_amount: options.refill_amount,
permissions: options.permissions.into_option(),
metadata: options
.metadata
.into_option()
.map(|value| value.unwrap_or(Value::Null)),
expires_in: options.expires_in.into_option(),
},
)
.await
})
.await
}
/// Verify a presented credential and consume one use after its permissions pass.
///
/// Validation errors reject the credential; internal errors preserve infrastructure failures.
pub async fn verify(
&self,
key: &str,
options: VerifyKeyOptions,
) -> Result<ApiKeyView, ApiKeyVerificationError> {
let permissions = options
.permissions
.map(|resources| serde_json::json!(resources));
self.context
.with_native_context(Default::default(), |context| async move {
Ok(self
.plugin
.verify_api_key(
&VerifyApiKey {
key,
config_id: options.config_id.as_deref(),
permissions: permissions.as_ref(),
},
&context,
)
.await)
})
.await
.map_err(ApiKeyVerificationError::Endpoint)?
}
}
impl<S: AuthSchema> BetterAuth<S> {
/// Consume phone OTPs through the registered server-only endpoint.
pub fn phone_number(
&self,
) -> AuthResult<better_auth_api::plugins::phone_number::PhoneNumberApi<'_, S>> {
better_auth_api::plugins::phone_number::PhoneNumberApi::from_context(self.context())
}
/// Access server-only Email OTP creation and retrieval using the registered plugin.
pub fn email_otp(&self) -> AuthResult<better_auth_api::plugins::email_otp::EmailOtpApi<'_, S>> {
better_auth_api::plugins::email_otp::EmailOtpApi::from_context(self.context())
}
}
impl<S: AuthSchema> BetterAuth<S> {
/// Provision users through the registered Admin plugin from trusted server code.
pub fn admin(&self) -> AuthResult<better_auth_api::plugins::admin::AdminApi<'_, S>> {
better_auth_api::plugins::admin::AdminApi::from_context(self.context())
}
/// Check Admin role permissions for application resources from server code.
///
/// The checks use the configuration of the registered `AdminPlugin` and add no routes.
/// This returns [`AdminPermissionError::PluginNotRegistered`] when the plugin is absent.
///
/// [`AdminPermissionError::PluginNotRegistered`]: better_auth_api::plugins::admin::AdminPermissionError::PluginNotRegistered
pub fn admin_permissions(
&self,
) -> Result<
better_auth_api::plugins::admin::AdminPermissionApi<'_, S>,
better_auth_api::plugins::admin::AdminPermissionError,
> {
better_auth_api::plugins::admin::AdminPermissionApi::from_context(self.context())
}
/// Use the registered JWT key adapter from trusted server code.
pub fn jwt(&self) -> AuthResult<better_auth_api::plugins::jwt::JwtApi<'_, S>> {
better_auth_api::plugins::jwt::JwtApi::from_context(self.context())
}
}
impl<S: AuthSchema> BetterAuth<S> {
/// Use the registered server-only TOTP and backup-code endpoints.
pub fn two_factor(
&self,
) -> AuthResult<better_auth_api::plugins::two_factor::TwoFactorApi<'_, S>> {
better_auth_api::plugins::two_factor::TwoFactorApi::from_context(self.context())
}
}