@oxog/authkeeper 1.5.1 → 1.6.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 (41) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +59 -2
  3. package/dist/{auth-source-CXqrhLDO.d.ts → auth-source-BwPxq1Za.d.ts} +1 -1
  4. package/dist/{auth-source-rjMWiP1Q.d.cts → auth-source-MSiTDST6.d.cts} +1 -1
  5. package/dist/{chunk-DLCD3SBV.js → chunk-K3XXGKGO.js} +2 -2
  6. package/dist/chunk-K3XXGKGO.js.map +1 -0
  7. package/dist/{chunk-XGKVBZSF.cjs → chunk-MONA6MGX.cjs} +2 -2
  8. package/dist/chunk-MONA6MGX.cjs.map +1 -0
  9. package/dist/{chunk-VVSZPARR.cjs → chunk-SI7KITBT.cjs} +323 -273
  10. package/dist/chunk-SI7KITBT.cjs.map +1 -0
  11. package/dist/{chunk-7B77NZGY.js → chunk-ZZMKSCXQ.js} +312 -263
  12. package/dist/chunk-ZZMKSCXQ.js.map +1 -0
  13. package/dist/{index-CQwGO-Wk.d.ts → index-BqxH4X40.d.ts} +52 -6
  14. package/dist/{index-C4pGS-TI.d.cts → index-ChJtNH74.d.cts} +52 -6
  15. package/dist/index.cjs +461 -52
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +32 -4
  18. package/dist/index.d.ts +32 -4
  19. package/dist/index.js +416 -7
  20. package/dist/index.js.map +1 -1
  21. package/dist/plugins/index.cjs +15 -15
  22. package/dist/plugins/index.d.cts +2 -2
  23. package/dist/plugins/index.d.ts +2 -2
  24. package/dist/plugins/index.js +2 -2
  25. package/dist/react/index.cjs +3 -3
  26. package/dist/react/index.d.cts +2 -2
  27. package/dist/react/index.d.ts +2 -2
  28. package/dist/react/index.js +1 -1
  29. package/dist/svelte/index.d.cts +2 -2
  30. package/dist/svelte/index.d.ts +2 -2
  31. package/dist/{types-DMPBl-Ym.d.ts → types-DWB4dbp8.d.cts} +26 -4
  32. package/dist/{types-DMPBl-Ym.d.cts → types-DWB4dbp8.d.ts} +26 -4
  33. package/dist/vue/index.cjs +2 -2
  34. package/dist/vue/index.d.cts +2 -2
  35. package/dist/vue/index.d.ts +2 -2
  36. package/dist/vue/index.js +1 -1
  37. package/package.json +1 -1
  38. package/dist/chunk-7B77NZGY.js.map +0 -1
  39. package/dist/chunk-DLCD3SBV.js.map +0 -1
  40. package/dist/chunk-VVSZPARR.cjs.map +0 -1
  41. package/dist/chunk-XGKVBZSF.cjs.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkVVSZPARR_cjs = require('./chunk-VVSZPARR.cjs');
4
- var chunkXGKVBZSF_cjs = require('./chunk-XGKVBZSF.cjs');
3
+ var chunkSI7KITBT_cjs = require('./chunk-SI7KITBT.cjs');
4
+ var chunkMONA6MGX_cjs = require('./chunk-MONA6MGX.cjs');
5
5
 
6
6
  // src/kernel/event-bus.ts
