@7365admin1/core 3.113.0 → 3.115.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.113.0",
4
+ "version": "3.115.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/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/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
  },
@@ -949,9 +949,15 @@ function buildApp(nsu, core) {
949
949
  // adapter reaches no network, so no vendor cloud is ever contacted.
950
950
  const f = core.useRobotFleetController();
951
951
  robots.get("/brands", requireAuth, f.getBrands);
952
+ // Reaches a vendor cloud: only exercised against a local mock (OUNITECH_API_BASE).
953
+ robots.post("/discover", requireAuth, f.discoverRobots);
952
954
  robots.get("/:id([0-9a-fA-F]{24})/state", requireAuth, f.getState);
953
955
  robots.post("/:id([0-9a-fA-F]{24})/command", requireAuth, f.sendCommand);
954
956
  robots.get("/:id([0-9a-fA-F]{24})/patrol-routes", requireAuth, f.getPatrolRoutes);
957
+ robots.post("/:id([0-9a-fA-F]{24})/live-video", requireAuth, f.getLiveVideo);
958
+ robots.post("/:id([0-9a-fA-F]{24})/alerts/resolve", requireAuth, f.resolveAlerts);
959
+ robots.get("/:id([0-9a-fA-F]{24})/patrol-history", requireAuth, f.getPatrolHistory);
960
+ robots.get("/:id([0-9a-fA-F]{24})/patrol-history/:recordId", requireAuth, f.getPatrolVisits);
955
961
  }
956
962
 
957
963
  // mirrors iservice365-API-core/src/routes/attendance-settings.route.ts
