@abraca/dabra 2.89.0 → 2.91.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/package.json +5 -11
- package/src/AbracadabraBaseProvider.ts +0 -963
- package/src/AbracadabraClient.ts +0 -1960
- package/src/AbracadabraProvider.ts +0 -915
- package/src/AbracadabraWS.ts +0 -695
- package/src/BackgroundSyncManager.ts +0 -856
- package/src/BackgroundSyncPersistence.ts +0 -140
- package/src/ChatClient.ts +0 -314
- package/src/CloseEvents.ts +0 -49
- package/src/ContentManager.ts +0 -246
- package/src/CoverReconcile.ts +0 -168
- package/src/CryptoIdentityKeystore.ts +0 -754
- package/src/DeviceRegistrationService.ts +0 -257
- package/src/DocConverters.ts +0 -1859
- package/src/DocKeyManager.ts +0 -163
- package/src/DocTypes.ts +0 -628
- package/src/DocUtils.ts +0 -251
- package/src/DocumentCache.ts +0 -210
- package/src/DocumentManager.ts +0 -410
- package/src/E2EAbracadabraProvider.ts +0 -426
- package/src/E2EOfflineStore.ts +0 -55
- package/src/EncryptedChatClient.ts +0 -173
- package/src/EncryptedY.ts +0 -145
- package/src/EventEmitter.ts +0 -59
- package/src/FileBlobStore.ts +0 -569
- package/src/IdentityDoc.ts +0 -711
- package/src/IncomingMessage.ts +0 -63
- package/src/MessageReceiver.ts +0 -151
- package/src/MessageSender.ts +0 -22
- package/src/MetaManager.ts +0 -194
- package/src/MnemonicKeyDerivation.ts +0 -171
- package/src/NodeConnect.ts +0 -63
- package/src/NodeIdentity.ts +0 -378
- package/src/NotificationsClient.ts +0 -207
- package/src/OfflineStore.ts +0 -294
- package/src/OutgoingMessage.ts +0 -25
- package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
- package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
- package/src/OutgoingMessages/CloseMessage.ts +0 -17
- package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
- package/src/OutgoingMessages/StatelessMessage.ts +0 -18
- package/src/OutgoingMessages/SubdocMessage.ts +0 -35
- package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
- package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
- package/src/OutgoingMessages/UpdateMessage.ts +0 -20
- package/src/QueryClient.ts +0 -209
- package/src/RpcClient.ts +0 -659
- package/src/SchemaTypes.ts +0 -179
- package/src/SearchIndex.ts +0 -250
- package/src/ServerRegistry.ts +0 -220
- package/src/ServerReset.ts +0 -222
- package/src/TokenManager.ts +0 -337
- package/src/TreeManager.ts +0 -894
- package/src/TreeTimestamps.ts +0 -101
- package/src/auth.ts +0 -62
- package/src/awarenessStatesToArray.ts +0 -10
- package/src/index.ts +0 -219
- package/src/messageRecord.ts +0 -121
- package/src/sync/BroadcastChannelSync.ts +0 -235
- package/src/types.ts +0 -790
- package/src/webrtc/AbracadabraWebRTC.ts +0 -683
- package/src/webrtc/DataChannelRouter.ts +0 -179
- package/src/webrtc/DevicePairingChannel.ts +0 -496
- package/src/webrtc/E2EEChannel.ts +0 -195
- package/src/webrtc/FileTransferChannel.ts +0 -367
- package/src/webrtc/ManualSignaling.ts +0 -204
- package/src/webrtc/PeerConnection.ts +0 -133
- package/src/webrtc/SignalingSocket.ts +0 -378
- package/src/webrtc/YjsDataChannel.ts +0 -203
- package/src/webrtc/index.ts +0 -26
- package/src/webrtc/types.ts +0 -177
package/src/ServerReset.ts
DELETED
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Detect that a server's database has been REPLACED, and drop this browser's
|
|
3
|
-
* caches for it before anything re-pushes them.
|
|
4
|
-
*
|
|
5
|
-
* ## The bug
|
|
6
|
-
*
|
|
7
|
-
* Deleting a backend's database does not give you a clean server. Every browser
|
|
8
|
-
* that was connected still holds that space's CRDT state in IndexedDB, and on
|
|
9
|
-
* reconnect it re-pushes the old tree into the fresh one. A seeder then adds its
|
|
10
|
-
* own on top and you get every page twice — `/about` AND `/about-1`. Repeat the
|
|
11
|
-
* cycle and it MULTIPLIES: `-2`, `-3`, `-4`.
|
|
12
|
-
*
|
|
13
|
-
* This is inherent to a CRDT and cannot be fixed downstream. A deleted database
|
|
14
|
-
* is not a tombstone; it is a peer that lost its memory, and the client is the
|
|
15
|
-
* one holding the newer state. No idempotency guard can see it — by the time one
|
|
16
|
-
* runs, the re-pushed tree looks exactly like real content.
|
|
17
|
-
*
|
|
18
|
-
* It is not a development-only annoyance. The expensive case is a production
|
|
19
|
-
* restore from backup, where the peers re-pushing stale trees are visitors who
|
|
20
|
-
* will never read a release note.
|
|
21
|
-
*
|
|
22
|
-
* ## Why the server can be believed
|
|
23
|
-
*
|
|
24
|
-
* The server mints a `server_id` and persists it beside its database. It
|
|
25
|
-
* survives restarts and changes when, and only when, that database is replaced.
|
|
26
|
-
* So it states outright what a CRDT cannot work out for itself: *the peer you
|
|
27
|
-
* are syncing with is not the one you have been talking to.*
|
|
28
|
-
*
|
|
29
|
-
* ## What gets dropped
|
|
30
|
-
*
|
|
31
|
-
* Everything this SDK scopes to a server, which is more than the document
|
|
32
|
-
* caches:
|
|
33
|
-
*
|
|
34
|
-
* | store | written by |
|
|
35
|
-
* |---|---|
|
|
36
|
-
* | `abracadabra:<host>/<docId>` | {@link OfflineStore} |
|
|
37
|
-
* | `abracadabra:meta-cache:<host>` | `DocumentCache` |
|
|
38
|
-
* | `abracadabra:files:<host>` | `FileBlobStore` |
|
|
39
|
-
* | `abracadabra:bgsync:<host>` | `BackgroundSyncPersistence` |
|
|
40
|
-
* | `abracadabra:search:<host>` | `SearchIndex` |
|
|
41
|
-
*
|
|
42
|
-
* One ANCHORED rule covers all five shapes, so nothing here has to stay in step
|
|
43
|
-
* with how each store builds its key. Anchored rather than a substring test on
|
|
44
|
-
* purpose — see {@link isServerScopedStore}, where the naive version would have
|
|
45
|
-
* cleared a different server's caches.
|
|
46
|
-
*
|
|
47
|
-
* `abracadabra:identity` is deliberately NOT dropped. It is this browser's
|
|
48
|
-
* keypair across every server it talks to; clearing it would sign the user out
|
|
49
|
-
* of all of them because one of them was reinstalled.
|
|
50
|
-
*/
|
|
51
|
-
|
|
52
|
-
/** Where the last-seen id for a host is remembered. */
|
|
53
|
-
const STORAGE_PREFIX = "abracadabra:server-id:";
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Stores that belong to no particular server and must survive a reset.
|
|
57
|
-
*
|
|
58
|
-
* `abracadabra:identity` is this browser's keypair for EVERY server it talks to,
|
|
59
|
-
* so dropping it because one server was reinstalled would sign the user out of
|
|
60
|
-
* all of them. Listed explicitly rather than relying on the anchored match, so
|
|
61
|
-
* that a future store named after a host cannot take it by accident.
|
|
62
|
-
*/
|
|
63
|
-
const GLOBAL_STORES = new Set(["abracadabra:identity", "abracadabra:softkey"]);
|
|
64
|
-
|
|
65
|
-
export interface ServerResetOutcome {
|
|
66
|
-
/** The id previously seen for this host, if any. */
|
|
67
|
-
previousServerId: string | null;
|
|
68
|
-
/** The id the server reports now. */
|
|
69
|
-
serverId: string;
|
|
70
|
-
/** Databases deleted because they belonged to the replaced server. */
|
|
71
|
-
cleared: string[];
|
|
72
|
-
/**
|
|
73
|
-
* Databases whose deletion was BLOCKED by an open connection.
|
|
74
|
-
*
|
|
75
|
-
* This is a failure, not a warning to swallow: the stale state is still in
|
|
76
|
-
* the tab and will be re-pushed. It happens when a provider opened the store
|
|
77
|
-
* before this ran, which means the guard was called too late. Callers should
|
|
78
|
-
* surface it rather than assume a clean result.
|
|
79
|
-
*/
|
|
80
|
-
blocked: string[];
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function storageAvailable(): boolean {
|
|
84
|
-
try {
|
|
85
|
-
return (
|
|
86
|
-
typeof globalThis !== "undefined" &&
|
|
87
|
-
"localStorage" in globalThis &&
|
|
88
|
-
"indexedDB" in globalThis
|
|
89
|
-
);
|
|
90
|
-
} catch {
|
|
91
|
-
return false;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* Does this database belong to the given server?
|
|
97
|
-
*
|
|
98
|
-
* The match is ANCHORED, and it has to be. A plain `name.includes(host)` looks
|
|
99
|
-
* right and is wrong in a way that destroys data: `other.example.com:3011`
|
|
100
|
-
* contains `example.com:3011`, so clearing one server's caches would delete a
|
|
101
|
-
* DIFFERENT server's — the exact "too broad" failure this guard exists to avoid.
|
|
102
|
-
* A unit test covers that pair.
|
|
103
|
-
*
|
|
104
|
-
* Three anchored shapes are needed, because the stores are NOT consistently
|
|
105
|
-
* scoped and pretending otherwise silently misses some:
|
|
106
|
-
*
|
|
107
|
-
* - `<host>/…` — {@link OfflineStore}, keyed `<host>/<docId>`
|
|
108
|
-
* - `…:<host>` — a namespaced store handed a bare host
|
|
109
|
-
* - `…://<host>` — a namespaced store handed a full URL. Real, not hypothetical:
|
|
110
|
-
* `@abraca/nuxt` passes `serverUrl` to `FileBlobStore`, so the database is
|
|
111
|
-
* named `abracadabra:files:http://example.com:3011`. Measured in a live
|
|
112
|
-
* browser; a rule written only for the first two shapes left it behind, which
|
|
113
|
-
* is a whole file cache surviving a wipe.
|
|
114
|
-
*/
|
|
115
|
-
export function isServerScopedStore(name: string, host: string): boolean {
|
|
116
|
-
if (!name.startsWith("abracadabra:")) return false;
|
|
117
|
-
if (GLOBAL_STORES.has(name)) return false;
|
|
118
|
-
const rest = name.slice("abracadabra:".length);
|
|
119
|
-
return (
|
|
120
|
-
rest === host ||
|
|
121
|
-
rest.startsWith(`${host}/`) ||
|
|
122
|
-
rest.endsWith(`:${host}`) ||
|
|
123
|
-
rest.endsWith(`://${host}`)
|
|
124
|
-
);
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Compare the server's identity against the one this browser last saw, and drop
|
|
129
|
-
* every cache belonging to it if the database has been replaced.
|
|
130
|
-
*
|
|
131
|
-
* **Call this before opening any provider.** Once a provider holds an IndexedDB
|
|
132
|
-
* handle, `deleteDatabase` blocks instead of deleting and the stale tree is
|
|
133
|
-
* already queued for re-push — the deletion completes later, having achieved
|
|
134
|
-
* nothing. Any store in that position comes back in `blocked`.
|
|
135
|
-
*
|
|
136
|
-
* Conservative by design:
|
|
137
|
-
*
|
|
138
|
-
* - the FIRST time a host is seen, the id is recorded and nothing is deleted —
|
|
139
|
-
* a new visitor must not have caches cleared for having no history;
|
|
140
|
-
* - a browser with no `indexedDB`/`localStorage` is a no-op;
|
|
141
|
-
* - it never throws. Failing to tidy a cache must not stop an app from starting.
|
|
142
|
-
*
|
|
143
|
-
* @param host The server's `host` (`example.com:3011`) — the same value
|
|
144
|
-
* providers scope their stores by. Not the full origin: the
|
|
145
|
-
* scheme is not part of a server's cache identity here.
|
|
146
|
-
* @param serverId `server_id` from `GET /info`.
|
|
147
|
-
*/
|
|
148
|
-
export async function dropCachesIfServerReplaced(
|
|
149
|
-
host: string,
|
|
150
|
-
serverId: string,
|
|
151
|
-
): Promise<ServerResetOutcome | null> {
|
|
152
|
-
if (!storageAvailable() || !host || !serverId) return null;
|
|
153
|
-
|
|
154
|
-
const key = STORAGE_PREFIX + host;
|
|
155
|
-
let previousServerId: string | null = null;
|
|
156
|
-
try {
|
|
157
|
-
previousServerId = globalThis.localStorage.getItem(key);
|
|
158
|
-
} catch {
|
|
159
|
-
return null;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// First sighting, or the same server we have always been talking to.
|
|
163
|
-
if (previousServerId === null) {
|
|
164
|
-
try {
|
|
165
|
-
globalThis.localStorage.setItem(key, serverId);
|
|
166
|
-
} catch {
|
|
167
|
-
/* private mode, quota — not worth failing over */
|
|
168
|
-
}
|
|
169
|
-
return null;
|
|
170
|
-
}
|
|
171
|
-
if (previousServerId === serverId) return null;
|
|
172
|
-
|
|
173
|
-
const cleared: string[] = [];
|
|
174
|
-
const blocked: string[] = [];
|
|
175
|
-
try {
|
|
176
|
-
const databases = (await globalThis.indexedDB.databases?.()) ?? [];
|
|
177
|
-
const doomed = databases
|
|
178
|
-
.map((d) => d.name)
|
|
179
|
-
.filter((n): n is string => !!n && isServerScopedStore(n, host));
|
|
180
|
-
|
|
181
|
-
await Promise.all(
|
|
182
|
-
doomed.map(
|
|
183
|
-
(name) =>
|
|
184
|
-
new Promise<void>((resolve) => {
|
|
185
|
-
const request = globalThis.indexedDB.deleteDatabase(name);
|
|
186
|
-
request.onsuccess = () => {
|
|
187
|
-
cleared.push(name);
|
|
188
|
-
resolve();
|
|
189
|
-
};
|
|
190
|
-
request.onerror = () => resolve();
|
|
191
|
-
// Still open somewhere. The delete stays pending and the stale
|
|
192
|
-
// state is still live in this tab — report it, do not hang the
|
|
193
|
-
// page waiting for a handle we do not own.
|
|
194
|
-
request.onblocked = () => {
|
|
195
|
-
blocked.push(name);
|
|
196
|
-
resolve();
|
|
197
|
-
};
|
|
198
|
-
}),
|
|
199
|
-
),
|
|
200
|
-
);
|
|
201
|
-
} catch {
|
|
202
|
-
/* enumeration unsupported or denied — nothing safely deletable */
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
try {
|
|
206
|
-
globalThis.localStorage.setItem(key, serverId);
|
|
207
|
-
} catch {
|
|
208
|
-
/* see above */
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
return { previousServerId, serverId, cleared, blocked };
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/** Forget what we know about a host, so the next check treats it as new. */
|
|
215
|
-
export function forgetServerIdentity(host: string): void {
|
|
216
|
-
if (!storageAvailable() || !host) return;
|
|
217
|
-
try {
|
|
218
|
-
globalThis.localStorage.removeItem(STORAGE_PREFIX + host);
|
|
219
|
-
} catch {
|
|
220
|
-
/* nothing to do */
|
|
221
|
-
}
|
|
222
|
-
}
|
package/src/TokenManager.ts
DELETED
|
@@ -1,337 +0,0 @@
|
|
|
1
|
-
import EventEmitter from "./EventEmitter.ts";
|
|
2
|
-
import type { AbracadabraClient } from "./AbracadabraClient.ts";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* On-disk shape of a device session. The server returns these values from
|
|
6
|
-
* `POST /auth/device-session`; persistence keeps them across reloads so a
|
|
7
|
-
* warm boot can mint a fresh JWT without re-prompting for the passkey.
|
|
8
|
-
*/
|
|
9
|
-
export interface DeviceSessionRecord {
|
|
10
|
-
sessionId: string;
|
|
11
|
-
sessionToken: string;
|
|
12
|
-
/** Unix seconds — matches what the server returns. */
|
|
13
|
-
expiresAt: number;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export interface DeviceSessionStorage {
|
|
17
|
-
load(): DeviceSessionRecord | null;
|
|
18
|
-
save(record: DeviceSessionRecord): void;
|
|
19
|
-
clear(): void;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const DEFAULT_STORAGE_KEY = "abracadabra:device-session";
|
|
23
|
-
|
|
24
|
-
/** localStorage-backed storage; safe in SSR/Node (no-ops without localStorage). */
|
|
25
|
-
export class LocalStorageDeviceSessionStorage implements DeviceSessionStorage {
|
|
26
|
-
constructor(private readonly key: string = DEFAULT_STORAGE_KEY) {}
|
|
27
|
-
|
|
28
|
-
load(): DeviceSessionRecord | null {
|
|
29
|
-
try {
|
|
30
|
-
const raw = localStorage.getItem(this.key);
|
|
31
|
-
if (!raw) return null;
|
|
32
|
-
const parsed = JSON.parse(raw) as DeviceSessionRecord;
|
|
33
|
-
if (
|
|
34
|
-
typeof parsed?.sessionId === "string" &&
|
|
35
|
-
typeof parsed?.sessionToken === "string" &&
|
|
36
|
-
typeof parsed?.expiresAt === "number"
|
|
37
|
-
) {
|
|
38
|
-
return parsed;
|
|
39
|
-
}
|
|
40
|
-
return null;
|
|
41
|
-
} catch {
|
|
42
|
-
return null;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
save(record: DeviceSessionRecord): void {
|
|
47
|
-
try {
|
|
48
|
-
localStorage.setItem(this.key, JSON.stringify(record));
|
|
49
|
-
} catch {
|
|
50
|
-
/* localStorage unavailable */
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
clear(): void {
|
|
55
|
-
try {
|
|
56
|
-
localStorage.removeItem(this.key);
|
|
57
|
-
} catch {
|
|
58
|
-
/* localStorage unavailable */
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export interface TokenManagerOptions {
|
|
64
|
-
client: AbracadabraClient;
|
|
65
|
-
/**
|
|
66
|
-
* Where the device session record lives. Defaults to a localStorage
|
|
67
|
-
* adapter under "abracadabra:device-session".
|
|
68
|
-
*/
|
|
69
|
-
storage?: DeviceSessionStorage;
|
|
70
|
-
/**
|
|
71
|
-
* Refresh the JWT this many milliseconds before its `exp`. Defaults to
|
|
72
|
-
* 5 minutes — well clear of clock skew without burning a refresh per
|
|
73
|
-
* minute. Refreshes are also dedup'd via in-flight promise.
|
|
74
|
-
*/
|
|
75
|
-
refreshLeadMs?: number;
|
|
76
|
-
/**
|
|
77
|
-
* Hook `document.visibilitychange` and `window.online` to opportunistically
|
|
78
|
-
* refresh when the tab/network resumes. Default true. The proactive
|
|
79
|
-
* `setTimeout` doesn't fire reliably while the tab is hidden or the
|
|
80
|
-
* laptop is asleep, which is the actual breakage path being addressed —
|
|
81
|
-
* the resume hook is what makes the system self-heal after a long sleep.
|
|
82
|
-
*/
|
|
83
|
-
installResumeHandlers?: boolean;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Manages the lifetime of the short-lived JWT against a long-lived device
|
|
88
|
-
* session token.
|
|
89
|
-
*
|
|
90
|
-
* Flow:
|
|
91
|
-
* - Bootstrap: if a stored device session exists, exchange it for a fresh
|
|
92
|
-
* JWT immediately (`bootstrap()`). Otherwise the consumer must run a
|
|
93
|
-
* full crypto-auth handshake and then call `attachSession(record)` once
|
|
94
|
-
* the server returns a device-session token.
|
|
95
|
-
* - Steady state: `getValidToken()` returns the JWT, refreshing if the
|
|
96
|
-
* JWT is within `refreshLeadMs` of expiry. Concurrent callers share one
|
|
97
|
-
* in-flight refresh.
|
|
98
|
-
* - Background: a proactive timer fires `refreshLeadMs` before `exp`.
|
|
99
|
-
* `visibilitychange` and `online` events trigger an opportunistic
|
|
100
|
-
* refresh in case the timer was suppressed (hidden tab, sleeping
|
|
101
|
-
* laptop). The combination is what restores the WS without a reload.
|
|
102
|
-
* - Failure: refresh errors with status 401/403 mean the device session
|
|
103
|
-
* itself is dead (revoked or 30 d expired). The record is cleared and
|
|
104
|
-
* `session-expired` fires so the consumer can prompt re-auth. Other
|
|
105
|
-
* errors (network) are transparent — the existing JWT is returned and
|
|
106
|
-
* the caller's normal retry loop covers it.
|
|
107
|
-
*/
|
|
108
|
-
export class TokenManager extends EventEmitter {
|
|
109
|
-
private readonly client: AbracadabraClient;
|
|
110
|
-
private readonly storage: DeviceSessionStorage;
|
|
111
|
-
private readonly refreshLeadMs: number;
|
|
112
|
-
private session: DeviceSessionRecord | null;
|
|
113
|
-
private refreshing: Promise<string> | null = null;
|
|
114
|
-
private proactiveTimer: ReturnType<typeof setTimeout> | null = null;
|
|
115
|
-
private resumeHandlersInstalled = false;
|
|
116
|
-
private boundOnResume: (() => void) | null = null;
|
|
117
|
-
private disposed = false;
|
|
118
|
-
|
|
119
|
-
constructor(options: TokenManagerOptions) {
|
|
120
|
-
super();
|
|
121
|
-
this.client = options.client;
|
|
122
|
-
this.storage = options.storage ?? new LocalStorageDeviceSessionStorage();
|
|
123
|
-
this.refreshLeadMs = options.refreshLeadMs ?? 5 * 60 * 1000;
|
|
124
|
-
this.session = this.storage.load();
|
|
125
|
-
if (options.installResumeHandlers !== false) {
|
|
126
|
-
this.installResumeHandlers();
|
|
127
|
-
}
|
|
128
|
-
// Schedule a refresh against the JWT the client may already be
|
|
129
|
-
// holding (loaded from persistAuth localStorage) so warm boots
|
|
130
|
-
// without an explicit bootstrap() still benefit from proactive
|
|
131
|
-
// refresh on the existing token.
|
|
132
|
-
this.scheduleProactiveRefresh();
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
get hasSession(): boolean {
|
|
136
|
-
return this.session !== null;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
get currentSession(): DeviceSessionRecord | null {
|
|
140
|
-
return this.session;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* Persist a freshly-issued device session and exchange it immediately
|
|
145
|
-
* for a JWT. Call this once after a successful crypto-auth login when
|
|
146
|
-
* the server returns a device-session token.
|
|
147
|
-
*/
|
|
148
|
-
async attachSession(record: DeviceSessionRecord): Promise<string> {
|
|
149
|
-
this.session = record;
|
|
150
|
-
this.storage.save(record);
|
|
151
|
-
const jwt = await this.runRefresh();
|
|
152
|
-
return jwt;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Drop the local device session (no server call). Use after a logout
|
|
157
|
-
* or when `session-expired` fires. To revoke server-side as well, call
|
|
158
|
-
* `client.revokeDeviceSession(sessionId)` first.
|
|
159
|
-
*/
|
|
160
|
-
clearSession(): void {
|
|
161
|
-
this.session = null;
|
|
162
|
-
this.storage.clear();
|
|
163
|
-
if (this.proactiveTimer) {
|
|
164
|
-
clearTimeout(this.proactiveTimer);
|
|
165
|
-
this.proactiveTimer = null;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* Return a valid JWT, refreshing if it is missing or within
|
|
171
|
-
* `refreshLeadMs` of expiry. Safe to call concurrently — one
|
|
172
|
-
* refresh is in flight at a time.
|
|
173
|
-
*
|
|
174
|
-
* Transient refresh errors (network) fall back to the cached JWT so
|
|
175
|
-
* the WS auth attempt can still proceed; the server will reject and
|
|
176
|
-
* the next reconnect tries again. Only 401/403 from the refresh
|
|
177
|
-
* endpoint surfaces as a thrown error here, since those mean the
|
|
178
|
-
* device session itself is dead.
|
|
179
|
-
*/
|
|
180
|
-
async getValidToken(): Promise<string> {
|
|
181
|
-
if (this.refreshing) return this.refreshing;
|
|
182
|
-
const current = this.client.token;
|
|
183
|
-
if (current && this.tokenIsFresh(current)) return current;
|
|
184
|
-
if (!this.session) return current ?? "";
|
|
185
|
-
try {
|
|
186
|
-
return await this.runRefresh();
|
|
187
|
-
} catch (err) {
|
|
188
|
-
const status = (err as { status?: number })?.status;
|
|
189
|
-
if (status === 401 || status === 403) throw err;
|
|
190
|
-
// Transient — let the caller use the stale token; the server
|
|
191
|
-
// will reject and the WS reconnect loop will retry the refresh.
|
|
192
|
-
return current ?? "";
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
/**
|
|
197
|
-
* If a stored device session exists, exchange it for a fresh JWT now.
|
|
198
|
-
* Returns the JWT (or null if there is no session to bootstrap from).
|
|
199
|
-
* Throws on 401/403 — the stored session is invalid and the caller
|
|
200
|
-
* should fall through to a full crypto-auth flow.
|
|
201
|
-
*/
|
|
202
|
-
async bootstrap(): Promise<string | null> {
|
|
203
|
-
if (!this.session) return null;
|
|
204
|
-
try {
|
|
205
|
-
return await this.runRefresh();
|
|
206
|
-
} catch (err) {
|
|
207
|
-
const status = (err as { status?: number })?.status;
|
|
208
|
-
if (status === 401 || status === 403) throw err;
|
|
209
|
-
// Transient — caller decides what to do (e.g. fall back to
|
|
210
|
-
// passkey login or proceed offline).
|
|
211
|
-
return null;
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
dispose(): void {
|
|
216
|
-
if (this.disposed) return;
|
|
217
|
-
this.disposed = true;
|
|
218
|
-
if (this.proactiveTimer) {
|
|
219
|
-
clearTimeout(this.proactiveTimer);
|
|
220
|
-
this.proactiveTimer = null;
|
|
221
|
-
}
|
|
222
|
-
if (this.boundOnResume) {
|
|
223
|
-
try {
|
|
224
|
-
if (typeof document !== "undefined") {
|
|
225
|
-
document.removeEventListener("visibilitychange", this.boundOnResume);
|
|
226
|
-
}
|
|
227
|
-
if (typeof window !== "undefined") {
|
|
228
|
-
window.removeEventListener("online", this.boundOnResume);
|
|
229
|
-
}
|
|
230
|
-
} catch { /* environment without listener APIs */ }
|
|
231
|
-
this.boundOnResume = null;
|
|
232
|
-
}
|
|
233
|
-
this.removeAllListeners();
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// ── internals ───────────────────────────────────────────────────────────
|
|
237
|
-
|
|
238
|
-
private runRefresh(): Promise<string> {
|
|
239
|
-
if (this.refreshing) return this.refreshing;
|
|
240
|
-
if (!this.session) return Promise.reject(new Error("No device session"));
|
|
241
|
-
const sessionToken = this.session.sessionToken;
|
|
242
|
-
this.refreshing = (async () => {
|
|
243
|
-
try {
|
|
244
|
-
const jwt = await this.client.refreshWithDeviceSession(sessionToken);
|
|
245
|
-
this.scheduleProactiveRefresh();
|
|
246
|
-
this.emit("refresh", jwt);
|
|
247
|
-
return jwt;
|
|
248
|
-
} catch (err) {
|
|
249
|
-
const status = (err as { status?: number })?.status;
|
|
250
|
-
if (status === 401 || status === 403) {
|
|
251
|
-
const message = (err as Error)?.message ?? "device session rejected";
|
|
252
|
-
this.clearSession();
|
|
253
|
-
this.emit("session-expired", { status, message });
|
|
254
|
-
}
|
|
255
|
-
throw err;
|
|
256
|
-
} finally {
|
|
257
|
-
this.refreshing = null;
|
|
258
|
-
}
|
|
259
|
-
})();
|
|
260
|
-
return this.refreshing;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
private tokenIsFresh(jwt: string): boolean {
|
|
264
|
-
const exp = this.parseExp(jwt);
|
|
265
|
-
if (exp == null) return false;
|
|
266
|
-
return exp * 1000 - Date.now() > this.refreshLeadMs;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
private parseExp(jwt: string): number | null {
|
|
270
|
-
try {
|
|
271
|
-
const [, payload] = jwt.split(".");
|
|
272
|
-
if (!payload) return null;
|
|
273
|
-
// base64url-safe: `atob` alone throws on `-`/`_`, which would make
|
|
274
|
-
// the proactive-refresh timer treat a valid token as unparseable.
|
|
275
|
-
let b64 = payload.replace(/-/g, "+").replace(/_/g, "/");
|
|
276
|
-
const pad = b64.length % 4;
|
|
277
|
-
if (pad) b64 += "=".repeat(4 - pad);
|
|
278
|
-
const json = new TextDecoder().decode(
|
|
279
|
-
Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)),
|
|
280
|
-
);
|
|
281
|
-
const { exp } = JSON.parse(json);
|
|
282
|
-
return typeof exp === "number" ? exp : null;
|
|
283
|
-
} catch {
|
|
284
|
-
return null;
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
private scheduleProactiveRefresh(): void {
|
|
289
|
-
if (this.proactiveTimer) {
|
|
290
|
-
clearTimeout(this.proactiveTimer);
|
|
291
|
-
this.proactiveTimer = null;
|
|
292
|
-
}
|
|
293
|
-
if (!this.session || this.disposed) return;
|
|
294
|
-
const jwt = this.client.token;
|
|
295
|
-
const exp = jwt ? this.parseExp(jwt) : null;
|
|
296
|
-
if (exp == null) {
|
|
297
|
-
// No JWT yet — defer; whoever calls getValidToken() / bootstrap()
|
|
298
|
-
// will reschedule once a JWT lands.
|
|
299
|
-
return;
|
|
300
|
-
}
|
|
301
|
-
// Floor at 30 s so a near-expired token doesn't trigger a busy
|
|
302
|
-
// refresh-then-immediately-refresh-again loop on clock skew.
|
|
303
|
-
const delay = Math.max(30_000, exp * 1000 - Date.now() - this.refreshLeadMs);
|
|
304
|
-
this.proactiveTimer = setTimeout(() => {
|
|
305
|
-
this.runRefresh().catch(() => {
|
|
306
|
-
// 401/403 already surfaced via session-expired event;
|
|
307
|
-
// transient errors are no-ops — the resume handler or the
|
|
308
|
-
// next getValidToken() call will retry.
|
|
309
|
-
});
|
|
310
|
-
}, delay);
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
private installResumeHandlers(): void {
|
|
314
|
-
if (this.resumeHandlersInstalled) return;
|
|
315
|
-
if (typeof document === "undefined" && typeof window === "undefined") return;
|
|
316
|
-
const onResume = () => {
|
|
317
|
-
if (this.disposed) return;
|
|
318
|
-
if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
|
|
319
|
-
if (!this.session) return;
|
|
320
|
-
const jwt = this.client.token;
|
|
321
|
-
if (jwt && this.tokenIsFresh(jwt)) return;
|
|
322
|
-
this.runRefresh().catch(() => {
|
|
323
|
-
/* same swallow as above */
|
|
324
|
-
});
|
|
325
|
-
};
|
|
326
|
-
this.boundOnResume = onResume;
|
|
327
|
-
try {
|
|
328
|
-
if (typeof document !== "undefined") {
|
|
329
|
-
document.addEventListener("visibilitychange", onResume);
|
|
330
|
-
}
|
|
331
|
-
if (typeof window !== "undefined") {
|
|
332
|
-
window.addEventListener("online", onResume);
|
|
333
|
-
}
|
|
334
|
-
this.resumeHandlersInstalled = true;
|
|
335
|
-
} catch { /* environment without listener APIs */ }
|
|
336
|
-
}
|
|
337
|
-
}
|