nestjs-authentication 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/CHANGELOG.md +77 -2
  2. package/README.md +108 -0
  3. package/SECURITY.md +15 -0
  4. package/dist/classes/email.password.user.d.ts +13 -0
  5. package/dist/classes/email.password.user.d.ts.map +1 -0
  6. package/dist/classes/email.password.user.js +3 -0
  7. package/dist/classes/email.password.user.js.map +1 -0
  8. package/dist/constants.d.ts +13 -0
  9. package/dist/constants.d.ts.map +1 -1
  10. package/dist/constants.js +14 -1
  11. package/dist/constants.js.map +1 -1
  12. package/dist/context/auth.context.d.ts +38 -0
  13. package/dist/context/auth.context.d.ts.map +1 -0
  14. package/dist/context/auth.context.js +39 -0
  15. package/dist/context/auth.context.js.map +1 -0
  16. package/dist/context/decorators.d.ts +25 -0
  17. package/dist/context/decorators.d.ts.map +1 -0
  18. package/dist/context/decorators.js +38 -0
  19. package/dist/context/decorators.js.map +1 -0
  20. package/dist/context/index.d.ts +5 -0
  21. package/dist/context/index.d.ts.map +1 -0
  22. package/dist/context/index.js +21 -0
  23. package/dist/context/index.js.map +1 -0
  24. package/dist/context/interceptor.d.ts +15 -0
  25. package/dist/context/interceptor.d.ts.map +1 -0
  26. package/dist/context/interceptor.js +51 -0
  27. package/dist/context/interceptor.js.map +1 -0
  28. package/dist/context/service.d.ts +18 -0
  29. package/dist/context/service.d.ts.map +1 -0
  30. package/dist/context/service.js +45 -0
  31. package/dist/context/service.js.map +1 -0
  32. package/dist/encryptor.d.ts +20 -0
  33. package/dist/encryptor.d.ts.map +1 -1
  34. package/dist/encryptor.js +36 -6
  35. package/dist/encryptor.js.map +1 -1
  36. package/dist/encryptors/index.d.ts +3 -0
  37. package/dist/encryptors/index.d.ts.map +1 -0
  38. package/dist/encryptors/index.js +19 -0
  39. package/dist/encryptors/index.js.map +1 -0
  40. package/dist/encryptors/migrating.d.ts +28 -0
  41. package/dist/encryptors/migrating.d.ts.map +1 -0
  42. package/dist/encryptors/migrating.js +72 -0
  43. package/dist/encryptors/migrating.js.map +1 -0
  44. package/dist/encryptors/scrypt.d.ts +42 -0
  45. package/dist/encryptors/scrypt.d.ts.map +1 -0
  46. package/dist/encryptors/scrypt.js +85 -0
  47. package/dist/encryptors/scrypt.js.map +1 -0
  48. package/dist/errors.d.ts +32 -0
  49. package/dist/errors.d.ts.map +1 -0
  50. package/dist/errors.js +63 -0
  51. package/dist/errors.js.map +1 -0
  52. package/dist/guard.d.ts +115 -15
  53. package/dist/guard.d.ts.map +1 -1
  54. package/dist/guard.js +302 -90
  55. package/dist/guard.js.map +1 -1
  56. package/dist/index.d.ts +10 -4
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +15 -5
  59. package/dist/index.js.map +1 -1
  60. package/dist/injection.d.ts +3 -0
  61. package/dist/injection.d.ts.map +1 -0
  62. package/dist/injection.js +9 -0
  63. package/dist/injection.js.map +1 -0
  64. package/dist/interfaces/auth.user.d.ts +16 -5
  65. package/dist/interfaces/auth.user.d.ts.map +1 -1
  66. package/dist/interfaces/auth.user.js +6 -0
  67. package/dist/interfaces/auth.user.js.map +1 -1
  68. package/dist/interfaces/encrypt.d.ts +29 -1
  69. package/dist/interfaces/encrypt.d.ts.map +1 -1
  70. package/dist/interfaces/options.d.ts +52 -5
  71. package/dist/interfaces/options.d.ts.map +1 -1
  72. package/dist/interfaces/provider.d.ts +26 -3
  73. package/dist/interfaces/provider.d.ts.map +1 -1
  74. package/dist/module.d.ts +48 -6
  75. package/dist/module.d.ts.map +1 -1
  76. package/dist/module.js +153 -50
  77. package/dist/module.js.map +1 -1
  78. package/dist/providers/auth.provider.d.ts +12 -4
  79. package/dist/providers/auth.provider.d.ts.map +1 -1
  80. package/dist/providers/auth.provider.js +7 -1
  81. package/dist/providers/auth.provider.js.map +1 -1
  82. package/dist/providers/email.password.auth.provider.d.ts +75 -0
  83. package/dist/providers/email.password.auth.provider.d.ts.map +1 -0
  84. package/dist/providers/email.password.auth.provider.js +120 -0
  85. package/dist/providers/email.password.auth.provider.js.map +1 -0
  86. package/dist/providers/memory.user.provider.d.ts +39 -6
  87. package/dist/providers/memory.user.provider.d.ts.map +1 -1
  88. package/dist/providers/memory.user.provider.js +70 -15
  89. package/dist/providers/memory.user.provider.js.map +1 -1
  90. package/dist/scopes/decorators.d.ts +41 -0
  91. package/dist/scopes/decorators.d.ts.map +1 -0
  92. package/dist/scopes/decorators.js +44 -0
  93. package/dist/scopes/decorators.js.map +1 -0
  94. package/dist/scopes/index.d.ts +4 -0
  95. package/dist/scopes/index.d.ts.map +1 -0
  96. package/dist/scopes/index.js +20 -0
  97. package/dist/scopes/index.js.map +1 -0
  98. package/dist/scopes/service.d.ts +32 -0
  99. package/dist/scopes/service.d.ts.map +1 -0
  100. package/dist/scopes/service.js +90 -0
  101. package/dist/scopes/service.js.map +1 -0
  102. package/dist/scopes/utils.d.ts +8 -0
  103. package/dist/scopes/utils.d.ts.map +1 -0
  104. package/dist/scopes/utils.js +29 -0
  105. package/dist/scopes/utils.js.map +1 -0
  106. package/dist/service.d.ts +25 -6
  107. package/dist/service.d.ts.map +1 -1
  108. package/dist/service.js +36 -5
  109. package/dist/service.js.map +1 -1
  110. package/dist/session/index.d.ts +3 -0
  111. package/dist/session/index.d.ts.map +1 -0
  112. package/dist/session/index.js +19 -0
  113. package/dist/session/index.js.map +1 -0
  114. package/dist/session/manager.d.ts +32 -0
  115. package/dist/session/manager.d.ts.map +1 -0
  116. package/dist/session/manager.js +131 -0
  117. package/dist/session/manager.js.map +1 -0
  118. package/dist/session/request.d.ts +14 -0
  119. package/dist/session/request.d.ts.map +1 -0
  120. package/dist/session/request.js +59 -0
  121. package/dist/session/request.js.map +1 -0
  122. package/dist/strategies/emailpassword.d.ts +20 -7
  123. package/dist/strategies/emailpassword.d.ts.map +1 -1
  124. package/dist/strategies/emailpassword.js +42 -19
  125. package/dist/strategies/emailpassword.js.map +1 -1
  126. package/dist/strategies/extract.d.ts +23 -0
  127. package/dist/strategies/extract.d.ts.map +1 -0
  128. package/dist/strategies/extract.js +57 -0
  129. package/dist/strategies/extract.js.map +1 -0
  130. package/dist/strategies/index.d.ts +8 -0
  131. package/dist/strategies/index.d.ts.map +1 -0
  132. package/dist/strategies/index.js +24 -0
  133. package/dist/strategies/index.js.map +1 -0
  134. package/dist/strategies/interfaces.d.ts +65 -0
  135. package/dist/strategies/interfaces.d.ts.map +1 -0
  136. package/dist/{classes/memory.user.js → strategies/interfaces.js} +1 -1
  137. package/dist/strategies/interfaces.js.map +1 -0
  138. package/dist/strategies/jwt.d.ts +87 -15
  139. package/dist/strategies/jwt.d.ts.map +1 -1
  140. package/dist/strategies/jwt.js +140 -9
  141. package/dist/strategies/jwt.js.map +1 -1
  142. package/dist/strategies/passport.d.ts +22 -0
  143. package/dist/strategies/passport.d.ts.map +1 -0
  144. package/dist/strategies/passport.js +90 -0
  145. package/dist/strategies/passport.js.map +1 -0
  146. package/dist/strategies/registry.d.ts +33 -0
  147. package/dist/strategies/registry.d.ts.map +1 -0
  148. package/dist/strategies/registry.js +67 -0
  149. package/dist/strategies/registry.js.map +1 -0
  150. package/dist/strategies/session.d.ts +18 -0
  151. package/dist/strategies/session.d.ts.map +1 -0
  152. package/dist/strategies/session.js +79 -0
  153. package/dist/strategies/session.js.map +1 -0
  154. package/dist/transports/graphql.d.ts +28 -0
  155. package/dist/transports/graphql.d.ts.map +1 -0
  156. package/dist/transports/graphql.js +59 -0
  157. package/dist/transports/graphql.js.map +1 -0
  158. package/dist/transports/http.d.ts +13 -0
  159. package/dist/transports/http.d.ts.map +1 -0
  160. package/dist/transports/http.js +31 -0
  161. package/dist/transports/http.js.map +1 -0
  162. package/dist/transports/index.d.ts +8 -0
  163. package/dist/transports/index.d.ts.map +1 -0
  164. package/dist/transports/index.js +24 -0
  165. package/dist/transports/index.js.map +1 -0
  166. package/dist/transports/interfaces.d.ts +36 -0
  167. package/dist/transports/interfaces.d.ts.map +1 -0
  168. package/dist/transports/interfaces.js +3 -0
  169. package/dist/transports/interfaces.js.map +1 -0
  170. package/dist/transports/registry.d.ts +25 -0
  171. package/dist/transports/registry.d.ts.map +1 -0
  172. package/dist/transports/registry.js +55 -0
  173. package/dist/transports/registry.js.map +1 -0
  174. package/dist/transports/rpc.d.ts +23 -0
  175. package/dist/transports/rpc.d.ts.map +1 -0
  176. package/dist/transports/rpc.js +54 -0
  177. package/dist/transports/rpc.js.map +1 -0
  178. package/dist/transports/utils.d.ts +21 -0
  179. package/dist/transports/utils.d.ts.map +1 -0
  180. package/dist/transports/utils.js +86 -0
  181. package/dist/transports/utils.js.map +1 -0
  182. package/dist/transports/ws.d.ts +31 -0
  183. package/dist/transports/ws.d.ts.map +1 -0
  184. package/dist/transports/ws.js +52 -0
  185. package/dist/transports/ws.js.map +1 -0
  186. package/package.json +102 -60
  187. package/dist/classes/memory.user.d.ts +0 -7
  188. package/dist/classes/memory.user.d.ts.map +0 -1
  189. package/dist/classes/memory.user.js.map +0 -1
  190. package/dist/providers/auth.memory.user.provider.d.ts +0 -15
  191. package/dist/providers/auth.memory.user.provider.d.ts.map +0 -1
  192. package/dist/providers/auth.memory.user.provider.js +0 -30
  193. package/dist/providers/auth.memory.user.provider.js.map +0 -1
  194. package/dist/user.serializer.d.ts +0 -10
  195. package/dist/user.serializer.d.ts.map +0 -1
  196. package/dist/user.serializer.js +0 -53
  197. package/dist/user.serializer.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,4 +1,79 @@
