Skip to content

Releases: lance0/latch

SECURITY: v0.4.7 - DoS and Source Code Exposure Fixes

16 Dec 14:00

Choose a tag to compare

Security update for CVE-2025-67779 (DoS) and CVE-2025-55183 (Source Code Exposure). Requires next>=15.0.7. See SECURITY.md for version table.

🔒 SECURITY: v0.4.6 - CVE-2025-55182 Mitigation

04 Dec 17:42

Choose a tag to compare

⚠️ CRITICAL SECURITY UPDATE

CVE-2025-55182: React Server Components Remote Code Execution (CVSS 10.0)

This release updates Latch's peer dependencies to require patched versions of React and Next.js.


🚨 Immediate Action Required

If you're using Latch, verify your React and Next.js versions are patched:

# Check current versions
npm list react next

# Upgrade to patched versions
npm install next@latest react@latest react-dom@latest

✅ Patched Versions

Next.js:

  • 15.0.5, 15.1.9, 15.2.6, 15.3.6, 15.4.8, 15.5.7, 16.0.7

React:

  • 19.0.1, 19.1.2, 19.2.1

📝 What Changed in Latch v0.4.6

Updated peer dependencies:

  • next: >=15.0.5 (was >=15.0.0)
  • react: >=19.0.1 (was ^19.0.0)
  • react-dom: >=19.0.1 (was ^19.0.0)

Updated example apps:

  • All examples now use Next.js 16.0.7 and React 19.0.1

Documentation:

  • Added security advisory to SECURITY.md
  • Added security banner to README.md
  • Updated CHANGELOG.md

ℹ️ About the Vulnerability

CVE-2025-55182 affects React Server Components (react-server-dom-* packages). While Latch does NOT directly depend on these packages, applications using vulnerable versions of React or Next.js may still be affected.

The vulnerability allows unauthenticated remote code execution through malicious HTTP requests to Server Function endpoints.

🔗 References


📦 Install

npm install @lance0/latch@0.4.6

# Then upgrade React and Next.js:
npm install next@latest react@latest react-dom@latest

v0.4.5 - Documentation Improvements

17 Nov 17:42

Choose a tag to compare

📚 Better Developer Onboarding

This release improves documentation to make production best practices more discoverable.

✨ What Changed

Wrapping Pattern in Quick Start:

The recommended production pattern is now prominently featured in the Quick Start guide (step 6), not hidden in advanced sections.

New Quick Start Flow:

  1. Install dependencies
  2. Configure environment
  3. Create API routes
  4. Wrap app with LatchProvider
  5. Use auth in components
  6. 🆕 Create app-specific auth helpers (lib/auth.ts) ← NEW
  7. Use helpers in components
  8. 🆕 Use wrapper in Server Actions & API routes ← NEW
  9. Protect routes
  10. Explore examples

📖 What You Get

lib/auth.ts example with:

  • getCurrentUser() - Cached, with database sync
  • requireAuth() - Authentication guard
  • JIT user provisioning pattern
  • Request-level caching with React cache()

Why this matters:

  • ✅ Prevents common mistakes (using Latch helpers everywhere)
  • ✅ Shows how to centralize auth logic
  • ✅ Demonstrates database integration
  • ✅ Makes testing easier

🚀 Generate with CLI

npx @lance0/latch-cli scaffold --type wrapper

Creates lib/auth.ts with recommended pattern ready to customize.

📦 Notes

  • No code changes - documentation-only release
  • Version bump to align with recent releases (v0.4.3 → v0.4.5)
  • v0.4.4 was CLI improvements

📖 Links

v0.4.4 - Enhanced CLI Scaffold Commands

17 Nov 17:40

Choose a tag to compare

🛠️ Enhanced CLI Developer Experience

This release significantly improves the command with new capabilities.

✨ New Scaffold Options

Interactive Menu:

npx @lance0/latch-cli scaffold

