@telamonjs/auth 1.4.0 → 1.4.1
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 +11 -0
- package/README.md +18 -6
- package/dist/{chunk-TL5OYB5P.js → chunk-G73ASFMN.js} +6 -2
- package/dist/chunk-G73ASFMN.js.map +1 -0
- package/dist/index.cjs +5 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{jwt-B_WnKVc1.d.cts → jwt-EyXe_d9K.d.cts} +10 -2
- package/dist/{jwt-B_WnKVc1.d.ts → jwt-EyXe_d9K.d.ts} +10 -2
- package/dist/nest/index.cjs +13 -4
- package/dist/nest/index.cjs.map +1 -1
- package/dist/nest/index.d.cts +11 -6
- package/dist/nest/index.d.ts +11 -6
- package/dist/nest/index.js +9 -4
- package/dist/nest/index.js.map +1 -1
- package/dist/next/index.cjs +13 -4
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +6 -3
- package/dist/next/index.d.ts +6 -3
- package/dist/next/index.js +9 -4
- package/dist/next/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-TL5OYB5P.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.4.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 7289ce5: Stricter session and API-key handling:
|
|
8
|
+
|
|
9
|
+
- API-key guards treat any falsy verifier result (`false`, `0`, `''`, `NaN`) as a rejection, like `null`.
|
|
10
|
+
- An explicit `maxAge` passed to `decodeSessionToken`, `createJwtAuthGuard` or `createAuthCallbacks({ tokenConfig })` is now enforced against the token's issue time. Without one, only the token's own expiry applies, as before.
|
|
11
|
+
- `createJwtAuthGuard` reads the `__Secure-authjs.session-token` cookie first and, while it is present, never falls back to the plain one. APIs served only over HTTPS can pass `cookieNames: ['__Secure-authjs.session-token']`.
|
|
12
|
+
- `createAuthCallbacks` applies an impersonation cookie only to the session that started the impersonation, and only for tokens issued by `createImpersonationToken`. Ending an impersonation also restores the actor's `accessAt`.
|
|
13
|
+
|
|
3
14
|
## 1.4.0
|
|
4
15
|
|
|
5
16
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
<a href="https://github.com/telamonjs/telamonjs"><img alt="TelamonJS" src="https://cdn.jsdelivr.net/gh/telamonjs/telamonjs@main/.github/assets/logo-mark.svg" height="40"></a>
|
|
2
|
+
|
|
1
3
|
# @telamonjs/auth
|
|
2
4
|
|
|
5
|
+
[](https://www.npmjs.com/package/@telamonjs/auth) [](https://github.com/telamonjs/telamonjs/blob/main/LICENSE)
|
|
6
|
+
|
|
3
7
|
The NextAuth v5 ↔ NestJS bridge. This package owns the **shape of the session
|
|
4
8
|
token** (an `@auth/core` JWE), not your login flow: your app's `authorize()`
|
|
5
9
|
still checks credentials. The Next side gets canonical `jwt`/`session`
|
|
@@ -56,7 +60,9 @@ export const JwtAuthGuard = createJwtAuthGuard()
|
|
|
56
60
|
The guard reads the token from `Authorization: Bearer`, then `?token=` (for
|
|
57
61
|
EventSource/SSE, which can't send headers), then the NextAuth cookies. Cookie
|
|
58
62
|
decoding is salt-aware (`__Secure-` names under HTTPS) and reassembles chunked
|
|
59
|
-
cookies.
|
|
63
|
+
cookies. While a `__Secure-` cookie is present, the plain one is never read; an
|
|
64
|
+
HTTPS-only API passes `cookieNames: ['__Secure-authjs.session-token']` so it is
|
|
65
|
+
never read at all. Opt a route out with `@Public()`.
|
|
60
66
|
|
|
61
67
|
The guard is built when its module is imported, before Nest DI and env
|
|
62
68
|
loading. To read the secret late, pass a function (sync or async), called on
|
|
@@ -91,7 +97,9 @@ const token = await createImpersonationToken({ target, actor, logId: log.id })
|
|
|
91
97
|
The impersonation token **is** the API credential: the callbacks swap
|
|
92
98
|
`accessToken` too, so impersonation is not cosmetic. Wire the cookies through
|
|
93
99
|
`createAuthCallbacks({ getImpersonationCookies, clearImpersonationCookies })`.
|
|
94
|
-
|
|
100
|
+
The cookie only applies to the session of the actor who started it (the
|
|
101
|
+
token's `originalUserId`), so another user signing in on the same browser
|
|
102
|
+
keeps their own identity. For immediate revocation, pass `isImpersonationActive` to the guard; tokens
|
|
95
103
|
without a `logId` are then rejected. Without the hook an impersonation token
|
|
96
104
|
stays valid until it expires, and the guard logs a one-time warning (Nest
|
|
97
105
|
`Logger`) the first time it accepts one:
|
|
@@ -174,8 +182,8 @@ export const InternalKeyGuard = createApiKeyGuard({
|
|
|
174
182
|
@Public() @UseGuards(InternalKeyGuard) @Post('emit') emit() {}
|
|
175
183
|
```
|
|
176
184
|
|
|
177
|
-
`verify(key, request)` returns a principal or `null` (
|
|
178
|
-
database lookup fits too). The principal goes to `request.servicePrincipal`;
|
|
185
|
+
`verify(key, request)` returns a principal, or `null` (any falsy value) to
|
|
186
|
+
reject (sync or async, so a database lookup fits too). The principal goes to `request.servicePrincipal`;
|
|
179
187
|
`request.user` is left alone. Anything else is a generic 401 (`createException`
|
|
180
188
|
applies); the guard logs nothing, and a thrown verifier error propagates.
|
|
181
189
|
`staticApiKey` compares sha256 digests with `timingSafeEqual` and rejects
|
|
@@ -214,7 +222,11 @@ hashApiKey(key) // → Promise<hex sha256>, to store
|
|
|
214
222
|
|
|
215
223
|
`TokenConfig` is `{ secret?, salt?, maxAge? }`. Defaults: salt
|
|
216
224
|
`'authjs.session-token'` (`DEFAULT_SALT`), maxAge 24 h (`DEFAULT_MAX_AGE`),
|
|
217
|
-
impersonation 1 h (`DEFAULT_IMPERSONATION_MAX_AGE`).
|
|
225
|
+
impersonation 1 h (`DEFAULT_IMPERSONATION_MAX_AGE`). Those maxAge defaults
|
|
226
|
+
set the lifetime of the tokens you encode. On the decoding side
|
|
227
|
+
(`decodeSessionToken`, the guard, `createAuthCallbacks({ tokenConfig })`) a
|
|
228
|
+
`maxAge` you pass also rejects a token issued longer ago than that; without
|
|
229
|
+
one, the token's own `exp` is the only limit.
|
|
218
230
|
|
|
219
231
|
`AuthUser` structurally satisfies `UserWithPermissions` from
|
|
220
232
|
[`@telamonjs/permissions`](https://www.npmjs.com/package/@telamonjs/permissions),
|
|
@@ -233,5 +245,5 @@ Every name each entry point exports, runtime and types: [Public API index](https
|
|
|
233
245
|
|
|
234
246
|
## Full docs
|
|
235
247
|
|
|
236
|
-
**Full docs →** [the auth page of the docs site](https://
|
|
248
|
+
**Full docs →** [the auth page of the docs site](https://telamonjs.com/docs/packages/auth)
|
|
237
249
|
(MDX sources, readable on GitHub).
|
|
@@ -51,7 +51,11 @@ async function decodeSessionToken(token, config) {
|
|
|
51
51
|
const { secret, salt } = resolveTokenConfig(config);
|
|
52
52
|
try {
|
|
53
53
|
const payload = await decode({ token, secret, salt });
|
|
54
|
-
|
|
54
|
+
if (!payload) return null;
|
|
55
|
+
if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1e3) {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
return payload;
|
|
55
59
|
} catch {
|
|
56
60
|
return null;
|
|
57
61
|
}
|
|
@@ -99,4 +103,4 @@ export {
|
|
|
99
103
|
decodeSessionToken,
|
|
100
104
|
payloadToAuthUser
|
|
101
105
|
};
|
|
102
|
-
//# sourceMappingURL=chunk-
|
|
106
|
+
//# sourceMappingURL=chunk-G73ASFMN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/session.ts","../src/jwt.ts"],"sourcesContent":["/**\n * Session freshness & revocation — pure, isomorphic, DB-agnostic.\n *\n * Roles/permissions are materialized in the session token, so a change in the\n * database only reaches the token at the next login, and a token cannot be\n * revoked by itself. The app keeps two per-user timestamps (e.g.\n * `accessChangedAt`, `sessionsRevokedAt`) and compares them with the times\n * stamped into the token at login; these helpers do the comparison.\n */\n\n/** Login/claims times stamped into the session token. */\nexport interface SessionTimes {\n /** Login time, epoch ms */\n authTime?: number\n /** When roles/permissions in the token were computed, epoch ms */\n accessAt?: number\n}\n\n/** Per-user marks the app stores. `null`/`undefined` mean \"nothing changed\". */\nexport interface SessionMarks {\n /** Every session that logged in before this instant is revoked */\n revokedAt?: Date | number | null\n /** Roles/permissions changed at this instant */\n accessChangedAt?: Date | number | null\n}\n\n/**\n * - `revoked`: the session must end (sign out / 401)\n * - `stale`: the session is valid, but its roles/permissions must be recomputed\n * - `fresh`: the token is up to date\n */\nexport type SessionState = 'revoked' | 'stale' | 'fresh'\n\n/** Stamps `authTime` and `accessAt` (epoch ms). Mutates and returns the token. */\nexport function stampSessionTimes<T extends object>(\n token: T,\n now: number = Date.now()\n): T & Required<SessionTimes> {\n return Object.assign(token, { authTime: now, accessAt: now })\n}\n\nfunction toMs(mark: Date | number | null | undefined): number | null {\n if (mark == null) return null\n return typeof mark === 'number' ? mark : mark.getTime()\n}\n\n/**\n * Compares the token's times with the user's marks. Revoked wins over stale.\n * A missing claim counts as 0, so tokens issued before adoption are caught by\n * the next revocation/access change.\n */\nexport function sessionState(\n token: SessionTimes,\n marks: SessionMarks\n): SessionState {\n const revokedAt = toMs(marks.revokedAt)\n if (revokedAt !== null && revokedAt > (token.authTime ?? 0)) return 'revoked'\n const accessChangedAt = toMs(marks.accessChangedAt)\n if (accessChangedAt !== null && accessChangedAt > (token.accessAt ?? 0)) {\n return 'stale'\n }\n return 'fresh'\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 /**\n * Seconds. Encoding: the token lifetime, default 24h. Decoding (and the\n * guard): only when set, rejects a token issued longer ago than this;\n * unset, the token's own `exp` is the only limit.\n */\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/**\n * Decodes the session JWE. Returns null for an invalid/expired token.\n * An explicit `config.maxAge` also rejects a token issued (`iat`) more than\n * that many seconds ago; without it, only the token's own `exp` applies.\n */\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 })) as MfJwtPayload | null\n if (!payload) return null\n // A token without iat counts as issued at 0: fail closed\n if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1000) {\n return null\n }\n return payload\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"],"mappings":";;;;;;;;;;;;AAkCO,SAAS,kBACd,OACA,MAAc,KAAK,IAAI,GACK;AAC5B,SAAO,OAAO,OAAO,OAAO,EAAE,UAAU,KAAK,UAAU,IAAI,CAAC;AAC9D;AAEA,SAAS,KAAK,MAAuD;AACnE,MAAI,QAAQ,KAAM,QAAO;AACzB,SAAO,OAAO,SAAS,WAAW,OAAO,KAAK,QAAQ;AACxD;AAOO,SAAS,aACd,OACA,OACc;AACd,QAAM,YAAY,KAAK,MAAM,SAAS;AACtC,MAAI,cAAc,QAAQ,aAAa,MAAM,YAAY,GAAI,QAAO;AACpE,QAAM,kBAAkB,KAAK,MAAM,eAAe;AAClD,MAAI,oBAAoB,QAAQ,mBAAmB,MAAM,YAAY,IAAI;AACvE,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;AC9DA,SAAS,QAAQ,cAAc;AAqBxB,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,QA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AK,eAAe;AAAA,MAClB,IAAI,QAAQ;AAAA,MACZ,MAAM,QAAQ;AAAA,MACd,OAAO,QAAQ;AAAA,MACf,MAAM;AAAA,MACN,OAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
package/dist/index.cjs
CHANGED
|
@@ -79,7 +79,11 @@ async function decodeSessionToken(token, config) {
|
|
|
79
79
|
const { secret, salt } = resolveTokenConfig(config);
|
|
80
80
|
try {
|
|
81
81
|
const payload = await (0, import_jwt.decode)({ token, secret, salt });
|
|
82
|
-
|
|
82
|
+
if (!payload) return null;
|
|
83
|
+
if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1e3) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
return payload;
|
|
83
87
|
} catch {
|
|
84
88
|
return null;
|
|
85
89
|
}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/jwt.ts","../src/session.ts","../src/impersonation.ts","../src/api-key.ts"],"sourcesContent":["/**\n * @telamonjs/auth — NextAuth v5 ↔ NestJS auth bridge.\n *\n * Isomorphic core: the session token contract (JWE @auth/core) shared\n * between the Next app and the Nest API. The login authorize() belongs to\n * the app; this package owns the token format, not the login flow.\n *\n * NestJS side (guard + @Public): '@telamonjs/auth/nest'.\n * Next side (callbacks): '@telamonjs/auth/next'.\n */\n\nexport {\n encodeSessionToken,\n decodeSessionToken,\n payloadToAuthUser,\n resolveTokenConfig,\n DEFAULT_SALT,\n DEFAULT_MAX_AGE,\n type TokenConfig,\n} from './jwt'\n\nexport {\n createImpersonationToken,\n DEFAULT_IMPERSONATION_MAX_AGE,\n type ImpersonationParty,\n type CreateImpersonationTokenInput,\n} from './impersonation'\n\nexport {\n stampSessionTimes,\n sessionState,\n type SessionState,\n type SessionMarks,\n type SessionTimes,\n} from './session'\n\nexport { generateApiKey, hashApiKey } from './api-key'\n\nexport type { RoleInfo, AuthUser, MfJwtPayload, JwtPayload } from './types'\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","/**\n * Session freshness & revocation — pure, isomorphic, DB-agnostic.\n *\n * Roles/permissions are materialized in the session token, so a change in the\n * database only reaches the token at the next login, and a token cannot be\n * revoked by itself. The app keeps two per-user timestamps (e.g.\n * `accessChangedAt`, `sessionsRevokedAt`) and compares them with the times\n * stamped into the token at login; these helpers do the comparison.\n */\n\n/** Login/claims times stamped into the session token. */\nexport interface SessionTimes {\n /** Login time, epoch ms */\n authTime?: number\n /** When roles/permissions in the token were computed, epoch ms */\n accessAt?: number\n}\n\n/** Per-user marks the app stores. `null`/`undefined` mean \"nothing changed\". */\nexport interface SessionMarks {\n /** Every session that logged in before this instant is revoked */\n revokedAt?: Date | number | null\n /** Roles/permissions changed at this instant */\n accessChangedAt?: Date | number | null\n}\n\n/**\n * - `revoked`: the session must end (sign out / 401)\n * - `stale`: the session is valid, but its roles/permissions must be recomputed\n * - `fresh`: the token is up to date\n */\nexport type SessionState = 'revoked' | 'stale' | 'fresh'\n\n/** Stamps `authTime` and `accessAt` (epoch ms). Mutates and returns the token. */\nexport function stampSessionTimes<T extends object>(\n token: T,\n now: number = Date.now()\n): T & Required<SessionTimes> {\n return Object.assign(token, { authTime: now, accessAt: now })\n}\n\nfunction toMs(mark: Date | number | null | undefined): number | null {\n if (mark == null) return null\n return typeof mark === 'number' ? mark : mark.getTime()\n}\n\n/**\n * Compares the token's times with the user's marks. Revoked wins over stale.\n * A missing claim counts as 0, so tokens issued before adoption are caught by\n * the next revocation/access change.\n */\nexport function sessionState(\n token: SessionTimes,\n marks: SessionMarks\n): SessionState {\n const revokedAt = toMs(marks.revokedAt)\n if (revokedAt !== null && revokedAt > (token.authTime ?? 0)) return 'revoked'\n const accessChangedAt = toMs(marks.accessChangedAt)\n if (accessChangedAt !== null && accessChangedAt > (token.accessAt ?? 0)) {\n return 'stale'\n }\n return 'fresh'\n}\n","import { encodeSessionToken, type TokenConfig } from './jwt'\nimport type { MfJwtPayload, RoleInfo } from './types'\n\n/** Seconds. Impersonation token default: 1h (the normal session is 24h). */\nexport const DEFAULT_IMPERSONATION_MAX_AGE = 60 * 60\n\n/**\n * Data for one side of the impersonation, ALREADY RESOLVED by the app.\n * The package never touches the database — loading the user/roles/permissions\n * is the app's job.\n */\nexport interface ImpersonationParty {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions?: string[]\n}\n\nexport interface CreateImpersonationTokenInput {\n /** User being impersonated — becomes the subject of the token. */\n target: ImpersonationParty & { permissions: string[] }\n /** Admin who started it (becomes the `original*` block). */\n actor: ImpersonationParty\n /** Id of the app's audit record (used by the revocation check in the guard). */\n logId: string\n /** Seconds. Default: `DEFAULT_IMPERSONATION_MAX_AGE` (1h). */\n maxAge?: number\n /**\n * Includes `originalPermissions` in the token. Default: false — it only\n * bloats the payload (chunked cookie) and nothing in the package reads\n * those permissions.\n */\n includeOriginalPermissions?: boolean\n}\n\n/**\n * Issues the impersonation token: a session JWE whose SUBJECT is the target\n * and which carries the actor in the `original*` claims — exactly the shape\n * `payloadToAuthUser` reads back (`isImpersonating` + `originalUser`).\n *\n * The token doubles as a credential: sent as `Authorization: Bearer` it\n * authenticates as the target on the API, with `impersonationLogId` for\n * revocation.\n *\n * ```ts\n * const token = await createImpersonationToken({ target, actor, logId: log.id })\n * ```\n *\n * `iat`/`exp`/`jti` are written by `@auth/core/jwt.encode` — the TTL goes\n * through `maxAge`, never as a claim in the payload.\n */\nexport async function createImpersonationToken(\n {\n target,\n actor,\n logId,\n maxAge,\n includeOriginalPermissions,\n }: CreateImpersonationTokenInput,\n config?: TokenConfig\n): Promise<string> {\n const payload: MfJwtPayload = {\n sub: target.id,\n id: target.id,\n pessoaId: target.pessoaId,\n name: target.name,\n email: target.email,\n role: target.role,\n roles: target.roles ?? [target.role],\n permissions: target.permissions ?? [],\n\n impersonatedUserId: target.id,\n impersonationLogId: logId,\n originalUserId: actor.id,\n originalUserName: actor.name,\n originalUserEmail: actor.email,\n originalUserRole: actor.role,\n originalUserRoles: actor.roles ?? [actor.role],\n }\n\n if (includeOriginalPermissions) {\n payload.originalPermissions = actor.permissions ?? []\n }\n\n return encodeSessionToken(payload, {\n ...config,\n maxAge: maxAge ?? config?.maxAge ?? DEFAULT_IMPERSONATION_MAX_AGE,\n })\n}\n","/**\n * API key helpers for machine-to-machine calls. Isomorphic (Web Crypto, no\n * `node:crypto`), so the core entry still loads in the browser and on the edge.\n * The Nest guard that checks keys lives in '@telamonjs/auth/nest'.\n */\n\n/**\n * A new random API key: 32 bytes as URL-safe base64 (43 characters), after\n * an optional `prefix` (e.g. `'svc_'`, so a leaked key is recognizable).\n * Show it once; store it in an env var, or store `hashApiKey(key)` in the\n * database.\n */\nexport function generateApiKey(prefix = ''): string {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32))\n const base64 = btoa(String.fromCharCode(...bytes))\n return (\n prefix +\n base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n )\n}\n\n/**\n * The hex sha256 of a key — what to store and look up instead of the key\n * itself. Same digest as `createHash('sha256').update(key).digest('hex')`.\n * A random 32-byte key needs no salt or slow hash: there is nothing to\n * brute-force.\n */\nexport async function hashApiKey(key: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(key)\n )\n return Array.from(new Uint8Array(digest), b =>\n b.toString(16).padStart(2, '0')\n ).join('')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAA+B;;;ACkCxB,SAAS,kBACd,OACA,MAAc,KAAK,IAAI,GACK;AAC5B,SAAO,OAAO,OAAO,OAAO,EAAE,UAAU,KAAK,UAAU,IAAI,CAAC;AAC9D;AAEA,SAAS,KAAK,MAAuD;AACnE,MAAI,QAAQ,KAAM,QAAO;AACzB,SAAO,OAAO,SAAS,WAAW,OAAO,KAAK,QAAQ;AACxD;AAOO,SAAS,aACd,OACA,OACc;AACd,QAAM,YAAY,KAAK,MAAM,SAAS;AACtC,MAAI,cAAc,QAAQ,aAAa,MAAM,YAAY,GAAI,QAAO;AACpE,QAAM,kBAAkB,KAAK,MAAM,eAAe;AAClD,MAAI,oBAAoB,QAAQ,mBAAmB,MAAM,YAAY,IAAI;AACvE,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;AD7CO,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;AASA,eAAsB,mBACpB,SACA,QACiB;AACjB,QAAM,EAAE,QAAQ,MAAM,OAAO,IAAI,mBAAmB,MAAM;AAC1D,QAAM,QACJ,QAAQ,YAAY,OAAO,kBAAk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ts","../src/api-key.ts"],"sourcesContent":["/**\n * @telamonjs/auth — NextAuth v5 ↔ NestJS auth bridge.\n *\n * Isomorphic core: the session token contract (JWE @auth/core) shared\n * between the Next app and the Nest API. The login authorize() belongs to\n * the app; this package owns the token format, not the login flow.\n *\n * NestJS side (guard + @Public): '@telamonjs/auth/nest'.\n * Next side (callbacks): '@telamonjs/auth/next'.\n */\n\nexport {\n encodeSessionToken,\n decodeSessionToken,\n payloadToAuthUser,\n resolveTokenConfig,\n DEFAULT_SALT,\n DEFAULT_MAX_AGE,\n type TokenConfig,\n} from './jwt'\n\nexport {\n createImpersonationToken,\n DEFAULT_IMPERSONATION_MAX_AGE,\n type ImpersonationParty,\n type CreateImpersonationTokenInput,\n} from './impersonation'\n\nexport {\n stampSessionTimes,\n sessionState,\n type SessionState,\n type SessionMarks,\n type SessionTimes,\n} from './session'\n\nexport { generateApiKey, hashApiKey } from './api-key'\n\nexport type { RoleInfo, AuthUser, MfJwtPayload, JwtPayload } from './types'\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 /**\n * Seconds. Encoding: the token lifetime, default 24h. Decoding (and the\n * guard): only when set, rejects a token issued longer ago than this;\n * unset, the token's own `exp` is the only limit.\n */\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/**\n * Decodes the session JWE. Returns null for an invalid/expired token.\n * An explicit `config.maxAge` also rejects a token issued (`iat`) more than\n * that many seconds ago; without it, only the token's own `exp` applies.\n */\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 })) as MfJwtPayload | null\n if (!payload) return null\n // A token without iat counts as issued at 0: fail closed\n if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1000) {\n return null\n }\n return payload\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","/**\n * Session freshness & revocation — pure, isomorphic, DB-agnostic.\n *\n * Roles/permissions are materialized in the session token, so a change in the\n * database only reaches the token at the next login, and a token cannot be\n * revoked by itself. The app keeps two per-user timestamps (e.g.\n * `accessChangedAt`, `sessionsRevokedAt`) and compares them with the times\n * stamped into the token at login; these helpers do the comparison.\n */\n\n/** Login/claims times stamped into the session token. */\nexport interface SessionTimes {\n /** Login time, epoch ms */\n authTime?: number\n /** When roles/permissions in the token were computed, epoch ms */\n accessAt?: number\n}\n\n/** Per-user marks the app stores. `null`/`undefined` mean \"nothing changed\". */\nexport interface SessionMarks {\n /** Every session that logged in before this instant is revoked */\n revokedAt?: Date | number | null\n /** Roles/permissions changed at this instant */\n accessChangedAt?: Date | number | null\n}\n\n/**\n * - `revoked`: the session must end (sign out / 401)\n * - `stale`: the session is valid, but its roles/permissions must be recomputed\n * - `fresh`: the token is up to date\n */\nexport type SessionState = 'revoked' | 'stale' | 'fresh'\n\n/** Stamps `authTime` and `accessAt` (epoch ms). Mutates and returns the token. */\nexport function stampSessionTimes<T extends object>(\n token: T,\n now: number = Date.now()\n): T & Required<SessionTimes> {\n return Object.assign(token, { authTime: now, accessAt: now })\n}\n\nfunction toMs(mark: Date | number | null | undefined): number | null {\n if (mark == null) return null\n return typeof mark === 'number' ? mark : mark.getTime()\n}\n\n/**\n * Compares the token's times with the user's marks. Revoked wins over stale.\n * A missing claim counts as 0, so tokens issued before adoption are caught by\n * the next revocation/access change.\n */\nexport function sessionState(\n token: SessionTimes,\n marks: SessionMarks\n): SessionState {\n const revokedAt = toMs(marks.revokedAt)\n if (revokedAt !== null && revokedAt > (token.authTime ?? 0)) return 'revoked'\n const accessChangedAt = toMs(marks.accessChangedAt)\n if (accessChangedAt !== null && accessChangedAt > (token.accessAt ?? 0)) {\n return 'stale'\n }\n return 'fresh'\n}\n","import { encodeSessionToken, type TokenConfig } from './jwt'\nimport type { MfJwtPayload, RoleInfo } from './types'\n\n/** Seconds. Impersonation token default: 1h (the normal session is 24h). */\nexport const DEFAULT_IMPERSONATION_MAX_AGE = 60 * 60\n\n/**\n * Data for one side of the impersonation, ALREADY RESOLVED by the app.\n * The package never touches the database — loading the user/roles/permissions\n * is the app's job.\n */\nexport interface ImpersonationParty {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions?: string[]\n}\n\nexport interface CreateImpersonationTokenInput {\n /** User being impersonated — becomes the subject of the token. */\n target: ImpersonationParty & { permissions: string[] }\n /** Admin who started it (becomes the `original*` block). */\n actor: ImpersonationParty\n /** Id of the app's audit record (used by the revocation check in the guard). */\n logId: string\n /** Seconds. Default: `DEFAULT_IMPERSONATION_MAX_AGE` (1h). */\n maxAge?: number\n /**\n * Includes `originalPermissions` in the token. Default: false — it only\n * bloats the payload (chunked cookie) and nothing in the package reads\n * those permissions.\n */\n includeOriginalPermissions?: boolean\n}\n\n/**\n * Issues the impersonation token: a session JWE whose SUBJECT is the target\n * and which carries the actor in the `original*` claims — exactly the shape\n * `payloadToAuthUser` reads back (`isImpersonating` + `originalUser`).\n *\n * The token doubles as a credential: sent as `Authorization: Bearer` it\n * authenticates as the target on the API, with `impersonationLogId` for\n * revocation.\n *\n * ```ts\n * const token = await createImpersonationToken({ target, actor, logId: log.id })\n * ```\n *\n * `iat`/`exp`/`jti` are written by `@auth/core/jwt.encode` — the TTL goes\n * through `maxAge`, never as a claim in the payload.\n */\nexport async function createImpersonationToken(\n {\n target,\n actor,\n logId,\n maxAge,\n includeOriginalPermissions,\n }: CreateImpersonationTokenInput,\n config?: TokenConfig\n): Promise<string> {\n const payload: MfJwtPayload = {\n sub: target.id,\n id: target.id,\n pessoaId: target.pessoaId,\n name: target.name,\n email: target.email,\n role: target.role,\n roles: target.roles ?? [target.role],\n permissions: target.permissions ?? [],\n\n impersonatedUserId: target.id,\n impersonationLogId: logId,\n originalUserId: actor.id,\n originalUserName: actor.name,\n originalUserEmail: actor.email,\n originalUserRole: actor.role,\n originalUserRoles: actor.roles ?? [actor.role],\n }\n\n if (includeOriginalPermissions) {\n payload.originalPermissions = actor.permissions ?? []\n }\n\n return encodeSessionToken(payload, {\n ...config,\n maxAge: maxAge ?? config?.maxAge ?? DEFAULT_IMPERSONATION_MAX_AGE,\n })\n}\n","/**\n * API key helpers for machine-to-machine calls. Isomorphic (Web Crypto, no\n * `node:crypto`), so the core entry still loads in the browser and on the edge.\n * The Nest guard that checks keys lives in '@telamonjs/auth/nest'.\n */\n\n/**\n * A new random API key: 32 bytes as URL-safe base64 (43 characters), after\n * an optional `prefix` (e.g. `'svc_'`, so a leaked key is recognizable).\n * Show it once; store it in an env var, or store `hashApiKey(key)` in the\n * database.\n */\nexport function generateApiKey(prefix = ''): string {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32))\n const base64 = btoa(String.fromCharCode(...bytes))\n return (\n prefix +\n base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n )\n}\n\n/**\n * The hex sha256 of a key — what to store and look up instead of the key\n * itself. Same digest as `createHash('sha256').update(key).digest('hex')`.\n * A random 32-byte key needs no salt or slow hash: there is nothing to\n * brute-force.\n */\nexport async function hashApiKey(key: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(key)\n )\n return Array.from(new Uint8Array(digest), b =>\n b.toString(16).padStart(2, '0')\n ).join('')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAA+B;;;ACkCxB,SAAS,kBACd,OACA,MAAc,KAAK,IAAI,GACK;AAC5B,SAAO,OAAO,OAAO,OAAO,EAAE,UAAU,K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3B,oBAAoB;AAAA,IACpB,gBAAgB,MAAM;AAAA,IACtB,kBAAkB,MAAM;AAAA,IACxB,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB,mBAAmB,MAAM,SAAS,CAAC,MAAM,IAAI;AAAA,EAC/C;AAEA,MAAI,4BAA4B;AAC9B,YAAQ,sBAAsB,MAAM,eAAe,CAAC;AAAA,EACtD;AAEA,SAAO,mBAAmB,SAAS;AAAA,IACjC,GAAG;AAAA,IACH,QAAQ,UAAU,QAAQ,UAAU;AAAA,EACtC,CAAC;AACH;;;AC/EO,SAAS,eAAe,SAAS,IAAY;AAClD,QAAM,QAAQ,WAAW,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC;AAClE,QAAM,SAAS,KAAK,OAAO,aAAa,GAAG,KAAK,CAAC;AACjD,SACE,SACA,OAAO,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE;AAEpE;AAQA,eAAsB,WAAW,KAA8B;AAC7D,QAAM,SAAS,MAAM,WAAW,OAAO,OAAO;AAAA,IAC5C;AAAA,IACA,IAAI,YAAY,EAAE,OAAO,GAAG;AAAA,EAC9B;AACA,SAAO,MAAM;AAAA,IAAK,IAAI,WAAW,MAAM;AAAA,IAAG,OACxC,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAAA,EAChC,EAAE,KAAK,EAAE;AACX;","names":[]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { R as RoleInfo, T as TokenConfig } from './jwt-
|
|
2
|
-
export { A as AuthUser, D as DEFAULT_MAX_AGE, a as DEFAULT_SALT, J as JwtPayload, M as MfJwtPayload, d as decodeSessionToken, e as encodeSessionToken, p as payloadToAuthUser, r as resolveTokenConfig } from './jwt-
|
|
1
|
+
import { R as RoleInfo, T as TokenConfig } from './jwt-EyXe_d9K.cjs';
|
|
2
|
+
export { A as AuthUser, D as DEFAULT_MAX_AGE, a as DEFAULT_SALT, J as JwtPayload, M as MfJwtPayload, d as decodeSessionToken, e as encodeSessionToken, p as payloadToAuthUser, r as resolveTokenConfig } from './jwt-EyXe_d9K.cjs';
|
|
3
3
|
|
|
4
4
|
/** Seconds. Impersonation token default: 1h (the normal session is 24h). */
|
|
5
5
|
declare const DEFAULT_IMPERSONATION_MAX_AGE: number;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { R as RoleInfo, T as TokenConfig } from './jwt-
|
|
2
|
-
export { A as AuthUser, D as DEFAULT_MAX_AGE, a as DEFAULT_SALT, J as JwtPayload, M as MfJwtPayload, d as decodeSessionToken, e as encodeSessionToken, p as payloadToAuthUser, r as resolveTokenConfig } from './jwt-
|
|
1
|
+
import { R as RoleInfo, T as TokenConfig } from './jwt-EyXe_d9K.js';
|
|
2
|
+
export { A as AuthUser, D as DEFAULT_MAX_AGE, a as DEFAULT_SALT, J as JwtPayload, M as MfJwtPayload, d as decodeSessionToken, e as encodeSessionToken, p as payloadToAuthUser, r as resolveTokenConfig } from './jwt-EyXe_d9K.js';
|
|
3
3
|
|
|
4
4
|
/** Seconds. Impersonation token default: 1h (the normal session is 24h). */
|
|
5
5
|
declare const DEFAULT_IMPERSONATION_MAX_AGE: number;
|
package/dist/index.js
CHANGED
|
@@ -75,7 +75,11 @@ interface TokenConfig {
|
|
|
75
75
|
* v4 cookie use 'next-auth.session-token'.
|
|
76
76
|
*/
|
|
77
77
|
salt?: string;
|
|
78
|
-
/**
|
|
78
|
+
/**
|
|
79
|
+
* Seconds. Encoding: the token lifetime, default 24h. Decoding (and the
|
|
80
|
+
* guard): only when set, rejects a token issued longer ago than this;
|
|
81
|
+
* unset, the token's own `exp` is the only limit.
|
|
82
|
+
*/
|
|
79
83
|
maxAge?: number;
|
|
80
84
|
}
|
|
81
85
|
declare const DEFAULT_SALT = "authjs.session-token";
|
|
@@ -89,7 +93,11 @@ declare function resolveTokenConfig(config?: TokenConfig): Required<TokenConfig>
|
|
|
89
93
|
* stamped (on a copy), so `sessionState` does not read it as issued at 0.
|
|
90
94
|
*/
|
|
91
95
|
declare function encodeSessionToken(payload: MfJwtPayload, config?: TokenConfig): Promise<string>;
|
|
92
|
-
/**
|
|
96
|
+
/**
|
|
97
|
+
* Decodes the session JWE. Returns null for an invalid/expired token.
|
|
98
|
+
* An explicit `config.maxAge` also rejects a token issued (`iat`) more than
|
|
99
|
+
* that many seconds ago; without it, only the token's own `exp` applies.
|
|
100
|
+
*/
|
|
93
101
|
declare function decodeSessionToken(token: string, config?: TokenConfig): Promise<MfJwtPayload | null>;
|
|
94
102
|
/**
|
|
95
103
|
* Maps the JWT payload to the request's AuthUser,
|
|
@@ -75,7 +75,11 @@ interface TokenConfig {
|
|
|
75
75
|
* v4 cookie use 'next-auth.session-token'.
|
|
76
76
|
*/
|
|
77
77
|
salt?: string;
|
|
78
|
-
/**
|
|
78
|
+
/**
|
|
79
|
+
* Seconds. Encoding: the token lifetime, default 24h. Decoding (and the
|
|
80
|
+
* guard): only when set, rejects a token issued longer ago than this;
|
|
81
|
+
* unset, the token's own `exp` is the only limit.
|
|
82
|
+
*/
|
|
79
83
|
maxAge?: number;
|
|
80
84
|
}
|
|
81
85
|
declare const DEFAULT_SALT = "authjs.session-token";
|
|
@@ -89,7 +93,11 @@ declare function resolveTokenConfig(config?: TokenConfig): Required<TokenConfig>
|
|
|
89
93
|
* stamped (on a copy), so `sessionState` does not read it as issued at 0.
|
|
90
94
|
*/
|
|
91
95
|
declare function encodeSessionToken(payload: MfJwtPayload, config?: TokenConfig): Promise<string>;
|
|
92
|
-
/**
|
|
96
|
+
/**
|
|
97
|
+
* Decodes the session JWE. Returns null for an invalid/expired token.
|
|
98
|
+
* An explicit `config.maxAge` also rejects a token issued (`iat`) more than
|
|
99
|
+
* that many seconds ago; without it, only the token's own `exp` applies.
|
|
100
|
+
*/
|
|
93
101
|
declare function decodeSessionToken(token: string, config?: TokenConfig): Promise<MfJwtPayload | null>;
|
|
94
102
|
/**
|
|
95
103
|
* Maps the JWT payload to the request's AuthUser,
|
package/dist/nest/index.cjs
CHANGED
|
@@ -62,7 +62,11 @@ async function decodeSessionToken(token, config) {
|
|
|
62
62
|
const { secret, salt } = resolveTokenConfig(config);
|
|
63
63
|
try {
|
|
64
64
|
const payload = await (0, import_jwt.decode)({ token, secret, salt });
|
|
65
|
-
|
|
65
|
+
if (!payload) return null;
|
|
66
|
+
if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1e3) {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
return payload;
|
|
66
70
|
} catch {
|
|
67
71
|
return null;
|
|
68
72
|
}
|
|
@@ -123,7 +127,7 @@ async function verifyApiKey(request, options) {
|
|
|
123
127
|
}
|
|
124
128
|
}
|
|
125
129
|
if (typeof key !== "string" || !key) return null;
|
|
126
|
-
return await options.verify(key, request)
|
|
130
|
+
return await options.verify(key, request) || null;
|
|
127
131
|
}
|
|
128
132
|
function createApiKeyGuard(options) {
|
|
129
133
|
let ApiKeyGuard = class {
|
|
@@ -196,7 +200,7 @@ var JwtAuthGuardBase = class {
|
|
|
196
200
|
};
|
|
197
201
|
function createJwtAuthGuard(options) {
|
|
198
202
|
const salt = options?.salt ?? DEFAULT_SALT;
|
|
199
|
-
const cookieNames = options?.cookieNames ?? [
|
|
203
|
+
const cookieNames = options?.cookieNames ?? [`__Secure-${salt}`, salt];
|
|
200
204
|
const headerSalts = [.../* @__PURE__ */ new Set([salt, ...cookieNames])];
|
|
201
205
|
const unauthorized = (message) => options?.createException?.(401, message) ?? new import_common4.UnauthorizedException(message);
|
|
202
206
|
let warnedIrrevocable = false;
|
|
@@ -232,7 +236,8 @@ function createJwtAuthGuard(options) {
|
|
|
232
236
|
for (const candidateSalt of candidate.salts) {
|
|
233
237
|
const payload = await decodeSessionToken(candidate.token, {
|
|
234
238
|
secret,
|
|
235
|
-
salt: candidateSalt
|
|
239
|
+
salt: candidateSalt,
|
|
240
|
+
maxAge: options?.maxAge
|
|
236
241
|
});
|
|
237
242
|
if (payload) {
|
|
238
243
|
if (payload.impersonatedUserId && options?.isImpersonationActive) {
|
|
@@ -297,6 +302,10 @@ function createJwtAuthGuard(options) {
|
|
|
297
302
|
candidates.push({ token: queryToken, salts: headerSalts });
|
|
298
303
|
}
|
|
299
304
|
for (const name of cookieNames) {
|
|
305
|
+
const secureTwin = `__Secure-${name}`;
|
|
306
|
+
if (cookieNames.includes(secureTwin) && this.readCookie(request, secureTwin)) {
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
300
309
|
const token = this.readCookie(request, name);
|
|
301
310
|
if (token) {
|
|
302
311
|
candidates.push({ token, salts: [.../* @__PURE__ */ new Set([name, salt])] });
|
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","../../src/nest/allow-service-token.decorator.ts","../../src/nest/api-key.guard.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 {\n createApiKeyGuard,\n staticApiKey,\n type ApiKeyGuardOptions,\n type ApiKeyOptions,\n type ApiKeyVerifier,\n type ServicePrincipal,\n} from './api-key.guard'\nexport {\n AllowServiceToken,\n ALLOW_SERVICE_TOKEN_KEY,\n} from './allow-service-token.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'\nimport { ALLOW_SERVICE_TOKEN_KEY } from './allow-service-token.decorator'\nimport { verifyApiKey, type ApiKeyOptions } from './api-key.guard'\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 /** Set by an accepted API key (`createApiKeyGuard`, `apiKey` option). */\n servicePrincipal?: 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 * Lets routes marked `@AllowServiceToken()` take an API key instead of a\n * session. On those routes a valid key passes and attaches the verifier's\n * principal to `request.servicePrincipal` (no `request.user`); no key or a\n * rejected one falls through to the session check. Other routes never read\n * the key. A thrown verifier error propagates.\n *\n * ```ts\n * createJwtAuthGuard({\n * apiKey: { verify: staticApiKey(() => process.env.INTERNAL_API_KEY) },\n * })\n * ```\n */\n apiKey?: ApiKeyOptions<unknown>\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\n if (\n options?.apiKey &&\n this.reflector.getAllAndOverride<boolean>(ALLOW_SERVICE_TOKEN_KEY, [\n context.getHandler(),\n context.getClass(),\n ])\n ) {\n const principal = await verifyApiKey(request, options.apiKey)\n if (principal != null) {\n request.servicePrincipal = principal\n return true\n }\n }\n\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","import { SetMetadata } from '@nestjs/common'\n\nexport const ALLOW_SERVICE_TOKEN_KEY = 'allowServiceToken'\n\n/**\n * Marks a route/controller that accepts an API key as well as a session:\n * a guard built with `createJwtAuthGuard({ apiKey })` lets a valid key through\n * and otherwise runs the normal session check. Unlike `@Public()`, the route\n * is never open.\n */\nexport const AllowServiceToken = () =>\n SetMetadata(ALLOW_SERVICE_TOKEN_KEY, true)\n","import { createHash, timingSafeEqual } from 'node:crypto'\nimport {\n Injectable,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common'\nimport type { RequestLike } from './jwt-auth.guard'\n\n/** What `staticApiKey` resolves to: the name the key was configured with. */\nexport interface ServicePrincipal {\n name: string\n}\n\n/**\n * Checks a key: the principal it belongs to, or `null`/`undefined` to reject.\n * Sync or async, so an env comparison (`staticApiKey`) and a database lookup\n * (by `hashApiKey(key)`) both fit. A thrown error propagates as-is — a\n * database outage is not an invalid key; throw your own exception to send a\n * specific 401/403 body.\n */\nexport type ApiKeyVerifier<TPrincipal> = (\n key: string,\n request: RequestLike\n) => TPrincipal | null | undefined | Promise<TPrincipal | null | undefined>\n\n/** Where the key is read from and how it is checked. */\nexport interface ApiKeyOptions<TPrincipal = ServicePrincipal> {\n verify: ApiKeyVerifier<TPrincipal>\n /** Header holding the key (any case). Default `'x-api-key'`; `false` reads none. */\n header?: string | false\n /** Also read `Authorization: Bearer <key>` (after the header). Default `false`. */\n bearer?: boolean\n}\n\nexport interface ApiKeyGuardOptions<TPrincipal = ServicePrincipal>\n extends ApiKeyOptions<TPrincipal> {\n /** Builds the 401, as in `createJwtAuthGuard` (host's class while linked). */\n createException?: (status: 401 | 403, message: string) => Error\n}\n\nconst INVALID_KEY = 'Invalid or missing API key'\n\n/**\n * Reads the key and runs the verifier: the principal, or `null` when there is\n * no key or the verifier rejects it. Shared with `createJwtAuthGuard({ apiKey })`.\n */\nexport async function verifyApiKey<TPrincipal>(\n request: RequestLike,\n options: ApiKeyOptions<TPrincipal>\n): Promise<TPrincipal | null> {\n const header = options.header ?? 'x-api-key'\n let key = header ? request.headers[header.toLowerCase()] : undefined\n if (!key && options.bearer) {\n const auth = request.headers['authorization']\n if (typeof auth === 'string' && auth.startsWith('Bearer ')) {\n key = auth.slice(7).trim()\n }\n }\n // A repeated header arrives as string[] — ambiguous, so not a key\n if (typeof key !== 'string' || !key) return null\n return (await options.verify(key, request)) ?? null\n}\n\n/**\n * Creates a guard that only accepts an API key: it attaches the verifier's\n * principal to `request.servicePrincipal` (`request.user` stays untouched)\n * and throws a generic 401 otherwise. It logs nothing.\n *\n * ```ts\n * export const InternalKeyGuard = createApiKeyGuard({\n * header: 'x-internal-token',\n * verify: staticApiKey(() => process.env.INTERNAL_API_TOKEN, 'jobs'),\n * })\n *\n * // with a global JwtAuthGuard: @Public() skips the session, the key guard\n * // protects the route\n * @Public()\n * @UseGuards(InternalKeyGuard)\n * @Post('emit')\n * ```\n *\n * It does not read `@Public()`. For a route that takes a key OR a session,\n * use `createJwtAuthGuard({ apiKey })` + `@AllowServiceToken()` instead.\n */\nexport function createApiKeyGuard<TPrincipal = ServicePrincipal>(\n options: ApiKeyGuardOptions<TPrincipal>\n): new () => CanActivate {\n @Injectable()\n class ApiKeyGuard implements CanActivate {\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<RequestLike>()\n const principal = await verifyApiKey(request, options)\n if (principal == null) {\n throw (\n options.createException?.(401, INVALID_KEY) ??\n new UnauthorizedException(INVALID_KEY)\n )\n }\n request.servicePrincipal = principal\n return true\n }\n }\n return ApiKeyGuard\n}\n\nconst sha256 = (value: string): Buffer =>\n createHash('sha256').update(value).digest()\n\n/**\n * Verifier for one shared secret (an env var): compares in constant time\n * (both sides hashed first, so lengths never leak) and resolves to\n * `{ name }`. An unset or empty expected key rejects everything — never open\n * when unconfigured. Pass a function to read the env late (the guard is built\n * at import, before env loading); it is called on every request.\n */\nexport function staticApiKey(\n expected: string | undefined | (() => string | undefined),\n name = 'service'\n): ApiKeyVerifier<ServicePrincipal> {\n return key => {\n const value = typeof expected === 'function' ? expected() : expected\n if (!value || !key) return null\n return timingSafeEqual(sha256(key), sha256(value)) ? { name } : null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;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,QAA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T;AAAA,IAEQ,uBAAuB,SAAwC;AACrE,YAAM,aAA+B,CAAC;AAGtC,YAAM,aAAa,QAAQ,QAAQ,eAAe;AAClD,UAAI,OAAO,eAAe,YAAY,WAAW,WAAW,SAAS,GAAG;AACtE,mBAAW,KAAK,EAAE,OAAO,WAAW,UAAU,CAAC,GAAG,OAAO,YAAY,CAAC;AAAA,MACxE;AAGA,YAAM,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;AAlKM,iBAAN;AAAA,QADC,2BAAW;AAAA,KACN;AAoKN,SAAO;AACT;","names":["import_common","import_common","import_common"]}
|
|
1
|
+
{"version":3,"sources":["../../src/nest/index.ts","../../src/nest/jwt-auth.guard.ts","../../src/jwt.ts","../../src/nest/public.decorator.ts","../../src/nest/allow-service-token.decorator.ts","../../src/nest/api-key.guard.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 {\n createApiKeyGuard,\n staticApiKey,\n type ApiKeyGuardOptions,\n type ApiKeyOptions,\n type ApiKeyVerifier,\n type ServicePrincipal,\n} from './api-key.guard'\nexport {\n AllowServiceToken,\n ALLOW_SERVICE_TOKEN_KEY,\n} from './allow-service-token.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'\nimport { ALLOW_SERVICE_TOKEN_KEY } from './allow-service-token.decorator'\nimport { verifyApiKey, type ApiKeyOptions } from './api-key.guard'\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 /** Set by an accepted API key (`createApiKeyGuard`, `apiKey` option). */\n servicePrincipal?: 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, in priority order.\n * Default: [`__Secure-${salt}`, salt]. The `__Secure-` cookie, which only a\n * secure origin can set, wins, and while it is present (even expired) the\n * plain one is never read. An HTTPS-only deployment passes\n * [`__Secure-${salt}`] so a planted plain cookie is never read at all.\n * Projects that decode with the v5 salt but still serve the legacy cookie\n * 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 * Lets routes marked `@AllowServiceToken()` take an API key instead of a\n * session. On those routes a valid key passes and attaches the verifier's\n * principal to `request.servicePrincipal` (no `request.user`); no key or a\n * rejected one falls through to the session check. Other routes never read\n * the key. A thrown verifier error propagates.\n *\n * ```ts\n * createJwtAuthGuard({\n * apiKey: { verify: staticApiKey(() => process.env.INTERNAL_API_KEY) },\n * })\n * ```\n */\n apiKey?: ApiKeyOptions<unknown>\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 ?? [`__Secure-${salt}`, 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\n if (\n options?.apiKey &&\n this.reflector.getAllAndOverride<boolean>(ALLOW_SERVICE_TOKEN_KEY, [\n context.getHandler(),\n context.getClass(),\n ])\n ) {\n const principal = await verifyApiKey(request, options.apiKey)\n if (principal != null) {\n request.servicePrincipal = principal\n return true\n }\n }\n\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 maxAge: options?.maxAge,\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 // Only a secure origin can set a __Secure- cookie; while it is present\n // (even expired/invalid), its plain twin, which any origin can plant,\n // is never a fallback\n const secureTwin = `__Secure-${name}`\n if (cookieNames.includes(secureTwin) && this.readCookie(request, secureTwin)) {\n continue\n }\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 /**\n * Seconds. Encoding: the token lifetime, default 24h. Decoding (and the\n * guard): only when set, rejects a token issued longer ago than this;\n * unset, the token's own `exp` is the only limit.\n */\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/**\n * Decodes the session JWE. Returns null for an invalid/expired token.\n * An explicit `config.maxAge` also rejects a token issued (`iat`) more than\n * that many seconds ago; without it, only the token's own `exp` applies.\n */\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 })) as MfJwtPayload | null\n if (!payload) return null\n // A token without iat counts as issued at 0: fail closed\n if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1000) {\n return null\n }\n return payload\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","import { SetMetadata } from '@nestjs/common'\n\nexport const ALLOW_SERVICE_TOKEN_KEY = 'allowServiceToken'\n\n/**\n * Marks a route/controller that accepts an API key as well as a session:\n * a guard built with `createJwtAuthGuard({ apiKey })` lets a valid key through\n * and otherwise runs the normal session check. Unlike `@Public()`, the route\n * is never open.\n */\nexport const AllowServiceToken = () =>\n SetMetadata(ALLOW_SERVICE_TOKEN_KEY, true)\n","import { createHash, timingSafeEqual } from 'node:crypto'\nimport {\n Injectable,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common'\nimport type { RequestLike } from './jwt-auth.guard'\n\n/** What `staticApiKey` resolves to: the name the key was configured with. */\nexport interface ServicePrincipal {\n name: string\n}\n\n/**\n * Checks a key: the principal it belongs to, or `null`/`undefined` to reject\n * (any falsy result, `false` included, rejects too).\n * Sync or async, so an env comparison (`staticApiKey`) and a database lookup\n * (by `hashApiKey(key)`) both fit. A thrown error propagates as-is — a\n * database outage is not an invalid key; throw your own exception to send a\n * specific 401/403 body.\n */\nexport type ApiKeyVerifier<TPrincipal> = (\n key: string,\n request: RequestLike\n) => TPrincipal | null | undefined | Promise<TPrincipal | null | undefined>\n\n/** Where the key is read from and how it is checked. */\nexport interface ApiKeyOptions<TPrincipal = ServicePrincipal> {\n verify: ApiKeyVerifier<TPrincipal>\n /** Header holding the key (any case). Default `'x-api-key'`; `false` reads none. */\n header?: string | false\n /** Also read `Authorization: Bearer <key>` (after the header). Default `false`. */\n bearer?: boolean\n}\n\nexport interface ApiKeyGuardOptions<TPrincipal = ServicePrincipal>\n extends ApiKeyOptions<TPrincipal> {\n /** Builds the 401, as in `createJwtAuthGuard` (host's class while linked). */\n createException?: (status: 401 | 403, message: string) => Error\n}\n\nconst INVALID_KEY = 'Invalid or missing API key'\n\n/**\n * Reads the key and runs the verifier: the principal, or `null` when there is\n * no key or the verifier rejects it. Shared with `createJwtAuthGuard({ apiKey })`.\n */\nexport async function verifyApiKey<TPrincipal>(\n request: RequestLike,\n options: ApiKeyOptions<TPrincipal>\n): Promise<TPrincipal | null> {\n const header = options.header ?? 'x-api-key'\n let key = header ? request.headers[header.toLowerCase()] : undefined\n if (!key && options.bearer) {\n const auth = request.headers['authorization']\n if (typeof auth === 'string' && auth.startsWith('Bearer ')) {\n key = auth.slice(7).trim()\n }\n }\n // A repeated header arrives as string[] — ambiguous, so not a key\n if (typeof key !== 'string' || !key) return null\n // Fail closed on every falsy result (false, 0, '', NaN), not only null:\n // a predicate verifier (`key => key === expected`) must not let a wrong key in\n return (await options.verify(key, request)) || null\n}\n\n/**\n * Creates a guard that only accepts an API key: it attaches the verifier's\n * principal to `request.servicePrincipal` (`request.user` stays untouched)\n * and throws a generic 401 otherwise. It logs nothing.\n *\n * ```ts\n * export const InternalKeyGuard = createApiKeyGuard({\n * header: 'x-internal-token',\n * verify: staticApiKey(() => process.env.INTERNAL_API_TOKEN, 'jobs'),\n * })\n *\n * // with a global JwtAuthGuard: @Public() skips the session, the key guard\n * // protects the route\n * @Public()\n * @UseGuards(InternalKeyGuard)\n * @Post('emit')\n * ```\n *\n * It does not read `@Public()`. For a route that takes a key OR a session,\n * use `createJwtAuthGuard({ apiKey })` + `@AllowServiceToken()` instead.\n */\nexport function createApiKeyGuard<TPrincipal = ServicePrincipal>(\n options: ApiKeyGuardOptions<TPrincipal>\n): new () => CanActivate {\n @Injectable()\n class ApiKeyGuard implements CanActivate {\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<RequestLike>()\n const principal = await verifyApiKey(request, options)\n if (principal == null) {\n throw (\n options.createException?.(401, INVALID_KEY) ??\n new UnauthorizedException(INVALID_KEY)\n )\n }\n request.servicePrincipal = principal\n return true\n }\n }\n return ApiKeyGuard\n}\n\nconst sha256 = (value: string): Buffer =>\n createHash('sha256').update(value).digest()\n\n/**\n * Verifier for one shared secret (an env var): compares in constant time\n * (both sides hashed first, so lengths never leak) and resolves to\n * `{ name }`. An unset or empty expected key rejects everything — never open\n * when unconfigured. Pass a function to read the env late (the guard is built\n * at import, before env loading); it is called on every request.\n */\nexport function staticApiKey(\n expected: string | undefined | (() => string | undefined),\n name = 'service'\n): ApiKeyVerifier<ServicePrincipal> {\n return key => {\n const value = typeof expected === 'function' ? expected() : expected\n if (!value || !key) return null\n return timingSafeEqual(sha256(key), sha256(value)) ? { name } : null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAMO;AACP,kBAA0B;;;ACP1B,iBAA+B;AAqBxB,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;AAwBA,eAAsB,mBACpB,OACA,QAC8B;AAC9B,QAAM,EAAE,QAAQ,KAAK,IAAI,mBAAmB,MAAM;AAClD,MAAI;AACF,UAAM,UAAW,UAAM,mBAAO,EAAE,OAAO,QAAQ,KAAK,CAAC;AACrD,QAAI,CAAC,QAAS,QAAO;AAErB,QAAI,QAAQ,UAAU,SAAS,QAAQ,OAAO,KAAK,OAAO,SAAS,KAAK,IAAI,IAAI,KAAM;AACpF,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,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,QA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2BAAW;AAAA,KACN;AA4KN,SAAO;AACT;","names":["import_common","import_common","import_common"]}
|
package/dist/nest/index.d.cts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import * as _nestjs_common from '@nestjs/common';
|
|
2
2
|
import { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
3
3
|
import { Reflector } from '@nestjs/core';
|
|
4
|
-
import { M as MfJwtPayload, T as TokenConfig, A as AuthUser } from '../jwt-
|
|
5
|
-
export { J as JwtPayload, R as RoleInfo } from '../jwt-
|
|
4
|
+
import { M as MfJwtPayload, T as TokenConfig, A as AuthUser } from '../jwt-EyXe_d9K.cjs';
|
|
5
|
+
export { J as JwtPayload, R as RoleInfo } from '../jwt-EyXe_d9K.cjs';
|
|
6
6
|
|
|
7
7
|
/** What `staticApiKey` resolves to: the name the key was configured with. */
|
|
8
8
|
interface ServicePrincipal {
|
|
9
9
|
name: string;
|
|
10
10
|
}
|
|
11
11
|
/**
|
|
12
|
-
* Checks a key: the principal it belongs to, or `null`/`undefined` to reject
|
|
12
|
+
* Checks a key: the principal it belongs to, or `null`/`undefined` to reject
|
|
13
|
+
* (any falsy result, `false` included, rejects too).
|
|
13
14
|
* Sync or async, so an env comparison (`staticApiKey`) and a database lookup
|
|
14
15
|
* (by `hashApiKey(key)`) both fit. A thrown error propagates as-is — a
|
|
15
16
|
* database outage is not an invalid key; throw your own exception to send a
|
|
@@ -104,9 +105,13 @@ interface JwtAuthGuardOptions extends Omit<TokenConfig, 'secret'> {
|
|
|
104
105
|
*/
|
|
105
106
|
createException?: (status: 401 | 403, message: string) => Error;
|
|
106
107
|
/**
|
|
107
|
-
* Cookie names to look for the session token in.
|
|
108
|
-
* Default: [
|
|
109
|
-
*
|
|
108
|
+
* Cookie names to look for the session token in, in priority order.
|
|
109
|
+
* Default: [`__Secure-${salt}`, salt]. The `__Secure-` cookie, which only a
|
|
110
|
+
* secure origin can set, wins, and while it is present (even expired) the
|
|
111
|
+
* plain one is never read. An HTTPS-only deployment passes
|
|
112
|
+
* [`__Secure-${salt}`] so a planted plain cookie is never read at all.
|
|
113
|
+
* Projects that decode with the v5 salt but still serve the legacy cookie
|
|
114
|
+
* pass ['next-auth.session-token', ...].
|
|
110
115
|
*/
|
|
111
116
|
cookieNames?: string[];
|
|
112
117
|
/**
|
package/dist/nest/index.d.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import * as _nestjs_common from '@nestjs/common';
|
|
2
2
|
import { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
3
3
|
import { Reflector } from '@nestjs/core';
|
|
4
|
-
import { M as MfJwtPayload, T as TokenConfig, A as AuthUser } from '../jwt-
|
|
5
|
-
export { J as JwtPayload, R as RoleInfo } from '../jwt-
|
|
4
|
+
import { M as MfJwtPayload, T as TokenConfig, A as AuthUser } from '../jwt-EyXe_d9K.js';
|
|
5
|
+
export { J as JwtPayload, R as RoleInfo } from '../jwt-EyXe_d9K.js';
|
|
6
6
|
|
|
7
7
|
/** What `staticApiKey` resolves to: the name the key was configured with. */
|
|
8
8
|
interface ServicePrincipal {
|
|
9
9
|
name: string;
|
|
10
10
|
}
|
|
11
11
|
/**
|
|
12
|
-
* Checks a key: the principal it belongs to, or `null`/`undefined` to reject
|
|
12
|
+
* Checks a key: the principal it belongs to, or `null`/`undefined` to reject
|
|
13
|
+
* (any falsy result, `false` included, rejects too).
|
|
13
14
|
* Sync or async, so an env comparison (`staticApiKey`) and a database lookup
|
|
14
15
|
* (by `hashApiKey(key)`) both fit. A thrown error propagates as-is — a
|
|
15
16
|
* database outage is not an invalid key; throw your own exception to send a
|
|
@@ -104,9 +105,13 @@ interface JwtAuthGuardOptions extends Omit<TokenConfig, 'secret'> {
|
|
|
104
105
|
*/
|
|
105
106
|
createException?: (status: 401 | 403, message: string) => Error;
|
|
106
107
|
/**
|
|
107
|
-
* Cookie names to look for the session token in.
|
|
108
|
-
* Default: [
|
|
109
|
-
*
|
|
108
|
+
* Cookie names to look for the session token in, in priority order.
|
|
109
|
+
* Default: [`__Secure-${salt}`, salt]. The `__Secure-` cookie, which only a
|
|
110
|
+
* secure origin can set, wins, and while it is present (even expired) the
|
|
111
|
+
* plain one is never read. An HTTPS-only deployment passes
|
|
112
|
+
* [`__Secure-${salt}`] so a planted plain cookie is never read at all.
|
|
113
|
+
* Projects that decode with the v5 salt but still serve the legacy cookie
|
|
114
|
+
* pass ['next-auth.session-token', ...].
|
|
110
115
|
*/
|
|
111
116
|
cookieNames?: string[];
|
|
112
117
|
/**
|
package/dist/nest/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
__decorateClass,
|
|
4
4
|
decodeSessionToken,
|
|
5
5
|
payloadToAuthUser
|
|
6
|
-
} from "../chunk-
|
|
6
|
+
} from "../chunk-G73ASFMN.js";
|
|
7
7
|
|
|
8
8
|
// src/nest/jwt-auth.guard.ts
|
|
9
9
|
import {
|
|
@@ -40,7 +40,7 @@ async function verifyApiKey(request, options) {
|
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
42
|
if (typeof key !== "string" || !key) return null;
|
|
43
|
-
return await options.verify(key, request)
|
|
43
|
+
return await options.verify(key, request) || null;
|
|
44
44
|
}
|
|
45
45
|
function createApiKeyGuard(options) {
|
|
46
46
|
let ApiKeyGuard = class {
|
|
@@ -113,7 +113,7 @@ var JwtAuthGuardBase = class {
|
|
|
113
113
|
};
|
|
114
114
|
function createJwtAuthGuard(options) {
|
|
115
115
|
const salt = options?.salt ?? DEFAULT_SALT;
|
|
116
|
-
const cookieNames = options?.cookieNames ?? [
|
|
116
|
+
const cookieNames = options?.cookieNames ?? [`__Secure-${salt}`, salt];
|
|
117
117
|
const headerSalts = [.../* @__PURE__ */ new Set([salt, ...cookieNames])];
|
|
118
118
|
const unauthorized = (message) => options?.createException?.(401, message) ?? new UnauthorizedException2(message);
|
|
119
119
|
let warnedIrrevocable = false;
|
|
@@ -149,7 +149,8 @@ function createJwtAuthGuard(options) {
|
|
|
149
149
|
for (const candidateSalt of candidate.salts) {
|
|
150
150
|
const payload = await decodeSessionToken(candidate.token, {
|
|
151
151
|
secret,
|
|
152
|
-
salt: candidateSalt
|
|
152
|
+
salt: candidateSalt,
|
|
153
|
+
maxAge: options?.maxAge
|
|
153
154
|
});
|
|
154
155
|
if (payload) {
|
|
155
156
|
if (payload.impersonatedUserId && options?.isImpersonationActive) {
|
|
@@ -214,6 +215,10 @@ function createJwtAuthGuard(options) {
|
|
|
214
215
|
candidates.push({ token: queryToken, salts: headerSalts });
|
|
215
216
|
}
|
|
216
217
|
for (const name of cookieNames) {
|
|
218
|
+
const secureTwin = `__Secure-${name}`;
|
|
219
|
+
if (cookieNames.includes(secureTwin) && this.readCookie(request, secureTwin)) {
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
217
222
|
const token = this.readCookie(request, name);
|
|
218
223
|
if (token) {
|
|
219
224
|
candidates.push({ token, salts: [.../* @__PURE__ */ new Set([name, salt])] });
|
package/dist/nest/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/nest/jwt-auth.guard.ts","../../src/nest/public.decorator.ts","../../src/nest/allow-service-token.decorator.ts","../../src/nest/api-key.guard.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'\nimport { ALLOW_SERVICE_TOKEN_KEY } from './allow-service-token.decorator'\nimport { verifyApiKey, type ApiKeyOptions } from './api-key.guard'\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 /** Set by an accepted API key (`createApiKeyGuard`, `apiKey` option). */\n servicePrincipal?: 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 * Lets routes marked `@AllowServiceToken()` take an API key instead of a\n * session. On those routes a valid key passes and attaches the verifier's\n * principal to `request.servicePrincipal` (no `request.user`); no key or a\n * rejected one falls through to the session check. Other routes never read\n * the key. A thrown verifier error propagates.\n *\n * ```ts\n * createJwtAuthGuard({\n * apiKey: { verify: staticApiKey(() => process.env.INTERNAL_API_KEY) },\n * })\n * ```\n */\n apiKey?: ApiKeyOptions<unknown>\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\n if (\n options?.apiKey &&\n this.reflector.getAllAndOverride<boolean>(ALLOW_SERVICE_TOKEN_KEY, [\n context.getHandler(),\n context.getClass(),\n ])\n ) {\n const principal = await verifyApiKey(request, options.apiKey)\n if (principal != null) {\n request.servicePrincipal = principal\n return true\n }\n }\n\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","import { SetMetadata } from '@nestjs/common'\n\nexport const ALLOW_SERVICE_TOKEN_KEY = 'allowServiceToken'\n\n/**\n * Marks a route/controller that accepts an API key as well as a session:\n * a guard built with `createJwtAuthGuard({ apiKey })` lets a valid key through\n * and otherwise runs the normal session check. Unlike `@Public()`, the route\n * is never open.\n */\nexport const AllowServiceToken = () =>\n SetMetadata(ALLOW_SERVICE_TOKEN_KEY, true)\n","import { createHash, timingSafeEqual } from 'node:crypto'\nimport {\n Injectable,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common'\nimport type { RequestLike } from './jwt-auth.guard'\n\n/** What `staticApiKey` resolves to: the name the key was configured with. */\nexport interface ServicePrincipal {\n name: string\n}\n\n/**\n * Checks a key: the principal it belongs to, or `null`/`undefined` to reject.\n * Sync or async, so an env comparison (`staticApiKey`) and a database lookup\n * (by `hashApiKey(key)`) both fit. A thrown error propagates as-is — a\n * database outage is not an invalid key; throw your own exception to send a\n * specific 401/403 body.\n */\nexport type ApiKeyVerifier<TPrincipal> = (\n key: string,\n request: RequestLike\n) => TPrincipal | null | undefined | Promise<TPrincipal | null | undefined>\n\n/** Where the key is read from and how it is checked. */\nexport interface ApiKeyOptions<TPrincipal = ServicePrincipal> {\n verify: ApiKeyVerifier<TPrincipal>\n /** Header holding the key (any case). Default `'x-api-key'`; `false` reads none. */\n header?: string | false\n /** Also read `Authorization: Bearer <key>` (after the header). Default `false`. */\n bearer?: boolean\n}\n\nexport interface ApiKeyGuardOptions<TPrincipal = ServicePrincipal>\n extends ApiKeyOptions<TPrincipal> {\n /** Builds the 401, as in `createJwtAuthGuard` (host's class while linked). */\n createException?: (status: 401 | 403, message: string) => Error\n}\n\nconst INVALID_KEY = 'Invalid or missing API key'\n\n/**\n * Reads the key and runs the verifier: the principal, or `null` when there is\n * no key or the verifier rejects it. Shared with `createJwtAuthGuard({ apiKey })`.\n */\nexport async function verifyApiKey<TPrincipal>(\n request: RequestLike,\n options: ApiKeyOptions<TPrincipal>\n): Promise<TPrincipal | null> {\n const header = options.header ?? 'x-api-key'\n let key = header ? request.headers[header.toLowerCase()] : undefined\n if (!key && options.bearer) {\n const auth = request.headers['authorization']\n if (typeof auth === 'string' && auth.startsWith('Bearer ')) {\n key = auth.slice(7).trim()\n }\n }\n // A repeated header arrives as string[] — ambiguous, so not a key\n if (typeof key !== 'string' || !key) return null\n return (await options.verify(key, request)) ?? null\n}\n\n/**\n * Creates a guard that only accepts an API key: it attaches the verifier's\n * principal to `request.servicePrincipal` (`request.user` stays untouched)\n * and throws a generic 401 otherwise. It logs nothing.\n *\n * ```ts\n * export const InternalKeyGuard = createApiKeyGuard({\n * header: 'x-internal-token',\n * verify: staticApiKey(() => process.env.INTERNAL_API_TOKEN, 'jobs'),\n * })\n *\n * // with a global JwtAuthGuard: @Public() skips the session, the key guard\n * // protects the route\n * @Public()\n * @UseGuards(InternalKeyGuard)\n * @Post('emit')\n * ```\n *\n * It does not read `@Public()`. For a route that takes a key OR a session,\n * use `createJwtAuthGuard({ apiKey })` + `@AllowServiceToken()` instead.\n */\nexport function createApiKeyGuard<TPrincipal = ServicePrincipal>(\n options: ApiKeyGuardOptions<TPrincipal>\n): new () => CanActivate {\n @Injectable()\n class ApiKeyGuard implements CanActivate {\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<RequestLike>()\n const principal = await verifyApiKey(request, options)\n if (principal == null) {\n throw (\n options.createException?.(401, INVALID_KEY) ??\n new UnauthorizedException(INVALID_KEY)\n )\n }\n request.servicePrincipal = principal\n return true\n }\n }\n return ApiKeyGuard\n}\n\nconst sha256 = (value: string): Buffer =>\n createHash('sha256').update(value).digest()\n\n/**\n * Verifier for one shared secret (an env var): compares in constant time\n * (both sides hashed first, so lengths never leak) and resolves to\n * `{ name }`. An unset or empty expected key rejects everything — never open\n * when unconfigured. Pass a function to read the env late (the guard is built\n * at import, before env loading); it is called on every request.\n */\nexport function staticApiKey(\n expected: string | undefined | (() => string | undefined),\n name = 'service'\n): ApiKeyVerifier<ServicePrincipal> {\n return key => {\n const value = typeof expected === 'function' ? expected() : expected\n if (!value || !key) return null\n return timingSafeEqual(sha256(key), sha256(value)) ? { name } : null\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAAA,EACE,cAAAA;AAAA,EACA;AAAA,EACA,yBAAAC;AAAA,OAGK;AACP,SAAS,iBAAiB;;;ACP1B,SAAS,mBAAmB;AAErB,IAAM,gBAAgB;AAMtB,IAAM,SAAS,MAAM,YAAY,eAAe,IAAI;;;ACR3D,SAAS,eAAAC,oBAAmB;AAErB,IAAM,0BAA0B;AAQhC,IAAM,oBAAoB,MAC/BA,aAAY,yBAAyB,IAAI;;;ACX3C,SAAS,YAAY,uBAAuB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAmCP,IAAM,cAAc;AAMpB,eAAsB,aACpB,SACA,SAC4B;AAC5B,QAAM,SAAS,QAAQ,UAAU;AACjC,MAAI,MAA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AAC,EAAE;AACpC,YAAI,UAAU,OAAW;AACzB,qBAAa;AAAA,MACf;AACA,aAAO,aAAa;AAAA,IACtB;AAAA,EACF;AAlKM,iBAAN;AAAA,IADCC,YAAW;AAAA,KACN;AAoKN,SAAO;AACT;","names":["Injectable","UnauthorizedException","SetMetadata","UnauthorizedException","Injectable"]}
|
|
1
|
+
{"version":3,"sources":["../../src/nest/jwt-auth.guard.ts","../../src/nest/public.decorator.ts","../../src/nest/allow-service-token.decorator.ts","../../src/nest/api-key.guard.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'\nimport { ALLOW_SERVICE_TOKEN_KEY } from './allow-service-token.decorator'\nimport { verifyApiKey, type ApiKeyOptions } from './api-key.guard'\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 /** Set by an accepted API key (`createApiKeyGuard`, `apiKey` option). */\n servicePrincipal?: 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, in priority order.\n * Default: [`__Secure-${salt}`, salt]. The `__Secure-` cookie, which only a\n * secure origin can set, wins, and while it is present (even expired) the\n * plain one is never read. An HTTPS-only deployment passes\n * [`__Secure-${salt}`] so a planted plain cookie is never read at all.\n * Projects that decode with the v5 salt but still serve the legacy cookie\n * 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 * Lets routes marked `@AllowServiceToken()` take an API key instead of a\n * session. On those routes a valid key passes and attaches the verifier's\n * principal to `request.servicePrincipal` (no `request.user`); no key or a\n * rejected one falls through to the session check. Other routes never read\n * the key. A thrown verifier error propagates.\n *\n * ```ts\n * createJwtAuthGuard({\n * apiKey: { verify: staticApiKey(() => process.env.INTERNAL_API_KEY) },\n * })\n * ```\n */\n apiKey?: ApiKeyOptions<unknown>\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 ?? [`__Secure-${salt}`, 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\n if (\n options?.apiKey &&\n this.reflector.getAllAndOverride<boolean>(ALLOW_SERVICE_TOKEN_KEY, [\n context.getHandler(),\n context.getClass(),\n ])\n ) {\n const principal = await verifyApiKey(request, options.apiKey)\n if (principal != null) {\n request.servicePrincipal = principal\n return true\n }\n }\n\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 maxAge: options?.maxAge,\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 // Only a secure origin can set a __Secure- cookie; while it is present\n // (even expired/invalid), its plain twin, which any origin can plant,\n // is never a fallback\n const secureTwin = `__Secure-${name}`\n if (cookieNames.includes(secureTwin) && this.readCookie(request, secureTwin)) {\n continue\n }\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","import { SetMetadata } from '@nestjs/common'\n\nexport const ALLOW_SERVICE_TOKEN_KEY = 'allowServiceToken'\n\n/**\n * Marks a route/controller that accepts an API key as well as a session:\n * a guard built with `createJwtAuthGuard({ apiKey })` lets a valid key through\n * and otherwise runs the normal session check. Unlike `@Public()`, the route\n * is never open.\n */\nexport const AllowServiceToken = () =>\n SetMetadata(ALLOW_SERVICE_TOKEN_KEY, true)\n","import { createHash, timingSafeEqual } from 'node:crypto'\nimport {\n Injectable,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@nestjs/common'\nimport type { RequestLike } from './jwt-auth.guard'\n\n/** What `staticApiKey` resolves to: the name the key was configured with. */\nexport interface ServicePrincipal {\n name: string\n}\n\n/**\n * Checks a key: the principal it belongs to, or `null`/`undefined` to reject\n * (any falsy result, `false` included, rejects too).\n * Sync or async, so an env comparison (`staticApiKey`) and a database lookup\n * (by `hashApiKey(key)`) both fit. A thrown error propagates as-is — a\n * database outage is not an invalid key; throw your own exception to send a\n * specific 401/403 body.\n */\nexport type ApiKeyVerifier<TPrincipal> = (\n key: string,\n request: RequestLike\n) => TPrincipal | null | undefined | Promise<TPrincipal | null | undefined>\n\n/** Where the key is read from and how it is checked. */\nexport interface ApiKeyOptions<TPrincipal = ServicePrincipal> {\n verify: ApiKeyVerifier<TPrincipal>\n /** Header holding the key (any case). Default `'x-api-key'`; `false` reads none. */\n header?: string | false\n /** Also read `Authorization: Bearer <key>` (after the header). Default `false`. */\n bearer?: boolean\n}\n\nexport interface ApiKeyGuardOptions<TPrincipal = ServicePrincipal>\n extends ApiKeyOptions<TPrincipal> {\n /** Builds the 401, as in `createJwtAuthGuard` (host's class while linked). */\n createException?: (status: 401 | 403, message: string) => Error\n}\n\nconst INVALID_KEY = 'Invalid or missing API key'\n\n/**\n * Reads the key and runs the verifier: the principal, or `null` when there is\n * no key or the verifier rejects it. Shared with `createJwtAuthGuard({ apiKey })`.\n */\nexport async function verifyApiKey<TPrincipal>(\n request: RequestLike,\n options: ApiKeyOptions<TPrincipal>\n): Promise<TPrincipal | null> {\n const header = options.header ?? 'x-api-key'\n let key = header ? request.headers[header.toLowerCase()] : undefined\n if (!key && options.bearer) {\n const auth = request.headers['authorization']\n if (typeof auth === 'string' && auth.startsWith('Bearer ')) {\n key = auth.slice(7).trim()\n }\n }\n // A repeated header arrives as string[] — ambiguous, so not a key\n if (typeof key !== 'string' || !key) return null\n // Fail closed on every falsy result (false, 0, '', NaN), not only null:\n // a predicate verifier (`key => key === expected`) must not let a wrong key in\n return (await options.verify(key, request)) || null\n}\n\n/**\n * Creates a guard that only accepts an API key: it attaches the verifier's\n * principal to `request.servicePrincipal` (`request.user` stays untouched)\n * and throws a generic 401 otherwise. It logs nothing.\n *\n * ```ts\n * export const InternalKeyGuard = createApiKeyGuard({\n * header: 'x-internal-token',\n * verify: staticApiKey(() => process.env.INTERNAL_API_TOKEN, 'jobs'),\n * })\n *\n * // with a global JwtAuthGuard: @Public() skips the session, the key guard\n * // protects the route\n * @Public()\n * @UseGuards(InternalKeyGuard)\n * @Post('emit')\n * ```\n *\n * It does not read `@Public()`. For a route that takes a key OR a session,\n * use `createJwtAuthGuard({ apiKey })` + `@AllowServiceToken()` instead.\n */\nexport function createApiKeyGuard<TPrincipal = ServicePrincipal>(\n options: ApiKeyGuardOptions<TPrincipal>\n): new () => CanActivate {\n @Injectable()\n class ApiKeyGuard implements CanActivate {\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<RequestLike>()\n const principal = await verifyApiKey(request, options)\n if (principal == null) {\n throw (\n options.createException?.(401, INVALID_KEY) ??\n new UnauthorizedException(INVALID_KEY)\n )\n }\n request.servicePrincipal = principal\n return true\n }\n }\n return ApiKeyGuard\n}\n\nconst sha256 = (value: string): Buffer =>\n createHash('sha256').update(value).digest()\n\n/**\n * Verifier for one shared secret (an env var): compares in constant time\n * (both sides hashed first, so lengths never leak) and resolves to\n * `{ name }`. An unset or empty expected key rejects everything — never open\n * when unconfigured. Pass a function to read the env late (the guard is built\n * at import, before env loading); it is called on every request.\n */\nexport function staticApiKey(\n expected: string | undefined | (() => string | undefined),\n name = 'service'\n): ApiKeyVerifier<ServicePrincipal> {\n return key => {\n const value = typeof expected === 'function' ? expected() : expected\n if (!value || !key) return null\n return timingSafeEqual(sha256(key), sha256(value)) ? { name } : null\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAAA,EACE,cAAAA;AAAA,EACA;AAAA,EACA,yBAAAC;AAAA,OAGK;AACP,SAAS,iBAAiB;;;ACP1B,SAAS,mBAAmB;AAErB,IAAM,gBAAgB;AAMtB,IAAM,SAAS,MAAM,YAAY,eAAe,IAAI;;;ACR3D,SAAS,eAAAC,oBAAmB;AAErB,IAAM,0BAA0B;AAQhC,IAAM,oBAAoB,MAC/BA,aAAY,yBAAyB,IAAI;;;ACX3C,SAAS,YAAY,uBAAuB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAoCP,IAAM,cAAc;AAMpB,eAAsB,aACpB,SACA,SAC4B;AAC5B,QAAM,SAAS,QAAQ,UAAU;AACjC,MAAI,MAAM,SAAS,QAAQ,QAAQ,OAAO,YAAY,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,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;AA1KM,iBAAN;AAAA,IADCC,YAAW;AAAA,KACN;AA4KN,SAAO;AACT;","names":["Injectable","UnauthorizedException","SetMetadata","UnauthorizedException","Injectable"]}
|
package/dist/next/index.cjs
CHANGED
|
@@ -50,7 +50,11 @@ async function decodeSessionToken(token, config) {
|
|
|
50
50
|
const { secret, salt } = resolveTokenConfig(config);
|
|
51
51
|
try {
|
|
52
52
|
const payload = await (0, import_jwt.decode)({ token, secret, salt });
|
|
53
|
-
|
|
53
|
+
if (!payload) return null;
|
|
54
|
+
if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1e3) {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
return payload;
|
|
54
58
|
} catch {
|
|
55
59
|
return null;
|
|
56
60
|
}
|
|
@@ -65,7 +69,10 @@ var IMPERSONATION_SWAP = {
|
|
|
65
69
|
role: "originalUserRole",
|
|
66
70
|
roles: "originalUserRoles",
|
|
67
71
|
permissions: "originalPermissions",
|
|
68
|
-
accessToken: "originalAccessToken"
|
|
72
|
+
accessToken: "originalAccessToken",
|
|
73
|
+
// when the actor's permissions above were computed: restored with them, so
|
|
74
|
+
// a target-side refresh during impersonation cannot hide an actor change
|
|
75
|
+
accessAt: "originalAccessAt"
|
|
69
76
|
};
|
|
70
77
|
function restoreActor(token) {
|
|
71
78
|
if (token.originalUserId) {
|
|
@@ -87,10 +94,12 @@ async function applyImpersonation(token, options) {
|
|
|
87
94
|
if (token.impersonatedUserId) restoreActor(token);
|
|
88
95
|
return;
|
|
89
96
|
}
|
|
90
|
-
const
|
|
97
|
+
const decoded = await decodeSessionToken(
|
|
91
98
|
impersonationToken,
|
|
92
99
|
options.tokenConfig
|
|
93
100
|
);
|
|
101
|
+
const actorId = token.originalUserId ?? token.id;
|
|
102
|
+
const payload = decoded?.impersonatedUserId && decoded.impersonationLogId && decoded.originalUserId && decoded.originalUserId === actorId ? decoded : null;
|
|
94
103
|
if (!payload) {
|
|
95
104
|
if (!token.impersonatedUserId) return;
|
|
96
105
|
restoreActor(token);
|
|
@@ -112,7 +121,7 @@ async function applyImpersonation(token, options) {
|
|
|
112
121
|
token.permissions = payload.permissions ?? [];
|
|
113
122
|
token.accessToken = payload.accessToken ?? impersonationToken;
|
|
114
123
|
token.impersonatedUserId = payload.id;
|
|
115
|
-
token.impersonationLogId = payload.impersonationLogId
|
|
124
|
+
token.impersonationLogId = payload.impersonationLogId;
|
|
116
125
|
token.isImpersonating = true;
|
|
117
126
|
}
|
|
118
127
|
function createAuthCallbacks(options = {}) {
|
package/dist/next/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next/index.ts","../../src/jwt.ts","../../src/session.ts"],"sourcesContent":["import { decodeSessionToken, type TokenConfig } from '../jwt'\nimport { stampSessionTimes } from '../session'\nimport type { MfJwtPayload, RoleInfo } from '../types'\n\n/**\n * Canonical claims the app's authorize() must return on the user object\n * so the callbacks can copy them into the token.\n */\nexport interface SessionClaims {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions: string[]\n accessToken?: string\n refreshToken?: string\n /** Stable per-login session id, kept across cookie renewals */\n sid?: string\n /** Login time, epoch ms. Stamped by `jwt` at login — authorize() need not return it */\n authTime?: number\n /** When roles/permissions were computed, epoch ms. Stamped by `jwt` at login */\n accessAt?: number\n}\n\n/** Impersonation cookies read by the app (the package does not import next/headers). */\nexport interface ImpersonationCookies {\n /** Token issued by `createImpersonationToken` */\n token?: string\n /** Audit log id */\n logId?: string\n}\n\nexport interface AuthCallbacksOptions {\n /**\n * Enables impersonation in the callbacks (opt-in). Reads the cookies in the app:\n *\n * ```ts\n * createAuthCallbacks({\n * getImpersonationCookies: async () => {\n * const c = await cookies()\n * return {\n * token: c.get('impersonation-token')?.value,\n * logId: c.get('impersonation-log-id')?.value\n * }\n * },\n * clearImpersonationCookies: async () => {\n * const c = await cookies()\n * c.delete('impersonation-token')\n * c.delete('impersonation-log-id')\n * }\n * })\n * ```\n */\n getImpersonationCookies?: () => Promise<\n ImpersonationCookies | null | undefined\n >\n /** Called when the impersonation token expires or is invalid. Optional. */\n clearImpersonationCookies?: () => Promise<void> | void\n /** secret/salt to decode the impersonation token. Default: env + v5 salt. */\n tokenConfig?: TokenConfig\n}\n\n/**\n * Token field ↔ claim where the ACTOR's value is kept while impersonation\n * is active. `refreshToken` is left out on purpose: it stays the actor's,\n * which is what keeps the session refresh healthy.\n */\nconst IMPERSONATION_SWAP = {\n id: 'originalUserId',\n pessoaId: 'originalPessoaId',\n name: 'originalUserName',\n email: 'originalUserEmail',\n role: 'originalUserRole',\n roles: 'originalUserRoles',\n permissions: 'originalPermissions',\n accessToken: 'originalAccessToken',\n} as const\n\ntype MutableToken = Record<string, unknown>\n\n/** Ends the impersonation: restores the actor's values and clears the claims. */\nfunction restoreActor(token: MutableToken): void {\n if (token.originalUserId) {\n for (const [field, claim] of Object.entries(IMPERSONATION_SWAP)) {\n token[field] = token[claim]\n }\n }\n for (const claim of Object.values(IMPERSONATION_SWAP)) delete token[claim]\n delete token.impersonatedUserId\n delete token.impersonationLogId\n delete token.isImpersonating\n}\n\nasync function applyImpersonation(\n token: MutableToken,\n options: AuthCallbacksOptions\n): Promise<void> {\n // The expiry flag lives for EXACTLY one cycle: set below on restore,\n // read by `session` in the same pass, deleted here on the next pass.\n delete token.impersonationExpired\n\n const cookies = await options.getImpersonationCookies?.()\n const impersonationToken = cookies?.token\n const logId = cookies?.logId\n\n if (!impersonationToken || !logId) {\n // Cookie is gone (stop-impersonate) → back to the actor, silently.\n if (token.impersonatedUserId) restoreActor(token)\n return\n }\n\n const payload = await decodeSessionToken(\n impersonationToken,\n options.tokenConfig\n )\n\n if (!payload) {\n // Expired/invalid. Orphan cookie with no active impersonation: ignore.\n if (!token.impersonatedUserId) return\n restoreActor(token)\n token.impersonationExpired = true\n await options.clearImpersonationCookies?.()\n return\n }\n\n if (!token.originalUserId) {\n for (const [field, claim] of Object.entries(IMPERSONATION_SWAP)) {\n token[claim] = token[field]\n }\n }\n\n token.id = payload.id\n token.pessoaId = payload.pessoaId\n token.name = payload.name\n token.email = payload.email\n token.role = payload.role\n token.roles = payload.roles ?? (payload.role ? [payload.role] : [])\n token.permissions = payload.permissions ?? []\n // The impersonation token IS the API credential. Without swapping the\n // accessToken the impersonation is merely cosmetic: the UI shows the target\n // while API calls keep going out with the admin's credential.\n token.accessToken = payload.accessToken ?? impersonationToken\n token.impersonatedUserId = payload.id\n token.impersonationLogId = payload.impersonationLogId ?? logId\n token.isImpersonating = true\n}\n\ntype JwtArgs = { token: Record<string, unknown>; user?: unknown }\n// Generic over the app's session type (next-auth's `Session` is an interface\n// without an index signature), so `base.session` plugs straight into\n// `callbacks.session` and keeps fields like `expires`.\ntype SessionArgs<S> = { session: S; token: Record<string, unknown> }\n\n/** What `session` adds on top of the app's session object. */\nexport interface SessionExtras {\n user: Record<string, unknown> & {\n id?: string\n pessoaId?: string\n role?: RoleInfo\n roles: RoleInfo[]\n permissions?: string[]\n accessToken?: string\n refreshToken?: string\n }\n isImpersonating: boolean\n impersonationLogId?: string\n impersonationExpired: boolean\n originalUser?: {\n id: string\n name?: string\n email?: string\n role?: RoleInfo\n roles: RoleInfo[]\n }\n}\n\n/**\n * jwt/session callbacks with the canonical claim-copy of the session\n * contract (id, role, roles[], permissions, impersonation).\n *\n * When `getImpersonationCookies` is passed, `jwt` also applies/ends\n * impersonation (swaps id/role/permissions **and accessToken** for the\n * target's, restoring everything on stop/expiry). Without that option the\n * behavior is exactly as before. The app composes on top for its own logic\n * (sliding window etc.):\n *\n * ```ts\n * const base = createAuthCallbacks()\n * callbacks: {\n * jwt: async (args) => { const token = await base.jwt(args); ...; return token },\n * session: base.session\n * }\n * ```\n */\nexport function createAuthCallbacks(options: AuthCallbacksOptions = {}) {\n return {\n async jwt({ token, user }: JwtArgs): Promise<Record<string, unknown>> {\n if (user) {\n const u = user as Partial<SessionClaims>\n token.id = u.id\n token.pessoaId = u.pessoaId\n token.name = u.name\n token.email = u.email\n token.role = u.role\n token.roles = u.roles || (u.role ? [u.role] : [])\n token.permissions = u.permissions\n token.accessToken = u.accessToken\n token.refreshToken = u.refreshToken\n // stable across renewals (NextAuth rotates jti on every encode)\n if (u.sid) token.sid = u.sid\n // only at a real login — renewals and impersonation swaps keep the times\n stampSessionTimes(token)\n }\n if (options.getImpersonationCookies) {\n await applyImpersonation(token, options)\n }\n return token\n },\n\n session<S extends { user?: object | null }>({\n session,\n token,\n }: SessionArgs<S>): S & SessionExtras {\n const t = token as Partial<MfJwtPayload> &\n Pick<SessionClaims, 'accessToken' | 'refreshToken'> &\n Record<string, unknown>\n const extras: SessionExtras = {\n user: {\n ...(session.user as Record<string, unknown> | null | undefined),\n id: t.id,\n pessoaId: t.pessoaId,\n role: t.role,\n roles: t.roles || (t.role ? [t.role] : []),\n permissions: t.permissions,\n accessToken: t.accessToken,\n refreshToken: t.refreshToken,\n },\n isImpersonating: !!t.impersonatedUserId,\n impersonationLogId: t.impersonationLogId,\n // true for ONE pass, right after the impersonation expires (toast)\n impersonationExpired: !!t.impersonationExpired,\n originalUser: t.originalUserId\n ? {\n id: t.originalUserId,\n name: t.originalUserName,\n email: t.originalUserEmail,\n role: t.originalUserRole,\n roles:\n t.originalUserRoles ||\n (t.originalUserRole ? [t.originalUserRole] : []),\n }\n : undefined,\n }\n return { ...session, ...extras }\n },\n }\n}\n\nexport type { MfJwtPayload, RoleInfo } from '../types'\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","/**\n * Session freshness & revocation — pure, isomorphic, DB-agnostic.\n *\n * Roles/permissions are materialized in the session token, so a change in the\n * database only reaches the token at the next login, and a token cannot be\n * revoked by itself. The app keeps two per-user timestamps (e.g.\n * `accessChangedAt`, `sessionsRevokedAt`) and compares them with the times\n * stamped into the token at login; these helpers do the comparison.\n */\n\n/** Login/claims times stamped into the session token. */\nexport interface SessionTimes {\n /** Login time, epoch ms */\n authTime?: number\n /** When roles/permissions in the token were computed, epoch ms */\n accessAt?: number\n}\n\n/** Per-user marks the app stores. `null`/`undefined` mean \"nothing changed\". */\nexport interface SessionMarks {\n /** Every session that logged in before this instant is revoked */\n revokedAt?: Date | number | null\n /** Roles/permissions changed at this instant */\n accessChangedAt?: Date | number | null\n}\n\n/**\n * - `revoked`: the session must end (sign out / 401)\n * - `stale`: the session is valid, but its roles/permissions must be recomputed\n * - `fresh`: the token is up to date\n */\nexport type SessionState = 'revoked' | 'stale' | 'fresh'\n\n/** Stamps `authTime` and `accessAt` (epoch ms). Mutates and returns the token. */\nexport function stampSessionTimes<T extends object>(\n token: T,\n now: number = Date.now()\n): T & Required<SessionTimes> {\n return Object.assign(token, { authTime: now, accessAt: now })\n}\n\nfunction toMs(mark: Date | number | null | undefined): number | null {\n if (mark == null) return null\n return typeof mark === 'number' ? mark : mark.getTime()\n}\n\n/**\n * Compares the token's times with the user's marks. Revoked wins over stale.\n * A missing claim counts as 0, so tokens issued before adoption are caught by\n * the next revocation/access change.\n */\nexport function sessionState(\n token: SessionTimes,\n marks: SessionMarks\n): SessionState {\n const revokedAt = toMs(marks.revokedAt)\n if (revokedAt !== null && revokedAt > (token.authTime ?? 0)) return 'revoked'\n const accessChangedAt = toMs(marks.accessChangedAt)\n if (accessChangedAt !== null && accessChangedAt > (token.accessAt ?? 0)) {\n return 'stale'\n }\n return 'fresh'\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAA+B;;;ACkCxB,SAAS,kBACd,OACA,MAAc,KAAK,IAAI,GACK;AAC5B,SAAO,OAAO,OAAO,OAAO,EAAE,UAAU,KAAK,UAAU,IAAI,CAAC;AAC9D;;;ADtBO,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;;;ADKA,IAAM,qBAAqB;AAAA,EACzB,IAAI;AAAA,EACJ,UAAU;AAAA,EACV,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,aAAa;AACf;AAKA,SAAS,aAAa,OAA2B;AAC/C,MAAI,MAAM,g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AAA,QAClD,IACA;AAAA,MACN;AACA,aAAO,EAAE,GAAG,SAAS,GAAG,OAAO;AAAA,IACjC;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/index.ts","../../src/jwt.ts","../../src/session.ts"],"sourcesContent":["import { decodeSessionToken, type TokenConfig } from '../jwt'\nimport { stampSessionTimes } from '../session'\nimport type { MfJwtPayload, RoleInfo } from '../types'\n\n/**\n * Canonical claims the app's authorize() must return on the user object\n * so the callbacks can copy them into the token.\n */\nexport interface SessionClaims {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions: string[]\n accessToken?: string\n refreshToken?: string\n /** Stable per-login session id, kept across cookie renewals */\n sid?: string\n /** Login time, epoch ms. Stamped by `jwt` at login — authorize() need not return it */\n authTime?: number\n /** When roles/permissions were computed, epoch ms. Stamped by `jwt` at login */\n accessAt?: number\n}\n\n/** Impersonation cookies read by the app (the package does not import next/headers). */\nexport interface ImpersonationCookies {\n /** Token issued by `createImpersonationToken` */\n token?: string\n /** Audit log id */\n logId?: string\n}\n\nexport interface AuthCallbacksOptions {\n /**\n * Enables impersonation in the callbacks (opt-in). Reads the cookies in the app:\n *\n * ```ts\n * createAuthCallbacks({\n * getImpersonationCookies: async () => {\n * const c = await cookies()\n * return {\n * token: c.get('impersonation-token')?.value,\n * logId: c.get('impersonation-log-id')?.value\n * }\n * },\n * clearImpersonationCookies: async () => {\n * const c = await cookies()\n * c.delete('impersonation-token')\n * c.delete('impersonation-log-id')\n * }\n * })\n * ```\n */\n getImpersonationCookies?: () => Promise<\n ImpersonationCookies | null | undefined\n >\n /**\n * Called when an active impersonation ends because its token expired, is\n * invalid or was not started by this session's user. Optional.\n */\n clearImpersonationCookies?: () => Promise<void> | void\n /** secret/salt to decode the impersonation token. Default: env + v5 salt. */\n tokenConfig?: TokenConfig\n}\n\n/**\n * Token field ↔ claim where the ACTOR's value is kept while impersonation\n * is active. `refreshToken` is left out on purpose: it stays the actor's,\n * which is what keeps the session refresh healthy.\n */\nconst IMPERSONATION_SWAP = {\n id: 'originalUserId',\n pessoaId: 'originalPessoaId',\n name: 'originalUserName',\n email: 'originalUserEmail',\n role: 'originalUserRole',\n roles: 'originalUserRoles',\n permissions: 'originalPermissions',\n accessToken: 'originalAccessToken',\n // when the actor's permissions above were computed: restored with them, so\n // a target-side refresh during impersonation cannot hide an actor change\n accessAt: 'originalAccessAt',\n} as const\n\ntype MutableToken = Record<string, unknown>\n\n/** Ends the impersonation: restores the actor's values and clears the claims. */\nfunction restoreActor(token: MutableToken): void {\n if (token.originalUserId) {\n for (const [field, claim] of Object.entries(IMPERSONATION_SWAP)) {\n token[field] = token[claim]\n }\n }\n for (const claim of Object.values(IMPERSONATION_SWAP)) delete token[claim]\n delete token.impersonatedUserId\n delete token.impersonationLogId\n delete token.isImpersonating\n}\n\nasync function applyImpersonation(\n token: MutableToken,\n options: AuthCallbacksOptions\n): Promise<void> {\n // The expiry flag lives for EXACTLY one cycle: set below on restore,\n // read by `session` in the same pass, deleted here on the next pass.\n delete token.impersonationExpired\n\n const cookies = await options.getImpersonationCookies?.()\n const impersonationToken = cookies?.token\n const logId = cookies?.logId\n\n if (!impersonationToken || !logId) {\n // Cookie is gone (stop-impersonate) → back to the actor, silently.\n if (token.impersonatedUserId) restoreActor(token)\n return\n }\n\n const decoded = await decodeSessionToken(\n impersonationToken,\n options.tokenConfig\n )\n // Only a real impersonation token (with its own log id) started by THIS\n // session's actor counts: a cookie left behind never applies to another user\n const actorId = token.originalUserId ?? token.id\n const payload =\n decoded?.impersonatedUserId &&\n decoded.impersonationLogId &&\n decoded.originalUserId &&\n decoded.originalUserId === actorId\n ? decoded\n : null\n\n if (!payload) {\n // Expired/invalid/not ours. Orphan cookie with no active impersonation: ignore.\n if (!token.impersonatedUserId) return\n restoreActor(token)\n token.impersonationExpired = true\n await options.clearImpersonationCookies?.()\n return\n }\n\n if (!token.originalUserId) {\n for (const [field, claim] of Object.entries(IMPERSONATION_SWAP)) {\n token[claim] = token[field]\n }\n }\n\n token.id = payload.id\n token.pessoaId = payload.pessoaId\n token.name = payload.name\n token.email = payload.email\n token.role = payload.role\n token.roles = payload.roles ?? (payload.role ? [payload.role] : [])\n token.permissions = payload.permissions ?? []\n // The impersonation token IS the API credential. Without swapping the\n // accessToken the impersonation is merely cosmetic: the UI shows the target\n // while API calls keep going out with the admin's credential.\n token.accessToken = payload.accessToken ?? impersonationToken\n token.impersonatedUserId = payload.id\n token.impersonationLogId = payload.impersonationLogId\n token.isImpersonating = true\n}\n\ntype JwtArgs = { token: Record<string, unknown>; user?: unknown }\n// Generic over the app's session type (next-auth's `Session` is an interface\n// without an index signature), so `base.session` plugs straight into\n// `callbacks.session` and keeps fields like `expires`.\ntype SessionArgs<S> = { session: S; token: Record<string, unknown> }\n\n/** What `session` adds on top of the app's session object. */\nexport interface SessionExtras {\n user: Record<string, unknown> & {\n id?: string\n pessoaId?: string\n role?: RoleInfo\n roles: RoleInfo[]\n permissions?: string[]\n accessToken?: string\n refreshToken?: string\n }\n isImpersonating: boolean\n impersonationLogId?: string\n impersonationExpired: boolean\n originalUser?: {\n id: string\n name?: string\n email?: string\n role?: RoleInfo\n roles: RoleInfo[]\n }\n}\n\n/**\n * jwt/session callbacks with the canonical claim-copy of the session\n * contract (id, role, roles[], permissions, impersonation).\n *\n * When `getImpersonationCookies` is passed, `jwt` also applies/ends\n * impersonation (swaps id/role/permissions **and accessToken** for the\n * target's, restoring everything on stop/expiry). Without that option the\n * behavior is exactly as before. The app composes on top for its own logic\n * (sliding window etc.):\n *\n * ```ts\n * const base = createAuthCallbacks()\n * callbacks: {\n * jwt: async (args) => { const token = await base.jwt(args); ...; return token },\n * session: base.session\n * }\n * ```\n */\nexport function createAuthCallbacks(options: AuthCallbacksOptions = {}) {\n return {\n async jwt({ token, user }: JwtArgs): Promise<Record<string, unknown>> {\n if (user) {\n const u = user as Partial<SessionClaims>\n token.id = u.id\n token.pessoaId = u.pessoaId\n token.name = u.name\n token.email = u.email\n token.role = u.role\n token.roles = u.roles || (u.role ? [u.role] : [])\n token.permissions = u.permissions\n token.accessToken = u.accessToken\n token.refreshToken = u.refreshToken\n // stable across renewals (NextAuth rotates jti on every encode)\n if (u.sid) token.sid = u.sid\n // only at a real login — renewals and impersonation swaps keep the times\n stampSessionTimes(token)\n }\n if (options.getImpersonationCookies) {\n await applyImpersonation(token, options)\n }\n return token\n },\n\n session<S extends { user?: object | null }>({\n session,\n token,\n }: SessionArgs<S>): S & SessionExtras {\n const t = token as Partial<MfJwtPayload> &\n Pick<SessionClaims, 'accessToken' | 'refreshToken'> &\n Record<string, unknown>\n const extras: SessionExtras = {\n user: {\n ...(session.user as Record<string, unknown> | null | undefined),\n id: t.id,\n pessoaId: t.pessoaId,\n role: t.role,\n roles: t.roles || (t.role ? [t.role] : []),\n permissions: t.permissions,\n accessToken: t.accessToken,\n refreshToken: t.refreshToken,\n },\n isImpersonating: !!t.impersonatedUserId,\n impersonationLogId: t.impersonationLogId,\n // true for ONE pass, right after the impersonation expires (toast)\n impersonationExpired: !!t.impersonationExpired,\n originalUser: t.originalUserId\n ? {\n id: t.originalUserId,\n name: t.originalUserName,\n email: t.originalUserEmail,\n role: t.originalUserRole,\n roles:\n t.originalUserRoles ||\n (t.originalUserRole ? [t.originalUserRole] : []),\n }\n : undefined,\n }\n return { ...session, ...extras }\n },\n }\n}\n\nexport type { MfJwtPayload, RoleInfo } from '../types'\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 /**\n * Seconds. Encoding: the token lifetime, default 24h. Decoding (and the\n * guard): only when set, rejects a token issued longer ago than this;\n * unset, the token's own `exp` is the only limit.\n */\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/**\n * Decodes the session JWE. Returns null for an invalid/expired token.\n * An explicit `config.maxAge` also rejects a token issued (`iat`) more than\n * that many seconds ago; without it, only the token's own `exp` applies.\n */\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 })) as MfJwtPayload | null\n if (!payload) return null\n // A token without iat counts as issued at 0: fail closed\n if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1000) {\n return null\n }\n return payload\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","/**\n * Session freshness & revocation — pure, isomorphic, DB-agnostic.\n *\n * Roles/permissions are materialized in the session token, so a change in the\n * database only reaches the token at the next login, and a token cannot be\n * revoked by itself. The app keeps two per-user timestamps (e.g.\n * `accessChangedAt`, `sessionsRevokedAt`) and compares them with the times\n * stamped into the token at login; these helpers do the comparison.\n */\n\n/** Login/claims times stamped into the session token. */\nexport interface SessionTimes {\n /** Login time, epoch ms */\n authTime?: number\n /** When roles/permissions in the token were computed, epoch ms */\n accessAt?: number\n}\n\n/** Per-user marks the app stores. `null`/`undefined` mean \"nothing changed\". */\nexport interface SessionMarks {\n /** Every session that logged in before this instant is revoked */\n revokedAt?: Date | number | null\n /** Roles/permissions changed at this instant */\n accessChangedAt?: Date | number | null\n}\n\n/**\n * - `revoked`: the session must end (sign out / 401)\n * - `stale`: the session is valid, but its roles/permissions must be recomputed\n * - `fresh`: the token is up to date\n */\nexport type SessionState = 'revoked' | 'stale' | 'fresh'\n\n/** Stamps `authTime` and `accessAt` (epoch ms). Mutates and returns the token. */\nexport function stampSessionTimes<T extends object>(\n token: T,\n now: number = Date.now()\n): T & Required<SessionTimes> {\n return Object.assign(token, { authTime: now, accessAt: now })\n}\n\nfunction toMs(mark: Date | number | null | undefined): number | null {\n if (mark == null) return null\n return typeof mark === 'number' ? mark : mark.getTime()\n}\n\n/**\n * Compares the token's times with the user's marks. Revoked wins over stale.\n * A missing claim counts as 0, so tokens issued before adoption are caught by\n * the next revocation/access change.\n */\nexport function sessionState(\n token: SessionTimes,\n marks: SessionMarks\n): SessionState {\n const revokedAt = toMs(marks.revokedAt)\n if (revokedAt !== null && revokedAt > (token.authTime ?? 0)) return 'revoked'\n const accessChangedAt = toMs(marks.accessChangedAt)\n if (accessChangedAt !== null && accessChangedAt > (token.accessAt ?? 0)) {\n return 'stale'\n }\n return 'fresh'\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAA+B;;;ACkCxB,SAAS,kBACd,OACA,MAAc,KAAK,IAAI,GACK;AAC5B,SAAO,OAAO,OAAO,OAAO,EAAE,UAAU,KAAK,UAAU,IAAI,CAAC;AAC9D;;;ADlBO,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;AAwBA,eAAsB,mBACpB,OACA,QAC8B;AAC9B,QAAM,EAAE,QAAQ,KAAK,IAAI,mBAAmB,MAAM;AAClD,MAAI;AACF,UAAM,UAAW,UAAM,mBAAO,EAAE,OAAO,QAAQ,KAAK,CAAC;AACrD,QAAI,CAAC,QAAS,QAAO;AAErB,QAAI,QAAQ,UAAU,SAAS,QAAQ,OAAO,KAAK,OAAO,SAAS,KAAK,IAAI,IAAI,KAAM;AACpF,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ADLA,IAAM,qBAAqB;AAAA,EACzB,IA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AA,QAClB;AAAA,QACA,iBAAiB,CAAC,CAAC,EAAE;AAAA,QACrB,oBAAoB,EAAE;AAAA;AAAA,QAEtB,sBAAsB,CAAC,CAAC,EAAE;AAAA,QAC1B,cAAc,EAAE,iBACZ;AAAA,UACE,IAAI,EAAE;AAAA,UACN,MAAM,EAAE;AAAA,UACR,OAAO,EAAE;AAAA,UACT,MAAM,EAAE;AAAA,UACR,OACE,EAAE,sBACD,EAAE,mBAAmB,CAAC,EAAE,gBAAgB,IAAI,CAAC;AAAA,QAClD,IACA;AAAA,MACN;AACA,aAAO,EAAE,GAAG,SAAS,GAAG,OAAO;AAAA,IACjC;AAAA,EACF;AACF;","names":[]}
|
package/dist/next/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { T as TokenConfig, R as RoleInfo } from '../jwt-
|
|
2
|
-
export { M as MfJwtPayload } from '../jwt-
|
|
1
|
+
import { T as TokenConfig, R as RoleInfo } from '../jwt-EyXe_d9K.cjs';
|
|
2
|
+
export { M as MfJwtPayload } from '../jwt-EyXe_d9K.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Canonical claims the app's authorize() must return on the user object
|
|
@@ -51,7 +51,10 @@ interface AuthCallbacksOptions {
|
|
|
51
51
|
* ```
|
|
52
52
|
*/
|
|
53
53
|
getImpersonationCookies?: () => Promise<ImpersonationCookies | null | undefined>;
|
|
54
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* Called when an active impersonation ends because its token expired, is
|
|
56
|
+
* invalid or was not started by this session's user. Optional.
|
|
57
|
+
*/
|
|
55
58
|
clearImpersonationCookies?: () => Promise<void> | void;
|
|
56
59
|
/** secret/salt to decode the impersonation token. Default: env + v5 salt. */
|
|
57
60
|
tokenConfig?: TokenConfig;
|
package/dist/next/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { T as TokenConfig, R as RoleInfo } from '../jwt-
|
|
2
|
-
export { M as MfJwtPayload } from '../jwt-
|
|
1
|
+
import { T as TokenConfig, R as RoleInfo } from '../jwt-EyXe_d9K.js';
|
|
2
|
+
export { M as MfJwtPayload } from '../jwt-EyXe_d9K.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Canonical claims the app's authorize() must return on the user object
|
|
@@ -51,7 +51,10 @@ interface AuthCallbacksOptions {
|
|
|
51
51
|
* ```
|
|
52
52
|
*/
|
|
53
53
|
getImpersonationCookies?: () => Promise<ImpersonationCookies | null | undefined>;
|
|
54
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* Called when an active impersonation ends because its token expired, is
|
|
56
|
+
* invalid or was not started by this session's user. Optional.
|
|
57
|
+
*/
|
|
55
58
|
clearImpersonationCookies?: () => Promise<void> | void;
|
|
56
59
|
/** secret/salt to decode the impersonation token. Default: env + v5 salt. */
|
|
57
60
|
tokenConfig?: TokenConfig;
|
package/dist/next/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
decodeSessionToken,
|
|
3
3
|
stampSessionTimes
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-G73ASFMN.js";
|
|
5
5
|
|
|
6
6
|
// src/next/index.ts
|
|
7
7
|
var IMPERSONATION_SWAP = {
|
|
@@ -12,7 +12,10 @@ var IMPERSONATION_SWAP = {
|
|
|
12
12
|
role: "originalUserRole",
|
|
13
13
|
roles: "originalUserRoles",
|
|
14
14
|
permissions: "originalPermissions",
|
|
15
|
-
accessToken: "originalAccessToken"
|
|
15
|
+
accessToken: "originalAccessToken",
|
|
16
|
+
// when the actor's permissions above were computed: restored with them, so
|
|
17
|
+
// a target-side refresh during impersonation cannot hide an actor change
|
|
18
|
+
accessAt: "originalAccessAt"
|
|
16
19
|
};
|
|
17
20
|
function restoreActor(token) {
|
|
18
21
|
if (token.originalUserId) {
|
|
@@ -34,10 +37,12 @@ async function applyImpersonation(token, options) {
|
|
|
34
37
|
if (token.impersonatedUserId) restoreActor(token);
|
|
35
38
|
return;
|
|
36
39
|
}
|
|
37
|
-
const
|
|
40
|
+
const decoded = await decodeSessionToken(
|
|
38
41
|
impersonationToken,
|
|
39
42
|
options.tokenConfig
|
|
40
43
|
);
|
|
44
|
+
const actorId = token.originalUserId ?? token.id;
|
|
45
|
+
const payload = decoded?.impersonatedUserId && decoded.impersonationLogId && decoded.originalUserId && decoded.originalUserId === actorId ? decoded : null;
|
|
41
46
|
if (!payload) {
|
|
42
47
|
if (!token.impersonatedUserId) return;
|
|
43
48
|
restoreActor(token);
|
|
@@ -59,7 +64,7 @@ async function applyImpersonation(token, options) {
|
|
|
59
64
|
token.permissions = payload.permissions ?? [];
|
|
60
65
|
token.accessToken = payload.accessToken ?? impersonationToken;
|
|
61
66
|
token.impersonatedUserId = payload.id;
|
|
62
|
-
token.impersonationLogId = payload.impersonationLogId
|
|
67
|
+
token.impersonationLogId = payload.impersonationLogId;
|
|
63
68
|
token.isImpersonating = true;
|
|
64
69
|
}
|
|
65
70
|
function createAuthCallbacks(options = {}) {
|
package/dist/next/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next/index.ts"],"sourcesContent":["import { decodeSessionToken, type TokenConfig } from '../jwt'\nimport { stampSessionTimes } from '../session'\nimport type { MfJwtPayload, RoleInfo } from '../types'\n\n/**\n * Canonical claims the app's authorize() must return on the user object\n * so the callbacks can copy them into the token.\n */\nexport interface SessionClaims {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions: string[]\n accessToken?: string\n refreshToken?: string\n /** Stable per-login session id, kept across cookie renewals */\n sid?: string\n /** Login time, epoch ms. Stamped by `jwt` at login — authorize() need not return it */\n authTime?: number\n /** When roles/permissions were computed, epoch ms. Stamped by `jwt` at login */\n accessAt?: number\n}\n\n/** Impersonation cookies read by the app (the package does not import next/headers). */\nexport interface ImpersonationCookies {\n /** Token issued by `createImpersonationToken` */\n token?: string\n /** Audit log id */\n logId?: string\n}\n\nexport interface AuthCallbacksOptions {\n /**\n * Enables impersonation in the callbacks (opt-in). Reads the cookies in the app:\n *\n * ```ts\n * createAuthCallbacks({\n * getImpersonationCookies: async () => {\n * const c = await cookies()\n * return {\n * token: c.get('impersonation-token')?.value,\n * logId: c.get('impersonation-log-id')?.value\n * }\n * },\n * clearImpersonationCookies: async () => {\n * const c = await cookies()\n * c.delete('impersonation-token')\n * c.delete('impersonation-log-id')\n * }\n * })\n * ```\n */\n getImpersonationCookies?: () => Promise<\n ImpersonationCookies | null | undefined\n >\n /** Called when the impersonation token expires or is invalid. Optional. */\n clearImpersonationCookies?: () => Promise<void> | void\n /** secret/salt to decode the impersonation token. Default: env + v5 salt. */\n tokenConfig?: TokenConfig\n}\n\n/**\n * Token field ↔ claim where the ACTOR's value is kept while impersonation\n * is active. `refreshToken` is left out on purpose: it stays the actor's,\n * which is what keeps the session refresh healthy.\n */\nconst IMPERSONATION_SWAP = {\n id: 'originalUserId',\n pessoaId: 'originalPessoaId',\n name: 'originalUserName',\n email: 'originalUserEmail',\n role: 'originalUserRole',\n roles: 'originalUserRoles',\n permissions: 'originalPermissions',\n accessToken: 'originalAccessToken',\n} as const\n\ntype MutableToken = Record<string, unknown>\n\n/** Ends the impersonation: restores the actor's values and clears the claims. */\nfunction restoreActor(token: MutableToken): void {\n if (token.originalUserId) {\n for (const [field, claim] of Object.entries(IMPERSONATION_SWAP)) {\n token[field] = token[claim]\n }\n }\n for (const claim of Object.values(IMPERSONATION_SWAP)) delete token[claim]\n delete token.impersonatedUserId\n delete token.impersonationLogId\n delete token.isImpersonating\n}\n\nasync function applyImpersonation(\n token: MutableToken,\n options: AuthCallbacksOptions\n): Promise<void> {\n // The expiry flag lives for EXACTLY one cycle: set below on restore,\n // read by `session` in the same pass, deleted here on the next pass.\n delete token.impersonationExpired\n\n const cookies = await options.getImpersonationCookies?.()\n const impersonationToken = cookies?.token\n const logId = cookies?.logId\n\n if (!impersonationToken || !logId) {\n // Cookie is gone (stop-impersonate) → back to the actor, silently.\n if (token.impersonatedUserId) restoreActor(token)\n return\n }\n\n const payload = await decodeSessionToken(\n impersonationToken,\n options.tokenConfig\n )\n\n if (!payload) {\n // Expired/invalid. Orphan cookie with no active impersonation: ignore.\n if (!token.impersonatedUserId) return\n restoreActor(token)\n token.impersonationExpired = true\n await options.clearImpersonationCookies?.()\n return\n }\n\n if (!token.originalUserId) {\n for (const [field, claim] of Object.entries(IMPERSONATION_SWAP)) {\n token[claim] = token[field]\n }\n }\n\n token.id = payload.id\n token.pessoaId = payload.pessoaId\n token.name = payload.name\n token.email = payload.email\n token.role = payload.role\n token.roles = payload.roles ?? (payload.role ? [payload.role] : [])\n token.permissions = payload.permissions ?? []\n // The impersonation token IS the API credential. Without swapping the\n // accessToken the impersonation is merely cosmetic: the UI shows the target\n // while API calls keep going out with the admin's credential.\n token.accessToken = payload.accessToken ?? impersonationToken\n token.impersonatedUserId = payload.id\n token.impersonationLogId = payload.impersonationLogId ?? logId\n token.isImpersonating = true\n}\n\ntype JwtArgs = { token: Record<string, unknown>; user?: unknown }\n// Generic over the app's session type (next-auth's `Session` is an interface\n// without an index signature), so `base.session` plugs straight into\n// `callbacks.session` and keeps fields like `expires`.\ntype SessionArgs<S> = { session: S; token: Record<string, unknown> }\n\n/** What `session` adds on top of the app's session object. */\nexport interface SessionExtras {\n user: Record<string, unknown> & {\n id?: string\n pessoaId?: string\n role?: RoleInfo\n roles: RoleInfo[]\n permissions?: string[]\n accessToken?: string\n refreshToken?: string\n }\n isImpersonating: boolean\n impersonationLogId?: string\n impersonationExpired: boolean\n originalUser?: {\n id: string\n name?: string\n email?: string\n role?: RoleInfo\n roles: RoleInfo[]\n }\n}\n\n/**\n * jwt/session callbacks with the canonical claim-copy of the session\n * contract (id, role, roles[], permissions, impersonation).\n *\n * When `getImpersonationCookies` is passed, `jwt` also applies/ends\n * impersonation (swaps id/role/permissions **and accessToken** for the\n * target's, restoring everything on stop/expiry). Without that option the\n * behavior is exactly as before. The app composes on top for its own logic\n * (sliding window etc.):\n *\n * ```ts\n * const base = createAuthCallbacks()\n * callbacks: {\n * jwt: async (args) => { const token = await base.jwt(args); ...; return token },\n * session: base.session\n * }\n * ```\n */\nexport function createAuthCallbacks(options: AuthCallbacksOptions = {}) {\n return {\n async jwt({ token, user }: JwtArgs): Promise<Record<string, unknown>> {\n if (user) {\n const u = user as Partial<SessionClaims>\n token.id = u.id\n token.pessoaId = u.pessoaId\n token.name = u.name\n token.email = u.email\n token.role = u.role\n token.roles = u.roles || (u.role ? [u.role] : [])\n token.permissions = u.permissions\n token.accessToken = u.accessToken\n token.refreshToken = u.refreshToken\n // stable across renewals (NextAuth rotates jti on every encode)\n if (u.sid) token.sid = u.sid\n // only at a real login — renewals and impersonation swaps keep the times\n stampSessionTimes(token)\n }\n if (options.getImpersonationCookies) {\n await applyImpersonation(token, options)\n }\n return token\n },\n\n session<S extends { user?: object | null }>({\n session,\n token,\n }: SessionArgs<S>): S & SessionExtras {\n const t = token as Partial<MfJwtPayload> &\n Pick<SessionClaims, 'accessToken' | 'refreshToken'> &\n Record<string, unknown>\n const extras: SessionExtras = {\n user: {\n ...(session.user as Record<string, unknown> | null | undefined),\n id: t.id,\n pessoaId: t.pessoaId,\n role: t.role,\n roles: t.roles || (t.role ? [t.role] : []),\n permissions: t.permissions,\n accessToken: t.accessToken,\n refreshToken: t.refreshToken,\n },\n isImpersonating: !!t.impersonatedUserId,\n impersonationLogId: t.impersonationLogId,\n // true for ONE pass, right after the impersonation expires (toast)\n impersonationExpired: !!t.impersonationExpired,\n originalUser: t.originalUserId\n ? {\n id: t.originalUserId,\n name: t.originalUserName,\n email: t.originalUserEmail,\n role: t.originalUserRole,\n roles:\n t.originalUserRoles ||\n (t.originalUserRole ? [t.originalUserRole] : []),\n }\n : undefined,\n }\n return { ...session, ...extras }\n },\n }\n}\n\nexport type { MfJwtPayload, RoleInfo } from '../types'\n"],"mappings":";;;;;;AAqEA,IAAM,qBAAqB;AAAA,EACzB,IAA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ACZ;AAAA,UACE,IAAI,EAAE;AAAA,UACN,MAAM,EAAE;AAAA,UACR,OAAO,EAAE;AAAA,UACT,MAAM,EAAE;AAAA,UACR,OACE,EAAE,sBACD,EAAE,mBAAmB,CAAC,EAAE,gBAAgB,IAAI,CAAC;AAAA,QAClD,IACA;AAAA,MACN;AACA,aAAO,EAAE,GAAG,SAAS,GAAG,OAAO;AAAA,IACjC;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/index.ts"],"sourcesContent":["import { decodeSessionToken, type TokenConfig } from '../jwt'\nimport { stampSessionTimes } from '../session'\nimport type { MfJwtPayload, RoleInfo } from '../types'\n\n/**\n * Canonical claims the app's authorize() must return on the user object\n * so the callbacks can copy them into the token.\n */\nexport interface SessionClaims {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions: string[]\n accessToken?: string\n refreshToken?: string\n /** Stable per-login session id, kept across cookie renewals */\n sid?: string\n /** Login time, epoch ms. Stamped by `jwt` at login — authorize() need not return it */\n authTime?: number\n /** When roles/permissions were computed, epoch ms. Stamped by `jwt` at login */\n accessAt?: number\n}\n\n/** Impersonation cookies read by the app (the package does not import next/headers). */\nexport interface ImpersonationCookies {\n /** Token issued by `createImpersonationToken` */\n token?: string\n /** Audit log id */\n logId?: string\n}\n\nexport interface AuthCallbacksOptions {\n /**\n * Enables impersonation in the callbacks (opt-in). Reads the cookies in the app:\n *\n * ```ts\n * createAuthCallbacks({\n * getImpersonationCookies: async () => {\n * const c = await cookies()\n * return {\n * token: c.get('impersonation-token')?.value,\n * logId: c.get('impersonation-log-id')?.value\n * }\n * },\n * clearImpersonationCookies: async () => {\n * const c = await cookies()\n * c.delete('impersonation-token')\n * c.delete('impersonation-log-id')\n * }\n * })\n * ```\n */\n getImpersonationCookies?: () => Promise<\n ImpersonationCookies | null | undefined\n >\n /**\n * Called when an active impersonation ends because its token expired, is\n * invalid or was not started by this session's user. Optional.\n */\n clearImpersonationCookies?: () => Promise<void> | void\n /** secret/salt to decode the impersonation token. Default: env + v5 salt. */\n tokenConfig?: TokenConfig\n}\n\n/**\n * Token field ↔ claim where the ACTOR's value is kept while impersonation\n * is active. `refreshToken` is left out on purpose: it stays the actor's,\n * which is what keeps the session refresh healthy.\n */\nconst IMPERSONATION_SWAP = {\n id: 'originalUserId',\n pessoaId: 'originalPessoaId',\n name: 'originalUserName',\n email: 'originalUserEmail',\n role: 'originalUserRole',\n roles: 'originalUserRoles',\n permissions: 'originalPermissions',\n accessToken: 'originalAccessToken',\n // when the actor's permissions above were computed: restored with them, so\n // a target-side refresh during impersonation cannot hide an actor change\n accessAt: 'originalAccessAt',\n} as const\n\ntype MutableToken = Record<string, unknown>\n\n/** Ends the impersonation: restores the actor's values and clears the claims. */\nfunction restoreActor(token: MutableToken): void {\n if (token.originalUserId) {\n for (const [field, claim] of Object.entries(IMPERSONATION_SWAP)) {\n token[field] = token[claim]\n }\n }\n for (const claim of Object.values(IMPERSONATION_SWAP)) delete token[claim]\n delete token.impersonatedUserId\n delete token.impersonationLogId\n delete token.isImpersonating\n}\n\nasync function applyImpersonation(\n token: MutableToken,\n options: AuthCallbacksOptions\n): Promise<void> {\n // The expiry flag lives for EXACTLY one cycle: set below on restore,\n // read by `session` in the same pass, deleted here on the next pass.\n delete token.impersonationExpired\n\n const cookies = await options.getImpersonationCookies?.()\n const impersonationToken = cookies?.token\n const logId = cookies?.logId\n\n if (!impersonationToken || !logId) {\n // Cookie is gone (stop-impersonate) → back to the actor, silently.\n if (token.impersonatedUserId) restoreActor(token)\n return\n }\n\n const decoded = await decodeSessionToken(\n impersonationToken,\n options.tokenConfig\n )\n // Only a real impersonation token (with its own log id) started by THIS\n // session's actor counts: a cookie left behind never applies to another user\n const actorId = token.originalUserId ?? token.id\n const payload =\n decoded?.impersonatedUserId &&\n decoded.impersonationLogId &&\n decoded.originalUserId &&\n decoded.originalUserId === actorId\n ? decoded\n : null\n\n if (!payload) {\n // Expired/invalid/not ours. Orphan cookie with no active impersonation: ignore.\n if (!token.impersonatedUserId) return\n restoreActor(token)\n token.impersonationExpired = true\n await options.clearImpersonationCookies?.()\n return\n }\n\n if (!token.originalUserId) {\n for (const [field, claim] of Object.entries(IMPERSONATION_SWAP)) {\n token[claim] = token[field]\n }\n }\n\n token.id = payload.id\n token.pessoaId = payload.pessoaId\n token.name = payload.name\n token.email = payload.email\n token.role = payload.role\n token.roles = payload.roles ?? (payload.role ? [payload.role] : [])\n token.permissions = payload.permissions ?? []\n // The impersonation token IS the API credential. Without swapping the\n // accessToken the impersonation is merely cosmetic: the UI shows the target\n // while API calls keep going out with the admin's credential.\n token.accessToken = payload.accessToken ?? impersonationToken\n token.impersonatedUserId = payload.id\n token.impersonationLogId = payload.impersonationLogId\n token.isImpersonating = true\n}\n\ntype JwtArgs = { token: Record<string, unknown>; user?: unknown }\n// Generic over the app's session type (next-auth's `Session` is an interface\n// without an index signature), so `base.session` plugs straight into\n// `callbacks.session` and keeps fields like `expires`.\ntype SessionArgs<S> = { session: S; token: Record<string, unknown> }\n\n/** What `session` adds on top of the app's session object. */\nexport interface SessionExtras {\n user: Record<string, unknown> & {\n id?: string\n pessoaId?: string\n role?: RoleInfo\n roles: RoleInfo[]\n permissions?: string[]\n accessToken?: string\n refreshToken?: string\n }\n isImpersonating: boolean\n impersonationLogId?: string\n impersonationExpired: boolean\n originalUser?: {\n id: string\n name?: string\n email?: string\n role?: RoleInfo\n roles: RoleInfo[]\n }\n}\n\n/**\n * jwt/session callbacks with the canonical claim-copy of the session\n * contract (id, role, roles[], permissions, impersonation).\n *\n * When `getImpersonationCookies` is passed, `jwt` also applies/ends\n * impersonation (swaps id/role/permissions **and accessToken** for the\n * target's, restoring everything on stop/expiry). Without that option the\n * behavior is exactly as before. The app composes on top for its own logic\n * (sliding window etc.):\n *\n * ```ts\n * const base = createAuthCallbacks()\n * callbacks: {\n * jwt: async (args) => { const token = await base.jwt(args); ...; return token },\n * session: base.session\n * }\n * ```\n */\nexport function createAuthCallbacks(options: AuthCallbacksOptions = {}) {\n return {\n async jwt({ token, user }: JwtArgs): Promise<Record<string, unknown>> {\n if (user) {\n const u = user as Partial<SessionClaims>\n token.id = u.id\n token.pessoaId = u.pessoaId\n token.name = u.name\n token.email = u.email\n token.role = u.role\n token.roles = u.roles || (u.role ? [u.role] : [])\n token.permissions = u.permissions\n token.accessToken = u.accessToken\n token.refreshToken = u.refreshToken\n // stable across renewals (NextAuth rotates jti on every encode)\n if (u.sid) token.sid = u.sid\n // only at a real login — renewals and impersonation swaps keep the times\n stampSessionTimes(token)\n }\n if (options.getImpersonationCookies) {\n await applyImpersonation(token, options)\n }\n return token\n },\n\n session<S extends { user?: object | null }>({\n session,\n token,\n }: SessionArgs<S>): S & SessionExtras {\n const t = token as Partial<MfJwtPayload> &\n Pick<SessionClaims, 'accessToken' | 'refreshToken'> &\n Record<string, unknown>\n const extras: SessionExtras = {\n user: {\n ...(session.user as Record<string, unknown> | null | undefined),\n id: t.id,\n pessoaId: t.pessoaId,\n role: t.role,\n roles: t.roles || (t.role ? [t.role] : []),\n permissions: t.permissions,\n accessToken: t.accessToken,\n refreshToken: t.refreshToken,\n },\n isImpersonating: !!t.impersonatedUserId,\n impersonationLogId: t.impersonationLogId,\n // true for ONE pass, right after the impersonation expires (toast)\n impersonationExpired: !!t.impersonationExpired,\n originalUser: t.originalUserId\n ? {\n id: t.originalUserId,\n name: t.originalUserName,\n email: t.originalUserEmail,\n role: t.originalUserRole,\n roles:\n t.originalUserRoles ||\n (t.originalUserRole ? [t.originalUserRole] : []),\n }\n : undefined,\n }\n return { ...session, ...extras }\n },\n }\n}\n\nexport type { MfJwtPayload, RoleInfo } from '../types'\n"],"mappings":";;;;;;AAwEA,IAAM,qBAAqB;AAAA,EACzB,IAAI;AAAA,EACJ,UAAU;AAAA,EACV,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,aAAa;AAAA;AAA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cAAc,EAAE,iBACZ;AAAA,UACE,IAAI,EAAE;AAAA,UACN,MAAM,EAAE;AAAA,UACR,OAAO,EAAE;AAAA,UACT,MAAM,EAAE;AAAA,UACR,OACE,EAAE,sBACD,EAAE,mBAAmB,CAAC,EAAE,gBAAgB,IAAI,CAAC;AAAA,QAClD,IACA;AAAA,MACN;AACA,aAAO,EAAE,GAAG,SAAS,GAAG,OAAO;AAAA,IACjC;AAAA,EACF;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@telamonjs/auth",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.1",
|
|
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",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/session.ts","../src/jwt.ts"],"sourcesContent":["/**\n * Session freshness & revocation — pure, isomorphic, DB-agnostic.\n *\n * Roles/permissions are materialized in the session token, so a change in the\n * database only reaches the token at the next login, and a token cannot be\n * revoked by itself. The app keeps two per-user timestamps (e.g.\n * `accessChangedAt`, `sessionsRevokedAt`) and compares them with the times\n * stamped into the token at login; these helpers do the comparison.\n */\n\n/** Login/claims times stamped into the session token. */\nexport interface SessionTimes {\n /** Login time, epoch ms */\n authTime?: number\n /** When roles/permissions in the token were computed, epoch ms */\n accessAt?: number\n}\n\n/** Per-user marks the app stores. `null`/`undefined` mean \"nothing changed\". */\nexport interface SessionMarks {\n /** Every session that logged in before this instant is revoked */\n revokedAt?: Date | number | null\n /** Roles/permissions changed at this instant */\n accessChangedAt?: Date | number | null\n}\n\n/**\n * - `revoked`: the session must end (sign out / 401)\n * - `stale`: the session is valid, but its roles/permissions must be recomputed\n * - `fresh`: the token is up to date\n */\nexport type SessionState = 'revoked' | 'stale' | 'fresh'\n\n/** Stamps `authTime` and `accessAt` (epoch ms). Mutates and returns the token. */\nexport function stampSessionTimes<T extends object>(\n token: T,\n now: number = Date.now()\n): T & Required<SessionTimes> {\n return Object.assign(token, { authTime: now, accessAt: now })\n}\n\nfunction toMs(mark: Date | number | null | undefined): number | null {\n if (mark == null) return null\n return typeof mark === 'number' ? mark : mark.getTime()\n}\n\n/**\n * Compares the token's times with the user's marks. Revoked wins over stale.\n * A missing claim counts as 0, so tokens issued before adoption are caught by\n * the next revocation/access change.\n */\nexport function sessionState(\n token: SessionTimes,\n marks: SessionMarks\n): SessionState {\n const revokedAt = toMs(marks.revokedAt)\n if (revokedAt !== null && revokedAt > (token.authTime ?? 0)) return 'revoked'\n const accessChangedAt = toMs(marks.accessChangedAt)\n if (accessChangedAt !== null && accessChangedAt > (token.accessAt ?? 0)) {\n return 'stale'\n }\n return 'fresh'\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"],"mappings":";;;;;;;;;;;;AAkCO,SAAS,kBACd,OACA,MAAc,KAAK,IAAI,GACK;AAC5B,SAAO,OAAO,OAAO,OAAO,EAAE,UAAU,KAAK,UAAU,IAAI,CAAC;AAC9D;AAEA,SAAS,KAAK,MAAuD;AACnE,MAAI,QAAQ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