1
0

Compare commits

...

4 Commits

Author SHA1 Message Date
f846695242 Update docs 2022-06-04 17:29:50 +02:00
695e1c0dfe .decode() syntax change to support headers 2022-06-04 17:23:53 +02:00
64da4c625f .verify() bugfix 2022-06-04 14:53:59 +02:00
e4038ae0a7 Just to make sure 2022-06-04 14:40:06 +02:00
5 changed files with 46 additions and 15 deletions

View File

@@ -36,7 +36,7 @@ async () => {
return return
// Decoding token // Decoding token
const payload = jwt.decode(token) const { payload } = jwt.decode(token)
} }
``` ```
@@ -62,15 +62,20 @@ async () => {
return return
// Decoding token // Decoding token
const payload = jwt.decode(token) // { name: 'John Doe', email: 'john.doe@gmail.com', ... } const { payload } = jwt.decode(token) // { name: 'John Doe', email: 'john.doe@gmail.com', ... }
} }
``` ```
## Usage ## Usage
- [Sign](#sign)
- [Verify](#verify)
- [Decode](#decode)
<hr> <hr>
### `jwt.sign(payload, secret, [options])` ### Sign
#### `jwt.sign(payload, secret, [options])`
Signs a payload and returns the token. Signs a payload and returns the token.
@@ -87,7 +92,8 @@ Returns token as a `string`.
<hr> <hr>
### `jwt.verify(token, secret, [options])` ### Verify
#### `jwt.verify(token, secret, [options])`
Verifies the integrity of the token and returns a boolean value. Verifies the integrity of the token and returns a boolean value.
@@ -102,7 +108,8 @@ Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherw
<hr> <hr>
### `jwt.decode(token)` ### Decode
#### `jwt.decode(token)`
Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure! Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure!
@@ -111,7 +118,19 @@ Argument | Type | Satus | Default | Description
`token` | `string` | required | - | The token string generated by `jwt.sign()`. `token` | `string` | required | - | The token string generated by `jwt.sign()`.
#### `return` #### `return`
Returns payload `object`. Returns an `object` containing `header` and `payload`:
```javascript
{
header: {
alg: 'HS256',
typ: 'JWT'
},
payload: {
name: 'John Doe',
email: 'john.doe@gmail.com'
}
}
```
### Available Algorithms ### Available Algorithms
- ES256 - ES256

9
index.d.ts vendored
View File

@@ -33,9 +33,9 @@ declare class JWT {
* Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure! * Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure!
* *
* @param {string} token The token string generated by `jwt.sign()`. * @param {string} token The token string generated by `jwt.sign()`.
* @returns {object | null} Returns payload `object`. * @returns {JWTDecodeReturn} Returns an `object` containing `header` and `payload`.
*/ */
decode(token: string): object | null decode(token: string): JWTDecodeReturn
} }
declare const _exports: JWT declare const _exports: JWT
@@ -52,4 +52,9 @@ type JWTVerifyOptions = {
throwError?: boolean throwError?: boolean
} }
type JWTDecodeReturn = {
header: object,
payload: object
}
export = _exports export = _exports

View File

@@ -113,10 +113,13 @@ class JWT {
} else } else
keyData = this._utf8ToUint8Array(secret) keyData = this._utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey(keyFormat, keyData, importAlgorithm, false, ['verify']) const key = await crypto.subtle.importKey(keyFormat, keyData, importAlgorithm, false, ['verify'])
return await crypto.subtle.verify(importAlgorithm, key, Base64URL.parse(tokenParts[2]), `${tokenParts[0]}.${tokenParts[1]}`) return await crypto.subtle.verify(importAlgorithm, key, Base64URL.parse(tokenParts[2]), this._utf8ToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`))
} }
decode(token) { decode(token) {
return this._decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')) return {
header: this._decodePayload(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')),
payload: this._decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
}
} }
} }

View File

@@ -1,4 +1,4 @@
const { subtle } = require('crypto').webcrypto const { subtle } = require('node:crypto').webcrypto
Object.defineProperty(global, 'crypto', { Object.defineProperty(global, 'crypto', {
value: { subtle } value: { subtle }
}) })
@@ -115,12 +115,14 @@ test.each(Object.entries(secrets))(`Self test: %s`, async (algorithm, key) => {
privateKey = key.private privateKey = key.private
publicKey = key.public publicKey = key.public
} }
const token = await JWT.sign(testPayload, privateKey, { algorithm }) const token = await JWT.sign(testPayload, privateKey, { algorithm })
expect(token).toMatch(/^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+$/) expect(token).toMatch(/^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+$/)
const verified = await JWT.verify(token, publicKey, { algorithm }) const verified = await JWT.verify(token, publicKey, { algorithm })
expect(verified).toBeTruthy() expect(verified).toBeTruthy()
const payload = JWT.decode(token)
expect(payload).toBeTruthy() const { payload } = JWT.decode(token)
expect({ expect({
sub: payload.sub, sub: payload.sub,
name: payload.name name: payload.name
@@ -151,9 +153,11 @@ test.each(Object.entries(externalTokens))('Verify external tokens: %s', async (a
privateKey = key.private privateKey = key.private
publicKey = key.public publicKey = key.public
} }
const verified = await JWT.verify(token, publicKey, { algorithm }) const verified = await JWT.verify(token, publicKey, { algorithm })
expect(verified).toBeTruthy() expect(verified).toBeTruthy()
const payload = JWT.decode(token)
const { payload } = JWT.decode(token)
expect({ expect({
sub: payload.sub, sub: payload.sub,
name: payload.name name: payload.name

View File

@@ -1,6 +1,6 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "1.3.0", "version": "1.4.0",
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker", "description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {