@tallyui/core 3.20.1 → 4.0.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.
Files changed (43) hide show
  1. package/dist/chunk-XF3RD6GX.js +515 -0
  2. package/dist/index.d.ts +41 -47
  3. package/dist/index.js +119 -101
  4. package/dist/server/index.cjs +1923 -0
  5. package/dist/server/index.d.cts +1039 -0
  6. package/dist/server/index.d.ts +46 -48
  7. package/dist/server/index.js +516 -206
  8. package/dist/{command-result-E_nH57WD.d.ts → tax-rate-DCJhfJbZ.d.ts} +442 -26
  9. package/package.json +10 -5
  10. package/src/commands.ts +12 -0
  11. package/src/context/money-format-context.tsx +50 -0
  12. package/src/coupons/woocommerce/to-coupon-configs.ts +5 -8
  13. package/src/fnv1a32.ts +14 -0
  14. package/src/index.ts +18 -5
  15. package/src/known-warnings.ts +23 -0
  16. package/src/money.ts +85 -2
  17. package/src/server/batch.ts +63 -27
  18. package/src/server/command-result.ts +28 -1
  19. package/src/server/display-signalling/contract.ts +203 -78
  20. package/src/server/display-signalling/memory-server.ts +71 -23
  21. package/src/server/fiscal-figures.ts +1 -1
  22. package/src/server/index.ts +5 -1
  23. package/src/server/money.ts +4 -1
  24. package/src/server/order-payload-shape.ts +96 -5
  25. package/src/server/refund-payload-shape.ts +5 -11
  26. package/src/server/register-payload-shape.ts +6 -12
  27. package/src/server/rejection-codes.ts +4 -4
  28. package/src/server/reopen-payload-shape.ts +25 -0
  29. package/src/server/shape-errors.ts +17 -0
  30. package/src/server/tax-rate.ts +13 -0
  31. package/src/server/update-payload-shape.ts +51 -0
  32. package/src/server/versions.ts +9 -2
  33. package/src/types/closures.ts +34 -0
  34. package/src/types/commands.ts +93 -8
  35. package/src/types/connector.ts +37 -4
  36. package/src/types/display-signalling.ts +30 -14
  37. package/src/types/index.ts +6 -3
  38. package/src/types/orders.ts +25 -3
  39. package/src/types/payment-methods.ts +17 -0
  40. package/src/types/stock.ts +2 -0
  41. package/src/types/store-settings.ts +7 -0
  42. package/src/types/traits/product.ts +19 -0
  43. package/dist/chunk-27L7XLTT.js +0 -235
@@ -3,41 +3,25 @@ import {
3
3
  DISPLAY_PAIR_CAPABILITY,
4
4
  DisplaySignallingError,
5
5
  MAX_COMMANDS_PER_BATCH,
6
+ ORDER_LINE_SKU_MAX,
7
+ ORDER_META_KEY_MAX,
8
+ ORDER_META_MAX,
6
9
  ORDER_NOTE_MAX,
10
+ ORDER_TAX_IDS_MAX,
11
+ ORDER_TAX_ID_TYPE_MAX,
12
+ ORDER_TAX_ID_VALUE_MAX,
13
+ currencyDecimals,
14
+ deriveSessionFigures,
15
+ deriveVariance,
16
+ majorToMinor,
17
+ minorToMajor,
18
+ minorUnitDigits,
7
19
  parseCommandResult,
8
- rateLimitSource
9
- } from "../chunk-27L7XLTT.js";
20
+ rateLimitSource,
21
+ ratePpmFromPercent
22
+ } from "../chunk-XF3RD6GX.js";
10
23
  import "../chunk-MLKGABMK.js";
11
24
 
12
- // src/server/money.ts
13
- function currencyDecimals(currency) {
14
- return new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits;
15
- }
16
- function minorToMajor(minor, decimals) {
17
- if (!Number.isSafeInteger(minor)) throw new RangeError("minor must be a safe integer");
18
- const sign = minor < 0 ? "-" : "";
19
- const digits = Math.abs(minor).toString().padStart(decimals + 1, "0");
20
- return sign + (decimals === 0 ? digits : `${digits.slice(0, -decimals)}.${digits.slice(-decimals)}`);
21
- }
22
- function majorToMinor(value, decimals) {
23
- const match = /^([+-]?)(\d+(?:\.\d*)?|\.\d+)(?:e([+-]?\d+))?$/i.exec(String(value));
24
- if (!match) throw new RangeError("value must be a finite decimal");
25
- const [, sign, mantissa, exponent = "0"] = match;
26
- const [whole, fraction = ""] = mantissa.split(".");
27
- const coefficient = BigInt(whole + fraction);
28
- const shift = BigInt(decimals) + BigInt(exponent) - BigInt(fraction.length);
29
- let rounded;
30
- if (shift >= 0n) {
31
- rounded = coefficient * 10n ** shift;
32
- } else {
33
- const divisor = 10n ** -shift;
34
- rounded = coefficient / divisor + (coefficient % divisor * 2n >= divisor ? 1n : 0n);
35
- }
36
- const minor = Number(sign === "-" ? -rounded : rounded);
37
- if (!Number.isSafeInteger(minor)) throw new RangeError("minor amount exceeds safe integer range");
38
- return minor;
39
- }
40
-
41
25
  // src/server/fingerprint.ts
42
26
  import { createHash } from "node:crypto";
43
27
  function canonicalJson(value) {
@@ -88,6 +72,9 @@ function payloadShapeErrors(payload) {
88
72
  if (item[optionalString] !== void 0) {
89
73
  check2(typeof item[optionalString] === "string", `${path}.${optionalString}`, "a string");
90
74
  }
75
+ if (!isLines && item.methodId !== void 0) {
76
+ check2(typeof item.methodId === "string" && item.methodId.length > 0, `${path}.methodId`, "a non-empty string");
77
+ }
91
78
  if (isLines && item.taxInclusive !== void 0) {
92
79
  check2(typeof item.taxInclusive === "boolean", `${path}.taxInclusive`, "a boolean");
93
80
  }
@@ -175,7 +162,8 @@ function payloadShapeErrors(payload) {
175
162
  if (items === void 0) continue;
176
163
  check2(Array.isArray(items), `${prefix}coupons`, "an array");
177
164
  if (!Array.isArray(items)) continue;
178
- const keys = prefix ? ["code", "amountMinor"] : ["code", "couponId", "discountMinor", "discountTaxMinor"];
165
+ const keys = prefix ? ["code", "amountMinor"] : ["code", "couponId", "discountMinor", "discountTaxMinor", "lines"];
166
+ const hasLines = !prefix && items.some((item) => object(item) && item.lines !== void 0);
179
167
  const seen = /* @__PURE__ */ new Set();
180
168
  items.forEach((item, index) => {
181
169
  const path = `${prefix}coupons[${index}]`;
@@ -187,6 +175,47 @@ function payloadShapeErrors(payload) {
187
175
  if (!prefix) {
188
176
  check2(!seen.has(item.code), `${path}.code`, "no duplicate code");
189
177
  seen.add(item.code);
178
+ if (hasLines) check2(Array.isArray(item.lines), `${path}.lines`, "an array");
179
+ if (Array.isArray(item.lines)) {
180
+ const ids = Array.isArray(payload.lines) ? payload.lines.map((line) => object(line) ? line.clientLineId : void 0) : [];
181
+ const seenIds = /* @__PURE__ */ new Set();
182
+ let previous = -1;
183
+ let validAmounts = true;
184
+ let discountSum = 0n;
185
+ let taxSum = 0n;
186
+ item.lines.forEach((line, index2) => {
187
+ const p = `${path}.lines[${index2}]`;
188
+ check2(object(line), p, "an object");
189
+ if (!object(line)) {
190
+ validAmounts = false;
191
+ previous = -1;
192
+ return;
193
+ }
194
+ for (const key of Object.keys(line)) check2(["clientLineId", "discountMinor", "discountTaxMinor"].includes(key), `${p}.${key}`, "no unknown key");
195
+ const at = typeof line.clientLineId === "string" ? ids.indexOf(line.clientLineId) : -1;
196
+ check2(at >= 0, `${p}.clientLineId`, "a payload lines[].clientLineId");
197
+ check2(!seenIds.has(line.clientLineId), `${p}.clientLineId`, "no duplicate clientLineId");
198
+ seenIds.add(line.clientLineId);
199
+ if (at >= 0 && previous >= 0) check2(at > previous, `${p}.clientLineId`, "payload lines order");
200
+ previous = at;
201
+ const valid = ["discountMinor", "discountTaxMinor"].map((key) => {
202
+ const valid2 = Number.isSafeInteger(line[key]) && line[key] >= 0;
203
+ check2(valid2, `${p}.${key}`, "a safe integer >= 0");
204
+ return valid2;
205
+ }).every(Boolean);
206
+ if (!valid) {
207
+ validAmounts = false;
208
+ return;
209
+ }
210
+ check2(line.discountMinor !== 0 || line.discountTaxMinor !== 0, p, "a non-zero discountMinor or discountTaxMinor");
211
+ discountSum += BigInt(line.discountMinor);
212
+ taxSum += BigInt(line.discountTaxMinor);
213
+ });
214
+ if (validAmounts && ["discountMinor", "discountTaxMinor"].every((key) => Number.isSafeInteger(item[key]) && item[key] >= 0)) {
215
+ check2(discountSum === BigInt(item.discountMinor), `${path}.lines`, `discountMinor summing to ${path}.discountMinor`);
216
+ check2(taxSum === BigInt(item.discountTaxMinor), `${path}.lines`, `discountTaxMinor summing to ${path}.discountTaxMinor`);
217
+ }
218
+ }
190
219
  }
191
220
  });
192
221
  }
@@ -211,14 +240,55 @@ function payloadShapeErrors(payload) {
211
240
  `a key of ${path}.attributes with a non-empty value`
212
241
  );
213
242
  });
243
+ if (line.sku !== void 0) {
244
+ check2(typeof line.sku === "string" && line.sku.length > 0, `${path}.sku`, "a non-empty string");
245
+ check2(line.custom === void 0, `${path}.sku`, "absent on a custom line (custom.sku)");
246
+ }
214
247
  });
