1
0

Compare commits

..

2 Commits

Author SHA1 Message Date
e96b507d6e 3.1.3 2024-10-27 13:38:35 +01:00
39e022d1b8 update readem 2024-10-27 13:38:23 +01:00
11 changed files with 832 additions and 608 deletions

View File

@@ -1,9 +1,8 @@
name: Publish name: Publish
run-name: Publish ${{ github.ref_name }}
on: on:
release: release:
types: [ published ] types: [published]
jobs: jobs:
publish: publish:
@@ -14,27 +13,18 @@ jobs:
with: with:
node-version: latest node-version: latest
registry-url: https://registry.npmjs.org/ registry-url: https://registry.npmjs.org/
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Run tests
run: npm test
- name: Build - name: Build
run: npm run build run: npm run build
- name: Publish to npmjs - name: Publish to npmjs
run: npm publish --tag latest --access public
env: env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || 'latest' }} --access public
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: latest
registry-url: https://npm.pkg.github.com/ registry-url: https://npm.pkg.github.com/
- name: Publish to GPR - name: Publish to GPR
run: npm publish --tag latest --access public
env: env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || 'latest' }} --access public

View File

@@ -1,31 +0,0 @@
name: Release
run-name: Release ${{ github.ref_name }}
on:
push:
tags:
- 'v*'
jobs:
release:
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
- name: Build
run: npm run build
- name: Create release
run: gh release create ${{ github.ref_name }} --draft ${{ contains(github.ref_name, '-') && '--prerelease --latest=false' || '--latest' }}
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -15,12 +15,7 @@ jobs:
with: with:
node-version: latest node-version: latest
registry-url: https://registry.npmjs.org/ registry-url: https://registry.npmjs.org/
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Run tests - name: Run tests
run: npm test run: npm test
- name: Build
run: npm run build

View File

