@tallyui/core 3.18.0 → 3.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/core",
3
- "version": "3.18.0",
3
+ "version": "3.20.0",
4
4
  "type": "module",
5
5
  "description": "Core interfaces, traits, and context providers for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -0,0 +1,57 @@
1
+ import type { DisplayAdvertisement, IceServer } from '../types/display-signalling';
2
+
3
+ /**
4
+ * v2's default ICE list: two operators' public STUN servers, so one outage does not cost the candidate (ADR-085 d7).
5
+ */
6
+ export const DEFAULT_ICE_SERVERS: readonly IceServer[] = Object.freeze([
7
+ { urls: 'stun:stun.cloudflare.com:3478' },
8
+ { urls: 'stun:stun.l.google.com:19302' },
9
+ ]);
10
+
11
+ const SCHEMES = ['stun:', 'stuns:', 'turn:', 'turns:'];
12
+
13
+ const isPlainObject = (value: unknown): value is Record<string, unknown> =>
14
+ typeof value === 'object' && value !== null && !Array.isArray(value);
15
+
16
+ const nonEmpty = (value: unknown): value is string => typeof value === 'string' && value.length > 0;
17
+
18
+ const defaults = (): IceServer[] => DEFAULT_ICE_SERVERS.map((server) => ({ ...server }));
19
+
20
+ /** One entry, keeping only `urls`, `username` and `credential`; `undefined` refuses the whole list. */
21
+ function parseIceServer(entry: unknown): IceServer | undefined {
22
+ if (!isPlainObject(entry)) return undefined;
23
+ const { urls, username, credential } = entry;
24
+ const list = typeof urls === 'string' ? [urls] : urls;
25
+ if (!Array.isArray(list) || list.length === 0 || !list.every(nonEmpty)) return undefined;
26
+ if (!list.every((url) => SCHEMES.some((scheme) => url.startsWith(scheme)))) return undefined;
27
+ const turn = list.some((url) => url.startsWith('turn:') || url.startsWith('turns:'));
28
+ if (turn && !(nonEmpty(username) && nonEmpty(credential))) return undefined;
29
+ return {
30
+ urls: typeof urls === 'string' ? urls : [...list],
31
+ ...(typeof username === 'string' ? { username } : {}),
32
+ ...(typeof credential === 'string' ? { credential } : {}),
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Reads `customerDisplay` of `GET /tally/v1/info` (ADR-085 d7, d8). Absent gives `undefined`: no second-device
38
+ * display. Not a plain object, or `v` other than 1, gives `undefined` and one `warn`. `iceServers` absent gives
39
+ * `DEFAULT_ICE_SERVERS`, `[]` is kept (LAN-only), and a refused list (a non-array, or an entry with a URL that is not
40
+ * `stun:`, `stuns:`, `turn:` or `turns:`, or a TURN URL without both username and credential) gives the default and
41
+ * one `warn`. `snapshot` is true only for `snapshot: 1`.
42
+ */
43
+ export function parseDisplayAdvertisement(value: unknown, warn?: (reason: string) => void): DisplayAdvertisement | undefined {
44
+ if (value === undefined) return undefined;
45
+ if (!isPlainObject(value) || value.v !== 1) {
46
+ warn?.('ignoring a malformed customerDisplay: no second-device display');
47
+ return undefined;
48
+ }
49
+ const snapshot = value.snapshot === 1;
50
+ if (value.iceServers === undefined) return { iceServers: defaults(), snapshot };
51
+ const parsed = Array.isArray(value.iceServers) ? value.iceServers.map(parseIceServer) : [undefined];
52
+ if (parsed.some((server) => server === undefined)) {
53
+ warn?.('refused customerDisplay.iceServers, so the default STUN servers apply');
54
+ return { iceServers: defaults(), snapshot };
55
+ }
56
+ return { iceServers: parsed as IceServer[], snapshot };
57
+ }
@@ -0,0 +1,2 @@
1
+ export { DEFAULT_ICE_SERVERS, parseDisplayAdvertisement } from './advertisement';
2
+ export { rateLimitSource } from './rate-limit-source';
@@ -0,0 +1,40 @@
1
+ const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
2
+ const HEXTET = /^[0-9a-f]{1,4}$/;
3
+
4
+ /** The eight hextets of an IPv6 address, each 4 lower-case digits, or `undefined` when it is not one. */
5
+ function expandIpv6(address: string): string[] | undefined {
6
+ let text = address.toLowerCase();
7
+ const last = text.slice(text.lastIndexOf(':') + 1);
8
+ if (IPV4.test(last)) {
9
+ const [a, b, c, d] = last.split('.').map(Number);
10
+ text = `${text.slice(0, text.length - last.length)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;
11
+ }
12
+ const halves = text.split('::');
13
+ if (halves.length > 2) return undefined;
14
+ const head = halves[0] ? halves[0].split(':') : [];
15
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
16
+ const missing = 8 - head.length - tail.length;
17
+ if (halves.length === 2 ? missing < 1 : missing !== 0) return undefined;
18
+ const groups = [...head, ...Array<string>(missing).fill('0'), ...tail];
19
+ if (!groups.every((group) => HEXTET.test(group))) return undefined;
20
+ return groups.map((group) => group.padStart(4, '0'));
21
+ }
22
+
23
+ /**
24
+ * The key that rate-limits failed claims per source (ADR-085 d4): an IPv4 address (also IPv4-mapped `::ffff:a.b.c.d`)
25
+ * is itself; an IPv6 address counts by its /64, as its first four hextets expanded plus `::/64`, with a zone id
26
+ * dropped. Anything else is the input, trimmed. Pure.
27
+ */
28
+ export function rateLimitSource(address: string): string {
29
+ const input = address.trim();
30
+ if (IPV4.test(input)) return input;
31
+ const zone = input.indexOf('%');
32
+ const hextets = expandIpv6(zone >= 0 ? input.slice(0, zone) : input);
33
+ if (!hextets) return input;
34
+ if (hextets.slice(0, 5).every((group) => group === '0000') && hextets[5] === 'ffff') {
35
+ const high = parseInt(hextets[6], 16);
36
+ const low = parseInt(hextets[7], 16);
37
+ return [high >> 8, high & 255, low >> 8, low & 255].join('.');
38
+ }
39
+ return `${hextets.slice(0, 4).join(':')}::/64`;
40
+ }
package/src/index.ts CHANGED
@@ -25,10 +25,17 @@ export type {
25
25
  StockStatus,
26
26
  StoreSettings,
27
27
  StoreSettingsChoice,
28
+ StoreTaxClass,
28
29
  StoreTaxRate,
29
30
  StoreTaxRateLocation,
30
31
  } from './types';
31
32
  export type { SignInResult, ServerCapabilities, TaxRounding } from './types/connector';
33
+ export type {
34
+ DisplaySignalling, DisplaySignallingContext, DisplaySignallingErrorCode, DisplayAdvertisement, IceServer,
35
+ PendingPairing, DisplayRecord, SignalMessage,
36
+ } from './types';
37
+ export { DisplaySignallingError, DISPLAY_PAIR_CAPABILITY } from './types/display-signalling';
38
+ export { DEFAULT_ICE_SERVERS, parseDisplayAdvertisement, rateLimitSource } from './customer-display';
32
39
  export type { CatalogueReconcileAdapter, CatalogueReconcileEntry } from './types/reconcile';
33
40
  export { parseInfoCapabilities, parseTaxRounding, parseLineTax, resolveCapabilities } from './types/connector';
34
41
  export { SignInError } from './sign-in';
@@ -38,15 +45,17 @@ export { errorKind, type ErrorKind, type SyncNotice } from './sync-notice';
38
45
  export { classifyFailure, neutralFailureClass, noResponse, type ConnectivityState, type FailureClass, type UpdateRequired } from './connectivity';
39
46
  export type { SignInErrorCode } from './sign-in';
40
47
  export { StoreSettingsError } from './store-settings';
41
- export { customerTraits, CustomerServiceError, type Customer, type CustomerInput, type CustomerAddress, type CustomerTaxId, type CustomerPatch } from './types/customers';
48
+ export { customerTraits, CustomerServiceError, type Customer, type CustomerInput, type CustomerAddress, type CustomerTaxId, type CustomerPatch, type CustomerPage } from './types/customers';
42
49
  export { paymentMethodOf, defaultPaymentMethods } from './types/payment-methods';
43
50
  export type {
44
51
  PaymentMethodDescriptor, PaymentKind, CaptureMode, CaptureModeEntry, PaymentHardware, PaymentTransport,
45
52
  PaymentOfflineMode, PaymentTipsMode, PaymentRounding,
46
53
  } from './types/payment-methods';
54
+ export type { ReceiptTemplate, ReceiptTemplateKind } from './types/receipt-templates';
47
55
  export type {
48
- StoreOrder, StoreOrderLine, StoreOrderCharge, StoreOrderPayment, StoreOrderRefund, ListOrdersQuery, StoreOrderPage,
56
+ StoreOrder, StoreOrderLine, StoreOrderCharge, StoreOrderPayment, StoreOrderRefund, ListOrdersQuery, StoreOrderPage, OrderFilterField,
49
57
  } from './types/orders';
58
+ export { ORDER_FILTER_FIELDS, UnsupportedOrderFilterError, orderFilterFields, assertOrderFiltersSupported, assertOrderDateRange } from './order-filters';
50
59
  export type { RegisterInfo } from './types/registers';
51
60
  export { CASHIER_PERMISSIONS, cashierPermissions, isCashierPermission, type Cashier, type CashierPermission } from './types/cashier';
52
61
  export type { StoreSettingsErrorCode, StoreSettingsChoices } from './store-settings';
@@ -66,6 +75,7 @@ export type {
66
75
  RegisterSessionTransitionPayload,
67
76
  RegisterMovementRecordPayload, RegisterMovementVoidPayload, RegisterClosureSubmitPayload,
68
77
  } from './types';
78
+ export type { OrderAddress } from './types/commands';
69
79
 
70
80
  export {
71
81
  COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, MAX_COMMANDS_PER_BATCH, ORDER_NOTE_MAX,
@@ -0,0 +1,58 @@
1
+ import type { ListOrdersQuery, OrderFilterField } from './types/orders';
2
+
3
+ /** Every ListOrdersQuery filter field, in the order refusals name them. */
4
+ export const ORDER_FILTER_FIELDS: readonly OrderFilterField[] = [
5
+ 'status', 'customerId', 'cashierId', 'registerId', 'paymentMethod', 'storeId', 'createdVia', 'dateRange',
6
+ ];
7
+
8
+ /** listOrders was asked to filter by fields the connector does not support (`TallyConnector.orderFilters`). */
9
+ export class UnsupportedOrderFilterError extends Error {
10
+ readonly code = 'unsupported_order_filter';
11
+ readonly fields: OrderFilterField[];
12
+ constructor(fields: OrderFilterField[]) {
13
+ super(`listOrders does not support: ${fields.join(', ')}`);
14
+ this.name = 'UnsupportedOrderFilterError';
15
+ this.fields = fields;
16
+ }
17
+ }
18
+
19
+ /** The filter fields a query sets (a field counts when its value is not undefined; dateRange counts when after or before is set). */
20
+ export function orderFilterFields(query: ListOrdersQuery | undefined): OrderFilterField[] {
21
+ if (!query) return [];
22
+ return ORDER_FILTER_FIELDS.filter((field) => {
23
+ if (field === 'dateRange') return query.dateRange?.after !== undefined || query.dateRange?.before !== undefined;
24
+ return query[field] !== undefined;
25
+ });
26
+ }
27
+
28
+ /**
29
+ * Throws UnsupportedOrderFilterError naming every set field not in `supported`, in OrderFilterField order. A connector
30
+ * calls this first in listOrders. An empty string is a set value, so it is refused too. When `dateRange` is set and
31
+ * supported, it is checked with `assertOrderDateRange`.
32
+ */
33
+ export function assertOrderFiltersSupported(query: ListOrdersQuery | undefined, supported: readonly OrderFilterField[] | undefined): void {
34
+ const set = orderFilterFields(query);
35
+ const missing = set.filter((field) => !supported?.includes(field));
36
+ if (missing.length > 0) throw new UnsupportedOrderFilterError(missing);
37
+ if (set.includes('dateRange')) assertOrderDateRange(query?.dateRange);
38
+ }
39
+
40
+ const UTC_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?Z$/;
41
+
42
+ function instantMs(end: 'after' | 'before', value: unknown): number {
43
+ const ms = typeof value === 'string' && UTC_INSTANT.test(value) ? Date.parse(value) : Number.NaN;
44
+ if (Number.isNaN(ms)) throw new TypeError(`dateRange.${end} must be an ISO 8601 UTC instant ending in Z: ${String(value)}`);
45
+ return ms;
46
+ }
47
+
48
+ /**
49
+ * Throws a TypeError for a dateRange end that is not an ISO UTC instant ending in Z, or after > before. `after` equal
50
+ * to `before` passes: an empty range is the caller's business.
51
+ */
52
+ export function assertOrderDateRange(range: ListOrdersQuery['dateRange']): void {
53
+ const after = range?.after === undefined ? undefined : instantMs('after', range.after);
54
+ const before = range?.before === undefined ? undefined : instantMs('before', range.before);
55
+ if (after !== undefined && before !== undefined && after > before) {
56
+ throw new TypeError(`dateRange.after (${range?.after}) is later than dateRange.before (${range?.before})`);
57
+ }
58
+ }
@@ -115,6 +115,10 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
115
115
  let versionError = command.version < 5 && v5Fields.length ? v5Fields.map(field => `${field} requires version 5`).join('; ')
116
116
  : command.version < 6 && v6Fields.length ? v6Fields.map(field => `${field} requires version 6`).join('; ')
117
117
  : command.version < 7 && payload.note !== undefined ? 'note requires version 7'
118
+ : command.version < 8 && payload.taxAddress !== undefined ? 'taxAddress requires version 8'
119
+ : command.version < 8 && (payload.customer?.billing !== undefined || payload.customer?.shipping !== undefined)
120
+ ? 'customer address requires version 8'
121
+ : command.version >= 8 && payload.taxAddress === undefined ? 'version 8 requires taxAddress'
118
122
  : command.version === 2 && discountMinor === undefined ? 'version 2 requires discountMinor'
119
123
  : command.version === 1 && discounted ? 'discountMinor requires version 2'
120
124
  : !v3 && (display !== undefined || taxByRate !== undefined) ? 'display and taxByRate require version 3'
@@ -0,0 +1,254 @@
1
+ import type { SyncContext } from '../../types/connector';
2
+ import type { DisplaySignalling, DisplaySignallingContext, DisplaySignallingErrorCode } from '../../types/display-signalling';
3
+ import { sha256Hex, type DisplaySignallingHarness } from './memory-server';
4
+
5
+ const MINUTE = 60_000, DAY = 24 * 60 * MINUTE;
6
+ /** The two till devices. */
7
+ const A = 'till-a', B = 'till-b';
8
+ const SECRET = /^[A-Za-z0-9_-]{22,}$/;
9
+
10
+ function check(condition: unknown, message: string): asserts condition {
11
+ if (!condition) throw new Error(`display signalling contract: ${message}`);
12
+ }
13
+
14
+ /** Resolves to the refusal when `promise` rejects with `code`; throws otherwise. */
15
+ async function expectRefusal(promise: Promise<unknown>, code: DisplaySignallingErrorCode, what: string): Promise<Error> {
16
+ let result: unknown;
17
+ try {
18
+ result = await promise;
19
+ } catch (error) {
20
+ const got = (error as { code?: unknown } | null)?.code;
21
+ check(got === code, `${what}: expected ${code}, got ${String(got ?? error)}`);
22
+ return error as Error;
23
+ }
24
+ throw new Error(`display signalling contract: ${what}: expected ${code}, but it resolved ${JSON.stringify(result)}`);
25
+ }
26
+
27
+ const sameRefusal = (x: Error, y: Error, what: string): void =>
28
+ check(x.message === y.message && (x as { code?: unknown }).code === (y as { code?: unknown }).code, `${what}: the refusals differ`);
29
+
30
+ /** A code of the same length that is not one of `used`. */
31
+ function unusedCode(...used: string[]): string {
32
+ for (let n = 0; ; n += 1) {
33
+ const code = String(n).padStart(used[0]?.length ?? 6, '0');
34
+ if (!used.includes(code)) return code;
35
+ }
36
+ }
37
+
38
+ interface World { h: DisplaySignallingHarness; s: DisplaySignalling; a: SyncContext; b: SyncContext; viewer: SyncContext }
39
+
40
+ async function world(make: () => Promise<DisplaySignallingHarness>): Promise<World> {
41
+ const h = await make();
42
+ const till = (cashierId: string, canPair = true) => h.till({ cashierId, canPair });
43
+ return { h, s: h.signalling, a: await till('cashier-a'), b: await till('cashier-b'), viewer: await till('cashier-viewer', false) };
44
+ }
45
+
46
+ /** Claims a fresh code from `deviceId`, giving the claim and its pending pairing's id. */
47
+ async function claimed(w: World, ctx: SyncContext, deviceId: string, d: DisplaySignallingContext, name: string, token?: string) {
48
+ const { code } = await w.s.mint(ctx, deviceId);
49
+ const claim = await w.s.claim(d, { code, displayName: name, ...(token ? { token } : {}) });
50
+ const entry = (await w.s.pending(ctx, deviceId)).find((p) => p.checkCode === claim.checkCode);
51
+ check(entry && entry.displayName === name, `the pending listing lacks the claim by ${name}`);
52
+ return { code, claim, claimId: entry.claimId };
53
+ }
54
+
55
+ /** Pairs a display with `deviceId` end to end: mint, claim, confirm, collect. */
56
+ async function paired(w: World, ctx: SyncContext, deviceId: string, source: string, name: string, token?: string) {
57
+ const d = w.h.display(source);
58
+ const { claim, claimId } = await claimed(w, ctx, deviceId, d, name, token);
59
+ await w.s.confirm(ctx, deviceId, claimId);
60
+ const result = await w.s.collect(d, claim.claimSecret);
61
+ check(result.status === 'paired', `collect after the confirm gave ${result.status}`);
62
+ return { d, claim, displayId: result.displayId, token: result.token };
63
+ }
64
+
65
+ /**
66
+ * The security floor of ADR-085 d4–d6 and d8, and #705, as runner-agnostic cases: each builds a fresh harness and
67
+ * throws on failure. Each plugin's connector runs it against its own routes:
68
+ * `for (const c of displaySignallingContract(make)) it(c.name, c.run);`
69
+ */
70
+ export function displaySignallingContract(makeHarness: () => Promise<DisplaySignallingHarness>): Array<{ name: string; run: () => Promise<void> }> {
71
+ const cases: Record<string, (w: World) => Promise<void>> = {
72
+ 'mint without the capability is forbidden and makes no code': async ({ h, s, viewer }) => {
73
+ await expectRefusal(s.mint(viewer, A), 'forbidden', 'mint without the capability');
74
+ check((await h.storedCounts()).codes === 0, 'a refused mint stored a code');
75
+ },
76
+ 'a minted code is at least 6 digits and expires within 10 minutes': async ({ h, s, a }) => {
77
+ const { code, expiresAt } = await s.mint(a, A);
78
+ check(/^\d{6,}$/.test(code), `code ${code} is not 6 or more digits`);
79
+ check(!Number.isNaN(Date.parse(expiresAt)), `expiresAt ${expiresAt} is not a date`);
80
+ await h.advance(10 * MINUTE);
81
+ await expectRefusal(s.claim(h.display('192.0.2.1'), { code, displayName: 'Late' }), 'claim_refused', 'a claim 10 minutes after the mint');
82
+ },
83
+ 'a device holds at most 5 unspent codes, and expired codes stop counting': async ({ h, s, a }) => {
84
+ for (let i = 0; i < 5; i += 1) await s.mint(a, A);
85
+ await expectRefusal(s.mint(a, A), 'limit', 'the 6th unspent code');
86
+ await h.advance(10 * MINUTE);
87
+ await s.mint(a, A);
88
+ },
89
+ 'spent, expired and unknown codes get the same claim refusal': async ({ h, s, a }) => {
90
+ const spent = (await s.mint(a, A)).code;
91
+ await s.claim(h.display('192.0.2.1'), { code: spent, displayName: 'First' });
92
+ const again = await expectRefusal(s.claim(h.display('192.0.2.2'), { code: spent, displayName: 'Second' }), 'claim_refused', 'a spent code');
93
+ const expired = (await s.mint(a, A)).code;
94
+ await h.advance(10 * MINUTE);
95
+ const late = await expectRefusal(s.claim(h.display('192.0.2.3'), { code: expired, displayName: 'Late' }), 'claim_refused', 'an expired code');
96
+ const unknown = await expectRefusal(s.claim(h.display('192.0.2.4'), { code: unusedCode(spent, expired), displayName: 'Guess' }), 'claim_refused', 'an unknown code');
97
+ sameRefusal(again, late, 'spent and expired');
98
+ sameRefusal(again, unknown, 'spent and unknown');
99
+ },
100
+ 'a claim issues no token: collect gives pending with its check code': async (w) => {
101
+ const d = w.h.display('192.0.2.1');
102
+ const { claim } = await claimed(w, w.a, A, d, 'Counter');
103
+ const result = await w.s.collect(d, claim.claimSecret);
104
+ check(result.status === 'pending' && result.checkCode === claim.checkCode, `collect before the confirm gave ${JSON.stringify(result)}`);
105
+ },
106
+ 'the check code matches on both screens, and two live claims never share one': async (w) => {
107
+ const d = w.h.display('192.0.2.1');
108
+ const first = await claimed(w, w.a, A, d, 'One');
109
+ check(/^\d{4}$/.test(first.claim.checkCode), `check code ${first.claim.checkCode} is not 4 digits`);
110
+ const listed = (await w.s.pending(w.a, A)).find((p) => p.claimId === first.claimId);
111
+ const collected = await w.s.collect(d, first.claim.claimSecret);
112
+ check(listed?.checkCode === first.claim.checkCode, 'the till lists another check code');
113
+ check(collected.status === 'pending' && collected.checkCode === first.claim.checkCode, 'collect gives another check code');
114
+ const second = await claimed(w, w.a, A, w.h.display('192.0.2.2'), 'Two');
115
+ check(second.claim.checkCode !== first.claim.checkCode, 'two live claims share a check code');
116
+ },
117
+ 'a confirm issues the token once, then collect is refused like an unknown secret': async (w) => {
118
+ const { d, claim, token } = await paired(w, w.a, A, '192.0.2.1', 'Counter');
119
+ check(SECRET.test(token), 'the token is not 22+ base64url characters');
120
+ const again = await expectRefusal(w.s.collect(d, claim.claimSecret), 'collect_refused', 'a second collect');
121
+ const unknown = await expectRefusal(w.s.collect(d, 'AAAAAAAAAAAAAAAAAAAAAA'), 'collect_refused', 'an unknown secret');
122
+ sameRefusal(again, unknown, 'second collect and unknown secret');
123
+ },
124
+ 'a decline, or an unconfirmed claim whose code expires, issues nothing': async (w) => {
125
+ const d = w.h.display('192.0.2.1');
126
+ const declined = await claimed(w, w.a, A, d, 'Declined');
127
+ await w.s.decline(w.a, A, declined.claimId);
128
+ await expectRefusal(w.s.collect(d, declined.claim.claimSecret), 'collect_refused', 'collect after a decline');
129
+ const lapsed = await claimed(w, w.a, A, d, 'Lapsed');
130
+ await w.h.advance(10 * MINUTE);
131
+ await expectRefusal(w.s.collect(d, lapsed.claim.claimSecret), 'collect_refused', 'collect after the code expired');
132
+ check((await w.h.storedCounts()).pending === 0, 'a pending pairing outlived its decline or its code');
133
+ },
134
+ 'a confirm needs the capability and the minting device': async (w) => {
135
+ const d = w.h.display('192.0.2.1');
136
+ const { claim, claimId } = await claimed(w, w.a, A, d, 'Counter');
137
+ await expectRefusal(w.s.confirm(w.viewer, A, claimId), 'forbidden', 'a confirm without the capability');
138
+ await expectRefusal(w.s.confirm(w.b, B, claimId), 'not_found', 'a confirm from another device');
139
+ check((await w.s.collect(d, claim.claimSecret)).status === 'pending', 'a refused confirm changed the claim');
140
+ },
141
+ 'one source is limited to 10 failed claims a minute, and a limited claim spends nothing': async ({ h, s, a }) => {
142
+ const { code } = await s.mint(a, A);
143
+ const guesser = h.display('198.51.100.7');
144
+ for (let i = 0; i < 10; i += 1) await expectRefusal(s.claim(guesser, { code: unusedCode(code), displayName: 'Guess' }), 'claim_refused', 'a wrong code');
145
+ await expectRefusal(s.claim(guesser, { code, displayName: 'Guess' }), 'claim_refused', 'a valid code from a limited source');
146
+ await s.claim(h.display('198.51.100.8'), { code, displayName: 'Other' });
147
+ await h.advance(MINUTE);
148
+ await s.claim(guesser, { code: (await s.mint(a, A)).code, displayName: 'Later' });
149
+ },
150
+ 'two IPv6 addresses in one /64 share a limit': async ({ h, s, a }) => {
151
+ const { code } = await s.mint(a, A);
152
+ const one = h.display('2001:db8:0:1::5');
153
+ const two = h.display('2001:db8:0:1:ffff::9');
154
+ 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');
155
+ await expectRefusal(s.claim(one, { code, displayName: 'Guess' }), 'claim_refused', 'a valid code from a limited /64');
156
+ await expectRefusal(s.claim(two, { code, displayName: 'Guess' }), 'claim_refused', 'a valid code from a limited /64');
157
+ await s.claim(h.display('2001:db8:0:2::5'), { code, displayName: 'Other' });
158
+ },
159
+ '100 failed claims store-wide pause every claim for 10 minutes': async ({ h, s, a }) => {
160
+ const { code } = await s.mint(a, A);
161
+ // 9 failures per address, so no source reaches its own limit of 10.
162
+ 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');
163
+ await expectRefusal(s.claim(h.display('203.0.113.200'), { code, displayName: 'Shop' }), 'claim_refused', 'a valid code while paused');
164
+ await h.advance(10 * MINUTE);
165
+ await s.claim(h.display('203.0.113.201'), { code: (await s.mint(a, A)).code, displayName: 'Shop' });
166
+ },
167
+ 'the claim secret and the token are stored only as hashes': async (w) => {
168
+ const { claim, token } = await paired(w, w.a, A, '192.0.2.1', 'Counter');
169
+ const text = await w.h.storedText();
170
+ check(SECRET.test(claim.claimSecret), 'the claim secret is not 22+ base64url characters');
171
+ check(!text.includes(claim.claimSecret) && !text.includes(token), 'the claim secret or the token is stored');
172
+ check(text.includes(await sha256Hex(token)), "the token's SHA-256 hex is not stored");
173
+ },
174
+ 'the registry lists a display on its owning device only, and tracks connected': async (w) => {
175
+ const { d, displayId, token } = await paired(w, w.a, A, '192.0.2.1', 'Counter');
176
+ const row = (await w.s.list(w.a, A)).find((r) => r.displayId === displayId);
177
+ check(row?.name === 'Counter' && row.cashierId === 'cashier-a', `the owner lists ${JSON.stringify(row)}`);
178
+ check(!(await w.s.list(w.b, B)).some((r) => r.displayId === displayId), 'another device lists the display');
179
+ await w.s.displayReceiveSignals(d, token);
180
+ check((await w.s.list(w.a, A))[0]?.connected === true, 'a display just seen is not connected');
181
+ await w.h.advance(31_000);
182
+ check((await w.s.list(w.a, A))[0]?.connected === false, 'a display unseen for 31 s is connected');
183
+ },
184
+ 'forget revokes the token, the row and the snapshot, for the owner only': async (w) => {
185
+ const { d, displayId, token } = await paired(w, w.a, A, '192.0.2.1', 'Counter');
186
+ await w.s.postSnapshot(w.a, A, displayId, { v: 1 });
187
+ await w.s.displaySendSignal(d, token, { type: 'answer', payload: 'a1' });
188
+ await expectRefusal(w.s.forget(w.b, B, displayId), 'not_found', 'forget from another device');
189
+ check((await w.s.list(w.a, A)).length === 1, 'a refused forget removed the display');
190
+ await w.s.forget(w.a, A, displayId);
191
+ await expectRefusal(w.s.displayReceiveSignals(d, token), 'token_refused', 'a forgotten token');
192
+ check((await w.s.list(w.a, A)).length === 0, 'the owner still lists a forgotten display');
193
+ check((await w.s.receiveSignals(w.a, A)).every((m) => m.displayId !== displayId), 'the till received from a forgotten display');
194
+ const counts = await w.h.storedCounts();
195
+ check(counts.displays === 0 && counts.snapshots === 0, `forget left ${JSON.stringify(counts)}`);
196
+ },
197
+ 'a display confirmed by a second till moves to it': async (w) => {
198
+ const first = await paired(w, w.a, A, '192.0.2.1', 'Counter');
199
+ await w.s.postSnapshot(w.a, A, first.displayId, { v: 1 });
200
+ await w.s.sendSignal(w.a, A, first.displayId, { type: 'offer', payload: 'o1' });
201
+ await w.s.displaySendSignal(first.d, first.token, { type: 'answer', payload: 'a1' });
202
+ const moved = await paired(w, w.b, B, '192.0.2.1', 'Counter', first.token);
203
+ check((await w.s.readSnapshot(moved.d, moved.token)) === null, "the first till's snapshot survived the move");
204
+ check((await w.s.displayReceiveSignals(moved.d, moved.token)).length === 0, "the first till's signal survived the move");
205
+ check((await w.h.storedCounts()).snapshots === 0, 'a snapshot is stored after the move');
206
+ check((await w.s.receiveSignals(w.a, A)).every((m) => m.displayId !== first.displayId), 'the first till received from a moved display');
207
+ check((await w.s.list(w.a, A)).length === 0, 'the first till still lists a moved display');
208
+ 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');
209
+ await expectRefusal(w.s.readSnapshot(first.d, first.token), 'token_refused', 'the old token after a move');
210
+ },
211
+ 'signals arrive once and in order, and only at their own display or till': async (w) => {
212
+ const x = await paired(w, w.a, A, '192.0.2.1', 'X');
213
+ const y = await paired(w, w.a, A, '192.0.2.2', 'Y');
214
+ const z = await paired(w, w.b, B, '192.0.2.3', 'Z');
215
+ await w.s.sendSignal(w.a, A, x.displayId, { type: 'offer', payload: 'o1' });
216
+ await w.s.sendSignal(w.a, A, x.displayId, { type: 'ice', payload: 'i1' });
217
+ const atX = await w.s.displayReceiveSignals(x.d, x.token);
218
+ check(atX.map((m) => m.payload).join() === 'o1,i1', `display X received ${JSON.stringify(atX)}`);
219
+ check((await w.s.displayReceiveSignals(x.d, x.token)).length === 0, 'display X received a message twice');
220
+ check((await w.s.displayReceiveSignals(y.d, y.token)).length === 0, "display Y received display X's messages");
221
+ await w.s.displaySendSignal(x.d, x.token, { type: 'answer', payload: 'a1' });
222
+ await w.s.displaySendSignal(x.d, x.token, { type: 'ice', payload: 'i2' });
223
+ await w.s.displaySendSignal(z.d, z.token, { type: 'answer', payload: 'z1' });
224
+ check((await w.s.receiveSignals(w.b, B)).every((m) => m.displayId === z.displayId), "device B received device A's display");
225
+ const atA = await w.s.receiveSignals(w.a, A);
226
+ check(atA.map((m) => `${m.displayId === x.displayId}:${m.payload}`).join() === 'true:a1,true:i2', `till A received ${JSON.stringify(atA)}`);
227
+ check((await w.s.receiveSignals(w.a, A)).length === 0, 'till A received a message twice');
228
+ },
229
+ 'the snapshot needs the token, keeps the latest body for 60 s, and refuses over 200 KiB': async (w) => {
230
+ const { d, displayId, token } = await paired(w, w.a, A, '192.0.2.1', 'Counter');
231
+ await expectRefusal(w.s.readSnapshot(d, 'not-a-token-not-a-token'), 'token_refused', 'a read without the token');
232
+ await w.s.postSnapshot(w.a, A, displayId, { seq: 1 });
233
+ await w.s.postSnapshot(w.a, A, displayId, { seq: 2 });
234
+ check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"seq":2}', 'the latest snapshot is not served');
235
+ await w.h.advance(61_000);
236
+ check((await w.s.readSnapshot(d, token)) === null, 'a snapshot outlived 60 s');
237
+ await w.s.postSnapshot(w.a, A, displayId, { seq: 3 });
238
+ await expectRefusal(w.s.postSnapshot(w.a, A, displayId, { pad: 'x'.repeat(204_800) }), 'too_large', 'a snapshot over 200 KiB');
239
+ check(JSON.stringify(await w.s.readSnapshot(d, token)) === '{"seq":3}', 'a refused snapshot replaced the previous one');
240
+ },
241
+ 'expired codes and displays unseen for 30 days are pruned': async (w) => {
242
+ const { d, token } = await paired(w, w.a, A, '192.0.2.1', 'Counter');
243
+ await w.s.mint(w.a, A);
244
+ await w.h.advance(10 * MINUTE);
245
+ await w.s.list(w.a, A);
246
+ check((await w.h.storedCounts()).codes === 0, 'an expired code is still stored');
247
+ await w.h.advance(30 * DAY);
248
+ await w.s.list(w.a, A);
249
+ check((await w.h.storedCounts()).displays === 0, 'a display unseen for 30 days is still stored');
250
+ await expectRefusal(w.s.readSnapshot(d, token), 'token_refused', 'a pruned display');
251
+ },
252
+ };
253
+ return Object.entries(cases).map(([name, run]) => ({ name, run: async () => run(await world(makeHarness)) }));
254
+ }
@@ -0,0 +1,3 @@
1
+ export { createMemoryDisplaySignalling } from './memory-server';
2
+ export type { DisplaySignallingHarness } from './memory-server';
3
+ export { displaySignallingContract } from './contract';