@tallyui/core 3.17.0 → 3.19.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/dist/{chunk-CSXNXRBA.js → chunk-27L7XLTT.js} +48 -0
- package/dist/command-result-BZd1YFMP.d.ts +1956 -0
- package/dist/index.d.ts +51 -1085
- package/dist/index.js +145 -9
- package/dist/server/index.d.ts +46 -5
- package/dist/server/index.js +594 -114
- package/package.json +1 -1
- package/src/customer-display/advertisement.ts +57 -0
- package/src/customer-display/index.ts +2 -0
- package/src/customer-display/rate-limit-source.ts +40 -0
- package/src/index.ts +13 -2
- package/src/order-filters.ts +58 -0
- package/src/server/batch.ts +4 -0
- package/src/server/display-signalling/contract.ts +254 -0
- package/src/server/display-signalling/index.ts +3 -0
- package/src/server/display-signalling/memory-server.ts +250 -0
- package/src/server/index.ts +2 -0
- package/src/server/order-payload-shape.ts +25 -1
- package/src/server/versions.ts +2 -2
- package/src/tax/woocommerce/index.ts +2 -0
- package/src/tax/woocommerce/tax-location.ts +59 -0
- package/src/types/commands.ts +27 -4
- package/src/types/connector.ts +41 -7
- package/src/types/customers.ts +9 -0
- package/src/types/display-signalling.ts +123 -0
- package/src/types/index.ts +6 -1
- package/src/types/orders.ts +23 -0
- package/src/types/receipt-templates.ts +26 -0
- package/src/types/store-settings.ts +42 -1
- package/dist/command-result-CoCa8PXJ.d.ts +0 -544
package/dist/server/index.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CommandResultError,
|
|
3
|
+
DISPLAY_PAIR_CAPABILITY,
|
|
4
|
+
DisplaySignallingError,
|
|
3
5
|
MAX_COMMANDS_PER_BATCH,
|
|
4
6
|
ORDER_NOTE_MAX,
|
|
5
|
-
parseCommandResult
|
|
6
|
-
|
|
7
|
+
parseCommandResult,
|
|
8
|
+
rateLimitSource
|
|
9
|
+
} from "../chunk-27L7XLTT.js";
|
|
7
10
|
import "../chunk-MLKGABMK.js";
|
|
8
11
|
|
|
9
12
|
// src/server/money.ts
|
|
@@ -54,39 +57,39 @@ function commandFingerprint(envelope) {
|
|
|
54
57
|
function payloadShapeErrors(payload) {
|
|
55
58
|
const errors = [];
|
|
56
59
|
const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
57
|
-
const
|
|
60
|
+
const check2 = (valid, path, expected) => {
|
|
58
61
|
if (!valid && errors.length < 10) errors.push(`${path}: expected ${expected}`);
|
|
59
62
|
};
|
|
60
|
-
const number = (value, path) =>
|
|
63
|
+
const number = (value, path) => check2(typeof value === "number" && Number.isFinite(value), path, "a finite number");
|
|
61
64
|
const discount = (value, path) => {
|
|
62
65
|
const valid = value === void 0 || Number.isSafeInteger(value) && value > 0;
|
|
63
|
-
|
|
66
|
+
check2(valid, path, "a positive safe integer");
|
|
64
67
|
return valid && value !== void 0 ? BigInt(value) : 0n;
|
|
65
68
|
};
|
|
66
69
|
if (!object(payload)) return ["payload: expected an object"];
|
|
67
|
-
|
|
68
|
-
for (const field of ["createdAt", "currency"])
|
|
69
|
-
|
|
70
|
+
check2(typeof payload.clientOrderId === "string" && payload.clientOrderId.length > 0, "clientOrderId", "a non-empty string");
|
|
71
|
+
for (const field of ["createdAt", "currency"]) check2(typeof payload[field] === "string", field, "a string");
|
|
72
|
+
check2(typeof payload.pricesIncludeTax === "boolean", "pricesIncludeTax", "a boolean");
|
|
70
73
|
for (const field of ["lines", "payments"]) {
|
|
71
74
|
const items = payload[field];
|
|
72
75
|
const isLines = field === "lines";
|
|
73
|
-
|
|
76
|
+
check2(Array.isArray(items) && (!isLines || items.length > 0), field, isLines ? "a non-empty array" : "an array");
|
|
74
77
|
if (!Array.isArray(items)) continue;
|
|
75
78
|
for (const [index, item] of items.entries()) {
|
|
76
79
|
if (errors.length === 10) break;
|
|
77
80
|
const path = `${field}[${index}]`;
|
|
78
|
-
|
|
81
|
+
check2(object(item), path, "an object");
|
|
79
82
|
if (!object(item)) continue;
|
|
80
83
|
for (const key of isLines ? ["clientLineId", "variantId"] : ["clientPaymentId", "method"]) {
|
|
81
84
|
if (key === "variantId" && item.custom !== void 0 && item.variantId === void 0) continue;
|
|
82
|
-
|
|
85
|
+
check2(typeof item[key] === "string", `${path}.${key}`, "a string");
|
|
83
86
|
}
|
|
84
87
|
const optionalString = isLines ? "title" : "reference";
|
|
85
88
|
if (item[optionalString] !== void 0) {
|
|
86
|
-
|
|
89
|
+
check2(typeof item[optionalString] === "string", `${path}.${optionalString}`, "a string");
|
|
87
90
|
}
|
|
88
91
|
if (isLines && item.taxInclusive !== void 0) {
|
|
89
|
-
|
|
92
|
+
check2(typeof item.taxInclusive === "boolean", `${path}.taxInclusive`, "a boolean");
|
|
90
93
|
}
|
|
91
94
|
for (const key of isLines ? ["quantity", "unitPriceMinor"] : ["amountMinor"]) number(item[key], `${path}.${key}`);
|
|
92
95
|
if (!isLines) {
|
|
@@ -99,32 +102,48 @@ function payloadShapeErrors(payload) {
|
|
|
99
102
|
for (const field of ["subtotalMinor", "taxMinor", "totalMinor"]) number(payload[field], field);
|
|
100
103
|
const lineDiscounts = (Array.isArray(payload.lines) ? payload.lines : []).reduce((sum, line, index) => sum + (object(line) ? discount(line.discountMinor, `lines[${index}].discountMinor`) : 0n), 0n);
|
|
101
104
|
const orderDiscount = discount(payload.discountMinor, "discountMinor");
|
|
102
|
-
if (errors.length === 0)
|
|
105
|
+
if (errors.length === 0) check2(orderDiscount === lineDiscounts, "discountMinor", "the sum of lines[].discountMinor");
|
|
103
106
|
if (payload.customer !== void 0 && payload.customer !== null) {
|
|
104
|
-
|
|
107
|
+
check2(object(payload.customer), "customer", "an object");
|
|
105
108
|
if (object(payload.customer) && payload.customer.email !== void 0) {
|
|
106
|
-
|
|
109
|
+
check2(typeof payload.customer.email === "string", "customer.email", "a string");
|
|
107
110
|
}
|
|
108
111
|
if (object(payload.customer) && payload.customer.customerId !== void 0) {
|
|
109
112
|
const id = payload.customer.customerId;
|
|
110
|
-
|
|
113
|
+
check2(typeof id === "string" && id.length > 0 && id.length <= 64, "customer.customerId", "a string of at most 64 characters");
|
|
114
|
+
}
|
|
115
|
+
for (const kind of ["billing", "shipping"]) {
|
|
116
|
+
const address = object(payload.customer) ? payload.customer[kind] : void 0;
|
|
117
|
+
if (address === void 0) continue;
|
|
118
|
+
check2(object(address), `customer.${kind}`, "an object");
|
|
119
|
+
if (object(address)) for (const [key, value] of Object.entries(address)) {
|
|
120
|
+
check2(ORDER_ADDRESS_KEYS.includes(key), `customer.${kind}.${key}`, "no unknown key");
|
|
121
|
+
check2(typeof value === "string", `customer.${kind}.${key}`, "a string");
|
|
122
|
+
}
|
|
111
123
|
}
|
|
112
124
|
}
|
|
125
|
+
if (payload.taxAddress !== void 0) {
|
|
126
|
+
const kind = payload.taxAddress;
|
|
127
|
+
const known = kind === "billing" || kind === "shipping";
|
|
128
|
+
check2(known, "taxAddress", "billing or shipping");
|
|
129
|
+
const address = known && object(payload.customer) ? payload.customer[kind] : void 0;
|
|
130
|
+
if (known) check2(object(address) && typeof address.country === "string" && address.country.length > 0, `customer.${kind}.country`, "a non-empty string");
|
|
131
|
+
}
|
|
113
132
|
if (payload.sessionId !== void 0) {
|
|
114
|
-
|
|
133
|
+
check2(
|
|
115
134
|
typeof payload.sessionId === "string" && payload.sessionId.length > 0 && payload.sessionId.length <= 36,
|
|
116
135
|
"sessionId",
|
|
117
136
|
"a string of at most 36 characters"
|
|
118
137
|
);
|
|
119
138
|
}
|
|
120
139
|
for (const field of ["registerId", "cashierRef", "locationId"]) {
|
|
121
|
-
if (payload[field] !== void 0)
|
|
140
|
+
if (payload[field] !== void 0) check2(typeof payload[field] === "string", field, "a string");
|
|
122
141
|
}
|
|
123
|
-
if (payload.note !== void 0)
|
|
142
|
+
if (payload.note !== void 0) check2(typeof payload.note === "string" && payload.note.length > 0, "note", "a non-empty string");
|
|
124
143
|
for (const field of ["fees", "shipping", "lines"]) {
|
|
125
144
|
const items = payload[field];
|
|
126
145
|
if (items === void 0 || field === "lines" && !Array.isArray(items)) continue;
|
|
127
|
-
|
|
146
|
+
check2(Array.isArray(items), field, "an array");
|
|
128
147
|
if (!Array.isArray(items)) continue;
|
|
129
148
|
const id = field === "fees" ? "clientFeeId" : "clientShippingId";
|
|
130
149
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -133,20 +152,20 @@ function payloadShapeErrors(payload) {
|
|
|
133
152
|
const item = custom && object(entry) ? entry.custom : entry;
|
|
134
153
|
const path = `${field}[${index}]${custom ? ".custom" : ""}`;
|
|
135
154
|
if (custom && (!object(entry) || item === void 0)) return;
|
|
136
|
-
|
|
155
|
+
check2(object(item), path, "an object");
|
|
137
156
|
if (!object(item)) return;
|
|
138
157
|
const keys = custom ? ["name", "sku", "taxClass", "taxStatus"] : [id, "name", "amountMinor", "taxMinor", "taxStatus", "taxClass", ...field === "shipping" ? ["methodId"] : []];
|
|
139
|
-
for (const key of Object.keys(item))
|
|
140
|
-
|
|
141
|
-
|
|
158
|
+
for (const key of Object.keys(item)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
|
|
159
|
+
check2(typeof item.name === "string" && item.name.length > 0, `${path}.name`, "a non-empty string");
|
|
160
|
+
check2(item.taxStatus === "taxable" || item.taxStatus === "none", `${path}.taxStatus`, "taxable or none");
|
|
142
161
|
for (const key of keys.filter((key2) => ["sku", "taxClass", "methodId"].includes(key2))) {
|
|
143
|
-
if (item[key] !== void 0)
|
|
162
|
+
if (item[key] !== void 0) check2(typeof item[key] === "string", `${path}.${key}`, "a string");
|
|
144
163
|
}
|
|
145
164
|
if (!custom) {
|
|
146
|
-
|
|
147
|
-
|
|
165
|
+
check2(typeof item[id] === "string" && item[id].length > 0, `${path}.${id}`, "a non-empty string");
|
|
166
|
+
check2(!seen.has(item[id]), `${path}.${id}`, `no duplicate ${id}`);
|
|
148
167
|
seen.add(item[id]);
|
|
149
|
-
for (const key of ["amountMinor", "taxMinor"])
|
|
168
|
+
for (const key of ["amountMinor", "taxMinor"]) check2(Number.isSafeInteger(item[key]) && item[key] >= 0, `${path}.${key}`, "a safe integer >= 0");
|
|
150
169
|
}
|
|
151
170
|
});
|
|
152
171
|
}
|
|
@@ -154,19 +173,19 @@ function payloadShapeErrors(payload) {
|
|
|
154
173
|
const parent = prefix ? payload.display : payload;
|
|
155
174
|
const items = object(parent) ? parent.coupons : void 0;
|
|
156
175
|
if (items === void 0) continue;
|
|
157
|
-
|
|
176
|
+
check2(Array.isArray(items), `${prefix}coupons`, "an array");
|
|
158
177
|
if (!Array.isArray(items)) continue;
|
|
159
178
|
const keys = prefix ? ["code", "amountMinor"] : ["code", "couponId", "discountMinor", "discountTaxMinor"];
|
|
160
179
|
const seen = /* @__PURE__ */ new Set();
|
|
161
180
|
items.forEach((item, index) => {
|
|
162
181
|
const path = `${prefix}coupons[${index}]`;
|
|
163
|
-
|
|
182
|
+
check2(object(item), path, "an object");
|
|
164
183
|
if (!object(item)) return;
|
|
165
|
-
for (const key of Object.keys(item))
|
|
166
|
-
for (const key of prefix ? ["code"] : ["code", "couponId"])
|
|
167
|
-
for (const key of prefix ? ["amountMinor"] : ["discountMinor", "discountTaxMinor"])
|
|
184
|
+
for (const key of Object.keys(item)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
|
|
185
|
+
for (const key of prefix ? ["code"] : ["code", "couponId"]) check2(typeof item[key] === "string" && item[key].length > 0, `${path}.${key}`, "a non-empty string");
|
|
186
|
+
for (const key of prefix ? ["amountMinor"] : ["discountMinor", "discountTaxMinor"]) check2(Number.isSafeInteger(item[key]) && item[key] >= 0, `${path}.${key}`, "a safe integer >= 0");
|
|
168
187
|
if (!prefix) {
|
|
169
|
-
|
|
188
|
+
check2(!seen.has(item.code), `${path}.code`, "no duplicate code");
|
|
170
189
|
seen.add(item.code);
|
|
171
190
|
}
|
|
172
191
|
});
|
|
@@ -174,28 +193,29 @@ function payloadShapeErrors(payload) {
|
|
|
174
193
|
if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
|
|
175
194
|
if (!object(line)) return;
|
|
176
195
|
const path = `lines[${index}]`;
|
|
177
|
-
if (line.regularUnitPriceMinor !== void 0)
|
|
196
|
+
if (line.regularUnitPriceMinor !== void 0) check2(Number.isSafeInteger(line.regularUnitPriceMinor) && line.regularUnitPriceMinor >= 0, `${path}.regularUnitPriceMinor`, "a safe integer >= 0");
|
|
178
197
|
if (line.attributes !== void 0) {
|
|
179
|
-
|
|
180
|
-
if (object(line.attributes)) for (const [key, value] of Object.entries(line.attributes))
|
|
198
|
+
check2(object(line.attributes), `${path}.attributes`, "an object");
|
|
199
|
+
if (object(line.attributes)) for (const [key, value] of Object.entries(line.attributes)) check2(typeof value === "string", `${path}.attributes.${key}`, "a string");
|
|
181
200
|
}
|
|
182
201
|
const { anyAttributes: names, attributes } = line;
|
|
183
|
-
if (names !== void 0)
|
|
202
|
+
if (names !== void 0) check2(Array.isArray(names), `${path}.anyAttributes`, "an array");
|
|
184
203
|
if (Array.isArray(names)) names.forEach((name, index2) => {
|
|
185
204
|
const at = `${path}.anyAttributes[${index2}]`;
|
|
186
|
-
|
|
205
|
+
check2(typeof name === "string" && name.length > 0, at, "a non-empty string");
|
|
187
206
|
if (typeof name !== "string" || !name) return;
|
|
188
|
-
|
|
189
|
-
|
|
207
|
+
check2(names.indexOf(name) === index2, at, "no duplicate name");
|
|
208
|
+
check2(
|
|
190
209
|
object(attributes) && Object.hasOwn(attributes, name) && typeof attributes[name] === "string" && attributes[name].length > 0,
|
|
191
210
|
at,
|
|
192
211
|
`a key of ${path}.attributes with a non-empty value`
|
|
193
212
|
);
|
|
194
213
|
});
|
|
195
214
|
});
|
|
196
|
-
for (const [value, path] of payloadStrings(payload))
|
|
215
|
+
for (const [value, path] of payloadStrings(payload)) check2(!value.includes("\0"), path, "no NUL character");
|
|
197
216
|
return errors;
|
|
198
217
|
}
|
|
218
|
+
var ORDER_ADDRESS_KEYS = ["firstName", "lastName", "company", "address1", "address2", "city", "state", "postcode", "country", "phone"];
|
|
199
219
|
function payloadBoundErrors(payload) {
|
|
200
220
|
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return [];
|
|
201
221
|
return payloadStrings(payload).filter(([value, , max]) => max !== void 0 && value.length > max).map(([, path, max]) => `${path}: expected at most ${max} characters`).slice(0, 10);
|
|
@@ -241,6 +261,10 @@ function payloadStrings(payload) {
|
|
|
241
261
|
if (object(line) && Array.isArray(line.anyAttributes)) line.anyAttributes.forEach((name, i) => found.push([name, `lines[${index}].anyAttributes[${i}]`, 255]));
|
|
242
262
|
});
|
|
243
263
|
if (object(payload.customer)) found.push([payload.customer.email, "customer.email", 254], [payload.customer.customerId, "customer.customerId", void 0]);
|
|
264
|
+
if (object(payload.customer)) for (const kind of ["billing", "shipping"]) {
|
|
265
|
+
const address = payload.customer[kind];
|
|
266
|
+
if (object(address)) for (const [key, value] of Object.entries(address)) found.push([value, `customer.${kind}.${key}`, 255]);
|
|
267
|
+
}
|
|
244
268
|
found.push([payload.sessionId, "sessionId", void 0]);
|
|
245
269
|
return found.filter((entry) => typeof entry[0] === "string");
|
|
246
270
|
}
|
|
@@ -248,40 +272,40 @@ function payloadStrings(payload) {
|
|
|
248
272
|
// src/server/fiscal-figures.ts
|
|
249
273
|
function fiscalFiguresErrors(payload) {
|
|
250
274
|
const errors = [];
|
|
251
|
-
const
|
|
275
|
+
const check2 = (valid, path, expected) => {
|
|
252
276
|
if (!valid && errors.length < 10) errors.push(`${path}: expected ${expected}`);
|
|
253
277
|
};
|
|
254
278
|
const object = (value, path, keys) => {
|
|
255
279
|
const valid = typeof value === "object" && value !== null && !Array.isArray(value);
|
|
256
|
-
|
|
257
|
-
if (valid) for (const key of Object.keys(value))
|
|
280
|
+
check2(valid, path, "an object");
|
|
281
|
+
if (valid) for (const key of Object.keys(value)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
|
|
258
282
|
return valid;
|
|
259
283
|
};
|
|
260
284
|
const money = (value, path, keys) => {
|
|
261
|
-
for (const key of keys)
|
|
285
|
+
for (const key of keys) check2(Number.isSafeInteger(value[key]), `${path}.${key}`, "a safe integer");
|
|
262
286
|
};
|
|
263
287
|
const { display, taxByRate } = payload;
|
|
264
288
|
if (object(display, "display", ["currency", "exponent", "taxInclusive", "subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor", "lines", "fees", "shipping", "coupons"])) {
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
289
|
+
check2(typeof display.currency === "string", "display.currency", "a string");
|
|
290
|
+
check2(Number.isInteger(display.exponent) && display.exponent >= 0, "display.exponent", "an integer >= 0");
|
|
291
|
+
check2(typeof display.taxInclusive === "boolean", "display.taxInclusive", "a boolean");
|
|
268
292
|
money(display, "display", ["subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor"]);
|
|
269
|
-
|
|
293
|
+
check2(Array.isArray(display.lines), "display.lines", "an array");
|
|
270
294
|
if (Array.isArray(display.lines)) display.lines.forEach((line, index) => {
|
|
271
295
|
const path = `display.lines[${index}]`;
|
|
272
296
|
if (!object(line, path, ["clientLineId", "amountMinor", "discounts"])) return;
|
|
273
|
-
|
|
297
|
+
check2(typeof line.clientLineId === "string", `${path}.clientLineId`, "a string");
|
|
274
298
|
money(line, path, ["amountMinor"]);
|
|
275
|
-
|
|
299
|
+
check2(Array.isArray(line.discounts), `${path}.discounts`, "an array");
|
|
276
300
|
if (Array.isArray(line.discounts)) line.discounts.forEach((discount, index2) => {
|
|
277
301
|
const discountPath = `${path}.discounts[${index2}]`;
|
|
278
302
|
if (!object(discount, discountPath, ["discountId", "label", "amountMinor"])) return;
|
|
279
|
-
|
|
280
|
-
if (discount.label !== void 0)
|
|
303
|
+
check2(typeof discount.discountId === "string", `${discountPath}.discountId`, "a string");
|
|
304
|
+
if (discount.label !== void 0) check2(typeof discount.label === "string", `${discountPath}.label`, "a string");
|
|
281
305
|
money(discount, discountPath, ["amountMinor"]);
|
|
282
306
|
});
|
|
283
307
|
});
|
|
284
|
-
if (payload.fees?.length || payload.shipping?.length)
|
|
308
|
+
if (payload.fees?.length || payload.shipping?.length) check2(display.taxInclusive === payload.pricesIncludeTax, "display.taxInclusive", "payload.pricesIncludeTax");
|
|
285
309
|
for (const field of ["fees", "shipping"]) {
|
|
286
310
|
const id = field === "fees" ? "clientFeeId" : "clientShippingId";
|
|
287
311
|
const amounts = new Map((payload[field] ?? []).map((entry) => [
|
|
@@ -289,59 +313,59 @@ function fiscalFiguresErrors(payload) {
|
|
|
289
313
|
entry.amountMinor
|
|
290
314
|
]));
|
|
291
315
|
const rows = display[field];
|
|
292
|
-
if (rows !== void 0)
|
|
316
|
+
if (rows !== void 0) check2(Array.isArray(rows), `display.${field}`, "an array");
|
|
293
317
|
const seen3 = /* @__PURE__ */ new Set();
|
|
294
318
|
if (Array.isArray(rows)) rows.forEach((row, index) => {
|
|
295
319
|
const path = `display.${field}[${index}]`;
|
|
296
320
|
if (!object(row, path, [id, "amountMinor"])) return;
|
|
297
|
-
|
|
321
|
+
check2(typeof row[id] === "string" && row[id].length > 0, `${path}.${id}`, "a non-empty string");
|
|
298
322
|
money(row, path, ["amountMinor"]);
|
|
299
|
-
|
|
300
|
-
|
|
323
|
+
check2(amounts.has(row[id]), `${path}.${id}`, `a payload.${field}[].${id}`);
|
|
324
|
+
check2(!seen3.has(row[id]), `${path}.${id}`, `no duplicate ${id}`);
|
|
301
325
|
seen3.add(row[id]);
|
|
302
|
-
if (amounts.has(row[id]))
|
|
326
|
+
if (amounts.has(row[id])) check2(row.amountMinor === amounts.get(row[id]), `${path}.amountMinor`, `the payload.${field} amountMinor`);
|
|
303
327
|
});
|
|
304
|
-
for (const key of amounts.keys())
|
|
328
|
+
for (const key of amounts.keys()) check2(seen3.has(key), `display.${field}`, `a row for ${id} ${key}`);
|
|
305
329
|
}
|
|
306
330
|
const codes = new Set((payload.coupons ?? []).map((coupon) => coupon.code));
|
|
307
331
|
const seen2 = /* @__PURE__ */ new Set();
|
|
308
332
|
if (Array.isArray(display.coupons)) display.coupons.forEach((row, index) => {
|
|
309
333
|
const path = `display.coupons[${index}]`;
|
|
310
|
-
|
|
311
|
-
|
|
334
|
+
check2(codes.has(row.code), `${path}.code`, "a payload.coupons[].code");
|
|
335
|
+
check2(!seen2.has(row.code), `${path}.code`, "no duplicate code");
|
|
312
336
|
seen2.add(row.code);
|
|
313
337
|
});
|
|
314
338
|
}
|
|
315
|
-
|
|
339
|
+
check2(Array.isArray(taxByRate), "taxByRate", "an array");
|
|
316
340
|
if (Array.isArray(taxByRate)) taxByRate.forEach((rate, index) => {
|
|
317
341
|
const path = `taxByRate[${index}]`;
|
|
318
342
|
if (!object(rate, path, ["ratePpm", "code", "netMinor", "taxMinor", "grossMinor"])) return;
|
|
319
|
-
|
|
320
|
-
if (rate.code !== void 0)
|
|
343
|
+
check2(Number.isInteger(rate.ratePpm), `${path}.ratePpm`, "an integer");
|
|
344
|
+
if (rate.code !== void 0) check2(typeof rate.code === "string", `${path}.code`, "a string");
|
|
321
345
|
money(rate, path, ["netMinor", "taxMinor", "grossMinor"]);
|
|
322
346
|
});
|
|
323
347
|
if (errors.length || !display || !Array.isArray(taxByRate)) return errors;
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
taxByRate.forEach((rate, index) =>
|
|
348
|
+
check2(display.currency === payload.currency, "display.currency", "payload.currency");
|
|
349
|
+
check2(display.totalMinor === payload.totalMinor, "display.totalMinor", "payload.totalMinor");
|
|
350
|
+
check2(display.taxMinor === payload.taxMinor, "display.taxMinor", "payload.taxMinor");
|
|
351
|
+
check2(taxByRate.length > 0 || payload.taxMinor === 0, "taxByRate", "a non-empty array when payload.taxMinor is nonzero");
|
|
352
|
+
check2(Number.isSafeInteger(payload.taxMinor) && taxByRate.reduce((sum, rate) => sum + BigInt(rate.taxMinor), 0n) === BigInt(payload.taxMinor), "taxByRate", "the sum of taxMinor to equal payload.taxMinor");
|
|
353
|
+
taxByRate.forEach((rate, index) => check2(BigInt(rate.grossMinor) === BigInt(rate.netMinor) + BigInt(rate.taxMinor), `taxByRate[${index}].grossMinor`, "netMinor + taxMinor"));
|
|
330
354
|
const ids = new Set(Array.isArray(payload.lines) ? payload.lines.map((line) => line?.clientLineId) : []);
|
|
331
355
|
const seen = /* @__PURE__ */ new Set();
|
|
332
356
|
display.lines.forEach((line, index) => {
|
|
333
|
-
|
|
334
|
-
|
|
357
|
+
check2(ids.has(line.clientLineId), `display.lines[${index}].clientLineId`, "a payload.lines[].clientLineId");
|
|
358
|
+
check2(!seen.has(line.clientLineId), `display.lines[${index}].clientLineId`, "no duplicate clientLineId");
|
|
335
359
|
seen.add(line.clientLineId);
|
|
336
360
|
});
|
|
337
361
|
try {
|
|
338
|
-
|
|
362
|
+
check2(display.exponent === currencyDecimals(payload.currency), "display.exponent", "the currency decimals");
|
|
339
363
|
} catch {
|
|
340
364
|
}
|
|
341
365
|
const text = (value, path) => {
|
|
342
366
|
if (typeof value !== "string") return;
|
|
343
|
-
|
|
344
|
-
|
|
367
|
+
check2(value.length <= 255, path, "at most 255 characters");
|
|
368
|
+
check2(!value.includes("\0"), path, "no NUL character");
|
|
345
369
|
};
|
|
346
370
|
display.lines.forEach((line, index) => line.discounts.forEach((discount, i) => {
|
|
347
371
|
for (const key of ["discountId", "label"]) text(discount[key], `display.lines[${index}].discounts[${i}].${key}`);
|
|
@@ -351,7 +375,7 @@ function fiscalFiguresErrors(payload) {
|
|
|
351
375
|
}
|
|
352
376
|
|
|
353
377
|
// src/server/versions.ts
|
|
354
|
-
var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4, 5, 6, 7];
|
|
378
|
+
var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4, 5, 6, 7, 8];
|
|
355
379
|
var SUPPORTED_REGISTER_VERSIONS = [1];
|
|
356
380
|
var SUPPORTED_ORDER_REFUND_VERSIONS = [1];
|
|
357
381
|
|
|
@@ -441,7 +465,7 @@ function precheckCommand(envelope, supported) {
|
|
|
441
465
|
if (line?.[field] !== void 0) v6Fields.push(`lines[${index}].${field}`);
|
|
442
466
|
}
|
|
443
467
|
});
|
|
444
|
-
let versionError = command.version < 5 && v5Fields.length ? v5Fields.map((field) => `${field} requires version 5`).join("; ") : command.version < 6 && v6Fields.length ? v6Fields.map((field) => `${field} requires version 6`).join("; ") : command.version < 7 && payload.note !== void 0 ? "note requires version 7" : command.version === 2 && discountMinor === void 0 ? "version 2 requires discountMinor" : command.version === 1 && discounted ? "discountMinor requires version 2" : !v3 && (display !== void 0 || taxByRate !== void 0) ? "display and taxByRate require version 3" : !v3 && sessionId !== void 0 ? "sessionId requires version 3" : !v3 && payload.customer?.customerId !== void 0 ? "customerId requires version 3" : v3 && display !== void 0 !== (taxByRate !== void 0) ? "display and taxByRate must both be present or both absent" : void 0;
|
|
468
|
+
let versionError = command.version < 5 && v5Fields.length ? v5Fields.map((field) => `${field} requires version 5`).join("; ") : command.version < 6 && v6Fields.length ? v6Fields.map((field) => `${field} requires version 6`).join("; ") : command.version < 7 && payload.note !== void 0 ? "note requires version 7" : command.version < 8 && payload.taxAddress !== void 0 ? "taxAddress requires version 8" : command.version < 8 && (payload.customer?.billing !== void 0 || payload.customer?.shipping !== void 0) ? "customer address requires version 8" : command.version >= 8 && payload.taxAddress === void 0 ? "version 8 requires taxAddress" : command.version === 2 && discountMinor === void 0 ? "version 2 requires discountMinor" : command.version === 1 && discounted ? "discountMinor requires version 2" : !v3 && (display !== void 0 || taxByRate !== void 0) ? "display and taxByRate require version 3" : !v3 && sessionId !== void 0 ? "sessionId requires version 3" : !v3 && payload.customer?.customerId !== void 0 ? "customerId requires version 3" : v3 && display !== void 0 !== (taxByRate !== void 0) ? "display and taxByRate must both be present or both absent" : void 0;
|
|
445
469
|
if (!versionError && Array.isArray(lines)) for (const [index, line] of lines.entries()) {
|
|
446
470
|
if (line?.custom === void 0 && (typeof line?.variantId !== "string" || !line.variantId.length)) {
|
|
447
471
|
versionError = `lines[${index}].variantId is required`;
|
|
@@ -482,29 +506,29 @@ function totalWarnings(expectedMinor, serverMinor) {
|
|
|
482
506
|
function registerPayloadErrors(type, payload) {
|
|
483
507
|
const errors = [];
|
|
484
508
|
const object = (value) => typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
485
|
-
const
|
|
509
|
+
const check2 = (valid, field, expected) => {
|
|
486
510
|
if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`);
|
|
487
511
|
};
|
|
488
512
|
if (!object(payload)) return ["payload: expected an object"];
|
|
489
513
|
const noNul = (value, field) => {
|
|
490
|
-
if (typeof value === "string")
|
|
514
|
+
if (typeof value === "string") check2(!value.includes("\0"), field, "no NUL character");
|
|
491
515
|
};
|
|
492
516
|
const string = (field, optional = false) => {
|
|
493
517
|
const value = payload[field];
|
|
494
518
|
if (optional && value === void 0) return;
|
|
495
|
-
|
|
496
|
-
if (typeof value === "string" && (field.endsWith("Id") || field === "voids"))
|
|
519
|
+
check2(typeof value === "string" && (optional || value.length > 0), field, optional ? "a string" : "a non-empty string");
|
|
520
|
+
if (typeof value === "string" && (field.endsWith("Id") || field === "voids")) check2(value.length <= 64, field, "at most 64 characters");
|
|
497
521
|
if (typeof value === "string" && ["openedAt", "at", "createdAt", "closedAt"].includes(field)) {
|
|
498
|
-
|
|
522
|
+
check2(!Number.isNaN(Date.parse(value)), field, "a valid date");
|
|
499
523
|
}
|
|
500
524
|
noNul(value, field);
|
|
501
525
|
};
|
|
502
|
-
const integer = (field, min = -Infinity) =>
|
|
526
|
+
const integer = (field, min = -Infinity) => check2(Number.isSafeInteger(payload[field]) && payload[field] >= min, field, `a safe integer >= ${min}`);
|
|
503
527
|
const record = (field) => {
|
|
504
528
|
const value = payload[field];
|
|
505
|
-
|
|
529
|
+
check2(object(value), field, "a record of integers");
|
|
506
530
|
if (object(value)) for (const [key, amount] of Object.entries(value)) {
|
|
507
|
-
|
|
531
|
+
check2(key.length > 0 && Number.isSafeInteger(amount), `${field}.${key}`, "a non-empty key with a safe integer");
|
|
508
532
|
noNul(key, `${field}.${JSON.stringify(key)}`);
|
|
509
533
|
}
|
|
510
534
|
};
|
|
@@ -514,7 +538,7 @@ function registerPayloadErrors(type, payload) {
|
|
|
514
538
|
for (const field of ["registerId", "openedAt"]) string(field);
|
|
515
539
|
for (const field of ["storeKey", "businessDay", "openedBy"]) string(field, true);
|
|
516
540
|
if (payload.deviceName !== void 0) {
|
|
517
|
-
|
|
541
|
+
check2(
|
|
518
542
|
typeof payload.deviceName === "string" && payload.deviceName.trim().length >= 1 && payload.deviceName.trim().length <= 64,
|
|
519
543
|
"deviceName",
|
|
520
544
|
"a string of 1 to 64 characters after trim"
|
|
@@ -522,7 +546,7 @@ function registerPayloadErrors(type, payload) {
|
|
|
522
546
|
noNul(payload.deviceName, "deviceName");
|
|
523
547
|
}
|
|
524
548
|
if (payload.supersedes !== void 0) {
|
|
525
|
-
|
|
549
|
+
check2(
|
|
526
550
|
typeof payload.supersedes === "string" && payload.supersedes.length > 0 && payload.supersedes.length <= 64,
|
|
527
551
|
"supersedes",
|
|
528
552
|
"a non-empty string of at most 64 characters"
|
|
@@ -534,9 +558,9 @@ function registerPayloadErrors(type, payload) {
|
|
|
534
558
|
break;
|
|
535
559
|
case "register.session.transition":
|
|
536
560
|
string("at");
|
|
537
|
-
|
|
561
|
+
check2(["open", "counting", "closed"].includes(payload.status), "status", "open, counting or closed");
|
|
538
562
|
for (const field of ["counted", "closedBy", "approvedBy"]) if (payload[field] !== void 0) {
|
|
539
|
-
|
|
563
|
+
check2(payload.status === "closed", field, "a closing transition");
|
|
540
564
|
if (field === "counted") record(field);
|
|
541
565
|
else string(field, true);
|
|
542
566
|
}
|
|
@@ -547,22 +571,22 @@ function registerPayloadErrors(type, payload) {
|
|
|
547
571
|
string("createdBy", true);
|
|
548
572
|
if (type === "register.movement.void") string("voids");
|
|
549
573
|
else {
|
|
550
|
-
|
|
574
|
+
check2(
|
|
551
575
|
typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
|
|
552
576
|
"reason",
|
|
553
577
|
"a non-empty string after trim of at most 500 characters"
|
|
554
578
|
);
|
|
555
579
|
noNul(payload.reason, "reason");
|
|
556
|
-
|
|
580
|
+
check2(["paid_in", "paid_out", "no_sale"].includes(payload.type), "type", "paid_in, paid_out or no_sale");
|
|
557
581
|
integer("amountMinor", payload.type === "no_sale" ? 0 : 1);
|
|
558
|
-
if (payload.type === "no_sale")
|
|
582
|
+
if (payload.type === "no_sale") check2(payload.amountMinor === 0, "amountMinor", "0 for no_sale");
|
|
559
583
|
}
|
|
560
584
|
break;
|
|
561
585
|
case "register.closure.submit":
|
|
562
586
|
for (const field of ["closureId", "registerId", "openedAt", "closedAt", "softwareVersion"]) string(field);
|
|
563
587
|
for (const field of ["businessDay", "closedBy", "approvedBy"]) string(field, true);
|
|
564
588
|
if (payload.approval !== void 0) {
|
|
565
|
-
|
|
589
|
+
check2(typeof payload.approval === "string" && payload.approval.length > 0, "approval", "a non-empty string");
|
|
566
590
|
noNul(payload.approval, "approval");
|
|
567
591
|
}
|
|
568
592
|
integer("number", 1);
|
|
@@ -575,19 +599,19 @@ function registerPayloadErrors(type, payload) {
|
|
|
575
599
|
"unsyncedTotalMinor"
|
|
576
600
|
]) integer(field, 0);
|
|
577
601
|
for (const field of ["number", "unsyncedCount"])
|
|
578
|
-
|
|
602
|
+
check2(payload[field] <= 2147483647, field, "at most 2147483647");
|
|
579
603
|
for (const field of ["tillExpected", "counted"]) record(field);
|
|
580
604
|
for (const field of ["orderIds", "movementIds"]) {
|
|
581
605
|
const value = payload[field];
|
|
582
|
-
|
|
606
|
+
check2(Array.isArray(value), field, "an array of ids");
|
|
583
607
|
if (Array.isArray(value)) value.forEach((id, index) => {
|
|
584
|
-
|
|
608
|
+
check2(typeof id === "string" && id.length > 0 && id.length <= 64, `${field}[${index}]`, "a non-empty string of at most 64 characters");
|
|
585
609
|
noNul(id, `${field}[${index}]`);
|
|
586
610
|
});
|
|
587
611
|
}
|
|
588
612
|
break;
|
|
589
613
|
default:
|
|
590
|
-
|
|
614
|
+
check2(false, "type", "a register command type");
|
|
591
615
|
}
|
|
592
616
|
return errors;
|
|
593
617
|
}
|
|
@@ -596,12 +620,12 @@ function registerPayloadErrors(type, payload) {
|
|
|
596
620
|
function refundPayloadErrors(payload) {
|
|
597
621
|
const errors = [];
|
|
598
622
|
const object = (value) => typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
599
|
-
const
|
|
623
|
+
const check2 = (valid, field, expected) => {
|
|
600
624
|
if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`);
|
|
601
625
|
};
|
|
602
626
|
if (!object(payload)) return ["payload: expected an object"];
|
|
603
627
|
const noNul = (value, field) => {
|
|
604
|
-
if (typeof value === "string")
|
|
628
|
+
if (typeof value === "string") check2(!value.includes("\0"), field, "no NUL character");
|
|
605
629
|
};
|
|
606
630
|
const fields = [
|
|
607
631
|
"clientRefundId",
|
|
@@ -626,19 +650,19 @@ function refundPayloadErrors(payload) {
|
|
|
626
650
|
for (const field of ["clientRefundId", "orderId", "registerId", "sessionId", "clientOrderId", "cashierRef"]) {
|
|
627
651
|
const value = payload[field];
|
|
628
652
|
if (["clientOrderId", "cashierRef"].includes(field) && value === void 0) continue;
|
|
629
|
-
|
|
653
|
+
check2(
|
|
630
654
|
typeof value === "string" && value.length > 0 && value.length <= 64,
|
|
631
655
|
field,
|
|
632
656
|
"a non-empty string of at most 64 characters"
|
|
633
657
|
);
|
|
634
658
|
noNul(value, field);
|
|
635
659
|
}
|
|
636
|
-
|
|
660
|
+
check2(Array.isArray(payload.lines) && payload.lines.length <= 500, "lines", "an array of at most 500 lines");
|
|
637
661
|
const seen = /* @__PURE__ */ new Set();
|
|
638
662
|
if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
|
|
639
663
|
const path = `lines[${index}]`;
|
|
640
664
|
if (!object(line)) {
|
|
641
|
-
|
|
665
|
+
check2(false, path, "an object");
|
|
642
666
|
return;
|
|
643
667
|
}
|
|
644
668
|
for (const key of Object.keys(line)) {
|
|
@@ -646,32 +670,32 @@ function refundPayloadErrors(payload) {
|
|
|
646
670
|
errors.push(`${path}.${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.refund version 1`);
|
|
647
671
|
}
|
|
648
672
|
}
|
|
649
|
-
|
|
673
|
+
check2(
|
|
650
674
|
typeof line.orderLineId === "string" && line.orderLineId.length > 0 && line.orderLineId.length <= 64,
|
|
651
675
|
`${path}.orderLineId`,
|
|
652
676
|
"a non-empty string of at most 64 characters"
|
|
653
677
|
);
|
|
654
678
|
noNul(line.orderLineId, `${path}.orderLineId`);
|
|
655
679
|
if (typeof line.orderLineId === "string") {
|
|
656
|
-
|
|
680
|
+
check2(!seen.has(line.orderLineId), `${path}.orderLineId`, "unique in lines");
|
|
657
681
|
seen.add(line.orderLineId);
|
|
658
682
|
}
|
|
659
|
-
|
|
660
|
-
|
|
683
|
+
check2(Number.isSafeInteger(line.quantity) && line.quantity >= 1, `${path}.quantity`, "a safe integer >= 1");
|
|
684
|
+
check2(typeof line.restock === "boolean", `${path}.restock`, "a boolean");
|
|
661
685
|
});
|
|
662
686
|
for (const field of ["shippingMinor", "totalMinor"]) {
|
|
663
|
-
|
|
687
|
+
check2(Number.isSafeInteger(payload[field]) && payload[field] >= 0, field, "a safe integer >= 0");
|
|
664
688
|
}
|
|
665
|
-
|
|
666
|
-
|
|
689
|
+
check2(Number.isSafeInteger(payload.adjustmentMinor), "adjustmentMinor", "a safe integer");
|
|
690
|
+
check2(payload.destination === "original_method" || payload.destination === "cash", "destination", "original_method or cash");
|
|
667
691
|
noNul(payload.destination, "destination");
|
|
668
|
-
|
|
692
|
+
check2(
|
|
669
693
|
typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
|
|
670
694
|
"reason",
|
|
671
695
|
"a non-empty string after trim of at most 500 characters"
|
|
672
696
|
);
|
|
673
697
|
noNul(payload.reason, "reason");
|
|
674
|
-
|
|
698
|
+
check2(
|
|
675
699
|
typeof payload.createdAt === "string" && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
|
|
676
700
|
"createdAt",
|
|
677
701
|
"a valid date"
|
|
@@ -724,6 +748,460 @@ function platformErrorResult(id, platformCode, platformMessage) {
|
|
|
724
748
|
function internalErrorResult(id, correlationId) {
|
|
725
749
|
return { id, status: "rejected", error: { code: "internal_error", message: `Internal error (ref ${correlationId})`, data: { correlationId } } };
|
|
726
750
|
}
|
|
751
|
+
|
|
752
|
+
// src/server/display-signalling/memory-server.ts
|
|
753
|
+
var MINUTE = 6e4;
|
|
754
|
+
var CODE_TTL = 10 * MINUTE;
|
|
755
|
+
var MAX_UNSPENT = 5;
|
|
756
|
+
var SNAPSHOT_TTL = MINUTE;
|
|
757
|
+
var SNAPSHOT_MAX_BYTES = 204800;
|
|
758
|
+
var SOURCE_WINDOW = MINUTE;
|
|
759
|
+
var SOURCE_MAX = 10;
|
|
760
|
+
var STORE_WINDOW = 10 * MINUTE;
|
|
761
|
+
var STORE_MAX = 100;
|
|
762
|
+
var CONNECTED_MS = 3e4;
|
|
763
|
+
var ROW_TTL = 30 * 24 * 60 * MINUTE;
|
|
764
|
+
var SESSION_HEADER = "x-memory-display-session";
|
|
765
|
+
var BASE_URL = "memory://display-signalling";
|
|
766
|
+
var randomBytes = (length) => globalThis.crypto.getRandomValues(new Uint8Array(length));
|
|
767
|
+
var toHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
768
|
+
var newId = () => toHex(randomBytes(16));
|
|
769
|
+
var newSecret = () => btoa(String.fromCharCode(...randomBytes(16))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
770
|
+
var sha256Hex = async (text) => toHex(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))));
|
|
771
|
+
function randomDigits(digits) {
|
|
772
|
+
const range = 10 ** digits, limit = Math.floor(2 ** 32 / range) * range;
|
|
773
|
+
for (; ; ) {
|
|
774
|
+
const [value] = globalThis.crypto.getRandomValues(new Uint32Array(1));
|
|
775
|
+
if (value < limit) return String(value % range).padStart(digits, "0");
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
var fail = (code) => new DisplaySignallingError(code);
|
|
779
|
+
var iso = (ms) => new Date(ms).toISOString();
|
|
780
|
+
var drain = (map, key) => {
|
|
781
|
+
const box = map.get(key) ?? [];
|
|
782
|
+
map.delete(key);
|
|
783
|
+
return box;
|
|
784
|
+
};
|
|
785
|
+
function createMemoryDisplaySignalling(options = {}) {
|
|
786
|
+
let offset = 0;
|
|
787
|
+
const clock = () => (options.now ?? Date.now)() + offset;
|
|
788
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
789
|
+
const sourceOf = /* @__PURE__ */ new WeakMap();
|
|
790
|
+
const codes = /* @__PURE__ */ new Map(), pending = /* @__PURE__ */ new Map(), displays = /* @__PURE__ */ new Map();
|
|
791
|
+
const snapshots = /* @__PURE__ */ new Map(), sources = /* @__PURE__ */ new Map();
|
|
792
|
+
const displayInbox = /* @__PURE__ */ new Map(), tillInbox = /* @__PURE__ */ new Map();
|
|
793
|
+
let storeWindow = null;
|
|
794
|
+
const dropDisplay = (displayId) => [displays, snapshots, displayInbox].forEach((map) => map.delete(displayId));
|
|
795
|
+
const prune = () => {
|
|
796
|
+
const now = clock();
|
|
797
|
+
for (const [code, entry] of codes) if (now >= entry.expiresAt) codes.delete(code);
|
|
798
|
+
for (const [claimId, entry] of pending) if (now >= entry.expiresAt) pending.delete(claimId);
|
|
799
|
+
for (const [displayId, entry] of snapshots) if (now >= entry.postedAt + SNAPSHOT_TTL) snapshots.delete(displayId);
|
|
800
|
+
for (const [displayId, row] of displays) if (now >= (row.lastSeenAt ?? row.confirmedAt) + ROW_TTL) dropDisplay(displayId);
|
|
801
|
+
for (const [key, window] of sources) if (now >= window.openedAt + SOURCE_WINDOW) sources.delete(key);
|
|
802
|
+
if (storeWindow && now >= storeWindow.openedAt + STORE_WINDOW) storeWindow = null;
|
|
803
|
+
return now;
|
|
804
|
+
};
|
|
805
|
+
const admit = (ctx) => {
|
|
806
|
+
const now = prune();
|
|
807
|
+
const session = sessions.get(ctx.headers?.[SESSION_HEADER] ?? "");
|
|
808
|
+
if (!session || !session.capabilities.includes(DISPLAY_PAIR_CAPABILITY)) throw fail("forbidden");
|
|
809
|
+
return { now, cashierId: session.cashierId };
|
|
810
|
+
};
|
|
811
|
+
const ownedIn = (map, deviceId, id) => {
|
|
812
|
+
const entry = map.get(id);
|
|
813
|
+
if (!entry || entry.deviceId !== deviceId) throw fail("not_found");
|
|
814
|
+
return entry;
|
|
815
|
+
};
|
|
816
|
+
const findByTokenHash = (tokenHash) => [...displays].find(([, row]) => row.tokenHash === tokenHash);
|
|
817
|
+
const byToken = async (token) => {
|
|
818
|
+
const tokenHash = await sha256Hex(token);
|
|
819
|
+
const now = prune();
|
|
820
|
+
const found = findByTokenHash(tokenHash);
|
|
821
|
+
if (!found) throw fail("token_refused");
|
|
822
|
+
found[1].lastSeenAt = now;
|
|
823
|
+
return found;
|
|
824
|
+
};
|
|
825
|
+
const failedClaim = (key, now) => {
|
|
826
|
+
const window = sources.get(key);
|
|
827
|
+
sources.set(key, { openedAt: window?.openedAt ?? now, failures: (window?.failures ?? 0) + 1 });
|
|
828
|
+
storeWindow = { openedAt: storeWindow?.openedAt ?? now, failures: (storeWindow?.failures ?? 0) + 1 };
|
|
829
|
+
return fail("claim_refused");
|
|
830
|
+
};
|
|
831
|
+
const signalling = {
|
|
832
|
+
async mint(ctx, deviceId) {
|
|
833
|
+
const { now } = admit(ctx);
|
|
834
|
+
const unspent = [...codes.values()].filter((entry) => entry.deviceId === deviceId && !entry.spent).length;
|
|
835
|
+
if (unspent >= MAX_UNSPENT) throw fail("limit");
|
|
836
|
+
let code;
|
|
837
|
+
do
|
|
838
|
+
code = randomDigits(6);
|
|
839
|
+
while (codes.has(code));
|
|
840
|
+
codes.set(code, { deviceId, expiresAt: now + CODE_TTL, spent: false });
|
|
841
|
+
return { code, expiresAt: iso(now + CODE_TTL) };
|
|
842
|
+
},
|
|
843
|
+
async pending(ctx, deviceId) {
|
|
844
|
+
admit(ctx);
|
|
845
|
+
return [...pending].filter(([, entry]) => entry.deviceId === deviceId).map(([claimId, entry]) => ({ claimId, displayName: entry.displayName, checkCode: entry.checkCode, expiresAt: iso(entry.expiresAt) }));
|
|
846
|
+
},
|
|
847
|
+
async confirm(ctx, deviceId, claimId) {
|
|
848
|
+
const { now, cashierId } = admit(ctx);
|
|
849
|
+
const entry = ownedIn(pending, deviceId, claimId);
|
|
850
|
+
pending.delete(claimId);
|
|
851
|
+
const moving = entry.movingDisplayId !== null && displays.has(entry.movingDisplayId) ? entry.movingDisplayId : null;
|
|
852
|
+
if (moving !== null) dropDisplay(moving);
|
|
853
|
+
const row = { deviceId, name: entry.displayName, cashierId, confirmedAt: now, lastSeenAt: null, tokenHash: null, secretHash: entry.secretHash };
|
|
854
|
+
displays.set(moving ?? newId(), row);
|
|
855
|
+
},
|
|
856
|
+
async decline(ctx, deviceId, claimId) {
|
|
857
|
+
admit(ctx);
|
|
858
|
+
ownedIn(pending, deviceId, claimId);
|
|
859
|
+
pending.delete(claimId);
|
|
860
|
+
},
|
|
861
|
+
async list(ctx, deviceId) {
|
|
862
|
+
const { now } = admit(ctx);
|
|
863
|
+
return [...displays].filter(([, row]) => row.deviceId === deviceId).map(([displayId, row]) => ({
|
|
864
|
+
displayId,
|
|
865
|
+
name: row.name,
|
|
866
|
+
cashierId: row.cashierId,
|
|
867
|
+
lastSeenAt: row.lastSeenAt === null ? null : iso(row.lastSeenAt),
|
|
868
|
+
connected: row.lastSeenAt !== null && now - row.lastSeenAt <= CONNECTED_MS
|
|
869
|
+
}));
|
|
870
|
+
},
|
|
871
|
+
async forget(ctx, deviceId, displayId) {
|
|
872
|
+
admit(ctx);
|
|
873
|
+
ownedIn(displays, deviceId, displayId);
|
|
874
|
+
dropDisplay(displayId);
|
|
875
|
+
},
|
|
876
|
+
async sendSignal(ctx, deviceId, displayId, message) {
|
|
877
|
+
admit(ctx);
|
|
878
|
+
ownedIn(displays, deviceId, displayId);
|
|
879
|
+
displayInbox.set(displayId, [...displayInbox.get(displayId) ?? [], { type: message.type, payload: message.payload }]);
|
|
880
|
+
},
|
|
881
|
+
async receiveSignals(ctx, deviceId) {
|
|
882
|
+
admit(ctx);
|
|
883
|
+
return drain(tillInbox, deviceId).filter((message) => displays.get(message.displayId)?.deviceId === deviceId);
|
|
884
|
+
},
|
|
885
|
+
async postSnapshot(ctx, deviceId, displayId, body) {
|
|
886
|
+
const { now } = admit(ctx);
|
|
887
|
+
ownedIn(displays, deviceId, displayId);
|
|
888
|
+
const text = JSON.stringify(body) ?? "null";
|
|
889
|
+
if (new TextEncoder().encode(text).length > SNAPSHOT_MAX_BYTES) throw fail("too_large");
|
|
890
|
+
snapshots.set(displayId, { text, postedAt: now });
|
|
891
|
+
},
|
|
892
|
+
async claim(dctx, { code, displayName, token }) {
|
|
893
|
+
const claimSecret = newSecret();
|
|
894
|
+
const secretHash = await sha256Hex(claimSecret);
|
|
895
|
+
const tokenHash = token ? await sha256Hex(token) : null;
|
|
896
|
+
const now = prune();
|
|
897
|
+
const key = rateLimitSource(sourceOf.get(dctx) ?? "");
|
|
898
|
+
if ((storeWindow?.failures ?? 0) >= STORE_MAX || (sources.get(key)?.failures ?? 0) >= SOURCE_MAX) throw fail("claim_refused");
|
|
899
|
+
const entry = codes.get(code);
|
|
900
|
+
if (!entry || entry.spent) throw failedClaim(key, now);
|
|
901
|
+
entry.spent = true;
|
|
902
|
+
let checkCode;
|
|
903
|
+
do
|
|
904
|
+
checkCode = randomDigits(4);
|
|
905
|
+
while ([...pending.values()].some((other) => other.checkCode === checkCode));
|
|
906
|
+
const movingDisplayId = tokenHash === null ? null : findByTokenHash(tokenHash)?.[0] ?? null;
|
|
907
|
+
pending.set(newId(), { deviceId: entry.deviceId, secretHash, displayName, checkCode, expiresAt: entry.expiresAt, movingDisplayId });
|
|
908
|
+
return { claimSecret, checkCode };
|
|
909
|
+
},
|
|
910
|
+
async collect(_dctx, claimSecret) {
|
|
911
|
+
const secretHash = await sha256Hex(claimSecret);
|
|
912
|
+
const token = newSecret();
|
|
913
|
+
const tokenHash = await sha256Hex(token);
|
|
914
|
+
prune();
|
|
915
|
+
const waiting = [...pending.values()].find((entry) => entry.secretHash === secretHash);
|
|
916
|
+
if (waiting) return { status: "pending", checkCode: waiting.checkCode };
|
|
917
|
+
const found = [...displays].find(([, row]) => row.secretHash === secretHash && row.tokenHash === null);
|
|
918
|
+
if (!found) throw fail("collect_refused");
|
|
919
|
+
found[1].secretHash = null;
|
|
920
|
+
found[1].tokenHash = tokenHash;
|
|
921
|
+
return { status: "paired", displayId: found[0], token };
|
|
922
|
+
},
|
|
923
|
+
async displaySendSignal(_dctx, token, message) {
|
|
924
|
+
const [displayId, row] = await byToken(token);
|
|
925
|
+
tillInbox.set(row.deviceId, [...tillInbox.get(row.deviceId) ?? [], { type: message.type, payload: message.payload, displayId }]);
|
|
926
|
+
},
|
|
927
|
+
async displayReceiveSignals(_dctx, token) {
|
|
928
|
+
const [displayId] = await byToken(token);
|
|
929
|
+
return drain(displayInbox, displayId);
|
|
930
|
+
},
|
|
931
|
+
async readSnapshot(_dctx, token) {
|
|
932
|
+
const [displayId] = await byToken(token);
|
|
933
|
+
const held = snapshots.get(displayId);
|
|
934
|
+
return held ? JSON.parse(held.text) : null;
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
const harness = {
|
|
938
|
+
signalling,
|
|
939
|
+
till({ cashierId, canPair }) {
|
|
940
|
+
const sessionId = newId();
|
|
941
|
+
sessions.set(sessionId, { cashierId, capabilities: canPair ? [DISPLAY_PAIR_CAPABILITY] : [] });
|
|
942
|
+
return { connectorId: "memory-display-signalling", baseUrl: BASE_URL, headers: { [SESSION_HEADER]: sessionId } };
|
|
943
|
+
},
|
|
944
|
+
display(source) {
|
|
945
|
+
const dctx = { baseUrl: BASE_URL };
|
|
946
|
+
sourceOf.set(dctx, source);
|
|
947
|
+
return dctx;
|
|
948
|
+
},
|
|
949
|
+
advance: async (ms) => {
|
|
950
|
+
offset += ms;
|
|
951
|
+
},
|
|
952
|
+
async storedText() {
|
|
953
|
+
prune();
|
|
954
|
+
return JSON.stringify({
|
|
955
|
+
sessions: [...sessions],
|
|
956
|
+
codes: [...codes],
|
|
957
|
+
pending: [...pending],
|
|
958
|
+
displays: [...displays],
|
|
959
|
+
snapshots: [...snapshots],
|
|
960
|
+
displayInbox: [...displayInbox],
|
|
961
|
+
tillInbox: [...tillInbox],
|
|
962
|
+
sources: [...sources],
|
|
963
|
+
storeWindow
|
|
964
|
+
});
|
|
965
|
+
},
|
|
966
|
+
async storedCounts() {
|
|
967
|
+
prune();
|
|
968
|
+
return { codes: codes.size, pending: pending.size, displays: displays.size, snapshots: snapshots.size };
|
|
969
|
+
}
|
|
970
|
+
};
|
|
971
|
+
return { signalling, harness };
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// src/server/display-signalling/contract.ts
|
|
975
|
+
var MINUTE2 = 6e4;
|
|
976
|
+
var DAY = 24 * 60 * MINUTE2;
|
|
977
|
+
var A = "till-a";
|
|
978
|
+
var B = "till-b";
|
|
979
|
+
var SECRET = /^[A-Za-z0-9_-]{22,}$/;
|
|
980
|
+
function check(condition, message) {
|
|
981
|
+
if (!condition) throw new Error(`display signalling contract: ${message}`);
|
|
982
|
+
}
|
|
983
|
+
async function expectRefusal(promise, code, what) {
|
|
984
|
+
let result;
|
|
985
|
+
try {
|
|
986
|
+
result = await promise;
|
|
987
|
+
} catch (error) {
|
|
988
|
+
const got = error?.code;
|
|
989
|
+
check(got === code, `${what}: expected ${code}, got ${String(got ?? error)}`);
|
|
990
|
+
return error;
|
|
991
|
+
}
|
|
992
|
+
throw new Error(`display signalling contract: ${what}: expected ${code}, but it resolved ${JSON.stringify(result)}`);
|
|
993
|
+
}
|
|
994
|
+
var sameRefusal = (x, y, what) => check(x.message === y.message && x.code === y.code, `${what}: the refusals differ`);
|
|
995
|
+
function unusedCode(...used) {
|
|
996
|
+
for (let n = 0; ; n += 1) {
|
|
997
|
+
const code = String(n).padStart(used[0]?.length ?? 6, "0");
|
|
998
|
+
if (!used.includes(code)) return code;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
async function world(make) {
|
|
1002
|
+
const h = await make();
|
|
1003
|
+
const till = (cashierId, canPair = true) => h.till({ cashierId, canPair });
|
|
1004
|
+
return { h, s: h.signalling, a: await till("cashier-a"), b: await till("cashier-b"), viewer: await till("cashier-viewer", false) };
|
|
1005
|
+
}
|
|
1006
|
+
async function claimed(w, ctx, deviceId, d, name, token) {
|
|
1007
|
+
const { code } = await w.s.mint(ctx, deviceId);
|
|
1008
|
+
const claim = await w.s.claim(d, { code, displayName: name, ...token ? { token } : {} });
|
|
1009
|
+
const entry = (await w.s.pending(ctx, deviceId)).find((p) => p.checkCode === claim.checkCode);
|
|
1010
|
+
check(entry && entry.displayName === name, `the pending listing lacks the claim by ${name}`);
|
|
1011
|
+
return { code, claim, claimId: entry.claimId };
|
|
1012
|
+
}
|
|
1013
|
+
async function paired(w, ctx, deviceId, source, name, token) {
|
|
1014
|
+
const d = w.h.display(source);
|
|
1015
|
+
const { claim, claimId } = await claimed(w, ctx, deviceId, d, name, token);
|
|
1016
|
+
await w.s.confirm(ctx, deviceId, claimId);
|
|
1017
|
+
const result = await w.s.collect(d, claim.claimSecret);
|
|
1018
|
+
check(result.status === "paired", `collect after the confirm gave ${result.status}`);
|
|
1019
|
+
return { d, claim, displayId: result.displayId, token: result.token };
|
|
1020
|
+
}
|
|
1021
|
+
function displaySignallingContract(makeHarness) {
|
|
1022
|
+
const cases = {
|
|
1023
|
+
"mint without the capability is forbidden and makes no code": async ({ h, s, viewer }) => {
|
|
1024
|
+
await expectRefusal(s.mint(viewer, A), "forbidden", "mint without the capability");
|
|
1025
|
+
check((await h.storedCounts()).codes === 0, "a refused mint stored a code");
|
|
1026
|
+
},
|
|
1027
|
+
"a minted code is at least 6 digits and expires within 10 minutes": async ({ h, s, a }) => {
|
|
1028
|
+
const { code, expiresAt } = await s.mint(a, A);
|
|
1029
|
+
check(/^\d{6,}$/.test(code), `code ${code} is not 6 or more digits`);
|
|
1030
|
+
check(!Number.isNaN(Date.parse(expiresAt)), `expiresAt ${expiresAt} is not a date`);
|
|
1031
|
+
await h.advance(10 * MINUTE2);
|
|
1032
|
+
await expectRefusal(s.claim(h.display("192.0.2.1"), { code, displayName: "Late" }), "claim_refused", "a claim 10 minutes after the mint");
|
|
1033
|
+
},
|
|
1034
|
+
"a device holds at most 5 unspent codes, and expired codes stop counting": async ({ h, s, a }) => {
|
|
1035
|
+
for (let i = 0; i < 5; i += 1) await s.mint(a, A);
|
|
1036
|
+
await expectRefusal(s.mint(a, A), "limit", "the 6th unspent code");
|
|
1037
|
+
await h.advance(10 * MINUTE2);
|
|
1038
|
+
await s.mint(a, A);
|
|
1039
|
+
},
|
|
1040
|
+
"spent, expired and unknown codes get the same claim refusal": async ({ h, s, a }) => {
|
|
1041
|
+
const spent = (await s.mint(a, A)).code;
|
|
1042
|
+
await s.claim(h.display("192.0.2.1"), { code: spent, displayName: "First" });
|
|
1043
|
+
const again = await expectRefusal(s.claim(h.display("192.0.2.2"), { code: spent, displayName: "Second" }), "claim_refused", "a spent code");
|
|
1044
|
+
const expired = (await s.mint(a, A)).code;
|
|
1045
|
+
await h.advance(10 * MINUTE2);
|
|
1046
|
+
const late = await expectRefusal(s.claim(h.display("192.0.2.3"), { code: expired, displayName: "Late" }), "claim_refused", "an expired code");
|
|
1047
|
+
const unknown = await expectRefusal(s.claim(h.display("192.0.2.4"), { code: unusedCode(spent, expired), displayName: "Guess" }), "claim_refused", "an unknown code");
|
|
1048
|
+
sameRefusal(again, late, "spent and expired");
|
|
1049
|
+
sameRefusal(again, unknown, "spent and unknown");
|
|
1050
|
+
},
|
|
1051
|
+
"a claim issues no token: collect gives pending with its check code": async (w) => {
|
|
1052
|
+
const d = w.h.display("192.0.2.1");
|
|
1053
|
+
const { claim } = await claimed(w, w.a, A, d, "Counter");
|
|
1054
|
+
const result = await w.s.collect(d, claim.claimSecret);
|
|
1055
|
+
check(result.status === "pending" && result.checkCode === claim.checkCode, `collect before the confirm gave ${JSON.stringify(result)}`);
|
|
1056
|
+
},
|
|
1057
|
+
"the check code matches on both screens, and two live claims never share one": async (w) => {
|
|
1058
|
+
const d = w.h.display("192.0.2.1");
|
|
1059
|
+
const first = await claimed(w, w.a, A, d, "One");
|
|
1060
|
+
check(/^\d{4}$/.test(first.claim.checkCode), `check code ${first.claim.checkCode} is not 4 digits`);
|
|
1061
|
+
const listed = (await w.s.pending(w.a, A)).find((p) => p.claimId === first.claimId);
|
|
1062
|
+
const collected = await w.s.collect(d, first.claim.claimSecret);
|
|
1063
|
+
check(listed?.checkCode === first.claim.checkCode, "the till lists another check code");
|
|
1064
|
+
check(collected.status === "pending" && collected.checkCode === first.claim.checkCode, "collect gives another check code");
|
|
1065
|
+
const second = await claimed(w, w.a, A, w.h.display("192.0.2.2"), "Two");
|
|
1066
|
+
check(second.claim.checkCode !== first.claim.checkCode, "two live claims share a check code");
|
|
1067
|
+
},
|
|
1068
|
+
"a confirm issues the token once, then collect is refused like an unknown secret": async (w) => {
|
|
1069
|
+
const { d, claim, token } = await paired(w, w.a, A, "192.0.2.1", "Counter");
|
|
1070
|
+
check(SECRET.test(token), "the token is not 22+ base64url characters");
|
|
1071
|
+
const again = await expectRefusal(w.s.collect(d, claim.claimSecret), "collect_refused", "a second collect");
|
|
1072
|
+
const unknown = await expectRefusal(w.s.collect(d, "AAAAAAAAAAAAAAAAAAAAAA"), "collect_refused", "an unknown secret");
|
|
1073
|
+
sameRefusal(again, unknown, "second collect and unknown secret");
|
|
1074
|
+
},
|
|
1075
|
+
"a decline, or an unconfirmed claim whose code expires, issues nothing": async (w) => {
|
|
1076
|
+
const d = w.h.display("192.0.2.1");
|
|
1077
|
+
const declined = await claimed(w, w.a, A, d, "Declined");
|
|
1078
|
+
await w.s.decline(w.a, A, declined.claimId);
|
|
1079
|
+
await expectRefusal(w.s.collect(d, declined.claim.claimSecret), "collect_refused", "collect after a decline");
|
|
1080
|
+
const lapsed = await claimed(w, w.a, A, d, "Lapsed");
|
|
1081
|
+
await w.h.advance(10 * MINUTE2);
|
|
1082
|
+
await expectRefusal(w.s.collect(d, lapsed.claim.claimSecret), "collect_refused", "collect after the code expired");
|
|
1083
|
+
check((await w.h.storedCounts()).pending === 0, "a pending pairing outlived its decline or its code");
|
|
1084
|
+
},
|
|
1085
|
+
"a confirm needs the capability and the minting device": async (w) => {
|
|
1086
|
+
const d = w.h.display("192.0.2.1");
|
|
1087
|
+
const { claim, claimId } = await claimed(w, w.a, A, d, "Counter");
|
|
1088
|
+
await expectRefusal(w.s.confirm(w.viewer, A, claimId), "forbidden", "a confirm without the capability");
|
|
1089
|
+
await expectRefusal(w.s.confirm(w.b, B, claimId), "not_found", "a confirm from another device");
|
|
1090
|
+
check((await w.s.collect(d, claim.claimSecret)).status === "pending", "a refused confirm changed the claim");
|
|
1091
|
+
},
|
|
1092
|
+
"one source is limited to 10 failed claims a minute, and a limited claim spends nothing": async ({ h, s, a }) => {
|
|
1093
|
+
const { code } = await s.mint(a, A);
|
|
1094
|
+
const guesser = h.display("198.51.100.7");
|
|
1095
|
+
for (let i = 0; i < 10; i += 1) await expectRefusal(s.claim(guesser, { code: unusedCode(code), displayName: "Guess" }), "claim_refused", "a wrong code");
|
|
1096
|
+
await expectRefusal(s.claim(guesser, { code, displayName: "Guess" }), "claim_refused", "a valid code from a limited source");
|
|
1097
|
+
await s.claim(h.display("198.51.100.8"), { code, displayName: "Other" });
|
|
1098
|
+
await h.advance(MINUTE2);
|
|
1099
|
+
await s.claim(guesser, { code: (await s.mint(a, A)).code, displayName: "Later" });
|
|
1100
|
+
},
|
|
1101
|
+
"two IPv6 addresses in one /64 share a limit": async ({ h, s, a }) => {
|
|
1102
|
+
const { code } = await s.mint(a, A);
|
|
1103
|
+
const one = h.display("2001:db8:0:1::5");
|
|
1104
|
+
const two = h.display("2001:db8:0:1:ffff::9");
|
|
1105
|
+
for (let i = 0; i < 10; i += 1) await expectRefusal(s.claim(i % 2 ? two : one, { code: unusedCode(code), displayName: "Guess" }), "claim_refused", "a wrong code");
|
|
1106
|
+
await expectRefusal(s.claim(one, { code, displayName: "Guess" }), "claim_refused", "a valid code from a limited /64");
|
|
1107
|
+
await expectRefusal(s.claim(two, { code, displayName: "Guess" }), "claim_refused", "a valid code from a limited /64");
|
|
1108
|
+
await s.claim(h.display("2001:db8:0:2::5"), { code, displayName: "Other" });
|
|
1109
|
+
},
|
|
1110
|
+
"100 failed claims store-wide pause every claim for 10 minutes": async ({ h, s, a }) => {
|
|
1111
|
+
const { code } = await s.mint(a, A);
|
|
1112
|
+
for (let i = 0; i < 100; i += 1) await expectRefusal(s.claim(h.display(`203.0.113.${Math.floor(i / 9) + 1}`), { code: unusedCode(code), displayName: "Guess" }), "claim_refused", "a wrong code");
|
|
1113
|
+
await expectRefusal(s.claim(h.display("203.0.113.200"), { code, displayName: "Shop" }), "claim_refused", "a valid code while paused");
|
|
1114
|
+
await h.advance(10 * MINUTE2);
|
|
1115
|
+
await s.claim(h.display("203.0.113.201"), { code: (await s.mint(a, A)).code, displayName: "Shop" });
|
|
1116
|
+
},
|
|
1117
|
+
"the claim secret and the token are stored only as hashes": async (w) => {
|
|
1118
|
+
const { claim, token } = await paired(w, w.a, A, "192.0.2.1", "Counter");
|
|
1119
|
+
const text = await w.h.storedText();
|
|
1120
|
+
check(SECRET.test(claim.claimSecret), "the claim secret is not 22+ base64url characters");
|
|
1121
|
+
check(!text.includes(claim.claimSecret) && !text.includes(token), "the claim secret or the token is stored");
|
|
1122
|
+
check(text.includes(await sha256Hex(token)), "the token's SHA-256 hex is not stored");
|
|
1123
|
+
},
|
|
1124
|
+
"the registry lists a display on its owning device only, and tracks connected": async (w) => {
|
|
1125
|
+
const { d, displayId, token } = await paired(w, w.a, A, "192.0.2.1", "Counter");
|
|
1126
|
+
const row = (await w.s.list(w.a, A)).find((r) => r.displayId === displayId);
|
|
1127
|
+
check(row?.name === "Counter" && row.cashierId === "cashier-a", `the owner lists ${JSON.stringify(row)}`);
|
|
1128
|
+
check(!(await w.s.list(w.b, B)).some((r) => r.displayId === displayId), "another device lists the display");
|
|
1129
|
+
await w.s.displayReceiveSignals(d, token);
|
|
1130
|
+
check((await w.s.list(w.a, A))[0]?.connected === true, "a display just seen is not connected");
|
|
1131
|
+
await w.h.advance(31e3);
|
|
1132
|
+
check((await w.s.list(w.a, A))[0]?.connected === false, "a display unseen for 31 s is connected");
|
|
1133
|
+
},
|
|
1134
|
+
"forget revokes the token, the row and the snapshot, for the owner only": async (w) => {
|
|
1135
|
+
const { d, displayId, token } = await paired(w, w.a, A, "192.0.2.1", "Counter");
|
|
1136
|
+
await w.s.postSnapshot(w.a, A, displayId, { v: 1 });
|
|
1137
|
+
await w.s.displaySendSignal(d, token, { type: "answer", payload: "a1" });
|
|
1138
|
+
await expectRefusal(w.s.forget(w.b, B, displayId), "not_found", "forget from another device");
|
|
1139
|
+
check((await w.s.list(w.a, A)).length === 1, "a refused forget removed the display");
|
|
1140
|
+
await w.s.forget(w.a, A, displayId);
|
|
1141
|
+
await expectRefusal(w.s.displayReceiveSignals(d, token), "token_refused", "a forgotten token");
|
|
1142
|
+
check((await w.s.list(w.a, A)).length === 0, "the owner still lists a forgotten display");
|
|
1143
|
+
check((await w.s.receiveSignals(w.a, A)).every((m) => m.displayId !== displayId), "the till received from a forgotten display");
|
|
1144
|
+
const counts = await w.h.storedCounts();
|
|
1145
|
+
check(counts.displays === 0 && counts.snapshots === 0, `forget left ${JSON.stringify(counts)}`);
|
|
1146
|
+
},
|
|
1147
|
+
"a display confirmed by a second till moves to it": async (w) => {
|
|
1148
|
+
const first = await paired(w, w.a, A, "192.0.2.1", "Counter");
|
|
1149
|
+
await w.s.postSnapshot(w.a, A, first.displayId, { v: 1 });
|
|
1150
|
+
await w.s.sendSignal(w.a, A, first.displayId, { type: "offer", payload: "o1" });
|
|
1151
|
+
await w.s.displaySendSignal(first.d, first.token, { type: "answer", payload: "a1" });
|
|
1152
|
+
const moved = await paired(w, w.b, B, "192.0.2.1", "Counter", first.token);
|
|
1153
|
+
check(await w.s.readSnapshot(moved.d, moved.token) === null, "the first till's snapshot survived the move");
|
|
1154
|
+
check((await w.s.displayReceiveSignals(moved.d, moved.token)).length === 0, "the first till's signal survived the move");
|
|
1155
|
+
check((await w.h.storedCounts()).snapshots === 0, "a snapshot is stored after the move");
|
|
1156
|
+
check((await w.s.receiveSignals(w.a, A)).every((m) => m.displayId !== first.displayId), "the first till received from a moved display");
|
|
1157
|
+
check((await w.s.list(w.a, A)).length === 0, "the first till still lists a moved display");
|
|
1158
|
+
check((await w.s.list(w.b, B)).some((r) => r.displayId === first.displayId) && moved.displayId === first.displayId, "the moved display has a new id");
|
|
1159
|
+
await expectRefusal(w.s.readSnapshot(first.d, first.token), "token_refused", "the old token after a move");
|
|
1160
|
+
},
|
|
1161
|
+
"signals arrive once and in order, and only at their own display or till": async (w) => {
|
|
1162
|
+
const x = await paired(w, w.a, A, "192.0.2.1", "X");
|
|
1163
|
+
const y = await paired(w, w.a, A, "192.0.2.2", "Y");
|
|
1164
|
+
const z = await paired(w, w.b, B, "192.0.2.3", "Z");
|
|
1165
|
+
await w.s.sendSignal(w.a, A, x.displayId, { type: "offer", payload: "o1" });
|
|
1166
|
+
await w.s.sendSignal(w.a, A, x.displayId, { type: "ice", payload: "i1" });
|
|
1167
|
+
const atX = await w.s.displayReceiveSignals(x.d, x.token);
|
|
1168
|
+
check(atX.map((m) => m.payload).join() === "o1,i1", `display X received ${JSON.stringify(atX)}`);
|
|
1169
|
+
check((await w.s.displayReceiveSignals(x.d, x.token)).length === 0, "display X received a message twice");
|
|
1170
|
+
check((await w.s.displayReceiveSignals(y.d, y.token)).length === 0, "display Y received display X's messages");
|
|
1171
|
+
await w.s.displaySendSignal(x.d, x.token, { type: "answer", payload: "a1" });
|
|
1172
|
+
await w.s.displaySendSignal(x.d, x.token, { type: "ice", payload: "i2" });
|
|
1173
|
+
await w.s.displaySendSignal(z.d, z.token, { type: "answer", payload: "z1" });
|
|
1174
|
+
check((await w.s.receiveSignals(w.b, B)).every((m) => m.displayId === z.displayId), "device B received device A's display");
|
|
1175
|
+
const atA = await w.s.receiveSignals(w.a, A);
|
|
1176
|
+
check(atA.map((m) => `${m.displayId === x.displayId}:${m.payload}`).join() === "true:a1,true:i2", `till A received ${JSON.stringify(atA)}`);
|
|
1177
|
+
check((await w.s.receiveSignals(w.a, A)).length === 0, "till A received a message twice");
|
|
1178
|
+
},
|
|
1179
|
+
"the snapshot needs the token, keeps the latest body for 60 s, and refuses over 200 KiB": async (w) => {
|
|
1180
|
+
const { d, displayId, token } = await paired(w, w.a, A, "192.0.2.1", "Counter");
|
|
1181
|
+
await expectRefusal(w.s.readSnapshot(d, "not-a-token-not-a-token"), "token_refused", "a read without the token");
|
|
1182
|
+
await w.s.postSnapshot(w.a, A, displayId, { seq: 1 });
|
|
1183
|
+
await w.s.postSnapshot(w.a, A, displayId, { seq: 2 });
|
|
1184
|
+
check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"seq":2}', "the latest snapshot is not served");
|
|
1185
|
+
await w.h.advance(61e3);
|
|
1186
|
+
check(await w.s.readSnapshot(d, token) === null, "a snapshot outlived 60 s");
|
|
1187
|
+
await w.s.postSnapshot(w.a, A, displayId, { seq: 3 });
|
|
1188
|
+
await expectRefusal(w.s.postSnapshot(w.a, A, displayId, { pad: "x".repeat(204800) }), "too_large", "a snapshot over 200 KiB");
|
|
1189
|
+
check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"seq":3}', "a refused snapshot replaced the previous one");
|
|
1190
|
+
},
|
|
1191
|
+
"expired codes and displays unseen for 30 days are pruned": async (w) => {
|
|
1192
|
+
const { d, token } = await paired(w, w.a, A, "192.0.2.1", "Counter");
|
|
1193
|
+
await w.s.mint(w.a, A);
|
|
1194
|
+
await w.h.advance(10 * MINUTE2);
|
|
1195
|
+
await w.s.list(w.a, A);
|
|
1196
|
+
check((await w.h.storedCounts()).codes === 0, "an expired code is still stored");
|
|
1197
|
+
await w.h.advance(30 * DAY);
|
|
1198
|
+
await w.s.list(w.a, A);
|
|
1199
|
+
check((await w.h.storedCounts()).displays === 0, "a display unseen for 30 days is still stored");
|
|
1200
|
+
await expectRefusal(w.s.readSnapshot(d, token), "token_refused", "a pruned display");
|
|
1201
|
+
}
|
|
1202
|
+
};
|
|
1203
|
+
return Object.entries(cases).map(([name, run]) => ({ name, run: async () => run(await world(makeHarness)) }));
|
|
1204
|
+
}
|
|
727
1205
|
export {
|
|
728
1206
|
CommandResultError,
|
|
729
1207
|
MAX_COMMANDS_PER_BATCH,
|
|
@@ -733,9 +1211,11 @@ export {
|
|
|
733
1211
|
SUPPORTED_REGISTER_VERSIONS,
|
|
734
1212
|
canonicalJson,
|
|
735
1213
|
commandFingerprint,
|
|
1214
|
+
createMemoryDisplaySignalling,
|
|
736
1215
|
currencyDecimals,
|
|
737
1216
|
deriveSessionFigures,
|
|
738
1217
|
deriveVariance,
|
|
1218
|
+
displaySignallingContract,
|
|
739
1219
|
fiscalFiguresErrors,
|
|
740
1220
|
inProgressOutcome,
|
|
741
1221
|
internalErrorResult,
|