@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.
- package/LICENSE +62 -0
- package/README.md +267 -0
- package/dist/chunk-3RG5ZIWI.js +8 -0
- package/dist/chunk-MNXTMLX2.js +50 -0
- package/dist/chunk-TRAEMNHD.js +27 -0
- package/dist/errors-MCGRQUDJ.js +2 -0
- package/dist/index.cjs +1054 -0
- package/dist/index.d.cts +943 -0
- package/dist/index.d.ts +943 -0
- package/dist/index.js +901 -0
- package/dist/payment-sheet-XOZDLRKL.js +2 -0
- package/package.json +68 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,901 @@
|
|
|
1
|
+
import { RelaiApiError, RelaiTransportError, RelaiUnlockRejected, RelaiMissingKeyError, RelaiError } from './chunk-MNXTMLX2.js';
|
|
2
|
+
export { RelaiApiError, RelaiError, RelaiLateFeeDue, RelaiMissingKeyError, RelaiTransportError, RelaiUnlockRejected } from './chunk-MNXTMLX2.js';
|
|
3
|
+
export { asPaymentRequired, presentRelaiPaymentSheet } from './chunk-TRAEMNHD.js';
|
|
4
|
+
import './chunk-3RG5ZIWI.js';
|
|
5
|
+
|
|
6
|
+
// src/http.ts
|
|
7
|
+
var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
|
|
8
|
+
function randomId() {
|
|
9
|
+
const c = globalThis.crypto;
|
|
10
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
11
|
+
return `idk_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
|
|
12
|
+
}
|
|
13
|
+
var HttpClient = class {
|
|
14
|
+
constructor(cfg) {
|
|
15
|
+
const f = cfg.fetchImpl ?? globalThis.fetch;
|
|
16
|
+
if (!f) throw new RelaiError("No global fetch available; pass fetchImpl to RelaiClient.");
|
|
17
|
+
this.fetchImpl = f;
|
|
18
|
+
this.cfg = { maxRetries: 3, ...cfg, baseUrl: cfg.baseUrl.replace(/\/+$/, "") };
|
|
19
|
+
}
|
|
20
|
+
async request(opts) {
|
|
21
|
+
const isWrite = opts.method === "POST" || opts.method === "DELETE";
|
|
22
|
+
const idem = isWrite ? opts.idempotencyKey ?? randomId() : void 0;
|
|
23
|
+
try {
|
|
24
|
+
return await this.attempt(opts, idem, false);
|
|
25
|
+
} catch (err) {
|
|
26
|
+
if (err instanceof RelaiApiError && err.code === "token_expired" && this.cfg.onTokenExpired && !opts.noBearer) {
|
|
27
|
+
const refreshed = await this.cfg.onTokenExpired();
|
|
28
|
+
if (refreshed) return this.attempt(opts, idem, true);
|
|
29
|
+
}
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async attempt(opts, idem, isRetryAfterRefresh) {
|
|
34
|
+
const url = this.buildUrl(opts.path, opts.query);
|
|
35
|
+
const headers = this.headers(opts, idem);
|
|
36
|
+
let lastErr;
|
|
37
|
+
for (let i = 0; i <= this.cfg.maxRetries; i++) {
|
|
38
|
+
let res;
|
|
39
|
+
try {
|
|
40
|
+
const init = { method: opts.method ?? "GET", headers };
|
|
41
|
+
if (opts.body !== void 0) init.body = JSON.stringify(opts.body);
|
|
42
|
+
res = await this.fetchImpl(url, init);
|
|
43
|
+
} catch (netErr) {
|
|
44
|
+
lastErr = netErr;
|
|
45
|
+
if (i < this.cfg.maxRetries) {
|
|
46
|
+
await sleep(backoffMs(i));
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
throw new RelaiError(`Network request failed: ${netErr.message}`);
|
|
50
|
+
}
|
|
51
|
+
if (res.ok) return await this.parseJson(res);
|
|
52
|
+
if (RETRYABLE_STATUS.has(res.status) && i < this.cfg.maxRetries) {
|
|
53
|
+
await sleep(retryDelayMs(res, i));
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
throw await this.toApiError(res);
|
|
57
|
+
}
|
|
58
|
+
throw lastErr instanceof Error ? lastErr : new RelaiError("Request failed");
|
|
59
|
+
}
|
|
60
|
+
buildUrl(path, query) {
|
|
61
|
+
const url = new URL(this.cfg.baseUrl + (path.startsWith("/") ? path : `/${path}`));
|
|
62
|
+
if (query) {
|
|
63
|
+
for (const [k, v] of Object.entries(query)) {
|
|
64
|
+
if (v !== void 0) url.searchParams.set(k, String(v));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return url.toString();
|
|
68
|
+
}
|
|
69
|
+
headers(opts, idem) {
|
|
70
|
+
const h = { "content-type": "application/json" };
|
|
71
|
+
const key = this.cfg.secretKey ?? this.cfg.publishableKey;
|
|
72
|
+
if (key) h["x-relai-key"] = key;
|
|
73
|
+
if (!opts.noBearer) {
|
|
74
|
+
const bearer = this.cfg.getBearer?.();
|
|
75
|
+
if (bearer) h["authorization"] = `Bearer ${bearer}`;
|
|
76
|
+
}
|
|
77
|
+
if (idem) h["idempotency-key"] = idem;
|
|
78
|
+
return h;
|
|
79
|
+
}
|
|
80
|
+
async parseJson(res) {
|
|
81
|
+
const text = await res.text();
|
|
82
|
+
if (!text) return {};
|
|
83
|
+
try {
|
|
84
|
+
return JSON.parse(text);
|
|
85
|
+
} catch {
|
|
86
|
+
throw new RelaiError(`Expected JSON from ${res.url} but got: ${text.slice(0, 120)}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async toApiError(res) {
|
|
90
|
+
let body;
|
|
91
|
+
try {
|
|
92
|
+
body = await this.parseJson(res);
|
|
93
|
+
} catch {
|
|
94
|
+
body = { error: { code: "http_error", message: `HTTP ${res.status}` } };
|
|
95
|
+
}
|
|
96
|
+
if (!body?.error?.code) body = { error: { code: "http_error", message: `HTTP ${res.status}` } };
|
|
97
|
+
if (body.error.code === "late_fee_due") {
|
|
98
|
+
const { RelaiLateFeeDue: RelaiLateFeeDue2 } = await import('./errors-MCGRQUDJ.js');
|
|
99
|
+
return new RelaiLateFeeDue2(res.status, body);
|
|
100
|
+
}
|
|
101
|
+
return new RelaiApiError(res.status, body);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
function backoffMs(attempt) {
|
|
105
|
+
return Math.min(1e3 * 2 ** attempt, 8e3) + Math.floor(Math.random() * 250);
|
|
106
|
+
}
|
|
107
|
+
function retryDelayMs(res, attempt) {
|
|
108
|
+
const ra = res.headers.get("retry-after");
|
|
109
|
+
if (ra) {
|
|
110
|
+
const secs = Number(ra);
|
|
111
|
+
if (Number.isFinite(secs)) return secs * 1e3;
|
|
112
|
+
}
|
|
113
|
+
return backoffMs(attempt);
|
|
114
|
+
}
|
|
115
|
+
function sleep(ms) {
|
|
116
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/auth.ts
|
|
120
|
+
var MemoryTokenStorage = class {
|
|
121
|
+
constructor() {
|
|
122
|
+
this.tokens = null;
|
|
123
|
+
}
|
|
124
|
+
get() {
|
|
125
|
+
return this.tokens;
|
|
126
|
+
}
|
|
127
|
+
set(tokens) {
|
|
128
|
+
this.tokens = tokens;
|
|
129
|
+
}
|
|
130
|
+
clear() {
|
|
131
|
+
this.tokens = null;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
var AuthModule = class {
|
|
135
|
+
constructor(http, storage) {
|
|
136
|
+
this.http = http;
|
|
137
|
+
this.storage = storage;
|
|
138
|
+
this.refreshInFlight = null;
|
|
139
|
+
}
|
|
140
|
+
/** Current access token, if signed in. */
|
|
141
|
+
get accessToken() {
|
|
142
|
+
return this.storage.get()?.access_token;
|
|
143
|
+
}
|
|
144
|
+
get isSignedIn() {
|
|
145
|
+
return !!this.storage.get();
|
|
146
|
+
}
|
|
147
|
+
/** Start the OTP flow: the platform emails a 6-digit code. */
|
|
148
|
+
async startOtp(email) {
|
|
149
|
+
await this.http.request({ method: "POST", path: "/auth/otp/start", body: { email }, noBearer: true });
|
|
150
|
+
}
|
|
151
|
+
/** Verify the code, receive and store the token pair. */
|
|
152
|
+
async verifyOtp(email, code) {
|
|
153
|
+
const tokens = await this.http.request({
|
|
154
|
+
method: "POST",
|
|
155
|
+
path: "/auth/otp/verify",
|
|
156
|
+
body: { email, code },
|
|
157
|
+
noBearer: true
|
|
158
|
+
});
|
|
159
|
+
this.storage.set(tokens);
|
|
160
|
+
return tokens;
|
|
161
|
+
}
|
|
162
|
+
/** Rotate the token pair. Single-flight: concurrent callers share one refresh. */
|
|
163
|
+
refresh() {
|
|
164
|
+
if (this.refreshInFlight) return this.refreshInFlight;
|
|
165
|
+
this.refreshInFlight = this.doRefresh().finally(() => {
|
|
166
|
+
this.refreshInFlight = null;
|
|
167
|
+
});
|
|
168
|
+
return this.refreshInFlight;
|
|
169
|
+
}
|
|
170
|
+
async doRefresh() {
|
|
171
|
+
const current = this.storage.get();
|
|
172
|
+
if (!current) return false;
|
|
173
|
+
try {
|
|
174
|
+
const tokens = await this.http.request({
|
|
175
|
+
method: "POST",
|
|
176
|
+
path: "/auth/refresh",
|
|
177
|
+
body: { refresh_token: current.refresh_token },
|
|
178
|
+
noBearer: true
|
|
179
|
+
});
|
|
180
|
+
this.storage.set(tokens);
|
|
181
|
+
return true;
|
|
182
|
+
} catch (err) {
|
|
183
|
+
if (err instanceof RelaiApiError && err.status === 401) this.storage.clear();
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** Revoke the refresh token and clear local state. */
|
|
188
|
+
async signOut() {
|
|
189
|
+
const current = this.storage.get();
|
|
190
|
+
if (current) {
|
|
191
|
+
await this.http.request({ method: "POST", path: "/auth/revoke", body: { refresh_token: current.refresh_token }, noBearer: true }).catch(() => void 0);
|
|
192
|
+
}
|
|
193
|
+
this.storage.clear();
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
// src/resources.ts
|
|
198
|
+
var ExchangeZonesModule = class {
|
|
199
|
+
constructor(http) {
|
|
200
|
+
this.http = http;
|
|
201
|
+
}
|
|
202
|
+
/** Nearby Exchange Zones, closest first. */
|
|
203
|
+
near(input) {
|
|
204
|
+
const query = { lat: input.lat, lng: input.lng };
|
|
205
|
+
if (input.radiusM !== void 0) query["radius_m"] = input.radiusM;
|
|
206
|
+
if (input.minNodes !== void 0) query["min_nodes"] = input.minNodes;
|
|
207
|
+
if (input.maxNodes !== void 0) query["max_nodes"] = input.maxNodes;
|
|
208
|
+
return this.http.request({ path: "/exchange-zones", query });
|
|
209
|
+
}
|
|
210
|
+
list(input) {
|
|
211
|
+
const query = {};
|
|
212
|
+
if (input?.minNodes !== void 0) query["min_nodes"] = input.minNodes;
|
|
213
|
+
if (input?.maxNodes !== void 0) query["max_nodes"] = input.maxNodes;
|
|
214
|
+
return this.http.request({ path: "/exchange-zones", query });
|
|
215
|
+
}
|
|
216
|
+
/** Full detail: towers → nodes (includes each tower's parent_ble_id). */
|
|
217
|
+
get(exchangeZoneId) {
|
|
218
|
+
return this.http.request({ path: `/exchange-zones/${exchangeZoneId}` });
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
var OrdersModule = class {
|
|
222
|
+
constructor(http) {
|
|
223
|
+
this.http = http;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Create an order. On DIRECTED-handoff apps, name the pick-up recipient by
|
|
227
|
+
* `recipient` (exact email or `@access-tag`) or by `recipientUserId` (from
|
|
228
|
+
* `client.recipients.lookup`).
|
|
229
|
+
*/
|
|
230
|
+
create(input) {
|
|
231
|
+
const body = { ez_id: input.exchangeZoneId };
|
|
232
|
+
if (input.handoffMode !== void 0) body["handoff_mode"] = input.handoffMode;
|
|
233
|
+
if (input.recipient !== void 0) body["recipient"] = input.recipient;
|
|
234
|
+
if (input.recipientUserId !== void 0) body["recipient_user_id"] = input.recipientUserId;
|
|
235
|
+
if (input.recipientEmail !== void 0) body["recipient_email"] = input.recipientEmail;
|
|
236
|
+
if (input.promotionCode !== void 0) body["promotion_code"] = input.promotionCode;
|
|
237
|
+
if (input.metadata !== void 0) body["metadata"] = input.metadata;
|
|
238
|
+
return this.http.request({ method: "POST", path: "/orders", body });
|
|
239
|
+
}
|
|
240
|
+
get(orderId) {
|
|
241
|
+
return this.http.request({ path: `/orders/${orderId}` });
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Request an open: one token + an unlock grant. On authenticated towers the
|
|
245
|
+
* grant's `token` is null; deliver it via `client.unlock(...)`, which mints it
|
|
246
|
+
* against a Parent nonce. Prefer `client.unlock` over calling this directly.
|
|
247
|
+
*
|
|
248
|
+
* An OPEN-mode pick-up passes `accessLink` (the sender's single-use code); an
|
|
249
|
+
* override passes `overrideCode`. A `late_fee_due` (402) response means a late
|
|
250
|
+
* pick-up fee gates the open: see `RelaiLateFeeDue`.
|
|
251
|
+
*/
|
|
252
|
+
open(orderId, input) {
|
|
253
|
+
const body = { intent: input.intent };
|
|
254
|
+
if (input.size !== void 0) body["size"] = input.size;
|
|
255
|
+
if (input.nodeId !== void 0) body["node_id"] = input.nodeId;
|
|
256
|
+
if (input.accessLink !== void 0) body["access_link"] = input.accessLink;
|
|
257
|
+
if (input.overrideCode !== void 0) body["override_code"] = input.overrideCode;
|
|
258
|
+
return this.http.request({ method: "POST", path: `/orders/${orderId}/opens`, body });
|
|
259
|
+
}
|
|
260
|
+
cancel(orderId) {
|
|
261
|
+
return this.http.request({ method: "POST", path: `/orders/${orderId}/cancel` });
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
var GrantsModule = class {
|
|
265
|
+
constructor(http) {
|
|
266
|
+
this.http = http;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Redeem a Parent-issued nonce for the authenticated command token
|
|
270
|
+
* (challenge–response). Called by `client.unlock`; public for advanced flows.
|
|
271
|
+
*/
|
|
272
|
+
mint(grantId, nonceB64Url) {
|
|
273
|
+
return this.http.request({
|
|
274
|
+
method: "POST",
|
|
275
|
+
path: `/grants/${grantId}/mint`,
|
|
276
|
+
body: { nonce: nonceB64Url }
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
var RecipientsModule = class {
|
|
281
|
+
constructor(http) {
|
|
282
|
+
this.http = http;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Resolve a directed-handoff recipient by EXACT email or `@access-tag` (no
|
|
286
|
+
* fuzzy search, no browse). Returns a minimal identity to confirm before
|
|
287
|
+
* creating the order. Requires a signed-in end-user.
|
|
288
|
+
*/
|
|
289
|
+
lookup(query) {
|
|
290
|
+
return this.http.request({ method: "POST", path: "/recipients/lookup", body: { query } });
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
var AccessLinksModule = class {
|
|
294
|
+
constructor(http) {
|
|
295
|
+
this.http = http;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Resolve an OPEN-mode access link code (`relai.access.…`) to its pick-up
|
|
299
|
+
* target. Does not burn the link; redemption happens on the open itself
|
|
300
|
+
* (pass the code as `accessLink`).
|
|
301
|
+
*/
|
|
302
|
+
resolve(code) {
|
|
303
|
+
return this.http.request({ method: "POST", path: "/access-links/resolve", body: { code } });
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
var OverrideLinksModule = class {
|
|
307
|
+
constructor(http) {
|
|
308
|
+
this.http = http;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Request a single-use override link for a node (SERVER ONLY: secret key).
|
|
312
|
+
* Auto-granted; the first 10 per organization per calendar month are free,
|
|
313
|
+
* then $1.00 each on the next invoice. Redeem via `overrideCode` on an open.
|
|
314
|
+
*/
|
|
315
|
+
request(input) {
|
|
316
|
+
const body = { node_id: input.nodeId };
|
|
317
|
+
if (input.expiresInHours !== void 0) body["expires_in_hours"] = input.expiresInHours;
|
|
318
|
+
return this.http.request({ method: "POST", path: "/override-links", body });
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
var TelemetryModule = class {
|
|
322
|
+
constructor(http) {
|
|
323
|
+
this.http = http;
|
|
324
|
+
}
|
|
325
|
+
send(input) {
|
|
326
|
+
const body = { ez_id: input.exchangeZoneId, events: input.events };
|
|
327
|
+
if (input.grantId !== void 0) body["grant_id"] = input.grantId;
|
|
328
|
+
if (input.batteryPct !== void 0) body["battery_pct"] = input.batteryPct;
|
|
329
|
+
if (input.firmware !== void 0) body["firmware"] = input.firmware;
|
|
330
|
+
return this.http.request({ method: "POST", path: "/telemetry", body });
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
// src/telemetry-queue.ts
|
|
335
|
+
var MemoryTelemetryQueue = class {
|
|
336
|
+
constructor() {
|
|
337
|
+
this.items = [];
|
|
338
|
+
this.seq = 0;
|
|
339
|
+
}
|
|
340
|
+
enqueue(payload) {
|
|
341
|
+
this.items.push({ id: `tq_${++this.seq}`, payload, attempts: 0 });
|
|
342
|
+
return Promise.resolve();
|
|
343
|
+
}
|
|
344
|
+
list() {
|
|
345
|
+
return Promise.resolve([...this.items]);
|
|
346
|
+
}
|
|
347
|
+
remove(id) {
|
|
348
|
+
this.items = this.items.filter((i) => i.id !== id);
|
|
349
|
+
return Promise.resolve();
|
|
350
|
+
}
|
|
351
|
+
markAttempt(id) {
|
|
352
|
+
const it = this.items.find((i) => i.id === id);
|
|
353
|
+
if (it) it.attempts += 1;
|
|
354
|
+
return Promise.resolve();
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
// src/telemetry-uploader.ts
|
|
359
|
+
var MAX_TELEMETRY_ATTEMPTS = 8;
|
|
360
|
+
function isPermanentFailure(err) {
|
|
361
|
+
return err instanceof RelaiApiError && err.status >= 400 && err.status < 500 && err.status !== 429;
|
|
362
|
+
}
|
|
363
|
+
var TelemetryUploader = class {
|
|
364
|
+
constructor(telemetry, queue) {
|
|
365
|
+
this.telemetry = telemetry;
|
|
366
|
+
this.queue = queue ?? new MemoryTelemetryQueue();
|
|
367
|
+
}
|
|
368
|
+
/** Send a payload; on failure, queue it for retry. Best-effort, never throws. */
|
|
369
|
+
async submit(payload) {
|
|
370
|
+
await this.flush();
|
|
371
|
+
try {
|
|
372
|
+
await this.telemetry.send(payload);
|
|
373
|
+
} catch {
|
|
374
|
+
await this.queue.enqueue(payload);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Retry queued telemetry. A permanently-rejected item (4xx) or one that has
|
|
379
|
+
* exhausted its attempts is dropped so it can't wedge the backlog behind it;
|
|
380
|
+
* a transient failure (network / 5xx / 429) stops the drain, leaving the rest
|
|
381
|
+
* queued for the next flush.
|
|
382
|
+
*/
|
|
383
|
+
async flush() {
|
|
384
|
+
const pending = await this.queue.list();
|
|
385
|
+
let sent = 0;
|
|
386
|
+
for (const item of pending) {
|
|
387
|
+
try {
|
|
388
|
+
await this.telemetry.send(item.payload);
|
|
389
|
+
await this.queue.remove(item.id);
|
|
390
|
+
sent += 1;
|
|
391
|
+
} catch (err) {
|
|
392
|
+
if (isPermanentFailure(err) || item.attempts + 1 >= MAX_TELEMETRY_ATTEMPTS) {
|
|
393
|
+
await this.queue.remove(item.id);
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
await this.queue.markAttempt(item.id);
|
|
397
|
+
break;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const remaining = (await this.queue.list()).length;
|
|
401
|
+
return { sent, remaining };
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
// src/unlock.ts
|
|
406
|
+
async function deliverOpen(deps, open, opts) {
|
|
407
|
+
const { transport } = opts;
|
|
408
|
+
const grant = open.grant;
|
|
409
|
+
const parentBleId = opts.parentBleId ?? grant.parent_ble_id;
|
|
410
|
+
if (!parentBleId) {
|
|
411
|
+
throw new RelaiTransportError(
|
|
412
|
+
`Grant ${grant.grant_id} names no parent_ble_id and none was provided; cannot select a Parent.`
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
const session = await transport.connect(parentBleId);
|
|
416
|
+
try {
|
|
417
|
+
let token = grant.token;
|
|
418
|
+
let keyVersion;
|
|
419
|
+
if (grant.algorithm === "relai-hmac-sha256-16-v1") {
|
|
420
|
+
const nonce = await transport.requestNonce(session);
|
|
421
|
+
const minted = await deps.grants.mint(grant.grant_id, nonce);
|
|
422
|
+
token = minted.token;
|
|
423
|
+
keyVersion = minted.key_version;
|
|
424
|
+
}
|
|
425
|
+
if (!token) {
|
|
426
|
+
throw new RelaiTransportError(
|
|
427
|
+
`Grant ${grant.grant_id} has no token to deliver (algorithm ${grant.algorithm}).`
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
const ack = await transport.sendCommand(session, token);
|
|
431
|
+
const ezId = opts.exchangeZoneId ?? grant.ez_id;
|
|
432
|
+
if (ezId) {
|
|
433
|
+
void deps.telemetry.submit({
|
|
434
|
+
exchangeZoneId: ezId,
|
|
435
|
+
grantId: grant.grant_id,
|
|
436
|
+
events: [
|
|
437
|
+
{
|
|
438
|
+
action: ack.accepted ? "unlock_used" : "unlock_failed",
|
|
439
|
+
result: ack.accepted ? "success" : "failure",
|
|
440
|
+
transport: "ble",
|
|
441
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
442
|
+
}
|
|
443
|
+
]
|
|
444
|
+
}).catch(() => void 0);
|
|
445
|
+
}
|
|
446
|
+
if (!ack.accepted) {
|
|
447
|
+
throw new RelaiUnlockRejected(ack.rejectReason ?? "UNKNOWN", ack.verbHint);
|
|
448
|
+
}
|
|
449
|
+
return {
|
|
450
|
+
open,
|
|
451
|
+
accepted: true,
|
|
452
|
+
command: ack.command,
|
|
453
|
+
keyVersion,
|
|
454
|
+
session
|
|
455
|
+
};
|
|
456
|
+
} finally {
|
|
457
|
+
if (!opts.keepConnected) await transport.disconnect(session).catch(() => void 0);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// src/client.ts
|
|
462
|
+
var DEFAULT_BASE_URL = "https://access.relai.us/api/v1";
|
|
463
|
+
var RelaiClient = class {
|
|
464
|
+
constructor(options) {
|
|
465
|
+
if (!options.publishableKey && !options.secretKey) throw new RelaiMissingKeyError();
|
|
466
|
+
const storage = options.tokenStorage ?? new MemoryTokenStorage();
|
|
467
|
+
let auth;
|
|
468
|
+
const httpConfig = {
|
|
469
|
+
baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
|
|
470
|
+
getBearer: () => auth?.accessToken,
|
|
471
|
+
onTokenExpired: () => auth?.refresh() ?? Promise.resolve(false),
|
|
472
|
+
...options.publishableKey !== void 0 ? { publishableKey: options.publishableKey } : {},
|
|
473
|
+
...options.secretKey !== void 0 ? { secretKey: options.secretKey } : {},
|
|
474
|
+
...options.fetchImpl !== void 0 ? { fetchImpl: options.fetchImpl } : {},
|
|
475
|
+
...options.maxRetries !== void 0 ? { maxRetries: options.maxRetries } : {}
|
|
476
|
+
};
|
|
477
|
+
this.http = new HttpClient(httpConfig);
|
|
478
|
+
auth = new AuthModule(this.http, storage);
|
|
479
|
+
this.auth = auth;
|
|
480
|
+
this.exchangeZones = new ExchangeZonesModule(this.http);
|
|
481
|
+
this.orders = new OrdersModule(this.http);
|
|
482
|
+
this.grants = new GrantsModule(this.http);
|
|
483
|
+
this.recipients = new RecipientsModule(this.http);
|
|
484
|
+
this.accessLinks = new AccessLinksModule(this.http);
|
|
485
|
+
this.overrideLinks = new OverrideLinksModule(this.http);
|
|
486
|
+
this.telemetry = new TelemetryModule(this.http);
|
|
487
|
+
this.telemetryUploader = new TelemetryUploader(this.telemetry, options.telemetryQueue);
|
|
488
|
+
}
|
|
489
|
+
/** Drain any telemetry queued after a failed send (e.g. on app foreground). */
|
|
490
|
+
flushTelemetry() {
|
|
491
|
+
return this.telemetryUploader.flush();
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Open a node: request the grant, then drive the physical unlock over the
|
|
495
|
+
* given transport (challenge → mint → write → ack). Throws
|
|
496
|
+
* `RelaiUnlockRejected` if the Parent refuses the command.
|
|
497
|
+
*/
|
|
498
|
+
async unlock(input) {
|
|
499
|
+
const requestOpen = () => this.orders.open(input.orderId, {
|
|
500
|
+
intent: input.intent,
|
|
501
|
+
...input.size !== void 0 ? { size: input.size } : {},
|
|
502
|
+
...input.nodeId !== void 0 ? { nodeId: input.nodeId } : {},
|
|
503
|
+
...input.accessLink !== void 0 ? { accessLink: input.accessLink } : {},
|
|
504
|
+
...input.overrideCode !== void 0 ? { overrideCode: input.overrideCode } : {}
|
|
505
|
+
});
|
|
506
|
+
let open;
|
|
507
|
+
try {
|
|
508
|
+
open = await requestOpen();
|
|
509
|
+
} catch (err) {
|
|
510
|
+
const { RelaiApiError: RelaiApiError2 } = await import('./errors-MCGRQUDJ.js');
|
|
511
|
+
if (input.presentPaymentSheet !== false && err instanceof RelaiApiError2 && err.code === "payment_required") {
|
|
512
|
+
const { asPaymentRequired: asPaymentRequired2, presentRelaiPaymentSheet: presentRelaiPaymentSheet2 } = await import('./payment-sheet-XOZDLRKL.js');
|
|
513
|
+
const details = asPaymentRequired2(err.details);
|
|
514
|
+
if (!details || !await presentRelaiPaymentSheet2(details)) throw err;
|
|
515
|
+
open = await requestOpen();
|
|
516
|
+
} else {
|
|
517
|
+
throw err;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
return deliverOpen(
|
|
521
|
+
{ grants: this.grants, telemetry: this.telemetryUploader },
|
|
522
|
+
open,
|
|
523
|
+
{
|
|
524
|
+
transport: input.transport,
|
|
525
|
+
...input.parentBleId !== void 0 ? { parentBleId: input.parentBleId } : {},
|
|
526
|
+
...input.exchangeZoneId !== void 0 ? { exchangeZoneId: input.exchangeZoneId } : {},
|
|
527
|
+
...input.keepConnected !== void 0 ? { keepConnected: input.keepConnected } : {}
|
|
528
|
+
}
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
|
|
533
|
+
// src/telemetry-storage.ts
|
|
534
|
+
var DEFAULT_KEY = "@relai/telemetry-queue";
|
|
535
|
+
var DEFAULT_MAX = 500;
|
|
536
|
+
var StorageTelemetryQueue = class {
|
|
537
|
+
constructor(storage, opts = {}) {
|
|
538
|
+
/** Serializes read-modify-write so concurrent calls don't lose updates. */
|
|
539
|
+
this.chain = Promise.resolve();
|
|
540
|
+
this.seq = 0;
|
|
541
|
+
this.storage = storage;
|
|
542
|
+
this.key = opts.storageKey ?? DEFAULT_KEY;
|
|
543
|
+
this.maxItems = Math.max(1, opts.maxItems ?? DEFAULT_MAX);
|
|
544
|
+
}
|
|
545
|
+
enqueue(payload) {
|
|
546
|
+
return this.mutate((items) => {
|
|
547
|
+
items.push({ id: this.nextId(), payload, attempts: 0 });
|
|
548
|
+
if (items.length > this.maxItems) items.splice(0, items.length - this.maxItems);
|
|
549
|
+
return items;
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
async list() {
|
|
553
|
+
return this.run(() => this.read());
|
|
554
|
+
}
|
|
555
|
+
remove(id) {
|
|
556
|
+
return this.mutate((items) => items.filter((i) => i.id !== id));
|
|
557
|
+
}
|
|
558
|
+
markAttempt(id) {
|
|
559
|
+
return this.mutate(
|
|
560
|
+
(items) => items.map((i) => i.id === id ? { ...i, attempts: i.attempts + 1 } : i)
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
// ── internals ──────────────────────────────────────────────────────────────
|
|
564
|
+
nextId() {
|
|
565
|
+
this.seq += 1;
|
|
566
|
+
return `tq_${Date.now().toString(36)}_${this.seq}`;
|
|
567
|
+
}
|
|
568
|
+
/** Serialize an operation after any in-flight ones (a simple promise lock). */
|
|
569
|
+
run(op) {
|
|
570
|
+
const next = this.chain.then(op, op);
|
|
571
|
+
this.chain = next.then(
|
|
572
|
+
() => void 0,
|
|
573
|
+
() => void 0
|
|
574
|
+
);
|
|
575
|
+
return next;
|
|
576
|
+
}
|
|
577
|
+
mutate(fn) {
|
|
578
|
+
return this.run(async () => {
|
|
579
|
+
const items = await this.read();
|
|
580
|
+
const nextItems = fn(items);
|
|
581
|
+
await this.storage.setItem(this.key, JSON.stringify(nextItems));
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
async read() {
|
|
585
|
+
let raw;
|
|
586
|
+
try {
|
|
587
|
+
raw = await this.storage.getItem(this.key);
|
|
588
|
+
} catch {
|
|
589
|
+
return [];
|
|
590
|
+
}
|
|
591
|
+
if (!raw) return [];
|
|
592
|
+
try {
|
|
593
|
+
const parsed = JSON.parse(raw);
|
|
594
|
+
if (!Array.isArray(parsed)) return [];
|
|
595
|
+
return parsed.filter(
|
|
596
|
+
(i) => !!i && typeof i.id === "string" && !!i.payload
|
|
597
|
+
);
|
|
598
|
+
} catch {
|
|
599
|
+
return [];
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
// src/transport/base64.ts
|
|
605
|
+
function utf8ToBase64(s) {
|
|
606
|
+
const g = globalThis;
|
|
607
|
+
if (g.Buffer) return g.Buffer.from(s, "utf8").toString("base64");
|
|
608
|
+
if (g.btoa) return g.btoa(unescape(encodeURIComponent(s)));
|
|
609
|
+
throw new Error("No base64 encoder available in this runtime.");
|
|
610
|
+
}
|
|
611
|
+
function base64ToUtf8(b64) {
|
|
612
|
+
const g = globalThis;
|
|
613
|
+
if (g.Buffer) return g.Buffer.from(b64, "base64").toString("utf8");
|
|
614
|
+
if (g.atob) return decodeURIComponent(escape(g.atob(b64)));
|
|
615
|
+
throw new Error("No base64 decoder available in this runtime.");
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// src/transport/simulated.ts
|
|
619
|
+
function randomNonceB64Url() {
|
|
620
|
+
const bytes = new Uint8Array(16);
|
|
621
|
+
const c = globalThis.crypto;
|
|
622
|
+
if (c?.getRandomValues) c.getRandomValues(bytes);
|
|
623
|
+
else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
624
|
+
let bin = "";
|
|
625
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
626
|
+
const g = globalThis;
|
|
627
|
+
const b64 = g.Buffer ? g.Buffer.from(bin, "binary").toString("base64") : g.btoa(bin);
|
|
628
|
+
return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
629
|
+
}
|
|
630
|
+
var SimulatedTransport = class {
|
|
631
|
+
constructor(parents = [{ parentBleId: "sim-parent-1", towerId: "twr_sim" }]) {
|
|
632
|
+
this.rejectQueue = /* @__PURE__ */ new Map();
|
|
633
|
+
this.parents = parents;
|
|
634
|
+
for (const p of parents) if (p.rejectWith) this.rejectQueue.set(p.parentBleId, p.rejectWith);
|
|
635
|
+
}
|
|
636
|
+
scan() {
|
|
637
|
+
return Promise.resolve(
|
|
638
|
+
this.parents.map((p) => {
|
|
639
|
+
const d = { parentBleId: p.parentBleId, isSimulated: true };
|
|
640
|
+
if (p.towerId !== void 0) d.towerId = p.towerId;
|
|
641
|
+
return d;
|
|
642
|
+
})
|
|
643
|
+
);
|
|
644
|
+
}
|
|
645
|
+
connect(parentBleId) {
|
|
646
|
+
return Promise.resolve({ id: `sess_${parentBleId}`, parentBleId, connectedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
647
|
+
}
|
|
648
|
+
requestNonce(_session) {
|
|
649
|
+
return Promise.resolve(randomNonceB64Url());
|
|
650
|
+
}
|
|
651
|
+
sendCommand(session, token) {
|
|
652
|
+
const forced = this.rejectQueue.get(session.parentBleId);
|
|
653
|
+
if (forced) {
|
|
654
|
+
this.rejectQueue.delete(session.parentBleId);
|
|
655
|
+
return Promise.resolve({ accepted: false, command: void 0, rejectReason: forced, verbHint: void 0 });
|
|
656
|
+
}
|
|
657
|
+
let command;
|
|
658
|
+
try {
|
|
659
|
+
command = base64ToUtf8(token).split("|")[0];
|
|
660
|
+
} catch {
|
|
661
|
+
return Promise.resolve({ accepted: false, command: void 0, rejectReason: "B64", verbHint: void 0 });
|
|
662
|
+
}
|
|
663
|
+
return Promise.resolve({ accepted: true, command, rejectReason: void 0, verbHint: void 0 });
|
|
664
|
+
}
|
|
665
|
+
readTelemetry(_session) {
|
|
666
|
+
return Promise.resolve({ batteryPct: 100, doorOpen: false });
|
|
667
|
+
}
|
|
668
|
+
disconnect(_session) {
|
|
669
|
+
return Promise.resolve();
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
|
|
673
|
+
// src/transport/sim-authenticated.ts
|
|
674
|
+
var DEFAULT_BASE_URL2 = "https://access.relai.us/api/v1";
|
|
675
|
+
var SimAuthenticatedTransport = class {
|
|
676
|
+
constructor(opts) {
|
|
677
|
+
this.publishableKey = opts.publishableKey;
|
|
678
|
+
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL2).replace(/\/$/, "");
|
|
679
|
+
const f = opts.fetchImpl ?? globalThis.fetch;
|
|
680
|
+
if (!f) throw new RelaiTransportError("No fetch available; pass fetchImpl.");
|
|
681
|
+
this.fetchImpl = f;
|
|
682
|
+
}
|
|
683
|
+
scan() {
|
|
684
|
+
return Promise.reject(new RelaiTransportError("SimAuthenticatedTransport has no discovery; use the grant's parent_ble_id."));
|
|
685
|
+
}
|
|
686
|
+
connect(parentBleId) {
|
|
687
|
+
return Promise.resolve({ id: parentBleId, parentBleId, connectedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
688
|
+
}
|
|
689
|
+
async requestNonce(session) {
|
|
690
|
+
const body = await this.post(`/sandbox/parents/${encodeURIComponent(session.parentBleId)}/challenge`);
|
|
691
|
+
if (!body?.nonce) throw new RelaiTransportError("Sim Parent returned no nonce.");
|
|
692
|
+
return body.nonce;
|
|
693
|
+
}
|
|
694
|
+
async sendCommand(session, token) {
|
|
695
|
+
const body = await this.post(
|
|
696
|
+
`/sandbox/parents/${encodeURIComponent(session.parentBleId)}/commands`,
|
|
697
|
+
{ token }
|
|
698
|
+
);
|
|
699
|
+
if (body?.accepted) {
|
|
700
|
+
return { accepted: true, command: body.command, rejectReason: void 0, verbHint: void 0 };
|
|
701
|
+
}
|
|
702
|
+
return { accepted: false, command: void 0, rejectReason: body?.reason ?? "UNKNOWN", verbHint: void 0 };
|
|
703
|
+
}
|
|
704
|
+
readTelemetry(_session) {
|
|
705
|
+
return Promise.resolve({});
|
|
706
|
+
}
|
|
707
|
+
disconnect(_session) {
|
|
708
|
+
return Promise.resolve();
|
|
709
|
+
}
|
|
710
|
+
async post(path, body) {
|
|
711
|
+
const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
712
|
+
method: "POST",
|
|
713
|
+
headers: {
|
|
714
|
+
"content-type": "application/json",
|
|
715
|
+
authorization: `Bearer ${this.publishableKey}`
|
|
716
|
+
},
|
|
717
|
+
body: JSON.stringify(body ?? {})
|
|
718
|
+
});
|
|
719
|
+
if (!res.ok) {
|
|
720
|
+
const text = await res.text().catch(() => "");
|
|
721
|
+
throw new RelaiTransportError(`Sim Parent ${path} failed (${res.status}): ${text.slice(0, 200)}`);
|
|
722
|
+
}
|
|
723
|
+
return await res.json();
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
|
|
727
|
+
// src/transport/notify.ts
|
|
728
|
+
var REJECT_REASONS = [
|
|
729
|
+
"B64",
|
|
730
|
+
"UNTAGGED",
|
|
731
|
+
"FORMAT",
|
|
732
|
+
"KEYVERSION",
|
|
733
|
+
"TAG",
|
|
734
|
+
"NONCE",
|
|
735
|
+
"LOCKED",
|
|
736
|
+
"ROTATE"
|
|
737
|
+
];
|
|
738
|
+
function parseNotifyLine(line) {
|
|
739
|
+
const trimmed = line.trim();
|
|
740
|
+
if (trimmed.startsWith("NONCE ")) {
|
|
741
|
+
const nonce = trimmed.slice("NONCE ".length).trim();
|
|
742
|
+
return { kind: "nonce", nonceB64Url: nonce };
|
|
743
|
+
}
|
|
744
|
+
if (trimmed.startsWith("[AUTH] ACCEPT ")) {
|
|
745
|
+
return { kind: "accept", command: trimmed.slice("[AUTH] ACCEPT ".length).trim() };
|
|
746
|
+
}
|
|
747
|
+
if (trimmed.startsWith("[AUTH] REJECT ")) {
|
|
748
|
+
const rest = trimmed.slice("[AUTH] REJECT ".length).trim();
|
|
749
|
+
const [reason, ...verbParts] = rest.split(/\s+/);
|
|
750
|
+
const verbHint = verbParts.length > 0 ? verbParts.join(" ") : void 0;
|
|
751
|
+
return { kind: "reject", reason: reason ?? "", verbHint };
|
|
752
|
+
}
|
|
753
|
+
return { kind: "passthrough", raw: trimmed };
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// src/transport/ble.ts
|
|
757
|
+
var RELAI_UART_SERVICE = "0000ff00-0000-1000-8000-00805f9b34fb";
|
|
758
|
+
var RELAI_RX_CHAR = "0000ff02-0000-1000-8000-00805f9b34fb";
|
|
759
|
+
var RELAI_TX_CHAR = "0000ff03-0000-1000-8000-00805f9b34fb";
|
|
760
|
+
var MIN_MTU = 110;
|
|
761
|
+
var NOTIFY_TIMEOUT_MS = 8e3;
|
|
762
|
+
var BleTransport = class {
|
|
763
|
+
constructor(opts) {
|
|
764
|
+
this.devices = /* @__PURE__ */ new Map();
|
|
765
|
+
this.manager = opts.manager;
|
|
766
|
+
this.scanImpl = opts.scan;
|
|
767
|
+
this.notifyTimeoutMs = opts.notifyTimeoutMs ?? NOTIFY_TIMEOUT_MS;
|
|
768
|
+
}
|
|
769
|
+
scan() {
|
|
770
|
+
if (!this.scanImpl) {
|
|
771
|
+
return Promise.reject(new RelaiTransportError("No scan() provided to BleTransport; drive discovery from your app."));
|
|
772
|
+
}
|
|
773
|
+
return this.scanImpl();
|
|
774
|
+
}
|
|
775
|
+
async connect(parentBleId) {
|
|
776
|
+
let device = await this.manager.connectToDevice(parentBleId);
|
|
777
|
+
if (this.manager.discoverAllServicesAndCharacteristicsForDevice) {
|
|
778
|
+
device = await this.manager.discoverAllServicesAndCharacteristicsForDevice(device.id);
|
|
779
|
+
}
|
|
780
|
+
try {
|
|
781
|
+
device = await device.requestMTU(MIN_MTU);
|
|
782
|
+
} catch {
|
|
783
|
+
}
|
|
784
|
+
this.devices.set(device.id, device);
|
|
785
|
+
return { id: device.id, parentBleId, connectedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
786
|
+
}
|
|
787
|
+
async requestNonce(session) {
|
|
788
|
+
const line = await this.writeAndAwait(session, utf8ToBase64("CHALLENGE"));
|
|
789
|
+
const parsed = parseNotifyLine(line);
|
|
790
|
+
if (parsed.kind !== "nonce") {
|
|
791
|
+
throw new RelaiTransportError(`Expected NONCE from Parent, got: ${line}`);
|
|
792
|
+
}
|
|
793
|
+
return parsed.nonceB64Url;
|
|
794
|
+
}
|
|
795
|
+
async sendCommand(session, token) {
|
|
796
|
+
const line = await this.writeAndAwait(session, token, (p) => p.kind === "accept" || p.kind === "reject");
|
|
797
|
+
const parsed = parseNotifyLine(line);
|
|
798
|
+
if (parsed.kind === "accept") {
|
|
799
|
+
return { accepted: true, command: parsed.command, rejectReason: void 0, verbHint: void 0 };
|
|
800
|
+
}
|
|
801
|
+
if (parsed.kind === "reject") {
|
|
802
|
+
return { accepted: false, command: void 0, rejectReason: parsed.reason, verbHint: parsed.verbHint };
|
|
803
|
+
}
|
|
804
|
+
throw new RelaiTransportError(`Expected an [AUTH] ack, got: ${line}`);
|
|
805
|
+
}
|
|
806
|
+
readTelemetry(_session) {
|
|
807
|
+
return Promise.resolve({});
|
|
808
|
+
}
|
|
809
|
+
async disconnect(session) {
|
|
810
|
+
const device = this.devices.get(session.id);
|
|
811
|
+
if (device) {
|
|
812
|
+
await device.cancelConnection().catch(() => void 0);
|
|
813
|
+
this.devices.delete(session.id);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Write one value and await the first notify line that matches `accept` (the
|
|
818
|
+
* default accepts the first non-passthrough line). Ordinary command output is
|
|
819
|
+
* skipped via the passthrough filter so we lock onto the structured line.
|
|
820
|
+
*/
|
|
821
|
+
writeAndAwait(session, valueBase64, accept = (p) => p.kind !== "passthrough") {
|
|
822
|
+
const device = this.devices.get(session.id);
|
|
823
|
+
if (!device) return Promise.reject(new RelaiTransportError("Not connected."));
|
|
824
|
+
return new Promise((resolve, reject) => {
|
|
825
|
+
let settled = false;
|
|
826
|
+
const sub = device.monitorCharacteristicForService(RELAI_UART_SERVICE, RELAI_TX_CHAR, (error, ch) => {
|
|
827
|
+
if (settled) return;
|
|
828
|
+
if (error) {
|
|
829
|
+
settled = true;
|
|
830
|
+
clearTimeout(timer);
|
|
831
|
+
sub.remove();
|
|
832
|
+
reject(new RelaiTransportError(`BLE notify error: ${String(error)}`));
|
|
833
|
+
return;
|
|
834
|
+
}
|
|
835
|
+
const value = ch?.value;
|
|
836
|
+
if (!value) return;
|
|
837
|
+
let text;
|
|
838
|
+
try {
|
|
839
|
+
text = base64ToUtf8(value);
|
|
840
|
+
} catch {
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
if (accept(parseNotifyLine(text))) {
|
|
844
|
+
settled = true;
|
|
845
|
+
clearTimeout(timer);
|
|
846
|
+
sub.remove();
|
|
847
|
+
resolve(text);
|
|
848
|
+
}
|
|
849
|
+
});
|
|
850
|
+
const timer = setTimeout(() => {
|
|
851
|
+
if (settled) return;
|
|
852
|
+
settled = true;
|
|
853
|
+
sub.remove();
|
|
854
|
+
reject(new RelaiTransportError("Timed out waiting for the Parent's notify response."));
|
|
855
|
+
}, this.notifyTimeoutMs);
|
|
856
|
+
device.writeCharacteristicWithResponseForService(RELAI_UART_SERVICE, RELAI_RX_CHAR, valueBase64).catch((err) => {
|
|
857
|
+
if (settled) return;
|
|
858
|
+
settled = true;
|
|
859
|
+
clearTimeout(timer);
|
|
860
|
+
sub.remove();
|
|
861
|
+
reject(new RelaiTransportError(`BLE write failed: ${String(err)}`));
|
|
862
|
+
});
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
};
|
|
866
|
+
|
|
867
|
+
// src/webhooks.ts
|
|
868
|
+
async function verifyWebhook(input) {
|
|
869
|
+
const tolerance = input.toleranceSeconds ?? 300;
|
|
870
|
+
const now = input.nowSeconds ?? Math.floor(Date.now() / 1e3);
|
|
871
|
+
const parts = /* @__PURE__ */ new Map();
|
|
872
|
+
for (const kv of input.signature.split(",")) {
|
|
873
|
+
const [k, v] = kv.split("=", 2);
|
|
874
|
+
if (k && v) parts.set(k.trim(), v.trim());
|
|
875
|
+
}
|
|
876
|
+
const t = Number(parts.get("t"));
|
|
877
|
+
const v1 = parts.get("v1");
|
|
878
|
+
if (!Number.isFinite(t) || !v1) return false;
|
|
879
|
+
if (Math.abs(now - t) > tolerance) return false;
|
|
880
|
+
const crypto = globalThis.crypto;
|
|
881
|
+
if (!crypto?.subtle) throw new Error("WebCrypto unavailable; verifyWebhook requires Node 18+ or an edge runtime.");
|
|
882
|
+
const enc = new TextEncoder();
|
|
883
|
+
const key = await crypto.subtle.importKey("raw", enc.encode(input.secret), { name: "HMAC", hash: "SHA-256" }, false, [
|
|
884
|
+
"sign"
|
|
885
|
+
]);
|
|
886
|
+
const mac = await crypto.subtle.sign("HMAC", key, enc.encode(`${t}.${input.payload}`));
|
|
887
|
+
const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
888
|
+
if (expected.length !== v1.length) return false;
|
|
889
|
+
let diff = 0;
|
|
890
|
+
for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ v1.charCodeAt(i);
|
|
891
|
+
return diff === 0;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// src/types.ts
|
|
895
|
+
var Intents = {
|
|
896
|
+
Occupy: "occupy",
|
|
897
|
+
OccupyLongTerm: "occupy_long_term",
|
|
898
|
+
MakeAvailable: "make_available"
|
|
899
|
+
};
|
|
900
|
+
|
|
901
|
+
export { AccessLinksModule, AuthModule, BleTransport, ExchangeZonesModule, GrantsModule, Intents, MemoryTelemetryQueue, MemoryTokenStorage, OrdersModule, OverrideLinksModule, REJECT_REASONS, RELAI_RX_CHAR, RELAI_TX_CHAR, RELAI_UART_SERVICE, RecipientsModule, RelaiClient, SimAuthenticatedTransport, SimulatedTransport, StorageTelemetryQueue, TelemetryModule, TelemetryUploader, deliverOpen, parseNotifyLine, verifyWebhook };
|