@relai-team/access-sdk 0.18.2 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +259 -48
- package/dist/index.d.cts +172 -56
- package/dist/index.d.ts +172 -56
- package/dist/index.js +257 -50
- 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
|
|
@@ -818,6 +925,7 @@ var RelaiClient = class {
|
|
|
818
925
|
constructor(options) {
|
|
819
926
|
if (!options.publishableKey && !options.secretKey) throw new exports.RelaiMissingKeyError();
|
|
820
927
|
this.stripe = options.stripe;
|
|
928
|
+
this.handleStorage = options.handleStorage;
|
|
821
929
|
const storage = options.tokenStorage ?? new MemoryTokenStorage();
|
|
822
930
|
let auth;
|
|
823
931
|
const httpConfig = {
|
|
@@ -899,7 +1007,12 @@ var RelaiClient = class {
|
|
|
899
1007
|
transport: input.transport,
|
|
900
1008
|
...input.parentBleId !== void 0 ? { parentBleId: input.parentBleId } : {},
|
|
901
1009
|
...input.exchangeZoneId !== void 0 ? { exchangeZoneId: input.exchangeZoneId } : {},
|
|
902
|
-
...input.keepConnected !== void 0 ? { keepConnected: input.keepConnected } : {}
|
|
1010
|
+
...input.keepConnected !== void 0 ? { keepConnected: input.keepConnected } : {},
|
|
1011
|
+
// Per-call first, then the client's. Spread rather than assigned:
|
|
1012
|
+
// exactOptionalPropertyTypes makes an explicit `undefined` a value, and
|
|
1013
|
+
// `new ParentHandleCache(undefined)` is a cache that silently does
|
|
1014
|
+
// nothing, which is precisely the bug being fixed.
|
|
1015
|
+
...input.handleStorage ?? this.handleStorage ? { handleStorage: input.handleStorage ?? this.handleStorage } : {}
|
|
903
1016
|
}
|
|
904
1017
|
);
|
|
905
1018
|
}
|
|
@@ -992,6 +1105,21 @@ function base64ToUtf8(b64) {
|
|
|
992
1105
|
if (g.atob) return decodeURIComponent(escape(g.atob(b64)));
|
|
993
1106
|
throw new Error("No base64 decoder available in this runtime.");
|
|
994
1107
|
}
|
|
1108
|
+
function base64ToBytes(b64) {
|
|
1109
|
+
const g = globalThis;
|
|
1110
|
+
try {
|
|
1111
|
+
if (g.Buffer) return new Uint8Array(g.Buffer.from(b64, "base64"));
|
|
1112
|
+
if (g.atob) {
|
|
1113
|
+
const binary = g.atob(b64);
|
|
1114
|
+
const out = new Uint8Array(binary.length);
|
|
1115
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
1116
|
+
return out;
|
|
1117
|
+
}
|
|
1118
|
+
return null;
|
|
1119
|
+
} catch {
|
|
1120
|
+
return null;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
995
1123
|
|
|
996
1124
|
// src/transport/simulated.ts
|
|
997
1125
|
function randomNonceB64Url() {
|
|
@@ -1113,6 +1241,33 @@ var SimAuthenticatedTransport = class {
|
|
|
1113
1241
|
// src/transport/ble.ts
|
|
1114
1242
|
init_errors();
|
|
1115
1243
|
|
|
1244
|
+
// src/parent-advertisement.ts
|
|
1245
|
+
var COMPANY_ID = 65535;
|
|
1246
|
+
var FORMAT_VERSION = 1;
|
|
1247
|
+
var HEADER_BYTES = 3;
|
|
1248
|
+
var SERIAL_MAX = 29 - HEADER_BYTES;
|
|
1249
|
+
function parseAdvertisedSerial(value) {
|
|
1250
|
+
if (!value) return null;
|
|
1251
|
+
const bytes = base64ToBytes(value);
|
|
1252
|
+
if (!bytes || bytes.length <= HEADER_BYTES) return null;
|
|
1253
|
+
const company = bytes[0] | bytes[1] << 8;
|
|
1254
|
+
if (company !== COMPANY_ID) return null;
|
|
1255
|
+
if (bytes[2] !== FORMAT_VERSION) return null;
|
|
1256
|
+
const body = bytes.subarray(HEADER_BYTES);
|
|
1257
|
+
if (body.length > SERIAL_MAX) return null;
|
|
1258
|
+
let serial = "";
|
|
1259
|
+
for (const byte of body) {
|
|
1260
|
+
const char = String.fromCharCode(byte);
|
|
1261
|
+
if (!/[A-Z0-9._:/-]/.test(char)) return null;
|
|
1262
|
+
serial += char;
|
|
1263
|
+
}
|
|
1264
|
+
return serial.length > 0 ? serial : null;
|
|
1265
|
+
}
|
|
1266
|
+
function serialMatches(advertised, granted) {
|
|
1267
|
+
if (!advertised || !granted) return false;
|
|
1268
|
+
return advertised.toUpperCase() === granted.toUpperCase();
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1116
1271
|
// src/transport/notify.ts
|
|
1117
1272
|
var REJECT_REASONS = [
|
|
1118
1273
|
"B64",
|
|
@@ -1159,11 +1314,65 @@ var BleTransport = class {
|
|
|
1159
1314
|
this.scanImpl = opts.scan;
|
|
1160
1315
|
this.notifyTimeoutMs = opts.notifyTimeoutMs ?? NOTIFY_TIMEOUT_MS;
|
|
1161
1316
|
}
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1317
|
+
/**
|
|
1318
|
+
* Relai Parents in range.
|
|
1319
|
+
*
|
|
1320
|
+
* An app-supplied `scan` still wins, because an app with its own discovery UI
|
|
1321
|
+
* has already solved this and may filter differently. Otherwise the manager's
|
|
1322
|
+
* own scanner is driven here, filtered to the Relai service so the list is
|
|
1323
|
+
* Parents rather than every radio in the building.
|
|
1324
|
+
*
|
|
1325
|
+
* Results are ordered by signal, strongest first. That is a weak hint and
|
|
1326
|
+
* treated as one: towers at an Exchange Zone stand side by side, so signal
|
|
1327
|
+
* barely separates them. What actually identifies a Parent is that it accepts
|
|
1328
|
+
* the command; this ordering only decides who gets asked first.
|
|
1329
|
+
*/
|
|
1330
|
+
scan(timeoutMs = 4e3) {
|
|
1331
|
+
if (this.scanImpl) return this.scanImpl();
|
|
1332
|
+
const manager = this.manager;
|
|
1333
|
+
if (!manager.startDeviceScan || !manager.stopDeviceScan) {
|
|
1334
|
+
return Promise.reject(
|
|
1335
|
+
new exports.RelaiTransportError("No scan() provided to BleTransport; drive discovery from your app.")
|
|
1336
|
+
);
|
|
1165
1337
|
}
|
|
1166
|
-
return
|
|
1338
|
+
return new Promise((resolve) => {
|
|
1339
|
+
const found = /* @__PURE__ */ new Map();
|
|
1340
|
+
let settled = false;
|
|
1341
|
+
const finish = () => {
|
|
1342
|
+
if (settled) return;
|
|
1343
|
+
settled = true;
|
|
1344
|
+
try {
|
|
1345
|
+
manager.stopDeviceScan();
|
|
1346
|
+
} catch {
|
|
1347
|
+
}
|
|
1348
|
+
resolve([...found.values()].sort((a, b) => (b.rssi ?? -999) - (a.rssi ?? -999)));
|
|
1349
|
+
};
|
|
1350
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
1351
|
+
try {
|
|
1352
|
+
manager.startDeviceScan([RELAI_UART_SERVICE], null, (error, device) => {
|
|
1353
|
+
if (error) {
|
|
1354
|
+
clearTimeout(timer);
|
|
1355
|
+
finish();
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
if (!device?.id || found.has(device.id)) return;
|
|
1359
|
+
const fields = device;
|
|
1360
|
+
const rssi = fields.rssi;
|
|
1361
|
+
const serial = parseAdvertisedSerial(fields.manufacturerData);
|
|
1362
|
+
found.set(device.id, {
|
|
1363
|
+
parentBleId: device.id,
|
|
1364
|
+
isSimulated: false,
|
|
1365
|
+
// Spread rather than assigned: exactOptionalPropertyTypes means an
|
|
1366
|
+
// explicit `undefined` is not the same as an absent field.
|
|
1367
|
+
...typeof rssi === "number" ? { rssi } : {},
|
|
1368
|
+
...serial ? { serial } : {}
|
|
1369
|
+
});
|
|
1370
|
+
});
|
|
1371
|
+
} catch {
|
|
1372
|
+
clearTimeout(timer);
|
|
1373
|
+
finish();
|
|
1374
|
+
}
|
|
1375
|
+
});
|
|
1167
1376
|
}
|
|
1168
1377
|
async connect(parentBleId) {
|
|
1169
1378
|
let device = await this.manager.connectToDevice(parentBleId);
|
|
@@ -1323,6 +1532,8 @@ exports.asPaymentRequired = asPaymentRequired;
|
|
|
1323
1532
|
exports.deliverOpen = deliverOpen;
|
|
1324
1533
|
exports.isRetryableRejectReason = isRetryableRejectReason;
|
|
1325
1534
|
exports.isStripePublishableKey = isStripePublishableKey;
|
|
1535
|
+
exports.parseAdvertisedSerial = parseAdvertisedSerial;
|
|
1326
1536
|
exports.parseNotifyLine = parseNotifyLine;
|
|
1327
1537
|
exports.presentRelaiPaymentSheet = presentRelaiPaymentSheet;
|
|
1538
|
+
exports.serialMatches = serialMatches;
|
|
1328
1539
|
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;
|
|
@@ -920,6 +930,60 @@ declare class TelemetryUploader {
|
|
|
920
930
|
}>;
|
|
921
931
|
}
|
|
922
932
|
|
|
933
|
+
/**
|
|
934
|
+
* Persistent telemetry queue (owner, 2026-07-24). `MemoryTelemetryQueue` loses
|
|
935
|
+
* anything queued when the app is killed; a React Native app that opens nodes
|
|
936
|
+
* offline needs its unreported opens to survive a restart. This backs the same
|
|
937
|
+
* `TelemetryQueue` interface with a key-value store.
|
|
938
|
+
*
|
|
939
|
+
* The store is AsyncStorage-shaped on purpose, so RN apps pass the library in
|
|
940
|
+
* directly (it is an OPTIONAL dependency: the SDK core never imports it):
|
|
941
|
+
*
|
|
942
|
+
* import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
943
|
+
* const client = new RelaiClient({
|
|
944
|
+
* publishableKey,
|
|
945
|
+
* telemetryQueue: new StorageTelemetryQueue(AsyncStorage),
|
|
946
|
+
* });
|
|
947
|
+
*
|
|
948
|
+
* The whole queue is one JSON blob under a single key: telemetry volume is one
|
|
949
|
+
* item per open, so this stays small; writes are serialized through an internal
|
|
950
|
+
* lock so concurrent submit/flush calls can't clobber each other.
|
|
951
|
+
*/
|
|
952
|
+
|
|
953
|
+
/** The subset of AsyncStorage (and localStorage-async wrappers) we need. */
|
|
954
|
+
interface KeyValueStorage {
|
|
955
|
+
getItem(key: string): Promise<string | null>;
|
|
956
|
+
setItem(key: string, value: string): Promise<void>;
|
|
957
|
+
removeItem(key: string): Promise<void>;
|
|
958
|
+
}
|
|
959
|
+
interface StorageTelemetryQueueOptions {
|
|
960
|
+
/** Storage key for the serialized queue. Default `@relai/telemetry-queue`. */
|
|
961
|
+
storageKey?: string;
|
|
962
|
+
/**
|
|
963
|
+
* Hard cap on queued items; when exceeded the OLDEST are dropped so a long
|
|
964
|
+
* outage can't grow storage without bound. Default 500.
|
|
965
|
+
*/
|
|
966
|
+
maxItems?: number;
|
|
967
|
+
}
|
|
968
|
+
declare class StorageTelemetryQueue implements TelemetryQueue {
|
|
969
|
+
private readonly storage;
|
|
970
|
+
private readonly key;
|
|
971
|
+
private readonly maxItems;
|
|
972
|
+
/** Serializes read-modify-write so concurrent calls don't lose updates. */
|
|
973
|
+
private chain;
|
|
974
|
+
private seq;
|
|
975
|
+
constructor(storage: KeyValueStorage, opts?: StorageTelemetryQueueOptions);
|
|
976
|
+
enqueue(payload: TelemetryPayload): Promise<void>;
|
|
977
|
+
list(): Promise<QueuedTelemetry[]>;
|
|
978
|
+
remove(id: string): Promise<void>;
|
|
979
|
+
markAttempt(id: string): Promise<void>;
|
|
980
|
+
private nextId;
|
|
981
|
+
/** Serialize an operation after any in-flight ones (a simple promise lock). */
|
|
982
|
+
private run;
|
|
983
|
+
private mutate;
|
|
984
|
+
private read;
|
|
985
|
+
}
|
|
986
|
+
|
|
923
987
|
/**
|
|
924
988
|
* The outcome of writing one authenticated command to a Parent, distilled from
|
|
925
989
|
* the notify surface. `accepted` is the ONLY control-flow signal; `verbHint` is
|
|
@@ -953,6 +1017,12 @@ interface DiscoveredParent {
|
|
|
953
1017
|
parentBleId: string;
|
|
954
1018
|
/** The tower this Parent controls, when known from discovery context. */
|
|
955
1019
|
towerId?: string;
|
|
1020
|
+
/**
|
|
1021
|
+
* The chassis serial read off this Parent's advertisement, when it published
|
|
1022
|
+
* one. UNAUTHENTICATED: it decides which Parent to try first and nothing
|
|
1023
|
+
* else. See `parseAdvertisedSerial`.
|
|
1024
|
+
*/
|
|
1025
|
+
serial?: string;
|
|
956
1026
|
rssi?: number;
|
|
957
1027
|
isSimulated: boolean;
|
|
958
1028
|
}
|
|
@@ -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
|
|
@@ -1123,6 +1201,22 @@ interface RelaiClientOptions {
|
|
|
1123
1201
|
maxRetries?: number;
|
|
1124
1202
|
/** Persistent telemetry queue (default: in-memory). RN apps can back it with storage. */
|
|
1125
1203
|
telemetryQueue?: TelemetryQueue;
|
|
1204
|
+
/**
|
|
1205
|
+
* Where to remember which local handle turned out to be which Parent.
|
|
1206
|
+
*
|
|
1207
|
+
* Pass the same `KeyValueStorage` the telemetry queue uses, typically
|
|
1208
|
+
* AsyncStorage, and an open that resolved a Parent connects straight to it
|
|
1209
|
+
* next time instead of scanning. Omit it and every open rescans, which costs
|
|
1210
|
+
* a few seconds and nothing else.
|
|
1211
|
+
*
|
|
1212
|
+
* HERE rather than only on each `unlock()` call, because the mapping is
|
|
1213
|
+
* per-install device state like `tokenStorage` and `telemetryQueue`: an app
|
|
1214
|
+
* wires its store once. `UnlockInput.handleStorage` overrides it per call.
|
|
1215
|
+
*
|
|
1216
|
+
* The mapping is per device, because the identifier is: the handle this phone
|
|
1217
|
+
* connects by is not the handle another phone gets for the same Parent.
|
|
1218
|
+
*/
|
|
1219
|
+
handleStorage?: KeyValueStorage;
|
|
1126
1220
|
/**
|
|
1127
1221
|
* The `@stripe/stripe-react-native` module, for Relai checkout. Pass it and
|
|
1128
1222
|
* payment-gated opens present the standard Payment Sheet and retry
|
|
@@ -1173,6 +1267,15 @@ interface UnlockInput {
|
|
|
1173
1267
|
/** Admin/partner override link code: bypasses handoff + paywall gates. */
|
|
1174
1268
|
overrideCode?: string;
|
|
1175
1269
|
keepConnected?: boolean;
|
|
1270
|
+
/**
|
|
1271
|
+
* Override the client's `handleStorage` for this open.
|
|
1272
|
+
*
|
|
1273
|
+
* Normally omitted: set it once on the client. This exists because
|
|
1274
|
+
* `deliverOpen` has always accepted it and `unlock()` dropped it silently, so
|
|
1275
|
+
* a Relai-checkout app could not reach the cache at all without
|
|
1276
|
+
* reimplementing the payment handling (partner report, 2026-10-05).
|
|
1277
|
+
*/
|
|
1278
|
+
handleStorage?: KeyValueStorage;
|
|
1176
1279
|
}
|
|
1177
1280
|
declare class RelaiClient {
|
|
1178
1281
|
readonly auth: AuthModule;
|
|
@@ -1197,6 +1300,8 @@ declare class RelaiClient {
|
|
|
1197
1300
|
private readonly http;
|
|
1198
1301
|
/** The app-supplied Stripe module, if any. See `RelaiClientOptions.stripe`. */
|
|
1199
1302
|
private readonly stripe;
|
|
1303
|
+
/** Where resolved Parent handles are remembered. See `RelaiClientOptions.handleStorage`. */
|
|
1304
|
+
private readonly handleStorage;
|
|
1200
1305
|
constructor(options: RelaiClientOptions);
|
|
1201
1306
|
/** Drain any telemetry queued after a failed send (e.g. on app foreground). */
|
|
1202
1307
|
flushTelemetry(): Promise<{
|
|
@@ -1223,60 +1328,6 @@ declare class RelaiClient {
|
|
|
1223
1328
|
unlock(input: UnlockInput): Promise<UnlockResult>;
|
|
1224
1329
|
}
|
|
1225
1330
|
|
|
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
1331
|
/**
|
|
1281
1332
|
* SimulatedTransport: lets an app exercise the full open flow with no hardware.
|
|
1282
1333
|
* It emulates the Parent's notify surface: issues a random nonce on CHALLENGE,
|
|
@@ -1344,6 +1395,16 @@ interface BleDeviceLike {
|
|
|
1344
1395
|
interface BleManagerLike {
|
|
1345
1396
|
connectToDevice(id: string, options?: unknown): Promise<BleDeviceLike>;
|
|
1346
1397
|
discoverAllServicesAndCharacteristicsForDevice?(id: string): Promise<BleDeviceLike>;
|
|
1398
|
+
/**
|
|
1399
|
+
* Discovery, where the platform provides it.
|
|
1400
|
+
*
|
|
1401
|
+
* OPTIONAL so every transport and test double written against the two methods
|
|
1402
|
+
* above keeps compiling. `react-native-ble-plx` has both of these; a manager
|
|
1403
|
+
* without them simply never scans, which is correct on a platform where the
|
|
1404
|
+
* grant's id is already a usable handle.
|
|
1405
|
+
*/
|
|
1406
|
+
startDeviceScan?(serviceUUIDs: string[] | null, options: unknown, listener: (error: unknown, device: BleDeviceLike | null) => void): void;
|
|
1407
|
+
stopDeviceScan?(): void;
|
|
1347
1408
|
}
|
|
1348
1409
|
interface BleTransportOptions {
|
|
1349
1410
|
manager: BleManagerLike;
|
|
@@ -1357,7 +1418,20 @@ declare class BleTransport implements ParentTransport {
|
|
|
1357
1418
|
private readonly scanImpl;
|
|
1358
1419
|
private readonly notifyTimeoutMs;
|
|
1359
1420
|
constructor(opts: BleTransportOptions);
|
|
1360
|
-
|
|
1421
|
+
/**
|
|
1422
|
+
* Relai Parents in range.
|
|
1423
|
+
*
|
|
1424
|
+
* An app-supplied `scan` still wins, because an app with its own discovery UI
|
|
1425
|
+
* has already solved this and may filter differently. Otherwise the manager's
|
|
1426
|
+
* own scanner is driven here, filtered to the Relai service so the list is
|
|
1427
|
+
* Parents rather than every radio in the building.
|
|
1428
|
+
*
|
|
1429
|
+
* Results are ordered by signal, strongest first. That is a weak hint and
|
|
1430
|
+
* treated as one: towers at an Exchange Zone stand side by side, so signal
|
|
1431
|
+
* barely separates them. What actually identifies a Parent is that it accepts
|
|
1432
|
+
* the command; this ordering only decides who gets asked first.
|
|
1433
|
+
*/
|
|
1434
|
+
scan(timeoutMs?: number): Promise<DiscoveredParent[]>;
|
|
1361
1435
|
connect(parentBleId: string): Promise<Session>;
|
|
1362
1436
|
requestNonce(session: Session): Promise<string>;
|
|
1363
1437
|
sendCommand(session: Session, token: string): Promise<CommandAck>;
|
|
@@ -1434,6 +1508,48 @@ declare function isRetryableRejectReason(reason: string): boolean;
|
|
|
1434
1508
|
/** Parse one already-decoded (plain-text) notify line. */
|
|
1435
1509
|
declare function parseNotifyLine(line: string): NotifyLine;
|
|
1436
1510
|
|
|
1511
|
+
/**
|
|
1512
|
+
* Reading a Parent's chassis serial off its advertisement (2026-10-05).
|
|
1513
|
+
*
|
|
1514
|
+
* A Parent publishes the serial stamped on its tower's chassis plate in its
|
|
1515
|
+
* scan response, as manufacturer-specific data: company id `0xFFFF`, one format
|
|
1516
|
+
* version byte, then the serial as ASCII. Firmware lays those bytes out in
|
|
1517
|
+
* `shared/src/SerialAdv.h`.
|
|
1518
|
+
*
|
|
1519
|
+
* WHAT THIS BUYS. Without it, resolving which Parent a grant belongs to means
|
|
1520
|
+
* connecting to candidates in turn and letting the HMAC refuse the wrong ones.
|
|
1521
|
+
* That works, and it is slow: a connect, a nonce, a mint and a write per
|
|
1522
|
+
* attempt, with somebody standing at a tower. A serial read from the scan tells
|
|
1523
|
+
* the SDK which candidate to try FIRST, usually making it the only one.
|
|
1524
|
+
*
|
|
1525
|
+
* A MATCH IS A HINT AND NOTHING MORE. `0xFFFF` is the identifier the Bluetooth
|
|
1526
|
+
* assigned-numbers list reserves for use without a company id, so any device may
|
|
1527
|
+
* emit it with any payload: a serial read here is unauthenticated and trivially
|
|
1528
|
+
* spoofable. It only ever reorders candidates. The tag on the command still
|
|
1529
|
+
* decides, exactly as it did before, so the cost of a lie is one wasted
|
|
1530
|
+
* connection and never an open.
|
|
1531
|
+
*/
|
|
1532
|
+
/**
|
|
1533
|
+
* The serial in one manufacturer-data field, or null if there isn't one.
|
|
1534
|
+
*
|
|
1535
|
+
* `value` is what `react-native-ble-plx` puts on `device.manufacturerData`:
|
|
1536
|
+
* base64 of the AD field's value, company id included, header excluded.
|
|
1537
|
+
*
|
|
1538
|
+
* Every rejection path returns null rather than throwing. This runs once per
|
|
1539
|
+
* device per scan, over bytes from strangers, and a neighbouring smart lightbulb
|
|
1540
|
+
* emitting `0xFFFF` garbage must cost nothing but a null.
|
|
1541
|
+
*/
|
|
1542
|
+
declare function parseAdvertisedSerial(value: string | null | undefined): string | null;
|
|
1543
|
+
/**
|
|
1544
|
+
* Do these name the same tower?
|
|
1545
|
+
*
|
|
1546
|
+
* Case-folded, because a Parent only ever stores an upper-cased serial
|
|
1547
|
+
* (firmware upper-cases every command before dispatch) while the platform keeps
|
|
1548
|
+
* the case an admin typed. Comparing them literally would miss every serial
|
|
1549
|
+
* entered in lower case, which is the common one.
|
|
1550
|
+
*/
|
|
1551
|
+
declare function serialMatches(advertised: string | null | undefined, granted: string | null | undefined): boolean;
|
|
1552
|
+
|
|
1437
1553
|
/**
|
|
1438
1554
|
* Webhook verification for partner BACKENDS (Node 18+ / edge: WebCrypto).
|
|
1439
1555
|
* Pinned platform scheme (2026-07-23, Stripe-style):
|
|
@@ -1596,4 +1712,4 @@ declare class RelaiTransportError extends RelaiError {
|
|
|
1596
1712
|
constructor(message: string);
|
|
1597
1713
|
}
|
|
1598
1714
|
|
|
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 };
|
|
1715
|
+
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;
|
|
@@ -920,6 +930,60 @@ declare class TelemetryUploader {
|
|
|
920
930
|
}>;
|
|
921
931
|
}
|
|
922
932
|
|
|
933
|
+
/**
|
|
934
|
+
* Persistent telemetry queue (owner, 2026-07-24). `MemoryTelemetryQueue` loses
|
|
935
|
+
* anything queued when the app is killed; a React Native app that opens nodes
|
|
936
|
+
* offline needs its unreported opens to survive a restart. This backs the same
|
|
937
|
+
* `TelemetryQueue` interface with a key-value store.
|
|
938
|
+
*
|
|
939
|
+
* The store is AsyncStorage-shaped on purpose, so RN apps pass the library in
|
|
940
|
+
* directly (it is an OPTIONAL dependency: the SDK core never imports it):
|
|
941
|
+
*
|
|
942
|
+
* import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
943
|
+
* const client = new RelaiClient({
|
|
944
|
+
* publishableKey,
|
|
945
|
+
* telemetryQueue: new StorageTelemetryQueue(AsyncStorage),
|
|
946
|
+
* });
|
|
947
|
+
*
|
|
948
|
+
* The whole queue is one JSON blob under a single key: telemetry volume is one
|
|
949
|
+
* item per open, so this stays small; writes are serialized through an internal
|
|
950
|
+
* lock so concurrent submit/flush calls can't clobber each other.
|
|
951
|
+
*/
|
|
952
|
+
|
|
953
|
+
/** The subset of AsyncStorage (and localStorage-async wrappers) we need. */
|
|
954
|
+
interface KeyValueStorage {
|
|
955
|
+
getItem(key: string): Promise<string | null>;
|
|
956
|
+
setItem(key: string, value: string): Promise<void>;
|
|
957
|
+
removeItem(key: string): Promise<void>;
|
|
958
|
+
}
|
|
959
|
+
interface StorageTelemetryQueueOptions {
|
|
960
|
+
/** Storage key for the serialized queue. Default `@relai/telemetry-queue`. */
|
|
961
|
+
storageKey?: string;
|
|
962
|
+
/**
|
|
963
|
+
* Hard cap on queued items; when exceeded the OLDEST are dropped so a long
|
|
964
|
+
* outage can't grow storage without bound. Default 500.
|
|
965
|
+
*/
|
|
966
|
+
maxItems?: number;
|
|
967
|
+
}
|
|
968
|
+
declare class StorageTelemetryQueue implements TelemetryQueue {
|
|
969
|
+
private readonly storage;
|
|
970
|
+
private readonly key;
|
|
971
|
+
private readonly maxItems;
|
|
972
|
+
/** Serializes read-modify-write so concurrent calls don't lose updates. */
|
|
973
|
+
private chain;
|
|
974
|
+
private seq;
|
|
975
|
+
constructor(storage: KeyValueStorage, opts?: StorageTelemetryQueueOptions);
|
|
976
|
+
enqueue(payload: TelemetryPayload): Promise<void>;
|
|
977
|
+
list(): Promise<QueuedTelemetry[]>;
|
|
978
|
+
remove(id: string): Promise<void>;
|
|
979
|
+
markAttempt(id: string): Promise<void>;
|
|
980
|
+
private nextId;
|
|
981
|
+
/** Serialize an operation after any in-flight ones (a simple promise lock). */
|
|
982
|
+
private run;
|
|
983
|
+
private mutate;
|
|
984
|
+
private read;
|
|
985
|
+
}
|
|
986
|
+
|
|
923
987
|
/**
|
|
924
988
|
* The outcome of writing one authenticated command to a Parent, distilled from
|
|
925
989
|
* the notify surface. `accepted` is the ONLY control-flow signal; `verbHint` is
|
|
@@ -953,6 +1017,12 @@ interface DiscoveredParent {
|
|
|
953
1017
|
parentBleId: string;
|
|
954
1018
|
/** The tower this Parent controls, when known from discovery context. */
|
|
955
1019
|
towerId?: string;
|
|
1020
|
+
/**
|
|
1021
|
+
* The chassis serial read off this Parent's advertisement, when it published
|
|
1022
|
+
* one. UNAUTHENTICATED: it decides which Parent to try first and nothing
|
|
1023
|
+
* else. See `parseAdvertisedSerial`.
|
|
1024
|
+
*/
|
|
1025
|
+
serial?: string;
|
|
956
1026
|
rssi?: number;
|
|
957
1027
|
isSimulated: boolean;
|
|
958
1028
|
}
|
|
@@ -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
|
|
@@ -1123,6 +1201,22 @@ interface RelaiClientOptions {
|
|
|
1123
1201
|
maxRetries?: number;
|
|
1124
1202
|
/** Persistent telemetry queue (default: in-memory). RN apps can back it with storage. */
|
|
1125
1203
|
telemetryQueue?: TelemetryQueue;
|
|
1204
|
+
/**
|
|
1205
|
+
* Where to remember which local handle turned out to be which Parent.
|
|
1206
|
+
*
|
|
1207
|
+
* Pass the same `KeyValueStorage` the telemetry queue uses, typically
|
|
1208
|
+
* AsyncStorage, and an open that resolved a Parent connects straight to it
|
|
1209
|
+
* next time instead of scanning. Omit it and every open rescans, which costs
|
|
1210
|
+
* a few seconds and nothing else.
|
|
1211
|
+
*
|
|
1212
|
+
* HERE rather than only on each `unlock()` call, because the mapping is
|
|
1213
|
+
* per-install device state like `tokenStorage` and `telemetryQueue`: an app
|
|
1214
|
+
* wires its store once. `UnlockInput.handleStorage` overrides it per call.
|
|
1215
|
+
*
|
|
1216
|
+
* The mapping is per device, because the identifier is: the handle this phone
|
|
1217
|
+
* connects by is not the handle another phone gets for the same Parent.
|
|
1218
|
+
*/
|
|
1219
|
+
handleStorage?: KeyValueStorage;
|
|
1126
1220
|
/**
|
|
1127
1221
|
* The `@stripe/stripe-react-native` module, for Relai checkout. Pass it and
|
|
1128
1222
|
* payment-gated opens present the standard Payment Sheet and retry
|
|
@@ -1173,6 +1267,15 @@ interface UnlockInput {
|
|
|
1173
1267
|
/** Admin/partner override link code: bypasses handoff + paywall gates. */
|
|
1174
1268
|
overrideCode?: string;
|
|
1175
1269
|
keepConnected?: boolean;
|
|
1270
|
+
/**
|
|
1271
|
+
* Override the client's `handleStorage` for this open.
|
|
1272
|
+
*
|
|
1273
|
+
* Normally omitted: set it once on the client. This exists because
|
|
1274
|
+
* `deliverOpen` has always accepted it and `unlock()` dropped it silently, so
|
|
1275
|
+
* a Relai-checkout app could not reach the cache at all without
|
|
1276
|
+
* reimplementing the payment handling (partner report, 2026-10-05).
|
|
1277
|
+
*/
|
|
1278
|
+
handleStorage?: KeyValueStorage;
|
|
1176
1279
|
}
|
|
1177
1280
|
declare class RelaiClient {
|
|
1178
1281
|
readonly auth: AuthModule;
|
|
@@ -1197,6 +1300,8 @@ declare class RelaiClient {
|
|
|
1197
1300
|
private readonly http;
|
|
1198
1301
|
/** The app-supplied Stripe module, if any. See `RelaiClientOptions.stripe`. */
|
|
1199
1302
|
private readonly stripe;
|
|
1303
|
+
/** Where resolved Parent handles are remembered. See `RelaiClientOptions.handleStorage`. */
|
|
1304
|
+
private readonly handleStorage;
|
|
1200
1305
|
constructor(options: RelaiClientOptions);
|
|
1201
1306
|
/** Drain any telemetry queued after a failed send (e.g. on app foreground). */
|
|
1202
1307
|
flushTelemetry(): Promise<{
|
|
@@ -1223,60 +1328,6 @@ declare class RelaiClient {
|
|
|
1223
1328
|
unlock(input: UnlockInput): Promise<UnlockResult>;
|
|
1224
1329
|
}
|
|
1225
1330
|
|
|
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
1331
|
/**
|
|
1281
1332
|
* SimulatedTransport: lets an app exercise the full open flow with no hardware.
|
|
1282
1333
|
* It emulates the Parent's notify surface: issues a random nonce on CHALLENGE,
|
|
@@ -1344,6 +1395,16 @@ interface BleDeviceLike {
|
|
|
1344
1395
|
interface BleManagerLike {
|
|
1345
1396
|
connectToDevice(id: string, options?: unknown): Promise<BleDeviceLike>;
|
|
1346
1397
|
discoverAllServicesAndCharacteristicsForDevice?(id: string): Promise<BleDeviceLike>;
|
|
1398
|
+
/**
|
|
1399
|
+
* Discovery, where the platform provides it.
|
|
1400
|
+
*
|
|
1401
|
+
* OPTIONAL so every transport and test double written against the two methods
|
|
1402
|
+
* above keeps compiling. `react-native-ble-plx` has both of these; a manager
|
|
1403
|
+
* without them simply never scans, which is correct on a platform where the
|
|
1404
|
+
* grant's id is already a usable handle.
|
|
1405
|
+
*/
|
|
1406
|
+
startDeviceScan?(serviceUUIDs: string[] | null, options: unknown, listener: (error: unknown, device: BleDeviceLike | null) => void): void;
|
|
1407
|
+
stopDeviceScan?(): void;
|
|
1347
1408
|
}
|
|
1348
1409
|
interface BleTransportOptions {
|
|
1349
1410
|
manager: BleManagerLike;
|
|
@@ -1357,7 +1418,20 @@ declare class BleTransport implements ParentTransport {
|
|
|
1357
1418
|
private readonly scanImpl;
|
|
1358
1419
|
private readonly notifyTimeoutMs;
|
|
1359
1420
|
constructor(opts: BleTransportOptions);
|
|
1360
|
-
|
|
1421
|
+
/**
|
|
1422
|
+
* Relai Parents in range.
|
|
1423
|
+
*
|
|
1424
|
+
* An app-supplied `scan` still wins, because an app with its own discovery UI
|
|
1425
|
+
* has already solved this and may filter differently. Otherwise the manager's
|
|
1426
|
+
* own scanner is driven here, filtered to the Relai service so the list is
|
|
1427
|
+
* Parents rather than every radio in the building.
|
|
1428
|
+
*
|
|
1429
|
+
* Results are ordered by signal, strongest first. That is a weak hint and
|
|
1430
|
+
* treated as one: towers at an Exchange Zone stand side by side, so signal
|
|
1431
|
+
* barely separates them. What actually identifies a Parent is that it accepts
|
|
1432
|
+
* the command; this ordering only decides who gets asked first.
|
|
1433
|
+
*/
|
|
1434
|
+
scan(timeoutMs?: number): Promise<DiscoveredParent[]>;
|
|
1361
1435
|
connect(parentBleId: string): Promise<Session>;
|
|
1362
1436
|
requestNonce(session: Session): Promise<string>;
|
|
1363
1437
|
sendCommand(session: Session, token: string): Promise<CommandAck>;
|
|
@@ -1434,6 +1508,48 @@ declare function isRetryableRejectReason(reason: string): boolean;
|
|
|
1434
1508
|
/** Parse one already-decoded (plain-text) notify line. */
|
|
1435
1509
|
declare function parseNotifyLine(line: string): NotifyLine;
|
|
1436
1510
|
|
|
1511
|
+
/**
|
|
1512
|
+
* Reading a Parent's chassis serial off its advertisement (2026-10-05).
|
|
1513
|
+
*
|
|
1514
|
+
* A Parent publishes the serial stamped on its tower's chassis plate in its
|
|
1515
|
+
* scan response, as manufacturer-specific data: company id `0xFFFF`, one format
|
|
1516
|
+
* version byte, then the serial as ASCII. Firmware lays those bytes out in
|
|
1517
|
+
* `shared/src/SerialAdv.h`.
|
|
1518
|
+
*
|
|
1519
|
+
* WHAT THIS BUYS. Without it, resolving which Parent a grant belongs to means
|
|
1520
|
+
* connecting to candidates in turn and letting the HMAC refuse the wrong ones.
|
|
1521
|
+
* That works, and it is slow: a connect, a nonce, a mint and a write per
|
|
1522
|
+
* attempt, with somebody standing at a tower. A serial read from the scan tells
|
|
1523
|
+
* the SDK which candidate to try FIRST, usually making it the only one.
|
|
1524
|
+
*
|
|
1525
|
+
* A MATCH IS A HINT AND NOTHING MORE. `0xFFFF` is the identifier the Bluetooth
|
|
1526
|
+
* assigned-numbers list reserves for use without a company id, so any device may
|
|
1527
|
+
* emit it with any payload: a serial read here is unauthenticated and trivially
|
|
1528
|
+
* spoofable. It only ever reorders candidates. The tag on the command still
|
|
1529
|
+
* decides, exactly as it did before, so the cost of a lie is one wasted
|
|
1530
|
+
* connection and never an open.
|
|
1531
|
+
*/
|
|
1532
|
+
/**
|
|
1533
|
+
* The serial in one manufacturer-data field, or null if there isn't one.
|
|
1534
|
+
*
|
|
1535
|
+
* `value` is what `react-native-ble-plx` puts on `device.manufacturerData`:
|
|
1536
|
+
* base64 of the AD field's value, company id included, header excluded.
|
|
1537
|
+
*
|
|
1538
|
+
* Every rejection path returns null rather than throwing. This runs once per
|
|
1539
|
+
* device per scan, over bytes from strangers, and a neighbouring smart lightbulb
|
|
1540
|
+
* emitting `0xFFFF` garbage must cost nothing but a null.
|
|
1541
|
+
*/
|
|
1542
|
+
declare function parseAdvertisedSerial(value: string | null | undefined): string | null;
|
|
1543
|
+
/**
|
|
1544
|
+
* Do these name the same tower?
|
|
1545
|
+
*
|
|
1546
|
+
* Case-folded, because a Parent only ever stores an upper-cased serial
|
|
1547
|
+
* (firmware upper-cases every command before dispatch) while the platform keeps
|
|
1548
|
+
* the case an admin typed. Comparing them literally would miss every serial
|
|
1549
|
+
* entered in lower case, which is the common one.
|
|
1550
|
+
*/
|
|
1551
|
+
declare function serialMatches(advertised: string | null | undefined, granted: string | null | undefined): boolean;
|
|
1552
|
+
|
|
1437
1553
|
/**
|
|
1438
1554
|
* Webhook verification for partner BACKENDS (Node 18+ / edge: WebCrypto).
|
|
1439
1555
|
* Pinned platform scheme (2026-07-23, Stripe-style):
|
|
@@ -1596,4 +1712,4 @@ declare class RelaiTransportError extends RelaiError {
|
|
|
1596
1712
|
constructor(message: string);
|
|
1597
1713
|
}
|
|
1598
1714
|
|
|
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 };
|
|
1715
|
+
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
|
|
@@ -657,6 +762,7 @@ var RelaiClient = class {
|
|
|
657
762
|
constructor(options) {
|
|
658
763
|
if (!options.publishableKey && !options.secretKey) throw new RelaiMissingKeyError();
|
|
659
764
|
this.stripe = options.stripe;
|
|
765
|
+
this.handleStorage = options.handleStorage;
|
|
660
766
|
const storage = options.tokenStorage ?? new MemoryTokenStorage();
|
|
661
767
|
let auth;
|
|
662
768
|
const httpConfig = {
|
|
@@ -738,7 +844,12 @@ var RelaiClient = class {
|
|
|
738
844
|
transport: input.transport,
|
|
739
845
|
...input.parentBleId !== void 0 ? { parentBleId: input.parentBleId } : {},
|
|
740
846
|
...input.exchangeZoneId !== void 0 ? { exchangeZoneId: input.exchangeZoneId } : {},
|
|
741
|
-
...input.keepConnected !== void 0 ? { keepConnected: input.keepConnected } : {}
|
|
847
|
+
...input.keepConnected !== void 0 ? { keepConnected: input.keepConnected } : {},
|
|
848
|
+
// Per-call first, then the client's. Spread rather than assigned:
|
|
849
|
+
// exactOptionalPropertyTypes makes an explicit `undefined` a value, and
|
|
850
|
+
// `new ParentHandleCache(undefined)` is a cache that silently does
|
|
851
|
+
// nothing, which is precisely the bug being fixed.
|
|
852
|
+
...input.handleStorage ?? this.handleStorage ? { handleStorage: input.handleStorage ?? this.handleStorage } : {}
|
|
742
853
|
}
|
|
743
854
|
);
|
|
744
855
|
}
|
|
@@ -828,6 +939,21 @@ function base64ToUtf8(b64) {
|
|
|
828
939
|
if (g.atob) return decodeURIComponent(escape(g.atob(b64)));
|
|
829
940
|
throw new Error("No base64 decoder available in this runtime.");
|
|
830
941
|
}
|
|
942
|
+
function base64ToBytes(b64) {
|
|
943
|
+
const g = globalThis;
|
|
944
|
+
try {
|
|
945
|
+
if (g.Buffer) return new Uint8Array(g.Buffer.from(b64, "base64"));
|
|
946
|
+
if (g.atob) {
|
|
947
|
+
const binary = g.atob(b64);
|
|
948
|
+
const out = new Uint8Array(binary.length);
|
|
949
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
950
|
+
return out;
|
|
951
|
+
}
|
|
952
|
+
return null;
|
|
953
|
+
} catch {
|
|
954
|
+
return null;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
831
957
|
|
|
832
958
|
// src/transport/simulated.ts
|
|
833
959
|
function randomNonceB64Url() {
|
|
@@ -945,6 +1071,33 @@ var SimAuthenticatedTransport = class {
|
|
|
945
1071
|
}
|
|
946
1072
|
};
|
|
947
1073
|
|
|
1074
|
+
// src/parent-advertisement.ts
|
|
1075
|
+
var COMPANY_ID = 65535;
|
|
1076
|
+
var FORMAT_VERSION = 1;
|
|
1077
|
+
var HEADER_BYTES = 3;
|
|
1078
|
+
var SERIAL_MAX = 29 - HEADER_BYTES;
|
|
1079
|
+
function parseAdvertisedSerial(value) {
|
|
1080
|
+
if (!value) return null;
|
|
1081
|
+
const bytes = base64ToBytes(value);
|
|
1082
|
+
if (!bytes || bytes.length <= HEADER_BYTES) return null;
|
|
1083
|
+
const company = bytes[0] | bytes[1] << 8;
|
|
1084
|
+
if (company !== COMPANY_ID) return null;
|
|
1085
|
+
if (bytes[2] !== FORMAT_VERSION) return null;
|
|
1086
|
+
const body = bytes.subarray(HEADER_BYTES);
|
|
1087
|
+
if (body.length > SERIAL_MAX) return null;
|
|
1088
|
+
let serial = "";
|
|
1089
|
+
for (const byte of body) {
|
|
1090
|
+
const char = String.fromCharCode(byte);
|
|
1091
|
+
if (!/[A-Z0-9._:/-]/.test(char)) return null;
|
|
1092
|
+
serial += char;
|
|
1093
|
+
}
|
|
1094
|
+
return serial.length > 0 ? serial : null;
|
|
1095
|
+
}
|
|
1096
|
+
function serialMatches(advertised, granted) {
|
|
1097
|
+
if (!advertised || !granted) return false;
|
|
1098
|
+
return advertised.toUpperCase() === granted.toUpperCase();
|
|
1099
|
+
}
|
|
1100
|
+
|
|
948
1101
|
// src/transport/notify.ts
|
|
949
1102
|
var REJECT_REASONS = [
|
|
950
1103
|
"B64",
|
|
@@ -991,11 +1144,65 @@ var BleTransport = class {
|
|
|
991
1144
|
this.scanImpl = opts.scan;
|
|
992
1145
|
this.notifyTimeoutMs = opts.notifyTimeoutMs ?? NOTIFY_TIMEOUT_MS;
|
|
993
1146
|
}
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
1147
|
+
/**
|
|
1148
|
+
* Relai Parents in range.
|
|
1149
|
+
*
|
|
1150
|
+
* An app-supplied `scan` still wins, because an app with its own discovery UI
|
|
1151
|
+
* has already solved this and may filter differently. Otherwise the manager's
|
|
1152
|
+
* own scanner is driven here, filtered to the Relai service so the list is
|
|
1153
|
+
* Parents rather than every radio in the building.
|
|
1154
|
+
*
|
|
1155
|
+
* Results are ordered by signal, strongest first. That is a weak hint and
|
|
1156
|
+
* treated as one: towers at an Exchange Zone stand side by side, so signal
|
|
1157
|
+
* barely separates them. What actually identifies a Parent is that it accepts
|
|
1158
|
+
* the command; this ordering only decides who gets asked first.
|
|
1159
|
+
*/
|
|
1160
|
+
scan(timeoutMs = 4e3) {
|
|
1161
|
+
if (this.scanImpl) return this.scanImpl();
|
|
1162
|
+
const manager = this.manager;
|
|
1163
|
+
if (!manager.startDeviceScan || !manager.stopDeviceScan) {
|
|
1164
|
+
return Promise.reject(
|
|
1165
|
+
new RelaiTransportError("No scan() provided to BleTransport; drive discovery from your app.")
|
|
1166
|
+
);
|
|
997
1167
|
}
|
|
998
|
-
return
|
|
1168
|
+
return new Promise((resolve) => {
|
|
1169
|
+
const found = /* @__PURE__ */ new Map();
|
|
1170
|
+
let settled = false;
|
|
1171
|
+
const finish = () => {
|
|
1172
|
+
if (settled) return;
|
|
1173
|
+
settled = true;
|
|
1174
|
+
try {
|
|
1175
|
+
manager.stopDeviceScan();
|
|
1176
|
+
} catch {
|
|
1177
|
+
}
|
|
1178
|
+
resolve([...found.values()].sort((a, b) => (b.rssi ?? -999) - (a.rssi ?? -999)));
|
|
1179
|
+
};
|
|
1180
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
1181
|
+
try {
|
|
1182
|
+
manager.startDeviceScan([RELAI_UART_SERVICE], null, (error, device) => {
|
|
1183
|
+
if (error) {
|
|
1184
|
+
clearTimeout(timer);
|
|
1185
|
+
finish();
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
if (!device?.id || found.has(device.id)) return;
|
|
1189
|
+
const fields = device;
|
|
1190
|
+
const rssi = fields.rssi;
|
|
1191
|
+
const serial = parseAdvertisedSerial(fields.manufacturerData);
|
|
1192
|
+
found.set(device.id, {
|
|
1193
|
+
parentBleId: device.id,
|
|
1194
|
+
isSimulated: false,
|
|
1195
|
+
// Spread rather than assigned: exactOptionalPropertyTypes means an
|
|
1196
|
+
// explicit `undefined` is not the same as an absent field.
|
|
1197
|
+
...typeof rssi === "number" ? { rssi } : {},
|
|
1198
|
+
...serial ? { serial } : {}
|
|
1199
|
+
});
|
|
1200
|
+
});
|
|
1201
|
+
} catch {
|
|
1202
|
+
clearTimeout(timer);
|
|
1203
|
+
finish();
|
|
1204
|
+
}
|
|
1205
|
+
});
|
|
999
1206
|
}
|
|
1000
1207
|
async connect(parentBleId) {
|
|
1001
1208
|
let device = await this.manager.connectToDevice(parentBleId);
|
|
@@ -1123,4 +1330,4 @@ var Intents = {
|
|
|
1123
1330
|
MakeAvailable: "make_available"
|
|
1124
1331
|
};
|
|
1125
1332
|
|
|
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 };
|
|
1333
|
+
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.20.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",
|