@oxog/authkeeper 1.5.0 → 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 +19 -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-47JWRVTL.cjs → chunk-SI7KITBT.cjs} +319 -264
  10. package/dist/chunk-SI7KITBT.cjs.map +1 -0
  11. package/dist/{chunk-ANGR5HRJ.js → chunk-ZZMKSCXQ.js} +310 -256
  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 +36 -4
  18. package/dist/index.d.ts +36 -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 +5 -2
  38. package/dist/chunk-47JWRVTL.cjs.map +0 -1
  39. package/dist/chunk-ANGR5HRJ.js.map +0 -1
  40. package/dist/chunk-DLCD3SBV.js.map +0 -1
  41. package/dist/chunk-XGKVBZSF.cjs.map +0 -1
@@ -1,6 +1,253 @@
1
1
  'use strict';
2
2
 
3
- var chunkXGKVBZSF_cjs = require('./chunk-XGKVBZSF.cjs');
3
+ var chunkMONA6MGX_cjs = require('./chunk-MONA6MGX.cjs');
4
+
5
+ // src/plugins/core/storage-memory.ts
6
+ var MemoryStorageAdapter = class {
7
+ constructor(options = {}) {
8
+ this.store = /* @__PURE__ */ new Map();
9
+ this.prefix = options.prefix || "authkeeper:";
10
+ }
11
+ /**
12
+ * Get value by key
13
+ */
14
+ get(key) {
15
+ return this.store.get(this.prefix + key) || null;
16
+ }
17
+ /**
18
+ * Set value by key
19
+ */
20
+ set(key, value) {
21
+ this.store.set(this.prefix + key, value);
22
+ }
23
+ /**
24
+ * Remove value by key
25
+ */
26
+ remove(key) {
27
+ this.store.delete(this.prefix + key);
28
+ }
29
+ /**
30
+ * Clear all values
31
+ */
32
+ clear() {
33
+ const keysToDelete = [];
34
+ for (const key of this.store.keys()) {
35
+ if (key.startsWith(this.prefix)) {
36
+ keysToDelete.push(key);
37
+ }
38
+ }
39
+ keysToDelete.forEach((key) => this.store.delete(key));
40
+ }
41
+ };
42
+ function createMemoryStorage(options) {
43
+ return new MemoryStorageAdapter(options);
44
+ }
45
+
46
+ // src/utils/cookie.ts
47
+ function parseCookies(cookieString) {
48
+ const cookies = {};
49
+ if (!cookieString) {
50
+ return cookies;
51
+ }
52
+ cookieString.split(";").forEach((cookie) => {
53
+ const [key, ...valueParts] = cookie.split("=");
54
+ const trimmedKey = key?.trim();
55
+ const value = valueParts.join("=").trim();
56
+ if (trimmedKey) {
57
+ cookies[safeDecode(trimmedKey)] = safeDecode(value);
58
+ }
59
+ });
60
+ return cookies;
61
+ }
62
+ function safeDecode(value) {
63
+ try {
64
+ return decodeURIComponent(value);
65
+ } catch {
66
+ return value;
67
+ }
68
+ }
69
+ var INVALID_ATTRIBUTE_VALUE = /[;\r\n\0]/;
70
+ function assertAttributeValue(name, value) {
71
+ if (INVALID_ATTRIBUTE_VALUE.test(value)) {
72
+ throw new TypeError(`Invalid cookie ${name}: must not contain ';', CR, LF or NUL`);
73
+ }
74
+ }
75
+ function getCookie(name) {
76
+ if (typeof document === "undefined") {
77
+ return null;
78
+ }
79
+ const cookies = parseCookies(document.cookie);
80
+ return cookies[name] || null;
81
+ }
82
+ function serializeCookie(name, value, attributes = {}) {
83
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
84
+ if (attributes.path) {
85
+ assertAttributeValue("path", attributes.path);
86
+ cookie += `; Path=${attributes.path}`;
87
+ }
88
+ if (attributes.domain) {
89
+ assertAttributeValue("domain", attributes.domain);
90
+ cookie += `; Domain=${attributes.domain}`;
91
+ }
92
+ if (attributes.maxAge !== void 0) {
93
+ cookie += `; Max-Age=${attributes.maxAge}`;
94
+ }
95
+ if (attributes.expires) {
96
+ cookie += `; Expires=${attributes.expires.toUTCString()}`;
97
+ }
98
+ if (attributes.secure || attributes.sameSite === "none") {
99
+ cookie += "; Secure";
100
+ }
101
+ if (attributes.sameSite) {
102
+ const sameSite = attributes.sameSite.charAt(0).toUpperCase() + attributes.sameSite.slice(1);
103
+ cookie += `; SameSite=${sameSite}`;
104
+ }
105
+ if (attributes.httpOnly) {
106
+ cookie += "; HttpOnly";
107
+ }
108
+ return cookie;
109
+ }
110
+ function setCookie(name, value, attributes = {}) {
111
+ if (typeof document === "undefined") {
112
+ return;
113
+ }
114
+ document.cookie = serializeCookie(name, value, attributes);
115
+ }
116
+ function deleteCookie(name, attributes = {}) {
117
+ if (typeof document === "undefined") {
118
+ return;
119
+ }
120
+ document.cookie = serializeCookie(name, "", {
121
+ ...attributes,
122
+ expires: /* @__PURE__ */ new Date(0)
123
+ });
124
+ }
125
+
126
+ // src/utils/storage.ts
127
+ function isQuotaExceeded(error) {
128
+ if (typeof error !== "object" || error === null) return false;
129
+ const { name, code } = error;
130
+ return name === "QuotaExceededError" || code === 22;
131
+ }
132
+ function isStorageAvailable(storage) {
133
+ if (!storage) {
134
+ return false;
135
+ }
136
+ try {
137
+ const testKey = "__storage_test__";
138
+ storage.setItem(testKey, "test");
139
+ storage.removeItem(testKey);
140
+ return true;
141
+ } catch (error) {
142
+ return isQuotaExceeded(error) && storage.length > 0;
143
+ }
144
+ }
145
+ function safeGetItem(storage, key) {
146
+ try {
147
+ return storage.get(key);
148
+ } catch {
149
+ return null;
150
+ }
151
+ }
152
+ function safeSetItem(storage, key, value) {
153
+ try {
154
+ storage.set(key, value);
155
+ return true;
156
+ } catch {
157
+ return false;
158
+ }
159
+ }
160
+ function safeRemoveItem(storage, key) {
161
+ try {
162
+ storage.remove(key);
163
+ return true;
164
+ } catch {
165
+ return false;
166
+ }
167
+ }
168
+
169
+ // src/plugins/core/storage-web.ts
170
+ var WebStorageAdapter = class {
171
+ constructor(storage, options = {}) {
172
+ this.storage = storage;
173
+ this.prefix = options.prefix ?? "authkeeper:";
174
+ }
175
+ get(key) {
176
+ return this.storage.getItem(this.prefix + key);
177
+ }
178
+ set(key, value) {
179
+ this.storage.setItem(this.prefix + key, value);
180
+ }
181
+ remove(key) {
182
+ this.storage.removeItem(this.prefix + key);
183
+ }
184
+ clear() {
185
+ const keys = [];
186
+ for (let i = 0; i < this.storage.length; i++) {
187
+ const key = this.storage.key(i);
188
+ if (key !== null && key.startsWith(this.prefix)) {
189
+ keys.push(key);
190
+ }
191
+ }
192
+ keys.forEach((key) => this.storage.removeItem(key));
193
+ }
194
+ };
195
+ var CookieStorageAdapter = class {
196
+ constructor(options = {}) {
197
+ this.keys = /* @__PURE__ */ new Set();
198
+ this.prefix = options.prefix ?? "authkeeper_";
199
+ this.attributes = { path: "/", secure: true, sameSite: "strict", ...options.attributes };
200
+ }
201
+ get(key) {
202
+ return getCookie(this.prefix + key);
203
+ }
204
+ set(key, value) {
205
+ setCookie(this.prefix + key, value, this.attributes);
206
+ this.keys.add(key);
207
+ if (typeof document !== "undefined" && this.get(key) !== value) {
208
+ throw new chunkMONA6MGX_cjs.AuthError(
209
+ "STORAGE_ERROR",
210
+ `Cookie "${this.prefix + key}" was not stored (too large or blocked)`
211
+ );
212
+ }
213
+ }
214
+ remove(key) {
215
+ const { path, domain, secure, sameSite } = this.attributes;
216
+ deleteCookie(this.prefix + key, { path, domain, secure, sameSite });
217
+ this.keys.delete(key);
218
+ }
219
+ clear() {
220
+ Array.from(this.keys).forEach((key) => this.remove(key));
221
+ }
222
+ };
223
+ function getWebStorage(type) {
224
+ try {
225
+ return typeof window !== "undefined" ? window[type] : void 0;
226
+ } catch {
227
+ return void 0;
228
+ }
229
+ }
230
+ function resolveStorage(storage) {
231
+ if (storage === void 0 || storage === "memory") {
232
+ return void 0;
233
+ }
234
+ if (typeof storage === "object" && storage !== null) {
235
+ return storage;
236
+ }
237
+ switch (storage) {
238
+ case "localStorage":
239
+ case "sessionStorage": {
240
+ const webStorage = getWebStorage(storage);
241
+ return webStorage && isStorageAvailable(webStorage) ? new WebStorageAdapter(webStorage) : createMemoryStorage();
242
+ }
243
+ case "cookie":
244
+ return typeof document !== "undefined" ? new CookieStorageAdapter() : createMemoryStorage();
245
+ default:
246
+ throw new chunkMONA6MGX_cjs.AuthError("CONFIG_ERROR", `Unknown storage type: ${String(storage)}`, {
247
+ context: { storage }
248
+ });
249
+ }
250
+ }
4
251
 
