next-token-auth 1.0.13 → 1.0.15

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,512 +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
- this.config = config;
272
- }
273
- // ─── Public API ─────────────────────────────────────────────────────────────
274
- getTokens() {
275
- if (this.config.token.storage === "memory") {
276
- return this.memoryStore;
277
- }
278
- return this.readFromCookie();
279
- }
280
- async setTokens(tokens) {
281
- if (this.config.token.storage === "memory") {
282
- this.memoryStore = tokens;
283
- return;
284
- }
285
- await this.writeToCookie(tokens);
286
- }
287
- clearTokens() {
288
- this.memoryStore = null;
289
- if (this.config.token.storage === "cookie") {
290
- this.deleteCookie();
291
- }
292
- }
293
- isAccessExpired(tokens) {
294
- const threshold = (this.config.refreshThreshold ?? 60) * 1e3;
295
- return Date.now() >= tokens.accessTokenExpiresAt - threshold;
296
- }
297
- isRefreshExpired(tokens) {
298
- if (!tokens.refreshTokenExpiresAt) return false;
299
- return Date.now() >= tokens.refreshTokenExpiresAt;
300
- }
301
- // ─── Cookie helpers (client-side only) ──────────────────────────────────────
302
- cookieName() {
303
- return this.config.token.cookieName ?? "next-token-auth.session";
304
- }
305
- readFromCookie() {
306
- if (typeof document === "undefined") return null;
307
- const raw = getCookieValue(this.cookieName());
308
- if (!raw) return null;
309
- try {
310
- return JSON.parse(decodeURIComponent(raw));
311
- } catch {
312
- return null;
313
- }
314
- }
315
- async writeToCookie(tokens) {
316
- if (typeof document === "undefined") return;
317
- const value = encodeURIComponent(JSON.stringify(tokens));
318
- const secure = this.config.token.secure !== false ? "; Secure" : "";
319
- const sameSite = this.config.token.sameSite ?? "lax";
320
- const maxAge = tokens.refreshTokenExpiresAt ? Math.floor((tokens.refreshTokenExpiresAt - Date.now()) / 1e3) : 604800;
321
- document.cookie = [
322
- `${this.cookieName()}=${value}`,
323
- `Max-Age=${maxAge}`,
324
- `Path=/`,
325
- `SameSite=${sameSite}`,
326
- secure
327
- ].filter(Boolean).join("; ");
328
- }
329
- deleteCookie() {
330
- if (typeof document === "undefined") return;
331
- document.cookie = `${this.cookieName()}=; Max-Age=0; Path=/`;
332
- }
333
- // ─── Server-side helpers ─────────────────────────────────────────────────────
334
- /**
335
- * Encrypts tokens for secure server-side cookie storage.
336
- */
337
- async encryptTokens(tokens) {
338
- return encrypt(JSON.stringify(tokens), this.config.secret);
339
- }
340
- /**
341
- * Decrypts tokens from a server-side cookie value.
342
- */
343
- async decryptTokens(ciphertext) {
344
- try {
345
- const json = await decrypt(ciphertext, this.config.secret);
346
- return JSON.parse(json);
347
- } catch {
348
- return null;
349
- }
350
- }
351
- };
352
- function getCookieValue(name) {
353
- if (typeof document === "undefined") return null;
354
- const match = document.cookie.match(
355
- new RegExp(`(?:^|;\\s*)${escapeRegex(name)}=([^;]*)`)
356
- );
357
- return match ? match[1] : null;
358
- }
359
- function escapeRegex(str) {
360
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
361
- }
362
-
363
- // src/core/AuthClient.ts
364
- var AuthClient = class {
365
- constructor(config) {
366
- this.sessionListeners = [];
367
- this.config = config;
368
- this.tokenManager = new TokenManager(config);
369
- this.httpClient = new HttpClient(config, this.tokenManager);
370
- this.sessionManager = new SessionManager(
371
- config,
372
- this.tokenManager,
373
- this.httpClient
374
- );
375
- this.httpClient.setRefreshFn(() => this.refresh());
376
- }
377
- // ─── Auth Operations ────────────────────────────────────────────────────────
378
- /**
379
- * Authenticates the user and stores tokens.
380
- */
381
- async login(input) {
382
- const res = await this.httpClient.doFetch(
383
- this.httpClient.url(this.config.endpoints.login),
384
- {
385
- method: "POST",
386
- headers: { "Content-Type": "application/json" },
387
- body: JSON.stringify(input)
388
- }
389
- );
390
- if (!res.ok) {
391
- const error = await res.text();
392
- throw new Error(`Login failed (${res.status}): ${error}`);
393
- }
394
- const data = await res.json();
395
- const tokens = this.buildTokens(data);
396
- await this.tokenManager.setTokens(tokens);
397
- await this.sessionManager.loadSession();
398
- const session = this.sessionManager.getSession();
399
- this.config.onLogin?.(session);
400
- this.notifyListeners(session);
401
- return session;
402
- }
403
- /**
404
- * Logs out the user, clears tokens, and optionally calls the backend.
405
- */
406
- async logout() {
407
- const logoutEndpoint = this.config.endpoints.logout;
408
- if (logoutEndpoint) {
409
- try {
410
- await this.httpClient.fetch(this.httpClient.url(logoutEndpoint), {
411
- method: "POST"
412
- });
413
- } catch {
414
- }
415
- }
416
- this.tokenManager.clearTokens();
417
- this.sessionManager.clearSession();
418
- this.config.onLogout?.();
419
- this.notifyListeners(this.sessionManager.getSession());
420
- }
421
- /**
422
- * Refreshes the access token using the stored refresh token.
423
- * Returns true on success, false on failure.
424
- */
425
- async refresh() {
426
- const tokens = this.tokenManager.getTokens();
427
- if (!tokens) return false;
428
- if (this.tokenManager.isRefreshExpired(tokens)) {
429
- await this.logout();
430
- return false;
431
- }
432
- try {
433
- const res = await this.httpClient.doFetch(
434
- this.httpClient.url(this.config.endpoints.refresh),
435
- {
436
- method: "POST",
437
- headers: { "Content-Type": "application/json" },
438
- body: JSON.stringify({ refreshToken: tokens.refreshToken })
439
- }
440
- );
441
- if (!res.ok) {
442
- await this.logout();
443
- return false;
444
- }
445
- const data = await res.json();
446
- const newTokens = this.buildTokens(data);
447
- await this.tokenManager.setTokens(newTokens);
448
- await this.sessionManager.refreshSession(newTokens);
449
- this.notifyListeners(this.sessionManager.getSession());
450
- return true;
451
- } catch (err) {
452
- this.config.onRefreshError?.(err);
453
- return false;
454
- }
455
- }
456
- /**
457
- * Loads the session from stored tokens (call on app mount).
458
- */
459
- async initialize() {
460
- const session = await this.sessionManager.loadSession();
461
- if (session.isAuthenticated && session.tokens && this.tokenManager.isAccessExpired(session.tokens) && !this.tokenManager.isRefreshExpired(session.tokens)) {
462
- await this.refresh();
463
- }
464
- return this.sessionManager.getSession();
465
- }
466
- getSession() {
467
- return this.sessionManager.getSession();
468
- }
469
- /**
470
- * Returns the authenticated fetch wrapper.
471
- */
472
- get fetch() {
473
- return this.httpClient.fetch.bind(this.httpClient);
474
- }
475
- // ─── Subscription ────────────────────────────────────────────────────────────
476
- subscribe(listener) {
477
- this.sessionListeners.push(listener);
478
- return () => {
479
- this.sessionListeners = this.sessionListeners.filter((l) => l !== listener);
480
- };
481
- }
482
- // ─── Private ────────────────────────────────────────────────────────────────
483
- buildTokens(data) {
484
- const strategy = this.config.expiry?.strategy ?? "hybrid";
485
- const configAccess = this.config.expiry?.accessTokenExpiresIn;
486
- const configRefresh = this.config.expiry?.refreshTokenExpiresIn;
487
- return {
488
- accessToken: data.accessToken,
489
- refreshToken: data.refreshToken,
490
- accessTokenExpiresAt: resolveAccessTokenExpiry(data, configAccess, strategy),
491
- refreshTokenExpiresAt: resolveRefreshTokenExpiry(data, configRefresh, strategy)
492
- };
493
- }
494
- notifyListeners(session) {
495
- for (const listener of this.sessionListeners) {
496
- listener(session);
497
- }
498
- }
499
- };
500
5
  var AuthContext = createContext(null);
