@invonetwork/web-sdk 3.29.1 → 3.30.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1442 -1397
- package/README.md +2954 -2923
- package/dist/chunk-3ECVREIM.js +6 -0
- package/dist/chunk-7O5JT3LK.js +1590 -0
- package/dist/{chunk-VP3OK4J4.js → chunk-TCT2QSVB.js} +515 -3
- package/dist/{chunk-YONO4JE5.js → chunk-V2RQYQQD.js} +44 -5
- package/dist/game-server.cjs +387 -42
- package/dist/game-server.d.cts +42 -6
- package/dist/game-server.d.ts +42 -6
- package/dist/game-server.js +286 -8
- package/dist/game.cjs +2677 -9
- package/dist/game.d.cts +78 -4
- package/dist/game.d.ts +78 -4
- package/dist/game.js +558 -3
- package/dist/hosted-approval-DcY4U2RN.d.cts +96 -0
- package/dist/hosted-approval-DiKmtjEh.d.ts +96 -0
- package/dist/index.d.cts +7 -96
- package/dist/index.d.ts +7 -96
- package/dist/index.js +2 -1635
- package/dist/loyalty-events-CmDw2ZoR.d.cts +40 -0
- package/dist/loyalty-events-CmDw2ZoR.d.ts +40 -0
- package/dist/{server-Bxo_wgHx.d.cts → server-BAOn3KH3.d.cts} +28 -2
- package/dist/{server-BYY6tM6X.d.ts → server-DHmQU1eN.d.ts} +28 -2
- package/dist/server.cjs +106 -40
- package/dist/server.d.cts +4 -3
- package/dist/server.d.ts +4 -3
- package/dist/server.js +3 -4
- package/dist/{types-_lIm74kd.d.cts → types-BTbZicgj.d.cts} +1 -40
- package/dist/{types-_lIm74kd.d.ts → types-BTbZicgj.d.ts} +1 -40
- package/dist/{types-CLyJDuXd.d.cts → types-jUxfYjiD.d.cts} +64 -1
- package/dist/{types-CLyJDuXd.d.ts → types-jUxfYjiD.d.ts} +64 -1
- package/dist/{version-DOaYbHu7.d.cts → version-CR7XECyP.d.cts} +1 -1
- package/dist/{version-DOaYbHu7.d.ts → version-CR7XECyP.d.ts} +1 -1
- package/package.json +91 -91
- package/dist/chunk-6CN236QH.js +0 -473
- package/dist/chunk-VOGZZ6QS.js +0 -6
package/dist/index.js
CHANGED
|
@@ -1,1637 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
export { phoneChangeSignalMessage } from './chunk-
|
|
3
|
-
import { InvoError, buildGameEventBody, toReportGameEventResult } from './chunk-VP3OK4J4.js';
|
|
4
|
-
export { InvoError } from './chunk-VP3OK4J4.js';
|
|
5
|
-
|
|
6
|
-
// src/shared/webauthn.ts
|
|
7
|
-
function malformedOptions(field) {
|
|
8
|
-
return new InvoError({
|
|
9
|
-
message: `Malformed WebAuthn options from the backend: missing/invalid \`${field}\`.`,
|
|
10
|
-
code: "WEBAUTHN_OPTIONS_MALFORMED",
|
|
11
|
-
status: 0
|
|
12
|
-
});
|
|
13
|
-
}
|
|
14
|
-
function b64urlToBuffer(value) {
|
|
15
|
-
const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
|
|
16
|
-
const b64 = value.replace(/-/g, "+").replace(/_/g, "/") + pad;
|
|
17
|
-
const bin = atob(b64);
|
|
18
|
-
const bytes = new Uint8Array(bin.length);
|
|
19
|
-
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
|
20
|
-
return bytes.buffer;
|
|
21
|
-
}
|
|
22
|
-
function bufferToB64url(buf) {
|
|
23
|
-
const bytes = new Uint8Array(buf);
|
|
24
|
-
let bin = "";
|
|
25
|
-
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
|
26
|
-
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
27
|
-
}
|
|
28
|
-
function descriptorsToBinary(list) {
|
|
29
|
-
return (list ?? []).map((d) => {
|
|
30
|
-
const out = {
|
|
31
|
-
id: b64urlToBuffer(d.id),
|
|
32
|
-
type: d.type
|
|
33
|
-
};
|
|
34
|
-
if (d.transports) out.transports = d.transports;
|
|
35
|
-
return out;
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
function toCreationOptions(json) {
|
|
39
|
-
if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
|
|
40
|
-
if (typeof json["user"]?.id !== "string") throw malformedOptions("user.id");
|
|
41
|
-
const opts = {
|
|
42
|
-
...json,
|
|
43
|
-
challenge: b64urlToBuffer(json["challenge"]),
|
|
44
|
-
user: {
|
|
45
|
-
...json["user"],
|
|
46
|
-
id: b64urlToBuffer(json["user"].id)
|
|
47
|
-
}
|
|
48
|
-
};
|
|
49
|
-
if (json["excludeCredentials"]) {
|
|
50
|
-
opts.excludeCredentials = descriptorsToBinary(json["excludeCredentials"]);
|
|
51
|
-
}
|
|
52
|
-
return opts;
|
|
53
|
-
}
|
|
54
|
-
function toRequestOptions(json) {
|
|
55
|
-
if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
|
|
56
|
-
const opts = {
|
|
57
|
-
...json,
|
|
58
|
-
challenge: b64urlToBuffer(json["challenge"])
|
|
59
|
-
};
|
|
60
|
-
if (json["allowCredentials"]) {
|
|
61
|
-
opts.allowCredentials = descriptorsToBinary(json["allowCredentials"]);
|
|
62
|
-
}
|
|
63
|
-
return opts;
|
|
64
|
-
}
|
|
65
|
-
function registrationToJSON(cred) {
|
|
66
|
-
const r = cred.response;
|
|
67
|
-
return {
|
|
68
|
-
id: cred.id,
|
|
69
|
-
rawId: bufferToB64url(cred.rawId),
|
|
70
|
-
type: cred.type,
|
|
71
|
-
authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
|
|
72
|
-
clientExtensionResults: cred.getClientExtensionResults(),
|
|
73
|
-
response: {
|
|
74
|
-
clientDataJSON: bufferToB64url(r.clientDataJSON),
|
|
75
|
-
attestationObject: bufferToB64url(r.attestationObject),
|
|
76
|
-
transports: typeof r.getTransports === "function" ? r.getTransports() : void 0
|
|
77
|
-
}
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
function assertionToJSON(cred) {
|
|
81
|
-
const r = cred.response;
|
|
82
|
-
return {
|
|
83
|
-
id: cred.id,
|
|
84
|
-
rawId: bufferToB64url(cred.rawId),
|
|
85
|
-
type: cred.type,
|
|
86
|
-
authenticatorAttachment: cred.authenticatorAttachment ?? void 0,
|
|
87
|
-
clientExtensionResults: cred.getClientExtensionResults(),
|
|
88
|
-
response: {
|
|
89
|
-
clientDataJSON: bufferToB64url(r.clientDataJSON),
|
|
90
|
-
authenticatorData: bufferToB64url(r.authenticatorData),
|
|
91
|
-
signature: bufferToB64url(r.signature),
|
|
92
|
-
userHandle: r.userHandle ? bufferToB64url(r.userHandle) : null
|
|
93
|
-
}
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// src/shared/hosted-approval.ts
|
|
98
|
-
var HOSTED_FLOWS = [
|
|
99
|
-
"transfer",
|
|
100
|
-
"send",
|
|
101
|
-
"send_receipt",
|
|
102
|
-
"transfer_receipt"
|
|
103
|
-
];
|
|
104
|
-
var HOSTED_MESSAGE_TYPE = "invo.approval";
|
|
105
|
-
var MAX_EXPIRES_IN_S = 24 * 24 * 60 * 60;
|
|
106
|
-
var CONFIRM_QUIET_CODES = /* @__PURE__ */ new Set([
|
|
107
|
-
"DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED",
|
|
108
|
-
"DEVICE_APPROVAL_NO_ENROLLMENT_PENDING"
|
|
109
|
-
]);
|
|
110
|
-
var MAX_TRANSIENT_POLL_FAILURES = 5;
|
|
111
|
-
function derivePlatformOrigin(verificationUriComplete, explicit) {
|
|
112
|
-
let u;
|
|
113
|
-
try {
|
|
114
|
-
u = new URL(verificationUriComplete);
|
|
115
|
-
} catch {
|
|
116
|
-
throw new InvoError({
|
|
117
|
-
message: "begin returned no absolute verification_uri_complete.",
|
|
118
|
-
code: "UNEXPECTED_RESPONSE",
|
|
119
|
-
status: 0
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
|
|
123
|
-
if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
|
|
124
|
-
throw new InvoError({
|
|
125
|
-
message: "The hosted approval page must be https (plaintext would let any page forge the wake-up).",
|
|
126
|
-
code: "INVALID_INPUT",
|
|
127
|
-
status: 0
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
if (explicit !== void 0 && u.origin !== explicit) {
|
|
131
|
-
throw new InvoError({
|
|
132
|
-
message: `platformOrigin (${explicit}) does not match the hosted page's origin (${u.origin}).`,
|
|
133
|
-
code: "INVALID_INPUT",
|
|
134
|
-
status: 0
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
return u.origin;
|
|
138
|
-
}
|
|
139
|
-
function normalizeEnrollment(input) {
|
|
140
|
-
if (!input || typeof input !== "object") return null;
|
|
141
|
-
const state = typeof input.state === "string" ? input.state : "";
|
|
142
|
-
if (!state) return null;
|
|
143
|
-
const label = input.device_label ?? input.deviceLabel;
|
|
144
|
-
const code = input.match_code ?? input.matchCode;
|
|
145
|
-
const at = input.requested_at ?? input.requestedAt;
|
|
146
|
-
return {
|
|
147
|
-
state,
|
|
148
|
-
deviceLabel: typeof label === "string" && label ? label : "your phone",
|
|
149
|
-
matchCode: typeof code === "string" ? code : "",
|
|
150
|
-
requestedAt: typeof at === "string" ? at : void 0,
|
|
151
|
-
raw: input
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
var BRAND = "#4f46e5";
|
|
155
|
-
var FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
|
|
156
|
-
var MONO = "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace";
|
|
157
|
-
var PROMPT_IDS = {
|
|
158
|
-
root: "invo-hosted-enrollment",
|
|
159
|
-
title: "invo-hosted-enrollment-title",
|
|
160
|
-
code: "invo-hosted-enrollment-code",
|
|
161
|
-
yes: "invo-hosted-enrollment-yes",
|
|
162
|
-
no: "invo-hosted-enrollment-no",
|
|
163
|
-
stop: "invo-hosted-enrollment-stop",
|
|
164
|
-
error: "invo-hosted-enrollment-error"
|
|
165
|
-
};
|
|
166
|
-
var HostedEnrollmentPrompt = class {
|
|
167
|
-
constructor() {
|
|
168
|
-
this.handlers = { respond: async () => {
|
|
169
|
-
}, renderPrompt: true };
|
|
170
|
-
this.enrollment = null;
|
|
171
|
-
/** The last match code the player answered, so a stale poll can't re-ask it. */
|
|
172
|
-
this.decided = null;
|
|
173
|
-
this.root = null;
|
|
174
|
-
this.previousFocus = null;
|
|
175
|
-
this.keyHandler = null;
|
|
176
|
-
this.busy = false;
|
|
177
|
-
}
|
|
178
|
-
get current() {
|
|
179
|
-
return this.enrollment;
|
|
180
|
-
}
|
|
181
|
-
configure(handlers) {
|
|
182
|
-
this.handlers = handlers;
|
|
183
|
-
this.decided = null;
|
|
184
|
-
if (this.enrollment) this.render();
|
|
185
|
-
}
|
|
186
|
-
update(input) {
|
|
187
|
-
let next = normalizeEnrollment(input);
|
|
188
|
-
if (next && next.state === "awaiting_screen" && this.decided && this.decided.code === next.matchCode) {
|
|
189
|
-
next = this.decided.decision === "approve" ? { ...next, state: "confirmed" } : null;
|
|
190
|
-
}
|
|
191
|
-
const changed = this.enrollment === null !== (next === null) || this.enrollment && next && (this.enrollment.state !== next.state || this.enrollment.matchCode !== next.matchCode || this.enrollment.deviceLabel !== next.deviceLabel);
|
|
192
|
-
this.enrollment = next;
|
|
193
|
-
if (changed) this.handlers.onEnrollment?.(next, this.handlers.respond);
|
|
194
|
-
this.render();
|
|
195
|
-
}
|
|
196
|
-
clear() {
|
|
197
|
-
this.update(null);
|
|
198
|
-
}
|
|
199
|
-
// --- rendering ---
|
|
200
|
-
render() {
|
|
201
|
-
if (typeof document === "undefined") return;
|
|
202
|
-
const e = this.enrollment;
|
|
203
|
-
const visible = this.handlers.renderPrompt && e && (e.state === "awaiting_screen" || e.state === "confirmed");
|
|
204
|
-
if (!visible || !e) {
|
|
205
|
-
this.unmount();
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
this.mount();
|
|
209
|
-
const root = this.root;
|
|
210
|
-
root.innerHTML = "";
|
|
211
|
-
root.appendChild(e.state === "awaiting_screen" ? this.buildPrompt(e) : this.buildFinishing(e));
|
|
212
|
-
this.focusInitial(e.state);
|
|
213
|
-
}
|
|
214
|
-
mount() {
|
|
215
|
-
if (this.root) return;
|
|
216
|
-
this.previousFocus = document.activeElement;
|
|
217
|
-
const overlay = document.createElement("div");
|
|
218
|
-
overlay.id = PROMPT_IDS.root;
|
|
219
|
-
overlay.setAttribute("role", "dialog");
|
|
220
|
-
overlay.setAttribute("aria-modal", "true");
|
|
221
|
-
overlay.setAttribute("aria-labelledby", PROMPT_IDS.title);
|
|
222
|
-
overlay.tabIndex = -1;
|
|
223
|
-
overlay.style.cssText = [
|
|
224
|
-
"position:fixed",
|
|
225
|
-
"inset:0",
|
|
226
|
-
"z-index:2147483000",
|
|
227
|
-
"display:flex",
|
|
228
|
-
"align-items:center",
|
|
229
|
-
"justify-content:center",
|
|
230
|
-
"padding:16px",
|
|
231
|
-
"background:rgba(17,24,39,.55)",
|
|
232
|
-
`font-family:${FONT}`,
|
|
233
|
-
"color:#111827",
|
|
234
|
-
"-webkit-font-smoothing:antialiased",
|
|
235
|
-
"outline:none"
|
|
236
|
-
].join(";");
|
|
237
|
-
this.keyHandler = (ev) => this.onKeyDown(ev);
|
|
238
|
-
overlay.addEventListener("keydown", this.keyHandler);
|
|
239
|
-
document.body.appendChild(overlay);
|
|
240
|
-
this.root = overlay;
|
|
241
|
-
}
|
|
242
|
-
unmount() {
|
|
243
|
-
if (!this.root) return;
|
|
244
|
-
if (this.keyHandler) this.root.removeEventListener("keydown", this.keyHandler);
|
|
245
|
-
this.root.remove();
|
|
246
|
-
this.root = null;
|
|
247
|
-
this.keyHandler = null;
|
|
248
|
-
this.busy = false;
|
|
249
|
-
const prev = this.previousFocus;
|
|
250
|
-
this.previousFocus = null;
|
|
251
|
-
if (prev && typeof prev.focus === "function") {
|
|
252
|
-
try {
|
|
253
|
-
prev.focus();
|
|
254
|
-
} catch {
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
card() {
|
|
259
|
-
const card = document.createElement("div");
|
|
260
|
-
card.style.cssText = [
|
|
261
|
-
"background:#ffffff",
|
|
262
|
-
"border-radius:16px",
|
|
263
|
-
"box-shadow:0 20px 60px rgba(17,24,39,.25)",
|
|
264
|
-
"max-width:420px",
|
|
265
|
-
"width:100%",
|
|
266
|
-
"padding:28px 28px 24px",
|
|
267
|
-
"box-sizing:border-box",
|
|
268
|
-
"text-align:center"
|
|
269
|
-
].join(";");
|
|
270
|
-
const mark = document.createElement("div");
|
|
271
|
-
mark.textContent = "INVO";
|
|
272
|
-
mark.setAttribute("aria-hidden", "true");
|
|
273
|
-
mark.style.cssText = `font-weight:800;letter-spacing:.18em;font-size:13px;color:${BRAND};margin-bottom:14px`;
|
|
274
|
-
card.appendChild(mark);
|
|
275
|
-
return card;
|
|
276
|
-
}
|
|
277
|
-
button(id, label, primary) {
|
|
278
|
-
const b = document.createElement("button");
|
|
279
|
-
b.type = "button";
|
|
280
|
-
b.id = id;
|
|
281
|
-
b.textContent = label;
|
|
282
|
-
b.style.cssText = [
|
|
283
|
-
"display:block",
|
|
284
|
-
"width:100%",
|
|
285
|
-
"box-sizing:border-box",
|
|
286
|
-
"border-radius:10px",
|
|
287
|
-
"padding:12px 16px",
|
|
288
|
-
"font:inherit",
|
|
289
|
-
"font-size:15px",
|
|
290
|
-
"font-weight:600",
|
|
291
|
-
"cursor:pointer",
|
|
292
|
-
"margin-top:10px",
|
|
293
|
-
primary ? `background:${BRAND};color:#ffffff;border:1px solid ${BRAND}` : "background:#ffffff;color:#374151;border:1px solid #d1d5db"
|
|
294
|
-
].join(";");
|
|
295
|
-
return b;
|
|
296
|
-
}
|
|
297
|
-
buildPrompt(e) {
|
|
298
|
-
const card = this.card();
|
|
299
|
-
const title = document.createElement("h2");
|
|
300
|
-
title.id = PROMPT_IDS.title;
|
|
301
|
-
title.textContent = `Set up INVO on ${e.deviceLabel}?`;
|
|
302
|
-
title.style.cssText = "margin:0 0 14px;font-size:20px;font-weight:700;line-height:1.3";
|
|
303
|
-
card.appendChild(title);
|
|
304
|
-
const codeLabel = document.createElement("div");
|
|
305
|
-
codeLabel.textContent = "Code";
|
|
306
|
-
codeLabel.style.cssText = "font-size:12px;text-transform:uppercase;letter-spacing:.12em;color:#6b7280";
|
|
307
|
-
card.appendChild(codeLabel);
|
|
308
|
-
const code = document.createElement("div");
|
|
309
|
-
code.id = PROMPT_IDS.code;
|
|
310
|
-
code.textContent = e.matchCode;
|
|
311
|
-
code.setAttribute("aria-label", `Code ${e.matchCode.split("").join(" ")}`);
|
|
312
|
-
code.style.cssText = [
|
|
313
|
-
`font-family:${MONO}`,
|
|
314
|
-
"font-size:40px",
|
|
315
|
-
"font-weight:700",
|
|
316
|
-
"letter-spacing:.3em",
|
|
317
|
-
"text-indent:.3em",
|
|
318
|
-
"line-height:1.2",
|
|
319
|
-
"margin:6px 0 16px",
|
|
320
|
-
"color:#111827",
|
|
321
|
-
"background:#f3f4f6",
|
|
322
|
-
"border-radius:12px",
|
|
323
|
-
"padding:14px 8px"
|
|
324
|
-
].join(";");
|
|
325
|
-
card.appendChild(code);
|
|
326
|
-
const body = document.createElement("p");
|
|
327
|
-
body.textContent = "Say Yes only if the phone you just scanned/opened shows this code.";
|
|
328
|
-
body.style.cssText = "margin:0 0 6px;font-size:15px;line-height:1.5;color:#374151";
|
|
329
|
-
card.appendChild(body);
|
|
330
|
-
const err = document.createElement("div");
|
|
331
|
-
err.id = PROMPT_IDS.error;
|
|
332
|
-
err.setAttribute("role", "alert");
|
|
333
|
-
err.style.cssText = "min-height:18px;font-size:13px;color:#b91c1c;margin-top:4px";
|
|
334
|
-
card.appendChild(err);
|
|
335
|
-
const yes = this.button(PROMPT_IDS.yes, "Yes, it shows this code", true);
|
|
336
|
-
yes.addEventListener("click", () => void this.decide("approve"));
|
|
337
|
-
card.appendChild(yes);
|
|
338
|
-
const no = this.button(PROMPT_IDS.no, "No, that is not my phone", false);
|
|
339
|
-
no.addEventListener("click", () => void this.decide("deny"));
|
|
340
|
-
card.appendChild(no);
|
|
341
|
-
return card;
|
|
342
|
-
}
|
|
343
|
-
buildFinishing(e) {
|
|
344
|
-
const card = this.card();
|
|
345
|
-
card.style.padding = "18px 22px";
|
|
346
|
-
const row = document.createElement("div");
|
|
347
|
-
row.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap";
|
|
348
|
-
const text = document.createElement("div");
|
|
349
|
-
text.id = PROMPT_IDS.title;
|
|
350
|
-
text.textContent = `Finishing on ${e.deviceLabel}\u2026`;
|
|
351
|
-
text.tabIndex = -1;
|
|
352
|
-
text.setAttribute("aria-live", "polite");
|
|
353
|
-
text.style.cssText = "font-size:15px;color:#374151;outline:none";
|
|
354
|
-
row.appendChild(text);
|
|
355
|
-
const stop = document.createElement("button");
|
|
356
|
-
stop.type = "button";
|
|
357
|
-
stop.id = PROMPT_IDS.stop;
|
|
358
|
-
stop.textContent = "Stop it, wrong code";
|
|
359
|
-
stop.style.cssText = `background:none;border:0;padding:6px 0;font:inherit;font-size:14px;font-weight:600;color:${BRAND};cursor:pointer;text-decoration:underline`;
|
|
360
|
-
stop.addEventListener("click", () => void this.decide("deny"));
|
|
361
|
-
row.appendChild(stop);
|
|
362
|
-
card.appendChild(row);
|
|
363
|
-
return card;
|
|
364
|
-
}
|
|
365
|
-
async decide(decision) {
|
|
366
|
-
if (this.busy || !this.enrollment) return;
|
|
367
|
-
this.busy = true;
|
|
368
|
-
this.root?.focus();
|
|
369
|
-
this.setButtonsDisabled(true);
|
|
370
|
-
try {
|
|
371
|
-
await this.handlers.respond(decision);
|
|
372
|
-
const now = this.enrollment;
|
|
373
|
-
if (!now) return;
|
|
374
|
-
this.decided = { code: now.matchCode, decision };
|
|
375
|
-
if (decision === "deny") {
|
|
376
|
-
this.update(null);
|
|
377
|
-
} else if (now.state === "awaiting_screen") {
|
|
378
|
-
this.update({ ...now.raw, state: "confirmed" });
|
|
379
|
-
}
|
|
380
|
-
} catch (err) {
|
|
381
|
-
const box = this.root?.querySelector(`#${PROMPT_IDS.error}`);
|
|
382
|
-
if (box) {
|
|
383
|
-
box.textContent = err instanceof Error && err.message ? `Couldn't send your answer: ${err.message}` : "Couldn't send your answer. Try again.";
|
|
384
|
-
}
|
|
385
|
-
} finally {
|
|
386
|
-
this.busy = false;
|
|
387
|
-
this.setButtonsDisabled(false);
|
|
388
|
-
if (this.root && this.enrollment?.state === "awaiting_screen") this.focusInitial("awaiting_screen");
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
setButtonsDisabled(disabled) {
|
|
392
|
-
this.root?.querySelectorAll("button").forEach((b) => {
|
|
393
|
-
b.disabled = disabled;
|
|
394
|
-
});
|
|
395
|
-
}
|
|
396
|
-
focusables() {
|
|
397
|
-
if (!this.root) return [];
|
|
398
|
-
return Array.from(this.root.querySelectorAll("button:not([disabled])"));
|
|
399
|
-
}
|
|
400
|
-
/** Prompt: first button. Finishing row: the text, NOT "Stop it" — a stray Enter must not deny. */
|
|
401
|
-
focusInitial(state) {
|
|
402
|
-
const target = state === "confirmed" ? this.root?.querySelector(`#${PROMPT_IDS.title}`) : this.focusables()[0];
|
|
403
|
-
try {
|
|
404
|
-
(target ?? this.root)?.focus();
|
|
405
|
-
} catch {
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
onKeyDown(ev) {
|
|
409
|
-
if (ev.key === "Escape") {
|
|
410
|
-
ev.preventDefault();
|
|
411
|
-
void this.decide("deny");
|
|
412
|
-
return;
|
|
413
|
-
}
|
|
414
|
-
if (ev.key !== "Tab") return;
|
|
415
|
-
ev.preventDefault();
|
|
416
|
-
const items = this.focusables();
|
|
417
|
-
if (items.length === 0) {
|
|
418
|
-
this.root?.focus();
|
|
419
|
-
return;
|
|
420
|
-
}
|
|
421
|
-
const active = document.activeElement;
|
|
422
|
-
const idx = items.indexOf(active);
|
|
423
|
-
let nextIdx;
|
|
424
|
-
if (idx === -1) nextIdx = ev.shiftKey ? items.length - 1 : 0;
|
|
425
|
-
else nextIdx = (idx + (ev.shiftKey ? -1 : 1) + items.length) % items.length;
|
|
426
|
-
items[nextIdx].focus();
|
|
427
|
-
}
|
|
428
|
-
};
|
|
429
|
-
var COOP_HINT = "The popup was severed from this window as soon as INVO's page loaded. Your page most likely sends `Cross-Origin-Opener-Policy: same-origin`; use `same-origin-allow-popups` so the hosted page can reach window.opener. The grant is still live: the device_approval.approved webhook will tell your server.";
|
|
430
|
-
var BLOCKED_HINT = "The browser blocked the popup. Nothing was started \u2014 call approveHosted() from a click handler.";
|
|
431
|
-
function pollToken(err) {
|
|
432
|
-
if (!(err instanceof InvoError) || err.status === 0 || err.status === 429 || err.status >= 500) return null;
|
|
433
|
-
const body = err.body && typeof err.body === "object" ? err.body : {};
|
|
434
|
-
const token = typeof body["error"] === "string" ? body["error"] : "";
|
|
435
|
-
return { token, body };
|
|
436
|
-
}
|
|
437
|
-
async function runHostedApproval(opts, api, deps = {}) {
|
|
438
|
-
if (typeof window === "undefined") {
|
|
439
|
-
throw new InvoError({
|
|
440
|
-
message: "approveHosted requires a browser window.",
|
|
441
|
-
code: "DOM_UNAVAILABLE",
|
|
442
|
-
status: 0
|
|
443
|
-
});
|
|
444
|
-
}
|
|
445
|
-
if (!opts.transactionId || !String(opts.transactionId).trim()) {
|
|
446
|
-
throw new Error("approveHosted requires a `transactionId`.");
|
|
447
|
-
}
|
|
448
|
-
if (!HOSTED_FLOWS.includes(opts.flow)) {
|
|
449
|
-
throw new Error(`approveHosted: unknown flow "${String(opts.flow)}" (expected ${HOSTED_FLOWS.join(" | ")}).`);
|
|
450
|
-
}
|
|
451
|
-
if (opts.renderPrompt !== false && typeof document === "undefined") {
|
|
452
|
-
throw new InvoError({
|
|
453
|
-
message: "approveHosted needs a DOM to render the match-code prompt (or pass renderPrompt:false).",
|
|
454
|
-
code: "DOM_UNAVAILABLE",
|
|
455
|
-
status: 0
|
|
456
|
-
});
|
|
457
|
-
}
|
|
458
|
-
const signal = opts.signal;
|
|
459
|
-
if (signal?.aborted) return { status: "closed", popupBlocked: false };
|
|
460
|
-
const open = deps.open ?? ((u, n, f) => window.open(u, n, f));
|
|
461
|
-
const navigate = deps.navigate ?? ((u) => window.location.assign(u));
|
|
462
|
-
const closedPollMs = deps.closedPollMs ?? 500;
|
|
463
|
-
const coopGraceMs = deps.coopGraceMs ?? 1500;
|
|
464
|
-
const createPrompt = deps.createPrompt ?? (() => new HostedEnrollmentPrompt());
|
|
465
|
-
const width = opts.popup?.width ?? 480;
|
|
466
|
-
const height = opts.popup?.height ?? 720;
|
|
467
|
-
const sw = window.screen?.width ?? width;
|
|
468
|
-
const sh = window.screen?.height ?? height;
|
|
469
|
-
const left = Math.max(0, Math.round((sw - width) / 2));
|
|
470
|
-
const top = Math.max(0, Math.round((sh - height) / 2));
|
|
471
|
-
const features = `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`;
|
|
472
|
-
const name = `invo-approval-${encodeURIComponent(String(opts.transactionId)).replace(/[^A-Za-z0-9-]/g, "")}`;
|
|
473
|
-
let popup;
|
|
474
|
-
try {
|
|
475
|
-
popup = open("about:blank", name, features);
|
|
476
|
-
} catch {
|
|
477
|
-
popup = null;
|
|
478
|
-
}
|
|
479
|
-
const mode = opts.popupBlocked ?? "resolve";
|
|
480
|
-
if (!popup && mode === "resolve") {
|
|
481
|
-
return { status: "blocked", popupBlocked: true, message: BLOCKED_HINT };
|
|
482
|
-
}
|
|
483
|
-
let begin;
|
|
484
|
-
try {
|
|
485
|
-
begin = await api.begin();
|
|
486
|
-
} catch (err) {
|
|
487
|
-
try {
|
|
488
|
-
popup?.close();
|
|
489
|
-
} catch {
|
|
490
|
-
}
|
|
491
|
-
if (signal?.aborted || err instanceof InvoError && err.code === "ABORTED") {
|
|
492
|
-
return { status: "closed", popupBlocked: false };
|
|
493
|
-
}
|
|
494
|
-
throw err;
|
|
495
|
-
}
|
|
496
|
-
const deviceCode = typeof begin["device_code"] === "string" ? begin["device_code"] : "";
|
|
497
|
-
const url = typeof begin["verification_uri_complete"] === "string" ? begin["verification_uri_complete"] : "";
|
|
498
|
-
if (!deviceCode || !url) {
|
|
499
|
-
try {
|
|
500
|
-
popup?.close();
|
|
501
|
-
} catch {
|
|
502
|
-
}
|
|
503
|
-
const { device_code: _dc, ...safeBody } = begin;
|
|
504
|
-
throw new InvoError({
|
|
505
|
-
message: "begin returned no device_code / verification_uri_complete.",
|
|
506
|
-
code: "UNEXPECTED_RESPONSE",
|
|
507
|
-
status: 0,
|
|
508
|
-
body: safeBody
|
|
509
|
-
});
|
|
510
|
-
}
|
|
511
|
-
let origin;
|
|
512
|
-
try {
|
|
513
|
-
origin = derivePlatformOrigin(url, opts.platformOrigin);
|
|
514
|
-
} catch (err) {
|
|
515
|
-
try {
|
|
516
|
-
popup?.close();
|
|
517
|
-
} catch {
|
|
518
|
-
}
|
|
519
|
-
throw err;
|
|
520
|
-
}
|
|
521
|
-
const expiresIn = Math.min(
|
|
522
|
-
MAX_EXPIRES_IN_S,
|
|
523
|
-
Math.max(1, Number(begin["expires_in"]) || 600)
|
|
524
|
-
);
|
|
525
|
-
let interval = Math.max(1, Number(begin["interval"]) || 5);
|
|
526
|
-
if (!popup) {
|
|
527
|
-
try {
|
|
528
|
-
navigate(url);
|
|
529
|
-
return { status: "redirected", popupBlocked: true };
|
|
530
|
-
} catch (err) {
|
|
531
|
-
return {
|
|
532
|
-
status: "blocked",
|
|
533
|
-
popupBlocked: true,
|
|
534
|
-
message: `The browser blocked the popup and the redirect fallback failed${err instanceof Error && err.message ? `: ${err.message}` : "."}`
|
|
535
|
-
};
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
|
-
const win = popup;
|
|
539
|
-
try {
|
|
540
|
-
const loc = win.location;
|
|
541
|
-
if (loc && typeof loc.replace === "function") loc.replace(url);
|
|
542
|
-
else if (loc) loc.href = url;
|
|
543
|
-
} catch {
|
|
544
|
-
}
|
|
545
|
-
const navigatedAt = Date.now();
|
|
546
|
-
try {
|
|
547
|
-
win.focus?.();
|
|
548
|
-
} catch {
|
|
549
|
-
}
|
|
550
|
-
return new Promise((resolve, reject) => {
|
|
551
|
-
let settled = false;
|
|
552
|
-
let prompt;
|
|
553
|
-
let wake = null;
|
|
554
|
-
let expiryTimer;
|
|
555
|
-
let closedTimer;
|
|
556
|
-
const cleanup = (closePopup) => {
|
|
557
|
-
settled = true;
|
|
558
|
-
window.removeEventListener("message", onMessage);
|
|
559
|
-
signal?.removeEventListener("abort", onAbort);
|
|
560
|
-
if (expiryTimer !== void 0) clearTimeout(expiryTimer);
|
|
561
|
-
if (closedTimer !== void 0) clearInterval(closedTimer);
|
|
562
|
-
prompt?.clear();
|
|
563
|
-
if (closePopup && !win.closed) {
|
|
564
|
-
try {
|
|
565
|
-
win.close();
|
|
566
|
-
} catch {
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
wake?.();
|
|
570
|
-
};
|
|
571
|
-
const finish = (result, closePopup) => {
|
|
572
|
-
if (settled) return;
|
|
573
|
-
cleanup(closePopup);
|
|
574
|
-
resolve(result);
|
|
575
|
-
};
|
|
576
|
-
const fail = (err) => {
|
|
577
|
-
if (settled) return;
|
|
578
|
-
cleanup(false);
|
|
579
|
-
reject(err);
|
|
580
|
-
};
|
|
581
|
-
const respond = async (decision) => {
|
|
582
|
-
if (settled) return;
|
|
583
|
-
try {
|
|
584
|
-
await api.confirmEnrollment(deviceCode, decision);
|
|
585
|
-
} catch (err) {
|
|
586
|
-
if (err instanceof InvoError && err.rawCode && CONFIRM_QUIET_CODES.has(err.rawCode)) {
|
|
587
|
-
prompt?.update(null);
|
|
588
|
-
return;
|
|
589
|
-
}
|
|
590
|
-
throw err;
|
|
591
|
-
}
|
|
592
|
-
wake?.();
|
|
593
|
-
};
|
|
594
|
-
const ensurePrompt = () => {
|
|
595
|
-
if (!prompt) {
|
|
596
|
-
prompt = createPrompt();
|
|
597
|
-
prompt.configure({
|
|
598
|
-
respond,
|
|
599
|
-
onEnrollment: opts.onEnrollment,
|
|
600
|
-
renderPrompt: opts.renderPrompt !== false
|
|
601
|
-
});
|
|
602
|
-
}
|
|
603
|
-
return prompt;
|
|
604
|
-
};
|
|
605
|
-
const showEnrollment = (input) => {
|
|
606
|
-
const e = input && typeof input === "object" ? input : null;
|
|
607
|
-
if (e) ensurePrompt().update(e);
|
|
608
|
-
else prompt?.update(null);
|
|
609
|
-
};
|
|
610
|
-
const onMessage = (event) => {
|
|
611
|
-
if (event.origin !== origin) return;
|
|
612
|
-
if (event.source && event.source !== win) return;
|
|
613
|
-
const data = event.data;
|
|
614
|
-
if (!data || typeof data !== "object" || data.type !== HOSTED_MESSAGE_TYPE) return;
|
|
615
|
-
wake?.();
|
|
616
|
-
};
|
|
617
|
-
const onAbort = () => finish({ status: "closed", popupBlocked: false }, true);
|
|
618
|
-
const pause = (ms) => new Promise((r) => {
|
|
619
|
-
const t = setTimeout(() => {
|
|
620
|
-
wake = null;
|
|
621
|
-
r();
|
|
622
|
-
}, ms);
|
|
623
|
-
wake = () => {
|
|
624
|
-
clearTimeout(t);
|
|
625
|
-
wake = null;
|
|
626
|
-
r();
|
|
627
|
-
};
|
|
628
|
-
});
|
|
629
|
-
window.addEventListener("message", onMessage);
|
|
630
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
631
|
-
expiryTimer = setTimeout(() => finish({ status: "expired", popupBlocked: false }, false), expiresIn * 1e3);
|
|
632
|
-
closedTimer = setInterval(() => {
|
|
633
|
-
if (!win.closed) return;
|
|
634
|
-
if (Date.now() - navigatedAt < coopGraceMs) {
|
|
635
|
-
finish({ status: "blocked", popupBlocked: true, message: COOP_HINT }, false);
|
|
636
|
-
} else {
|
|
637
|
-
finish({ status: "closed", popupBlocked: false }, false);
|
|
638
|
-
}
|
|
639
|
-
}, closedPollMs);
|
|
640
|
-
void (async () => {
|
|
641
|
-
let transientFailures = 0;
|
|
642
|
-
while (!settled) {
|
|
643
|
-
await pause(interval * 1e3);
|
|
644
|
-
if (settled) return;
|
|
645
|
-
let raw;
|
|
646
|
-
try {
|
|
647
|
-
raw = await api.poll(deviceCode);
|
|
648
|
-
} catch (err) {
|
|
649
|
-
if (settled) return;
|
|
650
|
-
const p = pollToken(err);
|
|
651
|
-
if (!p) {
|
|
652
|
-
if (++transientFailures >= MAX_TRANSIENT_POLL_FAILURES) return fail(err);
|
|
653
|
-
const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
|
|
654
|
-
if (typeof ra === "number" && ra > interval) interval = Math.min(ra, MAX_EXPIRES_IN_S);
|
|
655
|
-
continue;
|
|
656
|
-
}
|
|
657
|
-
transientFailures = 0;
|
|
658
|
-
const bodyInterval = Number(p.body["interval"]);
|
|
659
|
-
switch (p.token) {
|
|
660
|
-
case "authorization_pending":
|
|
661
|
-
if (bodyInterval > 0) interval = bodyInterval;
|
|
662
|
-
showEnrollment(p.body["enrollment"]);
|
|
663
|
-
continue;
|
|
664
|
-
case "slow_down":
|
|
665
|
-
interval = Math.max(interval + 5, bodyInterval > 0 ? bodyInterval : 0);
|
|
666
|
-
continue;
|
|
667
|
-
case "expired_token":
|
|
668
|
-
return finish({ status: "expired", popupBlocked: false }, false);
|
|
669
|
-
case "access_denied":
|
|
670
|
-
return finish({ status: "denied", popupBlocked: false }, false);
|
|
671
|
-
default:
|
|
672
|
-
return fail(err);
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
if (settled) return;
|
|
676
|
-
if (raw["status"] !== "approved") continue;
|
|
677
|
-
try {
|
|
678
|
-
const approval = await api.approve(deviceCode);
|
|
679
|
-
if (settled) return;
|
|
680
|
-
finish({ status: "approved", popupBlocked: false, approval }, true);
|
|
681
|
-
} catch (err) {
|
|
682
|
-
fail(err);
|
|
683
|
-
}
|
|
684
|
-
return;
|
|
685
|
-
}
|
|
686
|
-
})();
|
|
687
|
-
});
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
// src/shared/purchase-status.ts
|
|
691
|
-
function str(v) {
|
|
692
|
-
return typeof v === "string" ? v : v === null || v === void 0 ? null : String(v);
|
|
693
|
-
}
|
|
694
|
-
function toPurchaseStatusResult(raw, sessionId) {
|
|
695
|
-
return {
|
|
696
|
-
status: String(raw["status"] ?? ""),
|
|
697
|
-
// INVO SAYS, AND ONLY AN EXPLICIT `true` SAYS IT. A missing or malformed field reads
|
|
698
|
-
// false, which keeps a poll running; the alternative, guessing terminality from
|
|
699
|
-
// `status`, is how an old SDK declares a future status finished.
|
|
700
|
-
terminal: raw["terminal"] === true,
|
|
701
|
-
orderId: str(raw["order_id"]),
|
|
702
|
-
sessionId: String(raw["session_id"] ?? sessionId),
|
|
703
|
-
coinsCredited: str(raw["coins_credited"]),
|
|
704
|
-
transactionId: str(raw["transaction_id"]),
|
|
705
|
-
newBalance: str(raw["new_balance"]),
|
|
706
|
-
reasonCode: str(raw["reason_code"]),
|
|
707
|
-
message: str(raw["message"]),
|
|
708
|
-
amountChargedUsd: str(raw["amount_charged_usd"]),
|
|
709
|
-
listedUsd: str(raw["listed_usd"]),
|
|
710
|
-
currencyName: str(raw["currency_name"]),
|
|
711
|
-
...receiptFields(raw),
|
|
712
|
-
raw
|
|
713
|
-
};
|
|
714
|
-
}
|
|
715
|
-
function isPurchaseCredited(r) {
|
|
716
|
-
return r.status === "credited";
|
|
717
|
-
}
|
|
718
|
-
function isPurchaseRefused(r) {
|
|
719
|
-
return r.status === "refused";
|
|
720
|
-
}
|
|
721
|
-
function isPurchaseRefunded(r) {
|
|
722
|
-
return r.status === "refunded";
|
|
723
|
-
}
|
|
724
|
-
function isPurchaseExpired(r) {
|
|
725
|
-
return r.status === "expired";
|
|
726
|
-
}
|
|
727
|
-
var NOTHING_CHARGED_REASONS = /* @__PURE__ */ new Set(["PAYMENT_DECLINED", "PAYMENT_CANCELLED"]);
|
|
728
|
-
function nothingWasCharged(r) {
|
|
729
|
-
if (r.status === "expired") return true;
|
|
730
|
-
if (r.status !== "refused") return false;
|
|
731
|
-
return r.reasonCode !== null && NOTHING_CHARGED_REASONS.has(r.reasonCode);
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
// src/index.ts
|
|
735
|
-
function clientInvalidInput(message) {
|
|
736
|
-
return new InvoError({ message, code: "INVALID_INPUT", status: 0 });
|
|
737
|
-
}
|
|
738
|
-
function randomNonce() {
|
|
739
|
-
const c = globalThis.crypto;
|
|
740
|
-
if (!c || typeof c.getRandomValues !== "function") {
|
|
741
|
-
throw clientInvalidInput(
|
|
742
|
-
"No secure random source in this environment; pass a deviceSignal you built yourself."
|
|
743
|
-
);
|
|
744
|
-
}
|
|
745
|
-
const bytes = c.getRandomValues(new Uint8Array(16));
|
|
746
|
-
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
747
|
-
}
|
|
748
|
-
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
749
|
-
function toPendingCollectItem(row) {
|
|
750
|
-
return {
|
|
751
|
-
transferId: String(row["transfer_id"] ?? ""),
|
|
752
|
-
kind: String(row["kind"] ?? ""),
|
|
753
|
-
flow: String(row["flow"] ?? ""),
|
|
754
|
-
amount: row["amount"] ?? null,
|
|
755
|
-
currency: String(row["currency"] ?? ""),
|
|
756
|
-
counterpartyGame: String(row["counterparty_game"] ?? ""),
|
|
757
|
-
expiresAt: row["expires_at"] ?? null,
|
|
758
|
-
stepUpRequired: row["step_up_required"] === true,
|
|
759
|
-
held: row["held"] === true,
|
|
760
|
-
holdReason: row["hold_reason"] ?? null,
|
|
761
|
-
raw: row
|
|
762
|
-
};
|
|
763
|
-
}
|
|
764
|
-
function toBalanceRow(row) {
|
|
765
|
-
return {
|
|
766
|
-
currencyId: row["currency_id"] ?? "",
|
|
767
|
-
currencyName: String(row["currency_name"] ?? ""),
|
|
768
|
-
currencySymbol: row["currency_symbol"] ?? null,
|
|
769
|
-
currencySymbolUrl: row["currency_symbol_url"] ?? null,
|
|
770
|
-
availableBalance: String(row["available_balance"] ?? ""),
|
|
771
|
-
reservedBalance: String(row["reserved_balance"] ?? ""),
|
|
772
|
-
totalBalance: String(row["total_balance"] ?? ""),
|
|
773
|
-
raw: row
|
|
774
|
-
};
|
|
775
|
-
}
|
|
776
|
-
function toApproveResult(raw, transactionId) {
|
|
777
|
-
const holdReason = raw["error_code"] ?? raw["code"];
|
|
778
|
-
return {
|
|
779
|
-
status: String(raw["status"] ?? ""),
|
|
780
|
-
next: String(raw["next"] ?? ""),
|
|
781
|
-
transactionId: String(raw["transaction_id"] ?? transactionId),
|
|
782
|
-
claimCode: raw["claim_code"],
|
|
783
|
-
claimCodeExpiresAt: raw["claim_code_expires_at"],
|
|
784
|
-
holdReason: typeof holdReason === "string" ? holdReason : void 0,
|
|
785
|
-
risk: raw["risk"],
|
|
786
|
-
guardianApproval: raw["guardian_approval"] ?? void 0,
|
|
787
|
-
pollEndpoint: raw["poll_endpoint"],
|
|
788
|
-
...typeof raw["claim_delivery"] === "string" && raw["claim_delivery"] ? { claimDelivery: raw["claim_delivery"] } : {},
|
|
789
|
-
raw
|
|
790
|
-
};
|
|
791
|
-
}
|
|
792
|
-
function toConfirmReceiptResult(raw) {
|
|
793
|
-
const holdReason = raw["error_code"] ?? raw["code"];
|
|
794
|
-
return {
|
|
795
|
-
status: String(raw["status"] ?? ""),
|
|
796
|
-
holdReason: typeof holdReason === "string" ? holdReason : void 0,
|
|
797
|
-
raw
|
|
798
|
-
};
|
|
799
|
-
}
|
|
800
|
-
var PlatformCommerceClient = class {
|
|
801
|
-
/**
|
|
802
|
-
* Embed INVO's hosted checkout in an iframe and listen for completion.
|
|
803
|
-
*
|
|
804
|
-
* ```ts
|
|
805
|
-
* const handle = invo.platformCommerce.mountCheckout("#checkout", checkoutUrl, {
|
|
806
|
-
* onComplete: () => showProcessing(), // then reconcile server-side
|
|
807
|
-
* });
|
|
808
|
-
* // later: handle.destroy();
|
|
809
|
-
* ```
|
|
810
|
-
*
|
|
811
|
-
* Or skip the helper and redirect: `location.href = checkoutUrl` (the buyer returns to
|
|
812
|
-
* the `successUrl`/`cancelUrl` you passed to the server `purchase()`).
|
|
813
|
-
*
|
|
814
|
-
* `onComplete` fires on the page's `INVO_CHECKOUT_COMPLETE` postMessage -- accepted ONLY
|
|
815
|
-
* from the checkout URL's own origin (any other window could forge the event). It is a
|
|
816
|
-
* UX signal: the sale is REAL only on the `platform_commerce.purchased` webhook, never
|
|
817
|
-
* on this client event.
|
|
818
|
-
*/
|
|
819
|
-
mountCheckout(el, checkoutUrl, opts) {
|
|
820
|
-
if (typeof document === "undefined" || typeof window === "undefined") {
|
|
821
|
-
throw new InvoError({
|
|
822
|
-
message: "mountCheckout requires a browser DOM (window/document).",
|
|
823
|
-
code: "DOM_UNAVAILABLE",
|
|
824
|
-
status: 0
|
|
825
|
-
});
|
|
826
|
-
}
|
|
827
|
-
if (!checkoutUrl || !checkoutUrl.trim()) {
|
|
828
|
-
throw new Error("mountCheckout requires the server-returned `checkoutUrl`.");
|
|
829
|
-
}
|
|
830
|
-
let checkoutOrigin;
|
|
831
|
-
try {
|
|
832
|
-
const u = new URL(checkoutUrl);
|
|
833
|
-
const isLocal = u.hostname === "localhost" || u.hostname === "127.0.0.1";
|
|
834
|
-
if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
|
|
835
|
-
throw new Error("not https");
|
|
836
|
-
}
|
|
837
|
-
checkoutOrigin = u.origin;
|
|
838
|
-
} catch {
|
|
839
|
-
throw new InvoError({
|
|
840
|
-
message: "mountCheckout requires an absolute https checkoutUrl.",
|
|
841
|
-
code: "INVALID_INPUT",
|
|
842
|
-
status: 0
|
|
843
|
-
});
|
|
844
|
-
}
|
|
845
|
-
const container = typeof el === "string" ? document.querySelector(el) : el;
|
|
846
|
-
if (!container) {
|
|
847
|
-
throw new InvoError({
|
|
848
|
-
message: `mountCheckout could not find the container "${String(el)}".`,
|
|
849
|
-
code: "MOUNT_NOT_FOUND",
|
|
850
|
-
status: 0
|
|
851
|
-
});
|
|
852
|
-
}
|
|
853
|
-
const iframe = document.createElement("iframe");
|
|
854
|
-
iframe.src = checkoutUrl;
|
|
855
|
-
iframe.title = opts?.title ?? "INVO checkout";
|
|
856
|
-
if (opts?.className) iframe.className = opts.className;
|
|
857
|
-
iframe.style.width = "100%";
|
|
858
|
-
iframe.style.border = "0";
|
|
859
|
-
iframe.allow = "payment";
|
|
860
|
-
const onMessage = (event) => {
|
|
861
|
-
if (event.origin !== checkoutOrigin) return;
|
|
862
|
-
if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
|
|
863
|
-
const msg = event.data;
|
|
864
|
-
if (!msg || msg.type !== "INVO_CHECKOUT_COMPLETE") return;
|
|
865
|
-
opts?.onComplete?.(
|
|
866
|
-
msg.data && typeof msg.data === "object" ? msg.data : {}
|
|
867
|
-
);
|
|
868
|
-
};
|
|
869
|
-
window.addEventListener("message", onMessage);
|
|
870
|
-
container.appendChild(iframe);
|
|
871
|
-
return {
|
|
872
|
-
iframe,
|
|
873
|
-
destroy() {
|
|
874
|
-
window.removeEventListener("message", onMessage);
|
|
875
|
-
iframe.remove();
|
|
876
|
-
}
|
|
877
|
-
};
|
|
878
|
-
}
|
|
879
|
-
};
|
|
880
|
-
var DEFAULT_PURCHASE_POLL_INTERVAL_MS = 1500;
|
|
881
|
-
var DEFAULT_PURCHASE_POLL_TIMEOUT_MS = 18e4;
|
|
882
|
-
function pollSleep(ms, signal) {
|
|
883
|
-
return new Promise((resolve) => {
|
|
884
|
-
if (signal?.aborted) return resolve();
|
|
885
|
-
const timer = setTimeout(done, ms);
|
|
886
|
-
const onAbort = () => done();
|
|
887
|
-
function done() {
|
|
888
|
-
clearTimeout(timer);
|
|
889
|
-
signal?.removeEventListener("abort", onAbort);
|
|
890
|
-
resolve();
|
|
891
|
-
}
|
|
892
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
893
|
-
});
|
|
894
|
-
}
|
|
895
|
-
function isTransientPollFailure(err) {
|
|
896
|
-
if (!(err instanceof InvoError)) return false;
|
|
897
|
-
if (err.code === "ABORTED") return false;
|
|
898
|
-
return err.status === 0 || err.status === 429 || err.status >= 500;
|
|
899
|
-
}
|
|
900
|
-
var CheckoutClient = class _CheckoutClient {
|
|
901
|
-
constructor(config) {
|
|
902
|
-
if (!config?.baseUrl) throw new Error("CheckoutClient requires a `baseUrl`.");
|
|
903
|
-
assertSecureBaseUrl(config.baseUrl);
|
|
904
|
-
this.http = new Http({
|
|
905
|
-
baseUrl: config.baseUrl,
|
|
906
|
-
timeoutMs: config.timeoutMs,
|
|
907
|
-
fetchImpl: config.fetch,
|
|
908
|
-
maxRetries: config.maxRetries,
|
|
909
|
-
retryBaseDelayMs: config.retryBaseDelayMs,
|
|
910
|
-
hooks: config.hooks
|
|
911
|
-
});
|
|
912
|
-
}
|
|
913
|
-
/**
|
|
914
|
-
* Wrap an `Http` the owning client already built, so `invo.checkout` shares that
|
|
915
|
-
* client's baseUrl, timeout, retry budget and observability hooks.
|
|
916
|
-
*
|
|
917
|
-
* @internal Not part of the public API; it takes an internal type and may change.
|
|
918
|
-
*/
|
|
919
|
-
static _withHttp(http) {
|
|
920
|
-
const client = Object.create(_CheckoutClient.prototype);
|
|
921
|
-
client.http = http;
|
|
922
|
-
return client;
|
|
923
|
-
}
|
|
924
|
-
/**
|
|
925
|
-
* Read a purchase's status once.
|
|
926
|
-
*
|
|
927
|
-
* Answers `200` with a {@link PurchaseStatusResult} for every state of the purchase,
|
|
928
|
-
* including "we have your money and your coins are not there". There is no tenant gate
|
|
929
|
-
* on it: a partner suspended after a buyer's card was charged is exactly the case it
|
|
930
|
-
* exists for.
|
|
931
|
-
*
|
|
932
|
-
* Throws an {@link InvoError} on `401` (no token, bad signature, or a card-setup token:
|
|
933
|
-
* `err.isWrongSessionPurpose`), `403` (a valid token for a DIFFERENT session:
|
|
934
|
-
* `err.isCheckoutSessionMismatch`) and `410` (the token is more than 24 hours past its
|
|
935
|
-
* expiry: `err.isCheckoutSessionExpired`; show the buyer the order id you already have
|
|
936
|
-
* and a Contact support link).
|
|
937
|
-
*
|
|
938
|
-
* Storefront (in-client) purchases are keyed on the partner's own purchase reference
|
|
939
|
-
* rather than on a checkout session, so a read by session id finds nothing and answers
|
|
940
|
-
* `pending`. Do not conclude from that that such a purchase never happened.
|
|
941
|
-
*/
|
|
942
|
-
async getPurchaseStatus(input, opts) {
|
|
943
|
-
const sessionId = String(input?.sessionId ?? "").trim();
|
|
944
|
-
const sessionToken = String(input?.sessionToken ?? "").trim();
|
|
945
|
-
if (!sessionId) {
|
|
946
|
-
throw new InvoError({
|
|
947
|
-
message: "getPurchaseStatus requires `sessionId` (from createCheckout).",
|
|
948
|
-
code: "INVALID_INPUT",
|
|
949
|
-
status: 0
|
|
950
|
-
});
|
|
951
|
-
}
|
|
952
|
-
if (!sessionToken) {
|
|
953
|
-
throw new InvoError({
|
|
954
|
-
message: "getPurchaseStatus requires `sessionToken`. The session token is the credential; the id in the path is not.",
|
|
955
|
-
code: "INVALID_INPUT",
|
|
956
|
-
status: 0
|
|
957
|
-
});
|
|
958
|
-
}
|
|
959
|
-
const raw = await this.http.get(
|
|
960
|
-
`/api/checkout/sessions/${encodeURIComponent(sessionId)}`,
|
|
961
|
-
{ kind: "bearer", token: sessionToken },
|
|
962
|
-
{ signal: opts?.signal }
|
|
963
|
-
);
|
|
964
|
-
return toPurchaseStatusResult(raw, sessionId);
|
|
965
|
-
}
|
|
966
|
-
/**
|
|
967
|
-
* Poll {@link getPurchaseStatus} until INVO says the purchase is finished, and return
|
|
968
|
-
* that final result.
|
|
969
|
-
*
|
|
970
|
-
* ```ts
|
|
971
|
-
* const result = await invo.checkout.waitForPurchase({
|
|
972
|
-
* sessionId, sessionToken,
|
|
973
|
-
* intervalMs: 1500,
|
|
974
|
-
* timeoutMs: 300_000,
|
|
975
|
-
* signal: controller.signal,
|
|
976
|
-
* onUpdate: (r) => render(r), // keep the modal open on every non-terminal read
|
|
977
|
-
* });
|
|
978
|
-
* if (isPurchaseCredited(result)) showCoins(result.coinsCredited, result.currencyName);
|
|
979
|
-
* else if (result.message) showMessage(result.message, result.orderId); // verbatim
|
|
980
|
-
* ```
|
|
981
|
-
*
|
|
982
|
-
* IT STOPS ON `result.terminal` AND ON NOTHING ELSE. `terminal` is INVO's word, read off
|
|
983
|
-
* the response; this loop never recomputes it from `status`, so a status a later backend
|
|
984
|
-
* introduces cannot end a wait here as a success. `paid_pending_credit` is deliberately
|
|
985
|
-
* not terminal and is never promoted to a failure by age: INVO's reconciler recovers a
|
|
986
|
-
* stalled credit, and telling a buyer they lost money they are about to receive would
|
|
987
|
-
* be a fresh lie in place of the old silence.
|
|
988
|
-
*
|
|
989
|
-
* A transient failure (network, timeout, 429, 5xx) is polled through rather than raised;
|
|
990
|
-
* a `401`, `403` or `410` is raised at once. On the cap it returns the LAST result it
|
|
991
|
-
* read, whose `terminal` is false. Nothing is guessed and nothing is thrown, so the page
|
|
992
|
-
* keeps showing the buyer what INVO last said. If it never got a single answer, the last
|
|
993
|
-
* transport failure is thrown.
|
|
994
|
-
*/
|
|
995
|
-
async waitForPurchase(input) {
|
|
996
|
-
const intervalMs = Math.max(0, input?.intervalMs ?? DEFAULT_PURCHASE_POLL_INTERVAL_MS);
|
|
997
|
-
const timeoutMs = Math.max(0, input?.timeoutMs ?? DEFAULT_PURCHASE_POLL_TIMEOUT_MS);
|
|
998
|
-
const maxAttempts = input?.maxAttempts === void 0 ? Number.POSITIVE_INFINITY : Math.max(1, input.maxAttempts);
|
|
999
|
-
const deadline = Date.now() + timeoutMs;
|
|
1000
|
-
const signal = input?.signal;
|
|
1001
|
-
let last;
|
|
1002
|
-
let lastFailure;
|
|
1003
|
-
for (let attempts = 0; ; ) {
|
|
1004
|
-
if (signal?.aborted) {
|
|
1005
|
-
throw new InvoError({
|
|
1006
|
-
message: "waitForPurchase was aborted",
|
|
1007
|
-
code: "ABORTED",
|
|
1008
|
-
status: 0
|
|
1009
|
-
});
|
|
1010
|
-
}
|
|
1011
|
-
attempts += 1;
|
|
1012
|
-
try {
|
|
1013
|
-
const result = await this.getPurchaseStatus(input, { signal });
|
|
1014
|
-
last = result;
|
|
1015
|
-
lastFailure = void 0;
|
|
1016
|
-
try {
|
|
1017
|
-
input?.onUpdate?.(result);
|
|
1018
|
-
} catch {
|
|
1019
|
-
}
|
|
1020
|
-
if (result.terminal) return result;
|
|
1021
|
-
} catch (err) {
|
|
1022
|
-
if (!isTransientPollFailure(err)) throw err;
|
|
1023
|
-
lastFailure = err;
|
|
1024
|
-
}
|
|
1025
|
-
if (attempts >= maxAttempts) break;
|
|
1026
|
-
if (Date.now() + intervalMs >= deadline) break;
|
|
1027
|
-
await pollSleep(intervalMs, signal);
|
|
1028
|
-
}
|
|
1029
|
-
if (last) return last;
|
|
1030
|
-
throw lastFailure instanceof Error ? lastFailure : new InvoError({
|
|
1031
|
-
message: "waitForPurchase could not read the purchase status before the cap.",
|
|
1032
|
-
code: "PURCHASE_STATUS_UNAVAILABLE",
|
|
1033
|
-
status: 0
|
|
1034
|
-
});
|
|
1035
|
-
}
|
|
1036
|
-
};
|
|
1037
|
-
var InvoClient = class {
|
|
1038
|
-
constructor(config) {
|
|
1039
|
-
/**
|
|
1040
|
-
* Platform Commerce (ecommerce) hosted-checkout embed. Use after
|
|
1041
|
-
* `InvoServer.platformCommerce.purchase({ fundingSource: "card" })` returns a
|
|
1042
|
-
* `checkoutUrl` — either redirect the buyer there, or embed it with
|
|
1043
|
-
* `mountCheckout`. No card element, no processor dependency. See
|
|
1044
|
-
* {@link PlatformCommerceClient}.
|
|
1045
|
-
*/
|
|
1046
|
-
this.platformCommerce = new PlatformCommerceClient();
|
|
1047
|
-
if (!config.token) throw new Error("InvoClient requires a player `token`.");
|
|
1048
|
-
if (!config.baseUrl) throw new Error("InvoClient requires a `baseUrl`.");
|
|
1049
|
-
assertSecureBaseUrl(config.baseUrl);
|
|
1050
|
-
this.http = new Http({
|
|
1051
|
-
baseUrl: config.baseUrl,
|
|
1052
|
-
timeoutMs: config.timeoutMs,
|
|
1053
|
-
fetchImpl: config.fetch,
|
|
1054
|
-
maxRetries: config.maxRetries,
|
|
1055
|
-
retryBaseDelayMs: config.retryBaseDelayMs,
|
|
1056
|
-
hooks: config.hooks
|
|
1057
|
-
// Browser: do NOT set User-Agent (forbidden header); the browser's own UA is fine.
|
|
1058
|
-
});
|
|
1059
|
-
this.auth = { kind: "bearer", token: config.token };
|
|
1060
|
-
this.refreshToken = config.refreshToken;
|
|
1061
|
-
this.checkout = CheckoutClient._withHttp(this.http);
|
|
1062
|
-
}
|
|
1063
|
-
assertWebAuthn() {
|
|
1064
|
-
if (typeof navigator === "undefined" || !navigator.credentials) {
|
|
1065
|
-
throw new Error("WebAuthn is not available in this environment (browser required).");
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
|
-
/**
|
|
1069
|
-
* Enroll a passkey for the token's identity (register/begin -> create() -> register/complete).
|
|
1070
|
-
* Gates: `ENROLLMENT_REQUIRES_AUTHORIZATION` → {@link enrollmentBegin} OTP grant;
|
|
1071
|
-
* `ENROLLMENT_REQUIRES_PROOF` → {@link linkDevice}, or {@link recoveryBegin} when the
|
|
1072
|
-
* player lost/deleted the old passkey ("Lost or replaced your passkey?").
|
|
1073
|
-
*/
|
|
1074
|
-
async enrollPasskey(opts) {
|
|
1075
|
-
this.assertWebAuthn();
|
|
1076
|
-
const signal = opts?.signal;
|
|
1077
|
-
return this.withTokenRetry(async () => {
|
|
1078
|
-
const options = await this.post(
|
|
1079
|
-
"/api/sdk/webauthn/register/begin",
|
|
1080
|
-
void 0,
|
|
1081
|
-
signal
|
|
1082
|
-
);
|
|
1083
|
-
const cred = await navigator.credentials.create({
|
|
1084
|
-
publicKey: toCreationOptions(options),
|
|
1085
|
-
signal
|
|
1086
|
-
});
|
|
1087
|
-
if (!cred) throw new Error("Passkey creation was cancelled or returned no credential.");
|
|
1088
|
-
const raw = await this.post(
|
|
1089
|
-
"/api/sdk/webauthn/register/complete",
|
|
1090
|
-
{ credential: registrationToJSON(cred) },
|
|
1091
|
-
signal
|
|
1092
|
-
);
|
|
1093
|
-
return { status: String(raw["status"] ?? ""), device: raw["device"] ?? null, raw };
|
|
1094
|
-
});
|
|
1095
|
-
}
|
|
1096
|
-
async approveHosted(opts) {
|
|
1097
|
-
const txn = String(opts.transactionId ?? "");
|
|
1098
|
-
const id = encodeURIComponent(txn);
|
|
1099
|
-
const signal = opts.signal;
|
|
1100
|
-
const api = {
|
|
1101
|
-
begin: () => this.withTokenRetry(
|
|
1102
|
-
() => this.post(
|
|
1103
|
-
"/api/sdk/approvals/device/begin",
|
|
1104
|
-
{ transaction_id: txn, flow: opts.flow, channel: "popup" },
|
|
1105
|
-
signal
|
|
1106
|
-
)
|
|
1107
|
-
),
|
|
1108
|
-
poll: (deviceCode) => this.withTokenRetry(
|
|
1109
|
-
() => this.post(
|
|
1110
|
-
"/api/sdk/approvals/device/poll",
|
|
1111
|
-
{ device_code: deviceCode },
|
|
1112
|
-
signal
|
|
1113
|
-
)
|
|
1114
|
-
),
|
|
1115
|
-
confirmEnrollment: (deviceCode, decision) => this.withTokenRetry(
|
|
1116
|
-
() => this.post(
|
|
1117
|
-
"/api/sdk/approvals/device/confirm-enrollment",
|
|
1118
|
-
{ device_code: deviceCode, decision },
|
|
1119
|
-
signal
|
|
1120
|
-
)
|
|
1121
|
-
),
|
|
1122
|
-
approve: (deviceCode) => this.withTokenRetry(async () => {
|
|
1123
|
-
const body = { device_code: deviceCode };
|
|
1124
|
-
switch (opts.flow) {
|
|
1125
|
-
case "transfer":
|
|
1126
|
-
return toApproveResult(
|
|
1127
|
-
await this.post(`/api/sdk/transfers/${id}/approve`, body, signal),
|
|
1128
|
-
txn
|
|
1129
|
-
);
|
|
1130
|
-
case "send":
|
|
1131
|
-
return toApproveResult(
|
|
1132
|
-
await this.post(`/api/sdk/send/${id}/approve`, body, signal),
|
|
1133
|
-
txn
|
|
1134
|
-
);
|
|
1135
|
-
case "send_receipt":
|
|
1136
|
-
return toConfirmReceiptResult(
|
|
1137
|
-
await this.post(`/api/sdk/send/${id}/confirm-receipt`, body, signal)
|
|
1138
|
-
);
|
|
1139
|
-
case "transfer_receipt":
|
|
1140
|
-
return toConfirmReceiptResult(
|
|
1141
|
-
await this.post(`/api/sdk/transfers/${id}/confirm-receipt`, body, signal)
|
|
1142
|
-
);
|
|
1143
|
-
default:
|
|
1144
|
-
throw new Error(`approveHosted: unknown flow "${String(opts.flow)}".`);
|
|
1145
|
-
}
|
|
1146
|
-
})
|
|
1147
|
-
};
|
|
1148
|
-
return runHostedApproval(opts, api);
|
|
1149
|
-
}
|
|
1150
|
-
/**
|
|
1151
|
-
* Approve a SEND with the player's passkey.
|
|
1152
|
-
*
|
|
1153
|
-
* Throws 403 `err.isPlayerTokenStale` when the player token predates a change to the
|
|
1154
|
-
* sender's identity (their phone was added on the initiate). Not retried automatically,
|
|
1155
|
-
* because this call moves money: re-mint the player token (or use the `playerToken`
|
|
1156
|
-
* your server got back from `initiateSend`) and retry once.
|
|
1157
|
-
*/
|
|
1158
|
-
async approveSend(transactionId, opts) {
|
|
1159
|
-
return this.approve("send", transactionId, opts);
|
|
1160
|
-
}
|
|
1161
|
-
/** Approve a TRANSFER with the player's passkey (returns the sender's claim code). Same
|
|
1162
|
-
* `err.isPlayerTokenStale` handling as {@link approveSend}: re-mint and retry once. */
|
|
1163
|
-
async approveTransfer(transactionId, opts) {
|
|
1164
|
-
return this.approve("transfers", transactionId, opts);
|
|
1165
|
-
}
|
|
1166
|
-
/**
|
|
1167
|
-
* Recipient self-claims a SEND with their passkey.
|
|
1168
|
-
*
|
|
1169
|
-
* May throw a 409 with `err.isPhoneShareApprovalRequired` when the receiver phone is
|
|
1170
|
-
* contested (the collecting identity isn't yet authorized for it). NOT a failure — the
|
|
1171
|
-
* money is held and the phone owner is texted to approve. Show `err.message`
|
|
1172
|
-
* (`err.phoneShareLast4` names the phone), then **retry this same call** once approved
|
|
1173
|
-
* (it then succeeds idempotently); on denial/expiry the backend refunds the sender.
|
|
1174
|
-
*/
|
|
1175
|
-
async confirmReceiptSend(transactionId, opts) {
|
|
1176
|
-
return this.confirmReceipt("send", transactionId, opts);
|
|
1177
|
-
}
|
|
1178
|
-
/** Recipient self-claims a TRANSFER with their passkey. Can throw the same phone-share
|
|
1179
|
-
* 409 as {@link confirmReceiptSend} (`err.isPhoneShareApprovalRequired`) — handle it the
|
|
1180
|
-
* same way: show `err.message`, retry after the phone owner approves. */
|
|
1181
|
-
async confirmReceiptTransfer(transactionId, opts) {
|
|
1182
|
-
return this.confirmReceipt("transfers", transactionId, opts);
|
|
1183
|
-
}
|
|
1184
|
-
/**
|
|
1185
|
-
* Phone changes waiting for THIS player's enrolled device to approve
|
|
1186
|
-
* (`GET /api/sdk/players/phone/change-approvals`, player token). A row appears after the
|
|
1187
|
-
* player entered the emailed code on INVO's page for a change whose `confirmation` is
|
|
1188
|
-
* `"email_code_and_device"`. Show each one ("Approve changing your number to
|
|
1189
|
-
* ***-***-0123?") and answer it with {@link approvePhoneChange}. Read-only.
|
|
1190
|
-
*/
|
|
1191
|
-
async listPhoneChangeApprovals(opts) {
|
|
1192
|
-
return this.withTokenRetry(async () => {
|
|
1193
|
-
const raw = await this.get(
|
|
1194
|
-
"/api/sdk/players/phone/change-approvals",
|
|
1195
|
-
opts?.signal
|
|
1196
|
-
);
|
|
1197
|
-
return toPhoneChangeApprovalsResult(raw);
|
|
1198
|
-
});
|
|
1199
|
-
}
|
|
1200
|
-
/**
|
|
1201
|
-
* Approve (or, with `decision: "deny"`, decline) a phone change from the player's enrolled
|
|
1202
|
-
* device (`POST /api/sdk/players/phone/change-requests/{id}/approve`, player token).
|
|
1203
|
-
*
|
|
1204
|
-
* The device key signs `phone-change|<changeRequestId>|<nonce>|<timestamp>` to approve or
|
|
1205
|
-
* `phone-change-deny|<changeRequestId>|<nonce>|<timestamp>` to decline (`timestamp` in
|
|
1206
|
-
* epoch seconds). Either pass `sign`, and the SDK makes a fresh nonce and timestamp, builds
|
|
1207
|
-
* that message and asks you for the base64 signature; or pass a `deviceSignal` you signed
|
|
1208
|
-
* yourself (build the message with {@link phoneChangeSignalMessage}). This is a device key
|
|
1209
|
-
* registered with INVO, not a passkey.
|
|
1210
|
-
*
|
|
1211
|
-
* `status: "confirmed"` means the change is applied: store `identityId` and use
|
|
1212
|
-
* `playerToken` (tokens minted before the change are stale). `status: "denied"` means
|
|
1213
|
-
* nothing changed. Refusals: 409 `err.isChangeRequestNotReady` (the player has not entered
|
|
1214
|
-
* the code on INVO's page yet), 409 `err.isChangeRequestNotPending` (`err.changeRequestStatus`),
|
|
1215
|
-
* 409 `err.isDeviceEnrolledAfterRequest` (this device was set up after the change was
|
|
1216
|
-
* requested; approve on the earlier device, or the game creates a new request), 409
|
|
1217
|
-
* `err.isPhoneChangeRecoveryCooldown` (a recent sign-in recovery; retry later, declining
|
|
1218
|
-
* still works), 404 `err.isChangeRequestNotFound`, 401 `err.isDeviceSignalRejected`, 403
|
|
1219
|
-
* `DEVICE_REQUIRES_ELEVATION`, or any refusal of the change itself (for example
|
|
1220
|
-
* `err.isPendingTransfersToOldPhone`).
|
|
1221
|
-
*/
|
|
1222
|
-
async approvePhoneChange(changeRequestId, input, opts) {
|
|
1223
|
-
if (typeof changeRequestId !== "string" || !changeRequestId.trim()) {
|
|
1224
|
-
throw clientInvalidInput("changeRequestId is required.");
|
|
1225
|
-
}
|
|
1226
|
-
if (!input || typeof input.deviceFingerprint !== "string" || !input.deviceFingerprint.trim()) {
|
|
1227
|
-
throw clientInvalidInput("deviceFingerprint is required.");
|
|
1228
|
-
}
|
|
1229
|
-
const decision = input.decision ?? "approve";
|
|
1230
|
-
if (decision !== "approve" && decision !== "deny") {
|
|
1231
|
-
throw clientInvalidInput('decision must be "approve" or "deny".');
|
|
1232
|
-
}
|
|
1233
|
-
const hasSignal = input.deviceSignal !== void 0;
|
|
1234
|
-
const hasSigner = typeof input.sign === "function";
|
|
1235
|
-
if (hasSignal === hasSigner) {
|
|
1236
|
-
throw clientInvalidInput("Pass exactly one of deviceSignal or sign.");
|
|
1237
|
-
}
|
|
1238
|
-
if (hasSignal) {
|
|
1239
|
-
const sig = input.deviceSignal;
|
|
1240
|
-
if (!sig || typeof sig.nonce !== "string" || !sig.nonce || typeof sig.timestamp !== "number" || !Number.isInteger(sig.timestamp) || typeof sig.signature !== "string" || !sig.signature) {
|
|
1241
|
-
throw clientInvalidInput(
|
|
1242
|
-
"deviceSignal needs a nonce (string), an integer epoch-seconds timestamp and a base64 signature."
|
|
1243
|
-
);
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
const id = encodeURIComponent(changeRequestId);
|
|
1247
|
-
const signal = opts?.signal;
|
|
1248
|
-
return this.withTokenRetry(async () => {
|
|
1249
|
-
let deviceSignal;
|
|
1250
|
-
if (hasSignal) {
|
|
1251
|
-
const sig = input.deviceSignal;
|
|
1252
|
-
deviceSignal = {
|
|
1253
|
-
transfer_id: changeRequestId,
|
|
1254
|
-
nonce: sig.nonce,
|
|
1255
|
-
timestamp: sig.timestamp,
|
|
1256
|
-
signature: sig.signature
|
|
1257
|
-
};
|
|
1258
|
-
} else {
|
|
1259
|
-
const nonce = randomNonce();
|
|
1260
|
-
const timestamp = Math.floor(Date.now() / 1e3);
|
|
1261
|
-
const signature = await input.sign(
|
|
1262
|
-
phoneChangeSignalMessage(changeRequestId, nonce, timestamp, decision)
|
|
1263
|
-
);
|
|
1264
|
-
if (typeof signature !== "string" || !signature) {
|
|
1265
|
-
throw clientInvalidInput("sign must return the base64 signature as a non-empty string.");
|
|
1266
|
-
}
|
|
1267
|
-
deviceSignal = { transfer_id: changeRequestId, nonce, timestamp, signature };
|
|
1268
|
-
}
|
|
1269
|
-
const raw = await this.post(
|
|
1270
|
-
`/api/sdk/players/phone/change-requests/${id}/approve`,
|
|
1271
|
-
{ device_fingerprint: input.deviceFingerprint, device_signal: deviceSignal, decision },
|
|
1272
|
-
signal
|
|
1273
|
-
);
|
|
1274
|
-
return toApprovePhoneChangeResult(raw, changeRequestId);
|
|
1275
|
-
});
|
|
1276
|
-
}
|
|
1277
|
-
/**
|
|
1278
|
-
* Interchangeable methods (§4.6): prove an *already-enrolled* method (e.g. the
|
|
1279
|
-
* INVO app device key) to authorize adding a new partner passkey. The returned
|
|
1280
|
-
* single-use grant lets a subsequent enrollPasskey() succeed instead of being
|
|
1281
|
-
* blocked with ENROLLMENT_REQUIRES_PROOF.
|
|
1282
|
-
*
|
|
1283
|
-
* begin -> navigator.credentials.get() -> complete with { link_id, webauthn_assertion }.
|
|
1284
|
-
*
|
|
1285
|
-
* Call it with no arguments: `await invo.linkDevice()`. THE SERVER MINTS THE
|
|
1286
|
-
* LINK ID, so there is nothing for the caller to supply. The parameter is kept
|
|
1287
|
-
* (optional, and sent but ignored by the server) so that code written against
|
|
1288
|
-
* 3.10 and earlier, which had to pass a placeholder, keeps compiling and
|
|
1289
|
-
* working unchanged.
|
|
1290
|
-
*/
|
|
1291
|
-
async linkDevice(linkId, opts) {
|
|
1292
|
-
this.assertWebAuthn();
|
|
1293
|
-
const signal = opts?.signal;
|
|
1294
|
-
return this.withTokenRetry(async () => {
|
|
1295
|
-
const begin = await this.post(
|
|
1296
|
-
"/api/sdk/device/link/webauthn/begin",
|
|
1297
|
-
// The server ignores the body and mints its own id; `linkId` travels only
|
|
1298
|
-
// for callers who still pass one.
|
|
1299
|
-
linkId ? { link_id: linkId } : {},
|
|
1300
|
-
signal
|
|
1301
|
-
);
|
|
1302
|
-
const cred = await navigator.credentials.get({
|
|
1303
|
-
publicKey: toRequestOptions(begin.options),
|
|
1304
|
-
signal
|
|
1305
|
-
});
|
|
1306
|
-
if (!cred) throw new Error("Passkey assertion was cancelled or returned no credential.");
|
|
1307
|
-
const raw = await this.post(
|
|
1308
|
-
"/api/sdk/device/link/webauthn/complete",
|
|
1309
|
-
{ link_id: begin.link_id, webauthn_assertion: assertionToJSON(cred) },
|
|
1310
|
-
signal
|
|
1311
|
-
);
|
|
1312
|
-
return { status: String(raw["status"] ?? ""), raw };
|
|
1313
|
-
});
|
|
1314
|
-
}
|
|
1315
|
-
/**
|
|
1316
|
-
* List the player's own pending items to collect (browser, player-token). Each row's
|
|
1317
|
-
* `kind` tells you which action to call: `"identity_gate"` → `approve*` (you initiated);
|
|
1318
|
-
* `"receiving_confirm"` → `confirmReceipt*` (a peer sent to you). PII-free — no claim
|
|
1319
|
-
* code or phone (those are only on the server-side `getInboundPending`).
|
|
1320
|
-
*/
|
|
1321
|
-
async getPendingCollect(opts) {
|
|
1322
|
-
return this.withTokenRetry(async () => {
|
|
1323
|
-
const raw = await this.get(
|
|
1324
|
-
"/api/sdk/transfers/pending",
|
|
1325
|
-
opts?.signal
|
|
1326
|
-
);
|
|
1327
|
-
const rows = Array.isArray(raw["pending"]) ? raw["pending"] : [];
|
|
1328
|
-
return { pending: rows.map(toPendingCollectItem), raw };
|
|
1329
|
-
});
|
|
1330
|
-
}
|
|
1331
|
-
/**
|
|
1332
|
-
* List the games/tenants this player can send/transfer to, with display metadata
|
|
1333
|
-
* inline (name, icon, currency, min/max limits) — one call, no per-game lookup.
|
|
1334
|
-
* Source game is the token's own game. Player-token (browser).
|
|
1335
|
-
*/
|
|
1336
|
-
async getDestinations(query, opts) {
|
|
1337
|
-
const direction = query?.direction ?? "transfer";
|
|
1338
|
-
return this.withTokenRetry(async () => {
|
|
1339
|
-
const raw = await this.get(
|
|
1340
|
-
`/api/sdk/destinations?direction=${encodeURIComponent(direction)}`,
|
|
1341
|
-
opts?.signal
|
|
1342
|
-
);
|
|
1343
|
-
return toDestinationsResult(raw, direction);
|
|
1344
|
-
});
|
|
1345
|
-
}
|
|
1346
|
-
/**
|
|
1347
|
-
* The player's balances for the token's game (browser, player-token). Amounts are
|
|
1348
|
-
* decimal strings. A player who hasn't transacted here yet returns `200` with an empty
|
|
1349
|
-
* `balances` array (show 0.00) — not an error; a `404 GAME_NOT_FOUND` (bad game/token)
|
|
1350
|
-
* throws. Rows include the currency symbol + icon URL (each may be null).
|
|
1351
|
-
*/
|
|
1352
|
-
async getBalance(opts) {
|
|
1353
|
-
return this.withTokenRetry(async () => {
|
|
1354
|
-
const raw = await this.get("/api/sdk/balance", opts?.signal);
|
|
1355
|
-
const rows = Array.isArray(raw["balances"]) ? raw["balances"] : [];
|
|
1356
|
-
const summary = raw["summary"] ?? {};
|
|
1357
|
-
return {
|
|
1358
|
-
gameId: raw["game_id"] ?? "",
|
|
1359
|
-
gameName: String(raw["game_name"] ?? ""),
|
|
1360
|
-
balances: rows.map(toBalanceRow),
|
|
1361
|
-
totalValue: String(summary["total_value"] ?? "0"),
|
|
1362
|
-
currencyCount: Number(summary["currency_count"] ?? rows.length),
|
|
1363
|
-
hasFunds: summary["has_funds"] === true,
|
|
1364
|
-
raw
|
|
1365
|
-
};
|
|
1366
|
-
});
|
|
1367
|
-
}
|
|
1368
|
-
// ---- Loyalty and rewards (player token) ----
|
|
1369
|
-
/**
|
|
1370
|
-
* The signed-in player's loyalty cards in this game: one card per program, each step with
|
|
1371
|
-
* its `state` and `progress` (`{ current, target }`, or `null` when the number could not
|
|
1372
|
-
* be read this time: render `state` alone then), and the rewards the player unlocked.
|
|
1373
|
-
* A card never carries a code; a redeemed reward shows its mask. Your server reads the
|
|
1374
|
-
* same cards for any of your players with `InvoServer.getPlayerRewards(playerEmail)`.
|
|
1375
|
-
*/
|
|
1376
|
-
async getMyRewards(opts) {
|
|
1377
|
-
return this.withTokenRetry(async () => {
|
|
1378
|
-
const raw = await this.get("/api/sdk/loyalty/me/card", opts?.signal);
|
|
1379
|
-
return toLoyaltyCardsResult(raw);
|
|
1380
|
-
});
|
|
1381
|
-
}
|
|
1382
|
-
/** Every reward the signed-in player holds or held, newest first. Codes are masked. */
|
|
1383
|
-
async getMyVault(opts) {
|
|
1384
|
-
return this.withTokenRetry(async () => {
|
|
1385
|
-
const raw = await this.get("/api/sdk/loyalty/me/vault", opts?.signal);
|
|
1386
|
-
return toLoyaltyVaultResult(raw);
|
|
1387
|
-
});
|
|
1388
|
-
}
|
|
1389
|
-
/**
|
|
1390
|
-
* Redeem one unlocked reward and return its code. This is the only response that
|
|
1391
|
-
* carries a code: show it straight away and never log, cache or store it. Calling again
|
|
1392
|
-
* for a reward this player already redeemed shows the code once more while the card's
|
|
1393
|
-
* `canRevealAgain` is true (`revealedAgain: true`). Never auto-retried.
|
|
1394
|
-
*
|
|
1395
|
-
* Refusals: `409 already_redeemed` (`err.isRewardAlreadyRedeemed`), `404
|
|
1396
|
-
* vault_entry_not_found` (`err.isRewardNotFound`), `410 vault_entry_expired`
|
|
1397
|
-
* (`err.isRewardExpired`), `409 inventory_exhausted` / `409 conflict`
|
|
1398
|
-
* (`err.isRewardUnavailable`: no units or codes left, or the reward is reserved or revoked).
|
|
1399
|
-
*/
|
|
1400
|
-
async redeemReward(vaultEntryId, opts) {
|
|
1401
|
-
if (typeof vaultEntryId !== "string" || !UUID_RE.test(vaultEntryId.trim())) {
|
|
1402
|
-
throw new InvoError({
|
|
1403
|
-
message: `vaultEntryId must be a reward's vaultEntryId (got ${JSON.stringify(vaultEntryId)}).`,
|
|
1404
|
-
code: "INVALID_INPUT",
|
|
1405
|
-
status: 0
|
|
1406
|
-
});
|
|
1407
|
-
}
|
|
1408
|
-
const id = vaultEntryId.trim();
|
|
1409
|
-
return this.withTokenRetry(async () => {
|
|
1410
|
-
const raw = await this.post(
|
|
1411
|
-
`/api/sdk/loyalty/me/vault/${encodeURIComponent(id)}/redeem`,
|
|
1412
|
-
void 0,
|
|
1413
|
-
opts?.signal
|
|
1414
|
-
);
|
|
1415
|
-
return toRedeemRewardResult(raw, id);
|
|
1416
|
-
});
|
|
1417
|
-
}
|
|
1418
|
-
/**
|
|
1419
|
-
* A short-lived link to INVO's hosted "My rewards" page for the signed-in player: their
|
|
1420
|
-
* cards, progress and rewards, with a Redeem button. Open `url` in a browser or web view
|
|
1421
|
-
* (it cannot be embedded in an iframe). Ask for a fresh link each time the player opens
|
|
1422
|
-
* the page; never share or store it.
|
|
1423
|
-
*/
|
|
1424
|
-
async getRewardsPageLink(opts) {
|
|
1425
|
-
return this.withTokenRetry(async () => {
|
|
1426
|
-
const raw = await this.post(
|
|
1427
|
-
"/api/sdk/loyalty/me/rewards-page",
|
|
1428
|
-
void 0,
|
|
1429
|
-
opts?.signal
|
|
1430
|
-
);
|
|
1431
|
-
return toRewardsPageLink(raw);
|
|
1432
|
-
});
|
|
1433
|
-
}
|
|
1434
|
-
/**
|
|
1435
|
-
* Report a gameplay event for the signed-in player to INVO's loyalty engine
|
|
1436
|
-
* (`POST /api/sdk/loyalty/events`, player token). Use it for sessions, milestones and
|
|
1437
|
-
* registered custom events (see {@link GameEventType}). Events your SERVER reports with
|
|
1438
|
-
* `InvoServer.reportGameEvent` are the ones trusted for rewards; prefer those when a
|
|
1439
|
-
* reward depends on the event.
|
|
1440
|
-
*
|
|
1441
|
-
* Pass your own `eventId` (a UUID) or reuse the returned one if you retry, so INVO counts
|
|
1442
|
-
* the event once. Not auto-retried from the browser.
|
|
1443
|
-
*
|
|
1444
|
-
* Refusals: `INVALID_INPUT` before the network (non-`game.*` type, malformed `eventId`,
|
|
1445
|
-
* `occurredAt` without a timezone, non-object payload); `400 RESERVED_EVENT_TYPE` /
|
|
1446
|
-
* `EVENT_TYPE_NOT_ALLOWED`; `401 SDK_TOKEN_MISSING` / `SDK_TOKEN_WRONG_SCOPE`;
|
|
1447
|
-
* `422 validation_failed`.
|
|
1448
|
-
*/
|
|
1449
|
-
async reportGameEvent(input, opts) {
|
|
1450
|
-
const { body, eventId } = buildGameEventBody(input);
|
|
1451
|
-
return this.withTokenRetry(async () => {
|
|
1452
|
-
const raw = await this.post("/api/sdk/loyalty/events", body, opts?.signal);
|
|
1453
|
-
return toReportGameEventResult(raw ?? {}, eventId);
|
|
1454
|
-
});
|
|
1455
|
-
}
|
|
1456
|
-
/**
|
|
1457
|
-
* First-enrollment OTP grant (§4.2). When `enrollPasskey()` throws
|
|
1458
|
-
* `ENROLLMENT_REQUIRES_AUTHORIZATION` (`err.isEnrollmentAuthorizationRequired`), call
|
|
1459
|
-
* this to send a 6-digit code to the player's phone + email on file, collect the code,
|
|
1460
|
-
* call `enrollmentVerify(code)`, then RETRY the SAME `enrollPasskey()` —
|
|
1461
|
-
* `register/complete` auto-consumes the server-side grant (30-min TTL). For
|
|
1462
|
-
* `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice`
|
|
1463
|
-
* (player still has the other method) or `recoveryBegin`/`recoveryComplete`
|
|
1464
|
-
* (player lost/deleted their passkey).
|
|
1465
|
-
*/
|
|
1466
|
-
async enrollmentBegin(opts) {
|
|
1467
|
-
return this.withTokenRetry(async () => {
|
|
1468
|
-
const raw = await this.post(
|
|
1469
|
-
"/api/sdk/device/enrollment/begin",
|
|
1470
|
-
void 0,
|
|
1471
|
-
opts?.signal
|
|
1472
|
-
);
|
|
1473
|
-
return {
|
|
1474
|
-
status: String(raw["status"] ?? ""),
|
|
1475
|
-
channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
|
|
1476
|
-
raw
|
|
1477
|
-
};
|
|
1478
|
-
});
|
|
1479
|
-
}
|
|
1480
|
-
/** Verify the enrollment OTP (see {@link enrollmentBegin}); on success, retry `enrollPasskey()`. */
|
|
1481
|
-
async enrollmentVerify(code, opts) {
|
|
1482
|
-
if (!code || !code.trim()) throw new Error("enrollmentVerify requires the OTP `code`.");
|
|
1483
|
-
return this.withTokenRetry(async () => {
|
|
1484
|
-
const raw = await this.post(
|
|
1485
|
-
"/api/sdk/device/enrollment/verify",
|
|
1486
|
-
{ code },
|
|
1487
|
-
opts?.signal
|
|
1488
|
-
);
|
|
1489
|
-
return { status: String(raw["status"] ?? ""), raw };
|
|
1490
|
-
});
|
|
1491
|
-
}
|
|
1492
|
-
/**
|
|
1493
|
-
* Passkey recovery — "Lost or replaced your passkey?". Deleting a passkey on the
|
|
1494
|
-
* device never tells the server the key is gone, so the next `enrollPasskey()` is
|
|
1495
|
-
* blocked by the anti-takeover gate with `ENROLLMENT_REQUIRES_PROOF`
|
|
1496
|
-
* (`err.isEnrollmentProofRequired`). When the player can't prove the old method
|
|
1497
|
-
* (they deleted/lost it — otherwise prefer `linkDevice`), run:
|
|
1498
|
-
*
|
|
1499
|
-
* 1. `recoveryBegin()` — sends a one-time code to the phone/email on file
|
|
1500
|
-
* (422 `no_channel_on_file`, 429 `rate_limited` at 5/10min).
|
|
1501
|
-
* 2. `recoveryComplete(code)` — deactivates the stale server-side passkey and
|
|
1502
|
-
* authorizes a fresh enrollment (400 `ENROLLMENT_CODE_INVALID` on a wrong/
|
|
1503
|
-
* expired code — attempt-capped; let the user retry or resend).
|
|
1504
|
-
* 3. Immediately retry the SAME `enrollPasskey()` — it now succeeds.
|
|
1505
|
-
*
|
|
1506
|
-
* The owner also gets an out-of-band "your passkey was reset" SMS/email — that's
|
|
1507
|
-
* the intended tamper alert; surface nothing special for it.
|
|
1508
|
-
*
|
|
1509
|
-
* ⚠ 24-HOUR MONEY COOLDOWN: a recovery-enrolled passkey logs in and COLLECTS
|
|
1510
|
-
* funds immediately, but `approveSend`/`approveTransfer` throw
|
|
1511
|
-
* `PASSKEY_RECOVERY_COOLDOWN` (403; `err.isPasskeyRecoveryCooldown`,
|
|
1512
|
-
* `err.retryAfterAt`) for 24h — SIM-swap protection. Show the pause message with
|
|
1513
|
-
* the timestamp; do not retry-loop it.
|
|
1514
|
-
*
|
|
1515
|
-
* If the OS itself fails to SAVE a new passkey ("there is a problem saving your
|
|
1516
|
-
* passkey"), have the user delete the stale entry in their password manager first
|
|
1517
|
-
* (iPhone: Settings → Passwords; Android: Google Password Manager; Windows:
|
|
1518
|
-
* Settings → Accounts → Passkeys).
|
|
1519
|
-
*/
|
|
1520
|
-
async recoveryBegin(opts) {
|
|
1521
|
-
return this.withTokenRetry(async () => {
|
|
1522
|
-
const raw = await this.post(
|
|
1523
|
-
"/api/sdk/device/recover/begin",
|
|
1524
|
-
void 0,
|
|
1525
|
-
opts?.signal
|
|
1526
|
-
);
|
|
1527
|
-
return {
|
|
1528
|
-
status: String(raw["status"] ?? ""),
|
|
1529
|
-
channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
|
|
1530
|
-
raw
|
|
1531
|
-
};
|
|
1532
|
-
});
|
|
1533
|
-
}
|
|
1534
|
-
/** Verify the recovery code (see {@link recoveryBegin}); on success, call `enrollPasskey()`. */
|
|
1535
|
-
async recoveryComplete(code, opts) {
|
|
1536
|
-
if (!code || !code.trim()) throw new Error("recoveryComplete requires the one-time `code`.");
|
|
1537
|
-
return this.withTokenRetry(async () => {
|
|
1538
|
-
const raw = await this.post(
|
|
1539
|
-
"/api/sdk/device/recover/complete",
|
|
1540
|
-
{ code },
|
|
1541
|
-
opts?.signal
|
|
1542
|
-
);
|
|
1543
|
-
return {
|
|
1544
|
-
status: String(raw["status"] ?? ""),
|
|
1545
|
-
deactivatedCount: Number(raw["deactivated_count"] ?? 0),
|
|
1546
|
-
next: typeof raw["next"] === "string" ? raw["next"] : void 0,
|
|
1547
|
-
raw
|
|
1548
|
-
};
|
|
1549
|
-
});
|
|
1550
|
-
}
|
|
1551
|
-
// --- internals ---
|
|
1552
|
-
/** POST with the current player token. Token-expiry retry is handled one level
|
|
1553
|
-
* up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
|
|
1554
|
-
async post(path, body, signal) {
|
|
1555
|
-
return this.http.post(path, body, this.auth, { signal });
|
|
1556
|
-
}
|
|
1557
|
-
async get(path, signal) {
|
|
1558
|
-
return this.http.get(path, this.auth, { signal });
|
|
1559
|
-
}
|
|
1560
|
-
/**
|
|
1561
|
-
* Run a whole flow, retrying it ONCE if any call fails with SDK_TOKEN_EXPIRED
|
|
1562
|
-
* and a `refreshToken` hook is configured. We re-run the entire begin→get→
|
|
1563
|
-
* complete ceremony (not just the failed call) so the retry always uses a fresh,
|
|
1564
|
-
* unconsumed challenge — never replaying a single-use WebAuthn assertion (§4.4).
|
|
1565
|
-
* The refresh is single-flighted so concurrent expiries trigger one re-mint.
|
|
1566
|
-
*/
|
|
1567
|
-
async withTokenRetry(run) {
|
|
1568
|
-
try {
|
|
1569
|
-
return await run();
|
|
1570
|
-
} catch (err) {
|
|
1571
|
-
if (err instanceof InvoError && err.isTokenExpired && await this.tryRefresh()) {
|
|
1572
|
-
return await run();
|
|
1573
|
-
}
|
|
1574
|
-
throw err;
|
|
1575
|
-
}
|
|
1576
|
-
}
|
|
1577
|
-
async tryRefresh() {
|
|
1578
|
-
if (!this.refreshToken) return false;
|
|
1579
|
-
if (!this.refreshInFlight) {
|
|
1580
|
-
this.refreshInFlight = Promise.resolve(this.refreshToken()).finally(() => {
|
|
1581
|
-
this.refreshInFlight = void 0;
|
|
1582
|
-
});
|
|
1583
|
-
}
|
|
1584
|
-
const fresh = await this.refreshInFlight;
|
|
1585
|
-
if (!fresh) return false;
|
|
1586
|
-
this.auth = { kind: "bearer", token: fresh };
|
|
1587
|
-
return true;
|
|
1588
|
-
}
|
|
1589
|
-
async runAssertion(beginPath, beginBody, signal) {
|
|
1590
|
-
this.assertWebAuthn();
|
|
1591
|
-
const options = await this.post(beginPath, beginBody, signal);
|
|
1592
|
-
const cred = await navigator.credentials.get({
|
|
1593
|
-
publicKey: toRequestOptions(options),
|
|
1594
|
-
signal
|
|
1595
|
-
});
|
|
1596
|
-
if (!cred) throw new Error("Passkey assertion was cancelled or returned no credential.");
|
|
1597
|
-
return assertionToJSON(cred);
|
|
1598
|
-
}
|
|
1599
|
-
async approve(flow, transactionId, opts) {
|
|
1600
|
-
const id = encodeURIComponent(transactionId);
|
|
1601
|
-
const signal = opts?.signal;
|
|
1602
|
-
return this.withTokenRetry(async () => {
|
|
1603
|
-
const assertion = await this.runAssertion(
|
|
1604
|
-
`/api/sdk/${flow}/${id}/approve/webauthn/begin`,
|
|
1605
|
-
void 0,
|
|
1606
|
-
signal
|
|
1607
|
-
);
|
|
1608
|
-
const raw = await this.post(
|
|
1609
|
-
`/api/sdk/${flow}/${id}/approve`,
|
|
1610
|
-
{ webauthn_assertion: assertion },
|
|
1611
|
-
signal
|
|
1612
|
-
);
|
|
1613
|
-
return toApproveResult(raw, transactionId);
|
|
1614
|
-
});
|
|
1615
|
-
}
|
|
1616
|
-
async confirmReceipt(flow, transactionId, opts) {
|
|
1617
|
-
const id = encodeURIComponent(transactionId);
|
|
1618
|
-
const signal = opts?.signal;
|
|
1619
|
-
return this.withTokenRetry(async () => {
|
|
1620
|
-
const assertion = await this.runAssertion(
|
|
1621
|
-
`/api/sdk/${flow}/${id}/confirm-receipt/webauthn/begin`,
|
|
1622
|
-
void 0,
|
|
1623
|
-
signal
|
|
1624
|
-
);
|
|
1625
|
-
const raw = await this.post(
|
|
1626
|
-
`/api/sdk/${flow}/${id}/confirm-receipt`,
|
|
1627
|
-
{ webauthn_assertion: assertion },
|
|
1628
|
-
signal
|
|
1629
|
-
);
|
|
1630
|
-
return toConfirmReceiptResult(raw);
|
|
1631
|
-
});
|
|
1632
|
-
}
|
|
1633
|
-
};
|
|
1634
|
-
|
|
1635
|
-
export { CheckoutClient, InvoClient, PlatformCommerceClient, isPurchaseCredited, isPurchaseExpired, isPurchaseRefunded, isPurchaseRefused, nothingWasCharged };
|
|
1
|
+
export { CheckoutClient, InvoClient, PlatformCommerceClient } from './chunk-7O5JT3LK.js';
|
|
2
|
+
export { InvoError, isPurchaseCredited, isPurchaseExpired, isPurchaseRefunded, isPurchaseRefused, nothingWasCharged, phoneChangeSignalMessage } from './chunk-TCT2QSVB.js';
|
|
1636
3
|
//# sourceMappingURL=index.js.map
|
|
1637
4
|
//# sourceMappingURL=index.js.map
|