fiberx-backend-toolkit 0.0.44 → 0.0.46

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.
@@ -0,0 +1,23 @@
1
+ import { Model } from "sequelize";
2
+ import { Request, Response, NextFunction, RequestHandler } from "express";
3
+ import { AuthenticatorOptions, DefaultRequestInfo, DefaultAccessTokenPayload, DefaultRefreshTokenPayload } from "../types/middle_ware_type";
4
+ declare class AuthenicationMiddleWare {
5
+ private name;
6
+ private logger;
7
+ private readonly options;
8
+ constructor(options: AuthenticatorOptions);
9
+ /** Extract tokens + device info from request */
10
+ protected extractRequestInfo(req: Request): Promise<DefaultRequestInfo | null>;
11
+ protected validateAccessToken(access_token: string, request_info?: DefaultRequestInfo): Promise<DefaultAccessTokenPayload | null>;
12
+ protected validateRefreshToken(refresh_token: string, request_info?: DefaultRequestInfo): Promise<DefaultRefreshTokenPayload | null>;
13
+ protected LoadActor(actor_type: string, actor_id: number | string, request_info?: DefaultRequestInfo): Promise<Model | null>;
14
+ protected loadMemberSession(member_id: number | string, session_id: number | string, request_info?: DefaultRequestInfo, is_2fa_validated?: boolean): Promise<Model | null>;
15
+ protected loadMemberLoginChallenge(member_id: number | string, challenge_id: number | string, request_info?: DefaultRequestInfo, is_2fa_validated?: boolean): Promise<Model | null>;
16
+ protected getActorPermissions(actor_id: number | string, role_ids: (number | string)[]): Promise<string[]>;
17
+ protected validateHasPermission(request_info: DefaultRequestInfo): Promise<boolean>;
18
+ setPermissionName(permission_name: string): RequestHandler;
19
+ requireNoAuth(req: Request, res: Response, next: NextFunction): Promise<void | Response>;
20
+ requirePartialAuth(req: Request, res: Response, next: NextFunction): Promise<void | Response>;
21
+ requireFullAuth(req: Request, res: Response, next: NextFunction): Promise<void | Response>;
22
+ }
23
+ export default AuthenicationMiddleWare;
@@ -0,0 +1,188 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const main_1 = require("../utils/main");
13
+ class AuthenicationMiddleWare {
14
+ name = "authentication_middle_ware";
15
+ logger = new main_1.LoggerUtil(this.name);
16
+ options;
17
+ constructor(options) {
18
+ this.options = options;
19
+ main_1.SafeExecuteUtil.setNamedInstance(this.name, this);
20
+ }
21
+ /** Extract tokens + device info from request */
22
+ async extractRequestInfo(req) {
23
+ if (!this.options?.extractRequestInfoMethod) {
24
+ return null;
25
+ }
26
+ return this.options?.extractRequestInfoMethod(req);
27
+ }
28
+ // Method to validate access token payload
29
+ async validateAccessToken(access_token, request_info) {
30
+ if (!this.options?.validateAccessTokenMethod) {
31
+ return null;
32
+ }
33
+ return this.options?.validateAccessTokenMethod(access_token, request_info);
34
+ }
35
+ // Method to validate refresh token payload
36
+ async validateRefreshToken(refresh_token, request_info) {
37
+ if (!this.options?.validateRefreshTokenMethod) {
38
+ return null;
39
+ }
40
+ return this.options?.validateRefreshTokenMethod(refresh_token, request_info);
41
+ }
42
+ // Method to fetch member session history record
43
+ async LoadActor(actor_type, actor_id, request_info) {
44
+ if (!this.options?.loadActorMethod) {
45
+ return null;
46
+ }
47
+ return this.options?.loadActorMethod(actor_type, actor_id, request_info);
48
+ }
49
+ // Method to fetch member session history record
50
+ async loadMemberSession(member_id, session_id, request_info, is_2fa_validated = true) {
51
+ if (!this.options?.loadMemberSessionMethod) {
52
+ return null;
53
+ }
54
+ return this.options?.loadMemberSessionMethod(member_id, session_id, request_info, is_2fa_validated);
55
+ }
56
+ // Method to load member login challenge
57
+ async loadMemberLoginChallenge(member_id, challenge_id, request_info, is_2fa_validated = true) {
58
+ if (!this.options?.loadMemberLoginChallenegeMethod) {
59
+ return null;
60
+ }
61
+ return this.options?.loadMemberLoginChallenegeMethod(member_id, challenge_id, request_info, is_2fa_validated);
62
+ }
63
+ // Method to load member login challenge
64
+ async getActorPermissions(actor_id, role_ids) {
65
+ if (!this.options?.getActorPermissionsMethod) {
66
+ return [];
67
+ }
68
+ return this.options?.getActorPermissionsMethod(actor_id, role_ids);
69
+ }
70
+ // Method to validate refresh token payload
71
+ async validateHasPermission(request_info) {
72
+ if (!this.options?.validateActorHasPermissionMethod) {
73
+ return false;
74
+ }
75
+ return this.options?.validateActorHasPermissionMethod(request_info);
76
+ }
77
+ // -----------------------------------
78
+ // GENERIC MIDDLEWARES
79
+ // -----------------------------------
80
+ setPermissionName(permission_name) {
81
+ return async (req, res, next) => {
82
+ req.permission_name = permission_name;
83
+ this.logger.info(`[${this.name}] 🔐 Route permission set as ${permission_name} for request ${req.request_id}`);
84
+ const request_info = await this.extractRequestInfo(req) || req;
85
+ const has_permission = await this.validateHasPermission(request_info);
86
+ if (!has_permission) {
87
+ this.logger.info(`[${this.name}] ⛔ Permission denied for request ${req.request_id} with required permission ${permission_name}`);
88
+ return res.errResponse(403, "unauthorized_access_permission");
89
+ }
90
+ this.logger.success(`[${this.name}] ✅ Permission granted for request ${req.request_id} with required permission ${permission_name}`);
91
+ next();
92
+ };
93
+ }
94
+ async requireNoAuth(req, res, next) {
95
+ if (!this.options?.requireNoAuthMiddleWareMethod) {
96
+ return next();
97
+ }
98
+ return this.options?.requireNoAuthMiddleWareMethod(req, res, next);
99
+ }
100
+ ;
101
+ async requirePartialAuth(req, res, next) {
102
+ if (!this.options?.requirePartialAuthMiddleWareMethod) {
103
+ return next();
104
+ }
105
+ return this.options?.requirePartialAuthMiddleWareMethod(req, res, next);
106
+ }
107
+ ;
108
+ async requireFullAuth(req, res, next) {
109
+ if (!this.options?.requireFullAuthMiddleWareMethod) {
110
+ return next();
111
+ }
112
+ return this.options?.requireFullAuthMiddleWareMethod(req, res, next);
113
+ }
114
+ ;
115
+ }
116
+ __decorate([
117
+ main_1.SafeExecuteUtil.safeExecuteReturn("authentication_middle_ware", null),
118
+ __metadata("design:type", Function),
119
+ __metadata("design:paramtypes", [Object]),
120
+ __metadata("design:returntype", Promise)
121
+ ], AuthenicationMiddleWare.prototype, "extractRequestInfo", null);
122
+ __decorate([
123
+ main_1.SafeExecuteUtil.safeExecuteReturn("authentication_middle_ware", null),
124
+ __metadata("design:type", Function),
125
+ __metadata("design:paramtypes", [String, Object]),
126
+ __metadata("design:returntype", Promise)
127
+ ], AuthenicationMiddleWare.prototype, "validateAccessToken", null);
128
+ __decorate([
129
+ main_1.SafeExecuteUtil.safeExecuteReturn("authentication_middle_ware", null),
130
+ __metadata("design:type", Function),
131
+ __metadata("design:paramtypes", [String, Object]),
132
+ __metadata("design:returntype", Promise)
133
+ ], AuthenicationMiddleWare.prototype, "validateRefreshToken", null);
134
+ __decorate([
135
+ main_1.SafeExecuteUtil.safeExecuteReturn("authentication_middle_ware", null),
136
+ __metadata("design:type", Function),
137
+ __metadata("design:paramtypes", [String, Object, Object]),
138
+ __metadata("design:returntype", Promise)
139
+ ], AuthenicationMiddleWare.prototype, "LoadActor", null);
140
+ __decorate([
141
+ main_1.SafeExecuteUtil.safeExecuteReturn("authentication_middle_ware", null),
142
+ __metadata("design:type", Function),
143
+ __metadata("design:paramtypes", [Object, Object, Object, Boolean]),
144
+ __metadata("design:returntype", Promise)
145
+ ], AuthenicationMiddleWare.prototype, "loadMemberSession", null);
146
+ __decorate([
147
+ main_1.SafeExecuteUtil.safeExecuteReturn("authentication_middle_ware", null),
148
+ __metadata("design:type", Function),
149
+ __metadata("design:paramtypes", [Object, Object, Object, Boolean]),
150
+ __metadata("design:returntype", Promise)
151
+ ], AuthenicationMiddleWare.prototype, "loadMemberLoginChallenge", null);
152
+ __decorate([
153
+ main_1.SafeExecuteUtil.safeExecuteReturn("authentication_middle_ware", []),
154
+ __metadata("design:type", Function),
155
+ __metadata("design:paramtypes", [Object, Array]),
156
+ __metadata("design:returntype", Promise)
157
+ ], AuthenicationMiddleWare.prototype, "getActorPermissions", null);
158
+ __decorate([
159
+ main_1.SafeExecuteUtil.safeExecuteReturn("authentication_middle_ware", false),
160
+ __metadata("design:type", Function),
161
+ __metadata("design:paramtypes", [Object]),
162
+ __metadata("design:returntype", Promise)
163
+ ], AuthenicationMiddleWare.prototype, "validateHasPermission", null);
164
+ __decorate([
165
+ main_1.SafeExecuteUtil.safeExecuteThrow("authentication_middle_ware"),
166
+ __metadata("design:type", Function),
167
+ __metadata("design:paramtypes", [String]),
168
+ __metadata("design:returntype", Function)
169
+ ], AuthenicationMiddleWare.prototype, "setPermissionName", null);
170
+ __decorate([
171
+ main_1.SafeExecuteUtil.safeExecuteThrow("authentication_middle_ware"),
172
+ __metadata("design:type", Function),
173
+ __metadata("design:paramtypes", [Object, Object, Function]),
174
+ __metadata("design:returntype", Promise)
175
+ ], AuthenicationMiddleWare.prototype, "requireNoAuth", null);
176
+ __decorate([
177
+ main_1.SafeExecuteUtil.safeExecuteThrow("authentication_middle_ware"),
178
+ __metadata("design:type", Function),
179
+ __metadata("design:paramtypes", [Object, Object, Function]),
180
+ __metadata("design:returntype", Promise)
181
+ ], AuthenicationMiddleWare.prototype, "requirePartialAuth", null);
182
+ __decorate([
183
+ main_1.SafeExecuteUtil.safeExecuteThrow("authentication_middle_ware"),
184
+ __metadata("design:type", Function),
185
+ __metadata("design:paramtypes", [Object, Object, Function]),
186
+ __metadata("design:returntype", Promise)
187
+ ], AuthenicationMiddleWare.prototype, "requireFullAuth", null);
188
+ exports.default = AuthenicationMiddleWare;
@@ -5,4 +5,5 @@ import HTTPSEnforcementMiddleWare from "./https_enforcement_middle_ware";
5
5
  import SecureHeadersMiddleWare from "./secure_headers_middle_ware";
