{"_id":"@ai-universe/auth-context","_rev":"3-fe4f7662f3f1e201dae44090cee7a035","name":"@ai-universe/auth-context","dist-tags":{"latest":"1.0.2"},"versions":{"1.0.0":{"name":"@ai-universe/auth-context","version":"1.0.0","keywords":["authentication","auth-context","firebase","ai-universe"],"author":{"name":"AI Universe Team"},"license":"MIT","_id":"@ai-universe/auth-context@1.0.0","maintainers":[{"name":"jleechan","email":"jleechan+npm@gmail.com"}],"dist":{"shasum":"53341897767505a6db36ecf689e8cdd6655faa29","tarball":"https://registry.npmjs.org/@ai-universe/auth-context/-/auth-context-1.0.0.tgz","fileCount":34,"integrity":"sha512-2F0YGbpE8xl/ZSJOD3T9zLXsvHdQz0BOcRei4O+1lheKp4FrzJLB2Y1UmJuGMiftzcnewYbHvsCid1MYoVMfPA==","signatures":[{"sig":"MEUCICuLjDEudQo2/Wae+A/Yb7wglIJxXkWR1pq3Z3/QaXcVAiEA7f+6Cs6HoSDo25XBUiqYBNSnFRQqWxXALx0Qofbv0Ts=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":110716},"main":"dist/index.js","types":"dist/index.d.ts","scripts":{"test":"jest","build":"tsc","test:watch":"jest --watch","test:coverage":"jest --coverage"},"_npmUser":{"name":"jleechan","email":"jleechan+npm@gmail.com"},"_npmVersion":"8.19.4","description":"Centralized authentication context resolution for AI Universe","directories":{},"_nodeVersion":"20.19.4","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.5.0","ts-jest":"^29.1.0","typescript":"^5.0.0","@types/jest":"^29.5.0","@types/node":"^20.0.0"},"peerDependencies":{"@ai-universe/mcp-server-utils":"^1.0.0"},"_npmOperationalInternal":{"tmp":"tmp/auth-context_1.0.0_1763154323126_0.30876256342493624","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"@ai-universe/auth-context","version":"1.0.1","keywords":["authentication","auth-context","firebase","ai-universe"],"author":{"name":"AI Universe Team"},"license":"MIT","_id":"@ai-universe/auth-context@1.0.1","maintainers":[{"name":"jleechan","email":"jleechan+npm@gmail.com"}],"dist":{"shasum":"6751dd38bd1b999d678730a47a8955a8a41d359b","tarball":"https://registry.npmjs.org/@ai-universe/auth-context/-/auth-context-1.0.1.tgz","fileCount":34,"integrity":"sha512-Z0yzcm5YYYiSzTlrDlZffvt/KtjhQm1TnvW5AQ2EMkvL64T5hYyUR5dcAeURNBJCTdnrSHDYRDUJtkil2SiODQ==","signatures":[{"sig":"MEQCIEj8M42Qx8y5asvL8u+541tLe/MqerF7jYhbQcyrkteyAiARA4ZRv/cG0xywuo2aIho6Fo4kTXGJVvthDS86UGpdGQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":111490},"main":"dist/index.js","types":"dist/index.d.ts","scripts":{"test":"jest","build":"tsc","test:watch":"jest --watch","test:coverage":"jest --coverage"},"_npmUser":{"name":"jleechan","email":"jleechan+npm@gmail.com"},"_npmVersion":"8.19.4","description":"Centralized authentication context resolution for AI Universe","directories":{},"_nodeVersion":"20.19.4","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.5.0","ts-jest":"^29.1.0","typescript":"^5.0.0","@types/jest":"^29.5.0","@types/node":"^20.0.0"},"peerDependencies":{"@ai-universe/mcp-server-utils":"^1.0.0"},"_npmOperationalInternal":{"tmp":"tmp/auth-context_1.0.1_1763189610607_0.6521731552500247","host":"s3://npm-registry-packages-npm-production"}},"1.0.2":{"name":"@ai-universe/auth-context","version":"1.0.2","description":"Centralized authentication context resolution for AI Universe","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"build":"tsc","test":"jest","test:watch":"jest --watch","test:coverage":"jest --coverage"},"keywords":["authentication","auth-context","firebase","ai-universe"],"author":{"name":"AI Universe Team"},"license":"MIT","devDependencies":{"@types/jest":"^29.5.0","@types/node":"^20.19.25","jest":"^29.5.0","ts-jest":"^29.1.0","typescript":"^5.0.0"},"peerDependencies":{"@ai-universe/mcp-server-utils":"^1.0.0"},"_id":"@ai-universe/auth-context@1.0.2","_nodeVersion":"20.19.4","_npmVersion":"8.19.4","dist":{"integrity":"sha512-jvmVzHlp0DkEhbdpYZVe6etkZ1zT2QTYWhyqAOt4z1Z63TB5gglfaQIjYpYAbo/gG73UWtIlvTVtJMWAjRDN6A==","shasum":"e2e9f9daf73f4ea02d1ebbd47cb05850197ea18c","tarball":"https://registry.npmjs.org/@ai-universe/auth-context/-/auth-context-1.0.2.tgz","fileCount":21,"unpackedSize":49347,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQD4l9XBvC/qb/Df9pwQJblUjxpuf0r4ew3HxFYQnJML4AIgKXzcHxrboJIIEl7Y6laqr9zRkEzHlBUUuLUtU73Bslo="}]},"_npmUser":{"name":"jleechan","email":"jleechan+npm@gmail.com"},"directories":{},"maintainers":[{"name":"jleechan","email":"jleechan+npm@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/auth-context_1.0.2_1763755333375_0.5029586281429037"},"_hasShrinkwrap":false}},"time":{"created":"2025-11-14T21:05:23.060Z","modified":"2025-11-21T20:02:13.765Z","1.0.0":"2025-11-14T21:05:23.344Z","1.0.1":"2025-11-15T06:53:30.806Z","1.0.2":"2025-11-21T20:02:13.556Z"},"author":{"name":"AI Universe Team"},"license":"MIT","keywords":["authentication","auth-context","firebase","ai-universe"],"description":"Centralized authentication context resolution for AI Universe","maintainers":[{"name":"jleechan","email":"jleechan+npm@gmail.com"}],"readme":"# @ai-universe/auth-context\n\nCentralized authentication context resolution for AI Universe with comprehensive test coverage and TDD methodology.\n\n## Overview\n\nThis 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.\n\n## Features\n\n- ✅ **Server Middleware Auth** - Most secure, uses server-verified token (cannot be spoofed)\n- ⚠️ **Legacy idToken Support** - Deprecated but still functional for backward compatibility\n- ⚠️ **Legacy userId Support** - Deprecated, treated as anonymous for security\n- 🔒 **Anonymous Fallback** - Safe default for unauthenticated requests\n- 📊 **Comprehensive Logging** - Info, warn, and error logging with structured context\n- 🧪 **100% Test Coverage** - 48 tests covering all authentication paths\n- 📈 **TDD Methodology** - Built using Matrix-Enhanced Test-Driven Development\n\n## Installation\n\n```bash\nnpm install @ai-universe/auth-context\n```\n\n## Usage\n\n```typescript\nimport { AuthContextResolver } from '@ai-universe/auth-context';\nimport type { AuthContextParams } from '@ai-universe/auth-context';\n\n// Create resolver with dependencies\nconst resolver = new AuthContextResolver(firebaseAuthTool, logger);\n\n// Resolve authentication context\nconst params: AuthContextParams = {\n  // Server middleware injected (most secure)\n  _authenticatedUserId: 'user-123',\n  _authenticatedUserEmail: 'user@example.com',\n  _authenticatedUserName: 'John Doe',\n\n  // OR legacy methods (deprecated)\n  idToken: 'firebase-token',\n  userId: 'client-provided-id'\n};\n\nconst result = await resolver.resolve(params);\n\nconsole.log(result.user.id);                   // 'user-123'\nconsole.log(result.authenticationMethod);       // 'server-middleware'\nconsole.log(result.deprecationWarnings);        // []\n```\n\n## Authentication Priority\n\nThe resolver uses a strict priority order:\n\n1. **Server Middleware** (`_authenticatedUserId`) - Highest priority, most secure\n2. **idToken Verification** - Deprecated, logs warning\n3. **userId** - Deprecated, treated as anonymous for security\n4. **Anonymous User** - Default fallback\n\n## API Reference\n\n### `AuthContextResolver`\n\n#### Constructor\n\n```typescript\nconstructor(authTool: FirebaseAuthTool, logger: Logger)\n```\n\n**Parameters:**\n- `authTool` - FirebaseAuthTool instance for token verification\n- `logger` - Logger instance for structured logging\n\n#### Methods\n\n##### `resolve(params: AuthContextParams): Promise<AuthContextResolutionResult>`\n\nResolves authentication context from request parameters.\n\n**Returns:**\n```typescript\n{\n  user: User;                    // Resolved user object\n  effectiveUserId: string;       // User ID to use for authorization\n  authenticationMethod: 'server-middleware' | 'idToken' | 'anonymous';\n  deprecationWarnings: string[]; // List of deprecation warnings\n}\n```\n\n## Types\n\n### `AuthContextParams`\n\n```typescript\ninterface AuthContextParams {\n  // Server middleware injected (most secure)\n  _authenticatedUserId?: string;\n  _authenticatedUserUid?: string;\n  _authenticatedUserEmail?: string;\n  _authenticatedUserName?: string;\n\n  // DEPRECATED: Legacy authentication\n  idToken?: string;\n  userId?: string;\n}\n```\n\n### `User`\n\n```typescript\ninterface User {\n  id: string;\n  uid?: string;\n  email?: string;\n  name?: string;\n  isAuthenticated: boolean;\n}\n```\n\n## Test Matrix Coverage\n\n### Matrix Testing Results\n\n✅ **48 tests passing** with **100% code coverage**\n\n**Test Distribution:**\n- Matrix 1: Authentication Path Testing (10 tests)\n- Matrix 2: _authenticatedUserId Variations (6 tests)\n- Matrix 3: idToken Verification Outcomes (6 tests)\n- Matrix 4: userId Fallback Behavior (5 tests)\n- Matrix 5: Logger Integration (5 tests)\n- Matrix 6: Anonymous User Creation (2 tests)\n- Matrix 7: FirebaseAuthTool Integration (4 tests)\n- Edge Cases Matrix (8 tests)\n- Integration Tests (2 tests)\n\n**Coverage Metrics:**\n```\nFile                    | % Stmts | % Branch | % Funcs | % Lines |\n------------------------|---------|----------|---------|---------|\nAuthContextResolver.ts  |     100 |      100 |     100 |     100 |\n```\n\nSee `AUTH_CONTEXT_TEST_MATRIX.md` for complete test matrix documentation.\n\n## Development\n\n### Running Tests\n\n```bash\n# Run all tests\nnpm test\n\n# Run with coverage\nnpm test -- --coverage\n\n# Watch mode\nnpm run test:watch\n```\n\n### Building\n\n```bash\nnpm run build\n```\n\n## Security Considerations\n\n### Why userId is Deprecated\n\nClient-provided `userId` can be spoofed by malicious clients, allowing impersonation attacks. The resolver now treats any `userId` without server verification as anonymous for security.\n\n### Server Middleware Auth\n\nThe `_authenticatedUserId` field is injected by server middleware after token verification, making it impossible for clients to spoof. This is the recommended authentication method.\n\n## Migration Guide\n\n### From Legacy userId\n\n**Before:**\n```typescript\nconst params = {\n  userId: user.uid,  // ❌ Can be spoofed\n  content: \"message\"\n};\n```\n\n**After:**\n```typescript\n// Frontend: Send token in Authorization header\nheaders['Authorization'] = `Bearer ${firebaseToken}`;\n\n// Backend: Server middleware injects _authenticatedUserId\n// AuthContextResolver automatically uses it\n```\n\n### From idToken in Body\n\n**Before:**\n```typescript\nconst params = {\n  idToken: firebaseToken,  // ⚠️ Deprecated\n  content: \"message\"\n};\n```\n\n**After:**\n```typescript\n// Send token in Authorization header instead\nheaders['Authorization'] = `Bearer ${firebaseToken}`;\n\n// Server middleware handles verification and injection\n```\n\n## Changelog\n\n### v1.0.0 (2025-11-14)\n\n- Initial release with TDD methodology\n- 48 comprehensive matrix tests\n- 100% code coverage\n- Full backward compatibility with legacy auth methods\n- Deprecation warnings for legacy methods\n\n## License\n\nMIT\n\n## Contributing\n\nThis package was built using Matrix-Enhanced Test-Driven Development. All changes must maintain 100% test coverage and follow the existing test matrix structure.\n\nSee `AUTH_CONTEXT_TEST_MATRIX.md` for the complete test specification.\n","readmeFilename":"README.md"}