Nav apraksta
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

routes.js 19KB

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