-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttps-preview.js
More file actions
188 lines (169 loc) · 5.4 KB
/
Copy pathhttps-preview.js
File metadata and controls
188 lines (169 loc) · 5.4 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
"use strict";
const childProcess = require("child_process");
const fs = require("fs");
const http = require("http");
const https = require("https");
const path = require("path");
const root = __dirname;
const port = Number(process.argv[2] || 4190);
const origin = "http://127.0.0.1:" + port;
const toolsDir = path.join(root, "tools");
const cloudflared = path.join(toolsDir, "cloudflared.exe");
const logDir = path.join(root, "debug-sheets");
const stamp = timestamp();
const logFile = path.join(logDir, "cloudflared-https-" + stamp + ".log");
const urlFile = path.join(logDir, "cloudflared-https-url.txt");
const pidFile = path.join(logDir, "cloudflared-https.pid");
function timestamp() {
const d = new Date();
function pad(n) {
return String(n).padStart(2, "0");
}
return String(d.getFullYear()) + pad(d.getMonth() + 1) + pad(d.getDate()) + "-" + pad(d.getHours()) + pad(d.getMinutes()) + pad(d.getSeconds());
}
function sleep(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
function ensureCloudflared() {
ensureDir(toolsDir);
if (fs.existsSync(cloudflared)) return;
const downloadUrl = "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe";
childProcess.execFileSync("curl.exe", ["-L", "--fail", "-o", cloudflared, downloadUrl], { stdio: "inherit" });
if (!fs.existsSync(cloudflared)) {
throw new Error("cloudflared download failed");
}
}
function request(url, timeoutMs) {
return new Promise(function (resolve, reject) {
const client = url.indexOf("https://") === 0 ? https : http;
const req = client.get(url, function (res) {
res.resume();
res.on("end", function () {
if (res.statusCode >= 200 && res.statusCode < 400) {
resolve(res.statusCode);
} else {
reject(new Error("HTTP " + res.statusCode));
}
});
});
req.setTimeout(timeoutMs, function () {
req.destroy(new Error("timeout"));
});
req.on("error", reject);
});
}
async function ensureLocalServer() {
try {
await request(origin + "/?health=https-preview", 5000);
return null;
} catch (error) {
const server = childProcess.spawn("python", ["-m", "http.server", String(port), "--bind", "127.0.0.1"], {
cwd: root,
detached: true,
stdio: "ignore"
});
server.unref();
await sleep(1200);
await request(origin + "/?health=https-preview", 8000);
return server.pid;
}
}
function startTunnel() {
const tunnel = childProcess.spawn(cloudflared, [
"--logfile", logFile,
"--loglevel", "info",
"tunnel",
"--url", origin,
"--no-autoupdate",
"--protocol", "http2"
], {
cwd: root,
detached: true,
stdio: "ignore"
});
tunnel.unref();
return tunnel.pid;
}
function stopExistingTunnels() {
if (process.platform !== "win32") return;
try {
const safeRoot = root.replace(/'/g, "''");
const command = "$root = '" + safeRoot + "'; " +
"Get-CimInstance Win32_Process | " +
"Where-Object { $_.Name -eq 'cloudflared.exe' -and $_.CommandLine -match [regex]::Escape($root) } | " +
"ForEach-Object { Stop-Process -Id $_.ProcessId -Force }";
childProcess.execFileSync("powershell.exe", ["-NoProfile", "-Command", command], { stdio: "ignore" });
} catch (error) {
}
}
function readTunnelUrl() {
if (!fs.existsSync(logFile)) return "";
const text = fs.readFileSync(logFile, "utf8");
const match = text.match(/https:\/\/[a-zA-Z0-9-]+\.trycloudflare\.com/);
return match ? match[0] : "";
}
async function waitForTunnelUrl() {
let i;
let url = "";
for (i = 0; i < 60; i += 1) {
await sleep(1000);
url = readTunnelUrl();
if (url) return url;
}
throw new Error("Cloudflare HTTPS URL was not created. Check " + logFile);
}
async function waitForPublicUrl(url) {
let i;
let lastError = "";
for (i = 0; i < 45; i += 1) {
try {
return await request(url, 20000);
} catch (error) {
lastError = error.message;
await sleep(2000);
}
}
throw new Error("HTTPS URL was created but is not reachable yet: " + url + " Last error: " + lastError);
}
function openBrowser(url) {
try {
const proc = childProcess.spawn("cmd.exe", ["/c", "start", "", url], {
detached: true,
stdio: "ignore"
});
proc.unref();
} catch (error) {
}
}
async function main() {
ensureDir(logDir);
ensureCloudflared();
const serverPid = await ensureLocalServer();
stopExistingTunnels();
const tunnelPid = startTunnel();
const publicBase = await waitForTunnelUrl();
const previewUrl = publicBase + "/?refresh=public-https-v33";
const status = await waitForPublicUrl(previewUrl);
fs.writeFileSync(urlFile, previewUrl);
fs.writeFileSync(pidFile, String(tunnelPid));
let message = "\nFlowerMoji HTTPS preview is running.\n";
if (serverPid) message += "Local server PID: " + serverPid + "\n";
message += "Cloudflare tunnel PID: " + tunnelPid + "\n\n";
message += "Open this HTTPS URL on your phone:\n";
message += previewUrl + "\n\n";
message += "HTTPS check: HTTP " + status + "\n\n";
message += "This is a temporary preview URL. It stays alive while this PC and the tunnel process are running.\n";
process.stdout.write(message);
openBrowser(previewUrl);
}
main().catch(function (error) {
console.error(error.message);
process.exit(1);
});