This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPayment.jsm
422 lines (371 loc) · 14.3 KB
/
Payment.jsm
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
this.EXPORTED_SYMBOLS = [];
const PAYMENT_IPC_MSG_NAMES = ["Payment:Pay",
"Payment:Success",
"Payment:Failed"];
const PREF_PAYMENTPROVIDERS_BRANCH = "dom.payment.provider.";
const PREF_PAYMENT_BRANCH = "dom.payment.";
const PREF_DEBUG = "dom.payment.debug";
XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
"@mozilla.org/parentprocessmessagemanager;1",
"nsIMessageListenerManager");
XPCOMUtils.defineLazyServiceGetter(this, "prefService",
"@mozilla.org/preferences-service;1",
"nsIPrefService");
var PaymentManager = {
init: function init() {
// Payment providers data are stored as a preference.
this.registeredProviders = null;
this.messageManagers = {};
// The dom.payment.skipHTTPSCheck pref is supposed to be used only during
// development process. This preference should not be active for a
// production build.
let paymentPrefs = prefService.getBranch(PREF_PAYMENT_BRANCH);
this.checkHttps = true;
try {
if (paymentPrefs.getPrefType("skipHTTPSCheck")) {
this.checkHttps = !paymentPrefs.getBoolPref("skipHTTPSCheck");
}
} catch(e) {}
for (let msgname of PAYMENT_IPC_MSG_NAMES) {
ppmm.addMessageListener(msgname, this);
}
Services.obs.addObserver(this, "xpcom-shutdown", false);
try {
this._debug =
Services.prefs.getPrefType(PREF_DEBUG) == Ci.nsIPrefBranch.PREF_BOOL
&& Services.prefs.getBoolPref(PREF_DEBUG);
} catch(e) {
this._debug = false;
}
},
/**
* Process a message from the content process.
*/
receiveMessage: function receiveMessage(aMessage) {
let name = aMessage.name;
let msg = aMessage.json;
if (this._debug) {
this.LOG("Received '" + name + "' message from content process");
}
switch (name) {
case "Payment:Pay": {
// First of all, we register the payment providers.
if (!this.registeredProviders) {
this.registeredProviders = {};
this.registerPaymentProviders();
}
// We save the message target message manager so we can later dispatch
// back messages without broadcasting to all child processes.
let requestId = msg.requestId;
this.messageManagers[requestId] = aMessage.target;
// We check the jwt type and look for a match within the
// registered payment providers to get the correct payment request
// information.
let paymentRequests = [];
let jwtTypes = [];
for (let i in msg.jwts) {
let pr = this.getPaymentRequestInfo(requestId, msg.jwts[i]);
if (!pr) {
continue;
}
// We consider jwt type repetition an error.
if (jwtTypes[pr.type]) {
this.paymentFailed(requestId,
"PAY_REQUEST_ERROR_DUPLICATED_JWT_TYPE");
return;
}
jwtTypes[pr.type] = true;
paymentRequests.push(pr);
}
if (!paymentRequests.length) {
this.paymentFailed(requestId,
"PAY_REQUEST_ERROR_NO_VALID_REQUEST_FOUND");
return;
}
// After getting the list of valid payment requests, we ask the user
// for confirmation before sending any request to any payment provider.
// If there is more than one choice, we also let the user select the one
// that he prefers.
let glue = Cc["@mozilla.org/payment/ui-glue;1"]
.createInstance(Ci.nsIPaymentUIGlue);
if (!glue) {
if (this._debug) {
this.LOG("Could not create nsIPaymentUIGlue instance");
}
this.paymentFailed(requestId,
"INTERNAL_ERROR_CREATE_PAYMENT_GLUE_FAILED");
return;
}
let confirmPaymentSuccessCb = function successCb(aRequestId,
aResult) {
// Get the appropriate payment provider data based on user's choice.
let selectedProvider = this.registeredProviders[aResult];
if (!selectedProvider || !selectedProvider.uri) {
if (this._debug) {
this.LOG("Could not retrieve a valid provider based on user's " +
"selection");
}
this.paymentFailed(aRequestId,
"INTERNAL_ERROR_NO_VALID_SELECTED_PROVIDER");
return;
}
let jwt;
for (let i in paymentRequests) {
if (paymentRequests[i].type == aResult) {
jwt = paymentRequests[i].jwt;
break;
}
}
if (!jwt) {
if (this._debug) {
this.LOG("The selected request has no JWT information " +
"associated");
}
this.paymentFailed(aRequestId,
"INTERNAL_ERROR_NO_JWT_ASSOCIATED_TO_REQUEST");
return;
}
this.showPaymentFlow(aRequestId, selectedProvider, jwt);
};
let confirmPaymentErrorCb = this.paymentFailed;
glue.confirmPaymentRequest(requestId,
paymentRequests,
confirmPaymentSuccessCb.bind(this),
confirmPaymentErrorCb.bind(this));
break;
}
case "Payment:Success":
case "Payment:Failed": {
let mm = this.messageManagers[msg.requestId];
mm.sendAsyncMessage(name, {
requestId: msg.requestId,
result: msg.result,
errorMsg: msg.errorMsg
});
break;
}
}
},
/**
* Helper function to register payment providers stored as preferences.
*/
registerPaymentProviders: function registerPaymentProviders() {
let paymentProviders = prefService
.getBranch(PREF_PAYMENTPROVIDERS_BRANCH)
.getChildList("");
// First get the numbers of the providers by getting all ###.uri prefs.
let nums = [];
for (let i in paymentProviders) {
let match = /^(\d+)\.uri$/.exec(paymentProviders[i]);
if (!match) {
continue;
} else {
nums.push(match[1]);
}
}
#ifdef MOZ_B2G
let appsService = Cc["@mozilla.org/AppsService;1"]
.getService(Ci.nsIAppsService);
let systemAppId = Ci.nsIScriptSecurityManager.NO_APP_ID;
try {
let manifestURL = Services.prefs.getCharPref("b2g.system_manifest_url");
systemAppId = appsService.getAppLocalIdByManifestURL(manifestURL);
this.LOG("System app id=" + systemAppId);
} catch(e) {}
#endif
// Now register the payment providers.
for (let i in nums) {
let branch = prefService
.getBranch(PREF_PAYMENTPROVIDERS_BRANCH + nums[i] + ".");
let vals = branch.getChildList("");
if (vals.length == 0) {
return;
}
try {
let type = branch.getCharPref("type");
if (type in this.registeredProviders) {
continue;
}
let provider = this.registeredProviders[type] = {
name: branch.getCharPref("name"),
uri: branch.getCharPref("uri"),
description: branch.getCharPref("description"),
requestMethod: branch.getCharPref("requestMethod")
};
#ifdef MOZ_B2G
// Let this payment provider access the firefox-accounts API when
// it's loaded in the trusted UI.
if (systemAppId != Ci.nsIScriptSecurityManager.NO_APP_ID) {
this.LOG("Granting firefox-accounts permission to " + provider.uri);
let uri = Services.io.newURI(provider.uri, null, null);
let attrs = {appId: systemAppId, inBrowser: true};
let principal =
Services.scriptSecurityManager.createCodebasePrincipal(uri, attrs);
Services.perms.addFromPrincipal(principal, "firefox-accounts",
Ci.nsIPermissionManager.ALLOW_ACTION,
Ci.nsIPermissionManager.EXPIRE_SESSION);
}
#endif
if (this._debug) {
this.LOG("Registered Payment Providers: " +
JSON.stringify(this.registeredProviders[type]));
}
} catch (ex) {
if (this._debug) {
this.LOG("An error ocurred registering a payment provider. " + ex);
}
}
}
},
/**
* Helper for sending a Payment:Failed message to the parent process.
*/
paymentFailed: function paymentFailed(aRequestId, aErrorMsg) {
let mm = this.messageManagers[aRequestId];
mm.sendAsyncMessage("Payment:Failed", {
requestId: aRequestId,
errorMsg: aErrorMsg
});
},
/**
* Helper function to get the payment request info according to the jwt
* type. Payment provider's data is stored as a preference.
*/
getPaymentRequestInfo: function getPaymentRequestInfo(aRequestId, aJwt) {
if (!aJwt) {
this.paymentFailed(aRequestId, "INTERNAL_ERROR_CALL_WITH_MISSING_JWT");
return true;
}
// First thing, we check that the jwt type is an allowed type and has a
// payment provider flow information associated.
// A jwt string consists in three parts separated by period ('.'): header,
// payload and signature.
let segments = aJwt.split('.');
if (segments.length !== 3) {
if (this._debug) {
this.LOG("Error getting payment provider's uri. " +
"Not enough or too many segments");
}
this.paymentFailed(aRequestId,
"PAY_REQUEST_ERROR_WRONG_SEGMENTS_COUNT");
return true;
}
let payloadObject;
try {
// We only care about the payload segment, which contains the jwt type
// that should match with any of the stored payment provider's data and
// the payment request information to be shown to the user.
// Before decoding the JWT string we need to normalize it to be compliant
// with RFC 4648.
segments[1] = segments[1].replace(/-/g, "+").replace(/_/g, "/");
let payload = atob(segments[1]);
if (this._debug) {
this.LOG("Payload " + payload);
}
if (!payload.length) {
this.paymentFailed(aRequestId, "PAY_REQUEST_ERROR_EMPTY_PAYLOAD");
return true;
}
payloadObject = JSON.parse(payload);
if (!payloadObject) {
this.paymentFailed(aRequestId,
"PAY_REQUEST_ERROR_ERROR_PARSING_JWT_PAYLOAD");
return true;
}
} catch (e) {
this.paymentFailed(aRequestId,
"PAY_REQUEST_ERROR_ERROR_DECODING_JWT");
return true;
}
if (!payloadObject.typ) {
this.paymentFailed(aRequestId,
"PAY_REQUEST_ERROR_NO_TYP_PARAMETER");
return true;
}
if (!payloadObject.request) {
this.paymentFailed(aRequestId,
"PAY_REQUEST_ERROR_NO_REQUEST_PARAMETER");
return true;
}
// Once we got the jwt 'typ' value we look for a match within the payment
// providers stored preferences. If the jwt 'typ' is not recognized as one
// of the allowed values for registered payment providers, we skip the jwt
// validation but we don't fire any error. This way developers might have
// a default set of well formed JWTs that might be used in different B2G
// devices with a different set of allowed payment providers.
let provider = this.registeredProviders[payloadObject.typ];
if (!provider) {
if (this._debug) {
this.LOG("Not registered payment provider for jwt type: " +
payloadObject.typ);
}
return false;
}
if (!provider.uri || !provider.name) {
this.paymentFailed(aRequestId,
"INTERNAL_ERROR_WRONG_REGISTERED_PAY_PROVIDER");
return true;
}
// We only allow https for payment providers uris.
if (this.checkHttps && !/^https/.exec(provider.uri.toLowerCase())) {
// We should never get this far.
if (this._debug) {
this.LOG("Payment provider uris must be https: " + provider.uri);
}
this.paymentFailed(aRequestId,
"INTERNAL_ERROR_NON_HTTPS_PROVIDER_URI");
return true;
}
let pldRequest = payloadObject.request;
return { jwt: aJwt, type: payloadObject.typ, providerName: provider.name };
},
showPaymentFlow: function showPaymentFlow(aRequestId,
aPaymentProvider,
aJwt) {
let paymentFlowInfo = Cc["@mozilla.org/payment/flow-info;1"]
.createInstance(Ci.nsIPaymentFlowInfo);
paymentFlowInfo.uri = aPaymentProvider.uri;
paymentFlowInfo.requestMethod = aPaymentProvider.requestMethod;
paymentFlowInfo.jwt = aJwt;
paymentFlowInfo.name = aPaymentProvider.name;
paymentFlowInfo.description = aPaymentProvider.description;
let glue = Cc["@mozilla.org/payment/ui-glue;1"]
.createInstance(Ci.nsIPaymentUIGlue);
if (!glue) {
if (this._debug) {
this.LOG("Could not create nsIPaymentUIGlue instance");
}
this.paymentFailed(aRequestId,
"INTERNAL_ERROR_CREATE_PAYMENT_GLUE_FAILED");
return false;
}
glue.showPaymentFlow(aRequestId,
paymentFlowInfo,
this.paymentFailed.bind(this));
},
// nsIObserver
observe: function observe(subject, topic, data) {
if (topic == "xpcom-shutdown") {
for (let msgname of PAYMENT_IPC_MSG_NAMES) {
ppmm.removeMessageListener(msgname, this);
}
this.registeredProviders = null;
this.messageManagers = null;
Services.obs.removeObserver(this, "xpcom-shutdown");
}
},
LOG: function LOG(s) {
if (!this._debug) {
return;
}
dump("-*- PaymentManager: " + s + "\n");
}
};
PaymentManager.init();