CI / build (push) Successful in 2m2s
Contractors are not in HR. Store them in COST_MODEL_DATA_DIR (contractors.json, never in Git) behind a PUT /api/cost-model/contractors endpoint with server-side normalization, and save automatically from the board whenever the contractor list changes. Production no longer shows the synthetic seed contractors. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
267 lines
15 KiB
JavaScript
267 lines
15 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { spawn } from 'node:child_process';
|
|
import test from 'node:test';
|
|
import { createServer } from 'node:http';
|
|
import { generateKeyPairSync, sign } from 'node:crypto';
|
|
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
|
|
const node = process.execPath;
|
|
|
|
async function waitFor(url) {
|
|
for (let attempt = 0; attempt < 40; attempt += 1) {
|
|
try {
|
|
const response = await fetch(url);
|
|
if (response.ok) return response;
|
|
} catch {}
|
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
}
|
|
throw new Error(`Server did not start: ${url}`);
|
|
}
|
|
|
|
function start(env) {
|
|
return spawn(node, ['server.js'], { env: { ...process.env, ...env }, stdio: 'ignore' });
|
|
}
|
|
|
|
test('development preview serves synthetic data and health', async (t) => {
|
|
const child = start({ PORT: '18081', HOST: '127.0.0.1', NODE_ENV: 'development' });
|
|
t.after(() => child.kill());
|
|
await waitFor('http://127.0.0.1:18081/api/health');
|
|
assert.equal((await fetch('http://127.0.0.1:18081/')).status, 200);
|
|
const bootstrap = await fetch('http://127.0.0.1:18081/api/bootstrap');
|
|
assert.equal(bootstrap.status, 200);
|
|
assert.equal((await bootstrap.json()).source, 'synthetic-demo');
|
|
});
|
|
|
|
test('production fails closed when OIDC settings are unavailable', async (t) => {
|
|
const child = start({ PORT: '18082', HOST: '127.0.0.1', NODE_ENV: 'production', OIDC_ISSUER: '', OIDC_CLIENT_ID: '', OIDC_CLIENT_SECRET: '' });
|
|
t.after(() => child.kill());
|
|
await waitFor('http://127.0.0.1:18082/api/health');
|
|
assert.equal((await fetch('http://127.0.0.1:18082/', { redirect: 'manual' })).status, 503);
|
|
assert.equal((await fetch('http://127.0.0.1:18082/api/bootstrap')).status, 503);
|
|
});
|
|
|
|
test('production source does not include a synthetic fallback', async () => {
|
|
const source = await readFile(new URL('../server.js', import.meta.url), 'utf8');
|
|
const bootstrapRoute = source.slice(source.indexOf("url.pathname === '/api/bootstrap'"), source.indexOf("url.pathname === '/'"));
|
|
assert.match(bootstrapRoute, /if \(isProduction\)/);
|
|
assert.match(bootstrapRoute, /error: 'hr_not_configured'/);
|
|
assert.match(bootstrapRoute, /error: 'access_denied'/);
|
|
});
|
|
|
|
test('configured production redirects pages and protects APIs', async (t) => {
|
|
const child = start({
|
|
PORT: '18083',
|
|
HOST: '127.0.0.1',
|
|
NODE_ENV: 'production',
|
|
OIDC_ISSUER: 'https://auth.example.test/application/o/pm-board/',
|
|
OIDC_CLIENT_ID: 'test-client',
|
|
OIDC_CLIENT_SECRET: 'test-secret',
|
|
});
|
|
t.after(() => child.kill());
|
|
await waitFor('http://127.0.0.1:18083/api/health');
|
|
const page = await fetch('http://127.0.0.1:18083/', { redirect: 'manual' });
|
|
assert.equal(page.status, 302);
|
|
assert.equal(page.headers.get('location'), '/api/auth/login');
|
|
assert.equal((await fetch('http://127.0.0.1:18083/api/bootstrap')).status, 401);
|
|
const logout = await fetch('http://127.0.0.1:18083/api/auth/logout', {
|
|
method: 'POST', redirect: 'manual',
|
|
headers: { cookie: 'pm_board_session=invalid; pm_board_login=pending' },
|
|
});
|
|
assert.equal(logout.status, 302);
|
|
assert.equal(logout.headers.get('location'), '/logged-out');
|
|
assert.match(logout.headers.get('set-cookie'), /pm_board_session=;.*Max-Age=0/);
|
|
const loggedOut = await fetch('http://127.0.0.1:18083/logged-out');
|
|
assert.equal(loggedOut.status, 200);
|
|
assert.match(await loggedOut.text(), /已登出/);
|
|
assert.equal((await fetch('http://127.0.0.1:18083/api/bootstrap', { headers: { cookie: 'pm_board_session=invalid' } })).status, 401);
|
|
assert.equal((await fetch('http://127.0.0.1:18083/api/auth/logout', {
|
|
method: 'POST', redirect: 'manual', headers: { origin: 'https://other.example.test' },
|
|
})).status, 403);
|
|
});
|
|
|
|
test('a signed-in session is revoked by logout and cannot be replayed', async (t) => {
|
|
const dataDir = await mkdtemp(join(tmpdir(), 'pm-board-cost-model-'));
|
|
t.after(() => rm(dataDir, { recursive: true, force: true }));
|
|
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
|
const key = { ...publicKey.export({ format: 'jwk' }), kid: 'test-key' };
|
|
let nonce;
|
|
let issuer;
|
|
const scopes = [];
|
|
const provider = createServer((req, res) => {
|
|
res.setHeader('Content-Type', 'application/json');
|
|
if (req.url === '/.well-known/openid-configuration') {
|
|
return res.end(JSON.stringify({ authorization_endpoint: `${issuer}/authorize`, token_endpoint: `${issuer}/token`, jwks_uri: `${issuer}/keys`, end_session_endpoint: `${issuer}/end-session` }));
|
|
}
|
|
if (req.url === '/keys') return res.end(JSON.stringify({ keys: [key] }));
|
|
if (req.url === '/token') {
|
|
if (req.method === 'POST') {
|
|
let body = '';
|
|
req.on('data', chunk => { body += chunk; });
|
|
req.on('end', () => {
|
|
const form = new URLSearchParams(body);
|
|
if (form.get('grant_type') === 'urn:ietf:params:oauth:grant-type:token-exchange') {
|
|
scopes.push(form.get('scope'));
|
|
return res.end(JSON.stringify({ access_token: 'hr-token', expires_in: 300 }));
|
|
}
|
|
const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url');
|
|
const signed = `${encode({ alg: 'RS256', kid: key.kid })}.${encode({
|
|
iss: issuer, aud: 'test-client', exp: Math.floor(Date.now() / 1000) + 300,
|
|
nonce, employee_number: '20150906', name: 'Test user',
|
|
})}`;
|
|
res.end(JSON.stringify({ id_token: `${signed}.${sign('RSA-SHA256', Buffer.from(signed), privateKey).toString('base64url')}`,
|
|
access_token: 'login-token', refresh_token: 'refresh-token', expires_in: 3600 }));
|
|
});
|
|
return;
|
|
}
|
|
}
|
|
if (req.url === '/employees?status=ACTIVE') return res.end(JSON.stringify([
|
|
{ employeeNumber: '20150906', name: 'Test user', departmentCode: 'G1', departmentName: '製作組', status: 'ACTIVE' },
|
|
{ employeeNumber: 'old', name: 'Former user', departmentCode: 'G1', status: 'OFFBOARDED' },
|
|
]));
|
|
if (req.url === '/organizations?flat=1') return res.end(JSON.stringify([
|
|
{ deptCode: 'C1', deptName: 'Test company', levelName: '公司' },
|
|
{ deptCode: 'D1', deptName: '製作部', upperDeptCode: 'C1', levelName: '部' },
|
|
{ deptCode: 'G1', deptName: '製作組', upperDeptCode: 'D1', levelName: '組' },
|
|
]));
|
|
if (req.url === '/employees/20150906/salary') return res.end(JSON.stringify({ employeeNumber: '20150906', amount: 50000, salaryType: 'monthly' }));
|
|
res.writeHead(404).end();
|
|
});
|
|
await new Promise(resolve => provider.listen(0, '127.0.0.1', resolve));
|
|
issuer = `http://127.0.0.1:${provider.address().port}`;
|
|
t.after(() => provider.close());
|
|
const base = 'http://127.0.0.1:18085';
|
|
const child = start({ PORT: '18085', HOST: '127.0.0.1', NODE_ENV: 'production',
|
|
OIDC_ISSUER: issuer, OIDC_CLIENT_ID: 'test-client', OIDC_CLIENT_SECRET: 'test-secret',
|
|
COST_MODEL_DATA_DIR: dataDir,
|
|
RESOURCE_SERVERS: JSON.stringify({ 'hr-sync': { audience: 'hr-sync-api', base_url: issuer,
|
|
required_scopes: ['hr-sync-api', 'employee_number'], scopes: ['hr:read', 'hr:salary:read'] } }) });
|
|
t.after(() => child.kill());
|
|
await waitFor(`${base}/api/health`);
|
|
const login = await fetch(`${base}/api/auth/login`, { redirect: 'manual' });
|
|
const authorize = new URL(login.headers.get('location'));
|
|
assert.match(authorize.searchParams.get('scope'), /offline_access/);
|
|
nonce = authorize.searchParams.get('nonce');
|
|
const state = authorize.searchParams.get('state');
|
|
const callback = await fetch(`${base}/api/auth/callback/authentik?state=${state}&code=test-code`, {
|
|
redirect: 'manual', headers: { cookie: `pm_board_login=${state}` },
|
|
});
|
|
assert.equal(callback.status, 302);
|
|
const cookie = callback.headers.getSetCookie().find(value => value.startsWith('pm_board_session=')).split(';')[0];
|
|
const app = await fetch(`${base}/`, { headers: { cookie } });
|
|
assert.equal(app.status, 200);
|
|
const appHtml = await app.text();
|
|
assert.match(appHtml, /id="nav-personnel" onclick="showHrPersonnelView\(\)"/);
|
|
assert.match(appHtml, /id="hr-personnel" class="view"/);
|
|
const bootstrap = await fetch(`${base}/api/bootstrap`, { headers: { cookie } });
|
|
assert.equal(bootstrap.status, 200);
|
|
const model = await bootstrap.json();
|
|
assert.equal(model.source, 'hr-sync-2027-planning');
|
|
assert.equal(model.globalParams.reportYear, 2027);
|
|
const planningPerson = model.baseData.find(person => person.employeeNumber === '20150906');
|
|
assert.equal(planningPerson.h1Start, 1);
|
|
assert.equal(planningPerson.h1End, 6);
|
|
assert.equal(planningPerson.calculationReady, false);
|
|
const override = await fetch(`${base}/api/hr/cost-model/employees/20150906`, {
|
|
method: 'POST', headers: { cookie, 'content-type': 'application/json' },
|
|
body: JSON.stringify({ role: 'A - 藝術家', weeklyWorkDays: 3, h1Start: 1, h1End: 6 }),
|
|
});
|
|
assert.equal(override.status, 200);
|
|
const savedOverrides = JSON.parse(await readFile(join(dataDir, 'cost-overrides.json'), 'utf8'));
|
|
assert.equal(savedOverrides['20150906'].role, 'A - 藝術家');
|
|
const updatedModel = await fetch(`${base}/api/hr/cost-model`, { headers: { cookie } });
|
|
const updatedPerson = (await updatedModel.json()).baseData.find(person => person.employeeNumber === '20150906');
|
|
assert.equal(updatedPerson.role, 'A - 藝術家');
|
|
assert.equal(updatedPerson.calculationReady, true);
|
|
const clearH1 = await fetch(`${base}/api/hr/cost-model/employees/20150906`, {
|
|
method: 'POST', headers: { cookie, 'content-type': 'application/json' },
|
|
body: JSON.stringify({ field: 'h1End', value: '' }),
|
|
});
|
|
assert.equal(clearH1.status, 200);
|
|
const partiallyScheduled = await fetch(`${base}/api/hr/cost-model`, { headers: { cookie } });
|
|
const partiallyScheduledPerson = (await partiallyScheduled.json()).baseData.find(person => person.employeeNumber === '20150906');
|
|
assert.equal(partiallyScheduledPerson.h1Start, 1);
|
|
assert.equal(partiallyScheduledPerson.h1End, '');
|
|
const restoreH1 = await fetch(`${base}/api/hr/cost-model/employees/20150906/overrides/h1End`, {
|
|
method: 'DELETE', headers: { cookie },
|
|
});
|
|
assert.equal(restoreH1.status, 200);
|
|
const restoredSchedule = await fetch(`${base}/api/hr/cost-model`, { headers: { cookie } });
|
|
const restoredPerson = (await restoredSchedule.json()).baseData.find(person => person.employeeNumber === '20150906');
|
|
assert.equal(restoredPerson.h1Start, 1);
|
|
assert.equal(restoredPerson.h1End, 6);
|
|
const roster = await fetch(`${base}/api/hr/employees`, { headers: { cookie } });
|
|
assert.equal(roster.status, 200);
|
|
const people = (await roster.json()).employees;
|
|
assert.equal(people.length, 1);
|
|
assert.equal(people[0].departmentName, '製作部');
|
|
assert.equal(people[0].groupName, '製作組');
|
|
assert.equal((await fetch(`${base}/api/hr/organizations`, { headers: { cookie } })).status, 200);
|
|
assert.equal((await fetch(`${base}/api/hr/employees/missing/salary`, { headers: { cookie } })).status, 404);
|
|
const salary = await fetch(`${base}/api/hr/employees/20150906/salary`, { headers: { cookie } });
|
|
assert.equal(salary.status, 200);
|
|
assert.equal((await salary.json()).salary.amount, 50000);
|
|
assert(scopes.some(scope => scope.includes('hr:read') && !scope.includes('hr:salary:read')));
|
|
assert(scopes.some(scope => scope.includes('hr:salary:read') && !scope.includes('hr:read')));
|
|
const logout = await fetch(`${base}/api/auth/logout`, {
|
|
method: 'POST', redirect: 'manual', headers: { cookie, origin: 'https://127.0.0.1:18085' },
|
|
});
|
|
assert.equal(logout.status, 302);
|
|
assert.equal(logout.headers.get('location'), '/logged-out');
|
|
assert.equal((await fetch(`${base}/api/auth/me`, { headers: { cookie } })).status, 401);
|
|
assert.equal((await fetch(`${base}/api/bootstrap`, { headers: { cookie } })).status, 401);
|
|
assert.equal((await fetch(`${base}/`, { headers: { cookie }, redirect: 'manual' })).status, 302);
|
|
|
|
const secondLogin = await fetch(`${base}/api/auth/login`, { redirect: 'manual' });
|
|
const secondAuthorize = new URL(secondLogin.headers.get('location'));
|
|
nonce = secondAuthorize.searchParams.get('nonce');
|
|
const secondState = secondAuthorize.searchParams.get('state');
|
|
const secondCallback = await fetch(`${base}/api/auth/callback/authentik?state=${secondState}&code=test-code`, {
|
|
redirect: 'manual', headers: { cookie: `pm_board_login=${secondState}` },
|
|
});
|
|
const secondCookie = secondCallback.headers.getSetCookie().find(value => value.startsWith('pm_board_session=')).split(';')[0];
|
|
const companyLogout = await fetch(`${base}/api/auth/company-logout`, {
|
|
method: 'POST', redirect: 'manual', headers: { cookie: secondCookie, origin: 'https://127.0.0.1:18085' },
|
|
});
|
|
assert.equal(companyLogout.status, 302);
|
|
const companyTarget = new URL(companyLogout.headers.get('location'));
|
|
assert.equal(companyTarget.pathname, '/end-session');
|
|
assert.equal(companyTarget.searchParams.get('post_logout_redirect_uri'), 'https://127.0.0.1:18085/logged-out');
|
|
assert(companyTarget.searchParams.has('id_token_hint'));
|
|
assert.equal((await fetch(`${base}/api/auth/me`, { headers: { cookie: secondCookie } })).status, 401);
|
|
const returnedCookie = companyLogout.headers.getSetCookie().find(value => value.startsWith('pm_board_company_logout=')).split(';')[0];
|
|
const returnedPage = await fetch(`${base}/logged-out`, { headers: { cookie: returnedCookie } });
|
|
assert.match(await returnedPage.text(), /已從 MoonShine 公司帳號登出/);
|
|
});
|
|
|
|
test('contractors saved on the board persist across restarts in COST_MODEL_DATA_DIR', async (t) => {
|
|
const dataDir = await mkdtemp(join(tmpdir(), 'pm-board-contractors-'));
|
|
t.after(() => rm(dataDir, { recursive: true, force: true }));
|
|
const env = { PORT: '18089', HOST: '127.0.0.1', NODE_ENV: 'development', COST_MODEL_DATA_DIR: dataDir };
|
|
let child = start(env);
|
|
await waitFor('http://127.0.0.1:18089/api/health');
|
|
const saved = await fetch('http://127.0.0.1:18089/api/cost-model/contractors', {
|
|
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ contractors: [{ name: '測試外包', dept: '視效部', group: '合成組', dayrate: 3000, h1Start: 1, h1End: 6 }] }),
|
|
});
|
|
assert.equal(saved.status, 200);
|
|
assert.equal((await saved.json()).count, 1);
|
|
const invalid = await fetch('http://127.0.0.1:18089/api/cost-model/contractors', {
|
|
method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contractors: 'x' }),
|
|
});
|
|
assert.equal(invalid.status, 400);
|
|
child.kill();
|
|
await new Promise(resolve => child.once('exit', resolve));
|
|
|
|
child = start(env);
|
|
t.after(() => child.kill());
|
|
await waitFor('http://127.0.0.1:18089/api/health');
|
|
const bootstrap = await (await fetch('http://127.0.0.1:18089/api/bootstrap')).json();
|
|
const contractors = bootstrap.baseData.filter(person => person.role.startsWith('O'));
|
|
assert.deepEqual(contractors.map(person => person.name), ['測試外包']);
|
|
assert.equal(contractors[0].dayrate, '3000');
|
|
const file = JSON.parse(await readFile(join(dataDir, 'contractors.json'), 'utf8'));
|
|
assert.equal(file.length, 1);
|
|
});
|