mailsentry-auth 0.1.6 → 0.1.7

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.
Files changed (2) hide show
  1. package/dist/middleware.mjs +7 -349
  2. package/package.json +1 -1
@@ -1,25 +1,5 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
-
21
- // src/middlewares/handlers/base-middleware-handler.ts
22
- import { NextResponse } from "next/server";
1
+ import { NextResponse } from 'next/server';
2
+ import Cookies from 'js-cookie';
23
3
 
24
4
  // src/config/middleware.ts
25
5
  var _MiddlewareConfig = class _MiddlewareConfig {
@@ -80,9 +60,6 @@ var config = {
80
60
  matcher: middlewareMatcher
81
61
  };
82
62
 
83
- // src/services/utils/cookie-utils.ts
84
- import Cookies from "js-cookie";
85
-
86
63
  // src/services/utils/url-utils.ts
87
64
  var UrlUtils = class {
88
65
  /**
@@ -174,7 +151,7 @@ var _CookieUtils = class _CookieUtils {
174
151
  */
175
152
  static async getServerTokens() {
176
153
  try {
177
- const { getAuthTokens } = await import("mailsentry-auth/server");
154
+ const { getAuthTokens } = await import('mailsentry-auth/server');
178
155
  return await getAuthTokens();
179
156
  } catch (error) {
180
157
  console.error("Failed to get server tokens:", error);
@@ -344,323 +321,10 @@ var _CookieUtils = class _CookieUtils {
344
321
  _CookieUtils.COOKIE_DOMAIN = _CookieUtils.getRootDomain();
345
322
  var CookieUtils = _CookieUtils;
346
323
 
347
- // src/services/utils/localstorage-utils.ts
348
- var LocalStorageUtils = class {
349
- // 5 minutes
350
- /**
351
- * Check if localStorage is available
352
- */
353
- static isAvailable() {
354
- try {
355
- if (typeof window === "undefined") return false;
356
- localStorage.setItem("test", "test");
357
- localStorage.removeItem("test");
358
- return true;
359
- } catch (e) {
360
- return false;
361
- }
362
- }
363
- /**
364
- * Save user profile to localStorage with timestamp
365
- */
366
- static saveUserProfile(userProfile) {
367
- if (!this.isAvailable() || !userProfile) return false;
368
- try {
369
- localStorage.setItem(this.USER_PROFILE_STORAGE_KEY, JSON.stringify(userProfile));
370
- localStorage.setItem(this.USER_PROFILE_TIMESTAMP_KEY, Date.now().toString());
371
- return true;
372
- } catch (e) {
373
- return false;
374
- }
375
- }
376
- /**
377
- * Get user profile from localStorage with cache validation
378
- */
379
- static getUserProfile(cacheDuration = this.DEFAULT_CACHE_DURATION) {
380
- if (!this.isAvailable()) return null;
381
- try {
382
- const userProfileData = localStorage.getItem(this.USER_PROFILE_STORAGE_KEY);
383
- const timestamp = localStorage.getItem(this.USER_PROFILE_TIMESTAMP_KEY);
384
- if (!userProfileData || !timestamp) return null;
385
- const cacheAge = Date.now() - parseInt(timestamp);
386
- if (cacheAge >= cacheDuration) {
387
- this.clearUserProfile();
388
- return null;
389
- }
390
- return JSON.parse(userProfileData);
391
- } catch (e) {
392
- this.clearUserProfile();
393
- return null;
394
- }
395
- }
396
- /**
397
- * Clear user profile data from localStorage
398
- */
399
- static clearUserProfile() {
400
- if (!this.isAvailable()) return false;
401
- try {
402
- localStorage.removeItem(this.USER_PROFILE_STORAGE_KEY);
403
- localStorage.removeItem(this.USER_PROFILE_TIMESTAMP_KEY);
404
- return true;
405
- } catch (e) {
406
- return false;
407
- }
408
- }
409
- /**
410
- * Check if cached user profile is still valid
411
- */
412
- static isCacheValid(cacheDuration = this.DEFAULT_CACHE_DURATION) {
413
- if (!this.isAvailable()) return false;
414
- try {
415
- const timestamp = localStorage.getItem(this.USER_PROFILE_TIMESTAMP_KEY);
416
- if (!timestamp) return false;
417
- const cacheAge = Date.now() - parseInt(timestamp);
418
- return cacheAge < cacheDuration;
419
- } catch (e) {
420
- return false;
421
- }
422
- }
423
- };
424
- LocalStorageUtils.USER_PROFILE_STORAGE_KEY = "user_profile_data";
425
- LocalStorageUtils.USER_PROFILE_TIMESTAMP_KEY = "user_profile_timestamp";
426
- LocalStorageUtils.DEFAULT_CACHE_DURATION = 5 * 60 * 1e3;
427
-
428
- // src/config/auth-steps.tsx
429
- import React2 from "react";
430
- import {
431
- MailOutlined,
432
- LockOutlined,
433
- CheckCircleOutlined
434
- } from "@ant-design/icons";
435
-
436
- // src/config/step-navigation.ts
437
- var EMAIL_SUBMISSION_NAVIGATION = {
438
- ["login-verification" /* LOGIN_VERIFICATION */]: "verification" /* VERIFICATION */,
439
- ["login" /* LOGIN */]: "password" /* PASSWORD */,
440
- ["signup" /* SIGNUP */]: "password" /* PASSWORD */
441
- };
442
- var PASSWORD_SUBMISSION_NAVIGATION = {
443
- VERIFIED: "verification" /* VERIFICATION */,
444
- UNVERIFIED: "verification" /* VERIFICATION */
445
- };
446
- var VERIFICATION_SUBMISSION_NAVIGATION = {
447
- SUCCESS: "verification" /* VERIFICATION */,
448
- ERROR: "verification" /* VERIFICATION */
449
- // Stay on verification step on error
450
- };
451
-
452
- // src/config/form-fields.tsx
453
- import { Input } from "antd";
454
- import { MailOutlined as MailOutlined2, LockOutlined as LockOutlined2, CheckCircleOutlined as CheckCircleOutlined2 } from "@ant-design/icons";
455
-
456
324
  // src/services/api/endpoints.ts
457
325
  var AUTH_ENDPOINTS = {
458
- // Email existence check
459
- CHECK_EMAIL_EXISTS: (email) => `/auth/user/exist-email/${encodeURIComponent(email)}`,
460
- // User authentication
461
- LOGIN: "/auth/user/login",
462
- VERIFY_EMAIL: "/auth/user/verify",
463
326
  // User profile
464
- GET_USER_PROFILE: "/auth/user/profile",
465
- // User logout
466
- LOGOUT: "/auth/logout"
467
- };
468
- var EndpointBuilder = class {
469
- };
470
- EndpointBuilder.auth = AUTH_ENDPOINTS;
471
-
472
- // src/services/auth/patterns/command/auth-result-factory.ts
473
- var AuthResultFactory = class {
474
- /**
475
- * Creates a successful authentication result
476
- */
477
- static createSuccess(message, data) {
478
- return {
479
- success: true,
480
- data,
481
- message
482
- };
483
- }
484
- /**
485
- * Creates a failed authentication result
486
- */
487
- static createFailure(message, error) {
488
- const errorMessage = error instanceof Error ? error.message : typeof error === "string" ? error : error ? String(error) : "Authentication failed";
489
- return {
490
- success: false,
491
- error: errorMessage,
492
- message
493
- };
494
- }
495
- };
496
-
497
- // src/services/auth/patterns/logger/development-logger.ts
498
- var DevelopmentLogger = class {
499
- log(message, data) {
500
- console.log(message, data);
501
- }
502
- warn(message, data) {
503
- console.warn(message, data);
504
- }
505
- error(message, data) {
506
- console.error(message, data);
507
- }
508
- };
509
-
510
- // src/services/auth/patterns/logger/production-logger.ts
511
- var ProductionLogger = class {
512
- log(_message, _data) {
513
- }
514
- warn(_message, _data) {
515
- }
516
- error(_message, _data) {
517
- }
518
- };
519
-
520
- // src/services/auth/patterns/logger/logger-factory.ts
521
- var LoggerFactory = class {
522
- static create(environment) {
523
- const env = environment || process.env.NODE_ENV || "development";
524
- const loggerFactory = this.loggers.get(env) || this.loggers.get("development");
525
- return loggerFactory();
526
- }
527
- };
528
- LoggerFactory.loggers = /* @__PURE__ */ new Map([
529
- ["development", () => new DevelopmentLogger()],
530
- ["production", () => new ProductionLogger()],
531
- ["test", () => new DevelopmentLogger()]
532
- ]);
533
-
534
- // src/services/auth/patterns/strategy/signup-flow-strategy.ts
535
- var SignupFlowStrategy = class {
536
- constructor(authService, tokenManager) {
537
- this.authService = authService;
538
- this.tokenManager = tokenManager;
539
- }
540
- async execute(credentials) {
541
- const loginResult = await this.authService.login(credentials);
542
- if (!loginResult.data.isVerifiedEmail) {
543
- return AuthResultFactory.createFailure("Email verification required");
544
- }
545
- return this.handleSuccessfulAuthentication(loginResult);
546
- }
547
- async handleSuccessfulAuthentication(loginResult) {
548
- if (loginResult.data.accessToken) {
549
- this.tokenManager.saveTokens(
550
- loginResult.data.accessToken,
551
- loginResult.data.refreshToken
552
- );
553
- LoggerFactory.create("development").log("Tokens saved successfully:", {
554
- hasAccessToken: !!loginResult.data.accessToken,
555
- hasRefreshToken: !!loginResult.data.refreshToken,
556
- domainInfo: this.tokenManager.getDomainInfo()
557
- });
558
- const profile = await this.authService.getUserProfile();
559
- return AuthResultFactory.createSuccess("Login successful", __spreadProps(__spreadValues({}, loginResult.data), {
560
- profile: profile.data,
561
- tokenInfo: {
562
- domain: this.tokenManager.getDomainInfo().domain
563
- }
564
- }));
565
- }
566
- return AuthResultFactory.createFailure("Authentication failed - no access token received");
567
- }
568
- };
569
-
570
- // src/services/auth/patterns/strategy/existing-user-login-strategy.ts
571
- var ExistingUserLoginStrategy = class {
572
- constructor(authService, tokenManager) {
573
- this.authService = authService;
574
- this.tokenManager = tokenManager;
575
- }
576
- async execute(credentials) {
577
- const loginResult = await this.authService.login(credentials);
578
- return this.handleSuccessfulAuthentication(loginResult);
579
- }
580
- async handleSuccessfulAuthentication(loginResult) {
581
- if (loginResult.data.accessToken) {
582
- this.tokenManager.saveTokens(
583
- loginResult.data.accessToken,
584
- loginResult.data.refreshToken
585
- );
586
- LoggerFactory.create("development").log("Tokens saved successfully:", {
587
- hasAccessToken: !!loginResult.data.accessToken,
588
- hasRefreshToken: !!loginResult.data.refreshToken,
589
- domainInfo: this.tokenManager.getDomainInfo()
590
- });
591
- const profile = await this.authService.getUserProfile();
592
- return AuthResultFactory.createSuccess("Login successful", __spreadProps(__spreadValues({}, loginResult.data), {
593
- profile: profile.data,
594
- tokenInfo: {
595
- domain: this.tokenManager.getDomainInfo().domain
596
- }
597
- }));
598
- }
599
- return AuthResultFactory.createFailure("Authentication failed - no access token received");
600
- }
601
- };
602
-
603
- // src/services/auth/patterns/strategy/login-flow-strategy-factory.ts
604
- var LoginFlowStrategyFactory = class {
605
- static createStrategy(action, authService, tokenManager) {
606
- const strategyFactory = this.strategies.get(action);
607
- if (!strategyFactory) {
608
- throw new Error(`No strategy found for action: ${action}`);
609
- }
610
- return strategyFactory(authService, tokenManager);
611
- }
612
- };
613
- LoginFlowStrategyFactory.strategies = /* @__PURE__ */ new Map([
614
- ["signup" /* SIGNUP */, (authService, tokenManager) => new SignupFlowStrategy(authService, tokenManager)],
615
- ["login" /* LOGIN */, (authService, tokenManager) => new ExistingUserLoginStrategy(authService, tokenManager)]
616
- ]);
617
-
618
- // src/services/auth/patterns/state/authenticated-state.ts
619
- var AuthenticatedState = class {
620
- async getStatus(tokenManager) {
621
- const authStatus = await this.buildAuthStatus(tokenManager, true);
622
- return AuthResultFactory.createSuccess("User is authenticated", authStatus);
623
- }
624
- async buildAuthStatus(tokenManager, isAuthenticated) {
625
- return {
626
- isAuthenticated,
627
- hasAccessToken: !!await tokenManager.getAccessToken(),
628
- hasRefreshToken: !!await tokenManager.getRefreshToken(),
629
- cookiesSupported: tokenManager.areCookiesSupported(),
630
- domainInfo: tokenManager.getDomainInfo()
631
- };
632
- }
633
- };
634
-
635
- // src/services/auth/patterns/state/unauthenticated-state.ts
636
- var UnauthenticatedState = class {
637
- async getStatus(tokenManager) {
638
- const authStatus = await this.buildAuthStatus(tokenManager, false);
639
- return AuthResultFactory.createFailure("User is not authenticated", authStatus);
640
- }
641
- async buildAuthStatus(tokenManager, isAuthenticated) {
642
- return {
643
- isAuthenticated,
644
- hasAccessToken: !!await tokenManager.getAccessToken(),
645
- hasRefreshToken: !!await tokenManager.getRefreshToken(),
646
- cookiesSupported: tokenManager.areCookiesSupported(),
647
- domainInfo: tokenManager.getDomainInfo()
648
- };
649
- }
650
- };
651
-
652
- // src/services/auth/patterns/state/authentication-status-context.ts
653
- var AuthenticationStatusContext = class {
654
- static async getStatus(tokenManager) {
655
- const isAuthenticated = !!await tokenManager.getAccessToken();
656
- const state = this.states.get(isAuthenticated) || new UnauthenticatedState();
657
- return await state.getStatus(tokenManager);
658
- }
659
- };
660
- AuthenticationStatusContext.states = /* @__PURE__ */ new Map([
661
- [true, new AuthenticatedState()],
662
- [false, new UnauthenticatedState()]
663
- ]);
327
+ GET_USER_PROFILE: "/auth/user/profile"};
664
328
 
665
329
  // src/middlewares/handlers/base-middleware-handler.ts
666
330
  var BaseMiddlewareHandler = class {
@@ -818,9 +482,6 @@ var AuthenticationHandler = class extends BaseMiddlewareHandler {
818
482
  }
819
483
  }
820
484
  };
821
-
822
- // src/middlewares/handlers/middleware-chain.ts
823
- import { NextResponse as NextResponse2 } from "next/server";
824
485
  var MiddlewareChain = class {
825
486
  constructor() {
826
487
  this.handlers = [];
@@ -836,7 +497,7 @@ var MiddlewareChain = class {
836
497
  return result;
837
498
  }
838
499
  }
839
- return NextResponse2.next();
500
+ return NextResponse.next();
840
501
  }
841
502
  };
842
503
 
@@ -855,8 +516,5 @@ async function middleware(req) {
855
516
  const chain = new MiddlewareChain().addHandler(new MethodFilterHandler()).addHandler(new AuthenticationHandler());
856
517
  return await chain.process(context);
857
518
  }
858
- export {
859
- config,
860
- middleware,
861
- middlewareMatcher
862
- };
519
+
520
+ export { config, middleware, middlewareMatcher };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mailsentry-auth",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Next.js 15 authentication package with multi-step auth flow, cross-tab sync, and Zustand state management",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",