Skip to main content

MastraAuthNeon and MastraRBACNeon

MastraAuthNeon connects Mastra authentication to Neon Auth. It authenticates JWT bearer tokens with Neon Auth's JWKS endpoint and falls back to validating 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.

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 your Neon Auth service URL. You can also pass baseUrl directly to both constructors.

MastraAuthNeon
Direct link to mastraauthneon

Constructor parameters
Direct link to Constructor parameters

The MastraAuthNeon constructor accepts an optional MastraAuthNeonOptions object.

baseUrl?:

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

jwksUrl?:

string
JWKS endpoint used to verify bearer tokens. Falls back to NEON_AUTH_JWKS_URL, then <baseUrl>/auth/jwks.

sessionCookieName?:

string
Name of the Neon Auth session cookie. Defaults to neonauth.session_token.

signUpEnabled?:

boolean
Whether credentials-based sign-up is enabled. 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 the token as a JWT with the configured JWKS endpoint. If JWT verification fails, the provider validates it as a Neon Auth session token through the session API. Returns the authenticated NeonAuthUser, or null when neither method succeeds.

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, optional token, and response cookies.

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 authenticated user, optional token, and response cookies.

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

await auth.destroySession(sessionId)

Completes without a remote request. Neon Auth handles session destruction through its sign-out endpoint, while getClearSessionHeaders() returns the headers used to clear local session cookies.

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 service URL. Falls back to the NEON_AUTH_BASE_URL environment variable. Trailing slashes are removed.

organizationId?:

string
Restricts membership lookup to one Neon Auth organization.

getUserRoles?:

(user: EEUser) => Promise<string[]> | string[]
Custom function for extracting role names. When omitted, the provider fetches organization memberships from Neon Auth.

cache?:

{ ttlMs?: number; maxSize?: number }
Role lookup cache configuration. The defaults are 30,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, the user's JWT role claim, or Neon Auth organization memberships. When organizationId is set, only memberships for that organization are considered.

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.