@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 ADDED
@@ -0,0 +1,3 @@
1
+ # @vizualkei/neuma-client-sdk
2
+
3
+ See [NEUMA-SDK.md](../../NEUMA-SDK.md) for the Neuma SDK API documentation.
@@ -0,0 +1,165 @@
1
+ import type { NeumaMobileOptions, KeyRetrievalResult, PendingOperationInfo, UserDescriptor } from './NeumaMobileInterface';
2
+ export type EnrollUserOptions = {
3
+ email?: string | null;
4
+ phoneNo?: string | null;
5
+ };
6
+ export type NeumaClientHelperConfig = {
7
+ biometricSessionUrl: string;
8
+ biometricResultUrl: string;
9
+ fetcher: (input: RequestInfo, init?: RequestInit) => Promise<Response>;
10
+ biometricService?: string;
11
+ onQrCode?: NeumaMobileOptions['onQrCode'];
12
+ onAppLaunchFailed?: NeumaMobileOptions['onAppLaunchFailed'];
13
+ sdkOptions?: Omit<NeumaMobileOptions, 'biometricSessionToken' | 'onQrCode' | 'onAppLaunchFailed'>;
14
+ resultPayloadBuilder?: (params: {
15
+ brt: string;
16
+ enrollOptions?: EnrollUserOptions;
17
+ }) => Record<string, unknown>;
18
+ };
19
+ type MaybePromise<T> = T | Promise<T>;
20
+ export type PendingOperationMatcher = string | readonly string[] | ((operation: string) => boolean);
21
+ export type PendingOperationResult = {
22
+ operation: string;
23
+ callbackId: string;
24
+ payload: unknown;
25
+ brt?: string;
26
+ claims?: Record<string, unknown>;
27
+ submitted: boolean;
28
+ };
29
+ export type PendingOperationErrorContext = {
30
+ operation: string;
31
+ callbackId: string;
32
+ payload?: unknown;
33
+ brt?: string;
34
+ claims?: Record<string, unknown>;
35
+ };
36
+ export type HandlePendingOperationOptions = {
37
+ /**
38
+ * Limit handling to one or more SDK operation names, e.g.
39
+ * `authenticate`, `enroll`, `restore`, or `unenroll-user`.
40
+ */
41
+ operation?: PendingOperationMatcher;
42
+ /**
43
+ * Submit the recovered BRT to `biometricResultUrl` before calling
44
+ * `onSuccess`. Defaults to `true`, matching foreground helper methods.
45
+ * Set to `false` for direct business flows such as password updates.
46
+ */
47
+ submitResult?: boolean;
48
+ /**
49
+ * Optional enrollment metadata to include when `submitResult` is true.
50
+ */
51
+ enrollOptions?: EnrollUserOptions;
52
+ /**
53
+ * Reject BRTs whose decoded claim has `success: false`. Defaults to
54
+ * `true`, matching foreground SDK behavior.
55
+ */
56
+ requireSuccess?: boolean;
57
+ /**
58
+ * Fallback error message when a failed BRT has no server-provided error.
59
+ */
60
+ failureMessage?: string;
61
+ /**
62
+ * Called after a matching recoverable operation is found and before
63
+ * polling/cached-result recovery starts. Useful for showing loading UI
64
+ * without first manually inspecting SDK recovery state.
65
+ */
66
+ onStart?: (pending: PendingOperationInfo) => MaybePromise<void>;
67
+ /**
68
+ * Called after the SDK has recovered the payload and, when requested,
69
+ * submitted the BRT. Recovery state is cleared only after this callback
70
+ * resolves, so apps can durably persist or show their result UI here.
71
+ */
72
+ onSuccess?: (result: PendingOperationResult) => MaybePromise<void>;
73
+ /**
74
+ * Called when recovery or BRT validation fails. Recovery state is cleared
75
+ * after this callback resolves. If omitted, the error is rethrown and
76
+ * recovery state is left intact for a later retry.
77
+ */
78
+ onError?: (error: unknown, context: PendingOperationErrorContext) => MaybePromise<void>;
79
+ };
80
+ export declare class NeumaClientHelper {
81
+ private readonly config;
82
+ private readonly biometricService;
83
+ constructor(config: NeumaClientHelperConfig);
84
+ /**
85
+ * Optional early initialization hook (preserves prior SwClient behavior).
86
+ */
87
+ ensureInitialized(): void;
88
+ enrollUser(user: UserDescriptor, enrollOptions?: EnrollUserOptions): Promise<string>;
89
+ restoreUser(): Promise<string>;
90
+ authenticateUser(): Promise<string>;
91
+ /**
92
+ * Authenticate and return a signed BRT without auto-submitting it to the
93
+ * biometric result endpoint. Use this for business routes that validate
94
+ * the BRT themselves (e.g. ticket purchase, update-password).
95
+ */
96
+ authenticateUserDirect(): Promise<string>;
97
+ unenrollUser(): Promise<string>;
98
+ retrieveKey(): Promise<null>;
99
+ clearUser(): Promise<void>;
100
+ parseRetrieveKeyResult(jsonString: string): KeyRetrievalResult;
101
+ /**
102
+ * Returns metadata for a pending deep-link operation issued from this
103
+ * browser tab whose result has not yet been retrieved, or `null` when
104
+ * there is none. See {@link NeumaMobileInterface.getPendingOperation}.
105
+ */
106
+ getPendingOperation(): PendingOperationInfo | null;
107
+ /**
108
+ * Resume polling for a pending deep-link operation's result. See
109
+ * {@link NeumaMobileInterface.resumePendingResult}.
110
+ */
111
+ resumePendingResult(): Promise<unknown | null>;
112
+ /**
113
+ * Clears SDK recovery state for the current deep-link operation after
114
+ * app-level result handling has been persisted or shown.
115
+ */
116
+ clearPendingResult(): void;
117
+ /**
118
+ * High-level iOS Safari recovery helper for page-load handling.
119
+ *
120
+ * This hides the storage/URL recovery details from webapps: it checks
121
+ * whether a matching operation is recoverable, resumes or retrieves the
122
+ * raw payload, decodes failed BRTs into NeumaError, optionally submits
123
+ * the BRT to `biometricResultUrl`, and clears SDK recovery state only
124
+ * after the caller's success/error handler has completed.
125
+ */
126
+ handlePendingOperation(options?: HandlePendingOperationOptions): Promise<PendingOperationResult | null>;
127
+ private createSdk;
128
+ private runSignedOperation;
129
+ private matchesPendingOperation;
130
+ private extractBrt;
131
+ private decodeJwtPayload;
132
+ private isFailedClaims;
133
+ private errorFromFailedClaims;
134
+ private requestBiometricSessionToken;
135
+ private submitBiometricResultToken;
136
+ private buildResultPayload;
137
+ private postJson;
138
+ /**
139
+ * POST helper for the biometric-result submission path. Retries only
140
+ * on network-class fetch rejections (e.g. iOS Safari tab-refocus
141
+ * jitter producing `TypeError: Failed to fetch`). HTTP error statuses
142
+ * are deterministic server responses and are not retried. The
143
+ * /biometric-results endpoint is server-side keyed by callbackId/jti
144
+ * so retrying a POST is idempotent.
145
+ */
146
+ private postJsonWithRetry;
147
+ }
148
+ export declare const neumaClientHelper: {
149
+ init(config: NeumaClientHelperConfig): NeumaClientHelper;
150
+ get: () => NeumaClientHelper;
151
+ ensureInitialized(): void;
152
+ enrollUser(user: UserDescriptor, enrollOptions?: EnrollUserOptions): Promise<string>;
153
+ restoreUser(): Promise<string>;
154
+ authenticateUser(): Promise<string>;
155
+ authenticateUserDirect(): Promise<string>;
156
+ unenrollUser(): Promise<string>;
157
+ retrieveKey(): Promise<null>;
158
+ clearUser(): Promise<void>;
159
+ parseRetrieveKeyResult(jsonString: string): KeyRetrievalResult;
160
+ getPendingOperation(): PendingOperationInfo | null;
161
+ resumePendingResult(): Promise<unknown | null>;
162
+ clearPendingResult(): void;
163
+ handlePendingOperation(options?: HandlePendingOperationOptions): Promise<PendingOperationResult | null>;
164
+ };
165
+ export {};
@@ -0,0 +1,345 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.neumaClientHelper = exports.NeumaClientHelper = void 0;
4
+ const NeumaMobile_1 = require("./NeumaMobile");
5
+ const biometricService_1 = require("./biometricService");
6
+ const NeumaMobileInterface_1 = require("./NeumaMobileInterface");
7
+ const installLinks_1 = require("./installLinks");
8
+ const DEFAULT_BIOMETRIC_SERVICE = 'https://api.neuma.me:443';
9
+ class NeumaClientHelper {
10
+ constructor(config) {
11
+ this.config = config;
12
+ const service = config.biometricService?.trim();
13
+ this.biometricService = (0, biometricService_1.normalizeBiometricService)(service && service.length > 0 ? service : DEFAULT_BIOMETRIC_SERVICE);
14
+ }
15
+ /**
16
+ * Optional early initialization hook (preserves prior SwClient behavior).
17
+ */
18
+ ensureInitialized() {
19
+ this.createSdk();
20
+ }
21
+ async enrollUser(user, enrollOptions) {
22
+ return this.runSignedOperation(client => client.enrollUser(user), { enrollOptions });
23
+ }
24
+ async restoreUser() {
25
+ return this.runSignedOperation(client => client.restoreUser());
26
+ }
27
+ async authenticateUser() {
28
+ return this.runSignedOperation(client => client.authenticateUser());
29
+ }
30
+ /**
31
+ * Authenticate and return a signed BRT without auto-submitting it to the
32
+ * biometric result endpoint. Use this for business routes that validate
33
+ * the BRT themselves (e.g. ticket purchase, update-password).
34
+ */
35
+ async authenticateUserDirect() {
36
+ const { bst } = await this.requestBiometricSessionToken();
37
+ const client = this.createSdk(bst);
38
+ return client.authenticateUser();
39
+ }
40
+ async unenrollUser() {
41
+ return this.runSignedOperation(client => client.unenrollUser());
42
+ }
43
+ async retrieveKey() {
44
+ const client = this.createSdk();
45
+ return client.retrieveKey();
46
+ }
47
+ async clearUser() {
48
+ const client = this.createSdk();
49
+ return client.clearUser();
50
+ }
51
+ parseRetrieveKeyResult(jsonString) {
52
+ const client = this.createSdk();
53
+ return client.parseRetrieveKeyResult(jsonString);
54
+ }
55
+ /**
56
+ * Returns metadata for a pending deep-link operation issued from this
57
+ * browser tab whose result has not yet been retrieved, or `null` when
58
+ * there is none. See {@link NeumaMobileInterface.getPendingOperation}.
59
+ */
60
+ getPendingOperation() {
61
+ return this.createSdk().getPendingOperation();
62
+ }
63
+ /**
64
+ * Resume polling for a pending deep-link operation's result. See
65
+ * {@link NeumaMobileInterface.resumePendingResult}.
66
+ */
67
+ async resumePendingResult() {
68
+ return this.createSdk().resumePendingResult();
69
+ }
70
+ /**
71
+ * Clears SDK recovery state for the current deep-link operation after
72
+ * app-level result handling has been persisted or shown.
73
+ */
74
+ clearPendingResult() {
75
+ this.createSdk().clearPendingResult();
76
+ }
77
+ /**
78
+ * High-level iOS Safari recovery helper for page-load handling.
79
+ *
80
+ * This hides the storage/URL recovery details from webapps: it checks
81
+ * whether a matching operation is recoverable, resumes or retrieves the
82
+ * raw payload, decodes failed BRTs into NeumaError, optionally submits
83
+ * the BRT to `biometricResultUrl`, and clears SDK recovery state only
84
+ * after the caller's success/error handler has completed.
85
+ */
86
+ async handlePendingOperation(options = {}) {
87
+ const pending = this.getPendingOperation();
88
+ if (!pending || !this.matchesPendingOperation(pending.operation, options.operation)) {
89
+ return null;
90
+ }
91
+ let context = {
92
+ operation: pending.operation,
93
+ callbackId: pending.callbackId,
94
+ };
95
+ try {
96
+ await options.onStart?.(pending);
97
+ const payload = await this.resumePendingResult();
98
+ if (payload === null) {
99
+ this.clearPendingResult();
100
+ return null;
101
+ }
102
+ const brt = this.extractBrt(payload);
103
+ const claims = brt ? this.decodeJwtPayload(brt) : undefined;
104
+ context = { ...context, payload, brt, claims };
105
+ if (brt && options.requireSuccess !== false && claims && this.isFailedClaims(claims)) {
106
+ throw this.errorFromFailedClaims(claims, options.failureMessage);
107
+ }
108
+ const shouldSubmit = options.submitResult !== false && !!brt;
109
+ if (shouldSubmit && brt) {
110
+ await this.submitBiometricResultToken(brt, options.enrollOptions);
111
+ }
112
+ const result = {
113
+ operation: pending.operation,
114
+ callbackId: pending.callbackId,
115
+ payload,
116
+ ...(brt ? { brt } : {}),
117
+ ...(claims ? { claims } : {}),
118
+ submitted: shouldSubmit,
119
+ };
120
+ await options.onSuccess?.(result);
121
+ this.clearPendingResult();
122
+ return result;
123
+ }
124
+ catch (error) {
125
+ if (!options.onError) {
126
+ throw error;
127
+ }
128
+ await options.onError(error, context);
129
+ this.clearPendingResult();
130
+ return null;
131
+ }
132
+ }
133
+ createSdk(biometricSessionToken) {
134
+ const client = NeumaMobile_1.NeumaMobileFactory.create();
135
+ const sdkOptions = this.config.sdkOptions;
136
+ const initOptions = {
137
+ ...sdkOptions,
138
+ overlay: { appName: 'Neuma mobile app', ...(sdkOptions?.overlay || {}) },
139
+ installUrlResolver: sdkOptions?.installUrlResolver ?? installLinks_1.getNeumaMobileInstallUrl,
140
+ ...(this.config.onQrCode ? { onQrCode: this.config.onQrCode } : {}),
141
+ ...(this.config.onAppLaunchFailed
142
+ ? { onAppLaunchFailed: this.config.onAppLaunchFailed }
143
+ : {}),
144
+ ...(biometricSessionToken ? { biometricSessionToken } : {}),
145
+ biometricService: this.biometricService,
146
+ };
147
+ client.initialize(initOptions);
148
+ return client;
149
+ }
150
+ async runSignedOperation(run, context) {
151
+ const { bst } = await this.requestBiometricSessionToken();
152
+ const client = this.createSdk(bst);
153
+ const brt = await run(client);
154
+ const claims = this.decodeJwtPayload(brt);
155
+ if (claims && this.isFailedClaims(claims)) {
156
+ throw this.errorFromFailedClaims(claims);
157
+ }
158
+ await this.submitBiometricResultToken(brt, context?.enrollOptions);
159
+ return brt;
160
+ }
161
+ matchesPendingOperation(operation, matcher) {
162
+ if (!matcher)
163
+ return true;
164
+ if (typeof matcher === 'string')
165
+ return operation === matcher;
166
+ if (Array.isArray(matcher))
167
+ return matcher.includes(operation);
168
+ if (typeof matcher === 'function')
169
+ return matcher(operation);
170
+ return false;
171
+ }
172
+ extractBrt(payload) {
173
+ if (!payload || typeof payload !== 'object')
174
+ return undefined;
175
+ const brt = payload.brt;
176
+ return typeof brt === 'string' && brt.length > 0 ? brt : undefined;
177
+ }
178
+ decodeJwtPayload(token) {
179
+ try {
180
+ const parts = token.split('.');
181
+ if (parts.length < 2)
182
+ return undefined;
183
+ const payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
184
+ const padded = payload + '='.repeat((4 - (payload.length % 4)) % 4);
185
+ const json = typeof atob === 'function'
186
+ ? atob(padded)
187
+ : Buffer.from(padded, 'base64').toString('utf-8');
188
+ return JSON.parse(json);
189
+ }
190
+ catch {
191
+ return undefined;
192
+ }
193
+ }
194
+ isFailedClaims(claims) {
195
+ return claims.success === false || claims.success === 'false';
196
+ }
197
+ errorFromFailedClaims(claims, fallbackMessage = 'Biometric result not successful') {
198
+ const reason = String(claims.reason ?? '').toLowerCase();
199
+ const code = String(claims.code ?? '').toUpperCase();
200
+ const error = String(claims.error ?? '');
201
+ const cancelled = claims.cancelled === true ||
202
+ reason === 'back' ||
203
+ reason === 'cancel' ||
204
+ reason === 'cancelled' ||
205
+ reason === 'user_cancelled' ||
206
+ code === 'CANCELLED' ||
207
+ code === 'USER_CANCELLED' ||
208
+ /cancel|canceled|cancelled/i.test(error);
209
+ if (cancelled) {
210
+ return new NeumaMobileInterface_1.NeumaError('Cancelled by user', 'USER_CANCELLED');
211
+ }
212
+ return new NeumaMobileInterface_1.NeumaError(error || fallbackMessage, 'AUTH_FAILED');
213
+ }
214
+ async requestBiometricSessionToken() {
215
+ const response = await this.postJson(this.config.biometricSessionUrl);
216
+ if (!response?.bst || typeof response.bst !== 'string') {
217
+ throw new Error('Missing bst in biometric session response');
218
+ }
219
+ return response;
220
+ }
221
+ async submitBiometricResultToken(brt, enrollOptions) {
222
+ const payload = this.buildResultPayload(brt, enrollOptions);
223
+ return this.postJsonWithRetry(this.config.biometricResultUrl, payload);
224
+ }
225
+ buildResultPayload(brt, enrollOptions) {
226
+ if (this.config.resultPayloadBuilder) {
227
+ return this.config.resultPayloadBuilder({ brt, enrollOptions });
228
+ }
229
+ return { brt };
230
+ }
231
+ async postJson(url, body) {
232
+ if (!this.config.fetcher) {
233
+ throw new Error('Missing fetcher for NeumaClientHelper');
234
+ }
235
+ const response = await this.config.fetcher(url, {
236
+ method: 'POST',
237
+ headers: {
238
+ 'Content-Type': 'application/json',
239
+ },
240
+ body: body ? JSON.stringify(body) : undefined,
241
+ });
242
+ if (!response.ok) {
243
+ const message = await response.text();
244
+ throw new Error(message || `Request failed (${response.status})`);
245
+ }
246
+ return response.json();
247
+ }
248
+ /**
249
+ * POST helper for the biometric-result submission path. Retries only
250
+ * on network-class fetch rejections (e.g. iOS Safari tab-refocus
251
+ * jitter producing `TypeError: Failed to fetch`). HTTP error statuses
252
+ * are deterministic server responses and are not retried. The
253
+ * /biometric-results endpoint is server-side keyed by callbackId/jti
254
+ * so retrying a POST is idempotent.
255
+ */
256
+ async postJsonWithRetry(url, body) {
257
+ if (!this.config.fetcher) {
258
+ throw new Error('Missing fetcher for NeumaClientHelper');
259
+ }
260
+ const maxAttempts = 5;
261
+ const retryDelayMs = 2000;
262
+ let lastNetworkError;
263
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
264
+ let response;
265
+ try {
266
+ response = await this.config.fetcher(url, {
267
+ method: 'POST',
268
+ headers: {
269
+ 'Content-Type': 'application/json',
270
+ },
271
+ body: body ? JSON.stringify(body) : undefined,
272
+ });
273
+ }
274
+ catch (err) {
275
+ lastNetworkError = err;
276
+ if (attempt === maxAttempts)
277
+ break;
278
+ await new Promise(r => setTimeout(r, retryDelayMs));
279
+ continue;
280
+ }
281
+ if (!response.ok) {
282
+ const message = await response.text();
283
+ throw new Error(message || `Request failed (${response.status})`);
284
+ }
285
+ return response.json();
286
+ }
287
+ throw lastNetworkError;
288
+ }
289
+ }
290
+ exports.NeumaClientHelper = NeumaClientHelper;
291
+ let helperInstance = null;
292
+ const getHelperInstance = () => {
293
+ if (!helperInstance) {
294
+ throw new Error('neumaClientHelper is not initialized');
295
+ }
296
+ return helperInstance;
297
+ };
298
+ exports.neumaClientHelper = {
299
+ init(config) {
300
+ if (!helperInstance) {
301
+ helperInstance = new NeumaClientHelper(config);
302
+ }
303
+ return helperInstance;
304
+ },
305
+ get: getHelperInstance,
306
+ ensureInitialized() {
307
+ getHelperInstance().ensureInitialized();
308
+ },
309
+ enrollUser(user, enrollOptions) {
310
+ return getHelperInstance().enrollUser(user, enrollOptions);
311
+ },
312
+ restoreUser() {
313
+ return getHelperInstance().restoreUser();
314
+ },
315
+ authenticateUser() {
316
+ return getHelperInstance().authenticateUser();
317
+ },
318
+ authenticateUserDirect() {
319
+ return getHelperInstance().authenticateUserDirect();
320
+ },
321
+ unenrollUser() {
322
+ return getHelperInstance().unenrollUser();
323
+ },
324
+ retrieveKey() {
325
+ return getHelperInstance().retrieveKey();
326
+ },
327
+ clearUser() {
328
+ return getHelperInstance().clearUser();
329
+ },
330
+ parseRetrieveKeyResult(jsonString) {
331
+ return getHelperInstance().parseRetrieveKeyResult(jsonString);
332
+ },
333
+ getPendingOperation() {
334
+ return getHelperInstance().getPendingOperation();
335
+ },
336
+ resumePendingResult() {
337
+ return getHelperInstance().resumePendingResult();
338
+ },
339
+ clearPendingResult() {
340
+ getHelperInstance().clearPendingResult();
341
+ },
342
+ handlePendingOperation(options) {
343
+ return getHelperInstance().handlePendingOperation(options);
344
+ },
345
+ };
@@ -0,0 +1,5 @@
1
+ import { NeumaMobileInterface } from './NeumaMobileInterface';
2
+ export declare class NeumaMobileFactory {
3
+ private constructor();
4
+ static create(): NeumaMobileInterface;
5
+ }