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
4 changes: 2 additions & 2 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ This TypeScript library implements the German FinTS 3.0 banking protocol for sec

### Core Components

- **`FinTSClient`**: Main API - handles account balances, statements, portfolios, and credit card data
- **`FinTSClient`**: Main API - handles account balances, statements, portfolios, credit card data and SEPA credit transfers
- **`FinTSConfig`**: Configuration factory with two modes: `forFirstTimeUse()` and `fromBankingInformation()`
- **Segments**: FinTS protocol message units (see `src/segments/`) - each has request/response pairs (e.g., `HKSAL`/`HISAL`)
- **Interactions**: High-level transaction orchestrators (see `src/interactions/`) that combine multiple segments
Expand Down Expand Up @@ -111,7 +111,7 @@ Check capability with `can*()` methods (e.g., `canGetAccountBalance()`). Not all

- **FinTS 3.0 only** - older protocol versions not supported
- **PIN/TAN authentication only** - no certificate-based auth
- **No payment transactions** - read-only operations (balances, statements, portfolios)
- **Few payment transactions** - besides read-only operations (balances, statements, portfolios) only single SEPA credit transfers (HKCCS, instant HKIPZ) with Verification of Payee (HKVPP/HKVPA)
- **German banking focus** - country code defaults to 280

When extending functionality, follow the established segment definition pattern and ensure proper registration in the registry.
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ The following table shows all transactions supported by the FinTSClient interfac
| **Portfolio** | `getPortfolio(account: AccountRef, currency?, priceQuality?, maxEntries?)` | Fetches securities portfolio information for depot accounts | HKWPD | ✓ | ✓ |
| **Credit Card Statements** | `getCreditCardStatements(account: AccountRef, from?, to?)` | Fetches credit card statements for credit card accounts | HKKKU, DKKKU | ✓ | ✓ |
| **Electronic Statements** | `getElectronicStatements(account: AccountRef, options?)` | Fetches the statement document from the electronic mailbox, usually a PDF | HKEKA | ✓ | ✓ |
| **SEPA Credit Transfer** | `transfer(account: AccountRef, sepaDescriptor, painMessage, instant?)` | Sends a single SEPA credit transfer (pain.001), regular or instant, with Verification of Payee | HKCCS, HKIPZ, HKVPP, HKVPA | ✓ | ✓ |
| **TAN Method Selection** | `selectTanMethod(tanMethodId)` | Selects a TAN method by ID from available methods | - | ❌ | ❌ |
| **TAN Media Selection** | `selectTanMedia(tanMediaName)` | Selects a specific TAN media device by name | - | ❌ | ❌ |

Expand All @@ -223,6 +224,7 @@ For each account-specific transaction, the client provides corresponding `can*`
| `canGetPortfolio(account?: AccountRef)` | Checks if portfolio information fetching is supported |
| `canGetCreditCardStatements(account?: AccountRef)` | Checks if credit card statements fetching is supported |
| `canGetElectronicStatements(account?: AccountRef)` | Checks if electronic account statements fetching is supported |
| `canTransfer(account?: AccountRef, instant?)` | Checks if (instant) SEPA credit transfers are supported |

### Transaction Parameters

Expand Down Expand Up @@ -274,14 +276,41 @@ Every transaction that supports TAN authentication has a corresponding `*WithTan
- `getAccountStatementsWithTan(tanReference, tan?)`
- `getPortfolioWithTan(tanReference, tan?)`
- `getCreditCardStatementsWithTan(tanReference, tan?)`
- `transferWithTan(tanReference, tan?)`

The `tan` parameter can be omitted when using decoupled TAN methods.

### SEPA credit transfers and Verification of Payee

`transfer()` sends one SEPA credit transfer. The caller builds the complete pain.001 document (one transaction) and passes the format the bank lists in the HISPAS parameters (`config.getTransactionParameters<HISPASParameter>('HKSPA')?.supportedSepaFormats`). With `instant = true` it goes as an instant transfer (HKIPZ); the pain.001 should then carry `<LclInstrm><Cd>INST</Cd></LclInstrm>`.

Since October 2025 banks check the payee's name before executing a transfer (Verification of Payee, VoP). Where the BPD list HKVPP, the library sends the name check along and may come back with `requiresVopConfirmation`: the bank has checked the name and waits for the customer's go-ahead. Show `response.vop` (result `RCVC` match, `RVMC` close match with `differentName`, `RVNM` no match, `RVNA` not possible, plus the bank's `infoText`) and call `confirmTransfer()` only if the customer still wants to pay. Without it the bank executes nothing.

```typescript
let response = await client.transfer(account, sepaDescriptor, painXml, true);

