@7365admin1/core 3.103.0 → 3.106.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.103.0",
4
+ "version": "3.106.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/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/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 --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/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 --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
  },
@@ -225,7 +225,11 @@ function startMailSink() {
225
225
  function buildApp(nsu, core) {
226
226
  const { requireAuth, errorHandler } = nsu;
227
227
  const app = express();
228
- app.use(express.json());
228
+ // mirrors iservice365-API-core/src/app.ts: 2 MB only for building-map writes
229
+ // (a full building, or one floor plan image), 100 kB everywhere else.
230
+ const bigJson = express.json({ limit: "2mb" });
231
+ const json = express.json();
232
+ app.use((req, res, next) => (/^\/api\/robots\/building-maps(\/|$)/.test(req.path) ? bigJson : json)(req, res, next));
229
233
 
230
234
  // mirrors iservice365-API-core/src/routes/auth.route.ts
231
235
  const auth = express.Router();
@@ -725,9 +729,14 @@ function buildApp(nsu, core) {
725
729
  // mirrors iservice365-API-core/src/routes/notification-preference.route.ts
726
730
  const notificationPreferences = express.Router();
727
731
  {
728
- const { get, update } = core.useNotificationPreferenceController();
732
+ const { get, update, requestEmail, verifyEmail, emailOff } =
733
+ core.useNotificationPreferenceController();
729
734
  notificationPreferences.get("/", requireAuth, get);
730
735
  notificationPreferences.put("/", requireAuth, update);
736
+ // the one-click turn-off link in a notification email: deliberately no requireAuth
737
+ notificationPreferences.get("/email/off", emailOff);
738
+ notificationPreferences.post("/email", requireAuth, requestEmail);
739
+ notificationPreferences.post("/email/verify", requireAuth, verifyEmail);
731
740
  }
732
741
 
733
742
  // mirrors iservice365-API-core/src/routes/personal-emergency-chain.route.ts
@@ -922,6 +931,10 @@ function buildApp(nsu, core) {
922
931
  robots.get(MAP, requireAuth, m.getMap);
923
932
  robots.patch(MAP, requireAuth, m.updateMap);
924
933
  robots.delete(MAP, requireAuth, m.deleteMap);
934
+ robots.get(`${MAP}/export`, requireAuth, m.exportMap);
935
+ robots.get(`${MAP}/floor-plans/:floorNo(-?[0-9]{1,3})`, requireAuth, m.getFloorPlan);
936
+ robots.put(`${MAP}/floor-plans/:floorNo(-?[0-9]{1,3})`, requireAuth, m.putFloorPlan);
937
+ robots.delete(`${MAP}/floor-plans/:floorNo(-?[0-9]{1,3})`, requireAuth, m.deleteFloorPlan);
925
938
  robots.get(`${MAP}/lifts`, requireAuth, m.getLiftQueue);
926
939
  robots.post(`${MAP}/lifts/:liftName/sessions`, requireAuth, m.requestLift);
927
940
  robots.post(`${SESSION}/refresh`, requireAuth, m.refreshLiftSession);
@@ -931,6 +944,7 @@ function buildApp(nsu, core) {
931
944
  // State and command, for DEMO-brand robots only in these tests: the demo
932
945
  // adapter reaches no network, so no vendor cloud is ever contacted.
933
946
  const f = core.useRobotFleetController();
947
+ robots.get("/brands", requireAuth, f.getBrands);
934
948
  robots.get("/:id([0-9a-fA-F]{24})/state", requireAuth, f.getState);
935
949
  robots.post("/:id([0-9a-fA-F]{24})/command", requireAuth, f.sendCommand);
936
950
  robots.get("/:id([0-9a-fA-F]{24})/patrol-routes", requireAuth, f.getPatrolRoutes);
@@ -1670,7 +1684,7 @@ export async function startHarness() {
1670
1684
  MAILER_TRANSPORT_PORT: String(mail.port),
1671
1685
  MAILER_TRANSPORT_SECURE: "false",
1672
1686
  MAILER_EMAIL: "no-reply@e2e.example.com",
1673
- MAILER_PASSWORD: "e2e",
1687
+ MAILER_PASSWORD: "e2e-mailer-secret",
1674
1688
  APP_MAIN: "http://app.e2e.example.com",
1675
1689
  DOMAIN: "localhost",
1676
1690
  // the S3 client is constructed eagerly by the user service; this flow never
@@ -1789,8 +1803,15 @@ export async function startHarness() {
1789
1803
  const redisGet = (key) => nsu.useRedis().getClient().get(key);
1790
1804
  const redisDel = (key) => nsu.useRedis().getClient().del(key);
1791
1805
 
1806
+ /** Raw response (headers + bytes), for binary endpoints. */
1807
+ async function raw(path, { sid } = {}) {
1808
+ const res = await fetch(`${base}${path}`, { headers: sid ? { authorization: `Bearer ${sid}` } : {} });
1809
+ return { status: res.status, headers: res.headers, bytes: Buffer.from(await res.arrayBuffer()) };
1810
+ }
1811
+
1792
1812
  return {
1793
1813
  api,
1814
+ raw,
1794
1815
  login,
1795
1816
  mailAt,
1796
1817
  db,
@@ -0,0 +1,117 @@
1
+ // End-to-end proof for the Invite member dialog fix (owner report 2026-09-25,
2
+ // Wing Tai Holdings / Winsland House I): the Role dropdown listed org-less
3
+ // template roles ("Org Owner", "Org - Admin Doan623"...) and the site list
4
+ // offered the organisation's other sites.
5
+ //
6
+ // Server half, proved here against a real in-process MongoDB:
7
+ // - the dropdown's read (GET /api/roles?org&type&site) returns only this
8
+ // organisation's roles for this app and site — never a template, another
9
+ // organisation's role, another site's role or a deleted role;
10
+ // - POST /api/auth/invite/member refuses every one of those, and still
11
+ // accepts every valid choice.
12
+ //
13
+ // Nothing outside the harness is touched. Run with: yarn test:e2e
14
+
15
+ import { after, before, describe, it } from "node:test";
16
+ import assert from "node:assert/strict";
17
+ import { ObjectId } from "mongodb";
18
+
19
+ import { startHarness } from "./harness.mjs";
20
+
21
+ const PASSWORD = "InviteRoleSite-Passw0rd!";
22
+ const ADMIN = "wing-admin@e2e.example.com";
23
+ const PM = "property_management_agency";
24
+
25
+ describe("invite member: role and site scope", { concurrency: 1 }, () => {
26
+ let h;
27
+ let sid;
28
+ const id = {};
29
+
30
+ before(async () => {
31
+ h = await startHarness();
32
+ Object.assign(id, await seed(h));
33
+ sid = await h.login(ADMIN, PASSWORD);
34
+ }, { timeout: 300000 });
35
+
36
+ after(async () => {
37
+ if (h) await h.stop();
38
+ });
39
+
40
+ const invite = (role, site = id.site1, email = `m-${new ObjectId()}@e2e.example.com`) =>
41
+ h.api("/auth/invite/member", {
42
+ method: "POST",
43
+ sid,
44
+ body: { email, app: PM, org: id.org.toString(), role: role.toString(), siteId: site ? site.toString() : "", siteName: site ? "Site" : "" },
45
+ });
46
+
47
+ it("the dropdown read lists only this org's roles for this app and site", async () => {
48
+ const res = await h.api(`/roles?org=${id.org}&type=${PM}&site=${id.site1}&limit=50`, { sid });
49
+ assert.equal(res.status, 200, JSON.stringify(res.body));
50
+ const names = res.body.items.map((r) => r.name).sort();
51
+ assert.deepEqual(names, ["Org-wide PM", "Site 1 PM"]);
52
+ });
53
+
54
+ for (const [name, key, message] of [
55
+ ["an org-less template role", "template", "shared template"],
56
+ ["another organisation's role", "otherOrg", "different organisation"],
57
+ ["a role pinned to another site of the same org", "site2Role", "different site"],
58
+ ["another application's role", "cleaning", "different application"],
59
+ ["a deleted role", "deleted", "deleted"],
60
+ ]) {
61
+ it(`refuses ${name}`, async () => {
62
+ const res = await invite(id[key]);
63
+ assert.equal(res.status, 400, JSON.stringify(res.body));
64
+ assert.match(JSON.stringify(res.body), new RegExp(message));
65
+ });
66
+ }
67
+
68
+ it("refuses a site role on an org-wide invitation (no site)", async () => {
69
+ const res = await invite(id.site1Role, null);
70
+ assert.equal(res.status, 400, JSON.stringify(res.body));
71
+ });
72
+
73
+ for (const [name, key] of [
74
+ ["this site's role", "site1Role"],
75
+ ["the org-wide role for this app", "orgWide"],
76
+ ["the org-wide 'organization' owner role", "owner"],
77
+ ]) {
78
+ it(`accepts ${name}`, async () => {
79
+ const res = await invite(id[key]);
80
+ assert.equal(res.status, 201, JSON.stringify(res.body));
81
+ });
82
+ }
83
+ });
84
+
85
+ async function seed(h) {
86
+ const now = new Date().toISOString();
87
+ const org = new ObjectId(), other = new ObjectId(), site1 = new ObjectId(), site2 = new ObjectId();
88
+ const ids = Object.fromEntries(
89
+ ["template", "otherOrg", "site1Role", "site2Role", "orgWide", "cleaning", "deleted", "owner"].map((k) => [k, new ObjectId()]),
90
+ );
91
+
92
+ await h.db.collection("organizations").insertMany([
93
+ { _id: org, name: "Wing E2E", email: "wing@e2e.example.com", type: "org", nature: PM, status: "active", createdAt: now },
94
+ { _id: other, name: "Doan E2E", email: "doan@e2e.example.com", type: "org", nature: PM, status: "active", createdAt: now },
95
+ ]);
96
+ await h.db.collection("sites").insertMany([
97
+ { _id: site1, name: "Winsland E2E I", org, orgId: org, status: "active" },
98
+ { _id: site2, name: "Winsland E2E II", org, orgId: org, status: "active" },
99
+ ]);
100
+ await h.db.collection("roles").insertMany([
101
+ { _id: ids.template, name: "Org - Admin Doan623", type: "organization", org: "", site: "", permissions: [], status: "active" },
102
+ { _id: ids.otherOrg, name: "Doan PM", type: PM, org: other, site: "", permissions: [], status: "active" },
103
+ { _id: ids.site1Role, name: "Site 1 PM", type: PM, org, site: site1, permissions: [], status: "active" },
104
+ { _id: ids.site2Role, name: "Site 2 PM", type: PM, org, site: site2, permissions: [], status: "active" },
105
+ { _id: ids.orgWide, name: "Org-wide PM", type: PM, org, site: "", permissions: [], status: "active" },
106
+ { _id: ids.cleaning, name: "Cleaner", type: "cleaning_services", org, site: "", permissions: [], status: "active" },
107
+ { _id: ids.deleted, name: "Old PM", type: PM, org, site: "", permissions: [], status: "deleted" },
108
+ { _id: ids.owner, name: "owner", type: "organization", org, site: "", permissions: ["*"], default: true, status: "active" },
109
+ ]);
110
+ await h.db.collection("subscriptions").insertOne({ org, type: "organization", status: "active", maxSeats: 0, paidSeats: 0, currentSeats: 0, createdAt: now });
111
+
112
+ const { insertedId: admin } = await h.db.collection("users").insertOne({ email: ADMIN, name: "wing-admin", status: "active", createdAt: now });
113
+ await h.db.collection("users").updateOne({ _id: admin }, { $set: { password: await h.hashPassword(PASSWORD) } });
114
+ await h.db.collection("members").insertOne({ user: admin, org, type: PM, role: ids.owner, status: "active" });
115
+
116
+ return { org, other, site1, site2, ...ids };
117
+ }
@@ -0,0 +1,331 @@
1
+ // Notification emails, end to end (owner request 2026-09-25).
2
+ //
3
+ // Real HTTP through the real `requireAuth`, the real preference service and
4
+ // both halves of the email path (queue + mailer) into the harness's loopback
5
+ // SMTP sink. Nothing can reach a real inbox: the mailer points at 127.0.0.1.
6
+ //
7
+ // Run with: yarn test:e2e
8
+
9
+ import { after, before, describe, it } from "node:test";
10
+ import assert from "node:assert/strict";
11
+ import { createRequire } from "node:module";
12
+ import { ObjectId } from "mongodb";
13
+
14
+ import { startHarness } from "./harness.mjs";
15
+
16
+ const require = createRequire(import.meta.url);
17
+
18
+ const PASSWORD = "Mail-Passw0rd!";
19
+ const RESIDENT = "resident@e2e.example.com";
20
+ const OTHER = "second@e2e.example.com";
21
+
22
+ const qp = (s) =>
23
+ String(s)
24
+ .replace(/=\r?\n/g, "")
25
+ .replace(/=([0-9A-Fa-f]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
26
+
27
+ describe("notification emails, end to end", { concurrency: 1 }, () => {
28
+ let h;
29
+ let sid;
30
+ let userId;
31
+ let otherSid;
32
+ let site;
33
+ const logs = [];
34
+ const result = [];
35
+ let restoreLogger;
36
+
37
+ const record = (name, fn) =>
38
+ it(name, async () => {
39
+ try {
40
+ await fn();
41
+ result.push(["PASS", name]);
42
+ } catch (error) {
43
+ result.push(["FAIL", name]);
44
+ throw error;
45
+ }
46
+ });
47
+
48
+ before(async () => {
49
+ process.env.EMAIL_NOTIFICATIONS_ALLOWLIST = "*@e2e.example.com";
50
+ h = await startHarness();
51
+
52
+ const { logger } = require("@7365admin1/node-server-utils");
53
+ const original = logger.log;
54
+ logger.log = function (entry, ...rest) {
55
+ logs.push(typeof entry === "string" ? entry : String(entry?.message ?? ""));
56
+ return original.call(this, entry, ...rest);
57
+ };
58
+ restoreLogger = () => (logger.log = original);
59
+
60
+ const org = new ObjectId();
61
+ site = new ObjectId();
62
+ const role = new ObjectId();
63
+ await h.db.collection("sites").insertOne({ _id: site, name: "Aurora", orgId: org, status: "active" });
64
+ await h.db.collection("roles").insertOne({ _id: role, name: "Resident", org, status: "active", permissions: [] });
65
+ const users = await h.db.collection("users").insertMany([
66
+ { email: RESIDENT, password: await h.hashPassword(PASSWORD), name: "Robin", status: "active", defaultOrg: org.toString() },
67
+ { email: OTHER, password: await h.hashPassword(PASSWORD), name: "Sam", status: "active", defaultOrg: org.toString() },
68
+ ]);
69
+ userId = users.insertedIds[0].toString();
70
+ await h.db.collection("members").insertMany([
71
+ { user: users.insertedIds[0], org, site, role, type: "resident", status: "active" },
72
+ { user: users.insertedIds[1], org, site, role, type: "resident", status: "active" },
73
+ ]);
74
+ sid = await h.login(RESIDENT, PASSWORD);
75
+ otherSid = await h.login(OTHER, PASSWORD);
76
+ }, { timeout: 300000 });
77
+
78
+ after(async () => {
79
+ restoreLogger?.();
80
+ delete process.env.EMAIL_NOTIFICATIONS_ALLOWLIST;
81
+ if (h) await h.stop();
82
+ console.log("\n--- notification emails: per-case result ---");
83
+ for (const [verdict, name] of result) console.log(`${verdict} ${name}`);
84
+ });
85
+
86
+ const mailsTo = (addr) => h.mails.filter((m) => m.to.includes(addr));
87
+ const prefs = (s = sid) => h.api("/notification-preferences?include=email", { sid: s });
88
+ const put = (body, s = sid) =>
89
+ h.api("/notification-preferences?include=email", { method: "PUT", sid: s, body });
90
+
91
+ /** Send one notice-board notification to the resident; return the emails it produced. */
92
+ async function notice(subject = "Lift maintenance") {
93
+ const before = mailsTo(RESIDENT).length;
94
+ await h.core.NotificationService.bulletinBoardCreated({
95
+ to: userId,
96
+ bulletinId: new ObjectId(),
97
+ subject,
98
+ status: "published",
99
+ siteId: site.toString(),
100
+ });
101
+ await h.core.flushNotificationEmails();
102
+ return mailsTo(RESIDENT).slice(before).map((m) => ({ ...m, body: qp(m.body) }));
103
+ }
104
+
105
+ async function verifyAddress(address) {
106
+ const before = mailsTo(address).length;
107
+ const res = await h.api("/notification-preferences/email", { method: "POST", sid, body: { address } });
108
+ assert.equal(res.status, 200, JSON.stringify(res.body));
109
+ const mail = mailsTo(address)[before];
110
+ assert.ok(mail, "a code was emailed");
111
+ const code = qp(mail.body).match(/\b(\d{6})\b/)[1];
112
+ return { res, code };
113
+ }
114
+
115
+ record("1. an older client sees exactly the old shape (no email channel, no email block)", async () => {
116
+ const res = await h.api("/notification-preferences", { sid });
117
+ assert.equal(res.status, 200);
118
+ assert.equal(res.body.data.email, undefined);
119
+ for (const c of res.body.data.categories) {
120
+ assert.ok(!c.channels.some((ch) => ch.key === "email"), c.key);
121
+ }
122
+ });
123
+
124
+ record("2. with include=email: Email is offered, OFF for every module, address suggested", async () => {
125
+ const res = await prefs();
126
+ assert.equal(res.status, 200);
127
+ const { email, categories } = res.body.data;
128
+ assert.equal(email.available, true);
129
+ assert.equal(email.address, null);
130
+ assert.equal(email.verified, false);
131
+ assert.equal(email.accountEmail, RESIDENT);
132
+ assert.ok(categories.length > 0);
133
+ for (const c of categories) {
134
+ const ch = c.channels.find((x) => x.key === "email");
135
+ assert.ok(ch, `${c.key} has an Email row`);
136
+ assert.equal(ch.enabled, false, `${c.key} email is off by default`);
137
+ }
138
+ });
139
+
140
+ record("3. nothing is emailed while email is off", async () => {
141
+ assert.equal((await notice()).length, 0);
142
+ });
143
+
144
+ record("4. email ON but address not verified: still nothing is emailed", async () => {
145
+ const res = await put({ off: [], email: ["bulletinBoard"] });
146
+ assert.equal(res.status, 200, JSON.stringify(res.body));
147
+ const nb = res.body.data.categories.find((c) => c.key === "bulletinBoard");
148
+ assert.equal(nb.channels.find((c) => c.key === "email").enabled, true);
149
+ assert.equal((await notice()).length, 0);
150
+ });
151
+
152
+ record("5. verification: wrong code refused, resend throttled, right code verifies", async () => {
153
+ const { res, code } = await verifyAddress(RESIDENT);
154
+ assert.equal(res.body.data.email.pendingAddress, RESIDENT);
155
+ assert.equal(res.body.data.email.verified, false);
156
+
157
+ const again = await h.api("/notification-preferences/email", { method: "POST", sid, body: { address: RESIDENT } });
158
+ assert.equal(again.status, 400, "a second code within a minute is refused");
159
+
160
+ const wrong = code === "000000" ? "111111" : "000000";
161
+ const bad = await h.api("/notification-preferences/email/verify", { method: "POST", sid, body: { code: wrong } });
162
+ assert.equal(bad.status, 400);
163
+
164
+ const ok = await h.api("/notification-preferences/email/verify", { method: "POST", sid, body: { code } });
165
+ assert.equal(ok.status, 200, JSON.stringify(ok.body));
166
+ assert.equal(ok.body.data.email.verified, true);
167
+ assert.equal(ok.body.data.email.address, RESIDENT);
168
+ assert.equal(ok.body.data.email.pendingAddress, null);
169
+
170
+ const row = await h.db.collection("notification-preferences").findOne({ userId: new ObjectId(userId) });
171
+ assert.ok(row.email.offKey, "a turn-off secret was created");
172
+ assert.ok(!JSON.stringify(row).includes(`"${code}"`), "the code itself is never stored");
173
+ });
174
+
175
+ record("6. on + verified: one email, with button, why, turn-off and settings links", async () => {
176
+ const mails = await notice("Water shut-off Tuesday");
177
+ assert.equal(mails.length, 1);
178
+ const m = mails[0];
179
+ assert.match(m.body, /Open in iService365/);
180
+ assert.match(m.body, /notifications\/open\?kind=bulletinBoard/);
181
+ assert.match(m.body, new RegExp(`site=${site}`));
182
+ assert.match(m.body, /Why am I getting this\?/);
183
+ assert.match(m.body, /Turn off email for Notice Board/);
184
+ assert.match(m.body, /\/notification-settings/);
185
+ assert.match(m.body, /\/api\/notification-preferences\/email\/off\?u=/);
186
+ });
187
+
188
+ record("7. the turn-off link works without signing in and cannot be tampered with", async () => {
189
+ const m = (await notice())[0];
190
+ const link = m.body.match(/https?:\/\/[^\s"<]+\/api\/notification-preferences\/email\/off\?[^\s"<]+/)[0].replace(/&amp;/g, "&");
191
+ const url = new URL(link);
192
+ const path = `/notification-preferences/email/off?${url.searchParams.toString()}`;
193
+
194
+ const tamper = (k, v) => {
195
+ const p = new URLSearchParams(url.searchParams);
196
+ p.set(k, v);
197
+ return `/notification-preferences/email/off?${p.toString()}`;
198
+ };
199
+ for (const bad of [
200
+ tamper("c", "feedback"),
201
+ tamper("u", new ObjectId().toString()),
202
+ tamper("t", "x" + url.searchParams.get("t").slice(1)),
203
+ "/notification-preferences/email/off",
204
+ ]) {
205
+ const res = await h.api(bad);
206
+ assert.equal(res.status, 400, bad);
207
+ assert.match(String(res.body), /This link does not work/);
208
+ }
209
+ assert.equal((await notice()).length, 1, "still on after every forged link");
210
+
211
+ const res = await h.api(path); // no sid
212
+ assert.equal(res.status, 200);
213
+ assert.match(String(res.body), /Email for Notice Board is off/);
214
+ assert.equal((await notice()).length, 0, "off after the genuine link");
215
+
216
+ const view = await prefs();
217
+ const nb = view.body.data.categories.find((c) => c.key === "bulletinBoard");
218
+ assert.equal(nb.channels.find((c) => c.key === "email").enabled, false);
219
+ });
220
+
221
+ record("8. rate limit: at most 5 per module per hour, the last one says the rest are held", async () => {
222
+ await put({ off: [], email: ["bulletinBoard"] });
223
+ await h.db.collection("notification-preferences").updateOne(
224
+ { userId: new ObjectId(userId) },
225
+ { $unset: { emailSends: "" } },
226
+ );
227
+ const got = [];
228
+ for (let i = 0; i < 8; i++) got.push(...(await notice(`Burst ${i}`)));
229
+ assert.equal(got.length, 5);
230
+ assert.match(got[4].body, /will not email you about Notice Board again for up to an hour/);
231
+ assert.doesNotMatch(got[3].body, /for up to an hour/);
232
+ assert.ok(logs.some((l) => /held \(hourly limit\)/.test(l)));
233
+ });
234
+
235
+ record("9. 'Turn everything off' from an older client (no email field) turns email off too", async () => {
236
+ await h.db.collection("notification-preferences").updateOne(
237
+ { userId: new ObjectId(userId) },
238
+ { $unset: { emailSends: "" } },
239
+ );
240
+ assert.equal((await notice()).length, 1, "on before");
241
+ const view = (await prefs()).body.data;
242
+ const off = view.categories.flatMap((c) =>
243
+ c.channels.filter((ch) => ch.key !== "email").map((ch) => ({ category: c.key, channel: ch.key })),
244
+ );
245
+ const res = await h.api("/notification-preferences", { method: "PUT", sid, body: { off } });
246
+ assert.equal(res.status, 200, JSON.stringify(res.body));
247
+ assert.equal((await notice()).length, 0);
248
+ const row = await h.db.collection("notification-preferences").findOne({ userId: new ObjectId(userId) });
249
+ assert.deepEqual(row.emailOn, []);
250
+ });
251
+
252
+ record("10. an older client saving an ordinary change leaves email choices alone", async () => {
253
+ await put({ off: [], email: ["bulletinBoard"] });
254
+ const res = await h.api("/notification-preferences", {
255
+ method: "PUT",
256
+ sid,
257
+ body: { off: [{ category: "bulletinBoard", channel: "push" }] },
258
+ });
259
+ assert.equal(res.status, 200);
260
+ const row = await h.db.collection("notification-preferences").findOne({ userId: new ObjectId(userId) });
261
+ assert.deepEqual(row.emailOn, ["bulletinBoard"]);
262
+ });
263
+
264
+ record("11. allow-list guard: an address not on the list is never sent to (logged as would-send)", async () => {
265
+ await h.db.collection("notification-preferences").updateOne(
266
+ { userId: new ObjectId(userId) },
267
+ { $unset: { emailSends: "" } },
268
+ );
269
+ process.env.EMAIL_NOTIFICATIONS_ALLOWLIST = "*@somewhere-else.example";
270
+ try {
271
+ assert.equal((await notice()).length, 0);
272
+ assert.ok(logs.some((l) => /would send \(address not on the allow-list\)/.test(l)));
273
+ const res = await h.api("/notification-preferences/email", {
274
+ method: "POST",
275
+ sid,
276
+ body: { address: "other@e2e.example.com" },
277
+ });
278
+ assert.equal(res.status, 400, "no code is sent to an address the list refuses");
279
+ } finally {
280
+ process.env.EMAIL_NOTIFICATIONS_ALLOWLIST = "*@e2e.example.com";
281
+ }
282
+ });
283
+
284
+ record("12. with the list unset it fails closed to Seven365's domain: e2e addresses get nothing", async () => {
285
+ await h.db.collection("notification-preferences").updateOne(
286
+ { userId: new ObjectId(userId) },
287
+ { $unset: { emailSends: "" } },
288
+ );
289
+ delete process.env.EMAIL_NOTIFICATIONS_ALLOWLIST;
290
+ try {
291
+ assert.equal((await notice()).length, 0);
292
+ const view = await prefs();
293
+ assert.equal(view.body.data.email.available, false, "not offered to a non-allow-listed account");
294
+ assert.ok(
295
+ !view.body.data.categories.some((c) => c.channels.some((ch) => ch.key === "email")),
296
+ "no Email switch drawn when it is not available",
297
+ );
298
+ } finally {
299
+ process.env.EMAIL_NOTIFICATIONS_ALLOWLIST = "*@e2e.example.com";
300
+ }
301
+ });
302
+
303
+ record("13. a change of address keeps the old verified one until the new code is entered", async () => {
304
+ await h.db.collection("notification-preferences").updateOne(
305
+ { userId: new ObjectId(userId) },
306
+ { $unset: { emailSends: "" } },
307
+ );
308
+ const { res } = await verifyAddress("new-box@e2e.example.com");
309
+ assert.equal(res.body.data.email.address, RESIDENT, "old verified address still in use");
310
+ assert.equal(res.body.data.email.pendingAddress, "new-box@e2e.example.com");
311
+ const mails = await notice();
312
+ assert.equal(mails.length, 1);
313
+ assert.equal(mailsTo("new-box@e2e.example.com").filter((m) => /Notice Board/.test(qp(m.body))).length, 0);
314
+ });
315
+
316
+ record("14. one person's settings never reach another (other user unaffected)", async () => {
317
+ const res = await prefs(otherSid);
318
+ assert.equal(res.body.data.email.address, null);
319
+ assert.ok(res.body.data.categories.every((c) => c.channels.find((ch) => ch.key === "email").enabled === false));
320
+ });
321
+
322
+ record("15. no address, code, or mailer password in any log line of the email path", async () => {
323
+ const lines = logs.filter((l) => l.includes("[notification-email]"));
324
+ assert.ok(lines.length > 0);
325
+ for (const l of lines) {
326
+ assert.doesNotMatch(l, /@/, l);
327
+ assert.doesNotMatch(l, /\b\d{6}\b/, l);
328
+ assert.ok(!l.includes(process.env.MAILER_PASSWORD), l);
329
+ }
330
+ });
331
+ });
@@ -294,21 +294,17 @@ describe("notification settings: the measured matrix", { concurrency: 1 }, () =>
294
294
  });
295
295
  }
296
296
 
297
- it("no category in the catalogue can deliver email", async () => {
298
- const withEmail = h.core.NOTIFICATION_CATEGORIES.filter((c) => c.channels.email).map((c) => c.key);
299
- assert.deepEqual(
300
- withEmail,
301
- [],
302
- "a category claims an email channel — then a sender must call filterRecipients with \"email\", and none does",
303
- );
297
+ it("email (opt-in, 2026-09-25) is offered by every rendered category and read by the email queue", async () => {
298
+ const withoutEmail = h.core.NOTIFICATION_CATEGORIES.filter((c) => c.rendered && !c.channels.email).map((c) => c.key);
299
+ assert.deepEqual(withoutEmail, [], "every rendered category offers the Email switch");
304
300
  });
305
301
 
306
- it("a category that cannot use a channel keeps nobody on it", async () => {
302
+ it("email never passes the absent-is-on guard: nobody is emailed without opting in", async () => {
307
303
  const { filterRecipients } = h.core.useNotificationPreferenceRepo();
308
304
  assert.deepEqual(
309
305
  await filterRecipients([id.user.toString()], "bulletinBoard", "email"),
310
306
  [],
311
- "an email send would reach nobody, which is why no switch is offered",
307
+ "email is decided by emailRecipients (opt-in + verified), never by filterRecipients",
312
308
  );
313
309
  });
314
310
  });
@@ -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