Compare commits
14 Commits
v2.4.1
...
e6baf7ab75
| Author | SHA1 | Date | |
|---|---|---|---|
|
e6baf7ab75
|
|||
|
cf24b34f63
|
|||
|
91f30929da
|
|||
|
93082884fa
|
|||
|
a9e83968b9
|
|||
|
4c480d5ac7
|
|||
|
adf522c3ab
|
|||
|
7c82dff259
|
|||
|
4ceac0270f
|
|||
|
32e00ac6b9
|
|||
|
|
247da9b396 | ||
|
db0e5b51e0
|
|||
|
6594895273
|
|||
|
61a3a2ed50
|
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
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -145,4 +145,6 @@ dist
|
||||
|
||||
# Custom
|
||||
/index.js
|
||||
/index.d.ts
|
||||
/index.d.ts
|
||||
/utils.js
|
||||
/utils.d.ts
|
||||
@@ -3,7 +3,9 @@
|
||||
.gitignore
|
||||
.nvmrc
|
||||
coverage/
|
||||
jest.config.ts
|
||||
vite.config.ts
|
||||
src/
|
||||
tests/
|
||||
tsconfig.json
|
||||
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
|
||||
4354
package-lock.json
generated
4354
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.4.1",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
||||
36
src/index.ts
36
src/index.ts
@@ -1,10 +1,10 @@
|
||||
import {
|
||||
textToArrayBuffer,
|
||||
arrayBufferToBase64Url,
|
||||
base64UrlToArrayBuffer,
|
||||
textToBase64Url,
|
||||
importKey,
|
||||
decodePayload
|
||||
textToArrayBuffer,
|
||||
arrayBufferToBase64Url,
|
||||
base64UrlToArrayBuffer,
|
||||
textToBase64Url,
|
||||
importKey,
|
||||
decodePayload
|
||||
} from "./utils"
|
||||
|
||||
if (typeof crypto === 'undefined' || !crypto.subtle)
|
||||
@@ -34,6 +34,13 @@ export type JwtHeader<T = {}> = {
|
||||
* @default "JWT"
|
||||
*/
|
||||
typ?: string
|
||||
|
||||
/**
|
||||
* Algorithm (default: `"HS256"`)
|
||||
*
|
||||
* @default "HS256"
|
||||
*/
|
||||
alg?: JwtAlgorithm
|
||||
} & T
|
||||
|
||||
/**
|
||||
@@ -46,7 +53,7 @@ export type JwtHeader<T = {}> = {
|
||||
* @prop {string} [iat] Issued At
|
||||
* @prop {string} [jti] JWT ID
|
||||
*/
|
||||
export type JwtPayload<T = {}> = {
|
||||
export type JwtPayload<T = { [key: string]: any }> = {
|
||||
/** Issuer */
|
||||
iss?: string
|
||||
|
||||
@@ -67,8 +74,6 @@ export type JwtPayload<T = {}> = {
|
||||
|
||||
/** JWT ID */
|
||||
jti?: string
|
||||
|
||||
[key: string]: any
|
||||
} & T
|
||||
|
||||
/**
|
||||
@@ -158,7 +163,7 @@ export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payloa
|
||||
|
||||
const partialToken = `${textToBase64Url(JSON.stringify({ ...options.header, alg: options.algorithm }))}.${textToBase64Url(JSON.stringify(payload))}`
|
||||
|
||||
const key = secret instanceof CryptoKey ? secret : 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)}`
|
||||
@@ -198,7 +203,13 @@ export async function verify(token: string, secret: string | JsonWebKey | Crypto
|
||||
if (!algorithm)
|
||||
throw new Error('algorithm not found')
|
||||
|
||||
const { payload } = decode(token)
|
||||
const { header, payload } = decode(token)
|
||||
|
||||
if (header?.alg !== options.algorithm) {
|
||||
if (options.throwError)
|
||||
throw new Error('ALG_MISMATCH')
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
if (!payload)
|
||||
@@ -210,13 +221,12 @@ export async function verify(token: string, secret: string | JsonWebKey | Crypto
|
||||
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000))
|
||||
throw new Error('EXPIRED')
|
||||
|
||||
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
3
src/test.ts
Normal file
3
src/test.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { sign } from './index'
|
||||
|
||||
console.log(await sign())
|
||||
27
src/utils.ts
27
src/utils.ts
@@ -49,36 +49,37 @@ 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"])
|
||||
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): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("jwk", key, algorithm, true, ["verify", "sign"])
|
||||
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): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("spki", pemToBinary(key), algorithm, true, ["verify"])
|
||||
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): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("pkcs8", pemToBinary(key), algorithm, true, ["sign"])
|
||||
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): Promise<CryptoKey> {
|
||||
export async function importKey(key: string | JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
if (typeof key === 'object')
|
||||
return importJwk(key, algorithm)
|
||||
return importJwk(key, algorithm, keyUsages)
|
||||
|
||||
if (typeof key !== 'string')
|
||||
throw new Error('Unsupported key type!')
|
||||
|
||||
if (key.includes('PUBLIC'))
|
||||
return importPublicKey(key, algorithm)
|
||||
return importPublicKey(key, algorithm, keyUsages)
|
||||
|
||||
if (key.includes('PRIVATE'))
|
||||
return importPrivateKey(key, algorithm)
|
||||
return importPrivateKey(key, algorithm, keyUsages)
|
||||
|
||||
return importTextSecret(key, algorithm)
|
||||
return importTextSecret(key, algorithm, keyUsages)
|
||||
}
|
||||
|
||||
export function decodePayload<T = any>(raw: string): T | undefined {
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import crypto from 'node:crypto'
|
||||
Object.defineProperty(global, 'crypto', { value: { subtle: crypto.webcrypto.subtle }})
|
||||
|
||||
import { describe, expect, test } from '@jest/globals'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import jwt, { JwtAlgorithm } from '../src/index'
|
||||
|
||||
type Dataset = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, test } from '@jest/globals'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import {
|
||||
bytesToByteString,
|
||||
byteStringToBytes,
|
||||
@@ -67,7 +67,7 @@ describe('Imports', () => {
|
||||
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)
|
||||
expect(await importTextSecret(testKey, testAlgorithm, ['verify', 'sign'])).toMatchObject(testCryptoKey)
|
||||
})
|
||||
|
||||
//test('importJwk', async () => {})
|
||||
|
||||
@@ -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