diff --git a/.env.sample b/.env.sample index 9c71d50a9..7ec91d7d8 100644 --- a/.env.sample +++ b/.env.sample @@ -15,6 +15,7 @@ DB_TYPE=mysql REDIS_PORT=6379 REDIS_HOST=cache +CACHE_TYPE=redis ######## # KEYS # diff --git a/.pnp.cjs b/.pnp.cjs index 879183c10..13c687cf9 100755 --- a/.pnp.cjs +++ b/.pnp.cjs @@ -4623,8 +4623,11 @@ const RAW_RUNTIME_STATE = "packageDependencies": [\ ["@standardnotes/home-server", "workspace:packages/home-server"],\ ["@standardnotes/api-gateway", "workspace:packages/api-gateway"],\ + ["@standardnotes/auth-server", "workspace:packages/auth"],\ + ["@standardnotes/domain-core", "workspace:packages/domain-core"],\ ["@types/cors", "npm:2.8.13"],\ ["@types/express", "npm:4.17.17"],\ + ["@types/prettyjson", "npm:0.0.30"],\ ["@typescript-eslint/eslint-plugin", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:5.59.2"],\ ["@typescript-eslint/parser", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:5.59.2"],\ ["cors", "npm:2.8.5"],\ @@ -4637,6 +4640,7 @@ const RAW_RUNTIME_STATE = ["inversify", "npm:6.0.1"],\ ["inversify-express-utils", "npm:6.4.3"],\ ["prettier", "npm:2.8.8"],\ + ["prettyjson", "npm:1.2.5"],\ ["reflect-metadata", "npm:0.1.13"],\ ["typescript", "patch:typescript@npm%3A5.0.4#optional!builtin::version=5.0.4&hash=b5f058"],\ ["winston", "npm:3.8.2"]\ diff --git a/packages/api-gateway/src/Bootstrap/Container.ts b/packages/api-gateway/src/Bootstrap/Container.ts index 150e83022..1aa08b2bc 100644 --- a/packages/api-gateway/src/Bootstrap/Container.ts +++ b/packages/api-gateway/src/Bootstrap/Container.ts @@ -9,19 +9,23 @@ import { Timer, TimerInterface } from '@standardnotes/time' import { Env } from './Env' import { TYPES } from './Types' import { AuthMiddleware } from '../Controller/AuthMiddleware' -import { HttpServiceInterface } from '../Service/Http/HttpServiceInterface' -import { HttpService } from '../Service/Http/HttpService' +import { ServiceProxyInterface } from '../Service/Http/ServiceProxyInterface' +import { HttpServiceProxy } from '../Service/Http/HttpServiceProxy' import { SubscriptionTokenAuthMiddleware } from '../Controller/SubscriptionTokenAuthMiddleware' import { CrossServiceTokenCacheInterface } from '../Service/Cache/CrossServiceTokenCacheInterface' import { RedisCrossServiceTokenCache } from '../Infra/Redis/RedisCrossServiceTokenCache' import { WebSocketAuthMiddleware } from '../Controller/WebSocketAuthMiddleware' import { InMemoryCrossServiceTokenCache } from '../Infra/InMemory/InMemoryCrossServiceTokenCache' +import { DirectCallServiceProxy } from '../Service/Proxy/DirectCallServiceProxy' +import { ServiceContainerInterface } from '@standardnotes/domain-core' +import { EndpointResolverInterface } from '../Service/Resolver/EndpointResolverInterface' +import { EndpointResolver } from '../Service/Resolver/EndpointResolver' // eslint-disable-next-line @typescript-eslint/no-var-requires const newrelicFormatter = require('@newrelic/winston-enricher') export class ContainerConfigLoader { - async load(): Promise { + async load(serviceContainer?: ServiceContainerInterface): Promise { const env: Env = new Env() env.load() @@ -57,14 +61,14 @@ export class ContainerConfigLoader { container.bind(TYPES.HTTPClient).toConstantValue(axios.create()) // env vars - container.bind(TYPES.SYNCING_SERVER_JS_URL).toConstantValue(env.get('SYNCING_SERVER_JS_URL')) - container.bind(TYPES.AUTH_SERVER_URL).toConstantValue(env.get('AUTH_SERVER_URL')) + container.bind(TYPES.SYNCING_SERVER_JS_URL).toConstantValue(env.get('SYNCING_SERVER_JS_URL', true)) + container.bind(TYPES.AUTH_SERVER_URL).toConstantValue(env.get('AUTH_SERVER_URL', true)) container.bind(TYPES.REVISIONS_SERVER_URL).toConstantValue(env.get('REVISIONS_SERVER_URL', true)) container.bind(TYPES.EMAIL_SERVER_URL).toConstantValue(env.get('EMAIL_SERVER_URL', true)) container.bind(TYPES.PAYMENTS_SERVER_URL).toConstantValue(env.get('PAYMENTS_SERVER_URL', true)) container.bind(TYPES.FILES_SERVER_URL).toConstantValue(env.get('FILES_SERVER_URL', true)) - container.bind(TYPES.AUTH_JWT_SECRET).toConstantValue(env.get('AUTH_JWT_SECRET')) container.bind(TYPES.WEB_SOCKET_SERVER_URL).toConstantValue(env.get('WEB_SOCKET_SERVER_URL', true)) + container.bind(TYPES.AUTH_JWT_SECRET).toConstantValue(env.get('AUTH_JWT_SECRET')) container .bind(TYPES.HTTP_CALL_TIMEOUT) .toConstantValue(env.get('HTTP_CALL_TIMEOUT', true) ? +env.get('HTTP_CALL_TIMEOUT', true) : 60_000) @@ -79,7 +83,16 @@ export class ContainerConfigLoader { .to(SubscriptionTokenAuthMiddleware) // Services - container.bind(TYPES.HTTPService).to(HttpService) + if (isConfiguredForHomeServer) { + if (!serviceContainer) { + throw new Error('Service container is required when configured for home server') + } + container + .bind(TYPES.ServiceProxy) + .toConstantValue(new DirectCallServiceProxy(serviceContainer)) + } else { + container.bind(TYPES.ServiceProxy).to(HttpServiceProxy) + } container.bind(TYPES.Timer).toConstantValue(new Timer()) if (isConfiguredForHomeServer) { @@ -89,6 +102,9 @@ export class ContainerConfigLoader { } else { container.bind(TYPES.CrossServiceTokenCache).to(RedisCrossServiceTokenCache) } + container + .bind(TYPES.EndpointResolver) + .toConstantValue(new EndpointResolver(isConfiguredForHomeServer)) return container } diff --git a/packages/api-gateway/src/Bootstrap/Service.ts b/packages/api-gateway/src/Bootstrap/Service.ts new file mode 100644 index 000000000..9778244d1 --- /dev/null +++ b/packages/api-gateway/src/Bootstrap/Service.ts @@ -0,0 +1,37 @@ +import { + ControllerContainerInterface, + ServiceContainerInterface, + ServiceIdentifier, + ServiceInterface, +} from '@standardnotes/domain-core' + +import { ContainerConfigLoader } from './Container' + +export class Service implements ServiceInterface { + constructor( + private serviceContainer: ServiceContainerInterface, + private controllerContainer: ControllerContainerInterface, + ) { + this.serviceContainer.register(ServiceIdentifier.create(ServiceIdentifier.NAMES.ApiGateway).getValue(), this) + } + + async handleRequest(request: never, response: never, endpointOrMethodIdentifier: string): Promise { + const method = this.controllerContainer.get(endpointOrMethodIdentifier) + + if (!method) { + throw new Error(`Method ${endpointOrMethodIdentifier} not found`) + } + + return method(request, response) + } + + async getContainer(): Promise { + const config = new ContainerConfigLoader() + + return config.load(this.serviceContainer) + } + + getId(): ServiceIdentifier { + return ServiceIdentifier.create(ServiceIdentifier.NAMES.Auth).getValue() + } +} diff --git a/packages/api-gateway/src/Bootstrap/Types.ts b/packages/api-gateway/src/Bootstrap/Types.ts index f517fabe0..c4c5957a6 100644 --- a/packages/api-gateway/src/Bootstrap/Types.ts +++ b/packages/api-gateway/src/Bootstrap/Types.ts @@ -19,9 +19,10 @@ export const TYPES = { WebSocketAuthMiddleware: Symbol.for('WebSocketAuthMiddleware'), SubscriptionTokenAuthMiddleware: Symbol.for('SubscriptionTokenAuthMiddleware'), // Services - HTTPService: Symbol.for('HTTPService'), + ServiceProxy: Symbol.for('ServiceProxy'), CrossServiceTokenCache: Symbol.for('CrossServiceTokenCache'), Timer: Symbol.for('Timer'), + EndpointResolver: Symbol.for('EndpointResolver'), } // export default TYPES diff --git a/packages/api-gateway/src/Bootstrap/index.ts b/packages/api-gateway/src/Bootstrap/index.ts index 6d4b6a89c..b80889bf5 100644 --- a/packages/api-gateway/src/Bootstrap/index.ts +++ b/packages/api-gateway/src/Bootstrap/index.ts @@ -1,3 +1,3 @@ export * from './Container' -export * from './Env' +export * from './Service' export * from './Types' diff --git a/packages/api-gateway/src/Controller/LegacyController.ts b/packages/api-gateway/src/Controller/LegacyController.ts index efd78b7a9..fca3ae7d7 100644 --- a/packages/api-gateway/src/Controller/LegacyController.ts +++ b/packages/api-gateway/src/Controller/LegacyController.ts @@ -2,14 +2,14 @@ import { Request, Response } from 'express' import { inject } from 'inversify' import { controller, all, BaseHttpController, httpPost, httpGet, results, httpDelete } from 'inversify-express-utils' import { TYPES } from '../Bootstrap/Types' -import { HttpServiceInterface } from '../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../Service/Http/ServiceProxyInterface' @controller('') export class LegacyController extends BaseHttpController { private AUTH_ROUTES: Map private PARAMETRIZED_AUTH_ROUTES: Map - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor(@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface) { super() this.AUTH_ROUTES = new Map([ diff --git a/packages/api-gateway/src/Controller/v1/ActionsController.ts b/packages/api-gateway/src/Controller/v1/ActionsController.ts index c2d9382cf..827e776f3 100644 --- a/packages/api-gateway/src/Controller/v1/ActionsController.ts +++ b/packages/api-gateway/src/Controller/v1/ActionsController.ts @@ -2,37 +2,51 @@ import { Request, Response } from 'express' import { inject } from 'inversify' import { BaseHttpController, controller, httpGet, httpPost } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1') export class ActionsController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private serviceProxy: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @httpPost('/login') async login(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/sign_in', request.body) + await this.serviceProxy.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/sign_in'), + request.body, + ) } @httpGet('/login-params') async loginParams(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/params', request.body) + await this.serviceProxy.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'auth/params'), + request.body, + ) } @httpPost('/logout') async logout(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/sign_out', request.body) - } - - @httpGet('/auth/methods') - async methods(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/methods', request.body) + await this.serviceProxy.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/sign_out'), + request.body, + ) } @httpGet('/unsubscribe/:token') async emailUnsubscribe(request: Request, response: Response): Promise { - await this.httpService.callEmailServer( + await this.serviceProxy.callEmailServer( request, response, `subscriptions/actions/unsubscribe/${request.params.token}`, @@ -42,16 +56,31 @@ export class ActionsController extends BaseHttpController { @httpPost('/recovery/codes', TYPES.AuthMiddleware) async recoveryCodes(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/recovery/codes', request.body) + await this.serviceProxy.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/recovery/codes'), + request.body, + ) } @httpPost('/recovery/login') async recoveryLogin(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/recovery/login', request.body) + await this.serviceProxy.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/recovery/login'), + request.body, + ) } @httpPost('/recovery/login-params') async recoveryParams(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/recovery/params', request.body) + await this.serviceProxy.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/recovery/params'), + request.body, + ) } } diff --git a/packages/api-gateway/src/Controller/v1/AuthenticatorsController.ts b/packages/api-gateway/src/Controller/v1/AuthenticatorsController.ts index 1e88e5018..d03612e7f 100644 --- a/packages/api-gateway/src/Controller/v1/AuthenticatorsController.ts +++ b/packages/api-gateway/src/Controller/v1/AuthenticatorsController.ts @@ -3,11 +3,15 @@ import { Request, Response } from 'express' import { controller, BaseHttpController, httpPost, httpGet, httpDelete } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1/authenticators') export class AuthenticatorsController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @@ -16,14 +20,23 @@ export class AuthenticatorsController extends BaseHttpController { await this.httpService.callAuthServer( request, response, - `authenticators/${request.params.authenticatorId}`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'DELETE', + 'authenticators/:authenticatorId', + request.params.authenticatorId, + ), request.body, ) } @httpGet('/', TYPES.AuthMiddleware) async list(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'authenticators/', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'authenticators/'), + request.body, + ) } @httpGet('/generate-registration-options', TYPES.AuthMiddleware) @@ -31,7 +44,7 @@ export class AuthenticatorsController extends BaseHttpController { await this.httpService.callAuthServer( request, response, - 'authenticators/generate-registration-options', + this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'authenticators/generate-registration-options'), request.body, ) } @@ -41,13 +54,18 @@ export class AuthenticatorsController extends BaseHttpController { await this.httpService.callAuthServer( request, response, - 'authenticators/generate-authentication-options', + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'authenticators/generate-authentication-options'), request.body, ) } @httpPost('/verify-registration', TYPES.AuthMiddleware) async verifyRegistration(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'authenticators/verify-registration', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'authenticators/verify-registration'), + request.body, + ) } } diff --git a/packages/api-gateway/src/Controller/v1/FilesController.ts b/packages/api-gateway/src/Controller/v1/FilesController.ts index e21d5f21d..2977cf500 100644 --- a/packages/api-gateway/src/Controller/v1/FilesController.ts +++ b/packages/api-gateway/src/Controller/v1/FilesController.ts @@ -3,16 +3,25 @@ import { inject } from 'inversify' import { BaseHttpController, controller, httpPost } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1/files') export class FilesController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @httpPost('/valet-tokens', TYPES.AuthMiddleware) async createToken(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'valet-tokens', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'valet-tokens'), + request.body, + ) } } diff --git a/packages/api-gateway/src/Controller/v1/InvoicesController.ts b/packages/api-gateway/src/Controller/v1/InvoicesController.ts index f29c4004a..d24eceb2f 100644 --- a/packages/api-gateway/src/Controller/v1/InvoicesController.ts +++ b/packages/api-gateway/src/Controller/v1/InvoicesController.ts @@ -2,11 +2,11 @@ import { Request, Response } from 'express' import { BaseHttpController, controller, httpPost } from 'inversify-express-utils' import { inject } from 'inversify' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' @controller('/v1') export class InvoicesController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor(@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface) { super() } diff --git a/packages/api-gateway/src/Controller/v1/ItemsController.ts b/packages/api-gateway/src/Controller/v1/ItemsController.ts index ad46cb15e..c12c0c2df 100644 --- a/packages/api-gateway/src/Controller/v1/ItemsController.ts +++ b/packages/api-gateway/src/Controller/v1/ItemsController.ts @@ -2,26 +2,45 @@ import { Request, Response } from 'express' import { inject } from 'inversify' import { BaseHttpController, controller, httpGet, httpPost } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1/items', TYPES.AuthMiddleware) export class ItemsController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @httpPost('/') async sync(request: Request, response: Response): Promise { - await this.httpService.callSyncingServer(request, response, 'items/sync', request.body) + await this.httpService.callSyncingServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'items/sync'), + request.body, + ) } @httpPost('/check-integrity') async checkIntegrity(request: Request, response: Response): Promise { - await this.httpService.callSyncingServer(request, response, 'items/check-integrity', request.body) + await this.httpService.callSyncingServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'items/check-integrity'), + request.body, + ) } @httpGet('/:uuid') async getItem(request: Request, response: Response): Promise { - await this.httpService.callSyncingServer(request, response, `items/${request.params.uuid}`, request.body) + await this.httpService.callSyncingServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'items/:uuid', request.params.uuid), + request.body, + ) } } diff --git a/packages/api-gateway/src/Controller/v1/OfflineController.ts b/packages/api-gateway/src/Controller/v1/OfflineController.ts index 2e12c0bf5..cde152e0e 100644 --- a/packages/api-gateway/src/Controller/v1/OfflineController.ts +++ b/packages/api-gateway/src/Controller/v1/OfflineController.ts @@ -3,22 +3,36 @@ import { inject } from 'inversify' import { BaseHttpController, controller, httpGet, httpPost } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1/offline') export class OfflineController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @httpGet('/features') async getOfflineFeatures(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'offline/features', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'offline/features'), + request.body, + ) } @httpPost('/subscription-tokens') async createOfflineSubscriptionToken(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'offline/subscription-tokens', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'offline/subscription-tokens'), + request.body, + ) } @httpPost('/payments/stripe-setup-intent') diff --git a/packages/api-gateway/src/Controller/v1/PaymentsController.ts b/packages/api-gateway/src/Controller/v1/PaymentsController.ts index 8aba03c97..053d1b89a 100644 --- a/packages/api-gateway/src/Controller/v1/PaymentsController.ts +++ b/packages/api-gateway/src/Controller/v1/PaymentsController.ts @@ -2,11 +2,11 @@ import { Request, Response } from 'express' import { inject } from 'inversify' import { all, BaseHttpController, controller, httpDelete, httpGet, httpPost } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' @controller('/v1') export class PaymentsController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor(@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface) { super() } diff --git a/packages/api-gateway/src/Controller/v1/SessionsController.ts b/packages/api-gateway/src/Controller/v1/SessionsController.ts index a2b473c45..6a171b1ee 100644 --- a/packages/api-gateway/src/Controller/v1/SessionsController.ts +++ b/packages/api-gateway/src/Controller/v1/SessionsController.ts @@ -2,33 +2,55 @@ import { Request, Response } from 'express' import { inject } from 'inversify' import { BaseHttpController, controller, httpDelete, httpGet, httpPost } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1/sessions') export class SessionsController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @httpGet('/', TYPES.AuthMiddleware) async getSessions(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'sessions') + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'sessions'), + ) } @httpDelete('/:uuid', TYPES.AuthMiddleware) async deleteSession(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'session', { - uuid: request.params.uuid, - }) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('DELETE', 'session'), + { + uuid: request.params.uuid, + }, + ) } @httpDelete('/', TYPES.AuthMiddleware) async deleteSessions(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'session/all') + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('DELETE', 'session/all'), + ) } @httpPost('/refresh') async refreshSession(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'session/refresh', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'session/refresh'), + request.body, + ) } } diff --git a/packages/api-gateway/src/Controller/v1/SubscriptionInvitesController.ts b/packages/api-gateway/src/Controller/v1/SubscriptionInvitesController.ts index 0a7bbdc40..c067a59bf 100644 --- a/packages/api-gateway/src/Controller/v1/SubscriptionInvitesController.ts +++ b/packages/api-gateway/src/Controller/v1/SubscriptionInvitesController.ts @@ -3,31 +3,61 @@ import { inject } from 'inversify' import { BaseHttpController, controller, httpDelete, httpGet, httpPost } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1/subscription-invites') export class SubscriptionInvitesController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @httpPost('/', TYPES.AuthMiddleware) async inviteToSubscriptionSharing(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'subscription-invites', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'subscription-invites'), + request.body, + ) } @httpGet('/', TYPES.AuthMiddleware) async listInvites(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'subscription-invites', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'subscription-invites'), + request.body, + ) } @httpDelete('/:inviteUuid', TYPES.AuthMiddleware) async cancelSubscriptionSharing(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, `subscription-invites/${request.params.inviteUuid}`) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'DELETE', + 'subscription-invites/:inviteUuid', + request.params.inviteUuid, + ), + ) } @httpPost('/:inviteUuid/accept', TYPES.AuthMiddleware) async acceptInvite(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, `subscription-invites/${request.params.inviteUuid}/accept`) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'POST', + 'subscription-invites/:inviteUuid/accept', + request.params.inviteUuid, + ), + ) } } diff --git a/packages/api-gateway/src/Controller/v1/TokensController.ts b/packages/api-gateway/src/Controller/v1/TokensController.ts index 2e2c53cc0..3384561b6 100644 --- a/packages/api-gateway/src/Controller/v1/TokensController.ts +++ b/packages/api-gateway/src/Controller/v1/TokensController.ts @@ -3,16 +3,25 @@ import { inject } from 'inversify' import { BaseHttpController, controller, httpPost } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1/subscription-tokens') export class TokensController extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @httpPost('/', TYPES.AuthMiddleware) async createToken(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'subscription-tokens', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'subscription-tokens'), + request.body, + ) } } diff --git a/packages/api-gateway/src/Controller/v1/UsersController.ts b/packages/api-gateway/src/Controller/v1/UsersController.ts index d4beb3a02..0ddd77d34 100644 --- a/packages/api-gateway/src/Controller/v1/UsersController.ts +++ b/packages/api-gateway/src/Controller/v1/UsersController.ts @@ -13,13 +13,15 @@ import { } from 'inversify-express-utils' import { Logger } from 'winston' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' import { TokenAuthenticationMethod } from '../TokenAuthenticationMethod' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1/users') export class UsersController extends BaseHttpController { constructor( - @inject(TYPES.HTTPService) private httpService: HttpServiceInterface, + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, @inject(TYPES.Logger) private logger: Logger, ) { super() @@ -37,7 +39,12 @@ export class UsersController extends BaseHttpController { @httpPatch('/:userId', TYPES.AuthMiddleware) async updateUser(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, `users/${request.params.userId}`, request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('PATCH', 'users/:userId', request.params.userId), + request.body, + ) } @httpPut('/:userUuid/password', TYPES.AuthMiddleware) @@ -49,7 +56,11 @@ export class UsersController extends BaseHttpController { await this.httpService.callAuthServer( request, response, - `users/${request.params.userUuid}/attributes/credentials`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'PUT', + 'users/:userUuid/attributes/credentials', + request.params.userUuid, + ), request.body, ) } @@ -59,14 +70,22 @@ export class UsersController extends BaseHttpController { await this.httpService.callAuthServer( request, response, - `users/${request.params.userUuid}/attributes/credentials`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'PUT', + 'users/:userUuid/attributes/credentials', + request.params.userUuid, + ), request.body, ) } @httpGet('/:userId/params', TYPES.AuthMiddleware) async getKeyParams(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/params') + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'auth/params'), + ) } @all('/:userId/mfa', TYPES.AuthMiddleware) @@ -76,22 +95,49 @@ export class UsersController extends BaseHttpController { @httpPost('/:userUuid/integrations/listed', TYPES.AuthMiddleware) async createListedAccount(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'listed', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'listed'), + request.body, + ) } @httpPost('/') async register(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth'), + request.body, + ) } @httpGet('/:userUuid/settings', TYPES.AuthMiddleware) async listSettings(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/settings`) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'GET', + 'users/:userUuid/settings', + request.params.userUuid, + ), + ) } @httpPut('/:userUuid/settings', TYPES.AuthMiddleware) async putSetting(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/settings`, request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'PUT', + 'users/:userUuid/settings', + request.params.userUuid, + ), + request.body, + ) } @httpGet('/:userUuid/settings/:settingName', TYPES.AuthMiddleware) @@ -99,7 +145,12 @@ export class UsersController extends BaseHttpController { await this.httpService.callAuthServer( request, response, - `users/${request.params.userUuid}/settings/${request.params.settingName}`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'GET', + 'users/:userUuid/settings/:settingName', + request.params.userUuid, + request.params.settingName, + ), ) } @@ -108,7 +159,12 @@ export class UsersController extends BaseHttpController { await this.httpService.callAuthServer( request, response, - `users/${request.params.userUuid}/settings/${request.params.settingName}`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'DELETE', + 'users/:userUuid/settings/:settingName', + request.params.userUuid, + request.params.settingName, + ), request.body, ) } @@ -118,29 +174,62 @@ export class UsersController extends BaseHttpController { await this.httpService.callAuthServer( request, response, - `users/${request.params.userUuid}/subscription-settings/${request.params.subscriptionSettingName}`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'GET', + 'users/:userUuid/subscription-settings/:subscriptionSettingName', + request.params.userUuid, + request.params.subscriptionSettingName, + ), ) } @httpGet('/:userUuid/features', TYPES.AuthMiddleware) async getFeatures(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/features`) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'GET', + 'users/:userUuid/features', + request.params.userUuid, + ), + ) } @httpGet('/:userUuid/subscription', TYPES.AuthMiddleware) async getSubscription(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/subscription`) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'GET', + 'users/:userUuid/subscription', + request.params.userUuid, + ), + ) } @httpGet('/subscription', TYPES.SubscriptionTokenAuthMiddleware) async getSubscriptionBySubscriptionToken(request: Request, response: Response): Promise { if (response.locals.tokenAuthenticationMethod === TokenAuthenticationMethod.OfflineSubscriptionToken) { - await this.httpService.callAuthServer(request, response, 'offline/users/subscription') + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('GET', 'offline/users/subscription'), + ) return } - await this.httpService.callAuthServer(request, response, `users/${response.locals.userUuid}/subscription`) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'GET', + 'users/:userUuid/subscription', + response.locals.userUuid, + ), + ) } @httpDelete('/:userUuid', TYPES.AuthMiddleware) @@ -150,6 +239,15 @@ export class UsersController extends BaseHttpController { @httpPost('/:userUuid/requests', TYPES.AuthMiddleware) async submitRequest(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, `users/${request.params.userUuid}/requests`, request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'POST', + 'users/:userUuid/requests', + request.params.userUuid, + ), + request.body, + ) } } diff --git a/packages/api-gateway/src/Controller/v1/WebSocketsController.ts b/packages/api-gateway/src/Controller/v1/WebSocketsController.ts index a4249e4e7..811ce496a 100644 --- a/packages/api-gateway/src/Controller/v1/WebSocketsController.ts +++ b/packages/api-gateway/src/Controller/v1/WebSocketsController.ts @@ -4,12 +4,14 @@ import { BaseHttpController, controller, httpDelete, httpPost } from 'inversify- import { Logger } from 'winston' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v1/sockets') export class WebSocketsController extends BaseHttpController { constructor( - @inject(TYPES.HTTPService) private httpService: HttpServiceInterface, + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, @inject(TYPES.Logger) private logger: Logger, ) { super() @@ -17,7 +19,12 @@ export class WebSocketsController extends BaseHttpController { @httpPost('/tokens', TYPES.AuthMiddleware) async createWebSocketConnectionToken(request: Request, response: Response): Promise { - await this.httpService.callWebSocketServer(request, response, 'sockets/tokens', request.body) + await this.httpService.callWebSocketServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'sockets/tokens'), + request.body, + ) } @httpPost('/connections', TYPES.WebSocketAuthMiddleware) @@ -33,7 +40,11 @@ export class WebSocketsController extends BaseHttpController { await this.httpService.callWebSocketServer( request, response, - `sockets/connections/${request.headers.connectionid}`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'POST', + 'sockets/connections/:connectionId', + request.headers.connectionid as string, + ), request.body, ) } @@ -51,7 +62,11 @@ export class WebSocketsController extends BaseHttpController { await this.httpService.callWebSocketServer( request, response, - `sockets/connections/${request.headers.connectionid}`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'DELETE', + 'sockets/connections/:connectionId', + request.headers.connectionid as string, + ), request.body, ) } diff --git a/packages/api-gateway/src/Controller/v2/ActionsControllerV2.ts b/packages/api-gateway/src/Controller/v2/ActionsControllerV2.ts index 310ebf26c..8a1af1475 100644 --- a/packages/api-gateway/src/Controller/v2/ActionsControllerV2.ts +++ b/packages/api-gateway/src/Controller/v2/ActionsControllerV2.ts @@ -3,21 +3,35 @@ import { inject } from 'inversify' import { BaseHttpController, controller, httpPost } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v2') export class ActionsControllerV2 extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @httpPost('/login') async login(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/pkce_sign_in', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/pkce_sign_in'), + request.body, + ) } @httpPost('/login-params') async loginParams(request: Request, response: Response): Promise { - await this.httpService.callAuthServer(request, response, 'auth/pkce_params', request.body) + await this.httpService.callAuthServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier('POST', 'auth/pkce_params'), + request.body, + ) } } diff --git a/packages/api-gateway/src/Controller/v2/PaymentsControllerV2.ts b/packages/api-gateway/src/Controller/v2/PaymentsControllerV2.ts index d39ab5a2f..ad48dcc3c 100644 --- a/packages/api-gateway/src/Controller/v2/PaymentsControllerV2.ts +++ b/packages/api-gateway/src/Controller/v2/PaymentsControllerV2.ts @@ -2,11 +2,11 @@ import { Request, Response } from 'express' import { BaseHttpController, controller, httpDelete, httpGet, httpPatch, httpPost } from 'inversify-express-utils' import { inject } from 'inversify' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' @controller('/v2') export class PaymentsControllerV2 extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor(@inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface) { super() } diff --git a/packages/api-gateway/src/Controller/v2/RevisionsControllerV2.ts b/packages/api-gateway/src/Controller/v2/RevisionsControllerV2.ts index 95fe19a95..e4e72b412 100644 --- a/packages/api-gateway/src/Controller/v2/RevisionsControllerV2.ts +++ b/packages/api-gateway/src/Controller/v2/RevisionsControllerV2.ts @@ -3,17 +3,29 @@ import { inject } from 'inversify' import { BaseHttpController, controller, httpDelete, httpGet } from 'inversify-express-utils' import { TYPES } from '../../Bootstrap/Types' -import { HttpServiceInterface } from '../../Service/Http/HttpServiceInterface' +import { ServiceProxyInterface } from '../../Service/Http/ServiceProxyInterface' +import { EndpointResolverInterface } from '../../Service/Resolver/EndpointResolverInterface' @controller('/v2/items/:itemUuid/revisions', TYPES.AuthMiddleware) export class RevisionsControllerV2 extends BaseHttpController { - constructor(@inject(TYPES.HTTPService) private httpService: HttpServiceInterface) { + constructor( + @inject(TYPES.ServiceProxy) private httpService: ServiceProxyInterface, + @inject(TYPES.EndpointResolver) private endpointResolver: EndpointResolverInterface, + ) { super() } @httpGet('/') async getRevisions(request: Request, response: Response): Promise { - await this.httpService.callRevisionsServer(request, response, `items/${request.params.itemUuid}/revisions`) + await this.httpService.callRevisionsServer( + request, + response, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'GET', + 'items/:itemUuid/revisions', + request.params.itemUuid, + ), + ) } @httpGet('/:id') @@ -21,7 +33,12 @@ export class RevisionsControllerV2 extends BaseHttpController { await this.httpService.callRevisionsServer( request, response, - `items/${request.params.itemUuid}/revisions/${request.params.id}`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'GET', + 'items/:itemUuid/revisions/:id', + request.params.itemUuid, + request.params.id, + ), ) } @@ -30,7 +47,12 @@ export class RevisionsControllerV2 extends BaseHttpController { await this.httpService.callRevisionsServer( request, response, - `items/${request.params.itemUuid}/revisions/${request.params.id}`, + this.endpointResolver.resolveEndpointOrMethodIdentifier( + 'DELETE', + 'items/:itemUuid/revisions/:id', + request.params.itemUuid, + request.params.id, + ), ) } } diff --git a/packages/api-gateway/src/Infra/index.ts b/packages/api-gateway/src/Infra/index.ts deleted file mode 100644 index 750d1ef77..000000000 --- a/packages/api-gateway/src/Infra/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './InMemory/InMemoryCrossServiceTokenCache' -export * from './Redis/RedisCrossServiceTokenCache' diff --git a/packages/api-gateway/src/Service/Http/HttpService.ts b/packages/api-gateway/src/Service/Http/HttpServiceProxy.ts similarity index 82% rename from packages/api-gateway/src/Service/Http/HttpService.ts rename to packages/api-gateway/src/Service/Http/HttpServiceProxy.ts index 64effdba4..80cb07c0d 100644 --- a/packages/api-gateway/src/Service/Http/HttpService.ts +++ b/packages/api-gateway/src/Service/Http/HttpServiceProxy.ts @@ -6,10 +6,10 @@ import { Logger } from 'winston' import { TYPES } from '../../Bootstrap/Types' import { CrossServiceTokenCacheInterface } from '../Cache/CrossServiceTokenCacheInterface' -import { HttpServiceInterface } from './HttpServiceInterface' +import { ServiceProxyInterface } from './ServiceProxyInterface' @injectable() -export class HttpService implements HttpServiceInterface { +export class HttpServiceProxy implements ServiceProxyInterface { constructor( @inject(TYPES.HTTPClient) private httpClient: AxiosInstance, @inject(TYPES.AUTH_SERVER_URL) private authServerUrl: string, @@ -27,16 +27,16 @@ export class HttpService implements HttpServiceInterface { async callSyncingServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { - await this.callServer(this.syncingServerJsUrl, request, response, endpoint, payload) + await this.callServer(this.syncingServerJsUrl, request, response, endpointOrMethodIdentifier, payload) } async callRevisionsServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { if (!this.revisionsServerUrl) { @@ -44,31 +44,37 @@ export class HttpService implements HttpServiceInterface { return } - await this.callServer(this.revisionsServerUrl, request, response, endpoint, payload) + await this.callServer(this.revisionsServerUrl, request, response, endpointOrMethodIdentifier, payload) } async callLegacySyncingServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { - await this.callServerWithLegacyFormat(this.syncingServerJsUrl, request, response, endpoint, payload) + await this.callServerWithLegacyFormat( + this.syncingServerJsUrl, + request, + response, + endpointOrMethodIdentifier, + payload, + ) } async callAuthServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { - await this.callServer(this.authServerUrl, request, response, endpoint, payload) + await this.callServer(this.authServerUrl, request, response, endpointOrMethodIdentifier, payload) } async callEmailServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { if (!this.emailServerUrl) { @@ -77,13 +83,13 @@ export class HttpService implements HttpServiceInterface { return } - await this.callServer(this.emailServerUrl, request, response, endpoint, payload) + await this.callServer(this.emailServerUrl, request, response, endpointOrMethodIdentifier, payload) } async callWebSocketServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { if (!this.webSocketServerUrl) { @@ -92,13 +98,13 @@ export class HttpService implements HttpServiceInterface { return } - await this.callServer(this.webSocketServerUrl, request, response, endpoint, payload) + await this.callServer(this.webSocketServerUrl, request, response, endpointOrMethodIdentifier, payload) } async callPaymentsServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { if (!this.paymentsServerUrl) { @@ -106,23 +112,29 @@ export class HttpService implements HttpServiceInterface { return } - await this.callServerWithLegacyFormat(this.paymentsServerUrl, request, response, endpoint, payload) + await this.callServerWithLegacyFormat( + this.paymentsServerUrl, + request, + response, + endpointOrMethodIdentifier, + payload, + ) } async callAuthServerWithLegacyFormat( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { - await this.callServerWithLegacyFormat(this.authServerUrl, request, response, endpoint, payload) + await this.callServerWithLegacyFormat(this.authServerUrl, request, response, endpointOrMethodIdentifier, payload) } private async getServerResponse( serverUrl: string, request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { try { @@ -142,7 +154,7 @@ export class HttpService implements HttpServiceInterface { headers['X-Auth-Offline-Token'] = response.locals.offlineAuthToken } - this.logger.debug(`Calling [${request.method}] ${serverUrl}/${endpoint}, + this.logger.debug(`Calling [${request.method}] ${serverUrl}/${endpointOrMethodIdentifier}, headers: ${JSON.stringify(headers)}, query: ${JSON.stringify(request.query)}, payload: ${JSON.stringify(payload)}`) @@ -150,7 +162,7 @@ export class HttpService implements HttpServiceInterface { const serviceResponse = await this.httpClient.request({ method: request.method as Method, headers, - url: `${serverUrl}/${endpoint}`, + url: `${serverUrl}/${endpointOrMethodIdentifier}`, data: this.getRequestData(payload), maxContentLength: Infinity, maxBodyLength: Infinity, @@ -172,7 +184,9 @@ export class HttpService implements HttpServiceInterface { ? JSON.stringify((error as AxiosError).response?.data) : (error as Error).message - this.logger.error(`Could not pass the request to ${serverUrl}/${endpoint} on underlying service: ${errorMessage}`) + this.logger.error( + `Could not pass the request to ${serverUrl}/${endpointOrMethodIdentifier} on underlying service: ${errorMessage}`, + ) this.logger.debug('Response error: %O', (error as AxiosError).response ?? error) @@ -195,10 +209,16 @@ export class HttpService implements HttpServiceInterface { serverUrl: string, request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { - const serviceResponse = await this.getServerResponse(serverUrl, request, response, endpoint, payload) + const serviceResponse = await this.getServerResponse( + serverUrl, + request, + response, + endpointOrMethodIdentifier, + payload, + ) this.logger.debug(`Response from underlying server: ${JSON.stringify(serviceResponse?.data)}, headers: ${JSON.stringify(serviceResponse?.headers)}`) @@ -233,10 +253,16 @@ export class HttpService implements HttpServiceInterface { serverUrl: string, request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise { - const serviceResponse = await this.getServerResponse(serverUrl, request, response, endpoint, payload) + const serviceResponse = await this.getServerResponse( + serverUrl, + request, + response, + endpointOrMethodIdentifier, + payload, + ) if (!serviceResponse) { return diff --git a/packages/api-gateway/src/Service/Http/HttpServiceInterface.ts b/packages/api-gateway/src/Service/Http/ServiceProxyInterface.ts similarity index 75% rename from packages/api-gateway/src/Service/Http/HttpServiceInterface.ts rename to packages/api-gateway/src/Service/Http/ServiceProxyInterface.ts index b13eaa920..f1ce049d0 100644 --- a/packages/api-gateway/src/Service/Http/HttpServiceInterface.ts +++ b/packages/api-gateway/src/Service/Http/ServiceProxyInterface.ts @@ -1,52 +1,52 @@ import { Request, Response } from 'express' -export interface HttpServiceInterface { +export interface ServiceProxyInterface { callEmailServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise callAuthServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise callAuthServerWithLegacyFormat( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise callRevisionsServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise callSyncingServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise callLegacySyncingServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise callPaymentsServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise callWebSocketServer( request: Request, response: Response, - endpoint: string, + endpointOrMethodIdentifier: string, payload?: Record | string, ): Promise } diff --git a/packages/api-gateway/src/Service/Proxy/DirectCallServiceProxy.ts b/packages/api-gateway/src/Service/Proxy/DirectCallServiceProxy.ts new file mode 100644 index 000000000..3062d20cd --- /dev/null +++ b/packages/api-gateway/src/Service/Proxy/DirectCallServiceProxy.ts @@ -0,0 +1,74 @@ +import { Request, Response } from 'express' + +import { ServiceProxyInterface } from '../Http/ServiceProxyInterface' +import { ServiceContainerInterface, ServiceIdentifier } from '@standardnotes/domain-core' + +export class DirectCallServiceProxy implements ServiceProxyInterface { + constructor(private serviceContainer: ServiceContainerInterface) {} + + async callEmailServer(_request: Request, _response: Response, _endpointOrMethodIdentifier: string): Promise { + throw new Error('Email server is not available.') + } + + async callAuthServer(request: never, response: never, endpointOrMethodIdentifier: string): Promise { + const authService = this.serviceContainer.get(ServiceIdentifier.create(ServiceIdentifier.NAMES.Auth).getValue()) + if (!authService) { + throw new Error('Auth service not found') + } + + const serviceResponse = (await authService.handleRequest(request, response, endpointOrMethodIdentifier)) as { + statusCode: number + json: Record + } + + void (response as Response).status(serviceResponse.statusCode).send(serviceResponse.json) + } + + async callAuthServerWithLegacyFormat( + _request: Request, + _response: Response, + _endpointOrMethodIdentifier: string, + ): Promise { + throw new Error('Legacy auth endpoints are no longer available.') + } + + async callRevisionsServer(request: never, response: never, endpointOrMethodIdentifier: string): Promise { + const service = this.serviceContainer.get(ServiceIdentifier.create(ServiceIdentifier.NAMES.Revisions).getValue()) + if (!service) { + throw new Error('Revisions service not found') + } + + await service.handleRequest(request, response, endpointOrMethodIdentifier) + } + + async callSyncingServer(request: never, response: never, endpointOrMethodIdentifier: string): Promise { + const service = this.serviceContainer.get( + ServiceIdentifier.create(ServiceIdentifier.NAMES.SyncingServer).getValue(), + ) + if (!service) { + throw new Error('Syncing service not found') + } + + await service.handleRequest(request, response, endpointOrMethodIdentifier) + } + + async callLegacySyncingServer( + _request: Request, + _response: Response, + _endpointOrMethodIdentifier: string, + ): Promise { + throw new Error('Legacy syncing server endpoints are no longer available.') + } + + async callPaymentsServer(_request: Request, _response: Response, _endpointOrMethodIdentifier: string): Promise { + throw new Error('Payments server is not available.') + } + + async callWebSocketServer( + _request: Request, + _response: Response, + _endpointOrMethodIdentifier: string, + ): Promise { + throw new Error('Websockets server is not available.') + } +} diff --git a/packages/api-gateway/src/Service/Resolver/EndpointResolver.ts b/packages/api-gateway/src/Service/Resolver/EndpointResolver.ts new file mode 100644 index 000000000..9caceee95 --- /dev/null +++ b/packages/api-gateway/src/Service/Resolver/EndpointResolver.ts @@ -0,0 +1,70 @@ +import { EndpointResolverInterface } from './EndpointResolverInterface' + +export class EndpointResolver implements EndpointResolverInterface { + constructor(private isConfiguredForHomeServer: boolean) {} + + private readonly endpointToIdentifierMap: Map = new Map([ + // Actions Controller + ['[POST]:auth/sign_in', 'auth.signIn'], + ['[GET]:auth/params', 'auth.params'], + ['[POST]:auth/sign_out', 'auth.signOut'], + ['[POST]:auth/recovery/codes', 'auth.generateRecoveryCodes'], + ['[POST]:auth/recovery/login', 'auth.signInWithRecoveryCodes'], + ['[POST]:auth/recovery/params', 'auth.recoveryKeyParams'], + // Authenticators Controller + ['[DELETE]:authenticators/:authenticatorId', 'auth.authenticators.delete'], + ['[GET]:authenticators/', 'auth.authenticators.list'], + ['[GET]:authenticators/generate-registration-options', 'auth.authenticators.generateRegistrationOptions'], + ['[POST]:authenticators/generate-authentication-options', 'auth.authenticators.generateAuthenticationOptions'], + ['[POST]:authenticators/verify-registration', 'auth.authenticators.verifyRegistrationResponse'], + // Files Controller + ['[POST]:valet-tokens', 'auth.valet-tokens.create'], + // Offline Controller + ['[GET]:offline/features', 'auth.offline.features'], + ['[POST]:offline/subscription-tokens', 'auth.offline.subscriptionTokens.create'], + // Sessions Controller + ['[GET]:sessions', 'auth.sessions.list'], + ['[DELETE]:session', 'auth.sessions.delete'], + ['[DELETE]:session/all', 'auth.sessions.deleteAll'], + ['[POST]:session/refresh', 'auth.sessions.refresh'], + // Subscription Invites Controller + ['[POST]:subscription-invites', 'auth.subscriptionInvites.create'], + ['[GET]:subscription-invites', 'auth.subscriptionInvites.list'], + ['[DELETE]:subscription-invites/:inviteUuid', 'auth.subscriptionInvites.delete'], + ['[POST]:subscription-invites/:inviteUuid/accept', 'auth.subscriptionInvites.accept'], + // Tokens Controller + ['[POST]:subscription-tokens', 'auth.subscription-tokens.create'], + // Users Controller + ['[PATCH]:users/:userId', 'auth.users.update'], + ['[PUT]:users/:userUuid/attributes/credentials', 'auth.users.updateCredentials'], + ['[PUT]:auth/params', 'auth.users.getKeyParams'], + ['[POST]:listed', 'auth.users.createListedAccount'], + ['[POST]:auth', 'auth.users.register'], + ['[GET]:users/:userUuid/settings', 'auth.users.getSettings'], + ['[PUT]:users/:userUuid/settings', 'auth.users.updateSetting'], + ['[GET]:users/:userUuid/settings/:settingName', 'auth.users.getSetting'], + ['[DELETE]:users/:userUuid/settings/:settingName', 'auth.users.deleteSetting'], + ['[GET]:users/:userUuid/subscription-settings/:subscriptionSettingName', 'auth.users.getSubscriptionSetting'], + ['[GET]:users/:userUuid/features', 'auth.users.getFeatures'], + ['[GET]:users/:userUuid/subscription', 'auth.users.getSubscription'], + ['[GET]:offline/users/subscription', 'auth.users.getOfflineSubscriptionByToken'], + ['[POST]:users/:userUuid/requests', 'auth.users.createRequest'], + ]) + + resolveEndpointOrMethodIdentifier(method: string, endpoint: string, ...params: string[]): string { + if (!this.isConfiguredForHomeServer) { + if (params.length > 0) { + return params.reduce((acc, param) => acc.replace(/:[a-zA-Z0-9]+/, param), endpoint) + } + + return endpoint + } + const identifier = this.endpointToIdentifierMap.get(`[${method}]:${endpoint}`) + + if (!identifier) { + throw new Error(`Endpoint ${endpoint} not found`) + } + + return identifier + } +} diff --git a/packages/api-gateway/src/Service/Resolver/EndpointResolverInterface.ts b/packages/api-gateway/src/Service/Resolver/EndpointResolverInterface.ts new file mode 100644 index 000000000..1c89b072e --- /dev/null +++ b/packages/api-gateway/src/Service/Resolver/EndpointResolverInterface.ts @@ -0,0 +1,3 @@ +export interface EndpointResolverInterface { + resolveEndpointOrMethodIdentifier(method: string, endpoint: string, ...params: string[]): string +} diff --git a/packages/api-gateway/src/Service/index.ts b/packages/api-gateway/src/Service/index.ts deleted file mode 100644 index a71ad56f2..000000000 --- a/packages/api-gateway/src/Service/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './Cache/CrossServiceTokenCacheInterface' -export * from './Http/HttpService' -export * from './Http/HttpServiceInterface' diff --git a/packages/api-gateway/src/index.ts b/packages/api-gateway/src/index.ts index 16cada35d..609d1e872 100644 --- a/packages/api-gateway/src/index.ts +++ b/packages/api-gateway/src/index.ts @@ -1,4 +1,2 @@ export * from './Bootstrap' export * from './Controller' -export * from './Infra' -export * from './Service' diff --git a/packages/auth/bin/backup.ts b/packages/auth/bin/backup.ts index 952f7a192..d59bbea06 100644 --- a/packages/auth/bin/backup.ts +++ b/packages/auth/bin/backup.ts @@ -84,14 +84,14 @@ void container.load().then((container) => { const env: Env = new Env() env.load() - const logger: Logger = container.get(TYPES.Logger) + const logger: Logger = container.get(TYPES.Auth_Logger) logger.info(`Starting ${backupFrequency} ${backupProvider} backup requesting...`) - const settingRepository: SettingRepositoryInterface = container.get(TYPES.SettingRepository) - const roleService: RoleServiceInterface = container.get(TYPES.RoleService) - const domainEventFactory: DomainEventFactoryInterface = container.get(TYPES.DomainEventFactory) - const domainEventPublisher: DomainEventPublisherInterface = container.get(TYPES.DomainEventPublisher) + const settingRepository: SettingRepositoryInterface = container.get(TYPES.Auth_SettingRepository) + const roleService: RoleServiceInterface = container.get(TYPES.Auth_RoleService) + const domainEventFactory: DomainEventFactoryInterface = container.get(TYPES.Auth_DomainEventFactory) + const domainEventPublisher: DomainEventPublisherInterface = container.get(TYPES.Auth_DomainEventPublisher) Promise.resolve(requestBackups(settingRepository, roleService, domainEventFactory, domainEventPublisher)) .then(() => { diff --git a/packages/auth/bin/cleanup.ts b/packages/auth/bin/cleanup.ts index 66f881010..bbc1485d6 100644 --- a/packages/auth/bin/cleanup.ts +++ b/packages/auth/bin/cleanup.ts @@ -25,12 +25,12 @@ void container.load().then((container) => { const env: Env = new Env() env.load() - const logger: Logger = container.get(TYPES.Logger) + const logger: Logger = container.get(TYPES.Auth_Logger) logger.info('Starting sessions and session traces cleanup') - const cleanupSessionTraces: CleanupSessionTraces = container.get(TYPES.CleanupSessionTraces) - const cleanupExpiredSessions: CleanupExpiredSessions = container.get(TYPES.CleanupExpiredSessions) + const cleanupSessionTraces: CleanupSessionTraces = container.get(TYPES.Auth_CleanupSessionTraces) + const cleanupExpiredSessions: CleanupExpiredSessions = container.get(TYPES.Auth_CleanupExpiredSessions) Promise.resolve(cleanup(cleanupSessionTraces, cleanupExpiredSessions)) .then(() => { diff --git a/packages/auth/bin/server.ts b/packages/auth/bin/server.ts index cc1d4214e..fd613ccc3 100644 --- a/packages/auth/bin/server.ts +++ b/packages/auth/bin/server.ts @@ -44,7 +44,7 @@ void container.load().then((container) => { server.setConfig((app) => { app.use((_request: Request, response: Response, next: NextFunction) => { - response.setHeader('X-Auth-Version', container.get(TYPES.VERSION)) + response.setHeader('X-Auth-Version', container.get(TYPES.Auth_VERSION)) next() }) app.use(json()) @@ -52,7 +52,7 @@ void container.load().then((container) => { app.use(cors()) }) - const logger: winston.Logger = container.get(TYPES.Logger) + const logger: winston.Logger = container.get(TYPES.Auth_Logger) server.setErrorConfig((app) => { app.use((error: Record, _request: Request, response: Response, _next: NextFunction) => { diff --git a/packages/auth/bin/stats.ts b/packages/auth/bin/stats.ts index 5688ccc86..5f4d0c178 100644 --- a/packages/auth/bin/stats.ts +++ b/packages/auth/bin/stats.ts @@ -15,12 +15,12 @@ void container.load().then((container) => { const env: Env = new Env() env.load() - const logger: Logger = container.get(TYPES.Logger) + const logger: Logger = container.get(TYPES.Auth_Logger) logger.info('Starting session traces cleanup') - const persistStats: PersistStatistics = container.get(TYPES.PersistStatistics) - const timer: TimerInterface = container.get(TYPES.Timer) + const persistStats: PersistStatistics = container.get(TYPES.Auth_PersistStatistics) + const timer: TimerInterface = container.get(TYPES.Auth_Timer) Promise.resolve( persistStats.execute({ diff --git a/packages/auth/bin/user_email_backup.ts b/packages/auth/bin/user_email_backup.ts index a7c3ecc5f..0efb9cc03 100644 --- a/packages/auth/bin/user_email_backup.ts +++ b/packages/auth/bin/user_email_backup.ts @@ -72,15 +72,15 @@ void container.load().then((container) => { const env: Env = new Env() env.load() - const logger: Logger = container.get(TYPES.Logger) + const logger: Logger = container.get(TYPES.Auth_Logger) logger.info(`Starting email backup requesting for ${backupEmail} ...`) - const settingRepository: SettingRepositoryInterface = container.get(TYPES.SettingRepository) - const userRepository: UserRepositoryInterface = container.get(TYPES.UserRepository) - const roleService: RoleServiceInterface = container.get(TYPES.RoleService) - const domainEventFactory: DomainEventFactoryInterface = container.get(TYPES.DomainEventFactory) - const domainEventPublisher: DomainEventPublisherInterface = container.get(TYPES.DomainEventPublisher) + const settingRepository: SettingRepositoryInterface = container.get(TYPES.Auth_SettingRepository) + const userRepository: UserRepositoryInterface = container.get(TYPES.Auth_UserRepository) + const roleService: RoleServiceInterface = container.get(TYPES.Auth_RoleService) + const domainEventFactory: DomainEventFactoryInterface = container.get(TYPES.Auth_DomainEventFactory) + const domainEventPublisher: DomainEventPublisherInterface = container.get(TYPES.Auth_DomainEventPublisher) Promise.resolve( requestBackups(userRepository, settingRepository, roleService, domainEventFactory, domainEventPublisher), diff --git a/packages/auth/bin/worker.ts b/packages/auth/bin/worker.ts index 67004db20..25acae57a 100644 --- a/packages/auth/bin/worker.ts +++ b/packages/auth/bin/worker.ts @@ -18,11 +18,13 @@ void container.load().then((container) => { const env: Env = new Env() env.load() - const logger: Logger = container.get(TYPES.Logger) + const logger: Logger = container.get(TYPES.Auth_Logger) logger.info('Starting worker...') - const subscriberFactory: DomainEventSubscriberFactoryInterface = container.get(TYPES.DomainEventSubscriberFactory) + const subscriberFactory: DomainEventSubscriberFactoryInterface = container.get( + TYPES.Auth_DomainEventSubscriberFactory, + ) subscriberFactory.create().start() setInterval(() => logger.info('Alive and kicking!'), 20 * 60 * 1000) diff --git a/packages/auth/package.json b/packages/auth/package.json index 7de895e70..764491fac 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -15,6 +15,7 @@ "setup:env": "cp .env.sample .env", "build": "tsc --build", "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --fix --ext .ts", "pretest": "yarn lint && yarn build", "test": "jest --coverage --config=./jest.config.js --maxWorkers=50%", "start": "yarn node dist/bin/server.js", diff --git a/packages/auth/src/Bootstrap/Container.ts b/packages/auth/src/Bootstrap/Container.ts index ae9a15d85..8da9ea250 100644 --- a/packages/auth/src/Bootstrap/Container.ts +++ b/packages/auth/src/Bootstrap/Container.ts @@ -187,7 +187,13 @@ import { UserRequestsController } from '../Controller/UserRequestsController' import { EmailSubscriptionUnsubscribedEventHandler } from '../Domain/Handler/EmailSubscriptionUnsubscribedEventHandler' import { SessionTraceRepositoryInterface } from '../Domain/Session/SessionTraceRepositoryInterface' import { TypeORMSessionTraceRepository } from '../Infra/TypeORM/TypeORMSessionTraceRepository' -import { CacheEntry, CacheEntryRepositoryInterface, MapperInterface } from '@standardnotes/domain-core' +import { + CacheEntry, + CacheEntryRepositoryInterface, + ControllerContainer, + ControllerContainerInterface, + MapperInterface, +} from '@standardnotes/domain-core' import { SessionTracePersistenceMapper } from '../Mapping/SessionTracePersistenceMapper' import { SessionTrace } from '../Domain/Session/SessionTrace' import { TypeORMSessionTrace } from '../Infra/TypeORM/TypeORMSessionTrace' @@ -226,12 +232,17 @@ import { TypeORMEphemeralSessionRepository } from '../Infra/TypeORM/TypeORMEphem import { TypeORMOfflineSubscriptionTokenRepository } from '../Infra/TypeORM/TypeORMOfflineSubscriptionTokenRepository' import { TypeORMPKCERepository } from '../Infra/TypeORM/TypeORMPKCERepository' import { TypeORMSubscriptionTokenRepository } from '../Infra/TypeORM/TypeORMSubscriptionTokenRepository' +import { InversifyExpressAuthController } from '../Infra/InversifyExpressUtils/InversifyExpressAuthController' +import { InversifyExpressAuthenticatorsController } from '../Infra/InversifyExpressUtils/InversifyExpressAuthenticatorsController' +import { InversifyExpressSubscriptionInvitesController } from '../Infra/InversifyExpressUtils/InversifyExpressSubscriptionInvitesController' +import { InversifyExpressUserRequestsController } from '../Infra/InversifyExpressUtils/InversifyExpressUserRequestsController' +import { InversifyExpressWebSocketsController } from '../Infra/InversifyExpressUtils/InversifyExpressWebSocketsController' // eslint-disable-next-line @typescript-eslint/no-var-requires const newrelicFormatter = require('@newrelic/winston-enricher') export class ContainerConfigLoader { - async load(): Promise { + async load(controllerConatiner?: ControllerContainerInterface): Promise { const env: Env = new Env() env.load() @@ -241,16 +252,18 @@ export class ContainerConfigLoader { const isConfiguredForHomeServer = env.get('DB_TYPE') === 'sqlite' - const redisUrl = env.get('REDIS_URL') - const isRedisInClusterMode = redisUrl.indexOf(',') > 0 - let redis - if (isRedisInClusterMode) { - redis = new Redis.Cluster(redisUrl.split(',')) - } else { - redis = new Redis(redisUrl) - } + if (!isConfiguredForHomeServer) { + const redisUrl = env.get('REDIS_URL') + const isRedisInClusterMode = redisUrl.indexOf(',') > 0 + let redis + if (isRedisInClusterMode) { + redis = new Redis.Cluster(redisUrl.split(',')) + } else { + redis = new Redis(redisUrl) + } - container.bind(TYPES.Redis).toConstantValue(redis) + container.bind(TYPES.Auth_Redis).toConstantValue(redis) + } const newrelicWinstonFormatter = newrelicFormatter(winston) const winstonFormatters = [winston.format.splat(), winston.format.json()] @@ -263,9 +276,9 @@ export class ContainerConfigLoader { format: winston.format.combine(...winstonFormatters), transports: [new winston.transports.Console({ level: env.get('LOG_LEVEL') || 'info' })], }) - container.bind(TYPES.Logger).toConstantValue(logger) + container.bind(TYPES.Auth_Logger).toConstantValue(logger) - container.bind(TYPES.Timer).toConstantValue(new Timer()) + container.bind(TYPES.Auth_Timer).toConstantValue(new Timer()) const snsConfig: SNSClientConfig = { region: env.get('SNS_AWS_REGION', true), @@ -279,7 +292,7 @@ export class ContainerConfigLoader { secretAccessKey: env.get('SNS_SECRET_ACCESS_KEY', true), } } - container.bind(TYPES.SNS).toConstantValue(new SNSClient(snsConfig)) + container.bind(TYPES.Auth_SNS).toConstantValue(new SNSClient(snsConfig)) const sqsConfig: SQSClientConfig = { region: env.get('SQS_AWS_REGION', true), @@ -293,611 +306,718 @@ export class ContainerConfigLoader { secretAccessKey: env.get('SQS_SECRET_ACCESS_KEY', true), } } - container.bind(TYPES.SQS).toConstantValue(new SQSClient(sqsConfig)) + container.bind(TYPES.Auth_SQS).toConstantValue(new SQSClient(sqsConfig)) // Mapping container - .bind>(TYPES.SessionTracePersistenceMapper) + .bind>(TYPES.Auth_SessionTracePersistenceMapper) .toConstantValue(new SessionTracePersistenceMapper()) container - .bind>(TYPES.AuthenticatorPersistenceMapper) + .bind>(TYPES.Auth_AuthenticatorPersistenceMapper) .toConstantValue(new AuthenticatorPersistenceMapper()) container - .bind>(TYPES.AuthenticatorHttpMapper) + .bind>(TYPES.Auth_AuthenticatorHttpMapper) .toConstantValue(new AuthenticatorHttpMapper()) container .bind>( - TYPES.AuthenticatorChallengePersistenceMapper, + TYPES.Auth_AuthenticatorChallengePersistenceMapper, ) .toConstantValue(new AuthenticatorChallengePersistenceMapper()) container - .bind>(TYPES.CacheEntryPersistenceMapper) + .bind>(TYPES.Auth_CacheEntryPersistenceMapper) .toConstantValue(new CacheEntryPersistenceMapper()) // ORM container - .bind>(TYPES.ORMOfflineSettingRepository) + .bind>(TYPES.Auth_ORMOfflineSettingRepository) .toConstantValue(AppDataSource.getRepository(OfflineSetting)) container - .bind>(TYPES.ORMOfflineUserSubscriptionRepository) + .bind>(TYPES.Auth_ORMOfflineUserSubscriptionRepository) .toConstantValue(AppDataSource.getRepository(OfflineUserSubscription)) container - .bind>(TYPES.ORMRevokedSessionRepository) + .bind>(TYPES.Auth_ORMRevokedSessionRepository) .toConstantValue(AppDataSource.getRepository(RevokedSession)) - container.bind>(TYPES.ORMRoleRepository).toConstantValue(AppDataSource.getRepository(Role)) + container.bind>(TYPES.Auth_ORMRoleRepository).toConstantValue(AppDataSource.getRepository(Role)) container - .bind>(TYPES.ORMSessionRepository) + .bind>(TYPES.Auth_ORMSessionRepository) .toConstantValue(AppDataSource.getRepository(Session)) container - .bind>(TYPES.ORMSettingRepository) + .bind>(TYPES.Auth_ORMSettingRepository) .toConstantValue(AppDataSource.getRepository(Setting)) container - .bind>(TYPES.ORMSharedSubscriptionInvitationRepository) + .bind>(TYPES.Auth_ORMSharedSubscriptionInvitationRepository) .toConstantValue(AppDataSource.getRepository(SharedSubscriptionInvitation)) container - .bind>(TYPES.ORMSubscriptionSettingRepository) + .bind>(TYPES.Auth_ORMSubscriptionSettingRepository) .toConstantValue(AppDataSource.getRepository(SubscriptionSetting)) - container.bind>(TYPES.ORMUserRepository).toConstantValue(AppDataSource.getRepository(User)) + container.bind>(TYPES.Auth_ORMUserRepository).toConstantValue(AppDataSource.getRepository(User)) container - .bind>(TYPES.ORMUserSubscriptionRepository) + .bind>(TYPES.Auth_ORMUserSubscriptionRepository) .toConstantValue(AppDataSource.getRepository(UserSubscription)) container - .bind>(TYPES.ORMSessionTraceRepository) + .bind>(TYPES.Auth_ORMSessionTraceRepository) .toConstantValue(AppDataSource.getRepository(TypeORMSessionTrace)) container - .bind>(TYPES.ORMAuthenticatorRepository) + .bind>(TYPES.Auth_ORMAuthenticatorRepository) .toConstantValue(AppDataSource.getRepository(TypeORMAuthenticator)) container - .bind>(TYPES.ORMAuthenticatorChallengeRepository) + .bind>(TYPES.Auth_ORMAuthenticatorChallengeRepository) .toConstantValue(AppDataSource.getRepository(TypeORMAuthenticatorChallenge)) container - .bind>(TYPES.ORMCacheEntryRepository) + .bind>(TYPES.Auth_ORMCacheEntryRepository) .toConstantValue(AppDataSource.getRepository(TypeORMCacheEntry)) // Repositories - container.bind(TYPES.SessionRepository).to(TypeORMSessionRepository) + container.bind(TYPES.Auth_SessionRepository).to(TypeORMSessionRepository) container - .bind(TYPES.RevokedSessionRepository) + .bind(TYPES.Auth_RevokedSessionRepository) .to(TypeORMRevokedSessionRepository) - container.bind(TYPES.UserRepository).to(TypeORMUserRepository) - container.bind(TYPES.SettingRepository).to(TypeORMSettingRepository) + container.bind(TYPES.Auth_UserRepository).to(TypeORMUserRepository) + container.bind(TYPES.Auth_SettingRepository).to(TypeORMSettingRepository) container - .bind(TYPES.SubscriptionSettingRepository) + .bind(TYPES.Auth_SubscriptionSettingRepository) .to(TypeORMSubscriptionSettingRepository) container - .bind(TYPES.OfflineSettingRepository) + .bind(TYPES.Auth_OfflineSettingRepository) .to(TypeORMOfflineSettingRepository) - container.bind(TYPES.RoleRepository).to(TypeORMRoleRepository) + container.bind(TYPES.Auth_RoleRepository).to(TypeORMRoleRepository) container - .bind(TYPES.UserSubscriptionRepository) + .bind(TYPES.Auth_UserSubscriptionRepository) .to(TypeORMUserSubscriptionRepository) container - .bind(TYPES.OfflineUserSubscriptionRepository) + .bind(TYPES.Auth_OfflineUserSubscriptionRepository) .to(TypeORMOfflineUserSubscriptionRepository) container - .bind(TYPES.SharedSubscriptionInvitationRepository) + .bind(TYPES.Auth_SharedSubscriptionInvitationRepository) .to(TypeORMSharedSubscriptionInvitationRepository) container - .bind(TYPES.SessionTraceRepository) + .bind(TYPES.Auth_SessionTraceRepository) .toConstantValue( new TypeORMSessionTraceRepository( - container.get(TYPES.ORMSessionTraceRepository), - container.get(TYPES.SessionTracePersistenceMapper), + container.get(TYPES.Auth_ORMSessionTraceRepository), + container.get(TYPES.Auth_SessionTracePersistenceMapper), ), ) container - .bind(TYPES.AuthenticatorRepository) + .bind(TYPES.Auth_AuthenticatorRepository) .toConstantValue( new TypeORMAuthenticatorRepository( - container.get(TYPES.ORMAuthenticatorRepository), - container.get(TYPES.AuthenticatorPersistenceMapper), + container.get(TYPES.Auth_ORMAuthenticatorRepository), + container.get(TYPES.Auth_AuthenticatorPersistenceMapper), ), ) container - .bind(TYPES.AuthenticatorChallengeRepository) + .bind(TYPES.Auth_AuthenticatorChallengeRepository) .toConstantValue( new TypeORMAuthenticatorChallengeRepository( - container.get(TYPES.ORMAuthenticatorChallengeRepository), - container.get(TYPES.AuthenticatorChallengePersistenceMapper), + container.get(TYPES.Auth_ORMAuthenticatorChallengeRepository), + container.get(TYPES.Auth_AuthenticatorChallengePersistenceMapper), ), ) container - .bind(TYPES.CacheEntryRepository) + .bind(TYPES.Auth_CacheEntryRepository) .toConstantValue( new TypeORMCacheEntryRepository( - container.get(TYPES.ORMCacheEntryRepository), - container.get(TYPES.CacheEntryPersistenceMapper), + container.get(TYPES.Auth_ORMCacheEntryRepository), + container.get(TYPES.Auth_CacheEntryPersistenceMapper), ), ) // Middleware - container.bind(TYPES.AuthMiddleware).to(AuthMiddleware) - container.bind(TYPES.SessionMiddleware).to(SessionMiddleware) - container.bind(TYPES.LockMiddleware).to(LockMiddleware) - container.bind(TYPES.AuthMiddlewareWithoutResponse).to(AuthMiddlewareWithoutResponse) - container.bind(TYPES.ApiGatewayAuthMiddleware).to(ApiGatewayAuthMiddleware) + container.bind(TYPES.Auth_AuthMiddleware).to(AuthMiddleware) + container.bind(TYPES.Auth_SessionMiddleware).to(SessionMiddleware) + container.bind(TYPES.Auth_LockMiddleware).to(LockMiddleware) container - .bind(TYPES.ApiGatewayOfflineAuthMiddleware) + .bind(TYPES.Auth_AuthMiddlewareWithoutResponse) + .to(AuthMiddlewareWithoutResponse) + container.bind(TYPES.Auth_ApiGatewayAuthMiddleware).to(ApiGatewayAuthMiddleware) + container + .bind(TYPES.Auth_ApiGatewayOfflineAuthMiddleware) .to(ApiGatewayOfflineAuthMiddleware) - container.bind(TYPES.OfflineUserAuthMiddleware).to(OfflineUserAuthMiddleware) + container.bind(TYPES.Auth_OfflineUserAuthMiddleware).to(OfflineUserAuthMiddleware) // Projectors - container.bind(TYPES.SessionProjector).to(SessionProjector) - container.bind(TYPES.UserProjector).to(UserProjector) - container.bind(TYPES.RoleProjector).to(RoleProjector) - container.bind(TYPES.PermissionProjector).to(PermissionProjector) - container.bind(TYPES.SettingProjector).to(SettingProjector) - container.bind(TYPES.SubscriptionSettingProjector).to(SubscriptionSettingProjector) + container.bind(TYPES.Auth_SessionProjector).to(SessionProjector) + container.bind(TYPES.Auth_UserProjector).to(UserProjector) + container.bind(TYPES.Auth_RoleProjector).to(RoleProjector) + container.bind(TYPES.Auth_PermissionProjector).to(PermissionProjector) + container.bind(TYPES.Auth_SettingProjector).to(SettingProjector) + container + .bind(TYPES.Auth_SubscriptionSettingProjector) + .to(SubscriptionSettingProjector) // Factories - container.bind(TYPES.SettingFactory).to(SettingFactory) + container.bind(TYPES.Auth_SettingFactory).to(SettingFactory) // env vars - container.bind(TYPES.JWT_SECRET).toConstantValue(env.get('JWT_SECRET')) - container.bind(TYPES.LEGACY_JWT_SECRET).toConstantValue(env.get('LEGACY_JWT_SECRET')) - container.bind(TYPES.AUTH_JWT_SECRET).toConstantValue(env.get('AUTH_JWT_SECRET')) - container.bind(TYPES.AUTH_JWT_TTL).toConstantValue(+env.get('AUTH_JWT_TTL')) - container.bind(TYPES.VALET_TOKEN_SECRET).toConstantValue(env.get('VALET_TOKEN_SECRET', true)) - container.bind(TYPES.VALET_TOKEN_TTL).toConstantValue(+env.get('VALET_TOKEN_TTL', true)) + container.bind(TYPES.Auth_JWT_SECRET).toConstantValue(env.get('JWT_SECRET')) + container.bind(TYPES.Auth_LEGACY_JWT_SECRET).toConstantValue(env.get('LEGACY_JWT_SECRET', true)) + container.bind(TYPES.Auth_AUTH_JWT_SECRET).toConstantValue(env.get('AUTH_JWT_SECRET')) container - .bind(TYPES.WEB_SOCKET_CONNECTION_TOKEN_SECRET) + .bind(TYPES.Auth_AUTH_JWT_TTL) + .toConstantValue(env.get('AUTH_JWT_TTL', true) ? +env.get('AUTH_JWT_TTL') : 60_000) + container.bind(TYPES.Auth_VALET_TOKEN_SECRET).toConstantValue(env.get('VALET_TOKEN_SECRET', true)) + container.bind(TYPES.Auth_VALET_TOKEN_TTL).toConstantValue(+env.get('VALET_TOKEN_TTL', true)) + container + .bind(TYPES.Auth_WEB_SOCKET_CONNECTION_TOKEN_SECRET) .toConstantValue(env.get('WEB_SOCKET_CONNECTION_TOKEN_SECRET', true)) - container.bind(TYPES.ENCRYPTION_SERVER_KEY).toConstantValue(env.get('ENCRYPTION_SERVER_KEY')) - container.bind(TYPES.ACCESS_TOKEN_AGE).toConstantValue(env.get('ACCESS_TOKEN_AGE')) - container.bind(TYPES.REFRESH_TOKEN_AGE).toConstantValue(env.get('REFRESH_TOKEN_AGE')) - container.bind(TYPES.MAX_LOGIN_ATTEMPTS).toConstantValue(env.get('MAX_LOGIN_ATTEMPTS')) - container.bind(TYPES.FAILED_LOGIN_LOCKOUT).toConstantValue(env.get('FAILED_LOGIN_LOCKOUT')) - container.bind(TYPES.PSEUDO_KEY_PARAMS_KEY).toConstantValue(env.get('PSEUDO_KEY_PARAMS_KEY')) - container.bind(TYPES.EPHEMERAL_SESSION_AGE).toConstantValue(env.get('EPHEMERAL_SESSION_AGE')) - container.bind(TYPES.REDIS_URL).toConstantValue(env.get('REDIS_URL')) + container.bind(TYPES.Auth_ENCRYPTION_SERVER_KEY).toConstantValue(env.get('ENCRYPTION_SERVER_KEY')) container - .bind(TYPES.DISABLE_USER_REGISTRATION) + .bind(TYPES.Auth_ACCESS_TOKEN_AGE) + .toConstantValue(env.get('ACCESS_TOKEN_AGE', true) ? +env.get('ACCESS_TOKEN_AGE', true) : 5184000) + container + .bind(TYPES.Auth_REFRESH_TOKEN_AGE) + .toConstantValue(env.get('REFRESH_TOKEN_AGE', true) ? +env.get('REFRESH_TOKEN_AGE', true) : 31556926) + container + .bind(TYPES.Auth_MAX_LOGIN_ATTEMPTS) + .toConstantValue(env.get('MAX_LOGIN_ATTEMPTS', true) ? +env.get('MAX_LOGIN_ATTEMPTS', true) : 6) + container + .bind(TYPES.Auth_FAILED_LOGIN_LOCKOUT) + .toConstantValue(env.get('FAILED_LOGIN_LOCKOUT', true) ? +env.get('FAILED_LOGIN_LOCKOUT', true) : 3600) + container.bind(TYPES.Auth_PSEUDO_KEY_PARAMS_KEY).toConstantValue(env.get('PSEUDO_KEY_PARAMS_KEY')) + container + .bind(TYPES.Auth_EPHEMERAL_SESSION_AGE) + .toConstantValue(env.get('EPHEMERAL_SESSION_AGE', true) ? +env.get('EPHEMERAL_SESSION_AGE', true) : 259200) + container.bind(TYPES.Auth_REDIS_URL).toConstantValue(env.get('REDIS_URL', true)) + container + .bind(TYPES.Auth_DISABLE_USER_REGISTRATION) .toConstantValue(env.get('DISABLE_USER_REGISTRATION', true) === 'true') - container.bind(TYPES.SNS_TOPIC_ARN).toConstantValue(env.get('SNS_TOPIC_ARN')) - container.bind(TYPES.SNS_AWS_REGION).toConstantValue(env.get('SNS_AWS_REGION', true)) - container.bind(TYPES.SQS_QUEUE_URL).toConstantValue(env.get('SQS_QUEUE_URL')) - container.bind(TYPES.USER_SERVER_REGISTRATION_URL).toConstantValue(env.get('USER_SERVER_REGISTRATION_URL', true)) - container.bind(TYPES.USER_SERVER_AUTH_KEY).toConstantValue(env.get('USER_SERVER_AUTH_KEY', true)) - container.bind(TYPES.USER_SERVER_CHANGE_EMAIL_URL).toConstantValue(env.get('USER_SERVER_CHANGE_EMAIL_URL', true)) - container.bind(TYPES.NEW_RELIC_ENABLED).toConstantValue(env.get('NEW_RELIC_ENABLED', true)) - container.bind(TYPES.SYNCING_SERVER_URL).toConstantValue(env.get('SYNCING_SERVER_URL')) - container.bind(TYPES.VERSION).toConstantValue(env.get('VERSION')) - container.bind(TYPES.PAYMENTS_SERVER_URL).toConstantValue(env.get('PAYMENTS_SERVER_URL', true)) + container.bind(TYPES.Auth_SNS_TOPIC_ARN).toConstantValue(env.get('SNS_TOPIC_ARN', true)) + container.bind(TYPES.Auth_SNS_AWS_REGION).toConstantValue(env.get('SNS_AWS_REGION', true)) + container.bind(TYPES.Auth_SQS_QUEUE_URL).toConstantValue(env.get('SQS_QUEUE_URL', true)) container - .bind(TYPES.SESSION_TRACE_DAYS_TTL) + .bind(TYPES.Auth_USER_SERVER_REGISTRATION_URL) + .toConstantValue(env.get('USER_SERVER_REGISTRATION_URL', true)) + container.bind(TYPES.Auth_USER_SERVER_AUTH_KEY).toConstantValue(env.get('USER_SERVER_AUTH_KEY', true)) + container + .bind(TYPES.Auth_USER_SERVER_CHANGE_EMAIL_URL) + .toConstantValue(env.get('USER_SERVER_CHANGE_EMAIL_URL', true)) + container.bind(TYPES.Auth_NEW_RELIC_ENABLED).toConstantValue(env.get('NEW_RELIC_ENABLED', true)) + container.bind(TYPES.Auth_SYNCING_SERVER_URL).toConstantValue(env.get('SYNCING_SERVER_URL', true)) + container.bind(TYPES.Auth_VERSION).toConstantValue(env.get('VERSION')) + container.bind(TYPES.Auth_PAYMENTS_SERVER_URL).toConstantValue(env.get('PAYMENTS_SERVER_URL', true)) + container + .bind(TYPES.Auth_SESSION_TRACE_DAYS_TTL) .toConstantValue(env.get('SESSION_TRACE_DAYS_TTL', true) ? +env.get('SESSION_TRACE_DAYS_TTL', true) : 90) container - .bind(TYPES.U2F_RELYING_PARTY_NAME) + .bind(TYPES.Auth_U2F_RELYING_PARTY_NAME) .toConstantValue(env.get('U2F_RELYING_PARTY_NAME', true) ?? 'Standard Notes') container - .bind(TYPES.U2F_RELYING_PARTY_ID) + .bind(TYPES.Auth_U2F_RELYING_PARTY_ID) .toConstantValue(env.get('U2F_RELYING_PARTY_ID', true) ?? 'app.standardnotes.com') container - .bind(TYPES.U2F_EXPECTED_ORIGIN) + .bind(TYPES.Auth_U2F_EXPECTED_ORIGIN) .toConstantValue( env.get('U2F_EXPECTED_ORIGIN', true) ? env.get('U2F_EXPECTED_ORIGIN', true).split(',') : ['https://app.standardnotes.com'], ) container - .bind(TYPES.U2F_REQUIRE_USER_VERIFICATION) + .bind(TYPES.Auth_U2F_REQUIRE_USER_VERIFICATION) .toConstantValue(env.get('U2F_REQUIRE_USER_VERIFICATION', true) === 'true') container - .bind(TYPES.READONLY_USERS) + .bind(TYPES.Auth_READONLY_USERS) .toConstantValue(env.get('READONLY_USERS', true) ? env.get('READONLY_USERS', true).split(',') : []) if (isConfiguredForHomeServer) { container - .bind(TYPES.LockRepository) + .bind(TYPES.Auth_LockRepository) .toConstantValue( new TypeORMLockRepository( - container.get(TYPES.CacheEntryRepository), - container.get(TYPES.Timer), - container.get(TYPES.MAX_LOGIN_ATTEMPTS), - container.get(TYPES.FAILED_LOGIN_LOCKOUT), + container.get(TYPES.Auth_CacheEntryRepository), + container.get(TYPES.Auth_Timer), + container.get(TYPES.Auth_MAX_LOGIN_ATTEMPTS), + container.get(TYPES.Auth_FAILED_LOGIN_LOCKOUT), ), ) container - .bind(TYPES.EphemeralSessionRepository) + .bind(TYPES.Auth_EphemeralSessionRepository) .toConstantValue( new TypeORMEphemeralSessionRepository( - container.get(TYPES.CacheEntryRepository), - container.get(TYPES.EPHEMERAL_SESSION_AGE), - container.get(TYPES.Timer), + container.get(TYPES.Auth_CacheEntryRepository), + container.get(TYPES.Auth_EPHEMERAL_SESSION_AGE), + container.get(TYPES.Auth_Timer), ), ) container - .bind(TYPES.OfflineSubscriptionTokenRepository) + .bind(TYPES.Auth_OfflineSubscriptionTokenRepository) .toConstantValue( new TypeORMOfflineSubscriptionTokenRepository( - container.get(TYPES.CacheEntryRepository), - container.get(TYPES.Timer), + container.get(TYPES.Auth_CacheEntryRepository), + container.get(TYPES.Auth_Timer), ), ) container - .bind(TYPES.PKCERepository) + .bind(TYPES.Auth_PKCERepository) .toConstantValue( new TypeORMPKCERepository( - container.get(TYPES.CacheEntryRepository), - container.get(TYPES.Logger), - container.get(TYPES.Timer), + container.get(TYPES.Auth_CacheEntryRepository), + container.get(TYPES.Auth_Logger), + container.get(TYPES.Auth_Timer), ), ) container - .bind(TYPES.SubscriptionTokenRepository) + .bind(TYPES.Auth_SubscriptionTokenRepository) .toConstantValue( - new TypeORMSubscriptionTokenRepository(container.get(TYPES.CacheEntryRepository), container.get(TYPES.Timer)), + new TypeORMSubscriptionTokenRepository( + container.get(TYPES.Auth_CacheEntryRepository), + container.get(TYPES.Auth_Timer), + ), ) } else { - container.bind(TYPES.PKCERepository).to(RedisPKCERepository) - container.bind(TYPES.LockRepository).to(LockRepository) + container.bind(TYPES.Auth_PKCERepository).to(RedisPKCERepository) + container.bind(TYPES.Auth_LockRepository).to(LockRepository) container - .bind(TYPES.EphemeralSessionRepository) + .bind(TYPES.Auth_EphemeralSessionRepository) .to(RedisEphemeralSessionRepository) container - .bind(TYPES.OfflineSubscriptionTokenRepository) + .bind(TYPES.Auth_OfflineSubscriptionTokenRepository) .to(RedisOfflineSubscriptionTokenRepository) container - .bind(TYPES.SubscriptionTokenRepository) + .bind(TYPES.Auth_SubscriptionTokenRepository) .to(RedisSubscriptionTokenRepository) } // Services - container.bind(TYPES.DeviceDetector).toConstantValue(new UAParser()) - container.bind(TYPES.SessionService).to(SessionService) - container.bind(TYPES.AuthResponseFactory20161215).to(AuthResponseFactory20161215) - container.bind(TYPES.AuthResponseFactory20190520).to(AuthResponseFactory20190520) - container.bind(TYPES.AuthResponseFactory20200115).to(AuthResponseFactory20200115) - container.bind(TYPES.AuthResponseFactoryResolver).to(AuthResponseFactoryResolver) - container.bind(TYPES.KeyParamsFactory).to(KeyParamsFactory) + container.bind(TYPES.Auth_DeviceDetector).toConstantValue(new UAParser()) + container.bind(TYPES.Auth_SessionService).to(SessionService) + container.bind(TYPES.Auth_AuthResponseFactory20161215).to(AuthResponseFactory20161215) + container.bind(TYPES.Auth_AuthResponseFactory20190520).to(AuthResponseFactory20190520) + container.bind(TYPES.Auth_AuthResponseFactory20200115).to(AuthResponseFactory20200115) + container.bind(TYPES.Auth_AuthResponseFactoryResolver).to(AuthResponseFactoryResolver) + container.bind(TYPES.Auth_KeyParamsFactory).to(KeyParamsFactory) container - .bind>(TYPES.SessionTokenDecoder) - .toConstantValue(new TokenDecoder(container.get(TYPES.JWT_SECRET))) + .bind>(TYPES.Auth_SessionTokenDecoder) + .toConstantValue(new TokenDecoder(container.get(TYPES.Auth_JWT_SECRET))) container - .bind>(TYPES.FallbackSessionTokenDecoder) - .toConstantValue(new TokenDecoder(container.get(TYPES.LEGACY_JWT_SECRET))) + .bind>(TYPES.Auth_FallbackSessionTokenDecoder) + .toConstantValue(new TokenDecoder(container.get(TYPES.Auth_LEGACY_JWT_SECRET))) container - .bind>(TYPES.CrossServiceTokenDecoder) - .toConstantValue(new TokenDecoder(container.get(TYPES.AUTH_JWT_SECRET))) + .bind>(TYPES.Auth_CrossServiceTokenDecoder) + .toConstantValue(new TokenDecoder(container.get(TYPES.Auth_AUTH_JWT_SECRET))) container - .bind>(TYPES.OfflineUserTokenDecoder) - .toConstantValue(new TokenDecoder(container.get(TYPES.AUTH_JWT_SECRET))) + .bind>(TYPES.Auth_OfflineUserTokenDecoder) + .toConstantValue(new TokenDecoder(container.get(TYPES.Auth_AUTH_JWT_SECRET))) container - .bind>(TYPES.WebSocketConnectionTokenDecoder) + .bind>(TYPES.Auth_WebSocketConnectionTokenDecoder) .toConstantValue( - new TokenDecoder(container.get(TYPES.WEB_SOCKET_CONNECTION_TOKEN_SECRET)), + new TokenDecoder(container.get(TYPES.Auth_WEB_SOCKET_CONNECTION_TOKEN_SECRET)), ) container - .bind>(TYPES.OfflineUserTokenEncoder) - .toConstantValue(new TokenEncoder(container.get(TYPES.AUTH_JWT_SECRET))) + .bind>(TYPES.Auth_OfflineUserTokenEncoder) + .toConstantValue(new TokenEncoder(container.get(TYPES.Auth_AUTH_JWT_SECRET))) container - .bind>(TYPES.SessionTokenEncoder) - .toConstantValue(new TokenEncoder(container.get(TYPES.JWT_SECRET))) + .bind>(TYPES.Auth_SessionTokenEncoder) + .toConstantValue(new TokenEncoder(container.get(TYPES.Auth_JWT_SECRET))) container - .bind>(TYPES.CrossServiceTokenEncoder) - .toConstantValue(new TokenEncoder(container.get(TYPES.AUTH_JWT_SECRET))) + .bind>(TYPES.Auth_CrossServiceTokenEncoder) + .toConstantValue(new TokenEncoder(container.get(TYPES.Auth_AUTH_JWT_SECRET))) container - .bind>(TYPES.ValetTokenEncoder) - .toConstantValue(new TokenEncoder(container.get(TYPES.VALET_TOKEN_SECRET))) - container.bind(TYPES.AuthenticationMethodResolver).to(AuthenticationMethodResolver) - container.bind(TYPES.DomainEventFactory).to(DomainEventFactory) - container.bind(TYPES.HTTPClient).toConstantValue(axios.create()) - container.bind(TYPES.Crypter).to(CrypterNode) - container.bind(TYPES.SettingService).to(SettingService) - container.bind(TYPES.SubscriptionSettingService).to(SubscriptionSettingService) - container.bind(TYPES.OfflineSettingService).to(OfflineSettingService) - container.bind(TYPES.CryptoNode).toConstantValue(new CryptoNode()) - container.bind(TYPES.ContenDecoder).toConstantValue(new ContentDecoder()) - container.bind(TYPES.WebSocketsClientService).to(WebSocketsClientService) - container.bind(TYPES.RoleService).to(RoleService) - container.bind(TYPES.RoleToSubscriptionMap).to(RoleToSubscriptionMap) - container.bind(TYPES.SettingsAssociationService).to(SettingsAssociationService) + .bind>(TYPES.Auth_ValetTokenEncoder) + .toConstantValue(new TokenEncoder(container.get(TYPES.Auth_VALET_TOKEN_SECRET))) container - .bind(TYPES.SubscriptionSettingsAssociationService) + .bind(TYPES.Auth_AuthenticationMethodResolver) + .to(AuthenticationMethodResolver) + container.bind(TYPES.Auth_DomainEventFactory).to(DomainEventFactory) + container.bind(TYPES.Auth_HTTPClient).toConstantValue(axios.create()) + container.bind(TYPES.Auth_Crypter).to(CrypterNode) + container.bind(TYPES.Auth_SettingService).to(SettingService) + container + .bind(TYPES.Auth_SubscriptionSettingService) + .to(SubscriptionSettingService) + container.bind(TYPES.Auth_OfflineSettingService).to(OfflineSettingService) + container.bind(TYPES.Auth_CryptoNode).toConstantValue(new CryptoNode()) + container.bind(TYPES.Auth_ContenDecoder).toConstantValue(new ContentDecoder()) + container.bind(TYPES.Auth_WebSocketsClientService).to(WebSocketsClientService) + container.bind(TYPES.Auth_RoleService).to(RoleService) + container.bind(TYPES.Auth_RoleToSubscriptionMap).to(RoleToSubscriptionMap) + container + .bind(TYPES.Auth_SettingsAssociationService) + .to(SettingsAssociationService) + container + .bind(TYPES.Auth_SubscriptionSettingsAssociationService) .to(SubscriptionSettingsAssociationService) - container.bind(TYPES.FeatureService).to(FeatureService) - container.bind(TYPES.SettingInterpreter).to(SettingInterpreter) - container.bind(TYPES.SettingDecrypter).to(SettingDecrypter) + container.bind(TYPES.Auth_FeatureService).to(FeatureService) + container.bind(TYPES.Auth_SettingInterpreter).to(SettingInterpreter) + container.bind(TYPES.Auth_SettingDecrypter).to(SettingDecrypter) container - .bind>(TYPES.ProtocolVersionSelector) + .bind>(TYPES.Auth_ProtocolVersionSelector) .toConstantValue(new DeterministicSelector()) container - .bind>(TYPES.BooleanSelector) + .bind>(TYPES.Auth_BooleanSelector) .toConstantValue(new DeterministicSelector()) - container.bind(TYPES.UserSubscriptionService).to(UserSubscriptionService) + container.bind(TYPES.Auth_UserSubscriptionService).to(UserSubscriptionService) container - .bind(TYPES.DomainEventPublisher) - .toConstantValue(new SNSDomainEventPublisher(container.get(TYPES.SNS), container.get(TYPES.SNS_TOPIC_ARN))) + .bind(TYPES.Auth_DomainEventPublisher) + .toConstantValue( + new SNSDomainEventPublisher(container.get(TYPES.Auth_SNS), container.get(TYPES.Auth_SNS_TOPIC_ARN)), + ) // use cases container - .bind(TYPES.TraceSession) + .bind(TYPES.Auth_TraceSession) .toConstantValue( new TraceSession( - container.get(TYPES.SessionTraceRepository), - container.get(TYPES.Timer), - container.get(TYPES.SESSION_TRACE_DAYS_TTL), + container.get(TYPES.Auth_SessionTraceRepository), + container.get(TYPES.Auth_Timer), + container.get(TYPES.Auth_SESSION_TRACE_DAYS_TTL), ), ) container - .bind(TYPES.PersistStatistics) + .bind(TYPES.Auth_PersistStatistics) .toConstantValue( new PersistStatistics( - container.get(TYPES.SessionTraceRepository), - container.get(TYPES.DomainEventPublisher), - container.get(TYPES.DomainEventFactory), - container.get(TYPES.Timer), + container.get(TYPES.Auth_SessionTraceRepository), + container.get(TYPES.Auth_DomainEventPublisher), + container.get(TYPES.Auth_DomainEventFactory), + container.get(TYPES.Auth_Timer), ), ) container - .bind(TYPES.GenerateAuthenticatorRegistrationOptions) + .bind(TYPES.Auth_GenerateAuthenticatorRegistrationOptions) .toConstantValue( new GenerateAuthenticatorRegistrationOptions( - container.get(TYPES.AuthenticatorRepository), - container.get(TYPES.AuthenticatorChallengeRepository), - container.get(TYPES.U2F_RELYING_PARTY_NAME), - container.get(TYPES.U2F_RELYING_PARTY_ID), - container.get(TYPES.UserRepository), - container.get(TYPES.FeatureService), + container.get(TYPES.Auth_AuthenticatorRepository), + container.get(TYPES.Auth_AuthenticatorChallengeRepository), + container.get(TYPES.Auth_U2F_RELYING_PARTY_NAME), + container.get(TYPES.Auth_U2F_RELYING_PARTY_ID), + container.get(TYPES.Auth_UserRepository), + container.get(TYPES.Auth_FeatureService), ), ) container - .bind(TYPES.VerifyAuthenticatorRegistrationResponse) + .bind(TYPES.Auth_VerifyAuthenticatorRegistrationResponse) .toConstantValue( new VerifyAuthenticatorRegistrationResponse( - container.get(TYPES.AuthenticatorRepository), - container.get(TYPES.AuthenticatorChallengeRepository), - container.get(TYPES.U2F_RELYING_PARTY_ID), - container.get(TYPES.U2F_EXPECTED_ORIGIN), - container.get(TYPES.U2F_REQUIRE_USER_VERIFICATION), - container.get(TYPES.UserRepository), - container.get(TYPES.FeatureService), + container.get(TYPES.Auth_AuthenticatorRepository), + container.get(TYPES.Auth_AuthenticatorChallengeRepository), + container.get(TYPES.Auth_U2F_RELYING_PARTY_ID), + container.get(TYPES.Auth_U2F_EXPECTED_ORIGIN), + container.get(TYPES.Auth_U2F_REQUIRE_USER_VERIFICATION), + container.get(TYPES.Auth_UserRepository), + container.get(TYPES.Auth_FeatureService), ), ) container - .bind(TYPES.GenerateAuthenticatorAuthenticationOptions) + .bind(TYPES.Auth_GenerateAuthenticatorAuthenticationOptions) .toConstantValue( new GenerateAuthenticatorAuthenticationOptions( - container.get(TYPES.UserRepository), - container.get(TYPES.AuthenticatorRepository), - container.get(TYPES.AuthenticatorChallengeRepository), - container.get(TYPES.PSEUDO_KEY_PARAMS_KEY), + container.get(TYPES.Auth_UserRepository), + container.get(TYPES.Auth_AuthenticatorRepository), + container.get(TYPES.Auth_AuthenticatorChallengeRepository), + container.get(TYPES.Auth_PSEUDO_KEY_PARAMS_KEY), ), ) container - .bind(TYPES.VerifyAuthenticatorAuthenticationResponse) + .bind(TYPES.Auth_VerifyAuthenticatorAuthenticationResponse) .toConstantValue( new VerifyAuthenticatorAuthenticationResponse( - container.get(TYPES.AuthenticatorRepository), - container.get(TYPES.AuthenticatorChallengeRepository), - container.get(TYPES.U2F_RELYING_PARTY_ID), - container.get(TYPES.U2F_EXPECTED_ORIGIN), - container.get(TYPES.U2F_REQUIRE_USER_VERIFICATION), + container.get(TYPES.Auth_AuthenticatorRepository), + container.get(TYPES.Auth_AuthenticatorChallengeRepository), + container.get(TYPES.Auth_U2F_RELYING_PARTY_ID), + container.get(TYPES.Auth_U2F_EXPECTED_ORIGIN), + container.get(TYPES.Auth_U2F_REQUIRE_USER_VERIFICATION), ), ) container - .bind(TYPES.ListAuthenticators) + .bind(TYPES.Auth_ListAuthenticators) .toConstantValue( new ListAuthenticators( - container.get(TYPES.AuthenticatorRepository), - container.get(TYPES.UserRepository), - container.get(TYPES.FeatureService), + container.get(TYPES.Auth_AuthenticatorRepository), + container.get(TYPES.Auth_UserRepository), + container.get(TYPES.Auth_FeatureService), ), ) container - .bind(TYPES.DeleteAuthenticator) + .bind(TYPES.Auth_DeleteAuthenticator) .toConstantValue( new DeleteAuthenticator( - container.get(TYPES.AuthenticatorRepository), - container.get(TYPES.UserRepository), - container.get(TYPES.FeatureService), + container.get(TYPES.Auth_AuthenticatorRepository), + container.get(TYPES.Auth_UserRepository), + container.get(TYPES.Auth_FeatureService), ), ) container - .bind(TYPES.GenerateRecoveryCodes) + .bind(TYPES.Auth_GenerateRecoveryCodes) .toConstantValue( new GenerateRecoveryCodes( - container.get(TYPES.UserRepository), - container.get(TYPES.SettingService), - container.get(TYPES.CryptoNode), + container.get(TYPES.Auth_UserRepository), + container.get(TYPES.Auth_SettingService), + container.get(TYPES.Auth_CryptoNode), ), ) container - .bind(TYPES.CleanupSessionTraces) - .toConstantValue(new CleanupSessionTraces(container.get(TYPES.SessionTraceRepository))) + .bind(TYPES.Auth_CleanupSessionTraces) + .toConstantValue(new CleanupSessionTraces(container.get(TYPES.Auth_SessionTraceRepository))) container - .bind(TYPES.CleanupExpiredSessions) - .toConstantValue(new CleanupExpiredSessions(container.get(TYPES.SessionRepository))) - container.bind(TYPES.AuthenticateUser).to(AuthenticateUser) - container.bind(TYPES.AuthenticateRequest).to(AuthenticateRequest) - container.bind(TYPES.RefreshSessionToken).to(RefreshSessionToken) - container.bind(TYPES.SignIn).to(SignIn) - container.bind(TYPES.VerifyMFA).to(VerifyMFA) - container.bind(TYPES.ClearLoginAttempts).to(ClearLoginAttempts) - container.bind(TYPES.IncreaseLoginAttempts).to(IncreaseLoginAttempts) + .bind(TYPES.Auth_CleanupExpiredSessions) + .toConstantValue(new CleanupExpiredSessions(container.get(TYPES.Auth_SessionRepository))) + container.bind(TYPES.Auth_AuthenticateUser).to(AuthenticateUser) + container.bind(TYPES.Auth_AuthenticateRequest).to(AuthenticateRequest) + container.bind(TYPES.Auth_RefreshSessionToken).to(RefreshSessionToken) + container.bind(TYPES.Auth_SignIn).to(SignIn) + container.bind(TYPES.Auth_VerifyMFA).to(VerifyMFA) + container.bind(TYPES.Auth_ClearLoginAttempts).to(ClearLoginAttempts) + container.bind(TYPES.Auth_IncreaseLoginAttempts).to(IncreaseLoginAttempts) container - .bind(TYPES.GetUserKeyParamsRecovery) + .bind(TYPES.Auth_GetUserKeyParamsRecovery) .toConstantValue( new GetUserKeyParamsRecovery( - container.get(TYPES.KeyParamsFactory), - container.get(TYPES.UserRepository), - container.get(TYPES.PKCERepository), - container.get(TYPES.SettingService), + container.get(TYPES.Auth_KeyParamsFactory), + container.get(TYPES.Auth_UserRepository), + container.get(TYPES.Auth_PKCERepository), + container.get(TYPES.Auth_SettingService), ), ) - container.bind(TYPES.GetUserKeyParams).to(GetUserKeyParams) - container.bind(TYPES.UpdateUser).to(UpdateUser) - container.bind(TYPES.Register).to(Register) - container.bind(TYPES.GetActiveSessionsForUser).to(GetActiveSessionsForUser) - container.bind(TYPES.DeletePreviousSessionsForUser).to(DeletePreviousSessionsForUser) - container.bind(TYPES.DeleteSessionForUser).to(DeleteSessionForUser) - container.bind(TYPES.ChangeCredentials).to(ChangeCredentials) - container.bind(TYPES.GetSettings).to(GetSettings) - container.bind(TYPES.GetSetting).to(GetSetting) - container.bind(TYPES.GetUserFeatures).to(GetUserFeatures) - container.bind(TYPES.UpdateSetting).to(UpdateSetting) - container.bind(TYPES.DeleteSetting).to(DeleteSetting) + container.bind(TYPES.Auth_GetUserKeyParams).to(GetUserKeyParams) + container.bind(TYPES.Auth_UpdateUser).to(UpdateUser) + container.bind(TYPES.Auth_Register).to(Register) + container.bind(TYPES.Auth_GetActiveSessionsForUser).to(GetActiveSessionsForUser) container - .bind(TYPES.SignInWithRecoveryCodes) + .bind(TYPES.Auth_DeletePreviousSessionsForUser) + .to(DeletePreviousSessionsForUser) + container.bind(TYPES.Auth_DeleteSessionForUser).to(DeleteSessionForUser) + container.bind(TYPES.Auth_ChangeCredentials).to(ChangeCredentials) + container.bind(TYPES.Auth_GetSettings).to(GetSettings) + container.bind(TYPES.Auth_GetSetting).to(GetSetting) + container.bind(TYPES.Auth_GetUserFeatures).to(GetUserFeatures) + container.bind(TYPES.Auth_UpdateSetting).to(UpdateSetting) + container.bind(TYPES.Auth_DeleteSetting).to(DeleteSetting) + container + .bind(TYPES.Auth_SignInWithRecoveryCodes) .toConstantValue( new SignInWithRecoveryCodes( - container.get(TYPES.UserRepository), - container.get(TYPES.AuthResponseFactory20200115), - container.get(TYPES.PKCERepository), - container.get(TYPES.Crypter), - container.get(TYPES.SettingService), - container.get(TYPES.GenerateRecoveryCodes), - container.get(TYPES.IncreaseLoginAttempts), - container.get(TYPES.ClearLoginAttempts), - container.get(TYPES.DeleteSetting), - container.get(TYPES.AuthenticatorRepository), + container.get(TYPES.Auth_UserRepository), + container.get(TYPES.Auth_AuthResponseFactory20200115), + container.get(TYPES.Auth_PKCERepository), + container.get(TYPES.Auth_Crypter), + container.get(TYPES.Auth_SettingService), + container.get(TYPES.Auth_GenerateRecoveryCodes), + container.get(TYPES.Auth_IncreaseLoginAttempts), + container.get(TYPES.Auth_ClearLoginAttempts), + container.get(TYPES.Auth_DeleteSetting), + container.get(TYPES.Auth_AuthenticatorRepository), ), ) - container.bind(TYPES.DeleteAccount).to(DeleteAccount) - container.bind(TYPES.GetUserSubscription).to(GetUserSubscription) - container.bind(TYPES.GetUserOfflineSubscription).to(GetUserOfflineSubscription) - container.bind(TYPES.CreateSubscriptionToken).to(CreateSubscriptionToken) - container.bind(TYPES.AuthenticateSubscriptionToken).to(AuthenticateSubscriptionToken) + container.bind(TYPES.Auth_DeleteAccount).to(DeleteAccount) + container.bind(TYPES.Auth_GetUserSubscription).to(GetUserSubscription) + container.bind(TYPES.Auth_GetUserOfflineSubscription).to(GetUserOfflineSubscription) + container.bind(TYPES.Auth_CreateSubscriptionToken).to(CreateSubscriptionToken) container - .bind(TYPES.AuthenticateOfflineSubscriptionToken) + .bind(TYPES.Auth_AuthenticateSubscriptionToken) + .to(AuthenticateSubscriptionToken) + container + .bind(TYPES.Auth_AuthenticateOfflineSubscriptionToken) .to(AuthenticateOfflineSubscriptionToken) container - .bind(TYPES.CreateOfflineSubscriptionToken) + .bind(TYPES.Auth_CreateOfflineSubscriptionToken) .to(CreateOfflineSubscriptionToken) - container.bind(TYPES.CreateValetToken).to(CreateValetToken) - container.bind(TYPES.CreateListedAccount).to(CreateListedAccount) - container.bind(TYPES.InviteToSharedSubscription).to(InviteToSharedSubscription) + container.bind(TYPES.Auth_CreateValetToken).to(CreateValetToken) + container.bind(TYPES.Auth_CreateListedAccount).to(CreateListedAccount) + container.bind(TYPES.Auth_InviteToSharedSubscription).to(InviteToSharedSubscription) container - .bind(TYPES.AcceptSharedSubscriptionInvitation) + .bind(TYPES.Auth_AcceptSharedSubscriptionInvitation) .to(AcceptSharedSubscriptionInvitation) container - .bind(TYPES.DeclineSharedSubscriptionInvitation) + .bind(TYPES.Auth_DeclineSharedSubscriptionInvitation) .to(DeclineSharedSubscriptionInvitation) container - .bind(TYPES.CancelSharedSubscriptionInvitation) + .bind(TYPES.Auth_CancelSharedSubscriptionInvitation) .to(CancelSharedSubscriptionInvitation) container - .bind(TYPES.ListSharedSubscriptionInvitations) + .bind(TYPES.Auth_ListSharedSubscriptionInvitations) .to(ListSharedSubscriptionInvitations) - container.bind(TYPES.VerifyPredicate).to(VerifyPredicate) - container.bind(TYPES.CreateCrossServiceToken).to(CreateCrossServiceToken) - container.bind(TYPES.ProcessUserRequest).to(ProcessUserRequest) + container.bind(TYPES.Auth_VerifyPredicate).to(VerifyPredicate) + container.bind(TYPES.Auth_CreateCrossServiceToken).to(CreateCrossServiceToken) + container.bind(TYPES.Auth_ProcessUserRequest).to(ProcessUserRequest) // Controller - container.bind(TYPES.AuthController).to(AuthController) container - .bind(TYPES.AuthenticatorsController) + .bind(TYPES.Auth_ControllerContainer) + .toConstantValue(controllerConatiner ?? new ControllerContainer()) + container + .bind(TYPES.Auth_AuthController) .toConstantValue( - new AuthenticatorsController( - container.get(TYPES.GenerateAuthenticatorRegistrationOptions), - container.get(TYPES.VerifyAuthenticatorRegistrationResponse), - container.get(TYPES.GenerateAuthenticatorAuthenticationOptions), - container.get(TYPES.ListAuthenticators), - container.get(TYPES.DeleteAuthenticator), - container.get(TYPES.AuthenticatorHttpMapper), + new AuthController( + container.get(TYPES.Auth_ClearLoginAttempts), + container.get(TYPES.Auth_Register), + container.get(TYPES.Auth_DomainEventPublisher), + container.get(TYPES.Auth_DomainEventFactory), + container.get(TYPES.Auth_SignInWithRecoveryCodes), + container.get(TYPES.Auth_GetUserKeyParamsRecovery), + container.get(TYPES.Auth_GenerateRecoveryCodes), + container.get(TYPES.Auth_Logger), + container.get(TYPES.Auth_SessionService), ), ) - container.bind(TYPES.SubscriptionInvitesController).to(SubscriptionInvitesController) - container.bind(TYPES.UserRequestsController).to(UserRequestsController) + container + .bind(TYPES.Auth_AuthenticatorsController) + .toConstantValue( + new AuthenticatorsController( + container.get(TYPES.Auth_GenerateAuthenticatorRegistrationOptions), + container.get(TYPES.Auth_VerifyAuthenticatorRegistrationResponse), + container.get(TYPES.Auth_GenerateAuthenticatorAuthenticationOptions), + container.get(TYPES.Auth_ListAuthenticators), + container.get(TYPES.Auth_DeleteAuthenticator), + container.get(TYPES.Auth_AuthenticatorHttpMapper), + ), + ) + container + .bind(TYPES.Auth_SubscriptionInvitesController) + .to(SubscriptionInvitesController) + container.bind(TYPES.Auth_UserRequestsController).to(UserRequestsController) // Handlers - container.bind(TYPES.UserRegisteredEventHandler).to(UserRegisteredEventHandler) + container.bind(TYPES.Auth_UserRegisteredEventHandler).to(UserRegisteredEventHandler) container - .bind(TYPES.AccountDeletionRequestedEventHandler) + .bind(TYPES.Auth_AccountDeletionRequestedEventHandler) .to(AccountDeletionRequestedEventHandler) container - .bind(TYPES.SubscriptionPurchasedEventHandler) + .bind(TYPES.Auth_SubscriptionPurchasedEventHandler) .to(SubscriptionPurchasedEventHandler) container - .bind(TYPES.SubscriptionCancelledEventHandler) + .bind(TYPES.Auth_SubscriptionCancelledEventHandler) .to(SubscriptionCancelledEventHandler) container - .bind(TYPES.SubscriptionRenewedEventHandler) + .bind(TYPES.Auth_SubscriptionRenewedEventHandler) .to(SubscriptionRenewedEventHandler) container - .bind(TYPES.SubscriptionRefundedEventHandler) + .bind(TYPES.Auth_SubscriptionRefundedEventHandler) .to(SubscriptionRefundedEventHandler) container - .bind(TYPES.SubscriptionExpiredEventHandler) + .bind(TYPES.Auth_SubscriptionExpiredEventHandler) .to(SubscriptionExpiredEventHandler) container - .bind(TYPES.SubscriptionSyncRequestedEventHandler) + .bind(TYPES.Auth_SubscriptionSyncRequestedEventHandler) .to(SubscriptionSyncRequestedEventHandler) container - .bind(TYPES.ExtensionKeyGrantedEventHandler) + .bind(TYPES.Auth_ExtensionKeyGrantedEventHandler) .to(ExtensionKeyGrantedEventHandler) container - .bind(TYPES.SubscriptionReassignedEventHandler) + .bind(TYPES.Auth_SubscriptionReassignedEventHandler) .to(SubscriptionReassignedEventHandler) - container.bind(TYPES.UserEmailChangedEventHandler).to(UserEmailChangedEventHandler) - container.bind(TYPES.FileUploadedEventHandler).to(FileUploadedEventHandler) - container.bind(TYPES.FileRemovedEventHandler).to(FileRemovedEventHandler) container - .bind(TYPES.ListedAccountCreatedEventHandler) + .bind(TYPES.Auth_UserEmailChangedEventHandler) + .to(UserEmailChangedEventHandler) + container.bind(TYPES.Auth_FileUploadedEventHandler).to(FileUploadedEventHandler) + container.bind(TYPES.Auth_FileRemovedEventHandler).to(FileRemovedEventHandler) + container + .bind(TYPES.Auth_ListedAccountCreatedEventHandler) .to(ListedAccountCreatedEventHandler) container - .bind(TYPES.ListedAccountDeletedEventHandler) + .bind(TYPES.Auth_ListedAccountDeletedEventHandler) .to(ListedAccountDeletedEventHandler) container - .bind(TYPES.UserDisabledSessionUserAgentLoggingEventHandler) + .bind(TYPES.Auth_UserDisabledSessionUserAgentLoggingEventHandler) .to(UserDisabledSessionUserAgentLoggingEventHandler) container - .bind(TYPES.SharedSubscriptionInvitationCreatedEventHandler) + .bind(TYPES.Auth_SharedSubscriptionInvitationCreatedEventHandler) .to(SharedSubscriptionInvitationCreatedEventHandler) container - .bind(TYPES.PredicateVerificationRequestedEventHandler) + .bind(TYPES.Auth_PredicateVerificationRequestedEventHandler) .to(PredicateVerificationRequestedEventHandler) container - .bind(TYPES.EmailSubscriptionUnsubscribedEventHandler) + .bind(TYPES.Auth_EmailSubscriptionUnsubscribedEventHandler) .toConstantValue( new EmailSubscriptionUnsubscribedEventHandler( - container.get(TYPES.UserRepository), - container.get(TYPES.SettingService), + container.get(TYPES.Auth_UserRepository), + container.get(TYPES.Auth_SettingService), ), ) const eventHandlers: Map = new Map([ - ['USER_REGISTERED', container.get(TYPES.UserRegisteredEventHandler)], - ['ACCOUNT_DELETION_REQUESTED', container.get(TYPES.AccountDeletionRequestedEventHandler)], - ['SUBSCRIPTION_PURCHASED', container.get(TYPES.SubscriptionPurchasedEventHandler)], - ['SUBSCRIPTION_CANCELLED', container.get(TYPES.SubscriptionCancelledEventHandler)], - ['SUBSCRIPTION_RENEWED', container.get(TYPES.SubscriptionRenewedEventHandler)], - ['SUBSCRIPTION_REFUNDED', container.get(TYPES.SubscriptionRefundedEventHandler)], - ['SUBSCRIPTION_EXPIRED', container.get(TYPES.SubscriptionExpiredEventHandler)], - ['SUBSCRIPTION_SYNC_REQUESTED', container.get(TYPES.SubscriptionSyncRequestedEventHandler)], - ['EXTENSION_KEY_GRANTED', container.get(TYPES.ExtensionKeyGrantedEventHandler)], - ['SUBSCRIPTION_REASSIGNED', container.get(TYPES.SubscriptionReassignedEventHandler)], - ['USER_EMAIL_CHANGED', container.get(TYPES.UserEmailChangedEventHandler)], - ['FILE_UPLOADED', container.get(TYPES.FileUploadedEventHandler)], - ['FILE_REMOVED', container.get(TYPES.FileRemovedEventHandler)], - ['LISTED_ACCOUNT_CREATED', container.get(TYPES.ListedAccountCreatedEventHandler)], - ['LISTED_ACCOUNT_DELETED', container.get(TYPES.ListedAccountDeletedEventHandler)], + ['USER_REGISTERED', container.get(TYPES.Auth_UserRegisteredEventHandler)], + ['ACCOUNT_DELETION_REQUESTED', container.get(TYPES.Auth_AccountDeletionRequestedEventHandler)], + ['SUBSCRIPTION_PURCHASED', container.get(TYPES.Auth_SubscriptionPurchasedEventHandler)], + ['SUBSCRIPTION_CANCELLED', container.get(TYPES.Auth_SubscriptionCancelledEventHandler)], + ['SUBSCRIPTION_RENEWED', container.get(TYPES.Auth_SubscriptionRenewedEventHandler)], + ['SUBSCRIPTION_REFUNDED', container.get(TYPES.Auth_SubscriptionRefundedEventHandler)], + ['SUBSCRIPTION_EXPIRED', container.get(TYPES.Auth_SubscriptionExpiredEventHandler)], + ['SUBSCRIPTION_SYNC_REQUESTED', container.get(TYPES.Auth_SubscriptionSyncRequestedEventHandler)], + ['EXTENSION_KEY_GRANTED', container.get(TYPES.Auth_ExtensionKeyGrantedEventHandler)], + ['SUBSCRIPTION_REASSIGNED', container.get(TYPES.Auth_SubscriptionReassignedEventHandler)], + ['USER_EMAIL_CHANGED', container.get(TYPES.Auth_UserEmailChangedEventHandler)], + ['FILE_UPLOADED', container.get(TYPES.Auth_FileUploadedEventHandler)], + ['FILE_REMOVED', container.get(TYPES.Auth_FileRemovedEventHandler)], + ['LISTED_ACCOUNT_CREATED', container.get(TYPES.Auth_ListedAccountCreatedEventHandler)], + ['LISTED_ACCOUNT_DELETED', container.get(TYPES.Auth_ListedAccountDeletedEventHandler)], [ 'USER_DISABLED_SESSION_USER_AGENT_LOGGING', - container.get(TYPES.UserDisabledSessionUserAgentLoggingEventHandler), + container.get(TYPES.Auth_UserDisabledSessionUserAgentLoggingEventHandler), ], - ['SHARED_SUBSCRIPTION_INVITATION_CREATED', container.get(TYPES.SharedSubscriptionInvitationCreatedEventHandler)], - ['PREDICATE_VERIFICATION_REQUESTED', container.get(TYPES.PredicateVerificationRequestedEventHandler)], - ['EMAIL_SUBSCRIPTION_UNSUBSCRIBED', container.get(TYPES.EmailSubscriptionUnsubscribedEventHandler)], + [ + 'SHARED_SUBSCRIPTION_INVITATION_CREATED', + container.get(TYPES.Auth_SharedSubscriptionInvitationCreatedEventHandler), + ], + ['PREDICATE_VERIFICATION_REQUESTED', container.get(TYPES.Auth_PredicateVerificationRequestedEventHandler)], + ['EMAIL_SUBSCRIPTION_UNSUBSCRIBED', container.get(TYPES.Auth_EmailSubscriptionUnsubscribedEventHandler)], ]) container - .bind(TYPES.DomainEventMessageHandler) + .bind(TYPES.Auth_DomainEventMessageHandler) .toConstantValue( env.get('NEW_RELIC_ENABLED', true) === 'true' - ? new SQSNewRelicEventMessageHandler(eventHandlers, container.get(TYPES.Logger)) - : new SQSEventMessageHandler(eventHandlers, container.get(TYPES.Logger)), + ? new SQSNewRelicEventMessageHandler(eventHandlers, container.get(TYPES.Auth_Logger)) + : new SQSEventMessageHandler(eventHandlers, container.get(TYPES.Auth_Logger)), ) container - .bind(TYPES.DomainEventSubscriberFactory) + .bind(TYPES.Auth_DomainEventSubscriberFactory) .toConstantValue( new SQSDomainEventSubscriberFactory( - container.get(TYPES.SQS), - container.get(TYPES.SQS_QUEUE_URL), - container.get(TYPES.DomainEventMessageHandler), + container.get(TYPES.Auth_SQS), + container.get(TYPES.Auth_SQS_QUEUE_URL), + container.get(TYPES.Auth_DomainEventMessageHandler), + ), + ) + + container + .bind(TYPES.Auth_InversifyExpressAuthController) + .toConstantValue( + new InversifyExpressAuthController( + container.get(TYPES.Auth_VerifyMFA), + container.get(TYPES.Auth_SignIn), + container.get(TYPES.Auth_GetUserKeyParams), + container.get(TYPES.Auth_ClearLoginAttempts), + container.get(TYPES.Auth_IncreaseLoginAttempts), + container.get(TYPES.Auth_Logger), + container.get(TYPES.Auth_AuthController), + container.get(TYPES.Auth_ControllerContainer), + ), + ) + container + .bind(TYPES.Auth_InversifyExpressAuthenticatorsController) + .toConstantValue( + new InversifyExpressAuthenticatorsController( + container.get(TYPES.Auth_AuthenticatorsController), + container.get(TYPES.Auth_ControllerContainer), + ), + ) + container + .bind(TYPES.Auth_InversifyExpressSubscriptionInvitesController) + .toConstantValue( + new InversifyExpressSubscriptionInvitesController( + container.get(TYPES.Auth_SubscriptionInvitesController), + container.get(TYPES.Auth_ControllerContainer), + ), + ) + container + .bind(TYPES.Auth_InversifyExpressUserRequestsController) + .toConstantValue( + new InversifyExpressUserRequestsController( + container.get(TYPES.Auth_UserRequestsController), + container.get(TYPES.Auth_ControllerContainer), + ), + ) + container + .bind(TYPES.Auth_InversifyExpressWebSocketsController) + .toConstantValue( + new InversifyExpressWebSocketsController( + container.get(TYPES.Auth_CreateCrossServiceToken), + container.get(TYPES.Auth_WebSocketConnectionTokenDecoder), + container.get(TYPES.Auth_ControllerContainer), ), ) diff --git a/packages/auth/src/Bootstrap/DataSource.ts b/packages/auth/src/Bootstrap/DataSource.ts index b6a1edae4..e178f1ef6 100644 --- a/packages/auth/src/Bootstrap/DataSource.ts +++ b/packages/auth/src/Bootstrap/DataSource.ts @@ -28,29 +28,6 @@ const maxQueryExecutionTime = env.get('DB_MAX_QUERY_EXECUTION_TIME', true) ? +env.get('DB_MAX_QUERY_EXECUTION_TIME', true) : 45_000 -const inReplicaMode = env.get('DB_REPLICA_HOST', true) ? true : false - -const replicationConfig = { - master: { - host: env.get('DB_HOST'), - port: parseInt(env.get('DB_PORT')), - username: env.get('DB_USERNAME'), - password: env.get('DB_PASSWORD'), - database: env.get('DB_DATABASE'), - }, - slaves: [ - { - host: env.get('DB_REPLICA_HOST', true), - port: parseInt(env.get('DB_PORT')), - username: env.get('DB_USERNAME'), - password: env.get('DB_PASSWORD'), - database: env.get('DB_DATABASE'), - }, - ], - removeNodeErrorCount: 10, - restoreNodeTimeout: 5, -} - const commonDataSourceOptions = { maxQueryExecutionTime, entities: [ @@ -71,29 +48,59 @@ const commonDataSourceOptions = { TypeORMEmergencyAccessInvitation, TypeORMCacheEntry, ], - migrations: [`dist/migrations/${isConfiguredForMySQL ? 'mysql' : 'sqlite'}/*.js`], + migrations: [`${__dirname}/../../migrations/${isConfiguredForMySQL ? 'mysql' : 'sqlite'}/*.js`], migrationsRun: true, - logging: env.get('DB_DEBUG_LEVEL'), + logging: env.get('DB_DEBUG_LEVEL', true) ?? 'info', } -const mySQLDataSourceOptions: MysqlConnectionOptions = { - ...commonDataSourceOptions, - type: 'mysql', - charset: 'utf8mb4', - supportBigNumbers: true, - bigNumberStrings: false, - replication: inReplicaMode ? replicationConfig : undefined, - host: inReplicaMode ? undefined : env.get('DB_HOST'), - port: inReplicaMode ? undefined : parseInt(env.get('DB_PORT')), - username: inReplicaMode ? undefined : env.get('DB_USERNAME'), - password: inReplicaMode ? undefined : env.get('DB_PASSWORD'), - database: inReplicaMode ? undefined : env.get('DB_DATABASE'), +let dataSource: DataSource +if (isConfiguredForMySQL) { + const inReplicaMode = env.get('DB_REPLICA_HOST', true) ? true : false + + const replicationConfig = { + master: { + host: env.get('DB_HOST'), + port: parseInt(env.get('DB_PORT')), + username: env.get('DB_USERNAME'), + password: env.get('DB_PASSWORD'), + database: env.get('DB_DATABASE'), + }, + slaves: [ + { + host: env.get('DB_REPLICA_HOST', true), + port: parseInt(env.get('DB_PORT')), + username: env.get('DB_USERNAME'), + password: env.get('DB_PASSWORD'), + database: env.get('DB_DATABASE'), + }, + ], + removeNodeErrorCount: 10, + restoreNodeTimeout: 5, + } + + const mySQLDataSourceOptions: MysqlConnectionOptions = { + ...commonDataSourceOptions, + type: 'mysql', + charset: 'utf8mb4', + supportBigNumbers: true, + bigNumberStrings: false, + replication: inReplicaMode ? replicationConfig : undefined, + host: inReplicaMode ? undefined : env.get('DB_HOST'), + port: inReplicaMode ? undefined : parseInt(env.get('DB_PORT')), + username: inReplicaMode ? undefined : env.get('DB_USERNAME'), + password: inReplicaMode ? undefined : env.get('DB_PASSWORD'), + database: inReplicaMode ? undefined : env.get('DB_DATABASE'), + } + + dataSource = new DataSource(mySQLDataSourceOptions) +} else { + const sqliteDataSourceOptions: SqliteConnectionOptions = { + ...commonDataSourceOptions, + type: 'sqlite', + database: `data/${env.get('DB_DATABASE')}.sqlite`, + } + + dataSource = new DataSource(sqliteDataSourceOptions) } -const sqliteDataSourceOptions: SqliteConnectionOptions = { - ...commonDataSourceOptions, - type: 'sqlite', - database: `data/${env.get('DB_DATABASE')}.sqlite`, -} - -export const AppDataSource = new DataSource(isConfiguredForMySQL ? mySQLDataSourceOptions : sqliteDataSourceOptions) +export const AppDataSource = dataSource diff --git a/packages/auth/src/Bootstrap/Service.ts b/packages/auth/src/Bootstrap/Service.ts new file mode 100644 index 000000000..0cb4e4ce2 --- /dev/null +++ b/packages/auth/src/Bootstrap/Service.ts @@ -0,0 +1,37 @@ +import { + ControllerContainerInterface, + ServiceContainerInterface, + ServiceIdentifier, + ServiceInterface, +} from '@standardnotes/domain-core' + +import { ContainerConfigLoader } from './Container' + +export class Service implements ServiceInterface { + constructor( + private serviceContainer: ServiceContainerInterface, + private controllerContainer: ControllerContainerInterface, + ) { + this.serviceContainer.register(ServiceIdentifier.create(ServiceIdentifier.NAMES.Auth).getValue(), this) + } + + async handleRequest(request: never, response: never, endpointOrMethodIdentifier: string): Promise { + const method = this.controllerContainer.get(endpointOrMethodIdentifier) + + if (!method) { + throw new Error(`Method ${endpointOrMethodIdentifier} not found`) + } + + return method(request, response) + } + + async getContainer(): Promise { + const config = new ContainerConfigLoader() + + return config.load(this.controllerContainer) + } + + getId(): ServiceIdentifier { + return ServiceIdentifier.create(ServiceIdentifier.NAMES.Auth).getValue() + } +} diff --git a/packages/auth/src/Bootstrap/Types.ts b/packages/auth/src/Bootstrap/Types.ts index 40241fd3e..9a55b0468 100644 --- a/packages/auth/src/Bootstrap/Types.ts +++ b/packages/auth/src/Bootstrap/Types.ts @@ -1,217 +1,227 @@ const TYPES = { - Logger: Symbol.for('Logger'), - Redis: Symbol.for('Redis'), - SNS: Symbol.for('SNS'), - SQS: Symbol.for('SQS'), + Auth_Logger: Symbol.for('Auth_Logger'), + Auth_Redis: Symbol.for('Auth_Redis'), + Auth_SNS: Symbol.for('Auth_SNS'), + Auth_SQS: Symbol.for('Auth_SQS'), // Mapping - SessionTracePersistenceMapper: Symbol.for('SessionTracePersistenceMapper'), - AuthenticatorChallengePersistenceMapper: Symbol.for('AuthenticatorChallengePersistenceMapper'), - AuthenticatorPersistenceMapper: Symbol.for('AuthenticatorPersistenceMapper'), - AuthenticatorHttpMapper: Symbol.for('AuthenticatorHttpMapper'), - CacheEntryPersistenceMapper: Symbol.for('CacheEntryPersistenceMapper'), + Auth_SessionTracePersistenceMapper: Symbol.for('Auth_SessionTracePersistenceMapper'), + Auth_AuthenticatorChallengePersistenceMapper: Symbol.for('Auth_AuthenticatorChallengePersistenceMapper'), + Auth_AuthenticatorPersistenceMapper: Symbol.for('Auth_AuthenticatorPersistenceMapper'), + Auth_AuthenticatorHttpMapper: Symbol.for('Auth_AuthenticatorHttpMapper'), + Auth_CacheEntryPersistenceMapper: Symbol.for('Auth_CacheEntryPersistenceMapper'), // Controller - AuthController: Symbol.for('AuthController'), - AuthenticatorsController: Symbol.for('AuthenticatorsController'), - SubscriptionInvitesController: Symbol.for('SubscriptionInvitesController'), - UserRequestsController: Symbol.for('UserRequestsController'), + Auth_ControllerContainer: Symbol.for('Auth_ControllerContainer'), + Auth_AuthController: Symbol.for('Auth_AuthController'), + Auth_AuthenticatorsController: Symbol.for('Auth_AuthenticatorsController'), + Auth_SubscriptionInvitesController: Symbol.for('Auth_SubscriptionInvitesController'), + Auth_UserRequestsController: Symbol.for('Auth_UserRequestsController'), // Repositories - UserRepository: Symbol.for('UserRepository'), - SessionRepository: Symbol.for('SessionRepository'), - EphemeralSessionRepository: Symbol.for('EphemeralSessionRepository'), - RevokedSessionRepository: Symbol.for('RevokedSessionRepository'), - SettingRepository: Symbol.for('SettingRepository'), - SubscriptionSettingRepository: Symbol.for('SubscriptionSettingRepository'), - OfflineSettingRepository: Symbol.for('OfflineSettingRepository'), - LockRepository: Symbol.for('LockRepository'), - RoleRepository: Symbol.for('RoleRepository'), - UserSubscriptionRepository: Symbol.for('UserSubscriptionRepository'), - OfflineUserSubscriptionRepository: Symbol.for('OfflineUserSubscriptionRepository'), - SubscriptionTokenRepository: Symbol.for('SubscriptionTokenRepository'), - OfflineSubscriptionTokenRepository: Symbol.for('OfflineSubscriptionTokenRepository'), - SharedSubscriptionInvitationRepository: Symbol.for('SharedSubscriptionInvitationRepository'), - PKCERepository: Symbol.for('PKCERepository'), - SessionTraceRepository: Symbol.for('SessionTraceRepository'), - AuthenticatorRepository: Symbol.for('AuthenticatorRepository'), - AuthenticatorChallengeRepository: Symbol.for('AuthenticatorChallengeRepository'), - CacheEntryRepository: Symbol.for('CacheEntryRepository'), + Auth_UserRepository: Symbol.for('Auth_UserRepository'), + Auth_SessionRepository: Symbol.for('Auth_SessionRepository'), + Auth_EphemeralSessionRepository: Symbol.for('Auth_EphemeralSessionRepository'), + Auth_RevokedSessionRepository: Symbol.for('Auth_RevokedSessionRepository'), + Auth_SettingRepository: Symbol.for('Auth_SettingRepository'), + Auth_SubscriptionSettingRepository: Symbol.for('Auth_SubscriptionSettingRepository'), + Auth_OfflineSettingRepository: Symbol.for('Auth_OfflineSettingRepository'), + Auth_LockRepository: Symbol.for('Auth_LockRepository'), + Auth_RoleRepository: Symbol.for('Auth_RoleRepository'), + Auth_UserSubscriptionRepository: Symbol.for('Auth_UserSubscriptionRepository'), + Auth_OfflineUserSubscriptionRepository: Symbol.for('Auth_OfflineUserSubscriptionRepository'), + Auth_SubscriptionTokenRepository: Symbol.for('Auth_SubscriptionTokenRepository'), + Auth_OfflineSubscriptionTokenRepository: Symbol.for('Auth_OfflineSubscriptionTokenRepository'), + Auth_SharedSubscriptionInvitationRepository: Symbol.for('Auth_SharedSubscriptionInvitationRepository'), + Auth_PKCERepository: Symbol.for('Auth_PKCERepository'), + Auth_SessionTraceRepository: Symbol.for('Auth_SessionTraceRepository'), + Auth_AuthenticatorRepository: Symbol.for('Auth_AuthenticatorRepository'), + Auth_AuthenticatorChallengeRepository: Symbol.for('Auth_AuthenticatorChallengeRepository'), + Auth_CacheEntryRepository: Symbol.for('Auth_CacheEntryRepository'), // ORM - ORMOfflineSettingRepository: Symbol.for('ORMOfflineSettingRepository'), - ORMOfflineUserSubscriptionRepository: Symbol.for('ORMOfflineUserSubscriptionRepository'), - ORMRevokedSessionRepository: Symbol.for('ORMRevokedSessionRepository'), - ORMRoleRepository: Symbol.for('ORMRoleRepository'), - ORMSessionRepository: Symbol.for('ORMSessionRepository'), - ORMSettingRepository: Symbol.for('ORMSettingRepository'), - ORMSharedSubscriptionInvitationRepository: Symbol.for('ORMSharedSubscriptionInvitationRepository'), - ORMSubscriptionSettingRepository: Symbol.for('ORMSubscriptionSettingRepository'), - ORMUserRepository: Symbol.for('ORMUserRepository'), - ORMUserSubscriptionRepository: Symbol.for('ORMUserSubscriptionRepository'), - ORMSessionTraceRepository: Symbol.for('ORMSessionTraceRepository'), - ORMAuthenticatorRepository: Symbol.for('ORMAuthenticatorRepository'), - ORMAuthenticatorChallengeRepository: Symbol.for('ORMAuthenticatorChallengeRepository'), - ORMCacheEntryRepository: Symbol.for('ORMCacheEntryRepository'), + Auth_ORMOfflineSettingRepository: Symbol.for('Auth_ORMOfflineSettingRepository'), + Auth_ORMOfflineUserSubscriptionRepository: Symbol.for('Auth_ORMOfflineUserSubscriptionRepository'), + Auth_ORMRevokedSessionRepository: Symbol.for('Auth_ORMRevokedSessionRepository'), + Auth_ORMRoleRepository: Symbol.for('Auth_ORMRoleRepository'), + Auth_ORMSessionRepository: Symbol.for('Auth_ORMSessionRepository'), + Auth_ORMSettingRepository: Symbol.for('Auth_ORMSettingRepository'), + Auth_ORMSharedSubscriptionInvitationRepository: Symbol.for('Auth_ORMSharedSubscriptionInvitationRepository'), + Auth_ORMSubscriptionSettingRepository: Symbol.for('Auth_ORMSubscriptionSettingRepository'), + Auth_ORMUserRepository: Symbol.for('Auth_ORMUserRepository'), + Auth_ORMUserSubscriptionRepository: Symbol.for('Auth_ORMUserSubscriptionRepository'), + Auth_ORMSessionTraceRepository: Symbol.for('Auth_ORMSessionTraceRepository'), + Auth_ORMAuthenticatorRepository: Symbol.for('Auth_ORMAuthenticatorRepository'), + Auth_ORMAuthenticatorChallengeRepository: Symbol.for('Auth_ORMAuthenticatorChallengeRepository'), + Auth_ORMCacheEntryRepository: Symbol.for('Auth_ORMCacheEntryRepository'), // Middleware - AuthMiddleware: Symbol.for('AuthMiddleware'), - ApiGatewayAuthMiddleware: Symbol.for('ApiGatewayAuthMiddleware'), - ApiGatewayOfflineAuthMiddleware: Symbol.for('ApiGatewayOfflineAuthMiddleware'), - OfflineUserAuthMiddleware: Symbol.for('OfflineUserAuthMiddleware'), - AuthMiddlewareWithoutResponse: Symbol.for('AuthMiddlewareWithoutResponse'), - LockMiddleware: Symbol.for('LockMiddleware'), - SessionMiddleware: Symbol.for('SessionMiddleware'), + Auth_AuthMiddleware: Symbol.for('Auth_AuthMiddleware'), + Auth_ApiGatewayAuthMiddleware: Symbol.for('Auth_ApiGatewayAuthMiddleware'), + Auth_ApiGatewayOfflineAuthMiddleware: Symbol.for('Auth_ApiGatewayOfflineAuthMiddleware'), + Auth_OfflineUserAuthMiddleware: Symbol.for('Auth_OfflineUserAuthMiddleware'), + Auth_AuthMiddlewareWithoutResponse: Symbol.for('Auth_AuthMiddlewareWithoutResponse'), + Auth_LockMiddleware: Symbol.for('Auth_LockMiddleware'), + Auth_SessionMiddleware: Symbol.for('Auth_SessionMiddleware'), // Projectors - SessionProjector: Symbol.for('SessionProjector'), - UserProjector: Symbol.for('UserProjector'), - RoleProjector: Symbol.for('RoleProjector'), - PermissionProjector: Symbol.for('PermissionProjector'), - SettingProjector: Symbol.for('SettingProjector'), - SubscriptionSettingProjector: Symbol.for('SubscriptionSettingProjector'), + Auth_SessionProjector: Symbol.for('Auth_SessionProjector'), + Auth_UserProjector: Symbol.for('Auth_UserProjector'), + Auth_RoleProjector: Symbol.for('Auth_RoleProjector'), + Auth_PermissionProjector: Symbol.for('Auth_PermissionProjector'), + Auth_SettingProjector: Symbol.for('Auth_SettingProjector'), + Auth_SubscriptionSettingProjector: Symbol.for('Auth_SubscriptionSettingProjector'), // Factories - SettingFactory: Symbol.for('SettingFactory'), + Auth_SettingFactory: Symbol.for('Auth_SettingFactory'), // env vars - JWT_SECRET: Symbol.for('JWT_SECRET'), - LEGACY_JWT_SECRET: Symbol.for('LEGACY_JWT_SECRET'), - AUTH_JWT_SECRET: Symbol.for('AUTH_JWT_SECRET'), - AUTH_JWT_TTL: Symbol.for('AUTH_JWT_TTL'), - VALET_TOKEN_SECRET: Symbol.for('VALET_TOKEN_SECRET'), - VALET_TOKEN_TTL: Symbol.for('VALET_TOKEN_TTL'), - WEB_SOCKET_CONNECTION_TOKEN_SECRET: Symbol.for('WEB_SOCKET_CONNECTION_TOKEN_SECRET'), - WEB_SOCKET_CONNECTION_TOKEN_TTL: Symbol.for('WEB_SOCKET_CONNECTION_TOKEN_TTL'), - ENCRYPTION_SERVER_KEY: Symbol.for('ENCRYPTION_SERVER_KEY'), - ACCESS_TOKEN_AGE: Symbol.for('ACCESS_TOKEN_AGE'), - REFRESH_TOKEN_AGE: Symbol.for('REFRESH_TOKEN_AGE'), - EPHEMERAL_SESSION_AGE: Symbol.for('EPHEMERAL_SESSION_AGE'), - MAX_LOGIN_ATTEMPTS: Symbol.for('MAX_LOGIN_ATTEMPTS'), - FAILED_LOGIN_LOCKOUT: Symbol.for('FAILED_LOGIN_LOCKOUT'), - PSEUDO_KEY_PARAMS_KEY: Symbol.for('PSEUDO_KEY_PARAMS_KEY'), - REDIS_URL: Symbol.for('REDIS_URL'), - DISABLE_USER_REGISTRATION: Symbol.for('DISABLE_USER_REGISTRATION'), - SNS_TOPIC_ARN: Symbol.for('SNS_TOPIC_ARN'), - SNS_AWS_REGION: Symbol.for('SNS_AWS_REGION'), - SQS_QUEUE_URL: Symbol.for('SQS_QUEUE_URL'), - SQS_AWS_REGION: Symbol.for('SQS_AWS_REGION'), - USER_SERVER_REGISTRATION_URL: Symbol.for('USER_SERVER_REGISTRATION_URL'), - USER_SERVER_AUTH_KEY: Symbol.for('USER_SERVER_AUTH_KEY'), - USER_SERVER_CHANGE_EMAIL_URL: Symbol.for('USER_SERVER_CHANGE_EMAIL_URL'), - NEW_RELIC_ENABLED: Symbol.for('NEW_RELIC_ENABLED'), - SYNCING_SERVER_URL: Symbol.for('SYNCING_SERVER_URL'), - VERSION: Symbol.for('VERSION'), - PAYMENTS_SERVER_URL: Symbol.for('PAYMENTS_SERVER_URL'), - SESSION_TRACE_DAYS_TTL: Symbol.for('SESSION_TRACE_DAYS_TTL'), - U2F_RELYING_PARTY_ID: Symbol.for('U2F_RELYING_PARTY_ID'), - U2F_RELYING_PARTY_NAME: Symbol.for('U2F_RELYING_PARTY_NAME'), - U2F_EXPECTED_ORIGIN: Symbol.for('U2F_EXPECTED_ORIGIN'), - U2F_REQUIRE_USER_VERIFICATION: Symbol.for('U2F_REQUIRE_USER_VERIFICATION'), - READONLY_USERS: Symbol.for('READONLY_USERS'), + Auth_JWT_SECRET: Symbol.for('Auth_JWT_SECRET'), + Auth_LEGACY_JWT_SECRET: Symbol.for('Auth_LEGACY_JWT_SECRET'), + Auth_AUTH_JWT_SECRET: Symbol.for('Auth_AUTH_JWT_SECRET'), + Auth_AUTH_JWT_TTL: Symbol.for('Auth_AUTH_JWT_TTL'), + Auth_VALET_TOKEN_SECRET: Symbol.for('Auth_VALET_TOKEN_SECRET'), + Auth_VALET_TOKEN_TTL: Symbol.for('Auth_VALET_TOKEN_TTL'), + Auth_WEB_SOCKET_CONNECTION_TOKEN_SECRET: Symbol.for('Auth_WEB_SOCKET_CONNECTION_TOKEN_SECRET'), + Auth_WEB_SOCKET_CONNECTION_TOKEN_TTL: Symbol.for('Auth_WEB_SOCKET_CONNECTION_TOKEN_TTL'), + Auth_ENCRYPTION_SERVER_KEY: Symbol.for('Auth_ENCRYPTION_SERVER_KEY'), + Auth_ACCESS_TOKEN_AGE: Symbol.for('Auth_ACCESS_TOKEN_AGE'), + Auth_REFRESH_TOKEN_AGE: Symbol.for('Auth_REFRESH_TOKEN_AGE'), + Auth_EPHEMERAL_SESSION_AGE: Symbol.for('Auth_EPHEMERAL_SESSION_AGE'), + Auth_MAX_LOGIN_ATTEMPTS: Symbol.for('Auth_MAX_LOGIN_ATTEMPTS'), + Auth_FAILED_LOGIN_LOCKOUT: Symbol.for('Auth_FAILED_LOGIN_LOCKOUT'), + Auth_PSEUDO_KEY_PARAMS_KEY: Symbol.for('Auth_PSEUDO_KEY_PARAMS_KEY'), + Auth_REDIS_URL: Symbol.for('Auth_REDIS_URL'), + Auth_DISABLE_USER_REGISTRATION: Symbol.for('Auth_DISABLE_USER_REGISTRATION'), + Auth_SNS_TOPIC_ARN: Symbol.for('Auth_SNS_TOPIC_ARN'), + Auth_SNS_AWS_REGION: Symbol.for('Auth_SNS_AWS_REGION'), + Auth_SQS_QUEUE_URL: Symbol.for('Auth_SQS_QUEUE_URL'), + Auth_SQS_AWS_REGION: Symbol.for('Auth_SQS_AWS_REGION'), + Auth_USER_SERVER_REGISTRATION_URL: Symbol.for('Auth_USER_SERVER_REGISTRATION_URL'), + Auth_USER_SERVER_AUTH_KEY: Symbol.for('Auth_USER_SERVER_AUTH_KEY'), + Auth_USER_SERVER_CHANGE_EMAIL_URL: Symbol.for('Auth_USER_SERVER_CHANGE_EMAIL_URL'), + Auth_NEW_RELIC_ENABLED: Symbol.for('Auth_NEW_RELIC_ENABLED'), + Auth_SYNCING_SERVER_URL: Symbol.for('Auth_SYNCING_SERVER_URL'), + Auth_VERSION: Symbol.for('Auth_VERSION'), + Auth_PAYMENTS_SERVER_URL: Symbol.for('Auth_PAYMENTS_SERVER_URL'), + Auth_SESSION_TRACE_DAYS_TTL: Symbol.for('Auth_SESSION_TRACE_DAYS_TTL'), + Auth_U2F_RELYING_PARTY_ID: Symbol.for('Auth_U2F_RELYING_PARTY_ID'), + Auth_U2F_RELYING_PARTY_NAME: Symbol.for('Auth_U2F_RELYING_PARTY_NAME'), + Auth_U2F_EXPECTED_ORIGIN: Symbol.for('Auth_U2F_EXPECTED_ORIGIN'), + Auth_U2F_REQUIRE_USER_VERIFICATION: Symbol.for('Auth_U2F_REQUIRE_USER_VERIFICATION'), + Auth_READONLY_USERS: Symbol.for('Auth_READONLY_USERS'), // use cases - AuthenticateUser: Symbol.for('AuthenticateUser'), - AuthenticateRequest: Symbol.for('AuthenticateRequest'), - RefreshSessionToken: Symbol.for('RefreshSessionToken'), - VerifyMFA: Symbol.for('VerifyMFA'), - SignIn: Symbol.for('SignIn'), - ClearLoginAttempts: Symbol.for('ClearLoginAttempts'), - IncreaseLoginAttempts: Symbol.for('IncreaseLoginAttempts'), - GetUserKeyParams: Symbol.for('GetUserKeyParams'), - UpdateUser: Symbol.for('UpdateUser'), - Register: Symbol.for('Register'), - GetActiveSessionsForUser: Symbol.for('GetActiveSessionsForUser'), - DeletePreviousSessionsForUser: Symbol.for('DeletePreviousSessionsForUser'), - DeleteSessionForUser: Symbol.for('DeleteSessionForUser'), - ChangeCredentials: Symbol.for('ChangePassword'), - GetSettings: Symbol.for('GetSettings'), - GetSetting: Symbol.for('GetSetting'), - GetUserFeatures: Symbol.for('GetUserFeatures'), - UpdateSetting: Symbol.for('UpdateSetting'), - DeleteSetting: Symbol.for('DeleteSetting'), - DeleteAccount: Symbol.for('DeleteAccount'), - GetUserSubscription: Symbol.for('GetUserSubscription'), - GetUserOfflineSubscription: Symbol.for('GetUserOfflineSubscription'), - CreateSubscriptionToken: Symbol.for('CreateSubscriptionToken'), - AuthenticateSubscriptionToken: Symbol.for('AuthenticateSubscriptionToken'), - CreateOfflineSubscriptionToken: Symbol.for('CreateOfflineSubscriptionToken'), - AuthenticateOfflineSubscriptionToken: Symbol.for('AuthenticateOfflineSubscriptionToken'), - CreateValetToken: Symbol.for('CreateValetToken'), - CreateListedAccount: Symbol.for('CreateListedAccount'), - InviteToSharedSubscription: Symbol.for('InviteToSharedSubscription'), - AcceptSharedSubscriptionInvitation: Symbol.for('AcceptSharedSubscriptionInvitation'), - DeclineSharedSubscriptionInvitation: Symbol.for('DeclineSharedSubscriptionInvitation'), - CancelSharedSubscriptionInvitation: Symbol.for('CancelSharedSubscriptionInvitation'), - ListSharedSubscriptionInvitations: Symbol.for('ListSharedSubscriptionInvitations'), - VerifyPredicate: Symbol.for('VerifyPredicate'), - CreateCrossServiceToken: Symbol.for('CreateCrossServiceToken'), - ProcessUserRequest: Symbol.for('ProcessUserRequest'), - TraceSession: Symbol.for('TraceSession'), - CleanupSessionTraces: Symbol.for('CleanupSessionTraces'), - CleanupExpiredSessions: Symbol.for('CleanupExpiredSessions'), - PersistStatistics: Symbol.for('PersistStatistics'), - GenerateAuthenticatorRegistrationOptions: Symbol.for('GenerateAuthenticatorRegistrationOptions'), - VerifyAuthenticatorRegistrationResponse: Symbol.for('VerifyAuthenticatorRegistrationResponse'), - GenerateAuthenticatorAuthenticationOptions: Symbol.for('GenerateAuthenticatorAuthenticationOptions'), - VerifyAuthenticatorAuthenticationResponse: Symbol.for('VerifyAuthenticatorAuthenticationResponse'), - ListAuthenticators: Symbol.for('ListAuthenticators'), - DeleteAuthenticator: Symbol.for('DeleteAuthenticator'), - GenerateRecoveryCodes: Symbol.for('GenerateRecoveryCodes'), - SignInWithRecoveryCodes: Symbol.for('SignInWithRecoveryCodes'), - GetUserKeyParamsRecovery: Symbol.for('GetUserKeyParamsRecovery'), + Auth_AuthenticateUser: Symbol.for('Auth_AuthenticateUser'), + Auth_AuthenticateRequest: Symbol.for('Auth_AuthenticateRequest'), + Auth_RefreshSessionToken: Symbol.for('Auth_RefreshSessionToken'), + Auth_VerifyMFA: Symbol.for('Auth_VerifyMFA'), + Auth_SignIn: Symbol.for('Auth_SignIn'), + Auth_ClearLoginAttempts: Symbol.for('Auth_ClearLoginAttempts'), + Auth_IncreaseLoginAttempts: Symbol.for('Auth_IncreaseLoginAttempts'), + Auth_GetUserKeyParams: Symbol.for('Auth_GetUserKeyParams'), + Auth_UpdateUser: Symbol.for('Auth_UpdateUser'), + Auth_Register: Symbol.for('Auth_Register'), + Auth_GetActiveSessionsForUser: Symbol.for('Auth_GetActiveSessionsForUser'), + Auth_DeletePreviousSessionsForUser: Symbol.for('Auth_DeletePreviousSessionsForUser'), + Auth_DeleteSessionForUser: Symbol.for('Auth_DeleteSessionForUser'), + Auth_ChangeCredentials: Symbol.for('Auth_ChangePassword'), + Auth_GetSettings: Symbol.for('Auth_GetSettings'), + Auth_GetSetting: Symbol.for('Auth_GetSetting'), + Auth_GetUserFeatures: Symbol.for('Auth_GetUserFeatures'), + Auth_UpdateSetting: Symbol.for('Auth_UpdateSetting'), + Auth_DeleteSetting: Symbol.for('Auth_DeleteSetting'), + Auth_DeleteAccount: Symbol.for('Auth_DeleteAccount'), + Auth_GetUserSubscription: Symbol.for('Auth_GetUserSubscription'), + Auth_GetUserOfflineSubscription: Symbol.for('Auth_GetUserOfflineSubscription'), + Auth_CreateSubscriptionToken: Symbol.for('Auth_CreateSubscriptionToken'), + Auth_AuthenticateSubscriptionToken: Symbol.for('Auth_AuthenticateSubscriptionToken'), + Auth_CreateOfflineSubscriptionToken: Symbol.for('Auth_CreateOfflineSubscriptionToken'), + Auth_AuthenticateOfflineSubscriptionToken: Symbol.for('Auth_AuthenticateOfflineSubscriptionToken'), + Auth_CreateValetToken: Symbol.for('Auth_CreateValetToken'), + Auth_CreateListedAccount: Symbol.for('Auth_CreateListedAccount'), + Auth_InviteToSharedSubscription: Symbol.for('Auth_InviteToSharedSubscription'), + Auth_AcceptSharedSubscriptionInvitation: Symbol.for('Auth_AcceptSharedSubscriptionInvitation'), + Auth_DeclineSharedSubscriptionInvitation: Symbol.for('Auth_DeclineSharedSubscriptionInvitation'), + Auth_CancelSharedSubscriptionInvitation: Symbol.for('Auth_CancelSharedSubscriptionInvitation'), + Auth_ListSharedSubscriptionInvitations: Symbol.for('Auth_ListSharedSubscriptionInvitations'), + Auth_VerifyPredicate: Symbol.for('Auth_VerifyPredicate'), + Auth_CreateCrossServiceToken: Symbol.for('Auth_CreateCrossServiceToken'), + Auth_ProcessUserRequest: Symbol.for('Auth_ProcessUserRequest'), + Auth_TraceSession: Symbol.for('Auth_TraceSession'), + Auth_CleanupSessionTraces: Symbol.for('Auth_CleanupSessionTraces'), + Auth_CleanupExpiredSessions: Symbol.for('Auth_CleanupExpiredSessions'), + Auth_PersistStatistics: Symbol.for('Auth_PersistStatistics'), + Auth_GenerateAuthenticatorRegistrationOptions: Symbol.for('Auth_GenerateAuthenticatorRegistrationOptions'), + Auth_VerifyAuthenticatorRegistrationResponse: Symbol.for('Auth_VerifyAuthenticatorRegistrationResponse'), + Auth_GenerateAuthenticatorAuthenticationOptions: Symbol.for('Auth_GenerateAuthenticatorAuthenticationOptions'), + Auth_VerifyAuthenticatorAuthenticationResponse: Symbol.for('Auth_VerifyAuthenticatorAuthenticationResponse'), + Auth_ListAuthenticators: Symbol.for('Auth_ListAuthenticators'), + Auth_DeleteAuthenticator: Symbol.for('Auth_DeleteAuthenticator'), + Auth_GenerateRecoveryCodes: Symbol.for('Auth_GenerateRecoveryCodes'), + Auth_SignInWithRecoveryCodes: Symbol.for('Auth_SignInWithRecoveryCodes'), + Auth_GetUserKeyParamsRecovery: Symbol.for('Auth_GetUserKeyParamsRecovery'), // Handlers - UserRegisteredEventHandler: Symbol.for('UserRegisteredEventHandler'), - AccountDeletionRequestedEventHandler: Symbol.for('AccountDeletionRequestedEventHandler'), - SubscriptionPurchasedEventHandler: Symbol.for('SubscriptionPurchasedEventHandler'), - SubscriptionCancelledEventHandler: Symbol.for('SubscriptionCancelledEventHandler'), - SubscriptionReassignedEventHandler: Symbol.for('SubscriptionReassignedEventHandler'), - SubscriptionRenewedEventHandler: Symbol.for('SubscriptionRenewedEventHandler'), - SubscriptionRefundedEventHandler: Symbol.for('SubscriptionRefundedEventHandler'), - SubscriptionExpiredEventHandler: Symbol.for('SubscriptionExpiredEventHandler'), - SubscriptionSyncRequestedEventHandler: Symbol.for('SubscriptionSyncRequestedEventHandler'), - ExtensionKeyGrantedEventHandler: Symbol.for('ExtensionKeyGrantedEventHandler'), - UserEmailChangedEventHandler: Symbol.for('UserEmailChangedEventHandler'), - FileUploadedEventHandler: Symbol.for('FileUploadedEventHandler'), - FileRemovedEventHandler: Symbol.for('FileRemovedEventHandler'), - ListedAccountCreatedEventHandler: Symbol.for('ListedAccountCreatedEventHandler'), - ListedAccountDeletedEventHandler: Symbol.for('ListedAccountDeletedEventHandler'), - UserDisabledSessionUserAgentLoggingEventHandler: Symbol.for('UserDisabledSessionUserAgentLoggingEventHandler'), - SharedSubscriptionInvitationCreatedEventHandler: Symbol.for('SharedSubscriptionInvitationCreatedEventHandler'), - PredicateVerificationRequestedEventHandler: Symbol.for('PredicateVerificationRequestedEventHandler'), - EmailSubscriptionUnsubscribedEventHandler: Symbol.for('EmailSubscriptionUnsubscribedEventHandler'), + Auth_UserRegisteredEventHandler: Symbol.for('Auth_UserRegisteredEventHandler'), + Auth_AccountDeletionRequestedEventHandler: Symbol.for('Auth_AccountDeletionRequestedEventHandler'), + Auth_SubscriptionPurchasedEventHandler: Symbol.for('Auth_SubscriptionPurchasedEventHandler'), + Auth_SubscriptionCancelledEventHandler: Symbol.for('Auth_SubscriptionCancelledEventHandler'), + Auth_SubscriptionReassignedEventHandler: Symbol.for('Auth_SubscriptionReassignedEventHandler'), + Auth_SubscriptionRenewedEventHandler: Symbol.for('Auth_SubscriptionRenewedEventHandler'), + Auth_SubscriptionRefundedEventHandler: Symbol.for('Auth_SubscriptionRefundedEventHandler'), + Auth_SubscriptionExpiredEventHandler: Symbol.for('Auth_SubscriptionExpiredEventHandler'), + Auth_SubscriptionSyncRequestedEventHandler: Symbol.for('Auth_SubscriptionSyncRequestedEventHandler'), + Auth_ExtensionKeyGrantedEventHandler: Symbol.for('Auth_ExtensionKeyGrantedEventHandler'), + Auth_UserEmailChangedEventHandler: Symbol.for('Auth_UserEmailChangedEventHandler'), + Auth_FileUploadedEventHandler: Symbol.for('Auth_FileUploadedEventHandler'), + Auth_FileRemovedEventHandler: Symbol.for('Auth_FileRemovedEventHandler'), + Auth_ListedAccountCreatedEventHandler: Symbol.for('Auth_ListedAccountCreatedEventHandler'), + Auth_ListedAccountDeletedEventHandler: Symbol.for('Auth_ListedAccountDeletedEventHandler'), + Auth_UserDisabledSessionUserAgentLoggingEventHandler: Symbol.for( + 'Auth_UserDisabledSessionUserAgentLoggingEventHandler', + ), + Auth_SharedSubscriptionInvitationCreatedEventHandler: Symbol.for( + 'Auth_SharedSubscriptionInvitationCreatedEventHandler', + ), + Auth_PredicateVerificationRequestedEventHandler: Symbol.for('Auth_PredicateVerificationRequestedEventHandler'), + Auth_EmailSubscriptionUnsubscribedEventHandler: Symbol.for('Auth_EmailSubscriptionUnsubscribedEventHandler'), // Services - DeviceDetector: Symbol.for('DeviceDetector'), - SessionService: Symbol.for('SessionService'), - SettingService: Symbol.for('SettingService'), - SubscriptionSettingService: Symbol.for('SubscriptionSettingService'), - OfflineSettingService: Symbol.for('OfflineSettingService'), - AuthResponseFactory20161215: Symbol.for('AuthResponseFactory20161215'), - AuthResponseFactory20190520: Symbol.for('AuthResponseFactory20190520'), - AuthResponseFactory20200115: Symbol.for('AuthResponseFactory20200115'), - AuthResponseFactoryResolver: Symbol.for('AuthResponseFactoryResolver'), - KeyParamsFactory: Symbol.for('KeyParamsFactory'), - SessionTokenDecoder: Symbol.for('SessionTokenDecoder'), - FallbackSessionTokenDecoder: Symbol.for('FallbackSessionTokenDecoder'), - CrossServiceTokenDecoder: Symbol.for('CrossServiceTokenDecoder'), - OfflineUserTokenDecoder: Symbol.for('OfflineUserTokenDecoder'), - OfflineUserTokenEncoder: Symbol.for('OfflineUserTokenEncoder'), - CrossServiceTokenEncoder: Symbol.for('CrossServiceTokenEncoder'), - SessionTokenEncoder: Symbol.for('SessionTokenEncoder'), - ValetTokenEncoder: Symbol.for('ValetTokenEncoder'), - WebSocketConnectionTokenDecoder: Symbol.for('WebSocketConnectionTokenDecoder'), - AuthenticationMethodResolver: Symbol.for('AuthenticationMethodResolver'), - DomainEventPublisher: Symbol.for('DomainEventPublisher'), - DomainEventSubscriberFactory: Symbol.for('DomainEventSubscriberFactory'), - DomainEventFactory: Symbol.for('DomainEventFactory'), - DomainEventMessageHandler: Symbol.for('DomainEventMessageHandler'), - HTTPClient: Symbol.for('HTTPClient'), - Crypter: Symbol.for('Crypter'), - CryptoNode: Symbol.for('CryptoNode'), - Timer: Symbol.for('Timer'), - ContenDecoder: Symbol.for('ContenDecoder'), - WebSocketsClientService: Symbol.for('WebSocketClientService'), - RoleService: Symbol.for('RoleService'), - RoleToSubscriptionMap: Symbol.for('RoleToSubscriptionMap'), - SettingsAssociationService: Symbol.for('SettingsAssociationService'), - SubscriptionSettingsAssociationService: Symbol.for('SubscriptionSettingsAssociationService'), - FeatureService: Symbol.for('FeatureService'), - SettingDecrypter: Symbol.for('SettingDecrypter'), - SettingInterpreter: Symbol.for('SettingInterpreter'), - ProtocolVersionSelector: Symbol.for('ProtocolVersionSelector'), - BooleanSelector: Symbol.for('BooleanSelector'), - UserSubscriptionService: Symbol.for('UserSubscriptionService'), + Auth_DeviceDetector: Symbol.for('Auth_DeviceDetector'), + Auth_SessionService: Symbol.for('Auth_SessionService'), + Auth_SettingService: Symbol.for('Auth_SettingService'), + Auth_SubscriptionSettingService: Symbol.for('Auth_SubscriptionSettingService'), + Auth_OfflineSettingService: Symbol.for('Auth_OfflineSettingService'), + Auth_AuthResponseFactory20161215: Symbol.for('Auth_AuthResponseFactory20161215'), + Auth_AuthResponseFactory20190520: Symbol.for('Auth_AuthResponseFactory20190520'), + Auth_AuthResponseFactory20200115: Symbol.for('Auth_AuthResponseFactory20200115'), + Auth_AuthResponseFactoryResolver: Symbol.for('Auth_AuthResponseFactoryResolver'), + Auth_KeyParamsFactory: Symbol.for('Auth_KeyParamsFactory'), + Auth_SessionTokenDecoder: Symbol.for('Auth_SessionTokenDecoder'), + Auth_FallbackSessionTokenDecoder: Symbol.for('Auth_FallbackSessionTokenDecoder'), + Auth_CrossServiceTokenDecoder: Symbol.for('Auth_CrossServiceTokenDecoder'), + Auth_OfflineUserTokenDecoder: Symbol.for('Auth_OfflineUserTokenDecoder'), + Auth_OfflineUserTokenEncoder: Symbol.for('Auth_OfflineUserTokenEncoder'), + Auth_CrossServiceTokenEncoder: Symbol.for('Auth_CrossServiceTokenEncoder'), + Auth_SessionTokenEncoder: Symbol.for('Auth_SessionTokenEncoder'), + Auth_ValetTokenEncoder: Symbol.for('Auth_ValetTokenEncoder'), + Auth_WebSocketConnectionTokenDecoder: Symbol.for('Auth_WebSocketConnectionTokenDecoder'), + Auth_AuthenticationMethodResolver: Symbol.for('Auth_AuthenticationMethodResolver'), + Auth_DomainEventPublisher: Symbol.for('Auth_DomainEventPublisher'), + Auth_DomainEventSubscriberFactory: Symbol.for('Auth_DomainEventSubscriberFactory'), + Auth_DomainEventFactory: Symbol.for('Auth_DomainEventFactory'), + Auth_DomainEventMessageHandler: Symbol.for('Auth_DomainEventMessageHandler'), + Auth_HTTPClient: Symbol.for('Auth_HTTPClient'), + Auth_Crypter: Symbol.for('Auth_Crypter'), + Auth_CryptoNode: Symbol.for('Auth_CryptoNode'), + Auth_Timer: Symbol.for('Auth_Timer'), + Auth_ContenDecoder: Symbol.for('Auth_ContenDecoder'), + Auth_WebSocketsClientService: Symbol.for('Auth_WebSocketClientService'), + Auth_RoleService: Symbol.for('Auth_RoleService'), + Auth_RoleToSubscriptionMap: Symbol.for('Auth_RoleToSubscriptionMap'), + Auth_SettingsAssociationService: Symbol.for('Auth_SettingsAssociationService'), + Auth_SubscriptionSettingsAssociationService: Symbol.for('Auth_SubscriptionSettingsAssociationService'), + Auth_FeatureService: Symbol.for('Auth_FeatureService'), + Auth_SettingDecrypter: Symbol.for('Auth_SettingDecrypter'), + Auth_SettingInterpreter: Symbol.for('Auth_SettingInterpreter'), + Auth_ProtocolVersionSelector: Symbol.for('Auth_ProtocolVersionSelector'), + Auth_BooleanSelector: Symbol.for('Auth_BooleanSelector'), + Auth_UserSubscriptionService: Symbol.for('Auth_UserSubscriptionService'), + Auth_InversifyExpressAuthController: Symbol.for('Auth_InversifyExpressAuthController'), + Auth_InversifyExpressAuthenticatorsController: Symbol.for('Auth_InversifyExpressAuthenticatorsController'), + Auth_InversifyExpressSubscriptionInvitesController: Symbol.for('Auth_InversifyExpressSubscriptionInvitesController'), + Auth_InversifyExpressUserRequestsController: Symbol.for('Auth_InversifyExpressUserRequestsController'), + Auth_InversifyExpressWebSocketsController: Symbol.for('Auth_InversifyExpressWebSocketsController'), } export default TYPES diff --git a/packages/auth/src/Bootstrap/index.ts b/packages/auth/src/Bootstrap/index.ts new file mode 100644 index 000000000..22cddecef --- /dev/null +++ b/packages/auth/src/Bootstrap/index.ts @@ -0,0 +1 @@ +export * from './Service' diff --git a/packages/auth/src/Controller/AdminController.spec.ts b/packages/auth/src/Controller/AdminController.spec.ts index dcfb43e40..8ed41a0c0 100644 --- a/packages/auth/src/Controller/AdminController.spec.ts +++ b/packages/auth/src/Controller/AdminController.spec.ts @@ -8,6 +8,7 @@ import * as express from 'express' import { DeleteSetting } from '../Domain/UseCase/DeleteSetting/DeleteSetting' import { CreateSubscriptionToken } from '../Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken' import { CreateOfflineSubscriptionToken } from '../Domain/UseCase/CreateOfflineSubscriptionToken/CreateOfflineSubscriptionToken' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('AdminController', () => { let deleteSetting: DeleteSetting @@ -16,9 +17,16 @@ describe('AdminController', () => { let createOfflineSubscriptionToken: CreateOfflineSubscriptionToken let request: express.Request let user: User + let controllerContainer: ControllerContainerInterface const createController = () => - new AdminController(deleteSetting, userRepository, createSubscriptionToken, createOfflineSubscriptionToken) + new AdminController( + deleteSetting, + userRepository, + createSubscriptionToken, + createOfflineSubscriptionToken, + controllerContainer, + ) beforeEach(() => { user = {} as jest.Mocked @@ -50,6 +58,9 @@ describe('AdminController', () => { body: {}, params: {}, } as jest.Mocked + + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() }) it('should return error if missing email parameter', async () => { diff --git a/packages/auth/src/Controller/AdminController.ts b/packages/auth/src/Controller/AdminController.ts index 6add2556d..549a97d91 100644 --- a/packages/auth/src/Controller/AdminController.ts +++ b/packages/auth/src/Controller/AdminController.ts @@ -1,4 +1,4 @@ -import { Username } from '@standardnotes/domain-core' +import { ControllerContainerInterface, Username } from '@standardnotes/domain-core' import { SettingName } from '@standardnotes/settings' import { Request } from 'express' import { inject } from 'inversify' @@ -20,13 +20,20 @@ import { UserRepositoryInterface } from '../Domain/User/UserRepositoryInterface' @controller('/admin') export class AdminController extends BaseHttpController { constructor( - @inject(TYPES.DeleteSetting) private doDeleteSetting: DeleteSetting, - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.CreateSubscriptionToken) private createSubscriptionToken: CreateSubscriptionToken, - @inject(TYPES.CreateOfflineSubscriptionToken) + @inject(TYPES.Auth_DeleteSetting) private doDeleteSetting: DeleteSetting, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_CreateSubscriptionToken) private createSubscriptionToken: CreateSubscriptionToken, + @inject(TYPES.Auth_CreateOfflineSubscriptionToken) private createOfflineSubscriptionToken: CreateOfflineSubscriptionToken, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('admin.getUser', this.getUser.bind(this)) + this.controllerContainer.register('admin.deleteMFASetting', this.deleteMFASetting.bind(this)) + this.controllerContainer.register('admin.createToken', this.createToken.bind(this)) + this.controllerContainer.register('admin.createOfflineToken', this.createOfflineToken.bind(this)) + this.controllerContainer.register('admin.disableEmailBackups', this.disableEmailBackups.bind(this)) } @httpGet('/user/:email') diff --git a/packages/auth/src/Controller/ApiGatewayAuthMiddleware.ts b/packages/auth/src/Controller/ApiGatewayAuthMiddleware.ts index 2665df1c3..04f93ea7c 100644 --- a/packages/auth/src/Controller/ApiGatewayAuthMiddleware.ts +++ b/packages/auth/src/Controller/ApiGatewayAuthMiddleware.ts @@ -8,8 +8,8 @@ import TYPES from '../Bootstrap/Types' @injectable() export class ApiGatewayAuthMiddleware extends BaseMiddleware { constructor( - @inject(TYPES.CrossServiceTokenDecoder) private tokenDecoder: TokenDecoderInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_CrossServiceTokenDecoder) private tokenDecoder: TokenDecoderInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) { super() } diff --git a/packages/auth/src/Controller/ApiGatewayOfflineAuthMiddleware.ts b/packages/auth/src/Controller/ApiGatewayOfflineAuthMiddleware.ts index 44c2543d0..bb33675af 100644 --- a/packages/auth/src/Controller/ApiGatewayOfflineAuthMiddleware.ts +++ b/packages/auth/src/Controller/ApiGatewayOfflineAuthMiddleware.ts @@ -8,8 +8,8 @@ import TYPES from '../Bootstrap/Types' @injectable() export class ApiGatewayOfflineAuthMiddleware extends BaseMiddleware { constructor( - @inject(TYPES.OfflineUserTokenDecoder) private tokenDecoder: TokenDecoderInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_OfflineUserTokenDecoder) private tokenDecoder: TokenDecoderInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) { super() } diff --git a/packages/auth/src/Controller/AuthController.spec.ts b/packages/auth/src/Controller/AuthController.spec.ts index 414d9a695..a790afbc6 100644 --- a/packages/auth/src/Controller/AuthController.spec.ts +++ b/packages/auth/src/Controller/AuthController.spec.ts @@ -13,6 +13,7 @@ import { SignInWithRecoveryCodes } from '../Domain/UseCase/SignInWithRecoveryCod import { GetUserKeyParamsRecovery } from '../Domain/UseCase/GetUserKeyParamsRecovery/GetUserKeyParamsRecovery' import { GenerateRecoveryCodes } from '../Domain/UseCase/GenerateRecoveryCodes/GenerateRecoveryCodes' import { Logger } from 'winston' +import { SessionServiceInterface } from '../Domain/Session/SessionServiceInterface' describe('AuthController', () => { let clearLoginAttempts: ClearLoginAttempts @@ -25,6 +26,7 @@ describe('AuthController', () => { let getUserKeyParamsRecovery: GetUserKeyParamsRecovery let doGenerateRecoveryCodes: GenerateRecoveryCodes let logger: Logger + let sessionService: SessionServiceInterface const createController = () => new AuthController( @@ -36,6 +38,7 @@ describe('AuthController', () => { getUserKeyParamsRecovery, doGenerateRecoveryCodes, logger, + sessionService, ) beforeEach(() => { @@ -58,6 +61,9 @@ describe('AuthController', () => { logger = {} as jest.Mocked logger.debug = jest.fn() + + sessionService = {} as jest.Mocked + sessionService.deleteSessionByToken = jest.fn().mockReturnValue('1-2-3') }) it('should register a user', async () => { diff --git a/packages/auth/src/Controller/AuthController.ts b/packages/auth/src/Controller/AuthController.ts index 800621d0b..17ecb6c8b 100644 --- a/packages/auth/src/Controller/AuthController.ts +++ b/packages/auth/src/Controller/AuthController.ts @@ -1,4 +1,3 @@ -import { inject, injectable } from 'inversify' import { DomainEventPublisherInterface } from '@standardnotes/domain-events' import { ApiVersion, @@ -7,10 +6,9 @@ import { UserDeletionResponseBody, UserRegistrationResponseBody, } from '@standardnotes/api' -import { HttpResponse, HttpStatusCode } from '@standardnotes/responses' +import { ErrorTag, HttpResponse, HttpStatusCode } from '@standardnotes/responses' import { ProtocolVersion } from '@standardnotes/common' -import TYPES from '../Bootstrap/Types' import { ClearLoginAttempts } from '../Domain/UseCase/ClearLoginAttempts' import { Register } from '../Domain/UseCase/Register' import { DomainEventFactoryInterface } from '../Domain/Event/DomainEventFactoryInterface' @@ -24,18 +22,19 @@ import { GenerateRecoveryCodesResponseBody } from '../Infra/Http/Response/Genera import { GenerateRecoveryCodes } from '../Domain/UseCase/GenerateRecoveryCodes/GenerateRecoveryCodes' import { GenerateRecoveryCodesRequestParams } from '../Infra/Http/Request/GenerateRecoveryCodesRequestParams' import { Logger } from 'winston' +import { SessionServiceInterface } from '../Domain/Session/SessionServiceInterface' -@injectable() export class AuthController implements UserServerInterface { constructor( - @inject(TYPES.ClearLoginAttempts) private clearLoginAttempts: ClearLoginAttempts, - @inject(TYPES.Register) private registerUser: Register, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.SignInWithRecoveryCodes) private doSignInWithRecoveryCodes: SignInWithRecoveryCodes, - @inject(TYPES.GetUserKeyParamsRecovery) private getUserKeyParamsRecovery: GetUserKeyParamsRecovery, - @inject(TYPES.GenerateRecoveryCodes) private doGenerateRecoveryCodes: GenerateRecoveryCodes, - @inject(TYPES.Logger) private logger: Logger, + private clearLoginAttempts: ClearLoginAttempts, + private registerUser: Register, + private domainEventPublisher: DomainEventPublisherInterface, + private domainEventFactory: DomainEventFactoryInterface, + private doSignInWithRecoveryCodes: SignInWithRecoveryCodes, + private getUserKeyParamsRecovery: GetUserKeyParamsRecovery, + private doGenerateRecoveryCodes: GenerateRecoveryCodes, + private logger: Logger, + private sessionService: SessionServiceInterface, ) {} async deleteAccount(_params: never): Promise> { @@ -200,4 +199,33 @@ export class AuthController implements UserServerInterface { }, } } + + async signOut(params: Record): Promise { + if (params.readOnlyAccess) { + return { + status: HttpStatusCode.Unauthorized, + data: { + error: { + tag: ErrorTag.ReadOnlyAccess, + message: 'Session has read-only access.', + }, + }, + } + } + + const userUuid = await this.sessionService.deleteSessionByToken( + (params.authorizationHeader as string).replace('Bearer ', ''), + ) + + let headers = undefined + if (userUuid !== null) { + headers = new Map([['x-invalidate-cache', userUuid]]) + } + + return { + status: HttpStatusCode.NoContent, + data: {}, + headers, + } + } } diff --git a/packages/auth/src/Controller/AuthMiddleware.ts b/packages/auth/src/Controller/AuthMiddleware.ts index c8a78eeb1..e30cef017 100644 --- a/packages/auth/src/Controller/AuthMiddleware.ts +++ b/packages/auth/src/Controller/AuthMiddleware.ts @@ -8,8 +8,8 @@ import { AuthenticateRequest } from '../Domain/UseCase/AuthenticateRequest' @injectable() export class AuthMiddleware extends BaseMiddleware { constructor( - @inject(TYPES.AuthenticateRequest) private authenticateRequest: AuthenticateRequest, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_AuthenticateRequest) private authenticateRequest: AuthenticateRequest, + @inject(TYPES.Auth_Logger) private logger: Logger, ) { super() } diff --git a/packages/auth/src/Controller/AuthMiddlewareWithoutResponse.ts b/packages/auth/src/Controller/AuthMiddlewareWithoutResponse.ts index 4204770f2..443435ab0 100644 --- a/packages/auth/src/Controller/AuthMiddlewareWithoutResponse.ts +++ b/packages/auth/src/Controller/AuthMiddlewareWithoutResponse.ts @@ -6,7 +6,7 @@ import { AuthenticateRequest } from '../Domain/UseCase/AuthenticateRequest' @injectable() export class AuthMiddlewareWithoutResponse extends BaseMiddleware { - constructor(@inject(TYPES.AuthenticateRequest) private authenticateRequest: AuthenticateRequest) { + constructor(@inject(TYPES.Auth_AuthenticateRequest) private authenticateRequest: AuthenticateRequest) { super() } diff --git a/packages/auth/src/Controller/FeaturesController.spec.ts b/packages/auth/src/Controller/FeaturesController.spec.ts index 7595c0c7b..199d22214 100644 --- a/packages/auth/src/Controller/FeaturesController.spec.ts +++ b/packages/auth/src/Controller/FeaturesController.spec.ts @@ -6,6 +6,7 @@ import { FeaturesController } from './FeaturesController' import { results } from 'inversify-express-utils' import { User } from '../Domain/User/User' import { GetUserFeatures } from '../Domain/UseCase/GetUserFeatures/GetUserFeatures' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('FeaturesController', () => { let getUserFeatures: GetUserFeatures @@ -13,10 +14,14 @@ describe('FeaturesController', () => { let request: express.Request let response: express.Response let user: User + let controllerContainer: ControllerContainerInterface - const createController = () => new FeaturesController(getUserFeatures) + const createController = () => new FeaturesController(getUserFeatures, controllerContainer) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + user = {} as jest.Mocked user.uuid = '123' diff --git a/packages/auth/src/Controller/FeaturesController.ts b/packages/auth/src/Controller/FeaturesController.ts index 274311846..46ff3ad50 100644 --- a/packages/auth/src/Controller/FeaturesController.ts +++ b/packages/auth/src/Controller/FeaturesController.ts @@ -9,14 +9,20 @@ import { } from 'inversify-express-utils' import TYPES from '../Bootstrap/Types' import { GetUserFeatures } from '../Domain/UseCase/GetUserFeatures/GetUserFeatures' +import { ControllerContainerInterface } from '@standardnotes/domain-core' @controller('/users/:userUuid/features') export class FeaturesController extends BaseHttpController { - constructor(@inject(TYPES.GetUserFeatures) private doGetUserFeatures: GetUserFeatures) { + constructor( + @inject(TYPES.Auth_GetUserFeatures) private doGetUserFeatures: GetUserFeatures, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, + ) { super() + + this.controllerContainer.register('auth.users.getFeatures', this.getFeatures.bind(this)) } - @httpGet('/', TYPES.ApiGatewayAuthMiddleware) + @httpGet('/', TYPES.Auth_ApiGatewayAuthMiddleware) async getFeatures(request: Request, response: Response): Promise { if (request.params.userUuid !== response.locals.user.uuid) { return this.json( diff --git a/packages/auth/src/Controller/InternalController.ts b/packages/auth/src/Controller/InternalController.ts index bd49102c3..46cd38e3a 100644 --- a/packages/auth/src/Controller/InternalController.ts +++ b/packages/auth/src/Controller/InternalController.ts @@ -14,8 +14,8 @@ import { GetUserFeatures } from '../Domain/UseCase/GetUserFeatures/GetUserFeatur @controller('/internal') export class InternalController extends BaseHttpController { constructor( - @inject(TYPES.GetUserFeatures) private doGetUserFeatures: GetUserFeatures, - @inject(TYPES.GetSetting) private doGetSetting: GetSetting, + @inject(TYPES.Auth_GetUserFeatures) private doGetUserFeatures: GetUserFeatures, + @inject(TYPES.Auth_GetSetting) private doGetSetting: GetSetting, ) { super() } diff --git a/packages/auth/src/Controller/ListedController.spec.ts b/packages/auth/src/Controller/ListedController.spec.ts index 6ecff0eb4..048b598d1 100644 --- a/packages/auth/src/Controller/ListedController.spec.ts +++ b/packages/auth/src/Controller/ListedController.spec.ts @@ -6,6 +6,7 @@ import { results } from 'inversify-express-utils' import { ListedController } from './ListedController' import { User } from '../Domain/User/User' import { CreateListedAccount } from '../Domain/UseCase/CreateListedAccount/CreateListedAccount' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('ListedController', () => { let createListedAccount: CreateListedAccount @@ -13,10 +14,14 @@ describe('ListedController', () => { let request: express.Request let response: express.Response let user: User + let controllerContainer: ControllerContainerInterface - const createController = () => new ListedController(createListedAccount) + const createController = () => new ListedController(createListedAccount, controllerContainer) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + user = {} as jest.Mocked user.uuid = '123' diff --git a/packages/auth/src/Controller/ListedController.ts b/packages/auth/src/Controller/ListedController.ts index e724ad69e..65b25e614 100644 --- a/packages/auth/src/Controller/ListedController.ts +++ b/packages/auth/src/Controller/ListedController.ts @@ -5,14 +5,20 @@ import { Request, Response } from 'express' import TYPES from '../Bootstrap/Types' import { CreateListedAccount } from '../Domain/UseCase/CreateListedAccount/CreateListedAccount' import { ErrorTag } from '@standardnotes/responses' +import { ControllerContainerInterface } from '@standardnotes/domain-core' @controller('/listed') export class ListedController extends BaseHttpController { - constructor(@inject(TYPES.CreateListedAccount) private doCreateListedAccount: CreateListedAccount) { + constructor( + @inject(TYPES.Auth_CreateListedAccount) private doCreateListedAccount: CreateListedAccount, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, + ) { super() + + this.controllerContainer.register('auth.users.createListedAccount', this.createListedAccount.bind(this)) } - @httpPost('/', TYPES.ApiGatewayAuthMiddleware) + @httpPost('/', TYPES.Auth_ApiGatewayAuthMiddleware) async createListedAccount(_request: Request, response: Response): Promise { if (response.locals.readOnlyAccess) { return this.json( diff --git a/packages/auth/src/Controller/LockMiddleware.ts b/packages/auth/src/Controller/LockMiddleware.ts index 34f3b9f55..72f5fb00d 100644 --- a/packages/auth/src/Controller/LockMiddleware.ts +++ b/packages/auth/src/Controller/LockMiddleware.ts @@ -10,8 +10,8 @@ import { UserRepositoryInterface } from '../Domain/User/UserRepositoryInterface' @injectable() export class LockMiddleware extends BaseMiddleware { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.LockRepository) private lockRepository: LockRepositoryInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_LockRepository) private lockRepository: LockRepositoryInterface, ) { super() } diff --git a/packages/auth/src/Controller/OfflineController.spec.ts b/packages/auth/src/Controller/OfflineController.spec.ts index 9c6266083..831c29104 100644 --- a/packages/auth/src/Controller/OfflineController.spec.ts +++ b/packages/auth/src/Controller/OfflineController.spec.ts @@ -14,6 +14,7 @@ import { GetUserOfflineSubscription } from '../Domain/UseCase/GetUserOfflineSubs import { OfflineUserTokenData, TokenEncoderInterface } from '@standardnotes/security' import { SubscriptionName } from '@standardnotes/common' import { Logger } from 'winston' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('OfflineController', () => { let getUserFeatures: GetUserFeatures @@ -28,6 +29,8 @@ describe('OfflineController', () => { let response: express.Response let user: User + let controllerContainer: ControllerContainerInterface + const createController = () => new OfflineController( getUserFeatures, @@ -37,9 +40,13 @@ describe('OfflineController', () => { tokenEncoder, jwtTTL, logger, + controllerContainer, ) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + user = {} as jest.Mocked user.uuid = '123' diff --git a/packages/auth/src/Controller/OfflineController.ts b/packages/auth/src/Controller/OfflineController.ts index 42f264f8c..c42561310 100644 --- a/packages/auth/src/Controller/OfflineController.ts +++ b/packages/auth/src/Controller/OfflineController.ts @@ -15,23 +15,30 @@ import { CreateOfflineSubscriptionToken } from '../Domain/UseCase/CreateOfflineS import { GetUserOfflineSubscription } from '../Domain/UseCase/GetUserOfflineSubscription/GetUserOfflineSubscription' import { Logger } from 'winston' import { OfflineUserTokenData, TokenEncoderInterface } from '@standardnotes/security' +import { ControllerContainerInterface } from '@standardnotes/domain-core' @controller('/offline') export class OfflineController extends BaseHttpController { constructor( - @inject(TYPES.GetUserFeatures) private doGetUserFeatures: GetUserFeatures, - @inject(TYPES.GetUserOfflineSubscription) private getUserOfflineSubscription: GetUserOfflineSubscription, - @inject(TYPES.CreateOfflineSubscriptionToken) + @inject(TYPES.Auth_GetUserFeatures) private doGetUserFeatures: GetUserFeatures, + @inject(TYPES.Auth_GetUserOfflineSubscription) private getUserOfflineSubscription: GetUserOfflineSubscription, + @inject(TYPES.Auth_CreateOfflineSubscriptionToken) private createOfflineSubscriptionToken: CreateOfflineSubscriptionToken, - @inject(TYPES.AuthenticateOfflineSubscriptionToken) private authenticateToken: AuthenticateOfflineSubscriptionToken, - @inject(TYPES.OfflineUserTokenEncoder) private tokenEncoder: TokenEncoderInterface, - @inject(TYPES.AUTH_JWT_TTL) private jwtTTL: number, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_AuthenticateOfflineSubscriptionToken) + private authenticateToken: AuthenticateOfflineSubscriptionToken, + @inject(TYPES.Auth_OfflineUserTokenEncoder) private tokenEncoder: TokenEncoderInterface, + @inject(TYPES.Auth_AUTH_JWT_TTL) private jwtTTL: number, + @inject(TYPES.Auth_Logger) private logger: Logger, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('auth.offline.features', this.getOfflineFeatures.bind(this)) + this.controllerContainer.register('auth.offline.subscriptionTokens.create', this.createToken.bind(this)) + this.controllerContainer.register('auth.users.getOfflineSubscriptionByToken', this.getSubscription.bind(this)) } - @httpGet('/features', TYPES.OfflineUserAuthMiddleware) + @httpGet('/features', TYPES.Auth_OfflineUserAuthMiddleware) async getOfflineFeatures(_request: Request, response: Response): Promise { const result = await this.doGetUserFeatures.execute({ email: response.locals.offlineUserEmail, @@ -119,7 +126,7 @@ export class OfflineController extends BaseHttpController { return this.json({ authToken }) } - @httpGet('/users/subscription', TYPES.ApiGatewayOfflineAuthMiddleware) + @httpGet('/users/subscription', TYPES.Auth_ApiGatewayOfflineAuthMiddleware) async getSubscription(_request: Request, response: Response): Promise { const result = await this.getUserOfflineSubscription.execute({ userEmail: response.locals.userEmail, diff --git a/packages/auth/src/Controller/OfflineUserAuthMiddleware.ts b/packages/auth/src/Controller/OfflineUserAuthMiddleware.ts index adec3ee9f..efc4273cf 100644 --- a/packages/auth/src/Controller/OfflineUserAuthMiddleware.ts +++ b/packages/auth/src/Controller/OfflineUserAuthMiddleware.ts @@ -9,8 +9,8 @@ import { OfflineSettingRepositoryInterface } from '../Domain/Setting/OfflineSett @injectable() export class OfflineUserAuthMiddleware extends BaseMiddleware { constructor( - @inject(TYPES.OfflineSettingRepository) private offlineSettingRepository: OfflineSettingRepositoryInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_OfflineSettingRepository) private offlineSettingRepository: OfflineSettingRepositoryInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) { super() } diff --git a/packages/auth/src/Controller/SessionController.spec.ts b/packages/auth/src/Controller/SessionController.spec.ts index f926fbc2b..55329f796 100644 --- a/packages/auth/src/Controller/SessionController.spec.ts +++ b/packages/auth/src/Controller/SessionController.spec.ts @@ -7,6 +7,7 @@ import { results } from 'inversify-express-utils' import { RefreshSessionToken } from '../Domain/UseCase/RefreshSessionToken' import { DeletePreviousSessionsForUser } from '../Domain/UseCase/DeletePreviousSessionsForUser' import { DeleteSessionForUser } from '../Domain/UseCase/DeleteSessionForUser' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('SessionController', () => { let deleteSessionForUser: DeleteSessionForUser @@ -14,11 +15,15 @@ describe('SessionController', () => { let refreshSessionToken: RefreshSessionToken let request: express.Request let response: express.Response + let controllerContainer: ControllerContainerInterface const createController = () => - new SessionController(deleteSessionForUser, deletePreviousSessionsForUser, refreshSessionToken) + new SessionController(deleteSessionForUser, deletePreviousSessionsForUser, refreshSessionToken, controllerContainer) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + deleteSessionForUser = {} as jest.Mocked deleteSessionForUser.execute = jest.fn().mockReturnValue({ success: true }) diff --git a/packages/auth/src/Controller/SessionController.ts b/packages/auth/src/Controller/SessionController.ts index e09a5d74d..46f01b17a 100644 --- a/packages/auth/src/Controller/SessionController.ts +++ b/packages/auth/src/Controller/SessionController.ts @@ -13,18 +13,25 @@ import TYPES from '../Bootstrap/Types' import { DeletePreviousSessionsForUser } from '../Domain/UseCase/DeletePreviousSessionsForUser' import { DeleteSessionForUser } from '../Domain/UseCase/DeleteSessionForUser' import { RefreshSessionToken } from '../Domain/UseCase/RefreshSessionToken' +import { ControllerContainerInterface } from '@standardnotes/domain-core' @controller('/session') export class SessionController extends BaseHttpController { constructor( - @inject(TYPES.DeleteSessionForUser) private deleteSessionForUser: DeleteSessionForUser, - @inject(TYPES.DeletePreviousSessionsForUser) private deletePreviousSessionsForUser: DeletePreviousSessionsForUser, - @inject(TYPES.RefreshSessionToken) private refreshSessionToken: RefreshSessionToken, + @inject(TYPES.Auth_DeleteSessionForUser) private deleteSessionForUser: DeleteSessionForUser, + @inject(TYPES.Auth_DeletePreviousSessionsForUser) + private deletePreviousSessionsForUser: DeletePreviousSessionsForUser, + @inject(TYPES.Auth_RefreshSessionToken) private refreshSessionToken: RefreshSessionToken, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('auth.session.delete', this.deleteSession.bind(this)) + this.controllerContainer.register('auth.session.deleteAll', this.deleteAllSessions.bind(this)) + this.controllerContainer.register('auth.session.refresh', this.refresh.bind(this)) } - @httpDelete('/', TYPES.AuthMiddleware, TYPES.SessionMiddleware) + @httpDelete('/', TYPES.Auth_AuthMiddleware, TYPES.Auth_SessionMiddleware) async deleteSession(request: Request, response: Response): Promise { if (response.locals.readOnlyAccess) { return this.json( @@ -80,7 +87,7 @@ export class SessionController extends BaseHttpController { response.status(204).send() } - @httpDelete('/all', TYPES.AuthMiddleware, TYPES.SessionMiddleware) + @httpDelete('/all', TYPES.Auth_AuthMiddleware, TYPES.Auth_SessionMiddleware) async deleteAllSessions(_request: Request, response: Response): Promise { if (response.locals.readOnlyAccess) { return this.json( diff --git a/packages/auth/src/Controller/SessionsController.spec.ts b/packages/auth/src/Controller/SessionsController.spec.ts index d15576f27..e2492e897 100644 --- a/packages/auth/src/Controller/SessionsController.spec.ts +++ b/packages/auth/src/Controller/SessionsController.spec.ts @@ -10,6 +10,7 @@ import { GetActiveSessionsForUser } from '../Domain/UseCase/GetActiveSessionsFor import { AuthenticateRequest } from '../Domain/UseCase/AuthenticateRequest' import { User } from '../Domain/User/User' import { CreateCrossServiceToken } from '../Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('SessionsController', () => { let getActiveSessionsForUser: GetActiveSessionsForUser @@ -20,11 +21,21 @@ describe('SessionsController', () => { let response: express.Response let user: User let createCrossServiceToken: CreateCrossServiceToken + let controllerContainer: ControllerContainerInterface const createController = () => - new SessionsController(getActiveSessionsForUser, authenticateRequest, sessionProjector, createCrossServiceToken) + new SessionsController( + getActiveSessionsForUser, + authenticateRequest, + sessionProjector, + createCrossServiceToken, + controllerContainer, + ) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + session = {} as jest.Mocked user = {} as jest.Mocked diff --git a/packages/auth/src/Controller/SessionsController.ts b/packages/auth/src/Controller/SessionsController.ts index bebeab699..ba68a686b 100644 --- a/packages/auth/src/Controller/SessionsController.ts +++ b/packages/auth/src/Controller/SessionsController.ts @@ -16,16 +16,20 @@ import { User } from '../Domain/User/User' import { ProjectorInterface } from '../Projection/ProjectorInterface' import { SessionProjector } from '../Projection/SessionProjector' import { CreateCrossServiceToken } from '../Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken' +import { ControllerContainerInterface } from '@standardnotes/domain-core' @controller('/sessions') export class SessionsController extends BaseHttpController { constructor( - @inject(TYPES.GetActiveSessionsForUser) private getActiveSessionsForUser: GetActiveSessionsForUser, - @inject(TYPES.AuthenticateRequest) private authenticateRequest: AuthenticateRequest, - @inject(TYPES.SessionProjector) private sessionProjector: ProjectorInterface, - @inject(TYPES.CreateCrossServiceToken) private createCrossServiceToken: CreateCrossServiceToken, + @inject(TYPES.Auth_GetActiveSessionsForUser) private getActiveSessionsForUser: GetActiveSessionsForUser, + @inject(TYPES.Auth_AuthenticateRequest) private authenticateRequest: AuthenticateRequest, + @inject(TYPES.Auth_SessionProjector) private sessionProjector: ProjectorInterface, + @inject(TYPES.Auth_CreateCrossServiceToken) private createCrossServiceToken: CreateCrossServiceToken, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('auth.sessions.list', this.getSessions.bind(this)) } @httpPost('/validate') @@ -56,7 +60,7 @@ export class SessionsController extends BaseHttpController { return this.json({ authToken: result.token }) } - @httpGet('/', TYPES.AuthMiddleware, TYPES.SessionMiddleware) + @httpGet('/', TYPES.Auth_AuthMiddleware, TYPES.Auth_SessionMiddleware) async getSessions(_request: Request, response: Response): Promise { if (response.locals.readOnlyAccess) { return this.json([]) diff --git a/packages/auth/src/Controller/SettingsController.spec.ts b/packages/auth/src/Controller/SettingsController.spec.ts index 70f48b0b3..154634ce6 100644 --- a/packages/auth/src/Controller/SettingsController.spec.ts +++ b/packages/auth/src/Controller/SettingsController.spec.ts @@ -10,6 +10,7 @@ import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting' import { UpdateSetting } from '../Domain/UseCase/UpdateSetting/UpdateSetting' import { DeleteSetting } from '../Domain/UseCase/DeleteSetting/DeleteSetting' import { EncryptionVersion } from '../Domain/Encryption/EncryptionVersion' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('SettingsController', () => { let deleteSetting: DeleteSetting @@ -20,10 +21,15 @@ describe('SettingsController', () => { let request: express.Request let response: express.Response let user: User + let controllerContainer: ControllerContainerInterface - const createController = () => new SettingsController(getSettings, getSetting, updateSetting, deleteSetting) + const createController = () => + new SettingsController(getSettings, getSetting, updateSetting, deleteSetting, controllerContainer) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + deleteSetting = {} as jest.Mocked deleteSetting.execute = jest.fn().mockReturnValue({ success: true }) diff --git a/packages/auth/src/Controller/SettingsController.ts b/packages/auth/src/Controller/SettingsController.ts index c94a17bb1..09ec96eb2 100644 --- a/packages/auth/src/Controller/SettingsController.ts +++ b/packages/auth/src/Controller/SettingsController.ts @@ -16,19 +16,26 @@ import { DeleteSetting } from '../Domain/UseCase/DeleteSetting/DeleteSetting' import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting' import { GetSettings } from '../Domain/UseCase/GetSettings/GetSettings' import { UpdateSetting } from '../Domain/UseCase/UpdateSetting/UpdateSetting' +import { ControllerContainerInterface } from '@standardnotes/domain-core' @controller('/users/:userUuid') export class SettingsController extends BaseHttpController { constructor( - @inject(TYPES.GetSettings) private doGetSettings: GetSettings, - @inject(TYPES.GetSetting) private doGetSetting: GetSetting, - @inject(TYPES.UpdateSetting) private doUpdateSetting: UpdateSetting, - @inject(TYPES.DeleteSetting) private doDeleteSetting: DeleteSetting, + @inject(TYPES.Auth_GetSettings) private doGetSettings: GetSettings, + @inject(TYPES.Auth_GetSetting) private doGetSetting: GetSetting, + @inject(TYPES.Auth_UpdateSetting) private doUpdateSetting: UpdateSetting, + @inject(TYPES.Auth_DeleteSetting) private doDeleteSetting: DeleteSetting, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('auth.users.getSettings', this.getSettings.bind(this)) + this.controllerContainer.register('auth.users.getSetting', this.getSetting.bind(this)) + this.controllerContainer.register('auth.users.updateSetting', this.updateSetting.bind(this)) + this.controllerContainer.register('auth.users.deleteSetting', this.deleteSetting.bind(this)) } - @httpGet('/settings', TYPES.ApiGatewayAuthMiddleware) + @httpGet('/settings', TYPES.Auth_ApiGatewayAuthMiddleware) async getSettings(request: Request, response: Response): Promise { if (request.params.userUuid !== response.locals.user.uuid) { return this.json( @@ -47,7 +54,7 @@ export class SettingsController extends BaseHttpController { return this.json(result) } - @httpGet('/settings/:settingName', TYPES.ApiGatewayAuthMiddleware) + @httpGet('/settings/:settingName', TYPES.Auth_ApiGatewayAuthMiddleware) async getSetting(request: Request, response: Response): Promise { if (request.params.userUuid !== response.locals.user.uuid) { return this.json( @@ -70,7 +77,7 @@ export class SettingsController extends BaseHttpController { return this.json(result, 400) } - @httpPut('/settings', TYPES.ApiGatewayAuthMiddleware) + @httpPut('/settings', TYPES.Auth_ApiGatewayAuthMiddleware) async updateSetting(request: Request, response: Response): Promise { if (response.locals.readOnlyAccess) { return this.json( @@ -117,7 +124,7 @@ export class SettingsController extends BaseHttpController { return this.json(result, result.statusCode) } - @httpDelete('/settings/:settingName', TYPES.ApiGatewayAuthMiddleware) + @httpDelete('/settings/:settingName', TYPES.Auth_ApiGatewayAuthMiddleware) async deleteSetting(request: Request, response: Response): Promise { if (response.locals.readOnlyAccess) { return this.json( diff --git a/packages/auth/src/Controller/SubscriptionInvitesController.ts b/packages/auth/src/Controller/SubscriptionInvitesController.ts index 05c562208..825059231 100644 --- a/packages/auth/src/Controller/SubscriptionInvitesController.ts +++ b/packages/auth/src/Controller/SubscriptionInvitesController.ts @@ -26,14 +26,14 @@ import { ListSharedSubscriptionInvitations } from '../Domain/UseCase/ListSharedS @injectable() export class SubscriptionInvitesController implements SubscriptionServerInterface { constructor( - @inject(TYPES.InviteToSharedSubscription) private inviteToSharedSubscription: InviteToSharedSubscription, - @inject(TYPES.AcceptSharedSubscriptionInvitation) + @inject(TYPES.Auth_InviteToSharedSubscription) private inviteToSharedSubscription: InviteToSharedSubscription, + @inject(TYPES.Auth_AcceptSharedSubscriptionInvitation) private acceptSharedSubscriptionInvitation: AcceptSharedSubscriptionInvitation, - @inject(TYPES.DeclineSharedSubscriptionInvitation) + @inject(TYPES.Auth_DeclineSharedSubscriptionInvitation) private declineSharedSubscriptionInvitation: DeclineSharedSubscriptionInvitation, - @inject(TYPES.CancelSharedSubscriptionInvitation) + @inject(TYPES.Auth_CancelSharedSubscriptionInvitation) private cancelSharedSubscriptionInvitation: CancelSharedSubscriptionInvitation, - @inject(TYPES.ListSharedSubscriptionInvitations) + @inject(TYPES.Auth_ListSharedSubscriptionInvitations) private listSharedSubscriptionInvitations: ListSharedSubscriptionInvitations, ) {} diff --git a/packages/auth/src/Controller/SubscriptionSettingsController.spec.ts b/packages/auth/src/Controller/SubscriptionSettingsController.spec.ts index ba8e5e1cb..d659ef524 100644 --- a/packages/auth/src/Controller/SubscriptionSettingsController.spec.ts +++ b/packages/auth/src/Controller/SubscriptionSettingsController.spec.ts @@ -6,6 +6,7 @@ import { results } from 'inversify-express-utils' import { User } from '../Domain/User/User' import { SubscriptionSettingsController } from './SubscriptionSettingsController' import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('SubscriptionSettingsController', () => { let getSetting: GetSetting @@ -13,10 +14,14 @@ describe('SubscriptionSettingsController', () => { let request: express.Request let response: express.Response let user: User + let controllerContainer: ControllerContainerInterface - const createController = () => new SubscriptionSettingsController(getSetting) + const createController = () => new SubscriptionSettingsController(getSetting, controllerContainer) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + user = {} as jest.Mocked user.uuid = '123' diff --git a/packages/auth/src/Controller/SubscriptionSettingsController.ts b/packages/auth/src/Controller/SubscriptionSettingsController.ts index 0835a795f..bce5f93ad 100644 --- a/packages/auth/src/Controller/SubscriptionSettingsController.ts +++ b/packages/auth/src/Controller/SubscriptionSettingsController.ts @@ -9,14 +9,20 @@ import { } from 'inversify-express-utils' import TYPES from '../Bootstrap/Types' import { GetSetting } from '../Domain/UseCase/GetSetting/GetSetting' +import { ControllerContainerInterface } from '@standardnotes/domain-core' @controller('/users/:userUuid') export class SubscriptionSettingsController extends BaseHttpController { - constructor(@inject(TYPES.GetSetting) private doGetSetting: GetSetting) { + constructor( + @inject(TYPES.Auth_GetSetting) private doGetSetting: GetSetting, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, + ) { super() + + this.controllerContainer.register('auth.users.getSubscriptionSetting', this.getSubscriptionSetting.bind(this)) } - @httpGet('/subscription-settings/:subscriptionSettingName', TYPES.ApiGatewayAuthMiddleware) + @httpGet('/subscription-settings/:subscriptionSettingName', TYPES.Auth_ApiGatewayAuthMiddleware) async getSubscriptionSetting(request: Request, response: Response): Promise { const result = await this.doGetSetting.execute({ userUuid: response.locals.user.uuid, diff --git a/packages/auth/src/Controller/SubscriptionTokensController.spec.ts b/packages/auth/src/Controller/SubscriptionTokensController.spec.ts index 2c54c00ce..c4f56c6bf 100644 --- a/packages/auth/src/Controller/SubscriptionTokensController.spec.ts +++ b/packages/auth/src/Controller/SubscriptionTokensController.spec.ts @@ -13,6 +13,7 @@ import { Role } from '../Domain/Role/Role' import { SettingServiceInterface } from '../Domain/Setting/SettingServiceInterface' import { Setting } from '../Domain/Setting/Setting' import { CrossServiceTokenData, TokenEncoderInterface } from '@standardnotes/security' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('SubscriptionTokensController', () => { let createSubscriptionToken: CreateSubscriptionToken @@ -29,6 +30,8 @@ describe('SubscriptionTokensController', () => { let user: User let role: Role + let controllerContainer: ControllerContainerInterface + const createController = () => new SubscriptionTokensController( createSubscriptionToken, @@ -38,9 +41,13 @@ describe('SubscriptionTokensController', () => { roleProjector, tokenEncoder, jwtTTL, + controllerContainer, ) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + user = {} as jest.Mocked user.uuid = '123' user.roles = Promise.resolve([role]) diff --git a/packages/auth/src/Controller/SubscriptionTokensController.ts b/packages/auth/src/Controller/SubscriptionTokensController.ts index 713841709..f4929894f 100644 --- a/packages/auth/src/Controller/SubscriptionTokensController.ts +++ b/packages/auth/src/Controller/SubscriptionTokensController.ts @@ -18,22 +18,26 @@ import { AuthenticateSubscriptionToken } from '../Domain/UseCase/AuthenticateSub import { CreateSubscriptionToken } from '../Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken' import { User } from '../Domain/User/User' import { ProjectorInterface } from '../Projection/ProjectorInterface' +import { ControllerContainerInterface } from '@standardnotes/domain-core' @controller('/subscription-tokens') export class SubscriptionTokensController extends BaseHttpController { constructor( - @inject(TYPES.CreateSubscriptionToken) private createSubscriptionToken: CreateSubscriptionToken, - @inject(TYPES.AuthenticateSubscriptionToken) private authenticateToken: AuthenticateSubscriptionToken, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.UserProjector) private userProjector: ProjectorInterface, - @inject(TYPES.RoleProjector) private roleProjector: ProjectorInterface, - @inject(TYPES.CrossServiceTokenEncoder) private tokenEncoder: TokenEncoderInterface, - @inject(TYPES.AUTH_JWT_TTL) private jwtTTL: number, + @inject(TYPES.Auth_CreateSubscriptionToken) private createSubscriptionToken: CreateSubscriptionToken, + @inject(TYPES.Auth_AuthenticateSubscriptionToken) private authenticateToken: AuthenticateSubscriptionToken, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_UserProjector) private userProjector: ProjectorInterface, + @inject(TYPES.Auth_RoleProjector) private roleProjector: ProjectorInterface, + @inject(TYPES.Auth_CrossServiceTokenEncoder) private tokenEncoder: TokenEncoderInterface, + @inject(TYPES.Auth_AUTH_JWT_TTL) private jwtTTL: number, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('auth.subscription-tokens.create', this.createToken.bind(this)) } - @httpPost('/', TYPES.ApiGatewayAuthMiddleware) + @httpPost('/', TYPES.Auth_ApiGatewayAuthMiddleware) async createToken(_request: Request, response: Response): Promise { if (response.locals.readOnlyAccess) { return this.json( diff --git a/packages/auth/src/Controller/UserRequestsController.ts b/packages/auth/src/Controller/UserRequestsController.ts index 0cbcf2dd0..a760c1578 100644 --- a/packages/auth/src/Controller/UserRequestsController.ts +++ b/packages/auth/src/Controller/UserRequestsController.ts @@ -6,7 +6,7 @@ import { ProcessUserRequest } from '../Domain/UseCase/ProcessUserRequest/Process @injectable() export class UserRequestsController implements UserRequestServerInterface { - constructor(@inject(TYPES.ProcessUserRequest) private processUserRequest: ProcessUserRequest) {} + constructor(@inject(TYPES.Auth_ProcessUserRequest) private processUserRequest: ProcessUserRequest) {} async submitUserRequest(params: UserRequestRequestParams): Promise> { const result = await this.processUserRequest.execute({ diff --git a/packages/auth/src/Controller/UsersController.spec.ts b/packages/auth/src/Controller/UsersController.spec.ts index 3e1cd4285..e3d262938 100644 --- a/packages/auth/src/Controller/UsersController.spec.ts +++ b/packages/auth/src/Controller/UsersController.spec.ts @@ -13,6 +13,7 @@ import { ClearLoginAttempts } from '../Domain/UseCase/ClearLoginAttempts' import { IncreaseLoginAttempts } from '../Domain/UseCase/IncreaseLoginAttempts' import { ChangeCredentials } from '../Domain/UseCase/ChangeCredentials/ChangeCredentials' import { InviteToSharedSubscription } from '../Domain/UseCase/InviteToSharedSubscription/InviteToSharedSubscription' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('UsersController', () => { let updateUser: UpdateUser @@ -27,6 +28,7 @@ describe('UsersController', () => { let request: express.Request let response: express.Response let user: User + let controllerContainer: ControllerContainerInterface const createController = () => new UsersController( @@ -37,9 +39,13 @@ describe('UsersController', () => { clearLoginAttempts, increaseLoginAttempts, changeCredentials, + controllerContainer, ) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + updateUser = {} as jest.Mocked updateUser.execute = jest.fn() diff --git a/packages/auth/src/Controller/UsersController.ts b/packages/auth/src/Controller/UsersController.ts index 7efdcb788..f04b3ae5f 100644 --- a/packages/auth/src/Controller/UsersController.ts +++ b/packages/auth/src/Controller/UsersController.ts @@ -19,22 +19,29 @@ import { GetUserSubscription } from '../Domain/UseCase/GetUserSubscription/GetUs import { ClearLoginAttempts } from '../Domain/UseCase/ClearLoginAttempts' import { IncreaseLoginAttempts } from '../Domain/UseCase/IncreaseLoginAttempts' import { ChangeCredentials } from '../Domain/UseCase/ChangeCredentials/ChangeCredentials' +import { ControllerContainerInterface } from '@standardnotes/domain-core' @controller('/users') export class UsersController extends BaseHttpController { constructor( - @inject(TYPES.UpdateUser) private updateUser: UpdateUser, - @inject(TYPES.GetUserKeyParams) private getUserKeyParams: GetUserKeyParams, - @inject(TYPES.DeleteAccount) private doDeleteAccount: DeleteAccount, - @inject(TYPES.GetUserSubscription) private doGetUserSubscription: GetUserSubscription, - @inject(TYPES.ClearLoginAttempts) private clearLoginAttempts: ClearLoginAttempts, - @inject(TYPES.IncreaseLoginAttempts) private increaseLoginAttempts: IncreaseLoginAttempts, - @inject(TYPES.ChangeCredentials) private changeCredentialsUseCase: ChangeCredentials, + @inject(TYPES.Auth_UpdateUser) private updateUser: UpdateUser, + @inject(TYPES.Auth_GetUserKeyParams) private getUserKeyParams: GetUserKeyParams, + @inject(TYPES.Auth_DeleteAccount) private doDeleteAccount: DeleteAccount, + @inject(TYPES.Auth_GetUserSubscription) private doGetUserSubscription: GetUserSubscription, + @inject(TYPES.Auth_ClearLoginAttempts) private clearLoginAttempts: ClearLoginAttempts, + @inject(TYPES.Auth_IncreaseLoginAttempts) private increaseLoginAttempts: IncreaseLoginAttempts, + @inject(TYPES.Auth_ChangeCredentials) private changeCredentialsUseCase: ChangeCredentials, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('auth.users.update', this.update.bind(this)) + this.controllerContainer.register('auth.users.getKeyParams', this.keyParams.bind(this)) + this.controllerContainer.register('auth.users.getSubscription', this.getSubscription.bind(this)) + this.controllerContainer.register('auth.users.updateCredentials', this.changeCredentials.bind(this)) } - @httpPatch('/:userId', TYPES.ApiGatewayAuthMiddleware) + @httpPatch('/:userId', TYPES.Auth_ApiGatewayAuthMiddleware) async update(request: Request, response: Response): Promise { if (response.locals.readOnlyAccess) { return this.json( @@ -125,7 +132,7 @@ export class UsersController extends BaseHttpController { return this.json({ message: result.message }, result.responseCode) } - @httpGet('/:userUuid/subscription', TYPES.ApiGatewayAuthMiddleware) + @httpGet('/:userUuid/subscription', TYPES.Auth_ApiGatewayAuthMiddleware) async getSubscription(request: Request, response: Response): Promise { if (request.params.userUuid !== response.locals.user.uuid) { return this.json( @@ -149,7 +156,7 @@ export class UsersController extends BaseHttpController { return this.json(result, 400) } - @httpPut('/:userId/attributes/credentials', TYPES.AuthMiddleware) + @httpPut('/:userId/attributes/credentials', TYPES.Auth_AuthMiddleware) async changeCredentials(request: Request, response: Response): Promise { if (response.locals.readOnlyAccess) { return this.json( diff --git a/packages/auth/src/Controller/ValetTokenController.spec.ts b/packages/auth/src/Controller/ValetTokenController.spec.ts index d8f379cdd..7da3a7908 100644 --- a/packages/auth/src/Controller/ValetTokenController.spec.ts +++ b/packages/auth/src/Controller/ValetTokenController.spec.ts @@ -4,15 +4,20 @@ import { Request, Response } from 'express' import { results } from 'inversify-express-utils' import { ValetTokenController } from './ValetTokenController' import { CreateValetToken } from '../Domain/UseCase/CreateValetToken/CreateValetToken' +import { ControllerContainerInterface } from '@standardnotes/domain-core' describe('ValetTokenController', () => { let createValetToken: CreateValetToken let request: Request let response: Response + let controllerContainer: ControllerContainerInterface - const createController = () => new ValetTokenController(createValetToken) + const createController = () => new ValetTokenController(createValetToken, controllerContainer) beforeEach(() => { + controllerContainer = {} as jest.Mocked + controllerContainer.register = jest.fn() + createValetToken = {} as jest.Mocked createValetToken.execute = jest.fn().mockReturnValue({ success: true, valetToken: 'foobar' }) diff --git a/packages/auth/src/Controller/ValetTokenController.ts b/packages/auth/src/Controller/ValetTokenController.ts index 57951a3e3..c4c45ac87 100644 --- a/packages/auth/src/Controller/ValetTokenController.ts +++ b/packages/auth/src/Controller/ValetTokenController.ts @@ -9,15 +9,20 @@ import { } from 'inversify-express-utils' import { CreateValetTokenPayload, ErrorTag } from '@standardnotes/responses' import { ValetTokenOperation } from '@standardnotes/security' -import { Uuid } from '@standardnotes/domain-core' +import { ControllerContainerInterface, Uuid } from '@standardnotes/domain-core' import TYPES from '../Bootstrap/Types' import { CreateValetToken } from '../Domain/UseCase/CreateValetToken/CreateValetToken' -@controller('/valet-tokens', TYPES.ApiGatewayAuthMiddleware) +@controller('/valet-tokens', TYPES.Auth_ApiGatewayAuthMiddleware) export class ValetTokenController extends BaseHttpController { - constructor(@inject(TYPES.CreateValetToken) private createValetKey: CreateValetToken) { + constructor( + @inject(TYPES.Auth_CreateValetToken) private createValetKey: CreateValetToken, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, + ) { super() + + this.controllerContainer.register('auth.valet-tokens.create', this.create.bind(this)) } @httpPost('/') diff --git a/packages/auth/src/Domain/Auth/AuthResponseFactory20161215.ts b/packages/auth/src/Domain/Auth/AuthResponseFactory20161215.ts index 632ceb06d..cd6827a36 100644 --- a/packages/auth/src/Domain/Auth/AuthResponseFactory20161215.ts +++ b/packages/auth/src/Domain/Auth/AuthResponseFactory20161215.ts @@ -15,9 +15,9 @@ import { AuthResponseFactoryInterface } from './AuthResponseFactoryInterface' @injectable() export class AuthResponseFactory20161215 implements AuthResponseFactoryInterface { constructor( - @inject(TYPES.UserProjector) protected userProjector: ProjectorInterface, - @inject(TYPES.SessionTokenEncoder) protected tokenEncoder: TokenEncoderInterface, - @inject(TYPES.Logger) protected logger: Logger, + @inject(TYPES.Auth_UserProjector) protected userProjector: ProjectorInterface, + @inject(TYPES.Auth_SessionTokenEncoder) protected tokenEncoder: TokenEncoderInterface, + @inject(TYPES.Auth_Logger) protected logger: Logger, ) {} async createResponse(dto: { diff --git a/packages/auth/src/Domain/Auth/AuthResponseFactory20200115.ts b/packages/auth/src/Domain/Auth/AuthResponseFactory20200115.ts index f62faa5d4..368385d65 100644 --- a/packages/auth/src/Domain/Auth/AuthResponseFactory20200115.ts +++ b/packages/auth/src/Domain/Auth/AuthResponseFactory20200115.ts @@ -23,13 +23,13 @@ import { AuthResponse20200115 } from './AuthResponse20200115' @injectable() export class AuthResponseFactory20200115 extends AuthResponseFactory20190520 { constructor( - @inject(TYPES.SessionService) private sessionService: SessionServiceInterface, - @inject(TYPES.KeyParamsFactory) private keyParamsFactory: KeyParamsFactoryInterface, - @inject(TYPES.UserProjector) userProjector: ProjectorInterface, - @inject(TYPES.SessionTokenEncoder) protected override tokenEncoder: TokenEncoderInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.Logger) logger: Logger, + @inject(TYPES.Auth_SessionService) private sessionService: SessionServiceInterface, + @inject(TYPES.Auth_KeyParamsFactory) private keyParamsFactory: KeyParamsFactoryInterface, + @inject(TYPES.Auth_UserProjector) userProjector: ProjectorInterface, + @inject(TYPES.Auth_SessionTokenEncoder) protected override tokenEncoder: TokenEncoderInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_Logger) logger: Logger, ) { super(userProjector, tokenEncoder, logger) } diff --git a/packages/auth/src/Domain/Auth/AuthResponseFactoryResolver.ts b/packages/auth/src/Domain/Auth/AuthResponseFactoryResolver.ts index b0163def9..bf1a9b3a6 100644 --- a/packages/auth/src/Domain/Auth/AuthResponseFactoryResolver.ts +++ b/packages/auth/src/Domain/Auth/AuthResponseFactoryResolver.ts @@ -11,10 +11,10 @@ import { AuthResponseFactoryResolverInterface } from './AuthResponseFactoryResol @injectable() export class AuthResponseFactoryResolver implements AuthResponseFactoryResolverInterface { constructor( - @inject(TYPES.AuthResponseFactory20161215) private authResponseFactory20161215: AuthResponseFactory20161215, - @inject(TYPES.AuthResponseFactory20190520) private authResponseFactory20190520: AuthResponseFactory20190520, - @inject(TYPES.AuthResponseFactory20200115) private authResponseFactory20200115: AuthResponseFactory20200115, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_AuthResponseFactory20161215) private authResponseFactory20161215: AuthResponseFactory20161215, + @inject(TYPES.Auth_AuthResponseFactory20190520) private authResponseFactory20190520: AuthResponseFactory20190520, + @inject(TYPES.Auth_AuthResponseFactory20200115) private authResponseFactory20200115: AuthResponseFactory20200115, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} resolveAuthResponseFactoryVersion(apiVersion: string): AuthResponseFactoryInterface { diff --git a/packages/auth/src/Domain/Auth/AuthenticationMethodResolver.ts b/packages/auth/src/Domain/Auth/AuthenticationMethodResolver.ts index feabcb333..469cd9ff6 100644 --- a/packages/auth/src/Domain/Auth/AuthenticationMethodResolver.ts +++ b/packages/auth/src/Domain/Auth/AuthenticationMethodResolver.ts @@ -9,10 +9,10 @@ import { AuthenticationMethodResolverInterface } from './AuthenticationMethodRes @injectable() export class AuthenticationMethodResolver implements AuthenticationMethodResolverInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.SessionService) private sessionService: SessionServiceInterface, - @inject(TYPES.SessionTokenDecoder) private sessionTokenDecoder: TokenDecoderInterface, - @inject(TYPES.FallbackSessionTokenDecoder) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_SessionService) private sessionService: SessionServiceInterface, + @inject(TYPES.Auth_SessionTokenDecoder) private sessionTokenDecoder: TokenDecoderInterface, + @inject(TYPES.Auth_FallbackSessionTokenDecoder) private fallbackSessionTokenDecoder: TokenDecoderInterface, ) {} diff --git a/packages/auth/src/Domain/Encryption/CrypterNode.ts b/packages/auth/src/Domain/Encryption/CrypterNode.ts index 4538102fb..47b7af171 100644 --- a/packages/auth/src/Domain/Encryption/CrypterNode.ts +++ b/packages/auth/src/Domain/Encryption/CrypterNode.ts @@ -9,9 +9,9 @@ import { CrypterInterface } from './CrypterInterface' @injectable() export class CrypterNode implements CrypterInterface { constructor( - @inject(TYPES.ENCRYPTION_SERVER_KEY) private encryptionServerKey: string, - @inject(TYPES.CryptoNode) private cryptoNode: CryptoNode, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_ENCRYPTION_SERVER_KEY) private encryptionServerKey: string, + @inject(TYPES.Auth_CryptoNode) private cryptoNode: CryptoNode, + @inject(TYPES.Auth_Logger) private logger: Logger, ) { const keyBuffer = Buffer.from(encryptionServerKey, 'hex') const { byteLength } = keyBuffer diff --git a/packages/auth/src/Domain/Event/DomainEventFactory.ts b/packages/auth/src/Domain/Event/DomainEventFactory.ts index 1e46bde5d..570c811b8 100644 --- a/packages/auth/src/Domain/Event/DomainEventFactory.ts +++ b/packages/auth/src/Domain/Event/DomainEventFactory.ts @@ -30,7 +30,7 @@ import { DomainEventFactoryInterface } from './DomainEventFactoryInterface' @injectable() export class DomainEventFactory implements DomainEventFactoryInterface { - constructor(@inject(TYPES.Timer) private timer: TimerInterface) {} + constructor(@inject(TYPES.Auth_Timer) private timer: TimerInterface) {} createSessionCreatedEvent(dto: { userUuid: string }): SessionCreatedEvent { return { diff --git a/packages/auth/src/Domain/Feature/FeatureService.ts b/packages/auth/src/Domain/Feature/FeatureService.ts index 92b27bf9f..968718d44 100644 --- a/packages/auth/src/Domain/Feature/FeatureService.ts +++ b/packages/auth/src/Domain/Feature/FeatureService.ts @@ -15,10 +15,10 @@ import { TimerInterface } from '@standardnotes/time' @injectable() export class FeatureService implements FeatureServiceInterface { constructor( - @inject(TYPES.RoleToSubscriptionMap) private roleToSubscriptionMap: RoleToSubscriptionMapInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_RoleToSubscriptionMap) private roleToSubscriptionMap: RoleToSubscriptionMapInterface, + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async userIsEntitledToFeature(user: User, featureIdentifier: string): Promise { diff --git a/packages/auth/src/Domain/Handler/AccountDeletionRequestedEventHandler.ts b/packages/auth/src/Domain/Handler/AccountDeletionRequestedEventHandler.ts index e7c6e45b4..d2b5d5d56 100644 --- a/packages/auth/src/Domain/Handler/AccountDeletionRequestedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/AccountDeletionRequestedEventHandler.ts @@ -10,11 +10,12 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface' @injectable() export class AccountDeletionRequestedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.SessionRepository) private sessionRepository: SessionRepositoryInterface, - @inject(TYPES.EphemeralSessionRepository) private ephemeralSessionRepository: EphemeralSessionRepositoryInterface, - @inject(TYPES.RevokedSessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_SessionRepository) private sessionRepository: SessionRepositoryInterface, + @inject(TYPES.Auth_EphemeralSessionRepository) + private ephemeralSessionRepository: EphemeralSessionRepositoryInterface, + @inject(TYPES.Auth_RevokedSessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: AccountDeletionRequestedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/ExtensionKeyGrantedEventHandler.ts b/packages/auth/src/Domain/Handler/ExtensionKeyGrantedEventHandler.ts index d8866aea1..f0d58ebcb 100644 --- a/packages/auth/src/Domain/Handler/ExtensionKeyGrantedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/ExtensionKeyGrantedEventHandler.ts @@ -16,11 +16,11 @@ import { Username } from '@standardnotes/domain-core' @injectable() export class ExtensionKeyGrantedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.OfflineSettingService) private offlineSettingService: OfflineSettingServiceInterface, - @inject(TYPES.ContenDecoder) private contentDecoder: ContentDecoderInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_OfflineSettingService) private offlineSettingService: OfflineSettingServiceInterface, + @inject(TYPES.Auth_ContenDecoder) private contentDecoder: ContentDecoderInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: ExtensionKeyGrantedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/FileRemovedEventHandler.ts b/packages/auth/src/Domain/Handler/FileRemovedEventHandler.ts index a4c5310c0..cef93733d 100644 --- a/packages/auth/src/Domain/Handler/FileRemovedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/FileRemovedEventHandler.ts @@ -12,9 +12,10 @@ import { UserSubscriptionServiceInterface } from '../Subscription/UserSubscripti @injectable() export class FileRemovedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, - @inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, + @inject(TYPES.Auth_SubscriptionSettingService) + private subscriptionSettingService: SubscriptionSettingServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: FileRemovedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/FileUploadedEventHandler.ts b/packages/auth/src/Domain/Handler/FileUploadedEventHandler.ts index 542a6435f..80758550d 100644 --- a/packages/auth/src/Domain/Handler/FileUploadedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/FileUploadedEventHandler.ts @@ -13,10 +13,11 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface' @injectable() export class FileUploadedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, - @inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, + @inject(TYPES.Auth_SubscriptionSettingService) + private subscriptionSettingService: SubscriptionSettingServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: FileUploadedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/ListedAccountCreatedEventHandler.ts b/packages/auth/src/Domain/Handler/ListedAccountCreatedEventHandler.ts index b9027e021..d4411db62 100644 --- a/packages/auth/src/Domain/Handler/ListedAccountCreatedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/ListedAccountCreatedEventHandler.ts @@ -11,9 +11,9 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface' @injectable() export class ListedAccountCreatedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: ListedAccountCreatedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/ListedAccountDeletedEventHandler.ts b/packages/auth/src/Domain/Handler/ListedAccountDeletedEventHandler.ts index 3e5c12379..9011e1a3c 100644 --- a/packages/auth/src/Domain/Handler/ListedAccountDeletedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/ListedAccountDeletedEventHandler.ts @@ -11,9 +11,9 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface' @injectable() export class ListedAccountDeletedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: ListedAccountDeletedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/PredicateVerificationRequestedEventHandler.ts b/packages/auth/src/Domain/Handler/PredicateVerificationRequestedEventHandler.ts index 4366a2408..e5e3f19f1 100644 --- a/packages/auth/src/Domain/Handler/PredicateVerificationRequestedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/PredicateVerificationRequestedEventHandler.ts @@ -16,11 +16,11 @@ import { UserRepositoryInterface } from '../User/UserRepositoryInterface' @injectable() export class PredicateVerificationRequestedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.VerifyPredicate) private verifyPredicate: VerifyPredicate, - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_VerifyPredicate) private verifyPredicate: VerifyPredicate, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: PredicateVerificationRequestedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/SharedSubscriptionInvitationCreatedEventHandler.ts b/packages/auth/src/Domain/Handler/SharedSubscriptionInvitationCreatedEventHandler.ts index e1a4df77a..d77d6eaa8 100644 --- a/packages/auth/src/Domain/Handler/SharedSubscriptionInvitationCreatedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/SharedSubscriptionInvitationCreatedEventHandler.ts @@ -8,7 +8,7 @@ import { AcceptSharedSubscriptionInvitation } from '../UseCase/AcceptSharedSubsc @injectable() export class SharedSubscriptionInvitationCreatedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.AcceptSharedSubscriptionInvitation) + @inject(TYPES.Auth_AcceptSharedSubscriptionInvitation) private acceptSharedSubscriptionInvitation: AcceptSharedSubscriptionInvitation, ) {} diff --git a/packages/auth/src/Domain/Handler/SubscriptionCancelledEventHandler.ts b/packages/auth/src/Domain/Handler/SubscriptionCancelledEventHandler.ts index be3490ac5..c13767da9 100644 --- a/packages/auth/src/Domain/Handler/SubscriptionCancelledEventHandler.ts +++ b/packages/auth/src/Domain/Handler/SubscriptionCancelledEventHandler.ts @@ -8,8 +8,9 @@ import { OfflineUserSubscriptionRepositoryInterface } from '../Subscription/Offl @injectable() export class SubscriptionCancelledEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, ) {} diff --git a/packages/auth/src/Domain/Handler/SubscriptionExpiredEventHandler.ts b/packages/auth/src/Domain/Handler/SubscriptionExpiredEventHandler.ts index bf4798794..d737ac458 100644 --- a/packages/auth/src/Domain/Handler/SubscriptionExpiredEventHandler.ts +++ b/packages/auth/src/Domain/Handler/SubscriptionExpiredEventHandler.ts @@ -12,12 +12,13 @@ import { Username } from '@standardnotes/domain-core' @injectable() export class SubscriptionExpiredEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, - @inject(TYPES.RoleService) private roleService: RoleServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: SubscriptionExpiredEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/SubscriptionPurchasedEventHandler.ts b/packages/auth/src/Domain/Handler/SubscriptionPurchasedEventHandler.ts index aa4a56309..fb2a92727 100644 --- a/packages/auth/src/Domain/Handler/SubscriptionPurchasedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/SubscriptionPurchasedEventHandler.ts @@ -17,13 +17,15 @@ import { Username } from '@standardnotes/domain-core' @injectable() export class SubscriptionPurchasedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, - @inject(TYPES.RoleService) private roleService: RoleServiceInterface, - @inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface, + @inject(TYPES.Auth_SubscriptionSettingService) + private subscriptionSettingService: SubscriptionSettingServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: SubscriptionPurchasedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/SubscriptionReassignedEventHandler.ts b/packages/auth/src/Domain/Handler/SubscriptionReassignedEventHandler.ts index e3460df86..8cb5fc3de 100644 --- a/packages/auth/src/Domain/Handler/SubscriptionReassignedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/SubscriptionReassignedEventHandler.ts @@ -18,12 +18,14 @@ import { Username } from '@standardnotes/domain-core' @injectable() export class SubscriptionReassignedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.RoleService) private roleService: RoleServiceInterface, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_SubscriptionSettingService) + private subscriptionSettingService: SubscriptionSettingServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: SubscriptionReassignedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/SubscriptionRefundedEventHandler.ts b/packages/auth/src/Domain/Handler/SubscriptionRefundedEventHandler.ts index 29926bcd2..f541381d1 100644 --- a/packages/auth/src/Domain/Handler/SubscriptionRefundedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/SubscriptionRefundedEventHandler.ts @@ -12,12 +12,13 @@ import { Username } from '@standardnotes/domain-core' @injectable() export class SubscriptionRefundedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, - @inject(TYPES.RoleService) private roleService: RoleServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: SubscriptionRefundedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/SubscriptionRenewedEventHandler.ts b/packages/auth/src/Domain/Handler/SubscriptionRenewedEventHandler.ts index e67e1675a..2b8e78d32 100644 --- a/packages/auth/src/Domain/Handler/SubscriptionRenewedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/SubscriptionRenewedEventHandler.ts @@ -13,12 +13,13 @@ import { Username } from '@standardnotes/domain-core' @injectable() export class SubscriptionRenewedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, - @inject(TYPES.RoleService) private roleService: RoleServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: SubscriptionRenewedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/SubscriptionSyncRequestedEventHandler.ts b/packages/auth/src/Domain/Handler/SubscriptionSyncRequestedEventHandler.ts index 7e042dc87..ef7b115e5 100644 --- a/packages/auth/src/Domain/Handler/SubscriptionSyncRequestedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/SubscriptionSyncRequestedEventHandler.ts @@ -24,16 +24,18 @@ import { Username } from '@standardnotes/domain-core' @injectable() export class SubscriptionSyncRequestedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, - @inject(TYPES.RoleService) private roleService: RoleServiceInterface, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, - @inject(TYPES.OfflineSettingService) private offlineSettingService: OfflineSettingServiceInterface, - @inject(TYPES.ContenDecoder) private contentDecoder: ContentDecoderInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_SubscriptionSettingService) + private subscriptionSettingService: SubscriptionSettingServiceInterface, + @inject(TYPES.Auth_OfflineSettingService) private offlineSettingService: OfflineSettingServiceInterface, + @inject(TYPES.Auth_ContenDecoder) private contentDecoder: ContentDecoderInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: SubscriptionSyncRequestedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/UserDisabledSessionUserAgentLoggingEventHandler.ts b/packages/auth/src/Domain/Handler/UserDisabledSessionUserAgentLoggingEventHandler.ts index 865cf168f..ce958811c 100644 --- a/packages/auth/src/Domain/Handler/UserDisabledSessionUserAgentLoggingEventHandler.ts +++ b/packages/auth/src/Domain/Handler/UserDisabledSessionUserAgentLoggingEventHandler.ts @@ -8,8 +8,8 @@ import { SessionRepositoryInterface } from '../Session/SessionRepositoryInterfac @injectable() export class UserDisabledSessionUserAgentLoggingEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.SessionRepository) private sessionRepository: SessionRepositoryInterface, - @inject(TYPES.SessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface, + @inject(TYPES.Auth_SessionRepository) private sessionRepository: SessionRepositoryInterface, + @inject(TYPES.Auth_SessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface, ) {} async handle(event: UserDisabledSessionUserAgentLoggingEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/UserEmailChangedEventHandler.ts b/packages/auth/src/Domain/Handler/UserEmailChangedEventHandler.ts index b6522e709..6534225dc 100644 --- a/packages/auth/src/Domain/Handler/UserEmailChangedEventHandler.ts +++ b/packages/auth/src/Domain/Handler/UserEmailChangedEventHandler.ts @@ -8,10 +8,10 @@ import TYPES from '../../Bootstrap/Types' @injectable() export class UserEmailChangedEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.HTTPClient) private httpClient: AxiosInstance, - @inject(TYPES.USER_SERVER_CHANGE_EMAIL_URL) private userServerChangeEmailUrl: string, - @inject(TYPES.USER_SERVER_AUTH_KEY) private userServerAuthKey: string, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_HTTPClient) private httpClient: AxiosInstance, + @inject(TYPES.Auth_USER_SERVER_CHANGE_EMAIL_URL) private userServerChangeEmailUrl: string, + @inject(TYPES.Auth_USER_SERVER_AUTH_KEY) private userServerAuthKey: string, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: UserEmailChangedEvent): Promise { diff --git a/packages/auth/src/Domain/Handler/UserRegisteredEventHandler.ts b/packages/auth/src/Domain/Handler/UserRegisteredEventHandler.ts index c4ba7e9fe..fd38ffd7e 100644 --- a/packages/auth/src/Domain/Handler/UserRegisteredEventHandler.ts +++ b/packages/auth/src/Domain/Handler/UserRegisteredEventHandler.ts @@ -8,10 +8,10 @@ import TYPES from '../../Bootstrap/Types' @injectable() export class UserRegisteredEventHandler implements DomainEventHandlerInterface { constructor( - @inject(TYPES.HTTPClient) private httpClient: AxiosInstance, - @inject(TYPES.USER_SERVER_REGISTRATION_URL) private userServerRegistrationUrl: string, - @inject(TYPES.USER_SERVER_AUTH_KEY) private userServerAuthKey: string, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_HTTPClient) private httpClient: AxiosInstance, + @inject(TYPES.Auth_USER_SERVER_REGISTRATION_URL) private userServerRegistrationUrl: string, + @inject(TYPES.Auth_USER_SERVER_AUTH_KEY) private userServerAuthKey: string, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async handle(event: UserRegisteredEvent): Promise { diff --git a/packages/auth/src/Domain/Role/RoleService.ts b/packages/auth/src/Domain/Role/RoleService.ts index 726fd9e89..6780359f5 100644 --- a/packages/auth/src/Domain/Role/RoleService.ts +++ b/packages/auth/src/Domain/Role/RoleService.ts @@ -17,13 +17,13 @@ import { OfflineUserSubscription } from '../Subscription/OfflineUserSubscription @injectable() export class RoleService implements RoleServiceInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.RoleRepository) private roleRepository: RoleRepositoryInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_RoleRepository) private roleRepository: RoleRepositoryInterface, + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, - @inject(TYPES.WebSocketsClientService) private webSocketsClientService: ClientServiceInterface, - @inject(TYPES.RoleToSubscriptionMap) private roleToSubscriptionMap: RoleToSubscriptionMapInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_WebSocketsClientService) private webSocketsClientService: ClientServiceInterface, + @inject(TYPES.Auth_RoleToSubscriptionMap) private roleToSubscriptionMap: RoleToSubscriptionMapInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async userHasPermission(userUuid: string, permissionName: PermissionName): Promise { diff --git a/packages/auth/src/Domain/Session/SessionService.ts b/packages/auth/src/Domain/Session/SessionService.ts index dfc55142f..080e13f98 100644 --- a/packages/auth/src/Domain/Session/SessionService.ts +++ b/packages/auth/src/Domain/Session/SessionService.ts @@ -27,19 +27,21 @@ export class SessionService implements SessionServiceInterface { static readonly SESSION_TOKEN_VERSION = 1 constructor( - @inject(TYPES.SessionRepository) private sessionRepository: SessionRepositoryInterface, - @inject(TYPES.EphemeralSessionRepository) private ephemeralSessionRepository: EphemeralSessionRepositoryInterface, - @inject(TYPES.RevokedSessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface, - @inject(TYPES.DeviceDetector) private deviceDetector: UAParser, - @inject(TYPES.Timer) private timer: TimerInterface, - @inject(TYPES.Logger) private logger: Logger, - @inject(TYPES.ACCESS_TOKEN_AGE) private accessTokenAge: number, - @inject(TYPES.REFRESH_TOKEN_AGE) private refreshTokenAge: number, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.CryptoNode) private cryptoNode: CryptoNode, - @inject(TYPES.TraceSession) private traceSession: TraceSession, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.READONLY_USERS) private readonlyUsers: string[], + @inject(TYPES.Auth_SessionRepository) private sessionRepository: SessionRepositoryInterface, + @inject(TYPES.Auth_EphemeralSessionRepository) + private ephemeralSessionRepository: EphemeralSessionRepositoryInterface, + @inject(TYPES.Auth_RevokedSessionRepository) private revokedSessionRepository: RevokedSessionRepositoryInterface, + @inject(TYPES.Auth_DeviceDetector) private deviceDetector: UAParser, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, + @inject(TYPES.Auth_ACCESS_TOKEN_AGE) private accessTokenAge: number, + @inject(TYPES.Auth_REFRESH_TOKEN_AGE) private refreshTokenAge: number, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_CryptoNode) private cryptoNode: CryptoNode, + @inject(TYPES.Auth_TraceSession) private traceSession: TraceSession, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_READONLY_USERS) private readonlyUsers: string[], ) {} async createNewSessionForUser(dto: { diff --git a/packages/auth/src/Domain/Setting/OfflineSettingService.ts b/packages/auth/src/Domain/Setting/OfflineSettingService.ts index 02e12383d..6987f73dc 100644 --- a/packages/auth/src/Domain/Setting/OfflineSettingService.ts +++ b/packages/auth/src/Domain/Setting/OfflineSettingService.ts @@ -12,8 +12,8 @@ import { OfflineSettingServiceInterface } from './OfflineSettingServiceInterface @injectable() export class OfflineSettingService implements OfflineSettingServiceInterface { constructor( - @inject(TYPES.OfflineSettingRepository) private offlineSettingRepository: OfflineSettingRepositoryInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_OfflineSettingRepository) private offlineSettingRepository: OfflineSettingRepositoryInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async createOrUpdate(dto: { diff --git a/packages/auth/src/Domain/Setting/SettingDecrypter.ts b/packages/auth/src/Domain/Setting/SettingDecrypter.ts index cf462eb36..c41538083 100644 --- a/packages/auth/src/Domain/Setting/SettingDecrypter.ts +++ b/packages/auth/src/Domain/Setting/SettingDecrypter.ts @@ -10,8 +10,8 @@ import { SubscriptionSetting } from './SubscriptionSetting' @injectable() export class SettingDecrypter implements SettingDecrypterInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.Crypter) private crypter: CrypterInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_Crypter) private crypter: CrypterInterface, ) {} async decryptSettingValue(setting: Setting | SubscriptionSetting, userUuid: string): Promise { diff --git a/packages/auth/src/Domain/Setting/SettingFactory.ts b/packages/auth/src/Domain/Setting/SettingFactory.ts index d670869b6..659733b6d 100644 --- a/packages/auth/src/Domain/Setting/SettingFactory.ts +++ b/packages/auth/src/Domain/Setting/SettingFactory.ts @@ -15,8 +15,8 @@ import { SubscriptionSettingProps } from './SubscriptionSettingProps' @injectable() export class SettingFactory implements SettingFactoryInterface { constructor( - @inject(TYPES.Crypter) private crypter: CrypterInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Crypter) private crypter: CrypterInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async createSubscriptionSetting( diff --git a/packages/auth/src/Domain/Setting/SettingInterpreter.ts b/packages/auth/src/Domain/Setting/SettingInterpreter.ts index e0caadb30..d71febb31 100644 --- a/packages/auth/src/Domain/Setting/SettingInterpreter.ts +++ b/packages/auth/src/Domain/Setting/SettingInterpreter.ts @@ -24,9 +24,9 @@ export class SettingInterpreter implements SettingInterpreterInterface { ]) constructor( - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.SettingRepository) private settingRepository: SettingRepositoryInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_SettingRepository) private settingRepository: SettingRepositoryInterface, ) {} async interpretSettingUpdated( diff --git a/packages/auth/src/Domain/Setting/SettingService.ts b/packages/auth/src/Domain/Setting/SettingService.ts index 7460c8ca4..5d3fa868a 100644 --- a/packages/auth/src/Domain/Setting/SettingService.ts +++ b/packages/auth/src/Domain/Setting/SettingService.ts @@ -17,12 +17,13 @@ import { SettingFactoryInterface } from './SettingFactoryInterface' @injectable() export class SettingService implements SettingServiceInterface { constructor( - @inject(TYPES.SettingFactory) private factory: SettingFactoryInterface, - @inject(TYPES.SettingRepository) private settingRepository: SettingRepositoryInterface, - @inject(TYPES.SettingsAssociationService) private settingsAssociationService: SettingsAssociationServiceInterface, - @inject(TYPES.SettingInterpreter) private settingInterpreter: SettingInterpreterInterface, - @inject(TYPES.SettingDecrypter) private settingDecrypter: SettingDecrypterInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_SettingFactory) private factory: SettingFactoryInterface, + @inject(TYPES.Auth_SettingRepository) private settingRepository: SettingRepositoryInterface, + @inject(TYPES.Auth_SettingsAssociationService) + private settingsAssociationService: SettingsAssociationServiceInterface, + @inject(TYPES.Auth_SettingInterpreter) private settingInterpreter: SettingInterpreterInterface, + @inject(TYPES.Auth_SettingDecrypter) private settingDecrypter: SettingDecrypterInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async applyDefaultSettingsUponRegistration(user: User): Promise { diff --git a/packages/auth/src/Domain/Setting/SubscriptionSettingService.ts b/packages/auth/src/Domain/Setting/SubscriptionSettingService.ts index f511189cc..c379ae640 100644 --- a/packages/auth/src/Domain/Setting/SubscriptionSettingService.ts +++ b/packages/auth/src/Domain/Setting/SubscriptionSettingService.ts @@ -22,15 +22,16 @@ import { SettingInterpreterInterface } from './SettingInterpreterInterface' @injectable() export class SubscriptionSettingService implements SubscriptionSettingServiceInterface { constructor( - @inject(TYPES.SettingFactory) private factory: SettingFactoryInterface, - @inject(TYPES.SubscriptionSettingRepository) + @inject(TYPES.Auth_SettingFactory) private factory: SettingFactoryInterface, + @inject(TYPES.Auth_SubscriptionSettingRepository) private subscriptionSettingRepository: SubscriptionSettingRepositoryInterface, - @inject(TYPES.SubscriptionSettingsAssociationService) + @inject(TYPES.Auth_SubscriptionSettingsAssociationService) private subscriptionSettingAssociationService: SubscriptionSettingsAssociationServiceInterface, - @inject(TYPES.SettingInterpreter) private settingInterpreter: SettingInterpreterInterface, - @inject(TYPES.SettingDecrypter) private settingDecrypter: SettingDecrypterInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_SettingInterpreter) private settingInterpreter: SettingInterpreterInterface, + @inject(TYPES.Auth_SettingDecrypter) private settingDecrypter: SettingDecrypterInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async applyDefaultSubscriptionSettingsForSubscription( diff --git a/packages/auth/src/Domain/Setting/SubscriptionSettingsAssociationService.ts b/packages/auth/src/Domain/Setting/SubscriptionSettingsAssociationService.ts index 7d4f77c10..49701f63c 100644 --- a/packages/auth/src/Domain/Setting/SubscriptionSettingsAssociationService.ts +++ b/packages/auth/src/Domain/Setting/SubscriptionSettingsAssociationService.ts @@ -15,8 +15,8 @@ import { SubscriptionSettingsAssociationServiceInterface } from './SubscriptionS @injectable() export class SubscriptionSettingsAssociationService implements SubscriptionSettingsAssociationServiceInterface { constructor( - @inject(TYPES.RoleToSubscriptionMap) private roleToSubscriptionMap: RoleToSubscriptionMapInterface, - @inject(TYPES.RoleRepository) private roleRepository: RoleRepositoryInterface, + @inject(TYPES.Auth_RoleToSubscriptionMap) private roleToSubscriptionMap: RoleToSubscriptionMapInterface, + @inject(TYPES.Auth_RoleRepository) private roleRepository: RoleRepositoryInterface, ) {} private readonly settingsToSubscriptionNameMap = new Map>([ diff --git a/packages/auth/src/Domain/Subscription/UserSubscriptionService.ts b/packages/auth/src/Domain/Subscription/UserSubscriptionService.ts index 3acd0a6a2..70eb2dded 100644 --- a/packages/auth/src/Domain/Subscription/UserSubscriptionService.ts +++ b/packages/auth/src/Domain/Subscription/UserSubscriptionService.ts @@ -11,7 +11,8 @@ import { UserSubscriptionType } from './UserSubscriptionType' @injectable() export class UserSubscriptionService implements UserSubscriptionServiceInterface { constructor( - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, ) {} async findRegularSubscriptionForUserUuid(userUuid: string): Promise { diff --git a/packages/auth/src/Domain/UseCase/AcceptSharedSubscriptionInvitation/AcceptSharedSubscriptionInvitation.ts b/packages/auth/src/Domain/UseCase/AcceptSharedSubscriptionInvitation/AcceptSharedSubscriptionInvitation.ts index 58b07da55..b16d92137 100644 --- a/packages/auth/src/Domain/UseCase/AcceptSharedSubscriptionInvitation/AcceptSharedSubscriptionInvitation.ts +++ b/packages/auth/src/Domain/UseCase/AcceptSharedSubscriptionInvitation/AcceptSharedSubscriptionInvitation.ts @@ -21,13 +21,15 @@ import { AcceptSharedSubscriptionInvitationResponse } from './AcceptSharedSubscr @injectable() export class AcceptSharedSubscriptionInvitation implements UseCaseInterface { constructor( - @inject(TYPES.SharedSubscriptionInvitationRepository) + @inject(TYPES.Auth_SharedSubscriptionInvitationRepository) private sharedSubscriptionInvitationRepository: SharedSubscriptionInvitationRepositoryInterface, - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.RoleService) private roleService: RoleServiceInterface, - @inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface, + @inject(TYPES.Auth_SubscriptionSettingService) + private subscriptionSettingService: SubscriptionSettingServiceInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async execute(dto: AcceptSharedSubscriptionInvitationDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/AuthenticateOfflineSubscriptionToken/AuthenticateOfflineSubscriptionToken.ts b/packages/auth/src/Domain/UseCase/AuthenticateOfflineSubscriptionToken/AuthenticateOfflineSubscriptionToken.ts index e68607abe..b9d5f3ca0 100644 --- a/packages/auth/src/Domain/UseCase/AuthenticateOfflineSubscriptionToken/AuthenticateOfflineSubscriptionToken.ts +++ b/packages/auth/src/Domain/UseCase/AuthenticateOfflineSubscriptionToken/AuthenticateOfflineSubscriptionToken.ts @@ -12,11 +12,11 @@ import { AuthenticateOfflineSubscriptionTokenResponse } from './AuthenticateOffl @injectable() export class AuthenticateOfflineSubscriptionToken implements UseCaseInterface { constructor( - @inject(TYPES.OfflineSubscriptionTokenRepository) + @inject(TYPES.Auth_OfflineSubscriptionTokenRepository) private offlineSubscriptionTokenRepository: OfflineSubscriptionTokenRepositoryInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, - @inject(TYPES.OfflineSettingRepository) private offlineSettingRepository: OfflineSettingRepositoryInterface, + @inject(TYPES.Auth_OfflineSettingRepository) private offlineSettingRepository: OfflineSettingRepositoryInterface, ) {} async execute(dto: AuthenticateOfflineSubscriptionTokenDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/AuthenticateRequest.ts b/packages/auth/src/Domain/UseCase/AuthenticateRequest.ts index 5295320f8..acad1e48a 100644 --- a/packages/auth/src/Domain/UseCase/AuthenticateRequest.ts +++ b/packages/auth/src/Domain/UseCase/AuthenticateRequest.ts @@ -10,8 +10,8 @@ import { UseCaseInterface } from './UseCaseInterface' @injectable() export class AuthenticateRequest implements UseCaseInterface { constructor( - @inject(TYPES.AuthenticateUser) private authenticateUser: AuthenticateUser, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_AuthenticateUser) private authenticateUser: AuthenticateUser, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: AuthenticateRequestDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/AuthenticateSubscriptionToken/AuthenticateSubscriptionToken.ts b/packages/auth/src/Domain/UseCase/AuthenticateSubscriptionToken/AuthenticateSubscriptionToken.ts index d8ca7bed0..892c36037 100644 --- a/packages/auth/src/Domain/UseCase/AuthenticateSubscriptionToken/AuthenticateSubscriptionToken.ts +++ b/packages/auth/src/Domain/UseCase/AuthenticateSubscriptionToken/AuthenticateSubscriptionToken.ts @@ -10,9 +10,9 @@ import { AuthenticateSubscriptionTokenResponse } from './AuthenticateSubscriptio @injectable() export class AuthenticateSubscriptionToken implements UseCaseInterface { constructor( - @inject(TYPES.SubscriptionTokenRepository) + @inject(TYPES.Auth_SubscriptionTokenRepository) private subscriptionTokenRepository: SubscriptionTokenRepositoryInterface, - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, ) {} async execute(dto: AuthenticateSubscriptionTokenDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/AuthenticateUser.ts b/packages/auth/src/Domain/UseCase/AuthenticateUser.ts index ddaa244f4..d5169f3e7 100644 --- a/packages/auth/src/Domain/UseCase/AuthenticateUser.ts +++ b/packages/auth/src/Domain/UseCase/AuthenticateUser.ts @@ -13,10 +13,10 @@ import { UseCaseInterface } from './UseCaseInterface' @injectable() export class AuthenticateUser implements UseCaseInterface { constructor( - @inject(TYPES.AuthenticationMethodResolver) + @inject(TYPES.Auth_AuthenticationMethodResolver) private authenticationMethodResolver: AuthenticationMethodResolverInterface, - @inject(TYPES.Timer) private timer: TimerInterface, - @inject(TYPES.ACCESS_TOKEN_AGE) private accessTokenAge: number, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, + @inject(TYPES.Auth_ACCESS_TOKEN_AGE) private accessTokenAge: number, ) {} async execute(dto: AuthenticateUserDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/CancelSharedSubscriptionInvitation/CancelSharedSubscriptionInvitation.ts b/packages/auth/src/Domain/UseCase/CancelSharedSubscriptionInvitation/CancelSharedSubscriptionInvitation.ts index f2d41e95d..124654c08 100644 --- a/packages/auth/src/Domain/UseCase/CancelSharedSubscriptionInvitation/CancelSharedSubscriptionInvitation.ts +++ b/packages/auth/src/Domain/UseCase/CancelSharedSubscriptionInvitation/CancelSharedSubscriptionInvitation.ts @@ -23,15 +23,16 @@ import { CancelSharedSubscriptionInvitationResponse } from './CancelSharedSubscr @injectable() export class CancelSharedSubscriptionInvitation implements UseCaseInterface { constructor( - @inject(TYPES.SharedSubscriptionInvitationRepository) + @inject(TYPES.Auth_SharedSubscriptionInvitationRepository) private sharedSubscriptionInvitationRepository: SharedSubscriptionInvitationRepositoryInterface, - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.RoleService) private roleService: RoleServiceInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.Timer) private timer: TimerInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: CancelSharedSubscriptionInvitationDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/ChangeCredentials/ChangeCredentials.ts b/packages/auth/src/Domain/UseCase/ChangeCredentials/ChangeCredentials.ts index b88c50b53..dbab71d9b 100644 --- a/packages/auth/src/Domain/UseCase/ChangeCredentials/ChangeCredentials.ts +++ b/packages/auth/src/Domain/UseCase/ChangeCredentials/ChangeCredentials.ts @@ -16,12 +16,12 @@ import { Username } from '@standardnotes/domain-core' @injectable() export class ChangeCredentials implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.AuthResponseFactoryResolver) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_AuthResponseFactoryResolver) private authResponseFactoryResolver: AuthResponseFactoryResolverInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async execute(dto: ChangeCredentialsDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/ClearLoginAttempts.ts b/packages/auth/src/Domain/UseCase/ClearLoginAttempts.ts index 76bf8ff9d..e2af712fa 100644 --- a/packages/auth/src/Domain/UseCase/ClearLoginAttempts.ts +++ b/packages/auth/src/Domain/UseCase/ClearLoginAttempts.ts @@ -11,9 +11,9 @@ import { UseCaseInterface } from './UseCaseInterface' @injectable() export class ClearLoginAttempts implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.LockRepository) private lockRepository: LockRepositoryInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_LockRepository) private lockRepository: LockRepositoryInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: ClearLoginAttemptsDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken.ts b/packages/auth/src/Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken.ts index 69f0171a1..087450b15 100644 --- a/packages/auth/src/Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken.ts +++ b/packages/auth/src/Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken.ts @@ -15,12 +15,12 @@ import { CreateCrossServiceTokenResponse } from './CreateCrossServiceTokenRespon @injectable() export class CreateCrossServiceToken implements UseCaseInterface { constructor( - @inject(TYPES.UserProjector) private userProjector: ProjectorInterface, - @inject(TYPES.SessionProjector) private sessionProjector: ProjectorInterface, - @inject(TYPES.RoleProjector) private roleProjector: ProjectorInterface, - @inject(TYPES.CrossServiceTokenEncoder) private tokenEncoder: TokenEncoderInterface, - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.AUTH_JWT_TTL) private jwtTTL: number, + @inject(TYPES.Auth_UserProjector) private userProjector: ProjectorInterface, + @inject(TYPES.Auth_SessionProjector) private sessionProjector: ProjectorInterface, + @inject(TYPES.Auth_RoleProjector) private roleProjector: ProjectorInterface, + @inject(TYPES.Auth_CrossServiceTokenEncoder) private tokenEncoder: TokenEncoderInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_AUTH_JWT_TTL) private jwtTTL: number, ) {} async execute(dto: CreateCrossServiceTokenDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/CreateListedAccount/CreateListedAccount.ts b/packages/auth/src/Domain/UseCase/CreateListedAccount/CreateListedAccount.ts index 9c8315689..29363a5ce 100644 --- a/packages/auth/src/Domain/UseCase/CreateListedAccount/CreateListedAccount.ts +++ b/packages/auth/src/Domain/UseCase/CreateListedAccount/CreateListedAccount.ts @@ -10,8 +10,8 @@ import { CreateListedAccountResponse } from './CreateListedAccountResponse' @injectable() export class CreateListedAccount implements UseCaseInterface { constructor( - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, ) {} async execute(dto: CreateListedAccountDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/CreateOfflineSubscriptionToken/CreateOfflineSubscriptionToken.ts b/packages/auth/src/Domain/UseCase/CreateOfflineSubscriptionToken/CreateOfflineSubscriptionToken.ts index 2afb4c0d9..ecfbfb498 100644 --- a/packages/auth/src/Domain/UseCase/CreateOfflineSubscriptionToken/CreateOfflineSubscriptionToken.ts +++ b/packages/auth/src/Domain/UseCase/CreateOfflineSubscriptionToken/CreateOfflineSubscriptionToken.ts @@ -17,15 +17,15 @@ import { CreateOfflineSubscriptionTokenResponse } from './CreateOfflineSubscript @injectable() export class CreateOfflineSubscriptionToken implements UseCaseInterface { constructor( - @inject(TYPES.OfflineSubscriptionTokenRepository) + @inject(TYPES.Auth_OfflineSubscriptionTokenRepository) private offlineSubscriptionTokenRepository: OfflineSubscriptionTokenRepositoryInterface, - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, - @inject(TYPES.CryptoNode) private cryptoNode: CryptoNode, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.Timer) private timer: TimerInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_CryptoNode) private cryptoNode: CryptoNode, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: CreateOfflineSubscriptionTokenDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken.ts b/packages/auth/src/Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken.ts index 5b2492cfd..f1e943086 100644 --- a/packages/auth/src/Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken.ts +++ b/packages/auth/src/Domain/UseCase/CreateSubscriptionToken/CreateSubscriptionToken.ts @@ -12,11 +12,11 @@ import { CreateSubscriptionTokenResponse } from './CreateSubscriptionTokenRespon @injectable() export class CreateSubscriptionToken implements UseCaseInterface { constructor( - @inject(TYPES.SubscriptionTokenRepository) + @inject(TYPES.Auth_SubscriptionTokenRepository) private subscriptionTokenRepository: SubscriptionTokenRepositoryInterface, - @inject(TYPES.CryptoNode) private cryptoNode: CryptoNode, - @inject(TYPES.Timer) private timer: TimerInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_CryptoNode) private cryptoNode: CryptoNode, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: CreateSubscriptionTokenDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/CreateValetToken/CreateValetToken.ts b/packages/auth/src/Domain/UseCase/CreateValetToken/CreateValetToken.ts index a7c608a5b..38210ea35 100644 --- a/packages/auth/src/Domain/UseCase/CreateValetToken/CreateValetToken.ts +++ b/packages/auth/src/Domain/UseCase/CreateValetToken/CreateValetToken.ts @@ -16,13 +16,14 @@ import { UserSubscriptionServiceInterface } from '../../Subscription/UserSubscri @injectable() export class CreateValetToken implements UseCaseInterface { constructor( - @inject(TYPES.ValetTokenEncoder) private tokenEncoder: TokenEncoderInterface, - @inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, - @inject(TYPES.SubscriptionSettingsAssociationService) + @inject(TYPES.Auth_ValetTokenEncoder) private tokenEncoder: TokenEncoderInterface, + @inject(TYPES.Auth_SubscriptionSettingService) + private subscriptionSettingService: SubscriptionSettingServiceInterface, + @inject(TYPES.Auth_SubscriptionSettingsAssociationService) private subscriptionSettingsAssociationService: SubscriptionSettingsAssociationServiceInterface, - @inject(TYPES.UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, - @inject(TYPES.Timer) private timer: TimerInterface, - @inject(TYPES.VALET_TOKEN_TTL) private valetTokenTTL: number, + @inject(TYPES.Auth_UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, + @inject(TYPES.Auth_VALET_TOKEN_TTL) private valetTokenTTL: number, ) {} async execute(dto: CreateValetTokenDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/DeclineSharedSubscriptionInvitation/DeclineSharedSubscriptionInvitation.ts b/packages/auth/src/Domain/UseCase/DeclineSharedSubscriptionInvitation/DeclineSharedSubscriptionInvitation.ts index fe734b390..662e6ff16 100644 --- a/packages/auth/src/Domain/UseCase/DeclineSharedSubscriptionInvitation/DeclineSharedSubscriptionInvitation.ts +++ b/packages/auth/src/Domain/UseCase/DeclineSharedSubscriptionInvitation/DeclineSharedSubscriptionInvitation.ts @@ -12,9 +12,9 @@ import { DeclineSharedSubscriptionInvitationResponse } from './DeclineSharedSubs @injectable() export class DeclineSharedSubscriptionInvitation implements UseCaseInterface { constructor( - @inject(TYPES.SharedSubscriptionInvitationRepository) + @inject(TYPES.Auth_SharedSubscriptionInvitationRepository) private sharedSubscriptionInvitationRepository: SharedSubscriptionInvitationRepositoryInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async execute(dto: DeclineSharedSubscriptionInvitationDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/DeleteAccount/DeleteAccount.ts b/packages/auth/src/Domain/UseCase/DeleteAccount/DeleteAccount.ts index e160ee00f..118148980 100644 --- a/packages/auth/src/Domain/UseCase/DeleteAccount/DeleteAccount.ts +++ b/packages/auth/src/Domain/UseCase/DeleteAccount/DeleteAccount.ts @@ -15,11 +15,11 @@ import { DeleteAccountResponse } from './DeleteAccountResponse' @injectable() export class DeleteAccount implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async execute(dto: DeleteAccountDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/DeletePreviousSessionsForUser.ts b/packages/auth/src/Domain/UseCase/DeletePreviousSessionsForUser.ts index 7fc3201ba..43acf6c04 100644 --- a/packages/auth/src/Domain/UseCase/DeletePreviousSessionsForUser.ts +++ b/packages/auth/src/Domain/UseCase/DeletePreviousSessionsForUser.ts @@ -10,8 +10,8 @@ import { UseCaseInterface } from './UseCaseInterface' @injectable() export class DeletePreviousSessionsForUser implements UseCaseInterface { constructor( - @inject(TYPES.SessionRepository) private sessionRepository: SessionRepositoryInterface, - @inject(TYPES.SessionService) private sessionService: SessionServiceInterface, + @inject(TYPES.Auth_SessionRepository) private sessionRepository: SessionRepositoryInterface, + @inject(TYPES.Auth_SessionService) private sessionService: SessionServiceInterface, ) {} async execute(dto: DeletePreviousSessionsForUserDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/DeleteSessionForUser.ts b/packages/auth/src/Domain/UseCase/DeleteSessionForUser.ts index f568999bc..563bbc623 100644 --- a/packages/auth/src/Domain/UseCase/DeleteSessionForUser.ts +++ b/packages/auth/src/Domain/UseCase/DeleteSessionForUser.ts @@ -12,9 +12,10 @@ import { UseCaseInterface } from './UseCaseInterface' @injectable() export class DeleteSessionForUser implements UseCaseInterface { constructor( - @inject(TYPES.SessionRepository) private sessionRepository: SessionRepositoryInterface, - @inject(TYPES.EphemeralSessionRepository) private ephemeralSessionRepository: EphemeralSessionRepositoryInterface, - @inject(TYPES.SessionService) private sessionService: SessionServiceInterface, + @inject(TYPES.Auth_SessionRepository) private sessionRepository: SessionRepositoryInterface, + @inject(TYPES.Auth_EphemeralSessionRepository) + private ephemeralSessionRepository: EphemeralSessionRepositoryInterface, + @inject(TYPES.Auth_SessionService) private sessionService: SessionServiceInterface, ) {} async execute(dto: DeleteSessionForUserDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/DeleteSetting/DeleteSetting.ts b/packages/auth/src/Domain/UseCase/DeleteSetting/DeleteSetting.ts index 80770e25e..3f65744e8 100644 --- a/packages/auth/src/Domain/UseCase/DeleteSetting/DeleteSetting.ts +++ b/packages/auth/src/Domain/UseCase/DeleteSetting/DeleteSetting.ts @@ -10,8 +10,8 @@ import { Setting } from '../../Setting/Setting' @injectable() export class DeleteSetting implements UseCaseInterface { constructor( - @inject(TYPES.SettingRepository) private settingRepository: SettingRepositoryInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_SettingRepository) private settingRepository: SettingRepositoryInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async execute(dto: DeleteSettingDto): Promise { diff --git a/packages/auth/src/Domain/UseCase/GetActiveSessionsForUser.ts b/packages/auth/src/Domain/UseCase/GetActiveSessionsForUser.ts index 6986db68e..8647a2c86 100644 --- a/packages/auth/src/Domain/UseCase/GetActiveSessionsForUser.ts +++ b/packages/auth/src/Domain/UseCase/GetActiveSessionsForUser.ts @@ -9,8 +9,9 @@ import { UseCaseInterface } from './UseCaseInterface' @injectable() export class GetActiveSessionsForUser implements UseCaseInterface { constructor( - @inject(TYPES.SessionRepository) private sessionRepository: SessionRepositoryInterface, - @inject(TYPES.EphemeralSessionRepository) private ephemeralSessionRepository: EphemeralSessionRepositoryInterface, + @inject(TYPES.Auth_SessionRepository) private sessionRepository: SessionRepositoryInterface, + @inject(TYPES.Auth_EphemeralSessionRepository) + private ephemeralSessionRepository: EphemeralSessionRepositoryInterface, ) {} async execute(dto: GetActiveSessionsForUserDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/GetSetting/GetSetting.ts b/packages/auth/src/Domain/UseCase/GetSetting/GetSetting.ts index 6957aa7fe..e606b87a4 100644 --- a/packages/auth/src/Domain/UseCase/GetSetting/GetSetting.ts +++ b/packages/auth/src/Domain/UseCase/GetSetting/GetSetting.ts @@ -16,11 +16,12 @@ import { UserSubscription } from '../../Subscription/UserSubscription' @injectable() export class GetSetting implements UseCaseInterface { constructor( - @inject(TYPES.SettingProjector) private settingProjector: SettingProjector, - @inject(TYPES.SubscriptionSettingProjector) private subscriptionSettingProjector: SubscriptionSettingProjector, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, - @inject(TYPES.UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, + @inject(TYPES.Auth_SettingProjector) private settingProjector: SettingProjector, + @inject(TYPES.Auth_SubscriptionSettingProjector) private subscriptionSettingProjector: SubscriptionSettingProjector, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_SubscriptionSettingService) + private subscriptionSettingService: SubscriptionSettingServiceInterface, + @inject(TYPES.Auth_UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, ) {} async execute(dto: GetSettingDto): Promise { diff --git a/packages/auth/src/Domain/UseCase/GetSettings/GetSettings.ts b/packages/auth/src/Domain/UseCase/GetSettings/GetSettings.ts index 0506de565..1fafe7644 100644 --- a/packages/auth/src/Domain/UseCase/GetSettings/GetSettings.ts +++ b/packages/auth/src/Domain/UseCase/GetSettings/GetSettings.ts @@ -19,14 +19,14 @@ import { SubscriptionSettingProjector } from '../../../Projection/SubscriptionSe @injectable() export class GetSettings implements UseCaseInterface { constructor( - @inject(TYPES.SettingRepository) private settingRepository: SettingRepositoryInterface, - @inject(TYPES.SubscriptionSettingRepository) + @inject(TYPES.Auth_SettingRepository) private settingRepository: SettingRepositoryInterface, + @inject(TYPES.Auth_SubscriptionSettingRepository) private subscriptionSettingRepository: SubscriptionSettingRepositoryInterface, - @inject(TYPES.UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, - @inject(TYPES.SettingProjector) private settingProjector: SettingProjector, - @inject(TYPES.SubscriptionSettingProjector) private subscriptionSettingProjector: SubscriptionSettingProjector, - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.Crypter) private crypter: CrypterInterface, + @inject(TYPES.Auth_UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, + @inject(TYPES.Auth_SettingProjector) private settingProjector: SettingProjector, + @inject(TYPES.Auth_SubscriptionSettingProjector) private subscriptionSettingProjector: SubscriptionSettingProjector, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_Crypter) private crypter: CrypterInterface, ) {} async execute(dto: GetSettingsDto): Promise { diff --git a/packages/auth/src/Domain/UseCase/GetUserFeatures/GetUserFeatures.ts b/packages/auth/src/Domain/UseCase/GetUserFeatures/GetUserFeatures.ts index a335ec686..7e5b58958 100644 --- a/packages/auth/src/Domain/UseCase/GetUserFeatures/GetUserFeatures.ts +++ b/packages/auth/src/Domain/UseCase/GetUserFeatures/GetUserFeatures.ts @@ -9,8 +9,8 @@ import { FeatureServiceInterface } from '../../Feature/FeatureServiceInterface' @injectable() export class GetUserFeatures implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.FeatureService) private featureService: FeatureServiceInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_FeatureService) private featureService: FeatureServiceInterface, ) {} async execute(dto: GetUserFeaturesDto): Promise { diff --git a/packages/auth/src/Domain/UseCase/GetUserKeyParams/GetUserKeyParams.ts b/packages/auth/src/Domain/UseCase/GetUserKeyParams/GetUserKeyParams.ts index 812d6e452..d6e0a5472 100644 --- a/packages/auth/src/Domain/UseCase/GetUserKeyParams/GetUserKeyParams.ts +++ b/packages/auth/src/Domain/UseCase/GetUserKeyParams/GetUserKeyParams.ts @@ -15,10 +15,10 @@ import { Username } from '@standardnotes/domain-core' @injectable() export class GetUserKeyParams implements UseCaseInterface { constructor( - @inject(TYPES.KeyParamsFactory) private keyParamsFactory: KeyParamsFactoryInterface, - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.PKCERepository) private pkceRepository: PKCERepositoryInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_KeyParamsFactory) private keyParamsFactory: KeyParamsFactoryInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_PKCERepository) private pkceRepository: PKCERepositoryInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: GetUserKeyParamsDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/GetUserOfflineSubscription/GetUserOfflineSubscription.ts b/packages/auth/src/Domain/UseCase/GetUserOfflineSubscription/GetUserOfflineSubscription.ts index 49e2c8b87..6307321d7 100644 --- a/packages/auth/src/Domain/UseCase/GetUserOfflineSubscription/GetUserOfflineSubscription.ts +++ b/packages/auth/src/Domain/UseCase/GetUserOfflineSubscription/GetUserOfflineSubscription.ts @@ -8,7 +8,7 @@ import { OfflineUserSubscriptionRepositoryInterface } from '../../Subscription/O @injectable() export class GetUserOfflineSubscription implements UseCaseInterface { constructor( - @inject(TYPES.OfflineUserSubscriptionRepository) + @inject(TYPES.Auth_OfflineUserSubscriptionRepository) private offlineUserSubscriptionRepository: OfflineUserSubscriptionRepositoryInterface, ) {} diff --git a/packages/auth/src/Domain/UseCase/GetUserSubscription/GetUserSubscription.ts b/packages/auth/src/Domain/UseCase/GetUserSubscription/GetUserSubscription.ts index bbed915d7..f2213186c 100644 --- a/packages/auth/src/Domain/UseCase/GetUserSubscription/GetUserSubscription.ts +++ b/packages/auth/src/Domain/UseCase/GetUserSubscription/GetUserSubscription.ts @@ -9,8 +9,9 @@ import { UserSubscriptionRepositoryInterface } from '../../Subscription/UserSubs @injectable() export class GetUserSubscription implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, ) {} async execute(dto: GetUserSubscriptionDto): Promise { diff --git a/packages/auth/src/Domain/UseCase/IncreaseLoginAttempts.ts b/packages/auth/src/Domain/UseCase/IncreaseLoginAttempts.ts index 516d5ae37..51431b255 100644 --- a/packages/auth/src/Domain/UseCase/IncreaseLoginAttempts.ts +++ b/packages/auth/src/Domain/UseCase/IncreaseLoginAttempts.ts @@ -11,10 +11,10 @@ import { UseCaseInterface } from './UseCaseInterface' @injectable() export class IncreaseLoginAttempts implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.LockRepository) private lockRepository: LockRepositoryInterface, - @inject(TYPES.MAX_LOGIN_ATTEMPTS) private maxLoginAttempts: number, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_LockRepository) private lockRepository: LockRepositoryInterface, + @inject(TYPES.Auth_MAX_LOGIN_ATTEMPTS) private maxLoginAttempts: number, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: IncreaseLoginAttemptsDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/InviteToSharedSubscription/InviteToSharedSubscription.ts b/packages/auth/src/Domain/UseCase/InviteToSharedSubscription/InviteToSharedSubscription.ts index 1a9fb88b2..4c7d2e7f8 100644 --- a/packages/auth/src/Domain/UseCase/InviteToSharedSubscription/InviteToSharedSubscription.ts +++ b/packages/auth/src/Domain/UseCase/InviteToSharedSubscription/InviteToSharedSubscription.ts @@ -22,12 +22,13 @@ import { InviteToSharedSubscriptionResult } from './InviteToSharedSubscriptionRe export class InviteToSharedSubscription implements UseCaseInterface { private readonly MAX_NUMBER_OF_INVITES = 5 constructor( - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.Timer) private timer: TimerInterface, - @inject(TYPES.SharedSubscriptionInvitationRepository) + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, + @inject(TYPES.Auth_SharedSubscriptionInvitationRepository) private sharedSubscriptionInvitationRepository: SharedSubscriptionInvitationRepositoryInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, ) {} async execute(dto: InviteToSharedSubscriptionDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/ListSharedSubscriptionInvitations/ListSharedSubscriptionInvitations.ts b/packages/auth/src/Domain/UseCase/ListSharedSubscriptionInvitations/ListSharedSubscriptionInvitations.ts index 355c8efe4..c83f1a652 100644 --- a/packages/auth/src/Domain/UseCase/ListSharedSubscriptionInvitations/ListSharedSubscriptionInvitations.ts +++ b/packages/auth/src/Domain/UseCase/ListSharedSubscriptionInvitations/ListSharedSubscriptionInvitations.ts @@ -9,7 +9,7 @@ import { ListSharedSubscriptionInvitationsResponse } from './ListSharedSubscript @injectable() export class ListSharedSubscriptionInvitations implements UseCaseInterface { constructor( - @inject(TYPES.SharedSubscriptionInvitationRepository) + @inject(TYPES.Auth_SharedSubscriptionInvitationRepository) private sharedSubscriptionInvitationRepository: SharedSubscriptionInvitationRepositoryInterface, ) {} diff --git a/packages/auth/src/Domain/UseCase/ProcessUserRequest/ProcessUserRequest.ts b/packages/auth/src/Domain/UseCase/ProcessUserRequest/ProcessUserRequest.ts index 1d2acd627..30b5c355f 100644 --- a/packages/auth/src/Domain/UseCase/ProcessUserRequest/ProcessUserRequest.ts +++ b/packages/auth/src/Domain/UseCase/ProcessUserRequest/ProcessUserRequest.ts @@ -13,9 +13,10 @@ import { ProcessUserRequestResponse } from './ProcessUserRequestResponse' @injectable() export class ProcessUserRequest implements UseCaseInterface { constructor( - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, ) {} async execute(dto: ProcessUserRequestDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/RefreshSessionToken.ts b/packages/auth/src/Domain/UseCase/RefreshSessionToken.ts index 372362c5a..95ca334ce 100644 --- a/packages/auth/src/Domain/UseCase/RefreshSessionToken.ts +++ b/packages/auth/src/Domain/UseCase/RefreshSessionToken.ts @@ -13,11 +13,11 @@ import { RefreshSessionTokenDTO } from './RefreshSessionTokenDTO' @injectable() export class RefreshSessionToken { constructor( - @inject(TYPES.SessionService) private sessionService: SessionServiceInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.Timer) private timer: TimerInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_SessionService) private sessionService: SessionServiceInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: RefreshSessionTokenDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/Register.ts b/packages/auth/src/Domain/UseCase/Register.ts index 639198108..0ae91512f 100644 --- a/packages/auth/src/Domain/UseCase/Register.ts +++ b/packages/auth/src/Domain/UseCase/Register.ts @@ -20,13 +20,13 @@ import { AuthResponse20200115 } from '../Auth/AuthResponse20200115' @injectable() export class Register implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.RoleRepository) private roleRepository: RoleRepositoryInterface, - @inject(TYPES.AuthResponseFactory20200115) private authResponseFactory20200115: AuthResponseFactory20200115, - @inject(TYPES.Crypter) private crypter: CrypterInterface, - @inject(TYPES.DISABLE_USER_REGISTRATION) private disableUserRegistration: boolean, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_RoleRepository) private roleRepository: RoleRepositoryInterface, + @inject(TYPES.Auth_AuthResponseFactory20200115) private authResponseFactory20200115: AuthResponseFactory20200115, + @inject(TYPES.Auth_Crypter) private crypter: CrypterInterface, + @inject(TYPES.Auth_DISABLE_USER_REGISTRATION) private disableUserRegistration: boolean, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async execute(dto: RegisterDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/SignIn.ts b/packages/auth/src/Domain/UseCase/SignIn.ts index 9a078b0e4..b32219c98 100644 --- a/packages/auth/src/Domain/UseCase/SignIn.ts +++ b/packages/auth/src/Domain/UseCase/SignIn.ts @@ -23,15 +23,15 @@ import { getBody, getSubject } from '../Email/UserSignedIn' @injectable() export class SignIn implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.AuthResponseFactoryResolver) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_AuthResponseFactoryResolver) private authResponseFactoryResolver: AuthResponseFactoryResolverInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.SessionService) private sessionService: SessionServiceInterface, - @inject(TYPES.PKCERepository) private pkceRepository: PKCERepositoryInterface, - @inject(TYPES.Crypter) private crypter: CrypterInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_SessionService) private sessionService: SessionServiceInterface, + @inject(TYPES.Auth_PKCERepository) private pkceRepository: PKCERepositoryInterface, + @inject(TYPES.Auth_Crypter) private crypter: CrypterInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: SignInDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/UpdateSetting/UpdateSetting.ts b/packages/auth/src/Domain/UseCase/UpdateSetting/UpdateSetting.ts index 2a14f22df..098f4ca76 100644 --- a/packages/auth/src/Domain/UseCase/UpdateSetting/UpdateSetting.ts +++ b/packages/auth/src/Domain/UseCase/UpdateSetting/UpdateSetting.ts @@ -20,15 +20,17 @@ import { SubscriptionSettingProjector } from '../../../Projection/SubscriptionSe @injectable() export class UpdateSetting implements UseCaseInterface { constructor( - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.SubscriptionSettingService) private subscriptionSettingService: SubscriptionSettingServiceInterface, - @inject(TYPES.UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, - @inject(TYPES.SettingProjector) private settingProjector: SettingProjector, - @inject(TYPES.SubscriptionSettingProjector) private subscriptionSettingProjector: SubscriptionSettingProjector, - @inject(TYPES.SettingsAssociationService) private settingsAssociationService: SettingsAssociationServiceInterface, - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.RoleService) private roleService: RoleServiceInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_SubscriptionSettingService) + private subscriptionSettingService: SubscriptionSettingServiceInterface, + @inject(TYPES.Auth_UserSubscriptionService) private userSubscriptionService: UserSubscriptionServiceInterface, + @inject(TYPES.Auth_SettingProjector) private settingProjector: SettingProjector, + @inject(TYPES.Auth_SubscriptionSettingProjector) private subscriptionSettingProjector: SubscriptionSettingProjector, + @inject(TYPES.Auth_SettingsAssociationService) + private settingsAssociationService: SettingsAssociationServiceInterface, + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_RoleService) private roleService: RoleServiceInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: UpdateSettingDto): Promise { diff --git a/packages/auth/src/Domain/UseCase/UpdateUser.ts b/packages/auth/src/Domain/UseCase/UpdateUser.ts index 43a40cd03..863081924 100644 --- a/packages/auth/src/Domain/UseCase/UpdateUser.ts +++ b/packages/auth/src/Domain/UseCase/UpdateUser.ts @@ -10,10 +10,10 @@ import { UseCaseInterface } from './UseCaseInterface' @injectable() export class UpdateUser implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.AuthResponseFactoryResolver) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_AuthResponseFactoryResolver) private authResponseFactoryResolver: AuthResponseFactoryResolverInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async execute(dto: UpdateUserDTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/VerifyMFA.ts b/packages/auth/src/Domain/UseCase/VerifyMFA.ts index 911a36b3b..02eaab058 100644 --- a/packages/auth/src/Domain/UseCase/VerifyMFA.ts +++ b/packages/auth/src/Domain/UseCase/VerifyMFA.ts @@ -23,15 +23,15 @@ import { Setting } from '../Setting/Setting' @injectable() export class VerifyMFA implements UseCaseInterface { constructor( - @inject(TYPES.UserRepository) private userRepository: UserRepositoryInterface, - @inject(TYPES.SettingService) private settingService: SettingServiceInterface, - @inject(TYPES.BooleanSelector) private booleanSelector: SelectorInterface, - @inject(TYPES.LockRepository) private lockRepository: LockRepositoryInterface, - @inject(TYPES.PSEUDO_KEY_PARAMS_KEY) private pseudoKeyParamsKey: string, - @inject(TYPES.AuthenticatorRepository) private authenticatorRepository: AuthenticatorRepositoryInterface, - @inject(TYPES.VerifyAuthenticatorAuthenticationResponse) + @inject(TYPES.Auth_UserRepository) private userRepository: UserRepositoryInterface, + @inject(TYPES.Auth_SettingService) private settingService: SettingServiceInterface, + @inject(TYPES.Auth_BooleanSelector) private booleanSelector: SelectorInterface, + @inject(TYPES.Auth_LockRepository) private lockRepository: LockRepositoryInterface, + @inject(TYPES.Auth_PSEUDO_KEY_PARAMS_KEY) private pseudoKeyParamsKey: string, + @inject(TYPES.Auth_AuthenticatorRepository) private authenticatorRepository: AuthenticatorRepositoryInterface, + @inject(TYPES.Auth_VerifyAuthenticatorAuthenticationResponse) private verifyAuthenticatorAuthenticationResponse: DomainUseCaseInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async execute(dto: VerifyMFADTO): Promise { diff --git a/packages/auth/src/Domain/UseCase/VerifyPredicate/VerifyPredicate.ts b/packages/auth/src/Domain/UseCase/VerifyPredicate/VerifyPredicate.ts index b8fea3a58..20035ac34 100644 --- a/packages/auth/src/Domain/UseCase/VerifyPredicate/VerifyPredicate.ts +++ b/packages/auth/src/Domain/UseCase/VerifyPredicate/VerifyPredicate.ts @@ -13,8 +13,9 @@ import { VerifyPredicateResponse } from './VerifyPredicateResponse' @injectable() export class VerifyPredicate implements UseCaseInterface { constructor( - @inject(TYPES.SettingRepository) private settingRepository: SettingRepositoryInterface, - @inject(TYPES.UserSubscriptionRepository) private userSubscriptionRepository: UserSubscriptionRepositoryInterface, + @inject(TYPES.Auth_SettingRepository) private settingRepository: SettingRepositoryInterface, + @inject(TYPES.Auth_UserSubscriptionRepository) + private userSubscriptionRepository: UserSubscriptionRepositoryInterface, ) {} async execute(dto: VerifyPredicateDTO): Promise { diff --git a/packages/auth/src/Domain/User/KeyParamsFactory.ts b/packages/auth/src/Domain/User/KeyParamsFactory.ts index c65f76dbc..a48f5e16e 100644 --- a/packages/auth/src/Domain/User/KeyParamsFactory.ts +++ b/packages/auth/src/Domain/User/KeyParamsFactory.ts @@ -11,8 +11,8 @@ import { SelectorInterface } from '@standardnotes/security' @injectable() export class KeyParamsFactory implements KeyParamsFactoryInterface { constructor( - @inject(TYPES.PSEUDO_KEY_PARAMS_KEY) private pseudoKeyParamsKey: string, - @inject(TYPES.ProtocolVersionSelector) private protocolVersionSelector: SelectorInterface, + @inject(TYPES.Auth_PSEUDO_KEY_PARAMS_KEY) private pseudoKeyParamsKey: string, + @inject(TYPES.Auth_ProtocolVersionSelector) private protocolVersionSelector: SelectorInterface, ) {} createPseudoParams(email: string): KeyParamsData { diff --git a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressAuthController.ts b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressAuthController.ts index 0c9936c87..0cd5edeb6 100644 --- a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressAuthController.ts +++ b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressAuthController.ts @@ -1,5 +1,4 @@ import { Request, Response } from 'express' -import { ErrorTag } from '@standardnotes/responses' import { BaseHttpController, controller, @@ -10,32 +9,42 @@ import { } from 'inversify-express-utils' import TYPES from '../../Bootstrap/Types' -import { SessionServiceInterface } from '../../Domain/Session/SessionServiceInterface' import { SignIn } from '../../Domain/UseCase/SignIn' import { ClearLoginAttempts } from '../../Domain/UseCase/ClearLoginAttempts' import { VerifyMFA } from '../../Domain/UseCase/VerifyMFA' import { IncreaseLoginAttempts } from '../../Domain/UseCase/IncreaseLoginAttempts' import { Logger } from 'winston' import { GetUserKeyParams } from '../../Domain/UseCase/GetUserKeyParams/GetUserKeyParams' -import { inject } from 'inversify' import { AuthController } from '../../Controller/AuthController' +import { ControllerContainerInterface } from '@standardnotes/domain-core' +import { inject } from 'inversify' @controller('/auth') export class InversifyExpressAuthController extends BaseHttpController { constructor( - @inject(TYPES.SessionService) private sessionService: SessionServiceInterface, - @inject(TYPES.VerifyMFA) private verifyMFA: VerifyMFA, - @inject(TYPES.SignIn) private signInUseCase: SignIn, - @inject(TYPES.GetUserKeyParams) private getUserKeyParams: GetUserKeyParams, - @inject(TYPES.ClearLoginAttempts) private clearLoginAttempts: ClearLoginAttempts, - @inject(TYPES.IncreaseLoginAttempts) private increaseLoginAttempts: IncreaseLoginAttempts, - @inject(TYPES.Logger) private logger: Logger, - @inject(TYPES.AuthController) private authController: AuthController, + @inject(TYPES.Auth_VerifyMFA) private verifyMFA: VerifyMFA, + @inject(TYPES.Auth_SignIn) private signInUseCase: SignIn, + @inject(TYPES.Auth_GetUserKeyParams) private getUserKeyParams: GetUserKeyParams, + @inject(TYPES.Auth_ClearLoginAttempts) private clearLoginAttempts: ClearLoginAttempts, + @inject(TYPES.Auth_IncreaseLoginAttempts) private increaseLoginAttempts: IncreaseLoginAttempts, + @inject(TYPES.Auth_Logger) private logger: Logger, + @inject(TYPES.Auth_AuthController) private authController: AuthController, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('auth.params', this.params.bind(this)) + this.controllerContainer.register('auth.signIn', this.signIn.bind(this)) + this.controllerContainer.register('auth.pkceParams', this.pkceParams.bind(this)) + this.controllerContainer.register('auth.pkceSignIn', this.pkceSignIn.bind(this)) + this.controllerContainer.register('auth.users.register', this.register.bind(this)) + this.controllerContainer.register('auth.generateRecoveryCodes', this.generateRecoveryCodes.bind(this)) + this.controllerContainer.register('auth.signInWithRecoveryCodes', this.recoveryLogin.bind(this)) + this.controllerContainer.register('auth.recoveryKeyParams', this.recoveryParams.bind(this)) + this.controllerContainer.register('auth.signOut', this.signOut.bind(this)) } - @httpGet('/params', TYPES.AuthMiddlewareWithoutResponse) + @httpGet('/params', TYPES.Auth_AuthMiddlewareWithoutResponse) async params(request: Request, response: Response): Promise { if (response.locals.session) { const result = await this.getUserKeyParams.execute({ @@ -85,7 +94,7 @@ export class InversifyExpressAuthController extends BaseHttpController { return this.json(result.keyParams) } - @httpPost('/sign_in', TYPES.LockMiddleware) + @httpPost('/sign_in', TYPES.Auth_LockMiddleware) async signIn(request: Request): Promise { if (!request.body.email || !request.body.password) { this.logger.debug('/auth/sign_in request missing credentials: %O', request.body) @@ -146,7 +155,7 @@ export class InversifyExpressAuthController extends BaseHttpController { return this.json(signInResult.authResponse) } - @httpPost('/pkce_params', TYPES.AuthMiddlewareWithoutResponse) + @httpPost('/pkce_params', TYPES.Auth_AuthMiddlewareWithoutResponse) async pkceParams(request: Request, response: Response): Promise { if (!request.body.code_challenge) { return this.json( @@ -209,7 +218,7 @@ export class InversifyExpressAuthController extends BaseHttpController { return this.json(result.keyParams) } - @httpPost('/pkce_sign_in', TYPES.LockMiddleware) + @httpPost('/pkce_sign_in', TYPES.Auth_LockMiddleware) async pkceSignIn(request: Request): Promise { if (!request.body.email || !request.body.password || !request.body.code_verifier) { this.logger.debug('/auth/sign_in request missing credentials: %O', request.body) @@ -252,7 +261,7 @@ export class InversifyExpressAuthController extends BaseHttpController { return this.json(signInResult.authResponse) } - @httpPost('/recovery/codes', TYPES.ApiGatewayAuthMiddleware) + @httpPost('/recovery/codes', TYPES.Auth_ApiGatewayAuthMiddleware) async generateRecoveryCodes(_request: Request, response: Response): Promise { const result = await this.authController.generateRecoveryCodes({ userUuid: response.locals.user.uuid, @@ -261,7 +270,7 @@ export class InversifyExpressAuthController extends BaseHttpController { return this.json(result.data, result.status) } - @httpPost('/recovery/login', TYPES.LockMiddleware) + @httpPost('/recovery/login', TYPES.Auth_LockMiddleware) async recoveryLogin(request: Request): Promise { const result = await this.authController.signInWithRecoveryCodes({ apiVersion: request.body.api_version, @@ -287,28 +296,14 @@ export class InversifyExpressAuthController extends BaseHttpController { return this.json(result.data, result.status) } - @httpPost('/sign_out', TYPES.AuthMiddlewareWithoutResponse) + @httpPost('/sign_out', TYPES.Auth_AuthMiddlewareWithoutResponse) async signOut(request: Request, response: Response): Promise { - if (response.locals.readOnlyAccess) { - return this.json( - { - error: { - tag: ErrorTag.ReadOnlyAccess, - message: 'Session has read-only access.', - }, - }, - 401, - ) - } + const result = await this.authController.signOut({ + readOnlyAccess: response.locals.readOnlyAccess, + authorizationHeader: request.headers.authorization, + }) - const authorizationHeader = request.headers.authorization - - const userUuid = await this.sessionService.deleteSessionByToken(authorizationHeader.replace('Bearer ', '')) - - if (userUuid !== null) { - response.setHeader('x-invalidate-cache', userUuid) - } - response.status(204).send() + return this.json(result.data, result.status) } @httpPost('/') diff --git a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressAuthenticatorsController.ts b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressAuthenticatorsController.ts index 5af70e1a1..670da6643 100644 --- a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressAuthenticatorsController.ts +++ b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressAuthenticatorsController.ts @@ -1,5 +1,4 @@ import { Request, Response } from 'express' -import { inject } from 'inversify' import { BaseHttpController, controller, @@ -11,14 +10,34 @@ import { } from 'inversify-express-utils' import TYPES from '../../Bootstrap/Types' import { AuthenticatorsController } from '../../Controller/AuthenticatorsController' +import { ControllerContainerInterface } from '@standardnotes/domain-core' +import { inject } from 'inversify' @controller('/authenticators') export class InversifyExpressAuthenticatorsController extends BaseHttpController { - constructor(@inject(TYPES.AuthenticatorsController) private authenticatorsController: AuthenticatorsController) { + constructor( + @inject(TYPES.Auth_AuthenticatorsController) private authenticatorsController: AuthenticatorsController, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, + ) { super() + + this.controllerContainer.register('auth.authenticators.list', this.list.bind(this)) + this.controllerContainer.register('auth.authenticators.delete', this.delete.bind(this)) + this.controllerContainer.register( + 'auth.authenticators.generateRegistrationOptions', + this.generateRegistrationOptions.bind(this), + ) + this.controllerContainer.register( + 'auth.authenticators.verifyRegistrationResponse', + this.verifyRegistration.bind(this), + ) + this.controllerContainer.register( + 'auth.authenticators.generateAuthenticationOptions', + this.generateAuthenticationOptions.bind(this), + ) } - @httpGet('/', TYPES.ApiGatewayAuthMiddleware) + @httpGet('/', TYPES.Auth_ApiGatewayAuthMiddleware) async list(_request: Request, response: Response): Promise { const result = await this.authenticatorsController.list({ userUuid: response.locals.user.uuid, @@ -27,7 +46,7 @@ export class InversifyExpressAuthenticatorsController extends BaseHttpController return this.json(result.data, result.status) } - @httpDelete('/:authenticatorId', TYPES.ApiGatewayAuthMiddleware) + @httpDelete('/:authenticatorId', TYPES.Auth_ApiGatewayAuthMiddleware) async delete(request: Request, response: Response): Promise { const result = await this.authenticatorsController.delete({ userUuid: response.locals.user.uuid, @@ -37,7 +56,7 @@ export class InversifyExpressAuthenticatorsController extends BaseHttpController return this.json(result.data, result.status) } - @httpGet('/generate-registration-options', TYPES.ApiGatewayAuthMiddleware) + @httpGet('/generate-registration-options', TYPES.Auth_ApiGatewayAuthMiddleware) async generateRegistrationOptions(_request: Request, response: Response): Promise { const result = await this.authenticatorsController.generateRegistrationOptions({ username: response.locals.user.email, @@ -47,7 +66,7 @@ export class InversifyExpressAuthenticatorsController extends BaseHttpController return this.json(result.data, result.status) } - @httpPost('/verify-registration', TYPES.ApiGatewayAuthMiddleware) + @httpPost('/verify-registration', TYPES.Auth_ApiGatewayAuthMiddleware) async verifyRegistration(request: Request, response: Response): Promise { const result = await this.authenticatorsController.verifyRegistrationResponse({ userUuid: response.locals.user.uuid, diff --git a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressSubscriptionInvitesController.ts b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressSubscriptionInvitesController.ts index 3330fb195..8cedf2b74 100644 --- a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressSubscriptionInvitesController.ts +++ b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressSubscriptionInvitesController.ts @@ -1,7 +1,6 @@ import { ApiVersion } from '@standardnotes/api' import { Role } from '@standardnotes/security' import { Request, Response } from 'express' -import { inject } from 'inversify' import { BaseHttpController, controller, @@ -13,16 +12,26 @@ import { } from 'inversify-express-utils' import TYPES from '../../Bootstrap/Types' import { SubscriptionInvitesController } from '../../Controller/SubscriptionInvitesController' +import { ControllerContainerInterface } from '@standardnotes/domain-core' +import { inject } from 'inversify' @controller('/subscription-invites') export class InversifyExpressSubscriptionInvitesController extends BaseHttpController { constructor( - @inject(TYPES.SubscriptionInvitesController) private subscriptionInvitesController: SubscriptionInvitesController, + @inject(TYPES.Auth_SubscriptionInvitesController) + private subscriptionInvitesController: SubscriptionInvitesController, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('auth.subscriptionInvites.accept', this.acceptInvite.bind(this)) + this.controllerContainer.register('auth.subscriptionInvites.declineInvite', this.declineInvite.bind(this)) + this.controllerContainer.register('auth.subscriptionInvites.create', this.inviteToSubscriptionSharing.bind(this)) + this.controllerContainer.register('auth.subscriptionInvites.delete', this.cancelSubscriptionSharing.bind(this)) + this.controllerContainer.register('auth.subscriptionInvites.list', this.listInvites.bind(this)) } - @httpPost('/:inviteUuid/accept', TYPES.ApiGatewayAuthMiddleware) + @httpPost('/:inviteUuid/accept', TYPES.Auth_ApiGatewayAuthMiddleware) async acceptInvite(request: Request, response: Response): Promise { const result = await this.subscriptionInvitesController.acceptInvite({ api: request.query.api as ApiVersion, @@ -43,7 +52,7 @@ export class InversifyExpressSubscriptionInvitesController extends BaseHttpContr return this.json(response.data, response.status) } - @httpPost('/', TYPES.ApiGatewayAuthMiddleware) + @httpPost('/', TYPES.Auth_ApiGatewayAuthMiddleware) async inviteToSubscriptionSharing(request: Request, response: Response): Promise { const result = await this.subscriptionInvitesController.invite({ ...request.body, @@ -55,7 +64,7 @@ export class InversifyExpressSubscriptionInvitesController extends BaseHttpContr return this.json(result.data, result.status) } - @httpDelete('/:inviteUuid', TYPES.ApiGatewayAuthMiddleware) + @httpDelete('/:inviteUuid', TYPES.Auth_ApiGatewayAuthMiddleware) async cancelSubscriptionSharing(request: Request, response: Response): Promise { const result = await this.subscriptionInvitesController.cancelInvite({ ...request.body, @@ -66,7 +75,7 @@ export class InversifyExpressSubscriptionInvitesController extends BaseHttpContr return this.json(result.data, result.status) } - @httpGet('/', TYPES.ApiGatewayAuthMiddleware) + @httpGet('/', TYPES.Auth_ApiGatewayAuthMiddleware) async listInvites(request: Request, response: Response): Promise { const result = await this.subscriptionInvitesController.listInvites({ ...request.body, diff --git a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressUserRequestsController.ts b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressUserRequestsController.ts index cc3f5aaf9..95d6e1595 100644 --- a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressUserRequestsController.ts +++ b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressUserRequestsController.ts @@ -1,17 +1,23 @@ import { Request, Response } from 'express' -import { inject } from 'inversify' -import { controller, BaseHttpController, results, httpPost } from 'inversify-express-utils' +import { BaseHttpController, results, httpPost, controller } from 'inversify-express-utils' import TYPES from '../../Bootstrap/Types' import { UserRequestsController } from '../../Controller/UserRequestsController' +import { ControllerContainerInterface } from '@standardnotes/domain-core' +import { inject } from 'inversify' @controller('/users/:userUuid/requests') export class InversifyExpressUserRequestsController extends BaseHttpController { - constructor(@inject(TYPES.UserRequestsController) private userRequestsController: UserRequestsController) { + constructor( + @inject(TYPES.Auth_UserRequestsController) private userRequestsController: UserRequestsController, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, + ) { super() + + this.controllerContainer.register('auth.users.createRequest', this.submitRequest.bind(this)) } - @httpPost('/', TYPES.ApiGatewayAuthMiddleware) + @httpPost('/', TYPES.Auth_ApiGatewayAuthMiddleware) async submitRequest(request: Request, response: Response): Promise { const result = await this.userRequestsController.submitUserRequest({ requestType: request.body.requestType, diff --git a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressWebSocketsController.ts b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressWebSocketsController.ts index c976c5707..3ca18bb5f 100644 --- a/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressWebSocketsController.ts +++ b/packages/auth/src/Infra/InversifyExpressUtils/InversifyExpressWebSocketsController.ts @@ -1,7 +1,6 @@ import { ErrorTag } from '@standardnotes/responses' import { TokenDecoderInterface, WebSocketConnectionTokenData } from '@standardnotes/security' import { Request } from 'express' -import { inject } from 'inversify' import { BaseHttpController, controller, @@ -9,17 +8,22 @@ import { // eslint-disable-next-line @typescript-eslint/no-unused-vars results, } from 'inversify-express-utils' -import TYPES from '../../Bootstrap/Types' import { CreateCrossServiceToken } from '../../Domain/UseCase/CreateCrossServiceToken/CreateCrossServiceToken' +import { ControllerContainerInterface } from '@standardnotes/domain-core' +import { inject } from 'inversify' +import TYPES from '../../Bootstrap/Types' @controller('/sockets') export class InversifyExpressWebSocketsController extends BaseHttpController { constructor( - @inject(TYPES.CreateCrossServiceToken) private createCrossServiceToken: CreateCrossServiceToken, - @inject(TYPES.WebSocketConnectionTokenDecoder) + @inject(TYPES.Auth_CreateCrossServiceToken) private createCrossServiceToken: CreateCrossServiceToken, + @inject(TYPES.Auth_WebSocketConnectionTokenDecoder) private tokenDecoder: TokenDecoderInterface, + @inject(TYPES.Auth_ControllerContainer) private controllerContainer: ControllerContainerInterface, ) { super() + + this.controllerContainer.register('auth.webSockets.validateToken', this.validateToken.bind(this)) } @httpPost('/tokens/validate') diff --git a/packages/auth/src/Infra/Redis/LockRepository.ts b/packages/auth/src/Infra/Redis/LockRepository.ts index ae19da51b..7807b5642 100644 --- a/packages/auth/src/Infra/Redis/LockRepository.ts +++ b/packages/auth/src/Infra/Redis/LockRepository.ts @@ -10,9 +10,9 @@ export class LockRepository implements LockRepositoryInterface { private readonly OTP_PREFIX = 'otp-lock' constructor( - @inject(TYPES.Redis) private redisClient: IORedis.Redis, - @inject(TYPES.MAX_LOGIN_ATTEMPTS) private maxLoginAttempts: number, - @inject(TYPES.FAILED_LOGIN_LOCKOUT) private failedLoginLockout: number, + @inject(TYPES.Auth_Redis) private redisClient: IORedis.Redis, + @inject(TYPES.Auth_MAX_LOGIN_ATTEMPTS) private maxLoginAttempts: number, + @inject(TYPES.Auth_FAILED_LOGIN_LOCKOUT) private failedLoginLockout: number, ) {} async lockSuccessfullOTP(userIdentifier: string, otp: string): Promise { diff --git a/packages/auth/src/Infra/Redis/RedisEphemeralSessionRepository.ts b/packages/auth/src/Infra/Redis/RedisEphemeralSessionRepository.ts index 915de352f..22ea0176c 100644 --- a/packages/auth/src/Infra/Redis/RedisEphemeralSessionRepository.ts +++ b/packages/auth/src/Infra/Redis/RedisEphemeralSessionRepository.ts @@ -11,8 +11,8 @@ export class RedisEphemeralSessionRepository implements EphemeralSessionReposito private readonly USER_SESSIONS_PREFIX = 'user-sessions' constructor( - @inject(TYPES.Redis) private redisClient: IORedis.Redis, - @inject(TYPES.EPHEMERAL_SESSION_AGE) private ephemeralSessionAge: number, + @inject(TYPES.Auth_Redis) private redisClient: IORedis.Redis, + @inject(TYPES.Auth_EPHEMERAL_SESSION_AGE) private ephemeralSessionAge: number, ) {} async deleteOne(uuid: string, userUuid: string): Promise { diff --git a/packages/auth/src/Infra/Redis/RedisOfflineSubscriptionTokenRepository.ts b/packages/auth/src/Infra/Redis/RedisOfflineSubscriptionTokenRepository.ts index 44c5fef4c..89a232b6d 100644 --- a/packages/auth/src/Infra/Redis/RedisOfflineSubscriptionTokenRepository.ts +++ b/packages/auth/src/Infra/Redis/RedisOfflineSubscriptionTokenRepository.ts @@ -12,9 +12,9 @@ export class RedisOfflineSubscriptionTokenRepository implements OfflineSubscript private readonly PREFIX = 'offline-subscription-token' constructor( - @inject(TYPES.Redis) private redisClient: IORedis.Redis, - @inject(TYPES.Timer) private timer: TimerInterface, - @inject(TYPES.Logger) private logger: Logger, + @inject(TYPES.Auth_Redis) private redisClient: IORedis.Redis, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Logger) private logger: Logger, ) {} async getUserEmailByToken(token: string): Promise { diff --git a/packages/auth/src/Infra/Redis/RedisPKCERepository.ts b/packages/auth/src/Infra/Redis/RedisPKCERepository.ts index b808a7072..5666c434c 100644 --- a/packages/auth/src/Infra/Redis/RedisPKCERepository.ts +++ b/packages/auth/src/Infra/Redis/RedisPKCERepository.ts @@ -9,7 +9,10 @@ import { PKCERepositoryInterface } from '../../Domain/User/PKCERepositoryInterfa export class RedisPKCERepository implements PKCERepositoryInterface { private readonly PREFIX = 'pkce' - constructor(@inject(TYPES.Redis) private redisClient: IORedis.Redis, @inject(TYPES.Logger) private logger: Logger) {} + constructor( + @inject(TYPES.Auth_Redis) private redisClient: IORedis.Redis, + @inject(TYPES.Auth_Logger) private logger: Logger, + ) {} async storeCodeChallenge(codeChallenge: string): Promise { this.logger.debug(`Storing code challenge: ${codeChallenge}`) diff --git a/packages/auth/src/Infra/Redis/RedisSubscriptionTokenRepository.ts b/packages/auth/src/Infra/Redis/RedisSubscriptionTokenRepository.ts index a578edca7..54947ce03 100644 --- a/packages/auth/src/Infra/Redis/RedisSubscriptionTokenRepository.ts +++ b/packages/auth/src/Infra/Redis/RedisSubscriptionTokenRepository.ts @@ -11,8 +11,8 @@ export class RedisSubscriptionTokenRepository implements SubscriptionTokenReposi private readonly PREFIX = 'subscription-token' constructor( - @inject(TYPES.Redis) private redisClient: IORedis.Redis, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Redis) private redisClient: IORedis.Redis, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async getUserUuidByToken(token: string): Promise { diff --git a/packages/auth/src/Infra/TypeORM/TypeORMOfflineSettingRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMOfflineSettingRepository.ts index c48d64956..b8b262900 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMOfflineSettingRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMOfflineSettingRepository.ts @@ -8,7 +8,7 @@ import { OfflineSettingRepositoryInterface } from '../../Domain/Setting/OfflineS @injectable() export class TypeORMOfflineSettingRepository implements OfflineSettingRepositoryInterface { - constructor(@inject(TYPES.ORMOfflineSettingRepository) private ormRepository: Repository) {} + constructor(@inject(TYPES.Auth_ORMOfflineSettingRepository) private ormRepository: Repository) {} async save(offlineSetting: OfflineSetting): Promise { return this.ormRepository.save(offlineSetting) diff --git a/packages/auth/src/Infra/TypeORM/TypeORMOfflineUserSubscriptionRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMOfflineUserSubscriptionRepository.ts index f19504040..3f4545f54 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMOfflineUserSubscriptionRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMOfflineUserSubscriptionRepository.ts @@ -8,7 +8,7 @@ import { OfflineUserSubscriptionRepositoryInterface } from '../../Domain/Subscri @injectable() export class TypeORMOfflineUserSubscriptionRepository implements OfflineUserSubscriptionRepositoryInterface { constructor( - @inject(TYPES.ORMOfflineUserSubscriptionRepository) + @inject(TYPES.Auth_ORMOfflineUserSubscriptionRepository) private ormRepository: Repository, ) {} diff --git a/packages/auth/src/Infra/TypeORM/TypeORMRevokedSessionRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMRevokedSessionRepository.ts index 4eb1813e0..44eec6b41 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMRevokedSessionRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMRevokedSessionRepository.ts @@ -8,7 +8,7 @@ import { RevokedSessionRepositoryInterface } from '../../Domain/Session/RevokedS @injectable() export class TypeORMRevokedSessionRepository implements RevokedSessionRepositoryInterface { constructor( - @inject(TYPES.ORMRevokedSessionRepository) + @inject(TYPES.Auth_ORMRevokedSessionRepository) private ormRepository: Repository, ) {} diff --git a/packages/auth/src/Infra/TypeORM/TypeORMRoleRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMRoleRepository.ts index 726393758..46bee9d4d 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMRoleRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMRoleRepository.ts @@ -8,7 +8,7 @@ import { RoleRepositoryInterface } from '../../Domain/Role/RoleRepositoryInterfa @injectable() export class TypeORMRoleRepository implements RoleRepositoryInterface { constructor( - @inject(TYPES.ORMRoleRepository) + @inject(TYPES.Auth_ORMRoleRepository) private ormRepository: Repository, ) {} diff --git a/packages/auth/src/Infra/TypeORM/TypeORMSessionRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMSessionRepository.ts index 97e7091c3..fea831d83 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMSessionRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMSessionRepository.ts @@ -11,9 +11,9 @@ import { SessionRepositoryInterface } from '../../Domain/Session/SessionReposito @injectable() export class TypeORMSessionRepository implements SessionRepositoryInterface { constructor( - @inject(TYPES.ORMSessionRepository) + @inject(TYPES.Auth_ORMSessionRepository) private ormRepository: Repository, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async save(session: Session): Promise { diff --git a/packages/auth/src/Infra/TypeORM/TypeORMSettingRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMSettingRepository.ts index be0400e7d..97253b83b 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMSettingRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMSettingRepository.ts @@ -10,7 +10,7 @@ import { DeleteSettingDto } from '../../Domain/UseCase/DeleteSetting/DeleteSetti @injectable() export class TypeORMSettingRepository implements SettingRepositoryInterface { constructor( - @inject(TYPES.ORMSettingRepository) + @inject(TYPES.Auth_ORMSettingRepository) private ormRepository: Repository, ) {} diff --git a/packages/auth/src/Infra/TypeORM/TypeORMSharedSubscriptionInvitationRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMSharedSubscriptionInvitationRepository.ts index b8ab1be09..47d1812a4 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMSharedSubscriptionInvitationRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMSharedSubscriptionInvitationRepository.ts @@ -9,7 +9,7 @@ import { SharedSubscriptionInvitationRepositoryInterface } from '../../Domain/Sh @injectable() export class TypeORMSharedSubscriptionInvitationRepository implements SharedSubscriptionInvitationRepositoryInterface { constructor( - @inject(TYPES.ORMSharedSubscriptionInvitationRepository) + @inject(TYPES.Auth_ORMSharedSubscriptionInvitationRepository) private ormRepository: Repository, ) {} diff --git a/packages/auth/src/Infra/TypeORM/TypeORMSubscriptionSettingRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMSubscriptionSettingRepository.ts index fbd962242..053661929 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMSubscriptionSettingRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMSubscriptionSettingRepository.ts @@ -8,7 +8,7 @@ import { SubscriptionSettingRepositoryInterface } from '../../Domain/Setting/Sub @injectable() export class TypeORMSubscriptionSettingRepository implements SubscriptionSettingRepositoryInterface { constructor( - @inject(TYPES.ORMSubscriptionSettingRepository) + @inject(TYPES.Auth_ORMSubscriptionSettingRepository) private ormRepository: Repository, ) {} diff --git a/packages/auth/src/Infra/TypeORM/TypeORMUserRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMUserRepository.ts index 8c3e3e346..c68823d45 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMUserRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMUserRepository.ts @@ -10,7 +10,7 @@ import { UserRepositoryInterface } from '../../Domain/User/UserRepositoryInterfa @injectable() export class TypeORMUserRepository implements UserRepositoryInterface { constructor( - @inject(TYPES.ORMUserRepository) + @inject(TYPES.Auth_ORMUserRepository) private ormRepository: Repository, ) {} diff --git a/packages/auth/src/Infra/TypeORM/TypeORMUserSubscriptionRepository.ts b/packages/auth/src/Infra/TypeORM/TypeORMUserSubscriptionRepository.ts index d1929b277..511475416 100644 --- a/packages/auth/src/Infra/TypeORM/TypeORMUserSubscriptionRepository.ts +++ b/packages/auth/src/Infra/TypeORM/TypeORMUserSubscriptionRepository.ts @@ -10,9 +10,9 @@ import { UserSubscriptionType } from '../../Domain/Subscription/UserSubscription @injectable() export class TypeORMUserSubscriptionRepository implements UserSubscriptionRepositoryInterface { constructor( - @inject(TYPES.ORMUserSubscriptionRepository) + @inject(TYPES.Auth_ORMUserSubscriptionRepository) private ormRepository: Repository, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} async countActiveSubscriptions(): Promise { diff --git a/packages/auth/src/Infra/WebSockets/WebSocketsClientService.ts b/packages/auth/src/Infra/WebSockets/WebSocketsClientService.ts index 342ed1f87..ee71a78c9 100644 --- a/packages/auth/src/Infra/WebSockets/WebSocketsClientService.ts +++ b/packages/auth/src/Infra/WebSockets/WebSocketsClientService.ts @@ -9,8 +9,8 @@ import { DomainEventPublisherInterface } from '@standardnotes/domain-events' @injectable() export class WebSocketsClientService implements ClientServiceInterface { constructor( - @inject(TYPES.DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, - @inject(TYPES.DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, + @inject(TYPES.Auth_DomainEventFactory) private domainEventFactory: DomainEventFactoryInterface, + @inject(TYPES.Auth_DomainEventPublisher) private domainEventPublisher: DomainEventPublisherInterface, ) {} async sendUserRolesChangedEvent(user: User): Promise { diff --git a/packages/auth/src/Projection/SessionProjector.ts b/packages/auth/src/Projection/SessionProjector.ts index 70997fb4e..cd8792413 100644 --- a/packages/auth/src/Projection/SessionProjector.ts +++ b/packages/auth/src/Projection/SessionProjector.ts @@ -11,8 +11,8 @@ export class SessionProjector implements ProjectorInterface { static readonly CURRENT_SESSION_PROJECTION = 'CURRENT_SESSION_PROJECTION' constructor( - @inject(TYPES.SessionService) private sessionService: SessionServiceInterface, - @inject(TYPES.Timer) private timer: TimerInterface, + @inject(TYPES.Auth_SessionService) private sessionService: SessionServiceInterface, + @inject(TYPES.Auth_Timer) private timer: TimerInterface, ) {} projectSimple(session: Session): Record { diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts new file mode 100644 index 000000000..c82bbe40e --- /dev/null +++ b/packages/auth/src/index.ts @@ -0,0 +1 @@ +export * from './Bootstrap' diff --git a/packages/domain-core/src/Domain/DI/ControllerContainer.ts b/packages/domain-core/src/Domain/DI/ControllerContainer.ts new file mode 100644 index 000000000..021e4898f --- /dev/null +++ b/packages/domain-core/src/Domain/DI/ControllerContainer.ts @@ -0,0 +1,13 @@ +import { ControllerContainerInterface } from './ControllerContainerInterface' + +export class ControllerContainer implements ControllerContainerInterface { + private controllerMethodsMap: Map Promise> = new Map() + + register(methodIdentifier: string, binding: (request: never, response: never) => Promise): void { + this.controllerMethodsMap.set(methodIdentifier, binding) + } + + get(methodIdentifier: string): ((request: never, response: never) => Promise) | undefined { + return this.controllerMethodsMap.get(methodIdentifier) + } +} diff --git a/packages/domain-core/src/Domain/DI/ControllerContainerInterface.ts b/packages/domain-core/src/Domain/DI/ControllerContainerInterface.ts new file mode 100644 index 000000000..e725caf6d --- /dev/null +++ b/packages/domain-core/src/Domain/DI/ControllerContainerInterface.ts @@ -0,0 +1,4 @@ +export interface ControllerContainerInterface { + register(methodIdentifier: string, binding: (request: never, response: never) => Promise): void + get(methodIdentifier: string): ((request: never, response: never) => Promise) | undefined +} diff --git a/packages/domain-core/src/Domain/Service/ServiceContainer.ts b/packages/domain-core/src/Domain/Service/ServiceContainer.ts new file mode 100644 index 000000000..d2dc6af4b --- /dev/null +++ b/packages/domain-core/src/Domain/Service/ServiceContainer.ts @@ -0,0 +1,15 @@ +import { ServiceContainerInterface } from './ServiceContainerInterface' +import { ServiceIdentifier } from './ServiceIdentifier' +import { ServiceInterface } from './ServiceInterface' + +export class ServiceContainer implements ServiceContainerInterface { + private serviceMap: Map = new Map() + + register(serviceIdentifer: ServiceIdentifier, service: ServiceInterface): void { + this.serviceMap.set(serviceIdentifer.value, service) + } + + get(serviceIdentifer: ServiceIdentifier): ServiceInterface | undefined { + return this.serviceMap.get(serviceIdentifer.value) as ServiceInterface + } +} diff --git a/packages/domain-core/src/Domain/Service/ServiceContainerInterface.ts b/packages/domain-core/src/Domain/Service/ServiceContainerInterface.ts new file mode 100644 index 000000000..fca3a943e --- /dev/null +++ b/packages/domain-core/src/Domain/Service/ServiceContainerInterface.ts @@ -0,0 +1,7 @@ +import { ServiceIdentifier } from './ServiceIdentifier' +import { ServiceInterface } from './ServiceInterface' + +export interface ServiceContainerInterface { + register(serviceIdentifer: ServiceIdentifier, service: ServiceInterface): void + get(serviceIdentifer: ServiceIdentifier): ServiceInterface | undefined +} diff --git a/packages/domain-core/src/Domain/Service/ServiceIdentifier.spec.ts b/packages/domain-core/src/Domain/Service/ServiceIdentifier.spec.ts new file mode 100644 index 000000000..634bbe3f3 --- /dev/null +++ b/packages/domain-core/src/Domain/Service/ServiceIdentifier.spec.ts @@ -0,0 +1,18 @@ +import { ServiceIdentifier } from './ServiceIdentifier' + +describe('ServiceIdentifier', () => { + it('should create a value object', () => { + const valueOrError = ServiceIdentifier.create(ServiceIdentifier.NAMES.Auth) + + expect(valueOrError.isFailed()).toBeFalsy() + expect(valueOrError.getValue().value).toEqual('Auth') + }) + + it('should not create an invalid value object', () => { + for (const value of ['', undefined, null, 0, 'SOME_SERVICE']) { + const valueOrError = ServiceIdentifier.create(value as string) + + expect(valueOrError.isFailed()).toBeTruthy() + } + }) +}) diff --git a/packages/domain-core/src/Domain/Service/ServiceIdentifier.ts b/packages/domain-core/src/Domain/Service/ServiceIdentifier.ts new file mode 100644 index 000000000..64b98e863 --- /dev/null +++ b/packages/domain-core/src/Domain/Service/ServiceIdentifier.ts @@ -0,0 +1,29 @@ +import { ValueObject } from '../Core/ValueObject' +import { Result } from '../Core/Result' +import { ServiceIdentifierProps } from './ServiceIdentifierProps' + +export class ServiceIdentifier extends ValueObject { + static readonly NAMES = { + ApiGateway: 'ApiGateway', + Auth: 'Auth', + SyncingServer: 'SyncingServer', + Revisions: 'Revisions', + } + + get value(): string { + return this.props.value + } + + private constructor(props: ServiceIdentifierProps) { + super(props) + } + + static create(name: string): Result { + const isValidName = Object.values(this.NAMES).includes(name) + if (!isValidName) { + return Result.fail(`Invalid subscription plan name: ${name}`) + } else { + return Result.ok(new ServiceIdentifier({ value: name })) + } + } +} diff --git a/packages/domain-core/src/Domain/Service/ServiceIdentifierProps.ts b/packages/domain-core/src/Domain/Service/ServiceIdentifierProps.ts new file mode 100644 index 000000000..388574b77 --- /dev/null +++ b/packages/domain-core/src/Domain/Service/ServiceIdentifierProps.ts @@ -0,0 +1,3 @@ +export interface ServiceIdentifierProps { + value: string +} diff --git a/packages/domain-core/src/Domain/Service/ServiceInterface.ts b/packages/domain-core/src/Domain/Service/ServiceInterface.ts new file mode 100644 index 000000000..c047a7966 --- /dev/null +++ b/packages/domain-core/src/Domain/Service/ServiceInterface.ts @@ -0,0 +1,7 @@ +import { ServiceIdentifier } from './ServiceIdentifier' + +export interface ServiceInterface { + getContainer(): Promise + getId(): ServiceIdentifier + handleRequest(request: never, response: never, endpointOrMethodIdentifier: string): Promise +} diff --git a/packages/domain-core/src/Domain/index.ts b/packages/domain-core/src/Domain/index.ts index 35682ead7..bf0ff2b4d 100644 --- a/packages/domain-core/src/Domain/index.ts +++ b/packages/domain-core/src/Domain/index.ts @@ -31,11 +31,20 @@ export * from './Core/Validator' export * from './Core/ValueObject' export * from './Core/ValueObjectProps' +export * from './DI/ControllerContainer' +export * from './DI/ControllerContainerInterface' + export * from './Email/EmailLevel' export * from './Email/EmailLevelProps' export * from './Mapping/MapperInterface' +export * from './Service/ServiceContainer' +export * from './Service/ServiceContainerInterface' +export * from './Service/ServiceIdentifier' +export * from './Service/ServiceIdentifierProps' +export * from './Service/ServiceInterface' + export * from './Subscription/SubscriptionPlanName' export * from './Subscription/SubscriptionPlanNameProps' diff --git a/packages/home-server/.env.sample b/packages/home-server/.env.sample new file mode 100644 index 000000000..af0bcbf2c --- /dev/null +++ b/packages/home-server/.env.sample @@ -0,0 +1,17 @@ +LOG_LEVEL=debug +NODE_ENV=development +VERSION=development + +# (Optional) New Relic Setup +NEW_RELIC_ENABLED=false +NEW_RELIC_APP_NAME="Home Server" + +CACHE_TYPE=memory + +DB_TYPE=sqlite +DB_DATABASE=home_server + +JWT_SECRET= +AUTH_JWT_SECRET= +ENCRYPTION_SERVER_KEY= +PSEUDO_KEY_PARAMS_KEY= diff --git a/packages/home-server/bin/server.ts b/packages/home-server/bin/server.ts index 790764b24..d624f4aa7 100644 --- a/packages/home-server/bin/server.ts +++ b/packages/home-server/bin/server.ts @@ -1,5 +1,10 @@ import 'reflect-metadata' +import { ControllerContainer, ServiceContainer } from '@standardnotes/domain-core' +import { Service as ApiGatewayService, TYPES as ApiGatewayTYPES } from '@standardnotes/api-gateway' +import { Service as AuthService } from '@standardnotes/auth-server' +import { Container } from 'inversify' +import { InversifyExpressServer } from 'inversify-express-utils' import helmet from 'helmet' import * as cors from 'cors' import { text, json, Request, Response, NextFunction } from 'express' @@ -7,25 +12,26 @@ import * as winston from 'winston' // eslint-disable-next-line @typescript-eslint/no-var-requires const robots = require('express-robots-txt') -import { InversifyExpressServer } from 'inversify-express-utils' import { Env } from '../src/Bootstrap/Env' -import { - ContainerConfigLoader as APIGatewayContainerConfigLoader, - TYPES as APIGatewayTYPES, -} from '@standardnotes/api-gateway' -const container = new APIGatewayContainerConfigLoader() -void container.load().then((container) => { +const startServer = async (): Promise => { + const controllerContainer = new ControllerContainer() + const serviceContainer = new ServiceContainer() + + const apiGatewayService = new ApiGatewayService(serviceContainer, controllerContainer) + const authService = new AuthService(serviceContainer, controllerContainer) + + const container = Container.merge( + (await apiGatewayService.getContainer()) as Container, + (await authService.getContainer()) as Container, + ) + const env: Env = new Env() env.load() const server = new InversifyExpressServer(container) server.setConfig((app) => { - app.use((_request: Request, response: Response, next: NextFunction) => { - response.setHeader('X-API-Gateway-Version', container.get(APIGatewayTYPES.VERSION)) - next() - }) /* eslint-disable */ app.use(helmet({ contentSecurityPolicy: { @@ -63,7 +69,7 @@ void container.load().then((container) => { ) }) - const logger: winston.Logger = container.get(APIGatewayTYPES.Logger) + const logger: winston.Logger = container.get(ApiGatewayTYPES.Logger) server.setErrorConfig((app) => { app.use((error: Record, _request: Request, response: Response, _next: NextFunction) => { @@ -80,7 +86,17 @@ void container.load().then((container) => { const serverInstance = server.build() - serverInstance.listen(env.get('PORT')) + serverInstance.listen(env.get('PORT', true) ? +env.get('PORT', true) : 3000) logger.info(`Server started on port ${process.env.PORT}`) -}) +} + +Promise.resolve(startServer()) + .then(() => { + // eslint-disable-next-line no-console + console.log('Server started') + }) + .catch((error) => { + // eslint-disable-next-line no-console + console.log(`Could not start server: ${error.message}`) + }) diff --git a/packages/home-server/package.json b/packages/home-server/package.json index 6ab873374..b211a23cb 100644 --- a/packages/home-server/package.json +++ b/packages/home-server/package.json @@ -19,6 +19,8 @@ }, "dependencies": { "@standardnotes/api-gateway": "workspace:^", + "@standardnotes/auth-server": "workspace:^", + "@standardnotes/domain-core": "workspace:^", "cors": "2.8.5", "dotenv": "^16.0.1", "express": "^4.18.2", @@ -26,12 +28,14 @@ "helmet": "^6.0.0", "inversify": "^6.0.1", "inversify-express-utils": "^6.4.3", + "prettyjson": "^1.2.5", "reflect-metadata": "0.1.13", "winston": "^3.8.1" }, "devDependencies": { "@types/cors": "^2.8.9", "@types/express": "^4.17.14", + "@types/prettyjson": "^0.0.30", "@typescript-eslint/eslint-plugin": "^5.59.2", "@typescript-eslint/parser": "^5.59.2", "eslint": "^8.39.0", diff --git a/yarn.lock b/yarn.lock index 6073ba8c4..255548610 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3985,7 +3985,7 @@ __metadata: languageName: node linkType: hard -"@standardnotes/auth-server@workspace:packages/auth": +"@standardnotes/auth-server@workspace:^, @standardnotes/auth-server@workspace:packages/auth": version: 0.0.0-use.local resolution: "@standardnotes/auth-server@workspace:packages/auth" dependencies: @@ -4246,8 +4246,11 @@ __metadata: resolution: "@standardnotes/home-server@workspace:packages/home-server" dependencies: "@standardnotes/api-gateway": "workspace:^" + "@standardnotes/auth-server": "workspace:^" + "@standardnotes/domain-core": "workspace:^" "@types/cors": "npm:^2.8.9" "@types/express": "npm:^4.17.14" + "@types/prettyjson": "npm:^0.0.30" "@typescript-eslint/eslint-plugin": "npm:^5.59.2" "@typescript-eslint/parser": "npm:^5.59.2" cors: "npm:2.8.5" @@ -4260,6 +4263,7 @@ __metadata: inversify: "npm:^6.0.1" inversify-express-utils: "npm:^6.4.3" prettier: "npm:^2.8.8" + prettyjson: "npm:^1.2.5" reflect-metadata: "npm:0.1.13" typescript: "npm:^5.0.4" winston: "npm:^3.8.1"