if (response.requiresVopConfirmation) {
// response.vop.result: 'RCVC' | 'RVMC' | 'RVNM' | 'RVNA' | ...
if (!customerAgrees(response.vop)) return; // nothing is executed
response = await client.confirmTransfer();
}

if (response.requiresTan) {
response = await client.transferWithTan(response.tanReference!, userTAN);
}

console.log(response.success, response.bankAnswers);
```

A bank that is still checking the name answers with an Aufsetzpunkt (3040); the dialog then polls on its own, waiting as long as the bank asks. Code 3091 means the bank needs no confirmation and continues with the TAN right away. The message order follows recorded traffic from Atruvia (Volksbanken).

Never send a transfer twice on your own: a network error after sending leaves it open whether the bank received the order.

## Limitations

- Only FinTS 3.0 is supported (older versions may not work)
- Only PIN/TAN security is supported (including decoupled TAN methods)
- No support for payment transactions or transfers yet
- Of the payment transactions, only single SEPA credit transfers (regular and instant) are supported – no batch or scheduled transfers, standing orders or direct debits yet

Implementing further transactions should be straight forward and contributions are highly appreciated

Expand All @@ -291,6 +320,7 @@ Implementing further transactions should be straight forward and contributions a
- DKB
- ING-DiBa
- Renault Bank Direkt
- meine Volksbank Raiffeisenbank (Atruvia) – including SEPA credit transfers, instant transfers and Verification of Payee

## Built With

Expand Down
72 changes: 72 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,17 @@ import {
} from './interactions/portfolioInteraction.js';
import { StatementInteractionCAMT } from './interactions/statementInteractionCAMT.js';
import { StatementInteractionMT940 } from './interactions/statementInteractionMT940.js';
import { TransferInteraction } from './interactions/transferInteraction.js';
import { DKKKU } from './segments/DKKKU.js';
import { HKCAZ } from './segments/HKCAZ.js';
import { HKCCS } from './segments/HKCCS.js';
import { HKEKA } from './segments/HKEKA.js';
import { HKIDN } from './segments/HKIDN.js';
import { HKIPZ } from './segments/HKIPZ.js';
import { HKKAZ } from './segments/HKKAZ.js';
import { HKKKU } from './segments/HKKKU.js';
import { HKSAL } from './segments/HKSAL.js';
import { HKVPP } from './segments/HKVPP.js';
import { HKWPD } from './segments/HKWPD.js';
import type { TanMethod } from './tanMethod.js';

Expand Down Expand Up @@ -98,6 +102,74 @@ export class FinTSClient {
* @param account when the account number is provided, checks if the account supports fetching the balance
* @returns true if the bank (and account) supports fetching the account balance
*/
/**
* Checks if the bank accepts SEPA single credit transfers (HKCCS), or instant ones (HKIPZ)
* @param account - optional, checks the account's allowed transactions as well
* @param instant - SEPA Instant (HKIPZ) instead of a regular transfer
*/
canTransfer(account?: AccountRef, instant = false): boolean {
const segId = instant ? HKIPZ.Id : HKCCS.Id;
return account
? this.config.isAccountTransactionSupported(account, segId)
: this.config.isTransactionSupported(segId);
}

/**
* Sends a SEPA single credit transfer. The bank usually asks for a TAN.
* @param account - the debtor account, must be in config.bankingInformation.upd.bankAccounts
* @param sepaDescriptor - the pain format URN, one the bank lists in HISPAS supportedSepaFormats
* @param painMessage - the complete pain.001 XML document with exactly one transaction
* @param instant - SEPA Instant (HKIPZ): the money arrives within seconds; the pain.001 should carry LclInstrm INST
* @returns the response; success and bankAnswers tell whether the bank accepted the order
*/
async transfer(
account: AccountRef,
sepaDescriptor: string,
painMessage: string,
instant = false,
): Promise<ClientResponse> {
// BPD stored before HIVPPS was understood lack its parameters (the report formats).
// Version 0 makes the bank send the BPD again with this dialog's initialisation.
const bpd = this.config.bankingInformation.bpd;
if (
bpd &&
this.config.isTransactionSupported(HKVPP.Id) &&
!this.config.getTransactionParameters(HKVPP.Id)
) {
bpd.version = 0;
}
return this.startCustomerOrderInteraction(
new TransferInteraction(account, sepaDescriptor, painMessage, instant),
);
}

/**
* Continues a credit transfer when a TAN is required
* @param tanReference The TAN reference provided in the first call's response
* @param tan The TAN entered by the user, can be omitted if a decoupled TAN method is used
*/
/**
* Releases a transfer after Verification of Payee. Call it when `transfer` returned
* `requiresVopConfirmation` and the customer, having seen `vop`, still wants to pay.
* The bank then usually asks for the TAN; continue with `transferWithTan`.
* Not calling it leaves the order unexecuted.
*/
async confirmTransfer(): Promise<ClientResponse> {
if (!this.currentDialog) {
throw new Error('no transfer is waiting for the payee name check to be confirmed');
}
const responses = await this.currentDialog.resume();
return (
responses.get(HKCCS.Id) ??
responses.get(HKIPZ.Id) ??
([...responses.values()].at(-1) as ClientResponse)
);
}

async transferWithTan(tanReference: string, tan?: string): Promise<ClientResponse> {
return this.continueCustomerInteractionWithTan([HKCCS.Id, HKIPZ.Id], tanReference, tan);
}

canGetAccountBalance(account?: AccountRef): boolean {
return account
? this.config.isAccountTransactionSupported(account, HKSAL.Id)
Expand Down
95 changes: 57 additions & 38 deletions src/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import { HKEND } from './segments/HKEND.js';
import { HKTAN, type HKTANSegment } from './segments/HKTAN.js';
import { HNHBK, type HNHBKSegment } from './segments/HNHBK.js';

/** A name check should take seconds; this many polls is plenty */
const MAX_VOP_POLLS = 10;

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export class Dialog {
dialogId: string = '0';
lastMessageNumber = 0;
Expand Down Expand Up @@ -59,18 +64,55 @@ export class Dialog {
throw new Error('dialog start can only be called on a new dialog');
}

return this.run();
}

/**
* Continues a customer order the bank paused for Verification of Payee, once the
* customer has seen the name check and agreed (see FinTSClient.confirmTransfer).
*/
async resume(): Promise<Map<string, ClientResponse>> {
if (this.hasEnded) {
throw Error('cannot resume a customer order when dialog has already ended');
}

if (!this.currentInteraction) {
throw new Error('there is no running customer interaction in this dialog to resume');
}

return this.run();
}

/**
* Sends one message after another until the dialog ends, fails or waits for the
* customer: a TAN, or the release after a name check. A name check the bank has
* not finished yet is asked again after the pause it requests.
*/
private async run(firstMessage?: CustomerMessage): Promise<Map<string, ClientResponse>> {
let clientResponse: ClientResponse;
let message = firstMessage;
let polls = 0;

do {
const message = this.createCurrentCustomerMessage();
const responseMessage = await this.httpClient.sendMessage(message);
await this.handlePartedMessages(message, responseMessage, this.currentInteraction);
const sent = message ?? this.createCurrentCustomerMessage();
message = undefined;
const responseMessage = await this.httpClient.sendMessage(sent);
await this.handlePartedMessages(sent, responseMessage, this.currentInteraction);
clientResponse = this.currentInteraction.handleClientResponse(responseMessage);
this.checkEnded(clientResponse);
this.dialogId = clientResponse.dialogId;
this.responses.set(this.currentInteraction.segId, clientResponse);

if (clientResponse.success && !clientResponse.requiresTan) {
if (clientResponse.vopPending) {
if (++polls > MAX_VOP_POLLS) {
throw new Error('the bank did not finish the payee name check in time');
}
await wait(Math.min(Math.max(clientResponse.vopWaitSeconds ?? 2, 1), 10) * 1000);
} else if (
clientResponse.success &&
!clientResponse.requiresTan &&
!clientResponse.requiresVopConfirmation
) {
this.currentInteractionIndex++;

if (this.currentInteractionIndex > 0) {
Expand All @@ -81,7 +123,8 @@ export class Dialog {
!this.hasEnded &&
this.currentInteractionIndex < this.interactions.length &&
clientResponse.success &&
!clientResponse.requiresTan
!clientResponse.requiresTan &&
!clientResponse.requiresVopConfirmation
);

return this.responses;
Expand All @@ -104,38 +147,7 @@ export class Dialog {
throw new Error('there is no running customer interaction in this dialog to continue');
}

let clientResponse: ClientResponse;

let isFirstMessage = true;

do {
const message = isFirstMessage
? this.createCurrentTanMessage(tanOrderReference, tan)
: this.createCurrentCustomerMessage();
const responseMessage = await this.httpClient.sendMessage(message);
await this.handlePartedMessages(message, responseMessage, this.currentInteraction);
clientResponse = this.currentInteraction.handleClientResponse(responseMessage);
this.checkEnded(clientResponse);
this.dialogId = clientResponse.dialogId;
this.responses.set(this.currentInteraction.segId, clientResponse);

if (clientResponse.success && !clientResponse.requiresTan) {
this.currentInteractionIndex++;

if (this.currentInteractionIndex > 0) {
this.isInitialized = true;
}
}

isFirstMessage = false;
} while (
!this.hasEnded &&
this.currentInteractionIndex < this.interactions.length &&
clientResponse.success &&
!clientResponse.requiresTan
);

return this.responses;
return this.run(this.createCurrentTanMessage(tanOrderReference, tan));
}

addCustomerInteraction(interaction: CustomerInteraction, afterCurrent = false): void {
Expand Down Expand Up @@ -176,7 +188,10 @@ export class Dialog {

const tanMethod = this.config.selectedTanMethod;
const isScaSupported = tanMethod && tanMethod.version >= 6;
let isTanMethodNeeded = isScaSupported && this.currentInteraction.segId !== HKEND.Id;
let isTanMethodNeeded =
isScaSupported &&
this.currentInteraction.segId !== HKEND.Id &&
!this.currentInteraction.withoutTan;

if (isCustomerOrder) {
const bankTransaction = this.config.bankingInformation.bpd?.allowedTransactions.find(
Expand Down Expand Up @@ -213,6 +228,10 @@ export class Dialog {
message.addSegment(hktan);
}

for (const segment of this.currentInteraction.getSegmentsAfterTan(this.config)) {
message.addSegment(segment);
}

return message;
}

Expand Down
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ export * from './electronicStatement.js';
export * from './httpClient.js';
export type { AccountBalanceResponse } from './interactions/balanceInteraction.js';
export type { CreditCardStatementResponse } from './interactions/creditcardStatementInteraction.js';
export type { ClientResponse, StatementResponse } from './interactions/customerInteraction.js';
export type {
ClientResponse,
StatementResponse,
VopResult,
} from './interactions/customerInteraction.js';
export type {
ElectronicStatementOptions,
ElectronicStatementResponse,
Expand All @@ -25,6 +29,7 @@ export * from './message.js';
export * from './mt535parser.js';
export * from './mt940parser.js';
export * from './segment.js';
export type { VopResultCode } from './segments/HIVPP.js';
export { StatementFormat } from './segments/HKEKA.js';
export * from './statement.js';
export * from './upd.js';
31 changes: 31 additions & 0 deletions src/interactions/customerInteraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { Dialog } from '../dialog.js';
import type { Message } from '../message.js';
import type { Segment } from '../segment.js';
import { HITAN, type HITANSegment } from '../segments/HITAN.js';
import type { VopResultCode } from '../segments/HIVPP.js';
import { HNHBK, type HNHBKSegment } from '../segments/HNHBK.js';
import type { Statement } from '../statement.js';

Expand Down Expand Up @@ -40,6 +41,29 @@ export interface ClientResponse {
*/
tanChallengeHhdUc?: string;
tanMediaName?: string;
/**
* Verification of Payee: the bank checked the payee's name and waits for the
* customer to release the order (see FinTSClient.confirmTransfer). The dialog
* stays open until then.
*/
requiresVopConfirmation?: boolean;
/** The bank has not finished the name check yet; the dialog polls again. */
vopPending?: boolean;
/** Seconds the bank asks to wait before polling again */
vopWaitSeconds?: number;
/** Result of the name check, when the bank sent one */
vop?: VopResult;
}

export interface VopResult {
/** RCVC match, RVMC close match, RVNM no match, RVNA not applicable, PDNG pending */
result?: VopResultCode;
/** For a close match: the name the bank has on record */
differentName?: string;
/** Why the check was not possible (RVNA) */
reason?: string;
/** Text the bank wants shown to the customer */
infoText?: string;
}

export interface StatementResponse extends ClientResponse {
Expand All @@ -48,6 +72,13 @@ export interface StatementResponse extends ClientResponse {

export abstract class CustomerInteraction {
dialog?: Dialog;
/** The next message of this interaction goes without HKTAN (a Verification of Payee poll) */
withoutTan = false;

/** Segments that follow HKTAN in the same message (the Verification of Payee request, HKVPP) */
getSegmentsAfterTan(_config: FinTSConfig): Segment[] {
return [];
}

constructor(public segId: string) {}

Expand Down
Loading