BillTracker/scripts/test-cookie-options.js

51 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

2026-05-03 19:51:57 -05:00
#!/usr/bin/env node
'use strict';
const assert = require('assert');
const { cookieOpts } = require('../services/authService');
function withEnv(values, fn) {
const saved = {};
for (const key of Object.keys(values)) {
saved[key] = process.env[key];
if (values[key] === undefined) delete process.env[key];
else process.env[key] = values[key];
}
try {
fn();
} finally {
for (const [key, value] of Object.entries(saved)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
}
}
function req(headers = {}, secure = false) {
return {
secure,
headers,
get(name) {
return headers[String(name).toLowerCase()];
},
};
}
withEnv({ NODE_ENV: 'production', HTTPS: undefined, COOKIE_SECURE: undefined }, () => {
assert.strictEqual(cookieOpts(req()).secure, false, 'production over plain HTTP should not force Secure cookies');
});
withEnv({ HTTPS: 'true', COOKIE_SECURE: undefined }, () => {
assert.strictEqual(cookieOpts(req()).secure, true, 'HTTPS=true should force Secure cookies');
});
withEnv({ HTTPS: 'true', COOKIE_SECURE: 'false' }, () => {
assert.strictEqual(cookieOpts(req()).secure, false, 'COOKIE_SECURE=false should override HTTPS=true');
});
withEnv({ HTTPS: undefined, COOKIE_SECURE: undefined }, () => {
assert.strictEqual(cookieOpts(req({ 'x-forwarded-proto': 'https' })).secure, true, 'HTTPS proxy requests should use Secure cookies');
});
console.log('Cookie option tests passed.');