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
2 changes: 2 additions & 0 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,5 @@ OCI_LOGGING_MAX_BATCH_SIZE=50
OCI_LOGGING_FLUSH_INTERVAL_MS=5000

LOG_LEVEL=debug

BUYMEACOFFEE_WEBHOOK_SECRET=
2 changes: 2 additions & 0 deletions apps/api/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { UserModule } from './user/user.module';
import { RedirectModule } from './redirect/redirect.module';
import { TeslaPublicKeyModule } from './tesla-public-key/tesla-public-key.module';
import { OnboardingModule } from './onboarding/onboarding.module';
import { SupportersModule } from './supporters/supporters.module';
import { CloudflareThrottlerGuard } from '../common/guards/cloudflare-throttler.guard';
import { LogContextInterceptor } from '../common/interceptors/log-context.interceptor';
import { TokenRevokedExceptionFilter } from '../common/filters/token-revoked-exception.filter';
Expand Down Expand Up @@ -70,6 +71,7 @@ import {
OffensiveResponseModule,
AlertsModule,
NotificationsModule,
SupportersModule,
ThrottlerModule.forRoot([getThrottleConfig()]),
],
controllers: [AppController, HealthController],
Expand Down
109 changes: 109 additions & 0 deletions apps/api/src/app/supporters/bmc-webhook-parser.util.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import * as crypto from 'crypto';
import { SupporterType } from '../../entities/supporter.entity';
import {
BmcWebhookPayload,
verifyWebhookSignature,
} from './bmc-webhook-parser.util';

describe('The bmc-webhook-parser utility', () => {
const originalSecret = process.env.BUYMEACOFFEE_WEBHOOK_SECRET;

afterEach(() => {
process.env.BUYMEACOFFEE_WEBHOOK_SECRET = originalSecret;
});

describe('The verifyWebhookSignature() function', () => {
describe('When signature matches the HMAC of the raw body', () => {
it('should return true', () => {
const secret = 'test-secret-key-123';
process.env.BUYMEACOFFEE_WEBHOOK_SECRET = secret;
const rawBody = JSON.stringify({ type: 'donation.created' });
const signature = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');

expect(verifyWebhookSignature(rawBody, signature)).toBe(true);
});
});

describe('When signature does not match', () => {
it('should return false', () => {
process.env.BUYMEACOFFEE_WEBHOOK_SECRET = 'secret';
expect(verifyWebhookSignature('{"foo":"bar"}', 'invalid-hex-signature')).toBe(false);
});
});
});

describe('The BmcWebhookPayload class', () => {
describe('When instantiated with a donation payload', () => {
it('should transform into a complete active donation supporter entity', () => {
const payload = {
type: 'donation.created',
data: {
transaction_id: 'txn-123',
supporter_name: 'John Doe',
supporter_email: 'john@example.com',
coffee_count: 5,
support_note: 'Awesome project!',
support_created_on: '2024-01-01T12:00:00Z',
},
};

const result = new BmcWebhookPayload(payload).toSupporter();

expect(result).toStrictEqual({
external_id: 'txn-123',
name: 'John Doe',
email: 'john@example.com',
coffees: 5,
type: SupporterType.Donation,
is_active: true,
message: 'Awesome project!',
support_date: new Date('2024-01-01T12:00:00Z'),
});
});
});

describe('When instantiated with a membership payload', () => {
it('should transform into an active membership supporter entity with calculated coffees', () => {
const payload = {
type: 'membership.started',
data: {
psp_id: 'sub-456',
supporter_name: 'Alice',
amount: 5,
status: 'active',
started_at: 1719825600,
},
};

const result = new BmcWebhookPayload(payload).toSupporter();

expect(result).toStrictEqual({
external_id: 'sub-456',
name: 'Alice',
email: null,
coffees: 2,
type: SupporterType.Membership,
is_active: true,
message: null,
support_date: new Date(1719825600 * 1000),
});
});
});

describe('When instantiated with a cancellation or refund event', () => {
it('should mark isActive as false', () => {
const payload = {
type: 'membership.cancelled',
data: {
psp_id: 'sub-456',
status: 'canceled',
},
};

const result = new BmcWebhookPayload(payload).toSupporter();

expect(result.is_active).toBe(false);
});
});
});
});
157 changes: 157 additions & 0 deletions apps/api/src/app/supporters/bmc-webhook-parser.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import * as crypto from 'crypto';
import { Supporter, SupporterType } from '../../entities/supporter.entity';
import {
isPrivateSupporter,
sanitizeMessage,
sanitizeName,
} from './supporter-sanitizer.util';

export function verifyWebhookSignature(rawBody: string, signature?: string): boolean {
const secret = process.env.BUYMEACOFFEE_WEBHOOK_SECRET;
if (!secret || !signature) {
return false;
}

const calculated = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
const signatureBuffer = Buffer.from(signature, 'hex');
const calculatedBuffer = Buffer.from(calculated, 'hex');

if (signatureBuffer.length !== calculatedBuffer.length) {
return false;
}

return crypto.timingSafeEqual(signatureBuffer, calculatedBuffer);
}

