Skip to content

Commit 2897286

Browse files
Merge pull request #88 from jobbykings/feature/implement-backend-features
feat: Implement comprehensive backend features for SubStream Protocol
2 parents d9f7e26 + 164ba8a commit 2897286

File tree

13 files changed

+2279
-5
lines changed

13 files changed

+2279
-5
lines changed

.env.example

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Server Configuration
2+
PORT=3000
3+
NODE_ENV=development
4+
5+
# JWT Configuration
6+
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
7+
8+
# Pinata Configuration
9+
PINATA_API_KEY=your-pinata-api-key
10+
PINATA_SECRET_KEY=your-pinata-secret-key
11+
12+
# Web3.Storage Configuration
13+
WEB3STORAGE_API_KEY=your-web3-storage-api-key
14+
15+
# Infura IPFS Configuration
16+
INFURA_API_KEY=your-infura-api-key
17+
18+
# Database Configuration (for production)
19+
# DATABASE_URL=postgresql://username:password@localhost:5432/substream
20+
21+
# Redis Configuration (for production caching)
22+
# REDIS_URL=redis://localhost:6379
23+
24+
# Analytics Database (for production)
25+
# INFLUXDB_URL=http://localhost:8086
26+
# INFLUXDB_TOKEN=your-influxdb-token
27+
# INFLUXDB_ORG=your-org
28+
# INFLUXDB_BUCKET=substream-analytics

