### Installing Dependencies with npm Source: https://github.com/nekzus/tokenly/blob/main/CONTRIBUTING.md This command installs all the necessary dependencies for the Tokenly project, as specified in the package.json file. It is a prerequisite for running tests, building the project, and developing new features. ```bash npm install ``` -------------------------------- ### Install Tokenly via bun Source: https://github.com/nekzus/tokenly/blob/main/docs/api/tokenly.md Install the Tokenly library using bun. This command adds Tokenly as a project dependency. ```shell $ bun add @nekzus/tokenly ``` -------------------------------- ### Installing Tokenly via bun Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Install the Tokenly library using bun. This command adds Tokenly as a project dependency. ```sh $ bun add @nekzus/tokenly ``` -------------------------------- ### Initializing Tokenly with Basic Configuration (TypeScript) Source: https://github.com/nekzus/tokenly/blob/main/docs/public/llms-full.txt This code initializes the Tokenly library with a basic configuration, setting access and refresh token expiry times, enabling device fingerprinting, and setting a maximum number of devices. It demonstrates the basic setup required to start using Tokenly for token management. ```TypeScript import { Tokenly, TokenlyConfig } from 'tokenly'; // Basic configuration const config: TokenlyConfig = { accessTokenExpiry: '15m', refreshTokenExpiry: '7d', securityConfig: { enableFingerprint: true, maxDevices: 5, enableRateLimiting: true } }; const tokenly = new Tokenly(config); ``` -------------------------------- ### Install Tokenly via yarn Source: https://github.com/nekzus/tokenly/blob/main/docs/api/tokenly.md Install the Tokenly library using yarn. This command adds Tokenly as a project dependency. ```shell $ yarn add @nekzus/tokenly ``` -------------------------------- ### Install Tokenly via npm Source: https://github.com/nekzus/tokenly/blob/main/docs/api/tokenly.md Install the Tokenly library using npm. This command adds Tokenly as a project dependency. ```shell $ npm install @nekzus/tokenly ``` -------------------------------- ### Install Tokenly via pnpm Source: https://github.com/nekzus/tokenly/blob/main/docs/api/tokenly.md Install the Tokenly library using pnpm. This command adds Tokenly as a project dependency. ```shell $ pnpm add @nekzus/tokenly ``` -------------------------------- ### Installing Tokenly via npm Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Install the Tokenly library using npm. This command adds Tokenly as a project dependency. ```sh $ npm install @nekzus/tokenly ``` -------------------------------- ### Installing Tokenly via pnpm Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Install the Tokenly library using pnpm. This command adds Tokenly as a project dependency. ```sh $ pnpm add @nekzus/tokenly ``` -------------------------------- ### Installing Tokenly via yarn Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Install the Tokenly library using yarn. This command adds Tokenly as a project dependency. ```sh $ yarn add @nekzus/tokenly ``` -------------------------------- ### Installing Tokenly package Source: https://github.com/nekzus/tokenly/blob/main/README.md This command installs the Tokenly package from npm, allowing you to use it in your Node.js project. ```Bash npm install @nekzus/tokenly ``` -------------------------------- ### Building the Project with npm Source: https://github.com/nekzus/tokenly/blob/main/CONTRIBUTING.md This command compiles the TypeScript code into JavaScript and prepares the project for distribution. It is necessary to build the project after making changes to the source code. ```bash npm run build ``` -------------------------------- ### Running Tests with npm Source: https://github.com/nekzus/tokenly/blob/main/CONTRIBUTING.md This command executes the test suite for the Tokenly project. It ensures that existing functionality is working as expected and that new changes do not introduce regressions. ```bash npm test ``` -------------------------------- ### Installing cookie-parser dependency Source: https://github.com/nekzus/tokenly/blob/main/README.md This command installs the cookie-parser middleware, which is required for secure handling of refresh tokens with HttpOnly cookies. ```Bash npm install cookie-parser ``` -------------------------------- ### Production Setup for Tokenly Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Configure Tokenly for a production environment with stricter security settings, including shorter token expiry times, device fingerprinting, and secure cookie settings. ```ts const tokenly = new Tokenly({ accessTokenExpiry: '5m', refreshTokenExpiry: '1d', securityConfig: { enableFingerprint: true, enableBlacklist: true, maxDevices: 3, revokeOnSecurityBreach: true }, cookieConfig: { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'strict' } }); ``` -------------------------------- ### Initializing Tokenly with Device Fingerprinting Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/security.md This code snippet demonstrates how to initialize Tokenly with device fingerprinting enabled. It shows how to generate an access token with device context (user agent and IP address) and how to verify the token, handling potential fingerprint mismatches. ```typescript const tokenly = new Tokenly({ securityConfig: { enableFingerprint: true // Enabled by default } }); // Token generation with device context const token = tokenly.generateAccessToken( { userId: '123' }, undefined, { userAgent: req.headers['user-agent'], ip: getClientIP(req.headers) } ); ``` ```typescript try { const verified = tokenly.verifyAccessToken(token, { userAgent: req.headers['user-agent'], ip: getClientIP(req.headers) }); } catch (error) { // Handle invalid fingerprint } ``` -------------------------------- ### Running Tests with npm Source: https://github.com/nekzus/tokenly/blob/main/CONTRIBUTING.md This command executes the test suite for the Tokenly project. It ensures that existing functionality is working as expected and that new changes do not introduce regressions. All tests must pass before submitting a pull request. ```bash npm test ``` -------------------------------- ### Implementing Token Rotation Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/security.md This code snippet demonstrates how to implement token rotation with Tokenly. It configures the rotation settings, enables auto-rotation, and shows how to manually rotate tokens. ```typescript const tokenly = new Tokenly({ rotationConfig: { checkInterval: 60000, // Check every minute rotateBeforeExpiry: 300000, // Rotate 5 minutes before expiry maxRotationCount: 100 // Maximum rotation count } }); // Enable auto rotation tokenly.enableAutoRotation(); // Manual rotation const tokens = tokenly.rotateTokens(currentRefreshToken); ``` -------------------------------- ### Configuring Production Security Settings Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/security.md This code snippet provides recommended security settings for a production environment using Tokenly. It configures short-lived access tokens, daily refresh tokens, device fingerprinting, blacklisting, device limits, secure cookies, and token rotation. ```typescript const tokenly = new Tokenly({ accessTokenExpiry: '5m', // Short-lived access tokens refreshTokenExpiry: '1d', // Daily refresh securityConfig: { enableFingerprint: true, enableBlacklist: true, maxDevices: 3, revokeOnSecurityBreach: true }, cookieConfig: { httpOnly: true, secure: true, sameSite: 'strict' }, rotationConfig: { checkInterval: 60000, rotateBeforeExpiry: 300000, maxRotationCount: 100 } }); ``` -------------------------------- ### Initializing Tokenly with Configuration Options Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/advanced-concepts.md Initializes a new Tokenly instance with specified access token expiry, refresh token expiry, and security configurations. The security configuration includes enabling refresh token rotation and setting the rotation interval. This setup allows for secure and manageable token handling. ```typescript const tokenly = new Tokenly({ accessTokenExpiry: '15m', refreshTokenExpiry: '7d', securityConfig: { rotateRefreshToken: true, refreshTokenRotationInterval: '24h' } }) ``` -------------------------------- ### Monitoring Security Events Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/security.md This code snippet demonstrates how to monitor security-related activities using Tokenly's event listeners. It shows how to listen for invalid fingerprint detections, maximum device limits being reached, token revocations, and token expirations. ```typescript // Invalid fingerprint detection tokenly.on('invalid_fingerprint', (event: InvalidFingerprintEvent) => { console.log('Invalid fingerprint:', event); // { // token: string, // expectedFingerprint: string, // receivedFingerprint: string // } }); // Maximum devices reached tokenly.on('max_devices', (event: MaxDevicesEvent) => { console.log('Max devices reached:', event); // { // userId: string, // currentDevices: number, // maxDevices: number // } }); // Token revocation tokenly.on('token_revoked', (event: TokenRevokedEvent) => { console.log('Token revoked:', event); // { // token: string, // userId: string, // timestamp: number // } }); // Token expiring tokenly.on('token_expiring', (event: TokenExpiringEvent) => { console.log('Token expiring:', event); // { // token: string, // userId: string, // expiresIn: number // } }); ``` -------------------------------- ### Analyzing Token Security Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/security.md This code snippet shows how to analyze the security characteristics of a token using Tokenly. The analysis provides information about the algorithm, fingerprint status, expiration time, and strength of the token. ```typescript const analysis = tokenly.analyzeTokenSecurity(token); /* Returns: { algorithm: "HS512", hasFingerprint: boolean, expirationTime: Date, issuedAt: Date, timeUntilExpiry: number, strength: "strong" | "medium" | "weak" } */ ``` -------------------------------- ### Managing Device Limits Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/security.md This code snippet shows how to control the number of active devices per user using Tokenly. It configures the maximum number of devices and enables automatic token revocation on security breaches. ```typescript const tokenly = new Tokenly({ securityConfig: { maxDevices: 5, // Maximum devices per user revokeOnSecurityBreach: true // Auto-revoke on security issues } }); ``` -------------------------------- ### Handling Security Errors Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/security.md This code snippet demonstrates how to handle security-related errors when verifying access tokens with Tokenly. It shows how to catch specific error codes for invalid fingerprints and maximum device limits, and how to take appropriate actions such as logging alerts, revoking tokens, and notifying users. ```typescript try { const verified = tokenly.verifyAccessToken(token); } catch (error) { if (error.code === ErrorCode.INVALID_FINGERPRINT) { // Handle potential token theft await securityLogger.alert('Token theft attempt', error); await revokeAllUserTokens(userId); } if (error.code === ErrorCode.MAX_DEVICES_REACHED) { // Handle device limit exceeded await notifyUser(userId, 'Maximum devices reached'); } } ``` -------------------------------- ### Leveraging Type Inference for Complex Types Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/type-safety.md This snippet demonstrates how to leverage TypeScript's type inference to automatically infer complex types, reducing the need for explicit type annotations. It shows an example where the result of tokenly.verifyAccessToken is automatically typed based on the generic type parameter provided, making the code more concise and readable. ```typescript // Let TypeScript infer complex types const result = await tokenly.verifyAccessToken(token); // result.payload is automatically typed ``` -------------------------------- ### Configuring JWT Secrets and Token Expiry via Environment Variables Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/security.md This snippet demonstrates how to configure JWT secrets and token expiry settings using environment variables. JWT_SECRET_ACCESS and JWT_SECRET_REFRESH are used to set the secrets, while ACCESS_TOKEN_EXPIRY and REFRESH_TOKEN_EXPIRY define the token durations. If JWT secrets are not provided, Tokenly will generate random secrets that change on server restart, invalidating existing tokens. ```env JWT_SECRET_ACCESS=your_secure_access_token_secret JWT_SECRET_REFRESH=your_secure_refresh_token_secret ACCESS_TOKEN_EXPIRY=5m REFRESH_TOKEN_EXPIRY=1d ``` -------------------------------- ### Initializing Tokenly with basic configuration Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Initialize Tokenly with access and refresh token expiry times. This sets up the basic token management system. ```ts import { Tokenly } from '@nekzus/tokenly'; const tokenly = new Tokenly({ accessTokenExpiry: '15m', refreshTokenExpiry: '7d' }); ``` -------------------------------- ### Initializing Tokenly with Configuration Source: https://github.com/nekzus/tokenly/blob/main/docs/api/tokenly.md Initializes a new Tokenly instance with specified configurations for access token expiry, refresh token expiry, and security settings such as device fingerprinting, blacklisting, device limits, and security breach handling. ```typescript import { Tokenly } from '@nekzus/tokenly'; // Initialize with configuration const tokenly = new Tokenly({ accessTokenExpiry: '15m', refreshTokenExpiry: '7d', securityConfig: { enableFingerprint: true, enableBlacklist: true, maxDevices: 5, revokeOnSecurityBreach: true } }); ``` -------------------------------- ### Tokenly Initialization with Security Configuration Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Demonstrates initializing the Tokenly instance with a custom security configuration. It enables fingerprinting and blacklisting, sets the maximum number of devices to 5, and enables auto-revocation on security breaches. ```typescript const tokenly = new Tokenly({ securityConfig: { enableFingerprint: true, // default: true enableBlacklist: true, // default: true maxDevices: 5, // default: 5 revokeOnSecurityBreach: true // default: true } }); ``` -------------------------------- ### Configuring Device Fingerprinting Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Configure Tokenly to enable device fingerprinting and blacklist features for enhanced security. Includes a security event listener for invalid fingerprints. ```ts const tokenly = new Tokenly({ securityConfig: { enableFingerprint: true, enableBlacklist: true, maxDevices: 5, revokeOnSecurityBreach: true } }); // Monitor security events tokenly.on('invalid_fingerprint', async (event) => { console.log('Potential token theft detected:', event); await notifySecurityTeam(event); }); ``` -------------------------------- ### Initializing Tokenly with Express Source: https://github.com/nekzus/tokenly/blob/main/README.md This code snippet demonstrates how to initialize Tokenly with Express, including loading environment variables, setting up middleware, and generating access tokens with device fingerprinting. ```TypeScript import { getClientIP, Tokenly } from "@nekzus/tokenly"; import cookieParser from "cookie-parser"; import dotenv from "dotenv"; // Load environment variables dotenv.config(); // Initialize Express const app = express(); // Required middleware for refresh tokens app.use(cookieParser()); // Initialize Tokenly const auth = new Tokenly({ accessTokenExpiry: "15m", refreshTokenExpiry: "7d", securityConfig: { enableFingerprint: true, maxDevices: 5, }, }); // Generate token with fingerprinting app.post("/login", (req, res) => { const token = auth.generateAccessToken( { userId: "123", role: "user" }, undefined, { userAgent: req.headers["user-agent"] || "", ip: getClientIP(req.headers), }, ); res.json({ token }); }); ``` -------------------------------- ### Production Tokenly Configuration Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Demonstrates a production-ready configuration for the Tokenly instance. It includes settings for access token expiry, refresh token expiry, security configuration, cookie configuration, and rotation configuration, optimized for a secure production environment. ```typescript const tokenly = new Tokenly({ accessTokenExpiry: '15m', refreshTokenExpiry: '7d', securityConfig: { enableFingerprint: true, enableBlacklist: true, maxDevices: 5, revokeOnSecurityBreach: true }, cookieConfig: { httpOnly: true, secure: true, sameSite: 'strict', path: '/' }, rotationConfig: { checkInterval: 60000, rotateBeforeExpiry: 300000, maxRotationCount: 100 } }); ``` -------------------------------- ### Development Tokenly Configuration Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Demonstrates a development configuration for the Tokenly instance. It includes settings for access token expiry, refresh token expiry, and security configuration, optimized for a more lenient development environment. ```typescript const tokenly = new Tokenly({ accessTokenExpiry: '1h', // Longer for testing refreshTokenExpiry: '7d', securityConfig: { enableFingerprint: true, enableBlacklist: true, maxDevices: 10 // More lenient for testing } }); ``` -------------------------------- ### Next.js Initial Props Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet shows how to use `getInitialProps` to fetch data on both the server and client side. This is an older approach and is generally not recommended for new projects. Use `getServerSideProps` or `getStaticProps` instead. ```javascript FileName.getInitialProps = async (ctx) => { return { } } ``` -------------------------------- ### Initializing Tokenly with Security Configuration Source: https://github.com/nekzus/tokenly/blob/main/docs/api/utils/device-helper.md Configures Tokenly's device management features, such as enabling device fingerprinting and token blacklisting, setting the maximum number of devices per user, and enabling automatic revocation on security breaches. These settings are applied when the Tokenly instance is created. ```typescript import { Tokenly } from 'tokenly' const tokenly = new Tokenly({ securityConfig: { enableFingerprint: true, // Enable device fingerprinting (default: true) enableBlacklist: true, // Enable token blacklisting (default: true) maxDevices: 5, // Maximum devices per user (default: 5) revokeOnSecurityBreach: true // Auto-revoke on security issues (default: true) } }) ``` -------------------------------- ### Token Generation and Verification with Tokenly Source: https://github.com/nekzus/tokenly/blob/main/docs/public/llms-full.txt This TypeScript code demonstrates how to generate and verify access tokens using the Tokenly library. It initializes Tokenly with a security configuration that enables fingerprinting and sets the maximum number of devices. The code then generates an access token for a user and verifies it using the raw token and user agent/IP address. ```typescript import { Tokenly } from 'tokenly'; const tokenly = new Tokenly({ securityConfig: { enableFingerprint: true, maxDevices: 5 } }); // Access token generation const accessToken = tokenly.generateAccessToken( { userId: '123' }, undefined, { userAgent: 'Mozilla/5.0', ip: '192.168.1.1' } ); // Token verification const verified = tokenly.verifyAccessToken( accessToken.raw, { userAgent: 'Mozilla/5.0', ip: '192.168.1.1' } ); ``` -------------------------------- ### Tokenly Initialization with Cookie Configuration Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Demonstrates initializing the Tokenly instance with a custom cookie configuration. It sets httpOnly to true, secure based on the environment, sameSite to strict, path to '/', and maxAge to 7 days. ```typescript const tokenly = new Tokenly({ cookieConfig: { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'strict', path: '/', maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days } }); ``` -------------------------------- ### Basic Tokenly Initialization Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Demonstrates basic initialization of the Tokenly instance with custom access token and refresh token expiry times. The accessTokenExpiry is set to 15 minutes and refreshTokenExpiry is set to 7 days. ```typescript const tokenly = new Tokenly({ accessTokenExpiry: '15m', // 15 minutes (default) refreshTokenExpiry: '7d', // 7 days (default) }); ``` -------------------------------- ### Integrating Tokenly with Express Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Integrate Tokenly with an Express application for JWT token management. Includes middleware for parsing JSON and cookies, and endpoints for login and token refresh. ```ts import express from 'express'; import { Tokenly, getClientIP } from '@nekzus/tokenly'; import cookieParser from 'cookie-parser'; const app = express(); app.use(express.json()); app.use(cookieParser()); const tokenly = new Tokenly({ accessTokenExpiry: '15m', refreshTokenExpiry: '7d', securityConfig: { enableFingerprint: true, enableBlacklist: true, maxDevices: 5, revokeOnSecurityBreach: true } }); // Login endpoint app.post('/login', async (req, res) => { try { const { username, password } = req.body; const user = await authenticate(username, password); const accessToken = tokenly.generateAccessToken( { userId: user.id }, undefined, { userAgent: req.headers['user-agent'], ip: getClientIP(req.headers) } ); const refreshToken = tokenly.generateRefreshToken({ userId: user.id }); if (refreshToken.cookieConfig) { res.cookie( refreshToken.cookieConfig.name, refreshToken.cookieConfig.value, refreshToken.cookieConfig.options ); } res.json({ token: accessToken.raw }); } catch (error) { res.status(401).json({ error: 'Authentication failed' }); } }); // Token refresh endpoint app.post('/refresh', async (req, res) => { try { const oldRefreshToken = req.cookies.refresh_token; const tokens = tokenly.rotateTokens(oldRefreshToken); if (tokens.refreshToken.cookieConfig) { res.cookie( tokens.refreshToken.cookieConfig.name, tokens.refreshToken.cookieConfig.value, tokens.refreshToken.cookieConfig.options ); } res.json({ token: tokens.accessToken.raw }); } catch (error) { res.status(401).json({ error: 'Invalid refresh token' }); } }); // Protected route example app.get('/protected', authenticateToken, (req, res) => { res.json({ message: 'Protected data' }); }); ``` -------------------------------- ### Tokenly Initialization with Rotation Configuration Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Demonstrates initializing the Tokenly instance with a custom rotation configuration. It sets the check interval to 60000ms, rotate before expiry to 300000ms, and maximum rotation count to 100. ```typescript const tokenly = new Tokenly({ rotationConfig: { checkInterval: 60000, // Check every minute rotateBeforeExpiry: 300000, // Rotate 5 minutes before expiry maxRotationCount: 100 // Maximum 100 rotations } }); ``` -------------------------------- ### Next.js Page with Static Props Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet demonstrates how to fetch data at build time using `getStaticProps`. The fetched data is then passed as props to the page component. This is suitable for content that doesn't change frequently. ```javascript const FileName = ({}) => { return
} export const getStaticProps = async (ctx) => { return { props: {}, } } export default FileName ``` -------------------------------- ### Tokenly Event System Source: https://github.com/nekzus/tokenly/blob/main/docs/api/tokenly.md Demonstrates how to subscribe to Tokenly's event system to listen for events such as token revocation, device limit reached, invalid fingerprint, and token expiring. ```typescript // Token revocation tokenly.on('token_revoked', (event: TokenRevokedEvent) => { console.log('Token revoked:', event); }); // Device limit reached tokenly.on('max_devices', (event: MaxDevicesEvent) => { console.log('Max devices reached:', event); }); // Invalid fingerprint tokenly.on('invalid_fingerprint', (event: InvalidFingerprintEvent) => { console.log('Invalid fingerprint:', event); }); // Token expiring tokenly.on('token_expiring', (event: TokenExpiringEvent) => { console.log('Token expiring:', event); }); ``` -------------------------------- ### Initializing Tokenly with Type-Safe Configuration Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/type-safety.md This snippet demonstrates how to initialize Tokenly with a type-safe configuration using TypeScript. It imports necessary types and defines a configuration object with specific properties like accessTokenExpiry, refreshTokenExpiry, and securityConfig. The Tokenly instance is then created using this configuration. ```typescript import { Tokenly, TokenlyConfig, TokenPayload } from '@nekzus/tokenly'; // Basic configuration with type checking const config: TokenlyConfig = { accessTokenExpiry: '15m', refreshTokenExpiry: '7d', securityConfig: { enableFingerprint: true, maxDevices: 5 } }; // Initialize with type-safe config const tokenly = new Tokenly(config); ``` -------------------------------- ### Next.js Custom App Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet shows how to create a custom `_app.js` file to wrap all pages in your application. This is useful for persisting layout between page changes, keeping state when navigating pages, and adding global styles. ```javascript export default function MyApp({ Component, pageProps }) { return } ``` -------------------------------- ### Next.js Image Component Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet demonstrates how to use the `next/image` component for optimized image loading. It requires the `src` and `alt` attributes to be specified. ```javascript ``` -------------------------------- ### Login Implementation with Token Generation (TypeScript) Source: https://github.com/nekzus/tokenly/blob/main/docs/public/llms-full.txt This code snippet demonstrates the login implementation using Tokenly. It generates access and refresh tokens based on user credentials and device information, then sets these tokens as HttpOnly cookies in the response. Error handling is included to manage authentication failures. ```TypeScript // Login implementation async function handleLogin(credentials: Credentials) { try { // Generate tokens const { accessToken, refreshToken } = await tokenly.generateTokenPair({ userId: user.id, roles: user.roles, deviceInfo: { userAgent: req.headers['user-agent'], ip: req.ip } }); // Set cookies tokenly.setTokenCookies(res, accessToken, refreshToken); return { success: true, user: user.profile }; } catch (error) { tokenly.handleAuthError(error); } } ``` -------------------------------- ### Next.js Page with Static Paths Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet shows how to define dynamic routes using `getStaticPaths`. It specifies the possible values for a dynamic route parameter. This is used in conjunction with `getStaticProps` to generate static pages for each path. ```javascript const FileName = ({}) => { return
} export const getStaticPaths = async () => { return { paths: [], fallback: false, } } export default FileName ``` -------------------------------- ### Environment Variables Configuration (ENV) Source: https://github.com/nekzus/tokenly/blob/main/docs/public/llms-full.txt This code block defines the environment variables required for configuring Tokenly, including JWT secrets, token expiration times, security settings, and optional Redis configuration. These variables are used to customize Tokenly's behavior and security features. ```ENV # Required settings JWT_SECRET_ACCESS=your-secure-access-secret JWT_SECRET_REFRESH=your-secure-refresh-secret # Token expiration ACCESS_TOKEN_EXPIRY=15m REFRESH_TOKEN_EXPIRY=7d # Security settings ENABLE_FINGERPRINT=true MAX_DEVICES=5 RATE_LIMIT_WINDOW=15m RATE_LIMIT_MAX_REQUESTS=100 # Redis configuration (optional) REDIS_URL=redis://localhost:6379 REDIS_PREFIX=tokenly: ``` -------------------------------- ### Next.js Static Paths Only Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet demonstrates the usage of `getStaticPaths` without a corresponding page component. This is useful when you only need to define dynamic routes and don't need to render a page. ```javascript export const getStaticPaths = async () => { return { paths: [], fallback: false, } } ``` -------------------------------- ### Next.js Static Props Only Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet demonstrates the usage of `getStaticProps` without a corresponding page component. This is useful when you only need to fetch data at build time and don't need to render a page. ```javascript export const getStaticProps = async (ctx) => { return { props: {}, } } ``` -------------------------------- ### Creating a Basic Next.js Page Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet demonstrates the basic structure of a Next.js page component. It defines a functional component that returns a simple div element. This is the foundation for building more complex pages in a Next.js application. ```javascript const FileName = ({}) => { return
} export default FileName ``` -------------------------------- ### Generating Access Token with Device Fingerprinting Source: https://github.com/nekzus/tokenly/blob/main/docs/api/tokenly.md Generates an access token with device fingerprinting enabled, using the user agent and IP address from the request headers to create a unique device context. ```typescript const token = tokenly.generateAccessToken( { userId: '123' }, undefined, { userAgent: req.headers['user-agent'], ip: req.ip } ); ``` -------------------------------- ### Complete Tokenly Configuration Interface (TypeScript) Source: https://github.com/nekzus/tokenly/blob/main/docs/public/llms-full.txt This code defines the complete configuration interface for Tokenly, including token settings, cookie options, security configuration, cache configuration, and error handling. It provides a comprehensive overview of all configurable options available in the Tokenly library. ```TypeScript interface TokenlyConfig { // Token settings accessTokenExpiry?: string; refreshTokenExpiry?: string; tokenAlgorithm?: 'HS256' | 'HS384' | 'HS512'; // Cookie options cookieOptions?: { secure?: boolean; sameSite?: 'strict' | 'lax' | 'none'; domain?: string; path?: string; }; // Security configuration securityConfig?: { enableFingerprint?: boolean; maxDevices?: number; enableRateLimiting?: boolean; rateLimitWindow?: string; maxRequestsPerWindow?: number; enableAuditLog?: boolean; }; // Cache configuration cacheConfig?: { enable?: boolean; provider?: 'redis' | 'memory'; ttl?: string; }; // Error handling errorConfig?: { verbose?: boolean; customErrors?: Record; }; } ``` -------------------------------- ### Security Event Handling Source: https://github.com/nekzus/tokenly/blob/main/README.md This code snippet demonstrates how to listen for security events such as invalid fingerprint detection and device limit reached, logging relevant information. ```TypeScript // Invalid Fingerprint Detection auth.on("invalid_fingerprint", (event) => { console.log(`Security Alert: Invalid fingerprint detected`); console.log(`User: ${event.userId}`); console.log(`IP: ${event.context.ip}`); }); // Device Limit Reached auth.on("max_devices_reached", (event) => { console.log(`Device limit reached for user: ${event.userId}`); console.log(`Current devices: ${event.context.currentDevices}`); }); ``` -------------------------------- ### Security Configuration Interface Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Defines the SecurityConfig interface, which includes options for enabling device fingerprinting, enabling token blacklisting, setting the maximum number of devices per user, and enabling auto-revocation on security issues. These settings enhance the security of the Tokenly instance. ```typescript interface SecurityConfig { enableFingerprint: boolean; // Enable device fingerprinting enableBlacklist: boolean; // Enable token blacklisting maxDevices: number; // Max devices per user revokeOnSecurityBreach?: boolean; // Auto-revoke on security issues } ``` -------------------------------- ### Next.js API Route Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet shows how to create a Next.js API route. API routes allow you to create serverless functions that can be used to handle API requests. They are defined in the `pages/api` directory. ```javascript export default async function handler(req, res) { } ``` -------------------------------- ### Basic Tokenly Configuration Source: https://github.com/nekzus/tokenly/blob/main/README.md This code snippet shows a basic configuration of Tokenly, setting the access token expiry to 15 minutes, refresh token expiry to 7 days, enabling device tracking, and setting the maximum number of devices per user to 5. ```TypeScript const auth = new Tokenly({ accessTokenExpiry: "15m", // 15 minutes refreshTokenExpiry: "7d", // 7 days securityConfig: { enableFingerprint: true, // Enable device tracking maxDevices: 5, // Max devices per user }, }); ``` -------------------------------- ### Tokenly Configuration Interface Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Defines the TokenlyConfig interface, which includes options for access token expiry, refresh token expiry, security configuration, rotation configuration, and cookie configuration. These options allow customization of the Tokenly instance's behavior. ```typescript interface TokenlyConfig { accessTokenExpiry?: string; refreshTokenExpiry?: string; securityConfig?: SecurityConfig; rotationConfig?: RotationConfig; cookieConfig?: CookieConfig; } ``` -------------------------------- ### Tokenly Configuration Interface Source: https://github.com/nekzus/tokenly/blob/main/docs/public/llms-full.txt This TypeScript interface defines the configuration options for the Tokenly library. It includes properties for setting access and refresh token expiry times, cookie options, and security configurations such as enabling fingerprinting and setting the maximum number of devices. ```typescript interface TokenlyConfig { accessTokenExpiry?: string; refreshTokenExpiry?: string; cookieOptions?: TokenlyOptions; securityConfig?: { enableFingerprint?: boolean; maxDevices?: number; } } ``` -------------------------------- ### Token Generation API Reference Source: https://github.com/nekzus/tokenly/blob/main/README.md This code snippet shows the API reference for generating access tokens using Tokenly, including the payload, options, and context parameters. ```TypeScript const token = auth.generateAccessToken( payload: { userId: string; role: string }, options?: { fingerprint?: string; deviceId?: string }, context?: { userAgent: string; ip: string } ); ``` -------------------------------- ### Configuring Token Rotation Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Configure Tokenly to enable token rotation with specific intervals, expiry thresholds, and maximum rotation counts. This enhances security by periodically refreshing tokens. ```ts const tokenly = new Tokenly({ rotationConfig: { checkInterval: 60000, // Check every minute rotateBeforeExpiry: 300000, // Rotate 5 minutes before expiry maxRotationCount: 100 // Maximum rotation count } }); ``` -------------------------------- ### getClientIP Usage with X-Real-IP Source: https://github.com/nekzus/tokenly/blob/main/docs/api/utils/ip-helper.md Demonstrates how to use the getClientIP function with the X-Real-IP header. It creates a headers object with the X-Real-IP field set to '192.168.1.1' and calls getClientIP with these headers, which returns '192.168.1.1'. ```typescript import { getClientIP } from 'tokenly' // Using X-Real-IP const headers = { 'x-real-ip': '192.168.1.1' } getClientIP(headers) // Returns: '192.168.1.1' ``` -------------------------------- ### Next.js Page with Server-Side Props Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet shows how to fetch data on the server side using `getServerSideProps`. The fetched data is then passed as props to the page component. This is useful for dynamic content that needs to be updated on every request. ```javascript const FileName = ({}) => { return
} export const getServerSideProps = async (ctx) => { return { props: {} } } export default FileName ``` -------------------------------- ### Token Verification and Refresh (TypeScript) Source: https://github.com/nekzus/tokenly/blob/main/docs/public/llms-full.txt This code snippet shows how to verify an access token using Tokenly, including handling token expiration and refreshing the token if necessary. It checks the token's validity and device fingerprint, and provides a mechanism to refresh the token if it has expired. ```TypeScript // Token verification async function verifyAuth(req: Request, res: Response) { try { const verified = await tokenly.verifyAccessToken(req.cookies.accessToken, { fingerprint: req.headers['x-device-fingerprint'] }); return verified.payload; } catch (error) { if (tokenly.isTokenExpiredError(error)) { return await tokenly.handleTokenRefresh(req, res); } throw error; } } ``` -------------------------------- ### Next.js Server-Side Props Only Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet demonstrates the usage of `getServerSideProps` without a corresponding page component. This is useful when you only need to fetch data on the server side and don't need to render a page. ```javascript export const getServerSideProps = async (ctx) => { return { props: {} } } ``` -------------------------------- ### Authentication Middleware for Express Source: https://github.com/nekzus/tokenly/blob/main/docs/guide/getting-started.md Middleware function to authenticate JWT tokens in Express routes. Verifies the token and attaches the decoded user information to the request object. ```ts function authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) { return res.status(401).json({ error: 'No token provided' }); } try { const decoded = tokenly.verifyAccessToken(token); req.user = decoded; next(); } catch (error) { return res.status(403).json({ error: 'Invalid token' }); } } ``` -------------------------------- ### Verifying Access Token with Device Context Source: https://github.com/nekzus/tokenly/blob/main/docs/api/utils/device-helper.md Verifies an access token by validating the device fingerprint against the user agent and IP address provided in the request headers. An error is thrown if the device fingerprint does not match the provided context. ```typescript // Verify token with device context const verified = tokenly.verifyAccessToken(token, { userAgent: request.headers['user-agent'], ip: request.ip }) // Throws error if device fingerprint doesn't match ``` -------------------------------- ### Rotation Configuration Interface Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Defines the RotationConfig interface, which includes options for setting the check interval, rotate before expiry time, and maximum rotation count. These settings control how token rotation is handled by the Tokenly instance. ```typescript interface RotationConfig { checkInterval?: number; // Check interval in milliseconds rotateBeforeExpiry?: number; // Time before expiry to rotate maxRotationCount?: number; // Maximum number of rotations } ``` -------------------------------- ### Handling Tokenly Errors Source: https://github.com/nekzus/tokenly/blob/main/docs/api/tokenly.md Illustrates how to catch and handle specific Tokenly errors such as token expiration, invalid token, fingerprint mismatch, and max devices reached. ```typescript try { const verified = tokenly.verifyAccessToken(token); } catch (error) { if (error instanceof TokenlyError) { switch (error.code) { case 'TOKEN_EXPIRED': case 'TOKEN_INVALID': case 'FINGERPRINT_MISMATCH': case 'MAX_DEVICES_REACHED': // Handle specific errors break; } } } ``` -------------------------------- ### Next.js Custom Document Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet demonstrates how to create a custom `_document.js` file to customize the HTML document structure. This is useful for modifying the `` and `` tags, setting up scripts, and controlling browser rendering. ```javascript import Document, { Html, Head, Main, NextScript } from 'next/document' class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx) return { ...initialProps } } render() { return (
); } } export default MyDocument ``` -------------------------------- ### Next.js Image Component Source: https://github.com/nekzus/tokenly/blob/main/docs/typescript-snippets.md Shows the usage of the Next.js Image component. The `src` and `alt` attributes must be defined. ```typescript ``` -------------------------------- ### Advanced Tokenly Security Configuration Source: https://github.com/nekzus/tokenly/blob/main/README.md This code snippet demonstrates an advanced security configuration of Tokenly, setting shorter token lifetimes, enabling token revocation, and setting a strict device limit. ```TypeScript const auth = new Tokenly({ accessTokenExpiry: "5m", // Shorter token life refreshTokenExpiry: "1d", // Daily refresh required securityConfig: { enableFingerprint: true, // Required for device tracking enableBlacklist: true, // Enable token revocation maxDevices: 3, // Strict device limit }, }); ``` -------------------------------- ### IP Detection Helper API Reference Source: https://github.com/nekzus/tokenly/blob/main/README.md This code snippet shows the API reference for the getClientIP helper function, which detects the client's IP address from the request headers. ```TypeScript import { getClientIP } from "@nekzus/tokenly"; const clientIP = getClientIP(headers, defaultIP); ``` -------------------------------- ### getClientIP Usage with X-Forwarded-For Source: https://github.com/nekzus/tokenly/blob/main/docs/api/utils/ip-helper.md Demonstrates how to use the getClientIP function with the X-Forwarded-For header. It creates a proxyHeaders object with the X-Forwarded-For field set to '192.168.1.1, 10.0.0.1' and calls getClientIP with these headers, which returns '192.168.1.1'. ```typescript // Using X-Forwarded-For const proxyHeaders = { 'x-forwarded-for': '192.168.1.1, 10.0.0.1' } getClientIP(proxyHeaders) // Returns: '192.168.1.1' ``` -------------------------------- ### Next.js Middleware Source: https://github.com/nekzus/tokenly/blob/main/docs/javascript-snippets.md This snippet demonstrates how to create Next.js middleware. Middleware allows you to run code before a request is completed. You can then modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly. ```javascript import { NextResponse } from 'next/server' export async function middleware(request) { } export const config = { matcher: '/about/:path*', } ``` -------------------------------- ### Next.js Page with Static Props Source: https://github.com/nekzus/tokenly/blob/main/docs/typescript-snippets.md Implements a Next.js page component with static data fetching using `getStaticProps`. It defines a page component and a `getStaticProps` function that fetches data at build time. The fetched data is then passed as props to the page component. ```typescript import { NextPage, GetStaticProps } from 'next' interface Props {} const FileName: NextPage = ({}) => { return
} export const getStaticProps: GetStaticProps = async (ctx) => { return { props: {}, } } export default FileName ``` -------------------------------- ### Next.js Page with Static Paths Source: https://github.com/nekzus/tokenly/blob/main/docs/typescript-snippets.md Defines a Next.js page component with static path generation using `getStaticPaths`. It defines a page component and a `getStaticPaths` function that specifies the possible paths for the page. This is used for dynamic routes that are known at build time. ```typescript import { NextPage, GetStaticPaths } from 'next' interface Props {} const FileName: NextPage = ({}) => { return
} export const getStaticPaths: GetStaticPaths = async () => { return { paths: [], fallback: false, } } export default FileName ``` -------------------------------- ### Cookie Configuration Interface Source: https://github.com/nekzus/tokenly/blob/main/docs/api/configuration.md Defines the CookieConfig interface, which includes options for setting secure, httpOnly, sameSite, domain, path, and maxAge attributes for cookies. These settings control how cookies are handled by the Tokenly instance. ```typescript interface CookieConfig { secure?: boolean; httpOnly?: boolean; sameSite?: 'strict' | 'lax' | 'none'; domain?: string; path?: string; maxAge?: number; } ``` -------------------------------- ### getClientIP Usage with Custom Default IP Source: https://github.com/nekzus/tokenly/blob/main/docs/api/utils/ip-helper.md Demonstrates how to use the getClientIP function with a custom default IP address. It calls getClientIP with an empty object and the default IP set to '127.0.0.1', which returns '127.0.0.1'. ```typescript // Custom default IP getClientIP({}, '127.0.0.1') // Returns: '127.0.0.1' ``` -------------------------------- ### getClientIP Usage with No Valid Headers Source: https://github.com/nekzus/tokenly/blob/main/docs/api/utils/ip-helper.md Demonstrates how the getClientIP function handles the case when no valid headers are provided. It calls getClientIP with an empty object, which returns the default IP address '0.0.0.0'. ```typescript // No valid headers getClientIP({}) // Returns: '0.0.0.0' ``` -------------------------------- ### Generating Access and Refresh Tokens in Express Source: https://github.com/nekzus/tokenly/blob/main/docs/api/tokenly.md This Express route handles user login, authenticates the user, generates access and refresh tokens using Tokenly, sets the refresh token as an HttpOnly cookie, and returns the access token. ```typescript // Express example app.post('/login', async (req, res) => { const { username, password } = req.body; const user = await authenticate(username, password); // Generate access token with device context const accessToken = tokenly.generateAccessToken( { userId: user.id }, undefined, { userAgent: req.headers['user-agent'], ip: req.ip } ); // Generate refresh token const refreshToken = tokenly.generateRefreshToken({ userId: user.id }); // Set refresh token cookie if configured if (refreshToken.cookieConfig) { res.cookie( refreshToken.cookieConfig.name, refreshToken.cookieConfig.value, refreshToken.cookieConfig.options ); } res.json({ token: accessToken.raw }); }); ``` -------------------------------- ### Headers Type Definition Source: https://github.com/nekzus/tokenly/blob/main/docs/api/utils/ip-helper.md Defines the Headers interface, which specifies the structure of the HTTP headers object. It includes optional fields for 'x-real-ip' and 'x-forwarded-for', as well as a generic index signature for other header fields. ```typescript interface Headers { 'x-real-ip'?: string 'x-forwarded-for'?: string [key: string]: string | string[] | undefined } ``` -------------------------------- ### Analyzing Token Security Source: https://github.com/nekzus/tokenly/blob/main/docs/api/utils/device-helper.md Analyzes the security of a token, including the algorithm used, the presence of a device fingerprint, expiration time, issued at time, time until expiry, and strength. This analysis provides insights into the token's security characteristics. ```typescript const analysis = tokenly.analyzeTokenSecurity(token) console.log(analysis) /* Output: { algorithm: "HS512", hasFingerprint: true, expirationTime: Date, issuedAt: Date, timeUntilExpiry: number, strength: "strong" | "medium" | "weak" } */ ``` -------------------------------- ### Next.js Initial Props Function Source: https://github.com/nekzus/tokenly/blob/main/docs/typescript-snippets.md Defines a `getInitialProps` function for fetching data in Next.js. This function is used to fetch data on both the server and the client, but is now discouraged in favor of `getStaticProps` or `getServerSideProps`. ```typescript FileName.getInitialProps = async (ctx) => { return { } } ```