const { test } = require('node:test'); const assert = require('node:assert'); const fs = require('fs'); const os = require('os'); const path = require('path'); const { createAllowlistMiddleware } = require('../src/allowlist'); function mockRes() { return { statusCode: null, body: null, status(code) { this.statusCode = code; return this; }, send(body) { this.body = body; return this; }, }; } function tmpAllowlistFile(emails) { const filePath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'allowlist-mw-test-')), 'allowlist.json'); fs.writeFileSync(filePath, JSON.stringify({ emails })); return filePath; } test('allows a request whose email is in the allowlist file (case-insensitive)', () => { const filePath = tmpAllowlistFile(['a@example.com', 'b@example.com']); const middleware = createAllowlistMiddleware(filePath); const req = { headers: { 'x-auth-request-email': 'B@Example.com' } }; const res = mockRes(); let nextCalled = false; middleware(req, res, () => { nextCalled = true; }); assert.strictEqual(nextCalled, true); assert.strictEqual(res.statusCode, null); }); test('rejects with 403 when email is missing', () => { const filePath = tmpAllowlistFile(['a@example.com']); const middleware = createAllowlistMiddleware(filePath); const req = { headers: {} }; const res = mockRes(); middleware(req, res, () => { throw new Error('next should not be called'); }); assert.strictEqual(res.statusCode, 403); }); test('rejects with 403 when email is not in the allowlist file', () => { const filePath = tmpAllowlistFile(['a@example.com']); const middleware = createAllowlistMiddleware(filePath); const req = { headers: { 'x-auth-request-email': 'stranger@example.com' } }; const res = mockRes(); middleware(req, res, () => { throw new Error('next should not be called'); }); assert.strictEqual(res.statusCode, 403); }); test('re-reads the file on every request, reflecting changes without restart', () => { const filePath = tmpAllowlistFile(['a@example.com']); const middleware = createAllowlistMiddleware(filePath); const req = { headers: { 'x-auth-request-email': 'new@example.com' } }; const res1 = mockRes(); middleware(req, res1, () => { throw new Error('should not reach next yet'); }); assert.strictEqual(res1.statusCode, 403); fs.writeFileSync(filePath, JSON.stringify({ emails: ['a@example.com', 'new@example.com'] })); const res2 = mockRes(); let nextCalled = false; middleware(req, res2, () => { nextCalled = true; }); assert.strictEqual(nextCalled, true); });