Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
ec41207832
|
|||
|
e64e89f325
|
|||
|
fb573d928a
|
|||
|
382ad66ea9
|
|||
|
ffc1e87b32
|
|||
|
decfa65391
|
|||
|
|
67f1a8e5ed |
@@ -84,7 +84,7 @@ Signs a payload and returns the token.
|
|||||||
|
|
||||||
#### Arguments
|
#### Arguments
|
||||||
|
|
||||||
Argument | Type | Satus | 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` | required | - | A string which is used to sign the payload.
|
`secret` | `string` | required | - | A string which is used to sign the payload.
|
||||||
@@ -100,7 +100,7 @@ Returns token as a `string`.
|
|||||||
|
|
||||||
Verifies the integrity of the token and returns a boolean value.
|
Verifies the integrity of the token and returns a boolean value.
|
||||||
|
|
||||||
Argument | Type | Satus | Default | Description
|
Argument | Type | Status | Default | Description
|
||||||
----------- | -------- | -------- | ------- | -----------
|
----------- | -------- | -------- | ------- | -----------
|
||||||
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
||||||
`secret` | `string` | required | - | The string which was used to sign the payload.
|
`secret` | `string` | required | - | The string which was used to sign the payload.
|
||||||
@@ -119,7 +119,7 @@ Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherw
|
|||||||
|
|
||||||
Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure!
|
Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure!
|
||||||
|
|
||||||
Argument | Type | Satus | Default | Description
|
Argument | Type | Status | Default | Description
|
||||||
----------- | -------- | -------- | ------- | -----------
|
----------- | -------- | -------- | ------- | -----------
|
||||||
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
||||||
|
|
||||||
|
|||||||
@@ -22,9 +22,10 @@ const secrets = {}
|
|||||||
|
|
||||||
// Keypairs
|
// Keypairs
|
||||||
for (const algorithm of algorithms) {
|
for (const algorithm of algorithms) {
|
||||||
if (algorithm.startsWith('HS'))
|
if (algorithm.startsWith('HS')) {
|
||||||
|
//secrets[algorithm] = 'c2VjcmV0'
|
||||||
secrets[algorithm] = 'secret'
|
secrets[algorithm] = 'secret'
|
||||||
else if (algorithm.startsWith('RS')) {
|
} else if (algorithm.startsWith('RS')) {
|
||||||
secrets[algorithm] = {
|
secrets[algorithm] = {
|
||||||
public: `-----BEGIN PUBLIC KEY-----
|
public: `-----BEGIN PUBLIC KEY-----
|
||||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo
|
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo
|
||||||
@@ -122,6 +123,7 @@ const testPayload = {
|
|||||||
test.each(Object.entries(secrets))(`Self test: %s`, async (algorithm, key) => {
|
test.each(Object.entries(secrets))(`Self test: %s`, async (algorithm, key) => {
|
||||||
let privateKey = key
|
let privateKey = key
|
||||||
let publicKey = key
|
let publicKey = key
|
||||||
|
|
||||||
if (typeof key === 'object') {
|
if (typeof key === 'object') {
|
||||||
privateKey = key.private
|
privateKey = key.private
|
||||||
publicKey = key.public
|
publicKey = key.public
|
||||||
@@ -158,12 +160,11 @@ const externalTokens = {
|
|||||||
|
|
||||||
test.each(Object.entries(externalTokens))('Verify external tokens: %s', async (algorithm, token) => {
|
test.each(Object.entries(externalTokens))('Verify external tokens: %s', async (algorithm, token) => {
|
||||||
const key = secrets[algorithm]
|
const key = secrets[algorithm]
|
||||||
let privateKey = key
|
|
||||||
let publicKey = key
|
let publicKey = key
|
||||||
if (typeof key === 'object') {
|
|
||||||
privateKey = key.private
|
if (typeof key === 'object')
|
||||||
publicKey = key.public
|
publicKey = key.public
|
||||||
}
|
|
||||||
|
|
||||||
const verified = await jwt.verify(token, publicKey, { algorithm })
|
const verified = await jwt.verify(token, publicKey, { algorithm })
|
||||||
expect(verified).toBeTruthy()
|
expect(verified).toBeTruthy()
|
||||||
|
|||||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "2.0.1",
|
"version": "2.1.2",
|
||||||
"lockfileVersion": 2,
|
"lockfileVersion": 2,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "2.0.1",
|
"version": "2.1.2",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@cloudflare/workers-types": "^3.13.0",
|
"@cloudflare/workers-types": "^3.13.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "2.0.1",
|
"version": "2.1.2",
|
||||||
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"types": "index.d.ts",
|
"types": "index.d.ts",
|
||||||
|
|||||||
28
src/index.ts
28
src/index.ts
@@ -135,11 +135,14 @@ function _utf8ToUint8Array(str: string): Uint8Array {
|
|||||||
|
|
||||||
function _str2ab(str: string): ArrayBuffer {
|
function _str2ab(str: string): ArrayBuffer {
|
||||||
str = atob(str)
|
str = atob(str)
|
||||||
|
|
||||||
const buf = new ArrayBuffer(str.length);
|
const buf = new ArrayBuffer(str.length);
|
||||||
const bufView = new Uint8Array(buf);
|
const bufView = new Uint8Array(buf);
|
||||||
|
|
||||||
for (let i = 0, strLen = str.length; i < strLen; i++) {
|
for (let i = 0, strLen = str.length; i < strLen; i++) {
|
||||||
bufView[i] = str.charCodeAt(i);
|
bufView[i] = str.charCodeAt(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
return buf;
|
return buf;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,6 +159,7 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
|
|||||||
default:
|
default:
|
||||||
throw new Error('Illegal base64url string!')
|
throw new Error('Illegal base64url string!')
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return JSON.parse(decodeURIComponent(escape(atob(raw))))
|
return JSON.parse(decodeURIComponent(escape(atob(raw))))
|
||||||
} catch {
|
} catch {
|
||||||
@@ -175,17 +179,25 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
|
|||||||
export async function sign(payload: JwtPayload, secret: string, options: JwtSignOptions | JwtAlgorithm = { algorithm: 'HS256', header: { typ: 'JWT' } }): Promise<string> {
|
export async function sign(payload: JwtPayload, secret: string, options: JwtSignOptions | JwtAlgorithm = { algorithm: 'HS256', header: { typ: 'JWT' } }): Promise<string> {
|
||||||
if (typeof options === 'string')
|
if (typeof options === 'string')
|
||||||
options = { algorithm: options, header: { typ: 'JWT' } }
|
options = { algorithm: options, header: { typ: 'JWT' } }
|
||||||
|
|
||||||
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
|
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
|
||||||
|
|
||||||
if (payload === null || typeof payload !== 'object')
|
if (payload === null || typeof payload !== 'object')
|
||||||
throw new Error('payload must be an object')
|
throw new Error('payload must be an object')
|
||||||
|
|
||||||
if (typeof secret !== 'string')
|
if (typeof secret !== 'string')
|
||||||
throw new Error('secret must be a string')
|
throw new Error('secret must be a string')
|
||||||
|
|
||||||
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 algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
||||||
|
|
||||||
if (!algorithm)
|
if (!algorithm)
|
||||||
throw new Error('algorithm not found')
|
throw new Error('algorithm not found')
|
||||||
|
|
||||||
payload.iat = Math.floor(Date.now() / 1000)
|
payload.iat = Math.floor(Date.now() / 1000)
|
||||||
|
|
||||||
const payloadAsJSON = JSON.stringify(payload)
|
const payloadAsJSON = JSON.stringify(payload)
|
||||||
const partialToken = `${base64UrlStringify(_utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm })))}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}`
|
const partialToken = `${base64UrlStringify(_utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm })))}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}`
|
||||||
let keyFormat = 'raw'
|
let keyFormat = 'raw'
|
||||||
@@ -197,6 +209,7 @@ export async function sign(payload: JwtPayload, secret: string, options: JwtSign
|
|||||||
keyData = _utf8ToUint8Array(secret)
|
keyData = _utf8ToUint8Array(secret)
|
||||||
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['sign'])
|
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['sign'])
|
||||||
const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken))
|
const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken))
|
||||||
|
|
||||||
return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}`
|
return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,33 +225,48 @@ export async function sign(payload: JwtPayload, secret: string, options: JwtSign
|
|||||||
export async function verify(token: string, secret: string, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', throwError: false }): Promise<boolean> {
|
export async function verify(token: string, secret: string, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', throwError: false }): Promise<boolean> {
|
||||||
if (typeof options === 'string')
|
if (typeof options === 'string')
|
||||||
options = { algorithm: options, throwError: false }
|
options = { algorithm: options, throwError: false }
|
||||||
|
|
||||||
options = { algorithm: 'HS256', throwError: false, ...options }
|
options = { algorithm: 'HS256', throwError: false, ...options }
|
||||||
|
|
||||||
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 (typeof secret !== 'string')
|
if (typeof secret !== 'string')
|
||||||
throw new Error('secret must be a string')
|
throw new Error('secret must be a string')
|
||||||
|
|
||||||
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('.')
|
const tokenParts = token.split('.')
|
||||||
|
|
||||||
if (tokenParts.length !== 3)
|
if (tokenParts.length !== 3)
|
||||||
throw new Error('token must consist of 3 parts')
|
throw new Error('token must consist of 3 parts')
|
||||||
|
|
||||||
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
||||||
|
|
||||||
if (!algorithm)
|
if (!algorithm)
|
||||||
throw new Error('algorithm not found')
|
throw new Error('algorithm not found')
|
||||||
|
|
||||||
const { payload } = decode(token)
|
const { payload } = decode(token)
|
||||||
|
|
||||||
if (!payload) {
|
if (!payload) {
|
||||||
if (options.throwError)
|
if (options.throwError)
|
||||||
throw 'PARSE_ERROR'
|
throw 'PARSE_ERROR'
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {
|
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {
|
||||||
if (options.throwError)
|
if (options.throwError)
|
||||||
throw 'NOT_YET_VALID'
|
throw 'NOT_YET_VALID'
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {
|
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {
|
||||||
if (options.throwError)
|
if (options.throwError)
|
||||||
throw 'EXPIRED'
|
throw 'EXPIRED'
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
let keyFormat = 'raw'
|
let keyFormat = 'raw'
|
||||||
|
|||||||
Reference in New Issue
Block a user