@relai-team/access-sdk 0.18.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -479,6 +479,22 @@ var OrdersModule = class {
479
479
  if (input.metadata !== void 0) body["metadata"] = input.metadata;
480
480
  return this.http.request({ method: "POST", path: "/orders", body });
481
481
  }
482
+ /**
483
+ * Fetch one order.
484
+ *
485
+ * WHO MAY READ IT, because this is the call most likely to surprise you:
486
+ *
487
+ * - A SECRET key reads any order of the app. Server-to-server.
488
+ * - A PUBLISHABLE key needs a signed-in end user, who must be the order's
489
+ * initiator or its recipient. A publishable key ships inside your app
490
+ * binary, so it proves nothing about who is asking.
491
+ * - A GUEST session reads only its own orders that have no recipient. Guest
492
+ * mode is one shared identity per app, so a guest order with no recipient
493
+ * names nobody, while a directed one names a real person.
494
+ *
495
+ * Every refusal is `not_found`, identical to an id that does not exist, so
496
+ * you cannot tell the two apart and should not try.
497
+ */
482
498
  get(orderId) {
483
499
  return this.http.request({ path: `/orders/${orderId}` });
484
500
  }
@@ -738,6 +754,63 @@ init_errors();
738
754
 
739
755
  // src/unlock.ts
740
756
  init_errors();
757
+
758
+ // src/parent-resolve.ts
759
+ var WRONG_PARENT = "TAG";
760
+ function isWrongParentReject(reason) {
761
+ return reason === WRONG_PARENT;
762
+ }
763
+ var CACHE_PREFIX = "relai.parent.";
764
+ var ParentHandleCache = class {
765
+ constructor(storage) {
766
+ this.storage = storage;
767
+ }
768
+ async get(parentBleId) {
769
+ if (!this.storage) return null;
770
+ try {
771
+ return await this.storage.getItem(CACHE_PREFIX + parentBleId) ?? null;
772
+ } catch {
773
+ return null;
774
+ }
775
+ }
776
+ async set(parentBleId, handle) {
777
+ if (!this.storage || handle === parentBleId) return;
778
+ try {
779
+ await this.storage.setItem(CACHE_PREFIX + parentBleId, handle);
780
+ } catch {
781
+ }
782
+ }
783
+ async forget(parentBleId) {
784
+ if (!this.storage) return;
785
+ try {
786
+ await this.storage.removeItem(CACHE_PREFIX + parentBleId);
787
+ } catch {
788
+ }
789
+ }
790
+ };
791
+ function orderCandidates(input) {
792
+ const out = [];
793
+ const seen = /* @__PURE__ */ new Set();
794
+ const push = (h) => {
795
+ if (!h || seen.has(h)) return;
796
+ seen.add(h);
797
+ out.push(h);
798
+ };
799
+ push(input.cached);
800
+ push(input.parentBleId);
801
+ const scanned = input.scanned ?? [];
802
+ if (input.parentSerial && input.scannedSerials) {
803
+ const want = input.parentSerial.toUpperCase();
804
+ for (const handle of scanned) {
805
+ if (input.scannedSerials.get(handle)?.toUpperCase() === want) push(handle);
806
+ }
807
+ }
808
+ for (const h of scanned) push(h);
809
+ return out;
810
+ }
811
+ var MAX_PARENT_ATTEMPTS = 6;
812
+
813
+ // src/unlock.ts
741
814
  async function deliverOpen(deps, open, opts) {
742
815
  const { transport } = opts;
743
816
  const grant = open.grant;
@@ -747,53 +820,103 @@ async function deliverOpen(deps, open, opts) {
747
820
  `Grant ${grant.grant_id} names no parent_ble_id and none was provided; cannot select a Parent.`
748
821
  );
749
822
  }
