|
| 1 | +/* |
| 2 | + * Open Bank Project - API Explorer II |
| 3 | + * Copyright (C) 2023-2025, TESOBE GmbH |
| 4 | + * |
| 5 | + * This program is free software: you can redistribute it and/or modify |
| 6 | + * it under the terms of the GNU Affero General Public License as published by |
| 7 | + * the Free Software Foundation, either version 3 of the License, or |
| 8 | + * (at your option) any later version. |
| 9 | + * |
| 10 | + * This program is distributed in the hope that it will be useful, |
| 11 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | + * GNU Affero General Public License for more details. |
| 14 | + * |
| 15 | + * You should have received a copy of the GNU Affero General Public License |
| 16 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | + * |
| 18 | + * Email: contact@tesobe.com |
| 19 | + * TESOBE GmbH |
| 20 | + * Osloerstrasse 16/17 |
| 21 | + * Berlin 13359, Germany |
| 22 | + * |
| 23 | + * This product includes software developed at |
| 24 | + * TESOBE (http://www.tesobe.com/) |
| 25 | + * |
| 26 | + */ |
| 27 | + |
| 28 | +import { Service } from 'typedi' |
| 29 | +import crypto from 'crypto' |
| 30 | +import fs from 'fs' |
| 31 | +import type { BerlinGroupConfig, BerlinGroupHeaders } from '../types/berlin-group.js' |
| 32 | + |
| 33 | +/** |
| 34 | + * BerlinGroupSignatureService generates RSA-SHA256 digital signatures, |
| 35 | + * SHA-256 body digests, and TPP certificate headers required by |
| 36 | + * Berlin Group PSD2 APIs. |
| 37 | + * |
| 38 | + * Configuration is loaded from environment variables at construction. |
| 39 | + * If certificate files are not configured, the service gracefully degrades |
| 40 | + * and isEnabled() returns false. |
| 41 | + */ |
| 42 | +@Service() |
| 43 | +export class BerlinGroupSignatureService { |
| 44 | + private privateKey: string | null = null |
| 45 | + private certificate: string | null = null |
| 46 | + private config: BerlinGroupConfig | null = null |
| 47 | + |
| 48 | + constructor() { |
| 49 | + this.loadConfig() |
| 50 | + } |
| 51 | + |
| 52 | + private loadConfig(): void { |
| 53 | + const privateKeyPath = process.env.VITE_BG_PRIVATE_KEY_PATH |
| 54 | + const certificatePath = process.env.VITE_BG_CERTIFICATE_PATH |
| 55 | + |
| 56 | + if (!privateKeyPath || !certificatePath) { |
| 57 | + console.log('BerlinGroupSignatureService: Certificate paths not configured, signing disabled') |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + try { |
| 62 | + this.privateKey = fs.readFileSync(privateKeyPath, 'utf8') |
| 63 | + this.certificate = fs.readFileSync(certificatePath, 'utf8') |
| 64 | + |
| 65 | + this.config = { |
| 66 | + privateKeyPath, |
| 67 | + certificatePath, |
| 68 | + keyId: process.env.VITE_BG_KEY_ID || 'SN=unknown, CA=CN=unknown', |
| 69 | + apiVersion: process.env.VITE_BG_API_VERSION || 'v1.3', |
| 70 | + psuDeviceId: process.env.VITE_BG_PSU_DEVICE_ID || 'device-api-explorer-ii', |
| 71 | + psuDeviceName: process.env.VITE_BG_PSU_DEVICE_NAME || 'API-Explorer-II', |
| 72 | + psuIpAddress: process.env.VITE_BG_PSU_IP_ADDRESS || '127.0.0.1', |
| 73 | + tppRedirectUri: process.env.VITE_BG_TPP_REDIRECT_URI || '', |
| 74 | + tppNokRedirectUri: process.env.VITE_BG_TPP_NOK_REDIRECT_URI || '' |
| 75 | + } |
| 76 | + |
| 77 | + console.log('BerlinGroupSignatureService: Private key and certificate loaded successfully') |
| 78 | + } catch (error: any) { |
| 79 | + console.error('BerlinGroupSignatureService: Failed to load certificate files:', error.message) |
| 80 | + this.privateKey = null |
| 81 | + this.certificate = null |
| 82 | + this.config = null |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * Check if Berlin Group signing is enabled (certificates are loaded) |
| 88 | + */ |
| 89 | + isEnabled(): boolean { |
| 90 | + return this.privateKey !== null && this.certificate !== null && this.config !== null |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Get the configured Berlin Group API version |
| 95 | + */ |
| 96 | + getApiVersion(): string { |
| 97 | + return this.config?.apiVersion || 'v1.3' |
| 98 | + } |
| 99 | + |
| 100 | + /** |
| 101 | + * Detect whether a request path is a Berlin Group API path |
| 102 | + */ |
| 103 | + static isBerlinGroupPath(path: string): boolean { |
| 104 | + return path.includes('/berlin-group/') |
| 105 | + } |
| 106 | + |
| 107 | + /** |
| 108 | + * Generate all required Berlin Group PSD2 headers for a request |
| 109 | + * |
| 110 | + * @param method - HTTP method (GET, POST, PUT, DELETE) |
| 111 | + * @param body - Request body (empty string for GET/DELETE) |
| 112 | + * @param consentId - Optional Consent-ID for account data endpoints |
| 113 | + * @returns Object containing all required Berlin Group headers |
| 114 | + */ |
| 115 | + generateHeaders( |
| 116 | + method: string, |
| 117 | + body: string, |
| 118 | + consentId?: string |
| 119 | + ): BerlinGroupHeaders { |
| 120 | + if (!this.privateKey || !this.certificate || !this.config) { |
| 121 | + throw new Error('BerlinGroupSignatureService: Cannot generate headers - not configured') |
| 122 | + } |
| 123 | + |
| 124 | + // Use empty string body for GET and DELETE requests |
| 125 | + const effectiveBody = method === 'GET' || method === 'DELETE' ? '' : body |
| 126 | + |
| 127 | + // Generate Date in RFC 7231 format |
| 128 | + const dateHeader = new Date().toUTCString() |
| 129 | + |
| 130 | + // Generate UUID v4 for X-Request-ID |
| 131 | + const xRequestId = crypto.randomUUID() |
| 132 | + |
| 133 | + // Compute SHA-256 digest of the body |
| 134 | + const digestValue = crypto.createHash('sha256').update(effectiveBody).digest('base64') |
| 135 | + const digestHeader = `SHA-256=${digestValue}` |
| 136 | + |
| 137 | + // Create the string to sign per PSD2 spec |
| 138 | + const dataToSign = `digest: ${digestHeader}\ndate: ${dateHeader}\nx-request-id: ${xRequestId}` |
| 139 | + |
| 140 | + // Sign with RSA-SHA256 |
| 141 | + const sign = crypto.createSign('RSA-SHA256') |
| 142 | + sign.update(dataToSign) |
| 143 | + sign.end() |
| 144 | + const signature = sign.sign(this.privateKey, 'base64') |
| 145 | + |
| 146 | + // Build Signature header |
| 147 | + const signatureHeader = `keyId="${this.config.keyId}", algorithm="rsa-sha256", headers="digest date x-request-id", signature="${signature}"` |
| 148 | + |
| 149 | + // Base64-encode the certificate |
| 150 | + const certificateBase64 = Buffer.from(this.certificate).toString('base64') |
| 151 | + |
| 152 | + // Build headers object |
| 153 | + const headers: BerlinGroupHeaders = { |
| 154 | + 'Content-Type': 'application/json', |
| 155 | + Date: dateHeader, |
| 156 | + 'X-Request-ID': xRequestId, |
| 157 | + Digest: digestHeader, |
| 158 | + Signature: signatureHeader, |
| 159 | + 'TPP-Signature-Certificate': certificateBase64, |
| 160 | + 'PSU-Device-ID': this.config.psuDeviceId, |
| 161 | + 'PSU-Device-Name': this.config.psuDeviceName, |
| 162 | + 'PSU-IP-Address': this.config.psuIpAddress |
| 163 | + } |
| 164 | + |
| 165 | + // Add redirect URIs for POST requests |
| 166 | + if (method === 'POST' && this.config.tppRedirectUri) { |
| 167 | + headers['TPP-Redirect-URI'] = this.config.tppRedirectUri |
| 168 | + } |
| 169 | + if (method === 'POST' && this.config.tppNokRedirectUri) { |
| 170 | + headers['TPP-Nok-Redirect-URI'] = this.config.tppNokRedirectUri |
| 171 | + } |
| 172 | + |
| 173 | + // Add Consent-ID when provided |
| 174 | + if (consentId) { |
| 175 | + headers['Consent-ID'] = consentId |
| 176 | + } |
| 177 | + |
| 178 | + console.log(`BerlinGroupSignatureService: Generated headers for ${method} request`) |
| 179 | + console.log(` X-Request-ID: ${xRequestId}`) |
| 180 | + console.log(` Digest: ${digestHeader}`) |
| 181 | + |
| 182 | + return headers |
| 183 | + } |
| 184 | +} |
0 commit comments