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

@ai-universe/auth-context

v1.0.2

Published

Centralized authentication context resolution for AI Universe

Downloads

36

Readme

@ai-universe/auth-context

Centralized authentication context resolution for AI Universe with comprehensive test coverage and TDD methodology.

Overview

This package provides a single, secure source of truth for authentication context resolution across AI Universe services. It implements a priority-based authentication strategy with built-in deprecation warnings for legacy authentication methods.

Features

  • Server Middleware Auth - Most secure, uses server-verified token (cannot be spoofed)
  • ⚠️ Legacy idToken Support - Deprecated but still functional for backward compatibility
  • ⚠️ Legacy userId Support - Deprecated, treated as anonymous for security
  • 🔒 Anonymous Fallback - Safe default for unauthenticated requests
  • 📊 Comprehensive Logging - Info, warn, and error logging with structured context
  • 🧪 100% Test Coverage - 48 tests covering all authentication paths
  • 📈 TDD Methodology - Built using Matrix-Enhanced Test-Driven Development

Installation

npm install @ai-universe/auth-context

Usage

import { AuthContextResolver } from '@ai-universe/auth-context';
import type { AuthContextParams } from '@ai-universe/auth-context';

// Create resolver with dependencies
const resolver = new AuthContextResolver(firebaseAuthTool, logger);

// Resolve authentication context
const params: AuthContextParams = {
  // Server middleware injected (most secure)
  _authenticatedUserId: 'user-123',
  _authenticatedUserEmail: '[email protected]',
  _authenticatedUserName: 'John Doe',

  // OR legacy methods (deprecated)
  idToken: 'firebase-token',
  userId: 'client-provided-id'
};

const result = await resolver.resolve(params);

console.log(result.user.id);                   // 'user-123'
console.log(result.authenticationMethod);       // 'server-middleware'
console.log(result.deprecationWarnings);        // []

Authentication Priority

The resolver uses a strict priority order:

  1. Server Middleware (_authenticatedUserId) - Highest priority, most secure
  2. idToken Verification - Deprecated, logs warning
  3. userId - Deprecated, treated as anonymous for security
  4. Anonymous User - Default fallback

API Reference

AuthContextResolver

Constructor

constructor(authTool: FirebaseAuthTool, logger: Logger)

Parameters:

  • authTool - FirebaseAuthTool instance for token verification
  • logger - Logger instance for structured logging

Methods

resolve(params: AuthContextParams): Promise<AuthContextResolutionResult>

Resolves authentication context from request parameters.

Returns:

{
  user: User;                    // Resolved user object
  effectiveUserId: string;       // User ID to use for authorization
  authenticationMethod: 'server-middleware' | 'idToken' | 'anonymous';
  deprecationWarnings: string[]; // List of deprecation warnings
}

Types

AuthContextParams

interface AuthContextParams {
  // Server middleware injected (most secure)
  _authenticatedUserId?: string;
  _authenticatedUserUid?: string;
  _authenticatedUserEmail?: string;
  _authenticatedUserName?: string;

  // DEPRECATED: Legacy authentication
  idToken?: string;
  userId?: string;
}

User

interface User {
  id: string;
  uid?: string;
  email?: string;
  name?: string;
  isAuthenticated: boolean;
}

Test Matrix Coverage

Matrix Testing Results

48 tests passing with 100% code coverage

Test Distribution:

  • Matrix 1: Authentication Path Testing (10 tests)
  • Matrix 2: _authenticatedUserId Variations (6 tests)
  • Matrix 3: idToken Verification Outcomes (6 tests)
  • Matrix 4: userId Fallback Behavior (5 tests)
  • Matrix 5: Logger Integration (5 tests)
  • Matrix 6: Anonymous User Creation (2 tests)
  • Matrix 7: FirebaseAuthTool Integration (4 tests)
  • Edge Cases Matrix (8 tests)
  • Integration Tests (2 tests)

Coverage Metrics:

File                    | % Stmts | % Branch | % Funcs | % Lines |
------------------------|---------|----------|---------|---------|
AuthContextResolver.ts  |     100 |      100 |     100 |     100 |

See AUTH_CONTEXT_TEST_MATRIX.md for complete test matrix documentation.

Development

Running Tests

# Run all tests
npm test

# Run with coverage
npm test -- --coverage

# Watch mode
npm run test:watch

Building

npm run build

Security Considerations

Why userId is Deprecated

Client-provided userId can be spoofed by malicious clients, allowing impersonation attacks. The resolver now treats any userId without server verification as anonymous for security.

Server Middleware Auth

The _authenticatedUserId field is injected by server middleware after token verification, making it impossible for clients to spoof. This is the recommended authentication method.

Migration Guide

From Legacy userId

Before:

const params = {
  userId: user.uid,  // ❌ Can be spoofed
  content: "message"
};

After:

// Frontend: Send token in Authorization header
headers['Authorization'] = `Bearer ${firebaseToken}`;

// Backend: Server middleware injects _authenticatedUserId
// AuthContextResolver automatically uses it

From idToken in Body

Before:

const params = {
  idToken: firebaseToken,  // ⚠️ Deprecated
  content: "message"
};

After:

// Send token in Authorization header instead
headers['Authorization'] = `Bearer ${firebaseToken}`;

// Server middleware handles verification and injection

Changelog

v1.0.0 (2025-11-14)

  • Initial release with TDD methodology
  • 48 comprehensive matrix tests
  • 100% code coverage
  • Full backward compatibility with legacy auth methods
  • Deprecation warnings for legacy methods

License

MIT

Contributing

This package was built using Matrix-Enhanced Test-Driven Development. All changes must maintain 100% test coverage and follow the existing test matrix structure.

See AUTH_CONTEXT_TEST_MATRIX.md for the complete test specification.