@abraca/dabra 2.101.0 → 2.103.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.
Files changed (151) hide show
  1. package/dist/abracadabra-provider.cjs +6673 -6543
  2. package/dist/abracadabra-provider.cjs.map +1 -1
  3. package/dist/esm/AbracadabraBaseProvider.js +558 -0
  4. package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
  5. package/dist/esm/AbracadabraClient.js +1424 -0
  6. package/dist/esm/AbracadabraClient.js.map +1 -0
  7. package/dist/esm/AbracadabraProvider.js +547 -0
  8. package/dist/esm/AbracadabraProvider.js.map +1 -0
  9. package/dist/esm/AbracadabraWS.js +398 -0
  10. package/dist/esm/AbracadabraWS.js.map +1 -0
  11. package/dist/esm/BackgroundSyncManager.js +571 -0
  12. package/dist/esm/BackgroundSyncManager.js.map +1 -0
  13. package/dist/esm/BackgroundSyncPersistence.js +62 -0
  14. package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
  15. package/dist/esm/ChatClient.js +176 -0
  16. package/dist/esm/ChatClient.js.map +1 -0
  17. package/dist/esm/CloseEvents.js +45 -0
  18. package/dist/esm/CloseEvents.js.map +1 -0
  19. package/dist/esm/ContentManager.js +153 -0
  20. package/dist/esm/ContentManager.js.map +1 -0
  21. package/dist/esm/CoverReconcile.js +124 -0
  22. package/dist/esm/CoverReconcile.js.map +1 -0
  23. package/dist/esm/CryptoIdentityKeystore.js +580 -0
  24. package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
  25. package/dist/esm/DeviceRegistrationService.js +158 -0
  26. package/dist/esm/DeviceRegistrationService.js.map +1 -0
  27. package/dist/esm/DocConverters.js +1300 -0
  28. package/dist/esm/DocConverters.js.map +1 -0
  29. package/dist/esm/DocKeyManager.js +145 -0
  30. package/dist/esm/DocKeyManager.js.map +1 -0
  31. package/dist/esm/DocTypes.js +792 -0
  32. package/dist/esm/DocTypes.js.map +1 -0
  33. package/dist/esm/DocUtils.js +180 -0
  34. package/dist/esm/DocUtils.js.map +1 -0
  35. package/dist/esm/DocumentCache.js +131 -0
  36. package/dist/esm/DocumentCache.js.map +1 -0
  37. package/dist/esm/DocumentManager.js +240 -0
  38. package/dist/esm/DocumentManager.js.map +1 -0
  39. package/dist/esm/E2EAbracadabraProvider.js +273 -0
  40. package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
  41. package/dist/esm/E2EOfflineStore.js +53 -0
  42. package/dist/esm/E2EOfflineStore.js.map +1 -0
  43. package/dist/esm/EncryptedChatClient.js +156 -0
  44. package/dist/esm/EncryptedChatClient.js.map +1 -0
  45. package/dist/esm/EncryptedY.js +115 -0
  46. package/dist/esm/EncryptedY.js.map +1 -0
  47. package/dist/esm/EventEmitter.js +40 -0
  48. package/dist/esm/EventEmitter.js.map +1 -0
  49. package/dist/esm/FileBlobStore.js +410 -0
  50. package/dist/esm/FileBlobStore.js.map +1 -0
  51. package/dist/esm/IdentityDoc.js +413 -0
  52. package/dist/esm/IdentityDoc.js.map +1 -0
  53. package/dist/esm/IncomingMessage.js +39 -0
  54. package/dist/esm/IncomingMessage.js.map +1 -0
  55. package/dist/esm/LifecycleGate.js +124 -0
  56. package/dist/esm/LifecycleGate.js.map +1 -0
  57. package/dist/esm/MessageReceiver.js +86 -0
  58. package/dist/esm/MessageReceiver.js.map +1 -0
  59. package/dist/esm/MessageSender.js +19 -0
  60. package/dist/esm/MessageSender.js.map +1 -0
  61. package/dist/esm/MetaManager.js +112 -0
  62. package/dist/esm/MetaManager.js.map +1 -0
  63. package/dist/esm/MnemonicKeyDerivation.js +137 -0
  64. package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
  65. package/dist/esm/NodeConnect.js +63 -0
  66. package/dist/esm/NodeConnect.js.map +1 -0
  67. package/dist/esm/NodeIdentity.js +212 -0
  68. package/dist/esm/NodeIdentity.js.map +1 -0
  69. package/dist/esm/NotificationsClient.js +136 -0
  70. package/dist/esm/NotificationsClient.js.map +1 -0
  71. package/dist/esm/OfflineStore.js +291 -0
  72. package/dist/esm/OfflineStore.js.map +1 -0
  73. package/dist/esm/OutgoingMessage.js +18 -0
  74. package/dist/esm/OutgoingMessage.js.map +1 -0
  75. package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
  76. package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
  77. package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
  78. package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
  79. package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
  80. package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
  81. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
  82. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
  83. package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
  84. package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
  85. package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
  86. package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
  87. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
  88. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
  89. package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
  90. package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
  91. package/dist/esm/PerfCounters.js +336 -0
  92. package/dist/esm/PerfCounters.js.map +1 -0
  93. package/dist/esm/QueryClient.js +117 -0
  94. package/dist/esm/QueryClient.js.map +1 -0
  95. package/dist/esm/RpcClient.js +456 -0
  96. package/dist/esm/RpcClient.js.map +1 -0
  97. package/dist/esm/SchemaTypes.js +38 -0
  98. package/dist/esm/SchemaTypes.js.map +1 -0
  99. package/dist/esm/SearchIndex.js +167 -0
  100. package/dist/esm/SearchIndex.js.map +1 -0
  101. package/dist/esm/ServerRegistry.js +139 -0
  102. package/dist/esm/ServerRegistry.js.map +1 -0
  103. package/dist/esm/ServerReset.js +170 -0
  104. package/dist/esm/ServerReset.js.map +1 -0
  105. package/dist/esm/TokenManager.js +236 -0
  106. package/dist/esm/TokenManager.js.map +1 -0
  107. package/dist/esm/TreeManager.js +655 -0
  108. package/dist/esm/TreeManager.js.map +1 -0
  109. package/dist/esm/TreeTimestamps.js +61 -0
  110. package/dist/esm/TreeTimestamps.js.map +1 -0
  111. package/dist/esm/auth.js +43 -0
  112. package/dist/esm/auth.js.map +1 -0
  113. package/dist/esm/awarenessStatesToArray.js +13 -0
  114. package/dist/esm/awarenessStatesToArray.js.map +1 -0
  115. package/dist/esm/docIds.js +53 -0
  116. package/dist/esm/docIds.js.map +1 -0
  117. package/dist/esm/encryptedContent.js +21 -0
  118. package/dist/esm/encryptedContent.js.map +1 -0
  119. package/dist/esm/index.js +61 -0
  120. package/dist/esm/messageRecord.js +64 -0
  121. package/dist/esm/messageRecord.js.map +1 -0
  122. package/dist/esm/sync/BroadcastChannelSync.js +160 -0
  123. package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
  124. package/dist/esm/types.js +54 -0
  125. package/dist/esm/types.js.map +1 -0
  126. package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
  127. package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
  128. package/dist/esm/webrtc/DataChannelRouter.js +124 -0
  129. package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
  130. package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
  131. package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
  132. package/dist/esm/webrtc/E2EEChannel.js +137 -0
  133. package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
  134. package/dist/esm/webrtc/FileTransferChannel.js +250 -0
  135. package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
  136. package/dist/esm/webrtc/ManualSignaling.js +161 -0
  137. package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
  138. package/dist/esm/webrtc/PeerConnection.js +96 -0
  139. package/dist/esm/webrtc/PeerConnection.js.map +1 -0
  140. package/dist/esm/webrtc/SignalingSocket.js +274 -0
  141. package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
  142. package/dist/esm/webrtc/YjsDataChannel.js +135 -0
  143. package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
  144. package/dist/esm/webrtc/types.js +29 -0
  145. package/dist/esm/webrtc/types.js.map +1 -0
  146. package/dist/esm/x25519Convert.js +69 -0
  147. package/dist/esm/x25519Convert.js.map +1 -0
  148. package/dist/index.d.ts +26 -11
  149. package/package.json +6 -4
  150. package/dist/abracadabra-provider.esm.js +0 -14860
  151. package/dist/abracadabra-provider.esm.js.map +0 -1