7
7
  var EventBus = class {
@@ -110,7 +110,7 @@ var PluginRegistry = class {
110
110
  */
111
111
  register(plugin) {
112
112
  if (this.plugins.has(plugin.name)) {
113
- throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", `Plugin "${plugin.name}" is already registered`, {
113
+ throw new chunkMONA6MGX_cjs.AuthError("CONFIG_ERROR", `Plugin "${plugin.name}" is already registered`, {
114
114
  context: { pluginName: plugin.name }
115
115
  });
116
116
  }
@@ -133,7 +133,7 @@ var PluginRegistry = class {
133
133
  async install(name, kernel) {
134
134
  const instance = this.plugins.get(name);
135
135
  if (!instance) {
136
- throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", `Plugin "${name}" not found`, {
136
+ throw new chunkMONA6MGX_cjs.AuthError("CONFIG_ERROR", `Plugin "${name}" not found`, {
137
137
  context: { pluginName: name }
138
138
  });
139
139
  }
@@ -145,7 +145,7 @@ var PluginRegistry = class {
145
145
  instance.api = api || null;
146
146
  instance.installed = true;
147
147
  } catch (error) {
148
- throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", `Failed to install plugin "${name}"`, {
148
+ throw new chunkMONA6MGX_cjs.AuthError("CONFIG_ERROR", `Failed to install plugin "${name}"`, {
149
149
  cause: error,
150
150
  context: { pluginName: name }
151
151
  });
@@ -240,10 +240,279 @@ var PluginRegistry = class {
240
240
  }
241
241
  };
242
242
 
243
+ // src/kernel/tab-sync.ts
244
+ var LEASE_TTL = 5e3;
245
+ var LEASE_RENEW = 1500;
246
+ var LEASE_POLL = 50;
247
+ var LEASE_SETTLE = 25;
248
+ var MAX_LOCK_HOLD = 3e4;
249
+ var ACTIONS = ["login", "refresh", "logout"];
250
+ function describeSyncScope(storage) {
251
+ if (!storage || typeof window === "undefined") return null;
252
+ const { adapter, key } = storage;
253
+ if (adapter instanceof chunkSI7KITBT_cjs.MemoryStorageAdapter) return null;
254
+ const localStorage = getLocalStorage();
255
+ if (adapter instanceof chunkSI7KITBT_cjs.WebStorageAdapter) {
256
+ if (localStorage === null || adapter.storage !== localStorage) return null;
257
+ return { name: adapter.prefix + key, localStorage, messagesInStorage: true };
258
+ }
259
+ const prefix = adapter instanceof chunkSI7KITBT_cjs.CookieStorageAdapter ? adapter.prefix : "";
260
+ return { name: prefix + key, localStorage, messagesInStorage: false };
261
+ }
262
+ function getLocalStorage() {
263
+ try {
264
+ return window.localStorage;
265
+ } catch {
266
+ return null;
267
+ }
268
+ }
269
+ function closedError() {
270
+ return new chunkMONA6MGX_cjs.AuthError("REFRESH_FAILED", "AuthKeeper was destroyed while refreshing", {
271
+ context: { superseded: true }
272
+ });
273
+ }
274
+ function isSyncMessage(value) {
275
+ if (value === null || typeof value !== "object") return false;
276
+ const m = value;
277
+ return m["v"] === 1 && typeof m["source"] === "string" && typeof m["seq"] === "number" && typeof m["gen"] === "number" && typeof m["action"] === "string" && ACTIONS.includes(m["action"]) && (m["action"] === "logout" ? m["tokens"] === null : chunkSI7KITBT_cjs.isStoredTokens(m["tokens"]));
278
+ }
279
+ function readLease(storage, key) {
280
+ try {
281
+ const lease = JSON.parse(storage.getItem(key) ?? "null");
282
+ return lease && typeof lease.owner === "string" && typeof lease.expires === "number" ? lease : null;
283
+ } catch {
284
+ return null;
285
+ }
286
+ }
287
+ var TabSync = class _TabSync {
288
+ constructor(config) {
289
+ this.seq = 0;
290
+ this.gen = 0;
291
+ this.genSource = "";
292
+ this.lastSeq = /* @__PURE__ */ new Map();
293
+ this.channel = null;
294
+ this.storageListener = null;
295
+ this.closed = false;
296
+ /** Run by close(): end waits, abort lock requests, release held locks */
297
+ this.closeHandlers = /* @__PURE__ */ new Set();
298
+ this.leaseSerial = 0;
299
+ this.config = config;
300
+ this.key = `authkeeper-sync:${config.name}`;
301
+ this.id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
302
+ }
303
+ /**
304
+ * Start syncing; null when there is no way to reach the other tabs
305
+ * (no BroadcastChannel and no storage transport)
306
+ */
307
+ static open(config) {
308
+ const sync = new _TabSync(config);
309
+ return sync.connect() ? sync : null;
310
+ }
311
+ connect() {
312
+ const Channel = globalThis.BroadcastChannel;
313
+ if (typeof Channel === "function") {
314
+ try {
315
+ this.channel = new Channel(this.key);
316
+ this.channel.onmessage = (event) => this.receive(event.data);
317
+ return true;
318
+ } catch {
319
+ }
320
+ }
321
+ const storage = this.config.localStorage;
322
+ if (!this.config.messagesInStorage || !storage) return false;
323
+ this.storageListener = (event) => {
324
+ if (event.key !== this.key || event.newValue === null) return;
325
+ let data;
326
+ try {
327
+ data = JSON.parse(event.newValue);
328
+ } catch {
329
+ return;
330
+ }
331
+ this.receive(data);
332
+ };
333
+ window.addEventListener("storage", this.storageListener);
334
+ return true;
335
+ }
336
+ /** Tell the other tabs about a change made in this one */
337
+ publish(action, tokens) {
338
+ if (this.closed) return;
339
+ this.touch();
340
+ const message = {
341
+ v: 1,
342
+ source: this.id,
343
+ seq: ++this.seq,
344
+ gen: this.gen,
345
+ action,
346
+ tokens
347
+ };
348
+ try {
349
+ if (this.channel) {
350
+ this.channel.postMessage(message);
351
+ } else {
352
+ const storage = this.config.localStorage;
353
+ storage.setItem(this.key, JSON.stringify(message));
354
+ storage.removeItem(this.key);
355
+ }
356
+ } catch {
357
+ }
358
+ }
359
+ /** A change made in this tab that the others are not told about (local logout) */
360
+ touch() {
361
+ this.gen = Math.max(Date.now(), this.gen + 1);
362
+ this.genSource = this.id;
363
+ }
364
+ receive(data) {
365
+ if (this.closed || !isSyncMessage(data) || data.source === this.id) return;
366
+ if (data.seq <= (this.lastSeq.get(data.source) ?? 0)) return;
367
+ this.lastSeq.set(data.source, data.seq);
368
+ if (data.gen < this.gen || data.gen === this.gen && data.source <= this.genSource) return;
369
+ this.gen = data.gen;
370
+ this.genSource = data.source;
371
+ this.config.onMessage(data);
372
+ }
373
+ /**
374
+ * Run `task` while holding the refresh lock of this app (one tab at a
375
+ * time). Without a lock mechanism, or when the lock cannot be taken, the
376
+ * task runs right away. Rejects (superseded) when the instance is closed
377
+ * while waiting for the lock.
378
+ */
379
+ exclusive(task) {
380
+ return new Promise((resolve, reject) => {
381
+ let started = false;
382
+ const run = () => {
383
+ started = true;
384
+ const work = task();
385
+ work.then(resolve, reject);
386
+ return this.hold(work);
387
+ };
388
+ this.acquire(run).catch(() => {
389
+ if (started) return;
390
+ if (this.closed) {
391
+ reject(closedError());
392
+ } else {
393
+ void run();
394
+ }
395
+ });
396
+ });
397
+ }
398
+ /** Settles when the lock is to be released: work done, held too long, or closed */
399
+ hold(work) {
400
+ return new Promise((resolve) => {
401
+ const done = () => {
402
+ clearTimeout(timer);
403
+ this.closeHandlers.delete(done);
404
+ resolve();
405
+ };
406
+ const timer = setTimeout(done, MAX_LOCK_HOLD);
407
+ this.closeHandlers.add(done);
408
+ work.then(done, done);
409
+ });
410
+ }
411
+ acquire(run) {
412
+ if (this.closed) return Promise.reject(closedError());
413
+ const locks = typeof navigator === "undefined" ? void 0 : navigator.locks;
414
+ if (locks && typeof locks.request === "function") {
415
+ const controller = new AbortController();
416
+ const abort = () => controller.abort();
417
+ this.closeHandlers.add(abort);
418
+ return locks.request(`${this.key}:refresh`, { signal: controller.signal }, () => {
419
+ this.closeHandlers.delete(abort);
420
+ return run();
421
+ }).finally(() => this.closeHandlers.delete(abort));
422
+ }
423
+ const storage = this.config.localStorage;
424
+ return storage ? this.lease(storage, run) : run();
425
+ }
426
+ /** The localStorage lease lock */
427
+ async lease(storage, run) {
428
+ const key = `${this.key}:lease`;
429
+ const owner = `${this.id}:${++this.leaseSerial}`;
430
+ const write = () => {
431
+ storage.setItem(key, JSON.stringify({ owner, expires: Date.now() + LEASE_TTL }));
432
+ };
433
+ const release = () => {
434
+ try {
435
+ if (readLease(storage, key)?.owner === owner) storage.removeItem(key);
436
+ } catch {
437
+ }
438
+ };
439
+ for (; ; ) {
440
+ const current = readLease(storage, key);
441
+ const free = current === null || current.expires <= Date.now();
442
+ if (free) {
443
+ write();
444
+ }
445
+ await this.wait(free ? LEASE_SETTLE : LEASE_POLL);
446
+ if (this.closed) {
447
+ release();
448
+ throw closedError();
449
+ }
450
+ if (free && readLease(storage, key)?.owner === owner) break;
451
+ }
452
+ const renew = setInterval(() => {
453
+ try {
454
+ write();
455
+ } catch {
456
+ }
457
+ }, LEASE_RENEW);
458
+ try {
459
+ await run();
460
+ } finally {
461
+ clearInterval(renew);
462
+ release();
463
+ }
464
+ }
465
+ /** Resolves after `ms`, or at once when closed */
466
+ wait(ms) {
467
+ return new Promise((resolve) => {
468
+ const done = () => {
469
+ clearTimeout(timer);
470
+ this.closeHandlers.delete(done);
471
+ resolve();
472
+ };
473
+ const timer = setTimeout(done, ms);
474
+ this.closeHandlers.add(done);
475
+ });
476
+ }
477
+ /** Stop syncing: close the channel, remove the listener, release / give up locks */
478
+ close() {
479
+ if (this.closed) return;
480
+ this.closed = true;
481
+ if (this.channel) {
482
+ this.channel.onmessage = null;
483
+ this.channel.close();
484
+ this.channel = null;
485
+ }
486
+ if (this.storageListener) {
487
+ window.removeEventListener("storage", this.storageListener);
488
+ this.storageListener = null;
489
+ }
490
+ Array.from(this.closeHandlers).forEach((handler) => handler());
491
+ this.closeHandlers.clear();
492
+ }
493
+ };
494
+
243
495
  // src/kernel/kernel.ts
496
+ var REMOTE_SESSION_WAIT = 1e3;
497
+ var MAX_REPLACED = 16;
498
+ function isSyncableStore(store) {
499
+ return typeof store?.replace === "function" && typeof store.readPersisted === "function" && typeof store.getStorage === "function";
500
+ }
501
+ function toTokenSet(tokens) {
502
+ const set = { accessToken: tokens.accessToken, tokenType: tokens.tokenType };
503
+ if (tokens.refreshToken !== null) set.refreshToken = tokens.refreshToken;
504
+ if (tokens.expiresAt !== null) set.expiresAt = tokens.expiresAt / 1e3;
505
+ return set;
506
+ }
244
507
  var AuthKeeperKernel = class {
245
508
  constructor(options) {
246
509
  this.initialized = false;
510
+ /** Cross-tab sync, while `syncTabs` is on and the storage is shared */
511
+ this.tabSync = null;
512
+ /** Refresh tokens another tab replaced (refreshed or signed out) */
513
+ this.replacedRemotely = /* @__PURE__ */ new Set();
514
+ /** Waiting for the next change adopted from another tab */
515
+ this.remoteWaiters = /* @__PURE__ */ new Set();
247
516
  this.options = {
248
517
  autoRefresh: true,
249
518
  refreshThreshold: 60,
@@ -273,12 +542,14 @@ var AuthKeeperKernel = class {
273
542
  }
274
543
  }
275
544
  this.initialized = true;
545
+ this.updateTabSync();
276
546
  }
277
547
  /**
278
548
  * Destroy the kernel and cleanup
279
549
  */
280
550
  destroy() {
281
551
  this.cancelScheduledRefresh();
552
+ this.stopTabSync();
282
553
  this.eventBus.clear();
283
554
  const pluginNames = this.pluginRegistry.getNames();
284
555
  for (const name of pluginNames) {
@@ -298,17 +569,20 @@ var AuthKeeperKernel = class {
298
569
  setTokens(tokens) {
299
570
  const tokenStore = this.pluginRegistry.getApi("token-store");
300
571
  if (!tokenStore) {
301
- throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", "token-store plugin not installed");
572
+ throw new chunkMONA6MGX_cjs.AuthError("CONFIG_ERROR", "token-store plugin not installed");
302
573
  }
303
574
  tokenStore.set(tokens);
304
575
  const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
305
- if (refreshEngine?.isApplyingRefresh?.() !== true) {
576
+ const isRefresh = refreshEngine?.isApplyingRefresh?.() === true;
577
+ if (!isRefresh) {
578
+ this.replacedRemotely.clear();
306
579
  this.emit({
307
580
  type: "login",
308
581
  tokens,
309
582
  timestamp: Date.now()
310
583
  });
311
584
  }
585
+ this.tabSync?.publish(isRefresh ? "refresh" : "login", tokenStore.get());
312
586
  if (this.options.autoRefresh && !this.isExpired()) {
313
587
  this.scheduleRefresh();
314
588
  }
@@ -346,6 +620,8 @@ var AuthKeeperKernel = class {
346
620
  if (tokenStore) {
347
621
  tokenStore.clear();
348
622
  }
623
+ this.replacedRemotely.clear();
624
+ this.tabSync?.touch();
349
625
  }
350
626
  // ============================================================================
351
627
  // Auth State
@@ -443,7 +719,7 @@ var AuthKeeperKernel = class {
443
719
  async refresh() {
444
720
  const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
445
721
  if (!refreshEngine) {
446
- throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", "refresh-engine plugin not installed");
722
+ throw new chunkMONA6MGX_cjs.AuthError("CONFIG_ERROR", "refresh-engine plugin not installed");
447
723
  }
448
724
  return refreshEngine.refresh();
449
725
  }
@@ -478,11 +754,15 @@ var AuthKeeperKernel = class {
478
754
  /**
479
755
  * Logout user
480
756
  *
481
- * Clears tokens and emits logout event.
757
+ * Clears tokens and emits logout event. Only this tab is signed out unless
758
+ * `allTabs` is set (and `syncTabs` is active).
482
759
  */
483
760
  logout(options = {}) {
484
761
  this.cancelScheduledRefresh();
485
762
  this.clearTokens();
763
+ if (options.allTabs) {
764
+ this.tabSync?.publish("logout", null);
765
+ }
486
766
  this.emit({
487
767
  type: "logout",
488
768
  reason: "manual",
@@ -598,6 +878,9 @@ var AuthKeeperKernel = class {
598
878
  ...this.options,
599
879
  ...options
600
880
  };
881
+ if (options.syncTabs !== void 0) {
882
+ this.updateTabSync();
883
+ }
601
884
  if (options.refreshThreshold !== void 0) {
602
885
  const refreshEngine = this.pluginRegistry.getApi("refresh-engine");
603
886
  if (refreshEngine && refreshEngine.setThreshold) {
@@ -609,22 +892,148 @@ var AuthKeeperKernel = class {
609
892
  * Get current configuration
610
893
  */
611
894
  getOptions() {
612
- return { ...this.options, syncTabs: false };
895
+ return { ...this.options, syncTabs: this.tabSync !== null };
896
+ }
897
+ // ============================================================================
898
+ // Tab Sync
899
+ // ============================================================================
900
+ /** Start or stop cross-tab sync to match `syncTabs` */
901
+ updateTabSync() {
902
+ if (!this.initialized || this.options.syncTabs !== true) {
903
+ this.stopTabSync();
904
+ return;
905
+ }
906
+ if (this.tabSync) return;
907
+ const store = this.pluginRegistry.getApi("token-store");
908
+ if (!isSyncableStore(store)) return;
909
+ const scope = describeSyncScope(store.getStorage());
910
+ if (!scope) return;
911
+ const sync = TabSync.open({
912
+ ...scope,
913
+ onMessage: (message) => this.applyRemote(store, message)
914
+ });
915
+ if (!sync) return;
916
+ this.tabSync = sync;
917
+ const coordinator = {
918
+ exclusive: (task) => sync.exclusive(task),
919
+ beforeRefresh: (refreshToken) => this.awaitNewerSession(store, refreshToken),
920
+ replacement: (refreshToken) => this.replacementFor(store, refreshToken)
921
+ };
922
+ this.pluginRegistry.getApi("refresh-engine")?.setCoordinator?.(coordinator);
923
+ }
924
+ stopTabSync() {
925
+ if (!this.tabSync) return;
926
+ this.tabSync.close();
927
+ this.tabSync = null;
928
+ this.pluginRegistry.getApi("refresh-engine")?.setCoordinator?.(null);
929
+ this.replacedRemotely.clear();
930
+ this.remoteWaiters.forEach((wake) => wake());
931
+ }
932
+ /**
933
+ * Adopt a change made in another tab: update the in-memory session (the
934
+ * other tab has already written the storage) and emit the same event as
935
+ * there, marked `remote`, followed by a 'tab-sync' event
936
+ */
937
+ applyRemote(tokenStore, message) {
938
+ const current = tokenStore.get();
939
+ const timestamp = Date.now();
940
+ const remote = { remote: true, sourceTabId: message.source };
941
+ if (message.tokens === null) {
942
+ if (!current) return;
943
+ this.noteReplaced(current.refreshToken);
944
+ this.cancelScheduledRefresh();
945
+ tokenStore.replace(null);
946
+ this.emit({ type: "logout", reason: "tab-sync", timestamp, ...remote });
947
+ } else {
948
+ const tokens = message.tokens;
949
+ if (message.action === "refresh" && !current) return;
950
+ if (current && current.accessToken === tokens.accessToken && current.refreshToken === tokens.refreshToken) {
951
+ return;
952
+ }
953
+ const previousExpiresAt = this.getExpiresAt();
954
+ this.noteReplaced(current?.refreshToken ?? null);
955
+ tokenStore.replace(tokens);
956
+ const tokenSet = toTokenSet(tokens);
957
+ if (message.action === "refresh") {
958
+ this.emit({
959
+ type: "refresh",
960
+ tokens: tokenSet,
961
+ previousExpiresAt,
962
+ newExpiresAt: this.getExpiresAt(),
963
+ timestamp,
964
+ ...remote
965
+ });
966
+ } else {
967
+ this.emit({ type: "login", tokens: tokenSet, timestamp, ...remote });
968
+ }
969
+ this.cancelScheduledRefresh();
970
+ if (!this.isExpired()) {
971
+ this.scheduleRefresh();
972
+ }
973
+ }
974
+ this.emit({
975
+ type: "tab-sync",
976
+ action: message.action,
977
+ sourceTabId: message.source,
978
+ timestamp
979
+ });
980
+ this.remoteWaiters.forEach((wake) => wake());
981
+ }
982
+ noteReplaced(refreshToken) {
983
+ if (refreshToken === null) return;
984
+ this.replacedRemotely.delete(refreshToken);
985
+ this.replacedRemotely.add(refreshToken);
986
+ if (this.replacedRemotely.size > MAX_REPLACED) {
987
+ const oldest = this.replacedRemotely.values().next().value;
988
+ this.replacedRemotely.delete(oldest);
989
+ }
990
+ }
991
+ /** The session another tab replaced `refreshToken` with (null if none) */
992
+ replacementFor(tokenStore, refreshToken) {
993
+ if (!this.replacedRemotely.has(refreshToken)) return null;
994
+ const current = tokenStore.get();
995
+ return current ? toTokenSet(current) : null;
996
+ }
997
+ /**
998
+ * Before refreshing with `refreshToken` (refresh lock held): if the storage
999
+ * already holds a newer session from another tab, its message is on the
1000
+ * way - wait for it (up to REMOTE_SESSION_WAIT) instead of refreshing with a
1001
+ * refresh token that may have been rotated out.
1002
+ */
1003
+ async awaitNewerSession(tokenStore, refreshToken) {
1004
+ const persisted = tokenStore.readPersisted();
1005
+ const current = tokenStore.get();
1006
+ if (persisted !== null && persisted.refreshToken !== refreshToken && persisted.setAt > current.setAt) {
1007
+ await this.waitForRemote(REMOTE_SESSION_WAIT);
1008
+ }
1009
+ return this.replacementFor(tokenStore, refreshToken);
1010
+ }
1011
+ /** Resolves on the next change adopted from another tab, after `ms`, or when sync stops */
1012
+ waitForRemote(ms) {
1013
+ return new Promise((resolve) => {
1014
+ const wake = () => {
1015
+ clearTimeout(timer);
1016
+ this.remoteWaiters.delete(wake);
1017
+ resolve();
1018
+ };
1019
+ const timer = setTimeout(wake, ms);
1020
+ this.remoteWaiters.add(wake);
1021
+ });
613
1022
  }
614
1023
  };
615
1024
 
616
1025
  // src/factory.ts
617
1026
  async function createAuthKeeper(options) {
618
1027
  const kernel = new AuthKeeperKernel(options);
619
- await kernel.register(chunkVVSZPARR_cjs.createTokenStorePlugin({ storage: chunkVVSZPARR_cjs.resolveStorage(options.storage) }));
620
- await kernel.register(chunkVVSZPARR_cjs.createTokenDecoderPlugin());
1028
+ await kernel.register(chunkSI7KITBT_cjs.createTokenStorePlugin({ storage: chunkSI7KITBT_cjs.resolveStorage(options.storage) }));
1029
+ await kernel.register(chunkSI7KITBT_cjs.createTokenDecoderPlugin());
621
1030
  await kernel.register(
622
- chunkVVSZPARR_cjs.createRefreshEnginePlugin({
1031
+ chunkSI7KITBT_cjs.createRefreshEnginePlugin({
623
1032
  refreshFn: options.refreshToken,
624
1033
  threshold: options.refreshThreshold
625
1034
  })
626
1035
  );
627
- await kernel.register(chunkVVSZPARR_cjs.createFetchInterceptorPlugin());
1036
+ await kernel.register(chunkSI7KITBT_cjs.createFetchInterceptorPlugin());
628
1037
  await kernel.init();
629
1038
  if (kernel.getAccessToken() && !kernel.isExpired()) {
630
1039
  kernel.scheduleRefresh();
@@ -691,7 +1100,7 @@ function generateCodeVerifier(length = 64) {
691
1100
  const byteLength = Math.ceil(length * 3 / 4);
692
1101
  const randomBytes = new Uint8Array(byteLength);
693
1102
  crypto.getRandomValues(randomBytes);
694
- const verifier = chunkVVSZPARR_cjs.base64UrlEncode(randomBytes).substring(0, length);
1103
+ const verifier = chunkSI7KITBT_cjs.base64UrlEncode(randomBytes).substring(0, length);
695
1104
  return verifier;
696
1105
  }
697
1106
  async function generateCodeChallenge(codeVerifier) {
@@ -699,13 +1108,13 @@ async function generateCodeChallenge(codeVerifier) {
699
1108
  const data = encoder.encode(codeVerifier);
700
1109
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
701
1110
  const hashArray = new Uint8Array(hashBuffer);
702
- return chunkVVSZPARR_cjs.base64UrlEncode(hashArray);
1111
+ return chunkSI7KITBT_cjs.base64UrlEncode(hashArray);
703
1112
  }
704
1113
  function generateRandomString(length) {
705
1114
  const byteLength = Math.ceil(length * 3 / 4);
706
1115
  const randomBytes = new Uint8Array(byteLength);
707
1116
  crypto.getRandomValues(randomBytes);
708
- return chunkVVSZPARR_cjs.base64UrlEncode(randomBytes).substring(0, length);
1117
+ return chunkSI7KITBT_cjs.base64UrlEncode(randomBytes).substring(0, length);
709
1118
  }
710
1119
  function generateUuid() {
711
1120
  if (typeof crypto.randomUUID === "function") {
@@ -721,143 +1130,143 @@ function generateUuid() {
721
1130
 
722
1131
  Object.defineProperty(exports, "CookieStorageAdapter", {
723
1132
  enumerable: true,
724
- get: function () { return chunkVVSZPARR_cjs.CookieStorageAdapter; }
1133
+ get: function () { return chunkSI7KITBT_cjs.CookieStorageAdapter; }
725
1134
  });
726
1135
  Object.defineProperty(exports, "FetchInterceptorPlugin", {
727
1136
  enumerable: true,
728
- get: function () { return chunkVVSZPARR_cjs.FetchInterceptorPlugin; }
1137
+ get: function () { return chunkSI7KITBT_cjs.FetchInterceptorPlugin; }
729
1138
  });
730
1139
  Object.defineProperty(exports, "MemoryStorageAdapter", {
731
1140
  enumerable: true,
732
- get: function () { return chunkVVSZPARR_cjs.MemoryStorageAdapter; }
1141
+ get: function () { return chunkSI7KITBT_cjs.MemoryStorageAdapter; }
733
1142
  });
734
1143
  Object.defineProperty(exports, "RefreshEnginePlugin", {
735
1144
  enumerable: true,
736
- get: function () { return chunkVVSZPARR_cjs.RefreshEnginePlugin; }
1145
+ get: function () { return chunkSI7KITBT_cjs.RefreshEnginePlugin; }
737
1146
  });
738
1147
  Object.defineProperty(exports, "TokenDecoderPlugin", {
739
1148
  enumerable: true,
740
- get: function () { return chunkVVSZPARR_cjs.TokenDecoderPlugin; }
1149
+ get: function () { return chunkSI7KITBT_cjs.TokenDecoderPlugin; }
741
1150
  });
742
1151
  Object.defineProperty(exports, "TokenStorePlugin", {
743
1152
  enumerable: true,
744
- get: function () { return chunkVVSZPARR_cjs.TokenStorePlugin; }
1153
+ get: function () { return chunkSI7KITBT_cjs.TokenStorePlugin; }
745
1154
  });
746
1155
  Object.defineProperty(exports, "WebStorageAdapter", {
747
1156
  enumerable: true,
748
- get: function () { return chunkVVSZPARR_cjs.WebStorageAdapter; }
1157
+ get: function () { return chunkSI7KITBT_cjs.WebStorageAdapter; }
749
1158
  });
750
1159
  Object.defineProperty(exports, "base64UrlDecode", {
751
1160
  enumerable: true,
752
- get: function () { return chunkVVSZPARR_cjs.base64UrlDecode; }
1161
+ get: function () { return chunkSI7KITBT_cjs.base64UrlDecode; }
753
1162
  });
754
1163
  Object.defineProperty(exports, "base64UrlDecodeToBytes", {
755
1164
  enumerable: true,
756
- get: function () { return chunkVVSZPARR_cjs.base64UrlDecodeToBytes; }
1165
+ get: function () { return chunkSI7KITBT_cjs.base64UrlDecodeToBytes; }
757
1166
  });
758
1167
  Object.defineProperty(exports, "base64UrlEncode", {
759
1168
  enumerable: true,
760
- get: function () { return chunkVVSZPARR_cjs.base64UrlEncode; }
1169
+ get: function () { return chunkSI7KITBT_cjs.base64UrlEncode; }
761
1170
  });
762
1171
  Object.defineProperty(exports, "createFetchInterceptorPlugin", {
763
1172
  enumerable: true,
764
- get: function () { return chunkVVSZPARR_cjs.createFetchInterceptorPlugin; }
1173
+ get: function () { return chunkSI7KITBT_cjs.createFetchInterceptorPlugin; }
765
1174
  });
766
1175
  Object.defineProperty(exports, "createMemoryStorage", {
767
1176
  enumerable: true,
768
- get: function () { return chunkVVSZPARR_cjs.createMemoryStorage; }
1177
+ get: function () { return chunkSI7KITBT_cjs.createMemoryStorage; }
769
1178
  });
770
1179
  Object.defineProperty(exports, "createRefreshEnginePlugin", {
771
1180
  enumerable: true,
772
- get: function () { return chunkVVSZPARR_cjs.createRefreshEnginePlugin; }
1181
+ get: function () { return chunkSI7KITBT_cjs.createRefreshEnginePlugin; }
773
1182
  });
774
1183
  Object.defineProperty(exports, "createTokenDecoderPlugin", {
775
1184
  enumerable: true,
776
- get: function () { return chunkVVSZPARR_cjs.createTokenDecoderPlugin; }
1185
+ get: function () { return chunkSI7KITBT_cjs.createTokenDecoderPlugin; }
777
1186
  });
778
1187
  Object.defineProperty(exports, "createTokenStorePlugin", {
779
1188
  enumerable: true,
780
- get: function () { return chunkVVSZPARR_cjs.createTokenStorePlugin; }
1189
+ get: function () { return chunkSI7KITBT_cjs.createTokenStorePlugin; }
781
1190
  });
782
1191
  Object.defineProperty(exports, "decodeHeader", {
783
1192
  enumerable: true,
784
- get: function () { return chunkVVSZPARR_cjs.decodeHeader; }
1193
+ get: function () { return chunkSI7KITBT_cjs.decodeHeader; }
785
1194
  });
786
1195
  Object.defineProperty(exports, "decodeJwt", {
787
1196
  enumerable: true,
788
- get: function () { return chunkVVSZPARR_cjs.decodeJwt; }
1197
+ get: function () { return chunkSI7KITBT_cjs.decodeJwt; }
789
1198
  });
790
1199
  Object.defineProperty(exports, "decodePayload", {
791
1200
  enumerable: true,
792
- get: function () { return chunkVVSZPARR_cjs.decodePayload; }
1201
+ get: function () { return chunkSI7KITBT_cjs.decodePayload; }
793
1202
  });
794
1203
  Object.defineProperty(exports, "deleteCookie", {
795
1204
  enumerable: true,
796
- get: function () { return chunkVVSZPARR_cjs.deleteCookie; }
1205
+ get: function () { return chunkSI7KITBT_cjs.deleteCookie; }
797
1206
  });
798
1207
  Object.defineProperty(exports, "getClaim", {
799
1208
  enumerable: true,
800
- get: function () { return chunkVVSZPARR_cjs.getClaim; }
1209
+ get: function () { return chunkSI7KITBT_cjs.getClaim; }
801
1210
  });
802
1211
  Object.defineProperty(exports, "getClaims", {
803
1212
  enumerable: true,
804
- get: function () { return chunkVVSZPARR_cjs.getClaims; }
1213
+ get: function () { return chunkSI7KITBT_cjs.getClaims; }
805
1214
  });
806
1215
  Object.defineProperty(exports, "getCookie", {
807
1216
  enumerable: true,
808
- get: function () { return chunkVVSZPARR_cjs.getCookie; }
1217
+ get: function () { return chunkSI7KITBT_cjs.getCookie; }
809
1218
  });
810
1219
  Object.defineProperty(exports, "getTimeUntilExpiry", {
811
1220
  enumerable: true,
812
- get: function () { return chunkVVSZPARR_cjs.getTimeUntilExpiry; }
1221
+ get: function () { return chunkSI7KITBT_cjs.getTimeUntilExpiry; }
813
1222
  });
814
1223
  Object.defineProperty(exports, "getTokenExpiry", {
815
1224
  enumerable: true,
816
- get: function () { return chunkVVSZPARR_cjs.getTokenExpiry; }
1225
+ get: function () { return chunkSI7KITBT_cjs.getTokenExpiry; }
817
1226
  });
818
1227
  Object.defineProperty(exports, "isStorageAvailable", {
819
1228
  enumerable: true,
820
- get: function () { return chunkVVSZPARR_cjs.isStorageAvailable; }
1229
+ get: function () { return chunkSI7KITBT_cjs.isStorageAvailable; }
821
1230
  });
822
1231
  Object.defineProperty(exports, "isTokenExpired", {
823
1232
  enumerable: true,
824
- get: function () { return chunkVVSZPARR_cjs.isTokenExpired; }
1233
+ get: function () { return chunkSI7KITBT_cjs.isTokenExpired; }
825
1234
  });
826
1235
  Object.defineProperty(exports, "isValidJwtFormat", {
827
1236
  enumerable: true,
828
- get: function () { return chunkVVSZPARR_cjs.isValidJwtFormat; }
1237
+ get: function () { return chunkSI7KITBT_cjs.isValidJwtFormat; }
829
1238
  });
830
1239
  Object.defineProperty(exports, "parseCookies", {
831
1240
  enumerable: true,
832
- get: function () { return chunkVVSZPARR_cjs.parseCookies; }
1241
+ get: function () { return chunkSI7KITBT_cjs.parseCookies; }
833
1242
  });
834
1243
  Object.defineProperty(exports, "safeGetItem", {
835
1244
  enumerable: true,
836
- get: function () { return chunkVVSZPARR_cjs.safeGetItem; }
1245
+ get: function () { return chunkSI7KITBT_cjs.safeGetItem; }
837
1246
  });
838
1247
  Object.defineProperty(exports, "safeRemoveItem", {
839
1248
  enumerable: true,
840
- get: function () { return chunkVVSZPARR_cjs.safeRemoveItem; }
1249
+ get: function () { return chunkSI7KITBT_cjs.safeRemoveItem; }
841
1250
  });
842
1251
  Object.defineProperty(exports, "safeSetItem", {
843
1252
  enumerable: true,
844
- get: function () { return chunkVVSZPARR_cjs.safeSetItem; }
1253
+ get: function () { return chunkSI7KITBT_cjs.safeSetItem; }
845
1254
  });
846
1255
  Object.defineProperty(exports, "serializeCookie", {
847
1256
  enumerable: true,
848
- get: function () { return chunkVVSZPARR_cjs.serializeCookie; }
1257
+ get: function () { return chunkSI7KITBT_cjs.serializeCookie; }
849
1258
  });
850
1259
  Object.defineProperty(exports, "setCookie", {
851
1260
  enumerable: true,
852
- get: function () { return chunkVVSZPARR_cjs.setCookie; }
1261
+ get: function () { return chunkSI7KITBT_cjs.setCookie; }
853
1262
  });
854
1263
  Object.defineProperty(exports, "stringToBase64Url", {
855
1264
  enumerable: true,
856
- get: function () { return chunkVVSZPARR_cjs.stringToBase64Url; }
1265
+ get: function () { return chunkSI7KITBT_cjs.stringToBase64Url; }
857
1266
  });
858
1267
  Object.defineProperty(exports, "AuthError", {
859
1268
  enumerable: true,
860
- get: function () { return chunkXGKVBZSF_cjs.AuthError; }
1269
+ get: function () { return chunkMONA6MGX_cjs.AuthError; }
861
1270
  });
862
1271
  exports.AuthKeeperKernel = AuthKeeperKernel;
863
1272
  exports.EventBus = EventBus;