262 lines
13 KiB
JavaScript
262 lines
13 KiB
JavaScript
import { randomBytes } from 'node:crypto';
|
|
import { createServer } from 'node:http';
|
|
|
|
// A synthetic version of the original API. It has no database, external calls,
|
|
// project configuration, or durable storage. Its intentionally permissive write
|
|
// handlers make it possible to prove that the bridge enforces permissions itself.
|
|
export const fixturePassword = 'Synthetic!Root93';
|
|
export const replacementPassword = 'Synthetic!Next94';
|
|
|
|
const clone = (value) => structuredClone(value);
|
|
const redact = (value) => {
|
|
if (Array.isArray(value)) return value.map(redact);
|
|
if (!value || typeof value !== 'object') return value;
|
|
return Object.fromEntries(Object.entries(value).map(([key, item]) => [
|
|
key, /password|token|secret/i.test(key) && item !== '' ? '[redacted]' : redact(item),
|
|
]));
|
|
};
|
|
|
|
export function flattenTree(rows) {
|
|
return rows.flatMap((row) => [row, ...flattenTree(row.children ?? [])]);
|
|
}
|
|
|
|
function tree(rows, pid = 0) {
|
|
return rows.filter((row) => Number(row.pid) === pid)
|
|
.map((row) => ({ ...clone(row), children: tree(rows, Number(row.id)) }));
|
|
}
|
|
|
|
function fixtures() {
|
|
const baseUser = {
|
|
disable: 0, root: 0, is_paw: 1, role_id: ['7'], dept_id: ['11'], jobs_id: ['21', '22'],
|
|
avatar: 'https://fixture.invalid/avatars/doctor.png', multipoint_login: 1,
|
|
gender: 2, age: 43, phone: '13800000000', title: '主任医师', department: '中医科',
|
|
specialty: '针灸', education: '博士', experience: '合成从业资料', honors: '合成荣誉',
|
|
license_no: 'SYNTHETIC-LICENSE', qualification_images: ['https://fixture.invalid/license.png'],
|
|
enable_image_consult: 0, enable_video_consult: 1, enable_charge: 1,
|
|
work_wechat_userid: 'synthetic_wecom', need_bind_work_wechat: false,
|
|
role_name: ['临床医生'], dept_name: '总院', create_time: '2026-01-01 00:00:00',
|
|
// Deliberately hostile source fields must never escape a bridge DTO.
|
|
password: 'synthetic-stored-password-value', password_hash: 'synthetic-stored-hash-value',
|
|
token: 'synthetic-user-record-token-value',
|
|
};
|
|
const users = [
|
|
{ ...clone(baseUser), id: 1, account: 'OriginalRoot', name: '原系统管理员', root: 1, role_name: '系统管理员' },
|
|
{ ...clone(baseUser), id: 2, account: 'OriginalReader', name: '原只读账号', role_id: ['8'] },
|
|
{ ...clone(baseUser), id: 3, account: 'OriginalDoctor', name: '合成医生' },
|
|
{ ...clone(baseUser), id: 4, account: 'FirstPassword', name: '首次改密账号', is_paw: 0 },
|
|
{ ...clone(baseUser), id: 5, account: 'WecomBinding', name: '企微待绑定账号', need_bind_work_wechat: true, work_wechat_userid: '' },
|
|
{ ...clone(baseUser), id: 6, account: 'DepartmentEditor', name: '部门编辑账号', role_id: ['9'] },
|
|
];
|
|
const menuBase = { icon: '', sort: 0, is_cache: 0, is_show: 1, is_disable: 0, selected: '', params: '' };
|
|
const menus = [
|
|
{ ...menuBase, id: 100, pid: 0, type: 'M', name: '原权限目录', paths: 'permission', component: '', perms: '' },
|
|
{ ...menuBase, id: 101, pid: 100, type: 'C', name: '原账号页', paths: 'admin', component: 'permission/admin/index', perms: 'auth.admin/lists' },
|
|
{ ...menuBase, id: 102, pid: 100, type: 'C', name: '原角色页', paths: 'role', component: 'permission/role/index', perms: 'auth.role/lists' },
|
|
{ ...menuBase, id: 103, pid: 100, type: 'C', name: '原菜单页', paths: 'menu', component: 'permission/menu/index', perms: 'auth.menu/lists' },
|
|
{ ...menuBase, id: 104, pid: 100, type: 'C', name: '原部门页', paths: 'department', component: 'organization/department/index', perms: 'dept.dept/lists' },
|
|
{ ...menuBase, id: 109, pid: 101, type: 'A', name: '已停用授权', paths: '', component: '', perms: 'auth.admin/delete', is_disable: 1 },
|
|
{
|
|
...menuBase, id: 110, pid: 0, type: 'C', name: '原医疗页面', paths: 'doctor/consultation',
|
|
component: 'doctor/consultation/index', perms: 'doctor.consultation/lists',
|
|
is_cache: 1, selected: '/doctor/appointments', params: '{"tab":"remote","scope":3}',
|
|
},
|
|
];
|
|
const roles = [
|
|
{ id: 7, name: '临床医生', desc: '原角色', sort: 5, data_scope: 3, menu_id: ['101', '109'], num: 4 },
|
|
{ id: 8, name: '只读角色', desc: '', sort: 0, data_scope: 4, menu_id: ['101', '102', '103', '104'], num: 1 },
|
|
{ id: 9, name: '部门编辑角色', desc: '', sort: 0, data_scope: 2, menu_id: ['104'], num: 1 },
|
|
];
|
|
const depts = [
|
|
{ id: 11, pid: 0, name: '总院', status: 1, sort: 5, leader: '合成院长', mobile: '13900000001' },
|
|
{ id: 12, pid: 11, name: '停用分院', status: 0, sort: 1, leader: '合成分院长', mobile: '13900000002' },
|
|
];
|
|
return { users, menus, roles, depts };
|
|
}
|
|
|
|
async function bodyOf(request) {
|
|
let text = '';
|
|
for await (const chunk of request) {
|
|
text += chunk;
|
|
if (text.length > 1_000_000) throw new Error('Synthetic request too large');
|
|
}
|
|
if (!text) return {};
|
|
if (request.headers['content-type']?.includes('application/json')) return JSON.parse(text);
|
|
const fields = {};
|
|
for (const [key, value] of new URLSearchParams(text)) {
|
|
const array = key.match(/^(.+)\[(?:\d*)\]$/);
|
|
if (array) (fields[array[1]] ??= []).push(value);
|
|
else fields[key] = value;
|
|
}
|
|
return fields;
|
|
}
|
|
|
|
export async function createSharedUpstream({ groupEnabled = false } = {}) {
|
|
const state = {
|
|
...fixtures(), sessions: new Map(), passwords: new Map(), faults: new Map(), log: [],
|
|
sensitiveValues: new Set([
|
|
fixturePassword, replacementPassword, 'synthetic-stored-password-value',
|
|
'synthetic-stored-hash-value', 'synthetic-user-record-token-value',
|
|
]),
|
|
permissionOverrides: new Map(),
|
|
};
|
|
|
|
function reset() {
|
|
Object.assign(state, fixtures());
|
|
state.sessions.clear();
|
|
state.passwords = new Map(state.users.map((user) => [user.account, fixturePassword]));
|
|
state.faults.clear();
|
|
state.permissionOverrides.clear();
|
|
state.log.length = 0;
|
|
}
|
|
reset();
|
|
|
|
function permissions(user) {
|
|
if (state.permissionOverrides.has(user.account)) return state.permissionOverrides.get(user.account);
|
|
if (Number(user.root) === 1) return ['*'];
|
|
if (user.account === 'DepartmentEditor') return ['dept.dept/lists', 'dept.dept/edit'];
|
|
return ['auth.admin/lists', 'auth.role/lists', 'auth.menu/lists', 'dept.dept/lists'];
|
|
}
|
|
|
|
function reply(response, code = 1, data = [], msg = '') {
|
|
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
response.end(JSON.stringify({ code, show: 0, msg, data }));
|
|
}
|
|
|
|
const server = createServer(async (request, response) => {
|
|
try {
|
|
const url = new URL(request.url, 'http://127.0.0.1');
|
|
const path = url.pathname.replace(/^\/adminapi\//, '').replace(/\/+$/, '');
|
|
const body = await bodyOf(request);
|
|
const sourceToken = request.headers.token;
|
|
const account = state.sessions.get(sourceToken);
|
|
state.log.push({
|
|
path, method: request.method, query: Object.fromEntries(url.searchParams), body: redact(body),
|
|
hasTokenHeader: typeof sourceToken === 'string' && sourceToken.length > 0,
|
|
hasAuthorizationHeader: Boolean(request.headers.authorization), account: account ?? null,
|
|
});
|
|
const fault = state.faults.get(path);
|
|
if (fault?.kind === 'network') return request.socket.destroy();
|
|
if (fault?.kind === 'non-json') {
|
|
response.writeHead(200, { 'Content-Type': 'text/html' });
|
|
return response.end('<html>synthetic private upstream diagnostic</html>');
|
|
}
|
|
if (fault?.kind === 'protocol') {
|
|
response.writeHead(200, { 'Content-Type': 'application/json' });
|
|
return response.end('{"unexpected":"synthetic private upstream diagnostic"}');
|
|
}
|
|
if (fault?.kind === 'redirect') {
|
|
response.writeHead(302, { Location: '/adminapi/login/account' });
|
|
return response.end();
|
|
}
|
|
if (fault) return reply(response, fault.code, fault.data ?? [], fault.msg ?? '合成源拒绝');
|
|
|
|
if (path === 'identity.session/login') {
|
|
const user = state.users.find((item) => item.account === body.account);
|
|
if (!user || body.password !== state.passwords.get(body.account) || Number(user.disable) === 1) {
|
|
return reply(response, 0, [], '账号或密码错误');
|
|
}
|
|
const expectedTerminal = groupEnabled ? 11 : 1;
|
|
if (Number(body.terminal) !== expectedTerminal) return reply(response, 0, [], `terminal必须为${expectedTerminal}`);
|
|
const token = `synthetic-source-${randomBytes(24).toString('hex')}`;
|
|
state.sessions.set(token, user.account);
|
|
state.sensitiveValues.add(token);
|
|
return reply(response, 1, {
|
|
name: user.name, avatar: user.avatar, role_name: user.role_name, token,
|
|
is_paw: user.is_paw, need_bind_work_wechat: user.need_bind_work_wechat,
|
|
});
|
|
}
|
|
|
|
const user = state.users.find((item) => item.account === account);
|
|
if (!user) return reply(response, -1, [], '登录已过期');
|
|
|
|
if (path === 'auth.admin/mySelf') {
|
|
return reply(response, 1, {
|
|
user: { ...clone(user), role_ids: user.role_id.map(Number) },
|
|
menu: tree(state.menus.filter((menu) => Number(menu.is_disable) === 0 && menu.type !== 'A')),
|
|
permissions: permissions(user),
|
|
});
|
|
}
|
|
if (path === 'identity.hospitalSso/issue') {
|
|
if (!/^[A-Za-z0-9_-]{43}$/.test(body.code_challenge || '') || body.code_challenge_method !== 'S256') return reply(response, 0, [], '登录校验参数无效');
|
|
return reply(response, 1, { ticket: randomBytes(32).toString('hex') });
|
|
}
|
|
if (path === 'identity.session/logout') {
|
|
for (const [token, owner] of state.sessions) {
|
|
if (Number(body.all) === 1 ? owner === account : token === sourceToken) state.sessions.delete(token);
|
|
}
|
|
return reply(response);
|
|
}
|
|
if (path === 'identity.session/password') {
|
|
if (Number(user.is_paw) !== 0 && body.old_password !== state.passwords.get(account)) return reply(response, 0, [], '原密码错误');
|
|
if (body.password !== body.password_confirm || !body.password) return reply(response, 0, [], '密码确认不一致');
|
|
user.is_paw = 1;
|
|
state.passwords.set(account, body.password);
|
|
state.sensitiveValues.add(body.password);
|
|
for (const [token, owner] of state.sessions) {
|
|
if (owner === account) state.sessions.delete(token);
|
|
}
|
|
return reply(response);
|
|
}
|
|
|
|
const route = path.match(/^(auth\.(admin|role|menu)|dept\.(dept))\/(lists|all|detail|add|edit|delete)$/);
|
|
if (!route) return reply(response, 0, [], '未知合成源接口');
|
|
const kind = route[2] ?? route[3];
|
|
const operation = route[4];
|
|
const collection = { admin: state.users, role: state.roles, menu: state.menus, dept: state.depts }[kind];
|
|
if (operation === 'detail') {
|
|
const row = collection.find((item) => Number(item.id) === Number(url.searchParams.get('id') ?? body.id));
|
|
return row ? reply(response, 1, clone(row)) : reply(response, 0, [], '记录不存在');
|
|
}
|
|
if (operation === 'lists' || operation === 'all') {
|
|
if (kind === 'dept') return reply(response, 1, tree(collection));
|
|
if (kind === 'menu') {
|
|
const rows = operation === 'all'
|
|
? collection.filter((item) => Number(item.is_disable) === 0).map(({ id, pid, name }) => ({ id, pid, name }))
|
|
: collection;
|
|
const lists = tree(rows);
|
|
return reply(response, 1, operation === 'all' ? lists : { lists, count: collection.length });
|
|
}
|
|
if (operation === 'all') return reply(response, 1, clone(collection));
|
|
// Like the real role source, this API deliberately ignores keyword/disable.
|
|
const page = Math.max(1, Number(url.searchParams.get('page_no') ?? 1));
|
|
const size = Math.min(100, Math.max(1, Number(url.searchParams.get('page_size') ?? 25)));
|
|
return reply(response, 1, {
|
|
lists: clone(collection.slice((page - 1) * size, page * size)), count: collection.length,
|
|
page_no: page, page_size: size,
|
|
});
|
|
}
|
|
if (operation === 'add') {
|
|
const id = Math.max(0, ...collection.map((item) => Number(item.id))) + 1;
|
|
collection.push({ ...clone(body), id });
|
|
return reply(response, 1, { id });
|
|
}
|
|
const index = collection.findIndex((item) => Number(item.id) === Number(body.id));
|
|
if (index < 0) return reply(response, 0, [], '记录不存在');
|
|
if (operation === 'delete') {
|
|
collection.splice(index, 1);
|
|
return reply(response);
|
|
}
|
|
Object.assign(collection[index], clone(body));
|
|
return reply(response);
|
|
} catch {
|
|
// Fixture failures are deliberately generic; never echo request credentials.
|
|
reply(response, 0, [], '合成源请求格式错误');
|
|
}
|
|
});
|
|
|
|
await new Promise((resolve, reject) => {
|
|
server.once('error', reject);
|
|
server.listen(0, '127.0.0.1', resolve);
|
|
});
|
|
const { port } = server.address();
|
|
return {
|
|
url: `http://127.0.0.1:${port}/adminapi`, state, reset,
|
|
requests: (path) => state.log.filter((entry) => entry.path === path),
|
|
last: (path) => state.log.findLast((entry) => entry.path === path),
|
|
async close() {
|
|
server.closeAllConnections();
|
|
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
},
|
|
};
|
|
}
|