@didit-protocol/sdk-web 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -0
- package/dist/didit-sdk.cjs.js +944 -3
- package/dist/didit-sdk.cjs.js.map +1 -1
- package/dist/didit-sdk.esm.js +943 -4
- package/dist/didit-sdk.esm.js.map +1 -1
- package/dist/didit-sdk.umd.js +944 -3
- package/dist/didit-sdk.umd.js.map +1 -1
- package/dist/didit-sdk.umd.min.js +2 -2
- package/dist/didit-sdk.umd.min.js.map +1 -1
- package/dist/index.d.ts +246 -2
- package/package.json +6 -2
package/dist/didit-sdk.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Didit SDK for Web v0.
|
|
2
|
+
* Didit SDK for Web v0.3.0
|
|
3
3
|
* (c) 2026 Didit
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -180,6 +180,14 @@
|
|
|
180
180
|
ariaLabelModal: "Didit যাচাইকরণ",
|
|
181
181
|
ariaLabelClose: "যাচাইকরণ বন্ধ করুন"
|
|
182
182
|
},
|
|
183
|
+
bs: {
|
|
184
|
+
exitTitle: "Izaći iz verifikacije?",
|
|
185
|
+
exitMessage: "Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",
|
|
186
|
+
continueButton: "Nastavi",
|
|
187
|
+
exitButton: "Izađi",
|
|
188
|
+
ariaLabelModal: "Didit verifikacija",
|
|
189
|
+
ariaLabelClose: "Zatvori verifikaciju"
|
|
190
|
+
},
|
|
183
191
|
ca: {
|
|
184
192
|
exitTitle: "Sortir de la verificació?",
|
|
185
193
|
exitMessage: "Sortir finalitzarà el procés de verificació. N'esteu segur?",
|
|
@@ -341,6 +349,14 @@
|
|
|
341
349
|
ariaLabelModal: "Didit შემოწმება",
|
|
342
350
|
ariaLabelClose: "შემოწმების დახურვა"
|
|
343
351
|
},
|
|
352
|
+
kk: {
|
|
353
|
+
exitTitle: "Растаудан шығасыз ба?",
|
|
354
|
+
exitMessage: "Шығу растау процесін аяқтайды. Сенімдісіз бе?",
|
|
355
|
+
continueButton: "Жалғастыру",
|
|
356
|
+
exitButton: "Шығу",
|
|
357
|
+
ariaLabelModal: "Didit растауы",
|
|
358
|
+
ariaLabelClose: "Растауды жабу"
|
|
359
|
+
},
|
|
344
360
|
ko: {
|
|
345
361
|
exitTitle: "인증을 종료하시겠습니까?",
|
|
346
362
|
exitMessage: "종료하면 인증 절차가 중단됩니다. 확실하십니까?",
|
|
@@ -349,6 +365,14 @@
|
|
|
349
365
|
ariaLabelModal: "Didit 인증",
|
|
350
366
|
ariaLabelClose: "인증 닫기"
|
|
351
367
|
},
|
|
368
|
+
ky: {
|
|
369
|
+
exitTitle: "Текшерүүдөн чыгасызбы?",
|
|
370
|
+
exitMessage: "Чыгуу текшерүү процессин токтотот. Ишенесизби?",
|
|
371
|
+
continueButton: "Улантуу",
|
|
372
|
+
exitButton: "Чыгуу",
|
|
373
|
+
ariaLabelModal: "Didit текшерүүсү",
|
|
374
|
+
ariaLabelClose: "Текшерүүнү жабуу"
|
|
375
|
+
},
|
|
352
376
|
lt: {
|
|
353
377
|
exitTitle: "Išeiti iš patvirtinimo?",
|
|
354
378
|
exitMessage: "Išėjimas nutrauks jūsų patvirtinimo procesą. Ar esate tikri?",
|
|
@@ -469,6 +493,14 @@
|
|
|
469
493
|
ariaLabelModal: "Xaqiijinta Didit",
|
|
470
494
|
ariaLabelClose: "Xir xaqiijinta"
|
|
471
495
|
},
|
|
496
|
+
sq: {
|
|
497
|
+
exitTitle: "Dilni nga verifikimi?",
|
|
498
|
+
exitMessage: "Dalja do të përfundojë procesin tuaj të verifikimit. A jeni të sigurt?",
|
|
499
|
+
continueButton: "Vazhdo",
|
|
500
|
+
exitButton: "Dil",
|
|
501
|
+
ariaLabelModal: "Verifikimi Didit",
|
|
502
|
+
ariaLabelClose: "Mbyll verifikimin"
|
|
503
|
+
},
|
|
472
504
|
sr: {
|
|
473
505
|
exitTitle: "Изаћи из верификације?",
|
|
474
506
|
exitMessage: "Изласком ћете прекинути процес верификације. Да ли сте сигурни?",
|
|
@@ -571,6 +603,8 @@
|
|
|
571
603
|
this.embedded = false;
|
|
572
604
|
this.embeddedContainer = null;
|
|
573
605
|
this.language = "en";
|
|
606
|
+
/** body.style.overflow value observed right before this modal locked scroll, restored on close(). */
|
|
607
|
+
this.previousBodyOverflow = null;
|
|
574
608
|
this.modalId = generateModalId();
|
|
575
609
|
this.config = {
|
|
576
610
|
zIndex: configuration?.zIndex ?? DEFAULT_CONFIG.zIndex,
|
|
@@ -904,6 +938,12 @@
|
|
|
904
938
|
this.embeddedContainer.appendChild(this.container);
|
|
905
939
|
}
|
|
906
940
|
setupEventListeners() {
|
|
941
|
+
// Idempotent: open() calls this every time it presents the modal, but a
|
|
942
|
+
// modal that was already open (or re-opened without an intervening
|
|
943
|
+
// close()) must not accumulate duplicate listeners.
|
|
944
|
+
if (this.boundHandleMessage || this.boundHandleKeydown) {
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
907
947
|
this.boundHandleMessage = this.handleMessage.bind(this);
|
|
908
948
|
window.addEventListener("message", this.boundHandleMessage);
|
|
909
949
|
this.boundHandleKeydown = this.handleKeydown.bind(this);
|
|
@@ -919,12 +959,38 @@
|
|
|
919
959
|
this.boundHandleKeydown = null;
|
|
920
960
|
}
|
|
921
961
|
}
|
|
962
|
+
pushToTop() {
|
|
963
|
+
const modals = VerificationModal.openModals;
|
|
964
|
+
const existingIndex = modals.indexOf(this);
|
|
965
|
+
if (existingIndex !== -1) {
|
|
966
|
+
modals.splice(existingIndex, 1);
|
|
967
|
+
}
|
|
968
|
+
modals.push(this);
|
|
969
|
+
}
|
|
970
|
+
removeFromStack() {
|
|
971
|
+
const modals = VerificationModal.openModals;
|
|
972
|
+
const existingIndex = modals.indexOf(this);
|
|
973
|
+
if (existingIndex !== -1) {
|
|
974
|
+
modals.splice(existingIndex, 1);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
isTopmost() {
|
|
978
|
+
const modals = VerificationModal.openModals;
|
|
979
|
+
return modals.length > 0 && modals[modals.length - 1] === this;
|
|
980
|
+
}
|
|
922
981
|
handleMessage(event) {
|
|
923
982
|
if (!this.iframe?.src)
|
|
924
983
|
return;
|
|
925
984
|
if (!isAllowedOrigin(event.origin, this.iframe.src)) {
|
|
926
985
|
return SDKLogger.warn("Received postMessage from unallowed origin:", event.origin);
|
|
927
986
|
}
|
|
987
|
+
// Scope every message to this modal's own iframe. Without this check, a
|
|
988
|
+
// second VerificationModal open at the same time (e.g. a transaction
|
|
989
|
+
// action modal stacked over the verification modal) would also react to
|
|
990
|
+
// postMessages meant for the other iframe.
|
|
991
|
+
if (!this.iframe || event.source !== this.iframe.contentWindow) {
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
928
994
|
SDKLogger.log("Received postMessage:", event.data);
|
|
929
995
|
let messageData;
|
|
930
996
|
try {
|
|
@@ -948,6 +1014,12 @@
|
|
|
948
1014
|
handleKeydown(event) {
|
|
949
1015
|
if (!this.state.isOpen)
|
|
950
1016
|
return;
|
|
1017
|
+
// When multiple modals are open at once, only the topmost one should
|
|
1018
|
+
// react to a keypress aimed at it (e.g. Escape closing a stacked
|
|
1019
|
+
// transaction action modal must not also trigger the exit confirmation
|
|
1020
|
+
// of the verification modal underneath it).
|
|
1021
|
+
if (!this.isTopmost())
|
|
1022
|
+
return;
|
|
951
1023
|
if (event.key === "Escape") {
|
|
952
1024
|
event.preventDefault();
|
|
953
1025
|
if (this.state.showConfirmation) {
|
|
@@ -987,11 +1059,19 @@
|
|
|
987
1059
|
this.callbacks.onCloseConfirmed();
|
|
988
1060
|
}
|
|
989
1061
|
open(verificationUrl) {
|
|
1062
|
+
// Whether this modal already held its scroll lock before this call. Re-opening
|
|
1063
|
+
// an already-open instance must not re-capture previousBodyOverflow, or it
|
|
1064
|
+
// would record this modal's own "hidden" lock and close() could never restore
|
|
1065
|
+
// the real pre-lock value.
|
|
1066
|
+
const wasAlreadyOpen = this.state.isOpen;
|
|
990
1067
|
this.language = detectLanguageFromUrl(verificationUrl);
|
|
991
1068
|
if (!this.overlay && !this.container) {
|
|
992
1069
|
this.createDOM();
|
|
993
|
-
this.setupEventListeners();
|
|
994
1070
|
}
|
|
1071
|
+
// Re-attach listeners every open() (idempotent) since close() now tears
|
|
1072
|
+
// them down; this lets the same instance be re-opened without a
|
|
1073
|
+
// destroy()/re-create cycle.
|
|
1074
|
+
this.setupEventListeners();
|
|
995
1075
|
SDKLogger.log("Opening with URL:", verificationUrl);
|
|
996
1076
|
this.state.isLoading = true;
|
|
997
1077
|
this.state.showConfirmation = false;
|
|
@@ -1001,10 +1081,20 @@
|
|
|
1001
1081
|
this.iframe.src = verificationUrl;
|
|
1002
1082
|
}
|
|
1003
1083
|
this.state.isOpen = true;
|
|
1084
|
+
this.pushToTop();
|
|
1004
1085
|
if (this.embedded) {
|
|
1005
1086
|
return;
|
|
1006
1087
|
}
|
|
1007
1088
|
this.overlay?.classList.add("active");
|
|
1089
|
+
// Capture whatever overflow value is currently in effect (which may
|
|
1090
|
+
// already be "hidden" because another modal is open) so close() can
|
|
1091
|
+
// restore exactly that value instead of clobbering a scroll lock owned
|
|
1092
|
+
// by a concurrently open modal. Skip the capture on a re-open: the value
|
|
1093
|
+
// in effect is this modal's own lock, and previousBodyOverflow already
|
|
1094
|
+
// holds the correct pre-lock value.
|
|
1095
|
+
if (!wasAlreadyOpen) {
|
|
1096
|
+
this.previousBodyOverflow = document.body.style.overflow;
|
|
1097
|
+
}
|
|
1008
1098
|
document.body.style.overflow = "hidden";
|
|
1009
1099
|
}
|
|
1010
1100
|
close() {
|
|
@@ -1012,6 +1102,8 @@
|
|
|
1012
1102
|
this.state.isOpen = false;
|
|
1013
1103
|
this.state.isLoading = true;
|
|
1014
1104
|
this.state.showConfirmation = false;
|
|
1105
|
+
this.removeFromStack();
|
|
1106
|
+
this.removeEventListeners();
|
|
1015
1107
|
if (this.iframe) {
|
|
1016
1108
|
this.iframe.src = "about:blank";
|
|
1017
1109
|
}
|
|
@@ -1019,7 +1111,8 @@
|
|
|
1019
1111
|
return;
|
|
1020
1112
|
}
|
|
1021
1113
|
this.overlay?.classList.remove("active");
|
|
1022
|
-
document.body.style.overflow = "";
|
|
1114
|
+
document.body.style.overflow = this.previousBodyOverflow ?? "";
|
|
1115
|
+
this.previousBodyOverflow = null;
|
|
1023
1116
|
}
|
|
1024
1117
|
destroy() {
|
|
1025
1118
|
SDKLogger.log("Destroying");
|
|
@@ -1044,6 +1137,652 @@
|
|
|
1044
1137
|
return this.state.isLoading;
|
|
1045
1138
|
}
|
|
1046
1139
|
}
|
|
1140
|
+
/**
|
|
1141
|
+
* Every currently-open modal, oldest first. Used so a single Escape
|
|
1142
|
+
* keypress (or other document-level shortcut) only acts on the topmost
|
|
1143
|
+
* modal when multiple VerificationModal instances are open at once (e.g.
|
|
1144
|
+
* a transaction action modal stacked over the verification modal).
|
|
1145
|
+
*/
|
|
1146
|
+
VerificationModal.openModals = [];
|
|
1147
|
+
|
|
1148
|
+
/**
|
|
1149
|
+
* Minimal self-contained port of the didit-fp-v2 device fingerprint used by the
|
|
1150
|
+
* Didit verification frontend. It collects stable browser signals, hashes them
|
|
1151
|
+
* with WebCrypto SHA-256 and persists a random device id in localStorage with a
|
|
1152
|
+
* cookie fallback. The payload shape matches the didit-fp-v2 schema so the Didit
|
|
1153
|
+
* backend middleware parses it identically to the verification flow:
|
|
1154
|
+
*
|
|
1155
|
+
* - headers: X-Didit-PID (persistent id) and X-Didit-FP-Hash (composite hash)
|
|
1156
|
+
* - body: a top-level `fingerprint_v2` field carrying the full payload
|
|
1157
|
+
*/
|
|
1158
|
+
const PERSISTENT_ID_STORAGE_KEY = "didit-pid-v1";
|
|
1159
|
+
const PERSISTENT_ID_COOKIE_NAME = "didit_pid";
|
|
1160
|
+
const PERSISTENT_ID_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365 * 2;
|
|
1161
|
+
const PERSISTENT_ID_BYTE_LENGTH = 16;
|
|
1162
|
+
const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
1163
|
+
let memoryPersistentId = null;
|
|
1164
|
+
let cachedPayload = null;
|
|
1165
|
+
let cachedPayloadPromise = null;
|
|
1166
|
+
function bytesToBase64Url(bytes) {
|
|
1167
|
+
let output = "";
|
|
1168
|
+
let i = 0;
|
|
1169
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
1170
|
+
const triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
|
|
1171
|
+
output += BASE64URL_ALPHABET[(triplet >> 18) & 0x3f];
|
|
1172
|
+
output += BASE64URL_ALPHABET[(triplet >> 12) & 0x3f];
|
|
1173
|
+
output += BASE64URL_ALPHABET[(triplet >> 6) & 0x3f];
|
|
1174
|
+
output += BASE64URL_ALPHABET[triplet & 0x3f];
|
|
1175
|
+
}
|
|
1176
|
+
if (i < bytes.length) {
|
|
1177
|
+
const remaining = bytes.length - i;
|
|
1178
|
+
const a = bytes[i];
|
|
1179
|
+
const b = remaining > 1 ? bytes[i + 1] : 0;
|
|
1180
|
+
const triplet = (a << 16) | (b << 8);
|
|
1181
|
+
output += BASE64URL_ALPHABET[(triplet >> 18) & 0x3f];
|
|
1182
|
+
output += BASE64URL_ALPHABET[(triplet >> 12) & 0x3f];
|
|
1183
|
+
if (remaining > 1) {
|
|
1184
|
+
output += BASE64URL_ALPHABET[(triplet >> 6) & 0x3f];
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
return output;
|
|
1188
|
+
}
|
|
1189
|
+
function randomBytes(length) {
|
|
1190
|
+
if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
|
|
1191
|
+
const buffer = new Uint8Array(length);
|
|
1192
|
+
crypto.getRandomValues(buffer);
|
|
1193
|
+
return buffer;
|
|
1194
|
+
}
|
|
1195
|
+
const fallback = new Uint8Array(length);
|
|
1196
|
+
for (let i = 0; i < length; i++) {
|
|
1197
|
+
fallback[i] = Math.floor(Math.random() * 256);
|
|
1198
|
+
}
|
|
1199
|
+
return fallback;
|
|
1200
|
+
}
|
|
1201
|
+
function randomBase64Url(byteLength) {
|
|
1202
|
+
return bytesToBase64Url(randomBytes(byteLength));
|
|
1203
|
+
}
|
|
1204
|
+
// SHA-256 truncated to the leading 128 bits, base64url-encoded (22 chars).
|
|
1205
|
+
// Same construction as the didit-fp-v2 composite hash in the verification frontend.
|
|
1206
|
+
async function sha256_128(input) {
|
|
1207
|
+
if (typeof crypto === "undefined" || !crypto.subtle) {
|
|
1208
|
+
throw new Error("WebCrypto SubtleCrypto is not available");
|
|
1209
|
+
}
|
|
1210
|
+
const bytes = new TextEncoder().encode(input);
|
|
1211
|
+
const view = new Uint8Array(bytes.byteLength);
|
|
1212
|
+
view.set(bytes);
|
|
1213
|
+
const digest = await crypto.subtle.digest("SHA-256", view.buffer);
|
|
1214
|
+
return bytesToBase64Url(new Uint8Array(digest).slice(0, 16));
|
|
1215
|
+
}
|
|
1216
|
+
// FNV-1a 32-bit fallback hash, only used when WebCrypto is unavailable.
|
|
1217
|
+
function fnv1a32(value) {
|
|
1218
|
+
let hash = 0x811c9dc5;
|
|
1219
|
+
for (let i = 0; i < value.length; i++) {
|
|
1220
|
+
hash ^= value.charCodeAt(i);
|
|
1221
|
+
hash = Math.imul(hash, 0x01000193);
|
|
1222
|
+
}
|
|
1223
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
1224
|
+
}
|
|
1225
|
+
function stableStringify(value) {
|
|
1226
|
+
if (value === null || value === undefined)
|
|
1227
|
+
return JSON.stringify(value ?? null);
|
|
1228
|
+
if (Array.isArray(value))
|
|
1229
|
+
return `[${value.map((v) => stableStringify(v)).join(",")}]`;
|
|
1230
|
+
if (typeof value === "object") {
|
|
1231
|
+
const keys = Object.keys(value).sort();
|
|
1232
|
+
const parts = keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`);
|
|
1233
|
+
return `{${parts.join(",")}}`;
|
|
1234
|
+
}
|
|
1235
|
+
return JSON.stringify(value);
|
|
1236
|
+
}
|
|
1237
|
+
function isValidPersistentId(value) {
|
|
1238
|
+
return typeof value === "string" && /^[A-Za-z0-9_-]{20,32}$/.test(value);
|
|
1239
|
+
}
|
|
1240
|
+
function readLocalStorageId() {
|
|
1241
|
+
try {
|
|
1242
|
+
if (typeof localStorage === "undefined")
|
|
1243
|
+
return null;
|
|
1244
|
+
const value = localStorage.getItem(PERSISTENT_ID_STORAGE_KEY);
|
|
1245
|
+
return isValidPersistentId(value) ? value : null;
|
|
1246
|
+
}
|
|
1247
|
+
catch {
|
|
1248
|
+
return null;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
function writeLocalStorageId(id) {
|
|
1252
|
+
try {
|
|
1253
|
+
if (typeof localStorage === "undefined")
|
|
1254
|
+
return;
|
|
1255
|
+
localStorage.setItem(PERSISTENT_ID_STORAGE_KEY, id);
|
|
1256
|
+
}
|
|
1257
|
+
catch {
|
|
1258
|
+
// Storage may be blocked (private mode, storage policies); cookie layer still applies.
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
function readCookieId() {
|
|
1262
|
+
try {
|
|
1263
|
+
if (typeof document === "undefined" || !document.cookie)
|
|
1264
|
+
return null;
|
|
1265
|
+
const prefix = `${PERSISTENT_ID_COOKIE_NAME}=`;
|
|
1266
|
+
for (const part of document.cookie.split(";")) {
|
|
1267
|
+
const trimmed = part.trim();
|
|
1268
|
+
if (trimmed.startsWith(prefix)) {
|
|
1269
|
+
const value = decodeURIComponent(trimmed.substring(prefix.length));
|
|
1270
|
+
return isValidPersistentId(value) ? value : null;
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
return null;
|
|
1274
|
+
}
|
|
1275
|
+
catch {
|
|
1276
|
+
return null;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
function writeCookieId(id) {
|
|
1280
|
+
try {
|
|
1281
|
+
if (typeof document === "undefined")
|
|
1282
|
+
return;
|
|
1283
|
+
const isSecure = typeof location !== "undefined" && location.protocol === "https:";
|
|
1284
|
+
const attributes = [
|
|
1285
|
+
`${PERSISTENT_ID_COOKIE_NAME}=${encodeURIComponent(id)}`,
|
|
1286
|
+
"Path=/",
|
|
1287
|
+
`Max-Age=${PERSISTENT_ID_COOKIE_MAX_AGE_SECONDS}`,
|
|
1288
|
+
"SameSite=Lax"
|
|
1289
|
+
];
|
|
1290
|
+
if (isSecure)
|
|
1291
|
+
attributes.push("Secure");
|
|
1292
|
+
document.cookie = attributes.join("; ");
|
|
1293
|
+
}
|
|
1294
|
+
catch {
|
|
1295
|
+
// Cookies may be blocked; localStorage layer still applies.
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
function loadOrCreatePersistentId() {
|
|
1299
|
+
const fromLocalStorage = readLocalStorageId();
|
|
1300
|
+
const fromCookie = readCookieId();
|
|
1301
|
+
let id;
|
|
1302
|
+
let sources;
|
|
1303
|
+
let wasCreated = false;
|
|
1304
|
+
if (fromLocalStorage) {
|
|
1305
|
+
id = fromLocalStorage;
|
|
1306
|
+
sources = fromCookie === fromLocalStorage ? ["localStorage", "cookie"] : ["localStorage"];
|
|
1307
|
+
}
|
|
1308
|
+
else if (fromCookie) {
|
|
1309
|
+
id = fromCookie;
|
|
1310
|
+
sources = ["cookie"];
|
|
1311
|
+
}
|
|
1312
|
+
else if (memoryPersistentId && isValidPersistentId(memoryPersistentId)) {
|
|
1313
|
+
id = memoryPersistentId;
|
|
1314
|
+
sources = ["memory"];
|
|
1315
|
+
}
|
|
1316
|
+
else {
|
|
1317
|
+
id = randomBase64Url(PERSISTENT_ID_BYTE_LENGTH);
|
|
1318
|
+
sources = ["fresh"];
|
|
1319
|
+
wasCreated = true;
|
|
1320
|
+
}
|
|
1321
|
+
memoryPersistentId = id;
|
|
1322
|
+
// Self-heal any layer that was missing or mismatched.
|
|
1323
|
+
if (fromLocalStorage !== id)
|
|
1324
|
+
writeLocalStorageId(id);
|
|
1325
|
+
if (fromCookie !== id)
|
|
1326
|
+
writeCookieId(id);
|
|
1327
|
+
return { id, sources, wasCreated };
|
|
1328
|
+
}
|
|
1329
|
+
function collectNavigatorSignals() {
|
|
1330
|
+
const nav = typeof navigator !== "undefined" ? navigator : null;
|
|
1331
|
+
const scr = typeof screen !== "undefined" ? screen : null;
|
|
1332
|
+
let timeZone = null;
|
|
1333
|
+
try {
|
|
1334
|
+
timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
|
|
1335
|
+
}
|
|
1336
|
+
catch {
|
|
1337
|
+
timeZone = null;
|
|
1338
|
+
}
|
|
1339
|
+
const uaData = nav
|
|
1340
|
+
? nav
|
|
1341
|
+
.userAgentData
|
|
1342
|
+
: undefined;
|
|
1343
|
+
return {
|
|
1344
|
+
userAgent: nav?.userAgent ?? "",
|
|
1345
|
+
platform: nav?.platform ?? null,
|
|
1346
|
+
language: nav?.language ?? "",
|
|
1347
|
+
languages: nav?.languages ? [...nav.languages] : [],
|
|
1348
|
+
hardwareConcurrency: typeof nav?.hardwareConcurrency === "number" ? nav.hardwareConcurrency : null,
|
|
1349
|
+
deviceMemory: (() => {
|
|
1350
|
+
const memory = nav ? nav.deviceMemory : undefined;
|
|
1351
|
+
return typeof memory === "number" ? memory : null;
|
|
1352
|
+
})(),
|
|
1353
|
+
maxTouchPoints: typeof nav?.maxTouchPoints === "number" ? nav.maxTouchPoints : null,
|
|
1354
|
+
devicePixelRatio: typeof window !== "undefined" && typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : null,
|
|
1355
|
+
screenWidth: typeof scr?.width === "number" ? scr.width : null,
|
|
1356
|
+
screenHeight: typeof scr?.height === "number" ? scr.height : null,
|
|
1357
|
+
colorDepth: typeof scr?.colorDepth === "number" ? scr.colorDepth : null,
|
|
1358
|
+
timeZone,
|
|
1359
|
+
uaDataPlatform: uaData?.platform ?? null,
|
|
1360
|
+
uaDataMobile: typeof uaData?.mobile === "boolean" ? uaData.mobile : null,
|
|
1361
|
+
uaDataBrands: uaData?.brands ? uaData.brands.map((entry) => `${entry.brand} ${entry.version}`) : []
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
function detectWebViewKind(userAgent) {
|
|
1365
|
+
if (/;\s?wv\)/.test(userAgent) || /\bVersion\/[\d.]+\s+Chrome\/[\d.]+\s+Mobile\b/.test(userAgent)) {
|
|
1366
|
+
return "android-webview";
|
|
1367
|
+
}
|
|
1368
|
+
if (/FBAN|FBAV|Instagram|Line\/|MicroMessenger|Snapchat|musical_ly|BytedanceWebview/i.test(userAgent)) {
|
|
1369
|
+
return "in-app-browser";
|
|
1370
|
+
}
|
|
1371
|
+
if (/iPhone|iPad|iPod/.test(userAgent) && !/Safari\//.test(userAgent) && !/CriOS|FxiOS|EdgiOS/.test(userAgent)) {
|
|
1372
|
+
return "ios-webview";
|
|
1373
|
+
}
|
|
1374
|
+
return "browser";
|
|
1375
|
+
}
|
|
1376
|
+
function detectBot(signals) {
|
|
1377
|
+
const flags = [];
|
|
1378
|
+
const userAgent = signals.navigator.userAgent;
|
|
1379
|
+
if (typeof navigator !== "undefined" && navigator.webdriver) {
|
|
1380
|
+
flags.push("webdriver");
|
|
1381
|
+
}
|
|
1382
|
+
if (/HeadlessChrome|PhantomJS|Selenium|puppeteer|playwright/i.test(userAgent)) {
|
|
1383
|
+
flags.push("headless-ua");
|
|
1384
|
+
}
|
|
1385
|
+
if (signals.navigator.uaDataMobile === false && /Android|iPhone|iPad/i.test(userAgent)) {
|
|
1386
|
+
flags.push("ua-mobile-mismatch");
|
|
1387
|
+
}
|
|
1388
|
+
return { score: Math.min(1, flags.length / 4), flags };
|
|
1389
|
+
}
|
|
1390
|
+
function canonicalizeSignals(signals) {
|
|
1391
|
+
// Only drift-resistant fields, serialized with stable key order so the same
|
|
1392
|
+
// device always produces the same composite hash.
|
|
1393
|
+
const stable = {
|
|
1394
|
+
platform: signals.platform,
|
|
1395
|
+
navigator: {
|
|
1396
|
+
ua: signals.navigator.userAgent,
|
|
1397
|
+
platform: signals.navigator.platform,
|
|
1398
|
+
lang: signals.navigator.language.split("-")[0],
|
|
1399
|
+
languages: [...signals.navigator.languages].sort(),
|
|
1400
|
+
concurrency: signals.navigator.hardwareConcurrency,
|
|
1401
|
+
memory: signals.navigator.deviceMemory,
|
|
1402
|
+
maxTouch: signals.navigator.maxTouchPoints,
|
|
1403
|
+
dpr: signals.navigator.devicePixelRatio,
|
|
1404
|
+
screen: [signals.navigator.screenWidth, signals.navigator.screenHeight],
|
|
1405
|
+
colorDepth: signals.navigator.colorDepth,
|
|
1406
|
+
timeZone: signals.navigator.timeZone,
|
|
1407
|
+
uaDataPlatform: signals.navigator.uaDataPlatform,
|
|
1408
|
+
uaDataBrands: signals.navigator.uaDataBrands
|
|
1409
|
+
},
|
|
1410
|
+
webview: signals.webview.kind
|
|
1411
|
+
};
|
|
1412
|
+
return stableStringify(stable);
|
|
1413
|
+
}
|
|
1414
|
+
async function computeCompositeHash(canonical) {
|
|
1415
|
+
try {
|
|
1416
|
+
return await sha256_128(canonical);
|
|
1417
|
+
}
|
|
1418
|
+
catch {
|
|
1419
|
+
// Environments without WebCrypto (very old browsers) fall back to a stable FNV-1a pair.
|
|
1420
|
+
return `fnv-${fnv1a32(canonical)}${fnv1a32(`${canonical}:fallback`)}`;
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
async function buildPayload() {
|
|
1424
|
+
const persistent = loadOrCreatePersistentId();
|
|
1425
|
+
const navigatorSignals = collectNavigatorSignals();
|
|
1426
|
+
const signals = {
|
|
1427
|
+
platform: "web",
|
|
1428
|
+
navigator: navigatorSignals,
|
|
1429
|
+
webview: { kind: detectWebViewKind(navigatorSignals.userAgent) }
|
|
1430
|
+
};
|
|
1431
|
+
const compositeHash = await computeCompositeHash(canonicalizeSignals(signals));
|
|
1432
|
+
return {
|
|
1433
|
+
version: 2,
|
|
1434
|
+
schema: "didit-fp-v2",
|
|
1435
|
+
platform: "web",
|
|
1436
|
+
collectedAt: new Date().toISOString(),
|
|
1437
|
+
persistentId: persistent.id,
|
|
1438
|
+
persistentIdSources: persistent.sources,
|
|
1439
|
+
persistentIdWasCreated: persistent.wasCreated,
|
|
1440
|
+
signals,
|
|
1441
|
+
bot: detectBot(signals),
|
|
1442
|
+
compositeHash
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
function isBrowserEnvironment() {
|
|
1446
|
+
return typeof window !== "undefined" && typeof navigator !== "undefined" && typeof document !== "undefined";
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Collects the device fingerprint. Resolves to null outside a browser
|
|
1450
|
+
* environment (SSR, Node, workers) so callers degrade to a fingerprint-less
|
|
1451
|
+
* request instead of sending junk signals. Never intended to throw into the
|
|
1452
|
+
* submit path: callers still guard with .catch(() => null).
|
|
1453
|
+
*/
|
|
1454
|
+
async function getDeviceFingerprintPayload() {
|
|
1455
|
+
if (!isBrowserEnvironment())
|
|
1456
|
+
return null;
|
|
1457
|
+
if (cachedPayload)
|
|
1458
|
+
return cachedPayload;
|
|
1459
|
+
if (!cachedPayloadPromise) {
|
|
1460
|
+
cachedPayloadPromise = buildPayload().then((payload) => {
|
|
1461
|
+
cachedPayload = payload;
|
|
1462
|
+
return payload;
|
|
1463
|
+
}, (error) => {
|
|
1464
|
+
// Do not cache failures; a later call may succeed.
|
|
1465
|
+
cachedPayloadPromise = null;
|
|
1466
|
+
throw error;
|
|
1467
|
+
});
|
|
1468
|
+
}
|
|
1469
|
+
return cachedPayloadPromise;
|
|
1470
|
+
}
|
|
1471
|
+
function buildFingerprintHeaders(payload) {
|
|
1472
|
+
if (!payload)
|
|
1473
|
+
return {};
|
|
1474
|
+
const headers = { "X-Didit-FP-V2": "1" };
|
|
1475
|
+
if (payload.persistentId)
|
|
1476
|
+
headers["X-Didit-PID"] = payload.persistentId;
|
|
1477
|
+
if (payload.compositeHash)
|
|
1478
|
+
headers["X-Didit-FP-Hash"] = payload.compositeHash;
|
|
1479
|
+
if (payload.signals.webview.kind)
|
|
1480
|
+
headers["X-Didit-FP-Webview"] = payload.signals.webview.kind;
|
|
1481
|
+
if (payload.bot.score)
|
|
1482
|
+
headers["X-Didit-FP-Bot-Score"] = payload.bot.score.toFixed(2);
|
|
1483
|
+
return headers;
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
const DEFAULT_TRANSACTION_BASE_URL = "https://verification.didit.me";
|
|
1487
|
+
const ACTION_POLL_INTERVAL_MS = 1500;
|
|
1488
|
+
const ACTION_POLL_MAX_ATTEMPTS = 10;
|
|
1489
|
+
const TRANSACTION_ERROR_MESSAGES = {
|
|
1490
|
+
invalid_token: "The transaction token is invalid.",
|
|
1491
|
+
expired_token: "The transaction token has expired.",
|
|
1492
|
+
validation: "The transaction payload failed validation.",
|
|
1493
|
+
network: "A network error occurred while contacting the Didit API."
|
|
1494
|
+
};
|
|
1495
|
+
/**
|
|
1496
|
+
* Typed error thrown by DiditSdk.submitTransaction.
|
|
1497
|
+
*
|
|
1498
|
+
* - "invalid_token": the X-Transaction-Token was rejected (missing, revoked, over max uses)
|
|
1499
|
+
* - "expired_token": the transaction token TTL has elapsed
|
|
1500
|
+
* - "validation": the payload failed validation; see fieldErrors for per-field details
|
|
1501
|
+
* - "network": the request could not complete or the API returned an unexpected error
|
|
1502
|
+
*/
|
|
1503
|
+
class DiditTransactionError extends Error {
|
|
1504
|
+
constructor(type, message, options) {
|
|
1505
|
+
super(message || TRANSACTION_ERROR_MESSAGES[type]);
|
|
1506
|
+
this.name = "DiditTransactionError";
|
|
1507
|
+
this.type = type;
|
|
1508
|
+
this.status = options?.status;
|
|
1509
|
+
this.fieldErrors = options?.fieldErrors;
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
function isPlainRecord(value) {
|
|
1513
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1514
|
+
}
|
|
1515
|
+
function compact(record) {
|
|
1516
|
+
const result = {};
|
|
1517
|
+
for (const [key, value] of Object.entries(record)) {
|
|
1518
|
+
if (value !== undefined)
|
|
1519
|
+
result[key] = value;
|
|
1520
|
+
}
|
|
1521
|
+
return result;
|
|
1522
|
+
}
|
|
1523
|
+
function mapDetails(details) {
|
|
1524
|
+
return compact({
|
|
1525
|
+
direction: details.direction,
|
|
1526
|
+
amount: details.amount,
|
|
1527
|
+
currency: details.currency,
|
|
1528
|
+
currencyType: details.currencyType,
|
|
1529
|
+
amountInDefaultCurrency: details.amountInDefaultCurrency,
|
|
1530
|
+
defaultCurrencyCode: details.defaultCurrencyCode,
|
|
1531
|
+
paymentDetails: details.paymentDetails,
|
|
1532
|
+
paymentTxnId: details.paymentTxnId,
|
|
1533
|
+
type: details.actionType,
|
|
1534
|
+
cryptoParams: details.cryptoParams
|
|
1535
|
+
});
|
|
1536
|
+
}
|
|
1537
|
+
function mapParticipant(participant) {
|
|
1538
|
+
if (!participant)
|
|
1539
|
+
return undefined;
|
|
1540
|
+
return compact({
|
|
1541
|
+
type: participant.type,
|
|
1542
|
+
externalUserId: participant.externalUserId,
|
|
1543
|
+
fullName: participant.fullName,
|
|
1544
|
+
firstName: participant.firstName,
|
|
1545
|
+
lastName: participant.lastName,
|
|
1546
|
+
dob: participant.dob,
|
|
1547
|
+
address: participant.address,
|
|
1548
|
+
institutionInfo: participant.institutionInfo,
|
|
1549
|
+
device: participant.device,
|
|
1550
|
+
paymentMethod: participant.paymentMethod
|
|
1551
|
+
? compact({
|
|
1552
|
+
type: participant.paymentMethod.type,
|
|
1553
|
+
accountId: participant.paymentMethod.accountId,
|
|
1554
|
+
issuingCountry: participant.paymentMethod.issuingCountry
|
|
1555
|
+
})
|
|
1556
|
+
: undefined
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
function mapTravelRule(travelRule) {
|
|
1560
|
+
if (!travelRule)
|
|
1561
|
+
return undefined;
|
|
1562
|
+
return compact({
|
|
1563
|
+
status: travelRule.status,
|
|
1564
|
+
protocol: travelRule.protocol,
|
|
1565
|
+
required: travelRule.required,
|
|
1566
|
+
obligationsCount: travelRule.obligationsCount,
|
|
1567
|
+
originatorData: travelRule.originatorData,
|
|
1568
|
+
beneficiaryData: travelRule.beneficiaryData,
|
|
1569
|
+
metadata: travelRule.metadata
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Maps the SDK-friendly camelCase payload onto the wire aliases accepted by the
|
|
1574
|
+
* Didit transactions API (txnId, txnDate, zoneId, type, info, subject,
|
|
1575
|
+
* counterparty, props, travelRule, includeCryptoScreening).
|
|
1576
|
+
*/
|
|
1577
|
+
function buildTransactionRequestBody(transaction) {
|
|
1578
|
+
return compact({
|
|
1579
|
+
txnId: transaction.txnId,
|
|
1580
|
+
txnDate: transaction.txnDate,
|
|
1581
|
+
zoneId: transaction.zoneId,
|
|
1582
|
+
type: transaction.category,
|
|
1583
|
+
info: mapDetails(transaction.details),
|
|
1584
|
+
subject: mapParticipant(transaction.subject),
|
|
1585
|
+
counterparty: mapParticipant(transaction.counterparty),
|
|
1586
|
+
props: transaction.customProperties,
|
|
1587
|
+
travelRule: mapTravelRule(transaction.travelRule),
|
|
1588
|
+
includeCryptoScreening: transaction.includeCryptoScreening
|
|
1589
|
+
});
|
|
1590
|
+
}
|
|
1591
|
+
function pickString(record, ...keys) {
|
|
1592
|
+
for (const key of keys) {
|
|
1593
|
+
const value = record[key];
|
|
1594
|
+
if (typeof value === "string" && value)
|
|
1595
|
+
return value;
|
|
1596
|
+
}
|
|
1597
|
+
return undefined;
|
|
1598
|
+
}
|
|
1599
|
+
function mapActionRequired(raw) {
|
|
1600
|
+
if (!isPlainRecord(raw))
|
|
1601
|
+
return undefined;
|
|
1602
|
+
const type = pickString(raw, "type");
|
|
1603
|
+
const url = pickString(raw, "url");
|
|
1604
|
+
if (!type || !url)
|
|
1605
|
+
return undefined;
|
|
1606
|
+
const action = { type, url };
|
|
1607
|
+
const sessionId = pickString(raw, "session_id", "sessionId");
|
|
1608
|
+
if (sessionId)
|
|
1609
|
+
action.sessionId = sessionId;
|
|
1610
|
+
const sessionToken = pickString(raw, "session_token", "sessionToken");
|
|
1611
|
+
if (sessionToken)
|
|
1612
|
+
action.sessionToken = sessionToken;
|
|
1613
|
+
const status = pickString(raw, "status");
|
|
1614
|
+
if (status)
|
|
1615
|
+
action.status = status;
|
|
1616
|
+
const widgetSessionId = pickString(raw, "widget_session_id", "widgetSessionId");
|
|
1617
|
+
if (widgetSessionId)
|
|
1618
|
+
action.widgetSessionId = widgetSessionId;
|
|
1619
|
+
const expiresAt = pickString(raw, "expires_at", "expiresAt");
|
|
1620
|
+
if (expiresAt)
|
|
1621
|
+
action.expiresAt = expiresAt;
|
|
1622
|
+
return action;
|
|
1623
|
+
}
|
|
1624
|
+
function mapTravelRuleStatus(raw) {
|
|
1625
|
+
const travelRule = raw.travel_rule ?? raw.travelRule;
|
|
1626
|
+
if (isPlainRecord(travelRule)) {
|
|
1627
|
+
const status = pickString(travelRule, "status");
|
|
1628
|
+
if (status)
|
|
1629
|
+
return status;
|
|
1630
|
+
}
|
|
1631
|
+
const props = raw.props;
|
|
1632
|
+
if (isPlainRecord(props)) {
|
|
1633
|
+
const status = pickString(props, "travel_rule_status", "travelRuleStatus");
|
|
1634
|
+
if (status)
|
|
1635
|
+
return status;
|
|
1636
|
+
}
|
|
1637
|
+
return pickString(raw, "travel_rule_status", "travelRuleStatus");
|
|
1638
|
+
}
|
|
1639
|
+
function mapTransactionResponse(raw) {
|
|
1640
|
+
const transactionId = pickString(raw, "uuid", "transaction_id", "transactionId");
|
|
1641
|
+
const status = pickString(raw, "status");
|
|
1642
|
+
if (!transactionId || !status) {
|
|
1643
|
+
// A missing id/status is not a valid transaction snapshot: fabricating
|
|
1644
|
+
// empty strings here would let a malformed response (envelope,
|
|
1645
|
+
// intercepting proxy, contract drift) look like a real result to
|
|
1646
|
+
// callers - e.g. the poll's statusMoved early-exit would trigger on an
|
|
1647
|
+
// empty status that merely differs from a real initialStatus.
|
|
1648
|
+
throw new DiditTransactionError("network", "Unexpected response shape from the Didit API: missing transaction id or status.");
|
|
1649
|
+
}
|
|
1650
|
+
const result = { transactionId, status };
|
|
1651
|
+
const travelRuleStatus = mapTravelRuleStatus(raw);
|
|
1652
|
+
if (travelRuleStatus)
|
|
1653
|
+
result.travelRuleStatus = travelRuleStatus;
|
|
1654
|
+
const actionRequired = mapActionRequired(raw.action_required ?? raw.actionRequired);
|
|
1655
|
+
if (actionRequired)
|
|
1656
|
+
result.actionRequired = actionRequired;
|
|
1657
|
+
return result;
|
|
1658
|
+
}
|
|
1659
|
+
function extractDetailMessage(body) {
|
|
1660
|
+
if (!isPlainRecord(body))
|
|
1661
|
+
return undefined;
|
|
1662
|
+
return pickString(body, "detail", "message", "error");
|
|
1663
|
+
}
|
|
1664
|
+
function classifyTransactionError(status, body) {
|
|
1665
|
+
const detail = extractDetailMessage(body);
|
|
1666
|
+
if (status === 401 || status === 403) {
|
|
1667
|
+
const serialized = `${detail ?? ""} ${pickString(isPlainRecord(body) ? body : {}, "code") ?? ""}`;
|
|
1668
|
+
if (/expired/i.test(serialized)) {
|
|
1669
|
+
return new DiditTransactionError("expired_token", detail, { status });
|
|
1670
|
+
}
|
|
1671
|
+
return new DiditTransactionError("invalid_token", detail, { status });
|
|
1672
|
+
}
|
|
1673
|
+
if (status === 400 || status === 422) {
|
|
1674
|
+
return new DiditTransactionError("validation", detail, {
|
|
1675
|
+
status,
|
|
1676
|
+
fieldErrors: isPlainRecord(body) ? body : undefined
|
|
1677
|
+
});
|
|
1678
|
+
}
|
|
1679
|
+
return new DiditTransactionError("network", `Request failed with status ${status}.`, { status });
|
|
1680
|
+
}
|
|
1681
|
+
async function readJsonBody(response) {
|
|
1682
|
+
try {
|
|
1683
|
+
return await response.json();
|
|
1684
|
+
}
|
|
1685
|
+
catch {
|
|
1686
|
+
return null;
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
async function performRequest(url, init) {
|
|
1690
|
+
if (typeof fetch !== "function") {
|
|
1691
|
+
throw new DiditTransactionError("network", "fetch is not available in this environment.");
|
|
1692
|
+
}
|
|
1693
|
+
let response;
|
|
1694
|
+
try {
|
|
1695
|
+
response = await fetch(url, init);
|
|
1696
|
+
}
|
|
1697
|
+
catch {
|
|
1698
|
+
throw new DiditTransactionError("network");
|
|
1699
|
+
}
|
|
1700
|
+
const body = await readJsonBody(response);
|
|
1701
|
+
if (!response.ok) {
|
|
1702
|
+
throw classifyTransactionError(response.status, body);
|
|
1703
|
+
}
|
|
1704
|
+
if (!isPlainRecord(body)) {
|
|
1705
|
+
throw new DiditTransactionError("network", "Unexpected empty response from the Didit API.", {
|
|
1706
|
+
status: response.status
|
|
1707
|
+
});
|
|
1708
|
+
}
|
|
1709
|
+
return mapTransactionResponse(body);
|
|
1710
|
+
}
|
|
1711
|
+
async function submitTransactionRequest(args) {
|
|
1712
|
+
const fingerprint = await getDeviceFingerprintPayload().catch(() => null);
|
|
1713
|
+
const body = buildTransactionRequestBody(args.transaction);
|
|
1714
|
+
if (fingerprint) {
|
|
1715
|
+
body.fingerprint_v2 = fingerprint;
|
|
1716
|
+
}
|
|
1717
|
+
return performRequest(`${args.baseUrl}/v1/transactions/`, {
|
|
1718
|
+
method: "POST",
|
|
1719
|
+
headers: {
|
|
1720
|
+
"Content-Type": "application/json",
|
|
1721
|
+
"X-Transaction-Token": args.transactionToken,
|
|
1722
|
+
...buildFingerprintHeaders(fingerprint)
|
|
1723
|
+
},
|
|
1724
|
+
body: JSON.stringify(body)
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
async function fetchTransaction(args) {
|
|
1728
|
+
return performRequest(`${args.baseUrl}/v1/transactions/${args.transactionId}/`, {
|
|
1729
|
+
method: "GET",
|
|
1730
|
+
headers: { "X-Transaction-Token": args.transactionToken }
|
|
1731
|
+
});
|
|
1732
|
+
}
|
|
1733
|
+
function delay(ms) {
|
|
1734
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1735
|
+
}
|
|
1736
|
+
/** Terminal auth failures that will never succeed on retry: keep polling would just burn the token's remaining uses. */
|
|
1737
|
+
function isTerminalPollError(error) {
|
|
1738
|
+
return error instanceof DiditTransactionError && (error.type === "invalid_token" || error.type === "expired_token");
|
|
1739
|
+
}
|
|
1740
|
+
/**
|
|
1741
|
+
* Re-fetches the transaction after an action flow finished or its modal was
|
|
1742
|
+
* closed. Polls with a bounded retry (never relies on a single event/attempt)
|
|
1743
|
+
* and stops early once the required action is cleared or the status moved on.
|
|
1744
|
+
* Returns the latest successfully fetched result, or null when every attempt
|
|
1745
|
+
* failed.
|
|
1746
|
+
*
|
|
1747
|
+
* A terminal auth failure (invalid_token/expired_token - e.g. a maxUses
|
|
1748
|
+
* token exhausted by the poll's own GETs, or the token TTL elapsing while
|
|
1749
|
+
* the user was in the action flow) aborts immediately instead of retrying:
|
|
1750
|
+
* it can never succeed, and each attempt would otherwise still count
|
|
1751
|
+
* against the token's use_count server-side. The error is rethrown so the
|
|
1752
|
+
* caller can surface it instead of silently returning a stale result.
|
|
1753
|
+
*
|
|
1754
|
+
* `isAborted` is polled between attempts so a caller that tears down (e.g.
|
|
1755
|
+
* DiditSdk.destroy()) can stop the loop from making further network calls.
|
|
1756
|
+
*/
|
|
1757
|
+
async function pollTransactionAfterAction(args) {
|
|
1758
|
+
const intervalMs = args.intervalMs ?? ACTION_POLL_INTERVAL_MS;
|
|
1759
|
+
const maxAttempts = Math.max(1, args.maxAttempts ?? ACTION_POLL_MAX_ATTEMPTS);
|
|
1760
|
+
let latest = null;
|
|
1761
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1762
|
+
if (args.isAborted?.())
|
|
1763
|
+
return latest;
|
|
1764
|
+
if (attempt > 0) {
|
|
1765
|
+
await delay(intervalMs);
|
|
1766
|
+
}
|
|
1767
|
+
if (args.isAborted?.())
|
|
1768
|
+
return latest;
|
|
1769
|
+
try {
|
|
1770
|
+
latest = await fetchTransaction(args);
|
|
1771
|
+
const actionResolved = !latest.actionRequired;
|
|
1772
|
+
const statusMoved = args.initialStatus !== undefined && latest.status !== args.initialStatus;
|
|
1773
|
+
if (actionResolved || statusMoved) {
|
|
1774
|
+
return latest;
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
catch (error) {
|
|
1778
|
+
if (isTerminalPollError(error)) {
|
|
1779
|
+
throw error;
|
|
1780
|
+
}
|
|
1781
|
+
// Transient failure; keep polling until the bound is reached.
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
return latest;
|
|
1785
|
+
}
|
|
1047
1786
|
|
|
1048
1787
|
class DiditSdk {
|
|
1049
1788
|
static get shared() {
|
|
@@ -1067,12 +1806,32 @@
|
|
|
1067
1806
|
get isPresented() {
|
|
1068
1807
|
return this._modal?.isOpen() ?? false;
|
|
1069
1808
|
}
|
|
1809
|
+
/**
|
|
1810
|
+
* True while a transaction's wallet-ownership action modal (auto-launched
|
|
1811
|
+
* by submitTransaction) is on screen. verification_session actions are
|
|
1812
|
+
* never auto-launched, so they never affect this flag - see
|
|
1813
|
+
* {@link submitTransaction}. Tracked separately from {@link isPresented},
|
|
1814
|
+
* which reflects the verification modal only.
|
|
1815
|
+
*/
|
|
1816
|
+
get isActionModalPresented() {
|
|
1817
|
+
return this._actionModal?.isOpen() ?? false;
|
|
1818
|
+
}
|
|
1070
1819
|
get errorMessage() {
|
|
1071
1820
|
return this._errorMessage;
|
|
1072
1821
|
}
|
|
1073
1822
|
constructor() {
|
|
1074
1823
|
this._state = "idle";
|
|
1075
1824
|
this._modal = null;
|
|
1825
|
+
this._actionModal = null;
|
|
1826
|
+
this._actionModalSettle = null;
|
|
1827
|
+
/**
|
|
1828
|
+
* Bumped by destroy() to invalidate any transaction action in flight
|
|
1829
|
+
* (pending action modal and/or its follow-up poll) so a torn-down SDK
|
|
1830
|
+
* instance can never deliver a late onActionCompleted. A new
|
|
1831
|
+
* submitTransaction call always reads the current generation, so it is
|
|
1832
|
+
* unaffected by a destroy() that happened before it started.
|
|
1833
|
+
*/
|
|
1834
|
+
this._actionGeneration = 0;
|
|
1076
1835
|
SDKLogger.log("DiditSdk initialized");
|
|
1077
1836
|
}
|
|
1078
1837
|
async startVerification(options) {
|
|
@@ -1104,16 +1863,196 @@
|
|
|
1104
1863
|
this.handleError(error);
|
|
1105
1864
|
}
|
|
1106
1865
|
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Submits a transaction (including travel-rule and crypto-monitoring payloads)
|
|
1868
|
+
* directly from the end-user device.
|
|
1869
|
+
*
|
|
1870
|
+
* The request is authenticated with a short-lived transaction token minted by
|
|
1871
|
+
* your backend (POST /v3/transactions/sdk-token/) and sent via the
|
|
1872
|
+
* X-Transaction-Token header. Device intelligence is attached automatically:
|
|
1873
|
+
* the SDK collects a didit-fp-v2 fingerprint and sends it as the X-Didit-PID /
|
|
1874
|
+
* X-Didit-FP-Hash headers plus a `fingerprint_v2` body field.
|
|
1875
|
+
*
|
|
1876
|
+
* When the response contains an `actionRequired` block, the contract differs
|
|
1877
|
+
* by type:
|
|
1878
|
+
* - `wallet_ownership` (a same-origin, Didit-hosted widget): when
|
|
1879
|
+
* `autoLaunchAction` is not false, the SDK opens the action URL in the
|
|
1880
|
+
* verification modal itself. Once the flow completes or the modal is
|
|
1881
|
+
* closed, the transaction is re-fetched with a bounded poll (never a
|
|
1882
|
+
* single event) and `onActionCompleted` is invoked with the refreshed
|
|
1883
|
+
* result.
|
|
1884
|
+
* - `verification_session` (a biometric verification session): never
|
|
1885
|
+
* auto-launched, regardless of `autoLaunchAction`. It is only ever
|
|
1886
|
+
* returned in `result.actionRequired` for the host application to launch
|
|
1887
|
+
* with its own verification integration (e.g. `startVerification`).
|
|
1888
|
+
*
|
|
1889
|
+
* @param options Submission options: transactionToken, transaction payload,
|
|
1890
|
+
* optional baseUrl (defaults to https://verification.didit.me),
|
|
1891
|
+
* autoLaunchAction (defaults to true, applies to wallet_ownership actions
|
|
1892
|
+
* only) and onActionCompleted callback.
|
|
1893
|
+
* @returns The created transaction: transactionId, status, travelRuleStatus
|
|
1894
|
+
* and actionRequired when a user action is pending.
|
|
1895
|
+
* @throws {DiditTransactionError} Typed as "invalid_token", "expired_token",
|
|
1896
|
+
* "validation" (with fieldErrors) or "network".
|
|
1897
|
+
*/
|
|
1898
|
+
async submitTransaction(options) {
|
|
1899
|
+
if (!options?.transactionToken || typeof options.transactionToken !== "string") {
|
|
1900
|
+
throw new DiditTransactionError("invalid_token", "transactionToken is required.");
|
|
1901
|
+
}
|
|
1902
|
+
if (!options.transaction || typeof options.transaction !== "object") {
|
|
1903
|
+
throw new DiditTransactionError("validation", "transaction payload is required.");
|
|
1904
|
+
}
|
|
1905
|
+
if (!options.transaction.txnId || typeof options.transaction.txnId !== "string") {
|
|
1906
|
+
throw new DiditTransactionError("validation", "transaction.txnId is required.");
|
|
1907
|
+
}
|
|
1908
|
+
if (!options.transaction.details || typeof options.transaction.details !== "object") {
|
|
1909
|
+
throw new DiditTransactionError("validation", "transaction.details is required.");
|
|
1910
|
+
}
|
|
1911
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_TRANSACTION_BASE_URL).replace(/\/+$/, "");
|
|
1912
|
+
SDKLogger.log("Submitting transaction:", options.transaction.txnId);
|
|
1913
|
+
const result = await submitTransactionRequest({
|
|
1914
|
+
baseUrl,
|
|
1915
|
+
transactionToken: options.transactionToken,
|
|
1916
|
+
transaction: options.transaction
|
|
1917
|
+
});
|
|
1918
|
+
SDKLogger.log("Transaction submitted:", result);
|
|
1919
|
+
// Only wallet_ownership is a same-origin, Didit-hosted widget that is
|
|
1920
|
+
// safe for the SDK to open on the integrator's behalf. verification_session
|
|
1921
|
+
// is never auto-launched: it is already returned in result.actionRequired
|
|
1922
|
+
// above for the host to launch with its own verification integration.
|
|
1923
|
+
const autoLaunchAction = options.autoLaunchAction ?? true;
|
|
1924
|
+
if (autoLaunchAction && result.actionRequired?.type === "wallet_ownership" && result.actionRequired.url) {
|
|
1925
|
+
void this.runTransactionAction(baseUrl, options.transactionToken, result, options.onActionCompleted);
|
|
1926
|
+
}
|
|
1927
|
+
return result;
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* Dismisses everything currently on screen in one deterministic call: a
|
|
1931
|
+
* pending transaction action modal is treated as an abort (no follow-up
|
|
1932
|
+
* poll, no onActionCompleted) and the verification modal is always closed
|
|
1933
|
+
* afterwards, regardless of whether an action modal was present.
|
|
1934
|
+
*/
|
|
1107
1935
|
close() {
|
|
1108
1936
|
SDKLogger.log("Closing verification programmatically");
|
|
1937
|
+
this._actionModalSettle?.("aborted");
|
|
1109
1938
|
this.handleModalCloseConfirmed();
|
|
1110
1939
|
}
|
|
1111
1940
|
destroy() {
|
|
1112
1941
|
SDKLogger.log("Destroying SDK instance");
|
|
1942
|
+
// Invalidate any transaction action in flight so a poll that is already
|
|
1943
|
+
// running cannot deliver onActionCompleted after teardown.
|
|
1944
|
+
this._actionGeneration++;
|
|
1945
|
+
this._actionModalSettle?.("aborted");
|
|
1113
1946
|
this._modal?.destroy();
|
|
1114
1947
|
this._modal = null;
|
|
1115
1948
|
this.reset();
|
|
1116
1949
|
}
|
|
1950
|
+
async runTransactionAction(baseUrl, transactionToken, submitResult, onActionCompleted) {
|
|
1951
|
+
const generation = this._actionGeneration;
|
|
1952
|
+
let delivered = false;
|
|
1953
|
+
// Guarantees at-most-once delivery: a throwing integrator callback must
|
|
1954
|
+
// not be re-invoked by a surrounding catch, and a destroy() that
|
|
1955
|
+
// happened while we were awaiting the modal/poll must suppress delivery
|
|
1956
|
+
// entirely rather than calling back into a torn-down integration.
|
|
1957
|
+
const deliver = (result, error) => {
|
|
1958
|
+
if (delivered || generation !== this._actionGeneration)
|
|
1959
|
+
return;
|
|
1960
|
+
delivered = true;
|
|
1961
|
+
try {
|
|
1962
|
+
onActionCompleted?.(result, error);
|
|
1963
|
+
}
|
|
1964
|
+
catch (callbackError) {
|
|
1965
|
+
SDKLogger.error("onActionCompleted callback threw:", callbackError);
|
|
1966
|
+
}
|
|
1967
|
+
};
|
|
1968
|
+
try {
|
|
1969
|
+
const outcome = await this.presentTransactionActionModal(submitResult.actionRequired.url);
|
|
1970
|
+
if (outcome === "aborted" || generation !== this._actionGeneration) {
|
|
1971
|
+
return;
|
|
1972
|
+
}
|
|
1973
|
+
if (!submitResult.transactionId) {
|
|
1974
|
+
deliver(submitResult);
|
|
1975
|
+
return;
|
|
1976
|
+
}
|
|
1977
|
+
let refreshed = null;
|
|
1978
|
+
let pollError;
|
|
1979
|
+
try {
|
|
1980
|
+
refreshed = await pollTransactionAfterAction({
|
|
1981
|
+
baseUrl,
|
|
1982
|
+
transactionToken,
|
|
1983
|
+
transactionId: submitResult.transactionId,
|
|
1984
|
+
initialStatus: submitResult.status,
|
|
1985
|
+
isAborted: () => generation !== this._actionGeneration
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
catch (error) {
|
|
1989
|
+
if (error instanceof DiditTransactionError) {
|
|
1990
|
+
pollError = error;
|
|
1991
|
+
}
|
|
1992
|
+
else {
|
|
1993
|
+
throw error;
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
if (pollError) {
|
|
1997
|
+
// Terminal auth failure (invalid_token/expired_token): surface it
|
|
1998
|
+
// instead of silently handing back the stale pre-action result.
|
|
1999
|
+
deliver(submitResult, { type: pollError.type, message: pollError.message });
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
deliver(refreshed ?? submitResult);
|
|
2003
|
+
}
|
|
2004
|
+
catch (error) {
|
|
2005
|
+
SDKLogger.error("Transaction action follow-up failed:", error);
|
|
2006
|
+
deliver(submitResult);
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
presentTransactionActionModal(url) {
|
|
2010
|
+
// Abort any previous action modal before opening a new one.
|
|
2011
|
+
this._actionModalSettle?.("aborted");
|
|
2012
|
+
return new Promise((resolve) => {
|
|
2013
|
+
let settled = false;
|
|
2014
|
+
const settle = (outcome) => {
|
|
2015
|
+
if (settled)
|
|
2016
|
+
return;
|
|
2017
|
+
settled = true;
|
|
2018
|
+
const modal = this._actionModal;
|
|
2019
|
+
this._actionModal = null;
|
|
2020
|
+
this._actionModalSettle = null;
|
|
2021
|
+
modal?.destroy();
|
|
2022
|
+
resolve(outcome);
|
|
2023
|
+
};
|
|
2024
|
+
// this._actionModalSettle is assigned only after the modal is
|
|
2025
|
+
// successfully constructed and opened. If either throws (e.g. no
|
|
2026
|
+
// `document` in Node/SSR, or document.body not ready yet), the
|
|
2027
|
+
// settle callback must not be left dangling: a later close() would
|
|
2028
|
+
// otherwise find a stale this._actionModalSettle for a modal that
|
|
2029
|
+
// was never presented, "settle" it, and return early without ever
|
|
2030
|
+
// closing the actual verification modal.
|
|
2031
|
+
let modal;
|
|
2032
|
+
try {
|
|
2033
|
+
modal = new VerificationModal(undefined, {
|
|
2034
|
+
onClose: () => { },
|
|
2035
|
+
onCloseConfirmed: () => settle("finished"),
|
|
2036
|
+
onMessage: (event) => {
|
|
2037
|
+
this.onEvent?.(event);
|
|
2038
|
+
if (event.type === "didit:completed" || event.type === "didit:cancelled") {
|
|
2039
|
+
settle("finished");
|
|
2040
|
+
}
|
|
2041
|
+
},
|
|
2042
|
+
onIframeLoad: () => { }
|
|
2043
|
+
});
|
|
2044
|
+
SDKLogger.log("Launching required transaction action:", url);
|
|
2045
|
+
modal.open(url);
|
|
2046
|
+
}
|
|
2047
|
+
catch (error) {
|
|
2048
|
+
this._actionModal = null;
|
|
2049
|
+
this._actionModalSettle = null;
|
|
2050
|
+
throw error;
|
|
2051
|
+
}
|
|
2052
|
+
this._actionModal = modal;
|
|
2053
|
+
this._actionModalSettle = settle;
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
1117
2056
|
handleModalClose() {
|
|
1118
2057
|
SDKLogger.log("Modal close requested");
|
|
1119
2058
|
}
|
|
@@ -1265,7 +2204,9 @@
|
|
|
1265
2204
|
}
|
|
1266
2205
|
DiditSdk._instance = null;
|
|
1267
2206
|
|
|
2207
|
+
exports.DEFAULT_TRANSACTION_BASE_URL = DEFAULT_TRANSACTION_BASE_URL;
|
|
1268
2208
|
exports.DiditSdk = DiditSdk;
|
|
2209
|
+
exports.DiditTransactionError = DiditTransactionError;
|
|
1269
2210
|
exports.SDK_VERSION = SDK_VERSION;
|
|
1270
2211
|
exports.default = DiditSdk;
|
|
1271
2212
|
|