@arsedizioni/ars-utils 22.5.13 → 22.5.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,8 +1,8 @@
1
- import { HttpErrorResponse, HttpClient, HttpHeaders } from '@angular/common/http';
1
+ import { HttpResponse, HttpClient } from '@angular/common/http';
2
2
  import * as i0 from '@angular/core';
3
3
  import { inject, signal, Service, DestroyRef } from '@angular/core';
4
4
  import { BroadcastService, SystemUtils } from '@arsedizioni/ars-utils/core';
5
- import { catchError, throwError, EMPTY, of } from 'rxjs';
5
+ import { tap, catchError, throwError, EMPTY, of } from 'rxjs';
6
6
  import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
7
7
  import { catchError as catchError$1, map, finalize } from 'rxjs/operators';
8
8
 
@@ -20,6 +20,15 @@ const EvolutionMessages = {
20
20
  LOGOUT: '§evo-logout'
21
21
  };
22
22
 
23
+ /**
24
+ * The `sessionStorage` key naming which account a tab is working as; its value travels on every
25
+ * request as `X-Evo-Account`.
26
+ *
27
+ * It lives here, and not on `CoreService`, so the auth interceptor can read it without importing a
28
+ * service: the interceptor is a factory precisely so that registering it does not pull the Evolution
29
+ * service graph into the eager bundle.
30
+ */
31
+ const EVOLUTION_ACTIVE_ACCOUNT_KEY = 'evolution_account';
23
32
  var EvolutionServiceFlags;
