Compare commits
35 Commits
v2.2.10
...
e6baf7ab75
| Author | SHA1 | Date | |
|---|---|---|---|
|
e6baf7ab75
|
|||
|
cf24b34f63
|
|||
|
91f30929da
|
|||
|
93082884fa
|
|||
|
a9e83968b9
|
|||
|
4c480d5ac7
|
|||
|
adf522c3ab
|
|||
|
7c82dff259
|
|||
|
4ceac0270f
|
|||
|
32e00ac6b9
|
|||
|
|
247da9b396 | ||
|
db0e5b51e0
|
|||
|
6594895273
|
|||
|
61a3a2ed50
|
|||
|
d7a6847206
|
|||
|
5ab19c4dc0
|
|||
|
0308d20c38
|
|||
|
703c0c4131
|
|||
|
6b3e828126
|
|||
|
35dc875f56
|
|||
|
|
11afa8eb87 | ||
|
|
b05345279d
|
||
|
|
55bc15bec4 | ||
|
|
b0d4084a0f | ||
|
|
3fd594bbb5 | ||
|
|
f8a216574a | ||
|
|
1f511549f5 | ||
|
|
4be64469d3 | ||
|
72e64f1316
|
|||
|
e235d835aa
|
|||
|
03c66f4223
|
|||
|
70488a6a48
|
|||
|
760245d1c7
|
|||
|
d40d924176
|
|||
|
c2e4fccf56
|
21
.github/workflows/test.yml
vendored
Normal file
21
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
name: Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
run:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: latest
|
||||
registry-url: https://registry.npmjs.org/
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -146,3 +146,5 @@ dist
|
||||
# Custom
|
||||
/index.js
|
||||
/index.d.ts
|
||||
/utils.js
|
||||
/utils.d.ts
|
||||
14
.npmignore
14
.npmignore
@@ -1,7 +1,11 @@
|
||||
.github/
|
||||
src/
|
||||
.editorconfig
|
||||
index.spec.js
|
||||
index.test.js
|
||||
jest.config.ts
|
||||
.github/
|
||||
.gitignore
|
||||
.nvmrc
|
||||
coverage/
|
||||
vite.config.ts
|
||||
src/
|
||||
tests/
|
||||
tsconfig.json
|
||||
utils.*
|
||||
*.tgz
|
||||
@@ -1,9 +0,0 @@
|
||||
import type { Config } from 'jest'
|
||||
|
||||
const config: Config = {
|
||||
preset: 'ts-jest',
|
||||
testEnvironment: 'node',
|
||||
verbose: true
|
||||
}
|
||||
|
||||
export default config
|
||||
4350
package-lock.json
generated
4350
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
20
package.json
20
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.2.10",
|
||||
"version": "2.4.6",
|
||||
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
||||
"type": "module",
|
||||
"exports": "./index.js",
|
||||
@@ -9,8 +9,8 @@
|
||||
"node": ">=18"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test": "jest"
|
||||
"build": "tsc & esbuild --bundle --target=esnext --platform=neutral --outfile=index.js src/index.ts & wait",
|
||||
"test": "vitest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -30,13 +30,11 @@
|
||||
},
|
||||
"homepage": "https://github.com/tsndr/cloudflare-worker-jwt#readme",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^4.20231025.0",
|
||||
"@jest/globals": "^29.7.0",
|
||||
"@types/jest": "^29.5.8",
|
||||
"@types/node": "^20.9.0",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.1.1",
|
||||
"ts-node": "^10.9.1",
|
||||
"typescript": "^5.2.2"
|
||||
"@cloudflare/workers-types": "^4.20240208.0",
|
||||
"@edge-runtime/vm": "^3.2.0",
|
||||
"@types/node": "^20.11.19",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.3.3",
|
||||
"vitest": "^1.3.1"
|
||||
}
|
||||
}
|
||||
|
||||
286
src/index.ts
286
src/index.ts
@@ -1,16 +1,25 @@
|
||||
import {
|
||||
textToArrayBuffer,
|
||||
arrayBufferToBase64Url,
|
||||
base64UrlToArrayBuffer,
|
||||
textToBase64Url,
|
||||
importKey,
|
||||
decodePayload
|
||||
} from "./utils"
|
||||
|
||||
if (typeof crypto === 'undefined' || !crypto.subtle)
|
||||
throw new Error('SubtleCrypto not supported!')
|
||||
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
export interface JwtAlgorithms {
|
||||
export type JwtAlgorithms = {
|
||||
[key: string]: SubtleCryptoImportKeyAlgorithm
|
||||
}
|
||||
|
||||
@@ -18,7 +27,7 @@ export interface JwtAlgorithms {
|
||||
* @typedef JwtHeader
|
||||
* @prop {string} [typ] Type
|
||||
*/
|
||||
export interface JwtHeader {
|
||||
export type JwtHeader<T = {}> = {
|
||||
/**
|
||||
* Type (default: `"JWT"`)
|
||||
*
|
||||
@@ -26,8 +35,13 @@ export interface JwtHeader {
|
||||
*/
|
||||
typ?: string
|
||||
|
||||
[key: string]: any
|
||||
}
|
||||
/**
|
||||
* Algorithm (default: `"HS256"`)
|
||||
*
|
||||
* @default "HS256"
|
||||
*/
|
||||
alg?: JwtAlgorithm
|
||||
} & T
|
||||
|
||||
/**
|
||||
* @typedef JwtPayload
|
||||
@@ -39,7 +53,7 @@ export interface JwtHeader {
|
||||
* @prop {string} [iat] Issued At
|
||||
* @prop {string} [jti] JWT ID
|
||||
*/
|
||||
export interface JwtPayload {
|
||||
export type JwtPayload<T = { [key: string]: any }> = {
|
||||
/** Issuer */
|
||||
iss?: string
|
||||
|
||||
@@ -60,15 +74,13 @@ export interface JwtPayload {
|
||||
|
||||
/** JWT ID */
|
||||
jti?: string
|
||||
|
||||
[key: string]: any
|
||||
}
|
||||
} & T
|
||||
|
||||
/**
|
||||
* @typedef JwtOptions
|
||||
* @prop {JwtAlgorithm | string} algorithm
|
||||
*/
|
||||
export interface JwtOptions {
|
||||
export type JwtOptions = {
|
||||
algorithm?: JwtAlgorithm | string
|
||||
}
|
||||
|
||||
@@ -77,37 +89,32 @@ export interface JwtOptions {
|
||||
* @extends JwtOptions
|
||||
* @prop {JwtHeader} [header]
|
||||
*/
|
||||
export interface JwtSignOptions extends JwtOptions {
|
||||
header?: JwtHeader
|
||||
}
|
||||
export type JwtSignOptions<T> = {
|
||||
header?: JwtHeader<T>
|
||||
} & JwtOptions
|
||||
|
||||
/**
|
||||
* @typedef JwtVerifyOptions
|
||||
* @extends JwtOptions
|
||||
* @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
|
||||
*/
|
||||
export interface JwtVerifyOptions extends JwtOptions {
|
||||
/**
|
||||
* If `true` all expiry checks will be skipped
|
||||
*/
|
||||
skipValidation?: boolean
|
||||
|
||||
export type JwtVerifyOptions = {
|
||||
/**
|
||||
* If `true` throw error if checks fail. (default: `false`)
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
throwError?: boolean
|
||||
}
|
||||
} & JwtOptions
|
||||
|
||||
/**
|
||||
* @typedef JwtData
|
||||
* @prop {JwtHeader} header
|
||||
* @prop {JwtPayload} payload
|
||||
*/
|
||||
export interface JwtData {
|
||||
header: JwtHeader
|
||||
payload: JwtPayload
|
||||
export type JwtData<Payload = {}, Header = {}> = {
|
||||
header?: JwtHeader<Header>
|
||||
payload?: JwtPayload<Payload>
|
||||
}
|
||||
|
||||
const algorithms: JwtAlgorithms = {
|
||||
@@ -122,177 +129,26 @@ const algorithms: JwtAlgorithms = {
|
||||
RS512: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512' } }
|
||||
}
|
||||
|
||||
function bytesToByteString(bytes: Uint8Array): string {
|
||||
let byteStr = ''
|
||||
for (let i = 0; i < bytes.byteLength; i++) {
|
||||
byteStr += String.fromCharCode(bytes[i])
|
||||
}
|
||||
return byteStr
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
function arrayBufferToBase64String(arrayBuffer: ArrayBuffer): string {
|
||||
return btoa(bytesToByteString(new Uint8Array(arrayBuffer)))
|
||||
}
|
||||
|
||||
function base64StringToArrayBuffer(b64str: string): ArrayBuffer {
|
||||
return byteStringToBytes(atob(b64str)).buffer
|
||||
}
|
||||
|
||||
function textToArrayBuffer(str: string): ArrayBuffer {
|
||||
return byteStringToBytes(decodeURI(encodeURIComponent(str)))
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
function arrayBufferToText(arrayBuffer: ArrayBuffer): string {
|
||||
return bytesToByteString(new Uint8Array(arrayBuffer))
|
||||
}
|
||||
|
||||
function arrayBufferToBase64Url(arrayBuffer: ArrayBuffer): string {
|
||||
return arrayBufferToBase64String(arrayBuffer).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
||||
}
|
||||
|
||||
function base64UrlToArrayBuffer(b64url: string): ArrayBuffer {
|
||||
return base64StringToArrayBuffer(b64url.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''))
|
||||
}
|
||||
|
||||
function textToBase64Url(str: string): string {
|
||||
return btoa(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
||||
}
|
||||
|
||||
function pemToBinary(pem: string): ArrayBuffer {
|
||||
return base64StringToArrayBuffer(pem.replace(/-+(BEGIN|END).*/g, '').replace(/\s/g, ''))
|
||||
}
|
||||
|
||||
async function importTextSecret(key: string, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("raw", textToArrayBuffer(key), algorithm, true, ["verify", "sign"])
|
||||
}
|
||||
|
||||
async function importJwk(key: JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("jwk", key, algorithm, true, ["verify", "sign"])
|
||||
}
|
||||
|
||||
async function importPublicKey(key: string, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("spki", pemToBinary(key), algorithm, true, ["verify"])
|
||||
}
|
||||
|
||||
async function importPrivateKey(key: string, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("pkcs8", pemToBinary(key), algorithm, true, ["sign"])
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
function decodePayload(raw: string): JwtHeader | JwtPayload | null {
|
||||
try {
|
||||
raw += '='.repeat(4-(raw.length % 4))
|
||||
return JSON.parse(atob(raw))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies the integrity of the token and returns a boolean value.
|
||||
*
|
||||
* @param {string} token The token string generated by `jwt.sign()`.
|
||||
* @param {string | JsonWebKey} secret The string which was used to sign the payload.
|
||||
* @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.
|
||||
* @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> {
|
||||
if (typeof options === 'string')
|
||||
options = { algorithm: options, throwError: false }
|
||||
|
||||
options = { algorithm: 'HS256', skipValidation: false, throwError: false, ...options }
|
||||
|
||||
if (typeof token !== 'string')
|
||||
throw new Error('token 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')
|
||||
throw new Error('options.algorithm must be a string')
|
||||
|
||||
const tokenParts = token.split('.')
|
||||
|
||||
if (tokenParts.length !== 3)
|
||||
throw new Error('token must consist of 3 parts')
|
||||
|
||||
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
||||
|
||||
if (!algorithm)
|
||||
throw new Error('algorithm not found')
|
||||
|
||||
const { payload } = decode(token)
|
||||
|
||||
if (!options.skipValidation && !payload) {
|
||||
if (options.throwError)
|
||||
throw 'PARSE_ERROR'
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
const key = await importKey(secret, algorithm)
|
||||
|
||||
return await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`))
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {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.
|
||||
* @throws {Error} If there's a validation issue.
|
||||
* @returns {Promise<string>} Returns token as a `string`.
|
||||
*/
|
||||
export async function sign(payload: JwtPayload, secret: string | JsonWebKey, options: JwtSignOptions | JwtAlgorithm = 'HS256'): 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')
|
||||
options = { algorithm: options }
|
||||
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
|
||||
|
||||
options = { algorithm: 'HS256', header: { typ: 'JWT' } as JwtHeader<Header>, ...options }
|
||||
|
||||
if (!payload || typeof payload !== 'object')
|
||||
throw new Error('payload must be an 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')
|
||||
throw new Error('options.algorithm must be a string')
|
||||
@@ -307,22 +163,84 @@ export async function sign(payload: JwtPayload, secret: string | JsonWebKey, opt
|
||||
|
||||
const partialToken = `${textToBase64Url(JSON.stringify({ ...options.header, alg: options.algorithm }))}.${textToBase64Url(JSON.stringify(payload))}`
|
||||
|
||||
const key = await importKey(secret, algorithm)
|
||||
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ['sign'])
|
||||
const signature = await crypto.subtle.sign(algorithm, key, textToArrayBuffer(partialToken))
|
||||
|
||||
return `${partialToken}.${arrayBufferToBase64Url(signature)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies the integrity of the token and returns a boolean value.
|
||||
*
|
||||
* @param {string} token The token string generated by `jwt.sign()`.
|
||||
* @param {string | JsonWebKey | CryptoKey} secret The string which was used to sign the payload.
|
||||
* @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.
|
||||
* @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 | CryptoKey, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', throwError: false }): Promise<boolean> {
|
||||
if (typeof options === 'string')
|
||||
options = { algorithm: options, throwError: false }
|
||||
|
||||
options = { algorithm: 'HS256', throwError: false, ...options }
|
||||
|
||||
if (typeof token !== 'string')
|
||||
throw new Error('token must be a string')
|
||||
|
||||
if (typeof secret !== 'string' && typeof secret !== 'object')
|
||||
throw new Error('secret must be a string, a JWK object or a CryptoKey object')
|
||||
|
||||
if (typeof options.algorithm !== 'string')
|
||||
throw new Error('options.algorithm must be a string')
|
||||
|
||||
const tokenParts = token.split('.')
|
||||
|
||||
if (tokenParts.length !== 3)
|
||||
throw new Error('token must consist of 3 parts')
|
||||
|
||||
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
||||
|
||||
if (!algorithm)
|
||||
throw new Error('algorithm not found')
|
||||
|
||||
const { header, payload } = decode(token)
|
||||
|
||||
if (header?.alg !== options.algorithm) {
|
||||
if (options.throwError)
|
||||
throw new Error('ALG_MISMATCH')
|
||||
return false
|
||||
}
|
||||
|
||||
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, ['verify'])
|
||||
|
||||
return await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`))
|
||||
} catch(err) {
|
||||
if (options.throwError)
|
||||
throw err
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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()`.
|
||||
* @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 {
|
||||
header: decodePayload(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')) as JwtHeader,
|
||||
payload: decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')) as JwtPayload
|
||||
header: decodePayload<JwtHeader<Header>>(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')),
|
||||
payload: decodePayload<JwtPayload<Payload>>(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
3
src/test.ts
Normal file
3
src/test.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { sign } from './index'
|
||||
|
||||
console.log(await sign())
|
||||
94
src/utils.ts
Normal file
94
src/utils.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
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, ''))
|
||||
}
|
||||
|
||||
type KeyUsages = 'sign' | 'verify';
|
||||
export async function importTextSecret(key: string, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("raw", textToArrayBuffer(key), algorithm, true, keyUsages)
|
||||
}
|
||||
|
||||
export async function importJwk(key: JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("jwk", key, algorithm, true, keyUsages)
|
||||
}
|
||||
|
||||
export async function importPublicKey(key: string, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("spki", pemToBinary(key), algorithm, true, keyUsages)
|
||||
}
|
||||
|
||||
export async function importPrivateKey(key: string, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("pkcs8", pemToBinary(key), algorithm, true, keyUsages)
|
||||
}
|
||||
|
||||
export async function importKey(key: string | JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
if (typeof key === 'object')
|
||||
return importJwk(key, algorithm, keyUsages)
|
||||
|
||||
if (typeof key !== 'string')
|
||||
throw new Error('Unsupported key type!')
|
||||
|
||||
if (key.includes('PUBLIC'))
|
||||
return importPublicKey(key, algorithm, keyUsages)
|
||||
|
||||
if (key.includes('PRIVATE'))
|
||||
return importPrivateKey(key, algorithm, keyUsages)
|
||||
|
||||
return importTextSecret(key, algorithm, keyUsages)
|
||||
}
|
||||
|
||||
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,8 +1,5 @@
|
||||
import crypto from 'node:crypto'
|
||||
Object.defineProperty(global, 'crypto', { value: { subtle: crypto.webcrypto.subtle }})
|
||||
|
||||
import { describe, expect, test } from '@jest/globals'
|
||||
import jwt, { JwtAlgorithm } from '.'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import jwt, { JwtAlgorithm } from '../src/index'
|
||||
|
||||
type Dataset = {
|
||||
public: string
|
||||
@@ -14,6 +11,11 @@ type Data = {
|
||||
[key in JwtAlgorithm]: Dataset
|
||||
}
|
||||
|
||||
type Payload = {
|
||||
sub: string
|
||||
name: string
|
||||
}
|
||||
|
||||
const data: Data = {
|
||||
'ES256': {
|
||||
public: '-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9\nq9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==\n-----END PUBLIC KEY-----',
|
||||
@@ -63,11 +65,16 @@ const data: Data = {
|
||||
|
||||
}
|
||||
|
||||
const payload = {
|
||||
const payload: Payload = {
|
||||
sub: "1234567890",
|
||||
name: "John Doe",
|
||||
}
|
||||
|
||||
const unicodePayload: Payload = {
|
||||
sub: "1234567890",
|
||||
name: "John Doe 😎",
|
||||
}
|
||||
|
||||
describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorithm, data) => {
|
||||
let token = ''
|
||||
|
||||
@@ -77,18 +84,23 @@ describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorith
|
||||
})
|
||||
|
||||
test('decode external', async () => {
|
||||
const decoded = jwt.decode(data.token)
|
||||
const decoded = jwt.decode<Payload>(data.token)
|
||||
expect({
|
||||
sub: payload.sub,
|
||||
name: payload.name
|
||||
}).toMatchObject({
|
||||
sub: decoded.payload.sub,
|
||||
sub: decoded.payload?.sub,
|
||||
name: payload.name
|
||||
})
|
||||
})
|
||||
|
||||
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\-_]+$/)
|
||||
})
|
||||
|
||||
@@ -98,7 +110,7 @@ describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorith
|
||||
sub: payload.sub,
|
||||
name: payload.name
|
||||
}).toMatchObject({
|
||||
sub: decoded.payload.sub,
|
||||
sub: decoded.payload?.sub,
|
||||
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 'vitest'
|
||||
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, ['verify', 'sign'])).toMatchObject(testCryptoKey)
|
||||
})
|
||||
|
||||
//test('importJwk', async () => {})
|
||||
//test('importPublicKey', async () => {})
|
||||
//test('importPrivateKey', async () => {})
|
||||
//test('importKey', async () => {})
|
||||
})
|
||||
|
||||
//describe('Payload', () => {
|
||||
// test('decodePayload', () => {})
|
||||
//})
|
||||
@@ -5,6 +5,7 @@
|
||||
"target": "esnext",
|
||||
"lib": ["esnext"],
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"strict": true,
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true,
|
||||
|
||||
9
vite.config.ts
Normal file
9
vite.config.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: 'edge-runtime',
|
||||
watch: false,
|
||||
reporters: ['verbose']
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user