@telamonjs/auth

The NextAuth v5 ↔ NestJS bridge. This package owns the shape of the session
token (an @auth/core JWE), not your login flow: your app's authorize()
still checks credentials. The Next side gets canonical jwt/session
callbacks, the Nest side gets a guard that decodes the same JWE and attaches a
typed AuthUser to the request, and both share revocable impersonation.
Zero runtime dependencies · dual ESM/CJS · sideEffects: false.
Install
pnpm add @telamonjs/auth @auth/core
| Peer dependency |
Range |
@auth/core |
>=0.34.0 <1 |
@nestjs/common (optional) |
^10.0.0 \|\| ^11.0.0 |
@nestjs/core (optional) |
^10.0.0 \|\| ^11.0.0 |
The Nest peers are only needed for @telamonjs/auth/nest. Set AUTH_SECRET
(or NEXTAUTH_SECRET) on both sides.
Next side: compose over the base callbacks
import NextAuth from 'next-auth'
import { createAuthCallbacks } from '@telamonjs/auth/next'
const base = createAuthCallbacks()
export const { handlers, auth } = NextAuth({
// ...providers with your own authorize()...
callbacks: {
jwt: async args => { const token = await base.jwt(args); /* extend */ return token },
session: base.session,
},
})
The session carries SessionClaims: id, email, role, roles[],
permissions[] and accessToken, the same claims the Nest guard reads.
Nest side: one line
import { createJwtAuthGuard, Public } from '@telamonjs/auth/nest'
export const JwtAuthGuard = createJwtAuthGuard()
The guard reads the token from Authorization: Bearer, then ?token= (for
EventSource/SSE, which can't send headers), then the NextAuth cookies. Cookie
decoding is salt-aware (__Secure- names under HTTPS) and reassembles chunked
cookies. While a __Secure- cookie is present, the plain one is never read; an
HTTPS-only API passes cookieNames: ['__Secure-authjs.session-token'] so it is
never read at all. Opt a route out with @Public(). A Bearer that fails to
decode falls through to ?token= and the cookies; bearerFallthrough: false
makes it a hard 401.
A token in the URL ends up in access logs, proxies and Referer headers, so
read ?token= only on SSE requests (Accept: text/event-stream, which
EventSource always sends):
import { createJwtAuthGuard, sseOnlyQueryToken } from '@telamonjs/auth/nest'
export const JwtAuthGuard = createJwtAuthGuard({ allowQueryToken: sseOnlyQueryToken })
The default still reads it on every request (no breaking change), but the
guard logs a one-time warning the first time a ?token= authenticates a
request that is not SSE.
The guard is built when its module is imported, before Nest DI and env
loading. To read the secret late, pass a function (sync or async), called on
every request; undefined falls back to the env vars:
createJwtAuthGuard({ secret: () => process.env.AUTH_SECRET })
With no secret at all (option and env vars empty), every request that needs a
session fails with a configuration error, a 500 logged once, instead of a 401:
a missing secret is a deployment error, not a bad token.
While the package is linked (link:/file:), its @nestjs/common is not the
host's, and the host's filters turn the guard's 401 into a 500. Pass
createException so the guard throws the host's class (same signature as the
option of createPermissionsGuard):
import { ForbiddenException, UnauthorizedException } from '@nestjs/common'
const createException = (status: 401 | 403, message: string) =>
status === 401 ? new UnauthorizedException(message) : new ForbiddenException(message)
createJwtAuthGuard({ createException })
The 401 texts are English. Replace any of them with messages (a key left out
keeps its default; createException receives the replaced text):
createJwtAuthGuard({
messages: {
invalidToken: 'Token inválido ou expirado', // 'Invalid or expired token'
sessionInvalid: 'Sessão não é mais válida', // 'Session is no longer valid'
impersonationInactive: 'Personificação encerrada', // 'Impersonation session is no longer active'
},
})
Impersonation
import { createImpersonationToken } from '@telamonjs/auth'
const token = await createImpersonationToken({ target, actor, logId: log.id })
The impersonation token is the API credential: the callbacks swap
accessToken too, so impersonation is not cosmetic. Wire the cookies through
createAuthCallbacks({ getImpersonationCookies, clearImpersonationCookies }).
The cookie only applies to the session of the actor who started it (the
token's originalUserId), so another user signing in on the same browser
keeps their own identity. For immediate revocation, pass isImpersonationActive to the guard; tokens
without a logId are then rejected. Without the hook an impersonation token
stays valid until it expires, and the guard logs a one-time warning (Nest
Logger) the first time it accepts one:
createJwtAuthGuard({
isImpersonationActive: async logId =>
!!(await prisma.impersonationLog.findFirst({ where: { id: logId, endedAt: null } })),
})
ImpersonationBanner and ImpersonationDialog in @telamonjs/ui are the UI side.
Session freshness & revocation
Permissions live in the token, so DB changes apply at the next login. To
apply them sooner, or to revoke every session of a user, the jwt callback
stamps authTime/accessAt at login and sessionState(token, marks) compares
them with two per-user timestamps your app keeps:
import { sessionState } from '@telamonjs/auth'
sessionState(payload, { revokedAt: user.sessionsRevokedAt, accessChangedAt: user.accessChangedAt })
// → 'revoked' | 'stale' | 'fresh'
stampSessionTimes(token, now?) sets both claims to the same instant (it
mutates and returns token). encodeSessionToken stamps a payload that has no
authTime on its own, so tokens issued on the API (server-side login,
impersonation) are compared correctly too.
Refreshing a stale token: recompute roles/permissions and set only
token.accessAt = Date.now(). Never call stampSessionTimes again there: it
also moves authTime forward, which would resurrect a revoked session.
On the Nest side, subclass the guard (createJwtAuthGuard() returns a subclass
of JwtAuthGuardBase, exported for apps built with declaration: true) and
override resolveUser (its return becomes request.user, null is a 401);
overriding allowQueryToken replaces the option of the same name. Full recipe
on the docs site.
For yes/no checks on a user that comes from the token (still active, not
suspended, session not ended), override validateUser instead: it runs after
resolveUser and its verdict can be cached per session token, so the
database is not hit on every request:
@Injectable()
export class JwtAuthGuard extends createJwtAuthGuard({ validateUserCacheTtlMs: 30_000 }) {
constructor(reflector: Reflector, private readonly users: UsersService) {
super(reflector)
}
protected override async validateUser(user: AuthUser) {
return (await this.users.isActive(user.id)) || 'user inactive'
}
}
true passes; false or a reason string is a 401 with a generic message, the
reason going to the Nest Logger. A thrown error propagates (a 5xx), like
resolveUser's, so a database outage doesn't sign users out. The cache is in
memory, per process, bounded to 1000 tokens, and never keeps a thrown error.
The cache is keyed by a hash of the session token and indexed by user, so
JwtAuthGuard.invalidateUser(userId) (a static of the guard class) drops every
cached verdict of that user, including the impersonations they started. Call it
from the flows that deactivate a user or end their sessions. On several
replicas, pass a shared store so the call reaches all of them: an object with
get(key), set(key, value, ttlMs, userIds) and deleteUser(userId), string
values with a millisecond TTL, the shape of a Redis client:
import Redis from 'ioredis'
import { createJwtAuthGuard, type ValidateUserCacheStore } from '@telamonjs/auth/nest'
const redis = new Redis(process.env.REDIS_URL!)
const validateUserCache: ValidateUserCacheStore = {
get: (key) => redis.get(`authz:${key}`),
set: (key, value, ttlMs, userIds) => {
const tx = redis.multi().set(`authz:${key}`, value, 'PX', ttlMs)
for (const id of userIds) tx.sadd(`authz:user:${id}`, key).pexpire(`authz:user:${id}`, ttlMs)
return tx.exec()
},
deleteUser: async (userId) => {
const keys = await redis.smembers(`authz:user:${userId}`)
await redis.del(`authz:user:${userId}`, ...keys.map((key) => `authz:${key}`))
},
}
export class JwtAuthGuard extends createJwtAuthGuard({
validateUserCacheTtlMs: 300_000,
validateUserCache,
}) { /* validateUser as above */ }
// users.service.ts, after setting active = false
await JwtAuthGuard.invalidateUser(user.id)
A store error is logged and treated as a miss (validateUser runs), so a
Redis outage costs database checks, never logins. Without a shared store the
TTL is the bound: each replica forgets a verdict at most that long after it
was cached.
Service-to-service (API keys)
Jobs, CI and other APIs call with a key instead of a session. A route that
only takes a key:
import { createApiKeyGuard, staticApiKey, Public } 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() @UseGuards(InternalKeyGuard) @Post('emit') emit() {}
verify(key, request) returns a principal, or null (any falsy value) to
reject (sync or async, so a database lookup fits too). The principal goes to request.servicePrincipal;
request.user is left alone. Anything else is a generic 401 'Invalid or
missing API key' (createException applies; messages: { invalidKey: '…' }
replaces the text); the guard logs nothing, and a thrown verifier error
propagates. staticApiKey compares sha256 digests with timingSafeEqual and
rejects everything while the expected key is unset: a missing env var is that
same 401, on purpose (fail closed), not a 500.
A route that takes a session or a key: give the session guard apiKey and
mark the route.
import { AllowServiceToken } from '@telamonjs/auth/nest'
export const JwtAuthGuard = createJwtAuthGuard({
apiKey: { verify: staticApiKey(() => process.env.INTERNAL_API_KEY) },
})
@AllowServiceToken() @Post('send') send() {}
A valid key passes; anything else falls through to the session check.
Unmarked routes never read the key.
Keys stored in the database: generateApiKey(prefix?) (32 random bytes,
base64url) and await hashApiKey(key) (hex sha256) from the core entry. Store
the hash, show the key once, look it up by hashApiKey(key) in verify.
Scopes, rotation and audit logging stay in your app.
Core (isomorphic)
encodeSessionToken(payload, config?) // JwtPayload → JWE string
decodeSessionToken(token, config?) // → JwtPayload | null (invalid or expired)
payloadToAuthUser(payload) // claims → typed AuthUser
generateApiKey(prefix?) // random URL-safe API key
hashApiKey(key) // → Promise<hex sha256>, to store
TokenConfig is { secret?, salt?, maxAge? }. Defaults: salt
'authjs.session-token' (DEFAULT_SALT), maxAge 24 h (DEFAULT_MAX_AGE),
impersonation 1 h (DEFAULT_IMPERSONATION_MAX_AGE). Those maxAge defaults
set the lifetime of the tokens you encode. On the decoding side
(decodeSessionToken, the guard, createAuthCallbacks({ tokenConfig })) a
maxAge you pass also rejects a token issued longer ago than that; without
one, the token's own exp is the only limit.
AuthUser structurally satisfies UserWithPermissions from
@telamonjs/permissions,
with no dependency between the packages. Order the guards as
@UseGuards(JwtAuthGuard, PermissionsGuard).
Entry points
@telamonjs/auth
@telamonjs/auth/nest
@telamonjs/auth/next
Every name each entry point exports, runtime and types: Public API index.
Full docs
Full docs → the auth page of the docs site
(MDX sources, readable on GitHub).