@7365admin1/core 3.113.0 → 3.115.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,250 @@
1
+ // End-to-end proof for Ounitech's Part 1 answers (2026-09-26):
2
+ // - requests go to OUNITECH_API_BASE + the endpoint path (Q1),
3
+ // - sign = sha1("appid=..,timestamp=..,url=<that path>,secret=..") (Q3),
4
+ // verified SERVER-SIDE by a mock that recomputes it,
5
+ // - timestamp is UTC+0 now (Q4),
6
+ // - one AppID/Secret per company (Q2): entered once, discovered robots picked
7
+ // by serial, reused for the client's next robot without re-entry.
8
+ //
9
+ // The "Ounitech cloud" here is a loopback mock with fake credentials. Nothing
10
+ // leaves the machine. Run with: yarn test:e2e
11
+
12
+ import { after, before, describe, it } from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import crypto from "node:crypto";
15
+ import http from "node:http";
16
+ import { once } from "node:events";
17
+ import { ObjectId } from "mongodb";
18
+
19
+ import { startHarness } from "./harness.mjs";
20
+
21
+ const PASSWORD = "Robot-Passw0rd!";
22
+ const MANAGER = "ouc-manager@e2e.example.com";
23
+ const OUTSIDER = "ouc-outsider@e2e.example.com";
24
+ const APPID = "fake-company-appid";
25
+ const SECRET = "fake-company-secret";
26
+ const sha1 = (s) => crypto.createHash("sha1").update(s).digest("hex");
27
+
28
+ /** A stand-in for app.frankfurt.robotcloud.top that checks every signature. */
29
+ async function startMockOunitech() {
30
+ const calls = [];
31
+ const server = http.createServer((req, res) => {
32
+ let raw = "";
33
+ req.on("data", (c) => (raw += c));
34
+ req.on("end", () => {
35
+ const body = raw ? JSON.parse(raw) : {};
36
+ const t = String(body.timestamp ?? "");
37
+ const sent = /^\d{14}$/.test(t)
38
+ ? Date.UTC(+t.slice(0, 4), +t.slice(4, 6) - 1, +t.slice(6, 8), +t.slice(8, 10), +t.slice(10, 12), +t.slice(12, 14))
39
+ : NaN;
40
+ const utcNow = Math.abs(Date.now() - sent) < 30_000;
41
+ const signOk = body.appid === APPID && body.sign === sha1(`appid=${APPID},timestamp=${t},url=${req.url},secret=${SECRET}`);
42
+ calls.push({ path: req.url, signOk, utcNow, leakedSecret: raw.includes(SECRET) });
43
+ res.setHeader("content-type", "application/json");
44
+ if (!signOk || !utcNow) return res.end(JSON.stringify({ ok: false, msg: "sign error" }));
45
+ if (req.url === "/portal/robots/get-robot-list") {
46
+ return res.end(JSON.stringify({
47
+ robotList: [
48
+ { robotSn: "OT-SN-A", robotName: "Lobby Q3", ownerName: "Vendor Owner", ownerPhone: "+6500000000", statusFlag: 1, onlineFlag: true },
49
+ { robotSn: "OT-SN-B", robotName: "Carpark Q3", ownerName: "Vendor Owner", ownerPhone: "+6500000000", statusFlag: 1, onlineFlag: true },
50
+ ],
51
+ }));
52
+ }
53
+ res.end(JSON.stringify({ ok: true }));
54
+ });
55
+ });
56
+ server.listen(0, "127.0.0.1");
57
+ await once(server, "listening");
58
+ return { server, calls, url: `http://127.0.0.1:${server.address().port}/` };
59
+ }
60
+
61
+ describe("Ounitech: base URL, server-verified sign, UTC timestamp, one credential per company", { concurrency: 1 }, () => {
62
+ let h;
63
+ let mock;
64
+ let managerSid;
65
+ let outsiderSid;
66
+ const id = {};
67
+
68
+ before(async () => {
69
+ mock = await startMockOunitech();
70
+ // Read at import by config.ts, so set before the harness loads the package.
71
+ process.env.OUNITECH_API_BASE = mock.url;
72
+ process.env.ROBOT_CREDENTIALS_KEY = crypto.randomBytes(32).toString("hex");
73
+ h = await startHarness();
74
+ Object.assign(id, await seed(h));
75
+ managerSid = await h.login(MANAGER, PASSWORD);
76
+ outsiderSid = await h.login(OUTSIDER, PASSWORD);
77
+ }, { timeout: 300000 });
78
+
79
+ after(async () => {
80
+ delete process.env.OUNITECH_API_BASE;
81
+ delete process.env.ROBOT_CREDENTIALS_KEY;
82
+ if (h) await h.stop();
83
+ mock?.server.close();
84
+ });
85
+
86
+ const robots = () => h.db.collection("robots");
87
+ const lastCall = () => mock.calls[mock.calls.length - 1];
88
+
89
+ it("a wrong secret is refused by the (mock) cloud and reported, not swallowed", async () => {
90
+ const res = await h.api("/robots/discover", {
91
+ method: "POST",
92
+ sid: managerSid,
93
+ body: { site: String(id.siteB), appKey: APPID, appToken: "wrong-secret" },
94
+ });
95
+ assert.equal(res.status, 400, JSON.stringify(res.body));
96
+ assert.match(JSON.stringify(res.body), /sign error/);
97
+ assert.equal(lastCall().signOk, false);
98
+ });
99
+
100
+ it("typed company credentials list the company's robots; request is signed for its own path in UTC", async () => {
101
+ const res = await h.api("/robots/discover", {
102
+ method: "POST",
103
+ sid: managerSid,
104
+ body: { site: String(id.siteB), appKey: APPID, appToken: SECRET },
105
+ });
106
+ assert.equal(res.status, 200, JSON.stringify(res.body));
107
+ assert.deepEqual(res.body.items.map((r) => [r.robotSn, r.name, r.added]), [
108
+ ["OT-SN-A", "Lobby Q3", false],
109
+ ["OT-SN-B", "Carpark Q3", false],
110
+ ]);
111
+ const text = JSON.stringify(res.body);
112
+ for (const s of [APPID, SECRET, "ownerPhone", "Vendor Owner"]) assert.equal(text.includes(s), false, s);
113
+ assert.deepEqual(lastCall(), { path: "/portal/robots/get-robot-list", signOk: true, utcNow: true, leakedSecret: false });
114
+ });
115
+
116
+ it("the first robot is added with typed credentials and a picked serial; stored encrypted", async () => {
117
+ const res = await h.api("/robots", {
118
+ method: "POST",
119
+ sid: managerSid,
120
+ body: { name: "Lobby", brand: "ounitech", type: "cleaning", robotSn: "OT-SN-A", appKey: APPID, appToken: SECRET, metadata: { orgId: String(id.orgB), siteId: String(id.siteB) } },
121
+ });
122
+ assert.equal(res.status, 201, JSON.stringify(res.body));
123
+ const row = await robots().findOne({ name: "Lobby" });
124
+ assert.match(row.appKey, /^rc1:/);
125
+ assert.match(row.appToken, /^rc1:/);
126
+ id.lobby = row;
127
+ });
128
+
129
+ it("discovery with the SAVED credentials needs no re-entry and marks the added serial", async () => {
130
+ const res = await h.api("/robots/discover", { method: "POST", sid: managerSid, body: { site: String(id.siteB2) } });
131
+ assert.equal(res.status, 200, JSON.stringify(res.body));
132
+ assert.deepEqual(res.body.items.map((r) => [r.robotSn, r.added]), [["OT-SN-A", true], ["OT-SN-B", false]]);
133
+ assert.equal(lastCall().signOk, true);
134
+ });
135
+
136
+ it("the next robot reuses the client's saved pair (at another site of the same client)", async () => {
137
+ const noSerial = await h.api("/robots", {
138
+ method: "POST",
139
+ sid: managerSid,
140
+ body: { name: "Carpark", brand: "ounitech", useClientCredentials: true, metadata: { orgId: String(id.orgB), siteId: String(id.siteB2) } },
141
+ });
142
+ assert.equal(noSerial.status, 400, "a company pair covers many robots - the serial must be picked");
143
+
144
+ const res = await h.api("/robots", {
145
+ method: "POST",
146
+ sid: managerSid,
147
+ body: { name: "Carpark", brand: "ounitech", robotSn: "OT-SN-B", useClientCredentials: true, metadata: { orgId: String(id.orgB), siteId: String(id.siteB2) } },
148
+ });
149
+ assert.equal(res.status, 201, JSON.stringify(res.body));
150
+ const row = await robots().findOne({ name: "Carpark" });
151
+ assert.equal(row.appKey, id.lobby.appKey, "copied as stored, still encrypted");
152
+ assert.equal(row.appToken, id.lobby.appToken);
153
+ assert.equal(row.robotSn, "OT-SN-B");
154
+ assert.equal("useClientCredentials" in row, false);
155
+ id.carpark = row._id;
156
+ });
157
+
158
+ it("the reused pair actually signs: a command reaches return-to-base, correctly signed", async () => {
159
+ const res = await h.api(`/robots/${id.carpark}/command`, { method: "POST", sid: managerSid, body: { kind: "return" } });
160
+ assert.ok(res.status < 300, JSON.stringify(res.body));
161
+ const call = mock.calls.find((c) => c.path === "/portal/robots/return-to-base");
162
+ assert.deepEqual(call, { path: "/portal/robots/return-to-base", signOk: true, utcNow: true, leakedSecret: false });
163
+ assert.equal(mock.calls.some((c) => c.leakedSecret), false);
164
+ });
165
+
166
+ it("no GET returns the credentials", async () => {
167
+ for (const path of [`/robots/${id.carpark}`, `/robots/organization/${id.orgB}/site/${id.siteB2}`]) {
168
+ const res = await h.api(path, { sid: managerSid });
169
+ assert.equal(res.status, 200, path);
170
+ const text = JSON.stringify(res.body);
171
+ for (const s of [APPID, SECRET, id.lobby.appKey, id.lobby.appToken, "appToken", "appKey"]) assert.equal(text.includes(s), false, `${path} leaks ${s}`);
172
+ }
173
+ });
174
+
175
+ it("a robot saved the OLD way (per-robot pair, no serial) keeps its pair; Edit picks its serial with no re-entry", async () => {
176
+ const add = await h.api("/robots", {
177
+ method: "POST",
178
+ sid: managerSid,
179
+ body: { name: "Legacy", brand: "ounitech", type: "cleaning", appKey: APPID, appToken: SECRET, metadata: { orgId: String(id.orgB), siteId: String(id.siteB) } },
180
+ });
181
+ assert.equal(add.status, 201, JSON.stringify(add.body));
182
+ const legacy = await robots().findOne({ name: "Legacy" });
183
+ // This company pair covers two robots, so the serial cannot be guessed.
184
+ const before = await h.api(`/robots/${legacy._id}/state`, { sid: managerSid });
185
+ assert.equal(before.status, 400, JSON.stringify(before.body));
186
+ const found = await h.api("/robots/discover", { method: "POST", sid: managerSid, body: { robot: String(legacy._id) } });
187
+ assert.equal(found.status, 200, JSON.stringify(found.body));
188
+ assert.deepEqual(found.body.items.map((r) => r.robotSn), ["OT-SN-A", "OT-SN-B"]);
189
+ const pick = await h.api(`/robots/${legacy._id}`, { method: "PATCH", sid: managerSid, body: { robotSn: "OT-SN-A" } });
190
+ assert.ok(pick.status < 300, JSON.stringify(pick.body));
191
+ const state = await h.api(`/robots/${legacy._id}/state`, { sid: managerSid });
192
+ assert.equal(state.status, 200, JSON.stringify(state.body));
193
+ assert.equal(state.body.robotSn, "OT-SN-A");
194
+ assert.equal(state.body.online, true);
195
+ assert.equal((await robots().findOne({ _id: legacy._id })).appKey, legacy.appKey, "pair untouched");
196
+ assert.equal(lastCall().signOk, true);
197
+ // An outsider cannot use another client's robot to discover.
198
+ const other = await h.api("/robots/discover", { method: "POST", sid: outsiderSid, body: { robot: String(legacy._id) } });
199
+ assert.equal(other.status, 404, JSON.stringify(other.body));
200
+ });
201
+
202
+ it("another client can neither discover with nor borrow this client's pair", async () => {
203
+ const reach = await h.api("/robots/discover", { method: "POST", sid: outsiderSid, body: { site: String(id.siteB) } });
204
+ assert.equal(reach.status, 404, JSON.stringify(reach.body));
205
+ const own = await h.api("/robots/discover", { method: "POST", sid: outsiderSid, body: { site: String(id.siteA) } });
206
+ assert.equal(own.status, 400, "client A has no saved pair - B's is never used");
207
+ const borrow = await h.api("/robots", {
208
+ method: "POST",
209
+ sid: outsiderSid,
210
+ // metadata.orgId naming client B changes nothing: the client is read off the SITE.
211
+ body: { name: "Borrowed", brand: "ounitech", robotSn: "OT-SN-B", useClientCredentials: true, metadata: { orgId: String(id.orgB), siteId: String(id.siteA) } },
212
+ });
213
+ assert.equal(borrow.status, 400, JSON.stringify(borrow.body));
214
+ assert.equal(await robots().countDocuments({ name: "Borrowed" }), 0);
215
+ });
216
+ });
217
+
218
+ async function seed(h) {
219
+ const now = new Date().toISOString();
220
+ const orgA = new ObjectId();
221
+ const orgB = new ObjectId();
222
+ const siteA = new ObjectId();
223
+ const siteB = new ObjectId();
224
+ const siteB2 = new ObjectId();
225
+ const roleA = new ObjectId();
226
+ const roleB = new ObjectId();
227
+ await h.db.collection("organizations").insertMany([
228
+ { _id: orgA, name: "OUC Org A", email: "euca@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now },
229
+ { _id: orgB, name: "OUC Org B", email: "eucb@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now },
230
+ ]);
231
+ await h.db.collection("sites").insertMany([
232
+ { _id: siteA, name: "OUC Site A", org: orgA, orgId: orgA, status: "active" },
233
+ { _id: siteB, name: "OUC Site B", org: orgB, orgId: orgB, status: "active" },
234
+ { _id: siteB2, name: "OUC Site B2", org: orgB, orgId: orgB, status: "active" },
235
+ ]);
236
+ await h.db.collection("roles").insertMany([
237
+ { _id: roleA, name: "Manager A", org: orgA, permissions: ["*"], status: "active" },
238
+ { _id: roleB, name: "Manager B", org: orgB, permissions: ["*"], status: "active" },
239
+ ]);
240
+ const emails = [OUTSIDER, MANAGER];
241
+ const users = await h.db.collection("users").insertMany(emails.map((email) => ({ email, name: email.split("@")[0], status: "active", createdAt: now })));
242
+ const hashed = await h.hashPassword(PASSWORD);
243
+ await h.db.collection("users").updateMany({ email: { $in: emails } }, { $set: { password: hashed } });
244
+ const [outsider, manager] = [0, 1].map((i) => users.insertedIds[i]);
245
+ await h.db.collection("members").insertMany([
246
+ { user: outsider, org: orgA, siteId: siteA, type: "organization", role: roleA, status: "active" },
247
+ { user: manager, org: orgB, type: "organization", role: roleB, status: "active" },
248
+ ]);
249
+ return { orgA, orgB, siteA, siteB, siteB2 };
250
+ }
@@ -0,0 +1,91 @@
1
+ import assert from "node:assert/strict";
2
+ import { createHash } from "node:crypto";
3
+ import http from "node:http";
4
+ import { once } from "node:events";
5
+ import { test } from "node:test";
6
+
7
+ import {
8
+ ROBOT_CLOUD_PATHS,
9
+ robotCloudBody,
10
+ robotCloudTimestamp,
11
+ } from "./.build/utils/robot-cloud.util.mjs";
12
+ import { OUNITECH_DEFAULT_API_BASE, ROBOT_CLOUD_BASE_URL } from "./.build/config.mjs";
13
+ import { createOunitechAdapter } from "./.build/services/ounitech.adapter.mjs";
14
+
15
+ /* --------------------------------------------------------------------------
16
+ * Ounitech's answers, Part 1 (2026-09-26):
17
+ * Q1 base URL https://app.frankfurt.robotcloud.top
18
+ * Q3 sign sha1("appid=..,timestamp=..,url=..,secret=..") with url = THAT
19
+ * endpoint's path; the document's example values are wrong
20
+ * Q4 timestamp UTC+0 (format yyyyMMddHHmmss from the document)
21
+ * Fake credentials only - nothing here reaches Ounitech.
22
+ * ----------------------------------------------------------------------- */
23
+
24
+ const APPID = "test-appid";
25
+ const SECRET = "test-secret";
26
+ // 09:30:05 in Singapore = 01:30:05 UTC. A local-time bug would print 0930.
27
+ const CLOCK = new Date("2026-09-26T09:30:05+08:00");
28
+ const sha1 = (s) => createHash("sha1").update(s).digest("hex");
29
+
30
+ test("the default base URL is the one Ounitech gave (Part 1, Q1)", () => {
31
+ assert.equal(OUNITECH_DEFAULT_API_BASE, "https://app.frankfurt.robotcloud.top");
32
+ if (!process.env.OUNITECH_API_BASE && !process.env.ROBOT_CLOUD_BASE_URL) {
33
+ assert.equal(ROBOT_CLOUD_BASE_URL, OUNITECH_DEFAULT_API_BASE);
34
+ }
35
+ });
36
+
37
+ test("timestamp is UTC+0, not the server's local time (Part 1, Q4)", () => {
38
+ assert.equal(robotCloudTimestamp(CLOCK), "20260926013005");
39
+ });
40
+
41
+ for (const [name, path] of Object.entries(ROBOT_CLOUD_PATHS)) {
42
+ test(`sign for ${name} hashes exactly its own path ${path}`, () => {
43
+ const body = robotCloudBody(APPID, SECRET, path, { robotSn: "SN1" }, CLOCK);
44
+ const expected = sha1(`appid=${APPID},timestamp=20260926013005,url=${path},secret=${SECRET}`);
45
+ assert.equal(body.timestamp, "20260926013005");
46
+ assert.equal(body.sign, expected);
47
+ assert.equal(body.appid, APPID);
48
+ assert.equal(JSON.stringify(body).includes(SECRET), false);
49
+ });
50
+ }
51
+
52
+ test("every endpoint has a different sign at the same instant (Part 1, Q3)", () => {
53
+ const signs = Object.values(ROBOT_CLOUD_PATHS).map((p) => robotCloudBody(APPID, SECRET, p, {}, CLOCK).sign);
54
+ assert.equal(new Set(signs).size, signs.length);
55
+ });
56
+
57
+ test("the adapter posts to base + path, signed for that path, stamped in UTC now", async () => {
58
+ const seen = [];
59
+ const server = http.createServer((req, res) => {
60
+ let raw = "";
61
+ req.on("data", (c) => (raw += c));
62
+ req.on("end", () => {
63
+ const body = JSON.parse(raw);
64
+ seen.push({ url: req.url, body });
65
+ res.setHeader("content-type", "application/json");
66
+ if (req.url === ROBOT_CLOUD_PATHS.robotList) {
67
+ res.end(JSON.stringify({ robotList: [{ robotSn: "SN1", robotName: "Lobby", onlineFlag: true, statusFlag: 1 }] }));
68
+ } else res.end(JSON.stringify({ ok: true }));
69
+ });
70
+ });
71
+ server.listen(0, "127.0.0.1");
72
+ await once(server, "listening");
73
+ try {
74
+ const base = `http://127.0.0.1:${server.address().port}/`;
75
+ const adapter = createOunitechAdapter({ appid: APPID, secret: SECRET }, { baseUrl: base });
76
+ const robots = await adapter.listRobots();
77
+ await adapter.sendCommand("SN1", { kind: "return" });
78
+ assert.deepEqual(robots.map((r) => r.robotSn), ["SN1"]);
79
+ assert.deepEqual(seen.map((s) => s.url), [ROBOT_CLOUD_PATHS.robotList, ROBOT_CLOUD_PATHS.returnToBase]);
80
+ for (const { url, body } of seen) {
81
+ assert.equal(body.sign, sha1(`appid=${APPID},timestamp=${body.timestamp},url=${url},secret=${SECRET}`));
82
+ assert.equal(JSON.stringify(body).includes(SECRET), false);
83
+ assert.match(body.timestamp, /^\d{14}$/);
84
+ const t = body.timestamp;
85
+ const sent = Date.UTC(+t.slice(0, 4), +t.slice(4, 6) - 1, +t.slice(6, 8), +t.slice(8, 10), +t.slice(10, 12), +t.slice(12, 14));
86
+ assert.ok(Math.abs(Date.now() - sent) < 10_000, `timestamp ${t} is not UTC now`);
87
+ }
88
+ } finally {
89
+ server.close();
90
+ }
91
+ });