@nestjs-kitchen/authz 1.0.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 (66) hide show
  1. package/README.md +0 -0
  2. package/dist/authz.provider.d.ts +7 -0
  3. package/dist/authz.provider.js +34 -0
  4. package/dist/constants.d.ts +11 -0
  5. package/dist/constants.js +46 -0
  6. package/dist/errors.d.ts +12 -0
  7. package/dist/errors.js +60 -0
  8. package/dist/index.d.ts +21 -0
  9. package/dist/index.js +43 -0
  10. package/dist/jwt/extract-jwt.d.ts +71 -0
  11. package/dist/jwt/extract-jwt.js +162 -0
  12. package/dist/jwt/index.d.ts +16 -0
  13. package/dist/jwt/index.js +30 -0
  14. package/dist/jwt/jwt-authz-als.middleware.d.ts +28 -0
  15. package/dist/jwt/jwt-authz-als.middleware.js +83 -0
  16. package/dist/jwt/jwt-authz.guard.d.ts +60 -0
  17. package/dist/jwt/jwt-authz.guard.js +182 -0
  18. package/dist/jwt/jwt-authz.interface.d.ts +58 -0
  19. package/dist/jwt/jwt-authz.interface.js +94 -0
  20. package/dist/jwt/jwt-authz.module.d.ts +80 -0
  21. package/dist/jwt/jwt-authz.module.js +244 -0
  22. package/dist/jwt/jwt-authz.service.d.ts +33 -0
  23. package/dist/jwt/jwt-authz.service.js +144 -0
  24. package/dist/jwt/jwt-authz.strategy.d.ts +40 -0
  25. package/dist/jwt/jwt-authz.strategy.js +194 -0
  26. package/dist/session/index.d.ts +12 -0
  27. package/dist/session/index.js +27 -0
  28. package/dist/session/session-authz-als.middleware.d.ts +25 -0
  29. package/dist/session/session-authz-als.middleware.js +134 -0
  30. package/dist/session/session-authz.guard.d.ts +43 -0
  31. package/dist/session/session-authz.guard.js +142 -0
  32. package/dist/session/session-authz.interface.d.ts +23 -0
  33. package/dist/session/session-authz.interface.js +43 -0
  34. package/dist/session/session-authz.module.d.ts +71 -0
  35. package/dist/session/session-authz.module.js +245 -0
  36. package/dist/session/session-authz.service.d.ts +20 -0
  37. package/dist/session/session-authz.service.js +93 -0
  38. package/dist/session/session-authz.strategy.d.ts +24 -0
  39. package/dist/session/session-authz.strategy.js +107 -0
  40. package/dist/user.decorator.d.ts +6 -0
  41. package/dist/user.decorator.js +36 -0
  42. package/dist/utils/cookie-parsers.d.ts +12 -0
  43. package/dist/utils/cookie-parsers.js +77 -0
  44. package/dist/utils/create-authz-decorator-factory.d.ts +9 -0
  45. package/dist/utils/create-authz-decorator-factory.js +56 -0
  46. package/dist/utils/create-set-cookie-fn.d.ts +9 -0
  47. package/dist/utils/create-set-cookie-fn.js +46 -0
  48. package/dist/utils/generics.d.ts +6 -0
  49. package/dist/utils/generics.js +66 -0
  50. package/dist/utils/get-allow-anonymous.d.ts +11 -0
  51. package/dist/utils/get-allow-anonymous.js +30 -0
  52. package/dist/utils/get-als-store.d.ts +5 -0
  53. package/dist/utils/get-als-store.js +35 -0
  54. package/dist/utils/get-context-authz-meta-params-list.d.ts +12 -0
  55. package/dist/utils/get-context-authz-meta-params-list.js +36 -0
  56. package/dist/utils/get-passport-property.d.ts +3 -0
  57. package/dist/utils/get-passport-property.js +31 -0
  58. package/dist/utils/index.d.ts +16 -0
  59. package/dist/utils/index.js +41 -0
  60. package/dist/utils/merge-dynamic-module-configs.d.ts +5 -0
  61. package/dist/utils/merge-dynamic-module-configs.js +50 -0
  62. package/dist/utils/msgpackrs.d.ts +4 -0
  63. package/dist/utils/msgpackrs.js +37 -0
  64. package/dist/utils/types.d.ts +56 -0
  65. package/dist/utils/types.js +15 -0
  66. package/package.json +68 -0
