-
Notifications
You must be signed in to change notification settings - Fork 57
/
index.js
278 lines (247 loc) · 8.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
'use strict';
// Native
const crypto = require('crypto');
const https = require('https');
const query = require('querystring');
const url = require('url');
// Modules
const secp256k1 = require('secp256k1');
function PaymentProtocol(requestOptions, trustedKeys) {
this.options = Object.assign({}, { agent: false }, requestOptions);
this.trustedKeys = trustedKeys;
if (!this.trustedKeys || !Object.keys(this.trustedKeys).length) {
throw new Error('Invalid constructor, no trusted keys added to agent');
}
}
/**
* Internal method for making requests asynchronously
* @param {Object} options
* @return {Promise<Object{rawBody: String, headers: Object}>}
* @private
*/
PaymentProtocol.prototype._asyncRequest = async function(options) {
let requestOptions = Object.assign({}, this.options, options);
const parsedUrl = url.parse(requestOptions.url);
// Copy headers directly as they're objects
requestOptions.headers = Object.assign({}, this.options.headers, options.headers);
requestOptions.hostname = parsedUrl.hostname;
requestOptions.path = parsedUrl.path;
requestOptions.port = parsedUrl.port;
delete requestOptions.url;
return new Promise((resolve, reject) => {
const request = https.request(requestOptions, (response) => {
const body = [];
response.on('data', chunk => body.push(chunk));
response.on('end', () => {
if (response.statusCode !== 200) {
console.log('Status', response.statusCode);
return reject(new Error(body.join('')));
}
resolve({
rawBody: body.join(''),
headers: response.headers
});
});
});
request.on('error', reject);
if (requestOptions.body) {
request.write(requestOptions.body);
}
request.end();
});
};
/**
* Makes a request to the given url and returns the raw JSON string retrieved as well as the headers
* @param {string} paymentUrl the payment protocol specific url
* @param {boolean} unsafeBypassValidation bypasses signature verification on the request (DO NOT USE IN PRODUCTION)
*/
PaymentProtocol.prototype.getPaymentOptions = async function(paymentUrl, unsafeBypassValidation = false) {
const paymentUrlObject = url.parse(paymentUrl);
// Detect 'bitcoin:' urls and extract payment-protocol section
if (paymentUrlObject.protocol !== 'http:' && paymentUrlObject.protocol !== 'https:') {
let uriQuery = query.decode(paymentUrlObject.query);
if (!uriQuery.r) {
throw new Error('Invalid payment protocol url');
} else {
paymentUrl = uriQuery.r;
}
}
const { rawBody, headers } = await this._asyncRequest({
method: 'GET',
url: paymentUrl,
headers: {
Accept: 'application/payment-options',
'x-paypro-version': 2
}
});
return await this.verifyResponse(paymentUrl, rawBody, headers, unsafeBypassValidation);
};
/**
* Selects which chain and currency option the user will be using for payment
* @param {string} paymentUrl the payment protocol specific url
* @param chain
* @param currency
* @param unsafeBypassValidation
* @return {Promise<{requestUrl, responseData}|{keyData, requestUrl, responseData}>}
*/
PaymentProtocol.prototype.selectPaymentOption = async function(paymentUrl, chain, currency, unsafeBypassValidation = false) {
const { rawBody, headers } = await this._asyncRequest({
url: paymentUrl,
method: 'POST',
headers: {
'Content-Type': 'application/payment-request',
'x-paypro-version': 2
},
body: JSON.stringify({
chain,
currency
})
});
return await this.verifyResponse(paymentUrl, rawBody, headers, unsafeBypassValidation);
};
/**
* Sends an unsigned raw transaction to the server for verification of outputs and fee amount
* @param {string} paymentUrl - the payment protocol specific url
* @param {string} chain - The cryptocurrency chain of the payment (BTC, BCH, ETH, etc)
* @param {string} currency - When spending a token on top of a chain, such as GUSD on ETH this would be GUSD,
* if no token is used this should be blank
* @param [{tx: string, weightedSize: number}] unsignedTransactions - Hexadecimal format unsigned transactions
* @param {boolean} unsafeBypassValidation
* @return {Promise<{responseData: any}>}
*/
PaymentProtocol.prototype.verifyUnsignedPayment = async function({
paymentUrl,
chain,
currency,
unsignedTransactions,
unsafeBypassValidation = false
}) {
const { rawBody, headers } = await this._asyncRequest({
url: paymentUrl,
method: 'POST',
headers: {
'Content-Type': 'application/payment-verification',
'x-paypro-version': 2
},
body: JSON.stringify({
chain,
currency,
transactions: unsignedTransactions
})
});
return await this.verifyResponse(paymentUrl, rawBody, headers, unsafeBypassValidation);
};
/**
* Sends a signed transaction as the final step for payment
* @param {string} paymentUrl the payment protocol specific url
* @param {string} chain
* @param {string} currency
* @param {[string]} signedTransactions
* @param {number} weightedSize
* @param {boolean} unsafeBypassValidation
* @return {Promise<{keyData: Object, requestUrl: String, responseData: Object}|{requestUrl: String, responseData: Object}>}
*/
PaymentProtocol.prototype.sendSignedPayment = async function({
paymentUrl,
chain,
currency,
signedTransactions,
unsafeBypassValidation = false
}) {
const { rawBody, headers } = await this._asyncRequest({
url: paymentUrl,
method: 'POST',
headers: {
'Content-Type': 'application/payment',
'x-paypro-version': 2
},
body: JSON.stringify({
chain,
currency,
transactions: signedTransactions
})
});
return await this.verifyResponse(paymentUrl, rawBody, headers, unsafeBypassValidation);
};
/**
* Verifies the signature on any response from the payment requestor
* @param {String} requestUrl - Url which the request was made to
* @param {String} rawBody - The raw string body of the response
* @param {Object} headers -
* @param {Boolean} unsafeBypassValidation
* @return {Promise<{keyData: Object, requestUrl: String, responseData: Object}|{requestUrl: String, responseData: Object}>}
*/
PaymentProtocol.prototype.verifyResponse = async function(requestUrl, rawBody, headers, unsafeBypassValidation) {
if (!requestUrl) {
throw new Error('Parameter requestUrl is required');
}
if (!rawBody) {
throw new Error('Parameter rawBody is required');
}
if (!headers) {
throw new Error('Parameter headers is required');
}
let responseData;
try {
responseData = JSON.parse(rawBody);
} catch (e) {
throw new Error('Invalid JSON in response body');
}
if (unsafeBypassValidation) {
return { requestUrl, responseData };
}
const hash = headers.digest.split('=')[1];
const signature = headers.signature;
const signatureType = headers['x-signature-type'];
const identity = headers['x-identity'];
let host;
try {
host = url.parse(requestUrl).hostname;
} catch (e) {
}
if (!host) {
throw new Error('Invalid requestUrl');
}
if (!signatureType) {
throw new Error('Response missing x-signature-type header');
}
if (typeof signatureType !== 'string') {
throw new Error('Invalid x-signature-type header');
}
if (signatureType !== 'ecc') {
throw new Error(`Unknown signature type ${signatureType}`);
}
if (!signature) {
throw new Error('Response missing signature header');
}
if (typeof signature !== 'string') {
throw new Error('Invalid signature header');
}
if (!identity) {
throw new Error('Response missing x-identity header');
}
if (typeof identity !== 'string') {
throw new Error('Invalid identity header');
}
if (!this.trustedKeys[identity]) {
throw new Error(`Response signed by unknown key (${identity}), unable to validate`);
}
const keyData = this.trustedKeys[identity];
const actualHash = crypto.createHash('sha256').update(rawBody, 'utf8').digest('hex');
if (hash !== actualHash) {
throw new Error(`Response body hash does not match digest header. Actual: ${actualHash} Expected: ${hash}`);
}
if (!keyData.domains.includes(host)) {
throw new Error(`The key on the response (${identity}) is not trusted for domain ${host}`);
}
let valid = secp256k1.verify(
Buffer.from(hash, 'hex'),
Buffer.from(signature, 'hex'),
Buffer.from(keyData.publicKey, 'hex')
);
if (!valid) {
throw new Error('Response signature invalid');
}
return { requestUrl, responseData, keyData };
};
module.exports = PaymentProtocol;