5
252
  // src/utils/base64.ts
6
253
  function base64UrlEncode(buffer) {
@@ -54,7 +301,7 @@ function decodeJwt(token) {
54
301
  const parts = token.split(".");
55
302
  const [headerPart, payloadPart] = parts;
56
303
  if (parts.length !== 3 || headerPart === void 0 || payloadPart === void 0) {
57
- throw new chunkXGKVBZSF_cjs.AuthError("TOKEN_DECODE_FAILED", "Invalid JWT format: must have 3 parts", {
304
+ throw new chunkMONA6MGX_cjs.AuthError("TOKEN_DECODE_FAILED", "Invalid JWT format: must have 3 parts", {
58
305
  context: { parts: parts.length }
59
306
  });
60
307
  }
@@ -65,7 +312,7 @@ function decodeJwt(token) {
65
312
  const payload = JSON.parse(payloadJson);
66
313
  return { header, payload };
67
314
  } catch (error) {
68
- throw new chunkXGKVBZSF_cjs.AuthError("TOKEN_DECODE_FAILED", "Failed to decode JWT", {
315
+ throw new chunkMONA6MGX_cjs.AuthError("TOKEN_DECODE_FAILED", "Failed to decode JWT", {
69
316
  cause: error
70
317
  });
71
318
  }
@@ -151,6 +398,16 @@ function getClaims(token, claims) {
151
398
  }
152
399
  }
153
400
 
401
+ // src/plugins/core/stored-tokens.ts
402
+ function isStoredTokens(value) {
403
+ if (value === null || typeof value !== "object") return false;
404
+ const v = value;
405
+ return typeof v["accessToken"] === "string" && v["accessToken"] !== "" && (v["refreshToken"] === null || typeof v["refreshToken"] === "string") && typeof v["tokenType"] === "string" && (v["expiresAt"] === null || isFiniteNumber(v["expiresAt"])) && isFiniteNumber(v["setAt"]) && isFiniteNumber(v["refreshCount"]);
406
+ }
407
+ function isFiniteNumber(value) {
408
+ return typeof value === "number" && Number.isFinite(value);
409
+ }
410
+
154
411
  // src/plugins/core/token-store.ts
155
412
  var TokenStorePlugin = class {
156
413
  constructor(options = {}) {
@@ -189,7 +446,12 @@ var TokenStorePlugin = class {
189
446
  if (!this.tokens?.setAt) return null;
190
447
  return new Date(this.tokens.setAt);
191
448
  },
192
- getRefreshCount: () => this.tokens?.refreshCount || 0
449
+ getRefreshCount: () => this.tokens?.refreshCount || 0,
450
+ replace: (tokens) => {
451
+ this.tokens = tokens === null ? null : { ...tokens };
452
+ },
453
+ readPersisted: () => this.readPersisted(),
454
+ getStorage: () => this.options.storage ? { adapter: this.options.storage, key: this.storageKey } : null
193
455
  };
194
456
  }
195
457
  /**
@@ -197,15 +459,15 @@ var TokenStorePlugin = class {
197
459
  */
198
460
  set(tokens) {
199
461
  if (typeof tokens?.accessToken !== "string" || tokens.accessToken === "") {
200
- throw new chunkXGKVBZSF_cjs.AuthError("TOKEN_INVALID", "accessToken must be a non-empty string");
462
+ throw new chunkMONA6MGX_cjs.AuthError("TOKEN_INVALID", "accessToken must be a non-empty string");
201
463
  }
202
464
  if (this.options.validateOnSet && !isValidJwtFormat(tokens.accessToken)) {
203
- throw new chunkXGKVBZSF_cjs.AuthError("TOKEN_INVALID", "accessToken is not a valid JWT");
465
+ throw new chunkMONA6MGX_cjs.AuthError("TOKEN_INVALID", "accessToken is not a valid JWT");
204
466
  }
205
467
  let expiresAt;
206
- if (isFiniteNumber(tokens.expiresAt)) {
468
+ if (isFiniteNumber2(tokens.expiresAt)) {
207
469
  expiresAt = tokens.expiresAt * 1e3;
208
- } else if (isFiniteNumber(tokens.expiresIn)) {
470
+ } else if (isFiniteNumber2(tokens.expiresIn)) {
209
471
  expiresAt = Date.now() + tokens.expiresIn * 1e3;
210
472
  } else {
211
473
  expiresAt = getTokenExpiry(tokens.accessToken)?.getTime() ?? null;
@@ -271,6 +533,15 @@ var TokenStorePlugin = class {
271
533
  this.reportStorageError("Failed to persist tokens", error);
272
534
  }
273
535
  }
536
+ /** The tokens in the storage adapter, if readable and well-formed */
537
+ readPersisted() {
538
+ try {
539
+ const parsed = JSON.parse(this.options.storage?.get(this.storageKey) ?? "null");
540
+ return isStoredTokens(parsed) ? parsed : null;
541
+ } catch {
542
+ return null;
543
+ }
544
+ }
274
545
  /**
275
546
  * Load tokens from the storage adapter. Corrupt or malformed entries are
276
547
  * removed rather than trusted.
@@ -303,7 +574,7 @@ var TokenStorePlugin = class {
303
574
  this.reportStorageError("Discarded malformed persisted tokens");
304
575
  }
305
576
  reportStorageError(message, cause) {
306
- const error = new chunkXGKVBZSF_cjs.AuthError("STORAGE_ERROR", message, {
577
+ const error = new chunkMONA6MGX_cjs.AuthError("STORAGE_ERROR", message, {
307
578
  cause: (
308
579
  // eslint-disable-next-line @typescript-eslint/no-base-to-string -- a non-Error cause is kept as its string form
309
580
  cause === void 0 ? void 0 : cause instanceof Error ? cause : new Error(String(cause))
@@ -314,12 +585,7 @@ var TokenStorePlugin = class {
314
585
  }
315
586
  }
316
587
  };
317
- function isStoredTokens(value) {
318
- if (value === null || typeof value !== "object") return false;
319
- const v = value;
320
- return typeof v["accessToken"] === "string" && v["accessToken"] !== "" && (v["refreshToken"] === null || typeof v["refreshToken"] === "string") && typeof v["tokenType"] === "string" && (v["expiresAt"] === null || isFiniteNumber(v["expiresAt"])) && isFiniteNumber(v["setAt"]) && isFiniteNumber(v["refreshCount"]);
321
- }
322
- function isFiniteNumber(value) {
588
+ function isFiniteNumber2(value) {
323
589
  return typeof value === "number" && Number.isFinite(value);
324
590
  }
325
591
  function createTokenStorePlugin(options) {
@@ -464,6 +730,7 @@ var RefreshEnginePlugin = class {
464
730
  this.backoffs = /* @__PURE__ */ new Set();
465
731
  this.uninstalled = false;
466
732
  this.scheduledRefreshTimeout = null;
733
+ this.coordinator = null;
467
734
  this.options = options;
468
735
  this.refreshFn = options.refreshFn;
469
736
  this.threshold = options.threshold ?? 60;
@@ -485,6 +752,9 @@ var RefreshEnginePlugin = class {
485
752
  },
486
753
  setThreshold: (seconds) => {
487
754
  this.threshold = seconds;
755
+ },
756
+ setCoordinator: (coordinator) => {
757
+ this.coordinator = coordinator;
488
758
  }
489
759
  };
490
760
  }
@@ -500,7 +770,8 @@ var RefreshEnginePlugin = class {
500
770
  }
501
771
  this.endBackoffs();
502
772
  this.isRefreshingFlag = true;
503
- const promise = this.executeRefresh();
773
+ const coordinator = this.coordinator;
774
+ const promise = coordinator && refreshToken ? this.coordinatedRefresh(coordinator, refreshToken) : this.executeRefresh();
504
775
  this.refreshPromise = promise;
505
776
  this.refreshPromiseToken = refreshToken;
506
777
  try {
@@ -514,6 +785,24 @@ var RefreshEnginePlugin = class {
514
785
  }
515
786
  }
516
787
  }
788
+ /**
789
+ * Refresh while holding the cross-tab lock. Another tab may have refreshed
790
+ * this session meanwhile: its result is used instead of refreshing again
791
+ * (with rotating refresh tokens a second refresh would be rejected).
792
+ */
793
+ coordinatedRefresh(coordinator, refreshToken) {
794
+ return coordinator.exclusive(async () => {
795
+ if (this.kernel.getRefreshToken() === refreshToken) {
796
+ const adopted = await coordinator.beforeRefresh(refreshToken);
797
+ if (adopted) return adopted;
798
+ }
799
+ return this.executeRefresh(0, refreshToken);
800
+ });
801
+ }
802
+ /** The session another tab replaced `refreshToken` with, if any */
803
+ replacementFor(refreshToken) {
804
+ return this.coordinator?.replacement(refreshToken) ?? null;
805
+ }
517
806
  /** Wait before a retry; endBackoffs() cuts the wait short */
518
807
  waitBackoff(ms) {
519
808
  return new Promise((resolve) => {
@@ -540,13 +829,15 @@ var RefreshEnginePlugin = class {
540
829
  async executeRefresh(retryCount = 0, initialRefreshToken) {
541
830
  const refreshToken = this.uninstalled ? null : this.kernel.getRefreshToken();
542
831
  if (initialRefreshToken !== void 0 && refreshToken !== initialRefreshToken) {
832
+ const replacement = this.replacementFor(initialRefreshToken);
833
+ if (replacement) return replacement;
543
834
  throw supersededError();
544
835
  }
545
836
  if (this.options.onRefreshStart) {
546
837
  this.options.onRefreshStart();
547
838
  }
548
839
  if (!refreshToken) {
549
- const error = new chunkXGKVBZSF_cjs.AuthError("REFRESH_TOKEN_MISSING", "No refresh token available");
840
+ const error = new chunkMONA6MGX_cjs.AuthError("REFRESH_TOKEN_MISSING", "No refresh token available");
550
841
  this.kernel.emit({
551
842
  type: "error",
552
843
  error,
@@ -559,6 +850,8 @@ var RefreshEnginePlugin = class {
559
850
  const previousExpiresAt = this.kernel.getExpiresAt();
560
851
  const newTokens = await this.refreshFn(refreshToken);
561
852
  if (this.kernel.getRefreshToken() !== refreshToken) {
853
+ const replacement = this.replacementFor(refreshToken);
854
+ if (replacement) return replacement;
562
855
  throw new SupersededRefreshError();
563
856
  }
564
857
  this.applyingRefresh = true;
@@ -586,12 +879,14 @@ var RefreshEnginePlugin = class {
586
879
  if (error instanceof SupersededRefreshError) {
587
880
  throw supersededError();
588
881
  }
882
+ const replacement = this.replacementFor(refreshToken);
883
+ if (replacement) return replacement;
589
884
  if (retryCount < this.maxRetries) {
590
885
  const delay = this.retryDelay * Math.pow(2, retryCount);
591
886
  await this.waitBackoff(Math.min(delay, MAX_TIMEOUT_DELAY));
592
887
  return this.executeRefresh(retryCount + 1, refreshToken);
593
888
  }
594
- const authError = new chunkXGKVBZSF_cjs.AuthError("REFRESH_FAILED", "Token refresh failed", {
889
+ const authError = new chunkMONA6MGX_cjs.AuthError("REFRESH_FAILED", "Token refresh failed", {
595
890
  cause: error instanceof Error ? error : new Error(String(error)),
596
891
  context: { retryCount }
597
892
  });
@@ -677,266 +972,25 @@ var RefreshEnginePlugin = class {
677
972
  */
678
973
  uninstall() {
679
974
  this.cancelScheduledRefresh();
975
+ this.coordinator = null;
680
976
  this.uninstalled = true;
681
977
  this.endBackoffs();
682
978
  }
683
979
  };
684
980
  function supersededError() {
685
- return new chunkXGKVBZSF_cjs.AuthError(
981
+ return new chunkMONA6MGX_cjs.AuthError(
686
982
  "REFRESH_FAILED",
687
983
  "Session changed while refreshing (logout or new login); refresh result discarded",
688
984
  { context: { superseded: true } }
689
985
  );
690
986
  }
691
987
  function isSupersededError(error) {
692
- return error instanceof chunkXGKVBZSF_cjs.AuthError && error.context?.["superseded"] === true;
988
+ return error instanceof chunkMONA6MGX_cjs.AuthError && error.context?.["superseded"] === true;
693
989
  }
694
990
  function createRefreshEnginePlugin(options) {
695
991
  return new RefreshEnginePlugin(options);
696
992
  }
697
993
 
698
- // src/plugins/core/storage-memory.ts
699
- var MemoryStorageAdapter = class {
700
- constructor(options = {}) {
701
- this.store = /* @__PURE__ */ new Map();
702
- this.prefix = options.prefix || "authkeeper:";
703
- }
704
- /**
705
- * Get value by key
706
- */
707
- get(key) {
708
- return this.store.get(this.prefix + key) || null;
709
- }
710
- /**
711
- * Set value by key
712
- */
713
- set(key, value) {
714
- this.store.set(this.prefix + key, value);
715
- }
716
- /**
717
- * Remove value by key
718
- */
719
- remove(key) {
720
- this.store.delete(this.prefix + key);
721
- }
722
- /**
723
- * Clear all values
724
- */
725
- clear() {
726
- const keysToDelete = [];
727
- for (const key of this.store.keys()) {
728
- if (key.startsWith(this.prefix)) {
729
- keysToDelete.push(key);
730
- }
731
- }
732
- keysToDelete.forEach((key) => this.store.delete(key));
733
- }
734
- };
735
- function createMemoryStorage(options) {
736
- return new MemoryStorageAdapter(options);
737
- }
738
-
739
- // src/utils/cookie.ts
740
- function parseCookies(cookieString) {
741
- const cookies = {};
742
- if (!cookieString) {
743
- return cookies;
744
- }
745
- cookieString.split(";").forEach((cookie) => {
746
- const [key, ...valueParts] = cookie.split("=");
747
- const trimmedKey = key?.trim();
748
- const value = valueParts.join("=").trim();
749
- if (trimmedKey) {
750
- cookies[safeDecode(trimmedKey)] = safeDecode(value);
751
- }
752
- });
753
- return cookies;
754
- }
755
- function safeDecode(value) {
756
- try {
757
- return decodeURIComponent(value);
758
- } catch {
759
- return value;
760
- }
761
- }
762
- var INVALID_ATTRIBUTE_VALUE = /[;\r\n\0]/;
763
- function assertAttributeValue(name, value) {
764
- if (INVALID_ATTRIBUTE_VALUE.test(value)) {
765
- throw new TypeError(`Invalid cookie ${name}: must not contain ';', CR, LF or NUL`);
766
- }
767
- }
768
- function getCookie(name) {
769
- if (typeof document === "undefined") {
770
- return null;
771
- }
772
- const cookies = parseCookies(document.cookie);
773
- return cookies[name] || null;
774
- }
775
- function serializeCookie(name, value, attributes = {}) {
776
- let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
777
- if (attributes.path) {
778
- assertAttributeValue("path", attributes.path);
779
- cookie += `; Path=${attributes.path}`;
780
- }
781
- if (attributes.domain) {
782
- assertAttributeValue("domain", attributes.domain);
783
- cookie += `; Domain=${attributes.domain}`;
784
- }
785
- if (attributes.maxAge !== void 0) {
786
- cookie += `; Max-Age=${attributes.maxAge}`;
787
- }
788
- if (attributes.expires) {
789
- cookie += `; Expires=${attributes.expires.toUTCString()}`;
790
- }
791
- if (attributes.secure || attributes.sameSite === "none") {
792
- cookie += "; Secure";
793
- }
794
- if (attributes.sameSite) {
795
- const sameSite = attributes.sameSite.charAt(0).toUpperCase() + attributes.sameSite.slice(1);
796
- cookie += `; SameSite=${sameSite}`;
797
- }
798
- if (attributes.httpOnly) {
799
- cookie += "; HttpOnly";
800
- }
801
- return cookie;
802
- }
803
- function setCookie(name, value, attributes = {}) {
804
- if (typeof document === "undefined") {
805
- return;
806
- }
807
- document.cookie = serializeCookie(name, value, attributes);
808
- }
809
- function deleteCookie(name, attributes = {}) {
810
- if (typeof document === "undefined") {
811
- return;
812
- }
813
- document.cookie = serializeCookie(name, "", {
814
- ...attributes,
815
- expires: /* @__PURE__ */ new Date(0)
816
- });
817
- }
818
-
819
- // src/utils/storage.ts
820
- function isStorageAvailable(storage) {
821
- if (!storage) {
822
- return false;
823
- }
824
- try {
825
- const testKey = "__storage_test__";
826
- storage.setItem(testKey, "test");
827
- storage.removeItem(testKey);
828
- return true;
829
- } catch {
830
- return false;
831
- }
832
- }
833
- function safeGetItem(storage, key) {
834
- try {
835
- return storage.get(key);
836
- } catch {
837
- return null;
838
- }
839
- }
840
- function safeSetItem(storage, key, value) {
841
- try {
842
- storage.set(key, value);
843
- return true;
844
- } catch {
845
- return false;
846
- }
847
- }
848
- function safeRemoveItem(storage, key) {
849
- try {
850
- storage.remove(key);
851
- return true;
852
- } catch {
853
- return false;
854
- }
855
- }
856
-
857
- // src/plugins/core/storage-web.ts
858
- var WebStorageAdapter = class {
859
- constructor(storage, options = {}) {
860
- this.storage = storage;
861
- this.prefix = options.prefix ?? "authkeeper:";
862
- }
863
- get(key) {
864
- return this.storage.getItem(this.prefix + key);
865
- }
866
- set(key, value) {
867
- this.storage.setItem(this.prefix + key, value);
868
- }
869
- remove(key) {
870
- this.storage.removeItem(this.prefix + key);
871
- }
872
- clear() {
873
- const keys = [];
874
- for (let i = 0; i < this.storage.length; i++) {
875
- const key = this.storage.key(i);
876
- if (key !== null && key.startsWith(this.prefix)) {
877
- keys.push(key);
878
- }
879
- }
880
- keys.forEach((key) => this.storage.removeItem(key));
881
- }
882
- };
883
- var CookieStorageAdapter = class {
884
- constructor(options = {}) {
885
- this.keys = /* @__PURE__ */ new Set();
886
- this.prefix = options.prefix ?? "authkeeper_";
887
- this.attributes = { path: "/", secure: true, sameSite: "strict", ...options.attributes };
888
- }
889
- get(key) {
890
- return getCookie(this.prefix + key);
891
- }
892
- set(key, value) {
893
- setCookie(this.prefix + key, value, this.attributes);
894
- this.keys.add(key);
895
- if (typeof document !== "undefined" && this.get(key) !== value) {
896
- throw new chunkXGKVBZSF_cjs.AuthError(
897
- "STORAGE_ERROR",
898
- `Cookie "${this.prefix + key}" was not stored (too large or blocked)`
899
- );
900
- }
901
- }
902
- remove(key) {
903
- const { path, domain, secure, sameSite } = this.attributes;
904
- deleteCookie(this.prefix + key, { path, domain, secure, sameSite });
905
- this.keys.delete(key);
906
- }
907
- clear() {
908
- Array.from(this.keys).forEach((key) => this.remove(key));
909
- }
910
- };
911
- function getWebStorage(type) {
912
- try {
913
- return typeof window !== "undefined" ? window[type] : void 0;
914
- } catch {
915
- return void 0;
916
- }
917
- }
918
- function resolveStorage(storage) {
919
- if (storage === void 0 || storage === "memory") {
920
- return void 0;
921
- }
922
- if (typeof storage === "object" && storage !== null) {
923
- return storage;
924
- }
925
- switch (storage) {
926
- case "localStorage":
927
- case "sessionStorage": {
928
- const webStorage = getWebStorage(storage);
929
- return webStorage && isStorageAvailable(webStorage) ? new WebStorageAdapter(webStorage) : createMemoryStorage();
930
- }
931
- case "cookie":
932
- return typeof document !== "undefined" ? new CookieStorageAdapter() : createMemoryStorage();
933
- default:
934
- throw new chunkXGKVBZSF_cjs.AuthError("CONFIG_ERROR", `Unknown storage type: ${String(storage)}`, {
935
- context: { storage }
936
- });
937
- }
938
- }
939
-
940
994
  // src/plugins/core/fetch-interceptor.ts
941
995
  var FetchInterceptorPlugin = class {
942
996
  constructor() {
@@ -1077,6 +1131,7 @@ exports.getCookie = getCookie;
1077
1131
  exports.getTimeUntilExpiry = getTimeUntilExpiry;
1078
1132
  exports.getTokenExpiry = getTokenExpiry;
1079
1133
  exports.isStorageAvailable = isStorageAvailable;
1134
+ exports.isStoredTokens = isStoredTokens;
1080
1135
  exports.isTokenExpired = isTokenExpired;
1081
1136
  exports.isValidJwtFormat = isValidJwtFormat;
1082
1137
  exports.parseCookies = parseCookies;
@@ -1087,5 +1142,5 @@ exports.safeSetItem = safeSetItem;
1087
1142
  exports.serializeCookie = serializeCookie;
1088
1143
  exports.setCookie = setCookie;
1089
1144
  exports.stringToBase64Url = stringToBase64Url;
1090
- //# sourceMappingURL=chunk-47JWRVTL.cjs.map
1091
- //# sourceMappingURL=chunk-47JWRVTL.cjs.map
1145
+ //# sourceMappingURL=chunk-SI7KITBT.cjs.map
1146
+ //# sourceMappingURL=chunk-SI7KITBT.cjs.map