@payello-module/jwt 0.1.1 → 0.1.3
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/JWT.d.ts +22 -0
- package/dist/JWT.js +34 -2
- package/package.json +2 -2
- package/readme.md +82 -16
package/dist/JWT.d.ts
CHANGED
@@ -1,9 +1,31 @@
|
|
1
1
|
import { JwtSignOpts } from "./JwtSignOpts";
|
2
2
|
import { JwtExtract } from "./JwtExtract";
|
3
3
|
import { JwtExtractOpts } from "./JwtExtractOpts";
|
4
|
+
/**
|
5
|
+
* Class representing JSON Web Tokens (JWT) functionalities, including signing, extracting components,
|
6
|
+
* and verifying the signature of the token.
|
7
|
+
*/
|
4
8
|
export declare class JWT {
|
9
|
+
/**
|
10
|
+
* Signs the given payload and returns a JWT string.
|
11
|
+
* @param payload - The payload of the JWT which is the content that you want to protect.
|
12
|
+
* @param options - The options for signing the JWT, including the private key, public key, and algorithm.
|
13
|
+
* @returns A promise that resolves to the signed JWT string.
|
14
|
+
*/
|
5
15
|
static sign(payload: any, options?: JwtSignOpts): Promise<string>;
|
16
|
+
/**
|
17
|
+
* Extracts and returns the header, payload, and signature components from a JWT string.
|
18
|
+
* @param input - The JWT string to be parsed.
|
19
|
+
* @param opts - Optional parameters, including the requirements for the presence of required properties in the payload.
|
20
|
+
* @returns A promise that resolves to an object containing the separated components of the JWT (header, payload, signature).
|
21
|
+
*/
|
6
22
|
static extract(input: string, opts?: JwtExtractOpts): Promise<JwtExtract>;
|
23
|
+
/**
|
24
|
+
* Verifies the given JWT string using the secret key fetched by the given issuer.
|
25
|
+
* @param input - The JWT string to be verified.
|
26
|
+
* @param opts - An object containing a function getSecretKey to retrieve the secret key based on the issuer.
|
27
|
+
* @returns A promise that resolves to a boolean indicating whether the JWT has been verified successfully or not.
|
28
|
+
*/
|
7
29
|
static verify(input: string, opts: {
|
8
30
|
getSecretKey(issuer: string): Promise<string>;
|
9
31
|
}): Promise<true>;
|
package/dist/JWT.js
CHANGED
@@ -1,11 +1,22 @@
|
|
1
1
|
import { HmacSha256, HmacSha512 } from "@payello-module/encryption";
|
2
2
|
import { JwtError } from "./JwtError";
|
3
|
+
/**
|
4
|
+
* Class representing JSON Web Tokens (JWT) functionalities, including signing, extracting components,
|
5
|
+
* and verifying the signature of the token.
|
6
|
+
*/
|
3
7
|
export class JWT {
|
8
|
+
/**
|
9
|
+
* Signs the given payload and returns a JWT string.
|
10
|
+
* @param payload - The payload of the JWT which is the content that you want to protect.
|
11
|
+
* @param options - The options for signing the JWT, including the private key, public key, and algorithm.
|
12
|
+
* @returns A promise that resolves to the signed JWT string.
|
13
|
+
*/
|
4
14
|
static async sign(payload, options = { privKey: '', pubKey: '', algorithm: 'HS512' }) {
|
5
15
|
const _header = {
|
6
16
|
typ: 'JWT',
|
7
17
|
alg: options.algorithm
|
8
18
|
};
|
19
|
+
// Create payload with unique identifier, issued-at time, and incorporate the public key if provided.
|
9
20
|
const _payload = {
|
10
21
|
jti: `jti_${Date.now().valueOf()}`,
|
11
22
|
iat: Math.floor(Date.now().valueOf() / 1000),
|
@@ -14,6 +25,7 @@ export class JWT {
|
|
14
25
|
};
|
15
26
|
const _body = btoa(JSON.stringify(_header)) + "." + btoa(JSON.stringify(_payload));
|
16
27
|
let signature = "";
|
28
|
+
// Create signature based on selected algorithm.
|
17
29
|
switch (options.algorithm) {
|
18
30
|
case 'HS256':
|
19
31
|
signature = await HmacSha256.encrypt(_body, options.privKey);
|
@@ -22,41 +34,60 @@ export class JWT {
|
|
22
34
|
signature = await HmacSha512.encrypt(_body, options.privKey);
|
23
35
|
break;
|
24
36
|
}
|
37
|
+
// Returns the final JWT token as a concatenation of header, payload, and signature
|
25
38
|
return _body + "." + signature;
|
26
39
|
}
|
40
|
+
/**
|
41
|
+
* Extracts and returns the header, payload, and signature components from a JWT string.
|
42
|
+
* @param input - The JWT string to be parsed.
|
43
|
+
* @param opts - Optional parameters, including the requirements for the presence of required properties in the payload.
|
44
|
+
* @returns A promise that resolves to an object containing the separated components of the JWT (header, payload, signature).
|
45
|
+
*/
|
27
46
|
static async extract(input, opts = {}) {
|
28
47
|
const bits = input.split(".");
|
48
|
+
// Ensures that the JWT string has three parts: header, payload, and signature.
|
29
49
|
if (bits.length !== 3) {
|
30
50
|
throw new JwtError(`Invalid number of parts in JWT string. Expected 3 but got ${bits.length}`);
|
31
51
|
}
|
32
|
-
const header = JSON.parse(bits[0]);
|
52
|
+
const header = JSON.parse(atob(bits[0]));
|
33
53
|
if (!header || !header.typ || header.typ !== "JWT") {
|
34
54
|
throw new JwtError("Header invalid or type is not JWT");
|
35
55
|
}
|
36
|
-
const payload = JSON.parse(bits[1]);
|
56
|
+
const payload = JSON.parse(atob(bits[1]));
|
37
57
|
if (!payload || !payload.jti) {
|
38
58
|
throw new JwtError("Payload invalid or missing jti value");
|
39
59
|
}
|
60
|
+
// Validates the present of required properties in the payload.
|
40
61
|
const requiredProps = opts.requiredProps || ["jti", "iss", "iat"];
|
41
62
|
for (const prop in requiredProps) {
|
42
63
|
if (!payload[prop]) {
|
43
64
|
throw new JwtError(`Payload missing ${prop} value`);
|
44
65
|
}
|
45
66
|
}
|
67
|
+
// Returns an object containing the extracted components of the JWT.
|
46
68
|
return {
|
47
69
|
header: header,
|
48
70
|
payload: payload,
|
49
71
|
signature: bits[2]
|
50
72
|
};
|
51
73
|
}
|
74
|
+
/**
|
75
|
+
* Verifies the given JWT string using the secret key fetched by the given issuer.
|
76
|
+
* @param input - The JWT string to be verified.
|
77
|
+
* @param opts - An object containing a function getSecretKey to retrieve the secret key based on the issuer.
|
78
|
+
* @returns A promise that resolves to a boolean indicating whether the JWT has been verified successfully or not.
|
79
|
+
*/
|
52
80
|
static async verify(input, opts) {
|
53
81
|
const extracted = await this.extract(input);
|
82
|
+
// Fetches the secret key based on the issuer in the payload.
|
54
83
|
const secretKey = await opts.getSecretKey(extracted.payload.jti);
|
55
84
|
if (!secretKey) {
|
56
85
|
throw new JwtError(`Public key not found`);
|
57
86
|
}
|
58
87
|
let verify = false;
|
88
|
+
// Preparation of the data to verify the signature.
|
59
89
|
const data = `${btoa(JSON.stringify(extracted.header))}.${btoa(JSON.stringify(extracted.payload))}`;
|
90
|
+
// Verification of the signature based on the algorithm specified in the header.
|
60
91
|
switch (extracted.header.alg) {
|
61
92
|
case 'HS256':
|
62
93
|
verify = await HmacSha256.verify(data, extracted.signature, secretKey);
|
@@ -70,6 +101,7 @@ export class JWT {
|
|
70
101
|
if (!verify) {
|
71
102
|
throw new JwtError(`Signature not verified`);
|
72
103
|
}
|
104
|
+
// Returns the result of the verification process.
|
73
105
|
return verify;
|
74
106
|
}
|
75
107
|
}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@payello-module/jwt",
|
3
|
-
"version": "0.1.
|
3
|
+
"version": "0.1.3",
|
4
4
|
"author": "Payello <devsupport@payello.com> (https://payello.com/)",
|
5
5
|
"displayName": "@payello-module/jwt",
|
6
6
|
"description": "JSON Web Token Module",
|
@@ -23,6 +23,6 @@
|
|
23
23
|
"url": "https://git.fuse.hk/payello/dev/payello-module/jwt"
|
24
24
|
},
|
25
25
|
"dependencies": {
|
26
|
-
"@payello-module/encryption": "^0.1.
|
26
|
+
"@payello-module/encryption": "^0.1.3"
|
27
27
|
}
|
28
28
|
}
|
package/readme.md
CHANGED
@@ -1,28 +1,94 @@
|
|
1
1
|
# JWT Module
|
2
|
-
|
2
|
+
|
3
|
+
This is a TypeScript library for working with JSON Web Tokens (JWT). It provides easy-to-use asynchronous methods to sign, extract, and verify JWTs using HMAC SHA256 and HMAC SHA512 hashing algorithms.
|
4
|
+
|
5
|
+
This module relies on the `@payello-module/encryption` package for encryption operations.
|
6
|
+
|
7
|
+
## Features
|
8
|
+
|
9
|
+
- **Sign JWTs:** Create signed JWTs with custom payloads and options.
|
10
|
+
- **Extract JWTs:** Extract the payload, header, and signature from a JWT.
|
11
|
+
- **Verify JWTs:** Verify the authenticity of a JWT against a secret key.
|
12
|
+
|
13
|
+
## Installation
|
14
|
+
|
15
|
+
You can install the module using npm or yarn:
|
16
|
+
|
17
|
+
```shell
|
18
|
+
npm install @payello-module/jwt
|
19
|
+
# or
|
20
|
+
yarn add @payello-module/jwt
|
21
|
+
```
|
3
22
|
|
4
23
|
## Usage
|
5
|
-
|
24
|
+
|
25
|
+
### Signing a JWT
|
26
|
+
|
27
|
+
```typescript
|
28
|
+
import { JWT } from '@payello-module/jwt';
|
29
|
+
|
30
|
+
const payload = { /* Your JWT payload here */ };
|
31
|
+
const options = {
|
32
|
+
privKey: 'your_private_key',
|
33
|
+
pubKey: 'your_public_key',
|
34
|
+
algorithm: 'HS512' // or 'HS256'
|
35
|
+
};
|
36
|
+
|
37
|
+
JWT.sign(payload, options)
|
38
|
+
.then(token => console.log(token))
|
39
|
+
.catch(error => console.error(error));
|
6
40
|
```
|
7
|
-
|
41
|
+
|
42
|
+
### Extracting a JWT
|
43
|
+
|
44
|
+
```typescript
|
45
|
+
import { JWT } from '@payello-module/jwt';
|
46
|
+
|
47
|
+
const token = 'your.jwt.token';
|
48
|
+
|
49
|
+
JWT.extract(token)
|
50
|
+
.then(({ header, payload, signature }) => {
|
51
|
+
console.log(header, payload, signature);
|
52
|
+
})
|
53
|
+
.catch(error => console.error(error));
|
8
54
|
```
|
9
55
|
|
10
|
-
|
11
|
-
```ts
|
12
|
-
import { JWT } from "@payello-module/jwt";
|
56
|
+
### Verifying a JWT
|
13
57
|
|
14
|
-
|
15
|
-
|
16
|
-
};
|
58
|
+
```typescript
|
59
|
+
import { JWT } from '@payello-module/jwt';
|
17
60
|
|
18
|
-
const
|
19
|
-
|
20
|
-
|
21
|
-
|
61
|
+
const token = 'your.jwt.token';
|
62
|
+
const getSecretKey = async (issuer) => {
|
63
|
+
// Logic to retrieve the secret key for a given issuer
|
64
|
+
return 'secret_key';
|
22
65
|
};
|
23
66
|
|
24
|
-
|
67
|
+
JWT.verify(token, { getSecretKey })
|
68
|
+
.then(isVerified => console.log(isVerified))
|
69
|
+
.catch(error => console.error(error));
|
70
|
+
```
|
71
|
+
|
72
|
+
## API Reference
|
73
|
+
|
74
|
+
#### `JWT.sign(payload: any, options: JwtSignOpts): Promise<string>`
|
75
|
+
|
76
|
+
Signs the provided payload and returns a JWT string.
|
77
|
+
|
78
|
+
#### `JWT.extract(input: string, opts: JwtExtractOpts): Promise<JwtExtract>`
|
79
|
+
|
80
|
+
Extracts and returns the header, payload, and signature from a JWT string.
|
81
|
+
|
82
|
+
#### `JWT.verify(input: string, opts: { getSecretKey(issuer: string): Promise<string> }): Promise<boolean>`
|
83
|
+
|
84
|
+
Verifies a JWT string against a secret key retrieved by the `getSecretKey` function.
|
85
|
+
|
86
|
+
## Contributing
|
25
87
|
|
26
|
-
|
88
|
+
We welcome contributions to this module! Please consider the following guidelines when contributing:
|
27
89
|
|
28
|
-
|
90
|
+
1. Fork the repository and create your branch from `main`.
|
91
|
+
2. If you've added code that should be tested, add tests.
|
92
|
+
3. Ensure your code passes existing tests.
|
93
|
+
4. Ensure your code follows the existing code style.
|
94
|
+
5. Issue that pull request!
|