-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathpostMessage.js
More file actions
71 lines (61 loc) · 2.11 KB
/
postMessage.js
File metadata and controls
71 lines (61 loc) · 2.11 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
import { uniqueID } from '@krakenjs/belter/src';
// these constants are defined in PostMessenger
const POSTMESSENGER_EVENT_TYPES = {
ACK: 'ack',
MESSAGE: 'message'
};
const POSTMESSENGER_ACK_PAYLOAD = {
ok: 'true'
};
// these constants should maintain parity with MESSAGE_MODAL_EVENT_NAMES in core-web-sdk
export const POSTMESSENGER_EVENT_NAMES = {
CALCULATE: 'paypal-messages-modal-calculate',
CLOSE: 'paypal-messages-modal-close',
SHOW: 'paypal-messages-modal-show'
};
export function sendEvent(payload, trustedOrigin) {
if (!trustedOrigin) {
return;
}
const isTest = process.env.NODE_ENV === 'test';
const targetWindow = !isTest && window.parent === window ? window.opener : window.parent;
targetWindow.postMessage(payload, trustedOrigin);
}
// This function provides data security by preventing accidentally exposing sensitive data; we are adding
// an extra layer of validation here by only allowing explicitly approved fields to be included
function createSafePayload(unscreenedPayload) {
const allowedFields = [
'linkName' // close event
];
const safePayload = {};
if (unscreenedPayload) {
const entries = Object.entries(unscreenedPayload);
entries.forEach(entry => {
const [key, value] = entry;
if (allowedFields.includes(key)) {
safePayload[key] = value;
} else {
console.warn(`modal hook payload param should be allowlisted if secure: ${key}`);
}
});
}
return safePayload;
}
export function createPostMessengerEvent(typeArg, eventName, eventPayloadArg) {
let type;
let eventPayload;
if (typeArg === 'ack') {
type = POSTMESSENGER_EVENT_TYPES.ACK;
eventPayload = POSTMESSENGER_ACK_PAYLOAD;
} else if (typeArg === 'message') {
type = POSTMESSENGER_EVENT_TYPES.MESSAGE;
// createSafePayload, only call this if a payload is sent
eventPayload = createSafePayload(eventPayloadArg);
}
return {
eventName,
id: uniqueID(),
type,
eventPayload: eventPayload || {}
};
}