1use 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
35const 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
47const 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
62pub(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
71pub(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
84pub(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#[derive(Clone, Copy, Debug, Default)]
134pub struct BetterAuthScrypt;
135
136impl BetterAuthScrypt {
137 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(), ¶ms, key.as_mut())
145 .expect("64 bytes is a valid scrypt output length");
146 key
147 }
148
149 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 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#[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 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 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 pub fn cookie_prefix(mut self, prefix: impl Into<String>) -> Self {
247 self.cookie_prefix = prefix.into();
248 self
249 }
250
251 pub fn expires_in(mut self, d: Duration) -> Self {
255 self.expires_in = d;
256 self
257 }
258
259 pub fn update_age(mut self, d: Duration) -> Self {
261 self.update_age = d;
262 self
263 }
264
265 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}