Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(comms)!: new communications module that merges SMS, Push and Email into a single service #1160

Open
wants to merge 14 commits into
base: v-next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 6 additions & 28 deletions libraries/grpc-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,11 @@ import {
Authentication,
Authorization,
Chat,
Comms,
Config,
Core,
DatabaseProvider,
Email,
PushNotifications,
Router,
SMS,
Storage,
} from './modules/index.js';
import crypto from 'crypto';
Expand Down Expand Up @@ -51,11 +49,9 @@ class ConduitGrpcSdk {
router: Router,
database: DatabaseProvider,
storage: Storage,
email: Email,
pushNotifications: PushNotifications,
comms: Comms,
authentication: Authentication,
authorization: Authorization,
sms: SMS,
chat: Chat,
};
private _dynamicModules: { [key: string]: CompatServiceDefinition } = {};
Expand Down Expand Up @@ -213,20 +209,11 @@ class ConduitGrpcSdk {
}
}

get emailProvider(): Email | null {
if (this._modules['email']) {
return this._modules['email'] as Email;
get comms(): Comms | null {
if (this._modules['comms']) {
return this._modules['comms'] as Comms;
} else {
ConduitGrpcSdk.Logger.warn('Email provider not up yet!');
return null;
}
}

get pushNotifications(): PushNotifications | null {
if (this._modules['pushNotifications']) {
return this._modules['pushNotifications'] as PushNotifications;
} else {
ConduitGrpcSdk.Logger.warn('Push notifications module not up yet!');
ConduitGrpcSdk.Logger.warn('Comms not up yet!');
return null;
}
}
Expand All @@ -249,15 +236,6 @@ class ConduitGrpcSdk {
}
}

get sms(): SMS | null {
if (this._modules['sms']) {
return this._modules['sms'] as SMS;
} else {
ConduitGrpcSdk.Logger.warn('SMS module not up yet!');
return null;
}
}

get chat(): Chat | null {
if (this._modules['chat']) {
return this._modules['chat'] as Chat;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ConduitModule } from '../../classes/index.js';
import { EmailDefinition } from '../../protoUtils/email.js';
import { ConduitModule } from '../../../classes/index.js';
import { EmailDefinition } from '../../../protoUtils/index.js';

export class Email extends ConduitModule<typeof EmailDefinition> {
constructor(
Expand Down
39 changes: 39 additions & 0 deletions libraries/grpc-sdk/src/modules/comms/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { ConduitModule } from '../../classes/index.js';
import { CommsDefinition } from '../../protoUtils/index.js';
import { Email } from './email';
import { SMS } from './sms';
import { PushNotifications } from './pushNotifications';

export class Comms extends ConduitModule<typeof CommsDefinition> {
private readonly _email: Email;
private readonly _sms: SMS;
private readonly _pushNotifications: PushNotifications;

constructor(
private readonly moduleName: string,
url: string,
grpcToken?: string,
) {
super(moduleName, 'comms', url, grpcToken);
this.initializeClient(CommsDefinition);
this._email = new Email(moduleName, url, grpcToken);
this._sms = new SMS(moduleName, url, grpcToken);
this._pushNotifications = new PushNotifications(moduleName, url, grpcToken);
}

get email() {
return this._email;
}

get sms() {
return this._sms;
}

get pushNotifications() {
return this._pushNotifications;
}

featureAvailable(name: string) {
return this.client!.featureAvailable({ serviceName: name });
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ConduitModule } from '../../classes/index.js';
import { ConduitModule } from '../../../classes/index.js';
import {
PushNotificationsDefinition,
SendNotificationResponse,
} from '../../protoUtils/index.js';
} from '../../../protoUtils/index.js';
import { SendNotificationOptions } from './types';
import { isNil } from 'lodash';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { ConduitModule } from '../../classes/index.js';
import { ConduitModule } from '../../../classes/index.js';
import {
SendSmsResponse,
SendVerificationCodeResponse,
SmsDefinition,
VerifyResponse,
} from '../../protoUtils/sms.js';
} from '../../../protoUtils/index.js';

export class SMS extends ConduitModule<typeof SmsDefinition> {
constructor(
Expand Down
7 changes: 4 additions & 3 deletions libraries/grpc-sdk/src/modules/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
export * from './storage/index.js';
export * from './router/index.js';
export * from './email/index.js';
export * from './database/index.js';
export * from './config/index.js';
export * from './comms/index.js';
export * from './comms/email/index.js';
export * from './comms/sms/index.js';
export * from './comms/pushNotifications/index.js';
export * from './core/index.js';
export * from './admin/index.js';
export * from './pushNotifications/index.js';
export * from './sms/index.js';
export * from './chat/index.js';
export * from './authorization/index.js';
export * from './authentication/index.js';
29 changes: 21 additions & 8 deletions libraries/module-tools/src/ManagedModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,14 +158,27 @@ export abstract class ManagedModule<T> extends ConduitServiceModule {

async startGrpcServer() {
if (this.service) {
this._serviceName = this.service.protoDescription.substring(
this.service.protoDescription.indexOf('.') + 1,
);
await this.grpcServer.addService(
this.service.protoPath,
this.service.protoDescription,
this.service.functions,
);
// singular service
if (this.service.protoDescription.includes('.')) {
this._serviceName = this.service.protoDescription.substring(
this.service.protoDescription.indexOf('.') + 1,
);
await this.grpcServer.addService(
this.service.protoPath,
this.service.protoDescription,
this.service.functions as { [name: string]: Function },
);
} else {
const packageName = this.service.protoDescription;
for (const service of Object.keys(this.service.functions)) {
this._serviceName = packageName + '.' + service;
await this.grpcServer.addService(
this.service.protoPath,
this._serviceName,
this.service.functions[service] as { [name: string]: Function },
);
}
}
}
RoutingManager.ClientController = new RoutingController();
RoutingManager.AdminController = new RoutingController();
Expand Down
10 changes: 6 additions & 4 deletions libraries/module-tools/src/interfaces/ConduitService.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { GrpcRequest, GrpcResponse } from '@conduitplatform/grpc-sdk';

export type ServiceFunction = (
call: GrpcRequest<any>,
callback: GrpcResponse<any>,
) => void | Promise<void>;

export interface ConduitService {
readonly protoPath: string;
readonly protoDescription: string;
functions: {
[p: string]: (
call: GrpcRequest<any>,
callback: GrpcResponse<any>,
) => void | Promise<void>;
[p: string]: ServiceFunction | { [p: string]: ServiceFunction };
};
}
6 changes: 3 additions & 3 deletions libraries/testing-tools/src/mock-module/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { Channel, Client, createChannel, createClientFactory } from 'nice-grpc';
import { getModuleNameInterceptor } from './utils';
import { HealthCheckResponse, HealthDefinition } from '../protoUtils/grpc_health_check';
import { EventEmitter } from 'events';
import { EmailDefinition } from '../protoUtils/email';
import { EmailDefinition } from '../protoUtils/comms';
import { RouterDefinition } from '../protoUtils/router';
import { DatabaseProviderDefinition } from '../protoUtils/database';
import { StorageDefinition } from '../protoUtils/storage';
import { PushNotificationsDefinition } from '../protoUtils/push-notifications';
import { PushNotificationsDefinition } from '../protoUtils/comms';
import { AuthenticationDefinition } from '../protoUtils/authentication';
import { AuthorizationDefinition } from '../protoUtils/authorization';
import { SmsDefinition } from '../protoUtils/sms';
import { SmsDefinition } from '../protoUtils/comms';
import { ChatDefinition } from '../protoUtils/chat';

export default class MockModule<T extends CompatServiceDefinition> {
Expand Down
8 changes: 5 additions & 3 deletions modules/authentication/src/Authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import AppConfigSchema, { Config } from './config/index.js';
import { AdminHandlers } from './admin/index.js';
import { AuthenticationRoutes } from './routes/index.js';
import * as models from './models/index.js';
import { User } from './models/index.js';
import { AuthUtils } from './utils/index.js';
import { TokenType } from './constants/index.js';
import { v4 as uuid } from 'uuid';
Expand Down Expand Up @@ -50,7 +51,6 @@ import { User as UserAuthz } from './authz/index.js';
import { handleAuthentication } from './routes/middleware.js';
import { fileURLToPath } from 'node:url';
import { TeamsHandler } from './handlers/team.js';
import { User } from './models/index.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
Expand Down Expand Up @@ -313,7 +313,9 @@ export default class Authentication extends ManagedModule<Config> {
}
const sendEmail =
ConfigController.getInstance().config.local.verification.send_email;
const emailAvailable = this.grpcSdk.isAvailable('email');
const emailAvailable =
this.grpcSdk.isAvailable('comms') &&
(await this.grpcSdk.comms?.featureAvailable('email'));
if (verify && sendEmail && emailAvailable) {
const serverConfig = await this.grpcSdk.config.get('router');
const url = serverConfig.hostUrl;
Expand All @@ -324,7 +326,7 @@ export default class Authentication extends ManagedModule<Config> {
});
const result = { verificationToken, hostUrl: url };
const link = `${result.hostUrl}/hook/authentication/verify-email/${result.verificationToken.token}`;
await this.grpcSdk.emailProvider!.sendEmail('EmailVerification', {
await this.grpcSdk.comms?.email!.sendEmail('EmailVerification', {
email: user.email,
variables: {
link,
Expand Down
11 changes: 6 additions & 5 deletions modules/authentication/src/handlers/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -709,11 +709,12 @@ export class LocalHandlers implements IAuthenticationStrategy {
private async initDbAndEmail() {
const config = ConfigController.getInstance().config;

if (config.local.verification.send_email && this.grpcSdk.isAvailable('email')) {
this.emailModule = this.grpcSdk.emailProvider!;
}

if (config.local.verification.send_email && this.grpcSdk.isAvailable('email')) {
if (
config.local.verification.send_email &&
this.grpcSdk.isAvailable('comms') &&
this.grpcSdk.comms?.featureAvailable('email')
) {
this.emailModule = this.grpcSdk.comms.email!;
this.registerTemplates();
}
this.initialized = true;
Expand Down
8 changes: 6 additions & 2 deletions modules/authentication/src/handlers/magicLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,12 @@ export class MagicLinkHandlers implements IAuthenticationStrategy {

async validate(): Promise<boolean> {
const config = ConfigController.getInstance().config;
if (config.magic_link.enabled && this.grpcSdk.isAvailable('email')) {
this.emailModule = this.grpcSdk.emailProvider!;
if (
config.magic_link.enabled &&
this.grpcSdk.isAvailable('comms') &&
(await this.grpcSdk.comms!.featureAvailable('email'))
) {
this.emailModule = this.grpcSdk.comms?.email!;
const success = await this.registerTemplate()
.then(() => true)
.catch(e => {
Expand Down
6 changes: 4 additions & 2 deletions modules/authentication/src/handlers/phone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ export class PhoneHandlers implements IAuthenticationStrategy {

async validate(): Promise<boolean> {
const config = ConfigController.getInstance().config;
const isAvailable = this.grpcSdk.isAvailable('sms');
const isAvailable =
this.grpcSdk.isAvailable('comms') &&
(await this.grpcSdk.comms!.featureAvailable('sms'));
if (config.phoneAuthentication.enabled && isAvailable) {
this.sms = this.grpcSdk.sms!;
this.sms = this.grpcSdk.comms!.sms!;
ConduitGrpcSdk.Logger.log('Phone authentication is available');
return (this.initialized = true);
} else {
Expand Down
22 changes: 16 additions & 6 deletions modules/authentication/src/handlers/team.ts
Original file line number Diff line number Diff line change
Expand Up @@ -539,22 +539,27 @@ export class TeamsHandler implements IAuthenticationStrategy {
role,
inviter: user,
});
if (email && config.teams.invites.sendEmail && this.grpcSdk.isAvailable('email')) {
if (
email &&
config.teams.invites.sendEmail &&
this.grpcSdk.isAvailable('comms') &&
(await this.grpcSdk.comms?.featureAvailable('email'))
) {
let link = !isEmpty(redirectUri)
? AuthUtils.validateRedirectUri(redirectUri)
: config.teams.invites.inviteUrl;
link += `?invitationToken=${invitation.token}`;

await this.grpcSdk
.emailProvider!.sendEmail('TeamInvite', {
.comms!.email!.sendEmail('TeamInvite', {
email: email,
variables: {
link,
teamName: team.name,
inviterName: user.name,
},
})
.catch(e => {
.catch((e: Error) => {
ConduitGrpcSdk.Logger.error(e);
});
}
Expand Down Expand Up @@ -854,14 +859,19 @@ export class TeamsHandler implements IAuthenticationStrategy {
}
}
if (config.teams.invites.enabled && config.teams.invites.sendEmail) {
if (!config.teams.invites.sendEmail || !this.grpcSdk.isAvailable('email')) {
if (
!config.teams.invites.sendEmail ||
!this.grpcSdk.isAvailable('comms') ||
!(await this.grpcSdk.comms!.featureAvailable('email'))
) {
ConduitGrpcSdk.Logger.warn(
'Team invites are enabled, but email sending is disabled. No invites will be sent.',
);
}
if (config.teams.invites.sendEmail) {
this.grpcSdk.onceModuleUp('email', async () => {
await this.grpcSdk.emailProvider!.registerTemplate(TeamInviteTemplate);
this.grpcSdk.onceModuleUp('comms', async () => {
// email doesn't have to be generally serving to user registerTemplate
await this.grpcSdk.comms!.email.registerTemplate(TeamInviteTemplate);
});
}
}
Expand Down
6 changes: 5 additions & 1 deletion modules/authentication/src/handlers/twoFa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,15 @@ export class TwoFa implements IAuthenticationStrategy {
return false;
}
if (authConfig.twoFa.enabled && authConfig.twoFa.methods.sms) {
if (!this.grpcSdk.isAvailable('sms')) {
if (
!this.grpcSdk.isAvailable('comms') ||
!(await this.grpcSdk.comms!.featureAvailable('sms'))
) {
ConduitGrpcSdk.Logger.error('SMS module not available');
return false;
}
}
this.smsModule = this.grpcSdk.comms!.sms!;
ConduitGrpcSdk.Logger.log('TwoFactor authentication is available');
return true;
}
Expand Down
2 changes: 1 addition & 1 deletion modules/authentication/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export namespace AuthUtils {
token: Token,
code: string,
): Promise<boolean> {
const verified = await grpcSdk.sms!.verify(token.data.verification, code);
const verified = await grpcSdk.comms!.sms!.verify(token.data.verification, code);
if (!verified.verified) {
return false;
}
Expand Down
Loading