npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@epicdm/flowstate-auth-core

v1.0.0

Published

Core authentication business logic and interfaces for FlowState

Readme

@epic-flow/flowstate-auth-core

Core authentication business logic and interfaces for FlowState.

Features

  • JWT Token Management: RS256-based access and refresh tokens
  • API Token Generation: Secure service account tokens with bcrypt hashing
  • Key Management: RS256 key pair generation and import utilities
  • Storage Adapters: RxDB storage adapter for authentication data
  • TypeScript: Full type safety with comprehensive type definitions

Installation

yarn add @epic-flow/flowstate-auth-core

Quick Start

JWT Token Management

import { TokenManager, generateKeyPair } from '@epic-flow/flowstate-auth-core'

// Generate RS256 key pair
const keys = await generateKeyPair()

// Initialize TokenManager
const manager = await TokenManager.create({
  privateKey: keys.privateKey,
  publicKey: keys.publicKey,
  accessTokenTTL: 900,      // 15 minutes
  refreshTokenTTL: 2592000  // 30 days
})

// Create access token
const accessToken = await manager.createAccessToken({
  userId: 'user-123',
  email: '[email protected]',
  domainId: 'domain-1',
  orgId: 'org-1',
  scopes: ['read', 'write']
})

// Verify access token
const payload = await manager.verifyAccessToken(accessToken)
console.log(payload.userId) // 'user-123'

// Create refresh token
const refreshToken = await manager.createRefreshToken({
  userId: 'user-123',
  sessionId: 'session-abc',
  domainId: 'domain-1'
})

// Verify refresh token
const refreshPayload = await manager.verifyRefreshToken(refreshToken)

API Token Management

import { generateAPIToken, hashAPIToken, verifyAPIToken } from '@epic-flow/flowstate-auth-core'

// Generate API token
const token = generateAPIToken('live')  // Format: epic_live_{32_chars}
// or for test environment
const testToken = generateAPIToken('test')  // Format: epic_test_{32_chars}

// Hash token for storage (bcrypt with 10 rounds)
const hash = await hashAPIToken(token)

// Store hash in database, return token to user (one-time display)

// Later: verify token against hash
const isValid = await verifyAPIToken(token, hash)
if (isValid) {
  // Authenticate request
}

API Reference

Key Management

generateKeyPair(): Promise<{ privateKey: string, publicKey: string }>

Generates an RS256 key pair for JWT signing.

Returns: Promise resolving to PEM-formatted private and public keys.

Example:

const { privateKey, publicKey } = await generateKeyPair()

importKeys(config: JWTConfig): Promise<{ privateKeyObject: KeyLike, publicKeyObject: KeyLike, config: JWTConfig }>

Imports and validates PEM-formatted keys.

Parameters:

  • config: JWT configuration with private/public keys and TTL settings

Returns: Promise resolving to imported key objects and validated config.

Throws: Error if keys are invalid or malformed.

loadKeysFromEnv(): JWTConfig

Loads JWT configuration from environment variables.

Environment Variables:

  • JWT_PRIVATE_KEY: PEM-formatted RS256 private key
  • JWT_PUBLIC_KEY: PEM-formatted RS256 public key
  • JWT_ACCESS_TOKEN_TTL: Access token TTL in seconds (default: 900)
  • JWT_REFRESH_TOKEN_TTL: Refresh token TTL in seconds (default: 2592000)

Returns: JWT configuration object.

Throws: Error if required environment variables are missing.

TokenManager

TokenManager.create(config: JWTConfig): Promise<TokenManager>

Factory method to create a new TokenManager instance.

Parameters:

  • config: JWT configuration with keys and TTL settings

Returns: Promise resolving to initialized TokenManager instance.

createAccessToken(payload: AccessTokenPayload): Promise<string>

Creates a signed JWT access token.

Parameters:

  • payload: Access token payload with userId, email, domainId, orgId, and optional scopes

Returns: Promise resolving to JWT token string.

verifyAccessToken(token: string): Promise<AccessTokenPayload>

Verifies and decodes a JWT access token.

Parameters:

  • token: JWT token string to verify

Returns: Promise resolving to decoded access token payload.

Throws: Error if token is invalid, expired, or signature verification fails.

createRefreshToken(payload: RefreshTokenPayload): Promise<string>

Creates a signed JWT refresh token.

Parameters:

  • payload: Refresh token payload with userId, sessionId, and domainId

Returns: Promise resolving to JWT token string.

verifyRefreshToken(token: string): Promise<RefreshTokenPayload>

Verifies and decodes a JWT refresh token.

Parameters:

  • token: JWT token string to verify

Returns: Promise resolving to decoded refresh token payload.

Throws: Error if token is invalid, expired, or signature verification fails.

API Token Functions

generateAPIToken(environment: 'live' | 'test'): string

Generates a secure API token with environment-specific prefix.

Parameters:

  • environment: Token environment ('live' or 'test')

Returns: API token string in format epic_{env}_{32_random_chars}.

hashAPIToken(token: string): Promise<string>

Hashes an API token using bcrypt with 10 rounds.

Parameters:

  • token: API token string to hash

Returns: Promise resolving to bcrypt hash string.

verifyAPIToken(token: string, hash: string): Promise<boolean>

Verifies an API token against its stored hash.

Parameters:

  • token: API token string to verify
  • hash: Stored bcrypt hash

Returns: Promise resolving to true if token matches hash, false otherwise.

Configuration

JWT Configuration

interface JWTConfig {
  privateKey: string           // PEM-formatted RS256 private key
  publicKey: string            // PEM-formatted RS256 public key
  accessTokenTTL: number       // Access token TTL in seconds (default: 900)
  refreshTokenTTL: number      // Refresh token TTL in seconds (default: 2592000)
  previousPublicKeys?: string[] // Optional: previous public keys for key rotation
}

Token Payloads

interface AccessTokenPayload {
  userId: string
  email: string
  domainId: string
  orgId: string
  scopes?: string[]
}

interface RefreshTokenPayload {
  userId: string
  sessionId: string
  domainId: string
}

Security Best Practices

Key Management

  1. Generate strong keys: Use generateKeyPair() to generate cryptographically secure RS256 keys
  2. Store keys securely: Use environment variables or secure vaults (1Password, AWS Secrets Manager)
  3. Never commit keys: Add keys to .gitignore and use environment-specific configuration
  4. Rotate keys regularly: Implement key rotation using previousPublicKeys for zero-downtime rotation

Token Management

  1. Short-lived access tokens: Use default 15-minute TTL for access tokens
  2. One-time refresh tokens: Implement token rotation to prevent replay attacks
  3. Secure token storage: Store refresh tokens in httpOnly cookies or secure storage
  4. Validate all claims: Always verify userId, domainId, and orgId match expected values

API Tokens

  1. Display once: Show API tokens to users only once during generation
  2. Hash before storage: Always use hashAPIToken() before storing in database
  3. Use environment prefixes: Distinguish live and test tokens with epic_live_ and epic_test_ prefixes
  4. Implement rate limiting: Add rate limiting to API endpoints using API tokens

Generate Keys for Development

Use the included script to generate RS256 keys:

yarn generate-keys

This will output a private and public key that you can add to your .env file:

JWT_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
JWT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"
JWT_ACCESS_TOKEN_TTL=900
JWT_REFRESH_TOKEN_TTL=2592000

Testing

# Run all tests
yarn test

# Run tests in watch mode
yarn test:watch

# Run tests with coverage
yarn test --coverage

Development

# Build the package
yarn build

# Build in watch mode
yarn dev

# Type checking
yarn typecheck

# Linting
yarn lint

License

MIT