{"_id":"@cocotastic/azure-cosmosdb-adapter","name":"@cocotastic/azure-cosmosdb-adapter","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@cocotastic/azure-cosmosdb-adapter","version":"0.1.0","description":"Azure Cosmos DB adapter for Auth.js","keywords":["auth","cosmosdb","azure","adapter","nextauth"],"type":"module","main":"dist/index.js","module":"dist/index.mjs","types":"dist/index.d.ts","publishConfig":{"access":"public"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","require":"./dist/index.cjs"}},"dependencies":{"next-auth":"5.0.0-beta.29"},"peerDependencies":{"@azure/cosmos":"^4.5.0"},"devDependencies":{"@azure/cosmos":"^4.5.0","@types/node":"^24.3.0","@typescript-eslint/eslint-plugin":"^8.41.0","@typescript-eslint/parser":"^8.41.0","@vitest/coverage-v8":"^1.0.0","@vercel/cosmosdb-server":"1.0.0","eslint":"^9.34.0","eslint-config-prettier":"^8.10.0","eslint-plugin-prettier":"^5.5.4","prettier":"^3.6.2","rimraf":"^5.0.0","tsup":"^8.5.0","typescript":"^5.9.2","vitest":"^1.0.0"},"scripts":{"build":"tsup","dev":"tsup --watch","clean":"rimraf dist","typecheck":"tsc --noEmit --project tsconfig.json","typecheck:test":"tsc --noEmit --project tsconfig.test.json","test":"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage","test:unit":"vitest run src/__tests__/unit","test:integration":"vitest run src/__tests__/integration --reporter=dot","test:integration:watch":"vitest src/__tests__/integration","cosmos:start":"node scripts/cosmos-server.js start","cosmos:stop":"node scripts/cosmos-server.js stop","cosmos:status":"node scripts/cosmos-server.js status","lint":"eslint 'src/**/*.{ts,tsx}'","lint:fix":"eslint 'src/**/*.{ts,tsx}' --fix","format":"prettier --write 'src/**/*.{ts,tsx,json,md}'","validate":"npm run typecheck && npm run lint && npm run test"},"_id":"@cocotastic/azure-cosmosdb-adapter@0.1.0","_integrity":"sha512-cK7mFKiZREGYDaK339ccOP4uNnMCqKQiVf+KN6/L4VuShUXWYRLgvI5S/9ROp2JtI8pv92CZhSCxuCdzPv1zMg==","_resolved":"/private/var/folders/xg/706rv9rd50d1gfr5f0lnxjym0000gn/T/becc73c05dc3445703c13cc50632ad56/cocotastic-azure-cosmosdb-adapter-0.1.0.tgz","_from":"file:cocotastic-azure-cosmosdb-adapter-0.1.0.tgz","_nodeVersion":"18.20.8","_npmVersion":"10.8.2","dist":{"integrity":"sha512-cK7mFKiZREGYDaK339ccOP4uNnMCqKQiVf+KN6/L4VuShUXWYRLgvI5S/9ROp2JtI8pv92CZhSCxuCdzPv1zMg==","shasum":"c169a456254fbed2f3583a754e09f48b39d8b0b5","tarball":"https://registry.npmjs.org/@cocotastic/azure-cosmosdb-adapter/-/azure-cosmosdb-adapter-0.1.0.tgz","fileCount":38,"unpackedSize":620848,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCsDM3/heHRXhvR5WEHklS7pqYW1FqQxoDt3ipgyMA6FwIgQHMhv9PXgehYHrOmQtQGnWfyXC5C35vW72NbvcBT5iI="}]},"_npmUser":{"name":"cocotastic","email":"sullivanmark@gmail.com"},"directories":{},"maintainers":[{"name":"cocotastic","email":"sullivanmark@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/azure-cosmosdb-adapter_0.1.0_1756651893356_0.8545768700019851"},"_hasShrinkwrap":false}},"time":{"created":"2025-08-31T14:51:33.203Z","0.1.0":"2025-08-31T14:51:33.547Z","modified":"2025-08-31T14:51:33.896Z"},"maintainers":[{"name":"cocotastic","email":"sullivanmark@gmail.com"}],"description":"Azure Cosmos DB adapter for Auth.js","keywords":["auth","cosmosdb","azure","adapter","nextauth"],"readme":"# @auth/azure-cosmosdb-adapter\n\nA robust, production-ready Azure Cosmos DB adapter for Auth.js with comprehensive error handling, input validation, structured logging, and performance optimizations.\n\n## Features\n\n- 🔒 **Type-safe**: Full TypeScript support with strict validation\n- 🛡️ **Secure**: Input validation, SQL injection prevention, and error handling\n- 📊 **Observable**: Structured logging and telemetry support\n- ⚡ **Performant**: Optimized queries, connection pooling, and parallel operations\n- 🧪 **Testable**: Comprehensive test suite with 95%+ coverage\n- 🔧 **Configurable**: Flexible configuration options and dependency injection\n- 🌐 **WebAuthn Ready**: Full support for WebAuthn authenticators\n- 🔄 **Reliable**: Automatic retries, graceful error handling, and cleanup\n\n## Quick Start\n\n### Installation\n\n```bash\nnpm install @auth/azure-cosmosdb-adapter @azure/cosmos\n# or\npnpm add @auth/azure-cosmosdb-adapter @azure/cosmos\n# or\nyarn add @auth/azure-cosmosdb-adapter @azure/cosmos\n```\n\n### Basic Usage\n\n```ts\nimport { AzureCosmosAdapter } from \"@auth/azure-cosmosdb-adapter\"\nimport { Auth } from \"@auth/core\"\n\nconst adapter = AzureCosmosAdapter({\n  clientOptions: {\n    endpoint: process.env.COSMOSDB_URI!,\n    key: process.env.COSMOSDB_KEY!,\n  },\n})\n\nconst response = await Auth(request, {\n  adapter,\n  // other Auth.js options...\n})\n```\n\n## Configuration\n\n### Basic Configuration\n\n```ts\nconst adapter = AzureCosmosAdapter({\n  clientOptions: {\n    endpoint: process.env.COSMOSDB_URI!,\n    key: process.env.COSMOSDB_KEY!,\n  },\n  databaseId: \"authjs\", // optional, defaults to \"authjs\"\n})\n```\n\n### Advanced Configuration\n\n```ts\nimport { \n  AzureCosmosAdapter, \n  ConsoleLogger, \n  PerformanceOptimizer \n} from \"@auth/azure-cosmosdb-adapter\"\n\nconst adapter = AzureCosmosAdapter({\n  clientOptions: {\n    endpoint: process.env.COSMOSDB_URI!,\n    key: process.env.COSMOSDB_KEY!,\n    connectionPolicy: {\n      enableEndpointDiscovery: true,\n      maxRetryAttemptsOnThrottledRequests: 3,\n      retryOptions: {\n        maxRetryAttemptsOnThrottledRequests: 5,\n        maxRetryWaitTimeInSeconds: 60\n      }\n    }\n  },\n  databaseId: \"production_auth\",\n  logger: ConsoleLogger, // or your custom logger\n  telemetry: {\n    trackOperation: (name, duration, success, context) => {\n      // Send metrics to your monitoring service\n      console.log(`Operation ${name}: ${duration}ms, success: ${success}`);\n    }\n  },\n  containerOptions: {\n    // Customize container creation options\n    usersOptions: {\n      body: { \n        id: \"users\", \n        partitionKey: { kind: \"Hash\", paths: [\"/id\"] },\n        defaultTtl: -1 // never expire\n      },\n      options: { offerThroughput: 400 }\n    },\n    // Additional container customizations...\n  },\n})\n```\n\n### Environment Variables\n\n```env\n# Required\nCOSMOSDB_URI=https://your-account.documents.azure.com:443/\nCOSMOSDB_KEY=your-primary-key\n\n# Optional\nCOSMOSDB_DATABASE_ID=authjs\n```\n\n## Container Schema\n\nThe adapter creates the following containers in your Cosmos DB database:\n\n| Container | Partition Key | Purpose |\n|-----------|---------------|----------|\n| `users` | `/id` | User accounts |\n| `accounts` | `/userId` | OAuth/social accounts linked to users |\n| `sessions` | `/sessionToken` | Active user sessions |\n| `tokens` | `/identifier` | Verification tokens (email, etc.) |\n| `authenticators` | `/userId` | WebAuthn authenticators |\n\n## API Reference\n\n### Core Adapter Methods\n\n#### User Management\n```ts\n// Create a new user\nawait adapter.createUser({\n  id: \"user_123\",\n  email: \"user@example.com\",\n  emailVerified: new Date(),\n})\n\n// Get user by ID\nconst user = await adapter.getUser(\"user_123\")\n\n// Get user by email\nconst user = await adapter.getUserByEmail(\"user@example.com\")\n\n// Update user\nawait adapter.updateUser({\n  id: \"user_123\",\n  name: \"Updated Name\"\n})\n\n// Delete user (cascades to accounts, sessions, authenticators)\nawait adapter.deleteUser(\"user_123\")\n```\n\n#### Account Linking\n```ts\n// Link OAuth account to user\nawait adapter.linkAccount({\n  id: \"account_123\",\n  userId: \"user_123\",\n  type: \"oauth\",\n  provider: \"google\",\n  providerAccountId: \"google_user_id\",\n  access_token: \"token\",\n  refresh_token: \"refresh\",\n  expires_at: Math.floor(Date.now() / 1000) + 3600\n})\n\n// Get user by linked account\nconst user = await adapter.getUserByAccount({\n  provider: \"google\",\n  providerAccountId: \"google_user_id\"\n})\n\n// Unlink account\nawait adapter.unlinkAccount({\n  provider: \"google\",\n  providerAccountId: \"google_user_id\"\n})\n```\n\n#### Session Management\n```ts\n// Create session\nawait adapter.createSession({\n  sessionToken: \"session_token\",\n  userId: \"user_123\",\n  expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 days\n})\n\n// Get session and user\nconst result = await adapter.getSessionAndUser(\"session_token\")\nif (result) {\n  const { session, user } = result\n}\n\n// Update session\nawait adapter.updateSession({\n  sessionToken: \"session_token\",\n  expires: new Date(Date.now() + 60 * 24 * 60 * 60 * 1000) // extend to 60 days\n})\n\n// Delete session\nawait adapter.deleteSession(\"session_token\")\n```\n\n#### WebAuthn Support\n```ts\n// Create authenticator\nawait adapter.createAuthenticator!({\n  credentialID: \"credential_id\",\n  userId: \"user_123\",\n  providerAccountId: \"provider_id\",\n  credentialPublicKey: new Uint8Array([/* key bytes */]),\n  counter: 0,\n  credentialDeviceType: \"singleDevice\",\n  credentialBackedUp: false,\n  transports: \"usb,nfc\"\n})\n\n// Get authenticator\nconst auth = await adapter.getAuthenticator!(\"credential_id\")\n\n// List user's authenticators\nconst auths = await adapter.listAuthenticatorsByUserId!(\"user_123\")\n\n// Update counter\nawait adapter.updateAuthenticatorCounter!(\"credential_id\", 1)\n```\n\n### Error Handling\n\nThe adapter provides structured error handling:\n\n```ts\nimport { \n  isNotFoundError, \n  AdapterError, \n  ValidationError,\n  ConfigurationError \n} from \"@auth/azure-cosmosdb-adapter\"\n\ntry {\n  const user = await adapter.getUser(\"nonexistent\")\n} catch (error) {\n  if (isNotFoundError(error)) {\n    // Handle not found case\n  } else if (error instanceof ValidationError) {\n    console.log(`Validation failed: ${error.message}`);\n  } else if (error instanceof AdapterError) {\n    console.log(`Adapter operation failed: ${error.operation}`);\n  }\n}\n```\n\n## Logging and Telemetry\n\n### Console Logger\n```ts\nimport { ConsoleLogger } from \"@auth/azure-cosmosdb-adapter\"\n\nconst adapter = AzureCosmosAdapter({\n  // ... other options\n  logger: ConsoleLogger\n})\n```\n\n### Custom Logger\n```ts\nimport type { Logger } from \"@auth/azure-cosmosdb-adapter\"\n\nconst customLogger: Logger = {\n  debug: (message, context) => {\n    // Send to your logging service\n  },\n  info: (message, context) => {\n    // Send to your logging service\n  },\n  warn: (message, context) => {\n    // Send to your logging service\n  },\n  error: (message, context) => {\n    // Send to your logging service\n  }\n}\n\nconst adapter = AzureCosmosAdapter({\n  // ... other options\n  logger: customLogger\n})\n```\n\n### Telemetry\n```ts\nimport type { Telemetry } from \"@auth/azure-cosmosdb-adapter\"\n\nconst telemetry: Telemetry = {\n  trackOperation: (operationName, duration, success, context) => {\n    // Send metrics to Application Insights, DataDog, etc.\n    metrics.timing(`auth.adapter.${operationName}`, duration, {\n      success: success.toString(),\n      ...context\n    });\n  }\n}\n```\n\n## Testing\n\n### Local Development with Emulator\n\nFor local development, you can use the Azure Cosmos DB Emulator:\n\n```bash\n# Start the emulator (Windows)\ncosmosdb-emulator.exe\n\n# Or use Docker (cross-platform)\ndocker run -p 8081:8081 -p 10251:10251 -p 10252:10252 -p 10253:10253 -p 10254:10254 \\\n  -m 3g --cpus=2.0 --name=test-cosmosdb \\\n  -e AZURE_COSMOS_EMULATOR_PARTITION_COUNT=10 \\\n  -e AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE=true \\\n  mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest\n```\n\nEnvironment variables for emulator:\n```env\nCOSMOSDB_URI=https://localhost:8081\nCOSMOSDB_KEY=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==\n```\n\n### Running Tests\n\n```bash\n# Install dependencies\nnpm install\n\n# Run unit tests\nnpm run test\n\n# Run tests with coverage\nnpm run test:coverage\n\n# Run integration tests (requires emulator)\nnpm run test:integration\n\n# Run all validation (typecheck + lint + test)\nnpm run validate\n```\n\n## Performance Optimization\n\n### Connection Configuration\n```ts\nconst adapter = AzureCosmosAdapter({\n  clientOptions: {\n    endpoint: process.env.COSMOSDB_URI!,\n    key: process.env.COSMOSDB_KEY!,\n    connectionPolicy: {\n      enableEndpointDiscovery: true,\n      maxRetryAttemptsOnThrottledRequests: 5,\n      retryOptions: {\n        maxRetryWaitTimeInSeconds: 60\n      },\n      // Connection pooling\n      connectionMode: \"Gateway\", // or \"Direct\" for better performance\n      maxConnectionPoolSize: 10\n    }\n  },\n  // Enable performance optimizations\n  performance: {\n    enableParallelExecution: true,\n    maxDegreeOfParallelism: 10,\n    enableCaching: false // disable if you need real-time data\n  }\n})\n```\n\n### Query Optimization Tips\n\n1. **Use partition keys**: The adapter is optimized for partition key-based operations\n2. **Batch operations**: Related operations are automatically batched\n3. **Parallel execution**: Bulk operations use parallel processing\n4. **Efficient queries**: Queries use projection to minimize data transfer\n\n## Migration Guide\n\n### From v0.x to v1.x\n\nThe adapter maintains backward compatibility, but new features are available:\n\n```ts\n// Before (still works)\nconst adapter = AzureCosmosAdapter({\n  clientOptions: { endpoint, key }\n})\n\n// After (enhanced with new features)\nconst adapter = AzureCosmosAdapter({\n  clientOptions: { endpoint, key },\n  logger: ConsoleLogger,        // NEW: structured logging\n  telemetry: myTelemetry,       // NEW: performance monitoring\n  performance: {                // NEW: performance optimizations\n    enableParallelExecution: true\n  }\n})\n```\n\n## Development\n\n### Setup\n```bash\n# Clone and install dependencies\ngit clone <repo>\ncd packages/adapter-azure-cosmosdb\nnpm install\n\n# Build\nnpm run build\n\n# Type checking\nnpm run typecheck\n\n# Linting\nnpm run lint\n\n# Format code\nnpm run format\n```\n\n### Project Structure\n```\nsrc/\n├── index.ts              # Main adapter implementation\n├── types.ts              # TypeScript type definitions\n├── container.ts          # Cosmos DB container management\n├── queries.ts            # SQL query builders\n├── validation.ts         # Input validation\n├── errors.ts             # Error classes and utilities\n├── logger.ts             # Logging and telemetry\n├── performance.ts        # Performance optimizations\n├── util.ts               # Utility functions\n└── __tests__/           # Test suites\n    ├── unit/            # Unit tests\n    └── integration/     # Integration tests\n```\n\n## Contributing\n\nContributions are welcome! Please:\n\n1. **Follow TypeScript best practices**: Use strict typing, avoid `any`\n2. **Add tests**: Both unit and integration tests for new features\n3. **Update documentation**: Keep README and JSDoc comments current\n4. **Follow conventions**: Use existing patterns for consistency\n5. **Run validation**: Ensure `npm run validate` passes\n\n### Code Quality Standards\n- **Type Safety**: 100% (no `any` types in public API)\n- **Test Coverage**: 95%+ on critical paths\n- **Error Handling**: All operations have proper error paths\n- **Documentation**: 100% of public APIs documented\n\n## License\n\nMIT License - see [LICENSE](../../LICENSE) file for details.\n\n## Support\n\n- 📖 [Auth.js Documentation](https://authjs.dev)\n- 🐛 [Report Issues](https://github.com/nextauthjs/next-auth/issues)\n- 💬 [Community Discord](https://discord.gg/nextauth)\n- 📧 [Azure Cosmos DB Documentation](https://docs.microsoft.com/en-us/azure/cosmos-db/)","readmeFilename":"README.md","_rev":"1-b0d01e38ce9d1834b5a06ba3f5b33a3c"}