1
0

Compare commits

...

13 Commits

Author SHA1 Message Date
66385f323c 3.1.5 2025-05-11 23:12:57 +02:00
1b6ac02f7c update readme 2025-05-11 23:11:14 +02:00
95e45e67f6 3.1.4 2025-03-14 14:34:33 +01:00
5e6af9cf25 update dependencies and address type errors 2025-03-14 14:31:50 +01:00
d3d7e10b60 3.1.3 2024-10-27 13:45:10 +01:00
fdaa618f65 update pipelines 2024-10-27 13:44:59 +01:00
cce5a61777 update readme 2024-10-27 13:43:25 +01:00
e57ccf7e1c 3.1.2 2024-10-07 19:18:46 +02:00
0d4eb1919b clean up readme 2024-10-07 19:18:26 +02:00
ea136cf1a5 3.1.1 2024-10-03 19:32:59 +02:00
457a989fe3 update readme 2024-10-03 19:32:05 +02:00
9f74c8b56c 3.1.0 2024-10-03 19:25:44 +02:00
c7ce8686d3 add options.header 2024-10-03 19:25:22 +02:00
9 changed files with 495 additions and 790 deletions

View File

@@ -1,8 +1,9 @@
name: Publish name: Publish
run-name: Publish ${{ github.ref_name }}
on: on:
release: release:
types: [published] types: [ published ]
jobs: jobs:
publish: publish:
@@ -13,18 +14,27 @@ 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

