Overview
bun-smtp supports four SASL authentication methods: PLAIN, LOGIN, CRAM-MD5, and XOAUTH2. You can control which methods are available and enforce authentication requirements through configuration options.Configuration Options
Control authentication behavior with these options:By default,
allowInsecureAuth is false, meaning clients must complete STARTTLS before authenticating. This prevents credentials from being transmitted over unencrypted connections.Options Reference
The onAuth Callback
TheonAuth callback is invoked for every authentication attempt. Call callback(null, { user }) to accept or callback(new Error("reason")) to reject.
PLAIN and LOGIN
Both PLAIN and LOGIN methods deliver credentials in the same format. The only difference is the wire protocol — both provideusername and password fields.
1
Configure the server
Enable PLAIN and LOGIN in your server configuration:
2
Implement the onAuth handler
Check the credentials and call the callback:
3
Handle the user object
The
user object you pass is available on session.user for all subsequent callbacks:Auth Object Fields (PLAIN/LOGIN)
CRAM-MD5
CRAM-MD5 provides challenge-response authentication without transmitting the password. The server sends a challenge, and the client responds with an HMAC-MD5 digest.CRAM-MD5 requires you to have access to the plaintext password (or a reversibly encrypted version) to verify the response. If you only store password hashes, CRAM-MD5 won’t work.
Auth Object Fields (CRAM-MD5)
How CRAM-MD5 validation works
How CRAM-MD5 validation works
The
validatePassword() method computes HMAC-MD5 of the challenge using the provided password and compares it to the client’s response:src/auth.ts
XOAUTH2
XOAUTH2 is used for OAuth2 bearer token authentication, commonly used with services like Gmail and Office 365.Auth Object Fields (XOAUTH2)
Storing the Authenticated User
Whatever you pass asuser in the success response is stored on session.user for the rest of the connection. You can pass any value — a string, number, or object:
- String
- Object
Custom Error Messages
You can customize error responses by settingresponseCode on the error object:
Security Best Practices
1
Require TLS
Always keep
allowInsecureAuth: false in production to prevent credential theft.2
Rate limit authentication attempts
Track failed attempts per IP address and implement exponential backoff:
3
Use secure password storage
Never store plaintext passwords. Use bcrypt, scrypt, or Argon2 for password hashing.
Multiple Authentication Methods
You can support multiple methods simultaneously. Use theauth.method field to determine which method the client used: