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