1
0

Compare commits

..

9 Commits

Author SHA1 Message Date
1de6acbfff 2.1.4 2022-12-14 14:42:51 +01:00
b002db4547 option to set iat 2022-12-14 14:42:23 +01:00
1bdbd0a5c5 2.1.3 2022-11-25 00:34:50 +01:00
883ec55b73 ocd 2022-11-25 00:32:26 +01:00
Can Rau
c515fb76e6 docs: don't install as dev dependency (I think?)
Think the installation command shouldn't use `-D` as it's used in the production code right, so installing as dev dep would be confusing, right?

Please correct me if I'm wrong 🙏

Also thanks a lot for this package, was just using for a way to sign and verify JWT in Pages ❤️
2022-11-25 00:07:00 +01:00
ec41207832 2.1.2 2022-10-09 20:56:50 +02:00
e64e89f325 fix typo 2022-10-09 20:56:35 +02:00
fb573d928a 2.1.1 2022-10-09 20:48:01 +02:00
382ad66ea9 Revert "support for base64 secrets"
This reverts commit 67f1a8e5ed.
2022-10-09 20:47:29 +02:00
4 changed files with 33 additions and 34 deletions

View File

@@ -16,7 +16,7 @@ A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
## Install ## Install
``` ```
npm i -D @tsndr/cloudflare-worker-jwt npm i @tsndr/cloudflare-worker-jwt
``` ```
@@ -84,7 +84,7 @@ Signs a payload and returns the token.
#### Arguments #### Arguments
Argument | Type | Satus | Default | Description Argument | Type | Status | Default | Description
----------- | -------- | -------- | ------- | ----------- ----------- | -------- | -------- | ------- | -----------
`payload` | `object` | required | - | The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload. `payload` | `object` | required | - | The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
`secret` | `string` | required | - | A string which is used to sign the payload. `secret` | `string` | required | - | A string which is used to sign the payload.
@@ -100,7 +100,7 @@ Returns token as a `string`.
Verifies the integrity of the token and returns a boolean value. Verifies the integrity of the token and returns a boolean value.
Argument | Type | Satus | Default | Description Argument | Type | Status | Default | Description
----------- | -------- | -------- | ------- | ----------- ----------- | -------- | -------- | ------- | -----------
`token` | `string` | required | - | The token string generated by `jwt.sign()`. `token` | `string` | required | - | The token string generated by `jwt.sign()`.
`secret` | `string` | required | - | The string which was used to sign the payload. `secret` | `string` | required | - | The string which was used to sign the payload.
@@ -119,7 +119,7 @@ Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherw
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!
Argument | Type | Satus | Default | Description Argument | Type | Status | Default | Description
----------- | -------- | -------- | ------- | ----------- ----------- | -------- | -------- | ------- | -----------
`token` | `string` | required | - | The token string generated by `jwt.sign()`. `token` | `string` | required | - | The token string generated by `jwt.sign()`.

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "2.1.0", "version": "2.1.4",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "2.1.0", "version": "2.1.4",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@cloudflare/workers-types": "^3.13.0", "@cloudflare/workers-types": "^3.13.0",

View File

@@ -1,6 +1,6 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "2.1.0", "version": "2.1.4",
"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",
"types": "index.d.ts", "types": "index.d.ts",

View File

@@ -129,17 +129,6 @@ const algorithms: JwtAlgorithms = {
RS512: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512' } } RS512: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512' } }
} }
function _parseSecret(secret: string): { raw: boolean, key: ArrayBuffer } {
if (secret.startsWith('-----BEGIN'))
return { raw: false, key: _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, '')) }
// Check for Base64
if (/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/.test(secret))
return { raw: true, key: base64UrlParse(secret) }
else
return { raw: true, key: _utf8ToUint8Array(secret) }
}
function _utf8ToUint8Array(str: string): Uint8Array { function _utf8ToUint8Array(str: string): Uint8Array {
return base64UrlParse(btoa(unescape(encodeURIComponent(str)))) return base64UrlParse(btoa(unescape(encodeURIComponent(str))))
} }
@@ -207,13 +196,19 @@ export async function sign(payload: JwtPayload, secret: string, options: JwtSign
if (!algorithm) if (!algorithm)
throw new Error('algorithm not found') throw new Error('algorithm not found')
if (!payload.iat)
payload.iat = Math.floor(Date.now() / 1000) payload.iat = Math.floor(Date.now() / 1000)
const payloadAsJSON = JSON.stringify(payload) const payloadAsJSON = JSON.stringify(payload)
const partialToken = `${base64UrlStringify(_utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm })))}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}` const partialToken = `${base64UrlStringify(_utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm })))}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}`
const parsedSecret = _parseSecret(secret) let keyFormat = 'raw'
let keyData
const key = await crypto.subtle.importKey(parsedSecret.raw ? 'raw' : 'pkcs8', parsedSecret.key, algorithm, false, ['sign']) if (secret.startsWith('-----BEGIN')) {
keyFormat = 'pkcs8'
keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, ''))
} else
keyData = _utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['sign'])
const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken)) const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken))
return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}` return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}`
@@ -275,11 +270,15 @@ export async function verify(token: string, secret: string, options: JwtVerifyOp
return false return false
} }
let keyFormat = 'raw'
const parsedSecret = _parseSecret(secret) let keyData
const key = await crypto.subtle.importKey(parsedSecret.raw ? 'raw' : 'spki', parsedSecret.key, algorithm, false, ['verify']) if (secret.startsWith('-----BEGIN')) {
keyFormat = 'spki'
return crypto.subtle.verify(algorithm, key, base64UrlParse(tokenParts[2]), _utf8ToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`)) keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, ''))
} else
keyData = _utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['verify'])
return await crypto.subtle.verify(algorithm, key, base64UrlParse(tokenParts[2]), _utf8ToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`))
} }
/** /**