/** * @file remote-client.js (routes) * @description `/api/remote-client` — a LOCAL AgentHub's link to the company * hub (server/lib/remote-client.js): whether this machine is enrolled, which * Company-account sessions it sent and when, and enroll / log out / send now. * Every write is same-origin; the password in `login` goes on to the hub once * and is never stored; no answer ever carries the device token. A hub (server * mode) has none of this: it answers 404 ENOTLOCAL there. * @author Nguyễn Ngọc Trí Vĩ */ const express = require("express"); const { sameOriginGuard } = require("../lib/same-origin"); const remote = require("../lib/remote-client"); const router = express.Router(); router.use((req, res, next) => require("../lib/auth").isServerMode() ? res .status(404) .json({ error: { code: "ENOTLOCAL", message: "a hub does not enroll with another hub" } }) : next() ); const statusOf = (e) => e.code === "EHUBDOWN" ? 503 : e.code === "ETOOMANY" ? 429 : e.status && e.status >= 400 && e.status < 600 ? e.status : 400; const send = (res, e) => res.status(statusOf(e)).json({ error: { code: e.code || "EINTERNAL", message: e.message } }); router.get("/", (_req, res) => { res.json({ ...remote.status(), uploads: remote.uploads() }); }); router.post("/login", sameOriginGuard, async (req, res) => { try { const { hub, username, password, deviceName } = req.body || {}; res.json(await remote.login({ hub, username, password, deviceName })); } catch (e) { send(res, e); } }); router.post("/logout", sameOriginGuard, async (_req, res) => { try { res.json(await remote.logout()); } catch (e) { send(res, e); } }); router.post("/upload", sameOriginGuard, async (_req, res) => { try { if (!remote.status().enrolled) { return res .status(400) .json({ error: { code: "ENOHUB", message: "this machine is not enrolled with a hub" } }); } res.json(await remote.uploadAll()); } catch (e) { send(res, e); } }); module.exports = router;