@relai-team/access-sdk 0.20.2 → 0.21.1
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 +100 -46
- package/dist/index.d.cts +38 -2
- package/dist/index.d.ts +38 -2
- package/dist/index.js +100 -47
- 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,13 @@ function orderCandidates(input) {
|
|
|
811
847
|
var MAX_PARENT_ATTEMPTS = 6;
|
|
812
848
|
|
|
813
849
|
// src/unlock.ts
|
|
850
|
+
var MAX_NONCE_RETRIES = 1;
|
|
851
|
+
var MAX_NOT_READY_RETRIES = 2;
|
|
852
|
+
var NOT_READY_BACKOFF_MS = 300;
|
|
853
|
+
var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
854
|
+
function isNotReadyYet(err) {
|
|
855
|
+
return err instanceof exports.RelaiUnlockRejected && isRetryableRejectReason(err.reason);
|
|
856
|
+
}
|
|
814
857
|
async function deliverOpen(deps, open, opts) {
|
|
815
858
|
const { transport } = opts;
|
|
816
859
|
const grant = open.grant;
|
|
@@ -826,20 +869,46 @@ async function deliverOpen(deps, open, opts) {
|
|
|
826
869
|
const session = await transport.connect(handle);
|
|
827
870
|
let keep = false;
|
|
828
871
|
try {
|
|
829
|
-
|
|
872
|
+
const authenticated = grant.algorithm === "relai-hmac-sha256-16-v1";
|
|
830
873
|
let keyVersion;
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
874
|
+
let ack;
|
|
875
|
+
let staleNonces = 0;
|
|
876
|
+
let notReady = 0;
|
|
877
|
+
for (; ; ) {
|
|
878
|
+
let token = grant.token;
|
|
879
|
+
if (authenticated) {
|
|
880
|
+
let nonce;
|
|
881
|
+
try {
|
|
882
|
+
nonce = await transport.requestNonce(session);
|
|
883
|
+
} catch (err) {
|
|
884
|
+
if (isNotReadyYet(err) && notReady < MAX_NOT_READY_RETRIES) {
|
|
885
|
+
notReady += 1;
|
|
886
|
+
await wait(NOT_READY_BACKOFF_MS);
|
|
887
|
+
continue;
|
|
888
|
+
}
|
|
889
|
+
throw err;
|
|
890
|
+
}
|
|
891
|
+
const minted = await deps.grants.mint(grant.grant_id, nonce);
|
|
892
|
+
token = minted.token;
|
|
893
|
+
keyVersion = minted.key_version;
|
|
894
|
+
}
|
|
895
|
+
if (!token) {
|
|
896
|
+
throw new exports.RelaiError(
|
|
897
|
+
`Grant ${grant.grant_id} has no token to deliver (algorithm ${grant.algorithm}).`
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
ack = await transport.sendCommand(session, token);
|
|
901
|
+
if (!ack.accepted && authenticated && needsFreshNonce(ack.rejectReason ?? "") && staleNonces < MAX_NONCE_RETRIES) {
|
|
902
|
+
staleNonces += 1;
|
|
903
|
+
continue;
|
|
904
|
+
}
|
|
905
|
+
if (!ack.accepted && isRetryableRejectReason(ack.rejectReason ?? "") && notReady < MAX_NOT_READY_RETRIES) {
|
|
906
|
+
notReady += 1;
|
|
907
|
+
await wait(NOT_READY_BACKOFF_MS);
|
|
908
|
+
continue;
|
|
909
|
+
}
|
|
910
|
+
break;
|
|
841
911
|
}
|
|
842
|
-
const ack = await transport.sendCommand(session, token);
|
|
843
912
|
if (!ack.accepted && isWrongParentReject(ack.rejectReason ?? "")) {
|
|
844
913
|
return null;
|
|
845
914
|
}
|
|
@@ -996,7 +1065,8 @@ var RelaiClient = class {
|
|
|
996
1065
|
open = await requestOpen();
|
|
997
1066
|
} catch (err) {
|
|
998
1067
|
const { RelaiApiError: RelaiApiError2 } = await Promise.resolve().then(() => (init_errors(), errors_exports));
|
|
999
|
-
|
|
1068
|
+
const payable = err instanceof RelaiApiError2 && (err.code === "payment_required" || err.code === "late_fee_due");
|
|
1069
|
+
if (input.presentPaymentSheet !== false && payable) {
|
|
1000
1070
|
const { asPaymentRequired: asPaymentRequired2, presentRelaiPaymentSheet: presentRelaiPaymentSheet2 } = await Promise.resolve().then(() => (init_payment_sheet(), payment_sheet_exports));
|
|
1001
1071
|
const details = asPaymentRequired2(err.details);
|
|
1002
1072
|
if (!details || !await presentRelaiPaymentSheet2(details, this.stripe)) throw err;
|
|
@@ -1273,39 +1343,6 @@ function serialMatches(advertised, granted) {
|
|
|
1273
1343
|
return advertised.toUpperCase() === granted.toUpperCase();
|
|
1274
1344
|
}
|
|
1275
1345
|
|
|
1276
|
-
// src/transport/notify.ts
|
|
1277
|
-
var REJECT_REASONS = [
|
|
1278
|
-
"B64",
|
|
1279
|
-
"UNTAGGED",
|
|
1280
|
-
"FORMAT",
|
|
1281
|
-
"KEYVERSION",
|
|
1282
|
-
"TAG",
|
|
1283
|
-
"NONCE",
|
|
1284
|
-
"LOCKED",
|
|
1285
|
-
"ROTATE",
|
|
1286
|
-
"NOTREADY"
|
|
1287
|
-
];
|
|
1288
|
-
function isRetryableRejectReason(reason) {
|
|
1289
|
-
return reason === "NOTREADY";
|
|
1290
|
-
}
|
|
1291
|
-
function parseNotifyLine(line) {
|
|
1292
|
-
const trimmed = line.trim();
|
|
1293
|
-
if (trimmed.startsWith("NONCE ")) {
|
|
1294
|
-
const nonce = trimmed.slice("NONCE ".length).trim();
|
|
1295
|
-
return { kind: "nonce", nonceB64Url: nonce };
|
|
1296
|
-
}
|
|
1297
|
-
if (trimmed.startsWith("[AUTH] ACCEPT ")) {
|
|
1298
|
-
return { kind: "accept", command: trimmed.slice("[AUTH] ACCEPT ".length).trim() };
|
|
1299
|
-
}
|
|
1300
|
-
if (trimmed.startsWith("[AUTH] REJECT ")) {
|
|
1301
|
-
const rest = trimmed.slice("[AUTH] REJECT ".length).trim();
|
|
1302
|
-
const [reason, ...verbParts] = rest.split(/\s+/);
|
|
1303
|
-
const verbHint = verbParts.length > 0 ? verbParts.join(" ") : void 0;
|
|
1304
|
-
return { kind: "reject", reason: reason ?? "", verbHint };
|
|
1305
|
-
}
|
|
1306
|
-
return { kind: "passthrough", raw: trimmed };
|
|
1307
|
-
}
|
|
1308
|
-
|
|
1309
1346
|
// src/transport/ble.ts
|
|
1310
1347
|
var RELAI_UART_SERVICE = "0000ff00-0000-1000-8000-00805f9b34fb";
|
|
1311
1348
|
var RELAI_RX_CHAR = "0000ff02-0000-1000-8000-00805f9b34fb";
|
|
@@ -1393,6 +1430,19 @@ var BleTransport = class {
|
|
|
1393
1430
|
* one would leave a live CoreBluetooth connection behind it.
|
|
1394
1431
|
*/
|
|
1395
1432
|
async connect(parentBleId) {
|
|
1433
|
+
const held = this.devices.get(parentBleId);
|
|
1434
|
+
if (held) {
|
|
1435
|
+
const state = this.notify.get(parentBleId);
|
|
1436
|
+
if (state) {
|
|
1437
|
+
try {
|
|
1438
|
+
state.remove();
|
|
1439
|
+
} catch {
|
|
1440
|
+
}
|
|
1441
|
+
this.notify.delete(parentBleId);
|
|
1442
|
+
}
|
|
1443
|
+
this.devices.delete(parentBleId);
|
|
1444
|
+
await held.cancelConnection().catch(() => void 0);
|
|
1445
|
+
}
|
|
1396
1446
|
let device = await this.manager.connectToDevice(parentBleId, { timeout: this.connectTimeoutMs });
|
|
1397
1447
|
try {
|
|
1398
1448
|
if (this.manager.discoverAllServicesAndCharacteristicsForDevice) {
|
|
@@ -1458,6 +1508,9 @@ var BleTransport = class {
|
|
|
1458
1508
|
async requestNonce(session) {
|
|
1459
1509
|
const line = await this.writeAndAwait(session, utf8ToBase64("CHALLENGE"));
|
|
1460
1510
|
const parsed = parseNotifyLine(line);
|
|
1511
|
+
if (parsed.kind === "reject") {
|
|
1512
|
+
throw new exports.RelaiUnlockRejected(parsed.reason, parsed.verbHint);
|
|
1513
|
+
}
|
|
1461
1514
|
if (parsed.kind !== "nonce") {
|
|
1462
1515
|
throw new exports.RelaiTransportError(`Expected NONCE from Parent, got: ${line}`);
|
|
1463
1516
|
}
|
|
@@ -1613,6 +1666,7 @@ exports.asPaymentRequired = asPaymentRequired;
|
|
|
1613
1666
|
exports.deliverOpen = deliverOpen;
|
|
1614
1667
|
exports.isRetryableRejectReason = isRetryableRejectReason;
|
|
1615
1668
|
exports.isStripePublishableKey = isStripePublishableKey;
|
|
1669
|
+
exports.needsFreshNonce = needsFreshNonce;
|
|
1616
1670
|
exports.parseAdvertisedSerial = parseAdvertisedSerial;
|
|
1617
1671
|
exports.parseNotifyLine = parseNotifyLine;
|
|
1618
1672
|
exports.presentRelaiPaymentSheet = presentRelaiPaymentSheet;
|
package/dist/index.d.cts
CHANGED
|
@@ -1121,7 +1121,13 @@ declare function deliverOpen(deps: UnlockDeps, open: Open, opts: DeliverOptions)
|
|
|
1121
1121
|
* `import` is what Metro sees, and it exists only in apps that installed it.
|
|
1122
1122
|
*/
|
|
1123
1123
|
interface PaymentRequiredDetails {
|
|
1124
|
-
|
|
1124
|
+
/**
|
|
1125
|
+
* Which payment this is. `late_fee` arrives on a `late_fee_due` 402 and is
|
|
1126
|
+
* the late pick-up fee, the one payment the platform asks an end user for
|
|
1127
|
+
* directly; the rest arrive on `payment_required`. One shape for both, so
|
|
1128
|
+
* this helper presents either.
|
|
1129
|
+
*/
|
|
1130
|
+
kind: "prepaid" | "payg_base" | "payg_setup" | "payg_pickup" | "late_fee";
|
|
1125
1131
|
client_secret: string | null;
|
|
1126
1132
|
/** True when this is a card SAVE (PAYG with a zero base), not a charge. */
|
|
1127
1133
|
setup: boolean;
|
|
@@ -1136,6 +1142,8 @@ interface PaymentRequiredDetails {
|
|
|
1136
1142
|
processing_cents: number;
|
|
1137
1143
|
total_cents: number;
|
|
1138
1144
|
};
|
|
1145
|
+
/** The late pick-up fee, on `late_fee` only. Equal to `breakdown.total_cents`. */
|
|
1146
|
+
fee_cents?: number;
|
|
1139
1147
|
}
|
|
1140
1148
|
/**
|
|
1141
1149
|
* The slice of `@stripe/stripe-react-native` this SDK uses. Structural on
|
|
@@ -1531,6 +1539,34 @@ declare const REJECT_REASONS: readonly ["B64", "UNTAGGED", "FORMAT", "KEYVERSION
|
|
|
1531
1539
|
* caller" rather than to an infinite retry loop.
|
|
1532
1540
|
*/
|
|
1533
1541
|
declare function isRetryableRejectReason(reason: string): boolean;
|
|
1542
|
+
/**
|
|
1543
|
+
* Does this rejection mean "challenge again", rather than "stop"?
|
|
1544
|
+
*
|
|
1545
|
+
* ONLY `NONCE`, and the reason is in the firmware: a Parent holds ONE
|
|
1546
|
+
* outstanding challenge nonce (`CommandAuth.cpp`). Two phones at the same tower
|
|
1547
|
+
* seconds apart means the second `CHALLENGE` overwrites the first's nonce, and
|
|
1548
|
+
* the first phone's token is then refused as a replay it never attempted.
|
|
1549
|
+
* Nothing is wrong with the key, the grant or the radio: a fresh
|
|
1550
|
+
* challenge-mint-write round succeeds.
|
|
1551
|
+
*
|
|
1552
|
+
* DISTINCT FROM `isRetryableRejectReason`, which is about sending the SAME
|
|
1553
|
+
* bytes again after a pause (`NOTREADY`, where the Parent's key store had not
|
|
1554
|
+
* finished loading). This one needs NEW bytes, because the old token is bound
|
|
1555
|
+
* to a nonce the Parent has already discarded, so resending it can only fail
|
|
1556
|
+
* the same way.
|
|
1557
|
+
*
|
|
1558
|
+
* IT ALSO MEANS THE PARENT IS THE RIGHT ONE. The firmware verifies in a fixed
|
|
1559
|
+
* order (format, key version, tag, then nonce), so a command that reaches the
|
|
1560
|
+
* nonce check has already proved its tag against this Parent's key. A `NONCE`
|
|
1561
|
+
* rejection can only come from the Parent the grant names, which is why the
|
|
1562
|
+
* retry stays on the same session instead of resuming the search.
|
|
1563
|
+
*
|
|
1564
|
+
* SAFE TO RETRY, which is the question worth asking of any retry on a door.
|
|
1565
|
+
* `[AUTH] ACCEPT` is emitted at verify time, before the lock is touched, so a
|
|
1566
|
+
* `REJECT NONCE` means nothing moved and a second attempt cannot open a
|
|
1567
|
+
* compartment twice.
|
|
1568
|
+
*/
|
|
1569
|
+
declare function needsFreshNonce(reason: string): boolean;
|
|
1534
1570
|
/** Parse one already-decoded (plain-text) notify line. */
|
|
1535
1571
|
declare function parseNotifyLine(line: string): NotifyLine;
|
|
1536
1572
|
|
|
@@ -1738,4 +1774,4 @@ declare class RelaiTransportError extends RelaiError {
|
|
|
1738
1774
|
constructor(message: string);
|
|
1739
1775
|
}
|
|
1740
1776
|
|
|
1741
|
-
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 };
|
|
1777
|
+
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
|
@@ -1121,7 +1121,13 @@ declare function deliverOpen(deps: UnlockDeps, open: Open, opts: DeliverOptions)
|
|
|
1121
1121
|
* `import` is what Metro sees, and it exists only in apps that installed it.
|
|
1122
1122
|
*/
|
|
1123
1123
|
interface PaymentRequiredDetails {
|
|
1124
|
-
|
|
1124
|
+
/**
|
|
1125
|
+
* Which payment this is. `late_fee` arrives on a `late_fee_due` 402 and is
|
|
1126
|
+
* the late pick-up fee, the one payment the platform asks an end user for
|
|
1127
|
+
* directly; the rest arrive on `payment_required`. One shape for both, so
|
|
1128
|
+
* this helper presents either.
|
|
1129
|
+
*/
|
|
1130
|
+
kind: "prepaid" | "payg_base" | "payg_setup" | "payg_pickup" | "late_fee";
|
|
1125
1131
|
client_secret: string | null;
|
|
1126
1132
|
/** True when this is a card SAVE (PAYG with a zero base), not a charge. */
|
|
1127
1133
|
setup: boolean;
|
|
@@ -1136,6 +1142,8 @@ interface PaymentRequiredDetails {
|
|
|
1136
1142
|
processing_cents: number;
|
|
1137
1143
|
total_cents: number;
|
|
1138
1144
|
};
|
|
1145
|
+
/** The late pick-up fee, on `late_fee` only. Equal to `breakdown.total_cents`. */
|
|
1146
|
+
fee_cents?: number;
|
|
1139
1147
|
}
|
|
1140
1148
|
/**
|
|
1141
1149
|
* The slice of `@stripe/stripe-react-native` this SDK uses. Structural on
|
|
@@ -1531,6 +1539,34 @@ declare const REJECT_REASONS: readonly ["B64", "UNTAGGED", "FORMAT", "KEYVERSION
|
|
|
1531
1539
|
* caller" rather than to an infinite retry loop.
|
|
1532
1540
|
*/
|
|
1533
1541
|
declare function isRetryableRejectReason(reason: string): boolean;
|
|
1542
|
+
/**
|
|
1543
|
+
* Does this rejection mean "challenge again", rather than "stop"?
|
|
1544
|
+
*
|
|
1545
|
+
* ONLY `NONCE`, and the reason is in the firmware: a Parent holds ONE
|
|
1546
|
+
* outstanding challenge nonce (`CommandAuth.cpp`). Two phones at the same tower
|
|
1547
|
+
* seconds apart means the second `CHALLENGE` overwrites the first's nonce, and
|
|
1548
|
+
* the first phone's token is then refused as a replay it never attempted.
|
|
1549
|
+
* Nothing is wrong with the key, the grant or the radio: a fresh
|
|
1550
|
+
* challenge-mint-write round succeeds.
|
|
1551
|
+
*
|
|
1552
|
+
* DISTINCT FROM `isRetryableRejectReason`, which is about sending the SAME
|
|
1553
|
+
* bytes again after a pause (`NOTREADY`, where the Parent's key store had not
|
|
1554
|
+
* finished loading). This one needs NEW bytes, because the old token is bound
|
|
1555
|
+
* to a nonce the Parent has already discarded, so resending it can only fail
|
|
1556
|
+
* the same way.
|
|
1557
|
+
*
|
|
1558
|
+
* IT ALSO MEANS THE PARENT IS THE RIGHT ONE. The firmware verifies in a fixed
|
|
1559
|
+
* order (format, key version, tag, then nonce), so a command that reaches the
|
|
1560
|
+
* nonce check has already proved its tag against this Parent's key. A `NONCE`
|
|
1561
|
+
* rejection can only come from the Parent the grant names, which is why the
|
|
1562
|
+
* retry stays on the same session instead of resuming the search.
|
|
1563
|
+
*
|
|
1564
|
+
* SAFE TO RETRY, which is the question worth asking of any retry on a door.
|
|
1565
|
+
* `[AUTH] ACCEPT` is emitted at verify time, before the lock is touched, so a
|
|
1566
|
+
* `REJECT NONCE` means nothing moved and a second attempt cannot open a
|
|
1567
|
+
* compartment twice.
|
|
1568
|
+
*/
|
|
1569
|
+
declare function needsFreshNonce(reason: string): boolean;
|
|
1534
1570
|
/** Parse one already-decoded (plain-text) notify line. */
|
|
1535
1571
|
declare function parseNotifyLine(line: string): NotifyLine;
|
|
1536
1572
|
|
|
@@ -1738,4 +1774,4 @@ declare class RelaiTransportError extends RelaiError {
|
|
|
1738
1774
|
constructor(message: string);
|
|
1739
1775
|
}
|
|
1740
1776
|
|
|
1741
|
-
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 };
|
|
1777
|
+
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,13 @@ function orderCandidates(input) {
|
|
|
648
684
|
var MAX_PARENT_ATTEMPTS = 6;
|
|
649
685
|
|
|
650
686
|
// src/unlock.ts
|
|
687
|
+
var MAX_NONCE_RETRIES = 1;
|
|
688
|
+
var MAX_NOT_READY_RETRIES = 2;
|
|
689
|
+
var NOT_READY_BACKOFF_MS = 300;
|
|
690
|
+
var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
691
|
+
function isNotReadyYet(err) {
|
|
692
|
+
return err instanceof RelaiUnlockRejected && isRetryableRejectReason(err.reason);
|
|
693
|
+
}
|
|
651
694
|
async function deliverOpen(deps, open, opts) {
|
|
652
695
|
const { transport } = opts;
|
|
653
696
|
const grant = open.grant;
|
|
@@ -663,20 +706,46 @@ async function deliverOpen(deps, open, opts) {
|
|
|
663
706
|
const session = await transport.connect(handle);
|
|
664
707
|
let keep = false;
|
|
665
708
|
try {
|
|
666
|
-
|
|
709
|
+
const authenticated = grant.algorithm === "relai-hmac-sha256-16-v1";
|
|
667
710
|
let keyVersion;
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
711
|
+
let ack;
|
|
712
|
+
let staleNonces = 0;
|
|
713
|
+
let notReady = 0;
|
|
714
|
+
for (; ; ) {
|
|
715
|
+
let token = grant.token;
|
|
716
|
+
if (authenticated) {
|
|
717
|
+
let nonce;
|
|
718
|
+
try {
|
|
719
|
+
nonce = await transport.requestNonce(session);
|
|
720
|
+
} catch (err) {
|
|
721
|
+
if (isNotReadyYet(err) && notReady < MAX_NOT_READY_RETRIES) {
|
|
722
|
+
notReady += 1;
|
|
723
|
+
await wait(NOT_READY_BACKOFF_MS);
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
throw err;
|
|
727
|
+
}
|
|
728
|
+
const minted = await deps.grants.mint(grant.grant_id, nonce);
|
|
729
|
+
token = minted.token;
|
|
730
|
+
keyVersion = minted.key_version;
|
|
731
|
+
}
|
|
732
|
+
if (!token) {
|
|
733
|
+
throw new RelaiError(
|
|
734
|
+
`Grant ${grant.grant_id} has no token to deliver (algorithm ${grant.algorithm}).`
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
ack = await transport.sendCommand(session, token);
|
|
738
|
+
if (!ack.accepted && authenticated && needsFreshNonce(ack.rejectReason ?? "") && staleNonces < MAX_NONCE_RETRIES) {
|
|
739
|
+
staleNonces += 1;
|
|
740
|
+
continue;
|
|
741
|
+
}
|
|
742
|
+
if (!ack.accepted && isRetryableRejectReason(ack.rejectReason ?? "") && notReady < MAX_NOT_READY_RETRIES) {
|
|
743
|
+
notReady += 1;
|
|
744
|
+
await wait(NOT_READY_BACKOFF_MS);
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
break;
|
|
678
748
|
}
|
|
679
|
-
const ack = await transport.sendCommand(session, token);
|
|
680
749
|
if (!ack.accepted && isWrongParentReject(ack.rejectReason ?? "")) {
|
|
681
750
|
return null;
|
|
682
751
|
}
|
|
@@ -833,7 +902,8 @@ var RelaiClient = class {
|
|
|
833
902
|
open = await requestOpen();
|
|
834
903
|
} catch (err) {
|
|
835
904
|
const { RelaiApiError: RelaiApiError2 } = await import('./errors-NKRGOFB3.js');
|
|
836
|
-
|
|
905
|
+
const payable = err instanceof RelaiApiError2 && (err.code === "payment_required" || err.code === "late_fee_due");
|
|
906
|
+
if (input.presentPaymentSheet !== false && payable) {
|
|
837
907
|
const { asPaymentRequired: asPaymentRequired2, presentRelaiPaymentSheet: presentRelaiPaymentSheet2 } = await import('./payment-sheet-B3X5QQMO.js');
|
|
838
908
|
const details = asPaymentRequired2(err.details);
|
|
839
909
|
if (!details || !await presentRelaiPaymentSheet2(details, this.stripe)) throw err;
|
|
@@ -1103,39 +1173,6 @@ function serialMatches(advertised, granted) {
|
|
|
1103
1173
|
return advertised.toUpperCase() === granted.toUpperCase();
|
|
1104
1174
|
}
|
|
1105
1175
|
|
|
1106
|
-
// src/transport/notify.ts
|
|
1107
|
-
var REJECT_REASONS = [
|
|
1108
|
-
"B64",
|
|
1109
|
-
"UNTAGGED",
|
|
1110
|
-
"FORMAT",
|
|
1111
|
-
"KEYVERSION",
|
|
1112
|
-
"TAG",
|
|
1113
|
-
"NONCE",
|
|
1114
|
-
"LOCKED",
|
|
1115
|
-
"ROTATE",
|
|
1116
|
-
"NOTREADY"
|
|
1117
|
-
];
|
|
1118
|
-
function isRetryableRejectReason(reason) {
|
|
1119
|
-
return reason === "NOTREADY";
|
|
1120
|
-
}
|
|
1121
|
-
function parseNotifyLine(line) {
|
|
1122
|
-
const trimmed = line.trim();
|
|
1123
|
-
if (trimmed.startsWith("NONCE ")) {
|
|
1124
|
-
const nonce = trimmed.slice("NONCE ".length).trim();
|
|
1125
|
-
return { kind: "nonce", nonceB64Url: nonce };
|
|
1126
|
-
}
|
|
1127
|
-
if (trimmed.startsWith("[AUTH] ACCEPT ")) {
|
|
1128
|
-
return { kind: "accept", command: trimmed.slice("[AUTH] ACCEPT ".length).trim() };
|
|
1129
|
-
}
|
|
1130
|
-
if (trimmed.startsWith("[AUTH] REJECT ")) {
|
|
1131
|
-
const rest = trimmed.slice("[AUTH] REJECT ".length).trim();
|
|
1132
|
-
const [reason, ...verbParts] = rest.split(/\s+/);
|
|
1133
|
-
const verbHint = verbParts.length > 0 ? verbParts.join(" ") : void 0;
|
|
1134
|
-
return { kind: "reject", reason: reason ?? "", verbHint };
|
|
1135
|
-
}
|
|
1136
|
-
return { kind: "passthrough", raw: trimmed };
|
|
1137
|
-
}
|
|
1138
|
-
|
|
1139
1176
|
// src/transport/ble.ts
|
|
1140
1177
|
var RELAI_UART_SERVICE = "0000ff00-0000-1000-8000-00805f9b34fb";
|
|
1141
1178
|
var RELAI_RX_CHAR = "0000ff02-0000-1000-8000-00805f9b34fb";
|
|
@@ -1223,6 +1260,19 @@ var BleTransport = class {
|
|
|
1223
1260
|
* one would leave a live CoreBluetooth connection behind it.
|
|
1224
1261
|
*/
|
|
1225
1262
|
async connect(parentBleId) {
|
|
1263
|
+
const held = this.devices.get(parentBleId);
|
|
1264
|
+
if (held) {
|
|
1265
|
+
const state = this.notify.get(parentBleId);
|
|
1266
|
+
if (state) {
|
|
1267
|
+
try {
|
|
1268
|
+
state.remove();
|
|
1269
|
+
} catch {
|
|
1270
|
+
}
|
|
1271
|
+
this.notify.delete(parentBleId);
|
|
1272
|
+
}
|
|
1273
|
+
this.devices.delete(parentBleId);
|
|
1274
|
+
await held.cancelConnection().catch(() => void 0);
|
|
1275
|
+
}
|
|
1226
1276
|
let device = await this.manager.connectToDevice(parentBleId, { timeout: this.connectTimeoutMs });
|
|
1227
1277
|
try {
|
|
1228
1278
|
if (this.manager.discoverAllServicesAndCharacteristicsForDevice) {
|
|
@@ -1288,6 +1338,9 @@ var BleTransport = class {
|
|
|
1288
1338
|
async requestNonce(session) {
|
|
1289
1339
|
const line = await this.writeAndAwait(session, utf8ToBase64("CHALLENGE"));
|
|
1290
1340
|
const parsed = parseNotifyLine(line);
|
|
1341
|
+
if (parsed.kind === "reject") {
|
|
1342
|
+
throw new RelaiUnlockRejected(parsed.reason, parsed.verbHint);
|
|
1343
|
+
}
|
|
1291
1344
|
if (parsed.kind !== "nonce") {
|
|
1292
1345
|
throw new RelaiTransportError(`Expected NONCE from Parent, got: ${line}`);
|
|
1293
1346
|
}
|
|
@@ -1411,4 +1464,4 @@ var Intents = {
|
|
|
1411
1464
|
MakeAvailable: "make_available"
|
|
1412
1465
|
};
|
|
1413
1466
|
|
|
1414
|
-
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 };
|
|
1467
|
+
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.
|
|
3
|
+
"version": "0.21.1",
|
|
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",
|