Sin descripción
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 our TURN relay if
  115. // configured. Two credential modes:
  116. // - Shared secret (recommended, coturn `use-auth-secret`): set TURN_SECRET and we mint
  117. // time-limited credentials per request (no permanent password is ever handed out, so
  118. // outsiders can't reuse your relay). Optional TURN_TTL seconds (default 24h).
  119. // - Static: set TURN_USERNAME + TURN_CREDENTIAL for a fixed long-term credential.
  120. route('GET', '/api/ice', async (req, res) => {
  121. const iceServers = [{ urls: 'stun:stun.l.google.com:19302' }];
  122. if (process.env.TURN_URLS) {
  123. const urls = process.env.TURN_URLS.split(',').map((u) => u.trim()).filter(Boolean);
  124. let username = process.env.TURN_USERNAME || '';
  125. let credential = process.env.TURN_CREDENTIAL || '';
  126. if (process.env.TURN_SECRET) {
  127. const ttl = parseInt(process.env.TURN_TTL || '86400', 10);
  128. username = String(Math.floor(Date.now() / 1000) + ttl); // coturn expects "<expiry>"
  129. credential = require('crypto').createHmac('sha1', process.env.TURN_SECRET).update(username).digest('base64');
  130. }
  131. iceServers.push({ urls, username, credential });
  132. }
  133. json(res, 200, { iceServers });
  134. });
  135. route('GET', '/api/me', async (req, res) => {
  136. const u = currentUser(req);
  137. if (!u) return json(res, 401, { error: 'unauthorized' });
  138. json(res, 200, { id: u.id, email: u.email, role: u.role, teamId: u.team_id, name: u.name || null });
  139. });
  140. // ---------- BizGaze SSO: agent arrives already logged in ----------
  141. route('GET', '/sso', async (req, res) => {
  142. if (!process.env.SSO_SECRET) { res.writeHead(503); return res.end('SSO not configured'); }
  143. const q = new URLSearchParams(req.url.split('?')[1] || '');
  144. const token = q.get('token') || '';
  145. const [payloadB64, sig] = token.split('.');
  146. const fail = (msg) => { res.writeHead(403, { 'Content-Type': 'text/plain' }); res.end(msg); };
  147. if (!payloadB64 || !sig) return fail('Invalid SSO token');
  148. const crypto = require('crypto');
  149. const expect = crypto.createHmac('sha256', process.env.SSO_SECRET).update(payloadB64).digest('base64url');
  150. const sigBuf = Buffer.from(sig), expBuf = Buffer.from(expect);
  151. if (sigBuf.length !== expBuf.length || !crypto.timingSafeEqual(sigBuf, expBuf)) return fail('Invalid SSO signature');
  152. let p; try { p = JSON.parse(Buffer.from(payloadB64, 'base64url').toString()); } catch { return fail('Invalid SSO payload'); }
  153. if (!p.email || !p.exp || p.exp < Math.floor(now() / 1000)) return fail('SSO token expired');
  154. let u = R.users.byEmail(p.email);
  155. if (!u) {
  156. const team = R.teams.first();
  157. if (!team) return fail('No team configured');
  158. const { hash, salt } = A.hashPassword(A.token());
  159. const role = (p.role === 'admin' || p.role === 'viewer') ? p.role : 'technician';
  160. const userId = R.users.create({ tenantId: team.id, email: p.email, hash, salt, role, name: p.name || null, mfaSecret: A.newMfaSecret() });
  161. u = R.users.byId(userId);
  162. audit({ team_id: team.id, user_id: userId, user_email: p.email, action: 'sso_user_created', detail: p.name || '' });
  163. } else if (p.name && p.name !== u.name) {
  164. R.users.setName(u.id, p.name);
  165. }
  166. if (u.active === 0) return fail('Account deactivated');
  167. const tok = A.token();
  168. R.authSessions.create({ token: tok, userId: u.id, mfaPassed: true, ttl: SESSION_TTL });
  169. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'login', detail: 'via BizGaze SSO' });
  170. const dest = '/connect' + (p.ticket ? ('?ticket=' + encodeURIComponent(p.ticket)) : '');
  171. res.writeHead(302, { 'Set-Cookie': `sid=${tok}; HttpOnly; Path=/; Max-Age=${SESSION_TTL / 1000}`, Location: dest });
  172. res.end();
  173. });
  174. // Admin adds an agent login to their team
  175. route('POST', '/api/users', async (req, res) => {
  176. const u = currentUser(req);
  177. if (!u) return json(res, 401, { error: 'unauthorized' });
  178. if (u.role !== 'admin') return json(res, 403, { error: 'only admins can add agents' });
  179. // With BizGaze as the identity provider, logins are created in BizGaze — not here.
  180. // (Creating local accounts is what previously shadowed BizGaze and split tenants.)
  181. 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.' });
  182. const { email, password, name, role } = await readBody(req);
  183. if (!email || !password) return json(res, 400, { error: 'email and temporary password required' });
  184. if (R.users.emailExists(email))
  185. return json(res, 409, { error: 'email already registered' });
  186. const { hash, salt } = A.hashPassword(password);
  187. const r = (role === 'admin' || role === 'viewer') ? role : 'technician';
  188. const userId = R.users.create({ tenantId: u.team_id, email, hash, salt, role: r, name: name || null, mfaSecret: A.newMfaSecret() });
  189. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_added', detail: email + ' (' + r + ')' });
  190. json(res, 200, { ok: true, id: userId, email, role: r });
  191. });
  192. // List the team's agents
  193. route('GET', '/api/users', async (req, res) => {
  194. const u = currentUser(req);
  195. if (!u) return json(res, 401, { error: 'unauthorized' });
  196. const rows = R.users.listByTenant(u.team_id);
  197. json(res, 200, rows);
  198. });
  199. // First-login MFA self-setup: a logged-in (password ok) user who hasn't enabled MFA yet
  200. route('GET', '/api/mfa/setup', async (req, res) => {
  201. const u = currentUser(req, { requireMfa: false });
  202. if (!u) return json(res, 401, { error: 'unauthorized' });
  203. if (u.mfa_enabled) return json(res, 400, { error: 'MFA already enabled' });
  204. json(res, 200, { secret: u.mfa_secret, otpauthUrl: A.otpauthUrl(u.mfa_secret, u.email) });
  205. });
  206. // Admin manages an agent: reset password, rename, deactivate/activate, delete.
  207. route('POST', '/api/users/manage', async (req, res) => {
  208. const u = currentUser(req);
  209. if (!u) return json(res, 401, { error: 'unauthorized' });
  210. if (u.role !== 'admin') return json(res, 403, { error: 'only admins can manage agents' });
  211. const { id, action, password, name } = await readBody(req);
  212. const target = R.users.inTenant(id, u.team_id);
  213. if (!target) return json(res, 404, { error: 'no such agent' });
  214. switch (action) {
  215. case 'reset-password': {
  216. if (!password || String(password).length < 8) return json(res, 400, { error: 'new password must be at least 8 characters' });
  217. const { hash, salt } = A.hashPassword(password);
  218. R.users.setPassword(target.id, hash, salt);
  219. R.authSessions.deleteByUser(target.id); // force re-login
  220. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_password_reset', detail: target.email });
  221. return json(res, 200, { ok: true });
  222. }
  223. case 'rename': {
  224. const clean = String(name || '').trim().slice(0, 60);
  225. if (!clean) return json(res, 400, { error: 'name required' });
  226. R.users.setName(target.id, clean);
  227. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_renamed', detail: target.email + ' -> ' + clean });
  228. return json(res, 200, { ok: true, name: clean });
  229. }
  230. case 'deactivate': {
  231. if (target.id === u.id) return json(res, 400, { error: 'you cannot deactivate your own account' });
  232. R.users.setActive(target.id, false);
  233. R.authSessions.deleteByUser(target.id);
  234. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_deactivated', detail: target.email });
  235. return json(res, 200, { ok: true });
  236. }
  237. case 'activate': {
  238. R.users.setActive(target.id, true);
  239. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_activated', detail: target.email });
  240. return json(res, 200, { ok: true });
  241. }
  242. case 'delete': {
  243. if (target.id === u.id) return json(res, 400, { error: 'you cannot delete your own account' });
  244. R.authSessions.deleteByUser(target.id);
  245. R.users.remove(target.id);
  246. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_deleted', detail: target.email });
  247. return json(res, 200, { ok: true });
  248. }
  249. default: return json(res, 400, { error: 'unknown action' });
  250. }
  251. });
  252. // Session report: one row per session, filterable by agent and date period
  253. route('GET', '/api/report', async (req, res) => {
  254. const u = currentUser(req);
  255. if (!u) return json(res, 401, { error: 'unauthorized' });
  256. const q = new URLSearchParams(req.url.split('?')[1] || '');
  257. // Admins see the whole team (and may filter by agent); everyone else sees only
  258. // their own sessions, regardless of any agent filter passed.
  259. const agentEmail = u.role !== 'admin' ? u.email : (q.get('agent') || null);
  260. const from = q.get('from') ? new Date(q.get('from') + 'T00:00:00').getTime() : null;
  261. const to = q.get('to') ? new Date(q.get('to') + 'T23:59:59').getTime() : null;
  262. json(res, 200, R.sessionsLog.report({ tenantId: u.team_id, agentEmail, from, to }));
  263. });
  264. // List machines for the team (with live online status from signaling layer)
  265. route('GET', '/api/machines', async (req, res) => {
  266. const u = currentUser(req);
  267. if (!u) return json(res, 401, { error: 'unauthorized' });
  268. const rows = R.machines.listByTenant(u.team_id);
  269. json(res, 200, rows.map((m) => ({ ...m, online: onlineAgents.has(m.id) })));
  270. });
  271. // Create a machine enrollment token (admin/technician). Agent uses it to come online.
  272. route('POST', '/api/machines', async (req, res) => {
  273. const u = currentUser(req);
  274. if (!u) return json(res, 401, { error: 'unauthorized' });
  275. if (u.role === 'viewer') return json(res, 403, { error: 'forbidden' });
  276. const { name, unattended } = await readBody(req);
  277. const enroll = A.token();
  278. const mId = R.machines.create({ tenantId: u.team_id, name: name || 'Unnamed PC', enrollToken: enroll, unattended: !!unattended });
  279. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, machine_id: mId, machine_name: name, action: 'machine_enrolled' });
  280. json(res, 200, { id: mId, enrollToken: enroll });
  281. });
  282. route('GET', '/api/audit', async (req, res) => {
  283. const u = currentUser(req);
  284. if (!u) return json(res, 401, { error: 'unauthorized' });
  285. const rows = R.audit.listByTenant(u.team_id);
  286. json(res, 200, rows);
  287. });
  288. // ---------- session recording: upload (agent) ----------
  289. const MAX_REC_BYTES = 500 * 1024 * 1024; // 500 MB safety cap
  290. route('POST', '/api/recording', async (req, res) => {
  291. const u = currentUser(req);
  292. if (!u) return json(res, 401, { error: 'unauthorized' });
  293. const params = new URLSearchParams(req.url.split('?')[1] || '');
  294. const sid = params.get('sessionId');
  295. const ext = params.get('ext') === 'mp4' ? 'mp4' : 'webm'; // container chosen by the recorder
  296. if (!sid) return json(res, 400, { error: 'sessionId required' });
  297. const row = R.sessionsLog.byIdInTenant(sid, u.team_id);
  298. if (!row) return json(res, 404, { error: 'no such session' });
  299. const chunks = []; let total = 0, aborted = false;
  300. req.on('data', (c) => { total += c.length; if (total > MAX_REC_BYTES) { aborted = true; req.destroy(); return; } chunks.push(c); });
  301. req.on('end', () => {
  302. if (aborted) return json(res, 413, { error: 'recording too large' });
  303. const fname = sid + '.' + ext;
  304. try {
  305. fs.writeFileSync(path.join(REC_DIR, fname), Buffer.concat(chunks));
  306. R.sessionsLog.setRecording(sid, fname);
  307. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'recording_saved', detail: 'session ' + sid });
  308. json(res, 200, { ok: true });
  309. } catch (e) { json(res, 500, { error: 'could not save recording' }); }
  310. });
  311. req.on('error', () => { try { res.end(); } catch (e) {} });
  312. });
  313. route('POST', '/api/transcript', async (req, res) => {
  314. const u = currentUser(req);
  315. if (!u) return json(res, 401, { error: 'unauthorized' });
  316. const sid = new URLSearchParams(req.url.split('?')[1] || '').get('sessionId');
  317. if (!sid) return json(res, 400, { error: 'sessionId required' });
  318. const row = R.sessionsLog.byIdInTenant(sid, u.team_id);
  319. if (!row) return json(res, 404, { error: 'no such session' });
  320. const chunks = []; let total = 0, aborted = false;
  321. req.on('data', (c) => { total += c.length; if (total > 5 * 1024 * 1024) { aborted = true; req.destroy(); return; } chunks.push(c); });
  322. req.on('end', () => {
  323. if (aborted) return json(res, 413, { error: 'transcript too large' });
  324. const fname = sid + '.txt';
  325. try {
  326. fs.writeFileSync(path.join(TRANS_DIR, fname), Buffer.concat(chunks));
  327. R.sessionsLog.setTranscript(sid, fname);
  328. json(res, 200, { ok: true });
  329. } catch (e) { json(res, 500, { error: 'could not save transcript' }); }
  330. });
  331. req.on('error', () => { try { res.end(); } catch (e) {} });
  332. });
  333. // API versioning: alias every /api/* route under /api/v1/* — a frozen contract for
  334. // native desktop/mobile clients. The web app keeps using the unversioned paths, and
  335. // both share the same handlers. (/sso is a browser redirect, intentionally unversioned.)
  336. for (const key of Object.keys(routes)) {
  337. const m = key.match(/^(\S+) \/api\/(.+)$/);
  338. if (m) routes[`${m[1]} /api/v1/${m[2]}`] = routes[key];
  339. }
  340. module.exports = routes;