Без опису
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // HTTP JSON API routes (auth, MFA, users, machines, report, audit, media uploads, SSO).
  2. // Returns a { "METHOD /path": handler } map consumed by server.js.
  3. const fs = require('fs');
  4. const path = require('path');
  5. const R = require('./repos');
  6. const A = require('./auth');
  7. const BZ = require('./bizgaze');
  8. const { now, json, readBody, parseCookies } = require('./lib');
  9. const { audit, currentUser } = require('./session');
  10. const { onlineAgents } = require('./presence');
  11. const { REC_DIR, TRANS_DIR, SESSION_TTL } = require('./config');
  12. const routes = {};
  13. const route = (method, p, fn) => (routes[`${method} ${p}`] = fn);
  14. // Register: creates a team + admin user. MFA must be set up before full access.
  15. route('POST', '/api/register', async (req, res) => {
  16. const anyUser = R.users.anyExists();
  17. if (anyUser && process.env.ALLOW_REGISTRATION !== '1')
  18. return json(res, 403, { error: 'Registration is closed. Contact your administrator.' });
  19. const { email, password, teamName } = await readBody(req);
  20. if (!email || !password) return json(res, 400, { error: 'email and password required' });
  21. if (R.users.emailExists(email))
  22. return json(res, 409, { error: 'email already registered' });
  23. const { hash, salt } = A.hashPassword(password);
  24. const team = R.teams.create(teamName || `${email}'s team`);
  25. const userId = R.users.create({ tenantId: team.id, email, hash, salt, role: 'admin', name: null, mfaSecret: A.newMfaSecret() });
  26. audit({ team_id: team.id, user_id: userId, user_email: email, action: 'user_registered' });
  27. json(res, 200, { ok: true });
  28. });
  29. // Verify MFA enrollment (confirm the user scanned the QR / entered code)
  30. route('POST', '/api/mfa/enable', async (req, res) => {
  31. const { email, code } = await readBody(req);
  32. const u = R.users.byEmail(email);
  33. if (!u) return json(res, 404, { error: 'no such user' });
  34. if (!A.verifyTotp(u.mfa_secret, code)) return json(res, 401, { error: 'invalid code' });
  35. R.users.enableMfa(u.id);
  36. json(res, 200, { ok: true });
  37. });
  38. // Provision (or refresh) a local user from a successful BizGaze identity check.
  39. // The local row exists so sessions, audit, and team-scoped data work; BizGaze stays
  40. // the source of truth for credentials (the local password is random + unused).
  41. function provisionFromBizgaze(email, bz) {
  42. const existing = R.users.byEmail(email);
  43. if (!existing) {
  44. const team = R.teams.first() || R.teams.create('BizGaze');
  45. const { hash, salt } = A.hashPassword(A.token());
  46. const role = bz.isAdmin ? 'admin' : 'technician';
  47. const id = R.users.create({ tenantId: team.id, email, hash, salt, role, name: bz.name || null, mfaSecret: A.newMfaSecret() });
  48. audit({ team_id: team.id, user_id: id, user_email: email, action: 'sso_user_created', detail: 'via BizGaze' });
  49. return R.users.byId(id);
  50. }
  51. if (bz.name && bz.name !== existing.name) R.users.setName(existing.id, bz.name);
  52. return R.users.byId(existing.id);
  53. }
  54. // Login: validates locally first (seeded/bootstrap accounts), then against BizGaze
  55. // (the identity provider) when BIZGAZE_LOGIN_URL is configured. Sets a session cookie.
  56. route('POST', '/api/login', async (req, res) => {
  57. const { email, password, remember } = await readBody(req);
  58. if (!email || !password) return json(res, 400, { error: 'email and password required' });
  59. const existing = R.users.byEmail(email);
  60. if (existing && existing.active === 0) return json(res, 403, { error: 'This account has been deactivated' });
  61. let u = (existing && A.verifyPassword(password, existing.pw_salt, existing.pw_hash)) ? existing : null;
  62. if (!u) {
  63. const bz = await BZ.validateLogin(email, password);
  64. if (bz.ok) u = provisionFromBizgaze(email, bz);
  65. else if (bz.error) return json(res, 503, { error: bz.error });
  66. }
  67. if (!u) return json(res, 401, { error: 'invalid credentials' });
  68. const tok = A.token();
  69. const ttl = remember ? 1000 * 60 * 60 * 24 * 30 : SESSION_TTL; // 30 days if remembered, else 24h
  70. R.authSessions.create({ token: tok, userId: u.id, mfaPassed: true, ttl });
  71. res.setHeader('Set-Cookie', `sid=${tok}; HttpOnly; Path=/; Max-Age=${ttl / 1000}`);
  72. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'login' });
  73. // Cookie for the web app; token in the body for native desktop/mobile clients
  74. // (they send it back as `Authorization: Bearer <token>`).
  75. json(res, 200, { ok: true, mfaRequired: false, token: tok, expiresAt: now() + ttl });
  76. });
  77. // Login step 2: TOTP code -> marks session mfa_passed
  78. route('POST', '/api/login/mfa', async (req, res) => {
  79. const { code } = await readBody(req);
  80. const tok = parseCookies(req).sid;
  81. const s = tok && R.authSessions.byToken(tok);
  82. if (!s) return json(res, 401, { error: 'no session' });
  83. const u = R.users.byId(s.user_id);
  84. if (!A.verifyTotp(u.mfa_secret, code)) return json(res, 401, { error: 'invalid code' });
  85. R.authSessions.markMfaPassed(tok);
  86. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'login' });
  87. json(res, 200, { ok: true });
  88. });
  89. route('POST', '/api/logout', async (req, res) => {
  90. const tok = parseCookies(req).sid;
  91. if (tok) R.authSessions.deleteByToken(tok);
  92. res.setHeader('Set-Cookie', 'sid=; HttpOnly; Path=/; Max-Age=0');
  93. json(res, 200, { ok: true });
  94. });
  95. route('GET', '/api/setup-state', async (req, res) => {
  96. const anyUser = R.users.anyExists();
  97. json(res, 200, { registrationOpen: !anyUser || process.env.ALLOW_REGISTRATION === '1' });
  98. });
  99. // ICE servers for WebRTC. Always includes a public STUN; adds managed TURN if
  100. // configured via env (TURN_URLS comma-separated, TURN_USERNAME, TURN_CREDENTIAL).
  101. route('GET', '/api/ice', async (req, res) => {
  102. const iceServers = [{ urls: 'stun:stun.l.google.com:19302' }];
  103. if (process.env.TURN_URLS) {
  104. iceServers.push({
  105. urls: process.env.TURN_URLS.split(',').map((u) => u.trim()).filter(Boolean),
  106. username: process.env.TURN_USERNAME || '',
  107. credential: process.env.TURN_CREDENTIAL || '',
  108. });
  109. }
  110. json(res, 200, { iceServers });
  111. });
  112. route('GET', '/api/me', async (req, res) => {
  113. const u = currentUser(req);
  114. if (!u) return json(res, 401, { error: 'unauthorized' });
  115. json(res, 200, { id: u.id, email: u.email, role: u.role, teamId: u.team_id, name: u.name || null });
  116. });
  117. // ---------- BizGaze SSO: agent arrives already logged in ----------
  118. route('GET', '/sso', async (req, res) => {
  119. if (!process.env.SSO_SECRET) { res.writeHead(503); return res.end('SSO not configured'); }
  120. const q = new URLSearchParams(req.url.split('?')[1] || '');
  121. const token = q.get('token') || '';
  122. const [payloadB64, sig] = token.split('.');
  123. const fail = (msg) => { res.writeHead(403, { 'Content-Type': 'text/plain' }); res.end(msg); };
  124. if (!payloadB64 || !sig) return fail('Invalid SSO token');
  125. const crypto = require('crypto');
  126. const expect = crypto.createHmac('sha256', process.env.SSO_SECRET).update(payloadB64).digest('base64url');
  127. const sigBuf = Buffer.from(sig), expBuf = Buffer.from(expect);
  128. if (sigBuf.length !== expBuf.length || !crypto.timingSafeEqual(sigBuf, expBuf)) return fail('Invalid SSO signature');
  129. let p; try { p = JSON.parse(Buffer.from(payloadB64, 'base64url').toString()); } catch { return fail('Invalid SSO payload'); }
  130. if (!p.email || !p.exp || p.exp < Math.floor(now() / 1000)) return fail('SSO token expired');
  131. let u = R.users.byEmail(p.email);
  132. if (!u) {
  133. const team = R.teams.first();
  134. if (!team) return fail('No team configured');
  135. const { hash, salt } = A.hashPassword(A.token());
  136. const role = (p.role === 'admin' || p.role === 'viewer') ? p.role : 'technician';
  137. const userId = R.users.create({ tenantId: team.id, email: p.email, hash, salt, role, name: p.name || null, mfaSecret: A.newMfaSecret() });
  138. u = R.users.byId(userId);
  139. audit({ team_id: team.id, user_id: userId, user_email: p.email, action: 'sso_user_created', detail: p.name || '' });
  140. } else if (p.name && p.name !== u.name) {
  141. R.users.setName(u.id, p.name);
  142. }
  143. if (u.active === 0) return fail('Account deactivated');
  144. const tok = A.token();
  145. R.authSessions.create({ token: tok, userId: u.id, mfaPassed: true, ttl: SESSION_TTL });
  146. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'login', detail: 'via BizGaze SSO' });
  147. const dest = '/connect' + (p.ticket ? ('?ticket=' + encodeURIComponent(p.ticket)) : '');
  148. res.writeHead(302, { 'Set-Cookie': `sid=${tok}; HttpOnly; Path=/; Max-Age=${SESSION_TTL / 1000}`, Location: dest });
  149. res.end();
  150. });
  151. // Admin adds an agent login to their team
  152. route('POST', '/api/users', async (req, res) => {
  153. const u = currentUser(req);
  154. if (!u) return json(res, 401, { error: 'unauthorized' });
  155. if (u.role !== 'admin') return json(res, 403, { error: 'only admins can add agents' });
  156. const { email, password, name, role } = await readBody(req);
  157. if (!email || !password) return json(res, 400, { error: 'email and temporary password required' });
  158. if (R.users.emailExists(email))
  159. return json(res, 409, { error: 'email already registered' });
  160. const { hash, salt } = A.hashPassword(password);
  161. const r = (role === 'admin' || role === 'viewer') ? role : 'technician';
  162. const userId = R.users.create({ tenantId: u.team_id, email, hash, salt, role: r, name: name || null, mfaSecret: A.newMfaSecret() });
  163. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_added', detail: email + ' (' + r + ')' });
  164. json(res, 200, { ok: true, id: userId, email, role: r });
  165. });
  166. // List the team's agents
  167. route('GET', '/api/users', async (req, res) => {
  168. const u = currentUser(req);
  169. if (!u) return json(res, 401, { error: 'unauthorized' });
  170. const rows = R.users.listByTenant(u.team_id);
  171. json(res, 200, rows);
  172. });
  173. // First-login MFA self-setup: a logged-in (password ok) user who hasn't enabled MFA yet
  174. route('GET', '/api/mfa/setup', async (req, res) => {
  175. const u = currentUser(req, { requireMfa: false });
  176. if (!u) return json(res, 401, { error: 'unauthorized' });
  177. if (u.mfa_enabled) return json(res, 400, { error: 'MFA already enabled' });
  178. json(res, 200, { secret: u.mfa_secret, otpauthUrl: A.otpauthUrl(u.mfa_secret, u.email) });
  179. });
  180. // Admin manages an agent: reset password, rename, deactivate/activate, delete.
  181. route('POST', '/api/users/manage', async (req, res) => {
  182. const u = currentUser(req);
  183. if (!u) return json(res, 401, { error: 'unauthorized' });
  184. if (u.role !== 'admin') return json(res, 403, { error: 'only admins can manage agents' });
  185. const { id, action, password, name } = await readBody(req);
  186. const target = R.users.inTenant(id, u.team_id);
  187. if (!target) return json(res, 404, { error: 'no such agent' });
  188. switch (action) {
  189. case 'reset-password': {
  190. if (!password || String(password).length < 8) return json(res, 400, { error: 'new password must be at least 8 characters' });
  191. const { hash, salt } = A.hashPassword(password);
  192. R.users.setPassword(target.id, hash, salt);
  193. R.authSessions.deleteByUser(target.id); // force re-login
  194. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_password_reset', detail: target.email });
  195. return json(res, 200, { ok: true });
  196. }
  197. case 'rename': {
  198. const clean = String(name || '').trim().slice(0, 60);
  199. if (!clean) return json(res, 400, { error: 'name required' });
  200. R.users.setName(target.id, clean);
  201. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_renamed', detail: target.email + ' -> ' + clean });
  202. return json(res, 200, { ok: true, name: clean });
  203. }
  204. case 'deactivate': {
  205. if (target.id === u.id) return json(res, 400, { error: 'you cannot deactivate your own account' });
  206. R.users.setActive(target.id, false);
  207. R.authSessions.deleteByUser(target.id);
  208. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_deactivated', detail: target.email });
  209. return json(res, 200, { ok: true });
  210. }
  211. case 'activate': {
  212. R.users.setActive(target.id, true);
  213. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_activated', detail: target.email });
  214. return json(res, 200, { ok: true });
  215. }
  216. case 'delete': {
  217. if (target.id === u.id) return json(res, 400, { error: 'you cannot delete your own account' });
  218. R.authSessions.deleteByUser(target.id);
  219. R.users.remove(target.id);
  220. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_deleted', detail: target.email });
  221. return json(res, 200, { ok: true });
  222. }
  223. default: return json(res, 400, { error: 'unknown action' });
  224. }
  225. });
  226. // Session report: one row per session, filterable by agent and date period
  227. route('GET', '/api/report', async (req, res) => {
  228. const u = currentUser(req);
  229. if (!u) return json(res, 401, { error: 'unauthorized' });
  230. const q = new URLSearchParams(req.url.split('?')[1] || '');
  231. // Admins see the whole team (and may filter by agent); everyone else sees only
  232. // their own sessions, regardless of any agent filter passed.
  233. const agentEmail = u.role !== 'admin' ? u.email : (q.get('agent') || null);
  234. const from = q.get('from') ? new Date(q.get('from') + 'T00:00:00').getTime() : null;
  235. const to = q.get('to') ? new Date(q.get('to') + 'T23:59:59').getTime() : null;
  236. json(res, 200, R.sessionsLog.report({ tenantId: u.team_id, agentEmail, from, to }));
  237. });
  238. // List machines for the team (with live online status from signaling layer)
  239. route('GET', '/api/machines', async (req, res) => {
  240. const u = currentUser(req);
  241. if (!u) return json(res, 401, { error: 'unauthorized' });
  242. const rows = R.machines.listByTenant(u.team_id);
  243. json(res, 200, rows.map((m) => ({ ...m, online: onlineAgents.has(m.id) })));
  244. });
  245. // Create a machine enrollment token (admin/technician). Agent uses it to come online.
  246. route('POST', '/api/machines', async (req, res) => {
  247. const u = currentUser(req);
  248. if (!u) return json(res, 401, { error: 'unauthorized' });
  249. if (u.role === 'viewer') return json(res, 403, { error: 'forbidden' });
  250. const { name, unattended } = await readBody(req);
  251. const enroll = A.token();
  252. const mId = R.machines.create({ tenantId: u.team_id, name: name || 'Unnamed PC', enrollToken: enroll, unattended: !!unattended });
  253. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, machine_id: mId, machine_name: name, action: 'machine_enrolled' });
  254. json(res, 200, { id: mId, enrollToken: enroll });
  255. });
  256. route('GET', '/api/audit', async (req, res) => {
  257. const u = currentUser(req);
  258. if (!u) return json(res, 401, { error: 'unauthorized' });
  259. const rows = R.audit.listByTenant(u.team_id);
  260. json(res, 200, rows);
  261. });
  262. // ---------- session recording: upload (agent) ----------
  263. const MAX_REC_BYTES = 500 * 1024 * 1024; // 500 MB safety cap
  264. route('POST', '/api/recording', async (req, res) => {
  265. const u = currentUser(req);
  266. if (!u) return json(res, 401, { error: 'unauthorized' });
  267. const params = new URLSearchParams(req.url.split('?')[1] || '');
  268. const sid = params.get('sessionId');
  269. const ext = params.get('ext') === 'mp4' ? 'mp4' : 'webm'; // container chosen by the recorder
  270. if (!sid) return json(res, 400, { error: 'sessionId required' });
  271. const row = R.sessionsLog.byIdInTenant(sid, u.team_id);
  272. if (!row) return json(res, 404, { error: 'no such session' });
  273. const chunks = []; let total = 0, aborted = false;
  274. req.on('data', (c) => { total += c.length; if (total > MAX_REC_BYTES) { aborted = true; req.destroy(); return; } chunks.push(c); });
  275. req.on('end', () => {
  276. if (aborted) return json(res, 413, { error: 'recording too large' });
  277. const fname = sid + '.' + ext;
  278. try {
  279. fs.writeFileSync(path.join(REC_DIR, fname), Buffer.concat(chunks));
  280. R.sessionsLog.setRecording(sid, fname);
  281. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'recording_saved', detail: 'session ' + sid });
  282. json(res, 200, { ok: true });
  283. } catch (e) { json(res, 500, { error: 'could not save recording' }); }
  284. });
  285. req.on('error', () => { try { res.end(); } catch (e) {} });
  286. });
  287. route('POST', '/api/transcript', async (req, res) => {
  288. const u = currentUser(req);
  289. if (!u) return json(res, 401, { error: 'unauthorized' });
  290. const sid = new URLSearchParams(req.url.split('?')[1] || '').get('sessionId');
  291. if (!sid) return json(res, 400, { error: 'sessionId required' });
  292. const row = R.sessionsLog.byIdInTenant(sid, u.team_id);
  293. if (!row) return json(res, 404, { error: 'no such session' });
  294. const chunks = []; let total = 0, aborted = false;
  295. req.on('data', (c) => { total += c.length; if (total > 5 * 1024 * 1024) { aborted = true; req.destroy(); return; } chunks.push(c); });
  296. req.on('end', () => {
  297. if (aborted) return json(res, 413, { error: 'transcript too large' });
  298. const fname = sid + '.txt';
  299. try {
  300. fs.writeFileSync(path.join(TRANS_DIR, fname), Buffer.concat(chunks));
  301. R.sessionsLog.setTranscript(sid, fname);
  302. json(res, 200, { ok: true });
  303. } catch (e) { json(res, 500, { error: 'could not save transcript' }); }
  304. });
  305. req.on('error', () => { try { res.end(); } catch (e) {} });
  306. });
  307. // API versioning: alias every /api/* route under /api/v1/* — a frozen contract for
  308. // native desktop/mobile clients. The web app keeps using the unversioned paths, and
  309. // both share the same handlers. (/sso is a browser redirect, intentionally unversioned.)
  310. for (const key of Object.keys(routes)) {
  311. const m = key.match(/^(\S+) \/api\/(.+)$/);
  312. if (m) routes[`${m[1]} /api/v1/${m[2]}`] = routes[key];
  313. }
  314. module.exports = routes;