1
- # Change Log
1
+ # Changelog
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
- See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
4
+
5
+ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [0.5.0] - 2026-11-16
8
+
9
+ ### BREAKING CHANGE
10
+
11
+ - Support NestJS v12 only (peer dependencies `@nestjs/common` and `@nestjs/core` `^12.0.0`), drop NestJS v8
12
+ - Node engine is now `>= 22.12.0` (required to load the ESM-only NestJS v12 packages with `require(esm)`)
13
+ - passport is optional: the strategies are native ([`AuthStrategy`](https://github.com/Pop-Code/nestjs-authentication/wiki/Strategies)), and the passport strategies work through an adapter when passport is installed
14
+ - `@nestjs/passport` is no longer a peer dependency, `passport` is an optional one (`^0.6.0 || ^0.7.0`: 0.5 is affected by a session fixation vulnerability, CVE-2022-25896), and `passport-jwt`, `passport-local` and `debug` are no longer dependencies
15
+ - `JwtStrategy` (built on jsonwebtoken v9, see its [migration notes](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9)) and `EmailPasswordStrategy` are native strategies: they no longer extend `PassportStrategy` and are not registered in passport. Their constructors, `validate()`, `getNamespace()` and `JwtStrategy.sign()` are unchanged
16
+ - `JwtStrategyOptions` has the option names of passport-jwt (`secretOrKey`, `secretOrKeyProvider`, `jwtFromRequest`, `algorithms`, `issuer`, `audience`, `ignoreExpiration`, `jsonWebTokenOptions`); `passReqToCallback` is not accepted, and `jwtFromRequest` defaults to the bearer token. Import `ExtractJwt` from `nestjs-authentication` (the passport-jwt extractors still work)
17
+ - `UserSerializer` is removed: the native `session` strategy stores the user in the same place (`session.passport.user`), so the existing sessions keep working
18
+ - `passport.initialize()` is no longer applied to the routes; the guard adds `req.logIn()`, `req.logOut()` (with a callback) and `req.isAuthenticated()`, compatible with passport
19
+ - Sessions: a login route saves the user with the `saveSession: true` guard option (`@Auth({ strategies: { emailpassword: {} }, saveSession: true })`), and reads it with `fromSession: true`. The `session` and `keepSessionInfo` options of the strategies are removed (the guard throws if they are set): use `saveSession` and `keepSessionInfo` on the guard. Logging in regenerates the session (against session fixation): `keepSessionInfo: true` keeps its data
20
+ - A session whose user or auth provider does not exist anymore is not authenticated (the user is removed from the session); the other errors of `loadUser()` are thrown
21
+ - `AuthGuard` with `fromSession: true` fails (500) when there is no session middleware, instead of silently ignoring the session
22
+ - `AuthModule` registers `AuthGuard` as a global guard. It only acts on the routes with `@Auth()`, `@Public()` or `@RequireScopes()` (or all of them with `globalGuard: true`), so the routes protected with `@UseGuards(new AuthGuard(...))` are not affected
23
+ - Your users keep their shape: `IAuthUser` (`authSerialize()`) and the `_id` / `email` / `passwordEncrypted` properties are no longer required
24
+ - `AuthMemoryUserProvider` is renamed `EmailPasswordAuthProvider`, and takes your functions (`findById`, `findByEmail`, `getId`, `getPasswordHash`, `updatePasswordHash`) instead of a user provider: it never receives the password in clear text, nor the other properties of the payload. The 0.4 constructor `(namespace, userProvider, encryptor)` and `getProvider()` are removed
25
+ - The payload stored in the sessions and the tokens is built by the auth provider: `{ sub, namespace }` (`user.authSerialize()` is still used when the user implements it). The `_id` and `id` of the existing sessions and tokens are still read
26
+ - `MemoryUser` is renamed `EmailPasswordUser`, and `MemoryUserCredentials` `EmailPasswordCredentials`
27
+ - `AuthGuard.getRequestReponse()` (typo) is renamed `getRequestResponse()`
28
+ - `AuthGuard.scopes` and `AuthGuard.registerScopes()` are removed: use the `AuthScopes` service
29
+ - `AuthService.loadUser()` is typed `Promise<U | undefined>`
30
+ - `Encryptor` throws if the key is not 32 bytes or the iv is not 16 bytes (it threw on the first `encrypt()`)
31
+
32
+ ### Fixed
33
+
34
+ - `forRootAsync()`: the `imports` are imported by the module, so `inject` can use their providers (they were ignored)
35
+ - `AuthGuard`: `null` users are not logged in (a `typeof user !== null` check was always true), and `request.authInfo` is an object keyed by strategy (it was an array)
36
+ - `EmailPasswordStrategy` no longer throws when the request has no body (express 5), and ignores a non string namespace
37
+ - Websockets and microservices are supported (they threw a `NotImplementedException`), and GraphQL subscriptions (they failed on the missing `context.req`)
38
+ - `registerAuthProviders()` accepts class providers, and the modules that provide their dependencies (`imports`)
39
+ - The module exports the `EmailPasswordStrategy`
40
+
41
+ ### Added
42
+
43
+ - Strategies: the `AuthStrategy` interface, `AuthModule.registerStrategies(providers, imports?)`, the `AuthStrategyRegistry`, the native `session` strategy (`SessionStrategy`), and `PassportAuthStrategy` (any passport strategy by name, OAuth redirects end the request)
44
+ - `EmailPasswordAuthProvider<User>` options, `MemoryUserProvider<User>` accessors (`getId`, `getEmail`, `setPasswordHash`) with `findById()` and `findByEmail()`, `IAuthProvider.serializeUser()`, `AuthService.serializeUser()`, and `JwtStrategy.signUser(user, { expiresIn, scope, namespace, claims })`
45
+ - `JwtStrategy`: `secretOrKeyProvider` returns a promise or uses the passport-jwt callback (so `passportJwtSecret()` of jwks-rsa works for JWKS), `verify()`, `sign()` uses the `secretOrKey` option when no key is given, and the `scope` / `scp` / `scopes` claims are the scopes of the request
46
+ - `ExtractJwt` (passport-jwt API, plus `fromCookie()`)
47
+ - Global guard and decorators: `@Auth(options)` on a class or a method, `@Public()`, and the `defaults` and `globalGuard` module options
48
+ - Scopes: `@RequireScopes(...)` and `@RequireAnyScope(...)` (wildcards: `orders:*`, `*`), `AuthContext.scopes`, the `scopes` module option (e.g. roles as scopes), the `scopeExceptionFactory` guard option (default: 403 `Insufficient scope`), and the `AuthScopes` service that lists the scopes required and requested in the application
49
+ - Transports: the guard and the decorators work on http (express and fastify), GraphQL (queries, mutations and subscriptions over graphql-ws), websockets (socket.io, ws) and microservices (gRPC, NATS, Kafka, RabbitMQ, TCP...)
50
+ - GraphQL: reads `context.req`, `context.request`, `context.reply.request`, and for subscriptions the upgrade request and the token in `connectionParams`
51
+ - socket.io: the handshake headers, cookies, session, query and `auth.token`; ws: `WsAuthTransport.setRequest(client, request)`
52
+ - microservices: the message metadata, or `data.headers`
53
+ - your own transports with the `transports` option of the module or of a guard (`AuthTransport`, `AuthTransports`)
54
+ - Auth context: `@CurrentUser()`, `@CurrentUser('property')`, `@CurrentAuth()` (user, strategy, namespace, auth info, transport, scopes) on every transport, and `AuthContextService` / `getAuthContext()` in any service, with `AsyncLocalStorage` (global `AuthContextInterceptor`, disable with `context: false`). `runWithAuthContext()` for jobs and tests
55
+ - Errors: the `exceptionFactory` guard option, `unauthorized()` (401, optional `WWW-Authenticate` challenge), `forbidden()`, `toTransportException()` (`WsException` / `RpcException`)
56
+ - `AuthGuard.withDefaults()` returns a guard class with default options
57
+ - Sessions: `sessionLogIn()`, `sessionLogOut()`, `getSessionPayload()`, `removeSessionUser()`, `decorateRequest()`, and the `sessionKey` module option. They work with express-session, @fastify/session and @fastify/secure-session (callback, promise or synchronous session methods, cookie sessions)
58
+ - `JwtStrategy` options `namespace` (loads all the users of the tokens with the auth provider of a namespace: the tokens of an identity provider) and `name` (a second jwt strategy)
59
+ - Pluggable encryptor: the `encryptor` option (an `IEncryptor` instance, or a class instantiated with dependency injection) is provided with the `ENCRYPTOR` token and the `@InjectEncryptor()` decorator. The default `Encryptor` is still used when only `encrypt` is set
60
+ - `IEncryptor.compare()` (optional, may be async) to check a password against a salted hash (bcrypt, argon2...); `encrypt()` may be async; `canVerify()` and `needsRehash()`
61
+ - `ScryptEncryptor`: password hashing with scrypt (built in Node.js), salted, with the parameters stored in the hash
62
+ - `MigratingEncryptor`: hashes with a new encryptor, verifies the legacy values and re-hashes them on login, with `IUserProvider.updatePassword()`
63
+ - `Encryptor.compare()` and `Encryptor.canVerify()`; `EmailPasswordAuthProvider` compares the passwords in constant time
64
+ - `AuthService.getAuthProviders()`, `MemoryUserProvider.removeUser()` and `updatePassword()`, the `DEFAULT_NAMESPACE` constant, the `AuthUserPayload`, `AuthModuleOptions` and `AuthModuleAsyncOptions` types
65
+ - `AuthProvider` and `IAuthProvider` have a second type parameter for the data given to `loadUser()`
66
+ - Tests of the code of the wiki tutorial and testing guide
67
+ - Documentation: TSDoc on the public API (kept in the published typings), a new README, guides in the [wiki](https://github.com/Pop-Code/nestjs-authentication/wiki)
68
+
69
+ ### Changed
70
+
71
+ - The `Encryptor` (aes-256-ctr with a fixed key and iv) is only kept to read old hashes: use `ScryptEncryptor`, and `MigratingEncryptor` to migrate the stored passwords
72
+ - Update dev dependencies (TypeScript 6, Jest 30, ESLint 10 with flat config, Prettier 3, typedoc 0.28, express 5 through @nestjs/platform-express 12) and switch to yarn v1
73
+ - Tests: unit tests of every component, and end-to-end tests with express, fastify, Apollo (queries and graphql-ws subscriptions), socket.io, a TCP microservice and passport strategies
74
+ - CI: tests on Node 24 and 26, a job with passport 0.6, and a smoke test on Node 22 (also without passport); bump all GitHub Actions; CodeQL and GitHub Pages (API reference) workflows
75
+ - Release workflow: create the GitHub release with the `gh` CLI and stage the npm release (trusted publishing with provenance), see `RELEASING.md`
76
+ - Dependabot: weekly, grouped updates for npm and GitHub Actions, keeping the supported ranges
77
+ - Define package contents with the `files` field in `package.json` (replaces `.npmignore`)
78
+ - The build removes `tsconfig.build.tsbuildinfo` (a stale file made `tsc -b` skip the build after `dist` was removed)
79
+ - Security reports go through GitHub private vulnerability reporting (`SECURITY.md`)
package/README.md CHANGED
@@ -1 +1,109 @@
1
1
  # nestjs-authentication
2
+
3
+ [![Test](https://github.com/Pop-Code/nestjs-authentication/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/Pop-Code/nestjs-authentication/actions/workflows/test.yml)
4
+ [![npm](https://img.shields.io/npm/v/nestjs-authentication.svg)][npm]
5
+ [![codecov](https://codecov.io/gh/Pop-Code/nestjs-authentication/branch/master/graph/badge.svg)](https://codecov.io/gh/Pop-Code/nestjs-authentication)
6
+
7
+ Authentication for [NestJS](https://nestjs.com) with several user sources and every transport. Any [passport](https://www.passportjs.org) strategy works too, but passport is optional.
8
+
9
+ - One guard, global with `@Auth()` / `@Public()` or per route, that tries one or more strategies in order, optionally from the session first
10
+ - Native `jwt` (jsonwebtoken), `emailpassword` and `session` strategies, your own (`AuthStrategy`), and the passport ecosystem through an adapter
11
+ - Scopes: `@RequireScopes()` from the token claims or your roles, and the list of the scopes of the application
12
+ - Auth providers per **namespace**: users, admins, api clients... each loaded from its own source
13
+ - Login sessions (express-session, @fastify/session, @fastify/secure-session), with the user stored as a small payload and loaded back on each request
14
+ - Every transport: http (express, fastify), GraphQL (queries, mutations, subscriptions), websockets (socket.io, ws), microservices
15
+ - `@CurrentUser()`, `@CurrentAuth()`, and the user of the current request in any service (`AuthContextService`)
16
+ - Password hashing with scrypt (built in), migration of legacy hashes on login, or your own encryptor (bcrypt, argon2...)
17
+
18
+ ## Requirements
19
+
20
+ | nestjs-authentication | NestJS | passport | Node.js |
21
+ | --------------------- | ------ | ------------------------ | -------- |
22
+ | 0.5.x | 12 | optional (0.6, 0.7) | >= 22.12 |
23
+ | 0.4.x | 8 | 0.5 + @nestjs/passport 8 | >= 14 |
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ npm install nestjs-authentication
29
+ # for login sessions: express-session (express), or @fastify/session / @fastify/secure-session (fastify)
30
+ npm install express-session
31
+ # optional, to use passport strategies (OAuth providers, SAML, LDAP...)
32
+ npm install passport
33
+ ```
34
+
35
+ ## Quick start
36
+
37
+ ```ts
38
+ // app.module.ts
39
+ @Module({
40
+ imports: [
41
+ AuthModule.forRoot({
42
+ encryptor: new ScryptEncryptor(),
43
+ jwt: { secretOrKey: process.env.JWT_SECRET, algorithms: ['HS256'] },
44
+ // the options of @Auth(): a valid token, or 401
45
+ defaults: { strategies: { jwt: {} }, required: true, exceptionFactory: unauthorized() }
46
+ }),
47
+ // your users keep their shape: say how to find and read them
48
+ AuthModule.registerAuthProviders(
49
+ [
50
+ {
51
+ provide: 'USERS_AUTH_PROVIDER',
52
+ inject: [ENCRYPTOR, UsersService],
53
+ useFactory: (encryptor: IEncryptor, users: UsersService) =>
54
+ new EmailPasswordAuthProvider<User>({
55
+ encryptor,
56
+ findById: (id) => users.findById(id),
57
+ findByEmail: (email) => users.findByEmail(email),
58
+ getId: (user) => user.id,
59
+ getPasswordHash: (user) => user.passwordHash
60
+ })
61
+ }
62
+ ],
63
+ [UsersModule]
64
+ )
65
+ ],
66
+ controllers: [AuthController]
67
+ })
68
+ export class AppModule {}
69
+
70
+ // auth.controller.ts
71
+ @Controller('auth')
72
+ export class AuthController {
73
+ constructor(private readonly jwt: JwtStrategy<User>) {}
74
+
75
+ // email + password in the body
76
+ @Post('login')
77
+ @Auth({ strategies: { emailpassword: {} } })
78
+ login(@CurrentUser() user: User) {
79
+ return { token: this.jwt.signUser(user, { expiresIn: '1h', scope: ['orders:read'] }) };
80
+ }
81
+
82
+ // a valid token with the scope
83
+ @Get('orders')
84
+ @Auth()
85
+ @RequireScopes('orders:read')
86
+ orders(@CurrentUser() user: User) {}
87
+ }
88
+ ```
89
+
90
+ The same decorators protect GraphQL resolvers, websocket gateways and microservices. The [Getting started](https://github.com/Pop-Code/nestjs-authentication/wiki/Getting-Started) tutorial builds this app step by step.
91
+
92
+ ## Documentation
93
+
94
+ - [Wiki](https://github.com/Pop-Code/nestjs-authentication/wiki)
95
+ - [API](https://pop-code.github.io/nestjs-authentication)
96
+ - [Changelog](https://github.com/Pop-Code/nestjs-authentication/blob/master/CHANGELOG.md)
97
+
98
+ ## Development
99
+
100
+ ```bash
101
+ yarn install
102
+ yarn lint && yarn build && yarn test
103
+ yarn doc # regenerate the API reference in ./docs
104
+ ```
105
+
106
+ The tests need Node.js >= 24.9 (Jest loads the ESM-only NestJS 12 packages).
107
+ See [RELEASING.md](./RELEASING.md) to publish a version.
108
+
109
+ [npm]: https://www.npmjs.com/package/nestjs-authentication
package/SECURITY.md ADDED
@@ -0,0 +1,15 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ | Version | Supported |
6
+ | ------- | ------------------ |
7
+ | 0.5.x | :white_check_mark: |
8
+ | < 0.5 | :x: |
9
+
10
+ ## Reporting a Vulnerability
11
+
12
+ Please do not open a public issue for a vulnerability.
13
+ Report it privately with [GitHub private vulnerability reporting](https://github.com/Pop-Code/nestjs-authentication/security/advisories/new)
14
+ (**Security** tab → **Report a vulnerability**).
15
+ If the report is accepted, we will publish a fix and an advisory.
@@ -0,0 +1,13 @@
1
+ import { IAuthUser } from '../interfaces/auth.user';
2
+ /**
3
+ * The default shape of the users of {@link EmailPasswordAuthProvider} and {@link MemoryUserProvider}.
4
+ * Not required: give the `getId` / `getPasswordHash` options for another shape.
5
+ */
6
+ export interface EmailPasswordUser extends Partial<IAuthUser> {
7
+ /** The id of the user. */
8
+ _id: any;
9
+ email: string;
10
+ /** The password encrypted (hashed) with the encryptor: `await encryptor.encrypt(password)`. */
11
+ passwordEncrypted: string;
12
+ }
13
+ //# sourceMappingURL=email.password.user.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"email.password.user.d.ts","sourceRoot":"","sources":["../../src/classes/email.password.user.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEpD;;;GAGG;AACH,MAAM,WAAW,iBAAkB,SAAQ,OAAO,CAAC,SAAS,CAAC;IACzD,0BAA0B;IAC1B,GAAG,EAAE,GAAG,CAAC;IACT,KAAK,EAAE,MAAM,CAAC;IACd,+FAA+F;IAC/F,iBAAiB,EAAE,MAAM,CAAC;CAC7B"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=email.password.user.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"email.password.user.js","sourceRoot":"","sources":["../../src/classes/email.password.user.ts"],"names":[],"mappings":""}
@@ -1,3 +1,16 @@
1
+ /** Injection token of the {@link AuthModuleOptions} given to `AuthModule.forRoot()` / `forRootAsync()`. */
1
2
  export declare const MODULE_OPTIONS_TOKEN = "nestjs-authentication:options";
3
+ /** Injection token of the internal provider that registers the auth providers given to `AuthModule.registerAuthProviders()`. */
2
4
  export declare const MODULE_PROVIDER_REGISTER = "nestjs-authentication:provider.register";
5
+ /** Name of the auth provider used when a request, a session or a token has no namespace. */
6
+ export declare const DEFAULT_NAMESPACE = "default";
7
+ /**
8
+ * Injection token of the {@link IEncryptor} of the module: the `encryptor` option,
9
+ * or the default {@link Encryptor} when only the `encrypt` option is set. Inject it with {@link InjectEncryptor}.
10
+ */
11
+ export declare const ENCRYPTOR = "nestjs-authentication:encryptor";
12
+ /** Injection token of the internal provider that registers the `transports` option. */
13
+ export declare const MODULE_TRANSPORTS_REGISTER = "nestjs-authentication:transports.register";
14
+ /** Injection token of the internal provider that registers the built-in strategies. */
15
+ export declare const MODULE_STRATEGY_REGISTER = "nestjs-authentication:strategy.register";
3
16
  //# sourceMappingURL=constants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oBAAoB,kCAAkC,CAAC;AACpE,eAAO,MAAM,wBAAwB,4CAA4C,CAAC"}
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,eAAO,MAAM,oBAAoB,kCAAkC,CAAC;AAEpE,gIAAgI;AAChI,eAAO,MAAM,wBAAwB,4CAA4C,CAAC;AAElF,4FAA4F;AAC5F,eAAO,MAAM,iBAAiB,YAAY,CAAC;AAE3C;;;GAGG;AACH,eAAO,MAAM,SAAS,oCAAoC,CAAC;AAE3D,uFAAuF;AACvF,eAAO,MAAM,0BAA0B,8CAA8C,CAAC;AAEtF,uFAAuF;AACvF,eAAO,MAAM,wBAAwB,4CAA4C,CAAC"}
package/dist/constants.js CHANGED
@@ -1,6 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MODULE_PROVIDER_REGISTER = exports.MODULE_OPTIONS_TOKEN = void 0;
3
+ exports.MODULE_STRATEGY_REGISTER = exports.MODULE_TRANSPORTS_REGISTER = exports.ENCRYPTOR = exports.DEFAULT_NAMESPACE = exports.MODULE_PROVIDER_REGISTER = exports.MODULE_OPTIONS_TOKEN = void 0;
4
+ /** Injection token of the {@link AuthModuleOptions} given to `AuthModule.forRoot()` / `forRootAsync()`. */
4
5
  exports.MODULE_OPTIONS_TOKEN = 'nestjs-authentication:options';
6
+ /** Injection token of the internal provider that registers the auth providers given to `AuthModule.registerAuthProviders()`. */
5
7
  exports.MODULE_PROVIDER_REGISTER = 'nestjs-authentication:provider.register';
8
+ /** Name of the auth provider used when a request, a session or a token has no namespace. */
9
+ exports.DEFAULT_NAMESPACE = 'default';
10
+ /**
11
+ * Injection token of the {@link IEncryptor} of the module: the `encryptor` option,
12
+ * or the default {@link Encryptor} when only the `encrypt` option is set. Inject it with {@link InjectEncryptor}.
13
+ */
14
+ exports.ENCRYPTOR = 'nestjs-authentication:encryptor';
15
+ /** Injection token of the internal provider that registers the `transports` option. */
16
+ exports.MODULE_TRANSPORTS_REGISTER = 'nestjs-authentication:transports.register';
17
+ /** Injection token of the internal provider that registers the built-in strategies. */
18
+ exports.MODULE_STRATEGY_REGISTER = 'nestjs-authentication:strategy.register';
6
19
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,oBAAoB,GAAG,+BAA+B,CAAC;AACvD,QAAA,wBAAwB,GAAG,yCAAyC,CAAC"}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAA,2GAA2G;AAC9F,QAAA,oBAAoB,GAAG,+BAA+B,CAAC;AAEpE,gIAAgI;AACnH,QAAA,wBAAwB,GAAG,yCAAyC,CAAC;AAElF,4FAA4F;AAC/E,QAAA,iBAAiB,GAAG,SAAS,CAAC;AAE3C;;;GAGG;AACU,QAAA,SAAS,GAAG,iCAAiC,CAAC;AAE3D,uFAAuF;AAC1E,QAAA,0BAA0B,GAAG,2CAA2C,CAAC;AAEtF,uFAAuF;AAC1E,QAAA,wBAAwB,GAAG,yCAAyC,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The authentication of the current request, operation, connection or message.
3
+ *
4
+ * Set by the {@link AuthGuard} when it authenticates the request. Read it with {@link CurrentAuth} / {@link CurrentUser},
5
+ * the {@link AuthContextService}, or {@link getAuthContext}.
6
+ */
7
+ export interface AuthContext<User = any> {
8
+ /** The authenticated user. */
9
+ user: User;
10
+ /** The strategy that authenticated the user, `session` when it was restored from the session. */
11
+ strategy: string;
12
+ /** The namespace of the auth provider that loaded the user, if known. */
13
+ namespace?: string;
14
+ /** The auth info returned by the strategy. */
15
+ info?: unknown;
16
+ /** The transport of the request (`http`, `graphql`, `ws`, `rpc`...). */
17
+ transport: string;
18
+ /** The scopes granted to the request: from the strategy (e.g. the token `scope` claim) and the `scopes` module option. */
19
+ scopes?: string[];
20
+ }
21
+ /** The key of the {@link AuthContext} on the request. */
22
+ export declare const AUTH_CONTEXT: unique symbol;
23
+ /**
24
+ * Returns the {@link AuthContext} of the current async context, or `undefined` if the request is not authenticated.
25
+ *
26
+ * Available in the handlers and everything they call, when the {@link AuthContextInterceptor} is enabled (default).
27
+ */
28
+ export declare function getAuthContext<User = any>(): AuthContext<User> | undefined;
29
+ /**
30
+ * Runs `fn` with an {@link AuthContext}: {@link getAuthContext} and the {@link AuthContextService} return it.
31
+ * Used by the {@link AuthContextInterceptor}, and useful in tests and jobs (queues, crons) that run as a user.
32
+ */
33
+ export declare function runWithAuthContext<R>(auth: AuthContext | undefined, fn: () => R): R;
34
+ /** Returns the {@link AuthContext} stored on a request by the guard. */
35
+ export declare function getRequestAuthContext<User = any>(request: unknown): AuthContext<User> | undefined;
36
+ /** Stores an {@link AuthContext} on a request (`undefined` removes it). */
37
+ export declare function setRequestAuthContext(request: object, auth: AuthContext | undefined): void;
38
+ //# sourceMappingURL=auth.context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.context.d.ts","sourceRoot":"","sources":["../../src/context/auth.context.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,WAAW,WAAW,CAAC,IAAI,GAAG,GAAG;IACnC,8BAA8B;IAC9B,IAAI,EAAE,IAAI,CAAC;IACX,iGAAiG;IACjG,QAAQ,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,8CAA8C;IAC9C,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,wEAAwE;IACxE,SAAS,EAAE,MAAM,CAAC;IAClB,0HAA0H;IAC1H,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED,yDAAyD;AACzD,eAAO,MAAM,YAAY,eAA8C,CAAC;AAQxE;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,GAAG,GAAG,KAAK,WAAW,CAAC,IAAI,CAAC,GAAG,SAAS,CAE1E;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,GAAG,SAAS,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAEnF;AAED,wEAAwE;AACxE,wBAAgB,qBAAqB,CAAC,IAAI,GAAG,GAAG,EAAE,OAAO,EAAE,OAAO,GAAG,WAAW,CAAC,IAAI,CAAC,GAAG,SAAS,CAKjG;AAED,2EAA2E;AAC3E,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAE1F"}
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AUTH_CONTEXT = void 0;
4
+ exports.getAuthContext = getAuthContext;
5
+ exports.runWithAuthContext = runWithAuthContext;
6
+ exports.getRequestAuthContext = getRequestAuthContext;
7
+ exports.setRequestAuthContext = setRequestAuthContext;
8
+ const async_hooks_1 = require("async_hooks");
9
+ /** The key of the {@link AuthContext} on the request. */
10
+ exports.AUTH_CONTEXT = Symbol.for('nestjs-authentication:context');
11
+ const storage = new async_hooks_1.AsyncLocalStorage();
12
+ /**
13
+ * Returns the {@link AuthContext} of the current async context, or `undefined` if the request is not authenticated.
14
+ *
15
+ * Available in the handlers and everything they call, when the {@link AuthContextInterceptor} is enabled (default).
16
+ */
17
+ function getAuthContext() {
18
+ var _a;
19
+ return (_a = storage.getStore()) === null || _a === void 0 ? void 0 : _a.auth;
20
+ }
21
+ /**
22
+ * Runs `fn` with an {@link AuthContext}: {@link getAuthContext} and the {@link AuthContextService} return it.
23
+ * Used by the {@link AuthContextInterceptor}, and useful in tests and jobs (queues, crons) that run as a user.
24
+ */
25
+ function runWithAuthContext(auth, fn) {
26
+ return storage.run({ auth }, fn);
27
+ }
28
+ /** Returns the {@link AuthContext} stored on a request by the guard. */
29
+ function getRequestAuthContext(request) {
30
+ if (request === undefined || request === null || typeof request !== 'object') {
31
+ return undefined;
32
+ }
33
+ return request[exports.AUTH_CONTEXT];
34
+ }
35
+ /** Stores an {@link AuthContext} on a request (`undefined` removes it). */
36
+ function setRequestAuthContext(request, auth) {
37
+ request[exports.AUTH_CONTEXT] = auth;
38
+ }
39
+ //# sourceMappingURL=auth.context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.context.js","sourceRoot":"","sources":["../../src/context/auth.context.ts"],"names":[],"mappings":";;;AAqCA,wCAEC;AAMD,gDAEC;AAGD,sDAKC;AAGD,sDAEC;AA5DD,6CAAgD;AAuBhD,yDAAyD;AAC5C,QAAA,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;AAMxE,MAAM,OAAO,GAAG,IAAI,+BAAiB,EAAoB,CAAC;AAE1D;;;;GAIG;AACH,SAAgB,cAAc;;IAC1B,OAAO,MAAA,OAAO,CAAC,QAAQ,EAAE,0CAAE,IAAI,CAAC;AACpC,CAAC;AAED;;;GAGG;AACH,SAAgB,kBAAkB,CAAI,IAA6B,EAAE,EAAW;IAC5E,OAAO,OAAO,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;AACrC,CAAC;AAED,wEAAwE;AACxE,SAAgB,qBAAqB,CAAa,OAAgB;IAC9D,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC3E,OAAO,SAAS,CAAC;IACrB,CAAC;IACD,OAAQ,OAAyD,CAAC,oBAAY,CAAC,CAAC;AACpF,CAAC;AAED,2EAA2E;AAC3E,SAAgB,qBAAqB,CAAC,OAAe,EAAE,IAA6B;IAC/E,OAAmD,CAAC,oBAAY,CAAC,GAAG,IAAI,CAAC;AAC9E,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { ExecutionContext } from '@nestjs/common';
2
+ import { AuthContext } from './auth.context';
3
+ /** Returns the {@link AuthContext} of an execution context. */
4
+ export declare function getExecutionAuthContext<User = any>(context: ExecutionContext): AuthContext<User> | undefined;
5
+ /**
6
+ * Injects the {@link AuthContext} of the request (http, GraphQL, websockets, microservices), `undefined` if it is not
7
+ * authenticated.
8
+ *
9
+ * ```ts
10
+ * @Get('me')
11
+ * me(@CurrentAuth() auth: AuthContext<User>) {}
12
+ * ```
13
+ */
14
+ export declare const CurrentAuth: (...dataOrPipes: unknown[]) => ParameterDecorator;
15
+ /**
16
+ * Injects the authenticated user (http, GraphQL, websockets, microservices), `undefined` if the request is not
17
+ * authenticated. Give a property name to inject only this property.
18
+ *
19
+ * ```ts
20
+ * @Get('me')
21
+ * me(@CurrentUser() user: User, @CurrentUser('email') email: string) {}
22
+ * ```
23
+ */
24
+ export declare const CurrentUser: (...dataOrPipes: (string | import("@nestjs/common").ParameterDecoratorOptions | import("@nestjs/common").PipeTransform<any, any> | import("@nestjs/common").Type<import("@nestjs/common").PipeTransform<any, any>> | undefined)[]) => ParameterDecorator;
25
+ //# sourceMappingURL=decorators.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../../src/context/decorators.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAGxE,OAAO,EAAE,WAAW,EAAyC,MAAM,gBAAgB,CAAC;AAEpF,+DAA+D;AAC/D,wBAAgB,uBAAuB,CAAC,IAAI,GAAG,GAAG,EAAE,OAAO,EAAE,gBAAgB,GAAG,WAAW,CAAC,IAAI,CAAC,GAAG,SAAS,CAK5G;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,mDAEvB,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,0PAGtB,CAAC"}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CurrentUser = exports.CurrentAuth = void 0;
4
+ exports.getExecutionAuthContext = getExecutionAuthContext;
5
+ const common_1 = require("@nestjs/common");
6
+ const registry_1 = require("../transports/registry");
7
+ const auth_context_1 = require("./auth.context");
8
+ /** Returns the {@link AuthContext} of an execution context. */
9
+ function getExecutionAuthContext(context) {
10
+ const transport = registry_1.AuthTransports.find(context);
11
+ const fromRequest = transport !== undefined ? (0, auth_context_1.getRequestAuthContext)(transport.getRequest(context)) : undefined;
12
+ return fromRequest !== null && fromRequest !== void 0 ? fromRequest : (0, auth_context_1.getAuthContext)();
13
+ }
14
+ /**
15
+ * Injects the {@link AuthContext} of the request (http, GraphQL, websockets, microservices), `undefined` if it is not
16
+ * authenticated.
17
+ *
18
+ * ```ts
19
+ * @Get('me')
20
+ * me(@CurrentAuth() auth: AuthContext<User>) {}
21
+ * ```
22
+ */
23
+ exports.CurrentAuth = (0, common_1.createParamDecorator)((_data, context) => getExecutionAuthContext(context));
24
+ /**
25
+ * Injects the authenticated user (http, GraphQL, websockets, microservices), `undefined` if the request is not
26
+ * authenticated. Give a property name to inject only this property.
27
+ *
28
+ * ```ts
29
+ * @Get('me')
30
+ * me(@CurrentUser() user: User, @CurrentUser('email') email: string) {}
31
+ * ```
32
+ */
33
+ exports.CurrentUser = (0, common_1.createParamDecorator)((property, context) => {
34
+ var _a;
35
+ const user = (_a = getExecutionAuthContext(context)) === null || _a === void 0 ? void 0 : _a.user;
36
+ return property !== undefined && user !== undefined && user !== null ? user[property] : user;
37
+ });
38
+ //# sourceMappingURL=decorators.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorators.js","sourceRoot":"","sources":["../../src/context/decorators.ts"],"names":[],"mappings":";;;AAMA,0DAKC;AAXD,2CAAwE;AAExE,qDAAwD;AACxD,iDAAoF;AAEpF,+DAA+D;AAC/D,SAAgB,uBAAuB,CAAa,OAAyB;IACzE,MAAM,SAAS,GAAG,yBAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC/C,MAAM,WAAW,GACb,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,IAAA,oCAAqB,EAAO,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACrG,OAAO,WAAW,aAAX,WAAW,cAAX,WAAW,GAAI,IAAA,6BAAc,GAAQ,CAAC;AACjD,CAAC;AAED;;;;;;;;GAQG;AACU,QAAA,WAAW,GAAG,IAAA,6BAAoB,EAAC,CAAC,KAAc,EAAE,OAAyB,EAAE,EAAE,CAC1F,uBAAuB,CAAC,OAAO,CAAC,CACnC,CAAC;AAEF;;;;;;;;GAQG;AACU,QAAA,WAAW,GAAG,IAAA,6BAAoB,EAAC,CAAC,QAA4B,EAAE,OAAyB,EAAE,EAAE;;IACxG,MAAM,IAAI,GAAG,MAAA,uBAAuB,CAAC,OAAO,CAAC,0CAAE,IAAI,CAAC;IACpD,OAAO,QAAQ,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACjG,CAAC,CAAC,CAAC"}
@@ -0,0 +1,5 @@
1
+ export * from './auth.context';
2
+ export * from './decorators';
3
+ export * from './interceptor';
4
+ export * from './service';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/context/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./auth.context"), exports);
18
+ __exportStar(require("./decorators"), exports);
19
+ __exportStar(require("./interceptor"), exports);
20
+ __exportStar(require("./service"), exports);
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/context/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,iDAA+B;AAC/B,+CAA6B;AAC7B,gDAA8B;AAC9B,4CAA0B"}
@@ -0,0 +1,15 @@
1
+ import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
2
+ import { Observable } from 'rxjs';
3
+ import { IAuthModuleOptions } from '../interfaces/options';
4
+ /**
5
+ * Runs the handlers in the {@link AuthContext} set by the guard, so {@link getAuthContext} and the
6
+ * {@link AuthContextService} return it in everything the handler calls.
7
+ *
8
+ * Registered as a global interceptor by the {@link AuthModule} (disable it with `context: false`).
9
+ */
10
+ export declare class AuthContextInterceptor implements NestInterceptor {
11
+ protected readonly options?: IAuthModuleOptions | undefined;
12
+ constructor(options?: IAuthModuleOptions | undefined);
13
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown>;
14
+ }
15
+ //# sourceMappingURL=interceptor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interceptor.d.ts","sourceRoot":"","sources":["../../src/context/interceptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAsB,eAAe,EAAY,MAAM,gBAAgB,CAAC;AAC9G,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAGlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAI3D;;;;;GAKG;AACH,qBACa,sBAAuB,YAAW,eAAe;IACJ,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,kBAAkB;gBAA5B,OAAO,CAAC,EAAE,kBAAkB,YAAA;IAErG,SAAS,CAAC,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,WAAW,GAAG,UAAU,CAAC,OAAO,CAAC;CAY/E"}
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AuthContextInterceptor = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const constants_1 = require("../constants");
18
+ const registry_1 = require("../transports/registry");
19
+ const auth_context_1 = require("./auth.context");
20
+ /**
21
+ * Runs the handlers in the {@link AuthContext} set by the guard, so {@link getAuthContext} and the
22
+ * {@link AuthContextService} return it in everything the handler calls.
23
+ *
24
+ * Registered as a global interceptor by the {@link AuthModule} (disable it with `context: false`).
25
+ */
26
+ let AuthContextInterceptor = class AuthContextInterceptor {
27
+ constructor(options) {
28
+ this.options = options;
29
+ }
30
+ intercept(context, next) {
31
+ var _a;
32
+ if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.context) === false) {
33
+ return next.handle();
34
+ }
35
+ const transport = registry_1.AuthTransports.find(context);
36
+ if (transport === undefined) {
37
+ return next.handle();
38
+ }
39
+ const auth = (0, auth_context_1.getRequestAuthContext)(transport.getRequest(context));
40
+ // next.handle() binds the handler to the async context it is called in
41
+ return (0, auth_context_1.runWithAuthContext)(auth, () => next.handle());
42
+ }
43
+ };
44
+ exports.AuthContextInterceptor = AuthContextInterceptor;
45
+ exports.AuthContextInterceptor = AuthContextInterceptor = __decorate([
46
+ (0, common_1.Injectable)(),
47
+ __param(0, (0, common_1.Optional)()),
48
+ __param(0, (0, common_1.Inject)(constants_1.MODULE_OPTIONS_TOKEN)),
49
+ __metadata("design:paramtypes", [Object])
50
+ ], AuthContextInterceptor);
51
+ //# sourceMappingURL=interceptor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../../src/context/interceptor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAA8G;AAG9G,4CAAoD;AAEpD,qDAAwD;AACxD,iDAA2E;AAE3E;;;;;GAKG;AAEI,IAAM,sBAAsB,GAA5B,MAAM,sBAAsB;IAC/B,YAAyE,OAA4B;QAA5B,YAAO,GAAP,OAAO,CAAqB;IAAG,CAAC;IAEzG,SAAS,CAAC,OAAyB,EAAE,IAAiB;;QAClD,IAAI,CAAA,MAAA,IAAI,CAAC,OAAO,0CAAE,OAAO,MAAK,KAAK,EAAE,CAAC;YAClC,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC;QACzB,CAAC;QACD,MAAM,SAAS,GAAG,yBAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC/C,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAC1B,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC;QACzB,CAAC;QACD,MAAM,IAAI,GAAG,IAAA,oCAAqB,EAAC,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;QAClE,uEAAuE;QACvE,OAAO,IAAA,iCAAkB,EAAC,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IACzD,CAAC;CACJ,CAAA;AAfY,wDAAsB;iCAAtB,sBAAsB;IADlC,IAAA,mBAAU,GAAE;IAEI,WAAA,IAAA,iBAAQ,GAAE,CAAA;IAAE,WAAA,IAAA,eAAM,EAAC,gCAAoB,CAAC,CAAA;;GAD5C,sBAAsB,CAelC"}
@@ -0,0 +1,18 @@
1
+ import { AuthContext } from './auth.context';
2
+ /**
3
+ * Reads the {@link AuthContext} of the current request in any service (no request scope needed).
4
+ */
5
+ export declare class AuthContextService<User = any> {
6
+ /** Returns the auth context, or `undefined` if the request is not authenticated. */
7
+ get(): AuthContext<User> | undefined;
8
+ /** Returns the authenticated user, or `undefined`. */
9
+ getUser(): User | undefined;
10
+ /**
11
+ * Returns the authenticated user.
12
+ *
13
+ * @throws UnauthorizedException if the request is not authenticated
14
+ */
15
+ getUserOrFail(): User;
16
+ isAuthenticated(): boolean;
17
+ }
18
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/context/service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAkB,MAAM,gBAAgB,CAAC;AAE7D;;GAEG;AACH,qBACa,kBAAkB,CAAC,IAAI,GAAG,GAAG;IACtC,oFAAoF;IACpF,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,GAAG,SAAS;IAIpC,sDAAsD;IACtD,OAAO,IAAI,IAAI,GAAG,SAAS;IAI3B;;;;OAIG;IACH,aAAa,IAAI,IAAI;IAQrB,eAAe,IAAI,OAAO;CAG7B"}