Skip to content
Merged
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
286 changes: 33 additions & 253 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
"@nestjs/platform-express": "^10.0.0",
"@nestjs/schedule": "^6.1.3",
"@nestjs/terminus": "^10.1.0",
"@nestjs/typeorm": "^10.0.0",
"@stellar/stellar-sdk": "^12.0.0",
"axios": "^1.6.0",
"class-transformer": "^0.5.1",
Expand All @@ -47,7 +46,6 @@
"prom-client": "^15.0.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.0",
"typeorm": "^0.3.17",
"uuid": "^9.0.0",
"zod": "^4.4.3"
},
Expand Down
30 changes: 8 additions & 22 deletions src/__tests__/app.smoke.spec.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
import { INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { TypeOrmHealthIndicator } from '@nestjs/terminus';
import request from 'supertest';
import { AppModule } from '../app.module';
import { CorsOriginsCacheService } from '../middleware/cors-origins-cache.service';
import { PaymentDetectorService } from '../payments/payment-detector.service';
import { RedisService } from '../redis/redis.service';

jest.mock('@nestjs/typeorm', () => {
const actual = jest.requireActual('@nestjs/typeorm');

return {
...actual,
TypeOrmModule: {
...actual.TypeOrmModule,
forRoot: jest.fn(() => ({
module: class MockTypeOrmModule {},
})),
},
};
});
jest.mock('../db/index', () => ({
db: {
execute: jest.fn().mockResolvedValue([]),
query: {},
},
client: {},
schema: {},
}));

describe('App smoke test', () => {
let app: INestApplication;
Expand All @@ -37,14 +31,6 @@ describe('App smoke test', () => {
const module: TestingModule = await Test.createTestingModule({
imports: [AppModule],
})
.overrideProvider(TypeOrmHealthIndicator)
.useValue({
pingCheck: jest.fn().mockResolvedValue({
database: {
status: 'up',
},
}),
})
.overrideProvider(RedisService)
.useValue({
getClient: jest.fn(() => redisClient),
Expand Down
10 changes: 6 additions & 4 deletions src/__tests__/webhook-controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ function build() {
}

describe('WebhookController', () => {
it('is JWT-guarded at the class level', () => {
const guards = Reflect.getMetadata('__guards__', WebhookController);
expect(guards).toBeDefined();
expect(guards).toHaveLength(1);
it('dashboard endpoints are JWT-guarded individually', () => {
const deliveryGuards = Reflect.getMetadata(
'__guards__',
WebhookController.prototype.listDeliveries,
);
expect(deliveryGuards).toBeDefined();
});

describe('merchant scoping', () => {
Expand Down
7 changes: 0 additions & 7 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ScheduleModule } from '@nestjs/schedule';
import { AuthModule } from './auth/auth.module';
import { MerchantsModule } from './merchants/merchants.module';
Expand All @@ -19,12 +18,6 @@ import { SecurityHeadersMiddleware } from './middleware/security-headers.middlew
imports: [
ConfigModule,
ScheduleModule.forRoot(),
TypeOrmModule.forRoot({
type: 'postgres',
url: process.env.DATABASE_URL,
autoLoadEntities: true,
synchronize: process.env.NODE_ENV !== 'production',
}),
RedisModule,
RateLimitModule,
AuditModule,
Expand Down
6 changes: 6 additions & 0 deletions src/checkout/checkout.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ export class CheckoutController {
return this.checkout.getSession(id);
}

@UseGuards(ApiKeyGuard)
@Get('sessions/:id/payment')
getSessionPayment(@Param('id') id: string) {
return this.checkout.getSessionPayment(id);
}

@UseGuards(ApiKeyGuard, RolesGuard, ResourceOwnershipGuard)
@Roles('admin', 'merchant')
@ResourceOwner('checkout_session')
Expand Down
24 changes: 23 additions & 1 deletion src/checkout/checkout.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { db } from '../db/index';
import { checkoutSessions } from '../db/schema';
import { checkoutSessions, payments } from '../db/schema';
import { eq, and } from 'drizzle-orm';
import * as crypto from 'crypto';
import { AuditService } from '../audit/audit.service';
Expand Down Expand Up @@ -129,4 +129,26 @@ export class CheckoutService {
.returning();
return updated;
}

async getSessionPayment(sessionId: string) {
const session = await db.query.checkoutSessions.findFirst({
where: eq(checkoutSessions.id, sessionId),
});
if (!session) throw new NotFoundException('Session not found');

const payment = await db.query.payments.findFirst({
where: eq(payments.sessionId, sessionId),
});
if (!payment) throw new NotFoundException('Payment not found for session');

return {
id: payment.id,
sessionId: payment.sessionId,
txHash: payment.txHash,
amount: payment.amount,
asset: payment.assetCode,
sender: payment.senderAddress,
confirmedAt: payment.confirmedAt,
};
}
}
30 changes: 30 additions & 0 deletions src/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,34 @@ export const webhookDeadLetters = pgTable('webhook_dead_letters', {
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});

export const webhookEndpoints = pgTable('webhook_endpoints', {
id: uuid('id').defaultRandom().primaryKey(),
merchantId: uuid('merchant_id')
.notNull()
.references(() => merchants.id, { onDelete: 'cascade' }),
url: text('url').notNull(),
events: jsonb('events').notNull().default([]),
secret: text('secret').notNull(),
isActive: boolean('is_active').notNull().default(true),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});

export const paymentLinks = pgTable('payment_links', {
id: uuid('id').defaultRandom().primaryKey(),
merchantId: uuid('merchant_id')
.notNull()
.references(() => merchants.id, { onDelete: 'cascade' }),
amount: numeric('amount', { precision: 36, scale: 7 }).notNull(),
assetCode: text('asset_code').notNull(),
assetIssuer: text('asset_issuer'),
description: text('description'),
displayCurrency: text('display_currency'),
metadata: jsonb('metadata'),
active: boolean('active').notNull().default(true),
expiresAt: timestamp('expires_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});

export const auditLogs = pgTable('audit_logs', {
id: uuid('id').defaultRandom().primaryKey(),
merchantId: uuid('merchant_id').references(() => merchants.id),
Expand All @@ -171,5 +199,7 @@ export const schema = {
payments,
webhookDeliveries,
webhookDeadLetters,
webhookEndpoints,
paymentLinks,
auditLogs,
};
16 changes: 10 additions & 6 deletions src/monitoring/health.controller.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import { Controller, Get } from '@nestjs/common';
import { HealthCheck, HealthCheckService, TypeOrmHealthIndicator } from '@nestjs/terminus';
import { HealthCheck, HealthCheckService } from '@nestjs/terminus';
import { db } from '../db/index';
import { sql } from 'drizzle-orm';

@Controller('health')
export class HealthController {
constructor(
private health: HealthCheckService,
private db: TypeOrmHealthIndicator,
) {}
constructor(private health: HealthCheckService) {}

@Get()
@HealthCheck()
check() {
return this.health.check([() => this.db.pingCheck('database')]);
return this.health.check([
async () => {
await db.execute(sql`SELECT 1`);
return { database: { status: 'up' } };
},
]);
}
}
55 changes: 44 additions & 11 deletions src/webhook/webhook.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,64 +6,97 @@ import {
Param,
ParseUUIDPipe,
Post,
Body,
Query,
Request,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { WebhookService } from './webhook.service';
import { MerchantsService } from '../merchants/merchants.service';
import { ApiKeyGuard } from '../auth/api-key.guard';
import { IsArray, IsString, IsUrl } from 'class-validator';

class CreateWebhookEndpointDto {
@IsUrl({}, { message: 'Invalid URL format' })
url: string;

@IsArray()
@IsString({ each: true })
events: string[];
}

@Controller('v1/webhooks')
@UseGuards(AuthGuard('jwt'))
export class WebhookController {
constructor(
private readonly webhooks: WebhookService,
private readonly merchants: MerchantsService,
) {}

private async merchantId(req: any): Promise<string> {
private async merchantIdFromJwt(req: any): Promise<string> {
const merchant = await this.merchants.findByWallet(req.user.walletAddress);
if (!merchant) throw new NotFoundException('Merchant not found');
return merchant.id;
}

/** List recent webhook deliveries for the authenticated merchant. */
// ── SDK-facing endpoints (API key auth) ──

@UseGuards(ApiKeyGuard)
@Post()
async createEndpoint(@Request() req: any, @Body() dto: CreateWebhookEndpointDto) {
return this.webhooks.createEndpoint(req.merchantId, dto.url, dto.events);
}

@UseGuards(ApiKeyGuard)
@Get()
async listEndpoints(@Request() req: any) {
return this.webhooks.listEndpoints(req.merchantId);
}

// ── Dashboard-facing endpoints (JWT auth) ──

@UseGuards(AuthGuard('jwt'))
@Get('deliveries')
async listDeliveries(@Request() req: any, @Query('limit') limit?: string) {
const merchantId = await this.merchantId(req);
const merchantId = await this.merchantIdFromJwt(req);
return this.webhooks.listDeliveries(merchantId, this.clampLimit(limit));
}

/** Bound a client-supplied limit to a sane [1, 100] range (default 50). */
private clampLimit(limit?: string): number {
const n = Number(limit);
if (!Number.isFinite(n) || n <= 0) return 50;
return Math.min(Math.floor(n), 100);
}

/** List dead-letter entries for the authenticated merchant. */
@UseGuards(AuthGuard('jwt'))
@Get('dead-letter')
async listDeadLetter(@Request() req: any) {
const merchantId = await this.merchantId(req);
const merchantId = await this.merchantIdFromJwt(req);
return this.webhooks.listDeadLetters(merchantId);
}

/** Manually retry a dead-letter entry. */
@UseGuards(AuthGuard('jwt'))
@Post('dead-letter/:id/retry')
async retryDeadLetter(@Request() req: any, @Param('id', ParseUUIDPipe) id: string) {
const merchantId = await this.merchantId(req);
const merchantId = await this.merchantIdFromJwt(req);
const result = await this.webhooks.retryDeadLetter(merchantId, id);
if (!result) throw new NotFoundException('Dead-letter entry not found');
return { status: 'requeued', ...result };
}

/** Dismiss (delete) a dead-letter entry. */
@UseGuards(AuthGuard('jwt'))
@Delete('dead-letter/:id')
async dismissDeadLetter(@Request() req: any, @Param('id', ParseUUIDPipe) id: string) {
const merchantId = await this.merchantId(req);
const merchantId = await this.merchantIdFromJwt(req);
const ok = await this.webhooks.dismissDeadLetter(merchantId, id);
if (!ok) throw new NotFoundException('Dead-letter entry not found');
return { status: 'dismissed' };
}

@UseGuards(ApiKeyGuard)
@Delete(':id')
async deleteEndpoint(@Request() req: any, @Param('id', ParseUUIDPipe) id: string) {
const ok = await this.webhooks.deleteEndpoint(req.merchantId, id);
if (!ok) throw new NotFoundException('Webhook endpoint not found');
}
}
41 changes: 40 additions & 1 deletion src/webhook/webhook.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Injectable, Logger } from '@nestjs/common';
import { db } from '../db/index';
import { webhookDeadLetters, webhookDeliveries, merchants } from '../db/schema';
import { webhookDeadLetters, webhookDeliveries, webhookEndpoints, merchants } from '../db/schema';
import { and, desc, eq } from 'drizzle-orm';
import * as crypto from 'crypto';
import { WebhookQueueService } from './webhook-queue.service';

@Injectable()
Expand Down Expand Up @@ -62,4 +63,42 @@ export class WebhookService {
.returning();
return !!deleted;
}

// ── Webhook Endpoints CRUD ──

async createEndpoint(merchantId: string, url: string, events: string[]) {
const secret = 'whsec_' + crypto.randomBytes(24).toString('hex');
const [endpoint] = await db
.insert(webhookEndpoints)
.values({ merchantId, url, events, secret } as any)
.returning();
return this.toEndpointDto(endpoint);
}

async listEndpoints(merchantId: string) {
const endpoints = await db.query.webhookEndpoints.findMany({
where: eq(webhookEndpoints.merchantId, merchantId),
orderBy: [desc(webhookEndpoints.createdAt)],
});
return endpoints.map((e) => this.toEndpointDto(e));
}

async deleteEndpoint(merchantId: string, endpointId: string): Promise<boolean> {
const [deleted] = await db
.delete(webhookEndpoints)
.where(and(eq(webhookEndpoints.id, endpointId), eq(webhookEndpoints.merchantId, merchantId)))
.returning();
return !!deleted;
}

private toEndpointDto(endpoint: any) {
return {
id: endpoint.id,
url: endpoint.url,
events: endpoint.events,
secret: endpoint.secret,
active: endpoint.isActive,
createdAt: endpoint.createdAt,
};
}
}
Loading