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