@atol-sh/js 0.1.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,46 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@atol-sh/js` are documented here.
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ No unreleased changes yet.
10
+
11
+ ## [0.1.0] - 2026-07-05
12
+
13
+ Initial release. Framework-agnostic browser security core extracted from
14
+ `@atol-sh/react` so non-React bindings can share the same proven logic.
15
+
16
+ ### Added
17
+
18
+ - `createAtolBrowserAuth`: config-driven browser auth client. OIDC
19
+ Authorization Code + PKCE login, memory-only token storage, DPoP-aware
20
+ `getAccessToken`, proactive + on-demand silent renewal with single-flight
21
+ and cross-tab coordination, RP-initiated logout, and `onSessionChange`
22
+ subscriptions. Cross-tab token adoption is authenticated (ID token
23
+ verified against the IdP JWKS + subject pinning) before any rotated token
24
+ is applied.
25
+ - Renewal model: hidden-iframe silent authentication against the IdP
26
+ session cookie (`prompt=none`) is the default. No refresh token is
27
+ requested or stored, and DPoP still binds the iframe code exchange.
28
+ Opt into refresh tokens with `useRefreshTokens: true` (default `false`)
29
+ only for cross-site apps where third-party-cookie policies block the
30
+ iframe; that appends `offline_access`, renews via the refresh-token
31
+ grant, and revokes the refresh token on logout. Same-site apps (a console
32
+ on a subdomain of the IdP) should leave it `false`.
33
+ - Lower-level primitives: `createDPoPKeyManager` (RFC 9449),
34
+ `verifyIdToken` (JWKS), `createUserManager` / `silentAuthorize` /
35
+ `exchangeCode` / `refreshTokenGrant` / `revokeToken`,
36
+ `createTokenBroadcast`, `withTabLock`, `loadPermissions`, `KEKVault` +
37
+ zero-knowledge encryption helpers, and JWT claim helpers.
38
+ - Optional `@atol-sh/js/device` subpath: `DeviceCollector` and device
39
+ intelligence types, isolating the optional `@atol-sh/fingerprint` peer
40
+ dependency from the core bundle.
41
+ - Dual ESM/CJS build (tsup) with type declarations for both entry points.
42
+ - Tokens are memory-only: access/ID/refresh tokens never touch Web Storage;
43
+ `sessionStorage` holds only the OIDC state/PKCE verifier.
44
+
45
+ [Unreleased]: https://github.com/atol-sh/atol-sdk-js/compare/v0.1.0...HEAD
46
+ [0.1.0]: https://github.com/atol-sh/atol-sdk-js/releases/tag/v0.1.0
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 2026 Atol
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/NOTICE ADDED
@@ -0,0 +1,15 @@
1
+ @atol-sh/js
2
+ Copyright 2026 Atol
3
+
4
+ This product includes software developed at Atol (https://atol.sh).
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not
7
+ use this software except in compliance with the License. A copy of the
8
+ License is included in the LICENSE file and is available at
9
+ http://www.apache.org/licenses/LICENSE-2.0.
10
+
11
+ This package bundles, depends on, or interoperates with the following
12
+ third-party software, each under its own license:
13
+
14
+ - oidc-client-ts (Apache-2.0)
15
+ - jose (MIT)
package/README.md ADDED
@@ -0,0 +1,204 @@
1
+ # @atol-sh/js
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@atol-sh/js.svg)](https://www.npmjs.com/package/@atol-sh/js)
4
+ [![CI](https://github.com/atol-sh/atol-sdk-js/actions/workflows/ci.yml/badge.svg)](https://github.com/atol-sh/atol-sdk-js/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/@atol-sh/js.svg)](./LICENSE)
6
+
7
+ Framework-agnostic browser security core for [Atol](https://atol.sh): a
8
+ single config-driven client for OIDC authentication (Authorization Code +
9
+ PKCE), DPoP sender-constrained tokens (RFC 9449), silent renewal, cross-tab
10
+ coordination, and permission loading. `@atol-sh/react` is the React
11
+ binding, built as a thin wrapper over this same core -- future Vue,
12
+ Svelte, and vanilla-JS bindings will share it too.
13
+
14
+ Building a React app? Use [`@atol-sh/react`](https://github.com/atol-sh/atol-sdk-react)
15
+ instead, the React binding over this core. Either way you'll need a
16
+ publishable key id (`atol_kid_...`) -- get one from [console.atol.sh](https://console.atol.sh).
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install @atol-sh/js
22
+ ```
23
+
24
+ ## Quickstart
25
+
26
+ The keystone export is `createAtolBrowserAuth`. Everything else in the
27
+ package is a lower-level primitive it is built from.
28
+
29
+ ```ts
30
+ import { createAtolBrowserAuth } from '@atol-sh/js'
31
+
32
+ const auth = createAtolBrowserAuth({
33
+ issuer: 'https://id.atol.sh', // OIDC issuer URL
34
+ clientId: 'atol_kid_abc123', // publishable key id, safe for the browser
35
+ audience: 'https://api.example.com', // optional API audience
36
+ scopes: 'openid profile email', // optional; used verbatim (no offline_access by default)
37
+ redirectUri: 'https://app.example.com/callback',
38
+ dpop: true, // optional RFC 9449 sender-constrained tokens
39
+ useRefreshTokens: false, // default (same-site); REQUIRED true for cross-site apps
40
+ storage: 'memory', // tokens are always memory-only
41
+ })
42
+
43
+ const unsubscribe = auth.onSessionChange(({ isAuthenticated, user }) => {
44
+ render(isAuthenticated, user)
45
+ })
46
+
47
+ // On startup: handles a redirect callback, or silently restores a session
48
+ // from the IdP session cookie.
49
+ await auth.init()
50
+
51
+ // Start a login (redirects the browser):
52
+ await auth.beginLogin()
53
+
54
+ // On the redirect URI page: exchange the code for tokens. init() calls
55
+ // this automatically, so most apps never call it directly.
56
+ await auth.completeLogin()
57
+
58
+ // Get a token for an API call (DPoP-aware: pass the request you're about
59
+ // to make so the proof's `htm`/`htu` bind to it):
60
+ const result = await auth.getAccessToken({
61
+ dpop: { method: 'GET', url: 'https://api.example.com/me' },
62
+ })
63
+ if (result) {
64
+ const headers = result.proof
65
+ ? { Authorization: `DPoP ${result.token}`, DPoP: result.proof }
66
+ : { Authorization: `Bearer ${result.token}` }
67
+ }
68
+
69
+ // Sign out (revokes the refresh token, then RP-initiated end_session):
70
+ await auth.logout()
71
+ ```
72
+
73
+ Other methods on the returned client: `forceRenew()` bypasses the
74
+ freshness check and renews immediately; `stepUp()` forces re-authentication
75
+ (`prompt=login`, `max_age=0`, `acr_values=mfa` by default) for a sensitive
76
+ operation that requires a fresh auth; `signDPoPProof(method, url)` signs a
77
+ standalone RFC 9449 proof for a request to your own protected resource;
78
+ `isDPoPActive()` reports whether DPoP is actually in effect (it can be
79
+ `false` even when `dpop: true` was requested, if WebCrypto is unavailable);
80
+ `destroy()` tears down timers and subscriptions.
81
+
82
+ ## Lower-level primitives
83
+
84
+ The core also exports the building blocks for consumers who assemble their
85
+ own flows:
86
+
87
+ - **DPoP** - `createDPoPKeyManager` (per-tab non-exportable ES256 key,
88
+ RFC 9449 proofs).
89
+ - **Verification** - `verifyIdToken` (JWKS signature + issuer + audience,
90
+ the trust gate for cross-tab token adoption).
91
+ - **OIDC / PKCE** - `createUserManager`, `silentAuthorize`,
92
+ `silentAuthorizeWithRetry`, `exchangeCode`, `refreshTokenGrant`,
93
+ `revokeToken`.
94
+ - **Cross-tab** - `createTokenBroadcast`, `hasBroadcastSupport`,
95
+ `withTabLock`, `hasTabLockSupport`.
96
+ - **Permissions** - `loadPermissions`, `permissionKey`.
97
+ - **Encryption** - `KEKVault`, `unwrapDEK`, `extractKEKFromFragment`,
98
+ `kekBase64ToBytes`, `base64ToBytes` / `bytesToBase64Url` /
99
+ `stringToBase64Url`.
100
+ - **Claims** - `parseAtolUser`, `decodeJWTPayload`, `getTokenExpiry`.
101
+
102
+ See the published type declarations (`dist/index.d.ts`) for the full
103
+ signatures; every export carries a doc comment.
104
+
105
+ ## Security
106
+
107
+ This is a security library first. Key properties:
108
+
109
+ - **Memory-only tokens.** Access, ID, and (when opted in) refresh tokens
110
+ live in an in-memory store and are never written to `localStorage` or
111
+ `sessionStorage`. `sessionStorage` holds only the transient OIDC
112
+ state/PKCE verifier needed to survive the login redirect. A page reload
113
+ starts with an empty store; the client recovers by silently renewing
114
+ against the IdP session cookie.
115
+ - **Iframe-default renewal, refresh required for cross-site.** By default
116
+ the client renews in a hidden iframe against the IdP session cookie
117
+ (`prompt=none`) and requests no refresh token, so there is no long-lived
118
+ bearer credential to leak. The iframe path depends on the IdP session
119
+ cookie being sent from a third-party context, which Safari ITP blocks
120
+ outright and Chrome's third-party-cookie phase-out removes, so it fails
121
+ **unconditionally** for a cross-site app -- one served on a different
122
+ registrable domain than the IdP. Such apps therefore **must** set
123
+ `useRefreshTokens: true`; that appends `offline_access` and renews via the
124
+ refresh-token grant (memory-only, rotated, and DPoP-bound when `dpop` is
125
+ on). Same-site apps (a console on a subdomain of the IdP) reach the
126
+ first-party session cookie in the iframe and leave it `false`.
127
+ - **DPoP sender-constraint (RFC 9449).** When `dpop: true`, a per-tab,
128
+ non-exportable ES256 keypair is generated on `init()` and a proof JWT is
129
+ attached to every token-endpoint call and to `getAccessToken({ dpop })`
130
+ results. A stolen access token cannot be replayed from another client
131
+ without the private key, which never leaves the browser's WebCrypto
132
+ keystore.
133
+ - **PKCE + nonce + ID token verification.** Login uses OIDC Authorization
134
+ Code with PKCE (no implicit flow, no client secret in the browser).
135
+ Cross-tab token adoption over `BroadcastChannel` is untrusted by default:
136
+ a rotated token is only adopted after its ID token is verified against
137
+ the issuer's JWKS (signature, issuer, audience) and the subject is
138
+ pinned to the current session, so a same-origin script cannot forge a
139
+ session takeover.
140
+ - **RP-initiated logout + refresh-token revocation.** `logout()`
141
+ best-effort revokes the refresh token (RFC 7009) when one exists (the
142
+ refresh opt-in) before redirecting to the issuer's `end_session` endpoint
143
+ with `id_token_hint` and `post_logout_redirect_uri`, so the IdP session
144
+ is torn down, not just the local one.
145
+
146
+ Found a vulnerability? See [SECURITY.md](./SECURITY.md) for how to report
147
+ it privately.
148
+
149
+ ## Device intelligence (optional subpath)
150
+
151
+ ```ts
152
+ import { DeviceCollector } from '@atol-sh/js/device'
153
+ ```
154
+
155
+ The `@atol-sh/js/device` subpath is split out of the core barrel and
156
+ dynamic-imports `@atol-sh/fingerprint` (an optional peer dependency) so
157
+ consumers who don't use device intelligence never pull it into their
158
+ bundle. Install `@atol-sh/fingerprint` alongside `@atol-sh/js` to use it.
159
+
160
+ ## Browser support
161
+
162
+ Requires a browser with WebCrypto (`crypto.subtle`): all evergreen
163
+ browsers (Chrome, Firefox, Safari, Edge) on both desktop and mobile.
164
+ When WebCrypto is unavailable (for example, a non-browser or non-secure
165
+ context), DPoP key generation returns `null` and the client falls back to
166
+ plain Bearer tokens automatically -- `isDPoPActive()` reports `false` and
167
+ no proof is attached, but authentication and token renewal continue to
168
+ work.
169
+
170
+ ## Troubleshooting
171
+
172
+ - **Silent renew fails under Safari ITP, or any cross-site third-party-cookie
173
+ blocking.** The default renewal model uses a hidden iframe against the
174
+ IdP session cookie, which requires that cookie to be readable in a
175
+ third-party context. Safari ITP blocks this outright, and Chrome's
176
+ third-party-cookie phase-out removes it too. Fix: set
177
+ `useRefreshTokens: true` so the client renews via the refresh-token grant
178
+ instead.
179
+ - **"invalid redirect_uri".** The `redirectUri` you pass must be allow-listed
180
+ for your publishable key in [console.atol.sh](https://console.atol.sh).
181
+ Add the exact URI (scheme, host, port, path) there.
182
+ - **DPoP silently falls back to Bearer.** `dpop: true` only takes effect
183
+ when WebCrypto is available; call `isDPoPActive()` to check whether it
184
+ actually did. A server-issued `DPoP-Nonce` challenge is retried
185
+ automatically with the nonce attached -- no consumer action needed.
186
+ - **Permission checks return `false` unexpectedly.** `loadPermissions`
187
+ denies by default: a `false` means either the server-side permission
188
+ genuinely isn't granted, or the bulk load itself failed (network error,
189
+ shape mismatch) and the caller is expected to treat "unknown" the same as
190
+ "denied".
191
+
192
+ ## Contributing
193
+
194
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for dev setup, the test/coverage
195
+ gate, and the PR process. Please read [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md)
196
+ before participating.
197
+
198
+ ## Changelog
199
+
200
+ See [CHANGELOG.md](./CHANGELOG.md) for release notes.
201
+
202
+ ## License
203
+
204
+ Apache-2.0. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
@@ -0,0 +1,115 @@
1
+ 'use strict';
2
+
3
+ // src/device/types.ts
4
+ var initialDeviceState = {
5
+ deviceId: null,
6
+ known: false,
7
+ confidence: 0,
8
+ newDevice: false,
9
+ platform: null,
10
+ browser: null,
11
+ osVersion: null,
12
+ signals: null,
13
+ loading: false,
14
+ error: null
15
+ };
16
+
17
+ // src/device/collector.ts
18
+ var DEFAULT_DEVICE_API_URL = "https://api.atol.sh";
19
+ function parseSignals(raw) {
20
+ if (!raw || typeof raw !== "object") return null;
21
+ const r = raw;
22
+ return {
23
+ bot: r.bot === true,
24
+ vpn: r.vpn === true,
25
+ proxy: r.proxy === true,
26
+ tor: r.tor === true,
27
+ incognito: r.incognito === true,
28
+ tampered: r.tampered === true,
29
+ emulator: r.emulator === true,
30
+ rooted: r.rooted === true,
31
+ geo_mismatch: r.geo_mismatch === true,
32
+ anomaly_score: typeof r.anomaly_score === "number" ? r.anomaly_score : 0
33
+ };
34
+ }
35
+ function deviceStateFromResult(result) {
36
+ return {
37
+ deviceId: result.device_id ?? null,
38
+ known: result.known ?? false,
39
+ confidence: result.confidence ?? 0,
40
+ newDevice: result.new_device ?? false,
41
+ platform: result.platform || null,
42
+ browser: result.browser || null,
43
+ osVersion: result.os_version || null,
44
+ signals: parseSignals(result.signals),
45
+ loading: false,
46
+ error: null
47
+ };
48
+ }
49
+ var DeviceCollector = class {
50
+ constructor(apiUrl, onState) {
51
+ this.apiUrl = apiUrl;
52
+ this.onState = onState;
53
+ this.agent = null;
54
+ this.agentApiUrl = null;
55
+ this.inFlight = null;
56
+ this.inFlightToken = null;
57
+ }
58
+ /**
59
+ * Collect device signals. With a token, submits an identify call and
60
+ * emits the mapped DeviceState; without one, just pre-loads the agent.
61
+ * Concurrent calls with the same token share one in-flight promise.
62
+ */
63
+ collect(token) {
64
+ const key = token ?? null;
65
+ if (this.inFlight && this.inFlightToken === key) {
66
+ return this.inFlight;
67
+ }
68
+ const run = (async () => {
69
+ this.onState({ ...initialDeviceState, loading: true });
70
+ try {
71
+ let mod;
72
+ try {
73
+ mod = await import('@atol-sh/fingerprint');
74
+ } catch (importErr) {
75
+ throw new Error(
76
+ `device intelligence is enabled but @atol-sh/fingerprint is not installed -- run \`npm i @atol-sh/fingerprint\` or disable device intelligence (${String(importErr)})`
77
+ );
78
+ }
79
+ const AtolFingerprint = mod.AtolFingerprint ?? mod.default;
80
+ if (!AtolFingerprint) {
81
+ throw new Error(
82
+ "@atol-sh/fingerprint loaded but exports no AtolFingerprint -- check the installed package version"
83
+ );
84
+ }
85
+ if (!this.agent || this.agentApiUrl !== this.apiUrl) {
86
+ this.agent = await AtolFingerprint.load({ endpoint: this.apiUrl });
87
+ this.agentApiUrl = this.apiUrl;
88
+ }
89
+ if (token) {
90
+ const result = await this.agent.identify({ token });
91
+ this.onState(deviceStateFromResult(result));
92
+ } else {
93
+ this.onState({ ...initialDeviceState, loading: false });
94
+ }
95
+ } catch (err) {
96
+ const error = err instanceof Error ? err : new Error(`Device intelligence collection failed: ${String(err)}`);
97
+ this.onState({ ...initialDeviceState, loading: false, error });
98
+ } finally {
99
+ this.inFlight = null;
100
+ this.inFlightToken = null;
101
+ }
102
+ })();
103
+ this.inFlight = run;
104
+ this.inFlightToken = key;
105
+ return run;
106
+ }
107
+ };
108
+
109
+ exports.DEFAULT_DEVICE_API_URL = DEFAULT_DEVICE_API_URL;
110
+ exports.DeviceCollector = DeviceCollector;
111
+ exports.deviceStateFromResult = deviceStateFromResult;
112
+ exports.initialDeviceState = initialDeviceState;
113
+ exports.parseSignals = parseSignals;
114
+ //# sourceMappingURL=device.cjs.map
115
+ //# sourceMappingURL=device.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/device/types.ts","../src/device/collector.ts"],"names":[],"mappings":";;;AAmGO,IAAM,kBAAA,GAAkC;AAAA,EAC7C,QAAA,EAAU,IAAA;AAAA,EACV,KAAA,EAAO,KAAA;AAAA,EACP,UA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\n * Device intelligence types.\n *\n * Wire shapes mirror the Atol control plane's identify endpoint\n * (`POST /api/v1/devices/identify`) -- the same shapes\n * `@atol-sh/fingerprint` returns from `identify()`, since that SDK\n * passes the server response through verbatim. The fingerprint package\n * is an optional peer dependency that is not statically resolvable\n * here, so the contract is mirrored locally instead of imported.\n */\n\n/** Configuration for device intelligence collection. */\nexport interface DeviceConfig {\n /** Whether device intelligence is enabled. */\n enabled: boolean\n\n /**\n * Base URL of the Atol API host that serves\n * `POST /api/v1/devices/identify`. This is the API host\n * (https://api.atol.sh), NOT the OIDC authority (https://auth.atol.sh).\n * Default: \"https://api.atol.sh\".\n */\n apiUrl?: string\n\n /** Collect device signals on mount. Default: true. */\n collectOnMount?: boolean\n\n /** Interval in ms to re-collect signals. 0 = disabled. Default: 0. */\n recheckInterval?: number\n}\n\n/**\n * Smart signals computed server-side. Keys match the server's signals\n * map exactly (snake_case); no client-side fabrication.\n */\nexport interface SmartSignals {\n bot: boolean\n vpn: boolean\n proxy: boolean\n tor: boolean\n incognito: boolean\n tampered: boolean\n emulator: boolean\n rooted: boolean\n geo_mismatch: boolean\n anomaly_score: number\n}\n\n/**\n * Raw identify response from the control plane (snake_case, verbatim).\n * `signals` is null when the server computed no smart signals.\n */\nexport interface IdentifyResult {\n device_id: string\n known: boolean\n confidence: number\n new_device: boolean\n platform: string\n browser: string\n os_version: string\n signals: SmartSignals | null\n}\n\n/** Device intelligence state (binding-facing, camelCase). */\nexport interface DeviceState {\n /** Unique device identifier assigned by the Atol control plane. */\n deviceId: string | null\n\n /** Whether this device has been seen before. */\n known: boolean\n\n /** Confidence score (0-1) for the device fingerprint match. */\n confidence: number\n\n /** Whether the server created a new device record for this identify. */\n newDevice: boolean\n\n /** Platform reported by the server (e.g. \"macOS\"). Null before identify. */\n platform: string | null\n\n /** Browser family reported by the server. Null before identify. */\n browser: string | null\n\n /** OS version reported by the server. Null before identify. */\n osVersion: string | null\n\n /** Smart signals from server-side analysis. Null before identify or\n * when the server returned none. */\n signals: SmartSignals | null\n\n /** Whether device intelligence is currently loading. */\n loading: boolean\n\n /** Error from device intelligence collection, if any. */\n error: Error | null\n}\n\n/** Initial / not-collected device state. Shared by bindings' context\n * default and the no-provider fallback. */\nexport const initialDeviceState: DeviceState = {\n deviceId: null,\n known: false,\n confidence: 0,\n newDevice: false,\n platform: null,\n browser: null,\n osVersion: null,\n signals: null,\n loading: false,\n error: null,\n}\n","/**\n * Framework-agnostic device intelligence collector.\n *\n * Owns the `@atol-sh/fingerprint` agent lifecycle and the identify call,\n * plus the mapping from the server's snake_case response to the\n * binding-facing DeviceState. React (and any other) bindings wrap this\n * with their own reactive state; the collector itself has no framework\n * dependency.\n *\n * This module lives under the optional `@atol-sh/js/device` subpath so a\n * consumer that never uses device intelligence never pulls\n * `@atol-sh/fingerprint` (an optional peer dependency, dynamic-imported\n * here) into their bundle.\n */\n\nimport {\n initialDeviceState,\n type DeviceState,\n type IdentifyResult,\n type SmartSignals,\n} from './types'\n\n/** Default Atol API host serving POST /api/v1/devices/identify. */\nexport const DEFAULT_DEVICE_API_URL = 'https://api.atol.sh'\n\n/**\n * Structural surface of `@atol-sh/fingerprint` consumed here. The package\n * is an OPTIONAL peer dependency, so it cannot be statically imported\n * without breaking installs that skip it. These interfaces mirror the\n * published package API (`AtolFingerprint.load` / `identify`) and the wire\n * shapes are pinned to the server contract -- the fingerprint SDK returns\n * the server JSON verbatim.\n */\ninterface FingerprintAgent {\n identify(options?: { token?: string }): Promise<IdentifyResult>\n}\n\ninterface FingerprintStatic {\n load(config?: { endpoint?: string; apiKey?: string }): Promise<FingerprintAgent>\n}\n\ninterface FingerprintModule {\n AtolFingerprint?: FingerprintStatic\n default?: FingerprintStatic\n}\n\n/**\n * Map the server's signals object onto SmartSignals. Only the keys the\n * server actually emits are read -- nothing is fabricated. Returns null\n * when the server sent no signals.\n */\nexport function parseSignals(raw: unknown): SmartSignals | null {\n if (!raw || typeof raw !== 'object') return null\n const r = raw as Record<string, unknown>\n return {\n bot: r.bot === true,\n vpn: r.vpn === true,\n proxy: r.proxy === true,\n tor: r.tor === true,\n incognito: r.incognito === true,\n tampered: r.tampered === true,\n emulator: r.emulator === true,\n rooted: r.rooted === true,\n geo_mismatch: r.geo_mismatch === true,\n anomaly_score: typeof r.anomaly_score === 'number' ? r.anomaly_score : 0,\n }\n}\n\n/** Map a raw identify result to the fully-populated DeviceState. */\nexport function deviceStateFromResult(result: IdentifyResult): DeviceState {\n return {\n deviceId: result.device_id ?? null,\n known: result.known ?? false,\n confidence: result.confidence ?? 0,\n newDevice: result.new_device ?? false,\n platform: result.platform || null,\n browser: result.browser || null,\n osVersion: result.os_version || null,\n signals: parseSignals(result.signals),\n loading: false,\n error: null,\n }\n}\n\n/**\n * DeviceCollector loads and caches the fingerprint agent, and performs\n * identify calls. It is stateless with respect to the reactive UI: callers\n * pass an `onState` sink that receives DeviceState transitions, and drive\n * `collect()` in response to token changes / intervals.\n *\n * The agent is (re)loaded when missing or bound to a stale endpoint, so a\n * changed API host does not pin to the first host seen. A single-flight\n * guard keyed by token prevents duplicate concurrent identify POSTs (e.g.\n * React Strict Mode's double invoke).\n */\nexport class DeviceCollector {\n private agent: FingerprintAgent | null = null\n private agentApiUrl: string | null = null\n private inFlight: Promise<void> | null = null\n private inFlightToken: string | null = null\n\n constructor(\n private readonly apiUrl: string,\n private readonly onState: (state: DeviceState) => void,\n ) {}\n\n /**\n * Collect device signals. With a token, submits an identify call and\n * emits the mapped DeviceState; without one, just pre-loads the agent.\n * Concurrent calls with the same token share one in-flight promise.\n */\n collect(token?: string): Promise<void> {\n const key = token ?? null\n if (this.inFlight && this.inFlightToken === key) {\n return this.inFlight\n }\n\n const run = (async () => {\n this.onState({ ...initialDeviceState, loading: true })\n try {\n let mod: FingerprintModule\n try {\n mod = (await import('@atol-sh/fingerprint')) as FingerprintModule\n } catch (importErr) {\n throw new Error(\n 'device intelligence is enabled but @atol-sh/fingerprint is not ' +\n 'installed -- run `npm i @atol-sh/fingerprint` or disable device ' +\n `intelligence (${String(importErr)})`,\n )\n }\n const AtolFingerprint = mod.AtolFingerprint ?? mod.default\n if (!AtolFingerprint) {\n throw new Error(\n '@atol-sh/fingerprint loaded but exports no AtolFingerprint -- ' +\n 'check the installed package version',\n )\n }\n\n // (Re)load the agent when missing or bound to a stale endpoint.\n if (!this.agent || this.agentApiUrl !== this.apiUrl) {\n this.agent = await AtolFingerprint.load({ endpoint: this.apiUrl })\n this.agentApiUrl = this.apiUrl\n }\n\n if (token) {\n const result = await this.agent.identify({ token })\n this.onState(deviceStateFromResult(result))\n } else {\n // No token yet -- agent pre-loaded, nothing to identify.\n this.onState({ ...initialDeviceState, loading: false })\n }\n } catch (err) {\n const error =\n err instanceof Error\n ? err\n : new Error(`Device intelligence collection failed: ${String(err)}`)\n this.onState({ ...initialDeviceState, loading: false, error })\n } finally {\n this.inFlight = null\n this.inFlightToken = null\n }\n })()\n\n this.inFlight = run\n this.inFlightToken = key\n return run\n }\n}\n"]}