@telamonjs/auth 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +23 -0
- package/dist/nest/index.cjs +46 -1
- package/dist/nest/index.cjs.map +1 -1
- package/dist/nest/index.d.cts +23 -0
- package/dist/nest/index.d.ts +23 -0
- package/dist/nest/index.js +46 -1
- package/dist/nest/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- b00ad5f: `createJwtAuthGuard`: a protected `validateUser(user, payload, context)` hook for
|
|
8
|
+
yes/no checks after `resolveUser` (user still active, account suspended, session
|
|
9
|
+
ended). `true` passes; `false` or a reason string is a 401 with a generic message,
|
|
10
|
+
the reason logged through the guard's Nest `Logger`; a thrown error propagates (a 5xx, like `resolveUser`), so an outage does not sign users out.
|
|
11
|
+
The new `validateUserCacheTtlMs` option caches its verdict per session token (in
|
|
12
|
+
memory, bounded to 1000 tokens, thrown errors never cached), so the check does not
|
|
13
|
+
hit the database on every request.
|
|
14
|
+
|
|
3
15
|
## 1.2.1
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -134,6 +134,29 @@ override `resolveUser` (its return becomes `request.user`, `null` is a 401);
|
|
|
134
134
|
`allowQueryToken` turns `?token=` off outside SSE routes. Full recipe on the
|
|
135
135
|
docs site.
|
|
136
136
|
|
|
137
|
+
For yes/no checks on a user that comes from the token (still active, not
|
|
138
|
+
suspended, session not ended), override `validateUser` instead: it runs after
|
|
139
|
+
`resolveUser` and its verdict can be cached per session token, so the
|
|
140
|
+
database is not hit on every request:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
@Injectable()
|
|
144
|
+
export class JwtAuthGuard extends createJwtAuthGuard({ validateUserCacheTtlMs: 30_000 }) {
|
|
145
|
+
constructor(reflector: Reflector, private readonly users: UsersService) {
|
|
146
|
+
super(reflector)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
protected override async validateUser(user: AuthUser) {
|
|
150
|
+
return (await this.users.isActive(user.id)) || 'user inactive'
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
`true` passes; `false` or a reason string is a 401 with a generic message, the
|
|
156
|
+
reason going to the Nest `Logger`. A thrown error propagates (a 5xx), like
|
|
157
|
+
`resolveUser`'s, so a database outage doesn't sign users out. The cache is in
|
|
158
|
+
memory, per process, bounded to 1000 tokens, and never keeps a thrown error.
|
|
159
|
+
|
|
137
160
|
## Core (isomorphic)
|
|
138
161
|
|
|
139
162
|
```ts
|
package/dist/nest/index.cjs
CHANGED
|
@@ -101,6 +101,7 @@ var IS_PUBLIC_KEY = "isPublic";
|
|
|
101
101
|
var Public = () => (0, import_common.SetMetadata)(IS_PUBLIC_KEY, true);
|
|
102
102
|
|
|
103
103
|
// src/nest/jwt-auth.guard.ts
|
|
104
|
+
var VALIDATE_CACHE_MAX = 1e3;
|
|
104
105
|
var JwtAuthGuardBase = class {
|
|
105
106
|
/** Overridden by the class `createJwtAuthGuard` builds (it owns the options). */
|
|
106
107
|
canActivate(_context) {
|
|
@@ -117,6 +118,22 @@ var JwtAuthGuardBase = class {
|
|
|
117
118
|
resolveUser(payload, _context) {
|
|
118
119
|
return payloadToAuthUser(payload);
|
|
119
120
|
}
|
|
121
|
+
/**
|
|
122
|
+
* Per-request yes/no check on the resolved user, called after `resolveUser`
|
|
123
|
+
* (only when it returned a user). Return `true` to pass, or `false` / a
|
|
124
|
+
* reason string to reject with a 401 'Session is no longer valid': the
|
|
125
|
+
* reason is logged (Nest `Logger`), never sent to the client. A thrown error
|
|
126
|
+
* propagates (a 5xx, never cached), like `resolveUser`'s: a database outage
|
|
127
|
+
* must not look like an expired session and sign every user out.
|
|
128
|
+
*
|
|
129
|
+
* Unlike `resolveUser`, its verdict can be cached:
|
|
130
|
+
* `validateUserCacheTtlMs` keeps it per session token. With the cache on,
|
|
131
|
+
* the verdict must depend only on the token (user/payload), not on the
|
|
132
|
+
* request. Default: `true`.
|
|
133
|
+
*/
|
|
134
|
+
validateUser(_user, _payload, _context) {
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
120
137
|
/**
|
|
121
138
|
* Whether `?token=` (SSE) is read for this request. Default: `true`.
|
|
122
139
|
* Return `false` (e.g. outside your SSE routes, by `request.path`) to keep
|
|
@@ -132,6 +149,9 @@ function createJwtAuthGuard(options) {
|
|
|
132
149
|
const headerSalts = [.../* @__PURE__ */ new Set([salt, ...cookieNames])];
|
|
133
150
|
const unauthorized = (message) => options?.createException?.(401, message) ?? new import_common2.UnauthorizedException(message);
|
|
134
151
|
let warnedIrrevocable = false;
|
|
152
|
+
const logger = new import_common2.Logger("JwtAuthGuard");
|
|
153
|
+
const cacheTtl = options?.validateUserCacheTtlMs ?? 0;
|
|
154
|
+
const verdicts = /* @__PURE__ */ new Map();
|
|
135
155
|
let JwtAuthGuard = class extends JwtAuthGuardBase {
|
|
136
156
|
reflector;
|
|
137
157
|
// Reflector is stateless; the default covers instantiation outside DI (tests, @UseGuards)
|
|
@@ -167,9 +187,21 @@ function createJwtAuthGuard(options) {
|
|
|
167
187
|
if (user == null) {
|
|
168
188
|
throw unauthorized("Session is no longer valid");
|
|
169
189
|
}
|
|
190
|
+
const verdict = await this.cachedVerdict(
|
|
191
|
+
candidate.token,
|
|
192
|
+
user,
|
|
193
|
+
payload,
|
|
194
|
+
context
|
|
195
|
+
);
|
|
196
|
+
if (verdict !== true) {
|
|
197
|
+
logger.warn(
|
|
198
|
+
`validateUser rejected user ${payload.id}: ${verdict || "returned false"}`
|
|
199
|
+
);
|
|
200
|
+
throw unauthorized("Session is no longer valid");
|
|
201
|
+
}
|
|
170
202
|
if (payload.impersonatedUserId && !options?.isImpersonationActive && !warnedIrrevocable) {
|
|
171
203
|
warnedIrrevocable = true;
|
|
172
|
-
|
|
204
|
+
logger.warn(
|
|
173
205
|
"Accepted an impersonation token without an isImpersonationActive hook: ending the impersonation cannot revoke it before it expires. Pass isImpersonationActive to createJwtAuthGuard()."
|
|
174
206
|
);
|
|
175
207
|
}
|
|
@@ -180,6 +212,19 @@ function createJwtAuthGuard(options) {
|
|
|
180
212
|
}
|
|
181
213
|
throw unauthorized("Invalid or expired token");
|
|
182
214
|
}
|
|
215
|
+
async cachedVerdict(token, user, payload, context) {
|
|
216
|
+
const hit = verdicts.get(token);
|
|
217
|
+
if (hit && hit.expiresAt > Date.now()) return hit.verdict;
|
|
218
|
+
verdicts.delete(token);
|
|
219
|
+
const verdict = await this.validateUser(user, payload, context);
|
|
220
|
+
if (cacheTtl > 0) {
|
|
221
|
+
if (verdicts.size >= VALIDATE_CACHE_MAX) {
|
|
222
|
+
verdicts.delete(verdicts.keys().next().value);
|
|
223
|
+
}
|
|
224
|
+
verdicts.set(token, { verdict, expiresAt: Date.now() + cacheTtl });
|
|
225
|
+
}
|
|
226
|
+
return verdict;
|
|
227
|
+
}
|
|
183
228
|
extractTokenCandidates(request) {
|
|
184
229
|
const candidates = [];
|
|
185
230
|
const authHeader = request.headers["authorization"];
|
package/dist/nest/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/nest/index.ts","../../src/nest/jwt-auth.guard.ts","../../src/jwt.ts","../../src/nest/public.decorator.ts"],"sourcesContent":["export {\n createJwtAuthGuard,\n JwtAuthGuardBase,\n type JwtAuthGuardClass,\n type JwtAuthGuardOptions,\n type RequestLike,\n} from './jwt-auth.guard'\nexport { Public, IS_PUBLIC_KEY } from './public.decorator'\nexport type { AuthUser, MfJwtPayload, JwtPayload, RoleInfo } from '../types'\n","import {\n Injectable,\n Logger,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common'\nimport { Reflector } from '@nestjs/core'\nimport {\n decodeSessionToken,\n payloadToAuthUser,\n DEFAULT_SALT,\n type TokenConfig,\n} from '../jwt'\nimport type { AuthUser, MfJwtPayload } from '../types'\nimport { IS_PUBLIC_KEY } from './public.decorator'\n\n/** Minimal request shape (Express/Fastify) — avoids depending on @types/express */\nexport interface RequestLike {\n headers: Record<string, string | string[] | undefined>\n query?: Record<string, unknown>\n cookies?: Record<string, string | undefined>\n user?: unknown\n path?: string\n url?: string\n}\n\nexport interface JwtAuthGuardOptions extends Omit<TokenConfig, 'secret'> {\n /**\n * The JWE secret, or a function resolved on every request (sync or async).\n * The guard class is built when its module is imported, before Nest DI and\n * env loading, so pass a function to read the value late:\n *\n * ```ts\n * createJwtAuthGuard({ secret: () => process.env.AUTH_SECRET })\n * ```\n *\n * `undefined` (static or returned) falls back to\n * `process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET`.\n */\n secret?: string | (() => string | undefined | Promise<string | undefined>)\n /**\n * Builds the 401 the guard throws. Default: Nest's `UnauthorizedException`\n * from the package's own `@nestjs/common`. While the package is linked\n * (`link:`/`file:`), that copy differs from the host's and its filters\n * (`instanceof HttpException`) turn the 401 into a 500 — pass the host's class:\n *\n * ```ts\n * import { ForbiddenException, UnauthorizedException } from '@nestjs/common'\n *\n * createJwtAuthGuard({\n * createException: (status, message) =>\n * status === 401 ? new UnauthorizedException(message) : new ForbiddenException(message),\n * })\n * ```\n *\n * Same signature as the option of `createPermissionsGuard`, so one function\n * serves both guards (this guard only ever passes 401).\n */\n createException?: (status: 401 | 403, message: string) => Error\n /**\n * Cookie names to look for the session token in.\n * Default: [salt, `__Secure-${salt}`]. Projects that decode with the v5\n * salt but still serve the legacy cookie pass ['next-auth.session-token', ...].\n */\n cookieNames?: string[]\n /**\n * Impersonation revocation. Called only when the request is an\n * impersonation one; `false` → 401. The package knows nothing about the\n * database/Redis — the app checks its log:\n *\n * ```ts\n * createJwtAuthGuard({\n * isImpersonationActive: async (logId) => !!(await prisma.impersonationLog\n * .findFirst({ where: { id: logId, endedAt: null } }))\n * })\n * ```\n *\n * With the hook configured, an impersonation token WITHOUT\n * `impersonationLogId` (issued before the contract, hence irrevocable)\n * is rejected as well. Without it, an impersonation token stays valid until\n * it expires; the guard logs a one-time warning (Nest `Logger`) the first\n * time it accepts one.\n */\n isImpersonationActive?: (\n logId: string,\n context: ExecutionContext\n ) => boolean | Promise<boolean>\n}\n\n/** Candidate token + the salts to try decoding it with. */\ninterface TokenCandidate {\n token: string\n salts: string[]\n}\n\n/**\n * What `createJwtAuthGuard` returns: subclass it to override the protected\n * hooks. Not abstract on purpose — an abstract `canActivate` would force every\n * subclass to implement it. Exported so that apps compiled with\n * `declaration: true` can `export class AppGuard extends createJwtAuthGuard()`\n * (otherwise TS4094/TS4020); instantiate it only through the factory.\n */\nexport class JwtAuthGuardBase<TUser> implements CanActivate {\n /** Overridden by the class `createJwtAuthGuard` builds (it owns the options). */\n canActivate(_context: ExecutionContext): Promise<boolean> {\n throw new Error('Build the guard with createJwtAuthGuard()')\n }\n\n /**\n * Per-request user resolution, called after the token is decoded and the\n * impersonation check passed. The return value becomes `request.user`;\n * `null` → 401 'Session is no longer valid'. Errors thrown here propagate\n * as-is (a database outage is not an \"invalid token\").\n *\n * Default: `payloadToAuthUser(payload)`. With a custom `TUser`, override it.\n */\n protected resolveUser(\n payload: MfJwtPayload,\n _context: ExecutionContext\n ): TUser | null | Promise<TUser | null> {\n // Correct for the default TUser = AuthUser; a custom TUser must override this\n return payloadToAuthUser(payload) as unknown as TUser\n }\n\n /**\n * Whether `?token=` (SSE) is read for this request. Default: `true`.\n * Return `false` (e.g. outside your SSE routes, by `request.path`) to keep\n * session tokens out of URLs and access logs.\n */\n protected allowQueryToken(_request: RequestLike): boolean {\n return true\n }\n}\n\n/** Constructor type returned by `createJwtAuthGuard` (subclassable, DI-friendly). */\nexport type JwtAuthGuardClass<TUser> = new (\n reflector?: Reflector\n) => JwtAuthGuardBase<TUser>\n\n/**\n * Creates the authentication guard: decodes the NextAuth session JWE\n * (Bearer → ?token= for SSE → cookies) and attaches `request.user` (AuthUser).\n *\n * NextAuth derives the JWE key with salt = the cookie NAME — over HTTPS\n * (useSecureCookies) the name becomes `__Secure-<salt>`, so each cookie is\n * decoded using its own name as the salt. Large cookies are chunked\n * (`name.0`, `name.1`, …) and reassembled here.\n *\n * ```ts\n * export const JwtAuthGuard = createJwtAuthGuard()\n *\n * // per-request checks (session freshness, revocation): subclass it\n * @Injectable()\n * export class AppGuard extends createJwtAuthGuard<MyUser>() {\n * constructor(reflector: Reflector, private readonly users: UsersService) {\n * super(reflector)\n * }\n * protected override async resolveUser(payload: MfJwtPayload) { ... }\n * }\n * ```\n */\nexport function createJwtAuthGuard<TUser = AuthUser>(\n options?: JwtAuthGuardOptions\n): JwtAuthGuardClass<TUser> {\n const salt = options?.salt ?? DEFAULT_SALT\n const cookieNames = options?.cookieNames ?? [salt, `__Secure-${salt}`]\n // Bearer/query arrive without a cookie name — we try every possible salt\n const headerSalts = [...new Set([salt, ...cookieNames])]\n const unauthorized = (message: string): Error =>\n options?.createException?.(401, message) ??\n new UnauthorizedException(message)\n // Once per guard class: a warning per request would flood the logs\n let warnedIrrevocable = false\n\n @Injectable()\n class JwtAuthGuard extends JwtAuthGuardBase<TUser> {\n private readonly reflector: Reflector\n\n // Reflector is stateless; the default covers instantiation outside DI (tests, @UseGuards)\n constructor(reflector?: Reflector) {\n super()\n this.reflector = reflector ?? new Reflector()\n }\n\n override async canActivate(context: ExecutionContext): Promise<boolean> {\n const isPublic = this.reflector.getAllAndOverride<boolean>(\n IS_PUBLIC_KEY,\n [context.getHandler(), context.getClass()]\n )\n if (isPublic) return true\n\n const request = context.switchToHttp().getRequest<RequestLike>()\n // Resolved here, per request: a function reads values loaded after import\n const secret =\n typeof options?.secret === 'function'\n ? await options.secret()\n : options?.secret\n\n for (const candidate of this.extractTokenCandidates(request)) {\n for (const candidateSalt of candidate.salts) {\n const payload = await decodeSessionToken(candidate.token, {\n secret,\n salt: candidateSalt,\n })\n if (payload) {\n if (payload.impersonatedUserId && options?.isImpersonationActive) {\n const active =\n !!payload.impersonationLogId &&\n (await options.isImpersonationActive(\n payload.impersonationLogId,\n context\n ))\n if (!active) {\n throw unauthorized('Impersonation session is no longer active')\n }\n }\n const user = await this.resolveUser(payload, context)\n if (user == null) {\n throw unauthorized('Session is no longer valid')\n }\n if (\n payload.impersonatedUserId &&\n !options?.isImpersonationActive &&\n !warnedIrrevocable\n ) {\n warnedIrrevocable = true\n new Logger('JwtAuthGuard').warn(\n 'Accepted an impersonation token without an isImpersonationActive hook: ' +\n 'ending the impersonation cannot revoke it before it expires. ' +\n 'Pass isImpersonationActive to createJwtAuthGuard().'\n )\n }\n request.user = user\n return true\n }\n }\n }\n\n throw unauthorized('Invalid or expired token')\n }\n\n private extractTokenCandidates(request: RequestLike): TokenCandidate[] {\n const candidates: TokenCandidate[] = []\n\n // Priority 1: Bearer token from Authorization header (API pattern)\n const authHeader = request.headers['authorization']\n if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {\n candidates.push({ token: authHeader.substring(7), salts: headerSalts })\n }\n\n // Priority 2: query param (SSE/EventSource cannot send custom headers)\n const queryToken = request.query?.['token']\n if (\n typeof queryToken === 'string' &&\n queryToken &&\n this.allowQueryToken(request)\n ) {\n candidates.push({ token: queryToken, salts: headerSalts })\n }\n\n // Priority 3: NextAuth cookies. NextAuth convention: the cookie NAME\n // is the salt (over HTTPS the name gains __Secure- and the salt\n // changes with it). Custom setups encode with one salt but serve the\n // cookie under another name — hence we try both the name AND the\n // configured salt.\n for (const name of cookieNames) {\n const token = this.readCookie(request, name)\n if (token) {\n candidates.push({ token, salts: [...new Set([name, salt])] })\n }\n }\n\n return candidates\n }\n\n /** Reads the cookie, reassembling chunks (`name.0`, `name.1`, …) if needed. */\n private readCookie(request: RequestLike, name: string): string | undefined {\n const cookies = request.cookies\n if (!cookies) return undefined\n if (cookies[name]) return cookies[name]\n\n let assembled = ''\n for (let i = 0; ; i++) {\n const chunk = cookies[`${name}.${i}`]\n if (chunk === undefined) break\n assembled += chunk\n }\n return assembled || undefined\n }\n }\n\n return JwtAuthGuard\n}\n","import { encode, decode } from '@auth/core/jwt'\nimport { stampSessionTimes } from './session'\nimport type { AuthUser, MfJwtPayload, RoleInfo } from './types'\n\nexport interface TokenConfig {\n /** Default: process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET */\n secret?: string\n /**\n * Key-derivation salt for the JWE — it MUST be identical on both sides.\n * Default: 'authjs.session-token' (NextAuth v5). Projects on the legacy\n * v4 cookie use 'next-auth.session-token'.\n */\n salt?: string\n /** Seconds. Default: 24h */\n maxAge?: number\n}\n\nexport const DEFAULT_SALT = 'authjs.session-token'\nexport const DEFAULT_MAX_AGE = 24 * 60 * 60\n\nexport function resolveTokenConfig(\n config?: TokenConfig\n): Required<TokenConfig> {\n const secret =\n config?.secret ?? process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET\n if (!secret) {\n throw new Error('AUTH_SECRET or NEXTAUTH_SECRET must be defined')\n }\n return {\n secret,\n salt: config?.salt ?? DEFAULT_SALT,\n maxAge: config?.maxAge ?? DEFAULT_MAX_AGE,\n }\n}\n\n/**\n * Issues the session JWE in the NextAuth v5 format (for server-side login on\n * the API, impersonation, etc.). Same secret+salt as the Next app.\n *\n * A payload without `authTime` is a new session: it gets `authTime`/`accessAt`\n * stamped (on a copy), so `sessionState` does not read it as issued at 0.\n */\nexport async function encodeSessionToken(\n payload: MfJwtPayload,\n config?: TokenConfig\n): Promise<string> {\n const { secret, salt, maxAge } = resolveTokenConfig(config)\n const token =\n payload.authTime == null ? stampSessionTimes({ ...payload }) : payload\n return encode({ token, secret, salt, maxAge })\n}\n\n/** Decodes the session JWE. Returns null for an invalid/expired token. */\nexport async function decodeSessionToken(\n token: string,\n config?: TokenConfig\n): Promise<MfJwtPayload | null> {\n const { secret, salt } = resolveTokenConfig(config)\n try {\n const payload = await decode({ token, secret, salt })\n return (payload as MfJwtPayload | null) ?? null\n } catch {\n return null\n }\n}\n\n/**\n * Maps the JWT payload to the request's AuthUser,\n * including the impersonation block.\n */\nexport function payloadToAuthUser(payload: MfJwtPayload): AuthUser {\n const role = payload.role as RoleInfo\n const roles = payload.roles ?? (role ? [role] : [])\n const user: AuthUser = {\n id: payload.id,\n pessoaId: payload.pessoaId ? String(payload.pessoaId) : undefined,\n name: payload.name,\n email: payload.email,\n role,\n roles,\n permissions: payload.permissions ?? [],\n sessionId: payload.sid ?? payload.jti,\n }\n\n if (payload.clienteIds) {\n user.clienteIds = payload.clienteIds\n }\n\n if (payload.impersonatedUserId) {\n const origRole = payload.originalUserRole as RoleInfo\n const origRoles = payload.originalUserRoles ?? (origRole ? [origRole] : [])\n user.isImpersonating = true\n user.impersonationLogId = payload.impersonationLogId\n user.originalUser = {\n id: payload.originalUserId as string,\n name: payload.originalUserName as string,\n email: payload.originalUserEmail as string,\n role: origRole,\n roles: origRoles,\n }\n }\n\n return user\n}\n","import { SetMetadata } from '@nestjs/common'\n\nexport const IS_PUBLIC_KEY = 'isPublic'\n\n/**\n * Marks a route/controller as public — the JwtAuthGuard allows it without a token.\n * Useful with a global guard (APP_GUARD) and per-route opt-out.\n */\nexport const Public = () => SetMetadata(IS_PUBLIC_KEY, true)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAMO;AACP,kBAA0B;;;ACP1B,iBAA+B;AAiBxB,IAAM,eAAe;AACrB,IAAM,kBAAkB,KAAK,KAAK;AAElC,SAAS,mBACd,QACuB;AACvB,QAAM,SACJ,QAAQ,UAAU,QAAQ,IAAI,eAAe,QAAQ,IAAI;AAC3D,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AACA,SAAO;AAAA,IACL;AAAA,IACA,MAAM,QAAQ,QAAQ;AAAA,IACtB,QAAQ,QAAQ,UAAU;AA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AI,YAAY;AAChB,eAAS,IAAI,KAAK,KAAK;AACrB,cAAM,QAAQ,QAAQ,GAAG,IAAI,IAAI,CAAC,EAAE;AACpC,YAAI,UAAU,OAAW;AACzB,qBAAa;AAAA,MACf;AACA,aAAO,aAAa;AAAA,IACtB;AAAA,EACF;AAlHM,iBAAN;AAAA,QADC,2BAAW;AAAA,KACN;AAoHN,SAAO;AACT;","names":["import_common"]}
|
|
1
|
+
{"version":3,"sources":["../../src/nest/index.ts","../../src/nest/jwt-auth.guard.ts","../../src/jwt.ts","../../src/nest/public.decorator.ts"],"sourcesContent":["export {\n createJwtAuthGuard,\n JwtAuthGuardBase,\n type JwtAuthGuardClass,\n type JwtAuthGuardOptions,\n type RequestLike,\n} from './jwt-auth.guard'\nexport { Public, IS_PUBLIC_KEY } from './public.decorator'\nexport type { AuthUser, MfJwtPayload, JwtPayload, RoleInfo } from '../types'\n","import {\n Injectable,\n Logger,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common'\nimport { Reflector } from '@nestjs/core'\nimport {\n decodeSessionToken,\n payloadToAuthUser,\n DEFAULT_SALT,\n type TokenConfig,\n} from '../jwt'\nimport type { AuthUser, MfJwtPayload } from '../types'\nimport { IS_PUBLIC_KEY } from './public.decorator'\n\n/** Minimal request shape (Express/Fastify) — avoids depending on @types/express */\nexport interface RequestLike {\n headers: Record<string, string | string[] | undefined>\n query?: Record<string, unknown>\n cookies?: Record<string, string | undefined>\n user?: unknown\n path?: string\n url?: string\n}\n\nexport interface JwtAuthGuardOptions extends Omit<TokenConfig, 'secret'> {\n /**\n * The JWE secret, or a function resolved on every request (sync or async).\n * The guard class is built when its module is imported, before Nest DI and\n * env loading, so pass a function to read the value late:\n *\n * ```ts\n * createJwtAuthGuard({ secret: () => process.env.AUTH_SECRET })\n * ```\n *\n * `undefined` (static or returned) falls back to\n * `process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET`.\n */\n secret?: string | (() => string | undefined | Promise<string | undefined>)\n /**\n * Builds the 401 the guard throws. Default: Nest's `UnauthorizedException`\n * from the package's own `@nestjs/common`. While the package is linked\n * (`link:`/`file:`), that copy differs from the host's and its filters\n * (`instanceof HttpException`) turn the 401 into a 500 — pass the host's class:\n *\n * ```ts\n * import { ForbiddenException, UnauthorizedException } from '@nestjs/common'\n *\n * createJwtAuthGuard({\n * createException: (status, message) =>\n * status === 401 ? new UnauthorizedException(message) : new ForbiddenException(message),\n * })\n * ```\n *\n * Same signature as the option of `createPermissionsGuard`, so one function\n * serves both guards (this guard only ever passes 401).\n */\n createException?: (status: 401 | 403, message: string) => Error\n /**\n * Cookie names to look for the session token in.\n * Default: [salt, `__Secure-${salt}`]. Projects that decode with the v5\n * salt but still serve the legacy cookie pass ['next-auth.session-token', ...].\n */\n cookieNames?: string[]\n /**\n * Impersonation revocation. Called only when the request is an\n * impersonation one; `false` → 401. The package knows nothing about the\n * database/Redis — the app checks its log:\n *\n * ```ts\n * createJwtAuthGuard({\n * isImpersonationActive: async (logId) => !!(await prisma.impersonationLog\n * .findFirst({ where: { id: logId, endedAt: null } }))\n * })\n * ```\n *\n * With the hook configured, an impersonation token WITHOUT\n * `impersonationLogId` (issued before the contract, hence irrevocable)\n * is rejected as well. Without it, an impersonation token stays valid until\n * it expires; the guard logs a one-time warning (Nest `Logger`) the first\n * time it accepts one.\n */\n isImpersonationActive?: (\n logId: string,\n context: ExecutionContext\n ) => boolean | Promise<boolean>\n /**\n * Caches the verdict of `validateUser` for this many milliseconds, per\n * session token, so a database check does not run on every request.\n * Default: no cache. The cache is in memory, per guard class (per process),\n * bounded to 1000 tokens; a thrown error is never cached. A change in the\n * database (user deactivated, sessions revoked) takes up to this long to\n * apply — keep it short (e.g. `30_000`).\n */\n validateUserCacheTtlMs?: number\n}\n\n/** Most tokens the `validateUser` cache keeps; past it, the oldest goes first. */\nconst VALIDATE_CACHE_MAX = 1000\n\n/** Candidate token + the salts to try decoding it with. */\ninterface TokenCandidate {\n token: string\n salts: string[]\n}\n\n/**\n * What `createJwtAuthGuard` returns: subclass it to override the protected\n * hooks. Not abstract on purpose — an abstract `canActivate` would force every\n * subclass to implement it. Exported so that apps compiled with\n * `declaration: true` can `export class AppGuard extends createJwtAuthGuard()`\n * (otherwise TS4094/TS4020); instantiate it only through the factory.\n */\nexport class JwtAuthGuardBase<TUser> implements CanActivate {\n /** Overridden by the class `createJwtAuthGuard` builds (it owns the options). */\n canActivate(_context: ExecutionContext): Promise<boolean> {\n throw new Error('Build the guard with createJwtAuthGuard()')\n }\n\n /**\n * Per-request user resolution, called after the token is decoded and the\n * impersonation check passed. The return value becomes `request.user`;\n * `null` → 401 'Session is no longer valid'. Errors thrown here propagate\n * as-is (a database outage is not an \"invalid token\").\n *\n * Default: `payloadToAuthUser(payload)`. With a custom `TUser`, override it.\n */\n protected resolveUser(\n payload: MfJwtPayload,\n _context: ExecutionContext\n ): TUser | null | Promise<TUser | null> {\n // Correct for the default TUser = AuthUser; a custom TUser must override this\n return payloadToAuthUser(payload) as unknown as TUser\n }\n\n /**\n * Per-request yes/no check on the resolved user, called after `resolveUser`\n * (only when it returned a user). Return `true` to pass, or `false` / a\n * reason string to reject with a 401 'Session is no longer valid': the\n * reason is logged (Nest `Logger`), never sent to the client. A thrown error\n * propagates (a 5xx, never cached), like `resolveUser`'s: a database outage\n * must not look like an expired session and sign every user out.\n *\n * Unlike `resolveUser`, its verdict can be cached:\n * `validateUserCacheTtlMs` keeps it per session token. With the cache on,\n * the verdict must depend only on the token (user/payload), not on the\n * request. Default: `true`.\n */\n protected validateUser(\n _user: TUser,\n _payload: MfJwtPayload,\n _context: ExecutionContext\n ): boolean | string | Promise<boolean | string> {\n return true\n }\n\n /**\n * Whether `?token=` (SSE) is read for this request. Default: `true`.\n * Return `false` (e.g. outside your SSE routes, by `request.path`) to keep\n * session tokens out of URLs and access logs.\n */\n protected allowQueryToken(_request: RequestLike): boolean {\n return true\n }\n}\n\n/** Constructor type returned by `createJwtAuthGuard` (subclassable, DI-friendly). */\nexport type JwtAuthGuardClass<TUser> = new (\n reflector?: Reflector\n) => JwtAuthGuardBase<TUser>\n\n/**\n * Creates the authentication guard: decodes the NextAuth session JWE\n * (Bearer → ?token= for SSE → cookies) and attaches `request.user` (AuthUser).\n *\n * NextAuth derives the JWE key with salt = the cookie NAME — over HTTPS\n * (useSecureCookies) the name becomes `__Secure-<salt>`, so each cookie is\n * decoded using its own name as the salt. Large cookies are chunked\n * (`name.0`, `name.1`, …) and reassembled here.\n *\n * ```ts\n * export const JwtAuthGuard = createJwtAuthGuard()\n *\n * // per-request checks (session freshness, revocation): subclass it\n * @Injectable()\n * export class AppGuard extends createJwtAuthGuard<MyUser>() {\n * constructor(reflector: Reflector, private readonly users: UsersService) {\n * super(reflector)\n * }\n * protected override async resolveUser(payload: MfJwtPayload) { ... }\n * }\n * ```\n */\nexport function createJwtAuthGuard<TUser = AuthUser>(\n options?: JwtAuthGuardOptions\n): JwtAuthGuardClass<TUser> {\n const salt = options?.salt ?? DEFAULT_SALT\n const cookieNames = options?.cookieNames ?? [salt, `__Secure-${salt}`]\n // Bearer/query arrive without a cookie name — we try every possible salt\n const headerSalts = [...new Set([salt, ...cookieNames])]\n const unauthorized = (message: string): Error =>\n options?.createException?.(401, message) ??\n new UnauthorizedException(message)\n // Once per guard class: a warning per request would flood the logs\n let warnedIrrevocable = false\n const logger = new Logger('JwtAuthGuard')\n const cacheTtl = options?.validateUserCacheTtlMs ?? 0\n // Keyed by the token, not the user id: a verdict can depend on its claims\n // (session id, authTime), and a new login must not inherit an old `false`.\n // ponytail: FIFO eviction via Map insertion order; an LRU if churn shows up.\n const verdicts = new Map<string, { verdict: boolean | string; expiresAt: number }>()\n\n @Injectable()\n class JwtAuthGuard extends JwtAuthGuardBase<TUser> {\n private readonly reflector: Reflector\n\n // Reflector is stateless; the default covers instantiation outside DI (tests, @UseGuards)\n constructor(reflector?: Reflector) {\n super()\n this.reflector = reflector ?? new Reflector()\n }\n\n override async canActivate(context: ExecutionContext): Promise<boolean> {\n const isPublic = this.reflector.getAllAndOverride<boolean>(\n IS_PUBLIC_KEY,\n [context.getHandler(), context.getClass()]\n )\n if (isPublic) return true\n\n const request = context.switchToHttp().getRequest<RequestLike>()\n // Resolved here, per request: a function reads values loaded after import\n const secret =\n typeof options?.secret === 'function'\n ? await options.secret()\n : options?.secret\n\n for (const candidate of this.extractTokenCandidates(request)) {\n for (const candidateSalt of candidate.salts) {\n const payload = await decodeSessionToken(candidate.token, {\n secret,\n salt: candidateSalt,\n })\n if (payload) {\n if (payload.impersonatedUserId && options?.isImpersonationActive) {\n const active =\n !!payload.impersonationLogId &&\n (await options.isImpersonationActive(\n payload.impersonationLogId,\n context\n ))\n if (!active) {\n throw unauthorized('Impersonation session is no longer active')\n }\n }\n const user = await this.resolveUser(payload, context)\n if (user == null) {\n throw unauthorized('Session is no longer valid')\n }\n // A thrown error propagates (5xx), like resolveUser's: an outage\n // must not look like an expired session and sign every user out\n const verdict = await this.cachedVerdict(\n candidate.token,\n user,\n payload,\n context\n )\n if (verdict !== true) {\n logger.warn(\n `validateUser rejected user ${payload.id}: ${verdict || 'returned false'}`\n )\n throw unauthorized('Session is no longer valid')\n }\n if (\n payload.impersonatedUserId &&\n !options?.isImpersonationActive &&\n !warnedIrrevocable\n ) {\n warnedIrrevocable = true\n logger.warn(\n 'Accepted an impersonation token without an isImpersonationActive hook: ' +\n 'ending the impersonation cannot revoke it before it expires. ' +\n 'Pass isImpersonationActive to createJwtAuthGuard().'\n )\n }\n request.user = user\n return true\n }\n }\n }\n\n throw unauthorized('Invalid or expired token')\n }\n\n private async cachedVerdict(\n token: string,\n user: TUser,\n payload: MfJwtPayload,\n context: ExecutionContext\n ): Promise<boolean | string> {\n const hit = verdicts.get(token)\n if (hit && hit.expiresAt > Date.now()) return hit.verdict\n verdicts.delete(token)\n const verdict = await this.validateUser(user, payload, context)\n if (cacheTtl > 0) {\n if (verdicts.size >= VALIDATE_CACHE_MAX) {\n verdicts.delete(verdicts.keys().next().value as string)\n }\n verdicts.set(token, { verdict, expiresAt: Date.now() + cacheTtl })\n }\n return verdict\n }\n\n private extractTokenCandidates(request: RequestLike): TokenCandidate[] {\n const candidates: TokenCandidate[] = []\n\n // Priority 1: Bearer token from Authorization header (API pattern)\n const authHeader = request.headers['authorization']\n if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {\n candidates.push({ token: authHeader.substring(7), salts: headerSalts })\n }\n\n // Priority 2: query param (SSE/EventSource cannot send custom headers)\n const queryToken = request.query?.['token']\n if (\n typeof queryToken === 'string' &&\n queryToken &&\n this.allowQueryToken(request)\n ) {\n candidates.push({ token: queryToken, salts: headerSalts })\n }\n\n // Priority 3: NextAuth cookies. NextAuth convention: the cookie NAME\n // is the salt (over HTTPS the name gains __Secure- and the salt\n // changes with it). Custom setups encode with one salt but serve the\n // cookie under another name — hence we try both the name AND the\n // configured salt.\n for (const name of cookieNames) {\n const token = this.readCookie(request, name)\n if (token) {\n candidates.push({ token, salts: [...new Set([name, salt])] })\n }\n }\n\n return candidates\n }\n\n /** Reads the cookie, reassembling chunks (`name.0`, `name.1`, …) if needed. */\n private readCookie(request: RequestLike, name: string): string | undefined {\n const cookies = request.cookies\n if (!cookies) return undefined\n if (cookies[name]) return cookies[name]\n\n let assembled = ''\n for (let i = 0; ; i++) {\n const chunk = cookies[`${name}.${i}`]\n if (chunk === undefined) break\n assembled += chunk\n }\n return assembled || undefined\n }\n }\n\n return JwtAuthGuard\n}\n","import { encode, decode } from '@auth/core/jwt'\nimport { stampSessionTimes } from './session'\nimport type { AuthUser, MfJwtPayload, RoleInfo } from './types'\n\nexport interface TokenConfig {\n /** Default: process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET */\n secret?: string\n /**\n * Key-derivation salt for the JWE — it MUST be identical on both sides.\n * Default: 'authjs.session-token' (NextAuth v5). Projects on the legacy\n * v4 cookie use 'next-auth.session-token'.\n */\n salt?: string\n /** Seconds. Default: 24h */\n maxAge?: number\n}\n\nexport const DEFAULT_SALT = 'authjs.session-token'\nexport const DEFAULT_MAX_AGE = 24 * 60 * 60\n\nexport function resolveTokenConfig(\n config?: TokenConfig\n): Required<TokenConfig> {\n const secret =\n config?.secret ?? process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET\n if (!secret) {\n throw new Error('AUTH_SECRET or NEXTAUTH_SECRET must be defined')\n }\n return {\n secret,\n salt: config?.salt ?? DEFAULT_SALT,\n maxAge: config?.maxAge ?? DEFAULT_MAX_AGE,\n }\n}\n\n/**\n * Issues the session JWE in the NextAuth v5 format (for server-side login on\n * the API, impersonation, etc.). Same secret+salt as the Next app.\n *\n * A payload without `authTime` is a new session: it gets `authTime`/`accessAt`\n * stamped (on a copy), so `sessionState` does not read it as issued at 0.\n */\nexport async function encodeSessionToken(\n payload: MfJwtPayload,\n config?: TokenConfig\n): Promise<string> {\n const { secret, salt, maxAge } = resolveTokenConfig(config)\n const token =\n payload.authTime == null ? stampSessionTimes({ ...payload }) : payload\n return encode({ token, secret, salt, maxAge })\n}\n\n/** Decodes the session JWE. Returns null for an invalid/expired token. */\nexport async function decodeSessionToken(\n token: string,\n config?: TokenConfig\n): Promise<MfJwtPayload | null> {\n const { secret, salt } = resolveTokenConfig(config)\n try {\n const payload = await decode({ token, secret, salt })\n return (payload as MfJwtPayload | null) ?? null\n } catch {\n return null\n }\n}\n\n/**\n * Maps the JWT payload to the request's AuthUser,\n * including the impersonation block.\n */\nexport function payloadToAuthUser(payload: MfJwtPayload): AuthUser {\n const role = payload.role as RoleInfo\n const roles = payload.roles ?? (role ? [role] : [])\n const user: AuthUser = {\n id: payload.id,\n pessoaId: payload.pessoaId ? String(payload.pessoaId) : undefined,\n name: payload.name,\n email: payload.email,\n role,\n roles,\n permissions: payload.permissions ?? [],\n sessionId: payload.sid ?? payload.jti,\n }\n\n if (payload.clienteIds) {\n user.clienteIds = payload.clienteIds\n }\n\n if (payload.impersonatedUserId) {\n const origRole = payload.originalUserRole as RoleInfo\n const origRoles = payload.originalUserRoles ?? (origRole ? [origRole] : [])\n user.isImpersonating = true\n user.impersonationLogId = payload.impersonationLogId\n user.originalUser = {\n id: payload.originalUserId as string,\n name: payload.originalUserName as string,\n email: payload.originalUserEmail as string,\n role: origRole,\n roles: origRoles,\n }\n }\n\n return user\n}\n","import { SetMetadata } from '@nestjs/common'\n\nexport const IS_PUBLIC_KEY = 'isPublic'\n\n/**\n * Marks a route/controller as public — the JwtAuthGuard allows it without a token.\n * Useful with a global guard (APP_GUARD) and per-route opt-out.\n */\nexport const Public = () => SetMetadata(IS_PUBLIC_KEY, true)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAMO;AACP,kBAA0B;;;ACP1B,iBAA+B;AAiBxB,IAAM,eAAe;AACrB,IAAM,kBAAkB,KAAK,KAAK;AAElC,SAAS,mBACd,QACuB;AACvB,QAAM,SACJ,QAAQ,UAAU,QAAQ,IAAI,eAAe,QAAQ,IAAI;AAC3D,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AACA,SAAO;AAAA,IACL;AAAA,IACA,MAAM,QAAQ,QAAQ;AAAA,IACtB,QAAQ,QAAQ,UAAU;AAAA,EAC5B;AACF;AAoBA,eAAsB,mBACpB,OACA,QAC8B;AAC9B,QAAM,EAAE,QAAQ,KAAK,IAAI,mBAAmB,MAAM;AAClD,MAAI;AACF,UAAM,UAAU,UAAM,mBAAO,EAAE,OAAO,QAAQ,KAAK,CAAC;AACpD,WAAQ,WAAmC;AAAA,EAC7C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,kBAAkB,SAAiC;AACjE,QAAM,OAAO,QAAQ;AACrB,QAAM,QAAQ,QAAQ,UAAU,OAAO,CAAC,IAAI,IAAI,CAAC;AACjD,QAAM,OAAiB;AAAA,IACrB,IAAI,QAAQ;AAAA,IACZ,UAAU,QAAQ,WAAW,OAAO,QAAQ,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AAgB,OAAO,GAC5B;AACA,mBAAW,KAAK,EAAE,OAAO,YAAY,OAAO,YAAY,CAAC;AAAA,MAC3D;AAOA,iBAAW,QAAQ,aAAa;AAC9B,cAAM,QAAQ,KAAK,WAAW,SAAS,IAAI;AAC3C,YAAI,OAAO;AACT,qBAAW,KAAK,EAAE,OAAO,OAAO,CAAC,GAAG,oBAAI,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,EAAE,CAAC;AAAA,QAC9D;AAAA,MACF;AAEA,aAAO;AAAA,IACT;AAAA;AAAA,IAGQ,WAAW,SAAsB,MAAkC;AACzE,YAAM,UAAU,QAAQ;AACxB,UAAI,CAAC,QAAS,QAAO;AACrB,UAAI,QAAQ,IAAI,EAAG,QAAO,QAAQ,IAAI;AAEtC,UAAI,YAAY;AAChB,eAAS,IAAI,KAAK,KAAK;AACrB,cAAM,QAAQ,QAAQ,GAAG,IAAI,IAAI,CAAC,EAAE;AACpC,YAAI,UAAU,OAAW;AACzB,qBAAa;AAAA,MACf;AACA,aAAO,aAAa;AAAA,IACtB;AAAA,EACF;AAnJM,iBAAN;AAAA,QADC,2BAAW;AAAA,KACN;AAqJN,SAAO;AACT;","names":["import_common"]}
|
package/dist/nest/index.d.cts
CHANGED
|
@@ -71,6 +71,15 @@ interface JwtAuthGuardOptions extends Omit<TokenConfig, 'secret'> {
|
|
|
71
71
|
* time it accepts one.
|
|
72
72
|
*/
|
|
73
73
|
isImpersonationActive?: (logId: string, context: ExecutionContext) => boolean | Promise<boolean>;
|
|
74
|
+
/**
|
|
75
|
+
* Caches the verdict of `validateUser` for this many milliseconds, per
|
|
76
|
+
* session token, so a database check does not run on every request.
|
|
77
|
+
* Default: no cache. The cache is in memory, per guard class (per process),
|
|
78
|
+
* bounded to 1000 tokens; a thrown error is never cached. A change in the
|
|
79
|
+
* database (user deactivated, sessions revoked) takes up to this long to
|
|
80
|
+
* apply — keep it short (e.g. `30_000`).
|
|
81
|
+
*/
|
|
82
|
+
validateUserCacheTtlMs?: number;
|
|
74
83
|
}
|
|
75
84
|
/**
|
|
76
85
|
* What `createJwtAuthGuard` returns: subclass it to override the protected
|
|
@@ -91,6 +100,20 @@ declare class JwtAuthGuardBase<TUser> implements CanActivate {
|
|
|
91
100
|
* Default: `payloadToAuthUser(payload)`. With a custom `TUser`, override it.
|
|
92
101
|
*/
|
|
93
102
|
protected resolveUser(payload: MfJwtPayload, _context: ExecutionContext): TUser | null | Promise<TUser | null>;
|
|
103
|
+
/**
|
|
104
|
+
* Per-request yes/no check on the resolved user, called after `resolveUser`
|
|
105
|
+
* (only when it returned a user). Return `true` to pass, or `false` / a
|
|
106
|
+
* reason string to reject with a 401 'Session is no longer valid': the
|
|
107
|
+
* reason is logged (Nest `Logger`), never sent to the client. A thrown error
|
|
108
|
+
* propagates (a 5xx, never cached), like `resolveUser`'s: a database outage
|
|
109
|
+
* must not look like an expired session and sign every user out.
|
|
110
|
+
*
|
|
111
|
+
* Unlike `resolveUser`, its verdict can be cached:
|
|
112
|
+
* `validateUserCacheTtlMs` keeps it per session token. With the cache on,
|
|
113
|
+
* the verdict must depend only on the token (user/payload), not on the
|
|
114
|
+
* request. Default: `true`.
|
|
115
|
+
*/
|
|
116
|
+
protected validateUser(_user: TUser, _payload: MfJwtPayload, _context: ExecutionContext): boolean | string | Promise<boolean | string>;
|
|
94
117
|
/**
|
|
95
118
|
* Whether `?token=` (SSE) is read for this request. Default: `true`.
|
|
96
119
|
* Return `false` (e.g. outside your SSE routes, by `request.path`) to keep
|
package/dist/nest/index.d.ts
CHANGED
|
@@ -71,6 +71,15 @@ interface JwtAuthGuardOptions extends Omit<TokenConfig, 'secret'> {
|
|
|
71
71
|
* time it accepts one.
|
|
72
72
|
*/
|
|
73
73
|
isImpersonationActive?: (logId: string, context: ExecutionContext) => boolean | Promise<boolean>;
|
|
74
|
+
/**
|
|
75
|
+
* Caches the verdict of `validateUser` for this many milliseconds, per
|
|
76
|
+
* session token, so a database check does not run on every request.
|
|
77
|
+
* Default: no cache. The cache is in memory, per guard class (per process),
|
|
78
|
+
* bounded to 1000 tokens; a thrown error is never cached. A change in the
|
|
79
|
+
* database (user deactivated, sessions revoked) takes up to this long to
|
|
80
|
+
* apply — keep it short (e.g. `30_000`).
|
|
81
|
+
*/
|
|
82
|
+
validateUserCacheTtlMs?: number;
|
|
74
83
|
}
|
|
75
84
|
/**
|
|
76
85
|
* What `createJwtAuthGuard` returns: subclass it to override the protected
|
|
@@ -91,6 +100,20 @@ declare class JwtAuthGuardBase<TUser> implements CanActivate {
|
|
|
91
100
|
* Default: `payloadToAuthUser(payload)`. With a custom `TUser`, override it.
|
|
92
101
|
*/
|
|
93
102
|
protected resolveUser(payload: MfJwtPayload, _context: ExecutionContext): TUser | null | Promise<TUser | null>;
|
|
103
|
+
/**
|
|
104
|
+
* Per-request yes/no check on the resolved user, called after `resolveUser`
|
|
105
|
+
* (only when it returned a user). Return `true` to pass, or `false` / a
|
|
106
|
+
* reason string to reject with a 401 'Session is no longer valid': the
|
|
107
|
+
* reason is logged (Nest `Logger`), never sent to the client. A thrown error
|
|
108
|
+
* propagates (a 5xx, never cached), like `resolveUser`'s: a database outage
|
|
109
|
+
* must not look like an expired session and sign every user out.
|
|
110
|
+
*
|
|
111
|
+
* Unlike `resolveUser`, its verdict can be cached:
|
|
112
|
+
* `validateUserCacheTtlMs` keeps it per session token. With the cache on,
|
|
113
|
+
* the verdict must depend only on the token (user/payload), not on the
|
|
114
|
+
* request. Default: `true`.
|
|
115
|
+
*/
|
|
116
|
+
protected validateUser(_user: TUser, _payload: MfJwtPayload, _context: ExecutionContext): boolean | string | Promise<boolean | string>;
|
|
94
117
|
/**
|
|
95
118
|
* Whether `?token=` (SSE) is read for this request. Default: `true`.
|
|
96
119
|
* Return `false` (e.g. outside your SSE routes, by `request.path`) to keep
|
package/dist/nest/index.js
CHANGED
|
@@ -19,6 +19,7 @@ var IS_PUBLIC_KEY = "isPublic";
|
|
|
19
19
|
var Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
|
20
20
|
|
|
21
21
|
// src/nest/jwt-auth.guard.ts
|
|
22
|
+
var VALIDATE_CACHE_MAX = 1e3;
|
|
22
23
|
var JwtAuthGuardBase = class {
|
|
23
24
|
/** Overridden by the class `createJwtAuthGuard` builds (it owns the options). */
|
|
24
25
|
canActivate(_context) {
|
|
@@ -35,6 +36,22 @@ var JwtAuthGuardBase = class {
|
|
|
35
36
|
resolveUser(payload, _context) {
|
|
36
37
|
return payloadToAuthUser(payload);
|
|
37
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Per-request yes/no check on the resolved user, called after `resolveUser`
|
|
41
|
+
* (only when it returned a user). Return `true` to pass, or `false` / a
|
|
42
|
+
* reason string to reject with a 401 'Session is no longer valid': the
|
|
43
|
+
* reason is logged (Nest `Logger`), never sent to the client. A thrown error
|
|
44
|
+
* propagates (a 5xx, never cached), like `resolveUser`'s: a database outage
|
|
45
|
+
* must not look like an expired session and sign every user out.
|
|
46
|
+
*
|
|
47
|
+
* Unlike `resolveUser`, its verdict can be cached:
|
|
48
|
+
* `validateUserCacheTtlMs` keeps it per session token. With the cache on,
|
|
49
|
+
* the verdict must depend only on the token (user/payload), not on the
|
|
50
|
+
* request. Default: `true`.
|
|
51
|
+
*/
|
|
52
|
+
validateUser(_user, _payload, _context) {
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
38
55
|
/**
|
|
39
56
|
* Whether `?token=` (SSE) is read for this request. Default: `true`.
|
|
40
57
|
* Return `false` (e.g. outside your SSE routes, by `request.path`) to keep
|
|
@@ -50,6 +67,9 @@ function createJwtAuthGuard(options) {
|
|
|
50
67
|
const headerSalts = [.../* @__PURE__ */ new Set([salt, ...cookieNames])];
|
|
51
68
|
const unauthorized = (message) => options?.createException?.(401, message) ?? new UnauthorizedException(message);
|
|
52
69
|
let warnedIrrevocable = false;
|
|
70
|
+
const logger = new Logger("JwtAuthGuard");
|
|
71
|
+
const cacheTtl = options?.validateUserCacheTtlMs ?? 0;
|
|
72
|
+
const verdicts = /* @__PURE__ */ new Map();
|
|
53
73
|
let JwtAuthGuard = class extends JwtAuthGuardBase {
|
|
54
74
|
reflector;
|
|
55
75
|
// Reflector is stateless; the default covers instantiation outside DI (tests, @UseGuards)
|
|
@@ -85,9 +105,21 @@ function createJwtAuthGuard(options) {
|
|
|
85
105
|
if (user == null) {
|
|
86
106
|
throw unauthorized("Session is no longer valid");
|
|
87
107
|
}
|
|
108
|
+
const verdict = await this.cachedVerdict(
|
|
109
|
+
candidate.token,
|
|
110
|
+
user,
|
|
111
|
+
payload,
|
|
112
|
+
context
|
|
113
|
+
);
|
|
114
|
+
if (verdict !== true) {
|
|
115
|
+
logger.warn(
|
|
116
|
+
`validateUser rejected user ${payload.id}: ${verdict || "returned false"}`
|
|
117
|
+
);
|
|
118
|
+
throw unauthorized("Session is no longer valid");
|
|
119
|
+
}
|
|
88
120
|
if (payload.impersonatedUserId && !options?.isImpersonationActive && !warnedIrrevocable) {
|
|
89
121
|
warnedIrrevocable = true;
|
|
90
|
-
|
|
122
|
+
logger.warn(
|
|
91
123
|
"Accepted an impersonation token without an isImpersonationActive hook: ending the impersonation cannot revoke it before it expires. Pass isImpersonationActive to createJwtAuthGuard()."
|
|
92
124
|
);
|
|
93
125
|
}
|
|
@@ -98,6 +130,19 @@ function createJwtAuthGuard(options) {
|
|
|
98
130
|
}
|
|
99
131
|
throw unauthorized("Invalid or expired token");
|
|
100
132
|
}
|
|
133
|
+
async cachedVerdict(token, user, payload, context) {
|
|
134
|
+
const hit = verdicts.get(token);
|
|
135
|
+
if (hit && hit.expiresAt > Date.now()) return hit.verdict;
|
|
136
|
+
verdicts.delete(token);
|
|
137
|
+
const verdict = await this.validateUser(user, payload, context);
|
|
138
|
+
if (cacheTtl > 0) {
|
|
139
|
+
if (verdicts.size >= VALIDATE_CACHE_MAX) {
|
|
140
|
+
verdicts.delete(verdicts.keys().next().value);
|
|
141
|
+
}
|
|
142
|
+
verdicts.set(token, { verdict, expiresAt: Date.now() + cacheTtl });
|
|
143
|
+
}
|
|
144
|
+
return verdict;
|
|
145
|
+
}
|
|
101
146
|
extractTokenCandidates(request) {
|
|
102
147
|
const candidates = [];
|
|
103
148
|
const authHeader = request.headers["authorization"];
|
package/dist/nest/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/nest/jwt-auth.guard.ts","../../src/nest/public.decorator.ts"],"sourcesContent":["import {\n Injectable,\n Logger,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common'\nimport { Reflector } from '@nestjs/core'\nimport {\n decodeSessionToken,\n payloadToAuthUser,\n DEFAULT_SALT,\n type TokenConfig,\n} from '../jwt'\nimport type { AuthUser, MfJwtPayload } from '../types'\nimport { IS_PUBLIC_KEY } from './public.decorator'\n\n/** Minimal request shape (Express/Fastify) — avoids depending on @types/express */\nexport interface RequestLike {\n headers: Record<string, string | string[] | undefined>\n query?: Record<string, unknown>\n cookies?: Record<string, string | undefined>\n user?: unknown\n path?: string\n url?: string\n}\n\nexport interface JwtAuthGuardOptions extends Omit<TokenConfig, 'secret'> {\n /**\n * The JWE secret, or a function resolved on every request (sync or async).\n * The guard class is built when its module is imported, before Nest DI and\n * env loading, so pass a function to read the value late:\n *\n * ```ts\n * createJwtAuthGuard({ secret: () => process.env.AUTH_SECRET })\n * ```\n *\n * `undefined` (static or returned) falls back to\n * `process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET`.\n */\n secret?: string | (() => string | undefined | Promise<string | undefined>)\n /**\n * Builds the 401 the guard throws. Default: Nest's `UnauthorizedException`\n * from the package's own `@nestjs/common`. While the package is linked\n * (`link:`/`file:`), that copy differs from the host's and its filters\n * (`instanceof HttpException`) turn the 401 into a 500 — pass the host's class:\n *\n * ```ts\n * import { ForbiddenException, UnauthorizedException } from '@nestjs/common'\n *\n * createJwtAuthGuard({\n * createException: (status, message) =>\n * status === 401 ? new UnauthorizedException(message) : new ForbiddenException(message),\n * })\n * ```\n *\n * Same signature as the option of `createPermissionsGuard`, so one function\n * serves both guards (this guard only ever passes 401).\n */\n createException?: (status: 401 | 403, message: string) => Error\n /**\n * Cookie names to look for the session token in.\n * Default: [salt, `__Secure-${salt}`]. Projects that decode with the v5\n * salt but still serve the legacy cookie pass ['next-auth.session-token', ...].\n */\n cookieNames?: string[]\n /**\n * Impersonation revocation. Called only when the request is an\n * impersonation one; `false` → 401. The package knows nothing about the\n * database/Redis — the app checks its log:\n *\n * ```ts\n * createJwtAuthGuard({\n * isImpersonationActive: async (logId) => !!(await prisma.impersonationLog\n * .findFirst({ where: { id: logId, endedAt: null } }))\n * })\n * ```\n *\n * With the hook configured, an impersonation token WITHOUT\n * `impersonationLogId` (issued before the contract, hence irrevocable)\n * is rejected as well. Without it, an impersonation token stays valid until\n * it expires; the guard logs a one-time warning (Nest `Logger`) the first\n * time it accepts one.\n */\n isImpersonationActive?: (\n logId: string,\n context: ExecutionContext\n ) => boolean | Promise<boolean>\n}\n\n/** Candidate token + the salts to try decoding it with. */\ninterface TokenCandidate {\n token: string\n salts: string[]\n}\n\n/**\n * What `createJwtAuthGuard` returns: subclass it to override the protected\n * hooks. Not abstract on purpose — an abstract `canActivate` would force every\n * subclass to implement it. Exported so that apps compiled with\n * `declaration: true` can `export class AppGuard extends createJwtAuthGuard()`\n * (otherwise TS4094/TS4020); instantiate it only through the factory.\n */\nexport class JwtAuthGuardBase<TUser> implements CanActivate {\n /** Overridden by the class `createJwtAuthGuard` builds (it owns the options). */\n canActivate(_context: ExecutionContext): Promise<boolean> {\n throw new Error('Build the guard with createJwtAuthGuard()')\n }\n\n /**\n * Per-request user resolution, called after the token is decoded and the\n * impersonation check passed. The return value becomes `request.user`;\n * `null` → 401 'Session is no longer valid'. Errors thrown here propagate\n * as-is (a database outage is not an \"invalid token\").\n *\n * Default: `payloadToAuthUser(payload)`. With a custom `TUser`, override it.\n */\n protected resolveUser(\n payload: MfJwtPayload,\n _context: ExecutionContext\n ): TUser | null | Promise<TUser | null> {\n // Correct for the default TUser = AuthUser; a custom TUser must override this\n return payloadToAuthUser(payload) as unknown as TUser\n }\n\n /**\n * Whether `?token=` (SSE) is read for this request. Default: `true`.\n * Return `false` (e.g. outside your SSE routes, by `request.path`) to keep\n * session tokens out of URLs and access logs.\n */\n protected allowQueryToken(_request: RequestLike): boolean {\n return true\n }\n}\n\n/** Constructor type returned by `createJwtAuthGuard` (subclassable, DI-friendly). */\nexport type JwtAuthGuardClass<TUser> = new (\n reflector?: Reflector\n) => JwtAuthGuardBase<TUser>\n\n/**\n * Creates the authentication guard: decodes the NextAuth session JWE\n * (Bearer → ?token= for SSE → cookies) and attaches `request.user` (AuthUser).\n *\n * NextAuth derives the JWE key with salt = the cookie NAME — over HTTPS\n * (useSecureCookies) the name becomes `__Secure-<salt>`, so each cookie is\n * decoded using its own name as the salt. Large cookies are chunked\n * (`name.0`, `name.1`, …) and reassembled here.\n *\n * ```ts\n * export const JwtAuthGuard = createJwtAuthGuard()\n *\n * // per-request checks (session freshness, revocation): subclass it\n * @Injectable()\n * export class AppGuard extends createJwtAuthGuard<MyUser>() {\n * constructor(reflector: Reflector, private readonly users: UsersService) {\n * super(reflector)\n * }\n * protected override async resolveUser(payload: MfJwtPayload) { ... }\n * }\n * ```\n */\nexport function createJwtAuthGuard<TUser = AuthUser>(\n options?: JwtAuthGuardOptions\n): JwtAuthGuardClass<TUser> {\n const salt = options?.salt ?? DEFAULT_SALT\n const cookieNames = options?.cookieNames ?? [salt, `__Secure-${salt}`]\n // Bearer/query arrive without a cookie name — we try every possible salt\n const headerSalts = [...new Set([salt, ...cookieNames])]\n const unauthorized = (message: string): Error =>\n options?.createException?.(401, message) ??\n new UnauthorizedException(message)\n // Once per guard class: a warning per request would flood the logs\n let warnedIrrevocable = false\n\n @Injectable()\n class JwtAuthGuard extends JwtAuthGuardBase<TUser> {\n private readonly reflector: Reflector\n\n // Reflector is stateless; the default covers instantiation outside DI (tests, @UseGuards)\n constructor(reflector?: Reflector) {\n super()\n this.reflector = reflector ?? new Reflector()\n }\n\n override async canActivate(context: ExecutionContext): Promise<boolean> {\n const isPublic = this.reflector.getAllAndOverride<boolean>(\n IS_PUBLIC_KEY,\n [context.getHandler(), context.getClass()]\n )\n if (isPublic) return true\n\n const request = context.switchToHttp().getRequest<RequestLike>()\n // Resolved here, per request: a function reads values loaded after import\n const secret =\n typeof options?.secret === 'function'\n ? await options.secret()\n : options?.secret\n\n for (const candidate of this.extractTokenCandidates(request)) {\n for (const candidateSalt of candidate.salts) {\n const payload = await decodeSessionToken(candidate.token, {\n secret,\n salt: candidateSalt,\n })\n if (payload) {\n if (payload.impersonatedUserId && options?.isImpersonationActive) {\n const active =\n !!payload.impersonationLogId &&\n (await options.isImpersonationActive(\n payload.impersonationLogId,\n context\n ))\n if (!active) {\n throw unauthorized('Impersonation session is no longer active')\n }\n }\n const user = await this.resolveUser(payload, context)\n if (user == null) {\n throw unauthorized('Session is no longer valid')\n }\n if (\n payload.impersonatedUserId &&\n !options?.isImpersonationActive &&\n !warnedIrrevocable\n ) {\n warnedIrrevocable = true\n new Logger('JwtAuthGuard').warn(\n 'Accepted an impersonation token without an isImpersonationActive hook: ' +\n 'ending the impersonation cannot revoke it before it expires. ' +\n 'Pass isImpersonationActive to createJwtAuthGuard().'\n )\n }\n request.user = user\n return true\n }\n }\n }\n\n throw unauthorized('Invalid or expired token')\n }\n\n private extractTokenCandidates(request: RequestLike): TokenCandidate[] {\n const candidates: TokenCandidate[] = []\n\n // Priority 1: Bearer token from Authorization header (API pattern)\n const authHeader = request.headers['authorization']\n if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {\n candidates.push({ token: authHeader.substring(7), salts: headerSalts })\n }\n\n // Priority 2: query param (SSE/EventSource cannot send custom headers)\n const queryToken = request.query?.['token']\n if (\n typeof queryToken === 'string' &&\n queryToken &&\n this.allowQueryToken(request)\n ) {\n candidates.push({ token: queryToken, salts: headerSalts })\n }\n\n // Priority 3: NextAuth cookies. NextAuth convention: the cookie NAME\n // is the salt (over HTTPS the name gains __Secure- and the salt\n // changes with it). Custom setups encode with one salt but serve the\n // cookie under another name — hence we try both the name AND the\n // configured salt.\n for (const name of cookieNames) {\n const token = this.readCookie(request, name)\n if (token) {\n candidates.push({ token, salts: [...new Set([name, salt])] })\n }\n }\n\n return candidates\n }\n\n /** Reads the cookie, reassembling chunks (`name.0`, `name.1`, …) if needed. */\n private readCookie(request: RequestLike, name: string): string | undefined {\n const cookies = request.cookies\n if (!cookies) return undefined\n if (cookies[name]) return cookies[name]\n\n let assembled = ''\n for (let i = 0; ; i++) {\n const chunk = cookies[`${name}.${i}`]\n if (chunk === undefined) break\n assembled += chunk\n }\n return assembled || undefined\n }\n }\n\n return JwtAuthGuard\n}\n","import { SetMetadata } from '@nestjs/common'\n\nexport const IS_PUBLIC_KEY = 'isPublic'\n\n/**\n * Marks a route/controller as public — the JwtAuthGuard allows it without a token.\n * Useful with a global guard (APP_GUARD) and per-route opt-out.\n */\nexport const Public = () => SetMetadata(IS_PUBLIC_KEY, true)\n"],"mappings":";;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,iBAAiB;;;ACP1B,SAAS,mBAAmB;AAErB,IAAM,gBAAgB;AAMtB,IAAM,SAAS,MAAM,YAAY,eAAe,IAAI;;;AD+FpD,IAAM,mBAAN,MAAqD;AAAA;AAAA,EAE1D,YAAY,UAA8C;AACxD,UAAM,IAAI,MAAM,2CAA2C;AAAA,EAC7D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUU,YACR,SACA,UACsC;AAEtC,WAAO,kBAAkB,OAAO;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOU,gBAAgB,UAAgC;AACxD,WAAO;AAAA,EACT;AACF;AA6BO,SAAS,mBACd,SAC0B;AAC1B,QAAM,OAAO,SAAS,QAAQ;AAC9B,QAAM,cAAc,SAAS,eAAe,CAAC,MAAM,YAAY,IAAI,EAAE;AAEr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../../src/nest/public.decorator.ts"],"sourcesContent":["import {\n Injectable,\n Logger,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common'\nimport { Reflector } from '@nestjs/core'\nimport {\n decodeSessionToken,\n payloadToAuthUser,\n DEFAULT_SALT,\n type TokenConfig,\n} from '../jwt'\nimport type { AuthUser, MfJwtPayload } from '../types'\nimport { IS_PUBLIC_KEY } from './public.decorator'\n\n/** Minimal request shape (Express/Fastify) — avoids depending on @types/express */\nexport interface RequestLike {\n headers: Record<string, string | string[] | undefined>\n query?: Record<string, unknown>\n cookies?: Record<string, string | undefined>\n user?: unknown\n path?: string\n url?: string\n}\n\nexport interface JwtAuthGuardOptions extends Omit<TokenConfig, 'secret'> {\n /**\n * The JWE secret, or a function resolved on every request (sync or async).\n * The guard class is built when its module is imported, before Nest DI and\n * env loading, so pass a function to read the value late:\n *\n * ```ts\n * createJwtAuthGuard({ secret: () => process.env.AUTH_SECRET })\n * ```\n *\n * `undefined` (static or returned) falls back to\n * `process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET`.\n */\n secret?: string | (() => string | undefined | Promise<string | undefined>)\n /**\n * Builds the 401 the guard throws. Default: Nest's `UnauthorizedException`\n * from the package's own `@nestjs/common`. While the package is linked\n * (`link:`/`file:`), that copy differs from the host's and its filters\n * (`instanceof HttpException`) turn the 401 into a 500 — pass the host's class:\n *\n * ```ts\n * import { ForbiddenException, UnauthorizedException } from '@nestjs/common'\n *\n * createJwtAuthGuard({\n * createException: (status, message) =>\n * status === 401 ? new UnauthorizedException(message) : new ForbiddenException(message),\n * })\n * ```\n *\n * Same signature as the option of `createPermissionsGuard`, so one function\n * serves both guards (this guard only ever passes 401).\n */\n createException?: (status: 401 | 403, message: string) => Error\n /**\n * Cookie names to look for the session token in.\n * Default: [salt, `__Secure-${salt}`]. Projects that decode with the v5\n * salt but still serve the legacy cookie pass ['next-auth.session-token', ...].\n */\n cookieNames?: string[]\n /**\n * Impersonation revocation. Called only when the request is an\n * impersonation one; `false` → 401. The package knows nothing about the\n * database/Redis — the app checks its log:\n *\n * ```ts\n * createJwtAuthGuard({\n * isImpersonationActive: async (logId) => !!(await prisma.impersonationLog\n * .findFirst({ where: { id: logId, endedAt: null } }))\n * })\n * ```\n *\n * With the hook configured, an impersonation token WITHOUT\n * `impersonationLogId` (issued before the contract, hence irrevocable)\n * is rejected as well. Without it, an impersonation token stays valid until\n * it expires; the guard logs a one-time warning (Nest `Logger`) the first\n * time it accepts one.\n */\n isImpersonationActive?: (\n logId: string,\n context: ExecutionContext\n ) => boolean | Promise<boolean>\n /**\n * Caches the verdict of `validateUser` for this many milliseconds, per\n * session token, so a database check does not run on every request.\n * Default: no cache. The cache is in memory, per guard class (per process),\n * bounded to 1000 tokens; a thrown error is never cached. A change in the\n * database (user deactivated, sessions revoked) takes up to this long to\n * apply — keep it short (e.g. `30_000`).\n */\n validateUserCacheTtlMs?: number\n}\n\n/** Most tokens the `validateUser` cache keeps; past it, the oldest goes first. */\nconst VALIDATE_CACHE_MAX = 1000\n\n/** Candidate token + the salts to try decoding it with. */\ninterface TokenCandidate {\n token: string\n salts: string[]\n}\n\n/**\n * What `createJwtAuthGuard` returns: subclass it to override the protected\n * hooks. Not abstract on purpose — an abstract `canActivate` would force every\n * subclass to implement it. Exported so that apps compiled with\n * `declaration: true` can `export class AppGuard extends createJwtAuthGuard()`\n * (otherwise TS4094/TS4020); instantiate it only through the factory.\n */\nexport class JwtAuthGuardBase<TUser> implements CanActivate {\n /** Overridden by the class `createJwtAuthGuard` builds (it owns the options). */\n canActivate(_context: ExecutionContext): Promise<boolean> {\n throw new Error('Build the guard with createJwtAuthGuard()')\n }\n\n /**\n * Per-request user resolution, called after the token is decoded and the\n * impersonation check passed. The return value becomes `request.user`;\n * `null` → 401 'Session is no longer valid'. Errors thrown here propagate\n * as-is (a database outage is not an \"invalid token\").\n *\n * Default: `payloadToAuthUser(payload)`. With a custom `TUser`, override it.\n */\n protected resolveUser(\n payload: MfJwtPayload,\n _context: ExecutionContext\n ): TUser | null | Promise<TUser | null> {\n // Correct for the default TUser = AuthUser; a custom TUser must override this\n return payloadToAuthUser(payload) as unknown as TUser\n }\n\n /**\n * Per-request yes/no check on the resolved user, called after `resolveUser`\n * (only when it returned a user). Return `true` to pass, or `false` / a\n * reason string to reject with a 401 'Session is no longer valid': the\n * reason is logged (Nest `Logger`), never sent to the client. A thrown error\n * propagates (a 5xx, never cached), like `resolveUser`'s: a database outage\n * must not look like an expired session and sign every user out.\n *\n * Unlike `resolveUser`, its verdict can be cached:\n * `validateUserCacheTtlMs` keeps it per session token. With the cache on,\n * the verdict must depend only on the token (user/payload), not on the\n * request. Default: `true`.\n */\n protected validateUser(\n _user: TUser,\n _payload: MfJwtPayload,\n _context: ExecutionContext\n ): boolean | string | Promise<boolean | string> {\n return true\n }\n\n /**\n * Whether `?token=` (SSE) is read for this request. Default: `true`.\n * Return `false` (e.g. outside your SSE routes, by `request.path`) to keep\n * session tokens out of URLs and access logs.\n */\n protected allowQueryToken(_request: RequestLike): boolean {\n return true\n }\n}\n\n/** Constructor type returned by `createJwtAuthGuard` (subclassable, DI-friendly). */\nexport type JwtAuthGuardClass<TUser> = new (\n reflector?: Reflector\n) => JwtAuthGuardBase<TUser>\n\n/**\n * Creates the authentication guard: decodes the NextAuth session JWE\n * (Bearer → ?token= for SSE → cookies) and attaches `request.user` (AuthUser).\n *\n * NextAuth derives the JWE key with salt = the cookie NAME — over HTTPS\n * (useSecureCookies) the name becomes `__Secure-<salt>`, so each cookie is\n * decoded using its own name as the salt. Large cookies are chunked\n * (`name.0`, `name.1`, …) and reassembled here.\n *\n * ```ts\n * export const JwtAuthGuard = createJwtAuthGuard()\n *\n * // per-request checks (session freshness, revocation): subclass it\n * @Injectable()\n * export class AppGuard extends createJwtAuthGuard<MyUser>() {\n * constructor(reflector: Reflector, private readonly users: UsersService) {\n * super(reflector)\n * }\n * protected override async resolveUser(payload: MfJwtPayload) { ... }\n * }\n * ```\n */\nexport function createJwtAuthGuard<TUser = AuthUser>(\n options?: JwtAuthGuardOptions\n): JwtAuthGuardClass<TUser> {\n const salt = options?.salt ?? DEFAULT_SALT\n const cookieNames = options?.cookieNames ?? [salt, `__Secure-${salt}`]\n // Bearer/query arrive without a cookie name — we try every possible salt\n const headerSalts = [...new Set([salt, ...cookieNames])]\n const unauthorized = (message: string): Error =>\n options?.createException?.(401, message) ??\n new UnauthorizedException(message)\n // Once per guard class: a warning per request would flood the logs\n let warnedIrrevocable = false\n const logger = new Logger('JwtAuthGuard')\n const cacheTtl = options?.validateUserCacheTtlMs ?? 0\n // Keyed by the token, not the user id: a verdict can depend on its claims\n // (session id, authTime), and a new login must not inherit an old `false`.\n // ponytail: FIFO eviction via Map insertion order; an LRU if churn shows up.\n const verdicts = new Map<string, { verdict: boolean | string; expiresAt: number }>()\n\n @Injectable()\n class JwtAuthGuard extends JwtAuthGuardBase<TUser> {\n private readonly reflector: Reflector\n\n // Reflector is stateless; the default covers instantiation outside DI (tests, @UseGuards)\n constructor(reflector?: Reflector) {\n super()\n this.reflector = reflector ?? new Reflector()\n }\n\n override async canActivate(context: ExecutionContext): Promise<boolean> {\n const isPublic = this.reflector.getAllAndOverride<boolean>(\n IS_PUBLIC_KEY,\n [context.getHandler(), context.getClass()]\n )\n if (isPublic) return true\n\n const request = context.switchToHttp().getRequest<RequestLike>()\n // Resolved here, per request: a function reads values loaded after import\n const secret =\n typeof options?.secret === 'function'\n ? await options.secret()\n : options?.secret\n\n for (const candidate of this.extractTokenCandidates(request)) {\n for (const candidateSalt of candidate.salts) {\n const payload = await decodeSessionToken(candidate.token, {\n secret,\n salt: candidateSalt,\n })\n if (payload) {\n if (payload.impersonatedUserId && options?.isImpersonationActive) {\n const active =\n !!payload.impersonationLogId &&\n (await options.isImpersonationActive(\n payload.impersonationLogId,\n context\n ))\n if (!active) {\n throw unauthorized('Impersonation session is no longer active')\n }\n }\n const user = await this.resolveUser(payload, context)\n if (user == null) {\n throw unauthorized('Session is no longer valid')\n }\n // A thrown error propagates (5xx), like resolveUser's: an outage\n // must not look like an expired session and sign every user out\n const verdict = await this.cachedVerdict(\n candidate.token,\n user,\n payload,\n context\n )\n if (verdict !== true) {\n logger.warn(\n `validateUser rejected user ${payload.id}: ${verdict || 'returned false'}`\n )\n throw unauthorized('Session is no longer valid')\n }\n if (\n payload.impersonatedUserId &&\n !options?.isImpersonationActive &&\n !warnedIrrevocable\n ) {\n warnedIrrevocable = true\n logger.warn(\n 'Accepted an impersonation token without an isImpersonationActive hook: ' +\n 'ending the impersonation cannot revoke it before it expires. ' +\n 'Pass isImpersonationActive to createJwtAuthGuard().'\n )\n }\n request.user = user\n return true\n }\n }\n }\n\n throw unauthorized('Invalid or expired token')\n }\n\n private async cachedVerdict(\n token: string,\n user: TUser,\n payload: MfJwtPayload,\n context: ExecutionContext\n ): Promise<boolean | string> {\n const hit = verdicts.get(token)\n if (hit && hit.expiresAt > Date.now()) return hit.verdict\n verdicts.delete(token)\n const verdict = await this.validateUser(user, payload, context)\n if (cacheTtl > 0) {\n if (verdicts.size >= VALIDATE_CACHE_MAX) {\n verdicts.delete(verdicts.keys().next().value as string)\n }\n verdicts.set(token, { verdict, expiresAt: Date.now() + cacheTtl })\n }\n return verdict\n }\n\n private extractTokenCandidates(request: RequestLike): TokenCandidate[] {\n const candidates: TokenCandidate[] = []\n\n // Priority 1: Bearer token from Authorization header (API pattern)\n const authHeader = request.headers['authorization']\n if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {\n candidates.push({ token: authHeader.substring(7), salts: headerSalts })\n }\n\n // Priority 2: query param (SSE/EventSource cannot send custom headers)\n const queryToken = request.query?.['token']\n if (\n typeof queryToken === 'string' &&\n queryToken &&\n this.allowQueryToken(request)\n ) {\n candidates.push({ token: queryToken, salts: headerSalts })\n }\n\n // Priority 3: NextAuth cookies. NextAuth convention: the cookie NAME\n // is the salt (over HTTPS the name gains __Secure- and the salt\n // changes with it). Custom setups encode with one salt but serve the\n // cookie under another name — hence we try both the name AND the\n // configured salt.\n for (const name of cookieNames) {\n const token = this.readCookie(request, name)\n if (token) {\n candidates.push({ token, salts: [...new Set([name, salt])] })\n }\n }\n\n return candidates\n }\n\n /** Reads the cookie, reassembling chunks (`name.0`, `name.1`, …) if needed. */\n private readCookie(request: RequestLike, name: string): string | undefined {\n const cookies = request.cookies\n if (!cookies) return undefined\n if (cookies[name]) return cookies[name]\n\n let assembled = ''\n for (let i = 0; ; i++) {\n const chunk = cookies[`${name}.${i}`]\n if (chunk === undefined) break\n assembled += chunk\n }\n return assembled || undefined\n }\n }\n\n return JwtAuthGuard\n}\n","import { SetMetadata } from '@nestjs/common'\n\nexport const IS_PUBLIC_KEY = 'isPublic'\n\n/**\n * Marks a route/controller as public — the JwtAuthGuard allows it without a token.\n * Useful with a global guard (APP_GUARD) and per-route opt-out.\n */\nexport const Public = () => SetMetadata(IS_PUBLIC_KEY, true)\n"],"mappings":";;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,iBAAiB;;;ACP1B,SAAS,mBAAmB;AAErB,IAAM,gBAAgB;AAMtB,IAAM,SAAS,MAAM,YAAY,eAAe,IAAI;;;AD4F3D,IAAM,qBAAqB;AAepB,IAAM,mBAAN,MAAqD;AAAA;AAAA,EAE1D,YAAY,UAA8C;AACxD,UAAM,IAAI,MAAM,2CAA2C;AAAA,EAC7D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUU,YACR,SACA,UACsC;AAEtC,WAAO,kBAAkB,OAAO;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeU,aACR,OACA,UACA,UAC8C;AAC9C,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOU,gBAAgB,UAAgC;AACxD,WAAO;AAAA,EACT;AACF;AA6BO,SAAS,mBACd,SAC0B;AAC1B,QAAM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AAM,aAAa,QAAQ,QAAQ,OAAO;AAC1C,UACE,OAAO,eAAe,YACtB,cACA,KAAK,gBAAgB,OAAO,GAC5B;AACA,mBAAW,KAAK,EAAE,OAAO,YAAY,OAAO,YAAY,CAAC;AAAA,MAC3D;AAOA,iBAAW,QAAQ,aAAa;AAC9B,cAAM,QAAQ,KAAK,WAAW,SAAS,IAAI;AAC3C,YAAI,OAAO;AACT,qBAAW,KAAK,EAAE,OAAO,OAAO,CAAC,GAAG,oBAAI,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,EAAE,CAAC;AAAA,QAC9D;AAAA,MACF;AAEA,aAAO;AAAA,IACT;AAAA;AAAA,IAGQ,WAAW,SAAsB,MAAkC;AACzE,YAAM,UAAU,QAAQ;AACxB,UAAI,CAAC,QAAS,QAAO;AACrB,UAAI,QAAQ,IAAI,EAAG,QAAO,QAAQ,IAAI;AAEtC,UAAI,YAAY;AAChB,eAAS,IAAI,KAAK,KAAK;AACrB,cAAM,QAAQ,QAAQ,GAAG,IAAI,IAAI,CAAC,EAAE;AACpC,YAAI,UAAU,OAAW;AACzB,qBAAa;AAAA,MACf;AACA,aAAO,aAAa;AAAA,IACtB;AAAA,EACF;AAnJM,iBAAN;AAAA,IADC,WAAW;AAAA,KACN;AAqJN,SAAO;AACT;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@telamonjs/auth",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "NextAuth v5 <-> NestJS auth bridge: the JWE session-token contract, a Nest guard, Next callbacks and revocable impersonation",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.js",
|