@alwatr/pre-handlers 4.10.0 → 9.1.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/handler/parse-body-as-json.d.ts.map +1 -1
- package/dist/main.js +5 -0
- package/dist/main.js.map +12 -0
- package/package.json +48 -50
- package/src/handler/parse-body-as-json.ts +52 -0
- package/src/handler/require-access-token.ts +52 -0
- package/src/lib/get-auth-bearer.ts +26 -0
- package/src/main.ts +3 -0
- package/CHANGELOG.md +0 -120
- package/dist/main.cjs +0 -4
- package/dist/main.cjs.map +0 -7
- package/dist/main.mjs +0 -4
- package/dist/main.mjs.map +0 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-body-as-json.d.ts","sourceRoot":"","sources":["../../src/handler/parse-body-as-json.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,qBAAqB,EAAC,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"parse-body-as-json.d.ts","sourceRoot":"","sources":["../../src/handler/parse-body-as-json.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,qBAAqB,EAAC,MAAM,6BAA6B,CAAC;AAEvE;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,qBAAqB,CAAC;IAAC,IAAI,CAAC,EAAE,UAAU,GAAG,SAAS,CAAA;CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CA6BjH"}
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/* 📦 @alwatr/pre-handlers v9.1.0 */
|
|
2
|
+
function x(B){let z=B?.split(" ");if(!z||z[0].toLowerCase()!=="bearer"||!z[1])return null;return z[1]}import{HttpStatusCodes as E}from"@alwatr/nanotron-api-server";async function Q(){this.logger_.logMethod?.("parseBodyAsJson");let B=await this.getBodyRaw();if(B.length===0){this.logger_.error("parseBodyAsJson","body_required"),this.serverResponse.statusCode=E.Error_Client_422_Unprocessable_Entity,this.serverResponse.replyErrorResponse({ok:!1,errorCode:"body_required",errorMessage:"Request body is required."});return}try{this.sharedMeta.body=JSON.parse(B.toString())}catch(z){this.logger_.error("parseBodyAsJson","invalid_body_json",z),this.serverResponse.statusCode=E.Error_Client_422_Unprocessable_Entity,this.serverResponse.replyErrorResponse({ok:!1,errorCode:"invalid_body_json",errorMessage:"Invalid JSON in request body."})}this.logger_.logProperty?.("body",this.sharedMeta.body)}import{HttpStatusCodes as L}from"@alwatr/nanotron-api-server";var X=(B)=>async function(){let g=x(this.headers.authorization);if(this.logger_.logMethodArgs?.("requireAccessToken",{userToken:g}),g===null){this.serverResponse.statusCode=L.Error_Client_401_Unauthorized,this.serverResponse.replyErrorResponse({ok:!1,errorCode:"authorization_required",errorMessage:"Authorization token required"});return}if(g!==B)this.serverResponse.statusCode=L.Error_Client_403_Forbidden,this.serverResponse.replyErrorResponse({ok:!1,errorCode:"access_denied",errorMessage:"Access denied, token is invalid!"})};export{X as requireAccessToken,Q as parseBodyAsJson,x as getAuthBearer};
|
|
3
|
+
|
|
4
|
+
//# debugId=CE62094DBB63953064756E2164756E21
|
|
5
|
+
//# sourceMappingURL=main.js.map
|
package/dist/main.js.map
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/get-auth-bearer.ts", "../src/handler/parse-body-as-json.ts", "../src/handler/require-access-token.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Extracts the Bearer token from the authorization header.\n *\n * This function takes an optional authorization header string, extracts the Bearer token, and returns it.\n * If the header is invalid or the token is missing, it returns null.\n *\n * @param {string} [authorizationHeader] - The authorization header string.\n * @returns {string | null} The extracted Bearer token or null if the header is invalid.\n *\n * @example\n * ```ts\n * console.log(this.headers.authorization); // 'Bearer myToken123'\n * const token = getAuthBearer(this.headers.authorization);\n * console.log(token); // 'myToken123'\n *\n * const invalidToken = getAuthBearer('Basic myToken123');\n * console.log(invalidToken); // null\n * ```\n */\nexport function getAuthBearer(authorizationHeader?: string): string | null {\n const auth = authorizationHeader?.split(' ');\n if (!auth || auth[0].toLowerCase() !== 'bearer' || !auth[1]) {\n return null;\n }\n return auth[1];\n}\n",
|
|
6
|
+
"import {HttpStatusCodes} from '@alwatr/nanotron-api-server';\n\nimport type {NanotronClientRequest} from '@alwatr/nanotron-api-server';\n\n/**\n * Middleware to parses the request body as JSON and assigns it to `this.sharedMeta.body`.\n * If the body is empty or invalid, it sends an error response,\n * which triggers `terminatedHandlers` and prevents further handlers from executing.\n *\n * @this {NanotronClientRequest<{body: DictionaryOpt}>}\n * @returns {Promise<void>} A promise that resolves when the body is successfully parsed or an error response is sent.\n *\n * @example\n * ```ts\n * nanotronApiServer.defineRoute<{body: DictionaryOpt}>({\n * preHandlers: [parseBodyAsJson],\n * async handler() {\n * const body = this.sharedMeta.body; // json object\n * },\n * });\n * ```\n */\nexport async function parseBodyAsJson(this: NanotronClientRequest<{body?: JsonObject | JsonArray}>): Promise<void> {\n this.logger_.logMethod?.('parseBodyAsJson');\n const bodyBuffer = await this.getBodyRaw();\n\n if (bodyBuffer.length === 0) {\n this.logger_.error('parseBodyAsJson', 'body_required');\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_422_Unprocessable_Entity;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'body_required',\n errorMessage: 'Request body is required.',\n });\n return;\n }\n\n try {\n this.sharedMeta.body = JSON.parse(bodyBuffer.toString()) as DictionaryOpt | JsonArray;\n }\n catch (error) {\n this.logger_.error('parseBodyAsJson', 'invalid_body_json', error);\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_422_Unprocessable_Entity;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'invalid_body_json',\n errorMessage: 'Invalid JSON in request body.',\n });\n }\n\n this.logger_.logProperty?.('body', this.sharedMeta.body);\n}\n",
|
|
7
|
+
"import {HttpStatusCodes, type NanotronClientRequest} from '@alwatr/nanotron-api-server';\n\nimport {getAuthBearer} from '../lib/get-auth-bearer.js';\n\n/**\n * Middleware to require a valid access token for a Nanotron API request.\n *\n * This function checks the authorization header for a Bearer token and compares it to the provided access token.\n * If the token is missing or invalid, it sends an appropriate error response and prevents further handlers from executing.\n *\n * @param {string} accessToken - The valid access token to compare against.\n * @returns {Function} A middleware function for Nanotron API requests.\n *\n * @example\n * ```ts\n * nanotronApiServer.defineRoute({\n * method: 'POST',\n * url: 'secure-endpoint',\n * preHandlers: [requireAccessToken('mySecretToken')],\n * async handler() {\n * this.serverResponse.replyJson({\n * ok: true,\n * message: 'Access granted!',\n * });\n * },\n * });\n * ```\n */\nexport const requireAccessToken = (accessToken: string) =>\n async function requireAccessToken_(this: NanotronClientRequest): Promise<void> {\n const userToken = getAuthBearer(this.headers.authorization);\n this.logger_.logMethodArgs?.('requireAccessToken', {userToken});\n\n if (userToken === null) {\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_401_Unauthorized;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'authorization_required',\n errorMessage: 'Authorization token required',\n });\n return;\n }\n\n if (userToken !== accessToken) {\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_403_Forbidden;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'access_denied',\n errorMessage: 'Access denied, token is invalid!',\n });\n }\n };\n"
|
|
8
|
+
],
|
|
9
|
+
"mappings": ";AAmBO,SAAS,CAAa,CAAC,EAA6C,CACzE,IAAM,EAAO,GAAqB,MAAM,GAAG,EAC3C,GAAI,CAAC,GAAQ,EAAK,GAAG,YAAY,IAAM,UAAY,CAAC,EAAK,GACvD,OAAO,KAET,OAAO,EAAK,GCxBd,0BAAQ,oCAsBR,eAAsB,CAAe,EAA8E,CACjH,KAAK,QAAQ,YAAY,iBAAiB,EAC1C,IAAM,EAAa,MAAM,KAAK,WAAW,EAEzC,GAAI,EAAW,SAAW,EAAG,CAC3B,KAAK,QAAQ,MAAM,kBAAmB,eAAe,EACrD,KAAK,eAAe,WAAa,EAAgB,sCACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,GACJ,UAAW,gBACX,aAAc,2BAChB,CAAC,EACD,OAGF,GAAI,CACF,KAAK,WAAW,KAAO,KAAK,MAAM,EAAW,SAAS,CAAC,EAEzD,MAAO,EAAO,CACZ,KAAK,QAAQ,MAAM,kBAAmB,oBAAqB,CAAK,EAChE,KAAK,eAAe,WAAa,EAAgB,sCACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,GACJ,UAAW,oBACX,aAAc,+BAChB,CAAC,EAGH,KAAK,QAAQ,cAAc,OAAQ,KAAK,WAAW,IAAI,EClDzD,0BAAQ,oCA4BD,IAAM,EAAqB,CAAC,IACjC,cAAkC,EAA6C,CAC7E,IAAM,EAAY,EAAc,KAAK,QAAQ,aAAa,EAG1D,GAFA,KAAK,QAAQ,gBAAgB,qBAAsB,CAAC,WAAS,CAAC,EAE1D,IAAc,KAAM,CACtB,KAAK,eAAe,WAAa,EAAgB,8BACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,GACJ,UAAW,yBACX,aAAc,8BAChB,CAAC,EACD,OAGF,GAAI,IAAc,EAChB,KAAK,eAAe,WAAa,EAAgB,2BACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,GACJ,UAAW,gBACX,aAAc,kCAChB,CAAC",
|
|
10
|
+
"debugId": "CE62094DBB63953064756E2164756E21",
|
|
11
|
+
"names": []
|
|
12
|
+
}
|
package/package.json
CHANGED
|
@@ -1,33 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/pre-handlers",
|
|
3
|
+
"version": "9.1.0",
|
|
3
4
|
"description": "Functions that will run before processing every defined route.",
|
|
4
|
-
"
|
|
5
|
-
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
"@alwatr/nano-build": "^6.3.1",
|
|
12
|
-
"@alwatr/prettier-config": "^5.0.4",
|
|
13
|
-
"@alwatr/tsconfig-base": "^6.0.2",
|
|
14
|
-
"@alwatr/type-helper": "^6.1.1",
|
|
15
|
-
"@types/node": "^22.18.6",
|
|
16
|
-
"jest": "^30.1.3",
|
|
17
|
-
"typescript": "^5.9.2"
|
|
5
|
+
"license": "MPL-2.0",
|
|
6
|
+
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/Alwatr/alwatr",
|
|
11
|
+
"directory": "pkg/nanotron-old/pre-handlers"
|
|
18
12
|
},
|
|
13
|
+
"homepage": "https://github.com/Alwatr/alwatr/tree/main/pkg/nanotron-old/pre-handlers#readme",
|
|
14
|
+
"bugs": "https://github.com/Alwatr/alwatr/issues",
|
|
19
15
|
"exports": {
|
|
20
16
|
".": {
|
|
21
17
|
"types": "./dist/main.d.ts",
|
|
22
|
-
"import": "./dist/main.
|
|
23
|
-
"
|
|
18
|
+
"import": "./dist/main.js",
|
|
19
|
+
"default": "./dist/main.js"
|
|
24
20
|
}
|
|
25
21
|
},
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@alwatr/nanotron-api-server": "9.1.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@alwatr/nano-build": "9.1.0",
|
|
28
|
+
"@alwatr/tsconfig-base": "9.1.0",
|
|
29
|
+
"@alwatr/type-helper": "9.1.0",
|
|
30
|
+
"@types/node": "^25.5.0",
|
|
31
|
+
"typescript": "^6.0.2"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"b": "bun run build",
|
|
35
|
+
"build": "bun run build:ts && bun run build:es",
|
|
36
|
+
"build:es": "nano-build --preset=module src/main.ts",
|
|
37
|
+
"build:ts": "tsc --build",
|
|
38
|
+
"cl": "bun run clean",
|
|
39
|
+
"clean": "rm -rfv dist *.tsbuildinfo",
|
|
40
|
+
"format": "prettier --write \"src/**/*.ts\"",
|
|
41
|
+
"lint": "eslint src/ --ext .ts",
|
|
42
|
+
"t": "bun run test",
|
|
43
|
+
"test": "ALWATR_DEBUG=0 bun test",
|
|
44
|
+
"w": "bun run watch",
|
|
45
|
+
"watch": "bun run watch:ts & bun run watch:es",
|
|
46
|
+
"watch:es": "bun run build:es --watch",
|
|
47
|
+
"watch:ts": "bun run build:ts --watch --preserveWatchOutput"
|
|
48
|
+
},
|
|
26
49
|
"files": [
|
|
27
|
-
"
|
|
28
|
-
"
|
|
50
|
+
"dist",
|
|
51
|
+
"src/**/*.ts",
|
|
52
|
+
"!src/**/*.test.ts",
|
|
53
|
+
"README.md",
|
|
54
|
+
"LICENSE"
|
|
29
55
|
],
|
|
30
|
-
"
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public"
|
|
58
|
+
},
|
|
31
59
|
"keywords": [
|
|
32
60
|
"alwatr",
|
|
33
61
|
"api",
|
|
@@ -39,35 +67,5 @@
|
|
|
39
67
|
"server",
|
|
40
68
|
"typescript"
|
|
41
69
|
],
|
|
42
|
-
"
|
|
43
|
-
"main": "./dist/main.cjs",
|
|
44
|
-
"module": "./dist/main.mjs",
|
|
45
|
-
"prettier": "@alwatr/prettier-config",
|
|
46
|
-
"publishConfig": {
|
|
47
|
-
"access": "public"
|
|
48
|
-
},
|
|
49
|
-
"repository": {
|
|
50
|
-
"type": "git",
|
|
51
|
-
"url": "https://github.com/Alwatr/pre-handlers",
|
|
52
|
-
"directory": "packages/pre-handlers"
|
|
53
|
-
},
|
|
54
|
-
"scripts": {
|
|
55
|
-
"b": "yarn run build",
|
|
56
|
-
"build": "yarn run build:ts & yarn run build:es",
|
|
57
|
-
"build:es": "nano-build --preset=module",
|
|
58
|
-
"build:ts": "tsc --build",
|
|
59
|
-
"c": "yarn run clean",
|
|
60
|
-
"cb": "yarn run clean && yarn run build",
|
|
61
|
-
"clean": "rm -rfv dist *.tsbuildinfo",
|
|
62
|
-
"d": "yarn run build:es && yarn node --enable-source-maps --trace-warnings",
|
|
63
|
-
"t": "yarn run test",
|
|
64
|
-
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --enable-source-maps --experimental-vm-modules\" jest",
|
|
65
|
-
"w": "yarn run watch",
|
|
66
|
-
"watch": "yarn run watch:ts & yarn run watch:es",
|
|
67
|
-
"watch:es": "yarn run build:es --watch",
|
|
68
|
-
"watch:ts": "yarn run build:ts --watch --preserveWatchOutput"
|
|
69
|
-
},
|
|
70
|
-
"type": "module",
|
|
71
|
-
"types": "./dist/main.d.ts",
|
|
72
|
-
"gitHead": "234113e16cdec26d18c5687219d5f5c29829e045"
|
|
70
|
+
"gitHead": "4a25cd3e0499cf61dd761e87d3711abf9b0cd208"
|
|
73
71
|
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {HttpStatusCodes} from '@alwatr/nanotron-api-server';
|
|
2
|
+
|
|
3
|
+
import type {NanotronClientRequest} from '@alwatr/nanotron-api-server';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Middleware to parses the request body as JSON and assigns it to `this.sharedMeta.body`.
|
|
7
|
+
* If the body is empty or invalid, it sends an error response,
|
|
8
|
+
* which triggers `terminatedHandlers` and prevents further handlers from executing.
|
|
9
|
+
*
|
|
10
|
+
* @this {NanotronClientRequest<{body: DictionaryOpt}>}
|
|
11
|
+
* @returns {Promise<void>} A promise that resolves when the body is successfully parsed or an error response is sent.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* nanotronApiServer.defineRoute<{body: DictionaryOpt}>({
|
|
16
|
+
* preHandlers: [parseBodyAsJson],
|
|
17
|
+
* async handler() {
|
|
18
|
+
* const body = this.sharedMeta.body; // json object
|
|
19
|
+
* },
|
|
20
|
+
* });
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export async function parseBodyAsJson(this: NanotronClientRequest<{body?: JsonObject | JsonArray}>): Promise<void> {
|
|
24
|
+
this.logger_.logMethod?.('parseBodyAsJson');
|
|
25
|
+
const bodyBuffer = await this.getBodyRaw();
|
|
26
|
+
|
|
27
|
+
if (bodyBuffer.length === 0) {
|
|
28
|
+
this.logger_.error('parseBodyAsJson', 'body_required');
|
|
29
|
+
this.serverResponse.statusCode = HttpStatusCodes.Error_Client_422_Unprocessable_Entity;
|
|
30
|
+
this.serverResponse.replyErrorResponse({
|
|
31
|
+
ok: false,
|
|
32
|
+
errorCode: 'body_required',
|
|
33
|
+
errorMessage: 'Request body is required.',
|
|
34
|
+
});
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
this.sharedMeta.body = JSON.parse(bodyBuffer.toString()) as DictionaryOpt | JsonArray;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
this.logger_.error('parseBodyAsJson', 'invalid_body_json', error);
|
|
43
|
+
this.serverResponse.statusCode = HttpStatusCodes.Error_Client_422_Unprocessable_Entity;
|
|
44
|
+
this.serverResponse.replyErrorResponse({
|
|
45
|
+
ok: false,
|
|
46
|
+
errorCode: 'invalid_body_json',
|
|
47
|
+
errorMessage: 'Invalid JSON in request body.',
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
this.logger_.logProperty?.('body', this.sharedMeta.body);
|
|
52
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {HttpStatusCodes, type NanotronClientRequest} from '@alwatr/nanotron-api-server';
|
|
2
|
+
|
|
3
|
+
import {getAuthBearer} from '../lib/get-auth-bearer.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Middleware to require a valid access token for a Nanotron API request.
|
|
7
|
+
*
|
|
8
|
+
* This function checks the authorization header for a Bearer token and compares it to the provided access token.
|
|
9
|
+
* If the token is missing or invalid, it sends an appropriate error response and prevents further handlers from executing.
|
|
10
|
+
*
|
|
11
|
+
* @param {string} accessToken - The valid access token to compare against.
|
|
12
|
+
* @returns {Function} A middleware function for Nanotron API requests.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* nanotronApiServer.defineRoute({
|
|
17
|
+
* method: 'POST',
|
|
18
|
+
* url: 'secure-endpoint',
|
|
19
|
+
* preHandlers: [requireAccessToken('mySecretToken')],
|
|
20
|
+
* async handler() {
|
|
21
|
+
* this.serverResponse.replyJson({
|
|
22
|
+
* ok: true,
|
|
23
|
+
* message: 'Access granted!',
|
|
24
|
+
* });
|
|
25
|
+
* },
|
|
26
|
+
* });
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export const requireAccessToken = (accessToken: string) =>
|
|
30
|
+
async function requireAccessToken_(this: NanotronClientRequest): Promise<void> {
|
|
31
|
+
const userToken = getAuthBearer(this.headers.authorization);
|
|
32
|
+
this.logger_.logMethodArgs?.('requireAccessToken', {userToken});
|
|
33
|
+
|
|
34
|
+
if (userToken === null) {
|
|
35
|
+
this.serverResponse.statusCode = HttpStatusCodes.Error_Client_401_Unauthorized;
|
|
36
|
+
this.serverResponse.replyErrorResponse({
|
|
37
|
+
ok: false,
|
|
38
|
+
errorCode: 'authorization_required',
|
|
39
|
+
errorMessage: 'Authorization token required',
|
|
40
|
+
});
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (userToken !== accessToken) {
|
|
45
|
+
this.serverResponse.statusCode = HttpStatusCodes.Error_Client_403_Forbidden;
|
|
46
|
+
this.serverResponse.replyErrorResponse({
|
|
47
|
+
ok: false,
|
|
48
|
+
errorCode: 'access_denied',
|
|
49
|
+
errorMessage: 'Access denied, token is invalid!',
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extracts the Bearer token from the authorization header.
|
|
3
|
+
*
|
|
4
|
+
* This function takes an optional authorization header string, extracts the Bearer token, and returns it.
|
|
5
|
+
* If the header is invalid or the token is missing, it returns null.
|
|
6
|
+
*
|
|
7
|
+
* @param {string} [authorizationHeader] - The authorization header string.
|
|
8
|
+
* @returns {string | null} The extracted Bearer token or null if the header is invalid.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* console.log(this.headers.authorization); // 'Bearer myToken123'
|
|
13
|
+
* const token = getAuthBearer(this.headers.authorization);
|
|
14
|
+
* console.log(token); // 'myToken123'
|
|
15
|
+
*
|
|
16
|
+
* const invalidToken = getAuthBearer('Basic myToken123');
|
|
17
|
+
* console.log(invalidToken); // null
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export function getAuthBearer(authorizationHeader?: string): string | null {
|
|
21
|
+
const auth = authorizationHeader?.split(' ');
|
|
22
|
+
if (!auth || auth[0].toLowerCase() !== 'bearer' || !auth[1]) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
return auth[1];
|
|
26
|
+
}
|
package/src/main.ts
ADDED
package/CHANGELOG.md
DELETED
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
# Change Log
|
|
2
|
-
|
|
3
|
-
All notable changes to this project will be documented in this file.
|
|
4
|
-
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
|
-
|
|
6
|
-
## [4.10.0](https://github.com/Alwatr/pre-handlers/compare/v4.9.4...v4.10.0) (2025-09-21)
|
|
7
|
-
|
|
8
|
-
### 🐛 Bug Fixes
|
|
9
|
-
|
|
10
|
-
* update function signature to allow body as JsonArray in parseBodyAsJson middleware ([11751ec](https://github.com/Alwatr/pre-handlers/commit/11751ec1bea9126165ca8ee324ae9f2c7c64db08))
|
|
11
|
-
* update workspace dependency versioning to use wildcard for nanotron-api-server ([0f62667](https://github.com/Alwatr/pre-handlers/commit/0f62667adfb3d35026ebe143b8f682d128ccfdc1))
|
|
12
|
-
|
|
13
|
-
### 🔨 Code Refactoring
|
|
14
|
-
|
|
15
|
-
* remove unused packageTracer import and development mode tracer from main.ts ([411708a](https://github.com/Alwatr/pre-handlers/commit/411708a37a1202098b747d902cd255c03cfad061))
|
|
16
|
-
|
|
17
|
-
### 🧹 Miscellaneous Chores
|
|
18
|
-
|
|
19
|
-
* remove Exir Studio sponsorship logo from multiple README files ([af3fd5d](https://github.com/Alwatr/pre-handlers/commit/af3fd5dda9b57d0948003db1feb0dc2dad4883d7))
|
|
20
|
-
* remove unused types from compiler options in tsconfig.json ([2d47851](https://github.com/Alwatr/pre-handlers/commit/2d47851db94f8c9da50d3b0a3570d02052bfe61a))
|
|
21
|
-
* standardize formatting in tsconfig.json files by removing trailing commas ([fb9c6b9](https://github.com/Alwatr/pre-handlers/commit/fb9c6b9648b04b038db212727e8d38761d081a65))
|
|
22
|
-
* update @alwatr/nanolib and @alwatr/nano-build to version 6.1.1 and 6.3.1 respectively ([81b3d5e](https://github.com/Alwatr/pre-handlers/commit/81b3d5ebf5ecc1242ee0a010631e4d920af9f3dd))
|
|
23
|
-
* update @alwatr/nanolib and related dependencies to version 6.x ([d824f0d](https://github.com/Alwatr/pre-handlers/commit/d824f0d5b8e008ec758842997a6e2ee6f7d078d5))
|
|
24
|
-
* update licenses from AGPL-3.0 to MPL-2.0 ([a84513e](https://github.com/Alwatr/pre-handlers/commit/a84513efbe12b9570c7550c887f2cdfbf67fc82b))
|
|
25
|
-
|
|
26
|
-
### 🔗 Dependencies update
|
|
27
|
-
|
|
28
|
-
* remove @alwatr/nanolib from dependencies in package.json ([62e6b0d](https://github.com/Alwatr/pre-handlers/commit/62e6b0d858e10bc0c594fd616e584f51c299bd2c))
|
|
29
|
-
|
|
30
|
-
## [4.9.4](https://github.com/Alwatr/pre-handlers/compare/v4.9.3...v4.9.4) (2025-08-23)
|
|
31
|
-
|
|
32
|
-
### 🔨 Code Refactoring
|
|
33
|
-
|
|
34
|
-
* reorganize package.json files for consistency and clarity ([bde116e](https://github.com/Alwatr/pre-handlers/commit/bde116e21f9d9bd6084940e257438916d2c3d312)) by @alimd
|
|
35
|
-
|
|
36
|
-
### 🔗 Dependencies update
|
|
37
|
-
|
|
38
|
-
* downgrade @types/node version to 22.17.2 in all package.json files ([4f01e14](https://github.com/Alwatr/pre-handlers/commit/4f01e1408d8d0954865eb9d20f90178f13e98719)) by @alimd
|
|
39
|
-
* update dependencies for eslint-config, lerna-lite, typescript, and nanolib ([de16a71](https://github.com/Alwatr/pre-handlers/commit/de16a718bb1c0fa569d39c824ec39a1e67ef8dfe)) by @alimd
|
|
40
|
-
|
|
41
|
-
## [4.9.3](https://github.com/Alwatr/pre-handlers/compare/v4.9.2...v4.9.3) (2025-07-23)
|
|
42
|
-
|
|
43
|
-
**Note:** Version bump only for package @alwatr/pre-handlers
|
|
44
|
-
|
|
45
|
-
## [4.9.2](https://github.com/Alwatr/pre-handlers/compare/v4.9.1...v4.9.2) (2025-07-23)
|
|
46
|
-
|
|
47
|
-
### Dependencies update
|
|
48
|
-
|
|
49
|
-
* update dependencies to latest versions ([353d048](https://github.com/Alwatr/pre-handlers/commit/353d0485a5c21ab219d84cd0a6c35f62b46c2da9)) by @alimd
|
|
50
|
-
|
|
51
|
-
## [4.9.1](https://github.com/Alwatr/pre-handlers/compare/v4.9.0...v4.9.1) (2025-03-06)
|
|
52
|
-
|
|
53
|
-
### Dependencies update
|
|
54
|
-
|
|
55
|
-
* **deps-dev:** bump the dependencies group with 5 updates ([e6a00eb](https://github.com/Alwatr/pre-handlers/commit/e6a00eb139f70f2396ecf12b68103b40aa785521)) by @dependabot[bot]
|
|
56
|
-
* update @alwatr/nanolib and @alwatr/nano-build to version 5.5.0; bump @alwatr/type-helper to version 5.4.0 ([1e8b122](https://github.com/Alwatr/pre-handlers/commit/1e8b1228034af44e0d4914f5100d9e564c05a5a6)) by @
|
|
57
|
-
|
|
58
|
-
## [4.9.0](https://github.com/Alwatr/pre-handlers/compare/v4.8.1...v4.9.0) (2025-02-26)
|
|
59
|
-
|
|
60
|
-
### Dependencies update
|
|
61
|
-
|
|
62
|
-
* bump @types/node from 22.13.4 to 22.13.5 and prettier from 3.5.1 to 3.5.2 across multiple packages ([3d55c9a](https://github.com/Alwatr/pre-handlers/commit/3d55c9a4044773fdc8d7c8b635311f2043f48569)) by @alimd
|
|
63
|
-
|
|
64
|
-
## [4.8.1](https://github.com/Alwatr/pre-handlers/compare/v4.8.0...v4.8.1) (2025-02-18)
|
|
65
|
-
|
|
66
|
-
### Dependencies update
|
|
67
|
-
|
|
68
|
-
* **deps-dev:** bump the dependencies group across 1 directory with 11 updates ([9257e08](https://github.com/Alwatr/pre-handlers/commit/9257e08b96f5661a7e13e153b9c71d9dbc08fd18)) by @dependabot[bot]
|
|
69
|
-
* update TypeScript, Prettier, and various dependencies to latest versions ([5c0f752](https://github.com/Alwatr/pre-handlers/commit/5c0f7521851acaabb2466e459754c130d7ebf31b)) by @
|
|
70
|
-
|
|
71
|
-
## [4.8.0](https://github.com/Alwatr/pre-handlers/compare/v4.7.0...v4.8.0) (2024-11-08)
|
|
72
|
-
|
|
73
|
-
**Note:** Version bump only for package @alwatr/pre-handlers
|
|
74
|
-
|
|
75
|
-
## [4.7.0](https://github.com/Alwatr/pre-handlers/compare/v4.6.0...v4.7.0) (2024-11-07)
|
|
76
|
-
|
|
77
|
-
**Note:** Version bump only for package @alwatr/pre-handlers
|
|
78
|
-
|
|
79
|
-
## [4.6.0](https://github.com/Alwatr/pre-handlers/compare/v4.5.2...v4.6.0) (2024-11-07)
|
|
80
|
-
|
|
81
|
-
### Dependencies update
|
|
82
|
-
|
|
83
|
-
* **deps-dev:** bump @types/node in the dependencies group ([9901819](https://github.com/Alwatr/pre-handlers/commit/9901819d0a7fef85736951f354bc1846294bb7fe)) by @dependabot[bot]
|
|
84
|
-
* **deps:** bump @alwatr/nanolib from 5.0.0 to 5.2.1 in the alwatr group ([f06afb7](https://github.com/Alwatr/pre-handlers/commit/f06afb74f363c478ffc5967bafadfa2bc9009129)) by @dependabot[bot]
|
|
85
|
-
|
|
86
|
-
## [4.5.2](https://github.com/Alwatr/pre-handlers/compare/v4.5.1...v4.5.2) (2024-11-02)
|
|
87
|
-
|
|
88
|
-
### Dependencies update
|
|
89
|
-
|
|
90
|
-
* **deps:** bump the alwatr group with 6 updates ([6636bb3](https://github.com/Alwatr/pre-handlers/commit/6636bb307401e28863eb27288d5abbaab2d67e18)) by @dependabot[bot]
|
|
91
|
-
* update ([86fbeb6](https://github.com/Alwatr/pre-handlers/commit/86fbeb663d94452f3596d0894ec19d4c6bed3099)) by @
|
|
92
|
-
|
|
93
|
-
## [4.5.1](https://github.com/Alwatr/pre-handlers/compare/v4.5.0...v4.5.1) (2024-10-28)
|
|
94
|
-
|
|
95
|
-
### Bug Fixes
|
|
96
|
-
|
|
97
|
-
* deps ([fc6724b](https://github.com/Alwatr/pre-handlers/commit/fc6724b3b42fac816982c94128157bb188318243)) by @
|
|
98
|
-
|
|
99
|
-
## [4.5.0](https://github.com/Alwatr/pre-handlers/compare/v4.4.1...v4.5.0) (2024-10-28)
|
|
100
|
-
|
|
101
|
-
### Features
|
|
102
|
-
|
|
103
|
-
* add `pre-handlers` package ([6578a63](https://github.com/Alwatr/pre-handlers/commit/6578a63e1dfd325947352b66d8087c9f0e70c32e)) by @mohammadhonarvar
|
|
104
|
-
* **pre-handlers:** Add getAuthBearer function ([43de511](https://github.com/Alwatr/pre-handlers/commit/43de511f5b7fc74836d3e31ee9f0b9db2d9a4e11)) by @AliMD
|
|
105
|
-
* **pre-handlers:** Add requireAccessToken middleware ([8ed4eb3](https://github.com/Alwatr/pre-handlers/commit/8ed4eb3899b89032acd13095b6c72e2676ff4eaa)) by @AliMD
|
|
106
|
-
|
|
107
|
-
### Bug Fixes
|
|
108
|
-
|
|
109
|
-
* **pre-handlers:** some issues of `review` feedbacks ([72ad94b](https://github.com/Alwatr/pre-handlers/commit/72ad94b37f059a7b765dd8bc3a5216fe53746479)) by @mohammadhonarvar
|
|
110
|
-
|
|
111
|
-
### Code Refactoring
|
|
112
|
-
|
|
113
|
-
* **pre-handlers:** Remove logger module ([70b0357](https://github.com/Alwatr/pre-handlers/commit/70b0357b0accd6ed96c0cdc62099146b36ce2660)) by @AliMD
|
|
114
|
-
* **pre-handlers:** Rename parse-body-as-json.ts to handler/parse-body-as-json.ts ([3d5f756](https://github.com/Alwatr/pre-handlers/commit/3d5f756453be4b40510f70925ffb3954c428a9f1)) by @AliMD
|
|
115
|
-
* **pre-handlers:** Update main.ts exports and add package tracer ([dc29d20](https://github.com/Alwatr/pre-handlers/commit/dc29d20f9f9d415d3cbad51b0ea7b44fbe4c1149)) by @AliMD
|
|
116
|
-
|
|
117
|
-
### Dependencies update
|
|
118
|
-
|
|
119
|
-
* update ([584ebc4](https://github.com/Alwatr/pre-handlers/commit/584ebc4271719fb3ed1e9a185d38c1a44bf35d50)) by @mohammadhonarvar
|
|
120
|
-
* update nanolib v1.4.0 and other deps ([b8e7be7](https://github.com/Alwatr/pre-handlers/commit/b8e7be7b6c58d4f1cbc12593b2d6124f3d19b377)) by @
|
package/dist/main.cjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/** 📦 @alwatr/pre-handlers v4.10.0 */
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/pre-handlers v4.10.0");
|
|
3
|
-
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{getAuthBearer:()=>getAuthBearer,parseBodyAsJson:()=>parseBodyAsJson,requireAccessToken:()=>requireAccessToken});module.exports=__toCommonJS(main_exports);function getAuthBearer(authorizationHeader){const auth=authorizationHeader?.split(" ");if(!auth||auth[0].toLowerCase()!=="bearer"||!auth[1]){return null}return auth[1]}var import_nanotron_api_server=require("@alwatr/nanotron-api-server");async function parseBodyAsJson(){this.logger_.logMethod?.("parseBodyAsJson");const bodyBuffer=await this.getBodyRaw();if(bodyBuffer.length===0){this.logger_.error("parseBodyAsJson","body_required");this.serverResponse.statusCode=import_nanotron_api_server.HttpStatusCodes.Error_Client_422_Unprocessable_Entity;this.serverResponse.replyErrorResponse({ok:false,errorCode:"body_required",errorMessage:"Request body is required."});return}try{this.sharedMeta.body=JSON.parse(bodyBuffer.toString())}catch(error){this.logger_.error("parseBodyAsJson","invalid_body_json",error);this.serverResponse.statusCode=import_nanotron_api_server.HttpStatusCodes.Error_Client_422_Unprocessable_Entity;this.serverResponse.replyErrorResponse({ok:false,errorCode:"invalid_body_json",errorMessage:"Invalid JSON in request body."})}this.logger_.logProperty?.("body",this.sharedMeta.body)}var import_nanotron_api_server2=require("@alwatr/nanotron-api-server");var requireAccessToken=accessToken=>async function requireAccessToken_(){const userToken=getAuthBearer(this.headers.authorization);this.logger_.logMethodArgs?.("requireAccessToken",{userToken});if(userToken===null){this.serverResponse.statusCode=import_nanotron_api_server2.HttpStatusCodes.Error_Client_401_Unauthorized;this.serverResponse.replyErrorResponse({ok:false,errorCode:"authorization_required",errorMessage:"Authorization token required"});return}if(userToken!==accessToken){this.serverResponse.statusCode=import_nanotron_api_server2.HttpStatusCodes.Error_Client_403_Forbidden;this.serverResponse.replyErrorResponse({ok:false,errorCode:"access_denied",errorMessage:"Access denied, token is invalid!"})}};0&&(module.exports={getAuthBearer,parseBodyAsJson,requireAccessToken});
|
|
4
|
-
//# sourceMappingURL=main.cjs.map
|
package/dist/main.cjs.map
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/main.ts", "../src/lib/get-auth-bearer.ts", "../src/handler/parse-body-as-json.ts", "../src/handler/require-access-token.ts"],
|
|
4
|
-
"sourcesContent": ["export * from './lib/get-auth-bearer.js';\nexport * from './handler/parse-body-as-json.js';\nexport * from './handler/require-access-token.js';\n", "/**\n * Extracts the Bearer token from the authorization header.\n *\n * This function takes an optional authorization header string, extracts the Bearer token, and returns it.\n * If the header is invalid or the token is missing, it returns null.\n *\n * @param {string} [authorizationHeader] - The authorization header string.\n * @returns {string | null} The extracted Bearer token or null if the header is invalid.\n *\n * @example\n * ```ts\n * console.log(this.headers.authorization); // 'Bearer myToken123'\n * const token = getAuthBearer(this.headers.authorization);\n * console.log(token); // 'myToken123'\n *\n * const invalidToken = getAuthBearer('Basic myToken123');\n * console.log(invalidToken); // null\n * ```\n */\nexport function getAuthBearer(authorizationHeader?: string): string | null {\n const auth = authorizationHeader?.split(' ');\n if (!auth || auth[0].toLowerCase() !== 'bearer' || !auth[1]) {\n return null;\n }\n return auth[1];\n}\n", "import {HttpStatusCodes} from '@alwatr/nanotron-api-server';\n\nimport type {NanotronClientRequest} from '@alwatr/nanotron-api-server';\nimport type {} from '@alwatr/type-helper';\n\n/**\n * Middleware to parses the request body as JSON and assigns it to `this.sharedMeta.body`.\n * If the body is empty or invalid, it sends an error response,\n * which triggers `terminatedHandlers` and prevents further handlers from executing.\n *\n * @this {NanotronClientRequest<{body: DictionaryOpt}>}\n * @returns {Promise<void>} A promise that resolves when the body is successfully parsed or an error response is sent.\n *\n * @example\n * ```ts\n * nanotronApiServer.defineRoute<{body: DictionaryOpt}>({\n * preHandlers: [parseBodyAsJson],\n * async handler() {\n * const body = this.sharedMeta.body; // json object\n * },\n * });\n * ```\n */\nexport async function parseBodyAsJson(this: NanotronClientRequest<{body?: JsonObject | JsonArray}>): Promise<void> {\n this.logger_.logMethod?.('parseBodyAsJson');\n const bodyBuffer = await this.getBodyRaw();\n\n if (bodyBuffer.length === 0) {\n this.logger_.error('parseBodyAsJson', 'body_required');\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_422_Unprocessable_Entity;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'body_required',\n errorMessage: 'Request body is required.',\n });\n return;\n }\n\n try {\n this.sharedMeta.body = JSON.parse(bodyBuffer.toString()) as DictionaryOpt | JsonArray;\n }\n catch (error) {\n this.logger_.error('parseBodyAsJson', 'invalid_body_json', error);\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_422_Unprocessable_Entity;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'invalid_body_json',\n errorMessage: 'Invalid JSON in request body.',\n });\n }\n\n this.logger_.logProperty?.('body', this.sharedMeta.body);\n}\n", "import {HttpStatusCodes, type NanotronClientRequest} from '@alwatr/nanotron-api-server';\n\nimport {getAuthBearer} from '../lib/get-auth-bearer.js';\n\n/**\n * Middleware to require a valid access token for a Nanotron API request.\n *\n * This function checks the authorization header for a Bearer token and compares it to the provided access token.\n * If the token is missing or invalid, it sends an appropriate error response and prevents further handlers from executing.\n *\n * @param {string} accessToken - The valid access token to compare against.\n * @returns {Function} A middleware function for Nanotron API requests.\n *\n * @example\n * ```ts\n * nanotronApiServer.defineRoute({\n * method: 'POST',\n * url: 'secure-endpoint',\n * preHandlers: [requireAccessToken('mySecretToken')],\n * async handler() {\n * this.serverResponse.replyJson({\n * ok: true,\n * message: 'Access granted!',\n * });\n * },\n * });\n * ```\n */\nexport const requireAccessToken = (accessToken: string) =>\n async function requireAccessToken_(this: NanotronClientRequest): Promise<void> {\n const userToken = getAuthBearer(this.headers.authorization);\n this.logger_.logMethodArgs?.('requireAccessToken', {userToken});\n\n if (userToken === null) {\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_401_Unauthorized;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'authorization_required',\n errorMessage: 'Authorization token required',\n });\n return;\n }\n\n if (userToken !== accessToken) {\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_403_Forbidden;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'access_denied',\n errorMessage: 'Access denied, token is invalid!',\n });\n }\n };\n"],
|
|
5
|
-
"mappings": ";;qqBAAA,qMCmBO,SAAS,cAAc,oBAA6C,CACzE,MAAM,KAAO,qBAAqB,MAAM,GAAG,EAC3C,GAAI,CAAC,MAAQ,KAAK,CAAC,EAAE,YAAY,IAAM,UAAY,CAAC,KAAK,CAAC,EAAG,CAC3D,OAAO,IACT,CACA,OAAO,KAAK,CAAC,CACf,CCzBA,+BAA8B,uCAuB9B,eAAsB,iBAA6F,CACjH,KAAK,QAAQ,YAAY,iBAAiB,EAC1C,MAAM,WAAa,MAAM,KAAK,WAAW,EAEzC,GAAI,WAAW,SAAW,EAAG,CAC3B,KAAK,QAAQ,MAAM,kBAAmB,eAAe,EACrD,KAAK,eAAe,WAAa,2CAAgB,sCACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,MACJ,UAAW,gBACX,aAAc,2BAChB,CAAC,EACD,MACF,CAEA,GAAI,CACF,KAAK,WAAW,KAAO,KAAK,MAAM,WAAW,SAAS,CAAC,CACzD,OACO,MAAO,CACZ,KAAK,QAAQ,MAAM,kBAAmB,oBAAqB,KAAK,EAChE,KAAK,eAAe,WAAa,2CAAgB,sCACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,MACJ,UAAW,oBACX,aAAc,+BAChB,CAAC,CACH,CAEA,KAAK,QAAQ,cAAc,OAAQ,KAAK,WAAW,IAAI,CACzD,CCpDA,IAAAA,4BAA0D,uCA4BnD,IAAM,mBAAsB,aACjC,eAAe,qBAAgE,CAC7E,MAAM,UAAY,cAAc,KAAK,QAAQ,aAAa,EAC1D,KAAK,QAAQ,gBAAgB,qBAAsB,CAAC,SAAS,CAAC,EAE9D,GAAI,YAAc,KAAM,CACtB,KAAK,eAAe,WAAa,4CAAgB,8BACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,MACJ,UAAW,yBACX,aAAc,8BAChB,CAAC,EACD,MACF,CAEA,GAAI,YAAc,YAAa,CAC7B,KAAK,eAAe,WAAa,4CAAgB,2BACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,MACJ,UAAW,gBACX,aAAc,kCAChB,CAAC,CACH,CACF",
|
|
6
|
-
"names": ["import_nanotron_api_server"]
|
|
7
|
-
}
|
package/dist/main.mjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/** 📦 @alwatr/pre-handlers v4.10.0 */
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/pre-handlers v4.10.0");
|
|
3
|
-
function getAuthBearer(authorizationHeader){const auth=authorizationHeader?.split(" ");if(!auth||auth[0].toLowerCase()!=="bearer"||!auth[1]){return null}return auth[1]}import{HttpStatusCodes}from"@alwatr/nanotron-api-server";async function parseBodyAsJson(){this.logger_.logMethod?.("parseBodyAsJson");const bodyBuffer=await this.getBodyRaw();if(bodyBuffer.length===0){this.logger_.error("parseBodyAsJson","body_required");this.serverResponse.statusCode=HttpStatusCodes.Error_Client_422_Unprocessable_Entity;this.serverResponse.replyErrorResponse({ok:false,errorCode:"body_required",errorMessage:"Request body is required."});return}try{this.sharedMeta.body=JSON.parse(bodyBuffer.toString())}catch(error){this.logger_.error("parseBodyAsJson","invalid_body_json",error);this.serverResponse.statusCode=HttpStatusCodes.Error_Client_422_Unprocessable_Entity;this.serverResponse.replyErrorResponse({ok:false,errorCode:"invalid_body_json",errorMessage:"Invalid JSON in request body."})}this.logger_.logProperty?.("body",this.sharedMeta.body)}import{HttpStatusCodes as HttpStatusCodes2}from"@alwatr/nanotron-api-server";var requireAccessToken=accessToken=>async function requireAccessToken_(){const userToken=getAuthBearer(this.headers.authorization);this.logger_.logMethodArgs?.("requireAccessToken",{userToken});if(userToken===null){this.serverResponse.statusCode=HttpStatusCodes2.Error_Client_401_Unauthorized;this.serverResponse.replyErrorResponse({ok:false,errorCode:"authorization_required",errorMessage:"Authorization token required"});return}if(userToken!==accessToken){this.serverResponse.statusCode=HttpStatusCodes2.Error_Client_403_Forbidden;this.serverResponse.replyErrorResponse({ok:false,errorCode:"access_denied",errorMessage:"Access denied, token is invalid!"})}};export{getAuthBearer,parseBodyAsJson,requireAccessToken};
|
|
4
|
-
//# sourceMappingURL=main.mjs.map
|
package/dist/main.mjs.map
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/get-auth-bearer.ts", "../src/handler/parse-body-as-json.ts", "../src/handler/require-access-token.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Extracts the Bearer token from the authorization header.\n *\n * This function takes an optional authorization header string, extracts the Bearer token, and returns it.\n * If the header is invalid or the token is missing, it returns null.\n *\n * @param {string} [authorizationHeader] - The authorization header string.\n * @returns {string | null} The extracted Bearer token or null if the header is invalid.\n *\n * @example\n * ```ts\n * console.log(this.headers.authorization); // 'Bearer myToken123'\n * const token = getAuthBearer(this.headers.authorization);\n * console.log(token); // 'myToken123'\n *\n * const invalidToken = getAuthBearer('Basic myToken123');\n * console.log(invalidToken); // null\n * ```\n */\nexport function getAuthBearer(authorizationHeader?: string): string | null {\n const auth = authorizationHeader?.split(' ');\n if (!auth || auth[0].toLowerCase() !== 'bearer' || !auth[1]) {\n return null;\n }\n return auth[1];\n}\n", "import {HttpStatusCodes} from '@alwatr/nanotron-api-server';\n\nimport type {NanotronClientRequest} from '@alwatr/nanotron-api-server';\nimport type {} from '@alwatr/type-helper';\n\n/**\n * Middleware to parses the request body as JSON and assigns it to `this.sharedMeta.body`.\n * If the body is empty or invalid, it sends an error response,\n * which triggers `terminatedHandlers` and prevents further handlers from executing.\n *\n * @this {NanotronClientRequest<{body: DictionaryOpt}>}\n * @returns {Promise<void>} A promise that resolves when the body is successfully parsed or an error response is sent.\n *\n * @example\n * ```ts\n * nanotronApiServer.defineRoute<{body: DictionaryOpt}>({\n * preHandlers: [parseBodyAsJson],\n * async handler() {\n * const body = this.sharedMeta.body; // json object\n * },\n * });\n * ```\n */\nexport async function parseBodyAsJson(this: NanotronClientRequest<{body?: JsonObject | JsonArray}>): Promise<void> {\n this.logger_.logMethod?.('parseBodyAsJson');\n const bodyBuffer = await this.getBodyRaw();\n\n if (bodyBuffer.length === 0) {\n this.logger_.error('parseBodyAsJson', 'body_required');\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_422_Unprocessable_Entity;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'body_required',\n errorMessage: 'Request body is required.',\n });\n return;\n }\n\n try {\n this.sharedMeta.body = JSON.parse(bodyBuffer.toString()) as DictionaryOpt | JsonArray;\n }\n catch (error) {\n this.logger_.error('parseBodyAsJson', 'invalid_body_json', error);\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_422_Unprocessable_Entity;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'invalid_body_json',\n errorMessage: 'Invalid JSON in request body.',\n });\n }\n\n this.logger_.logProperty?.('body', this.sharedMeta.body);\n}\n", "import {HttpStatusCodes, type NanotronClientRequest} from '@alwatr/nanotron-api-server';\n\nimport {getAuthBearer} from '../lib/get-auth-bearer.js';\n\n/**\n * Middleware to require a valid access token for a Nanotron API request.\n *\n * This function checks the authorization header for a Bearer token and compares it to the provided access token.\n * If the token is missing or invalid, it sends an appropriate error response and prevents further handlers from executing.\n *\n * @param {string} accessToken - The valid access token to compare against.\n * @returns {Function} A middleware function for Nanotron API requests.\n *\n * @example\n * ```ts\n * nanotronApiServer.defineRoute({\n * method: 'POST',\n * url: 'secure-endpoint',\n * preHandlers: [requireAccessToken('mySecretToken')],\n * async handler() {\n * this.serverResponse.replyJson({\n * ok: true,\n * message: 'Access granted!',\n * });\n * },\n * });\n * ```\n */\nexport const requireAccessToken = (accessToken: string) =>\n async function requireAccessToken_(this: NanotronClientRequest): Promise<void> {\n const userToken = getAuthBearer(this.headers.authorization);\n this.logger_.logMethodArgs?.('requireAccessToken', {userToken});\n\n if (userToken === null) {\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_401_Unauthorized;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'authorization_required',\n errorMessage: 'Authorization token required',\n });\n return;\n }\n\n if (userToken !== accessToken) {\n this.serverResponse.statusCode = HttpStatusCodes.Error_Client_403_Forbidden;\n this.serverResponse.replyErrorResponse({\n ok: false,\n errorCode: 'access_denied',\n errorMessage: 'Access denied, token is invalid!',\n });\n }\n };\n"],
|
|
5
|
-
"mappings": ";;AAmBO,SAAS,cAAc,oBAA6C,CACzE,MAAM,KAAO,qBAAqB,MAAM,GAAG,EAC3C,GAAI,CAAC,MAAQ,KAAK,CAAC,EAAE,YAAY,IAAM,UAAY,CAAC,KAAK,CAAC,EAAG,CAC3D,OAAO,IACT,CACA,OAAO,KAAK,CAAC,CACf,CCzBA,OAAQ,oBAAsB,8BAuB9B,eAAsB,iBAA6F,CACjH,KAAK,QAAQ,YAAY,iBAAiB,EAC1C,MAAM,WAAa,MAAM,KAAK,WAAW,EAEzC,GAAI,WAAW,SAAW,EAAG,CAC3B,KAAK,QAAQ,MAAM,kBAAmB,eAAe,EACrD,KAAK,eAAe,WAAa,gBAAgB,sCACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,MACJ,UAAW,gBACX,aAAc,2BAChB,CAAC,EACD,MACF,CAEA,GAAI,CACF,KAAK,WAAW,KAAO,KAAK,MAAM,WAAW,SAAS,CAAC,CACzD,OACO,MAAO,CACZ,KAAK,QAAQ,MAAM,kBAAmB,oBAAqB,KAAK,EAChE,KAAK,eAAe,WAAa,gBAAgB,sCACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,MACJ,UAAW,oBACX,aAAc,+BAChB,CAAC,CACH,CAEA,KAAK,QAAQ,cAAc,OAAQ,KAAK,WAAW,IAAI,CACzD,CCpDA,OAAQ,mBAAAA,qBAAkD,8BA4BnD,IAAM,mBAAsB,aACjC,eAAe,qBAAgE,CAC7E,MAAM,UAAY,cAAc,KAAK,QAAQ,aAAa,EAC1D,KAAK,QAAQ,gBAAgB,qBAAsB,CAAC,SAAS,CAAC,EAE9D,GAAI,YAAc,KAAM,CACtB,KAAK,eAAe,WAAaC,iBAAgB,8BACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,MACJ,UAAW,yBACX,aAAc,8BAChB,CAAC,EACD,MACF,CAEA,GAAI,YAAc,YAAa,CAC7B,KAAK,eAAe,WAAaA,iBAAgB,2BACjD,KAAK,eAAe,mBAAmB,CACrC,GAAI,MACJ,UAAW,gBACX,aAAc,kCAChB,CAAC,CACH,CACF",
|
|
6
|
-
"names": ["HttpStatusCodes", "HttpStatusCodes"]
|
|
7
|
-
}
|