/**
 * Main entry point for the Digital Citizenship proxy.
 */ import * as apicache from "apicache" ; import * as bodyParser from "body-parser" ; import * as express from "express" ; import * as helmet from "helmet" ; import * as morgan from "morgan" ; import * as passport from "passport" ; import { Express } from "express" ; import expressEnforcesSsl = require ( "express-enforces-ssl" ) ; import { NodeEnvironment , NodeEnvironmentEnum } from "italia-ts-commons/lib/environment" ; import { CIDR } from "italia-ts-commons/lib/strings" ; import { QueueClient } from "@azure/storage-queue" ; import { withSpid } from "@pagopa/io-spid-commons" ; import { getSpidStrategyOption } from "@pagopa/io-spid-commons/dist/utils/middleware" ; import * as appInsights from "applicationinsights" ; import { tryCatch2v } from "fp-ts/lib/Either" ; import { isEmpty , StrMap } from "fp-ts/lib/StrMap" ; import { fromLeft , taskEither , tryCatch } from "fp-ts/lib/TaskEither" ; import { ServerInfo } from "../generated/public/ServerInfo" ; import { VersionPerPlatform } from "../generated/public/VersionPerPlatform" ; import { API_CLIENT , appConfig , BONUS_API_CLIENT , CACHE_MAX_AGE_SECONDS , CGN_API_CLIENT , ENABLE_NOTICE_EMAIL_CACHE , ENV , FF_BONUS_ENABLED , FF_CGN_ENABLED , FF_EUCOVIDCERT_ENABLED , getClientProfileRedirectionUrl , IDP_METADATA_REFRESH_INTERVAL_SECONDS , NOTIFICATION_DEFAULT_SUBJECT , NOTIFICATION_DEFAULT_TITLE , NOTIFICATIONS_QUEUE_NAME , NOTIFICATIONS_STORAGE_CONNECTION_STRING , PAGOPA_CLIENT , samlConfig , serviceProviderConfig , SPID_LOG_QUEUE_NAME , SPID_LOG_STORAGE_CONNECTION_STRING , TEST_LOGIN_FISCAL_CODES , TEST_LOGIN_PASSWORD , tokenDurationSecs , URL_TOKEN_STRATEGY , USERS_LOGIN_QUEUE_NAME , USERS_LOGIN_STORAGE_CONNECTION_STRING , TEST_CGN_FISCAL_CODES , CGN_OPERATOR_SEARCH_API_CLIENT , CGN_OPERATOR_SEARCH_CACHE_MAX_AGE_SECONDS , EUCOVIDCERT_API_CLIENT , FF_MIT_VOUCHER_ENABLED , getClientErrorRedirectionUrl , FF_USER_AGE_LIMIT_ENABLED , PECSERVER_CLIENT } from "./config" ; import AuthenticationController from "./controllers/authenticationController" ; import MessagesController from "./controllers/messagesController" ; import NotificationController from "./controllers/notificationController" ; import PagoPAController from "./controllers/pagoPAController" ; import PagoPAProxyController from "./controllers/pagoPAProxyController" ; import ProfileController from "./controllers/profileController" ; import ServicesController from "./controllers/servicesController" ; import SessionController from "./controllers/sessionController" ; import UserMetadataController from "./controllers/userMetadataController" ; import { log } from "./utils/logger" ; import checkIP from "./utils/middleware/checkIP" ; import BonusController from "./controllers/bonusController" ; import CgnController from "./controllers/cgnController" ; import SessionLockController from "./controllers/sessionLockController" ; import { getUserForBPD , getUserForMyPortal } from "./controllers/ssoController" ; import SupportController from "./controllers/supportController" ; import ZendeskController from "./controllers/zendeskController" ; import UserDataProcessingController from "./controllers/userDataProcessingController" ; import BonusService from "./services/bonusService" ; import CgnService from "./services/cgnService" ; import CgnOperatorSearchService from "./services/cgnOperatorSearchService" ; import MessagesService from "./services/messagesService" ; import NotificationService from "./services/notificationService" ; import PagoPAProxyService from "./services/pagoPAProxyService" ; import ProfileService from "./services/profileService" ; import RedisSessionStorage from "./services/redisSessionStorage" ; import RedisUserMetadataStorage from "./services/redisUserMetadataStorage" ; import TokenService from "./services/tokenService" ; import UserDataProcessingService from "./services/userDataProcessingService" ; import UsersLoginLogService from "./services/usersLoginLogService" ; import bearerBPDTokenStrategy from "./strategies/bearerBPDTokenStrategy" ; import bearerMyPortalTokenStrategy from "./strategies/bearerMyPortalTokenStrategy" ; import bearerSessionTokenStrategy from "./strategies/bearerSessionTokenStrategy" ; import bearerWalletTokenStrategy from "./strategies/bearerWalletTokenStrategy" ; import bearerZendeskTokenStrategy from "./strategies/bearerZendeskTokenStrategy" ; import { localStrategy } from "./strategies/localStrategy" ; import { User } from "./types/user" ; import { attachTrackingData , StartupEventName , trackStartupTime } from "./utils/appinsights" ; import { getRequiredENVVar } from "./utils/container" ; import { constantExpressHandler , toExpressHandler } from "./utils/express" ; import { expressErrorMiddleware } from "./utils/middleware/express" ; import { getCurrentBackendVersion , getObjectFromPackageJson } from "./utils/package" ; import { createClusterRedisClient , createSimpleRedisClient } from "./utils/redis" ; import { ResponseErrorDismissed } from "./utils/responses" ; import { makeSpidLogCallback } from "./utils/spid" ; import { TimeTracer } from "./utils/timer" ; import CgnOperatorSearchController from "./controllers/cgnOperatorSearchController" ; import EUCovidCertService from "./services/eucovidcertService" ; import EUCovidCertController from "./controllers/eucovidcertController" ; import MitVoucherController from "./controllers/mitVoucherController" ; const defaultModule = { newApp } ; const cacheDuration = `${ CACHE_MAX_AGE_SECONDS } seconds` ; const cachingMiddleware = apicache . options ( { debug : process . env . NODE_ENV === NodeEnvironmentEnum . DEVELOPMENT || process . env . APICACHE_DEBUG === "true" , defaultDuration : cacheDuration , statusCodes : { include : [ 200 ] } } ) . middleware ; export interface IAppFactoryParameters { readonly env : NodeEnvironment ; readonly appInsightsClient ? : appInsights . TelemetryClient ; readonly allowNotifyIPSourceRange : ReadonlyArray < CIDR > ; readonly allowPagoPAIPSourceRange : ReadonlyArray < CIDR > ; readonly allowMyPortalIPSourceRange : ReadonlyArray < CIDR > ; readonly allowBPDIPSourceRange : ReadonlyArray < CIDR > ; readonly allowSessionHandleIPSourceRange : ReadonlyArray < CIDR > ; readonly allowZendeskIPSourceRange : ReadonlyArray < CIDR > ; readonly authenticationBasePath : string ; readonly APIBasePath : string ; readonly BonusAPIBasePath : string ; readonly PagoPABasePath : string ; readonly MyPortalBasePath : string ; readonly BPDBasePath : string ; readonly CGNAPIBasePath : string ; readonly CGNOperatorSearchAPIBasePath : string ; readonly EUCovidCertBasePath : string ; readonly MitVoucherBasePath : string ; readonly ZendeskBasePath : string ; } export function newApp ( { env , allowNotifyIPSourceRange , allowPagoPAIPSourceRange , allowMyPortalIPSourceRange , allowBPDIPSourceRange , allowSessionHandleIPSourceRange , allowZendeskIPSourceRange , appInsightsClient , authenticationBasePath , APIBasePath , BonusAPIBasePath , PagoPABasePath , MyPortalBasePath , BPDBasePath , CGNAPIBasePath , CGNOperatorSearchAPIBasePath , EUCovidCertBasePath , MitVoucherBasePath , ZendeskBasePath } ) { const REDIS_CLIENT = ENV === NodeEnvironmentEnum . DEVELOPMENT ? createSimpleRedisClient ( process . env . REDIS_URL ) : createClusterRedisClient ( getRequiredENVVar ( "REDIS_URL" ) , process . env . REDIS_PASSWORD , process . env . REDIS_PORT ) ; const SESSION_STORAGE = new RedisSessionStorage ( REDIS_CLIENT , tokenDurationSecs ) ; passport . use ( "bearer.session" , bearerSessionTokenStrategy ( SESSION_STORAGE , attachTrackingData ) ) ; passport . use ( "bearer.wallet" , bearerWalletTokenStrategy ( SESSION_STORAGE ) ) ; passport . use ( "bearer.myportal" , bearerMyPortalTokenStrategy ( SESSION_STORAGE ) ) ; passport . use ( "bearer.bpd" , bearerBPDTokenStrategy ( SESSION_STORAGE ) ) ; passport . use ( "bearer.zendesk" , bearerZendeskTokenStrategy ( SESSION_STORAGE ) ) ; passport . use ( URL_TOKEN_STRATEGY ) ; const authMiddlewares = { bearerBPD : passport . authenticate ( "bearer.bpd" , { session : false } ) , bearerMyPortal : passport . authenticate ( "bearer.myportal" , { session : false } ) , bearerSession : passport . authenticate ( "bearer.session" , { session : false } ) , bearerWallet : passport . authenticate ( "bearer.wallet" , { session : false } ) , bearerZendesk : passport . authenticate ( "bearer.zendesk" , { session : false } ) , local : passport . authenticate ( "local" , { session : false } ) , urlToken : passport . authenticate ( "authtoken" , { session : false } ) } ; const app = express ( ) ; if ( env !== NodeEnvironmentEnum . DEVELOPMENT ) { app . enable ( "trust proxy" ) ; app . use ( /\/((?!ping).)*/ , expressEnforcesSsl ( ) ) ; } app . use ( helmet ( ) ) ; morgan . token ( "detail" , ( _ , res ) => res . locals . detail ) ; morgan . token ( "fiscal_code_short" , ( req , _ ) => User . decode ( req . user ) . map ( user => String ( user . fiscal_code ) . slice ( 0 , 6 ) ) . getOrElse ( "" ) ) ; const obfuscateToken = ( originalUrl ) => originalUrl . replace ( /([?&]token=|[?&]access_token=)([^&]*)/g , "$1REDACTED" ) ; morgan . token ( "obfuscated_url" , ( req , _ ) => obfuscateToken ( req . originalUrl ) ) ; const loggerFormat = ":date[iso] - :method :obfuscated_url :status - :fiscal_code_short - :response-time ms - :detail" ; app . use ( morgan ( loggerFormat ) ) ; app . use ( bodyParser . json ( ) ) ; app . use ( bodyParser . urlencoded ( { extended : true } ) ) ; app . use ( express . static ( "public" ) ) ; app . use ( passport . initialize ( ) ) ; return tryCatch ( async ( ) => { const TOKEN_SERVICE = new TokenService ( ) ; const PROFILE_SERVICE = new ProfileService ( API_CLIENT ) ; const BONUS_SERVICE = new BonusService ( BONUS_API_CLIENT ) ; const CGN_SERVICE = new CgnService ( CGN_API_CLIENT ) ; const CGN_OPERATOR_SEARCH_SERVICE = new CgnOperatorSearchService ( CGN_OPERATOR_SEARCH_API_CLIENT ) ; const EUCOVIDCERT_SERVICE = new EUCovidCertService ( EUCOVIDCERT_API_CLIENT ) ; const USER_DATA_PROCESSING_SERVICE = new UserDataProcessingService ( API_CLIENT ) ; const ERROR_OR_NOTIFICATION_SERVICE = tryCatch2v ( ( ) => new NotificationService ( NOTIFICATIONS_STORAGE_CONNECTION_STRING , NOTIFICATIONS_QUEUE_NAME ) , err => { throw new Error ( `Error initializing Notification Service: [${ err }]` ) ; } ) ; const NOTIFICATION_SERVICE = ERROR_OR_NOTIFICATION_SERVICE . value ; const ERROR_OR_USERS_LOGIN_LOG_SERVICE = tryCatch2v ( ( ) => new UsersLoginLogService ( USERS_LOGIN_STORAGE_CONNECTION_STRING , USERS_LOGIN_QUEUE_NAME ) , err => { throw new Error ( `Error initializing UsersLoginLogService: [${ err }]` ) ; } ) ; const USERS_LOGIN_LOG_SERVICE = ERROR_OR_USERS_LOGIN_LOG_SERVICE . value ; const acsController = new AuthenticationController ( SESSION_STORAGE , TOKEN_SERVICE , getClientProfileRedirectionUrl , getClientErrorRedirectionUrl , PROFILE_SERVICE , NOTIFICATION_SERVICE , USERS_LOGIN_LOG_SERVICE , TEST_LOGIN_FISCAL_CODES , FF_USER_AGE_LIMIT_ENABLED , appInsightsClient ) ; registerPublicRoutes ( app ) ; registerAuthenticationRoutes ( app , authenticationBasePath , acsController , authMiddlewares . bearerSession , authMiddlewares . local ) ; const MESSAGES_SERVICE = new MessagesService ( API_CLIENT , PECSERVER_CLIENT ) ; const PAGOPA_PROXY_SERVICE = new PagoPAProxyService ( PAGOPA_CLIENT ) ; const USER_METADATA_STORAGE = new RedisUserMetadataStorage ( REDIS_CLIENT ) ; registerAPIRoutes ( app , APIBasePath , allowNotifyIPSourceRange , authMiddlewares . urlToken , PROFILE_SERVICE , MESSAGES_SERVICE , NOTIFICATION_SERVICE , SESSION_STORAGE , PAGOPA_PROXY_SERVICE , USER_METADATA_STORAGE , USER_DATA_PROCESSING_SERVICE , TOKEN_SERVICE , authMiddlewares . bearerSession ) ; registerSessionAPIRoutes ( app , APIBasePath , allowSessionHandleIPSourceRange , authMiddlewares . urlToken , SESSION_STORAGE , USER_METADATA_STORAGE ) ; if ( FF_BONUS_ENABLED ) { registerBonusAPIRoutes ( app , BonusAPIBasePath , BONUS_SERVICE , authMiddlewares . bearerSession ) ; } if ( FF_CGN_ENABLED ) { registerCgnAPIRoutes ( app , CGNAPIBasePath , CGN_SERVICE , authMiddlewares . bearerSession ) ; registerCgnOperatorSearchAPIRoutes ( app , CGNOperatorSearchAPIBasePath , CGN_SERVICE , CGN_OPERATOR_SEARCH_SERVICE , authMiddlewares . bearerSession ) ; } if ( FF_EUCOVIDCERT_ENABLED ) { registerEUCovidCertAPIRoutes ( app , EUCovidCertBasePath , EUCOVIDCERT_SERVICE , authMiddlewares . bearerSession ) ; } if ( FF_MIT_VOUCHER_ENABLED ) { registerMitVoucherAPIRoutes ( app , MitVoucherBasePath , TOKEN_SERVICE , authMiddlewares . bearerSession ) ; } registerPagoPARoutes ( app , PagoPABasePath , allowPagoPAIPSourceRange , PROFILE_SERVICE , SESSION_STORAGE , ENABLE_NOTICE_EMAIL_CACHE , authMiddlewares . bearerWallet ) ; registerMyPortalRoutes ( app , MyPortalBasePath , allowMyPortalIPSourceRange , authMiddlewares . bearerMyPortal ) ; registerBPDRoutes ( app , BPDBasePath , allowBPDIPSourceRange , authMiddlewares . bearerBPD ) ; registerZendeskRoutes ( app , ZendeskBasePath , allowZendeskIPSourceRange , PROFILE_SERVICE , TOKEN_SERVICE , authMiddlewares . bearerZendesk ) ; return { acsController , app } ; } , err => new Error ( `Error on app routes setup: [${ err }]` ) ) . chain ( _ => { const spidQueueClient = new QueueClient ( SPID_LOG_STORAGE_CONNECTION_STRING , SPID_LOG_QUEUE_NAME ) ; const spidLogCallback = makeSpidLogCallback ( spidQueueClient ) ; const timer = TimeTracer ( ) ; return tryCatch ( ( ) => withSpid ( { acs : _ . acsController . acs . bind ( _ . acsController ) , app : _ . app , appConfig : { ... appConfig , eventTraker : event => { appInsightsClient ?. trackEvent ( { name : event . name , properties : { type : event . type , ... event . data } } ) ; } } , doneCb : spidLogCallback , logout : _ . acsController . slo . bind ( _ . acsController ) , redisClient : REDIS_CLIENT , samlConfig , serviceProviderConfig } ) . run ( ) , err => new Error ( `Unexpected error initizing Spid Login: [${ err }]` ) ) . map ( withSpidApp => ( { ... withSpidApp , spidConfigTime : timer . getElapsedMilliseconds ( ) } ) ) ; } ) . map ( _ => { if ( appInsightsClient ) { trackStartupTime ( appInsightsClient , StartupEventName . SPID , _ . spidConfigTime ) ; } log . info ( `Spid init time: %sms` , _ . spidConfigTime . toString ( ) ) ; const startIdpMetadataRefreshTimer = setInterval ( ( ) => _ . idpMetadataRefresher ( ) . run ( ) . catch ( e => { log . error ( "loadSpidStrategyOptions|error:%s" , e ) ; } ) , IDP_METADATA_REFRESH_INTERVAL_SECONDS * 1000 ) ; _ . app . on ( "server:stop" , ( ) => clearInterval ( startIdpMetadataRefreshTimer ) ) ; return _ . app ; } ) . chain ( _ => { const spidStrategyOption = getSpidStrategyOption ( _ ) ; if ( isEmpty ( new StrMap ( spidStrategyOption ?. idp || { } ) ) ) { log . error ( "Fatal error during application start. Cannot get IDPs metadata." ) ; return fromLeft < Error , Express > ( new Error ( "Fatal error during application start. Cannot get IDPs metadata." ) ) ; } return taskEither . of ( _ ) ; } ) . map ( _ => { _ . use ( expressErrorMiddleware ) ; return _ ; } ) . getOrElseL ( err => { app . emit ( "server:stop" ) ; throw err ; } ) . run ( ) ; } function registerPagoPARoutes ( app , basePath , allowPagoPAIPSourceRange , profileService , sessionStorage , enableNoticeEmailCache , bearerWalletTokenAuth ) { const pagopaController = new PagoPAController ( profileService , sessionStorage , enableNoticeEmailCache ) ; app . get ( `${ basePath }/user` , checkIP ( allowPagoPAIPSourceRange ) , bearerWalletTokenAuth , toExpressHandler ( pagopaController . getUser , pagopaController ) ) ; } function registerMyPortalRoutes ( app , basePath , allowMyPortalIPSourceRange , bearerMyPortalTokenAuth ) { app . get ( `${ basePath }/user` , checkIP ( allowMyPortalIPSourceRange ) , bearerMyPortalTokenAuth , toExpressHandler ( getUserForMyPortal ) ) ; } function registerBPDRoutes ( app , basePath , allowBPDIPSourceRange , bearerBPDTokenAuth ) { app . get ( `${ basePath }/user` , checkIP ( allowBPDIPSourceRange ) , bearerBPDTokenAuth , toExpressHandler ( getUserForBPD ) ) ; } function registerZendeskRoutes ( app , basePath , allowZendeskIPSourceRange , profileService , tokenService , bearerZendeskTokenAuth ) { const zendeskController = new ZendeskController ( profileService , tokenService ) ; app . post ( `${ basePath }/jwt` , checkIP ( allowZendeskIPSourceRange ) , bearerZendeskTokenAuth , toExpressHandler ( zendeskController . getZendeskSupportToken , zendeskController ) ) ; } function registerEUCovidCertAPIRoutes ( app , basePath , eucovidcertService , bearerSessionTokenAuth ) { const eucovidCertController = new EUCovidCertController ( eucovidcertService ) ; app . post ( `${ basePath }/certificate` , bearerSessionTokenAuth , toExpressHandler ( eucovidCertController . getEUCovidCertificate , eucovidCertController ) ) ; } function registerMitVoucherAPIRoutes ( app , basePath , tokenService , bearerSessionTokenAuth ) { const mitVoucherController = new MitVoucherController ( tokenService ) ; app . get ( `${ basePath }/token` , bearerSessionTokenAuth , toExpressHandler ( mitVoucherController . getMitVoucherToken , mitVoucherController ) ) ; } function registerAPIRoutes ( app , basePath , allowNotifyIPSourceRange , urlTokenAuth , profileService , messagesService , notificationService , sessionStorage , pagoPaProxyService , userMetadataStorage , userDataProcessingService , tokenService , bearerSessionTokenAuth ) { const profileController = new ProfileController ( profileService , sessionStorage ) ; const messagesController = new MessagesController ( messagesService , tokenService ) ; const servicesController = new ServicesController ( messagesService ) ; const notificationController = new NotificationController ( notificationService , sessionStorage , { notificationDefaultSubject : NOTIFICATION_DEFAULT_SUBJECT , notificationDefaultTitle : NOTIFICATION_DEFAULT_TITLE } ) ; const sessionController = new SessionController ( sessionStorage , tokenService ) ; const pagoPAProxyController = new PagoPAProxyController ( pagoPaProxyService ) ; const userMetadataController = new UserMetadataController ( userMetadataStorage ) ; const userDataProcessingController = new UserDataProcessingController ( userDataProcessingService ) ; const supportController = new SupportController ( tokenService ) ; app . get ( `${ basePath }/profile` , bearerSessionTokenAuth , toExpressHandler ( profileController . getProfile , profileController ) ) ; app . get ( `${ basePath }/api-profile` , bearerSessionTokenAuth , toExpressHandler ( profileController . getApiProfile , profileController ) ) ; app . post ( `${ basePath }/profile` , bearerSessionTokenAuth , toExpressHandler ( profileController . updateProfile , profileController ) ) ; app . post ( `${ basePath }/email-validation-process` , bearerSessionTokenAuth , toExpressHandler ( profileController . startEmailValidationProcess , profileController ) ) ; app . get ( `${ basePath }/user-metadata` , bearerSessionTokenAuth , toExpressHandler ( userMetadataController . getMetadata , userMetadataController ) ) ; app . post ( `${ basePath }/user-metadata` , bearerSessionTokenAuth , toExpressHandler ( userMetadataController . upsertMetadata , userMetadataController ) ) ; app . post ( `${ basePath }/user-data-processing` , bearerSessionTokenAuth , toExpressHandler ( userDataProcessingController . upsertUserDataProcessing , userDataProcessingController ) ) ; app . get ( `${ basePath }/user-data-processing/:choice` , bearerSessionTokenAuth , toExpressHandler ( userDataProcessingController . getUserDataProcessing , userDataProcessingController ) ) ; app . delete ( `${ basePath }/user-data-processing/:choice` , bearerSessionTokenAuth , toExpressHandler ( userDataProcessingController . abortUserDataProcessing , userDataProcessingController ) ) ; app . get ( `${ basePath }/messages` , bearerSessionTokenAuth , toExpressHandler ( messagesController . getMessagesByUser , messagesController ) ) ; app . get ( `${ basePath }/messages/:id` , bearerSessionTokenAuth , toExpressHandler ( messagesController . getMessage , messagesController ) ) ; app . get ( `${ basePath }/legal-messages/:id` , bearerSessionTokenAuth , toExpressHandler ( messagesController . getLegalMessage , messagesController ) ) ; app . get ( `${ basePath }/legal-messages/:legal_message_unique_id/attachments/:attachment_id` , bearerSessionTokenAuth , toExpressHandler ( messagesController . getLegalMessageAttachment , messagesController ) ) ; app . get ( `${ basePath }/services/:id` , bearerSessionTokenAuth , cachingMiddleware ( ) , toExpressHandler ( servicesController . getService , servicesController ) ) ; app . get ( `${ basePath }/services/:id/preferences` , bearerSessionTokenAuth , toExpressHandler ( servicesController . getServicePreferences , servicesController ) ) ; app . post ( `${ basePath }/services/:id/preferences` , bearerSessionTokenAuth , toExpressHandler ( servicesController . upsertServicePreferences , servicesController ) ) ; app . get ( `${ basePath }/services` , bearerSessionTokenAuth , cachingMiddleware ( ) , toExpressHandler ( servicesController . getVisibleServices , servicesController ) ) ; app . put ( `${ basePath }/installations/:id` , bearerSessionTokenAuth , toExpressHandler ( notificationController . createOrUpdateInstallation , notificationController ) ) ; app . post ( `${ basePath }/notify` , checkIP ( allowNotifyIPSourceRange ) , urlTokenAuth , toExpressHandler ( notificationController . notify , notificationController ) ) ; app . get ( `${ basePath }/session` , bearerSessionTokenAuth , toExpressHandler ( sessionController . getSessionState , sessionController ) ) ; app . get ( `${ basePath }/sessions` , bearerSessionTokenAuth , toExpressHandler ( sessionController . listSessions , sessionController ) ) ; app . get ( `${ basePath }/payment-requests/:rptId` , bearerSessionTokenAuth , toExpressHandler ( pagoPAProxyController . getPaymentInfo , pagoPAProxyController ) ) ; app . post ( `${ basePath }/payment-activations` , bearerSessionTokenAuth , toExpressHandler ( pagoPAProxyController . activatePayment , pagoPAProxyController ) ) ; app . get ( `${ basePath }/payment-activations/:codiceContestoPagamento` , bearerSessionTokenAuth , toExpressHandler ( pagoPAProxyController . getActivationStatus , pagoPAProxyController ) ) ; app . get ( `${ basePath }/token/support` , bearerSessionTokenAuth , toExpressHandler ( supportController . getSupportToken , supportController ) ) ; } function registerSessionAPIRoutes ( app , basePath , allowSessionHandleIPSourceRange , urlTokenAuth , sessionStorage , userMetadataStorage ) { const sessionLockController = new SessionLockController ( sessionStorage , userMetadataStorage ) ; app . post ( `${ basePath }/sessions/:fiscal_code/lock` , checkIP ( allowSessionHandleIPSourceRange ) , urlTokenAuth , toExpressHandler ( sessionLockController . lockUserSession , sessionLockController ) ) ; app . delete ( `${ basePath }/sessions/:fiscal_code/lock` , checkIP ( allowSessionHandleIPSourceRange ) , urlTokenAuth , toExpressHandler ( sessionLockController . unlockUserSession , sessionLockController ) ) ; } function registerCgnAPIRoutes ( app , basePath , cgnService , bearerSessionTokenAuth ) { const cgnController = new CgnController ( cgnService , TEST_CGN_FISCAL_CODES ) ; app . get ( `${ basePath }/status` , bearerSessionTokenAuth , toExpressHandler ( cgnController . getCgnStatus , cgnController ) ) ; app . get ( `${ basePath }/eyca/status` , bearerSessionTokenAuth , toExpressHandler ( cgnController . getEycaStatus , cgnController ) ) ; app . post ( `${ basePath }/activation` , bearerSessionTokenAuth , toExpressHandler ( cgnController . startCgnActivation , cgnController ) ) ; app . get ( `${ basePath }/activation` , bearerSessionTokenAuth , toExpressHandler ( cgnController . getCgnActivation , cgnController ) ) ; app . post ( `${ basePath }/eyca/activation` , bearerSessionTokenAuth , toExpressHandler ( cgnController . startEycaActivation , cgnController ) ) ; app . get ( `${ basePath }/eyca/activation` , bearerSessionTokenAuth , toExpressHandler ( cgnController . getEycaActivation , cgnController ) ) ; app . post ( `${ basePath }/otp` , bearerSessionTokenAuth , toExpressHandler ( cgnController . generateOtp , cgnController ) ) ; } function registerCgnOperatorSearchAPIRoutes ( app , basePath , cgnService , cgnOperatorSearchService , bearerSessionTokenAuth ) { const cgnOperatorController = new CgnOperatorSearchController ( cgnService , cgnOperatorSearchService ) ; const cgnOperatorSearchCacheDuration = `${ CGN_OPERATOR_SEARCH_CACHE_MAX_AGE_SECONDS } seconds` ; const cgnOperatorSearchCachingMiddleware = apicache . options ( { debug : process . env . NODE_ENV === NodeEnvironmentEnum . DEVELOPMENT || process . env . APICACHE_DEBUG === "true" , defaultDuration : cgnOperatorSearchCacheDuration , statusCodes : { include : [ 200 ] } } ) . middleware ; app . get ( `${ basePath }/merchants/:merchantId` , bearerSessionTokenAuth , cgnOperatorSearchCachingMiddleware ( ) , toExpressHandler ( cgnOperatorController . getMerchant , cgnOperatorController ) ) ; app . post ( `${ basePath }/online-merchants` , bearerSessionTokenAuth , toExpressHandler ( cgnOperatorController . getOnlineMerchants , cgnOperatorController ) ) ; app . post ( `${ basePath }/offline-merchants` , bearerSessionTokenAuth , toExpressHandler ( cgnOperatorController . getOfflineMerchants , cgnOperatorController ) ) ; app . get ( `${ basePath }/discount-bucket-code/:discountId` , bearerSessionTokenAuth , toExpressHandler ( cgnOperatorController . getDiscountBucketCode , cgnOperatorController ) ) ; } function registerBonusAPIRoutes ( app , basePath , bonusService , bearerSessionTokenAuth ) { const bonusController = new BonusController ( bonusService ) ; app . post ( `${ basePath }/bonus/vacanze/eligibility` , bearerSessionTokenAuth , constantExpressHandler ( ResponseErrorDismissed ) ) ; app . get ( `${ basePath }/bonus/vacanze/eligibility` , bearerSessionTokenAuth , toExpressHandler ( bonusController . getBonusEligibilityCheck , bonusController ) ) ; app . get ( `${ basePath }/bonus/vacanze/activations/:bonus_id` , bearerSessionTokenAuth , toExpressHandler ( bonusController . getLatestBonusActivationById , bonusController ) ) ; app . get ( `${ basePath }/bonus/vacanze/activations` , bearerSessionTokenAuth , toExpressHandler ( bonusController . getAllBonusActivations , bonusController ) ) ; app . post ( `${ basePath }/bonus/vacanze/activations` , bearerSessionTokenAuth , constantExpressHandler ( ResponseErrorDismissed ) ) ; } function registerAuthenticationRoutes ( app , authBasePath , acsController , bearerSessionTokenAuth , localAuth ) { TEST_LOGIN_PASSWORD . map ( testLoginPassword => { passport . use ( "local" , localStrategy ( TEST_LOGIN_FISCAL_CODES , testLoginPassword ) ) ; app . post ( `${ authBasePath }/test-login` , localAuth , toExpressHandler ( req => acsController . acsTest ( req . user ) , acsController ) ) ; } ) ; app . post ( `${ authBasePath }/logout` , bearerSessionTokenAuth , toExpressHandler ( acsController . logout , acsController ) ) ; app . get ( `${ authBasePath }/user-identity` , bearerSessionTokenAuth , toExpressHandler ( acsController . getUserIdentity , acsController ) ) ; } function registerPublicRoutes ( app ) { const version = getCurrentBackendVersion ( ) ; const minAppVersion = getObjectFromPackageJson ( "min_app_version" , VersionPerPlatform ) ; const minAppVersionPagoPa = getObjectFromPackageJson ( "min_app_version_pagopa" , VersionPerPlatform ) ; app . get ( "/info" , ( _ , res ) => { const serverInfo = { min_app_version : minAppVersion . getOrElse ( { android : "UNKNOWN" , ios : "UNKNOWN" } ) , min_app_version_pagopa : minAppVersionPagoPa . getOrElse ( { android : "UNKNOWN" , ios : "UNKNOWN" } ) , version } ; res . status ( 200 ) . json ( serverInfo ) ; } ) ; app . get ( "/ping" , ( _ , res ) => res . status ( 200 ) . send ( "ok" ) ) ; } export default defaultModule ;