Compare commits
11 Commits
v2.3.1
...
35dc875f56
| Author | SHA1 | Date | |
|---|---|---|---|
|
35dc875f56
|
|||
|
|
11afa8eb87 | ||
|
|
b05345279d
|
||
|
|
55bc15bec4 | ||
|
|
b0d4084a0f | ||
|
|
3fd594bbb5 | ||
|
|
f8a216574a | ||
|
|
1f511549f5 | ||
|
|
4be64469d3 | ||
|
72e64f1316
|
|||
|
e235d835aa
|
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.3.1",
|
||||
"version": "2.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.3.1",
|
||||
"version": "2.4.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^4.20231025.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.3.1",
|
||||
"version": "2.4.0",
|
||||
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
||||
"type": "module",
|
||||
"exports": "./index.js",
|
||||
|
||||
@@ -14,6 +14,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 +68,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,7 +87,7 @@ 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
|
||||
@@ -88,7 +98,12 @@ describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorith
|
||||
})
|
||||
|
||||
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\-_]+$/)
|
||||
})
|
||||
|
||||
|
||||
32
src/index.ts
32
src/index.ts
@@ -75,8 +75,8 @@ export type JwtOptions = {
|
||||
* @extends JwtOptions
|
||||
* @prop {JwtHeader} [header]
|
||||
*/
|
||||
export type JwtSignOptions = {
|
||||
header?: JwtHeader
|
||||
export type JwtSignOptions<T> = {
|
||||
header?: JwtHeader<T>
|
||||
} & JwtOptions
|
||||
|
||||
/**
|
||||
@@ -157,7 +157,10 @@ function base64UrlToArrayBuffer(b64url: string): ArrayBuffer {
|
||||
}
|
||||
|
||||
function textToBase64Url(str: string): string {
|
||||
return btoa(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
||||
const encoder = new TextEncoder();
|
||||
const charCodes = encoder.encode(str);
|
||||
const binaryStr = String.fromCharCode(...charCodes);
|
||||
return btoa(binaryStr).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
||||
}
|
||||
|
||||
function pemToBinary(pem: string): ArrayBuffer {
|
||||
@@ -198,7 +201,10 @@ async function importKey(key: string | JsonWebKey, algorithm: SubtleCryptoImport
|
||||
|
||||
function decodePayload<T = any>(raw: string): T | undefined {
|
||||
try {
|
||||
return JSON.parse(atob(raw))
|
||||
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
|
||||
}
|
||||
@@ -208,22 +214,22 @@ function decodePayload<T = any>(raw: string): T | undefined {
|
||||
* 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')
|
||||
@@ -238,7 +244,7 @@ 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)
|
||||
const signature = await crypto.subtle.sign(algorithm, key, textToArrayBuffer(partialToken))
|
||||
|
||||
return `${partialToken}.${arrayBufferToBase64Url(signature)}`
|
||||
@@ -248,12 +254,12 @@ export async function sign(payload: JwtPayload, secret: string | JsonWebKey, opt
|
||||
* 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 {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, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', 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')
|
||||
options = { algorithm: options, throwError: false }
|
||||
|
||||
@@ -263,7 +269,7 @@ export async function verify(token: string, secret: string | JsonWebKey, options
|
||||
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')
|
||||
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')
|
||||
@@ -290,7 +296,7 @@ export async function verify(token: string, secret: string | JsonWebKey, options
|
||||
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000))
|
||||
throw new Error('EXPIRED')
|
||||
|
||||
const key = await importKey(secret, algorithm)
|
||||
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) {
|
||||
|
||||
Reference in New Issue
Block a user