6
6
  import RequestLoggerMiddleWare from "./request_logger_middle_ware";
7
7
  import ResponseFormatterMiddleWare from "./response_formatter_middle_ware";
8
- export { CookieManagerMiddleWare, CorsMiddleWare, RateLimiterMiddleWare, HTTPSEnforcementMiddleWare, SecureHeadersMiddleWare, RequestLoggerMiddleWare, ResponseFormatterMiddleWare };
8
+ import AuthenicationMiddleWare from "./authentication_middle_ware";
9
+ export { CookieManagerMiddleWare, CorsMiddleWare, RateLimiterMiddleWare, HTTPSEnforcementMiddleWare, SecureHeadersMiddleWare, RequestLoggerMiddleWare, ResponseFormatterMiddleWare, AuthenicationMiddleWare };
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ResponseFormatterMiddleWare = exports.RequestLoggerMiddleWare = exports.SecureHeadersMiddleWare = exports.HTTPSEnforcementMiddleWare = exports.RateLimiterMiddleWare = exports.CorsMiddleWare = exports.CookieManagerMiddleWare = void 0;
6
+ exports.AuthenicationMiddleWare = exports.ResponseFormatterMiddleWare = exports.RequestLoggerMiddleWare = exports.SecureHeadersMiddleWare = exports.HTTPSEnforcementMiddleWare = exports.RateLimiterMiddleWare = exports.CorsMiddleWare = exports.CookieManagerMiddleWare = void 0;
7
7
  const cookie_manager_middle_ware_1 = __importDefault(require("./cookie_manager_middle_ware"));
