@7365admin1/core 3.107.0 → 3.110.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.107.0",
4
+ "version": "3.110.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 --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 src/utils/invite-origin.util.ts src/utils/member-role-assign.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
  },
@@ -0,0 +1,149 @@
1
+ // Assign Role end to end, reproducing the owner's report (2026-09-25,
2
+ // production): Security app, Aigle Security / Newton 200 → Members → Assign Role
3
+ // "Security Newton 200" → "No owner role found."
4
+ //
5
+ // The organisation here stores NO "*" role at all — its owner holds an org-less
6
+ // template ("Org Owner", explicit list), exactly like Aigle. Before the fix
7
+ // case 1 answered 400 "No owner role found.".
8
+ //
9
+ // Everything runs against the throwaway harness (in-process MongoDB, loopback
10
+ // Redis/mail). No staging or production system is touched.
11
+ //
12
+ // Run with: yarn test:e2e
13
+
14
+ import { after, before, describe, it } from "node:test";
15
+ import assert from "node:assert/strict";
16
+ import { ObjectId } from "mongodb";
17
+
18
+ import { startHarness } from "./harness.mjs";
19
+
20
+ const PASSWORD = "AssignRole-Passw0rd!";
21
+ const OWNER = "ar-owner@e2e.example.com"; // holds the org-less template, like Aigle's owner
22
+ const GUARD = "ar-guard@e2e.example.com"; // an ordinary member without the grant
23
+ const TARGET = "ar-target@e2e.example.com"; // the site member being re-roled
24
+ const OUTSIDER = "ar-outsider@e2e.example.com"; // admin of another org
25
+ const SOLE = "ar-sole@e2e.example.com"; // the only '*' owner in org B
26
+ const STAFF = "ar-staff@e2e.example.com"; // Seven365 platform staff (console)
27
+
28
+ describe("Assign Role works without a stored owner role, and stays scoped", { concurrency: 1 }, () => {
29
+ let h;
30
+ const id = {};
31
+ const sid = {};
32
+
33
+ before(async () => {
34
+ h = await startHarness();
35
+ Object.assign(id, await seed(h));
36
+ for (const [k, e] of Object.entries({ OWNER, GUARD, OUTSIDER, SOLE, STAFF })) sid[k] = await h.login(e, PASSWORD);
37
+ }, { timeout: 300000 });
38
+
39
+ after(async () => {
40
+ if (h) await h.stop();
41
+ });
42
+
43
+ const url = (member, role, org = id.org, type = "security_agency") =>
44
+ `/members/id/${member}/role/${role}/type/${type}/org/${org}`;
45
+ const roleOf = async (member) =>
46
+ (await h.db.collection("members").findOne({ _id: member }))?.role?.toString();
47
+
48
+ it("1. owner assigns this site's role to a site member — org has no stored owner role", async () => {
49
+ const res = await h.api(url(id.target, id.siteRole), { method: "PUT", sid: sid.OWNER });
50
+ assert.equal(res.status, 200, JSON.stringify(res.body));
51
+ assert.equal(await roleOf(id.target), id.siteRole.toString());
52
+ });
53
+
54
+ it("2. a role of another organisation is refused", async () => {
55
+ const res = await h.api(url(id.target, id.otherOrgRole), { method: "PUT", sid: sid.OWNER });
56
+ assert.equal(res.status, 400);
57
+ assert.match(res.body.message, /different organisation/);
58
+ assert.equal(await roleOf(id.target), id.siteRole.toString());
59
+ });
60
+
61
+ it("3. a role pinned to another site is refused", async () => {
62
+ const res = await h.api(url(id.target, id.otherSiteRole), { method: "PUT", sid: sid.OWNER });
63
+ assert.equal(res.status, 400);
64
+ assert.match(res.body.message, /different site/);
65
+ });
66
+
67
+ it("4. a member without members:assign-member-role is refused", async () => {
68
+ const res = await h.api(url(id.target, id.oldRole), { method: "PUT", sid: sid.GUARD });
69
+ assert.equal(res.status, 401);
70
+ assert.equal(await roleOf(id.target), id.siteRole.toString());
71
+ });
72
+
73
+ it("5. another org's admin is refused", async () => {
74
+ const res = await h.api(url(id.target, id.oldRole), { method: "PUT", sid: sid.OUTSIDER });
75
+ assert.equal(res.status, 401);
76
+ });
77
+
78
+ it("6. the only '*' owner still cannot be demoted", async () => {
79
+ const res = await h.api(url(id.soleMember, id.plainRoleB, id.orgB, "organization"), { method: "PUT", sid: sid.SOLE });
80
+ assert.equal(res.status, 400);
81
+ assert.match(res.body.message, /only owner member/);
82
+ });
83
+
84
+ it("8. console: staff re-role an org-less staff membership via the empty-org URL; a client cannot", async () => {
85
+ const path = `/members/id/${id.staffTarget}/role/${id.staffRole2}/type/admin/org/`;
86
+ const refused = await h.api(path, { method: "PUT", sid: sid.OWNER });
87
+ assert.equal(refused.status, 401);
88
+ const res = await h.api(path, { method: "PUT", sid: sid.STAFF });
89
+ assert.equal(res.status, 200, JSON.stringify(res.body));
90
+ assert.equal(await roleOf(id.staffTarget), id.staffRole2.toString());
91
+ });
92
+
93
+ it("7. the Members list shows the real role name and flags a deleted role", async () => {
94
+ await h.db.collection("members").updateOne({ _id: id.target }, { $set: { role: id.deletedRole } });
95
+ const res = await h.api(`/members?org=${id.org}&siteId=${id.site}&type=security_agency&status=active&page=1`, { sid: sid.OWNER });
96
+ assert.equal(res.status, 200, JSON.stringify(res.body));
97
+ const row = res.body.items.find((m) => String(m._id) === String(id.target));
98
+ assert.equal(row.roleName, "Security");
99
+ assert.equal(row.roleState, "deleted");
100
+ });
101
+ });
102
+
103
+ async function seed(h) {
104
+ const now = new Date().toISOString();
105
+ const org = new ObjectId(), orgB = new ObjectId(), site = new ObjectId(), otherSite = new ObjectId();
106
+ const template = new ObjectId(), guardRole = new ObjectId(), oldRole = new ObjectId(), siteRole = new ObjectId();
107
+ const otherSiteRole = new ObjectId(), deletedRole = new ObjectId(), otherOrgRole = new ObjectId();
108
+ const ownerRoleB = new ObjectId(), plainRoleB = new ObjectId();
109
+ const staffRole = new ObjectId(), staffRole2 = new ObjectId();
110
+
111
+ await h.db.collection("organizations").insertMany([
112
+ { _id: org, name: "AR Security", email: "ar-org@e2e.example.com", type: "org", nature: "security_agency", status: "active", createdAt: now },
113
+ { _id: orgB, name: "AR Other", email: "ar-orgb@e2e.example.com", type: "org", nature: "security_agency", status: "active", createdAt: now },
114
+ ]);
115
+ await h.db.collection("sites").insertMany([
116
+ { _id: site, name: "Newton 200", org, orgId: org, status: "active" },
117
+ { _id: otherSite, name: "The Loft", org, orgId: org, status: "active" },
118
+ ]);
119
+ await h.db.collection("roles").insertMany([
120
+ { _id: template, name: "Org Owner", org: "", type: "organization", permissions: ["members:view-members", "members:assign-member-role"], status: "active" },
121
+ { _id: guardRole, name: "Guard", org, type: "security_agency", permissions: ["members:view-members"], status: "active" },
122
+ { _id: oldRole, name: "Old", org, type: "security_agency", permissions: ["members:view-members"], status: "active" },
123
+ { _id: siteRole, name: "Security Newton 200", org, site, type: "security_agency", permissions: ["members:view-members"], status: "active" },
124
+ { _id: otherSiteRole, name: "Security Roles", org, site: otherSite, type: "security_agency", permissions: [], status: "active" },
125
+ { _id: deletedRole, name: "Security", org, type: "security_agency", permissions: [], status: "deleted" },
126
+ { _id: otherOrgRole, name: "Other org role", org: orgB, type: "security_agency", permissions: [], status: "active" },
127
+ { _id: ownerRoleB, name: "owner", org: orgB, type: "organization", permissions: ["*"], status: "active" },
128
+ { _id: plainRoleB, name: "Plain B", org: orgB, type: "organization", permissions: ["members:view-members"], status: "active" },
129
+ { _id: staffRole, name: "Super Admin", type: "admin", default: true, permissions: [], status: "active" },
130
+ { _id: staffRole2, name: "Support", type: "admin", permissions: [], status: "active" },
131
+ ]);
132
+
133
+ const emails = [OWNER, GUARD, TARGET, OUTSIDER, SOLE, STAFF, "ar-staff2@e2e.example.com"];
134
+ const users = await h.db.collection("users").insertMany(emails.map((email) => ({ email, name: email, status: "active", createdAt: now })));
135
+ await h.db.collection("users").updateMany({ email: { $in: emails } }, { $set: { password: await h.hashPassword(PASSWORD) } });
136
+ const [owner, guard, target, outsider, sole, staff, staff2] = emails.map((_, i) => users.insertedIds[i]);
137
+
138
+ const m = await h.db.collection("members").insertMany([
139
+ { user: owner, org, type: "security_agency", role: template, status: "active" },
140
+ { user: guard, org, type: "security_agency", role: guardRole, siteId: site, siteName: "Newton 200", status: "active" },
141
+ { user: target, org, type: "security_agency", role: oldRole, siteId: site, siteName: "Newton 200", status: "active", dateInvited: now },
142
+ { user: outsider, org: orgB, type: "organization", role: plainRoleB, status: "active" },
143
+ { user: sole, org: orgB, type: "organization", role: ownerRoleB, status: "active" },
144
+ { user: staff, type: "admin", role: staffRole, status: "active" },
145
+ { user: staff2, type: "admin", role: staffRole, status: "active" },
146
+ ]);
147
+
148
+ return { org, orgB, site, siteRole, otherSiteRole, deletedRole, otherOrgRole, oldRole, plainRoleB, target: m.insertedIds[2], soleMember: m.insertedIds[4], staffTarget: m.insertedIds[6], staffRole2 };
149
+ }
@@ -334,6 +334,7 @@ function buildApp(nsu, core) {
334
334
  members.get("/user/:id/app/:type", requireAuth, getByUserIdType);
335
335
  members.put("/:id/:status", requireAuth, updateMemberStatus);
336
336
  members.put("/id/:id/role/:role/type/:type/org/:org", requireAuth, updateRoleById);
337
+ members.put("/id/:id/role/:role/type/:type/org", requireAuth, updateRoleById);
337
338
  members.put("/site", requireAuth, updateSiteById);
338
339
  members.put("/:id/onboarding/complete", requireAuth, completeOnboarding);
339
340
  members.get("/user/:id/app/:type/org", requireAuth, getByUserIdTypeOrg);
@@ -354,17 +354,18 @@ describe("invitations are scoped to an organisation the caller can reach", { con
354
354
  assert.equal(res.status, 201, JSON.stringify(res.body));
355
355
  });
356
356
 
357
- record("18. an invitation that names NO organisation is left alone", async () => {
358
- // web-app-org pages/organizations/invite.vue sends email/app/role/name and
359
- // no org at all. It grants no organisation, so it is not this rule's
360
- // business — exactly as an org-less GET /api/roles is not.
357
+ record("18. an invitation that names NO organisation is Seven365 staff's alone", async () => {
358
+ // Changed 2026-09-25 (owner report, org invite in the Seven365 console): an
359
+ // invitation naming no organisation is Seven365's - a new client or Seven365
360
+ // staff - and is listed as sent by Seven365 (`invite-origin.util.ts`). So
361
+ // an ordinary account can no longer send one; it used to get 201 here.
361
362
  const res = await h.api("/auth/invite", {
362
363
  method: "POST",
363
364
  sid: mallorySid,
364
365
  body: { email: "no-org@e2e.example.com", app: "organization", role: id.roleA.toString() },
365
366
  });
366
367
 
367
- assert.equal(res.status, 201, JSON.stringify(res.body));
368
+ assert.equal(res.status, 401, JSON.stringify(res.body));
368
369
  });
369
370
 
370
371
  record("19. the seat-gated organisation invite still works for a member", async () => {
@@ -0,0 +1,188 @@
1
+ // End-to-end proof for the owner report of 2026-09-25 (production): Aigle
2
+ // Security invited a person into its own organisation from the Organization
3
+ // app, and the invitation was listed in the Seven365 console's Invitations
4
+ // ("Invitations sent from Seven365") - which listed every client's invitations.
5
+ //
6
+ // Proved here against a real in-process MongoDB, over the real handlers:
7
+ // - a client's organisation invitation is stored with its org and role, is in
8
+ // the client's own list and never in Seven365's;
9
+ // - Seven365's own invitations (staff, new client, Invite Client into an
10
+ // existing client) are marked and listed, and so are unmarked org-less ones
11
+ // written before the marker;
12
+ // - only Seven365 staff may send an invitation naming no organisation, or read
13
+ // Seven365's list; an organisation invitation must name a role;
14
+ // - accepting the client's invitation makes the right membership.
15
+ //
16
+ // Nothing outside the harness is touched. Run with: yarn test:e2e
17
+
18
+ import { after, before, describe, it } from "node:test";
19
+ import assert from "node:assert/strict";
20
+ import { ObjectId } from "mongodb";
21
+
22
+ import { startHarness } from "./harness.mjs";
23
+
24
+ const PASSWORD = "OrgInviteScope-Passw0rd!";
25
+ const STAFF = "staff@e2e.example.com";
26
+ const OWNER = "aigle-owner@e2e.example.com";
27
+ const INVITEE = "kanesan@e2e.example.com";
28
+ const LIST = "/verifications?status=pending&type=user-invite,member-invite&limit=100";
29
+
30
+ describe("organisation invitations stay with their organisation", { concurrency: 1 }, () => {
31
+ let h;
32
+ let staff;
33
+ let owner;
34
+ const id = {};
35
+ let clientInvite;
36
+
37
+ before(async () => {
38
+ h = await startHarness();
39
+ Object.assign(id, await seed(h));
40
+ staff = await h.login(STAFF, PASSWORD);
41
+ owner = await h.login(OWNER, PASSWORD);
42
+ }, { timeout: 300000 });
43
+
44
+ after(async () => {
45
+ if (h) await h.stop();
46
+ });
47
+
48
+ const byEmail = (email) => h.db.collection("verifications").findOne({ email });
49
+ const seven365 = async () => {
50
+ const res = await h.api(`${LIST}&origin=seven365`, { sid: staff });
51
+ assert.equal(res.status, 200, JSON.stringify(res.body));
52
+ return res.body.items.map((i) => i.email);
53
+ };
54
+
55
+ it("the client's organisation invitation is stored with its org and role, and no origin", async () => {
56
+ const res = await h.api("/auth/invite/member", {
57
+ method: "POST",
58
+ sid: owner,
59
+ body: { email: INVITEE, app: "organization", org: id.aigle.toString(), role: id.aigleRole.toString(), siteId: "", siteName: "" },
60
+ });
61
+ assert.equal(res.status, 201, JSON.stringify(res.body));
62
+ clientInvite = await byEmail(INVITEE);
63
+ assert.equal(clientInvite.type, "member-invite");
64
+ assert.equal(String(clientInvite.metadata.org), String(id.aigle));
65
+ assert.equal(String(clientInvite.metadata.role), String(id.aigleRole));
66
+ assert.equal(clientInvite.metadata.app, "organization");
67
+ assert.equal(clientInvite.metadata.origin, undefined);
68
+ });
69
+
70
+ it("it is in the client's own Invitations list, with its role", async () => {
71
+ const res = await h.api(`/verifications?status=pending&type=member-invite&app=organization&orgId=${id.aigle}`, { sid: owner });
72
+ assert.equal(res.status, 200, JSON.stringify(res.body));
73
+ const row = res.body.items.find((i) => i.email === INVITEE);
74
+ assert.ok(row, "missing from the client's list");
75
+ assert.equal(row.roleName, "Aigle Supervisor");
76
+ });
77
+
78
+ it("Seven365's own invitations are marked seven365", async () => {
79
+ const staffInvite = await h.api("/auth/invite", {
80
+ method: "POST",
81
+ sid: staff,
82
+ body: { email: "new-staff@e2e.example.com", app: "admin", role: id.staffRole.toString(), name: "Super Admin" },
83
+ });
84
+ assert.equal(staffInvite.status, 201, JSON.stringify(staffInvite.body));
85
+ const newClient = await h.api("/auth/invite/user", {
86
+ method: "POST",
87
+ sid: staff,
88
+ body: { email: "new-client@e2e.example.com", app: ["security_agency"] },
89
+ });
90
+ assert.equal(newClient.status, 201, JSON.stringify(newClient.body));
91
+ const intoClient = await h.api("/auth/invite/user", {
92
+ method: "POST",
93
+ sid: staff,
94
+ body: { email: "console-into-aigle@e2e.example.com", app: ["organization"], org: id.aigle.toString(), role: id.aigleRole.toString() },
95
+ });
96
+ assert.equal(intoClient.status, 201, JSON.stringify(intoClient.body));
97
+ for (const email of ["new-staff@e2e.example.com", "new-client@e2e.example.com", "console-into-aigle@e2e.example.com"]) {
98
+ assert.equal((await byEmail(email)).metadata.origin, "seven365", email);
99
+ }
100
+ });
101
+
102
+ it("Seven365's list holds only what Seven365 sent - never the client's invitation", async () => {
103
+ const emails = await seven365();
104
+ assert.ok(!emails.includes(INVITEE), "the client's invitation is in Seven365's list");
105
+ assert.ok(!emails.includes("legacy-client@e2e.example.com"), "an unmarked client invitation is in Seven365's list");
106
+ for (const email of ["new-staff@e2e.example.com", "new-client@e2e.example.com", "console-into-aigle@e2e.example.com", "legacy-orgless@e2e.example.com"]) {
107
+ assert.ok(emails.includes(email), `${email} missing from Seven365's list`);
108
+ }
109
+ });
110
+
111
+ it("a client invitation sent by a Seven365 staff member from the Organization app is still the client's", async () => {
112
+ const res = await h.api("/auth/invite/member", {
113
+ method: "POST",
114
+ sid: staff,
115
+ body: { email: "staff-as-aigle@e2e.example.com", app: "organization", org: id.aigle.toString(), role: id.aigleRole.toString() },
116
+ });
117
+ assert.equal(res.status, 201, JSON.stringify(res.body));
118
+ assert.equal((await byEmail("staff-as-aigle@e2e.example.com")).metadata.origin, undefined);
119
+ assert.ok(!(await seven365()).includes("staff-as-aigle@e2e.example.com"));
120
+ });
121
+
122
+ it("a client cannot read Seven365's list, or send an invitation naming no organisation", async () => {
123
+ assert.equal((await h.api(`${LIST}&origin=seven365`, { sid: owner })).status, 401);
124
+ assert.equal((await h.api(`${LIST}&origin=seven365&orgId=${id.aigle}`, { sid: owner })).status, 401);
125
+ for (const [path, body] of [
126
+ ["/auth/invite", { email: "orgless-1@e2e.example.com", app: "organization", role: id.aigleRole.toString() }],
127
+ ["/auth/invite/member", { email: "orgless-2@e2e.example.com", app: "organization", role: id.aigleRole.toString() }],
128
+ ["/auth/invite/user", { email: "orgless-3@e2e.example.com", app: ["organization"] }],
129
+ ["/auth/v2/invite", { email: "orgless-4@e2e.example.com", app: "organization", role: id.aigleRole.toString() }],
130
+ ]) {
131
+ const res = await h.api(path, { method: "POST", sid: owner, body });
132
+ assert.ok([400, 401].includes(res.status), `${path} ${res.status} ${JSON.stringify(res.body)}`);
133
+ }
134
+ assert.equal(await h.db.collection("verifications").countDocuments({ email: /^orgless-/ }), 0);
135
+ });
136
+
137
+ it("an organisation invitation must name a role", async () => {
138
+ const res = await h.api("/auth/invite/member", {
139
+ method: "POST",
140
+ sid: owner,
141
+ body: { email: "no-role@e2e.example.com", app: "organization", org: id.aigle.toString(), role: "" },
142
+ });
143
+ assert.equal(res.status, 400, JSON.stringify(res.body));
144
+ assert.match(JSON.stringify(res.body), /role/i);
145
+ });
146
+
147
+ it("accepting the client's invitation makes the membership in that client, with the chosen role", async () => {
148
+ const sid = await h.login(INVITEE, PASSWORD);
149
+ const res = await h.api(`/members/verification/${clientInvite._id}`, { method: "POST", sid });
150
+ assert.equal(res.status, 201, JSON.stringify(res.body));
151
+ const member = await h.db.collection("members").findOne({ user: id.invitee });
152
+ assert.ok(member, "no membership written");
153
+ assert.equal(String(member.org), String(id.aigle));
154
+ assert.equal(member.type, "organization");
155
+ assert.equal(String(member.role), String(id.aigleRole));
156
+ });
157
+ });
158
+
159
+ async function seed(h) {
160
+ const now = new Date().toISOString();
161
+ const later = new Date(Date.now() + 72 * 3600e3).toISOString();
162
+ const aigle = new ObjectId(), aigleRole = new ObjectId(), ownerRole = new ObjectId(), staffRole = new ObjectId();
163
+
164
+ await h.db.collection("organizations").insertOne({ _id: aigle, name: "Aigle E2E", email: "aigle@e2e.example.com", type: "org", nature: "security_agency", status: "active", createdAt: now });
165
+ await h.db.collection("roles").insertMany([
166
+ { _id: staffRole, name: "Super Admin", type: "admin", default: true, permissions: [], status: "active" },
167
+ { _id: ownerRole, name: "owner", type: "organization", org: aigle, site: "", permissions: ["*"], default: true, status: "active" },
168
+ { _id: aigleRole, name: "Aigle Supervisor", type: "organization", org: aigle, site: "", permissions: [], status: "active" },
169
+ ]);
170
+ await h.db.collection("subscriptions").insertOne({ org: aigle, type: "organization", status: "active", maxSeats: 0, paidSeats: 0, currentSeats: 0, createdAt: now });
171
+
172
+ const users = await h.db.collection("users").insertMany(
173
+ [STAFF, OWNER, INVITEE].map((email) => ({ email, name: email.split("@")[0], status: "active", createdAt: now })),
174
+ );
175
+ await h.db.collection("users").updateMany({}, { $set: { password: await h.hashPassword(PASSWORD) } });
176
+ await h.db.collection("members").insertMany([
177
+ { user: users.insertedIds[0], type: "admin", role: staffRole, status: "active" },
178
+ { user: users.insertedIds[1], org: aigle, type: "organization", role: ownerRole, status: "active" },
179
+ ]);
180
+
181
+ // Written before the origin marker existed.
182
+ await h.db.collection("verifications").insertMany([
183
+ { type: "user-invite", email: "legacy-orgless@e2e.example.com", metadata: { app: "security_agency", role: "", org: "" }, status: "pending", createdAt: now, expireAt: later },
184
+ { type: "member-invite", email: "legacy-client@e2e.example.com", metadata: { app: "organization", role: aigleRole, org: aigle }, status: "pending", createdAt: now, expireAt: later },
185
+ ]);
186
+
187
+ return { aigle, aigleRole, ownerRole, staffRole, invitee: users.insertedIds[2] };
188
+ }
@@ -0,0 +1,148 @@
1
+ // Owner decision (Harris, 2026-09-25): only the OWNING client organisation -
2
+ // a member whose role holds the existing "Delete Site" right (or `*`) - and
3
+ // Seven365 Super Admin may delete a site. A service provider that serves the
4
+ // site is refused with a plain message and keeps "Remove from your Sites".
5
+ //
6
+ // Everything runs against the throwaway in-process harness (in-memory MongoDB,
7
+ // loopback Redis and mail). Nothing outside this process is touched.
8
+ //
9
+ // Run with: yarn build && node --test test/e2e/site-delete-owner-only.e2e.test.mjs
10
+
11
+ import { after, before, describe, it } from "node:test";
12
+ import assert from "node:assert/strict";
13
+ import { ObjectId } from "mongodb";
14
+
15
+ import { startHarness } from "./harness.mjs";
16
+
17
+ const PASSWORD = "DeleteOwner-Passw0rd!";
18
+ const MANAGER = "do-manager@e2e.example.com"; // owning client, holds Delete Site
19
+ const VIEWER = "do-viewer@e2e.example.com"; // owning client, no Delete Site
20
+ const AGENCY = "do-agency@e2e.example.com"; // provider org admin, serves the site
21
+ const STAFF = "do-sevenadmin@e2e.example.com";
22
+ const REFUSAL =
23
+ "This site belongs to DO Client. Only they can delete it. You can remove it from your Sites list instead.";
24
+
25
+ describe("only the owning client (or Seven365) deletes a site", { concurrency: 1 }, () => {
26
+ let h;
27
+ const id = {};
28
+ const result = [];
29
+ const sid = {};
30
+
31
+ const record = (name, fn) =>
32
+ it(name, async () => {
33
+ try {
34
+ await fn();
35
+ result.push(["PASS", name]);
36
+ } catch (error) {
37
+ result.push(["FAIL", name]);
38
+ throw error;
39
+ }
40
+ });
41
+
42
+ const status = async (site) => (await h.db.collection("sites").findOne({ _id: site }))?.status;
43
+
44
+ before(async () => {
45
+ h = await startHarness();
46
+ Object.assign(id, await seed(h));
47
+ }, { timeout: 300000 });
48
+
49
+ after(async () => {
50
+ if (h) await h.stop();
51
+ console.log("\n--- site delete owner-only: per-case result ---");
52
+ for (const [verdict, name] of result) console.log(`${verdict} ${name}`);
53
+ });
54
+
55
+ record("0. baseline", async () => {
56
+ sid.manager = await h.login(MANAGER, PASSWORD);
57
+ sid.viewer = await h.login(VIEWER, PASSWORD);
58
+ sid.agency = await h.login(AGENCY, PASSWORD);
59
+ sid.staff = await h.login(STAFF, PASSWORD);
60
+ assert.equal(await status(id.tower), "active");
61
+ });
62
+
63
+ record("1. the provider that serves the site cannot delete it, and is told why", async () => {
64
+ const res = await h.api(`/sites/${id.tower}`, { method: "DELETE", sid: sid.agency });
65
+ assert.equal(res.status, 403, JSON.stringify(res.body));
66
+ assert.equal(res.body?.message, REFUSAL);
67
+ assert.equal(await status(id.tower), "active", "site untouched");
68
+ });
69
+
70
+ record("2. an owner-org member without Delete Site cannot delete it", async () => {
71
+ const res = await h.api(`/sites/${id.tower}`, { method: "DELETE", sid: sid.viewer });
72
+ assert.equal(res.status, 403, JSON.stringify(res.body));
73
+ assert.equal(res.body?.message, "You do not have permission to delete this site.");
74
+ assert.equal(await status(id.tower), "active");
75
+ });
76
+
77
+ record("3. the provider CAN still remove the site from its own Sites list", async () => {
78
+ const res = await h.api(`/customer-sites/${id.served}`, { method: "DELETE", sid: sid.agency });
79
+ assert.equal(res.status, 200, JSON.stringify(res.body));
80
+ const row = await h.db.collection("customer.sites").findOne({ _id: new ObjectId(id.served) });
81
+ assert.equal(row.status, "deleted");
82
+ assert.equal(await status(id.tower), "active", "the client's site itself is untouched");
83
+ });
84
+
85
+ record("4. the owner holding Delete Site CAN delete it", async () => {
86
+ const res = await h.api(`/sites/${id.tower}`, { method: "DELETE", sid: sid.manager });
87
+ assert.equal(res.status, 200, JSON.stringify(res.body));
88
+ assert.equal(await status(id.tower), "deleted");
89
+ });
90
+
91
+ record("5. Seven365 Super Admin CAN delete a client's site", async () => {
92
+ const res = await h.api(`/sites/${id.annex}`, { method: "DELETE", sid: sid.staff });
93
+ assert.equal(res.status, 200, JSON.stringify(res.body));
94
+ assert.equal(await status(id.annex), "deleted");
95
+ });
96
+ });
97
+
98
+ async function seed(h) {
99
+ const now = new Date().toISOString();
100
+ const client = new ObjectId();
101
+ const agency = new ObjectId();
102
+ const tower = new ObjectId();
103
+ const annex = new ObjectId();
104
+ const staffRole = new ObjectId();
105
+ const managerRole = new ObjectId();
106
+ const viewerRole = new ObjectId();
107
+ const agencyRole = new ObjectId();
108
+
109
+ await h.db.collection("organizations").insertMany([
110
+ { _id: client, name: "DO Client", email: "do-client@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now, defaultSite: tower.toString() },
111
+ { _id: agency, name: "DO Agency", email: "do-agency-org@e2e.example.com", type: "org", nature: "security_agency", status: "active", createdAt: now },
112
+ ]);
113
+
114
+ await h.db.collection("sites").insertMany([
115
+ { _id: tower, name: "DO Tower", org: client, orgId: client, status: "active", timezone: "Asia/Singapore", createdAt: now },
116
+ { _id: annex, name: "DO Annex", org: client, orgId: client, status: "active", timezone: "Asia/Singapore", createdAt: now },
117
+ ]);
118
+
119
+ const rows = await h.db.collection("customer.sites").insertMany([
120
+ { name: "DO Tower", org: agency, siteOrg: client, siteOrgName: "DO Client", site: tower, status: "active", createdAt: now },
121
+ { name: "DO Tower", org: client, siteOrg: client, siteOrgName: "DO Client", site: tower, status: "active", createdAt: now },
122
+ ]);
123
+
124
+ await h.db.collection("roles").insertMany([
125
+ { _id: staffRole, name: "Super Admin", type: "admin", default: true, permissions: [], status: "active" },
126
+ { _id: managerRole, name: "Site Admin", org: client, type: "organization", permissions: ["sites:see-all-sites", "sites:delete-site"], status: "active" },
127
+ { _id: viewerRole, name: "Site Viewer", org: client, type: "organization", permissions: ["sites:see-all-sites"], status: "active" },
128
+ { _id: agencyRole, name: "Owner", org: agency, type: "organization", permissions: ["*"], status: "active" },
129
+ ]);
130
+
131
+ const emails = [MANAGER, VIEWER, AGENCY, STAFF];
132
+ const users = await h.db.collection("users").insertMany(
133
+ emails.map((email) => ({ email, name: email.split("@")[0], status: "active", createdAt: now })),
134
+ );
135
+ const hashed = await h.hashPassword(PASSWORD);
136
+ await h.db.collection("users").updateMany({ email: { $in: emails } }, { $set: { password: hashed } });
137
+ const [manager, viewer, agencyAdmin, staff] = [0, 1, 2, 3].map((i) => users.insertedIds[i]);
138
+
139
+ await h.db.collection("members").insertMany([
140
+ { user: manager, org: client, type: "organization", role: managerRole, status: "active" },
141
+ { user: viewer, org: client, type: "organization", role: viewerRole, status: "active" },
142
+ // the provider's company-wide admin: no membership in the client at all
143
+ { user: agencyAdmin, org: agency, type: "organization", role: agencyRole, status: "active" },
144
+ { user: staff, type: "admin", role: staffRole, status: "active" },
145
+ ]);
146
+
147
+ return { tower, annex, served: rows.insertedIds[0].toString() };
148
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Who sent an invitation (owner report 2026-09-25: Aigle Security's own
3
+ * invitation was listed in the Seven365 console). The behaviour is proved over
4
+ * HTTP in `test/e2e/org-invite-scope.e2e.test.mjs`; this pins the filter and
5
+ * the wiring that silently rot when a handler is copied.
6
+ */
7
+ import { test } from "node:test";
8
+ import assert from "node:assert/strict";
9
+ import { readFileSync } from "node:fs";
10
+
11
+ import {
12
+ SEVEN365_INVITE_ORIGIN,
13
+ seven365InviteQuery,
14
+ } from "./.build/utils/invite-origin.util.mjs";
15
+
16
+ test("Seven365's list = marked Seven365, or an unmarked invitation naming no organisation", () => {
17
+ assert.equal(SEVEN365_INVITE_ORIGIN, "seven365");
18
+ assert.deepEqual(seven365InviteQuery(), {
19
+ $or: [
20
+ { "metadata.origin": "seven365" },
21
+ { "metadata.origin": { $exists: false }, "metadata.org": { $in: ["", null] } },
22
+ ],
23
+ });
24
+ });
25
+
26
+ const src = (f) => readFileSync(new URL(`../src/${f}`, import.meta.url), "utf8");
27
+
28
+ test("every member/user invite handler records its origin after its reach check", () => {
29
+ const v1 = src("controllers/verification.controller.ts");
30
+ const v2 = src("controllers/verification-v2.controller.ts");
31
+ assert.equal((v1.match(/requireInviteOrigin\(req, org, role\)/g) || []).length, 2);
32
+ assert.equal((v1.match(/requireInviteOrigin\(req, org, role, true\)/g) || []).length, 1);
33
+ assert.equal((v2.match(/requireInviteOrigin\(req, org, role\)/g) || []).length, 1);
34
+ assert.equal((v1.match(/\.\.\.origin/g) || []).length, 3);
35
+ });
36
+
37
+ test("the list endpoint takes origin and gates it to Seven365 staff", () => {
38
+ const v1 = src("controllers/verification.controller.ts");
39
+ assert.match(v1, /origin: Joi\.string\(\)\.valid\(SEVEN365_INVITE_ORIGIN\)/);
40
+ assert.match(v1, /requireVerificationListReach\(req, origin \? null : orgId\)/);
41
+ assert.match(src("repositories/verification.repo.ts"), /seven365InviteQuery\(\)/);
42
+ });