-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathjwsSigner.js
More file actions
158 lines (124 loc) · 6.24 KB
/
Copy pathjwsSigner.js
File metadata and controls
158 lines (124 loc) · 6.24 KB
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
/*****
License
--------------
Copyright © 2020-2025 Mojaloop Foundation
The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Contributors
--------------
This is the official list of the Mojaloop project contributors for this file.
Names of the original copyright holders (individuals or organizations)
should be listed with a '*' in the first column. People who have
contributed from an organization can be listed under the organization
that actually holds the copyright for their contributions (see the
Mojaloop Foundation for an example). Those individuals should have
their names indented and be marked with a '-'. Email address can be added
optionally within square brackets <email>.
* Mojaloop Foundation
- Name Surname <name.surname@mojaloop.io>
* ModusBox
- James Bush - james.bush@modusbox.com - ORIGINAL AUTHOR
--------------
******/
'use strict';
const jws = require('jws');
const safeStringify = require('fast-safe-stringify');
const uriRegex = /(?:^.*)(\/(participants|parties|quotes|bulkQuotes|transfers|bulkTransfers|transactionRequests|thirdpartyRequests|authorizations|consents|consentRequests|fxQuotes|fxTransfers|)(\/.*)*)$/;
/**
* Provides methods for Mojaloop compliant JWS signing and signature verification
*/
class JwsSigner {
constructor(config) {
this.logger = config.logger?.child({ component: this.constructor.name }) || console;
if(!config.signingKey) {
throw new Error('Signing key must be supplied as config argument');
}
// the JWS signature algorithm to use. Note that Mojaloop spec requires RS256 at present
this.alg = config.signingKey.includes('BEGIN EC ') ? 'ES256' : 'RS256';
this.signingKey = config.signingKey;
}
/**
* Adds JWS headers to an outgoing HTTP request options object
*
* @param requestOptions {object} a request-promise-native/axios style request options object
* (see https://github.com/request/request-promise-native)
* (see https://github.com/axios/axios)
*/
sign(requestOptions) {
this.logger.isDebugEnabled && this.logger.debug(`JWS Signing request: ${safeStringify(requestOptions)}`);
const payload = requestOptions.body || requestOptions.data;
const uri = requestOptions.uri || requestOptions.url;
if(!payload) {
throw new Error('Cannot sign with no body');
}
const uriMatches = uriRegex.exec(uri);
if(!uriMatches || uriMatches.length < 2) {
throw new Error(`URI not valid for protected header: ${uri}`);
}
// add required JWS headers to the request options
requestOptions.headers['fspiop-http-method'] = requestOptions.method.toUpperCase();
requestOptions.headers['fspiop-uri'] = uriMatches[1];
// get the signature and add it to the header
requestOptions.headers['fspiop-signature'] = this.getSignature(requestOptions);
if (requestOptions.body && typeof requestOptions.body !== 'string') {
requestOptions.body = safeStringify(requestOptions.body);
}
if (requestOptions.data && typeof requestOptions.data !== 'string') {
requestOptions.data = safeStringify(requestOptions.data);
}
}
/**
* Returns JWS signature for an outgoing HTTP request options object
*
* @param requestOptions {object} a request-promise-native/axios style request options object
* (see https://github.com/request/request-promise-native)
* (see https://github.com/axios/axios)
*
* @returns {string} - JWS Signature as a string
*/
getSignature(requestOptions) {
this.logger.isDebugEnabled && this.logger.debug(`Get JWS Signature: ${safeStringify(requestOptions)}`);
const payload = requestOptions.body || requestOptions.data;
const uri = requestOptions.uri || requestOptions.url;
if(!payload) {
throw new Error('Cannot sign with no body');
}
const uriMatches = uriRegex.exec(uri);
if(!uriMatches || uriMatches.length < 2) {
throw new Error(`URI not valid for protected header: ${uri}`);
}
// generate the protected header as base64url encoding of UTF-8 encoding of JSON string
// Note: Property names are case sensitive in the protected header object even though they are
// not case sensitive in the actual HTTP headers
const protectedHeaderObject = {
alg: this.alg,
'FSPIOP-URI': requestOptions.headers['fspiop-uri'],
'FSPIOP-HTTP-Method': requestOptions.method.toUpperCase(),
'FSPIOP-Source': requestOptions.headers['fspiop-source']
};
// set destination in the protected header object if it is present in the request headers
if (requestOptions.headers['fspiop-destination']) {
protectedHeaderObject['FSPIOP-Destination'] = requestOptions.headers['fspiop-destination'];
}
// set date in the protected header object if it is present in the request headers
if (requestOptions.headers['date']) {
protectedHeaderObject['Date'] = requestOptions.headers['date'];
}
// now we sign
const token = jws.sign({
header: protectedHeaderObject,
payload,
secret: this.signingKey,
encoding: 'utf8'
});
// now set the signature header as JSON encoding of the signature and protected header as per mojaloop spec
const [ protectedHeaderBase64, , signature ] = token.split('.');
const signatureObject = {
signature: signature.replace('"', ''),
protectedHeader: protectedHeaderBase64.replace('"', '')
};
return safeStringify(signatureObject);
}
}
module.exports = JwsSigner;