From 88a1976383435c433615b7c7383116e99928d715 Mon Sep 17 00:00:00 2001 From: vveerrgg Date: Sun, 2 Feb 2025 11:25:19 -0800 Subject: [PATCH 1/3] chore: add modernization checklist --- COLAB-DOCS/CHECKLIST.md | 59 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 COLAB-DOCS/CHECKLIST.md diff --git a/COLAB-DOCS/CHECKLIST.md b/COLAB-DOCS/CHECKLIST.md new file mode 100644 index 0000000..13a5f04 --- /dev/null +++ b/COLAB-DOCS/CHECKLIST.md @@ -0,0 +1,59 @@ +# Development Checklist and Notes + +## Package Structure +- Package should be set up as a hybrid CommonJS/ESM module +- Main entry points should be defined in package.json: + - CommonJS: `./dist/cjs/index.js` + - ESM: `./dist/esm/index.js` + - TypeScript types: `./dist/types/index.d.ts` + - Browser bundle: `./dist/browser/nostr-auth-middleware.min.js` + +## Build Process +1. Multiple build targets required: + - `npm run build:types` - Generate TypeScript declaration files + - `npm run build:cjs` - Build CommonJS modules + - `npm run build:esm` - Build ES modules + - `npm run build:browser` - Create browser bundles using webpack + - `npm run build` - Run all builds in sequence + +2. Build Configuration: + - ESM build must use Node16 module resolution + - All relative imports in ESM must include `.js` extensions + - Browser bundle should be configured with webpack + - Preserve all existing test and deployment scripts + +## Dependencies +1. External Dependencies: + - Replace local file dependencies with published versions: + - @humanjavaenterprises/nostr-crypto-utils + - @humanjavaenterprises/nostr-nsec-seedphrase-library + - Keep core dependencies up to date while maintaining compatibility + +2. Development Dependencies: + - Add webpack and related build tools + - Maintain existing test framework (Jest) + - Keep TypeScript and related tools + +## Module Resolution +1. TypeScript Configuration: + - Update tsconfig.json for dual CJS/ESM output + - Add separate configs for different build targets + - Maintain strict type checking + +2. Package Exports: + - Configure package.json exports field for proper resolution + - Support both import and require syntax + - Maintain TypeScript types accessibility + +## Testing Guidelines +1. Run full test suite after any build changes +2. Test all module formats: + - CommonJS (`require`) + - ESM (`import`) + - Browser bundle +3. Maintain existing test coverage + +## Deployment Process +1. Preserve all existing deployment scripts +2. Update CI/CD if needed for new build process +3. Maintain PM2 configuration From af63a87a40274c8003efe5b5a0029c6eb455fb76 Mon Sep 17 00:00:00 2001 From: vveerrgg Date: Sun, 2 Feb 2025 11:26:41 -0800 Subject: [PATCH 2/3] docs: add purpose statement to CHECKLIST.md --- COLAB-DOCS/CHECKLIST.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/COLAB-DOCS/CHECKLIST.md b/COLAB-DOCS/CHECKLIST.md index 13a5f04..74ecf35 100644 --- a/COLAB-DOCS/CHECKLIST.md +++ b/COLAB-DOCS/CHECKLIST.md @@ -1,3 +1,8 @@ +# Purpose +This CHECKLIST.md serves as an active memory document for the nostr-auth-middleware project. It is designed to maintain consistency across development sessions and AI collaboration sessions, ensuring that all contributors (human and AI) follow the same modernization guidelines and architectural decisions. This document should be consulted before making significant changes to the project structure or build system. + +--- + # Development Checklist and Notes ## Package Structure From 4d8795761aff49b55966b01897585c862ac86642 Mon Sep 17 00:00:00 2001 From: vveerrgg Date: Sun, 2 Feb 2025 11:43:45 -0800 Subject: [PATCH 3/3] docs: add comprehensive DEV-STRATEGY.md and update CHECKLIST.md - Add DEV-STRATEGY.md documenting architectural decisions and patterns - Update CHECKLIST.md with security and architectural requirements - Document environment-specific configurations and deployment processes - Add detailed testing and documentation requirements --- COLAB-DOCS/CHECKLIST.md | 93 +++++++++++---- COLAB-DOCS/DEV-STRATEGY.md | 224 +++++++++++++++++++++++++++++++++++++ 2 files changed, 298 insertions(+), 19 deletions(-) create mode 100644 COLAB-DOCS/DEV-STRATEGY.md diff --git a/COLAB-DOCS/CHECKLIST.md b/COLAB-DOCS/CHECKLIST.md index 74ecf35..3c461aa 100644 --- a/COLAB-DOCS/CHECKLIST.md +++ b/COLAB-DOCS/CHECKLIST.md @@ -5,6 +5,20 @@ This CHECKLIST.md serves as an active memory document for the nostr-auth-middlew # Development Checklist and Notes +## Core Requirements +1. Single Responsibility Principle + - [ ] New features must ONLY handle authentication-related functionality + - [ ] Business logic must remain in the API layer + - [ ] JWT claims must stay minimal (npub, timestamp only) + +2. Security Requirements + - [ ] No sensitive data in code or comments + - [ ] No hardcoded keys or secrets + - [ ] All cryptographic operations must use approved libraries + - [ ] Environment variables must be properly validated + - [ ] Security-critical code must include tests + - [ ] All authentication flows must be documented + ## Package Structure - Package should be set up as a hybrid CommonJS/ESM module - Main entry points should be defined in package.json: @@ -36,29 +50,70 @@ This CHECKLIST.md serves as an active memory document for the nostr-auth-middlew 2. Development Dependencies: - Add webpack and related build tools - - Maintain existing test framework (Jest) + - Maintain Vitest test framework - Keep TypeScript and related tools -## Module Resolution -1. TypeScript Configuration: - - Update tsconfig.json for dual CJS/ESM output - - Add separate configs for different build targets - - Maintain strict type checking +## Environment Handling +1. Development Mode Requirements + - [ ] Use local directory structure + - [ ] Enable detailed logging + - [ ] Support hot-reloading + - [ ] Use in-memory storage when appropriate -2. Package Exports: - - Configure package.json exports field for proper resolution - - Support both import and require syntax - - Maintain TypeScript types accessibility +2. Production Mode Requirements + - [ ] Implement proper file permissions + - [ ] Enable log rotation + - [ ] Configure rate limiting + - [ ] Set up IP whitelisting + - [ ] Enable automatic backups ## Testing Guidelines -1. Run full test suite after any build changes -2. Test all module formats: - - CommonJS (`require`) - - ESM (`import`) - - Browser bundle -3. Maintain existing test coverage +1. Test Coverage Requirements + - [ ] All security-critical code must have 100% coverage + - [ ] All authentication flows must have integration tests + - [ ] All API endpoints must have tests + - [ ] All error conditions must be tested + +2. Test Organization + - [ ] Unit tests in `src/__tests__` + - [ ] Integration tests using test scripts + - [ ] Live testing configurations separate + +## Documentation Requirements +1. Code Documentation + - [ ] All public APIs must have JSDoc comments + - [ ] All security-critical functions must be documented + - [ ] All configuration options must be documented + - [ ] All error conditions must be documented + +2. Architectural Documentation + - [ ] Update architecture diagrams when changing flows + - [ ] Document all environment variables + - [ ] Maintain security considerations section + - [ ] Update deployment instructions ## Deployment Process -1. Preserve all existing deployment scripts -2. Update CI/CD if needed for new build process -3. Maintain PM2 configuration +1. Pre-deployment Checklist + - [ ] All tests passing + - [ ] Security audit completed + - [ ] Environment variables validated + - [ ] Backup strategy confirmed + +2. Deployment Requirements + - [ ] Use PM2 for process management + - [ ] Configure proper directory permissions + - [ ] Set up log rotation + - [ ] Configure monitoring + +## Code Review Requirements +1. Security Checks + - [ ] No sensitive data exposure + - [ ] Proper error handling + - [ ] Input validation + - [ ] Rate limiting where needed + +2. Architecture Checks + - [ ] Maintains single responsibility + - [ ] No business logic in auth layer + - [ ] Proper separation of concerns + - [ ] Follows established patterns diff --git a/COLAB-DOCS/DEV-STRATEGY.md b/COLAB-DOCS/DEV-STRATEGY.md new file mode 100644 index 0000000..38c1390 --- /dev/null +++ b/COLAB-DOCS/DEV-STRATEGY.md @@ -0,0 +1,224 @@ +# Development Strategy + +## Purpose +This document outlines the key architectural decisions, development patterns, and modernization strategies for the nostr-auth-middleware project. It serves as a living document to help maintain consistency across development sessions and preserve the reasoning behind important technical decisions. + +## Core Architecture Principles + +### 1. Single Responsibility +- **Authentication Only**: Middleware focuses solely on Nostr key-based authentication +- **No Business Logic**: Business rules, user tiers, and application logic belong in the API layer +- **Simple JWT**: Issues basic JWTs with minimal claims (npub, timestamp) + +### 2. Security First +- **Open Source**: Fully auditable security-critical code +- **Transparent**: Clear, readable implementation +- **Focused Scope**: Does one thing well - Nostr authentication + +### 3. Integration Architecture +```plaintext +┌─────────────────┐ +│ Client App │ +└────────┬────────┘ + │ + ▼ +┌─────────────────┐ +│ Nostr Auth │ ◄── This Service +│ Service │ Simple Auth Only +└────────┬────────┘ + │ + ▼ +┌─────────────────┐ +│ App Platform │ ◄── Your Business Logic +│ API │ User Tiers +└─────────────────┘ Rate Limits +``` + +### 4. Environment-Aware Design +#### Development Mode Features +- Local directory structure +- Auto-generated test keys +- In-memory data storage option +- Hot-reloading enabled +- Detailed logging +- No root permissions required + +#### Production Mode Features +- System-level directory structure +- Secure key management via Supabase +- Proper file permissions +- Log rotation and compression +- Automatic backups +- Rate limiting +- IP whitelisting + +## Module System Strategy + +### Hybrid Module Support (ESM/CommonJS) +- Package supports both ESM and CommonJS through dual publishing +- Entry points defined in package.json: + ```json + { + "main": "./dist/cjs/index.js", // CommonJS + "module": "./dist/esm/index.js", // ESM + "types": "./dist/types/index.d.ts" // TypeScript + } + ``` +- Browser bundle available at `dist/browser/nostr-auth-middleware.min.js` + +### Import/Export Patterns +1. **Local Imports** + - Must include `.js` extension for ESM compatibility + - Example: `import { NostrService } from '../services/nostr.service.js'` + +2. **External Package Imports** + - Do not include `.js` extension + - Example: `import { hexToBytes } from '@noble/hashes/utils'` + +3. **Type Imports** + - Use explicit type imports for better tree-shaking + - Example: `import type { NostrAuthConfig } from './types/index.js'` + +## Testing Strategy + +### Vitest Over Jest +- Chose Vitest for: + - Native ESM support + - Better TypeScript integration + - Improved performance + - Modern tooling compatibility + - Simpler configuration + +### Test Organization +- Unit tests located in `src/__tests__` +- Integration tests in `scripts/test-auth.sh` +- Live testing via `scripts/test-auth-live.ts` + +## Build System + +### Multiple Build Targets +1. **TypeScript Declarations** + - Generated using `tsconfig.types.json` + - Outputs to `dist/types` + +2. **CommonJS Build** + - Uses `tsconfig.cjs.json` + - Outputs to `dist/cjs` + - Maintains backward compatibility + +3. **ESM Build** + - Uses `tsconfig.esm.json` + - Outputs to `dist/esm` + - Primary modern entry point + +4. **Browser Bundle** + - Generated using webpack + - UMD format for broad compatibility + - External dependencies properly configured + +## Type System + +### TypeScript Configuration +- Uses `"moduleResolution": "NodeNext"` for modern resolution +- Strict type checking enabled +- Separate configs for different build targets +- Preserves source maps and declaration maps + +### Type Exports +- Types available for both ESM and CommonJS +- Browser-specific type declarations +- Global type augmentation for UMD bundle + +## Development Workflow + +### Local Development +1. Use `npm run dev` for development server +2. Run `npm test` for Vitest test suite +3. Use `npm run build` to verify all build targets + +### Environment Configuration +```bash +# Core Configuration +NODE_ENV=development # development or production +DOMAIN=nostr-platform.app # your domain +SERVICE_NAME=auth # service identifier + +# Service URLs +AUTH_SERVICE_URL=http://localhost:3002 # becomes https://auth.your-domain.app +IPFS_SERVICE_URL=http://localhost:3001 # becomes https://ipfs.your-domain.app +RELAY_SERVICE_URL=http://localhost:3000 # becomes https://relay.your-domain.app + +# Security Configuration +SERVER_PRIVATE_KEY= # auto-generated if not provided +SERVER_PUBLIC_KEY= # auto-generated if not provided +JWT_SECRET=your_jwt_secret # required in production + +# Supabase Configuration +SUPABASE_PROJECT=your-project # project identifier +SUPABASE_URL=your_supabase_url # required in production +SUPABASE_KEY=your_supabase_key # required in production +``` + +### Directory Structure +#### Development +- Source code in `src/` +- Tests in `src/__tests__/` +- Build output in `dist/` +- Scripts in `scripts/` +- Documentation in `docs/` + +#### Production +- Deploy directory: `/opt/nostr-platform/auth` +- Backup directory: `/opt/backups/nostr` +- Log directory: `/var/log/nostr-platform` + +### Code Organization +- Core middleware in `src/middleware` +- Utilities in `src/utils` +- Types in `src/types` +- Services in `src/services` + +### Code Style +- ESLint configured for TypeScript +- Prettier for consistent formatting +- Enforced `.js` extensions in imports +- Explicit type imports/exports + +## Security Considerations +⚠️ **Critical Security Notes** +- Handles cryptographic keys and authentication tokens +- Private keys (`nsec`) and authentication tokens require secure storage +- Developers must inform users about key management responsibilities +- No hardcoding of sensitive values +- Regular security audits recommended + +## Deployment Strategy +### Scripts and Automation +- `startup.sh`: Service initialization and startup + - Environment detection + - Directory creation + - Permission setting + - Service startup +- `shutdown.sh`: Clean service shutdown + - Process termination + - Log rotation + - Cleanup operations +- `config.sh`: Configuration management + - Environment detection + - Variable validation + +### Process Management +- PM2 for process management +- Environment variables via dotenv +- Separate configurations for different environments +- Automated deployment scripts + +## Future Considerations +1. Browser bundle optimization +2. Additional type safety improvements +3. Performance monitoring +4. Integration with other Nostr tools +5. WebSocket support enhancement +6. Enhanced backup strategies +7. Advanced rate limiting options +8. Geographic distribution support