24
33
  (function (EvolutionServiceFlags) {
25
34
  EvolutionServiceFlags[EvolutionServiceFlags["None"] = 0] = "None";
@@ -483,14 +492,81 @@ var ERPPlace;
483
492
  class EvolutionComplianceContextInfo {
484
493
  }
485
494
 
486
- /** Minimum milliseconds between consecutive error broadcasts (debounce guard). */
495
+ /** Minimum milliseconds between consecutive generic error broadcasts (debounce guard). */
487
496
  const ERROR_DEBOUNCE_MS = 5000;
497
+ /**
498
+ * Returns whether the URL is an authentication endpoint, where a 401 is a normal outcome -- wrong
499
+ * credentials, a rejected code, a refused passkey -- rather than an expired or invalid session.
500
+ *
501
+ * They are called by a visitor who has no session by definition, so answering "la sessione non è
502
+ * più valida" would send them back to the page they are already standing on and hide the real
503
+ * reason they were refused.
504
+ *
505
+ * The list covers the whole Evolution sign-in surface, including the ways in that this library does
506
+ * not itself offer: a host application registers one interceptor for every call it makes to the
507
+ * API, its own passkey and provider flows included.
508
+ * @param url - The request URL.
509
+ * @returns True when the URL is a login / confirm / otp / oauth / passkey endpoint.
510
+ */
511
+ function isAuthEndpoint(url) {
512
+ return url.includes('/session/login')
513
+ || url.includes('/session/confirm')
514
+ || url.includes('/session/otp')
515
+ || url.includes('/session/oauth')
516
+ || url.includes('/passkeys/request-options')
517
+ || url.includes('/passkeys/login');
518
+ }
519
+ /**
520
+ * Resolves the user-facing message for a failed request.
521
+ * @param error - The raw HTTP error object.
522
+ * @param errorStatus - The numeric HTTP status code.
523
+ * @returns A localised message, ready to be rendered as HTML.
524
+ */
525
+ function resolveErrorMessage(error, errorStatus) {
526
+ const message = error?.error?.message ?? error?.message;
527
+ switch (errorStatus) {
528
+ case 0:
529
+ return "In questo momento Evolution non è disponibile. Riprova tra qualche minuto.";
530
+ case 401:
531
+ // A 401 that reaches here comes from a sign-in attempt; anything else was classified as a
532
+ // dead session before this function was called.
533
+ return message ?? "Credenziali non valide o accesso non abilitato.";
534
+ case 403:
535
+ return "Non hai i permessi necessari per eseguire l'operazione richiesta.";
536
+ case 429:
537
+ return message ?? "Troppe richieste consecutive. Aspetta qualche secondo.";
538
+ default:
539
+ return (message ?? "Impossibile eseguire l'operazione richiesta.")
540
+ .replaceAll('\r\n', '</p><p>');
541
+ }
542
+ }
488
543
  /**
489
544
  * Builds the Evolution auth HTTP interceptor.
490
545
  *
491
- * Takes its two inputs — the Evolution base URI and the service flags — directly
492
- * as arguments (captured in the closure), so it never injects EvolutionService:
493
- * registering it does not pull the full Evolution service into the eager bundle.
546
+ * Attaches the credentials, the service-worker bypass and the active-account header to every
547
+ * request aimed at the Evolution API, and turns HTTP failures into broadcast messages -- no UI
548
+ * dependency here.
549
+ *
550
+ * Takes the Evolution base URI and the service flags directly as arguments, captured in the
551
+ * closure, so it never injects `EvolutionService`: registering it does not pull the whole Evolution
552
+ * service into the eager bundle. The debounce and the expiry latch live in that same closure, so
553
+ * two applications registering two interceptors never share them.
554
+ *
555
+ * ## What the statuses mean
556
+ *
557
+ * Aligned with the Evolution API on 2026-08-25. The meaning of the status codes changed with it:
558
+ * failures used to arrive as `200 OK` with `success: false`, and a dead session had to be guessed
559
+ * from a 405, a 410 or any 5xx. Now the status is the truth -- a 401 on an already-authenticated
560
+ * request means the session is gone, a 403 means the permission is missing, a 5xx means the server
561
+ * broke, and those are three different things that used to be one. `invalidateSession` is
562
+ * therefore now, and only, a 401 outside the authentication endpoints.
563
+ *
564
+ * `EvolutionServiceFlags.NotifySystemErrors` still governs one narrow case, and only that one: a
565
+ * 5xx, i.e. a failure of the server rather than of the request. Without the flag it is swallowed,
566
+ * as it always was in this library.
567
+ *
568
+ * Errors are re-thrown rather than swallowed: call sites rely on their `error` callback firing, and
569
+ * on `finalize` clearing a busy dialog.
494
570
  *
495
571
  * Register it with `withInterceptors`:
496
572
  * @example
@@ -504,48 +580,31 @@ const ERROR_DEBOUNCE_MS = 5000;
504
580
  * @returns An `HttpInterceptorFn` ready to register.
505
581
  */
506
582
  function evolutionAuthInterceptor(serviceUri, flags = EvolutionServiceFlags.None) {
507
- // Debounce state, persisted across requests via the factory closure.
583
+ /** Timestamp of the last generic error shown, used to debounce a burst of failures into one. */
508
584
  let lastErrorTime = -1;
509
585
  /**
510
- * Broadcasts a user-friendly message for an Evolution HTTP error, debounced.
511
- * @param error - The raw error value thrown by the HTTP layer.
586
+ * Whether the session-expiry notification has already been sent. Prevents a storm of dialogs when
587
+ * several in-flight requests fail at once; re-armed on the next successful response.
588
+ */
589
+ let sessionExpiredNotified = false;
590
+ /**
591
+ * Broadcasts a generic, user-facing error for an Evolution HTTP failure, debounced.
592
+ * @param error - The raw error value thrown by the HTTP layer.
593
+ * @param errorStatus - The numeric HTTP status code.
512
594
  * @param broadcastService - The broadcast service for the current request.
513
595
  * @returns void
514
596
  */
515
- function handleError(error, broadcastService) {
516
- if (!(error instanceof HttpErrorResponse))
517
- return;
518
- // Only reject errors that explicitly belong to a different service; a missing
519
- // url (network failure on an Evolution request) is allowed through.
520
- if (error.url && !error.url.startsWith(serviceUri))
521
- return;
522
- const errorStatus = error.status;
523
- const shouldNotify = errorStatus === 0 ||
524
- (errorStatus > 0 && errorStatus < 500) ||
525
- (flags & EvolutionServiceFlags.NotifySystemErrors) > 0;
526
- if (!shouldNotify)
597
+ function notifyError(error, errorStatus, broadcastService) {
598
+ // A broken server is the one case the flag still governs.
599
+ if (errorStatus >= 500 && (flags & EvolutionServiceFlags.NotifySystemErrors) === 0)
527
600
  return;
528
601
  const now = Date.now();
529
602
  if (now - lastErrorTime <= ERROR_DEBOUNCE_MS)
530
603
  return;
531
604
  lastErrorTime = now;
532
- let message;
533
- switch (errorStatus) {
534
- case 0:
535
- message = "In questo momento Evolution non è disponibile. Riprova tra qualche minuto.";
536
- break;
537
- case 403:
538
- message = "Non hai i permessi necessari per eseguire l'operazione richiesta.";
539
- break;
540
- default:
541
- message = (error.error?.['message'] ??
542
- error.message ??
543
- "Impossibile eseguire l'operazione richiesta.").replaceAll('\r\n', '</p><p>');
544
- break;
545
- }
546
605
  broadcastService.sendMessage(EvolutionMessages.ERROR, {
547
- invalidateSession: errorStatus === 405 || errorStatus === 410,
548
- message,
606
+ invalidateSession: false,
607
+ message: resolveErrorMessage(error, errorStatus),
549
608
  title: "Errore in Evolution",
550
609
  errorStatus,
551
610
  service: serviceUri
@@ -558,14 +617,47 @@ function evolutionAuthInterceptor(serviceUri, flags = EvolutionServiceFlags.None
558
617
  }
559
618
  const broadcastService = inject(BroadcastService);
560
619
  const authenticatedRequest = request.clone({
620
+ // `withCredentials` is what carries the session: an HttpOnly cookie the application cannot
621
+ // read, cannot forge and cannot forget to send.
561
622
  withCredentials: true,
562
623
  setHeaders: {
563
624
  'ngsw-bypass': 'ngsw-bypass',
564
- 'X-Client-Id': sessionStorage.getItem('evolution_client_id') ?? ''
625
+ // Which of the accounts inside the one session cookie this tab is working as. It replaces
626
+ // the per-tab random `X-Client-Id`, whose only job was to give each tab a cookie of its
627
+ // own -- one per tab ever opened, all of them sent on every request, until the header
628
+ // outgrew what the server accepts. Empty on a tab that has not signed in yet: the API then
629
+ // serves the active account.
630
+ 'X-Evo-Account': sessionStorage.getItem(EVOLUTION_ACTIVE_ACCOUNT_KEY) ?? ''
565
631
  }
566
632
  });
567
- return next(authenticatedRequest).pipe(catchError((error) => {
568
- handleError(error, broadcastService);
633
+ return next(authenticatedRequest).pipe(tap(event => {
634
+ // A response means the session is valid again: re-arm the expiry notifier.
635
+ if (event instanceof HttpResponse) {
636
+ sessionExpiredNotified = false;
637
+ }
638
+ }), catchError((error) => {
639
+ // Which request this was is read from the request, not from `error.url`: a failure with no
640
+ // response -- the browser refusing the connection while the API restarts -- carries no URL
641
+ // at all. Everything that gets here is an Evolution request anyway: the others returned
642
+ // before the pipe was built.
643
+ const errorStatus = parseInt(error?.status ?? '0');
644
+ if (errorStatus === 401 && !isAuthEndpoint(authenticatedRequest.url)) {
645
+ // Expired or invalidated session on an authenticated request. Notified once: several
646
+ // in-flight requests failing together is how a single expiry becomes a wall of dialogs.
647
+ if (!sessionExpiredNotified) {
648
+ sessionExpiredNotified = true;
649
+ broadcastService.sendMessage(EvolutionMessages.ERROR, {
650
+ invalidateSession: true,
651
+ message: "La sessione di lavoro non è più valida.",
652
+ title: "Errore in Evolution",
653
+ errorStatus,
654
+ service: serviceUri
655
+ });
656
+ }
657
+ }
658
+ else {
659
+ notifyError(error, errorStatus, broadcastService);
660
+ }
569
661
  return throwError(() => error);
570
662
  }));
571
663
  };
@@ -587,9 +679,16 @@ class CoreService {
587
679
  constructor() {
588
680
  this.broadcastService = inject(BroadcastService);
589
681
  this._flags = EvolutionServiceFlags.None;
590
- this._loggedIn = signal(false, /* @ts-ignore */
682
+ /**
683
+ * Seeded from the stored context, which means "this browser signed in at some point" and nothing
684
+ * more: the auth cookie is HttpOnly and may have expired while the stored context lived on.
685
+ * `LoginService.initialize` turns the hint into an answer by asking `/session/me`, and the hint
686
+ * is what keeps a visitor who never signed in from calling a route that would answer 401 and
687
+ * raise a dead-session error over the sign-in page.
688
+ */
689
+ this._loggedIn = signal(localStorage.getItem('evolution_context') !== null, /* @ts-ignore */
591
690
  ...(ngDevMode ? [{ debugName: "_loggedIn" }] : /* istanbul ignore next */ []));
592
- /** `true` when the user has an active (non-temporary) session. */
691
+ /** `true` when this browser has a session the API has accepted. */
593
692
  this.loggedIn = this._loggedIn.asReadonly();
594
693
  /** `true` while a login request is in flight. */
595
694
  this.loggingIn = signal(false, /* @ts-ignore */
@@ -642,6 +741,11 @@ class CoreService {
642
741
  }
643
742
  return this._loginInfo;
644
743
  }
744
+ /**
745
+ * Gets the signed-in account.
746
+ * @returns The current {@link EvolutionUserInfo}, or `undefined` when there is no session.
747
+ */
748
+ get user() { return this.loginInfo?.context; }
645
749
  /**
646
750
  * Sets the logged-in state.
647
751
  * @param value - The new logged-in value.
@@ -650,19 +754,26 @@ class CoreService {
650
754
  setLoggedIn(value) {
651
755
  this._loggedIn.set(value);
652
756
  }
757
+ /** The `sessionStorage` key naming which account this tab is working as. */
758
+ static { this.activeAccountKey = EVOLUTION_ACTIVE_ACCOUNT_KEY; }
653
759
  /**
654
- * Records the OAuth provider / remember flag on the login info, creating the
655
- * container if needed.
656
- * @param oauth - The OAuth provider type, if any.
657
- * @param remember - Whether the session should persist across restarts.
760
+ * Records which account this tab is working as, so the interceptor can name it on every request.
761
+ *
762
+ * `sessionStorage` and not `localStorage`: the choice belongs to the tab. One cookie holds every
763
+ * account this browser has open, and two tabs may sit on two different licences while reading
764
+ * that same cookie -- which is what replaced the per-tab `X-Client-Id`, a random UUID that gave
765
+ * every tab ever opened a session cookie of its own until the header outgrew what the server
766
+ * accepts.
767
+ * @param userId - The account to work as, or `undefined` to stop naming one.
658
768
  * @returns void
659
769
  */
660
- setAuthMeta(oauth, remember) {
661
- if (!this._loginInfo) {
662
- this._loginInfo = { context: undefined };
770
+ setActiveAccount(userId) {
771
+ if (userId && userId > 0) {
772
+ sessionStorage.setItem(CoreService.activeAccountKey, String(userId));
773
+ }
774
+ else {
775
+ sessionStorage.removeItem(CoreService.activeAccountKey);
663
776
  }
664
- this._loginInfo.oauth = oauth;
665
- this._loginInfo.remember = remember;
666
777
  }
667
778
  /**
668
779
  * Persists the current login info to `localStorage`.
@@ -694,17 +805,33 @@ class CoreService {
694
805
  this.broadcastService.sendMessage(EvolutionMessages.LOGOUT_COMPLETED);
695
806
  }
696
807
  /**
697
- * Removes Evolution session data from `sessionStorage` and calls {@link reset}.
698
- * @param clearOAuthToken - When true, also removes the stored OAuth2 access token.
808
+ * Clears every trace of the session on this device -- the stored context, the account this tab
809
+ * was working as and the leftovers of the token era -- and then calls {@link reset}. It asks the
810
+ * API nothing: use `LoginService.logout` for that.
811
+ *
812
+ * It takes no argument any more. `clearOAuthToken` decided whether to drop
813
+ * `evolution_oauth_token`, a provider access token this library no longer obtains, stores or
814
+ * sends: the whole exchange happens on the backend.
699
815
  * @returns void
700
816
  */
701
- clear(clearOAuthToken = false) {
817
+ clear() {
818
+ // The stored context goes with the session it describes. It used to be removed by `logout()`
819
+ // alone, so every other way of losing a session -- an expiry, a rejected restore -- left it
820
+ // behind for the next bootstrap to trust.
821
+ localStorage.removeItem('evolution_context');
822
+ // The account this tab was working as. Left behind, the next request would name an account no
823
+ // longer in the cookie: harmless, because the API falls back to the active one, but it would
824
+ // also survive a sign-in as somebody else until the next `completeLogin` overwrote it.
825
+ sessionStorage.removeItem(CoreService.activeAccountKey);
826
+ // Leftovers of the token era, when the session travelled in session storage instead of an
827
+ // HttpOnly cookie, and of the per-tab cookie era. Nothing writes them any more; they are
828
+ // removed so a browser upgrading from the previous version does not keep them for good.
702
829
  sessionStorage.removeItem('evolution_auth');
703
830
  sessionStorage.removeItem('evolution_refresh');
704
831
  sessionStorage.removeItem('evolution_oauth');
705
- if (clearOAuthToken) {
706
- sessionStorage.removeItem('evolution_oauth_token');
707
- }
832
+ sessionStorage.removeItem('evolution_auth_oauth');
833
+ sessionStorage.removeItem('evolution_oauth_token');
834
+ sessionStorage.removeItem('evolution_client_id');
708
835
  this.reset();
709
836
  }
710
837
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: CoreService, deps: [], target: i0.ɵɵFactoryTarget.Service }); }
@@ -715,11 +842,35 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImpor
715
842
  }] });
716
843
 
717
844
  /**
718
- * Authentication service for the Evolution module: login / logout / MFA,
719
- * session bootstrap, connectivity ping and the broadcast handler.
720
- * All session state lives in the private {@link CoreService}; this service
721
- * orchestrates the HTTP flows and re-publishes the parts of core that
722
- * consumers need.
845
+ * Authentication for the Evolution back end: password login, e-mailed code confirmation, account
846
+ * switch, logout and session restore. All session state lives in the private {@link CoreService};
847
+ * this service orchestrates the HTTP flows and re-publishes the parts of core that consumers need.
848
+ *
849
+ * Aligned with the Evolution API on 2026-08-25. Everything goes through `/session/*` and an
850
+ * HttpOnly cookie now: there is no bearer token, no `remember` credential the API can replay, and
851
+ * no provider token acquired by the caller -- the external-provider flow is a full-page redirect
852
+ * handled server-side, and all that reaches this service is the `/session/me` call on the way back.
853
+ *
854
+ * ## What this service no longer offers, and why
855
+ *
856
+ * - **`autoLogin`.** It was `login(undefined, undefined, true)`: a credential-less sign-in that
857
+ * worked only because the API could decrypt a stored password from an `evolution_remember`
858
+ * cookie. `POST /session/login` takes a user and a password and nothing else.
859
+ * - **`autoLogout`.** It wrapped {@link logout} in toasts and a callback, and ran the callback
860
+ * from `complete` -- that is, before the request it was waiting for had said anything. A host
861
+ * that wants a callback subscribes: `logout().subscribe(() => …)`.
862
+ * - **re-login on `LOGIN_CHANGED`.** The handler used to answer that message with a silent
863
+ * `autoLogin`, which is the same replay by another name. The message is still broadcast by hosts
864
+ * that link and unlink Evolution, and it is theirs to act on; this library no longer signs
865
+ * anybody in without being asked.
866
+ * - **the OAuth `Authorization` header, and the per-tab `X-Client-Id`.** The first is server-side
867
+ * now; the second was a random UUID that gave every tab a session cookie of its own. A tab says
868
+ * which of the accounts in the one cookie it is working as with `X-Evo-Account`, written by
869
+ * {@link CoreService.setActiveAccount}.
870
+ *
871
+ * This is a deliberately reduced subset of what the Evolution application itself does: passkeys and
872
+ * the provider redirect are not here. A library whose job is to let another application talk to
873
+ * Evolution signs in with a password; an application that offers the other ways in owns them.
723
874
  */
724
875
  class LoginService {
725
876
  constructor() {
@@ -745,9 +896,14 @@ class LoginService {
745
896
  * @returns The current {@link EvolutionLoginInfo}, or undefined.
746
897
  */
747
898
  get loginInfo() { return this.core.loginInfo; }
748
- /** `true` when the user has an active (non-temporary) session. */
899
+ /**
900
+ * Gets the signed-in account with its licence context.
901
+ * @returns The current {@link EvolutionUserInfo}, or undefined when there is no session.
902
+ */
903
+ get user() { return this.core.user; }
904
+ /** `true` when this browser has a session the API has accepted. */
749
905
  get loggedIn() { return this.core.loggedIn; }
750
- /** `true` while a login request is in flight. */
906
+ /** `true` while an authentication is in flight. */
751
907
  get loggingIn() { return this.core.loggingIn; }
752
908
  // ── Re-published core operations ────────────────────────────────────────────
753
909
  /**
@@ -767,26 +923,26 @@ class LoginService {
767
923
  */
768
924
  reset() { this.core.reset(); }
769
925
  /**
770
- * Removes Evolution session data and resets the state (delegates to core).
771
- * @param clearOAuthToken - When true, also removes the stored OAuth2 access token.
926
+ * Clears every trace of the session on this device without asking the API anything
927
+ * (delegates to core). Use {@link logout} for a real sign-out.
772
928
  * @returns void
773
929
  */
774
- clear(clearOAuthToken = false) { this.core.clear(clearOAuthToken); }
930
+ clear() { this.core.clear(); }
775
931
  // ── Lifecycle ───────────────────────────────────────────────────────────────
776
932
  /**
777
- * Initialises the service with the back-end URI and optional feature flags.
778
- * Must be called once during application bootstrap before any other method.
933
+ * Initialises the service with the back-end URI and optional feature flags, and revalidates a
934
+ * session that survived a page refresh instead of assuming it is still there.
935
+ *
936
+ * Must be called once during application bootstrap, before any other method. What it used to do
937
+ * on a refresh was announce `LOGIN_COMPLETED` on the strength of a value in local storage; the
938
+ * auth cookie is HttpOnly and may have expired while that value lived on, so the claim was never
939
+ * verified and the consumer met the inevitable 401 as "your session just expired" rather than as
940
+ * a bootstrap that never got off the ground.
779
941
  * @param serviceUri - Base URL of the Evolution service.
780
942
  * @param flags - Bitmask of `EvolutionServiceFlags` (default: `None`).
781
943
  * @returns void
782
944
  */
783
945
  initialize(serviceUri, flags = EvolutionServiceFlags.None) {
784
- // Create a unique per-tab client ID if not already set
785
- if (!sessionStorage.getItem('evolution_client_id')) {
786
- sessionStorage.setItem('evolution_client_id', (flags & EvolutionServiceFlags.Embedded) > 0
787
- ? 'embedded'
788
- : SystemUtils.generateUUID());
789
- }
790
946
  this.core.setServiceUri(serviceUri);
791
947
  this.core.setFlags(flags);
792
948
  // Subscribe to broadcast messages (only once)
@@ -799,10 +955,11 @@ class LoginService {
799
955
  this.handleBroadcastMessage(message);
800
956
  });
801
957
  }
802
- // If a session is already active (e.g. after an F5 page refresh), notify consumers
958
+ // A stored context means this browser signed in at some point, never that the session is still
959
+ // alive: the API is the only one that knows, and it is asked here.
803
960
  if (this.core.loggedIn()) {
804
- this.core.loggingIn.set(false);
805
- this.broadcastService.sendMessage(EvolutionMessages.LOGIN_COMPLETED);
961
+ this.core.loggingIn.set(true);
962
+ this.restoreSession();
806
963
  }
807
964
  }
808
965
  /**
@@ -811,47 +968,26 @@ class LoginService {
811
968
  * @returns void
812
969
  */
813
970
  handleBroadcastMessage(message) {
814
- if (message.id === EvolutionMessages.LOGIN_CHANGED) {
815
- const data = message.data;
816
- this.login(undefined, undefined, true, data?.['oauth'], data?.['oauthAccessToken']).subscribe({
817
- next: r => {
818
- if (!r.success) {
819
- if ((this.core.flags & EvolutionServiceFlags.DisplayConnectionStateMessages) > 0) {
820
- this.broadcastService.sendMessage(EvolutionMessages.ERROR, { message: "Le credenziali di accesso sono cambiate o non sono più valide. Esegui un nuovo accesso." });
821
- }
822
- this.broadcastService.sendMessage(EvolutionMessages.LOGIN_FAILED);
823
- }
824
- else {
825
- if ((this.core.flags & EvolutionServiceFlags.DisplayConnectionStateMessages) > 0) {
826
- this.broadcastService.sendMessage(EvolutionMessages.SUCCESS_TOAST, { message: 'Connesso a Evolution', icon: 'power', duration: 1500 });
827
- }
828
- }
829
- },
830
- error: () => { console.error('Evolution non disponibile.'); }
831
- });
971
+ if (message.id !== EvolutionMessages.LOGOUT)
972
+ return;
973
+ if (!this.core.loggedIn()) {
974
+ // No session to close server-side, but the device must still be left clean.
975
+ this.core.clear();
976
+ return;
832
977
  }
833
- else if (message.id === EvolutionMessages.LOGOUT) {
834
- if (this.core.loggedIn()) {
835
- this.logout().subscribe(r => {
836
- if (!r.success) {
837
- if (r.message) {
838
- this.broadcastService.sendMessage(EvolutionMessages.ERROR, { message: "<p>" + r.message + "</p><br><br><hr><p class='small'><i>Per eliminare la configurazione di Evolution accedere a:<br><b>menu > personalizza > collegamenti</b></i></p>" });
839
- }
840
- }
841
- else {
842
- if ((this.core.flags & EvolutionServiceFlags.DisplayConnectionStateMessages) > 0) {
843
- this.broadcastService.sendMessage(EvolutionMessages.SUCCESS_TOAST, { message: 'Disconnesso da Evolution', icon: 'power_off', duration: 1500 });
844
- }
845
- }
846
- });
978
+ this.logout().subscribe(r => {
979
+ if (!r.success) {
980
+ if (r.message) {
981
+ this.broadcastService.sendMessage(EvolutionMessages.ERROR, { message: "<p>" + r.message + "</p><br><br><hr><p class='small'><i>Per eliminare la configurazione di Evolution accedere a:<br><b>menu > personalizza > collegamenti</b></i></p>" });
982
+ }
847
983
  }
848
- else {
849
- this.core.clear();
984
+ else if ((this.core.flags & EvolutionServiceFlags.DisplayConnectionStateMessages) > 0) {
985
+ this.broadcastService.sendMessage(EvolutionMessages.SUCCESS_TOAST, { message: 'Disconnesso da Evolution', icon: 'power_off', duration: 1500 });
850
986
  }
851
- }
987
+ });
852
988
  }
853
989
  /**
854
- * Sends a one-shot ping to the back end to verify connectivity.
990
+ * Sends a one-shot ping to the back end to verify connectivity. Errors are swallowed.
855
991
  * @returns void
856
992
  */
857
993
  ping() {
@@ -860,78 +996,30 @@ class LoginService {
860
996
  .pipe(catchError$1(() => EMPTY))
861
997
  .subscribe();
862
998
  }
999
+ // ── Session ─────────────────────────────────────────────────────────────────
863
1000
  /**
864
- * Performs an automatic login using the credentials already stored in the session.
865
- * @param onSuccess - Optional callback invoked after a successful login.
866
- * @returns `true` (always) — the result is handled via the subscription callbacks.
867
- */
868
- autoLogin(onSuccess) {
869
- this.login(undefined, undefined, true)
870
- .subscribe({
871
- next: r => {
872
- if (!r.success) {
873
- this.broadcastService.sendMessage(EvolutionMessages.ERROR, { message: r.message });
874
- }
875
- else {
876
- if (!r.value?.requiresMfa) {
877
- this.broadcastService.sendMessage(EvolutionMessages.SUCCESS_TOAST, { message: 'Connesso ad Evolution', icon: 'power', duration: 1500 });
878
- }
879
- onSuccess?.();
880
- }
881
- },
882
- error: () => { this.broadcastService.sendMessage(EvolutionMessages.ERROR, { message: "Evolution non disponibile." }); }
883
- });
884
- return true;
885
- }
886
- /**
887
- * Performs an automatic logout, notifying the user when the session ends.
888
- * @param onSuccess - Optional callback invoked after the logout completes.
889
- * @returns void
890
- */
891
- autoLogout(onSuccess) {
892
- this.logout().subscribe({
893
- next: r => {
894
- if (!r.success) {
895
- if (r.message) {
896
- this.broadcastService.sendMessage(EvolutionMessages.ERROR, { message: r.message });
897
- }
898
- this.broadcastService.sendMessage(EvolutionMessages.LOGIN_CHANGED);
899
- }
900
- else {
901
- this.broadcastService.sendMessage(EvolutionMessages.SUCCESS_TOAST, { message: 'Disconnesso da Evolution', icon: 'power_off', duration: 1500 });
902
- }
903
- },
904
- error: () => { },
905
- complete: () => {
906
- onSuccess?.();
907
- }
908
- });
909
- }
910
- /**
911
- * Authenticates the user against the Evolution back end (credential or OAuth2).
912
- * @param email - User e-mail (credential login only; omit for OAuth2).
913
- * @param password - User password (credential login only; omit for OAuth2).
914
- * @param remember - Whether to persist the session across browser restarts.
915
- * @param oauth - OAuth2 provider type, when using federated login.
916
- * @param oauthAccessToken - Bearer token from the OAuth2 provider.
1001
+ * Authenticates the user with an e-mail address and a password, the only credentials
1002
+ * `POST /session/login` accepts.
1003
+ *
1004
+ * On success the session cookie is issued and the context stored, unless the API answers
1005
+ * `requiresMfa`: the device is not a trusted one, a six-digit code has been e-mailed and nothing
1006
+ * about the account is disclosed until {@link confirmIdentity} redeems it.
1007
+ *
1008
+ * A failure is no longer a `200 OK` carrying `success: false`. Wrong credentials come back as a
1009
+ * real 4xx with the message in the envelope, so the `next` branch of the caller is never reached.
1010
+ * @param email - The user's e-mail address.
1011
+ * @param password - The user's password.
917
1012
  * @returns An observable that emits the `ApiResult<EvolutionLoginResult>`.
918
1013
  */
919
- login(email, password, remember, oauth, oauthAccessToken = sessionStorage.getItem('evolution_oauth_token') ?? undefined) {
1014
+ login(email, password) {
1015
+ // Kept for the confirmation step, which has to name the account the code was issued to.
1016
+ this.pendingLoginEmail = email;
920
1017
  return this.httpClient
921
- .post(this.core.serviceUri + '/login2', {
922
- user: oauth ? null : email,
923
- password: oauth ? null : password,
924
- remember,
925
- oauth
926
- }, {
927
- headers: oauth && oauthAccessToken
928
- ? new HttpHeaders().set('Authorization', oauthAccessToken)
929
- : new HttpHeaders()
930
- })
1018
+ .post(this.core.serviceUri + '/session/login', { user: email ?? '', password: password ?? '' })
931
1019
  .pipe(catchError$1(err => throwError(() => err)), map((r) => {
932
1020
  if (r.success) {
933
- this.core.setAuthMeta(oauth, remember);
934
- if (!oauth && r.value?.requiresMfa) {
1021
+ if (r.value?.requiresMfa) {
1022
+ // Notify the login is pending an e-mailed code.
935
1023
  this.broadcastService.sendMessage(EvolutionMessages.LOGIN_PENDING, {});
936
1024
  }
937
1025
  else {
@@ -942,24 +1030,20 @@ class LoginService {
942
1030
  }));
943
1031
  }
944
1032
  /**
945
- * Finalises a successful login by updating the stored context and notifying consumers.
946
- * @param result - The login result payload from the server.
947
- * @returns void
948
- */
949
- completeLogin(result) {
950
- this.core.updateContext(result);
951
- this.core.setLoggedIn(!result.context?.isTemporary);
952
- this.core.loggingIn.set(false);
953
- this.broadcastService.sendMessage(EvolutionMessages.LOGIN_COMPLETED);
954
- }
955
- /**
956
- * Confirms a multi-factor authentication challenge and completes the login.
957
- * @param code - The one-time MFA code entered by the user.
1033
+ * Confirms a pending e-mailed code challenge, which establishes the session and marks this device
1034
+ * as trusted: the next sign-in from it will not ask for a code again.
1035
+ *
1036
+ * The address travels with the code, in the body. The API stores each code under the account it
1037
+ * was issued to, so naming the account is part of redeeming it; and a code in the body is a code
1038
+ * that stays out of the URL, where `POST /login/confirm/{code}` left it for the access logs and
1039
+ * the browser history to keep.
1040
+ * @param code - The one-time confirmation code provided to the user.
1041
+ * @param email - The address the code was sent to; defaults to the one the pending login started with.
958
1042
  * @returns An observable that emits the `ApiResult<EvolutionLoginResult>`.
959
1043
  */
960
- confirmIdentity(code) {
1044
+ confirmIdentity(code, email) {
961
1045
  return this.httpClient
962
- .post(this.core.serviceUri + '/login/confirm/' + code, {})
1046
+ .post(this.core.serviceUri + '/session/confirm', { email: email ?? this.pendingLoginEmail, code: code })
963
1047
  .pipe(catchError$1(err => throwError(() => err)), map((r) => {
964
1048
  if (r.success) {
965
1049
  this.completeLogin(r.value);
@@ -968,33 +1052,119 @@ class LoginService {
968
1052
  }));
969
1053
  }
970
1054
  /**
971
- * Logs the current user out of the back end and clears local session data.
972
- * @param forget - When `true`, instructs the server to discard all stored credentials.
973
- * @returns An observable that emits `ApiResult<unknown>`.
1055
+ * Reads the current session from the server, which resolves it from the auth cookie's claims.
1056
+ * Used to restore the state after a page refresh instead of trusting what local storage holds.
1057
+ *
1058
+ * The route answers with the same `EvolutionLoginResult` a login answers with, built by the same
1059
+ * `ResolveSignInContextAsync`, so a restored session and a fresh one are identical by
1060
+ * construction.
1061
+ * @returns An observable that emits the `ApiResult<EvolutionLoginResult>`.
974
1062
  */
975
- logout(forget = false) {
1063
+ me() {
976
1064
  return this.httpClient
977
- .post(this.core.serviceUri + '/logout/?forget=' + forget, {})
978
- .pipe(finalize(() => {
979
- this.core.clear();
980
- localStorage.removeItem('evolution_context');
981
- }), catchError$1(() => of({ success: false, value: undefined, message: undefined })));
1065
+ .get(this.core.serviceUri + '/session/me')
1066
+ .pipe(map((r) => {
1067
+ if (r?.success) {
1068
+ // No LOGIN_COMPLETED from here: {@link restoreSession} announces it, so a consumer
1069
+ // hears it once whether the session was opened or recovered.
1070
+ this.completeLogin(r.value, false);
1071
+ }
1072
+ return r;
1073
+ }));
1074
+ }
1075
+ /**
1076
+ * Asks `/session/me` whether the restored session is still alive, and announces the login when it
1077
+ * is.
1078
+ *
1079
+ * Nothing is cleared on failure, and that is deliberate: a failure here is not proof of a dead
1080
+ * session -- the API may be unreachable, the proxy may have answered 502, the device may be
1081
+ * offline -- and clearing on any of those would sign the user out with a perfectly valid cookie.
1082
+ * A genuine 401 is a different matter and the interceptor has already reported it.
1083
+ * @returns void
1084
+ */
1085
+ restoreSession() {
1086
+ this.me()
1087
+ .pipe(finalize(() => this.core.loggingIn.set(false)))
1088
+ .subscribe({
1089
+ next: r => {
1090
+ if (r?.success) {
1091
+ this.broadcastService.sendMessage(EvolutionMessages.LOGIN_COMPLETED);
1092
+ }
1093
+ },
1094
+ // Consumed so the rethrown error is not reported a second time as an unhandled one.
1095
+ error: () => { }
1096
+ });
982
1097
  }
983
1098
  /**
984
- * Switches the active session to a different user account while retaining credentials.
1099
+ * Switches this tab to another account of the same person -- same address, same stored password
1100
+ * -- without re-entering credentials.
1101
+ *
1102
+ * The account being left stays open: a switch used to close its session, because each account had
1103
+ * a cookie of its own, and they now share one cookie holding several. What changes here is only
1104
+ * which account THIS tab names on its requests, which {@link completeLogin} records.
985
1105
  * @param id - The user ID to switch to.
986
1106
  * @returns An observable that emits the `ApiResult<EvolutionLoginResult>`.
987
1107
  */
988
1108
  loginSwitch(id) {
989
1109
  return this.httpClient
990
- .post(this.core.serviceUri + '/login/switch', { userId: id })
1110
+ .post(this.core.serviceUri + '/session/switch', { userId: id })
991
1111
  .pipe(catchError$1(err => throwError(() => err)), map((r) => {
992
1112
  if (r.success) {
993
- this.completeLogin(r.value);
1113
+ this.completeLogin(r.value, false);
994
1114
  }
995
1115
  return r;
996
1116
  }));
997
1117
  }
1118
+ /**
1119
+ * Signs out: closes this browser's session on the API and clears the local state whatever the
1120
+ * answer, since there is nothing useful to do with a logout that failed.
1121
+ *
1122
+ * `forget` no longer means "drop the stored credentials" -- there are none to drop. It means
1123
+ * "stop trusting this device", that is clear the MFA cookie, so that the next sign-in from here
1124
+ * is challenged with an e-mailed code again. It also closes one session and not all of them: an
1125
+ * account may hold one per front end, and signing out of this browser must not sign the person
1126
+ * out of their phone.
1127
+ * @param forget - When `true`, the device stops being a trusted one. Defaults to `false`.
1128
+ * @returns An observable that emits `ApiResult<unknown>`.
1129
+ */
1130
+ logout(forget = false) {
1131
+ return this.httpClient
1132
+ .post(this.core.serviceUri + '/session/logout?forget=' + forget, {})
1133
+ .pipe(finalize(() => this.core.clear()),
1134
+ // A logout that failed is still a logout as far as this device is concerned: the local
1135
+ // state has already been cleared by `finalize`, and there is nothing useful a caller could
1136
+ // do with the failure. `message` is empty rather than absent because `ApiResponse` declares
1137
+ // it as a string.
1138
+ catchError$1(() => of({ success: false, value: undefined, message: '' })));
1139
+ }
1140
+ /**
1141
+ * Finalises a login, a code confirmation, an account switch or a session restore: stores the
1142
+ * context, raises the logged-in signal, records which account this tab is working as and
1143
+ * optionally announces `LOGIN_COMPLETED`.
1144
+ *
1145
+ * `loggedIn` is raised unconditionally. It used to be `!result.context?.isTemporary`, and
1146
+ * `isTemporary` was always false -- it is `[NotMapped]` on the API and never filled -- so the
1147
+ * condition never did anything. An expired password is reported by `requiresPasswordChange` and
1148
+ * does not mean there is no session: the cookie has been issued, and it is what the password
1149
+ * change itself travels on.
1150
+ *
1151
+ * `loggingIn` is deliberately left alone. Whoever raised it lowers it -- {@link restoreSession}
1152
+ * for a refresh, the host application for its own sign-in flow -- because lowering it here would
1153
+ * drop the host's splash the instant the response arrived, before anything was on screen.
1154
+ * @param result - The login result payload from the server.
1155
+ * @param notify - Whether to broadcast `LOGIN_COMPLETED`. Defaults to `true`.
1156
+ * @returns void
1157
+ */
1158
+ completeLogin(result, notify = true) {
1159
+ this.core.updateContext(result);
1160
+ this.core.setLoggedIn(true);
1161
+ // Which account THIS TAB is working as. Per tab on purpose: two tabs may sit on two different
1162
+ // licences, and they share the one cookie that holds both.
1163
+ this.core.setActiveAccount(result?.context?.userId);
1164
+ if (notify) {
1165
+ this.broadcastService.sendMessage(EvolutionMessages.LOGIN_COMPLETED);
1166
+ }
1167
+ }
998
1168
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: LoginService, deps: [], target: i0.ɵɵFactoryTarget.Service }); }
999
1169
  static { this.ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.1.3", ngImport: i0, type: LoginService }); }
1000
1170
  }
@@ -1093,7 +1263,15 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImpor
1093
1263
  type: Service
1094
1264
  }] });
1095
1265
 
1096
- /** Account endpoints (the `Links` section): user links management. */
1266
+ /**
1267
+ * The `/account/*` endpoints: the links a user account carries, its settings, its password and the
1268
+ * licence behind it.
1269
+ *
1270
+ * Everything here acts on the account the session names, which is why none of these methods takes
1271
+ * one. The licence refresh is the exception in appearance only: the id in the route is ignored by
1272
+ * the API, which reads the account from the session -- it used to be taken at face value, with no
1273
+ * authorization at all, so any integer returned somebody else's company and expiry.
1274
+ */
1097
1275
  class AccountService {
1098
1276
  constructor() {
1099
1277
  this.httpClient = inject(HttpClient);
@@ -1115,6 +1293,42 @@ class AccountService {
1115
1293
  deleteLink(item) {
1116
1294
  return this.httpClient.post(this.core.serviceUri + '/account/links/delete', item);
1117
1295
  }
1296
+ /**
1297
+ * Persists updated settings for the signed-in account (dashboard, flags).
1298
+ * @param params - The settings to save.
1299
+ * @returns An observable that emits `ApiResult<boolean>`.
1300
+ */
1301
+ updateSettings(params) {
1302
+ return this.httpClient.post(this.core.serviceUri + '/account/settings/save', params);
1303
+ }
1304
+ /**
1305
+ * Changes a password: the signed-in account's own, with `oldPassword`, or somebody else's when an
1306
+ * administrator names it.
1307
+ * @param params - The password change to apply.
1308
+ * @returns An observable that emits `ApiResult<boolean>`.
1309
+ */
1310
+ resetPassword(params) {
1311
+ return this.httpClient.post(this.core.serviceUri + '/account/password/reset', params);
1312
+ }
1313
+ /**
1314
+ * Starts a password recovery, which mails a reset link to the given address.
1315
+ * @param params - The address to recover, with the reCAPTCHA token that guards the route.
1316
+ * @returns An observable that emits `ApiResult<boolean>`.
1317
+ */
1318
+ recoverPassword(params) {
1319
+ return this.httpClient.post(this.core.serviceUri + '/account/password/recover', params);
1320
+ }
1321
+ /**
1322
+ * Re-reads the licence of the signed-in account: company, expiry, quotas and allowed modules.
1323
+ *
1324
+ * Does NOT update the stored context: what the caller does with a fresh licence -- refresh a
1325
+ * settings page, recompute a quota, store it -- is the caller's business, and a service that
1326
+ * quietly rewrote the session context under it would be doing more than it was asked.
1327
+ * @returns An observable that emits `ApiResult<EvolutionUserInfo>`.
1328
+ */
1329
+ refreshLicence() {
1330
+ return this.httpClient.get(this.core.serviceUri + '/account/licenses/refresh/' + (this.core.user?.userId ?? -1));
1331
+ }
1118
1332
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AccountService, deps: [], target: i0.ɵɵFactoryTarget.Service }); }
1119
1333
  static { this.ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.1.3", ngImport: i0, type: AccountService }); }
1120
1334
  }
@@ -1163,9 +1377,18 @@ class EvolutionService {
1163
1377
  * @returns The current {@link EvolutionLoginInfo}, or undefined.
1164
1378
  */
1165
1379
  get loginInfo() { return this.core.loginInfo; }
1166
- /** `true` when the user has an active (non-temporary) session. */
1380
+ /**
1381
+ * Gets the signed-in account with its licence context.
1382
+ * @returns The current {@link EvolutionUserInfo}, or undefined when there is no session.
1383
+ */
1384
+ get user() { return this.core.user; }
1385
+ /**
1386
+ * `true` when this browser has a session the API has accepted. It starts from the stored context
1387
+ * and is confirmed -- or left to the interceptor's 401 handling -- by the `/session/me` call
1388
+ * {@link initialize} makes.
1389
+ */
1167
1390
  get loggedIn() { return this.core.loggedIn; }
1168
- /** `true` while a login request is in flight. */
1391
+ /** `true` while an authentication is in flight. */
1169
1392
  get loggingIn() { return this.core.loggingIn; }
1170
1393
  // ── Lifecycle (the only flattened sub-service methods) ──────────────────────
1171
1394
  /**
@@ -1204,5 +1427,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImpor
1204
1427
  * Generated bundle index. Do not edit.
1205
1428
  */
1206
1429
 
1207
- export { AccountService, ComplianceService, ERPComplianceActivityState, ERPComplianceLawOrigin, ERPComplianceLawState, ERPComplianceLawsSelectionType, ERPComplianceNotificationLimit, ERPComplianceProfileFlags, ERPComplianceProfileRole, ERPComplianceRegisterNotificationType, ERPComplianceRegisterSiteImportOptions, ERPComplianceScope, ERPExportFormat, ERPExportPart, ERPExportSource, ERPExportType, ERPModule, ERPPlace, ERPPlacePermission, ERPRecurrenceFrequencyType, EvolutionComplianceActivityStates, EvolutionComplianceContextInfo, EvolutionComplianceLawChangeStates, EvolutionComplianceLawOrigins, EvolutionComplianceLawStates, EvolutionComplianceNotificationLimits, EvolutionComplianceNotifications, EvolutionComplianceObligationAuthorities, EvolutionComplianceObligationTypes, EvolutionComplianceProfileFlags, EvolutionComplianceProfileRoles, EvolutionComplianceScopes, EvolutionMessages, EvolutionRecurrenceFrequencyTypes, EvolutionService, EvolutionServiceFlags, LoginService, evolutionAuthInterceptor };
1430
+ export { AccountService, ComplianceService, ERPComplianceActivityState, ERPComplianceLawOrigin, ERPComplianceLawState, ERPComplianceLawsSelectionType, ERPComplianceNotificationLimit, ERPComplianceProfileFlags, ERPComplianceProfileRole, ERPComplianceRegisterNotificationType, ERPComplianceRegisterSiteImportOptions, ERPComplianceScope, ERPExportFormat, ERPExportPart, ERPExportSource, ERPExportType, ERPModule, ERPPlace, ERPPlacePermission, ERPRecurrenceFrequencyType, EVOLUTION_ACTIVE_ACCOUNT_KEY, EvolutionComplianceActivityStates, EvolutionComplianceContextInfo, EvolutionComplianceLawChangeStates, EvolutionComplianceLawOrigins, EvolutionComplianceLawStates, EvolutionComplianceNotificationLimits, EvolutionComplianceNotifications, EvolutionComplianceObligationAuthorities, EvolutionComplianceObligationTypes, EvolutionComplianceProfileFlags, EvolutionComplianceProfileRoles, EvolutionComplianceScopes, EvolutionMessages, EvolutionRecurrenceFrequencyTypes, EvolutionService, EvolutionServiceFlags, LoginService, evolutionAuthInterceptor };
1208
1431
  //# sourceMappingURL=arsedizioni-ars-utils-evolution.common.mjs.map