Choose from:

  • API Routes - Auth endpoints (/api/latch/*)
  • Proxy (Next.js 16) - Session validation middleware
  • Auth Wrapper - lib/auth.ts helper functions
  • All of the Above - Complete setup

Or use CLI flags:

npx @lance0/latch-cli scaffold --type proxy    # Generate proxy.ts
npx @lance0/latch-cli scaffold --type wrapper  # Generate lib/auth.ts
npx @lance0/latch-cli scaffold --type all      # Everything

📦 What Gets Generated

proxy.ts (Next.js 16 compatible):

  • ✅ No runtime export (avoids build errors)
  • ✅ Proper session validation (checks session.sub)
  • ✅ Customizable public routes
  • ✅ Works with Next.js 16 automatically

lib/auth.ts (Recommended wrapper pattern):

  • getCurrentUser() with React cache
  • requireAuth() guard function
  • ✅ TODO comments for database sync
  • ✅ JIT user provisioning pattern

🎯 Why These Additions?

Based on real production feedback:

  • Users need a reference proxy.ts for Next.js 16
  • Wrapping pattern should be easier to set up
  • One command should generate everything needed

📖 Links

v0.4.3 - DX Improvements from Real Production Feedback

17 Nov 15:00

Choose a tag to compare

🎯 DX Improvements Based on Scout Integration

This release addresses critical developer experience issues discovered during real production integration.

✨ New Helper Functions

Better TypeScript Support:

  • requireServerSession() - Get authenticated session or throw (no more ! assertions)
  • isLatchSession() - Type guard for proper TypeScript narrowing
  • checkLatchHealth() - Configuration validation for health check endpoints

🐛 Critical Fixes

Next.js 16 Compatibility:

  • ❌ Fixed: export const runtime = 'nodejs' causes build errors in proxy.ts
  • ✅ proxy.ts automatically uses Node.js runtime (no config needed)

Session Validation:

  • ❌ Fixed: Examples checking session.idToken (property doesn't exist)
  • ✅ Check session.sub instead (from ID token claims)

📚 Documentation

New Reference Implementation:

  • examples/nextjs16/proxy.ts - Complete Next.js 16 proxy with proper session validation

Enhanced API_REFERENCE.md:

  • Clear LatchSession/LatchUser structure documentation
  • ✅ Correct vs ❌ Wrong usage examples
  • Cookie name constants documentation
  • Session validation patterns for proxy.ts

🧪 Testing

  • Added 17 new tests for DX helpers
  • All 182 tests passing
  • No breaking changes

📦 What Changed

Added:

  • requireServerSession() helper
  • isLatchSession() type guard
  • checkLatchHealth() config validator
  • Reference proxy.ts for Next.js 16
  • Comprehensive session documentation

Fixed:

  • Next.js 16 proxy.ts runtime export issue
  • Session validation patterns in examples
  • Documentation clarity on session structure

🙏 Credits

Based on real production feedback from integrating Latch into Scout app. Thanks for the 2.5 hours of pain points that made this release possible!

📖 Links

v0.4.2 - Performance & UX Improvements

12 Nov 18:44

Choose a tag to compare

🚀 Performance & User Experience Improvements

Based on technical review feedback, v0.4.2 delivers two critical enhancements that significantly improve both production UX and performance.


🎯 Key Improvements

1. Automatic Token Refresh

Problem Solved: Users were unexpectedly logged out after 1 hour when ID tokens expired, even though refresh tokens remained valid for 7 days.

Solution: LatchProvider now automatically refreshes sessions 5 minutes before token expiry.

Benefits:

  • ✅ Users stay logged in for the full 7-day refresh token lifetime
  • ✅ No more surprise logouts mid-session
  • ✅ Seamless background refresh with proper cleanup
  • ✅ Handles edge cases (tab close, multiple tabs, expires soon)

Implementation:

// Automatic - no code changes needed!
<LatchProvider>
  {children}
</LatchProvider>

The refresh timer automatically sets up when a user authenticates and cleans up on logout or unmount.


2. PBKDF2 Key Caching

Problem Solved: Cookie encryption was deriving the AES key with 100,000 PBKDF2 iterations on every seal/unseal operation (~10-20ms overhead).

Solution: Derived keys are now cached in memory, keyed by secret.

Performance Impact:

  • First operation: ~10-20ms (key derivation)
  • Subsequent operations: <1ms (cached key)
  • Improvement: 10-20x faster

Benefits:

  • ✅ Massive performance gain for high-traffic apps
  • ✅ Reduced CPU usage under load
  • ✅ Zero security trade-off (secret already in memory)
  • ✅ Supports secret rotation automatically

Technical:

// Automatic caching - no code changes needed!
const sealed = await seal(userData, secret); // Fast!

// Optional: Manual cache clearing for testing
import { clearKeyCache } from '@lance0/latch';
clearKeyCache();

📦 Installation

npm install @lance0/latch@0.4.2

🔄 Migration from v0.4.1

Breaking Changes: None! Fully backward compatible.

Action Required: None - improvements are automatic.

Just update your package and enjoy better performance and UX:

npm update @lance0/latch

📊 Technical Details

Auto-Refresh Implementation

  • Uses React useEffect with dependency on user.exp timestamp
  • Calculates time until expiry and sets setTimeout
  • Refreshes 5 minutes before expiry (configurable buffer)
  • Proper cleanup prevents memory leaks
  • Safe for multiple tabs (each refreshes independently)

Key Cache Implementation

  • Module-level Map<string, CryptoKey> cache
  • Cache key is the secret itself
  • New secrets automatically create new cache entries
  • Export clearKeyCache() for testing/manual invalidation
  • Cache is per-process (doesn't leak across requests)

🧪 Testing

New Tests Added:

  • ✅ Key caching performance test
  • ✅ Multiple secrets independence test
  • ✅ Manual cache clearing test

All Existing Tests:

  • ✅ 164 tests passing (3 new tests added)
  • ✅ No regressions
  • ✅ TypeScript compilation clean

📝 Full Changelog

Added

  • Automatic Token Refresh - LatchProvider auto-refreshes sessions before expiry
  • PBKDF2 Key Caching - Derived keys cached for 10-20x performance gain
  • clearKeyCache() export for testing/manual cache invalidation

Performance

  • Cookie encryption: ~10-20ms → <1ms (after first operation)
  • Reduced CPU usage under high load
  • Seamless session management without database queries

User Experience

  • Users stay logged in for full refresh token lifetime (7 days)
  • No more unexpected 1-hour logout due to ID token expiry
  • Automatic background session refresh with 5-minute buffer

🙏 Credits

These improvements were implemented based on feedback from a comprehensive technical review identifying production pain points.


🔗 Links

v0.4.1 - Enhanced Validation Guards

12 Nov 15:19

Choose a tag to compare

🔒 Enhanced Validation Guards & Token Confusion Prevention

Critical security release adding token confusion attack prevention and configurable security settings.

🛡️ Security Improvements

Token Confusion Attack Prevention:

  • Strict issuer validation prevents tokens from wrong tenant/cloud
  • Automatic detection of commercial vs government cloud mismatches
  • Validates tenant ID matches expected value
  • Clear error messages indicating exact mismatch

Example Attack Prevented:

// Attacker obtains token from their Azure AD tenant
// Tries to use it in your application
// ❌ Latch now rejects with clear error:
// "Token issuer mismatch (potential token confusion attack)"

🆕 New Features

1. validateIssuer() Helper:

import { validateIssuer } from '@lance0/latch';

// Validate token issuer matches expectations
validateIssuer(payload.iss, config.tenantId, config.cloud);

2. Enhanced verifyIdToken():

const user = await verifyIdToken(
  tokens.id_token,
  endpoints.jwksUri,
  config.clientId,
  pkceData.nonce,
  {
    tenantId: config.tenantId,  // Validates correct tenant
    cloud: config.cloud,         // Validates correct cloud
    clockTolerance: 60,          // Configurable clock skew
  }
);

3. Configurable Security Settings:

# Clock skew tolerance for token validation
LATCH_CLOCK_SKEW_TOLERANCE=60    # default: 60 seconds

# JWKS cache TTL
LATCH_JWKS_CACHE_TTL=3600         # default: 1 hour

📚 Security Documentation

Updated SECURITY.md:

  • New section: Token Confusion Attack Prevention
  • Attack scenarios and protections explained
  • Code examples and best practices
  • Multi-tenant security guidance

Attack Scenarios Prevented:

  • Multi-tenant apps accepting tokens from wrong tenant
  • Apps misconfigured for wrong cloud (commercial vs government)
  • Token replay from different tenant
  • Cross-cloud token confusion

🧪 Tests

  • 19 new security tests for issuer validation
  • Multi-tenant scenario coverage
  • Token confusion attack scenarios
  • 161 total tests passing

📦 Installation

npm install @lance0/latch@0.4.1

🔄 Migration

Breaking Changes: None

Recommended (Optional):
Update your callback route to enable enhanced validation:

const user = await verifyIdToken(
  tokens.id_token,
  endpoints.jwksUri,
  config.clientId,
  pkceData.nonce,
  {
    tenantId: config.tenantId,  // Add this
    cloud: config.cloud,         // Add this
  }
);

This is optional but strongly recommended for multi-tenant applications or government cloud deployments.

📊 Roadmap Progress

Completed: Enhanced Validation Guards (High Priority)

Remaining for v1.0:

  1. Example App Presets (2-3 hours)
  2. Migration Guides (2-3 hours)
  3. Security Audit (external)

🔗 Links


Security Note: This release hardens Latch against token confusion attacks, a class of vulnerability where applications accept tokens from unintended issuers. All users should upgrade.

v0.4.0 - Server Actions Support

12 Nov 15:13

Choose a tag to compare

🎉 Server Actions Support for Next.js 15+

Major new feature release adding first-class support for Next.js 15 Server Actions!

🚀 New Features

Server Actions Helpers:

  • getServerSession(cookieSecret) - Get current session in Server Actions/Components
  • requireAuth(cookieSecret) - Require authentication with helpful errors
  • Full TypeScript support with proper type inference

Example Code:

'use server';

import { requireAuth } from '@lance0/latch';

export async function getProfile() {
  const user = await requireAuth(process.env.LATCH_COOKIE_SECRET!);
  return { name: user.name, email: user.email };
}

📚 Documentation & Examples

  • New Guide: docs/SERVER_ACTIONS.md - Comprehensive patterns and best practices
  • Example Actions:
    • apps/example-app/app/actions/profile.ts - Read operations
    • apps/example-app/app/actions/updateSettings.ts - Mutations & form actions
  • Live Demo: /dashboard/server-actions-demo page with interactive examples
  • README: Updated with Server Actions quick start

🔧 Error Handling

  • New LATCH_UNAUTHORIZED error code
  • Helpful error messages with solutions
  • Clear guidance on handling auth errors in Server Actions

🧪 Tests

  • 7 new tests for Server Actions helpers
  • 142 total tests passing
  • Full coverage of auth scenarios

📊 Roadmap Progress

Completed high-priority item: Server Actions Patterns (15 hours estimated)

This was identified as critical for v1.0 GA and is now complete!

📦 Installation

npm install @lance0/latch@0.4.0

🔄 Migration

Breaking Changes: None
Required Changes: None

This release is 100% backward compatible. New helpers are opt-in additions.

🎯 When to Use

Use Server Actions when:

  • Form submissions and mutations
  • Simple authenticated data fetching
  • Collocated with UI components
  • Want end-to-end TypeScript types

Use API Routes when:

  • OAuth callbacks (like Latch uses)
  • Webhooks from external services
  • Public REST APIs
  • Rate limiting and complex middleware

See the Server Actions guide for detailed decision matrix.

🙏 What's Next

With Server Actions support complete, the next priorities for v1.0 are:

  1. Enhanced validation guards (strict tenant/issuer validation)
  2. Example app presets (commercial vs GCC-High)
  3. Security audit preparation

📖 Learn More


npm: https://www.npmjs.com/package/@lance0/latch

v0.3.4 - Quick Wins

12 Nov 14:56

Choose a tag to compare

Quick Win Improvements

Small, high-impact improvements based on continued DX feedback.

Logout Improvements

  • New helper: clearLatchCookies(response) - Delete all Latch cookies at once
  • Updated example logout route to use buildLogoutUrl() helper
  • Comprehensive JSDoc documenting Azure AD SSO logout behavior
  • Clear explanation of local vs SSO logout options

Session & Refresh Route Documentation

  • Fixed bug: Session route now checks refresh token expiry (7-day lifetime)
  • Added detailed JSDoc to session route explaining purpose and usage
  • Added comprehensive JSDoc to refresh route with Direct Token and Secure Proxy patterns
  • Clear guidance on when to call each route

README Documentation

  • New section: Cookie Storage Pattern with size table
  • Added step 4 to Quick Start: Create API routes
  • Explained what each of the 5 routes does
  • Quick setup command to copy routes from example app

Tests

  • Fixed seal test to validate new 4KB size checking behavior
  • Added test for moderately sized objects under 4KB

Installation

npm install @lance0/latch@0.3.4

What's Next

These improvements make Latch easier to integrate and understand. All changes are non-breaking and focused on developer experience.

Full changelog: https://github.com/lance0/latch/blob/master/CHANGELOG.md

v0.3.3 - Critical DX Improvements

04 Nov 21:29

Choose a tag to compare

Critical DX Improvements

Cookie size validation and comprehensive documentation based on real user feedback.

Cookie Size Validation

  • Automatic 4KB browser limit checking
  • Warns at 3.5KB, errors at 4KB
  • Clear error messages with solutions

Improved Documentation

  • Detailed COOKIE_NAMES JSDoc
  • Size estimates for each cookie
  • Correct vs incorrect examples

Helper Functions

  • getUserDisplayName, getUserInitials
  • requireIdToken, requireRefreshToken
  • RECOMMENDED_SCOPES constant

Installation

npm install @lance0/latch@0.3.3