{"id":23970586,"url":"https://github.com/humanjavaenterprises/nostr-auth-middleware","last_synced_at":"2025-06-13T21:06:00.536Z","repository":{"id":266192255,"uuid":"897526194","full_name":"HumanjavaEnterprises/nostr-auth-middleware","owner":"HumanjavaEnterprises","description":"The nostr-auth-middleware repository offers a TypeScript-based middleware solution for managing authentication and enrollment in Nostr web applications. It supports NIP-07 compatible authentication, secure user enrollment, event validation, and JWT-based session management, with optional Supabase integration for data persistence.","archived":false,"fork":false,"pushed_at":"2025-02-09T23:04:43.000Z","size":326,"stargazers_count":4,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-23T14:34:53.251Z","etag":null,"topics":["authentication","decentralized-protocols","event-validation","jwt","middleware","nostr","security","supabase","web-applications"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/HumanjavaEnterprises.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["humanjavaenterprises"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":["https://getalby.com/p/vveerrgg","https://blockchair.com/bitcoin/address/bc1qw6kasfudkd64sts2q5a0lpm8zgea9txjc4gxj7","https://blockchair.com/litecoin/address/ltc1qhvt82z3308nr2gmpfuhldmu9cw3d943n7lf2we"]}},"created_at":"2024-12-02T19:30:28.000Z","updated_at":"2025-03-09T08:05:14.000Z","dependencies_parsed_at":"2025-02-02T20:24:31.835Z","dependency_job_id":"991fc780-b257-444a-8782-43e3fb9bb45e","html_url":"https://github.com/HumanjavaEnterprises/nostr-auth-middleware","commit_stats":null,"previous_names":["humanjavaenterprises/nostr-auth-middleware"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/HumanjavaEnterprises/nostr-auth-middleware","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HumanjavaEnterprises%2Fnostr-auth-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HumanjavaEnterprises%2Fnostr-auth-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HumanjavaEnterprises%2Fnostr-auth-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HumanjavaEnterprises%2Fnostr-auth-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HumanjavaEnterprises","download_url":"https://codeload.github.com/HumanjavaEnterprises/nostr-auth-middleware/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HumanjavaEnterprises%2Fnostr-auth-middleware/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259719717,"owners_count":22901239,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","decentralized-protocols","event-validation","jwt","middleware","nostr","security","supabase","web-applications"],"created_at":"2025-01-07T02:07:23.404Z","updated_at":"2025-06-13T21:06:00.503Z","avatar_url":"https://github.com/HumanjavaEnterprises.png","language":"TypeScript","funding_links":["https://github.com/sponsors/humanjavaenterprises","https://getalby.com/p/vveerrgg","https://blockchair.com/bitcoin/address/bc1qw6kasfudkd64sts2q5a0lpm8zgea9txjc4gxj7","https://blockchair.com/litecoin/address/ltc1qhvt82z3308nr2gmpfuhldmu9cw3d943n7lf2we"],"categories":[],"sub_categories":[],"readme":"# Nostr Auth Middleware\n\nA focused, security-first authentication middleware for Nostr applications.\n\n## Requirements\n\n- Node.js ≥18.0.0 (Active LTS versions only)\n- npm ≥7.0.0\n\n## Installation\n\n```bash\nnpm install nostr-auth-middleware\n```\n\n**Important Security Notice**\n\nThis library handles cryptographic keys and authentication tokens that are critical for securing your Nostr application and user data. Any private keys (`nsec`) or authentication tokens must be stored and managed with the utmost security and care.\n\nDevelopers using this middleware must inform their users about the critical nature of managing private keys and tokens. It is the user's responsibility to securely store and manage these credentials. The library and its authors disclaim any responsibility or liability for lost keys, compromised tokens, or data resulting from mismanagement.\n\n## Usage\n\n### ESM (Recommended)\n```javascript\nimport { NostrAuthMiddleware } from 'nostr-auth-middleware';\n```\n\n### CommonJS\n```javascript\nconst { NostrAuthMiddleware } = require('nostr-auth-middleware');\n```\n\n### Browser\n```html\n\u003cscript src=\"dist/browser/nostr-auth-middleware.min.js\"\u003e\u003c/script\u003e\n\u003cscript\u003e\n  const auth = new NostrAuthMiddleware.NostrBrowserAuth();\n\u003c/script\u003e\n```\n\n## Project Philosophy\n\nThis middleware follows key principles that promote security, auditability, and simplicity:\n\n### 1. Single Responsibility\n- **Authentication Only**: Handles only Nostr key-based authentication\n- **No Business Logic**: Business rules, user tiers, and application logic belong in your API layer\n- **Simple JWT**: Issues basic JWTs with minimal claims (npub, timestamp)\n\n### 2. Security First\n- **Open Source**: Fully auditable security-critical code\n- **Transparent**: Clear, readable implementation\n- **Focused Scope**: Does one thing well - Nostr authentication\n\n### 3. Integration Ready\n```\n+---------------+\n|  Client App  |\n+-------+-------+\n        |\n        v\n+---------------+\n| Nostr Auth    | \u003c-- This Service\n|  Service      |     Simple Auth Only\n+-------+-------+\n        |\n        v\n+---------------+\n| App Platform  | \u003c-- Your Business Logic\n|    API        |     User Tiers\n+---------------+     Rate Limits\n```\n\n## Core Features\n\n- Authentication: NIP-07 Compatible Authentication\n- Enrollment: Secure User Enrollment with Nostr\n- Validation: Comprehensive Event Validation\n- Cryptography: Advanced Cryptographic Operations\n- Data Persistence: Supabase Integration for Data Persistence\n- Session Management: JWT-based Session Management\n- Profile Management: Profile Management \u0026 Synchronization\n- Logging and Monitoring: Detailed Logging and Monitoring\n- Key Management: Automatic Key Management\n- Deployment: Environment-Aware Deployment\n- Modes: Development \u0026 Production Modes\n- Directory Management: Automated Directory Management\n\n## JWT Configuration \u0026 Usage\n\n### Basic Setup\n```javascript\nconst auth = new NostrAuthMiddleware({\n  jwtSecret: process.env.JWT_SECRET,  // Required in production\n  expiresIn: '24h'                    // Optional, defaults to '24h'\n});\n```\n\n### Environment-Specific Behavior\n- **Production**: JWT_SECRET is required. The middleware will throw an error if not provided\n- **Development**: A default development-only secret is used if JWT_SECRET is not provided (not secure for production use)\n\n### JWT Operations\n\n#### Token Generation\n```javascript\n// Generate a JWT token with minimal claims\nconst token = await auth.generateToken({ pubkey });\n\n// The generated token includes:\n// - pubkey (npub)\n// - iat (issued at timestamp)\n// - exp (expiration timestamp)\n```\n\n#### Token Verification\n```javascript\n// Verify a JWT token\nconst isValid = await auth.verifyToken(token);\nif (isValid) {\n  // Token is valid, proceed with authentication\n}\n```\n\n### Browser Compatibility\n\nThe middleware is fully compatible with modern browsers and works seamlessly with build tools like Vite, Webpack, and Rollup. When using in a browser environment:\n\n1. **Import the Package**\n```javascript\nimport { NostrAuthMiddleware } from 'nostr-auth-middleware';\n```\n\n2. **Initialize with Environment Variables**\n```javascript\nconst auth = new NostrAuthMiddleware({\n  jwtSecret: import.meta.env.VITE_JWT_SECRET,  // For Vite\n  // or\n  jwtSecret: process.env.REACT_APP_JWT_SECRET  // For Create React App\n});\n```\n\n3. **Handle Browser-Specific Features**\n- Automatically detects and uses browser's localStorage for session management\n- Compatible with browser-based Nostr extensions (nos2x, Alby)\n- Handles browser-specific cryptographic operations\n\n### Security Best Practices\n\n1. **JWT Secret Management**\n   - Use a strong, unique secret for JWT signing\n   - Never expose the JWT secret in client-side code\n   - Rotate secrets periodically in production\n\n2. **Token Storage**\n   - Store tokens securely using browser's localStorage or sessionStorage\n   - Clear tokens on logout\n   - Implement token refresh mechanisms for long-lived sessions\n\n3. **Environment Variables**\n   - Use different JWT secrets for development and production\n   - Configure appropriate token expiration times\n   - Implement proper error handling for token validation\n\n## Session Management\n\n### Browser Session Verification\n```javascript\n// Verify if a user's session is still valid\nconst isValid = await auth.verifySession(userPubkey);\nif (isValid) {\n  console.log('Session is valid');\n} else {\n  console.log('Session is invalid or expired');\n  // Handle logout\n}\n```\n\nThe session verification:\n- Checks if the Nostr extension is still available\n- Verifies the public key matches\n- Handles disconnection gracefully\n- Works in both browser and server environments\n\n### Development Mode\nWhen running in development mode, the middleware provides detailed logging:\n```javascript\n// Development mode logs\nCached Profile: { /* profile data */ }\nFresh Profile: { /* profile and event data */ }\nProfile Cache Hit: { pubkey, cacheAge }\nProfile Cache Expired: { pubkey, cacheAge }\nProfile Cached: { pubkey, profile }\nProfile Cache Cleared: { pubkey }\n```\n\n## Documentation\n\n- [Architecture Guide](docs/architecture-guide.md) - Understanding the service architecture\n- [Key Management Guide](docs/key-management.md) - Comprehensive key management documentation\n- [Deployment Guide](docs/deployment-guide.md) - Environment-specific deployment instructions\n- [Getting Started](docs/getting-started.md) - Quick start guide\n- [Authentication Flow](docs/authentication-flow.md) - Detailed authentication process\n- [Troubleshooting Guide](docs/troubleshooting.md) - Common issues and solutions\n- [API Documentation](docs/api.md) - API endpoints and usage\n- [Security Guide](docs/security.md) - Security best practices and considerations\n- [Automated Tests](docs/automated-tests.md) - Comprehensive test suite documentation\n- [TypeScript Guide](docs/typescript.md) - TypeScript declaration patterns and best practices\n- [Browser Authentication](docs/browser-authentication.md) - Browser-based authentication flow\n\n### TypeScript Declaration Pattern\n\nFor browser-specific TypeScript declarations, we follow a top-level pattern that avoids module augmentation blocks:\n\n```typescript\n// Define interfaces and types at top level\ninterface NostrAuthConfig { ... }\ninterface NostrEvent { ... }\n\n// Declare classes at top level\ndeclare class NostrAuthClient { ... }\n\n// Global augmentations after type definitions\ndeclare global {\n  interface Window {\n    NostrAuthMiddleware: typeof NostrAuthClient;\n  }\n}\n\n// Single export at the end\nexport = NostrAuthClient;\n```\n\nThis pattern ensures better IDE support and cleaner type declarations. For more details, see our [TypeScript Guide](docs/typescript.md).\n\n## Browser Authentication\n\nFor client-side applications, we provide a lightweight browser-based authentication flow using NIP-07. This implementation works directly with Nostr browser extensions like nos2x or Alby.\n\n### Example Usage\n\n```typescript\n// Browser\nconst auth = new NostrAuthMiddleware.NostrBrowserAuth({\n  customKind: 22242,  // Optional: custom event kind\n  timeout: 30000      // Optional: timeout in milliseconds\n});\n\n// Get user's public key\nconst publicKey = await auth.getPublicKey();\n\n// Sign a challenge\nconst challenge = await auth.signChallenge();\n\n// Verify a session\nconst isValid = await auth.validateSession(session);\n```\n\n## Development Mode\n\nFeatures enabled in development mode:\n- Hot-reloading enabled\n- Detailed logging\n- No root permissions required\n\n## Production Mode\n\nAdditional features in production mode:\n- Enhanced security checks\n- Performance optimizations\n- Minimal logging\n- Production-ready JWT configuration\n\n## Contributing\n\nPlease see our [Contributing Guide](CONTRIBUTING.md) for details on our code of conduct and the process for submitting pull requests.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Security\n\nFor security issues, please see our [Security Policy](SECURITY.md) and report any vulnerabilities responsibly.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhumanjavaenterprises%2Fnostr-auth-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhumanjavaenterprises%2Fnostr-auth-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhumanjavaenterprises%2Fnostr-auth-middleware/lists"}