B2B-88: add starter kit structure and elements
This commit is contained in:
1
packages/database-webhooks/src/index.ts
Normal file
1
packages/database-webhooks/src/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './server/services/database-webhook-handler.service';
|
||||
16
packages/database-webhooks/src/server/record-change.type.ts
Normal file
16
packages/database-webhooks/src/server/record-change.type.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Database } from '@kit/supabase/database';
|
||||
|
||||
export type Tables = Database['public']['Tables'];
|
||||
|
||||
export type TableChangeType = 'INSERT' | 'UPDATE' | 'DELETE';
|
||||
|
||||
export interface RecordChange<
|
||||
Table extends keyof Tables,
|
||||
Row = Tables[Table]['Row'],
|
||||
> {
|
||||
type: TableChangeType;
|
||||
table: Table;
|
||||
record: Row;
|
||||
schema: 'public';
|
||||
old_record: null | Row;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import 'server-only';
|
||||
|
||||
import { getLogger } from '@kit/shared/logger';
|
||||
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
|
||||
|
||||
import { RecordChange, Tables } from '../record-change.type';
|
||||
import { createDatabaseWebhookRouterService } from './database-webhook-router.service';
|
||||
import { getDatabaseWebhookVerifier } from './verifier';
|
||||
|
||||
/**
|
||||
* @name DatabaseChangePayload
|
||||
* @description Payload for the database change event. Useful for handling custom webhooks.
|
||||
*/
|
||||
export type DatabaseChangePayload<Table extends keyof Tables> =
|
||||
RecordChange<Table>;
|
||||
|
||||
export function getDatabaseWebhookHandlerService() {
|
||||
return new DatabaseWebhookHandlerService();
|
||||
}
|
||||
|
||||
/**
|
||||
* @name getDatabaseWebhookHandlerService
|
||||
* @description Get the database webhook handler service
|
||||
*/
|
||||
class DatabaseWebhookHandlerService {
|
||||
private readonly namespace = 'database-webhook-handler';
|
||||
|
||||
/**
|
||||
* @name handleWebhook
|
||||
* @description Handle the webhook event
|
||||
* @param params
|
||||
*/
|
||||
async handleWebhook(params: {
|
||||
body: RecordChange<keyof Tables>;
|
||||
signature: string;
|
||||
handleEvent?<Table extends keyof Tables>(
|
||||
payload: Table extends keyof Tables
|
||||
? DatabaseChangePayload<Table>
|
||||
: never,
|
||||
): unknown;
|
||||
}) {
|
||||
const logger = await getLogger();
|
||||
const { table, type } = params.body;
|
||||
|
||||
const ctx = {
|
||||
name: this.namespace,
|
||||
table,
|
||||
type,
|
||||
};
|
||||
|
||||
logger.info(ctx, 'Received webhook from DB. Processing...');
|
||||
|
||||
// check if the signature is valid
|
||||
const verifier = await getDatabaseWebhookVerifier();
|
||||
|
||||
await verifier.verifySignatureOrThrow(params.signature);
|
||||
|
||||
// all good, we can now the webhook
|
||||
|
||||
// create a client with admin access since we are handling webhooks and no user is authenticated
|
||||
const adminClient = getSupabaseServerAdminClient();
|
||||
|
||||
const service = createDatabaseWebhookRouterService(adminClient);
|
||||
|
||||
try {
|
||||
// handle the webhook event based on the table
|
||||
await service.handleWebhook(params.body);
|
||||
|
||||
// if a custom handler is provided, call it
|
||||
if (params?.handleEvent) {
|
||||
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
|
||||
await params.handleEvent(params.body as any);
|
||||
}
|
||||
|
||||
logger.info(ctx, 'Webhook processed successfully');
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
{
|
||||
...ctx,
|
||||
error,
|
||||
},
|
||||
'Failed to process webhook',
|
||||
);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { SupabaseClient } from '@supabase/supabase-js';
|
||||
|
||||
import { Database } from '@kit/supabase/database';
|
||||
|
||||
import { RecordChange, Tables } from '../record-change.type';
|
||||
|
||||
export function createDatabaseWebhookRouterService(
|
||||
adminClient: SupabaseClient<Database>,
|
||||
) {
|
||||
return new DatabaseWebhookRouterService(adminClient);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name DatabaseWebhookRouterService
|
||||
* @description Service that routes the webhook event to the appropriate service
|
||||
*/
|
||||
class DatabaseWebhookRouterService {
|
||||
constructor(private readonly adminClient: SupabaseClient<Database>) {}
|
||||
|
||||
/**
|
||||
* @name handleWebhook
|
||||
* @description Handle the webhook event
|
||||
* @param body
|
||||
*/
|
||||
async handleWebhook(body: RecordChange<keyof Tables>) {
|
||||
switch (body.table) {
|
||||
case 'invitations': {
|
||||
const payload = body as RecordChange<typeof body.table>;
|
||||
|
||||
return this.handleInvitationsWebhook(payload);
|
||||
}
|
||||
|
||||
case 'subscriptions': {
|
||||
const payload = body as RecordChange<typeof body.table>;
|
||||
|
||||
return this.handleSubscriptionsWebhook(payload);
|
||||
}
|
||||
|
||||
case 'accounts': {
|
||||
const payload = body as RecordChange<typeof body.table>;
|
||||
|
||||
return this.handleAccountsWebhook(payload);
|
||||
}
|
||||
|
||||
default: {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async handleInvitationsWebhook(body: RecordChange<'invitations'>) {
|
||||
const { createAccountInvitationsWebhookService } = await import(
|
||||
'@kit/team-accounts/webhooks'
|
||||
);
|
||||
|
||||
const service = createAccountInvitationsWebhookService(this.adminClient);
|
||||
|
||||
return service.handleInvitationWebhook(body.record);
|
||||
}
|
||||
|
||||
private async handleSubscriptionsWebhook(
|
||||
body: RecordChange<'subscriptions'>,
|
||||
) {
|
||||
if (body.type === 'DELETE' && body.old_record) {
|
||||
const { createBillingWebhooksService } = await import(
|
||||
'@kit/billing-gateway'
|
||||
);
|
||||
|
||||
const service = createBillingWebhooksService();
|
||||
|
||||
return service.handleSubscriptionDeletedWebhook(body.old_record);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleAccountsWebhook(body: RecordChange<'accounts'>) {
|
||||
if (body.type === 'DELETE' && body.old_record) {
|
||||
const { createAccountWebhooksService } = await import(
|
||||
'@kit/team-accounts/webhooks'
|
||||
);
|
||||
|
||||
const service = createAccountWebhooksService();
|
||||
|
||||
return service.handleAccountDeletedWebhook(body.old_record);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export abstract class DatabaseWebhookVerifierService {
|
||||
abstract verifySignatureOrThrow(header: string): Promise<boolean>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
const WEBHOOK_SENDER_PROVIDER =
|
||||
process.env.WEBHOOK_SENDER_PROVIDER ?? 'postgres';
|
||||
|
||||
export async function getDatabaseWebhookVerifier() {
|
||||
switch (WEBHOOK_SENDER_PROVIDER) {
|
||||
case 'postgres': {
|
||||
const { createDatabaseWebhookVerifierService } = await import(
|
||||
'./postgres-database-webhook-verifier.service'
|
||||
);
|
||||
|
||||
return createDatabaseWebhookVerifierService();
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(
|
||||
`Invalid WEBHOOK_SENDER_PROVIDER: ${WEBHOOK_SENDER_PROVIDER}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { DatabaseWebhookVerifierService } from './database-webhook-verifier.service';
|
||||
|
||||
const webhooksSecret = z
|
||||
.string({
|
||||
description: `The secret used to verify the webhook signature`,
|
||||
required_error: `Provide the variable SUPABASE_DB_WEBHOOK_SECRET. This is used to authenticate the webhook event from Supabase.`,
|
||||
})
|
||||
.min(1)
|
||||
.parse(process.env.SUPABASE_DB_WEBHOOK_SECRET);
|
||||
|
||||
export function createDatabaseWebhookVerifierService() {
|
||||
return new PostgresDatabaseWebhookVerifierService();
|
||||
}
|
||||
|
||||
class PostgresDatabaseWebhookVerifierService
|
||||
implements DatabaseWebhookVerifierService
|
||||
{
|
||||
verifySignatureOrThrow(header: string) {
|
||||
if (header !== webhooksSecret) {
|
||||
throw new Error('Invalid signature');
|
||||
}
|
||||
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user