1
0

Compare commits

...

1 Commits

Author SHA1 Message Date
1b4c93adb2 add algorithm none 2025-05-29 01:26:59 +02:00
4 changed files with 37 additions and 28 deletions

View File

@@ -99,7 +99,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` | required | - | A string which is used to sign the payload. `secret` | `string`, `JsonWebKey`, `CryptoKey` | optional | - | A secret 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 +121,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` | required | - | The string which was used to sign the payload. `secret` | `string`, `JsonWebKey`, `CryptoKey` | optional | - | The secret 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,3 +189,4 @@ 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`

View File

@@ -12,9 +12,9 @@ if (typeof crypto === "undefined" || !crypto.subtle)
/** /**
* @typedef JwtAlgorithm * @typedef JwtAlgorithm
* @type {"ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512"} * @type {"none" | "ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512"}
*/ */
export type JwtAlgorithm = "ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512" export type JwtAlgorithm = "none" | "ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512"
/** /**
* @typedef JwtAlgorithms * @typedef JwtAlgorithms
@@ -118,11 +118,12 @@ 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" } },
@@ -143,7 +144,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, options: JwtSignOptions<Header> | JwtAlgorithm = "HS256"): Promise<string> { export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payload>, secret: string | JsonWebKeyWithKid | CryptoKey | undefined, options: JwtSignOptions<Header> | JwtAlgorithm = "HS256"): Promise<string> {
if (typeof options === "string") if (typeof options === "string")
options = { algorithm: options } options = { algorithm: options }
@@ -152,7 +153,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 (!secret || (typeof secret !== "string" && typeof secret !== "object")) if (options.algorithm !== "none" && (!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")
@@ -168,7 +169,10 @@ 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"]) if (options.algorithm === "none")
return partialToken
const key = secret instanceof CryptoKey ? secret : await importKey(secret!, algorithm, ["sign"])
const signature = await crypto.subtle.sign(algorithm, key, textToUint8Array(partialToken)) const signature = await crypto.subtle.sign(algorithm, key, textToUint8Array(partialToken))
return `${partialToken}.${arrayBufferToBase64Url(signature)}` return `${partialToken}.${arrayBufferToBase64Url(signature)}`
@@ -183,7 +187,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, options: JwtVerifyOptions | JwtAlgorithm = "HS256"): Promise<JwtData<Payload, Header> | undefined> { export async function verify<Payload = {}, Header = {}>(token: string, secret: string | JsonWebKeyWithKid | CryptoKey | undefined, 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 }
@@ -191,16 +195,18 @@ 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 (typeof secret !== "string" && typeof secret !== "object") if (options.algorithm !== "none" && 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(".") const tokenParts = token.split(".", 3)
if (tokenParts.length !== 3) if (tokenParts.length < 2)
throw new Error("token must consist of 3 parts") throw new Error("token must consist of 2 or more parts")
const [ tokenHeader, tokenPayload, tokenSignature ] = tokenParts
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm] const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
@@ -223,9 +229,12 @@ export async function verify<Payload = {}, Header = {}>(token: string, secret: s
throw new Error("EXPIRED") throw new Error("EXPIRED")
} }
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["verify"]) if (algorithm.name === "none")
return decodedToken
if (!await crypto.subtle.verify(algorithm, key, base64UrlToUint8Array(tokenParts[2]), textToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`))) const key = secret instanceof CryptoKey ? secret : await importKey(secret!, algorithm, ["verify"])
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

@@ -84,13 +84,9 @@ 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 | undefined { export function decodePayload<T = any>(raw: string): T {
try {
const bytes = Array.from(atob(raw), char => char.charCodeAt(0)); const bytes = Array.from(atob(raw), char => char.charCodeAt(0));
const decodedString = new TextDecoder("utf-8").decode(new Uint8Array(bytes)); 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,6 +18,9 @@ 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-----',
@@ -72,7 +75,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) => {