@ideem/zsm-client-sdk 2.2.5 → 2.4.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 CHANGED
@@ -29,3 +29,9 @@ An example application demonstrating how to integrate this SDK into an applicati
29
29
 
30
30
  ## Support
31
31
  You can receive support and get your questions answered by emailing <a href="mailto:support@useideem.com">support@useideem.com</a>.
32
+
33
+ ### License
34
+ Please refer to the LICENSE file in this directory for the license governing the use of this SDK.
35
+
36
+ ### Release Notes
37
+ Please refer to the RELEASE_NOTES.txt file in this directory for the release notes of this SDK.
@@ -0,0 +1,116 @@
1
+ ZSM Client SDK for Browser Apps
2
+ Latest version: v2.3.0
3
+ Latest release date: March 24, 2025
4
+
5
+ The ZSM Client SDK for Browser Apps provides the resources needed to integrate Ideem's FIDO2 Authenticator
6
+ and Universal MFA into a browser application.
7
+
8
+ ## Resources:
9
+ - UMFA Documentation: https://docs.useideem.com/umfa_sdk/browser/index.html
10
+ - FIDO2 Documentation: https://docs.useideem.com/fido2_sdk/browser/index.html
11
+ - Support: support@useideem.com
12
+
13
+ ## Known Issues
14
+ - None
15
+
16
+ ----
17
+
18
+ ## Release 2.4.0 - May 1, 2025 [ NPM PACKAGE RELEASE ] **[ LATEST ]**
19
+ - Minor bug fixes and improvements
20
+ - Updates to documentation
21
+ - Adds event emitters to the UMFAClient and FIDO2Client for on-the-fly initializations
22
+ - Adds extended multi-tenancy support for the UMFAClient and FIDO2Client
23
+ - Adds increased detail to performance logging
24
+ - Extends secure local storage support
25
+
26
+ ## Release 2.3.0 - Mar 24, 2025
27
+ - Minor bug fixes and improvements
28
+ - Updates to documentation
29
+ - Introduces web-worker-driven JS SDK Client for browser-based applications
30
+ - Significant performance improvements to the UMFA JS Client
31
+ - Updates native mobile SDKs to support the new optimized flows
32
+ - Adds unenroll/webauthnDelete functionality to UMFAClient and FIDO2Client (browser, mobile, and native)
33
+ - Updates data parsing and replication in SQL and Oracle environments
34
+
35
+ ## Release 2.2.12 - Mar 14, 2025
36
+ - Minor bug fixes and improvements
37
+ - Updates to documentation
38
+ - Improves server-side TLS handling performance
39
+ - Adds optimized flows to the UMFA CLI Client
40
+
41
+ ## Release 2.2.11 - Mar 5, 2025
42
+ - Minor bug fixes and improvements
43
+ - Updates to documentation
44
+ - Updates to UMFA CLI for enhanced trace reporting
45
+ - Updates Affinity rules
46
+ - Native Webauthn apps and sdk updates
47
+ - Improves package and file versioning for safer deployments
48
+
49
+ ## Release 2.2.10 - Feb 27, 2025
50
+ - Minor bug fixes and improvements
51
+ - Updates to documentation
52
+ - Performance upgrades to AS2 environment
53
+ - Extended Trace Map and Host URL Parameter Renames
54
+ - Updates to Android-based tls security
55
+ - CLI updates for compression formats
56
+
57
+ ## Release 2.2.9 - Feb 14, 2025
58
+ - Minor bug fixes and improvements
59
+ - Updates to documentation
60
+ - Adjustments to deployment process
61
+ - React Native SDK updates
62
+ - Extended trace mapping implementation
63
+
64
+ ## Release 2.2.8 - Feb 7, 2025 [ NPM PACKAGE RELEASE ]
65
+ - Minor bug fixes and improvements
66
+ - Updates to documentation
67
+ - Adds support for the latest version of the React Native SDK
68
+ - Adds 2 New production-ready environments
69
+ - Updates binaries for use with M-class Macs
70
+ - Improves WASM binary benchmarks
71
+
72
+ ## Release 2.2.7 - Jan 31, 2025
73
+ - Minor bug fixes and improvements
74
+ - Updates to documentation
75
+ - Removed validate token message from UMFA demo transcript
76
+ - Fixes condition in which mobile portrait view loses contact with clear and docs buttons.
77
+ - Removed dependency on colored crate
78
+ - Added new API for enhanced security features
79
+
80
+ ## Release 2.2.6 - January 24, 2024 [ NPM PACKAGE RELEASE ]
81
+ - Minor bug fixes and improvements
82
+ - Updates to documentation
83
+ - Increased high-latency tolerance timeout from a 65-second max to a 300-second max.
84
+ - Expand Performance Logging
85
+
86
+ ## Release 2.2.4 - January 22, 2024 [ NPM PACKAGE RELEASE ]
87
+ - Minor bug fixes and improvements
88
+ - Updates to documentation
89
+ - AS2 support added
90
+
91
+ ## Release 2.2.3 - January 20, 2024 [ NPM PACKAGE RELEASE ]
92
+ - Minor bug fixes and improvements
93
+ - Updates to documentation
94
+ - Stability and format improvements
95
+
96
+ ## Release v2.2.2 - January 13, 2024 [ NPM PACKAGE RELEASE ]
97
+ - Minor bug fixes and improvements
98
+ - Updates to documentation
99
+ - Deployment via NPM
100
+ - Addition of Vue support (foundation for other web frameworks)
101
+ - Addition of checkEnrollment() and enroll() APIs
102
+ - Addition of SDK-to-server API Key for reporting purposes (not security)
103
+ - Removal of validateToken() API. Token validation is to be via server-to-server for security reasons.
104
+
105
+ ## Release v2.2.1 - December 9, 2024 [ NPM PACKAGE RELEASE ]
106
+ - Performance and stability improvements
107
+ - WASM size reduction
108
+ - Reduced expiration time to 30 seconds for the JWT returned by Authenticate
109
+ - Restructured SDK files to be more organized
110
+ - Modified application configuration approach to use a configuration json file,
111
+ but can also be overridden in the code.
112
+ - Improvements to Demo apps at https://demo.useideem.com
113
+
114
+ ## Release v2.2.0 - November 19, 2024 [ NPM PACKAGE RELEASE ]
115
+ - Addition of FIDO2 Authenticator interfaces
116
+ - Addition of Universal MFA interfaces
@@ -0,0 +1,473 @@
1
+ // Alias environment-specific global object
2
+ const GLOBAL = typeof globalThis !== "undefined" ? globalThis
3
+ : typeof self !== "undefined" ? self
4
+ : typeof window !== "undefined" ? window
5
+ : typeof global !== "undefined" ? global
6
+ : (() => { throw new Error("Unable to determine global scope"); })();
7
+
8
+ // Error class for worker errors
9
+ class WorkerError extends Error {
10
+ constructor(name, message, ...details) {
11
+ super(message);
12
+ this.name = name ? `Worker ${name} Error` : 'Worker Error';
13
+ if (details.length) this.details = details;
14
+ if (Error.captureStackTrace) {
15
+ Error.captureStackTrace(this, WorkerError);
16
+ } else {
17
+ this.stack = (new Error(message)).stack;
18
+ }
19
+ }
20
+ }
21
+
22
+ class ZSMClientBase {
23
+ constructor(config) {
24
+ this.config = config;
25
+ this.clientWorker = null;
26
+ this.timeoutTimer = null;
27
+ GLOBAL.zsmClient = null;
28
+ }
29
+
30
+ /**
31
+ * @name init
32
+ * @description Initializes the ZSMClient instance and sets up the worker.
33
+ * @param {String} clientType The type of client to initialize [default: 'UMFAClient']
34
+ * @param {Object} config The configuration object for the client [default: this.config]
35
+ * @returns {Promise<ZSMClientBase>} A promise that resolves to the initialized ZSMClient instance.
36
+ */
37
+ async init(clientType='UMFAClient', config=this.config) {
38
+ if(GLOBAL.clientWorker) GLOBAL.clientWorker.terminate();
39
+ const workerPath = GLOBAL?.workerPath ? GLOBAL.workerPath
40
+ : config?.workerPath ? config.workerPath
41
+ : './worker.js';
42
+ const pathResolver = (import.meta && import.meta?.resolve) ? import.meta?.resolve(workerPath)
43
+ : (import.meta && import.meta?.url) ? import.meta?.url.replace(/\/[^\/]+$/, '/' + workerPath)
44
+ : document?.currentScript ? document?.currentScript?.src?.replace(/\/[^\/]+$/, '/' + workerPath)
45
+ : workerPath;
46
+ GLOBAL.clientWorker = this.clientWorker = new Worker(new URL(pathResolver));
47
+ GLOBAL.zsmClient = this;
48
+ await this.callWorkerFunction("init", {config, clientType}, false);
49
+ return this;
50
+ }
51
+
52
+ /**
53
+ * @name callWorkerFunction
54
+ * @description Calls a function in the worker and returns a promise that resolves with the result.
55
+ * @param {String} functionName The name of the function to call in the worker.
56
+ * @param {Object} data The data to pass to the worker function.
57
+ * @param {Boolean} responseExpected Whether an acknowledgement is expected [Default: true]
58
+ * @returns {Promise<Object>} A promise that resolves with the result of the worker function.
59
+ */
60
+ async callWorkerFunction(functionName, data, responseExpected=true) {
61
+ let workerPromise = new Promise((resolve, reject) => {
62
+ this.clientWorker.postMessage({functionName, data });
63
+ if(responseExpected) this.timeoutTimer = GLOBAL.setTimeout(() => reject(new WorkerError('Transaction', 'Transaction timed out after 60 seconds!')), 60000);
64
+
65
+ this.clientWorker.onmessage = (event) => {
66
+ GLOBAL.clearTimeout(this.timeoutTimer);
67
+
68
+ let workerResponse = event.data;
69
+
70
+ if(GLOBAL.showWorkerTelemetry && (workerResponse.result || workerResponse.error)) {
71
+ console.groupCollapsed(`%cWorker posted to Main Thread a response to invocation:`, 'font-weight:bold; color:#F60;', functionName)
72
+ console.log(`%c Function Invoked:`, 'font-weight:100; color:#AAA;', workerResponse.functionName);
73
+ console.log(`%c Success Status:`, 'font-weight:100; color:#AAA;', workerResponse.success ? 'true' : 'false');
74
+ console.log(`%c Result value:`, 'font-weight:100; color:#AAA;', (workerResponse.success ? workerResponse.result : workerResponse.error));
75
+ console.log(`%c Response Object:`, 'font-weight:100; color:#AAA;', workerResponse);
76
+ console.groupEnd();
77
+ }
78
+
79
+ if (workerResponse instanceof Error || workerResponse.error || !workerResponse.success) {
80
+ return reject(workerResponse.error);
81
+ }
82
+ resolve(workerResponse.result);
83
+ };
84
+
85
+ this.clientWorker.onerror = (err) => { GLOBAL.clearTimeout(this.timeoutTimer); reject(new WorkerError('', err.message)); };
86
+ this.clientWorker.onmessageerror = (err) => { GLOBAL.clearTimeout(this.timeoutTimer); reject(new WorkerError('Message', err.message)); };
87
+ });
88
+
89
+ /**
90
+ * @event workerEvent
91
+ * @description Event triggered when the worker posts an event to the main thread.
92
+ * @param {String} eventName The name of the event.
93
+ * @param {Object} eventData The data associated with the event.
94
+ * @returns {void}
95
+ * @emits {CustomEvent} event The event object containing the received event name and data.
96
+ * @example GLOBAL.addEventListener('workerEvent', (event) => {
97
+ * @ console.log('Received event from worker:', event.detail.eventName, event.detail.eventData);
98
+ * @ });
99
+ */
100
+ this.clientWorker.addEventListener('message', (event) => {
101
+ if(!event.data || !event.data.eventName) return;
102
+ const { eventName, eventData } = event.data;
103
+ if(GLOBAL.showWorkerTelemetry) console.log(`%cWorker posted to Main Thread an event:`, 'font-weight:bold; color:#F60;', eventName, eventData);
104
+ GLOBAL.dispatchEvent(new CustomEvent(eventName, { detail: eventData }));
105
+ });
106
+ return workerPromise;
107
+ }
108
+ }
109
+
110
+ class UMFAClient extends ZSMClientBase {
111
+ constructor(config) {
112
+ super(config);
113
+ this.init = super.init.bind(this);
114
+ this.callWorkerFunction = super.callWorkerFunction.bind(this);
115
+ this.checkEnrollment = this.checkEnrollment.bind(this);
116
+ this.enroll = this.enroll.bind(this);
117
+ this.authenticate = this.authenticate.bind(this);
118
+ this.optimizedEnroll = this.optimizedEnroll.bind(this);
119
+ this.optimizedAuthenticate = this.optimizedAuthenticate.bind(this);
120
+ this.init('UMFAClient');
121
+ }
122
+
123
+ async checkEnrollment(user) { return await this.callWorkerFunction('checkEnrollment', user); }
124
+ async enroll(user) { return await this.callWorkerFunction('enroll', user); }
125
+ async authenticate(user) { return await this.callWorkerFunction('authenticate', user); }
126
+ async optimizedEnroll(user) { return await this.callWorkerFunction('optimizedEnroll', user); }
127
+ async optimizedAuthenticate(user) { return await this.callWorkerFunction('optimizedAuthenticate', user); }
128
+ async unenroll(user) { return await this.callWorkerFunction('unenroll', user); }
129
+ }
130
+
131
+ class FIDO2Client extends ZSMClientBase {
132
+ constructor(config) {
133
+ super(config);
134
+ this.init = super.init.bind(this);
135
+ this.callWorkerFunction = super.callWorkerFunction.bind(this);
136
+ this.checkEnrollment = this.checkEnrollment.bind(this);
137
+ this.checkIdentity = this.checkIdentity.bind(this);
138
+ this.webauthnCreate = this.webauthnCreate.bind(this);
139
+ this.webauthnGet = this.webauthnGet.bind(this);
140
+ this.webauthnRetrieve = this.webauthnRetrieve.bind(this);
141
+ this.webauthnDelete = this.webauthnDelete.bind(this);
142
+ this.init('FIDO2Client');
143
+ }
144
+
145
+ async checkIdentity(user, auto=true) { return await this.callWorkerFunction('checkIdentity', [user, auto]); }
146
+ async checkEnrollment(user) { return await this.callWorkerFunction('checkEnrollment', user); }
147
+ async webauthnCreate(user) { return await this.callWorkerFunction('webauthnCreate', user); }
148
+ async webauthnGet(user) { return await this.callWorkerFunction('webauthnGet', user); }
149
+ async webauthnRetrieve(user) { return await this.callWorkerFunction('webauthnRetrieve', user); }
150
+ async webauthnDelete(user) { return await this.callWorkerFunction('webauthnDelete', user); }
151
+ }
152
+
153
+ function amendPerformanceLoggingToClass(cls) {
154
+ GLOBAL.sessionStamp = new Date();
155
+ GLOBAL.sessionStamp = new Date(GLOBAL.sessionStamp.getTime() - (GLOBAL.sessionStamp.getTimezoneOffset() * 60000)).toISOString().slice(11, -5);
156
+ GLOBAL.exportCount = 0;
157
+
158
+ if(GLOBAL.logStack == null) {
159
+ GLOBAL.logStack = [];
160
+ GLOBAL.getLogs = () => GLOBAL.logStack.sort((a, b) => a.stamp - b.stamp);
161
+ GLOBAL.clearLogs = () => {GLOBAL.logStack = []; };
162
+ GLOBAL.showLogs = () => {
163
+ if(!GLOBAL.logStack || GLOBAL.logStack.length === 0) return console.info('There are no logs currently in the stack!');
164
+
165
+ const getTime = (ISOStamp) => new Date(ISOStamp).toISOString().split('T')[1].slice(0,-1);
166
+
167
+ (function parseLog(stack=[...GLOBAL.logStack], parentEndTime = Infinity) {
168
+ while (stack.length > 0 && stack[0].startTime < parentEndTime) {
169
+ let markS, markE, spanName, indE, duration, stamps;
170
+ markS = stack.shift();
171
+ spanName = markS.name.slice(0, -6);
172
+ indE = stack.findIndex(log => log.name === spanName + "-END");
173
+ if (indE !== -1) markE = stack.splice(indE, 1)[0];
174
+ duration = (markE != null) ? (markE.startTime - markS.startTime).toFixed(4) + 'ms' : 'ONGOING';
175
+ stamps = (markE != null) ? getTime(markS.stamp) + " - " + getTime(markE.stamp) : getTime(markS.stamp) + " - ...";
176
+
177
+ console.groupCollapsed(spanName.replace(/-/g, ' :: ') + ' :: ' + duration + " (" + stamps + ")");
178
+ parseLog(stack, markE.startTime);
179
+ console.groupEnd();
180
+ }
181
+ })()
182
+ }
183
+
184
+ GLOBAL.addPerfMarker = (tag) => {
185
+ const {name, startTime} = performance.mark(tag).toJSON();
186
+ GLOBAL.logStack.push({
187
+ type : "MAINTHREAD",
188
+ order : GLOBAL.logStack.length,
189
+ name,
190
+ absTime : startTime,
191
+ stamp : performance.timeOrigin + startTime
192
+ });
193
+ }
194
+ }
195
+
196
+ return class extends cls {
197
+ constructor(...args) {
198
+ super(...args);
199
+
200
+ Object.getOwnPropertyNames(this).forEach(propName => {
201
+ if (propName === "constructor" || typeof this[propName] !== "function") return;
202
+
203
+ const originalMethod = this[propName];
204
+ let markerTagPrefix = `[MAINTHREAD]-${cls.name}-${propName}`;
205
+ this[propName] = function(...args) {
206
+ if(propName === "callWorkerFunction") markerTagPrefix = `[MAINTHREAD]-${cls.name}-${propName}-${args[0]}`;
207
+ GLOBAL.addPerfMarker(markerTagPrefix + "-START");
208
+ const result = originalMethod.apply(this, args);
209
+ if (result && typeof result.then === 'function') {
210
+ return result.finally(() => GLOBAL.addPerfMarker(markerTagPrefix + "-END"));
211
+ } else {
212
+ GLOBAL.addPerfMarker(markerTagPrefix + "-END");
213
+ return result;
214
+ }
215
+ };
216
+ });
217
+ }
218
+ };
219
+ }
220
+
221
+ //
222
+ if(typeof UMFAClient !== "undefined" && UMFAClient instanceof Function) UMFAClient = amendPerformanceLoggingToClass(UMFAClient);
223
+ if(typeof FIDO2Client !== "undefined" && FIDO2Client instanceof Function) FIDO2Client = amendPerformanceLoggingToClass(FIDO2Client);
224
+
225
+ let masterLogs = [];
226
+ if(window){
227
+ let tzO = new Date().getTimezoneOffset() * 60000;
228
+
229
+ GLOBAL.getAllLogs = async (showCSV) => {
230
+ let res = await zsmClient.callWorkerFunction("getLogs");
231
+ let {logs, timeOrigin} = JSON.parse(res);
232
+ let timeDifferential = performance.timeOrigin - timeOrigin;
233
+ if(!showCSV) {
234
+ console.groupCollapsed('RAW logs');
235
+ GLOBAL.logStack.forEach(mainRecord => console.info('mainRecord :', mainRecord));
236
+ logs.forEach(workerRecord => {
237
+ workerRecord.absTime = workerRecord.absTime - timeDifferential;
238
+ console.info('workerRecord :', workerRecord);
239
+ });
240
+ console.groupEnd();
241
+ }
242
+ let allLogs = [...GLOBAL.logStack, ...logs];
243
+ allLogs = allLogs.sort((a, b) => a.absTime - b.absTime);
244
+ allLogs = allLogs.map((log, i) => Object.assign(log, {stamp: log.absTime + performance.timeOrigin, order:i}));
245
+ if(!showCSV) {
246
+ console.groupCollapsed('ALL logs (Combined and Sorted)');
247
+ masterLogs = [...masterLogs, ...allLogs];
248
+ allLogs.forEach(log => console.info('log :', log));
249
+ console.groupEnd();
250
+ }
251
+ console.groupCollapsed('ALL logs (Combined and Sorted)');
252
+ allLogs = allLogs.map(log => {
253
+ if(!localStorage) return log;
254
+ let activeEnv = localStorage.getItem('activeEnv');
255
+ if(!activeEnv) return log;
256
+ if(! /RELPARTYSERVER|CRYPTOSERVER/.test(log.type)) return log;
257
+ // log.type += '-' + activeEnv.toUpperCase();
258
+ return log;
259
+ });
260
+ allLogs.forEach(log => console.info('log :', log));
261
+ console.groupEnd();
262
+
263
+ return allLogs;
264
+ };
265
+
266
+ GLOBAL.showLogs = async (showCSV=false) => {
267
+ const getTime = (ISOStamp, timeOnly=true) => {
268
+ try{
269
+ return timeOnly ? new Date((+ISOStamp - tzO)).toISOString().slice(11,-1) : new Date(+ISOStamp - tzO).toISOString();
270
+ }catch(e){
271
+ console.error('Error parsing ISOStamp:', ISOStamp, e);
272
+ return ISOStamp;
273
+ }
274
+ }
275
+ const stripStartEnd = (name) => name.replace(/-(START|END)$/gi, '');
276
+
277
+ function recursivelyMoveChildLogsIntoStartNode(stack) {
278
+ let processedLogs = [];
279
+ while (stack.length > 0) {
280
+ let startingMarker = stack.shift();
281
+ if(/-END$/i.test(startingMarker.name)) {
282
+ continue;
283
+ }
284
+ let endingMarker = stack.findIndex(log => log.name === stripStartEnd(startingMarker.name) + '-END'),
285
+ dateTimeStamps = [],
286
+ fullDateStamps = [],
287
+ stackSubset = [],
288
+ totalDuration = 0,
289
+ networkLatency = 0,
290
+ computeDuration = 0;
291
+
292
+ if(!~endingMarker) {
293
+ stackSubset = stack;
294
+ endingMarker = stack.length;
295
+ totalDuration = 'ONGOING';
296
+ dateTimeStamps.push(getTime(startingMarker.stamp), '...?');
297
+ fullDateStamps.push(getTime(startingMarker.stamp, false), '...?');
298
+
299
+ }else{
300
+ stackSubset = stack.splice(0, endingMarker+1);
301
+ endingMarker = stackSubset[stackSubset.length-1];
302
+ totalDuration = endingMarker.absTime - startingMarker.absTime;
303
+ dateTimeStamps.push(getTime(startingMarker.stamp), getTime(endingMarker.stamp));
304
+ fullDateStamps.push(getTime(startingMarker.stamp, false), getTime(endingMarker.stamp, false));
305
+
306
+ }
307
+
308
+ processedLogs.push(Object.assign(startingMarker, {
309
+ name: stripStartEnd(startingMarker.name),
310
+ children: recursivelyMoveChildLogsIntoStartNode(stackSubset),
311
+ totalDuration,
312
+ dateTimeStamps,
313
+ fullDateStamps,
314
+ networkLatency,
315
+ computeDuration
316
+ }));
317
+ }
318
+ return processedLogs;
319
+ }
320
+
321
+ function recursivelyComputeCumulativeNetworkLatency(node) {
322
+ let nodeLatency = 0;
323
+ if(node.clientToServerLatency) nodeLatency += node.clientToServerLatency;
324
+ if(node.serverToClientLatency) nodeLatency += node.serverToClientLatency;
325
+
326
+ if (Array.isArray(node.children) && node.children.length > 0) {
327
+ node.children.forEach(child => {
328
+ nodeLatency += recursivelyComputeCumulativeNetworkLatency(child);
329
+ });
330
+ }
331
+ node.networkLatency = nodeLatency;
332
+ return nodeLatency;
333
+ }
334
+
335
+ function calculateComputeDurationForNode(node) {
336
+ if(!node.children) return node.computeDuration = totalDuration;
337
+ node.computeDuration = (node.children.reduce((acc,child)=>{
338
+ return acc - child.totalDuration;
339
+ }, node.totalDuration))
340
+ node.children.forEach(calculateComputeDurationForNode)
341
+ }
342
+
343
+ let exportableStack = [];
344
+
345
+ function recursivelyOutputLogsToConsole(stack, depth = 0) {
346
+ let outputColors={
347
+ 'MAINTHREAD': '#509',
348
+ 'WORKER': '#009',
349
+ 'RELPARTYSERVER': '#076',
350
+ 'CRYPTOSERVER': '#700',
351
+ 'RELPARTY': '#076',
352
+ 'CRYPTO': '#700',
353
+ };
354
+
355
+ function formatNumberColumn(num, NaNValue='0.000') {
356
+ let opValue = isNaN(num) ? NaNValue : Math.abs(num).toFixed(3);
357
+ let lPadStr = ' '.repeat(12 - opValue.length);
358
+ return lPadStr + opValue;
359
+ }
360
+
361
+ stack.forEach(item => {
362
+ let spacePadding = ' '.repeat(100);
363
+ let exportableRecord = {}
364
+ let sequence = item.order;
365
+ let nameElements = (item.name.match(/\[(.*?)\]-(.*)$/) || new Array(3).fill('')).slice(1,3);
366
+ let threadName = (nameElements[0] + spacePadding).replace('SERVER', '').slice(0, 14);
367
+ let processName = (nameElements[1] + spacePadding).slice(0, 70-(depth*2));
368
+ let totalDuration = formatNumberColumn(item?.totalDuration, 'ONGOING');
369
+ let computeDuration = (/ONGOING/.test(totalDuration)) ? formatNumberColumn('ONGOING', 'ONGOING') : formatNumberColumn(item?.computeDuration);
370
+ let networkLatency = (/ONGOING/.test(totalDuration)) ? formatNumberColumn('ONGOING', 'ONGOING') : formatNumberColumn(item?.networkLatency);
371
+ let cumulativeCompute;
372
+ if(/ONGOING/.test(totalDuration)) cumulativeCompute = formatNumberColumn('ONGOING', 'ONGOING');
373
+ else {
374
+ if(totalDuration < (Math.abs(networkLatency) + Math.abs(computeDuration))) totalDuration = formatNumberColumn(Math.abs(networkLatency) + Math.abs(computeDuration));
375
+ cumulativeCompute = formatNumberColumn((totalDuration - networkLatency - computeDuration), 'ONGOING');
376
+ }
377
+ let indentionDepth = depth;
378
+ if (/^CRYPTO/.test(threadName)) {
379
+ indentionDepth = depth + 2;
380
+ processName = processName.slice(0, -4);
381
+ }
382
+
383
+ let indentionPads = depth > 0 ? ' '.repeat(indentionDepth-1) + ' ' : ' ';
384
+ let detailPads = depth > 0 ? ' '.repeat(indentionDepth-1) + ' '.repeat(threadName.length) + ' ' : ' ' + ' '.repeat(threadName.length);
385
+ let timeSpan = item?.dateTimeStamps ? (' ' + item.dateTimeStamps[0]) : 'N/A';
386
+
387
+ // if(!showCSV) {
388
+ let outputLine = ` ${threadName}${indentionPads} ${processName} ${totalDuration} ${networkLatency} ${cumulativeCompute} ${computeDuration} ${timeSpan}`;
389
+ console.groupCollapsed(`%c${outputLine}`, `color: ${outputColors[item.type]}; font-weight: 500;`);
390
+ console.info(`%c${detailPads} Sequence: `, `color: ${outputColors[item.type]}; font-weight: 700;`, sequence);
391
+ console.info(`%c${detailPads} Thread Name: `, `color: ${outputColors[item.type]}; font-weight: 700;`, threadName.trim());
392
+ console.info(`%c${detailPads} Process Name: `, `color: ${outputColors[item.type]}; font-weight: 700;`, processName.trim());
393
+ console.info(`%c${detailPads} Abs. Performance Mark: `, `color: ${outputColors[item.type]}; font-weight: 700;`, (item?.absTime??'') + 'ms from timeOrigin');
394
+ console.info(`%c${detailPads} TimeStamp (Start): `, `color: ${outputColors[item.type]}; font-weight: 700;`, (item?.dateTimeStamps[0]??''));
395
+ console.info(`%c${detailPads} TimeStamp (End): `, `color: ${outputColors[item.type]}; font-weight: 700;`, (item?.dateTimeStamps[1]??''));
396
+ console.info(`%c${detailPads} Cumulative Tot. Duration: `, `color: ${outputColors[item.type]}; font-weight: 700;`, (/ONGOING/.test(totalDuration) ? 'ONGOING' : totalDuration.trim() + 'ms'));
397
+ console.info(`%c${detailPads} Cumulative Network Latency: `, `color: ${outputColors[item.type]}; font-weight: 700;`, (/ONGOING/.test(networkLatency) ? 'ONGOING' : networkLatency.trim() + 'ms'));
398
+ console.info(`%c${detailPads} Cumulative Compute Duration: `, `color: ${outputColors[item.type]}; font-weight: 700;`, (/ONGOING/.test(cumulativeCompute) ? 'ONGOING' : cumulativeCompute.trim() + 'ms'));
399
+ console.info(`%c${detailPads} Process Compute Duration: `, `color: ${outputColors[item.type]}; font-weight: 700;`, (/ONGOING/.test(computeDuration) ? 'ONGOING' : computeDuration.trim() + 'ms'));
400
+ console.info(`%c${detailPads} ================================================================`, `color: ${outputColors[item.type]}; font-weight: 700;`, "\n\n");
401
+ console.groupEnd();
402
+ // } else if(!showCSV || showCSV) {
403
+ let activeEnv = '';
404
+ let pageHost = window.location.host;
405
+
406
+ if(localStorage && localStorage.getItem('activeEnv')) {
407
+ activeEnv = (/RELPARTY|CRYPTO/.test(threadName)) ? localStorage.getItem('activeEnv') : 'N/A';
408
+ }
409
+ exportableRecord = {
410
+ sequence : sequence,
411
+ threadName : threadName.trim(),
412
+ processName : processName.trim(),
413
+ absTime : (item?.absTime) ? (item.absTime.toFixed(5)) : '',
414
+ totalDuration : (/ONGOING/.test(totalDuration) ? 'ONGOING' : +(totalDuration.trim())),
415
+ networkLatency : (/ONGOING/.test(networkLatency) ? 'ONGOING' : +(networkLatency.trim())),
416
+ cumulativeCompute : (/ONGOING/.test(cumulativeCompute) ? 'ONGOING' : +(cumulativeCompute.trim())),
417
+ computeDuration : (/ONGOING/.test(computeDuration) ? 'ONGOING' : +(computeDuration.trim())),
418
+ startTime : (item?.fullDateStamps[0]?.replace(/[TZ]/g, ' ').trim() ?? ''),
419
+ endTime : (item?.fullDateStamps[1]?.replace(/[TZ]/g, ' ').trim() ?? ''),
420
+ spawnsChildren : item?.children ? item.children.length : 0,
421
+ host : pageHost,
422
+ remoteAPIEnv : activeEnv,
423
+ };
424
+
425
+ exportableStack.push(exportableRecord);
426
+ // }
427
+ if(item.children.length > 0) recursivelyOutputLogsToConsole(item.children, depth + 1);
428
+ });
429
+ return exportableStack.length ? exportableStack : undefined;
430
+ }
431
+
432
+ let allLogs = await GLOBAL.getAllLogs(showCSV);
433
+ let processedStack = recursivelyMoveChildLogsIntoStartNode(allLogs);
434
+ processedStack.forEach(root => recursivelyComputeCumulativeNetworkLatency(root));
435
+ processedStack.forEach(root => calculateComputeDurationForNode(root));
436
+ if(!showCSV) console.info(`%c${' THREAD PROCESS NAME DURATION NETWORK TOT.COMP. COMPUTE START TIME'}`, 'color: #000; font-weight: 700;');
437
+ let exportableData = recursivelyOutputLogsToConsole(processedStack);
438
+ console.log('exportableData :', exportableData);
439
+ if(!showCSV || !exportableData) return;
440
+ let csvData = exportableData.flatMap((log, i) => {
441
+ let retVal = [Object.values(log)];
442
+ retVal[0][0] = i + 1;
443
+ retVal = ['"' + retVal[0].join('","') + '"'];
444
+ if(i === 0) retVal.unshift('"' + Object.keys(log).join('","') + '"');
445
+ return retVal;
446
+ });
447
+
448
+ try {
449
+ GLOBAL.exportCount++;
450
+ console.groupCollapsed(`CSV Data Exported as %c${GLOBAL.sessionStamp}-${(GLOBAL.exportCount)}.csv`, 'color: #F60; font-weight: 700;');
451
+ let blobdtMIME = new Blob([csvData.join('\n')], { type: "text/csv" });
452
+ let url = URL.createObjectURL(blobdtMIME)
453
+ let anchor = document.createElement("a")
454
+ anchor.id = "download"
455
+ anchor.setAttribute("download", `${GLOBAL.sessionStamp}-${(GLOBAL.exportCount)}.csv`);
456
+ anchor.href = url;
457
+ anchor.click();
458
+ console.info(`CSV Data:\n${csvData.join('\n')}\n...EOS`);
459
+ URL.revokeObjectURL(url);
460
+ GLOBAL.logStack = [];
461
+ zsmClient.callWorkerFunction("clearLogs", true);
462
+ console.groupEnd();
463
+ } catch (error) {
464
+ console.error('Error during download:', error);
465
+ console.groupEnd();
466
+ }
467
+
468
+ return exportableData;
469
+ }
470
+
471
+ }
472
+
473
+ export { UMFAClient, FIDO2Client };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ideem/zsm-client-sdk",
3
- "version": "2.2.5",
4
- "description": "A monolithic library exporting UMFAClient and FIDO2Client.",
3
+ "version": "2.4.0",
4
+ "description": "ZSM makes 2FA easy and invisible for everyone, all the time, using advanced cryptography like MPC to establish cryptographic proof of the origin of any transaction or login attempt, while eliminating opportunities for social engineering. ZSM has no reliance on specific hardware. Our cryptographic module has completed FIPS 140-3 NIST approved lab testing, is FIDO2-ready, and is on the Modules In Progress (MIP) list. Superior Usability. no opt-in, no codes, no downloads, no authenticator apps. Better Security.",
5
5
  "author": "@JJ (Jason Jurusz) <jj@useideem.com>/<nerdy.deeds@done.cheap>",
