@relai-team/access-sdk 0.20.1 → 0.20.3
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 +148 -99
- package/dist/index.d.cts +53 -10
- package/dist/index.d.ts +53 -10
- package/dist/index.js +148 -100
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -755,6 +755,42 @@ init_errors();
|
|
|
755
755
|
// src/unlock.ts
|
|
756
756
|
init_errors();
|
|
757
757
|
|
|
758
|
+
// src/transport/notify.ts
|
|
759
|
+
var REJECT_REASONS = [
|
|
760
|
+
"B64",
|
|
761
|
+
"UNTAGGED",
|
|
762
|
+
"FORMAT",
|
|
763
|
+
"KEYVERSION",
|
|
764
|
+
"TAG",
|
|
765
|
+
"NONCE",
|
|
766
|
+
"LOCKED",
|
|
767
|
+
"ROTATE",
|
|
768
|
+
"NOTREADY"
|
|
769
|
+
];
|
|
770
|
+
function isRetryableRejectReason(reason) {
|
|
771
|
+
return reason === "NOTREADY";
|
|
772
|
+
}
|
|
773
|
+
function needsFreshNonce(reason) {
|
|
774
|
+
return reason === "NONCE";
|
|
775
|
+
}
|
|
776
|
+
function parseNotifyLine(line) {
|
|
777
|
+
const trimmed = line.trim();
|
|
778
|
+
if (trimmed.startsWith("NONCE ")) {
|
|
779
|
+
const nonce = trimmed.slice("NONCE ".length).trim();
|
|
780
|
+
return { kind: "nonce", nonceB64Url: nonce };
|
|
781
|
+
}
|
|
782
|
+
if (trimmed.startsWith("[AUTH] ACCEPT ")) {
|
|
783
|
+
return { kind: "accept", command: trimmed.slice("[AUTH] ACCEPT ".length).trim() };
|
|
784
|
+
}
|
|
785
|
+
if (trimmed.startsWith("[AUTH] REJECT ")) {
|
|
786
|
+
const rest = trimmed.slice("[AUTH] REJECT ".length).trim();
|
|
787
|
+
const [reason, ...verbParts] = rest.split(/\s+/);
|
|
788
|
+
const verbHint = verbParts.length > 0 ? verbParts.join(" ") : void 0;
|
|
789
|
+
return { kind: "reject", reason: reason ?? "", verbHint };
|
|
790
|
+
}
|
|
791
|
+
return { kind: "passthrough", raw: trimmed };
|
|
792
|
+
}
|
|
793
|
+
|
|
758
794
|
// src/parent-resolve.ts
|
|
759
795
|
var WRONG_PARENT = "TAG";
|
|
760
796
|
function isWrongParentReject(reason) {
|
|
@@ -811,6 +847,7 @@ function orderCandidates(input) {
|
|
|
811
847
|
var MAX_PARENT_ATTEMPTS = 6;
|
|
812
848
|
|
|
813
849
|
// src/unlock.ts
|
|
850
|
+
var MAX_NONCE_RETRIES = 1;
|
|
814
851
|
async function deliverOpen(deps, open, opts) {
|
|
815
852
|
const { transport } = opts;
|
|
816
853
|
const grant = open.grant;
|
|
@@ -826,20 +863,30 @@ async function deliverOpen(deps, open, opts) {
|
|
|
826
863
|
const session = await transport.connect(handle);
|
|
827
864
|
let keep = false;
|
|
828
865
|
try {
|
|
829
|
-
|
|
866
|
+
const authenticated = grant.algorithm === "relai-hmac-sha256-16-v1";
|
|
830
867
|
let keyVersion;
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
token =
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
868
|
+
let ack;
|
|
869
|
+
let staleNonces = 0;
|
|
870
|
+
for (; ; ) {
|
|
871
|
+
let token = grant.token;
|
|
872
|
+
if (authenticated) {
|
|
873
|
+
const nonce = await transport.requestNonce(session);
|
|
874
|
+
const minted = await deps.grants.mint(grant.grant_id, nonce);
|
|
875
|
+
token = minted.token;
|
|
876
|
+
keyVersion = minted.key_version;
|
|
877
|
+
}
|
|
878
|
+
if (!token) {
|
|
879
|
+
throw new exports.RelaiError(
|
|
880
|
+
`Grant ${grant.grant_id} has no token to deliver (algorithm ${grant.algorithm}).`
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
ack = await transport.sendCommand(session, token);
|
|
884
|
+
if (!ack.accepted && authenticated && needsFreshNonce(ack.rejectReason ?? "") && staleNonces < MAX_NONCE_RETRIES) {
|
|
885
|
+
staleNonces += 1;
|
|
886
|
+
continue;
|
|
887
|
+
}
|
|
888
|
+
break;
|
|
841
889
|
}
|
|
842
|
-
const ack = await transport.sendCommand(session, token);
|
|
843
890
|
if (!ack.accepted && isWrongParentReject(ack.rejectReason ?? "")) {
|
|
844
891
|
return null;
|
|
845
892
|
}
|
|
@@ -874,10 +921,13 @@ async function deliverOpen(deps, open, opts) {
|
|
|
874
921
|
}).catch(() => void 0);
|
|
875
922
|
}
|
|
876
923
|
let candidates = orderCandidates({ cached: await cache.get(parentBleId), parentBleId });
|
|
924
|
+
const tried = /* @__PURE__ */ new Set();
|
|
877
925
|
let scanned = false;
|
|
926
|
+
let attempts = 0;
|
|
878
927
|
let lastConnectError;
|
|
879
|
-
|
|
880
|
-
|
|
928
|
+
while (attempts < MAX_PARENT_ATTEMPTS) {
|
|
929
|
+
let handle = candidates.find((h) => !tried.has(h));
|
|
930
|
+
if (!handle) {
|
|
881
931
|
if (scanned) break;
|
|
882
932
|
scanned = true;
|
|
883
933
|
const found = await transport.scan().catch(() => []);
|
|
@@ -892,9 +942,11 @@ async function deliverOpen(deps, open, opts) {
|
|
|
892
942
|
parentSerial: open.grant.parent_serial
|
|
893
943
|
});
|
|
894
944
|
await cache.forget(parentBleId);
|
|
895
|
-
|
|
945
|
+
handle = candidates.find((h) => !tried.has(h));
|
|
946
|
+
if (!handle) break;
|
|
896
947
|
}
|
|
897
|
-
|
|
948
|
+
tried.add(handle);
|
|
949
|
+
attempts += 1;
|
|
898
950
|
try {
|
|
899
951
|
const result = await attempt(handle);
|
|
900
952
|
if (result) return result;
|
|
@@ -1268,45 +1320,13 @@ function serialMatches(advertised, granted) {
|
|
|
1268
1320
|
return advertised.toUpperCase() === granted.toUpperCase();
|
|
1269
1321
|
}
|
|
1270
1322
|
|
|
1271
|
-
// src/transport/notify.ts
|
|
1272
|
-
var REJECT_REASONS = [
|
|
1273
|
-
"B64",
|
|
1274
|
-
"UNTAGGED",
|
|
1275
|
-
"FORMAT",
|
|
1276
|
-
"KEYVERSION",
|
|
1277
|
-
"TAG",
|
|
1278
|
-
"NONCE",
|
|
1279
|
-
"LOCKED",
|
|
1280
|
-
"ROTATE",
|
|
1281
|
-
"NOTREADY"
|
|
1282
|
-
];
|
|
1283
|
-
function isRetryableRejectReason(reason) {
|
|
1284
|
-
return reason === "NOTREADY";
|
|
1285
|
-
}
|
|
1286
|
-
function parseNotifyLine(line) {
|
|
1287
|
-
const trimmed = line.trim();
|
|
1288
|
-
if (trimmed.startsWith("NONCE ")) {
|
|
1289
|
-
const nonce = trimmed.slice("NONCE ".length).trim();
|
|
1290
|
-
return { kind: "nonce", nonceB64Url: nonce };
|
|
1291
|
-
}
|
|
1292
|
-
if (trimmed.startsWith("[AUTH] ACCEPT ")) {
|
|
1293
|
-
return { kind: "accept", command: trimmed.slice("[AUTH] ACCEPT ".length).trim() };
|
|
1294
|
-
}
|
|
1295
|
-
if (trimmed.startsWith("[AUTH] REJECT ")) {
|
|
1296
|
-
const rest = trimmed.slice("[AUTH] REJECT ".length).trim();
|
|
1297
|
-
const [reason, ...verbParts] = rest.split(/\s+/);
|
|
1298
|
-
const verbHint = verbParts.length > 0 ? verbParts.join(" ") : void 0;
|
|
1299
|
-
return { kind: "reject", reason: reason ?? "", verbHint };
|
|
1300
|
-
}
|
|
1301
|
-
return { kind: "passthrough", raw: trimmed };
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
1323
|
// src/transport/ble.ts
|
|
1305
1324
|
var RELAI_UART_SERVICE = "0000ff00-0000-1000-8000-00805f9b34fb";
|
|
1306
1325
|
var RELAI_RX_CHAR = "0000ff02-0000-1000-8000-00805f9b34fb";
|
|
1307
1326
|
var RELAI_TX_CHAR = "0000ff03-0000-1000-8000-00805f9b34fb";
|
|
1308
1327
|
var MIN_MTU = 110;
|
|
1309
1328
|
var NOTIFY_TIMEOUT_MS = 8e3;
|
|
1329
|
+
var CONNECT_TIMEOUT_MS = 1e4;
|
|
1310
1330
|
var BleTransport = class {
|
|
1311
1331
|
constructor(opts) {
|
|
1312
1332
|
this.devices = /* @__PURE__ */ new Map();
|
|
@@ -1314,6 +1334,7 @@ var BleTransport = class {
|
|
|
1314
1334
|
this.manager = opts.manager;
|
|
1315
1335
|
this.scanImpl = opts.scan;
|
|
1316
1336
|
this.notifyTimeoutMs = opts.notifyTimeoutMs ?? NOTIFY_TIMEOUT_MS;
|
|
1337
|
+
this.connectTimeoutMs = opts.connectTimeoutMs ?? CONNECT_TIMEOUT_MS;
|
|
1317
1338
|
}
|
|
1318
1339
|
/**
|
|
1319
1340
|
* Relai Parents in range.
|
|
@@ -1375,53 +1396,78 @@ var BleTransport = class {
|
|
|
1375
1396
|
}
|
|
1376
1397
|
});
|
|
1377
1398
|
}
|
|
1399
|
+
/**
|
|
1400
|
+
* Connect, discover, and start listening, or leave nothing behind.
|
|
1401
|
+
*
|
|
1402
|
+
* Every step after `connectToDevice` can fail, and a failure here returns no
|
|
1403
|
+
* Session, so NOBODY WILL EVER CALL `disconnect` for this device: the caller
|
|
1404
|
+
* has nothing to pass it. Anything this method set up has to be undone on the
|
|
1405
|
+
* way out or the connection is held until the app restarts. On iOS that is
|
|
1406
|
+
* not merely untidy: `deliverOpen` walks several candidates, and each failed
|
|
1407
|
+
* one would leave a live CoreBluetooth connection behind it.
|
|
1408
|
+
*/
|
|
1378
1409
|
async connect(parentBleId) {
|
|
1379
|
-
let device = await this.manager.connectToDevice(parentBleId);
|
|
1380
|
-
if (this.manager.discoverAllServicesAndCharacteristicsForDevice) {
|
|
1381
|
-
device = await this.manager.discoverAllServicesAndCharacteristicsForDevice(device.id);
|
|
1382
|
-
}
|
|
1410
|
+
let device = await this.manager.connectToDevice(parentBleId, { timeout: this.connectTimeoutMs });
|
|
1383
1411
|
try {
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
remove: () => void 0
|
|
1394
|
-
};
|
|
1395
|
-
const sub = device.monitorCharacteristicForService(
|
|
1396
|
-
RELAI_UART_SERVICE,
|
|
1397
|
-
RELAI_TX_CHAR,
|
|
1398
|
-
(error, ch) => {
|
|
1399
|
-
if (error) {
|
|
1400
|
-
const err = new exports.RelaiTransportError(`BLE notify error: ${String(error)}`);
|
|
1401
|
-
state.error = err;
|
|
1402
|
-
state.failed?.(err);
|
|
1403
|
-
return;
|
|
1404
|
-
}
|
|
1405
|
-
const value = ch?.value;
|
|
1406
|
-
if (!value) return;
|
|
1407
|
-
let text;
|
|
1412
|
+
if (this.manager.discoverAllServicesAndCharacteristicsForDevice) {
|
|
1413
|
+
device = await this.manager.discoverAllServicesAndCharacteristicsForDevice(device.id);
|
|
1414
|
+
}
|
|
1415
|
+
try {
|
|
1416
|
+
device = await device.requestMTU(MIN_MTU);
|
|
1417
|
+
} catch {
|
|
1418
|
+
}
|
|
1419
|
+
const previous = this.notify.get(device.id);
|
|
1420
|
+
if (previous) {
|
|
1408
1421
|
try {
|
|
1409
|
-
|
|
1422
|
+
previous.remove();
|
|
1410
1423
|
} catch {
|
|
1411
|
-
return;
|
|
1412
|
-
}
|
|
1413
|
-
if (state.waiter && state.accept?.(parseNotifyLine(text))) {
|
|
1414
|
-
const resolve = state.waiter;
|
|
1415
|
-
state.waiter = void 0;
|
|
1416
|
-
state.accept = void 0;
|
|
1417
|
-
state.failed = void 0;
|
|
1418
|
-
resolve(text);
|
|
1419
1424
|
}
|
|
1425
|
+
this.notify.delete(device.id);
|
|
1420
1426
|
}
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1427
|
+
this.devices.set(device.id, device);
|
|
1428
|
+
const state = {
|
|
1429
|
+
waiter: void 0,
|
|
1430
|
+
accept: void 0,
|
|
1431
|
+
failed: void 0,
|
|
1432
|
+
error: void 0,
|
|
1433
|
+
remove: () => void 0
|
|
1434
|
+
};
|
|
1435
|
+
const sub = device.monitorCharacteristicForService(
|
|
1436
|
+
RELAI_UART_SERVICE,
|
|
1437
|
+
RELAI_TX_CHAR,
|
|
1438
|
+
(error, ch) => {
|
|
1439
|
+
if (error) {
|
|
1440
|
+
const err = new exports.RelaiTransportError(`BLE notify error: ${String(error)}`);
|
|
1441
|
+
state.error = err;
|
|
1442
|
+
state.failed?.(err);
|
|
1443
|
+
return;
|
|
1444
|
+
}
|
|
1445
|
+
const value = ch?.value;
|
|
1446
|
+
if (!value) return;
|
|
1447
|
+
let text;
|
|
1448
|
+
try {
|
|
1449
|
+
text = base64ToUtf8(value);
|
|
1450
|
+
} catch {
|
|
1451
|
+
return;
|
|
1452
|
+
}
|
|
1453
|
+
if (state.waiter && state.accept?.(parseNotifyLine(text))) {
|
|
1454
|
+
const resolve = state.waiter;
|
|
1455
|
+
state.waiter = void 0;
|
|
1456
|
+
state.accept = void 0;
|
|
1457
|
+
state.failed = void 0;
|
|
1458
|
+
resolve(text);
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
);
|
|
1462
|
+
state.remove = () => sub.remove();
|
|
1463
|
+
this.notify.set(device.id, state);
|
|
1464
|
+
return { id: device.id, parentBleId, connectedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
1465
|
+
} catch (err) {
|
|
1466
|
+
this.notify.delete(device.id);
|
|
1467
|
+
this.devices.delete(device.id);
|
|
1468
|
+
await device.cancelConnection().catch(() => void 0);
|
|
1469
|
+
throw err;
|
|
1470
|
+
}
|
|
1425
1471
|
}
|
|
1426
1472
|
async requestNonce(session) {
|
|
1427
1473
|
const line = await this.writeAndAwait(session, utf8ToBase64("CHALLENGE"));
|
|
@@ -1463,17 +1509,19 @@ var BleTransport = class {
|
|
|
1463
1509
|
/**
|
|
1464
1510
|
* Write one value and await the first notify line that matches `accept`.
|
|
1465
1511
|
*
|
|
1466
|
-
*
|
|
1512
|
+
* REGISTER, WRITE, WAIT, in that order, on the session's single subscription.
|
|
1467
1513
|
*
|
|
1468
|
-
*
|
|
1469
|
-
*
|
|
1470
|
-
*
|
|
1471
|
-
*
|
|
1514
|
+
* The waiter is registered SYNCHRONOUSLY, before the write is issued, so
|
|
1515
|
+
* there is no window in which a reply could arrive unwatched: the notify
|
|
1516
|
+
* callback cannot run before this function returns to the event loop. That is
|
|
1517
|
+
* why there is no buffer of unclaimed lines (see `NotifyState`), and why a
|
|
1518
|
+
* line that arrives with no waiter is dropped rather than kept: the Parent
|
|
1519
|
+
* speaks only in answer to a write, so an unclaimed line is stale, and a
|
|
1520
|
+
* stale `NONCE` carried forward would be minted against and then refused by
|
|
1521
|
+
* the Parent as a replay.
|
|
1472
1522
|
*
|
|
1473
|
-
*
|
|
1474
|
-
*
|
|
1475
|
-
* between the nonce leg and the command leg is covered: there is no moment in
|
|
1476
|
-
* the session when nobody is listening.
|
|
1523
|
+
* The subscription itself is opened in `connect` and held for the session, so
|
|
1524
|
+
* the gap between the nonce leg and the command leg is covered too.
|
|
1477
1525
|
*/
|
|
1478
1526
|
writeAndAwait(session, valueBase64, accept = (p) => p.kind !== "passthrough") {
|
|
1479
1527
|
const device = this.devices.get(session.id);
|
|
@@ -1579,6 +1627,7 @@ exports.asPaymentRequired = asPaymentRequired;
|
|
|
1579
1627
|
exports.deliverOpen = deliverOpen;
|
|
1580
1628
|
exports.isRetryableRejectReason = isRetryableRejectReason;
|
|
1581
1629
|
exports.isStripePublishableKey = isStripePublishableKey;
|
|
1630
|
+
exports.needsFreshNonce = needsFreshNonce;
|
|
1582
1631
|
exports.parseAdvertisedSerial = parseAdvertisedSerial;
|
|
1583
1632
|
exports.parseNotifyLine = parseNotifyLine;
|
|
1584
1633
|
exports.presentRelaiPaymentSheet = presentRelaiPaymentSheet;
|
package/dist/index.d.cts
CHANGED
|
@@ -1411,6 +1411,8 @@ interface BleTransportOptions {
|
|
|
1411
1411
|
/** Discovery is app-specific (scan is often driven by your own UI); optional. */
|
|
1412
1412
|
scan?: () => Promise<DiscoveredParent[]>;
|
|
1413
1413
|
notifyTimeoutMs?: number;
|
|
1414
|
+
/** Per-candidate connection timeout; see CONNECT_TIMEOUT_MS. */
|
|
1415
|
+
connectTimeoutMs?: number;
|
|
1414
1416
|
}
|
|
1415
1417
|
declare class BleTransport implements ParentTransport {
|
|
1416
1418
|
private readonly manager;
|
|
@@ -1418,6 +1420,7 @@ declare class BleTransport implements ParentTransport {
|
|
|
1418
1420
|
private readonly notify;
|
|
1419
1421
|
private readonly scanImpl;
|
|
1420
1422
|
private readonly notifyTimeoutMs;
|
|
1423
|
+
private readonly connectTimeoutMs;
|
|
1421
1424
|
constructor(opts: BleTransportOptions);
|
|
1422
1425
|
/**
|
|
1423
1426
|
* Relai Parents in range.
|
|
@@ -1433,6 +1436,16 @@ declare class BleTransport implements ParentTransport {
|
|
|
1433
1436
|
* the command; this ordering only decides who gets asked first.
|
|
1434
1437
|
*/
|
|
1435
1438
|
scan(timeoutMs?: number): Promise<DiscoveredParent[]>;
|
|
1439
|
+
/**
|
|
1440
|
+
* Connect, discover, and start listening, or leave nothing behind.
|
|
1441
|
+
*
|
|
1442
|
+
* Every step after `connectToDevice` can fail, and a failure here returns no
|
|
1443
|
+
* Session, so NOBODY WILL EVER CALL `disconnect` for this device: the caller
|
|
1444
|
+
* has nothing to pass it. Anything this method set up has to be undone on the
|
|
1445
|
+
* way out or the connection is held until the app restarts. On iOS that is
|
|
1446
|
+
* not merely untidy: `deliverOpen` walks several candidates, and each failed
|
|
1447
|
+
* one would leave a live CoreBluetooth connection behind it.
|
|
1448
|
+
*/
|
|
1436
1449
|
connect(parentBleId: string): Promise<Session>;
|
|
1437
1450
|
requestNonce(session: Session): Promise<string>;
|
|
1438
1451
|
sendCommand(session: Session, token: string): Promise<CommandAck>;
|
|
@@ -1441,17 +1454,19 @@ declare class BleTransport implements ParentTransport {
|
|
|
1441
1454
|
/**
|
|
1442
1455
|
* Write one value and await the first notify line that matches `accept`.
|
|
1443
1456
|
*
|
|
1444
|
-
*
|
|
1457
|
+
* REGISTER, WRITE, WAIT, in that order, on the session's single subscription.
|
|
1445
1458
|
*
|
|
1446
|
-
*
|
|
1447
|
-
*
|
|
1448
|
-
*
|
|
1449
|
-
*
|
|
1459
|
+
* The waiter is registered SYNCHRONOUSLY, before the write is issued, so
|
|
1460
|
+
* there is no window in which a reply could arrive unwatched: the notify
|
|
1461
|
+
* callback cannot run before this function returns to the event loop. That is
|
|
1462
|
+
* why there is no buffer of unclaimed lines (see `NotifyState`), and why a
|
|
1463
|
+
* line that arrives with no waiter is dropped rather than kept: the Parent
|
|
1464
|
+
* speaks only in answer to a write, so an unclaimed line is stale, and a
|
|
1465
|
+
* stale `NONCE` carried forward would be minted against and then refused by
|
|
1466
|
+
* the Parent as a replay.
|
|
1450
1467
|
*
|
|
1451
|
-
*
|
|
1452
|
-
*
|
|
1453
|
-
* between the nonce leg and the command leg is covered: there is no moment in
|
|
1454
|
-
* the session when nobody is listening.
|
|
1468
|
+
* The subscription itself is opened in `connect` and held for the session, so
|
|
1469
|
+
* the gap between the nonce leg and the command leg is covered too.
|
|
1455
1470
|
*/
|
|
1456
1471
|
private writeAndAwait;
|
|
1457
1472
|
}
|
|
@@ -1516,6 +1531,34 @@ declare const REJECT_REASONS: readonly ["B64", "UNTAGGED", "FORMAT", "KEYVERSION
|
|
|
1516
1531
|
* caller" rather than to an infinite retry loop.
|
|
1517
1532
|
*/
|
|
1518
1533
|
declare function isRetryableRejectReason(reason: string): boolean;
|
|
1534
|
+
/**
|
|
1535
|
+
* Does this rejection mean "challenge again", rather than "stop"?
|
|
1536
|
+
*
|
|
1537
|
+
* ONLY `NONCE`, and the reason is in the firmware: a Parent holds ONE
|
|
1538
|
+
* outstanding challenge nonce (`CommandAuth.cpp`). Two phones at the same tower
|
|
1539
|
+
* seconds apart means the second `CHALLENGE` overwrites the first's nonce, and
|
|
1540
|
+
* the first phone's token is then refused as a replay it never attempted.
|
|
1541
|
+
* Nothing is wrong with the key, the grant or the radio: a fresh
|
|
1542
|
+
* challenge-mint-write round succeeds.
|
|
1543
|
+
*
|
|
1544
|
+
* DISTINCT FROM `isRetryableRejectReason`, which is about sending the SAME
|
|
1545
|
+
* bytes again after a pause (`NOTREADY`, where the Parent's key store had not
|
|
1546
|
+
* finished loading). This one needs NEW bytes, because the old token is bound
|
|
1547
|
+
* to a nonce the Parent has already discarded, so resending it can only fail
|
|
1548
|
+
* the same way.
|
|
1549
|
+
*
|
|
1550
|
+
* IT ALSO MEANS THE PARENT IS THE RIGHT ONE. The firmware verifies in a fixed
|
|
1551
|
+
* order (format, key version, tag, then nonce), so a command that reaches the
|
|
1552
|
+
* nonce check has already proved its tag against this Parent's key. A `NONCE`
|
|
1553
|
+
* rejection can only come from the Parent the grant names, which is why the
|
|
1554
|
+
* retry stays on the same session instead of resuming the search.
|
|
1555
|
+
*
|
|
1556
|
+
* SAFE TO RETRY, which is the question worth asking of any retry on a door.
|
|
1557
|
+
* `[AUTH] ACCEPT` is emitted at verify time, before the lock is touched, so a
|
|
1558
|
+
* `REJECT NONCE` means nothing moved and a second attempt cannot open a
|
|
1559
|
+
* compartment twice.
|
|
1560
|
+
*/
|
|
1561
|
+
declare function needsFreshNonce(reason: string): boolean;
|
|
1519
1562
|
/** Parse one already-decoded (plain-text) notify line. */
|
|
1520
1563
|
declare function parseNotifyLine(line: string): NotifyLine;
|
|
1521
1564
|
|
|
@@ -1723,4 +1766,4 @@ declare class RelaiTransportError extends RelaiError {
|
|
|
1723
1766
|
constructor(message: string);
|
|
1724
1767
|
}
|
|
1725
1768
|
|
|
1726
|
-
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 };
|
|
1769
|
+
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, needsFreshNonce, parseAdvertisedSerial, parseNotifyLine, presentRelaiPaymentSheet, serialMatches, verifyWebhook };
|
package/dist/index.d.ts
CHANGED
|
@@ -1411,6 +1411,8 @@ interface BleTransportOptions {
|
|
|
1411
1411
|
/** Discovery is app-specific (scan is often driven by your own UI); optional. */
|
|
1412
1412
|
scan?: () => Promise<DiscoveredParent[]>;
|
|
1413
1413
|
notifyTimeoutMs?: number;
|
|
1414
|
+
/** Per-candidate connection timeout; see CONNECT_TIMEOUT_MS. */
|
|
1415
|
+
connectTimeoutMs?: number;
|
|
1414
1416
|
}
|
|
1415
1417
|
declare class BleTransport implements ParentTransport {
|
|
1416
1418
|
private readonly manager;
|
|
@@ -1418,6 +1420,7 @@ declare class BleTransport implements ParentTransport {
|
|
|
1418
1420
|
private readonly notify;
|
|
1419
1421
|
private readonly scanImpl;
|
|
1420
1422
|
private readonly notifyTimeoutMs;
|
|
1423
|
+
private readonly connectTimeoutMs;
|
|
1421
1424
|
constructor(opts: BleTransportOptions);
|
|
1422
1425
|
/**
|
|
1423
1426
|
* Relai Parents in range.
|
|
@@ -1433,6 +1436,16 @@ declare class BleTransport implements ParentTransport {
|
|
|
1433
1436
|
* the command; this ordering only decides who gets asked first.
|
|
1434
1437
|
*/
|
|
1435
1438
|
scan(timeoutMs?: number): Promise<DiscoveredParent[]>;
|
|
1439
|
+
/**
|
|
1440
|
+
* Connect, discover, and start listening, or leave nothing behind.
|
|
1441
|
+
*
|
|
1442
|
+
* Every step after `connectToDevice` can fail, and a failure here returns no
|
|
1443
|
+
* Session, so NOBODY WILL EVER CALL `disconnect` for this device: the caller
|
|
1444
|
+
* has nothing to pass it. Anything this method set up has to be undone on the
|
|
1445
|
+
* way out or the connection is held until the app restarts. On iOS that is
|
|
1446
|
+
* not merely untidy: `deliverOpen` walks several candidates, and each failed
|
|
1447
|
+
* one would leave a live CoreBluetooth connection behind it.
|
|
1448
|
+
*/
|
|
1436
1449
|
connect(parentBleId: string): Promise<Session>;
|
|
1437
1450
|
requestNonce(session: Session): Promise<string>;
|
|
1438
1451
|
sendCommand(session: Session, token: string): Promise<CommandAck>;
|
|
@@ -1441,17 +1454,19 @@ declare class BleTransport implements ParentTransport {
|
|
|
1441
1454
|
/**
|
|
1442
1455
|
* Write one value and await the first notify line that matches `accept`.
|
|
1443
1456
|
*
|
|
1444
|
-
*
|
|
1457
|
+
* REGISTER, WRITE, WAIT, in that order, on the session's single subscription.
|
|
1445
1458
|
*
|
|
1446
|
-
*
|
|
1447
|
-
*
|
|
1448
|
-
*
|
|
1449
|
-
*
|
|
1459
|
+
* The waiter is registered SYNCHRONOUSLY, before the write is issued, so
|
|
1460
|
+
* there is no window in which a reply could arrive unwatched: the notify
|
|
1461
|
+
* callback cannot run before this function returns to the event loop. That is
|
|
1462
|
+
* why there is no buffer of unclaimed lines (see `NotifyState`), and why a
|
|
1463
|
+
* line that arrives with no waiter is dropped rather than kept: the Parent
|
|
1464
|
+
* speaks only in answer to a write, so an unclaimed line is stale, and a
|
|
1465
|
+
* stale `NONCE` carried forward would be minted against and then refused by
|
|
1466
|
+
* the Parent as a replay.
|
|
1450
1467
|
*
|
|
1451
|
-
*
|
|
1452
|
-
*
|
|
1453
|
-
* between the nonce leg and the command leg is covered: there is no moment in
|
|
1454
|
-
* the session when nobody is listening.
|
|
1468
|
+
* The subscription itself is opened in `connect` and held for the session, so
|
|
1469
|
+
* the gap between the nonce leg and the command leg is covered too.
|
|
1455
1470
|
*/
|
|
1456
1471
|
private writeAndAwait;
|
|
1457
1472
|
}
|
|
@@ -1516,6 +1531,34 @@ declare const REJECT_REASONS: readonly ["B64", "UNTAGGED", "FORMAT", "KEYVERSION
|
|
|
1516
1531
|
* caller" rather than to an infinite retry loop.
|
|
1517
1532
|
*/
|
|
1518
1533
|
declare function isRetryableRejectReason(reason: string): boolean;
|
|
1534
|
+
/**
|
|
1535
|
+
* Does this rejection mean "challenge again", rather than "stop"?
|
|
1536
|
+
*
|
|
1537
|
+
* ONLY `NONCE`, and the reason is in the firmware: a Parent holds ONE
|
|
1538
|
+
* outstanding challenge nonce (`CommandAuth.cpp`). Two phones at the same tower
|
|
1539
|
+
* seconds apart means the second `CHALLENGE` overwrites the first's nonce, and
|
|
1540
|
+
* the first phone's token is then refused as a replay it never attempted.
|
|
1541
|
+
* Nothing is wrong with the key, the grant or the radio: a fresh
|
|
1542
|
+
* challenge-mint-write round succeeds.
|
|
1543
|
+
*
|
|
1544
|
+
* DISTINCT FROM `isRetryableRejectReason`, which is about sending the SAME
|
|
1545
|
+
* bytes again after a pause (`NOTREADY`, where the Parent's key store had not
|
|
1546
|
+
* finished loading). This one needs NEW bytes, because the old token is bound
|
|
1547
|
+
* to a nonce the Parent has already discarded, so resending it can only fail
|
|
1548
|
+
* the same way.
|
|
1549
|
+
*
|
|
1550
|
+
* IT ALSO MEANS THE PARENT IS THE RIGHT ONE. The firmware verifies in a fixed
|
|
1551
|
+
* order (format, key version, tag, then nonce), so a command that reaches the
|
|
1552
|
+
* nonce check has already proved its tag against this Parent's key. A `NONCE`
|
|
1553
|
+
* rejection can only come from the Parent the grant names, which is why the
|
|
1554
|
+
* retry stays on the same session instead of resuming the search.
|
|
1555
|
+
*
|
|
1556
|
+
* SAFE TO RETRY, which is the question worth asking of any retry on a door.
|
|
1557
|
+
* `[AUTH] ACCEPT` is emitted at verify time, before the lock is touched, so a
|
|
1558
|
+
* `REJECT NONCE` means nothing moved and a second attempt cannot open a
|
|
1559
|
+
* compartment twice.
|
|
1560
|
+
*/
|
|
1561
|
+
declare function needsFreshNonce(reason: string): boolean;
|
|
1519
1562
|
/** Parse one already-decoded (plain-text) notify line. */
|
|
1520
1563
|
declare function parseNotifyLine(line: string): NotifyLine;
|
|
1521
1564
|
|
|
@@ -1723,4 +1766,4 @@ declare class RelaiTransportError extends RelaiError {
|
|
|
1723
1766
|
constructor(message: string);
|
|
1724
1767
|
}
|
|
1725
1768
|
|
|
1726
|
-
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 };
|
|
1769
|
+
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, needsFreshNonce, parseAdvertisedSerial, parseNotifyLine, presentRelaiPaymentSheet, serialMatches, verifyWebhook };
|
package/dist/index.js
CHANGED
|
@@ -592,6 +592,42 @@ var TelemetryUploader = class {
|
|
|
592
592
|
}
|
|
593
593
|
};
|
|
594
594
|
|
|
595
|
+
// src/transport/notify.ts
|
|
596
|
+
var REJECT_REASONS = [
|
|
597
|
+
"B64",
|
|
598
|
+
"UNTAGGED",
|
|
599
|
+
"FORMAT",
|
|
600
|
+
"KEYVERSION",
|
|
601
|
+
"TAG",
|
|
602
|
+
"NONCE",
|
|
603
|
+
"LOCKED",
|
|
604
|
+
"ROTATE",
|
|
605
|
+
"NOTREADY"
|
|
606
|
+
];
|
|
607
|
+
function isRetryableRejectReason(reason) {
|
|
608
|
+
return reason === "NOTREADY";
|
|
609
|
+
}
|
|
610
|
+
function needsFreshNonce(reason) {
|
|
611
|
+
return reason === "NONCE";
|
|
612
|
+
}
|
|
613
|
+
function parseNotifyLine(line) {
|
|
614
|
+
const trimmed = line.trim();
|
|
615
|
+
if (trimmed.startsWith("NONCE ")) {
|
|
616
|
+
const nonce = trimmed.slice("NONCE ".length).trim();
|
|
617
|
+
return { kind: "nonce", nonceB64Url: nonce };
|
|
618
|
+
}
|
|
619
|
+
if (trimmed.startsWith("[AUTH] ACCEPT ")) {
|
|
620
|
+
return { kind: "accept", command: trimmed.slice("[AUTH] ACCEPT ".length).trim() };
|
|
621
|
+
}
|
|
622
|
+
if (trimmed.startsWith("[AUTH] REJECT ")) {
|
|
623
|
+
const rest = trimmed.slice("[AUTH] REJECT ".length).trim();
|
|
624
|
+
const [reason, ...verbParts] = rest.split(/\s+/);
|
|
625
|
+
const verbHint = verbParts.length > 0 ? verbParts.join(" ") : void 0;
|
|
626
|
+
return { kind: "reject", reason: reason ?? "", verbHint };
|
|
627
|
+
}
|
|
628
|
+
return { kind: "passthrough", raw: trimmed };
|
|
629
|
+
}
|
|
630
|
+
|
|
595
631
|
// src/parent-resolve.ts
|
|
596
632
|
var WRONG_PARENT = "TAG";
|
|
597
633
|
function isWrongParentReject(reason) {
|
|
@@ -648,6 +684,7 @@ function orderCandidates(input) {
|
|
|
648
684
|
var MAX_PARENT_ATTEMPTS = 6;
|
|
649
685
|
|
|
650
686
|
// src/unlock.ts
|
|
687
|
+
var MAX_NONCE_RETRIES = 1;
|
|
651
688
|
async function deliverOpen(deps, open, opts) {
|
|
652
689
|
const { transport } = opts;
|
|
653
690
|
const grant = open.grant;
|
|
@@ -663,20 +700,30 @@ async function deliverOpen(deps, open, opts) {
|
|
|
663
700
|
const session = await transport.connect(handle);
|
|
664
701
|
let keep = false;
|
|
665
702
|
try {
|
|
666
|
-
|
|
703
|
+
const authenticated = grant.algorithm === "relai-hmac-sha256-16-v1";
|
|
667
704
|
let keyVersion;
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
token =
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
705
|
+
let ack;
|
|
706
|
+
let staleNonces = 0;
|
|
707
|
+
for (; ; ) {
|
|
708
|
+
let token = grant.token;
|
|
709
|
+
if (authenticated) {
|
|
710
|
+
const nonce = await transport.requestNonce(session);
|
|
711
|
+
const minted = await deps.grants.mint(grant.grant_id, nonce);
|
|
712
|
+
token = minted.token;
|
|
713
|
+
keyVersion = minted.key_version;
|
|
714
|
+
}
|
|
715
|
+
if (!token) {
|
|
716
|
+
throw new RelaiError(
|
|
717
|
+
`Grant ${grant.grant_id} has no token to deliver (algorithm ${grant.algorithm}).`
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
ack = await transport.sendCommand(session, token);
|
|
721
|
+
if (!ack.accepted && authenticated && needsFreshNonce(ack.rejectReason ?? "") && staleNonces < MAX_NONCE_RETRIES) {
|
|
722
|
+
staleNonces += 1;
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
break;
|
|
678
726
|
}
|
|
679
|
-
const ack = await transport.sendCommand(session, token);
|
|
680
727
|
if (!ack.accepted && isWrongParentReject(ack.rejectReason ?? "")) {
|
|
681
728
|
return null;
|
|
682
729
|
}
|
|
@@ -711,10 +758,13 @@ async function deliverOpen(deps, open, opts) {
|
|
|
711
758
|
}).catch(() => void 0);
|
|
712
759
|
}
|
|
713
760
|
let candidates = orderCandidates({ cached: await cache.get(parentBleId), parentBleId });
|
|
761
|
+
const tried = /* @__PURE__ */ new Set();
|
|
714
762
|
let scanned = false;
|
|
763
|
+
let attempts = 0;
|
|
715
764
|
let lastConnectError;
|
|
716
|
-
|
|
717
|
-
|
|
765
|
+
while (attempts < MAX_PARENT_ATTEMPTS) {
|
|
766
|
+
let handle = candidates.find((h) => !tried.has(h));
|
|
767
|
+
if (!handle) {
|
|
718
768
|
if (scanned) break;
|
|
719
769
|
scanned = true;
|
|
720
770
|
const found = await transport.scan().catch(() => []);
|
|
@@ -729,9 +779,11 @@ async function deliverOpen(deps, open, opts) {
|
|
|
729
779
|
parentSerial: open.grant.parent_serial
|
|
730
780
|
});
|
|
731
781
|
await cache.forget(parentBleId);
|
|
732
|
-
|
|
782
|
+
handle = candidates.find((h) => !tried.has(h));
|
|
783
|
+
if (!handle) break;
|
|
733
784
|
}
|
|
734
|
-
|
|
785
|
+
tried.add(handle);
|
|
786
|
+
attempts += 1;
|
|
735
787
|
try {
|
|
736
788
|
const result = await attempt(handle);
|
|
737
789
|
if (result) return result;
|
|
@@ -1098,45 +1150,13 @@ function serialMatches(advertised, granted) {
|
|
|
1098
1150
|
return advertised.toUpperCase() === granted.toUpperCase();
|
|
1099
1151
|
}
|
|
1100
1152
|
|
|
1101
|
-
// src/transport/notify.ts
|
|
1102
|
-
var REJECT_REASONS = [
|
|
1103
|
-
"B64",
|
|
1104
|
-
"UNTAGGED",
|
|
1105
|
-
"FORMAT",
|
|
1106
|
-
"KEYVERSION",
|
|
1107
|
-
"TAG",
|
|
1108
|
-
"NONCE",
|
|
1109
|
-
"LOCKED",
|
|
1110
|
-
"ROTATE",
|
|
1111
|
-
"NOTREADY"
|
|
1112
|
-
];
|
|
1113
|
-
function isRetryableRejectReason(reason) {
|
|
1114
|
-
return reason === "NOTREADY";
|
|
1115
|
-
}
|
|
1116
|
-
function parseNotifyLine(line) {
|
|
1117
|
-
const trimmed = line.trim();
|
|
1118
|
-
if (trimmed.startsWith("NONCE ")) {
|
|
1119
|
-
const nonce = trimmed.slice("NONCE ".length).trim();
|
|
1120
|
-
return { kind: "nonce", nonceB64Url: nonce };
|
|
1121
|
-
}
|
|
1122
|
-
if (trimmed.startsWith("[AUTH] ACCEPT ")) {
|
|
1123
|
-
return { kind: "accept", command: trimmed.slice("[AUTH] ACCEPT ".length).trim() };
|
|
1124
|
-
}
|
|
1125
|
-
if (trimmed.startsWith("[AUTH] REJECT ")) {
|
|
1126
|
-
const rest = trimmed.slice("[AUTH] REJECT ".length).trim();
|
|
1127
|
-
const [reason, ...verbParts] = rest.split(/\s+/);
|
|
1128
|
-
const verbHint = verbParts.length > 0 ? verbParts.join(" ") : void 0;
|
|
1129
|
-
return { kind: "reject", reason: reason ?? "", verbHint };
|
|
1130
|
-
}
|
|
1131
|
-
return { kind: "passthrough", raw: trimmed };
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
1153
|
// src/transport/ble.ts
|
|
1135
1154
|
var RELAI_UART_SERVICE = "0000ff00-0000-1000-8000-00805f9b34fb";
|
|
1136
1155
|
var RELAI_RX_CHAR = "0000ff02-0000-1000-8000-00805f9b34fb";
|
|
1137
1156
|
var RELAI_TX_CHAR = "0000ff03-0000-1000-8000-00805f9b34fb";
|
|
1138
1157
|
var MIN_MTU = 110;
|
|
1139
1158
|
var NOTIFY_TIMEOUT_MS = 8e3;
|
|
1159
|
+
var CONNECT_TIMEOUT_MS = 1e4;
|
|
1140
1160
|
var BleTransport = class {
|
|
1141
1161
|
constructor(opts) {
|
|
1142
1162
|
this.devices = /* @__PURE__ */ new Map();
|
|
@@ -1144,6 +1164,7 @@ var BleTransport = class {
|
|
|
1144
1164
|
this.manager = opts.manager;
|
|
1145
1165
|
this.scanImpl = opts.scan;
|
|
1146
1166
|
this.notifyTimeoutMs = opts.notifyTimeoutMs ?? NOTIFY_TIMEOUT_MS;
|
|
1167
|
+
this.connectTimeoutMs = opts.connectTimeoutMs ?? CONNECT_TIMEOUT_MS;
|
|
1147
1168
|
}
|
|
1148
1169
|
/**
|
|
1149
1170
|
* Relai Parents in range.
|
|
@@ -1205,53 +1226,78 @@ var BleTransport = class {
|
|
|
1205
1226
|
}
|
|
1206
1227
|
});
|
|
1207
1228
|
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Connect, discover, and start listening, or leave nothing behind.
|
|
1231
|
+
*
|
|
1232
|
+
* Every step after `connectToDevice` can fail, and a failure here returns no
|
|
1233
|
+
* Session, so NOBODY WILL EVER CALL `disconnect` for this device: the caller
|
|
1234
|
+
* has nothing to pass it. Anything this method set up has to be undone on the
|
|
1235
|
+
* way out or the connection is held until the app restarts. On iOS that is
|
|
1236
|
+
* not merely untidy: `deliverOpen` walks several candidates, and each failed
|
|
1237
|
+
* one would leave a live CoreBluetooth connection behind it.
|
|
1238
|
+
*/
|
|
1208
1239
|
async connect(parentBleId) {
|
|
1209
|
-
let device = await this.manager.connectToDevice(parentBleId);
|
|
1210
|
-
if (this.manager.discoverAllServicesAndCharacteristicsForDevice) {
|
|
1211
|
-
device = await this.manager.discoverAllServicesAndCharacteristicsForDevice(device.id);
|
|
1212
|
-
}
|
|
1240
|
+
let device = await this.manager.connectToDevice(parentBleId, { timeout: this.connectTimeoutMs });
|
|
1213
1241
|
try {
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
remove: () => void 0
|
|
1224
|
-
};
|
|
1225
|
-
const sub = device.monitorCharacteristicForService(
|
|
1226
|
-
RELAI_UART_SERVICE,
|
|
1227
|
-
RELAI_TX_CHAR,
|
|
1228
|
-
(error, ch) => {
|
|
1229
|
-
if (error) {
|
|
1230
|
-
const err = new RelaiTransportError(`BLE notify error: ${String(error)}`);
|
|
1231
|
-
state.error = err;
|
|
1232
|
-
state.failed?.(err);
|
|
1233
|
-
return;
|
|
1234
|
-
}
|
|
1235
|
-
const value = ch?.value;
|
|
1236
|
-
if (!value) return;
|
|
1237
|
-
let text;
|
|
1242
|
+
if (this.manager.discoverAllServicesAndCharacteristicsForDevice) {
|
|
1243
|
+
device = await this.manager.discoverAllServicesAndCharacteristicsForDevice(device.id);
|
|
1244
|
+
}
|
|
1245
|
+
try {
|
|
1246
|
+
device = await device.requestMTU(MIN_MTU);
|
|
1247
|
+
} catch {
|
|
1248
|
+
}
|
|
1249
|
+
const previous = this.notify.get(device.id);
|
|
1250
|
+
if (previous) {
|
|
1238
1251
|
try {
|
|
1239
|
-
|
|
1252
|
+
previous.remove();
|
|
1240
1253
|
} catch {
|
|
1241
|
-
return;
|
|
1242
|
-
}
|
|
1243
|
-
if (state.waiter && state.accept?.(parseNotifyLine(text))) {
|
|
1244
|
-
const resolve = state.waiter;
|
|
1245
|
-
state.waiter = void 0;
|
|
1246
|
-
state.accept = void 0;
|
|
1247
|
-
state.failed = void 0;
|
|
1248
|
-
resolve(text);
|
|
1249
1254
|
}
|
|
1255
|
+
this.notify.delete(device.id);
|
|
1250
1256
|
}
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1257
|
+
this.devices.set(device.id, device);
|
|
1258
|
+
const state = {
|
|
1259
|
+
waiter: void 0,
|
|
1260
|
+
accept: void 0,
|
|
1261
|
+
failed: void 0,
|
|
1262
|
+
error: void 0,
|
|
1263
|
+
remove: () => void 0
|
|
1264
|
+
};
|
|
1265
|
+
const sub = device.monitorCharacteristicForService(
|
|
1266
|
+
RELAI_UART_SERVICE,
|
|
1267
|
+
RELAI_TX_CHAR,
|
|
1268
|
+
(error, ch) => {
|
|
1269
|
+
if (error) {
|
|
1270
|
+
const err = new RelaiTransportError(`BLE notify error: ${String(error)}`);
|
|
1271
|
+
state.error = err;
|
|
1272
|
+
state.failed?.(err);
|
|
1273
|
+
return;
|
|
1274
|
+
}
|
|
1275
|
+
const value = ch?.value;
|
|
1276
|
+
if (!value) return;
|
|
1277
|
+
let text;
|
|
1278
|
+
try {
|
|
1279
|
+
text = base64ToUtf8(value);
|
|
1280
|
+
} catch {
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
if (state.waiter && state.accept?.(parseNotifyLine(text))) {
|
|
1284
|
+
const resolve = state.waiter;
|
|
1285
|
+
state.waiter = void 0;
|
|
1286
|
+
state.accept = void 0;
|
|
1287
|
+
state.failed = void 0;
|
|
1288
|
+
resolve(text);
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
);
|
|
1292
|
+
state.remove = () => sub.remove();
|
|
1293
|
+
this.notify.set(device.id, state);
|
|
1294
|
+
return { id: device.id, parentBleId, connectedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
1295
|
+
} catch (err) {
|
|
1296
|
+
this.notify.delete(device.id);
|
|
1297
|
+
this.devices.delete(device.id);
|
|
1298
|
+
await device.cancelConnection().catch(() => void 0);
|
|
1299
|
+
throw err;
|
|
1300
|
+
}
|
|
1255
1301
|
}
|
|
1256
1302
|
async requestNonce(session) {
|
|
1257
1303
|
const line = await this.writeAndAwait(session, utf8ToBase64("CHALLENGE"));
|
|
@@ -1293,17 +1339,19 @@ var BleTransport = class {
|
|
|
1293
1339
|
/**
|
|
1294
1340
|
* Write one value and await the first notify line that matches `accept`.
|
|
1295
1341
|
*
|
|
1296
|
-
*
|
|
1342
|
+
* REGISTER, WRITE, WAIT, in that order, on the session's single subscription.
|
|
1297
1343
|
*
|
|
1298
|
-
*
|
|
1299
|
-
*
|
|
1300
|
-
*
|
|
1301
|
-
*
|
|
1344
|
+
* The waiter is registered SYNCHRONOUSLY, before the write is issued, so
|
|
1345
|
+
* there is no window in which a reply could arrive unwatched: the notify
|
|
1346
|
+
* callback cannot run before this function returns to the event loop. That is
|
|
1347
|
+
* why there is no buffer of unclaimed lines (see `NotifyState`), and why a
|
|
1348
|
+
* line that arrives with no waiter is dropped rather than kept: the Parent
|
|
1349
|
+
* speaks only in answer to a write, so an unclaimed line is stale, and a
|
|
1350
|
+
* stale `NONCE` carried forward would be minted against and then refused by
|
|
1351
|
+
* the Parent as a replay.
|
|
1302
1352
|
*
|
|
1303
|
-
*
|
|
1304
|
-
*
|
|
1305
|
-
* between the nonce leg and the command leg is covered: there is no moment in
|
|
1306
|
-
* the session when nobody is listening.
|
|
1353
|
+
* The subscription itself is opened in `connect` and held for the session, so
|
|
1354
|
+
* the gap between the nonce leg and the command leg is covered too.
|
|
1307
1355
|
*/
|
|
1308
1356
|
writeAndAwait(session, valueBase64, accept = (p) => p.kind !== "passthrough") {
|
|
1309
1357
|
const device = this.devices.get(session.id);
|
|
@@ -1377,4 +1425,4 @@ var Intents = {
|
|
|
1377
1425
|
MakeAvailable: "make_available"
|
|
1378
1426
|
};
|
|
1379
1427
|
|
|
1380
|
-
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 };
|
|
1428
|
+
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, needsFreshNonce, parseAdvertisedSerial, parseNotifyLine, serialMatches, verifyWebhook };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@relai-team/access-sdk",
|
|
3
|
-
"version": "0.20.
|
|
3
|
+
"version": "0.20.3",
|
|
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",
|