authkit 0.1.1

A better-auth inspired authentication library for Rust. Framework-agnostic, secure by default, with database-backed sessions and email verification.
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
# AuthKit

**A better-auth–inspired authentication library for Rust**  
Plug-and-play. Framework-agnostic. Opinionated, but extensible.

---

## Overview

AuthKit is a Rust authentication library designed to feel like [better-auth](https://github.com/better-auth/better-auth), but for the Rust ecosystem.

It provides:

- **A single `Auth` entry point**
- **Opinionated defaults** (secure by default)
- **Zero framework lock-in**
- **Database-backed authentication** using SQLx (Postgres / SQLite)
- **The same API** across HTTP servers, CLIs, background workers, and proxies

AuthKit is **not** a framework, middleware, or ORM.  
It is a self-contained authentication engine that you embed into your application.

---

## Design Goals

AuthKit is built around the following **non-negotiable principles**:

### 1. Single Entry Point

Users interact with **one object only**: `Auth`.

```rust
let auth = Auth::builder()
    .database(Database::sqlite("auth.db").await?)
    .build()?;
```

- No repositories.
- No generics.
- No leaked internals.

### 2. Framework-Agnostic by Design

AuthKit:

- Does **not** depend on Axum, Actix, Rocket, Hyper, or Tower
- Does **not** assume HTTP
- Works equally well in:
  - CLI tools
  - REST APIs
  - gRPC services
  - Proxies (Pingora)
  - Background workers

**Framework adapters live outside the core.**

### 3. Opinionated Defaults, Explicit Overrides

AuthKit ships with:

- Argon2id password hashing
- Database-backed sessions
- Secure token generation
- Sensible expiry defaults

Users can override behavior explicitly, but **never accidentally weaken security**.

### 4. No Leaky Abstractions

AuthKit hides:

- SQLx
- Database schemas
- Crypto implementations
- Token formats

Users **never interact with**:

- Traits
- Repositories
- Lifetimes
- Generic parameters

### 5. Same API Everywhere

```rust
auth.register(Register { ... }).await?;
auth.login(Login { ... }).await?;
auth.verify(Verify { token }).await?;
auth.logout(Logout { token }).await?;
```

These calls behave **identically** whether invoked from:

- an HTTP handler
- a CLI command
- a test
- a background task

---

## Non-Goals

AuthKit **intentionally does not** attempt to:

- Be an OAuth provider (may integrate later)
- Replace application authorization logic
- Act as a user management UI
- Tie itself to any web framework

---

## Example Usage

### Create an Auth Instance

```rust
use authkit::prelude::*;

let auth = Auth::builder()
    .database(Database::sqlite("auth.db").await?)
    .build()?;
```

### Register a User

```rust
auth.register(Register {
    email: "user@example.com".into(),
    password: "secure-password".into(),
}).await?;
```

### Login

```rust
let session = auth.login(Login {
    email: "user@example.com".into(),
    password: "secure-password".into(),
}).await?;
```

### Verify a Session

```rust
let user = auth.verify(Verify {
    token: session.token.clone(),
}).await?;
```

### Logout

```rust
auth.logout(Logout {
    token: session.token,
}).await?;
```

---

## Architecture

### High-Level Structure

```
Auth
 └── AuthInner (Arc)
     ├── Database (Arc<Box<dyn DatabaseTrait>>)
     ├── PasswordStrategy (Box<dyn PasswordStrategy>)
     ├── SessionStrategy (Box<dyn SessionStrategy>)
     └── TokenStrategy (Box<dyn TokenStrategy>)
```

**Key characteristics:**

- `Auth` is cheap to clone (uses `Arc` internally)
- Internals are completely hidden
- Components are swappable via builder pattern
- No global state

### Strategy Pattern (IMPORTANT!)

All strategies follow a **consistent pattern** where the database is passed as a parameter, not stored:

```rust
// ❌ WRONG - Don't store database in strategy
pub struct SomeStrategy {
    db: Arc<Box<dyn DatabaseTrait>>,
}

// ✅ CORRECT - Pass database as parameter
pub struct SomeStrategy;

#[async_trait]
impl SomeTrait for SomeStrategy {
    async fn do_something(
        &self,
        db: &dyn DatabaseTrait,  // ✅ Database passed as parameter
        ...
    ) -> Result<()> {
        db.some_operation(...).await
    }
}
```

**Why this pattern?**

1. **Consistency** - All strategies work the same way
2. **No coupling** - Strategies don't own database connections
3. **Testability** - Easy to mock `DatabaseTrait`
4. **Flexibility** - Strategies remain stateless

### Full Architecture Diagram

```
┌─────────────────────────────────────────────────────────┐
│                    Application Layer                     │
│  (Auth, Operations: register, login, verify, etc.)      │
└─────────────────────┬───────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│                  Strategy Layer                          │
│  • PasswordStrategy   (Argon2, Bcrypt, etc.)            │
│  • SessionStrategy    (Database-backed)                  │
│  • TokenStrategy      (Database-backed)                  │
│                                                           │
│  Strategies receive &dyn DatabaseTrait as parameter      │
└─────────────────────┬───────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│              DatabaseTrait (Abstraction)                 │
│                                                           │
│  User Operations:                                        │
│    • find_user_by_email()                                │
│    • find_user_by_id()                                   │
│    • create_user()                                       │
│                                                           │
│  Session Operations:                                     │
│    • create_session()                                    │
│    • find_session()                                      │
│    • delete_session()                                    │
│    • delete_expired_sessions()                           │
│                                                           │
│  Token Operations:                                       │
│    • create_token()                                      │
│    • find_token()                                        │
│    • mark_token_used()                                   │
│    • delete_token()                                      │
│    • delete_expired_tokens()                             │
└─────────────────────┬───────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│            Backend Implementations                       │
│                                                           │
│  ┌─────────────────┐        ┌─────────────────┐         │
│  │ SqliteDatabase  │        │ PostgresDatabase│         │
│  │                 │        │                 │         │
│  │ Uses ? params   │        │ Uses $N params  │         │
│  │ SQLite pool     │        │ Postgres pool   │         │
│  └─────────────────┘        └─────────────────┘         │
└─────────────────────────────────────────────────────────┘
```

---

## Database Support

Currently supported:

- **SQLite**
- **PostgreSQL**

Backed by SQLx, but **SQLx is not exposed**.

AuthKit manages:

- Schema
- Migrations
- Versioning

```rust
auth.migrate().await?;
```

### Database Schema

- **`users`** - User accounts with email, password, verification status
- **`sessions`** - Active user sessions with expiration
- **`tokens`** - Unified table for email verification, password reset, magic links, etc.

All tables include:
- Proper indexes for performance
- Foreign key constraints for data integrity
- Automatic cleanup of expired data

---

## Security Defaults

| Feature                | Default              |
|------------------------|----------------------|
| Password hashing       | Argon2id             |
| Timing-safe compares   | ✅ Enabled           |
| Session expiration     | ✅ Enabled (24h)     |
| Token entropy          | High (crypto secure) |
| Password reuse         | 🚫 Prevented         |
| Weak passwords         | 🚫 Rejected          |

Security-sensitive behavior requires **explicit opt-out**.

---

## Feature Flags

```toml
[features]
default = ["sqlite", "argon2"]

# Database backends
sqlite = ["sqlx/sqlite"]
postgres = ["sqlx/postgres"]

# Password strategies
argon2 = []
bcrypt = []

# Token strategies (future)
jwt = []
```

---

## Adapters

Adapters translate framework-specific concepts into AuthKit calls.

**Planned adapters:**

- Axum
- Actix
- Rocket
- Hyper
- Pingora
- CLI helpers

**Important:** Adapters contain **no authentication logic**.  
They only translate request/response formats.

---

## Project Status

**Current phase:** Foundation ✅

### Implemented:

- ✅ Core Auth API
- ✅ Builder pattern
- ✅ SQLite backend
- ✅ PostgreSQL backend
- ✅ Argon2 password hashing
- ✅ Database sessions
- ✅ Token infrastructure (strategy + database methods)
- ✅ Email verification flow (send, verify, resend operations)

### Planned:

- 🔜 Password reset flow
- 🔜 Magic link authentication
- 🔜 JWT sessions
- 🔜 Refresh tokens
- 🔜 Axum adapter
- 🔜 Actix adapter
- 🔜 Rate limiting
- 🔜 Audit logging
- 🔜 OAuth integration
- 🔜 Two-factor authentication

---

## Contribution Guidelines (Agents)

If you are contributing to this project:

### You MUST:

✅ **Preserve the single-entry-point design**  
✅ **Avoid exposing generics or traits publicly**  
✅ **Keep framework dependencies out of core**  
✅ **Prefer composition over configuration**  
✅ **Default to secure behavior**  
✅ **Follow the strategy pattern** (pass database as parameter, don't store it)  
✅ **Add database methods to `DatabaseTrait`**, not to strategies  
✅ **Implement all database methods in both SQLite and Postgres**  
✅ **Group related database methods** by feature area (users, sessions, tokens, etc.)

### You MUST NOT:

❌ **Add framework-specific logic to core**  
❌ **Leak SQLx types into the public API**  
❌ **Introduce global state**  
❌ **Require users to wire repositories manually**  
❌ **Store database references in strategies**  
❌ **Expose `DatabaseTrait` or strategy traits publicly**  
❌ **Create inconsistent patterns** (all strategies must follow the same approach)

### Key Principle:

**If a change makes the API feel less like better-auth, it is probably wrong.**

---

## Adding New Features

### To Add a New Database Feature:

1. **Add methods to `DatabaseTrait`** in `src/database/mod.rs`
2. **Implement for SQLite** in `src/database/sqlite.rs` (use `?` placeholders)
3. **Implement for Postgres** in `src/database/postgres.rs` (use `$N` placeholders)
4. **Update migrations** in both backends if schema changes needed
5. **Use in strategies** by passing `db: &dyn DatabaseTrait` as parameter

**Example:**

```rust
// 1. Add to DatabaseTrait
#[async_trait]
pub(crate) trait DatabaseTrait: Send + Sync {
    async fn create_password_reset(&self, user_id: &str, token_hash: &str) -> Result<()>;
}

// 2. Use in strategy (don't store db!)
pub struct PasswordResetStrategy;

impl PasswordResetStrategy {
    async fn create_token(
        &self,
        db: &dyn DatabaseTrait,  // ✅ Passed as parameter
        user_id: &str,
    ) -> Result<String> {
        let token = generate_token();
        db.create_password_reset(user_id, &hash_token(&token)).await?;
        Ok(token)
    }
}
```

### For Detailed Instructions:

See **[docs/DATABASE_ARCHITECTURE.md](docs/DATABASE_ARCHITECTURE.md)** for comprehensive guidance on:

- Database architecture details
- Step-by-step feature addition guide
- Common patterns and best practices
- SQL dialect differences (SQLite vs Postgres)
- Testing strategies

---

## Internal Documentation

- 📚 **[docs/DATABASE_ARCHITECTURE.md]docs/DATABASE_ARCHITECTURE.md** - Detailed database architecture and how to add features
- 📋 **[README.md]README.md** - Public-facing documentation and API reference

---

## License

This project is dual-licensed under your choice of:

- MIT License ([LICENSE-MIT]LICENSE-MIT)
- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

---

**Remember:** AuthKit's strength comes from its simplicity and consistency.  
Every feature should enhance, not complicate, the developer experience.