@fingerly/svelte 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/README.md +303 -2
- package/dist/context.d.ts +42 -0
- package/dist/context.js +56 -0
- package/dist/hooks.svelte.d.ts +54 -0
- package/dist/hooks.svelte.js +115 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +14 -0
- package/dist/state.svelte.d.ts +149 -0
- package/dist/state.svelte.js +228 -0
- package/package.json +45 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,304 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @fingerly/svelte
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
## Set it up
|
|
15
|
+
|
|
16
|
+
```svelte
|
|
17
|
+
<!-- +layout.svelte, or your root component -->
|
|
18
|
+
<script lang="ts">
|
|
19
|
+
import { setupFingerly } from '@fingerly/svelte'
|
|
20
|
+
|
|
21
|
+
let { children } = $props()
|
|
22
|
+
|
|
23
|
+
// consent: 'granted' only once you have consent (or another lawful basis)
|
|
24
|
+
setupFingerly({ apiKey: 'fly_pk_production_…', endpoints: '/k7x2qm4a', consent: 'granted' })
|
|
25
|
+
</script>
|
|
26
|
+
|
|
27
|
+
{@render children()}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
`endpoints` is the path of your first-party proxy, the one the dashboard
|
|
31
|
+
issued. With `@fingerly/node` it is a SvelteKit endpoint at that path:
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
// src/routes/k7x2qm4a/+server.js
|
|
35
|
+
import { Fingerly } from '@fingerly/node'
|
|
36
|
+
|
|
37
|
+
// Built on the first request rather than at import: the build imports this
|
|
38
|
+
// module, and the proxy key is a runtime secret.
|
|
39
|
+
let proxy
|
|
40
|
+
const addresses = new WeakMap()
|
|
41
|
+
|
|
42
|
+
export function POST(event) {
|
|
43
|
+
proxy ??= Fingerly.createProxy({
|
|
44
|
+
proxyKey: process.env.FINGERLY_PROXY_KEY,
|
|
45
|
+
clientIp: (request) => addresses.get(request) ?? '',
|
|
46
|
+
})
|
|
47
|
+
// The connection's peer address, which adapter-node takes from its
|
|
48
|
+
// ADDRESS_HEADER setting when the app runs behind a trusted proxy.
|
|
49
|
+
addresses.set(event.request, event.getClientAddress())
|
|
50
|
+
return proxy(event.request)
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The key is a **public** SDK key from the dashboard, and it belongs in the page:
|
|
55
|
+
it is scoped to the origins you list, which is what makes it safe there. A
|
|
56
|
+
**secret** key is refused if it arrives with an `Origin`, so pasting one here
|
|
57
|
+
does not work by design.
|
|
58
|
+
|
|
59
|
+
Setting up collects nothing. It makes the client reachable and no more; when to
|
|
60
|
+
identify is the page's decision. Like every Svelte context call it has to run
|
|
61
|
+
during component initialisation: a `<script>` block, not an event handler and
|
|
62
|
+
not an `$effect`.
|
|
63
|
+
|
|
64
|
+
Consent defaults to `pending`, and nothing is collected or sent until it is
|
|
65
|
+
`granted`. A page with a consent banner leaves it `pending` and calls
|
|
66
|
+
`setConsent('granted')` once the banner is accepted; see
|
|
67
|
+
[Waiting for consent](#waiting-for-consent).
|
|
68
|
+
|
|
69
|
+
## Identify
|
|
70
|
+
|
|
71
|
+
```svelte
|
|
72
|
+
<script lang="ts">
|
|
73
|
+
import { useIdentify } from '@fingerly/svelte'
|
|
74
|
+
|
|
75
|
+
const fingerly = useIdentify()
|
|
76
|
+
|
|
77
|
+
async function submit() {
|
|
78
|
+
await fingerly.identify()
|
|
79
|
+
|
|
80
|
+
if (fingerly.isSuspicious) {
|
|
81
|
+
// step up to MFA, hold for review, add friction
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
</script>
|
|
85
|
+
|
|
86
|
+
<button onclick={submit} disabled={fingerly.isLoading}>
|
|
87
|
+
{fingerly.isLoading ? 'Checking…' : 'Continue'}
|
|
88
|
+
</button>
|
|
89
|
+
|
|
90
|
+
{#if fingerly.error}<p>{fingerly.error.message}</p>{/if}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`identify()` collects and submits, and resolves with the server's answer in the
|
|
94
|
+
same round trip: the `requestId`, who the visitor is (`visitorId`), and the
|
|
95
|
+
`suspectScore` and `suspectLevel`, unless the key hides them. Nothing is decided
|
|
96
|
+
in the page: scoring lives on the server, under the weights you set.
|
|
97
|
+
|
|
98
|
+
### On mount instead
|
|
99
|
+
|
|
100
|
+
```svelte
|
|
101
|
+
<script lang="ts">
|
|
102
|
+
const fingerly = useIdentify({ immediate: true })
|
|
103
|
+
</script>
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
`immediate` runs in an `$effect`, which is what makes it **safe under SSR**:
|
|
107
|
+
effects do not run during a server render, so a SvelteKit page using this
|
|
108
|
+
renders on the server and collects on the client with no guard of its own.
|
|
109
|
+
|
|
110
|
+
Pass it in as many components as want it. The state is shared, so the second
|
|
111
|
+
and third callers get the first one's answer rather than starting their own
|
|
112
|
+
submission.
|
|
113
|
+
|
|
114
|
+
## One identification per page
|
|
115
|
+
|
|
116
|
+
The state lives in context, not in each `useIdentify()` call. Three components
|
|
117
|
+
asking whether the visitor is suspicious produce **one** submission, one
|
|
118
|
+
`requestId`, and one line on your bill:
|
|
119
|
+
|
|
120
|
+
```svelte
|
|
121
|
+
<!-- All three of Header.svelte, CheckoutForm.svelte, RiskBanner.svelte: -->
|
|
122
|
+
const fingerly = useIdentify({ immediate: true })
|
|
123
|
+
<!-- → one network request, one shared answer -->
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Context rather than a module-level singleton, and the reason is the server: a
|
|
127
|
+
module-level state on a SvelteKit server is shared by every request the process
|
|
128
|
+
renders. Context is per component tree, and a component tree is per request.
|
|
129
|
+
|
|
130
|
+
To deliberately identify again (a long-lived app reaching a second checkout):
|
|
131
|
+
|
|
132
|
+
```svelte
|
|
133
|
+
await fingerly.refresh() // ignores the cached result and collects afresh
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Reading the answer
|
|
137
|
+
|
|
138
|
+
`suspectLevel` is the server's band for this submission, under the weights you
|
|
139
|
+
set. `isSuspicious` is `true` for `medium` or `high`, `false` for `low`, and
|
|
140
|
+
`null` when the level is absent: no server has answered yet, the submission went
|
|
141
|
+
unscored, or the SDK key hides the score from the page, which cannot tell those
|
|
142
|
+
apart. Null is not a clean result.
|
|
143
|
+
|
|
144
|
+
Signals are read on your backend, by `requestId`, never in the page: which check
|
|
145
|
+
tripped is what a fraudster wants to learn.
|
|
146
|
+
|
|
147
|
+
## A correlation tag
|
|
148
|
+
|
|
149
|
+
Echoed back on the finished event so you can match a submission to whatever the
|
|
150
|
+
page was doing. It accepts a getter, and is read at submission time rather than
|
|
151
|
+
at initialisation:
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
const fingerly = useIdentify({ tag: () => `checkout:${page.params.orderId}` })
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Collect without submitting
|
|
158
|
+
|
|
159
|
+
For a debug page that wants the raw report and nothing else:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
setupFingerly({ apiKey: 'fly_pk_production_…', submit: false })
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Everything the server decides comes back empty: no `requestId`, no `visitorId`,
|
|
166
|
+
`suspectScore` is `null` rather than `0`, and `isSuspicious` is
|
|
167
|
+
`null` rather than `false`. That is the honest answer rather than a gap: nothing
|
|
168
|
+
was sent, so nobody scored it, and this SDK decides nothing on its own.
|
|
169
|
+
|
|
170
|
+
## Waiting for consent
|
|
171
|
+
|
|
172
|
+
If identifying a visitor needs their consent first, set up with `consent:
|
|
173
|
+
'pending'`, the default. Until it is `granted` nothing is collected and nothing is sent:
|
|
174
|
+
`useIdentify({ immediate: true })` waits, and the client is not even built.
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
const fingerly = setupFingerly({ apiKey: 'fly_pk_production_…', consent: 'pending' })
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Then set it from wherever your consent tool reports the answer:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
fingerly.setConsent('granted') // from the consent tool's callback
|
|
184
|
+
|
|
185
|
+
const client = await fingerly.client()
|
|
186
|
+
client.setConsent('denied') // the same, on the client itself
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
- `consent`: `'pending'` (the default), `'granted'` or `'denied'`, an option to
|
|
190
|
+
`setupFingerly()` and `createFingerly()`.
|
|
191
|
+
- `setConsent(state)`: on the object `setupFingerly()`, `useFingerly()` and
|
|
192
|
+
`useIdentify()` return, and on the client. Synchronous, and setting the
|
|
193
|
+
current value again does nothing.
|
|
194
|
+
- `fingerly.consent`: the current state, reactive, for rendering a banner.
|
|
195
|
+
|
|
196
|
+
Setting `granted` starts the identification that was waiting, once. `pending`
|
|
197
|
+
and `denied` behave the same. Withdrawing consent while an identification is
|
|
198
|
+
running stops it before it submits, and it fails with a `ConsentError`.
|
|
199
|
+
|
|
200
|
+
## What you get back
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
const fingerly = useIdentify()
|
|
204
|
+
|
|
205
|
+
fingerly.requestId // string | null: identifies this submission
|
|
206
|
+
fingerly.visitorId // string | null: who the server decided this is
|
|
207
|
+
fingerly.visitorIsNew // boolean: never seen before
|
|
208
|
+
fingerly.visitorConfidence // number: 0 to 100
|
|
209
|
+
fingerly.identifiable // boolean: false when the signals were too thin
|
|
210
|
+
fingerly.duplicate // boolean: answered before; this is the first answer
|
|
211
|
+
fingerly.state // string | null: the server's disposition
|
|
212
|
+
fingerly.reason // string | null: always null (deprecated); your backend reads it on the event
|
|
213
|
+
fingerly.suspectScore // number | null: null when nothing scored it
|
|
214
|
+
fingerly.suspectLevel // string | null: low, medium, high
|
|
215
|
+
fingerly.report // SignalReport | null: every source, with status and timing
|
|
216
|
+
fingerly.error // Error | null
|
|
217
|
+
fingerly.consent // ConsentState (granted, pending or denied)
|
|
218
|
+
fingerly.isLoading // boolean
|
|
219
|
+
fingerly.isReady // boolean: finished, successfully or not
|
|
220
|
+
fingerly.isSuspicious // boolean | null: true for medium or high; null when the level is absent
|
|
221
|
+
fingerly.identify() // Promise<IdentifyResult>
|
|
222
|
+
fingerly.refresh() // Promise<IdentifyResult>
|
|
223
|
+
fingerly.setConsent('granted')
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Every field is a getter over a rune, so reading one in a template subscribes to
|
|
227
|
+
it and reading one in an event handler gets the current value. None of them is
|
|
228
|
+
settable: the state is shared, so a component that could assign to it would be
|
|
229
|
+
changing what every other component sees.
|
|
230
|
+
|
|
231
|
+
Weights and signal names never reach the browser: your backend reads them on the
|
|
232
|
+
server-side event read.
|
|
233
|
+
|
|
234
|
+
The detectors run on the server, over the report this package sends, so rules
|
|
235
|
+
improve without every integration redeploying. Everything here that says
|
|
236
|
+
anything about a visitor came from the server.
|
|
237
|
+
|
|
238
|
+
## The visitor is never asked for anything
|
|
239
|
+
|
|
240
|
+
No permission prompt, no picker, no dialog, on any browser. Reading a
|
|
241
|
+
permission's *state* prompts nobody and is used freely; requesting is banned
|
|
242
|
+
outright and enforced by a test in `@fingerly/web-js`. The one API that prompts on
|
|
243
|
+
some browsers (canvas readback, which raises a doorhanger in Tor Browser) is
|
|
244
|
+
skipped when the SDK measures a clamped clock.
|
|
245
|
+
|
|
246
|
+
You can drop this into a checkout without it ever interrupting the checkout.
|
|
247
|
+
|
|
248
|
+
## Errors
|
|
249
|
+
|
|
250
|
+
`identify()` both stores the error and rethrows it, so either style works:
|
|
251
|
+
|
|
252
|
+
```ts
|
|
253
|
+
try {
|
|
254
|
+
await fingerly.identify()
|
|
255
|
+
} catch (error) {
|
|
256
|
+
// your own handling
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
```svelte
|
|
261
|
+
{#if fingerly.error}<p>{fingerly.error.message}</p>{/if}
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
A failed identification is not repeated behind your back. When the server
|
|
265
|
+
answers `429` with `Retry-After`, every call, `refresh()` included, gets the
|
|
266
|
+
same error until that time has passed; the error carries it as
|
|
267
|
+
`retryAfterMs`. After a transient failure without one (a `5xx`, a network
|
|
268
|
+
error), components that identify automatically wait 5 seconds, doubling per
|
|
269
|
+
consecutive failure up to a minute, so route changes during an outage send
|
|
270
|
+
nothing; a call you make yourself, such as on a click, still tries at once.
|
|
271
|
+
Any other failure, such as a wrong key, is tried again on the next call.
|
|
272
|
+
|
|
273
|
+
`TransportError` carries a `status`. The two worth branching on are `401` (the
|
|
274
|
+
key is wrong, or was used from an origin it does not list) and `402` (the
|
|
275
|
+
organisation is not accepting traffic). Both are your configuration rather than
|
|
276
|
+
the visitor's.
|
|
277
|
+
|
|
278
|
+
`ConsentError` means consent is not `granted`. It carries `code:
|
|
279
|
+
'consent_required'` and the `state`, and lands in `error` like any other
|
|
280
|
+
failure. `{ immediate: true }` waits for consent rather than producing one, so
|
|
281
|
+
it only sees this error when consent is withdrawn while it runs.
|
|
282
|
+
|
|
283
|
+
Calling `identify()` during SSR rejects with `FingerlyServerError` and a message
|
|
284
|
+
saying what to do instead. Use `{ immediate: true }`, which already waits for
|
|
285
|
+
the client.
|
|
286
|
+
|
|
287
|
+
## Running the playground
|
|
288
|
+
|
|
289
|
+
`playground/` is this package's own state and hooks driving the real SDK (no
|
|
290
|
+
mocks), showing `suspectScore` and `suspectLevel` beside the raw
|
|
291
|
+
report, all sharing one identification. It uses `submit: false`, so no server
|
|
292
|
+
answers: the raw report fills in, and the score and level read hidden.
|
|
293
|
+
|
|
294
|
+
```
|
|
295
|
+
pnpm --filter @fingerly/svelte playground # http://localhost:4176
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
## A note on the build
|
|
299
|
+
|
|
300
|
+
The package is emitted by `tsc`, not bundled, and that is a requirement rather
|
|
301
|
+
than a preference. The runes in `*.svelte.js` are compiled by the *app's*
|
|
302
|
+
Svelte plugin, which decides what to compile by the file name. Bundling them
|
|
303
|
+
into an `index.js` would hand the app a file full of `$state(…)` that nothing
|
|
304
|
+
compiles, and `$state is not defined` at runtime.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Putting the state where every component can reach it.
|
|
3
|
+
*
|
|
4
|
+
* Svelte's context rather than a module-level singleton, and the reason is the
|
|
5
|
+
* server. A module-level state on a SvelteKit server is shared by every
|
|
6
|
+
* request the process renders, which is the one way this package could leak
|
|
7
|
+
* one visitor's report into another visitor's page. Context is per component
|
|
8
|
+
* tree, and a component tree is per request.
|
|
9
|
+
*/
|
|
10
|
+
import { type Fingerly, type FingerlyOptions } from './state.svelte.js';
|
|
11
|
+
/**
|
|
12
|
+
* The context key.
|
|
13
|
+
*
|
|
14
|
+
* A symbol, so nothing else can collide with it, and exported so an advanced
|
|
15
|
+
* caller can reach the state with `getContext()` directly.
|
|
16
|
+
*/
|
|
17
|
+
export declare const FINGERLY_KEY: unique symbol;
|
|
18
|
+
/**
|
|
19
|
+
* Create the state and put it in context. Call it once, high up.
|
|
20
|
+
*
|
|
21
|
+
* ```svelte
|
|
22
|
+
* <!-- +layout.svelte -->
|
|
23
|
+
* <script lang="ts">
|
|
24
|
+
* import { setupFingerly } from '@fingerly/svelte'
|
|
25
|
+
* setupFingerly({ apiKey: 'fly_pk_production_…' })
|
|
26
|
+
* </script>
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* Like every Svelte context call, it has to run during component
|
|
30
|
+
* initialisation - not in an event handler, and not in an `$effect`.
|
|
31
|
+
*
|
|
32
|
+
* Nothing is collected here. When to identify stays the page's decision.
|
|
33
|
+
*/
|
|
34
|
+
export declare function setupFingerly(options: FingerlyOptions): Fingerly;
|
|
35
|
+
/**
|
|
36
|
+
* The state `setupFingerly()` put in context.
|
|
37
|
+
*
|
|
38
|
+
* The error is worth its length: a missing setup otherwise surfaces as
|
|
39
|
+
* "cannot read properties of undefined" inside a function the caller did not
|
|
40
|
+
* write, and the fix - one call in a layout - is not guessable from that.
|
|
41
|
+
*/
|
|
42
|
+
export declare function useFingerly(): Fingerly;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Putting the state where every component can reach it.
|
|
3
|
+
*
|
|
4
|
+
* Svelte's context rather than a module-level singleton, and the reason is the
|
|
5
|
+
* server. A module-level state on a SvelteKit server is shared by every
|
|
6
|
+
* request the process renders, which is the one way this package could leak
|
|
7
|
+
* one visitor's report into another visitor's page. Context is per component
|
|
8
|
+
* tree, and a component tree is per request.
|
|
9
|
+
*/
|
|
10
|
+
import { getContext, hasContext, setContext } from 'svelte';
|
|
11
|
+
import { createFingerly } from './state.svelte.js';
|
|
12
|
+
/**
|
|
13
|
+
* The context key.
|
|
14
|
+
*
|
|
15
|
+
* A symbol, so nothing else can collide with it, and exported so an advanced
|
|
16
|
+
* caller can reach the state with `getContext()` directly.
|
|
17
|
+
*/
|
|
18
|
+
export const FINGERLY_KEY = Symbol('fingerly');
|
|
19
|
+
/**
|
|
20
|
+
* Create the state and put it in context. Call it once, high up.
|
|
21
|
+
*
|
|
22
|
+
* ```svelte
|
|
23
|
+
* <!-- +layout.svelte -->
|
|
24
|
+
* <script lang="ts">
|
|
25
|
+
* import { setupFingerly } from '@fingerly/svelte'
|
|
26
|
+
* setupFingerly({ apiKey: 'fly_pk_production_…' })
|
|
27
|
+
* </script>
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* Like every Svelte context call, it has to run during component
|
|
31
|
+
* initialisation - not in an event handler, and not in an `$effect`.
|
|
32
|
+
*
|
|
33
|
+
* Nothing is collected here. When to identify stays the page's decision.
|
|
34
|
+
*/
|
|
35
|
+
export function setupFingerly(options) {
|
|
36
|
+
const fingerly = createFingerly(options);
|
|
37
|
+
setContext(FINGERLY_KEY, fingerly);
|
|
38
|
+
return fingerly;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The state `setupFingerly()` put in context.
|
|
42
|
+
*
|
|
43
|
+
* The error is worth its length: a missing setup otherwise surfaces as
|
|
44
|
+
* "cannot read properties of undefined" inside a function the caller did not
|
|
45
|
+
* write, and the fix - one call in a layout - is not guessable from that.
|
|
46
|
+
*/
|
|
47
|
+
export function useFingerly() {
|
|
48
|
+
if (!hasContext(FINGERLY_KEY)) {
|
|
49
|
+
throw new Error('No Fingerly context. Call setupFingerly() in a component above this one:\n\n' +
|
|
50
|
+
" import { setupFingerly } from '@fingerly/svelte'\n" +
|
|
51
|
+
" setupFingerly({ apiKey: 'fly_pk_production_…' })\n\n" +
|
|
52
|
+
'It has to run during component initialisation - a <script> block, not an ' +
|
|
53
|
+
'event handler or an $effect.');
|
|
54
|
+
}
|
|
55
|
+
return getContext(FINGERLY_KEY);
|
|
56
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
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
|
+
*/
|
|
11
|
+
import type { Fingerly } from './state.svelte.js';
|
|
12
|
+
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
|
+
*/
|
|
27
|
+
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
|
+
*/
|
|
35
|
+
tag?: string | (() => string | undefined);
|
|
36
|
+
}
|
|
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
|
+
export declare function useIdentify(options?: UseIdentifyOptions): Fingerly;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
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
|
+
*/
|
|
11
|
+
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
|
+
export function useIdentify(options = {}) {
|
|
30
|
+
const fingerly = useFingerly();
|
|
31
|
+
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.
|
|
36
|
+
const identify = (callOptions = {}) => {
|
|
37
|
+
const tag = resolveTag(callOptions.tag);
|
|
38
|
+
return fingerly.identify({
|
|
39
|
+
...(tag === undefined ? {} : { tag }),
|
|
40
|
+
...(callOptions.force === undefined ? {} : { force: callOptions.force }),
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
const refresh = (callOptions = {}) => identify({ ...callOptions, force: true });
|
|
44
|
+
if (options.immediate) {
|
|
45
|
+
$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
|
+
if (fingerly.consent !== 'granted')
|
|
50
|
+
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
|
+
const tag = resolveTag();
|
|
58
|
+
void fingerly.identify({ ...(tag === undefined ? {} : { tag }), automatic: true }).catch(() => undefined);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
get requestId() {
|
|
63
|
+
return fingerly.requestId;
|
|
64
|
+
},
|
|
65
|
+
get visitorId() {
|
|
66
|
+
return fingerly.visitorId;
|
|
67
|
+
},
|
|
68
|
+
get visitorIsNew() {
|
|
69
|
+
return fingerly.visitorIsNew;
|
|
70
|
+
},
|
|
71
|
+
get visitorConfidence() {
|
|
72
|
+
return fingerly.visitorConfidence;
|
|
73
|
+
},
|
|
74
|
+
get identifiable() {
|
|
75
|
+
return fingerly.identifiable;
|
|
76
|
+
},
|
|
77
|
+
get duplicate() {
|
|
78
|
+
return fingerly.duplicate;
|
|
79
|
+
},
|
|
80
|
+
get state() {
|
|
81
|
+
return fingerly.state;
|
|
82
|
+
},
|
|
83
|
+
get reason() {
|
|
84
|
+
return fingerly.reason;
|
|
85
|
+
},
|
|
86
|
+
get suspectScore() {
|
|
87
|
+
return fingerly.suspectScore;
|
|
88
|
+
},
|
|
89
|
+
get suspectLevel() {
|
|
90
|
+
return fingerly.suspectLevel;
|
|
91
|
+
},
|
|
92
|
+
get report() {
|
|
93
|
+
return fingerly.report;
|
|
94
|
+
},
|
|
95
|
+
get error() {
|
|
96
|
+
return fingerly.error;
|
|
97
|
+
},
|
|
98
|
+
get isLoading() {
|
|
99
|
+
return fingerly.isLoading;
|
|
100
|
+
},
|
|
101
|
+
get isReady() {
|
|
102
|
+
return fingerly.isReady;
|
|
103
|
+
},
|
|
104
|
+
get isSuspicious() {
|
|
105
|
+
return fingerly.isSuspicious;
|
|
106
|
+
},
|
|
107
|
+
get consent() {
|
|
108
|
+
return fingerly.consent;
|
|
109
|
+
},
|
|
110
|
+
setConsent: fingerly.setConsent,
|
|
111
|
+
identify,
|
|
112
|
+
refresh,
|
|
113
|
+
client: fingerly.client,
|
|
114
|
+
};
|
|
115
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
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.
|
|
10
|
+
*/
|
|
11
|
+
export { FINGERLY_KEY, setupFingerly, useFingerly } from './context.js';
|
|
12
|
+
export { createFingerly, FingerlyServerError } from './state.svelte.js';
|
|
13
|
+
export type { Fingerly, FingerlyOptions } from './state.svelte.js';
|
|
14
|
+
export { useIdentify } from './hooks.svelte.js';
|
|
15
|
+
export type { UseIdentifyOptions } from './hooks.svelte.js';
|
|
16
|
+
export type { FingerlyWebEvent, Confidence, ConsentState, IdentifyResult, IntegrityReport, Lie, SignalOutcome, SignalReport, SignalStatus, } from '@fingerly/web-js';
|
|
17
|
+
export { ConsentError, TransportError } from '@fingerly/web-js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
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.
|
|
10
|
+
*/
|
|
11
|
+
export { FINGERLY_KEY, setupFingerly, useFingerly } from './context.js';
|
|
12
|
+
export { createFingerly, FingerlyServerError } from './state.svelte.js';
|
|
13
|
+
export { useIdentify } from './hooks.svelte.js';
|
|
14
|
+
export { ConsentError, TransportError } from '@fingerly/web-js';
|
|
@@ -0,0 +1,149 @@
|
|
|
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.
|
|
16
|
+
*/
|
|
17
|
+
import { type ConsentState, type FingerlyClient, type IdentifyResult, type SignalReport } from '@fingerly/web-js';
|
|
18
|
+
/** Options for [[createFingerly]] and [[setupFingerly]]. */
|
|
19
|
+
export interface FingerlyOptions {
|
|
20
|
+
/** The SDK key from the dashboard. A public key is safe in a page. */
|
|
21
|
+
apiKey: string;
|
|
22
|
+
/** Origin of the API. Defaults to production. */
|
|
23
|
+
/** API route version. Defaults to v1. */
|
|
24
|
+
apiVersion?: string;
|
|
25
|
+
endpoint?: string;
|
|
26
|
+
endpoints?: string | readonly string[];
|
|
27
|
+
fallbackToDefaultEndpoint?: boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Collect without submitting anything.
|
|
30
|
+
*
|
|
31
|
+
* Everything the server decides comes back empty: no `requestId`, no
|
|
32
|
+
* `visitorId`, no `suspectScore`, no `suspectLevel`. That is the honest
|
|
33
|
+
* answer rather than a gap - nothing was sent, so nobody scored it, and
|
|
34
|
+
* this SDK decides nothing on its own.
|
|
35
|
+
*/
|
|
36
|
+
submit?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Whether the visitor has agreed to be identified. Defaults to `pending`.
|
|
39
|
+
*
|
|
40
|
+
* Leave it `pending` while identification waits on a consent banner, then
|
|
41
|
+
* call [[Fingerly.setConsent]] when it is answered, or pass `granted`
|
|
42
|
+
* once you have consent (or another lawful basis). Until then nothing is
|
|
43
|
+
* collected or sent: `useIdentify({ immediate: true })` waits, and a manual
|
|
44
|
+
* `identify()` fails with a `ConsentError` in `error`.
|
|
45
|
+
*/
|
|
46
|
+
consent?: ConsentState;
|
|
47
|
+
}
|
|
48
|
+
/** What a component reads. Every field is reactive; none of them is settable. */
|
|
49
|
+
export interface Fingerly {
|
|
50
|
+
readonly requestId: string | null;
|
|
51
|
+
/**
|
|
52
|
+
* Who the server decided this is. Null under `submit: false`, and null
|
|
53
|
+
* before the first identification - never empty-string, so a template can
|
|
54
|
+
* ask `fingerly.visitorId` without also asking whether it means anything.
|
|
55
|
+
*/
|
|
56
|
+
readonly visitorId: string | null;
|
|
57
|
+
/** True when the server had never seen this visitor before. */
|
|
58
|
+
readonly visitorIsNew: boolean;
|
|
59
|
+
/** How sure the server is of `visitorId`, 0-100. */
|
|
60
|
+
readonly visitorConfidence: number;
|
|
61
|
+
/** False when the signals were too thin to identify anybody. */
|
|
62
|
+
readonly identifiable: boolean;
|
|
63
|
+
/** True when this submission had already been answered. */
|
|
64
|
+
readonly duplicate: boolean;
|
|
65
|
+
/** The server's disposition of the check. */
|
|
66
|
+
readonly state: string | null;
|
|
67
|
+
/**
|
|
68
|
+
* @deprecated Always `null`. A browser is no longer told why a check went
|
|
69
|
+
* unscored; your backend reads `reason` on the server-side event read, by
|
|
70
|
+
* `requestId`. Kept so code written against 0.1.0 still compiles.
|
|
71
|
+
*/
|
|
72
|
+
readonly reason: string | null;
|
|
73
|
+
/**
|
|
74
|
+
* The server's score, 0-100, or null when it did not score.
|
|
75
|
+
*
|
|
76
|
+
* Null and zero are different answers: null is "not scored", zero is
|
|
77
|
+
* "scored, nothing found". Do not collapse them with `?? 0`.
|
|
78
|
+
*/
|
|
79
|
+
readonly suspectScore: number | null;
|
|
80
|
+
/** The score as a band - `low`, `medium`, `high`. Null when unscored. */
|
|
81
|
+
readonly suspectLevel: string | null;
|
|
82
|
+
readonly report: SignalReport | null;
|
|
83
|
+
readonly error: Error | null;
|
|
84
|
+
readonly isLoading: boolean;
|
|
85
|
+
/** True once an identification has completed, successfully or not. */
|
|
86
|
+
readonly isReady: boolean;
|
|
87
|
+
/**
|
|
88
|
+
* True when the server scored this `medium` or `high` under the weights you
|
|
89
|
+
* set: the "should I even look?" flag, and not a policy. `null` when no
|
|
90
|
+
* server has answered or the level is absent (not identified yet, `submit:
|
|
91
|
+
* false`, unscored, or hidden by the key), which is not a clean result.
|
|
92
|
+
* Anything more nuanced reads `suspectLevel`, or your backend reads the signals.
|
|
93
|
+
*/
|
|
94
|
+
readonly isSuspicious: boolean | null;
|
|
95
|
+
/**
|
|
96
|
+
* Whether the visitor has agreed to be identified, as last set here or on
|
|
97
|
+
* the client. Automatic identification waits for `granted`.
|
|
98
|
+
*/
|
|
99
|
+
readonly consent: ConsentState;
|
|
100
|
+
/**
|
|
101
|
+
* Record the visitor's consent, as the consent tool reports it.
|
|
102
|
+
*
|
|
103
|
+
* Usable before the client exists - during SSR, or before anything has
|
|
104
|
+
* identified - and forwarded to it once it does. Setting `granted` is what
|
|
105
|
+
* starts any `useIdentify({ immediate: true })` that was waiting for it.
|
|
106
|
+
* The client's own `setConsent()` does the same.
|
|
107
|
+
*/
|
|
108
|
+
setConsent(state: ConsentState): void;
|
|
109
|
+
/** Collect, score and submit. Reuses a completed run unless `force`. */
|
|
110
|
+
identify(options?: {
|
|
111
|
+
tag?: string;
|
|
112
|
+
force?: boolean;
|
|
113
|
+
automatic?: boolean;
|
|
114
|
+
}): Promise<IdentifyResult>;
|
|
115
|
+
/** Identify again from scratch, ignoring any previous result. */
|
|
116
|
+
refresh(options?: {
|
|
117
|
+
tag?: string;
|
|
118
|
+
}): Promise<IdentifyResult>;
|
|
119
|
+
/** The underlying client, built on first use. */
|
|
120
|
+
client(): Promise<FingerlyClient>;
|
|
121
|
+
}
|
|
122
|
+
/** Thrown when the SDK is asked to collect somewhere there is no browser. */
|
|
123
|
+
export declare class FingerlyServerError extends Error {
|
|
124
|
+
readonly name = "FingerlyServerError";
|
|
125
|
+
constructor();
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Build the state.
|
|
129
|
+
*
|
|
130
|
+
* Nothing is collected here. Creating it only makes the client reachable - a
|
|
131
|
+
* factory that fingerprinted as it ran would collect during a server render
|
|
132
|
+
* and take the choice of *when* away from the page that knows.
|
|
133
|
+
*/
|
|
134
|
+
/**
|
|
135
|
+
* How long a failed identification holds off the next one.
|
|
136
|
+
*
|
|
137
|
+
* Without this a failure was forgotten at once, and every component mounting
|
|
138
|
+
* with `immediate` started another identification - three requests per route
|
|
139
|
+
* change while the API was answering 429. A `Retry-After` the server sent
|
|
140
|
+
* holds every call, forced or not, until it passes. A transient failure
|
|
141
|
+
* without one (a 5xx, a network error) holds automatic calls only, for 5 s
|
|
142
|
+
* doubling per consecutive failure up to a minute; a click still tries at
|
|
143
|
+
* once. Anything else holds nothing.
|
|
144
|
+
*/
|
|
145
|
+
export declare function failureHold(error: unknown, consecutive: number, now: number): {
|
|
146
|
+
until: number;
|
|
147
|
+
automaticUntil: number;
|
|
148
|
+
};
|
|
149
|
+
export declare function createFingerly(options: FingerlyOptions): Fingerly;
|
|
@@ -0,0 +1,228 @@
|
|
|
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.
|
|
16
|
+
*/
|
|
17
|
+
import { isSuspiciousLevel, load, } from '@fingerly/web-js';
|
|
18
|
+
/** Thrown when the SDK is asked to collect somewhere there is no browser. */
|
|
19
|
+
export class FingerlyServerError extends Error {
|
|
20
|
+
name = 'FingerlyServerError';
|
|
21
|
+
constructor() {
|
|
22
|
+
super('Fingerly collects signals from a browser and cannot run during server-side rendering. ' +
|
|
23
|
+
'Call identify() from an $effect, or pass { immediate: true } to useIdentify(), ' +
|
|
24
|
+
'which already waits for the client.');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
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
|
+
export function failureHold(error, consecutive, now) {
|
|
46
|
+
const failure = error;
|
|
47
|
+
const retryAfter = typeof failure?.retryAfterMs === 'number' && failure.retryAfterMs > 0 ? failure.retryAfterMs : 0;
|
|
48
|
+
const backoff = failure?.retryable === true ? Math.min(60_000, 5_000 * 2 ** Math.max(0, consecutive - 1)) : 0;
|
|
49
|
+
return { until: now + retryAfter, automaticUntil: now + Math.max(retryAfter, backoff) };
|
|
50
|
+
}
|
|
51
|
+
export function createFingerly(options) {
|
|
52
|
+
let requestId = $state(null);
|
|
53
|
+
let visitorId = $state(null);
|
|
54
|
+
let visitorIsNew = $state(false);
|
|
55
|
+
let visitorConfidence = $state(0);
|
|
56
|
+
let identifiable = $state(false);
|
|
57
|
+
let duplicate = $state(false);
|
|
58
|
+
let checkState = $state(null);
|
|
59
|
+
let suspectScore = $state(null);
|
|
60
|
+
let suspectLevel = $state(null);
|
|
61
|
+
let report = $state(null);
|
|
62
|
+
let error = $state(null);
|
|
63
|
+
let isLoading = $state(false);
|
|
64
|
+
let consent = $state(options.consent ?? 'pending');
|
|
65
|
+
const isReady = $derived(report !== null || error !== null);
|
|
66
|
+
const isSuspicious = $derived(isSuspiciousLevel(suspectLevel));
|
|
67
|
+
let clientPromise;
|
|
68
|
+
let loaded;
|
|
69
|
+
let current;
|
|
70
|
+
let held;
|
|
71
|
+
let consecutiveFailures = 0;
|
|
72
|
+
const mirrorConsent = (next) => {
|
|
73
|
+
consent = next;
|
|
74
|
+
};
|
|
75
|
+
const client = () => {
|
|
76
|
+
if (typeof window === 'undefined')
|
|
77
|
+
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
|
+
clientPromise ??= Promise.resolve().then(() => load({
|
|
84
|
+
apiKey: options.apiKey,
|
|
85
|
+
...(options.endpoint === undefined ? {} : { endpoint: options.endpoint }),
|
|
86
|
+
...(options.apiVersion === undefined ? {} : { apiVersion: options.apiVersion }),
|
|
87
|
+
...(options.endpoints === undefined ? {} : { endpoints: options.endpoints }),
|
|
88
|
+
...(options.fallbackToDefaultEndpoint === undefined ? {} : { fallbackToDefaultEndpoint: options.fallbackToDefaultEndpoint }),
|
|
89
|
+
consent,
|
|
90
|
+
}).then((fingerly) => {
|
|
91
|
+
// Caught up before anything can identify through it: setConsent() may
|
|
92
|
+
// have been called while load() was settling.
|
|
93
|
+
if (fingerly.consent !== consent)
|
|
94
|
+
fingerly.setConsent(consent);
|
|
95
|
+
// And followed from here on, so a consent tool holding the client itself
|
|
96
|
+
// moves this state - and whatever is waiting on it - as well.
|
|
97
|
+
fingerly.onConsentChange(mirrorConsent);
|
|
98
|
+
loaded = fingerly;
|
|
99
|
+
return fingerly;
|
|
100
|
+
}));
|
|
101
|
+
return clientPromise;
|
|
102
|
+
};
|
|
103
|
+
const setConsent = (next) => {
|
|
104
|
+
// The client first, so it validates the value and has it before an effect
|
|
105
|
+
// reacting to the state below asks it to identify.
|
|
106
|
+
loaded?.setConsent(next);
|
|
107
|
+
mirrorConsent(next);
|
|
108
|
+
};
|
|
109
|
+
const identify = (identifyOptions = {}) => {
|
|
110
|
+
if (typeof window === 'undefined')
|
|
111
|
+
return Promise.reject(new FingerlyServerError());
|
|
112
|
+
// One promise for the page, in flight or already settled, which is what
|
|
113
|
+
// makes `useIdentify({ immediate: true })` safe in as many components as
|
|
114
|
+
// want it.
|
|
115
|
+
//
|
|
116
|
+
// Memoising the promise rather than the report also settles a case the Vue
|
|
117
|
+
// binding had to learn: under `submit: false` there is no requestId, so a
|
|
118
|
+
// cache keyed on one never engages and every component re-collects the
|
|
119
|
+
// whole fingerprint. A promise has an identity either way.
|
|
120
|
+
if (current && !identifyOptions.force)
|
|
121
|
+
return current;
|
|
122
|
+
// Holding off after a failure; see failureHold.
|
|
123
|
+
const now = Date.now();
|
|
124
|
+
if (held && (now < held.until || (identifyOptions.automatic && now < held.automaticUntil))) {
|
|
125
|
+
return Promise.reject(held.error);
|
|
126
|
+
}
|
|
127
|
+
isLoading = true;
|
|
128
|
+
error = null;
|
|
129
|
+
const run = client()
|
|
130
|
+
.then((fingerly) => fingerly.identify({
|
|
131
|
+
...(identifyOptions.tag === undefined ? {} : { tag: identifyOptions.tag }),
|
|
132
|
+
...(options.submit === undefined ? {} : { submit: options.submit }),
|
|
133
|
+
}))
|
|
134
|
+
.then((result) => {
|
|
135
|
+
requestId = result.requestId === '' ? null : result.requestId;
|
|
136
|
+
visitorId = result.visitorId === '' ? null : result.visitorId;
|
|
137
|
+
visitorIsNew = result.visitorIsNew;
|
|
138
|
+
visitorConfidence = result.visitorConfidence;
|
|
139
|
+
identifiable = result.identifiable;
|
|
140
|
+
duplicate = result.duplicate;
|
|
141
|
+
checkState = result.state === '' ? null : result.state;
|
|
142
|
+
suspectScore = result.suspectScore ?? null;
|
|
143
|
+
suspectLevel = result.suspectLevel ?? null;
|
|
144
|
+
report = result.report;
|
|
145
|
+
held = undefined;
|
|
146
|
+
consecutiveFailures = 0;
|
|
147
|
+
return result;
|
|
148
|
+
})
|
|
149
|
+
.catch((cause) => {
|
|
150
|
+
const failure = cause instanceof Error ? cause : new Error(String(cause));
|
|
151
|
+
error = failure;
|
|
152
|
+
consecutiveFailures += 1;
|
|
153
|
+
held = { error: failure, ...failureHold(failure, consecutiveFailures, Date.now()) };
|
|
154
|
+
// Forgotten, so the next caller retries rather than being handed a
|
|
155
|
+
// rejected promise forever.
|
|
156
|
+
if (current === run)
|
|
157
|
+
current = undefined;
|
|
158
|
+
// Rethrown as well as stored: a caller that awaited identify() should
|
|
159
|
+
// be able to try/catch it, and a component that only reads `error`
|
|
160
|
+
// should not have to.
|
|
161
|
+
throw failure;
|
|
162
|
+
})
|
|
163
|
+
.finally(() => {
|
|
164
|
+
isLoading = false;
|
|
165
|
+
});
|
|
166
|
+
current = run;
|
|
167
|
+
return run;
|
|
168
|
+
};
|
|
169
|
+
const refresh = (refreshOptions = {}) => identify({ ...refreshOptions, force: true });
|
|
170
|
+
// Getters rather than fields: reading through one is what subscribes the
|
|
171
|
+
// caller's template to the rune behind it. Returning the values directly
|
|
172
|
+
// would hand out a snapshot taken at the moment this function ran.
|
|
173
|
+
return {
|
|
174
|
+
get requestId() {
|
|
175
|
+
return requestId;
|
|
176
|
+
},
|
|
177
|
+
get visitorId() {
|
|
178
|
+
return visitorId;
|
|
179
|
+
},
|
|
180
|
+
get visitorIsNew() {
|
|
181
|
+
return visitorIsNew;
|
|
182
|
+
},
|
|
183
|
+
get visitorConfidence() {
|
|
184
|
+
return visitorConfidence;
|
|
185
|
+
},
|
|
186
|
+
get identifiable() {
|
|
187
|
+
return identifiable;
|
|
188
|
+
},
|
|
189
|
+
get duplicate() {
|
|
190
|
+
return duplicate;
|
|
191
|
+
},
|
|
192
|
+
get state() {
|
|
193
|
+
return checkState;
|
|
194
|
+
},
|
|
195
|
+
get reason() {
|
|
196
|
+
// Deprecated: the server no longer tells a browser. See the interface.
|
|
197
|
+
return null;
|
|
198
|
+
},
|
|
199
|
+
get suspectScore() {
|
|
200
|
+
return suspectScore;
|
|
201
|
+
},
|
|
202
|
+
get suspectLevel() {
|
|
203
|
+
return suspectLevel;
|
|
204
|
+
},
|
|
205
|
+
get report() {
|
|
206
|
+
return report;
|
|
207
|
+
},
|
|
208
|
+
get error() {
|
|
209
|
+
return error;
|
|
210
|
+
},
|
|
211
|
+
get isLoading() {
|
|
212
|
+
return isLoading;
|
|
213
|
+
},
|
|
214
|
+
get isReady() {
|
|
215
|
+
return isReady;
|
|
216
|
+
},
|
|
217
|
+
get isSuspicious() {
|
|
218
|
+
return isSuspicious;
|
|
219
|
+
},
|
|
220
|
+
get consent() {
|
|
221
|
+
return consent;
|
|
222
|
+
},
|
|
223
|
+
setConsent,
|
|
224
|
+
identify,
|
|
225
|
+
refresh,
|
|
226
|
+
client,
|
|
227
|
+
};
|
|
228
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fingerly/svelte",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"description": "Svelte 5 bindings for the Fingerly SDK",
|
|
8
|
+
"license": "Apache-2.0",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "https://github.com/fingerly-io/sdks.git",
|
|
12
|
+
"directory": "client/web/svelte"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"main": "./dist/index.js",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"svelte": "./dist/index.js",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@fingerly/web-js": "0.1.1"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"svelte": ">=5"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@sveltejs/vite-plugin-svelte": "^4.0.4",
|
|
36
|
+
"svelte": "^5.56.10",
|
|
37
|
+
"typescript": "^5.7.2",
|
|
38
|
+
"vite": "^5.4.21",
|
|
39
|
+
"vitest": "^2.1.8"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsc -p tsconfig.build.json",
|
|
43
|
+
"lint": "tsc --noEmit",
|
|
44
|
+
"test": "vitest run",
|
|
45
|
+
"playground": "vite --config playground/vite.config.ts",
|
|
46
|
+
"demo": "vite --config playground/vite.config.ts"
|
|
47
|
+
}
|
|
6
48
|
}
|