@vizualkei/neuma-client-sdk 0.100.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 +3 -0
- package/dist/NeumaClientHelper.d.ts +165 -0
- package/dist/NeumaClientHelper.js +345 -0
- package/dist/NeumaMobile.d.ts +5 -0
- package/dist/NeumaMobile.js +1199 -0
- package/dist/NeumaMobileInterface.d.ts +232 -0
- package/dist/NeumaMobileInterface.js +11 -0
- package/dist/biometricService.d.ts +2 -0
- package/dist/biometricService.js +55 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +16 -0
- package/dist/installLinks.d.ts +4 -0
- package/dist/installLinks.js +15 -0
- package/package.json +49 -0
|
@@ -0,0 +1,1199 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.NeumaMobileFactory = void 0;
|
|
7
|
+
const NeumaMobileInterface_1 = require("./NeumaMobileInterface");
|
|
8
|
+
const common_utils_1 = require("@vizualkei/common-utils");
|
|
9
|
+
const package_json_1 = __importDefault(require("../package.json"));
|
|
10
|
+
const biometricService_1 = require("./biometricService");
|
|
11
|
+
const SDK_VERSION = typeof package_json_1.default.version === 'string' ? package_json_1.default.version : '0.0.0+0';
|
|
12
|
+
const DEFAULT_BIOMETRIC_SERVICE = 'https://api.neuma.me:443';
|
|
13
|
+
// Initialize logging for the SDK
|
|
14
|
+
void (0, common_utils_1.initLogging)({ serviceName: 'neuma-client-sdk', level: 'info' });
|
|
15
|
+
// Operation code mappings for short URLs
|
|
16
|
+
const OP_CODES = {
|
|
17
|
+
enroll: 'e',
|
|
18
|
+
authenticate: 'a',
|
|
19
|
+
'clear-user': 'c',
|
|
20
|
+
'unenroll-user': 'u',
|
|
21
|
+
'retrieve-key': 'r',
|
|
22
|
+
restore: 'rs',
|
|
23
|
+
};
|
|
24
|
+
class NeumaMobile {
|
|
25
|
+
constructor() {
|
|
26
|
+
this.options = {
|
|
27
|
+
customSchemeBase: 'neumadplk://operation',
|
|
28
|
+
timeoutMs: 90000,
|
|
29
|
+
overlay: { appName: 'Neuma Mobile' },
|
|
30
|
+
apiServerPort: 443,
|
|
31
|
+
biometricService: DEFAULT_BIOMETRIC_SERVICE,
|
|
32
|
+
installUrlResolver: undefined,
|
|
33
|
+
qrAppLinkBase: undefined,
|
|
34
|
+
biometricSessionToken: undefined,
|
|
35
|
+
onQrCode: undefined,
|
|
36
|
+
onAppLaunchFailed: undefined,
|
|
37
|
+
};
|
|
38
|
+
this.versionInfo = this.parsePackageVersion(SDK_VERSION);
|
|
39
|
+
}
|
|
40
|
+
initialize(opts) {
|
|
41
|
+
const { overlay, timeoutMs, onQrCode, onAppLaunchFailed, biometricSessionToken, biometricService, installUrlResolver, qrAppLinkBase, } = opts;
|
|
42
|
+
this.options = {
|
|
43
|
+
...this.options,
|
|
44
|
+
timeoutMs: timeoutMs ?? this.options.timeoutMs,
|
|
45
|
+
overlay: { ...this.options.overlay, ...(overlay || {}) },
|
|
46
|
+
onQrCode: onQrCode ?? this.options.onQrCode,
|
|
47
|
+
onAppLaunchFailed: onAppLaunchFailed ?? this.options.onAppLaunchFailed,
|
|
48
|
+
biometricSessionToken: biometricSessionToken ?? this.options.biometricSessionToken,
|
|
49
|
+
biometricService: (0, biometricService_1.normalizeBiometricService)(biometricService ?? this.options.biometricService),
|
|
50
|
+
installUrlResolver: installUrlResolver ?? this.options.installUrlResolver,
|
|
51
|
+
qrAppLinkBase: qrAppLinkBase ?? this.options.qrAppLinkBase,
|
|
52
|
+
};
|
|
53
|
+
common_utils_1.logger.info('SDK initialized', {
|
|
54
|
+
timeoutMs: this.options.timeoutMs,
|
|
55
|
+
hasQrCallback: !!onQrCode,
|
|
56
|
+
hasAppLaunchFailedCallback: !!onAppLaunchFailed,
|
|
57
|
+
hasBiometricSessionToken: !!this.options.biometricSessionToken,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
detectLaunchPlatform() {
|
|
61
|
+
if (typeof navigator === 'undefined') {
|
|
62
|
+
return 'unknown';
|
|
63
|
+
}
|
|
64
|
+
const ua = navigator.userAgent.toLowerCase();
|
|
65
|
+
if (ua.includes('android')) {
|
|
66
|
+
return 'android';
|
|
67
|
+
}
|
|
68
|
+
if (/(iphone|ipad|ipod)/.test(ua)) {
|
|
69
|
+
return 'ios';
|
|
70
|
+
}
|
|
71
|
+
return 'unknown';
|
|
72
|
+
}
|
|
73
|
+
buildLaunchFailureContext(operation) {
|
|
74
|
+
const platform = this.detectLaunchPlatform();
|
|
75
|
+
const appName = this.options.overlay.appName || 'Neuma Mobile';
|
|
76
|
+
const installUrl = this.options.installUrlResolver?.(platform);
|
|
77
|
+
const message = `Install ${appName} to continue this biometric step.`;
|
|
78
|
+
return {
|
|
79
|
+
operation,
|
|
80
|
+
platform,
|
|
81
|
+
appName,
|
|
82
|
+
installUrl,
|
|
83
|
+
message,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
async getVersion() {
|
|
87
|
+
return this.versionInfo;
|
|
88
|
+
}
|
|
89
|
+
parsePackageVersion(version) {
|
|
90
|
+
const [core, buildMeta] = version.split('+');
|
|
91
|
+
const [major = '0', minor = '0', patch = '0'] = core.split('.');
|
|
92
|
+
const parsePart = (value) => {
|
|
93
|
+
const parsed = Number.parseInt(value, 10);
|
|
94
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
95
|
+
};
|
|
96
|
+
return {
|
|
97
|
+
major: parsePart(major),
|
|
98
|
+
minor: parsePart(minor),
|
|
99
|
+
patch: parsePart(patch),
|
|
100
|
+
build: buildMeta ? parsePart(buildMeta) : 0,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
normalizeUserDescriptor(result, fallback) {
|
|
104
|
+
const descriptor = result?.userDescriptor;
|
|
105
|
+
const userName = descriptor?.userName ?? result?.userName ?? fallback?.userName ?? 'Neuma User';
|
|
106
|
+
const email = descriptor?.email ?? result?.email ?? fallback?.email ?? '';
|
|
107
|
+
const phone = descriptor?.phone ?? result?.phone ?? fallback?.phone ?? '';
|
|
108
|
+
return { userName, email, phone };
|
|
109
|
+
}
|
|
110
|
+
persistEnrollment(info) {
|
|
111
|
+
if (typeof window === 'undefined')
|
|
112
|
+
return;
|
|
113
|
+
try {
|
|
114
|
+
if (!info) {
|
|
115
|
+
localStorage.removeItem('neuma_enrolled_user');
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const payload = {
|
|
119
|
+
userId: info.userId,
|
|
120
|
+
enrollmentId: info.enrollmentId,
|
|
121
|
+
enrolledAt: (info.enrolledAt instanceof Date
|
|
122
|
+
? info.enrolledAt
|
|
123
|
+
: new Date(info.enrolledAt)).toISOString(),
|
|
124
|
+
userDescriptor: info.userDescriptor,
|
|
125
|
+
};
|
|
126
|
+
localStorage.setItem('neuma_enrolled_user', JSON.stringify(payload));
|
|
127
|
+
}
|
|
128
|
+
catch { }
|
|
129
|
+
}
|
|
130
|
+
readPersistedEnrollment() {
|
|
131
|
+
if (typeof window === 'undefined')
|
|
132
|
+
return null;
|
|
133
|
+
try {
|
|
134
|
+
const raw = localStorage.getItem('neuma_enrolled_user');
|
|
135
|
+
if (!raw)
|
|
136
|
+
return null;
|
|
137
|
+
const parsed = JSON.parse(raw);
|
|
138
|
+
if (!parsed.userId || !parsed.userDescriptor)
|
|
139
|
+
return null;
|
|
140
|
+
const enrollmentId = typeof parsed.enrollmentId === 'string' ? parsed.enrollmentId : '';
|
|
141
|
+
if (!enrollmentId)
|
|
142
|
+
return null;
|
|
143
|
+
const enrolledAt = parsed.enrolledAt ? new Date(parsed.enrolledAt) : new Date();
|
|
144
|
+
return {
|
|
145
|
+
userId: parsed.userId,
|
|
146
|
+
enrollmentId,
|
|
147
|
+
enrolledAt,
|
|
148
|
+
userDescriptor: parsed.userDescriptor,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Persist pending-op metadata immediately before the deep link fires.
|
|
157
|
+
* Called from {@link invokeMobileApp} for the polling-based operations
|
|
158
|
+
* only.
|
|
159
|
+
*
|
|
160
|
+
* Why: when iOS Safari refocuses the originating browser tab via
|
|
161
|
+
* `openURL` from the mobile app, it often does NOT restore from the
|
|
162
|
+
* back-forward cache. The page reloads, the React component unmounts,
|
|
163
|
+
* and the in-flight `await waitForResult(...)` promise is gone — even
|
|
164
|
+
* though the biometric server has the result ready. Persisting the
|
|
165
|
+
* callbackId here lets the page resume polling on remount via
|
|
166
|
+
* {@link resumePendingResult}.
|
|
167
|
+
*
|
|
168
|
+
* Android additionally writes a localStorage fallback. Field logs from a
|
|
169
|
+
* low-end Android device showed Chrome returning through a non-bfcache
|
|
170
|
+
* back/forward navigation where `sessionStorage` had been lost, leaving
|
|
171
|
+
* no callback ID for recovery.
|
|
172
|
+
*
|
|
173
|
+
* Best-effort: failures (private mode, quota) are swallowed. The pending
|
|
174
|
+
* TTL guards abandoned fallback entries.
|
|
175
|
+
*/
|
|
176
|
+
persistPendingOperation(callbackId, operation) {
|
|
177
|
+
const record = JSON.stringify({ callbackId, operation, ts: Date.now() });
|
|
178
|
+
try {
|
|
179
|
+
if (typeof sessionStorage !== 'undefined') {
|
|
180
|
+
sessionStorage.setItem(NeumaMobile.PENDING_KEY, record);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
/* private mode / quota / etc. — ignore */
|
|
185
|
+
}
|
|
186
|
+
if (this.shouldUseAndroidPendingFallback()) {
|
|
187
|
+
try {
|
|
188
|
+
localStorage.setItem(NeumaMobile.ANDROID_PENDING_KEY, record);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
/* private mode / quota / etc. — ignore */
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
shouldUseAndroidPendingFallback() {
|
|
196
|
+
return this.detectLaunchPlatform() === 'android';
|
|
197
|
+
}
|
|
198
|
+
persistCompletedResult(callbackId, operation, payload, consuming = true) {
|
|
199
|
+
if (typeof sessionStorage === 'undefined')
|
|
200
|
+
return;
|
|
201
|
+
try {
|
|
202
|
+
const record = {
|
|
203
|
+
callbackId,
|
|
204
|
+
operation,
|
|
205
|
+
payload,
|
|
206
|
+
ts: Date.now(),
|
|
207
|
+
...(consuming ? { consumingAt: Date.now() } : {}),
|
|
208
|
+
};
|
|
209
|
+
sessionStorage.setItem(NeumaMobile.COMPLETED_RESULT_KEY, JSON.stringify(record));
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
/* private mode / quota / non-serializable payload — ignore */
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Remove the pending-op entry. Always safe to call.
|
|
217
|
+
*/
|
|
218
|
+
clearPendingOperation() {
|
|
219
|
+
try {
|
|
220
|
+
if (typeof sessionStorage !== 'undefined') {
|
|
221
|
+
sessionStorage.removeItem(NeumaMobile.PENDING_KEY);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
/* ignore */
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
if (typeof localStorage !== 'undefined') {
|
|
229
|
+
localStorage.removeItem(NeumaMobile.ANDROID_PENDING_KEY);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
/* ignore */
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
clearCompletedResult() {
|
|
237
|
+
if (typeof sessionStorage === 'undefined')
|
|
238
|
+
return;
|
|
239
|
+
try {
|
|
240
|
+
sessionStorage.removeItem(NeumaMobile.COMPLETED_RESULT_KEY);
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
/* ignore */
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
readCompletedResult() {
|
|
247
|
+
if (typeof sessionStorage === 'undefined')
|
|
248
|
+
return null;
|
|
249
|
+
try {
|
|
250
|
+
const raw = sessionStorage.getItem(NeumaMobile.COMPLETED_RESULT_KEY);
|
|
251
|
+
if (!raw)
|
|
252
|
+
return null;
|
|
253
|
+
const parsed = JSON.parse(raw);
|
|
254
|
+
if (!parsed ||
|
|
255
|
+
typeof parsed.callbackId !== 'string' ||
|
|
256
|
+
typeof parsed.operation !== 'string' ||
|
|
257
|
+
typeof parsed.ts !== 'number' ||
|
|
258
|
+
!('payload' in parsed)) {
|
|
259
|
+
this.clearCompletedResult();
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
const age = Date.now() - parsed.ts;
|
|
263
|
+
if (age > NeumaMobile.PENDING_TTL_MS) {
|
|
264
|
+
common_utils_1.logger.info('Completed result stale, clearing', { ageMs: age });
|
|
265
|
+
this.clearCompletedResult();
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
if (typeof parsed.consumingAt === 'number') {
|
|
269
|
+
const consumingAge = Date.now() - parsed.consumingAt;
|
|
270
|
+
if (consumingAge > NeumaMobile.COMPLETED_CONSUMING_GRACE_MS) {
|
|
271
|
+
common_utils_1.logger.info('Completed result consumption window expired, clearing', {
|
|
272
|
+
consumingAgeMs: consumingAge,
|
|
273
|
+
});
|
|
274
|
+
this.clearCompletedResult();
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
callbackId: parsed.callbackId,
|
|
280
|
+
operation: parsed.operation,
|
|
281
|
+
ts: parsed.ts,
|
|
282
|
+
payload: parsed.payload,
|
|
283
|
+
...(typeof parsed.consumingAt === 'number'
|
|
284
|
+
? { consumingAt: parsed.consumingAt }
|
|
285
|
+
: {}),
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
this.clearCompletedResult();
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
markCompletedResultConsuming(record) {
|
|
294
|
+
if (typeof sessionStorage === 'undefined')
|
|
295
|
+
return;
|
|
296
|
+
try {
|
|
297
|
+
sessionStorage.setItem(NeumaMobile.COMPLETED_RESULT_KEY, JSON.stringify({ ...record, consumingAt: Date.now() }));
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
/* ignore */
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
getReturnUrlPendingOperation() {
|
|
304
|
+
if (typeof window === 'undefined')
|
|
305
|
+
return null;
|
|
306
|
+
try {
|
|
307
|
+
const url = new URL(window.location.href);
|
|
308
|
+
const callbackId = url.searchParams.get('neuma_cb');
|
|
309
|
+
const operation = url.searchParams.get('neuma_op');
|
|
310
|
+
const tsRaw = url.searchParams.get('neuma_ts');
|
|
311
|
+
if (!callbackId || !operation || !tsRaw)
|
|
312
|
+
return null;
|
|
313
|
+
const ts = Number.parseInt(tsRaw, 10);
|
|
314
|
+
if (!Number.isFinite(ts))
|
|
315
|
+
return null;
|
|
316
|
+
const age = Date.now() - ts;
|
|
317
|
+
if (age > NeumaMobile.PENDING_TTL_MS) {
|
|
318
|
+
this.clearReturnUrlMarkers();
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
return { callbackId, operation, ts };
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
clearReturnUrlMarkers() {
|
|
328
|
+
if (typeof window === 'undefined' || typeof window.history === 'undefined') {
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
const url = new URL(window.location.href);
|
|
333
|
+
let changed = false;
|
|
334
|
+
for (const key of ['neuma_cb', 'neuma_op', 'neuma_ts']) {
|
|
335
|
+
if (url.searchParams.has(key)) {
|
|
336
|
+
url.searchParams.delete(key);
|
|
337
|
+
changed = true;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (changed) {
|
|
341
|
+
window.history.replaceState(window.history.state, '', url.toString());
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
/* ignore */
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
readPendingOperationFromSessionStorage() {
|
|
349
|
+
if (typeof sessionStorage === 'undefined')
|
|
350
|
+
return null;
|
|
351
|
+
try {
|
|
352
|
+
const raw = sessionStorage.getItem(NeumaMobile.PENDING_KEY);
|
|
353
|
+
if (!raw)
|
|
354
|
+
return null;
|
|
355
|
+
return this.parsePendingOperation(raw, () => this.clearPendingOperation());
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
this.clearPendingOperation();
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
readPendingOperationFromAndroidFallback() {
|
|
363
|
+
if (!this.shouldUseAndroidPendingFallback() || typeof localStorage === 'undefined') {
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
const raw = localStorage.getItem(NeumaMobile.ANDROID_PENDING_KEY);
|
|
368
|
+
if (!raw)
|
|
369
|
+
return null;
|
|
370
|
+
return this.parsePendingOperation(raw, () => {
|
|
371
|
+
try {
|
|
372
|
+
localStorage.removeItem(NeumaMobile.ANDROID_PENDING_KEY);
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
/* ignore */
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
try {
|
|
381
|
+
localStorage.removeItem(NeumaMobile.ANDROID_PENDING_KEY);
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
/* ignore */
|
|
385
|
+
}
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
parsePendingOperation(raw, clearInvalid) {
|
|
390
|
+
const parsed = JSON.parse(raw);
|
|
391
|
+
if (!parsed ||
|
|
392
|
+
typeof parsed.callbackId !== 'string' ||
|
|
393
|
+
typeof parsed.operation !== 'string' ||
|
|
394
|
+
typeof parsed.ts !== 'number') {
|
|
395
|
+
clearInvalid();
|
|
396
|
+
return null;
|
|
397
|
+
}
|
|
398
|
+
const age = Date.now() - parsed.ts;
|
|
399
|
+
if (age > NeumaMobile.PENDING_TTL_MS) {
|
|
400
|
+
common_utils_1.logger.info('Pending op stale, clearing', { ageMs: age });
|
|
401
|
+
clearInvalid();
|
|
402
|
+
return null;
|
|
403
|
+
}
|
|
404
|
+
return {
|
|
405
|
+
callbackId: parsed.callbackId,
|
|
406
|
+
operation: parsed.operation,
|
|
407
|
+
ts: parsed.ts,
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
getPendingOperation() {
|
|
411
|
+
const pending = this.readPendingOperationFromSessionStorage();
|
|
412
|
+
if (pending)
|
|
413
|
+
return pending;
|
|
414
|
+
const completed = this.readCompletedResult();
|
|
415
|
+
if (completed) {
|
|
416
|
+
return {
|
|
417
|
+
callbackId: completed.callbackId,
|
|
418
|
+
operation: completed.operation,
|
|
419
|
+
ts: completed.ts,
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
return this.readPendingOperationFromAndroidFallback() ?? this.getReturnUrlPendingOperation();
|
|
423
|
+
}
|
|
424
|
+
async resumePendingResult() {
|
|
425
|
+
const completed = this.readCompletedResult();
|
|
426
|
+
if (completed) {
|
|
427
|
+
common_utils_1.logger.info('Recovering cached completed operation result', {
|
|
428
|
+
callbackId: completed.callbackId,
|
|
429
|
+
operation: completed.operation,
|
|
430
|
+
ageMs: Date.now() - completed.ts,
|
|
431
|
+
});
|
|
432
|
+
this.markCompletedResultConsuming(completed);
|
|
433
|
+
this.clearPendingOperation();
|
|
434
|
+
return completed.payload;
|
|
435
|
+
}
|
|
436
|
+
const pending = this.getPendingOperation();
|
|
437
|
+
if (!pending)
|
|
438
|
+
return null;
|
|
439
|
+
// Offline operations don't have a server-side result to poll for.
|
|
440
|
+
if (pending.operation === 'retrieve-key' || pending.operation === 'clear-user') {
|
|
441
|
+
this.clearPendingResult();
|
|
442
|
+
return null;
|
|
443
|
+
}
|
|
444
|
+
common_utils_1.logger.info('Resuming pending operation polling', {
|
|
445
|
+
callbackId: pending.callbackId,
|
|
446
|
+
operation: pending.operation,
|
|
447
|
+
ageMs: Date.now() - pending.ts,
|
|
448
|
+
});
|
|
449
|
+
try {
|
|
450
|
+
const payload = await this.waitForResult(pending.callbackId, this.options.timeoutMs);
|
|
451
|
+
this.persistCompletedResult(pending.callbackId, pending.operation, payload);
|
|
452
|
+
return payload;
|
|
453
|
+
}
|
|
454
|
+
finally {
|
|
455
|
+
this.clearPendingOperation();
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
clearPendingResult() {
|
|
459
|
+
this.clearPendingOperation();
|
|
460
|
+
this.clearCompletedResult();
|
|
461
|
+
}
|
|
462
|
+
generateRandomId() {
|
|
463
|
+
return (Math.random().toString(36).substring(2, 15) +
|
|
464
|
+
Math.random().toString(36).substring(2, 15));
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Returns true only when running in **iOS Safari** — not iOS Chrome
|
|
468
|
+
* (`CriOS`), iOS Firefox (`FxiOS`), iOS Edge (`EdgiOS`), iOS Opera
|
|
469
|
+
* (`OPiOS`), iOS DuckDuckGo (`DuckDuckGo`), Brave on iOS, etc., and
|
|
470
|
+
* not Safari on macOS (the iPad-on-macOS-as-iPhone-imposter check
|
|
471
|
+
* uses platform too).
|
|
472
|
+
*
|
|
473
|
+
* Used to gate `returnUrl` emission. iOS Safari is the only browser
|
|
474
|
+
* where launching `https://...` from a third-party app reliably
|
|
475
|
+
* refocuses an existing tab; every other mobile browser opens a new
|
|
476
|
+
* tab, losing the originating tab's JS state. For those, the deep
|
|
477
|
+
* link should not carry `returnUrl` so the mobile app falls back to
|
|
478
|
+
* exit-on-Close (its legacy behavior).
|
|
479
|
+
*/
|
|
480
|
+
isIOSSafari() {
|
|
481
|
+
if (typeof window === 'undefined' || typeof navigator === 'undefined') {
|
|
482
|
+
return false;
|
|
483
|
+
}
|
|
484
|
+
const ua = navigator.userAgent;
|
|
485
|
+
// iPad on iPadOS 13+ identifies as Mac in UA but has touch points;
|
|
486
|
+
// include both checks. iPhone/iPod always show "iPhone" / "iPod".
|
|
487
|
+
const isIOS = /iPad|iPhone|iPod/.test(ua) ||
|
|
488
|
+
(/Macintosh/.test(ua) && navigator.maxTouchPoints > 1);
|
|
489
|
+
if (!isIOS)
|
|
490
|
+
return false;
|
|
491
|
+
// Reject all known iOS browsers that aren't Safari.
|
|
492
|
+
if (/CriOS|FxiOS|EdgiOS|OPiOS|YaBrowser|DuckDuckGo|Brave/.test(ua)) {
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
// Safari on iOS includes "Safari" in UA. (WebViews don't always.)
|
|
496
|
+
return /Safari/.test(ua);
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Injects `neuma_cb=<callbackId>` into the current browser URL via
|
|
500
|
+
* `history.replaceState` and returns the resulting `window.location.href`
|
|
501
|
+
* for use as the deep-link `returnUrl`.
|
|
502
|
+
*
|
|
503
|
+
* Why: when the mobile app later launches `returnUrl` to refocus the
|
|
504
|
+
* originating browser tab, the OS will refocus *some* tab matching that
|
|
505
|
+
* URL. The unique `neuma_cb=<callbackId>` query param disambiguates the
|
|
506
|
+
* originating tab so Safari does not open a new tab on return. For polling
|
|
507
|
+
* operations, the same markers also let the SDK resume polling after an
|
|
508
|
+
* iOS Safari remount. Offline operations (`retrieve-key`, `clear-user`)
|
|
509
|
+
* use the markers only for exact tab matching and do not persist pending
|
|
510
|
+
* polling state.
|
|
511
|
+
*
|
|
512
|
+
* Notes:
|
|
513
|
+
* - Returns null on every browser other than iOS Safari. Other browsers
|
|
514
|
+
* open a new tab on `openURL` / `ACTION_VIEW`, so emitting `returnUrl`
|
|
515
|
+
* would just leak the callbackId in the URL bar with no benefit.
|
|
516
|
+
* - Uses the current `history.state` (we never overwrite app state).
|
|
517
|
+
* - The `returnUrl` must be an `https://` URL — the mobile app validates
|
|
518
|
+
* this and silently drops non-https values.
|
|
519
|
+
* - The captured value must be passed byte-for-byte to the mobile app;
|
|
520
|
+
* callers must not mutate it.
|
|
521
|
+
*/
|
|
522
|
+
captureReturnUrl(callbackId, operation) {
|
|
523
|
+
// returnUrl flow is iOS-Safari-only. Other browsers open a new tab on
|
|
524
|
+
// openURL/ACTION_VIEW, so emitting returnUrl would create a new tab
|
|
525
|
+
// without any benefit.
|
|
526
|
+
if (!this.isIOSSafari()) {
|
|
527
|
+
common_utils_1.logger.info('Skipping returnUrl capture (not iOS Safari)');
|
|
528
|
+
return null;
|
|
529
|
+
}
|
|
530
|
+
if (typeof window === 'undefined' || typeof window.history === 'undefined') {
|
|
531
|
+
return null;
|
|
532
|
+
}
|
|
533
|
+
try {
|
|
534
|
+
const currentUrl = new URL(window.location.href);
|
|
535
|
+
// Only emit https returnUrl. Localhost / file:// dev environments
|
|
536
|
+
// produce non-https hrefs that the mobile app will reject.
|
|
537
|
+
if (currentUrl.protocol !== 'https:') {
|
|
538
|
+
common_utils_1.logger.info('Skipping returnUrl capture (non-https origin)', {
|
|
539
|
+
protocol: currentUrl.protocol,
|
|
540
|
+
});
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
currentUrl.searchParams.set('neuma_cb', callbackId);
|
|
544
|
+
currentUrl.searchParams.set('neuma_op', operation);
|
|
545
|
+
currentUrl.searchParams.set('neuma_ts', String(Date.now()));
|
|
546
|
+
const newHref = currentUrl.toString();
|
|
547
|
+
// Preserve existing app state; only swap the URL.
|
|
548
|
+
window.history.replaceState(window.history.state, '', newHref);
|
|
549
|
+
return window.location.href;
|
|
550
|
+
}
|
|
551
|
+
catch (err) {
|
|
552
|
+
common_utils_1.logger.warning('Failed to capture returnUrl', {
|
|
553
|
+
error: err instanceof Error ? err.message : String(err),
|
|
554
|
+
});
|
|
555
|
+
return null;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
isFailure(result) {
|
|
559
|
+
if (!result)
|
|
560
|
+
return false;
|
|
561
|
+
if (result.success === false || result.success === 'false')
|
|
562
|
+
return true;
|
|
563
|
+
if (typeof result.error === 'string' && result.error.length > 0)
|
|
564
|
+
return true;
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
isUserCancelledPayload(result) {
|
|
568
|
+
if (!result)
|
|
569
|
+
return false;
|
|
570
|
+
if (result?.cancelled)
|
|
571
|
+
return true;
|
|
572
|
+
const reason = String(result?.reason || '').toLowerCase();
|
|
573
|
+
if (reason === 'back' || reason === 'cancel' || reason === 'user_cancelled')
|
|
574
|
+
return true;
|
|
575
|
+
const code = String(result?.code || '').toUpperCase();
|
|
576
|
+
if (code === 'CANCELLED' || code === 'USER_CANCELLED')
|
|
577
|
+
return true;
|
|
578
|
+
const err = String(result?.error || '').toLowerCase();
|
|
579
|
+
if (/(cancel|canceled|cancelled)/.test(err))
|
|
580
|
+
return true;
|
|
581
|
+
return false;
|
|
582
|
+
}
|
|
583
|
+
extractBiometricResultToken(payload, operation, errorCode) {
|
|
584
|
+
if (this.isUserCancelledPayload(payload)) {
|
|
585
|
+
common_utils_1.logger.info('Operation cancelled by user', { operation });
|
|
586
|
+
throw new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED');
|
|
587
|
+
}
|
|
588
|
+
if (this.isFailure(payload)) {
|
|
589
|
+
const message = typeof payload?.error === 'string' ? payload.error : `${operation} failed`;
|
|
590
|
+
common_utils_1.logger.error('Operation failed', { operation, error: message });
|
|
591
|
+
throw new NeumaMobileInterface_1.NeumaError(message, errorCode);
|
|
592
|
+
}
|
|
593
|
+
const brt = payload?.brt;
|
|
594
|
+
if (typeof brt !== 'string' || brt.length === 0) {
|
|
595
|
+
common_utils_1.logger.error('Biometric result token missing', {
|
|
596
|
+
operation,
|
|
597
|
+
payloadKeys: Object.keys(payload || {}),
|
|
598
|
+
});
|
|
599
|
+
throw new NeumaMobileInterface_1.NeumaError('Biometric result token missing', errorCode);
|
|
600
|
+
}
|
|
601
|
+
const claims = this.decodeJwtPayload(brt);
|
|
602
|
+
if (claims && claims.success === false) {
|
|
603
|
+
if (this.isUserCancelledPayload(claims)) {
|
|
604
|
+
common_utils_1.logger.info('Operation cancelled by user', { operation });
|
|
605
|
+
throw new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED');
|
|
606
|
+
}
|
|
607
|
+
const message = typeof claims.error === 'string' ? claims.error : `${operation} failed`;
|
|
608
|
+
common_utils_1.logger.error('Operation failed', { operation, error: message });
|
|
609
|
+
throw new NeumaMobileInterface_1.NeumaError(message, errorCode);
|
|
610
|
+
}
|
|
611
|
+
return brt;
|
|
612
|
+
}
|
|
613
|
+
decodeJwtPayload(token) {
|
|
614
|
+
try {
|
|
615
|
+
const parts = token.split('.');
|
|
616
|
+
if (parts.length < 2)
|
|
617
|
+
return null;
|
|
618
|
+
const payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
|
|
619
|
+
const padded = payload + '='.repeat((4 - (payload.length % 4)) % 4);
|
|
620
|
+
const json = typeof window !== 'undefined'
|
|
621
|
+
? atob(padded)
|
|
622
|
+
: Buffer.from(padded, 'base64').toString('utf-8');
|
|
623
|
+
return JSON.parse(json);
|
|
624
|
+
}
|
|
625
|
+
catch {
|
|
626
|
+
return null;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
async waitForResult(callbackId, timeoutMs = 90000) {
|
|
630
|
+
const pollUrl = `${(0, biometricService_1.buildBiometricServiceBaseUrl)(this.options.biometricService, this.options.apiServerPort)}/api/biometric-results/${callbackId}`;
|
|
631
|
+
const maxRetries = 5; // Allow enough retries for 90s timeout (server polls every ~30s)
|
|
632
|
+
const retryDelayMs = 2000;
|
|
633
|
+
const startTime = Date.now();
|
|
634
|
+
common_utils_1.logger.info('Starting long polling for result', { pollUrl, maxRetries, timeoutMs });
|
|
635
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
636
|
+
const elapsed = Date.now() - startTime;
|
|
637
|
+
if (elapsed >= timeoutMs) {
|
|
638
|
+
common_utils_1.logger.error('Operation timed out', { elapsed, timeoutMs });
|
|
639
|
+
throw new Error(`Operation timed out after ${elapsed}ms - no response received`);
|
|
640
|
+
}
|
|
641
|
+
try {
|
|
642
|
+
common_utils_1.logger.verbose('Long poll attempt', { attempt, maxRetries });
|
|
643
|
+
const response = await fetch(pollUrl, {
|
|
644
|
+
method: 'GET',
|
|
645
|
+
headers: { Accept: 'application/json' },
|
|
646
|
+
});
|
|
647
|
+
if (response.ok) {
|
|
648
|
+
const payload = await response.json();
|
|
649
|
+
if (payload && typeof payload.brt === 'string' && payload.brt.length > 0) {
|
|
650
|
+
common_utils_1.logger.info('Received biometric result token via long polling', {
|
|
651
|
+
callbackId,
|
|
652
|
+
payloadKeys: Object.keys(payload || {}),
|
|
653
|
+
});
|
|
654
|
+
return payload;
|
|
655
|
+
}
|
|
656
|
+
if (payload && payload.id === callbackId) {
|
|
657
|
+
common_utils_1.logger.info('Received result via long polling', {
|
|
658
|
+
callbackId,
|
|
659
|
+
operation: payload.operation,
|
|
660
|
+
});
|
|
661
|
+
return payload;
|
|
662
|
+
}
|
|
663
|
+
common_utils_1.logger.warning('Received result but callbackId does not match', {
|
|
664
|
+
expected: callbackId,
|
|
665
|
+
received: payload?.id,
|
|
666
|
+
payloadKeys: Object.keys(payload || {}),
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
else if (response.status === 404) {
|
|
670
|
+
common_utils_1.logger.verbose('Long poll attempt - no result yet', { attempt, maxRetries });
|
|
671
|
+
if (attempt < maxRetries) {
|
|
672
|
+
const remainingTime = timeoutMs - (Date.now() - startTime);
|
|
673
|
+
if (remainingTime > retryDelayMs) {
|
|
674
|
+
await new Promise(resolve => setTimeout(resolve, retryDelayMs));
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
else {
|
|
679
|
+
common_utils_1.logger.error('Polling error', {
|
|
680
|
+
status: response.status,
|
|
681
|
+
statusText: response.statusText,
|
|
682
|
+
});
|
|
683
|
+
if (attempt < maxRetries) {
|
|
684
|
+
await new Promise(resolve => setTimeout(resolve, retryDelayMs));
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
catch (err) {
|
|
689
|
+
common_utils_1.logger.error('Failed to poll for result', { attempt, maxRetries, error: err });
|
|
690
|
+
if (attempt < maxRetries) {
|
|
691
|
+
await new Promise(resolve => setTimeout(resolve, retryDelayMs));
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
common_utils_1.logger.error('All polling retries exhausted', { maxRetries });
|
|
696
|
+
throw new Error(`Operation timed out after ${maxRetries} attempts - no response received`);
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Detect if running in a desktop browser (not mobile)
|
|
700
|
+
*/
|
|
701
|
+
isDesktopBrowser() {
|
|
702
|
+
if (typeof window === 'undefined' || typeof navigator === 'undefined') {
|
|
703
|
+
return false;
|
|
704
|
+
}
|
|
705
|
+
const userAgent = navigator.userAgent.toLowerCase();
|
|
706
|
+
// Check for mobile indicators
|
|
707
|
+
const mobileKeywords = [
|
|
708
|
+
'android',
|
|
709
|
+
'webos',
|
|
710
|
+
'iphone',
|
|
711
|
+
'ipad',
|
|
712
|
+
'ipod',
|
|
713
|
+
'blackberry',
|
|
714
|
+
'iemobile',
|
|
715
|
+
'opera mini',
|
|
716
|
+
'mobile',
|
|
717
|
+
'tablet',
|
|
718
|
+
'touch',
|
|
719
|
+
];
|
|
720
|
+
const isMobile = mobileKeywords.some(keyword => userAgent.includes(keyword));
|
|
721
|
+
return !isMobile;
|
|
722
|
+
}
|
|
723
|
+
resolveQrAppLinkBase() {
|
|
724
|
+
const fallback = `${window.location.origin}/f`;
|
|
725
|
+
const configuredBase = this.options.qrAppLinkBase?.trim();
|
|
726
|
+
if (!configuredBase) {
|
|
727
|
+
return fallback;
|
|
728
|
+
}
|
|
729
|
+
try {
|
|
730
|
+
const baseUrl = new URL(configuredBase, window.location.origin);
|
|
731
|
+
if (baseUrl.protocol !== 'https:' && window.location.protocol === 'https:') {
|
|
732
|
+
common_utils_1.logger.warning('Ignoring non-HTTPS qrAppLinkBase on HTTPS page', {
|
|
733
|
+
qrAppLinkBase: configuredBase,
|
|
734
|
+
});
|
|
735
|
+
return fallback;
|
|
736
|
+
}
|
|
737
|
+
baseUrl.hash = '';
|
|
738
|
+
baseUrl.search = '';
|
|
739
|
+
return baseUrl.toString().replace(/\/$/, '');
|
|
740
|
+
}
|
|
741
|
+
catch {
|
|
742
|
+
common_utils_1.logger.warning('Ignoring invalid qrAppLinkBase', { qrAppLinkBase: configuredBase });
|
|
743
|
+
return fallback;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Invoke mobile app via QR code flow (for desktop browsers)
|
|
748
|
+
* Uses HTTPS App Link format for QR codes (works on both iOS and Android)
|
|
749
|
+
* URL format: {qrAppLinkBase}/{op}/{id}?b={bioServer}&w={webServer}&u={userName}&m={email}&p={phone}
|
|
750
|
+
*/
|
|
751
|
+
async invokeMobileAppViaQr(operation, user) {
|
|
752
|
+
const callbackId = this.generateRandomId();
|
|
753
|
+
common_utils_1.logger.info('Invoking mobile app via QR code', {
|
|
754
|
+
operation,
|
|
755
|
+
callbackId,
|
|
756
|
+
hasBiometricSessionToken: !!this.options.biometricSessionToken,
|
|
757
|
+
hasUser: !!user,
|
|
758
|
+
});
|
|
759
|
+
// Get short operation code
|
|
760
|
+
const opCode = OP_CODES[operation] || operation.charAt(0);
|
|
761
|
+
const params = new URLSearchParams({
|
|
762
|
+
b: this.options.biometricService,
|
|
763
|
+
w: window.location.host,
|
|
764
|
+
});
|
|
765
|
+
if (user) {
|
|
766
|
+
params.append('u', user.userName);
|
|
767
|
+
const email = user.email?.trim() ?? '';
|
|
768
|
+
const phone = user.phone?.trim() ?? '';
|
|
769
|
+
if (email) {
|
|
770
|
+
params.append('m', email);
|
|
771
|
+
}
|
|
772
|
+
if (phone) {
|
|
773
|
+
params.append('p', phone);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
if (this.options.biometricSessionToken) {
|
|
777
|
+
params.append('bst', this.options.biometricSessionToken);
|
|
778
|
+
}
|
|
779
|
+
// Use HTTPS App Link for QR codes - Android camera apps don't support custom schemes
|
|
780
|
+
const appLinkBase = this.resolveQrAppLinkBase();
|
|
781
|
+
const deepLinkUrl = `${appLinkBase}/${opCode}/${callbackId}?${params.toString()}`;
|
|
782
|
+
common_utils_1.logger.info('QR deep link prepared', {
|
|
783
|
+
callbackId,
|
|
784
|
+
appLinkBase,
|
|
785
|
+
});
|
|
786
|
+
// Cancellation state
|
|
787
|
+
let cancelled = false;
|
|
788
|
+
let rejectFn = null;
|
|
789
|
+
// Call onQrCode callback to display QR code
|
|
790
|
+
const qrData = {
|
|
791
|
+
deepLinkUrl,
|
|
792
|
+
callbackId,
|
|
793
|
+
onCancel: () => {
|
|
794
|
+
cancelled = true;
|
|
795
|
+
common_utils_1.logger.info('QR code cancelled by user', { callbackId });
|
|
796
|
+
if (rejectFn) {
|
|
797
|
+
rejectFn(new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED'));
|
|
798
|
+
}
|
|
799
|
+
},
|
|
800
|
+
};
|
|
801
|
+
let cleanupFn = undefined;
|
|
802
|
+
if (this.options.onQrCode) {
|
|
803
|
+
cleanupFn = this.options.onQrCode(qrData);
|
|
804
|
+
common_utils_1.logger.info('QR code callback invoked', { callbackId });
|
|
805
|
+
}
|
|
806
|
+
// For retrieve-key and clear-user operations, work in offline mode (no polling)
|
|
807
|
+
if (operation === 'retrieve-key' || operation === 'clear-user') {
|
|
808
|
+
common_utils_1.logger.info('Offline operation - no polling', { callbackId, operation });
|
|
809
|
+
return null;
|
|
810
|
+
}
|
|
811
|
+
// Start polling for result (in parallel with QR display)
|
|
812
|
+
// Wrap in a race between polling and cancellation
|
|
813
|
+
try {
|
|
814
|
+
const payload = await new Promise((resolve, reject) => {
|
|
815
|
+
rejectFn = reject;
|
|
816
|
+
// Check if already cancelled before starting
|
|
817
|
+
if (cancelled) {
|
|
818
|
+
reject(new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED'));
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
this.waitForResult(callbackId, this.options.timeoutMs).then(resolve).catch(reject);
|
|
822
|
+
});
|
|
823
|
+
return payload;
|
|
824
|
+
}
|
|
825
|
+
finally {
|
|
826
|
+
// Call cleanup function to dismiss QR code
|
|
827
|
+
if (typeof cleanupFn === 'function') {
|
|
828
|
+
cleanupFn();
|
|
829
|
+
common_utils_1.logger.info('QR code cleanup called', { callbackId });
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
async invokeMobileApp(operation, user) {
|
|
834
|
+
// Check if we should use QR code flow (desktop browser + onQrCode callback provided)
|
|
835
|
+
const isDesktop = this.isDesktopBrowser();
|
|
836
|
+
const hasQrCallback = !!this.options.onQrCode;
|
|
837
|
+
if (isDesktop && hasQrCallback) {
|
|
838
|
+
common_utils_1.logger.info('Using QR code flow for desktop browser', {
|
|
839
|
+
operation,
|
|
840
|
+
isDesktop,
|
|
841
|
+
hasQrCallback,
|
|
842
|
+
});
|
|
843
|
+
return this.invokeMobileAppViaQr(operation, user);
|
|
844
|
+
}
|
|
845
|
+
// Phone browser flow - use deep-link (unchanged)
|
|
846
|
+
const callbackId = this.generateRandomId();
|
|
847
|
+
common_utils_1.logger.info('Invoking mobile app via deep-link', {
|
|
848
|
+
operation,
|
|
849
|
+
callbackId,
|
|
850
|
+
isDesktop,
|
|
851
|
+
hasBiometricSessionToken: !!this.options.biometricSessionToken,
|
|
852
|
+
hasUser: !!user,
|
|
853
|
+
});
|
|
854
|
+
const isOfflineOperation = operation === 'retrieve-key' || operation === 'clear-user';
|
|
855
|
+
// Always give iOS Safari a returnUrl so Neuma's Close button can
|
|
856
|
+
// foreground the originating browser tab. All iOS Safari returnUrls
|
|
857
|
+
// get a unique marker for exact tab matching; only polling operations
|
|
858
|
+
// persist pending state because offline operations (`retrieve-key`,
|
|
859
|
+
// `clear-user`) do not write a server result for the SDK to resume.
|
|
860
|
+
const returnUrl = this.captureReturnUrl(callbackId, operation);
|
|
861
|
+
// Persist pending-op metadata BEFORE firing the deep link when a
|
|
862
|
+
// browser return path can lose the in-memory polling promise. iOS
|
|
863
|
+
// Safari needs this because returnUrl refocus can remount the tab.
|
|
864
|
+
// Android Chrome on low-memory devices can recreate the page during
|
|
865
|
+
// native-app handoff and lose sessionStorage, so the Android path
|
|
866
|
+
// also writes a localStorage fallback inside persistPendingOperation().
|
|
867
|
+
const shouldPersistPending = !isOfflineOperation && (returnUrl !== null || this.shouldUseAndroidPendingFallback());
|
|
868
|
+
if (shouldPersistPending) {
|
|
869
|
+
this.persistPendingOperation(callbackId, operation);
|
|
870
|
+
}
|
|
871
|
+
// Build deep link with separate biometric and web hosts.
|
|
872
|
+
const params = new URLSearchParams({
|
|
873
|
+
operation,
|
|
874
|
+
id: callbackId,
|
|
875
|
+
bioServer: this.options.biometricService,
|
|
876
|
+
webServer: window.location.host,
|
|
877
|
+
});
|
|
878
|
+
if (user) {
|
|
879
|
+
params.append('userName', user.userName);
|
|
880
|
+
const email = user.email?.trim() ?? '';
|
|
881
|
+
const phone = user.phone?.trim() ?? '';
|
|
882
|
+
if (email) {
|
|
883
|
+
params.append('email', email);
|
|
884
|
+
}
|
|
885
|
+
if (phone) {
|
|
886
|
+
params.append('phone', phone);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
if (this.options.biometricSessionToken) {
|
|
890
|
+
params.append('bst', this.options.biometricSessionToken);
|
|
891
|
+
}
|
|
892
|
+
if (returnUrl) {
|
|
893
|
+
params.append('returnUrl', returnUrl);
|
|
894
|
+
}
|
|
895
|
+
const customScheme = `${this.options.customSchemeBase}?${params.toString()}`;
|
|
896
|
+
common_utils_1.logger.info('Custom scheme prepared', {
|
|
897
|
+
callbackId,
|
|
898
|
+
customSchemeBase: this.options.customSchemeBase,
|
|
899
|
+
hasReturnUrl: !!returnUrl,
|
|
900
|
+
});
|
|
901
|
+
let launchFailureTimer = null;
|
|
902
|
+
let hasInferredLaunchFailure = false;
|
|
903
|
+
const cancelLaunchFailureTimer = () => {
|
|
904
|
+
if (launchFailureTimer) {
|
|
905
|
+
clearTimeout(launchFailureTimer);
|
|
906
|
+
launchFailureTimer = null;
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
const onVisibility = () => {
|
|
910
|
+
if (document.visibilityState === 'hidden')
|
|
911
|
+
cancelLaunchFailureTimer();
|
|
912
|
+
};
|
|
913
|
+
document.addEventListener('visibilitychange', onVisibility);
|
|
914
|
+
// Open app immediately using custom scheme
|
|
915
|
+
try {
|
|
916
|
+
window.location.href = customScheme;
|
|
917
|
+
}
|
|
918
|
+
catch { }
|
|
919
|
+
// Infer failed launches only for phone-browser deep-link flow.
|
|
920
|
+
if (!isDesktop) {
|
|
921
|
+
launchFailureTimer = setTimeout(() => {
|
|
922
|
+
if (document.visibilityState !== 'visible')
|
|
923
|
+
return;
|
|
924
|
+
hasInferredLaunchFailure = true;
|
|
925
|
+
const context = this.buildLaunchFailureContext(operation);
|
|
926
|
+
common_utils_1.logger.info('Deep-link launch likely failed', {
|
|
927
|
+
operation,
|
|
928
|
+
platform: context.platform,
|
|
929
|
+
hasInstallUrl: !!context.installUrl,
|
|
930
|
+
});
|
|
931
|
+
this.options.onAppLaunchFailed?.(context);
|
|
932
|
+
}, 2000);
|
|
933
|
+
}
|
|
934
|
+
// For retrieve-key and clear-user operations, work in offline mode (no polling, no server connection).
|
|
935
|
+
// Do not resolve immediately after assigning `window.location.href` to the custom scheme:
|
|
936
|
+
// on iOS Safari that can let the webapp mutate UI/state while the browser is still
|
|
937
|
+
// completing the handoff to Neuma, which makes the later `returnUrl` launch more prone
|
|
938
|
+
// to opening a fresh Safari tab. Instead, resolve after Safari has hidden for the app
|
|
939
|
+
// handoff and then becomes visible again.
|
|
940
|
+
if (isOfflineOperation) {
|
|
941
|
+
common_utils_1.logger.info('Offline operation - no polling', { callbackId, operation });
|
|
942
|
+
return await new Promise(resolve => {
|
|
943
|
+
let sawAppHandoff = document.visibilityState === 'hidden';
|
|
944
|
+
let settled = false;
|
|
945
|
+
const cleanup = () => {
|
|
946
|
+
cancelLaunchFailureTimer();
|
|
947
|
+
document.removeEventListener('visibilitychange', onVisibility);
|
|
948
|
+
document.removeEventListener('visibilitychange', onOfflineVisibility);
|
|
949
|
+
window.removeEventListener('focus', onOfflineReturn);
|
|
950
|
+
window.removeEventListener('pageshow', onOfflineReturn);
|
|
951
|
+
};
|
|
952
|
+
const complete = () => {
|
|
953
|
+
if (settled)
|
|
954
|
+
return;
|
|
955
|
+
settled = true;
|
|
956
|
+
cleanup();
|
|
957
|
+
common_utils_1.logger.info('Offline operation returned to browser', {
|
|
958
|
+
callbackId,
|
|
959
|
+
operation,
|
|
960
|
+
});
|
|
961
|
+
resolve(null);
|
|
962
|
+
};
|
|
963
|
+
const onOfflineReturn = () => {
|
|
964
|
+
if (sawAppHandoff && document.visibilityState !== 'hidden') {
|
|
965
|
+
complete();
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
const onOfflineVisibility = () => {
|
|
969
|
+
if (document.visibilityState === 'hidden') {
|
|
970
|
+
sawAppHandoff = true;
|
|
971
|
+
cancelLaunchFailureTimer();
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
onOfflineReturn();
|
|
975
|
+
};
|
|
976
|
+
document.addEventListener('visibilitychange', onOfflineVisibility);
|
|
977
|
+
window.addEventListener('focus', onOfflineReturn);
|
|
978
|
+
window.addEventListener('pageshow', onOfflineReturn);
|
|
979
|
+
onOfflineReturn();
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
try {
|
|
983
|
+
const payload = await this.waitForResult(callbackId, this.options.timeoutMs);
|
|
984
|
+
this.persistCompletedResult(callbackId, operation, payload);
|
|
985
|
+
return payload;
|
|
986
|
+
}
|
|
987
|
+
finally {
|
|
988
|
+
if (!hasInferredLaunchFailure) {
|
|
989
|
+
cancelLaunchFailureTimer();
|
|
990
|
+
}
|
|
991
|
+
document.removeEventListener('visibilitychange', onVisibility);
|
|
992
|
+
// Polling completed (success, failure, or timeout) — drop the
|
|
993
|
+
// pending entry so it isn't picked up by a later remount.
|
|
994
|
+
this.clearPendingOperation();
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
async enrollUser(user) {
|
|
998
|
+
try {
|
|
999
|
+
const payload = await this.invokeMobileApp('enroll', user);
|
|
1000
|
+
const brt = this.extractBiometricResultToken(payload, 'enroll', 'USER_EXISTS');
|
|
1001
|
+
const decoded = this.decodeJwtPayload(brt);
|
|
1002
|
+
if (decoded && decoded.userId && decoded.enrollmentId) {
|
|
1003
|
+
const enrollment = {
|
|
1004
|
+
userId: String(decoded.userId),
|
|
1005
|
+
enrollmentId: String(decoded.enrollmentId),
|
|
1006
|
+
enrolledAt: new Date(decoded.enrolledAt || Date.now()),
|
|
1007
|
+
userDescriptor: {
|
|
1008
|
+
userName: String(decoded.userName || user.userName || 'Neuma User'),
|
|
1009
|
+
email: String(user.email || ''),
|
|
1010
|
+
phone: String(user.phone || ''),
|
|
1011
|
+
},
|
|
1012
|
+
};
|
|
1013
|
+
this.persistEnrollment(enrollment);
|
|
1014
|
+
}
|
|
1015
|
+
common_utils_1.logger.info('Enrollment successful', { userName: user.userName });
|
|
1016
|
+
return brt;
|
|
1017
|
+
}
|
|
1018
|
+
catch (error) {
|
|
1019
|
+
if (error instanceof NeumaMobileInterface_1.NeumaError && error.code === 'USER_CANCELLED')
|
|
1020
|
+
throw error;
|
|
1021
|
+
if (error instanceof Error && /(cancel|canceled|cancelled)/i.test(error.message)) {
|
|
1022
|
+
throw new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED');
|
|
1023
|
+
}
|
|
1024
|
+
const msg = error instanceof Error ? error.message : 'Enrollment failed';
|
|
1025
|
+
common_utils_1.logger.error('Enrollment error', { error: msg, userName: user.userName });
|
|
1026
|
+
throw new NeumaMobileInterface_1.NeumaError(msg, 'USER_EXISTS');
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
async restoreUser() {
|
|
1030
|
+
try {
|
|
1031
|
+
const payload = await this.invokeMobileApp('restore', undefined);
|
|
1032
|
+
const brt = this.extractBiometricResultToken(payload, 'restore', 'AUTH_FAILED');
|
|
1033
|
+
const decoded = this.decodeJwtPayload(brt);
|
|
1034
|
+
if (decoded && decoded.userId && decoded.enrollmentId) {
|
|
1035
|
+
const enrollment = {
|
|
1036
|
+
userId: String(decoded.userId),
|
|
1037
|
+
enrollmentId: String(decoded.enrollmentId),
|
|
1038
|
+
enrolledAt: new Date(decoded.enrolledAt || Date.now()),
|
|
1039
|
+
userDescriptor: {
|
|
1040
|
+
userName: String(decoded.userName || 'Neuma User'),
|
|
1041
|
+
email: '',
|
|
1042
|
+
phone: '',
|
|
1043
|
+
},
|
|
1044
|
+
};
|
|
1045
|
+
this.persistEnrollment(enrollment);
|
|
1046
|
+
}
|
|
1047
|
+
common_utils_1.logger.info('Restore successful');
|
|
1048
|
+
return brt;
|
|
1049
|
+
}
|
|
1050
|
+
catch (error) {
|
|
1051
|
+
if (error instanceof NeumaMobileInterface_1.NeumaError && error.code === 'USER_CANCELLED')
|
|
1052
|
+
throw error;
|
|
1053
|
+
if (error instanceof Error && /(cancel|canceled|cancelled)/i.test(error.message)) {
|
|
1054
|
+
throw new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED');
|
|
1055
|
+
}
|
|
1056
|
+
const msg = error instanceof Error ? error.message : 'Restore failed';
|
|
1057
|
+
common_utils_1.logger.error('Restore error', { error: msg });
|
|
1058
|
+
throw new NeumaMobileInterface_1.NeumaError(msg, 'AUTH_FAILED');
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
async authenticateUser() {
|
|
1062
|
+
try {
|
|
1063
|
+
const payload = await this.invokeMobileApp('authenticate', undefined);
|
|
1064
|
+
const brt = this.extractBiometricResultToken(payload, 'authenticate', 'AUTH_FAILED');
|
|
1065
|
+
common_utils_1.logger.info('Authentication successful');
|
|
1066
|
+
return brt;
|
|
1067
|
+
}
|
|
1068
|
+
catch (error) {
|
|
1069
|
+
if (error instanceof NeumaMobileInterface_1.NeumaError && error.code === 'USER_CANCELLED')
|
|
1070
|
+
throw error;
|
|
1071
|
+
if (error instanceof Error && /(cancel|canceled|cancelled)/i.test(error.message)) {
|
|
1072
|
+
throw new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED');
|
|
1073
|
+
}
|
|
1074
|
+
const msg = error instanceof Error ? error.message : 'Authentication failed';
|
|
1075
|
+
common_utils_1.logger.error('Authentication error', { error: msg });
|
|
1076
|
+
throw new NeumaMobileInterface_1.NeumaError(msg, 'AUTH_FAILED');
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
async retrieveKey() {
|
|
1080
|
+
// retrieveKey requires clipboard sharing between browser and mobile app,
|
|
1081
|
+
// which only works when both are on the same device (mobile browser)
|
|
1082
|
+
if (this.isDesktopBrowser()) {
|
|
1083
|
+
common_utils_1.logger.error('retrieveKey called from desktop browser');
|
|
1084
|
+
throw new NeumaMobileInterface_1.NeumaError('This operation is supported only on mobile browsers', 'AUTH_FAILED');
|
|
1085
|
+
}
|
|
1086
|
+
await this.invokeMobileApp('retrieve-key', undefined);
|
|
1087
|
+
return null;
|
|
1088
|
+
}
|
|
1089
|
+
parseRetrieveKeyResult(jsonString) {
|
|
1090
|
+
try {
|
|
1091
|
+
const result = JSON.parse(jsonString);
|
|
1092
|
+
if (this.isUserCancelledPayload(result)) {
|
|
1093
|
+
common_utils_1.logger.info('Key retrieval cancelled by user');
|
|
1094
|
+
throw new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED');
|
|
1095
|
+
}
|
|
1096
|
+
if (this.isFailure(result)) {
|
|
1097
|
+
common_utils_1.logger.error('Key retrieval failed', { error: result.error });
|
|
1098
|
+
throw new NeumaMobileInterface_1.NeumaError(result.error || 'Key retrieval failed', 'AUTH_FAILED');
|
|
1099
|
+
}
|
|
1100
|
+
common_utils_1.logger.info('Key retrieval successful', { userId: result.userId });
|
|
1101
|
+
return {
|
|
1102
|
+
key: result.key,
|
|
1103
|
+
userId: result.userId || 'unknown',
|
|
1104
|
+
userDescriptor: this.normalizeUserDescriptor(result),
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
catch (error) {
|
|
1108
|
+
if (error instanceof NeumaMobileInterface_1.NeumaError)
|
|
1109
|
+
throw error;
|
|
1110
|
+
const msg = error instanceof Error ? error.message : 'Invalid JSON format';
|
|
1111
|
+
common_utils_1.logger.error('Failed to parse retrieve-key result', { error: msg });
|
|
1112
|
+
throw new NeumaMobileInterface_1.NeumaError(msg, 'PARSE_ERROR');
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
async getEnrolledUser() {
|
|
1116
|
+
return this.readPersistedEnrollment();
|
|
1117
|
+
}
|
|
1118
|
+
async clearUser() {
|
|
1119
|
+
try {
|
|
1120
|
+
if (this.isDesktopBrowser()) {
|
|
1121
|
+
common_utils_1.logger.error('clearUser called from desktop browser');
|
|
1122
|
+
throw new NeumaMobileInterface_1.NeumaError('This operation is supported only on mobile browsers', 'AUTH_FAILED');
|
|
1123
|
+
}
|
|
1124
|
+
await this.invokeMobileApp('clear-user', undefined);
|
|
1125
|
+
this.persistEnrollment(null);
|
|
1126
|
+
common_utils_1.logger.info('User cleared successfully');
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
catch (error) {
|
|
1130
|
+
if (error instanceof NeumaMobileInterface_1.NeumaError && error.code === 'USER_CANCELLED')
|
|
1131
|
+
throw error;
|
|
1132
|
+
if (error instanceof Error && /(cancel|canceled|cancelled)/i.test(error.message)) {
|
|
1133
|
+
throw new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED');
|
|
1134
|
+
}
|
|
1135
|
+
const msg = error instanceof Error ? error.message : 'Clear user failed';
|
|
1136
|
+
common_utils_1.logger.error('Clear user error', { error: msg });
|
|
1137
|
+
throw new NeumaMobileInterface_1.NeumaError(msg, 'USER_NOT_FOUND');
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
async unenrollUser() {
|
|
1141
|
+
try {
|
|
1142
|
+
const payload = await this.invokeMobileApp('unenroll-user', undefined);
|
|
1143
|
+
const brt = this.extractBiometricResultToken(payload, 'unenroll-user', 'USER_NOT_FOUND');
|
|
1144
|
+
this.persistEnrollment(null);
|
|
1145
|
+
common_utils_1.logger.info('User unenrolled successfully');
|
|
1146
|
+
return brt;
|
|
1147
|
+
}
|
|
1148
|
+
catch (error) {
|
|
1149
|
+
if (error instanceof NeumaMobileInterface_1.NeumaError && error.code === 'USER_CANCELLED')
|
|
1150
|
+
throw error;
|
|
1151
|
+
if (error instanceof Error && /(cancel|canceled|cancelled)/i.test(error.message)) {
|
|
1152
|
+
throw new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED');
|
|
1153
|
+
}
|
|
1154
|
+
const msg = error instanceof Error ? error.message : 'Unenroll user failed';
|
|
1155
|
+
common_utils_1.logger.error('Unenroll error', { error: msg });
|
|
1156
|
+
throw new NeumaMobileInterface_1.NeumaError(msg, 'USER_NOT_FOUND');
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* `sessionStorage` key under which the SDK stores the metadata for an
|
|
1162
|
+
* in-flight deep-link operation. See {@link getPendingOperation} and
|
|
1163
|
+
* {@link resumePendingResult}.
|
|
1164
|
+
*/
|
|
1165
|
+
NeumaMobile.PENDING_KEY = '__neuma_pending_op__';
|
|
1166
|
+
/**
|
|
1167
|
+
* Android Chrome can recreate the tab during native app handoff on
|
|
1168
|
+
* low-memory devices, which drops `sessionStorage`. Keep an Android-only
|
|
1169
|
+
* pending fallback in `localStorage` so the page can recover the callback
|
|
1170
|
+
* ID after that dark-screen reload path.
|
|
1171
|
+
*/
|
|
1172
|
+
NeumaMobile.ANDROID_PENDING_KEY = '__neuma_android_pending_op__';
|
|
1173
|
+
/**
|
|
1174
|
+
* Short-lived cache for a result that already arrived from the biometric
|
|
1175
|
+
* server but may not have been handled by the webapp yet. This closes the
|
|
1176
|
+
* iOS Safari race where the original tab remounts after polling has
|
|
1177
|
+
* completed and pending metadata has been cleared, but before the app's
|
|
1178
|
+
* result popup/business state has been persisted.
|
|
1179
|
+
*/
|
|
1180
|
+
NeumaMobile.COMPLETED_RESULT_KEY = '__neuma_completed_result__';
|
|
1181
|
+
/**
|
|
1182
|
+
* Maximum age of a pending entry before it is treated as stale and
|
|
1183
|
+
* cleared on read (5 minutes).
|
|
1184
|
+
*/
|
|
1185
|
+
NeumaMobile.PENDING_TTL_MS = 5 * 60 * 1000;
|
|
1186
|
+
/**
|
|
1187
|
+
* Once a cached completed result has been returned to app code, keep it
|
|
1188
|
+
* briefly so a second iOS Safari remount during page-level handling can
|
|
1189
|
+
* still recover. Apps should call clearPendingResult() after durable
|
|
1190
|
+
* handling to clear it immediately.
|
|
1191
|
+
*/
|
|
1192
|
+
NeumaMobile.COMPLETED_CONSUMING_GRACE_MS = 2 * 60 * 1000;
|
|
1193
|
+
class NeumaMobileFactory {
|
|
1194
|
+
constructor() { }
|
|
1195
|
+
static create() {
|
|
1196
|
+
return new NeumaMobile();
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
exports.NeumaMobileFactory = NeumaMobileFactory;
|