@fingerly/web-js 0.2.0 → 0.3.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
@@ -1,20 +1,34 @@
1
- # @fingerly/web-js
1
+ <p align="center">
2
+ <a href="https://fingerly.io">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/logo-dark.svg">
5
+ <img src="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/logo-light.svg" alt="Fingerly" height="44">
6
+ </picture>
7
+ </a>
8
+ </p>
2
9
 
3
- The Fingerly browser SDK. It reads the signals a browser exposes, sends them to
4
- Fingerly, and returns a stable visitor ID with a suspect score, so you can
5
- recognise returning visitors and spot automation, tampering and abuse.
10
+ <p align="center"><b>Fingerly for the browser</b><br>Recognise returning visitors and spot automation, tampering and abuse, with one call from the page.</p>
6
11
 
7
- ```
8
- npm install @fingerly/web-js
9
- ```
12
+ <p align="center">
13
+ <a href="https://www.npmjs.com/package/@fingerly/web-js"><img src="https://img.shields.io/npm/v/@fingerly/web-js?style=flat-square" alt="npm version"></a>
14
+ <a href="https://www.npmjs.com/package/@fingerly/web-js"><img src="https://img.shields.io/npm/dm/@fingerly/web-js?style=flat-square" alt="npm downloads"></a>
15
+ <a href="https://github.com/fingerly-io/sdks/blob/main/client/web/web-js/LICENSE"><img src="https://img.shields.io/npm/l/@fingerly/web-js?style=flat-square" alt="Apache-2.0 licence"></a>
16
+ </p>
17
+
18
+ <p align="center"><img src="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/banner.webp" alt="Fingerly" width="100%"></p>
19
+
20
+ ## What is this
10
21
 
