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