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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
'use strict';

const { port, maxBodySize, adminKey, sensitiveKeys, rateLimitEnabled, rateLimitMax, rateLimitWindowMs, rateLimitWindowSec } = require('../config');
const argon2 = require('argon2');
const db = require('../db');
const { seed } = require('../db/seed');
const { SETTING_DEFS } = require('../db/seed-settings');
const { runtimeConfig } = require('../config/runtime-config');

module.exports = function createRouter(rateLimiter, faviconIco, faviconPng, redis) {
  function json(res, status, data) {
    const body = JSON.stringify(data);
    res.writeHead(status, {
      'Content-Type': 'application/json; charset=utf-8',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'X-Powered-By': 'json-api-server/1.0',
    });
    res.end(body);
  }

  function notFound(res, msg = 'Not Found') {
    json(res, 404, { error: msg });
  }

  function badRequest(res, msg = 'Bad Request') {
    json(res, 400, { error: msg });
  }

  const BODY_TOO_LARGE = Symbol('BODY_TOO_LARGE');

  function readBody(req, res) {
    return new Promise((resolve, reject) => {
      let body = '';
      req.on('data', (chunk) => {
        body += chunk;
        if (body.length > maxBodySize) {
          json(res, 413, { error: 'Request body too large', message: `Body exceeds ${maxBodySize} bytes limit` });
          req.destroy();
          reject(BODY_TOO_LARGE);
        }
      });
      req.on('end', () => {
        try {
          let parsed = body ? JSON.parse(body) : {};
          if (parsed === null) parsed = {};
          resolve(parsed);
        } catch (_) {
          reject(new Error('Invalid JSON'));
        }
      });
      req.on('error', reject);
    });
  }

  async function readBodySafe(req, res) {
    try {
      return await readBody(req, res);
    } catch (e) {
      if (e !== BODY_TOO_LARGE) badRequest(res, 'Invalid JSON body');
    }
    return null;
  }

  function parseRoute(pathname) {
    const parts = pathname.replace(/^\/+|\/+$/g, '').split('/');
    if (parts[0] !== 'api') return null;
    parts.shift();

    const [table, rawId, sub] = parts;
    const id = rawId ? parseInt(rawId, 10) : null;

    if (!db.TABLES.includes(table)) return null;
    if (rawId && isNaN(id)) return { invalidId: true };

    return { table, id, sub };
  }

  const NESTED = {
    users: { posts: 'userId', albums: 'userId', todos: 'userId' },
    posts: { comments: 'postId' },
    albums: { photos: 'albumId' },
  };

  async function handleGET(req, res, route, query) {
    const { table, id, sub } = route;

    for (const param of ['_page', '_limit', '_start', '_end']) {
      if (query[param] !== undefined) {
        if (query[param] === '') {
          delete query[param];
        } else {
          const val = Number(query[param]);
          if (!Number.isInteger(val) || val < 0) {
            return badRequest(res, `Invalid ${param}: must be a non-negative integer`);
          }
          if ((param === '_page' || param === '_limit') && val < 1) {
            return badRequest(res, `Invalid ${param}: must be a positive integer`);
          }
        }
      }
    }

    if (id !== null && sub) {
      const parentExists = db.getOne(table, id);
      if (!parentExists) return notFound(res);

      const fkMap = NESTED[table] || {};
      if (!fkMap[sub]) return notFound(res, `No nested route '${sub}' under '${table}'`);

      const results = db.listAll(sub, { [fkMap[sub]]: String(id), ...query });
      return json(res, 200, results);
    }

    if (id !== null) {
      const row = db.getOne(table, id);
      return row ? json(res, 200, row) : notFound(res);
    }

    const rows = db.listAll(table, query);
    json(res, 200, rows);
  }

  async function handlePOST(req, res, route) {
    const { table } = route;
    const body = await readBodySafe(req, res);
    if (body === null) return;

    if (!body.id) body.id = db.nextId(table);

    try {
      const created = db.insertOne(table, body);
      json(res, 201, created);
    } catch (e) {
      badRequest(res, e.message);
    }
  }

  async function handlePUT(req, res, route) {
    const { table, id } = route;
    if (id === null) return badRequest(res, 'PUT requires an id');

    const body = await readBodySafe(req, res);
    if (body === null) return;

    const updated = db.updateOne(table, id, body, true);
    updated ? json(res, 200, updated) : notFound(res);
  }

  async function handlePATCH(req, res, route) {
    const { table, id } = route;
    if (id === null) return badRequest(res, 'PATCH requires an id');

    const body = await readBodySafe(req, res);
    if (body === null) return;

    const updated = db.updateOne(table, id, body, false);
    updated ? json(res, 200, updated) : notFound(res);
  }

  function handleDELETE(_req, res, route) {
    const { table, id } = route;
    if (id === null) return badRequest(res, 'DELETE requires an id');

    const deleted = db.deleteOne(table, id);
    deleted ? json(res, 200, {}) : notFound(res);
  }

  function handleHealth(res) {
    json(res, 200, {
      status: 'ok',
      redis: redis.connected ? 'connected' : 'disconnected',
      tables: db.TABLES,
      rateLimit: {
        enabled: runtimeConfig.get('rateLimitEnabled'),
        max: runtimeConfig.get('rateLimitMax'),
        windowMs: runtimeConfig.get('rateLimitWindowMs'),
      },
    });
  }

  const authCache = new Map();
  const AUTH_CACHE_TTL_MS = 5_000;

  function getCachedAuth(token) {
    const entry = authCache.get(token);
    if (entry && Date.now() - entry.ts < AUTH_CACHE_TTL_MS) {
      return entry.valid;
    }
    authCache.delete(token);
    return undefined;
  }

  function setCachedAuth(token, valid) {
    if (authCache.size > 1000) {
      const cutoff = Date.now() - AUTH_CACHE_TTL_MS;
      for (const [key, entry] of authCache) {
        if (entry.ts < cutoff) authCache.delete(key);
      }
    }
    authCache.set(token, { valid, ts: Date.now() });
  }

  function resetAuthCache() {
    authCache.clear();
  }

  async function checkAdminAuth(req) {
    if (!adminKey) return false;
    const auth = req.headers['authorization'] || '';
    const match = auth.match(/^Bearer\s+(.+)$/i);
    if (!match) return false;
    const token = match[1];
    const cached = getCachedAuth(token);
    if (cached !== undefined) return cached;
    try {
      const d = db.getWrappedDb();
      const row = d.prepare('SELECT value FROM settings WHERE key = ?').get('ADMIN_KEY');
      if (!row) return false;
      const valid = await argon2.verify(row.value, token);
      setCachedAuth(token, valid);
      return valid;
    } catch {
      setCachedAuth(token, false);
      return false;
    }
  }

  async function handleAdmin(req, res, pathname, method) {
    if (!(await checkAdminAuth(req))) {
      return json(res, 401, { error: 'Unauthorized' });
    }

    if (pathname === '/api/admin/settings' && method === 'GET') {
      const rows = db.listAll('settings').map((r) => sensitiveKeys.includes(r.key) ? { ...r, value: '***' } : r);
      return json(res, 200, rows);
    }

    const settingsMatch = pathname.match(/^\/api\/admin\/settings\/(.+)$/);
    if (settingsMatch && method === 'PATCH') {
      return await handleAdminPatchSetting(req, res, settingsMatch[1]);
    }

    if (pathname === '/api/admin/reset-database' && method === 'POST') {
      return await handleAdminResetDatabase(req, res);
    }

    return notFound(res, `Unknown admin route: ${pathname}`);
  }

  const RATE_LIMIT_SETTINGS = new Set([
    'RATE_LIMIT_ENABLED',
    'RATE_LIMIT_MAX',
    'RATE_LIMIT_WINDOW_MS',
  ]);

  const REDIS_SETTINGS = new Set([
    'REDIS_HOST',
    'REDIS_PORT',
    'REDIS_DB',
    'REDIS_PASSWORD',
    'REDIS_URL',
  ]);

  function applyRateLimitUpdate(settingKey, value) {
    const updates = {};
    switch (settingKey) {
      case 'RATE_LIMIT_ENABLED': {
        const enabled = value !== 'false' && value !== false;
        updates.enabled = enabled;
        runtimeConfig.set('rateLimitEnabled', enabled);
        break;
      }
      case 'RATE_LIMIT_MAX': {
        const max = parseInt(value, 10);
        if (!isNaN(max)) {
          updates.max = max;
          runtimeConfig.set('rateLimitMax', max);
        }
        break;
      }
      case 'RATE_LIMIT_WINDOW_MS': {
        const windowMs = parseInt(value, 10);
        if (!isNaN(windowMs)) {
          updates.windowMs = windowMs;
          runtimeConfig.set('rateLimitWindowMs', windowMs);
          runtimeConfig.set('rateLimitWindowSec', Math.ceil(windowMs / 1000));
        }
        break;
      }
    }
    if (Object.keys(updates).length > 0) {
      rateLimiter.updateConfig(updates);
    }
  }

  async function applyRedisUpdate() {
    const d = db.getWrappedDb();
    const rows = d.prepare(
      'SELECT key, value FROM settings WHERE key IN (?, ?, ?, ?, ?)'
    ).all('REDIS_URL', 'REDIS_HOST', 'REDIS_PORT', 'REDIS_DB', 'REDIS_PASSWORD');

    const settings = {};
    for (const row of rows) {
      settings[row.key] = row.value;
    }

    const opts = settings.REDIS_URL
      ? { url: settings.REDIS_URL }
      : {
          host: settings.REDIS_HOST || '127.0.0.1',
          port: parseInt(settings.REDIS_PORT || '6379', 10),
          db: parseInt(settings.REDIS_DB || '0', 10),
          password: settings.REDIS_PASSWORD || undefined,
        };

    await redis.reconnect(opts);
  }

  async function applyRuntimeUpdate(settingKey, value) {
    if (RATE_LIMIT_SETTINGS.has(settingKey)) {
      applyRateLimitUpdate(settingKey, value);
    } else if (REDIS_SETTINGS.has(settingKey)) {
      await applyRedisUpdate();
    }
  }

  async function handleAdminPatchSetting(req, res, settingKey) {
    const body = await readBodySafe(req, res);
    if (body === null) return;

    if (body.value === undefined) {
      return badRequest(res, 'Missing "value" in request body');
    }
    if (body.value === null || typeof body.value === 'object') {
      return badRequest(res, 'Setting value must be a string or number');
    }

    const d = db.getWrappedDb();
    const existing = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);

    /* v8 ignore next */ if (!existing) {
      const def = SETTING_DEFS.find(s => s.key === settingKey);
      /* v8 ignore next */ if (!def) return notFound(res, `Setting '${settingKey}' not found`);
      const valToStore = settingKey === 'ADMIN_KEY' ? await argon2.hash(body.value) : body.value;
      d.prepare(`INSERT INTO settings (key, value, description, updated_at) VALUES (?, ?, ?, datetime('now'))`).run(settingKey, valToStore, def.description);
      const created = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
      applyRuntimeUpdate(settingKey, body.value).catch(err => {
        console.error('[Runtime] Failed to apply setting:', err.message);
      });
      return json(res, 201, created);
    }

    const valToStore = settingKey === 'ADMIN_KEY' ? await argon2.hash(body.value) : body.value;
    d.prepare(`UPDATE settings SET value = ?, updated_at = datetime('now') WHERE key = ?`).run(valToStore, settingKey);
    const updated = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
    applyRuntimeUpdate(settingKey, body.value).catch(err => {
      console.error('[Runtime] Failed to apply setting:', err.message);
    });
    json(res, 200, updated);
  }

  let resetLock = Promise.resolve();
  const RESET_LOCK_TIMEOUT_MS = 30_000;

  async function withResetLock(fn) {
    let release;
    let timer;
    const prev = resetLock;
    resetLock = new Promise((resolve) => { release = resolve; });
    await prev;
    timer = setTimeout(release, RESET_LOCK_TIMEOUT_MS);
    try {
      return await fn();
    } finally {
      clearTimeout(timer);
      release();
    }
  }

  async function handleAdminResetDatabase(req, res) {
    const body = await readBodySafe(req, res);
    if (body === null) return;
    if (body.confirm !== true) {
      return badRequest(res, 'Reset requires confirm: true in request body');
    }
    await withResetLock(async () => {
      const d = db.getWrappedDb();
      d.exec('BEGIN');
      try {
        const deleteOrder = ['photos', 'comments', 'albums', 'posts', 'todos', 'users'];
        for (const table of deleteOrder) {
          d.prepare(`DELETE FROM ${table}`).run();
        }
        if (d.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sqlite_sequence'").get()) {
          d.exec('DELETE FROM sqlite_sequence');
        }
        const fetchFn = async (url) => {
          const response = await globalThis.fetch(url);
          return response.json();
        };
        await seed({ database: d, fetch: fetchFn, runMigrate: false, skipTransaction: true });
        d.exec('COMMIT');
        json(res, 200, { message: 'Database reset and re-seeded successfully' });
      } catch (error) {
        d.exec('ROLLBACK');
        throw error;
      }
    });
  }

  async function requestHandler(req, res) {
    const parsed = new URL(req.url, 'http://localhost');
    const pathname = parsed.pathname.length > 1 ? parsed.pathname.replace(/\/+$/, '') : parsed.pathname;
    const query = Object.fromEntries(parsed.searchParams);
    const method = req.method.toUpperCase();

    if (method === 'OPTIONS') {
      res.writeHead(204, {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      });
      return res.end();
    }

    if (pathname === '/health' || pathname === '/api/health') {
      return handleHealth(res);
    }

    if (pathname === '/' || pathname === '/api') {
      return json(res, 200, {
        message: 'Nodejs JSON API Server — JSONPlaceholder-compatible REST API',
        version: '1.0.0',
        endpoints: db.TABLES.map((t) => `/api/${t}`),
        docs: 'GET /health for server status',
      });
    }

    if (pathname === '/favicon.ico') {
      res.writeHead(200, { 'Content-Type': 'image/x-icon' });
      return res.end(faviconIco);
    }

    if (pathname === '/favicon.png') {
      res.writeHead(200, { 'Content-Type': 'image/png' });
      return res.end(faviconPng);
    }

    await new Promise((resolve) => {
      rateLimiter(req, res, resolve);
    });
    /* v8 ignore next */ if (res.writableEnded) return;

    if (pathname.startsWith('/api/admin/')) {
      try {
        return await handleAdmin(req, res, pathname, method);
      } catch (err) {
        console.error('[Error]', err);
        return json(res, 500, { error: 'Internal Server Error', message: err.message });
      }
    }

    const route = parseRoute(pathname);
    /* v8 ignore next */ if (!route) return notFound(res, `Unknown route: ${pathname}`);
    /* v8 ignore next */ if (route.invalidId) return badRequest(res, 'Invalid ID format');

    try {
      switch (method) {
        case 'GET': return await handleGET(req, res, route, query);
        case 'POST': return await handlePOST(req, res, route);
        case 'PUT': return await handlePUT(req, res, route);
        case 'PATCH': return await handlePATCH(req, res, route);
        case 'DELETE': return handleDELETE(req, res, route);
        default:
          return json(res, 405, { error: `Method ${method} not allowed` });
      }
    } catch (err) {
      console.error('[Error]', err);
      json(res, 500, { error: 'Internal Server Error', message: err.message });
    }
  }

  return { requestHandler, resetAuthCache };
};