various modular fixes

This commit is contained in:
AngelPashov 2018-06-01 16:16:43 +03:00
parent f207254238
commit 8492d94054
23 changed files with 605 additions and 612 deletions

View File

@ -1,5 +1,5 @@
{
"extends": "airbnb",
"extends": "airbnb-base",
"env": {
"node": true
},

View File

@ -1,4 +1,5 @@
'use strict';
const Client = require('./lib/Client');
module.exports = Client;

View File

@ -1,56 +1,45 @@
'use strict';
const fs = require('fs');
const moment = require('moment');
const handlebars = require('handlebars');
const BN = require("bn.js");
const BN = require('bn.js');
module.exports = class BankLetter {
constructor(client, bankName) {
this.client = client;
this.bankName = bankName;
this.pathToTemplate = './app/ebics/ini.hbs';
};
const registerHelpers = () => {
handlebars.registerHelper('today', () => moment().format('DD.MM.YYYY'));
_registerHelpers() {
handlebars.registerHelper("today", () => {
return moment().format('DD.MM.YYYY');
});
handlebars.registerHelper('now', () => moment().format('HH:mm:ss'));
handlebars.registerHelper("now", () => {
return moment().format('HH:mm:ss');
});
handlebars.registerHelper('keyExponentBits', k => Buffer.byteLength(new BN(k.key.keyPair.e).toBuffer()) * 8);
handlebars.registerHelper("keyExponentBits", (k) => {
return Buffer.byteLength(new BN(k.key.keyPair.e).toBuffer()) * 8;
});
handlebars.registerHelper("keyModulusBits", (k) => {
return k.key.getKeySize();
handlebars.registerHelper('keyModulusBits', k => k.key.getKeySize());
// return Buffer.byteLength(new BN(k.key.keyPair.e).toBuffer()) * 8;
});
handlebars.registerHelper("keyExponent", (k) => {
return k.e();
});
handlebars.registerHelper('keyExponent', k => k.e());
handlebars.registerHelper("keyModulus", (k) => {
return k.n().toUpperCase().match(/.{1,2}/g).join(' ');
});
handlebars.registerHelper('keyModulus', k => k.n().toUpperCase().match(/.{1,2}/g).join(' '));
handlebars.registerHelper("sha256", (k) => {
handlebars.registerHelper('sha256', (k) => {
const digest = Buffer.from(k.publicDigest(), 'base64').toString('HEX');
return digest.toUpperCase().match(/.{1,2}/g).join(' ');
});
};
module.exports = class BankLetter {
constructor({
client,
bankName,
template,
}) {
this.client = client;
this.bankName = bankName;
this.template = template;
}
generate() {
this._registerHelpers();
registerHelpers();
const str = fs.readFileSync(this.pathToTemplate).toString();
const templ = handlebars.compile(str);
const templ = handlebars.compile(this.template);
const data = {
bankName: this.bankName,
@ -63,4 +52,4 @@ module.exports = class BankLetter {
return templ(data);
}
}
};

View File

@ -1,13 +1,15 @@
'use strict';
const fs = require("fs");
const crypto = require("crypto");
const $request = require("request");
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const $request = require('request');
const BN = require('bn.js');
const xpath = require("xpath");
const NodeRSA = require("node-rsa");
const DOMParser = require("xmldom").DOMParser;
const xpath = require('xpath');
const NodeRSA = require('node-rsa');
const { DOMParser } = require('xmldom');
const Key = require('./Key');
const XMLSign = require('./middleware/XMLSign');
@ -22,6 +24,8 @@ const EBICSHAC = require('./orders/HAC');
const EBICSHTD = require('./orders/HTD');
const EBICSC52 = require('./orders/C52');
const defaultIniTemplatePath = path.join(__dirname, '../templates/ini.hbs');
const utils = {
exponent: {
// str = 65537 => AQAB
@ -31,9 +35,9 @@ const utils = {
// str = AQAB => 65537
fromBase64(str) {
return new BN(Buffer.from(str, 'base64'), 2).toNumber();
}
}
}
},
},
};
module.exports = class Client {
constructor(keysContent, passphrase, url, hostId, userId, partnerId) {
this.keysContent = keysContent;
@ -44,18 +48,18 @@ module.exports = class Client {
this.partnerId = partnerId;
this.encryptAlgorithm = 'aes-256-cbc';
this.keys = keysContent ? this.extractKeys() : {};
};
}
a() {
return this.keys["A006"];
};
return this.keys.A006;
}
e() {
return this.keys["E002"];
};
return this.keys.E002;
}
x() {
return this.keys["X002"];
return this.keys.X002;
}
bankX() {
@ -71,58 +75,70 @@ module.exports = class Client {
const encrypted = cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
return Buffer.from(encrypted).toString('base64');
};
}
decrypt(data) {
data = (new Buffer(data, 'base64')).toString();
data = (new Buffer(data, 'base64')).toString(); // eslint-disable-line no-buffer-constructor
const decipher = crypto.createDecipher(this.encryptAlgorithm, this.passphrase);
const decrypted = decipher.update(data, 'hex', 'utf8') + decipher.final('utf8');
return decrypted;
};
}
static setup(passphrase, url, hostId, userId, partnerId, keysize = 2048) {
const client = new Client(null, passphrase, url, hostId, userId, partnerId);
for (let key in {A006: '', X002: '', E002: ''}) {
Object.keys({ A006: '', X002: '', E002: '' }).forEach((key) => {
client.keys[key] = new Key(new NodeRSA({ b: keysize }));
}
});
// for (const key in Object.keys({ A006: '', X002: '', E002: '' }))
// client.keys[key] = new Key(new NodeRSA({ b: keysize }));
return client;
};
}
saveIniLetter(bankName, path) {
const letter = new BankLetter(this, bankName);
saveIniLetter(bankName, target, template) {
const letter = new BankLetter({
client: this,
bankName,
template: template || fs.readFileSync(defaultIniTemplatePath, { encoding: 'utf8' }),
});
try {
fs.writeFileSync(path, letter.generate());
fs.writeFileSync(target, letter.generate());
} catch (error) {
throw error;
}
};
}
saveKeys(path) {
saveKeys(target) {
const data = {};
for (let key in this.keys) {
Object.keys(this.keys).forEach((key) => {
data[key] = this.encrypt(this.keys[key].toPem());
};
});
// for (const key in this.keys)
// data[key] = this.encrypt(this.keys[key].toPem());
try {
fs.writeFileSync(path, JSON.stringify(data));
fs.writeFileSync(target, JSON.stringify(data));
} catch (error) {
throw error;
}
};
}
extractKeys() {
const keys = {};
const jsonData = JSON.parse(this.keysContent);
for (let key in jsonData) {
Object.keys(jsonData).forEach((key) => {
keys[key] = new Key(this.decrypt(jsonData[key]));
}
});
// for (const key in jsonData)
// keys[key] = new Key(this.decrypt(jsonData[key]));
return keys;
}
@ -130,31 +146,31 @@ module.exports = class Client {
async download(order) {
const res = await this.ebicsRequest(order.toXML());
const ttt = res.toXML(); // keep this for debugging purposes
const ttt = res.toXML(); // TODO: keep this for debugging purposes
order.transactionId = res.transactionId();
if (res.isSegmented() && res.isLastSegment()) {
const receipt = await this.ebicsRequest(order.toReceiptXML());
const receiptXML = order.toReceiptXML(); // keep this for debugging purposes
const rX = receipt.toXML(); // keep this for debugging purposes
const receiptXML = order.toReceiptXML(); // TODO: keep this for debugging purposes
const rX = receipt.toXML(); // TODO: keep this for debugging purposes
}
return res.orderData();
};
}
async upload(order) {
let res = await this.ebicsRequest(order.toXML());
order.transactionId = res.transactionId();
const orderId = res.orderId();
// const orderId = res.orderId();
res = await this.ebicsRequest(order.toTransferXML());
return res.transactionId();
}
async downloadAndUnzip(order) {
async downloadAndUnzip(order) { // eslint-disable-line
}
@ -163,36 +179,34 @@ module.exports = class Client {
$request.post({
url: this.url,
body: XMLSign.go(this, order),
headers: { 'content-type': 'text/xml;charset=UTF-8' }
}, (err, res, data) => {
return err ? reject(err): resolve(ParseResponse.go(this, data));
headers: { 'content-type': 'text/xml;charset=UTF-8' },
}, (err, res, data) => (err ? reject(err) : resolve(ParseResponse.go(this, data))));
});
});
};
}
async INI() {
return this.ebicsRequest((new EBICSINI(this)).toXML());
};
}
async HIA() {
return this.ebicsRequest((new EBICSHIA(this)).toXML());
};
}
async HPB() {
const data = await this.download(new EBICSHPB(this));
const doc = new DOMParser().parseFromString(data, 'text/xml');
const sel = xpath.useNamespaces({'xmlns': "urn:org:ebics:H004"});
const keyNodes = sel("//xmlns:PubKeyValue", doc);
const sel = xpath.useNamespaces({ xmlns: 'urn:org:ebics:H004' });
const keyNodes = sel('//xmlns:PubKeyValue', doc);
// console.log(keyNodes);
function xmlLastChild(node) {
let y = node.lastChild;
while (y.nodeType != 1) y = y.previousSibling;
while (y.nodeType !== 1) y = y.previousSibling;
return y;
};
}
for (let i = 0; i < keyNodes.length; i++) {
const type = xmlLastChild(keyNodes[i].parentNode).textContent;
@ -210,23 +224,23 @@ module.exports = class Client {
}
return [this.bankX(), this.bankE()];
};
}
HKD() {
return this.download(new EBICSHKD(this));
};
}
HAA() {
return this.download(new EBICSHAA(this));
};
}
HTD() {
return this.download(new EBICSHTD(this));
};
}
HAC(from = null, to = null) {
return this.download(new EBICSHAC(this, from, to));
};
}
C52(from, to) {
return this.downloadAndUnzip(new EBICSC52(this, from, to));

View File

@ -3,77 +3,74 @@
const crypto = require('crypto');
const BN = require('bn.js');
const NodeRSA = require("node-rsa");
const NodeRSA = require('node-rsa');
const MGF1 = require('./MGF1');
const mgf1 = require('./MGF1');
module.exports = class Key {
constructor(encodedKey, passphrase = null) {
if (encodedKey instanceof NodeRSA) {
this.key = encodedKey
} else {
this.key = new NodeRSA(encodedKey);
constructor(encodedKey/* , passphrase = null */) {
this.key = (encodedKey instanceof NodeRSA) ? encodedKey : new NodeRSA(encodedKey);
}
};
publicDigest() {
const str = [this.e().replace(/^(0+)/g, ''), this.n().replace(/^(0+)/g, '')].map((x) => x.toLowerCase()).join(' ');
const str = [this.e().replace(/^(0+)/g, ''), this.n().replace(/^(0+)/g, '')].map(x => x.toLowerCase()).join(' ');
return crypto.createHash('sha256').update(str).digest('base64').trim();
};
}
publicEncrypt(buf) {
return crypto.publicEncrypt({ 'key': this.toPem(), padding: crypto.constants.RSA_PKCS1_PADDING }, buf);
return crypto.publicEncrypt({
key: this.toPem(),
padding: crypto.constants.RSA_PKCS1_PADDING,
}, buf);
}
n() {
return this.key.exportKey("components-public").n.toString("hex", 1);
};
return this.key.exportKey('components-public').n.toString('hex', 1);
}
e() {
return new BN(this.key.exportKey("components-public").e).toBuffer().toString('hex');
};
return new BN(this.key.exportKey('components-public').e).toBuffer().toString('hex');
}
toPem() {
return this.key.isPrivate() ? this.key.exportKey("pkcs1-private-pem") : this.key.exportKey("pkcs8-public-pem");
return this.key.isPrivate() ? this.key.exportKey('pkcs1-private-pem') : this.key.exportKey('pkcs8-public-pem');
}
sign(msg, salt = crypto.randomBytes(32)) {
const base = new BN(this._emsaPSS(msg, salt));
const base = new BN(Key._emsaPSS(msg, salt));
const power = new BN(this.key.keyPair.d.toBuffer());
const mod = new BN(this.key.keyPair.n.toBuffer());
return (this._modPow(base, power, mod)).toBuffer().toString('base64');
return (Key._modPow(base, power, mod)).toBuffer().toString('base64');
}
_emsaPSS(msg, salt) {
const eightNullBytes = Buffer.from("\x00".repeat(8));
static _emsaPSS(msg, salt) {
const eightNullBytes = Buffer.from('\x00'.repeat(8));
const digestedMsg = crypto.createHash('sha256').update(msg).digest();
const mTickHash = crypto.createHash('sha256').update(Buffer.concat([eightNullBytes, digestedMsg, salt]), 'binary').digest();
const ps = Buffer.from("\x00".repeat(190));
const db = Buffer.concat([ps, Buffer.from("\x01"), salt]);
const ps = Buffer.from('\x00'.repeat(190));
const db = Buffer.concat([ps, Buffer.from('\x01'), salt]);
const dbMask = MGF1.generate(mTickHash, db.length);
const maskedDb = MGF1.xor(db, dbMask); // so far so good
const dbMask = mgf1.generate(mTickHash, db.length);
const maskedDb = mgf1.xor(db, dbMask); // so far so good
let maskedDbMsb = (new MGF1)._rjust(new BN(maskedDb.slice(0, 1), 2).toString(2), 8, "0");
maskedDbMsb = "0" + maskedDbMsb.substr(1);
let maskedDbMsb = mgf1.rjust(new BN(maskedDb.slice(0, 1), 2).toString(2), 8, '0');
maskedDb[0] = (new BN(maskedDbMsb, 2).toBuffer())[0];
maskedDbMsb = `0${maskedDbMsb.substr(1)}`;
maskedDb[0] = (new BN(maskedDbMsb, 2).toBuffer())[0]; // eslint-disable-line
return Buffer.concat([maskedDb, mTickHash, Buffer.from('BC', 'hex')]);
}
_modPow(base, power, mod) {
static _modPow(base, power, mod) {
let result = new BN(1);
while (power > 0) {
result = power.and(new BN(1)) == 1 ? (result.mul(base)).mod(mod) : result;
result = power.and(new BN(1)) === 1 ? (result.mul(base)).mod(mod) : result;
base = (base.mul(base)).mod(mod);
power = power.shrn(1);
}
return result;
}
};

View File

@ -1,67 +1,48 @@
'use strict'
'use strict';
const crypto = require("crypto");
const crypto = require('crypto');
const BN = require('bn.js');
module.exports = class MGF1 {
const MFG_LEN = 32;
constructor() {
this._len = 32;
}
/**
*
* @param {Buffer} seed
* @param {Number} masklen
*
* @returns Buffer
*/
static generate(seed, masklen) {
const mgf1 = new MGF1();
if ( masklen > 4294967296 * this._len) {
throw new Error('Mask too long');
}
const b = [];
for (let i = 0; i < mgf1._divceil(masklen, mgf1._len); i++) {
b[i] = crypto.createHash('sha256').update(Buffer.concat([seed, mgf1._i2osp(i, 4)])).digest();
}
return (Buffer.concat(b)).slice(0, masklen);
}
static xor(a, b) {
if ( a.length != b.length ) {
throw new Error('Different length for a and b');
}
for ( let i = 0; i < a.length; i++ ) {
a[i] ^= b[i];
}
return a;
}
_divceil(a, b) {
return ~~((a + b - 1) / b);
}
_i2osp(x, len) {
if ( x >= 256 ** len ) {
throw new Error('Integer too large');
}
return Buffer.from(this._rjust( (Buffer.from((new BN(x)).toArray('be', 4)).toString()).replace(/\x00/gi, ''), len, "\x00" ));
}
_rjust( string, width, padding ) {
padding = padding || " ";
const divceil = (a, b) => ~~(((a + b) - 1) / b); // eslint-disable-line no-bitwise
const rjust = (string, width, padding) => {
padding = padding || ' ';
padding = padding.substr(0, 1);
if (string.length < width)
return padding.repeat(width - string.length) + string;
else
return string;
}
}
};
const xor = (a, b) => {
if (a.length !== b.length)
throw new Error('Different length for a and b');
for (let i = 0; i < a.length; i++)
a[i] ^= b[i]; // eslint-disable-line no-bitwise
return a;
};
const i2osp = (x, len) => {
if (x >= 256 ** len)
throw new Error('Integer too large');
return Buffer.from(rjust((Buffer.from((new BN(x)).toArray('be', 4)).toString()).replace(/\x00/gi, ''), len, '\x00')); // eslint-disable-line no-control-regex
};
module.exports = {
generate(seed, masklen) {
if (masklen > 4294967296 * MFG_LEN)
throw new Error('Mask too long');
const b = [];
for (let i = 0; i < divceil(masklen, MFG_LEN); i++)
b[i] = crypto.createHash('sha256').update(Buffer.concat([seed, i2osp(i, 4)])).digest();
return (Buffer.concat(b)).slice(0, masklen);
},
xor,
rjust,
};

View File

@ -1,42 +1,42 @@
'use strict';
const zlib = require('zlib');
const crypto = require("crypto");
const crypto = require('crypto');
const DOMParser = require("xmldom").DOMParser;
const XMLSerializer = require("xmldom").XMLSerializer;
const xpath = require("xpath");
const { DOMParser, XMLSerializer } = require('xmldom');
const xpath = require('xpath');
const DEFAULT_IV = Buffer.from(Array(16).fill(0, 0, 15));
module.exports = class Response {
constructor(client, data) {
this.client = client;
this.doc = new DOMParser().parseFromString(data, 'text/xml');
};
}
isSegmented() {
const select = xpath.useNamespaces({'xmlns': "urn:org:ebics:H004"});
const node = select("//xmlns:header/xmlns:mutable/xmlns:SegmentNumber", this.doc);
const select = xpath.useNamespaces({ xmlns: 'urn:org:ebics:H004' });
const node = select('//xmlns:header/xmlns:mutable/xmlns:SegmentNumber', this.doc);
return node.length ? true: false;
return !!node.length;
}
isLastSegment() {
const select = xpath.useNamespaces({'xmlns': "urn:org:ebics:H004"});
const select = xpath.useNamespaces({ xmlns: 'urn:org:ebics:H004' });
const node = select("//xmlns:header/xmlns:mutable/*[@lastSegment='true']", this.doc);
return node.length ? true: false;
return !!node.length;
}
orderData() {
const orderData = this.doc.getElementsByTagNameNS("urn:org:ebics:H004", "OrderData")[0].textContent;
const decipher = crypto.createDecipheriv('aes-128-cbc', this.transactionKey(), Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,])).setAutoPadding(false);
const orderData = this.doc.getElementsByTagNameNS('urn:org:ebics:H004', 'OrderData')[0].textContent;
const decipher = crypto.createDecipheriv('aes-128-cbc', this.transactionKey(), DEFAULT_IV).setAutoPadding(false);
const data = Buffer.from(decipher.update(orderData, 'base64', 'binary') + decipher.final('binary'), 'binary');
return zlib.inflateSync(data).toString();
}
transactionKey() {
const keyNodeText = this.doc.getElementsByTagNameNS("urn:org:ebics:H004", "TransactionKey")[0].textContent;
const keyNodeText = this.doc.getElementsByTagNameNS('urn:org:ebics:H004', 'TransactionKey')[0].textContent;
const tkEncrypted = Buffer.from(keyNodeText, 'base64');
this.client.e().key.setOptions({ encryptionScheme: 'pkcs1' });
@ -45,8 +45,8 @@ module.exports = class Response {
}
transactionId() {
const select = xpath.useNamespaces({'xmlns': "urn:org:ebics:H004"});
const node = select("//xmlns:header/xmlns:static/xmlns:TransactionID", this.doc);
const select = xpath.useNamespaces({ xmlns: 'urn:org:ebics:H004' });
const node = select('//xmlns:header/xmlns:static/xmlns:TransactionID', this.doc);
return node.length ? node[0].textContent : '';
}

View File

@ -1,11 +1,10 @@
'use strict';
const crypto = require("crypto");
const crypto = require('crypto');
const DOMParser = require("xmldom").DOMParser;
const XMLSerializer = require("xmldom").XMLSerializer;
const select = require("xpath.js");
const c14n = require('xml-crypto/lib/c14n-canonicalization').C14nCanonicalization;
const { DOMParser, XMLSerializer } = require('xmldom');
const select = require('xpath.js');
const C14n = require('xml-crypto/lib/c14n-canonicalization').C14nCanonicalization;
module.exports = class Signer {
@ -67,30 +66,29 @@ module.exports = class Signer {
digest() {
// get the xml node, where the digested value is supposed to be
const nodeDigestValue = this.doc.getElementsByTagName("ds:DigestValue")[0];
const nodeDigestValue = this.doc.getElementsByTagName('ds:DigestValue')[0];
const nodes = select(this.doc, "//*[@authenticate='true']");
// const nodes = select(this.doc, "//*[@authenticate='true']");
// canonicalize the node that has authenticate='true' attribute
// const contentToDigest = select(this.doc, '//*[@authenticate="true"]')
const contentToDigest = select(this.doc, "//*[@authenticate='true']")
.map(x => {
const aaaa = x.toString();
return new c14n().process(x)
}).join("");
.map(x => new C14n().process(x)).join('');
console.log('digest', 'contentToDigest', contentToDigest);
// fix the canonicalization
const fixedContent = contentToDigest.replace(/xmlns="urn:org:ebics:H004"/g, 'xmlns="urn:org:ebics:H004" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"');
if (nodeDigestValue) {
if (nodeDigestValue)
nodeDigestValue.textContent = crypto.createHash('sha256').update(fixedContent).digest('base64').trim();
}
};
sign() {
const nodeSignatureValue = this.doc.getElementsByTagName("ds:SignatureValue")[0];
const nodeSignatureValue = this.doc.getElementsByTagName('ds:SignatureValue')[0];
console.log('sign =>');
if (nodeSignatureValue) {
const contentToSign = (new c14n().process(select(this.doc, "//ds:SignedInfo")[0])).replace('xmlns:ds="http://www.w3.org/2000/09/xmldsig#"', 'xmlns="urn:org:ebics:H004" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"');
const contentToSign = (new C14n().process(select(this.doc, '//ds:SignedInfo')[0])).replace('xmlns:ds="http://www.w3.org/2000/09/xmldsig#"', 'xmlns="urn:org:ebics:H004" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"');
nodeSignatureValue.textContent = this.client.x().key.sign(contentToSign, 'base64');
}
@ -99,5 +97,4 @@ module.exports = class Signer {
toXML() {
return new XMLSerializer().serializeToString(this.doc);
}
};

View File

@ -3,7 +3,7 @@
const packageJson = require('../package.json');
const name = 'eCollect Node Ebics Client';
const version = packageJson.version;
const { version } = packageJson;
module.exports = {
name,

View File

@ -6,10 +6,10 @@ module.exports = class ParseResponse {
constructor(client, data) {
this.client = client;
this.data = data;
};
}
static go(client, data) {
const parseRensponse = new ParseResponse(client, data);
// const parseRensponse = new ParseResponse(client, data);
const response = new Response(client, data);
// TODO:

View File

@ -6,10 +6,10 @@ module.exports = class XMLSign {
constructor(client, data) {
this.client = client;
this.data = data;
};
}
static go(client, data) {
const xmlSigner = new XMLSign(client, data);
// const xmlSigner = new XMLSign(client, data);
const signer = new Signer(client, data);
signer.digest();

View File

@ -9,7 +9,9 @@ module.exports = class C52 extends GenericOrder {
this._to = to;
this._schema.header = {
"@" : { authenticate: true },
'@': {
authenticate: true,
},
static: {
HostID: this.hostId,
Nonce: this.nonce(),
@ -17,34 +19,42 @@ module.exports = class C52 extends GenericOrder {
PartnerID: this.partnerId,
UserID: this.userId,
Product: {
"@": { Language: "de" },
"#": this.productString,
'@': {
Language: 'de',
},
'#': this.productString,
},
OrderDetails: {
OrderType : "C52",
OrderAttribute : "DZHNN",
OrderType: 'C52',
OrderAttribute: 'DZHNN',
StandardOrderParams: {
DateRange: {
Start: this._from,
End : this._to
}
End: this._to,
},
},
},
BankPubKeyDigests: {
Authentication: {
"@": { Version: "X002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankX().publicDigest()
'@': {
Version: 'X002',
Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',
},
'#': this.client.bankX().publicDigest(),
},
Encryption: {
"@": { Version: "E002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankE().publicDigest()
}
'@': {
Version: 'E002',
Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',
},
SecurityMedium: "0000"
'#': this.client.bankE().publicDigest(),
},
},
SecurityMedium: '0000',
},
mutable: {
TransactionPhase: "Initialisation"
TransactionPhase: 'Initialisation',
},
};
}
};
};
};

View File

@ -1,10 +1,47 @@
'use strict';
// const randHex = require('../../lib/utils').randHex;
const crypto = require("crypto");
const crypto = require('crypto');
const js2xmlparser = require('js2xmlparser');
const consts = require('../consts');
const authSignature = () => {
return {
'ds:SignedInfo': {
'ds:CanonicalizationMethod': {
'@': {
Algorithm:
'http://www.w3.org/TR/2001/REC-xml-c14n-20010315',
},
},
'ds:SignatureMethod': {
'@': {
Algorithm:
'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',
},
},
'ds:Reference': {
'@': { URI: "#xpointer(//*[@authenticate='true'])" },
'ds:Transforms': {
'ds:Transform': {
'@': {
Algorithm:
'http://www.w3.org/TR/2001/REC-xml-c14n-20010315',
},
},
},
'ds:DigestMethod': {
'@': {
Algorithm:
'http://www.w3.org/2001/04/xmlenc#sha256',
},
},
'ds:DigestValue': {},
},
},
'ds:SignatureValue': {},
};
};
module.exports = class GenericOrder {
constructor(client) {
this.client = client;
@ -18,67 +55,29 @@ module.exports = class GenericOrder {
this.xmlOptions = {
declaration: {
include: true,
encoding: "utf-8"
encoding: 'utf-8',
},
format: {
doubleQuotes: true,
indent: '',
newline: '',
pretty: true
}
pretty: true,
},
};
this._schema = {
"@": {
"xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
xmlns: "urn:org:ebics:H004",
Version: "H004",
Revision: "1"
'@': {
'xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
xmlns: 'urn:org:ebics:H004',
Version: 'H004',
Revision: '1',
},
header: {},
AuthSignature: this.authSignature(),
AuthSignature: authSignature(),
body: {}
};
}
authSignature() {
return {
"ds:SignedInfo": {
"ds:CanonicalizationMethod": {
"@": {
Algorithm:
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
}
},
"ds:SignatureMethod": {
"@": {
Algorithm:
"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
}
},
"ds:Reference": {
"@": { URI: "#xpointer(//*[@authenticate='true'])" },
"ds:Transforms": {
"ds:Transform": {
"@": {
Algorithm:
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
}
}
},
"ds:DigestMethod": {
"@": {
Algorithm:
"http://www.w3.org/2001/04/xmlenc#sha256"
}
},
"ds:DigestValue": {}
}
},
"ds:SignatureValue": {}
body: {},
};
}
@ -86,50 +85,51 @@ module.exports = class GenericOrder {
return this._schema;
}
get productString() {
static get productString() {
return consts.productString;
}
nonce() {
static nonce() {
return crypto.randomBytes(16).toString('hex');
}
timestamp() {
// TODO: remove eslint-disable-line
timestamp() { // eslint-disable-line
return new Date().toISOString();
}
root() {
return "ebicsRequest";
root() { // eslint-disable-line class-methods-use-this
return 'ebicsRequest';
}
toReceiptXML() {
const xmlObj = {
"@": {
"xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
xmlns: "urn:org:ebics:H004",
Version: "H004",
Revision: "1"
'@': {
'xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
xmlns: 'urn:org:ebics:H004',
Version: 'H004',
Revision: '1',
},
header: {
"@": { authenticate: true },
'@': { authenticate: true },
static: {
HostID: this.hostId,
TransactionID: this.transactionId
TransactionID: this.transactionId,
},
mutable: {
TransactionPhase: 'Receipt',
}
},
},
AuthSignature: this.authSignature(),
body: {
TransferReceipt: {
"@": { authenticate: true },
ReceiptCode: 0
}
}
'@': { authenticate: true },
ReceiptCode: 0,
},
},
};
return js2xmlparser.parse(this.root(), xmlObj, this.xmlOptions);
@ -137,41 +137,42 @@ module.exports = class GenericOrder {
toTransferXML() {
const xmlObj = {
"@": {
"xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
xmlns: "urn:org:ebics:H004",
Version: "H004",
Revision: "1"
'@': {
'xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
xmlns: 'urn:org:ebics:H004',
Version: 'H004',
Revision: '1',
},
header: {
"@": { authenticate: true },
'@': { authenticate: true },
static: {
HostID: this.hostId,
TransactionID: this.transactionId
TransactionID: this.transactionId,
},
mutable: {
TransactionPhase: 'Transfer',
SegmentNumber: {
"@": { lastSegment: true },
"#": 1
}
}
'@': { lastSegment: true },
'#': 1,
},
},
},
AuthSignature: this.authSignature(),
body: {
DataTransfer: {
OrderData: this.encryptedOrderData()
}
}
OrderData: this.encryptedOrderData(),
},
},
};
return js2xmlparser.parse(this.root(), xmlObj, this.xmlOptions);
}
encryptedOrderData() {
encryptedOrderData() { // eslint-disable-line class-methods-use-this
return null;
}
toXML() {

View File

@ -1,12 +1,19 @@
'use strict';
const zlib = require('zlib');
const crypto = require("crypto");
const crypto = require('crypto');
const js2xmlparser = require('js2xmlparser');
const GenericOrder = require('./GenericOrder');
const pad = (d) => {
const dLen = d.length;
const len = 16 * (Math.trunc(dLen / 16) + 1);
return Buffer.concat([d, Buffer.from(Buffer.from([0]).toString().repeat(len - dLen - 1)), Buffer.from([len - dLen])]);
};
module.exports = class GenericUploadOrder extends GenericOrder {
constructor(client, document) {
super(client);
@ -17,63 +24,56 @@ module.exports = class GenericUploadOrder extends GenericOrder {
this._schema.body = {
DataTransfer: {
DataEncryptionInfo: {
"@": { authenticate: true },
'@': { authenticate: true },
EncryptionPubKeyDigest: {
"@": { Version: "E002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankE().publicDigest()
'@': { Version: 'E002', Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' },
'#': this.client.bankE().publicDigest(),
},
TransactionKey: this.client.bankE().publicEncrypt(this._key).toString('base64'),
},
SignatureData: {
"@": { authenticate: true },
"#": this.encryptedOrderSignature()
}
}
};
'@': { authenticate: true },
'#': this.encryptedOrderSignature(),
},
},
};
}
orderSignature() {
const xmlObj = {
"@": {
xmlns: "http://www.ebics.org/S001",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": "http://www.ebics.org/S001 http://www.ebics.org/S001/ebics_signature.xsd"
'@': {
xmlns: 'http://www.ebics.org/S001',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation': 'http://www.ebics.org/S001 http://www.ebics.org/S001/ebics_signature.xsd',
},
OrderSignatureData: {
SignatureVersion: "A006",
SignatureVersion: 'A006',
SignatureValue: this.signatureValue(),
PartnerID: this.partnerId,
UserID: this.userId
}
UserID: this.userId,
},
};
return js2xmlparser.parse('UserSignatureData', xmlObj, this.xmlOptions);
};
}
signatureValue() {
const digested = crypto.createHash('sha256').update(this._document.replace(/\n|\r/g, "")).digest();
const digested = crypto.createHash('sha256').update(this._document.replace(/\n|\r/g, '')).digest();
return this.client.a().sign(digested);
};
}
encryptedOrderData() {
const dst = zlib.deflateSync(this._document.replace(/\r|\n/g, ""));
const cipher = crypto.createCipheriv('aes-128-cbc', this._key, Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,])).setAutoPadding(false);
const dst = zlib.deflateSync(this._document.replace(/\r|\n/g, ''));
const cipher = crypto.createCipheriv('aes-128-cbc', this._key, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])).setAutoPadding(false);
return Buffer.concat([cipher.update(this._pad(dst)), cipher.final()]).toString('base64');
return Buffer.concat([cipher.update(pad(dst)), cipher.final()]).toString('base64');
}
encryptedOrderSignature() {
const dst = zlib.deflateSync(this.orderSignature());
const cipher = crypto.createCipheriv('aes-128-cbc', this._key, Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,])).setAutoPadding(false);
const cipher = crypto.createCipheriv('aes-128-cbc', this._key, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])).setAutoPadding(false);
return Buffer.concat([cipher.update(this._pad(dst)), cipher.final()]).toString('base64');
};
_pad(d) {
const dLen = d.length;
const len = 16 * ( Math.trunc(dLen / 16) + 1 );
return Buffer.concat([d, Buffer.from(Buffer.from([0]).toString().repeat(len - dLen - 1)), Buffer.from([len-dLen])]);
return Buffer.concat([cipher.update(pad(dst)), cipher.final()]).toString('base64');
}
};

