@forinda/kickjs 5.3.0 → 5.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-C1w_xt08.d.mts → adapter-0r2uRCD3.d.mts} +2 -2
- package/dist/{adapter-C1w_xt08.d.mts.map → adapter-0r2uRCD3.d.mts.map} +1 -1
- package/dist/app-module-CzlIIjO3.d.mts +92 -0
- package/dist/app-module-CzlIIjO3.d.mts.map +1 -0
- package/dist/{application-BTRI4aBd.d.mts → application-CaEYca9E.d.mts} +34 -7
- package/dist/application-CaEYca9E.d.mts.map +1 -0
- package/dist/application-Zt956jNS.mjs +12 -0
- package/dist/application-Zt956jNS.mjs.map +1 -0
- package/dist/bootstrap-CmFQq1ar.mjs +12 -0
- package/dist/{bootstrap-kPcmbbWe.mjs.map → bootstrap-CmFQq1ar.mjs.map} +1 -1
- package/dist/{bootstrap-B4YrBipl.d.mts → bootstrap-Db8k2-21.d.mts} +2 -2
- package/dist/{bootstrap-B4YrBipl.d.mts.map → bootstrap-Db8k2-21.d.mts.map} +1 -1
- package/dist/config/index.mjs +2 -4
- package/dist/config-DDz5LuWw.mjs +12 -0
- package/dist/{config-DxEREQmR.mjs.map → config-DDz5LuWw.mjs.map} +1 -1
- package/dist/container-DrioVLNv.mjs +12 -0
- package/dist/{container-SMnB5yeT.mjs.map → container-DrioVLNv.mjs.map} +1 -1
- package/dist/context-B4BeGq1B.mjs +12 -0
- package/dist/context-B4BeGq1B.mjs.map +1 -0
- package/dist/{context-Ymvv-85x.d.mts → context-BAdAV-zO.d.mts} +48 -11
- package/dist/context-BAdAV-zO.d.mts.map +1 -0
- package/dist/{context-decorator-Bca_BoRK.d.mts → context-decorator-BgdDd-6X.d.mts} +19 -4
- package/dist/{context-decorator-Bca_BoRK.d.mts.map → context-decorator-BgdDd-6X.d.mts.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +2 -2
- package/dist/core/app-module.d.mts +2 -2
- package/dist/core/app-module.mjs +2 -2
- package/dist/core/cache.mjs +2 -103
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.mjs +2 -3
- package/dist/core/cron.mjs +2 -32
- package/dist/core/cron.mjs.map +1 -1
- package/dist/core/decorators.mjs +2 -285
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +2 -110
- package/dist/core/errors.mjs.map +1 -1
- package/dist/core/interfaces.mjs +2 -53
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.mjs +2 -207
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.mjs +2 -35
- package/dist/core/path.mjs.map +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +2 -2
- package/dist/core/reactivity.mjs +2 -179
- package/dist/core/reactivity.mjs.map +1 -1
- package/dist/core-MvABl8Cl.mjs +13 -0
- package/dist/core-MvABl8Cl.mjs.map +1 -0
- package/dist/env-CObTuGZ3.mjs +12 -0
- package/dist/{env-C4Yr6nN8.mjs.map → env-CObTuGZ3.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -3
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -3
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -3
- package/dist/http/middleware/cors.mjs +2 -73
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.mjs +2 -62
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -54
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.mjs +2 -41
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -91
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.mjs +2 -25
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -39
- package/dist/http/middleware/request-logger.mjs.map +1 -1
- package/dist/http/middleware/session.mjs +2 -167
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -98
- package/dist/http/middleware/spa.mjs.map +1 -1
- package/dist/http/middleware/upload.mjs +2 -181
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.mjs +2 -68
- package/dist/http/middleware/validate.mjs.map +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -56
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.mjs +2 -3
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -105
- package/dist/http/router-builder.mjs.map +1 -1
- package/dist/{index-DvZfBNIf.d.mts → index-D-Wb23e6.d.mts} +264 -86
- package/dist/index-D-Wb23e6.d.mts.map +1 -0
- package/dist/index.d.mts +12 -12
- package/dist/index.mjs +2 -171
- package/dist/index.mjs.map +1 -1
- package/dist/metadata-WTmSU6Sf.mjs +12 -0
- package/dist/{metadata-CdYaU-XM.mjs.map → metadata-WTmSU6Sf.mjs.map} +1 -1
- package/dist/{plugin-DF8Xfv9Z.d.mts → plugin-JMkG7soG.d.mts} +102 -8
- package/dist/plugin-JMkG7soG.d.mts.map +1 -0
- package/dist/query-BmO0aBf6.mjs +12 -0
- package/dist/{query-nAYUgagU.mjs.map → query-BmO0aBf6.mjs.map} +1 -1
- package/dist/{router-builder-C7sXk_FG.d.mts → router-builder-CaQ629tw.d.mts} +2 -2
- package/dist/{router-builder-C7sXk_FG.d.mts.map → router-builder-CaQ629tw.d.mts.map} +1 -1
- package/dist/{spa-e4FIS2RB.d.mts → spa-CreyQc4N.d.mts} +2 -2
- package/dist/{spa-e4FIS2RB.d.mts.map → spa-CreyQc4N.d.mts.map} +1 -1
- package/dist/{views-DkNp9JJs.d.mts → views-1e3jQr5C.d.mts} +4 -4
- package/dist/{views-DkNp9JJs.d.mts.map → views-1e3jQr5C.d.mts.map} +1 -1
- package/package.json +2 -2
- package/dist/app-module-D6zL_V5S.d.mts +0 -50
- package/dist/app-module-D6zL_V5S.d.mts.map +0 -1
- package/dist/application-BTRI4aBd.d.mts.map +0 -1
- package/dist/application-Cna_2gex.mjs +0 -574
- package/dist/application-Cna_2gex.mjs.map +0 -1
- package/dist/bootstrap-kPcmbbWe.mjs +0 -195
- package/dist/config-DxEREQmR.mjs +0 -135
- package/dist/container-SMnB5yeT.mjs +0 -897
- package/dist/context-B0B3WQft.mjs +0 -348
- package/dist/context-B0B3WQft.mjs.map +0 -1
- package/dist/context-Ymvv-85x.d.mts.map +0 -1
- package/dist/core--a4XflX7.mjs +0 -820
- package/dist/core--a4XflX7.mjs.map +0 -1
- package/dist/env-C4Yr6nN8.mjs +0 -137
- package/dist/index-DvZfBNIf.d.mts.map +0 -1
- package/dist/metadata-CdYaU-XM.mjs +0 -76
- package/dist/plugin-DF8Xfv9Z.d.mts.map +0 -1
- package/dist/query-nAYUgagU.mjs +0 -164
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,57 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
import { HttpException } from "../../core/errors.mjs";
|
|
13
|
-
import "../../core--a4XflX7.mjs";
|
|
14
|
-
//#region src/http/middleware/error-handler.ts
|
|
15
|
-
const log = createLogger("ErrorHandler");
|
|
16
|
-
/** Catch-all for unmatched routes */
|
|
17
|
-
function notFoundHandler() {
|
|
18
|
-
return (_req, res, _next) => {
|
|
19
|
-
res.status(404).json({ message: "Not Found" });
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Global error handler.
|
|
24
|
-
*
|
|
25
|
-
* Default behavior strips error `details` from the response in production
|
|
26
|
-
* (NODE_ENV === 'production') so internal context (DB errors, validation
|
|
27
|
-
* issues, custom payloads) does not leak to clients. Apps that want to
|
|
28
|
-
* expose details in production — for client-facing field-level validation,
|
|
29
|
-
* for example — should pass their own `onError` to `bootstrap()` and decide
|
|
30
|
-
* the policy explicitly.
|
|
31
|
-
*/
|
|
32
|
-
function errorHandler() {
|
|
33
|
-
const isProduction = process.env.NODE_ENV === "production";
|
|
34
|
-
return (err, req, res, _next) => {
|
|
35
|
-
if (res.headersSent) {
|
|
36
|
-
log.warn(`Error after headers sent: ${err?.message || "Unknown"}`);
|
|
37
|
-
return;
|
|
38
|
-
}
|
|
39
|
-
if (err?.name === "ZodError") {
|
|
40
|
-
const firstIssue = err.issues?.[0];
|
|
41
|
-
return res.status(422).json({
|
|
42
|
-
message: firstIssue?.message || "Validation failed",
|
|
43
|
-
...isProduction ? {} : { errors: err.issues }
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
if (err instanceof HttpException) {
|
|
47
|
-
if (err.status >= 500) log.error(err, err.message);
|
|
48
|
-
if (err.headers) for (const [k, v] of Object.entries(err.headers)) res.setHeader(k, v);
|
|
49
|
-
const exposeDetails = !isProduction && err.details !== void 0;
|
|
50
|
-
return res.status(err.status).json({
|
|
51
|
-
message: err.message,
|
|
52
|
-
...exposeDetails ? { errors: err.details } : {}
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
const status = err.status || err.statusCode || 500;
|
|
56
|
-
log.error(err, `${req.method} ${req.originalUrl} — ${err.message || "Unhandled error"}`);
|
|
57
|
-
const message = status === 500 ? "Internal Server Error" : err.message || "Error";
|
|
58
|
-
res.status(status).json({ message });
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
//#endregion
|
|
62
|
-
export { errorHandler, notFoundHandler };
|
|
63
|
-
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import"../../core-MvABl8Cl.mjs";import{HttpException}from"../../core/errors.mjs";const log=createLogger(`ErrorHandler`);function notFoundHandler(){return(_req,res,_next)=>{res.status(404).json({message:`Not Found`})}}function errorHandler(){let isProduction=process.env.NODE_ENV===`production`;return(err,req,res,_next)=>{if(res.headersSent){log.warn(`Error after headers sent: ${err?.message||`Unknown`}`);return}if(err?.name===`ZodError`){let firstIssue=err.issues?.[0];return res.status(422).json({message:firstIssue?.message||`Validation failed`,...isProduction?{}:{errors:err.issues}})}if(err instanceof HttpException){if(err.status>=500&&log.error(err,err.message),err.headers)for(let[k,v]of Object.entries(err.headers))res.setHeader(k,v);let exposeDetails=!isProduction&&err.details!==void 0;return res.status(err.status).json({message:err.message,...exposeDetails?{errors:err.details}:{}})}let status=err.status||err.statusCode||500;log.error(err,`${req.method} ${req.originalUrl} — ${err.message||`Unhandled error`}`);let message=status===500?`Internal Server Error`:err.message||`Error`;res.status(status).json({message})}}export{errorHandler,notFoundHandler};
|
|
64
12
|
//# sourceMappingURL=error-handler.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.mjs","names":[],"sources":["../../../src/http/middleware/error-handler.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\nimport { HttpException, createLogger } from '../../core'\n\nconst log = createLogger('ErrorHandler')\n\n/** Catch-all for unmatched routes */\nexport function notFoundHandler() {\n return (_req: Request, res: Response, _next: NextFunction) => {\n res.status(404).json({ message: 'Not Found' })\n }\n}\n\n/**\n * Global error handler.\n *\n * Default behavior strips error `details` from the response in production\n * (NODE_ENV === 'production') so internal context (DB errors, validation\n * issues, custom payloads) does not leak to clients. Apps that want to\n * expose details in production — for client-facing field-level validation,\n * for example — should pass their own `onError` to `bootstrap()` and decide\n * the policy explicitly.\n */\nexport function errorHandler() {\n const isProduction = process.env.NODE_ENV === 'production'\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Don't write after headers are already sent\n if (res.headersSent) {\n log.warn(`Error after headers sent: ${err?.message || 'Unknown'}`)\n return\n }\n\n // Zod validation errors\n if (err?.name === 'ZodError') {\n const firstIssue = err.issues?.[0]\n return res.status(422).json({\n message: firstIssue?.message || 'Validation failed',\n ...(isProduction ? {} : { errors: err.issues }),\n })\n }\n\n // HttpException (expected application errors)\n if (err instanceof HttpException) {\n if (err.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n const exposeDetails = !isProduction && err.details !== undefined\n return res.status(err.status).json({\n message: err.message,\n ...(exposeDetails ? { errors: err.details } : {}),\n })\n }\n\n // Unexpected errors — always log\n const status = err.status || err.statusCode || 500\n log.error(err, `${req.method} ${req.originalUrl} — ${err.message || 'Unhandled error'}`)\n const message = status === 500 ? 'Internal Server Error' : err.message || 'Error'\n res.status(status).json({ message })\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"error-handler.mjs","names":[],"sources":["../../../src/http/middleware/error-handler.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\nimport { HttpException, createLogger } from '../../core'\n\nconst log = createLogger('ErrorHandler')\n\n/** Catch-all for unmatched routes */\nexport function notFoundHandler() {\n return (_req: Request, res: Response, _next: NextFunction) => {\n res.status(404).json({ message: 'Not Found' })\n }\n}\n\n/**\n * Global error handler.\n *\n * Default behavior strips error `details` from the response in production\n * (NODE_ENV === 'production') so internal context (DB errors, validation\n * issues, custom payloads) does not leak to clients. Apps that want to\n * expose details in production — for client-facing field-level validation,\n * for example — should pass their own `onError` to `bootstrap()` and decide\n * the policy explicitly.\n */\nexport function errorHandler() {\n const isProduction = process.env.NODE_ENV === 'production'\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Don't write after headers are already sent\n if (res.headersSent) {\n log.warn(`Error after headers sent: ${err?.message || 'Unknown'}`)\n return\n }\n\n // Zod validation errors\n if (err?.name === 'ZodError') {\n const firstIssue = err.issues?.[0]\n return res.status(422).json({\n message: firstIssue?.message || 'Validation failed',\n ...(isProduction ? {} : { errors: err.issues }),\n })\n }\n\n // HttpException (expected application errors)\n if (err instanceof HttpException) {\n if (err.status >= 500) {\n log.error(err, err.message)\n }\n if (err.headers) {\n for (const [k, v] of Object.entries(err.headers)) {\n res.setHeader(k, v)\n }\n }\n const exposeDetails = !isProduction && err.details !== undefined\n return res.status(err.status).json({\n message: err.message,\n ...(exposeDetails ? { errors: err.details } : {}),\n })\n }\n\n // Unexpected errors — always log\n const status = err.status || err.statusCode || 500\n log.error(err, `${req.method} ${req.originalUrl} — ${err.message || 'Unhandled error'}`)\n const message = status === 500 ? 'Internal Server Error' : err.message || 'Error'\n res.status(status).json({ message })\n }\n}\n"],"mappings":";;;;;;;;;;iIAGA,MAAM,IAAM,aAAa,eAAe,CAGxC,SAAgB,iBAAkB,CAChC,OAAQ,KAAe,IAAe,QAAwB,CAC5D,IAAI,OAAO,IAAI,CAAC,KAAK,CAAE,QAAS,YAAa,CAAC,EAclD,SAAgB,cAAe,CAC7B,IAAM,aAAe,QAAQ,IAAI,WAAa,aAC9C,OAAQ,IAAU,IAAc,IAAe,QAAwB,CAErE,GAAI,IAAI,YAAa,CACnB,IAAI,KAAK,6BAA6B,KAAK,SAAW,YAAY,CAClE,OAIF,GAAI,KAAK,OAAS,WAAY,CAC5B,IAAM,WAAa,IAAI,SAAS,GAChC,OAAO,IAAI,OAAO,IAAI,CAAC,KAAK,CAC1B,QAAS,YAAY,SAAW,oBAChC,GAAI,aAAe,EAAE,CAAG,CAAE,OAAQ,IAAI,OAAQ,CAC/C,CAAC,CAIJ,GAAI,eAAe,cAAe,CAIhC,GAHI,IAAI,QAAU,KAChB,IAAI,MAAM,IAAK,IAAI,QAAQ,CAEzB,IAAI,QACN,IAAK,GAAM,CAAC,EAAG,KAAM,OAAO,QAAQ,IAAI,QAAQ,CAC9C,IAAI,UAAU,EAAG,EAAE,CAGvB,IAAM,cAAgB,CAAC,cAAgB,IAAI,UAAY,IAAA,GACvD,OAAO,IAAI,OAAO,IAAI,OAAO,CAAC,KAAK,CACjC,QAAS,IAAI,QACb,GAAI,cAAgB,CAAE,OAAQ,IAAI,QAAS,CAAG,EAAE,CACjD,CAAC,CAIJ,IAAM,OAAS,IAAI,QAAU,IAAI,YAAc,IAC/C,IAAI,MAAM,IAAK,GAAG,IAAI,OAAO,GAAG,IAAI,YAAY,KAAK,IAAI,SAAW,oBAAoB,CACxF,IAAM,QAAU,SAAW,IAAM,wBAA0B,IAAI,SAAW,QAC1E,IAAI,OAAO,OAAO,CAAC,KAAK,CAAE,QAAS,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,44 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Security headers middleware. Lightweight alternative to the `helmet` npm package
|
|
14
|
-
* with sensible defaults for API servers.
|
|
15
|
-
*
|
|
16
|
-
* @example
|
|
17
|
-
* ```ts
|
|
18
|
-
* bootstrap({
|
|
19
|
-
* middleware: [helmet(), requestId(), express.json()],
|
|
20
|
-
* })
|
|
21
|
-
* ```
|
|
22
|
-
*/
|
|
23
|
-
function helmet(options = {}) {
|
|
24
|
-
const { noSniff = true, frameguard = "DENY", hsts = {
|
|
25
|
-
maxAge: 31536e3,
|
|
26
|
-
includeSubDomains: true
|
|
27
|
-
}, dnsPrefetch = false, hidePoweredBy = true, referrerPolicy = "no-referrer", xssFilter = true, contentSecurityPolicy = false } = options;
|
|
28
|
-
return (req, res, next) => {
|
|
29
|
-
if (hidePoweredBy) res.removeHeader("X-Powered-By");
|
|
30
|
-
if (noSniff) res.setHeader("X-Content-Type-Options", "nosniff");
|
|
31
|
-
if (frameguard) res.setHeader("X-Frame-Options", frameguard);
|
|
32
|
-
if (xssFilter) res.setHeader("X-XSS-Protection", "0");
|
|
33
|
-
if (referrerPolicy) res.setHeader("Referrer-Policy", referrerPolicy);
|
|
34
|
-
if (!dnsPrefetch) res.setHeader("X-DNS-Prefetch-Control", "off");
|
|
35
|
-
if (hsts) {
|
|
36
|
-
let value = `max-age=${hsts.maxAge ?? 31536e3}`;
|
|
37
|
-
if (hsts.includeSubDomains) value += "; includeSubDomains";
|
|
38
|
-
if (hsts.preload) value += "; preload";
|
|
39
|
-
res.setHeader("Strict-Transport-Security", value);
|
|
40
|
-
}
|
|
41
|
-
if (contentSecurityPolicy) {
|
|
42
|
-
const policy = typeof contentSecurityPolicy === "object" ? Object.entries(contentSecurityPolicy).map(([key, values]) => `${key} ${values.join(" ")}`).join("; ") : "default-src 'self'";
|
|
43
|
-
res.setHeader("Content-Security-Policy", policy);
|
|
44
|
-
}
|
|
45
|
-
next();
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
//#endregion
|
|
49
|
-
export { helmet };
|
|
50
|
-
|
|
11
|
+
function helmet(options={}){let{noSniff=!0,frameguard=`DENY`,hsts={maxAge:31536e3,includeSubDomains:!0},dnsPrefetch=!1,hidePoweredBy=!0,referrerPolicy=`no-referrer`,xssFilter=!0,contentSecurityPolicy=!1}=options;return(req,res,next)=>{if(hidePoweredBy&&res.removeHeader(`X-Powered-By`),noSniff&&res.setHeader(`X-Content-Type-Options`,`nosniff`),frameguard&&res.setHeader(`X-Frame-Options`,frameguard),xssFilter&&res.setHeader(`X-XSS-Protection`,`0`),referrerPolicy&&res.setHeader(`Referrer-Policy`,referrerPolicy),dnsPrefetch||res.setHeader(`X-DNS-Prefetch-Control`,`off`),hsts){let value=`max-age=${hsts.maxAge??31536e3}`;hsts.includeSubDomains&&(value+=`; includeSubDomains`),hsts.preload&&(value+=`; preload`),res.setHeader(`Strict-Transport-Security`,value)}if(contentSecurityPolicy){let policy=typeof contentSecurityPolicy==`object`?Object.entries(contentSecurityPolicy).map(([key,values])=>`${key} ${values.join(` `)}`).join(`; `):`default-src 'self'`;res.setHeader(`Content-Security-Policy`,policy)}next()}}export{helmet};
|
|
51
12
|
//# sourceMappingURL=helmet.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helmet.mjs","names":[],"sources":["../../../src/http/middleware/helmet.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\n\nexport interface HelmetOptions {\n /** Set Content-Security-Policy header (default: self-only policy) */\n contentSecurityPolicy?: boolean | Record<string, string[]>\n /** Set X-Content-Type-Options: nosniff (default: true) */\n noSniff?: boolean\n /** Set X-Frame-Options (default: 'DENY') */\n frameguard?: false | 'DENY' | 'SAMEORIGIN'\n /** Set Strict-Transport-Security (default: max-age=31536000; includeSubDomains) */\n hsts?: false | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean }\n /** Set X-DNS-Prefetch-Control (default: off) */\n dnsPrefetch?: boolean\n /** Remove X-Powered-By header (default: true) */\n hidePoweredBy?: boolean\n /** Set Referrer-Policy (default: 'no-referrer') */\n referrerPolicy?: false | string\n /** Set X-XSS-Protection: 0 (default: true — disables legacy XSS auditor) */\n xssFilter?: boolean\n}\n\n/**\n * Security headers middleware. Lightweight alternative to the `helmet` npm package\n * with sensible defaults for API servers.\n *\n * @example\n * ```ts\n * bootstrap({\n * middleware: [helmet(), requestId(), express.json()],\n * })\n * ```\n */\nexport function helmet(options: HelmetOptions = {}) {\n const {\n noSniff = true,\n frameguard = 'DENY',\n hsts = { maxAge: 31536000, includeSubDomains: true },\n dnsPrefetch = false,\n hidePoweredBy = true,\n referrerPolicy = 'no-referrer',\n xssFilter = true,\n contentSecurityPolicy = false,\n } = options\n\n return (req: Request, res: Response, next: NextFunction) => {\n if (hidePoweredBy) res.removeHeader('X-Powered-By')\n if (noSniff) res.setHeader('X-Content-Type-Options', 'nosniff')\n if (frameguard) res.setHeader('X-Frame-Options', frameguard)\n if (xssFilter) res.setHeader('X-XSS-Protection', '0')\n if (referrerPolicy) res.setHeader('Referrer-Policy', referrerPolicy)\n if (!dnsPrefetch) res.setHeader('X-DNS-Prefetch-Control', 'off')\n\n if (hsts) {\n const maxAge = hsts.maxAge ?? 31536000\n let value = `max-age=${maxAge}`\n if (hsts.includeSubDomains) value += '; includeSubDomains'\n if (hsts.preload) value += '; preload'\n res.setHeader('Strict-Transport-Security', value)\n }\n\n if (contentSecurityPolicy) {\n const policy =\n typeof contentSecurityPolicy === 'object'\n ? Object.entries(contentSecurityPolicy)\n .map(([key, values]) => `${key} ${values.join(' ')}`)\n .join('; ')\n : \"default-src 'self'\"\n res.setHeader('Content-Security-Policy', policy)\n }\n\n next()\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"helmet.mjs","names":[],"sources":["../../../src/http/middleware/helmet.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\n\nexport interface HelmetOptions {\n /** Set Content-Security-Policy header (default: self-only policy) */\n contentSecurityPolicy?: boolean | Record<string, string[]>\n /** Set X-Content-Type-Options: nosniff (default: true) */\n noSniff?: boolean\n /** Set X-Frame-Options (default: 'DENY') */\n frameguard?: false | 'DENY' | 'SAMEORIGIN'\n /** Set Strict-Transport-Security (default: max-age=31536000; includeSubDomains) */\n hsts?: false | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean }\n /** Set X-DNS-Prefetch-Control (default: off) */\n dnsPrefetch?: boolean\n /** Remove X-Powered-By header (default: true) */\n hidePoweredBy?: boolean\n /** Set Referrer-Policy (default: 'no-referrer') */\n referrerPolicy?: false | string\n /** Set X-XSS-Protection: 0 (default: true — disables legacy XSS auditor) */\n xssFilter?: boolean\n}\n\n/**\n * Security headers middleware. Lightweight alternative to the `helmet` npm package\n * with sensible defaults for API servers.\n *\n * @example\n * ```ts\n * bootstrap({\n * middleware: [helmet(), requestId(), express.json()],\n * })\n * ```\n */\nexport function helmet(options: HelmetOptions = {}) {\n const {\n noSniff = true,\n frameguard = 'DENY',\n hsts = { maxAge: 31536000, includeSubDomains: true },\n dnsPrefetch = false,\n hidePoweredBy = true,\n referrerPolicy = 'no-referrer',\n xssFilter = true,\n contentSecurityPolicy = false,\n } = options\n\n return (req: Request, res: Response, next: NextFunction) => {\n if (hidePoweredBy) res.removeHeader('X-Powered-By')\n if (noSniff) res.setHeader('X-Content-Type-Options', 'nosniff')\n if (frameguard) res.setHeader('X-Frame-Options', frameguard)\n if (xssFilter) res.setHeader('X-XSS-Protection', '0')\n if (referrerPolicy) res.setHeader('Referrer-Policy', referrerPolicy)\n if (!dnsPrefetch) res.setHeader('X-DNS-Prefetch-Control', 'off')\n\n if (hsts) {\n const maxAge = hsts.maxAge ?? 31536000\n let value = `max-age=${maxAge}`\n if (hsts.includeSubDomains) value += '; includeSubDomains'\n if (hsts.preload) value += '; preload'\n res.setHeader('Strict-Transport-Security', value)\n }\n\n if (contentSecurityPolicy) {\n const policy =\n typeof contentSecurityPolicy === 'object'\n ? Object.entries(contentSecurityPolicy)\n .map(([key, values]) => `${key} ${values.join(' ')}`)\n .join('; ')\n : \"default-src 'self'\"\n res.setHeader('Content-Security-Policy', policy)\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;AAgCA,SAAgB,OAAO,QAAyB,EAAE,CAAE,CAClD,GAAM,CACJ,QAAU,GACV,WAAa,OACb,KAAO,CAAE,OAAQ,QAAU,kBAAmB,GAAM,CACpD,YAAc,GACd,cAAgB,GAChB,eAAiB,cACjB,UAAY,GACZ,sBAAwB,IACtB,QAEJ,OAAQ,IAAc,IAAe,OAAuB,CAQ1D,GAPI,eAAe,IAAI,aAAa,eAAe,CAC/C,SAAS,IAAI,UAAU,yBAA0B,UAAU,CAC3D,YAAY,IAAI,UAAU,kBAAmB,WAAW,CACxD,WAAW,IAAI,UAAU,mBAAoB,IAAI,CACjD,gBAAgB,IAAI,UAAU,kBAAmB,eAAe,CAC/D,aAAa,IAAI,UAAU,yBAA0B,MAAM,CAE5D,KAAM,CAER,IAAI,MAAQ,WADG,KAAK,QAAU,UAE1B,KAAK,oBAAmB,OAAS,uBACjC,KAAK,UAAS,OAAS,aAC3B,IAAI,UAAU,4BAA6B,MAAM,CAGnD,GAAI,sBAAuB,CACzB,IAAM,OACJ,OAAO,uBAA0B,SAC7B,OAAO,QAAQ,sBAAsB,CAClC,KAAK,CAAC,IAAK,UAAY,GAAG,IAAI,GAAG,OAAO,KAAK,IAAI,GAAG,CACpD,KAAK,KAAK,CACb,qBACN,IAAI,UAAU,0BAA2B,OAAO,CAGlD,MAAM"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,94 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
|
|
12
|
-
var MemoryStore = class {
|
|
13
|
-
hits = /* @__PURE__ */ new Map();
|
|
14
|
-
cleanupTimer;
|
|
15
|
-
constructor(windowMs) {
|
|
16
|
-
this.windowMs = windowMs;
|
|
17
|
-
this.cleanupTimer = setInterval(() => this.cleanup(), windowMs);
|
|
18
|
-
if (this.cleanupTimer.unref) this.cleanupTimer.unref();
|
|
19
|
-
}
|
|
20
|
-
async increment(key) {
|
|
21
|
-
const now = Date.now();
|
|
22
|
-
const entry = this.hits.get(key);
|
|
23
|
-
if (entry && entry.resetTime.getTime() > now) {
|
|
24
|
-
entry.totalHits++;
|
|
25
|
-
return {
|
|
26
|
-
totalHits: entry.totalHits,
|
|
27
|
-
resetTime: entry.resetTime
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
const resetTime = new Date(now + this.windowMs);
|
|
31
|
-
const newEntry = {
|
|
32
|
-
totalHits: 1,
|
|
33
|
-
resetTime
|
|
34
|
-
};
|
|
35
|
-
this.hits.set(key, newEntry);
|
|
36
|
-
return {
|
|
37
|
-
totalHits: 1,
|
|
38
|
-
resetTime
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
async decrement(key) {
|
|
42
|
-
const entry = this.hits.get(key);
|
|
43
|
-
if (entry && entry.totalHits > 0) entry.totalHits--;
|
|
44
|
-
}
|
|
45
|
-
async reset(key) {
|
|
46
|
-
this.hits.delete(key);
|
|
47
|
-
}
|
|
48
|
-
cleanup() {
|
|
49
|
-
const now = Date.now();
|
|
50
|
-
for (const [key, entry] of this.hits) if (entry.resetTime.getTime() <= now) this.hits.delete(key);
|
|
51
|
-
}
|
|
52
|
-
};
|
|
53
|
-
/**
|
|
54
|
-
* Rate limiting middleware.
|
|
55
|
-
*
|
|
56
|
-
* Limits the number of requests a client can make within a time window.
|
|
57
|
-
* Uses an in-memory store by default, but accepts a custom store for
|
|
58
|
-
* distributed deployments (e.g. Redis).
|
|
59
|
-
*
|
|
60
|
-
* @example
|
|
61
|
-
* ```ts
|
|
62
|
-
* import { rateLimit } from '@forinda/kickjs'
|
|
63
|
-
*
|
|
64
|
-
* bootstrap({
|
|
65
|
-
* modules,
|
|
66
|
-
* middleware: [
|
|
67
|
-
* rateLimit({ max: 100, windowMs: 60_000 }),
|
|
68
|
-
* // ... other middleware
|
|
69
|
-
* ],
|
|
70
|
-
* })
|
|
71
|
-
* ```
|
|
72
|
-
*/
|
|
73
|
-
function rateLimit(options = {}) {
|
|
74
|
-
const max = options.max ?? 100;
|
|
75
|
-
const windowMs = options.windowMs ?? 6e4;
|
|
76
|
-
const message = options.message ?? "Too Many Requests";
|
|
77
|
-
const statusCode = options.statusCode ?? 429;
|
|
78
|
-
const keyGenerator = options.keyGenerator ?? ((req) => req.ip ?? "127.0.0.1");
|
|
79
|
-
const sendHeaders = options.headers ?? true;
|
|
80
|
-
const store = options.store ?? new MemoryStore(windowMs);
|
|
81
|
-
const skip = options.skip;
|
|
82
|
-
const skipPaths = new Set(options.skipPaths ?? []);
|
|
83
|
-
return async (req, res, next) => {
|
|
84
|
-
if (skipPaths.has(req.path)) return next();
|
|
85
|
-
if (skip && skip(req)) return next();
|
|
86
|
-
const key = keyGenerator(req);
|
|
87
|
-
const { totalHits, resetTime } = await store.increment(key);
|
|
88
|
-
const remaining = Math.max(0, max - totalHits);
|
|
89
|
-
if (sendHeaders) {
|
|
90
|
-
res.setHeader("RateLimit-Limit", max);
|
|
91
|
-
res.setHeader("RateLimit-Remaining", remaining);
|
|
92
|
-
res.setHeader("RateLimit-Reset", Math.ceil(resetTime.getTime() / 1e3));
|
|
93
|
-
}
|
|
94
|
-
if (totalHits > max) return res.status(statusCode).json({ message });
|
|
95
|
-
next();
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
//#endregion
|
|
99
|
-
export { rateLimit };
|
|
100
|
-
|
|
11
|
+
var MemoryStore=class{hits=new Map;cleanupTimer;constructor(windowMs){this.windowMs=windowMs,this.cleanupTimer=setInterval(()=>this.cleanup(),windowMs),this.cleanupTimer.unref&&this.cleanupTimer.unref()}async increment(key){let now=Date.now(),entry=this.hits.get(key);if(entry&&entry.resetTime.getTime()>now)return entry.totalHits++,{totalHits:entry.totalHits,resetTime:entry.resetTime};let resetTime=new Date(now+this.windowMs),newEntry={totalHits:1,resetTime};return this.hits.set(key,newEntry),{totalHits:1,resetTime}}async decrement(key){let entry=this.hits.get(key);entry&&entry.totalHits>0&&entry.totalHits--}async reset(key){this.hits.delete(key)}cleanup(){let now=Date.now();for(let[key,entry]of this.hits)entry.resetTime.getTime()<=now&&this.hits.delete(key)}};function rateLimit(options={}){let max=options.max??100,windowMs=options.windowMs??6e4,message=options.message??`Too Many Requests`,statusCode=options.statusCode??429,keyGenerator=options.keyGenerator??(req=>req.ip??`127.0.0.1`),sendHeaders=options.headers??!0,store=options.store??new MemoryStore(windowMs),skip=options.skip,skipPaths=new Set(options.skipPaths??[]);return async(req,res,next)=>{if(skipPaths.has(req.path)||skip&&skip(req))return next();let key=keyGenerator(req),{totalHits,resetTime}=await store.increment(key),remaining=Math.max(0,max-totalHits);if(sendHeaders&&(res.setHeader(`RateLimit-Limit`,max),res.setHeader(`RateLimit-Remaining`,remaining),res.setHeader(`RateLimit-Reset`,Math.ceil(resetTime.getTime()/1e3))),totalHits>max)return res.status(statusCode).json({message});next()}}export{rateLimit};
|
|
101
12
|
//# sourceMappingURL=rate-limit.mjs.map
|
|
@@ -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'\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":"
|
|
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,YAAN,KAA4C,CAC1C,KAAe,IAAI,IACnB,aAEA,YAAY,SAA0B,CAAlB,KAAA,SAAA,SAClB,KAAK,aAAe,gBAAkB,KAAK,SAAS,CAAE,SAAS,CAE3D,KAAK,aAAa,OACpB,KAAK,aAAa,OAAO,CAI7B,MAAM,UAAU,IAA8D,CAC5E,IAAM,IAAM,KAAK,KAAK,CAChB,MAAQ,KAAK,KAAK,IAAI,IAAI,CAEhC,GAAI,OAAS,MAAM,UAAU,SAAS,CAAG,IAEvC,MADA,OAAM,YACC,CAAE,UAAW,MAAM,UAAW,UAAW,MAAM,UAAW,CAGnE,IAAM,UAAY,IAAI,KAAK,IAAM,KAAK,SAAS,CACzC,SAA6B,CAAE,UAAW,EAAG,UAAW,CAE9D,OADA,KAAK,KAAK,IAAI,IAAK,SAAS,CACrB,CAAE,UAAW,EAAG,UAAW,CAGpC,MAAM,UAAU,IAA4B,CAC1C,IAAM,MAAQ,KAAK,KAAK,IAAI,IAAI,CAC5B,OAAS,MAAM,UAAY,GAC7B,MAAM,YAIV,MAAM,MAAM,IAA4B,CACtC,KAAK,KAAK,OAAO,IAAI,CAGvB,SAAwB,CACtB,IAAM,IAAM,KAAK,KAAK,CACtB,IAAK,GAAM,CAAC,IAAK,SAAU,KAAK,KAC1B,MAAM,UAAU,SAAS,EAAI,KAC/B,KAAK,KAAK,OAAO,IAAI,GA0B7B,SAAgB,UAAU,QAA4B,EAAE,CAAE,CACxD,IAAM,IAAM,QAAQ,KAAO,IACrB,SAAW,QAAQ,UAAY,IAC/B,QAAU,QAAQ,SAAW,oBAC7B,WAAa,QAAQ,YAAc,IACnC,aAAe,QAAQ,eAAkB,KAAiB,IAAI,IAAM,aACpE,YAAc,QAAQ,SAAW,GACjC,MAAQ,QAAQ,OAAS,IAAI,YAAY,SAAS,CAClD,KAAO,QAAQ,KACf,UAAY,IAAI,IAAI,QAAQ,WAAa,EAAE,CAAC,CAElD,OAAO,MAAO,IAAc,IAAe,OAAuB,CAOhE,GALI,UAAU,IAAI,IAAI,KAAK,EAKvB,MAAQ,KAAK,IAAI,CACnB,OAAO,MAAM,CAGf,IAAM,IAAM,aAAa,IAAI,CACvB,CAAE,UAAW,WAAc,MAAM,MAAM,UAAU,IAAI,CACrD,UAAY,KAAK,IAAI,EAAG,IAAM,UAAU,CAQ9C,GANI,cACF,IAAI,UAAU,kBAAmB,IAAI,CACrC,IAAI,UAAU,sBAAuB,UAAU,CAC/C,IAAI,UAAU,kBAAmB,KAAK,KAAK,UAAU,SAAS,CAAG,IAAK,CAAC,EAGrE,UAAY,IACd,OAAO,IAAI,OAAO,WAAW,CAAC,KAAK,CAAE,QAAS,CAAC,CAGjD,MAAM"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,28 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
//#region src/http/middleware/request-id.ts
|
|
13
|
-
const REQUEST_ID_HEADER = "x-request-id";
|
|
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
|
-
*/
|
|
24
|
-
function requestId() {
|
|
25
|
-
return (req, res, next) => {
|
|
26
|
-
const id = req.requestId || req.headers["x-request-id"] || randomUUID();
|
|
27
|
-
req.requestId = id;
|
|
28
|
-
res.setHeader(REQUEST_ID_HEADER, id);
|
|
29
|
-
next();
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
//#endregion
|
|
33
|
-
export { REQUEST_ID_HEADER, requestId };
|
|
34
|
-
|
|
11
|
+
import{randomUUID}from"node:crypto";const REQUEST_ID_HEADER=`x-request-id`;function requestId(){return(req,res,next)=>{let id=req.requestId||req.headers[`x-request-id`]||randomUUID();req.requestId=id,res.setHeader(REQUEST_ID_HEADER,id),next()}}export{REQUEST_ID_HEADER,requestId};
|
|
35
12
|
//# sourceMappingURL=request-id.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-id.mjs","names":[],"sources":["../../../src/http/middleware/request-id.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\n\nexport const REQUEST_ID_HEADER = 'x-request-id'\n\n/**\n * Middleware that generates or propagates a unique request ID.\n *\n * Idempotent: if `req.requestId` is already set (e.g. by\n * `requestScopeMiddleware` earlier in the pipeline), this middleware reuses\n * it instead of generating a divergent second value. Keeps the\n * X-Request-Id response header, the ALS store's `requestId`, and\n * `RequestContext.requestId` in agreement for every request, regardless of\n * mounting order.\n */\nexport function requestId() {\n return (req: Request, res: Response, next: NextFunction) => {\n const existing = (req as Request & { requestId?: string }).requestId\n const id = existing || (req.headers[REQUEST_ID_HEADER] as string) || randomUUID()\n ;(req as any).requestId = id\n res.setHeader(REQUEST_ID_HEADER, id)\n next()\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"request-id.mjs","names":[],"sources":["../../../src/http/middleware/request-id.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\n\nexport const REQUEST_ID_HEADER = 'x-request-id'\n\n/**\n * Middleware that generates or propagates a unique request ID.\n *\n * Idempotent: if `req.requestId` is already set (e.g. by\n * `requestScopeMiddleware` earlier in the pipeline), this middleware reuses\n * it instead of generating a divergent second value. Keeps the\n * X-Request-Id response header, the ALS store's `requestId`, and\n * `RequestContext.requestId` in agreement for every request, regardless of\n * mounting order.\n */\nexport function requestId() {\n return (req: Request, res: Response, next: NextFunction) => {\n const existing = (req as Request & { requestId?: string }).requestId\n const id = existing || (req.headers[REQUEST_ID_HEADER] as string) || randomUUID()\n ;(req as any).requestId = id\n res.setHeader(REQUEST_ID_HEADER, id)\n next()\n }\n}\n"],"mappings":";;;;;;;;;;oCAGA,MAAa,kBAAoB,eAYjC,SAAgB,WAAY,CAC1B,OAAQ,IAAc,IAAe,OAAuB,CAE1D,IAAM,GADY,IAAyC,WACnC,IAAI,QAAA,iBAAyC,YAAY,CAC/E,IAAY,UAAY,GAC1B,IAAI,UAAU,kBAAmB,GAAG,CACpC,MAAM"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,42 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
import "../../core--a4XflX7.mjs";
|
|
13
|
-
//#region src/http/middleware/request-logger.ts
|
|
14
|
-
/**
|
|
15
|
-
* Middleware that logs every request with method, URL, status, duration, and request ID.
|
|
16
|
-
*
|
|
17
|
-
* @example
|
|
18
|
-
* ```ts
|
|
19
|
-
* bootstrap({
|
|
20
|
-
* middleware: [requestId(), requestLogger(), express.json()],
|
|
21
|
-
* })
|
|
22
|
-
* ```
|
|
23
|
-
*
|
|
24
|
-
* Output:
|
|
25
|
-
* ```
|
|
26
|
-
* [HTTP] GET /api/v1/users 200 12ms req-abc123
|
|
27
|
-
* [HTTP] POST /api/v1/users 201 45ms req-def456
|
|
28
|
-
* ```
|
|
29
|
-
*/
|
|
30
|
-
function requestLogger(options = {}) {
|
|
31
|
-
const log = createLogger(options.name ?? "HTTP");
|
|
32
|
-
const level = options.level ?? "info";
|
|
33
|
-
const skip = options.skip ?? [];
|
|
34
|
-
return (req, res, next) => {
|
|
35
|
-
if (skip.some((prefix) => req.path.startsWith(prefix))) return next();
|
|
36
|
-
const start = Date.now();
|
|
37
|
-
res.on("finish", () => {
|
|
38
|
-
const duration = Date.now() - start;
|
|
39
|
-
const requestId = req.requestId || req.headers["x-request-id"] || "-";
|
|
40
|
-
const status = res.statusCode;
|
|
41
|
-
log[level](`${req.method} ${req.originalUrl} ${status} ${duration}ms ${requestId}`);
|
|
42
|
-
});
|
|
43
|
-
next();
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
//#endregion
|
|
47
|
-
export { requestLogger };
|
|
48
|
-
|
|
11
|
+
import{createLogger}from"../../core/logger.mjs";import"../../core-MvABl8Cl.mjs";function requestLogger(options={}){let log=createLogger(options.name??`HTTP`),level=options.level??`info`,skip=options.skip??[];return(req,res,next)=>{if(skip.some(prefix=>req.path.startsWith(prefix)))return next();let start=Date.now();res.on(`finish`,()=>{let duration=Date.now()-start,requestId=req.requestId||req.headers[`x-request-id`]||`-`,status=res.statusCode;log[level](`${req.method} ${req.originalUrl} ${status} ${duration}ms ${requestId}`)}),next()}}export{requestLogger};
|
|
49
12
|
//# sourceMappingURL=request-logger.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-logger.mjs","names":[],"sources":["../../../src/http/middleware/request-logger.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\nimport { createLogger } from '../../core'\n\nexport interface RequestLoggerOptions {\n /** Logger name (default: 'HTTP') */\n name?: string\n /** Log level for successful requests (default: 'info') */\n level?: 'info' | 'debug' | 'trace'\n /** Skip logging for paths matching these prefixes (e.g. ['/health', '/_debug']) */\n skip?: string[]\n}\n\n/**\n * Middleware that logs every request with method, URL, status, duration, and request ID.\n *\n * @example\n * ```ts\n * bootstrap({\n * middleware: [requestId(), requestLogger(), express.json()],\n * })\n * ```\n *\n * Output:\n * ```\n * [HTTP] GET /api/v1/users 200 12ms req-abc123\n * [HTTP] POST /api/v1/users 201 45ms req-def456\n * ```\n */\nexport function requestLogger(options: RequestLoggerOptions = {}) {\n const log = createLogger(options.name ?? 'HTTP')\n const level = options.level ?? 'info'\n const skip = options.skip ?? []\n\n return (req: Request, res: Response, next: NextFunction) => {\n // Skip logging for excluded paths\n if (skip.some((prefix) => req.path.startsWith(prefix))) {\n return next()\n }\n\n const start = Date.now()\n\n res.on('finish', () => {\n const duration = Date.now() - start\n const requestId = (req as any).requestId || req.headers['x-request-id'] || '-'\n const status = res.statusCode\n\n log[level](`${req.method} ${req.originalUrl} ${status} ${duration}ms ${requestId}`)\n })\n\n next()\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"request-logger.mjs","names":[],"sources":["../../../src/http/middleware/request-logger.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\nimport { createLogger } from '../../core'\n\nexport interface RequestLoggerOptions {\n /** Logger name (default: 'HTTP') */\n name?: string\n /** Log level for successful requests (default: 'info') */\n level?: 'info' | 'debug' | 'trace'\n /** Skip logging for paths matching these prefixes (e.g. ['/health', '/_debug']) */\n skip?: string[]\n}\n\n/**\n * Middleware that logs every request with method, URL, status, duration, and request ID.\n *\n * @example\n * ```ts\n * bootstrap({\n * middleware: [requestId(), requestLogger(), express.json()],\n * })\n * ```\n *\n * Output:\n * ```\n * [HTTP] GET /api/v1/users 200 12ms req-abc123\n * [HTTP] POST /api/v1/users 201 45ms req-def456\n * ```\n */\nexport function requestLogger(options: RequestLoggerOptions = {}) {\n const log = createLogger(options.name ?? 'HTTP')\n const level = options.level ?? 'info'\n const skip = options.skip ?? []\n\n return (req: Request, res: Response, next: NextFunction) => {\n // Skip logging for excluded paths\n if (skip.some((prefix) => req.path.startsWith(prefix))) {\n return next()\n }\n\n const start = Date.now()\n\n res.on('finish', () => {\n const duration = Date.now() - start\n const requestId = (req as any).requestId || req.headers['x-request-id'] || '-'\n const status = res.statusCode\n\n log[level](`${req.method} ${req.originalUrl} ${status} ${duration}ms ${requestId}`)\n })\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;gFA4BA,SAAgB,cAAc,QAAgC,EAAE,CAAE,CAChE,IAAM,IAAM,aAAa,QAAQ,MAAQ,OAAO,CAC1C,MAAQ,QAAQ,OAAS,OACzB,KAAO,QAAQ,MAAQ,EAAE,CAE/B,OAAQ,IAAc,IAAe,OAAuB,CAE1D,GAAI,KAAK,KAAM,QAAW,IAAI,KAAK,WAAW,OAAO,CAAC,CACpD,OAAO,MAAM,CAGf,IAAM,MAAQ,KAAK,KAAK,CAExB,IAAI,GAAG,aAAgB,CACrB,IAAM,SAAW,KAAK,KAAK,CAAG,MACxB,UAAa,IAAY,WAAa,IAAI,QAAQ,iBAAmB,IACrE,OAAS,IAAI,WAEnB,IAAI,OAAO,GAAG,IAAI,OAAO,GAAG,IAAI,YAAY,GAAG,OAAO,GAAG,SAAS,KAAK,YAAY,EACnF,CAEF,MAAM"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.5.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,170 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import { createHmac,
|
|
12
|
-
//#region src/http/middleware/session.ts
|
|
13
|
-
var MemoryStore = class {
|
|
14
|
-
sessions = /* @__PURE__ */ new Map();
|
|
15
|
-
cleanupInterval;
|
|
16
|
-
constructor() {
|
|
17
|
-
this.cleanupInterval = setInterval(() => this.purge(), 6e4);
|
|
18
|
-
this.cleanupInterval.unref();
|
|
19
|
-
}
|
|
20
|
-
async get(sid) {
|
|
21
|
-
const entry = this.sessions.get(sid);
|
|
22
|
-
if (!entry) return null;
|
|
23
|
-
if (Date.now() > entry.expires) {
|
|
24
|
-
this.sessions.delete(sid);
|
|
25
|
-
return null;
|
|
26
|
-
}
|
|
27
|
-
return entry.data;
|
|
28
|
-
}
|
|
29
|
-
async set(sid, data, maxAge) {
|
|
30
|
-
this.sessions.set(sid, {
|
|
31
|
-
data,
|
|
32
|
-
expires: Date.now() + maxAge
|
|
33
|
-
});
|
|
34
|
-
}
|
|
35
|
-
async destroy(sid) {
|
|
36
|
-
this.sessions.delete(sid);
|
|
37
|
-
}
|
|
38
|
-
async touch(sid, maxAge) {
|
|
39
|
-
const entry = this.sessions.get(sid);
|
|
40
|
-
if (entry) entry.expires = Date.now() + maxAge;
|
|
41
|
-
}
|
|
42
|
-
purge() {
|
|
43
|
-
const now = Date.now();
|
|
44
|
-
for (const [sid, entry] of this.sessions) if (now > entry.expires) this.sessions.delete(sid);
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
function parseCookieHeader(header) {
|
|
48
|
-
const out = {};
|
|
49
|
-
for (const pair of header.split(";")) {
|
|
50
|
-
const eq = pair.indexOf("=");
|
|
51
|
-
if (eq === -1) continue;
|
|
52
|
-
const key = pair.slice(0, eq).trim();
|
|
53
|
-
if (!key) continue;
|
|
54
|
-
let value = pair.slice(eq + 1).trim();
|
|
55
|
-
if (value.startsWith("\"") && value.endsWith("\"")) value = value.slice(1, -1);
|
|
56
|
-
try {
|
|
57
|
-
out[key] = decodeURIComponent(value);
|
|
58
|
-
} catch {
|
|
59
|
-
out[key] = value;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
return out;
|
|
63
|
-
}
|
|
64
|
-
function sign(value, secret) {
|
|
65
|
-
return `s:${value}.${createHmac("sha256", secret).update(value).digest("base64url")}`;
|
|
66
|
-
}
|
|
67
|
-
function unsign(signed, secret) {
|
|
68
|
-
if (!signed.startsWith("s:")) return false;
|
|
69
|
-
const raw = signed.slice(2);
|
|
70
|
-
const dotIndex = raw.lastIndexOf(".");
|
|
71
|
-
if (dotIndex === -1) return false;
|
|
72
|
-
const value = raw.slice(0, dotIndex);
|
|
73
|
-
const providedSig = raw.slice(dotIndex + 1);
|
|
74
|
-
const expectedSig = createHmac("sha256", secret).update(value).digest("base64url");
|
|
75
|
-
const a = Buffer.from(providedSig);
|
|
76
|
-
const b = Buffer.from(expectedSig);
|
|
77
|
-
if (a.length !== b.length || !timingSafeEqual(a, b)) return false;
|
|
78
|
-
return value;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Session management middleware.
|
|
82
|
-
*
|
|
83
|
-
* Attaches a `req.session` object with `id`, `data`, `regenerate()`,
|
|
84
|
-
* `destroy()`, and `save()` methods. Session IDs are signed with
|
|
85
|
-
* HMAC-SHA256 to prevent cookie tampering.
|
|
86
|
-
*
|
|
87
|
-
* Reads the session cookie from `req.cookies` when an upstream cookie
|
|
88
|
-
* parser is present; otherwise parses `req.headers.cookie` directly, so
|
|
89
|
-
* no cookie parser is required upstream.
|
|
90
|
-
*
|
|
91
|
-
* @example
|
|
92
|
-
* ```ts
|
|
93
|
-
* import { session } from '@forinda/kickjs'
|
|
94
|
-
*
|
|
95
|
-
* bootstrap({
|
|
96
|
-
* modules,
|
|
97
|
-
* middleware: [
|
|
98
|
-
* session({ secret: process.env.SESSION_SECRET! }),
|
|
99
|
-
* // ... other middleware
|
|
100
|
-
* ],
|
|
101
|
-
* })
|
|
102
|
-
* ```
|
|
103
|
-
*/
|
|
104
|
-
function session(options) {
|
|
105
|
-
const { secret, cookieName = "kick.sid", maxAge = 864e5, rolling = false, saveUninitialized = true, store = new MemoryStore(), cookie: cookieOpts = {} } = options;
|
|
106
|
-
const cookieDefaults = {
|
|
107
|
-
httpOnly: cookieOpts.httpOnly ?? true,
|
|
108
|
-
secure: cookieOpts.secure ?? process.env.NODE_ENV === "production",
|
|
109
|
-
sameSite: cookieOpts.sameSite ?? "lax",
|
|
110
|
-
path: cookieOpts.path ?? "/",
|
|
111
|
-
...cookieOpts.domain ? { domain: cookieOpts.domain } : {},
|
|
112
|
-
maxAge
|
|
113
|
-
};
|
|
114
|
-
return async (req, res, next) => {
|
|
115
|
-
let cookies = req.cookies;
|
|
116
|
-
if (!cookies) {
|
|
117
|
-
const header = req.headers.cookie;
|
|
118
|
-
cookies = header ? parseCookieHeader(header) : {};
|
|
119
|
-
}
|
|
120
|
-
const signedCookie = cookies[cookieName];
|
|
121
|
-
let sid = false;
|
|
122
|
-
let sessionData = null;
|
|
123
|
-
let isNew = false;
|
|
124
|
-
if (signedCookie) {
|
|
125
|
-
sid = unsign(signedCookie, secret);
|
|
126
|
-
if (sid) sessionData = await store.get(sid);
|
|
127
|
-
}
|
|
128
|
-
if (!sid || !sessionData) {
|
|
129
|
-
sid = randomUUID();
|
|
130
|
-
sessionData = {};
|
|
131
|
-
isNew = true;
|
|
132
|
-
}
|
|
133
|
-
let currentSid = sid;
|
|
134
|
-
let currentData = { ...sessionData };
|
|
135
|
-
let destroyed = false;
|
|
136
|
-
const sessionObj = {
|
|
137
|
-
get id() {
|
|
138
|
-
return currentSid;
|
|
139
|
-
},
|
|
140
|
-
data: currentData,
|
|
141
|
-
async regenerate() {
|
|
142
|
-
await store.destroy(currentSid);
|
|
143
|
-
currentSid = randomUUID();
|
|
144
|
-
currentData = {};
|
|
145
|
-
sessionObj.data = currentData;
|
|
146
|
-
await store.set(currentSid, currentData, maxAge);
|
|
147
|
-
res.cookie(cookieName, sign(currentSid, secret), cookieDefaults);
|
|
148
|
-
},
|
|
149
|
-
async destroy() {
|
|
150
|
-
await store.destroy(currentSid);
|
|
151
|
-
destroyed = true;
|
|
152
|
-
currentData = {};
|
|
153
|
-
sessionObj.data = currentData;
|
|
154
|
-
res.clearCookie(cookieName, { path: cookieDefaults.path });
|
|
155
|
-
},
|
|
156
|
-
async save() {
|
|
157
|
-
if (!destroyed) await store.set(currentSid, currentData, maxAge);
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
req.session = sessionObj;
|
|
161
|
-
if (isNew) res.cookie(cookieName, sign(currentSid, secret), cookieDefaults);
|
|
162
|
-
res.on("finish", async () => {
|
|
163
|
-
if (destroyed) return;
|
|
164
|
-
if (isNew && !saveUninitialized && Object.keys(currentData).length === 0) return;
|
|
165
|
-
await store.set(currentSid, currentData, maxAge);
|
|
166
|
-
if (rolling && !isNew) {
|
|
167
|
-
if (store.touch) await store.touch(currentSid, maxAge);
|
|
168
|
-
}
|
|
169
|
-
});
|
|
170
|
-
if (rolling && !isNew) res.cookie(cookieName, sign(currentSid, secret), cookieDefaults);
|
|
171
|
-
next();
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
//#endregion
|
|
175
|
-
export { session };
|
|
176
|
-
|
|
11
|
+
import{createHmac,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=new Map;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),null):entry.data:null}async set(sid,data,maxAge){this.sessions.set(sid,{data,expires:Date.now()+maxAge})}async destroy(sid){this.sessions.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge)}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&this.sessions.delete(sid)}};function parseCookieHeader(header){let out={};for(let pair of header.split(`;`)){let eq=pair.indexOf(`=`);if(eq===-1)continue;let key=pair.slice(0,eq).trim();if(!key)continue;let value=pair.slice(eq+1).trim();value.startsWith(`"`)&&value.endsWith(`"`)&&(value=value.slice(1,-1));try{out[key]=decodeURIComponent(value)}catch{out[key]=value}}return out}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secret){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),providedSig=raw.slice(dotIndex+1),expectedSig=createHmac(`sha256`,secret).update(value).digest(`base64url`),a=Buffer.from(providedSig),b=Buffer.from(expectedSig);return a.length!==b.length||!timingSafeEqual(a,b)?!1:value}function session(options){let{secret,cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,store=new MemoryStore,cookie:cookieOpts={}}=options,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??process.env.NODE_ENV===`production`,sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1;signedCookie&&(sid=unsign(signedCookie,secret),sid&&(sessionData=await store.get(sid))),(!sid||!sessionData)&&(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),res.cookie(cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,res.clearCookie(cookieName,{path:cookieDefaults.path})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&res.cookie(cookieName,sign(currentSid,secret),cookieDefaults),res.on(`finish`,async()=>{destroyed||isNew&&!saveUninitialized&&Object.keys(currentData).length===0||(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))}),rolling&&!isNew&&res.cookie(cookieName,sign(currentSid,secret),cookieDefaults),next()}}export{session};
|
|
177
12
|
//# sourceMappingURL=session.mjs.map
|