Ei kuvausta
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.

server.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // Remote Access Platform — backend server
  2. // HTTP JSON API (auth, MFA, machines, audit) + authenticated WebSocket signaling.
  3. const http = require('http');
  4. const https = require('https');
  5. const fs = require('fs');
  6. const path = require('path');
  7. const { WebSocketServer } = require('ws');
  8. const db = require('./db');
  9. const A = require('./auth');
  10. const PORT = process.env.PORT || 8090;
  11. const HTTPS_PORT = process.env.HTTPS_PORT || 8443;
  12. const PUBLIC_DIR = path.join(__dirname, 'public');
  13. const SESSION_TTL = 1000 * 60 * 60 * 12; // 12h
  14. // ---------- helpers ----------
  15. const now = () => Date.now();
  16. const json = (res, code, body) => {
  17. res.writeHead(code, { 'Content-Type': 'application/json' });
  18. res.end(JSON.stringify(body));
  19. };
  20. function readBody(req) {
  21. return new Promise((resolve) => {
  22. let data = '';
  23. req.on('data', (c) => (data += c));
  24. req.on('end', () => {
  25. try { resolve(data ? JSON.parse(data) : {}); } catch { resolve({}); }
  26. });
  27. });
  28. }
  29. function parseCookies(req) {
  30. const out = {};
  31. (req.headers.cookie || '').split(';').forEach((c) => {
  32. const [k, ...v] = c.trim().split('=');
  33. if (k) out[k] = decodeURIComponent(v.join('='));
  34. });
  35. return out;
  36. }
  37. function audit(entry) {
  38. db.prepare(
  39. `INSERT INTO audit_log (team_id,user_id,user_email,machine_id,machine_name,action,detail,at)
  40. VALUES (@team_id,@user_id,@user_email,@machine_id,@machine_name,@action,@detail,@at)`
  41. ).run({
  42. team_id: entry.team_id, user_id: entry.user_id || null, user_email: entry.user_email || null,
  43. machine_id: entry.machine_id || null, machine_name: entry.machine_name || null,
  44. action: entry.action, detail: entry.detail || null, at: now(),
  45. });
  46. }
  47. // Resolve the logged-in user from the session cookie. Returns user row (with mfa state) or null.
  48. function currentUser(req, { requireMfa = true } = {}) {
  49. const tok = parseCookies(req).sid;
  50. if (!tok) return null;
  51. const s = db.prepare('SELECT * FROM sessions_auth WHERE token=?').get(tok);
  52. if (!s || s.expires_at < now()) return null;
  53. if (requireMfa && !s.mfa_passed) return null;
  54. const u = db.prepare('SELECT * FROM users WHERE id=?').get(s.user_id);
  55. if (!u || u.active === 0) return null;
  56. return { ...u, _session: s };
  57. }
  58. // ---------- HTTP API ----------
  59. const routes = {};
  60. const route = (method, p, fn) => (routes[`${method} ${p}`] = fn);
  61. // Register: creates a team + admin user. MFA must be set up before full access.
  62. route('POST', '/api/register', async (req, res) => {
  63. const { email, password, teamName } = await readBody(req);
  64. if (!email || !password) return json(res, 400, { error: 'email and password required' });
  65. if (db.prepare('SELECT 1 FROM users WHERE email=?').get(email))
  66. return json(res, 409, { error: 'email already registered' });
  67. const teamId = A.id(), userId = A.id();
  68. const { hash, salt } = A.hashPassword(password);
  69. const mfaSecret = A.newMfaSecret();
  70. db.prepare('INSERT INTO teams (id,name,created_at) VALUES (?,?,?)')
  71. .run(teamId, teamName || `${email}'s team`, now());
  72. db.prepare(`INSERT INTO users (id,team_id,email,pw_hash,pw_salt,role,mfa_secret,mfa_enabled,created_at)
  73. VALUES (?,?,?,?,?,?,?,0,?)`)
  74. .run(userId, teamId, email, hash, salt, 'admin', mfaSecret, now());
  75. audit({ team_id: teamId, user_id: userId, user_email: email, action: 'user_registered' });
  76. json(res, 200, { ok: true });
  77. });
  78. // Verify MFA enrollment (confirm the user scanned the QR / entered code)
  79. route('POST', '/api/mfa/enable', async (req, res) => {
  80. const { email, code } = await readBody(req);
  81. const u = db.prepare('SELECT * FROM users WHERE email=?').get(email);
  82. if (!u) return json(res, 404, { error: 'no such user' });
  83. if (!A.verifyTotp(u.mfa_secret, code)) return json(res, 401, { error: 'invalid code' });
  84. db.prepare('UPDATE users SET mfa_enabled=1 WHERE id=?').run(u.id);
  85. json(res, 200, { ok: true });
  86. });
  87. // Login step 1: email + password -> sets a session cookie (mfa not yet passed)
  88. route('POST', '/api/login', async (req, res) => {
  89. const { email, password } = await readBody(req);
  90. const u = db.prepare('SELECT * FROM users WHERE email=?').get(email);
  91. if (!u || !A.verifyPassword(password, u.pw_salt, u.pw_hash))
  92. return json(res, 401, { error: 'invalid credentials' });
  93. if (u.active === 0) return json(res, 403, { error: 'This account has been deactivated' });
  94. const tok = A.token();
  95. db.prepare('INSERT INTO sessions_auth (token,user_id,mfa_passed,created_at,expires_at) VALUES (?,?,1,?,?)')
  96. .run(tok, u.id, now(), now() + SESSION_TTL);
  97. res.setHeader('Set-Cookie', `sid=${tok}; HttpOnly; Path=/; Max-Age=${SESSION_TTL / 1000}`);
  98. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'login' });
  99. json(res, 200, { ok: true, mfaRequired: false });
  100. });
  101. // Login step 2: TOTP code -> marks session mfa_passed
  102. route('POST', '/api/login/mfa', async (req, res) => {
  103. const { code } = await readBody(req);
  104. const tok = parseCookies(req).sid;
  105. const s = tok && db.prepare('SELECT * FROM sessions_auth WHERE token=?').get(tok);
  106. if (!s) return json(res, 401, { error: 'no session' });
  107. const u = db.prepare('SELECT * FROM users WHERE id=?').get(s.user_id);
  108. if (!A.verifyTotp(u.mfa_secret, code)) return json(res, 401, { error: 'invalid code' });
  109. db.prepare('UPDATE sessions_auth SET mfa_passed=1 WHERE token=?').run(tok);
  110. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'login' });
  111. json(res, 200, { ok: true });
  112. });
  113. route('POST', '/api/logout', async (req, res) => {
  114. const tok = parseCookies(req).sid;
  115. if (tok) db.prepare('DELETE FROM sessions_auth WHERE token=?').run(tok);
  116. res.setHeader('Set-Cookie', 'sid=; HttpOnly; Path=/; Max-Age=0');
  117. json(res, 200, { ok: true });
  118. });
  119. route('GET', '/api/me', async (req, res) => {
  120. const u = currentUser(req);
  121. if (!u) return json(res, 401, { error: 'unauthorized' });
  122. json(res, 200, { id: u.id, email: u.email, role: u.role, teamId: u.team_id, name: u.name || null });
  123. });
  124. // Admin adds an agent login to their team
  125. route('POST', '/api/users', async (req, res) => {
  126. const u = currentUser(req);
  127. if (!u) return json(res, 401, { error: 'unauthorized' });
  128. if (u.role !== 'admin') return json(res, 403, { error: 'only admins can add agents' });
  129. const { email, password, name, role } = await readBody(req);
  130. if (!email || !password) return json(res, 400, { error: 'email and temporary password required' });
  131. if (db.prepare('SELECT 1 FROM users WHERE email=?').get(email))
  132. return json(res, 409, { error: 'email already registered' });
  133. const userId = A.id();
  134. const { hash, salt } = A.hashPassword(password);
  135. const mfaSecret = A.newMfaSecret();
  136. const r = (role === 'admin' || role === 'viewer') ? role : 'technician';
  137. db.prepare(`INSERT INTO users (id,team_id,email,pw_hash,pw_salt,role,name,mfa_secret,mfa_enabled,created_at)
  138. VALUES (?,?,?,?,?,?,?,?,0,?)`)
  139. .run(userId, u.team_id, email, hash, salt, r, (name || null), mfaSecret, now());
  140. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_added', detail: email + ' (' + r + ')' });
  141. json(res, 200, { ok: true, id: userId, email, role: r });
  142. });
  143. // List the team's agents
  144. route('GET', '/api/users', async (req, res) => {
  145. const u = currentUser(req);
  146. if (!u) return json(res, 401, { error: 'unauthorized' });
  147. const rows = db.prepare('SELECT id,email,name,role,active,created_at FROM users WHERE team_id=?').all(u.team_id);
  148. json(res, 200, rows);
  149. });
  150. // First-login MFA self-setup: a logged-in (password ok) user who hasn't enabled MFA yet
  151. route('GET', '/api/mfa/setup', async (req, res) => {
  152. const u = currentUser(req, { requireMfa: false });
  153. if (!u) return json(res, 401, { error: 'unauthorized' });
  154. if (u.mfa_enabled) return json(res, 400, { error: 'MFA already enabled' });
  155. json(res, 200, { secret: u.mfa_secret, otpauthUrl: A.otpauthUrl(u.mfa_secret, u.email) });
  156. });
  157. // Admin manages an agent: reset password, rename, deactivate/activate, delete.
  158. // (Display names are owned by the admin/BizGaze app — agents cannot edit them.)
  159. route('POST', '/api/users/manage', async (req, res) => {
  160. const u = currentUser(req);
  161. if (!u) return json(res, 401, { error: 'unauthorized' });
  162. if (u.role !== 'admin') return json(res, 403, { error: 'only admins can manage agents' });
  163. const { id, action, password, name } = await readBody(req);
  164. const target = db.prepare('SELECT * FROM users WHERE id=? AND team_id=?').get(id, u.team_id);
  165. if (!target) return json(res, 404, { error: 'no such agent' });
  166. switch (action) {
  167. case 'reset-password': {
  168. if (!password || String(password).length < 8) return json(res, 400, { error: 'new password must be at least 8 characters' });
  169. const { hash, salt } = A.hashPassword(password);
  170. db.prepare('UPDATE users SET pw_hash=?, pw_salt=? WHERE id=?').run(hash, salt, target.id);
  171. db.prepare('DELETE FROM sessions_auth WHERE user_id=?').run(target.id); // force re-login
  172. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_password_reset', detail: target.email });
  173. return json(res, 200, { ok: true });
  174. }
  175. case 'rename': {
  176. const clean = String(name || '').trim().slice(0, 60);
  177. if (!clean) return json(res, 400, { error: 'name required' });
  178. db.prepare('UPDATE users SET name=? WHERE id=?').run(clean, target.id);
  179. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_renamed', detail: target.email + ' -> ' + clean });
  180. return json(res, 200, { ok: true, name: clean });
  181. }
  182. case 'deactivate': {
  183. if (target.id === u.id) return json(res, 400, { error: 'you cannot deactivate your own account' });
  184. db.prepare('UPDATE users SET active=0 WHERE id=?').run(target.id);
  185. db.prepare('DELETE FROM sessions_auth WHERE user_id=?').run(target.id);
  186. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_deactivated', detail: target.email });
  187. return json(res, 200, { ok: true });
  188. }
  189. case 'activate': {
  190. db.prepare('UPDATE users SET active=1 WHERE id=?').run(target.id);
  191. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_activated', detail: target.email });
  192. return json(res, 200, { ok: true });
  193. }
  194. case 'delete': {
  195. if (target.id === u.id) return json(res, 400, { error: 'you cannot delete your own account' });
  196. db.prepare('DELETE FROM sessions_auth WHERE user_id=?').run(target.id);
  197. db.prepare('DELETE FROM users WHERE id=?').run(target.id);
  198. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, action: 'agent_deleted', detail: target.email });
  199. return json(res, 200, { ok: true });
  200. }
  201. default: return json(res, 400, { error: 'unknown action' });
  202. }
  203. });
  204. // Session report: one row per session, filterable by agent and date period
  205. route('GET', '/api/report', async (req, res) => {
  206. const u = currentUser(req);
  207. if (!u) return json(res, 401, { error: 'unauthorized' });
  208. const q = new URLSearchParams(req.url.split('?')[1] || '');
  209. let sql = 'SELECT * FROM sessions_log WHERE team_id=?';
  210. const args = [u.team_id];
  211. if (q.get('agent')) { sql += ' AND agent_email=?'; args.push(q.get('agent')); }
  212. if (q.get('from')) { sql += ' AND started_at>=?'; args.push(new Date(q.get('from') + 'T00:00:00').getTime()); }
  213. if (q.get('to')) { sql += ' AND started_at<=?'; args.push(new Date(q.get('to') + 'T23:59:59').getTime()); }
  214. sql += ' ORDER BY started_at DESC LIMIT 500';
  215. json(res, 200, db.prepare(sql).all(...args));
  216. });
  217. // List machines for the team (with live online status from signaling layer)
  218. route('GET', '/api/machines', async (req, res) => {
  219. const u = currentUser(req);
  220. if (!u) return json(res, 401, { error: 'unauthorized' });
  221. const rows = db.prepare('SELECT id,name,unattended,last_seen FROM machines WHERE team_id=?').all(u.team_id);
  222. json(res, 200, rows.map((m) => ({ ...m, online: onlineAgents.has(m.id) })));
  223. });
  224. // Create a machine enrollment token (admin/technician). Agent uses it to come online.
  225. route('POST', '/api/machines', async (req, res) => {
  226. const u = currentUser(req);
  227. if (!u) return json(res, 401, { error: 'unauthorized' });
  228. if (u.role === 'viewer') return json(res, 403, { error: 'forbidden' });
  229. const { name, unattended } = await readBody(req);
  230. const mId = A.id(), enroll = A.token();
  231. db.prepare('INSERT INTO machines (id,team_id,name,enroll_token,unattended,created_at) VALUES (?,?,?,?,?,?)')
  232. .run(mId, u.team_id, name || 'Unnamed PC', enroll, unattended ? 1 : 0, now());
  233. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, machine_id: mId, machine_name: name, action: 'machine_enrolled' });
  234. json(res, 200, { id: mId, enrollToken: enroll });
  235. });
  236. route('GET', '/api/audit', async (req, res) => {
  237. const u = currentUser(req);
  238. if (!u) return json(res, 401, { error: 'unauthorized' });
  239. const rows = db.prepare("SELECT * FROM audit_log WHERE team_id=? OR team_id='adhoc' ORDER BY at DESC LIMIT 200").all(u.team_id);
  240. json(res, 200, rows);
  241. });
  242. // ---------- static + router ----------
  243. const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' };
  244. function serveStatic(req, res) {
  245. let p = req.url.split('?')[0];
  246. if (p === '/') p = '/index.html';
  247. if (p === '/share') p = '/share.html';
  248. if (p === '/connect') p = '/connect.html';
  249. const fp = path.join(PUBLIC_DIR, path.normalize(p));
  250. if (!fp.startsWith(PUBLIC_DIR)) return json(res, 403, { error: 'forbidden' });
  251. fs.readFile(fp, (err, data) => {
  252. if (err) return json(res, 404, { error: 'not found' });
  253. const ct = MIME[path.extname(fp)] || 'application/octet-stream';
  254. res.writeHead(200, { 'Content-Type': ct, 'Cache-Control': 'no-cache' });
  255. res.end(data);
  256. });
  257. }
  258. const server = http.createServer(async (req, res) => {
  259. const key = `${req.method} ${req.url.split('?')[0]}`;
  260. if (routes[key]) return routes[key](req, res);
  261. if (req.method === 'GET') return serveStatic(req, res);
  262. json(res, 404, { error: 'not found' });
  263. });
  264. // ---------- WebSocket signaling ----------
  265. // Two kinds of WS clients:
  266. // agent -> authenticates with machine enroll_token, waits for session requests
  267. // viewer -> authenticated technician, requests a session to a machine
  268. // The server brokers consent and relays SDP/ICE. Media never traverses the server.
  269. const onlineAgents = new Map(); // machineId -> { ws, machine }
  270. const liveSessions = new Map(); // sessionId -> { agentWs, viewerWs, machine, user }
  271. const pendingShares = new Map(); // code -> { sharerWs, sessionId } (no-install ad-hoc shares)
  272. function onConnection(ws, req) {
  273. ws.on('message', (raw) => {
  274. let m; try { m = JSON.parse(raw); } catch { return; }
  275. handle(ws, m, req);
  276. });
  277. ws.on('close', () => cleanup(ws));
  278. }
  279. const wss = new WebSocketServer({ server, path: '/ws' });
  280. wss.on('connection', onConnection);
  281. function handle(ws, m, req) {
  282. switch (m.type) {
  283. // --- Agent comes online ---
  284. case 'agent-hello': {
  285. const machine = db.prepare('SELECT * FROM machines WHERE enroll_token=?').get(m.enrollToken);
  286. if (!machine) return ws.send(JSON.stringify({ type: 'error', message: 'invalid enroll token' }));
  287. ws.kind = 'agent'; ws.machineId = machine.id;
  288. onlineAgents.set(machine.id, { ws, machine });
  289. db.prepare('UPDATE machines SET last_seen=? WHERE id=?').run(now(), machine.id);
  290. ws.send(JSON.stringify({ type: 'agent-registered', machineId: machine.id, name: machine.name }));
  291. break;
  292. }
  293. // --- Technician requests control of a machine ---
  294. case 'viewer-connect': {
  295. const u = currentUser(req); // cookie sent on WS upgrade
  296. if (!u) return ws.send(JSON.stringify({ type: 'error', message: 'unauthorized' }));
  297. const agent = onlineAgents.get(m.machineId);
  298. const machine = db.prepare('SELECT * FROM machines WHERE id=? AND team_id=?').get(m.machineId, u.team_id);
  299. if (!machine) return ws.send(JSON.stringify({ type: 'error', message: 'no such machine' }));
  300. if (!agent) return ws.send(JSON.stringify({ type: 'error', message: 'machine offline' }));
  301. if (u.role === 'viewer' && false) {} // view-only still allowed to watch; control gated agent-side
  302. const sessionId = A.token(8);
  303. ws.kind = 'viewer'; ws.sessionId = sessionId;
  304. liveSessions.set(sessionId, { agentWs: agent.ws, viewerWs: ws, machine, user: u });
  305. audit({ team_id: u.team_id, user_id: u.id, user_email: u.email, machine_id: machine.id, machine_name: machine.name, action: 'session_requested' });
  306. // Ask the agent for consent (or auto-grant if unattended policy is on)
  307. agent.ws.sessionId = sessionId;
  308. agent.ws.send(JSON.stringify({
  309. type: 'session-request', sessionId,
  310. technician: u.email, unattended: !!machine.unattended,
  311. }));
  312. ws.send(JSON.stringify({ type: 'session-pending', sessionId, machineName: machine.name }));
  313. break;
  314. }
  315. // --- Agent grants/denies consent ---
  316. case 'consent': {
  317. const sess = liveSessions.get(m.sessionId);
  318. if (!sess) return;
  319. if (m.granted) {
  320. audit({ team_id: sess.machine.team_id, user_id: sess.user.id, user_email: sess.user.email, machine_id: sess.machine.id, machine_name: sess.machine.name, action: 'consent_granted', detail: sess.ticket ? 'Ticket ' + sess.ticket : (sess.machine.id ? null : 'Direct session') });
  321. try {
  322. db.prepare('INSERT INTO sessions_log (id,team_id,agent_email,agent_name,ticket,started_at) VALUES (?,?,?,?,?,?)')
  323. .run(m.sessionId, sess.machine.team_id, sess.user.email, (sess.agentName || sess.user.email), sess.ticket || null, now());
  324. } catch (e) { /* duplicate consent */ }
  325. sess.viewerWs.send(JSON.stringify({ type: 'session-ready', sessionId: m.sessionId }));
  326. sess.agentWs.send(JSON.stringify({ type: 'start-stream', sessionId: m.sessionId }));
  327. } else {
  328. audit({ team_id: sess.machine.team_id, user_id: sess.user.id, user_email: sess.user.email, machine_id: sess.machine.id, machine_name: sess.machine.name, action: 'consent_denied', detail: sess.ticket ? 'Ticket ' + sess.ticket : (sess.machine.id ? null : 'Direct session') });
  329. sess.viewerWs.send(JSON.stringify({ type: 'session-denied', sessionId: m.sessionId }));
  330. liveSessions.delete(m.sessionId);
  331. }
  332. break;
  333. }
  334. // --- No-install: end user opens /share, gets a one-time code ---
  335. case 'share-create': {
  336. let code;
  337. do { code = A.numericCode(6); } while (pendingShares.has(code));
  338. const sessionId = A.token(8);
  339. ws.kind = 'sharer'; ws.shareCode = code; ws.sessionId = sessionId;
  340. pendingShares.set(code, { sharerWs: ws, sessionId });
  341. ws.send(JSON.stringify({ type: 'share-code', code }));
  342. break;
  343. }
  344. // --- Logged-in agent enters the code (+ ticket) to connect ---
  345. case 'code-connect': {
  346. const agent = currentUser(req); // identity from the agent's authenticated session
  347. if (!agent) {
  348. return ws.send(JSON.stringify({ type: 'error', message: 'Please sign in as an agent first' }));
  349. }
  350. const ticket = String(m.ticket || '').trim() || null; // optional: direct sessions have no ticket
  351. const pend = pendingShares.get(String(m.code || '').trim());
  352. if (!pend || pend.sharerWs.readyState !== 1) {
  353. return ws.send(JSON.stringify({ type: 'error', message: 'Invalid or expired code' }));
  354. }
  355. pendingShares.delete(pend.sharerWs.shareCode);
  356. const sessionId = pend.sessionId;
  357. ws.kind = 'viewer'; ws.sessionId = sessionId;
  358. const agentName = agent.name || agent.email;
  359. const machine = { id: null, name: 'Support session ' + pend.sharerWs.shareCode, team_id: agent.team_id };
  360. const user = { id: agent.id, email: agent.email, team_id: agent.team_id };
  361. liveSessions.set(sessionId, { agentWs: pend.sharerWs, viewerWs: ws, machine, user, ticket, agentName });
  362. pend.sharerWs.sessionId = sessionId;
  363. audit({ team_id: agent.team_id, user_id: agent.id, user_email: agent.email, machine_name: machine.name, action: 'code_session_requested', detail: (ticket ? 'Ticket ' + ticket : 'Direct session (no ticket)') + ' · agent ' + agentName });
  364. pend.sharerWs.send(JSON.stringify({ type: 'share-request', sessionId, technician: agentName, ticket }));
  365. ws.send(JSON.stringify({ type: 'code-pending', sessionId }));
  366. break;
  367. }
  368. // --- Relay WebRTC signaling between the two peers ---
  369. case 'offer': case 'answer': case 'ice-candidate': {
  370. const sess = liveSessions.get(m.sessionId || ws.sessionId);
  371. if (!sess) return;
  372. const peer = ws === sess.agentWs ? sess.viewerWs : sess.agentWs;
  373. if (peer && peer.readyState === 1) peer.send(JSON.stringify(m));
  374. break;
  375. }
  376. case 'end-session': {
  377. endSession(ws.sessionId, m.reason || null);
  378. break;
  379. }
  380. }
  381. }
  382. function endSession(sessionId, reason) {
  383. const sess = liveSessions.get(sessionId);
  384. if (!sess) return;
  385. try { db.prepare('UPDATE sessions_log SET ended_at=? WHERE id=? AND ended_at IS NULL').run(now(), sessionId); } catch (e) {}
  386. audit({ team_id: sess.machine.team_id, user_id: sess.user.id, user_email: sess.user.email, machine_id: sess.machine.id, machine_name: sess.machine.name, action: 'session_ended', detail: sess.ticket ? 'Ticket ' + sess.ticket : (sess.machine.id ? null : 'Direct session') });
  387. [sess.agentWs, sess.viewerWs].forEach((p) => {
  388. if (p && p.readyState === 1) p.send(JSON.stringify({ type: 'session-ended', sessionId, reason: reason || null }));
  389. });
  390. liveSessions.delete(sessionId);
  391. }
  392. function cleanup(ws) {
  393. if (ws.kind === 'agent' && ws.machineId) onlineAgents.delete(ws.machineId);
  394. if (ws.kind === 'sharer' && ws.shareCode) pendingShares.delete(ws.shareCode);
  395. if (ws.sessionId) {
  396. for (const [sid, sess] of liveSessions) {
  397. if (sess.agentWs === ws || sess.viewerWs === ws) endSession(sid);
  398. }
  399. }
  400. }
  401. server.listen(PORT, () => {
  402. console.log(`HTTP on http://localhost:${PORT}`);
  403. });
  404. // HTTPS — required so other devices can share their screen (browsers block
  405. // screen capture on non-secure origins). Uses cert.pem/key.pem if present.
  406. let httpsServer = null;
  407. try {
  408. const certPath = path.join(__dirname, 'cert.pem');
  409. const keyPath = path.join(__dirname, 'key.pem');
  410. if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
  411. httpsServer = https.createServer(
  412. { cert: fs.readFileSync(certPath), key: fs.readFileSync(keyPath) },
  413. (req, res) => server.emit('request', req, res)
  414. );
  415. const wssSecure = new WebSocketServer({ server: httpsServer, path: '/ws' });
  416. wssSecure.on('connection', onConnection);
  417. httpsServer.listen(HTTPS_PORT, () => {
  418. console.log(`HTTPS on https://localhost:${HTTPS_PORT} (use this address from other devices)`);
  419. console.log(` End user shares screen: https://<this-pc-ip>:${HTTPS_PORT}/share`);
  420. console.log(` Technician connects: https://<this-pc-ip>:${HTTPS_PORT}/connect`);
  421. });
  422. } else {
  423. console.log('(No cert.pem/key.pem found — HTTPS disabled. Other devices can view but not share their screen.)');
  424. }
  425. } catch (e) {
  426. console.log('HTTPS failed to start:', e.message);
  427. }
  428. module.exports = { server };