Files
2026-11-25 08:48:07 +00:00

496 lines
30 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';
import { DatabaseSync } from 'node:sqlite';
const node = process.execPath;
// 資料存在 <資料夾>/leadboard.db 的 documents 表;測試直接讀資料庫確認有存進去。
function stored(dataDir, name) {
const db = new DatabaseSync(join(dataDir, 'leadboard.db'), { readOnly: true });
try { return db.prepare('SELECT body FROM documents WHERE name = ?').get(name)?.body ?? null; } finally { db.close(); }
}
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('the shared button stylesheet is served and every page links it', async (t) => {
const child = start({ PORT: '18095', HOST: '127.0.0.1', NODE_ENV: 'development' });
t.after(() => child.kill());
await waitFor('http://127.0.0.1:18095/api/health');
const css = await fetch('http://127.0.0.1:18095/buttons.css');
assert.equal(css.status, 200);
assert.match(css.headers.get('content-type'), /^text\/css/);
assert.match(await css.text(), /prefers-reduced-motion/);
for (const file of ['index.html', 'my.html', 'archive.html']) {
assert.match(await readFile(file, 'utf8'), /<link rel="stylesheet" href="\/buttons\.css">/, file);
}
});
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');
// /api/bootstrap and /api/model both read their input through loadBoard.
const bootstrapRoute = source.slice(source.indexOf("url.pathname === '/api/bootstrap'"), source.indexOf("url.pathname === '/'"));
assert.match(bootstrapRoute, /await loadBoard\(session\)/);
const loader = source.slice(source.indexOf('async function loadBoard('), source.indexOf('function sendJson('));
assert.match(loader, /if \(isProduction\)/);
assert.match(loader, /error: 'hr_not_configured'/);
assert.match(loader, /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: 'leadboard_session=invalid; leadboard_login=pending' },
});
assert.equal(logout.status, 302);
assert.equal(logout.headers.get('location'), '/logged-out');
assert.match(logout.headers.get('set-cookie'), /leadboard_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: 'leadboard_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: `leadboard_login=${state}` },
});
assert.equal(callback.status, 302);
const cookie = callback.headers.getSetCookie().find(value => value.startsWith('leadboard_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-preview-personnel" onclick="showPersonnelView\('all', 'internal'\)"/);
assert.match(appHtml, /id="nav-contractors"/);
// Removed on request: the separate HR roster page, data reset, simulation mode and preview badge.
for (const removed of ['id="nav-personnel"', 'id="hr-personnel"', 'hardReset', 'toggleMode', 'id="mode-indicator"',
'id="nav-versions"', 'id="versions"', '系統預設支援部', '製程部', 'pcDept', 'supportConversionRate', 'rdIndividuals',
'raiseEvents', 'create-raise-event-modal', 'snapshots',
'exportToExcel', 'importFromExcel', 'copyDataForSync', 'import-review-modal', 'cdn.jsdelivr.net',
'promptAddDept', 'promptAddGroup', 'removeOrgDept', 'removeOrgGroup', '夢想動畫管理中心']) {
assert.equal(appHtml.includes(removed), false, removed);
}
assert.equal((await fetch(`${base}/hr.html`, { headers: { cookie } })).status, 404);
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(stored(dataDir, 'cost-overrides.json'));
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);
// A stale callback starts one fresh login, then shows a page instead of looping.
const stale = await fetch(`${base}/api/auth/callback/authentik?state=gone&code=test-code`, { redirect: 'manual', headers: { cookie: 'leadboard_login=gone' } });
assert.equal(stale.status, 302);
assert.equal(stale.headers.get('location'), '/api/auth/login');
const staleAgain = await fetch(`${base}/api/auth/callback/authentik?state=gone&code=test-code`, { redirect: 'manual', headers: { cookie: 'leadboard_login=gone; leadboard_login_retry=1' } });
assert.equal(staleAgain.status, 400);
assert.match(await staleAgain.text(), /重新登入/);
// Two tabs logging in at once: the earlier tab's state still completes.
const tabA = new URL((await fetch(`${base}/api/auth/login`, { redirect: 'manual' })).headers.get('location'));
const tabB = await fetch(`${base}/api/auth/login`, { redirect: 'manual', headers: { cookie: `leadboard_login=${tabA.searchParams.get('state')}` } });
const bothCookie = tabB.headers.getSetCookie().find(value => value.startsWith('leadboard_login=')).split(';')[0];
nonce = tabA.searchParams.get('nonce');
const tabADone = await fetch(`${base}/api/auth/callback/authentik?state=${tabA.searchParams.get('state')}&code=test-code`, { redirect: 'manual', headers: { cookie: bothCookie } });
assert.equal(tabADone.status, 302);
assert.equal(tabADone.headers.get('location'), '/');
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: `leadboard_login=${secondState}` },
});
const secondCookie = secondCallback.headers.getSetCookie().find(value => value.startsWith('leadboard_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('leadboard_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(stored(dataDir, 'contractors.json'));
assert.equal(file.length, 1);
});
test('RD / CG flags and parameters saved on the board persist across restarts', async (t) => {
const dataDir = await mkdtemp(join(tmpdir(), 'pm-board-settings-'));
t.after(() => rm(dataDir, { recursive: true, force: true }));
const env = { PORT: '18090', HOST: '127.0.0.1', NODE_ENV: 'development', COST_MODEL_DATA_DIR: dataDir };
let child = start(env);
await waitFor('http://127.0.0.1:18090/api/health');
const saved = await fetch('http://127.0.0.1:18090/api/cost-model/settings', {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ rdGroups: ['研發部|平台組'], cgLeadGroups: ['視效部|專案組'], params: { cgLeadReductionPct: 0.8 } }),
});
assert.equal(saved.status, 200);
assert.equal((await fetch('http://127.0.0.1:18090/api/cost-model/settings', {
method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rdGroups: 'x' }),
})).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:18090/api/health');
const { globalParams } = await (await fetch('http://127.0.0.1:18090/api/bootstrap')).json();
assert.deepEqual(globalParams.rdGroups, ['研發部|平台組']);
assert.deepEqual(globalParams.cgLeadGroups, ['視效部|專案組']);
assert.equal(globalParams.cgLeadReductionPct, 0.8);
assert.equal(typeof globalParams.opMultiplier, 'number');
});
// 假的公司登入伺服器:登入的人由 who.employee 決定。
async function fakeProvider(t, who) {
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const key = { ...publicKey.export({ format: 'jwk' }), kid: 'test-key' };
const state = { nonce: null, issuer: null };
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: `${state.issuer}/authorize`, token_endpoint: `${state.issuer}/token`, jwks_uri: `${state.issuer}/keys`, end_session_endpoint: `${state.issuer}/end-session` }));
}
if (req.url === '/keys') return res.end(JSON.stringify({ keys: [key] }));
if (req.url === '/token' && req.method === 'POST') {
let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
const form = new URLSearchParams(body);
if (form.get('grant_type') !== 'authorization_code') 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: state.issuer, aud: 'test-client', exp: Math.floor(Date.now() / 1000) + 300,
nonce: state.nonce, employee_number: who.employee, name: `User ${who.employee}`,
})}`;
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: 'Admin', departmentCode: 'G1', status: 'ACTIVE' },
{ employeeNumber: '30000001', name: 'Staff', departmentCode: 'G1', status: 'ACTIVE' },
]));
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: '組' },
]));
res.writeHead(404).end();
});
await new Promise(resolve => provider.listen(0, '127.0.0.1', resolve));
state.issuer = `http://127.0.0.1:${provider.address().port}`;
t.after(() => provider.close());
return state;
}
async function signIn(base, provider) {
const login = await fetch(`${base}/api/auth/login`, { redirect: 'manual' });
const authorize = new URL(login.headers.get('location'));
provider.nonce = authorize.searchParams.get('nonce');
const loginState = authorize.searchParams.get('state');
const callback = await fetch(`${base}/api/auth/callback/authentik?state=${loginState}&code=test-code`, {
redirect: 'manual', headers: { cookie: `leadboard_login=${loginState}` },
});
const cookie = callback.headers.getSetCookie().find(value => value.startsWith('leadboard_session='))?.split(';')[0];
return { callback, cookie };
}
test('login flow: any company account gets in; only the top admin reaches the board and admin functions', async (t) => {
const dataDir = await mkdtemp(join(tmpdir(), 'pm-board-login-'));
t.after(() => rm(dataDir, { recursive: true, force: true }));
const who = { employee: '30000001' };
const provider = await fakeProvider(t, who);
const port = '18086';
const base = `http://127.0.0.1:${port}`;
const env = { PORT: port, HOST: '127.0.0.1', NODE_ENV: 'production',
OIDC_ISSUER: provider.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: provider.issuer,
required_scopes: ['hr-sync-api', 'employee_number'], scopes: ['hr:read', 'hr:salary:read'] } }) };
let child = start(env);
t.after(() => child.kill());
await waitFor(`${base}/api/health`);
// 一般同仁:登得進來,被帶到 /my;主看板、管理功能、全公司資料都擋住。
const staff = await signIn(base, provider);
assert.equal(staff.callback.status, 302);
assert.equal(staff.callback.headers.get('location'), '/my');
const headers = { cookie: staff.cookie };
assert.equal((await fetch(`${base}/my`, { headers })).status, 200);
for (const page of ['/', '/permissions', '/archive']) {
const response = await fetch(`${base}${page}`, { headers, redirect: 'manual' });
assert.equal(response.status, 302, page);
assert.equal(response.headers.get('location'), '/my', page);
}
for (const [method, path] of [['GET', '/api/model'], ['GET', '/api/bootstrap'], ['GET', '/api/hr/cost-model'], ['GET', '/api/hr/employees'],
['GET', '/api/permissions'], ['POST', '/api/permissions'], ['GET', '/api/archive'], ['PUT', '/api/cost-model/settings'],
['PUT', '/api/cost-model/contractors'], ['POST', '/api/year/next'], ['POST', '/api/hr/cost-model/employees/30000001'],
['DELETE', '/api/hr/cost-model/employees/30000001/overrides/role'], ['GET', '/api/anchors'], ['POST', '/api/anchors'],
['GET', '/api/hr/organizations'], ['GET', '/api/hr/employees/30000001/salary'], ['GET', '/api/names'], ['PUT', '/api/names'], ['GET', '/api/plans'], ['PUT', '/api/plans']]) {
const response = await fetch(`${base}${path}`, { method, headers: { ...headers, 'content-type': 'application/json' }, body: method === 'GET' ? undefined : '{}' });
assert.equal(response.status, 403, `${method} ${path}`);
}
const scope = await fetch(`${base}/api/scope`, { headers });
assert.equal(scope.status, 403);
assert.equal((await scope.json()).error, 'no_permission');
assert.equal((await fetch(`${base}/api/simulate`, { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, body: JSON.stringify({ dept: '製作部' }) })).status, 403);
// /my 的登出可以轉到公司登入伺服器(form-action 有允許)。
assert.match((await fetch(`${base}/my`, { headers })).headers.get('content-security-policy'), new RegExp(`form-action 'self' ${provider.issuer.replace(/[.]/g, '\\.')}`));
// 最高管理者:進主看板。
who.employee = '20150906';
const admin = await signIn(base, provider);
assert.equal(admin.callback.headers.get('location'), '/');
assert.equal((await fetch(`${base}/`, { headers: { cookie: admin.cookie }, redirect: 'manual' })).status, 200);
// 權限管理搬進主看板後,舊網址導回看板並直接打開那個區塊。
const permRedirect = await fetch(`${base}/permissions`, { headers: { cookie: admin.cookie }, redirect: 'manual' });
assert.equal(permRedirect.status, 302);
assert.equal(permRedirect.headers.get('location'), '/?view=permissions');
// 部署重新啟動:兩個人都不用重新登入;檔案裡沒有 cookie 原始值。
child.kill('SIGTERM');
await new Promise(resolve => child.once('exit', resolve));
const saved = stored(dataDir, 'sessions.json');
assert.ok(!saved.includes(admin.cookie.split('=')[1]) && !saved.includes(staff.cookie.split('=')[1]));
// 登入資料(含 token、工號)加密存放。
assert.equal(JSON.parse(saved).version, 2);
assert.ok(!saved.includes('20150906') && !saved.includes('refreshToken') && !saved.includes('accessToken'));
child = start(env);
await waitFor(`${base}/api/health`);
assert.equal((await fetch(`${base}/api/auth/me`, { headers: { cookie: admin.cookie } })).status, 200);
assert.equal((await fetch(`${base}/`, { headers: { cookie: admin.cookie }, redirect: 'manual' })).status, 200);
assert.equal((await fetch(`${base}/my`, { headers, redirect: 'manual' })).status, 200);
// 登出後,重新啟動也不會復活。
assert.equal((await fetch(`${base}/api/auth/logout`, { method: 'POST', redirect: 'manual', headers: { cookie: staff.cookie, origin: `https://127.0.0.1:${port}` } })).status, 302);
child.kill('SIGTERM');
await new Promise(resolve => child.once('exit', resolve));
child = start(env);
await waitFor(`${base}/api/health`);
assert.equal((await fetch(`${base}/api/auth/me`, { headers })).status, 401);
assert.equal((await fetch(`${base}/api/auth/me`, { headers: { cookie: admin.cookie } })).status, 200);
});
test('planned hires saved in 預排異動 appear on the board and persist in COST_MODEL_DATA_DIR', async (t) => {
const dataDir = await mkdtemp(join(tmpdir(), 'pm-board-plans-'));
t.after(() => rm(dataDir, { recursive: true, force: true }));
const env = { PORT: '18093', HOST: '127.0.0.1', NODE_ENV: 'development', COST_MODEL_DATA_DIR: dataDir };
const base = 'http://127.0.0.1:18093';
const child = start(env);
t.after(() => child.kill());
await waitFor(`${base}/api/health`);
const before = (await (await fetch(`${base}/api/bootstrap`)).json()).baseData.length;
const empty = await (await fetch(`${base}/api/plans`)).json();
assert.deepEqual(empty.plans, { departures: [], hires: [], transfers: [], history: [] });
const bad = await fetch(`${base}/api/plans`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hires: [{ id: 'x' }] }) });
assert.equal(bad.status, 400);
const hire = { id: 'h1', name: '預排動畫師', dept: '動畫部', role: 'A - 藝術家', salaryType: 'monthly', amount: 45000, startMonth: '2027-03' };
const saved = await fetch(`${base}/api/plans`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hires: [hire] }) });
assert.equal(saved.status, 200);
assert.ok(['pending', 'overdue'].includes((await saved.json()).status.hires[0].status));
const after = (await (await fetch(`${base}/api/bootstrap`)).json()).baseData;
assert.equal(after.length, before + 1);
assert.equal(after.find(p => p.source === 'planned').name, '預排動畫師');
assert.equal(JSON.parse(stored(dataDir, 'planned-changes.json')).hires[0].id, 'h1');
});