diff --git a/src/httpClient.ts b/src/httpClient.ts index 174c623..6e72e7b 100644 --- a/src/httpClient.ts +++ b/src/httpClient.ts @@ -15,7 +15,7 @@ export class HttpClient { console.log('Request Message:\n'); if (this.debugRaw) { - console.log(encodedMessage.split("'").join('\n')); + console.log(redactSignature(encodedMessage).split("'").join('\n')); } else { console.log(message.toString()); } @@ -55,7 +55,21 @@ export class HttpClient { throw error; } } else { - throw Error(`Request failed with status code ${response.status}: ${await response.text()}`); + // The body is left out of the error: errors end up in application logs, and + // a bank's error page may echo parts of the request, which carries the PIN. + const body = await response.text(); + if (this.debug) { + console.log(`Error response:\n${body}`); + } + throw Error(`Request failed with status code ${response.status}`); } } } + +/** + * Replace the signature end segment (HNSHA), which carries the PIN and TAN, in an encoded + * message. A segment ends at the first `'` that is not escaped with `?`. + */ +export function redactSignature(encodedMessage: string): string { + return encodedMessage.replace(/HNSHA:(?:\?.|[^'?])*'/g, "HNSHA:***'"); +} diff --git a/src/interactions/statementInteractionCAMT.ts b/src/interactions/statementInteractionCAMT.ts index 3644f23..deda708 100644 --- a/src/interactions/statementInteractionCAMT.ts +++ b/src/interactions/statementInteractionCAMT.ts @@ -57,32 +57,29 @@ export class StatementInteractionCAMT extends CustomerOrderInteraction { .flatMap((segment) => segment.bookedTransactions ?? []); if (camtMessages.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); + // A parse failure is thrown: an empty result would look like an account + // without transactions. + // 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'); - } - - const parser = new CamtParser(xmlString); - const statements = parser.parse(); - allStatements.push(...statements); + 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'); } - clientResponse.statements = allStatements; - } catch (error) { - console.warn('CAMT parsing failed:', error); - clientResponse.statements = []; + + const parser = new CamtParser(xmlString); + const statements = parser.parse(); + allStatements.push(...statements); } + clientResponse.statements = allStatements; } else { clientResponse.statements = []; } diff --git a/src/interactions/statementInteractionMT940.ts b/src/interactions/statementInteractionMT940.ts index 5c9c9da..93336c4 100644 --- a/src/interactions/statementInteractionMT940.ts +++ b/src/interactions/statementInteractionMT940.ts @@ -50,13 +50,9 @@ export class StatementInteractionMT940 extends CustomerOrderInteraction { .join(''); if (bookedTransactions) { - try { - const parser = new Mt940Parser(bookedTransactions); - clientResponse.statements = parser.parse(); - } catch (error) { - console.warn('MT940 parsing failed:', error); - clientResponse.statements = []; - } + // A parse failure is thrown: an empty result would look like an account + // without transactions. + clientResponse.statements = new Mt940Parser(bookedTransactions).parse(); } else { clientResponse.statements = []; } diff --git a/src/segment.ts b/src/segment.ts index 1544a13..12b9775 100644 --- a/src/segment.ts +++ b/src/segment.ts @@ -61,7 +61,7 @@ export function encode(data: Segment): string { } export function segmentToString(segment: Segment): string { - const keyedSegment = segment as { [key: string]: unknown }; + const keyedSegment = withoutCredentials(segment) as { [key: string]: unknown }; const number = segment.header.segNr?.toString() ?? '?'; const segId = @@ -93,3 +93,22 @@ export function segmentToString(segment: Segment): string { text += `; ${texts.filter((text) => !!text).join('; ')}`; return text; } + +/** + * The signature end (HNSHA) carries the PIN and TAN. They are replaced before a segment + * is turned into text, so debug output never shows them. + */ +function withoutCredentials(segment: Segment): Segment { + if (segment.header.segId !== 'HNSHA') { + return segment; + } + const signature = (segment as { customSignature?: { pin?: string; tan?: string } }) + .customSignature; + if (!signature) { + return segment; + } + return { + ...segment, + customSignature: { pin: '***', ...(signature.tan ? { tan: '***' } : {}) }, + } as Segment; +} diff --git a/src/tests/credentialRedaction.test.ts b/src/tests/credentialRedaction.test.ts new file mode 100644 index 0000000..e642832 --- /dev/null +++ b/src/tests/credentialRedaction.test.ts @@ -0,0 +1,75 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { HttpClient, redactSignature } from '../httpClient.js'; +import { CustomerMessage } from '../message.js'; +import { HKIDN, type HKIDNSegment } from '../segments/HKIDN.js'; +import { registerSegments } from '../segments/registry.js'; + +registerSegments(); + +// Characters that FinTS escapes, so the redaction has to follow escaped segment ends. +const PIN = "S3cr3t?+:'PIN"; +const TAN = '654321'; + +function signedMessage(): CustomerMessage { + const message = new CustomerMessage('0', 1); + const hkidn: HKIDNSegment = { + header: { segId: HKIDN.Id, segNr: 0, version: HKIDN.Version }, + bank: { country: 280, bankId: '12030000' }, + customerId: '12345678', + systemId: '0', + systemIdRequired: 1, + }; + message.addSegment(hkidn); + message.sign(280, '12030000', '12345678', PIN, '0', 900, TAN); + return message; +} + +describe('credentials in debug output', () => { + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('the encoded message carries the PIN, the redacted one does not', () => { + const encoded = signedMessage().encode(); + expect(encoded).toContain('S3cr3t'); + const redacted = redactSignature(encoded); + expect(redacted).not.toContain('S3cr3t'); + expect(redacted).not.toContain(TAN); + expect(redacted).toContain("HNSHA:***'"); + }); + + it('the readable message text does not show PIN or TAN', () => { + const text = signedMessage().toString(); + expect(text).toContain('HNSHA'); + expect(text).not.toContain('S3cr3t'); + expect(text).not.toContain(TAN); + }); + + it('neither debug mode logs the PIN', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('down', { status: 503 })), + ); + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + for (const raw of [false, true]) { + await expect( + new HttpClient('http://bank.example', true, raw).sendMessage(signedMessage()), + ).rejects.toThrow(); + } + const logged = log.mock.calls.flat().join('\n'); + expect(logged).not.toContain('S3cr3t'); + expect(logged).not.toContain(TAN); + }); + + it('a failed request does not put the response body into the error', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(`echo: ${PIN}`, { status: 500 })), + ); + const error = await new HttpClient('http://bank.example') + .sendMessage(signedMessage()) + .catch((e) => e); + expect(error.message).toBe('Request failed with status code 500'); + }); +}); diff --git a/src/tests/statementParseFailure.test.ts b/src/tests/statementParseFailure.test.ts new file mode 100644 index 0000000..93f72ab --- /dev/null +++ b/src/tests/statementParseFailure.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; +import type { StatementResponse } from '../interactions/customerInteraction.js'; +import { StatementInteractionCAMT } from '../interactions/statementInteractionCAMT.js'; +import { Message } from '../message.js'; +import { registerSegments } from '../segments/registry.js'; + +registerSegments(); + +const CAMT_DESCRIPTOR = 'urn?:iso?:std?:iso?:20022?:tech?:xsd?:camt.052.001.08'; + +function hicazResponse(camtDocument: string): Message { + const hicaz = `HICAZ:5:1+DE991234567123456:BANK12+${CAMT_DESCRIPTOR}+@${camtDocument.length}@${camtDocument}'`; + return Message.decode(`HIRMG:3:2+0020::Abfrage erfolgreich.'${hicaz}`); +} + +describe('statement parse failures', () => { + it('a CAMT document that cannot be parsed is an error, not an empty account', () => { + const interaction = new StatementInteractionCAMT('123456'); + const clientResponse = { statements: [] } as unknown as StatementResponse; + const broken = ''; + expect(() => interaction.handleResponse(hicazResponse(broken), clientResponse)).toThrow(); + }); +});