248
+ const lists = [
249
+ ["customer.taxIds", object(payload.customer) ? payload.customer.taxIds : void 0, ["type", "value", "country"]],
250
+ ["meta", payload.meta, ["key", "value"]]
251
+ ];
252
+ for (const [field, items, keys] of lists) {
253
+ if (items === void 0) continue;
254
+ check2(Array.isArray(items), field, "an array");
255
+ if (!Array.isArray(items)) continue;
256
+ const seen = /* @__PURE__ */ new Set();
257
+ items.forEach((item, index) => {
258
+ const path = `${field}[${index}]`;
259
+ check2(object(item), path, "an object");
260
+ if (!object(item)) return;
261
+ for (const key of Object.keys(item)) check2(keys.includes(key), `${path}.${key}`, "no unknown key");
262
+ if (field === "meta") {
263
+ const key = item.key;
264
+ check2(typeof key === "string" && key.length > 0, `${path}.key`, "a non-empty string");
265
+ if (typeof key === "string" && key.length > 0) check2(!key.startsWith("_"), `${path}.key`, "a key not starting with _");
266
+ check2(typeof item.value === "string", `${path}.value`, "a string");
267
+ if (typeof key === "string") check2(!seen.has(key), `${path}.key`, "no duplicate key");
268
+ seen.add(key);
269
+ return;
270
+ }
271
+ for (const key of ["type", "value"]) check2(typeof item[key] === "string" && item[key].length > 0, `${path}.${key}`, "a non-empty string");
272
+ if (item.country !== void 0) check2(typeof item.country === "string" && /^[A-Z]{2}$/.test(item.country), `${path}.country`, "an ISO 3166-1 alpha-2 code");
273
+ });
274
+ }
215
275
  for (const [value, path] of payloadStrings(payload)) check2(!value.includes("\0"), path, "no NUL character");
216
276
  return errors;
217
277
  }
218
278
  var ORDER_ADDRESS_KEYS = ["firstName", "lastName", "company", "address1", "address2", "city", "state", "postcode", "country", "phone"];
219
279
  function payloadBoundErrors(payload) {
220
280
  if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return [];
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);
281
+ const record = payload;
282
+ const errors = payloadStrings(record).filter(([value, , max2]) => max2 !== void 0 && value.length > max2).map(([, path, max2]) => `${path}: expected at most ${max2} characters`).slice(0, 10);
283
+ const max = Array.isArray(record.lines) ? record.lines.length : 0;
284
+ if (Array.isArray(record.coupons)) record.coupons.forEach((coupon, index) => {
285
+ if (errors.length < 10 && typeof coupon === "object" && coupon !== null && !Array.isArray(coupon) && Array.isArray(coupon.lines) && coupon.lines.length > max) errors.push(`coupons[${index}].lines: expected at most ${max} entries`);
286
+ });
287
+ const customer = typeof record.customer === "object" && record.customer !== null ? record.customer : {};
288
+ for (const [path, items, most] of [["customer.taxIds", customer.taxIds, ORDER_TAX_IDS_MAX], ["meta", record.meta, ORDER_META_MAX]]) {
289
+ if (errors.length < 10 && Array.isArray(items) && items.length > most) errors.push(`${path}: expected at most ${most} entries`);
290
+ }
291
+ return errors;
222
292
  }
223
293
  function payloadStrings(payload) {
224
294
  const found = [];
@@ -231,6 +301,7 @@ function payloadStrings(payload) {
231
301
  if (object(item)) for (const key of field === "lines" ? ["clientLineId", "variantId", "title"] : ["clientPaymentId", "method", "reference"]) {
232
302
  found.push([item[key], `${field}[${index}].${key}`, 255]);
233
303
  }
304
+ if (object(item) && field === "payments") found.push([item.methodId, `payments[${index}].methodId`, 64]);
234
305
  });
235
306
  }
236
307
  if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
@@ -252,6 +323,9 @@ function payloadStrings(payload) {
252
323
  const items = object(parent) ? parent.coupons : void 0;
253
324
  if (Array.isArray(items)) items.forEach((item, index) => {
254
325
  if (object(item)) for (const key of prefix ? ["code"] : ["code", "couponId"]) found.push([item[key], `${prefix}coupons[${index}].${key}`, key === "code" ? 255 : 64]);
326
+ if (!prefix && object(item) && Array.isArray(item.lines)) item.lines.forEach((line, j) => {
327
+ if (object(line)) found.push([line.clientLineId, `coupons[${index}].lines[${j}].clientLineId`, 255]);
328
+ });
255
329
  });
256
330
  }
257
331
  if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
@@ -259,6 +333,13 @@ function payloadStrings(payload) {
259
333
  found.push([key, `lines[${index}].attributes`, 255], [value, `lines[${index}].attributes.${key}`, 255]);
260
334
  }
261
335
  if (object(line) && Array.isArray(line.anyAttributes)) line.anyAttributes.forEach((name, i) => found.push([name, `lines[${index}].anyAttributes[${i}]`, 255]));
336
+ if (object(line)) found.push([line.sku, `lines[${index}].sku`, ORDER_LINE_SKU_MAX]);
337
+ });
338
+ if (object(payload.customer) && Array.isArray(payload.customer.taxIds)) payload.customer.taxIds.forEach((taxId, index) => {
339
+ if (object(taxId)) for (const [key, max] of [["type", ORDER_TAX_ID_TYPE_MAX], ["value", ORDER_TAX_ID_VALUE_MAX], ["country", 2]]) found.push([taxId[key], `customer.taxIds[${index}].${key}`, max]);
340
+ });
341
+ if (Array.isArray(payload.meta)) payload.meta.forEach((entry, index) => {
342
+ if (object(entry)) found.push([entry.key, `meta[${index}].key`, ORDER_META_KEY_MAX], [entry.value, `meta[${index}].value`, ORDER_NOTE_MAX]);
262
343
  });
263
344
  if (object(payload.customer)) found.push([payload.customer.email, "customer.email", 254], [payload.customer.customerId, "customer.customerId", void 0]);
264
345
  if (object(payload.customer)) for (const kind of ["billing", "shipping"]) {
@@ -375,9 +456,72 @@ function fiscalFiguresErrors(payload) {
375
456
  }
376
457
 
377
458
  // src/server/versions.ts
378
- var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4, 5, 6, 7, 8];
459
+ var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
379
460
  var SUPPORTED_REGISTER_VERSIONS = [1];
380
461
  var SUPPORTED_ORDER_REFUND_VERSIONS = [1];