8
8
  exports.CookieManagerMiddleWare = cookie_manager_middle_ware_1.default;
9
9
  const cors_middle_ware_1 = __importDefault(require("./cors_middle_ware"));
@@ -18,3 +18,5 @@ const request_logger_middle_ware_1 = __importDefault(require("./request_logger_m
18
18
  exports.RequestLoggerMiddleWare = request_logger_middle_ware_1.default;
19
19
  const response_formatter_middle_ware_1 = __importDefault(require("./response_formatter_middle_ware"));
20
20
  exports.ResponseFormatterMiddleWare = response_formatter_middle_ware_1.default;
21
+ const authentication_middle_ware_1 = __importDefault(require("./authentication_middle_ware"));
22
+ exports.AuthenicationMiddleWare = authentication_middle_ware_1.default;
@@ -1,3 +1,5 @@
1
+ import { Model } from "sequelize";
2
+ import { Request, Response, NextFunction } from "express";
1
3
  export type CorsOriginResolver = ((origin?: string) => boolean | Promise<boolean>) | (() => Promise<string[]>);
2
4
  export interface CorsOptions {
3
5
  origins?: string[];
@@ -53,3 +55,35 @@ export interface ResponseFormatterOptions {
53
55
  default_info_message?: string;
54
56
  default_not_found_message?: string;
55
57
  }
58
+ export interface DefaultRequestInfo {
59
+ access_token: string | null;
60
+ refresh_token: string | null;
61
+ device_id?: string;
62
+ origin_url: string;
63
+ request_id: string;
64
+ }
65
+ export interface DefaultAccessTokenPayload {
66
+ type: string;
67
+ member_id: number | string;
68
+ request_id: string;
69
+ device_id: string;
70
+ }
71
+ export interface DefaultRefreshTokenPayload {
72
+ type: "refresh";
73
+ member_id: number | string;
74
+ request_id: string;
75
+ device_id: string;
76
+ }
77
+ export interface AuthenticatorOptions<TRequestInfo extends DefaultRequestInfo = DefaultRequestInfo, TAccessPayload extends DefaultAccessTokenPayload = DefaultAccessTokenPayload, TRefreshPayload extends DefaultRefreshTokenPayload = DefaultRefreshTokenPayload, TSessionModel extends Model = Model, TLoginChallengeModel extends Model = Model, TActorModel extends Model = Model> {
78
+ extractRequestInfoMethod: (req: Request) => Promise<TRequestInfo | null>;
79
+ validateAccessTokenMethod: (access_token: string, requestInfo?: TRequestInfo) => Promise<TAccessPayload | null>;
80
+ validateRefreshTokenMethod: (refresh_token: string, requestInfo?: TRequestInfo) => Promise<TRefreshPayload | null>;
81
+ loadActorMethod(actor_type: string, actor_id: number | string, requestInfo?: TRequestInfo): Promise<TActorModel | null>;
82
+ loadMemberSessionMethod(member_id: number | string, session_id: number | string, request_info?: TRequestInfo, is_2fa_validated?: boolean): Promise<TSessionModel | null>;
83
+ loadMemberLoginChallenegeMethod(member_id: number | string, challenge_id: number | string, request_info?: TRequestInfo, is_2fa_validated?: boolean): Promise<TLoginChallengeModel | null>;
84
+ getActorPermissionsMethod(actor_id: number | string, role_ids: (number | string)[]): Promise<string[]>;
85
+ validateActorHasPermissionMethod(request_info: TRequestInfo): Promise<boolean>;
86
+ requireNoAuthMiddleWareMethod(req: Request, res: Response, next: NextFunction): Promise<void | Response>;
87
+ requirePartialAuthMiddleWareMethod(req: Request, res: Response, next: NextFunction): Promise<void | Response>;
88
+ requireFullAuthMiddleWareMethod(req: Request, res: Response, next: NextFunction): Promise<void | Response>;
89
+ }
@@ -1,3 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  ;
4
+ ;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fiberx-backend-toolkit",
3
- "version": "0.0.44",
3
+ "version": "0.0.46",
4
4
  "description": "A TypeScript backend toolkit providing shared domain logic, infrastructure helpers, and utilities for FiberX server-side applications and services.",
5
5
  "type": "commonjs",
6
6
  "main": "./dist/index.js",