@7365admin1/core 3.114.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.
@@ -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
+ });