@@ -24,9 +24,8 @@ npm i @tsndr/cloudflare-worker-jwt
### Basic Example ### Basic Example
```typescript ```typescript
import jwt from "@tsndr/cloudflare-worker-jwt"
async () => { async () => {
import jwt from "@tsndr/cloudflare-worker-jwt"
// Create a token // Create a token
const token = await jwt.sign({ const token = await jwt.sign({
@@ -53,9 +52,8 @@ async () => {
### Restrict Timeframe ### Restrict Timeframe
```typescript ```typescript
import jwt from "@tsndr/cloudflare-worker-jwt"
async () => { async () => {
import jwt from "@tsndr/cloudflare-worker-jwt"
// Create a token // Create a token
const token = await jwt.sign({ const token = await jwt.sign({
@@ -99,7 +97,7 @@ Signs a payload and returns the token.
Argument | Type | Status | 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`, `JsonWebKey`, `CryptoKey` | optional | - | A secret which is used to sign the payload. `secret` | `string`, `JsonWebKey`, `CryptoKey` | required | - | A string which is used to sign the payload.
`options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object. `options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object.
`options.algorithm` | `string` | optional | `HS256` | See [Available Algorithms](#available-algorithms) `options.algorithm` | `string` | optional | `HS256` | See [Available Algorithms](#available-algorithms)
`options.header` | `object` | optional | `undefined` | Extend the header of the resulting JWT. `options.header` | `object` | optional | `undefined` | Extend the header of the resulting JWT.
@@ -121,7 +119,7 @@ Verifies the integrity of the token.
Argument | Type | Status | Default | Description Argument | Type | Status | Default | Description
------------------------ | ----------------------------------- | -------- | ------- | ----------- ------------------------ | ----------------------------------- | -------- | ------- | -----------
`token` | `string` | required | - | The token string generated by `sign()`. `token` | `string` | required | - | The token string generated by `sign()`.
`secret` | `string`, `JsonWebKey`, `CryptoKey` | optional | - | The secret which was used to sign the payload. `secret` | `string`, `JsonWebKey`, `CryptoKey` | required | - | The string which was used to sign the payload.
`options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object. `options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object.
`options.algorithm` | `string` | optional | `HS256` | See [Available Algorithms](#available-algorithms) `options.algorithm` | `string` | optional | `HS256` | See [Available Algorithms](#available-algorithms)
`options.clockTolerance` | `number` | optional | `0` | Clock tolerance in seconds, to help with slighly out of sync systems. `options.clockTolerance` | `number` | optional | `0` | Clock tolerance in seconds, to help with slighly out of sync systems.
@@ -189,4 +187,3 @@ Returns an `object` containing `header` and `payload`:
- `ES256`, `ES384`, `ES512` - `ES256`, `ES384`, `ES512`
- `HS256`, `HS384`, `HS512` - `HS256`, `HS384`, `HS512`
- `RS256`, `RS384`, `RS512` - `RS256`, `RS384`, `RS512`
- `none`

1231
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "3.1.7", "version": "3.1.3",
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker", "description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
"type": "module", "type": "module",
"exports": "./index.js", "exports": "./index.js",
@@ -30,10 +30,10 @@
}, },
"homepage": "https://github.com/tsndr/cloudflare-worker-jwt#readme", "homepage": "https://github.com/tsndr/cloudflare-worker-jwt#readme",
"devDependencies": { "devDependencies": {
"@cloudflare/workers-types": "^4.20250525.0", "@cloudflare/workers-types": "^4.20240925.0",
"@edge-runtime/vm": "^5.0.0", "@edge-runtime/vm": "^4.0.3",
"esbuild": "^0.25.4", "esbuild": "^0.24.0",
"typescript": "^5.8.3", "typescript": "^5.6.2",
"vitest": "^3.1.4" "vitest": "^2.1.1"
} }
} }

View File

@@ -1,7 +1,7 @@
import { import {
textToUint8Array, textToArrayBuffer,
arrayBufferToBase64Url, arrayBufferToBase64Url,
base64UrlToUint8Array, base64UrlToArrayBuffer,
textToBase64Url, textToBase64Url,
importKey, importKey,
decodePayload decodePayload
@@ -12,9 +12,9 @@ if (typeof crypto === "undefined" || !crypto.subtle)
/** /**
* @typedef JwtAlgorithm * @typedef JwtAlgorithm
* @type {"none" | "ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512"} * @type {"ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512"}
*/ */
export type JwtAlgorithm = "none" | "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
@@ -118,12 +118,11 @@ export type JwtVerifyOptions = {
* @prop {JwtPayload} payload * @prop {JwtPayload} payload
*/ */
export type JwtData<Payload = {}, Header = {}> = { export type JwtData<Payload = {}, Header = {}> = {
header: JwtHeader<Header> header?: JwtHeader<Header>
payload: JwtPayload<Payload> payload?: JwtPayload<Payload>
} }
const algorithms: JwtAlgorithms = { const algorithms: JwtAlgorithms = {
none: { name: "none" },
ES256: { name: "ECDSA", namedCurve: "P-256", hash: { name: "SHA-256" } }, ES256: { name: "ECDSA", namedCurve: "P-256", hash: { name: "SHA-256" } },
ES384: { name: "ECDSA", namedCurve: "P-384", hash: { name: "SHA-384" } }, ES384: { name: "ECDSA", namedCurve: "P-384", hash: { name: "SHA-384" } },
ES512: { name: "ECDSA", namedCurve: "P-521", hash: { name: "SHA-512" } }, ES512: { name: "ECDSA", namedCurve: "P-521", hash: { name: "SHA-512" } },
@@ -144,7 +143,7 @@ const algorithms: JwtAlgorithms = {
* @throws If there"s a validation issue. * @throws If there"s a validation issue.
* @returns Returns token as a `string`. * @returns Returns token as a `string`.
*/ */
export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payload>, secret: string | JsonWebKeyWithKid | CryptoKey | undefined, options: JwtSignOptions<Header> | JwtAlgorithm = "HS256"): Promise<string> { export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payload>, secret: string | JsonWebKey | CryptoKey, options: JwtSignOptions<Header> | JwtAlgorithm = "HS256"): Promise<string> {
if (typeof options === "string") if (typeof options === "string")
options = { algorithm: options } options = { algorithm: options }
@@ -153,7 +152,7 @@ export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payloa
if (!payload || 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 (options.algorithm !== "none" && (!secret || (typeof secret !== "string" && typeof secret !== "object"))) if (!secret || (typeof secret !== "string" && typeof secret !== "object"))
throw new Error("secret must be a string, a JWK object or a CryptoKey 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")
@@ -169,11 +168,8 @@ export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payloa
const partialToken = `${textToBase64Url(JSON.stringify({ ...options.header, alg: options.algorithm }))}.${textToBase64Url(JSON.stringify(payload))}` const partialToken = `${textToBase64Url(JSON.stringify({ ...options.header, alg: options.algorithm }))}.${textToBase64Url(JSON.stringify(payload))}`
if (options.algorithm === "none") const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["sign"])
return partialToken const signature = await crypto.subtle.sign(algorithm, key, textToArrayBuffer(partialToken))
const key = secret instanceof CryptoKey ? secret : await importKey(secret!, algorithm, ["sign"])
const signature = await crypto.subtle.sign(algorithm, key, textToUint8Array(partialToken))
return `${partialToken}.${arrayBufferToBase64Url(signature)}` return `${partialToken}.${arrayBufferToBase64Url(signature)}`
} }
@@ -187,7 +183,7 @@ export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payloa
* @throws Throws integration errors and if `options.throwError` is set to `true` also throws `NOT_YET_VALID`, `EXPIRED` or `INVALID_SIGNATURE`. * @throws Throws integration errors and if `options.throwError` is set to `true` also throws `NOT_YET_VALID`, `EXPIRED` or `INVALID_SIGNATURE`.
* @returns Returns the decoded token or `undefined`. * @returns Returns the decoded token or `undefined`.
*/ */
export async function verify<Payload = {}, Header = {}>(token: string, secret: string | JsonWebKeyWithKid | CryptoKey | undefined, options: JwtVerifyOptions | JwtAlgorithm = "HS256"): Promise<JwtData<Payload, Header> | undefined> { export async function verify<Payload = {}, Header = {}>(token: string, secret: string | JsonWebKey | CryptoKey, options: JwtVerifyOptions | JwtAlgorithm = "HS256"): Promise<JwtData<Payload, Header> | undefined> {
if (typeof options === "string") if (typeof options === "string")
options = { algorithm: options } options = { algorithm: options }
options = { algorithm: "HS256", clockTolerance: 0, throwError: false, ...options } options = { algorithm: "HS256", clockTolerance: 0, throwError: false, ...options }
@@ -195,18 +191,16 @@ export async function verify<Payload = {}, Header = {}>(token: string, secret: s
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 (options.algorithm !== "none" && typeof secret !== "string" && typeof secret !== "object") if (typeof secret !== "string" && typeof secret !== "object")
throw new Error("secret must be a string, a JWK object or a CryptoKey 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")
const tokenParts = token.split(".", 3) const tokenParts = token.split(".")
if (tokenParts.length < 2) if (tokenParts.length !== 3)
throw new Error("token must consist of 2 or more parts") throw new Error("token must consist of 3 parts")
const [ tokenHeader, tokenPayload, tokenSignature ] = tokenParts
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm] const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
@@ -229,12 +223,9 @@ export async function verify<Payload = {}, Header = {}>(token: string, secret: s
throw new Error("EXPIRED") throw new Error("EXPIRED")
} }
if (algorithm.name === "none") const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["verify"])
return decodedToken
const key = secret instanceof CryptoKey ? secret : await importKey(secret!, algorithm, ["verify"]) if (!await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`)))
if (!await crypto.subtle.verify(algorithm, key, base64UrlToUint8Array(tokenSignature), textToUint8Array(`${tokenHeader}.${tokenPayload}`)))
throw new Error("INVALID_SIGNATURE") throw new Error("INVALID_SIGNATURE")
return decodedToken return decodedToken

View File

@@ -20,11 +20,11 @@ export function arrayBufferToBase64String(arrayBuffer: ArrayBuffer): string {
return btoa(bytesToByteString(new Uint8Array(arrayBuffer))) return btoa(bytesToByteString(new Uint8Array(arrayBuffer)))
} }
export function base64StringToUint8Array(b64str: string): Uint8Array { export function base64StringToArrayBuffer(b64str: string): ArrayBuffer {
return byteStringToBytes(atob(b64str)) return byteStringToBytes(atob(b64str)).buffer
} }
export function textToUint8Array(str: string): Uint8Array { export function textToArrayBuffer(str: string): ArrayBuffer {
return byteStringToBytes(str) return byteStringToBytes(str)
} }
@@ -36,8 +36,8 @@ export function arrayBufferToBase64Url(arrayBuffer: ArrayBuffer): string {
return arrayBufferToBase64String(arrayBuffer).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") return arrayBufferToBase64String(arrayBuffer).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
} }
export function base64UrlToUint8Array(b64url: string): Uint8Array { export function base64UrlToArrayBuffer(b64url: string): ArrayBuffer {
return base64StringToUint8Array(b64url.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "")) return base64StringToArrayBuffer(b64url.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""))
} }
export function textToBase64Url(str: string): string { export function textToBase64Url(str: string): string {
@@ -48,15 +48,15 @@ export function textToBase64Url(str: string): string {
return btoa(binaryStr).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") return btoa(binaryStr).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
} }
export function pemToBinary(pem: string): Uint8Array { export function pemToBinary(pem: string): ArrayBuffer {
return base64StringToUint8Array(pem.replace(/-+(BEGIN|END).*/g, "").replace(/\s/g, "")) return base64StringToArrayBuffer(pem.replace(/-+(BEGIN|END).*/g, "").replace(/\s/g, ""))
} }
export async function importTextSecret(key: string, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> { export async function importTextSecret(key: string, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
return await crypto.subtle.importKey("raw", textToUint8Array(key), algorithm, true, keyUsages) return await crypto.subtle.importKey("raw", textToArrayBuffer(key), algorithm, true, keyUsages)
} }
export async function importJwk(key: JsonWebKeyWithKid, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> { export async function importJwk(key: JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
return await crypto.subtle.importKey("jwk", key, algorithm, true, keyUsages) return await crypto.subtle.importKey("jwk", key, algorithm, true, keyUsages)
} }
@@ -68,7 +68,7 @@ export async function importPrivateKey(key: string, algorithm: SubtleCryptoImpor
return await crypto.subtle.importKey("pkcs8", pemToBinary(key), algorithm, true, keyUsages) return await crypto.subtle.importKey("pkcs8", pemToBinary(key), algorithm, true, keyUsages)
} }
export async function importKey(key: string | JsonWebKeyWithKid, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> { export async function importKey(key: string | JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
if (typeof key === "object") if (typeof key === "object")
return importJwk(key, algorithm, keyUsages) return importJwk(key, algorithm, keyUsages)
@@ -84,9 +84,13 @@ export async function importKey(key: string | JsonWebKeyWithKid, algorithm: Subt
return importTextSecret(key, algorithm, keyUsages) return importTextSecret(key, algorithm, keyUsages)
} }
export function decodePayload<T = any>(raw: string): T { export function decodePayload<T = any>(raw: string): T | undefined {
const bytes = Array.from(atob(raw), char => char.charCodeAt(0)); try {
const decodedString = new TextDecoder("utf-8").decode(new Uint8Array(bytes)); const bytes = Array.from(atob(raw), char => char.charCodeAt(0));
const decodedString = new TextDecoder("utf-8").decode(new Uint8Array(bytes));
return JSON.parse(decodedString); return JSON.parse(decodedString);
} catch {
return
}
} }

View File

@@ -2,8 +2,8 @@ import { describe, expect, test } from 'vitest'
import jwt, { JwtAlgorithm } from '../src/index' import jwt, { JwtAlgorithm } from '../src/index'
type Dataset = { type Dataset = {
public?: string public: string
private?: string private: string
token: string token: string
} }
@@ -18,9 +18,6 @@ type Payload = {
} }
const data: Data = { const data: Data = {
'none': {
token: 'eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ'
},
'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-----',
private: '-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgevZzL1gdAFr88hb2\nOF/2NxApJCzGCEDdfSp6VQO30hyhRANCAAQRWz+jn65BtOMvdyHKcvjBeBSDZH2r\n1RTwjmYSi9R/zpBnuQ4EiMnCqfMPWiZqB4QdbAd0E7oH50VpuZ1P087G\n-----END PRIVATE KEY-----', private: '-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgevZzL1gdAFr88hb2\nOF/2NxApJCzGCEDdfSp6VQO30hyhRANCAAQRWz+jn65BtOMvdyHKcvjBeBSDZH2r\n1RTwjmYSi9R/zpBnuQ4EiMnCqfMPWiZqB4QdbAd0E7oH50VpuZ1P087G\n-----END PRIVATE KEY-----',
@@ -75,7 +72,7 @@ const payload: Payload = {
emoji: "😎" emoji: "😎"
} }
const jwtRegex = /^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)?$/ const jwtRegex = /^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+$/
describe("Internal", () => { describe("Internal", () => {
test.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', async (algorithm, data) => { test.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', async (algorithm, data) => {

View File

@@ -13,27 +13,27 @@ describe("Verify", async () => {
const notYetValidToken = await jwt.sign({ sub: "me", nbf: now + offset }, secret) const notYetValidToken = await jwt.sign({ sub: "me", nbf: now + offset }, secret)
const expiredToken = await jwt.sign({ sub: "me", exp: now - offset }, secret) const expiredToken = await jwt.sign({ sub: "me", exp: now - offset }, secret)
test("Valid", async () => { test("Valid", () => {
await expect(jwt.verify(validToken, secret, { throwError: true })).resolves.toBeTruthy() expect(jwt.verify(validToken, secret, { throwError: true })).resolves.toBeTruthy()
}) })
test("Not yet expired", async () => { test("Not yet expired", () => {
await expect(jwt.verify(notYetExpired, secret, { throwError: true })).resolves.toBeTruthy() expect(jwt.verify(notYetExpired, secret, { throwError: true })).resolves.toBeTruthy()
}) })
test("Not yet valid", async () => { test("Not yet valid", () => {
await expect(jwt.verify(notYetValidToken, secret, { throwError: true })).rejects.toThrowError("NOT_YET_VALID") expect(jwt.verify(notYetValidToken, secret, { throwError: true })).rejects.toThrowError("NOT_YET_VALID")
}) })
test("Expired", async () => { test("Expired", () => {
await expect(jwt.verify(expiredToken, secret, { throwError: true })).rejects.toThrowError("EXPIRED") expect(jwt.verify(expiredToken, secret, { throwError: true })).rejects.toThrowError("EXPIRED")
}) })
test("Clock offset", async () => { test("Clock offset", () => {
await expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBeTruthy() expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBeTruthy()
await expect(jwt.verify(expiredToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBeTruthy() expect(jwt.verify(expiredToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBeTruthy()
await expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("NOT_YET_VALID") expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("NOT_YET_VALID")
await expect(jwt.verify(expiredToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("EXPIRED") expect(jwt.verify(expiredToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("EXPIRED")
}) })
}) })

View File

@@ -3,11 +3,11 @@ import {
bytesToByteString, bytesToByteString,
byteStringToBytes, byteStringToBytes,
arrayBufferToBase64String, arrayBufferToBase64String,
base64StringToUint8Array, base64StringToArrayBuffer,
textToUint8Array, textToArrayBuffer,
arrayBufferToText, arrayBufferToText,
arrayBufferToBase64Url, arrayBufferToBase64Url,
base64UrlToUint8Array, base64UrlToArrayBuffer,
textToBase64Url, textToBase64Url,
pemToBinary, pemToBinary,
importTextSecret importTextSecret
@@ -18,7 +18,7 @@ describe("Converters", () => {
const testByteArray = [ 99, 108, 111, 117, 100, 102, 108, 97, 114, 101, 45, 119, 111, 114, 107, 101, 114, 45, 106, 119, 116 ] 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 testUint8Array = new Uint8Array(testByteArray)
const testBase64String = "Y2xvdWRmbGFyZS13b3JrZXItand0" const testBase64String = "Y2xvdWRmbGFyZS13b3JrZXItand0"
const testArrayBuffer = testUint8Array const testArrayBuffer = testUint8Array.buffer
test("bytesToByteString", () => { test("bytesToByteString", () => {
expect(bytesToByteString(testUint8Array)).toStrictEqual(testString) expect(bytesToByteString(testUint8Array)).toStrictEqual(testString)
@@ -33,11 +33,11 @@ describe("Converters", () => {
}) })
test("base64StringToArrayBuffer", () => { test("base64StringToArrayBuffer", () => {
expect(base64StringToUint8Array(testBase64String)).toStrictEqual(testArrayBuffer) expect(base64StringToArrayBuffer(testBase64String)).toStrictEqual(testArrayBuffer)
}) })
test("textToArrayBuffer", () => { test("textToArrayBuffer", () => {
expect(textToUint8Array(testString)).toStrictEqual(testUint8Array) expect(textToArrayBuffer(testString)).toStrictEqual(testUint8Array)
}) })
test("arrayBufferToText", () => { test("arrayBufferToText", () => {
@@ -49,7 +49,7 @@ describe("Converters", () => {
}) })
test("base64UrlToArrayBuffer", () => { test("base64UrlToArrayBuffer", () => {
expect(base64UrlToUint8Array(testBase64String)).toStrictEqual(testArrayBuffer) expect(base64UrlToArrayBuffer(testBase64String)).toStrictEqual(testArrayBuffer)
}) })
test("textToBase64Url", () => { test("textToBase64Url", () => {
@@ -67,7 +67,7 @@ describe("Imports", () => {
const testAlgorithm = { name: "HMAC", hash: { name: "SHA-256" } } const testAlgorithm = { name: "HMAC", hash: { name: "SHA-256" } }
const testCryptoKey = { type: "secret", extractable: true, algorithm: { ...testAlgorithm, length: 168 }, usages: ["verify", "sign"] } const testCryptoKey = { type: "secret", extractable: true, algorithm: { ...testAlgorithm, length: 168 }, usages: ["verify", "sign"] }
await expect(importTextSecret(testKey, testAlgorithm, ["verify", "sign"])).resolves.toMatchObject(testCryptoKey) expect(await importTextSecret(testKey, testAlgorithm, ["verify", "sign"])).toMatchObject(testCryptoKey)
}) })
test.todo("importJwk") test.todo("importJwk")