next-token-auth 1.0.14 → 1.0.16

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.
@@ -1,524 +1,9 @@
1
- import { createContext, useRef, useState, useEffect, useCallback, useContext } from 'react';
1
+ import { createContext, useState, useEffect, useCallback, useContext } from 'react';
2
2
  import { jsx } from 'react/jsx-runtime';
3
3
 
4
4
  // src/react/AuthProvider.tsx
5
-
6
- // src/utils/expiry.ts
7
- var UNIT_MAP = {
8
- s: 1,
9
- m: 60,
10
- h: 3600,
11
- d: 86400,
12
- w: 604800
13
- };
14
- function parseExpiry(input) {
15
- if (input === void 0 || input === null) {
16
- throw new Error("parseExpiry: no expiry value provided");
17
- }
18
- if (typeof input === "number") {
19
- if (input <= 0) throw new Error("parseExpiry: value must be positive");
20
- return input;
21
- }
22
- const trimmed = input.trim();
23
- if (/^\d+$/.test(trimmed)) {
24
- return parseInt(trimmed, 10);
25
- }
26
- const match = trimmed.match(/^(\d+(?:\.\d+)?)\s*([smhdw])$/i);
27
- if (!match) {
28
- throw new Error(
29
- `parseExpiry: unrecognised format "${input}". Expected a number or a string like "15m", "2h", "2d", "7d", "1w".`
30
- );
31
- }
32
- const value = parseFloat(match[1]);
33
- const unit = match[2].toLowerCase();
34
- return Math.floor(value * UNIT_MAP[unit]);
35
- }
36
- function safeParseExpiry(input, fallbackSeconds = 900) {
37
- try {
38
- return parseExpiry(input);
39
- } catch {
40
- return fallbackSeconds;
41
- }
42
- }
43
- function resolveAccessTokenExpiry(response, configExpiry, strategy = "hybrid") {
44
- const now = Date.now();
45
- const fromBackend = response.accessTokenExpiresIn ?? response.expiresIn ?? void 0;
46
- if (strategy === "backend") {
47
- if (fromBackend === void 0) {
48
- throw new Error(
49
- 'resolveAccessTokenExpiry: strategy is "backend" but API returned no expiry'
50
- );
51
- }
52
- return now + parseExpiry(fromBackend) * 1e3;
53
- }
54
- if (strategy === "config") {
55
- if (configExpiry === void 0) {
56
- throw new Error(
57
- 'resolveAccessTokenExpiry: strategy is "config" but no expiry configured'
58
- );
59
- }
60
- return now + parseExpiry(configExpiry) * 1e3;
61
- }
62
- if (fromBackend !== void 0) {
63
- return now + safeParseExpiry(fromBackend) * 1e3;
64
- }
65
- if (configExpiry !== void 0) {
66
- return now + safeParseExpiry(configExpiry) * 1e3;
67
- }
68
- return now + 900 * 1e3;
69
- }
70
- function resolveRefreshTokenExpiry(response, configExpiry, strategy = "hybrid") {
71
- const now = Date.now();
72
- const fromBackend = response.refreshTokenExpiresIn;
73
- if (strategy === "backend") {
74
- return fromBackend !== void 0 ? now + parseExpiry(fromBackend) * 1e3 : void 0;
75
- }
76
- if (strategy === "config") {
77
- return configExpiry !== void 0 ? now + parseExpiry(configExpiry) * 1e3 : void 0;
78
- }
79
- if (fromBackend !== void 0) {
80
- return now + safeParseExpiry(fromBackend) * 1e3;
81
- }
82
- if (configExpiry !== void 0) {
83
- return now + safeParseExpiry(configExpiry) * 1e3;
84
- }
85
- return void 0;
86
- }
87
-
88
- // src/core/HttpClient.ts
89
- var HttpClient = class {
90
- constructor(config, tokenManager) {
91
- this.refreshFn = null;
92
- this.refreshPromise = null;
93
- this.config = config;
94
- this.tokenManager = tokenManager;
95
- }
96
- /** Register the refresh callback (set by AuthClient to avoid circular deps) */
97
- setRefreshFn(fn) {
98
- this.refreshFn = fn;
99
- }
100
- /**
101
- * Authenticated fetch wrapper.
102
- * Automatically injects the Bearer token and handles 401 → refresh → retry.
103
- */
104
- async fetch(input, init = {}) {
105
- const tokens = this.tokenManager.getTokens();
106
- const headers = new Headers(init.headers);
107
- if (tokens?.accessToken) {
108
- headers.set("Authorization", `Bearer ${tokens.accessToken}`);
109
- }
110
- const response = await this.doFetch(input, { ...init, headers });
111
- if (response.status === 401 && this.refreshFn) {
112
- const refreshed = await this.deduplicatedRefresh();
113
- if (refreshed) {
114
- const newTokens = this.tokenManager.getTokens();
115
- if (newTokens?.accessToken) {
116
- headers.set("Authorization", `Bearer ${newTokens.accessToken}`);
117
- }
118
- return this.doFetch(input, { ...init, headers });
119
- }
120
- }
121
- return response;
122
- }
123
- /**
124
- * Raw fetch using the configured fetchFn or global fetch.
125
- */
126
- async doFetch(input, init) {
127
- const fetchFn = this.config.fetchFn ?? fetch;
128
- return fetchFn(input, init);
129
- }
130
- /**
131
- * Builds a full URL from a path relative to baseUrl.
132
- */
133
- url(path) {
134
- return `${this.config.baseUrl.replace(/\/$/, "")}/${path.replace(/^\//, "")}`;
135
- }
136
- // ─── Private ────────────────────────────────────────────────────────────────
137
- /**
138
- * Ensures only one refresh request is in-flight at a time.
139
- */
140
- async deduplicatedRefresh() {
141
- if (this.refreshPromise) return this.refreshPromise;
142
- this.refreshPromise = this.refreshFn().finally(() => {
143
- this.refreshPromise = null;
144
- });
145
- return this.refreshPromise;
146
- }
147
- };
148
-
149
- // src/core/SessionManager.ts
150
- var SessionManager = class {
151
- constructor(config, tokenManager, httpClient) {
152
- this.session = {
153
- user: null,
154
- tokens: null,
155
- isAuthenticated: false
156
- };
157
- this.config = config;
158
- this.tokenManager = tokenManager;
159
- this.httpClient = httpClient;
160
- }
161
- getSession() {
162
- return this.session;
163
- }
164
- setSession(session) {
165
- this.session = session;
166
- }
167
- /**
168
- * Builds a session from stored tokens, optionally fetching the user profile.
169
- */
170
- async loadSession() {
171
- const tokens = this.tokenManager.getTokens();
172
- if (!tokens) {
173
- this.session = { user: null, tokens: null, isAuthenticated: false };
174
- return this.session;
175
- }
176
- if (this.tokenManager.isAccessExpired(tokens) && this.tokenManager.isRefreshExpired(tokens)) {
177
- this.tokenManager.clearTokens();
178
- this.session = { user: null, tokens: null, isAuthenticated: false };
179
- return this.session;
180
- }
181
- const user = await this.fetchUser(tokens);
182
- this.session = {
183
- user,
184
- tokens,
185
- isAuthenticated: true
186
- };
187
- return this.session;
188
- }
189
- /**
190
- * Updates the session after a successful token refresh.
191
- */
192
- async refreshSession(tokens) {
193
- const user = this.session.user ?? await this.fetchUser(tokens);
194
- this.session = { user, tokens, isAuthenticated: true };
195
- }
196
- clearSession() {
197
- this.session = { user: null, tokens: null, isAuthenticated: false };
198
- }
199
- // ─── Private ────────────────────────────────────────────────────────────────
200
- async fetchUser(tokens) {
201
- const meEndpoint = this.config.endpoints.me;
202
- if (!meEndpoint) return null;
203
- try {
204
- const res = await this.httpClient.fetch(this.httpClient.url(meEndpoint));
205
- if (!res.ok) return null;
206
- return await res.json();
207
- } catch {
208
- return null;
209
- }
210
- }
211
- };
212
-
213
- // src/utils/crypto.ts
214
- var ALGO = "AES-GCM";
215
- var IV_LENGTH = 12;
216
- function getTextEncoder() {
217
- return new TextEncoder();
218
- }
219
- function getTextDecoder() {
220
- return new TextDecoder();
221
- }
222
- async function deriveKey(secret) {
223
- const raw = getTextEncoder().encode(secret.padEnd(32, "0").slice(0, 32));
224
- return crypto.subtle.importKey("raw", raw, { name: ALGO }, false, [
225
- "encrypt",
226
- "decrypt"
227
- ]);
228
- }
229
- async function encrypt(data, secret) {
230
- const key = await deriveKey(secret);
231
- const ivArray = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
232
- const iv = ivArray.buffer.slice(0, IV_LENGTH);
233
- const encoded = getTextEncoder().encode(data);
234
- const cipherBuffer = await crypto.subtle.encrypt({ name: ALGO, iv }, key, encoded);
235
- const ivB64 = bufferToBase64(new Uint8Array(iv));
236
- const cipherB64 = bufferToBase64(new Uint8Array(cipherBuffer));
237
- return `${ivB64}.${cipherB64}`;
238
- }
239
- async function decrypt(data, secret) {
240
- const [ivB64, cipherB64] = data.split(".");
241
- if (!ivB64 || !cipherB64) {
242
- throw new Error("decrypt: invalid ciphertext format");
243
- }
244
- const key = await deriveKey(secret);
245
- const ivBytes = base64ToBuffer(ivB64);
246
- const iv = ivBytes.buffer.slice(
247
- ivBytes.byteOffset,
248
- ivBytes.byteOffset + ivBytes.byteLength
249
- );
250
- const cipherBytes = base64ToBuffer(cipherB64);
251
- const cipherBuffer = cipherBytes.buffer.slice(
252
- cipherBytes.byteOffset,
253
- cipherBytes.byteOffset + cipherBytes.byteLength
254
- );
255
- const plainBuffer = await crypto.subtle.decrypt({ name: ALGO, iv }, key, cipherBuffer);
256
- return getTextDecoder().decode(plainBuffer);
257
- }
258
- function bufferToBase64(buffer) {
259
- return btoa(String.fromCharCode(...buffer)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
260
- }
261
- function base64ToBuffer(b64) {
262
- const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
263
- const binary = atob(padded);
264
- return Uint8Array.from(binary, (c) => c.charCodeAt(0));
265
- }
266
-
267
- // src/core/TokenManager.ts
268
- var TokenManager = class {
269
- constructor(config) {
270
- this.memoryStore = null;
271
- /** In-memory cache of the last successfully decrypted cookie value. */
272
- this.decryptedCache = null;
273
- this.config = config;
274
- }
275
- // ─── Public API ─────────────────────────────────────────────────────────────
276
- getTokens() {
277
- if (this.config.token.storage === "memory") {
278
- return this.memoryStore;
279
- }
280
- return this.decryptedCache;
281
- }
282
- /**
283
- * Must be called once on startup (before getTokens) when storage is "cookie".
284
- * Reads and decrypts the cookie, populating the in-memory cache.
285
- */
286
- async initFromCookie() {
287
- if (typeof document === "undefined") return;
288
- if (this.config.token.storage !== "cookie") return;
289
- const raw = getCookieValue(this.cookieName());
290
- if (!raw) return;
291
- try {
292
- const json = await decrypt(decodeURIComponent(raw), this.config.secret);
293
- this.decryptedCache = JSON.parse(json);
294
- } catch {
295
- this.decryptedCache = null;
296
- }
297
- }
298
- async setTokens(tokens) {
299
- if (this.config.token.storage === "memory") {
300
- this.memoryStore = tokens;
301
- return;
302
- }
303
- await this.writeToCookie(tokens);
304
- }
305
- clearTokens() {
306
- this.memoryStore = null;
307
- this.decryptedCache = null;
308
- if (this.config.token.storage === "cookie") {
309
- this.deleteCookie();
310
- }
311
- }
312
- isAccessExpired(tokens) {
313
- const threshold = (this.config.refreshThreshold ?? 60) * 1e3;
314
- return Date.now() >= tokens.accessTokenExpiresAt - threshold;
315
- }
316
- isRefreshExpired(tokens) {
317
- if (!tokens.refreshTokenExpiresAt) return false;
318
- return Date.now() >= tokens.refreshTokenExpiresAt;
319
- }
320
- // ─── Cookie helpers (client-side only) ──────────────────────────────────────
321
- cookieName() {
322
- return this.config.token.cookieName ?? "next-token-auth.session";
323
- }
324
- async writeToCookie(tokens) {
325
- if (typeof document === "undefined") return;
326
- const value = await encrypt(JSON.stringify(tokens), this.config.secret);
327
- const secure = this.config.token.secure !== false ? "; Secure" : "";
328
- const sameSite = this.config.token.sameSite ?? "lax";
329
- const maxAge = tokens.refreshTokenExpiresAt ? Math.floor((tokens.refreshTokenExpiresAt - Date.now()) / 1e3) : 604800;
330
- document.cookie = [
331
- `${this.cookieName()}=${encodeURIComponent(value)}`,
332
- `Max-Age=${maxAge}`,
333
- `Path=/`,
334
- `SameSite=${sameSite}`,
335
- secure
336
- ].filter(Boolean).join("; ");
337
- this.decryptedCache = tokens;
338
- }
339
- deleteCookie() {
340
- if (typeof document === "undefined") return;
341
- document.cookie = `${this.cookieName()}=; Max-Age=0; Path=/`;
342
- }
343
- // ─── Server-side helpers ─────────────────────────────────────────────────────
344
- /**
345
- * Encrypts tokens — used internally by writeToCookie and available for
346
- * advanced server-side use cases.
347
- */
348
- async encryptTokens(tokens) {
349
- return encrypt(JSON.stringify(tokens), this.config.secret);
350
- }
351
- /**
352
- * Decrypts tokens from a server-side cookie value.
353
- */
354
- async decryptTokens(ciphertext) {
355
- try {
356
- const json = await decrypt(ciphertext, this.config.secret);
357
- return JSON.parse(json);
358
- } catch {
359
- return null;
360
- }
361
- }
362
- };
363
- function getCookieValue(name) {
364
- if (typeof document === "undefined") return null;
365
- const match = document.cookie.match(
366
- new RegExp(`(?:^|;\\s*)${escapeRegex(name)}=([^;]*)`)
367
- );
368
- return match ? match[1] : null;
369
- }
370
- function escapeRegex(str) {
371
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
372
- }
373
-
374
- // src/core/AuthClient.ts
375
- var AuthClient = class {
376
- constructor(config) {
377
- this.sessionListeners = [];
378
- this.config = config;
379
- this.tokenManager = new TokenManager(config);
380
- this.httpClient = new HttpClient(config, this.tokenManager);
381
- this.sessionManager = new SessionManager(
382
- config,
383
- this.tokenManager,
384
- this.httpClient
385
- );
386
- this.httpClient.setRefreshFn(() => this.refresh());
387
- }
388
- // ─── Auth Operations ────────────────────────────────────────────────────────
389
- /**
390
- * Authenticates the user and stores tokens.
391
- */
392
- async login(input) {
393
- const res = await this.httpClient.doFetch(
394
- this.httpClient.url(this.config.endpoints.login),
395
- {
396
- method: "POST",
397
- headers: { "Content-Type": "application/json" },
398
- body: JSON.stringify(input)
399
- }
400
- );
401
- if (!res.ok) {
402
- const error = await res.text();
403
- throw new Error(`Login failed (${res.status}): ${error}`);
404
- }
405
- const data = await res.json();
406
- const tokens = this.buildTokens(data);
407
- await this.tokenManager.setTokens(tokens);
408
- await this.sessionManager.loadSession();
409
- const session = this.sessionManager.getSession();
410
- this.config.onLogin?.(session);
411
- this.notifyListeners(session);
412
- return session;
413
- }
414
- /**
415
- * Logs out the user, clears tokens, and optionally calls the backend.
416
- */
417
- async logout() {
418
- const logoutEndpoint = this.config.endpoints.logout;
419
- if (logoutEndpoint) {
420
- try {
421
- await this.httpClient.fetch(this.httpClient.url(logoutEndpoint), {
422
- method: "POST"
423
- });
424
- } catch {
425
- }
426
- }
427
- this.tokenManager.clearTokens();
428
- this.sessionManager.clearSession();
429
- this.config.onLogout?.();
430
- this.notifyListeners(this.sessionManager.getSession());
431
- }
432
- /**
433
- * Refreshes the access token using the stored refresh token.
434
- * Returns true on success, false on failure.
435
- */
436
- async refresh() {
437
- const tokens = this.tokenManager.getTokens();
438
- if (!tokens) return false;
439
- if (this.tokenManager.isRefreshExpired(tokens)) {
440
- await this.logout();
441
- return false;
442
- }
443
- try {
444
- const res = await this.httpClient.doFetch(
445
- this.httpClient.url(this.config.endpoints.refresh),
446
- {
447
- method: "POST",
448
- headers: { "Content-Type": "application/json" },
449
- body: JSON.stringify({ refreshToken: tokens.refreshToken })
450
- }
451
- );
452
- if (!res.ok) {
453
- await this.logout();
454
- return false;
455
- }
456
- const data = await res.json();
457
- const newTokens = this.buildTokens(data);
458
- await this.tokenManager.setTokens(newTokens);
459
- await this.sessionManager.refreshSession(newTokens);
460
- this.notifyListeners(this.sessionManager.getSession());
461
- return true;
462
- } catch (err) {
463
- this.config.onRefreshError?.(err);
464
- return false;
465
- }
466
- }
467
- /**
468
- * Loads the session from stored tokens (call on app mount).
469
- */
470
- async initialize() {
471
- await this.tokenManager.initFromCookie();
472
- const session = await this.sessionManager.loadSession();
473
- if (session.isAuthenticated && session.tokens && this.tokenManager.isAccessExpired(session.tokens) && !this.tokenManager.isRefreshExpired(session.tokens)) {
474
- await this.refresh();
475
- }
476
- return this.sessionManager.getSession();
477
- }
478
- getSession() {
479
- return this.sessionManager.getSession();
480
- }
481
- /**
482
- * Returns the authenticated fetch wrapper.
483
- */
484
- get fetch() {
485
- return this.httpClient.fetch.bind(this.httpClient);
486
- }
487
- // ─── Subscription ────────────────────────────────────────────────────────────
488
- subscribe(listener) {
489
- this.sessionListeners.push(listener);
490
- return () => {
491
- this.sessionListeners = this.sessionListeners.filter((l) => l !== listener);
492
- };
493
- }
494
- // ─── Private ────────────────────────────────────────────────────────────────
495
- buildTokens(data) {
496
- const strategy = this.config.expiry?.strategy ?? "hybrid";
497
- const configAccess = this.config.expiry?.accessTokenExpiresIn;
498
- const configRefresh = this.config.expiry?.refreshTokenExpiresIn;
499
- return {
500
- accessToken: data.accessToken,
501
- refreshToken: data.refreshToken,
502
- accessTokenExpiresAt: resolveAccessTokenExpiry(data, configAccess, strategy),
503
- refreshTokenExpiresAt: resolveRefreshTokenExpiry(data, configRefresh, strategy)
504
- };
505
- }
506
- notifyListeners(session) {
507
- for (const listener of this.sessionListeners) {
508
- listener(session);
509
- }
510
- }
511
- };
512
5
  var AuthContext = createContext(null);
513
- function AuthProvider({
514
- config,
515
- children
516
- }) {
517
- const clientRef = useRef(null);
518
- if (!clientRef.current) {
519
- clientRef.current = new AuthClient(config);
520
- }
521
- const client = clientRef.current;
6
+ function AuthProvider({ config, children }) {
522
7
  const [session, setSession] = useState({
523
8
  user: null,
524
9
  tokens: null,
@@ -527,57 +12,87 @@ function AuthProvider({
527
12
  const [isLoading, setIsLoading] = useState(true);
528
13
  useEffect(() => {
529
14
  let cancelled = false;
530
- client.initialize().then((s) => {
15
+ fetch("/api/auth/session").then((res) => res.json()).then((data) => {
16
+ if (!cancelled) {
17
+ setSession({
18
+ user: data.user ?? null,
19
+ tokens: null,
20
+ // tokens are HttpOnly, never exposed to client
21
+ isAuthenticated: data.isAuthenticated ?? false
22
+ });
23
+ setIsLoading(false);
24
+ }
25
+ }).catch(() => {
531
26
  if (!cancelled) {
532
- setSession(s);
27
+ setSession({ user: null, tokens: null, isAuthenticated: false });
533
28
  setIsLoading(false);
534
29
  }
535
30
  });
536
- const unsubscribe = client.subscribe((s) => {
537
- if (!cancelled) setSession(s);
538
- });
539
31
  return () => {
540
32
  cancelled = true;
541
- unsubscribe();
542
33
  };
543
- }, [client]);
34
+ }, []);
544
35
  useEffect(() => {
545
36
  if (!config.autoRefresh) return;
546
37
  const interval = setInterval(async () => {
547
- const tokens = client.tokenManager.getTokens();
548
- if (tokens && client.tokenManager.isAccessExpired(tokens) && !client.tokenManager.isRefreshExpired(tokens)) {
549
- await client.refresh();
38
+ if (session.isAuthenticated) {
39
+ try {
40
+ await fetch("/api/auth/refresh", { method: "POST" });
41
+ const updated = await fetch("/api/auth/session").then((r) => r.json());
42
+ setSession({
43
+ user: updated.user ?? null,
44
+ tokens: null,
45
+ isAuthenticated: updated.isAuthenticated ?? false
46
+ });
47
+ } catch {
48
+ }
550
49
  }
551
- }, 3e4);
50
+ }, (config.refreshThreshold ?? 60) * 1e3);
552
51
  return () => clearInterval(interval);
553
- }, [client, config.autoRefresh]);
52
+ }, [config.autoRefresh, config.refreshThreshold, session.isAuthenticated]);
554
53
  const login = useCallback(
555
54
  async (input) => {
556
55
  setIsLoading(true);
557
56
  try {
558
- const s = await client.login(input);
559
- setSession(s);
57
+ const res = await fetch("/api/auth/login", {
58
+ method: "POST",
59
+ headers: { "Content-Type": "application/json" },
60
+ body: JSON.stringify(input)
61
+ });
62
+ if (!res.ok) {
63
+ const { error } = await res.json();
64
+ throw new Error(error ?? "Login failed");
65
+ }
66
+ const { user } = await res.json();
67
+ const newSession = { user, tokens: null, isAuthenticated: true };
68
+ setSession(newSession);
69
+ config.onLogin?.(newSession);
560
70
  } finally {
561
71
  setIsLoading(false);
562
72
  }
563
73
  },
564
- [client]
74
+ [config]
565
75
  );
566
76
  const logout = useCallback(async () => {
567
- await client.logout();
77
+ await fetch("/api/auth/logout", { method: "POST" });
568
78
  setSession({ user: null, tokens: null, isAuthenticated: false });
569
- }, [client]);
79
+ config.onLogout?.();
80
+ }, [config]);
570
81
  const refresh = useCallback(async () => {
571
- await client.refresh();
572
- setSession(client.getSession());
573
- }, [client]);
82
+ await fetch("/api/auth/refresh", { method: "POST" });
83
+ const updated = await fetch("/api/auth/session").then((r) => r.json());
84
+ setSession({
85
+ user: updated.user ?? null,
86
+ tokens: null,
87
+ isAuthenticated: updated.isAuthenticated ?? false
88
+ });
89
+ }, []);
574
90
  const value = {
575
91
  session,
576
92
  isLoading,
577
93
  login,
578
94
  logout,
579
- refresh,
580
- client
95
+ refresh
581
96
  };
582
97
  return /* @__PURE__ */ jsx(AuthContext.Provider, { value, children });
583
98
  }