### Web Service Token Verification Example Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md A complete example demonstrating how to set up a verifier for a web service using Express. It includes common options like allowed issuers, audiences, required claims, and error handling for expired or invalid tokens. ```javascript const express = require('express') const { createVerifier, TOKEN_ERROR_CODES } = require('fast-jwt') const verify = createVerifier({ key: fs.readFileSync('./public.pem'), algorithms: ['RS256'], allowedIss: 'https://auth.example.com', allowedAud: 'my-api', requiredClaims: ['sub', 'email'], cache: true, cacheTTL: 3600000, // 1 hour clockTolerance: 2000 // 2 seconds }) app.use((req, res, next) => { const token = req.headers.authorization?.split(' ')[1] if (!token) return res.status(401).json({ error: 'Missing token' }) try { req.user = verify(token) next() } catch (err) { if (err.code === TOKEN_ERROR_CODES.expired) { res.status(401).json({ error: 'Token expired' }) } else if (err.code === TOKEN_ERROR_CODES.invalidSignature) { res.status(401).json({ error: 'Invalid token' }) } else { res.status(403).json({ error: 'Access denied' }) } } }) ``` -------------------------------- ### Signer (createSigner) Usage Examples Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt Demonstrates various ways to use the createSigner function, including HMAC, RSA, ECDSA, asynchronous operations, callbacks, and handling encrypted keys. Also shows payload mutation and custom header examples. ```javascript const signer = createSigner({ key: '-----BEGIN PRIVATE KEY-----\n...',\n algorithm: 'RS256' }); signer({ payload: { sub: '1234567890', name: 'John Doe', iat: 1516239022 } }).then(token => { console.log(token); }); ``` ```javascript const signer = createSigner({ key: '-----BEGIN PRIVATE KEY-----\n...', algorithm: 'RS256', // Custom header header: { kid: 'my-key-id' } }); signer({ payload: { sub: '1234567890', name: 'John Doe', iat: 1516239022 } }).then(token => { console.log(token); }); ``` ```javascript const signer = createSigner({ key: '-----BEGIN PRIVATE KEY-----\n...', algorithm: 'RS256', // Payload mutation mutatePayload: (payload) => { payload.custom = 'value'; return payload; } }); signer({ payload: { sub: '1234567890', name: 'John Doe', iat: 1516239022 } }).then(token => { console.log(token); }); ``` ```javascript const signer = createSigner({ key: '-----BEGIN PRIVATE KEY-----\n...', algorithm: 'RS256', // Encrypted private key passphrase: 'my-secret-passphrase' }); signer({ payload: { sub: '1234567890', name: 'John Doe', iat: 1516239022 } }).then(token => { console.log(token); }); ``` ```javascript const signer = createSigner({ key: async () => { // Async key fetching return await fetchKey(); }, algorithm: 'RS256' }); signer({ payload: { sub: '1234567890', name: 'John Doe', iat: 1516239022 } }).then(token => { console.log(token); }); ``` ```javascript const signer = createSigner({ key: 'my-secret-key', algorithm: 'HS256' }); signer({ payload: { sub: '1234567890', name: 'John Doe', iat: 1516239022 } }, (err, token) => { if (err) { console.error(err); } else { console.log(token); } }); ``` -------------------------------- ### Install fast-jwt Source: https://github.com/nearform/fast-jwt/blob/master/README.md Install the fast-jwt package using npm. ```bash npm install fast-jwt ``` -------------------------------- ### OAuth2 Authorization Server Example Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt Demonstrates the access and refresh token pattern for an OAuth2 authorization server using fast-jwt. ```javascript const { createSigner } = require('fast-jwt'); const accessTokenSigner = createSigner({ key: 'access-token-secret', algorithm: 'HS256', expiresIn: '1h' }); const refreshTokenSigner = createSigner({ key: 'refresh-token-secret', algorithm: 'HS256', expiresIn: '7d' }); // Endpoint to issue tokens app.post('/oauth2/token', (req, res) => { const { grant_type, code } = req.body; if (grant_type === 'authorization_code') { // Validate code and get user info const userId = getUserIdFromAuthCode(code); const accessToken = accessTokenSigner({ payload: { sub: userId, scope: 'read write' } }); const refreshToken = refreshTokenSigner({ payload: { sub: userId } }); res.json({ access_token: accessToken, refresh_token: refreshToken, token_type: 'Bearer', expires_in: 3600 }); } else { res.status(400).send('Unsupported grant type'); } }); ``` -------------------------------- ### Decoder (createDecoder) Usage Examples Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt Shows how to use the createDecoder function for parsing JWTs. Includes examples for complete token structure and type validation. ```javascript const decoder = createDecoder(); decoder('your.jwt.token').then(result => { console.log(result.header); console.log(result.payload); console.log(result.signature); }); ``` ```javascript const decoder = createDecoder({ // Type validation type: 'custom-jwt' }); decoder('your.jwt.token').then(result => { console.log(result.payload); }); ``` -------------------------------- ### JWKS Endpoint Integration Example Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt Shows how to integrate with a JWKS (JSON Web Key Set) endpoint for dynamic key fetching in fast-jwt. ```javascript const { createVerifier } = require('fast-jwt'); const axios = require('axios'); const jwksClient = axios.create({ baseURL: 'https://your.auth.server/.well-known/jwks.json' }); const verifier = createVerifier({ key: async (header, callback) => { try { const response = await jwksClient.get('/'); const key = response.data.keys.find(k => k.kid === header.kid); if (!key) { return callback(new Error('Key not found')); } // Convert JWK to PEM format if necessary const pem = await jose.JWK.asKey(key).toPEM(); callback(null, pem); } catch (err) { callback(err); } }, algorithms: ['RS256'] }); // Use verifier in your Express middleware... ``` -------------------------------- ### TokenError Usage Examples Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt Demonstrates how to work with TokenError, including wrapping errors and creating custom error instances. ```javascript try { // Some operation that might throw a TokenError } catch (err) { if (err instanceof TokenError) { console.error('Token Error:', err.message); console.error('Code:', err.code); } else { console.error('Other Error:', err); } } ``` ```javascript const originalError = new Error('Something went wrong'); const wrappedError = new TokenError('ERR_WRAPPER', 'Failed to process token', originalError); console.error(wrappedError); console.error(wrappedError.cause); ``` ```javascript const customError = TokenError.fromPayload('ERR_CUSTOM', 'Invalid audience', { aud: 'expected-audience' }); console.error(customError); ``` -------------------------------- ### Express.js Middleware Example Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt A complete implementation of an Express.js middleware for JWT authentication using fast-jwt. ```javascript const express = require('express'); const { createVerifier } = require('fast-jwt'); const app = express(); const verifier = createVerifier({ key: '-----BEGIN PUBLIC KEY-----\n...', algorithms: ['RS256'] }); app.use(async (req, res, next) => { const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).send('Unauthorized'); } try { req.user = await verifier(token); next(); } catch (err) { res.status(401).send('Unauthorized'); } }); app.get('/protected', (req, res) => { res.send(`Hello, ${req.user.name}!`); }); app.listen(3000); ``` -------------------------------- ### Create RSA Signer Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md This example demonstrates creating a signer for RSA-signed tokens using a private key file. It sets an expiration time in milliseconds and includes a key ID for versioning. The algorithm is auto-detected as RS256. ```javascript const signer = createSigner({ key: fs.readFileSync('./private.pem'), expiresIn: 3600000, kid: '2024-01', noTimestamp: false }) ``` -------------------------------- ### Configure Signer with Environment Variables Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md Example of configuring a JWT signer using environment variables for the private key, algorithm, and expiry time. Provides default values for algorithm and expiry. ```javascript const signer = createSigner({ key: process.env.PRIVATE_KEY, algorithm: process.env.TOKEN_ALGORITHM || 'HS256', expiresIn: parseInt(process.env.TOKEN_EXPIRY || '3600000') }) ``` -------------------------------- ### Verify JWT Token Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/README.md Example of creating a verifier function with a secret key and verifying a token. ```javascript const { createVerifier } = require('fast-jwt') const verify = createVerifier({ key: 'secret' }) const payload = verify(token) // => { userId: 123, email: 'user@example.com', iat: 1234567890 } ``` -------------------------------- ### Token Caching Example Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt Illustrates implementing an LRU (Least Recently Used) cache strategy for JWTs with fast-jwt. ```javascript const { createVerifier } = require('fast-jwt'); const verifier = createVerifier({ key: '-----BEGIN PUBLIC KEY-----\n...', // Your public key algorithms: ['RS256'], cache: { max: 1000, // Maximum number of tokens to cache ttl: 60000 // Time-to-live in milliseconds (1 minute) } }); // When verifier is called, it will automatically use the cache. ``` -------------------------------- ### Verifier (createVerifier) Usage Examples Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt Illustrates various ways to use the createVerifier function, including basic verification, RSA, complete options, caching, asynchronous keys, and claim validation. Also shows algorithm restriction and error caching. ```javascript const verifier = createVerifier({ key: '-----BEGIN PUBLIC KEY-----\n...', algorithms: ['RS256'] }); verifier('your.jwt.token').then(payload => { console.log(payload); }); ``` ```javascript const verifier = createVerifier({ key: '-----BEGIN PUBLIC KEY-----\n...', algorithms: ['RS256'], // Clock tolerance for time skew clockTolerance: 10 // seconds }); verifier('your.jwt.token').then(payload => { console.log(payload); }); ``` ```javascript const verifier = createVerifier({ key: '-----BEGIN PUBLIC KEY-----\n...', algorithms: ['RS256'], // Cache configuration cache: { max: 100, ttl: 60000 // 1 minute } }); verifier('your.jwt.token').then(payload => { console.log(payload); }); ``` ```javascript const verifier = createVerifier({ key: async () => { // Async key fetching return await fetchPublicKey(); }, algorithms: ['RS256'] }); verifier('your.jwt.token').then(payload => { console.log(payload); }); ``` ```javascript const verifier = createVerifier({ key: '-----BEGIN PUBLIC KEY-----\n...', algorithms: ['RS256'], // Claim validation allowedAud: ['my-audience'], allowedIss: ['my-issuer'] }); verifier('your.jwt.token').then(payload => { console.log(payload); }); ``` ```javascript const verifier = createVerifier({ key: '-----BEGIN PUBLIC KEY-----\n...', algorithms: ['RS256'], // Error caching errorCacheTTL: 5000 // 5 seconds }); verifier('your.jwt.token').catch(err => { console.error(err); }); ``` ```javascript const verifier = createVerifier({ key: 'my-secret-key', algorithms: ['HS256'] }); verifier('your.jwt.token', (err, payload) => { if (err) { console.error(err); } else { console.log(payload); } }); ``` -------------------------------- ### Async Key Function with Promise Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createSigner.md Demonstrates how to create a signer where the signing key is fetched asynchronously, for example, from an external vault service. This is useful for dynamic key management. ```APIDOC ## createSigner with Async Key ### Description Creates a JWT signer where the signing key is provided via an asynchronous function. This allows for dynamic fetching of secrets from external sources like vaults. ### Method Signature `createSigner(options)` ### Parameters #### options - **key** (Function) - Required - An async function that resolves to the signing key (string or object). ### Request Example ```javascript const { createSigner } = require('fast-jwt') const signer = createSigner({ key: async () => { // Fetch from external service const secret = await getSecretFromVault() return secret } }) async function signToken() { const token = await signer({ userId: 999, permissions: ['read', 'write'] }) return token } ``` ### Response - **token** (string) - The generated JWT. ``` -------------------------------- ### Create Signer with Async Key Fetching Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md Use this configuration when the private key needs to be fetched asynchronously, for example, from a secrets vault. The `key` option accepts an async function that resolves with the private key. ```javascript const signer = createSigner({ key: async (decoded) => { // decoded has: { header, payload, signature, input } return await getPrivateKeyFromVault(decoded.header.kid) }, expiresIn: '1h' }) ``` -------------------------------- ### Logging Minimal Error Information Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/errors.md This example demonstrates a best practice for logging errors. It advises against logging the entire token and instead suggests logging only essential context like the error code, message, and a timestamp. ```javascript // ❌ Don't log the token itself console.log('Token:', token) // ✅ Log only necessary context console.log('Verification failed', { code: err.code, message: err.message, timestamp: new Date().toISOString() }) ``` -------------------------------- ### Configure Verifier with Environment Variables Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md Example of configuring a JWT verifier using environment variables for the public key, allowed algorithms, allowed issuers, and allowed audiences. Handles comma-separated lists for algorithms and audiences. ```javascript const verify = createVerifier({ key: process.env.PUBLIC_KEY, algorithms: (process.env.ALLOWED_ALGORITHMS || 'RS256').split(','), allowedIss: process.env.ALLOWED_ISSUER, allowedAud: (process.env.ALLOWED_AUD || '').split(',').filter(Boolean) }) ``` -------------------------------- ### JWT Verification with Fast-JWT Source: https://github.com/nearform/fast-jwt/blob/master/README.md Demonstrates synchronous, callback, and promise-based JWT verification using fast-jwt. Includes an example of customizing error cache TTL. ```javascript const { createVerifier, TOKEN_ERROR_CODES } = require('fast-jwt') const token = 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9.mIcxteEVjbh2MnKQ3EQlojZojGSyA_guqRBYHQURcfnCSSBTT2OShF8lo9_ogjAv-5oECgmCur_cDWB7x3X53g' // Sync style const verifySync = createVerifier({ key: 'secret' }) const payload = verifySync(token) // => { a: 1, b: 2, c: 3, iat: 1579521212 } // Callback style with complete return const verifyWithCallback = createVerifier({ key: callback => callback(null, 'secret'), complete: true }) verifyWithCallback(token, (err, sections) => { /* sections === { header: { alg: 'HS512', typ: 'JWT' }, payload: { a: 1, b: 2, c: 3, iat: 1579521212 }, signature: 'mIcxteEVjbh2MnKQ3EQlojZojGSyA/guqRBYHQURcfnCSSBTT2OShF8lo9/ogjAv+5oECgmCur/cDWB7x3X53g==', input: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9' } */ }) // Promise style - Note that the key function style and the verifier function style are unrelated async function test() { const verifyWithPromise = createVerifier({ key: async () => 'secret' }) const payload = await verifyWithPromise(token) // => { a: 1, b: 2, c: 3, iat: 1579521212 } } // custom errorCacheTTL verifier const verifier = createVerifier({ key: 'secret', cache: true, errorCacheTTL: tokenError => { // customize the ttl based on the error code if (tokenError.code === TOKEN_ERROR_CODES.invalidKey) { return 1000 } return 2000 } }) ``` -------------------------------- ### RSA Signing with Expiration and Claims Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createSigner.md This example demonstrates signing JWTs using RSA (RS256) with an RSA private key. It also configures token expiration (`expiresIn`) and issuer/audience claims. ```javascript const fs = require('fs') const { createSigner } = require('fast-jwt') const privateKey = fs.readFileSync('./private-key.pem', 'utf-8') const signer = createSigner({ key: privateKey, algorithm: 'RS256', expiresIn: '7d', iss: 'my-app', aud: 'my-users' }) const token = signer({ userId: 456, roles: ['admin', 'user'] }) ``` -------------------------------- ### Create JWT Signer Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/README.md Example of creating a signer function with a secret key and signing a payload. ```javascript const { createSigner } = require('fast-jwt') const signer = createSigner({ key: 'secret' }) const token = signer({ userId: 123, email: 'user@example.com' }) // => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' ``` -------------------------------- ### Custom Claims Validation Example Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt Demonstrates how to perform custom claims validation using options like allowedIss (issuer) and allowedAud (audience) in fast-jwt. ```javascript const { createVerifier } = require('fast-jwt'); const verifier = createVerifier({ key: '-----BEGIN PUBLIC KEY-----\n...', // Your public key algorithms: ['RS256'], allowedIss: ['https://your.issuer.com'], // Allowed issuers allowedAud: ['my-api-audience'] // Allowed audiences }); verifier('your.jwt.token').then(payload => { console.log('Token is valid and claims are accepted:', payload); }).catch(err => { console.error('Token validation failed:', err.message); }); ``` -------------------------------- ### RSA Verification with Algorithm Restriction Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createVerifier.md Verify RSA-signed JWTs using a public key and restrict allowed algorithms. This example demonstrates reading a public key from a file and handling potential verification errors. ```javascript const fs = require('fs') const { createVerifier } = require('fast-jwt') const publicKey = fs.readFileSync('./public-key.pem', 'utf-8') const verify = createVerifier({ key: publicKey, algorithms: ['RS256'], ignoreExpiration: false }) try { const payload = verify(token) console.log('Token valid:', payload) } catch (err) { console.error('Token invalid:', err.code, err.message) } ``` -------------------------------- ### Catching and Handling Specific Token Errors Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/TokenError.md Provides an example of using a try-catch block to handle potential TokenErrors during token verification, checking the error code to determine the appropriate action. ```javascript const { createVerifier, TOKEN_ERROR_CODES } = require('fast-jwt') const verify = createVerifier({ key: 'secret' }) try { const payload = verify(token) } catch (err) { if (err instanceof TokenError) { switch (err.code) { case TOKEN_ERROR_CODES.expired: console.error('Token has expired, please login again') break case TOKEN_ERROR_CODES.invalidSignature: console.error('Token is tampered or signed with wrong key') break case TOKEN_ERROR_CODES.malformed: console.error('Token format is invalid') break default: console.error('Token verification failed:', err.message) } } else { console.error('Unexpected error:', err) } } ``` -------------------------------- ### Create Signer with Custom Header Claims Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md This example shows how to add custom claims to the JWT header. These claims are merged with the default header and can override existing ones like 'typ' or 'kid'. ```javascript const signer = createSigner({ key: 'secret', header: { cty: 'JWT', version: '1.0', custom: 'value' } }) ``` -------------------------------- ### Handling FAST_JWT_INVALID_CRIT_HEADER Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/errors.md This example demonstrates how to handle invalid critical headers in a JWT. It shows how to configure allowed critical headers and catch errors when a token contains an unsupported or malformed critical header. ```javascript const verify = createVerifier({ key: 'secret', allowedCritHeaders: ['custom-ext'] // Only allow 'custom-ext' }) // Token with unallowed critical header try { verify(tokenWithUnknownCrit) // ❌ Critical extension not supported } catch (err) { if (err.code === TOKEN_ERROR_CODES.invalidCritHeader) { console.error('Critical extension not supported') } } ``` -------------------------------- ### JWKS Endpoint Integration for JWT Verification Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/README.md This example shows how to configure fast-jwt's verifier to dynamically fetch JWKS (JSON Web Key Set) from an endpoint. This is useful for verifying tokens signed by external identity providers. ```javascript const { createVerifier } = require('fast-jwt') const verify = createVerifier({ key: async (decoded) => { const jwk = await getJWKFromEndpoint(decoded.header.kid) return jwk }, algorithms: ['RS256', 'RS384', 'RS512'], cache: true }) ``` -------------------------------- ### OAuth2 Authorization Server Token Issuance Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md Example of creating signers for both access and refresh tokens in an OAuth2 authorization server context. It shows how to configure different expiry times and payloads for each token type. ```javascript const { createSigner } = require('fast-jwt') const accessTokenSigner = createSigner({ key: fs.readFileSync('./private.pem'), algorithm: 'RS256', iss: 'https://auth.example.com', expiresIn: '1h', noTimestamp: false }) const refreshTokenSigner = createSigner({ key: fs.readFileSync('./refresh-private.pem'), algorithm: 'RS256', iss: 'https://auth.example.com', expiresIn: '30d' }) function issueTokens(userId) { const accessToken = accessTokenSigner({ sub: userId, aud: 'my-api', scope: ['read', 'write'] }) const refreshToken = refreshTokenSigner({ sub: userId, type: 'refresh' }) return { accessToken, refreshToken } } ``` -------------------------------- ### Handling Time-Based JWT Errors Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/errors.md This example demonstrates how to handle time-based JWT errors like expiration or tokens not yet valid. It shows how to trigger specific flows, such as a refresh token process or waiting for the token to become valid. ```javascript const verify = createVerifier({ key: 'secret' }) try { return verify(token) } catch (err) { if (err.code === TOKEN_ERROR_CODES.expired) { // Trigger refresh flow throw new RefreshRequiredError() } if (err.code === TOKEN_ERROR_CODES.inactive) { // Token not yet valid - wait or reject throw new NotYetValidError() } throw err } ``` -------------------------------- ### Project Release Process Source: https://github.com/nearform/fast-jwt/blob/master/CONTRIBUTING.md Steps to follow for releasing a new version of the project, including testing, version bumping, and publishing. ```bash npm test npm version git push && git push --tags npm publish ``` -------------------------------- ### Example Usage of TokenValidationErrorCode Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/types.md Demonstrates how to assign a specific error code string to a variable of type TokenValidationErrorCode. ```typescript const code: TokenValidationErrorCode = 'FAST_JWT_EXPIRED' ``` -------------------------------- ### Create Signer with Callback-Style Key Fetching Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md This snippet demonstrates how to fetch the private key using a callback-style asynchronous function. The callback is invoked with the fetched key or an error. ```javascript const signer = createSigner({ key: (decoded, callback) => { // decoded has: { header, payload, signature, input } getPrivateKeyFromDatabase(decoded.header.kid, callback) }, expiresIn: '1h' }) ``` -------------------------------- ### Decode JWT Token (No Verification) Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/README.md Example of creating a decoder function to parse a token's payload without verifying the signature. ```javascript const { createDecoder } = require('fast-jwt') const decode = createDecoder() const payload = decode(token) // => { userId: 123, email: 'user@example.com', iat: 1234567890 } ``` -------------------------------- ### Async Key Function with Callback Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createSigner.md Illustrates how to use an asynchronous key fetching function with a Node.js-style callback. The `key` option accepts a function that calls back with the secret or error. ```javascript const { createSigner } = require('fast-jwt') const signer = createSigner({ key: (callback) => { // Fetch key from database or secret manager setTimeout(() => callback(null, 'secret'), 100) } }) signer({ userId: 789 }, (err, token) => { if (err) console.error('Signing failed:', err) else console.log('Token:', token) }) ``` -------------------------------- ### Create JWTs with fast-jwt Source: https://github.com/nearform/fast-jwt/blob/master/README.md Demonstrates synchronous, callback, and promise-based JWT creation using createSigner. Also shows signing with a password-protected private key, which requires specifying the algorithm. ```javascript const { createSigner } = require('fast-jwt') // Sync style const signSync = createSigner({ key: 'secret' }) const token = signSync({ a: 1, b: 2, c: 3 }) // => eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9.mIcxteEVjbh2MnKQ3EQlojZojGSyA_guqRBYHQURcfnCSSBTT2OShF8lo9_ogjAv-5oECgmCur_cDWB7x3X53g // Callback style const signWithCallback = createSigner({ key: (callback) => callback(null, 'secret') }) signWithCallback({ a: 1, b: 2, c: 3 }, (err, token) => { // token === eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9.mIcxteEVjbh2MnKQ3EQlojZojGSyA_guqRBYHQURcfnCSSBTT2OShF8lo9_ogjAv-5oECgmCur_cDWB7x3X53g }) // Promise style - Note that the key function style and the signer function style are unrelated async function test() { const signWithPromise = createSigner({ key: async () => 'secret' }) const token = await signWithPromise({ a: 1, b: 2, c: 3 }) // => eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9.mIcxteEVjbh2MnKQ3EQlojZojGSyA_guqRBYHQURcfnCSSBTT2OShF8lo9_ogjAv-5oECgmCur_cDWB7x3X53g } // Using password protected private key - in this case you MUST provide the algorithm as well const signSync = createSigner({ algorithm: '', key: { key: '', passphrase: '' }) const token = signSync({ a: 1, b: 2, c: 3 }) ``` -------------------------------- ### Main Module Entry Point Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/EXPORTS.md Exports all public symbols from the main entry point of the fast-jwt library. ```javascript module.exports = { TokenError, TOKEN_ERROR_CODES, createDecoder, createVerifier, createSigner } ``` -------------------------------- ### Run Linters and Tests Source: https://github.com/nearform/fast-jwt/blob/master/CONTRIBUTING.md Execute the project's linters and run all tests to ensure code quality and correctness before contributing. ```bash npm lint npm test ``` -------------------------------- ### Signer (createSigner) Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/COMPLETION_REPORT.txt Creates a JWT signer. Supports various algorithms, options, and provides examples for different use cases including HMAC, RSA, ECDSA, async operations, and encrypted keys. ```APIDOC ## Signer (createSigner) ### Description Creates a JSON Web Token (JWT) signer. This function allows for the creation of signed JWTs using various cryptographic algorithms and offers extensive configuration options. ### Method `createSigner(options)` ### Parameters - **options** (object) - Required - Configuration options for the signer. - **algorithm** (string) - Required - The signing algorithm (e.g., 'HS256', 'RS256'). - **key** (string | Buffer | object) - Required - The secret or private key for signing. - **encoding** (string) - Optional - The encoding of the key (e.g., 'utf8', 'base64'). - **header** (object) - Optional - Custom JWT header parameters. - **jti** (boolean | string) - Optional - Whether to include a 'jti' claim, or a custom value for it. - **kid** (string) - Optional - Key ID to include in the header. - **signer** (function) - Optional - Custom signer function. - **payloadMutator** (function) - Optional - Function to mutate the payload before signing. - **expiresIn** (string | number) - Optional - Sets the 'exp' claim. - **notBefore** (string | number) - Optional - Sets the 'nbf' claim. - **audience** (string | string[]) - Optional - Sets the 'aud' claim. - **issuer** (string | string[]) - Optional - Sets the 'iss' claim. - **subject** (string | string[]) - Optional - Sets the 'sub' claim. - **jwtid** (string | string[]) - Optional - Sets the 'jti' claim. - **noTimestamp** (boolean) - Optional - If true, 'iat' and 'nbf' are not added. - **headerType** (string) - Optional - Sets the 'typ' header. ### Return Type `Signer` - An object with a `sign` method. ### Examples ```javascript // HMAC Example const signer = createSigner({ key: 'secret', algorithm: 'HS256' }); const token = await signer.sign({ data: 'payload' }); // RSA Example with encrypted key const signerRSA = createSigner({ key: { pem: fs.readFileSync('private.pem'), passphrase: 'password' }, algorithm: 'RS256' }); const tokenRSA = await signerRSA.sign({ data: 'payload' }); ``` ``` -------------------------------- ### Creating Custom TokenError Instances Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/TokenError.md Demonstrates how to create new TokenError instances, both with a basic code and message, and with additional contextual properties. ```javascript const { TokenError, TOKEN_ERROR_CODES } = require('fast-jwt') // Create with basic info const err1 = new TokenError( TOKEN_ERROR_CODES.invalidSignature, 'The signature does not match' ) // Create with additional context const err2 = new TokenError( TOKEN_ERROR_CODES.keyFetchingError, 'Could not fetch key', { keyId: 'key-123', reason: 'Database timeout', retryable: true } ) console.log(err2.keyId) // 'key-123' console.log(err2.retryable) // true ``` -------------------------------- ### Async Key Fetching with Promises Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md Implement Promise-based asynchronous key fetching for verifiers. The `key` function can be async and should use the `kid` header to retrieve the correct public key. ```javascript const verify = createVerifier({ key: async (decoded) => { // Use kid header to fetch the right key const publicKey = await getPublicKeyFromJWKS(decoded.header.kid) return publicKey } }) ``` -------------------------------- ### Asynchronous Key Fetching with Promise Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createVerifier.md Configure `createVerifier` with an `async` key function that returns a Promise to fetch keys. This is suitable for modern asynchronous operations, such as fetching keys from a JWKS endpoint. ```javascript const { createVerifier } = require('fast-jwt') const verify = createVerifier({ key: async (decoded) => { // Fetch key from JWKS endpoint const key = await jwks.getKey(decoded.header.kid) return key } }) async function validateToken(token) { try { const payload = await verify(token) return payload } catch (err) { console.error('Invalid token:', err.code) throw err } } ``` -------------------------------- ### Enable Basic Token Caching Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md Set 'cache' to 'true' to enable LRU token caching with the default size of 1000 tokens. ```javascript const verify = createVerifier({ key: 'secret', cache: true // Default size: 1000 tokens }) ``` -------------------------------- ### Inspect Token Before Verification Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createDecoder.md Demonstrates inspecting a token's header to determine the appropriate verification method before proceeding with signature validation. This allows for dynamic selection of verifiers based on the token's algorithm. ```javascript const { createDecoder, createVerifier } = require('fast-jwt') // First, inspect the token to decide on verification const inspect = createDecoder({ complete: true }) const decoded = inspect(token) // Route based on algorithm const verifyHS = createVerifier({ key: 'secret', algorithms: ['HS256'] }) const verifyRS = createVerifier({ key: publicKey, algorithms: ['RS256'] }) const verifier = decoded.header.alg === 'HS256' ? verifyHS : verifyRS const payload = verifier(token) ``` -------------------------------- ### Complete Token Structure Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createVerifier.md Configures the verifier to return the complete token structure, including header, payload, signature, and the original input token. ```APIDOC ## createVerifier with Complete Token Option ### Description Creates a verifier instance that, when successful, returns an object containing the token's header, payload, signature, and the original input token. ### Method `createVerifier(options)` ### Parameters #### Options - **key** (string | Buffer | object | function) - Required - The secret key for verification. - **complete** (boolean) - Required - Set to `true` to enable the return of the complete token structure. ### Returns - `function` - A verifier function that takes a token string and returns a complete token object or throws an error. ### Usage Example ```javascript const { createVerifier } = require('fast-jwt') const verify = createVerifier({ key: 'secret', complete: true }) const result = verify(token) console.log(result) /* { header: { alg: 'HS256', typ: 'JWT' }, payload: { userId: 123, iat: 1579521212 }, signature: 'xxx', input: 'eyJhbGci...' } */ ``` ``` -------------------------------- ### Create Signer with Encrypted Private Key Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md Use this snippet when your private key is encrypted. You must explicitly provide the algorithm and the key object containing the key material and its passphrase. ```javascript const signer = createSigner({ algorithm: 'RS256', key: { key: fs.readFileSync('./encrypted.pem'), passphrase: 'decryption-password' }, expiresIn: '24h' }) ``` -------------------------------- ### Async Key Function with Callback Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createVerifier.md Supports asynchronous retrieval of verification keys using a callback pattern, useful for dynamic key fetching. ```APIDOC ## createVerifier with Async Key Function (Callback) ### Description Creates a verifier instance where the verification key is fetched asynchronously using a callback function. This is useful when keys need to be dynamically retrieved based on token claims (e.g., `kid`). ### Method `createVerifier(options)` ### Parameters #### Options - **key** (function) - Required - An asynchronous function that accepts the decoded token header and a callback. The callback should be called with `(err, key)`. ### Returns - `function` - A verifier function that takes a token string and a callback, returning the decoded payload or an error. ### Usage Example ```javascript const { createVerifier } = require('fast-jwt') const verify = createVerifier({ key: (decoded, callback) => { // Use kid header to fetch the right key const keyId = decoded.header.kid database.getPublicKey(keyId, (err, key) => { callback(err, key) }) } }) verify(token, (err, payload) => { if (err) console.error('Verification failed:', err.code) else console.log('Valid token:', payload) }) ``` ``` -------------------------------- ### Async Key Function with Promise Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createVerifier.md Supports asynchronous retrieval of verification keys using Promises, enabling modern async/await syntax for dynamic key fetching. ```APIDOC ## createVerifier with Async Key Function (Promise) ### Description Creates a verifier instance where the verification key is fetched asynchronously using Promises. This allows for cleaner async/await syntax when dynamically retrieving keys. ### Method `createVerifier(options)` ### Parameters #### Options - **key** (async function) - Required - An asynchronous function that accepts the decoded token header and returns a Promise resolving to the verification key. ### Returns - `function` - A verifier function that takes a token string and returns a Promise resolving to the decoded payload or rejecting with an error. ### Usage Example ```javascript const { createVerifier } = require('fast-jwt') const verify = createVerifier({ key: async (decoded) => { // Fetch key from JWKS endpoint const key = await jwks.getKey(decoded.header.kid) return key } }) async function validateToken(token) { try { const payload = await verify(token) return payload } catch (err) { console.error('Invalid token:', err.code) throw err } } ``` ``` -------------------------------- ### Configure Custom Cache Size and TTL Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md Provide a number to 'cache' for a custom cache size and set 'cacheTTL' to define the entry lifetime in milliseconds. ```javascript const verify = createVerifier({ key: 'secret', cache: 5000, // Cache up to 5000 tokens cacheTTL: 1800000 // Entries valid for 30 minutes }) ``` -------------------------------- ### Implement Custom Cache Key Builder Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/configuration.md Provide a 'cacheKeyBuilder' function to customize how cache keys are generated, potentially for performance or specific logic. ```javascript const verify = createVerifier({ key: 'secret', cache: true, cacheKeyBuilder: (token) => { // Use first 100 chars as key (faster but less secure) return token.substring(0, 100) } }) ``` -------------------------------- ### Decode JWTs with fast-jwt Source: https://github.com/nearform/fast-jwt/blob/master/README.md Shows how to create a standard decoder and a decoder that returns all token sections (header, payload, signature, input). The `complete: true` option is used for the latter. ```javascript const { createDecoder } = require('fast-jwt') const token = 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9.mIcxteEVjbh2MnKQ3EQlojZojGSyA_guqRBYHQURcfnCSSBTT2OShF8lo9_ogjAv-5oECgmCur_cDWB7x3X53g' // Standard decoder const decode = createDecoder() const payload = decode(token) // => { a: 1, b: 2, c: 3, iat: 1579521212 } // Complete decoder const decodeComplete = createDecoder({ complete: true }) const sections = decodeComplete(token) /* => { header: { alg: 'HS512', typ: 'JWT' }, payload: { a: 1, b: 2, c: 3, iat: 1579521212 }, signature: 'mIcxteEVjbh2MnKQ3EQlojZojGSyA/guqRBYHQURcfnCSSBTT2OShF8lo9/ogjAv+5oECgmCur/cDWB7x3X53g==', input: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9' } */ ``` -------------------------------- ### Basic Verification (Synchronous) Source: https://github.com/nearform/fast-jwt/blob/master/_autodocs/api-reference/createVerifier.md Creates a verifier with a secret key for synchronous token verification. This is the simplest way to verify a JWT. ```APIDOC ## createVerifier ### Description Creates a verifier instance for JWT tokens using a synchronous key. ### Method `createVerifier(options)` ### Parameters #### Options - **key** (string | Buffer | object | function) - Required - The secret key or an object containing key information for verification. Can also be an asynchronous function. - **algorithms** (string[]) - Optional - An array of allowed algorithms. If not provided, all algorithms are allowed. - **complete** (boolean) - Optional - If true, the result will include the header, payload, signature, and input token. - **cache** (boolean | object) - Optional - Enables token caching. Can be a boolean or an object with cache configuration. - **cacheTTL** (number) - Optional - Time-to-live for cached tokens in milliseconds. - **cacheKeyBuilder** (function) - Optional - A function to build a custom cache key for tokens. - **ignoreExpiration** (boolean) - Optional - If true, expiration checks are ignored. - **ignoreNotBefore** (boolean) - Optional - If true, `nbf` (not before) checks are ignored. - **allowedIss** (string | string[] | RegExp) - Optional - Allowed issuers for the token. - **allowedAud** (string | string[] | RegExp) - Optional - Allowed audiences for the token. - **allowedSub** (string | RegExp) - Optional - Allowed subjects for the token. - **requiredClaims** (string[]) - Optional - An array of claim names that must be present in the token. - **maxAge** (number) - Optional - Maximum age of the token in milliseconds. - **errorCacheTTL** (number | function) - Optional - Time-to-live for caching verification errors, or a function to determine TTL based on the error. ### Returns - `function` - A verifier function that takes a token string and returns the decoded payload or throws an error. ### Usage Example ```javascript const { createVerifier } = require('fast-jwt') const verify = createVerifier({ key: 'secret' }) const payload = verify('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...') console.log(payload) // => { userId: 123, email: 'user@example.com', iat: 1579521212 } ``` ```