11
- **Not for apps.** Do not embed this SDK in an app's web view (iOS or macOS
12
- `WKWebView`, Android `WebView`, Capacitor, Cordova, Ionic, React Native WebView,
13
- Flutter, Electron). Inside an app it collects nothing and the server matches
14
- nothing; use the Fingerly iOS or Android SDK there. See
15
- [docs/privacy.md §3.3](../../../docs/privacy.md).
22
+ `@fingerly/web-js` is the Fingerly browser SDK (`0.3.0`, wire contract `v: 3`).
23
+ It reads the signals a browser exposes in a single pass (`350 ms` by default),
24
+ sends them to Fingerly in one request, and returns the server's answer: a
25
+ `requestId`, a stable `visitorId`, whether the visitor is `identifiable`, and
26
+ an optional `suspectScore` and `suspectLevel`. With it you can recognise
27
+ returning visitors and spot automation, tampering and abuse.
28
+ [Fingerly](https://fingerly.io) helps you protect signups, logins and payments
29
+ from fraud and abuse.
16
30
 
17
- Using a framework? The bindings wrap this package:
31
+ Using a framework? The `0.3.0` bindings wrap this package and install it for you:
18
32
  [`@fingerly/react`](https://www.npmjs.com/package/@fingerly/react),
19
33
  [`@fingerly/vue`](https://www.npmjs.com/package/@fingerly/vue),
20
34
  [`@fingerly/next`](https://www.npmjs.com/package/@fingerly/next),
@@ -22,33 +36,194 @@ Using a framework? The bindings wrap this package:
22
36
  [`@fingerly/svelte`](https://www.npmjs.com/package/@fingerly/svelte) and
23
37
  [`@fingerly/angular`](https://www.npmjs.com/package/@fingerly/angular).
24
38
 
25
- ## Load once, identify when it matters
39
+ > **Not for apps.** Do not embed this SDK in an app's web view (iOS or macOS
40
+ > `WKWebView`, Android `WebView`, Capacitor, Cordova, Ionic, React Native WebView,
41
+ > Flutter WebView, Electron). Inside an app's web view it runs only checks that
42
+ > identify no one, and the server returns `visitorId: ""`. Use the Fingerly iOS
43
+ > or Android SDK, or the React Native, Flutter or Lynx bridge, there. See
44
+ > section 3.3 of the
45
+ > [privacy notes](https://github.com/fingerly-io/sdks/blob/main/docs/privacy.md).
26
46
 
27
- ```ts
28
- import { load } from '@fingerly/web-js'
47
+ ## Getting started
29
48
 
30
- // A public SDK key from the dashboard. It is scoped to the origins you list,
31
- // which is what makes it safe to ship in the page.
32
- const fingerly = await load({ apiKey: 'fly_pk_production_…' })
49
+ 1. **Get a key.** Create a public SDK key in the dashboard, scoped to the origins
50
+ you list ([how keys work](https://docs.fingerly.io/docs/api-keys), and the
51
+ [quick start](https://docs.fingerly.io/docs/quick-start)).
52
+ 2. **Install.**
33
53
 
34
- // Later, from your consent tool, or pass consent: 'granted' to load() if you
35
- // already have consent or know none is required here (docs/privacy.md §4).
36
- fingerly.setConsent('granted')
54
+ ```sh
55
+ npm install @fingerly/web-js
56
+ # or: pnpm add @fingerly/web-js
57
+ # or: yarn add @fingerly/web-js
58
+ ```
37
59
 
38
- // When the visitor does something worth protecting: sign-up, login, checkout.
39
- const { requestId, visitorId, suspectLevel } = await fingerly.identify({ tag: 'login' })
40
- ```
60
+ 3. **Load once, identify when it matters.**
61
+
62
+ ```ts
63
+ import { load } from '@fingerly/web-js'
64
+
65
+ // A public SDK key from the dashboard. It is scoped to the origins you list,
66
+ // which is what makes it safe to ship in the page.
67
+ const fingerly = await load({ apiKey: 'fly_pk_production_…' })
68
+
69
+ // Later, from your consent tool, or pass consent: 'granted' to load() if you
70
+ // already have consent or know none is required here (see Consent below).
71
+ fingerly.setConsent('granted')
72
+
73
+ // When the visitor does something worth protecting: sign-up, login, checkout.
74
+ // The tag names this action; your backend checks it against the one it expects.
75
+ const { requestId } = await fingerly.identify({ tag: `login:${loginAttemptId}` })
76
+ ```
77
+
78
+ 4. **Decide on your backend.** Forward the request ID with the action, and let
79
+ your backend verify it and decide (see
80
+ [Decide on your backend](#decide-on-your-backend)):
81
+
82
+ ```ts
83
+ const { decision } = await (
84
+ await fetch('/api/login', {
85
+ method: 'POST',
86
+ headers: { 'Content-Type': 'application/json' },
87
+ body: JSON.stringify({ email, password, requestId }),
88
+ })
89
+ ).json()
90
+ ```
91
+
92
+ Loading collects nothing and sends nothing. Consent defaults to `'pending'`, and
93
+ `identify()` / `collect()` reject with a `ConsentError` until consent is
94
+ `'granted'`.
95
+
96
+ `identify()` runs one collection pass (`350 ms` default wall-clock budget) and
97
+ posts once to `POST /api/v1/ingest`, with no follow-up requests. Each report
98
+ carries a single-use freshness ticket from the server, so a recorded report
99
+ cannot be replayed. The ticket for the next report comes back with each answer
100
+ and is held in memory only; when none is held, a small ticket request to the
101
+ same path runs in parallel with collection, and if it fails the report is sent
102
+ without a ticket. When the SDK key asks for proof of work, the SDK solves it in
103
+ a Worker (or in short time slices when the page's Content Security Policy
104
+ refuses `blob:` workers) within 1500 ms, starting as soon as the ticket arrives.
41
105
 
42
- Loading collects nothing and sends nothing. Consent defaults to `pending`, and
43
- `identify()` rejects with a `ConsentError` until it is `granted`.
106
+ `visitorId` is `""` and `visitorIsNew` is `false` whenever `identifiable` is
107
+ `false`, when the report came from an app's web view, or when an unmatched web
108
+ report is high-risk.
109
+
110
+ ## Contents
111
+
112
+ - [Reading the answer](#reading-the-answer)
113
+ - [Decide on your backend](#decide-on-your-backend)
114
+ - [Consent](#consent)
115
+ - [Incognito detection](#incognito-detection)
116
+ - [Serve it from your own site](#serve-it-from-your-own-site)
117
+ - [Options](#options)
118
+ - [Errors](#errors)
119
+ - [Content Security Policy](#content-security-policy)
120
+ - [Without a bundler](#without-a-bundler)
121
+ - [TypeScript](#typescript)
122
+ - [Requirements](#requirements)
123
+ - [Documentation](#documentation)
124
+ - [Help](#help)
125
+ - [Licence](#licence)
126
+
127
+ ## Reading the answer
44
128
 
45
129
  This package collects and sends. Everything about the score is decided on the
46
- server, under the weights you set: `suspectLevel` is the band, and it is `null`
47
- when absent (unscored, or hidden by the SDK key), which is not a clean result.
130
+ server, under the weights you set: `suspectLevel` (`'low' | 'medium' | 'high'`)
131
+ is the band, and it and `suspectScore` are `null` when absent (unscored, or
132
+ hidden by `hide_client_score` on the SDK key), which is not a clean result.
133
+ They are a UI hint only: whoever controls the page controls every branch in it,
134
+ so never gate an action on them in the browser.
135
+
48
136
  Send `requestId` to your server and read the signals and the full result there
49
- with a secret key (see the server SDKs), rather than trusting what the page
50
- reports: the page runs code the visitor controls and is not told which signals
51
- fired.
137
+ with a secret key (see the [server SDKs](https://docs.fingerly.io/docs/sdks)),
138
+ rather than trusting what the page reports: the page runs code the visitor
139
+ controls and is not told which signals fired.
140
+
141
+ ## Decide on your backend
142
+
143
+ The `requestId` the page sends is untrusted input until your backend has
144
+ verified it. Read the stored event with a secret key and run the checks
145
+ described in
146
+ [server-side verification](https://docs.fingerly.io/docs/server-side-verification):
147
+
148
+ ```ts
149
+ // server (Node.js), never in the page
150
+ import { BlockList } from 'node:net'
151
+ import { Fingerly, FingerlyAPIError } from '@fingerly/node'
152
+
153
+ const fingerly = new Fingerly({ secretKey: process.env.FINGERLY_SECRET_KEY })
154
+ const MAX_AGE_MS = 2 * 60 * 1000
155
+
156
+ // expectedTag comes from your server session (`login:${loginAttemptId}` for
157
+ // the attempt your server issued), never from the request body. clientIp is
158
+ // the address of this post, as your framework resolves it.
159
+ export async function decide(requestId: string, expectedTag: string, clientIp: string) {
160
+ let event
161
+ try {
162
+ event = await fingerly.events.get(requestId) // 1. it exists
163
+ } catch (error) {
164
+ if (error instanceof FingerlyAPIError && error.isPending) return 'retry'
165
+ if (error instanceof FingerlyAPIError && error.code === 'event_not_found') return 'refuse'
166
+ throw error
167
+ }
168
+ if (event.tag !== expectedTag) return 'refuse' // 2. this action
169
+ if (Date.now() - Date.parse(event.occurred_at) > MAX_AGE_MS) return 'refuse' // 3. recent
170
+ if (!event.identifiable || event.suspect_score === null) return 'refuse' // 4. identifiable and scored
171
+ if (event.suspect_level === 'high') return 'review' // 5. your policy
172
+ // 6. another network than this post: step up (for example a second factor)
173
+ if (!event.ip_network || !inNetwork(clientIp, event.ip_network)) return 'challenge'
174
+ if (event.suspect_level === 'medium') return 'challenge'
175
+ return 'allow'
176
+ }
177
+
178
+ // ip_network is the /24 (IPv4) or /40 (IPv6) the identification came from;
179
+ // the API never returns the address itself.
180
+ function inNetwork(ip: string, cidr: string): boolean {
181
+ const [base = '', bits = '0'] = cidr.split('/')
182
+ const type = base.includes(':') ? 'ipv6' : 'ipv4'
183
+ const list = new BlockList()
184
+ list.addSubnet(base, Number(bits), type)
185
+ return list.check(ip, type)
186
+ }
187
+ ```
188
+
189
+ One event can back more than one decision inside the recency window; for a flow
190
+ that must be single use, record the `requestId` with the outcome and refuse one
191
+ you have already seen.
192
+
193
+ ## Consent
194
+
195
+ Consent is `'pending'` (the default), `'granted'` or `'denied'`. Until it is
196
+ `granted` nothing is collected and nothing is sent, and `identify()` and
197
+ `collect()` reject with a `ConsentError` (`code: 'consent_required'`, with the
198
+ `state`). `pending` and `denied` behave the same.
199
+
200
+ - Pass `consent` to `load()`, or call `setConsent(state)` on the client when your
201
+ consent tool reports the answer. It is synchronous, and setting the current
202
+ value again does nothing.
203
+ - `onConsentChange(listener)` runs on a change and returns the unsubscribe; read
204
+ `consent` for the current state.
205
+ - Withdrawing consent while a call is running stops it before it submits.
206
+ - Anything other than the three states throws a `TypeError`, so a consent tool's
207
+ `'accepted'` or `true` is refused loudly instead of read as an answer.
208
+
209
+ Pass `granted` only once the visitor has agreed, or where you have established
210
+ that this visitor needs none. See section 4 of the
211
+ [privacy notes](https://github.com/fingerly-io/sdks/blob/main/docs/privacy.md),
212
+ [privacy and consent](https://docs.fingerly.io/docs/privacy-and-consent) and
213
+ [consent tools](https://docs.fingerly.io/docs/consent-tools).
214
+
215
+ ## Incognito detection
216
+
217
+ `incognitoDetection` takes `'standard'` or `'extended'`. Set it on `load()`, or
218
+ override it per `identify()` or `collect()` call.
219
+
220
+ - `'standard'` (the default) detects private browsing without writing anything.
221
+ - `'extended'` also runs an opt-in private-browsing check that writes to
222
+ storage, inside the same single-pass budget.
223
+
224
+ In any mode the SDK never triggers a browser permission prompt, picker or
225
+ dialog, including in Firefox and Tor Browser with their strictest privacy
226
+ settings.
52
227
 
53
228
  ## Serve it from your own site
54
229
 
@@ -66,42 +241,105 @@ const fingerly = await load({
66
241
  ```
67
242
 
68
243
  The path is used exactly as given, with nothing appended. An array of paths
69
- or URLs is tried in order when one does not answer.
244
+ or URLs is tried in order when one does not answer (a `404` or `405` moves on
245
+ to the next at once). Pass `fallbackToDefaultEndpoint: true` only if you want
246
+ `https://api.fingerly.io` tried after your custom endpoints fail.
247
+
248
+ Pair it with a server SDK that mounts the proxy: see
249
+ [proxy integrations](https://docs.fingerly.io/docs/proxy-integrations) and the
250
+ server SDK pages for
251
+ [Node](https://docs.fingerly.io/docs/sdks/node),
252
+ [Python](https://docs.fingerly.io/docs/sdks/python),
253
+ [Go](https://docs.fingerly.io/docs/sdks/go),
254
+ [Java](https://docs.fingerly.io/docs/sdks/java),
255
+ [.NET](https://docs.fingerly.io/docs/sdks/dotnet),
256
+ [PHP](https://docs.fingerly.io/docs/sdks/php),
257
+ [Ruby](https://docs.fingerly.io/docs/sdks/ruby),
258
+ [Rust](https://docs.fingerly.io/docs/sdks/rust) and
259
+ [Cloudflare Workers](https://docs.fingerly.io/docs/sdks/cloudflare-worker).
260
+
261
+ ## Options
262
+
263
+ `load(options)` takes:
264
+
265
+ | Option | Type | Notes |
266
+ | --- | --- | --- |
267
+ | `apiKey` | `string` | Required. A public SDK key from the dashboard. |
268
+ | `endpoints` | `string \| string[]` | Ordered first-party ingestion URLs, posted to exactly as given: a root-relative path such as `/k7x2qm4a`, or an absolute URL. A bare origin such as `http://localhost:8099` is read as an API and gets the API's own path. No query or fragment. |
269
+ | `fallbackToDefaultEndpoint` | `boolean` | Try the Fingerly API after your custom endpoints fail, as a last resort. |
270
+ | `consent` | `'pending' \| 'granted' \| 'denied'` | Defaults to `pending`. |
271
+ | `incognitoDetection` | `'standard' \| 'extended'` | Defaults to `standard`. See [Incognito detection](#incognito-detection). |
272
+ | `apiVersion` | `string` | API route version. Defaults to `v1`. |
273
+ | `schedule` | object | Overrides for the collection scheduler: `budgetMs` (default `350`), `defaultSourceTimeoutMs`, `concurrency`, `filter`, `signal`. |
274
+ | `transport` | `Transport` | Replaces the HTTP transport, for tests or a custom network stack. |
275
+ | `sources` | array | Replaces the source set, for tests or a caller with a reason to run a subset. |
276
+
277
+ `identify(options)` takes `tag` (echoed back on the finished event, for your
278
+ own correlation), `incognitoDetection` and `signal` (an `AbortSignal` that
279
+ cancels collection and submission).
280
+
281
+ `collect(options)` takes `incognitoDetection` and `signal`. It runs the
282
+ collection and returns the `SignalReport` without sending anything, for
283
+ example on a debug page:
284
+
285
+ ```ts
286
+ const report = await fingerly.collect({ incognitoDetection: 'extended' })
287
+ ```
288
+
289
+ Consent applies to `collect()` too: it rejects with `ConsentError` until consent
290
+ is `'granted'`.
291
+
292
+ ## Errors
293
+
294
+ - `load()` never throws synchronously. Missing or backend-only keys (`fly_sk_`,
295
+ `fly_px_`, `fly_mk_`) fail closed.
296
+ - `identify()` and `collect()` reject with `ConsentError` while consent is not
297
+ `'granted'`.
298
+ - `identify()` rejects with `TransportError` when the submission cannot be
299
+ completed. Branch on its `status` and `retryable`. When the server sends
300
+ `Retry-After` on `429` or `503`, `retryAfterMs` carries the wait; waits up to
301
+ two seconds are retried automatically under the same `Idempotency-Key` so a
302
+ check is never billed twice.
303
+
304
+ `TransportError` also carries the server's error `code` when it sent one. The
305
+ two statuses worth branching on are `401` (the key is wrong, or was used from an
306
+ origin it does not list) and `402` (the organisation is not accepting traffic).
307
+ Both are your configuration rather than the visitor's. The full list is in the
308
+ [error reference](https://docs.fingerly.io/reference/errors).
70
309
 
71
310
  ## Content Security Policy
72
311
 
73
312
  With a first-party proxy the SDK needs nothing beyond what your page already
74
313
  allows: `connect-src 'self'` covers the proxy path, and the script itself is
75
- your own bundle or `script-src 'self'` for the script-tag build. Under a policy
76
- without `'unsafe-eval'`, one check that compiles a string is refused by the
77
- browser, once per page load; the SDK skips it and its sibling and carries on.
78
- That refusal is reported to your `report-uri` or `report-to` endpoint if you
79
- have one, as one `script-src` (`eval`) violation per page view.
314
+ your own bundle or `script-src 'self'` for the script-tag build.
80
315
 
81
- Firefox prints two deprecation warnings while the SDK reads the graphics
82
- renderer and the motion sensor. They come from the browser, change nothing
83
- for the visitor, and are not errors.
316
+ - **`'unsafe-eval'` is not needed.** The SDK never evaluates a string as code,
317
+ so a policy without `'unsafe-eval'` produces no violation report from it.
318
+ - **`blob:` workers are optional.** One check runs in a short-lived worker
319
+ built from a `blob:` URL inside the collection budget. If your policy
320
+ disallows `blob:` workers, the attempt is refused once and that check
321
+ reports `blocked`; the refusal is remembered for the rest of the page
322
+ session, so a strict policy produces at most one violation from it per page,
323
+ never one per call. To let the check run, add `worker-src blob:`.
324
+ - **Proof of work.** When the SDK key asks for proof of work, the SDK solves it
325
+ in a `blob:` worker too, and in short time slices on the page when the policy
326
+ refuses one.
84
327
 
85
- ## Errors
328
+ See [Content Security Policy](https://docs.fingerly.io/docs/content-security-policy).
86
329
 
87
- - `load()` rejects for a configuration mistake, such as a missing `apiKey`.
88
- It never throws synchronously, so a misconfigured key cannot take the page
89
- down with it.
90
- - `identify()` rejects with a `ConsentError` while consent is not `granted`,
91
- and with a `TransportError` when the request cannot be completed. Branch on
92
- its `status` and `retryable`. When the server asks for patience (`429` or
93
- `503` with `Retry-After`), `retryAfterMs` says how long; a wait of up to two
94
- seconds is taken care of before the error would be raised. A retry reuses
95
- the first attempt's idempotency key, so it is never counted twice.
330
+ Firefox prints a console deprecation warning while the SDK reads the graphics
331
+ renderer. It comes from the browser, changes nothing for the visitor, and is
332
+ not an error.
96
333
 
97
334
  ## Without a bundler
98
335
 
99
- The package includes a minified script-tag build, `dist/browser.global.js`,
100
- which defines a global `Fingerly`. Serve it from your own site under a neutral
101
- name and load it before your code:
336
+ The package (`0.3.0`) includes a minified IIFE script-tag build,
337
+ `dist/browser.global.js`, which defines a global `Fingerly`. Serve that file
338
+ from your own origin under a neutral path (for example copied from
339
+ `@fingerly/web-js@0.3.0/dist/browser.global.js`) and load it before your code:
102
340
 
103
341
  ```html
104
- <script src="/assets/app-core.js"></script>
342
+ <script src="/assets/app-core-0.3.0.js"></script>
105
343
  <script>
106
344
  Fingerly.load({ apiKey: 'fly_pk_production_…', consent: 'granted' })
107
345
  .then((fingerly) => fingerly.identify({ tag: 'login' }))
@@ -109,11 +347,36 @@ name and load it before your code:
109
347
  </script>
110
348
  ```
111
349
 
350
+ ## TypeScript
351
+
352
+ The package ships its own types (`dist/index.d.ts`), as ES modules and CommonJS.
353
+ It exports `FingerlyOptions` for `load()`, and re-exports the types you receive
354
+ so you do not need the kernel as a dependency: `IdentifyOptions`,
355
+ `CollectOptions`, `IdentifyResult`, `ConsentState`, `IncognitoDetection`,
356
+ `SuspectLevel`, `SignalReport`, `SignalOutcome`, `SignalStatus`,
357
+ `IntegrityReport`, `Lie` and `Confidence`. The values `FingerlyClient`,
358
+ `ConsentError`, `TransportError` and `isSuspiciousLevel` are exported too, so a
359
+ handler can branch with `instanceof`. The package is side-effect free, so a
360
+ bundler can tree shake what you do not import.
361
+
362
+ ## Requirements
363
+
364
+ A browser that runs ES2020 with `fetch` and `AbortController`: every current
365
+ version of Chrome, Edge, Firefox and Safari. A public SDK key whose allowed
366
+ origins include your page. The SDK runs in a browser page only; see the note on
367
+ apps above.
368
+
112
369
  ## Documentation
113
370
 
114
371
  The full guide, including consent tools, first-party proxies and the server
115
372
  side, is at [docs.fingerly.io](https://docs.fingerly.io/docs/sdks/javascript).
116
373
 
374
+ ## Help
375
+
376
+ Open an issue on [fingerly-io/sdks](https://github.com/fingerly-io/sdks/issues),
377
+ or write to [support@fingerly.io](mailto:support@fingerly.io). Security issues:
378
+ [security@fingerly.io](mailto:security@fingerly.io).
379
+
117
380
  ## Licence
118
381
 
119
- Apache-2.0
382
+ [Apache-2.0](https://github.com/fingerly-io/sdks/blob/main/client/web/web-js/LICENSE). Fingerly is a product of Badele LLC.