diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index dd55ad5..598de59 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -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 @@ -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. diff --git a/README.md b/README.md index 9264dfb..8f3c041 100644 --- a/README.md +++ b/README.md @@ -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 | - | ❌ | ❌ | @@ -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 @@ -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('HKSPA')?.supportedSepaFormats`). With `instant = true` it goes as an instant transfer (HKIPZ); the pain.001 should then carry `INST`. + +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 @@ -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 diff --git a/src/client.ts b/src/client.ts index 678de24..e1ecd09 100644 --- a/src/client.ts +++ b/src/client.ts @@ -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'; @@ -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 { + // 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 { + 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 { + return this.continueCustomerInteractionWithTan([HKCCS.Id, HKIPZ.Id], tanReference, tan); + } + canGetAccountBalance(account?: AccountRef): boolean { return account ? this.config.isAccountTransactionSupported(account, HKSAL.Id) diff --git a/src/dialog.ts b/src/dialog.ts index 1ab6a63..1cccc26 100644 --- a/src/dialog.ts +++ b/src/dialog.ts @@ -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; @@ -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> { + 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> { 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) { @@ -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; @@ -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 { @@ -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( @@ -213,6 +228,10 @@ export class Dialog { message.addSegment(hktan); } + for (const segment of this.currentInteraction.getSegmentsAfterTan(this.config)) { + message.addSegment(segment); + } + return message; } diff --git a/src/index.ts b/src/index.ts index bb330b0..491105c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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, @@ -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'; diff --git a/src/interactions/customerInteraction.ts b/src/interactions/customerInteraction.ts index 5ddb8e6..0de9841 100644 --- a/src/interactions/customerInteraction.ts +++ b/src/interactions/customerInteraction.ts @@ -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'; @@ -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 { @@ -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) {} diff --git a/src/interactions/transferInteraction.ts b/src/interactions/transferInteraction.ts new file mode 100644 index 0000000..3f249fc --- /dev/null +++ b/src/interactions/transferInteraction.ts @@ -0,0 +1,175 @@ +import { internationalAccount } from '../accountDescriptor.js'; +import { type AccountRef, describeAccount } from '../bankAccount.js'; +import type { FinTSConfig } from '../config.js'; +import type { Message } from '../message.js'; +import type { Segment } from '../segment.js'; +import { HITAN, type HITANSegment } from '../segments/HITAN.js'; +import { HIVPP, type HIVPPSegment, type VopResultCode } from '../segments/HIVPP.js'; +import type { HIVPPSParameter } from '../segments/HIVPPS.js'; +import { HKCCS, type HKCCSSegment } from '../segments/HKCCS.js'; +import { HKIPZ } from '../segments/HKIPZ.js'; +import { HKVPA, type HKVPASegment } from '../segments/HKVPA.js'; +import { HKVPP, type HKVPPSegment } from '../segments/HKVPP.js'; +import { type ClientResponse, CustomerOrderInteraction } from './customerInteraction.js'; + +/** Used when the bank names no report format of its own in HIVPPS */ +export const DEFAULT_VOP_REPORT = 'urn:iso:std:iso:20022:tech:xsd:pain.002.001.10'; + +/** Aufsetzpunkt: the bank is still checking, ask again */ +const CONTINUE = 3040; +/** VOP-Ausführungsauftrag nicht benötigt: no HKVPA, the bank goes on by itself */ +const NO_CONFIRMATION_NEEDED = 3091; + +/** + * A SEPA single credit transfer. The caller supplies the complete pain.001 document; + * the bank only confirms or rejects it, so the result is in `bankAnswers`. + * + * Where the bank requires Verification of Payee (HKVPP in the BPD) the order of + * messages follows recorded Atruvia traffic (phpFinTS): + * 1. HKCCS + HKTAN + HKVPP. Usually answered with an Aufsetzpunkt (3040) and a + * polling id: the check is still running. + * 2. HKVPP alone with polling id and Aufsetzpunkt, until HIVPP brings the VOP-ID and + * the result, either as a pain.002 report or as a single result. + * 3. After the customer agrees (FinTSClient.confirmTransfer): HKCCS + HKVPA + HKTAN, + * then the usual TAN challenge. + * Code 3091 says the bank needs no HKVPA; it then asks for the TAN (or is done) right away. + */ +export class TransferInteraction extends CustomerOrderInteraction { + private vopId?: string; + private polling?: { pollingId?: string; continuationMark?: string }; + private vopRequested = false; + + constructor( + public account: AccountRef, + public sepaDescriptor: string, + public painMessage: string, + /** SEPA Instant (HKIPZ) instead of a regular transfer (HKCCS); the pain.001 should say INST */ + public instant = false, + ) { + super(instant ? HKIPZ.Id : HKCCS.Id, ''); + } + + createSegments(init: FinTSConfig): Segment[] { + if (this.polling) { + return [this.hkvpp(init)]; + } + + const bankAccount = init.getBankAccount(this.account); + if (!init.isAccountTransactionSupported(this.account, this.segId)) { + throw Error( + `Account ${describeAccount(this.account)} does not support business transaction '${this.segId}'`, + ); + } + + const version = init.getMaxSupportedTransactionVersion(this.segId); + if (!version) { + throw Error(`There is no supported version for business transaction '${this.segId}'`); + } + + // HKIPZ v1 has the same elements as HKCCS v1. + const hkccs: HKCCSSegment = { + header: { segId: this.segId, segNr: 0, version }, + account: internationalAccount(init, bankAccount), + sepaDescriptor: this.sepaDescriptor, + sepaPainMessage: this.painMessage, + }; + + if (this.vopId) { + const hkvpa: HKVPASegment = { + header: { segId: HKVPA.Id, segNr: 0, version: HKVPA.Version }, + vopId: this.vopId, + }; + return [hkccs, hkvpa]; + } + return [hkccs]; + } + + getSegmentsAfterTan(init: FinTSConfig): Segment[] { + if (this.polling || this.vopId || !init.isTransactionSupported(HKVPP.Id)) { + return []; + } + this.vopRequested = true; + return [this.hkvpp(init)]; + } + + private hkvpp(init: FinTSConfig): HKVPPSegment { + return { + header: { segId: HKVPP.Id, segNr: 0, version: HKVPP.Version }, + supportedReports: [vopReportFormat(init)], + pollingId: this.polling?.pollingId, + continuationMark: this.polling?.continuationMark, + }; + } + + protected handleResponse(response: Message, clientResponse: ClientResponse): void { + this.withoutTan = false; + const hivpp = response.findSegment(HIVPP.Id); + if (!this.vopRequested || (!hivpp && !this.polling)) { + return; + } + + const continuation = clientResponse.bankAnswers.find((a) => a.code === CONTINUE); + if (continuation) { + this.polling = { pollingId: hivpp?.pollingId, continuationMark: continuation.params?.[0] }; + this.withoutTan = true; + clientResponse.vopPending = true; + clientResponse.vopWaitSeconds = hivpp?.waitSeconds; + return; + } + this.polling = undefined; + + if (!hivpp) { + throw new Error('the bank ended the payee name check without a result (HIVPP)'); + } + clientResponse.vop = { + result: vopResult(hivpp), + differentName: hivpp.result?.differentName, + reason: hivpp.result?.reason, + infoText: hivpp.infoText, + }; + + if (clientResponse.bankAnswers.some((a) => a.code === NO_CONFIRMATION_NEEDED)) { + // The bank goes straight on: a TAN challenge, or nothing left to do. + const hitan = response.findSegment(HITAN.Id); + if (hitan?.orderReference && hitan.orderReference !== 'noref') { + clientResponse.requiresTan = true; + clientResponse.tanReference = hitan.orderReference; + clientResponse.tanChallenge = hitan.challenge ?? ''; + } + return; + } + + if (!hivpp.vopId) { + throw new Error('the bank sent the payee name check without a VOP-ID'); + } + this.vopId = hivpp.vopId; + clientResponse.requiresVopConfirmation = true; + } +} + +/** + * The result from HIVPP: the single result group, or the status in the pain.002 + * report. For a single transfer the transaction status says more than the group + * status (RVCM = "partial", i.e. close match or no match). + */ +function vopResult(hivpp: HIVPPSegment): VopResultCode | undefined { + if (hivpp.result?.result) { + return hivpp.result.result; + } + const report = hivpp.report ?? ''; + const group = /\s*(\w{4})\s*<\/GrpSts>/.exec(report)?.[1]; + const single = /\s*1\s*<\/OrgnlNbOfTxs>/.test(report) + ? /\s*(\w{4})\s*<\/TxSts>/.exec(report)?.[1] + : undefined; + return (single ?? group) as VopResultCode | undefined; +} + +/** The bank's first pain.002 format for the report, or the DK default */ +function vopReportFormat(config: FinTSConfig): string { + const params = config.getTransactionParameters(HKVPP.Id); + const formats = (params?.supportedReports ?? '') + .split(';') + .map((f) => f.trim()) + .filter(Boolean); + return formats[0] ?? DEFAULT_VOP_REPORT; +} diff --git a/src/segments/HIVPP.ts b/src/segments/HIVPP.ts new file mode 100644 index 0000000..54ddfc7 --- /dev/null +++ b/src/segments/HIVPP.ts @@ -0,0 +1,62 @@ +import { AlphaNumeric } from '../dataElements/AlphaNumeric.js'; +import { Binary } from '../dataElements/Binary.js'; +import { Numeric } from '../dataElements/Numeric.js'; +import { DataGroup } from '../dataGroups/DataGroup.js'; +import { TimeStampGroup } from '../dataGroups/TimeStamp.js'; +import type { Segment } from '../segment.js'; +import { SegmentDefinition } from '../segmentDefinition.js'; + +/** RCVC match, RVMC close match, RVNM no match, RVNA not applicable, RVCM partial (several), PDNG pending */ +export type VopResultCode = 'RCVC' | 'RVMC' | 'RVNM' | 'RVNA' | 'RVCM' | 'PDNG'; + +export type HIVPPSegment = Segment & { + vopId?: string; + vopIdValidUntil?: { date: Date; time?: Date }; + pollingId?: string; + reportDescriptor?: string; + report?: string; + result?: { + iban: string; + ibanAddition?: string; + differentName?: string; + otherIdentifier?: string; + result: VopResultCode; + reason?: string; + }; + infoText?: string; + waitSeconds?: number; +}; + +/** + * Verification of Payee: result of the name check + */ +export class HIVPP extends SegmentDefinition { + static Id = 'HIVPP'; + static Version = 1; + constructor() { + super(HIVPP.Id); + } + version = HIVPP.Version; + elements = [ + new Binary('vopId', 0, 1, 1024), + new TimeStampGroup('vopIdValidUntil', 0, 1), + new Binary('pollingId', 0, 1), + new AlphaNumeric('reportDescriptor', 0, 1, 256), + new Binary('report', 0, 1), + new DataGroup( + 'result', + [ + new AlphaNumeric('iban', 1, 1, 34), + new AlphaNumeric('ibanAddition', 0, 1, 140), + new AlphaNumeric('differentName', 0, 1, 140), + new AlphaNumeric('otherIdentifier', 0, 1, 256), + new AlphaNumeric('result', 1, 1, 4), + new AlphaNumeric('reason', 0, 1, 256), + ], + 0, + 1, + ), + new AlphaNumeric('infoText', 0, 1, 65535), + new Numeric('waitSeconds', 0, 1, 1), + ]; +} diff --git a/src/segments/HIVPPS.ts b/src/segments/HIVPPS.ts new file mode 100644 index 0000000..43fbd86 --- /dev/null +++ b/src/segments/HIVPPS.ts @@ -0,0 +1,41 @@ +import { AlphaNumeric } from '../dataElements/AlphaNumeric.js'; +import { Numeric } from '../dataElements/Numeric.js'; +import { YesNo } from '../dataElements/YesNo.js'; +import { + BusinessTransactionParameter, + type BusinessTransactionParameterSegment, +} from './businessTransactionParameter.js'; + +export type HIVPPSSegment = BusinessTransactionParameterSegment; + +export type HIVPPSParameter = { + maxEntriesOptIn: number; + infoTextFormatted: boolean; + reportDelivery: string; + multipleAllowed: boolean; + entryCountAllowed: boolean; + /** Supported payment status report formats, separated by ';' */ + supportedReports: string; + /** The payment orders (HK...) that need a name check */ + orders?: string[]; +}; + +/** + * Parameters for HKVPP - Verification of Payee + */ +export class HIVPPS extends BusinessTransactionParameter { + static Id = 'HIVPPS'; + version = 1; + + constructor() { + super(HIVPPS.Id, [ + new Numeric('maxEntriesOptIn', 1, 1, 7), + new YesNo('infoTextFormatted', 1, 1), + new AlphaNumeric('reportDelivery', 1, 1, 1), + new YesNo('multipleAllowed', 1, 1), + new YesNo('entryCountAllowed', 1, 1), + new AlphaNumeric('supportedReports', 1, 1, 1024), + new AlphaNumeric('orders', 0, 999, 6), + ]); + } +} diff --git a/src/segments/HKCCS.ts b/src/segments/HKCCS.ts new file mode 100644 index 0000000..84abe9c --- /dev/null +++ b/src/segments/HKCCS.ts @@ -0,0 +1,31 @@ +import { AlphaNumeric } from '../dataElements/AlphaNumeric.js'; +import { Binary } from '../dataElements/Binary.js'; +import { + type InternationalAccount, + InternationalAccountGroup, +} from '../dataGroups/InternationalAccount.js'; +import type { Segment } from '../segment.js'; +import { SegmentDefinition } from '../segmentDefinition.js'; + +export type HKCCSSegment = Segment & { + account: InternationalAccount; + sepaDescriptor: string; + sepaPainMessage: string; +}; + +/** + * SEPA single credit transfer (SEPA-Einzelüberweisung) + */ +export class HKCCS extends SegmentDefinition { + static Id = 'HKCCS'; + static Version = 1; + constructor() { + super(HKCCS.Id); + } + version = HKCCS.Version; + elements = [ + new InternationalAccountGroup('account', 1, 1), + new AlphaNumeric('sepaDescriptor', 1, 1, 256), + new Binary('sepaPainMessage', 1, 1), + ]; +} diff --git a/src/segments/HKIPZ.ts b/src/segments/HKIPZ.ts new file mode 100644 index 0000000..60c3b9d --- /dev/null +++ b/src/segments/HKIPZ.ts @@ -0,0 +1,31 @@ +import { AlphaNumeric } from '../dataElements/AlphaNumeric.js'; +import { Binary } from '../dataElements/Binary.js'; +import { + type InternationalAccount, + InternationalAccountGroup, +} from '../dataGroups/InternationalAccount.js'; +import type { Segment } from '../segment.js'; +import { SegmentDefinition } from '../segmentDefinition.js'; + +export type HKIPZSegment = Segment & { + account: InternationalAccount; + sepaDescriptor: string; + sepaPainMessage: string; +}; + +/** + * SEPA instant credit transfer (SEPA-Instant Payment Zahlung), built like HKCCS + */ +export class HKIPZ extends SegmentDefinition { + static Id = 'HKIPZ'; + static Version = 1; + constructor() { + super(HKIPZ.Id); + } + version = HKIPZ.Version; + elements = [ + new InternationalAccountGroup('account', 1, 1), + new AlphaNumeric('sepaDescriptor', 1, 1, 256), + new Binary('sepaPainMessage', 1, 1), + ]; +} diff --git a/src/segments/HKVPA.ts b/src/segments/HKVPA.ts new file mode 100644 index 0000000..125ea3d --- /dev/null +++ b/src/segments/HKVPA.ts @@ -0,0 +1,21 @@ +import { Binary } from '../dataElements/Binary.js'; +import type { Segment } from '../segment.js'; +import { SegmentDefinition } from '../segmentDefinition.js'; + +export type HKVPASegment = Segment & { + vopId: string; +}; + +/** + * Verification of Payee: release the payment order after the name check + * (Namensabgleich Ausführungsauftrag). Sent together with the order again. + */ +export class HKVPA extends SegmentDefinition { + static Id = 'HKVPA'; + static Version = 1; + constructor() { + super(HKVPA.Id); + } + version = HKVPA.Version; + elements = [new Binary('vopId', 1, 1)]; +} diff --git a/src/segments/HKVPP.ts b/src/segments/HKVPP.ts new file mode 100644 index 0000000..73aa14a --- /dev/null +++ b/src/segments/HKVPP.ts @@ -0,0 +1,33 @@ +import { AlphaNumeric } from '../dataElements/AlphaNumeric.js'; +import { Binary } from '../dataElements/Binary.js'; +import { Numeric } from '../dataElements/Numeric.js'; +import { DataGroup } from '../dataGroups/DataGroup.js'; +import type { Segment } from '../segment.js'; +import { SegmentDefinition } from '../segmentDefinition.js'; + +export type HKVPPSegment = Segment & { + /** pain.002 formats the client can read; the group holds just the list */ + supportedReports: string[]; + pollingId?: string; + maxEntries?: number; + continuationMark?: string; +}; + +/** + * Verification of Payee: request the name check (Namensabgleich Prüfauftrag). + * Sent in the same message as the payment order it checks, before it. + */ +export class HKVPP extends SegmentDefinition { + static Id = 'HKVPP'; + static Version = 1; + constructor() { + super(HKVPP.Id); + } + version = HKVPP.Version; + elements = [ + new DataGroup('supportedReports', [new AlphaNumeric('descriptors', 1, 99, 256)], 1, 1), + new Binary('pollingId', 0, 1), + new Numeric('maxEntries', 0, 1, 4), + new AlphaNumeric('continuationMark', 0, 1, 35), + ]; +} diff --git a/src/segments/registry.ts b/src/segments/registry.ts index a38c1b9..fa6b1cb 100644 --- a/src/segments/registry.ts +++ b/src/segments/registry.ts @@ -26,11 +26,15 @@ import { HITAN } from './HITAN.js'; import { HITANS } from './HITANS.js'; import { HIUPA } from './HIUPA.js'; import { HIUPD } from './HIUPD.js'; +import { HIVPP } from './HIVPP.js'; +import { HIVPPS } from './HIVPPS.js'; import { HIWPD } from './HIWPD.js'; import { HKCAZ } from './HKCAZ.js'; +import { HKCCS } from './HKCCS.js'; import { HKEKA } from './HKEKA.js'; import { HKEND } from './HKEND.js'; import { HKIDN } from './HKIDN.js'; +import { HKIPZ } from './HKIPZ.js'; import { HKKAZ } from './HKKAZ.js'; import { HKKKU } from './HKKKU.js'; import { HKSAL } from './HKSAL.js'; @@ -38,6 +42,8 @@ import { HKSPA } from './HKSPA.js'; import { HKSYN } from './HKSYN.js'; import { HKTAB } from './HKTAB.js'; import { HKTAN } from './HKTAN.js'; +import { HKVPA } from './HKVPA.js'; +import { HKVPP } from './HKVPP.js'; import { HKVVB } from './HKVVB.js'; import { HKWPD } from './HKWPD.js'; import { HNHBK } from './HNHBK.js'; @@ -75,6 +81,12 @@ export function registerSegments() { registerSegmentDefinition(new HIUPD()); registerSegmentDefinition(new HKEND()); registerSegmentDefinition(new HKSAL()); + registerSegmentDefinition(new HKCCS()); + registerSegmentDefinition(new HKIPZ()); + registerSegmentDefinition(new HKVPP()); + registerSegmentDefinition(new HIVPP()); + registerSegmentDefinition(new HKVPA()); + registerSegmentDefinition(new HIVPPS()); registerSegmentDefinition(new HISAL()); registerSegmentDefinition(new HKKAZ()); registerSegmentDefinition(new DKKKU()); diff --git a/src/tests/HKCCS.test.ts b/src/tests/HKCCS.test.ts new file mode 100644 index 0000000..0a35e28 --- /dev/null +++ b/src/tests/HKCCS.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { decode, encode } from '../segment.js'; +import { HKCCS, type HKCCSSegment } from '../segments/HKCCS.js'; +import { registerSegments } from '../segments/registry.js'; + +registerSegments(); + +const PAIN = 'A+B: C\'s'; + +describe('HKCCS v1', () => { + it('encode carries the pain message as binary, unescaped', () => { + const segment: HKCCSSegment = { + header: { segId: HKCCS.Id, segNr: 3, version: 1 }, + account: { iban: 'DE991234567123456', bic: 'BANK12' }, + sepaDescriptor: 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.09', + sepaPainMessage: PAIN, + }; + + expect(encode(segment)).toBe( + `HKCCS:3:1+DE991234567123456:BANK12+urn?:iso?:std?:iso?:20022?:tech?:xsd?:pain.001.001.09+@${PAIN.length}@${PAIN}'`, + ); + }); + + it('decode and encode roundtrip matches', () => { + const text = `HKCCS:3:1+DE991234567123456:BANK12+urn?:iso?:std?:iso?:20022?:tech?:xsd?:pain.001.001.09+@${PAIN.length}@${PAIN}'`; + expect(encode(decode(text))).toBe(text); + }); +}); diff --git a/src/tests/transferVop.test.ts b/src/tests/transferVop.test.ts new file mode 100644 index 0000000..d1dc367 --- /dev/null +++ b/src/tests/transferVop.test.ts @@ -0,0 +1,252 @@ +import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest'; +import type { BankingInformation } from '../bankingInformation.js'; +import type { BPD } from '../bpd.js'; +import { Language } from '../codes.js'; +import { FinTSConfig } from '../config.js'; +import { Dialog } from '../dialog.js'; +import type { ClientResponse } from '../interactions/customerInteraction.js'; +import { TransferInteraction } from '../interactions/transferInteraction.js'; +import { type CustomerMessage, Message } from '../message.js'; +import { decode, encode, type Segment } from '../segment.js'; +import { HIVPP, type HIVPPSegment } from '../segments/HIVPP.js'; +import { HKVPP, type HKVPPSegment } from '../segments/HKVPP.js'; +import { registerSegments } from '../segments/registry.js'; +import type { UPD } from '../upd.js'; + +vi.mock('../httpClient.js', () => ({ + HttpClient: class MockHttpClient { + sendMessage = vi.fn(); + }, +})); + +registerSegments(); + +const REPORT_10 = 'urn:iso:std:iso:20022:tech:xsd:pain.002.001.10'; +const REPORT_10_ESC = 'urn?:iso?:std?:iso?:20022?:tech?:xsd?:pain.002.001.10'; +const POLLING_ID = 'c0f5c2a4-ebb7-4e72-be44-c68742177a2b'; +const VOP_ID = '5e3b5c99-df27-4d42-835b-18b35d0c66ff'; + +// Bank answers recorded from Atruvia (Volksbanken), taken from phpFinTS' tests +const POLLING_NEEDED = + "HIRMG:3:2+3060::Bitte beachten Sie die enthaltenen Warnungen/Hinweise.+3905::Es wurde keine Challenge erzeugt.'" + + "HIRMS:4:2:5+3040::Es liegen weitere Informationen vor.:staticscrollref'" + + "HIRMS:5:2:4+3945::Freigabe ohne VOP-Bestätigung nicht möglich.'" + + `HIVPP:6:1:5+++@36@${POLLING_ID}+++++2'`; +const report = (group: string, tx?: string) => + "" + + `1${group}` + + (tx + ? `${tx}` + : '') + + ''; +const withReport = (answers: string, xml: string, infoText = '') => + `${answers}HIVPP:5:1:3+@36@${VOP_ID}+++${REPORT_10_ESC}+@${xml.length}@${xml}++${infoText}'`; +const MATCH = withReport( + "HIRMG:3:2+0010::Nachricht entgegengenommen.'HIRMS:4:2:3+0020::Auftrag ausgeführt.+0025::Keine Namensabweichung.'", + report('RCVC'), +); +const NO_MATCH = withReport( + "HIRMG:3:2+3060::Bitte beachten Sie die enthaltenen Warnungen/Hinweise.'HIRMS:4:2:3+3090::Ergebnis des Namensabgleichs prüfen.'", + report('RVCM', 'RVNM'), + 'Der Name stimmt nicht überein.', +); +const CONFIRMED = + "HIRMG:3:2+3060::Bitte beachten Sie die enthaltenen Warnungen/Hinweise.'" + + "HIRMS:4:2:4+0020::Ausführungsbestätigung nach Namensabgleich erhalten.'" + + "HIRMS:5:2:5+3955::Sicherheitsfreigabe erfolgt über anderen Kanal.'" + + "HITAN:6:7:5+4++1234567890123456789012345678+Bitte bestätigen Sie den Vorgang in Ihrer SecureGo plus App'"; + +describe('VoP segments', () => { + it('HKVPP encodes the report format and, when polling, polling id and Aufsetzpunkt', () => { + const segment: HKVPPSegment = { + header: { segId: HKVPP.Id, segNr: 3, version: 1 }, + supportedReports: [REPORT_10], + pollingId: POLLING_ID, + continuationMark: 'staticscrollref', + }; + expect(encode(segment)).toBe(`HKVPP:3:1+${REPORT_10_ESC}+@36@${POLLING_ID}++staticscrollref'`); + }); + + it('HIVPP decodes a polling answer and a report', () => { + const polling = decode(`HIVPP:6:1:5+++@36@${POLLING_ID}+++++2'`) as HIVPPSegment; + expect(polling).toMatchObject({ pollingId: POLLING_ID, waitSeconds: 2 }); + expect(polling.vopId).toBeUndefined(); + + const single = decode( + "HIVPP:5:1:3+@3@abc+++++DE00ABCDEFGH1234567890::Testempfaenger GmbH::RVMC+Der Name weicht ab.'", + ) as HIVPPSegment; + expect(single.header.segId).toBe(HIVPP.Id); + expect(single.result).toMatchObject({ differentName: 'Testempfaenger GmbH', result: 'RVMC' }); + }); +}); + +describe('transfer with Verification of Payee (Atruvia)', () => { + let dialog: Dialog; + let send: MockInstance; + const sent: Segment[][] = []; + const ids = (i: number) => sent[i].map((s) => s.header.segId).filter((id) => /^HK/.test(id)); + + beforeEach(() => { + const bankingInformation = { + systemId: 'SYS', + bankMessages: [], + bpd: { + version: 1, + bankId: '12030000', + bankName: 'Mock Bank', + countryCode: 280, + url: 'http://mock.bank.url', + allowedTransactions: [ + { transId: 'HKCCS', tanRequired: true, versions: [1] }, + { transId: 'HKIPZ', tanRequired: true, versions: [1] }, + { + transId: 'HKVPP', + tanRequired: false, + versions: [1], + params: { supportedReports: REPORT_10 }, + }, + { transId: 'HKVPA', tanRequired: false, versions: [1] }, + ], + supportedTanMethods: [ + { + id: 946, + name: 'SecureGo plus', + version: 7, + isDecoupled: true, + activeTanMediaCount: 0, + activeTanMedia: [], + tanMediaRequirement: 0, + }, + ], + availableTanMethodIds: [946], + supportedLanguages: [Language.German], + maxTransactionsPerMessage: 1, + } as unknown as BPD, + upd: { + bankAccounts: [ + { + accountNumber: '202051', + bank: { country: 280, bankId: '12030000' }, + iban: 'DE89370400440532013000', + allowedTransactions: [{ transId: 'HKCCS' }, { transId: 'HKIPZ' }], + }, + ], + } as unknown as UPD, + } as BankingInformation; + const config = FinTSConfig.fromBankingInformation( + 'P', + '1.0', + bankingInformation, + 'u', + '1', + 946, + ); + + dialog = new Dialog(config); + const ok: ClientResponse = { + dialogId: 'D1', + success: true, + requiresTan: false, + bankingInformationUpdated: false, + bankAnswers: [], + }; + vi.spyOn(dialog.interactions[0], 'handleClientResponse').mockReturnValue(ok); + vi.spyOn(dialog.interactions[1], 'handleClientResponse').mockReturnValue(ok); + dialog.addCustomerInteraction( + new TransferInteraction('202051', 'sepade:xsd:pain.001.001.09.xsd', ''), + ); + + sent.length = 0; + send = vi.mocked(dialog.httpClient.sendMessage); + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.clearAllMocks(); + }); + + const respond = (...answers: string[]) => { + for (const text of answers) { + send.mockImplementationOnce(async (msg: CustomerMessage) => { + sent.push([...msg.segments]); + return text ? Message.decode(text) : new Message([]); + }); + } + }; + const run = async (work: Promise) => { + await vi.runAllTimersAsync(); + return work; + }; + + it('order first, TAN request, name check last; polls with Aufsetzpunkt; confirms; then TAN', async () => { + respond('', POLLING_NEEDED, MATCH); + const first = (await run(dialog.start())).get('HKCCS'); + expect(ids(1)).toEqual(['HKCCS', 'HKTAN', 'HKVPP']); + expect(ids(2)).toEqual(['HKVPP']); + const poll = sent[2].find((s) => s.header.segId === 'HKVPP') as HKVPPSegment; + expect(poll).toMatchObject({ pollingId: POLLING_ID, continuationMark: 'staticscrollref' }); + expect(first?.requiresVopConfirmation).toBe(true); + expect(first?.vop?.result).toBe('RCVC'); + expect(dialog.hasEnded).toBe(false); + + respond(CONFIRMED); + const second = (await run(dialog.resume())).get('HKCCS'); + expect(ids(3)).toEqual(['HKCCS', 'HKVPA', 'HKTAN']); + expect(sent[3].find((s) => s.header.segId === 'HKVPA')).toMatchObject({ vopId: VOP_ID }); + expect(second?.requiresTan).toBe(true); + expect(second?.tanReference).toBe('1234567890123456789012345678'); + }); + + it('a partial match in the report is read from the transaction status', async () => { + respond('', POLLING_NEEDED, NO_MATCH); + const response = (await run(dialog.start())).get('HKCCS'); + expect(response?.requiresVopConfirmation).toBe(true); + expect(response?.vop).toMatchObject({ + result: 'RVNM', + infoText: 'Der Name stimmt nicht überein.', + }); + }); + + it('3091: no confirmation, straight to the TAN', async () => { + const noConfirmation = withReport( + "HIRMG:3:2+0010::Nachricht entgegengenommen.'HIRMS:4:2:3+3091::VOP-Ausführungsauftrag nicht benötigt.+0025::Keine Namensabweichung.'", + report('RCVC'), + ).replace(/'$/, "'HITAN:6:7:5+4++REF9+Bitte in der App bestätigen'"); + respond('', POLLING_NEEDED, noConfirmation); + const response = (await run(dialog.start())).get('HKCCS'); + expect(response?.requiresVopConfirmation).toBeFalsy(); + expect(response?.requiresTan).toBe(true); + expect(response?.tanReference).toBe('REF9'); + }); + + it('3091 without challenge: the transfer is done at once', async () => { + const done = + "HIRMG:3:2+3060::Bitte beachten Sie die enthaltenen Warnungen/Hinweise.+3905::Es wurde keine Challenge erzeugt.'" + + "HIRMS:4:2:5+3091::VOP-Ausführungsauftrag nicht benötigt.+0025::Keine Namensabweichung.'" + + "HIRMS:5:2:4+3076::Keine starke Authentifizierung erforderlich.'" + + `HIVPP:6:1:5+@36@${VOP_ID}+++${REPORT_10_ESC}'` + + "HITAN:7:7:4+4++noref+nochallenge'" + + "HIRMS:8:2:3+0020::*SEPA-Einzelüberweisung erfolgreich+0900::Freigabe erfolgreich'"; + respond('', done, ''); + const response = (await run(dialog.start())).get('HKCCS'); + expect(response?.success).toBe(true); + expect(response?.requiresTan).toBe(false); + expect(response?.requiresVopConfirmation).toBeFalsy(); + }); + + it('instant: HKIPZ in place of HKCCS, same name check', async () => { + dialog.interactions.splice(1, 1); + dialog.addCustomerInteraction( + new TransferInteraction('202051', 'sepade:xsd:pain.001.001.09.xsd', '', true), + ); + respond('', POLLING_NEEDED, MATCH); + const first = (await run(dialog.start())).get('HKIPZ'); + expect(ids(1)).toEqual(['HKIPZ', 'HKTAN', 'HKVPP']); + expect(sent[1].find((s) => s.header.segId === 'HKTAN')).toMatchObject({ segId: 'HKIPZ' }); + expect(first?.requiresVopConfirmation).toBe(true); + respond(CONFIRMED); + await run(dialog.resume()); + expect(ids(3)).toEqual(['HKIPZ', 'HKVPA', 'HKTAN']); + }); +});