@7365admin1/core 3.115.0 → 3.116.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@7365admin1/core",
3
3
  "license": "MIT",
4
- "version": "3.115.0",
4
+ "version": "3.116.0",
5
5
  "author": "7365admin1",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.mjs",
@@ -13,7 +13,7 @@
13
13
  "build": "tsup src/index.ts --format cjs,esm --dts && shx cp -r src/public dist && shx cp -r src/utils/handlebars dist",
14
14
  "release": "yarn run build && changeset publish",
15
15
  "lint": "tsc",
16
- "test": "tsup src/config.ts src/utils/building-map.util.ts src/utils/robot-cloud.util.ts src/utils/robot-adapter.util.ts src/utils/png-encoder.util.ts src/services/demo.adapter.ts src/services/ounitech.adapter.ts src/services/padbot.adapter.ts src/utils/padbot-sign.util.ts src/services/open-rmf.adapter.ts src/utils/robot-credentials.util.ts src/utils/rmf-building.util.ts src/utils/door-contract.util.ts src/utils/robot-fault.util.ts src/utils/robot-tracking.util.ts src/utils/robot-apps.util.ts src/utils/robot-permission.util.ts src/utils/robot-network.util.ts src/utils/lift-contract.util.ts src/models/robot-building-map.model.ts src/utils/anpr-revoke.util.ts src/utils/anpr-plate.util.ts src/utils/vehicle-request.util.ts src/utils/camera-view.util.ts src/utils/camera-bulk-import.util.ts src/utils/dashboard-metrics.util.ts src/utils/camera-capability.util.ts src/utils/camera-playback.util.ts src/services/camera-device-http.service.ts src/utils/camera-alert.util.ts src/utils/dahua-protocol.util.ts src/utils/site-name.util.ts src/utils/site-owner-edit.util.ts src/utils/service-provider-invite.util.ts src/utils/notification-category.util.ts src/utils/notification-kind.util.ts src/utils/notification-email.util.ts src/models/notification.model.ts src/utils/hid-card.util.ts src/utils/hid-json.util.ts src/utils/hid-access.util.ts src/models/customer-site.model.ts src/models/site-camera.model.ts src/models/member.model.ts src/models/subscription.model.ts src/utils/session-id.util.ts src/utils/occurrence-query.util.ts src/utils/occurrence-book-create.util.ts src/utils/update-result.util.ts src/utils/hid-amico-authz.util.ts src/utils/promo-code-currency.util.ts src/utils/console-audit.util.ts src/utils/org-suspension.util.ts src/utils/session-revoke.util.ts src/models/hid-amico.model.ts src/models/patrol-email.model.ts src/utils/patrol-email-pdf.util.ts src/utils/visitor-status.util.ts src/utils/self-service-email.util.ts src/utils/hid-secret.util.ts src/models/visitor-invite.model.ts src/models/guard-invite.model.ts src/utils/site-timezone.util.ts src/utils/bulletin-service-apps.util.ts src/models/bulletin-board.model.ts src/utils/vehicle-import.util.ts src/utils/expired-vehicle-sweep.util.ts src/models/vehicle.model.ts src/controllers/chat.controller.ts src/utils/file-owner.util.ts src/utils/console-permission.util.ts src/utils/role-scope.util.ts src/utils/org-default-roles.util.ts src/utils/org-modules.util.ts src/utils/site-modules.util.ts src/utils/resident-app-modules.util.ts src/utils/resident-default-role.util.ts src/utils/invite-role-scope.util.ts src/models/personal-emergency-chain.model.ts src/utils/self-signup-files.util.ts src/models/person.model.ts src/utils/module-gate.util.ts src/utils/member-lookup.util.ts src/utils/notification-access.util.ts src/utils/module-access.util.ts src/services/module-gate.service.ts src/controllers/site.controller.ts src/controllers/organization.controller.ts src/controllers/member.controller.ts src/utils/org-owner-repair.util.ts src/utils/socket-session.util.ts src/utils/people-create-gate.util.ts src/utils/service-app-type.util.ts src/utils/customer-site-list.util.ts src/utils/org-search.util.ts src/utils/invite-origin.util.ts src/utils/member-role-assign.util.ts src/utils/cross-site-role.util.ts --format esm --out-dir test/.build --no-dts --silent && node --test test/*.test.mjs",
16
+ "test": "tsup src/config.ts src/utils/building-map.util.ts src/utils/robot-cloud.util.ts src/utils/robot-adapter.util.ts src/utils/png-encoder.util.ts src/services/demo.adapter.ts src/services/ounitech.adapter.ts src/services/robot-cloud.service.ts src/services/robot-fleet.service.ts src/services/padbot.adapter.ts src/utils/padbot-sign.util.ts src/services/open-rmf.adapter.ts src/utils/robot-credentials.util.ts src/utils/rmf-building.util.ts src/utils/door-contract.util.ts src/utils/robot-fault.util.ts src/utils/robot-tracking.util.ts src/utils/robot-apps.util.ts src/utils/robot-permission.util.ts src/utils/robot-network.util.ts src/utils/lift-contract.util.ts src/models/robot-building-map.model.ts src/utils/anpr-revoke.util.ts src/utils/anpr-plate.util.ts src/utils/vehicle-request.util.ts src/utils/camera-view.util.ts src/utils/camera-bulk-import.util.ts src/utils/dashboard-metrics.util.ts src/utils/camera-capability.util.ts src/utils/camera-playback.util.ts src/services/camera-device-http.service.ts src/utils/camera-alert.util.ts src/utils/dahua-protocol.util.ts src/utils/site-name.util.ts src/utils/site-owner-edit.util.ts src/utils/service-provider-invite.util.ts src/utils/notification-category.util.ts src/utils/notification-kind.util.ts src/utils/notification-email.util.ts src/models/notification.model.ts src/utils/hid-card.util.ts src/utils/hid-json.util.ts src/utils/hid-access.util.ts src/models/customer-site.model.ts src/models/site-camera.model.ts src/models/member.model.ts src/models/subscription.model.ts src/utils/session-id.util.ts src/utils/occurrence-query.util.ts src/utils/occurrence-book-create.util.ts src/utils/update-result.util.ts src/utils/hid-amico-authz.util.ts src/utils/promo-code-currency.util.ts src/utils/console-audit.util.ts src/utils/org-suspension.util.ts src/utils/session-revoke.util.ts src/models/hid-amico.model.ts src/models/patrol-email.model.ts src/utils/patrol-email-pdf.util.ts src/utils/visitor-status.util.ts src/utils/self-service-email.util.ts src/utils/hid-secret.util.ts src/models/visitor-invite.model.ts src/models/guard-invite.model.ts src/utils/site-timezone.util.ts src/utils/bulletin-service-apps.util.ts src/models/bulletin-board.model.ts src/utils/vehicle-import.util.ts src/utils/expired-vehicle-sweep.util.ts src/models/vehicle.model.ts src/controllers/chat.controller.ts src/utils/file-owner.util.ts src/utils/console-permission.util.ts src/utils/role-scope.util.ts src/utils/org-default-roles.util.ts src/utils/org-modules.util.ts src/utils/site-modules.util.ts src/utils/resident-app-modules.util.ts src/utils/resident-default-role.util.ts src/utils/invite-role-scope.util.ts src/models/personal-emergency-chain.model.ts src/utils/self-signup-files.util.ts src/models/person.model.ts src/utils/module-gate.util.ts src/utils/member-lookup.util.ts src/utils/notification-access.util.ts src/utils/module-access.util.ts src/services/module-gate.service.ts src/controllers/site.controller.ts src/controllers/organization.controller.ts src/controllers/member.controller.ts src/utils/org-owner-repair.util.ts src/utils/socket-session.util.ts src/utils/people-create-gate.util.ts src/utils/service-app-type.util.ts src/utils/customer-site-list.util.ts src/utils/org-search.util.ts src/utils/invite-origin.util.ts src/utils/member-role-assign.util.ts src/utils/cross-site-role.util.ts --format esm --out-dir test/.build --no-dts --silent && node --test test/*.test.mjs",
17
17
  "test:camera": "yarn test",