462
+ var SUPPORTED_ORDER_REOPEN_VERSIONS = [1];
463
+ var SUPPORTED_ORDER_UPDATE_VERSIONS = [1];
464
+
465
+ // src/server/shape-errors.ts
466
+ function isPlainObject(value) {
467
+ return typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
468
+ }
469
+ function shapeErrors() {
470
+ const errors = [];
471
+ const check2 = (valid, field, expected) => {
472
+ if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`);
473
+ };
474
+ const noNul = (value, field) => {
475
+ if (typeof value === "string") check2(!value.includes("\0"), field, "no NUL character");
476
+ };
477
+ return { errors, check: check2, noNul };
478
+ }
479
+
480
+ // src/server/update-payload-shape.ts
481
+ function updateOnlyErrors(payload) {
482
+ const { errors, check: check2 } = shapeErrors();
483
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
484
+ const body = payload;
485
+ const id = (value, field) => {
486
+ const max = field === "baseRevision" ? 128 : 64;
487
+ check2(typeof value === "string" && value.length > 0 && value.length <= max, field, `a non-empty string of at most ${max} characters`);
488
+ if (typeof value === "string") check2(!value.includes("\0"), field, "no NUL character");
489
+ };
490
+ id(body.orderId, "orderId");
491
+ if (body.baseRevision !== void 0) id(body.baseRevision, "baseRevision");
492
+ check2(Number.isSafeInteger(body.createVersion) && body.createVersion >= 1, "createVersion", "a positive safe integer");
493
+ const seenIds = { storeLineId: /* @__PURE__ */ new Set(), paymentId: /* @__PURE__ */ new Set() };
494
+ for (const [field, key] of [["lines", "storeLineId"], ["fees", "storeLineId"], ["shipping", "storeLineId"], ["payments", "paymentId"]]) {
495
+ const items = body[field], seen = seenIds[key];
496
+ if (!Array.isArray(items)) continue;
497
+ for (const [index, item] of items.entries()) {
498
+ if (typeof item !== "object" || item === null || Array.isArray(item) || item[key] === void 0) continue;
499
+ id(item[key], `${field}[${index}].${key}`);
500
+ check2(!seen.has(item[key]), `${field}[${index}].${key}`, "unique");
501
+ seen.add(item[key]);
502
+ }
503
+ }
504
+ return errors;
505
+ }
506
+ function updatePayloadErrors(payload) {
507
+ const errors = updateOnlyErrors(payload);
508
+ if (errors[0] === "payload: expected an object") return errors;
509
+ return [...errors, ...payloadShapeErrors(orderCreatePart(payload))].slice(0, 10);
510
+ }
511
+ function orderCreatePart(payload) {
512
+ const part = { ...payload };
513
+ for (const key of ["orderId", "baseRevision", "createVersion"]) delete part[key];
514
+ for (const [field, key] of [["lines", "storeLineId"], ["fees", "storeLineId"], ["shipping", "storeLineId"], ["payments", "paymentId"]]) {
515
+ const items = part[field];
516
+ if (Array.isArray(items)) part[field] = items.map((item) => {
517
+ if (typeof item !== "object" || item === null || Array.isArray(item)) return item;
518
+ const copy = { ...item };
519
+ delete copy[key];
520
+ return copy;
521
+ });
522
+ }
523
+ return part;
524
+ }
381
525
 
382
526
  // src/server/batch.ts
383
527
  function validateBatch(body) {
@@ -400,6 +544,8 @@ function validateBatch(body) {
400
544
  else if (![
401
545
  "order.create",
402
546
  "order.refund",
547
+ "order.reopen",
548
+ "order.update",
403
549
  "register.session.open",
404
550
  "register.session.transition",
405
551
  "register.movement.record",
@@ -415,38 +561,52 @@ function validateBatch(body) {
415
561
  }
416
562
  return { ok: true, commands };
417
563
  }
564
+ var rejected = (id, code, message, data) => ({ id, status: "rejected", error: data === void 0 ? { code, message } : { code, message, data } });
565
+ var firstTen = (errors) => errors.slice(0, 10).join("; ");
566
+ function unsupportedOptional(envelope, key, versions, noun) {
567
+ if (versions.includes(envelope.version)) return void 0;
568
+ return rejected(
569
+ envelope.id,
570
+ "unsupported_version",
571
+ `${envelope.type} version ${envelope.version} is not supported; this server ${versions.length ? `supports ${versions.join(", ")}` : `takes no ${noun}`}`,
572
+ { [key]: versions.length ? Math.max(...versions) : 0 }
573
+ );
574
+ }
418
575
  function precheckCommand(envelope, supported) {
419
576
  for (const key of ["orderCreate", "register"]) {
420
577
  if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`);
421
578
  }