export class BmcWebhookPayload {
private readonly eventType: string;
private readonly data: Record<string, unknown>;
private readonly isPrivate: boolean;

constructor(payload: Record<string, unknown>) {
this.eventType = String(payload['type'] || '');
this.data = (payload['data'] || payload['response'] || payload) as Record<string, unknown>;
this.isPrivate = isPrivateSupporter(this.data) || isPrivateSupporter(payload);
}

public toSupporter(): Partial<Supporter> {
return {
external_id: this.resolveExternalId(),
name: this.resolveName(),
email: this.resolveEmail(),
coffees: this.resolveCoffees(),
type: this.resolveType(),
is_active: this.resolveIsActive(),
message: this.resolveMessage(),
support_date: this.resolveSupportDate(),
};
}

private resolveExternalId(): string | null {
const id = String(
this.data['transaction_id'] ||
this.data['psp_id'] ||
this.data['subscription_id'] ||
this.data['id'] ||
''
);
return id || null;
}

private resolveName(): string {
const raw = String(
this.data['supporter_name'] ||
this.data['payer_name'] ||
this.data['name'] ||
'Anonymous'
);
return sanitizeName(raw, this.isPrivate);
}

private resolveEmail(): string | null {
const email = this.data['supporter_email'] || this.data['payer_email'] || this.data['email'];
return email ? String(email) : null;
}

private resolveCoffees(): number {
const count = Number(
this.data['coffee_count'] ||
this.data['number_of_coffees'] ||
this.data['coffees'] ||
this.data['quantity'] ||
0
);
const amount = Number(
this.data['amount'] ||
this.data['total_amount_charged'] ||
this.data['coffee_price'] ||
0
);
if (amount > 0) {
return Math.max(count, Math.max(1, Math.round(amount / 2.25)));
}
return Math.max(1, count);
}

private resolveType(): SupporterType {
return this.isSubscription() ? SupporterType.Membership : SupporterType.Donation;
}

private resolveIsActive(): boolean {
const isInactiveEvent =
this.eventType.endsWith('.refunded') ||
this.eventType.endsWith('.cancelled') ||
this.eventType.endsWith('.paused');
const isInactiveStatus =
this.data['status'] === 'refunded' ||
this.data['status'] === 'canceled' ||
this.data['status'] === 'paused';
const isInactiveFlag =
this.data['refunded'] === 'true' ||
this.data['canceled'] === 'true' ||
this.data['paused'] === 'true';

return !isInactiveEvent && !isInactiveStatus && !isInactiveFlag;
}

private resolveMessage(): string | null {
const raw = this.data['support_note'] || this.data['message'] || null;
return sanitizeMessage(raw ? String(raw) : null, this.isPrivate) || null;
}

private resolveSupportDate(): Date {
const raw =
this.data['support_created_on'] ||
this.data['created_at'] ||
this.data['started_at'] ||
this.data['created'];
return this.parseDate(raw);
}

private parseDate(raw: unknown): Date {
if (typeof raw === 'number') {
return raw < 1e11 ? new Date(raw * 1000) : new Date(raw);
}
if (typeof raw === 'string' && /^\d+$/.test(raw)) {
const num = parseInt(raw, 10);
return num < 1e11 ? new Date(num * 1000) : new Date(num);
}
if (typeof raw === 'string') {
return new Date(raw);
}
return new Date();
}

private isSubscription(): boolean {
return (
this.eventType.startsWith('membership.') ||
this.eventType.startsWith('recurring_donation.') ||
this.eventType === 'subscription' ||
Boolean(
this.data['subscription_id'] ||
this.data['membership_level_id'] ||
this.data['psp_id']
)
);
}
}
73 changes: 73 additions & 0 deletions apps/api/src/app/supporters/supporter-aggregator.util.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { Supporter, SupporterType } from '../../entities/supporter.entity';
import { aggregateSupporters } from './supporter-aggregator.util';

describe('The supporter-aggregator utility', () => {
describe('The aggregateSupporters() function', () => {
describe('When aggregating multiple donations from same user', () => {
it('should sum coffee counts and use latest date', () => {
const item1: Supporter = {
id: '1',
name: 'Yvan',
email: 'yvan@example.com',
coffees: 5,
type: SupporterType.Donation,
is_active: true,
support_date: new Date('2024-01-01T10:00:00Z'),
created_at: new Date(),
updated_at: new Date(),
};

const item2: Supporter = {
id: '2',
name: 'Yvan M.',
email: 'yvan@example.com',
coffees: 10,
type: SupporterType.Donation,
is_active: true,
support_date: new Date('2024-01-05T10:00:00Z'),
created_at: new Date(),
updated_at: new Date(),
};

const result = aggregateSupporters([item1, item2]);

expect(result).toHaveLength(1);
expect(result[0].coffees).toBe(15);
expect(result[0].name).toBe('Yvan M.');
expect(result[0].supportDate).toBe('2024-01-05T10:00:00.000Z');
});
});

describe('When grouping anonymous contributors without email', () => {
it('should not merge separate anonymous contributors', () => {
const item1: Supporter = {
id: 'anon-1',
name: 'Anonymous',
coffees: 1,
type: SupporterType.Donation,
is_active: true,
support_date: new Date('2024-01-01T10:00:00Z'),
created_at: new Date(),
updated_at: new Date(),
};

const item2: Supporter = {
id: 'anon-2',
name: 'Someone',
coffees: 2,
type: SupporterType.Donation,
is_active: true,
support_date: new Date('2024-01-02T10:00:00Z'),
created_at: new Date(),
updated_at: new Date(),
};

const result = aggregateSupporters([item1, item2]);

expect(result).toHaveLength(2);
expect(result[0].coffees).toBe(2);
expect(result[1].coffees).toBe(1);
});
});
});
});
Loading
Loading