18
18
  "test:e2e": "yarn build && node --test --test-concurrency=1 --test-timeout=600000 \"test/e2e/*.test.mjs\""
19
19
  },
@@ -952,6 +952,8 @@ function buildApp(nsu, core) {
952
952
  // Reaches a vendor cloud: only exercised against a local mock (OUNITECH_API_BASE).
953
953
  robots.post("/discover", requireAuth, f.discoverRobots);
954
954
  robots.get("/:id([0-9a-fA-F]{24})/state", requireAuth, f.getState);
955
+ robots.get("/:id([0-9a-fA-F]{24})/maps", requireAuth, f.getMaps);
956
+ robots.get("/:id([0-9a-fA-F]{24})/diagnose", requireAuth, f.diagnoseRobot);
955
957
  robots.post("/:id([0-9a-fA-F]{24})/command", requireAuth, f.sendCommand);
956
958
  robots.get("/:id([0-9a-fA-F]{24})/patrol-routes", requireAuth, f.getPatrolRoutes);
957
959
  robots.post("/:id([0-9a-fA-F]{24})/live-video", requireAuth, f.getLiveVideo);
@@ -0,0 +1,172 @@
1
+ // HERO-OTH (production, 2026-09-26): /api/robots/:id/state and /maps answered
2
+ // 500 {"status":"error","message":"Internal Server Error"}. Every Ounitech
3
+ // failure was a plain Error, which the shared error handler turns into a bare
4
+ // 500. This proves, through the real routes, that each vendor failure is now a
5
+ // handled answer with a plain reason, and that GET /:id/diagnose (Seven365
6
+ // staff only, read-only) names the failing step and what the vendor said -
7
+ // without ever returning a credential.
8
+ //
9
+ // The "Ounitech cloud" is a loopback mock with fake credentials. Nothing leaves
10
+ // the machine. Run with: yarn test:e2e
11
+
12
+ import { after, before, describe, it } from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import crypto from "node:crypto";
15
+ import http from "node:http";
16
+ import { once } from "node:events";
17
+ import { ObjectId } from "mongodb";
18
+
19
+ import { startHarness } from "./harness.mjs";
20
+
21
+ const PASSWORD = "Robot-Passw0rd!";
22
+ const MANAGER = "ove-manager@e2e.example.com";
23
+ const STAFF = "ove-staff@e2e.example.com";
24
+ const APPID = "fake-oth-appid";
25
+ const SECRET = "fake-oth-secret";
26
+
27
+ /** The mock answers however `mode` says. */
28
+ let mode = "badsign";
29
+ async function startMock() {
30
+ const server = http.createServer((req, res) => {
31
+ req.resume();
32
+ req.on("end", () => {
33
+ const send = (status, body, type = "application/json") => {
34
+ res.writeHead(status, { "content-type": type });
35
+ res.end(typeof body === "string" ? body : JSON.stringify(body));
36
+ };
37
+ const list = req.url === "/portal/robots/get-robot-list";
38
+ if (mode === "badsign") return send(200, { ok: false, msg: "sign error" });
39
+ if (mode === "html") return send(502, "<html>Bad gateway</html>", "text/html");
40
+ if (mode === "slow") return setTimeout(() => send(200, { robotList: [] }), 3000);
41
+ if (mode === "notbound") return send(200, list ? { robotList: [{ robotSn: "OTHER-SN", onlineFlag: true }] } : { ok: false, msg: "robot not bound" });
42
+ return send(200, list ? { robotList: [{ robotSn: "OTH-SN", robotName: "HERO", statusFlag: 1, onlineFlag: true }] } : { ok: true, mapList: [] });
43
+ });
44
+ });
45
+ server.listen(0, "127.0.0.1");
46
+ await once(server, "listening");
47
+ return { server, url: `http://127.0.0.1:${server.address().port}` };
48
+ }
49
+
50
+ describe("robot vendor failures are handled answers; diagnose names the step", { concurrency: 1 }, () => {
51
+ let h;
52
+ let mock;
53
+ let managerSid;
54
+ let staffSid;
55
+ const id = {};
56
+
57
+ before(async () => {
58
+ mock = await startMock();
59
+ process.env.OUNITECH_API_BASE = mock.url;
60
+ process.env.ROBOT_CLOUD_TIMEOUT_MS = "1500";
61
+ process.env.ROBOT_CREDENTIALS_KEY = crypto.randomBytes(32).toString("hex");
62
+ h = await startHarness();
63
+ Object.assign(id, await seed(h));
64
+ managerSid = await h.login(MANAGER, PASSWORD);
65
+ staffSid = await h.login(STAFF, PASSWORD);
66
+ const add = await h.api("/robots", {
67
+ method: "POST",
68
+ sid: managerSid,
69
+ body: { name: "HERO-OTH", brand: "ounitech", type: "cleaning", robotSn: "OTH-SN", appKey: APPID, appToken: SECRET, metadata: { orgId: String(id.org), siteId: String(id.site) } },
70
+ });
71
+ assert.equal(add.status, 201, JSON.stringify(add.body));
72
+ id.robot = (await h.db.collection("robots").findOne({ name: "HERO-OTH" }))._id;
73
+ }, { timeout: 300000 });
74
+
75
+ after(async () => {
76
+ delete process.env.OUNITECH_API_BASE;
77
+ delete process.env.ROBOT_CLOUD_TIMEOUT_MS;
78
+ delete process.env.ROBOT_CREDENTIALS_KEY;
79
+ if (h) await h.stop();
80
+ mock?.server.close();
81
+ });
82
+
83
+ const CASES = [
84
+ ["badsign", 502, /Ounitech rejected the robot list \(sign-in\) \(sign error\)/, /Ounitech rejected the floor maps \(sign error\)/],
85
+ ["html", 502, /Ounitech answered HTTP 502 for the robot list \(sign-in\) with a web page/, /HTTP 502 for the floor maps/],
86
+ ["slow", 504, /didn't answer the robot list \(sign-in\) in time/, /didn't answer the floor maps in time/],
87
+ ];
88
+
89
+ for (const [m, status, stateText, mapsText] of CASES) {
90
+ it(`vendor "${m}": /state and /maps answer ${status} with the reason, never a bare 500`, async () => {
91
+ mode = m;
92
+ const state = await h.api(`/robots/${id.robot}/state`, { sid: managerSid });
93
+ assert.equal(state.status, status, JSON.stringify(state.body));
94
+ assert.match(state.body.message, stateText);
95
+ const maps = await h.api(`/robots/${id.robot}/maps`, { sid: managerSid });
96
+ assert.equal(maps.status, status, JSON.stringify(maps.body));
97
+ assert.match(maps.body.message, mapsText);
98
+ });
99
+ }
100
+
101
+ it("the 4 s live poll (/robots/states) carries the plain reason for the detail screen", async () => {
102
+ mode = "badsign";
103
+ await new Promise((r) => setTimeout(r, 3200)); // past the 3 s memo of the last read
104
+ const res = await h.api(`/robots/states?ids=${id.robot}`, { sid: managerSid });
105
+ assert.equal(res.status, 200, JSON.stringify(res.body));
106
+ const item = res.body.items.find((i) => i.id === String(id.robot));
107
+ assert.equal(item.ok, false);
108
+ assert.match(item.reason, /Ounitech rejected the robot list \(sign-in\) \(sign error\)/);
109
+ assert.equal(JSON.stringify(res.body).includes(SECRET), false);
110
+ });
111
+
112
+ it("a serial the account does not list: state is a 200 saying so", async () => {
113
+ mode = "notbound";
114
+ const state = await h.api(`/robots/${id.robot}/state`, { sid: managerSid });
115
+ assert.equal(state.status, 200, JSON.stringify(state.body));
116
+ assert.match(state.body.statusName, /Serial OTH-SN is not on this Ounitech account - use Find robots/);
117
+ });
118
+
119
+ it("diagnose is Seven365 staff only", async () => {
120
+ const res = await h.api(`/robots/${id.robot}/diagnose`, { sid: managerSid });
121
+ assert.equal(res.status, 401, JSON.stringify(res.body));
122
+ });
123
+
124
+ it("diagnose names the failing step and the vendor's words, with no credential", async () => {
125
+ mode = "badsign";
126
+ const bad = await h.api(`/robots/${id.robot}/diagnose`, { sid: staffSid });
127
+ assert.equal(bad.status, 200, JSON.stringify(bad.body));
128
+ assert.equal(bad.body.failedStep, "sign-in (robot list)");
129
+ assert.deepEqual(bad.body.credentials, { appIdSaved: true, secretSaved: true, encrypted: true, serverKeyPresent: true, readable: true });
130
+ assert.equal(bad.body.robot.robotSnSaved, true);
131
+ const step = bad.body.steps.find((s) => !s.ok);
132
+ assert.equal(step.vendorMessage, "sign error");
133
+ const row = await h.db.collection("robots").findOne({ _id: id.robot });
134
+ const text = JSON.stringify(bad.body);
135
+ for (const s of [APPID, SECRET, row.appKey, row.appToken]) assert.equal(text.includes(s), false, s);
136
+
137
+ mode = "notbound";
138
+ const nb = await h.api(`/robots/${id.robot}/diagnose`, { sid: staffSid });
139
+ assert.equal(nb.body.failedStep, "get robot");
140
+ assert.match(nb.body.summary, /Serial OTH-SN is not on this account/);
141
+
142
+ mode = "ok";
143
+ const ok = await h.api(`/robots/${id.robot}/diagnose`, { sid: staffSid });
144
+ assert.equal(ok.body.failedStep, null, JSON.stringify(ok.body));
145
+ assert.equal(ok.body.steps.length, 4);
146
+ assert.ok(ok.body.clock?.vendorDate, "the vendor's clock is reported");
147
+ });
148
+ });
149
+
150
+ async function seed(h) {
151
+ const now = new Date().toISOString();
152
+ const org = new ObjectId();
153
+ const site = new ObjectId();
154
+ const role = new ObjectId();
155
+ const staffRole = new ObjectId();
156
+ await h.db.collection("organizations").insertOne({ _id: org, name: "OVE Org", email: "ove@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now });
157
+ await h.db.collection("sites").insertOne({ _id: site, name: "OVE Site", org, orgId: org, status: "active" });
158
+ await h.db.collection("roles").insertMany([
159
+ { _id: role, name: "Manager", org, permissions: ["*"], status: "active" },
160
+ { _id: staffRole, name: "Super Admin", type: "admin", default: true, permissions: [], status: "active" },
161
+ ]);
162
+ const emails = [MANAGER, STAFF];
163
+ const users = await h.db.collection("users").insertMany(emails.map((email) => ({ email, name: email.split("@")[0], status: "active", createdAt: now })));
164
+ const hashed = await h.hashPassword(PASSWORD);
165
+ await h.db.collection("users").updateMany({ email: { $in: emails } }, { $set: { password: hashed } });
166
+ const [manager, staff] = [0, 1].map((i) => users.insertedIds[i]);
167
+ await h.db.collection("members").insertMany([
168
+ { user: manager, org, type: "organization", role, status: "active" },
169
+ { user: staff, type: "admin", role: staffRole, status: "active" },
170
+ ]);
171
+ return { org, site };
172
+ }
@@ -0,0 +1,289 @@
1
+ import assert from "node:assert/strict";
2
+ import http from "node:http";
3
+ import { once } from "node:events";
4
+ import { after, before, test } from "node:test";
5
+
6
+ import { errorHandler } from "@7365admin1/node-server-utils";
7
+
8
+ import { RobotCloudError, useRobotCloudService } from "./.build/services/robot-cloud.service.mjs";
9
+ import { useRobotFleetService } from "./.build/services/robot-fleet.service.mjs";
10
+ import { adapterForRobot, registerRobotBrand } from "./.build/utils/robot-adapter.util.mjs";
11
+
12
+ /* --------------------------------------------------------------------------
13
+ * HERO-OTH (production, 2026-09-26): GET /api/robots/:id/state and /maps both
14
+ * answered 500 {"message":"Internal Server Error"}. Cause: every Ounitech
15
+ * failure was a plain `Error` (RobotCloudError extended Error, adapterForRobot
16
+ * threw Error), and the shared error handler turns anything that is not an
17
+ * operational AppError into a bare 500.
18
+ *
19
+ * These reproduce each plausible real answer from the vendor against a loopback
20
+ * mock and prove each one becomes a HANDLED error with a plain reason, and that
21
+ * the diagnostic names the failing step. Nothing leaves the machine; the
22
+ * credentials are fake.
23
+ * ----------------------------------------------------------------------- */
24
+
25
+ const CREDS = { appid: "fake-appid", secret: "fake-secret-value" };
26
+ const VENDOR_DATE = "Sat, 26 Sep 2026 00:00:00 GMT";
27
+
28
+ /** One mock; the first path segment picks how it misbehaves. */
29
+ let server;
30
+ let base;
31
+ let closedBase;
32
+ const seen = [];
33
+
34
+ function reply(res, status, body, type = "application/json") {
35
+ res.writeHead(status, { "content-type": type, date: VENDOR_DATE });
36
+ res.end(typeof body === "string" ? body : JSON.stringify(body));
37
+ }
38
+
39
+ before(async () => {
40
+ server = http.createServer((req, res) => {
41
+ let raw = "";
42
+ req.on("data", (c) => (raw += c));
43
+ req.on("end", () => {
44
+ seen.push(raw);
45
+ const [, mode, ...rest] = req.url.split("/");
46
+ const path = "/" + rest.join("/");
47
+ const list = path === "/portal/robots/get-robot-list";
48
+ switch (mode) {
49
+ case "ok":
50
+ if (list) return reply(res, 200, { robotList: [{ robotSn: "SN-1", robotName: "Lobby", statusFlag: 1, onlineFlag: true }] });
51
+ if (path === "/portal/maps/get-map-list") return reply(res, 200, { ok: true, mapList: [{ floorNo: 1, mapName: "L1" }] });
52
+ return reply(res, 200, { ok: true });
53
+ case "badsign":
54
+ return reply(res, 200, { ok: false, msg: "sign error" });
55
+ case "timestamp":
56
+ return reply(res, 200, { ok: false, msg: "timestamp out of range" });
57
+ case "codeenv":
58
+ return reply(res, 200, { code: 40001, msg: "invalid appid" });
59
+ case "empty":
60
+ return reply(res, 200, list ? { robotList: [] } : { ok: true, mapList: [] });
61
+ case "other":
62
+ return reply(res, 200, list ? { robotList: [{ robotSn: "SN-OTHER", onlineFlag: true }] } : { ok: true, mapList: [] });
63
+ case "html200":
64
+ return reply(res, 200, "<html><body>Maintenance</body></html>", "text/html");
65
+ case "html502":
66
+ return reply(res, 502, "<html><body>Bad gateway</body></html>", "text/html");
67
+ case "http401":
68
+ return reply(res, 401, { code: 401, msg: "unauthorized" });
69
+ case "shape":
70
+ return reply(res, 200, { robotList: { robotSn: "SN-1" } });
71
+ case "mapsfail":
72
+ if (list) return reply(res, 200, { robotList: [{ robotSn: "SN-1", onlineFlag: true }] });
73
+ return reply(res, 200, { ok: false, msg: "robot not bound" });
74
+ case "slow":
75
+ return setTimeout(() => reply(res, 200, { robotList: [] }), 2000);
76
+ default:
77
+ return reply(res, 404, "not found", "text/plain");
78
+ }
79
+ });
80
+ });
81
+ server.listen(0, "127.0.0.1");
82
+ await once(server, "listening");
83
+ base = `http://127.0.0.1:${server.address().port}`;
84
+
85
+ // A port nobody listens on: connection refused.
86
+ const tmp = http.createServer();
87
+ tmp.listen(0, "127.0.0.1");
88
+ await once(tmp, "listening");
89
+ closedBase = `http://127.0.0.1:${tmp.address().port}`;
90
+ await new Promise((r) => tmp.close(r));
91
+ });
92
+
93
+ after(() => {
94
+ server.closeAllConnections?.();
95
+ server.close();
96
+ });
97
+
98
+ const cloud = (mode, opts = {}) =>
99
+ useRobotCloudService(CREDS, { baseUrl: `${base}/${mode}`, timeoutMs: 1000, ...opts });
100
+
101
+ /** What the API would answer for this error - the real shared handler. */
102
+ function apiAnswer(err) {
103
+ const out = {};
104
+ const res = {
105
+ status(code) { out.status = code; return this; },
106
+ json(body) { out.body = body; return this; },
107
+ };
108
+ errorHandler(err, {}, res, () => {});
109
+ return out;
110
+ }
111
+
112
+ async function failureOf(promise) {
113
+ try {
114
+ await promise;
115
+ } catch (e) {
116
+ return e;
117
+ }
118
+ assert.fail("expected a failure");
119
+ }
120
+
121
+ /* ------------------------------------------------------ every failure mode */
122
+
123
+ const MODES = [
124
+ ["badsign", { kind: "refused", status: 502, text: /Ounitech rejected the robot list \(sign-in\) \(sign error\)\. Check the AppID\/Secret and the server clock/ }],
125
+ ["timestamp", { kind: "refused", status: 502, text: /timestamp out of range/ }],
126
+ ["codeenv", { kind: "refused", status: 502, text: /code 40001: invalid appid/ }],
127
+ ["html200", { kind: "not-json", status: 502, text: /Ounitech sent a web page for the robot list/ }],
128
+ ["html502", { kind: "http", status: 502, text: /Ounitech answered HTTP 502 for the robot list \(sign-in\) with a web page/ }],
129
+ ["http401", { kind: "http", status: 502, text: /HTTP 401 .*code 401: unauthorized/ }],
130
+ ["shape", { kind: "shape", status: 502, text: /not in the expected shape/ }],
131
+ ["slow", { kind: "timeout", status: 504, text: /Ounitech didn't answer the robot list \(sign-in\) in time/ }],
132
+ ];
133
+
134
+ for (const [mode, want] of MODES) {
135
+ test(`vendor "${mode}": a handled ${want.status} with a plain reason, never a bare 500`, async () => {
136
+ const e = await failureOf(cloud(mode).getRobots());
137
+ assert.ok(e instanceof RobotCloudError);
138
+ assert.equal(e.kind, want.kind);
139
+ assert.match(e.message, want.text);
140
+ const answer = apiAnswer(e);
141
+ assert.equal(answer.status, want.status);
142
+ assert.notEqual(answer.body.message, "Internal Server Error");
143
+ assert.match(answer.body.message, want.text);
144
+ // Nothing secret in what the caller or the log sees.
145
+ assert.ok(!e.message.includes(CREDS.secret) && !e.message.includes(CREDS.appid));
146
+ });
147
+ }
148
+
149
+ test("vendor unreachable (connection refused): a handled 502 naming the host", async () => {
150
+ const e = await failureOf(useRobotCloudService(CREDS, { baseUrl: closedBase, timeoutMs: 1000 }).getRobots());
151
+ assert.equal(e.kind, "unreachable");
152
+ assert.match(e.message, /Couldn't reach Ounitech's server \(127\.0\.0\.1:\d+, ECONNREFUSED\)/);
153
+ assert.equal(apiAnswer(e).status, 502);
154
+ });
155
+
156
+ test("the vendor's code, message, HTTP status and clock are carried for the diagnostic", async () => {
157
+ const e = await failureOf(cloud("http401").getRobots());
158
+ assert.equal(e.vendorCode, "401");
159
+ assert.equal(e.vendorMessage, "unauthorized");
160
+ assert.equal(e.httpStatus, 401);
161
+ assert.equal(e.serverDate, VENDOR_DATE);
162
+ });
163
+
164
+ test("a good answer still works, and the secret never rides in the request", async () => {
165
+ const robots = await cloud("ok").getRobots();
166
+ assert.equal(robots[0].robotSn, "SN-1");
167
+ assert.ok(seen.every((raw) => !raw.includes(CREDS.secret)));
168
+ });
169
+
170
+ test("an input refusal (area clean with no areas) is a 400, not a vendor 502", async () => {
171
+ const e = await failureOf(cloud("ok").startAreaCleaning("SN-1", [], { cleanTimes: 1, modeFlag: 1, subModeFlag: 0, levelFlag: 1 }));
172
+ assert.equal(apiAnswer(e).status, 400);
173
+ });
174
+
175
+ test("a robot with no saved credentials is a handled 400, not a 500", () => {
176
+ registerRobotBrand({ brand: "nocreds-test", displayName: "Test", capabilities: {}, create: () => ({}) });
177
+ let e;
178
+ try {
179
+ adapterForRobot({ brand: "nocreds-test", name: "HERO" });
180
+ } catch (err) {
181
+ e = err;
182
+ }
183
+ const answer = apiAnswer(e);
184
+ assert.equal(answer.status, 400);
185
+ assert.match(answer.body.message, /has no cloud credentials saved/);
186
+ });
187
+
188
+ /* ---------------------------------------------------- state, maps, diagnose */
189
+
190
+ const robotRow = (extra = {}) => ({
191
+ _id: "6ab73272cb53a5ecaa3e12bc",
192
+ name: "HERO-OTH",
193
+ brand: "ounitech",
194
+ robotSn: "SN-1",
195
+ appKey: CREDS.appid,
196
+ appToken: CREDS.secret,
197
+ metadata: {},
198
+ ...extra,
199
+ });
200
+
201
+ const fleetFor = (mode, timeoutMs = 1000) =>
202
+ useRobotFleetService({ cloudOptions: { baseUrl: `${base}/${mode}`, timeoutMs } });
203
+
204
+ test("state: a serial not on the account reads as a plain status, not an error", async () => {
205
+ const { OUNITECH_BRAND } = { OUNITECH_BRAND: "ounitech" };
206
+ const fleet = useRobotFleetService({
207
+ adapterFor: () => ({ brand: OUNITECH_BRAND, displayName: "Ounitech", capabilities: {}, listRobots: async () => [], getRobot: async () => null }),
208
+ });
209
+ const state = await fleet.getFleetRobot(robotRow());
210
+ assert.equal(state.online, false);
211
+ assert.match(state.statusName, /Serial SN-1 is not on this Ounitech account - use Find robots/);
212
+ });
213
+
214
+ test("diagnose: every step passes on a healthy account, with the vendor's clock", async () => {
215
+ const d = await fleetFor("ok").diagnose(robotRow());
216
+ assert.equal(d.failedStep, null);
217
+ assert.deepEqual(d.steps.map((s) => [s.step, s.ok]), [
218
+ ["credentials", true],
219
+ ["sign-in (robot list)", true],
220
+ ["get robot", true],
221
+ ["maps", true],
222
+ ]);
223
+ assert.equal(d.clock.vendorDate, VENDOR_DATE);
224
+ assert.equal(typeof d.clock.offsetSeconds, "number");
225
+ assert.equal(d.credentials.appIdSaved, true);
226
+ assert.equal(d.cloudHost, "127.0.0.1:" + base.split(":").pop());
227
+ });
228
+
229
+ test("diagnose: never returns a credential value", async () => {
230
+ for (const mode of ["ok", "badsign", "http401"]) {
231
+ const text = JSON.stringify(await fleetFor(mode).diagnose(robotRow()));
232
+ assert.ok(!text.includes(CREDS.secret), mode);
233
+ assert.ok(!text.includes(CREDS.appid), mode);
234
+ }
235
+ });
236
+
237
+ const DIAG = [
238
+ ["badsign", "sign-in (robot list)", /sign error/, { vendorMessage: "sign error", kind: "refused" }],
239
+ ["codeenv", "sign-in (robot list)", /invalid appid/, { vendorCode: "40001" }],
240
+ ["html200", "sign-in (robot list)", /web page/, { kind: "not-json" }],
241
+ ["http401", "sign-in (robot list)", /HTTP 401/, { httpStatus: 401 }],
242
+ ["slow", "sign-in (robot list)", /in time/, { kind: "timeout" }],
243
+ ["empty", "get robot", /Serial SN-1 is not on this account \(it lists 0\)/, {}],
244
+ ["other", "get robot", /use Find robots/, {}],
245
+ ["mapsfail", "maps", /Ounitech rejected the floor maps \(robot not bound\)/, { vendorMessage: "robot not bound" }],
246
+ ];
247
+
248
+ for (const [mode, step, text, fields] of DIAG) {
249
+ test(`diagnose "${mode}": names the failing step (${step}) and what Ounitech said`, async () => {
250
+ const d = await fleetFor(mode).diagnose(robotRow());
251
+ assert.equal(d.failedStep, step);
252
+ const failed = d.steps.find((s) => !s.ok);
253
+ assert.equal(failed.step, step);
254
+ assert.match(failed.detail, text);
255
+ assert.match(d.summary, text);
256
+ for (const [k, v] of Object.entries(fields)) assert.equal(failed[k], v, k);
257
+ });
258
+ }
259
+
260
+ test("diagnose: unreachable vendor names the host", async () => {
261
+ const d = await useRobotFleetService({ cloudOptions: { baseUrl: closedBase, timeoutMs: 1000 } }).diagnose(robotRow());
262
+ assert.equal(d.failedStep, "sign-in (robot list)");
263
+ assert.match(d.summary, /Couldn't reach Ounitech's server/);
264
+ });
265
+
266
+ test("diagnose: missing credentials and missing serial are named, with no vendor call", async () => {
267
+ const before = seen.length;
268
+ const d = await fleetFor("ok").diagnose(robotRow({ appKey: "", appToken: "" }));
269
+ assert.equal(d.failedStep, "credentials");
270
+ assert.match(d.summary, /No AppID and Secret saved/);
271
+ assert.equal(seen.length, before);
272
+
273
+ const noSn = await fleetFor("other").diagnose(robotRow({ robotSn: "" }));
274
+ assert.equal(noSn.failedStep, null);
275
+ assert.match(noSn.steps[2].detail, /No serial saved; the account has one robot \(SN-OTHER\)/);
276
+ });
277
+
278
+ test("diagnose: an encrypted credential with no key on this server is named", async () => {
279
+ const d = await fleetFor("ok").diagnose(robotRow({ appKey: "rc1:a:b:c", appToken: "rc1:a:b:c" }));
280
+ if (d.credentials.serverKeyPresent) return; // a key in this shell's env: nothing to prove
281
+ assert.equal(d.failedStep, "credentials");
282
+ assert.match(d.summary, /encrypted but the server has no key/);
283
+ assert.equal(d.credentials.encrypted, true);
284
+ });
285
+
286
+ test("diagnose: an unknown brand is named, not thrown", async () => {
287
+ const d = await fleetFor("ok").diagnose(robotRow({ brand: "nobody" }));
288
+ assert.equal(d.failedStep, "brand");
289
+ });