Skip to main content

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

The onAuth callback is invoked for every authentication attempt. Call callback(null, { user }) to accept or callback(new Error("reason")) to reject.
The onAuth callback is required if authOptional is false. Without it, all authentication attempts will fail with a 535 error.

PLAIN and LOGIN

Both PLAIN and LOGIN methods deliver credentials in the same format. The only difference is the wire protocol — both provide username 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)

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)

When authentication fails, you can pass a data object in the response to trigger an XOAUTH2 error challenge. This allows the client to understand why authentication failed and potentially retry with a refreshed token.

Storing the Authenticated User

Whatever you pass as user 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:

Custom Error Messages

You can customize error responses by setting responseCode 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 the auth.method field to determine which method the client used: