@relai-team/access-sdk 0.12.4 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -248,7 +248,7 @@ the whole exchange. A payment-gated open answers 402 `payment_required`, and
248
248
  by itself.
249
249
 
250
250
  Install the peer and hand the module to the client. **You import it, the SDK
251
- does not** — React Native resolves imports at build time, so a specifier
251
+ does not**. React Native resolves imports at build time, so a specifier
252
252
  written inside this package would force Stripe on every app, including the
253
253
  ones that want their own payment UI:
254
254
 
@@ -371,24 +371,114 @@ authenticated path and its reject cases. Sandbox keys only.
371
371
  ## Push notifications
372
372
 
373
373
  Register the end-user's device push token so drop-off / pick-up events notify
374
- them (delivery is enabled server-side per app):
374
+ them (delivery is enabled server-side per app). Requires a signed-in end user:
375
375
 
376
376
  ```ts
377
- await fetch(`${baseUrl}/push/tokens`, {
378
- method: "POST",
379
- headers: {
380
- // BOTH headers. The route authenticates the app with the API key first and
381
- // the person with the bearer second, so a bearer alone answers
382
- // 401 missing_publishable_key while your token is perfectly valid.
383
- "x-relai-key": publishableKey,
384
- authorization: `Bearer ${endUserAccessToken}`,
385
- "content-type": "application/json",
386
- },
387
- body: JSON.stringify({ token: expoPushToken, platform: "expo" }),
377
+ await relai.push.register(expoPushToken); // platform defaults to "expo"
378
+ await relai.push.unregister(expoPushToken); // on sign-out
379
+ ```
380
+
381
+ Safe to call on every launch: re-registering the same token updates it rather
382
+ than duplicating it. Unregister on sign-out, or the next person to use the
383
+ device gets their alerts.
384
+
385
+ This replaces the hand-rolled `fetch` this section used to show (0.13.0). That
386
+ snippet sent only a Bearer token, so it answered 401 `missing_publishable_key`
387
+ while the reader held a perfectly valid session: the route authenticates the app
388
+ with the API key FIRST and the person with the bearer second. `relai.push` sends
389
+ both, because the client already holds both.
390
+
391
+ ## Sandbox fault injection
392
+
393
+ Exercise the unhappy paths without hardware. Sandbox keys only; the platform
394
+ answers `forbidden` for a production key and `not_simulated` for an Exchange
395
+ Zone that is not simulated.
396
+
397
+ ```ts
398
+ await relai.sandbox.injectFault({
399
+ exchangeZoneId: "ez_123",
400
+ fault: "jammed_door",
401
+ nodeId: "cmp_456", // required for jammed_door
388
402
  });
389
- // DELETE the same route on sign-out.
403
+
404
+ await relai.sandbox.injectFault({ exchangeZoneId: "ez_123", fault: "dead_battery" });
405
+ await relai.sandbox.clearFault({ exchangeZoneId: "ez_123", nodeId: "cmp_456" });
390
406
  ```
391
407
 
408
+ Faults: `jammed_door`, `dead_battery`, `out_of_service`, and `clear`.
409
+
410
+ ## Knowing your own app
411
+
412
+ ```ts
413
+ const app = await relai.app.self();
414
+ app.plan; // { id, name } or null when unmetered
415
+ app.real_token_balance; // remaining REAL opens
416
+ app.sim_token_balance; // remaining SIMULATED opens (0.14.0)
417
+ ```
418
+
419
+ An open against a simulated Exchange Zone draws from `sim_token_balance`, not
420
+ the real one, and hitting zero raises `quota_exceeded` on the open exactly as it
421
+ does for real opens. A sandbox can dead-end mid-test, so check this before a
422
+ long test run, not after.
423
+
424
+ Null on either means "no active plan". It does NOT mean unlimited.
425
+
426
+ Worth calling at launch. Without it the first sign that an app is out of real
427
+ opens is a door that did not open, which is both the worst moment to find out
428
+ and the worst possible messenger. Warn while there is still time to top up.
429
+
430
+ ## Handling webhooks
431
+
432
+ `WebhookEvent` and its payload map are exported, so a partner backend can switch
433
+ on the event type instead of hand-casting `any`:
434
+
435
+ ```ts
436
+ import { verifyWebhook, type AnyWebhookEvent } from "@relai-team/access-sdk";
437
+
438
+ const event = JSON.parse(body) as AnyWebhookEvent;
439
+ switch (event.type) {
440
+ case "order.completed":
441
+ event.data.order; // typed
442
+ event.data.reason; // "node_out_of_service" when the platform completed it
443
+ break;
444
+ case "order.abandoned":
445
+ event.data.order_id;
446
+ break;
447
+ }
448
+ ```
449
+
450
+ There is deliberately no `payment.authorized`: Relai checkout intents capture
451
+ immediately, so success IS the capture. The published contract listed one until
452
+ 0.13.0, and omitted `order.abandoned`, which really is delivered.
453
+
454
+ ## When a payment gate is broken, not declined
455
+
456
+ `unlock()` presents the Stripe Payment Sheet when the platform answers 402
457
+ `payment_required`. If the gate itself is unusable, the SDK throws
458
+ `RelaiConfigError` rather than letting the 402 surface:
459
+
460
+ ```ts
461
+ import { RelaiConfigError } from "@relai-team/access-sdk";
462
+
463
+ try {
464
+ await relai.unlock({ orderId, intent: "occupy", transport });
465
+ } catch (err) {
466
+ if (err instanceof RelaiConfigError) {
467
+ // Relai's side is misconfigured. Retrying will not help and the person did
468
+ // nothing wrong. `err.field` names the offending value.
469
+ report(`Relai configuration problem: ${err.field}`);
470
+ } else if (err instanceof RelaiApiError && err.code === "payment_required") {
471
+ // A real payment outcome: declined, or the sheet was cancelled.
472
+ showPaymentNeeded();
473
+ }
474
+ }
475
+ ```
476
+
477
+ Before 0.14.0 these were the same thing. The key was checked for PRESENCE, so a
478
+ malformed value reached Stripe, failed there, and the SDK rethrew the original
479
+ 402. An app could not tell "your card was declined" from "Relai's Stripe key is
480
+ wrong", and neither could the person holding the phone.
481
+
392
482
  ## Offline-durable telemetry
393
483
 
394
484
  Every open reports best-effort telemetry. If the network is down when a node
@@ -6,23 +6,42 @@ var RelaiError = class extends Error {
6
6
  }
7
7
  };
