Skip to content
Open
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
18 changes: 16 additions & 2 deletions src/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down Expand Up @@ -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:***'");
}
43 changes: 20 additions & 23 deletions src/interactions/statementInteractionCAMT.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<?xml ... ?>`
// 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 `<?xml ... ?>`
// 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 = [];
}
Expand Down
10 changes: 3 additions & 7 deletions src/interactions/statementInteractionMT940.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
}
Expand Down
21 changes: 20 additions & 1 deletion src/segment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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;
}
75 changes: 75 additions & 0 deletions src/tests/credentialRedaction.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
23 changes: 23 additions & 0 deletions src/tests/statementParseFailure.test.ts
Original file line number Diff line number Diff line change
@@ -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 = '<?xml version="1.0" encoding="UTF-8"?><Document><BkToCstmrAcctRpt><Rpt>';
expect(() => interaction.handleResponse(hicazResponse(broken), clientResponse)).toThrow();
});
});