feat!: persist T-Bank data and synchronize reads
Backend security / security (push) Successful in 8s
Backend verify / verify (push) Failing after 10m45s
Conventional commits / commits (pull_request) Successful in 29s
Backend security / security (pull_request) Successful in 8s
Backend verify / verify (pull_request) Failing after 10m37s
Backend security / security (push) Successful in 8s
Backend verify / verify (push) Failing after 10m45s
Conventional commits / commits (pull_request) Successful in 29s
Backend security / security (pull_request) Successful in 8s
Backend verify / verify (pull_request) Failing after 10m37s
Store account membership, portfolio, operations, forecasts and market sources in SQLite. Coalesce scoped refreshes, fence connection revisions, preserve complete financial snapshots and stabilize operation period state. BREAKING CHANGE: investment reads return data/meta resource envelopes and locally persisted snapshots; consumers must use the matching OpenAPI contract and explicit synchronization endpoints.
This commit is contained in:
@@ -1,12 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TbankModule } from '../../../integrations/tbank/tbank.module';
|
||||
import { AuthModule } from '../../auth/auth.module';
|
||||
import { PortfolioModule } from '../portfolio/portfolio.module';
|
||||
import { TbankConnectionController } from './tbank-connection.controller';
|
||||
import { TbankConnectionService } from './tbank-connection.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, TbankModule, PortfolioModule],
|
||||
imports: [AuthModule, TbankModule],
|
||||
controllers: [TbankConnectionController],
|
||||
providers: [TbankConnectionService],
|
||||
})
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
jest.mock('../../../prisma/prisma.service', () => ({
|
||||
PrismaService: class PrismaService {},
|
||||
}));
|
||||
|
||||
import type { TbankClient } from '../../../integrations/tbank/tbank.client';
|
||||
import { TbankConnectionService } from './tbank-connection.service';
|
||||
|
||||
describe('TbankConnectionService', () => {
|
||||
const prisma = {
|
||||
tbankConnection: {
|
||||
findUnique: jest.fn(),
|
||||
upsert: jest.fn(),
|
||||
deleteMany: jest.fn(),
|
||||
},
|
||||
};
|
||||
const tokens = {
|
||||
encrypt: jest.fn((value: string) => `encrypted:${value}`),
|
||||
translateInvalidToken: jest.fn(
|
||||
async (operation: () => Promise<unknown>) => {
|
||||
try {
|
||||
return await operation();
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN')
|
||||
throw new BadRequestException({ code: 'INVALID_TBANK_TOKEN' });
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
),
|
||||
};
|
||||
const tbank: jest.Mocked<Pick<TbankClient, 'validateToken'>> = {
|
||||
validateToken: jest.fn(),
|
||||
};
|
||||
const portfolio = { invalidate: jest.fn() };
|
||||
const service = new TbankConnectionService(
|
||||
prisma as never,
|
||||
tokens as never,
|
||||
tbank,
|
||||
portfolio as never,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
tbank.validateToken.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it('does not persist an invalid token', async () => {
|
||||
tbank.validateToken.mockRejectedValueOnce(new Error('INVALID_TBANK_TOKEN'));
|
||||
|
||||
await expect(service.put('user-1', ' token ')).rejects.toEqual(
|
||||
expect.any(BadRequestException),
|
||||
);
|
||||
expect(prisma.tbankConnection.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('validates and encrypts a candidate token before persisting it', async () => {
|
||||
const connectedAt = new Date('2026-08-25T09:00:00.000Z');
|
||||
prisma.tbankConnection.upsert.mockResolvedValue({ connectedAt });
|
||||
|
||||
await expect(service.put('user-1', ' token ')).resolves.toEqual({
|
||||
connected: true,
|
||||
connectedAt: '2026-08-25T09:00:00.000Z',
|
||||
});
|
||||
|
||||
expect(tokens.translateInvalidToken).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
);
|
||||
expect(tbank.validateToken).toHaveBeenCalledWith('token');
|
||||
expect(tokens.encrypt).toHaveBeenCalledWith('token');
|
||||
expect(prisma.tbankConnection.upsert).toHaveBeenCalledWith({
|
||||
where: { userId: 'user-1' },
|
||||
create: {
|
||||
userId: 'user-1',
|
||||
encryptedToken: 'encrypted:token',
|
||||
connectedAt: expect.any(Date) as Date,
|
||||
},
|
||||
update: {
|
||||
encryptedToken: 'encrypted:token',
|
||||
connectedAt: expect.any(Date) as Date,
|
||||
},
|
||||
});
|
||||
expect(portfolio.invalidate).toHaveBeenCalledWith('user-1');
|
||||
});
|
||||
|
||||
it('re-encrypts the same plaintext token for every successful replacement', async () => {
|
||||
const connectedAt = new Date('2026-08-25T09:00:00.000Z');
|
||||
prisma.tbankConnection.upsert.mockResolvedValue({ connectedAt });
|
||||
tokens.encrypt
|
||||
.mockReturnValueOnce('encrypted:first-nonce')
|
||||
.mockReturnValueOnce('encrypted:second-nonce');
|
||||
|
||||
await service.put('user-1', 'same-token');
|
||||
await service.put('user-1', 'same-token');
|
||||
|
||||
expect(prisma.tbankConnection.upsert).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
update: expect.objectContaining({
|
||||
encryptedToken: 'encrypted:first-nonce',
|
||||
}) as object,
|
||||
}),
|
||||
);
|
||||
expect(prisma.tbankConnection.upsert).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
update: expect.objectContaining({
|
||||
encryptedToken: 'encrypted:second-nonce',
|
||||
}) as object,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('deletes a connection idempotently', async () => {
|
||||
await service.delete('user-1');
|
||||
|
||||
expect(prisma.tbankConnection.deleteMany).toHaveBeenCalledWith({
|
||||
where: { userId: 'user-1' },
|
||||
});
|
||||
expect(portfolio.invalidate).toHaveBeenCalledWith('user-1');
|
||||
});
|
||||
});
|
||||
@@ -2,9 +2,9 @@ import { BadRequestException, Inject, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
TbankClient,
|
||||
TbankTokenService,
|
||||
supportedTbankAccounts,
|
||||
} from '../../../integrations/tbank/tbank.api';
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
import { PortfolioService } from '../portfolio/portfolio.api';
|
||||
|
||||
type TbankTokenValidator = Pick<TbankClient, 'validateToken'>;
|
||||
|
||||
@@ -14,7 +14,6 @@ export class TbankConnectionService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly tokens: TbankTokenService,
|
||||
@Inject(TbankClient) private readonly tbank: TbankTokenValidator,
|
||||
private readonly portfolio: PortfolioService,
|
||||
) {}
|
||||
|
||||
async status(userId: string) {
|
||||
@@ -30,23 +29,34 @@ export class TbankConnectionService {
|
||||
async put(userId: string, value: string) {
|
||||
const token = value.trim();
|
||||
if (!token) throw new BadRequestException({ code: 'VALIDATION_ERROR' });
|
||||
await this.tokens.translateInvalidToken(() =>
|
||||
const accounts = await this.tokens.translateInvalidToken(() =>
|
||||
this.tbank.validateToken(token),
|
||||
);
|
||||
const encryptedToken = this.tokens.encrypt(token);
|
||||
const connection = await this.prisma.tbankConnection.upsert({
|
||||
where: { userId },
|
||||
create: {
|
||||
userId,
|
||||
encryptedToken,
|
||||
connectedAt: new Date(),
|
||||
},
|
||||
update: {
|
||||
encryptedToken,
|
||||
connectedAt: new Date(),
|
||||
},
|
||||
const connection = await this.prisma.$transaction(async (tx) => {
|
||||
// Cascade old private data and attempts in the same transaction that
|
||||
// publishes the validated membership and the new connection revision.
|
||||
await tx.tbankConnection.deleteMany({ where: { userId } });
|
||||
const now = new Date();
|
||||
return tx.tbankConnection.create({
|
||||
data: {
|
||||
userId,
|
||||
encryptedToken,
|
||||
connectedAt: now,
|
||||
membershipAt: now,
|
||||
membershipRevision: 1,
|
||||
accounts: {
|
||||
create: supportedTbankAccounts(accounts).map(
|
||||
({ id, ...account }, upstreamOrder) => ({
|
||||
...account,
|
||||
accountId: id,
|
||||
upstreamOrder,
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
this.portfolio.invalidate(userId);
|
||||
return {
|
||||
connected: true,
|
||||
connectedAt: connection.connectedAt.toISOString(),
|
||||
@@ -55,6 +65,5 @@ export class TbankConnectionService {
|
||||
|
||||
async delete(userId: string): Promise<void> {
|
||||
await this.prisma.tbankConnection.deleteMany({ where: { userId } });
|
||||
this.portfolio.invalidate(userId);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user