@noony-serverless/core 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/build/core/containerPool.d.ts +44 -0
- package/build/core/containerPool.js +100 -0
- package/build/core/core.d.ts +68 -17
- package/build/core/core.js +63 -2
- package/build/core/errors.d.ts +43 -0
- package/build/core/errors.js +74 -1
- package/build/core/handler.d.ts +16 -37
- package/build/core/handler.js +42 -131
- package/build/core/index.d.ts +1 -0
- package/build/core/index.js +1 -0
- package/build/index.d.ts +1 -0
- package/build/index.js +4 -0
- package/build/middlewares/authenticationMiddleware.d.ts +8 -6
- package/build/middlewares/authenticationMiddleware.js +4 -2
- package/build/middlewares/bodyParserMiddleware.d.ts +7 -5
- package/build/middlewares/bodyParserMiddleware.js +4 -2
- package/build/middlewares/bodyValidationMiddleware.d.ts +10 -12
- package/build/middlewares/bodyValidationMiddleware.js +7 -9
- package/build/middlewares/errorHandlerMiddleware.d.ts +8 -3
- package/build/middlewares/errorHandlerMiddleware.js +7 -0
- package/build/middlewares/guards/RouteGuards.d.ts +2 -2
- package/build/middlewares/guards/RouteGuards.js +2 -2
- package/build/middlewares/guards/adapters/CustomTokenVerificationPortAdapter.d.ts +1 -1
- package/build/middlewares/guards/guards/FastAuthGuard.d.ts +5 -5
- package/build/middlewares/guards/guards/PermissionGuardFactory.d.ts +10 -2
- package/build/middlewares/guards/guards/PermissionGuardFactory.js +1 -1
- package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.d.ts +1 -1
- package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.js +1 -1
- package/build/middlewares/guards/resolvers/PermissionResolver.d.ts +1 -1
- package/build/middlewares/guards/resolvers/PlainPermissionResolver.d.ts +1 -1
- package/build/middlewares/guards/resolvers/WildcardPermissionResolver.d.ts +1 -1
- package/build/middlewares/guards/services/FastUserContextService.d.ts +34 -10
- package/build/middlewares/index.d.ts +1 -3
- package/build/middlewares/index.js +1 -6
- package/build/middlewares/queryParametersMiddleware.d.ts +7 -3
- package/build/middlewares/queryParametersMiddleware.js +4 -0
- package/build/middlewares/responseWrapperMiddleware.d.ts +10 -4
- package/build/middlewares/responseWrapperMiddleware.js +6 -0
- package/build/middlewares/validationMiddleware.d.ts +154 -0
- package/build/middlewares/validationMiddleware.js +185 -0
- package/package.json +1 -3
package/build/core/handler.js
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
3
|
exports.Handler = void 0;
|
|
7
|
-
// Container import
|
|
8
|
-
const typedi_1 = __importDefault(require("typedi"));
|
|
4
|
+
// Container import removed - now using containerPool for performance
|
|
9
5
|
const core_1 = require("./core");
|
|
6
|
+
const containerPool_1 = require("./containerPool");
|
|
10
7
|
/**
|
|
11
8
|
* The Handler class is responsible for managing and executing middleware functions
|
|
12
9
|
* and a main handler function in a sequential and controlled manner.
|
|
@@ -15,8 +12,6 @@ const core_1 = require("./core");
|
|
|
15
12
|
* process a request/response flow either before the main handler (via `before`),
|
|
16
13
|
* after the main handler (via `after`), or handle errors (via `onError`).
|
|
17
14
|
*
|
|
18
|
-
* @example
|
|
19
|
-
* ```typescript
|
|
20
15
|
* interface MessagePayload {
|
|
21
16
|
* action: string;
|
|
22
17
|
* data: Record<string, unknown>;
|
|
@@ -27,10 +22,10 @@ const core_1 = require("./core");
|
|
|
27
22
|
* .use(bodyParser())
|
|
28
23
|
* .handle(async (context) => {
|
|
29
24
|
* const { req } = context;
|
|
30
|
-
* // Handle the request
|
|
25
|
+
* // Handle the request
|
|
31
26
|
* });
|
|
32
|
-
* ```
|
|
33
27
|
* @template T Type for the input request data.
|
|
28
|
+
* @template U Type for the additional context or response data.
|
|
34
29
|
*/
|
|
35
30
|
class Handler {
|
|
36
31
|
baseMiddlewares = [];
|
|
@@ -45,9 +40,12 @@ class Handler {
|
|
|
45
40
|
return handler;
|
|
46
41
|
}
|
|
47
42
|
use(middleware) {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
43
|
+
const handler = new Handler();
|
|
44
|
+
handler.baseMiddlewares = [
|
|
45
|
+
...this.baseMiddlewares,
|
|
46
|
+
middleware,
|
|
47
|
+
];
|
|
48
|
+
return handler;
|
|
51
49
|
}
|
|
52
50
|
handle(handler) {
|
|
53
51
|
this.handler = handler;
|
|
@@ -65,17 +63,12 @@ class Handler {
|
|
|
65
63
|
this.errorMiddlewares = this.reversedMiddlewares.filter((m) => m.onError);
|
|
66
64
|
this.middlewaresPrecomputed = true;
|
|
67
65
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const req = this.adaptToNoonyRequest(nativeReq);
|
|
75
|
-
const res = this.adaptToNoonyResponse(nativeRes, nativeReq);
|
|
76
|
-
// Direct container creation - simpler and appropriate for serverless
|
|
77
|
-
const container = typedi_1.default.of();
|
|
78
|
-
const context = (0, core_1.createContext)(req, res, {
|
|
66
|
+
async execute(req, res) {
|
|
67
|
+
const genericReq = (0, core_1.adaptGCPRequest)(req);
|
|
68
|
+
const genericRes = (0, core_1.adaptGCPResponse)(res);
|
|
69
|
+
// Performance optimization: Use container pool instead of creating new containers
|
|
70
|
+
const container = containerPool_1.containerPool.acquire();
|
|
71
|
+
const context = (0, core_1.createContext)(genericReq, genericRes, {
|
|
79
72
|
container,
|
|
80
73
|
});
|
|
81
74
|
try {
|
|
@@ -90,7 +83,10 @@ class Handler {
|
|
|
90
83
|
// Execute error handlers using pre-computed array
|
|
91
84
|
await this.executeErrorMiddlewares(error, context);
|
|
92
85
|
}
|
|
93
|
-
|
|
86
|
+
finally {
|
|
87
|
+
// Always return container to pool for reuse
|
|
88
|
+
containerPool_1.containerPool.release(container);
|
|
89
|
+
}
|
|
94
90
|
}
|
|
95
91
|
/**
|
|
96
92
|
* Execute before middlewares with optimized batching for independent middlewares
|
|
@@ -125,115 +121,30 @@ class Handler {
|
|
|
125
121
|
}
|
|
126
122
|
}
|
|
127
123
|
/**
|
|
128
|
-
*
|
|
129
|
-
*/
|
|
130
|
-
adaptToNoonyRequest(nativeReq) {
|
|
131
|
-
const req = nativeReq;
|
|
132
|
-
// Universal property mapping that works with any HTTP framework
|
|
133
|
-
return {
|
|
134
|
-
method: req.method || req.httpMethod || core_1.HttpMethod.GET,
|
|
135
|
-
url: req.url || req.originalUrl || req.path || '/',
|
|
136
|
-
path: req.path || req.resource,
|
|
137
|
-
headers: req.headers || {},
|
|
138
|
-
query: req.query || req.queryStringParameters || {},
|
|
139
|
-
params: req.params || req.pathParameters || {},
|
|
140
|
-
body: req.body,
|
|
141
|
-
rawBody: req.rawBody || req.body,
|
|
142
|
-
parsedBody: req.parsedBody,
|
|
143
|
-
validatedBody: req.validatedBody,
|
|
144
|
-
ip: req.ip || req.requestContext?.identity?.sourceIp,
|
|
145
|
-
userAgent: (typeof req.headers?.['user-agent'] === 'string'
|
|
146
|
-
? req.headers['user-agent']
|
|
147
|
-
: Array.isArray(req.headers?.['user-agent'])
|
|
148
|
-
? req.headers['user-agent'][0]
|
|
149
|
-
: undefined) || req.get?.('user-agent'),
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
/**
|
|
153
|
-
* Universal response adapter - converts any framework's response to NoonyResponse
|
|
154
|
-
*/
|
|
155
|
-
adaptToNoonyResponse(nativeRes, nativeReq) {
|
|
156
|
-
const req = nativeReq;
|
|
157
|
-
// Detect AWS Lambda pattern (different from standard HTTP)
|
|
158
|
-
if (req?.requestContext && typeof nativeRes === 'function') {
|
|
159
|
-
return this.createAWSLambdaResponse(nativeRes);
|
|
160
|
-
}
|
|
161
|
-
// Standard HTTP response (GCP, Express, Fastify, etc.)
|
|
162
|
-
return this.createStandardHTTPResponse(nativeRes);
|
|
163
|
-
}
|
|
164
|
-
/**
|
|
165
|
-
* Create response adapter for AWS Lambda
|
|
166
|
-
*/
|
|
167
|
-
createAWSLambdaResponse(lambdaCallback) {
|
|
168
|
-
let statusCode = 200;
|
|
169
|
-
const headers = {};
|
|
170
|
-
let body;
|
|
171
|
-
return {
|
|
172
|
-
status: (code) => {
|
|
173
|
-
statusCode = code;
|
|
174
|
-
return this.createAWSLambdaResponse(lambdaCallback);
|
|
175
|
-
},
|
|
176
|
-
json: (data) => {
|
|
177
|
-
body = JSON.stringify(data);
|
|
178
|
-
headers['Content-Type'] = 'application/json';
|
|
179
|
-
lambdaCallback(null, { statusCode, headers, body });
|
|
180
|
-
},
|
|
181
|
-
send: (data) => {
|
|
182
|
-
body = data;
|
|
183
|
-
lambdaCallback(null, { statusCode, headers, body });
|
|
184
|
-
},
|
|
185
|
-
header: (name, value) => {
|
|
186
|
-
headers[name] = value;
|
|
187
|
-
return this.createAWSLambdaResponse(lambdaCallback);
|
|
188
|
-
},
|
|
189
|
-
headers: (newHeaders) => {
|
|
190
|
-
Object.assign(headers, newHeaders);
|
|
191
|
-
return this.createAWSLambdaResponse(lambdaCallback);
|
|
192
|
-
},
|
|
193
|
-
end: () => lambdaCallback(null, { statusCode, headers, body }),
|
|
194
|
-
statusCode,
|
|
195
|
-
headersSent: false,
|
|
196
|
-
};
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* Create response adapter for standard HTTP frameworks (GCP, Express, Fastify)
|
|
200
|
-
*/
|
|
201
|
-
createStandardHTTPResponse(nativeRes) {
|
|
202
|
-
const res = nativeRes;
|
|
203
|
-
return {
|
|
204
|
-
status: (code) => {
|
|
205
|
-
res.status(code);
|
|
206
|
-
return this.createStandardHTTPResponse(nativeRes);
|
|
207
|
-
},
|
|
208
|
-
json: (data) => res.json(data),
|
|
209
|
-
send: (data) => res.send(data),
|
|
210
|
-
header: (name, value) => {
|
|
211
|
-
res.header(name, value);
|
|
212
|
-
return this.createStandardHTTPResponse(nativeRes);
|
|
213
|
-
},
|
|
214
|
-
headers: (headers) => {
|
|
215
|
-
if (res.set) {
|
|
216
|
-
res.set(headers); // Express style
|
|
217
|
-
}
|
|
218
|
-
else {
|
|
219
|
-
Object.entries(headers).forEach(([k, v]) => res.header(k, v)); // GCP style
|
|
220
|
-
}
|
|
221
|
-
return this.createStandardHTTPResponse(nativeRes);
|
|
222
|
-
},
|
|
223
|
-
end: () => res.end(),
|
|
224
|
-
get statusCode() {
|
|
225
|
-
return res.statusCode;
|
|
226
|
-
},
|
|
227
|
-
get headersSent() {
|
|
228
|
-
return res.headersSent;
|
|
229
|
-
},
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
/**
|
|
233
|
-
* @deprecated Use execute() instead - automatically detects framework
|
|
124
|
+
* Framework-agnostic execute method that works with GenericRequest/GenericResponse
|
|
234
125
|
*/
|
|
235
126
|
async executeGeneric(req, res) {
|
|
236
|
-
|
|
127
|
+
// Performance optimization: Use container pool instead of creating new containers
|
|
128
|
+
const container = containerPool_1.containerPool.acquire();
|
|
129
|
+
const context = (0, core_1.createContext)(req, res, {
|
|
130
|
+
container,
|
|
131
|
+
});
|
|
132
|
+
try {
|
|
133
|
+
// Execute before middlewares with performance optimizations
|
|
134
|
+
await this.executeBeforeMiddlewares(context);
|
|
135
|
+
await this.handler(context);
|
|
136
|
+
// Execute after middlewares in reverse order using pre-computed array
|
|
137
|
+
await this.executeAfterMiddlewares(context);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
context.error = error;
|
|
141
|
+
// Execute error handlers using pre-computed array
|
|
142
|
+
await this.executeErrorMiddlewares(error, context);
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
// Always return container to pool for reuse
|
|
146
|
+
containerPool_1.containerPool.release(container);
|
|
147
|
+
}
|
|
237
148
|
}
|
|
238
149
|
}
|
|
239
150
|
exports.Handler = Handler;
|
package/build/core/index.d.ts
CHANGED
package/build/core/index.js
CHANGED
|
@@ -18,6 +18,7 @@ __exportStar(require("./core"), exports);
|
|
|
18
18
|
__exportStar(require("./errors"), exports);
|
|
19
19
|
__exportStar(require("./handler"), exports);
|
|
20
20
|
__exportStar(require("./logger"), exports);
|
|
21
|
+
__exportStar(require("./containerPool"), exports);
|
|
21
22
|
__exportStar(require("./performanceMonitor"), exports);
|
|
22
23
|
__exportStar(require("../middlewares"), exports);
|
|
23
24
|
//# sourceMappingURL=index.js.map
|
package/build/index.d.ts
CHANGED
package/build/index.js
CHANGED
|
@@ -14,6 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
// Core exports
|
|
17
18
|
__exportStar(require("./core"), exports);
|
|
19
|
+
// Middleware exports
|
|
18
20
|
__exportStar(require("./middlewares"), exports);
|
|
21
|
+
// Utility exports
|
|
22
|
+
__exportStar(require("./utils"), exports);
|
|
19
23
|
//# sourceMappingURL=index.js.map
|
|
@@ -209,7 +209,8 @@ export interface AuthenticationOptions {
|
|
|
209
209
|
* Class-based authentication middleware with comprehensive security features.
|
|
210
210
|
* Provides JWT validation, rate limiting, token blacklisting, and security logging.
|
|
211
211
|
*
|
|
212
|
-
* @template
|
|
212
|
+
* @template TUser - The type of user data returned by the token verification port
|
|
213
|
+
* @template TBody - The type of the request body payload (preserves type chain)
|
|
213
214
|
*
|
|
214
215
|
* @example
|
|
215
216
|
* Basic JWT authentication:
|
|
@@ -292,17 +293,18 @@ export interface AuthenticationOptions {
|
|
|
292
293
|
* });
|
|
293
294
|
* ```
|
|
294
295
|
*/
|
|
295
|
-
export declare class AuthenticationMiddleware<
|
|
296
|
+
export declare class AuthenticationMiddleware<TUser = unknown, TBody = unknown> implements BaseMiddleware<TBody, TUser> {
|
|
296
297
|
private tokenVerificationPort;
|
|
297
298
|
private options;
|
|
298
|
-
constructor(tokenVerificationPort: CustomTokenVerificationPort<
|
|
299
|
-
before(context: Context): Promise<void>;
|
|
299
|
+
constructor(tokenVerificationPort: CustomTokenVerificationPort<TUser>, options?: AuthenticationOptions);
|
|
300
|
+
before(context: Context<TBody, TUser>): Promise<void>;
|
|
300
301
|
}
|
|
301
302
|
/**
|
|
302
303
|
* Factory function that creates an authentication middleware with token verification.
|
|
303
304
|
* Provides a functional approach for authentication setup.
|
|
304
305
|
*
|
|
305
|
-
* @template
|
|
306
|
+
* @template TUser - The type of user data returned by the token verification port
|
|
307
|
+
* @template TBody - The type of the request body payload (preserves type chain)
|
|
306
308
|
* @param tokenVerificationPort - The token verification implementation
|
|
307
309
|
* @param options - Authentication configuration options
|
|
308
310
|
* @returns A BaseMiddleware object with authentication logic
|
|
@@ -427,5 +429,5 @@ export declare class AuthenticationMiddleware<T> implements BaseMiddleware {
|
|
|
427
429
|
* };
|
|
428
430
|
* ```
|
|
429
431
|
*/
|
|
430
|
-
export declare const verifyAuthTokenMiddleware: <
|
|
432
|
+
export declare const verifyAuthTokenMiddleware: <TUser = unknown, TBody = unknown>(tokenVerificationPort: CustomTokenVerificationPort<TUser>, options?: AuthenticationOptions) => BaseMiddleware<TBody, TUser>;
|
|
431
433
|
//# sourceMappingURL=authenticationMiddleware.d.ts.map
|
|
@@ -173,7 +173,8 @@ async function verifyToken(tokenVerificationPort, context, options = {}) {
|
|
|
173
173
|
* Class-based authentication middleware with comprehensive security features.
|
|
174
174
|
* Provides JWT validation, rate limiting, token blacklisting, and security logging.
|
|
175
175
|
*
|
|
176
|
-
* @template
|
|
176
|
+
* @template TUser - The type of user data returned by the token verification port
|
|
177
|
+
* @template TBody - The type of the request body payload (preserves type chain)
|
|
177
178
|
*
|
|
178
179
|
* @example
|
|
179
180
|
* Basic JWT authentication:
|
|
@@ -272,7 +273,8 @@ exports.AuthenticationMiddleware = AuthenticationMiddleware;
|
|
|
272
273
|
* Factory function that creates an authentication middleware with token verification.
|
|
273
274
|
* Provides a functional approach for authentication setup.
|
|
274
275
|
*
|
|
275
|
-
* @template
|
|
276
|
+
* @template TUser - The type of user data returned by the token verification port
|
|
277
|
+
* @template TBody - The type of the request body payload (preserves type chain)
|
|
276
278
|
* @param tokenVerificationPort - The token verification implementation
|
|
277
279
|
* @param options - Authentication configuration options
|
|
278
280
|
* @returns A BaseMiddleware object with authentication logic
|
|
@@ -8,7 +8,8 @@ import { BaseMiddleware, Context } from '../core';
|
|
|
8
8
|
* - Base64 decoding for Pub/Sub messages
|
|
9
9
|
* - Non-blocking parsing using setImmediate
|
|
10
10
|
*
|
|
11
|
-
* @template
|
|
11
|
+
* @template TBody - The expected type of the parsed body. Defaults to unknown if not specified.
|
|
12
|
+
* @template TUser - The type of the authenticated user (preserves type chain)
|
|
12
13
|
* @implements {BaseMiddleware}
|
|
13
14
|
*
|
|
14
15
|
* @example
|
|
@@ -63,10 +64,10 @@ import { BaseMiddleware, Context } from '../core';
|
|
|
63
64
|
* });
|
|
64
65
|
* ```
|
|
65
66
|
*/
|
|
66
|
-
export declare class BodyParserMiddleware<
|
|
67
|
+
export declare class BodyParserMiddleware<TBody = unknown, TUser = unknown> implements BaseMiddleware<TBody, TUser> {
|
|
67
68
|
private maxSize;
|
|
68
69
|
constructor(maxSize?: number);
|
|
69
|
-
before(context: Context): Promise<void>;
|
|
70
|
+
before(context: Context<TBody, TUser>): Promise<void>;
|
|
70
71
|
}
|
|
71
72
|
/**
|
|
72
73
|
* Enhanced middleware function for parsing the request body in specific HTTP methods.
|
|
@@ -76,7 +77,8 @@ export declare class BodyParserMiddleware<T = unknown> implements BaseMiddleware
|
|
|
76
77
|
* - Async parsing for large payloads
|
|
77
78
|
* - Size validation
|
|
78
79
|
*
|
|
79
|
-
* @template
|
|
80
|
+
* @template TBody - The expected type of the parsed request body.
|
|
81
|
+
* @template TUser - The type of the authenticated user (preserves type chain)
|
|
80
82
|
* @param maxSize - Maximum allowed body size in bytes (default: 1MB)
|
|
81
83
|
* @returns {BaseMiddleware} A middleware object containing a `before` hook.
|
|
82
84
|
*
|
|
@@ -126,5 +128,5 @@ export declare class BodyParserMiddleware<T = unknown> implements BaseMiddleware
|
|
|
126
128
|
* });
|
|
127
129
|
* ```
|
|
128
130
|
*/
|
|
129
|
-
export declare const bodyParser: <
|
|
131
|
+
export declare const bodyParser: <TBody = unknown, TUser = unknown>(maxSize?: number) => BaseMiddleware<TBody, TUser>;
|
|
130
132
|
//# sourceMappingURL=bodyParserMiddleware.d.ts.map
|
|
@@ -157,7 +157,8 @@ const parseBody = async (body) => {
|
|
|
157
157
|
* - Base64 decoding for Pub/Sub messages
|
|
158
158
|
* - Non-blocking parsing using setImmediate
|
|
159
159
|
*
|
|
160
|
-
* @template
|
|
160
|
+
* @template TBody - The expected type of the parsed body. Defaults to unknown if not specified.
|
|
161
|
+
* @template TUser - The type of the authenticated user (preserves type chain)
|
|
161
162
|
* @implements {BaseMiddleware}
|
|
162
163
|
*
|
|
163
164
|
* @example
|
|
@@ -241,7 +242,8 @@ exports.BodyParserMiddleware = BodyParserMiddleware;
|
|
|
241
242
|
* - Async parsing for large payloads
|
|
242
243
|
* - Size validation
|
|
243
244
|
*
|
|
244
|
-
* @template
|
|
245
|
+
* @template TBody - The expected type of the parsed request body.
|
|
246
|
+
* @template TUser - The type of the authenticated user (preserves type chain)
|
|
245
247
|
* @param maxSize - Maximum allowed body size in bytes (default: 1MB)
|
|
246
248
|
* @returns {BaseMiddleware} A middleware object containing a `before` hook.
|
|
247
249
|
*
|
|
@@ -23,21 +23,20 @@ import { z } from 'zod';
|
|
|
23
23
|
*
|
|
24
24
|
* type UserRequest = z.infer<typeof userSchema>;
|
|
25
25
|
*
|
|
26
|
-
* async function handleCreateUser(context: Context<UserRequest>) {
|
|
26
|
+
* async function handleCreateUser(context: Context<UserRequest, AuthenticatedUser>) {
|
|
27
27
|
* const user = context.req.validatedBody!; // Fully typed
|
|
28
|
-
* const authenticatedUser = context.user; // User type inferred from auth middleware
|
|
29
28
|
* return { success: true, user: { id: '123', ...user } };
|
|
30
29
|
* }
|
|
31
30
|
*
|
|
32
|
-
* const createUserHandler = new Handler<UserRequest>()
|
|
33
|
-
* .use(new BodyValidationMiddleware<UserRequest>(userSchema))
|
|
31
|
+
* const createUserHandler = new Handler<UserRequest, AuthenticatedUser>()
|
|
32
|
+
* .use(new BodyValidationMiddleware<UserRequest, AuthenticatedUser>(userSchema))
|
|
34
33
|
* .handle(handleCreateUser);
|
|
35
34
|
* ```
|
|
36
35
|
*/
|
|
37
|
-
export declare class BodyValidationMiddleware<T = unknown> implements BaseMiddleware<T> {
|
|
36
|
+
export declare class BodyValidationMiddleware<T = unknown, U = unknown> implements BaseMiddleware<T, U> {
|
|
38
37
|
private readonly schema;
|
|
39
38
|
constructor(schema: z.ZodSchema<T>);
|
|
40
|
-
before(context: Context<T>): Promise<void>;
|
|
39
|
+
before(context: Context<T, U>): Promise<void>;
|
|
41
40
|
}
|
|
42
41
|
/**
|
|
43
42
|
* Factory function that creates a body validation middleware with Zod schema validation.
|
|
@@ -60,19 +59,18 @@ export declare class BodyValidationMiddleware<T = unknown> implements BaseMiddle
|
|
|
60
59
|
*
|
|
61
60
|
* type LoginRequest = z.infer<typeof loginSchema>;
|
|
62
61
|
*
|
|
63
|
-
* async function handleLogin(context: Context<LoginRequest>) {
|
|
62
|
+
* async function handleLogin(context: Context<LoginRequest, AuthenticatedUser>) {
|
|
64
63
|
* const credentials = context.req.parsedBody as LoginRequest;
|
|
65
64
|
* const token = await authenticate(credentials.username, credentials.password);
|
|
66
|
-
* const authenticatedUser = context.user; // User type from auth middleware
|
|
67
65
|
* return { success: true, token };
|
|
68
66
|
* }
|
|
69
67
|
*
|
|
70
|
-
* const loginHandler = new Handler<LoginRequest>()
|
|
71
|
-
* .use(bodyValidatorMiddleware<LoginRequest>(loginSchema))
|
|
68
|
+
* const loginHandler = new Handler<LoginRequest, AuthenticatedUser>()
|
|
69
|
+
* .use(bodyValidatorMiddleware<LoginRequest, AuthenticatedUser>(loginSchema))
|
|
72
70
|
* .handle(handleLogin);
|
|
73
71
|
* ```
|
|
74
72
|
*/
|
|
75
|
-
export declare const bodyValidatorMiddleware: <T>(schema: z.ZodType<T>) => {
|
|
76
|
-
before: (context: Context<T>) => Promise<void>;
|
|
73
|
+
export declare const bodyValidatorMiddleware: <T, U = unknown>(schema: z.ZodType<T>) => {
|
|
74
|
+
before: (context: Context<T, U>) => Promise<void>;
|
|
77
75
|
};
|
|
78
76
|
//# sourceMappingURL=bodyValidationMiddleware.d.ts.map
|
|
@@ -36,14 +36,13 @@ const validateBody = async (schema, data) => {
|
|
|
36
36
|
*
|
|
37
37
|
* type UserRequest = z.infer<typeof userSchema>;
|
|
38
38
|
*
|
|
39
|
-
* async function handleCreateUser(context: Context<UserRequest>) {
|
|
39
|
+
* async function handleCreateUser(context: Context<UserRequest, AuthenticatedUser>) {
|
|
40
40
|
* const user = context.req.validatedBody!; // Fully typed
|
|
41
|
-
* const authenticatedUser = context.user; // User type inferred from auth middleware
|
|
42
41
|
* return { success: true, user: { id: '123', ...user } };
|
|
43
42
|
* }
|
|
44
43
|
*
|
|
45
|
-
* const createUserHandler = new Handler<UserRequest>()
|
|
46
|
-
* .use(new BodyValidationMiddleware<UserRequest>(userSchema))
|
|
44
|
+
* const createUserHandler = new Handler<UserRequest, AuthenticatedUser>()
|
|
45
|
+
* .use(new BodyValidationMiddleware<UserRequest, AuthenticatedUser>(userSchema))
|
|
47
46
|
* .handle(handleCreateUser);
|
|
48
47
|
* ```
|
|
49
48
|
*/
|
|
@@ -78,19 +77,18 @@ exports.BodyValidationMiddleware = BodyValidationMiddleware;
|
|
|
78
77
|
*
|
|
79
78
|
* type LoginRequest = z.infer<typeof loginSchema>;
|
|
80
79
|
*
|
|
81
|
-
* async function handleLogin(context: Context<LoginRequest>) {
|
|
80
|
+
* async function handleLogin(context: Context<LoginRequest, AuthenticatedUser>) {
|
|
82
81
|
* const credentials = context.req.parsedBody as LoginRequest;
|
|
83
82
|
* const token = await authenticate(credentials.username, credentials.password);
|
|
84
|
-
* const authenticatedUser = context.user; // User type from auth middleware
|
|
85
83
|
* return { success: true, token };
|
|
86
84
|
* }
|
|
87
85
|
*
|
|
88
|
-
* const loginHandler = new Handler<LoginRequest>()
|
|
89
|
-
* .use(bodyValidatorMiddleware<LoginRequest>(loginSchema))
|
|
86
|
+
* const loginHandler = new Handler<LoginRequest, AuthenticatedUser>()
|
|
87
|
+
* .use(bodyValidatorMiddleware<LoginRequest, AuthenticatedUser>(loginSchema))
|
|
90
88
|
* .handle(handleLogin);
|
|
91
89
|
* ```
|
|
92
90
|
*/
|
|
93
|
-
//
|
|
91
|
+
// Modified to fix type instantiation error
|
|
94
92
|
const bodyValidatorMiddleware = (schema) => ({
|
|
95
93
|
before: async (context) => {
|
|
96
94
|
context.req.parsedBody = await validateBody(schema, context.req.body);
|
|
@@ -4,6 +4,9 @@ import { BaseMiddleware, Context } from '../core';
|
|
|
4
4
|
* Implements the `BaseMiddleware` interface and provides an asynchronous
|
|
5
5
|
* `onError` method that delegates error handling to the `handleError` function.
|
|
6
6
|
*
|
|
7
|
+
* @template TBody - The type of the request body payload (preserves type chain)
|
|
8
|
+
* @template TUser - The type of the authenticated user (preserves type chain)
|
|
9
|
+
*
|
|
7
10
|
* @remarks
|
|
8
11
|
* This middleware should be registered to catch and process errors that occur
|
|
9
12
|
* during request handling.
|
|
@@ -50,12 +53,14 @@ import { BaseMiddleware, Context } from '../core';
|
|
|
50
53
|
* });
|
|
51
54
|
* ```
|
|
52
55
|
*/
|
|
53
|
-
export declare class ErrorHandlerMiddleware implements BaseMiddleware {
|
|
54
|
-
onError(error: Error, context: Context): Promise<void>;
|
|
56
|
+
export declare class ErrorHandlerMiddleware<TBody = unknown, TUser = unknown> implements BaseMiddleware<TBody, TUser> {
|
|
57
|
+
onError(error: Error, context: Context<TBody, TUser>): Promise<void>;
|
|
55
58
|
}
|
|
56
59
|
/**
|
|
57
60
|
* Creates an error handling middleware for processing errors in the application.
|
|
58
61
|
*
|
|
62
|
+
* @template TBody - The type of the request body payload (preserves type chain)
|
|
63
|
+
* @template TUser - The type of the authenticated user (preserves type chain)
|
|
59
64
|
* @returns {BaseMiddleware} An object implementing the `onError` method to handle errors.
|
|
60
65
|
*
|
|
61
66
|
* @remarks
|
|
@@ -96,5 +101,5 @@ export declare class ErrorHandlerMiddleware implements BaseMiddleware {
|
|
|
96
101
|
* });
|
|
97
102
|
* ```
|
|
98
103
|
*/
|
|
99
|
-
export declare const errorHandler: () => BaseMiddleware
|
|
104
|
+
export declare const errorHandler: <TBody = unknown, TUser = unknown>() => BaseMiddleware<TBody, TUser>;
|
|
100
105
|
//# sourceMappingURL=errorHandlerMiddleware.d.ts.map
|
|
@@ -9,6 +9,8 @@ const core_1 = require("../core");
|
|
|
9
9
|
* - For `HttpError` instances, responds with the error message, and optionally details and code based on environment and error type.
|
|
10
10
|
* - For other errors, responds with a generic message in production, and includes stack trace in development.
|
|
11
11
|
*
|
|
12
|
+
* @template TBody - The type of the request body payload (preserves type chain)
|
|
13
|
+
* @template TUser - The type of the authenticated user (preserves type chain)
|
|
12
14
|
* @param error - The error object thrown during request processing.
|
|
13
15
|
* @param context - The request context containing request and response objects.
|
|
14
16
|
* @returns A promise that resolves when the error response has been sent.
|
|
@@ -65,6 +67,9 @@ const handleError = async (error, context) => {
|
|
|
65
67
|
* Implements the `BaseMiddleware` interface and provides an asynchronous
|
|
66
68
|
* `onError` method that delegates error handling to the `handleError` function.
|
|
67
69
|
*
|
|
70
|
+
* @template TBody - The type of the request body payload (preserves type chain)
|
|
71
|
+
* @template TUser - The type of the authenticated user (preserves type chain)
|
|
72
|
+
*
|
|
68
73
|
* @remarks
|
|
69
74
|
* This middleware should be registered to catch and process errors that occur
|
|
70
75
|
* during request handling.
|
|
@@ -120,6 +125,8 @@ exports.ErrorHandlerMiddleware = ErrorHandlerMiddleware;
|
|
|
120
125
|
/**
|
|
121
126
|
* Creates an error handling middleware for processing errors in the application.
|
|
122
127
|
*
|
|
128
|
+
* @template TBody - The type of the request body payload (preserves type chain)
|
|
129
|
+
* @template TUser - The type of the authenticated user (preserves type chain)
|
|
123
130
|
* @returns {BaseMiddleware} An object implementing the `onError` method to handle errors.
|
|
124
131
|
*
|
|
125
132
|
* @remarks
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
* return { valid: false, error: error.message };
|
|
43
43
|
* }
|
|
44
44
|
* },
|
|
45
|
-
* extractUserId: (decoded:
|
|
46
|
-
* isTokenExpired: (decoded:
|
|
45
|
+
* extractUserId: (decoded: any) => decoded.sub,
|
|
46
|
+
* isTokenExpired: (decoded: any) => decoded.exp < Date.now() / 1000
|
|
47
47
|
* };
|
|
48
48
|
*
|
|
49
49
|
* // Configure guard system
|
|
@@ -43,8 +43,8 @@
|
|
|
43
43
|
* return { valid: false, error: error.message };
|
|
44
44
|
* }
|
|
45
45
|
* },
|
|
46
|
-
* extractUserId: (decoded:
|
|
47
|
-
* isTokenExpired: (decoded:
|
|
46
|
+
* extractUserId: (decoded: any) => decoded.sub,
|
|
47
|
+
* isTokenExpired: (decoded: any) => decoded.exp < Date.now() / 1000
|
|
48
48
|
* };
|
|
49
49
|
*
|
|
50
50
|
* // Configure guard system
|
|
@@ -245,7 +245,7 @@ export declare class TokenVerificationAdapterFactory {
|
|
|
245
245
|
* @param expirationField - Optional field name for expiration (e.g., 'expiresAt', 'exp')
|
|
246
246
|
* @returns Configured adapter for API key tokens
|
|
247
247
|
*/
|
|
248
|
-
static forAPIKey<T extends Record<string,
|
|
248
|
+
static forAPIKey<T extends Record<string, any>>(verificationPort: CustomTokenVerificationPort<T>, userIdField: keyof T, expirationField?: keyof T): CustomTokenVerificationPortAdapter<T>;
|
|
249
249
|
/**
|
|
250
250
|
* Create adapter for OAuth tokens with standard OAuth claims.
|
|
251
251
|
*
|
|
@@ -43,7 +43,7 @@ export interface AuthenticationResult {
|
|
|
43
43
|
success: boolean;
|
|
44
44
|
user?: UserContext;
|
|
45
45
|
token?: {
|
|
46
|
-
decoded:
|
|
46
|
+
decoded: any;
|
|
47
47
|
raw: string;
|
|
48
48
|
expiresAt: string;
|
|
49
49
|
issuer?: string;
|
|
@@ -63,7 +63,7 @@ export interface AuthGuardConfig {
|
|
|
63
63
|
allowedIssuers?: string[];
|
|
64
64
|
requireEmailVerification: boolean;
|
|
65
65
|
allowInactiveUsers: boolean;
|
|
66
|
-
customValidation?: (token:
|
|
66
|
+
customValidation?: (token: any, user: UserContext) => Promise<boolean>;
|
|
67
67
|
}
|
|
68
68
|
/**
|
|
69
69
|
* Token validation service interface
|
|
@@ -74,17 +74,17 @@ export interface TokenValidator {
|
|
|
74
74
|
*/
|
|
75
75
|
validateToken(token: string): Promise<{
|
|
76
76
|
valid: boolean;
|
|
77
|
-
decoded?:
|
|
77
|
+
decoded?: any;
|
|
78
78
|
error?: string;
|
|
79
79
|
}>;
|
|
80
80
|
/**
|
|
81
81
|
* Extract user ID from decoded token
|
|
82
82
|
*/
|
|
83
|
-
extractUserId(decoded:
|
|
83
|
+
extractUserId(decoded: any): string;
|
|
84
84
|
/**
|
|
85
85
|
* Check if token is expired
|
|
86
86
|
*/
|
|
87
|
-
isTokenExpired(decoded:
|
|
87
|
+
isTokenExpired(decoded: any): boolean;
|
|
88
88
|
}
|
|
89
89
|
/**
|
|
90
90
|
* Fast Authentication Guard Implementation
|
|
@@ -162,8 +162,16 @@ export declare class PermissionGuardFactory {
|
|
|
162
162
|
getStats(): {
|
|
163
163
|
totalGuards: number;
|
|
164
164
|
guardsByType: Record<string, number>;
|
|
165
|
-
individualGuardStats:
|
|
166
|
-
|
|
165
|
+
individualGuardStats: {
|
|
166
|
+
guardType: string;
|
|
167
|
+
checkCount: number;
|
|
168
|
+
successCount: number;
|
|
169
|
+
failureCount: number;
|
|
170
|
+
successRate: number;
|
|
171
|
+
averageProcessingTimeUs: number;
|
|
172
|
+
totalProcessingTimeUs: number;
|
|
173
|
+
}[];
|
|
174
|
+
aggregatedStats: any;
|
|
167
175
|
};
|
|
168
176
|
/**
|
|
169
177
|
* Clear guard cache
|
|
@@ -388,7 +388,7 @@ let PermissionGuardFactory = class PermissionGuardFactory {
|
|
|
388
388
|
createCompositeGuard(requirements, config = {}) {
|
|
389
389
|
const fullConfig = {
|
|
390
390
|
requireAuth: true,
|
|
391
|
-
permissions: requirements, // Store requirements as permissions for cache key
|
|
391
|
+
permissions: requirements, // Store requirements as permissions for cache key (complex composite type)
|
|
392
392
|
cacheResults: true,
|
|
393
393
|
auditTrail: false,
|
|
394
394
|
...config,
|
|
@@ -118,7 +118,7 @@ export declare class ExpressionPermissionResolver extends PermissionResolver<Per
|
|
|
118
118
|
/**
|
|
119
119
|
* Check if this resolver can handle the given requirement type
|
|
120
120
|
*/
|
|
121
|
-
canHandle(requirement:
|
|
121
|
+
canHandle(requirement: any): requirement is PermissionExpression;
|
|
122
122
|
/**
|
|
123
123
|
* Normalize expression for consistent cache keys
|
|
124
124
|
*
|