View File

@ -7,7 +7,7 @@ module.exports = class HAA extends GenericOrder {
super(client);
this._schema.header = {
"@": { authenticate: true },
'@': { authenticate: true },
static: {
HostID: this.hostId,
Nonce: this.nonce(),
@ -15,29 +15,29 @@ module.exports = class HAA extends GenericOrder {
PartnerID: this.partnerId,
UserID: this.userId,
Product: {
"@": { Language: "de" },
"#": this.productString
'@': { Language: 'de' },
'#': this.productString,
},
OrderDetails: {
OrderType: "HAA",
OrderAttribute: "DZHNN",
StandardOrderParams: ""
OrderType: 'HAA',
OrderAttribute: 'DZHNN',
StandardOrderParams: '',
},
BankPubKeyDigests: {
Authentication: {
"@": { Version: "X002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankX().publicDigest()
'@': { Version: 'X002', Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' },
'#': this.client.bankX().publicDigest(),
},
Encryption: {
"@": { Version: "E002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankE().publicDigest()
}
'@': { Version: 'E002', Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' },
'#': this.client.bankE().publicDigest(),
},
SecurityMedium: "0000"
},
SecurityMedium: '0000',
},
mutable: {
TransactionPhase: "Initialisation"
TransactionPhase: 'Initialisation',
},
};
}
};
};
};

View File

@ -9,7 +9,7 @@ module.exports = class HAC extends GenericOrder {
this._to = to;
this._schema.header = {
"@" : { authenticate: true },
'@': { authenticate: true },
static: {
HostID: this.hostId,
Nonce: this.nonce(),
@ -17,36 +17,36 @@ module.exports = class HAC extends GenericOrder {
PartnerID: this.partnerId,
UserID: this.userId,
Product: {
"@": { Language: "de" },
"#": this.productString,
'@': { Language: 'de' },
'#': this.productString,
},
OrderDetails: {
OrderType : "HAC",
OrderAttribute : "DZHNN",
OrderType: 'HAC',
OrderAttribute: 'DZHNN',
StandardOrderParams: this._hasDateRange() ? {
DateRange: {
Start: this._from,
End : this._to
}
} : ""
End: this._to,
},
} : '',
},
BankPubKeyDigests: {
Authentication: {
"@": { Version: "X002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankX().publicDigest()
'@': { Version: 'X002', Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' },
'#': this.client.bankX().publicDigest(),
},
Encryption: {
"@": { Version: "E002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankE().publicDigest()
}
'@': { Version: 'E002', Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' },
'#': this.client.bankE().publicDigest(),
},
SecurityMedium: "0000"
},
SecurityMedium: '0000',
},
mutable: {
TransactionPhase: "Initialisation"
TransactionPhase: 'Initialisation',
},
};
}
};
};
_hasDateRange() {
return this._from && this._to;

View File

@ -10,76 +10,76 @@ module.exports = class HIA extends GenericOrder {
super(client);
this._schema = {
"@": {
"xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
xmlns: "urn:org:ebics:H004",
Version: "H004",
Revision: "1"
'@': {
'xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
xmlns: 'urn:org:ebics:H004',
Version: 'H004',
Revision: '1',
},
header: {
"@": { authenticate: true },
'@': { authenticate: true },
static: {
HostID: this.hostId,
PartnerID: this.partnerId,
UserID: this.userId,
Product: {
"@": { Language: "de" },
"#": this.productString,
'@': { Language: 'de' },
'#': this.productString,
},
OrderDetails: {
OrderType: "HIA",
OrderAttribute: "DZNNN"
OrderType: 'HIA',
OrderAttribute: 'DZNNN',
},
SecurityMedium: "0000"
SecurityMedium: '0000',
},
mutable: {}
mutable: {},
},
body: {
DataTransfer: {
OrderData: Buffer.from(zlib.deflateSync(this.orderData())).toString('base64')
}
}
OrderData: Buffer.from(zlib.deflateSync(this.orderData())).toString('base64'),
},
},
};
}
root() {
return "ebicsUnsecuredRequest";
};
root() { // eslint-disable-line class-methods-use-this
return 'ebicsUnsecuredRequest';
}
orderData() {
const xmlOrderData = {
"@": {
"xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
xmlns: "urn:org:ebics:H004"
'@': {
'xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
xmlns: 'urn:org:ebics:H004',
},
AuthenticationPubKeyInfo: {
PubKeyValue: {
"ds:RSAKeyValue": {
"ds:Modulus": Buffer.from(this.client.x().n(), 'HEX').toString('base64'),
"ds:Exponent": "AQAB"
'ds:RSAKeyValue': {
'ds:Modulus': Buffer.from(this.client.x().n(), 'HEX').toString('base64'),
'ds:Exponent': 'AQAB',
},
},
AuthenticationVersion: "X002"
AuthenticationVersion: 'X002',
},
EncryptionPubKeyInfo: {
PubKeyValue: {
"ds:RSAKeyValue": {
"ds:Modulus": Buffer.from(this.client.e().n(), 'HEX').toString('base64'),
"ds:Exponent": "AQAB"
'ds:RSAKeyValue': {
'ds:Modulus': Buffer.from(this.client.e().n(), 'HEX').toString('base64'),
'ds:Exponent': 'AQAB',
},
},
EncryptionVersion: "E002"
EncryptionVersion: 'E002',
},
PartnerID: this.partnerId,
UserID: this.userId
UserID: this.userId,
};
return js2xmlparser.parse("HIARequestOrderData", xmlOrderData, this.xmlOptions);
};
return js2xmlparser.parse('HIARequestOrderData', xmlOrderData, this.xmlOptions);
}
toXML() {
return js2xmlparser.parse(this.root(), this._schema, this.xmlOptions);
};
}
};

View File

@ -7,7 +7,7 @@ module.exports = class HKD extends GenericOrder {
super(client);
this._schema.header = {
"@": { authenticate: true },
'@': { authenticate: true },
static: {
HostID: this.hostId,
Nonce: this.nonce(),
@ -15,29 +15,29 @@ module.exports = class HKD extends GenericOrder {
PartnerID: this.partnerId,
UserID: this.userId,
Product: {
"@": { Language: "de" },
"#": this.productString,
'@': { Language: 'de' },
'#': this.productString,
},
OrderDetails: {
OrderType: "HKD",
OrderAttribute: "DZHNN",
StandardOrderParams: ""
OrderType: 'HKD',
OrderAttribute: 'DZHNN',
StandardOrderParams: '',
},
BankPubKeyDigests: {
Authentication: {
"@": { Version: "X002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankX().publicDigest()
'@': { Version: 'X002', Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' },
'#': this.client.bankX().publicDigest(),
},
Encryption: {
"@": { Version: "E002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankE().publicDigest()
}
'@': { Version: 'E002', Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' },
'#': this.client.bankE().publicDigest(),
},
SecurityMedium: "0000"
},
SecurityMedium: '0000',
},
mutable: {
TransactionPhase: "Initialisation"
TransactionPhase: 'Initialisation',
},
};
}
};
};
};

View File

@ -7,7 +7,7 @@ module.exports = class HPB extends GenericOrder {
super(client);
this._schema.header = {
"@": { authenticate: true },
'@': { authenticate: true },
static: {
HostID: this.hostId,
Nonce: this.nonce(),
@ -15,20 +15,20 @@ module.exports = class HPB extends GenericOrder {
PartnerID: this.partnerId,
UserID: this.userId,
Product: {
"@": { Language: "de" },
"#": this.productString,
'@': { Language: 'de' },
'#': this.productString,
},
OrderDetails: {
OrderType: "HPB",
OrderAttribute: "DZHNN"
OrderType: 'HPB',
OrderAttribute: 'DZHNN',
},
SecurityMedium: "0000"
SecurityMedium: '0000',
},
mutable: {}
};
mutable: {},
};
}
root() {
return "ebicsNoPubKeyDigestsRequest";
};
root() { // eslint-disable-line class-methods-use-this
return 'ebicsNoPubKeyDigestsRequest';
}
};

View File

@ -7,7 +7,7 @@ module.exports = class HTD extends GenericOrder {
super(client);
this._schema.header = {
"@": { authenticate: true },
'@': { authenticate: true },
static: {
HostID: this.hostId,
Nonce: this.nonce(),
@ -15,29 +15,29 @@ module.exports = class HTD extends GenericOrder {
PartnerID: this.partnerId,
UserID: this.userId,
Product: {
"@": { Language: "de" },
"#": this.productString,
'@': { Language: 'de' },
'#': this.productString,
},
OrderDetails: {
OrderType: "HTD",
OrderAttribute: "DZHNN",
StandardOrderParams: ""
OrderType: 'HTD',
OrderAttribute: 'DZHNN',
StandardOrderParams: '',
},
BankPubKeyDigests: {
Authentication: {
"@": { Version: "X002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankX().publicDigest()
'@': { Version: 'X002', Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' },
'#': this.client.bankX().publicDigest(),
},
Encryption: {
"@": { Version: "E002", Algorithm: "http://www.w3.org/2001/04/xmlenc#sha256" },
"#": this.client.bankE().publicDigest()
}
'@': { Version: 'E002', Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' },
'#': this.client.bankE().publicDigest(),
},
SecurityMedium: "0000"
},
SecurityMedium: '0000',
},
mutable: {
TransactionPhase: "Initialisation"
TransactionPhase: 'Initialisation',
},
};
}
};
};
};

View File

@ -10,66 +10,66 @@ module.exports = class INI extends GenericOrder {
super(client);
this._schema = {
"@": {
"xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
xmlns: "urn:org:ebics:H004",
Version: "H004",
Revision: "1"
'@': {
'xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
xmlns: 'urn:org:ebics:H004',
Version: 'H004',
Revision: '1',
},
header: {
"@": { authenticate: true },
'@': { authenticate: true },
static: {
HostID: this.hostId,
PartnerID: this.partnerId,
UserID: this.userId,
Product: {
"@": { Language: "de" },
"#": this.productString,
'@': { Language: 'de' },
'#': this.productString,
},
OrderDetails: {
OrderType: "INI",
OrderAttribute: "DZNNN"
OrderType: 'INI',
OrderAttribute: 'DZNNN',
},
SecurityMedium: "0000"
SecurityMedium: '0000',
},
mutable: {}
mutable: {},
},
body: {
DataTransfer: {
OrderData: Buffer.from(zlib.deflateSync(this.keySignature())).toString('base64')
}
}
OrderData: Buffer.from(zlib.deflateSync(this.keySignature())).toString('base64'),
},
},
};
}
root() {
return "ebicsUnsecuredRequest";
};
root() { // eslint-disable-line class-methods-use-this
return 'ebicsUnsecuredRequest';
}
keySignature() {
const xmlOrderData = {
"@": {
"xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
xmlns: "http://www.ebics.org/S001"
'@': {
'xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
xmlns: 'http://www.ebics.org/S001',
},
SignaturePubKeyInfo: {
PubKeyValue: {
"ds:RSAKeyValue": {
"ds:Modulus": Buffer.from(this.client.a().n(), 'HEX').toString('base64'),
"ds:Exponent": "AQAB"
'ds:RSAKeyValue': {
'ds:Modulus': Buffer.from(this.client.a().n(), 'HEX').toString('base64'),
'ds:Exponent': 'AQAB',
},
TimeStamp: this.timestamp()
TimeStamp: this.timestamp(),
},
SignatureVersion: "A006"
SignatureVersion: 'A006',
},
PartnerID: this.partnerId,
UserID: this.userId
UserID: this.userId,
};
return js2xmlparser.parse("SignaturePubKeyOrderData", xmlOrderData, this.xmlOptions);
};
return js2xmlparser.parse('SignaturePubKeyOrderData', xmlOrderData, this.xmlOptions);
}
toXML() {
return js2xmlparser.parse(this.root(), this._schema, this.xmlOptions);

View File

@ -1,6 +1,6 @@
{
"name": "node-ebics-client",
"version": "0.0.35",
"name": "ebics-client",
"version": "0.0.36",
"description": "Node.js ISO 20022 Compliant EBICS Client",
"main": "index.js",
"scripts": {
@ -24,9 +24,12 @@
"js2xmlparser": "^3.0.0",
"moment": "^2.22.1",
"node-rsa": "^0.4.2",
"request": "^2.87.0",
"xml-c14n": "0.0.6",
"xml-crypto": "^0.10.1",
"xmldom": "^0.1.27",
"xpath": "0.0.27"
"xpath": "0.0.27",
"xpath.js": "^1.1.0"
},
"devDependencies": {
"eslint": "^4.19.1",