@meebon/meebon-crypto 1.2.14 → 1.2.16

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.
@@ -3,9 +3,9 @@ import { MeebonCryptoKeyPair } from '../types/global';
3
3
  /**
4
4
  * Middleware for encrypting incoming request data and decrypting outgoing response data.
5
5
  *
6
- * @param {MeebonCryptoKeyPair} keys - An object containing the privateKey and publicKey in PEM format.
6
+ * @param {MeebonCryptoKeyPair} keys - An object containing the privateKey, publicKey, and forRequest flag.
7
7
  * @returns {RequestHandler} The Express middleware function.
8
8
  */
9
- declare function EncryptionMiddleware({ privateKey, publicKey }: MeebonCryptoKeyPair): RequestHandler;
9
+ declare function EncryptionMiddleware({ privateKey, publicKey, forRequest }: MeebonCryptoKeyPair): RequestHandler;
10
10
  export { EncryptionMiddleware };
11
11
  //# sourceMappingURL=ExpressEncryptionMiddleware.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ExpressEncryptionMiddleware.d.ts","sourceRoot":"","sources":["../lib/ExpressEncryptionMiddleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAmC,cAAc,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEtD;;;;;GAKG;AACH,iBAAS,oBAAoB,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,EAAE,mBAAmB,GAAG,cAAc,CAkC5F;AAED,OAAO,EAAE,oBAAoB,EAAE,CAAC"}
