@shamodha/jwt-security-kit 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,127 @@
1
+ # JWT Security Kit
2
+
3
+ A lightweight, zero-boilerplate, type-safe JWT security and RBAC middleware toolkit designed specifically for Express applications.
4
+
5
+ ---
6
+
7
+ ## Features
8
+
9
+ * **Type-Safe Roles**: Automatically infers strongly typed role maps from your configuration file.
10
+ * **Flexible Extractors**: Extract tokens seamlessly from authorization headers, cookies, or request bodies[cite: 3].
11
+ * **Zero Boilerplate**: Simple initialization using a centralized configuration file via CLI.
12
+ * **Dual Format Support**: Full support for both CommonJS and ES Modules.
13
+
14
+ ---
15
+
16
+ ## Installation
17
+
18
+ Install the package alongside its peer dependencies:
19
+
20
+ ```bash
21
+ npm install jwt-security-kit express
22
+ ```
23
+
24
+
25
+ ## Quick Start
26
+
27
+ ### 1. Initialize Configuration
28
+
29
+ Generate your security configuration file automatically using the built-in CLI:
30
+
31
+ ```bash
32
+ npx jwt-security-kit init
33
+ ```
34
+
35
+ This creates a jwt.security.config.ts (or .js with --js) file in your project root:
36
+
37
+ ```TypeScript
38
+ import { defineConfig, Extractors } from 'jwt-security-kit';
39
+
40
+ export default defineConfig({
41
+ // Secret configuration for access tokens (can be a raw string/buffer or an object with expiry)
42
+ secret: {
43
+ key: process.env.JWT_SECRET || 'your-super-secret-key',
44
+ exp: '15m' // Access token expiration (e.g., '15m', '1h', or seconds as a number)
45
+ },
46
+
47
+ // Optional: Separate secret configuration for refresh tokens
48
+ refreshSecret: {
49
+ key: process.env.JWT_REFRESH_SECRET || 'your-refresh-secret-key',
50
+ exp: '7d' // Refresh token expiration
51
+ },
52
+
53
+ // Define your application roles (fully type-safe)
54
+ roles: ['user', 'admin', 'manager'] as const,
55
+
56
+ // Custom request property name where decoded user payload will be attached (default: 'user')
57
+ userProperty: 'user',
58
+
59
+ // Custom property name inside the JWT payload used for RBAC checks (default: 'role')
60
+ roleProperty: 'role',
61
+
62
+ // Allowed cryptographic algorithms for token verification (default: ['HS256'])
63
+ algorithms: ['HS256'],
64
+
65
+ // Custom token extractors array (defaults to checking the Authorization header)[cite: 3]
66
+ extractors: [
67
+ Extractors.fromHeader('authorization'), // Checks 'Authorization: Bearer <token>'[cite: 3]
68
+ Extractors.fromCookie('access_token'), // Checks cookies[cite: 3]
69
+ Extractors.fromBody('token') // Checks request body[cite: 3]
70
+ ]
71
+ });
72
+ ```
73
+
74
+ ## 2. Setup Express Server
75
+ Integrate the security kit into your application server:
76
+
77
+ ```TypeScript
78
+ import express, { type Response } from "express"
79
+ import { createSecurityKit, type GuardedRequest } from "jwt-security-kit"
80
+ import securityConfig from "./jwt.security.config"
81
+
82
+ const app = express()
83
+ app.use(express.json())
84
+
85
+ const security = createSecurityKit(securityConfig)
86
+
87
+ // Example login route generating a token
88
+ app.post("/login", (req, res) => {
89
+ const token = security.generateToken({
90
+ sub: "123",
91
+ role: security.Role.ADMIN
92
+ })
93
+ res.json({ accessToken: token })
94
+ })
95
+
96
+ // Protected route utilizing guard and role-based access control
97
+ app.get(
98
+ "/dashboard",
99
+ security.guard(),
100
+ security.requireRole([security.Role.ADMIN]),
101
+ (req: GuardedRequest, res: Response) => {
102
+ res.json({ success: true, user: req.user })
103
+ }
104
+ )
105
+
106
+ app.listen(3000, () => console.log("Server running on port 3000"))
107
+ ```
108
+
109
+ CLI CommandsInitialize a default configuration template interactively:
110
+ TypeScript (Default):
111
+ ```bash
112
+ npx jwt-security-kit init
113
+ ```
114
+ JavaScript:
115
+ ```bash
116
+ npx jwt-security-kit init --js
117
+ ```
118
+
119
+ # License
120
+ This project is licensed under the MIT License.
121
+
122
+ ```bash
123
+ MIT © Shamodha Sahan
124
+ ```
125
+
126
+
127
+ <!--Sh208978$%dc -->
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli.ts
27
+ var fs = __toESM(require("fs"));
28
+ var path = __toESM(require("path"));
29
+ var args = process.argv.slice(2);
30
+ var command = args[0];
31
+ if (command === "init") {
32
+ const flags = args.slice(1);
33
+ const isJavaScript = flags.includes("--js") || flags.includes("-j");
34
+ const ext = isJavaScript ? "js" : "ts";
35
+ const fileName = `jwt.security.config.${ext}`;
36
+ const filePath = path.join(process.cwd(), fileName);
37
+ const template = isJavaScript ? `const { defineConfig } = require('jwt-security-kit');
38
+
39
+ module.exports = defineConfig({
40
+ secret: {
41
+ key: process.env.JWT_SECRET || 'your-super-secret-key',
42
+ exp: '15m'
43
+ },
44
+ roles: ['user', 'admin']
45
+ });
46
+ ` : `import { defineConfig } from 'jwt-security-kit';
47
+
48
+ export default defineConfig({
49
+ secret: {
50
+ key: process.env.JWT_SECRET || 'your-super-secret-key',
51
+ exp: '15m'
52
+ },
53
+ roles: ['user', 'admin'] as const
54
+ });
55
+ `;
56
+ if (fs.existsSync(filePath)) {
57
+ console.log(`\u26A0\uFE0F Configuration file already exists at: ${fileName}`);
58
+ process.exit(1);
59
+ }
60
+ try {
61
+ fs.writeFileSync(filePath, template, "utf8");
62
+ console.log(`\u2728 Successfully created ${fileName} in your project root!`);
63
+ } catch (err) {
64
+ console.error("\u274C Failed to create configuration file:", err);
65
+ process.exit(1);
66
+ }
67
+ } else {
68
+ console.log("Unknown command. Use: npx jwt-security-kit init [--js]");
69
+ }
70
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\r\nimport * as fs from \"fs\"\r\nimport * as path from \"path\"\r\n\r\nconst args = process.argv.slice(2)\r\nconst command = args[0]\r\n\r\nif (command === \"init\") {\r\n const flags = args.slice(1)\r\n const isJavaScript = flags.includes(\"--js\") || flags.includes(\"-j\")\r\n\r\n const ext = isJavaScript ? \"js\" : \"ts\"\r\n const fileName = `jwt.security.config.${ext}`\r\n const filePath = path.join(process.cwd(), fileName)\r\n\r\n const template = isJavaScript\r\n ? `const { defineConfig } = require('jwt-security-kit');\r\n\r\nmodule.exports = defineConfig({\r\n secret: {\r\n key: process.env.JWT_SECRET || 'your-super-secret-key',\r\n exp: '15m'\r\n },\r\n roles: ['user', 'admin']\r\n});\r\n`\r\n : `import { defineConfig } from 'jwt-security-kit';\r\n\r\nexport default defineConfig({\r\n secret: {\r\n key: process.env.JWT_SECRET || 'your-super-secret-key',\r\n exp: '15m'\r\n },\r\n roles: ['user', 'admin'] as const\r\n});\r\n`\r\n\r\n if (fs.existsSync(filePath)) {\r\n console.log(`⚠️ Configuration file already exists at: ${fileName}`)\r\n process.exit(1)\r\n }\r\n\r\n try {\r\n fs.writeFileSync(filePath, template, \"utf8\")\r\n console.log(`✨ Successfully created ${fileName} in your project root!`)\r\n } catch (err) {\r\n console.error(\"❌ Failed to create configuration file:\", err)\r\n process.exit(1)\r\n }\r\n} else {\r\n console.log(\"Unknown command. Use: npx jwt-security-kit init [--js]\")\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAoB;AACpB,WAAsB;AAEtB,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,IAAM,UAAU,KAAK,CAAC;AAEtB,IAAI,YAAY,QAAQ;AACtB,QAAM,QAAQ,KAAK,MAAM,CAAC;AAC1B,QAAM,eAAe,MAAM,SAAS,MAAM,KAAK,MAAM,SAAS,IAAI;AAElE,QAAM,MAAM,eAAe,OAAO;AAClC,QAAM,WAAW,uBAAuB,GAAG;AAC3C,QAAM,WAAgB,UAAK,QAAQ,IAAI,GAAG,QAAQ;AAElD,QAAM,WAAW,eACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAUA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWJ,MAAO,cAAW,QAAQ,GAAG;AAC3B,YAAQ,IAAI,sDAA4C,QAAQ,EAAE;AAClE,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,MAAI;AACF,IAAG,iBAAc,UAAU,UAAU,MAAM;AAC3C,YAAQ,IAAI,+BAA0B,QAAQ,wBAAwB;AAAA,EACxE,SAAS,KAAK;AACZ,YAAQ,MAAM,+CAA0C,GAAG;AAC3D,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,OAAO;AACL,UAAQ,IAAI,wDAAwD;AACtE;","names":[]}
package/dist/cli.mjs ADDED
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import * as fs from "fs";
5
+ import * as path from "path";
6
+ var args = process.argv.slice(2);
7
+ var command = args[0];
8
+ if (command === "init") {
9
+ const flags = args.slice(1);
10
+ const isJavaScript = flags.includes("--js") || flags.includes("-j");
11
+ const ext = isJavaScript ? "js" : "ts";
12
+ const fileName = `jwt.security.config.${ext}`;
13
+ const filePath = path.join(process.cwd(), fileName);
14
+ const template = isJavaScript ? `const { defineConfig } = require('jwt-security-kit');
15
+
16
+ module.exports = defineConfig({
17
+ secret: {
18
+ key: process.env.JWT_SECRET || 'your-super-secret-key',
19
+ exp: '15m'
20
+ },
21
+ roles: ['user', 'admin']
22
+ });
23
+ ` : `import { defineConfig } from 'jwt-security-kit';
24
+
25
+ export default defineConfig({
26
+ secret: {
27
+ key: process.env.JWT_SECRET || 'your-super-secret-key',
28
+ exp: '15m'
29
+ },
30
+ roles: ['user', 'admin'] as const
31
+ });
32
+ `;
33
+ if (fs.existsSync(filePath)) {
34
+ console.log(`\u26A0\uFE0F Configuration file already exists at: ${fileName}`);
35
+ process.exit(1);
36
+ }
37
+ try {
38
+ fs.writeFileSync(filePath, template, "utf8");
39
+ console.log(`\u2728 Successfully created ${fileName} in your project root!`);
40
+ } catch (err) {
41
+ console.error("\u274C Failed to create configuration file:", err);
42
+ process.exit(1);
43
+ }
44
+ } else {
45
+ console.log("Unknown command. Use: npx jwt-security-kit init [--js]");
46
+ }
47
+ //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\r\nimport * as fs from \"fs\"\r\nimport * as path from \"path\"\r\n\r\nconst args = process.argv.slice(2)\r\nconst command = args[0]\r\n\r\nif (command === \"init\") {\r\n const flags = args.slice(1)\r\n const isJavaScript = flags.includes(\"--js\") || flags.includes(\"-j\")\r\n\r\n const ext = isJavaScript ? \"js\" : \"ts\"\r\n const fileName = `jwt.security.config.${ext}`\r\n const filePath = path.join(process.cwd(), fileName)\r\n\r\n const template = isJavaScript\r\n ? `const { defineConfig } = require('jwt-security-kit');\r\n\r\nmodule.exports = defineConfig({\r\n secret: {\r\n key: process.env.JWT_SECRET || 'your-super-secret-key',\r\n exp: '15m'\r\n },\r\n roles: ['user', 'admin']\r\n});\r\n`\r\n : `import { defineConfig } from 'jwt-security-kit';\r\n\r\nexport default defineConfig({\r\n secret: {\r\n key: process.env.JWT_SECRET || 'your-super-secret-key',\r\n exp: '15m'\r\n },\r\n roles: ['user', 'admin'] as const\r\n});\r\n`\r\n\r\n if (fs.existsSync(filePath)) {\r\n console.log(`⚠️ Configuration file already exists at: ${fileName}`)\r\n process.exit(1)\r\n }\r\n\r\n try {\r\n fs.writeFileSync(filePath, template, \"utf8\")\r\n console.log(`✨ Successfully created ${fileName} in your project root!`)\r\n } catch (err) {\r\n console.error(\"❌ Failed to create configuration file:\", err)\r\n process.exit(1)\r\n }\r\n} else {\r\n console.log(\"Unknown command. Use: npx jwt-security-kit init [--js]\")\r\n}\r\n"],"mappings":";;;AACA,YAAY,QAAQ;AACpB,YAAY,UAAU;AAEtB,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,IAAM,UAAU,KAAK,CAAC;AAEtB,IAAI,YAAY,QAAQ;AACtB,QAAM,QAAQ,KAAK,MAAM,CAAC;AAC1B,QAAM,eAAe,MAAM,SAAS,MAAM,KAAK,MAAM,SAAS,IAAI;AAElE,QAAM,MAAM,eAAe,OAAO;AAClC,QAAM,WAAW,uBAAuB,GAAG;AAC3C,QAAM,WAAgB,UAAK,QAAQ,IAAI,GAAG,QAAQ;AAElD,QAAM,WAAW,eACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAUA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWJ,MAAO,cAAW,QAAQ,GAAG;AAC3B,YAAQ,IAAI,sDAA4C,QAAQ,EAAE;AAClE,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,MAAI;AACF,IAAG,iBAAc,UAAU,UAAU,MAAM;AAC3C,YAAQ,IAAI,+BAA0B,QAAQ,wBAAwB;AAAA,EACxE,SAAS,KAAK;AACZ,YAAQ,MAAM,+CAA0C,GAAG;AAC3D,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,OAAO;AACL,UAAQ,IAAI,wDAAwD;AACtE;","names":[]}
@@ -0,0 +1,6 @@
1
+ import type { TokenExtractor } from "./types";
2
+ export declare const Extractors: {
3
+ fromHeader: (headerName?: string) => TokenExtractor;
4
+ fromCookie: (cookieName: string) => TokenExtractor;
5
+ fromBody: (fieldName: string) => TokenExtractor;
6
+ };
@@ -0,0 +1,14 @@
1
+ import type { Response, NextFunction } from "express";
2
+ import jwt from "jsonwebtoken";
3
+ import type { SecurityKitConfig, GuardedRequest, RoleMap } from "./types";
4
+ export declare function createSecurityKit<const T extends readonly string[]>(config: SecurityKitConfig<T>): {
5
+ Role: Readonly<RoleMap<T>>;
6
+ generateToken: (payload: string | object | Buffer) => string;
7
+ generateRefreshToken: (payload: string | object | Buffer) => string;
8
+ verifyRefreshToken: (token: string) => string | jwt.JwtPayload;
9
+ guard: () => (req: GuardedRequest, res: Response, next: NextFunction) => void;
10
+ requireRole: (requiredRoles?: T[number][]) => (req: GuardedRequest, res: Response, next: NextFunction) => void;
11
+ };
12
+ export declare function defineConfig<const T extends readonly string[]>(config: SecurityKitConfig<T>): SecurityKitConfig<T>;
13
+ export { Extractors } from "./extractors";
14
+ export type { SecurityKitConfig, GuardedRequest, TokenExtractor, SecretConfig, RoleMap } from "./types";
package/dist/index.js ADDED
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ Extractors: () => Extractors,
34
+ createSecurityKit: () => createSecurityKit,
35
+ defineConfig: () => defineConfig
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+ var import_jsonwebtoken = __toESM(require("jsonwebtoken"));
39
+
40
+ // src/extractors.ts
41
+ var Extractors = {
42
+ fromHeader: (headerName = "authorization") => {
43
+ return (req) => {
44
+ const header = req.headers[headerName.toLowerCase()];
45
+ if (typeof header === "string" && header.startsWith("Bearer ")) {
46
+ return header.split(" ")[1];
47
+ }
48
+ return typeof header === "string" ? header : null;
49
+ };
50
+ },
51
+ fromCookie: (cookieName) => {
52
+ return (req) => req.cookies ? req.cookies[cookieName] || null : null;
53
+ },
54
+ fromBody: (fieldName) => {
55
+ return (req) => req.body ? req.body[fieldName] || null : null;
56
+ }
57
+ };
58
+
59
+ // src/index.ts
60
+ function createSecurityKit(config) {
61
+ if (!config.secret) throw new Error("FATAL: SecurityKit requires a secret.");
62
+ const secretCfg = typeof config.secret === "object" && config.secret !== null && "key" in config.secret ? config.secret : { key: config.secret };
63
+ const secret = secretCfg.key;
64
+ const accessExp = secretCfg.exp || "15m";
65
+ let refreshSecret;
66
+ let refreshExp = "7d";
67
+ if (config.refreshSecret) {
68
+ const refreshCfg = typeof config.refreshSecret === "object" && config.refreshSecret !== null && "key" in config.refreshSecret ? config.refreshSecret : { key: config.refreshSecret };
69
+ refreshSecret = refreshCfg.key;
70
+ refreshExp = refreshCfg.exp || "7d";
71
+ }
72
+ const userProp = config.userProperty || "user";
73
+ const roleProp = config.roleProperty || "role";
74
+ const algorithms = config.algorithms || ["HS256"];
75
+ const extractors = config.extractors?.length ? config.extractors : [Extractors.fromHeader()];
76
+ const rolesArray = config.roles || ["user", "admin"];
77
+ const Role = Object.freeze(
78
+ rolesArray.reduce((acc, role) => {
79
+ ;
80
+ acc[role.toUpperCase()] = role;
81
+ return acc;
82
+ }, {})
83
+ );
84
+ const signOpts = { expiresIn: accessExp };
85
+ const refreshSignOpts = { expiresIn: refreshExp };
86
+ const verifyOpts = { algorithms };
87
+ return {
88
+ Role,
89
+ generateToken: (payload) => {
90
+ return import_jsonwebtoken.default.sign(payload, secret, signOpts);
91
+ },
92
+ generateRefreshToken: (payload) => {
93
+ if (!refreshSecret) throw new Error("Refresh secret is not configured.");
94
+ return import_jsonwebtoken.default.sign(payload, refreshSecret, refreshSignOpts);
95
+ },
96
+ verifyRefreshToken: (token) => {
97
+ if (!refreshSecret) throw new Error("Refresh secret is not configured.");
98
+ return import_jsonwebtoken.default.verify(token, refreshSecret, verifyOpts);
99
+ },
100
+ guard: () => (req, res, next) => {
101
+ let token = null;
102
+ for (const extractor of extractors) {
103
+ if (token = extractor(req)) break;
104
+ }
105
+ if (!token) {
106
+ res.status(401).json({ error: "Unauthorized: No token provided" });
107
+ return;
108
+ }
109
+ try {
110
+ req[userProp] = import_jsonwebtoken.default.verify(token, secret, verifyOpts);
111
+ next();
112
+ } catch (err) {
113
+ const msg = err instanceof import_jsonwebtoken.default.TokenExpiredError ? "Token expired" : "Invalid token";
114
+ res.status(401).json({ error: `Unauthorized: ${msg}` });
115
+ }
116
+ },
117
+ requireRole: (requiredRoles = Object.values(Role)) => {
118
+ return (req, res, next) => {
119
+ const user = req[userProp];
120
+ if (!user) {
121
+ res.status(401).json({ error: "Unauthorized: Authentication required" });
122
+ return;
123
+ }
124
+ const userRole = user[roleProp];
125
+ if (!userRole || !requiredRoles.includes(userRole)) {
126
+ res.status(403).json({ error: "Forbidden: Insufficient permissions" });
127
+ return;
128
+ }
129
+ next();
130
+ };
131
+ }
132
+ };
133
+ }
134
+ function defineConfig(config) {
135
+ return config;
136
+ }
137
+ // Annotate the CommonJS export names for ESM import in node:
138
+ 0 && (module.exports = {
139
+ Extractors,
140
+ createSecurityKit,
141
+ defineConfig
142
+ });
143
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/extractors.ts"],"sourcesContent":["import type { Response, NextFunction } from \"express\"\r\nimport jwt from \"jsonwebtoken\"\r\nimport type {\r\n SecurityKitConfig,\r\n GuardedRequest,\r\n RoleMap,\r\n SecretConfig\r\n} from \"./types\"\r\nimport { Extractors } from \"./extractors\"\r\n\r\nexport function createSecurityKit<const T extends readonly string[]>(\r\n config: SecurityKitConfig<T>\r\n) {\r\n if (!config.secret) throw new Error(\"FATAL: SecurityKit requires a secret.\")\r\n\r\n const secretCfg: SecretConfig =\r\n typeof config.secret === \"object\" &&\r\n config.secret !== null &&\r\n \"key\" in config.secret\r\n ? config.secret\r\n : { key: config.secret }\r\n\r\n const secret = secretCfg.key\r\n const accessExp: string | number = secretCfg.exp || \"15m\"\r\n\r\n let refreshSecret: string | Buffer | undefined\r\n let refreshExp: string | number = \"7d\"\r\n\r\n if (config.refreshSecret) {\r\n const refreshCfg: SecretConfig =\r\n typeof config.refreshSecret === \"object\" &&\r\n config.refreshSecret !== null &&\r\n \"key\" in config.refreshSecret\r\n ? config.refreshSecret\r\n : { key: config.refreshSecret }\r\n\r\n refreshSecret = refreshCfg.key\r\n refreshExp = refreshCfg.exp || \"7d\"\r\n }\r\n\r\n const userProp = config.userProperty || \"user\"\r\n const roleProp = config.roleProperty || \"role\"\r\n const algorithms = config.algorithms || [\"HS256\"]\r\n const extractors = config.extractors?.length\r\n ? config.extractors\r\n : [Extractors.fromHeader()]\r\n\r\n const rolesArray = config.roles || ([\"user\", \"admin\"] as unknown as T)\r\n\r\n const Role = Object.freeze(\r\n rolesArray.reduce((acc, role) => {\r\n ;(acc as any)[role.toUpperCase()] = role\r\n return acc\r\n }, {} as RoleMap<T>)\r\n )\r\n\r\n const signOpts: jwt.SignOptions = { expiresIn: accessExp as any }\r\n const refreshSignOpts: jwt.SignOptions = { expiresIn: refreshExp as any }\r\n const verifyOpts: jwt.VerifyOptions = { algorithms }\r\n\r\n return {\r\n Role,\r\n\r\n generateToken: (payload: string | object | Buffer): string => {\r\n return jwt.sign(payload, secret, signOpts)\r\n },\r\n\r\n generateRefreshToken: (payload: string | object | Buffer): string => {\r\n if (!refreshSecret) throw new Error(\"Refresh secret is not configured.\")\r\n return jwt.sign(payload, refreshSecret, refreshSignOpts)\r\n },\r\n\r\n verifyRefreshToken: (token: string): string | jwt.JwtPayload => {\r\n if (!refreshSecret) throw new Error(\"Refresh secret is not configured.\")\r\n return jwt.verify(token, refreshSecret, verifyOpts)\r\n },\r\n\r\n guard:\r\n () =>\r\n (req: GuardedRequest, res: Response, next: NextFunction): void => {\r\n let token: string | null = null\r\n for (const extractor of extractors) {\r\n if ((token = extractor(req))) break\r\n }\r\n\r\n if (!token) {\r\n res.status(401).json({ error: \"Unauthorized: No token provided\" })\r\n return\r\n }\r\n\r\n try {\r\n req[userProp] = jwt.verify(token, secret, verifyOpts)\r\n next()\r\n } catch (err) {\r\n const msg =\r\n err instanceof jwt.TokenExpiredError\r\n ? \"Token expired\"\r\n : \"Invalid token\"\r\n res.status(401).json({ error: `Unauthorized: ${msg}` })\r\n }\r\n },\r\n\r\n requireRole: (\r\n requiredRoles: T[number][] = Object.values(Role) as T[number][]\r\n ) => {\r\n return (req: GuardedRequest, res: Response, next: NextFunction): void => {\r\n const user = req[userProp]\r\n\r\n if (!user) {\r\n res\r\n .status(401)\r\n .json({ error: \"Unauthorized: Authentication required\" })\r\n return\r\n }\r\n\r\n const userRole = user[roleProp]\r\n if (!userRole || !requiredRoles.includes(userRole)) {\r\n res.status(403).json({ error: \"Forbidden: Insufficient permissions\" })\r\n return\r\n }\r\n next()\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport function defineConfig<const T extends readonly string[]>(\r\n config: SecurityKitConfig<T>\r\n): SecurityKitConfig<T> {\r\n return config\r\n}\r\n\r\nexport { Extractors } from \"./extractors\"\r\nexport type {\r\n SecurityKitConfig,\r\n GuardedRequest,\r\n TokenExtractor,\r\n SecretConfig,\r\n RoleMap\r\n} from \"./types\"\r\n","import type { TokenExtractor } from \"./types\"\r\n\r\nexport const Extractors = {\r\n fromHeader: (headerName = \"authorization\"): TokenExtractor => {\r\n return (req) => {\r\n const header = req.headers[headerName.toLowerCase()]\r\n if (typeof header === \"string\" && header.startsWith(\"Bearer \")) {\r\n return header.split(\" \")[1]\r\n }\r\n return typeof header === \"string\" ? header : null\r\n }\r\n },\r\n fromCookie: (cookieName: string): TokenExtractor => {\r\n return (req) => (req.cookies ? req.cookies[cookieName] || null : null)\r\n },\r\n fromBody: (fieldName: string): TokenExtractor => {\r\n return (req) => (req.body ? req.body[fieldName] || null : null)\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,0BAAgB;;;ACCT,IAAM,aAAa;AAAA,EACxB,YAAY,CAAC,aAAa,oBAAoC;AAC5D,WAAO,CAAC,QAAQ;AACd,YAAM,SAAS,IAAI,QAAQ,WAAW,YAAY,CAAC;AACnD,UAAI,OAAO,WAAW,YAAY,OAAO,WAAW,SAAS,GAAG;AAC9D,eAAO,OAAO,MAAM,GAAG,EAAE,CAAC;AAAA,MAC5B;AACA,aAAO,OAAO,WAAW,WAAW,SAAS;AAAA,IAC/C;AAAA,EACF;AAAA,EACA,YAAY,CA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AE,KAAK,EAAE,OAAO,sCAAsC,CAAC;AACrE;AAAA,QACF;AACA,aAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,aACd,QACsB;AACtB,SAAO;AACT;","names":["jwt"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,106 @@
1
+ // src/index.ts
2
+ import jwt from "jsonwebtoken";
3
+
4
+ // src/extractors.ts
5
+ var Extractors = {
6
+ fromHeader: (headerName = "authorization") => {
7
+ return (req) => {
8
+ const header = req.headers[headerName.toLowerCase()];
9
+ if (typeof header === "string" && header.startsWith("Bearer ")) {
10
+ return header.split(" ")[1];
11
+ }
12
+ return typeof header === "string" ? header : null;
13
+ };
14
+ },
15
+ fromCookie: (cookieName) => {
16
+ return (req) => req.cookies ? req.cookies[cookieName] || null : null;
17
+ },
18
+ fromBody: (fieldName) => {
19
+ return (req) => req.body ? req.body[fieldName] || null : null;
20
+ }
21
+ };
22
+
23
+ // src/index.ts
24
+ function createSecurityKit(config) {
25
+ if (!config.secret) throw new Error("FATAL: SecurityKit requires a secret.");
26
+ const secretCfg = typeof config.secret === "object" && config.secret !== null && "key" in config.secret ? config.secret : { key: config.secret };
27
+ const secret = secretCfg.key;
28
+ const accessExp = secretCfg.exp || "15m";
29
+ let refreshSecret;
30
+ let refreshExp = "7d";
31
+ if (config.refreshSecret) {
32
+ const refreshCfg = typeof config.refreshSecret === "object" && config.refreshSecret !== null && "key" in config.refreshSecret ? config.refreshSecret : { key: config.refreshSecret };
33
+ refreshSecret = refreshCfg.key;
34
+ refreshExp = refreshCfg.exp || "7d";
35
+ }
36
+ const userProp = config.userProperty || "user";
37
+ const roleProp = config.roleProperty || "role";
38
+ const algorithms = config.algorithms || ["HS256"];
39
+ const extractors = config.extractors?.length ? config.extractors : [Extractors.fromHeader()];
40
+ const rolesArray = config.roles || ["user", "admin"];
41
+ const Role = Object.freeze(
42
+ rolesArray.reduce((acc, role) => {
43
+ ;
44
+ acc[role.toUpperCase()] = role;
45
+ return acc;
46
+ }, {})
47
+ );
48
+ const signOpts = { expiresIn: accessExp };
49
+ const refreshSignOpts = { expiresIn: refreshExp };
50
+ const verifyOpts = { algorithms };
51
+ return {
52
+ Role,
53
+ generateToken: (payload) => {
54
+ return jwt.sign(payload, secret, signOpts);
55
+ },
56
+ generateRefreshToken: (payload) => {
57
+ if (!refreshSecret) throw new Error("Refresh secret is not configured.");
58
+ return jwt.sign(payload, refreshSecret, refreshSignOpts);
59
+ },
60
+ verifyRefreshToken: (token) => {
61
+ if (!refreshSecret) throw new Error("Refresh secret is not configured.");
62
+ return jwt.verify(token, refreshSecret, verifyOpts);
63
+ },
64
+ guard: () => (req, res, next) => {
65
+ let token = null;
66
+ for (const extractor of extractors) {
67
+ if (token = extractor(req)) break;
68
+ }
69
+ if (!token) {
70
+ res.status(401).json({ error: "Unauthorized: No token provided" });
71
+ return;
72
+ }
73
+ try {
74
+ req[userProp] = jwt.verify(token, secret, verifyOpts);
75
+ next();
76
+ } catch (err) {
77
+ const msg = err instanceof jwt.TokenExpiredError ? "Token expired" : "Invalid token";
78
+ res.status(401).json({ error: `Unauthorized: ${msg}` });
79
+ }
80
+ },
81
+ requireRole: (requiredRoles = Object.values(Role)) => {
82
+ return (req, res, next) => {
83
+ const user = req[userProp];
84
+ if (!user) {
85
+ res.status(401).json({ error: "Unauthorized: Authentication required" });
86
+ return;
87
+ }
88
+ const userRole = user[roleProp];
89
+ if (!userRole || !requiredRoles.includes(userRole)) {
90
+ res.status(403).json({ error: "Forbidden: Insufficient permissions" });
91
+ return;
92
+ }
93
+ next();
94
+ };
95
+ }
96
+ };
97
+ }
98
+ function defineConfig(config) {
99
+ return config;
100
+ }
101
+ export {
102
+ Extractors,
103
+ createSecurityKit,
104
+ defineConfig
105
+ };
106
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/extractors.ts"],"sourcesContent":["import type { Response, NextFunction } from \"express\"\r\nimport jwt from \"jsonwebtoken\"\r\nimport type {\r\n SecurityKitConfig,\r\n GuardedRequest,\r\n RoleMap,\r\n SecretConfig\r\n} from \"./types\"\r\nimport { Extractors } from \"./extractors\"\r\n\r\nexport function createSecurityKit<const T extends readonly string[]>(\r\n config: SecurityKitConfig<T>\r\n) {\r\n if (!config.secret) throw new Error(\"FATAL: SecurityKit requires a secret.\")\r\n\r\n const secretCfg: SecretConfig =\r\n typeof config.secret === \"object\" &&\r\n config.secret !== null &&\r\n \"key\" in config.secret\r\n ? config.secret\r\n : { key: config.secret }\r\n\r\n const secret = secretCfg.key\r\n const accessExp: string | number = secretCfg.exp || \"15m\"\r\n\r\n let refreshSecret: string | Buffer | undefined\r\n let refreshExp: string | number = \"7d\"\r\n\r\n if (config.refreshSecret) {\r\n const refreshCfg: SecretConfig =\r\n typeof config.refreshSecret === \"object\" &&\r\n config.refreshSecret !== null &&\r\n \"key\" in config.refreshSecret\r\n ? config.refreshSecret\r\n : { key: config.refreshSecret }\r\n\r\n refreshSecret = refreshCfg.key\r\n refreshExp = refreshCfg.exp || \"7d\"\r\n }\r\n\r\n const userProp = config.userProperty || \"user\"\r\n const roleProp = config.roleProperty || \"role\"\r\n const algorithms = config.algorithms || [\"HS256\"]\r\n const extractors = config.extractors?.length\r\n ? config.extractors\r\n : [Extractors.fromHeader()]\r\n\r\n const rolesArray = config.roles || ([\"user\", \"admin\"] as unknown as T)\r\n\r\n const Role = Object.freeze(\r\n rolesArray.reduce((acc, role) => {\r\n ;(acc as any)[role.toUpperCase()] = role\r\n return acc\r\n }, {} as RoleMap<T>)\r\n )\r\n\r\n const signOpts: jwt.SignOptions = { expiresIn: accessExp as any }\r\n const refreshSignOpts: jwt.SignOptions = { expiresIn: refreshExp as any }\r\n const verifyOpts: jwt.VerifyOptions = { algorithms }\r\n\r\n return {\r\n Role,\r\n\r\n generateToken: (payload: string | object | Buffer): string => {\r\n return jwt.sign(payload, secret, signOpts)\r\n },\r\n\r\n generateRefreshToken: (payload: string | object | Buffer): string => {\r\n if (!refreshSecret) throw new Error(\"Refresh secret is not configured.\")\r\n return jwt.sign(payload, refreshSecret, refreshSignOpts)\r\n },\r\n\r\n verifyRefreshToken: (token: string): string | jwt.JwtPayload => {\r\n if (!refreshSecret) throw new Error(\"Refresh secret is not configured.\")\r\n return jwt.verify(token, refreshSecret, verifyOpts)\r\n },\r\n\r\n guard:\r\n () =>\r\n (req: GuardedRequest, res: Response, next: NextFunction): void => {\r\n let token: string | null = null\r\n for (const extractor of extractors) {\r\n if ((token = extractor(req))) break\r\n }\r\n\r\n if (!token) {\r\n res.status(401).json({ error: \"Unauthorized: No token provided\" })\r\n return\r\n }\r\n\r\n try {\r\n req[userProp] = jwt.verify(token, secret, verifyOpts)\r\n next()\r\n } catch (err) {\r\n const msg =\r\n err instanceof jwt.TokenExpiredError\r\n ? \"Token expired\"\r\n : \"Invalid token\"\r\n res.status(401).json({ error: `Unauthorized: ${msg}` })\r\n }\r\n },\r\n\r\n requireRole: (\r\n requiredRoles: T[number][] = Object.values(Role) as T[number][]\r\n ) => {\r\n return (req: GuardedRequest, res: Response, next: NextFunction): void => {\r\n const user = req[userProp]\r\n\r\n if (!user) {\r\n res\r\n .status(401)\r\n .json({ error: \"Unauthorized: Authentication required\" })\r\n return\r\n }\r\n\r\n const userRole = user[roleProp]\r\n if (!userRole || !requiredRoles.includes(userRole)) {\r\n res.status(403).json({ error: \"Forbidden: Insufficient permissions\" })\r\n return\r\n }\r\n next()\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport function defineConfig<const T extends readonly string[]>(\r\n config: SecurityKitConfig<T>\r\n): SecurityKitConfig<T> {\r\n return config\r\n}\r\n\r\nexport { Extractors } from \"./extractors\"\r\nexport type {\r\n SecurityKitConfig,\r\n GuardedRequest,\r\n TokenExtractor,\r\n SecretConfig,\r\n RoleMap\r\n} from \"./types\"\r\n","import type { TokenExtractor } from \"./types\"\r\n\r\nexport const Extractors = {\r\n fromHeader: (headerName = \"authorization\"): TokenExtractor => {\r\n return (req) => {\r\n const header = req.headers[headerName.toLowerCase()]\r\n if (typeof header === \"string\" && header.startsWith(\"Bearer \")) {\r\n return header.split(\" \")[1]\r\n }\r\n return typeof header === \"string\" ? header : null\r\n }\r\n },\r\n fromCookie: (cookieName: string): TokenExtractor => {\r\n return (req) => (req.cookies ? req.cookies[cookieName] || null : null)\r\n },\r\n fromBody: (fieldName: string): TokenExtractor => {\r\n return (req) => (req.body ? req.body[fieldName] || null : null)\r\n }\r\n}\r\n"],"mappings":";AACA,OAAO,SAAS;;;ACCT,IAAM,aAAa;AAAA,EACxB,YAAY,CAAC,aAAa,oBAAoC;AAC5D,WAAO,CAAC,QAAQ;AACd,YAAM,SAAS,IAAI,QAAQ,WAAW,YAAY,CAAC;AACnD,UAAI,OAAO,WAAW,YAAY,OAAO,WAAW,SAAS,GAAG;AAC9D,eAAO,OAAO,MAAM,GAAG,EAAE,CAAC;AAAA,MAC5B;AACA,aAAO,OAAO,WAAW,WAAW,SAAS;AAAA,IAC/C;AAAA,EACF;AAAA,EACA,YAAY,CAAC,eAAuC;AAClD,WAAO,CAAC,QAAS,IAAI,UAAU,IAAI,QAAQ,UAAU,KAAK,OAAO;AAAA,EACnE;AAAA,EACA,UAAU,CAAC,cAAsC;AAC/C,WAAO,CAAC,QAAS,IAAI,OAAO,IAAI,KAAK,SAAS,KAAK,OAAO;AAAA,EAC5D;AACF;;;ADRO,SAAS,kBACd,QACA;AACA,MAAI,CAAC,OAAO,OAAQ,OAAM,IAAI,MAAM,uCAAuC;AAE3E,QAAM,YACJ,OAAO,OAAO,WAAW,YACzB,OAAO,WAAW,QAClB,SAAS,OAAO,SACZ,OAAO,SACP,EAAE,KAAK,OAAO,OAAO;AAE3B,QAAM,SAAS,UAAU;AACzB,QAAM,YAA6B,UAAU,OAAO;AAEpD,MAAI;AACJ,MAAI,aAA8B;AAElC,MAAI,OAAO,eAAe;AACxB,UAAM,aACJ,OAAO,OAAO,kBAAkB,YAChC,OAAO,kBAAkB,QACzB,SAAS,OAAO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AACjE;AAAA,MACF;AAEA,UAAI;AACF,YAAI,QAAQ,IAAI,IAAI,OAAO,OAAO,QAAQ,UAAU;AACpD,aAAK;AAAA,MACP,SAAS,KAAK;AACZ,cAAM,MACJ,eAAe,IAAI,oBACf,kBACA;AACN,YAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,iBAAiB,GAAG,GAAG,CAAC;AAAA,MACxD;AAAA,IACF;AAAA,IAEF,aAAa,CACX,gBAA6B,OAAO,OAAO,IAAI,MAC5C;AACH,aAAO,CAAC,KAAqB,KAAe,SAA6B;AACvE,cAAM,OAAO,IAAI,QAAQ;AAEzB,YAAI,CAAC,MAAM;AACT,cACG,OAAO,GAAG,EACV,KAAK,EAAE,OAAO,wCAAwC,CAAC;AAC1D;AAAA,QACF;AAEA,cAAM,WAAW,KAAK,QAAQ;AAC9B,YAAI,CAAC,YAAY,CAAC,cAAc,SAAS,QAAQ,GAAG;AAClD,cAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,sCAAsC,CAAC;AACrE;AAAA,QACF;AACA,aAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,aACd,QACsB;AACtB,SAAO;AACT;","names":[]}
@@ -0,0 +1,22 @@
1
+ import type { Request } from "express";
2
+ import type { Algorithm } from "jsonwebtoken";
3
+ export type TokenExtractor = (req: Request) => string | null;
4
+ export type RoleMap<T extends readonly string[]> = {
5
+ [K in T[number] as Uppercase<K & string>]: K;
6
+ };
7
+ export interface SecretConfig {
8
+ key: string | Buffer;
9
+ exp?: string | number;
10
+ }
11
+ export interface SecurityKitConfig<T extends readonly string[]> {
12
+ secret: SecretConfig | string | Buffer;
13
+ refreshSecret?: SecretConfig | string | Buffer;
14
+ userProperty?: string;
15
+ roleProperty?: string;
16
+ algorithms?: Algorithm[];
17
+ extractors?: TokenExtractor[];
18
+ roles?: T;
19
+ }
20
+ export interface GuardedRequest extends Request {
21
+ [key: string]: any;
22
+ }
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@shamodha/jwt-security-kit",
3
+ "version": "1.0.1",
4
+ "main": "./dist/index.js",
5
+ "module": "./dist/index.mjs",
6
+ "types": "./dist/index.d.ts",
7
+ "bin": {
8
+ "jwt-security-kit": "./dist/cli.js"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/index.js"
15
+ }
16
+ },
17
+ "scripts": {
18
+ "build": "tsup && tsc --emitDeclarationOnly --declaration --outDir dist"
19
+ },
20
+ "peerDependencies": {
21
+ "express": "^4.17.0 || ^5.0.0",
22
+ "jsonwebtoken": "^9.0.0"
23
+ },
24
+ "devDependencies": {
25
+ "@types/express": "^4.17.0",
26
+ "@types/jsonwebtoken": "^9.0.0",
27
+ "@types/node": "^20.0.0",
28
+ "tsup": "^8.0.0",
29
+ "typescript": "^5.0.0"
30
+ }
31
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from "fs"
3
+ import * as path from "path"
4
+
5
+ const args = process.argv.slice(2)
6
+ const command = args[0]
7
+
8
+ if (command === "init") {
9
+ const flags = args.slice(1)
10
+ const isJavaScript = flags.includes("--js") || flags.includes("-j")
11
+
12
+ const ext = isJavaScript ? "js" : "ts"
13
+ const fileName = `jwt.security.config.${ext}`
14
+ const filePath = path.join(process.cwd(), fileName)
15
+
16
+ const template = isJavaScript
17
+ ? `const { defineConfig } = require('jwt-security-kit');
18
+
19
+ module.exports = defineConfig({
20
+ secret: {
21
+ key: process.env.JWT_SECRET || 'your-super-secret-key',
22
+ exp: '15m'
23
+ },
24
+ roles: ['user', 'admin']
25
+ });
26
+ `
27
+ : `import { defineConfig } from 'jwt-security-kit';
28
+
29
+ export default defineConfig({
30
+ secret: {
31
+ key: process.env.JWT_SECRET || 'your-super-secret-key',
32
+ exp: '15m'
33
+ },
34
+ roles: ['user', 'admin'] as const
35
+ });
36
+ `
37
+
38
+ if (fs.existsSync(filePath)) {
39
+ console.log(`⚠️ Configuration file already exists at: ${fileName}`)
40
+ process.exit(1)
41
+ }
42
+
43
+ try {
44
+ fs.writeFileSync(filePath, template, "utf8")
45
+ console.log(`✨ Successfully created ${fileName} in your project root!`)
46
+ } catch (err) {
47
+ console.error("❌ Failed to create configuration file:", err)
48
+ process.exit(1)
49
+ }
50
+ } else {
51
+ console.log("Unknown command. Use: npx jwt-security-kit init [--js]")
52
+ }
@@ -0,0 +1,19 @@
1
+ import type { TokenExtractor } from "./types"
2
+
3
+ export const Extractors = {
4
+ fromHeader: (headerName = "authorization"): TokenExtractor => {
5
+ return (req) => {
6
+ const header = req.headers[headerName.toLowerCase()]
7
+ if (typeof header === "string" && header.startsWith("Bearer ")) {
8
+ return header.split(" ")[1]
9
+ }
10
+ return typeof header === "string" ? header : null
11
+ }
12
+ },
13
+ fromCookie: (cookieName: string): TokenExtractor => {
14
+ return (req) => (req.cookies ? req.cookies[cookieName] || null : null)
15
+ },
16
+ fromBody: (fieldName: string): TokenExtractor => {
17
+ return (req) => (req.body ? req.body[fieldName] || null : null)
18
+ }
19
+ }
package/src/index.ts ADDED
@@ -0,0 +1,140 @@
1
+ import type { Response, NextFunction } from "express"
2
+ import jwt from "jsonwebtoken"
3
+ import type {
4
+ SecurityKitConfig,
5
+ GuardedRequest,
6
+ RoleMap,
7
+ SecretConfig
8
+ } from "./types"
9
+ import { Extractors } from "./extractors"
10
+
11
+ export function createSecurityKit<const T extends readonly string[]>(
12
+ config: SecurityKitConfig<T>
13
+ ) {
14
+ if (!config.secret) throw new Error("FATAL: SecurityKit requires a secret.")
15
+
16
+ const secretCfg: SecretConfig =
17
+ typeof config.secret === "object" &&
18
+ config.secret !== null &&
19
+ "key" in config.secret
20
+ ? config.secret
21
+ : { key: config.secret }
22
+
23
+ const secret = secretCfg.key
24
+ const accessExp: string | number = secretCfg.exp || "15m"
25
+
26
+ let refreshSecret: string | Buffer | undefined
27
+ let refreshExp: string | number = "7d"
28
+
29
+ if (config.refreshSecret) {
30
+ const refreshCfg: SecretConfig =
31
+ typeof config.refreshSecret === "object" &&
32
+ config.refreshSecret !== null &&
33
+ "key" in config.refreshSecret
34
+ ? config.refreshSecret
35
+ : { key: config.refreshSecret }
36
+
37
+ refreshSecret = refreshCfg.key
38
+ refreshExp = refreshCfg.exp || "7d"
39
+ }
40
+
41
+ const userProp = config.userProperty || "user"
42
+ const roleProp = config.roleProperty || "role"
43
+ const algorithms = config.algorithms || ["HS256"]
44
+ const extractors = config.extractors?.length
45
+ ? config.extractors
46
+ : [Extractors.fromHeader()]
47
+
48
+ const rolesArray = config.roles || (["user", "admin"] as unknown as T)
49
+
50
+ const Role = Object.freeze(
51
+ rolesArray.reduce((acc, role) => {
52
+ ;(acc as any)[role.toUpperCase()] = role
53
+ return acc
54
+ }, {} as RoleMap<T>)
55
+ )
56
+
57
+ const signOpts: jwt.SignOptions = { expiresIn: accessExp as any }
58
+ const refreshSignOpts: jwt.SignOptions = { expiresIn: refreshExp as any }
59
+ const verifyOpts: jwt.VerifyOptions = { algorithms }
60
+
61
+ return {
62
+ Role,
63
+
64
+ generateToken: (payload: string | object | Buffer): string => {
65
+ return jwt.sign(payload, secret, signOpts)
66
+ },
67
+
68
+ generateRefreshToken: (payload: string | object | Buffer): string => {
69
+ if (!refreshSecret) throw new Error("Refresh secret is not configured.")
70
+ return jwt.sign(payload, refreshSecret, refreshSignOpts)
71
+ },
72
+
73
+ verifyRefreshToken: (token: string): string | jwt.JwtPayload => {
74
+ if (!refreshSecret) throw new Error("Refresh secret is not configured.")
75
+ return jwt.verify(token, refreshSecret, verifyOpts)
76
+ },
77
+
78
+ guard:
79
+ () =>
80
+ (req: GuardedRequest, res: Response, next: NextFunction): void => {
81
+ let token: string | null = null
82
+ for (const extractor of extractors) {
83
+ if ((token = extractor(req))) break
84
+ }
85
+
86
+ if (!token) {
87
+ res.status(401).json({ error: "Unauthorized: No token provided" })
88
+ return
89
+ }
90
+
91
+ try {
92
+ req[userProp] = jwt.verify(token, secret, verifyOpts)
93
+ next()
94
+ } catch (err) {
95
+ const msg =
96
+ err instanceof jwt.TokenExpiredError
97
+ ? "Token expired"
98
+ : "Invalid token"
99
+ res.status(401).json({ error: `Unauthorized: ${msg}` })
100
+ }
101
+ },
102
+
103
+ requireRole: (
104
+ requiredRoles: T[number][] = Object.values(Role) as T[number][]
105
+ ) => {
106
+ return (req: GuardedRequest, res: Response, next: NextFunction): void => {
107
+ const user = req[userProp]
108
+
109
+ if (!user) {
110
+ res
111
+ .status(401)
112
+ .json({ error: "Unauthorized: Authentication required" })
113
+ return
114
+ }
115
+
116
+ const userRole = user[roleProp]
117
+ if (!userRole || !requiredRoles.includes(userRole)) {
118
+ res.status(403).json({ error: "Forbidden: Insufficient permissions" })
119
+ return
120
+ }
121
+ next()
122
+ }
123
+ }
124
+ }
125
+ }
126
+
127
+ export function defineConfig<const T extends readonly string[]>(
128
+ config: SecurityKitConfig<T>
129
+ ): SecurityKitConfig<T> {
130
+ return config
131
+ }
132
+
133
+ export { Extractors } from "./extractors"
134
+ export type {
135
+ SecurityKitConfig,
136
+ GuardedRequest,
137
+ TokenExtractor,
138
+ SecretConfig,
139
+ RoleMap
140
+ } from "./types"
package/src/types.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { Request } from "express"
2
+ import type { Algorithm } from "jsonwebtoken"
3
+
4
+ export type TokenExtractor = (req: Request) => string | null
5
+
6
+ export type RoleMap<T extends readonly string[]> = {
7
+ [K in T[number] as Uppercase<K & string>]: K
8
+ }
9
+
10
+ export interface SecretConfig {
11
+ key: string | Buffer
12
+ exp?: string | number
13
+ }
14
+
15
+ export interface SecurityKitConfig<T extends readonly string[]> {
16
+ secret: SecretConfig | string | Buffer
17
+ refreshSecret?: SecretConfig | string | Buffer
18
+ userProperty?: string
19
+ roleProperty?: string
20
+ algorithms?: Algorithm[]
21
+ extractors?: TokenExtractor[]
22
+ roles?: T
23
+ }
24
+
25
+ export interface GuardedRequest extends Request {
26
+ [key: string]: any
27
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "strict": true,
7
+ "esModuleInterop": true,
8
+ "skipLibCheck": true,
9
+ "forceConsistentCasingInFileNames": true,
10
+ "declaration": true,
11
+ "emitDeclarationOnly": true,
12
+ "rootDir": "src",
13
+ "outDir": "dist"
14
+ },
15
+ "include": ["src"]
16
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { defineConfig } from "tsup"
2
+
3
+ export default defineConfig({
4
+ entry: ["src/index.ts", "src/cli.ts"],
5
+ format: ["cjs", "esm"],
6
+ dts: false,
7
+ splitting: false,
8
+ sourcemap: true,
9
+ clean: true
10
+ })