Skip to content

Commit e72093c

Browse files
committed
Initial commit: Basic Nostr Magic Link middleware implementation
- Implemented NostrService for handling DM operations - Added MagicLinkService for token management - Created Express middleware for handling magic link requests - Added comprehensive test suite with mocks - Added documentation for testing Nostr services - Basic security features implemented (token expiry, validation) - TypeScript support with proper type definitions
0 parents  commit e72093c

34 files changed

+9022
-0
lines changed

.env.example

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Server Configuration
2+
NODE_ENV=development
3+
PORT=3003 # Using 3003 since 3000 (relay), 3001 (IPFS), and 3002 (auth) are taken
4+
5+
# CORS Configuration
6+
CORS_ORIGINS=http://localhost:3000,http://localhost:3001,http://localhost:3002,http://localhost:3003
7+
8+
# Nostr Configuration
9+
NOSTR_RELAYS=wss://relay.maiqr.app,wss://relay.damus.io,wss://relay.nostr.band
10+
NOSTR_PRIVATE_KEY= # Bot's private key in hex format (64 chars)
11+
NOSTR_PUBLIC_KEY= # Bot's public key in hex format (64 chars)
12+
13+
# Magic Link Configuration
14+
MAGIC_LINK_BASE_URL=http://localhost:3003/auth
15+
MAGIC_LINK_EXPIRY=300000 # 5 minutes in milliseconds
16+
17+
# JWT Configuration
18+
JWT_SECRET=your_jwt_secret_key
19+
JWT_EXPIRES_IN=24h
20+
21+
# API Platform Integration
22+
API_PLATFORM_URL=http://localhost:8000
23+
API_PLATFORM_JWT_PUBLIC_KEY=
24+
25+
# Logging
26+
LOG_LEVEL=info # debug, info, warn, error
27+
LOG_DIR=logs # Directory for log files
28+
29+
# Test Configuration
30+
AUTH_HOST=http://localhost:3003 # Used by test scripts
31+
TEST_PUBKEY= # Your test public key for running integration tests
32+
33+
# Security Configuration
34+
API_KEYS=your_api_key_1,your_api_key_2 # Comma-separated list of valid API keys
35+
RATE_LIMIT_WINDOW_MS=900000 # 15 minutes in milliseconds
36+
RATE_LIMIT_MAX_REQUESTS=100 # Maximum requests per window
37+
TRUSTED_PROXIES=127.0.0.1,::1 # Comma-separated list of trusted proxy IPs
38+
39+
# Development Mode (Optional)
40+
TEST_MODE=true # Set to false in production

.github/FUNDING.yml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# These are supported funding model platforms
2+
3+
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4+
patreon: # Replace with a single Patreon username
5+
open_collective: # Replace with a single Open Collective username
6+
ko_fi: # Replace with a single Ko-fi username
7+
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8+
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9+
liberapay: # Replace with a single Liberapay username
10+
issuehunt: # Replace with a single IssueHunt username
11+
otechie: # Replace with a single Otechie username
12+
custom: [
13+
'https://getalby.com/p/vveerrgg', # Lightning address
14+
'https://blockchair.com/bitcoin/address/bc1qw6kasfudkd64sts2q5a0lpm8zgea9txjc4gxj7', # Bitcoin address
15+
'https://blockchair.com/litecoin/address/ltc1qhvt82z3308nr2gmpfuhldmu9cw3d943n7lf2we' # Litecoin address
16+
] # Up to 4 custom sponsorship URLs

.gitignore

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Dependencies
2+
node_modules/
3+
npm-debug.log*
4+
yarn-debug.log*
5+
yarn-error.log*
6+
7+
# Build output
8+
dist/
9+
build/
10+
*.tsbuildinfo
11+
12+
# Environment variables
13+
.env
14+
.env.local
15+
.env.*.local
16+
17+
# IDE and editor files
18+
.idea/
19+
.vscode/
20+
*.swp
21+
*.swo
22+
.DS_Store
23+
24+
# Test coverage
25+
coverage/
26+
27+
# Logs
28+
logs/
29+
*.log
30+
31+
# Runtime data
32+
pids/
33+
*.pid
34+
*.seed
35+
*.pid.lock
36+
37+
# Optional npm cache directory
38+
.npm
39+
40+
# Optional eslint cache
41+
.eslintcache
42+
43+
# Optional REPL history
44+
.node_repl_history
45+
46+
# Output of 'npm pack'
47+
*.tgz
48+
49+
# Yarn Integrity file
50+
.yarn-integrity

.keys/jwt_secret

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
cc311501dc56dd5212ead538f5b36ab7cafe951608a91b8a46c0b8ac11ad
2+
87d2

.keys/nostr_private_key

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
c75ddaf00f239f0676a6b890a8f5c3e87ff5ef23ccbc9513f48b9e6c068a
2+
46ca