1
+ {"version":3,"file":"ExpressEncryptionMiddleware.d.ts","sourceRoot":"","sources":["../lib/ExpressEncryptionMiddleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAmC,cAAc,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEtD;;;;;GAKG;AACH,iBAAS,oBAAoB,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,EAAE,mBAAmB,GAAG,cAAc,CAsCxG;AAED,OAAO,EAAE,oBAAoB,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -79,34 +79,37 @@ var MeebonCrypto = class _MeebonCrypto {
79
79
  };
80
80
 
81
81
  // lib/ExpressEncryptionMiddleware.ts
82
- function EncryptionMiddleware({ privateKey, publicKey }) {
82
+ function EncryptionMiddleware({ privateKey, publicKey, forRequest }) {
83
83
  return (req, res, next) => {
84
- if (req.body && req.body.data) {
85
- try {
86
- const plainText = JSON.stringify(req.body.data);
87
- const encrypted = MeebonCrypto.encryptData(plainText, publicKey);
88
- req.body.data = encrypted;
89
- } catch (error) {
90
- return next(new Error(error?.message || "Encryption failed."));
84
+ if (forRequest) {
85
+ if (req.body && req.body.data) {
86
+ try {
87
+ const plainText = JSON.stringify(req.body.data);
88
+ const encrypted = MeebonCrypto.encryptData(plainText, publicKey);
89
+ req.body.data = encrypted;
90
+ } catch (error) {
91
+ next(new Error(error?.message || "Encryption failed."));
92
+ }
91
93
  }
92
- }
93
- const originalSend = res.send.bind(res);
94
- res.send = (body) => {
95
- try {
96
- if (typeof body === "string") {
97
- const decrypted = MeebonCrypto.decryptData(body, privateKey);
98
- try {
99
- body = JSON.parse(decrypted);
100
- } catch {
101
- body = decrypted;
94
+ } else {
95
+ const originalSend = res.send.bind(res);
96
+ res.send = (body) => {
97
+ try {
98
+ if (typeof body === "string" && body) {
99
+ const decrypted = MeebonCrypto.decryptData(body, privateKey);
100
+ try {
101
+ body = JSON.parse(decrypted);
102
+ } catch {
103
+ body = decrypted;
104
+ }
102
105
  }
106
+ } catch (error) {
107
+ next(new Error(error?.message || "Decryption failed."));
103
108
  }
104
- } catch (error) {
105
- throw new Error(error?.message ?? "Decryption failed");
106
- }
107
- return originalSend(body);
108
- };
109
- return next();
109
+ return originalSend(body);
110
+ };
111
+ }
112
+ next();
110
113
  };
111
114
  }
112
115
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meebon/meebon-crypto",
3
- "version": "1.2.14",
3
+ "version": "1.2.16",
4
4
  "description": "",
5
5
  "author": "kajalanS <103587022+kajalanS@users.noreply.github.com>",
6
6
  "homepage": "https://github.com/KsoftmHub/meebon-crypto?tab=readme-ov-file#getting-started",
@@ -8,6 +8,15 @@
8
8
  "main": "dist/index.js",
9
9
  "type": "module",
10
10
  "types": "types",
11
+ "directories": {
12
+ "lib": "lib",
13
+ "tests": "tests",
14
+ "types": "types"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "types"
19
+ ],
11
20
  "release": {
12
21
  "branches": [
13
22
  "master",
package/types/global.d.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  import { pki } from "node-forge";
2
2
 
3
3
  export interface MeebonCryptoProps {
4
- privateKeyPem: string;
5
- publicKeyPem: string;
6
- schema?: pki.rsa.EncryptionScheme;
4
+ privateKeyPem: string;
5
+ publicKeyPem: string;
6
+ schema?: pki.rsa.EncryptionScheme;
7
7
  }
8
8
 
9
9
  export interface MeebonCryptoKeyPair {
10
- privateKey: string;
11
- publicKey: string;
12
- }
10
+ privateKey: string;
11
+ publicKey: string;
12
+ forRequest?: boolean;
13
+ }
@@ -1,42 +0,0 @@
1
- name: Release
2
-
3
- on:
4
- push:
5
- branches:
6
- - master
7
- - beta
8
-
9
- permissions:
10
- contents: write
11
- issues: write
12
- pull-requests: write
13
-
14
- jobs:
15
- release:
16
- runs-on: ubuntu-latest
17
- steps:
18
- - name: Checkout code
19
- uses: actions/checkout@v4
20
-
21
- - name: Setup Node.js
22
- uses: actions/setup-node@v4
23
- with:
24
- node-version: "lts/*"
25
-
26
- - name: Install pnpm
27
- run: npm install -g pnpm
28
-
29
- - name: Install dependencies with pnpm
30
- run: pnpm install
31
-
32
- - name: Build the project
33
- run: pnpm run build
34
-
35
- - name: Audit dependencies
36
- run: pnpm audit --prod
37
-
38
- - name: Semantic Release
39
- uses: cycjimmy/semantic-release-action@v4
40
- env:
41
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
42
- NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
package/.gitmodules DELETED
@@ -1,3 +0,0 @@
1
- [submodule "scripts"]
2
- path = scripts
3
- url = https://github.com/KsoftmHub/ksoftm-node-build.git
package/.releaserc DELETED
@@ -1,28 +0,0 @@
1
- {
2
- "branches": [
3
- "master",
4
- {
5
- "name": "beta",
6
- "prerelease": true
7
- }
8
- ],
9
- "plugins": [
10
- "@semantic-release/commit-analyzer",
11
- "@semantic-release/release-notes-generator",
12
- [
13
- "@semantic-release/changelog",
14
- {
15
- "changelogFile": "CHANGELOG.md"
16
- }
17
- ],
18
- [
19
- "@semantic-release/git",
20
- {
21
- "assets": [
22
- "CHANGELOG.md"
23
- ]
24
- }
25
- ],
26
- "@semantic-release/github"
27
- ]
28
- }
@@ -1,15 +0,0 @@
1
- {
2
- "files.exclude": {
3
- "**/.git": false,
4
- "**/.svn": false,
5
- "**/.hg": false,
6
- "**/CVS": false,
7
- "**/.DS_Store": false,
8
- "**/Thumbs.db": false,
9
- "**/.classpath": false,
10
- "**/.project": false,
11
- "**/.settings": false,
12
- "**/.factorypath": false
13
- },
14
- "explorerExclude.backup": {}
15
- }
package/jest.config.js DELETED
@@ -1,33 +0,0 @@
1
- /**
2
- * For a detailed explanation regarding each configuration property, visit:
3
- * https://jestjs.io/docs/configuration
4
- */
5
-
6
- /** @type {import('jest').Config} */
7
- const config = {
8
- collectCoverage: true,
9
- coverageDirectory: "coverage",
10
- transformIgnorePatterns: [
11
- "\\\\node_modules\\\\",
12
- "\\.pnp\\.[^\\\\]+$",
13
- '\\.d\\.ts$',
14
- ],
15
- preset: 'ts-jest',
16
- testEnvironment: 'node',
17
- transform: {
18
- '^.+\\.tsx?$': 'ts-jest',
19
- },
20
- moduleNameMapper: {
21
- '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
22
- },
23
- coverageThreshold: {
24
- global: {
25
- branches: 80,
26
- functions: 80,
27
- lines: 80,
28
- statements: 80,
29
- },
30
- },
31
- };
32
-
33
- export default config;
@@ -1,47 +0,0 @@
1
- import { MeebonCrypto } from './MeebonCrypto';
2
- import { Request, Response, NextFunction, RequestHandler } from 'express';
3
- import { MeebonCryptoKeyPair } from '../types/global';
4
-
5
- /**
6
- * Middleware for encrypting incoming request data and decrypting outgoing response data.
7
- *
8
- * @param {MeebonCryptoKeyPair} keys - An object containing the privateKey and publicKey in PEM format.
9
- * @returns {RequestHandler} The Express middleware function.
10
- */
11
- function EncryptionMiddleware({ privateKey, publicKey }: MeebonCryptoKeyPair): RequestHandler {
12
- return (req: Request, res: Response, next: NextFunction) => {
13
- // Encrypt incoming request body data if it exists.
14
- if (req.body && req.body.data) {
15
- try {
16
- // Encrypt the JSON-stringified data using the provided public key.
17
- const plainText = JSON.stringify(req.body.data);
18
- const encrypted = MeebonCrypto.encryptData(plainText, publicKey);
19
- req.body.data = encrypted;
20
- } catch (error: any) {
21
- return next(new Error(error?.message || 'Encryption failed.'));
22
- }
23
- }
24
- // Override res.send to decrypt the response body before sending it.
25
- const originalSend = res.send.bind(res);
26
- res.send = (body: any): Response => {
27
- try {
28
- // Only decrypt if body is a string.
29
- if (typeof body === 'string') {
30
- const decrypted = MeebonCrypto.decryptData(body, privateKey);
31
- // Attempt to parse decrypted text as JSON. If parsing fails, send the plain decrypted text.
32
- try {
33
- body = JSON.parse(decrypted);
34
- } catch {
35
- body = decrypted;
36
- }
37
- }
38
- } catch (error: any) {
39
- throw new Error(error?.message ?? "Decryption failed");
40
- }
41
- return originalSend(body);
42
- };
43
- return next();
44
- };
45
- }
46
-
47
- export { EncryptionMiddleware };
@@ -1,98 +0,0 @@
1
- import forge from 'node-forge';
2
- import { MeebonCryptoKeyPair, MeebonCryptoProps } from '../types/global';
3
-
4
- export class MeebonCrypto {
5
- protected privateKeyPem: string;
6
- protected publicKeyPem: string;
7
-
8
- public privateKey: forge.pki.rsa.PrivateKey;
9
- public publicKey: forge.pki.rsa.PublicKey;
10
-
11
- protected schema: forge.pki.rsa.EncryptionScheme;
12
-
13
- private constructor({ privateKeyPem, publicKeyPem, schema }: MeebonCryptoProps) {
14
- this.privateKeyPem = privateKeyPem;
15
- this.publicKeyPem = publicKeyPem;
16
-
17
- this.privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
18
- this.publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
19
- this.schema = schema ?? 'RSAES-PKCS1-V1_5';
20
- }
21
-
22
- /**
23
- * Initializes a new instance of MeebonCrypto.
24
- * @param props - The crypto properties including keys and optional encryption scheme.
25
- * @returns {MeebonCrypto} The initialized MeebonCrypto instance.
26
- */
27
- public static init(props: MeebonCryptoProps): MeebonCrypto {
28
- return new MeebonCrypto(props);
29
- }
30
-
31
- /**
32
- * Encrypts data using the instance's public key.
33
- * @param {string} plainText - The data to encrypt.
34
- * @returns {string} The Base64-encoded encrypted data.
35
- */
36
- public encrypt(plainText: string): string {
37
- const encryptedBytes = this.publicKey.encrypt(plainText, this.schema);
38
- return forge.util.encode64(encryptedBytes);
39
- }
40
-
41
- /**
42
- * Decrypts data using the instance's private key.
43
- * @param {string} encryptedData - The Base64-encoded encrypted data.
44
- * @returns {string} The decrypted data.
45
- */
46
- public decrypt(encryptedData: string): string {
47
- const encryptedBytes = forge.util.decode64(encryptedData);
48
- return this.privateKey.decrypt(encryptedBytes, this.schema);
49
- }
50
-
51
- /**
52
- * Generates an RSA key pair with the specified key size.
53
- *
54
- * @param {number} [length=3072] - The length of the RSA key in bits (defaults to 3072).
55
- * @returns {MeebonCryptoKeyPair} An object containing the generated public and private keys in PEM format.
56
- */
57
- public static generateKeyPair(length: number = 3072): MeebonCryptoKeyPair {
58
- const keyPair = forge.pki.rsa.generateKeyPair({ bits: length, e: 0x10001 });
59
- return {
60
- publicKey: forge.pki.publicKeyToPem(keyPair.publicKey),
61
- privateKey: forge.pki.privateKeyToPem(keyPair.privateKey),
62
- };
63
- }
64
-
65
- /**
66
- * Encrypts data with a provided public key.
67
- * @param {string} data - The data to encrypt.
68
- * @param {string} publicKey - The public key in PEM format.
69
- * @param {string} [scheme='RSA-OAEP'] - The encryption scheme to use (defaults to 'RSA-OAEP').
70
- * @returns {string} The Base64-encoded encrypted data.
71
- */
72
- public static encryptData(
73
- data: string,
74
- publicKey: string,
75
- scheme: forge.pki.rsa.EncryptionScheme = 'RSA-OAEP'
76
- ): string {
77
- const publicKeyObj = forge.pki.publicKeyFromPem(publicKey);
78
- const encryptedBytes = publicKeyObj.encrypt(data, scheme);
79
- return forge.util.encode64(encryptedBytes);
80
- }
81
-
82
- /**
83
- * Decrypts data with a provided private key.
84
- * @param {string} encryptedData - The Base64-encoded encrypted data.
85
- * @param {string} privateKey - The private key in PEM format.
86
- * @param {string} [scheme='RSA-OAEP'] - The decryption scheme to use (defaults to 'RSA-OAEP').
87
- * @returns {string} The decrypted data.
88
- */
89
- public static decryptData(
90
- encryptedData: string,
91
- privateKey: string,
92
- scheme: forge.pki.rsa.EncryptionScheme = 'RSA-OAEP'
93
- ): string {
94
- const privateKeyObj = forge.pki.privateKeyFromPem(privateKey);
95
- const decodedBytes = forge.util.decode64(encryptedData);
96
- return privateKeyObj.decrypt(decodedBytes, scheme);
97
- }
98
- }
package/lib/index.ts DELETED
@@ -1,4 +0,0 @@
1
-
2
- import { MeebonCrypto } from "./MeebonCrypto";
3
- import { EncryptionMiddleware } from "./ExpressEncryptionMiddleware";
4
- export { EncryptionMiddleware, MeebonCrypto };
package/script/build.ts DELETED
@@ -1,30 +0,0 @@
1
- import { cpSync, readFileSync, rmSync } from "node:fs";
2
- import { buildSync } from "esbuild";
3
- import pkg from "../package.json";
4
- import { execSync } from "node:child_process";
5
-
6
- // Find the build directory from tsconfig.json
7
- const tsc = JSON.parse(readFileSync("tsconfig.json", "utf-8"));
8
- const buildDir = tsc?.compilerOptions?.outDir ?? "dist";
9
-
10
- // Remove the existing build directory
11
- rmSync(buildDir, { force: true, recursive: true });
12
-
13
- // Build TypeScript declaration files (*.d.ts)
14
- execSync("tsc --project tsconfig.declaration.json", { stdio: "inherit" });
15
-
16
- // Build files using esbuild
17
- buildSync({
18
- entryPoints: ["lib/index.ts"],
19
- outfile: `${buildDir}/index.js`,
20
- bundle: true,
21
- platform: "node",
22
- format: "esm",
23
- inject: ["types/global.d.ts"],
24
- tsconfig: "tsconfig.json",
25
- external: Object.keys(pkg.dependencies),
26
- resolveExtensions: [".ts", ".js", ".json", ".d.ts"],
27
- });
28
-
29
- // Optionally copy type files to the build directory
30
- // cpSync("types", "dist/types", { force: true, recursive: true });
package/script/clean.ts DELETED
@@ -1,27 +0,0 @@
1
- import { existsSync, readFileSync, rmSync } from "node:fs";
2
- import { execSync } from 'child_process'
3
- import picocolors from 'picocolors';
4
- import path from 'path'
5
- // find the build directory
6
- const tsc = JSON.parse(readFileSync("tsconfig.json").toString())
7
- const buildDir = tsc?.compilerOptions?.outDir ?? "dist";
8
-
9
- const foldersToClean = [
10
- buildDir,
11
- 'coverage',
12
-
13
-
14
- // package-manager lock files
15
- 'pnpm-lock.yaml',
16
- 'package-lock.json',
17
- 'yarn.lock',
18
- ]
19
-
20
- foldersToClean.forEach(folder => {
21
- if (existsSync(folder)) {
22
- rmSync(folder, { force: true, recursive: true });
23
- console.log(picocolors.redBright(`Folder: ${picocolors.italic(path.normalize(folder))} is deleted!`));
24
- }
25
- })
26
-
27
- execSync("pnpm run refresh", { stdio: "inherit" })
@@ -1,39 +0,0 @@
1
- import { defineConfig } from 'tsup'
2
- import pkg from '../package.json'
3
-
4
- export default defineConfig({
5
- // Specify the entry file(s) for your build.
6
- // Change or add more entries if needed.
7
- entry: ['lib/**/*.ts'],
8
-
9
- // Output directory for the build artifacts.
10
- outDir: 'dist',
11
-
12
- // Remove the output directory before building.
13
- clean: true,
14
-
15
- // Bundle your files into a single file per entry.
16
- bundle: true,
17
-
18
- // Target the Node.js environment (adjust version as needed)
19
- target: 'node20',
20
-
21
- // Generate sourcemaps for easier debugging.
22
- sourcemap: true,
23
-
24
- // Output format(s); here we're using ES modules.
25
- format: ['esm'],
26
-
27
- // Automatically generate .d.ts declaration files.
28
- dts: {
29
- // If you prefer to generate declarations for all entries, set dts: true.
30
- // Alternatively, you can customize options here.
31
- entry: 'lib/index.ts',
32
- },
33
-
34
- // Mark dependencies as external so they’re not bundled.
35
- external: [
36
- ...Object.keys(pkg?.dependencies || {}),
37
- ...Object.keys(pkg?.peerDependencies || {})
38
- ],
39
- })
@@ -1,4 +0,0 @@
1
-
2
- test('should expect true all time', () => {
3
- expect({ data: "done" }).toStrictEqual({ data: "done" })
4
- })
@@ -1,20 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "declarationMap": true,
5
- "declaration": true,
6
- "sourceMap": true,
7
- "declarationDir": "./dist",
8
- "emitDeclarationOnly": true,
9
- "outDir": "./dist"
10
- },
11
- "include": [
12
- "lib",
13
- "types"
14
- ],
15
- "exclude": [
16
- "node_modules",
17
- "tests",
18
- "coverage"
19
- ]
20
- }
package/tsconfig.json DELETED
@@ -1,24 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ESNext",
4
- "module": "ES2022",
5
- "declarationMap": false,
6
- "outDir": "./dist",
7
- "rootDir": "./lib",
8
- "esModuleInterop": true,
9
- "forceConsistentCasingInFileNames": true,
10
- "strict": true,
11
- "moduleResolution": "bundler",
12
- "skipLibCheck": true
13
- },
14
- "exclude": [
15
- "node_modules",
16
- "dist",
17
- "coverage",
18
- "tests"
19
- ],
20
- "include": [
21
- "lib",
22
- "types"
23
- ]
24
- }