@@ -0,0 +1,236 @@
1
+ import EventEmitter from "./EventEmitter.js";
2
+
3
+ //#region packages/provider/src/TokenManager.ts
4
+ const DEFAULT_STORAGE_KEY = "abracadabra:device-session";
5
+ /** localStorage-backed storage; safe in SSR/Node (no-ops without localStorage). */
6
+ var LocalStorageDeviceSessionStorage = class {
7
+ constructor(key = DEFAULT_STORAGE_KEY) {
8
+ this.key = key;
9
+ }
10
+ load() {
11
+ try {
12
+ const raw = localStorage.getItem(this.key);
13
+ if (!raw) return null;
14
+ const parsed = JSON.parse(raw);
15
+ if (typeof parsed?.sessionId === "string" && typeof parsed?.sessionToken === "string" && typeof parsed?.expiresAt === "number") return parsed;
16
+ return null;
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+ save(record) {
22
+ try {
23
+ localStorage.setItem(this.key, JSON.stringify(record));
24
+ } catch {}
25
+ }
26
+ clear() {
27
+ try {
28
+ localStorage.removeItem(this.key);
29
+ } catch {}
30
+ }
31
+ };
32
+ /**
33
+ * Manages the lifetime of the short-lived JWT against a long-lived device
34
+ * session token.
35
+ *
36
+ * Flow:
37
+ * - Bootstrap: if a stored device session exists, exchange it for a fresh
38
+ * JWT immediately (`bootstrap()`). Otherwise the consumer must run a
39
+ * full crypto-auth handshake and then call `attachSession(record)` once
40
+ * the server returns a device-session token.
41
+ * - Steady state: `getValidToken()` returns the JWT, refreshing if the
42
+ * JWT is within `refreshLeadMs` of expiry. Concurrent callers share one
43
+ * in-flight refresh.
44
+ * - Background: a proactive timer fires `refreshLeadMs` before `exp`.
45
+ * `visibilitychange` and `online` events trigger an opportunistic
46
+ * refresh in case the timer was suppressed (hidden tab, sleeping
47
+ * laptop). The combination is what restores the WS without a reload.
48
+ * - Failure: refresh errors with status 401/403 mean the device session
49
+ * itself is dead (revoked or 30 d expired). The record is cleared and
50
+ * `session-expired` fires so the consumer can prompt re-auth. Other
51
+ * errors (network) are transparent — the existing JWT is returned and
52
+ * the caller's normal retry loop covers it.
53
+ */
54
+ var TokenManager = class extends EventEmitter {
55
+ constructor(options) {
56
+ super();
57
+ this.refreshing = null;
58
+ this.proactiveTimer = null;
59
+ this.resumeHandlersInstalled = false;
60
+ this.boundOnResume = null;
61
+ this.disposed = false;
62
+ this.client = options.client;
63
+ this.storage = options.storage ?? new LocalStorageDeviceSessionStorage();
64
+ this.refreshLeadMs = options.refreshLeadMs ?? 300 * 1e3;
65
+ this.session = this.storage.load();
66
+ if (options.installResumeHandlers !== false) this.installResumeHandlers();
67
+ this.scheduleProactiveRefresh();
68
+ }
69
+ get hasSession() {
70
+ return this.session !== null;
71
+ }
72
+ get currentSession() {
73
+ return this.session;
74
+ }
75
+ /**
76
+ * Persist a freshly-issued device session and exchange it immediately
77
+ * for a JWT. Call this once after a successful crypto-auth login when
78
+ * the server returns a device-session token.
79
+ */
80
+ async attachSession(record) {
81
+ this.session = record;
82
+ this.storage.save(record);
83
+ return await this.runRefresh();
84
+ }
85
+ /**
86
+ * Drop the local device session (no server call). Use after a logout
87
+ * or when `session-expired` fires. To revoke server-side as well, call
88
+ * `client.revokeDeviceSession(sessionId)` first.
89
+ */
90
+ clearSession() {
91
+ this.session = null;
92
+ this.storage.clear();
93
+ if (this.proactiveTimer) {
94
+ clearTimeout(this.proactiveTimer);
95
+ this.proactiveTimer = null;
96
+ }
97
+ }
98
+ /**
99
+ * Return a valid JWT, refreshing if it is missing or within
100
+ * `refreshLeadMs` of expiry. Safe to call concurrently — one
101
+ * refresh is in flight at a time.
102
+ *
103
+ * Transient refresh errors (network) fall back to the cached JWT so
104
+ * the WS auth attempt can still proceed; the server will reject and
105
+ * the next reconnect tries again. Only 401/403 from the refresh
106
+ * endpoint surfaces as a thrown error here, since those mean the
107
+ * device session itself is dead.
108
+ */
109
+ async getValidToken() {
110
+ if (this.refreshing) return this.refreshing;
111
+ const current = this.client.token;
112
+ if (current && this.tokenIsFresh(current)) return current;
113
+ if (!this.session) return current ?? "";
114
+ try {
115
+ return await this.runRefresh();
116
+ } catch (err) {
117
+ const status = err?.status;
118
+ if (status === 401 || status === 403) throw err;
119
+ return current ?? "";
120
+ }
121
+ }
122
+ /**
123
+ * If a stored device session exists, exchange it for a fresh JWT now.
124
+ * Returns the JWT (or null if there is no session to bootstrap from).
125
+ * Throws on 401/403 — the stored session is invalid and the caller
126
+ * should fall through to a full crypto-auth flow.
127
+ */
128
+ async bootstrap() {
129
+ if (!this.session) return null;
130
+ try {
131
+ return await this.runRefresh();
132
+ } catch (err) {
133
+ const status = err?.status;
134
+ if (status === 401 || status === 403) throw err;
135
+ return null;
136
+ }
137
+ }
138
+ dispose() {
139
+ if (this.disposed) return;
140
+ this.disposed = true;
141
+ if (this.proactiveTimer) {
142
+ clearTimeout(this.proactiveTimer);
143
+ this.proactiveTimer = null;
144
+ }
145
+ if (this.boundOnResume) {
146
+ try {
147
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", this.boundOnResume);
148
+ if (typeof window !== "undefined") window.removeEventListener("online", this.boundOnResume);
149
+ } catch {}
150
+ this.boundOnResume = null;
151
+ }
152
+ this.removeAllListeners();
153
+ }
154
+ runRefresh() {
155
+ if (this.refreshing) return this.refreshing;
156
+ if (!this.session) return Promise.reject(/* @__PURE__ */ new Error("No device session"));
157
+ const sessionToken = this.session.sessionToken;
158
+ this.refreshing = (async () => {
159
+ try {
160
+ const jwt = await this.client.refreshWithDeviceSession(sessionToken);
161
+ this.scheduleProactiveRefresh();
162
+ this.emit("refresh", jwt);
163
+ return jwt;
164
+ } catch (err) {
165
+ const status = err?.status;
166
+ if (status === 401 || status === 403) {
167
+ const message = err?.message ?? "device session rejected";
168
+ this.clearSession();
169
+ this.emit("session-expired", {
170
+ status,
171
+ message
172
+ });
173
+ }
174
+ throw err;
175
+ } finally {
176
+ this.refreshing = null;
177
+ }
178
+ })();
179
+ return this.refreshing;
180
+ }
181
+ tokenIsFresh(jwt) {
182
+ const exp = this.parseExp(jwt);
183
+ if (exp == null) return false;
184
+ return exp * 1e3 - Date.now() > this.refreshLeadMs;
185
+ }
186
+ parseExp(jwt) {
187
+ try {
188
+ const [, payload] = jwt.split(".");
189
+ if (!payload) return null;
190
+ let b64 = payload.replace(/-/g, "+").replace(/_/g, "/");
191
+ const pad = b64.length % 4;
192
+ if (pad) b64 += "=".repeat(4 - pad);
193
+ const json = new TextDecoder().decode(Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)));
194
+ const { exp } = JSON.parse(json);
195
+ return typeof exp === "number" ? exp : null;
196
+ } catch {
197
+ return null;
198
+ }
199
+ }
200
+ scheduleProactiveRefresh() {
201
+ if (this.proactiveTimer) {
202
+ clearTimeout(this.proactiveTimer);
203
+ this.proactiveTimer = null;
204
+ }
205
+ if (!this.session || this.disposed) return;
206
+ const jwt = this.client.token;
207
+ const exp = jwt ? this.parseExp(jwt) : null;
208
+ if (exp == null) return;
209
+ const delay = Math.max(3e4, exp * 1e3 - Date.now() - this.refreshLeadMs);
210
+ this.proactiveTimer = setTimeout(() => {
211
+ this.runRefresh().catch(() => {});
212
+ }, delay);
213
+ }
214
+ installResumeHandlers() {
215
+ if (this.resumeHandlersInstalled) return;
216
+ if (typeof document === "undefined" && typeof window === "undefined") return;
217
+ const onResume = () => {
218
+ if (this.disposed) return;
219
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
220
+ if (!this.session) return;
221
+ const jwt = this.client.token;
222
+ if (jwt && this.tokenIsFresh(jwt)) return;
223
+ this.runRefresh().catch(() => {});
224
+ };
225
+ this.boundOnResume = onResume;
226
+ try {
227
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", onResume);
228
+ if (typeof window !== "undefined") window.addEventListener("online", onResume);
229
+ this.resumeHandlersInstalled = true;
230
+ } catch {}
231
+ }
232
+ };
233
+
234
+ //#endregion
235
+ export { LocalStorageDeviceSessionStorage, TokenManager };
236
+ //# sourceMappingURL=TokenManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TokenManager.js","names":[],"sources":["../../src/TokenManager.ts"],"sourcesContent":["import EventEmitter from \"./EventEmitter.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\n\n/**\n * On-disk shape of a device session. The server returns these values from\n * `POST /auth/device-session`; persistence keeps them across reloads so a\n * warm boot can mint a fresh JWT without re-prompting for the passkey.\n */\nexport interface DeviceSessionRecord {\n\tsessionId: string;\n\tsessionToken: string;\n\t/** Unix seconds — matches what the server returns. */\n\texpiresAt: number;\n}\n\nexport interface DeviceSessionStorage {\n\tload(): DeviceSessionRecord | null;\n\tsave(record: DeviceSessionRecord): void;\n\tclear(): void;\n}\n\nconst DEFAULT_STORAGE_KEY = \"abracadabra:device-session\";\n\n/** localStorage-backed storage; safe in SSR/Node (no-ops without localStorage). */\nexport class LocalStorageDeviceSessionStorage implements DeviceSessionStorage {\n\tconstructor(private readonly key: string = DEFAULT_STORAGE_KEY) {}\n\n\tload(): DeviceSessionRecord | null {\n\t\ttry {\n\t\t\tconst raw = localStorage.getItem(this.key);\n\t\t\tif (!raw) return null;\n\t\t\tconst parsed = JSON.parse(raw) as DeviceSessionRecord;\n\t\t\tif (\n\t\t\t\ttypeof parsed?.sessionId === \"string\" &&\n\t\t\t\ttypeof parsed?.sessionToken === \"string\" &&\n\t\t\t\ttypeof parsed?.expiresAt === \"number\"\n\t\t\t) {\n\t\t\t\treturn parsed;\n\t\t\t}\n\t\t\treturn null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tsave(record: DeviceSessionRecord): void {\n\t\ttry {\n\t\t\tlocalStorage.setItem(this.key, JSON.stringify(record));\n\t\t} catch {\n\t\t\t/* localStorage unavailable */\n\t\t}\n\t}\n\n\tclear(): void {\n\t\ttry {\n\t\t\tlocalStorage.removeItem(this.key);\n\t\t} catch {\n\t\t\t/* localStorage unavailable */\n\t\t}\n\t}\n}\n\nexport interface TokenManagerOptions {\n\tclient: AbracadabraClient;\n\t/**\n\t * Where the device session record lives. Defaults to a localStorage\n\t * adapter under \"abracadabra:device-session\".\n\t */\n\tstorage?: DeviceSessionStorage;\n\t/**\n\t * Refresh the JWT this many milliseconds before its `exp`. Defaults to\n\t * 5 minutes — well clear of clock skew without burning a refresh per\n\t * minute. Refreshes are also dedup'd via in-flight promise.\n\t */\n\trefreshLeadMs?: number;\n\t/**\n\t * Hook `document.visibilitychange` and `window.online` to opportunistically\n\t * refresh when the tab/network resumes. Default true. The proactive\n\t * `setTimeout` doesn't fire reliably while the tab is hidden or the\n\t * laptop is asleep, which is the actual breakage path being addressed —\n\t * the resume hook is what makes the system self-heal after a long sleep.\n\t */\n\tinstallResumeHandlers?: boolean;\n}\n\n/**\n * Manages the lifetime of the short-lived JWT against a long-lived device\n * session token.\n *\n * Flow:\n * - Bootstrap: if a stored device session exists, exchange it for a fresh\n * JWT immediately (`bootstrap()`). Otherwise the consumer must run a\n * full crypto-auth handshake and then call `attachSession(record)` once\n * the server returns a device-session token.\n * - Steady state: `getValidToken()` returns the JWT, refreshing if the\n * JWT is within `refreshLeadMs` of expiry. Concurrent callers share one\n * in-flight refresh.\n * - Background: a proactive timer fires `refreshLeadMs` before `exp`.\n * `visibilitychange` and `online` events trigger an opportunistic\n * refresh in case the timer was suppressed (hidden tab, sleeping\n * laptop). The combination is what restores the WS without a reload.\n * - Failure: refresh errors with status 401/403 mean the device session\n * itself is dead (revoked or 30 d expired). The record is cleared and\n * `session-expired` fires so the consumer can prompt re-auth. Other\n * errors (network) are transparent — the existing JWT is returned and\n * the caller's normal retry loop covers it.\n */\nexport class TokenManager extends EventEmitter {\n\tprivate readonly client: AbracadabraClient;\n\tprivate readonly storage: DeviceSessionStorage;\n\tprivate readonly refreshLeadMs: number;\n\tprivate session: DeviceSessionRecord | null;\n\tprivate refreshing: Promise<string> | null = null;\n\tprivate proactiveTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate resumeHandlersInstalled = false;\n\tprivate boundOnResume: (() => void) | null = null;\n\tprivate disposed = false;\n\n\tconstructor(options: TokenManagerOptions) {\n\t\tsuper();\n\t\tthis.client = options.client;\n\t\tthis.storage = options.storage ?? new LocalStorageDeviceSessionStorage();\n\t\tthis.refreshLeadMs = options.refreshLeadMs ?? 5 * 60 * 1000;\n\t\tthis.session = this.storage.load();\n\t\tif (options.installResumeHandlers !== false) {\n\t\t\tthis.installResumeHandlers();\n\t\t}\n\t\t// Schedule a refresh against the JWT the client may already be\n\t\t// holding (loaded from persistAuth localStorage) so warm boots\n\t\t// without an explicit bootstrap() still benefit from proactive\n\t\t// refresh on the existing token.\n\t\tthis.scheduleProactiveRefresh();\n\t}\n\n\tget hasSession(): boolean {\n\t\treturn this.session !== null;\n\t}\n\n\tget currentSession(): DeviceSessionRecord | null {\n\t\treturn this.session;\n\t}\n\n\t/**\n\t * Persist a freshly-issued device session and exchange it immediately\n\t * for a JWT. Call this once after a successful crypto-auth login when\n\t * the server returns a device-session token.\n\t */\n\tasync attachSession(record: DeviceSessionRecord): Promise<string> {\n\t\tthis.session = record;\n\t\tthis.storage.save(record);\n\t\tconst jwt = await this.runRefresh();\n\t\treturn jwt;\n\t}\n\n\t/**\n\t * Drop the local device session (no server call). Use after a logout\n\t * or when `session-expired` fires. To revoke server-side as well, call\n\t * `client.revokeDeviceSession(sessionId)` first.\n\t */\n\tclearSession(): void {\n\t\tthis.session = null;\n\t\tthis.storage.clear();\n\t\tif (this.proactiveTimer) {\n\t\t\tclearTimeout(this.proactiveTimer);\n\t\t\tthis.proactiveTimer = null;\n\t\t}\n\t}\n\n\t/**\n\t * Return a valid JWT, refreshing if it is missing or within\n\t * `refreshLeadMs` of expiry. Safe to call concurrently — one\n\t * refresh is in flight at a time.\n\t *\n\t * Transient refresh errors (network) fall back to the cached JWT so\n\t * the WS auth attempt can still proceed; the server will reject and\n\t * the next reconnect tries again. Only 401/403 from the refresh\n\t * endpoint surfaces as a thrown error here, since those mean the\n\t * device session itself is dead.\n\t */\n\tasync getValidToken(): Promise<string> {\n\t\tif (this.refreshing) return this.refreshing;\n\t\tconst current = this.client.token;\n\t\tif (current && this.tokenIsFresh(current)) return current;\n\t\tif (!this.session) return current ?? \"\";\n\t\ttry {\n\t\t\treturn await this.runRefresh();\n\t\t} catch (err) {\n\t\t\tconst status = (err as { status?: number })?.status;\n\t\t\tif (status === 401 || status === 403) throw err;\n\t\t\t// Transient — let the caller use the stale token; the server\n\t\t\t// will reject and the WS reconnect loop will retry the refresh.\n\t\t\treturn current ?? \"\";\n\t\t}\n\t}\n\n\t/**\n\t * If a stored device session exists, exchange it for a fresh JWT now.\n\t * Returns the JWT (or null if there is no session to bootstrap from).\n\t * Throws on 401/403 — the stored session is invalid and the caller\n\t * should fall through to a full crypto-auth flow.\n\t */\n\tasync bootstrap(): Promise<string | null> {\n\t\tif (!this.session) return null;\n\t\ttry {\n\t\t\treturn await this.runRefresh();\n\t\t} catch (err) {\n\t\t\tconst status = (err as { status?: number })?.status;\n\t\t\tif (status === 401 || status === 403) throw err;\n\t\t\t// Transient — caller decides what to do (e.g. fall back to\n\t\t\t// passkey login or proceed offline).\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\t\tif (this.proactiveTimer) {\n\t\t\tclearTimeout(this.proactiveTimer);\n\t\t\tthis.proactiveTimer = null;\n\t\t}\n\t\tif (this.boundOnResume) {\n\t\t\ttry {\n\t\t\t\tif (typeof document !== \"undefined\") {\n\t\t\t\t\tdocument.removeEventListener(\"visibilitychange\", this.boundOnResume);\n\t\t\t\t}\n\t\t\t\tif (typeof window !== \"undefined\") {\n\t\t\t\t\twindow.removeEventListener(\"online\", this.boundOnResume);\n\t\t\t\t}\n\t\t\t} catch { /* environment without listener APIs */ }\n\t\t\tthis.boundOnResume = null;\n\t\t}\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── internals ───────────────────────────────────────────────────────────\n\n\tprivate runRefresh(): Promise<string> {\n\t\tif (this.refreshing) return this.refreshing;\n\t\tif (!this.session) return Promise.reject(new Error(\"No device session\"));\n\t\tconst sessionToken = this.session.sessionToken;\n\t\tthis.refreshing = (async () => {\n\t\t\ttry {\n\t\t\t\tconst jwt = await this.client.refreshWithDeviceSession(sessionToken);\n\t\t\t\tthis.scheduleProactiveRefresh();\n\t\t\t\tthis.emit(\"refresh\", jwt);\n\t\t\t\treturn jwt;\n\t\t\t} catch (err) {\n\t\t\t\tconst status = (err as { status?: number })?.status;\n\t\t\t\tif (status === 401 || status === 403) {\n\t\t\t\t\tconst message = (err as Error)?.message ?? \"device session rejected\";\n\t\t\t\t\tthis.clearSession();\n\t\t\t\t\tthis.emit(\"session-expired\", { status, message });\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t} finally {\n\t\t\t\tthis.refreshing = null;\n\t\t\t}\n\t\t})();\n\t\treturn this.refreshing;\n\t}\n\n\tprivate tokenIsFresh(jwt: string): boolean {\n\t\tconst exp = this.parseExp(jwt);\n\t\tif (exp == null) return false;\n\t\treturn exp * 1000 - Date.now() > this.refreshLeadMs;\n\t}\n\n\tprivate parseExp(jwt: string): number | null {\n\t\ttry {\n\t\t\tconst [, payload] = jwt.split(\".\");\n\t\t\tif (!payload) return null;\n\t\t\t// base64url-safe: `atob` alone throws on `-`/`_`, which would make\n\t\t\t// the proactive-refresh timer treat a valid token as unparseable.\n\t\t\tlet b64 = payload.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\t\t\tconst pad = b64.length % 4;\n\t\t\tif (pad) b64 += \"=\".repeat(4 - pad);\n\t\t\tconst json = new TextDecoder().decode(\n\t\t\t\tUint8Array.from(atob(b64), (c) => c.charCodeAt(0)),\n\t\t\t);\n\t\t\tconst { exp } = JSON.parse(json);\n\t\t\treturn typeof exp === \"number\" ? exp : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate scheduleProactiveRefresh(): void {\n\t\tif (this.proactiveTimer) {\n\t\t\tclearTimeout(this.proactiveTimer);\n\t\t\tthis.proactiveTimer = null;\n\t\t}\n\t\tif (!this.session || this.disposed) return;\n\t\tconst jwt = this.client.token;\n\t\tconst exp = jwt ? this.parseExp(jwt) : null;\n\t\tif (exp == null) {\n\t\t\t// No JWT yet — defer; whoever calls getValidToken() / bootstrap()\n\t\t\t// will reschedule once a JWT lands.\n\t\t\treturn;\n\t\t}\n\t\t// Floor at 30 s so a near-expired token doesn't trigger a busy\n\t\t// refresh-then-immediately-refresh-again loop on clock skew.\n\t\tconst delay = Math.max(30_000, exp * 1000 - Date.now() - this.refreshLeadMs);\n\t\tthis.proactiveTimer = setTimeout(() => {\n\t\t\tthis.runRefresh().catch(() => {\n\t\t\t\t// 401/403 already surfaced via session-expired event;\n\t\t\t\t// transient errors are no-ops — the resume handler or the\n\t\t\t\t// next getValidToken() call will retry.\n\t\t\t});\n\t\t}, delay);\n\t}\n\n\tprivate installResumeHandlers(): void {\n\t\tif (this.resumeHandlersInstalled) return;\n\t\tif (typeof document === \"undefined\" && typeof window === \"undefined\") return;\n\t\tconst onResume = () => {\n\t\t\tif (this.disposed) return;\n\t\t\tif (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") return;\n\t\t\tif (!this.session) return;\n\t\t\tconst jwt = this.client.token;\n\t\t\tif (jwt && this.tokenIsFresh(jwt)) return;\n\t\t\tthis.runRefresh().catch(() => {\n\t\t\t\t/* same swallow as above */\n\t\t\t});\n\t\t};\n\t\tthis.boundOnResume = onResume;\n\t\ttry {\n\t\t\tif (typeof document !== \"undefined\") {\n\t\t\t\tdocument.addEventListener(\"visibilitychange\", onResume);\n\t\t\t}\n\t\t\tif (typeof window !== \"undefined\") {\n\t\t\t\twindow.addEventListener(\"online\", onResume);\n\t\t\t}\n\t\t\tthis.resumeHandlersInstalled = true;\n\t\t} catch { /* environment without listener APIs */ }\n\t}\n}\n"],"mappings":";;;AAqBA,MAAM,sBAAsB;;AAG5B,IAAa,mCAAb,MAA8E;CAC7E,YAAY,AAAiB,MAAc,qBAAqB;EAAnC;;CAE7B,OAAmC;AAClC,MAAI;GACH,MAAM,MAAM,aAAa,QAAQ,KAAK,IAAI;AAC1C,OAAI,CAAC,IAAK,QAAO;GACjB,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,OACC,OAAO,QAAQ,cAAc,YAC7B,OAAO,QAAQ,iBAAiB,YAChC,OAAO,QAAQ,cAAc,SAE7B,QAAO;AAER,UAAO;UACA;AACP,UAAO;;;CAIT,KAAK,QAAmC;AACvC,MAAI;AACH,gBAAa,QAAQ,KAAK,KAAK,KAAK,UAAU,OAAO,CAAC;UAC/C;;CAKT,QAAc;AACb,MAAI;AACH,gBAAa,WAAW,KAAK,IAAI;UAC1B;;;;;;;;;;;;;;;;;;;;;;;;;AAmDV,IAAa,eAAb,cAAkC,aAAa;CAW9C,YAAY,SAA8B;AACzC,SAAO;oBAPqC;wBACkB;iCAC7B;uBACW;kBAC1B;AAIlB,OAAK,SAAS,QAAQ;AACtB,OAAK,UAAU,QAAQ,WAAW,IAAI,kCAAkC;AACxE,OAAK,gBAAgB,QAAQ,iBAAiB,MAAS;AACvD,OAAK,UAAU,KAAK,QAAQ,MAAM;AAClC,MAAI,QAAQ,0BAA0B,MACrC,MAAK,uBAAuB;AAM7B,OAAK,0BAA0B;;CAGhC,IAAI,aAAsB;AACzB,SAAO,KAAK,YAAY;;CAGzB,IAAI,iBAA6C;AAChD,SAAO,KAAK;;;;;;;CAQb,MAAM,cAAc,QAA8C;AACjE,OAAK,UAAU;AACf,OAAK,QAAQ,KAAK,O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