nostr-auth-middleware 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,49 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.2.6] - 2023-12-05
9
+
10
+ ### Added
11
+ - New TypeScript interfaces in `interfaces/nostr.interface.ts` for better type safety
12
+ - More comprehensive event validation with detailed error messages
13
+
14
+ ### Enhanced
15
+ - Improved event validation with stricter type checking
16
+ - Better error handling and logging in event validator
17
+ - Updated to use latest crypto utilities
18
+
19
+ ## [0.2.5] - 2024-01-09
20
+
21
+ ### Changed
22
+ - Updated to use published versions of @humanjavaenterprises/nostr-crypto-utils@0.2.0 and @humanjavaenterprises/nostr-nsec-seedphrase-library@0.2.0
23
+ - Updated key generation to use new generateKeyPairWithSeed function from nostr-nsec-seedphrase-library
24
+
25
+ ## [0.2.3] - 2023-12-06
26
+
27
+ ### Added
28
+ - Comprehensive test suite with 94.8% coverage
29
+ - Tests for challenge generation and verification
30
+ - Tests for profile fetching
31
+ - Tests for enrollment and verification
32
+ - Tests for error handling
33
+ - Tests for router integration
34
+
35
+ ### Changed
36
+ - Updated README with testing documentation
37
+ - Improved error handling in middleware
38
+ - Enhanced TypeScript type safety
39
+
40
+ ## [0.2.2] - Previous Release
41
+
42
+ ### Added
43
+ - Initial implementation of Nostr authentication middleware
44
+ - NIP-07 compatible authentication
45
+ - Secure user enrollment with Nostr
46
+ - Comprehensive event validation
47
+ - Advanced cryptographic operations
48
+ - Supabase integration for data persistence
49
+ - JWT-based session management
@@ -0,0 +1,203 @@
1
+ # Development Guide
2
+
3
+ ## Strategy and Architecture
4
+
5
+ ### Purpose
6
+ 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.
7
+
8
+ ### Core Architecture Principles
9
+
10
+ #### 1. Single Responsibility
11
+ - **Authentication Only**: Middleware focuses solely on Nostr key-based authentication
12
+ - **No Business Logic**: Business rules, user tiers, and application logic belong in the API layer
13
+ - **Simple JWT**: Issues basic JWTs with minimal claims (npub, timestamp)
14
+
15
+ #### 2. Security First
16
+ - **Open Source**: Fully auditable security-critical code
17
+ - **Transparent**: Clear, readable implementation
18
+ - **Focused Scope**: Does one thing well - Nostr authentication
19
+
20
+ #### 3. Integration Architecture
21
+ ```plaintext
22
+ ┌─────────────────┐
23
+ │ Client App │
24
+ └────────┬────────┘
25
+
26
+
27
+ ┌─────────────────┐
28
+ │ Nostr Auth │ ◄── This Service
29
+ │ Service │ Simple Auth Only
30
+ └────────┬────────┘
31
+
32
+
33
+ ┌─────────────────┐
34
+ │ App Platform │ ◄── Your Business Logic
35
+ │ API │ User Tiers
36
+ └─────────────────┘ Rate Limits
37
+ ```
38
+
39
+ #### 4. Environment-Aware Design
40
+ ##### Development Mode Features
41
+ - Local directory structure
42
+ - Auto-generated test keys
43
+ - In-memory data storage option
44
+ - Hot-reloading enabled
45
+ - Detailed logging
46
+ - No root permissions required
47
+
48
+ ##### Production Mode Features
49
+ - System-level directory structure
50
+ - Secure key management via Supabase
51
+ - Proper file permissions
52
+ - Log rotation and compression
53
+ - Automatic backups
54
+ - Rate limiting
55
+ - IP whitelisting
56
+
57
+ ## Development Checklist
58
+
59
+ ### Version Requirements
60
+ - [ ] Specify Node.js version requirements:
61
+ ```json
62
+ {
63
+ "engines": {
64
+ "node": ">=18.0.0" // Only support active LTS versions
65
+ }
66
+ }
67
+ ```
68
+ - [ ] Document version requirements in README.md
69
+ - [ ] Configure CI to test only supported versions
70
+ - [ ] Remove legacy version support and polyfills
71
+
72
+ ### Package Configuration
73
+ - [ ] Configure package.json exports properly:
74
+ ```json
75
+ {
76
+ "exports": {
77
+ ".": {
78
+ "types": "./dist/types/index.d.ts", // Types must come first
79
+ "import": "./dist/esm/index.js",
80
+ "require": "./dist/cjs/index.js"
81
+ }
82
+ }
83
+ }
84
+ ```
85
+ - [ ] Include standard fields at root level:
86
+ - [ ] "main" for CommonJS entry
87
+ - [ ] "module" for ESM entry
88
+ - [ ] "types" for TypeScript types
89
+ - [ ] "browser" for browser bundles
90
+
91
+ ### Module System Strategy
92
+
93
+ #### Hybrid Module Support (ESM/CommonJS)
94
+ - Package supports both ESM and CommonJS through dual publishing
95
+ - Entry points defined in package.json:
96
+ ```json
97
+ {
98
+ "main": "./dist/cjs/index.js", // CommonJS
99
+ "module": "./dist/esm/index.js", // ESM
100
+ "types": "./dist/types/index.d.ts" // TypeScript
101
+ }
102
+ ```
103
+ - Browser bundle available at `dist/browser/nostr-auth-middleware.min.js`
104
+
105
+ #### TypeScript Declaration Patterns
106
+ - Browser-specific declarations in `browser.d.ts` follow top-level pattern:
107
+ ```typescript
108
+ // Define interfaces and types at top level
109
+ interface NostrAuthConfig { ... }
110
+ interface NostrEvent { ... }
111
+
112
+ // Declare classes at top level
113
+ declare class NostrAuthClient { ... }
114
+
115
+ // Global augmentations after type definitions
116
+ declare global {
117
+ interface Window {
118
+ NostrAuthMiddleware: typeof NostrAuthClient;
119
+ }
120
+ }
121
+
122
+ // Single export at the end
123
+ export = NostrAuthClient;
124
+ ```
125
+ - Avoid module augmentation blocks (`declare module`) in browser declarations
126
+ - Keep type definitions close to their implementation files
127
+
128
+ ### Build Configuration
129
+
130
+ #### TypeScript Configuration
131
+ - [ ] Use `NodeNext` for both `module` and `moduleResolution` in tsconfig.json
132
+ - [ ] Include `tslib` in dependencies for TypeScript helpers
133
+ - [ ] Use `.js` extensions in import statements (TypeScript convention for ESM)
134
+ - [ ] Configure separate tsconfig files for different build targets (browser, CJS, ESM)
135
+ - [ ] Handle type definitions:
136
+ - [ ] Consider inlining small type definitions instead of separate files
137
+ - [ ] Use declaration merging for global types (e.g., window object)
138
+
139
+ #### Webpack Configuration
140
+ - [ ] Configure proper module resolution:
141
+ - [ ] Add `.js` extension alias for `.ts` files
142
+ - [ ] Handle `.d.ts` files appropriately (use ignore-loader)
143
+ - [ ] Set up Node.js polyfills or fallbacks for browser environment
144
+ - [ ] Configure TypeScript loader:
145
+ - [ ] Use `ts-loader` with appropriate options
146
+ - [ ] Enable `transpileOnly` for faster builds
147
+ - [ ] Set correct module resolution strategy
148
+ - [ ] Handle external dependencies properly:
149
+ - [ ] Mark Node.js-only packages as external
150
+ - [ ] Configure fallbacks for Node.js core modules
151
+
152
+ ### Build Process
153
+ - [ ] Test builds before committing changes:
154
+ ```bash
155
+ npm run build && npm test
156
+ ```
157
+ - [ ] Verify all build targets work:
158
+ - [ ] TypeScript declarations
159
+ - [ ] CommonJS build
160
+ - [ ] ESM build
161
+ - [ ] Browser bundle
162
+ - [ ] Check bundle size and consider optimizations if needed
163
+ - [ ] Ensure source maps are generated correctly
164
+
165
+ ### Testing
166
+ - [ ] Configure test environment properly:
167
+ - [ ] Set up test globals
168
+ - [ ] Configure coverage reporting
169
+ - [ ] Ensure tests run in both ESM and CommonJS environments
170
+ - [ ] Test browser bundle in different environments
171
+ - [ ] Run tests across supported Node.js versions
172
+ - [ ] Verify package exports work in different environments
173
+
174
+ ### Development Workflow
175
+ - [ ] Run builds and tests before committing changes
176
+ - [ ] Update documentation when making significant changes
177
+ - [ ] Keep track of bundle size and performance impacts
178
+ - [ ] Document any workarounds or special configurations
179
+
180
+ ### Browser Integration
181
+ - [ ] Test browser bundle in different environments
182
+ - [ ] Verify global object access works correctly
183
+ - [ ] Check for any Node.js-specific code that needs browser alternatives
184
+ - [ ] Ensure proper error handling for browser-specific features
185
+
186
+ ### Dependencies
187
+ - [ ] Keep dependencies up to date
188
+ - [ ] Document any specific version requirements
189
+ - [ ] Consider the impact of dependencies on bundle size
190
+ - [ ] Use appropriate dependency types (dependencies vs devDependencies)
191
+ - [ ] Include necessary TypeScript helpers (e.g., tslib)
192
+
193
+ ### Common Issues and Solutions
194
+
195
+ #### Type assertions and casting:
196
+ - [ ] Avoid using `as unknown as Type` when possible
197
+ - [ ] Create proper type guards for runtime checks
198
+ - [ ] Use type predicates for narrowing types
199
+
200
+ #### External library types:
201
+ - [ ] Maintain proper type definitions for external libraries
202
+ - [ ] Use declaration merging for extending third-party types
203
+ - [ ] Document any type-related workarounds or limitations
@@ -0,0 +1,178 @@
1
+ # Working with AI: Collaborative Development Guide
2
+
3
+ ## Introduction
4
+
5
+ This guide outlines best practices for collaborating with AI Language Models (LLMs) in software development, based on our successful experience building the nostr-auth-middleware package. It aims to help developers maximize the benefits of AI pair programming while maintaining code quality and security.
6
+
7
+ ## Key Principles
8
+
9
+ ### 1. Iterative Development
10
+ - Start with small, well-defined tasks
11
+ - Build incrementally with continuous validation
12
+ - Let the AI help refactor and improve code quality
13
+ - Use the AI to help maintain consistency across the codebase
14
+
15
+ ### 2. Clear Communication
16
+ - Be specific about requirements and constraints
17
+ - Share context about the broader system
18
+ - Ask for explanations when changes aren't clear
19
+ - Use the AI to document decisions and rationale
20
+
21
+ ### 3. Quality Control
22
+ - Always review AI-generated code
23
+ - Run tests after each significant change
24
+ - Use the AI to help write and improve tests
25
+ - Let the AI help with code reviews
26
+
27
+ ## Effective Collaboration Patterns
28
+
29
+ ### 1. Setting Up the Project
30
+ ```markdown
31
+ Good: "Let's set up a TypeScript project with ESM and CommonJS support, including proper build configuration."
32
+ Bad: "Create a new project for me."
33
+ ```
34
+
35
+ ### 2. Implementing Features
36
+ ```markdown
37
+ Good: "We need to implement JWT token generation with these specific claims: [x, y, z]"
38
+ Bad: "Add authentication to the project"
39
+ ```
40
+
41
+ ### 3. Testing and Debugging
42
+ ```markdown
43
+ Good: "These specific tests are failing with this error message: [error]. Can you help debug?"
44
+ Bad: "Fix the tests"
45
+ ```
46
+
47
+ ## Best Practices
48
+
49
+ ### 1. Documentation
50
+ - Have the AI help maintain documentation alongside code changes
51
+ - Use the AI to generate detailed comments and JSDoc
52
+ - Ask the AI to explain complex parts of the codebase
53
+ - Keep a record of architectural decisions
54
+
55
+ ### 2. Code Quality
56
+ - Use the AI to identify potential improvements
57
+ - Ask for suggestions on code organization
58
+ - Have the AI help with type definitions
59
+ - Use the AI to ensure consistent coding style
60
+
61
+ ### 3. Testing
62
+ - Let the AI help write comprehensive tests
63
+ - Use the AI to identify edge cases
64
+ - Have the AI help with test organization
65
+ - Ask for help with test coverage improvements
66
+
67
+ ## Common Pitfalls to Avoid
68
+
69
+ ### 1. Over-Reliance
70
+ - Don't accept AI suggestions without review
71
+ - Maintain understanding of your codebase
72
+ - Keep security-critical decisions human-reviewed
73
+ - Verify generated code meets requirements
74
+
75
+ ### 2. Unclear Requirements
76
+ - Avoid vague or ambiguous requests
77
+ - Provide specific context when needed
78
+ - Be clear about constraints and limitations
79
+ - Share relevant error messages and logs
80
+
81
+ ### 3. Ignoring AI Capabilities
82
+ - Leverage AI for repetitive tasks
83
+ - Use AI for documentation generation
84
+ - Let AI help with code organization
85
+ - Take advantage of AI's pattern recognition
86
+
87
+ ## Real Examples from Our Project
88
+
89
+ ### 1. Build Configuration
90
+ ```typescript
91
+ // AI helped set up proper module exports
92
+ {
93
+ "exports": {
94
+ ".": {
95
+ "types": "./dist/types/index.d.ts",
96
+ "import": "./dist/esm/index.js",
97
+ "require": "./dist/cjs/index.js"
98
+ }
99
+ }
100
+ }
101
+ ```
102
+
103
+ ### 2. Test Implementation
104
+ ```typescript
105
+ // AI helped write clear, focused tests
106
+ describe('handleChallenge', () => {
107
+ it('should create and return a challenge', async () => {
108
+ await middleware.handleChallenge(
109
+ mockReq as Request,
110
+ mockRes as Response,
111
+ mockNext
112
+ );
113
+ expect(mockRes.json).toHaveBeenCalledWith({
114
+ challenge: mockChallenge
115
+ });
116
+ });
117
+ });
118
+ ```
119
+
120
+ ### 3. Error Handling
121
+ ```typescript
122
+ // AI helped implement proper error handling
123
+ try {
124
+ const challenge = await this.nostrService.createChallenge(pubkey);
125
+ res.json({ challenge });
126
+ } catch (error) {
127
+ logger.error('Error handling challenge:', {
128
+ error: error instanceof Error ? error.message : String(error)
129
+ });
130
+ next(error);
131
+ }
132
+ ```
133
+
134
+ ## Workflow Tips
135
+
136
+ ### 1. Development Cycle
137
+ 1. Define clear task objectives
138
+ 2. Let AI suggest implementation approach
139
+ 3. Review and refine AI's suggestions
140
+ 4. Implement with AI's assistance
141
+ 5. Test and validate changes
142
+ 6. Document with AI's help
143
+
144
+ ### 2. Code Review Process
145
+ 1. Have AI review code changes
146
+ 2. Ask for potential improvements
147
+ 3. Discuss trade-offs with AI
148
+ 4. Implement suggested improvements
149
+ 5. Verify changes meet standards
150
+
151
+ ### 3. Documentation Updates
152
+ 1. Ask AI to explain complex changes
153
+ 2. Have AI update relevant docs
154
+ 3. Review documentation accuracy
155
+ 4. Ensure docs match implementation
156
+ 5. Keep architecture docs current
157
+
158
+ ## Measuring Success
159
+
160
+ ### 1. Code Quality Metrics
161
+ - Passing tests
162
+ - Clean lint results
163
+ - Type safety
164
+ - Documentation coverage
165
+ - Code organization
166
+
167
+ ### 2. Development Velocity
168
+ - Faster implementation
169
+ - Fewer regressions
170
+ - Better test coverage
171
+ - Clearer documentation
172
+ - Consistent patterns
173
+
174
+ ## Conclusion
175
+
176
+ Working with AI can significantly enhance development productivity while maintaining high code quality. The key is to establish clear communication patterns, maintain proper review processes, and leverage AI's strengths while being mindful of its limitations.
177
+
178
+ Remember that AI is a powerful tool to augment human development capabilities, not replace human judgment. Use it wisely to improve code quality, maintain documentation, and accelerate development while keeping security and reliability as top priorities.
@@ -0,0 +1,97 @@
1
+ # Contributing to Nostr Auth Middleware
2
+
3
+ First off, thank you for considering contributing to Nostr Auth Middleware! It's people like you that make this tool better for everyone.
4
+
5
+ ## Code of Conduct
6
+
7
+ By participating in this project, you are expected to uphold our [Code of Conduct](CODE_OF_CONDUCT.md).
8
+
9
+ ## How Can I Contribute?
10
+
11
+ ### Reporting Bugs
12
+
13
+ Before creating bug reports, please check the issue list as you might find out that you don't need to create one. When you are creating a bug report, please include as many details as possible:
14
+
15
+ * Use a clear and descriptive title
16
+ * Describe the exact steps which reproduce the problem
17
+ * Provide specific examples to demonstrate the steps
18
+ * Describe the behavior you observed after following the steps
19
+ * Explain which behavior you expected to see instead and why
20
+ * Include any error messages or logs
21
+
22
+ ### Suggesting Enhancements
23
+
24
+ If you have a suggestion for a new feature or enhancement:
25
+
26
+ * Use a clear and descriptive title
27
+ * Provide a step-by-step description of the suggested enhancement
28
+ * Provide specific examples to demonstrate the steps
29
+ * Describe the current behavior and explain which behavior you expected to see instead
30
+ * Explain why this enhancement would be useful
31
+
32
+ ### Pull Requests
33
+
34
+ * Fill in the required template
35
+ * Do not include issue numbers in the PR title
36
+ * Follow the TypeScript styleguide
37
+ * Include thoughtfully-worded, well-structured tests
38
+ * Document new code
39
+ * End all files with a newline
40
+
41
+ ## Development Process
42
+
43
+ 1. Fork the repo
44
+ 2. Create a new branch from `main`:
45
+ ```bash
46
+ git checkout -b feature/your-feature-name
47
+ ```
48
+ 3. Make your changes
49
+ 4. Run the tests:
50
+ ```bash
51
+ npm test
52
+ ```
53
+ 5. Commit your changes using a descriptive commit message
54
+ 6. Push to your fork
55
+ 7. Submit a Pull Request
56
+
57
+ ## Pull Request Process
58
+
59
+ 1. Update the README.md with details of changes if needed
60
+ 2. Update the documentation with details of any changes to the interface
61
+ 3. The PR will be merged once you have the sign-off of at least one maintainer
62
+
63
+ ## Style Guides
64
+
65
+ ### Git Commit Messages
66
+
67
+ * Use the present tense ("Add feature" not "Added feature")
68
+ * Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
69
+ * Limit the first line to 72 characters or less
70
+ * Reference issues and pull requests liberally after the first line
71
+
72
+ ### TypeScript Style Guide
73
+
74
+ * Use TypeScript for all new code
75
+ * Follow the existing code style
76
+ * Use meaningful variable names
77
+ * Document complex code sections
78
+ * Add types for all parameters and return values
79
+
80
+ ### Documentation Style Guide
81
+
82
+ * Use Markdown
83
+ * Reference functions and classes with backticks: \`myFunction()\`
84
+ * Include code examples for new features
85
+ * Keep explanations clear and concise
86
+
87
+ ## Community
88
+
89
+ * Join our [Discord](https://discord.gg/your-invite-link)
90
+ * Follow us on [Twitter](https://twitter.com/your-handle)
91
+ * Read our [blog](https://your-blog-url.com)
92
+
93
+ ## Questions?
94
+
95
+ Feel free to open an issue with your question or reach out to the maintainers directly.
96
+
97
+ Thank you for contributing! 🚀
package/SECURITY.md ADDED
@@ -0,0 +1,36 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ We release patches for security vulnerabilities. Which versions are eligible for receiving such patches depends on the CVSS v3.0 Rating:
6
+
7
+ | CVSS v3.0 | Supported Versions |
8
+ | --------- | ---------------------------------------- |
9
+ | 9.0-10.0 | Releases within the last 6 months |
10
+ | 4.0-8.9 | Most recent release |
11
+
12
+ ## Reporting a Vulnerability
13
+
14
+ Please report security vulnerabilities to security@humanjavaenterprises.com.
15
+
16
+ The team will acknowledge your email within 48 hours, and will send a more detailed response within 72 hours indicating the next steps in handling your report.
17
+
18
+ After the initial reply to your report, the security team will endeavor to keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance.
19
+
20
+ ## Security Best Practices
21
+
22
+ When using this authentication middleware:
23
+
24
+ 1. Always use HTTPS in production
25
+ 2. Keep your JWT secret keys secure and rotate them regularly
26
+ 3. Set appropriate token expiration times
27
+ 4. Monitor for suspicious authentication patterns
28
+ 5. Keep the middleware and its dependencies up to date
29
+
30
+ ## Disclosure Policy
31
+
32
+ When the security team receives a security bug report, they will assign it to a primary handler. This person will coordinate the fix and release process.
33
+
34
+ ## Comments on this Policy
35
+
36
+ If you have suggestions on how this process could be improved please submit a pull request.