Skip to main content

MastraAuthNeon and MastraRBACNeon

MastraAuthNeon connects Mastra authentication to Neon Auth. It verifies Neon Auth JWTs sent as bearer tokens with Neon Auth's JWKS endpoint and validates Neon Auth session cookies through its session API. The provider also supports email-and-password sign-in, sign-up, and session management.

MastraRBACNeon maps Neon Auth organization roles to Mastra permissions. Register it separately when your application uses Neon Auth organization memberships for role-based access control.

note

RBAC requires a Mastra Enterprise Edition (EE) license in production. It works without a license in development. See what requires an EE license. Contact sales for more information.

Usage
Direct link to Usage

src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra'
import { MastraAuthNeon, MastraRBACNeon } from '@mastra/auth-neon'

const auth = new MastraAuthNeon()

const rbac = new MastraRBACNeon({
roleMapping: {
admin: ['*'],
member: ['agents:read', 'workflows:read'],
_default: [],
},
})

export const mastra = new Mastra({
server: {
auth,
rbac,
},
})

Set NEON_AUTH_BASE_URL to the Neon Auth URL shown in the Neon Console, for example https://ep-example-123456.neonauth.us-east-2.aws.neon.tech/neondb/auth. You can also pass baseUrl directly to both constructors.

Visit the Neon integration guide for setup steps.

MastraAuthNeon
Direct link to mastraauthneon

Constructor parameters
Direct link to Constructor parameters

The MastraAuthNeon constructor accepts an optional MastraAuthNeonOptions object.

baseUrl?:

string
Neon Auth URL, including the database path (for example /neondb/auth). Falls back to the NEON_AUTH_BASE_URL environment variable. Trailing slashes are removed. The JWT issuer and audience must equal the origin of this URL.

jwksUrl?:

string
JWKS endpoint used to verify bearer tokens. Falls back to NEON_AUTH_JWKS_URL, then <baseUrl>/.well-known/jwks.json.

sessionCookieName?:

string
Name of the Neon Auth session cookie. Defaults to __Secure-neon-auth.session_token.

signUpEnabled?:

boolean
Whether credentials-based sign-up is enabled. When false, signUp() throws and no Neon Auth account is created. Defaults to true.

name?:

string
Provider name. Defaults to neon.

authorizeUser?:

AuthorizeUserFn<NeonAuthUser>
Custom authorization function called after authentication.

mapUserToResourceId?:

(user: NeonAuthUser) => string | undefined | null
Maps an authenticated user to a Mastra memory resource ID.

protected?:

MastraAuthConfig['protected']
Routes that require authentication.

public?:

MastraAuthConfig['public']
Routes that do not require authentication.

Environment variables
Direct link to Environment variables

NEON_AUTH_BASE_URL:

string
Default Neon Auth service URL when baseUrl is not passed to the constructor.

NEON_AUTH_JWKS_URL:

string
Default JWKS endpoint when jwksUrl is not passed to the constructor.

Authentication methods
Direct link to Authentication methods

authenticateToken()
Direct link to authenticatetoken

await auth.authenticateToken(token, request)

Verifies a JWT-shaped token against the configured JWKS endpoint, checking its signature, issuer, audience, and expiry. Otherwise, validates the Neon Auth session cookie from the request through the session API. If JWT verification fails, the session cookie is still accepted, so an expired bearer token doesn't sign out a client that also sends cookies. When the request has no session cookie, a non-JWT token is treated as the session cookie value. Returns the authenticated NeonAuthUser, or null when validation fails.

NeonAuthUser contains the top-level id, email, and name, the Neon Auth user object, and either the session (cookie authentication) or the verified jwt claims (bearer authentication).

authorizeUser()
Direct link to authorizeuser

await auth.authorizeUser(user, request)

Runs the configured custom authorization function when one is provided. Otherwise, it requires a Neon Auth user ID and rejects expired JWT payloads.

Credentials methods
Direct link to Credentials methods

signIn()
Direct link to signin

const result = await auth.signIn(email, password, request)

Authenticates email-and-password credentials through Neon Auth. Returns the authenticated user, a Neon Auth JWT as token, and the Neon Auth session cookies. Neon Auth must trust the origin of the incoming request.

signUp()
Direct link to signup

const result = await auth.signUp(email, password, name, request)

