@fingerly/svelte 0.2.0 → 0.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
@@ -1,60 +1,106 @@
1
- # @fingerly/svelte
2
-
3
- Svelte bindings for the Fingerly SDK. One state per app, held in Svelte's
4
- context, read as plain reactive properties.
5
-
6
- Requires Svelte **5**. The state is built with runes, which is what lets a
7
- component read `fingerly.suspectLevel` and re-render with no store, no subscription
8
- and no `$` prefix at the call site.
9
-
10
- ```
11
- pnpm add @fingerly/svelte
12
- ```
13
-
14
- **Not for apps.** This binding runs the browser SDK, which collects nothing
15
- inside an app's web view (Capacitor, Cordova, Ionic, React Native WebView,
16
- `WKWebView`, Android `WebView`, Electron). Use the Fingerly iOS or Android SDK
17
- in an app; see [docs/privacy.md §3.3](../../../docs/privacy.md).
18
-
19
- ## Set it up
20
-
21
- ```svelte
22
- <!-- +layout.svelte, or your root component -->
23
- <script lang="ts">
24
- import { setupFingerly } from '@fingerly/svelte'
25
-
26
- let { children } = $props()
27
-
28
- // consent: 'granted' only once you have consent (or know none is required here; see docs/privacy.md §4)
29
- setupFingerly({ apiKey: 'fly_pk_production_…', endpoints: '/k7x2qm4a', consent: 'granted' })
30
- </script>
31
-
32
- {@render children()}
33
- ```
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>
9
+
10
+ <p align="center"><b>Fingerly for Svelte</b><br>One state per app, held in Svelte's context, read as plain reactive properties.</p>
11
+
12
+ <p align="center">
13
+ <a href="https://www.npmjs.com/package/@fingerly/svelte"><img src="https://img.shields.io/npm/v/@fingerly/svelte?style=flat-square" alt="npm version"></a>
14
+ <a href="https://www.npmjs.com/package/@fingerly/svelte"><img src="https://img.shields.io/npm/dm/@fingerly/svelte?style=flat-square" alt="npm downloads"></a>
15
+ <a href="https://github.com/fingerly-io/sdks/blob/main/client/web/svelte/LICENSE"><img src="https://img.shields.io/npm/l/@fingerly/svelte?style=flat-square" alt="Apache-2.0 licence"></a>
16
+ <img src="https://img.shields.io/badge/svelte-5%2B-blue?style=flat-square" alt="Svelte 5 or newer">
17
+ </p>
18
+
19
+ <p align="center"><img src="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/banner.webp" alt="Fingerly" width="100%"></p>
20
+
21
+ ## What is this
22
+
23
+ `@fingerly/svelte` is the Svelte 5 binding for the Fingerly browser SDK. One
24
+ state per app, held in Svelte's context, gives every component the same single
25
+ identification per page. The state is built with runes, which is what lets a
26
+ component read `fingerly.suspectLevel` and re-render with no store, no
27
+ subscription and no `$` prefix at the call site. [Fingerly](https://fingerly.io)
28
+ helps you protect signups, logins and payments from fraud and abuse.
29
+
30
+ > **Not for apps.** This binding runs the browser SDK, which collects no
31
+ > device-identifying signals inside an app's web view (Capacitor, Cordova,
32
+ > Ionic, React Native WebView, Flutter WebView, `WKWebView`, Android `WebView`,
33
+ > Electron), so the server answers there with an empty `visitorId`. This keeps
34
+ > apps within section 3.3.3(B) of Apple's developer licence. Use the Fingerly
35
+ > iOS or Android SDK, or the React Native, Flutter or Lynx bridge, in an app;
36
+ > see section 3.3 of the
37
+ > [privacy notes](https://github.com/fingerly-io/sdks/blob/main/docs/privacy.md).
38
+
39
+ ## Getting started
40
+
41
+ 1. **Get a key.** Create a public SDK key in the dashboard
42
+ ([how keys work](https://docs.fingerly.io/docs/api-keys)).
43
+ 2. **Install.**
44
+
45
+ ```sh
46
+ npm install @fingerly/svelte
47
+ # or: pnpm add @fingerly/svelte
48
+ # or: yarn add @fingerly/svelte
49
+ ```
50
+
51
+ 3. **Set it up once, then identify.**
52
+
53
+ ```svelte
54
+ <!-- +layout.svelte, or your root component -->
55
+ <script lang="ts">
56
+ import { setupFingerly } from '@fingerly/svelte'
57
+
58
+ let { children } = $props()
59
+
60
+ // consent: 'granted' only once you have consent (or know none is required here; see Consent below)
61
+ setupFingerly({ apiKey: 'fly_pk_production_…', endpoints: '/k7x2qm4a', consent: 'granted' })
62
+ </script>
63
+
64
+ {@render children()}
65
+ ```
66
+
67
+ ```svelte
68
+ <script lang="ts">
69
+ import { useIdentify } from '@fingerly/svelte'
70
+
71
+ let { orderId }: { orderId: string } = $props()
72
+ const fingerly = useIdentify({ tag: () => `checkout:${orderId}` })
73
+ let challenge = $state(false)
74
+
75
+ async function submit() {
76
+ const { requestId } = await fingerly.identify()
77
+
78
+ // The page only forwards the request ID. Your backend reads the event with
79
+ // the secret key and decides; the page acts on that decision.
80
+ const response = await fetch('/api/checkout', {
81
+ method: 'POST',
82
+ headers: { 'Content-Type': 'application/json' },
83
+ body: JSON.stringify({ orderId, requestId }),
84
+ })
85
+ const { decision } = await response.json()
86
+ challenge = decision === 'challenge'
87
+ }
88
+ </script>
89
+
90
+ <button onclick={submit} disabled={fingerly.isLoading}>
91
+ {fingerly.isLoading ? 'Checking…' : 'Continue'}
92
+ </button>
93
+
94
+ {#if challenge}<StepUp />{/if}
95
+ {#if fingerly.error}<p>{fingerly.error.message}</p>{/if}
96
+ ```
97
+
98
+ 4. **Decide on your backend.** Read the event by `requestId` with the secret
99
+ key; see [Decide on your backend](#decide-on-your-backend).
34
100
 
35
101
  `endpoints` is the path of your first-party proxy, the one the dashboard
36
- issued. With `@fingerly/node` it is a SvelteKit endpoint at that path:
37
-
38
- ```js
39
- // src/routes/k7x2qm4a/+server.js
40
- import { Fingerly } from '@fingerly/node'
41
-
42
- // Built on the first request rather than at import: the build imports this
43
- // module, and the proxy key is a runtime secret.
44
- let proxy
45
- const addresses = new WeakMap()
46
-
47
- export function POST(event) {
48
- proxy ??= Fingerly.createProxy({
49
- proxyKey: process.env.FINGERLY_PROXY_KEY,
50
- clientIp: (request) => addresses.get(request) ?? '',
51
- })
52
- // The connection's peer address, which adapter-node takes from its
53
- // ADDRESS_HEADER setting when the app runs behind a trusted proxy.
54
- addresses.set(event.request, event.getClientAddress())
55
- return proxy(event.request)
56
- }
57
- ```
102
+ issued (see [First-party endpoints](#first-party-endpoints)); drop it to post to
103
+ the Fingerly API directly.
58
104
 
59
105
  The key is a **public** SDK key from the dashboard, and it belongs in the page:
60
106
  it is scoped to the origins you list, which is what makes it safe there. A
@@ -66,41 +112,91 @@ identify is the page's decision. Like every Svelte context call it has to run
66
112
  during component initialisation: a `<script>` block, not an event handler and
67
113
  not an `$effect`.
68
114
 
69
- Consent defaults to `pending`, and nothing is collected or sent until it is
70
- `granted`. A page with a consent banner leaves it `pending` and calls
71
- `setConsent('granted')` once the banner is accepted; see
72
- [Waiting for consent](#waiting-for-consent).
73
-
74
- ## Identify
75
-
76
- ```svelte
77
- <script lang="ts">
78
- import { useIdentify } from '@fingerly/svelte'
79
-
80
- const fingerly = useIdentify()
115
+ `identify()` collects in a single pass (within a 350 ms budget by default) and
116
+ submits once to `POST /api/v1/ingest`, resolving in the same round trip with
117
+ the server's answer: the `requestId`, who the visitor is (`visitorId`), whether
118
+ they could be identified (`identifiable`), and the `suspectScore` and
119
+ `suspectLevel`, unless the key hides them. Nothing is decided in the page:
120
+ scoring lives on the server, under the weights you set. Each report carries a
121
+ single-use freshness ticket, held in memory only; when none is held, the ticket
122
+ request runs in parallel with collection and never holds up or fails
123
+ `identify()`.
124
+
125
+ ## Contents
126
+
127
+ - [Decide on your backend](#decide-on-your-backend)
128
+ - [Identify on mount](#identify-on-mount)
129
+ - [One identification per page](#one-identification-per-page)
130
+ - [Reading the answer](#reading-the-answer)
131
+ - [Consent](#consent)
132
+ - [First-party endpoints](#first-party-endpoints)
133
+ - [Options](#options)
134
+ - [What you get back](#what-you-get-back)
135
+ - [Errors](#errors)
136
+ - [Server rendering](#server-rendering)
137
+ - [More](#more)
138
+ - [TypeScript](#typescript)
139
+ - [Requirements](#requirements)
140
+ - [Documentation](#documentation)
141
+ - [Help](#help)
142
+ - [Licence](#licence)
143
+
144
+ ## Decide on your backend
145
+
146
+ Whoever controls the page controls every branch in it, so access decisions
147
+ (allow, step up, hold, refuse) are made on your backend. The `requestId` the
148
+ page sends is untrusted form input until your backend has verified it. Read the
149
+ event with the secret key and run the checks described in
150
+ [server-side verification](https://docs.fingerly.io/docs/server-side-verification):
81
151
 
82
- async function submit() {
83
- await fingerly.identify()
84
-
85
- if (fingerly.isSuspicious) {
86
- // step up to MFA, hold for review, add friction
87
- }
152
+ ```ts
153
+ // src/lib/server/fingerly.ts, never in the page
154
+ import { BlockList } from 'node:net'
155
+ import { Fingerly, FingerlyAPIError } from '@fingerly/node'
156
+
157
+ const fingerly = new Fingerly({ secretKey: process.env.FINGERLY_SECRET_KEY })
158
+ const MAX_AGE_MS = 2 * 60 * 1000
159
+
160
+ // expectedTag comes from your server session (the order this visitor is
161
+ // paying for), never from the request body. clientIp is the address of this
162
+ // post, for example event.getClientAddress() in a SvelteKit endpoint.
163
+ export async function decide(requestId: string, expectedTag: string, clientIp: string) {
164
+ let event
165
+ try {
166
+ event = await fingerly.events.get(requestId) // 1. it exists
167
+ } catch (error) {
168
+ if (error instanceof FingerlyAPIError && error.isPending) return 'retry'
169
+ if (error instanceof FingerlyAPIError && error.code === 'event_not_found') return 'refuse'
170
+ throw error
88
171
  }
89
- </script>
90
-
91
- <button onclick={submit} disabled={fingerly.isLoading}>
92
- {fingerly.isLoading ? 'Checking…' : 'Continue'}
93
- </button>
172
+ if (event.tag !== expectedTag) return 'refuse' // 2. this action
173
+ if (Date.now() - Date.parse(event.occurred_at) > MAX_AGE_MS) return 'refuse' // 3. recent
174
+ if (!event.identifiable || event.suspect_score === null) return 'refuse' // 4. identifiable and scored
175
+ if (event.suspect_level === 'high') return 'review' // 5. your policy
176
+ // 6. another network than this post: step up (for example a second factor)
177
+ if (!event.ip_network || !inNetwork(clientIp, event.ip_network)) return 'challenge'
178
+ if (event.suspect_level === 'medium') return 'challenge'
179
+ return 'allow'
180
+ }
94
181
 
95
- {#if fingerly.error}<p>{fingerly.error.message}</p>{/if}
182
+ // ip_network is the /24 (IPv4) or /40 (IPv6) the identification came from;
183
+ // the API never returns the address itself.
184
+ function inNetwork(ip: string, cidr: string): boolean {
185
+ const [base = '', bits = '0'] = cidr.split('/')
186
+ const type = base.includes(':') ? 'ipv6' : 'ipv4'
187
+ const list = new BlockList()
188
+ list.addSubnet(base, Number(bits), type)
189
+ return list.check(ip, type)
190
+ }
96
191
  ```
97
192
 
98
- `identify()` collects and submits, and resolves with the server's answer in the
99
- same round trip: the `requestId`, who the visitor is (`visitorId`), and the
100
- `suspectScore` and `suspectLevel`, unless the key hides them. Nothing is decided
101
- in the page: scoring lives on the server, under the weights you set.
193
+ `isSuspicious`, `suspectScore` and `suspectLevel` in the page are a UI hint
194
+ only (for example, to show a spinner a little longer). Never gate an action on
195
+ them. One event can back more than one decision inside the recency window; for
196
+ a flow that must be single use, record the `requestId` with the outcome and
197
+ refuse one you have already seen.
102
198
 
103
- ### On mount instead
199
+ ## Identify on mount
104
200
 
105
201
  ```svelte
106
202
  <script lang="ts">
@@ -134,7 +230,7 @@ renders. Context is per component tree, and a component tree is per request.
134
230
 
135
231
  To deliberately identify again (a long-lived app reaching a second checkout):
136
232
 
137
- ```svelte
233
+ ```ts
138
234
  await fingerly.refresh() // ignores the cached result and collects afresh
139
235
  ```
140
236
 
@@ -143,13 +239,20 @@ await fingerly.refresh() // ignores the cached result and collects afresh
143
239
  `suspectLevel` is the server's band for this submission, under the weights you
144
240
  set. `isSuspicious` is `true` for `medium` or `high`, `false` for `low`, and
145
241
  `null` when the level is absent: no server has answered yet, the submission went
146
- unscored, or the SDK key hides the score from the page, which cannot tell those
147
- apart. Null is not a clean result.
242
+ unscored, or the SDK key hides the score from the page. Null is not a clean
243
+ result.
244
+
245
+ `fingerly.visitorId` is `null` before the first identification completes.
246
+ Afterwards it holds the server's answer, which is `""` (with
247
+ `fingerly.visitorIsNew` `false`) whenever `fingerly.identifiable` is `false`,
248
+ inside an app's web view, or when an unmatched browser report is high risk.
148
249
 
149
250
  Signals are read on your backend, by `requestId`, never in the page: which check
150
- tripped is what a fraudster wants to learn.
251
+ tripped is what a fraudster wants to learn. See
252
+ [server-side verification](https://docs.fingerly.io/docs/server-side-verification)
253
+ and the [server SDKs](https://docs.fingerly.io/docs/sdks).
151
254
 
152
- ## A correlation tag
255
+ ### A correlation tag
153
256
 
154
257
  Echoed back on the finished event so you can match a submission to whatever the
155
258
  page was doing. It accepts a getter, and is read at submission time rather than
@@ -159,24 +262,13 @@ at initialisation:
159
262
  const fingerly = useIdentify({ tag: () => `checkout:${page.params.orderId}` })
160
263
  ```
161
264
 
162
- ## Collect without submitting
163
-
164
- For a debug page that wants the raw report and nothing else:
165
-
166
- ```ts
167
- setupFingerly({ apiKey: 'fly_pk_production_…', submit: false })
168
- ```
265
+ ## Consent
169
266
 
170
- Everything the server decides comes back empty: no `requestId`, no `visitorId`,
171
- `suspectScore` is `null` rather than `0`, and `isSuspicious` is
172
- `null` rather than `false`. That is the honest answer rather than a gap: nothing
173
- was sent, so nobody scored it, and this SDK decides nothing on its own.
174
-
175
- ## Waiting for consent
176
-
177
- If identifying a visitor needs their consent first, set up with `consent:
178
- 'pending'`, the default. Until it is `granted` nothing is collected and nothing is sent:
179
- `useIdentify({ immediate: true })` waits, and the client is not even built.
267
+ Consent defaults to `pending`, and nothing is collected or sent until it is
268
+ `granted`. If identifying a visitor needs their consent first, set up with
269
+ `consent: 'pending'`, the default, and call `setConsent('granted')` once your
270
+ consent banner is accepted: until then `useIdentify({ immediate: true })`
271
+ waits, and the client is not even built.
180
272
 
181
273
  ```ts
182
274
  const fingerly = setupFingerly({ apiKey: 'fly_pk_production_…', consent: 'pending' })
@@ -202,52 +294,117 @@ Setting `granted` starts the identification that was waiting, once. `pending`
202
294
  and `denied` behave the same. Withdrawing consent while an identification is
203
295
  running stops it before it submits, and it fails with a `ConsentError`.
204
296
 
297
+ Pass `granted` only once you have consent, or know none is required here. See
298
+ section 4 of the
299
+ [privacy notes](https://github.com/fingerly-io/sdks/blob/main/docs/privacy.md),
300
+ [privacy and consent](https://docs.fingerly.io/docs/privacy-and-consent) and
301
+ [consent tools](https://docs.fingerly.io/docs/consent-tools).
302
+
303
+ ## First-party endpoints
304
+
305
+ Content blockers refuse requests to third-party hosts. `endpoints` is the path
306
+ of your first-party proxy, the one the dashboard issued. With `@fingerly/node`
307
+ it is a SvelteKit endpoint at that path:
308
+
309
+ ```js
310
+ // src/routes/k7x2qm4a/+server.js
311
+ import { Fingerly } from '@fingerly/node'
312
+
313
+ // Built on the first request rather than at import: the build imports this
314
+ // module, and the proxy key is a runtime secret.
315
+ let proxy
316
+ const addresses = new WeakMap()
317
+
318
+ export function POST(event) {
319
+ proxy ??= Fingerly.createProxy({
320
+ proxyKey: process.env.FINGERLY_PROXY_KEY,
321
+ clientIp: (request) => addresses.get(request) ?? '',
322
+ })
323
+ // The connection's peer address, which adapter-node takes from its
324
+ // ADDRESS_HEADER setting when the app runs behind a trusted proxy.
325
+ addresses.set(event.request, event.getClientAddress())
326
+ return proxy(event.request)
327
+ }
328
+ ```
329
+
330
+ See [proxy integrations](https://docs.fingerly.io/docs/proxy-integrations) and
331
+ the [Node SDK](https://docs.fingerly.io/docs/sdks/node), or pick another
332
+ language on the [server SDK pages](https://docs.fingerly.io/docs/sdks).
333
+
334
+ ## Options
335
+
336
+ `setupFingerly(options)` and `createFingerly(options)`:
337
+
338
+ | Option | Type | Notes |
339
+ | --- | --- | --- |
340
+ | `apiKey` | `string` | Required. A public SDK key. |
341
+ | `endpoints` | `string \| string[]` | Ordered first-party ingestion paths or URLs. |
342
+ | `fallbackToDefaultEndpoint` | `boolean` | Try the Fingerly API only after the custom endpoints fail. |
343
+ | `consent` | `'pending' \| 'granted' \| 'denied'` | Defaults to `pending`. |
344
+ | `incognitoDetection` | `'standard' \| 'extended'` | Defaults to `standard` (see below). |
345
+ | `apiVersion` | `string` | API route version. Defaults to `v1`. |
346
+
347
+ `useIdentify()` options: `immediate`, `tag` and `incognitoDetection` (each of
348
+ the last two a value or a getter). `identify()` takes
349
+ `{ tag, incognitoDetection, force }` and `refresh()` takes
350
+ `{ tag, incognitoDetection }`.
351
+
352
+ ### Incognito detection
353
+
354
+ `incognitoDetection` is accepted on `setupFingerly()`, `useIdentify()`, and
355
+ `identify()` / `refresh()`, the narrowest one winning. `'standard'` (the
356
+ default) never writes to the visitor's storage; `'extended'` opts into an
357
+ additional storage timing check on Chromium browsers, inside the same
358
+ collection budget.
359
+
360
+ ### Collect without submitting
361
+
362
+ For a debug page that wants to inspect the raw `SignalReport` locally without
363
+ posting it to `/api/v1/ingest`, call `collect()` on the underlying client:
364
+
365
+ ```ts
366
+ const client = await fingerly.client()
367
+ const report = await client.collect()
368
+ ```
369
+
370
+ Nothing is sent, so nothing is scored and nothing in the state changes.
371
+ `collect()` still requires consent to be `granted` and rejects with a
372
+ `ConsentError` otherwise.
373
+
205
374
  ## What you get back
206
375
 
207
376
  ```ts
208
377
  const fingerly = useIdentify()
209
378
 
210
379
  fingerly.requestId // string | null: identifies this submission
211
- fingerly.visitorId // string | null: who the server decided this is
212
- fingerly.visitorIsNew // boolean: never seen before
380
+ fingerly.visitorId // string | null: null before completion; "" when identifiable === false
381
+ fingerly.visitorIsNew // boolean: true only when a new visitor was minted
213
382
  fingerly.visitorConfidence // number: 0 to 100
214
383
  fingerly.identifiable // boolean: false when the signals were too thin
215
- fingerly.duplicate // boolean: answered before; this is the first answer
384
+ fingerly.duplicate // boolean: answered before; this is the cached answer
216
385
  fingerly.state // string | null: the server's disposition
217
- fingerly.suspectScore // number | null: null when nothing scored it
386
+ fingerly.suspectScore // number | null: null when unscored or hidden by the key
218
387
  fingerly.suspectLevel // string | null: low, medium, high
219
- fingerly.report // SignalReport | null: every source, with status and timing
388
+ fingerly.identified // boolean: an identification has succeeded
220
389
  fingerly.error // Error | null
221
390
  fingerly.consent // ConsentState (granted, pending or denied)
222
- fingerly.isLoading // boolean
223
- fingerly.isReady // boolean: finished, successfully or not
224
- fingerly.isSuspicious // boolean | null: true for medium or high; null when the level is absent
225
- fingerly.identify() // Promise<IdentifyResult>
226
- fingerly.refresh() // Promise<IdentifyResult>
391
+ fingerly.isLoading // boolean
392
+ fingerly.isReady // boolean: finished, successfully or not
393
+ fingerly.isSuspicious // boolean | null: UI hint only; true for medium or high, null when absent
394
+ fingerly.identify() // Promise<IdentifyAnswer>
395
+ fingerly.refresh() // Promise<IdentifyAnswer>
227
396
  fingerly.setConsent('granted')
397
+ fingerly.client() // Promise<FingerlyClient>
228
398
  ```
229
399
 
230
400
  Every field is a getter over a rune, so reading one in a template subscribes to
231
401
  it and reading one in an event handler gets the current value. None of them is
232
- settable: the state is shared, so a component that could assign to it would be
233
- changing what every other component sees.
234
-
235
- Weights and signal names never reach the browser: your backend reads them on the
236
- server-side event read.
237
-
238
- The detectors run on the server, over the report this package sends, so rules
239
- improve without every integration redeploying. Everything here that says
240
- anything about a visitor came from the server.
241
-
242
- ## The visitor is never asked for anything
243
-
244
- No permission prompt, no picker, no dialog, on any browser. Reading a
245
- permission's *state* prompts nobody and is used freely; requesting is banned
246
- outright and enforced by a test in `@fingerly/web-js`. The one API that prompts on
247
- some browsers (canvas readback, which raises a doorhanger in Tor Browser) is
248
- skipped when the SDK measures a clamped clock.
402
+ settable.
249
403
 
250
- You can drop this into a checkout without it ever interrupting the checkout.
404
+ The binding never keeps the signal report: `identify()` resolves with the
405
+ server's answer (`IdentifyAnswer`, the result without `report`), and nothing of
406
+ the report stays in state. Use `collect()`
407
+ ([Collect without submitting](#collect-without-submitting)) to inspect one.
251
408
 
252
409
  ## Errors
253
410
 
@@ -267,12 +424,11 @@ try {
267
424
 
268
425
  A failed identification is not repeated behind your back. When the server
269
426
  answers `429` with `Retry-After`, every call, `refresh()` included, gets the
270
- same error until that time has passed; the error carries it as
271
- `retryAfterMs`. After a transient failure without one (a `5xx`, a network
272
- error), components that identify automatically wait 5 seconds, doubling per
273
- consecutive failure up to a minute, so route changes during an outage send
274
- nothing; a call you make yourself, such as on a click, still tries at once.
275
- Any other failure, such as a wrong key, is tried again on the next call.
427
+ same error until that time has passed; the error carries it as `retryAfterMs`.
428
+ After a transient failure without one (a `5xx`, a network error), components
429
+ that identify automatically wait 5 seconds, doubling per consecutive failure up
430
+ to a minute, so route changes during an outage send nothing; a call you make
431
+ yourself, such as on a click, still tries at once.
276
432
 
277
433
  `TransportError` carries a `status`. The two worth branching on are `401` (the
278
434
  key is wrong, or was used from an origin it does not list) and `402` (the
@@ -286,23 +442,82 @@ it only sees this error when consent is withdrawn while it runs.
286
442
 
287
443
  Calling `identify()` during SSR rejects with `FingerlyServerError` and a message
288
444
  saying what to do instead. Use `{ immediate: true }`, which already waits for
289
- the client.
445
+ the client. The error reference is at
446
+ [docs.fingerly.io](https://docs.fingerly.io/reference/errors).
290
447
 
291
- ## Running the playground
448
+ ## Server rendering
292
449
 
293
- `playground/` is this package's own state and hooks driving the real SDK (no
294
- mocks), showing `suspectScore` and `suspectLevel` beside the raw
295
- report, all sharing one identification. It uses `submit: false`, so no server
296
- answers: the raw report fills in, and the score and level read hidden.
450
+ The state is created in context, one per component tree, and a component tree is
451
+ per request, so two visitors never share one on a SvelteKit server.
452
+ `{ immediate: true }` runs in an `$effect`, which does not run during a server
453
+ render, so the page renders on the server and collects in the browser.
297
454
 
298
- ```
455
+ ## More
456
+
457
+ ### The visitor is never asked for anything
458
+
459
+ No permission prompt, no picker, no dialog, on any browser. Reading a
460
+ permission's *state* prompts nobody and is used freely; requesting is banned
461
+ outright and enforced by a test in `@fingerly/web-js`. The one browser API that
462
+ can prompt (Tor Browser, and Firefox with fingerprinting resistance on, answer
463
+ it with a doorhanger) is skipped whenever the SDK detects that browser would
464
+ prompt.
465
+
466
+ You can drop this into a checkout without it ever interrupting the checkout.
467
+
468
+ <details>
469
+ <summary>Running the playground</summary>
470
+
471
+ `playground/` (in the
472
+ [repository](https://github.com/fingerly-io/sdks/tree/main/client/web/svelte))
473
+ is this package's own state and hooks driving the real SDK (no mocks), showing
474
+ `suspectScore` and `suspectLevel`, all sharing one identification.
475
+
476
+ ```sh
299
477
  pnpm --filter @fingerly/svelte playground # http://localhost:4176
300
478
  ```
301
479
 
302
- ## A note on the build
480
+ </details>
481
+
482
+ <details>
483
+ <summary>A note on the build</summary>
303
484
 
304
485
  The package is emitted by `tsc`, not bundled, and that is a requirement rather
305
486
  than a preference. The runes in `*.svelte.js` are compiled by the *app's*
306
487
  Svelte plugin, which decides what to compile by the file name. Bundling them
307
488
  into an `index.js` would hand the app a file full of `$state(…)` that nothing
308
489
  compiles, and `$state is not defined` at runtime.
490
+
491
+ </details>
492
+
493
+ ## TypeScript
494
+
495
+ Types ship with the package. `Fingerly`, `FingerlyOptions`, `IdentifyAnswer`
496
+ and `UseIdentifyOptions` are exported, together with the types you receive and
497
+ pass (`IdentifyResult`, `IdentifyOptions`, `CollectOptions`, `ConsentState`,
498
+ `IncognitoDetection`, `SuspectLevel`, `SignalReport`, `SignalOutcome`,
499
+ `SignalStatus`, `IntegrityReport`, `Lie` and `Confidence`). The values
500
+ `ConsentError`, `TransportError`, `FingerlyServerError` and `FINGERLY_KEY` (the
501
+ context key, for an advanced `getContext()`) are exported too. The package is
502
+ side-effect free.
503
+
504
+ ## Requirements
505
+
506
+ Svelte **5**. The browser SDK it wraps needs ES2020 with `fetch` and
507
+ `AbortController`: every current version of Chrome, Edge, Firefox and Safari.
508
+
509
+ ## Documentation
510
+
511
+ The Svelte guide is at
512
+ [docs.fingerly.io](https://docs.fingerly.io/docs/sdks/svelte). The browser SDK
513
+ underneath is [`@fingerly/web-js`](https://www.npmjs.com/package/@fingerly/web-js).
514
+
515
+ ## Help
516
+
517
+ Open an issue on [fingerly-io/sdks](https://github.com/fingerly-io/sdks/issues),
518
+ or write to [support@fingerly.io](mailto:support@fingerly.io). Security issues:
519
+ [security@fingerly.io](mailto:security@fingerly.io).
520
+
521
+ ## Licence
522
+
523
+ [Apache-2.0](https://github.com/fingerly-io/sdks/blob/main/client/web/svelte/LICENSE). Fingerly is a product of Badele LLC.
@@ -1,54 +1,14 @@
1
1
  /**
2
2
  * What a component asks for: the identification.
3
- *
4
- * Named `useIdentify` to match the Vue, React and Next
5
- * bindings rather than to follow any Svelte convention. An SDK whose four
6
- * bindings answer the same question under four different names makes its own
7
- * documentation harder to read than the code it documents. What is Svelte's
8
- * here is the *shape*: reactive objects read as plain properties, no refs, no
9
- * `$` prefix, no subscription.
10
3
  */
4
+ import type { IncognitoDetection } from '@fingerly/web-js';
11
5
  import type { Fingerly } from './state.svelte.js';
12
6
  export interface UseIdentifyOptions {
13
- /**
14
- * Identify as soon as the component mounts.
15
- *
16
- * Safe to pass in every component that wants it: the context holds one
17
- * shared identification, so the second and third callers get the first
18
- * one's answer rather than starting their own submission.
19
- *
20
- * It runs in an `$effect`, which is what makes it server-safe - effects do
21
- * not run during SSR, so a SvelteKit page using this renders on the server
22
- * and collects on the client without a guard of its own.
23
- *
24
- * It waits for consent. While `consent` is `pending` or `denied` nothing is
25
- * started, and the identification begins once it becomes `granted`.
26
- */
7
+ /** Identify as soon as the component mounts (after consent is `'granted'`). */
27
8
  immediate?: boolean;
28
- /**
29
- * The customer's own correlation value, echoed back on the finished event.
30
- *
31
- * Accepts a getter as well as a string, so it can be
32
- * `() => page.params.orderId` and be read at the moment of submission
33
- * rather than at the moment the component initialised.
34
- */
9
+ /** Opaque correlation label echoed on the event. */
35
10
  tag?: string | (() => string | undefined);
11
+ /** Opt-in extended incognito probe control (`'standard'` or `'extended'`). */
12
+ incognitoDetection?: IncognitoDetection | (() => IncognitoDetection | undefined);
36
13
  }
37
- /**
38
- * The shared identification, optionally started on mount.
39
- *
40
- * ```svelte
41
- * <script lang="ts">
42
- * import { useIdentify } from '@fingerly/svelte'
43
- * const fingerly = useIdentify({ immediate: true })
44
- * </script>
45
- *
46
- * {#if fingerly.isReady && fingerly.isSuspicious}
47
- * <p>Something about this session is unusual.</p>
48
- * {/if}
49
- * ```
50
- *
51
- * Returns the same object `setupFingerly()` created, so `fingerly.suspectLevel`
52
- * in a template re-renders when the answer arrives.
53
- */
54
14
  export declare function useIdentify(options?: UseIdentifyOptions): Fingerly;
@@ -1,61 +1,37 @@
1
1
  /**
2
2
  * What a component asks for: the identification.
3
- *
4
- * Named `useIdentify` to match the Vue, React and Next
5
- * bindings rather than to follow any Svelte convention. An SDK whose four
6
- * bindings answer the same question under four different names makes its own
7
- * documentation harder to read than the code it documents. What is Svelte's
8
- * here is the *shape*: reactive objects read as plain properties, no refs, no
9
- * `$` prefix, no subscription.
10
3
  */
11
4
  import { useFingerly } from './context.js';
12
- /**
13
- * The shared identification, optionally started on mount.
14
- *
15
- * ```svelte
16
- * <script lang="ts">
17
- * import { useIdentify } from '@fingerly/svelte'
18
- * const fingerly = useIdentify({ immediate: true })
19
- * </script>
20
- *
21
- * {#if fingerly.isReady && fingerly.isSuspicious}
22
- * <p>Something about this session is unusual.</p>
23
- * {/if}
24
- * ```
25
- *
26
- * Returns the same object `setupFingerly()` created, so `fingerly.suspectLevel`
27
- * in a template re-renders when the answer arrives.
28
- */
29
5
  export function useIdentify(options = {}) {
30
6
  const fingerly = useFingerly();
31
7
  const resolveTag = (override) => override ?? (typeof options.tag === 'function' ? options.tag() : options.tag);
32
- // Wrapped rather than handed back as-is, so that `tag` applies to every call
33
- // this component makes and not only to the one `immediate` starts. The
34
- // getters below forward to the shared state, so the reactivity is the same
35
- // object's - what is per-component here is the tag, and nothing else.
8
+ const resolveIncognito = (override) => override ??
9
+ (typeof options.incognitoDetection === 'function'
10
+ ? options.incognitoDetection()
11
+ : options.incognitoDetection);
36
12
  const identify = (callOptions = {}) => {
37
13
  const tag = resolveTag(callOptions.tag);
14
+ const incognitoDetection = resolveIncognito(callOptions.incognitoDetection);
38
15
  return fingerly.identify({
39
16
  ...(tag === undefined ? {} : { tag }),
17
+ ...(incognitoDetection === undefined ? {} : { incognitoDetection }),
40
18
  ...(callOptions.force === undefined ? {} : { force: callOptions.force }),
41
19
  });
42
20
  };
43
21
  const refresh = (callOptions = {}) => identify({ ...callOptions, force: true });
44
22
  if (options.immediate) {
45
23
  $effect(() => {
46
- // Reading `consent` is what makes this effect run again when a banner is
47
- // accepted after mount. Once: the shared state memoises the run, so
48
- // consent flipping back and forth afterwards submits nothing more.
49
24
  if (fingerly.consent !== 'granted')
50
25
  return;
51
- // The rejection is swallowed rather than left to become an unhandled
52
- // one: the failure is already in `fingerly.error`, which is where a
53
- // component that opted into `immediate` will look for it. A caller who
54
- // wants to await the outcome calls identify() themselves.
55
- // Marked automatic, so a failure's hold applies: a remount while the
56
- // API is refusing must not send another identification.
57
26
  const tag = resolveTag();
58
- void fingerly.identify({ ...(tag === undefined ? {} : { tag }), automatic: true }).catch(() => undefined);
27
+ const incognitoDetection = resolveIncognito();
28
+ void fingerly
29
+ .identify({
30
+ ...(tag === undefined ? {} : { tag }),
31
+ ...(incognitoDetection === undefined ? {} : { incognitoDetection }),
32
+ automatic: true,
33
+ })
34
+ .catch(() => undefined);
59
35
  });
60
36
  }
61
37
  return {
@@ -86,8 +62,8 @@ export function useIdentify(options = {}) {
86
62
  get suspectLevel() {
87
63
  return fingerly.suspectLevel;
88
64
  },
89
- get report() {
90
- return fingerly.report;
65
+ get identified() {
66
+ return fingerly.identified;
91
67
  },
92
68
  get error() {
93
69
  return fingerly.error;
package/dist/index.d.ts CHANGED
@@ -1,17 +1,10 @@
1
1
  /**
2
- * @fingerly/svelte - Svelte 5 bindings for the Fingerly SDK.
3
- *
4
- * One state per app, held in Svelte's context, read as plain reactive
5
- * properties. See the README for the whole surface with examples.
6
- *
7
- * Requires Svelte 5: the state is built with runes, which is what lets a
8
- * component read `fingerly.suspectLevel` and re-render, with no store and no `$`
9
- * prefix at the call site.
2
+ * @fingerly/svelte - Svelte 5 bindings for the Fingerly SDK (`0.4.0`, single-pass `v: 3`).
10
3
  */
11
4
  export { FINGERLY_KEY, setupFingerly, useFingerly } from './context.js';
12
5
  export { createFingerly, FingerlyServerError } from './state.svelte.js';
13
- export type { Fingerly, FingerlyOptions } from './state.svelte.js';
6
+ export type { Fingerly, FingerlyOptions, IdentifyAnswer } from './state.svelte.js';
14
7
  export { useIdentify } from './hooks.svelte.js';
15
8
  export type { UseIdentifyOptions } from './hooks.svelte.js';
16
- export type { FingerlyWebEvent, Confidence, ConsentState, IdentifyResult, IntegrityReport, Lie, SignalOutcome, SignalReport, SignalStatus, } from '@fingerly/web-js';
9
+ export type { CollectOptions, Confidence, ConsentState, IdentifyOptions, IdentifyResult, IncognitoDetection, IntegrityReport, Lie, SignalOutcome, SignalReport, SignalStatus, SuspectLevel, } from '@fingerly/web-js';
17
10
  export { ConsentError, TransportError } from '@fingerly/web-js';
package/dist/index.js CHANGED
@@ -1,12 +1,5 @@
1
1
  /**
2
- * @fingerly/svelte - Svelte 5 bindings for the Fingerly SDK.
3
- *
4
- * One state per app, held in Svelte's context, read as plain reactive
5
- * properties. See the README for the whole surface with examples.
6
- *
7
- * Requires Svelte 5: the state is built with runes, which is what lets a
8
- * component read `fingerly.suspectLevel` and re-render, with no store and no `$`
9
- * prefix at the call site.
2
+ * @fingerly/svelte - Svelte 5 bindings for the Fingerly SDK (`0.4.0`, single-pass `v: 3`).
10
3
  */
11
4
  export { FINGERLY_KEY, setupFingerly, useFingerly } from './context.js';
12
5
  export { createFingerly, FingerlyServerError } from './state.svelte.js';
@@ -1,20 +1,17 @@
1
1
  /**
2
- * The shared state, in runes.
3
- *
4
- * A `.svelte.ts` module rather than a plain one, which is what lets `$state`
5
- * live outside a component: the file is compiled by the Svelte compiler in the
6
- * consuming app, so the fields below are reactive wherever they are read.
7
- * That is the whole reason this binding needs no store, no subscription and no
8
- * `$` prefix at the call site - a component reads `fingerly.suspectLevel` and
9
- * re-renders when it changes.
10
- *
11
- * One state per app, not one per component. Identification is a *page-level*
12
- * event: three components asking whether the visitor is suspicious should
13
- * produce one submission and one answer, not three. Per-component state would
14
- * bill the customer three times for one page load and hand the three
15
- * components three different `requestId`s for one visitor.
2
+ * The shared state, in Svelte 5 runes (`0.4.0`, single-pass `v: 3`).
16
3
  */
17
- import { type ConsentState, type FingerlyClient, type IdentifyResult, type SignalReport } from '@fingerly/web-js';
4
+ import { type ConsentState, type FingerlyClient, type IdentifyResult, type IncognitoDetection, type SuspectLevel } from '@fingerly/web-js';
5
+ /**
6
+ * What the binding hands back from `identify()`: the result without the full
7
+ * signal report. The report is evidence for the server; keeping it in app
8
+ * state for the page lifetime would let any component or debugging tool read
9
+ * or log the whole fingerprint. Call `(await client()).collect()` to inspect a
10
+ * report locally.
11
+ */
12
+ export type IdentifyAnswer = Omit<IdentifyResult, 'report'>;
13
+ /** A copy of `result` without its `report`, whether or not the client sent one. */
14
+ export declare function withoutReport<T extends object>(result: T): Omit<T, 'report'>;
18
15
  /** Options for [[createFingerly]] and [[setupFingerly]]. */
19
16
  export interface FingerlyOptions {
20
17
  /** The SDK key from the dashboard. A public key is safe in a page. */
@@ -25,91 +22,51 @@ export interface FingerlyOptions {
25
22
  endpoints?: string | readonly string[];
26
23
  fallbackToDefaultEndpoint?: boolean;
27
24
  /**
28
- * Collect without submitting anything.
29
- *
30
- * Everything the server decides comes back empty: no `requestId`, no
31
- * `visitorId`, no `suspectScore`, no `suspectLevel`. That is the honest
32
- * answer rather than a gap - nothing was sent, so nobody scored it, and
33
- * this SDK decides nothing on its own.
34
- */
35
- submit?: boolean;
36
- /**
37
- * Whether the visitor has agreed to be identified. Defaults to `pending`.
38
- *
39
- * Leave it `pending` while identification waits on a consent banner, then
40
- * call [[Fingerly.setConsent]] when it is answered, or pass `granted`
41
- * once you have consent (or know none is required here; see docs/privacy.md §4). Until then nothing is
42
- * collected or sent: `useIdentify({ immediate: true })` waits, and a manual
43
- * `identify()` fails with a `ConsentError` in `error`.
25
+ * Controls whether opt-in extended incognito probes (`storage_durability`)
26
+ * execute (`'standard'` default or `'extended'`).
44
27
  */
28
+ incognitoDetection?: IncognitoDetection;
29
+ /** Whether the visitor has agreed to be identified. Defaults to `pending`. */
45
30
  consent?: ConsentState;
46
31
  }
47
32
  /** What a component reads. Every field is reactive; none of them is settable. */
48
33
  export interface Fingerly {
49
34
  readonly requestId: string | null;
50
35
  /**
51
- * Who the server decided this is. Null under `submit: false`, and null
52
- * before the first identification - never empty-string, so a template can
53
- * ask `fingerly.visitorId` without also asking whether it means anything.
36
+ * `null` before the first identification; afterwards `result.visitorId`
37
+ * (`""` when `identifiable === false` under Option B).
54
38
  */
55
39
  readonly visitorId: string | null;
56
- /** True when the server had never seen this visitor before. */
57
40
  readonly visitorIsNew: boolean;
58
- /** How sure the server is of `visitorId`, 0-100. */
59
41
  readonly visitorConfidence: number;
60
- /** False when the signals were too thin to identify anybody. */
61
42
  readonly identifiable: boolean;
62
- /** True when this submission had already been answered. */
63
43
  readonly duplicate: boolean;
64
- /** The server's disposition of the check. */
65
44
  readonly state: string | null;
66
- /**
67
- * The server's score, 0-100, or null when it did not score.
68
- *
69
- * Null and zero are different answers: null is "not scored", zero is
70
- * "scored, nothing found". Do not collapse them with `?? 0`.
71
- */
72
45
  readonly suspectScore: number | null;
73
- /** The score as a band - `low`, `medium`, `high`. Null when unscored. */
74
- readonly suspectLevel: string | null;
75
- readonly report: SignalReport | null;
46
+ readonly suspectLevel: SuspectLevel | null;
47
+ /** True once an identification has succeeded. */
48
+ readonly identified: boolean;
76
49
  readonly error: Error | null;
77
50
  readonly isLoading: boolean;
78
- /** True once an identification has completed, successfully or not. */
79
51
  readonly isReady: boolean;
80
52
  /**
81
- * True when the server scored this `medium` or `high` under the weights you
82
- * set: the "should I even look?" flag, and not a policy. `null` when no
83
- * server has answered or the level is absent (not identified yet, `submit:
84
- * false`, unscored, or hidden by the key), which is not a clean result.
85
- * Anything more nuanced reads `suspectLevel`, or your backend reads the signals.
53
+ * True for `medium` or `high`, `null` when the level is absent. A UI hint
54
+ * only: access decisions belong on your backend, which reads the event by
55
+ * `requestId` with the secret key.
86
56
  */
87
57
  readonly isSuspicious: boolean | null;
88
- /**
89
- * Whether the visitor has agreed to be identified, as last set here or on
90
- * the client. Automatic identification waits for `granted`.
91
- */
92
58
  readonly consent: ConsentState;
93
- /**
94
- * Record the visitor's consent, as the consent tool reports it.
95
- *
96
- * Usable before the client exists - during SSR, or before anything has
97
- * identified - and forwarded to it once it does. Setting `granted` is what
98
- * starts any `useIdentify({ immediate: true })` that was waiting for it.
99
- * The client's own `setConsent()` does the same.
100
- */
101
59
  setConsent(state: ConsentState): void;
102
- /** Collect, score and submit. Reuses a completed run unless `force`. */
103
60
  identify(options?: {
104
61
  tag?: string;
62
+ incognitoDetection?: IncognitoDetection;
105
63
  force?: boolean;
106
64
  automatic?: boolean;
107
- }): Promise<IdentifyResult>;
108
- /** Identify again from scratch, ignoring any previous result. */
65
+ }): Promise<IdentifyAnswer>;
109
66
  refresh(options?: {
110
67
  tag?: string;
111
- }): Promise<IdentifyResult>;
112
- /** The underlying client, built on first use. */
68
+ incognitoDetection?: IncognitoDetection;
69
+ }): Promise<IdentifyAnswer>;
113
70
  client(): Promise<FingerlyClient>;
114
71
  }
115
72
  /** Thrown when the SDK is asked to collect somewhere there is no browser. */
@@ -117,24 +74,6 @@ export declare class FingerlyServerError extends Error {
117
74
  readonly name = "FingerlyServerError";
118
75
  constructor();
119
76
  }
120
- /**
121
- * Build the state.
122
- *
123
- * Nothing is collected here. Creating it only makes the client reachable - a
124
- * factory that fingerprinted as it ran would collect during a server render
125
- * and take the choice of *when* away from the page that knows.
126
- */
127
- /**
128
- * How long a failed identification holds off the next one.
129
- *
130
- * Without this a failure was forgotten at once, and every component mounting
131
- * with `immediate` started another identification - three requests per route
132
- * change while the API was answering 429. A `Retry-After` the server sent
133
- * holds every call, forced or not, until it passes. A transient failure
134
- * without one (a 5xx, a network error) holds automatic calls only, for 5 s
135
- * doubling per consecutive failure up to a minute; a click still tries at
136
- * once. Anything else holds nothing.
137
- */
138
77
  export declare function failureHold(error: unknown, consecutive: number, now: number): {
139
78
  until: number;
140
79
  automaticUntil: number;
@@ -1,20 +1,13 @@
1
1
  /**
2
- * The shared state, in runes.
3
- *
4
- * A `.svelte.ts` module rather than a plain one, which is what lets `$state`
5
- * live outside a component: the file is compiled by the Svelte compiler in the
6
- * consuming app, so the fields below are reactive wherever they are read.
7
- * That is the whole reason this binding needs no store, no subscription and no
8
- * `$` prefix at the call site - a component reads `fingerly.suspectLevel` and
9
- * re-renders when it changes.
10
- *
11
- * One state per app, not one per component. Identification is a *page-level*
12
- * event: three components asking whether the visitor is suspicious should
13
- * produce one submission and one answer, not three. Per-component state would
14
- * bill the customer three times for one page load and hand the three
15
- * components three different `requestId`s for one visitor.
2
+ * The shared state, in Svelte 5 runes (`0.4.0`, single-pass `v: 3`).
16
3
  */
17
4
  import { isSuspiciousLevel, load, } from '@fingerly/web-js';
5
+ /** A copy of `result` without its `report`, whether or not the client sent one. */
6
+ export function withoutReport(result) {
7
+ const copy = { ...result };
8
+ delete copy.report;
9
+ return copy;
10
+ }
18
11
  /** Thrown when the SDK is asked to collect somewhere there is no browser. */
19
12
  export class FingerlyServerError extends Error {
20
13
  name = 'FingerlyServerError';
@@ -24,27 +17,11 @@ export class FingerlyServerError extends Error {
24
17
  'which already waits for the client.');
25
18
  }
26
19
  }
27
- /**
28
- * Build the state.
29
- *
30
- * Nothing is collected here. Creating it only makes the client reachable - a
31
- * factory that fingerprinted as it ran would collect during a server render
32
- * and take the choice of *when* away from the page that knows.
33
- */
34
- /**
35
- * How long a failed identification holds off the next one.
36
- *
37
- * Without this a failure was forgotten at once, and every component mounting
38
- * with `immediate` started another identification - three requests per route
39
- * change while the API was answering 429. A `Retry-After` the server sent
40
- * holds every call, forced or not, until it passes. A transient failure
41
- * without one (a 5xx, a network error) holds automatic calls only, for 5 s
42
- * doubling per consecutive failure up to a minute; a click still tries at
43
- * once. Anything else holds nothing.
44
- */
45
20
  export function failureHold(error, consecutive, now) {
46
21
  const failure = error;
47
- const retryAfter = typeof failure?.retryAfterMs === 'number' && failure.retryAfterMs > 0 ? failure.retryAfterMs : 0;
22
+ const retryAfter = typeof failure?.retryAfterMs === 'number' && failure.retryAfterMs > 0
23
+ ? failure.retryAfterMs
24
+ : 0;
48
25
  const backoff = failure?.retryable === true ? Math.min(60_000, 5_000 * 2 ** Math.max(0, consecutive - 1)) : 0;
49
26
  return { until: now + retryAfter, automaticUntil: now + Math.max(retryAfter, backoff) };
50
27
  }
@@ -58,11 +35,11 @@ export function createFingerly(options) {
58
35
  let checkState = $state(null);
59
36
  let suspectScore = $state(null);
60
37
  let suspectLevel = $state(null);
61
- let report = $state(null);
38
+ let identified = $state(false);
62
39
  let error = $state(null);
63
40
  let isLoading = $state(false);
64
41
  let consent = $state(options.consent ?? 'pending');
65
- const isReady = $derived(report !== null || error !== null);
42
+ const isReady = $derived(identified || error !== null);
66
43
  const isSuspicious = $derived(isSuspiciousLevel(suspectLevel));
67
44
  let clientPromise;
68
45
  let loaded;
@@ -75,24 +52,20 @@ export function createFingerly(options) {
75
52
  const client = () => {
76
53
  if (typeof window === 'undefined')
77
54
  return Promise.reject(new FingerlyServerError());
78
- // Built once and memoised. `load()` is cheap today but is the documented
79
- // place for future warm-up work, and warming up per component would undo
80
- // it.
81
- // Through a promise even though load() returns one: a synchronous throw
82
- // here would escape every caller's .catch and leave isLoading stuck.
83
55
  clientPromise ??= Promise.resolve().then(() => load({
84
56
  apiKey: options.apiKey,
85
57
  ...(options.apiVersion === undefined ? {} : { apiVersion: options.apiVersion }),
86
58
  ...(options.endpoints === undefined ? {} : { endpoints: options.endpoints }),
87
- ...(options.fallbackToDefaultEndpoint === undefined ? {} : { fallbackToDefaultEndpoint: options.fallbackToDefaultEndpoint }),
59
+ ...(options.fallbackToDefaultEndpoint === undefined
60
+ ? {}
61
+ : { fallbackToDefaultEndpoint: options.fallbackToDefaultEndpoint }),
62
+ ...(options.incognitoDetection === undefined
63
+ ? {}
64
+ : { incognitoDetection: options.incognitoDetection }),
88
65
  consent,
89
66
  }).then((fingerly) => {
90
- // Caught up before anything can identify through it: setConsent() may
91
- // have been called while load() was settling.
92
67
  if (fingerly.consent !== consent)
93
68
  fingerly.setConsent(consent);
94
- // And followed from here on, so a consent tool holding the client itself
95
- // moves this state - and whatever is waiting on it - as well.
96
69
  fingerly.onConsentChange(mirrorConsent);
97
70
  loaded = fingerly;
98
71
  return fingerly;
@@ -100,47 +73,38 @@ export function createFingerly(options) {
100
73
  return clientPromise;
101
74
  };
102
75
  const setConsent = (next) => {
103
- // The client first, so it validates the value and has it before an effect
104
- // reacting to the state below asks it to identify.
105
76
  loaded?.setConsent(next);
106
77
  mirrorConsent(next);
107
78
  };
108
79
  const identify = (identifyOptions = {}) => {
109
80
  if (typeof window === 'undefined')
110
81
  return Promise.reject(new FingerlyServerError());
111
- // One promise for the page, in flight or already settled, which is what
112
- // makes `useIdentify({ immediate: true })` safe in as many components as
113
- // want it.
114
- //
115
- // Memoising the promise rather than the report also settles a case the Vue
116
- // binding had to learn: under `submit: false` there is no requestId, so a
117
- // cache keyed on one never engages and every component re-collects the
118
- // whole fingerprint. A promise has an identity either way.
119
82
  if (current && !identifyOptions.force)
120
83
  return current;
121
- // Holding off after a failure; see failureHold.
122
84
  const now = Date.now();
123
85
  if (held && (now < held.until || (identifyOptions.automatic && now < held.automaticUntil))) {
124
86
  return Promise.reject(held.error);
125
87
  }
126
88
  isLoading = true;
127
89
  error = null;
90
+ const incognitoDetection = identifyOptions.incognitoDetection ?? options.incognitoDetection;
128
91
  const run = client()
129
92
  .then((fingerly) => fingerly.identify({
130
93
  ...(identifyOptions.tag === undefined ? {} : { tag: identifyOptions.tag }),
131
- ...(options.submit === undefined ? {} : { submit: options.submit }),
94
+ ...(incognitoDetection === undefined ? {} : { incognitoDetection }),
132
95
  }))
133
- .then((result) => {
96
+ .then((full) => {
97
+ const result = withoutReport(full);
134
98
  requestId = result.requestId === '' ? null : result.requestId;
135
- visitorId = result.visitorId === '' ? null : result.visitorId;
99
+ visitorId = result.visitorId;
136
100
  visitorIsNew = result.visitorIsNew;
137
101
  visitorConfidence = result.visitorConfidence;
138
102
  identifiable = result.identifiable;
139
- duplicate = result.duplicate;
103
+ duplicate = result.duplicate ?? false;
140
104
  checkState = result.state === '' ? null : result.state;
141
105
  suspectScore = result.suspectScore ?? null;
142
106
  suspectLevel = result.suspectLevel ?? null;
143
- report = result.report;
107
+ identified = true;
144
108
  held = undefined;
145
109
  consecutiveFailures = 0;
146
110
  return result;
@@ -150,13 +114,8 @@ export function createFingerly(options) {
150
114
  error = failure;
151
115
  consecutiveFailures += 1;
152
116
  held = { error: failure, ...failureHold(failure, consecutiveFailures, Date.now()) };
153
- // Forgotten, so the next caller retries rather than being handed a
154
- // rejected promise forever.
155
117
  if (current === run)
156
118
  current = undefined;
157
- // Rethrown as well as stored: a caller that awaited identify() should
158
- // be able to try/catch it, and a component that only reads `error`
159
- // should not have to.
160
119
  throw failure;
161
120
  })
162
121
  .finally(() => {
@@ -166,9 +125,6 @@ export function createFingerly(options) {
166
125
  return run;
167
126
  };
168
127
  const refresh = (refreshOptions = {}) => identify({ ...refreshOptions, force: true });
169
- // Getters rather than fields: reading through one is what subscribes the
170
- // caller's template to the rune behind it. Returning the values directly
171
- // would hand out a snapshot taken at the moment this function ran.
172
128
  return {
173
129
  get requestId() {
174
130
  return requestId;
@@ -197,8 +153,8 @@ export function createFingerly(options) {
197
153
  get suspectLevel() {
198
154
  return suspectLevel;
199
155
  },
200
- get report() {
201
- return report;
156
+ get identified() {
157
+ return identified;
202
158
  },
203
159
  get error() {
204
160
  return error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fingerly/svelte",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -26,7 +26,7 @@
26
26
  ],
27
27
  "sideEffects": false,
28
28
  "dependencies": {
29
- "@fingerly/web-js": "0.2.0"
29
+ "@fingerly/web-js": "0.4.0"
30
30
  },
31
31
  "peerDependencies": {
32
32
  "svelte": ">=5"