8
8
  var RelaiApiError = class extends RelaiError {
9
- constructor(status, body) {
9
+ constructor(status, body, ctx = {}) {
10
10
  super(body.error.message);
11
11
  this.name = "RelaiApiError";
12
12
  this.code = body.error.code;
13
13
  this.status = status;
14
14
  this.docsUrl = body.error.docs_url;
15
15
  this.details = body.error.details;
16
+ this.requestId = ctx.requestId;
17
+ this.retryAfterSeconds = ctx.retryAfterSeconds;
18
+ this.method = ctx.method;
19
+ this.path = ctx.path;
20
+ }
21
+ };
22
+ var RelaiNetworkError = class extends RelaiApiError {
23
+ constructor(message, ctx = {}, cause) {
24
+ super(0, { error: { code: "network_error", message } }, ctx);
25
+ this.name = "RelaiNetworkError";
26
+ this.cause = cause;
16
27
  }
17
28
  };
18
29
  var RelaiLateFeeDue = class extends RelaiApiError {
19
- constructor(status, body) {
20
- super(status, body);
30
+ constructor(status, body, ctx = {}) {
31
+ super(status, body, ctx);
21
32
  this.feeCents = typeof this.details?.["fee_cents"] === "number" ? this.details["fee_cents"] : 0;
22
33
  const cs = this.details?.["client_secret"];
23
34
  this.clientSecret = typeof cs === "string" ? cs : null;
24
35
  }
25
36
  };
37
+ var RelaiConfigError = class extends RelaiError {
38
+ constructor(field, message) {
39
+ super(message);
40
+ this.name = "RelaiConfigError";
41
+ this.code = "invalid_gate_configuration";
42
+ this.field = field;
43
+ }
44
+ };
26
45
  var RelaiMissingKeyError = class extends RelaiError {
27
46
  constructor() {
28
47
  super(
@@ -47,4 +66,4 @@ var RelaiTransportError = class extends RelaiError {
47
66
  }
48
67
  };
49
68
 
50
- export { RelaiApiError, RelaiError, RelaiLateFeeDue, RelaiMissingKeyError, RelaiTransportError, RelaiUnlockRejected };
69
+ export { RelaiApiError, RelaiConfigError, RelaiError, RelaiLateFeeDue, RelaiMissingKeyError, RelaiNetworkError, RelaiTransportError, RelaiUnlockRejected };
@@ -1,14 +1,29 @@
1
1
  // src/payment-sheet.ts
2
+ function isStripePublishableKey(v) {
3
+ return typeof v === "string" && /^pk_(test|live)_[A-Za-z0-9]/.test(v);
4
+ }
5
+ function redactForMessage(v) {
6
+ if (typeof v !== "string") return String(v);
7
+ return v.length <= 12 ? v : `${v.slice(0, 12)}\u2026(${v.length} chars)`;
8
+ }
2
9
  function asPaymentRequired(details) {
3
- if (!details || typeof details["client_secret"] !== "string" || typeof details["kind"] !== "string") return null;
10
+ if (!details || typeof details["kind"] !== "string") return null;
4
11
  return details;
5
12
  }
6
13
  async function presentRelaiPaymentSheet(details, stripe) {
7
- if (!details.client_secret || !details.publishable_key) {
8
- console.warn(
9
- "[relai] Cannot present the payment sheet: the server did not return a client secret or publishable key."
14
+ if (!details.client_secret) {
15
+ const { RelaiConfigError } = await import('./errors-NKRGOFB3.js');
16
+ throw new RelaiConfigError(
17
+ "client_secret",
18
+ "Relai returned a payment gate with no client secret, so the payment sheet cannot be shown. This is a platform fault, not a declined payment. Quote the request id from the 402 to Relai support."
19
+ );
20
+ }
21
+ if (!isStripePublishableKey(details.publishable_key)) {
22
+ const { RelaiConfigError } = await import('./errors-NKRGOFB3.js');
23
+ throw new RelaiConfigError(
24
+ "publishable_key",
25
+ `Relai returned "${redactForMessage(details.publishable_key)}" as the Stripe publishable key, which is not one (it must start with pk_test_ or pk_live_). This is a platform misconfiguration, not a declined payment: retrying will not help, and no key on this device can substitute for it. Quote the request id from the 402 to Relai support.`
10
26
  );
11
- return false;
12
27
  }
13
28
  if (!stripe) {
14
29
  console.warn(
@@ -33,4 +48,4 @@ async function presentRelaiPaymentSheet(details, stripe) {
33
48
  return !error;
34
49
  }
35
50
 
36
- export { asPaymentRequired, presentRelaiPaymentSheet };
51
+ export { asPaymentRequired, isStripePublishableKey, presentRelaiPaymentSheet };
@@ -0,0 +1 @@
1
+ export { RelaiApiError, RelaiConfigError, RelaiError, RelaiLateFeeDue, RelaiMissingKeyError, RelaiNetworkError, RelaiTransportError, RelaiUnlockRejected } from './chunk-B2T3KFBF.js';
package/dist/index.cjs CHANGED
@@ -14,13 +14,15 @@ var __export = (target, all) => {
14
14
  var errors_exports = {};
15
15
  __export(errors_exports, {
16
16
  RelaiApiError: () => exports.RelaiApiError,
17
+ RelaiConfigError: () => exports.RelaiConfigError,
17
18
  RelaiError: () => exports.RelaiError,
18
19
  RelaiLateFeeDue: () => exports.RelaiLateFeeDue,
19
20
  RelaiMissingKeyError: () => exports.RelaiMissingKeyError,
21
+ RelaiNetworkError: () => exports.RelaiNetworkError,
20
22
  RelaiTransportError: () => exports.RelaiTransportError,
21
23
  RelaiUnlockRejected: () => exports.RelaiUnlockRejected
22
24
  });
23
- exports.RelaiError = void 0; exports.RelaiApiError = void 0; exports.RelaiLateFeeDue = void 0; exports.RelaiMissingKeyError = void 0; exports.RelaiUnlockRejected = void 0; exports.RelaiTransportError = void 0;
25
+ exports.RelaiError = void 0; exports.RelaiApiError = void 0; exports.RelaiNetworkError = void 0; exports.RelaiLateFeeDue = void 0; exports.RelaiConfigError = void 0; exports.RelaiMissingKeyError = void 0; exports.RelaiUnlockRejected = void 0; exports.RelaiTransportError = void 0;
24
26
  var init_errors = __esm({
25
27
  "src/errors.ts"() {
26
28
  exports.RelaiError = class extends Error {
@@ -30,23 +32,42 @@ var init_errors = __esm({
30
32
  }
31
33
  };
32
34
  exports.RelaiApiError = class extends exports.RelaiError {
33
- constructor(status, body) {
35
+ constructor(status, body, ctx = {}) {
34
36
  super(body.error.message);
35
37
  this.name = "RelaiApiError";
36
38
  this.code = body.error.code;
37
39
  this.status = status;
38
40
  this.docsUrl = body.error.docs_url;
39
41
  this.details = body.error.details;
42
+ this.requestId = ctx.requestId;
43
+ this.retryAfterSeconds = ctx.retryAfterSeconds;
44
+ this.method = ctx.method;
45
+ this.path = ctx.path;
46
+ }
47
+ };
48
+ exports.RelaiNetworkError = class extends exports.RelaiApiError {
49
+ constructor(message, ctx = {}, cause) {
50
+ super(0, { error: { code: "network_error", message } }, ctx);
51
+ this.name = "RelaiNetworkError";
52
+ this.cause = cause;
40
53
  }
41
54
  };
42
55
  exports.RelaiLateFeeDue = class extends exports.RelaiApiError {
43
- constructor(status, body) {
44
- super(status, body);
56
+ constructor(status, body, ctx = {}) {
57
+ super(status, body, ctx);
45
58
  this.feeCents = typeof this.details?.["fee_cents"] === "number" ? this.details["fee_cents"] : 0;
46
59
  const cs = this.details?.["client_secret"];
47
60
  this.clientSecret = typeof cs === "string" ? cs : null;
48
61
  }
49
62
  };
63
+ exports.RelaiConfigError = class extends exports.RelaiError {
64
+ constructor(field, message) {
65
+ super(message);
66
+ this.name = "RelaiConfigError";
67
+ this.code = "invalid_gate_configuration";
68
+ this.field = field;
69
+ }
70
+ };
50
71
  exports.RelaiMissingKeyError = class extends exports.RelaiError {
51
72
  constructor() {
52
73
  super(
@@ -77,18 +98,34 @@ var init_errors = __esm({
77
98
  var payment_sheet_exports = {};
78
99
  __export(payment_sheet_exports, {
79
100
  asPaymentRequired: () => asPaymentRequired,
101
+ isStripePublishableKey: () => isStripePublishableKey,
80
102
  presentRelaiPaymentSheet: () => presentRelaiPaymentSheet
81
103
  });
104
+ function isStripePublishableKey(v) {
105
+ return typeof v === "string" && /^pk_(test|live)_[A-Za-z0-9]/.test(v);
106
+ }
107
+ function redactForMessage(v) {
108
+ if (typeof v !== "string") return String(v);
109
+ return v.length <= 12 ? v : `${v.slice(0, 12)}\u2026(${v.length} chars)`;
110
+ }
82
111
  function asPaymentRequired(details) {
83
- if (!details || typeof details["client_secret"] !== "string" || typeof details["kind"] !== "string") return null;
112
+ if (!details || typeof details["kind"] !== "string") return null;
84
113
  return details;
85
114
  }
86
115
  async function presentRelaiPaymentSheet(details, stripe) {
87
- if (!details.client_secret || !details.publishable_key) {
88
- console.warn(
89
- "[relai] Cannot present the payment sheet: the server did not return a client secret or publishable key."
116
+ if (!details.client_secret) {
117
+ const { RelaiConfigError: RelaiConfigError2 } = await Promise.resolve().then(() => (init_errors(), errors_exports));
118
+ throw new RelaiConfigError2(
119
+ "client_secret",
120
+ "Relai returned a payment gate with no client secret, so the payment sheet cannot be shown. This is a platform fault, not a declined payment. Quote the request id from the 402 to Relai support."
121
+ );
122
+ }
123
+ if (!isStripePublishableKey(details.publishable_key)) {
124
+ const { RelaiConfigError: RelaiConfigError2 } = await Promise.resolve().then(() => (init_errors(), errors_exports));
125
+ throw new RelaiConfigError2(
126
+ "publishable_key",
127
+ `Relai returned "${redactForMessage(details.publishable_key)}" as the Stripe publishable key, which is not one (it must start with pk_test_ or pk_live_). This is a platform misconfiguration, not a declined payment: retrying will not help, and no key on this device can substitute for it. Quote the request id from the 402 to Relai support.`
90
128
  );
91
- return false;
92
129
  }
93
130
  if (!stripe) {
94
131
  console.warn(
@@ -164,14 +201,18 @@ var HttpClient = class {
164
201
  await sleep(backoffMs(i));
165
202
  continue;
166
203
  }
167
- throw new exports.RelaiError(`Network request failed: ${netErr.message}`);
204
+ throw new exports.RelaiNetworkError(
205
+ `Network request failed: ${netErr.message}`,
206
+ { method: opts.method ?? "GET", path: opts.path },
207
+ netErr
208
+ );
168
209
  }
169
210
  if (res.ok) return await this.parseJson(res);
170
211
  if (RETRYABLE_STATUS.has(res.status) && i < this.cfg.maxRetries) {
171
212
  await sleep(retryDelayMs(res, i));
172
213
  continue;
173
214
  }
174
- const apiErr = await this.toApiError(res);
215
+ const apiErr = await this.toApiError(res, opts);
175
216
  if (apiErr.code === "idempotency_in_progress" && i < this.cfg.maxRetries) {
176
217
  await sleep(retryDelayMs(res, i));
177
218
  continue;
@@ -209,7 +250,7 @@ var HttpClient = class {
209
250
  throw new exports.RelaiError(`Expected JSON from ${res.url} but got: ${text.slice(0, 120)}`);
210
251
  }
211
252
  }
212
- async toApiError(res) {
253
+ async toApiError(res, opts) {
213
254
  let body;
214
255
  try {
215
256
  body = await this.parseJson(res);
@@ -217,11 +258,18 @@ var HttpClient = class {
217
258
  body = { error: { code: "http_error", message: `HTTP ${res.status}` } };
218
259
  }
219
260
  if (!body?.error?.code) body = { error: { code: "http_error", message: `HTTP ${res.status}` } };
261
+ const ra = Number(res.headers.get("retry-after"));
262
+ const ctx = {
263
+ requestId: res.headers.get("x-relai-request-id") ?? void 0,
264
+ retryAfterSeconds: Number.isFinite(ra) && res.headers.get("retry-after") !== null ? ra : void 0,
265
+ method: opts.method ?? "GET",
266
+ path: opts.path
267
+ };
220
268
  if (body.error.code === "late_fee_due") {
221
269
  const { RelaiLateFeeDue: RelaiLateFeeDue2 } = await Promise.resolve().then(() => (init_errors(), errors_exports));
222
- return new RelaiLateFeeDue2(res.status, body);
270
+ return new RelaiLateFeeDue2(res.status, body, ctx);
223
271
  }
224
- return new exports.RelaiApiError(res.status, body);
272
+ return new exports.RelaiApiError(res.status, body, ctx);
225
273
  }
226
274
  };
227
275
  function backoffMs(attempt) {
@@ -512,6 +560,61 @@ var TelemetryModule = class {
512
560
  return this.http.request({ method: "POST", path: "/telemetry", body });
513
561
  }
514
562
  };
563
+ var PushModule = class {
564
+ constructor(http) {
565
+ this.http = http;
566
+ }
567
+ /**
568
+ * Register this device for handoff and pick-up notifications. Requires a
569
+ * signed-in end user. Safe to call on every launch: re-registering the same
570
+ * token updates it rather than duplicating it.
571
+ */
572
+ register(token, platform = "expo") {
573
+ return this.http.request({
574
+ method: "POST",
575
+ path: "/push/tokens",
576
+ body: { token, platform }
577
+ });
578
+ }
579
+ /** Unregister on sign-out, or the next person to use the device gets their alerts. */
580
+ unregister(token) {
581
+ return this.http.request({
582
+ method: "DELETE",
583
+ path: "/push/tokens",
584
+ body: { token }
585
+ });
586
+ }
587
+ };
588
+ var SandboxModule = class {
589
+ constructor(http) {
590
+ this.http = http;
591
+ }
592
+ /**
593
+ * Force a fault so the app's unhappy paths can be exercised without hardware.
594
+ * `jammed_door` needs a `nodeId`; `dead_battery` applies to the whole
595
+ * Exchange Zone.
596
+ */
597
+ injectFault(input) {
598
+ const body = { ez_id: input.exchangeZoneId, fault: input.fault };
599
+ if (input.nodeId !== void 0) body["node_id"] = input.nodeId;
600
+ return this.http.request({ method: "POST", path: "/sandbox/faults", body });
601
+ }
602
+ /** Clear an injected fault and return the Exchange Zone to service. */
603
+ clearFault(input) {
604
+ const body = { ez_id: input.exchangeZoneId, fault: "clear" };
605
+ if (input.nodeId !== void 0) body["node_id"] = input.nodeId;
606
+ return this.http.request({ method: "POST", path: "/sandbox/faults", body });
607
+ }
608
+ };
609
+ var AppModule = class {
610
+ constructor(http) {
611
+ this.http = http;
612
+ }
613
+ /** Config for the app the current key belongs to. */
614
+ self() {
615
+ return this.http.request({ path: "/apps/self" });
616
+ }
617
+ };
515
618
 
516
619
  // src/telemetry-uploader.ts
517
620
  init_errors();
@@ -676,6 +779,9 @@ var RelaiClient = class {
676
779
  this.overrideLinks = new OverrideLinksModule(this.http);
677
780
  this.endUsers = new EndUsersModule(this.http);
678
781
  this.telemetry = new TelemetryModule(this.http);
782
+ this.push = new PushModule(this.http);
783
+ this.sandbox = new SandboxModule(this.http);
784
+ this.app = new AppModule(this.http);
679
785
  this.telemetryUploader = new TelemetryUploader(this.telemetry, options.telemetryQueue);
680
786
  }
681
787
  /** Drain any telemetry queued after a failed send (e.g. on app foreground). */
@@ -1122,6 +1228,7 @@ var Intents = {
1122
1228
  };
1123
1229
 
1124
1230
  exports.AccessLinksModule = AccessLinksModule;
1231
+ exports.AppModule = AppModule;
1125
1232
  exports.AuthModule = AuthModule;
1126
1233
  exports.BleTransport = BleTransport;
1127
1234
  exports.EndUsersModule = EndUsersModule;
@@ -1132,12 +1239,14 @@ exports.MemoryTelemetryQueue = MemoryTelemetryQueue;
1132
1239
  exports.MemoryTokenStorage = MemoryTokenStorage;
1133
1240
  exports.OrdersModule = OrdersModule;
1134
1241
  exports.OverrideLinksModule = OverrideLinksModule;
1242
+ exports.PushModule = PushModule;
1135
1243
  exports.REJECT_REASONS = REJECT_REASONS;
1136
1244
  exports.RELAI_RX_CHAR = RELAI_RX_CHAR;
1137
1245
  exports.RELAI_TX_CHAR = RELAI_TX_CHAR;
1138
1246
  exports.RELAI_UART_SERVICE = RELAI_UART_SERVICE;
1139
1247
  exports.RecipientsModule = RecipientsModule;
1140
1248
  exports.RelaiClient = RelaiClient;
1249
+ exports.SandboxModule = SandboxModule;
1141
1250
  exports.SimAuthenticatedTransport = SimAuthenticatedTransport;
1142
1251
  exports.SimulatedTransport = SimulatedTransport;
1143
1252
  exports.StorageTelemetryQueue = StorageTelemetryQueue;
@@ -1145,6 +1254,7 @@ exports.TelemetryModule = TelemetryModule;
1145
1254
  exports.TelemetryUploader = TelemetryUploader;
1146
1255
  exports.asPaymentRequired = asPaymentRequired;
1147
1256
  exports.deliverOpen = deliverOpen;
1257
+ exports.isStripePublishableKey = isStripePublishableKey;
1148
1258
  exports.parseNotifyLine = parseNotifyLine;
1149
1259
  exports.presentRelaiPaymentSheet = presentRelaiPaymentSheet;
1150
1260
  exports.verifyWebhook = verifyWebhook;