@relai-team/access-sdk 0.18.2 → 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 +250 -47
- package/dist/index.d.cts +145 -56
- package/dist/index.d.ts +145 -56
- package/dist/index.js +248 -49
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -754,6 +754,63 @@ init_errors();
|
|
|
754
754
|
|
|
755
755
|
// src/unlock.ts
|
|
756
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
|
|
757
814
|
async function deliverOpen(deps, open, opts) {
|
|
758
815
|
const { transport } = opts;
|
|
759
816
|
const grant = open.grant;
|
|
@@ -763,53 +820,103 @@ async function deliverOpen(deps, open, opts) {
|
|
|
763
820
|
`Grant ${grant.grant_id} names no parent_ble_id and none was provided; cannot select a Parent.`
|
|
764
821
|
);
|
|
765
822
|
}
|
|
766
|
-
const
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
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);
|
|
780
856
|
}
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
if (ezId)
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
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;
|
|
799
896
|
}
|
|
800
|
-
|
|
801
|
-
|
|
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;
|
|
802
907
|
}
|
|
803
|
-
return {
|
|
804
|
-
open,
|
|
805
|
-
accepted: true,
|
|
806
|
-
command: ack.command,
|
|
807
|
-
keyVersion,
|
|
808
|
-
session
|
|
809
|
-
};
|
|
810
|
-
} finally {
|
|
811
|
-
if (!opts.keepConnected) await transport.disconnect(session).catch(() => void 0);
|
|
812
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;
|
|
813
920
|
}
|
|
814
921
|
|
|
815
922
|
// src/client.ts
|
|
@@ -1113,6 +1220,46 @@ var SimAuthenticatedTransport = class {
|
|
|
1113
1220
|
// src/transport/ble.ts
|
|
1114
1221
|
init_errors();
|
|
1115
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
|
+
|
|
1116
1263
|
// src/transport/notify.ts
|
|
1117
1264
|
var REJECT_REASONS = [
|
|
1118
1265
|
"B64",
|
|
@@ -1159,11 +1306,65 @@ var BleTransport = class {
|
|
|
1159
1306
|
this.scanImpl = opts.scan;
|
|
1160
1307
|
this.notifyTimeoutMs = opts.notifyTimeoutMs ?? NOTIFY_TIMEOUT_MS;
|
|
1161
1308
|
}
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
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
|
+
);
|
|
1165
1329
|
}
|
|
1166
|
-
return
|
|
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
|
+
});
|
|
1167
1368
|
}
|
|
1168
1369
|
async connect(parentBleId) {
|
|
1169
1370
|
let device = await this.manager.connectToDevice(parentBleId);
|
|
@@ -1323,6 +1524,8 @@ exports.asPaymentRequired = asPaymentRequired;
|
|
|
1323
1524
|
exports.deliverOpen = deliverOpen;
|
|
1324
1525
|
exports.isRetryableRejectReason = isRetryableRejectReason;
|
|
1325
1526
|
exports.isStripePublishableKey = isStripePublishableKey;
|
|
1527
|
+
exports.parseAdvertisedSerial = parseAdvertisedSerial;
|
|
1326
1528
|
exports.parseNotifyLine = parseNotifyLine;
|
|
1327
1529
|
exports.presentRelaiPaymentSheet = presentRelaiPaymentSheet;
|
|
1530
|
+
exports.serialMatches = serialMatches;
|
|
1328
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;
|
|
@@ -953,6 +963,12 @@ interface DiscoveredParent {
|
|
|
953
963
|
parentBleId: string;
|
|
954
964
|
/** The tower this Parent controls, when known from discovery context. */
|
|
955
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;
|
|
956
972
|
rssi?: number;
|
|
957
973
|
isSimulated: boolean;
|
|
958
974
|
}
|
|
@@ -988,6 +1004,60 @@ interface ParentTransport {
|
|
|
988
1004
|
disconnect(session: Session): Promise<void>;
|
|
989
1005
|
}
|
|
990
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
|
+
|
|
991
1061
|
interface UnlockDeps {
|
|
992
1062
|
grants: GrantsModule;
|
|
993
1063
|
telemetry: TelemetryUploader;
|
|
@@ -1012,6 +1082,14 @@ interface DeliverOptions {
|
|
|
1012
1082
|
exchangeZoneId?: string;
|
|
1013
1083
|
/** Keep the BLE session open after the unlock (default: disconnect). */
|
|
1014
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;
|
|
1015
1093
|
}
|
|
1016
1094
|
/**
|
|
1017
1095
|
* Deliver an already-issued Open to a Parent. Splits out so callers who created
|
|
@@ -1223,60 +1301,6 @@ declare class RelaiClient {
|
|
|
1223
1301
|
unlock(input: UnlockInput): Promise<UnlockResult>;
|
|
1224
1302
|
}
|
|
1225
1303
|
|
|
1226
|
-
/**
|
|
1227
|
-
* Persistent telemetry queue (owner, 2026-07-24). `MemoryTelemetryQueue` loses
|
|
1228
|
-
* anything queued when the app is killed; a React Native app that opens nodes
|
|
1229
|
-
* offline needs its unreported opens to survive a restart. This backs the same
|
|
1230
|
-
* `TelemetryQueue` interface with a key-value store.
|
|
1231
|
-
*
|
|
1232
|
-
* The store is AsyncStorage-shaped on purpose, so RN apps pass the library in
|
|
1233
|
-
* directly (it is an OPTIONAL dependency: the SDK core never imports it):
|
|
1234
|
-
*
|
|
1235
|
-
* import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
1236
|
-
* const client = new RelaiClient({
|
|
1237
|
-
* publishableKey,
|
|
1238
|
-
* telemetryQueue: new StorageTelemetryQueue(AsyncStorage),
|
|
1239
|
-
* });
|
|
1240
|
-
*
|
|
1241
|
-
* The whole queue is one JSON blob under a single key: telemetry volume is one
|
|
1242
|
-
* item per open, so this stays small; writes are serialized through an internal
|
|
1243
|
-
* lock so concurrent submit/flush calls can't clobber each other.
|
|
1244
|
-
*/
|
|
1245
|
-
|
|
1246
|
-
/** The subset of AsyncStorage (and localStorage-async wrappers) we need. */
|
|
1247
|
-
interface KeyValueStorage {
|
|
1248
|
-
getItem(key: string): Promise<string | null>;
|
|
1249
|
-
setItem(key: string, value: string): Promise<void>;
|
|
1250
|
-
removeItem(key: string): Promise<void>;
|
|
1251
|
-
}
|
|
1252
|
-
interface StorageTelemetryQueueOptions {
|
|
1253
|
-
/** Storage key for the serialized queue. Default `@relai/telemetry-queue`. */
|
|
1254
|
-
storageKey?: string;
|
|
1255
|
-
/**
|
|
1256
|
-
* Hard cap on queued items; when exceeded the OLDEST are dropped so a long
|
|
1257
|
-
* outage can't grow storage without bound. Default 500.
|
|
1258
|
-
*/
|
|
1259
|
-
maxItems?: number;
|
|
1260
|
-
}
|
|
1261
|
-
declare class StorageTelemetryQueue implements TelemetryQueue {
|
|
1262
|
-
private readonly storage;
|
|
1263
|
-
private readonly key;
|
|
1264
|
-
private readonly maxItems;
|
|
1265
|
-
/** Serializes read-modify-write so concurrent calls don't lose updates. */
|
|
1266
|
-
private chain;
|
|
1267
|
-
private seq;
|
|
1268
|
-
constructor(storage: KeyValueStorage, opts?: StorageTelemetryQueueOptions);
|
|
1269
|
-
enqueue(payload: TelemetryPayload): Promise<void>;
|
|
1270
|
-
list(): Promise<QueuedTelemetry[]>;
|
|
1271
|
-
remove(id: string): Promise<void>;
|
|
1272
|
-
markAttempt(id: string): Promise<void>;
|
|
1273
|
-
private nextId;
|
|
1274
|
-
/** Serialize an operation after any in-flight ones (a simple promise lock). */
|
|
1275
|
-
private run;
|
|
1276
|
-
private mutate;
|
|
1277
|
-
private read;
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
1304
|
/**
|
|
1281
1305
|
* SimulatedTransport: lets an app exercise the full open flow with no hardware.
|
|
1282
1306
|
* It emulates the Parent's notify surface: issues a random nonce on CHALLENGE,
|
|
@@ -1344,6 +1368,16 @@ interface BleDeviceLike {
|
|
|
1344
1368
|
interface BleManagerLike {
|
|
1345
1369
|
connectToDevice(id: string, options?: unknown): Promise<BleDeviceLike>;
|
|
1346
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;
|
|
1347
1381
|
}
|
|
1348
1382
|
interface BleTransportOptions {
|
|
1349
1383
|
manager: BleManagerLike;
|
|
@@ -1357,7 +1391,20 @@ declare class BleTransport implements ParentTransport {
|
|
|
1357
1391
|
private readonly scanImpl;
|
|
1358
1392
|
private readonly notifyTimeoutMs;
|
|
1359
1393
|
constructor(opts: BleTransportOptions);
|
|
1360
|
-
|
|
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[]>;
|
|
1361
1408
|
connect(parentBleId: string): Promise<Session>;
|
|
1362
1409
|
requestNonce(session: Session): Promise<string>;
|
|
1363
1410
|
sendCommand(session: Session, token: string): Promise<CommandAck>;
|
|
@@ -1434,6 +1481,48 @@ declare function isRetryableRejectReason(reason: string): boolean;
|
|
|
1434
1481
|
/** Parse one already-decoded (plain-text) notify line. */
|
|
1435
1482
|
declare function parseNotifyLine(line: string): NotifyLine;
|
|
1436
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
|
+
|
|
1437
1526
|
/**
|
|
1438
1527
|
* Webhook verification for partner BACKENDS (Node 18+ / edge: WebCrypto).
|
|
1439
1528
|
* Pinned platform scheme (2026-07-23, Stripe-style):
|
|
@@ -1596,4 +1685,4 @@ declare class RelaiTransportError extends RelaiError {
|
|
|
1596
1685
|
constructor(message: string);
|
|
1597
1686
|
}
|
|
1598
1687
|
|
|
1599
|
-
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;
|
|
@@ -953,6 +963,12 @@ interface DiscoveredParent {
|
|
|
953
963
|
parentBleId: string;
|
|
954
964
|
/** The tower this Parent controls, when known from discovery context. */
|
|
955
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;
|
|
956
972
|
rssi?: number;
|
|
957
973
|
isSimulated: boolean;
|
|
958
974
|
}
|
|
@@ -988,6 +1004,60 @@ interface ParentTransport {
|
|
|
988
1004
|
disconnect(session: Session): Promise<void>;
|
|
989
1005
|
}
|
|
990
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
|
+
|
|
991
1061
|
interface UnlockDeps {
|
|
992
1062
|
grants: GrantsModule;
|
|
993
1063
|
telemetry: TelemetryUploader;
|
|
@@ -1012,6 +1082,14 @@ interface DeliverOptions {
|
|
|
1012
1082
|
exchangeZoneId?: string;
|
|
1013
1083
|
/** Keep the BLE session open after the unlock (default: disconnect). */
|
|
1014
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;
|
|
1015
1093
|
}
|
|
1016
1094
|
/**
|
|
1017
1095
|
* Deliver an already-issued Open to a Parent. Splits out so callers who created
|
|
@@ -1223,60 +1301,6 @@ declare class RelaiClient {
|
|
|
1223
1301
|
unlock(input: UnlockInput): Promise<UnlockResult>;
|
|
1224
1302
|
}
|
|
1225
1303
|
|
|
1226
|
-
/**
|
|
1227
|
-
* Persistent telemetry queue (owner, 2026-07-24). `MemoryTelemetryQueue` loses
|
|
1228
|
-
* anything queued when the app is killed; a React Native app that opens nodes
|
|
1229
|
-
* offline needs its unreported opens to survive a restart. This backs the same
|
|
1230
|
-
* `TelemetryQueue` interface with a key-value store.
|
|
1231
|
-
*
|
|
1232
|
-
* The store is AsyncStorage-shaped on purpose, so RN apps pass the library in
|
|
1233
|
-
* directly (it is an OPTIONAL dependency: the SDK core never imports it):
|
|
1234
|
-
*
|
|
1235
|
-
* import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
1236
|
-
* const client = new RelaiClient({
|
|
1237
|
-
* publishableKey,
|
|
1238
|
-
* telemetryQueue: new StorageTelemetryQueue(AsyncStorage),
|
|
1239
|
-
* });
|
|
1240
|
-
*
|
|
1241
|
-
* The whole queue is one JSON blob under a single key: telemetry volume is one
|
|
1242
|
-
* item per open, so this stays small; writes are serialized through an internal
|
|
1243
|
-
* lock so concurrent submit/flush calls can't clobber each other.
|
|
1244
|
-
*/
|
|
1245
|
-
|
|
1246
|
-
/** The subset of AsyncStorage (and localStorage-async wrappers) we need. */
|
|
1247
|
-
interface KeyValueStorage {
|
|
1248
|
-
getItem(key: string): Promise<string | null>;
|
|
1249
|
-
setItem(key: string, value: string): Promise<void>;
|
|
1250
|
-
removeItem(key: string): Promise<void>;
|
|
1251
|
-
}
|
|
1252
|
-
interface StorageTelemetryQueueOptions {
|
|
1253
|
-
/** Storage key for the serialized queue. Default `@relai/telemetry-queue`. */
|
|
1254
|
-
storageKey?: string;
|
|
1255
|
-
/**
|
|
1256
|
-
* Hard cap on queued items; when exceeded the OLDEST are dropped so a long
|
|
1257
|
-
* outage can't grow storage without bound. Default 500.
|
|
1258
|
-
*/
|
|
1259
|
-
maxItems?: number;
|
|
1260
|
-
}
|
|
1261
|
-
declare class StorageTelemetryQueue implements TelemetryQueue {
|
|
1262
|
-
private readonly storage;
|
|
1263
|
-
private readonly key;
|
|
1264
|
-
private readonly maxItems;
|
|
1265
|
-
/** Serializes read-modify-write so concurrent calls don't lose updates. */
|
|
1266
|
-
private chain;
|
|
1267
|
-
private seq;
|
|
1268
|
-
constructor(storage: KeyValueStorage, opts?: StorageTelemetryQueueOptions);
|
|
1269
|
-
enqueue(payload: TelemetryPayload): Promise<void>;
|
|
1270
|
-
list(): Promise<QueuedTelemetry[]>;
|
|
1271
|
-
remove(id: string): Promise<void>;
|
|
1272
|
-
markAttempt(id: string): Promise<void>;
|
|
1273
|
-
private nextId;
|
|
1274
|
-
/** Serialize an operation after any in-flight ones (a simple promise lock). */
|
|
1275
|
-
private run;
|
|
1276
|
-
private mutate;
|
|
1277
|
-
private read;
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
1304
|
/**
|
|
1281
1305
|
* SimulatedTransport: lets an app exercise the full open flow with no hardware.
|
|
1282
1306
|
* It emulates the Parent's notify surface: issues a random nonce on CHALLENGE,
|
|
@@ -1344,6 +1368,16 @@ interface BleDeviceLike {
|
|
|
1344
1368
|
interface BleManagerLike {
|
|
1345
1369
|
connectToDevice(id: string, options?: unknown): Promise<BleDeviceLike>;
|
|
1346
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;
|
|
1347
1381
|
}
|
|
1348
1382
|
interface BleTransportOptions {
|
|
1349
1383
|
manager: BleManagerLike;
|
|
@@ -1357,7 +1391,20 @@ declare class BleTransport implements ParentTransport {
|
|
|
1357
1391
|
private readonly scanImpl;
|
|
1358
1392
|
private readonly notifyTimeoutMs;
|
|
1359
1393
|
constructor(opts: BleTransportOptions);
|
|
1360
|
-
|
|
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[]>;
|
|
1361
1408
|
connect(parentBleId: string): Promise<Session>;
|
|
1362
1409
|
requestNonce(session: Session): Promise<string>;
|
|
1363
1410
|
sendCommand(session: Session, token: string): Promise<CommandAck>;
|
|
@@ -1434,6 +1481,48 @@ declare function isRetryableRejectReason(reason: string): boolean;
|
|
|
1434
1481
|
/** Parse one already-decoded (plain-text) notify line. */
|
|
1435
1482
|
declare function parseNotifyLine(line: string): NotifyLine;
|
|
1436
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
|
+
|
|
1437
1526
|
/**
|
|
1438
1527
|
* Webhook verification for partner BACKENDS (Node 18+ / edge: WebCrypto).
|
|
1439
1528
|
* Pinned platform scheme (2026-07-23, Stripe-style):
|
|
@@ -1596,4 +1685,4 @@ declare class RelaiTransportError extends RelaiError {
|
|
|
1596
1685
|
constructor(message: string);
|
|
1597
1686
|
}
|
|
1598
1687
|
|
|
1599
|
-
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,
|
|
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
|
|
|
@@ -592,6 +592,61 @@ var TelemetryUploader = class {
|
|
|
592
592
|
}
|
|
593
593
|
};
|
|
594
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
|
+
|
|
595
650
|
// src/unlock.ts
|
|
596
651
|
async function deliverOpen(deps, open, opts) {
|
|
597
652
|
const { transport } = opts;
|
|
@@ -602,53 +657,103 @@ async function deliverOpen(deps, open, opts) {
|
|
|
602
657
|
`Grant ${grant.grant_id} names no parent_ble_id and none was provided; cannot select a Parent.`
|
|
603
658
|
);
|
|
604
659
|
}
|
|
605
|
-
const
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
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);
|
|
619
693
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
if (ezId)
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
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;
|
|
638
733
|
}
|
|
639
|
-
|
|
640
|
-
|
|
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;
|
|
641
744
|
}
|
|
642
|
-
return {
|
|
643
|
-
open,
|
|
644
|
-
accepted: true,
|
|
645
|
-
command: ack.command,
|
|
646
|
-
keyVersion,
|
|
647
|
-
session
|
|
648
|
-
};
|
|
649
|
-
} finally {
|
|
650
|
-
if (!opts.keepConnected) await transport.disconnect(session).catch(() => void 0);
|
|
651
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;
|
|
652
757
|
}
|
|
653
758
|
|
|
654
759
|
// src/client.ts
|
|
@@ -945,6 +1050,46 @@ var SimAuthenticatedTransport = class {
|
|
|
945
1050
|
}
|
|
946
1051
|
};
|
|
947
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
|
+
|
|
948
1093
|
// src/transport/notify.ts
|
|
949
1094
|
var REJECT_REASONS = [
|
|
950
1095
|
"B64",
|
|
@@ -991,11 +1136,65 @@ var BleTransport = class {
|
|
|
991
1136
|
this.scanImpl = opts.scan;
|
|
992
1137
|
this.notifyTimeoutMs = opts.notifyTimeoutMs ?? NOTIFY_TIMEOUT_MS;
|
|
993
1138
|
}
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
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
|
+
);
|
|
997
1159
|
}
|
|
998
|
-
return
|
|
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
|
+
});
|
|
999
1198
|
}
|
|
1000
1199
|
async connect(parentBleId) {
|
|
1001
1200
|
let device = await this.manager.connectToDevice(parentBleId);
|
|
@@ -1123,4 +1322,4 @@ var Intents = {
|
|
|
1123
1322
|
MakeAvailable: "make_available"
|
|
1124
1323
|
};
|
|
1125
1324
|
|
|
1126
|
-
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.
|
|
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",
|