@touchque/device-risk 0.0.0-stage → 3.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file. The
4
+ format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
+
6
+ ## [3.0.0] — 2026-11-24
7
+
8
+ First release of `@touchque/device-risk`: Touchque Device Risk is a separate product with its own SDK. Its
9
+ versions continue the script tag's line (2.x came with `@touchque/web`, which no longer has Device risk).
10
+
11
+ ### Added
12
+ - Everything `@touchque/web` 2.3.0 had for Device risk: `deviceRisk` / `createDeviceRisk` (`identify`,
13
+ `collect`), the script tag (`installDeviceRiskTag`, `touchque-device.global.js`, `dist/device-sri.json`),
14
+ the pointer and input summaries, automation tool marks.
15
+ - **Encrypted reports.** `collect` (and so `identify` and the tag) encrypts the report for Touchque:
16
+ `tqe1.<kid>.<epk>.<iv>.<ct>`, ECDH P-256 with Touchque's report key (`REPORT_KEY`, kid `9d8a2f55`),
17
+ HKDF-SHA256 (salt the one-time public key, info `touchque-device-report:v1`), AES-256-GCM with additional
18
+ data `tqe1.<kid>`. Only Touchque opens it; a changed byte makes it unreadable. Without WebCrypto the plain
19
+ report goes. `encrypt: false` gives the plain one. `sealReport` is exported.
20
+ - **Traits that cannot all be true** (`consistencyFindings`, in `s.tamper`): `ua_engine_mismatch` (the
21
+ JavaScript engine by the wording of one TypeError: iOS and Safari run JavaScriptCore, Chromium V8, Firefox
22
+ Gecko), `gpu_os_mismatch` (a desktop card on an "Android phone", anything but "Apple GPU" on an "iPhone",
23
+ phone chips on a Mac, Apple/Mali/PowerVR on Windows; Adreno allowed on Windows for Snapdragon),
24
+ `fonts_os_mismatch`, `mobile_desktop_mismatch` (a phone with no touch or a mouse only; an iPhone screen over
25
+ 1000 points or under 2x), `ua_platform_mismatch` for an iOS user agent with a Mac platform. In `s.vm`:
26
+ `emulator` (Android Studio, Genymotion, BlueStacks, Nox, LDPlayer, MuMu renderers) and `headless_window`
27
+ (an 800x600 screen with no browser frame: headless Chrome with its automation flag hidden). Checked with
28
+ Puppeteer, Playwright and an Android emulator on 2026-11-24; real Chrome, Firefox and Safari raised nothing.
29
+ - **The first-party cookie.** `identify` sends `credentials: 'same-origin'`: through your own `/_tq/` path,
30
+ Touchque's HttpOnly `_tqd` cookie (Path=/_tq, 400 days) goes there and back, and Safari keeps it past its
31
+ 7-day limit on script storage. To `api.touchque.com` no cookie is sent.
32
+ - `DEVICE_TAG_VERSION` is `3.0.0`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Touchque
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,270 @@
1
- # Temporary Holding Version
1
+ # @touchque/device-risk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Touchque Device Risk for the browser. It recognises the browser on your sign-in, sign-up, password-reset,
4
+ approval and payment pages, gives it a visitor ID of your workspace, and tells bots, emulators, anti-detect
5
+ browsers and spoofed phones apart. The same code is the script tag Touchque serves at
6
+ `https://cdn.touchque.com/device/vX.Y.Z/script.js`.
7
+
8
+ Your server reads what Touchque decided with a Device Risk server package: `@touchque/device-risk-node`,
9
+ `touchque-device-risk` (Python), `touchque/device-risk` (PHP), `touchque-device-risk-go`, `Touchque.DeviceRisk`
10
+ (.NET), `com.touchque:touchque-device-risk` (Java), `touchque-device-risk` (Ruby).
11
+
12
+ Versions continue the tag's line: 3.0.0 is the first release of this package (the tag's 2.x came with
13
+ `@touchque/web`).
14
+
15
+ ## Encrypted reports
16
+
17
+ Every report is signed by the browser's device-bound key and then encrypted for Touchque
18
+ (`tqe1.<kid>.<epk>.<iv>.<ct>`: ECDH P-256 with Touchque's report key, HKDF-SHA256, AES-256-GCM). The page,
19
+ its other scripts, browser extensions and the visitor see an opaque string; only Touchque's servers can
20
+ open it, and a changed byte makes it unreadable. A person who controls the browser can still change values
21
+ before they are encrypted, which is why Touchque checks them against each other, against the request and
22
+ against what it saw before. Without WebCrypto (an http page) the report goes unencrypted.
23
+ `collect({ encrypt: false })` gives the plain report for debugging.
24
+
25
+ ## What it catches
26
+
27
+ Besides the visitor ID: automation (WebDriver, headless Chrome, Playwright, Puppeteer, Selenium marks),
28
+ Android emulators, virtual machines and software graphics, and traits that cannot all be true
29
+ (`consistencyFindings`): a JavaScript engine that is not the claimed browser's, graphics or fonts of
30
+ another platform, a "phone" with no touch or a desktop screen. How the pointer moved and how the page was
31
+ typed into travel as short summaries (counts and milliseconds, never a key or a position).
32
+
33
+ ## Install on a page
34
+ A paid add-on, off until your workspace turns it on (dashboard → Device risk). Every browser that reaches one of
35
+ these pages gets a visitor ID of your workspace, like Fingerprint's `visitorId`, and the risk engine decides whether
36
+ anything about it asks for more.
37
+
38
+ ### One line on the page, one on your server
39
+
40
+ ```html
41
+ <script src="https://cdn.touchque.com/device/v3.0.0/script.js" data-site-key="tqpk_…" data-purpose="sign_in"
42
+ integrity="sha384-…" crossorigin="anonymous" async></script>
43
+ ```
44
+
45
+ ```typescript
46
+ // Your server, when the form arrives (@touchque/device-risk-node; every Device Risk server package has this call):
47
+ const verdict = await deviceRisk.check(req.body.touchque_request_id, { event: 'sign_in', externalUsername });
48
+ if (verdict.stepUp) { /* ask for more: a number-matched approval, a passkey, your emailed code */ }
49
+ ```
50
+
51
+ Pages that already load `…/device.js` (the tag's first name) keep working: the CDN serves the same bytes, with the same
52
+ `integrity`, at both names. The dashboard's Device risk → Settings shows the tag with your site key and this version's `integrity` hash
53
+ (`dist/device-sri.json` in the package; each version has its own path, so the hash never changes under you). The
54
+ tag identifies the browser when the page loads and puts the requestId into a hidden `touchque_request_id` field of
55
+ every form on the page, forms added later included. A form's own `data-touchque-purpose="sign_up"` wins over the
56
+ tag's `data-purpose` (default `sign_in`). Touchque accepts an identification for 15 minutes and for one account: the
57
+ tag takes a new one after 10 minutes, and another after each submit, so a single-page app's next attempt is fresh.
58
+ `data-api` points it at another Touchque API host. Allow the script host in `script-src` and your API host in
59
+ `connect-src` of your Content-Security-Policy.
60
+
61
+ **How the pointer moved.** When a form is sent, the tag adds 18 characters after the requestId and a dot: how the
62
+ pointer and the fingers moved on the page, as counts computed in the browser (`startPointerSummary`): presses on a
63
+ pointer that jumped onto the button and how long they lasted, how close long strokes and swipes came to a ruler line,
64
+ how long taps lasted. Never a position, a path or what was pressed. Software that drives a browser (Playwright,
65
+ Puppeteer, Selenium, AI browser agents) jumps the pointer and presses for 0 to 3 ms; a hand takes 30 ms and more. Pass
66
+ the field to `deviceRisk.check` as it is (45 characters, inside the 64 every server SDK passes on); the risk engine
67
+ weighs it as `device_pointer_synthetic`, a number-matched step-up at most, never a refusal, in shadow until you
68
+ enforce it. No movement at all (a keyboard, a screen reader) is never a sign; Voice Control and Switch Control move
69
+ like software and get the step-up. `data-pointer="off"` on the tag leaves it out. Name it in your privacy notice with
70
+ the rest: the numbers serve the sign-in's security, tell no person from another and are not kept apart from the
71
+ verdict.
72
+
73
+ Single-page apps read `window.TouchqueDevice`: `await TouchqueDevice.ready` (the first identification, or null),
74
+ `TouchqueDevice.value()` (what to send now: the requestId and the pointer summary), `TouchqueDevice.requestId`,
75
+ `TouchqueDevice.refresh()`, and the `touchque:device` event on `document` after each new identification. With npm
76
+ instead of the tag: `installDeviceRiskTag({ siteKey, purpose })` does the same.
77
+
78
+ **What a missing tag gets.** Nothing on the page is trusted. requestIds are made only by Touchque's server, used
79
+ for one account, bound to your site's origin and to 15 minutes; your server reads the verdict by requestId and the
80
+ risk engine decides. A page without the tag, or with it blocked, sends no requestId: `deviceRisk.check` still
81
+ answers (`report: 'missing'`, or `'unknown'` / `'expired'` for one that does not verify) with
82
+ `device_identification_missing`. Ad blockers block such scripts for honest people too, so that signal only ever asks
83
+ for a number-matched step-up, never refuses, and starts in shadow like the others. Removing or blocking the tag
84
+ gets the visitor a step-up at most, never a way past a check.
85
+
86
+ ### From your own domain (first-party)
87
+
88
+ Ad blockers and browser privacy lists drop scripts and calls to known third-party fingerprinting hosts, for honest
89
+ visitors too (they then get `device_identification_missing`, a step-up at most). Big sites serve the tag and its
90
+ identify call from their own domain instead, like Fingerprint's proxy integrations: two paths under `/_tq/` on your
91
+ site, passed on to Touchque.
92
+
93
+ | Your path | Goes to |
94
+ |---|---|
95
+ | `GET /_tq/device/vX.Y.Z/script.js` | `https://cdn.touchque.com/device/vX.Y.Z/script.js` (the same bytes, so the same `integrity`) |
96
+ | `POST /_tq/device-risk/identify` | `https://api.touchque.com/device-risk/identify` |
97
+
98
+ The tag then points at your domain (`data-api` is where it sends the identify call):
99
+
100
+ ```html
101
+ <script src="https://www.example.com/_tq/device/v3.0.0/script.js" data-site-key="tqpk_…" data-purpose="sign_in"
102
+ data-api="https://www.example.com/_tq" integrity="sha384-…" crossorigin="anonymous" async></script>
103
+ ```
104
+
105
+ Your Content-Security-Policy needs only `'self'` for both (`script-src`, `connect-src`).
106
+
107
+ **The proxy secret.** Behind your proxy every visitor reaches Touchque from your proxy's address. Send the visitor's
108
+ address as `X-Touchque-Client-IP` together with your workspace's proxy secret as `X-Touchque-Proxy-Secret`
109
+ (`tqps_…`, dashboard → Device risk → Settings; owners and admins see it, and the API key reads it from
110
+ `GET /device-risk/settings`). Touchque then records and scores the visitor's address and counts the per-address
111
+ limit (60 identifications a minute) on it instead of on your proxy. Keep the secret on the server like the API key:
112
+ an environment variable or a secret store, never in the page or in git. A wrong secret is
113
+ `403 proxy_secret_invalid`; rotating the site key makes a new secret. Without the secret the proxy still works, but
114
+ every visitor counts against the proxy's one address: fine for small sites only. Also pass the visitor's address as
115
+ `clientIp` to `deviceRisk.check` (and `login.request`) on your server. Your own cookies are not needed: drop them
116
+ on the way.
117
+
118
+ **nginx** (in your site's `server` block):
119
+
120
+ ```nginx
121
+ location /_tq/device/ {
122
+ proxy_pass https://cdn.touchque.com/device/;
123
+ proxy_ssl_server_name on;
124
+ proxy_set_header Cookie "";
125
+ proxy_set_header Authorization "";
126
+ }
127
+ location = /_tq/device-risk/identify {
128
+ limit_except POST { deny all; }
129
+ proxy_pass https://api.touchque.com/device-risk/identify;
130
+ proxy_ssl_server_name on;
131
+ proxy_set_header Cookie "";
132
+ proxy_set_header Authorization "";
133
+ proxy_set_header X-Forwarded-For "";
134
+ proxy_set_header X-Touchque-Proxy-Secret "tqps_…"; # from Device risk → Settings; keep this file out of git
135
+ proxy_set_header X-Touchque-Client-IP $remote_addr; # behind a load balancer: set_real_ip_from + real_ip_header first
136
+ }
137
+ ```
138
+
139
+ **Cloudflare Worker** (route `www.example.com/_tq/*`; `wrangler secret put TOUCHQUE_PROXY_SECRET`):
140
+
141
+ ```js
142
+ export default {
143
+ async fetch(request, env) {
144
+ const url = new URL(request.url);
145
+ if (request.method === 'GET' && url.pathname.startsWith('/_tq/device/')) {
146
+ return fetch('https://cdn.touchque.com/device/' + url.pathname.slice('/_tq/device/'.length));
147
+ }
148
+ if (request.method === 'POST' && url.pathname === '/_tq/device-risk/identify') {
149
+ return fetch('https://api.touchque.com/device-risk/identify', {
150
+ method: 'POST',
151
+ headers: {
152
+ 'Content-Type': 'text/plain',
153
+ Origin: request.headers.get('Origin') || '',
154
+ 'X-Touchque-Proxy-Secret': env.TOUCHQUE_PROXY_SECRET,
155
+ 'X-Touchque-Client-IP': request.headers.get('CF-Connecting-IP') || '',
156
+ },
157
+ body: await request.text(),
158
+ });
159
+ }
160
+ return new Response('Not found', { status: 404 });
161
+ },
162
+ };
163
+ ```
164
+
165
+ **Next.js middleware** (`middleware.ts`, on Vercel or your own server; Next.js 16 calls the file `proxy.ts` and the
166
+ function `proxy`; `TOUCHQUE_PROXY_SECRET` in the project's environment variables):
167
+
168
+ ```ts
169
+ import { NextRequest, NextResponse } from 'next/server';
170
+
171
+ export const config = { matcher: '/_tq/:path*' };
172
+
173
+ export async function middleware(req: NextRequest) {
174
+ const { pathname } = req.nextUrl;
175
+ if (req.method === 'GET' && pathname.startsWith('/_tq/device/')) {
176
+ return NextResponse.rewrite(new URL('https://cdn.touchque.com/device/' + pathname.slice('/_tq/device/'.length)));
177
+ }
178
+ if (req.method === 'POST' && pathname === '/_tq/device-risk/identify') {
179
+ const r = await fetch('https://api.touchque.com/device-risk/identify', {
180
+ method: 'POST',
181
+ headers: {
182
+ 'Content-Type': 'text/plain',
183
+ Origin: req.headers.get('origin') ?? '',
184
+ 'X-Touchque-Proxy-Secret': process.env.TOUCHQUE_PROXY_SECRET ?? '',
185
+ // On Vercel the first x-forwarded-for entry is the visitor; behind your own load balancer, its header.
186
+ 'X-Touchque-Client-IP': (req.headers.get('x-forwarded-for') ?? '').split(',')[0].trim(),
187
+ },
188
+ body: await req.text(),
189
+ });
190
+ return new Response(r.body, { status: r.status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } });
191
+ }
192
+ return new Response('Not found', { status: 404 });
193
+ }
194
+ ```
195
+
196
+ If you already have a middleware, add the two `/_tq/` branches at its top and `'/_tq/:path*'` to its matcher.
197
+
198
+ **Vercel rewrites** (`vercel.json`, any framework). A rewrite cannot add the proxy secret, so this suits small sites;
199
+ at volume, use the middleware above (or a Vercel function doing the same) for the identify path:
200
+
201
+ ```json
202
+ {
203
+ "rewrites": [
204
+ { "source": "/_tq/device/:path*", "destination": "https://cdn.touchque.com/device/:path*" },
205
+ { "source": "/_tq/device-risk/identify", "destination": "https://api.touchque.com/device-risk/identify" }
206
+ ]
207
+ }
208
+ ```
209
+
210
+ A Touchque Login custom domain (verified) serves both paths itself: Device risk → Settings then shows the tag with
211
+ `https://login.example.com/_tq`, nothing to proxy. In every case Touchque still checks the page's `Origin` against
212
+ your verified domains and listed origins, so pass `Origin` on unchanged (nginx passes it as it came; the Worker and
213
+ the middleware set it).
214
+
215
+ ### From your own code
216
+
217
+ ```typescript
218
+ import { deviceRisk } from '@touchque/device-risk';
219
+
220
+ // When the form is sent (purpose: 'sign_in' | 'sign_up' | 'password_reset' | 'approval'):
221
+ const id = await deviceRisk.identify({ siteKey: 'tqpk_…', purpose: 'sign_up' });
222
+ // id: { visitorId: 'tqv_…', requestId: 'dre_…', confidence: 0.99 }, or null when Touchque could not be reached
223
+ form.elements.deviceRiskRequestId.value = id?.requestId ?? '';
224
+ ```
225
+
226
+ Never trust the page's copy: your server reads the identification by `requestId` with a server SDK
227
+ (`deviceRisk.getEvent(requestId)`: the visitor, how sure, what the page showed, the risk engine's verdict), checks
228
+ it for an account on sign-up and password-reset pages (`deviceRisk.check(requestId, { event: 'sign_up',
229
+ externalUsername, clientIp })`), and passes it as `deviceRiskRequestId` to `login.request` and `risk.check` on
230
+ sign-in and approval pages. An identification serves one account for 15 minutes; another account gets
231
+ `device_report_replayed`.
232
+
233
+ - **The visitor ID** (`tqv_…`) belongs to your workspace only: another Touchque customer sees another one for the
234
+ same browser. It survives cleared site data, private windows where the browser lets its traits be seen, and browser
235
+ updates. `confidence`: 0.99 when the browser's device-bound key sealed the report, 0.95 its stored id, up to 0.9 a
236
+ match of its traits (lower for identical computers of a fleet), 0.5 to 0.6 a first sight.
237
+ - **Site key and origins:** the site key (`tqpk_…`) is public; Touchque answers only pages on your organization's
238
+ verified domains and their subdomains (Organization → Domains) and on the origins you list (Device risk →
239
+ Settings). The request is a
240
+ `text/plain` POST, so no CORS preflight; allow your Touchque API host in your Content-Security-Policy `connect-src`.
241
+ - **Relay instead:** `deviceRisk.collect({ purpose })` returns the encoded report for your server to pass as
242
+ `deviceRisk`, if your page must not call Touchque itself.
243
+ - **With Touchque's 2FA on the same page:** pass the report to `@touchque/web`'s behavioral widget
244
+ (`attachBehavioral(el, { deviceRiskReport: () => deviceRisk.collect({ purpose: 'sign_in' }) })`).
245
+ - **What it reads:** coarse traits (OS, browser family and major version, time zone, languages, screen size,
246
+ CPU cores, memory class, touch points, the graphics card's name) and short hashes of how the browser draws a
247
+ test text, plays a test sound, which of 25 common fonts it has, a few Math results and its WebGL limits. And
248
+ findings: browser functions replaced by script, traits that contradict each other (an anti-detect browser or
249
+ a spoofing extension), a virtual machine or software graphics, a headless or automated browser, and a private
250
+ window where the browser lets that be seen.
251
+ - **Sealed:** where the browser has a device-bound key (`browserKey`, the silent sign-in key), the report is
252
+ signed with it (`touchque-device:v1`, a different message from a proof's). Touchque then knows it came whole
253
+ from a browser holding that key, from your page's origin, once. A seal does not make the traits true: script
254
+ on the page can lie to its own report, so Touchque checks them against each other, against the address, and
255
+ against the devices it saw before.
256
+ - **What Touchque keeps:** no raw trait. Keyed hashes (HMAC with a key of your workspace alone, so a device is
257
+ never linked across Touchque customers), coarse labels ("Chrome 130 · macOS · laptop"), the account, the
258
+ country and a keyed hash of the address's network, for the 30 to 90 days your workspace sets.
259
+ - **What it does:** the risk engine counts per visitor (accounts, sign-ups, countries, stored-id resets), checks the
260
+ browser's clock against the address and decides. Every signal only ever asks for more (a number-matched approval or
261
+ a passkey; on a sign-up, your own extra check). It never lets anyone skip a check and never blocks on its own.
262
+ Signals start in shadow: reported and counted, asking only on visitors your admin marked "Step up always".
263
+ - **Never respawned:** the stored id lives in `localStorage` only. A cleared browser is matched back by its traits
264
+ on Touchque's side, not by copying the id between stores.
265
+
266
+ **Tell your users.** Use it only on sign-in, sign-up, password-reset and approval pages, and say it in your
267
+ privacy notice. In Turkey (KVKK) account security can rest on legitimate interest (art. 5/2(f)); in the EU,
268
+ reading the device needs consent unless it is strictly necessary for the security of a sign-in the user asked
269
+ for (ePrivacy art. 5(3)), and a check that lets a known device do less does not count. Ask your lawyer. A
270
+ starting text is on the dashboard's Device risk → Settings tab.
@@ -0,0 +1,5 @@
1
+ {
2
+ "version": "3.0.0",
3
+ "src": "https://cdn.touchque.com/device/v3.0.0/script.js",
4
+ "integrity": "sha384-w1C1e4WtBYv45iTHf//fjz6/X0vsAhUvArlvDe/LecDmewsZxD4zOOBByRxvV+aA"
5
+ }