@forinda/kickjs 3.1.3 → 4.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.
- package/README.md +13 -212
- package/dist/adapter-BNw2pGbg.d.mts +261 -0
- package/dist/adapter-BNw2pGbg.d.mts.map +1 -0
- package/dist/{app-module-Cotu9TIC.d.mts → app-module-CO0ksPCm.d.mts} +12 -2
- package/dist/app-module-CO0ksPCm.d.mts.map +1 -0
- package/dist/{application-BVl6L8xo.mjs → application-Ce4DQN6m.mjs} +114 -25
- package/dist/application-Ce4DQN6m.mjs.map +1 -0
- package/dist/application-Czwm7Gty.d.mts +302 -0
- package/dist/application-Czwm7Gty.d.mts.map +1 -0
- package/dist/{bootstrap-D6leYXz2.mjs → bootstrap-CB7bJeJG.mjs} +6 -6
- package/dist/{bootstrap-D6leYXz2.mjs.map → bootstrap-CB7bJeJG.mjs.map} +1 -1
- package/dist/bootstrap-NxFRaNTh.d.mts +28 -0
- package/dist/bootstrap-NxFRaNTh.d.mts.map +1 -0
- package/dist/{cache-CcTzzNdr.d.mts → cache-BStrqXSZ.d.mts} +2 -2
- package/dist/{cache-CcTzzNdr.d.mts.map → cache-BStrqXSZ.d.mts.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +3 -3
- package/dist/{config-gkVEnxVm.mjs → config-wZ_TgBfs.mjs} +4 -4
- package/dist/{config-gkVEnxVm.mjs.map → config-wZ_TgBfs.mjs.map} +1 -1
- package/dist/{container-BJb34faa.d.mts → container-CnWDsxi-.d.mts} +9 -7
- package/dist/container-CnWDsxi-.d.mts.map +1 -0
- package/dist/{container-BBZLlK6y.mjs → container-DYYSu58w.mjs} +313 -9
- package/dist/container-DYYSu58w.mjs.map +1 -0
- package/dist/context-BAGzqT7-.mjs +319 -0
- package/dist/context-BAGzqT7-.mjs.map +1 -0
- package/dist/context-Ymvv-85x.d.mts +260 -0
- package/dist/context-Ymvv-85x.d.mts.map +1 -0
- package/dist/context-decorator-B5v3VQCN.d.mts +111 -0
- package/dist/context-decorator-B5v3VQCN.d.mts.map +1 -0
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.d.mts +1 -1
- package/dist/core/cache.mjs +2 -2
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.d.mts +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.d.mts +1 -1
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +2 -2
- package/dist/core/decorators.mjs +48 -16
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.d.mts +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.d.mts +1 -1
- package/dist/core/interfaces.mjs +35 -16
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.d.mts +2 -2
- package/dist/core/logger.mjs +2 -4
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.d.mts +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.d.mts +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/core-DBcoqPHM.mjs +709 -0
- package/dist/core-DBcoqPHM.mjs.map +1 -0
- package/dist/cors-BfgqfLPd.d.mts +48 -0
- package/dist/cors-BfgqfLPd.d.mts.map +1 -0
- package/dist/{cron-H-IyLcOr.d.mts → cron-7zqvsmMI.d.mts} +1 -1
- package/dist/{cron-H-IyLcOr.d.mts.map → cron-7zqvsmMI.d.mts.map} +1 -1
- package/dist/csrf-DiK9zept.d.mts +52 -0
- package/dist/csrf-DiK9zept.d.mts.map +1 -0
- package/dist/{decorators-C9_SN7ge.d.mts → decorators-BMvaLliz.d.mts} +147 -12
- package/dist/decorators-BMvaLliz.d.mts.map +1 -0
- package/dist/{env-Cu5hWsuE.mjs → env-CdH5-dM_.mjs} +3 -4
- package/dist/{env-Cu5hWsuE.mjs.map → env-CdH5-dM_.mjs.map} +1 -1
- package/dist/error-handler-Xud_3Lah.d.mts +20 -0
- package/dist/error-handler-Xud_3Lah.d.mts.map +1 -0
- package/dist/{errors-BOUCRl-p.d.mts → errors-uaHCeXRz.d.mts} +1 -1
- package/dist/{errors-BOUCRl-p.d.mts.map → errors-uaHCeXRz.d.mts.map} +1 -1
- package/dist/execution-context-DKnt61pY.d.mts +57 -0
- package/dist/execution-context-DKnt61pY.d.mts.map +1 -0
- package/dist/helmet-CaMbjzBG.d.mts +41 -0
- package/dist/helmet-CaMbjzBG.d.mts.map +1 -0
- package/dist/http/application.d.mts +2 -239
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +2 -27
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +3 -262
- package/dist/http/context.mjs +2 -271
- package/dist/http/middleware/cors.d.mts +2 -47
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +2 -51
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.d.mts +2 -19
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.d.mts +2 -40
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.d.mts +2 -55
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.d.mts +2 -9
- package/dist/http/middleware/request-id.mjs +12 -3
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.d.mts +2 -31
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.d.mts +2 -69
- package/dist/http/middleware/session.mjs +1 -1
- package/dist/http/middleware/spa.d.mts +2 -100
- package/dist/http/middleware/spa.mjs +5 -5
- package/dist/http/middleware/spa.mjs.map +1 -1
- package/dist/http/middleware/upload.d.mts +2 -78
- package/dist/http/middleware/upload.mjs +1 -1
- package/dist/http/middleware/validate.d.mts +2 -22
- package/dist/http/middleware/validate.mjs +2 -2
- package/dist/http/middleware/views.d.mts +2 -61
- package/dist/http/middleware/views.mjs +16 -15
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.d.mts +1 -1
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +2 -20
- package/dist/http/router-builder.mjs +58 -10
- package/dist/http/router-builder.mjs.map +1 -1
- package/dist/{index-Co7a3Zat.d.mts → index-B9cyOQAe.d.mts} +1 -1
- package/dist/{index-Co7a3Zat.d.mts.map → index-B9cyOQAe.d.mts.map} +1 -1
- package/dist/{index-DNVfGjF9.d.mts → index-D-qhXg9M.d.mts} +3 -3
- package/dist/{index-DNVfGjF9.d.mts.map → index-D-qhXg9M.d.mts.map} +1 -1
- package/dist/index-DQyWtyp0.d.mts +511 -0
- package/dist/index-DQyWtyp0.d.mts.map +1 -0
- package/dist/index.d.mts +34 -133
- package/dist/index.mjs +14 -14
- package/dist/interfaces-B50n7dwl.d.mts +71 -0
- package/dist/{interfaces-DXjE8Re1.d.mts.map → interfaces-B50n7dwl.d.mts.map} +1 -1
- package/dist/{logger-CW6FHtvU.d.mts → logger-CLVRZf2N.d.mts} +2 -4
- package/dist/{logger-CW6FHtvU.d.mts.map → logger-CLVRZf2N.d.mts.map} +1 -1
- package/dist/{metadata-BwRJ69bC.mjs → metadata-VQM9wChy.mjs} +2 -2
- package/dist/{metadata-BwRJ69bC.mjs.map → metadata-VQM9wChy.mjs.map} +1 -1
- package/dist/{path-B4JcbwKX.d.mts → path-Diviu6hv.d.mts} +1 -1
- package/dist/path-Diviu6hv.d.mts.map +1 -0
- package/dist/plugin-WdrDgNzk.d.mts +165 -0
- package/dist/plugin-WdrDgNzk.d.mts.map +1 -0
- package/dist/{query-BQ2UT3oi.mjs → query-DJMxdx5r.mjs} +2 -2
- package/dist/{query-BQ2UT3oi.mjs.map → query-DJMxdx5r.mjs.map} +1 -1
- package/dist/rate-limit-DUwoICtI.d.mts +56 -0
- package/dist/rate-limit-DUwoICtI.d.mts.map +1 -0
- package/dist/{reactivity-I8nDlg4c.d.mts → reactivity-CfJceo4H.d.mts} +1 -1
- package/dist/{reactivity-I8nDlg4c.d.mts.map → reactivity-CfJceo4H.d.mts.map} +1 -1
- package/dist/request-id-BgglvZHN.d.mts +19 -0
- package/dist/request-id-BgglvZHN.d.mts.map +1 -0
- package/dist/request-logger-CWHbAzTE.d.mts +32 -0
- package/dist/request-logger-CWHbAzTE.d.mts.map +1 -0
- package/dist/router-builder-C799BAf0.d.mts +31 -0
- package/dist/router-builder-C799BAf0.d.mts.map +1 -0
- package/dist/session-N0hActOO.d.mts +70 -0
- package/dist/session-N0hActOO.d.mts.map +1 -0
- package/dist/spa-CrFR2_cz.d.mts +101 -0
- package/dist/spa-CrFR2_cz.d.mts.map +1 -0
- package/dist/upload-BueOnnLw.d.mts +79 -0
- package/dist/upload-BueOnnLw.d.mts.map +1 -0
- package/dist/validate-HwAyWTwH.d.mts +23 -0
- package/dist/validate-HwAyWTwH.d.mts.map +1 -0
- package/dist/views-DhQSXV2P.d.mts +176 -0
- package/dist/views-DhQSXV2P.d.mts.map +1 -0
- package/package.json +6 -9
- package/dist/adapter-DjL8ql5d.d.mts +0 -140
- package/dist/adapter-DjL8ql5d.d.mts.map +0 -1
- package/dist/app-module-Cotu9TIC.d.mts.map +0 -1
- package/dist/application-BVl6L8xo.mjs.map +0 -1
- package/dist/chunk-CVPG7JJl.mjs +0 -15
- package/dist/container-BBZLlK6y.mjs.map +0 -1
- package/dist/container-BJb34faa.d.mts.map +0 -1
- package/dist/core-qyPNtpKp.mjs +0 -121
- package/dist/core-qyPNtpKp.mjs.map +0 -1
- package/dist/decorators-C9_SN7ge.d.mts.map +0 -1
- package/dist/http/application.d.mts.map +0 -1
- package/dist/http/bootstrap.d.mts.map +0 -1
- package/dist/http/context.d.mts.map +0 -1
- package/dist/http/context.mjs.map +0 -1
- package/dist/http/middleware/cors.d.mts.map +0 -1
- package/dist/http/middleware/csrf.d.mts.map +0 -1
- package/dist/http/middleware/error-handler.d.mts.map +0 -1
- package/dist/http/middleware/helmet.d.mts.map +0 -1
- package/dist/http/middleware/rate-limit.d.mts.map +0 -1
- package/dist/http/middleware/request-id.d.mts.map +0 -1
- package/dist/http/middleware/request-logger.d.mts.map +0 -1
- package/dist/http/middleware/session.d.mts.map +0 -1
- package/dist/http/middleware/spa.d.mts.map +0 -1
- package/dist/http/middleware/upload.d.mts.map +0 -1
- package/dist/http/middleware/validate.d.mts.map +0 -1
- package/dist/http/middleware/views.d.mts.map +0 -1
- package/dist/http/router-builder.d.mts.map +0 -1
- package/dist/index-CwqjAF6I.d.mts +0 -112
- package/dist/index-CwqjAF6I.d.mts.map +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/interfaces-DXjE8Re1.d.mts +0 -52
- package/dist/path-B4JcbwKX.d.mts.map +0 -1
- package/dist/plugin-Cvacmm7N.d.mts +0 -95
- package/dist/plugin-Cvacmm7N.d.mts.map +0 -1
package/dist/http/context.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs
|
|
2
|
+
* @forinda/kickjs v4.0.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,274 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import {
|
|
12
|
-
//#region src/http/context.ts
|
|
13
|
-
/**
|
|
14
|
-
* Unified request/response abstraction passed to every controller method.
|
|
15
|
-
* Shields handlers from raw Express objects and provides convenience methods.
|
|
16
|
-
*/
|
|
17
|
-
var RequestContext = class {
|
|
18
|
-
constructor(req, res, next) {
|
|
19
|
-
this.req = req;
|
|
20
|
-
this.res = res;
|
|
21
|
-
this.next = next;
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Per-request metadata map shared across all RequestContext instances
|
|
25
|
-
* for the same request. Stored on `req` so middleware can pass data
|
|
26
|
-
* to handlers via `ctx.set()` / `ctx.get()`.
|
|
27
|
-
*/
|
|
28
|
-
get metadata() {
|
|
29
|
-
const r = this.req;
|
|
30
|
-
if (!r.__ctxMeta) r.__ctxMeta = /* @__PURE__ */ new Map();
|
|
31
|
-
return r.__ctxMeta;
|
|
32
|
-
}
|
|
33
|
-
get body() {
|
|
34
|
-
return this.req.body;
|
|
35
|
-
}
|
|
36
|
-
get params() {
|
|
37
|
-
return this.req.params;
|
|
38
|
-
}
|
|
39
|
-
get query() {
|
|
40
|
-
return this.req.query;
|
|
41
|
-
}
|
|
42
|
-
get headers() {
|
|
43
|
-
return this.req.headers;
|
|
44
|
-
}
|
|
45
|
-
get requestId() {
|
|
46
|
-
return this.req.requestId ?? this.req.headers["x-request-id"];
|
|
47
|
-
}
|
|
48
|
-
/** Session data (requires session middleware) */
|
|
49
|
-
get session() {
|
|
50
|
-
return this.req.session;
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* The authenticated user set by AuthAdapter.
|
|
54
|
-
* Reads from the per-request metadata store first (`ctx.set('user', ...)`),
|
|
55
|
-
* then falls back to `req.user` (set directly by AuthAdapter middleware).
|
|
56
|
-
*
|
|
57
|
-
* Extend the `AuthUser` interface via module augmentation in `@forinda/kickjs-auth`
|
|
58
|
-
* to get full typing.
|
|
59
|
-
*
|
|
60
|
-
* @example
|
|
61
|
-
* ```ts
|
|
62
|
-
* @Get('/me')
|
|
63
|
-
* @Authenticated()
|
|
64
|
-
* getProfile(ctx: RequestContext) {
|
|
65
|
-
* const user = ctx.user
|
|
66
|
-
* if (!user) return ctx.notFound()
|
|
67
|
-
* return ctx.json({ user })
|
|
68
|
-
* }
|
|
69
|
-
* ```
|
|
70
|
-
*/
|
|
71
|
-
get user() {
|
|
72
|
-
return this.metadata.get("user") ?? this.req.user;
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Tenant identifier for multi-tenant apps. Reads `user.tenantId` —
|
|
76
|
-
* populated either by `AuthAdapter.testMode({ tenantId })`, a tenant
|
|
77
|
-
* resolver middleware, or manually on the strategy's `mapPayload`.
|
|
78
|
-
*
|
|
79
|
-
* Augment `AuthUser` (or `ContextMeta['user']`) to widen the return
|
|
80
|
-
* type if your user shape guarantees a non-`string | undefined` id.
|
|
81
|
-
*/
|
|
82
|
-
get tenantId() {
|
|
83
|
-
return this.user?.tenantId;
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* Effective role list for the current user. Prefers `user.tenantRoles`
|
|
87
|
-
* (populated by `AuthAdapterOptions.roleResolver` under a tenant) and
|
|
88
|
-
* falls back to `user.roles`. Returns an empty array when the user is
|
|
89
|
-
* absent or the shape has neither field.
|
|
90
|
-
*/
|
|
91
|
-
get roles() {
|
|
92
|
-
const u = this.user;
|
|
93
|
-
return u?.tenantRoles ?? u?.roles ?? [];
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Parse the request query string into structured filters, sort, pagination, and search.
|
|
97
|
-
* Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).
|
|
98
|
-
*
|
|
99
|
-
* Generic over the field config: when passed an inline literal (or
|
|
100
|
-
* `as const`), `filters[].field` and `sort[].field` are narrowed to
|
|
101
|
-
* the exact whitelisted field names. Pass nothing or a non-literal
|
|
102
|
-
* config and you get the loose `string` fallback.
|
|
103
|
-
*
|
|
104
|
-
* @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields
|
|
105
|
-
*
|
|
106
|
-
* @example
|
|
107
|
-
* ```ts
|
|
108
|
-
* @Get('/')
|
|
109
|
-
* async list(ctx: RequestContext) {
|
|
110
|
-
* const parsed = ctx.qs({
|
|
111
|
-
* filterable: ['status', 'priority'],
|
|
112
|
-
* sortable: ['createdAt', 'title'],
|
|
113
|
-
* } as const)
|
|
114
|
-
* parsed.filters[0].field // typed as 'status' | 'priority'
|
|
115
|
-
* parsed.sort[0].field // typed as 'createdAt' | 'title'
|
|
116
|
-
* }
|
|
117
|
-
* ```
|
|
118
|
-
*/
|
|
119
|
-
qs(fieldConfig) {
|
|
120
|
-
return parseQuery(this.req.query, fieldConfig);
|
|
121
|
-
}
|
|
122
|
-
/** Single uploaded file (requires @FileUpload({ mode: 'single' })) */
|
|
123
|
-
get file() {
|
|
124
|
-
return this.req.file;
|
|
125
|
-
}
|
|
126
|
-
/** Array of uploaded files (requires @FileUpload({ mode: 'array' })) */
|
|
127
|
-
get files() {
|
|
128
|
-
return this.req.files;
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* Read a value from the per-request metadata store.
|
|
132
|
-
*
|
|
133
|
-
* When `ContextMeta` has been augmented with a matching key, the return
|
|
134
|
-
* type is inferred automatically. For ad-hoc keys, pass a generic:
|
|
135
|
-
* `ctx.get<MyType>('custom')`.
|
|
136
|
-
*/
|
|
137
|
-
get(key) {
|
|
138
|
-
return this.metadata.get(key);
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* Write a value to the per-request metadata store.
|
|
142
|
-
*
|
|
143
|
-
* When `ContextMeta` has been augmented with a matching key, the value
|
|
144
|
-
* type is checked at compile time.
|
|
145
|
-
*/
|
|
146
|
-
set(key, value) {
|
|
147
|
-
this.metadata.set(key, value);
|
|
148
|
-
}
|
|
149
|
-
json(data, status = 200) {
|
|
150
|
-
return this.res.status(status).json(data);
|
|
151
|
-
}
|
|
152
|
-
created(data) {
|
|
153
|
-
return this.res.status(201).json(data);
|
|
154
|
-
}
|
|
155
|
-
noContent() {
|
|
156
|
-
return this.res.status(204).end();
|
|
157
|
-
}
|
|
158
|
-
notFound(message = "Not Found") {
|
|
159
|
-
return this.res.status(404).json({ message });
|
|
160
|
-
}
|
|
161
|
-
badRequest(message) {
|
|
162
|
-
return this.res.status(400).json({ message });
|
|
163
|
-
}
|
|
164
|
-
html(content, status = 200) {
|
|
165
|
-
return this.res.status(status).type("html").send(content);
|
|
166
|
-
}
|
|
167
|
-
download(buffer, filename, contentType = "application/octet-stream") {
|
|
168
|
-
this.res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
|
|
169
|
-
this.res.setHeader("Content-Type", contentType);
|
|
170
|
-
return this.res.send(buffer);
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).
|
|
174
|
-
* Requires a ViewAdapter to be configured in bootstrap().
|
|
175
|
-
*
|
|
176
|
-
* @param template - Template name (without extension, relative to viewsDir)
|
|
177
|
-
* @param data - Data to pass to the template
|
|
178
|
-
*
|
|
179
|
-
* @example
|
|
180
|
-
* ```ts
|
|
181
|
-
* ctx.render('dashboard', { user, title: 'Dashboard' })
|
|
182
|
-
* ctx.render('emails/welcome', { name: 'Alice' })
|
|
183
|
-
* ```
|
|
184
|
-
*/
|
|
185
|
-
render(template, data = {}) {
|
|
186
|
-
return this.res.render(template, data);
|
|
187
|
-
}
|
|
188
|
-
/**
|
|
189
|
-
* Parse query params and return a standardized paginated response.
|
|
190
|
-
* Calls `ctx.qs()` internally, then wraps your data with pagination meta.
|
|
191
|
-
*
|
|
192
|
-
* @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`
|
|
193
|
-
* @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields
|
|
194
|
-
*
|
|
195
|
-
* @example
|
|
196
|
-
* ```ts
|
|
197
|
-
* @Get('/')
|
|
198
|
-
* async list(ctx: RequestContext) {
|
|
199
|
-
* return ctx.paginate(
|
|
200
|
-
* async (parsed) => {
|
|
201
|
-
* const data = await db.select().from(users)
|
|
202
|
-
* .where(query.where).limit(parsed.pagination.limit)
|
|
203
|
-
* .offset(parsed.pagination.offset).all()
|
|
204
|
-
* const total = await db.select({ count: count() }).from(users).get()
|
|
205
|
-
* return { data, total: total?.count ?? 0 }
|
|
206
|
-
* },
|
|
207
|
-
* { filterable: ['name', 'role'], sortable: ['createdAt'] },
|
|
208
|
-
* )
|
|
209
|
-
* }
|
|
210
|
-
* ```
|
|
211
|
-
*/
|
|
212
|
-
async paginate(fetcher, fieldConfig) {
|
|
213
|
-
const parsed = this.qs(fieldConfig);
|
|
214
|
-
const { data, total } = await fetcher(parsed);
|
|
215
|
-
const { page, limit } = parsed.pagination;
|
|
216
|
-
const totalPages = Math.ceil(total / limit) || 1;
|
|
217
|
-
const response = {
|
|
218
|
-
data,
|
|
219
|
-
meta: {
|
|
220
|
-
page,
|
|
221
|
-
limit,
|
|
222
|
-
total,
|
|
223
|
-
totalPages,
|
|
224
|
-
hasNext: page < totalPages,
|
|
225
|
-
hasPrev: page > 1
|
|
226
|
-
}
|
|
227
|
-
};
|
|
228
|
-
return this.json(response);
|
|
229
|
-
}
|
|
230
|
-
/**
|
|
231
|
-
* Start an SSE (Server-Sent Events) stream.
|
|
232
|
-
* Sets the correct headers and returns helpers to send events.
|
|
233
|
-
*
|
|
234
|
-
* @example
|
|
235
|
-
* ```ts
|
|
236
|
-
* @Get('/events')
|
|
237
|
-
* async stream(ctx: RequestContext) {
|
|
238
|
-
* const sse = ctx.sse()
|
|
239
|
-
*
|
|
240
|
-
* const interval = setInterval(() => {
|
|
241
|
-
* sse.send({ time: new Date().toISOString() }, 'tick')
|
|
242
|
-
* }, 1000)
|
|
243
|
-
*
|
|
244
|
-
* sse.onClose(() => clearInterval(interval))
|
|
245
|
-
* }
|
|
246
|
-
* ```
|
|
247
|
-
*/
|
|
248
|
-
sse() {
|
|
249
|
-
this.res.writeHead(200, {
|
|
250
|
-
"Content-Type": "text/event-stream",
|
|
251
|
-
"Cache-Control": "no-cache",
|
|
252
|
-
Connection: "keep-alive",
|
|
253
|
-
"X-Accel-Buffering": "no"
|
|
254
|
-
});
|
|
255
|
-
this.res.flushHeaders();
|
|
256
|
-
const closeCallbacks = [];
|
|
257
|
-
this.req.on("close", () => {
|
|
258
|
-
for (const cb of closeCallbacks) cb();
|
|
259
|
-
});
|
|
260
|
-
return {
|
|
261
|
-
send: (data, event, id) => {
|
|
262
|
-
if (id) this.res.write(`id: ${id}\n`);
|
|
263
|
-
if (event) this.res.write(`event: ${event}\n`);
|
|
264
|
-
this.res.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
265
|
-
},
|
|
266
|
-
comment: (text) => {
|
|
267
|
-
this.res.write(`: ${text}\n\n`);
|
|
268
|
-
},
|
|
269
|
-
onClose: (fn) => {
|
|
270
|
-
closeCallbacks.push(fn);
|
|
271
|
-
},
|
|
272
|
-
close: () => {
|
|
273
|
-
this.res.end();
|
|
274
|
-
}
|
|
275
|
-
};
|
|
276
|
-
}
|
|
277
|
-
};
|
|
278
|
-
//#endregion
|
|
11
|
+
import { t as RequestContext } from "../context-BAGzqT7-.mjs";
|
|
279
12
|
export { RequestContext };
|
|
280
|
-
|
|
281
|
-
//# sourceMappingURL=context.mjs.map
|
|
@@ -1,48 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
//#region src/http/middleware/cors.d.ts
|
|
5
|
-
interface CorsOptions {
|
|
6
|
-
/** Allowed origin(s). `true` reflects request origin, `'*'` allows all, `false` rejects all. Default: `false` (restrictive) */
|
|
7
|
-
origin?: boolean | string | RegExp | (string | RegExp)[];
|
|
8
|
-
/** Allowed HTTP methods. Default: `['GET','HEAD','PUT','PATCH','POST','DELETE']` */
|
|
9
|
-
methods?: string[];
|
|
10
|
-
/** Allowed request headers. Default: reflects `Access-Control-Request-Headers` */
|
|
11
|
-
allowedHeaders?: string[];
|
|
12
|
-
/** Headers exposed to the browser. Default: none */
|
|
13
|
-
exposedHeaders?: string[];
|
|
14
|
-
/** Allow credentials (cookies, authorization). Default: false */
|
|
15
|
-
credentials?: boolean;
|
|
16
|
-
/** Preflight cache duration in seconds. Default: 86400 (24h) */
|
|
17
|
-
maxAge?: number;
|
|
18
|
-
/** Handle preflight OPTIONS requests. Default: true */
|
|
19
|
-
preflight?: boolean;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* CORS middleware with correct spec behavior.
|
|
23
|
-
*
|
|
24
|
-
* - Reflects origin from allowlist (sets `Vary: Origin`)
|
|
25
|
-
* - Handles preflight `OPTIONS` with `204 No Content`
|
|
26
|
-
* - Supports string, regex, and array origin matching
|
|
27
|
-
*
|
|
28
|
-
* @example
|
|
29
|
-
* ```ts
|
|
30
|
-
* // Allow all origins
|
|
31
|
-
* bootstrap({ middleware: [cors(), express.json()] })
|
|
32
|
-
*
|
|
33
|
-
* // Allowlist specific origins
|
|
34
|
-
* bootstrap({
|
|
35
|
-
* middleware: [
|
|
36
|
-
* cors({
|
|
37
|
-
* origin: ['https://app.example.com', /\.example\.com$/],
|
|
38
|
-
* credentials: true,
|
|
39
|
-
* }),
|
|
40
|
-
* express.json(),
|
|
41
|
-
* ],
|
|
42
|
-
* })
|
|
43
|
-
* ```
|
|
44
|
-
*/
|
|
45
|
-
declare function cors(options?: CorsOptions): (req: Request, res: Response, next: NextFunction) => void;
|
|
46
|
-
//#endregion
|
|
47
|
-
export { CorsOptions, cors };
|
|
48
|
-
//# sourceMappingURL=cors.d.mts.map
|
|
2
|
+
import { n as cors, t as CorsOptions } from "../../cors-BfgqfLPd.mjs";
|
|
3
|
+
export { CorsOptions, cors };
|
|
@@ -1,52 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
//#region src/http/middleware/csrf.d.ts
|
|
5
|
-
interface CsrfOptions {
|
|
6
|
-
/** Cookie name for the CSRF token (default: '_csrf') */
|
|
7
|
-
cookie?: string;
|
|
8
|
-
/** Header name to check for the token (default: 'x-csrf-token') */
|
|
9
|
-
header?: string;
|
|
10
|
-
/** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */
|
|
11
|
-
methods?: string[];
|
|
12
|
-
/** Paths to exclude from CSRF checks (e.g. webhooks) */
|
|
13
|
-
ignorePaths?: string[];
|
|
14
|
-
/** Token byte length before hex encoding (default: 32 = 64 hex chars) */
|
|
15
|
-
tokenLength?: number;
|
|
16
|
-
/** Cookie options */
|
|
17
|
-
cookieOptions?: {
|
|
18
|
-
httpOnly?: boolean;
|
|
19
|
-
sameSite?: 'strict' | 'lax' | 'none';
|
|
20
|
-
secure?: boolean;
|
|
21
|
-
path?: string;
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Double-submit cookie CSRF protection middleware.
|
|
26
|
-
*
|
|
27
|
-
* On every request, sets a CSRF token cookie. For state-changing methods
|
|
28
|
-
* (POST, PUT, PATCH, DELETE), validates that the request header matches
|
|
29
|
-
* the cookie value.
|
|
30
|
-
*
|
|
31
|
-
* @example
|
|
32
|
-
* ```ts
|
|
33
|
-
* import { csrf } from '@forinda/kickjs-http'
|
|
34
|
-
*
|
|
35
|
-
* bootstrap({
|
|
36
|
-
* modules,
|
|
37
|
-
* middleware: [
|
|
38
|
-
* cookieParser(),
|
|
39
|
-
* csrf(),
|
|
40
|
-
* // ... other middleware
|
|
41
|
-
* ],
|
|
42
|
-
* })
|
|
43
|
-
* ```
|
|
44
|
-
*
|
|
45
|
-
* Client usage:
|
|
46
|
-
* 1. Read the `_csrf` cookie value
|
|
47
|
-
* 2. Send it in the `x-csrf-token` header on every mutating request
|
|
48
|
-
*/
|
|
49
|
-
declare function csrf(options?: CsrfOptions): (req: Request, res: Response, next: NextFunction) => void | Response<any, Record<string, any>>;
|
|
50
|
-
//#endregion
|
|
51
|
-
export { CsrfOptions, csrf };
|
|
52
|
-
//# sourceMappingURL=csrf.d.mts.map
|
|
2
|
+
import { n as csrf, t as CsrfOptions } from "../../csrf-DiK9zept.mjs";
|
|
3
|
+
export { CsrfOptions, csrf };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs
|
|
2
|
+
* @forinda/kickjs v4.0.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -19,7 +19,7 @@ import { randomBytes } from "node:crypto";
|
|
|
19
19
|
*
|
|
20
20
|
* @example
|
|
21
21
|
* ```ts
|
|
22
|
-
* import { csrf } from '@forinda/kickjs
|
|
22
|
+
* import { csrf } from '@forinda/kickjs'
|
|
23
23
|
*
|
|
24
24
|
* bootstrap({
|
|
25
25
|
* modules,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"csrf.mjs","names":[],"sources":["../../../src/http/middleware/csrf.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\n\nexport interface CsrfOptions {\n /** Cookie name for the CSRF token (default: '_csrf') */\n cookie?: string\n /** Header name to check for the token (default: 'x-csrf-token') */\n header?: string\n /** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */\n methods?: string[]\n /** Paths to exclude from CSRF checks (e.g. webhooks) */\n ignorePaths?: string[]\n /** Token byte length before hex encoding (default: 32 = 64 hex chars) */\n tokenLength?: number\n /** Cookie options */\n cookieOptions?: {\n httpOnly?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n secure?: boolean\n path?: string\n }\n}\n\n/**\n * Double-submit cookie CSRF protection middleware.\n *\n * On every request, sets a CSRF token cookie. For state-changing methods\n * (POST, PUT, PATCH, DELETE), validates that the request header matches\n * the cookie value.\n *\n * @example\n * ```ts\n * import { csrf } from '@forinda/kickjs
|
|
1
|
+
{"version":3,"file":"csrf.mjs","names":[],"sources":["../../../src/http/middleware/csrf.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\n\nexport interface CsrfOptions {\n /** Cookie name for the CSRF token (default: '_csrf') */\n cookie?: string\n /** Header name to check for the token (default: 'x-csrf-token') */\n header?: string\n /** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */\n methods?: string[]\n /** Paths to exclude from CSRF checks (e.g. webhooks) */\n ignorePaths?: string[]\n /** Token byte length before hex encoding (default: 32 = 64 hex chars) */\n tokenLength?: number\n /** Cookie options */\n cookieOptions?: {\n httpOnly?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n secure?: boolean\n path?: string\n }\n}\n\n/**\n * Double-submit cookie CSRF protection middleware.\n *\n * On every request, sets a CSRF token cookie. For state-changing methods\n * (POST, PUT, PATCH, DELETE), validates that the request header matches\n * the cookie value.\n *\n * @example\n * ```ts\n * import { csrf } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middleware: [\n * cookieParser(),\n * csrf(),\n * // ... other middleware\n * ],\n * })\n * ```\n *\n * Client usage:\n * 1. Read the `_csrf` cookie value\n * 2. Send it in the `x-csrf-token` header on every mutating request\n */\nexport function csrf(options: CsrfOptions = {}) {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const cookieOpts = {\n httpOnly: true,\n sameSite: 'strict' as const,\n secure: process.env.NODE_ENV === 'production',\n path: '/',\n ...options.cookieOptions,\n }\n\n return (req: Request, res: Response, next: NextFunction) => {\n // Generate or reuse CSRF token\n const cookies = (req as any).cookies || {}\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomBytes(tokenLength).toString('hex')\n res.cookie(cookieName, token, cookieOpts)\n }\n\n // Skip validation for safe methods and ignored paths\n if (!protectedMethods.has(req.method.toUpperCase())) {\n return next()\n }\n\n if (ignorePaths.has(req.path)) {\n return next()\n }\n\n // Validate: header token must match cookie token\n const headerToken = req.headers[headerName] as string | undefined\n\n if (!headerToken || headerToken !== token) {\n return res.status(403).json({\n message: 'CSRF token mismatch',\n })\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,KAAK,UAAuB,EAAE,EAAE;CAC9C,MAAM,aAAa,QAAQ,UAAU;CACrC,MAAM,aAAa,QAAQ,UAAU;CACrC,MAAM,mBAAmB,IAAI,KAC1B,QAAQ,WAAW;EAAC;EAAQ;EAAO;EAAS;EAAS,EAAE,KAAK,MAAM,EAAE,aAAa,CAAC,CACpF;CACD,MAAM,cAAc,IAAI,IAAI,QAAQ,eAAe,EAAE,CAAC;CACtD,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,aAAa;EACjB,UAAU;EACV,UAAU;EACV,QAAQ,QAAQ,IAAI,aAAa;EACjC,MAAM;EACN,GAAG,QAAQ;EACZ;AAED,SAAQ,KAAc,KAAe,SAAuB;EAG1D,IAAI,SADa,IAAY,WAAW,EAAE,EACtB;AAEpB,MAAI,CAAC,OAAO;AACV,WAAQ,YAAY,YAAY,CAAC,SAAS,MAAM;AAChD,OAAI,OAAO,YAAY,OAAO,WAAW;;AAI3C,MAAI,CAAC,iBAAiB,IAAI,IAAI,OAAO,aAAa,CAAC,CACjD,QAAO,MAAM;AAGf,MAAI,YAAY,IAAI,IAAI,KAAK,CAC3B,QAAO,MAAM;EAIf,MAAM,cAAc,IAAI,QAAQ;AAEhC,MAAI,CAAC,eAAe,gBAAgB,MAClC,QAAO,IAAI,OAAO,IAAI,CAAC,KAAK,EAC1B,SAAS,uBACV,CAAC;AAGJ,QAAM"}
|
|
@@ -1,20 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
//#region src/http/middleware/error-handler.d.ts
|
|
5
|
-
/** Catch-all for unmatched routes */
|
|
6
|
-
declare function notFoundHandler(): (_req: Request, res: Response, _next: NextFunction) => void;
|
|
7
|
-
/**
|
|
8
|
-
* Global error handler.
|
|
9
|
-
*
|
|
10
|
-
* Default behavior strips error `details` from the response in production
|
|
11
|
-
* (NODE_ENV === 'production') so internal context (DB errors, validation
|
|
12
|
-
* issues, custom payloads) does not leak to clients. Apps that want to
|
|
13
|
-
* expose details in production — for client-facing field-level validation,
|
|
14
|
-
* for example — should pass their own `onError` to `bootstrap()` and decide
|
|
15
|
-
* the policy explicitly.
|
|
16
|
-
*/
|
|
17
|
-
declare function errorHandler(): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>> | undefined;
|
|
18
|
-
//#endregion
|
|
19
|
-
export { errorHandler, notFoundHandler };
|
|
20
|
-
//# sourceMappingURL=error-handler.d.mts.map
|
|
2
|
+
import { n as notFoundHandler, t as errorHandler } from "../../error-handler-Xud_3Lah.mjs";
|
|
3
|
+
export { errorHandler, notFoundHandler };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs
|
|
2
|
+
* @forinda/kickjs v4.0.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { createLogger } from "../../core/logger.mjs";
|
|
12
12
|
import { HttpException } from "../../core/errors.mjs";
|
|
13
|
-
import "../../core-
|
|
13
|
+
import "../../core-DBcoqPHM.mjs";
|
|
14
14
|
//#region src/http/middleware/error-handler.ts
|
|
15
15
|
const log = createLogger("ErrorHandler");
|
|
16
16
|
/** Catch-all for unmatched routes */
|
|
@@ -1,41 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
//#region src/http/middleware/helmet.d.ts
|
|
5
|
-
interface HelmetOptions {
|
|
6
|
-
/** Set Content-Security-Policy header (default: self-only policy) */
|
|
7
|
-
contentSecurityPolicy?: boolean | Record<string, string[]>;
|
|
8
|
-
/** Set X-Content-Type-Options: nosniff (default: true) */
|
|
9
|
-
noSniff?: boolean;
|
|
10
|
-
/** Set X-Frame-Options (default: 'DENY') */
|
|
11
|
-
frameguard?: false | 'DENY' | 'SAMEORIGIN';
|
|
12
|
-
/** Set Strict-Transport-Security (default: max-age=31536000; includeSubDomains) */
|
|
13
|
-
hsts?: false | {
|
|
14
|
-
maxAge?: number;
|
|
15
|
-
includeSubDomains?: boolean;
|
|
16
|
-
preload?: boolean;
|
|
17
|
-
};
|
|
18
|
-
/** Set X-DNS-Prefetch-Control (default: off) */
|
|
19
|
-
dnsPrefetch?: boolean;
|
|
20
|
-
/** Remove X-Powered-By header (default: true) */
|
|
21
|
-
hidePoweredBy?: boolean;
|
|
22
|
-
/** Set Referrer-Policy (default: 'no-referrer') */
|
|
23
|
-
referrerPolicy?: false | string;
|
|
24
|
-
/** Set X-XSS-Protection: 0 (default: true — disables legacy XSS auditor) */
|
|
25
|
-
xssFilter?: boolean;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Security headers middleware. Lightweight alternative to the `helmet` npm package
|
|
29
|
-
* with sensible defaults for API servers.
|
|
30
|
-
*
|
|
31
|
-
* @example
|
|
32
|
-
* ```ts
|
|
33
|
-
* bootstrap({
|
|
34
|
-
* middleware: [helmet(), requestId(), express.json()],
|
|
35
|
-
* })
|
|
36
|
-
* ```
|
|
37
|
-
*/
|
|
38
|
-
declare function helmet(options?: HelmetOptions): (req: Request, res: Response, next: NextFunction) => void;
|
|
39
|
-
//#endregion
|
|
40
|
-
export { HelmetOptions, helmet };
|
|
41
|
-
//# sourceMappingURL=helmet.d.mts.map
|
|
2
|
+
import { n as helmet, t as HelmetOptions } from "../../helmet-CaMbjzBG.mjs";
|
|
3
|
+
export { HelmetOptions, helmet };
|
|
@@ -1,56 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
//#region src/http/middleware/rate-limit.d.ts
|
|
5
|
-
interface RateLimitStore {
|
|
6
|
-
increment(key: string): Promise<{
|
|
7
|
-
totalHits: number;
|
|
8
|
-
resetTime: Date;
|
|
9
|
-
}>;
|
|
10
|
-
decrement(key: string): Promise<void>;
|
|
11
|
-
reset(key: string): Promise<void>;
|
|
12
|
-
}
|
|
13
|
-
interface RateLimitOptions {
|
|
14
|
-
/** Maximum number of requests per window (default: 100) */
|
|
15
|
-
max?: number;
|
|
16
|
-
/** Time window in milliseconds (default: 60_000) */
|
|
17
|
-
windowMs?: number;
|
|
18
|
-
/** Response message when rate limit is exceeded (default: 'Too Many Requests') */
|
|
19
|
-
message?: string;
|
|
20
|
-
/** HTTP status code when rate limit is exceeded (default: 429) */
|
|
21
|
-
statusCode?: number;
|
|
22
|
-
/** Function to generate the key for rate limiting (default: req.ip) */
|
|
23
|
-
keyGenerator?: (req: Request) => string;
|
|
24
|
-
/** Whether to send rate limit headers (default: true) */
|
|
25
|
-
headers?: boolean;
|
|
26
|
-
/** Custom store implementation (default: in-memory Map) */
|
|
27
|
-
store?: RateLimitStore;
|
|
28
|
-
/** Function to skip rate limiting for certain requests */
|
|
29
|
-
skip?: (req: Request) => boolean;
|
|
30
|
-
/** Paths to exclude from rate limiting */
|
|
31
|
-
skipPaths?: string[];
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Rate limiting middleware.
|
|
35
|
-
*
|
|
36
|
-
* Limits the number of requests a client can make within a time window.
|
|
37
|
-
* Uses an in-memory store by default, but accepts a custom store for
|
|
38
|
-
* distributed deployments (e.g. Redis).
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* ```ts
|
|
42
|
-
* import { rateLimit } from '@forinda/kickjs-http'
|
|
43
|
-
*
|
|
44
|
-
* bootstrap({
|
|
45
|
-
* modules,
|
|
46
|
-
* middleware: [
|
|
47
|
-
* rateLimit({ max: 100, windowMs: 60_000 }),
|
|
48
|
-
* // ... other middleware
|
|
49
|
-
* ],
|
|
50
|
-
* })
|
|
51
|
-
* ```
|
|
52
|
-
*/
|
|
53
|
-
declare function rateLimit(options?: RateLimitOptions): (req: Request, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
|
|
54
|
-
//#endregion
|
|
55
|
-
export { RateLimitOptions, RateLimitStore, rateLimit };
|
|
56
|
-
//# sourceMappingURL=rate-limit.d.mts.map
|
|
2
|
+
import { n as RateLimitStore, r as rateLimit, t as RateLimitOptions } from "../../rate-limit-DUwoICtI.mjs";
|
|
3
|
+
export { RateLimitOptions, RateLimitStore, rateLimit };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs
|
|
2
|
+
* @forinda/kickjs v4.0.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -59,7 +59,7 @@ var MemoryStore = class {
|
|
|
59
59
|
*
|
|
60
60
|
* @example
|
|
61
61
|
* ```ts
|
|
62
|
-
* import { rateLimit } from '@forinda/kickjs
|
|
62
|
+
* import { rateLimit } from '@forinda/kickjs'
|
|
63
63
|
*
|
|
64
64
|
* bootstrap({
|
|
65
65
|
* modules,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limit.mjs","names":[],"sources":["../../../src/http/middleware/rate-limit.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\n\nexport interface RateLimitStore {\n increment(key: string): Promise<{ totalHits: number; resetTime: Date }>\n decrement(key: string): Promise<void>\n reset(key: string): Promise<void>\n}\n\nexport interface RateLimitOptions {\n /** Maximum number of requests per window (default: 100) */\n max?: number\n /** Time window in milliseconds (default: 60_000) */\n windowMs?: number\n /** Response message when rate limit is exceeded (default: 'Too Many Requests') */\n message?: string\n /** HTTP status code when rate limit is exceeded (default: 429) */\n statusCode?: number\n /** Function to generate the key for rate limiting (default: req.ip) */\n keyGenerator?: (req: Request) => string\n /** Whether to send rate limit headers (default: true) */\n headers?: boolean\n /** Custom store implementation (default: in-memory Map) */\n store?: RateLimitStore\n /** Function to skip rate limiting for certain requests */\n skip?: (req: Request) => boolean\n /** Paths to exclude from rate limiting */\n skipPaths?: string[]\n}\n\ninterface MemoryStoreEntry {\n totalHits: number\n resetTime: Date\n}\n\nclass MemoryStore implements RateLimitStore {\n private hits = new Map<string, MemoryStoreEntry>()\n private cleanupTimer: ReturnType<typeof setInterval>\n\n constructor(private windowMs: number) {\n this.cleanupTimer = setInterval(() => this.cleanup(), windowMs)\n // Allow the process to exit without waiting for the timer\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref()\n }\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = this.hits.get(key)\n\n if (entry && entry.resetTime.getTime() > now) {\n entry.totalHits++\n return { totalHits: entry.totalHits, resetTime: entry.resetTime }\n }\n\n const resetTime = new Date(now + this.windowMs)\n const newEntry: MemoryStoreEntry = { totalHits: 1, resetTime }\n this.hits.set(key, newEntry)\n return { totalHits: 1, resetTime }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = this.hits.get(key)\n if (entry && entry.totalHits > 0) {\n entry.totalHits--\n }\n }\n\n async reset(key: string): Promise<void> {\n this.hits.delete(key)\n }\n\n private cleanup(): void {\n const now = Date.now()\n for (const [key, entry] of this.hits) {\n if (entry.resetTime.getTime() <= now) {\n this.hits.delete(key)\n }\n }\n }\n}\n\n/**\n * Rate limiting middleware.\n *\n * Limits the number of requests a client can make within a time window.\n * Uses an in-memory store by default, but accepts a custom store for\n * distributed deployments (e.g. Redis).\n *\n * @example\n * ```ts\n * import { rateLimit } from '@forinda/kickjs
|
|
1
|
+
{"version":3,"file":"rate-limit.mjs","names":[],"sources":["../../../src/http/middleware/rate-limit.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\n\nexport interface RateLimitStore {\n increment(key: string): Promise<{ totalHits: number; resetTime: Date }>\n decrement(key: string): Promise<void>\n reset(key: string): Promise<void>\n}\n\nexport interface RateLimitOptions {\n /** Maximum number of requests per window (default: 100) */\n max?: number\n /** Time window in milliseconds (default: 60_000) */\n windowMs?: number\n /** Response message when rate limit is exceeded (default: 'Too Many Requests') */\n message?: string\n /** HTTP status code when rate limit is exceeded (default: 429) */\n statusCode?: number\n /** Function to generate the key for rate limiting (default: req.ip) */\n keyGenerator?: (req: Request) => string\n /** Whether to send rate limit headers (default: true) */\n headers?: boolean\n /** Custom store implementation (default: in-memory Map) */\n store?: RateLimitStore\n /** Function to skip rate limiting for certain requests */\n skip?: (req: Request) => boolean\n /** Paths to exclude from rate limiting */\n skipPaths?: string[]\n}\n\ninterface MemoryStoreEntry {\n totalHits: number\n resetTime: Date\n}\n\nclass MemoryStore implements RateLimitStore {\n private hits = new Map<string, MemoryStoreEntry>()\n private cleanupTimer: ReturnType<typeof setInterval>\n\n constructor(private windowMs: number) {\n this.cleanupTimer = setInterval(() => this.cleanup(), windowMs)\n // Allow the process to exit without waiting for the timer\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref()\n }\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = this.hits.get(key)\n\n if (entry && entry.resetTime.getTime() > now) {\n entry.totalHits++\n return { totalHits: entry.totalHits, resetTime: entry.resetTime }\n }\n\n const resetTime = new Date(now + this.windowMs)\n const newEntry: MemoryStoreEntry = { totalHits: 1, resetTime }\n this.hits.set(key, newEntry)\n return { totalHits: 1, resetTime }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = this.hits.get(key)\n if (entry && entry.totalHits > 0) {\n entry.totalHits--\n }\n }\n\n async reset(key: string): Promise<void> {\n this.hits.delete(key)\n }\n\n private cleanup(): void {\n const now = Date.now()\n for (const [key, entry] of this.hits) {\n if (entry.resetTime.getTime() <= now) {\n this.hits.delete(key)\n }\n }\n }\n}\n\n/**\n * Rate limiting middleware.\n *\n * Limits the number of requests a client can make within a time window.\n * Uses an in-memory store by default, but accepts a custom store for\n * distributed deployments (e.g. Redis).\n *\n * @example\n * ```ts\n * import { rateLimit } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * middleware: [\n * rateLimit({ max: 100, windowMs: 60_000 }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function rateLimit(options: RateLimitOptions = {}) {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n const keyGenerator = options.keyGenerator ?? ((req: Request) => req.ip ?? '127.0.0.1')\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new MemoryStore(windowMs)\n const skip = options.skip\n const skipPaths = new Set(options.skipPaths ?? [])\n\n return async (req: Request, res: Response, next: NextFunction) => {\n // Skip if path is in the skip list\n if (skipPaths.has(req.path)) {\n return next()\n }\n\n // Skip if the skip function returns true\n if (skip && skip(req)) {\n return next()\n }\n\n const key = keyGenerator(req)\n const { totalHits, resetTime } = await store.increment(key)\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n res.setHeader('RateLimit-Limit', max)\n res.setHeader('RateLimit-Remaining', remaining)\n res.setHeader('RateLimit-Reset', Math.ceil(resetTime.getTime() / 1000))\n }\n\n if (totalHits > max) {\n return res.status(statusCode).json({ message })\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;;AAkCA,IAAM,cAAN,MAA4C;CAC1C,uBAAe,IAAI,KAA+B;CAClD;CAEA,YAAY,UAA0B;AAAlB,OAAA,WAAA;AAClB,OAAK,eAAe,kBAAkB,KAAK,SAAS,EAAE,SAAS;AAE/D,MAAI,KAAK,aAAa,MACpB,MAAK,aAAa,OAAO;;CAI7B,MAAM,UAAU,KAA8D;EAC5E,MAAM,MAAM,KAAK,KAAK;EACtB,MAAM,QAAQ,KAAK,KAAK,IAAI,IAAI;AAEhC,MAAI,SAAS,MAAM,UAAU,SAAS,GAAG,KAAK;AAC5C,SAAM;AACN,UAAO;IAAE,WAAW,MAAM;IAAW,WAAW,MAAM;IAAW;;EAGnE,MAAM,YAAY,IAAI,KAAK,MAAM,KAAK,SAAS;EAC/C,MAAM,WAA6B;GAAE,WAAW;GAAG;GAAW;AAC9D,OAAK,KAAK,IAAI,KAAK,SAAS;AAC5B,SAAO;GAAE,WAAW;GAAG;GAAW;;CAGpC,MAAM,UAAU,KAA4B;EAC1C,MAAM,QAAQ,KAAK,KAAK,IAAI,IAAI;AAChC,MAAI,SAAS,MAAM,YAAY,EAC7B,OAAM;;CAIV,MAAM,MAAM,KAA4B;AACtC,OAAK,KAAK,OAAO,IAAI;;CAGvB,UAAwB;EACtB,MAAM,MAAM,KAAK,KAAK;AACtB,OAAK,MAAM,CAAC,KAAK,UAAU,KAAK,KAC9B,KAAI,MAAM,UAAU,SAAS,IAAI,IAC/B,MAAK,KAAK,OAAO,IAAI;;;;;;;;;;;;;;;;;;;;;;;AA0B7B,SAAgB,UAAU,UAA4B,EAAE,EAAE;CACxD,MAAM,MAAM,QAAQ,OAAO;CAC3B,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,aAAa,QAAQ,cAAc;CACzC,MAAM,eAAe,QAAQ,kBAAkB,QAAiB,IAAI,MAAM;CAC1E,MAAM,cAAc,QAAQ,WAAW;CACvC,MAAM,QAAQ,QAAQ,SAAS,IAAI,YAAY,SAAS;CACxD,MAAM,OAAO,QAAQ;CACrB,MAAM,YAAY,IAAI,IAAI,QAAQ,aAAa,EAAE,CAAC;AAElD,QAAO,OAAO,KAAc,KAAe,SAAuB;AAEhE,MAAI,UAAU,IAAI,IAAI,KAAK,CACzB,QAAO,MAAM;AAIf,MAAI,QAAQ,KAAK,IAAI,CACnB,QAAO,MAAM;EAGf,MAAM,MAAM,aAAa,IAAI;EAC7B,MAAM,EAAE,WAAW,cAAc,MAAM,MAAM,UAAU,IAAI;EAC3D,MAAM,YAAY,KAAK,IAAI,GAAG,MAAM,UAAU;AAE9C,MAAI,aAAa;AACf,OAAI,UAAU,mBAAmB,IAAI;AACrC,OAAI,UAAU,uBAAuB,UAAU;AAC/C,OAAI,UAAU,mBAAmB,KAAK,KAAK,UAAU,SAAS,GAAG,IAAK,CAAC;;AAGzE,MAAI,YAAY,IACd,QAAO,IAAI,OAAO,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC;AAGjD,QAAM"}
|
|
@@ -1,10 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
//#region src/http/middleware/request-id.d.ts
|
|
5
|
-
declare const REQUEST_ID_HEADER = "x-request-id";
|
|
6
|
-
/** Middleware that generates or propagates a unique request ID */
|
|
7
|
-
declare function requestId(): (req: Request, res: Response, next: NextFunction) => void;
|
|
8
|
-
//#endregion
|
|
9
|
-
export { REQUEST_ID_HEADER, requestId };
|
|
10
|
-
//# sourceMappingURL=request-id.d.mts.map
|
|
2
|
+
import { n as requestId, t as REQUEST_ID_HEADER } from "../../request-id-BgglvZHN.mjs";
|
|
3
|
+
export { REQUEST_ID_HEADER, requestId };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs
|
|
2
|
+
* @forinda/kickjs v4.0.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -11,10 +11,19 @@
|
|
|
11
11
|
import { randomUUID } from "node:crypto";
|
|
12
12
|
//#region src/http/middleware/request-id.ts
|
|
13
13
|
const REQUEST_ID_HEADER = "x-request-id";
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* Middleware that generates or propagates a unique request ID.
|
|
16
|
+
*
|
|
17
|
+
* Idempotent: if `req.requestId` is already set (e.g. by
|
|
18
|
+
* `requestScopeMiddleware` earlier in the pipeline), this middleware reuses
|
|
19
|
+
* it instead of generating a divergent second value. Keeps the
|
|
20
|
+
* X-Request-Id response header, the ALS store's `requestId`, and
|
|
21
|
+
* `RequestContext.requestId` in agreement for every request, regardless of
|
|
22
|
+
* mounting order.
|
|
23
|
+
*/
|
|
15
24
|
function requestId() {
|
|
16
25
|
return (req, res, next) => {
|
|
17
|
-
const id = req.headers["x-request-id"] || randomUUID();
|
|
26
|
+
const id = req.requestId || req.headers["x-request-id"] || randomUUID();
|
|
18
27
|
req.requestId = id;
|
|
19
28
|
res.setHeader(REQUEST_ID_HEADER, id);
|
|
20
29
|
next();
|