@atol-sh/js 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/device.d.ts CHANGED
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * Wire shapes mirror the Atol control plane's identify endpoint
5
5
  * (`POST /api/v1/devices/identify`) -- the same shapes
6
- * `@atol-sh/fingerprint` returns from `identify()`, since that SDK
7
- * passes the server response through verbatim. The fingerprint package
6
+ * `@atol-sh/fingerprint` returns from `identify()`. Both packages validate
7
+ * the response before exposing it. The fingerprint package
8
8
  * is an optional peer dependency that is not statically resolvable
9
9
  * here, so the contract is mirrored locally instead of imported.
10
10
  */
@@ -38,11 +38,14 @@ interface SmartSignals {
38
38
  emulator: boolean;
39
39
  rooted: boolean;
40
40
  geo_mismatch: boolean;
41
+ device_mismatch: boolean;
42
+ device_shared: boolean;
43
+ shared_user_count: number;
41
44
  anomaly_score: number;
42
45
  }
43
46
  /**
44
47
  * Raw identify response from the control plane (snake_case, verbatim).
45
- * `signals` is null when the server computed no smart signals.
48
+ * The server always returns the exact smart-signal evaluation.
46
49
  */
47
50
  interface IdentifyResult {
48
51
  device_id: string;
@@ -52,7 +55,7 @@ interface IdentifyResult {
52
55
  platform: string;
53
56
  browser: string;
54
57
  os_version: string;
55
- signals: SmartSignals | null;
58
+ signals: SmartSignals;
56
59
  }
57
60
  /** Device intelligence state (binding-facing, camelCase). */
58
61
  interface DeviceState {
@@ -70,8 +73,8 @@ interface DeviceState {
70
73
  browser: string | null;
71
74
  /** OS version reported by the server. Null before identify. */
72
75
  osVersion: string | null;
73
- /** Smart signals from server-side analysis. Null before identify or
74
- * when the server returned none. */
76
+ /** Smart signals from server-side analysis. Null before identify, reset,
77
+ * or failure; every successful server response contains the exact object. */
75
78
  signals: SmartSignals | null;
76
79
  /** Whether device intelligence is currently loading. */
77
80
  loading: boolean;
@@ -99,39 +102,80 @@ declare const initialDeviceState: DeviceState;
99
102
 
100
103
  /** Default Atol API host serving POST /api/v1/devices/identify. */
101
104
  declare const DEFAULT_DEVICE_API_URL = "https://api.atol.sh";
105
+ /** Exact identify request presented to the credential owner. */
106
+ interface DeviceAuthorizationRequest {
107
+ method: 'POST';
108
+ url: string;
109
+ }
110
+ /** One request's exact Bearer or DPoP authorization material. */
111
+ type DeviceAuthorization = {
112
+ scheme: 'Bearer';
113
+ accessToken: string;
114
+ } | {
115
+ scheme: 'DPoP';
116
+ accessToken: string;
117
+ dpopProof: string;
118
+ };
119
+ /**
120
+ * Acquire authorization for the exact identify request. The collector passes
121
+ * this owner through for one operation and does not retain its result.
122
+ */
123
+ type DeviceAuthorizationOwner = (request: Readonly<DeviceAuthorizationRequest>) => Promise<DeviceAuthorization>;
124
+ /**
125
+ * One credential generation's identify authority. Increment the non-secret
126
+ * generation whenever the owning session rotates or changes organization.
127
+ */
128
+ interface DeviceCollectionRequest {
129
+ credentialGeneration: number;
130
+ authorize: DeviceAuthorizationOwner;
131
+ }
102
132
  /**
103
- * Map the server's signals object onto SmartSignals. Only the keys the
104
- * server actually emits are read -- nothing is fabricated. Returns null
105
- * when the server sent no signals.
133
+ * Map the exact server signals object onto SmartSignals. Missing, null,
134
+ * unknown, or mistyped members are a contract failure.
106
135
  */
107
- declare function parseSignals(raw: unknown): SmartSignals | null;
108
- /** Map a raw identify result to the fully-populated DeviceState. */
109
- declare function deviceStateFromResult(result: IdentifyResult): DeviceState;
136
+ declare function parseSignals(raw: unknown): SmartSignals;
137
+ /** Validate and map a raw identify result to the fully-populated DeviceState. */
138
+ declare function deviceStateFromResult(result: unknown): DeviceState;
110
139
  /**
111
140
  * DeviceCollector loads and caches the fingerprint agent, and performs
112
141
  * identify calls. It is stateless with respect to the reactive UI: callers
113
142
  * pass an `onState` sink that receives DeviceState transitions, and drive
114
- * `collect()` in response to token changes / intervals.
143
+ * `collect()` in response to credential-generation changes or intervals.
115
144
  *
116
- * The agent is (re)loaded when missing or bound to a stale endpoint, so a
117
- * changed API host does not pin to the first host seen. A single-flight
118
- * guard keyed by token prevents duplicate concurrent identify POSTs (e.g.
119
- * React Strict Mode's double invoke).
145
+ * The agent is loaded once for this endpoint-bound collector. Calls for one
146
+ * credential generation are single-flight. A newer generation becomes the
147
+ * latest intent immediately, so a late older result cannot publish state.
120
148
  */
121
149
  declare class DeviceCollector {
122
150
  private readonly apiUrl;
123
151
  private readonly onState;
124
152
  private agent;
125
- private agentApiUrl;
126
- private inFlight;
127
- private inFlightToken;
153
+ private agentLoad;
154
+ private readonly inFlight;
155
+ private highestCredentialGeneration;
156
+ private invalidatedGenerationFloor;
157
+ private latestIntent;
128
158
  constructor(apiUrl: string, onState: (state: DeviceState) => void);
129
159
  /**
130
- * Collect device signals. With a token, submits an identify call and
131
- * emits the mapped DeviceState; without one, just pre-loads the agent.
132
- * Concurrent calls with the same token share one in-flight promise.
160
+ * Pre-load the fingerprint agent without changing credential authority.
161
+ * A later collect or invalidate operation fences this preparation's state.
162
+ */
163
+ prepare(): Promise<void>;
164
+ /**
165
+ * Submit one credential generation's identify operation. Generations are
166
+ * strictly monotonic for this collector's lifetime. A lower delayed
167
+ * generation is ignored before authorization or network dispatch, while a
168
+ * newer generation immediately fences every older result.
169
+ */
170
+ collect(request: DeviceCollectionRequest): Promise<void>;
171
+ /**
172
+ * Fence every in-flight identify and clear published device state. Future
173
+ * credentials must continue with a generation higher than any accepted one.
133
174
  */
134
- collect(token?: string): Promise<void>;
175
+ invalidate(): void;
176
+ private publishPreparation;
177
+ private publish;
178
+ private loadAgent;
135
179
  }
136
180
 
137
- export { DEFAULT_DEVICE_API_URL, DeviceCollector, type DeviceConfig, type DeviceState, type IdentifyResult, type SmartSignals, deviceStateFromResult, initialDeviceState, parseSignals };
181
+ export { DEFAULT_DEVICE_API_URL, type DeviceAuthorization, type DeviceAuthorizationOwner, type DeviceAuthorizationRequest, type DeviceCollectionRequest, DeviceCollector, type DeviceConfig, type DeviceState, type IdentifyResult, type SmartSignals, deviceStateFromResult, initialDeviceState, parseSignals };
package/dist/device.js CHANGED
@@ -14,31 +14,93 @@ var initialDeviceState = {
14
14
 
15
15
  // src/device/collector.ts
16
16
  var DEFAULT_DEVICE_API_URL = "https://api.atol.sh";
17
+ var DeviceDiagnosticError = class extends Error {
18
+ constructor(code, message) {
19
+ super(message);
20
+ this.code = code;
21
+ this.name = "DeviceDiagnosticError";
22
+ }
23
+ };
17
24
  function parseSignals(raw) {
18
- if (!raw || typeof raw !== "object") return null;
25
+ const expectedKeys = [
26
+ "anomaly_score",
27
+ "bot",
28
+ "device_mismatch",
29
+ "device_shared",
30
+ "emulator",
31
+ "geo_mismatch",
32
+ "incognito",
33
+ "proxy",
34
+ "rooted",
35
+ "shared_user_count",
36
+ "tampered",
37
+ "tor",
38
+ "vpn"
39
+ ];
40
+ if (!isExactRecord(raw, expectedKeys)) {
41
+ throw invalidDeviceResponse();
42
+ }
19
43
  const r = raw;
44
+ if (typeof r.bot !== "boolean" || typeof r.vpn !== "boolean" || typeof r.proxy !== "boolean" || typeof r.tor !== "boolean" || typeof r.incognito !== "boolean" || typeof r.tampered !== "boolean" || typeof r.emulator !== "boolean" || typeof r.rooted !== "boolean" || typeof r.geo_mismatch !== "boolean" || typeof r.device_mismatch !== "boolean" || typeof r.device_shared !== "boolean" || typeof r.shared_user_count !== "number" || !Number.isSafeInteger(r.shared_user_count) || r.shared_user_count < 0 || !isProbability(r.anomaly_score)) {
45
+ throw invalidDeviceResponse();
46
+ }
20
47
  return {
21
- bot: r.bot === true,
22
- vpn: r.vpn === true,
23
- proxy: r.proxy === true,
24
- tor: r.tor === true,
25
- incognito: r.incognito === true,
26
- tampered: r.tampered === true,
27
- emulator: r.emulator === true,
28
- rooted: r.rooted === true,
29
- geo_mismatch: r.geo_mismatch === true,
30
- anomaly_score: typeof r.anomaly_score === "number" ? r.anomaly_score : 0
48
+ bot: r.bot,
49
+ vpn: r.vpn,
50
+ proxy: r.proxy,
51
+ tor: r.tor,
52
+ incognito: r.incognito,
53
+ tampered: r.tampered,
54
+ emulator: r.emulator,
55
+ rooted: r.rooted,
56
+ geo_mismatch: r.geo_mismatch,
57
+ device_mismatch: r.device_mismatch,
58
+ device_shared: r.device_shared,
59
+ shared_user_count: r.shared_user_count,
60
+ anomaly_score: r.anomaly_score
31
61
  };
32
62
  }
63
+ function isExactRecord(value, expectedKeys) {
64
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
65
+ return false;
66
+ }
67
+ const actualKeys = Object.keys(value).sort();
68
+ return actualKeys.length === expectedKeys.length && actualKeys.every((key, index) => key === expectedKeys[index]);
69
+ }
70
+ function isProbability(value) {
71
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
72
+ }
73
+ function invalidDeviceResponse() {
74
+ return new DeviceDiagnosticError(
75
+ "device_response_invalid",
76
+ "Device intelligence returned an invalid response."
77
+ );
78
+ }
33
79
  function deviceStateFromResult(result) {
80
+ const expectedKeys = [
81
+ "browser",
82
+ "confidence",
83
+ "device_id",
84
+ "known",
85
+ "new_device",
86
+ "os_version",
87
+ "platform",
88
+ "signals"
89
+ ];
90
+ if (!isExactRecord(result, expectedKeys)) {
91
+ throw invalidDeviceResponse();
92
+ }
93
+ if (typeof result.device_id !== "string" || result.device_id.length === 0 || typeof result.known !== "boolean" || typeof result.new_device !== "boolean" || result.known === result.new_device || !isProbability(result.confidence) || typeof result.platform !== "string" || typeof result.browser !== "string" || typeof result.os_version !== "string") {
94
+ throw invalidDeviceResponse();
95
+ }
34
96
  return {
35
- deviceId: result.device_id ?? null,
36
- known: result.known ?? false,
37
- confidence: result.confidence ?? 0,
38
- newDevice: result.new_device ?? false,
39
- platform: result.platform || null,
40
- browser: result.browser || null,
41
- osVersion: result.os_version || null,
97
+ deviceId: result.device_id,
98
+ known: result.known,
99
+ confidence: result.confidence,
100
+ newDevice: result.new_device,
101
+ platform: result.platform,
102
+ browser: result.browser,
103
+ osVersion: result.os_version,
42
104
  signals: parseSignals(result.signals),
43
105
  loading: false,
44
106
  error: null
@@ -49,59 +111,163 @@ var DeviceCollector = class {
49
111
  this.apiUrl = apiUrl;
50
112
  this.onState = onState;
51
113
  this.agent = null;
52
- this.agentApiUrl = null;
53
- this.inFlight = null;
54
- this.inFlightToken = null;
114
+ this.agentLoad = null;
115
+ this.inFlight = /* @__PURE__ */ new Map();
116
+ this.highestCredentialGeneration = 0;
117
+ this.invalidatedGenerationFloor = 0;
118
+ this.latestIntent = 0;
55
119
  }
56
120
  /**
57
- * Collect device signals. With a token, submits an identify call and
58
- * emits the mapped DeviceState; without one, just pre-loads the agent.
59
- * Concurrent calls with the same token share one in-flight promise.
121
+ * Pre-load the fingerprint agent without changing credential authority.
122
+ * A later collect or invalidate operation fences this preparation's state.
60
123
  */
61
- collect(token) {
62
- const key = token ?? null;
63
- if (this.inFlight && this.inFlightToken === key) {
64
- return this.inFlight;
124
+ async prepare() {
125
+ const intent = this.latestIntent;
126
+ try {
127
+ await this.loadAgent();
128
+ this.publishPreparation(intent, {
129
+ ...initialDeviceState,
130
+ loading: false
131
+ });
132
+ } catch (err) {
133
+ const error = err instanceof DeviceDiagnosticError ? err : new DeviceDiagnosticError(
134
+ "device_collection_failed",
135
+ "Device intelligence collection failed. Retry the request."
136
+ );
137
+ this.publishPreparation(intent, {
138
+ ...initialDeviceState,
139
+ loading: false,
140
+ error
141
+ });
65
142
  }
66
- const run = (async () => {
67
- this.onState({ ...initialDeviceState, loading: true });
143
+ }
144
+ /**
145
+ * Submit one credential generation's identify operation. Generations are
146
+ * strictly monotonic for this collector's lifetime. A lower delayed
147
+ * generation is ignored before authorization or network dispatch, while a
148
+ * newer generation immediately fences every older result.
149
+ */
150
+ collect(request) {
151
+ const {
152
+ credentialGeneration: generation,
153
+ authorize
154
+ } = request;
155
+ if (!Number.isSafeInteger(generation) || generation <= 0) {
156
+ return Promise.reject(
157
+ new DeviceDiagnosticError(
158
+ "device_credential_generation_invalid",
159
+ "Device intelligence requires a positive credential generation."
160
+ )
161
+ );
162
+ }
163
+ if (generation < this.highestCredentialGeneration || generation <= this.invalidatedGenerationFloor) {
164
+ return Promise.resolve();
165
+ }
166
+ const existing = this.inFlight.get(generation);
167
+ if (existing) {
168
+ return existing;
169
+ }
170
+ if (generation > this.highestCredentialGeneration) {
171
+ this.highestCredentialGeneration = generation;
172
+ }
173
+ const intent = ++this.latestIntent;
174
+ const operation = (async () => {
175
+ this.publish(intent, { ...initialDeviceState, loading: true });
68
176
  try {
69
- let mod;
177
+ const agent = await this.loadAgent();
178
+ let result;
70
179
  try {
71
- mod = await import('@atol-sh/fingerprint');
72
- } catch (importErr) {
73
- throw new Error(
74
- `device intelligence is enabled but @atol-sh/fingerprint is not installed -- run \`npm i @atol-sh/fingerprint\` or disable device intelligence (${String(importErr)})`
75
- );
76
- }
77
- const AtolFingerprint = mod.AtolFingerprint ?? mod.default;
78
- if (!AtolFingerprint) {
79
- throw new Error(
80
- "@atol-sh/fingerprint loaded but exports no AtolFingerprint -- check the installed package version"
180
+ result = await agent.identify({ authorize });
181
+ } catch {
182
+ throw new DeviceDiagnosticError(
183
+ "device_collection_failed",
184
+ "Device intelligence collection failed. Retry the request."
81
185
  );
82
186
  }
83
- if (!this.agent || this.agentApiUrl !== this.apiUrl) {
84
- this.agent = await AtolFingerprint.load({ endpoint: this.apiUrl });
85
- this.agentApiUrl = this.apiUrl;
86
- }
87
- if (token) {
88
- const result = await this.agent.identify({ token });
89
- this.onState(deviceStateFromResult(result));
90
- } else {
91
- this.onState({ ...initialDeviceState, loading: false });
92
- }
187
+ this.publish(intent, deviceStateFromResult(result));
93
188
  } catch (err) {
94
- const error = err instanceof Error ? err : new Error(`Device intelligence collection failed: ${String(err)}`);
95
- this.onState({ ...initialDeviceState, loading: false, error });
96
- } finally {
97
- this.inFlight = null;
98
- this.inFlightToken = null;
189
+ const error = err instanceof DeviceDiagnosticError ? err : new DeviceDiagnosticError(
190
+ "device_collection_failed",
191
+ "Device intelligence collection failed. Retry the request."
192
+ );
193
+ this.publish(intent, { ...initialDeviceState, loading: false, error });
99
194
  }
100
195
  })();
101
- this.inFlight = run;
102
- this.inFlightToken = key;
196
+ let run;
197
+ run = operation.finally(() => {
198
+ if (this.inFlight.get(generation) === run) {
199
+ this.inFlight.delete(generation);
200
+ }
201
+ });
202
+ this.inFlight.set(generation, run);
103
203
  return run;
104
204
  }
205
+ /**
206
+ * Fence every in-flight identify and clear published device state. Future
207
+ * credentials must continue with a generation higher than any accepted one.
208
+ */
209
+ invalidate() {
210
+ this.latestIntent++;
211
+ this.invalidatedGenerationFloor = Math.max(
212
+ this.invalidatedGenerationFloor,
213
+ this.highestCredentialGeneration
214
+ );
215
+ this.onState(initialDeviceState);
216
+ }
217
+ publishPreparation(intent, state) {
218
+ if (this.highestCredentialGeneration === 0) {
219
+ this.publish(intent, state);
220
+ }
221
+ }
222
+ publish(intent, state) {
223
+ if (intent === this.latestIntent) {
224
+ this.onState(state);
225
+ }
226
+ }
227
+ async loadAgent() {
228
+ if (this.agent) {
229
+ return this.agent;
230
+ }
231
+ if (this.agentLoad) {
232
+ return this.agentLoad;
233
+ }
234
+ const load = (async () => {
235
+ let mod;
236
+ try {
237
+ mod = await import('@atol-sh/fingerprint');
238
+ } catch {
239
+ throw new DeviceDiagnosticError(
240
+ "device_dependency_unavailable",
241
+ "device intelligence is enabled but @atol-sh/fingerprint is not installed -- run `npm i @atol-sh/fingerprint` or disable device intelligence"
242
+ );
243
+ }
244
+ const AtolFingerprint = mod.AtolFingerprint ?? mod.default;
245
+ if (!AtolFingerprint) {
246
+ throw new DeviceDiagnosticError(
247
+ "device_dependency_invalid",
248
+ "@atol-sh/fingerprint loaded but exports no AtolFingerprint -- check the installed package version"
249
+ );
250
+ }
251
+ try {
252
+ const agent = await AtolFingerprint.load({ endpoint: this.apiUrl });
253
+ this.agent = agent;
254
+ return agent;
255
+ } catch {
256
+ throw new DeviceDiagnosticError(
257
+ "device_initialization_failed",
258
+ "Device intelligence could not be initialized. Retry or disable device intelligence."
259
+ );
260
+ }
261
+ })();
262
+ this.agentLoad = load;
263
+ try {
264
+ return await load;
265
+ } finally {
266
+ if (this.agentLoad === load) {
267
+ this.agentLoad = null;
268
+ }
269
+ }
270
+ }
105
271
  };
106
272
 
107
273
  export { DEFAULT_DEVICE_API_URL, DeviceCollector, deviceStateFromResult, initialDeviceState, parseSignals };
@@ -1 +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,UAAA,EAAY,CAAA;AAAA,EACZ,SAAA,EAAW,KAAA;AAAA,EACX,QAAA,EAAU,IAAA;AAAA,EACV,OAAA,EAAS,IAAA;AAAA,EACT,SAAA,EAAW,IAAA;AAAA,EACX,OAAA,EAAS,IAAA;AAAA,EACT,OAAA,EAAS,KAAA;AAAA,EACT,KAAA,EAAO;AACT;;;ACvFO,IAAM,sBAAA,GAAyB;AA4B/B,SAAS,aAAa,GAAA,EAAmC;AAC9D,EAAA,IAAI,CAAC,GAAA,IAAO,OAAO,GAAA,KAAQ,UAAU,OAAO,IAAA;AAC5C,EAAA,MAAM,CAAA,GAAI,GAAA;AACV,EAAA,OAAO;AAAA,IACL,GAAA,EAAK,EAAE,GAAA,KAAQ,IAAA;AAAA,IACf,GAAA,EAAK,EAAE,GAAA,KAAQ,IAAA;AAAA,IACf,KAAA,EAAO,EAAE,KAAA,KAAU,IAAA;AAAA,IACnB,GAAA,EAAK,EAAE,GAAA,KAAQ,IAAA;AAAA,IACf,SAAA,EAAW,EAAE,SAAA,KAAc,IAAA;AAAA,IAC3B,QAAA,EAAU,EAAE,QAAA,KAAa,IAAA;AAAA,IACzB,QAAA,EAAU,EAAE,QAAA,KAAa,IAAA;AAAA,IACzB,MAAA,EAAQ,EAAE,MAAA,KAAW,IAAA;AAAA,IACrB,YAAA,EAAc,EAAE,YAAA,KAAiB,IAAA;AAAA,IACjC,eAAe,OAAO,CAAA,CAAE,aA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AAE,GAAG,oBAAoB,OAAA,EAAS,KAAA,EAAO,OAAO,CAAA;AAAA,MAC/D,CAAA,SAAE;AACA,QAAA,IAAA,CAAK,QAAA,GAAW,IAAA;AAChB,QAAA,IAAA,CAAK,aAAA,GAAgB,IAAA;AAAA,MACvB;AAAA,IACF,CAAA,GAAG;AAEH,IAAA,IAAA,CAAK,QAAA,GAAW,GAAA;AAChB,IAAA,IAAA,CAAK,aAAA,GAAgB,GAAA;AACrB,IAAA,OAAO,GAAA;AAAA,EACT;AACF","file":"device.js","sourcesContent":["/**\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"]}
1
+ {"version":3,"sources":["../src/device/types.ts","../src/device/collector.ts"],"names":[],"mappings":";AAsGO,IAAM,kBAAA,GAAkC;AAAA,EAC7C,QAAA,EAAU,IAAA;AAAA,EACV,KAAA,EAAO,KAAA;AAAA,EACP,UAAA,EAAY,CAAA;AAAA,EACZ,SAAA,EAAW,KAAA;AAAA,EACX,QAAA,EAAU,IAAA;AAAA,EACV,OAAA,EAAS,IAAA;AAAA,EACT,SAAA,EAAW,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ror the Atol control plane's identify endpoint\n * (`POST /api/v1/devices/identify`) -- the same shapes\n * `@atol-sh/fingerprint` returns from `identify()`. Both packages validate\n * the response before exposing it. 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 device_mismatch: boolean\n device_shared: boolean\n shared_user_count: number\n anomaly_score: number\n}\n\n/**\n * Raw identify response from the control plane (snake_case, verbatim).\n * The server always returns the exact smart-signal evaluation.\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\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, reset,\n * or failure; every successful server response contains the exact object. */\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 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. This boundary validates the\n * dynamically loaded package result independently before exposing state.\n */\ninterface FingerprintAgent {\n identify(options?: { authorize?: DeviceAuthorizationOwner }): Promise<unknown>\n}\n\ninterface FingerprintStatic {\n load(config?: { endpoint?: string }): Promise<FingerprintAgent>\n}\n\ninterface FingerprintModule {\n AtolFingerprint?: FingerprintStatic\n default?: FingerprintStatic\n}\n\n/** Exact identify request presented to the credential owner. */\nexport interface DeviceAuthorizationRequest {\n method: 'POST'\n url: string\n}\n\n/** One request's exact Bearer or DPoP authorization material. */\nexport type DeviceAuthorization =\n | {\n scheme: 'Bearer'\n accessToken: string\n }\n | {\n scheme: 'DPoP'\n accessToken: string\n dpopProof: string\n }\n\n/**\n * Acquire authorization for the exact identify request. The collector passes\n * this owner through for one operation and does not retain its result.\n */\nexport type DeviceAuthorizationOwner = (\n request: Readonly<DeviceAuthorizationRequest>,\n) => Promise<DeviceAuthorization>\n\n/**\n * One credential generation's identify authority. Increment the non-secret\n * generation whenever the owning session rotates or changes organization.\n */\nexport interface DeviceCollectionRequest {\n credentialGeneration: number\n authorize: DeviceAuthorizationOwner\n}\n\ntype DeviceDiagnosticCode =\n | 'device_dependency_unavailable'\n | 'device_dependency_invalid'\n | 'device_initialization_failed'\n | 'device_collection_failed'\n | 'device_credential_generation_invalid'\n | 'device_response_invalid'\n\nclass DeviceDiagnosticError extends Error {\n readonly code: DeviceDiagnosticCode\n\n constructor(code: DeviceDiagnosticCode, message: string) {\n super(message)\n this.code = code\n this.name = 'DeviceDiagnosticError'\n }\n}\n\n/**\n * Map the exact server signals object onto SmartSignals. Missing, null,\n * unknown, or mistyped members are a contract failure.\n */\nexport function parseSignals(raw: unknown): SmartSignals {\n const expectedKeys = [\n 'anomaly_score',\n 'bot',\n 'device_mismatch',\n 'device_shared',\n 'emulator',\n 'geo_mismatch',\n 'incognito',\n 'proxy',\n 'rooted',\n 'shared_user_count',\n 'tampered',\n 'tor',\n 'vpn',\n ]\n if (!isExactRecord(raw, expectedKeys)) {\n throw invalidDeviceResponse()\n }\n const r = raw as Record<string, unknown>\n if (\n typeof r.bot !== 'boolean' ||\n typeof r.vpn !== 'boolean' ||\n typeof r.proxy !== 'boolean' ||\n typeof r.tor !== 'boolean' ||\n typeof r.incognito !== 'boolean' ||\n typeof r.tampered !== 'boolean' ||\n typeof r.emulator !== 'boolean' ||\n typeof r.rooted !== 'boolean' ||\n typeof r.geo_mismatch !== 'boolean' ||\n typeof r.device_mismatch !== 'boolean' ||\n typeof r.device_shared !== 'boolean' ||\n typeof r.shared_user_count !== 'number' ||\n !Number.isSafeInteger(r.shared_user_count) ||\n r.shared_user_count < 0 ||\n !isProbability(r.anomaly_score)\n ) {\n throw invalidDeviceResponse()\n }\n return {\n bot: r.bot,\n vpn: r.vpn,\n proxy: r.proxy,\n tor: r.tor,\n incognito: r.incognito,\n tampered: r.tampered,\n emulator: r.emulator,\n rooted: r.rooted,\n geo_mismatch: r.geo_mismatch,\n device_mismatch: r.device_mismatch,\n device_shared: r.device_shared,\n shared_user_count: r.shared_user_count,\n anomaly_score: r.anomaly_score,\n }\n}\n\nfunction isExactRecord(\n value: unknown,\n expectedKeys: readonly string[],\n): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false\n }\n const actualKeys = Object.keys(value).sort()\n return (\n actualKeys.length === expectedKeys.length &&\n actualKeys.every((key, index) => key === expectedKeys[index])\n )\n}\n\nfunction isProbability(value: unknown): value is number {\n return (\n typeof value === 'number' &&\n Number.isFinite(value) &&\n value >= 0 &&\n value <= 1\n )\n}\n\nfunction invalidDeviceResponse(): DeviceDiagnosticError {\n return new DeviceDiagnosticError(\n 'device_response_invalid',\n 'Device intelligence returned an invalid response.',\n )\n}\n\n/** Validate and map a raw identify result to the fully-populated DeviceState. */\nexport function deviceStateFromResult(result: unknown): DeviceState {\n const expectedKeys = [\n 'browser',\n 'confidence',\n 'device_id',\n 'known',\n 'new_device',\n 'os_version',\n 'platform',\n 'signals',\n ]\n if (!isExactRecord(result, expectedKeys)) {\n throw invalidDeviceResponse()\n }\n if (\n typeof result.device_id !== 'string' ||\n result.device_id.length === 0 ||\n typeof result.known !== 'boolean' ||\n typeof result.new_device !== 'boolean' ||\n result.known === result.new_device ||\n !isProbability(result.confidence) ||\n typeof result.platform !== 'string' ||\n typeof result.browser !== 'string' ||\n typeof result.os_version !== 'string'\n ) {\n throw invalidDeviceResponse()\n }\n return {\n deviceId: result.device_id,\n known: result.known,\n confidence: result.confidence,\n newDevice: result.new_device,\n platform: result.platform,\n browser: result.browser,\n osVersion: result.os_version,\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 credential-generation changes or intervals.\n *\n * The agent is loaded once for this endpoint-bound collector. Calls for one\n * credential generation are single-flight. A newer generation becomes the\n * latest intent immediately, so a late older result cannot publish state.\n */\nexport class DeviceCollector {\n private agent: FingerprintAgent | null = null\n private agentLoad: Promise<FingerprintAgent> | null = null\n private readonly inFlight = new Map<number, Promise<void>>()\n private highestCredentialGeneration = 0\n private invalidatedGenerationFloor = 0\n private latestIntent = 0\n\n constructor(\n private readonly apiUrl: string,\n private readonly onState: (state: DeviceState) => void,\n ) {}\n\n /**\n * Pre-load the fingerprint agent without changing credential authority.\n * A later collect or invalidate operation fences this preparation's state.\n */\n async prepare(): Promise<void> {\n const intent = this.latestIntent\n try {\n await this.loadAgent()\n this.publishPreparation(intent, {\n ...initialDeviceState,\n loading: false,\n })\n } catch (err) {\n const error =\n err instanceof DeviceDiagnosticError\n ? err\n : new DeviceDiagnosticError(\n 'device_collection_failed',\n 'Device intelligence collection failed. Retry the request.',\n )\n this.publishPreparation(intent, {\n ...initialDeviceState,\n loading: false,\n error,\n })\n }\n }\n\n /**\n * Submit one credential generation's identify operation. Generations are\n * strictly monotonic for this collector's lifetime. A lower delayed\n * generation is ignored before authorization or network dispatch, while a\n * newer generation immediately fences every older result.\n */\n collect(request: DeviceCollectionRequest): Promise<void> {\n const {\n credentialGeneration: generation,\n authorize,\n } = request\n if (!Number.isSafeInteger(generation) || generation <= 0) {\n return Promise.reject(\n new DeviceDiagnosticError(\n 'device_credential_generation_invalid',\n 'Device intelligence requires a positive credential generation.',\n ),\n )\n }\n if (\n generation < this.highestCredentialGeneration ||\n generation <= this.invalidatedGenerationFloor\n ) {\n return Promise.resolve()\n }\n const existing = this.inFlight.get(generation)\n if (existing) {\n return existing\n }\n if (generation > this.highestCredentialGeneration) {\n this.highestCredentialGeneration = generation\n }\n const intent = ++this.latestIntent\n\n const operation = (async () => {\n this.publish(intent, { ...initialDeviceState, loading: true })\n try {\n const agent = await this.loadAgent()\n let result: unknown\n try {\n result = await agent.identify({ authorize })\n } catch {\n throw new DeviceDiagnosticError(\n 'device_collection_failed',\n 'Device intelligence collection failed. Retry the request.',\n )\n }\n this.publish(intent, deviceStateFromResult(result))\n } catch (err) {\n const error =\n err instanceof DeviceDiagnosticError\n ? err\n : new DeviceDiagnosticError(\n 'device_collection_failed',\n 'Device intelligence collection failed. Retry the request.',\n )\n this.publish(intent, { ...initialDeviceState, loading: false, error })\n }\n })()\n\n let run: Promise<void>\n run = operation.finally(() => {\n if (this.inFlight.get(generation) === run) {\n this.inFlight.delete(generation)\n }\n })\n this.inFlight.set(generation, run)\n return run\n }\n\n /**\n * Fence every in-flight identify and clear published device state. Future\n * credentials must continue with a generation higher than any accepted one.\n */\n invalidate(): void {\n this.latestIntent++\n this.invalidatedGenerationFloor = Math.max(\n this.invalidatedGenerationFloor,\n this.highestCredentialGeneration,\n )\n this.onState(initialDeviceState)\n }\n\n private publishPreparation(intent: number, state: DeviceState): void {\n if (this.highestCredentialGeneration === 0) {\n this.publish(intent, state)\n }\n }\n\n private publish(intent: number, state: DeviceState): void {\n if (intent === this.latestIntent) {\n this.onState(state)\n }\n }\n\n private async loadAgent(): Promise<FingerprintAgent> {\n if (this.agent) {\n return this.agent\n }\n if (this.agentLoad) {\n return this.agentLoad\n }\n\n const load = (async () => {\n let mod: FingerprintModule\n try {\n mod = (await import('@atol-sh/fingerprint')) as FingerprintModule\n } catch {\n throw new DeviceDiagnosticError(\n 'device_dependency_unavailable',\n 'device intelligence is enabled but @atol-sh/fingerprint is not ' +\n 'installed -- run `npm i @atol-sh/fingerprint` or disable device ' +\n 'intelligence',\n )\n }\n const AtolFingerprint = mod.AtolFingerprint ?? mod.default\n if (!AtolFingerprint) {\n throw new DeviceDiagnosticError(\n 'device_dependency_invalid',\n '@atol-sh/fingerprint loaded but exports no AtolFingerprint -- ' +\n 'check the installed package version',\n )\n }\n\n try {\n const agent = await AtolFingerprint.load({ endpoint: this.apiUrl })\n this.agent = agent\n return agent\n } catch {\n throw new DeviceDiagnosticError(\n 'device_initialization_failed',\n 'Device intelligence could not be initialized. Retry or disable device intelligence.',\n )\n }\n })()\n\n this.agentLoad = load\n try {\n return await load\n } finally {\n if (this.agentLoad === load) {\n this.agentLoad = null\n }\n }\n }\n}\n"]}