Creates a Neon Auth account using email-and-password credentials. name is optional. When omitted, the provider derives a display name from the email address. Returns the same result as signIn().

isSignUpEnabled()
Direct link to issignupenabled

const enabled = auth.isSignUpEnabled()

Returns the configured signUpEnabled value.

Session methods
Direct link to Session methods

createSession()
Direct link to createsession

const session = await auth.createSession(userId, metadata)

Creates a normalized Mastra session with a generated ID and a seven-day expiration without creating a remote Neon Auth session.

validateSession()
Direct link to validatesession

const session = await auth.validateSession(sessionId)

Validates a Neon Auth session token and returns a normalized Mastra session, or null when the session is invalid.

refreshSession()
Direct link to refreshsession

const session = await auth.refreshSession(sessionId)

Validates the session through Neon Auth. Neon Auth refreshes sessions automatically when its configured update interval is reached.

destroySession()
Direct link to destroysession

const sessionId = auth.getSessionIdFromRequest(request)
if (sessionId) await auth.destroySession(sessionId)

Pass the signed session cookie value from getSessionIdFromRequest(), not the id returned by validateSession(). destroySession() attempts to revoke that session through the Neon Auth sign-out endpoint. A network error or non-2xx response can leave the session active, and the method doesn't throw for these failures. When Mastra sends the header from getClearSessionHeaders(), it clears the matching cookie on the Mastra host, not a cookie on a separate Neon Auth host. A separate Neon Auth session can remain active after Studio sign-out.

Revoking a session doesn't invalidate an already-issued JWT. Bearer tokens that pass JWT verification can still authenticate because verification doesn't check the Neon Auth session. JWT verification doesn't require an expiration claim, so a token without one may remain usable after sign-out.

MastraRBACNeon
Direct link to mastrarbacneon

Constructor parameters
Direct link to Constructor parameters

The MastraRBACNeon constructor accepts a MastraRBACNeonOptions object.

roleMapping:

RoleMapping
Maps Neon Auth role names to Mastra permission patterns. Use _default to define permissions for unmapped roles.

baseUrl?:

string
Neon Auth URL. Falls back to the NEON_AUTH_BASE_URL environment variable. Trailing slashes are removed.

organizationId?:

string
Organization whose membership role is used. Defaults to the active organization of the session.

getUserRoles?:

(user: NeonAuthUser) => Promise<string[]> | string[]
Custom function that returns role names for a user. Use it to assign roles to bearer JWT requests, which carry no organization roles.

cache?:

{ ttlMs?: number; maxSize?: number }
Role lookup cache configuration. The defaults are 60,000 ms and 1,000 entries.

Methods
Direct link to Methods

getRoles()
Direct link to getroles

const roles = await rbac.getRoles(user)

Returns roles from the configured getUserRoles function when provided. Otherwise, when organizationId is set or the session has an active organization, returns the user's role in that organization, read from Neon Auth with the user's session cookie. Non-members get no roles. Without an organization, returns the user's Neon Auth role, such as user or admin.

Bearer JWT requests have no session, so they get no roles unless getUserRoles is provided. The JWT role claim (authenticated) is never used as a Mastra role.

hasRole()
Direct link to hasrole

const allowed = await rbac.hasRole(user, 'admin')

Checks whether the user has the requested role.

getPermissions()
Direct link to getpermissions

const permissions = await rbac.getPermissions(user)

Resolves the user's roles through roleMapping and returns Mastra permission patterns.

hasPermission()
Direct link to haspermission

const allowed = await rbac.hasPermission(user, 'agents:read')

Checks whether the resolved permissions allow the requested permission.

hasAllPermissions() and hasAnyPermission()
Direct link to hasallpermissions-and-hasanypermission

const canReadAndRun = await rbac.hasAllPermissions(user, ['agents:read', 'agents:execute'])
const canReadAnything = await rbac.hasAnyPermission(user, ['agents:read', 'workflows:read'])

Checks whether the user has all or at least one of the requested permissions.

getAvailableRoles()
Direct link to getavailableroles

const roles = await rbac.getAvailableRoles()

Returns the configured role names except _default.

getRolePermissions()
Direct link to getrolepermissions

const permissions = await rbac.getRolePermissions('member')

Resolves the permission patterns configured for a role.