@@ -0,0 +1,244 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
21
+ var jwt_authz_module_exports = {};
22
+ __export(jwt_authz_module_exports, {
23
+ createJwtAuthzModule: () => createJwtAuthzModule
24
+ });
25
+ module.exports = __toCommonJS(jwt_authz_module_exports);
26
+ var import_node_async_hooks = require("node:async_hooks");
27
+ var import_common = require("@nestjs/common");
28
+ var import_uid = require("uid");
29
+ var import_constants = require("../constants");
30
+ var import_errors = require("../errors");
31
+ var import_utils = require("../utils");
32
+ var import_jwt_authz_als = require("./jwt-authz-als.middleware");
33
+ var import_jwt_authz = require("./jwt-authz.guard");
34
+ var import_jwt_authz2 = require("./jwt-authz.interface");
35
+ var import_jwt_authz3 = require("./jwt-authz.service");
36
+ var import_jwt_authz4 = require("./jwt-authz.strategy");
37
+ function _ts_decorate(decorators, target, key, desc) {
38
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
39
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
40
+ 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;
41
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
42
+ }
43
+ __name(_ts_decorate, "_ts_decorate");
44
+ function _ts_metadata(k, v) {
45
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
46
+ }
47
+ __name(_ts_metadata, "_ts_metadata");
48
+ function _ts_param(paramIndex, decorator) {
49
+ return function(target, key) {
50
+ decorator(target, key, paramIndex);
51
+ };
52
+ }
53
+ __name(_ts_param, "_ts_param");
54
+ const store = {
55
+ globalInited: 0
56
+ };
57
+ const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, ASYNC_OPTIONS_TYPE, OPTIONS_TYPE } = new import_common.ConfigurableModuleBuilder({
58
+ moduleName: "JwtAuthModule"
59
+ }).setFactoryMethodName("createJwtAuthzModuleOptions").setExtras({
60
+ authzProvider: void 0,
61
+ global: false
62
+ }, (definition, extras) => {
63
+ const { authzProvider, global } = extras;
64
+ if (!authzProvider) {
65
+ throw new import_errors.AuthzError(`InternalError: Missing parameter 'authzProvider' in configuration.`);
66
+ }
67
+ const routes = (0, import_utils.normalizedArray)(extras.routes) ?? [];
68
+ const excludes = (0, import_utils.normalizedArray)(extras.excludes) ?? [];
69
+ if (!global && !routes.length) {
70
+ throw new import_errors.AuthzError(`InternalError: Missing parameter 'global' or 'routes' in configuration.`);
71
+ }
72
+ if (store.globalInited) {
73
+ throw new import_errors.AuthzError(`InternalError: Cannot initialize mutiple global modules. Only one global module is allowed.`);
74
+ }
75
+ if (global) {
76
+ store.globalInited += 1;
77
+ }
78
+ return (0, import_utils.mergeDynamicModuleConfigs)(definition, {
79
+ global,
80
+ providers: [
81
+ {
82
+ provide: import_constants.ROUTES_OPTIONS,
83
+ useValue: {
84
+ global,
85
+ excludes,
86
+ routes
87
+ }
88
+ }
89
+ ],
90
+ exports: []
91
+ });
92
+ }).build();
93
+ const createJwtAuthzModule = /* @__PURE__ */ __name((authzProvider) => {
94
+ var _a;
95
+ const id = `${import_constants.PREFIX}${(0, import_uid.uid)()}`;
96
+ const JWT_STRATEGY = `${id}_JWT_STRATEGY`;
97
+ const JWT_REFRESH_STRATEGY = `${id}_REFRESH_STRATEGY`;
98
+ const AUTHZ_PROVIDER = `${id}_AUTHZ_PROVIDER`;
99
+ const ALS_PROVIDER = `${id}_ALS_PROVIDER`;
100
+ const JWT_AUTHZ_OPTIONS = `${id}_JWT_AUTHZ_OPTIONS`;
101
+ const JWT_META_KEY = `${id}_JWT_META_KEY`;
102
+ const JWT_REFRESH_META_KEY = `${id}_REFRESH_META_KEY`;
103
+ const JwtAuthzService = (0, import_jwt_authz3.createJwtAuthzService)([
104
+ AUTHZ_PROVIDER,
105
+ JWT_AUTHZ_OPTIONS,
106
+ ALS_PROVIDER
107
+ ]);
108
+ const JwtAuthzAlsMiddleware = (0, import_jwt_authz_als.createJwtAuthzAlsMiddleware)([
109
+ ALS_PROVIDER,
110
+ JWT_AUTHZ_OPTIONS
111
+ ]);
112
+ const als = new import_node_async_hooks.AsyncLocalStorage();
113
+ const JwtStrategy = (0, import_jwt_authz4.createJwtStrategy)([
114
+ JWT_STRATEGY,
115
+ AUTHZ_PROVIDER,
116
+ ALS_PROVIDER
117
+ ]);
118
+ const RefreshStrategy = (0, import_jwt_authz4.createRefreshStrategy)([
119
+ JWT_REFRESH_STRATEGY,
120
+ AUTHZ_PROVIDER,
121
+ ALS_PROVIDER
122
+ ]);
123
+ let isStrategyInited = false;
124
+ const RefreshAuthzGuard = (0, import_jwt_authz.createJwtRefreshAuthzGuard)([
125
+ JWT_REFRESH_STRATEGY,
126
+ JWT_AUTHZ_OPTIONS
127
+ ]);
128
+ const JwtAuthzGuard = (0, import_jwt_authz.createJwtAuthzGuard)([
129
+ JWT_STRATEGY,
130
+ AUTHZ_PROVIDER,
131
+ JWT_AUTHZ_OPTIONS,
132
+ ALS_PROVIDER,
133
+ JWT_META_KEY,
134
+ JWT_REFRESH_META_KEY
135
+ ]);
136
+ const Verify = (0, import_utils.createAuthzDecoratorFactory)(JWT_META_KEY);
137
+ const NoVerify = /* @__PURE__ */ __name(() => {
138
+ return (0, import_common.SetMetadata)(JWT_META_KEY, {
139
+ options: {
140
+ public: true,
141
+ override: true
142
+ }
143
+ });
144
+ }, "NoVerify");
145
+ const Refresh = /* @__PURE__ */ __name(() => {
146
+ return (0, import_common.applyDecorators)(JwtAuthzGuard.NoVerify(), (0, import_common.SetMetadata)(JWT_REFRESH_META_KEY, true), (0, import_common.UseGuards)(RefreshAuthzGuard));
147
+ }, "Refresh");
148
+ const Apply = /* @__PURE__ */ __name((...rest) => {
149
+ return (0, import_common.applyDecorators)(JwtAuthzGuard.Verify(...rest), (0, import_common.UseGuards)(JwtAuthzGuard));
150
+ }, "Apply");
151
+ JwtAuthzGuard.Verify = Verify;
152
+ JwtAuthzGuard.NoVerify = NoVerify;
153
+ JwtAuthzGuard.Refresh = Refresh;
154
+ JwtAuthzGuard.Apply = Apply;
155
+ const getCommonConfigs = /* @__PURE__ */ __name(() => {
156
+ const configs = {
157
+ providers: [
158
+ {
159
+ provide: AUTHZ_PROVIDER,
160
+ useClass: authzProvider
161
+ },
162
+ {
163
+ provide: ALS_PROVIDER,
164
+ useValue: als
165
+ },
166
+ ...!isStrategyInited ? [
167
+ JwtStrategy,
168
+ RefreshStrategy
169
+ ] : [],
170
+ JwtAuthzService
171
+ ],
172
+ exports: [
173
+ AUTHZ_PROVIDER,
174
+ ALS_PROVIDER,
175
+ JWT_AUTHZ_OPTIONS,
176
+ JwtAuthzService
177
+ ]
178
+ };
179
+ isStrategyInited = true;
180
+ return configs;
181
+ }, "getCommonConfigs");
182
+ let JwtAuthzModule = (_a = class extends ConfigurableModuleClass {
183
+ constructor(routesOpt) {
184
+ super();
185
+ __publicField(this, "routesOpt");
186
+ this.routesOpt = routesOpt;
187
+ }
188
+ static register(options) {
189
+ const jwtAuthzOptions = (0, import_jwt_authz2.normalizedJwtAuthzModuleOptions)(options);
190
+ return (0, import_utils.mergeDynamicModuleConfigs)(super.register({
191
+ ...options,
192
+ authzProvider
193
+ }), getCommonConfigs(), {
194
+ providers: [
195
+ {
196
+ provide: JWT_AUTHZ_OPTIONS,
197
+ useValue: jwtAuthzOptions
198
+ }
199
+ ]
200
+ });
201
+ }
202
+ static registerAsync(options) {
203
+ return (0, import_utils.mergeDynamicModuleConfigs)(super.registerAsync({
204
+ ...options,
205
+ authzProvider
206
+ }), getCommonConfigs(), {
207
+ providers: [
208
+ {
209
+ provide: JWT_AUTHZ_OPTIONS,
210
+ useFactory: /* @__PURE__ */ __name((moduleOptions) => {
211
+ const jwtAuthzOptions = (0, import_jwt_authz2.normalizedJwtAuthzModuleOptions)(moduleOptions);
212
+ return jwtAuthzOptions;
213
+ }, "useFactory"),
214
+ inject: [
215
+ MODULE_OPTIONS_TOKEN
216
+ ]
217
+ }
218
+ ]
219
+ });
220
+ }
221
+ configure(consumer) {
222
+ consumer.apply(JwtAuthzAlsMiddleware).exclude(...this.routesOpt.excludes).forRoutes(...this.routesOpt.global ? [
223
+ "*"
224
+ ] : this.routesOpt.routes);
225
+ }
226
+ }, __name(_a, "JwtAuthzModule"), _a);
227
+ JwtAuthzModule = _ts_decorate([
228
+ (0, import_common.Module)({}),
229
+ _ts_param(0, (0, import_common.Inject)(import_constants.ROUTES_OPTIONS)),
230
+ _ts_metadata("design:type", Function),
231
+ _ts_metadata("design:paramtypes", [
232
+ typeof RoutesOptions === "undefined" ? Object : RoutesOptions
233
+ ])
234
+ ], JwtAuthzModule);
235
+ return {
236
+ AuthzModule: JwtAuthzModule,
237
+ AuthzGuard: JwtAuthzGuard,
238
+ AuthzService: JwtAuthzService
239
+ };
240
+ }, "createJwtAuthzModule");
241
+ // Annotate the CommonJS export names for ESM import in node:
242
+ 0 && (module.exports = {
243
+ createJwtAuthzModule
244
+ });
@@ -0,0 +1,33 @@
1
+ import * as _nestjs_common from '@nestjs/common';
2
+ import { AuthzProviderClass } from '../authz.provider.js';
3
+ import { CookieOptionsWithSecret } from '../utils/types.js';
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
+ import { JwtAlsType } from './jwt-authz-als.middleware.js';
6
+ import { JwtAuthzOptions } from './jwt-authz.interface.js';
7
+ import '@nestjs/common/interfaces';
8
+ import 'express';
9
+ import '../constants.js';
10
+ import 'crypto';
11
+ import 'jsonwebtoken';
12
+ import './extract-jwt.js';
13
+ import 'cookie';
14
+
15
+ declare const createJwtAuthzService: <P = unknown, U = unknown>([AUTHZ_PROVIDER, JWT_AUTHZ_OPTIONS, ALS_PROVIDER]: [any, any, any]) => _nestjs_common.Type<Omit<{
16
+ readonly authzProvider: AuthzProviderClass<P, U>;
17
+ readonly jwtAuthzOptions: JwtAuthzOptions;
18
+ readonly als: AsyncLocalStorage<JwtAlsType<U>>;
19
+ logIn(user: U): Promise<{
20
+ token: string;
21
+ refresh: string;
22
+ } | {
23
+ token: string;
24
+ refresh?: undefined;
25
+ }>;
26
+ refresh(user?: U): Promise<{
27
+ token: string;
28
+ } | undefined>;
29
+ setCookie(name: string, value: string, options?: CookieOptionsWithSecret | undefined): void;
30
+ getUser(): U | undefined;
31
+ }, "als" | "jwtAuthzOptions" | "authzProvider">>;
32
+
33
+ export { createJwtAuthzService };
@@ -0,0 +1,144 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
31
+ var jwt_authz_service_exports = {};
32
+ __export(jwt_authz_service_exports, {
33
+ createJwtAuthzService: () => createJwtAuthzService
34
+ });
35
+ module.exports = __toCommonJS(jwt_authz_service_exports);
36
+ var import_node_async_hooks = require("node:async_hooks");
37
+ var import_common = require("@nestjs/common");
38
+ var import_jsonwebtoken = __toESM(require("jsonwebtoken"));
39
+ var import_authz = require("../authz.provider");
40
+ var import_constants = require("../constants");
41
+ var import_errors = require("../errors");
42
+ var import_utils = require("../utils");
43
+ function _ts_decorate(decorators, target, key, desc) {
44
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
45
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
46
+ 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;
47
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
48
+ }
49
+ __name(_ts_decorate, "_ts_decorate");
50
+ function _ts_metadata(k, v) {
51
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
52
+ }
53
+ __name(_ts_metadata, "_ts_metadata");
54
+ function _ts_param(paramIndex, decorator) {
55
+ return function(target, key) {
56
+ decorator(target, key, paramIndex);
57
+ };
58
+ }
59
+ __name(_ts_param, "_ts_param");
60
+ const createJwtAuthzService = /* @__PURE__ */ __name(([AUTHZ_PROVIDER, JWT_AUTHZ_OPTIONS, ALS_PROVIDER]) => {
61
+ var _a;
62
+ let JwtAuthzService = (_a = class {
63
+ constructor(authzProvider, jwtAuthzOptions, als) {
64
+ __publicField(this, "authzProvider");
65
+ __publicField(this, "jwtAuthzOptions");
66
+ __publicField(this, "als");
67
+ this.authzProvider = authzProvider;
68
+ this.jwtAuthzOptions = jwtAuthzOptions;
69
+ this.als = als;
70
+ if (typeof this.authzProvider.createPayload !== "function") {
71
+ throw new import_errors.AuthzError(`InternalError: Method 'createPayload' from abstract class 'AuthzProvider' must be implemented.`);
72
+ }
73
+ if (!jwtAuthzOptions.jwt?.sign) {
74
+ throw new import_errors.AuthzError(`InternalError: Missing JWT sign options.`);
75
+ }
76
+ if (this.jwtAuthzOptions.refresh && !this.jwtAuthzOptions.refresh.sign) {
77
+ throw new import_errors.AuthzError(`InternalError: Missing Refresh sign options.`);
78
+ }
79
+ }
80
+ async logIn(user) {
81
+ const payload = await this.authzProvider.createPayload(user);
82
+ const token = import_jsonwebtoken.default.sign(payload, this.jwtAuthzOptions.jwt.secretOrPrivateKey, this.jwtAuthzOptions.jwt.sign);
83
+ if (this.jwtAuthzOptions.refresh) {
84
+ const refresh = import_jsonwebtoken.default.sign({
85
+ data: (0, import_utils.encodeMsgpackrString)(payload)
86
+ }, this.jwtAuthzOptions.refresh.secretOrPrivateKey, this.jwtAuthzOptions.refresh.sign);
87
+ return {
88
+ token,
89
+ refresh
90
+ };
91
+ }
92
+ return {
93
+ token
94
+ };
95
+ }
96
+ async refresh(user) {
97
+ if (!this.jwtAuthzOptions.refresh) {
98
+ console.warn(`'refresh' method can only be called when configured in module options.`);
99
+ return void 0;
100
+ }
101
+ let userParams = user;
102
+ if (!user) {
103
+ const store = (0, import_utils.getAlsStore)(this.als);
104
+ if (store.jwtVerifiedBy !== import_constants.JwtValidationType.REFRESH) {
105
+ throw new import_errors.AuthzError(`InvocationError: Calling 'refresh' method without user parameter can only be called under @Refresh().`);
106
+ }
107
+ userParams = store.user;
108
+ }
109
+ if (!userParams) {
110
+ throw new import_errors.AuthzError(`ParameterError: User data is undefined.`);
111
+ }
112
+ const payload = await this.authzProvider.createPayload(userParams);
113
+ const token = import_jsonwebtoken.default.sign(payload, this.jwtAuthzOptions.jwt.secretOrPrivateKey, this.jwtAuthzOptions.jwt.sign);
114
+ return {
115
+ token
116
+ };
117
+ }
118
+ setCookie(...rest) {
119
+ const store = (0, import_utils.getAlsStore)(this.als);
120
+ store.setCookie(...rest);
121
+ }
122
+ getUser() {
123
+ const store = (0, import_utils.getAlsStore)(this.als);
124
+ const user = store.user;
125
+ return user;
126
+ }
127
+ }, __name(_a, "JwtAuthzService"), _a);
128
+ JwtAuthzService = _ts_decorate([
129
+ _ts_param(0, (0, import_common.Inject)(AUTHZ_PROVIDER)),
130
+ _ts_param(1, (0, import_common.Inject)(JWT_AUTHZ_OPTIONS)),
131
+ _ts_param(2, (0, import_common.Inject)(ALS_PROVIDER)),
132
+ _ts_metadata("design:type", Function),
133
+ _ts_metadata("design:paramtypes", [
134
+ typeof import_authz.AuthzProviderClass === "undefined" ? Object : import_authz.AuthzProviderClass,
135
+ typeof JwtAuthzOptions === "undefined" ? Object : JwtAuthzOptions,
136
+ typeof import_node_async_hooks.AsyncLocalStorage === "undefined" ? Object : import_node_async_hooks.AsyncLocalStorage
137
+ ])
138
+ ], JwtAuthzService);
139
+ return (0, import_common.mixin)(JwtAuthzService);
140
+ }, "createJwtAuthzService");
141
+ // Annotate the CommonJS export names for ESM import in node:
142
+ 0 && (module.exports = {
143
+ createJwtAuthzService
144
+ });
@@ -0,0 +1,40 @@
1
+ import * as _nestjs_common from '@nestjs/common';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { Request } from 'express';
4
+ import { AuthzProviderClass } from '../authz.provider.js';
5
+ import { JwtAlsType } from './jwt-authz-als.middleware.js';
6
+ import '../constants.js';
7
+ import '../utils/types.js';
8
+ import '@nestjs/common/interfaces';
9
+ import './jwt-authz.interface.js';
10
+ import 'crypto';
11
+ import 'jsonwebtoken';
12
+ import './extract-jwt.js';
13
+ import 'cookie';
14
+
15
+ declare const createJwtStrategy: ([JWT_STRATEGY, AUTHZ_PROVIDER, ALS_PROVIDER]: [string, any, any]) => _nestjs_common.Type<Omit<{
16
+ readonly authzProvider: AuthzProviderClass<unknown, unknown>;
17
+ readonly als: AsyncLocalStorage<JwtAlsType<unknown>>;
18
+ validate(req: Request): Promise<{}>;
19
+ authenticate(req: Request, options?: any): any;
20
+ success(user: any, info?: any): void;
21
+ fail(challenge: any, status: number): void;
22
+ fail(status: number): void;
23
+ redirect(url: string, status?: number): void;
24
+ pass(): void;
25
+ error(err: Error): void;
26
+ }, "als" | "authzProvider">>;
27
+ declare const createRefreshStrategy: ([JWT_REFRESH_STRATEGY, AUTHZ_PROVIDER, ALS_PROVIDER]: [string, any, any]) => _nestjs_common.Type<Omit<{
28
+ readonly authzProvider: AuthzProviderClass<unknown, unknown>;
29
+ readonly als: AsyncLocalStorage<JwtAlsType<unknown>>;
30
+ validate(req: Request): Promise<{}>;
31
+ authenticate(req: Request, options?: any): any;
32
+ success(user: any, info?: any): void;
33
+ fail(challenge: any, status: number): void;
34
+ fail(status: number): void;
35
+ redirect(url: string, status?: number): void;
36
+ pass(): void;
37
+ error(err: Error): void;
38
+ }, "als" | "authzProvider">>;
39
+
40
+ export { createJwtStrategy, createRefreshStrategy };
@@ -0,0 +1,194 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
31
+ var jwt_authz_strategy_exports = {};
32
+ __export(jwt_authz_strategy_exports, {
33
+ createJwtStrategy: () => createJwtStrategy,
34
+ createRefreshStrategy: () => createRefreshStrategy
35
+ });
36
+ module.exports = __toCommonJS(jwt_authz_strategy_exports);
37
+ var import_node_async_hooks = require("node:async_hooks");
38
+ var import_common = require("@nestjs/common");
39
+ var import_passport = require("@nestjs/passport");
40
+ var import_jsonwebtoken = __toESM(require("jsonwebtoken"));
41
+ var import_passport_custom = require("passport-custom");
42
+ var import_authz = require("../authz.provider");
43
+ var import_constants = require("../constants");
44
+ var import_errors = require("../errors");
45
+ var import_utils = require("../utils");
46
+ var import_extract_jwt = require("./extract-jwt");
47
+ function _ts_decorate(decorators, target, key, desc) {
48
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
49
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
50
+ 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;
51
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
52
+ }
53
+ __name(_ts_decorate, "_ts_decorate");
54
+ function _ts_metadata(k, v) {
55
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
56
+ }
57
+ __name(_ts_metadata, "_ts_metadata");
58
+ function _ts_param(paramIndex, decorator) {
59
+ return function(target, key) {
60
+ decorator(target, key, paramIndex);
61
+ };
62
+ }
63
+ __name(_ts_param, "_ts_param");
64
+ const createJwtStrategy = /* @__PURE__ */ __name(([JWT_STRATEGY, AUTHZ_PROVIDER, ALS_PROVIDER]) => {
65
+ var _a;
66
+ let JwtStrategy = (_a = class extends (0, import_passport.PassportStrategy)(import_passport_custom.Strategy, JWT_STRATEGY) {
67
+ constructor(authzProvider, als) {
68
+ super();
69
+ __publicField(this, "authzProvider");
70
+ __publicField(this, "als");
71
+ this.authzProvider = authzProvider, this.als = als;
72
+ if (typeof this.authzProvider.authenticate !== "function") {
73
+ throw new import_errors.AuthzError(`InternalError: Method 'authenticate' from abstract class 'AuthzProvider' must be implemented.`);
74
+ }
75
+ }
76
+ async validate(req) {
77
+ const store = (0, import_utils.getAlsStore)(this.als);
78
+ const authOptions = store.authOptions;
79
+ if (!authOptions.jwt.verify) {
80
+ return [
81
+ null,
82
+ new import_errors.AuthzError(`InternalError: Refresh verify options must be implemented.`)
83
+ ];
84
+ }
85
+ const extractor = import_extract_jwt.ExtractJwt.fromExtractors(authOptions.jwt.jwtFromRequest);
86
+ req[import_constants.PASSPORT_PROPERTY] = authOptions.passportProperty;
87
+ const token = extractor(req);
88
+ if (!token) {
89
+ return [
90
+ null,
91
+ new import_errors.AuthzAnonymousError("AnonymousError: Cannnot find token.")
92
+ ];
93
+ }
94
+ let user = void 0;
95
+ try {
96
+ const payload = import_jsonwebtoken.default.verify(token, authOptions.jwt.secretOrPublicKey, authOptions.jwt.verify);
97
+ user = await this.authzProvider.authenticate(payload);
98
+ } catch (error) {
99
+ return [
100
+ null,
101
+ error instanceof Error ? new import_errors.AuthzVerificationError(`${error.name}: ${error.message}`, error) : new import_errors.AuthzVerificationError(`${error}`)
102
+ ];
103
+ }
104
+ store.user = user;
105
+ store.jwtVerifiedBy = import_constants.JwtValidationType.JWT;
106
+ if (!user) {
107
+ return [
108
+ null,
109
+ new import_errors.AuthzAnonymousError("AnonymousError: Cannnot find user.")
110
+ ];
111
+ }
112
+ return user;
113
+ }
114
+ }, __name(_a, "JwtStrategy"), _a);
115
+ JwtStrategy = _ts_decorate([
116
+ _ts_param(0, (0, import_common.Inject)(AUTHZ_PROVIDER)),
117
+ _ts_param(1, (0, import_common.Inject)(ALS_PROVIDER)),
118
+ _ts_metadata("design:type", Function),
119
+ _ts_metadata("design:paramtypes", [
120
+ typeof import_authz.AuthzProviderClass === "undefined" ? Object : import_authz.AuthzProviderClass,
121
+ typeof import_node_async_hooks.AsyncLocalStorage === "undefined" ? Object : import_node_async_hooks.AsyncLocalStorage
122
+ ])
123
+ ], JwtStrategy);
124
+ return (0, import_common.mixin)(JwtStrategy);
125
+ }, "createJwtStrategy");
126
+ const createRefreshStrategy = /* @__PURE__ */ __name(([JWT_REFRESH_STRATEGY, AUTHZ_PROVIDER, ALS_PROVIDER]) => {
127
+ var _a;
128
+ let RefreshStrategy = (_a = class extends (0, import_passport.PassportStrategy)(import_passport_custom.Strategy, JWT_REFRESH_STRATEGY) {
129
+ constructor(authzProvider, als) {
130
+ super();
131
+ __publicField(this, "authzProvider");
132
+ __publicField(this, "als");
133
+ this.authzProvider = authzProvider, this.als = als;
134
+ if (typeof this.authzProvider.authenticate !== "function") {
135
+ throw new import_errors.AuthzError(`InternalError: Method 'authenticate' from abstract class 'AuthzProvider' must be implemented.`);
136
+ }
137
+ }
138
+ async validate(req) {
139
+ const store = (0, import_utils.getAlsStore)(this.als);
140
+ const authOptions = store.authOptions;
141
+ if (!authOptions.refresh.verify) {
142
+ return [
143
+ null,
144
+ new import_errors.AuthzError(`InternalError: Refresh verify options must be implemented.`)
145
+ ];
146
+ }
147
+ const extractor = import_extract_jwt.ExtractJwt.fromExtractors(authOptions.refresh.jwtFromRequest);
148
+ req[import_constants.PASSPORT_PROPERTY] = authOptions.passportProperty;
149
+ const token = extractor(req);
150
+ if (!token) {
151
+ return [
152
+ null,
153
+ new import_errors.AuthzAnonymousError("AnonymousError: Cannnot find token.")
154
+ ];
155
+ }
156
+ let user = void 0;
157
+ try {
158
+ const payload = import_jsonwebtoken.default.verify(token, authOptions.refresh.secretOrPublicKey, authOptions.refresh.verify);
159
+ const decodePayload = (0, import_utils.decodeMsgpackrString)(payload.data);
160
+ user = await this.authzProvider.authenticate(decodePayload);
161
+ } catch (error) {
162
+ return [
163
+ null,
164
+ error instanceof Error ? new import_errors.AuthzVerificationError(`${error.name}: ${error.message}`, error) : new import_errors.AuthzVerificationError(`${error}`)
165
+ ];
166
+ }
167
+ store.user = user;
168
+ store.jwtVerifiedBy = import_constants.JwtValidationType.REFRESH;
169
+ if (!user) {
170
+ return [
171
+ null,
172
+ new import_errors.AuthzAnonymousError("AnonymousError: Cannnot find user.")
173
+ ];
174
+ }
175
+ return user;
176
+ }
177
+ }, __name(_a, "RefreshStrategy"), _a);
178
+ RefreshStrategy = _ts_decorate([
179
+ (0, import_common.Injectable)(),
180
+ _ts_param(0, (0, import_common.Inject)(AUTHZ_PROVIDER)),
181
+ _ts_param(1, (0, import_common.Inject)(ALS_PROVIDER)),
182
+ _ts_metadata("design:type", Function),
183
+ _ts_metadata("design:paramtypes", [
184
+ typeof import_authz.AuthzProviderClass === "undefined" ? Object : import_authz.AuthzProviderClass,
185
+ typeof import_node_async_hooks.AsyncLocalStorage === "undefined" ? Object : import_node_async_hooks.AsyncLocalStorage
186
+ ])
187
+ ], RefreshStrategy);
188
+ return (0, import_common.mixin)(RefreshStrategy);
189
+ }, "createRefreshStrategy");
190
+ // Annotate the CommonJS export names for ESM import in node:
191
+ 0 && (module.exports = {
192
+ createJwtStrategy,
193
+ createRefreshStrategy
194
+ });
@@ -0,0 +1,12 @@
1
+ export { cereateSessionAuthzModule } from './session-authz.module.js';
2
+ import '@nestjs/core';
3
+ import '../authz.provider.js';
4
+ import '../utils/types.js';
5
+ import '@nestjs/common';
6
+ import '@nestjs/common/interfaces';
7
+ import 'express';
8
+ import 'node:async_hooks';
9
+ import 'express-session';
10
+ import '../errors.js';
11
+ import './session-authz-als.middleware.js';
12
+ import './session-authz.interface.js';