CONTRIBUTING.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Contributing to nostr-dm-magiclink-middleware
2+
3+
We love your input! We want to make contributing to nostr-dm-magiclink-middleware as easy and transparent as possible, whether it's:
4+
5+
- Reporting a bug
6+
- Discussing the current state of the code
7+
- Submitting a fix
8+
- Proposing new features
9+
- Becoming a maintainer
10+
11+
## We Develop with Github
12+
We use GitHub to host code, to track issues and feature requests, as well as accept pull requests.
13+
14+
## We Use [Github Flow](https://guides.github.com/introduction/flow/index.html)
15+
Pull requests are the best way to propose changes to the codebase. We actively welcome your pull requests:
16+
17+
1. Fork the repo and create your branch from `main`.
18+
2. If you've added code that should be tested, add tests.
19+
3. If you've changed APIs, update the documentation.
20+
4. Ensure the test suite passes.
21+
5. Make sure your code lints.
22+
6. Issue that pull request!
23+
24+
## Any contributions you make will be under the MIT Software License
25+
In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern.
26+
27+
## Report bugs using Github's [issue tracker](https://github.com/HumanjavaEnterprises/nostr-dm.magiclink-middleware/issues)
28+
We use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/HumanjavaEnterprises/nostr-dm.magiclink-middleware/issues/new); it's that easy!
29+
30+
## Write bug reports with detail, background, and sample code
31+
32+
**Great Bug Reports** tend to have:
33+
34+
- A quick summary and/or background
35+
- Steps to reproduce
36+
- Be specific!
37+
- Give sample code if you can.
38+
- What you expected would happen
39+
- What actually happens
40+
- Notes (possibly including why you think this might be happening, or stuff you tried that didn't work)
41+
42+
## License
43+
By contributing, you agree that your contributions will be licensed under its MIT License.
44+
45+
## References
46+
This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md).

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024 HumanjavaEnterprises
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# Nostr DM Magic Link Middleware
2+
3+
[![License](https://img.shields.io/npm/l/nostr-dm-magiclink-middleware)](https://github.com/HumanjavaEnterprises/nostr-dm.magiclink-middleware/blob/main/LICENSE)
4+
[![npm](https://img.shields.io/npm/v/nostr-dm-magiclink-middleware)](https://www.npmjs.com/package/nostr-dm-magiclink-middleware)
5+
[![GitHub issues](https://img.shields.io/github/issues/HumanjavaEnterprises/nostr-dm.magiclink-middleware)](https://github.com/HumanjavaEnterprises/nostr-dm.magiclink-middleware/issues)
6+
[![GitHub stars](https://img.shields.io/github/stars/HumanjavaEnterprises/nostr-dm.magiclink-middleware)](https://github.com/HumanjavaEnterprises/nostr-dm.magiclink-middleware/stargazers)
7+
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0-blue)](https://www.typescriptlang.org/)
8+
[![Node Version](https://img.shields.io/node/v/nostr-dm-magiclink-middleware)](https://nodejs.org/)
9+
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://makeapullrequest.com)
10+
11+
A middleware for handling magic link authentication via Nostr DMs. This package provides a secure way to implement passwordless authentication using Nostr's direct messaging system.
12+
13+
## Features
14+
15+
- 🔐 Secure magic link generation and verification
16+
- 📨 Delivery via encrypted Nostr DMs
17+
- 🔑 Built-in session management
18+
- 🚀 Easy integration with Express.js
19+
- 📦 TypeScript support
20+
- ⚡ Async/await API
21+
22+
## Installation
23+
24+
```bash
25+
npm install nostr-dm-magiclink-middleware
26+
```
27+
28+
## Quick Start
29+
30+
```typescript
31+
import express from 'express';
32+
import { createNostrMagicLink } from 'nostr-dm-magiclink-middleware';
33+
34+
const app = express();
35+
app.use(express.json());
36+
37+
// Initialize the middleware
38+
const magicLink = createNostrMagicLink({
39+
privateKey: process.env.NOSTR_PRIVATE_KEY!, // Your bot's private key
40+
baseUrl: 'https://your-app.com/auth', // Your auth endpoint base URL
41+
relayUrl: 'wss://relay.damus.io', // Optional: custom relay URL
42+
tokenExpiry: 5 * 60 * 1000 // Optional: token expiry in ms (default: 5 minutes)
43+
});
44+
45+
// Endpoint to initiate login
46+
app.post('/auth/login', magicLink.initiate);
47+
48+
// Endpoint to verify magic link
49+
app.get('/auth/verify', magicLink.verify, (req, res) => {
50+
// User is now verified
51+
const { npub, sessionId } = req.nostr;
52+
53+
// Create user session, JWT, etc.
54+
res.json({
55+
success: true,
56+
message: 'Authentication successful',
57+
npub
58+
});
59+
});
60+
61+
// Cleanup when shutting down
62+
process.on('SIGTERM', async () => {
63+
await magicLink.cleanup();
64+
});
65+
```
66+
67+
## How It Works
68+
69+
1. User requests login with their Nostr public key (npub)
70+
2. Middleware generates a secure magic link
71+
3. Link is sent via encrypted Nostr DM to the user
72+
4. User clicks the link in their Nostr client
73+
5. Middleware verifies the link and authenticates the user
74+
75+
## Security Features
76+
77+
- ✅ Encrypted DMs using NIP-04
78+
- ✅ One-time use tokens
79+
- ✅ Configurable token expiry
80+
- ✅ Session-based verification
81+
- ✅ Automatic cleanup of expired sessions
82+
83+
## Advanced Usage
84+
85+
You can also use the services directly for more custom implementations:
86+
87+
```typescript
88+
import { NostrService, MagicLinkService } from 'nostr-dm-magiclink-middleware';
89+
90+
// Use NostrService directly for DM functionality
91+
const nostr = new NostrService(privateKey, relayUrl);
92+
93+
// Use MagicLinkService for custom magic link handling
94+
const magicLink = new MagicLinkService(privateKey, baseUrl, relayUrl);
95+
```
96+
97+
## Documentation
98+
99+
For detailed documentation, check out:
100+
101+
- [Testing Nostr Services](docs/testing-nostr-services.md) - Learn about testing strategies, common challenges, and best practices for testing Nostr services
102+
- [API Reference](docs/api-reference.md) - Detailed API documentation
103+
- [Security Guide](docs/security-guide.md) - Security best practices and considerations
104+
105+
## Contributing
106+
107+
Contributions are welcome! Please feel free to submit a Pull Request.
108+
109+
## License
110+
111+
MIT License - see LICENSE file for details

0 commit comments

Comments
 (0)