@7365admin1/core 3.103.0 → 3.107.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.
@@ -509,15 +509,9 @@ describe("notification preferences, end to end", { concurrency: 1 }, () => {
509
509
  async () => {
510
510
  const { NOTIFICATION_CATEGORIES } = h.core;
511
511
 
512
- const emailCapable = NOTIFICATION_CATEGORIES.filter(
513
- (c) => c.channels.email,
514
- ).map((c) => c.key);
515
-
516
- assert.deepEqual(
517
- emailCapable,
518
- [],
519
- "no category governs email at all — nothing in the estate sends a notification by email",
520
- );
512
+ // Notification email (2026-09-25) is opt-in per module and governs only
513
+ // notification copies — the catalogue still holds nothing for sign-in mail.
514
+ assert.ok(NOTIFICATION_CATEGORIES.every((c) => c.channels.email));
521
515
 
522
516
  // and the catalogue holds no category for a one-time code, a password
523
517
  // reset or an address verification, so nothing on the screen can reach one
@@ -0,0 +1,387 @@
1
+ // End-to-end proof for (1) robot credentials encrypted at rest, (2) HERO Fleet
2
+ // Core building data stored in `robot-building-maps`, (3) floor plans stored
3
+ // privately in the map record.
4
+ //
5
+ // In-process MongoDB replica set, loopback Redis and mail sink only.
6
+ // Run with: yarn test:e2e
7
+
8
+ import { after, before, describe, it } from "node:test";
9
+ import assert from "node:assert/strict";
10
+ import crypto from "node:crypto";
11
+ import { ObjectId } from "mongodb";
12
+
13
+ import { startHarness } from "./harness.mjs";
14
+
15
+ const PASSWORD = "Robot-Passw0rd!";
16
+ const OUTSIDER = "rcf-outsider@e2e.example.com";
17
+ const MANAGER = "rcf-manager@e2e.example.com";
18
+ const KEY = crypto.randomBytes(32).toString("hex");
19
+
20
+ // 1x1 PNG, and the same bytes padded past the 100 kB default body limit.
21
+ const PNG = Buffer.from(
22
+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d4944415478da63f8cfc0f01f0005000201a5f2a0a30000000049454e44ae426082",
23
+ "hex",
24
+ );
25
+ const BIG_PNG = Buffer.concat([PNG, Buffer.alloc(300_000, 0)]);
26
+
27
+ describe("robot credentials at rest, stored Fleet Core buildings, private floor plans", { concurrency: 1 }, () => {
28
+ let h;
29
+ const id = {};
30
+ let managerSid;
31
+ let outsiderSid;
32
+ let mapId;
33
+ let version;
34
+
35
+ before(async () => {
36
+ delete process.env.ROBOT_CREDENTIALS_KEY;
37
+ h = await startHarness();
38
+ Object.assign(id, await seed(h));
39
+ await h.core.useRobotBuildingMapRepo().createIndex();
40
+ managerSid = await h.login(MANAGER, PASSWORD);
41
+ outsiderSid = await h.login(OUTSIDER, PASSWORD);
42
+ }, { timeout: 300000 });
43
+
44
+ after(async () => {
45
+ delete process.env.ROBOT_CREDENTIALS_KEY;
46
+ if (h) await h.stop();
47
+ });
48
+
49
+ const robots = () => h.db.collection("robots");
50
+ const stored = async (rid) => robots().findOne({ _id: new ObjectId(rid) });
51
+
52
+ /* ---------------------------------------------------------- credentials */
53
+
54
+ it("without the key: a new robot is stored as before, and the migration does nothing", async () => {
55
+ const res = await h.api("/robots", {
56
+ method: "POST",
57
+ sid: managerSid,
58
+ body: { name: "No-key bot", brand: "demo", appKey: "plain-key-1", appToken: "plain-token-1", metadata: { orgId: String(id.orgB), siteId: String(id.siteB) } },
59
+ });
60
+ assert.equal(res.status, 201, JSON.stringify(res.body));
61
+ const row = await robots().findOne({ name: "No-key bot" });
62
+ id.noKeyBot = row._id;
63
+ assert.equal(row.appKey, "plain-key-1");
64
+ const run = await h.core.useRobotRepo().encryptPlaintextCredentials();
65
+ assert.equal(run.skipped, "no-key");
66
+ assert.equal((await stored(id.demo1)).appKey, "seed-key-demo1");
67
+ // Brands say encryption is off, so the dialog does not claim it.
68
+ const brands = await h.api("/robots/brands", { sid: managerSid });
69
+ assert.equal(brands.status, 200);
70
+ assert.equal(brands.body.credentialsEncrypted, false);
71
+ });
72
+
73
+ it("with the key: the migration encrypts every plain pair once (removed robots too) and is idempotent", async () => {
74
+ process.env.ROBOT_CREDENTIALS_KEY = KEY;
75
+ const first = await h.core.useRobotRepo().encryptPlaintextCredentials();
76
+ assert.equal(first.skipped, null);
77
+ assert.equal(first.encrypted, 4, "demo1, demo2, removed, no-key bot");
78
+ assert.equal(first.remaining, 0);
79
+ for (const rid of [id.demo1, id.demo2, id.removed, id.noKeyBot]) {
80
+ const r = await stored(rid);
81
+ assert.ok(r.appKey.startsWith("rc1:") && r.appToken.startsWith("rc1:"), `encrypted ${rid}`);
82
+ }
83
+ const again = await h.core.useRobotRepo().encryptPlaintextCredentials();
84
+ assert.deepEqual(again, { skipped: null, encrypted: 0, remaining: 0 });
85
+ });
86
+
87
+ it("an encrypted robot still works through its adapter (demo command accepted)", async () => {
88
+ const res = await h.api(`/robots/${id.demo1}/state`, { sid: managerSid });
89
+ assert.equal(res.status, 200, JSON.stringify(res.body));
90
+ });
91
+
92
+ it("lazy re-encrypt: a plain pair written behind our back is encrypted on the next read", async () => {
93
+ await robots().updateOne({ _id: id.demo2 }, { $set: { appKey: "sneaky-plain", appToken: "sneaky-token" } });
94
+ const res = await h.api(`/robots/${id.demo2}/state`, { sid: managerSid });
95
+ assert.equal(res.status, 200, JSON.stringify(res.body));
96
+ let r;
97
+ for (let i = 0; i < 20; i++) {
98
+ r = await stored(id.demo2);
99
+ if (r.appKey.startsWith("rc1:")) break;
100
+ await new Promise((ok) => setTimeout(ok, 50));
101
+ }
102
+ assert.ok(r.appKey.startsWith("rc1:") && r.appToken.startsWith("rc1:"));
103
+ const dec = h.core.robotCloudCredentials(r);
104
+ assert.deepEqual(dec, { appid: "sneaky-plain", secret: "sneaky-token" });
105
+ });
106
+
107
+ it("replace-only edit writes the new pair encrypted", async () => {
108
+ const res = await h.api(`/robots/${id.demo1}`, { method: "PATCH", sid: managerSid, body: { appKey: "new-key", appToken: "new-token" } });
109
+ assert.equal(res.status, 200, JSON.stringify(res.body));
110
+ const r = await stored(id.demo1);
111
+ assert.ok(r.appKey.startsWith("rc1:"));
112
+ assert.deepEqual(h.core.robotCloudCredentials(r), { appid: "new-key", secret: "new-token" });
113
+ });
114
+
115
+ it("no endpoint returns the credentials, plain or encrypted", async () => {
116
+ const reads = [
117
+ `/robots/${id.demo1}`,
118
+ `/robots/organization/${id.orgB}/site/${id.siteB}`,
119
+ `/robots/organization/${id.orgB}/site/${id.siteB}/fleet`,
120
+ `/robots/${id.demo1}/state`,
121
+ "/robots/brands",
122
+ ];
123
+ for (const path of reads) {
124
+ const res = await h.api(path, { sid: managerSid });
125
+ const text = JSON.stringify(res.body);
126
+ assert.equal(/appKey|appToken|rc1:|new-key|new-token|seed-key|plain-key/.test(text), false, `${path} leaked: ${text.slice(0, 200)}`);
127
+ }
128
+ });
129
+
130
+ it("key removed after encryption: the robot is refused by name, not sent a blank credential", async () => {
131
+ delete process.env.ROBOT_CREDENTIALS_KEY;
132
+ const res = await h.api(`/robots/${id.demo1}/state`, { sid: managerSid });
133
+ assert.equal(res.status, 503);
134
+ assert.match(JSON.stringify(res.body), /no key to read them/);
135
+ process.env.ROBOT_CREDENTIALS_KEY = KEY;
136
+ });
137
+
138
+ /* ------------------------------------------------ Fleet Core building */
139
+
140
+ const legacy = {
141
+ name: "Tower C",
142
+ levels: [{ floorNo: 1, walls: [{ start: { x: 1, y: 1 }, end: { x: 10, y: 1 } }], zones: [] }, { floorNo: 2 }],
143
+ doors: [{ name: "Lobby", floorNo: 1, type: "hinged", start: { x: 2, y: 1 }, end: { x: 3, y: 1 } }],
144
+ lifts: [{ name: "Lift A", x: 20, y: 10, floors: [1, 2] }],
145
+ };
146
+
147
+ it("an old-style map still saves and reads exactly as before (no rmf added)", async () => {
148
+ const res = await h.api("/robots/building-maps", { method: "POST", sid: managerSid, body: { ...legacy, robotId: String(id.demo1) } });
149
+ assert.equal(res.status, 201, JSON.stringify(res.body));
150
+ mapId = res.body.id;
151
+ version = res.body.version;
152
+ const row = await h.db.collection("robot-building-maps").findOne({ _id: new ObjectId(mapId) });
153
+ assert.equal(row.rmf, undefined);
154
+ });
155
+
156
+ it("export works for a map with no rmf part (building file and 404 for an empty route graph)", async () => {
157
+ const b = await h.raw(`/robots/building-maps/${mapId}/export?format=building`, { sid: managerSid });
158
+ assert.equal(b.status, 200);
159
+ assert.match(b.headers.get("content-disposition"), /tower-c\.building\.yaml/);
160
+ const y = JSON.parse(b.bytes.toString());
161
+ assert.equal(y.coordinate_system, "cartesian_meters");
162
+ assert.equal(y.levels.L1.walls.length, 1);
163
+ assert.ok(y.lifts["Lift A"]);
164
+ const nav = await h.api(`/robots/building-maps/${mapId}/export?format=nav`, { sid: managerSid });
165
+ assert.equal(nav.status, 404);
166
+ assert.equal((await h.api(`/robots/building-maps/${mapId}/export`, { sid: outsiderSid })).status, 404);
167
+ });
168
+
169
+ it("an rmf save (import) is stored and the legacy fields are derived from it", async () => {
170
+ const body = {
171
+ name: "Tower C",
172
+ version,
173
+ levels: [],
174
+ doors: [],
175
+ lifts: [],
176
+ rmf: bigBuilding(),
177
+ };
178
+ assert.ok(JSON.stringify(body).length > 100_000, "bigger than the default 100 kB body limit");
179
+ const res = await h.api(`/robots/building-maps/${mapId}`, { method: "PATCH", sid: managerSid, body });
180
+ assert.equal(res.status, 200, JSON.stringify(res.body).slice(0, 300));
181
+ version = res.body.version;
182
+ const map = (await h.api(`/robots/building-maps/${mapId}`, { sid: managerSid })).body;
183
+ assert.equal(map.rmf.levels.length, 2);
184
+ assert.equal(map.rmf.levels[0].lanes.length, 800);
185
+ assert.equal(map.doors.length, 1);
186
+ assert.equal(map.doors[0].type, "sliding", "double_sliding collapses for old readers");
187
+ assert.equal(map.levels[0].walls.length, 1200);
188
+ assert.deepEqual(map.lifts[0].floors, [1, 2]);
189
+ });
190
+
191
+ it("a legacy save afterwards keeps lanes, waypoints and door types", async () => {
192
+ const map = (await h.api(`/robots/building-maps/${mapId}`, { sid: managerSid })).body;
193
+ const res = await h.api(`/robots/building-maps/${mapId}`, {
194
+ method: "PATCH",
195
+ sid: managerSid,
196
+ body: { name: map.name, version, levels: map.levels.map(({ floorNo, name, elevationM, walls, zones }) => ({ floorNo, name, elevationM, walls: walls.slice(1), zones })), doors: map.doors, lifts: map.lifts },
197
+ });
198
+ assert.equal(res.status, 200, JSON.stringify(res.body).slice(0, 300));
199
+ version = res.body.version;
200
+ const after = (await h.api(`/robots/building-maps/${mapId}`, { sid: managerSid })).body;
201
+ assert.equal(after.rmf.levels[0].lanes.length, 800, "lanes survived");
202
+ assert.equal(after.rmf.levels[0].walls.length, 1199);
203
+ assert.equal(after.rmf.levels[0].doors[0].type, "double_sliding", "RMF door type survived");
204
+ assert.ok(after.rmf.levels[0].vertices.some((v) => v.params?.is_charger), "charger waypoint survived");
205
+ const nav = await h.raw(`/robots/building-maps/${mapId}/export?format=nav&graph=0`, { sid: managerSid });
206
+ assert.equal(nav.status, 200);
207
+ assert.ok(JSON.parse(nav.bytes.toString()).levels.L1.lanes.length >= 800);
208
+ });
209
+
210
+ it("broken rmf references are refused in plain words", async () => {
211
+ const bad = bigBuilding();
212
+ bad.levels[0].lanes.push({ v1: "v1", v2: "missing", graphIdx: 0, bidirectional: true });
213
+ const res = await h.api(`/robots/building-maps/${mapId}`, { method: "PATCH", sid: managerSid, body: { name: "x", version, rmf: bad } });
214
+ assert.equal(res.status, 400);
215
+ assert.match(JSON.stringify(res.body), /does not exist/);
216
+ });
217
+
218
+ it("the fleet-core rmf read is 404 on a server without Fleet Core (and 401 without a session)", async () => {
219
+ assert.equal((await h.api(`/robots/fleet-core/building?site=${id.siteB}&format=rmf`)).status, 401);
220
+ assert.equal((await h.api(`/robots/fleet-core/building?site=${id.siteB}&format=rmf`, { sid: managerSid })).status, 404);
221
+ });
222
+
223
+ /* ------------------------------------------------------- floor plans */
224
+
225
+ it("floor plan: 401 unauthenticated, 404 at another estate", async () => {
226
+ const body = { version, image: PNG.toString("base64"), widthPx: 1, heightPx: 1, metersPerPixel: 0.05 };
227
+ assert.equal((await h.api(`/robots/building-maps/${mapId}/floor-plans/1`, { method: "PUT", body })).status, 401);
228
+ assert.equal((await h.api(`/robots/building-maps/${mapId}/floor-plans/1`, { method: "PUT", sid: outsiderSid, body })).status, 404);
229
+ });
230
+
231
+ it("floor plan: a non-image is refused by its bytes, not its name", async () => {
232
+ const body = { version, image: `data:image/png;base64,${Buffer.from("<svg onload=alert(1)>").toString("base64")}`, widthPx: 1, heightPx: 1, metersPerPixel: 0.05 };
233
+ const res = await h.api(`/robots/building-maps/${mapId}/floor-plans/1`, { method: "PUT", sid: managerSid, body });
234
+ assert.equal(res.status, 400);
235
+ });
236
+
237
+ it("floor plan: stored in the map record (not the file store), served only to the estate", async () => {
238
+ const res = await h.api(`/robots/building-maps/${mapId}/floor-plans/1`, {
239
+ method: "PUT",
240
+ sid: managerSid,
241
+ body: { version, image: `data:image/png;base64,${BIG_PNG.toString("base64")}`, widthPx: 800, heightPx: 600, metersPerPixel: 0.05, tx: 1, ty: 2 },
242
+ });
243
+ assert.equal(res.status, 200, JSON.stringify(res.body));
244
+ version = res.body.version;
245
+ const row = await h.db.collection("robot-building-maps").findOne({ _id: new ObjectId(mapId) });
246
+ assert.equal(row.floorPlans.length, 1);
247
+ assert.equal(row.floorPlans[0].bytes, BIG_PNG.length);
248
+ // A map read carries the metadata but never the bytes.
249
+ const map = (await h.api(`/robots/building-maps/${mapId}`, { sid: managerSid })).body;
250
+ assert.equal(map.floorPlans[0].metersPerPixel, 0.05);
251
+ assert.equal(map.floorPlans[0].data, undefined);
252
+ const img = await h.raw(`/robots/building-maps/${mapId}/floor-plans/1`, { sid: managerSid });
253
+ assert.equal(img.status, 200);
254
+ assert.equal(img.headers.get("content-type"), "image/png");
255
+ assert.match(img.headers.get("cache-control"), /private/);
256
+ assert.ok(img.bytes.equals(BIG_PNG));
257
+ assert.equal((await h.raw(`/robots/building-maps/${mapId}/floor-plans/1`)).status, 401);
258
+ assert.equal((await h.raw(`/robots/building-maps/${mapId}/floor-plans/1`, { sid: outsiderSid })).status, 404);
259
+ assert.ok(await h.db.collection("console-audit").findOne({ action: "robot.map-updated", "after.floorPlanChange": "added" }));
260
+ });
261
+
262
+ it("floor plan: rescale without re-uploading; a map save keeps the plan; stale version is 409", async () => {
263
+ const res = await h.api(`/robots/building-maps/${mapId}/floor-plans/1`, {
264
+ method: "PUT",
265
+ sid: managerSid,
266
+ body: { version, widthPx: 800, heightPx: 600, metersPerPixel: 0.04 },
267
+ });
268
+ assert.equal(res.status, 200, JSON.stringify(res.body));
269
+ const stale = await h.api(`/robots/building-maps/${mapId}/floor-plans/1`, { method: "PUT", sid: managerSid, body: { version, widthPx: 800, heightPx: 600, metersPerPixel: 0.03 } });
270
+ assert.equal(stale.status, 409);
271
+ version = res.body.version;
272
+ const map = (await h.api(`/robots/building-maps/${mapId}`, { sid: managerSid })).body;
273
+ const save = await h.api(`/robots/building-maps/${mapId}`, {
274
+ method: "PATCH",
275
+ sid: managerSid,
276
+ body: { name: map.name, version, levels: map.levels.map(({ floorNo, name, elevationM, walls, zones }) => ({ floorNo, name, elevationM, walls, zones })), doors: map.doors, lifts: map.lifts },
277
+ });
278
+ assert.equal(save.status, 200);
279
+ version = save.body.version;
280
+ const img = await h.raw(`/robots/building-maps/${mapId}/floor-plans/1`, { sid: managerSid });
281
+ assert.ok(img.bytes.equals(BIG_PNG), "plan survived the map save");
282
+ const after = (await h.api(`/robots/building-maps/${mapId}`, { sid: managerSid })).body;
283
+ assert.equal(after.floorPlans[0].metersPerPixel, 0.04);
284
+ });
285
+
286
+ it("floor plan: remove", async () => {
287
+ const res = await h.api(`/robots/building-maps/${mapId}/floor-plans/1?version=${version}`, { method: "DELETE", sid: managerSid });
288
+ assert.equal(res.status, 200, JSON.stringify(res.body));
289
+ assert.equal((await h.raw(`/robots/building-maps/${mapId}/floor-plans/1`, { sid: managerSid })).status, 404);
290
+ assert.equal((await h.api(`/robots/building-maps/${mapId}/floor-plans/1?version=${res.body.version}`, { method: "DELETE", sid: managerSid })).status, 404);
291
+ });
292
+
293
+ it("other routes keep the 100 kB limit", async () => {
294
+ const res = await h.api(`/robots/${id.demo1}`, { method: "PATCH", sid: managerSid, body: { name: "x".repeat(150_000) } });
295
+ // body-parser refuses it before any handler (the shared error handler reports it as 500).
296
+ assert.ok(res.status >= 400, String(res.status));
297
+ });
298
+ });
299
+
300
+ /** Two levels, 1200 walls and 800 lanes on L1 - well past 100 kB. */
301
+ function bigBuilding() {
302
+ const vertices = [];
303
+ const walls = [];
304
+ const lanes = [];
305
+ for (let i = 0; i < 1201; i++) vertices.push({ id: `v${i + 1}`, x: (i % 40) * 0.5, y: -Math.floor(i / 40) * 0.5 });
306
+ for (let i = 0; i < 1200; i++) walls.push({ v1: `v${i + 1}`, v2: `v${i + 2}` });
307
+ for (let i = 0; i < 800; i++) lanes.push({ v1: `v${i + 1}`, v2: `v${i + 2}`, graphIdx: 0, bidirectional: true, speedLimit: 0.7 });
308
+ vertices[5].name = "charger_1";
309
+ vertices[5].params = { is_charger: true, dock_name: "dock_1" };
310
+ vertices.push({ id: "d1", x: 30, y: 5 }, { id: "d2", x: 31, y: 5 });
311
+ const frame = { minX: -1, maxX: 21, minY: -16, maxY: 6 };
312
+ const level = (name, floorNo, extra = {}) => ({
313
+ name, floorNo, elevationM: floorNo * 4, planFrame: frame, vertices: [], walls: [], floors: [], holes: [], doors: [], lanes: [], measurements: [], fiducials: [], zones: [], ...extra,
314
+ });
315
+ return {
316
+ formatVersion: 1,
317
+ coordinateSystem: "cartesian_meters",
318
+ source: "fleet-core",
319
+ referenceLevel: "L1",
320
+ graphs: [{ idx: 0, name: "Graph 0", brands: ["fleet-core"] }],
321
+ levels: [
322
+ level("L1", 1, { vertices, walls, lanes, doors: [{ name: "Main", v1: "d1", v2: "d2", type: "double_sliding" }] }),
323
+ level("L2", 2),
324
+ ],
325
+ lifts: [
326
+ {
327
+ name: "Lift A", x: 10, y: -5, yawRad: 0, widthM: 2, depthM: 2, referenceFloor: "L1",
328
+ doors: [{ name: "door1", type: "double_sliding", x: 1, y: 0, widthM: 1.2, axisYawRad: 1.571 }],
329
+ levelDoors: [{ level: "L1", doors: ["door1"] }, { level: "L2", doors: ["door1"] }],
330
+ },
331
+ ],
332
+ };
333
+ }
334
+
335
+ async function seed(h) {
336
+ const now = new Date().toISOString();
337
+ const orgA = new ObjectId();
338
+ const orgB = new ObjectId();
339
+ const siteA = new ObjectId();
340
+ const siteB = new ObjectId();
341
+ const roleA = new ObjectId();
342
+ const roleB = new ObjectId();
343
+ await h.db.collection("organizations").insertMany([
344
+ { _id: orgA, name: "RCF Org A", email: "rcfa@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now },
345
+ { _id: orgB, name: "RCF Org B", email: "rcfb@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now },
346
+ ]);
347
+ await h.db.collection("sites").insertMany([
348
+ { _id: siteA, name: "RCF Site A", org: orgA, orgId: orgA, status: "active" },
349
+ { _id: siteB, name: "RCF Site B", org: orgB, orgId: orgB, status: "active" },
350
+ ]);
351
+ await h.db.collection("roles").insertMany([
352
+ { _id: roleA, name: "Manager A", org: orgA, permissions: ["*"], status: "active" },
353
+ { _id: roleB, name: "Manager B", org: orgB, permissions: ["*"], status: "active" },
354
+ ]);
355
+ const emails = [OUTSIDER, MANAGER];
356
+ const users = await h.db.collection("users").insertMany(emails.map((email) => ({ email, name: email.split("@")[0], status: "active", createdAt: now })));
357
+ const hashed = await h.hashPassword(PASSWORD);
358
+ await h.db.collection("users").updateMany({ email: { $in: emails } }, { $set: { password: hashed } });
359
+ const [outsider, manager] = [0, 1].map((i) => users.insertedIds[i]);
360
+ await h.db.collection("members").insertMany([
361
+ { user: outsider, org: orgA, siteId: siteA, type: "organization", role: roleA, status: "active" },
362
+ { user: manager, org: orgB, type: "organization", role: roleB, status: "active" },
363
+ ]);
364
+ const robot = (name, key, extra = {}) => ({
365
+ name,
366
+ brand: "demo",
367
+ type: "cleaning",
368
+ robotSn: `DEMO-C-00${name.slice(-1)}`,
369
+ appKey: `seed-key-${key}`,
370
+ appToken: `seed-token-${key}`,
371
+ createdBy: manager,
372
+ createdByName: "rcf-manager",
373
+ metadata: { orgId: orgB, siteId: siteB, administratorId: "" },
374
+ status: "",
375
+ deletedAt: "",
376
+ createdAt: new Date(),
377
+ ...extra,
378
+ });
379
+ const r = await h.db.collection("robots").insertMany([
380
+ robot("Demo 1", "demo1"),
381
+ robot("Demo 2", "demo2"),
382
+ robot("Removed 3", "removed", { deletedAt: new Date() }),
383
+ // Already encrypted under nothing - an empty pair is left alone by the migration.
384
+ robot("Empty 4", "x", { appKey: "", appToken: "" }),
385
+ ]);
386
+ return { orgA, orgB, siteA, siteB, roleA, roleB, demo1: r.insertedIds[0], demo2: r.insertedIds[1], removed: r.insertedIds[2] };
387
+ }
@@ -391,24 +391,21 @@ describe("safety alerts, end to end", { concurrency: 1 }, () => {
391
391
  // ----------------------------------------------------------------- 15
392
392
 
393
393
  record(
394
- "15. no safety alert emails anybody, and the category says so on screen",
394
+ "15. no safety alert emails anybody who has not opted in to email",
395
395
  async () => {
396
396
  const mailsBefore = h.mails.length;
397
397
  await fireAll(id.site);
398
398
 
399
+ await h.core.flushNotificationEmails();
399
400
  assert.equal(
400
401
  h.mails.length,
401
402
  mailsBefore,
402
- "these four have no per-user email recipient and must not send one",
403
+ "nobody opted in to email, so nobody is emailed (email is opt-in, 2026-09-25)",
403
404
  );
404
405
 
405
- const { categorySupportsChannel, notificationCategory } = h.core;
406
+ const { categorySupportsChannel } = h.core;
406
407
  for (const { category } of SAFETY) {
407
- assert.equal(categorySupportsChannel(category, "email"), false, category);
408
- assert.ok(
409
- notificationCategory(category).channelNote?.email,
410
- `${category} must record why it offers no email switch`,
411
- );
408
+ assert.equal(categorySupportsChannel(category, "email"), true, category);
412
409
  }
413
410
  },
414
411
  );
@@ -62,7 +62,7 @@ test("every invite handler asks requireInviteReach, and asks first", () => {
62
62
 
63
63
  assert.match(
64
64
  body,
65
- new RegExp(`await requireInviteReach\\(req, ${org}, app, role\\)`),
65
+ new RegExp(`await requireInviteReach\\(req, ${org}, app, role, siteId\\)`),
66
66
  `${handler} must check the organisation it was handed`,
67
67
  );
68
68
 
@@ -75,6 +75,68 @@ test("an ObjectId-shaped org is compared by value, not by identity", () => {
75
75
  );
76
76
  });
77
77
 
78
+ // ---------------------------------------------------------------------------
79
+ // REFUSED since 2026-09-25 — the Invite member dropdown's wrong options
80
+ // (owner report: Wing Tai / Winsland House I listed "Org Owner", "Org - Admin
81
+ // Doan623"...). Each was accepted before this change.
82
+ // ---------------------------------------------------------------------------
83
+
84
+ const SITE_B = "6a7bd4c3d62595d5b572a2a5";
85
+
86
+ test("an org-less TEMPLATE role is refused on an invitation that names an organisation", () => {
87
+ for (const role of [{ type: "organization", org: "" }, { type: "organization" }]) {
88
+ assert.equal(
89
+ roleInvitable(role, CLIENT_A, ["property_management_agency"], SITE_A),
90
+ "That role is a shared template, not one of this organisation's roles.",
91
+ );
92
+ }
93
+ });
94
+
95
+ test("a deleted role is refused", () => {
96
+ assert.equal(
97
+ roleInvitable(
98
+ { type: "property_management_agency", org: CLIENT_A, status: "deleted" },
99
+ CLIENT_A,
100
+ ["property_management_agency"],
101
+ ),
102
+ "That role has been deleted.",
103
+ );
104
+ });
105
+
106
+ test("another application's role is refused", () => {
107
+ assert.equal(
108
+ roleInvitable(
109
+ { type: "cleaning_services", org: CLIENT_A },
110
+ CLIENT_A,
111
+ ["property_management_agency"],
112
+ ),
113
+ "That role belongs to a different application.",
114
+ );
115
+ });
116
+
117
+ test("a role pinned to another site is refused, and so is a site role on an org-wide invite", () => {
118
+ const role = { type: "property_management_agency", org: CLIENT_A, site: SITE_A };
119
+ for (const site of [SITE_B, "", null, undefined]) {
120
+ assert.equal(
121
+ roleInvitable(role, CLIENT_A, ["property_management_agency"], site),
122
+ "That role belongs to a different site.",
123
+ `site=${site}`,
124
+ );
125
+ }
126
+ });
127
+
128
+ test("CONTROL: the same role on its own site is allowed", () => {
129
+ assert.equal(
130
+ roleInvitable(
131
+ { type: "property_management_agency", org: CLIENT_A, site: SITE_A },
132
+ CLIENT_A,
133
+ ["property_management_agency"],
134
+ SITE_A,
135
+ ),
136
+ null,
137
+ );
138
+ });
139
+
78
140
  // ---------------------------------------------------------------------------
79
141
  // ALLOWED — the zero-lockout proof. Every legitimate shape that reaches the
80
142
  // invitation endpoints today, and still must.
@@ -82,16 +144,29 @@ test("an ObjectId-shaped org is compared by value, not by identity", () => {
82
144
 
83
145
  const LEGITIMATE = [
84
146
  [
85
- "super-admin invites a client with a TEMPLATE role (org-less, ~340 live rows)",
147
+ "Invite Client with a TEMPLATE role names no organisation (~340 live rows)",
86
148
  { type: "organization", org: "" },
149
+ "",
150
+ ["property_management_agency"],
151
+ ],
152
+ [
153
+ "the org-wide 'organization' role on a property-management invite (onboarding Invite Member)",
154
+ { type: "organization", org: CLIENT_A, site: "" },
87
155
  CLIENT_A,
88
156
  ["property_management_agency"],
89
157
  ],
90
158
  [
91
- "the same template role when the role org is absent entirely",
92
- { type: "organization" },
159
+ "a SITE-PINNED role invited into THAT site",
160
+ { type: "security_agency", org: CLIENT_A, site: SITE_A, status: "active" },
93
161
  CLIENT_A,
94
162
  ["security_agency"],
163
+ SITE_A,
164
+ ],
165
+ [
166
+ "real_estate_developer role on a property-management invite (type alias)",
167
+ { type: "real_estate_developer", org: CLIENT_A },
168
+ CLIENT_A,
169
+ ["property_management_agency"],
95
170
  ],
96
171
  [
97
172
  "org admin invites a member with the organisation OWN role (the majority)",
@@ -111,12 +186,6 @@ const LEGITIMATE = [
111
186
  CLIENT_A,
112
187
  ["property_management_agency"],
113
188
  ],
114
- [
115
- "a SITE-PINNED role invited into another site of the SAME org (36 live rows)",
116
- { type: "property_management_agency", org: CLIENT_A, site: SITE_A },
117
- CLIENT_A,
118
- ["property_management_agency"],
119
- ],
120
189
  [
121
190
  "an invitation that names no organisation at all (2 live rows)",
122
191
  { type: "property_management_agency", org: CLIENT_A },
@@ -155,10 +224,10 @@ const LEGITIMATE = [
155
224
  ],
156
225
  ];
157
226
 
158
- for (const [name, role, org, apps] of LEGITIMATE) {
227
+ for (const [name, role, org, apps, site] of LEGITIMATE) {
159
228
  test(`ALLOWED: ${name}`, () => {
160
229
  assert.equal(
161
- roleInvitable(role, org, apps),
230
+ roleInvitable(role, org, apps, site),
162
231
  null,
163
232
  "this invitation works today and must keep working",
164
233
  );
@@ -178,7 +247,7 @@ test("requireInviteReach runs the role check, and runs it last", () => {
178
247
 
179
248
  assert.match(
180
249
  authz,
181
- /const refusal = roleInvitable\(stored, org, apps\);\n\s*if \(refusal\) throw new BadRequestError\(refusal\);/,
250
+ /const refusal = roleInvitable\(stored, org, apps, site\);\n\s*if \(refusal\) throw new BadRequestError\(refusal\);/,
182
251
  "the refusal must be raised as a 4xx, not swallowed",
183
252
  );
184
253
 
@@ -187,7 +256,7 @@ test("requireInviteReach runs the role check, and runs it last", () => {
187
256
 
188
257
  assert.match(
189
258
  body,
190
- /await requireRoleInvitable\(role, org, apps\);/,
259
+ /await requireRoleInvitable\(role, org, apps, site\);/,
191
260
  "requireInviteReach must run the role check",
192
261
  );
193
262
 
@@ -207,7 +276,7 @@ test("the role is only ever read from the STORED role, never from the request",
207
276
  );
208
277
 
209
278
  assert.match(body, /collection\("roles"\)/);
210
- assert.match(body, /projection: \{ org: 1, type: 1 \}/);
279
+ assert.match(body, /projection: \{ org: 1, type: 1, site: 1, status: 1 \}/);
211
280
  assert.doesNotMatch(
212
281
  body,
213
282
  /req\.body|req\.query/,
@@ -229,8 +298,8 @@ test("every invite handler hands its role to the gate", () => {
229
298
  for (const call of calls) {
230
299
  assert.match(
231
300
  call,
232
- /, role\)$/,
233
- `${call} must pass the role it is about to write`,
301
+ /, role, siteId\)$/,
302
+ `${call} must pass the role and the site it is about to write`,
234
303
  );
235
304
  }
236
305
  });
@@ -121,7 +121,7 @@ test("createUserInvite refuses a staff invitation from a non-staff caller", () =
121
121
  // yourself as staff, then accept your own invitation.
122
122
  const body = fn(verificationController, "createUserInvite");
123
123
 
124
- assert.match(body, /await requireInviteReach\(req, org, app, role\)/);
124
+ assert.match(body, /await requireInviteReach\(req, org, app, role, siteId\)/);
125
125
 
126
126
  const gate = body.indexOf("requireInviteReach");
127
127
  const write = body.indexOf("_createUserInvite(");