@@ -0,0 +1,359 @@
1
+ // End-to-end proof for the PadBot security-robot brand, against a local mock
2
+ // PadBot cloud that VERIFIES every request exactly as §2 of the vendor doc
3
+ // requires: the Authorization header, HMAC-SHA256 over the JCS body digest,
4
+ // the 300 s timestamp window, and anti-replay on accessKeyId + X-Request-ID.
5
+ //
6
+ // In-process MongoDB, loopback Redis and mail sink, loopback mock only - the
7
+ // real PadBot API is never called (PADBOT_API_BASE points at the mock).
8
+ //
9
+ // Run with: yarn test:e2e
10
+
11
+ import { after, before, describe, it } from "node:test";
12
+ import assert from "node:assert/strict";
13
+ import { createServer } from "node:http";
14
+ import { request as httpRequest } from "node:http";
15
+ import { ObjectId } from "mongodb";
16
+
17
+ import { startHarness } from "./harness.mjs";
18
+
19
+ const PASSWORD = "Robot-Passw0rd!";
20
+ const OUTSIDER = "pb-outsider@e2e.example.com";
21
+ const MANAGER = "pb-manager@e2e.example.com";
22
+ const AK = "e2e-access-key-id";
23
+ const SK = "e2e-access-key-secret"; // test value for the mock only
24
+
25
+ /** A PadBot cloud that checks signatures and replays like the real one (§2.2.1, §2.3). */
26
+ function startMockPadbot(core) {
27
+ const seen = [];
28
+ const usedIds = new Set();
29
+ const openAlarms = new Map([["a1", { alarmId: "a1", serialNumber: "PS0001", alarmType: "3", occurredAt: "2026-09-26T07:00:00.000Z", toPointName: "Lobby" }]]);
30
+ const now = () => new Date().toISOString();
31
+ const state = { nav: { actionType: 2, actionState: 2 } };
32
+ const data = {
33
+ "/api/v1/robots/list": () => [{ serialNumber: "PS0001", robotName: "Patrol 1", robotType: "PATROL", robotModel: "S2" }],
34
+ "/api/v1/robots/states/list": () => [
35
+ {
36
+ serialNumber: "PS0001",
37
+ states: [
38
+ { stateType: "1000", data: { updatedAt: now() } },
39
+ { stateType: "1001", data: { updatedAt: now(), batteryPercent: 72 } },
40
+ { stateType: "1002", data: { updatedAt: now(), chargingState: 0 } },
41
+ { stateType: "1003", data: { updatedAt: now(), ...state.nav, mapName: "L1" } },
42
+ { stateType: "1006", data: { updatedAt: now(), emergencyStopState: 0, wheelLockState: 0 } },
43
+ { stateType: "1007", data: { updatedAt: now(), mapId: "m1", floor: 1, width: 200, height: 100 } },
44
+ { stateType: "1010", data: { updatedAt: now(), workState: 0 } },
45
+ ],
46
+ },
47
+ ],
48
+ "/api/v1/robots/location/get": () => ({ mapId: "m1", worldX: 5, worldY: 2.5, yaw: 90 }),
49
+ "/api/v1/robots/maps/list": () => [
50
+ {
51
+ mapId: "m1", floor: 1, width: 200, height: 100, resolution: 0.05, originX: 0, originY: 0,
52
+ targetPoints: [
53
+ { targetPointId: "t1", name: "Entrance", worldX: 1, worldY: 1, targetPointType: 0 },
54
+ { targetPointId: "t2", name: "Lift lobby", worldX: 5, worldY: 2.5, targetPointType: 3 },
55
+ { targetPointId: "t3", name: "Dock", worldX: 9, worldY: 4, targetPointType: 10 },
56
+ ],
57
+ },
58
+ ],
59
+ "/api/v1/robots/patrol/paths/list": () => [
60
+ { pathId: "p1", pathName: "Lobby loop", mapId: "m1", isDefault: true, points: [
61
+ { targetPointId: "t1", targetPointName: "Entrance", pointIndex: 0 },
62
+ { targetPointId: "t2", targetPointName: "Lift lobby", pointIndex: 1 },
63
+ { targetPointId: "t3", targetPointName: "Dock", pointIndex: 2 },
64
+ ] },
65
+ ],
66
+ "/api/v1/robots/patrol/alarms/page": (b) => {
67
+ const items = [...openAlarms.values()].filter((a) => !b.alarmTypes?.length || b.alarmTypes.includes(a.alarmType));
68
+ return { items: items.slice(0, b.pageSize ?? 20), totalItems: items.length, totalPages: items.length ? 1 : 0, pageSize: b.pageSize ?? 20, pageNumber: 1 };
69
+ },
70
+ "/api/v1/robots/patrol/alarms/resolve": (b) => {
71
+ for (const id of b.alarmIds) openAlarms.delete(id);
72
+ return null;
73
+ },
74
+ "/api/v1/robots/patrol/video-stream": () => ({ playbackUrl: "https://video.mock/play/PS0001", expiresAt: "2026-09-26T09:00:00.000Z" }),
75
+ "/api/v1/robots/patrol/records/page": () => ({ items: [{ patrolRecordId: "r1", patrolPathName: "Lobby loop", completionState: 2, startedAt: "2026-09-26T03:32:00.000Z", endedAt: "2026-09-26T03:33:41.000Z", duration: 101, mileage: 19.89, alarmCount: 1 }], totalItems: 1, totalPages: 1, pageSize: 20, pageNumber: 1 }),
76
+ "/api/v1/robots/patrol/record-details/page": () => ({ items: [{ patrolRecordDetailId: "d1", targetPointName: "Entrance", capturedAt: "2026-09-26T03:32:30.000Z", skipped: false, visibleLightImageUrl: "https://img.mock/1.png", thermalImageUrl: null, centerTemperature: 24.5, maxTemperature: 25.7 }], totalItems: 1, totalPages: 1, pageSize: 20, pageNumber: 1 }),
77
+ "/api/v1/robots/patrol/start": () => null,
78
+ "/api/v1/robots/patrol/resume": () => null,
79
+ "/api/v1/robots/actions/stop": () => null,
80
+ "/api/v1/robots/actions/charge": () => null,
81
+ };
82
+
83
+ const server = createServer((req, res) => {
84
+ let raw = "";
85
+ req.on("data", (c) => (raw += c));
86
+ req.on("end", () => {
87
+ const reply = (status, body) => {
88
+ res.writeHead(status, { "Content-Type": "application/json" });
89
+ res.end(body === undefined ? "" : JSON.stringify(body));
90
+ };
91
+ const auth = core.parsePadbotAuthorization(req.headers.authorization);
92
+ const requestId = String(req.headers["x-request-id"] ?? "");
93
+ const record = { path: req.url, requestId, body: raw ? JSON.parse(raw) : null, verdict: "ok" };
94
+ seen.push(record);
95
+ const deny = (why) => {
96
+ record.verdict = why;
97
+ reply(401);
98
+ };
99
+ if (req.method !== "POST" || req.headers["content-type"] !== "application/json" || req.headers.accept !== "application/json") return deny("headers");
100
+ if (!req.headers["user-agent"]) return deny("user-agent");
101
+ if (!auth || auth.accessKeyId !== AK) return deny("auth-header");
102
+ if (Math.abs(Date.now() / 1000 - auth.timestamp) > 300) return deny("timestamp");
103
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(requestId)) return deny("request-id");
104
+ // The body must be byte-for-byte the canonical form that was signed.
105
+ if (raw !== core.jcs(JSON.parse(raw || "null"))) return deny("not-canonical");
106
+ const expect = core.padbotSignature({ method: "POST", path: req.url, accessKeyId: AK, timestamp: auth.timestamp, requestId, canonicalBody: raw, accessKeySecret: SK });
107
+ if (expect !== auth.signature) return deny("signature");
108
+ const replayKey = `${AK}:${requestId}`;
109
+ if (usedIds.has(replayKey)) return deny("replay");
110
+ usedIds.add(replayKey);
111
+ const hit = data[req.url];
112
+ if (!hit) return reply(404);
113
+ reply(200, { code: 0, message: "success", requestId, data: hit(record.body) ?? null });
114
+ });
115
+ });
116
+ return new Promise((resolve) =>
117
+ server.listen(0, "127.0.0.1", () => resolve({ server, seen, openAlarms, state, url: `http://127.0.0.1:${server.address().port}` })),
118
+ );
119
+ }
120
+
121
+ /** Send exactly the bytes and headers of an earlier request again (a replay). */
122
+ function replay(url, path, headers, body) {
123
+ return new Promise((resolve, reject) => {
124
+ const u = new URL(url + path);
125
+ const req = httpRequest({ hostname: u.hostname, port: u.port, path: u.pathname, method: "POST", headers }, (res) => {
126
+ res.resume();
127
+ res.on("end", () => resolve(res.statusCode));
128
+ });
129
+ req.on("error", reject);
130
+ req.end(body);
131
+ });
132
+ }
133
+
134
+ describe("PadBot security robots", { concurrency: 1 }, () => {
135
+ let h;
136
+ let mock;
137
+ const id = {};
138
+ let outsiderSid;
139
+ let managerSid;
140
+ const post = (path, body, sid = managerSid) => h.api(path, { method: "POST", sid, body });
141
+
142
+ before(async () => {
143
+ h = await startHarness();
144
+ mock = await startMockPadbot(h.core);
145
+ process.env.PADBOT_API_BASE = mock.url;
146
+ h.core.clearPadbotCache();
147
+ Object.assign(id, await seed(h));
148
+ outsiderSid = await h.login(OUTSIDER, PASSWORD);
149
+ managerSid = await h.login(MANAGER, PASSWORD);
150
+ }, { timeout: 300000 });
151
+
152
+ after(async () => {
153
+ delete process.env.PADBOT_API_BASE;
154
+ mock?.server.close();
155
+ if (h) await h.stop();
156
+ });
157
+
158
+ it("the brand list offers PadBot for security robots", async () => {
159
+ const res = await h.api("/robots/brands", { sid: managerSid });
160
+ assert.equal(res.status, 200);
161
+ const pb = res.body.items.find((b) => b.brand === "padbot");
162
+ assert.equal(pb.displayName, "PadBot");
163
+ assert.deepEqual(pb.types, ["security"]);
164
+ assert.equal(pb.capabilities.patrolControl, true);
165
+ assert.equal(pb.capabilities.pauseResume, false);
166
+ });
167
+
168
+ it("Add robot discovery: the typed AccessKey pair lists the account's patrol robots with who is reporting", async () => {
169
+ const res = await post("/robots/discover", { site: String(id.siteB), brand: "padbot", appKey: AK, appToken: SK });
170
+ assert.equal(res.status, 200, JSON.stringify(res.body));
171
+ assert.deepEqual(res.body.items.map((r) => [r.robotSn, r.name, r.online, r.added]), [["PS0001", "Patrol 1", true, false]]);
172
+ assert.equal(res.body.items[0].statusName, "Waiting for the lift");
173
+ assert.ok(!JSON.stringify(res.body).includes(SK));
174
+ assert.equal((await post("/robots/discover", { site: String(id.siteB), brand: "padbot", appKey: AK, appToken: SK }, outsiderSid)).status, 404);
175
+ });
176
+
177
+ it("Add robot: AccessKey pair saved in the credential fields, never returned; serial discovered from PadBot", async () => {
178
+ const create = await post("/robots", {
179
+ name: "Lobby patrol",
180
+ type: "security",
181
+ brand: "padbot",
182
+ appKey: AK,
183
+ appToken: SK,
184
+ metadata: { orgId: String(id.orgB), siteId: String(id.siteB) },
185
+ });
186
+ assert.equal(create.status, 201, JSON.stringify(create.body));
187
+ const row = await h.db.collection("robots").findOne({ name: "Lobby patrol" });
188
+ id.robot = String(row._id);
189
+ assert.equal(row.brand, "padbot");
190
+ const got = await h.api(`/robots/${id.robot}`, { sid: managerSid });
191
+ assert.equal(got.status, 200);
192
+ assert.ok(!JSON.stringify(got.body).includes(SK), "the secret never comes back");
193
+ assert.ok(!JSON.stringify(got.body).includes(AK), "nor the key id");
194
+ });
195
+
196
+ it("an outsider gets 404 and PadBot is not called", async () => {
197
+ const before = mock.seen.length;
198
+ assert.equal((await h.api(`/robots/${id.robot}/state`, { sid: outsiderSid })).status, 404);
199
+ assert.equal((await post(`/robots/${id.robot}/live-video`, {}, outsiderSid)).status, 404);
200
+ assert.equal(mock.seen.length, before);
201
+ });
202
+
203
+ it("state: battery, floor, lift phase in plain words, plan position, the open alarm as an alert", async () => {
204
+ const res = await h.api(`/robots/${id.robot}/state`, { sid: managerSid });
205
+ assert.equal(res.status, 200, JSON.stringify(res.body));
206
+ const s = res.body;
207
+ assert.equal(s.robotSn, "PS0001", "discovered from the account's patrol robots");
208
+ assert.equal(s.online, true);
209
+ assert.equal(s.mode, "IN_TRANSIT");
210
+ assert.equal(s.statusName, "Waiting for the lift");
211
+ assert.equal(s.batteryPercent, 72);
212
+ assert.equal(s.floorNo, 1);
213
+ assert.deepEqual(s.planPosition, { x: 50, y: 50 });
214
+ assert.equal(s.fault.code, "ALARM-3");
215
+ assert.equal(s.fault.message, "Smoke detected near Lobby");
216
+ assert.equal(s.model, "PadBot S2");
217
+ assert.equal((await h.db.collection("robots").findOne({ _id: new ObjectId(id.robot) })).robotSn, "PS0001");
218
+ });
219
+
220
+ it("patrol routes: the default route with its named checkpoints on the plan", async () => {
221
+ const res = await h.api(`/robots/${id.robot}/patrol-routes`, { sid: managerSid });
222
+ assert.equal(res.status, 200, JSON.stringify(res.body));
223
+ assert.equal(res.body.supported, true);
224
+ assert.equal(res.body.routes[0].name, "Lobby loop (default)");
225
+ assert.deepEqual(res.body.routes[0].checkpoints.map((c) => c.name), ["Entrance", "Lift lobby", "Dock"]);
226
+ assert.deepEqual(res.body.schedule, []);
227
+ });
228
+
229
+ it("commands: start patrol (default and named route), resume patrol, cancel, return - each the documented call; pause refused", async () => {
230
+ const mark = mock.seen.length;
231
+ // The robot reads IN_TRANSIT (riding a lift) - not free, so a new patrol is refused before PadBot is asked.
232
+ const busy = await post(`/robots/${id.robot}/command`, { kind: "full" });
233
+ assert.equal(busy.status, 400);
234
+ assert.ok(!mock.seen.slice(mark).some((c) => c.path === "/api/v1/robots/patrol/start"));
235
+
236
+ for (const [body, path] of [
237
+ [{ kind: "patrol-resume" }, "/api/v1/robots/patrol/resume"],
238
+ [{ kind: "cancel" }, "/api/v1/robots/actions/stop"],
239
+ [{ kind: "return" }, "/api/v1/robots/actions/charge"],
240
+ ]) {
241
+ const res = await post(`/robots/${id.robot}/command`, body);
242
+ assert.equal(res.status, 202, `${body.kind}: ${JSON.stringify(res.body)}`);
243
+ const call = mock.seen.filter((c) => c.path === path).at(-1);
244
+ assert.deepEqual(call.body, { serialNumber: "PS0001" });
245
+ assert.equal(call.verdict, "ok");
246
+ }
247
+ const pause = await post(`/robots/${id.robot}/command`, { kind: "pause" });
248
+ assert.equal(pause.status, 400);
249
+ assert.match(pause.body.message, /does not support "pause"/);
250
+ const audit = await h.db.collection("console-audit").find({ action: "robot.commanded", target: id.robot }).toArray();
251
+ assert.equal(audit.length, 3);
252
+ });
253
+
254
+ it("start patrol on a named route goes through once the robot is free - an open alarm does not block it", async () => {
255
+ mock.state.nav = { actionType: 0, actionState: 0 };
256
+ const res = await post(`/robots/${id.robot}/command`, { kind: "area", areas: ["p1"], cleanTimes: 2 });
257
+ assert.equal(res.status, 202, JSON.stringify(res.body));
258
+ const call = mock.seen.filter((c) => c.path === "/api/v1/robots/patrol/start").at(-1);
259
+ assert.deepEqual(call.body, { serialNumber: "PS0001", pathId: "p1", patrolCount: 2 });
260
+ const dflt = await post(`/robots/${id.robot}/command`, { kind: "full" });
261
+ assert.equal(dflt.status, 202, JSON.stringify(dflt.body));
262
+ assert.deepEqual(mock.seen.filter((c) => c.path === "/api/v1/robots/patrol/start").at(-1).body, { serialNumber: "PS0001", patrolCount: 1 });
263
+ mock.state.nav = { actionType: 2, actionState: 2 };
264
+ });
265
+
266
+ it("live video: minted on demand, not cached, not stored", async () => {
267
+ const res = await post(`/robots/${id.robot}/live-video`, {});
268
+ assert.equal(res.status, 200, JSON.stringify(res.body));
269
+ assert.deepEqual(res.body, { url: "https://video.mock/play/PS0001", expiresAt: "2026-09-26T09:00:00.000Z" });
270
+ const row = await h.db.collection("robots").findOne({ _id: new ObjectId(id.robot) });
271
+ assert.ok(!JSON.stringify(row).includes("video.mock"));
272
+ });
273
+
274
+ it("fault sweep: the open alarm is recorded and notified ONCE across sweeps; resolving clears it", async () => {
275
+ const sent = [];
276
+ const sweep = h.core.useRobotFaultSweep({ notifyFn: async (p) => sent.push(p), connectionNotifyFn: async () => undefined });
277
+ await sweep();
278
+ await sweep();
279
+ const faults = () => h.db.collection("robot-faults").find({ robotId: new ObjectId(id.robot) }).toArray().then((r) => r.length ? r : h.db.collection("robot-faults").find({ robotId: id.robot }).toArray());
280
+ const open = (await faults()).filter((f) => !f.clearedAt && f.code === "ALARM-3");
281
+ assert.equal(open.length, 1, "one record for one occurrence");
282
+ // The state read earlier already announced this occurrence; two sweeps add nothing.
283
+ assert.ok(open[0].notifiedAt, "announced once (by the first reader)");
284
+ assert.equal(sent.filter((p) => p.fault.code === "ALARM-3").length, 0, "the sweeps do not announce it again");
285
+
286
+ const res = await post(`/robots/${id.robot}/alerts/resolve`, { code: "ALARM-3" });
287
+ assert.equal(res.status, 200, JSON.stringify(res.body));
288
+ assert.equal(res.body.resolved, 1);
289
+ assert.equal(mock.openAlarms.size, 0);
290
+ await sweep();
291
+ const still = (await faults()).filter((f) => !f.clearedAt && f.code === "ALARM-3");
292
+ assert.equal(still.length, 0, "cleared once PadBot says resolved");
293
+ assert.equal(sent.filter((p) => p.fault.code === "ALARM-3").length, 0, "no second notice");
294
+ });
295
+
296
+ it("patrol history and one patrol's checkpoint visits", async () => {
297
+ const list = await h.api(`/robots/${id.robot}/patrol-history?page=1&limit=20`, { sid: managerSid });
298
+ assert.equal(list.status, 200, JSON.stringify(list.body));
299
+ assert.equal(list.body.total, 1);
300
+ assert.deepEqual(list.body.items[0], { id: "r1", routeName: "Lobby loop", result: "completed", startedAt: "2026-09-26T03:32:00.000Z", endedAt: "2026-09-26T03:33:41.000Z", durationS: 101, distanceM: 19.89, alarmCount: 1 });
301
+ const visits = await h.api(`/robots/${id.robot}/patrol-history/r1`, { sid: managerSid });
302
+ assert.equal(visits.status, 200);
303
+ assert.equal(visits.body.items[0].checkpoint, "Entrance");
304
+ assert.equal(visits.body.items[0].centerTempC, 24.5);
305
+ assert.equal((await h.api(`/robots/${id.robot}/patrol-history/bad%20id`, { sid: managerSid })).status, 400);
306
+ });
307
+
308
+ it("every request was signed correctly with a fresh X-Request-ID, and the mock refuses an exact replay", async () => {
309
+ assert.ok(mock.seen.length > 10);
310
+ assert.deepEqual([...new Set(mock.seen.map((c) => c.verdict))], ["ok"], "the mock accepted every signature");
311
+ assert.equal(new Set(mock.seen.map((c) => c.requestId)).size, mock.seen.length, "no X-Request-ID reused");
312
+ // Rebuild one request as it was sent and send it twice: second = replay.
313
+ const signed = h.core.padbotSignedRequest({ path: "/api/v1/robots/list", body: { robotTypes: ["PATROL"] }, accessKeyId: AK, accessKeySecret: SK });
314
+ assert.equal(await replay(mock.url, "/api/v1/robots/list", signed.headers, signed.body), 200);
315
+ assert.equal(await replay(mock.url, "/api/v1/robots/list", signed.headers, signed.body), 401);
316
+ assert.equal(mock.seen.at(-1).verdict, "replay");
317
+ // A wrong secret fails the signature check.
318
+ const forged = h.core.padbotSignedRequest({ path: "/api/v1/robots/list", body: {}, accessKeyId: AK, accessKeySecret: "wrong" });
319
+ assert.equal(await replay(mock.url, "/api/v1/robots/list", forged.headers, forged.body), 401);
320
+ assert.equal(mock.seen.at(-1).verdict, "signature");
321
+ // A non-canonical body (spaces) is refused even with a matching signature over it.
322
+ const spaced = '{ "robotTypes": ["PATROL"] }';
323
+ const sig = h.core.padbotSignedRequest({ path: "/api/v1/robots/list", body: { robotTypes: ["PATROL"] }, accessKeyId: AK, accessKeySecret: SK });
324
+ assert.equal(await replay(mock.url, "/api/v1/robots/list", sig.headers, spaced), 401);
325
+ assert.equal(mock.seen.at(-1).verdict, "not-canonical");
326
+ });
327
+ });
328
+
329
+ async function seed(h) {
330
+ const now = new Date().toISOString();
331
+ const orgA = new ObjectId();
332
+ const orgB = new ObjectId();
333
+ const siteA = new ObjectId();
334
+ const siteB = new ObjectId();
335
+ const roleA = new ObjectId();
336
+ const roleB = new ObjectId();
337
+ await h.db.collection("organizations").insertMany([
338
+ { _id: orgA, name: "PB Org A", email: "pba@e2e.example.com", type: "org", nature: "security_agency", status: "active", createdAt: now },
339
+ { _id: orgB, name: "PB Org B", email: "pbb@e2e.example.com", type: "org", nature: "security_agency", status: "active", createdAt: now },
340
+ ]);
341
+ await h.db.collection("sites").insertMany([
342
+ { _id: siteA, name: "PB Site A", org: orgA, orgId: orgA, status: "active" },
343
+ { _id: siteB, name: "PB Site B", org: orgB, orgId: orgB, status: "active" },
344
+ ]);
345
+ await h.db.collection("roles").insertMany([
346
+ { _id: roleA, name: "Manager A", org: orgA, permissions: ["*"], status: "active" },
347
+ { _id: roleB, name: "Manager B", org: orgB, permissions: ["*"], status: "active" },
348
+ ]);
349
+ const emails = [OUTSIDER, MANAGER];
350
+ const users = await h.db.collection("users").insertMany(emails.map((email) => ({ email, name: email.split("@")[0], status: "active", createdAt: now })));
351
+ const hashed = await h.hashPassword(PASSWORD);
352
+ await h.db.collection("users").updateMany({ email: { $in: emails } }, { $set: { password: hashed } });
353
+ const [outsider, manager] = [0, 1].map((i) => users.insertedIds[i]);
354
+ await h.db.collection("members").insertMany([
355
+ { user: outsider, org: orgA, siteId: siteA, type: "organization", role: roleA, status: "active" },
356
+ { user: manager, org: orgB, type: "organization", role: roleB, status: "active" },
357
+ ]);
358
+ return { orgA, orgB, siteA, siteB };
359
+ }