Skip to main content

fastauth_core/
compat.rs

1//! Better Auth database compatibility: run fastauth next to a Better Auth app on one
2//! database during a migration. Everything here is opt-in; without it fastauth behaves as it
3//! always has.
4//!
5//! - [`CookieSigning::BetterAuth`]: session cookies in Better Auth's format, so each app
6//!   accepts the other's cookies.
7//! - [`BetterAuthScrypt`]: Better Auth's password hashes, verified and written.
8//! - [`SlidingRefresh::ExpiresAt`]: Better Auth's rule for extending a session.
9//! - [`BetterAuthCompat`]: all of the above with Better Auth's numbers, set with
10//!   `FastAuth::builder().better_auth_compat(..)`.
11//!
12//! Each relaxes a fastauth default on purpose, for the migration window only:
13//! `docs/integrations/04-migrating-from-better-auth.md` lists the trade-offs.
14
15use std::borrow::Cow;
16
17use base64::Engine as _;
18use base64::engine::DecodePaddingMode;
19use base64::engine::general_purpose::{GeneralPurpose, GeneralPurposeConfig, STANDARD};
20use hmac::{Hmac, KeyInit, Mac};
21use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
22use sha2::Sha256;
23use time::Duration;
24use unicode_normalization::UnicodeNormalization;
25use zeroize::Zeroizing;
26
27use crate::config::{
28    CookieConfig, CookieSigning, EmailPassword, SessionConfig, SessionTokens, SlidingRefresh,
29};
30use crate::crypto::{PasswordHasher, Secret, ct_eq, random_bytes};
31use crate::error::BuildError;
32use crate::migrate::Migrations;
33use crate::schema::{ColumnNaming, Storage};
34
35/// What `encodeURIComponent` leaves alone: letters, digits and `-_.!~*'()`.
36const URI_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
37    .remove(b'-')
38    .remove(b'_')
39    .remove(b'.')
40    .remove(b'!')
41    .remove(b'~')
42    .remove(b'*')
43    .remove(b'\'')
44    .remove(b'(')
45    .remove(b')');
46
47/// Standard base64 decoded like the browser's `atob`, which ignores bits past the last byte.
48const ATOB: GeneralPurpose = GeneralPurpose::new(
49    &base64::alphabet::STANDARD,
50    GeneralPurposeConfig::new()
51        .with_decode_allow_trailing_bits(true)
52        .with_decode_padding_mode(DecodePaddingMode::Indifferent),
53);
54
55fn mac(secret: &[u8], value: &str) -> Hmac<Sha256> {
56    let mut mac =
57        <Hmac<Sha256> as KeyInit>::new_from_slice(secret).expect("HMAC takes any key length");
58    mac.update(value.as_bytes());
59    mac
60}
61
62/// better-call's `signCookieValue`: `encodeURIComponent(value + "." + base64(HMAC-SHA256))`,
63/// the HMAC keyed with the secret's bytes as they are and the signature in padded standard
64/// base64.
65pub(crate) fn sign_cookie(secret: &[u8], value: &str) -> String {
66    let tag = mac(secret, value).finalize().into_bytes();
67    let signed = format!("{value}.{}", STANDARD.encode(tag));
68    utf8_percent_encode(&signed, URI_COMPONENT).to_string()
69}
70
71/// better-call's `getSignedCookie` on a value [`decode_cookie`] already decoded: the value
72/// before the last `.`, when it isn't empty, the signature after it is 44 characters ending in
73/// `=`, and the HMAC matches (compared in constant time).
74pub(crate) fn verify_cookie<'a>(secret: &[u8], signed: &'a str) -> Option<&'a str> {
75    let (value, signature) = signed.rsplit_once('.')?;
76    if value.is_empty() || signature.len() != 44 || !signature.ends_with('=') {
77        return None;
78    }
79    let signature = ATOB.decode(signature).ok()?;
80    mac(secret, value).verify_slice(&signature).ok()?;
81    Some(value)
82}
83
84/// better-call's cookie parser decodes every value holding a `%` with
85/// `decodeURIComponent`, and keeps it as it came when that fails (a `%` without two hex
86/// digits after it, or bytes that aren't UTF-8). Values without a `%` are used as they are,
87/// so an unencoded signed value verifies too.
88///
89/// Like better-call's parser, surrounding whitespace is trimmed and one pair of quotes removed
90/// first.
91pub(crate) fn decode_cookie(raw: &str) -> Cow<'_, str> {
92    let raw = raw.trim();
93    let raw = match raw.strip_prefix('"') {
94        Some(rest) => {
95            let mut chars = rest.chars();
96            chars.next_back();
97            chars.as_str()
98        }
99        None => raw,
100    };
101    if !raw.contains('%') {
102        return Cow::Borrowed(raw);
103    }
104    let bytes = raw.as_bytes();
105    let escapes_ok = bytes.iter().enumerate().all(|(i, byte)| {
106        *byte != b'%'
107            || bytes
108                .get(i + 1..i + 3)
109                .is_some_and(|hex| hex.iter().all(u8::is_ascii_hexdigit))
110    });
111    if !escapes_ok {
112        return Cow::Borrowed(raw);
113    }
114    match percent_encoding::percent_decode_str(raw).decode_utf8() {
115        Ok(decoded) => Cow::Owned(decoded.into_owned()),
116        Err(_) => Cow::Borrowed(raw),
117    }
118}
119
120/// Better Auth's password hashes, as `@better-auth/utils/password` writes them:
121/// `"<salt>:<key>"`, where the salt is 16 random bytes in lowercase hex and the key is
122/// scrypt (N = 16384, r = 16, p = 1, 64 bytes) of the NFKC-normalized password, salted with
123/// the salt's hex string as UTF-8 (not the 16 bytes it encodes), in lowercase hex.
124///
125/// New hashes are written in the same format and [`PasswordHasher::needs_rehash`] is always
126/// false, so a Better Auth app on the same database keeps verifying every password, and
127/// rolling back to it loses nobody.
128///
129/// Each hash takes [`BetterAuthScrypt::MEMORY_BYTES`] (32 MiB), against argon2id's 19 MiB,
130/// so cap how many run at once with `EmailPassword::max_concurrent_hashes`;
131/// [`BetterAuthCompat`] does. It's weaker than fastauth's default argon2id: use it only
132/// while a Better Auth app shares the database.
133#[derive(Clone, Copy, Debug, Default)]
134pub struct BetterAuthScrypt;
135
136impl BetterAuthScrypt {
137    /// scrypt's working memory per hash: 128 · N · r bytes, 32 MiB.
138    pub const MEMORY_BYTES: usize = 128 * 16384 * 16;
139
140    fn key(password: &str, salt: &str) -> Zeroizing<[u8; 64]> {
141        let password: Zeroizing<String> = Zeroizing::new(password.nfkc().collect());
142        let params = scrypt::Params::new(14, 16, 1).expect("valid scrypt parameters");
143        let mut key = Zeroizing::new([0u8; 64]);
144        scrypt::scrypt(password.as_bytes(), salt.as_bytes(), &params, key.as_mut())
145            .expect("64 bytes is a valid scrypt output length");
146        key
147    }
148
149    /// The hash of `password` with this salt. Better Auth's salts are 32 lowercase hex
150    /// characters; [`PasswordHasher::hash`] makes a random one.
151    pub fn hash_with_salt(password: &str, salt: &str) -> String {
152        format!("{salt}:{}", hex(Self::key(password, salt).as_ref()))
153    }
154}
155
156fn hex(bytes: &[u8]) -> String {
157    const DIGITS: &[u8; 16] = b"0123456789abcdef";
158    bytes
159        .iter()
160        .flat_map(|b| [DIGITS[usize::from(b >> 4)], DIGITS[usize::from(b & 15)]])
161        .map(char::from)
162        .collect()
163}
164
165impl PasswordHasher for BetterAuthScrypt {
166    fn hash(&self, password: &str) -> Result<String, String> {
167        Ok(Self::hash_with_salt(password, &hex(&random_bytes::<16>())))
168    }
169
170    /// Like Better Auth: the first two `:`-separated parts are the salt and the key, and the
171    /// key must equal the lowercase hex of the derived key. A hash without both parts is an
172    /// error, as it is in Better Auth.
173    fn verify(&self, password: &str, hash: &str) -> Result<bool, String> {
174        let mut parts = hash.split(':');
175        let (Some(salt), Some(key)) = (
176            parts.next().filter(|s| !s.is_empty()),
177            parts.next().filter(|k| !k.is_empty()),
178        ) else {
179            return Err("not a Better Auth password hash (\"<salt>:<key>\")".into());
180        };
181        let derived = Zeroizing::new(hex(Self::key(password, salt).as_ref()));
182        Ok(ct_eq(derived.as_bytes(), key.as_bytes()))
183    }
184}
185
186/// Runs fastauth on a database a Better Auth app also uses, and lets the two share sign-ins:
187/// `FastAuth::builder().better_auth_compat(BetterAuthCompat::new(secret).cookie_prefix("vt"))`.
188///
189/// Applied at `.build()`, where it overrides the matching settings:
190///
191/// - cookies are named `{prefix}.session_token` (`__Secure-` in front on https) and signed in
192///   Better Auth's format with the raw secret ([`CookieSigning::BetterAuth`]);
193/// - sessions last [`BetterAuthCompat::expires_in`] (14 days unless set) and are extended
194///   once [`BetterAuthCompat::update_age`] (one day) has passed since their last extension,
195///   by Better Auth's rule ([`SlidingRefresh::ExpiresAt`]);
196/// - passwords use [`BetterAuthScrypt`], at most
197///   [`BetterAuthCompat::max_concurrent_hashes`] at a time;
198/// - columns are stored in Better Auth's names: [`ColumnNaming::CamelCase`], the password
199///   hash in `account.password`, and the OAuth tokens as hex in its text columns. The
200///   tokens stay encrypted: storing them as plain text, as Better Auth does, is a separate
201///   choice (`Builder::store_oauth_tokens_in_plaintext`) the preset never makes;
202/// - sessions are stored with their raw token ([`SessionTokens::Raw`]), so each app resolves
203///   the other's sessions;
204/// - fastauth leaves `account` rows of providers it doesn't own alone
205///   (`Builder::only_owned_accounts`);
206/// - the migrator is review-only ([`Migrations::ReviewOnly`]): `fastauth generate` writes the
207///   SQL to review, `fastauth migrate` refuses.
208///
209/// fastauth's verification rows don't fit Better Auth's `verification` table, so give them
210/// their own on the adapter: `Sqlx::new(pool).rename("verification", "fastauth_verification")`.
211///
212/// The cookie cache can't be used with it: `.build()` refuses `SessionConfig::cookie_cache`.
213/// fastauth's own `.secret(..)` is still needed; it keys everything that isn't a cookie
214/// (encrypted columns, plugin keys, rate-limit buckets).
215#[derive(Clone, Debug)]
216pub struct BetterAuthCompat {
217    secret: Secret,
218    cookie_prefix: String,
219    expires_in: Duration,
220    update_age: Duration,
221    max_concurrent_hashes: usize,
222}
223
224impl BetterAuthCompat {
225    /// The Better Auth app's secret (`BETTER_AUTH_SECRET`), as the app has it: its UTF-8 bytes
226    /// key the cookie HMAC, with no decoding and no key derivation.
227    pub fn new(secret: impl Into<Vec<u8>>) -> Self {
228        Self {
229            secret: Secret::from_bytes(secret),
230            cookie_prefix: "better-auth".into(),
231            expires_in: Duration::days(14),
232            update_age: Duration::days(1),
233            max_concurrent_hashes: 8,
234        }
235    }
236
237    /// [`BetterAuthCompat::new`] with the value of an environment variable, read as it is.
238    /// Unlike `Secret::from_env`, a value that happens to be valid base64 isn't decoded.
239    pub fn from_env(var: &str) -> Result<Self, BuildError> {
240        let value = std::env::var(var)
241            .map_err(|_| BuildError::new(format!("environment variable `{var}` is not set")))?;
242        Ok(Self::new(value))
243    }
244
245    /// The Better Auth app's `advanced.cookiePrefix` (default `"better-auth"`).
246    pub fn cookie_prefix(mut self, prefix: impl Into<String>) -> Self {
247        self.cookie_prefix = prefix.into();
248        self
249    }
250
251    /// The Better Auth app's `session.expiresIn` (14 days unless set; Better Auth's own
252    /// default is 7). Both apps should use the same value, since each extends a session to
253    /// its own.
254    pub fn expires_in(mut self, d: Duration) -> Self {
255        self.expires_in = d;
256        self
257    }
258
259    /// The Better Auth app's `session.updateAge` (one day, Better Auth's default).
260    pub fn update_age(mut self, d: Duration) -> Self {
261        self.update_age = d;
262        self
263    }
264
265    /// How many scrypt hashes run at once at most (default 8, and never more than the
266    /// number of CPUs): 32 MiB each, so 256 MiB at most by default.
267    pub fn max_concurrent_hashes(mut self, n: usize) -> Self {
268        self.max_concurrent_hashes = n.max(1);
269        self
270    }
271
272    #[allow(clippy::too_many_arguments)]
273    pub(crate) fn apply(
274        self,
275        cookies: &mut CookieConfig,
276        session: &mut SessionConfig,
277        email_password: Option<&mut EmailPassword>,
278        storage: &mut Storage,
279        session_tokens: &mut SessionTokens,
280        only_owned_accounts: &mut bool,
281        migrations: &mut Migrations,
282    ) {
283        storage.naming = ColumnNaming::CamelCase;
284        storage
285            .renames
286            .push(("account".into(), "password_hash".into(), "password".into()));
287        storage
288            .hex_text
289            .push(("account".into(), "access_token".into()));
290        storage
291            .hex_text
292            .push(("account".into(), "refresh_token".into()));
293        *session_tokens = SessionTokens::Raw;
294        *only_owned_accounts = true;
295        *migrations = Migrations::ReviewOnly;
296        cookies.prefix = self.cookie_prefix;
297        cookies.signing = CookieSigning::BetterAuth(self.secret);
298        session.expires_in = self.expires_in;
299        session.update_age = self.update_age;
300        session.sliding = SlidingRefresh::ExpiresAt;
301        if let Some(email_password) = email_password {
302            let cpus = std::thread::available_parallelism().map_or(2, |n| n.get());
303            email_password.hasher = std::sync::Arc::new(BetterAuthScrypt);
304            email_password.max_concurrent_hashes = Some(self.max_concurrent_hashes.min(cpus));
305        }
306    }
307}
308
309#[cfg(test)]
310mod vectors;
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    #[test]
317    fn signs_like_better_call() {
318        let signed = sign_cookie(b"secret", "a b");
319        assert!(signed.starts_with("a%20b."), "{signed}");
320        assert!(signed.ends_with("%3D"), "{signed}");
321        let decoded = decode_cookie(&signed);
322        assert_eq!(verify_cookie(b"secret", &decoded), Some("a b"));
323        assert_eq!(verify_cookie(b"other", &decoded), None);
324    }
325
326    #[test]
327    fn decodes_like_try_decode() {
328        assert_eq!(decode_cookie("abc"), "abc");
329        assert_eq!(decode_cookie("a%3Db"), "a=b");
330        assert_eq!(decode_cookie("a%zz"), "a%zz");
331        assert_eq!(decode_cookie("a%2"), "a%2");
332        assert_eq!(decode_cookie("%FF"), "%FF");
333        assert_eq!(decode_cookie("%C3%A6"), "æ");
334    }
335
336    #[test]
337    fn rejects_malformed_signatures() {
338        let signed = decode_cookie(&sign_cookie(b"k", "tok")).into_owned();
339        let (value, sig) = signed.rsplit_once('.').unwrap();
340        assert_eq!(verify_cookie(b"k", &format!(".{sig}")), None);
341        assert_eq!(verify_cookie(b"k", value), None);
342        let url_safe = sig.replace('+', "-").replace('/', "_");
343        if url_safe != sig {
344            assert_eq!(verify_cookie(b"k", &format!("{value}.{url_safe}")), None);
345        }
346        assert_eq!(
347            verify_cookie(b"k", &format!("{value}.{}", sig.trim_end_matches('='))),
348            None
349        );
350    }
351
352    #[test]
353    fn scrypt_round_trips_and_normalizes() {
354        let hasher = BetterAuthScrypt;
355        let hash = hasher.hash("\u{fb01}sh").unwrap();
356        let (salt, key) = hash.split_once(':').unwrap();
357        assert_eq!(salt.len(), 32);
358        assert_eq!(key.len(), 128);
359        assert!(hasher.verify("fish", &hash).unwrap());
360        assert!(!hasher.verify("fis", &hash).unwrap());
361        assert!(!hasher.needs_rehash(&hash));
362        assert!(hasher.verify("x", "nocolon").is_err());
363        assert!(hasher.verify("x", ":key").is_err());
364    }
365}