@fingerprint/node-sdk 7.0.0-test.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/.npmignore +9 -0
- package/LICENSE +19 -0
- package/dist/index.cjs +598 -0
- package/dist/index.d.ts +1872 -0
- package/dist/index.mjs +587 -0
- package/package.json +75 -0
- package/readme.md +191 -0
- package/src/errors/apiErrors.ts +51 -0
- package/src/errors/handleErrorResponse.ts +13 -0
- package/src/errors/toError.ts +7 -0
- package/src/errors/unsealError.ts +32 -0
- package/src/generatedApiTypes.ts +1517 -0
- package/src/index.ts +16 -0
- package/src/sealedResults.ts +94 -0
- package/src/serverApiClient.ts +321 -0
- package/src/types.ts +90 -0
- package/src/urlUtils.ts +171 -0
- package/src/webhook.ts +67 -0
package/.npmignore
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2021 FingerprintJS, Inc
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
SOFTWARE.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fingerprint Server Node.js SDK v7.0.0-test.0 - Copyright (c) FingerprintJS, Inc, 2026 (https://fingerprint.com)
|
|
3
|
+
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
var crypto = require('crypto');
|
|
9
|
+
var zlib = require('zlib');
|
|
10
|
+
var util = require('util');
|
|
11
|
+
var buffer = require('buffer');
|
|
12
|
+
|
|
13
|
+
exports.Region = void 0;
|
|
14
|
+
(function (Region) {
|
|
15
|
+
Region["EU"] = "EU";
|
|
16
|
+
Region["AP"] = "AP";
|
|
17
|
+
Region["Global"] = "Global";
|
|
18
|
+
})(exports.Region || (exports.Region = {}));
|
|
19
|
+
|
|
20
|
+
var version = "7.0.0-test.0";
|
|
21
|
+
|
|
22
|
+
const apiVersion = 'v4';
|
|
23
|
+
const euRegionUrl = 'https://eu.api.fpjs.io/';
|
|
24
|
+
const apRegionUrl = 'https://ap.api.fpjs.io/';
|
|
25
|
+
const globalRegionUrl = 'https://api.fpjs.io/';
|
|
26
|
+
function getIntegrationInfo() {
|
|
27
|
+
return `fingerprint-pro-server-node-sdk/${version}`;
|
|
28
|
+
}
|
|
29
|
+
function serializeQueryStringParams(params) {
|
|
30
|
+
const entries = [];
|
|
31
|
+
for (const [key, value] of Object.entries(params)) {
|
|
32
|
+
if (value == null) {
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (Array.isArray(value)) {
|
|
36
|
+
for (const v of value) {
|
|
37
|
+
if (v == null) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
entries.push([key, String(v)]);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
entries.push([key, String(value)]);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const urlSearchParams = new URLSearchParams(entries);
|
|
48
|
+
return urlSearchParams.toString();
|
|
49
|
+
}
|
|
50
|
+
function getServerApiUrl(region) {
|
|
51
|
+
switch (region) {
|
|
52
|
+
case exports.Region.EU:
|
|
53
|
+
return euRegionUrl;
|
|
54
|
+
case exports.Region.AP:
|
|
55
|
+
return apRegionUrl;
|
|
56
|
+
case exports.Region.Global:
|
|
57
|
+
return globalRegionUrl;
|
|
58
|
+
default:
|
|
59
|
+
throw new Error('Unsupported region');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Formats a URL for the FingerprintJS server API by replacing placeholders and
|
|
64
|
+
* appending query string parameters.
|
|
65
|
+
*
|
|
66
|
+
* @internal
|
|
67
|
+
*
|
|
68
|
+
* @param {GetRequestPathOptions<Path, Method>} options
|
|
69
|
+
* @param {Path} options.path - The path of the API endpoint
|
|
70
|
+
* @param {string[]} [options.pathParams] - Path parameters to be replaced in the path
|
|
71
|
+
* @param {QueryParams<Path, Method>["queryParams"]} [options.queryParams] - Query string
|
|
72
|
+
* parameters to be appended to the URL
|
|
73
|
+
* @param {Region} options.region - The region of the API endpoint
|
|
74
|
+
* @param {Method} options.method - The method of the API endpoint
|
|
75
|
+
*
|
|
76
|
+
* @returns {string} The formatted URL with parameters replaced and query string
|
|
77
|
+
* parameters appended
|
|
78
|
+
*/
|
|
79
|
+
function getRequestPath({ path, pathParams, queryParams, region,
|
|
80
|
+
// method mention here so that it can be referenced in JSDoc
|
|
81
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
82
|
+
method: _, }) {
|
|
83
|
+
// Step 1: Extract the path parameters (placeholders) from the path
|
|
84
|
+
const placeholders = Array.from(path.matchAll(/{(.*?)}/g)).map((match) => match[1]);
|
|
85
|
+
// Step 2: Replace the placeholders with provided pathParams
|
|
86
|
+
let formattedPath = `${apiVersion}${path}`;
|
|
87
|
+
placeholders.forEach((placeholder, index) => {
|
|
88
|
+
if (pathParams?.[index]) {
|
|
89
|
+
formattedPath = formattedPath.replace(`{${placeholder}}`, pathParams[index]);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
throw new Error(`Missing path parameter for ${placeholder}`);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
const queryStringParameters = {
|
|
96
|
+
...(queryParams ?? {}),
|
|
97
|
+
ii: getIntegrationInfo(),
|
|
98
|
+
};
|
|
99
|
+
const url = new URL(getServerApiUrl(region ?? exports.Region.Global));
|
|
100
|
+
url.pathname = formattedPath;
|
|
101
|
+
url.search = serializeQueryStringParams(queryStringParameters);
|
|
102
|
+
return url.toString();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
class SdkError extends Error {
|
|
106
|
+
response;
|
|
107
|
+
constructor(message, response, cause) {
|
|
108
|
+
super(message, { cause });
|
|
109
|
+
this.response = response;
|
|
110
|
+
this.name = this.constructor.name;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
class RequestError extends SdkError {
|
|
114
|
+
// HTTP Status code
|
|
115
|
+
statusCode;
|
|
116
|
+
// API error code
|
|
117
|
+
errorCode;
|
|
118
|
+
// API error response
|
|
119
|
+
responseBody;
|
|
120
|
+
// Raw HTTP response
|
|
121
|
+
response;
|
|
122
|
+
constructor(message, body, statusCode, errorCode, response) {
|
|
123
|
+
super(message, response);
|
|
124
|
+
this.responseBody = body;
|
|
125
|
+
this.response = response;
|
|
126
|
+
this.errorCode = errorCode;
|
|
127
|
+
this.statusCode = statusCode;
|
|
128
|
+
}
|
|
129
|
+
static unknown(response) {
|
|
130
|
+
return new RequestError('Unknown error', undefined, response.status, response.statusText, response);
|
|
131
|
+
}
|
|
132
|
+
static fromErrorResponse(body, response) {
|
|
133
|
+
return new RequestError(body.error.message, body, response.status, body.error.code, response);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Error that indicate that the request was throttled.
|
|
138
|
+
* */
|
|
139
|
+
class TooManyRequestsError extends RequestError {
|
|
140
|
+
constructor(body, response) {
|
|
141
|
+
super(body.error.message, body, 429, body.error.code, response);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function isErrorResponse(value) {
|
|
146
|
+
return Boolean(value &&
|
|
147
|
+
typeof value === 'object' &&
|
|
148
|
+
'error' in value &&
|
|
149
|
+
typeof value.error === 'object' &&
|
|
150
|
+
value.error &&
|
|
151
|
+
'code' in value.error &&
|
|
152
|
+
'message' in value.error);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function toError(e) {
|
|
156
|
+
if (e && typeof e === 'object' && 'message' in e) {
|
|
157
|
+
return e;
|
|
158
|
+
}
|
|
159
|
+
return new Error(String(e));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
class FingerprintServerApiClient {
|
|
163
|
+
region;
|
|
164
|
+
apiKey;
|
|
165
|
+
fetch;
|
|
166
|
+
defaultHeaders;
|
|
167
|
+
/**
|
|
168
|
+
* FingerprintJS server API client used to fetch data from FingerprintJS
|
|
169
|
+
* @constructor
|
|
170
|
+
* @param {Options} options - Options for FingerprintJS server API client
|
|
171
|
+
*/
|
|
172
|
+
constructor(options) {
|
|
173
|
+
if (!options.apiKey) {
|
|
174
|
+
throw Error('Api key is not set');
|
|
175
|
+
}
|
|
176
|
+
// These type assertions are safe because the Options type allows the
|
|
177
|
+
// region or authentication mode to be specified as a string or an enum value.
|
|
178
|
+
// The resulting JS from using the enum value or the string is identical.
|
|
179
|
+
this.region = options.region ?? exports.Region.Global;
|
|
180
|
+
this.apiKey = options.apiKey;
|
|
181
|
+
this.fetch = options.fetch ?? fetch;
|
|
182
|
+
this.defaultHeaders = {
|
|
183
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
184
|
+
...options.defaultHeaders,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Retrieves a specific identification event with the information from each activated product — Identification and all active [Smart signals](https://dev.fingerprint.com/docs/smart-signals-overview).
|
|
189
|
+
*
|
|
190
|
+
* @param eventId - identifier of the event
|
|
191
|
+
* @param {object|undefined} options - Optional `getEvent` operation options
|
|
192
|
+
* @param {string|undefined} options.ruleset_id - Optional ruleset ID to evaluate against the event
|
|
193
|
+
*
|
|
194
|
+
* @returns {Promise<Event>} - promise with event response. For more information, see the [Server API documentation](https://dev.fingerprint.com/reference/getevent).
|
|
195
|
+
*
|
|
196
|
+
* @example
|
|
197
|
+
* ```javascript Handling an event
|
|
198
|
+
* client
|
|
199
|
+
* .getEvent('<eventId>')
|
|
200
|
+
* .then((event) => console.log(event))
|
|
201
|
+
* .catch((error) => {
|
|
202
|
+
* if (error instanceof RequestError) {
|
|
203
|
+
* console.log(error.statusCode, error.message)
|
|
204
|
+
* // Access raw response in error
|
|
205
|
+
* console.log(error.response)
|
|
206
|
+
* }
|
|
207
|
+
* })
|
|
208
|
+
* ```
|
|
209
|
+
*
|
|
210
|
+
* @example Handling an event with rule_action
|
|
211
|
+
* ```javascript
|
|
212
|
+
* client
|
|
213
|
+
* .getEvent('<eventId>', { ruleset_id: '<rulesetId>' })
|
|
214
|
+
* .then((event) => {
|
|
215
|
+
* const ruleAction = event.rule_action
|
|
216
|
+
* if (ruleAction?.type === 'block') {
|
|
217
|
+
* console.log('Blocked by rule:', ruleAction.rule_id, ruleAction.status_code)
|
|
218
|
+
* }
|
|
219
|
+
* })
|
|
220
|
+
* .catch((error) => {
|
|
221
|
+
* if (error instanceof RequestError) {
|
|
222
|
+
* console.log(error.statusCode, error.message)
|
|
223
|
+
* }
|
|
224
|
+
* })
|
|
225
|
+
* ```
|
|
226
|
+
* */
|
|
227
|
+
async getEvent(eventId, options) {
|
|
228
|
+
if (!eventId) {
|
|
229
|
+
throw new TypeError('eventId is not set');
|
|
230
|
+
}
|
|
231
|
+
return this.callApi({
|
|
232
|
+
path: '/events/{event_id}',
|
|
233
|
+
pathParams: [eventId],
|
|
234
|
+
method: 'get',
|
|
235
|
+
queryParams: options,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Update an event with a given event ID
|
|
240
|
+
* @description Change information in existing events specified by `eventId` or *flag suspicious events*.
|
|
241
|
+
*
|
|
242
|
+
* When an event is created, it is assigned `linkedId` and `tag` submitted through the JS agent parameters. This information might not be available on the client so the Server API allows for updating the attributes after the fact.
|
|
243
|
+
*
|
|
244
|
+
* **Warning** It's not possible to update events older than one month.
|
|
245
|
+
*
|
|
246
|
+
* @param body - Data to update the event with.
|
|
247
|
+
* @param eventId The unique event [identifier](https://docs.fingerprint.com/reference/js-agent-v4-get-function#event_id).
|
|
248
|
+
*
|
|
249
|
+
* @return {Promise<void>}
|
|
250
|
+
*
|
|
251
|
+
* @example
|
|
252
|
+
* ```javascript
|
|
253
|
+
* const body = {
|
|
254
|
+
* linked_id: 'linked_id',
|
|
255
|
+
* suspect: false,
|
|
256
|
+
* }
|
|
257
|
+
*
|
|
258
|
+
* client
|
|
259
|
+
* .updateEvent(body, '<eventId>')
|
|
260
|
+
* .then(() => {
|
|
261
|
+
* // Event was successfully updated
|
|
262
|
+
* })
|
|
263
|
+
* .catch((error) => {
|
|
264
|
+
* if (error instanceof RequestError) {
|
|
265
|
+
* console.log(error.statusCode, error.message)
|
|
266
|
+
* // Access raw response in error
|
|
267
|
+
* console.log(error.response)
|
|
268
|
+
*
|
|
269
|
+
* if(error.statusCode === 409) {
|
|
270
|
+
* // Event is not mutable yet, wait a couple of seconds and retry the update.
|
|
271
|
+
* }
|
|
272
|
+
* }
|
|
273
|
+
* })
|
|
274
|
+
* ```
|
|
275
|
+
*/
|
|
276
|
+
async updateEvent(body, eventId) {
|
|
277
|
+
if (!body) {
|
|
278
|
+
throw new TypeError('body is not set');
|
|
279
|
+
}
|
|
280
|
+
if (!eventId) {
|
|
281
|
+
throw new TypeError('eventId is not set');
|
|
282
|
+
}
|
|
283
|
+
return this.callApi({
|
|
284
|
+
path: '/events/{event_id}',
|
|
285
|
+
pathParams: [eventId],
|
|
286
|
+
method: 'patch',
|
|
287
|
+
body: JSON.stringify(body),
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Delete data by visitor ID
|
|
292
|
+
* Request deleting all data associated with the specified visitor ID. This API is useful for compliance with privacy regulations. All delete requests are queued:
|
|
293
|
+
* Recent data (10 days or newer) belonging to the specified visitor will be deleted within 24 hours. * Data from older (11 days or more) identification events will be deleted after 90 days.
|
|
294
|
+
* If you are interested in using this API, please [contact our support team](https://fingerprint.com/support/) to activate it for you. Otherwise, you will receive a 403.
|
|
295
|
+
*
|
|
296
|
+
* @param visitorId The [visitor ID](https://dev.fingerprint.com/docs/js-agent#visitorid) you want to delete.*
|
|
297
|
+
*
|
|
298
|
+
* @return {Promise<void>} Promise that resolves when the deletion request is successfully queued
|
|
299
|
+
*
|
|
300
|
+
* @example
|
|
301
|
+
* ```javascript
|
|
302
|
+
* client
|
|
303
|
+
* .deleteVisitorData('<visitorId>')
|
|
304
|
+
* .then(() => {
|
|
305
|
+
* // Data deletion request was successfully queued
|
|
306
|
+
* })
|
|
307
|
+
* .catch((error) => {
|
|
308
|
+
* if (error instanceof RequestError) {
|
|
309
|
+
* console.log(error.statusCode, error.message)
|
|
310
|
+
* // Access raw response in error
|
|
311
|
+
* console.log(error.response)
|
|
312
|
+
* }
|
|
313
|
+
* })
|
|
314
|
+
* ```
|
|
315
|
+
*/
|
|
316
|
+
async deleteVisitorData(visitorId) {
|
|
317
|
+
if (!visitorId) {
|
|
318
|
+
throw new TypeError('visitorId is not set');
|
|
319
|
+
}
|
|
320
|
+
return this.callApi({
|
|
321
|
+
path: '/visitors/{visitor_id}',
|
|
322
|
+
pathParams: [visitorId],
|
|
323
|
+
method: 'delete',
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Search for identification events, including Smart Signals, using
|
|
328
|
+
* multiple filtering criteria. If you don't provide `start` or `end`
|
|
329
|
+
* parameters, the default search range is the last 7 days.
|
|
330
|
+
*
|
|
331
|
+
* Please note that events include mobile signals (e.g. `rootApps`) even if
|
|
332
|
+
* the request originated from a non-mobile platform. We recommend you
|
|
333
|
+
* **ignore** mobile signals for such requests.
|
|
334
|
+
*
|
|
335
|
+
* @param {SearchEventsFilter} filter - Events filter
|
|
336
|
+
* @param {number} filter.limit - Limit the number of events returned. Must be greater than 0.
|
|
337
|
+
* @param {string|undefined} filter.pagination_key - Use `pagination_key` to get the next page of results.
|
|
338
|
+
* @param {string|undefined} filter.visitor_id - Unique [visitor identifier](https://dev.fingerprint.com/reference/get-function#visitorid) issued by Fingerprint Identification. Filter for events matching this `visitor_id`.
|
|
339
|
+
* @param {string|undefined} filter.bot - Filter events by the bot detection result, specifically:
|
|
340
|
+
* - events where any kind of bot was detected.
|
|
341
|
+
* - events where a good bot was detected.
|
|
342
|
+
* - events where a bad bot was detected.
|
|
343
|
+
* - events where no bot was detected.
|
|
344
|
+
*
|
|
345
|
+
* Allowed values: `all`, `good`, `bad`, `none`.
|
|
346
|
+
* @param {string|undefined} filter.ip_address - Filter events by IP address range. The range can be as specific as a
|
|
347
|
+
* single IP (/32 for IPv4 or /128 for IPv6).
|
|
348
|
+
* All ip_address filters must use CIDR notation, for example,
|
|
349
|
+
* 10.0.0.0/24, 192.168.0.1/32
|
|
350
|
+
* @param {string|undefined} filter.linked_id - Filter events by your custom identifier.
|
|
351
|
+
* You can use [linked IDs](https://dev.fingerprint.com/reference/get-function#linkedid) to
|
|
352
|
+
* associate identification requests with your own identifier, for
|
|
353
|
+
* example, session ID, purchase ID, or transaction ID. You can then
|
|
354
|
+
* use this `linked_id` parameter to retrieve all events associated
|
|
355
|
+
* with your custom identifier.
|
|
356
|
+
* @param {string|undefined} filter.url - Filter events by the URL (`url` property) associated with the event.
|
|
357
|
+
* @param {string|undefined} filter.origin - Filter events by the origin field of the event. Origin could be the website domain or mobile app bundle ID (eg: com.foo.bar)
|
|
358
|
+
* @param {number|undefined} filter.start - Filter events with a timestamp greater than the start time, in Unix time (milliseconds).
|
|
359
|
+
* @param {number|undefined} filter.end - Filter events with a timestamp smaller than the end time, in Unix time (milliseconds).
|
|
360
|
+
* @param {boolean|undefined} filter.reverse - Sort events in reverse timestamp order.
|
|
361
|
+
* @param {boolean|undefined} filter.suspect - Filter events previously tagged as suspicious via the [Update API](https://dev.fingerprint.com/reference/updateevent).
|
|
362
|
+
* @param {boolean|undefined} filter.vpn - Filter events by VPN Detection result.
|
|
363
|
+
* @param {boolean|undefined} filter.virtual_machine - Filter events by Virtual Machine Detection result.
|
|
364
|
+
* @param {boolean|undefined} filter.tampering - Filter events by Browser Tampering Detection result.
|
|
365
|
+
* @param {boolean|undefined} filter.anti_detect_browser - Filter events by Anti-detect Browser Detection result.
|
|
366
|
+
* @param {boolean|undefined} filter.incognito - Filter events by Browser Incognito Detection result.
|
|
367
|
+
* @param {boolean|undefined} filter.privacy_settings - Filter events by Privacy Settings Detection result.
|
|
368
|
+
* @param {boolean|undefined} filter.jailbroken - Filter events by Jailbroken Device Detection result.
|
|
369
|
+
* @param {boolean|undefined} filter.frida - Filter events by Frida Detection result.
|
|
370
|
+
* @param {boolean|undefined} filter.factory_reset - Filter events by Factory Reset Detection result.
|
|
371
|
+
* @param {boolean|undefined} filter.cloned_app - Filter events by Cloned App Detection result.
|
|
372
|
+
* @param {boolean|undefined} filter.emulator - Filter events by Android Emulator Detection result.
|
|
373
|
+
* @param {boolean|undefined} filter.root_apps - Filter events by Rooted Device Detection result.
|
|
374
|
+
* @param {'high'|'medium'|'low'|undefined} filter.vpn_confidence - Filter events by VPN Detection result confidence level.
|
|
375
|
+
* @param {number|undefined} filter.min_suspect_score - Filter events with Suspect Score result above a provided minimum threshold.
|
|
376
|
+
* @param {boolean|undefined} filter.developer_tools - Filter events by Developer Tools detection result.
|
|
377
|
+
* @param {boolean|undefined} filter.location_spoofing - Filter events by Location Spoofing detection result.
|
|
378
|
+
* @param {boolean|undefined} filter.mitm_attack - Filter events by MITM (Man-in-the-Middle) Attack detection result.
|
|
379
|
+
* @param {boolean|undefined} filter.proxy - Filter events by Proxy detection result.
|
|
380
|
+
* @param {string|undefined} filter.sdk_version - Filter events by a specific SDK version associated with the identification event (`sdk.version` property).
|
|
381
|
+
* @param {string|undefined} filter.sdk_platform - Filter events by the SDK Platform associated with the identification event (`sdk.platform` property).
|
|
382
|
+
* @param {string[]|undefined} filter.environment - Filter for events by providing one or more environment IDs (`environment_id` property).
|
|
383
|
+
* */
|
|
384
|
+
async searchEvents(filter) {
|
|
385
|
+
return this.callApi({
|
|
386
|
+
path: '/events',
|
|
387
|
+
method: 'get',
|
|
388
|
+
queryParams: filter,
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
async callApi(options) {
|
|
392
|
+
const url = getRequestPath({
|
|
393
|
+
...options,
|
|
394
|
+
region: this.region,
|
|
395
|
+
});
|
|
396
|
+
let response;
|
|
397
|
+
try {
|
|
398
|
+
response = await this.fetch(url, {
|
|
399
|
+
method: options.method.toUpperCase(),
|
|
400
|
+
headers: {
|
|
401
|
+
...this.defaultHeaders,
|
|
402
|
+
...options.headers,
|
|
403
|
+
},
|
|
404
|
+
body: options.body,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
catch (e) {
|
|
408
|
+
throw new SdkError('Network or fetch error', undefined, e);
|
|
409
|
+
}
|
|
410
|
+
const contentType = response.headers.get('content-type') ?? '';
|
|
411
|
+
const isJson = contentType.includes('application/json');
|
|
412
|
+
if (response.ok) {
|
|
413
|
+
const hasNoBody = response.status === 204 || response.headers.get('content-length') === '0';
|
|
414
|
+
if (hasNoBody) {
|
|
415
|
+
return undefined;
|
|
416
|
+
}
|
|
417
|
+
if (!isJson) {
|
|
418
|
+
throw new SdkError('Expected JSON response but received non-JSON content type', response);
|
|
419
|
+
}
|
|
420
|
+
let data;
|
|
421
|
+
try {
|
|
422
|
+
data = await response.clone().json();
|
|
423
|
+
}
|
|
424
|
+
catch (e) {
|
|
425
|
+
throw new SdkError('Failed to parse JSON response', response, toError(e));
|
|
426
|
+
}
|
|
427
|
+
return data;
|
|
428
|
+
}
|
|
429
|
+
let errPayload;
|
|
430
|
+
try {
|
|
431
|
+
errPayload = await response.clone().json();
|
|
432
|
+
}
|
|
433
|
+
catch (e) {
|
|
434
|
+
throw new SdkError('Failed to parse JSON response', response, toError(e));
|
|
435
|
+
}
|
|
436
|
+
if (isErrorResponse(errPayload)) {
|
|
437
|
+
if (response.status === 429) {
|
|
438
|
+
throw new TooManyRequestsError(errPayload, response);
|
|
439
|
+
}
|
|
440
|
+
throw new RequestError(errPayload.error.message, errPayload, response.status, errPayload.error.code, response);
|
|
441
|
+
}
|
|
442
|
+
throw RequestError.unknown(response);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
class UnsealError extends Error {
|
|
447
|
+
key;
|
|
448
|
+
error;
|
|
449
|
+
constructor(key, error) {
|
|
450
|
+
let msg = `Unable to decrypt sealed data`;
|
|
451
|
+
if (error) {
|
|
452
|
+
msg = msg.concat(`: ${error.message}`);
|
|
453
|
+
}
|
|
454
|
+
super(msg);
|
|
455
|
+
this.key = key;
|
|
456
|
+
this.error = error;
|
|
457
|
+
this.name = 'UnsealError';
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
class UnsealAggregateError extends Error {
|
|
461
|
+
errors;
|
|
462
|
+
constructor(errors) {
|
|
463
|
+
super('Unable to decrypt sealed data');
|
|
464
|
+
this.errors = errors;
|
|
465
|
+
this.name = 'UnsealAggregateError';
|
|
466
|
+
}
|
|
467
|
+
addError(error) {
|
|
468
|
+
this.errors.push(error);
|
|
469
|
+
}
|
|
470
|
+
toString() {
|
|
471
|
+
return this.errors.map((e) => e.toString()).join('\n');
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const asyncInflateRaw = util.promisify(zlib.inflateRaw);
|
|
476
|
+
exports.DecryptionAlgorithm = void 0;
|
|
477
|
+
(function (DecryptionAlgorithm) {
|
|
478
|
+
DecryptionAlgorithm["Aes256Gcm"] = "aes-256-gcm";
|
|
479
|
+
})(exports.DecryptionAlgorithm || (exports.DecryptionAlgorithm = {}));
|
|
480
|
+
const SEALED_HEADER = buffer.Buffer.from([0x9e, 0x85, 0xdc, 0xed]);
|
|
481
|
+
function isEventResponse(data) {
|
|
482
|
+
return Boolean(data && typeof data === 'object' && 'event_id' in data && 'timestamp' in data);
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* @private
|
|
486
|
+
* */
|
|
487
|
+
function parseEventsResponse(unsealed) {
|
|
488
|
+
const json = JSON.parse(unsealed);
|
|
489
|
+
if (!isEventResponse(json)) {
|
|
490
|
+
throw new Error('Sealed data is not valid events response');
|
|
491
|
+
}
|
|
492
|
+
return json;
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Decrypts the sealed response with the provided keys.
|
|
496
|
+
* The SDK will try to decrypt the result with each key until it succeeds.
|
|
497
|
+
* To learn more about sealed results visit: https://dev.fingerprint.com/docs/sealed-client-results
|
|
498
|
+
* @throws UnsealAggregateError
|
|
499
|
+
* @throws Error
|
|
500
|
+
*/
|
|
501
|
+
async function unsealEventsResponse(sealedData, decryptionKeys) {
|
|
502
|
+
const unsealed = await unseal(sealedData, decryptionKeys);
|
|
503
|
+
return parseEventsResponse(unsealed);
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* @private
|
|
507
|
+
* */
|
|
508
|
+
async function unseal(sealedData, decryptionKeys) {
|
|
509
|
+
if (sealedData.subarray(0, SEALED_HEADER.length).toString('hex') !== SEALED_HEADER.toString('hex')) {
|
|
510
|
+
throw new Error('Invalid sealed data header');
|
|
511
|
+
}
|
|
512
|
+
const errors = new UnsealAggregateError([]);
|
|
513
|
+
for (const decryptionKey of decryptionKeys) {
|
|
514
|
+
switch (decryptionKey.algorithm) {
|
|
515
|
+
case exports.DecryptionAlgorithm.Aes256Gcm:
|
|
516
|
+
try {
|
|
517
|
+
return await unsealAes256Gcm(sealedData, decryptionKey.key);
|
|
518
|
+
}
|
|
519
|
+
catch (e) {
|
|
520
|
+
errors.addError(new UnsealError(decryptionKey, e));
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
default:
|
|
524
|
+
throw new Error(`Unsupported decryption algorithm: ${decryptionKey.algorithm}`);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
throw errors;
|
|
528
|
+
}
|
|
529
|
+
async function unsealAes256Gcm(sealedData, decryptionKey) {
|
|
530
|
+
const nonceLength = 12;
|
|
531
|
+
const nonce = sealedData.subarray(SEALED_HEADER.length, SEALED_HEADER.length + nonceLength);
|
|
532
|
+
const authTag = sealedData.subarray(-16);
|
|
533
|
+
const ciphertext = sealedData.subarray(SEALED_HEADER.length + nonceLength, -16);
|
|
534
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', decryptionKey, nonce).setAuthTag(authTag);
|
|
535
|
+
const compressed = buffer.Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
536
|
+
const payload = await asyncInflateRaw(compressed);
|
|
537
|
+
return payload.toString();
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function isValidHmacSignature(signature, data, secret) {
|
|
541
|
+
return signature === crypto.createHmac('sha256', secret).update(data).digest('hex');
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Verifies the HMAC signature extracted from the "fpjs-event-signature" header of the incoming request. This is a part of the webhook signing process, which is available only for enterprise customers.
|
|
545
|
+
* If you wish to enable it, please contact our support: https://fingerprint.com/support
|
|
546
|
+
*
|
|
547
|
+
* @param {IsValidWebhookSignatureParams} params
|
|
548
|
+
* @param {string} params.header - The value of the "fpjs-event-signature" header.
|
|
549
|
+
* @param {Buffer} params.data - The raw data of the incoming request.
|
|
550
|
+
* @param {string} params.secret - The secret key used to sign the request.
|
|
551
|
+
*
|
|
552
|
+
* @return {boolean} true if the signature is valid, false otherwise.
|
|
553
|
+
*
|
|
554
|
+
* @example
|
|
555
|
+
* ```javascript
|
|
556
|
+
* // Webhook endpoint handler
|
|
557
|
+
* export async function POST(request: Request) {
|
|
558
|
+
* try {
|
|
559
|
+
* const secret = process.env.WEBHOOK_SIGNATURE_SECRET;
|
|
560
|
+
* const header = request.headers.get("fpjs-event-signature");
|
|
561
|
+
* const data = Buffer.from(await request.arrayBuffer());
|
|
562
|
+
*
|
|
563
|
+
* if (!isValidWebhookSignature({ header, data, secret })) {
|
|
564
|
+
* return Response.json(
|
|
565
|
+
* { message: "Webhook signature is invalid." },
|
|
566
|
+
* { status: 403 },
|
|
567
|
+
* );
|
|
568
|
+
* }
|
|
569
|
+
*
|
|
570
|
+
* return Response.json({ message: "Webhook received." });
|
|
571
|
+
* } catch (error) {
|
|
572
|
+
* return Response.json({ error }, { status: 500 });
|
|
573
|
+
* }
|
|
574
|
+
* }
|
|
575
|
+
* ```
|
|
576
|
+
*/
|
|
577
|
+
function isValidWebhookSignature(params) {
|
|
578
|
+
const { header, data, secret } = params;
|
|
579
|
+
const signatures = header.split(',');
|
|
580
|
+
for (const signature of signatures) {
|
|
581
|
+
const [version, hash] = signature.split('=');
|
|
582
|
+
if (version === 'v1' && isValidHmacSignature(hash, data, secret)) {
|
|
583
|
+
return true;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return false;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
exports.FingerprintServerApiClient = FingerprintServerApiClient;
|
|
590
|
+
exports.RequestError = RequestError;
|
|
591
|
+
exports.SdkError = SdkError;
|
|
592
|
+
exports.TooManyRequestsError = TooManyRequestsError;
|
|
593
|
+
exports.UnsealAggregateError = UnsealAggregateError;
|
|
594
|
+
exports.UnsealError = UnsealError;
|
|
595
|
+
exports.isValidWebhookSignature = isValidWebhookSignature;
|
|
596
|
+
exports.parseEventsResponse = parseEventsResponse;
|
|
597
|
+
exports.unseal = unseal;
|
|
598
|
+
exports.unsealEventsResponse = unsealEventsResponse;
|