@oxog/authkeeper 1.0.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,621 @@
1
+ // src/plugins/core/token-store.ts
2
+ var TokenStorePlugin = class {
3
+ constructor(options = {}) {
4
+ this.name = "token-store";
5
+ this.version = "1.0.0";
6
+ this.type = "core";
7
+ this.tokens = null;
8
+ this.options = options;
9
+ }
10
+ install(_kernel) {
11
+ return {
12
+ set: this.set.bind(this),
13
+ get: this.get.bind(this),
14
+ clear: this.clear.bind(this),
15
+ getAccessToken: () => this.tokens?.accessToken || null,
16
+ getRefreshToken: () => this.tokens?.refreshToken || null,
17
+ getTokenType: () => this.tokens?.tokenType || "Bearer",
18
+ getExpiresAt: () => {
19
+ if (!this.tokens?.expiresAt) return null;
20
+ return new Date(this.tokens.expiresAt);
21
+ },
22
+ getExpiresIn: () => {
23
+ if (!this.tokens?.expiresAt) return null;
24
+ const now = Date.now();
25
+ const timeUntil = this.tokens.expiresAt - now;
26
+ return Math.max(0, timeUntil);
27
+ },
28
+ isExpired: () => {
29
+ if (!this.tokens?.expiresAt) return false;
30
+ return Date.now() >= this.tokens.expiresAt;
31
+ },
32
+ getSetAt: () => {
33
+ if (!this.tokens?.setAt) return null;
34
+ return new Date(this.tokens.setAt);
35
+ },
36
+ getRefreshCount: () => this.tokens?.refreshCount || 0
37
+ };
38
+ }
39
+ /**
40
+ * Set tokens
41
+ */
42
+ set(tokens) {
43
+ let expiresAt = null;
44
+ if (tokens.expiresAt) {
45
+ expiresAt = tokens.expiresAt * 1e3;
46
+ } else if (tokens.expiresIn) {
47
+ expiresAt = Date.now() + tokens.expiresIn * 1e3;
48
+ }
49
+ const refreshCount = this.tokens ? this.tokens.refreshCount + 1 : 1;
50
+ this.tokens = {
51
+ accessToken: tokens.accessToken,
52
+ refreshToken: tokens.refreshToken || null,
53
+ tokenType: tokens.tokenType || "Bearer",
54
+ expiresAt,
55
+ setAt: Date.now(),
56
+ refreshCount
57
+ };
58
+ if (this.options.onSet) {
59
+ this.options.onSet(this.tokens);
60
+ }
61
+ }
62
+ /**
63
+ * Get tokens
64
+ */
65
+ get() {
66
+ return this.tokens;
67
+ }
68
+ /**
69
+ * Clear tokens
70
+ */
71
+ clear() {
72
+ this.tokens = null;
73
+ if (this.options.onClear) {
74
+ this.options.onClear();
75
+ }
76
+ }
77
+ /**
78
+ * Uninstall plugin
79
+ */
80
+ uninstall() {
81
+ this.clear();
82
+ }
83
+ };
84
+ function createTokenStorePlugin(options) {
85
+ return new TokenStorePlugin(options);
86
+ }
87
+
88
+ // src/utils/base64.ts
89
+ function base64UrlDecode(str) {
90
+ let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
91
+ const pad = str.length % 4;
92
+ if (pad === 2) {
93
+ base64 += "==";
94
+ } else if (pad === 3) {
95
+ base64 += "=";
96
+ }
97
+ const binary = typeof window !== "undefined" ? atob(base64) : Buffer.from(base64, "base64").toString("binary");
98
+ return decodeURIComponent(
99
+ binary.split("").map((c) => {
100
+ return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
101
+ }).join("")
102
+ );
103
+ }
104
+
105
+ // src/types.ts
106
+ var AuthError = class _AuthError extends Error {
107
+ constructor(code, message, options) {
108
+ super(message);
109
+ this.name = "AuthError";
110
+ this.code = code;
111
+ this.context = options?.context;
112
+ this.cause = options?.cause;
113
+ if (Error.captureStackTrace) {
114
+ Error.captureStackTrace(this, _AuthError);
115
+ }
116
+ }
117
+ };
118
+
119
+ // src/utils/jwt.ts
120
+ function decodeJwt(token) {
121
+ const parts = token.split(".");
122
+ if (parts.length !== 3) {
123
+ throw new AuthError("TOKEN_DECODE_FAILED", "Invalid JWT format: must have 3 parts", {
124
+ context: { parts: parts.length }
125
+ });
126
+ }
127
+ try {
128
+ const headerJson = base64UrlDecode(parts[0]);
129
+ const header = JSON.parse(headerJson);
130
+ const payloadJson = base64UrlDecode(parts[1]);
131
+ const payload = JSON.parse(payloadJson);
132
+ return { header, payload };
133
+ } catch (error) {
134
+ throw new AuthError("TOKEN_DECODE_FAILED", "Failed to decode JWT", {
135
+ cause: error
136
+ });
137
+ }
138
+ }
139
+ function decodePayload(token) {
140
+ return decodeJwt(token).payload;
141
+ }
142
+ function decodeHeader(token) {
143
+ return decodeJwt(token).header;
144
+ }
145
+ function getTokenExpiry(token) {
146
+ try {
147
+ const payload = decodePayload(token);
148
+ if (payload.exp) {
149
+ return new Date(payload.exp * 1e3);
150
+ }
151
+ return null;
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
156
+ function isTokenExpired(token, bufferSeconds = 0) {
157
+ const expiry = getTokenExpiry(token);
158
+ if (!expiry) {
159
+ return false;
160
+ }
161
+ const now = Date.now();
162
+ const expiryTime = expiry.getTime() - bufferSeconds * 1e3;
163
+ return now >= expiryTime;
164
+ }
165
+ function getTimeUntilExpiry(token) {
166
+ const expiry = getTokenExpiry(token);
167
+ if (!expiry) {
168
+ return null;
169
+ }
170
+ const now = Date.now();
171
+ const timeUntil = expiry.getTime() - now;
172
+ return Math.max(0, timeUntil);
173
+ }
174
+ function getClaim(token, claim) {
175
+ try {
176
+ const payload = decodePayload(token);
177
+ return payload[claim];
178
+ } catch {
179
+ return void 0;
180
+ }
181
+ }
182
+ function getClaims(token, claims) {
183
+ try {
184
+ const payload = decodePayload(token);
185
+ const result = {};
186
+ for (const claim of claims) {
187
+ if (claim in payload) {
188
+ result[claim] = payload[claim];
189
+ }
190
+ }
191
+ return result;
192
+ } catch {
193
+ return {};
194
+ }
195
+ }
196
+
197
+ // src/plugins/core/token-decoder.ts
198
+ var TokenDecoderPlugin = class {
199
+ constructor() {
200
+ this.name = "token-decoder";
201
+ this.version = "1.0.0";
202
+ this.type = "core";
203
+ }
204
+ install(kernel) {
205
+ this.kernel = kernel;
206
+ return {
207
+ decode: this.decode.bind(this),
208
+ getHeader: this.getHeader.bind(this),
209
+ getClaim: this.getClaimFromToken.bind(this),
210
+ getClaims: this.getClaimsFromToken.bind(this),
211
+ getExpiry: this.getExpiry.bind(this),
212
+ isExpired: this.isExpiredToken.bind(this),
213
+ getTokenInfo: this.getTokenInfo.bind(this)
214
+ };
215
+ }
216
+ /**
217
+ * Decode token payload
218
+ */
219
+ decode(token) {
220
+ const jwt = token || this.kernel.getAccessToken();
221
+ if (!jwt) {
222
+ return null;
223
+ }
224
+ try {
225
+ return decodePayload(jwt);
226
+ } catch {
227
+ return null;
228
+ }
229
+ }
230
+ /**
231
+ * Decode token header
232
+ */
233
+ getHeader(token) {
234
+ const jwt = token || this.kernel.getAccessToken();
235
+ if (!jwt) {
236
+ return null;
237
+ }
238
+ try {
239
+ return decodeHeader(jwt);
240
+ } catch {
241
+ return null;
242
+ }
243
+ }
244
+ /**
245
+ * Get specific claim from token
246
+ */
247
+ getClaimFromToken(key, token) {
248
+ const jwt = token || this.kernel.getAccessToken();
249
+ if (!jwt) {
250
+ return void 0;
251
+ }
252
+ return getClaim(jwt, key);
253
+ }
254
+ /**
255
+ * Get multiple claims from token
256
+ */
257
+ getClaimsFromToken(keys, token) {
258
+ const jwt = token || this.kernel.getAccessToken();
259
+ if (!jwt) {
260
+ return {};
261
+ }
262
+ return getClaims(jwt, keys);
263
+ }
264
+ /**
265
+ * Get token expiry
266
+ */
267
+ getExpiry(token) {
268
+ const jwt = token || this.kernel.getAccessToken();
269
+ if (!jwt) {
270
+ return null;
271
+ }
272
+ return getTokenExpiry(jwt);
273
+ }
274
+ /**
275
+ * Check if token is expired
276
+ */
277
+ isExpiredToken(token) {
278
+ const jwt = token || this.kernel.getAccessToken();
279
+ if (!jwt) {
280
+ return true;
281
+ }
282
+ return isTokenExpired(jwt);
283
+ }
284
+ /**
285
+ * Get complete token information
286
+ */
287
+ getTokenInfo(token) {
288
+ const jwt = token || this.kernel.getAccessToken();
289
+ if (!jwt) {
290
+ return null;
291
+ }
292
+ try {
293
+ const { header, payload } = decodeJwt(jwt);
294
+ const expiresAt = getTokenExpiry(jwt);
295
+ const isExpired = isTokenExpired(jwt);
296
+ const expiresIn = getTimeUntilExpiry(jwt);
297
+ return {
298
+ raw: jwt,
299
+ header,
300
+ payload,
301
+ expiresAt,
302
+ isExpired,
303
+ expiresIn
304
+ };
305
+ } catch {
306
+ return null;
307
+ }
308
+ }
309
+ uninstall() {
310
+ }
311
+ };
312
+ function createTokenDecoderPlugin() {
313
+ return new TokenDecoderPlugin();
314
+ }
315
+
316
+ // src/plugins/core/refresh-engine.ts
317
+ var RefreshEnginePlugin = class {
318
+ constructor(options) {
319
+ this.name = "refresh-engine";
320
+ this.version = "1.0.0";
321
+ this.type = "core";
322
+ this.isRefreshingFlag = false;
323
+ this.refreshPromise = null;
324
+ this.scheduledRefreshTimeout = null;
325
+ this.options = options;
326
+ this.refreshFn = options.refreshFn;
327
+ this.threshold = options.threshold || 60;
328
+ this.maxRetries = options.maxRetries || 3;
329
+ this.retryDelay = options.retryDelay || 1e3;
330
+ }
331
+ install(kernel) {
332
+ this.kernel = kernel;
333
+ return {
334
+ refresh: this.refresh.bind(this),
335
+ scheduleRefresh: this.scheduleRefresh.bind(this),
336
+ cancelScheduledRefresh: this.cancelScheduledRefresh.bind(this),
337
+ isRefreshing: () => this.isRefreshingFlag,
338
+ getNextRefreshAt: this.getNextRefreshAt.bind(this),
339
+ setRefreshFn: (fn) => {
340
+ this.refreshFn = fn;
341
+ },
342
+ setThreshold: (seconds) => {
343
+ this.threshold = seconds;
344
+ }
345
+ };
346
+ }
347
+ /**
348
+ * Refresh tokens
349
+ *
350
+ * Queues concurrent requests - only one refresh executes at a time.
351
+ */
352
+ async refresh() {
353
+ if (this.refreshPromise) {
354
+ return this.refreshPromise;
355
+ }
356
+ this.isRefreshingFlag = true;
357
+ this.refreshPromise = this.executeRefresh();
358
+ try {
359
+ const tokens = await this.refreshPromise;
360
+ return tokens;
361
+ } finally {
362
+ this.isRefreshingFlag = false;
363
+ this.refreshPromise = null;
364
+ }
365
+ }
366
+ /**
367
+ * Execute token refresh with retry logic
368
+ */
369
+ async executeRefresh(retryCount = 0) {
370
+ if (this.options.onRefreshStart) {
371
+ this.options.onRefreshStart();
372
+ }
373
+ const refreshToken = this.kernel.getRefreshToken();
374
+ if (!refreshToken) {
375
+ const error = new Error("No refresh token available");
376
+ error.name = "AuthError";
377
+ error.code = "REFRESH_TOKEN_MISSING";
378
+ this.kernel.emit({
379
+ type: "error",
380
+ error,
381
+ context: "refresh",
382
+ timestamp: Date.now()
383
+ });
384
+ throw error;
385
+ }
386
+ try {
387
+ const previousExpiresAt = this.kernel.getExpiresAt();
388
+ const newTokens = await this.refreshFn(refreshToken);
389
+ this.kernel.setTokens(newTokens);
390
+ const newExpiresAt = this.kernel.getExpiresAt();
391
+ this.kernel.emit({
392
+ type: "refresh",
393
+ tokens: newTokens,
394
+ previousExpiresAt,
395
+ newExpiresAt,
396
+ timestamp: Date.now()
397
+ });
398
+ if (this.options.onRefreshSuccess) {
399
+ this.options.onRefreshSuccess(newTokens);
400
+ }
401
+ this.scheduleRefresh();
402
+ return newTokens;
403
+ } catch (error) {
404
+ if (retryCount < this.maxRetries) {
405
+ const delay = this.retryDelay * Math.pow(2, retryCount);
406
+ await new Promise((resolve) => setTimeout(resolve, delay));
407
+ return this.executeRefresh(retryCount + 1);
408
+ }
409
+ const authError = new Error("Token refresh failed");
410
+ authError.name = "AuthError";
411
+ authError.code = "REFRESH_FAILED";
412
+ authError.cause = error;
413
+ authError.context = { retryCount };
414
+ this.kernel.emit({
415
+ type: "error",
416
+ error: authError,
417
+ context: "refresh",
418
+ timestamp: Date.now()
419
+ });
420
+ if (this.options.onRefreshError) {
421
+ this.options.onRefreshError(authError);
422
+ }
423
+ throw authError;
424
+ }
425
+ }
426
+ /**
427
+ * Schedule automatic refresh
428
+ *
429
+ * Schedules refresh before token expires (threshold seconds before).
430
+ */
431
+ scheduleRefresh() {
432
+ this.cancelScheduledRefresh();
433
+ const expiresIn = this.kernel.getTimeUntilExpiry();
434
+ if (!expiresIn) {
435
+ return;
436
+ }
437
+ const refreshIn = expiresIn - this.threshold * 1e3;
438
+ if (refreshIn > 0) {
439
+ this.scheduledRefreshTimeout = setTimeout(() => {
440
+ this.refresh().catch((error) => {
441
+ console.error("[AuthKeeper] Scheduled refresh failed:", error);
442
+ });
443
+ }, refreshIn);
444
+ } else {
445
+ this.refresh().catch((error) => {
446
+ console.error("[AuthKeeper] Immediate refresh failed:", error);
447
+ });
448
+ }
449
+ }
450
+ /**
451
+ * Cancel scheduled refresh
452
+ */
453
+ cancelScheduledRefresh() {
454
+ if (this.scheduledRefreshTimeout) {
455
+ clearTimeout(this.scheduledRefreshTimeout);
456
+ this.scheduledRefreshTimeout = null;
457
+ }
458
+ }
459
+ /**
460
+ * Get next scheduled refresh time
461
+ */
462
+ getNextRefreshAt() {
463
+ const expiresAt = this.kernel.getExpiresAt();
464
+ if (!expiresAt) {
465
+ return null;
466
+ }
467
+ const refreshAt = new Date(expiresAt.getTime() - this.threshold * 1e3);
468
+ return refreshAt;
469
+ }
470
+ /**
471
+ * Uninstall plugin
472
+ */
473
+ uninstall() {
474
+ this.cancelScheduledRefresh();
475
+ }
476
+ };
477
+ function createRefreshEnginePlugin(options) {
478
+ return new RefreshEnginePlugin(options);
479
+ }
480
+
481
+ // src/plugins/core/storage-memory.ts
482
+ var MemoryStorageAdapter = class {
483
+ constructor(options = {}) {
484
+ this.store = /* @__PURE__ */ new Map();
485
+ this.prefix = options.prefix || "authkeeper:";
486
+ }
487
+ /**
488
+ * Get value by key
489
+ */
490
+ get(key) {
491
+ return this.store.get(this.prefix + key) || null;
492
+ }
493
+ /**
494
+ * Set value by key
495
+ */
496
+ set(key, value) {
497
+ this.store.set(this.prefix + key, value);
498
+ }
499
+ /**
500
+ * Remove value by key
501
+ */
502
+ remove(key) {
503
+ this.store.delete(this.prefix + key);
504
+ }
505
+ /**
506
+ * Clear all values
507
+ */
508
+ clear() {
509
+ const keysToDelete = [];
510
+ for (const key of this.store.keys()) {
511
+ if (key.startsWith(this.prefix)) {
512
+ keysToDelete.push(key);
513
+ }
514
+ }
515
+ keysToDelete.forEach((key) => this.store.delete(key));
516
+ }
517
+ };
518
+ function createMemoryStorage(options) {
519
+ return new MemoryStorageAdapter(options);
520
+ }
521
+
522
+ // src/plugins/core/fetch-interceptor.ts
523
+ var FetchInterceptorPlugin = class {
524
+ constructor() {
525
+ this.name = "fetch-interceptor";
526
+ this.version = "1.0.0";
527
+ this.type = "core";
528
+ this.originalFetch = null;
529
+ }
530
+ install(kernel) {
531
+ this.kernel = kernel;
532
+ return {
533
+ createFetch: this.createFetch.bind(this),
534
+ wrapFetch: this.wrapFetch.bind(this),
535
+ unwrapFetch: this.unwrapFetch.bind(this)
536
+ };
537
+ }
538
+ /**
539
+ * Create authenticated fetch function
540
+ */
541
+ createFetch(options = {}) {
542
+ const {
543
+ headerName = "Authorization",
544
+ headerPrefix = "Bearer ",
545
+ includeUrls = [],
546
+ excludeUrls = [],
547
+ retry401 = true,
548
+ maxRetries = 1,
549
+ onUnauthorized
550
+ } = options;
551
+ return async (input, init) => {
552
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
553
+ const shouldInclude = includeUrls.length === 0 || includeUrls.some(
554
+ (pattern) => typeof pattern === "string" ? url.includes(pattern) : pattern.test(url)
555
+ );
556
+ const shouldExclude = excludeUrls.some(
557
+ (pattern) => typeof pattern === "string" ? url.includes(pattern) : pattern.test(url)
558
+ );
559
+ if (!shouldInclude || shouldExclude) {
560
+ return fetch(input, init);
561
+ }
562
+ const accessToken = this.kernel.getAccessToken();
563
+ const headers = new Headers(init?.headers);
564
+ if (accessToken) {
565
+ headers.set(headerName, headerPrefix + accessToken);
566
+ }
567
+ let response = await fetch(input, {
568
+ ...init,
569
+ headers
570
+ });
571
+ if (response.status === 401 && retry401 && maxRetries > 0) {
572
+ if (onUnauthorized) {
573
+ onUnauthorized(response);
574
+ }
575
+ try {
576
+ await this.kernel.refresh();
577
+ const newToken = this.kernel.getAccessToken();
578
+ if (newToken) {
579
+ headers.set(headerName, headerPrefix + newToken);
580
+ response = await fetch(input, {
581
+ ...init,
582
+ headers
583
+ });
584
+ }
585
+ } catch (error) {
586
+ console.error("[AuthKeeper] Token refresh failed during 401 retry:", error);
587
+ }
588
+ }
589
+ return response;
590
+ };
591
+ }
592
+ /**
593
+ * Wrap global fetch with auth
594
+ */
595
+ wrapFetch(fetch2) {
596
+ if (!this.originalFetch) {
597
+ this.originalFetch = fetch2;
598
+ }
599
+ const authFetch = this.createFetch();
600
+ globalThis.fetch = authFetch;
601
+ }
602
+ /**
603
+ * Restore original fetch
604
+ */
605
+ unwrapFetch() {
606
+ if (this.originalFetch) {
607
+ globalThis.fetch = this.originalFetch;
608
+ this.originalFetch = null;
609
+ }
610
+ }
611
+ uninstall() {
612
+ this.unwrapFetch();
613
+ }
614
+ };
615
+ function createFetchInterceptorPlugin() {
616
+ return new FetchInterceptorPlugin();
617
+ }
618
+
619
+ export { FetchInterceptorPlugin, MemoryStorageAdapter, RefreshEnginePlugin, TokenDecoderPlugin, TokenStorePlugin, createFetchInterceptorPlugin, createMemoryStorage, createRefreshEnginePlugin, createTokenDecoderPlugin, createTokenStorePlugin };
620
+ //# sourceMappingURL=index.js.map
621
+ //# sourceMappingURL=index.js.map