-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
253 lines (215 loc) · 7.75 KB
/
Copy pathserver.js
File metadata and controls
253 lines (215 loc) · 7.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
const express = require('express');
const crypto = require('crypto');
const path = require('path');
const app = express();
app.use(express.json({ limit: '1mb' }));
// Serve static files from public directory
app.use(express.static(path.join(__dirname, 'public')));
// Challenge configuration defaults
const DEFAULT_LIFETIME_MS = 200;
const DEFAULT_DIFFICULTY = 4;
// Rate limiting configuration
const RATE_LIMIT_WINDOW_MS = 60000; // 1 minute
const RATE_LIMIT_MAX_REQUESTS = 100; // per tenant per window
/** Algorithm description returned in challenges so agents know how to solve. */
const ALGORITHM =
'sha256_hex_leading_zeros: Concatenate nonce and solution as strings. Compute SHA256(nonce+solution) and take the hex digest. The digest must start with exactly difficulty zero characters (e.g. difficulty 4 => prefix "0000").';
/** Tenants: apiKey -> { lifetimeMs, difficulty } */
const tenants = loadTenants();
/** Challenges per tenant: apiKey -> Map(nonce -> { nonce, expiry, difficulty }) */
const challengesByTenant = new Map();
/** Rate limit tracking: apiKey -> Array<timestamp> (sliding window) */
const rateLimitsByTenant = new Map();
// Validate that at least one tenant is configured
if (tenants.size === 0) {
console.error('Fatal: no tenants. Set TENANTS env (e.g. TENANTS=\'{"your-api-key":{}}\').');
process.exit(1);
}
/**
* Load tenant configuration from TENANTS environment variable.
* Returns Map<apiKey, {lifetimeMs, difficulty}>.
*/
function loadTenants() {
const raw = process.env.TENANTS;
if (!raw) return new Map();
try {
const obj = JSON.parse(raw);
const m = new Map();
for (const [key, config = {}] of Object.entries(obj)) {
m.set(key, {
lifetimeMs: config.lifetimeMs ?? DEFAULT_LIFETIME_MS,
difficulty: config.difficulty ?? DEFAULT_DIFFICULTY,
});
}
return m;
} catch {
return new Map();
}
}
/**
* Get challenge store for a specific tenant.
* Creates one if it doesn't exist.
*/
function getChallenges(apiKey) {
let m = challengesByTenant.get(apiKey);
if (!m) {
m = new Map();
challengesByTenant.set(apiKey, m);
}
return m;
}
/**
* Structured JSON logging for all tenant actions.
* Masks API key to last 4 characters for security.
*/
function tenantLog(apiKey, action, outcome, metadata = {}) {
const logEntry = {
ts: new Date().toISOString(),
tenant: apiKey ? `****${apiKey.slice(-4)}` : '????',
action,
outcome,
...metadata
};
console.log(JSON.stringify(logEntry));
}
/**
* Rate limiting middleware using sliding window algorithm.
* Tracks requests per tenant in memory.
*/
function rateLimit(req, res, next) {
const { apiKey } = req;
const now = Date.now();
// Get or create request history for this tenant
let requests = rateLimitsByTenant.get(apiKey);
if (!requests) {
requests = [];
rateLimitsByTenant.set(apiKey, requests);
}
// Remove requests outside the current window
const windowStart = now - RATE_LIMIT_WINDOW_MS;
const recentRequests = requests.filter(ts => ts > windowStart);
// Check if limit exceeded
if (recentRequests.length >= RATE_LIMIT_MAX_REQUESTS) {
tenantLog(apiKey, 'rate_limit', 'exceeded', {
window_ms: RATE_LIMIT_WINDOW_MS,
max_requests: RATE_LIMIT_MAX_REQUESTS
});
return res.status(429).json({ error: 'challenge failed' });
}
// Add current request and update store
recentRequests.push(now);
rateLimitsByTenant.set(apiKey, recentRequests);
next();
}
// Health check endpoint for load balancers and monitoring
app.get('/health', (req, res) => res.status(200).json({ ok: true }));
/**
* Authentication middleware.
* Accepts API key via X-API-Key header or Authorization: Bearer header.
* Returns 401 with generic error if key is invalid.
*/
function auth(req, res, next) {
const key = req.headers['x-api-key'] || (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
const config = key ? tenants.get(key) : null;
if (!config) {
tenantLog(key || '', 'auth', 'rejected');
return res.status(401).json({ error: 'challenge failed' });
}
req.apiKey = key;
req.tenantConfig = config;
next();
}
/**
* Generate a random 32-character hex nonce.
*/
function randomNonce() {
return crypto.randomBytes(16).toString('hex');
}
/**
* Verify proof-of-work solution.
* Returns true if SHA256(nonce + solution) starts with exactly `difficulty` zeros.
*/
function hashWithLeadingZeros(nonce, solution, difficulty) {
const digest = crypto.createHash('sha256').update(nonce + solution).digest('hex');
const prefix = digest.slice(0, difficulty);
return /^0+$/.test(prefix) && prefix.length === difficulty;
}
/**
* POST /challenge - Issue a new proof-of-work challenge.
* Returns { nonce, expiry, difficulty, algorithm }.
* Challenge is single-use and expires after lifetimeMs.
*/
app.post('/challenge', auth, rateLimit, (req, res) => {
const { apiKey, tenantConfig } = req;
const nonce = randomNonce();
const expiry = Date.now() + tenantConfig.lifetimeMs;
const difficulty = tenantConfig.difficulty;
// Store challenge in tenant's challenge map
getChallenges(apiKey).set(nonce, { nonce, expiry, difficulty });
tenantLog(apiKey, 'challenge', 'issued', { difficulty, lifetime_ms: tenantConfig.lifetimeMs });
res.status(200).json({ nonce, expiry, difficulty, algorithm: ALGORITHM });
});
/**
* POST /post - Verify challenge solution and accept payload.
* Body: { nonce, solution, payload? }
* Returns 200 with { accepted: true, payload } on success.
* Returns 403 with generic error on failure (expired, wrong solution, reused nonce).
* Challenge is consumed (deleted) after verification attempt.
*/
app.post('/post', auth, rateLimit, (req, res) => {
const { nonce, solution, payload } = req.body;
const { apiKey } = req;
const challenges = getChallenges(apiKey);
// Validate required fields
if (nonce == null || solution == null) {
tenantLog(apiKey, 'post', 'bad_request');
return res.status(400).json({ error: 'challenge failed' });
}
// Check if challenge exists (prevents reuse and unknown nonces)
const challenge = challenges.get(nonce);
if (!challenge) {
tenantLog(apiKey, 'post', 'reused_or_unknown');
return res.status(403).json({ error: 'challenge failed' });
}
// Check expiry
if (Date.now() > challenge.expiry) {
challenges.delete(nonce);
tenantLog(apiKey, 'post', 'expired');
return res.status(403).json({ error: 'challenge failed' });
}
// Verify proof-of-work solution
if (!hashWithLeadingZeros(nonce, solution, challenge.difficulty)) {
challenges.delete(nonce); // Consume challenge even on wrong solution
tenantLog(apiKey, 'post', 'invalid_solution');
return res.status(403).json({ error: 'challenge failed' });
}
// Solution verified - consume challenge and accept
challenges.delete(nonce);
tenantLog(apiKey, 'post', 'accepted');
res.status(200).json({ accepted: true, payload: payload ?? null });
});
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
tenantLog(null, 'server', 'started', { port: PORT, tenants: tenants.size });
});
/**
* Graceful shutdown handler.
* Stops accepting new connections and waits for in-flight requests to complete.
*/
function gracefulShutdown(signal) {
tenantLog(null, 'server', 'shutdown_initiated', { signal });
server.close(() => {
tenantLog(null, 'server', 'shutdown_complete');
process.exit(0);
});
// Force shutdown after 10 seconds if requests don't complete
setTimeout(() => {
tenantLog(null, 'server', 'shutdown_forced');
process.exit(1);
}, 10000);
}
// Listen for termination signals
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
// Export for testing
module.exports = { app, server, tenants, hashWithLeadingZeros, getChallenges };