Auth
Auth bridge NextAuth v5 ↔ NestJS — shared session-token contract, Nest guard, Next callbacks
@telamonjs/auth (current version: 1.4.0) is the
auth bridge between a Next.js app using NextAuth v5 and a NestJS API. Both
sides share one session token: the app issues it at login, the API decodes it
per request — no second login, no token exchange.
The package owns the token contract, not the login flow:
- Isomorphic core — the
JwtPayload/AuthUsertypes plusencodeSessionToken/decodeSessionToken/payloadToAuthUser,createImpersonationTokenand the session-freshness helpersstampSessionTimes/sessionState, andgenerateApiKey/hashApiKey /nextsubpath —createAuthCallbacks()with the canonical claim-copy for the NextAuthjwt/sessioncallbacks/nestsubpath —createJwtAuthGuard(), the@Public()decorator and the API-key guard for service-to-service calls
pnpm add @telamonjs/authShips dual ESM+CJS builds (NestJS apps on CJS work out of the box). Peer:
@auth/core; the /nest subpath additionally expects @nestjs/common and
@nestjs/core.
Token Architecture
The session token is the NextAuth v5 JWE produced by @auth/core/jwt —
an encrypted JWT, not a signed one. Decryption requires two inputs that MUST
be identical on both sides:
- Secret —
AUTH_SECRET(fallbackNEXTAUTH_SECRET), same value in the Next app and the Nest API. - Salt — used in the key derivation. NextAuth uses the session cookie
name as the salt, so the default is
'authjs.session-token'(v5). Apps still serving the legacy v4 cookie use'next-auth.session-token'.
import { encodeSessionToken, decodeSessionToken } from '@telamonjs/auth'
// Emit a session token outside the browser flow (server-side login, tests,
// impersonation):
const token = await encodeSessionToken(payload, { maxAge: 60 * 60 })
// Decode (returns null for invalid/expired tokens):
const payload = await decodeSessionToken(token)TokenConfig (secret, salt, maxAge) is accepted by every function and
by the Nest guard; secret defaults to the env vars, salt to the v5 default,
maxAge to 24h. The guard also accepts secret as a function resolved per
request (see Secret resolved per request).
Known trap: which salt does your project use?
Wrong salt = every token “invalid”
The salt feeds the JWE key derivation. If the app encodes with one salt and the API decodes with another, decryption fails silently and every request is a 401 — with valid cookies and the correct secret.
| Project | Cookie generation | Salt to configure |
|---|---|---|
| New apps (CLI template) | NextAuth v5 | 'authjs.session-token' (default — configure nothing) |
| Any app migrated from NextAuth v4 that kept its cookie config | Legacy v4 | 'next-auth.session-token' |
A related knob on the guard: cookieNames controls where the guard looks
for the cookie, independent of the salt. Default:
[salt, '__Secure-' + salt]. A project that decodes with one salt but serves
a differently-named cookie passes both explicitly (see below).
The payload contract
JwtPayload is the shared shape both sides agree on:
import type { JwtPayload } from '@telamonjs/auth'
interface JwtPayload {
id: string
pessoaId?: string
name?: string
email: string
role: RoleInfo // { id, name, code }
roles?: RoleInfo[] // multi-role
permissions: string[] // materialized RBAC — see the Permissions package
clienteIds?: string[] // optional data-scope claim (app domain)
sid?: string // stable per login; copied from `user.sid` by the jwt callback
authTime?: number // login time (epoch ms), stamped by the jwt callback
accessAt?: number // when role/roles/permissions were computed (epoch ms)
// NextAuth claims: sub, iat, exp, jti
// Impersonation block
impersonatedUserId?: string
originalUserId?: string
// ... originalUserName / Email / Role / Roles / Permissions
}payloadToAuthUser(payload) maps it to the AuthUser the guard attaches to
request.user, normalizing roles (falls back to [role]) and expanding the
impersonation block into isImpersonating + originalUser.
AuthUser.sessionId is sid ?? jti. NextAuth changes the jti on every cookie renewal, so return
a sid from authorize() when you need to end a specific session: it stays in the token across
renewals.
Next.js Setup
The package provides the callbacks, the app provides authorize():
how users are verified (password hash, external API, SSO) is app domain. The
contract is only that authorize() returns the canonical claims
(SessionClaims): id, email, role, roles, permissions, plus
optionals like pessoaId and accessToken.
import NextAuth from 'next-auth'
import Credentials from 'next-auth/providers/credentials'
import { createAuthCallbacks } from '@telamonjs/auth/next'
const base = createAuthCallbacks()
export const { handlers, auth, signIn, signOut } = NextAuth({
session: { strategy: 'jwt' },
providers: [
Credentials({
async authorize(credentials) {
// App domain: verify the user, then return SessionClaims
const user = await verifyLogin(credentials)
if (!user) return null
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role, // { id, name, code }
permissions: await getPermissionsForJWT(user), // materialized RBAC
}
},
}),
],
callbacks: base, // jwt + session with the canonical claim-copy
})createAuthCallbacks() returns { jwt, session }:
jwtcopies the claims fromuserinto the token on login (id, role, roles, permissions, accessToken/refreshToken) and stampsauthTime/accessAt(see Session freshness & revocation).sessionprojects the token back intosession.userand exposesisImpersonating/originalUserat the session root.
Apps with extra token logic (sliding window, impersonation cookies) compose on top instead of replacing:
const base = createAuthCallbacks()
callbacks: {
jwt: async (args) => {
const token = await base.jwt(args)
// app-specific claims here
return token
},
session: base.session,
}NestJS Setup
createJwtAuthGuard() builds the guard class; register it globally and opt
out per route with @Public():
import { createJwtAuthGuard } from '@telamonjs/auth/nest'
export const JwtAuthGuard = createJwtAuthGuard()
// Legacy v4 cookie project (see the salt table):
// export const JwtAuthGuard = createJwtAuthGuard({
// salt: 'next-auth.session-token',
// cookieNames: ['next-auth.session-token', '__Secure-next-auth.session-token'],
// })import { APP_GUARD } from '@nestjs/core'
import { JwtAuthGuard } from './common/guards/jwt-auth.guard'
@Module({
providers: [{ provide: APP_GUARD, useClass: JwtAuthGuard }],
})
export class AppModule {}import { Public } from '@telamonjs/auth/nest'
@Public() // guard lets this route through without a token
@Post('login')
login() {}Token extraction order
The guard looks for the session token in three places, in priority order:
Authorization: Bearer <token>— the API-client pattern; the Next app forwards its own session JWE as a bearer token.?token=query param — for SSE:EventSourcecannot send custom headers, so streams pass the token in the URL.- NextAuth cookies —
cookieNames(default[salt, '__Secure-' + salt]), for same-domain requests withcredentials: 'include'.
On success the guard attaches the decoded AuthUser to request.user; any
failure is a single UnauthorizedException('Invalid or expired token').
To keep session tokens out of URLs (and access logs) outside your SSE routes,
subclass the guard and override allowQueryToken(request) — request.path /
request.url are available; return false and ?token= is ignored.
Secret resolved per request
createJwtAuthGuard() runs when its module is imported, before Nest DI and
before your env is loaded. Instead of a static string, secret takes a
function (sync or async) that the guard calls on every request:
export const JwtAuthGuard = createJwtAuthGuard({
secret: () => process.env.AUTH_SECRET,
})Returning undefined falls back to AUTH_SECRET / NEXTAUTH_SECRET, as with
a static value. Subclasses inherit it unchanged.
Throwing the host's exceptions (createException)
createException?: (status: 401 | 403, message: string) => Error builds every
401 the guard throws (this guard only passes 401). Leave it out and the guard
throws UnauthorizedException from the package's @nestjs/common; set it when
the package is linked and that copy is not the host's — see
NestJS guard exceptions across package instances.
It has the same signature as the option of createPermissionsGuard, so one
function serves both guards.
Downstream, pair it with the permissions guard from
@telamonjs/permissions, which reads
request.user.permissions.
Impersonation
Impersonation is encoded in the token: when an admin impersonates a user,
the app re-issues the session token with the target user's claims plus the
original user's identity preserved in dedicated claims
(impersonatedUserId, originalUserId, originalUserName,
originalUserEmail, originalUserRole, originalUserRoles,
originalPermissions).
createImpersonationToken({ target, actor, logId })mints that token server-side:targetbecomes the subject,actorfills theoriginal*claims, andlogIdis the id of the app's audit record. It expires after 1h by default (DEFAULT_IMPERSONATION_MAX_AGE).encodeSessionTokenremains the lower-level primitive.payloadToAuthUsersurfaces it asuser.isImpersonating = trueanduser.originalUser— so API audit logs can attribute actions to the real operator while authorization applies the impersonated user's permissions.createAuthCallbacks().sessionexposes the same flags to the Next app (session.isImpersonating,session.originalUser) for the UI banner and the "stop impersonating" action.
Who may impersonate whom is app policy (typically superadmin-only, and never impersonating another superadmin) — the package only carries the state.
Session freshness & revocation
Roles and permissions live in the token, which keeps every check a lookup — but a role change in the database only reaches the token at the next login, and there is no way to end every session of a user. The package gives you the building blocks; the app keeps the state:
- The
jwtcallback stamps two claims at login:authTime(login time) andaccessAt(when roles/permissions were computed), both epoch ms.iatcan't serve: NextAuth re-signs the token on every renewal, soiatkeeps moving.encodeSessionTokenstamps both on a payload withoutauthTime, so tokens issued on the API (server-side login, impersonation) carry them too. sessionState(token, { revokedAt, accessChangedAt })compares them with two per-user marks and returns'revoked'(revocation newer than the login),'stale'(access changed after the claims were computed) or'fresh'. Revoked wins; a missing claim counts as 0, so tokens issued before you adopted this are caught by the next mark;nullmarks mean nothing changed.
Two per-user columns, stamped by the app. For example accessChangedAt
and sessionsRevokedAt on the user table. Set accessChangedAt = now() when
the user's roles change, or the permissions of a role they hold change (for
every holder of that role); set sessionsRevokedAt = now() when an admin
revokes the user's sessions (or on password change).
Nest: one lookup by primary key per request. Subclass the guard and
override resolveUser — its return value becomes request.user, null is a
401. It runs after the token is decoded and the impersonation check passed.
import { Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { payloadToAuthUser, sessionState } from '@telamonjs/auth'
import { createJwtAuthGuard, type MfJwtPayload } from '@telamonjs/auth/nest'
@Injectable()
export class JwtAuthGuard extends createJwtAuthGuard() {
constructor(
reflector: Reflector,
private readonly prisma: PrismaService
) {
super(reflector)
}
protected override async resolveUser(payload: MfJwtPayload) {
const marks = await this.prisma.user.findUnique({
where: { id: payload.id },
select: { accessChangedAt: true, sessionsRevokedAt: true },
})
if (!marks) return null
const user = payloadToAuthUser(payload)
switch (
sessionState(payload, {
revokedAt: marks.sessionsRevokedAt,
accessChangedAt: marks.accessChangedAt,
})
) {
case 'revoked':
return null
case 'stale': // recompute role/roles/permissions for this request only
return { ...user, ...(await loadAccess(this.prisma, payload.id)) }
default:
return user
}
}
}Errors thrown inside resolveUser propagate unchanged: a database outage is
a 500, not a misleading 401. With a custom user type, pass it as
createJwtAuthGuard<MyUser>() and return it from resolveUser.
The base class (JwtAuthGuardBase), the constructor type (JwtAuthGuardClass)
and RequestLike (the allowQueryToken parameter) are exported from
@telamonjs/auth/nest, so export class … extends createJwtAuthGuard() also
compiles in projects with declaration: true.
Next: refresh the token on renewal. Compose over createAuthCallbacks();
on non-login calls read the marks, sign out a revoked session by returning
null, and rewrite the claims (plus accessAt) of a stale one. auth() runs
the jwt callback on every call, so wrap the lookup in a per-request cache
such as React cache to avoid repeating it within one render.
import { cache } from 'react'
import { sessionState } from '@telamonjs/auth'
import { createAuthCallbacks } from '@telamonjs/auth/next'
const base = createAuthCallbacks()
const loadMarks = cache((userId: string) =>
prisma.user.findUnique({
where: { id: userId },
select: { accessChangedAt: true, sessionsRevokedAt: true },
})
)
callbacks: {
jwt: async args => {
const token = await base.jwt(args)
if (args.user) return token // fresh login: claims and times just stamped
const marks = await loadMarks(token.id as string)
if (!marks) return null
const state = sessionState(token, {
revokedAt: marks.sessionsRevokedAt,
accessChangedAt: marks.accessChangedAt,
})
if (state === 'revoked') return null // signs the user out
if (state === 'stale') {
// role, roles, permissions — same source as authorize()
Object.assign(token, await loadAccess(token.id as string), {
accessAt: Date.now(),
})
}
return token
},
session: base.session,
}Impersonation
While impersonating, id is the target's. Decide which user's marks apply —
typically the actor's (originalUserId) for revocation — and skip the stale
refresh: the impersonation token carries the target's claims.
Cached yes/no checks (validateUser)
resolveUser builds request.user, so it runs on every request. When the
user comes from the token and you only need a yes/no answer (user still
active, account not suspended, this session not ended), override
validateUser instead and cache its verdict with validateUserCacheTtlMs:
import { Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { createJwtAuthGuard, type AuthUser } from '@telamonjs/auth/nest'
@Injectable()
export class JwtAuthGuard extends createJwtAuthGuard({ validateUserCacheTtlMs: 30_000 }) {
constructor(
reflector: Reflector,
private readonly prisma: PrismaService
) {
super(reflector)
}
protected override async validateUser(user: AuthUser) {
// While impersonating, the actor losing access ends the session too
const ids = [user.id, user.originalUser?.id].filter((id): id is string => !!id)
const active = await this.prisma.user.count({
where: { id: { in: ids }, active: true, deletedAt: null },
})
if (active !== ids.length) return 'user inactive or deleted'
if (user.sessionId && (await this.prisma.sessionLog.count({
where: { sessionId: user.sessionId, endedAt: { not: null } },
}))) {
return 'session ended'
}
return true
}
}- It runs after
resolveUser, only when that returned a user, and receives(user, payload, context). truepasses.falseor a reason string is a 401 with the generic 'Session is no longer valid'; the reason goes to the guard's NestLogger, never to the client. A thrown error propagates (a 5xx), likeresolveUser's: a database outage must not look like an expired session and sign every user out. When the client must see a specific error (e.g. a suspended account), throw it fromresolveUser.- The cache is in memory, per process, keyed by the session token (a new
login does not inherit an old
false) and bounded to 1000 tokens. A thrown error is never cached. A database change takes up to the TTL to apply, so keep it short; with the cache on, the verdict must not depend on the request. WithoutvalidateUserCacheTtlMs, it runs on every request.
Service-to-service (API keys)
Jobs, CI pipelines, other APIs and external integrations call the API with a
key instead of a session. The /nest subpath checks the key; the core
generates and hashes it.
A route that only takes a key
createApiKeyGuard(options) builds a guard class. verify(key, request)
returns the principal the key belongs to, or null to reject; sync or async,
so a shared env secret and a database lookup both fit:
import { createApiKeyGuard, staticApiKey } from '@telamonjs/auth/nest'
export const InternalKeyGuard = createApiKeyGuard({
header: 'x-internal-token', // default 'x-api-key'
bearer: true, // also read Authorization: Bearer <key>
verify: staticApiKey(() => process.env.INTERNAL_API_TOKEN, 'jobs'),
})@Public() // skip the global session guard...
@UseGuards(InternalKeyGuard) // ...the key guard protects the route
@Post('emit')
emit(@Req() req: { servicePrincipal: ServicePrincipal }) {}- The key is read from
header(any case;falsereads none), then fromAuthorization: Bearerwhenbearer: true. A repeated header is not a key. - A valid key attaches the principal to
request.servicePrincipal;request.useris left untouched, so code that expects a user never mistakes a service for one. - Anything else is a 401 'Invalid or missing API key', built by
createExceptionwhen you pass it (same option ascreateJwtAuthGuard). The guard logs nothing, so no key reaches the logs. - A thrown verifier error propagates as-is: a database outage is not an
invalid key. To send a specific 401/403 body (e.g. a suspended client),
throw your own exception from
verify. - The guard does not read
@Public(); that is how it composes with a global session guard.
staticApiKey(expected, name = 'service') checks one shared secret: it
hashes both sides with sha256 and compares them with timingSafeEqual, so
neither the content nor the length leaks through timing, and it resolves to
{ name } (ServicePrincipal). An unset or empty expected key rejects every
request, never "open when unconfigured". Pass a function: the guard is built
at import, before your env loads, and the function is called per request.
A route that takes a session or a key
Give the session guard an apiKey option and mark the route
@AllowServiceToken():
import { createJwtAuthGuard, staticApiKey } from '@telamonjs/auth/nest'
export const JwtAuthGuard = createJwtAuthGuard({
apiKey: { verify: staticApiKey(() => process.env.INTERNAL_API_KEY) },
})import { AllowServiceToken } from '@telamonjs/auth/nest'
@AllowServiceToken() // a valid key passes; otherwise the normal session check
@Post('send')
send() {}On a marked route, a valid key passes and sets request.servicePrincipal; no
key or a rejected one falls through to the session check, so the route is
never open (unlike @Public()). Unmarked routes never read the key. With
bearer: true, a session JWE sent as Bearer simply misses the key check and
authenticates as a session.
The option lives on the session guard rather than in a second guard because a global guard is the one that has to let the key through: a second guard after it would never run for a request without a session.
A service request has no request.user, so a PermissionsGuard after the
session guard answers 401 on a route with @Permissions. When a route takes
both, decide in your own guard what a service may do (e.g. skip the
permission check when request.servicePrincipal is set).
Keys stored in the database
For many keys (one per client integration), store only a hash:
import { generateApiKey, hashApiKey } from '@telamonjs/auth'
const key = generateApiKey('svc_') // 32 random bytes, base64url, after the prefix
await prisma.integration.create({
data: { keyHash: await hashApiKey(key), keyStart: key.slice(0, 12) },
})
// show `key` once; it cannot be recoveredexport const IntegrationKeyGuard = createApiKeyGuard({
verify: async key => {
const row = await prisma.integration.findUnique({
where: { keyHash: await hashApiKey(key) },
})
return row?.active ? { clientId: row.clientId } : null
},
})hashApiKey is the hex sha256 of the key, the same digest as
createHash('sha256').update(key).digest('hex'), so hashes stored that way
keep working. A random 32-byte key needs no salt or slow hash. Both helpers use
Web Crypto, so the core entry stays isomorphic.
Scopes, rotation (several valid keys at once), rate limits and audit logging
stay in your app: put them in verify or in the principal it returns.
Troubleshooting
Every API request returns 401 with a valid session
Almost always the salt mismatch from the table above: the app encodes with
the legacy v4 salt while the guard decodes with the v5 default (or
vice-versa). Confirm which cookie name the browser actually stores and pass
that as salt (and cookieNames) to createJwtAuthGuard.
Second suspect: different AUTH_SECRET between the Next app and the API —
they must load the same value.
401 only on SSE endpoints
EventSource sends no custom headers and, cross-origin, no cookies either.
Append the session token as ?token= — extraction priority 2 exists for
exactly this.
401 only in production
Production serves the __Secure- cookie prefix over HTTPS. The default
cookieNames covers __Secure-${salt}, but if you passed custom
cookieNames remember to include both variants.
Guard works but request.user.permissions is empty
The claims were never copied into the token: authorize() didn't return
permissions, or the app replaced the callbacks instead of composing over
createAuthCallbacks(). Log the decoded payload — if permissions is missing
there, the problem is at login time, not in the guard.
500 instead of 401 in development
The package is linked instead of installed, so the guard throws an
UnauthorizedException from a second copy of @nestjs/common. Pass
createException so it throws the host's class; see
NestJS guard exceptions across package instances.
Related Links
- Permissions — the RBAC that fills
permissions[] - Admin Module Structure — where
getCurrentUser()guards Route Handlers - Troubleshooting — two copies of a peer dependency