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
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,4 @@ export const EU_COUNTRIES = [
'SE',
];
export const STRIPE_API_VERSION = '2025-02-24.acacia';
export const PAYMENTS_TOKEN_EXPIRATION = '6h';
7 changes: 2 additions & 5 deletions src/controller/object-storage.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ import config from '../config';
import Stripe from 'stripe';
import { setupAuth } from '../plugins/auth';
import { stripePaymentsAdapter } from '../infrastructure/adapters/stripe.adapter';

function signUserToken(customerId: string) {
return jwt.sign({ customerId }, config.JWT_SECRET);
}
import { signUserToken } from '../utils/signUserToken';

export function objectStorageController(paymentService: PaymentService) {
return async function (fastify: FastifyInstance) {
Expand Down Expand Up @@ -74,7 +71,7 @@ export function objectStorageController(paymentService: PaymentService) {
customerId = id;
}

return res.send({ customerId, token: signUserToken(customerId) });
return res.send({ customerId, token: signUserToken({ customerId }) });
},
);

Expand Down
3 changes: 2 additions & 1 deletion src/utils/signUserToken.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import jwt from 'jsonwebtoken';
import config from '../config';
import { PAYMENTS_TOKEN_EXPIRATION } from '../constants';

export function signUserToken(payload: { customerId?: string; invoiceId?: string }): string {
return jwt.sign(payload, config.JWT_SECRET);
return jwt.sign(payload, config.JWT_SECRET, { expiresIn: PAYMENTS_TOKEN_EXPIRATION });
}
15 changes: 15 additions & 0 deletions tests/src/controller/checkout.controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
getCreateSubscriptionResponse,
getCryptoCurrency,
getCustomer,
getExpiredUserToken,
getInvoice,
getPrice,
getRawCryptoInvoiceResponse,
Expand Down Expand Up @@ -1068,6 +1069,20 @@ describe('Checkout controller', () => {
});

describe('Verify the crypto payment', () => {
test('When the payment token has expired, then the verification is rejected', async () => {
const verifyCryptoPaymentSpy = jest.spyOn(PaymentService.prototype, 'verifyCryptoPayment');

const response = await app.inject({
path: '/checkout/crypto/verify/payment',
method: 'POST',
body: { token: getExpiredUserToken({ invoiceId: 'in_123' }) },
headers: { authorization: `Bearer ${getValidAuthToken(getUser().uuid)}` },
});

expect(response.statusCode).toBe(403);
expect(verifyCryptoPaymentSpy).not.toHaveBeenCalled();
});

test('When the crypto payment invoice has an status of paid, then true is returned indicating the invoice has been paid', async () => {
const mockedUser = getUser();
const userAuthToken = getValidAuthToken(mockedUser.uuid);
Expand Down
36 changes: 35 additions & 1 deletion tests/src/controller/payments.controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import jwt from 'jsonwebtoken';
import {
getCreateSubscriptionResponse,
getCustomer,
getExpiredUserToken,
getLicenseCode,
getPaymentIntent,
getUniqueCodes,
Expand Down Expand Up @@ -279,7 +280,7 @@ describe('Payment controller e2e tests', () => {
expect(response.statusCode).toBe(200);
expect(responseBody).toStrictEqual({
customerId: mockedCustomer.id,
token: jwt.sign({ customerId: mockedCustomer.id }, config.JWT_SECRET),
token: getValidUserToken({ customerId: mockedCustomer.id }),
});
expect(attachVatIdSpy).toHaveBeenCalled();
expect(attachVatIdSpy).toHaveBeenCalledWith(mockedCustomer.id, mockedCustomer.address?.country, companyVatId);
Expand Down Expand Up @@ -364,6 +365,22 @@ describe('Payment controller e2e tests', () => {
expect(responseBody).toStrictEqual(subResponse);
});

it('When the user token has expired, then the subscription is rejected', async () => {
const mockedUser = getUser();

const response = await app.inject({
method: 'POST',
path: '/object-storage/subscription',
body: {
customerId: mockedUser.customerId,
priceId: 'price_id',
token: getExpiredUserToken({ customerId: mockedUser.customerId }),
},
});

expect(response.statusCode).toBe(403);
});

it('When the user token is not provided, then an error indicating so is thrown', async () => {
const mockedUser = getUser();
const subResponse = getCreateSubscriptionResponse();
Expand Down Expand Up @@ -484,6 +501,23 @@ describe('Payment controller e2e tests', () => {
});
});

it('When the user token has expired, then the verification is rejected', async () => {
const mockedUser = getUser();

const response = await app.inject({
method: 'POST',
path: '/payment-method-verification',
body: {
customerId: mockedUser.customerId,
token: getExpiredUserToken({ customerId: mockedUser.customerId }),
paymentMethod: 'pm_123',
priceId: 'price_id',
},
});

expect(response.statusCode).toBe(403);
});

it('When the customer ID from the user token does not match with the real user customer ID, then an error indicating so is thrown', async () => {
const mockedUser = getUser();
const priceId = 'price_id';
Expand Down
8 changes: 7 additions & 1 deletion tests/src/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
import { FastifyBaseLogger } from 'fastify';
import { Chance } from 'chance';
import config from '../../src/config';
import { signUserToken } from '../../src/utils/signUserToken';
import { User, UserSubscription, UserType } from '../../src/core/users/User';
import { PaymentIntent, PaymentIntentCrypto, PaymentIntentFiat, PromotionCode } from '../../src/types/payment';
import { RenewalPeriod, SubscriptionCreated } from '../../src/types/subscription';
Expand Down Expand Up @@ -132,7 +133,12 @@ export const getValidGatewayToken = () => {
};

export const getValidUserToken = (payload: { customerId?: string; invoiceId?: string }): string => {
return jwt.sign(payload, config.JWT_SECRET);
return signUserToken(payload);
};

export const getExpiredUserToken = (payload: { customerId?: string; invoiceId?: string }): string => {
const twoHoursAgoInSeconds = Math.floor(Date.now() / 1000) - 2 * 60 * 60;
return jwt.sign({ ...payload, iat: twoHoursAgoInSeconds, exp: twoHoursAgoInSeconds + 60 * 60 }, config.JWT_SECRET);
};

export const getCustomer = (params?: Partial<Stripe.Customer>): Stripe.Customer => {
Expand Down
8 changes: 8 additions & 0 deletions tests/src/utils/signUserToken.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,12 @@ describe('Signing user token', () => {

expect(decodedToken.invoiceId).toBe(invoiceId);
});

test('When a token is signed, then it expires six hours later', () => {
const token = signUserToken({ customerId: 'cus_123' });

const { iat, exp } = jwt.verify(token, config.JWT_SECRET) as { iat: number; exp: number };

expect(exp - iat).toBe(6 * 60 * 60);
});
});
Loading