README.md

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
# SubStream Protocol Backend
2+
3+
A comprehensive backend API for the SubStream Protocol, supporting wallet-based authentication, tier-based content access, real-time analytics, and multi-region storage replication.
4+
5+
## Features
6+
7+
### 🔐 Authentication (SIWE)
8+
- Wallet-based authentication using Sign In With Ethereum
9+
- JWT token generation and validation
10+
- Nonce-based security
11+
- Multi-tier user support (Bronze, Silver, Gold)
12+
13+
### 📊 Real-time Analytics
14+
- View-time event aggregation
15+
- On-chain withdrawal event tracking
16+
- Heatmap generation for content engagement
17+
- Server-sent events for real-time updates
18+
- Creator analytics dashboard
19+
20+
### 🌍 Multi-Region Storage
21+
- IPFS content replication across multiple services
22+
- Automatic failover between regions
23+
- Health monitoring and service recovery
24+
- Support for Pinata, Web3.Storage, and Infura
25+
26+
### 🛡️ Tier-Based Access Control
27+
- Content filtering based on user subscription tier
28+
- Censored previews for unauthorized content
29+
- Database-level access control
30+
- Upgrade suggestions and tier management
31+
32+
## Quick Start
33+
34+
### Prerequisites
35+
- Node.js 16+
36+
- npm or yarn
37+
38+
### Installation
39+
40+
1. Clone the repository:
41+
```bash
42+
git clone https://github.com/jobbykings/SubStream-Protocol-Backend.git
43+
cd SubStream-Protocol-Backend
44+
```
45+
46+
2. Install dependencies:
47+
```bash
48+
npm install
49+
```
50+
51+
3. Copy environment variables:
52+
```bash
53+
cp .env.example .env
54+
```
55+
56+
4. Configure your environment variables in `.env`:
57+
- Set your JWT secret
58+
- Add IPFS service API keys
59+
- Configure database connections (optional for development)
60+
61+
5. Start the server:
62+
```bash
63+
# Development
64+
npm run dev
65+
66+
# Production
67+
npm start
68+
```
69+
70+
The API will be available at `http://localhost:3000`
71+
72+
## API Endpoints
73+
74+
### Authentication
75+
- `GET /auth/nonce?address={address}` - Get nonce for SIWE
76+
- `POST /auth/login` - Authenticate with wallet signature
77+
78+
### Content
79+
- `GET /content` - List content (filtered by user tier)
80+
- `GET /content/{id}` - Get specific content
81+
- `POST /content` - Create new content (requires authentication)
82+
- `PUT /content/{id}` - Update content (creator only)
83+
- `DELETE /content/{id}` - Delete content (creator only)
84+
- `GET /content/{id}/access` - Check access permissions
85+
- `GET /content/upgrade/suggestions` - Get upgrade suggestions
86+
87+
### Analytics
88+
- `POST /analytics/view-event` - Record view-time event
89+
- `POST /analytics/withdrawal-event` - Record withdrawal event
90+
- `GET /analytics/heatmap/{videoId}` - Get content heatmap
91+
- `GET /analytics/creator/{address}` - Get creator analytics
92+
- `GET /analytics/stream/{videoId}` - Real-time analytics stream
93+
94+
### Storage
95+
- `POST /storage/pin` - Pin content to multiple regions
96+
- `GET /storage/content/{id}` - Get content with failover
97+
- `GET /storage/metadata/{id}` - Get content metadata
98+
- `GET /storage/health` - Check storage service health
99+
- `GET /storage/url/{id}` - Get content URLs
100+
101+
### System
102+
- `GET /` - API information
103+
- `GET /health` - Health check
104+
105+
## Usage Examples
106+
107+
### Authentication
108+
```javascript
109+
// 1. Get nonce
110+
const nonceResponse = await fetch('/auth/nonce?address=0x742d35Cc6634C0532925a3b8D4C9db96C4b4Db45');
111+
const { nonce } = await nonceResponse.json();
112+
113+
// 2. Sign message with wallet
114+
const message = `Sign in to SubStream Protocol at ${new Date().toISOString()}\n\nNonce: ${nonce}\nAddress: 0x742d35Cc6634C0532925a3b8D4C9db96C4b4Db45`;
115+
const signature = await signer.signMessage(message);
116+
117+
// 3. Login
118+
const loginResponse = await fetch('/auth/login', {
119+
method: 'POST',
120+
headers: { 'Content-Type': 'application/json' },
121+
body: JSON.stringify({ address, signature, message, nonce })
122+
});
123+
const { token } = await loginResponse.json();
124+
```
125+
126+
### Content Access
127+
```javascript
128+
// Get content list (automatically filtered by tier)
129+
const response = await fetch('/content', {
130+
headers: { 'Authorization': `Bearer ${token}` }
131+
});
132+
const { content } = await response.json();
133+
134+
// Content will be full or censored based on user tier
135+
```
136+
137+
### Analytics
138+
```javascript
139+
// Record view event
140+
await fetch('/analytics/view-event', {
141+
method: 'POST',
142+
headers: {
143+
'Authorization': `Bearer ${token}`,
144+
'Content-Type': 'application/json'
145+
},
146+
body: JSON.stringify({
147+
videoId: 'video_001',
148+
watchTime: 120,
149+
totalDuration: 300
150+
})
151+
});
152+
153+
// Get heatmap
154+
const heatmapResponse = await fetch('/analytics/heatmap/video_001', {
155+
headers: { 'Authorization': `Bearer ${token}` }
156+
});
157+
```
158+
159+
## Architecture
160+
161+
### Services
162+
- **AuthService**: Handles SIWE authentication and JWT management
163+
- **ContentService**: Manages content with tier-based filtering
164+
- **AnalyticsService**: Processes real-time analytics and generates heatmaps
165+
- **StorageService**: Manages multi-region IPFS replication
166+
167+
### Middleware
168+
- **Authentication**: JWT token validation
169+
- **Tier Access**: Role-based access control
170+
- **Error Handling**: Centralized error management
171+
172+
### Data Flow
173+
1. User authenticates via wallet signature
174+
2. JWT token issued with tier information
175+
3. All subsequent requests include token
176+
4. Content filtered based on user tier
177+
5. Analytics events tracked in real-time
178+
6. Content replicated across multiple regions
179+
180+
## Environment Variables
181+
182+
See `.env.example` for all available configuration options.
183+
184+
## Development
185+
186+
### Running Tests
187+
```bash
188+
npm test
189+
```
190+
191+
### Project Structure
192+
```
193+
├── routes/ # API route handlers
194+
├── middleware/ # Express middleware
195+
├── services/ # Business logic services
196+
├── docs/ # API documentation
197+
├── tests/ # Test files
198+
└── index.js # Main application entry
199+
```
200+
201+
## Contributing
202+
203+
1. Fork the repository
204+
2. Create a feature branch
205+
3. Make your changes
206+
4. Add tests for new functionality
207+
5. Submit a pull request
208+
209+
## License
210+
211+
MIT License - see LICENSE file for details.
212+
213+
## Support
214+
215+
For issues and questions, please open an issue on GitHub.

