1
0

Compare commits

...

20 Commits

Author SHA1 Message Date
a8f95f1c6d 2.2.2 2023-08-25 16:01:57 +02:00
Tom Lokhorst
b2886c0778 Allow array in Audience 2023-08-25 16:00:30 +02:00
76b7fcef27 2.2.1 2023-02-02 16:13:50 +01:00
3b5d8bcde8 hotfix 2023-02-02 16:13:28 +01:00
e22c509852 2.2.0 2023-02-02 15:48:08 +01:00
7ed375e876 audit fix 2023-02-02 15:46:10 +01:00
de658122b9 clean up 2023-02-02 15:46:10 +01:00
Michael Cereda
10dcf2f01b Support JWK format 2023-02-02 15:46:10 +01:00
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
ffc1e87b32 2.1.0 2022-10-03 01:58:51 +02:00
decfa65391 clean up 2022-10-03 01:57:59 +02:00
badoge
67f1a8e5ed support for base64 secrets 2022-10-03 01:54:28 +02:00
5 changed files with 88 additions and 46 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()`.

View File

@@ -22,9 +22,10 @@ const secrets = {}
// Keypairs // Keypairs
for (const algorithm of algorithms) { for (const algorithm of algorithms) {
if (algorithm.startsWith('HS')) if (algorithm.startsWith('HS')) {
//secrets[algorithm] = 'c2VjcmV0'
secrets[algorithm] = 'secret' secrets[algorithm] = 'secret'
else if (algorithm.startsWith('RS')) { } else if (algorithm.startsWith('RS')) {
secrets[algorithm] = { secrets[algorithm] = {
public: `-----BEGIN PUBLIC KEY----- public: `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo
@@ -122,6 +123,7 @@ const testPayload = {
test.each(Object.entries(secrets))(`Self test: %s`, async (algorithm, key) => { test.each(Object.entries(secrets))(`Self test: %s`, async (algorithm, key) => {
let privateKey = key let privateKey = key
let publicKey = key let publicKey = key
if (typeof key === 'object') { if (typeof key === 'object') {
privateKey = key.private privateKey = key.private
publicKey = key.public publicKey = key.public
@@ -158,12 +160,11 @@ const externalTokens = {
test.each(Object.entries(externalTokens))('Verify external tokens: %s', async (algorithm, token) => { test.each(Object.entries(externalTokens))('Verify external tokens: %s', async (algorithm, token) => {
const key = secrets[algorithm] const key = secrets[algorithm]
let privateKey = key
let publicKey = key let publicKey = key
if (typeof key === 'object') {
privateKey = key.private if (typeof key === 'object')
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()

16
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "2.0.1", "version": "2.2.2",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "2.0.1", "version": "2.2.2",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@cloudflare/workers-types": "^3.13.0", "@cloudflare/workers-types": "^3.13.0",
@@ -2542,9 +2542,9 @@
"dev": true "dev": true
}, },
"node_modules/json5": { "node_modules/json5": {
"version": "2.2.1", "version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"dev": true, "dev": true,
"bin": { "bin": {
"json5": "lib/cli.js" "json5": "lib/cli.js"
@@ -5364,9 +5364,9 @@
"dev": true "dev": true
}, },
"json5": { "json5": {
"version": "2.2.1", "version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"dev": true "dev": true
}, },
"kleur": { "kleur": {

View File

@@ -1,6 +1,6 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "2.0.1", "version": "2.2.2",
"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

@@ -33,7 +33,7 @@ export interface JwtHeader {
* @typedef JwtPayload * @typedef JwtPayload
* @prop {string} [iss] Issuer * @prop {string} [iss] Issuer
* @prop {string} [sub] Subject * @prop {string} [sub] Subject
* @prop {string} [aud] Audience * @prop {string | string[]} [aud] Audience
* @prop {string} [exp] Expiration Time * @prop {string} [exp] Expiration Time
* @prop {string} [nbf] Not Before * @prop {string} [nbf] Not Before
* @prop {string} [iat] Issued At * @prop {string} [iat] Issued At
@@ -47,7 +47,7 @@ export interface JwtPayload {
sub?: string sub?: string
/** Audience */ /** Audience */
aud?: string aud?: string | string[]
/** Expiration Time */ /** Expiration Time */
exp?: number exp?: number
@@ -135,11 +135,14 @@ function _utf8ToUint8Array(str: string): Uint8Array {
function _str2ab(str: string): ArrayBuffer { function _str2ab(str: string): ArrayBuffer {
str = atob(str) str = atob(str)
const buf = new ArrayBuffer(str.length); const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf); const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) { for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i); bufView[i] = str.charCodeAt(i);
} }
return buf; return buf;
} }
@@ -156,6 +159,7 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
default: default:
throw new Error('Illegal base64url string!') throw new Error('Illegal base64url string!')
} }
try { try {
return JSON.parse(decodeURIComponent(escape(atob(raw)))) return JSON.parse(decodeURIComponent(escape(atob(raw))))
} catch { } catch {
@@ -167,36 +171,52 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
* Signs a payload and returns the token * Signs a payload and returns the token
* *
* @param {JwtPayload} payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload. * @param {JwtPayload} payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
* @param {string} secret A string which is used to sign the payload. * @param {string | JsonWebKey} secret A string which is used to sign the payload.
* @param {JwtSignOptions | JwtAlgorithm | string} [options={ algorithm: 'HS256', header: { typ: 'JWT' } }] The options object or the algorithm. * @param {JwtSignOptions | JwtAlgorithm | string} [options={ algorithm: 'HS256', header: { typ: 'JWT' } }] The options object or the algorithm.
* @throws {Error} If there's a validation issue. * @throws {Error} If there's a validation issue.
* @returns {Promise<string>} Returns token as a `string`. * @returns {Promise<string>} Returns token as a `string`.
*/ */
export async function sign(payload: JwtPayload, secret: string, options: JwtSignOptions | JwtAlgorithm = { algorithm: 'HS256', header: { typ: 'JWT' } }): Promise<string> { export async function sign(payload: JwtPayload, secret: string | JsonWebKey, options: JwtSignOptions | JwtAlgorithm = { algorithm: 'HS256', header: { typ: 'JWT' } }): Promise<string> {
if (typeof options === 'string') if (typeof options === 'string')
options = { algorithm: options, header: { typ: 'JWT' } } options = { algorithm: options, header: { typ: 'JWT' } }
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options } options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
if (payload === null || typeof payload !== 'object') if (payload === null || typeof payload !== 'object')
throw new Error('payload must be an object') throw new Error('payload must be an object')
if (typeof secret !== 'string')
throw new Error('secret must be a string') if (typeof secret !== 'string' && typeof secret !== 'object')
throw new Error('secret must be a string or a JWK object')
if (typeof options.algorithm !== 'string') if (typeof options.algorithm !== 'string')
throw new Error('options.algorithm must be a string') throw new Error('options.algorithm must be a string')
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm] const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
if (!algorithm) if (!algorithm)
throw new Error('algorithm not found') throw new Error('algorithm not found')
payload.iat = Math.floor(Date.now() / 1000)
if (!payload.iat)
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))}`
let keyFormat = 'raw' let keyFormat = 'raw'
let keyData let keyData
if (secret.startsWith('-----BEGIN')) {
if (typeof secret === 'object') {
keyFormat = 'jwk'
keyData = secret
} else if (typeof secret === 'string' && secret.startsWith('-----BEGIN')) {
keyFormat = 'pkcs8' keyFormat = 'pkcs8'
keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, '')) keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, ''))
} else } else
keyData = _utf8ToUint8Array(secret) keyData = _utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['sign']) 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))}`
} }
@@ -204,51 +224,72 @@ export async function sign(payload: JwtPayload, secret: string, options: JwtSign
* Verifies the integrity of the token and returns a boolean value. * Verifies the integrity of the token and returns a boolean value.
* *
* @param {string} token The token string generated by `jwt.sign()`. * @param {string} token The token string generated by `jwt.sign()`.
* @param {string} secret The string which was used to sign the payload. * @param {string | JsonWebKey} secret The string which was used to sign the payload.
* @param {JWTVerifyOptions | JWTAlgorithm} options The options object or the algorithm. * @param {JWTVerifyOptions | JWTAlgorithm} options The options object or the algorithm.
* @throws {Error | string} Throws an error `string` if the token is invalid or an `Error-Object` if there's a validation issue. * @throws {Error | string} Throws an error `string` if the token is invalid or an `Error-Object` if there's a validation issue.
* @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`. * @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
*/ */
export async function verify(token: string, secret: string, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', throwError: false }): Promise<boolean> { export async function verify(token: string, secret: string | JsonWebKey, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', throwError: false }): Promise<boolean> {
if (typeof options === 'string') if (typeof options === 'string')
options = { algorithm: options, throwError: false } options = { algorithm: options, throwError: false }
options = { algorithm: 'HS256', throwError: false, ...options } options = { algorithm: 'HS256', throwError: false, ...options }
if (typeof token !== 'string') if (typeof token !== 'string')
throw new Error('token must be a string') throw new Error('token must be a string')
if (typeof secret !== 'string')
throw new Error('secret must be a string') if (typeof secret !== 'string' && typeof secret !== 'object')
throw new Error('secret must be a string or a JWK object')
if (typeof options.algorithm !== 'string') if (typeof options.algorithm !== 'string')
throw new Error('options.algorithm must be a string') throw new Error('options.algorithm must be a string')
const tokenParts = token.split('.') const tokenParts = token.split('.')
if (tokenParts.length !== 3) if (tokenParts.length !== 3)
throw new Error('token must consist of 3 parts') throw new Error('token must consist of 3 parts')
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm] const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
if (!algorithm) if (!algorithm)
throw new Error('algorithm not found') throw new Error('algorithm not found')
const { payload } = decode(token) const { payload } = decode(token)
if (!payload) { if (!payload) {
if (options.throwError) if (options.throwError)
throw 'PARSE_ERROR' throw 'PARSE_ERROR'
return false return false
} }
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) { if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {
if (options.throwError) if (options.throwError)
throw 'NOT_YET_VALID' throw 'NOT_YET_VALID'
return false return false
} }
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) { if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {
if (options.throwError) if (options.throwError)
throw 'EXPIRED' throw 'EXPIRED'
return false return false
} }
let keyFormat = 'raw' let keyFormat = 'raw'
let keyData let keyData
if (secret.startsWith('-----BEGIN')) {
if (typeof secret === 'object') {
keyFormat = 'jwk';
keyData = secret;
} else if (typeof secret === 'string' && secret.startsWith('-----BEGIN')) {
keyFormat = 'spki' keyFormat = 'spki'
keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, '')) keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, ''))
} else } else
keyData = _utf8ToUint8Array(secret) keyData = _utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['verify']) 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]}`)) return await crypto.subtle.verify(algorithm, key, base64UrlParse(tokenParts[2]), _utf8ToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`))
} }