@oxog/authkeeper 1.0.0 → 1.2.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.
@@ -0,0 +1,1004 @@
1
+ // src/types.ts
2
+ var AuthError = class _AuthError extends Error {
3
+ constructor(code, message, options) {
4
+ super(message);
5
+ this.name = "AuthError";
6
+ this.code = code;
7
+ this.context = options?.context;
8
+ this.cause = options?.cause;
9
+ if (Error.captureStackTrace) {
10
+ Error.captureStackTrace(this, _AuthError);
11
+ }
12
+ }
13
+ };
14
+
15
+ // src/utils/base64.ts
16
+ function base64UrlEncode(buffer) {
17
+ let binary = "";
18
+ for (const byte of buffer) {
19
+ binary += String.fromCharCode(byte);
20
+ }
21
+ const base64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(binary, "binary").toString("base64");
22
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
23
+ }
24
+ function base64UrlDecode(str) {
25
+ let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
26
+ const pad = str.length % 4;
27
+ if (pad === 2) {
28
+ base64 += "==";
29
+ } else if (pad === 3) {
30
+ base64 += "=";
31
+ }
32
+ const binary = decodeBase64ToBinary(base64);
33
+ return decodeURIComponent(
34
+ binary.split("").map((c) => {
35
+ return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
36
+ }).join("")
37
+ );
38
+ }
39
+ function stringToBase64Url(str) {
40
+ const utf8Bytes = new TextEncoder().encode(str);
41
+ return base64UrlEncode(utf8Bytes);
42
+ }
43
+ function base64UrlDecodeToBytes(str) {
44
+ let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
45
+ const pad = str.length % 4;
46
+ if (pad === 2) {
47
+ base64 += "==";
48
+ } else if (pad === 3) {
49
+ base64 += "=";
50
+ }
51
+ const binary = decodeBase64ToBinary(base64);
52
+ const bytes = new Uint8Array(binary.length);
53
+ for (let i = 0; i < binary.length; i++) {
54
+ bytes[i] = binary.charCodeAt(i);
55
+ }
56
+ return bytes;
57
+ }
58
+ function decodeBase64ToBinary(base64) {
59
+ return typeof atob === "function" ? atob(base64) : Buffer.from(base64, "base64").toString("binary");
60
+ }
61
+
62
+ // src/utils/jwt.ts
63
+ function decodeJwt(token) {
64
+ const parts = token.split(".");
65
+ const [headerPart, payloadPart] = parts;
66
+ if (parts.length !== 3 || headerPart === void 0 || payloadPart === void 0) {
67
+ throw new AuthError("TOKEN_DECODE_FAILED", "Invalid JWT format: must have 3 parts", {
68
+ context: { parts: parts.length }
69
+ });
70
+ }
71
+ try {
72
+ const headerJson = base64UrlDecode(headerPart);
73
+ const header = JSON.parse(headerJson);
74
+ const payloadJson = base64UrlDecode(payloadPart);
75
+ const payload = JSON.parse(payloadJson);
76
+ return { header, payload };
77
+ } catch (error) {
78
+ throw new AuthError("TOKEN_DECODE_FAILED", "Failed to decode JWT", {
79
+ cause: error
80
+ });
81
+ }
82
+ }
83
+ function decodePayload(token) {
84
+ return decodeJwt(token).payload;
85
+ }
86
+ function decodeHeader(token) {
87
+ return decodeJwt(token).header;
88
+ }
89
+ function isValidJwtFormat(token) {
90
+ if (!token || typeof token !== "string") {
91
+ return false;
92
+ }
93
+ const parts = token.split(".");
94
+ if (parts.length !== 3) {
95
+ return false;
96
+ }
97
+ try {
98
+ for (const part of [parts[0], parts[1]]) {
99
+ if (!part || !/^[A-Za-z0-9_-]+$/.test(part)) {
100
+ return false;
101
+ }
102
+ const value = JSON.parse(base64UrlDecode(part));
103
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
104
+ return false;
105
+ }
106
+ }
107
+ return true;
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+ function getTokenExpiry(token) {
113
+ try {
114
+ const payload = decodePayload(token);
115
+ if (payload.exp) {
116
+ return new Date(payload.exp * 1e3);
117
+ }
118
+ return null;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+ function isTokenExpired(token, bufferSeconds = 0) {
124
+ const expiry = getTokenExpiry(token);
125
+ if (!expiry) {
126
+ return false;
127
+ }
128
+ const now = Date.now();
129
+ const expiryTime = expiry.getTime() - bufferSeconds * 1e3;
130
+ return now >= expiryTime;
131
+ }
132
+ function getTimeUntilExpiry(token) {
133
+ const expiry = getTokenExpiry(token);
134
+ if (!expiry) {
135
+ return null;
136
+ }
137
+ const now = Date.now();
138
+ const timeUntil = expiry.getTime() - now;
139
+ return Math.max(0, timeUntil);
140
+ }
141
+ function getClaim(token, claim) {
142
+ try {
143
+ const payload = decodePayload(token);
144
+ return payload[claim];
145
+ } catch {
146
+ return void 0;
147
+ }
148
+ }
149
+ function getClaims(token, claims) {
150
+ try {
151
+ const payload = decodePayload(token);
152
+ const result = {};
153
+ for (const claim of claims) {
154
+ if (claim in payload) {
155
+ result[claim] = payload[claim];
156
+ }
157
+ }
158
+ return result;
159
+ } catch {
160
+ return {};
161
+ }
162
+ }
163
+
164
+ // src/plugins/core/token-store.ts
165
+ var TokenStorePlugin = class {
166
+ constructor(options = {}) {
167
+ this.name = "token-store";
168
+ this.version = "1.0.0";
169
+ this.type = "core";
170
+ this.tokens = null;
171
+ this.kernel = null;
172
+ this.options = options;
173
+ }
174
+ install(kernel) {
175
+ this.kernel = kernel;
176
+ this.restore();
177
+ return {
178
+ set: this.set.bind(this),
179
+ get: this.get.bind(this),
180
+ clear: this.clear.bind(this),
181
+ getAccessToken: () => this.tokens?.accessToken || null,
182
+ getRefreshToken: () => this.tokens?.refreshToken || null,
183
+ getTokenType: () => this.tokens?.tokenType || "Bearer",
184
+ getExpiresAt: () => {
185
+ if (this.tokens?.expiresAt == null) return null;
186
+ return new Date(this.tokens.expiresAt);
187
+ },
188
+ getExpiresIn: () => {
189
+ if (this.tokens?.expiresAt == null) return null;
190
+ const now = Date.now();
191
+ const timeUntil = this.tokens.expiresAt - now;
192
+ return Math.max(0, timeUntil);
193
+ },
194
+ isExpired: () => {
195
+ if (this.tokens?.expiresAt == null) return false;
196
+ return Date.now() >= this.tokens.expiresAt;
197
+ },
198
+ getSetAt: () => {
199
+ if (!this.tokens?.setAt) return null;
200
+ return new Date(this.tokens.setAt);
201
+ },
202
+ getRefreshCount: () => this.tokens?.refreshCount || 0
203
+ };
204
+ }
205
+ /**
206
+ * Set tokens
207
+ */
208
+ set(tokens) {
209
+ if (typeof tokens?.accessToken !== "string" || tokens.accessToken === "") {
210
+ throw new AuthError("TOKEN_INVALID", "accessToken must be a non-empty string");
211
+ }
212
+ if (this.options.validateOnSet && !isValidJwtFormat(tokens.accessToken)) {
213
+ throw new AuthError("TOKEN_INVALID", "accessToken is not a valid JWT");
214
+ }
215
+ let expiresAt = null;
216
+ if (isFiniteNumber(tokens.expiresAt)) {
217
+ expiresAt = tokens.expiresAt * 1e3;
218
+ } else if (isFiniteNumber(tokens.expiresIn)) {
219
+ expiresAt = Date.now() + tokens.expiresIn * 1e3;
220
+ } else {
221
+ expiresAt = getTokenExpiry(tokens.accessToken)?.getTime() ?? null;
222
+ }
223
+ const refreshCount = this.tokens ? this.tokens.refreshCount + 1 : 1;
224
+ this.tokens = {
225
+ accessToken: tokens.accessToken,
226
+ refreshToken: tokens.refreshToken || null,
227
+ tokenType: tokens.tokenType || "Bearer",
228
+ expiresAt,
229
+ setAt: Date.now(),
230
+ refreshCount
231
+ };
232
+ this.persist(this.tokens);
233
+ if (this.options.onSet) {
234
+ this.options.onSet(this.tokens);
235
+ }
236
+ }
237
+ /**
238
+ * Get tokens
239
+ */
240
+ get() {
241
+ return this.tokens;
242
+ }
243
+ /**
244
+ * Clear tokens
245
+ */
246
+ clear() {
247
+ this.tokens = null;
248
+ this.persist(null);
249
+ if (this.options.onClear) {
250
+ this.options.onClear();
251
+ }
252
+ }
253
+ /**
254
+ * Uninstall plugin
255
+ *
256
+ * Drops the in-memory copy only: destroying an instance (e.g. on component
257
+ * unmount) must not log the user out of the persisted session.
258
+ */
259
+ uninstall() {
260
+ this.tokens = null;
261
+ this.kernel = null;
262
+ }
263
+ get storageKey() {
264
+ return this.options.storageKey ?? "tokens";
265
+ }
266
+ /**
267
+ * Write tokens to the storage adapter (null removes them).
268
+ * Failures (quota exceeded, storage disabled, ...) are reported as an
269
+ * 'error' event with context 'storage' instead of breaking setTokens().
270
+ */
271
+ persist(tokens) {
272
+ const storage = this.options.storage;
273
+ if (!storage) return;
274
+ try {
275
+ if (tokens) {
276
+ storage.set(this.storageKey, JSON.stringify(tokens));
277
+ } else {
278
+ storage.remove(this.storageKey);
279
+ }
280
+ } catch (error) {
281
+ this.reportStorageError("Failed to persist tokens", error);
282
+ }
283
+ }
284
+ /**
285
+ * Load tokens from the storage adapter. Corrupt or malformed entries are
286
+ * removed rather than trusted.
287
+ */
288
+ restore() {
289
+ const storage = this.options.storage;
290
+ if (!storage) return;
291
+ let raw;
292
+ try {
293
+ raw = storage.get(this.storageKey);
294
+ } catch (error) {
295
+ this.reportStorageError("Failed to read persisted tokens", error);
296
+ return;
297
+ }
298
+ if (raw == null) return;
299
+ let parsed;
300
+ try {
301
+ parsed = JSON.parse(raw);
302
+ } catch {
303
+ parsed = null;
304
+ }
305
+ if (isStoredTokens(parsed)) {
306
+ this.tokens = parsed;
307
+ return;
308
+ }
309
+ try {
310
+ storage.remove(this.storageKey);
311
+ } catch {
312
+ }
313
+ this.reportStorageError("Discarded malformed persisted tokens");
314
+ }
315
+ reportStorageError(message, cause) {
316
+ const error = new AuthError("STORAGE_ERROR", message, {
317
+ cause: cause === void 0 ? void 0 : cause instanceof Error ? cause : new Error(String(cause))
318
+ });
319
+ if (this.kernel && typeof this.kernel.emit === "function") {
320
+ this.kernel.emit({ type: "error", error, context: "storage", timestamp: Date.now() });
321
+ }
322
+ }
323
+ };
324
+ function isStoredTokens(value) {
325
+ if (value === null || typeof value !== "object") return false;
326
+ const v = value;
327
+ 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"]);
328
+ }
329
+ function isFiniteNumber(value) {
330
+ return typeof value === "number" && Number.isFinite(value);
331
+ }
332
+ function createTokenStorePlugin(options) {
333
+ return new TokenStorePlugin(options);
334
+ }
335
+
336
+ // src/plugins/core/token-decoder.ts
337
+ var TokenDecoderPlugin = class {
338
+ constructor() {
339
+ this.name = "token-decoder";
340
+ this.version = "1.0.0";
341
+ this.type = "core";
342
+ }
343
+ install(kernel) {
344
+ this.kernel = kernel;
345
+ return {
346
+ decode: this.decode.bind(this),
347
+ getHeader: this.getHeader.bind(this),
348
+ getClaim: this.getClaimFromToken.bind(this),
349
+ getClaims: this.getClaimsFromToken.bind(this),
350
+ getExpiry: this.getExpiry.bind(this),
351
+ isExpired: this.isExpiredToken.bind(this),
352
+ getTokenInfo: this.getTokenInfo.bind(this)
353
+ };
354
+ }
355
+ /**
356
+ * Decode token payload
357
+ */
358
+ decode(token) {
359
+ const jwt = token || this.kernel.getAccessToken();
360
+ if (!jwt) {
361
+ return null;
362
+ }
363
+ try {
364
+ return decodePayload(jwt);
365
+ } catch {
366
+ return null;
367
+ }
368
+ }
369
+ /**
370
+ * Decode token header
371
+ */
372
+ getHeader(token) {
373
+ const jwt = token || this.kernel.getAccessToken();
374
+ if (!jwt) {
375
+ return null;
376
+ }
377
+ try {
378
+ return decodeHeader(jwt);
379
+ } catch {
380
+ return null;
381
+ }
382
+ }
383
+ /**
384
+ * Get specific claim from token
385
+ */
386
+ getClaimFromToken(key, token) {
387
+ const jwt = token || this.kernel.getAccessToken();
388
+ if (!jwt) {
389
+ return void 0;
390
+ }
391
+ return getClaim(jwt, key);
392
+ }
393
+ /**
394
+ * Get multiple claims from token
395
+ */
396
+ getClaimsFromToken(keys, token) {
397
+ const jwt = token || this.kernel.getAccessToken();
398
+ if (!jwt) {
399
+ return {};
400
+ }
401
+ return getClaims(jwt, keys);
402
+ }
403
+ /**
404
+ * Get token expiry
405
+ */
406
+ getExpiry(token) {
407
+ const jwt = token || this.kernel.getAccessToken();
408
+ if (!jwt) {
409
+ return null;
410
+ }
411
+ return getTokenExpiry(jwt);
412
+ }
413
+ /**
414
+ * Check if token is expired
415
+ */
416
+ isExpiredToken(token) {
417
+ const jwt = token || this.kernel.getAccessToken();
418
+ if (!jwt) {
419
+ return true;
420
+ }
421
+ return isTokenExpired(jwt);
422
+ }
423
+ /**
424
+ * Get complete token information
425
+ */
426
+ getTokenInfo(token) {
427
+ const jwt = token || this.kernel.getAccessToken();
428
+ if (!jwt) {
429
+ return null;
430
+ }
431
+ try {
432
+ const { header, payload } = decodeJwt(jwt);
433
+ const expiresAt = getTokenExpiry(jwt);
434
+ const isExpired = isTokenExpired(jwt);
435
+ const expiresIn = getTimeUntilExpiry(jwt);
436
+ return {
437
+ raw: jwt,
438
+ header,
439
+ payload,
440
+ expiresAt,
441
+ isExpired,
442
+ expiresIn
443
+ };
444
+ } catch {
445
+ return null;
446
+ }
447
+ }
448
+ uninstall() {
449
+ }
450
+ };
451
+ function createTokenDecoderPlugin() {
452
+ return new TokenDecoderPlugin();
453
+ }
454
+
455
+ // src/plugins/core/refresh-engine.ts
456
+ var MIN_REFRESH_INTERVAL = 1e3;
457
+ var SupersededRefreshError = class extends Error {
458
+ };
459
+ var RefreshEnginePlugin = class {
460
+ constructor(options) {
461
+ this.name = "refresh-engine";
462
+ this.version = "1.0.0";
463
+ this.type = "core";
464
+ this.isRefreshingFlag = false;
465
+ this.applyingRefresh = false;
466
+ this.refreshPromise = null;
467
+ this.scheduledRefreshTimeout = null;
468
+ this.options = options;
469
+ this.refreshFn = options.refreshFn;
470
+ this.threshold = options.threshold ?? 60;
471
+ this.maxRetries = options.maxRetries ?? 3;
472
+ this.retryDelay = options.retryDelay ?? 1e3;
473
+ }
474
+ install(kernel) {
475
+ this.kernel = kernel;
476
+ return {
477
+ refresh: this.refresh.bind(this),
478
+ scheduleRefresh: this.scheduleRefresh.bind(this),
479
+ cancelScheduledRefresh: this.cancelScheduledRefresh.bind(this),
480
+ isRefreshing: () => this.isRefreshingFlag,
481
+ isApplyingRefresh: () => this.applyingRefresh,
482
+ getNextRefreshAt: this.getNextRefreshAt.bind(this),
483
+ setRefreshFn: (fn) => {
484
+ this.refreshFn = fn;
485
+ },
486
+ setThreshold: (seconds) => {
487
+ this.threshold = seconds;
488
+ }
489
+ };
490
+ }
491
+ /**
492
+ * Refresh tokens
493
+ *
494
+ * Queues concurrent requests - only one refresh executes at a time.
495
+ */
496
+ async refresh() {
497
+ if (this.refreshPromise) {
498
+ return this.refreshPromise;
499
+ }
500
+ this.isRefreshingFlag = true;
501
+ this.refreshPromise = this.executeRefresh();
502
+ try {
503
+ const tokens = await this.refreshPromise;
504
+ return tokens;
505
+ } finally {
506
+ this.isRefreshingFlag = false;
507
+ this.refreshPromise = null;
508
+ }
509
+ }
510
+ /**
511
+ * Execute token refresh with retry logic
512
+ */
513
+ async executeRefresh(retryCount = 0) {
514
+ if (this.options.onRefreshStart) {
515
+ this.options.onRefreshStart();
516
+ }
517
+ const refreshToken = this.kernel.getRefreshToken();
518
+ if (!refreshToken) {
519
+ const error = new AuthError("REFRESH_TOKEN_MISSING", "No refresh token available");
520
+ this.kernel.emit({
521
+ type: "error",
522
+ error,
523
+ context: "refresh",
524
+ timestamp: Date.now()
525
+ });
526
+ throw error;
527
+ }
528
+ try {
529
+ const previousExpiresAt = this.kernel.getExpiresAt();
530
+ const newTokens = await this.refreshFn(refreshToken);
531
+ if (this.kernel.getRefreshToken() !== refreshToken) {
532
+ throw new SupersededRefreshError();
533
+ }
534
+ this.applyingRefresh = true;
535
+ try {
536
+ this.kernel.setTokens(newTokens);
537
+ } finally {
538
+ this.applyingRefresh = false;
539
+ }
540
+ const newExpiresAt = this.kernel.getExpiresAt();
541
+ this.kernel.emit({
542
+ type: "refresh",
543
+ tokens: newTokens,
544
+ previousExpiresAt,
545
+ newExpiresAt,
546
+ timestamp: Date.now()
547
+ });
548
+ if (this.options.onRefreshSuccess) {
549
+ this.options.onRefreshSuccess(newTokens);
550
+ }
551
+ if (this.isAutoRefreshEnabled()) {
552
+ this.scheduleRefresh();
553
+ }
554
+ return newTokens;
555
+ } catch (error) {
556
+ if (error instanceof SupersededRefreshError) {
557
+ throw new AuthError(
558
+ "REFRESH_FAILED",
559
+ "Session changed while refreshing (logout or new login); refresh result discarded",
560
+ { context: { superseded: true } }
561
+ );
562
+ }
563
+ if (retryCount < this.maxRetries) {
564
+ const delay = this.retryDelay * Math.pow(2, retryCount);
565
+ await new Promise((resolve) => setTimeout(resolve, delay));
566
+ return this.executeRefresh(retryCount + 1);
567
+ }
568
+ const authError = new AuthError("REFRESH_FAILED", "Token refresh failed", {
569
+ cause: error instanceof Error ? error : new Error(String(error)),
570
+ context: { retryCount }
571
+ });
572
+ this.kernel.emit({
573
+ type: "error",
574
+ error: authError,
575
+ context: "refresh",
576
+ timestamp: Date.now()
577
+ });
578
+ if (this.options.onRefreshError) {
579
+ this.options.onRefreshError(authError);
580
+ }
581
+ throw authError;
582
+ }
583
+ }
584
+ /**
585
+ * Schedule automatic refresh
586
+ *
587
+ * Schedules refresh before token expires (threshold seconds before).
588
+ */
589
+ scheduleRefresh() {
590
+ this.cancelScheduledRefresh();
591
+ const expiresIn = this.kernel.getTimeUntilExpiry();
592
+ if (!expiresIn) {
593
+ return;
594
+ }
595
+ let refreshIn = expiresIn - this.threshold * 1e3;
596
+ if (refreshIn <= 0) {
597
+ if (!this.refreshPromise) {
598
+ this.refresh().catch((error) => {
599
+ console.error("[AuthKeeper] Immediate refresh failed:", error);
600
+ });
601
+ return;
602
+ }
603
+ refreshIn = Math.max(Math.floor(expiresIn / 2), MIN_REFRESH_INTERVAL);
604
+ }
605
+ this.scheduledRefreshTimeout = setTimeout(() => {
606
+ this.scheduledRefreshTimeout = null;
607
+ this.refresh().catch((error) => {
608
+ console.error("[AuthKeeper] Scheduled refresh failed:", error);
609
+ });
610
+ }, refreshIn);
611
+ }
612
+ /**
613
+ * Whether the kernel has automatic refresh enabled (default: true)
614
+ */
615
+ isAutoRefreshEnabled() {
616
+ if (typeof this.kernel.getOptions !== "function") {
617
+ return true;
618
+ }
619
+ return this.kernel.getOptions().autoRefresh !== false;
620
+ }
621
+ /**
622
+ * Cancel scheduled refresh
623
+ */
624
+ cancelScheduledRefresh() {
625
+ if (this.scheduledRefreshTimeout) {
626
+ clearTimeout(this.scheduledRefreshTimeout);
627
+ this.scheduledRefreshTimeout = null;
628
+ }
629
+ }
630
+ /**
631
+ * Get next scheduled refresh time
632
+ */
633
+ getNextRefreshAt() {
634
+ const expiresAt = this.kernel.getExpiresAt();
635
+ if (!expiresAt) {
636
+ return null;
637
+ }
638
+ const refreshAt = new Date(expiresAt.getTime() - this.threshold * 1e3);
639
+ return refreshAt;
640
+ }
641
+ /**
642
+ * Uninstall plugin
643
+ */
644
+ uninstall() {
645
+ this.cancelScheduledRefresh();
646
+ }
647
+ };
648
+ function createRefreshEnginePlugin(options) {
649
+ return new RefreshEnginePlugin(options);
650
+ }
651
+
652
+ // src/plugins/core/storage-memory.ts
653
+ var MemoryStorageAdapter = class {
654
+ constructor(options = {}) {
655
+ this.store = /* @__PURE__ */ new Map();
656
+ this.prefix = options.prefix || "authkeeper:";
657
+ }
658
+ /**
659
+ * Get value by key
660
+ */
661
+ get(key) {
662
+ return this.store.get(this.prefix + key) || null;
663
+ }
664
+ /**
665
+ * Set value by key
666
+ */
667
+ set(key, value) {
668
+ this.store.set(this.prefix + key, value);
669
+ }
670
+ /**
671
+ * Remove value by key
672
+ */
673
+ remove(key) {
674
+ this.store.delete(this.prefix + key);
675
+ }
676
+ /**
677
+ * Clear all values
678
+ */
679
+ clear() {
680
+ const keysToDelete = [];
681
+ for (const key of this.store.keys()) {
682
+ if (key.startsWith(this.prefix)) {
683
+ keysToDelete.push(key);
684
+ }
685
+ }
686
+ keysToDelete.forEach((key) => this.store.delete(key));
687
+ }
688
+ };
689
+ function createMemoryStorage(options) {
690
+ return new MemoryStorageAdapter(options);
691
+ }
692
+
693
+ // src/utils/cookie.ts
694
+ function parseCookies(cookieString) {
695
+ const cookies = {};
696
+ if (!cookieString) {
697
+ return cookies;
698
+ }
699
+ cookieString.split(";").forEach((cookie) => {
700
+ const [key, ...valueParts] = cookie.split("=");
701
+ const trimmedKey = key?.trim();
702
+ const value = valueParts.join("=").trim();
703
+ if (trimmedKey) {
704
+ cookies[safeDecode(trimmedKey)] = safeDecode(value);
705
+ }
706
+ });
707
+ return cookies;
708
+ }
709
+ function safeDecode(value) {
710
+ try {
711
+ return decodeURIComponent(value);
712
+ } catch {
713
+ return value;
714
+ }
715
+ }
716
+ var INVALID_ATTRIBUTE_VALUE = /[;\r\n\0]/;
717
+ function assertAttributeValue(name, value) {
718
+ if (INVALID_ATTRIBUTE_VALUE.test(value)) {
719
+ throw new TypeError(`Invalid cookie ${name}: must not contain ';', CR, LF or NUL`);
720
+ }
721
+ }
722
+ function getCookie(name) {
723
+ if (typeof document === "undefined") {
724
+ return null;
725
+ }
726
+ const cookies = parseCookies(document.cookie);
727
+ return cookies[name] || null;
728
+ }
729
+ function serializeCookie(name, value, attributes = {}) {
730
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
731
+ if (attributes.path) {
732
+ assertAttributeValue("path", attributes.path);
733
+ cookie += `; Path=${attributes.path}`;
734
+ }
735
+ if (attributes.domain) {
736
+ assertAttributeValue("domain", attributes.domain);
737
+ cookie += `; Domain=${attributes.domain}`;
738
+ }
739
+ if (attributes.maxAge !== void 0) {
740
+ cookie += `; Max-Age=${attributes.maxAge}`;
741
+ }
742
+ if (attributes.expires) {
743
+ cookie += `; Expires=${attributes.expires.toUTCString()}`;
744
+ }
745
+ if (attributes.secure || attributes.sameSite === "none") {
746
+ cookie += "; Secure";
747
+ }
748
+ if (attributes.sameSite) {
749
+ const sameSite = attributes.sameSite.charAt(0).toUpperCase() + attributes.sameSite.slice(1);
750
+ cookie += `; SameSite=${sameSite}`;
751
+ }
752
+ if (attributes.httpOnly) {
753
+ cookie += "; HttpOnly";
754
+ }
755
+ return cookie;
756
+ }
757
+ function setCookie(name, value, attributes = {}) {
758
+ if (typeof document === "undefined") {
759
+ return;
760
+ }
761
+ document.cookie = serializeCookie(name, value, attributes);
762
+ }
763
+ function deleteCookie(name, attributes = {}) {
764
+ if (typeof document === "undefined") {
765
+ return;
766
+ }
767
+ document.cookie = serializeCookie(name, "", {
768
+ ...attributes,
769
+ expires: /* @__PURE__ */ new Date(0)
770
+ });
771
+ }
772
+
773
+ // src/utils/storage.ts
774
+ function isStorageAvailable(storage) {
775
+ if (!storage) {
776
+ return false;
777
+ }
778
+ try {
779
+ const testKey = "__storage_test__";
780
+ storage.setItem(testKey, "test");
781
+ storage.removeItem(testKey);
782
+ return true;
783
+ } catch {
784
+ return false;
785
+ }
786
+ }
787
+ function safeGetItem(storage, key) {
788
+ try {
789
+ return storage.get(key);
790
+ } catch {
791
+ return null;
792
+ }
793
+ }
794
+ function safeSetItem(storage, key, value) {
795
+ try {
796
+ storage.set(key, value);
797
+ return true;
798
+ } catch {
799
+ return false;
800
+ }
801
+ }
802
+ function safeRemoveItem(storage, key) {
803
+ try {
804
+ storage.remove(key);
805
+ return true;
806
+ } catch {
807
+ return false;
808
+ }
809
+ }
810
+
811
+ // src/plugins/core/storage-web.ts
812
+ var WebStorageAdapter = class {
813
+ constructor(storage, options = {}) {
814
+ this.storage = storage;
815
+ this.prefix = options.prefix ?? "authkeeper:";
816
+ }
817
+ get(key) {
818
+ return this.storage.getItem(this.prefix + key);
819
+ }
820
+ set(key, value) {
821
+ this.storage.setItem(this.prefix + key, value);
822
+ }
823
+ remove(key) {
824
+ this.storage.removeItem(this.prefix + key);
825
+ }
826
+ clear() {
827
+ const keys = [];
828
+ for (let i = 0; i < this.storage.length; i++) {
829
+ const key = this.storage.key(i);
830
+ if (key !== null && key.startsWith(this.prefix)) {
831
+ keys.push(key);
832
+ }
833
+ }
834
+ keys.forEach((key) => this.storage.removeItem(key));
835
+ }
836
+ };
837
+ var CookieStorageAdapter = class {
838
+ constructor(options = {}) {
839
+ this.keys = /* @__PURE__ */ new Set();
840
+ this.prefix = options.prefix ?? "authkeeper_";
841
+ this.attributes = { path: "/", secure: true, sameSite: "strict", ...options.attributes };
842
+ }
843
+ get(key) {
844
+ return getCookie(this.prefix + key);
845
+ }
846
+ set(key, value) {
847
+ setCookie(this.prefix + key, value, this.attributes);
848
+ this.keys.add(key);
849
+ if (typeof document !== "undefined" && this.get(key) !== value) {
850
+ throw new AuthError("STORAGE_ERROR", `Cookie "${this.prefix + key}" was not stored (too large or blocked)`);
851
+ }
852
+ }
853
+ remove(key) {
854
+ const { path, domain, secure, sameSite } = this.attributes;
855
+ deleteCookie(this.prefix + key, { path, domain, secure, sameSite });
856
+ this.keys.delete(key);
857
+ }
858
+ clear() {
859
+ Array.from(this.keys).forEach((key) => this.remove(key));
860
+ }
861
+ };
862
+ function getWebStorage(type) {
863
+ try {
864
+ return typeof window !== "undefined" ? window[type] : void 0;
865
+ } catch {
866
+ return void 0;
867
+ }
868
+ }
869
+ function resolveStorage(storage) {
870
+ if (storage === void 0 || storage === "memory") {
871
+ return void 0;
872
+ }
873
+ if (typeof storage === "object" && storage !== null) {
874
+ return storage;
875
+ }
876
+ switch (storage) {
877
+ case "localStorage":
878
+ case "sessionStorage": {
879
+ const webStorage = getWebStorage(storage);
880
+ return webStorage && isStorageAvailable(webStorage) ? new WebStorageAdapter(webStorage) : createMemoryStorage();
881
+ }
882
+ case "cookie":
883
+ return typeof document !== "undefined" ? new CookieStorageAdapter() : createMemoryStorage();
884
+ default:
885
+ throw new AuthError("CONFIG_ERROR", `Unknown storage type: ${String(storage)}`, {
886
+ context: { storage }
887
+ });
888
+ }
889
+ }
890
+
891
+ // src/plugins/core/fetch-interceptor.ts
892
+ var FetchInterceptorPlugin = class {
893
+ constructor() {
894
+ this.name = "fetch-interceptor";
895
+ this.version = "1.0.0";
896
+ this.type = "core";
897
+ this.originalFetch = null;
898
+ }
899
+ /**
900
+ * The fetch implementation used to perform requests.
901
+ *
902
+ * While the global fetch is wrapped, this is the original (unwrapped)
903
+ * fetch; calling `globalThis.fetch` from inside the wrapper would recurse
904
+ * into the wrapper itself.
905
+ */
906
+ baseFetch(input, init) {
907
+ const impl = this.originalFetch ?? globalThis.fetch;
908
+ return impl(input, init);
909
+ }
910
+ install(kernel) {
911
+ this.kernel = kernel;
912
+ return {
913
+ createFetch: this.createFetch.bind(this),
914
+ wrapFetch: this.wrapFetch.bind(this),
915
+ unwrapFetch: this.unwrapFetch.bind(this)
916
+ };
917
+ }
918
+ /**
919
+ * Create authenticated fetch function
920
+ */
921
+ createFetch(options = {}) {
922
+ const {
923
+ headerName = "Authorization",
924
+ headerPrefix = "Bearer ",
925
+ includeUrls = [],
926
+ excludeUrls = [],
927
+ retry401 = true,
928
+ maxRetries = 1,
929
+ onUnauthorized
930
+ } = options;
931
+ return async (input, init) => {
932
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
933
+ const urlWithoutQuery = url.replace(/[?#][\s\S]*$/, "");
934
+ const matches = (pattern) => typeof pattern === "string" ? urlWithoutQuery.includes(pattern) : pattern.test(url);
935
+ const shouldInclude = includeUrls.length === 0 || includeUrls.some(matches);
936
+ const shouldExclude = excludeUrls.some(matches);
937
+ if (!shouldInclude || shouldExclude) {
938
+ return this.baseFetch(input, init);
939
+ }
940
+ const isRequest = typeof Request !== "undefined" && input instanceof Request;
941
+ const canRetry = retry401 && maxRetries > 0;
942
+ const pristineRequest = canRetry && isRequest ? input.clone() : null;
943
+ const accessToken = this.kernel.getAccessToken();
944
+ const headers = new Headers(init?.headers ?? (isRequest ? input.headers : void 0));
945
+ if (accessToken) {
946
+ headers.set(headerName, headerPrefix + accessToken);
947
+ }
948
+ let response = await this.baseFetch(input, {
949
+ ...init,
950
+ headers
951
+ });
952
+ for (let attempt = 0; canRetry && response.status === 401 && attempt < maxRetries; attempt++) {
953
+ if (onUnauthorized) {
954
+ onUnauthorized(response);
955
+ }
956
+ try {
957
+ await this.kernel.refresh();
958
+ } catch (error) {
959
+ console.error("[AuthKeeper] Token refresh failed during 401 retry:", error);
960
+ break;
961
+ }
962
+ const newToken = this.kernel.getAccessToken();
963
+ if (!newToken) {
964
+ break;
965
+ }
966
+ headers.set(headerName, headerPrefix + newToken);
967
+ response = await this.baseFetch(pristineRequest ? pristineRequest.clone() : input, {
968
+ ...init,
969
+ headers
970
+ });
971
+ }
972
+ return response;
973
+ };
974
+ }
975
+ /**
976
+ * Wrap global fetch with auth
977
+ */
978
+ wrapFetch(fetch) {
979
+ if (!this.originalFetch) {
980
+ this.originalFetch = fetch;
981
+ }
982
+ const authFetch = this.createFetch();
983
+ globalThis.fetch = authFetch;
984
+ }
985
+ /**
986
+ * Restore original fetch
987
+ */
988
+ unwrapFetch() {
989
+ if (this.originalFetch) {
990
+ globalThis.fetch = this.originalFetch;
991
+ this.originalFetch = null;
992
+ }
993
+ }
994
+ uninstall() {
995
+ this.unwrapFetch();
996
+ }
997
+ };
998
+ function createFetchInterceptorPlugin() {
999
+ return new FetchInterceptorPlugin();
1000
+ }
1001
+
1002
+ export { AuthError, CookieStorageAdapter, FetchInterceptorPlugin, MemoryStorageAdapter, RefreshEnginePlugin, TokenDecoderPlugin, TokenStorePlugin, WebStorageAdapter, base64UrlDecode, base64UrlDecodeToBytes, base64UrlEncode, createFetchInterceptorPlugin, createMemoryStorage, createRefreshEnginePlugin, createTokenDecoderPlugin, createTokenStorePlugin, decodeHeader, decodeJwt, decodePayload, deleteCookie, getClaim, getClaims, getCookie, getTimeUntilExpiry, getTokenExpiry, isStorageAvailable, isTokenExpired, isValidJwtFormat, parseCookies, resolveStorage, safeGetItem, safeRemoveItem, safeSetItem, serializeCookie, setCookie, stringToBase64Url };
1003
+ //# sourceMappingURL=chunk-5GAJ7NPE.js.map
1004
+ //# sourceMappingURL=chunk-5GAJ7NPE.js.map