docs/API_AUTHENTICATION.md

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# API Authentication Documentation
2+
3+
## Overview
4+
5+
The SubStream Protocol backend uses wallet-based authentication following the SIWE (Sign In With Ethereum) pattern. Users authenticate by signing a message with their wallet, which is then verified on the backend to issue a JWT token.
6+
7+
## Authentication Flow
8+
9+
### 1. POST /auth/login
10+
11+
Authenticate with the backend using a wallet signature.
12+
13+
#### Request Body
14+
```json
15+
{
16+
"address": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4Db45",
17+
"signature": "0x4355c47d63924e8a72e509b65029052eb6c50d03db4e6b1b3b9f1c2d3a4e5f6b",
18+
"message": "Sign in to SubStream Protocol at 2024-03-23T16:14:00.000Z",
19+
"nonce": "random_nonce_string"
20+
}
21+
```
22+
23+
#### Response
24+
```json
25+
{
26+
"success": true,
27+
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
28+
"user": {
29+
"address": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4Db45",
30+
"tier": "bronze"
31+
},
32+
"expiresIn": 86400
33+
}
34+
```
35+
36+
#### Error Response
37+
```json
38+
{
39+
"success": false,
40+
"error": "Invalid signature"
41+
}
42+
```
43+
44+
### 2. JWT Token Usage
45+
46+
Once authenticated, include the JWT token in the Authorization header for all protected endpoints:
47+
48+
```
49+
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
50+
```
51+
52+
#### Token Structure
53+
The JWT token contains the following claims:
54+
- `address`: User's wallet address
55+
- `tier`: User's subscription tier (bronze, silver, gold)
56+
- `iat`: Issued at timestamp
57+
- `exp`: Expiration timestamp (24 hours)
58+
59+
#### Protected Endpoints
60+
All endpoints except `/` and `/auth/login` require a valid JWT token.
61+
62+
## Implementation Details
63+
64+
### SIWE Message Format
65+
The message to sign should follow this format:
66+
```
67+
Sign in to SubStream Protocol at {timestamp}
68+
69+
Nonce: {nonce}
70+
Address: {wallet_address}
71+
```
72+
73+
### Signature Verification
74+
The backend verifies:
75+
1. The signature matches the address
76+
2. The nonce is valid and hasn't been used
77+
3. The timestamp is within acceptable range (5 minutes)
78+
79+
### Security Considerations
80+
- Nonces are single-use and expire after 5 minutes
81+
- JWT tokens expire after 24 hours
82+
- Rate limiting is applied to login attempts
83+
- All sensitive operations require valid JWT authentication
84+
85+
## Example Usage
86+
87+
### JavaScript/Node.js
88+
```javascript
89+
const response = await fetch('/auth/login', {
90+
method: 'POST',
91+
headers: {
92+
'Content-Type': 'application/json'
93+
},
94+
body: JSON.stringify({
95+
address: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4Db45',
96+
signature: '0x4355c47d63924e8a72e509b65029052eb6c50d03db4e6b1b3b9f1c2d3a4e5f6b',
97+
message: 'Sign in to SubStream Protocol at 2024-03-23T16:14:00.000Z',
98+
nonce: 'random_nonce_string'
99+
})
100+
});
101+
102+
const { token } = await response.json();
103+
104+
// Use token for authenticated requests
105+
const protectedResponse = await fetch('/content', {
106+
headers: {
107+
'Authorization': `Bearer ${token}`
108+
}
109+
});
110+
```
111+
112+
## Troubleshooting
113+
114+
### Common Errors
115+
116+
1. **Invalid signature**: Check that the signature was created with the correct message and address
117+
2. **Expired nonce**: Request a new nonce and try again
118+
3. **Token expired**: Re-authenticate to get a new token
119+
4. **Invalid token format**: Ensure the token is included in the Authorization header with "Bearer " prefix
120+
121+
### Support
122+
For authentication issues, check the browser console for detailed error messages or contact support with your wallet address.

0 commit comments

Comments
 (0)