501
- function AuthProvider({
502
- config,
503
- children
504
- }) {
505
- const clientRef = useRef(null);
506
- if (!clientRef.current) {
507
- clientRef.current = new AuthClient(config);
508
- }
509
- const client = clientRef.current;
6
+ function AuthProvider({ config, children }) {
510
7
  const [session, setSession] = useState({
511
8
  user: null,
512
9
  tokens: null,
@@ -515,57 +12,87 @@ function AuthProvider({
515
12
  const [isLoading, setIsLoading] = useState(true);
516
13
  useEffect(() => {
517
14
  let cancelled = false;
518
- 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(() => {
519
26
  if (!cancelled) {
520
- setSession(s);
27
+ setSession({ user: null, tokens: null, isAuthenticated: false });
521
28
  setIsLoading(false);
522
29
  }
523
30
  });
524
- const unsubscribe = client.subscribe((s) => {
525
- if (!cancelled) setSession(s);
526
- });
527
31
  return () => {
528
32
  cancelled = true;
529
- unsubscribe();
530
33
  };
531
- }, [client]);
34
+ }, []);
532
35
  useEffect(() => {
533
36
  if (!config.autoRefresh) return;
534
37
  const interval = setInterval(async () => {
535
- const tokens = client.tokenManager.getTokens();
536
- if (tokens && client.tokenManager.isAccessExpired(tokens) && !client.tokenManager.isRefreshExpired(tokens)) {
537
- 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
+ }
538
49
  }
539
- }, 3e4);
50
+ }, (config.refreshThreshold ?? 60) * 1e3);
540
51
  return () => clearInterval(interval);
541
- }, [client, config.autoRefresh]);
52
+ }, [config.autoRefresh, config.refreshThreshold, session.isAuthenticated]);
542
53
  const login = useCallback(
543
54
  async (input) => {
544
55
  setIsLoading(true);
545
56
  try {
546
- const s = await client.login(input);
547
- 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);
548
70
  } finally {
549
71
  setIsLoading(false);
550
72
  }
551
73
  },
552
- [client]
74
+ [config]
553
75
  );
554
76
  const logout = useCallback(async () => {
555
- await client.logout();
77
+ await fetch("/api/auth/logout", { method: "POST" });
556
78
  setSession({ user: null, tokens: null, isAuthenticated: false });
557
- }, [client]);
79
+ config.onLogout?.();
80
+ }, [config]);
558
81
  const refresh = useCallback(async () => {
559
- await client.refresh();
560
- setSession(client.getSession());
561
- }, [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
+ }, []);
562
90
  const value = {
563
91
  session,
564
92
  isLoading,
565
93
  login,
566
94
  logout,
567
- refresh,
568
- client
95
+ refresh
569
96
  };
570
97
  return /* @__PURE__ */ jsx(AuthContext.Provider, { value, children });
571
98
  }