@ai-universe/auth-context
v1.0.2
Published
Centralized authentication context resolution for AI Universe
Downloads
36
Maintainers
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-contextUsage
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:
- Server Middleware (
_authenticatedUserId) - Highest priority, most secure - idToken Verification - Deprecated, logs warning
- userId - Deprecated, treated as anonymous for security
- Anonymous User - Default fallback
API Reference
AuthContextResolver
Constructor
constructor(authTool: FirebaseAuthTool, logger: Logger)Parameters:
authTool- FirebaseAuthTool instance for token verificationlogger- 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:watchBuilding
npm run buildSecurity 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 itFrom 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 injectionChangelog
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.