750
- const session = await transport.connect(parentBleId);
751
- try {
752
- let token = grant.token;
753
- let keyVersion;
754
- if (grant.algorithm === "relai-hmac-sha256-16-v1") {
755
- const nonce = await transport.requestNonce(session);
756
- const minted = await deps.grants.mint(grant.grant_id, nonce);
757
- token = minted.token;
758
- keyVersion = minted.key_version;
759
- }
760
- if (!token) {
761
- throw new exports.RelaiTransportError(
762
- `Grant ${grant.grant_id} has no token to deliver (algorithm ${grant.algorithm}).`
763
- );
823
+ const cache = new ParentHandleCache(opts.handleStorage);
824
+ const ezId = opts.exchangeZoneId ?? grant.ez_id;
825
+ async function attempt(handle) {
826
+ const session = await transport.connect(handle);
827
+ let keep = false;
828
+ try {
829
+ let token = grant.token;
830
+ let keyVersion;
831
+ if (grant.algorithm === "relai-hmac-sha256-16-v1") {
832
+ const nonce = await transport.requestNonce(session);
833
+ const minted = await deps.grants.mint(grant.grant_id, nonce);
834
+ token = minted.token;
835
+ keyVersion = minted.key_version;
836
+ }
837
+ if (!token) {
838
+ throw new exports.RelaiError(
839
+ `Grant ${grant.grant_id} has no token to deliver (algorithm ${grant.algorithm}).`
840
+ );
841
+ }
842
+ const ack = await transport.sendCommand(session, token);
843
+ if (!ack.accepted && isWrongParentReject(ack.rejectReason ?? "")) {
844
+ return null;
845
+ }
846
+ if (!ack.accepted) {
847
+ await reportOutcome(false, ack.rejectReason ?? "UNKNOWN");
848
+ throw new exports.RelaiUnlockRejected(ack.rejectReason ?? "UNKNOWN", ack.verbHint);
849
+ }
850
+ await reportOutcome(true);
851
+ await cache.set(parentBleId, handle);
852
+ keep = Boolean(opts.keepConnected);
853
+ return { open, accepted: true, command: ack.command, keyVersion, session };
854
+ } finally {
855
+ if (!keep) await transport.disconnect(session).catch(() => void 0);
764
856
  }
765
- const ack = await transport.sendCommand(session, token);
766
- const ezId = opts.exchangeZoneId ?? grant.ez_id;
767
- if (ezId) {
768
- void deps.telemetry.submit({
769
- exchangeZoneId: ezId,
770
- grantId: grant.grant_id,
771
- events: [
772
- {
773
- action: ack.accepted ? "unlock_used" : "unlock_failed",
774
- result: ack.accepted ? "success" : "failure",
775
- transport: "ble",
776
- at: (/* @__PURE__ */ new Date()).toISOString(),
777
- // The Parent's own reject reason, so a failure is diagnosable
778
- // rather than merely counted.
779
- ...ack.accepted ? {} : { reason: ack.rejectReason ?? "UNKNOWN" }
780
- }
781
- ]
782
- }).catch(() => void 0);
857
+ }
858
+ async function reportOutcome(accepted, reason) {
859
+ if (!ezId) return;
860
+ void deps.telemetry.submit({
861
+ exchangeZoneId: ezId,
862
+ grantId: grant.grant_id,
863
+ events: [
864
+ {
865
+ action: accepted ? "unlock_used" : "unlock_failed",
866
+ result: accepted ? "success" : "failure",
867
+ transport: "ble",
868
+ at: (/* @__PURE__ */ new Date()).toISOString(),
869
+ // The Parent's own reject reason, so a failure is diagnosable
870
+ // rather than merely counted.
871
+ ...accepted ? {} : { reason: reason ?? "UNKNOWN" }
872
+ }
873
+ ]
874
+ }).catch(() => void 0);
875
+ }
876
+ let candidates = orderCandidates({ cached: await cache.get(parentBleId), parentBleId });
877
+ let scanned = false;
878
+ let lastConnectError;
879
+ for (let i = 0; i < MAX_PARENT_ATTEMPTS; i++) {
880
+ if (i >= candidates.length) {
881
+ if (scanned) break;
882
+ scanned = true;
883
+ const found = await transport.scan().catch(() => []);
884
+ const scannedSerials = /* @__PURE__ */ new Map();
885
+ for (const d of found) {
886
+ if (d.serial) scannedSerials.set(d.parentBleId, d.serial);
887
+ }
888
+ candidates = orderCandidates({
889
+ parentBleId,
890
+ scanned: found.map((d) => d.parentBleId),
891
+ scannedSerials,
892
+ parentSerial: open.grant.parent_serial
893
+ });
894
+ await cache.forget(parentBleId);
895
+ if (i >= candidates.length) break;
783
896
  }
784
- if (!ack.accepted) {
785
- throw new exports.RelaiUnlockRejected(ack.rejectReason ?? "UNKNOWN", ack.verbHint);
897
+ const handle = candidates[i];
898
+ try {
899
+ const result = await attempt(handle);
900
+ if (result) return result;
901
+ } catch (err) {
902
+ if (isParentUnreachable(err)) {
903
+ lastConnectError = err;
904
+ continue;
905
+ }
906
+ throw err;
786
907
  }
787
- return {
788
- open,
789
- accepted: true,
790
- command: ack.command,
791
- keyVersion,
792
- session
793
- };
794
- } finally {
795
- if (!opts.keepConnected) await transport.disconnect(session).catch(() => void 0);
796
908
  }
909
+ await reportOutcome(false, "NO_PARENT");
910
+ const detail = lastConnectError instanceof Error ? ` Last error: ${lastConnectError.message}` : "";
911
+ throw new exports.RelaiTransportError(
912
+ `No Parent in range accepted the command for grant ${grant.grant_id}. Check that you are standing at the Exchange Zone and that Bluetooth is on.${detail}`
913
+ );
914
+ }
915
+ function isParentUnreachable(err) {
916
+ if (!(err instanceof Error)) return false;
917
+ if (err instanceof exports.RelaiTransportError) return true;
918
+ if (err instanceof exports.RelaiError) return false;
919
+ return true;
797
920
  }
798
921
 
799
922
  // src/client.ts
@@ -1097,6 +1220,46 @@ var SimAuthenticatedTransport = class {
1097
1220
  // src/transport/ble.ts
1098
1221
  init_errors();
1099
1222
 
1223
+ // src/parent-advertisement.ts
1224
+ var COMPANY_ID = 65535;
1225
+ var FORMAT_VERSION = 1;
1226
+ var HEADER_BYTES = 3;
1227
+ var SERIAL_MAX = 12;
1228
+ function decodeBase64(value) {
1229
+ try {
1230
+ const binary = typeof atob === "function" ? atob(value) : (
1231
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1232
+ globalThis.Buffer.from(value, "base64").toString("binary")
1233
+ );
1234
+ const out = new Uint8Array(binary.length);
1235
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
1236
+ return out;
1237
+ } catch {
1238
+ return null;
1239
+ }
1240
+ }
1241
+ function parseAdvertisedSerial(value) {
1242
+ if (!value) return null;
1243
+ const bytes = decodeBase64(value);
1244
+ if (!bytes || bytes.length <= HEADER_BYTES) return null;
1245
+ const company = bytes[0] | bytes[1] << 8;
1246
+ if (company !== COMPANY_ID) return null;
1247
+ if (bytes[2] !== FORMAT_VERSION) return null;
1248
+ const body = bytes.subarray(HEADER_BYTES);
1249
+ if (body.length > SERIAL_MAX) return null;
1250
+ let serial = "";
1251
+ for (const byte of body) {
1252
+ const char = String.fromCharCode(byte);
1253
+ if (!/[A-Z0-9._:/-]/.test(char)) return null;
1254
+ serial += char;
1255
+ }
1256
+ return serial.length > 0 ? serial : null;
1257
+ }
1258
+ function serialMatches(advertised, granted) {
1259
+ if (!advertised || !granted) return false;
1260
+ return advertised.toUpperCase() === granted.toUpperCase();
1261
+ }
1262
+
1100
1263
  // src/transport/notify.ts
1101
1264
  var REJECT_REASONS = [
1102
1265
  "B64",
@@ -1143,11 +1306,65 @@ var BleTransport = class {
1143
1306
  this.scanImpl = opts.scan;
1144
1307
  this.notifyTimeoutMs = opts.notifyTimeoutMs ?? NOTIFY_TIMEOUT_MS;
1145
1308
  }
1146
- scan() {
1147
- if (!this.scanImpl) {
1148
- return Promise.reject(new exports.RelaiTransportError("No scan() provided to BleTransport; drive discovery from your app."));
1309
+ /**
1310
+ * Relai Parents in range.
1311
+ *
1312
+ * An app-supplied `scan` still wins, because an app with its own discovery UI
1313
+ * has already solved this and may filter differently. Otherwise the manager's
1314
+ * own scanner is driven here, filtered to the Relai service so the list is
1315
+ * Parents rather than every radio in the building.
1316
+ *
1317
+ * Results are ordered by signal, strongest first. That is a weak hint and
1318
+ * treated as one: towers at an Exchange Zone stand side by side, so signal
1319
+ * barely separates them. What actually identifies a Parent is that it accepts
1320
+ * the command; this ordering only decides who gets asked first.
1321
+ */
1322
+ scan(timeoutMs = 4e3) {
1323
+ if (this.scanImpl) return this.scanImpl();
1324
+ const manager = this.manager;
1325
+ if (!manager.startDeviceScan || !manager.stopDeviceScan) {
1326
+ return Promise.reject(
1327
+ new exports.RelaiTransportError("No scan() provided to BleTransport; drive discovery from your app.")
1328
+ );
1149
1329
  }
1150
- return this.scanImpl();
1330
+ return new Promise((resolve) => {
1331
+ const found = /* @__PURE__ */ new Map();
1332
+ let settled = false;
1333
+ const finish = () => {
1334
+ if (settled) return;
1335
+ settled = true;
1336
+ try {
1337
+ manager.stopDeviceScan();
1338
+ } catch {
1339
+ }
1340
+ resolve([...found.values()].sort((a, b) => (b.rssi ?? -999) - (a.rssi ?? -999)));
1341
+ };
1342
+ const timer = setTimeout(finish, timeoutMs);
1343
+ try {
1344
+ manager.startDeviceScan([RELAI_UART_SERVICE], null, (error, device) => {
1345
+ if (error) {
1346
+ clearTimeout(timer);
1347
+ finish();
1348
+ return;
1349
+ }
1350
+ if (!device?.id || found.has(device.id)) return;
1351
+ const fields = device;
1352
+ const rssi = fields.rssi;
1353
+ const serial = parseAdvertisedSerial(fields.manufacturerData);
1354
+ found.set(device.id, {
1355
+ parentBleId: device.id,
1356
+ isSimulated: false,
1357
+ // Spread rather than assigned: exactOptionalPropertyTypes means an
1358
+ // explicit `undefined` is not the same as an absent field.
1359
+ ...typeof rssi === "number" ? { rssi } : {},
1360
+ ...serial ? { serial } : {}
1361
+ });
1362
+ });
1363
+ } catch {
1364
+ clearTimeout(timer);
1365
+ finish();
1366
+ }
1367
+ });
1151
1368
  }
1152
1369
  async connect(parentBleId) {
1153
1370
  let device = await this.manager.connectToDevice(parentBleId);
@@ -1307,6 +1524,8 @@ exports.asPaymentRequired = asPaymentRequired;
1307
1524
  exports.deliverOpen = deliverOpen;
1308
1525
  exports.isRetryableRejectReason = isRetryableRejectReason;
1309
1526
  exports.isStripePublishableKey = isStripePublishableKey;
1527
+ exports.parseAdvertisedSerial = parseAdvertisedSerial;
1310
1528
  exports.parseNotifyLine = parseNotifyLine;
1311
1529
  exports.presentRelaiPaymentSheet = presentRelaiPaymentSheet;
1530
+ exports.serialMatches = serialMatches;
1312
1531
  exports.verifyWebhook = verifyWebhook;
package/dist/index.d.cts CHANGED
@@ -178,6 +178,16 @@ interface UnlockGrant {
178
178
  ez_id: string;
179
179
  /** The tower's Parent BLE identity: used to auto-select the scanned Parent. */
180
180
  parent_ble_id: string | null;
181
+ /**
182
+ * The serial stamped on the tower's chassis plate, unique platform-wide.
183
+ *
184
+ * Unlike `parent_ble_id`, which is the MAC recorded when the Parent was
185
+ * provisioned, this is an identity that exists on the hardware itself: it is
186
+ * readable off the unit, and it is what tells one tower from its neighbours
187
+ * at an Exchange Zone with several. Null on simulated towers, which have no
188
+ * chassis, and on towers commissioned before the serial was required.
189
+ */
190
+ parent_serial: string | null;
181
191
  /** Opaque payload written verbatim to the Parent. Null until minted (hmac). */
182
192
  token: string | null;
183
193
  jti: string;
@@ -671,6 +681,22 @@ declare class OrdersModule {
671
681
  promotionCode?: string;
672
682
  metadata?: Record<string, string>;
673
683
  }): Promise<Order>;
684
+ /**
685
+ * Fetch one order.
686
+ *
687
+ * WHO MAY READ IT, because this is the call most likely to surprise you:
688
+ *
689
+ * - A SECRET key reads any order of the app. Server-to-server.
690
+ * - A PUBLISHABLE key needs a signed-in end user, who must be the order's
691
+ * initiator or its recipient. A publishable key ships inside your app
692
+ * binary, so it proves nothing about who is asking.
693
+ * - A GUEST session reads only its own orders that have no recipient. Guest
694
+ * mode is one shared identity per app, so a guest order with no recipient
695
+ * names nobody, while a directed one names a real person.
696
+ *
697
+ * Every refusal is `not_found`, identical to an id that does not exist, so
698
+ * you cannot tell the two apart and should not try.
699
+ */
674
700
  get(orderId: string): Promise<Order>;
675
701
  /**
676
702
  * Request an open: one token + an unlock grant. On authenticated towers the
@@ -937,6 +963,12 @@ interface DiscoveredParent {
937
963
  parentBleId: string;
938
964
  /** The tower this Parent controls, when known from discovery context. */
939
965
  towerId?: string;
966
+ /**
967
+ * The chassis serial read off this Parent's advertisement, when it published
968
+ * one. UNAUTHENTICATED: it decides which Parent to try first and nothing
969
+ * else. See `parseAdvertisedSerial`.
970
+ */
971
+ serial?: string;
940
972
  rssi?: number;
941
973
  isSimulated: boolean;
942
974
  }
@@ -972,6 +1004,60 @@ interface ParentTransport {
972
1004
  disconnect(session: Session): Promise<void>;
973
1005
  }
974
1006
 
1007
+ /**
1008
+ * Persistent telemetry queue (owner, 2026-07-24). `MemoryTelemetryQueue` loses
1009
+ * anything queued when the app is killed; a React Native app that opens nodes
1010
+ * offline needs its unreported opens to survive a restart. This backs the same
1011
+ * `TelemetryQueue` interface with a key-value store.
1012
+ *
1013
+ * The store is AsyncStorage-shaped on purpose, so RN apps pass the library in
1014
+ * directly (it is an OPTIONAL dependency: the SDK core never imports it):
1015
+ *
1016
+ * import AsyncStorage from "@react-native-async-storage/async-storage";
1017
+ * const client = new RelaiClient({
1018
+ * publishableKey,
1019
+ * telemetryQueue: new StorageTelemetryQueue(AsyncStorage),
1020
+ * });
1021
+ *
1022
+ * The whole queue is one JSON blob under a single key: telemetry volume is one
1023
+ * item per open, so this stays small; writes are serialized through an internal
1024
+ * lock so concurrent submit/flush calls can't clobber each other.
1025
+ */
1026
+
1027
+ /** The subset of AsyncStorage (and localStorage-async wrappers) we need. */
1028
+ interface KeyValueStorage {
1029
+ getItem(key: string): Promise<string | null>;
1030
+ setItem(key: string, value: string): Promise<void>;
1031
+ removeItem(key: string): Promise<void>;
1032
+ }
1033
+ interface StorageTelemetryQueueOptions {
1034
+ /** Storage key for the serialized queue. Default `@relai/telemetry-queue`. */
1035
+ storageKey?: string;
1036
+ /**
1037
+ * Hard cap on queued items; when exceeded the OLDEST are dropped so a long
1038
+ * outage can't grow storage without bound. Default 500.
1039
+ */
1040
+ maxItems?: number;
1041
+ }
1042
+ declare class StorageTelemetryQueue implements TelemetryQueue {
1043
+ private readonly storage;
1044
+ private readonly key;
1045
+ private readonly maxItems;
1046
+ /** Serializes read-modify-write so concurrent calls don't lose updates. */
1047
+ private chain;
1048
+ private seq;
1049
+ constructor(storage: KeyValueStorage, opts?: StorageTelemetryQueueOptions);
1050
+ enqueue(payload: TelemetryPayload): Promise<void>;
1051
+ list(): Promise<QueuedTelemetry[]>;
1052
+ remove(id: string): Promise<void>;
1053
+ markAttempt(id: string): Promise<void>;
1054
+ private nextId;
1055
+ /** Serialize an operation after any in-flight ones (a simple promise lock). */
1056
+ private run;
1057
+ private mutate;
1058
+ private read;
1059
+ }
1060
+
975
1061
  interface UnlockDeps {
976
1062
  grants: GrantsModule;
977
1063
  telemetry: TelemetryUploader;
@@ -996,6 +1082,14 @@ interface DeliverOptions {
996
1082
  exchangeZoneId?: string;
997
1083
  /** Keep the BLE session open after the unlock (default: disconnect). */
998
1084
  keepConnected?: boolean;
1085
+ /**
1086
+ * Where to remember which local handle turned out to be which Parent.
1087
+ *
1088
+ * Optional, and the same storage the telemetry queue takes. Without it every
1089
+ * open on a platform that needs discovery pays for a scan; with it, only the
1090
+ * first one at a given tower does.
1091
+ */
1092
+ handleStorage?: KeyValueStorage;
999
1093
  }
1000
1094
  /**
1001
1095
  * Deliver an already-issued Open to a Parent. Splits out so callers who created
@@ -1207,60 +1301,6 @@ declare class RelaiClient {
1207
1301
  unlock(input: UnlockInput): Promise<UnlockResult>;
1208
1302
  }
1209
1303
 
1210
- /**
1211
- * Persistent telemetry queue (owner, 2026-07-24). `MemoryTelemetryQueue` loses
1212
- * anything queued when the app is killed; a React Native app that opens nodes
1213
- * offline needs its unreported opens to survive a restart. This backs the same
1214
- * `TelemetryQueue` interface with a key-value store.
1215
- *
1216
- * The store is AsyncStorage-shaped on purpose, so RN apps pass the library in
1217
- * directly (it is an OPTIONAL dependency: the SDK core never imports it):
1218
- *
1219
- * import AsyncStorage from "@react-native-async-storage/async-storage";
1220
- * const client = new RelaiClient({
1221
- * publishableKey,
1222
- * telemetryQueue: new StorageTelemetryQueue(AsyncStorage),
1223
- * });
1224
- *
1225
- * The whole queue is one JSON blob under a single key: telemetry volume is one
1226
- * item per open, so this stays small; writes are serialized through an internal
1227
- * lock so concurrent submit/flush calls can't clobber each other.
1228
- */
1229
-
1230
- /** The subset of AsyncStorage (and localStorage-async wrappers) we need. */
1231
- interface KeyValueStorage {
1232
- getItem(key: string): Promise<string | null>;
1233
- setItem(key: string, value: string): Promise<void>;
1234
- removeItem(key: string): Promise<void>;
1235
- }
1236
- interface StorageTelemetryQueueOptions {
1237
- /** Storage key for the serialized queue. Default `@relai/telemetry-queue`. */
1238
- storageKey?: string;
1239
- /**
1240
- * Hard cap on queued items; when exceeded the OLDEST are dropped so a long
1241
- * outage can't grow storage without bound. Default 500.
1242
- */
1243
- maxItems?: number;
1244
- }
1245
- declare class StorageTelemetryQueue implements TelemetryQueue {
1246
- private readonly storage;
1247
- private readonly key;
1248
- private readonly maxItems;
1249
- /** Serializes read-modify-write so concurrent calls don't lose updates. */
1250
- private chain;
1251
- private seq;
1252
- constructor(storage: KeyValueStorage, opts?: StorageTelemetryQueueOptions);
1253
- enqueue(payload: TelemetryPayload): Promise<void>;
1254
- list(): Promise<QueuedTelemetry[]>;
1255
- remove(id: string): Promise<void>;
1256
- markAttempt(id: string): Promise<void>;
1257
- private nextId;
1258
- /** Serialize an operation after any in-flight ones (a simple promise lock). */
1259
- private run;
1260
- private mutate;
1261
- private read;
1262
- }
1263
-
1264
1304
  /**
1265
1305
  * SimulatedTransport: lets an app exercise the full open flow with no hardware.
1266
1306
  * It emulates the Parent's notify surface: issues a random nonce on CHALLENGE,
@@ -1328,6 +1368,16 @@ interface BleDeviceLike {
1328
1368
  interface BleManagerLike {
1329
1369
  connectToDevice(id: string, options?: unknown): Promise<BleDeviceLike>;
1330
1370
  discoverAllServicesAndCharacteristicsForDevice?(id: string): Promise<BleDeviceLike>;
1371
+ /**
1372
+ * Discovery, where the platform provides it.
1373
+ *
1374
+ * OPTIONAL so every transport and test double written against the two methods
1375
+ * above keeps compiling. `react-native-ble-plx` has both of these; a manager
1376
+ * without them simply never scans, which is correct on a platform where the
1377
+ * grant's id is already a usable handle.
1378
+ */
1379
+ startDeviceScan?(serviceUUIDs: string[] | null, options: unknown, listener: (error: unknown, device: BleDeviceLike | null) => void): void;
1380
+ stopDeviceScan?(): void;
1331
1381
  }
1332
1382
  interface BleTransportOptions {
1333
1383
  manager: BleManagerLike;
@@ -1341,7 +1391,20 @@ declare class BleTransport implements ParentTransport {
1341
1391
  private readonly scanImpl;
1342
1392
  private readonly notifyTimeoutMs;
1343
1393
  constructor(opts: BleTransportOptions);
1344
- scan(): Promise<DiscoveredParent[]>;
1394
+ /**
1395
+ * Relai Parents in range.
1396
+ *
1397
+ * An app-supplied `scan` still wins, because an app with its own discovery UI
1398
+ * has already solved this and may filter differently. Otherwise the manager's
1399
+ * own scanner is driven here, filtered to the Relai service so the list is
1400
+ * Parents rather than every radio in the building.
1401
+ *
1402
+ * Results are ordered by signal, strongest first. That is a weak hint and
1403
+ * treated as one: towers at an Exchange Zone stand side by side, so signal
1404
+ * barely separates them. What actually identifies a Parent is that it accepts
1405
+ * the command; this ordering only decides who gets asked first.
1406
+ */
1407
+ scan(timeoutMs?: number): Promise<DiscoveredParent[]>;
1345
1408
  connect(parentBleId: string): Promise<Session>;
1346
1409
  requestNonce(session: Session): Promise<string>;
1347
1410
  sendCommand(session: Session, token: string): Promise<CommandAck>;
@@ -1418,6 +1481,48 @@ declare function isRetryableRejectReason(reason: string): boolean;
1418
1481
  /** Parse one already-decoded (plain-text) notify line. */
1419
1482
  declare function parseNotifyLine(line: string): NotifyLine;
1420
1483
 
1484
+ /**
1485
+ * Reading a Parent's chassis serial off its advertisement (2026-10-05).
1486
+ *
1487
+ * A Parent publishes the serial stamped on its tower's chassis plate in its
1488
+ * scan response, as manufacturer-specific data: company id `0xFFFF`, one format
1489
+ * version byte, then the serial as ASCII. Firmware lays those bytes out in
1490
+ * `shared/src/SerialAdv.h`.
1491
+ *
1492
+ * WHAT THIS BUYS. Without it, resolving which Parent a grant belongs to means
1493
+ * connecting to candidates in turn and letting the HMAC refuse the wrong ones.
1494
+ * That works, and it is slow: a connect, a nonce, a mint and a write per
1495
+ * attempt, with somebody standing at a tower. A serial read from the scan tells
1496
+ * the SDK which candidate to try FIRST, usually making it the only one.
1497
+ *
1498
+ * A MATCH IS A HINT AND NOTHING MORE. `0xFFFF` is the identifier the Bluetooth
1499
+ * assigned-numbers list reserves for use without a company id, so any device may
1500
+ * emit it with any payload: a serial read here is unauthenticated and trivially
1501
+ * spoofable. It only ever reorders candidates. The tag on the command still
1502
+ * decides, exactly as it did before, so the cost of a lie is one wasted
1503
+ * connection and never an open.
1504
+ */
1505
+ /**
1506
+ * The serial in one manufacturer-data field, or null if there isn't one.
1507
+ *
1508
+ * `value` is what `react-native-ble-plx` puts on `device.manufacturerData`:
1509
+ * base64 of the AD field's value, company id included, header excluded.
1510
+ *
1511
+ * Every rejection path returns null rather than throwing. This runs once per
1512
+ * device per scan, over bytes from strangers, and a neighbouring smart lightbulb
1513
+ * emitting `0xFFFF` garbage must cost nothing but a null.
1514
+ */
1515
+ declare function parseAdvertisedSerial(value: string | null | undefined): string | null;
1516
+ /**
1517
+ * Do these name the same tower?
1518
+ *
1519
+ * Case-folded, because a Parent only ever stores an upper-cased serial
1520
+ * (firmware upper-cases every command before dispatch) while the platform keeps
1521
+ * the case an admin typed. Comparing them literally would miss every serial
1522
+ * entered in lower case, which is the common one.
1523
+ */
1524
+ declare function serialMatches(advertised: string | null | undefined, granted: string | null | undefined): boolean;
1525
+
1421
1526
  /**
1422
1527
  * Webhook verification for partner BACKENDS (Node 18+ / edge: WebCrypto).
1423
1528
  * Pinned platform scheme (2026-07-23, Stripe-style):
@@ -1580,4 +1685,4 @@ declare class RelaiTransportError extends RelaiError {
1580
1685
  constructor(message: string);
1581
1686
  }
1582
1687
 
1583
- export { type AccessLinkTarget, AccessLinksModule, type AnyWebhookEvent, type ApiEnvironment, type ApiErrorBody, AppModule, type AppSelf, AuthModule, type BleDeviceLike, type BleManagerLike, BleTransport, type BleTransportOptions, type CommandAck, type DayWindow, type DeliverOptions, type DiscoveredParent, type EndUser, type EndUserPage, EndUsersModule, type ExchangeZone, type ExchangeZoneDetail, type ExchangeZonePage, ExchangeZonesModule, type GrantAlgorithm, GrantsModule, type HandoffMode, type Intent, Intents, type KeyValueStorage, type Me, MemoryTelemetryQueue, MemoryTokenStorage, type MintedCommand, type NotifyLine, type Open, type OperatingHours, type Order, type OrderPage, type OrderStatusFields, OrdersModule, type OverrideLink, OverrideLinksModule, type ParentTransport, type PaymentRequiredDetails, PushModule, type PushPlatform, type QueuedTelemetry, REJECT_REASONS, RELAI_RX_CHAR, RELAI_TX_CHAR, RELAI_UART_SERVICE, type RecipientMatch, RecipientsModule, RelaiApiError, RelaiClient, type RelaiClientOptions, RelaiConfigError, RelaiError, type RelaiErrorContext, RelaiLateFeeDue, RelaiMissingKeyError, RelaiNetworkError, RelaiTransportError, RelaiUnlockRejected, type SandboxFault, type SandboxFaultResult, SandboxModule, type SelfBillingChoice, type Session, SimAuthenticatedTransport, type SimAuthenticatedTransportOptions, type SimulatedParentConfig, SimulatedTransport, StorageTelemetryQueue, type StorageTelemetryQueueOptions, type StripeSdk, type TelemetryAction, type TelemetryEvent, TelemetryModule, type TelemetryPayload, type TelemetryQueue, TelemetryUploader, type TokenPair, type TokenStorage, type Tower, type TowerNode, type TowerTelemetry, type UnlockDeps, type UnlockGrant, type UnlockInput, type UnlockResult, type VerifyWebhookInput, type WebhookEvent, type WebhookEventOf, type WebhookEventType, type WebhookPayloads, asPaymentRequired, deliverOpen, isRetryableRejectReason, isStripePublishableKey, parseNotifyLine, presentRelaiPaymentSheet, verifyWebhook };
1688
+ export { type AccessLinkTarget, AccessLinksModule, type AnyWebhookEvent, type ApiEnvironment, type ApiErrorBody, AppModule, type AppSelf, AuthModule, type BleDeviceLike, type BleManagerLike, BleTransport, type BleTransportOptions, type CommandAck, type DayWindow, type DeliverOptions, type DiscoveredParent, type EndUser, type EndUserPage, EndUsersModule, type ExchangeZone, type ExchangeZoneDetail, type ExchangeZonePage, ExchangeZonesModule, type GrantAlgorithm, GrantsModule, type HandoffMode, type Intent, Intents, type KeyValueStorage, type Me, MemoryTelemetryQueue, MemoryTokenStorage, type MintedCommand, type NotifyLine, type Open, type OperatingHours, type Order, type OrderPage, type OrderStatusFields, OrdersModule, type OverrideLink, OverrideLinksModule, type ParentTransport, type PaymentRequiredDetails, PushModule, type PushPlatform, type QueuedTelemetry, REJECT_REASONS, RELAI_RX_CHAR, RELAI_TX_CHAR, RELAI_UART_SERVICE, type RecipientMatch, RecipientsModule, RelaiApiError, RelaiClient, type RelaiClientOptions, RelaiConfigError, RelaiError, type RelaiErrorContext, RelaiLateFeeDue, RelaiMissingKeyError, RelaiNetworkError, RelaiTransportError, RelaiUnlockRejected, type SandboxFault, type SandboxFaultResult, SandboxModule, type SelfBillingChoice, type Session, SimAuthenticatedTransport, type SimAuthenticatedTransportOptions, type SimulatedParentConfig, SimulatedTransport, StorageTelemetryQueue, type StorageTelemetryQueueOptions, type StripeSdk, type TelemetryAction, type TelemetryEvent, TelemetryModule, type TelemetryPayload, type TelemetryQueue, TelemetryUploader, type TokenPair, type TokenStorage, type Tower, type TowerNode, type TowerTelemetry, type UnlockDeps, type UnlockGrant, type UnlockInput, type UnlockResult, type VerifyWebhookInput, type WebhookEvent, type WebhookEventOf, type WebhookEventType, type WebhookPayloads, asPaymentRequired, deliverOpen, isRetryableRejectReason, isStripePublishableKey, parseAdvertisedSerial, parseNotifyLine, presentRelaiPaymentSheet, serialMatches, verifyWebhook };
package/dist/index.d.ts CHANGED
@@ -178,6 +178,16 @@ interface UnlockGrant {
178
178
  ez_id: string;
179
179
  /** The tower's Parent BLE identity: used to auto-select the scanned Parent. */
180
180
  parent_ble_id: string | null;
181
+ /**
182
+ * The serial stamped on the tower's chassis plate, unique platform-wide.
183
+ *
184
+ * Unlike `parent_ble_id`, which is the MAC recorded when the Parent was
185
+ * provisioned, this is an identity that exists on the hardware itself: it is
186
+ * readable off the unit, and it is what tells one tower from its neighbours
187
+ * at an Exchange Zone with several. Null on simulated towers, which have no
188
+ * chassis, and on towers commissioned before the serial was required.
189
+ */
190
+ parent_serial: string | null;
181
191
  /** Opaque payload written verbatim to the Parent. Null until minted (hmac). */
182
192
  token: string | null;
183
193
  jti: string;
@@ -671,6 +681,22 @@ declare class OrdersModule {
671
681
  promotionCode?: string;
672
682
  metadata?: Record<string, string>;
673
683
  }): Promise<Order>;
684
+ /**
685
+ * Fetch one order.
686
+ *
687
+ * WHO MAY READ IT, because this is the call most likely to surprise you:
688
+ *
689
+ * - A SECRET key reads any order of the app. Server-to-server.
690
+ * - A PUBLISHABLE key needs a signed-in end user, who must be the order's
691
+ * initiator or its recipient. A publishable key ships inside your app
692
+ * binary, so it proves nothing about who is asking.
693
+ * - A GUEST session reads only its own orders that have no recipient. Guest
694
+ * mode is one shared identity per app, so a guest order with no recipient
695
+ * names nobody, while a directed one names a real person.
696
+ *
697
+ * Every refusal is `not_found`, identical to an id that does not exist, so
698
+ * you cannot tell the two apart and should not try.
699
+ */
674
700
  get(orderId: string): Promise<Order>;
675
701
  /**
676
702
  * Request an open: one token + an unlock grant. On authenticated towers the
@@ -937,6 +963,12 @@ interface DiscoveredParent {
937
963
  parentBleId: string;
938
964
  /** The tower this Parent controls, when known from discovery context. */
939
965
  towerId?: string;
966
+ /**
967
+ * The chassis serial read off this Parent's advertisement, when it published
968
+ * one. UNAUTHENTICATED: it decides which Parent to try first and nothing
969
+ * else. See `parseAdvertisedSerial`.
970
+ */
971
+ serial?: string;
940
972
  rssi?: number;
941
973
  isSimulated: boolean;
942
974
  }
@@ -972,6 +1004,60 @@ interface ParentTransport {
972
1004
  disconnect(session: Session): Promise<void>;
973
1005
  }
974
1006
 
1007
+ /**
1008
+ * Persistent telemetry queue (owner, 2026-07-24). `MemoryTelemetryQueue` loses
1009
+ * anything queued when the app is killed; a React Native app that opens nodes
1010
+ * offline needs its unreported opens to survive a restart. This backs the same
1011
+ * `TelemetryQueue` interface with a key-value store.
1012
+ *
1013
+ * The store is AsyncStorage-shaped on purpose, so RN apps pass the library in
1014
+ * directly (it is an OPTIONAL dependency: the SDK core never imports it):
1015
+ *
1016
+ * import AsyncStorage from "@react-native-async-storage/async-storage";
1017
+ * const client = new RelaiClient({
1018
+ * publishableKey,
1019
+ * telemetryQueue: new StorageTelemetryQueue(AsyncStorage),
1020
+ * });
1021
+ *
1022
+ * The whole queue is one JSON blob under a single key: telemetry volume is one
1023
+ * item per open, so this stays small; writes are serialized through an internal
1024
+ * lock so concurrent submit/flush calls can't clobber each other.
1025
+ */
1026
+
1027
+ /** The subset of AsyncStorage (and localStorage-async wrappers) we need. */
1028
+ interface KeyValueStorage {
1029
+ getItem(key: string): Promise<string | null>;
1030
+ setItem(key: string, value: string): Promise<void>;
1031
+ removeItem(key: string): Promise<void>;
1032
+ }
1033
+ interface StorageTelemetryQueueOptions {
1034
+ /** Storage key for the serialized queue. Default `@relai/telemetry-queue`. */
1035
+ storageKey?: string;
1036
+ /**
1037
+ * Hard cap on queued items; when exceeded the OLDEST are dropped so a long
1038
+ * outage can't grow storage without bound. Default 500.
1039
+ */
1040
+ maxItems?: number;
1041
+ }
1042
+ declare class StorageTelemetryQueue implements TelemetryQueue {
1043
+ private readonly storage;
1044
+ private readonly key;
1045
+ private readonly maxItems;
1046
+ /** Serializes read-modify-write so concurrent calls don't lose updates. */
1047
+ private chain;
1048
+ private seq;
1049
+ constructor(storage: KeyValueStorage, opts?: StorageTelemetryQueueOptions);
1050
+ enqueue(payload: TelemetryPayload): Promise<void>;
1051
+ list(): Promise<QueuedTelemetry[]>;
1052
+ remove(id: string): Promise<void>;
1053
+ markAttempt(id: string): Promise<void>;
1054
+ private nextId;
1055
+ /** Serialize an operation after any in-flight ones (a simple promise lock). */
1056
+ private run;
1057
+ private mutate;
1058
+ private read;
1059
+ }
1060
+
975
1061
  interface UnlockDeps {
976
1062
  grants: GrantsModule;
977
1063
  telemetry: TelemetryUploader;
@@ -996,6 +1082,14 @@ interface DeliverOptions {
996
1082
  exchangeZoneId?: string;
997
1083
  /** Keep the BLE session open after the unlock (default: disconnect). */
998
1084
  keepConnected?: boolean;
1085
+ /**
1086
+ * Where to remember which local handle turned out to be which Parent.
1087
+ *
1088
+ * Optional, and the same storage the telemetry queue takes. Without it every
1089
+ * open on a platform that needs discovery pays for a scan; with it, only the
1090
+ * first one at a given tower does.
1091
+ */
1092
+ handleStorage?: KeyValueStorage;
999
1093
  }
1000
1094
  /**
1001
1095
  * Deliver an already-issued Open to a Parent. Splits out so callers who created
@@ -1207,60 +1301,6 @@ declare class RelaiClient {
1207
1301
  unlock(input: UnlockInput): Promise<UnlockResult>;
1208
1302
  }
1209
1303
 
1210
- /**
1211
- * Persistent telemetry queue (owner, 2026-07-24). `MemoryTelemetryQueue` loses
1212
- * anything queued when the app is killed; a React Native app that opens nodes
1213
- * offline needs its unreported opens to survive a restart. This backs the same
1214
- * `TelemetryQueue` interface with a key-value store.
1215
- *
1216
- * The store is AsyncStorage-shaped on purpose, so RN apps pass the library in
1217
- * directly (it is an OPTIONAL dependency: the SDK core never imports it):
1218
- *
1219
- * import AsyncStorage from "@react-native-async-storage/async-storage";
1220
- * const client = new RelaiClient({
1221
- * publishableKey,
1222
- * telemetryQueue: new StorageTelemetryQueue(AsyncStorage),
1223
- * });
1224
- *
1225
- * The whole queue is one JSON blob under a single key: telemetry volume is one
1226
- * item per open, so this stays small; writes are serialized through an internal
1227
- * lock so concurrent submit/flush calls can't clobber each other.
1228
- */
1229
-
1230
- /** The subset of AsyncStorage (and localStorage-async wrappers) we need. */
1231
- interface KeyValueStorage {
1232
- getItem(key: string): Promise<string | null>;
1233
- setItem(key: string, value: string): Promise<void>;
1234
- removeItem(key: string): Promise<void>;
1235
- }
1236
- interface StorageTelemetryQueueOptions {
1237
- /** Storage key for the serialized queue. Default `@relai/telemetry-queue`. */
1238
- storageKey?: string;
1239
- /**
1240
- * Hard cap on queued items; when exceeded the OLDEST are dropped so a long
1241
- * outage can't grow storage without bound. Default 500.
1242
- */
1243
- maxItems?: number;
1244
- }
1245
- declare class StorageTelemetryQueue implements TelemetryQueue {
1246
- private readonly storage;
1247
- private readonly key;
1248
- private readonly maxItems;
1249
- /** Serializes read-modify-write so concurrent calls don't lose updates. */
1250
- private chain;
1251
- private seq;
1252
- constructor(storage: KeyValueStorage, opts?: StorageTelemetryQueueOptions);
1253
- enqueue(payload: TelemetryPayload): Promise<void>;
1254
- list(): Promise<QueuedTelemetry[]>;
1255
- remove(id: string): Promise<void>;
1256
- markAttempt(id: string): Promise<void>;
1257
- private nextId;
1258
- /** Serialize an operation after any in-flight ones (a simple promise lock). */
1259
- private run;
1260
- private mutate;
1261
- private read;
1262
- }
1263
-
1264
1304
  /**
1265
1305
  * SimulatedTransport: lets an app exercise the full open flow with no hardware.
1266
1306
  * It emulates the Parent's notify surface: issues a random nonce on CHALLENGE,
@@ -1328,6 +1368,16 @@ interface BleDeviceLike {
1328
1368
  interface BleManagerLike {
1329
1369
  connectToDevice(id: string, options?: unknown): Promise<BleDeviceLike>;
1330
1370
  discoverAllServicesAndCharacteristicsForDevice?(id: string): Promise<BleDeviceLike>;
1371
+ /**
1372
+ * Discovery, where the platform provides it.
1373
+ *
1374
+ * OPTIONAL so every transport and test double written against the two methods
1375
+ * above keeps compiling. `react-native-ble-plx` has both of these; a manager
1376
+ * without them simply never scans, which is correct on a platform where the
1377
+ * grant's id is already a usable handle.
1378
+ */
1379
+ startDeviceScan?(serviceUUIDs: string[] | null, options: unknown, listener: (error: unknown, device: BleDeviceLike | null) => void): void;
1380
+ stopDeviceScan?(): void;
1331
1381
  }
1332
1382
  interface BleTransportOptions {
1333
1383
  manager: BleManagerLike;
@@ -1341,7 +1391,20 @@ declare class BleTransport implements ParentTransport {
1341
1391
  private readonly scanImpl;
1342
1392
  private readonly notifyTimeoutMs;
1343
1393
  constructor(opts: BleTransportOptions);
1344
- scan(): Promise<DiscoveredParent[]>;
1394
+ /**
1395
+ * Relai Parents in range.
1396
+ *
1397
+ * An app-supplied `scan` still wins, because an app with its own discovery UI
1398
+ * has already solved this and may filter differently. Otherwise the manager's
1399
+ * own scanner is driven here, filtered to the Relai service so the list is
1400
+ * Parents rather than every radio in the building.
1401
+ *
1402
+ * Results are ordered by signal, strongest first. That is a weak hint and
1403
+ * treated as one: towers at an Exchange Zone stand side by side, so signal
1404
+ * barely separates them. What actually identifies a Parent is that it accepts
1405
+ * the command; this ordering only decides who gets asked first.
1406
+ */
1407
+ scan(timeoutMs?: number): Promise<DiscoveredParent[]>;
1345
1408
  connect(parentBleId: string): Promise<Session>;
1346
1409
  requestNonce(session: Session): Promise<string>;
1347
1410
  sendCommand(session: Session, token: string): Promise<CommandAck>;
@@ -1418,6 +1481,48 @@ declare function isRetryableRejectReason(reason: string): boolean;
1418
1481
  /** Parse one already-decoded (plain-text) notify line. */
1419
1482
  declare function parseNotifyLine(line: string): NotifyLine;
1420
1483
 
1484
+ /**
1485
+ * Reading a Parent's chassis serial off its advertisement (2026-10-05).
1486
+ *
1487
+ * A Parent publishes the serial stamped on its tower's chassis plate in its
1488
+ * scan response, as manufacturer-specific data: company id `0xFFFF`, one format
1489
+ * version byte, then the serial as ASCII. Firmware lays those bytes out in
1490
+ * `shared/src/SerialAdv.h`.
1491
+ *
1492
+ * WHAT THIS BUYS. Without it, resolving which Parent a grant belongs to means
1493
+ * connecting to candidates in turn and letting the HMAC refuse the wrong ones.
1494
+ * That works, and it is slow: a connect, a nonce, a mint and a write per
1495
+ * attempt, with somebody standing at a tower. A serial read from the scan tells
1496
+ * the SDK which candidate to try FIRST, usually making it the only one.
1497
+ *
1498
+ * A MATCH IS A HINT AND NOTHING MORE. `0xFFFF` is the identifier the Bluetooth
1499
+ * assigned-numbers list reserves for use without a company id, so any device may
1500
+ * emit it with any payload: a serial read here is unauthenticated and trivially
1501
+ * spoofable. It only ever reorders candidates. The tag on the command still
1502
+ * decides, exactly as it did before, so the cost of a lie is one wasted
1503
+ * connection and never an open.
1504
+ */
1505
+ /**
1506
+ * The serial in one manufacturer-data field, or null if there isn't one.
1507
+ *
1508
+ * `value` is what `react-native-ble-plx` puts on `device.manufacturerData`:
1509
+ * base64 of the AD field's value, company id included, header excluded.
1510
+ *
1511
+ * Every rejection path returns null rather than throwing. This runs once per
1512
+ * device per scan, over bytes from strangers, and a neighbouring smart lightbulb
1513
+ * emitting `0xFFFF` garbage must cost nothing but a null.
1514
+ */
1515
+ declare function parseAdvertisedSerial(value: string | null | undefined): string | null;
1516
+ /**
1517
+ * Do these name the same tower?
1518
+ *
1519
+ * Case-folded, because a Parent only ever stores an upper-cased serial
1520
+ * (firmware upper-cases every command before dispatch) while the platform keeps
1521
+ * the case an admin typed. Comparing them literally would miss every serial
1522
+ * entered in lower case, which is the common one.
1523
+ */
1524
+ declare function serialMatches(advertised: string | null | undefined, granted: string | null | undefined): boolean;
1525
+
1421
1526
  /**
1422
1527
  * Webhook verification for partner BACKENDS (Node 18+ / edge: WebCrypto).
1423
1528
  * Pinned platform scheme (2026-07-23, Stripe-style):
@@ -1580,4 +1685,4 @@ declare class RelaiTransportError extends RelaiError {
1580
1685
  constructor(message: string);
1581
1686
  }
1582
1687
 
1583
- export { type AccessLinkTarget, AccessLinksModule, type AnyWebhookEvent, type ApiEnvironment, type ApiErrorBody, AppModule, type AppSelf, AuthModule, type BleDeviceLike, type BleManagerLike, BleTransport, type BleTransportOptions, type CommandAck, type DayWindow, type DeliverOptions, type DiscoveredParent, type EndUser, type EndUserPage, EndUsersModule, type ExchangeZone, type ExchangeZoneDetail, type ExchangeZonePage, ExchangeZonesModule, type GrantAlgorithm, GrantsModule, type HandoffMode, type Intent, Intents, type KeyValueStorage, type Me, MemoryTelemetryQueue, MemoryTokenStorage, type MintedCommand, type NotifyLine, type Open, type OperatingHours, type Order, type OrderPage, type OrderStatusFields, OrdersModule, type OverrideLink, OverrideLinksModule, type ParentTransport, type PaymentRequiredDetails, PushModule, type PushPlatform, type QueuedTelemetry, REJECT_REASONS, RELAI_RX_CHAR, RELAI_TX_CHAR, RELAI_UART_SERVICE, type RecipientMatch, RecipientsModule, RelaiApiError, RelaiClient, type RelaiClientOptions, RelaiConfigError, RelaiError, type RelaiErrorContext, RelaiLateFeeDue, RelaiMissingKeyError, RelaiNetworkError, RelaiTransportError, RelaiUnlockRejected, type SandboxFault, type SandboxFaultResult, SandboxModule, type SelfBillingChoice, type Session, SimAuthenticatedTransport, type SimAuthenticatedTransportOptions, type SimulatedParentConfig, SimulatedTransport, StorageTelemetryQueue, type StorageTelemetryQueueOptions, type StripeSdk, type TelemetryAction, type TelemetryEvent, TelemetryModule, type TelemetryPayload, type TelemetryQueue, TelemetryUploader, type TokenPair, type TokenStorage, type Tower, type TowerNode, type TowerTelemetry, type UnlockDeps, type UnlockGrant, type UnlockInput, type UnlockResult, type VerifyWebhookInput, type WebhookEvent, type WebhookEventOf, type WebhookEventType, type WebhookPayloads, asPaymentRequired, deliverOpen, isRetryableRejectReason, isStripePublishableKey, parseNotifyLine, presentRelaiPaymentSheet, verifyWebhook };
1688
+ export { type AccessLinkTarget, AccessLinksModule, type AnyWebhookEvent, type ApiEnvironment, type ApiErrorBody, AppModule, type AppSelf, AuthModule, type BleDeviceLike, type BleManagerLike, BleTransport, type BleTransportOptions, type CommandAck, type DayWindow, type DeliverOptions, type DiscoveredParent, type EndUser, type EndUserPage, EndUsersModule, type ExchangeZone, type ExchangeZoneDetail, type ExchangeZonePage, ExchangeZonesModule, type GrantAlgorithm, GrantsModule, type HandoffMode, type Intent, Intents, type KeyValueStorage, type Me, MemoryTelemetryQueue, MemoryTokenStorage, type MintedCommand, type NotifyLine, type Open, type OperatingHours, type Order, type OrderPage, type OrderStatusFields, OrdersModule, type OverrideLink, OverrideLinksModule, type ParentTransport, type PaymentRequiredDetails, PushModule, type PushPlatform, type QueuedTelemetry, REJECT_REASONS, RELAI_RX_CHAR, RELAI_TX_CHAR, RELAI_UART_SERVICE, type RecipientMatch, RecipientsModule, RelaiApiError, RelaiClient, type RelaiClientOptions, RelaiConfigError, RelaiError, type RelaiErrorContext, RelaiLateFeeDue, RelaiMissingKeyError, RelaiNetworkError, RelaiTransportError, RelaiUnlockRejected, type SandboxFault, type SandboxFaultResult, SandboxModule, type SelfBillingChoice, type Session, SimAuthenticatedTransport, type SimAuthenticatedTransportOptions, type SimulatedParentConfig, SimulatedTransport, StorageTelemetryQueue, type StorageTelemetryQueueOptions, type StripeSdk, type TelemetryAction, type TelemetryEvent, TelemetryModule, type TelemetryPayload, type TelemetryQueue, TelemetryUploader, type TokenPair, type TokenStorage, type Tower, type TowerNode, type TowerTelemetry, type UnlockDeps, type UnlockGrant, type UnlockInput, type UnlockResult, type VerifyWebhookInput, type WebhookEvent, type WebhookEventOf, type WebhookEventType, type WebhookPayloads, asPaymentRequired, deliverOpen, isRetryableRejectReason, isStripePublishableKey, parseAdvertisedSerial, parseNotifyLine, presentRelaiPaymentSheet, serialMatches, verifyWebhook };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { RelaiApiError, RelaiTransportError, RelaiUnlockRejected, RelaiMissingKeyError, RelaiError, RelaiNetworkError } from './chunk-B2T3KFBF.js';
1
+ import { RelaiApiError, RelaiTransportError, RelaiError, RelaiMissingKeyError, RelaiUnlockRejected, RelaiNetworkError } from './chunk-B2T3KFBF.js';
2
2
  export { RelaiApiError, RelaiConfigError, RelaiError, RelaiLateFeeDue, RelaiMissingKeyError, RelaiNetworkError, RelaiTransportError, RelaiUnlockRejected } from './chunk-B2T3KFBF.js';
3
3
  export { asPaymentRequired, isStripePublishableKey, presentRelaiPaymentSheet } from './chunk-BIHTDL4L.js';
4
4
 
@@ -325,6 +325,22 @@ var OrdersModule = class {
325
325
  if (input.metadata !== void 0) body["metadata"] = input.metadata;
326
326
  return this.http.request({ method: "POST", path: "/orders", body });
327
327
  }
328
+ /**
329
+ * Fetch one order.
330
+ *
331
+ * WHO MAY READ IT, because this is the call most likely to surprise you:
332
+ *
333
+ * - A SECRET key reads any order of the app. Server-to-server.
334
+ * - A PUBLISHABLE key needs a signed-in end user, who must be the order's
335
+ * initiator or its recipient. A publishable key ships inside your app
336
+ * binary, so it proves nothing about who is asking.
337
+ * - A GUEST session reads only its own orders that have no recipient. Guest
338
+ * mode is one shared identity per app, so a guest order with no recipient
339
+ * names nobody, while a directed one names a real person.
340
+ *
341
+ * Every refusal is `not_found`, identical to an id that does not exist, so
342
+ * you cannot tell the two apart and should not try.
343
+ */
328
344
  get(orderId) {
329
345
  return this.http.request({ path: `/orders/${orderId}` });
330
346
  }
@@ -576,6 +592,61 @@ var TelemetryUploader = class {
576
592
  }
577
593
  };
578
594
 
595
+ // src/parent-resolve.ts
596
+ var WRONG_PARENT = "TAG";
597
+ function isWrongParentReject(reason) {
598
+ return reason === WRONG_PARENT;
599
+ }
600
+ var CACHE_PREFIX = "relai.parent.";
601
+ var ParentHandleCache = class {
602
+ constructor(storage) {
603
+ this.storage = storage;
604
+ }
605
+ async get(parentBleId) {
606
+ if (!this.storage) return null;
607
+ try {
608
+ return await this.storage.getItem(CACHE_PREFIX + parentBleId) ?? null;
609
+ } catch {
610
+ return null;
611
+ }
612
+ }
613
+ async set(parentBleId, handle) {
614
+ if (!this.storage || handle === parentBleId) return;
615
+ try {
616
+ await this.storage.setItem(CACHE_PREFIX + parentBleId, handle);
617
+ } catch {
618
+ }
619
+ }
620
+ async forget(parentBleId) {
621
+ if (!this.storage) return;
622
+ try {
623
+ await this.storage.removeItem(CACHE_PREFIX + parentBleId);
624
+ } catch {
625
+ }
626
+ }
627
+ };
628
+ function orderCandidates(input) {
629
+ const out = [];
630
+ const seen = /* @__PURE__ */ new Set();
631
+ const push = (h) => {
632
+ if (!h || seen.has(h)) return;
633
+ seen.add(h);
634
+ out.push(h);
635
+ };
636
+ push(input.cached);
637
+ push(input.parentBleId);
638
+ const scanned = input.scanned ?? [];
639
+ if (input.parentSerial && input.scannedSerials) {
640
+ const want = input.parentSerial.toUpperCase();
641
+ for (const handle of scanned) {
642
+ if (input.scannedSerials.get(handle)?.toUpperCase() === want) push(handle);
643
+ }
644
+ }
645
+ for (const h of scanned) push(h);
646
+ return out;
647
+ }
648
+ var MAX_PARENT_ATTEMPTS = 6;
649
+
579
650
  // src/unlock.ts
580
651
  async function deliverOpen(deps, open, opts) {
581
652
  const { transport } = opts;
@@ -586,53 +657,103 @@ async function deliverOpen(deps, open, opts) {
586
657
  `Grant ${grant.grant_id} names no parent_ble_id and none was provided; cannot select a Parent.`
587
658
  );
588
659
  }
589
- const session = await transport.connect(parentBleId);
590
- try {
591
- let token = grant.token;
592
- let keyVersion;
593
- if (grant.algorithm === "relai-hmac-sha256-16-v1") {
594
- const nonce = await transport.requestNonce(session);
595
- const minted = await deps.grants.mint(grant.grant_id, nonce);
596
- token = minted.token;
597
- keyVersion = minted.key_version;
598
- }
599
- if (!token) {
600
- throw new RelaiTransportError(
601
- `Grant ${grant.grant_id} has no token to deliver (algorithm ${grant.algorithm}).`
602
- );
660
+ const cache = new ParentHandleCache(opts.handleStorage);
661
+ const ezId = opts.exchangeZoneId ?? grant.ez_id;
662
+ async function attempt(handle) {
663
+ const session = await transport.connect(handle);
664
+ let keep = false;
665
+ try {
666
+ let token = grant.token;
667
+ let keyVersion;
668
+ if (grant.algorithm === "relai-hmac-sha256-16-v1") {
669
+ const nonce = await transport.requestNonce(session);
670
+ const minted = await deps.grants.mint(grant.grant_id, nonce);
671
+ token = minted.token;
672
+ keyVersion = minted.key_version;
673
+ }
674
+ if (!token) {
675
+ throw new RelaiError(
676
+ `Grant ${grant.grant_id} has no token to deliver (algorithm ${grant.algorithm}).`
677
+ );
678
+ }
679
+ const ack = await transport.sendCommand(session, token);
680
+ if (!ack.accepted && isWrongParentReject(ack.rejectReason ?? "")) {
681
+ return null;
682
+ }
683
+ if (!ack.accepted) {
684
+ await reportOutcome(false, ack.rejectReason ?? "UNKNOWN");
685
+ throw new RelaiUnlockRejected(ack.rejectReason ?? "UNKNOWN", ack.verbHint);
686
+ }
687
+ await reportOutcome(true);
688
+ await cache.set(parentBleId, handle);
689
+ keep = Boolean(opts.keepConnected);
690
+ return { open, accepted: true, command: ack.command, keyVersion, session };
691
+ } finally {
692
+ if (!keep) await transport.disconnect(session).catch(() => void 0);
603
693
  }
604
- const ack = await transport.sendCommand(session, token);
605
- const ezId = opts.exchangeZoneId ?? grant.ez_id;
606
- if (ezId) {
607
- void deps.telemetry.submit({
608
- exchangeZoneId: ezId,
609
- grantId: grant.grant_id,
610
- events: [
611
- {
612
- action: ack.accepted ? "unlock_used" : "unlock_failed",
613
- result: ack.accepted ? "success" : "failure",
614
- transport: "ble",
615
- at: (/* @__PURE__ */ new Date()).toISOString(),
616
- // The Parent's own reject reason, so a failure is diagnosable
617
- // rather than merely counted.
618
- ...ack.accepted ? {} : { reason: ack.rejectReason ?? "UNKNOWN" }
619
- }
620
- ]
621
- }).catch(() => void 0);
694
+ }
695
+ async function reportOutcome(accepted, reason) {
696
+ if (!ezId) return;
697
+ void deps.telemetry.submit({
698
+ exchangeZoneId: ezId,
699
+ grantId: grant.grant_id,
700
+ events: [
701
+ {
702
+ action: accepted ? "unlock_used" : "unlock_failed",
703
+ result: accepted ? "success" : "failure",
704
+ transport: "ble",
705
+ at: (/* @__PURE__ */ new Date()).toISOString(),
706
+ // The Parent's own reject reason, so a failure is diagnosable
707
+ // rather than merely counted.
708
+ ...accepted ? {} : { reason: reason ?? "UNKNOWN" }
709
+ }
710
+ ]
711
+ }).catch(() => void 0);
712
+ }
713
+ let candidates = orderCandidates({ cached: await cache.get(parentBleId), parentBleId });
714
+ let scanned = false;
715
+ let lastConnectError;
716
+ for (let i = 0; i < MAX_PARENT_ATTEMPTS; i++) {
717
+ if (i >= candidates.length) {
718
+ if (scanned) break;
719
+ scanned = true;
720
+ const found = await transport.scan().catch(() => []);
721
+ const scannedSerials = /* @__PURE__ */ new Map();
722
+ for (const d of found) {
723
+ if (d.serial) scannedSerials.set(d.parentBleId, d.serial);
724
+ }
725
+ candidates = orderCandidates({
726
+ parentBleId,
727
+ scanned: found.map((d) => d.parentBleId),
728
+ scannedSerials,
729
+ parentSerial: open.grant.parent_serial
730
+ });
731
+ await cache.forget(parentBleId);
732
+ if (i >= candidates.length) break;
622
733
  }
623
- if (!ack.accepted) {
624
- throw new RelaiUnlockRejected(ack.rejectReason ?? "UNKNOWN", ack.verbHint);
734
+ const handle = candidates[i];
735
+ try {
736
+ const result = await attempt(handle);
737
+ if (result) return result;
738
+ } catch (err) {
739
+ if (isParentUnreachable(err)) {
740
+ lastConnectError = err;
741
+ continue;
742
+ }
743
+ throw err;
625
744
  }
626
- return {
627
- open,
628
- accepted: true,
629
- command: ack.command,
630
- keyVersion,
631
- session
632
- };
633
- } finally {
634
- if (!opts.keepConnected) await transport.disconnect(session).catch(() => void 0);
635
745
  }
746
+ await reportOutcome(false, "NO_PARENT");
747
+ const detail = lastConnectError instanceof Error ? ` Last error: ${lastConnectError.message}` : "";
748
+ throw new RelaiTransportError(
749
+ `No Parent in range accepted the command for grant ${grant.grant_id}. Check that you are standing at the Exchange Zone and that Bluetooth is on.${detail}`
750
+ );
751
+ }
752
+ function isParentUnreachable(err) {
753
+ if (!(err instanceof Error)) return false;
754
+ if (err instanceof RelaiTransportError) return true;
755
+ if (err instanceof RelaiError) return false;
756
+ return true;
636
757
  }
637
758
 
638
759
  // src/client.ts
@@ -929,6 +1050,46 @@ var SimAuthenticatedTransport = class {
929
1050
  }
930
1051
  };
931
1052
 
1053
+ // src/parent-advertisement.ts
1054
+ var COMPANY_ID = 65535;
1055
+ var FORMAT_VERSION = 1;
1056
+ var HEADER_BYTES = 3;
1057
+ var SERIAL_MAX = 12;
1058
+ function decodeBase64(value) {
1059
+ try {
1060
+ const binary = typeof atob === "function" ? atob(value) : (
1061
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1062
+ globalThis.Buffer.from(value, "base64").toString("binary")
1063
+ );
1064
+ const out = new Uint8Array(binary.length);
1065
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
1066
+ return out;
1067
+ } catch {
1068
+ return null;
1069
+ }
1070
+ }
1071
+ function parseAdvertisedSerial(value) {
1072
+ if (!value) return null;
1073
+ const bytes = decodeBase64(value);
1074
+ if (!bytes || bytes.length <= HEADER_BYTES) return null;
1075
+ const company = bytes[0] | bytes[1] << 8;
1076
+ if (company !== COMPANY_ID) return null;
1077
+ if (bytes[2] !== FORMAT_VERSION) return null;
1078
+ const body = bytes.subarray(HEADER_BYTES);
1079
+ if (body.length > SERIAL_MAX) return null;
1080
+ let serial = "";
1081
+ for (const byte of body) {
1082
+ const char = String.fromCharCode(byte);
1083
+ if (!/[A-Z0-9._:/-]/.test(char)) return null;
1084
+ serial += char;
1085
+ }
1086
+ return serial.length > 0 ? serial : null;
1087
+ }
1088
+ function serialMatches(advertised, granted) {
1089
+ if (!advertised || !granted) return false;
1090
+ return advertised.toUpperCase() === granted.toUpperCase();
1091
+ }
1092
+
932
1093
  // src/transport/notify.ts
933
1094
  var REJECT_REASONS = [
934
1095
  "B64",
@@ -975,11 +1136,65 @@ var BleTransport = class {
975
1136
  this.scanImpl = opts.scan;
976
1137
  this.notifyTimeoutMs = opts.notifyTimeoutMs ?? NOTIFY_TIMEOUT_MS;
977
1138
  }
978
- scan() {
979
- if (!this.scanImpl) {
980
- return Promise.reject(new RelaiTransportError("No scan() provided to BleTransport; drive discovery from your app."));
1139
+ /**
1140
+ * Relai Parents in range.
1141
+ *
1142
+ * An app-supplied `scan` still wins, because an app with its own discovery UI
1143
+ * has already solved this and may filter differently. Otherwise the manager's
1144
+ * own scanner is driven here, filtered to the Relai service so the list is
1145
+ * Parents rather than every radio in the building.
1146
+ *
1147
+ * Results are ordered by signal, strongest first. That is a weak hint and
1148
+ * treated as one: towers at an Exchange Zone stand side by side, so signal
1149
+ * barely separates them. What actually identifies a Parent is that it accepts
1150
+ * the command; this ordering only decides who gets asked first.
1151
+ */
1152
+ scan(timeoutMs = 4e3) {
1153
+ if (this.scanImpl) return this.scanImpl();
1154
+ const manager = this.manager;
1155
+ if (!manager.startDeviceScan || !manager.stopDeviceScan) {
1156
+ return Promise.reject(
1157
+ new RelaiTransportError("No scan() provided to BleTransport; drive discovery from your app.")
1158
+ );
981
1159
  }
982
- return this.scanImpl();
1160
+ return new Promise((resolve) => {
1161
+ const found = /* @__PURE__ */ new Map();
1162
+ let settled = false;
1163
+ const finish = () => {
1164
+ if (settled) return;
1165
+ settled = true;
1166
+ try {
1167
+ manager.stopDeviceScan();
1168
+ } catch {
1169
+ }
1170
+ resolve([...found.values()].sort((a, b) => (b.rssi ?? -999) - (a.rssi ?? -999)));
1171
+ };
1172
+ const timer = setTimeout(finish, timeoutMs);
1173
+ try {
1174
+ manager.startDeviceScan([RELAI_UART_SERVICE], null, (error, device) => {
1175
+ if (error) {
1176
+ clearTimeout(timer);
1177
+ finish();
1178
+ return;
1179
+ }
1180
+ if (!device?.id || found.has(device.id)) return;
1181
+ const fields = device;
1182
+ const rssi = fields.rssi;
1183
+ const serial = parseAdvertisedSerial(fields.manufacturerData);
1184
+ found.set(device.id, {
1185
+ parentBleId: device.id,
1186
+ isSimulated: false,
1187
+ // Spread rather than assigned: exactOptionalPropertyTypes means an
1188
+ // explicit `undefined` is not the same as an absent field.
1189
+ ...typeof rssi === "number" ? { rssi } : {},
1190
+ ...serial ? { serial } : {}
1191
+ });
1192
+ });
1193
+ } catch {
1194
+ clearTimeout(timer);
1195
+ finish();
1196
+ }
1197
+ });
983
1198
  }
984
1199
  async connect(parentBleId) {
985
1200
  let device = await this.manager.connectToDevice(parentBleId);
@@ -1107,4 +1322,4 @@ var Intents = {
1107
1322
  MakeAvailable: "make_available"
1108
1323
  };
1109
1324
 
1110
- export { AccessLinksModule, AppModule, AuthModule, BleTransport, EndUsersModule, ExchangeZonesModule, GrantsModule, Intents, MemoryTelemetryQueue, MemoryTokenStorage, OrdersModule, OverrideLinksModule, PushModule, REJECT_REASONS, RELAI_RX_CHAR, RELAI_TX_CHAR, RELAI_UART_SERVICE, RecipientsModule, RelaiClient, SandboxModule, SimAuthenticatedTransport, SimulatedTransport, StorageTelemetryQueue, TelemetryModule, TelemetryUploader, deliverOpen, isRetryableRejectReason, parseNotifyLine, verifyWebhook };
1325
+ export { AccessLinksModule, AppModule, AuthModule, BleTransport, EndUsersModule, ExchangeZonesModule, GrantsModule, Intents, MemoryTelemetryQueue, MemoryTokenStorage, OrdersModule, OverrideLinksModule, PushModule, REJECT_REASONS, RELAI_RX_CHAR, RELAI_TX_CHAR, RELAI_UART_SERVICE, RecipientsModule, RelaiClient, SandboxModule, SimAuthenticatedTransport, SimulatedTransport, StorageTelemetryQueue, TelemetryModule, TelemetryUploader, deliverOpen, isRetryableRejectReason, parseAdvertisedSerial, parseNotifyLine, serialMatches, verifyWebhook };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@relai-team/access-sdk",
3
- "version": "0.18.1",
3
+ "version": "0.19.0",
4
4
  "description": "Official Relai Access SDK, open Relai Exchange Zone nodes over BLE, backed by the Relai Access platform (server-owns-trust).",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -22,6 +22,7 @@
22
22
  "sideEffects": false,
23
23
  "scripts": {
24
24
  "build": "tsup",
25
+ "prepack": "npm run build",
25
26
  "typecheck": "tsc --noEmit",
26
27
  "pretest": "npm run build",
27
28
  "test": "vitest run",