31
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,31 @@
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,7 +15,12 @@ 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,18 +24,19 @@ 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 sign({ const token = await jwt.sign({
sub: "1234", sub: "1234",
name: "John Doe", name: "John Doe",
email: "john.doe@gmail.com" email: "john.doe@gmail.com"
}, "secret") }, "secret")
// Verify token // Verify token
const verifiedToken = await verify(token, "secret") const verifiedToken = await jwt.verify(token, "secret")
// Abort if token isn't valid // Abort if token isn't valid
if (!verifiedToken) if (!verifiedToken)
@@ -52,11 +53,12 @@ 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 sign({ const token = await jwt.sign({
sub: "1234", sub: "1234",
name: "John Doe", name: "John Doe",
email: "john.doe@gmail.com", email: "john.doe@gmail.com",
@@ -65,7 +67,7 @@ async () => {
}, "secret") }, "secret")
// Verify token // Verify token
const verifiedToken = await verify(token, "secret") // false const verifiedToken = await jwt.verify(token, "secret")
// Abort if token isn't valid // Abort if token isn't valid
if (!verifiedToken) if (!verifiedToken)
@@ -100,7 +102,7 @@ Argument | Type | Status | Defa
`secret` | `string`, `JsonWebKey`, `CryptoKey` | required | - | A string 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.keyid` | `string` | optional | `undefined` | The `keyid` or `kid` to be set in the header of the resulting JWT. `options.header` | `object` | optional | `undefined` | Extend the header of the resulting JWT.
#### `return` #### `return`
@@ -142,6 +144,7 @@ Returns the decoded token or `undefined`.
typ: "JWT" typ: "JWT"
}, },
payload: { payload: {
sub: "1234",
name: "John Doe", name: "John Doe",
email: "john.doe@gmail.com" email: "john.doe@gmail.com"
} }
@@ -173,6 +176,7 @@ Returns an `object` containing `header` and `payload`:
typ: "JWT" typ: "JWT"
}, },
payload: { payload: {
sub: "1234",
name: "John Doe", name: "John Doe",
email: "john.doe@gmail.com" email: "john.doe@gmail.com"
} }

1157
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.0.0", "version": "3.1.5",
"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.20240925.0", "@cloudflare/workers-types": "^4.20250313.0",
"@edge-runtime/vm": "^4.0.3", "@edge-runtime/vm": "^5.0.0",
"esbuild": "^0.24.0", "esbuild": "^0.25.1",
"typescript": "^5.6.2", "typescript": "^5.8.2",
"vitest": "^2.1.1" "vitest": "^3.0.8"
} }
} }

View File

@@ -1,7 +1,7 @@
import { import {
textToArrayBuffer, textToUint8Array,
arrayBufferToBase64Url, arrayBufferToBase64Url,
base64UrlToArrayBuffer, base64UrlToUint8Array,
textToBase64Url, textToBase64Url,
importKey, importKey,
decodePayload decodePayload
@@ -147,7 +147,7 @@ export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payloa
if (typeof options === "string") if (typeof options === "string")
options = { algorithm: options } options = { algorithm: options }
options = { algorithm: "HS256", header: { typ: "JWT" } as JwtHeader<Header>, ...options } options = { algorithm: "HS256", header: { typ: "JWT", ...(options.header ?? {}) } as JwtHeader<Header>, ...options }
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")
@@ -169,7 +169,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 partialToken = `${textToBase64Url(JSON.stringify({ ...options.header, alg: options.algorithm }))}.${textToBase64Url(JSON.stringify(payload))}`
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["sign"]) const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["sign"])
const signature = await crypto.subtle.sign(algorithm, key, textToArrayBuffer(partialToken)) const signature = await crypto.subtle.sign(algorithm, key, textToUint8Array(partialToken))
return `${partialToken}.${arrayBufferToBase64Url(signature)}` return `${partialToken}.${arrayBufferToBase64Url(signature)}`
} }
@@ -225,7 +225,7 @@ export async function verify<Payload = {}, Header = {}>(token: string, secret: s
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["verify"]) 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(tokenParts[2]), textToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`)))
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 base64StringToArrayBuffer(b64str: string): ArrayBuffer { export function base64StringToUint8Array(b64str: string): Uint8Array {
return byteStringToBytes(atob(b64str)).buffer return byteStringToBytes(atob(b64str))
} }
export function textToArrayBuffer(str: string): ArrayBuffer { export function textToUint8Array(str: string): Uint8Array {
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 base64UrlToArrayBuffer(b64url: string): ArrayBuffer { export function base64UrlToUint8Array(b64url: string): Uint8Array {
return base64StringToArrayBuffer(b64url.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "")) return base64StringToUint8Array(b64url.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""))
} }
export function textToBase64Url(str: string): string { export function textToBase64Url(str: string): string {
@@ -48,12 +48,12 @@ 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): ArrayBuffer { export function pemToBinary(pem: string): Uint8Array {
return base64StringToArrayBuffer(pem.replace(/-+(BEGIN|END).*/g, "").replace(/\s/g, "")) return base64StringToUint8Array(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", textToArrayBuffer(key), algorithm, true, keyUsages) return await crypto.subtle.importKey("raw", textToUint8Array(key), algorithm, true, keyUsages)
} }
export async function importJwk(key: JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> { export async function importJwk(key: JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {

View File

@@ -3,11 +3,11 @@ import {
bytesToByteString, bytesToByteString,
byteStringToBytes, byteStringToBytes,
arrayBufferToBase64String, arrayBufferToBase64String,
base64StringToArrayBuffer, base64StringToUint8Array,
textToArrayBuffer, textToUint8Array,
arrayBufferToText, arrayBufferToText,
arrayBufferToBase64Url, arrayBufferToBase64Url,
base64UrlToArrayBuffer, base64UrlToUint8Array,
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.buffer const testArrayBuffer = testUint8Array
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(base64StringToArrayBuffer(testBase64String)).toStrictEqual(testArrayBuffer) expect(base64StringToUint8Array(testBase64String)).toStrictEqual(testArrayBuffer)
}) })
test("textToArrayBuffer", () => { test("textToArrayBuffer", () => {
expect(textToArrayBuffer(testString)).toStrictEqual(testUint8Array) expect(textToUint8Array(testString)).toStrictEqual(testUint8Array)
}) })
test("arrayBufferToText", () => { test("arrayBufferToText", () => {
@@ -49,7 +49,7 @@ describe("Converters", () => {
}) })
test("base64UrlToArrayBuffer", () => { test("base64UrlToArrayBuffer", () => {
expect(base64UrlToArrayBuffer(testBase64String)).toStrictEqual(testArrayBuffer) expect(base64UrlToUint8Array(testBase64String)).toStrictEqual(testArrayBuffer)
}) })
test("textToBase64Url", () => { test("textToBase64Url", () => {