jssign 0.3.6 → 0.3.7

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/LICENSE CHANGED
@@ -1,9 +1,9 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 Sahil Aggawal, <aggarwalsahil2004@gmail.com>
3
+ Copyright (c) Sahil Aggawal, <aggarwalsahil2004@gmail.com>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
6
 
7
7
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
8
 
9
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # jssign
2
2
 
3
- A better, faster, lighter and more secure alternative to [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken)
3
+ A better, faster, lighter and more secure alternative to [`jsonwebtoken`](https://github.com/auth0/node-jsonwebtoken)
4
4
 
5
5
  ## Features
6
6
 
@@ -9,20 +9,20 @@ A better, faster, lighter and more secure alternative to [jsonwebtoken](https://
9
9
 
10
10
  ## Installation
11
11
 
12
- To install jssign
12
+ Install `jssign` using your preferred package manager:
13
13
 
14
14
  ```bash
15
- # with npm:
16
- npm install jssign --save
15
+ # with npm:
16
+ npm install jssign --save
17
17
 
18
- # with yarn:
19
- yarn add jssign
18
+ # with yarn:
19
+ yarn add jssign
20
20
 
21
- # with pnpm:
22
- pnpm add jssign
21
+ # with pnpm:
22
+ pnpm add jssign
23
23
 
24
- # with bun:
25
- bun add jssign
24
+ # with bun:
25
+ bun add jssign
26
26
  ```
27
27
 
28
28
  ## Usage
@@ -80,8 +80,18 @@ console.log(data); // { id: 'confidential_data' }
80
80
 
81
81
  - `expiresIn` can be a numeric value representing time in ms (default value is `0` which represents no expiration).
82
82
 
83
- `sjclOptions` are the options taken by `sjcl.encrypt` method having type `SjclCipherEncryptParams`
83
+ `sjclOptions` are the options taken by `sjcl.encrypt` method having type [`SjclOptions`](#sjcloptions)
84
84
 
85
- ## Author
85
+ ## Types
86
86
 
87
- [Sahil Aggarwal](https://www.github.com/SahilAggarwal2004)
87
+ ### SjclOptions
88
+
89
+ ```typescript
90
+ import type { SjclCipherEncryptParams } from "sjcl";
91
+
92
+ type SjclOptions = SjclCipherEncryptParams;
93
+ ```
94
+
95
+ ## License
96
+
97
+ This project is licensed under the [MIT License](LICENSE).
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+
3
+ var sjcl = require('sjcl');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var sjcl__default = /*#__PURE__*/_interopDefault(sjcl);
8
+
9
+ // src/index.ts
10
+
11
+ // src/constants.ts
12
+ var characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "[", "]", ";", ",", ".", "/", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "{", "}", ":", "<", ">", "?"];
13
+ var pairRegex = /(.{1,2})/g;
14
+
15
+ // src/lib/utils.ts
16
+ var byteHex = (n) => ("0" + Number(n).toString(16)).slice(-2);
17
+ var randomNumber = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
18
+ var randomElement = (array) => array[randomNumber(0, array.length - 1)];
19
+ function genSalt(length) {
20
+ let salt = randomElement(characters);
21
+ for (let i = 1; i < length; i++) salt += randomElement(characters);
22
+ return salt;
23
+ }
24
+ var stringFromCode = (code) => String.fromCharCode(code);
25
+ var textToChars = (text) => text.split("").map((c) => c.charCodeAt(0));
26
+
27
+ // src/lib/cipher.ts
28
+ var encoder = new TextEncoder();
29
+ var decoder = new TextDecoder();
30
+ function encode(data, secret, mode) {
31
+ if (mode === 0) {
32
+ const applySecret = (code) => textToChars(secret).reduce((a, b) => a ^ b, code);
33
+ return textToChars(data.toString()).map(applySecret).map(byteHex).join("");
34
+ }
35
+ const dataBytes = encoder.encode(data);
36
+ const secretBytes = encoder.encode(secret);
37
+ const dataLength = dataBytes.length;
38
+ const secretLength = secretBytes.length;
39
+ const tokenBytes = new Uint8Array(dataLength);
40
+ for (let i = 0; i < dataLength; i++) tokenBytes[i] = dataBytes[i] ^ secretBytes[i % secretLength];
41
+ return Array.from(tokenBytes).map((byte) => byte.toString(16).padStart(2, "0")).join("");
42
+ }
43
+ function decode(token, secret, mode) {
44
+ const hexPairs = token.match(pairRegex);
45
+ if (!hexPairs) return "";
46
+ if (mode === 0) {
47
+ const applySecret = (code) => textToChars(secret).reduce((a, b) => a ^ b, code);
48
+ return hexPairs.map((hex) => parseInt(hex, 16)).map(applySecret).map(stringFromCode).join("");
49
+ }
50
+ const tokenBytes = new Uint8Array(hexPairs.map((byte) => parseInt(byte, 16)));
51
+ const secretBytes = encoder.encode(secret);
52
+ const tokenLength = tokenBytes.length;
53
+ const secretLength = secretBytes.length;
54
+ const decodedBytes = new Uint8Array(tokenLength);
55
+ for (let i = 0; i < tokenLength; i++) decodedBytes[i] = tokenBytes[i] ^ secretBytes[i % secretLength];
56
+ return decoder.decode(decodedBytes);
57
+ }
58
+
59
+ // src/lib/token.ts
60
+ function validateData(token, secret, getData) {
61
+ try {
62
+ const { data, iat, exp } = JSON.parse(getData(token, secret));
63
+ if (exp && Date.now() > iat + exp) throw new Error("Expired token!");
64
+ return data;
65
+ } catch (error) {
66
+ throw new Error("Invalid token or secret!");
67
+ }
68
+ }
69
+
70
+ // src/index.ts
71
+ function sign(data, secret, { expiresIn = 0, sl = 32 } = {}) {
72
+ const salt = genSalt(sl);
73
+ const token = encode(JSON.stringify({ data, iat: Date.now(), exp: expiresIn }), salt, 1);
74
+ const signature = encode(salt, secret, 0);
75
+ return `${token}.${signature}`;
76
+ }
77
+ function verify(token, secret) {
78
+ return validateData(token, secret, (token2, secret2) => {
79
+ const [dataStr, signature] = token2.split(".");
80
+ const salt = decode(signature, secret2, 0);
81
+ return decode(dataStr, salt, 1);
82
+ });
83
+ }
84
+ function encrypt(data, secret, { expiresIn = 0 } = {}, sjclOptions) {
85
+ const encryptedObj = JSON.parse(sjcl__default.default.encrypt(secret, JSON.stringify({ data, iat: Date.now(), exp: expiresIn }), sjclOptions));
86
+ const encryptedArr = Object.entries(encryptedObj).map(([key, value]) => `${key}:${value}`);
87
+ return encryptedArr.join(".");
88
+ }
89
+ function decrypt(token, secret) {
90
+ return validateData(token, secret, (token2, secret2) => {
91
+ const encryptedArr = token2.split(".");
92
+ const encryptedObj = encryptedArr.reduce((obj, str) => {
93
+ const [key, value] = str.split(":");
94
+ obj[key] = isNaN(+value) ? value : +value;
95
+ return obj;
96
+ }, {});
97
+ return sjcl__default.default.decrypt(secret2, JSON.stringify(encryptedObj));
98
+ });
99
+ }
100
+
101
+ exports.decrypt = decrypt;
102
+ exports.encrypt = encrypt;
103
+ exports.sign = sign;
104
+ exports.verify = verify;
@@ -1,12 +1,9 @@
1
- import { SjclCipherEncryptParams } from "sjcl";
2
- export type EncryptOptions = {
3
- expiresIn?: number;
4
- };
5
- export type SignOptions = EncryptOptions & {
6
- sl?: number;
7
- };
8
- export type { SjclCipherEncryptParams };
9
- export declare function sign(data: any, secret: string, { expiresIn, sl }?: SignOptions): string;
10
- export declare function verify(token: string, secret: string): any;
11
- export declare function encrypt(data: any, secret: string, { expiresIn }?: EncryptOptions, sjclOptions?: SjclCipherEncryptParams): string;
12
- export declare function decrypt(token: string, secret: string): any;
1
+ import { SignOptions, EncryptOptions, SjclOptions } from './types.js';
2
+ import 'sjcl';
3
+
4
+ declare function sign(data: unknown, secret: string, { expiresIn, sl }?: SignOptions): string;
5
+ declare function verify(token: string, secret: string): unknown;
6
+ declare function encrypt(data: unknown, secret: string, { expiresIn }?: EncryptOptions, sjclOptions?: SjclOptions): string;
7
+ declare function decrypt(token: string, secret: string): unknown;
8
+
9
+ export { decrypt, encrypt, sign, verify };
package/dist/esm/index.js CHANGED
@@ -1,91 +1,95 @@
1
- import sjcl from "sjcl";
2
- const characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "[", "]", ";", ",", ".", "/", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "{", "}", ":", "<", ">", "?"];
3
- const encoder = new TextEncoder();
4
- const decoder = new TextDecoder();
5
- const randomNumber = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
6
- const randomElement = (array) => array[randomNumber(0, array.length - 1)];
7
- const textToChars = (text) => text.split("").map((c) => c.charCodeAt(0));
8
- const byteHex = (n) => ("0" + Number(n).toString(16)).slice(-2);
9
- const stringFromCode = (code) => String.fromCharCode(code);
1
+ import sjcl from 'sjcl';
2
+
3
+ // src/index.ts
4
+
5
+ // src/constants.ts
6
+ var characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "[", "]", ";", ",", ".", "/", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "{", "}", ":", "<", ">", "?"];
7
+ var pairRegex = /(.{1,2})/g;
8
+
9
+ // src/lib/utils.ts
10
+ var byteHex = (n) => ("0" + Number(n).toString(16)).slice(-2);
11
+ var randomNumber = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
12
+ var randomElement = (array) => array[randomNumber(0, array.length - 1)];
10
13
  function genSalt(length) {
11
- let salt = randomElement(characters);
12
- for (let i = 1; i < length; i++)
13
- salt += randomElement(characters);
14
- return salt;
14
+ let salt = randomElement(characters);
15
+ for (let i = 1; i < length; i++) salt += randomElement(characters);
16
+ return salt;
15
17
  }
16
- function encode(data, secret, type) {
17
- if (type === 0) {
18
- const applySecret = (code) => textToChars(secret).reduce((a, b) => a ^ b, code);
19
- return data.toString().split("").map(textToChars).map(applySecret).map(byteHex).join("");
20
- }
21
- const dataBytes = encoder.encode(data);
22
- const secretBytes = encoder.encode(secret);
23
- const dataLength = dataBytes.length;
24
- const secretLength = secretBytes.length;
25
- const tokenBytes = new Uint8Array(dataLength);
26
- for (let i = 0; i < dataLength; i++)
27
- tokenBytes[i] = dataBytes[i] ^ secretBytes[i % secretLength];
28
- return Array.from(tokenBytes)
29
- .map((byte) => byte.toString(16).padStart(2, "0"))
30
- .join("");
18
+ var stringFromCode = (code) => String.fromCharCode(code);
19
+ var textToChars = (text) => text.split("").map((c) => c.charCodeAt(0));
20
+
21
+ // src/lib/cipher.ts
22
+ var encoder = new TextEncoder();
23
+ var decoder = new TextDecoder();
24
+ function encode(data, secret, mode) {
25
+ if (mode === 0) {
26
+ const applySecret = (code) => textToChars(secret).reduce((a, b) => a ^ b, code);
27
+ return textToChars(data.toString()).map(applySecret).map(byteHex).join("");
28
+ }
29
+ const dataBytes = encoder.encode(data);
30
+ const secretBytes = encoder.encode(secret);
31
+ const dataLength = dataBytes.length;
32
+ const secretLength = secretBytes.length;
33
+ const tokenBytes = new Uint8Array(dataLength);
34
+ for (let i = 0; i < dataLength; i++) tokenBytes[i] = dataBytes[i] ^ secretBytes[i % secretLength];
35
+ return Array.from(tokenBytes).map((byte) => byte.toString(16).padStart(2, "0")).join("");
31
36
  }
32
- function decode(token, secret, type) {
33
- if (type === 0) {
34
- const applySecret = (code) => textToChars(secret).reduce((a, b) => a ^ b, code);
35
- return token
36
- .match(/.{1,2}/g)
37
- .map((hex) => parseInt(hex, 16))
38
- .map(applySecret)
39
- .map(stringFromCode)
40
- .join("");
41
- }
42
- const tokenBytes = new Uint8Array(token.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
43
- const secretBytes = encoder.encode(secret);
44
- const tokenLength = tokenBytes.length;
45
- const secretLength = secretBytes.length;
46
- const decodedBytes = new Uint8Array(tokenLength);
47
- for (let i = 0; i < tokenLength; i++)
48
- decodedBytes[i] = tokenBytes[i] ^ secretBytes[i % secretLength];
49
- return decoder.decode(decodedBytes);
37
+ function decode(token, secret, mode) {
38
+ const hexPairs = token.match(pairRegex);
39
+ if (!hexPairs) return "";
40
+ if (mode === 0) {
41
+ const applySecret = (code) => textToChars(secret).reduce((a, b) => a ^ b, code);
42
+ return hexPairs.map((hex) => parseInt(hex, 16)).map(applySecret).map(stringFromCode).join("");
43
+ }
44
+ const tokenBytes = new Uint8Array(hexPairs.map((byte) => parseInt(byte, 16)));
45
+ const secretBytes = encoder.encode(secret);
46
+ const tokenLength = tokenBytes.length;
47
+ const secretLength = secretBytes.length;
48
+ const decodedBytes = new Uint8Array(tokenLength);
49
+ for (let i = 0; i < tokenLength; i++) decodedBytes[i] = tokenBytes[i] ^ secretBytes[i % secretLength];
50
+ return decoder.decode(decodedBytes);
50
51
  }
51
- export function sign(data, secret, { expiresIn = 0, sl = 32 } = {}) {
52
- const salt = genSalt(sl);
53
- const token = encode(JSON.stringify({ data, iat: Date.now(), exp: expiresIn }), salt, 1);
54
- const signature = encode(salt, secret, 0);
55
- return `${token}.${signature}`;
52
+
53
+ // src/lib/token.ts
54
+ function validateData(token, secret, getData) {
55
+ try {
56
+ const { data, iat, exp } = JSON.parse(getData(token, secret));
57
+ if (exp && Date.now() > iat + exp) throw new Error("Expired token!");
58
+ return data;
59
+ } catch (error) {
60
+ throw new Error("Invalid token or secret!");
61
+ }
56
62
  }
57
- export function verify(token, secret) {
58
- try {
59
- const [dataStr, signature] = token.split(".");
60
- const salt = decode(signature, secret, 0);
61
- const { data, iat, exp } = JSON.parse(decode(dataStr, salt, 1));
62
- if (!exp || Date.now() < iat + exp)
63
- return data;
64
- throw new Error();
65
- }
66
- catch (_a) {
67
- throw new Error("Invalid token or secret!");
68
- }
63
+
64
+ // src/index.ts
65
+ function sign(data, secret, { expiresIn = 0, sl = 32 } = {}) {
66
+ const salt = genSalt(sl);
67
+ const token = encode(JSON.stringify({ data, iat: Date.now(), exp: expiresIn }), salt, 1);
68
+ const signature = encode(salt, secret, 0);
69
+ return `${token}.${signature}`;
69
70
  }
70
- export function encrypt(data, secret, { expiresIn = 0 } = {}, sjclOptions) {
71
- const encryptedObj = JSON.parse(sjcl.encrypt(secret, JSON.stringify({ data, iat: Date.now(), exp: expiresIn }), sjclOptions));
72
- const encryptedArr = Object.entries(encryptedObj).map(([key, value]) => `${key}:${value}`);
73
- return encryptedArr.join(".");
71
+ function verify(token, secret) {
72
+ return validateData(token, secret, (token2, secret2) => {
73
+ const [dataStr, signature] = token2.split(".");
74
+ const salt = decode(signature, secret2, 0);
75
+ return decode(dataStr, salt, 1);
76
+ });
74
77
  }
75
- export function decrypt(token, secret) {
76
- try {
77
- const encryptedArr = token.split(".");
78
- const encryptedObj = encryptedArr.reduce((obj, str) => {
79
- const [key, value] = str.split(":");
80
- obj[key] = +value || value;
81
- return obj;
82
- }, {});
83
- const { data, iat, exp } = JSON.parse(sjcl.decrypt(secret, JSON.stringify(encryptedObj)));
84
- if (!exp || Date.now() < iat + exp)
85
- return data;
86
- throw new Error();
87
- }
88
- catch (_a) {
89
- throw new Error("Invalid token or secret!");
90
- }
78
+ function encrypt(data, secret, { expiresIn = 0 } = {}, sjclOptions) {
79
+ const encryptedObj = JSON.parse(sjcl.encrypt(secret, JSON.stringify({ data, iat: Date.now(), exp: expiresIn }), sjclOptions));
80
+ const encryptedArr = Object.entries(encryptedObj).map(([key, value]) => `${key}:${value}`);
81
+ return encryptedArr.join(".");
91
82
  }
83
+ function decrypt(token, secret) {
84
+ return validateData(token, secret, (token2, secret2) => {
85
+ const encryptedArr = token2.split(".");
86
+ const encryptedObj = encryptedArr.reduce((obj, str) => {
87
+ const [key, value] = str.split(":");
88
+ obj[key] = isNaN(+value) ? value : +value;
89
+ return obj;
90
+ }, {});
91
+ return sjcl.decrypt(secret2, JSON.stringify(encryptedObj));
92
+ });
93
+ }
94
+
95
+ export { decrypt, encrypt, sign, verify };
@@ -0,0 +1,12 @@
1
+ import { SjclCipherEncryptParams } from 'sjcl';
2
+
3
+ type CipherMode = 0 | 1;
4
+ type EncryptOptions = {
5
+ expiresIn?: number;
6
+ };
7
+ type SignOptions = EncryptOptions & {
8
+ sl?: number;
9
+ };
10
+ type SjclOptions = SjclCipherEncryptParams;
11
+
12
+ export type { CipherMode, EncryptOptions, SignOptions, SjclOptions };
@@ -0,0 +1 @@
1
+
package/package.json CHANGED
@@ -1,46 +1,65 @@
1
- {
2
- "name": "jssign",
3
- "version": "0.3.6",
4
- "description": "A token generator library to encode and decode data using a secret key",
5
- "main": "dist/cjs/index.js",
6
- "module": "dist/esm/index.js",
7
- "types": "dist/esm/index.d.ts",
8
- "scripts": {
9
- "esm": "tsc",
10
- "cjs": "tsc --module commonjs --outDir dist/cjs --declaration false",
11
- "build": "bun i && bun esm && bun cjs"
12
- },
13
- "repository": {
14
- "type": "git",
15
- "url": "git+https://github.com/SahilAggarwal2004/jssign.git"
16
- },
17
- "keywords": [
18
- "jssign",
19
- "jss",
20
- "javascript",
21
- "sign",
22
- "javascriptsign",
23
- "token",
24
- "encryption",
25
- "decryption",
26
- "jsonwebtoken",
27
- "sjcl",
28
- "typescript",
29
- "js",
30
- "encoder",
31
- "decoder",
32
- "jwt-alternative"
33
- ],
34
- "author": "Sahil Aggarwal",
35
- "license": "MIT",
36
- "bugs": {
37
- "url": "https://github.com/SahilAggarwal2004/jssign/issues"
38
- },
39
- "homepage": "https://github.com/SahilAggarwal2004/jssign#readme",
40
- "dependencies": {
41
- "sjcl": "^1.0.8"
42
- },
43
- "devDependencies": {
44
- "@types/sjcl": "^1.0.34"
45
- }
1
+ {
2
+ "name": "jssign",
3
+ "version": "0.3.7",
4
+ "description": "A token generator library to encode and decode data using a secret key",
5
+ "license": "MIT",
6
+ "author": "Sahil Aggarwal <aggarwalsahil2004@gmail.com>",
7
+ "homepage": "https://github.com/SahilAggarwal2004/jssign#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/SahilAggarwal2004/jssign.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/SahilAggarwal2004/jssign/issues"
14
+ },
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/esm/index.js",
19
+ "require": "./dist/cjs/index.cjs"
20
+ },
21
+ "./types": "./dist/esm/types.js"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "sideEffects": false,
27
+ "types": "dist/esm/index.d.ts",
28
+ "dependencies": {
29
+ "sjcl": "^1.0.8"
30
+ },
31
+ "devDependencies": {
32
+ "@release-it/conventional-changelog": "^10.0.4",
33
+ "@types/sjcl": "^1.0.34",
34
+ "prettier-package-json": "^2.8.0",
35
+ "release-it": "^19.2.2",
36
+ "tsup": "^8.5.1",
37
+ "typescript": "^5.9.3"
38
+ },
39
+ "keywords": [
40
+ "decoder",
41
+ "decryption",
42
+ "encoder",
43
+ "encryption",
44
+ "javascript",
45
+ "javascriptsign",
46
+ "js",
47
+ "jsonwebtoken",
48
+ "jss",
49
+ "jssign",
50
+ "jwt-alternative",
51
+ "sign",
52
+ "sjcl",
53
+ "token",
54
+ "typescript"
55
+ ],
56
+ "scripts": {
57
+ "build": "pnpm i && pnpm run compile",
58
+ "compile": "tsup",
59
+ "dev": "tsup --watch",
60
+ "dry-release": "release-it --ci --dry-run",
61
+ "prettier": "prettier-package-json --write package.json",
62
+ "pub": "pnpm login && pnpm publish",
63
+ "release": "release-it --ci"
64
+ }
46
65
  }
package/dist/cjs/index.js DELETED
@@ -1,101 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.decrypt = exports.encrypt = exports.verify = exports.sign = void 0;
7
- const sjcl_1 = __importDefault(require("sjcl"));
8
- const characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "[", "]", ";", ",", ".", "/", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "{", "}", ":", "<", ">", "?"];
9
- const encoder = new TextEncoder();
10
- const decoder = new TextDecoder();
11
- const randomNumber = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
12
- const randomElement = (array) => array[randomNumber(0, array.length - 1)];
13
- const textToChars = (text) => text.split("").map((c) => c.charCodeAt(0));
14
- const byteHex = (n) => ("0" + Number(n).toString(16)).slice(-2);
15
- const stringFromCode = (code) => String.fromCharCode(code);
16
- function genSalt(length) {
17
- let salt = randomElement(characters);
18
- for (let i = 1; i < length; i++)
19
- salt += randomElement(characters);
20
- return salt;
21
- }
22
- function encode(data, secret, type) {
23
- if (type === 0) {
24
- const applySecret = (code) => textToChars(secret).reduce((a, b) => a ^ b, code);
25
- return data.toString().split("").map(textToChars).map(applySecret).map(byteHex).join("");
26
- }
27
- const dataBytes = encoder.encode(data);
28
- const secretBytes = encoder.encode(secret);
29
- const dataLength = dataBytes.length;
30
- const secretLength = secretBytes.length;
31
- const tokenBytes = new Uint8Array(dataLength);
32
- for (let i = 0; i < dataLength; i++)
33
- tokenBytes[i] = dataBytes[i] ^ secretBytes[i % secretLength];
34
- return Array.from(tokenBytes)
35
- .map((byte) => byte.toString(16).padStart(2, "0"))
36
- .join("");
37
- }
38
- function decode(token, secret, type) {
39
- if (type === 0) {
40
- const applySecret = (code) => textToChars(secret).reduce((a, b) => a ^ b, code);
41
- return token
42
- .match(/.{1,2}/g)
43
- .map((hex) => parseInt(hex, 16))
44
- .map(applySecret)
45
- .map(stringFromCode)
46
- .join("");
47
- }
48
- const tokenBytes = new Uint8Array(token.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
49
- const secretBytes = encoder.encode(secret);
50
- const tokenLength = tokenBytes.length;
51
- const secretLength = secretBytes.length;
52
- const decodedBytes = new Uint8Array(tokenLength);
53
- for (let i = 0; i < tokenLength; i++)
54
- decodedBytes[i] = tokenBytes[i] ^ secretBytes[i % secretLength];
55
- return decoder.decode(decodedBytes);
56
- }
57
- function sign(data, secret, { expiresIn = 0, sl = 32 } = {}) {
58
- const salt = genSalt(sl);
59
- const token = encode(JSON.stringify({ data, iat: Date.now(), exp: expiresIn }), salt, 1);
60
- const signature = encode(salt, secret, 0);
61
- return `${token}.${signature}`;
62
- }
63
- exports.sign = sign;
64
- function verify(token, secret) {
65
- try {
66
- const [dataStr, signature] = token.split(".");
67
- const salt = decode(signature, secret, 0);
68
- const { data, iat, exp } = JSON.parse(decode(dataStr, salt, 1));
69
- if (!exp || Date.now() < iat + exp)
70
- return data;
71
- throw new Error();
72
- }
73
- catch (_a) {
74
- throw new Error("Invalid token or secret!");
75
- }
76
- }
77
- exports.verify = verify;
78
- function encrypt(data, secret, { expiresIn = 0 } = {}, sjclOptions) {
79
- const encryptedObj = JSON.parse(sjcl_1.default.encrypt(secret, JSON.stringify({ data, iat: Date.now(), exp: expiresIn }), sjclOptions));
80
- const encryptedArr = Object.entries(encryptedObj).map(([key, value]) => `${key}:${value}`);
81
- return encryptedArr.join(".");
82
- }
83
- exports.encrypt = encrypt;
84
- function decrypt(token, secret) {
85
- try {
86
- const encryptedArr = token.split(".");
87
- const encryptedObj = encryptedArr.reduce((obj, str) => {
88
- const [key, value] = str.split(":");
89
- obj[key] = +value || value;
90
- return obj;
91
- }, {});
92
- const { data, iat, exp } = JSON.parse(sjcl_1.default.decrypt(secret, JSON.stringify(encryptedObj)));
93
- if (!exp || Date.now() < iat + exp)
94
- return data;
95
- throw new Error();
96
- }
97
- catch (_a) {
98
- throw new Error("Invalid token or secret!");
99
- }
100
- }
101
- exports.decrypt = decrypt;