422
- if (envelope.type === "order.refund") {
423
- const versions = supported.orderRefund ?? [];
424
- if (!versions.includes(envelope.version)) {
425
- return { id: envelope.id, status: "rejected", error: {
426
- code: "unsupported_version",
427
- message: `order.refund version ${envelope.version} is not supported; this server ${versions.length ? `supports ${versions.join(", ")}` : "takes no refunds"}`,
428
- data: { orderRefund: versions.length ? Math.max(...versions) : 0 }
429
- } };
430
- }
431
- return void 0;
579
+ if (envelope.type === "order.refund") return unsupportedOptional(envelope, "orderRefund", supported.orderRefund ?? [], "refunds");
580
+ if (envelope.type === "order.reopen") return unsupportedOptional(envelope, "orderReopen", supported.orderReopen ?? [], "reopens");
581
+ if (envelope.type === "order.update") {
582
+ const refusal = unsupportedOptional(envelope, "orderUpdate", supported.orderUpdate ?? [], "updates");
583
+ if (refusal) return refusal;
584
+ const payload2 = envelope.payload;
585
+ const createPayload = orderCreatePart(payload2);
586
+ const shape2 = payloadShapeErrors(createPayload);
587
+ const errors2 = updatePayloadErrors(payload2).filter((error) => !shape2.includes(error));
588
+ if (errors2.length) return rejected(envelope.id, "invalid_payload", firstTen(errors2));
589
+ return precheckCommand({ id: envelope.id, type: "order.create", version: payload2.createVersion, payload: createPayload }, supported);
432
590
  }
433
591
  if (envelope.type !== "order.create") {
434
592
  if (!supported.register.includes(envelope.version)) {
435
- return { id: envelope.id, status: "rejected", error: {
436
- code: "unsupported_version",
437
- message: `register version ${envelope.version} is not supported; this server supports ${supported.register.join(", ")}`,
438
- data: { register: Math.max(...supported.register) }
439
- } };
593
+ return rejected(
594
+ envelope.id,
595
+ "unsupported_version",
596
+ `register version ${envelope.version} is not supported; this server supports ${supported.register.join(", ")}`,
597
+ { register: Math.max(...supported.register) }
598
+ );
440
599
  }
441
600
  return void 0;
442
601
  }
443
602
  const command = envelope;
444
603
  if (!supported.orderCreate.includes(command.version)) {
445
- return { id: command.id, status: "rejected", error: {
446
- code: "unsupported_version",
447
- message: `order.create version ${command.version} is not supported; this server supports ${supported.orderCreate.join(", ")}`,
448
- data: { orderCreate: Math.max(...supported.orderCreate) }
449
- } };
604
+ return rejected(
605
+ command.id,
606
+ "unsupported_version",
607
+ `order.create version ${command.version} is not supported; this server supports ${supported.orderCreate.join(", ")}`,
608
+ { orderCreate: Math.max(...supported.orderCreate) }
609
+ );
450
610
  }
451
611
  const { lines, discountMinor } = command.payload;
452
612
  const discounted = discountMinor !== void 0 || Array.isArray(lines) && lines.some((line) => line?.discountMinor !== void 0);
@@ -465,7 +625,16 @@ function precheckCommand(envelope, supported) {
465
625
  if (line?.[field] !== void 0) v6Fields.push(`lines[${index}].${field}`);
466
626
  }
467
627
  });
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;
628
+ const coupons = Array.isArray(payload.coupons) ? payload.coupons.filter((coupon) => typeof coupon === "object" && coupon !== null && !Array.isArray(coupon)) : [];
629
+ const couponLines = coupons.filter((coupon) => coupon.lines !== void 0);
630
+ const couponsWithoutLines = coupons.filter((coupon) => coupon.lines === void 0);
631
+ const paymentsWithMethodId = Array.isArray(payload.payments) && payload.payments.some((payment) => typeof payment === "object" && payment !== null && payment.methodId !== void 0);
632
+ const v12Fields = payload.customer?.taxIds !== void 0 ? ["customer.taxIds"] : [];
633
+ if (Array.isArray(lines)) lines.forEach((line, index) => {
634
+ if (line?.sku !== void 0) v12Fields.push(`lines[${index}].sku`);
635
+ });
636
+ if (payload.meta !== void 0) v12Fields.push("meta");
637
+ 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 < 9 && couponLines.length ? "coupons[].lines requires version 9" : command.version < 10 && paymentsWithMethodId ? "payments[].methodId requires version 10" : command.version < 12 && v12Fields.length ? v12Fields.map((field) => `${field} requires version 12`).join("; ") : command.version >= 9 && couponsWithoutLines.length ? "version 9 requires coupons[].lines" : command.version === 8 && payload.taxAddress === void 0 ? "version 8 requires taxAddress" : command.version >= 9 && command.version < 11 && payload.taxAddress === void 0 && (payload.customer?.billing !== void 0 || payload.customer?.shipping !== void 0) ? "version 9 customer address 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;
469
638
  if (!versionError && Array.isArray(lines)) for (const [index, line] of lines.entries()) {
470
639
  if (line?.custom === void 0 && (typeof line?.variantId !== "string" || !line.variantId.length)) {
471
640
  versionError = `lines[${index}].variantId is required`;
@@ -475,16 +644,16 @@ function precheckCommand(envelope, supported) {
475
644
  if (versionError) break;
476
645
  }
477
646
  if (versionError) {
478
- return { id: command.id, status: "rejected", error: { code: "invalid_payload", message: versionError } };
647
+ return rejected(command.id, "invalid_payload", versionError);
479
648
  }
480
649
  const bounds = payloadBoundErrors(payload);
481
650
  if (bounds.length) {
482
- return { id: command.id, status: "rejected", error: { code: "invalid_payload", message: bounds.slice(0, 10).join("; ") } };
651
+ return rejected(command.id, "invalid_payload", firstTen(bounds));
483
652
  }
484
653
  const shape = payloadShapeErrors(payload);
485
654
  const errors = command.version >= 5 && shape.length ? shape : v3 && display !== void 0 && taxByRate !== void 0 && shape.length === 0 ? fiscalFiguresErrors(payload) : [];
486
655
  if (errors.length) {
487
- return { id: command.id, status: "rejected", error: { code: "invalid_payload", message: errors.slice(0, 10).join("; ") } };
656
+ return rejected(command.id, "invalid_payload", firstTen(errors));
488
657
  }
489
658
  return void 0;
490
659
  }
@@ -504,15 +673,8 @@ function totalWarnings(expectedMinor, serverMinor) {
504
673
 
505
674
  // src/server/register-payload-shape.ts
506
675
  function registerPayloadErrors(type, payload) {
507
- const errors = [];
508
- const object = (value) => typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
509
- const check2 = (valid, field, expected) => {
510
- if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`);
511
- };
512
- if (!object(payload)) return ["payload: expected an object"];
513
- const noNul = (value, field) => {
514
- if (typeof value === "string") check2(!value.includes("\0"), field, "no NUL character");
515
- };
676
+ const { errors, check: check2, noNul } = shapeErrors();
677
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
516
678
  const string = (field, optional = false) => {
517
679
  const value = payload[field];
518
680
  if (optional && value === void 0) return;
@@ -526,8 +688,8 @@ function registerPayloadErrors(type, payload) {
526
688
  const integer = (field, min = -Infinity) => check2(Number.isSafeInteger(payload[field]) && payload[field] >= min, field, `a safe integer >= ${min}`);
527
689
  const record = (field) => {
528
690
  const value = payload[field];
529
- check2(object(value), field, "a record of integers");
530
- if (object(value)) for (const [key, amount] of Object.entries(value)) {
691
+ check2(isPlainObject(value), field, "a record of integers");
692
+ if (isPlainObject(value)) for (const [key, amount] of Object.entries(value)) {
531
693
  check2(key.length > 0 && Number.isSafeInteger(amount), `${field}.${key}`, "a non-empty key with a safe integer");
532
694
  noNul(key, `${field}.${JSON.stringify(key)}`);
533
695
  }
@@ -618,15 +780,8 @@ function registerPayloadErrors(type, payload) {
618
780
 
619
781
  // src/server/refund-payload-shape.ts
620
782
  function refundPayloadErrors(payload) {
621
- const errors = [];
622
- const object = (value) => typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
623
- const check2 = (valid, field, expected) => {
624
- if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`);
625
- };
626
- if (!object(payload)) return ["payload: expected an object"];
627
- const noNul = (value, field) => {
628
- if (typeof value === "string") check2(!value.includes("\0"), field, "no NUL character");
629
- };
783
+ const { errors, check: check2, noNul } = shapeErrors();
784
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
630
785
  const fields = [
631
786
  "clientRefundId",
632
787
  "orderId",
@@ -661,7 +816,7 @@ function refundPayloadErrors(payload) {
661
816
  const seen = /* @__PURE__ */ new Set();
662
817
  if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
663
818
  const path = `lines[${index}]`;
664
- if (!object(line)) {
819
+ if (!isPlainObject(line)) {
665
820
  check2(false, path, "an object");
666
821
  return;
667
822
  }
@@ -704,41 +859,34 @@ function refundPayloadErrors(payload) {
704
859
  return errors;
705
860
  }
706
861
 
707
- // src/server/register-figures.ts
708
- function deriveSessionFigures(input) {
709
- const expected = Object.assign(/* @__PURE__ */ Object.create(null), { cash: input.countedFloatMinor });
710
- for (const order of input.orders) {
711
- if (!Array.isArray(order.payments)) continue;
712
- for (const payment of order.payments) {
713
- if (typeof payment?.method !== "string" || !payment.method.length || !Number.isSafeInteger(payment.amountMinor)) continue;
714
- expected[payment.method] = (expected[payment.method] ?? 0) + payment.amountMinor;
862
+ // src/server/reopen-payload-shape.ts
863
+ function reopenPayloadErrors(payload) {
864
+ const { errors, check: check2, noNul } = shapeErrors();
865
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
866
+ const fields = ["orderId", "clientOrderId", "baseRevision", "cashierRef", "registerId", "storeId", "createdAt"];
867
+ for (const key of Object.keys(payload)) {
868
+ if (!fields.includes(key) && errors.length < 10) {
869
+ errors.push(`${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.reopen version 1`);
715
870
  }
716
871
  }
717
- const voided = new Set(input.movements.filter((row) => row.type === "void").map((row) => row.voids));
718
- for (const row of input.movements) {
719
- if (row.type === "void" || voided.has(row.id)) continue;
720
- if (row.type === "paid_in") expected.cash += row.amountMinor;
721
- if (row.type === "paid_out") expected.cash -= row.amountMinor;
722
- }
723
- let refundsTotalMinor = 0;
724
- for (const refund of input.refunds ?? []) {
725
- if (typeof refund !== "object" || refund === null) continue;
726
- const byMethod = refund.byMethod;
727
- if (typeof byMethod !== "object" || byMethod === null || Object.getPrototypeOf(byMethod) !== Object.prototype && Object.getPrototypeOf(byMethod) !== null) continue;
728
- for (const [method, amount] of Object.entries(byMethod)) {
729
- if (!method.length || !Number.isSafeInteger(amount) || amount < 0) continue;
730
- expected[method] = (expected[method] ?? 0) - amount;
731
- refundsTotalMinor += amount;
732
- }
872
+ for (const field of ["orderId", "cashierRef", "registerId", "clientOrderId", "baseRevision", "storeId"]) {
873
+ const value = payload[field];
874
+ if (["clientOrderId", "baseRevision", "storeId"].includes(field) && value === void 0) continue;
875
+ const max = field === "baseRevision" ? 128 : 64;
876
+ check2(
877
+ typeof value === "string" && value.length > 0 && value.length <= max,
878
+ field,
879
+ `a non-empty string of at most ${max} characters`
880
+ );
881
+ noNul(value, field);
733
882
  }
734
- return {
735
- expected: { ...expected },
736
- salesCount: input.orders.length,
737
- ...input.refunds !== void 0 ? { refundsTotalMinor } : {}
738
- };
739
- }
740
- function deriveVariance(counted, expected) {
741
- return Object.fromEntries(Object.entries(counted).map(([key, value]) => [key, value - (expected[key] ?? 0)]));
883
+ check2(
884
+ typeof payload.createdAt === "string" && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
885
+ "createdAt",
886
+ "a valid date"
887
+ );
888
+ noNul(payload.createdAt, "createdAt");
889
+ return errors;
742
890
  }
743
891
 
744
892
  // src/server/rejection-codes.ts
@@ -768,6 +916,12 @@ var toHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0"))
768
916
  var newId = () => toHex(randomBytes(16));
769
917
  var newSecret = () => btoa(String.fromCharCode(...randomBytes(16))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
770
918
  var sha256Hex = async (text) => toHex(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))));
919
+ function sameText(x, y) {
920
+ if (x.length !== y.length) return false;
921
+ let diff = 0;
922
+ for (let i = 0; i < x.length; i += 1) diff |= x.charCodeAt(i) ^ y.charCodeAt(i);
923
+ return diff === 0;
924
+ }
771
925
  function randomDigits(digits) {
772
926
  const range = 10 ** digits, limit = Math.floor(2 ** 32 / range) * range;
773
927
  for (; ; ) {
@@ -790,6 +944,7 @@ function createMemoryDisplaySignalling(options = {}) {
790
944
  const codes = /* @__PURE__ */ new Map(), pending = /* @__PURE__ */ new Map(), displays = /* @__PURE__ */ new Map();
791
945
  const snapshots = /* @__PURE__ */ new Map(), sources = /* @__PURE__ */ new Map();
792
946
  const displayInbox = /* @__PURE__ */ new Map(), tillInbox = /* @__PURE__ */ new Map();
947
+ const devices = /* @__PURE__ */ new Map(), adoptions = [];
793
948
  let storeWindow = null;
794
949
  const dropDisplay = (displayId) => [displays, snapshots, displayInbox].forEach((map) => map.delete(displayId));
795
950
  const prune = () => {
@@ -800,6 +955,8 @@ function createMemoryDisplaySignalling(options = {}) {
800
955
  for (const [displayId, row] of displays) if (now >= (row.lastSeenAt ?? row.confirmedAt) + ROW_TTL) dropDisplay(displayId);
801
956
  for (const [key, window] of sources) if (now >= window.openedAt + SOURCE_WINDOW) sources.delete(key);
802
957
  if (storeWindow && now >= storeWindow.openedAt + STORE_WINDOW) storeWindow = null;
958
+ const owns = (id) => [...displays.values(), ...codes.values(), ...pending.values()].some((entry) => entry.deviceId === id);
959
+ for (const [id, device] of devices) if (now > device.lastCallAt + ROW_TTL && !owns(id)) devices.delete(id);
803
960
  return now;
804
961
  };
805
962
  const admit = (ctx) => {
@@ -808,6 +965,14 @@ function createMemoryDisplaySignalling(options = {}) {
808
965
  if (!session || !session.capabilities.includes(DISPLAY_PAIR_CAPABILITY)) throw fail("forbidden");
809
966
  return { now, cashierId: session.cashierId };
810
967
  };
968
+ const tillCall = async (ctx, device) => {
969
+ const keyHash = typeof device.deviceKey === "string" && device.deviceKey !== "" ? await sha256Hex(device.deviceKey) : "";
970
+ const admitted = admit(ctx);
971
+ const known = devices.get(device.deviceId);
972
+ if (!known || known.keyHash === null || !sameText(keyHash, known.keyHash)) throw fail("device_refused");
973
+ known.lastCallAt = admitted.now;
974
+ return { ...admitted, deviceId: device.deviceId };
975
+ };
811
976
  const ownedIn = (map, deviceId, id) => {
812
977
  const entry = map.get(id);
813
978
  if (!entry || entry.deviceId !== deviceId) throw fail("not_found");
@@ -829,8 +994,18 @@ function createMemoryDisplaySignalling(options = {}) {
829
994
  return fail("claim_refused");
830
995
  };
831
996
  const signalling = {
832
- async mint(ctx, deviceId) {
833
- const { now } = admit(ctx);
997
+ async registerDevice(ctx, deviceId) {
998
+ const deviceKey = newSecret();
999
+ const keyHash = await sha256Hex(deviceKey);
1000
+ const { now, cashierId } = admit(ctx);
1001
+ const known = devices.get(deviceId);
1002
+ if (known && (known.keyHash !== null || known.adopted)) throw fail("device_refused");
1003
+ if (known) adoptions.push({ deviceId, cashierId });
1004
+ devices.set(deviceId, { keyHash, adopted: known !== void 0, lastCallAt: now });
1005
+ return { deviceKey };
1006
+ },
1007
+ async mint(ctx, device) {
1008
+ const { now, deviceId } = await tillCall(ctx, device);
834
1009
  const unspent = [...codes.values()].filter((entry) => entry.deviceId === deviceId && !entry.spent).length;
835
1010
  if (unspent >= MAX_UNSPENT) throw fail("limit");
836
1011
  let code;
@@ -840,12 +1015,12 @@ function createMemoryDisplaySignalling(options = {}) {
840
1015
  codes.set(code, { deviceId, expiresAt: now + CODE_TTL, spent: false });
841
1016
  return { code, expiresAt: iso(now + CODE_TTL) };
842
1017
  },
843
- async pending(ctx, deviceId) {
844
- admit(ctx);
1018
+ async pending(ctx, device) {
1019
+ const { deviceId } = await tillCall(ctx, device);
845
1020
  return [...pending].filter(([, entry]) => entry.deviceId === deviceId).map(([claimId, entry]) => ({ claimId, displayName: entry.displayName, checkCode: entry.checkCode, expiresAt: iso(entry.expiresAt) }));
846
1021
  },
847
- async confirm(ctx, deviceId, claimId) {
848
- const { now, cashierId } = admit(ctx);
1022
+ async confirm(ctx, device, claimId) {
1023
+ const { now, cashierId, deviceId } = await tillCall(ctx, device);
849
1024
  const entry = ownedIn(pending, deviceId, claimId);
850
1025
  pending.delete(claimId);
851
1026
  const moving = entry.movingDisplayId !== null && displays.has(entry.movingDisplayId) ? entry.movingDisplayId : null;
@@ -853,13 +1028,13 @@ function createMemoryDisplaySignalling(options = {}) {
853
1028
  const row = { deviceId, name: entry.displayName, cashierId, confirmedAt: now, lastSeenAt: null, tokenHash: null, secretHash: entry.secretHash };
854
1029
  displays.set(moving ?? newId(), row);
855
1030
  },
856
- async decline(ctx, deviceId, claimId) {
857
- admit(ctx);
1031
+ async decline(ctx, device, claimId) {
1032
+ const { deviceId } = await tillCall(ctx, device);
858
1033
  ownedIn(pending, deviceId, claimId);
859
1034
  pending.delete(claimId);
860
1035
  },
861
- async list(ctx, deviceId) {
862
- const { now } = admit(ctx);
1036
+ async list(ctx, device) {
1037
+ const { now, deviceId } = await tillCall(ctx, device);
863
1038
  return [...displays].filter(([, row]) => row.deviceId === deviceId).map(([displayId, row]) => ({
864
1039
  displayId,
865
1040
  name: row.name,
@@ -868,22 +1043,22 @@ function createMemoryDisplaySignalling(options = {}) {
868
1043
  connected: row.lastSeenAt !== null && now - row.lastSeenAt <= CONNECTED_MS
869
1044
  }));
870
1045
  },
871
- async forget(ctx, deviceId, displayId) {
872
- admit(ctx);
1046
+ async forget(ctx, device, displayId) {
1047
+ const { deviceId } = await tillCall(ctx, device);
873
1048
  ownedIn(displays, deviceId, displayId);
874
1049
  dropDisplay(displayId);
875
1050
  },
876
- async sendSignal(ctx, deviceId, displayId, message) {
877
- admit(ctx);
1051
+ async sendSignal(ctx, device, displayId, message) {
1052
+ const { deviceId } = await tillCall(ctx, device);
878
1053
  ownedIn(displays, deviceId, displayId);
879
1054
  displayInbox.set(displayId, [...displayInbox.get(displayId) ?? [], { type: message.type, payload: message.payload }]);
880
1055
  },
881
- async receiveSignals(ctx, deviceId) {
882
- admit(ctx);
1056
+ async receiveSignals(ctx, device) {
1057
+ const { deviceId } = await tillCall(ctx, device);
883
1058
  return drain(tillInbox, deviceId).filter((message) => displays.get(message.displayId)?.deviceId === deviceId);
884
1059
  },
885
- async postSnapshot(ctx, deviceId, displayId, body) {
886
- const { now } = admit(ctx);
1060
+ async postSnapshot(ctx, device, displayId, body) {
1061
+ const { now, deviceId } = await tillCall(ctx, device);
887
1062
  ownedIn(displays, deviceId, displayId);
888
1063
  const text = JSON.stringify(body) ?? "null";
889
1064
  if (new TextEncoder().encode(text).length > SNAPSHOT_MAX_BYTES) throw fail("too_large");
@@ -902,7 +1077,7 @@ function createMemoryDisplaySignalling(options = {}) {
902
1077
  let checkCode;
903
1078
  do
904
1079
  checkCode = randomDigits(4);
905
- while ([...pending.values()].some((other) => other.checkCode === checkCode));
1080
+ while ([...pending.values()].some((other) => other.deviceId === entry.deviceId && other.checkCode === checkCode));
906
1081
  const movingDisplayId = tokenHash === null ? null : findByTokenHash(tokenHash)?.[0] ?? null;
907
1082
  pending.set(newId(), { deviceId: entry.deviceId, secretHash, displayName, checkCode, expiresAt: entry.expiresAt, movingDisplayId });
908
1083
  return { claimSecret, checkCode };
@@ -953,6 +1128,7 @@ function createMemoryDisplaySignalling(options = {}) {
953
1128
  prune();
954
1129
  return JSON.stringify({
955
1130
  sessions: [...sessions],
1131
+ devices: [...devices],
956
1132
  codes: [...codes],
957
1133
  pending: [...pending],
958
1134
  displays: [...displays],
@@ -965,8 +1141,15 @@ function createMemoryDisplaySignalling(options = {}) {
965
1141
  },
966
1142
  async storedCounts() {
967
1143
  prune();
968
- return { codes: codes.size, pending: pending.size, displays: displays.size, snapshots: snapshots.size };
969
- }
1144
+ return { codes: codes.size, pending: pending.size, displays: displays.size, snapshots: snapshots.size, devices: devices.size };
1145
+ },
1146
+ async seedLegacyDevice(deviceId) {
1147
+ const token = newSecret(), displayId = newId(), now = clock();
1148
+ devices.set(deviceId, { keyHash: null, adopted: false, lastCallAt: now });
1149
+ displays.set(displayId, { deviceId, name: "Legacy", cashierId: "cashier-legacy", confirmedAt: now, lastSeenAt: null, tokenHash: await sha256Hex(token), secretHash: null });
1150
+ return { displayId, token };
1151
+ },
1152
+ adoptionLog: async () => adoptions.map((entry) => ({ ...entry }))
970
1153
  };
971
1154
  return { signalling, harness };
972
1155
  }
@@ -998,50 +1181,84 @@ function unusedCode(...used) {
998
1181
  if (!used.includes(code)) return code;
999
1182
  }
1000
1183
  }
1184
+ var KEY_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1185
+ var randomKey = () => Array.from(globalThis.crypto.getRandomValues(new Uint8Array(22)), (n) => KEY_ALPHABET[n & 63]).join("");
1001
1186
  async function world(make) {
1002
1187
  const h = await make();
1003
1188
  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) };
1189
+ const [a, b, viewer] = [await till("cashier-a"), await till("cashier-b"), await till("cashier-viewer", false)];
1190
+ const da = { deviceId: A, deviceKey: (await h.signalling.registerDevice(a, A)).deviceKey };
1191
+ const db = { deviceId: B, deviceKey: (await h.signalling.registerDevice(b, B)).deviceKey };
1192
+ return { h, s: h.signalling, a, b, viewer, da, db };
1005
1193
  }
1006
- async function claimed(w, ctx, deviceId, d, name, token) {
1007
- const { code } = await w.s.mint(ctx, deviceId);
1194
+ async function claimed(w, ctx, device, d, name, token) {
1195
+ const { code } = await w.s.mint(ctx, device);
1008
1196
  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);
1197
+ const entry = (await w.s.pending(ctx, device)).find((p) => p.checkCode === claim.checkCode);
1010
1198
  check(entry && entry.displayName === name, `the pending listing lacks the claim by ${name}`);
1011
1199
  return { code, claim, claimId: entry.claimId };
1012
1200
  }
1013
- async function paired(w, ctx, deviceId, source, name, token) {
1201
+ async function paired(w, ctx, device, source, name, token) {
1014
1202
  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);
1203
+ const { claim, claimId } = await claimed(w, ctx, device, d, name, token);
1204
+ await w.s.confirm(ctx, device, claimId);
1017
1205
  const result = await w.s.collect(d, claim.claimSecret);
1018
1206
  check(result.status === "paired", `collect after the confirm gave ${result.status}`);
1019
1207
  return { d, claim, displayId: result.displayId, token: result.token };
1020
1208
  }
1209
+ async function armed(w) {
1210
+ const shown = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1211
+ await w.s.postSnapshot(w.a, w.da, shown.displayId, { v: 1 });
1212
+ await w.s.displaySendSignal(shown.d, shown.token, { type: "answer", payload: "a1" });
1213
+ const { claimId } = await claimed(w, w.a, w.da, w.h.display("192.0.2.2"), "Waiting");
1214
+ return { ...shown, claimId };
1215
+ }
1216
+ var tillCalls = (w, device, displayId, claimId) => [
1217
+ ["mint", () => w.s.mint(w.a, device)],
1218
+ ["pending", () => w.s.pending(w.a, device)],
1219
+ ["confirm", () => w.s.confirm(w.a, device, claimId)],
1220
+ ["decline", () => w.s.decline(w.a, device, claimId)],
1221
+ ["list", () => w.s.list(w.a, device)],
1222
+ ["forget", () => w.s.forget(w.a, device, displayId)],
1223
+ ["sendSignal", () => w.s.sendSignal(w.a, device, displayId, { type: "offer", payload: "o2" })],
1224
+ ["receiveSignals", () => w.s.receiveSignals(w.a, device)],
1225
+ ["postSnapshot", () => w.s.postSnapshot(w.a, device, displayId, { v: 2 })]
1226
+ ];
1227
+ var refusedDevices = (w) => [
1228
+ ["a missing key", { deviceId: A, deviceKey: "" }],
1229
+ ["a wrong key", { deviceId: A, deviceKey: randomKey() }],
1230
+ ["B's key on A's id", { deviceId: A, deviceKey: w.db.deviceKey }],
1231
+ ["an unregistered id", { deviceId: "till-never", deviceKey: w.da.deviceKey }]
1232
+ ];
1233
+ async function adopted(w) {
1234
+ const legacy = await w.h.seedLegacyDevice("till-legacy");
1235
+ const device = { deviceId: "till-legacy", deviceKey: (await w.s.registerDevice(w.a, "till-legacy")).deviceKey };
1236
+ return { ...legacy, device };
1237
+ }
1021
1238
  function displaySignallingContract(makeHarness) {
1022
1239
  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");
1240
+ "mint without the capability is forbidden and makes no code": async ({ h, s, viewer, da }) => {
1241
+ await expectRefusal(s.mint(viewer, da), "forbidden", "mint without the capability");
1025
1242
  check((await h.storedCounts()).codes === 0, "a refused mint stored a code");
1026
1243
  },
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);
1244
+ "a minted code is at least 6 digits and expires within 10 minutes": async ({ h, s, a, da }) => {
1245
+ const { code, expiresAt } = await s.mint(a, da);
1029
1246
  check(/^\d{6,}$/.test(code), `code ${code} is not 6 or more digits`);
1030
1247
  check(!Number.isNaN(Date.parse(expiresAt)), `expiresAt ${expiresAt} is not a date`);
1031
1248
  await h.advance(10 * MINUTE2);
1032
1249
  await expectRefusal(s.claim(h.display("192.0.2.1"), { code, displayName: "Late" }), "claim_refused", "a claim 10 minutes after the mint");
1033
1250
  },
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");
1251
+ "a device holds at most 5 unspent codes, and expired codes stop counting": async ({ h, s, a, da }) => {
1252
+ for (let i = 0; i < 5; i += 1) await s.mint(a, da);
1253
+ await expectRefusal(s.mint(a, da), "limit", "the 6th unspent code");
1037
1254
  await h.advance(10 * MINUTE2);
1038
- await s.mint(a, A);
1255
+ await s.mint(a, da);
1039
1256
  },
1040
- "spent, expired and unknown codes get the same claim refusal": async ({ h, s, a }) => {
1041
- const spent = (await s.mint(a, A)).code;
1257
+ "spent, expired and unknown codes get the same claim refusal": async ({ h, s, a, da }) => {
1258
+ const spent = (await s.mint(a, da)).code;
1042
1259
  await s.claim(h.display("192.0.2.1"), { code: spent, displayName: "First" });
1043
1260
  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;
1261
+ const expired = (await s.mint(a, da)).code;
1045
1262
  await h.advance(10 * MINUTE2);
1046
1263
  const late = await expectRefusal(s.claim(h.display("192.0.2.3"), { code: expired, displayName: "Late" }), "claim_refused", "an expired code");
1047
1264
  const unknown = await expectRefusal(s.claim(h.display("192.0.2.4"), { code: unusedCode(spent, expired), displayName: "Guess" }), "claim_refused", "an unknown code");
@@ -1050,23 +1267,23 @@ function displaySignallingContract(makeHarness) {
1050
1267
  },
1051
1268
  "a claim issues no token: collect gives pending with its check code": async (w) => {
1052
1269
  const d = w.h.display("192.0.2.1");
1053
- const { claim } = await claimed(w, w.a, A, d, "Counter");
1270
+ const { claim } = await claimed(w, w.a, w.da, d, "Counter");
1054
1271
  const result = await w.s.collect(d, claim.claimSecret);
1055
1272
  check(result.status === "pending" && result.checkCode === claim.checkCode, `collect before the confirm gave ${JSON.stringify(result)}`);
1056
1273
  },
1057
1274
  "the check code matches on both screens, and two live claims never share one": async (w) => {
1058
1275
  const d = w.h.display("192.0.2.1");
1059
- const first = await claimed(w, w.a, A, d, "One");
1276
+ const first = await claimed(w, w.a, w.da, d, "One");
1060
1277
  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);
1278
+ const listed = (await w.s.pending(w.a, w.da)).find((p) => p.claimId === first.claimId);
1062
1279
  const collected = await w.s.collect(d, first.claim.claimSecret);
1063
1280
  check(listed?.checkCode === first.claim.checkCode, "the till lists another check code");
1064
1281
  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");
1282
+ const second = await claimed(w, w.a, w.da, w.h.display("192.0.2.2"), "Two");
1066
1283
  check(second.claim.checkCode !== first.claim.checkCode, "two live claims share a check code");
1067
1284
  },
1068
1285
  "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");
1286
+ const { d, claim, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1070
1287
  check(SECRET.test(token), "the token is not 22+ base64url characters");
1071
1288
  const again = await expectRefusal(w.s.collect(d, claim.claimSecret), "collect_refused", "a second collect");
1072
1289
  const unknown = await expectRefusal(w.s.collect(d, "AAAAAAAAAAAAAAAAAAAAAA"), "collect_refused", "an unknown secret");
@@ -1074,32 +1291,32 @@ function displaySignallingContract(makeHarness) {
1074
1291
  },
1075
1292
  "a decline, or an unconfirmed claim whose code expires, issues nothing": async (w) => {
1076
1293
  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);
1294
+ const declined = await claimed(w, w.a, w.da, d, "Declined");
1295
+ await w.s.decline(w.a, w.da, declined.claimId);
1079
1296
  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");
1297
+ const lapsed = await claimed(w, w.a, w.da, d, "Lapsed");
1081
1298
  await w.h.advance(10 * MINUTE2);
1082
1299
  await expectRefusal(w.s.collect(d, lapsed.claim.claimSecret), "collect_refused", "collect after the code expired");
1083
1300
  check((await w.h.storedCounts()).pending === 0, "a pending pairing outlived its decline or its code");
1084
1301
  },
1085
1302
  "a confirm needs the capability and the minting device": async (w) => {
1086
1303
  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");
1304
+ const { claim, claimId } = await claimed(w, w.a, w.da, d, "Counter");
1305
+ await expectRefusal(w.s.confirm(w.viewer, w.da, claimId), "forbidden", "a confirm without the capability");
1306
+ await expectRefusal(w.s.confirm(w.b, w.db, claimId), "not_found", "a confirm from another device");
1090
1307
  check((await w.s.collect(d, claim.claimSecret)).status === "pending", "a refused confirm changed the claim");
1091
1308
  },
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);
1309
+ "one source is limited to 10 failed claims a minute, and a limited claim spends nothing": async ({ h, s, a, da }) => {
1310
+ const { code } = await s.mint(a, da);
1094
1311
  const guesser = h.display("198.51.100.7");
1095
1312
  for (let i = 0; i < 10; i += 1) await expectRefusal(s.claim(guesser, { code: unusedCode(code), displayName: "Guess" }), "claim_refused", "a wrong code");
1096
1313
  await expectRefusal(s.claim(guesser, { code, displayName: "Guess" }), "claim_refused", "a valid code from a limited source");
1097
1314
  await s.claim(h.display("198.51.100.8"), { code, displayName: "Other" });
1098
1315
  await h.advance(MINUTE2);
1099
- await s.claim(guesser, { code: (await s.mint(a, A)).code, displayName: "Later" });
1316
+ await s.claim(guesser, { code: (await s.mint(a, da)).code, displayName: "Later" });
1100
1317
  },
1101
- "two IPv6 addresses in one /64 share a limit": async ({ h, s, a }) => {
1102
- const { code } = await s.mint(a, A);
1318
+ "two IPv6 addresses in one /64 share a limit": async ({ h, s, a, da }) => {
1319
+ const { code } = await s.mint(a, da);
1103
1320
  const one = h.display("2001:db8:0:1::5");
1104
1321
  const two = h.display("2001:db8:0:1:ffff::9");
1105
1322
  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");
@@ -1107,63 +1324,63 @@ function displaySignallingContract(makeHarness) {
1107
1324
  await expectRefusal(s.claim(two, { code, displayName: "Guess" }), "claim_refused", "a valid code from a limited /64");
1108
1325
  await s.claim(h.display("2001:db8:0:2::5"), { code, displayName: "Other" });
1109
1326
  },
1110
- "100 failed claims store-wide pause every claim for 10 minutes": async ({ h, s, a }) => {
1111
- const { code } = await s.mint(a, A);
1327
+ "100 failed claims store-wide pause every claim for 10 minutes": async ({ h, s, a, da }) => {
1328
+ const { code } = await s.mint(a, da);
1112
1329
  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
1330
  await expectRefusal(s.claim(h.display("203.0.113.200"), { code, displayName: "Shop" }), "claim_refused", "a valid code while paused");
1114
1331
  await h.advance(10 * MINUTE2);
1115
- await s.claim(h.display("203.0.113.201"), { code: (await s.mint(a, A)).code, displayName: "Shop" });
1332
+ await s.claim(h.display("203.0.113.201"), { code: (await s.mint(a, da)).code, displayName: "Shop" });
1116
1333
  },
1117
1334
  "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");
1335
+ const { claim, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1119
1336
  const text = await w.h.storedText();
1120
1337
  check(SECRET.test(claim.claimSecret), "the claim secret is not 22+ base64url characters");
1121
1338
  check(!text.includes(claim.claimSecret) && !text.includes(token), "the claim secret or the token is stored");
1122
1339
  check(text.includes(await sha256Hex(token)), "the token's SHA-256 hex is not stored");
1123
1340
  },
1124
1341
  "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);
1342
+ const { d, displayId, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1343
+ const row = (await w.s.list(w.a, w.da)).find((r) => r.displayId === displayId);
1127
1344
  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");
1345
+ check(!(await w.s.list(w.b, w.db)).some((r) => r.displayId === displayId), "another device lists the display");
1129
1346
  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");
1347
+ check((await w.s.list(w.a, w.da))[0]?.connected === true, "a display just seen is not connected");
1131
1348
  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");
1349
+ check((await w.s.list(w.a, w.da))[0]?.connected === false, "a display unseen for 31 s is connected");
1133
1350
  },
1134
1351
  "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 });
1352
+ const { d, displayId, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1353
+ await w.s.postSnapshot(w.a, w.da, displayId, { v: 1 });
1137
1354
  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);
1355
+ await expectRefusal(w.s.forget(w.b, w.db, displayId), "not_found", "forget from another device");
1356
+ check((await w.s.list(w.a, w.da)).length === 1, "a refused forget removed the display");
1357
+ await w.s.forget(w.a, w.da, displayId);
1141
1358
  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");
1359
+ check((await w.s.list(w.a, w.da)).length === 0, "the owner still lists a forgotten display");
1360
+ check((await w.s.receiveSignals(w.a, w.da)).every((m) => m.displayId !== displayId), "the till received from a forgotten display");
1144
1361
  const counts = await w.h.storedCounts();
1145
1362
  check(counts.displays === 0 && counts.snapshots === 0, `forget left ${JSON.stringify(counts)}`);
1146
1363
  },
1147
1364
  "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" });
1365
+ const first = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1366
+ await w.s.postSnapshot(w.a, w.da, first.displayId, { v: 1 });
1367
+ await w.s.sendSignal(w.a, w.da, first.displayId, { type: "offer", payload: "o1" });
1151
1368
  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);
1369
+ const moved = await paired(w, w.b, w.db, "192.0.2.1", "Counter", first.token);
1153
1370
  check(await w.s.readSnapshot(moved.d, moved.token) === null, "the first till's snapshot survived the move");
1154
1371
  check((await w.s.displayReceiveSignals(moved.d, moved.token)).length === 0, "the first till's signal survived the move");
1155
1372
  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");
1373
+ check((await w.s.receiveSignals(w.a, w.da)).every((m) => m.displayId !== first.displayId), "the first till received from a moved display");
1374
+ check((await w.s.list(w.a, w.da)).length === 0, "the first till still lists a moved display");
1375
+ check((await w.s.list(w.b, w.db)).some((r) => r.displayId === first.displayId) && moved.displayId === first.displayId, "the moved display has a new id");
1159
1376
  await expectRefusal(w.s.readSnapshot(first.d, first.token), "token_refused", "the old token after a move");
1160
1377
  },
1161
1378
  "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" });
1379
+ const x = await paired(w, w.a, w.da, "192.0.2.1", "X");
1380
+ const y = await paired(w, w.a, w.da, "192.0.2.2", "Y");
1381
+ const z = await paired(w, w.b, w.db, "192.0.2.3", "Z");
1382
+ await w.s.sendSignal(w.a, w.da, x.displayId, { type: "offer", payload: "o1" });
1383
+ await w.s.sendSignal(w.a, w.da, x.displayId, { type: "ice", payload: "i1" });
1167
1384
  const atX = await w.s.displayReceiveSignals(x.d, x.token);
1168
1385
  check(atX.map((m) => m.payload).join() === "o1,i1", `display X received ${JSON.stringify(atX)}`);
1169
1386
  check((await w.s.displayReceiveSignals(x.d, x.token)).length === 0, "display X received a message twice");
@@ -1171,33 +1388,120 @@ function displaySignallingContract(makeHarness) {
1171
1388
  await w.s.displaySendSignal(x.d, x.token, { type: "answer", payload: "a1" });
1172
1389
  await w.s.displaySendSignal(x.d, x.token, { type: "ice", payload: "i2" });
1173
1390
  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);
1391
+ check((await w.s.receiveSignals(w.b, w.db)).every((m) => m.displayId === z.displayId), "device B received device A's display");
1392
+ const atA = await w.s.receiveSignals(w.a, w.da);
1176
1393
  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");
1394
+ check((await w.s.receiveSignals(w.a, w.da)).length === 0, "till A received a message twice");
1178
1395
  },
1179
1396
  "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");
1397
+ const { d, displayId, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1181
1398
  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 });
1399
+ await w.s.postSnapshot(w.a, w.da, displayId, { seq: 1 });
1400
+ await w.s.postSnapshot(w.a, w.da, displayId, { seq: 2 });
1184
1401
  check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"seq":2}', "the latest snapshot is not served");
1185
1402
  await w.h.advance(61e3);
1186
1403
  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");
1404
+ await w.s.postSnapshot(w.a, w.da, displayId, { seq: 3 });
1405
+ await expectRefusal(w.s.postSnapshot(w.a, w.da, displayId, { pad: "x".repeat(204800) }), "too_large", "a snapshot over 200 KiB");
1189
1406
  check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"seq":3}', "a refused snapshot replaced the previous one");
1190
1407
  },
1191
1408
  "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);
1409
+ const { d, token } = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1410
+ await w.s.mint(w.a, w.da);
1194
1411
  await w.h.advance(10 * MINUTE2);
1195
- await w.s.list(w.a, A);
1412
+ await w.s.list(w.a, w.da);
1196
1413
  check((await w.h.storedCounts()).codes === 0, "an expired code is still stored");
1197
1414
  await w.h.advance(30 * DAY);
1198
- await w.s.list(w.a, A);
1415
+ await w.s.list(w.a, w.da);
1199
1416
  check((await w.h.storedCounts()).displays === 0, "a display unseen for 30 days is still stored");
1200
1417
  await expectRefusal(w.s.readSnapshot(d, token), "token_refused", "a pruned display");
1418
+ },
1419
+ "K1: registerDevice needs the capability, and issues a 22+ character base64url key": async (w) => {
1420
+ const before = (await w.h.storedCounts()).devices;
1421
+ await expectRefusal(w.s.registerDevice(w.viewer, "till-c"), "forbidden", "a register without the capability");
1422
+ check((await w.h.storedCounts()).devices === before, "a refused register stored a device");
1423
+ check(SECRET.test((await w.s.registerDevice(w.a, "till-c")).deviceKey), "the device key is not 22+ base64url characters");
1424
+ },
1425
+ "K2: an id that holds a key cannot register again, by any cashier": async (w) => {
1426
+ await expectRefusal(w.s.registerDevice(w.a, A), "device_refused", "a second register by the same cashier");
1427
+ await expectRefusal(w.s.registerDevice(w.b, A), "device_refused", "a second register by another cashier");
1428
+ await w.s.list(w.a, w.da);
1429
+ },
1430
+ "K3: every till call refuses a missing, wrong, swapped or unregistered key the same way": async (w) => {
1431
+ const { displayId, claimId } = await armed(w);
1432
+ for (const [method] of tillCalls(w, w.da, displayId, claimId)) {
1433
+ const refusals = [];
1434
+ for (const [what, device] of refusedDevices(w)) {
1435
+ const call = tillCalls(w, device, displayId, claimId).find(([name]) => name === method)[1];
1436
+ refusals.push(await expectRefusal(call(), "device_refused", `${method} with ${what}`));
1437
+ }
1438
+ refusals.forEach((refusal, i) => sameRefusal(refusals[0], refusal, `${method}: refusal ${i}`));
1439
+ }
1440
+ },
1441
+ "K4: a refused till call has no effect": async (w) => {
1442
+ const { d, token, displayId, claimId } = await armed(w);
1443
+ const before = JSON.stringify(await w.h.storedCounts());
1444
+ for (const [, device] of refusedDevices(w)) {
1445
+ for (const [method, call] of tillCalls(w, device, displayId, claimId)) await expectRefusal(call(), "device_refused", method);
1446
+ }
1447
+ const after = JSON.stringify(await w.h.storedCounts());
1448
+ check(after === before, `refused calls changed the stored counts from ${before} to ${after}`);
1449
+ check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"v":1}', "a refused postSnapshot replaced the snapshot");
1450
+ check((await w.s.displayReceiveSignals(d, token)).length === 0, "a refused sendSignal queued a message");
1451
+ check((await w.s.receiveSignals(w.a, w.da)).map((m) => m.payload).join() === "a1", "a refused receiveSignals drained the inbox");
1452
+ },
1453
+ "K5: a wrong key gets device_refused, never not_found, on an owned and on a foreign display": async (w) => {
1454
+ const own = await paired(w, w.a, w.da, "192.0.2.1", "Own");
1455
+ const foreign = await paired(w, w.b, w.db, "192.0.2.2", "Foreign");
1456
+ const wrong = { deviceId: A, deviceKey: w.db.deviceKey };
1457
+ const onOwn = await expectRefusal(w.s.forget(w.a, wrong, own.displayId), "device_refused", "a wrong key on an owned display");
1458
+ const onForeign = await expectRefusal(w.s.forget(w.a, wrong, foreign.displayId), "device_refused", "a wrong key on a foreign display");
1459
+ sameRefusal(onOwn, onForeign, "owned and foreign displays");
1460
+ await expectRefusal(w.s.postSnapshot(w.a, wrong, foreign.displayId, { v: 1 }), "device_refused", "a wrong key posting to a foreign display");
1461
+ },
1462
+ "K6: the device key is stored only as its SHA-256 hex": async (w) => {
1463
+ const text = await w.h.storedText();
1464
+ check(!text.includes(w.da.deviceKey) && !text.includes(w.db.deviceKey), "a device key is stored");
1465
+ check(text.includes(await sha256Hex(w.da.deviceKey)), "the device key's SHA-256 hex is not stored");
1466
+ },
1467
+ "K7: a pre-migration till adopts its displays at its first register": async (w) => {
1468
+ const legacy = await w.h.seedLegacyDevice("till-legacy");
1469
+ await expectRefusal(w.s.registerDevice(w.viewer, "till-legacy"), "forbidden", "a register without the capability");
1470
+ check((await w.h.adoptionLog()).length === 0, "a refused register adopted");
1471
+ const before = JSON.stringify(await w.h.storedCounts());
1472
+ for (const [what, deviceKey] of [["no key", ""], ["a random key", randomKey()]]) {
1473
+ const keyless = { deviceId: "till-legacy", deviceKey };
1474
+ await expectRefusal(w.s.list(w.a, keyless), "device_refused", `list with ${what} before the adoption`);
1475
+ await expectRefusal(w.s.mint(w.a, keyless), "device_refused", `mint with ${what} before the adoption`);
1476
+ }
1477
+ const after = JSON.stringify(await w.h.storedCounts());
1478
+ check(after === before, `refused pre-adoption calls changed the stored counts from ${before} to ${after}`);
1479
+ const device = { deviceId: "till-legacy", deviceKey: (await w.s.registerDevice(w.a, "till-legacy")).deviceKey };
1480
+ check(SECRET.test(device.deviceKey), "the adopting key is not 22+ base64url characters");
1481
+ check((await w.s.list(w.a, device)).some((r) => r.displayId === legacy.displayId), "the adopted till does not list its display");
1482
+ await w.s.readSnapshot(w.h.display("192.0.2.1"), legacy.token);
1483
+ const log = JSON.stringify(await w.h.adoptionLog());
1484
+ check(log === JSON.stringify([{ deviceId: "till-legacy", cashierId: "cashier-a" }]), `the adoption log is ${log}`);
1485
+ },
1486
+ "K8: an adoption cannot repeat": async (w) => {
1487
+ const { device } = await adopted(w);
1488
+ await expectRefusal(w.s.registerDevice(w.b, "till-legacy"), "device_refused", "a second adoption by another cashier");
1489
+ await expectRefusal(w.s.registerDevice(w.a, "till-legacy"), "device_refused", "a second adoption by the same cashier");
1490
+ check((await w.h.adoptionLog()).length === 1, "the adoption log has more than one entry");
1491
+ await w.s.list(w.a, device);
1492
+ },
1493
+ "K9: a device that owns nothing and makes no till call for over 30 days is pruned, and its id registers again": async (w) => {
1494
+ const old = { deviceId: "till-idle", deviceKey: (await w.s.registerDevice(w.a, "till-idle")).deviceKey };
1495
+ const shown = await paired(w, w.a, w.da, "192.0.2.1", "Counter");
1496
+ await w.h.advance(29 * DAY);
1497
+ await expectRefusal(w.s.list(w.a, { deviceId: "till-idle", deviceKey: randomKey() }), "device_refused", "a wrong key on an idle device");
1498
+ await w.s.readSnapshot(shown.d, shown.token);
1499
+ await w.h.advance(2 * DAY);
1500
+ check((await w.s.list(w.a, w.da)).some((r) => r.displayId === shown.displayId), "a device that owns a live row was pruned");
1501
+ const fresh = (await w.s.registerDevice(w.a, "till-idle")).deviceKey;
1502
+ check(fresh !== old.deviceKey, "the re-registered id got its old key");
1503
+ await expectRefusal(w.s.list(w.a, old), "device_refused", "the key of a pruned device");
1504
+ await w.s.list(w.a, { deviceId: "till-idle", deviceKey: fresh });
1201
1505
  }
1202
1506
  };
1203
1507
  return Object.entries(cases).map(([name, run]) => ({ name, run: async () => run(await world(makeHarness)) }));
@@ -1208,6 +1512,8 @@ export {
1208
1512
  ORDER_NOTE_MAX,
1209
1513
  SUPPORTED_ORDER_CREATE_VERSIONS,
1210
1514
  SUPPORTED_ORDER_REFUND_VERSIONS,
1515
+ SUPPORTED_ORDER_REOPEN_VERSIONS,
1516
+ SUPPORTED_ORDER_UPDATE_VERSIONS,
1211
1517
  SUPPORTED_REGISTER_VERSIONS,
1212
1518
  canonicalJson,
1213
1519
  commandFingerprint,
@@ -1221,14 +1527,18 @@ export {
1221
1527
  internalErrorResult,
1222
1528
  majorToMinor,
1223
1529
  minorToMajor,
1530
+ minorUnitDigits,
1224
1531
  parseCommandResult,
1225
1532
  payloadBoundErrors,
1226
1533
  payloadShapeErrors,
1227
1534
  platformErrorResult,
1228
1535
  precheckCommand,
1536
+ ratePpmFromPercent,
1229
1537
  refundPayloadErrors,
1230
1538
  registerPayloadErrors,
1539
+ reopenPayloadErrors,
1231
1540
  totalWarnings,
1232
1541
  transientOutcome,
1542
+ updatePayloadErrors,
1233
1543
  validateBatch
1234
1544
  };