@invonetwork/web-sdk 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,357 @@
1
+ 'use strict';
2
+
3
+ // src/shared/errors.ts
4
+ var InvoError = class _InvoError extends Error {
5
+ constructor(args) {
6
+ super(args.message);
7
+ this.name = "InvoError";
8
+ this.code = args.code;
9
+ this.status = args.status;
10
+ this.body = args.body ?? null;
11
+ Object.setPrototypeOf(this, _InvoError.prototype);
12
+ }
13
+ /** True if this is the "recipient isn't passkey-enrolled, fall back to claim code" signal. */
14
+ get isReceiverNotEnrolled() {
15
+ return this.code === "receiver_not_enrolled_use_claim_code" || /receiver_not_enrolled_use_claim_code/i.test(this.message);
16
+ }
17
+ /** True if the session/SDK token has expired and the caller should re-mint + retry. */
18
+ get isTokenExpired() {
19
+ return this.code === "SDK_TOKEN_EXPIRED";
20
+ }
21
+ };
22
+ function errorFromResponse(status, body) {
23
+ let message = `INVO request failed (HTTP ${status})`;
24
+ let code;
25
+ if (body && typeof body === "object") {
26
+ const b = body;
27
+ if (typeof b["code"] === "string") code = b["code"];
28
+ if (typeof b["error"] === "string") message = b["error"];
29
+ else if (typeof b["message"] === "string") message = b["message"];
30
+ } else if (typeof body === "string" && body.trim()) {
31
+ message = body;
32
+ }
33
+ return new InvoError({ message, code, status, body });
34
+ }
35
+
36
+ // src/shared/http.ts
37
+ var DEFAULT_TIMEOUT = 3e4;
38
+ function assertSecureBaseUrl(baseUrl) {
39
+ let u;
40
+ try {
41
+ u = new URL(baseUrl);
42
+ } catch {
43
+ throw new Error(`Invalid baseUrl: ${baseUrl}`);
44
+ }
45
+ const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
46
+ if (u.protocol === "https:" || u.protocol === "http:" && isLocal) return;
47
+ throw new Error(
48
+ `baseUrl must use https:// (got "${u.protocol}//"). Plaintext would expose the token/secret on the wire.`
49
+ );
50
+ }
51
+ var Http = class {
52
+ constructor(opts) {
53
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
54
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT;
55
+ const f = opts.fetchImpl ?? globalThis.fetch;
56
+ if (typeof f !== "function") {
57
+ throw new Error(
58
+ "No fetch implementation available. Use Node >=18, or pass `fetch` in the config."
59
+ );
60
+ }
61
+ this.fetchImpl = f;
62
+ this.userAgent = opts.userAgent;
63
+ }
64
+ async post(path, body, auth) {
65
+ return this.request("POST", path, body, auth);
66
+ }
67
+ async get(path, auth) {
68
+ return this.request("GET", path, void 0, auth);
69
+ }
70
+ authHeaders(auth) {
71
+ switch (auth.kind) {
72
+ case "game-secret":
73
+ return { "X-Game-Secret-Key": auth.secret };
74
+ case "bearer":
75
+ return { Authorization: `Bearer ${auth.token}` };
76
+ case "none":
77
+ return {};
78
+ }
79
+ }
80
+ async request(method, path, body, auth) {
81
+ const url = `${this.baseUrl}${path}`;
82
+ const headers = {
83
+ Accept: "application/json",
84
+ ...this.authHeaders(auth)
85
+ };
86
+ if (this.userAgent) headers["User-Agent"] = this.userAgent;
87
+ if (body !== void 0) headers["Content-Type"] = "application/json";
88
+ const controller = new AbortController();
89
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
90
+ let res;
91
+ try {
92
+ res = await this.fetchImpl(url, {
93
+ method,
94
+ headers,
95
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
96
+ signal: controller.signal
97
+ });
98
+ } catch (err) {
99
+ throw new InvoError({
100
+ message: err instanceof Error && err.name === "AbortError" ? `Request to ${path} timed out after ${this.timeoutMs}ms` : `Network error calling ${path}: ${err?.message ?? err}`,
101
+ status: 0,
102
+ body: null
103
+ });
104
+ } finally {
105
+ clearTimeout(timer);
106
+ }
107
+ const text = await res.text();
108
+ let parsed = null;
109
+ if (text) {
110
+ try {
111
+ parsed = JSON.parse(text);
112
+ } catch {
113
+ parsed = text;
114
+ }
115
+ }
116
+ if (!res.ok) throw errorFromResponse(res.status, parsed);
117
+ return parsed ?? {};
118
+ }
119
+ };
120
+
121
+ // src/shared/webauthn.ts
122
+ function b64urlToBuffer(value) {
123
+ const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
124
+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/") + pad;
125
+ const bin = atob(b64);
126
+ const bytes = new Uint8Array(bin.length);
127
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
128
+ return bytes.buffer;
129
+ }
130
+ function bufferToB64url(buf) {
131
+ const bytes = new Uint8Array(buf);
132
+ let bin = "";
133
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
134
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
135
+ }
136
+ function descriptorsToBinary(list) {
137
+ return (list ?? []).map((d) => {
138
+ const out = {
139
+ id: b64urlToBuffer(d.id),
140
+ type: d.type
141
+ };
142
+ if (d.transports) out.transports = d.transports;
143
+ return out;
144
+ });
145
+ }
146
+ function toCreationOptions(json) {
147
+ const opts = {
148
+ ...json,
149
+ challenge: b64urlToBuffer(json["challenge"]),
150
+ user: {
151
+ ...json["user"],
152
+ id: b64urlToBuffer(json["user"].id)
153
+ }
154
+ };
155
+ if (json["excludeCredentials"]) {
156
+ opts.excludeCredentials = descriptorsToBinary(json["excludeCredentials"]);
157
+ }
158
+ return opts;
159
+ }
160
+ function toRequestOptions(json) {
161
+ const opts = {
162
+ ...json,
163
+ challenge: b64urlToBuffer(json["challenge"])
164
+ };
165
+ if (json["allowCredentials"]) {
166
+ opts.allowCredentials = descriptorsToBinary(json["allowCredentials"]);
167
+ }
168
+ return opts;
169
+ }
170
+ function registrationToJSON(cred) {
171
+ const r = cred.response;
172
+ return {
173
+ id: cred.id,
174
+ rawId: bufferToB64url(cred.rawId),
175
+ type: cred.type,
176
+ authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
177
+ clientExtensionResults: cred.getClientExtensionResults(),
178
+ response: {
179
+ clientDataJSON: bufferToB64url(r.clientDataJSON),
180
+ attestationObject: bufferToB64url(r.attestationObject),
181
+ transports: typeof r.getTransports === "function" ? r.getTransports() : void 0
182
+ }
183
+ };
184
+ }
185
+ function assertionToJSON(cred) {
186
+ const r = cred.response;
187
+ return {
188
+ id: cred.id,
189
+ rawId: bufferToB64url(cred.rawId),
190
+ type: cred.type,
191
+ authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
192
+ clientExtensionResults: cred.getClientExtensionResults(),
193
+ response: {
194
+ clientDataJSON: bufferToB64url(r.clientDataJSON),
195
+ authenticatorData: bufferToB64url(r.authenticatorData),
196
+ signature: bufferToB64url(r.signature),
197
+ userHandle: r.userHandle ? bufferToB64url(r.userHandle) : null
198
+ }
199
+ };
200
+ }
201
+
202
+ // src/index.ts
203
+ var InvoClient = class {
204
+ constructor(config) {
205
+ if (!config.token) throw new Error("InvoClient requires a player `token`.");
206
+ if (!config.baseUrl) throw new Error("InvoClient requires a `baseUrl`.");
207
+ assertSecureBaseUrl(config.baseUrl);
208
+ this.http = new Http({
209
+ baseUrl: config.baseUrl,
210
+ timeoutMs: config.timeoutMs,
211
+ fetchImpl: config.fetch
212
+ // Browser: do NOT set User-Agent (forbidden header); the browser's own UA is fine.
213
+ });
214
+ this.auth = { kind: "bearer", token: config.token };
215
+ this.refreshToken = config.refreshToken;
216
+ }
217
+ assertWebAuthn() {
218
+ if (typeof navigator === "undefined" || !navigator.credentials) {
219
+ throw new Error("WebAuthn is not available in this environment (browser required).");
220
+ }
221
+ }
222
+ /** Enroll a passkey for the token's identity (register/begin -> create() -> register/complete). */
223
+ async enrollPasskey() {
224
+ this.assertWebAuthn();
225
+ return this.withTokenRetry(async () => {
226
+ const options = await this.post(
227
+ "/api/sdk/webauthn/register/begin"
228
+ );
229
+ const cred = await navigator.credentials.create({
230
+ publicKey: toCreationOptions(options)
231
+ });
232
+ if (!cred) throw new Error("Passkey creation was cancelled or returned no credential.");
233
+ const raw = await this.post(
234
+ "/api/sdk/webauthn/register/complete",
235
+ { credential: registrationToJSON(cred) }
236
+ );
237
+ return { status: String(raw["status"] ?? ""), device: raw["device"] ?? null, raw };
238
+ });
239
+ }
240
+ /** Approve a SEND with the player's passkey. */
241
+ async approveSend(transactionId) {
242
+ return this.approve("send", transactionId);
243
+ }
244
+ /** Approve a TRANSFER with the player's passkey (returns the sender's claim code). */
245
+ async approveTransfer(transactionId) {
246
+ return this.approve("transfers", transactionId);
247
+ }
248
+ /** Recipient self-claims a SEND with their passkey. */
249
+ async confirmReceiptSend(transactionId) {
250
+ return this.confirmReceipt("send", transactionId);
251
+ }
252
+ /** Recipient self-claims a TRANSFER with their passkey. */
253
+ async confirmReceiptTransfer(transactionId) {
254
+ return this.confirmReceipt("transfers", transactionId);
255
+ }
256
+ /**
257
+ * Interchangeable methods (§4.6): prove an *already-enrolled* method (e.g. the
258
+ * INVO app device key) to authorize adding a new partner passkey. The returned
259
+ * single-use grant lets a subsequent enrollPasskey() succeed instead of being
260
+ * blocked with ENROLLMENT_REQUIRES_PROOF.
261
+ *
262
+ * begin -> navigator.credentials.get() -> complete with { link_id, webauthn_assertion }.
263
+ */
264
+ async linkDevice(linkId) {
265
+ if (!linkId) throw new Error("linkDevice requires a `linkId`.");
266
+ return this.withTokenRetry(async () => {
267
+ const assertion = await this.runAssertion("/api/sdk/device/link/webauthn/begin", {
268
+ link_id: linkId
269
+ });
270
+ const raw = await this.post(
271
+ "/api/sdk/device/link/webauthn/complete",
272
+ { link_id: linkId, webauthn_assertion: assertion }
273
+ );
274
+ return { status: String(raw["status"] ?? ""), raw };
275
+ });
276
+ }
277
+ // --- internals ---
278
+ /** POST with the current player token. Token-expiry retry is handled one level
279
+ * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
280
+ async post(path, body) {
281
+ return this.http.post(path, body, this.auth);
282
+ }
283
+ /**
284
+ * Run a whole flow, retrying it ONCE if any call fails with SDK_TOKEN_EXPIRED
285
+ * and a `refreshToken` hook is configured. We re-run the entire begin→get→
286
+ * complete ceremony (not just the failed call) so the retry always uses a fresh,
287
+ * unconsumed challenge — never replaying a single-use WebAuthn assertion (§4.4).
288
+ * The refresh is single-flighted so concurrent expiries trigger one re-mint.
289
+ */
290
+ async withTokenRetry(run) {
291
+ try {
292
+ return await run();
293
+ } catch (err) {
294
+ if (err instanceof InvoError && err.isTokenExpired && await this.tryRefresh()) {
295
+ return await run();
296
+ }
297
+ throw err;
298
+ }
299
+ }
300
+ async tryRefresh() {
301
+ if (!this.refreshToken) return false;
302
+ if (!this.refreshInFlight) {
303
+ this.refreshInFlight = Promise.resolve(this.refreshToken()).finally(() => {
304
+ this.refreshInFlight = void 0;
305
+ });
306
+ }
307
+ const fresh = await this.refreshInFlight;
308
+ if (!fresh) return false;
309
+ this.auth = { kind: "bearer", token: fresh };
310
+ return true;
311
+ }
312
+ async runAssertion(beginPath, beginBody) {
313
+ this.assertWebAuthn();
314
+ const options = await this.post(beginPath, beginBody);
315
+ const cred = await navigator.credentials.get({
316
+ publicKey: toRequestOptions(options)
317
+ });
318
+ if (!cred) throw new Error("Passkey assertion was cancelled or returned no credential.");
319
+ return assertionToJSON(cred);
320
+ }
321
+ async approve(flow, transactionId) {
322
+ const id = encodeURIComponent(transactionId);
323
+ return this.withTokenRetry(async () => {
324
+ const assertion = await this.runAssertion(`/api/sdk/${flow}/${id}/approve/webauthn/begin`);
325
+ const raw = await this.post(
326
+ `/api/sdk/${flow}/${id}/approve`,
327
+ { webauthn_assertion: assertion }
328
+ );
329
+ return {
330
+ status: String(raw["status"] ?? ""),
331
+ next: String(raw["next"] ?? ""),
332
+ transactionId: String(raw["transaction_id"] ?? transactionId),
333
+ claimCode: raw["claim_code"],
334
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
335
+ raw
336
+ };
337
+ });
338
+ }
339
+ async confirmReceipt(flow, transactionId) {
340
+ const id = encodeURIComponent(transactionId);
341
+ return this.withTokenRetry(async () => {
342
+ const assertion = await this.runAssertion(
343
+ `/api/sdk/${flow}/${id}/confirm-receipt/webauthn/begin`
344
+ );
345
+ const raw = await this.post(
346
+ `/api/sdk/${flow}/${id}/confirm-receipt`,
347
+ { webauthn_assertion: assertion }
348
+ );
349
+ return { status: String(raw["status"] ?? ""), raw };
350
+ });
351
+ }
352
+ };
353
+
354
+ exports.InvoClient = InvoClient;
355
+ exports.InvoError = InvoError;
356
+ //# sourceMappingURL=index.cjs.map
357
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,52 @@
1
+ import { C as ClientConfig, A as ApproveResult, a as ConfirmReceiptResult, L as LinkDeviceResult } from './errors-B7rVID2r.cjs';
2
+ export { I as InvoError, R as Rail, V as VerificationMethod } from './errors-B7rVID2r.cjs';
3
+
4
+ declare class InvoClient {
5
+ private readonly http;
6
+ private auth;
7
+ private readonly refreshToken;
8
+ /** In-flight refresh, shared so concurrent expiries trigger a single re-mint. */
9
+ private refreshInFlight;
10
+ constructor(config: ClientConfig);
11
+ private assertWebAuthn;
12
+ /** Enroll a passkey for the token's identity (register/begin -> create() -> register/complete). */
13
+ enrollPasskey(): Promise<{
14
+ status: string;
15
+ device: unknown;
16
+ raw: Record<string, unknown>;
17
+ }>;
18
+ /** Approve a SEND with the player's passkey. */
19
+ approveSend(transactionId: string): Promise<ApproveResult>;
20
+ /** Approve a TRANSFER with the player's passkey (returns the sender's claim code). */
21
+ approveTransfer(transactionId: string): Promise<ApproveResult>;
22
+ /** Recipient self-claims a SEND with their passkey. */
23
+ confirmReceiptSend(transactionId: string): Promise<ConfirmReceiptResult>;
24
+ /** Recipient self-claims a TRANSFER with their passkey. */
25
+ confirmReceiptTransfer(transactionId: string): Promise<ConfirmReceiptResult>;
26
+ /**
27
+ * Interchangeable methods (§4.6): prove an *already-enrolled* method (e.g. the
28
+ * INVO app device key) to authorize adding a new partner passkey. The returned
29
+ * single-use grant lets a subsequent enrollPasskey() succeed instead of being
30
+ * blocked with ENROLLMENT_REQUIRES_PROOF.
31
+ *
32
+ * begin -> navigator.credentials.get() -> complete with { link_id, webauthn_assertion }.
33
+ */
34
+ linkDevice(linkId: string): Promise<LinkDeviceResult>;
35
+ /** POST with the current player token. Token-expiry retry is handled one level
36
+ * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
37
+ private post;
38
+ /**
39
+ * Run a whole flow, retrying it ONCE if any call fails with SDK_TOKEN_EXPIRED
40
+ * and a `refreshToken` hook is configured. We re-run the entire begin→get→
41
+ * complete ceremony (not just the failed call) so the retry always uses a fresh,
42
+ * unconsumed challenge — never replaying a single-use WebAuthn assertion (§4.4).
43
+ * The refresh is single-flighted so concurrent expiries trigger one re-mint.
44
+ */
45
+ private withTokenRetry;
46
+ private tryRefresh;
47
+ private runAssertion;
48
+ private approve;
49
+ private confirmReceipt;
50
+ }
51
+
52
+ export { ApproveResult, ClientConfig, ConfirmReceiptResult, InvoClient, LinkDeviceResult };
@@ -0,0 +1,52 @@
1
+ import { C as ClientConfig, A as ApproveResult, a as ConfirmReceiptResult, L as LinkDeviceResult } from './errors-B7rVID2r.js';
2
+ export { I as InvoError, R as Rail, V as VerificationMethod } from './errors-B7rVID2r.js';
3
+
4
+ declare class InvoClient {
5
+ private readonly http;
6
+ private auth;
7
+ private readonly refreshToken;
8
+ /** In-flight refresh, shared so concurrent expiries trigger a single re-mint. */
9
+ private refreshInFlight;
10
+ constructor(config: ClientConfig);
11
+ private assertWebAuthn;
12
+ /** Enroll a passkey for the token's identity (register/begin -> create() -> register/complete). */
13
+ enrollPasskey(): Promise<{
14
+ status: string;
15
+ device: unknown;
16
+ raw: Record<string, unknown>;
17
+ }>;
18
+ /** Approve a SEND with the player's passkey. */
19
+ approveSend(transactionId: string): Promise<ApproveResult>;
20
+ /** Approve a TRANSFER with the player's passkey (returns the sender's claim code). */
21
+ approveTransfer(transactionId: string): Promise<ApproveResult>;
22
+ /** Recipient self-claims a SEND with their passkey. */
23
+ confirmReceiptSend(transactionId: string): Promise<ConfirmReceiptResult>;
24
+ /** Recipient self-claims a TRANSFER with their passkey. */
25
+ confirmReceiptTransfer(transactionId: string): Promise<ConfirmReceiptResult>;
26
+ /**
27
+ * Interchangeable methods (§4.6): prove an *already-enrolled* method (e.g. the
28
+ * INVO app device key) to authorize adding a new partner passkey. The returned
29
+ * single-use grant lets a subsequent enrollPasskey() succeed instead of being
30
+ * blocked with ENROLLMENT_REQUIRES_PROOF.
31
+ *
32
+ * begin -> navigator.credentials.get() -> complete with { link_id, webauthn_assertion }.
33
+ */
34
+ linkDevice(linkId: string): Promise<LinkDeviceResult>;
35
+ /** POST with the current player token. Token-expiry retry is handled one level
36
+ * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
37
+ private post;
38
+ /**
39
+ * Run a whole flow, retrying it ONCE if any call fails with SDK_TOKEN_EXPIRED
40
+ * and a `refreshToken` hook is configured. We re-run the entire begin→get→
41
+ * complete ceremony (not just the failed call) so the retry always uses a fresh,
42
+ * unconsumed challenge — never replaying a single-use WebAuthn assertion (§4.4).
43
+ * The refresh is single-flighted so concurrent expiries trigger one re-mint.
44
+ */
45
+ private withTokenRetry;
46
+ private tryRefresh;
47
+ private runAssertion;
48
+ private approve;
49
+ private confirmReceipt;
50
+ }
51
+
52
+ export { ApproveResult, ClientConfig, ConfirmReceiptResult, InvoClient, LinkDeviceResult };