diff --git a/.changeset/event-discriminated-union.md b/.changeset/event-discriminated-union.md new file mode 100644 index 00000000..fa5de33f --- /dev/null +++ b/.changeset/event-discriminated-union.md @@ -0,0 +1,16 @@ +--- +'@fingerprint/node-sdk': minor +--- + +**types**: ⚠️ Type-breaking change in generated TypeScript types for OpenAPI v3.11.0. No runtime change. + +- `Event` is now a union of `EventDevice` and `EventEdge`, discriminated by `source`. Both are exported. Edge events ([Automation Intelligence API](https://docs.fingerprint.com/reference/automation-intelligence-api)) have no Identification, no `rule_action`, and none of the Smart Signals that need device data. They still have IP, proxy, VPN and bot detection. +- Code that reads device-only fields such as `event.identification` or `event.rule_action` no longer compiles. Check `source` first: + + ```ts + if (event.source === 'device') { + console.log(event.rule_action?.type) + } + ``` + +- `source` is now required on `Event`. Objects typed as `Event` without `source` (for example, test fixtures) no longer compile. For webhook bodies, use the new `Webhook` type. diff --git a/.changeset/event-simulator-browser.md b/.changeset/event-simulator-browser.md new file mode 100644 index 00000000..dfe527a3 --- /dev/null +++ b/.changeset/event-simulator-browser.md @@ -0,0 +1,5 @@ +--- +'@fingerprint/node-sdk': minor +--- + +**events**: `simulator` also flags Safari running inside the iOS Simulator, not only the native iOS SDK diff --git a/.changeset/webhook-type.md b/.changeset/webhook-type.md new file mode 100644 index 00000000..4b06dc23 --- /dev/null +++ b/.changeset/webhook-type.md @@ -0,0 +1,5 @@ +--- +'@fingerprint/node-sdk': minor +--- + +**webhooks**: Add `Webhook` type for webhook bodies. Same as `Event`, but `source` is optional on device events, because webhooks stored before `source` existed don't have it. diff --git a/.schema-version b/.schema-version index aef07c2c..ede94c1b 100644 --- a/.schema-version +++ b/.schema-version @@ -1 +1 @@ -v3.10.0 \ No newline at end of file +v3.11.0 \ No newline at end of file diff --git a/example/getEvent.mjs b/example/getEvent.mjs index 0500d26b..7e531369 100644 --- a/example/getEvent.mjs +++ b/example/getEvent.mjs @@ -32,7 +32,8 @@ try { const event = await client.getEvent(eventId, { ruleset_id: rulesetId }) console.log(JSON.stringify(event, null, 2)) - if (rulesetId && event.rule_action) { + // Only device events have a rule action. + if (rulesetId && event.source === 'device' && event.rule_action) { const { type, ruleset_id, rule_id, rule_expression } = event.rule_action console.log(`Rule action: ${type} (ruleset: ${ruleset_id}, rule: ${rule_id}, expression: ${rule_expression})`) diff --git a/readme.md b/readme.md index a1ee6888..68dbb1d5 100644 --- a/readme.md +++ b/readme.md @@ -97,7 +97,10 @@ client.getEvent('').then((event) => { // Get an event with a ruleset evaluation client.getEvent('', { ruleset_id: '' }).then((event) => { - console.log(event.rule_action?.type) // 'allow' or 'block' + // Only device events have Identification and a rule action, edge events (Automation Intelligence API) don't. + if (event.source === 'device') { + console.log(event.rule_action?.type) // 'allow' or 'block' + } }) // Search for identification events @@ -151,12 +154,18 @@ Other `SdkError`s: #### Webhook types -When handling [Webhooks](https://dev.fingerprint.com/reference/posteventwebhook#/) coming from Fingerprint, you can cast the payload as the built-in `Event` type: +When handling [Webhooks](https://docs.fingerprint.com/reference/posteventwebhook) coming from Fingerprint, you can cast the payload as the built-in `Webhook` type: ```ts -import { Event } from '@fingerprint/node-sdk' +import { Webhook } from '@fingerprint/node-sdk' + +const webhook = eventWebhookBody as unknown as Webhook -const event = eventWebhookBody as unknown as Event +// Edge events (Automation Intelligence API) have no Identification. +// Bodies stored before `source` was added have no `source`; they are device events. +if (webhook.source !== 'edge') { + console.log(webhook.identification?.visitor_id) +} ``` #### Webhook signature validation diff --git a/resources/fingerprint-server-api.yaml b/resources/fingerprint-server-api.yaml index 5e7f0816..ac4adb7c 100644 --- a/resources/fingerprint-server-api.yaml +++ b/resources/fingerprint-server-api.yaml @@ -943,7 +943,8 @@ paths: schema: type: boolean description: > - Filter events by iOS Simulator Detection result. + Filter events by the Simulator Detection result (native iOS SDK and + Safari on iOS). > Note: When using this parameter, only events with the `simulator` @@ -1212,6 +1213,11 @@ components: enum: - device - edge + EnvironmentId: + type: string + examples: + - ae_47abaca3db2c7c43 + description: Environment ID of the event. Url: type: string examples: @@ -1619,6 +1625,55 @@ components: description: > `true` if the request came from a device running a VPN, `false` otherwise. + EventEdge: + type: object + description: >- + An event generated by the Automation Intelligence API (`source` is + `edge`), containing IP and bot analysis for a request intercepted at the + edge. No client-side agent is involved, so Identification (`visitor_id`) + and Smart Signals derived from device telemetry are not available. + `ip_info` is always present, but is empty when no IP intelligence is + available for the request. `environment_id` is only included in + webhooks, when the `/edge` request was authenticated with an + environment-scoped secret API key. API responses (`POST /v4/edge`, `GET + /v4/events`) never include it. + required: + - event_id + - timestamp + - source + - ip_info + properties: + event_id: + $ref: '#/components/schemas/EventId' + timestamp: + $ref: '#/components/schemas/Timestamp' + source: + $ref: '#/components/schemas/EventSource' + const: edge + linked_id: + $ref: '#/components/schemas/LinkedId' + environment_id: + $ref: '#/components/schemas/EnvironmentId' + tags: + $ref: '#/components/schemas/Tags' + url: + $ref: '#/components/schemas/Url' + bot_info: + $ref: '#/components/schemas/BotInfo' + ip_info: + $ref: '#/components/schemas/IPInfo' + proxy: + $ref: '#/components/schemas/Proxy' + proxy_confidence: + $ref: '#/components/schemas/ProxyConfidence' + proxy_details: + $ref: '#/components/schemas/ProxyDetails' + vpn: + $ref: '#/components/schemas/Vpn' + vpn_confidence: + $ref: '#/components/schemas/VpnConfidence' + vpn_methods: + $ref: '#/components/schemas/VpnMethods' ErrorCode: type: string enum: @@ -1728,11 +1783,6 @@ components: enum: - partially_completed - completed - EnvironmentId: - type: string - examples: - - ae_47abaca3db2c7c43 - description: Environment ID of the event. Suspect: type: boolean description: >- @@ -2378,10 +2428,14 @@ components: block: '#/components/schemas/EventRuleActionBlock' Simulator: type: boolean - description: | - iOS specific simulator detection. There are 2 values: + description: > + Flags requests coming from an iOS Simulator. Covers the native iOS SDK + and Safari running inside the iOS Simulator. There are 2 values: + * `true` - Simulator environment detected. - * `false` - No signs of simulator or the client is not iOS. + + * `false` - No signs of a simulator, or the request does not come from + iOS (native iOS SDK or Safari on iOS). SuspectScore: type: integer examples: @@ -3159,18 +3213,21 @@ components: case. This field is in the beta phase and only available to select customers. If you are interested, please [contact our support team](https://fingerprint.com/support/). - Event: + EventDevice: type: object description: >- - Contains results from Fingerprint Identification and all active Smart - Signals. Some Smart Signals are only supported for certain device types, - these fields will be omitted for events not generated from the supported - devices. Consult the [Smart Signals + An event generated by the JS agent or a mobile SDK running on an + end-user device (`source` is `device`). Contains results from + Fingerprint Identification and all active Smart Signals. Some Smart + Signals are only supported for certain device types, these fields will + be omitted for events not generated from the supported devices. Consult + the [Smart Signals reference](https://docs.fingerprint.com/docs/smart-signals-reference) for more details. required: - event_id - timestamp + - source properties: event_id: $ref: '#/components/schemas/EventId' @@ -3186,6 +3243,7 @@ components: - browser source: $ref: '#/components/schemas/EventSource' + const: device x-platforms: - android - ios @@ -3414,6 +3472,7 @@ components: $ref: '#/components/schemas/Simulator' x-platforms: - ios + - browser suspect_score: $ref: '#/components/schemas/SuspectScore' x-platforms: @@ -3518,6 +3577,40 @@ components: - browser - ios - android + Event: + type: object + description: > + A Device Intelligence or Automation Intelligence event. Check `source` + first, because it determines which properties the event can contain. + + + Both sources can contain: + + - Request metadata like `event_id`, `timestamp`, `source`, `linked_id`, + `environment_id`, `tags`, `url`. + + - IP and bot analysis fields like `ip_info`, `bot_info`, `proxy`, `vpn`. + + + Sources: + + - `device` - generated by the Fingerprint JavaScript agent or a mobile + SDK running on an end-user device. Also contains Identification + (`visitor_id`) and Smart Signals derived from device telemetry. See + `EventDevice`. + + - `edge` - generated by the Automation Intelligence API (`/edge` + endpoint) for a request intercepted at the edge. Contains only the + properties above. See `EventEdge`. + required: [] + oneOf: + - $ref: '#/components/schemas/EventDevice' + - $ref: '#/components/schemas/EventEdge' + discriminator: + propertyName: source + mapping: + device: '#/components/schemas/EventDevice' + edge: '#/components/schemas/EventEdge' EventUpdate: type: object required: [] diff --git a/src/generatedApiTypes.ts b/src/generatedApiTypes.ts index a8fbc211..1b0de959 100644 --- a/src/generatedApiTypes.ts +++ b/src/generatedApiTypes.ts @@ -157,6 +157,11 @@ export interface components { * @enum {string} */ EventSource: 'device' | 'edge' + /** + * @description Environment ID of the event. + * @example ae_47abaca3db2c7c43 + */ + EnvironmentId: string /** * @description Page URL from which the request was sent. * @example https://www.example.com/login @@ -421,6 +426,41 @@ export interface components { /** @description `true` if the request came from a device running a VPN, `false` otherwise. */ ml_prediction?: boolean } + /** @description An event generated by the Automation Intelligence API (`source` is `edge`), containing IP and bot analysis for a request intercepted at the edge. No client-side agent is involved, so Identification (`visitor_id`) and Smart Signals derived from device telemetry are not available. `ip_info` is always present, but is empty when no IP intelligence is available for the request. `environment_id` is only included in webhooks, when the `/edge` request was authenticated with an environment-scoped secret API key. API responses (`POST /v4/edge`, `GET /v4/events`) never include it. */ + EventEdge: { + /** @description Unique identifier of the user's request. The first portion of the event_id is a unix epoch milliseconds timestamp. */ + event_id: components['schemas']['EventId'] + /** @description Timestamp of the event with millisecond precision in Unix time. */ + timestamp: components['schemas']['Timestamp'] + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + source: 'edge' + /** @description A customer-provided ID that was sent with the request. */ + linked_id?: components['schemas']['LinkedId'] + /** @description Environment ID of the event. */ + environment_id?: components['schemas']['EnvironmentId'] + /** @description A customer-provided value or an object that was sent with the identification request or updated later. */ + tags?: components['schemas']['Tags'] + /** @description Page URL from which the request was sent. */ + url?: components['schemas']['Url'] + /** @description Extended bot information. */ + bot_info?: components['schemas']['BotInfo'] + /** @description Details about the request IP address. Has separate fields for v4 and v6 IP address versions. */ + ip_info: components['schemas']['IPInfo'] + /** @description IP address was used by a public proxy provider or belonged to a known recent residential proxy */ + proxy?: components['schemas']['Proxy'] + /** @description Confidence level of the proxy detection. If a proxy is not detected, confidence is "high". If it's detected, can be "low", "medium", or "high". */ + proxy_confidence?: components['schemas']['ProxyConfidence'] + /** @description Proxy detection details (present if `proxy` is `true`) */ + proxy_details?: components['schemas']['ProxyDetails'] + /** @description VPN or other anonymizing service has been used when sending the request. */ + vpn?: components['schemas']['Vpn'] + /** @description A confidence rating for the VPN detection result — "low", "medium", or "high". Depends on the combination of results returned from all VPN detection methods. */ + vpn_confidence?: components['schemas']['VpnConfidence'] + vpn_methods?: components['schemas']['VpnMethods'] + } /** * @description Error code: * * `request_cannot_be_parsed` - The query parameters or JSON payload contains some errors @@ -508,11 +548,6 @@ export interface components { * @enum {string} */ IncrementalIdentificationStatus: 'partially_completed' | 'completed' - /** - * @description Environment ID of the event. - * @example ae_47abaca3db2c7c43 - */ - EnvironmentId: string /** @description Field is `true` if you have previously set the `suspect` flag for this event using the [Server API Update event endpoint](https://docs.fingerprint.com/reference/server-api-update-event). */ Suspect: boolean Integration: { @@ -894,9 +929,9 @@ export interface components { /** @description Describes the action the client should take, according to the rule in the ruleset that matched the event. When getting an event by event ID, the rule_action will only be included when the ruleset_id query parameter is specified. */ EventRuleAction: components['schemas']['EventRuleActionAllow'] | components['schemas']['EventRuleActionBlock'] /** - * @description iOS specific simulator detection. There are 2 values: + * @description Flags requests coming from an iOS Simulator. Covers the native iOS SDK and Safari running inside the iOS Simulator. There are 2 values: * * `true` - Simulator environment detected. - * * `false` - No signs of simulator or the client is not iOS. + * * `false` - No signs of a simulator, or the request does not come from iOS (native iOS SDK or Safari on iOS). */ Simulator: boolean /** @@ -1416,18 +1451,17 @@ export interface components { */ ml_score?: number }[] - /** @description Contains results from Fingerprint Identification and all active Smart Signals. Some Smart Signals are only supported for certain device types, these fields will be omitted for events not generated from the supported devices. Consult the [Smart Signals reference](https://docs.fingerprint.com/docs/smart-signals-reference) for more details. */ - Event: { + /** @description An event generated by the JS agent or a mobile SDK running on an end-user device (`source` is `device`). Contains results from Fingerprint Identification and all active Smart Signals. Some Smart Signals are only supported for certain device types, these fields will be omitted for events not generated from the supported devices. Consult the [Smart Signals reference](https://docs.fingerprint.com/docs/smart-signals-reference) for more details. */ + EventDevice: { /** @description Unique identifier of the user's request. The first portion of the event_id is a unix epoch milliseconds timestamp. */ event_id: components['schemas']['EventId'] /** @description Timestamp of the event with millisecond precision in Unix time. */ timestamp: components['schemas']['Timestamp'] /** - * @description Identifies how the event was generated. - * - `device` - the event was generated by the JS agent or a mobile SDK running on an end-user device. - * - `edge` - the event was generated by the Automation Intelligence API (`/edge` endpoint), analyzing a request intercepted at the edge. + * @description discriminator enum property added by openapi-typescript + * @enum {string} */ - source?: components['schemas']['EventSource'] + source: 'device' /** * @description Only included for requests using incremental identification. * - `partially_completed` - Indicates this event corresponds to a 'minimal' request. Smart Signals, even if included in your plan, are not computed; hence, their values must be ignored. @@ -1547,9 +1581,9 @@ export interface components { /** @description Describes the action the client should take, according to the rule in the ruleset that matched the event. When getting an event by event ID, the rule_action will only be included when the ruleset_id query parameter is specified. */ rule_action?: components['schemas']['EventRuleAction'] /** - * @description iOS specific simulator detection. There are 2 values: + * @description Flags requests coming from an iOS Simulator. Covers the native iOS SDK and Safari running inside the iOS Simulator. There are 2 values: * * `true` - Simulator environment detected. - * * `false` - No signs of simulator or the client is not iOS. + * * `false` - No signs of a simulator, or the request does not come from iOS (native iOS SDK or Safari on iOS). */ simulator?: components['schemas']['Simulator'] /** @description Suspect Score is an easy way to integrate Smart Signals into your fraud protection work flow. It is a weighted representation of all Smart Signals present in the payload that helps identify suspicious activity. The value range is [0; S] where S is sum of all Smart Signals weights. See more details here: https://docs.fingerprint.com/docs/suspect-score */ @@ -1627,6 +1661,18 @@ export interface components { /** @description Each label returns a prediction (true or false) for a specific use case (label field) based on a machine learning score. The machine learning score is determined by a model trained on customer data for that use case. This field is in the beta phase and only available to select customers. If you are interested, please [contact our support team](https://fingerprint.com/support/). */ labels?: components['schemas']['Labels'] } + /** + * @description A Device Intelligence or Automation Intelligence event. Check `source` first, because it determines which properties the event can contain. + * + * Both sources can contain: + * - Request metadata like `event_id`, `timestamp`, `source`, `linked_id`, `environment_id`, `tags`, `url`. + * - IP and bot analysis fields like `ip_info`, `bot_info`, `proxy`, `vpn`. + * + * Sources: + * - `device` - generated by the Fingerprint JavaScript agent or a mobile SDK running on an end-user device. Also contains Identification (`visitor_id`) and Smart Signals derived from device telemetry. See `EventDevice`. + * - `edge` - generated by the Automation Intelligence API (`/edge` endpoint) for a request intercepted at the edge. Contains only the properties above. See `EventEdge`. + */ + Event: components['schemas']['EventDevice'] | components['schemas']['EventEdge'] EventUpdate: { /** * @description Linked ID value to assign to the existing event @@ -2166,7 +2212,7 @@ export interface operations { /** @description Filter events by their incremental identification status (`incremental_identification_status` property). Non incremental identification events are left out of the response. */ incremental_identification_status?: components['schemas']['SearchEventsIncrementalIdentificationStatus'] /** - * @description Filter events by iOS Simulator Detection result. + * @description Filter events by the Simulator Detection result (native iOS SDK and Safari on iOS). * * > Note: When using this parameter, only events with the `simulator` property set to `true` or `false` are returned. Events without a `simulator` Smart Signal result are left out of the response. */ diff --git a/src/index.ts b/src/index.ts index 2c9f2954..79558aa5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,8 @@ export { ErrorCode, ErrorResponse, Event, + EventDevice, + EventEdge, EventRuleAction, EventUpdate, GetEventOptions, @@ -10,6 +12,7 @@ export { Region, SearchEventsFilter, SearchEventsResponse, + Webhook, } from './types' export * from './sealedResults' export * from './errors/unsealError' diff --git a/src/serverApiClient.ts b/src/serverApiClient.ts index 408e1070..3753d04e 100644 --- a/src/serverApiClient.ts +++ b/src/serverApiClient.ts @@ -79,6 +79,8 @@ export class FingerprintServerApiClient implements FingerprintApi { * client * .getEvent('', { ruleset_id: '' }) * .then((event) => { + * // Only device events have a rule action. + * if (event.source !== 'device') return * const ruleAction = event.rule_action * if (ruleAction?.type === 'block') { * console.log('Blocked by rule:', ruleAction.rule_id, ruleAction.status_code) diff --git a/src/types.ts b/src/types.ts index 41d97723..6fc7ffe9 100644 --- a/src/types.ts +++ b/src/types.ts @@ -50,6 +50,22 @@ export type SearchEventsResponse = components['schemas']['EventSearch'] */ export type Event = components['schemas']['Event'] +/** Event from the JS agent or a mobile SDK (`source` is `device`), with Identification and Smart Signals. */ +export type EventDevice = components['schemas']['EventDevice'] + +/** Event from the Automation Intelligence API (`source` is `edge`), with IP, proxy, VPN and bot detection. */ +export type EventEdge = components['schemas']['EventEdge'] + +/** + * Body of a webhook sent by Fingerprint. + * Same as {@link Event}, except `source` is optional on device events: bodies stored before `source` was added + * don't have it, and resent webhooks deliver the stored body as-is. Check `source === 'edge'`; anything else is a + * device event. + * + * More info: https://docs.fingerprint.com/reference/posteventwebhook + */ +export type Webhook = (Omit & { source?: 'device' }) | EventEdge + export type GetEventOptions = paths['/events/{event_id}']['get']['parameters']['query'] export type EventUpdate = components['schemas']['EventUpdate'] diff --git a/tests/mocked-responses-tests/castWebhookEventTest.spec.ts b/tests/mocked-responses-tests/castWebhookEventTest.spec.ts index 51f786ff..9e38051a 100644 --- a/tests/mocked-responses-tests/castWebhookEventTest.spec.ts +++ b/tests/mocked-responses-tests/castWebhookEventTest.spec.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from 'vitest' -import { Event } from '../../src' +import { Webhook } from '../../src' import eventWebhookBody from './mocked-responses-data/webhook/webhook_event.json' describe('[Mocked body] Cast webhook event', () => { it('with sample request body', () => { - const event = eventWebhookBody as Event + const event = eventWebhookBody as Webhook // Assertion just to use the `event` variable. The goal of this test is to assume that Typescript won't throw an error here. expect(event).toBeTruthy() diff --git a/tests/mocked-responses-tests/getEventTests.spec.ts b/tests/mocked-responses-tests/getEventTests.spec.ts index b05b95af..a5ed1c3b 100644 --- a/tests/mocked-responses-tests/getEventTests.spec.ts +++ b/tests/mocked-responses-tests/getEventTests.spec.ts @@ -1,6 +1,7 @@ import { ServerApiError, ErrorResponse, + EventEdge, FingerprintServerApiClient, Region, RequestError, @@ -8,10 +9,11 @@ import { } from '../../src' import getEventResponse from './mocked-responses-data/events/get_event_200.json' import getEventRulesetResponse from './mocked-responses-data/events/get_event_ruleset_200.json' +import getEventEdgeResponse from './mocked-responses-data/events/get_event_with_edge_200.json' import Error429 from './mocked-responses-data/errors/429_too_many_requests.json' import { createJsonResponse } from './utils' import { getIntegrationInfo } from '../../src/urlUtils' -import { describe, expect, it } from 'vitest' +import { describe, expect, expectTypeOf, it } from 'vitest' import { mockFetch } from './mockFetch' describe('[Mocked response] Get Event', () => { @@ -51,6 +53,18 @@ describe('[Mocked response] Get Event', () => { expect(response).toEqual(getEventRulesetResponse) }) + it('with an edge event', async () => { + mockFetch.mockReturnValue(Promise.resolve(createJsonResponse(getEventEdgeResponse))) + + const response = await client.getEvent(existingEventId) + + expect(response).toEqual(getEventEdgeResponse) + if (response.source !== 'edge') { + throw new Error(`Expected an edge event, got source: ${response.source}`) + } + expectTypeOf(response).toEqualTypeOf() + }) + it('403 error', async () => { const errorInfo = { error: { diff --git a/tests/mocked-responses-tests/mocked-responses-data/events/get_event_200.json b/tests/mocked-responses-tests/mocked-responses-data/events/get_event_200.json index a2456b91..5a0fae32 100644 --- a/tests/mocked-responses-tests/mocked-responses-data/events/get_event_200.json +++ b/tests/mocked-responses-tests/mocked-responses-data/events/get_event_200.json @@ -317,6 +317,11 @@ "label": "fraud", "prediction": false, "ml_score": 0.01 + }, + { + "label": "chargebacks", + "prediction": false, + "ml_score": 0.01 } ], "active_call": false, diff --git a/tests/mocked-responses-tests/mocked-responses-data/events/get_event_ruleset_200.json b/tests/mocked-responses-tests/mocked-responses-data/events/get_event_ruleset_200.json index f2ebfe99..41ce619c 100644 --- a/tests/mocked-responses-tests/mocked-responses-data/events/get_event_ruleset_200.json +++ b/tests/mocked-responses-tests/mocked-responses-data/events/get_event_ruleset_200.json @@ -317,6 +317,11 @@ "label": "fraud", "prediction": false, "ml_score": 0.01 + }, + { + "label": "chargebacks", + "prediction": false, + "ml_score": 0.01 } ], "active_call": false, diff --git a/tests/mocked-responses-tests/mocked-responses-data/events/get_event_with_edge_200.json b/tests/mocked-responses-tests/mocked-responses-data/events/get_event_with_edge_200.json new file mode 100644 index 00000000..387c86eb --- /dev/null +++ b/tests/mocked-responses-tests/mocked-responses-data/events/get_event_with_edge_200.json @@ -0,0 +1,51 @@ +{ + "event_id": "1758130560902.8tRtrH", + "timestamp": 1758130560902, + "source": "edge", + "url": "https://example.com/login?foo=bar", + "bot_info": { + "category": "ai_agent", + "provider": "OpenAI", + "provider_url": "https://openai.com", + "name": "ChatGPT Agent", + "identity": "signed", + "confidence": "high" + }, + "ip_info": { + "v4": { + "address": "104.210.139.192", + "geolocation": { + "accuracy_radius": 20, + "latitude": 29.42412, + "longitude": -98.49363, + "postal_code": "78205", + "timezone": "America/Chicago", + "city_name": "San Antonio", + "country_code": "US", + "country_name": "United States", + "continent_code": "NA", + "continent_name": "North America", + "subdivisions": [ + { + "iso_code": "TX", + "name": "Texas" + } + ] + }, + "asn": "8075", + "asn_name": "Microsoft Corporation", + "asn_network": "104.208.0.0/13", + "asn_type": "hosting", + "datacenter_result": true, + "datacenter_name": "Microsoft Azure" + } + }, + "proxy": false, + "proxy_confidence": "high", + "vpn": false, + "vpn_confidence": "medium", + "vpn_methods": { + "public_vpn": false, + "relay": false + } +} \ No newline at end of file diff --git a/tests/mocked-responses-tests/mocked-responses-data/events/search/get_event_search_200.json b/tests/mocked-responses-tests/mocked-responses-data/events/search/get_event_search_200.json index f746fd86..a84da970 100644 --- a/tests/mocked-responses-tests/mocked-responses-data/events/search/get_event_search_200.json +++ b/tests/mocked-responses-tests/mocked-responses-data/events/search/get_event_search_200.json @@ -319,6 +319,11 @@ "label": "fraud", "prediction": false, "ml_score": 0.01 + }, + { + "label": "chargebacks", + "prediction": false, + "ml_score": 0.01 } ], "active_call": false, diff --git a/tests/mocked-responses-tests/mocked-responses-data/events/search/get_event_search_edge_200.json b/tests/mocked-responses-tests/mocked-responses-data/events/search/get_event_search_edge_200.json new file mode 100644 index 00000000..5a870426 --- /dev/null +++ b/tests/mocked-responses-tests/mocked-responses-data/events/search/get_event_search_edge_200.json @@ -0,0 +1,56 @@ +{ + "events": [ + { + "event_id": "1758130560902.8tRtrH", + "timestamp": 1758130560902, + "source": "edge", + "url": "https://example.com/login?foo=bar", + "bot_info": { + "category": "ai_agent", + "provider": "OpenAI", + "provider_url": "https://openai.com", + "name": "ChatGPT Agent", + "identity": "signed", + "confidence": "high" + }, + "ip_info": { + "v4": { + "address": "104.210.139.192", + "geolocation": { + "accuracy_radius": 20, + "latitude": 29.42412, + "longitude": -98.49363, + "postal_code": "78205", + "timezone": "America/Chicago", + "city_name": "San Antonio", + "country_code": "US", + "country_name": "United States", + "continent_code": "NA", + "continent_name": "North America", + "subdivisions": [ + { + "iso_code": "TX", + "name": "Texas" + } + ] + }, + "asn": "8075", + "asn_name": "Microsoft Corporation", + "asn_network": "104.208.0.0/13", + "asn_type": "hosting", + "datacenter_result": true, + "datacenter_name": "Microsoft Azure" + } + }, + "proxy": false, + "proxy_confidence": "high", + "vpn": false, + "vpn_confidence": "medium", + "vpn_methods": { + "public_vpn": false, + "relay": false + } + } + ], + "pagination_key": "S9rgMMUb4z3X5t5pr_tSgoSZlmyF0O8X7kCV2m981-iY1LmRTjraa1rTk3L-hQExnDWCi0RA-zAIjaVSTNO2AN2eqQWgzT0RjbieMxRfSdkM-HmOhdOgdQvYfPG3vqU1DJKh4Q" +} \ No newline at end of file diff --git a/tests/mocked-responses-tests/mocked-responses-data/webhook/webhook_event.json b/tests/mocked-responses-tests/mocked-responses-data/webhook/webhook_event.json index 35567917..fcbca7ff 100644 --- a/tests/mocked-responses-tests/mocked-responses-data/webhook/webhook_event.json +++ b/tests/mocked-responses-tests/mocked-responses-data/webhook/webhook_event.json @@ -3,6 +3,7 @@ "tags": {}, "timestamp": 1708102555327, "event_id": "1708102555327.NLOjmg", + "source": "device", "url": "https://www.example.com/login?hope{this{works[!", "ip_address": "61.127.217.15", "user_agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) ....", diff --git a/tests/mocked-responses-tests/searchEventsTests.spec.ts b/tests/mocked-responses-tests/searchEventsTests.spec.ts index a1e778b8..67f379a5 100644 --- a/tests/mocked-responses-tests/searchEventsTests.spec.ts +++ b/tests/mocked-responses-tests/searchEventsTests.spec.ts @@ -1,8 +1,9 @@ -import { ServerApiError, ErrorResponse, FingerprintServerApiClient, SearchEventsFilter } from '../../src' +import { ServerApiError, ErrorResponse, EventEdge, FingerprintServerApiClient, SearchEventsFilter } from '../../src' import getEventsSearch from './mocked-responses-data/events/search/get_event_search_200.json' +import getEventsSearchEdge from './mocked-responses-data/events/search/get_event_search_edge_200.json' import { createJsonResponse } from './utils' import { getIntegrationInfo } from '../../src/urlUtils' -import { describe, expect, it } from 'vitest' +import { describe, expect, expectTypeOf, it } from 'vitest' import { mockFetch } from './mockFetch' function expectedSearchEventsUrl(filters: NonNullable): string { @@ -25,6 +26,22 @@ describe('[Mocked response] Search Events', () => { const apiKey = 'dummy_api_key' const client = new FingerprintServerApiClient({ apiKey }) + it('with edge source', async () => { + mockFetch.mockReturnValue(Promise.resolve(createJsonResponse(getEventsSearchEdge))) + + const filter = { source: ['edge'] } satisfies SearchEventsFilter + const response = await client.searchEvents(filter) + + expect(mockFetch).toHaveBeenCalledWith(expectedSearchEventsUrl(filter), { + headers: { Authorization: `Bearer ${apiKey}` }, + method: 'GET', + }) + expect(response).toEqual(getEventsSearchEdge) + const edgeEvents = response.events.filter((event) => event.source === 'edge') + expect(edgeEvents).toHaveLength(response.events.length) + expectTypeOf(edgeEvents).toEqualTypeOf() + }) + it('without filter', async () => { mockFetch.mockReturnValue(Promise.resolve(createJsonResponse(getEventsSearch))) diff --git a/tests/unit-tests/__snapshots__/sealedResults.spec.ts.snap b/tests/unit-tests/__snapshots__/sealedResults.spec.ts.snap index 0b046536..b733f513 100644 --- a/tests/unit-tests/__snapshots__/sealedResults.spec.ts.snap +++ b/tests/unit-tests/__snapshots__/sealedResults.spec.ts.snap @@ -105,6 +105,7 @@ exports[`Unseal event response > unseals sealed data using aes256gcm 1`] = ` "platform": "js", "version": "3.11.10", }, + "source": "device", "supplementary_id_high_recall": { "confidence": { "score": 0.97, diff --git a/tests/unit-tests/eventType.spec.ts b/tests/unit-tests/eventType.spec.ts new file mode 100644 index 00000000..46ec2b5e --- /dev/null +++ b/tests/unit-tests/eventType.spec.ts @@ -0,0 +1,23 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { Event, Webhook } from '../../src' + +// Type-level tests: `pnpm typecheck:tests` fails if these stop compiling. +describe('Webhook type', () => { + it('accepts a device body stored before `source` was added', () => { + const legacy: Webhook = { event_id: '1708102555327.NLOjmg', timestamp: 1708102555327 } + expectTypeOf(legacy).toExtend() + }) + + it("narrows to the device variant on `source !== 'edge'`", () => { + const webhook = {} as Webhook + + if (webhook.source !== 'edge') { + expectTypeOf(webhook.source).toEqualTypeOf<'device' | undefined>() + expectTypeOf(webhook.identification?.visitor_id).toEqualTypeOf() + } + }) + + it('accepts every API event', () => { + expectTypeOf().toExtend() + }) +}) diff --git a/tests/unit-tests/sealedResults.spec.ts b/tests/unit-tests/sealedResults.spec.ts index 8ae8f0bd..0ce10d0d 100644 --- a/tests/unit-tests/sealedResults.spec.ts +++ b/tests/unit-tests/sealedResults.spec.ts @@ -17,7 +17,7 @@ describe('Parse events response', () => { describe('Unseal event response', () => { const sealedData = Buffer.from( - 'noXc7Xu7PIKu1tbMkMxLbQG4XU46Bv5dED98hqTkPYZnmb8PG81Q83Kpg541Vt4NQdkzfezDSVk8FP9ZzJ08L0MMb4S8bT78c10Op1LyKwZU6DGr1e3V+ZWcNzHVG1rPoL+eUHN6yR9MQp8/CmSUBQUPOOAUXdoqWohbfIGxoQIuQ5BtfpSJuYD6kTyswSi56wxzY/s24dMwgS2KnA81Y1pdi3ZVJKBdwGYGg4T5Dvcqu0GWv3sScKD9b4Tagfbe2m8nbXY/QtN770c7J1xo/TNXXdq4lyqaMyqIayHOwRBP58tNF8mACusm1pogOVIt456wIMetCGKxicPJr7m/Q02ONzhkMtzzXwgwriglGHfM7UbtTsCytCBP7J2vp0tEkHiq/X3qtuvSLJqNyRzwFJhgisKGftc5CIaT2VxVKKxkL/6Ws6FPm4sQB1UGtMCMftKpyb1lFzG9lwFkKvYN9+FGtvRM50mbrzz7ONDxbwykkxihAab36MIuk7dfhvnVLFAjr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s70SDW0wvk5B5LgR54BlkAd++CBlgg8fpxNsw9L8BdQqIaqQv4PaEKOcURpRn9ULDtfsW89dCXgcJnesirG22Mn+Ly6MH1f8paX59ZS2n1cPvvMkposgj2cIrfQJUoBlqoSI4Dp0qB7IDk7oD/ggZujTRYhwDrvInQDGSTybanwsfw2F78rSLeE/aKaKfUj2olHg9uD6bfkY+EZR9who+Qlr+PEp2I4qGf2NZFAD5TduQGveo864cYbWBZWoHg5GJ43fLmOwVfW5ZxByGCBseeYid80H05YWI+Etz5YxJfkYHI4oqJ3U4zrEtyWgryvCK6CvStHW820H0C77IE2ZAlh0mHXPUSV0UzoE+GaPLYIMk5TnhlYAd5H9Lg5Ggj01sxNdKRfmx/9hAUp3aOmeZ7N3PZYa07SoRvAkf5IAwVZqbT5i155jMXQ0oicyUvDC7+dHKjckbTCP8WhUadQPd5xRCCPJ7LWOXzNV6N/3zhIRNZ0Y5szQXWp/bTV1BY0lvpYpm1FIC0T2+mhBZeqhZSXPR3yD65lg71fysQlFJvsE9gNAYO82motGxhuUzb/pb9Zdrk/Kwb6N4DnqgryXsb4pj7D9HoIEz6HPkPK0FMx5MNgpAZiz63eU4U8MrxfgCy8iry6NTz2KXdbE8RwM5Ehrw', 'base64' ) const validKey = Buffer.from('p2PA7MGy5tx56cnyJaFZMr96BCFwZeHjZV2EqMvTq53=', 'base64') @@ -35,7 +35,7 @@ describe('Unseal event response', () => { }, ]) - expect(result).toBeTruthy() + expect(result.source).toBe('device') expect(result).toMatchSnapshot() })