6
6
  "keywords": [
7
7
  "ideem",
@@ -22,7 +22,7 @@
22
22
  ],
23
23
  "scripts": {
24
24
  "start": "echo 'This is a library, not an application. No start script defined. To use, import the library.'",
25
- "inc": "npm version patch && cd ..; sleep 1; npm pack ./npm-package"
25
+ "inc": "npm version patch && cd ..; sleep 1; npm pack ./pkg_files"
26
26
  },
27
27
  "collaborators": [
28
28
  "Joel Teply <joel@useideem.com>",
@@ -30,20 +30,25 @@
30
30
  "Brian Koziel <brian@useideem.com>",
31
31
  "@JJ <jj@useideem.com>"
32
32
  ],
33
- "main": "zsm-client-sdk.js",
34
- "module": "zsm-client-sdk.js",
35
- "browser": "zsm-client-sdk.js",
36
33
  "license": "SEE LICENSE IN LICENSE",
37
34
  "repository": {
38
35
  "type": "git",
39
- "url": "https://github.com/useideem/vHSM.git"
36
+ "url": "github:useideem/vHSM"
40
37
  },
41
- "bugs": "https://github.com/useideem/vHSM/issues",
42
38
  "homepage": "http://useideem.com",
39
+ "bugs": "https://github.com/useideem/vHSM/issues",
43
40
  "files": [
44
- "zsm-client-sdk.js"
41
+ "worker.js",
42
+ "ZSMClientSDK.js",
43
+ "RELEASE_NOTES.txt",
44
+ "LICENSE",
45
+ "README.md"
45
46
  ],
46
47
  "engines": {
47
- "node": ">=20.0.0"
48
- }
48
+ "node": ">=12.0.0"
49
+ },
50
+ "sideEffects": [
51
+ "worker.js",
52
+ "ZSMClientSDK.js"
53
+ ]
49
54
  }