diff --git a/src/httpClient.ts b/src/httpClient.ts index 174c623..badb19f 100644 --- a/src/httpClient.ts +++ b/src/httpClient.ts @@ -1,6 +1,13 @@ import { type CustomerMessage, type CustomerOrderMessage, Message } from './message.js'; export class HttpClient { + /** + * How long to wait for the bank's answer to one message, in milliseconds. Unset (the + * default) waits as long as the connection lasts; set it so that a bank that doesn't + * answer can't keep a dialog (and the caller) waiting forever. + */ + static timeoutMs: number | undefined = undefined; + constructor( public url: string, public debug = false, @@ -25,6 +32,8 @@ export class HttpClient { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: requestBuffer.toString('base64'), + signal: + HttpClient.timeoutMs === undefined ? undefined : AbortSignal.timeout(HttpClient.timeoutMs), }); if (response.ok) { @@ -50,8 +59,12 @@ export class HttpClient { } return responseMessage; } catch (error) { - console.error('Error decoding response message:', error); - console.error('Response Message Content:\n', responseText.split("'").join('\n')); + // The response carries account data (balances, bookings, names), so it is only + // printed when debugging was asked for + if (this.debug) { + console.error('Error decoding response message:', error); + console.error('Response Message Content:\n', responseText.split("'").join('\n')); + } throw error; } } else { diff --git a/src/interactions/customerInteraction.ts b/src/interactions/customerInteraction.ts index 5ddb8e6..8338168 100644 --- a/src/interactions/customerInteraction.ts +++ b/src/interactions/customerInteraction.ts @@ -44,6 +44,13 @@ export interface ClientResponse { export interface StatementResponse extends ClientResponse { statements: Statement[]; + /** + * The statement documents exactly as the bank sent them: one CAMT XML document per + * booking day (already decoded to a string), or the MT940 stream as one document. + * Lets callers run their own parser, e.g. to read fields the built-in parsers skip + * or to treat downloaded and uploaded statements alike. + */ + rawDocuments?: { format: 'camt' | 'mt940'; content: string }[]; } export abstract class CustomerInteraction { diff --git a/src/interactions/statementInteractionCAMT.ts b/src/interactions/statementInteractionCAMT.ts index 3644f23..3630794 100644 --- a/src/interactions/statementInteractionCAMT.ts +++ b/src/interactions/statementInteractionCAMT.ts @@ -56,24 +56,27 @@ export class StatementInteractionCAMT extends CustomerOrderInteraction { .findAllSegments(HICAZ.Id) .flatMap((segment) => segment.bookedTransactions ?? []); - if (camtMessages.length > 0) { + // Decode every document first, so callers get all of them as the bank sent them, + // even when the built-in parser fails on one + const xmlStrings = camtMessages.map((camtMessage) => { + // The regex looks for the XML declaration `` + // and checks if it contains the attribute encoding="UTF-8". + // The 'i' flag makes the match case-insensitive (e.g., for "utf-8"). + const isUtf8Encoded = /<\?xml[^>]*encoding="UTF-8"[^>]*\?>/i.test(camtMessage); + // camtMessage is initially encoded as 'latin1' (ISO-8859-1), but actually contains UTF-8 data. + // Therefore, we need to first convert it back to a buffer using 'latin1', and then decode it as 'utf8'. + return isUtf8Encoded ? Buffer.from(camtMessage, 'latin1').toString('utf8') : camtMessage; + }); + clientResponse.rawDocuments = xmlStrings.map((content) => ({ + format: 'camt' as const, + content, + })); + + if (xmlStrings.length > 0) { try { // Parse all CAMT messages (one per booking day) and combine statements const allStatements: Statement[] = []; - for (const camtMessage of camtMessages) { - // The regex looks for the XML declaration `` - // and checks if it contains the attribute encoding="UTF-8". - // The 'i' flag makes the match case-insensitive (e.g., for "utf-8"). - const isUtf8Encoded = /<\?xml[^>]*encoding="UTF-8"[^>]*\?>/i.test(camtMessage); - - let xmlString: string = camtMessage; - if (isUtf8Encoded) { - // camtMessage is initially encoded as 'latin1' (ISO-8859-1), but actually contains UTF-8 data. - // Therefore, we need to first convert it back to a buffer using 'latin1', and then decode it as 'utf8'. - const intermediateBuffer = Buffer.from(camtMessage, 'latin1'); - xmlString = intermediateBuffer.toString('utf8'); - } - + for (const xmlString of xmlStrings) { const parser = new CamtParser(xmlString); const statements = parser.parse(); allStatements.push(...statements); diff --git a/src/interactions/statementInteractionMT940.ts b/src/interactions/statementInteractionMT940.ts index 5c9c9da..e0f2416 100644 --- a/src/interactions/statementInteractionMT940.ts +++ b/src/interactions/statementInteractionMT940.ts @@ -49,6 +49,10 @@ export class StatementInteractionMT940 extends CustomerOrderInteraction { .filter((booked) => !!booked) .join(''); + clientResponse.rawDocuments = bookedTransactions + ? [{ format: 'mt940', content: bookedTransactions }] + : []; + if (bookedTransactions) { try { const parser = new Mt940Parser(bookedTransactions); diff --git a/src/tests/rawStatementsAndHttpClient.test.ts b/src/tests/rawStatementsAndHttpClient.test.ts new file mode 100644 index 0000000..9c8d2c4 --- /dev/null +++ b/src/tests/rawStatementsAndHttpClient.test.ts @@ -0,0 +1,126 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { HttpClient } from '../httpClient.js'; +import { StatementInteractionCAMT } from '../interactions/statementInteractionCAMT.js'; +import { StatementInteractionMT940 } from '../interactions/statementInteractionMT940.js'; +import { type CustomerMessage, Message } from '../message.js'; +import { HICAZ } from '../segments/HICAZ.js'; +import { registerSegments } from '../segments/registry.js'; + +registerSegments(); + +const CAMT_DESCRIPTOR = 'urn?:iso?:std?:iso?:20022?:tech?:xsd?:camt.052.001.08'; + +const camt = (id: string) => + `` + + `${id}2026-07-01T10:00:00+02:00` + + `${id}DE991234567123456EUR` + + `10.00DBIT` + + `
2026-07-01
2026-07-01
` + + `TXN${id}
`; + +const hicaz = (...docs: string[]) => + `HICAZ:5:1+DE991234567123456:BANK12+${CAMT_DESCRIPTOR}+${docs.map((d) => `@${d.length}@${d}`).join(':')}'`; + +const MT940 = + ':20:STARTUMS\r\n:25:12030000/1234567890\r\n:28C:00001/001\r\n:60F:C260701EUR100,00\r\n' + + ':61:2607010701DR10,00NMSCNONREF\r\n:86:166?00GUTSCHRIFT?20SVWZ+Test\r\n:62F:C260701EUR90,00\r\n-\r\n'; + +describe('rawDocuments: statements as the bank sent them', () => { + it('CAMT: one document per booking day, in order, even when the built-in parser fails', () => { + const message = Message.decode(`${hicaz(camt('A'))}${hicaz(camt('B'))}`); + const clientResponse = { statements: [] } as never as { + statements: unknown[]; + rawDocuments?: { format: string; content: string }[]; + }; + new StatementInteractionCAMT('123').handleResponse(message, clientResponse as never); + + expect(clientResponse.rawDocuments).toEqual([ + { format: 'camt', content: camt('A') }, + { format: 'camt', content: camt('B') }, + ]); + // These minimal documents have no balances, which the built-in parser rejects + expect(clientResponse.statements).toEqual([]); + }); + + it('CAMT: an empty list when the bank sent no bookings', () => { + const message = Message.decode(`HIRMG:3:2+0010::Entgegengenommen.'`); + const clientResponse = { statements: [] } as never as { rawDocuments?: unknown[] }; + new StatementInteractionCAMT('123').handleResponse(message, clientResponse as never); + expect(clientResponse.rawDocuments).toEqual([]); + }); + + it('MT940: the stream as one document', () => { + const message = Message.decode(`HIKAZ:5:7+@${MT940.length}@${MT940}'`); + const clientResponse = { statements: [] } as never as { + statements: unknown[]; + rawDocuments?: { format: string; content: string }[]; + }; + new StatementInteractionMT940('123').handleResponse(message, clientResponse as never); + expect(clientResponse.rawDocuments).toEqual([{ format: 'mt940', content: MT940 }]); + expect(clientResponse.statements.length).toBeGreaterThan(0); + }); +}); + +describe('HttpClient', () => { + const message = { + encode: () => "HNHBK:1:3'", + toString: () => 'HNHBK', + } as unknown as CustomerMessage; + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('waits without a timeout unless one is set', async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error('offline')); + vi.stubGlobal('fetch', fetchMock); + await expect(new HttpClient('http://bank.example').sendMessage(message)).rejects.toThrow( + 'offline', + ); + expect(fetchMock.mock.calls[0][1].signal).toBeUndefined(); + }); + + it('gives every request the timeout that was set', async () => { + const fetchMock = vi.fn().mockRejectedValue(new DOMException('timed out', 'TimeoutError')); + vi.stubGlobal('fetch', fetchMock); + HttpClient.timeoutMs = 30_000; + try { + await expect(new HttpClient('http://bank.example').sendMessage(message)).rejects.toThrow( + 'timed out', + ); + expect(fetchMock.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal); + } finally { + HttpClient.timeoutMs = undefined; + } + }); + + it('does not print an undecodable response (it holds account data) unless debugging', async () => { + const secret = "HIRMG:3:2+0010::Saldo 1.234,56 Max Mustermann DE99'"; + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockImplementation( + async () => new Response(Buffer.from(`garbage${secret}`, 'latin1').toString('base64')), + ), + ); + vi.spyOn(Message, 'decode').mockImplementation(() => { + throw new Error('cannot decode'); + }); + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}); + + await expect(new HttpClient('http://bank.example').sendMessage(message)).rejects.toThrow( + 'cannot decode', + ); + expect(errors).not.toHaveBeenCalled(); + + await expect(new HttpClient('http://bank.example', true).sendMessage(message)).rejects.toThrow( + 'cannot decode', + ); + expect(errors).toHaveBeenCalled(); + }); +}); + +// HICAZ is used through Message.decode above; keep the import explicit for readers +void HICAZ;