forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlive-preview-loader.html
More file actions
325 lines (300 loc) · 14.1 KB
/
live-preview-loader.html
File metadata and controls
325 lines (300 loc) · 14.1 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Phoenix Live Preview Loader...</title>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
}
iframe {
width: 100%;
height: 100%;
border: none; /* Removes the default border around an iframe */
}
</style>
<style>
.outer-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
z-index: 2;
}
.dialog-container {
border: 1px solid #ccc;
background-color: #fff;
padding: 20px;
box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
/* Other styles remain the same */
}
.dialog-title {
font-size: 1.2em;
margin-bottom: 10px;
}
.dialog-message {
margin-bottom: 20px;
}
.dialog-buttons {
text-align: right;
}
button {
padding: 5px 10px;
margin-left: 10px;
background-color: #eee; /* Light background for buttons */
color: #000; /* Dark text for buttons */
border: 1px solid #ccc; /* Border for buttons */
}
/* Dark theme styles */
@media (prefers-color-scheme: dark) {
.outer-container {
background-color: #1e1e1e; /* Dark background for the body */
color: #ffffff; /* Light text color for dark theme */
}
.dialog-container {
border: 1px solid #444; /* Darker border for the dialog */
background-color: #2a2a2a; /* Dark background for the dialog */
}
button {
background-color: #4a4a4a; /* Darker background for buttons */
color: #fff; /* Light text for buttons */
border: 1px solid #6a6a6a; /* Border for buttons */
}
button:hover {
background-color: #5a5a5a; /* Lighter background on hover for buttons */
}
}
</style>
<script>
const TRUSTED_ORIGINS = {
'http://localhost:8000': true, // phcode dev server
'http://localhost:8001': true, // phcode dev live preview server
'http://localhost:5000': true, // playwright tests
'http://127.0.0.1:8000': true, // phcode dev server
'http://127.0.0.1:8001': true, // phcode dev live preview server
'http://127.0.0.1:5000': true, // playwright tests
'https://phcode.live': true, // phcode prod live preview server
'https://phcode.dev': true,
'https://dev.phcode.dev': true,
'https://staging.phcode.dev': true,
'https://create.phcode.dev': true
};
let okMessageTemplate;
function isTrustedURL(url) {
if(!url){
return false;
}
for(let trustedUrl of Object.keys(TRUSTED_ORIGINS)){
if(url.startsWith(trustedUrl)){
return true;
}
}
return false;
}
const pageLoaderID = crypto.randomUUID();
let securityAlertAcknowledged = false;
let previewURL;
let trustedProjects = [];
let currentProjectRoot;
function getTrustOkButton() {
if(! okMessageTemplate){
return "Trust Project?";
}
if(!currentProjectRoot){
return okMessageTemplate.replace("{0}", "");
}
let projectName = currentProjectRoot;
if(projectName.endsWith("/")){
projectName = projectName.slice(0, -1);
}
projectName = projectName.split("/");
projectName = projectName[projectName.length-1];
return okMessageTemplate.replace("{0}", projectName);
}
function setupNavigationWatcher(controllingPhoenixInstanceID) {
let livepreviewServerIframe = document.getElementById("live-preview-server-iframe");
const LOG_LIVE_PREVIEW_KEY= "logLivePreview";
let loggingEnabled = localStorage.getItem(LOG_LIVE_PREVIEW_KEY) || "false";
const isLoggingEnabled = loggingEnabled.toLowerCase() === 'true';
function _debugLog(...args) {
if(isLoggingEnabled) {
console.log(...args);
}
}
const LOADER_BROADCAST_ID = `live-preview-loader-${controllingPhoenixInstanceID}`;
const navigatorChannel = new BroadcastChannel(LOADER_BROADCAST_ID);
const LIVE_PREVIEW_MESSENGER_CHANNEL = `live-preview-messenger-${controllingPhoenixInstanceID}`;
const phcodeBroadcastMessageChannel = new BroadcastChannel(LIVE_PREVIEW_MESSENGER_CHANNEL);
navigatorChannel.onmessage = (event) => {
_debugLog("Live Preview loader channel: Browser received event from Phoenix: ", JSON.stringify(event.data));
const type = event.data.type;
const dialog = document.getElementById('outer-container');
switch (type) {
case "INITIAL_URL_NAVIGATE":
previewURL = event.data.URL;
if(!securityAlertAcknowledged || event.data.pageLoaderID !== pageLoaderID){
return;
}
_debugLog("initial URL page: ", previewURL);
// we dont need to check for trusted domain here as the live preview nav channel is only
// accessible by the editor domain phcode.dev/localhost etc. This page will not load any page
// in iframe without explicit permission grant from the editor. same for all uses below
document.getElementById("previewFrame").src = previewURL;
return;
case "REDIRECT_PAGE":
previewURL = event.data.URL;
if(!securityAlertAcknowledged){
return;
}
_debugLog("Loading page: ", previewURL);
if(event.data.force || document.getElementById("previewFrame").src !== previewURL) {
document.getElementById("previewFrame").src = previewURL;
}
return;
case "UPDATE_TITLE_ICON":
// The live preview frame will send us its title and favicon for us to set the window
// title and favicon. If it is that message, then, set it up
if(event.data.title || event.data.title === '') {
document.title = event.data.title;
}
if(event.data.faviconBase64){
// Update the favicon
let link = document.querySelector("link[rel~='icon']");
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.getElementsByTagName('head')[0].appendChild(link);
}
link.href = event.data.faviconBase64;
}
return;
case "PROJECT_SWITCH":
currentProjectRoot = event.data.projectRoot;
document.getElementById('okButton').textContent = getTrustOkButton();
if(trustedProjects[currentProjectRoot] && dialog){
dialog.style.display = 'none';
document.getElementById('previewFrame').src = decodeURIComponent(previewURL);
securityAlertAcknowledged = true;
return;
}
securityAlertAcknowledged = false;
_debugLog("Project switched. Disable live preview tabs for security on untrusted project.");
document.getElementById("previewFrame").src = 'about:blank';
if(dialog){
dialog.style.display = 'flex';
}
return;
case 'TAB_LOADER_ONLINE': return; // loop-back message do nothing, this is for phoenix ot process.
default:
console.error("Unknown live preivew broadcast message received!: ", event);
}
}
setInterval(()=>{
// send page loader heartbeat
navigatorChannel.postMessage({
type: 'TAB_LOADER_ONLINE',
pageLoaderID: pageLoaderID,
url: previewURL
});
}, 3000);
navigatorChannel.postMessage({
type: 'GET_INITIAL_URL',
pageLoaderID: pageLoaderID
});
phcodeBroadcastMessageChannel.onmessage = (event) => {
_debugLog("Live Preview message channel: Browser received event from Phoenix: ", JSON.stringify(event.data));
if(event.data.pageLoaderID && event.data.pageLoaderID !== pageLoaderID){
// this message is not for this page loader window.
return;
}
// This is intended to the embedded live preview server frame which processes the request. just pass
livepreviewServerIframe.contentWindow.postMessage(event.data.data, '*');
}
// These messages are sent from either the live preview frame or the server frame.
window.addEventListener('message', function(event) {
// Security check: ensure the message is from the expected domain
if (!TRUSTED_ORIGINS[event.origin]) {
return;
}
// this is for phoenix to process, pass it on
phcodeBroadcastMessageChannel.postMessage({
pageLoaderID: pageLoaderID,
data: event.data
});
});
function securityOk() {
const dialog = document.getElementById('outer-container');
dialog.style.display = 'none';
document.getElementById('previewFrame').src = decodeURIComponent(previewURL);
securityAlertAcknowledged = true;
trustedProjects[currentProjectRoot] = true;
sessionStorage.setItem(SESSION_SECURITY_CLEAR_KEY+currentProjectRoot, 'true');
}
document.getElementById('okButton').addEventListener('click', function() {
securityOk();
});
const SESSION_SECURITY_CLEAR_KEY = "LIVE_PREVIEW_SESSION_SECURITY_CLEAR";
const isAck = sessionStorage.getItem(SESSION_SECURITY_CLEAR_KEY+currentProjectRoot);
if(isAck){
securityOk();
}
}
function navigateToInitialURL() {
const queryParams = new URLSearchParams(window.location.search);
const phoenixInstanceID = queryParams.get('phoenixInstanceID');
const virtualServerURL = queryParams.get('virtualServerURL');
const localiseMessage = queryParams.get('localMessage');
const appName = queryParams.get('appName');
// do not pass in any live preview initial urls as it can lead to spoofing phcode.dev doamin by just
// calling this page.
okMessageTemplate = decodeURIComponent(queryParams.get('okMessage'));
currentProjectRoot = queryParams.get('initialProjectRoot');
if(!phoenixInstanceID || !virtualServerURL || !appName){
console.error("Expected required query strings: phoenixInstanceID, virtualServerURL, appName");
return;
}
setupNavigationWatcher(phoenixInstanceID);
let livepreviewServerIframe = document.getElementById("live-preview-server-iframe");
let serverURL = `${decodeURIComponent(virtualServerURL)}?parentOrigin=${location.origin}`;
if(isTrustedURL(serverURL)) {
livepreviewServerIframe.setAttribute("src", serverURL);
}
document.getElementById('okButton').textContent = getTrustOkButton();
localiseMessage && (document.getElementById('dialog-message').textContent = decodeURIComponent(localiseMessage));
appName && (document.getElementById('appName').textContent = decodeURIComponent(appName));
}
</script>
</head>
<body onload="navigateToInitialURL()">
<div id="outer-container" class="outer-container">
<div id='dialog-container' class="dialog-container">
<div id="appName" class="dialog-title">Phoenix Code Live Preview</div>
<div id="dialog-message" class="dialog-message">
You are about to open an HTML file for live preview. Please proceed only if you trust the source of this project. Click 'OK' to continue, or close this window if you do not trust the source.
</div>
<div class="dialog-buttons">
<button id="okButton">Trust Project</button>
</div>
</div>
</div>
<iframe id="live-preview-server-iframe"
title="live preview server"
src="about:blank"
style="width:100%;"
sandbox="allow-same-origin allow-scripts"
hidden>
</iframe>
<iframe id="previewFrame"
title="live preview"
src="about:blank"
sandbox="allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox allow-forms allow-modals allow-pointer-lock allow-downloads">
</iframe>
</body>
</html>