@relai-team/access-sdk 0.8.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.
@@ -0,0 +1,943 @@
1
+ interface HttpConfig {
2
+ baseUrl: string;
3
+ publishableKey?: string | undefined;
4
+ secretKey?: string | undefined;
5
+ /** Returns the current end-user bearer, if any. */
6
+ getBearer?: () => string | undefined;
7
+ /** Invoked once on `token_expired`; returns true if a refresh succeeded. */
8
+ onTokenExpired?: () => Promise<boolean>;
9
+ fetchImpl?: typeof fetch;
10
+ maxRetries?: number;
11
+ }
12
+ interface RequestOptions {
13
+ method?: "GET" | "POST" | "DELETE";
14
+ path: string;
15
+ body?: unknown;
16
+ /** Sent as `Idempotency-Key`; auto-generated for writes when omitted. */
17
+ idempotencyKey?: string;
18
+ query?: Record<string, string | number | boolean | undefined>;
19
+ /** Skip the end-user bearer (endpoints authed by key alone). */
20
+ noBearer?: boolean;
21
+ }
22
+ declare class HttpClient {
23
+ private readonly cfg;
24
+ private readonly fetchImpl;
25
+ constructor(cfg: HttpConfig);
26
+ request<T>(opts: RequestOptions): Promise<T>;
27
+ private attempt;
28
+ private buildUrl;
29
+ private headers;
30
+ private parseJson;
31
+ private toApiError;
32
+ }
33
+
34
+ /**
35
+ * Wire types: the exact JSON shapes the Relai Access platform emits
36
+ * (mirrors the serializers in RELAI_ACCESS_WEB/lib/api/serialize.ts). Snake_case
37
+ * on the wire; the SDK surfaces these directly to stay unambiguous against the
38
+ * contract. Never widen or invent fields here: this file tracks the platform.
39
+ */
40
+ type ApiEnvironment = "sandbox" | "production";
41
+ /** An open specifies its effect on a node. Server-enforced. */
42
+ type Intent = "occupy" | "occupy_long_term" | "make_available";
43
+ declare const Intents: {
44
+ readonly Occupy: "occupy";
45
+ readonly OccupyLongTerm: "occupy_long_term";
46
+ readonly MakeAvailable: "make_available";
47
+ };
48
+ /**
49
+ * How a grant's `token` is authorized:
50
+ * - `relai-hmac-sha256-16-v1`: authenticated tower. `token` is null on the open
51
+ * response; the SDK must mint it against a Parent-issued nonce (server-owns-trust).
52
+ * - `relai-plain-v1`: legacy tower. `token` is present on the open response and
53
+ * written verbatim (no mint round-trip).
54
+ */
55
+ type GrantAlgorithm = "relai-hmac-sha256-16-v1" | "relai-plain-v1";
56
+ interface OrderStatusFields {
57
+ status: "open" | "completed" | "cancelled" | "refunded";
58
+ payment_status: "authorized" | "captured" | "failed";
59
+ }
60
+ /**
61
+ * Who may pick up an order (per-app setting, snapshotted onto each order):
62
+ * `self` = the dropper alone (re-opens allowed); `directed` = one named
63
+ * recipient; `open` = whoever redeems the drop-off's single-use access link.
64
+ */
65
+ type HandoffMode = "self" | "directed" | "open";
66
+ /** Self-mode billing style: pick-up window (late fees) or pay-as-you-go (long-term fee). */
67
+ type SelfBillingChoice = "pickup_window" | "pay_as_you_go";
68
+ interface Order extends OrderStatusFields {
69
+ id: string;
70
+ app_id: string;
71
+ ez_id: string;
72
+ token_count: number;
73
+ current_node_id: string | null;
74
+ long_term: boolean;
75
+ initiator_user_id: string | null;
76
+ recipient_user_id: string | null;
77
+ handoff_mode: HandoffMode;
78
+ billing_choice: SelfBillingChoice | null;
79
+ /**
80
+ * IANA timezone snapshot of the Exchange Zone at order creation. Present
81
+ * this order's timestamps in it (e.g. the pick-up window deadline).
82
+ */
83
+ timezone: string;
84
+ /** Promotion redeemed at creation, or null. `discount_cents` comes off the end-user open price. */
85
+ promotion: {
86
+ code: string;
87
+ discount_cents: number;
88
+ } | null;
89
+ /** Relai checkout state, or null before any charge or card save. */
90
+ checkout: {
91
+ drop_off_paid: boolean;
92
+ drop_off_charged_cents: number;
93
+ pickup_paid: boolean;
94
+ pickup_charged_cents: number;
95
+ } | null;
96
+ /** When the pick-up window closes; late fees escalate past it. Null = no window. */
97
+ pickup_window_expires_at: string | null;
98
+ /** The currently assessed late pick-up fee (flat step: $5 / $15 / $30). */
99
+ late_fee_cents: number;
100
+ late_fee_settled: boolean;
101
+ /** True once the order was abandoned (>24h past its window; node out of service). */
102
+ abandoned: boolean;
103
+ metadata?: Record<string, string>;
104
+ created_at: string;
105
+ completed_at: string | null;
106
+ }
107
+ /** Minimal confirm-identity returned by recipient lookup (directed handoff). */
108
+ interface RecipientMatch {
109
+ user_id: string;
110
+ first_name: string | null;
111
+ access_tag: string | null;
112
+ masked_email: string;
113
+ }
114
+ /** The pick-up target an OPEN-mode access link resolves to. */
115
+ interface AccessLinkTarget {
116
+ order_id: string;
117
+ ez_id: string;
118
+ node_id: string;
119
+ expires_at: string;
120
+ pickup_window_expires_at: string | null;
121
+ late_fee_cents: number;
122
+ }
123
+ /** A single-use override access link (bypasses every paywall). */
124
+ interface OverrideLink {
125
+ id: string;
126
+ code: string;
127
+ node_id: string;
128
+ ez_id: string | null;
129
+ expires_at: string | null;
130
+ /** 0 within the monthly free tier; 100 ($1.00) once past it. */
131
+ billed_cents: number;
132
+ free_per_month: number;
133
+ }
134
+ /** The unlock grant carried on an Open (or returned by mint). */
135
+ interface UnlockGrant {
136
+ grant_id: string;
137
+ order_id: string;
138
+ node_id: string;
139
+ tower_id: string | null;
140
+ /** The order's Exchange Zone: used for telemetry attribution. */
141
+ ez_id: string;
142
+ /** The tower's Parent BLE identity: used to auto-select the scanned Parent. */
143
+ parent_ble_id: string | null;
144
+ /** Opaque payload written verbatim to the Parent. Null until minted (hmac). */
145
+ token: string | null;
146
+ jti: string;
147
+ algorithm: GrantAlgorithm;
148
+ expires_at: string;
149
+ }
150
+ interface Open {
151
+ id: string;
152
+ order_id: string;
153
+ node_id: string;
154
+ tower_id: string | null;
155
+ intent: Intent;
156
+ ends_order: boolean;
157
+ grant: UnlockGrant;
158
+ /** OPEN-mode drop-off only: the single-use pick-up link the dropper shares. */
159
+ access_link?: {
160
+ code: string;
161
+ expires_at: string;
162
+ };
163
+ created_at: string;
164
+ }
165
+ /** Response of POST /grants/:id/mint, the authenticated token for one nonce. */
166
+ interface MintedCommand {
167
+ grant_id: string;
168
+ order_id: string;
169
+ node_id: string;
170
+ tower_id: string | null;
171
+ ez_id: string;
172
+ parent_ble_id: string | null;
173
+ token: string;
174
+ algorithm: GrantAlgorithm;
175
+ key_version: number;
176
+ expires_at: string;
177
+ }
178
+ interface ExchangeZone {
179
+ id: string;
180
+ name: string;
181
+ status: "active" | "maintenance";
182
+ address: string | null;
183
+ lat: number | null;
184
+ lng: number | null;
185
+ distance_m: number | null;
186
+ nodes_available: number;
187
+ /** Catalog name for the kind of place (Storefront, Restaurant, ...), or null. */
188
+ location_type: string | null;
189
+ /** Where the hardware sits relative to the building. */
190
+ placement: "inside" | "outside" | "both" | "na";
191
+ /** IANA timezone of the location, for presenting local times. */
192
+ timezone: string;
193
+ is_simulated: boolean;
194
+ }
195
+ interface TowerNode {
196
+ id: string;
197
+ tower_id: string;
198
+ label: string;
199
+ size: string;
200
+ status: "available" | "occupied" | "out_of_service";
201
+ }
202
+ interface Tower {
203
+ id: string;
204
+ ez_id: string;
205
+ label: string;
206
+ status: "active" | "maintenance";
207
+ firmware_version: string | null;
208
+ battery_pct: number;
209
+ parent_ble_id: string | null;
210
+ nodes: TowerNode[];
211
+ }
212
+ interface ExchangeZoneDetail extends ExchangeZone {
213
+ towers: Tower[];
214
+ /**
215
+ * Relai-checkout apps only: the resolved end-user prices for YOUR app at
216
+ * this Exchange Zone (per-EZ overrides applied), with sheet totals that
217
+ * include the Platform Fee and Processing lines. Show these at checkout.
218
+ */
219
+ end_user_pricing?: {
220
+ currency: "usd";
221
+ prepaid_cents: number;
222
+ prepaid_total_cents: number;
223
+ payg_base_cents: number;
224
+ payg_base_total_cents: number;
225
+ payg_hourly_cents: number;
226
+ };
227
+ }
228
+ interface TokenPair {
229
+ access_token: string;
230
+ refresh_token: string;
231
+ token_type: "Bearer";
232
+ expires_in: number;
233
+ }
234
+ type TelemetryAction = "unlock_issued" | "unlock_used" | "unlock_failed" | "door_open" | "door_close";
235
+ interface TelemetryEvent {
236
+ action: TelemetryAction;
237
+ result: "success" | "failure";
238
+ transport?: "ble" | "simulated";
239
+ at: string;
240
+ }
241
+
242
+ /**
243
+ * End-user auth: the OTP flow, rotating refresh (single-flight), and a pluggable
244
+ * token store. `MemoryTokenStorage` is the default; a React Native package would
245
+ * provide a Keychain/Keystore-backed store. The SDK attaches the access token as
246
+ * a Bearer on end-user calls and refreshes once, transparently, on expiry.
247
+ */
248
+
249
+ interface TokenStorage {
250
+ get(): TokenPair | null;
251
+ set(tokens: TokenPair): void;
252
+ clear(): void;
253
+ }
254
+ declare class MemoryTokenStorage implements TokenStorage {
255
+ private tokens;
256
+ get(): TokenPair | null;
257
+ set(tokens: TokenPair): void;
258
+ clear(): void;
259
+ }
260
+ declare class AuthModule {
261
+ private readonly http;
262
+ private readonly storage;
263
+ private refreshInFlight;
264
+ constructor(http: HttpClient, storage: TokenStorage);
265
+ /** Current access token, if signed in. */
266
+ get accessToken(): string | undefined;
267
+ get isSignedIn(): boolean;
268
+ /** Start the OTP flow: the platform emails a 6-digit code. */
269
+ startOtp(email: string): Promise<void>;
270
+ /** Verify the code, receive and store the token pair. */
271
+ verifyOtp(email: string, code: string): Promise<TokenPair>;
272
+ /** Rotate the token pair. Single-flight: concurrent callers share one refresh. */
273
+ refresh(): Promise<boolean>;
274
+ private doRefresh;
275
+ /** Revoke the refresh token and clear local state. */
276
+ signOut(): Promise<void>;
277
+ }
278
+
279
+ /**
280
+ * Resource modules: thin typed wrappers over the platform's HTTP surface. Each
281
+ * maps 1:1 to a route in RELAI_ACCESS_WEB. No local business logic; the platform
282
+ * is the authority (server-owns-trust).
283
+ */
284
+
285
+ declare class ExchangeZonesModule {
286
+ private readonly http;
287
+ constructor(http: HttpClient);
288
+ /** Nearby Exchange Zones, closest first. */
289
+ near(input: {
290
+ lat: number;
291
+ lng: number;
292
+ radiusM?: number;
293
+ /** Only zones with at least this many compartments. */
294
+ minNodes?: number;
295
+ /** Only zones with at most this many compartments. */
296
+ maxNodes?: number;
297
+ }): Promise<ExchangeZone[]>;
298
+ list(input?: {
299
+ minNodes?: number;
300
+ maxNodes?: number;
301
+ }): Promise<ExchangeZone[]>;
302
+ /** Full detail: towers → nodes (includes each tower's parent_ble_id). */
303
+ get(exchangeZoneId: string): Promise<ExchangeZoneDetail>;
304
+ }
305
+ declare class OrdersModule {
306
+ private readonly http;
307
+ constructor(http: HttpClient);
308
+ /**
309
+ * Create an order. On DIRECTED-handoff apps, name the pick-up recipient by
310
+ * `recipient` (exact email or `@access-tag`) or by `recipientUserId` (from
311
+ * `client.recipients.lookup`).
312
+ */
313
+ create(input: {
314
+ exchangeZoneId: string;
315
+ /** Pick one of the app's ENABLED handoff modes for this order. Omitted:
316
+ * a named recipient implies directed, else the app's default mode. */
317
+ handoffMode?: "self" | "directed" | "open";
318
+ /** Directed handoff: exact email or `@access-tag`. */
319
+ recipient?: string;
320
+ /** Directed handoff: the confirmed user id from recipients.lookup. */
321
+ recipientUserId?: string;
322
+ recipientEmail?: string;
323
+ /**
324
+ * Relai-issued promotion code. Redeemed at creation; the response's
325
+ * `promotion.discount_cents` comes off the end-user open price. Invalid,
326
+ * expired, or exhausted codes fail with `invalid_request` whose message
327
+ * is written for the person who typed the code.
328
+ */
329
+ promotionCode?: string;
330
+ metadata?: Record<string, string>;
331
+ }): Promise<Order>;
332
+ get(orderId: string): Promise<Order>;
333
+ /**
334
+ * Request an open: one token + an unlock grant. On authenticated towers the
335
+ * grant's `token` is null; deliver it via `client.unlock(...)`, which mints it
336
+ * against a Parent nonce. Prefer `client.unlock` over calling this directly.
337
+ *
338
+ * An OPEN-mode pick-up passes `accessLink` (the sender's single-use code); an
339
+ * override passes `overrideCode`. A `late_fee_due` (402) response means a late
340
+ * pick-up fee gates the open: see `RelaiLateFeeDue`.
341
+ */
342
+ open(orderId: string, input: {
343
+ intent: Intent;
344
+ size?: string;
345
+ nodeId?: string;
346
+ accessLink?: string;
347
+ overrideCode?: string;
348
+ }): Promise<Open>;
349
+ cancel(orderId: string): Promise<Order>;
350
+ }
351
+ declare class GrantsModule {
352
+ private readonly http;
353
+ constructor(http: HttpClient);
354
+ /**
355
+ * Redeem a Parent-issued nonce for the authenticated command token
356
+ * (challenge–response). Called by `client.unlock`; public for advanced flows.
357
+ */
358
+ mint(grantId: string, nonceB64Url: string): Promise<MintedCommand>;
359
+ }
360
+ declare class RecipientsModule {
361
+ private readonly http;
362
+ constructor(http: HttpClient);
363
+ /**
364
+ * Resolve a directed-handoff recipient by EXACT email or `@access-tag` (no
365
+ * fuzzy search, no browse). Returns a minimal identity to confirm before
366
+ * creating the order. Requires a signed-in end-user.
367
+ */
368
+ lookup(query: string): Promise<RecipientMatch>;
369
+ }
370
+ declare class AccessLinksModule {
371
+ private readonly http;
372
+ constructor(http: HttpClient);
373
+ /**
374
+ * Resolve an OPEN-mode access link code (`relai.access.…`) to its pick-up
375
+ * target. Does not burn the link; redemption happens on the open itself
376
+ * (pass the code as `accessLink`).
377
+ */
378
+ resolve(code: string): Promise<AccessLinkTarget>;
379
+ }
380
+ declare class OverrideLinksModule {
381
+ private readonly http;
382
+ constructor(http: HttpClient);
383
+ /**
384
+ * Request a single-use override link for a node (SERVER ONLY: secret key).
385
+ * Auto-granted; the first 10 per organization per calendar month are free,
386
+ * then $1.00 each on the next invoice. Redeem via `overrideCode` on an open.
387
+ */
388
+ request(input: {
389
+ nodeId: string;
390
+ expiresInHours?: number;
391
+ }): Promise<OverrideLink>;
392
+ }
393
+ declare class TelemetryModule {
394
+ private readonly http;
395
+ constructor(http: HttpClient);
396
+ send(input: {
397
+ exchangeZoneId: string;
398
+ grantId?: string;
399
+ events: TelemetryEvent[];
400
+ batteryPct?: number;
401
+ firmware?: string;
402
+ }): Promise<{
403
+ ok?: boolean;
404
+ } & Record<string, unknown>>;
405
+ }
406
+
407
+ /**
408
+ * Telemetry queue-and-retry (owner rule 2026-07-23). A delivered-but-unreported
409
+ * open must not be lost to a flaky network: telemetry that fails to POST is
410
+ * queued and retried on the next flush. The mint round-trip itself is already
411
+ * retried by the HTTP layer (network/5xx), so only telemetry needs this.
412
+ *
413
+ * `MemoryTelemetryQueue` is the default; a React Native app can supply a
414
+ * persistent implementation (e.g. AsyncStorage) so the queue survives restarts.
415
+ */
416
+ interface TelemetryPayload {
417
+ exchangeZoneId: string;
418
+ grantId?: string;
419
+ events: TelemetryEvent[];
420
+ batteryPct?: number;
421
+ firmware?: string;
422
+ }
423
+ interface QueuedTelemetry {
424
+ id: string;
425
+ payload: TelemetryPayload;
426
+ attempts: number;
427
+ }
428
+ interface TelemetryQueue {
429
+ enqueue(payload: TelemetryPayload): Promise<void>;
430
+ list(): Promise<QueuedTelemetry[]>;
431
+ remove(id: string): Promise<void>;
432
+ markAttempt(id: string): Promise<void>;
433
+ }
434
+ declare class MemoryTelemetryQueue implements TelemetryQueue {
435
+ private items;
436
+ private seq;
437
+ enqueue(payload: TelemetryPayload): Promise<void>;
438
+ list(): Promise<QueuedTelemetry[]>;
439
+ remove(id: string): Promise<void>;
440
+ markAttempt(id: string): Promise<void>;
441
+ }
442
+
443
+ /**
444
+ * Sends telemetry with queue-and-retry. `submit` flushes any backlog then sends;
445
+ * on failure the payload is queued for the next flush, so opens are never lost to
446
+ * a transient network error. Call `flush()` opportunistically (e.g. on app
447
+ * foreground) to drain the backlog.
448
+ */
449
+ declare class TelemetryUploader {
450
+ private readonly telemetry;
451
+ private readonly queue;
452
+ constructor(telemetry: TelemetryModule, queue?: TelemetryQueue);
453
+ /** Send a payload; on failure, queue it for retry. Best-effort, never throws. */
454
+ submit(payload: TelemetryPayload): Promise<void>;
455
+ /**
456
+ * Retry queued telemetry. A permanently-rejected item (4xx) or one that has
457
+ * exhausted its attempts is dropped so it can't wedge the backlog behind it;
458
+ * a transient failure (network / 5xx / 429) stops the drain, leaving the rest
459
+ * queued for the next flush.
460
+ */
461
+ flush(): Promise<{
462
+ sent: number;
463
+ remaining: number;
464
+ }>;
465
+ }
466
+
467
+ /**
468
+ * The outcome of writing one authenticated command to a Parent, distilled from
469
+ * the notify surface. `accepted` is the ONLY control-flow signal; `verbHint` is
470
+ * attacker-controlled correlation data (see notify.ts) and never gates logic.
471
+ */
472
+ interface CommandAck {
473
+ accepted: boolean;
474
+ /** Echoed command on accept (`[AUTH] ACCEPT <command>`). */
475
+ command: string | undefined;
476
+ /** Reject reason on failure (`[AUTH] REJECT <reason>`). */
477
+ rejectReason: string | undefined;
478
+ /** Correlation hint only: untrusted echoed verb. */
479
+ verbHint: string | undefined;
480
+ }
481
+
482
+ /**
483
+ * The transport seam: the ONLY place that touches a Parent. Every transport is
484
+ * a DUMB PIPE: it relays opaque bytes and reads the notify surface. It holds no
485
+ * command vocabulary and no keys (server-owns-trust). `BleTransport` (react-
486
+ * native-ble-plx) and `SimulatedTransport` implement the same interface; nothing
487
+ * above this layer knows which is in use.
488
+ *
489
+ * The open sequence lives in the orchestrator (src/unlock.ts): connect →
490
+ * requestNonce → (platform mint) → sendCommand → parse ack. The transport never
491
+ * calls the platform: it only does BLE I/O.
492
+ */
493
+
494
+ /** A Parent discovered over BLE (or via sandbox lookup). */
495
+ interface DiscoveredParent {
496
+ /** The Parent's BLE identity (bt_mac on Android; canonical from PROVISION). */
497
+ parentBleId: string;
498
+ /** The tower this Parent controls, when known from discovery context. */
499
+ towerId?: string;
500
+ rssi?: number;
501
+ isSimulated: boolean;
502
+ }
503
+ /** An open connection to one Parent. Opaque above the transport. */
504
+ interface Session {
505
+ id: string;
506
+ parentBleId: string;
507
+ connectedAt: string;
508
+ }
509
+ interface TowerTelemetry {
510
+ batteryPct?: number;
511
+ firmware?: string;
512
+ doorOpen?: boolean;
513
+ }
514
+ interface ParentTransport {
515
+ /** Discover reachable Parents (BLE adverts / sandbox lookup). */
516
+ scan(): Promise<DiscoveredParent[]>;
517
+ /** Connect to a specific Parent. MTU is negotiated ≥110 here (BLE). */
518
+ connect(parentBleId: string): Promise<Session>;
519
+ /**
520
+ * Challenge–response: write base64("CHALLENGE"), read the Parent's single-use
521
+ * nonce off the notify channel. Returns the base64url nonce.
522
+ */
523
+ requestNonce(session: Session): Promise<string>;
524
+ /**
525
+ * Write the opaque minted `token` verbatim (Write-With-Response) and read the
526
+ * Parent's `[AUTH] ACCEPT|REJECT` ack. One command in flight at a time.
527
+ */
528
+ sendCommand(session: Session, token: string): Promise<CommandAck>;
529
+ /** Read tower health/state, when the transport supports it. */
530
+ readTelemetry(session: Session): Promise<TowerTelemetry>;
531
+ /** Tear down the connection. */
532
+ disconnect(session: Session): Promise<void>;
533
+ }
534
+
535
+ interface UnlockDeps {
536
+ grants: GrantsModule;
537
+ telemetry: TelemetryUploader;
538
+ }
539
+ interface UnlockResult {
540
+ open: Open;
541
+ accepted: boolean;
542
+ /** Echoed command on accept (e.g. "OPEN 3:0"). */
543
+ command: string | undefined;
544
+ keyVersion: number | undefined;
545
+ session: Session;
546
+ }
547
+ interface DeliverOptions {
548
+ transport: ParentTransport;
549
+ /**
550
+ * The Parent to talk to. Defaults to the grant's `parent_ble_id` (the
551
+ * platform names the tower's Parent on every grant); pass explicitly only to
552
+ * override: e.g. a custom discovery flow.
553
+ */
554
+ parentBleId?: string;
555
+ /** Telemetry attribution override; defaults to the grant's `ez_id`. */
556
+ exchangeZoneId?: string;
557
+ /** Keep the BLE session open after the unlock (default: disconnect). */
558
+ keepConnected?: boolean;
559
+ }
560
+ /**
561
+ * Deliver an already-issued Open to a Parent. Splits out so callers who created
562
+ * the Open server-side (secret key) can still drive the physical unlock.
563
+ */
564
+ declare function deliverOpen(deps: UnlockDeps, open: Open, opts: DeliverOptions): Promise<UnlockResult>;
565
+
566
+ interface RelaiClientOptions {
567
+ /** Publishable key (pk_…): safe in client apps. */
568
+ publishableKey?: string;
569
+ /** Secret key (sk_…): SERVER ONLY. Never ship in a mobile/client app. */
570
+ secretKey?: string;
571
+ /** API base. Defaults to the hosted platform. */
572
+ baseUrl?: string;
573
+ /** Token store for the end-user session (default: in-memory). */
574
+ tokenStorage?: TokenStorage;
575
+ /** Override fetch (tests, custom runtimes). */
576
+ fetchImpl?: typeof fetch;
577
+ maxRetries?: number;
578
+ /** Persistent telemetry queue (default: in-memory). RN apps can back it with storage. */
579
+ telemetryQueue?: TelemetryQueue;
580
+ }
581
+ interface UnlockInput {
582
+ orderId: string;
583
+ intent: Intent;
584
+ transport: ParentTransport;
585
+ /**
586
+ * Override the Parent to talk to. Normally omitted: the grant names the
587
+ * tower's Parent (`parent_ble_id`) and the SDK selects it automatically.
588
+ */
589
+ parentBleId?: string;
590
+ /** Telemetry attribution override; defaults to the grant's ez_id. */
591
+ exchangeZoneId?: string;
592
+ size?: string;
593
+ nodeId?: string;
594
+ /** OPEN-mode pick-up: the sender's single-use access link code. */
595
+ accessLink?: string;
596
+ /**
597
+ * Relai checkout: set false to handle 402 payment_required yourself instead
598
+ * of the SDK auto-presenting the standard Stripe Payment Sheet.
599
+ */
600
+ presentPaymentSheet?: boolean;
601
+ /** Admin/partner override link code: bypasses handoff + paywall gates. */
602
+ overrideCode?: string;
603
+ keepConnected?: boolean;
604
+ }
605
+ declare class RelaiClient {
606
+ readonly auth: AuthModule;
607
+ readonly exchangeZones: ExchangeZonesModule;
608
+ readonly orders: OrdersModule;
609
+ readonly grants: GrantsModule;
610
+ readonly recipients: RecipientsModule;
611
+ readonly accessLinks: AccessLinksModule;
612
+ /** SERVER ONLY (secret key): request paywall-bypassing override links. */
613
+ readonly overrideLinks: OverrideLinksModule;
614
+ readonly telemetry: TelemetryModule;
615
+ /** Queue-and-retry telemetry uploader (used by unlock; flush opportunistically). */
616
+ readonly telemetryUploader: TelemetryUploader;
617
+ private readonly http;
618
+ constructor(options: RelaiClientOptions);
619
+ /** Drain any telemetry queued after a failed send (e.g. on app foreground). */
620
+ flushTelemetry(): Promise<{
621
+ sent: number;
622
+ remaining: number;
623
+ }>;
624
+ /**
625
+ * Open a node: request the grant, then drive the physical unlock over the
626
+ * given transport (challenge → mint → write → ack). Throws
627
+ * `RelaiUnlockRejected` if the Parent refuses the command.
628
+ */
629
+ unlock(input: UnlockInput): Promise<UnlockResult>;
630
+ }
631
+
632
+ /**
633
+ * Relai checkout payment sheet (owner spec, 2026-08-02). When an open is
634
+ * gated on payment the API answers 402 `payment_required` with everything
635
+ * Stripe's standard Payment Sheet needs; this module presents that sheet with
636
+ * ZERO app code, provided the optional peer `@stripe/stripe-react-native` is
637
+ * installed. Apps that want their own payment UI simply do not install it (or
638
+ * pass `presentPaymentSheet: false` to `unlock`) and handle the error's
639
+ * `details` themselves.
640
+ */
641
+ interface PaymentRequiredDetails {
642
+ kind: "prepaid" | "payg_base" | "payg_setup" | "payg_pickup";
643
+ client_secret: string | null;
644
+ /** True when this is a card SAVE (PAYG with a zero base), not a charge. */
645
+ setup: boolean;
646
+ publishable_key: string | null;
647
+ customer_id?: string;
648
+ ephemeral_key?: string;
649
+ statement_suffix?: string | null;
650
+ breakdown: {
651
+ price_cents: number;
652
+ item_cents: number;
653
+ platform_fee_cents: number;
654
+ processing_cents: number;
655
+ total_cents: number;
656
+ };
657
+ }
658
+ /** Narrow an error's `details` into the payment-sheet shape, if it is one. */
659
+ declare function asPaymentRequired(details: Record<string, unknown> | undefined): PaymentRequiredDetails | null;
660
+ /**
661
+ * Present the standard Stripe Payment Sheet for a gate. Returns true when the
662
+ * payment (or card save) completed and the open should be retried; false when
663
+ * the sheet is unavailable (peer not installed / no key) or was canceled.
664
+ */
665
+ declare function presentRelaiPaymentSheet(details: PaymentRequiredDetails): Promise<boolean>;
666
+
667
+ /**
668
+ * Persistent telemetry queue (owner, 2026-07-24). `MemoryTelemetryQueue` loses
669
+ * anything queued when the app is killed; a React Native app that opens nodes
670
+ * offline needs its unreported opens to survive a restart. This backs the same
671
+ * `TelemetryQueue` interface with a key-value store.
672
+ *
673
+ * The store is AsyncStorage-shaped on purpose, so RN apps pass the library in
674
+ * directly (it is an OPTIONAL dependency: the SDK core never imports it):
675
+ *
676
+ * import AsyncStorage from "@react-native-async-storage/async-storage";
677
+ * const client = new RelaiClient({
678
+ * publishableKey,
679
+ * telemetryQueue: new StorageTelemetryQueue(AsyncStorage),
680
+ * });
681
+ *
682
+ * The whole queue is one JSON blob under a single key: telemetry volume is one
683
+ * item per open, so this stays small; writes are serialized through an internal
684
+ * lock so concurrent submit/flush calls can't clobber each other.
685
+ */
686
+
687
+ /** The subset of AsyncStorage (and localStorage-async wrappers) we need. */
688
+ interface KeyValueStorage {
689
+ getItem(key: string): Promise<string | null>;
690
+ setItem(key: string, value: string): Promise<void>;
691
+ removeItem(key: string): Promise<void>;
692
+ }
693
+ interface StorageTelemetryQueueOptions {
694
+ /** Storage key for the serialized queue. Default `@relai/telemetry-queue`. */
695
+ storageKey?: string;
696
+ /**
697
+ * Hard cap on queued items; when exceeded the OLDEST are dropped so a long
698
+ * outage can't grow storage without bound. Default 500.
699
+ */
700
+ maxItems?: number;
701
+ }
702
+ declare class StorageTelemetryQueue implements TelemetryQueue {
703
+ private readonly storage;
704
+ private readonly key;
705
+ private readonly maxItems;
706
+ /** Serializes read-modify-write so concurrent calls don't lose updates. */
707
+ private chain;
708
+ private seq;
709
+ constructor(storage: KeyValueStorage, opts?: StorageTelemetryQueueOptions);
710
+ enqueue(payload: TelemetryPayload): Promise<void>;
711
+ list(): Promise<QueuedTelemetry[]>;
712
+ remove(id: string): Promise<void>;
713
+ markAttempt(id: string): Promise<void>;
714
+ private nextId;
715
+ /** Serialize an operation after any in-flight ones (a simple promise lock). */
716
+ private run;
717
+ private mutate;
718
+ private read;
719
+ }
720
+
721
+ /**
722
+ * SimulatedTransport: lets an app exercise the full open flow with no hardware.
723
+ * It emulates the Parent's notify surface: issues a random nonce on CHALLENGE,
724
+ * and ACCEPTs a well-formed token (echoing the command it decodes from the
725
+ * opaque wire message, exactly as a real Parent would). It performs NO crypto:
726
+ * real verification is the firmware's job, so it never fabricates a security
727
+ * property; it only mirrors the wire choreography. Reject behavior is injectable
728
+ * for testing error paths.
729
+ */
730
+
731
+ interface SimulatedParentConfig {
732
+ parentBleId: string;
733
+ towerId?: string;
734
+ /** Force the next N sendCommand calls to reject with this reason. */
735
+ rejectWith?: string;
736
+ }
737
+ declare class SimulatedTransport implements ParentTransport {
738
+ private readonly parents;
739
+ private rejectQueue;
740
+ constructor(parents?: SimulatedParentConfig[]);
741
+ scan(): Promise<DiscoveredParent[]>;
742
+ connect(parentBleId: string): Promise<Session>;
743
+ requestNonce(_session: Session): Promise<string>;
744
+ sendCommand(session: Session, token: string): Promise<CommandAck>;
745
+ readTelemetry(_session: Session): Promise<TowerTelemetry>;
746
+ disconnect(_session: Session): Promise<void>;
747
+ }
748
+
749
+ interface SimAuthenticatedTransportOptions {
750
+ /** Publishable (pk_sandbox_…) key: the sim-Parent endpoints are sandbox-gated. */
751
+ publishableKey: string;
752
+ /** API base, e.g. "https://access.relai.us/api/v1". */
753
+ baseUrl?: string;
754
+ fetchImpl?: typeof fetch;
755
+ }
756
+ declare class SimAuthenticatedTransport implements ParentTransport {
757
+ private readonly publishableKey;
758
+ private readonly baseUrl;
759
+ private readonly fetchImpl;
760
+ constructor(opts: SimAuthenticatedTransportOptions);
761
+ scan(): Promise<DiscoveredParent[]>;
762
+ connect(parentBleId: string): Promise<Session>;
763
+ requestNonce(session: Session): Promise<string>;
764
+ sendCommand(session: Session, token: string): Promise<CommandAck>;
765
+ readTelemetry(_session: Session): Promise<TowerTelemetry>;
766
+ disconnect(_session: Session): Promise<void>;
767
+ private post;
768
+ }
769
+
770
+ declare const RELAI_UART_SERVICE = "0000ff00-0000-1000-8000-00805f9b34fb";
771
+ declare const RELAI_RX_CHAR = "0000ff02-0000-1000-8000-00805f9b34fb";
772
+ declare const RELAI_TX_CHAR = "0000ff03-0000-1000-8000-00805f9b34fb";
773
+ /** The subset of react-native-ble-plx this transport needs (structural typing). */
774
+ interface BleDeviceLike {
775
+ id: string;
776
+ requestMTU(mtu: number): Promise<BleDeviceLike>;
777
+ writeCharacteristicWithResponseForService(service: string, char: string, valueBase64: string): Promise<unknown>;
778
+ monitorCharacteristicForService(service: string, char: string, listener: (error: unknown, characteristic: {
779
+ value?: string | null;
780
+ } | null) => void): {
781
+ remove(): void;
782
+ };
783
+ cancelConnection(): Promise<unknown>;
784
+ }
785
+ interface BleManagerLike {
786
+ connectToDevice(id: string, options?: unknown): Promise<BleDeviceLike>;
787
+ discoverAllServicesAndCharacteristicsForDevice?(id: string): Promise<BleDeviceLike>;
788
+ }
789
+ interface BleTransportOptions {
790
+ manager: BleManagerLike;
791
+ /** Discovery is app-specific (scan is often driven by your own UI); optional. */
792
+ scan?: () => Promise<DiscoveredParent[]>;
793
+ notifyTimeoutMs?: number;
794
+ }
795
+ declare class BleTransport implements ParentTransport {
796
+ private readonly manager;
797
+ private readonly devices;
798
+ private readonly scanImpl;
799
+ private readonly notifyTimeoutMs;
800
+ constructor(opts: BleTransportOptions);
801
+ scan(): Promise<DiscoveredParent[]>;
802
+ connect(parentBleId: string): Promise<Session>;
803
+ requestNonce(session: Session): Promise<string>;
804
+ sendCommand(session: Session, token: string): Promise<CommandAck>;
805
+ readTelemetry(_session: Session): Promise<TowerTelemetry>;
806
+ disconnect(session: Session): Promise<void>;
807
+ /**
808
+ * Write one value and await the first notify line that matches `accept` (the
809
+ * default accepts the first non-passthrough line). Ordinary command output is
810
+ * skipped via the passthrough filter so we lock onto the structured line.
811
+ */
812
+ private writeAndAwait;
813
+ }
814
+
815
+ /**
816
+ * Parser for the Parent's FROZEN TX-notify surface (RELAI firmware, 2026-07-22).
817
+ * The public SDK only ever issues open-path commands, so it parses exactly three
818
+ * line kinds; commissioning lines (PROVISION, PROVISIONLOCK, ROTATE) are
819
+ * intentionally NOT handled here: they belong to the private technician
820
+ * tooling, never this package. Ordinary command output also arrives here, so
821
+ * unknown lines are returned as `passthrough` and ignored by the orchestrator.
822
+ *
823
+ * Frozen surface (single line each, plain text once base64-decoded off BLE):
824
+ * NONCE <b64url>
825
+ * [AUTH] ACCEPT <command> (emitted at verify time, before output)
826
+ * [AUTH] REJECT <reason> [verb] (verb echoed only on tagged-path rejects)
827
+ *
828
+ * SECURITY: on a REJECT the echoed verb is ATTACKER-CONTROLLED bytes reflected
829
+ * by the Parent. It is surfaced as `verbHint` for correlation/logging only and
830
+ * MUST NOT drive control flow.
831
+ */
832
+ type NotifyLine = {
833
+ kind: "nonce";
834
+ nonceB64Url: string;
835
+ } | {
836
+ kind: "accept";
837
+ command: string;
838
+ } | {
839
+ kind: "reject";
840
+ reason: string;
841
+ verbHint: string | undefined;
842
+ } | {
843
+ kind: "passthrough";
844
+ raw: string;
845
+ };
846
+ /** Reject reasons the firmware can emit (documentation/validation aid). */
847
+ declare const REJECT_REASONS: readonly ["B64", "UNTAGGED", "FORMAT", "KEYVERSION", "TAG", "NONCE", "LOCKED", "ROTATE"];
848
+ /** Parse one already-decoded (plain-text) notify line. */
849
+ declare function parseNotifyLine(line: string): NotifyLine;
850
+
851
+ /**
852
+ * Webhook verification for partner BACKENDS (Node 18+ / edge: WebCrypto).
853
+ * Pinned platform scheme (2026-07-23, Stripe-style):
854
+ *
855
+ * X-Relai-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<rawBody>")>
856
+ *
857
+ * Verify over the RAW request body (before any JSON parsing), constant-time
858
+ * compare, and reject stale timestamps (default tolerance 5 minutes).
859
+ */
860
+ interface VerifyWebhookInput {
861
+ /** The raw request body, exactly as received. */
862
+ payload: string;
863
+ /** The X-Relai-Signature header value. */
864
+ signature: string;
865
+ /** The app's webhook secret (from the Relai portal). */
866
+ secret: string;
867
+ /** Max allowed |now − t| in seconds (default 300). */
868
+ toleranceSeconds?: number;
869
+ /** Override "now" (tests). Unix seconds. */
870
+ nowSeconds?: number;
871
+ }
872
+ /** Returns true only for a well-formed, fresh, correctly-signed payload. */
873
+ declare function verifyWebhook(input: VerifyWebhookInput): Promise<boolean>;
874
+
875
+ /**
876
+ * Error model. The platform returns `{ error: { code, message, docs_url } }`
877
+ * with a stable enumerated `code`; `RelaiApiError` carries it through so callers
878
+ * can branch on `code` rather than parsing messages.
879
+ */
880
+ interface ApiErrorBody {
881
+ error: {
882
+ code: string;
883
+ message: string;
884
+ docs_url?: string;
885
+ details?: Record<string, unknown>;
886
+ };
887
+ }
888
+ declare class RelaiError extends Error {
889
+ readonly name: string;
890
+ constructor(message: string);
891
+ }
892
+ /** A structured error response from the platform. */
893
+ declare class RelaiApiError extends RelaiError {
894
+ readonly name = "RelaiApiError";
895
+ readonly code: string;
896
+ readonly status: number;
897
+ readonly docsUrl: string | undefined;
898
+ /** Machine-readable payload for codes that carry one (e.g. late_fee_due). */
899
+ readonly details: Record<string, unknown> | undefined;
900
+ constructor(status: number, body: ApiErrorBody);
901
+ }
902
+ /**
903
+ * `late_fee_due` (402): a late pick-up fee must be paid before the node opens.
904
+ * Thrown by the HTTP layer in place of the plain `RelaiApiError` (it IS one, so
905
+ * existing catch blocks keep working). `feeCents` is the flat-step amount;
906
+ * `clientSecret` is the Stripe PaymentIntent client secret when the picking-up
907
+ * end-user is the payer: collect the payment, then retry the open.
908
+ */
909
+ declare class RelaiLateFeeDue extends RelaiApiError {
910
+ readonly feeCents: number;
911
+ readonly clientSecret: string | null;
912
+ constructor(status: number, body: ApiErrorBody);
913
+ }
914
+ /**
915
+ * The "doorway" error: the SDK was called with no publishable key. Thrown
916
+ * locally (before any request) with actionable guidance, since it's the most
917
+ * common first-run mistake.
918
+ */
919
+ declare class RelaiMissingKeyError extends RelaiError {
920
+ readonly name = "RelaiMissingKeyError";
921
+ readonly code = "missing_publishable_key";
922
+ constructor();
923
+ }
924
+ /** A Parent rejected an authenticated command (parsed from `[AUTH] REJECT`). */
925
+ declare class RelaiUnlockRejected extends RelaiError {
926
+ readonly name = "RelaiUnlockRejected";
927
+ /** B64 | UNTAGGED | FORMAT | KEYVERSION | TAG | NONCE | LOCKED | ROTATE. */
928
+ readonly reason: string;
929
+ /**
930
+ * Correlation hint only: for tagged-path rejects the Parent echoes the
931
+ * claimed verb, which is ATTACKER-CONTROLLED bytes. Never trust it for
932
+ * control flow; use it only for logging/telemetry correlation.
933
+ */
934
+ readonly verbHint: string | undefined;
935
+ constructor(reason: string, verbHint?: string);
936
+ }
937
+ /** The BLE/transport layer failed (connect, write, timeout, no nonce, …). */
938
+ declare class RelaiTransportError extends RelaiError {
939
+ readonly name = "RelaiTransportError";
940
+ constructor(message: string);
941
+ }
942
+
943
+ export { type AccessLinkTarget, AccessLinksModule, type ApiEnvironment, type ApiErrorBody, AuthModule, type BleDeviceLike, type BleManagerLike, BleTransport, type BleTransportOptions, type CommandAck, type DeliverOptions, type DiscoveredParent, type ExchangeZone, type ExchangeZoneDetail, ExchangeZonesModule, type GrantAlgorithm, GrantsModule, type HandoffMode, type Intent, Intents, type KeyValueStorage, MemoryTelemetryQueue, MemoryTokenStorage, type MintedCommand, type NotifyLine, type Open, type Order, OrdersModule, type OverrideLink, OverrideLinksModule, type ParentTransport, type PaymentRequiredDetails, type QueuedTelemetry, REJECT_REASONS, RELAI_RX_CHAR, RELAI_TX_CHAR, RELAI_UART_SERVICE, type RecipientMatch, RecipientsModule, RelaiApiError, RelaiClient, type RelaiClientOptions, RelaiError, RelaiLateFeeDue, RelaiMissingKeyError, RelaiTransportError, RelaiUnlockRejected, type SelfBillingChoice, type Session, SimAuthenticatedTransport, type SimAuthenticatedTransportOptions, type SimulatedParentConfig, SimulatedTransport, StorageTelemetryQueue, type StorageTelemetryQueueOptions, 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, asPaymentRequired, deliverOpen, parseNotifyLine, presentRelaiPaymentSheet, verifyWebhook };