Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
6594895273
|
|||
|
61a3a2ed50
|
|||
|
d7a6847206
|
|||
|
5ab19c4dc0
|
|||
|
0308d20c38
|
|||
|
703c0c4131
|
|||
|
6b3e828126
|
|||
|
35dc875f56
|
|||
|
|
11afa8eb87 | ||
|
|
b05345279d
|
||
|
|
55bc15bec4 | ||
|
|
b0d4084a0f | ||
|
|
3fd594bbb5 | ||
|
|
f8a216574a | ||
|
|
1f511549f5 | ||
|
|
4be64469d3 | ||
|
72e64f1316
|
|||
|
e235d835aa
|
|||
|
03c66f4223
|
|||
|
70488a6a48
|
|||
|
760245d1c7
|
|||
|
d40d924176
|
|||
|
c2e4fccf56
|
|||
|
0c0919f78d
|
|||
|
7299ea0614
|
|||
|
7004cd16ed
|
|||
|
5d4c51ad8a
|
|||
|
78a0eeee9c
|
|||
|
565c623005
|
|||
|
6b3192b4b9
|
|||
|
a659abecda
|
@@ -1,9 +1,9 @@
|
|||||||
.editorconfig
|
.editorconfig
|
||||||
.github/
|
.github/
|
||||||
|
.gitignore
|
||||||
.nvmrc
|
.nvmrc
|
||||||
index.spec.js
|
coverage/
|
||||||
index.test.js
|
|
||||||
jest.config.ts
|
jest.config.ts
|
||||||
src/
|
src/
|
||||||
test/
|
tests/
|
||||||
tsconfig.json
|
tsconfig.json
|
||||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "2.2.7",
|
"version": "2.4.2",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "2.2.7",
|
"version": "2.4.2",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@cloudflare/workers-types": "^4.20231025.0",
|
"@cloudflare/workers-types": "^4.20231025.0",
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "2.2.7",
|
"version": "2.4.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",
|
"type": "module",
|
||||||
|
"exports": "./index.js",
|
||||||
"types": "index.d.ts",
|
"types": "index.d.ts",
|
||||||
|
"engine": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"test": "jest"
|
"test": "jest"
|
||||||
|
|||||||
195
src/index.ts
195
src/index.ts
@@ -1,16 +1,25 @@
|
|||||||
|
import {
|
||||||
|
textToArrayBuffer,
|
||||||
|
arrayBufferToBase64Url,
|
||||||
|
base64UrlToArrayBuffer,
|
||||||
|
textToBase64Url,
|
||||||
|
importKey,
|
||||||
|
decodePayload
|
||||||
|
} from "./utils"
|
||||||
|
|
||||||
if (typeof crypto === 'undefined' || !crypto.subtle)
|
if (typeof crypto === 'undefined' || !crypto.subtle)
|
||||||
throw new Error('SubtleCrypto not supported!')
|
throw new Error('SubtleCrypto not supported!')
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef JwtAlgorithm
|
* @typedef JwtAlgorithm
|
||||||
* @type {'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'}
|
* @type {'ES256' | 'ES384' | 'ES512' | 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512'}
|
||||||
*/
|
*/
|
||||||
export type JwtAlgorithm = 'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'
|
export type JwtAlgorithm = 'ES256' | 'ES384' | 'ES512' | 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef JwtAlgorithms
|
* @typedef JwtAlgorithms
|
||||||
*/
|
*/
|
||||||
export interface JwtAlgorithms {
|
export type JwtAlgorithms = {
|
||||||
[key: string]: SubtleCryptoImportKeyAlgorithm
|
[key: string]: SubtleCryptoImportKeyAlgorithm
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,16 +27,14 @@ export interface JwtAlgorithms {
|
|||||||
* @typedef JwtHeader
|
* @typedef JwtHeader
|
||||||
* @prop {string} [typ] Type
|
* @prop {string} [typ] Type
|
||||||
*/
|
*/
|
||||||
export interface JwtHeader {
|
export type JwtHeader<T = {}> = {
|
||||||
/**
|
/**
|
||||||
* Type (default: `"JWT"`)
|
* Type (default: `"JWT"`)
|
||||||
*
|
*
|
||||||
* @default "JWT"
|
* @default "JWT"
|
||||||
*/
|
*/
|
||||||
typ?: string
|
typ?: string
|
||||||
|
} & T
|
||||||
[key: string]: any
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef JwtPayload
|
* @typedef JwtPayload
|
||||||
@@ -39,7 +46,7 @@ export interface JwtHeader {
|
|||||||
* @prop {string} [iat] Issued At
|
* @prop {string} [iat] Issued At
|
||||||
* @prop {string} [jti] JWT ID
|
* @prop {string} [jti] JWT ID
|
||||||
*/
|
*/
|
||||||
export interface JwtPayload {
|
export type JwtPayload<T = { [key: string]: any }> = {
|
||||||
/** Issuer */
|
/** Issuer */
|
||||||
iss?: string
|
iss?: string
|
||||||
|
|
||||||
@@ -60,15 +67,13 @@ export interface JwtPayload {
|
|||||||
|
|
||||||
/** JWT ID */
|
/** JWT ID */
|
||||||
jti?: string
|
jti?: string
|
||||||
|
} & T
|
||||||
[key: string]: any
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef JwtOptions
|
* @typedef JwtOptions
|
||||||
* @prop {JwtAlgorithm | string} algorithm
|
* @prop {JwtAlgorithm | string} algorithm
|
||||||
*/
|
*/
|
||||||
export interface JwtOptions {
|
export type JwtOptions = {
|
||||||
algorithm?: JwtAlgorithm | string
|
algorithm?: JwtAlgorithm | string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,49 +82,32 @@ export interface JwtOptions {
|
|||||||
* @extends JwtOptions
|
* @extends JwtOptions
|
||||||
* @prop {JwtHeader} [header]
|
* @prop {JwtHeader} [header]
|
||||||
*/
|
*/
|
||||||
export interface JwtSignOptions extends JwtOptions {
|
export type JwtSignOptions<T> = {
|
||||||
header?: JwtHeader
|
header?: JwtHeader<T>
|
||||||
}
|
} & JwtOptions
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef JwtVerifyOptions
|
* @typedef JwtVerifyOptions
|
||||||
* @extends JwtOptions
|
* @extends JwtOptions
|
||||||
* @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
|
* @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
|
||||||
*/
|
*/
|
||||||
export interface JwtVerifyOptions extends JwtOptions {
|
export type JwtVerifyOptions = {
|
||||||
/**
|
|
||||||
* If `true` all expiry checks will be skipped
|
|
||||||
*/
|
|
||||||
skipValidation?: boolean
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If `true` throw error if checks fail. (default: `false`)
|
* If `true` throw error if checks fail. (default: `false`)
|
||||||
*
|
*
|
||||||
* @default false
|
* @default false
|
||||||
*/
|
*/
|
||||||
throwError?: boolean
|
throwError?: boolean
|
||||||
}
|
} & JwtOptions
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef JwtData
|
* @typedef JwtData
|
||||||
* @prop {JwtHeader} header
|
* @prop {JwtHeader} header
|
||||||
* @prop {JwtPayload} payload
|
* @prop {JwtPayload} payload
|
||||||
*/
|
*/
|
||||||
export interface JwtData {
|
export type JwtData<Payload = {}, Header = {}> = {
|
||||||
header: JwtHeader
|
header?: JwtHeader<Header>
|
||||||
payload: JwtPayload
|
payload?: JwtPayload<Payload>
|
||||||
}
|
|
||||||
|
|
||||||
function base64UrlParse(s: string): Uint8Array {
|
|
||||||
// @ts-ignore
|
|
||||||
return new Uint8Array(Array.prototype.map.call(atob(s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '')), c => c.charCodeAt(0)))
|
|
||||||
// return new Uint8Array(Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''))).map(c => c.charCodeAt(0)))
|
|
||||||
}
|
|
||||||
|
|
||||||
function base64UrlStringify(a: Uint8Array): string {
|
|
||||||
// @ts-ignore
|
|
||||||
return btoa(String.fromCharCode.apply(0, a)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
|
||||||
// return btoa(String.fromCharCode.apply(0, Array.from(a))).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const algorithms: JwtAlgorithms = {
|
const algorithms: JwtAlgorithms = {
|
||||||
@@ -134,64 +122,26 @@ const algorithms: JwtAlgorithms = {
|
|||||||
RS512: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512' } }
|
RS512: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512' } }
|
||||||
}
|
}
|
||||||
|
|
||||||
function _utf8ToUint8Array(str: string): Uint8Array {
|
|
||||||
return base64UrlParse(btoa(unescape(encodeURIComponent(str))))
|
|
||||||
}
|
|
||||||
|
|
||||||
function _str2ab(str: string): ArrayBuffer {
|
|
||||||
str = atob(str)
|
|
||||||
|
|
||||||
const buf = new ArrayBuffer(str.length);
|
|
||||||
const bufView = new Uint8Array(buf);
|
|
||||||
|
|
||||||
for (let i = 0, strLen = str.length; i < strLen; i++) {
|
|
||||||
bufView[i] = str.charCodeAt(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
return buf;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
|
|
||||||
switch (raw.length % 4) {
|
|
||||||
case 0:
|
|
||||||
break
|
|
||||||
case 2:
|
|
||||||
raw += '=='
|
|
||||||
break
|
|
||||||
case 3:
|
|
||||||
raw += '='
|
|
||||||
break
|
|
||||||
default:
|
|
||||||
throw new Error('Illegal base64url string!')
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
return JSON.parse(decodeURIComponent(escape(atob(raw))))
|
|
||||||
} catch {
|
|
||||||
return 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 | JsonWebKey} secret A string which is used to sign the payload.
|
* @param {string | JsonWebKey | CryptoKey} 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 | JsonWebKey, options: JwtSignOptions | JwtAlgorithm = { algorithm: 'HS256', header: { typ: 'JWT' } }): Promise<string> {
|
export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payload>, secret: string | JsonWebKey, options: JwtSignOptions<Header> | JwtAlgorithm = 'HS256'): Promise<string> {
|
||||||
if (typeof options === 'string')
|
if (typeof options === 'string')
|
||||||
options = { algorithm: options, header: { typ: 'JWT' } }
|
options = { algorithm: options }
|
||||||
|
|
||||||
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
|
options = { algorithm: 'HS256', header: { typ: 'JWT' } as JwtHeader<Header>, ...options }
|
||||||
|
|
||||||
if (payload === null || typeof payload !== 'object')
|
if (!payload || typeof payload !== 'object')
|
||||||
throw new Error('payload must be an object')
|
throw new Error('payload must be an object')
|
||||||
|
|
||||||
if (typeof secret !== 'string' && typeof secret !== 'object')
|
if (!secret || (typeof secret !== 'string' && typeof secret !== 'object'))
|
||||||
throw new Error('secret must be a string or a JWK object')
|
throw new Error('secret must be a string, a JWK object or a CryptoKey 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')
|
||||||
@@ -204,47 +154,34 @@ export async function sign(payload: JwtPayload, secret: string | JsonWebKey, opt
|
|||||||
if (!payload.iat)
|
if (!payload.iat)
|
||||||
payload.iat = Math.floor(Date.now() / 1000)
|
payload.iat = Math.floor(Date.now() / 1000)
|
||||||
|
|
||||||
const payloadAsJSON = JSON.stringify(payload)
|
const partialToken = `${textToBase64Url(JSON.stringify({ ...options.header, alg: options.algorithm }))}.${textToBase64Url(JSON.stringify(payload))}`
|
||||||
const partialToken = `${base64UrlStringify(_utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm })))}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}`
|
|
||||||
|
|
||||||
let keyFormat = 'raw'
|
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm)
|
||||||
let keyData
|
const signature = await crypto.subtle.sign(algorithm, key, textToArrayBuffer(partialToken))
|
||||||
|
|
||||||
if (typeof secret === 'object') {
|
return `${partialToken}.${arrayBufferToBase64Url(signature)}`
|
||||||
keyFormat = 'jwk'
|
|
||||||
keyData = secret
|
|
||||||
} else if (typeof secret === 'string' && 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))
|
|
||||||
|
|
||||||
return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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 | JsonWebKey} secret The string which was used to sign the payload.
|
* @param {string | JsonWebKey | CryptoKey} 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 | JsonWebKey, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', skipValidation: false, throwError: false }): Promise<boolean> {
|
export async function verify(token: string, secret: string | JsonWebKey | CryptoKey, 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', skipValidation: false, 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' && typeof secret !== 'object')
|
if (typeof secret !== 'string' && typeof secret !== 'object')
|
||||||
throw new Error('secret must be a string or a JWK object')
|
throw new Error('secret must be a string, a JWK object or a CryptoKey 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')
|
||||||
@@ -261,41 +198,25 @@ export async function verify(token: string, secret: string | JsonWebKey, options
|
|||||||
|
|
||||||
const { payload } = decode(token)
|
const { payload } = decode(token)
|
||||||
|
|
||||||
if (!options.skipValidation && !payload) {
|
try {
|
||||||
|
if (!payload)
|
||||||
|
throw new Error('PARSE_ERROR')
|
||||||
|
|
||||||
|
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000))
|
||||||
|
throw new Error('NOT_YET_VALID')
|
||||||
|
|
||||||
|
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000))
|
||||||
|
throw new Error('EXPIRED')
|
||||||
|
|
||||||
|
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm)
|
||||||
|
|
||||||
|
return await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`))
|
||||||
|
} catch(err) {
|
||||||
if (options.throwError)
|
if (options.throwError)
|
||||||
throw 'PARSE_ERROR'
|
throw err
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!options.skipValidation && payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {
|
|
||||||
if (options.throwError)
|
|
||||||
throw 'NOT_YET_VALID'
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!options.skipValidation && payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {
|
|
||||||
if (options.throwError)
|
|
||||||
throw 'EXPIRED'
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
let keyFormat = 'raw'
|
|
||||||
let keyData
|
|
||||||
|
|
||||||
if (typeof secret === 'object') {
|
|
||||||
keyFormat = 'jwk';
|
|
||||||
keyData = secret;
|
|
||||||
} else if (typeof secret === 'string' && secret.startsWith('-----BEGIN')) {
|
|
||||||
keyFormat = 'spki'
|
|
||||||
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]}`))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -304,10 +225,10 @@ export async function verify(token: string, secret: string | JsonWebKey, options
|
|||||||
* @param {string} token The token string generated by `jwt.sign()`.
|
* @param {string} token The token string generated by `jwt.sign()`.
|
||||||
* @returns {JwtData} Returns an `object` containing `header` and `payload`.
|
* @returns {JwtData} Returns an `object` containing `header` and `payload`.
|
||||||
*/
|
*/
|
||||||
export function decode(token: string): JwtData {
|
export function decode<Payload = {}, Header = {}>(token: string): JwtData<Payload, Header> {
|
||||||
return {
|
return {
|
||||||
header: _decodePayload(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')) as JwtHeader,
|
header: decodePayload<JwtHeader<Header>>(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')),
|
||||||
payload: _decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')) as JwtPayload
|
payload: decodePayload<JwtPayload<Payload>>(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
93
src/utils.ts
Normal file
93
src/utils.ts
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
export function bytesToByteString(bytes: Uint8Array): string {
|
||||||
|
let byteStr = ''
|
||||||
|
for (let i = 0; i < bytes.byteLength; i++) {
|
||||||
|
byteStr += String.fromCharCode(bytes[i])
|
||||||
|
}
|
||||||
|
return byteStr
|
||||||
|
}
|
||||||
|
|
||||||
|
export function byteStringToBytes(byteStr: string): Uint8Array {
|
||||||
|
let bytes = new Uint8Array(byteStr.length)
|
||||||
|
for (let i = 0; i < byteStr.length; i++) {
|
||||||
|
bytes[i] = byteStr.charCodeAt(i)
|
||||||
|
}
|
||||||
|
return bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
export function arrayBufferToBase64String(arrayBuffer: ArrayBuffer): string {
|
||||||
|
return btoa(bytesToByteString(new Uint8Array(arrayBuffer)))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function base64StringToArrayBuffer(b64str: string): ArrayBuffer {
|
||||||
|
return byteStringToBytes(atob(b64str)).buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
export function textToArrayBuffer(str: string): ArrayBuffer {
|
||||||
|
return byteStringToBytes(decodeURI(encodeURIComponent(str)))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function arrayBufferToText(arrayBuffer: ArrayBuffer): string {
|
||||||
|
return bytesToByteString(new Uint8Array(arrayBuffer))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function arrayBufferToBase64Url(arrayBuffer: ArrayBuffer): string {
|
||||||
|
return arrayBufferToBase64String(arrayBuffer).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function base64UrlToArrayBuffer(b64url: string): ArrayBuffer {
|
||||||
|
return base64StringToArrayBuffer(b64url.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function textToBase64Url(str: string): string {
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const charCodes = encoder.encode(str);
|
||||||
|
const binaryStr = String.fromCharCode(...charCodes);
|
||||||
|
return btoa(binaryStr).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pemToBinary(pem: string): ArrayBuffer {
|
||||||
|
return base64StringToArrayBuffer(pem.replace(/-+(BEGIN|END).*/g, '').replace(/\s/g, ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importTextSecret(key: string, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
||||||
|
return await crypto.subtle.importKey("raw", textToArrayBuffer(key), algorithm, true, ["verify", "sign"])
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importJwk(key: JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
||||||
|
return await crypto.subtle.importKey("jwk", key, algorithm, true, ["verify", "sign"])
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importPublicKey(key: string, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
||||||
|
return await crypto.subtle.importKey("spki", pemToBinary(key), algorithm, true, ["verify"])
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importPrivateKey(key: string, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
||||||
|
return await crypto.subtle.importKey("pkcs8", pemToBinary(key), algorithm, true, ["sign"])
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importKey(key: string | JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
||||||
|
if (typeof key === 'object')
|
||||||
|
return importJwk(key, algorithm)
|
||||||
|
|
||||||
|
if (typeof key !== 'string')
|
||||||
|
throw new Error('Unsupported key type!')
|
||||||
|
|
||||||
|
if (key.includes('PUBLIC'))
|
||||||
|
return importPublicKey(key, algorithm)
|
||||||
|
|
||||||
|
if (key.includes('PRIVATE'))
|
||||||
|
return importPrivateKey(key, algorithm)
|
||||||
|
|
||||||
|
return importTextSecret(key, algorithm)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodePayload<T = any>(raw: string): T | undefined {
|
||||||
|
try {
|
||||||
|
const bytes = Array.from(atob(raw), char => char.charCodeAt(0));
|
||||||
|
const decodedString = new TextDecoder('utf-8').decode(new Uint8Array(bytes));
|
||||||
|
|
||||||
|
return JSON.parse(decodedString);
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
|
|
||||||
import crypto from 'node:crypto'
|
import crypto from 'node:crypto'
|
||||||
Object.defineProperty(global, 'crypto', { value: { subtle: crypto.webcrypto.subtle }})
|
Object.defineProperty(global, 'crypto', { value: { subtle: crypto.webcrypto.subtle }})
|
||||||
|
|
||||||
import { describe, expect, test } from '@jest/globals'
|
import { describe, expect, test } from '@jest/globals'
|
||||||
import jwt, { JwtAlgorithm } from '.'
|
import jwt, { JwtAlgorithm } from '../src/index'
|
||||||
|
|
||||||
type Dataset = {
|
type Dataset = {
|
||||||
public: string
|
public: string
|
||||||
@@ -15,6 +14,11 @@ type Data = {
|
|||||||
[key in JwtAlgorithm]: Dataset
|
[key in JwtAlgorithm]: Dataset
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Payload = {
|
||||||
|
sub: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
const data: Data = {
|
const data: Data = {
|
||||||
'ES256': {
|
'ES256': {
|
||||||
public: '-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9\nq9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==\n-----END PUBLIC KEY-----',
|
public: '-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9\nq9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==\n-----END PUBLIC KEY-----',
|
||||||
@@ -64,11 +68,16 @@ const data: Data = {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload = {
|
const payload: Payload = {
|
||||||
sub: "1234567890",
|
sub: "1234567890",
|
||||||
name: "John Doe",
|
name: "John Doe",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const unicodePayload: Payload = {
|
||||||
|
sub: "1234567890",
|
||||||
|
name: "John Doe 😎",
|
||||||
|
}
|
||||||
|
|
||||||
describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorithm, data) => {
|
describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorithm, data) => {
|
||||||
let token = ''
|
let token = ''
|
||||||
|
|
||||||
@@ -78,18 +87,23 @@ describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorith
|
|||||||
})
|
})
|
||||||
|
|
||||||
test('decode external', async () => {
|
test('decode external', async () => {
|
||||||
const decoded = jwt.decode(data.token)
|
const decoded = jwt.decode<Payload>(data.token)
|
||||||
expect({
|
expect({
|
||||||
sub: payload.sub,
|
sub: payload.sub,
|
||||||
name: payload.name
|
name: payload.name
|
||||||
}).toMatchObject({
|
}).toMatchObject({
|
||||||
sub: decoded.payload.sub,
|
sub: decoded.payload?.sub,
|
||||||
name: payload.name
|
name: payload.name
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test('sign internal', async () => {
|
test('sign internal', async () => {
|
||||||
token = await jwt.sign(payload, data.private, algorithm)
|
token = await jwt.sign<Payload>(payload, data.private, algorithm)
|
||||||
|
expect(token).toMatch(/^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+$/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('sign unciode', async () => {
|
||||||
|
token = await jwt.sign<Payload>(unicodePayload, data.private, 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\-_]+$/)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -99,7 +113,7 @@ describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorith
|
|||||||
sub: payload.sub,
|
sub: payload.sub,
|
||||||
name: payload.name
|
name: payload.name
|
||||||
}).toMatchObject({
|
}).toMatchObject({
|
||||||
sub: decoded.payload.sub,
|
sub: decoded.payload?.sub,
|
||||||
name: payload.name
|
name: payload.name
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
81
tests/utils.spec.ts
Normal file
81
tests/utils.spec.ts
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
import { describe, expect, test } from '@jest/globals'
|
||||||
|
import {
|
||||||
|
bytesToByteString,
|
||||||
|
byteStringToBytes,
|
||||||
|
arrayBufferToBase64String,
|
||||||
|
base64StringToArrayBuffer,
|
||||||
|
textToArrayBuffer,
|
||||||
|
arrayBufferToText,
|
||||||
|
arrayBufferToBase64Url,
|
||||||
|
base64UrlToArrayBuffer,
|
||||||
|
textToBase64Url,
|
||||||
|
pemToBinary,
|
||||||
|
importTextSecret
|
||||||
|
} from '../src/utils'
|
||||||
|
|
||||||
|
describe('Converters', () => {
|
||||||
|
const testString = 'cloudflare-worker-jwt'
|
||||||
|
const testByteArray = [ 99, 108, 111, 117, 100, 102, 108, 97, 114, 101, 45, 119, 111, 114, 107, 101, 114, 45, 106, 119, 116 ]
|
||||||
|
const testUint8Array = new Uint8Array(testByteArray)
|
||||||
|
const testBase64String = 'Y2xvdWRmbGFyZS13b3JrZXItand0'
|
||||||
|
const testArrayBuffer = testUint8Array.buffer
|
||||||
|
|
||||||
|
test('bytesToByteString', () => {
|
||||||
|
expect(bytesToByteString(testUint8Array)).toStrictEqual(testString)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('byteStringToBytes', () => {
|
||||||
|
expect(byteStringToBytes(testString)).toStrictEqual(testUint8Array)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('arrayBufferToBase64String', () => {
|
||||||
|
expect(arrayBufferToBase64String(testArrayBuffer)).toStrictEqual(testBase64String)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('base64StringToArrayBuffer', () => {
|
||||||
|
expect(base64StringToArrayBuffer(testBase64String)).toStrictEqual(testArrayBuffer)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('textToArrayBuffer', () => {
|
||||||
|
expect(textToArrayBuffer(testString)).toStrictEqual(testUint8Array)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('arrayBufferToText', () => {
|
||||||
|
expect(arrayBufferToText(testArrayBuffer)).toStrictEqual(testString)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('arrayBufferToBase64Url', () => {
|
||||||
|
expect(arrayBufferToBase64Url(testArrayBuffer)).toStrictEqual(testBase64String)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('base64UrlToArrayBuffer', () => {
|
||||||
|
expect(base64UrlToArrayBuffer(testBase64String)).toStrictEqual(testArrayBuffer)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('textToBase64Url', () => {
|
||||||
|
expect(textToBase64Url(testString)).toStrictEqual(testBase64String)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('pemToBinary', () => {
|
||||||
|
expect(pemToBinary(`-----BEGIN PUBLIC KEY-----\n${testBase64String}\n-----END PUBLIC KEY-----`)).toStrictEqual(testArrayBuffer)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Imports', () => {
|
||||||
|
test('importTextSecret', async () => {
|
||||||
|
const testKey = 'cloudflare-worker-jwt'
|
||||||
|
const testAlgorithm = { name: 'HMAC', hash: { name: 'SHA-256' } }
|
||||||
|
const testCryptoKey = { type: 'secret', extractable: true, algorithm: { ...testAlgorithm, length: 168 }, usages: ['verify', 'sign'] }
|
||||||
|
|
||||||
|
expect(await importTextSecret(testKey, testAlgorithm)).toMatchObject(testCryptoKey)
|
||||||
|
})
|
||||||
|
|
||||||
|
//test('importJwk', async () => {})
|
||||||
|
//test('importPublicKey', async () => {})
|
||||||
|
//test('importPrivateKey', async () => {})
|
||||||
|
//test('importKey', async () => {})
|
||||||
|
})
|
||||||
|
|
||||||
|
//describe('Payload', () => {
|
||||||
|
// test('decodePayload', () => {})
|
||||||
|
//})
|
||||||
Reference in New Issue
Block a user