/
application.js
233 lines (201 loc) · 6.92 KB
/
application.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
import JSONRPC from 'jsonrpc-dispatch';
import { fixedTimeCompare } from '../lib/string';
import { EventEmitter } from 'events';
import URI from '../lib/uri';
import logger from '../lib/logger';
import { calculateHeight, calculateWidth } from '../lib/dimension';
import MutationObserver from 'mutation-observer';
/** Application class which represents an embedded application. */
class Application extends EventEmitter {
init({ acls = [], secret = null, onReady = null }) {
this.acls = [].concat(acls);
this.secret = secret;
this.onReady = onReady;
this.resizeConfig = null;
this.requestResize = this.requestResize.bind(this);
this.handleConsumerMessage = this.handleConsumerMessage.bind(this);
this.authorizeConsumer = this.authorizeConsumer.bind(this);
this.verifyChallenge = this.verifyChallenge.bind(this);
this.emitError = this.emitError.bind(this);
// If the document referer (parent frame) origin is trusted, default that
// to the active ACL;
const parentOrigin = new URI(document.referrer).origin;
if (this.acls.includes(parentOrigin)) {
this.activeACL = parentOrigin;
}
const self = this;
this.JSONRPC = new JSONRPC(
self.send.bind(self),
{
event(event, detail) {
self.emit(event, detail);
return Promise.resolve();
},
resize(config = {}) {
self.resizeConfig = config;
self.requestResize();
// Registers a mutation observer for body
const observer = new MutationObserver(
(mutations) => self.requestResize()
);
observer.observe(
document.body,
{ attributes: true, childList: true, characterData: true, subtree: true }
);
// Registers a listener to window.onresize
// Optimizes the listener by debouncing (https://bencentra.com/code/2015/02/27/optimizing-window-resize.html#debouncing)
const interval = 100; // Resize event will be considered complete if no follow-up events within `interval` ms.
let resizeTimer = null;
window.onresize = (event) => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => self.requestResize(), interval);
};
return Promise.resolve();
},
}
);
}
requestResize() {
if (this.resizeConfig.customCal) {
this.JSONRPC.notification('resize');
} else if (this.resizeConfig.autoResizeWidth) {
const width = calculateWidth(this.resizeConfig.WidthCalculationMethod);
this.JSONRPC.notification('resize', [null, `${width}px`]);
} else {
const height = calculateHeight(this.resizeConfig.heightCalculationMethod);
this.JSONRPC.notification('resize', [`${height}px`]);
}
}
/**
* Triggers an event in the parent application.
* @param {string} event - The event name to trigger.
* @param {object} detail - The data context to send with the event.
*/
trigger(event, detail) {
this.JSONRPC.notification('event', [event, detail]);
}
/**
* Request to mount an application fullscreen.
* @param {string} url - The url of the application to mount.
*/
fullscreen(url) {
this.trigger('xfc.fullscreen', url);
}
/**
* Sends http errors to consumer.
* @param {object} error - an object containing error details
*/
httpError(error = {}) {
this.trigger('xfc.provider.httpError', error);
}
/**
* Request to load a new page of given url
* @param {string} url - The url of the new page.
*/
loadPage(url) {
this.JSONRPC.notification('loadPage', [url]);
}
/**
* Launches the provider app and begins the authorization sequence.
*/
launch() {
if (window.self !== window.top) {
// 1: Setup listeners for all incoming communication
window.addEventListener('message', this.handleConsumerMessage);
// 2: Begin launch and authorization sequence
this.JSONRPC.notification('launch');
// 2a. We have a specific origin to trust (excluding wildcard *),
// wait for response to authorize.
if (this.acls.some((x) => x !== '*')) {
this.JSONRPC.request('authorizeConsumer', [])
.then(this.authorizeConsumer)
.catch(this.emitError);
}
// 2b. We don't know who to trust, challenge parent for secret
if (this.secret) {
this.JSONRPC.request('challengeConsumer', [])
.then(this.verifyChallenge)
.catch(this.emitError);
}
// If not embedded, immediately authorize content
} else {
this.authorizeConsumer();
}
}
/**
* Handles an incoming message event by processing the JSONRPC request
* @param {object} event - The emitted message event.
*/
handleConsumerMessage(event) {
// Ignore Non-JSONRPC messages or messages not from the parent frame
if (!event.data.jsonrpc || event.source !== window.parent) {
return;
}
logger.log('<< provider', event.origin, event.data);
// For Chrome, the origin property is in the event.originalEvent object
const origin = event.origin || event.originalEvent.origin;
if (!this.activeACL && this.acls.includes(origin)) {
this.activeACL = origin;
}
if (this.acls.includes('*') || this.acls.includes(origin)) {
this.JSONRPC.handle(event.data);
}
}
/**
* Send the given message to the frame parent.
* @param {object} message - The message to send.
*/
send(message) {
// Dont' send messages if not embedded
if (window.self === window.top) {
return;
}
if (this.acls.length < 1) {
logger.error('Message not sent, no acls provided.');
}
if (message) {
logger.log('>> provider', this.acls, message);
if (this.activeACL) {
parent.postMessage(message, this.activeACL);
} else {
this.acls.forEach((uri) => parent.postMessage(message, uri));
}
}
}
/**
* Verify the challange made to the parent frame.
* @param {string} secretAttempt - The secret string to verify
*/
verifyChallenge(secretAttempt) {
const authorize = () => {
this.acls = ['*'];
this.authorizeConsumer();
};
if (typeof this.secret === 'string' && fixedTimeCompare(this.secret, secretAttempt)) {
authorize();
} else if (typeof this.secret === 'function') {
this.secret.call(this, secretAttempt).then(authorize);
}
}
/**
* Authorize the parent frame by unhiding the container.
*/
authorizeConsumer() {
document.documentElement.removeAttribute('hidden');
// Emit a ready event
this.emit('xfc.ready');
this.JSONRPC.notification('authorized', [{ url: window.location.href }]);
// If there is an onReady callback, execute it
if (typeof this.onReady === 'function') {
this.onReady.call(this);
}
}
/**
* Emit the given error
* @param {object} error - an error object containing error code and error message
*/
emitError(error) {
this.emit('xfc.error', error);
}
}
export default Application;