omo-web 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +23 -2
- package/bin/launcher-settings.js +116 -0
- package/bin/launcher-tls.js +67 -0
- package/bin/listen-address.js +20 -0
- package/bin/locale.js +6 -0
- package/bin/omo-web.js +98 -0
- package/bin/tui.js +645 -0
- package/bin/windows-password.js +79 -0
- package/dist/app.js +7 -0
- package/dist/server.js +12524 -0
- package/package.json +31 -4
- package/public/dag-graph.css +80 -0
- package/public/favicon.svg +13 -0
- package/public/icons.svg +89 -0
- package/public/index.html +486 -0
- package/public/licenses/teenyicons.txt +25 -0
- package/public/licenses/zod.txt +21 -0
- package/public/styles.css +422 -0
- package/public/tool-ledger.css +354 -0
- package/public/workbench.css +782 -0
package/bin/tui.js
ADDED
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
// allow: SIZE_OK — The npm package ships this indivisible terminal session as one module.
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { statSync } from "node:fs";
|
|
4
|
+
import { delimiter, join, resolve } from "node:path";
|
|
5
|
+
import { emitKeypressEvents } from "node:readline";
|
|
6
|
+
import { stripVTControlCharacters } from "node:util";
|
|
7
|
+
import { loadLauncherSettings } from "./launcher-settings.js";
|
|
8
|
+
import { generateCertificate } from "./launcher-tls.js";
|
|
9
|
+
import { interfaceAddresses, isRemoteAddress, loopbackAddress, wildcardAddress } from "./listen-address.js";
|
|
10
|
+
import { cliTr } from "./locale.js";
|
|
11
|
+
|
|
12
|
+
const CSI = "\x1b[";
|
|
13
|
+
const HOME_CLEAR = `${CSI}H${CSI}2J`;
|
|
14
|
+
const SHOW_CURSOR = `${CSI}?25h`;
|
|
15
|
+
const HIDE_CURSOR = `${CSI}?25l`;
|
|
16
|
+
const MAX_RECEIPT = 4096;
|
|
17
|
+
const CONFIG_PREFIX = "OmO Web config: ";
|
|
18
|
+
const START_MS = 30_000;
|
|
19
|
+
const STOP_MS = 4_000;
|
|
20
|
+
const REMOTE_WARNING = cliTr("警告:无密码保护", "Warning: No password protection");
|
|
21
|
+
const REMOTE_RISK = cliTr("能连上的人可访问 OmO 和工作目录。",
|
|
22
|
+
"Anyone who connects can access OmO and your working directories.");
|
|
23
|
+
const windows = process.platform === "win32";
|
|
24
|
+
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
25
|
+
const controls = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
|
|
26
|
+
const safeText = value => value.replace(controls, " ");
|
|
27
|
+
const glyphs = text => Array.from(segmenter.segment(text), ({ segment }) => segment);
|
|
28
|
+
// Reserve two cells for non-ASCII graphemes so wide paths cannot wrap at the edge.
|
|
29
|
+
const cells = glyph => /^[\x20-\x7e]+$/.test(glyph) ? glyph.length : 2;
|
|
30
|
+
const textWidth = text => glyphs(text).reduce((sum, glyph) => sum + cells(glyph), 0);
|
|
31
|
+
|
|
32
|
+
function fold(text, width) {
|
|
33
|
+
const lines = [""];
|
|
34
|
+
let remaining = width;
|
|
35
|
+
for (const glyph of glyphs(safeText(text))) {
|
|
36
|
+
const size = cells(glyph);
|
|
37
|
+
if (size > remaining) {
|
|
38
|
+
lines.push("");
|
|
39
|
+
remaining = width;
|
|
40
|
+
}
|
|
41
|
+
lines[lines.length - 1] += glyph;
|
|
42
|
+
remaining -= size;
|
|
43
|
+
}
|
|
44
|
+
return lines;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function pathLabel(path, width) {
|
|
48
|
+
const chars = glyphs(safeText(path));
|
|
49
|
+
const size = chars.reduce((sum, glyph) => sum + cells(glyph), 0);
|
|
50
|
+
if (size <= width) return chars.join("");
|
|
51
|
+
const head = fold(path, Math.min(10, Math.floor(width / 3)))[0];
|
|
52
|
+
let tail = "";
|
|
53
|
+
let room = width - [...head].reduce((sum, glyph) => sum + cells(glyph), 0) - 3;
|
|
54
|
+
for (const glyph of chars.reverse()) {
|
|
55
|
+
room -= cells(glyph);
|
|
56
|
+
if (room < 0) break;
|
|
57
|
+
tail = glyph + tail;
|
|
58
|
+
}
|
|
59
|
+
return `${head}...${tail}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function editorLine(draft, width) {
|
|
63
|
+
let left = "", right = "";
|
|
64
|
+
let column = 0;
|
|
65
|
+
for (const glyph of glyphs(safeText(draft.text.slice(0, draft.cursor))).reverse()) {
|
|
66
|
+
if (column + cells(glyph) >= width) break;
|
|
67
|
+
left = glyph + left;
|
|
68
|
+
column += cells(glyph);
|
|
69
|
+
}
|
|
70
|
+
let room = width - column;
|
|
71
|
+
for (const glyph of glyphs(safeText(draft.text.slice(draft.cursor)))) {
|
|
72
|
+
if (cells(glyph) > room) break;
|
|
73
|
+
right += glyph;
|
|
74
|
+
room -= cells(glyph);
|
|
75
|
+
}
|
|
76
|
+
// Let the terminal measure the cursor position, including ambiguous-width glyphs.
|
|
77
|
+
return `${left}${CSI}s${right}`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function receiveLines(stream, onLine) {
|
|
81
|
+
let pending = "";
|
|
82
|
+
stream.setEncoding("utf8");
|
|
83
|
+
stream.on("data", chunk => {
|
|
84
|
+
const pieces = chunk.split("\n");
|
|
85
|
+
for (const [index, piece] of pieces.entries()) {
|
|
86
|
+
if (pending !== null) {
|
|
87
|
+
pending = pending.length + piece.length > MAX_RECEIPT ? null : pending + piece;
|
|
88
|
+
}
|
|
89
|
+
if (index === pieces.length - 1) break;
|
|
90
|
+
const line = pending?.replace(/\r$/, "");
|
|
91
|
+
pending = "";
|
|
92
|
+
if (line !== undefined) onLine(line);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function receiveListener(stream, onUrl) {
|
|
98
|
+
receiveLines(stream, line => {
|
|
99
|
+
// Match the actual stdout receipt as a whole line, not its sanitized display.
|
|
100
|
+
const receipt = line.match(/^OmO Web: (https?:\/\/[^\s\\\p{Cc}\p{Cf}]+)$/u);
|
|
101
|
+
if (!receipt || receipt[0] !== line) return;
|
|
102
|
+
try {
|
|
103
|
+
const parsed = new URL(receipt[1]);
|
|
104
|
+
if (!parsed.username && !parsed.password) onUrl(receipt[1]);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (!(error instanceof TypeError)) throw error;
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Windows signals sent through Node terminate only the direct child.
|
|
112
|
+
// Stop the owned server process tree so a native engine cannot outlive it.
|
|
113
|
+
export function stopWindowsServer(child) {
|
|
114
|
+
if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) return;
|
|
115
|
+
const taskkill = join(process.env.SystemRoot || "C:\\Windows", "System32", "taskkill.exe");
|
|
116
|
+
const killer = spawn(taskkill, ["/PID", String(child.pid), "/T", "/F"], {
|
|
117
|
+
stdio: "ignore", windowsHide: true,
|
|
118
|
+
});
|
|
119
|
+
const fallback = () => {
|
|
120
|
+
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
|
|
121
|
+
};
|
|
122
|
+
killer.once("error", fallback);
|
|
123
|
+
killer.once("exit", code => { if (code !== 0) fallback(); });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function killServerGroup(child) {
|
|
127
|
+
if (!windows && child.pid !== undefined) {
|
|
128
|
+
try {
|
|
129
|
+
process.kill(-child.pid, "SIGKILL");
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (error.code !== "ESRCH") throw error;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Run the launcher until the user quits (0), Ctrl+C interrupts (130), or a signal ends it. */
|
|
137
|
+
export async function startTui({ entry, version }) {
|
|
138
|
+
const input = process.stdin;
|
|
139
|
+
const output = process.stdout;
|
|
140
|
+
const color = process.env.NO_COLOR === undefined;
|
|
141
|
+
const ink = (sgr, text) => color ? `${CSI}${sgr}m${text}${CSI}0m` : text;
|
|
142
|
+
const cwd = process.cwd();
|
|
143
|
+
const settings = await loadLauncherSettings(process.env);
|
|
144
|
+
let env = settings.effectiveEnv();
|
|
145
|
+
const address = () => env.OMO_WEB_HOST ?? loopbackAddress;
|
|
146
|
+
const unprotected = () => isRemoteAddress(address()) && !env.OMO_WEB_PASSWORD_FILE;
|
|
147
|
+
const optedIn = () => env.OMO_WEB_ALLOW_UNAUTHENTICATED === "1";
|
|
148
|
+
const hasPassword = () => Boolean(env.OMO_WEB_PASSWORD_FILE);
|
|
149
|
+
const hasHttps = () => Boolean(env.OMO_WEB_TLS_CERT && env.OMO_WEB_TLS_KEY && env.OMO_WEB_ORIGIN);
|
|
150
|
+
const switchLabel = on => on ? cliTr("开", "On") : cliTr("关", "Off");
|
|
151
|
+
let workspaces;
|
|
152
|
+
let draft;
|
|
153
|
+
let saving;
|
|
154
|
+
let networks = [];
|
|
155
|
+
let pasting = false;
|
|
156
|
+
let selected = 0;
|
|
157
|
+
let server;
|
|
158
|
+
let url;
|
|
159
|
+
let phase = "idle";
|
|
160
|
+
let stopped = false;
|
|
161
|
+
let notice = settings.warning;
|
|
162
|
+
let exitCode;
|
|
163
|
+
let settle;
|
|
164
|
+
let paint;
|
|
165
|
+
const finished = new Promise(resolve => { settle = resolve; });
|
|
166
|
+
|
|
167
|
+
const directoriesLabel = cliTr("工作目录", "Working directories");
|
|
168
|
+
const quitAction = [cliTr("退出", "Quit"), () => quit(0)];
|
|
169
|
+
const stopAction = [cliTr("停止服务", "Stop web"), stopWeb];
|
|
170
|
+
const backAction = [cliTr("返回", "Back"), () => go("idle")];
|
|
171
|
+
const menus = {
|
|
172
|
+
idle: [[cliTr("启动服务", "Start web"), requestStart], [directoriesLabel, editWorkspaces],
|
|
173
|
+
[cliTr("访问设置", "Access settings"), () => go("settings")], quitAction],
|
|
174
|
+
confirming: [
|
|
175
|
+
[cliTr("返回", "Back"), backFromConfirmation],
|
|
176
|
+
[cliTr("仅本次无密码启动", "Start once without a password"), () => startWeb(true)],
|
|
177
|
+
],
|
|
178
|
+
starting: [stopAction, quitAction],
|
|
179
|
+
ready: [[cliTr("打开浏览器", "Open browser"), openBrowser], stopAction, quitAction],
|
|
180
|
+
stopping: [quitAction],
|
|
181
|
+
};
|
|
182
|
+
const status = {
|
|
183
|
+
idle: [() => notice ? cliTr("待机 / 见提示", "Idle / see notice")
|
|
184
|
+
: stopped ? cliTr("已停止", "Stopped") : cliTr("待机", "Idle"), "36"],
|
|
185
|
+
settings: [() => cliTr("访问设置", "Access settings"), "36;1"],
|
|
186
|
+
networks: [() => cliTr("监听地址", "Listen address"), "36;1"],
|
|
187
|
+
confirming: [() => cliTr("确认远程访问", "Confirm remote access"), "33;1"],
|
|
188
|
+
starting: [() => cliTr("启动中", "Starting"), "33;1"],
|
|
189
|
+
ready: [() => cliTr("监听中", "Listening"), "32;1"],
|
|
190
|
+
stopping: [() => cliTr("停止中", "Stopping"), "33;1"],
|
|
191
|
+
};
|
|
192
|
+
const configured = () => workspaces ?? process.env.OMO_WEB_WORKSPACES;
|
|
193
|
+
const activePaths = () => configured()
|
|
194
|
+
? configured().split(delimiter).filter(Boolean).map(path => resolve(cwd, path))
|
|
195
|
+
: [cwd];
|
|
196
|
+
const viewport = () => ({
|
|
197
|
+
width: Math.min(72, (output.columns || 80) - 4),
|
|
198
|
+
height: Math.max(1, (output.rows || 24) - 1),
|
|
199
|
+
});
|
|
200
|
+
const riskLines = width => [cliTr(`${address()} 无密码访问`, `${address()} without a password`), REMOTE_RISK]
|
|
201
|
+
.flatMap(line => fold(line, width));
|
|
202
|
+
const confirmationFits = ({ width, height }) => width >= 32 && riskLines(width).length + 2 <= height;
|
|
203
|
+
function activeMenu(dimensions) {
|
|
204
|
+
if (phase === "settings") return [
|
|
205
|
+
[cliTr(`监听地址:${address()}`, `Listen address: ${address()}`), () => {
|
|
206
|
+
networks = interfaceAddresses();
|
|
207
|
+
go("networks");
|
|
208
|
+
}],
|
|
209
|
+
[cliTr(`密码:${switchLabel(hasPassword())}`, `Password: ${switchLabel(hasPassword())}`), togglePassword],
|
|
210
|
+
[cliTr("设置 / 修改密码", "Set / change password"), editPassword],
|
|
211
|
+
[cliTr(`HTTPS:${switchLabel(hasHttps())}`, `HTTPS: ${switchLabel(hasHttps())}`), toggleHttps],
|
|
212
|
+
[cliTr("生成 SSL 自签证书", "Generate self-signed SSL certificate"), editCertificate],
|
|
213
|
+
backAction,
|
|
214
|
+
];
|
|
215
|
+
if (phase === "networks") return [
|
|
216
|
+
[cliTr(`仅本机 (${loopbackAddress})`, `Loopback only (${loopbackAddress})`), () => chooseAddress(loopbackAddress)],
|
|
217
|
+
[cliTr(`全部 IPv4 网卡 (${wildcardAddress})`, `All IPv4 interfaces (${wildcardAddress})`), () => chooseAddress(wildcardAddress)],
|
|
218
|
+
...networks.map(({ name, address: ip, cidr }) =>
|
|
219
|
+
[`${cidr ?? ip} — ${name}`, () => chooseAddress(ip)]),
|
|
220
|
+
[cliTr("返回", "Back"), () => go("settings")],
|
|
221
|
+
];
|
|
222
|
+
return phase === "confirming" && !confirmationFits(dimensions) ? menus.confirming.slice(0, 1) : menus[phase];
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function render() {
|
|
226
|
+
paint = undefined;
|
|
227
|
+
const dimensions = viewport();
|
|
228
|
+
const { width, height } = dimensions;
|
|
229
|
+
if (width < 2) {
|
|
230
|
+
output.write(HIDE_CURSOR + HOME_CLEAR);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const [state, tone] = status[phase];
|
|
234
|
+
const label = state();
|
|
235
|
+
const build = fold(`v${version}`, 20)[0];
|
|
236
|
+
const title = cliTr(" Web 监听 ", " WEB LISTENER ");
|
|
237
|
+
const brand = "-- OmO Web ";
|
|
238
|
+
const gap = width - textWidth(title) - textWidth(label) - textWidth(build) - 1;
|
|
239
|
+
const boxed = width >= 44 && gap >= 2;
|
|
240
|
+
const header = boxed ? [
|
|
241
|
+
ink("36;1", `+${brand}${"-".repeat(width - brand.length)}+`),
|
|
242
|
+
`|${title}${ink(tone, label)}${" ".repeat(gap)}${build} |`,
|
|
243
|
+
ink("36", `+${"-".repeat(width)}+`),
|
|
244
|
+
] : fold(`OmO Web / ${label}`, width).map(line => ink(tone, line));
|
|
245
|
+
const short = text => fold(text, width)[0];
|
|
246
|
+
const editorTitle = draft && ink("1", short(draft.title));
|
|
247
|
+
const menu = activeMenu(dimensions);
|
|
248
|
+
const focus = Math.min(selected, menu.length - 1);
|
|
249
|
+
const actions = menu.map(([action], index) => index === focus
|
|
250
|
+
? ink("7;1", short(`> ${action} `)) : short(` ${action}`));
|
|
251
|
+
const message = notice ? fold(notice, width).slice(0, 2).map(line => ink("33;1", line)) : [];
|
|
252
|
+
const warning = unprotected() && (optedIn() || server) && phase !== "confirming"
|
|
253
|
+
? fold(REMOTE_WARNING, width).map(line => ink("33;1", line)) : [];
|
|
254
|
+
const risk = phase === "confirming" && menu.length > 1
|
|
255
|
+
? riskLines(width).map(line => ink("33;1", line)) : [];
|
|
256
|
+
let editor;
|
|
257
|
+
let lines;
|
|
258
|
+
if (draft) {
|
|
259
|
+
editor = editorLine(draft.masked ? { ...draft, text: "*".repeat(draft.text.length) } : draft, Math.max(2, width - 2));
|
|
260
|
+
lines = [...header, "", editorTitle, `> ${editor}`, "",
|
|
261
|
+
...fold(draft.hint, width),
|
|
262
|
+
...message, "", ...fold(cliTr("Enter 确认 / Esc 取消 / Ctrl+U 清空", "Enter confirm / Esc cancel / Ctrl+U clear"), width)];
|
|
263
|
+
} else if (phase === "confirming") {
|
|
264
|
+
lines = [...header, "", ...risk, "", ...actions, "",
|
|
265
|
+
...fold(menu.length > 1
|
|
266
|
+
? cliTr("↑/↓ 移动 / Enter 选择 / Esc 返回", "Up/Down move / Enter select / Esc back")
|
|
267
|
+
: cliTr("请放大终端以查看风险提示。", "Enlarge the terminal to review the risk."), width)];
|
|
268
|
+
} else if (phase === "settings" || phase === "networks") {
|
|
269
|
+
const hint = phase === "networks" ? cliTr("选择监听网卡,不会修改防火墙规则。", "Select a listen interface; firewall rules are unchanged.")
|
|
270
|
+
: cliTr("Enter 修改 · 保存后下次启动生效 · Esc 返回", "Enter to edit · Applies on the next start · Esc back");
|
|
271
|
+
const origin = phase === "settings" && hasHttps() ? fold(cliTr(`HTTPS 地址:${env.OMO_WEB_ORIGIN}`,
|
|
272
|
+
`HTTPS URL: ${env.OMO_WEB_ORIGIN}`), width) : [];
|
|
273
|
+
lines = [...header, "", ...actions, "", ...message, ...origin, ...fold(hint, width)];
|
|
274
|
+
} else {
|
|
275
|
+
const paths = activePaths();
|
|
276
|
+
const urlRows = url ? fold(url, Math.max(2, width - 2)) : [];
|
|
277
|
+
const pathCount = height >= 23 ? 4 : 2;
|
|
278
|
+
const details = url ? [ink("1", short(cliTr("浏览器地址", "Browser URL"))), ...urlRows.slice(0, 2).map(line => ` ${line}`),
|
|
279
|
+
...(urlRows.length > 2 ? [" ..."] : []), ""] : [];
|
|
280
|
+
const directories = paths.length ? paths.slice(0, pathCount).map(path => ` ${pathLabel(path, width - 2)}`)
|
|
281
|
+
: [short(cliTr(" (未配置)", " (none configured)"))];
|
|
282
|
+
if (paths.length > pathCount) directories.push(short(cliTr(` 另有 ${paths.length - pathCount} 个`, ` +${paths.length - pathCount} more`)));
|
|
283
|
+
const connection = phase === "idle" ? [
|
|
284
|
+
short(cliTr(` ${address()} · ${hasHttps() ? "HTTPS" : "HTTP"} · 密码${switchLabel(hasPassword())}`,
|
|
285
|
+
` ${address()} · ${hasHttps() ? "HTTPS" : "HTTP"} · Password ${switchLabel(hasPassword())}`)),
|
|
286
|
+
] : [];
|
|
287
|
+
lines = [...header, ...warning, "", ...details, ...connection, ink("1", short(directoriesLabel)), ...directories,
|
|
288
|
+
"", ...actions, ...message, "", ...fold(cliTr("↑/↓ 移动 / Enter 选择 / Q 退出", "Up/Down move / Enter select / Q quit"), width)];
|
|
289
|
+
}
|
|
290
|
+
for (let blank = lines.lastIndexOf(""); lines.length > height && blank >= 0; blank = lines.lastIndexOf("")) {
|
|
291
|
+
lines.splice(blank, 1);
|
|
292
|
+
}
|
|
293
|
+
// On very short terminals, prioritize the active control (or the draft).
|
|
294
|
+
if (lines.length > height) {
|
|
295
|
+
if (draft) {
|
|
296
|
+
lines = [...(height > 1 ? [editorTitle] : []), "> " + editor, ...message,
|
|
297
|
+
short(cliTr("Enter 确认 / Esc 取消", "Enter confirm / Esc cancel"))];
|
|
298
|
+
} else if (phase === "confirming") {
|
|
299
|
+
lines = [...risk, ...actions];
|
|
300
|
+
} else {
|
|
301
|
+
const compactStatus = ink(tone, short(`OmO Web / ${label}`));
|
|
302
|
+
if (phase === "settings" || phase === "networks") {
|
|
303
|
+
const slots = Math.max(1, height - 1 - message.length);
|
|
304
|
+
const first = Math.max(0, Math.min(focus - Math.floor(slots / 2), actions.length - slots));
|
|
305
|
+
lines = height > 1 ? [compactStatus, ...actions.slice(first, first + slots), ...message] : [actions[focus]];
|
|
306
|
+
} else lines = actions.length > height ? [actions[focus]] : warning.length && height > 1
|
|
307
|
+
? [compactStatus, ...warning.slice(0, Math.max(1, height - 2)), actions[focus]]
|
|
308
|
+
: [...actions, ...message, compactStatus];
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
output.write(HIDE_CURSOR + HOME_CLEAR + lines.slice(0, height).map(line => ` ${line}`).join("\r\n")
|
|
312
|
+
+ (editor ? `${CSI}u${SHOW_CURSOR}` : ""));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function redraw() {
|
|
316
|
+
paint ??= setImmediate(render);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function go(next) {
|
|
320
|
+
phase = next;
|
|
321
|
+
selected = 0;
|
|
322
|
+
notice = "";
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function runSetting(action) {
|
|
326
|
+
notice = cliTr("正在保存…", "Saving…");
|
|
327
|
+
saving = Promise.resolve().then(action).then(message => {
|
|
328
|
+
env = settings.effectiveEnv();
|
|
329
|
+
notice = message ?? cliTr("已保存,下次启动生效。", "Saved. Applies on the next start.");
|
|
330
|
+
}).catch(error => {
|
|
331
|
+
if (!(error instanceof Error)) throw error;
|
|
332
|
+
notice = error.message;
|
|
333
|
+
}).finally(() => {
|
|
334
|
+
saving = undefined;
|
|
335
|
+
if (exitCode !== undefined) settle(exitCode);
|
|
336
|
+
else redraw();
|
|
337
|
+
});
|
|
338
|
+
redraw();
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function chooseAddress(host) {
|
|
342
|
+
runSetting(async () => {
|
|
343
|
+
await settings.save({ OMO_WEB_HOST: host, OMO_WEB_ALLOW_UNAUTHENTICATED: null });
|
|
344
|
+
go("settings");
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function togglePassword() {
|
|
349
|
+
runSetting(async () => {
|
|
350
|
+
if (!await settings.setPasswordEnabled(!hasPassword())) {
|
|
351
|
+
editPassword();
|
|
352
|
+
return "";
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function editPassword() {
|
|
358
|
+
draft = {
|
|
359
|
+
masked: true, text: "", cursor: 0, title: cliTr("新密码", "New password"),
|
|
360
|
+
hint: cliTr("20–128 个可打印 ASCII 字符,输入仅显示星号。", "20–128 printable ASCII characters. Input is masked."),
|
|
361
|
+
submit(password) {
|
|
362
|
+
if (!/^[\x20-\x7e]{20,128}$/u.test(password)) {
|
|
363
|
+
notice = cliTr("请使用 20–128 个可打印 ASCII 字符。", "Use 20–128 printable ASCII characters.");
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
runSetting(async () => {
|
|
367
|
+
await settings.changePassword(password);
|
|
368
|
+
draft = undefined;
|
|
369
|
+
});
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
notice = "";
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function toggleHttps() {
|
|
376
|
+
runSetting(async () => {
|
|
377
|
+
if (!await settings.setHttpsEnabled(!hasHttps())) {
|
|
378
|
+
editCertificate();
|
|
379
|
+
return "";
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function editCertificate() {
|
|
385
|
+
let current;
|
|
386
|
+
try {
|
|
387
|
+
if (env.OMO_WEB_ORIGIN) current = new URL(env.OMO_WEB_ORIGIN).hostname;
|
|
388
|
+
} catch (error) {
|
|
389
|
+
if (!(error instanceof TypeError)) throw error;
|
|
390
|
+
}
|
|
391
|
+
const text = current ?? (address() === wildcardAddress ? interfaceAddresses()[0]?.address ?? loopbackAddress : address());
|
|
392
|
+
draft = {
|
|
393
|
+
text, cursor: text.length, title: cliTr("证书主机名", "Certificate host"),
|
|
394
|
+
hint: cliTr("浏览器使用的 IP 或 DNS 名。需 OpenSSL;请核验证书。",
|
|
395
|
+
"Browser IP or DNS name. Requires OpenSSL. Verify the certificate."),
|
|
396
|
+
submit(host) {
|
|
397
|
+
runSetting(async () => {
|
|
398
|
+
const path = await generateCertificate(settings, host, Number(env.OMO_WEB_PORT ?? "4317"));
|
|
399
|
+
draft = undefined;
|
|
400
|
+
return cliTr(`证书已生成:${path}`, `Certificate generated: ${path}`);
|
|
401
|
+
});
|
|
402
|
+
},
|
|
403
|
+
};
|
|
404
|
+
notice = "";
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function editWorkspaces() {
|
|
408
|
+
const text = configured() || cwd;
|
|
409
|
+
draft = {
|
|
410
|
+
text, cursor: text.length, title: cliTr("编辑目录", "Edit directories"),
|
|
411
|
+
hint: cliTr(`用 "${delimiter}" 分隔路径,留空使用启动目录。`,
|
|
412
|
+
`Separate paths with "${delimiter}". Empty uses the launch directory.`),
|
|
413
|
+
submit: applyWorkspaces,
|
|
414
|
+
};
|
|
415
|
+
notice = "";
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function applyWorkspaces(text) {
|
|
419
|
+
const paths = text.split(delimiter).filter(Boolean).map(path => resolve(cwd, path));
|
|
420
|
+
for (const path of paths) {
|
|
421
|
+
try {
|
|
422
|
+
if (statSync(path, { throwIfNoEntry: false })?.isDirectory()) continue;
|
|
423
|
+
notice = cliTr(`不是目录:${path}`, `Not a directory: ${path}`);
|
|
424
|
+
} catch (error) {
|
|
425
|
+
if (!(error instanceof Error)) throw error;
|
|
426
|
+
notice = cliTr(`无法使用目录 (${error.code ?? "?"}):${path}`,
|
|
427
|
+
`Cannot use directory (${error.code ?? "?"}): ${path}`);
|
|
428
|
+
}
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
workspaces = paths.join(delimiter);
|
|
432
|
+
draft = undefined;
|
|
433
|
+
notice = "";
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function editKey(text, key) {
|
|
437
|
+
if (!pasting && key.name === "escape") {
|
|
438
|
+
draft = undefined;
|
|
439
|
+
notice = "";
|
|
440
|
+
} else if (!pasting && (key.name === "return" || key.name === "enter")) {
|
|
441
|
+
draft.submit(draft.text);
|
|
442
|
+
} else {
|
|
443
|
+
const { text: value, cursor } = draft;
|
|
444
|
+
const left = value.slice(0, cursor), right = value.slice(cursor);
|
|
445
|
+
const previous = () => cursor - (glyphs(left).at(-1)?.length ?? 0);
|
|
446
|
+
const next = () => cursor + (glyphs(right)[0]?.length ?? 0);
|
|
447
|
+
if (!pasting && key.ctrl && key.name === "u") Object.assign(draft, { text: "", cursor: 0 });
|
|
448
|
+
else if (!pasting && key.name === "left") draft.cursor = previous();
|
|
449
|
+
else if (!pasting && key.name === "right") draft.cursor = next();
|
|
450
|
+
else if (!pasting && key.name === "home") draft.cursor = 0;
|
|
451
|
+
else if (!pasting && key.name === "end") draft.cursor = value.length;
|
|
452
|
+
else if (!pasting && key.name === "backspace") {
|
|
453
|
+
Object.assign(draft, { text: value.slice(0, previous()) + right, cursor: previous() });
|
|
454
|
+
} else if (!pasting && key.name === "delete") draft.text = left + value.slice(next());
|
|
455
|
+
else if (!key.ctrl && !key.meta && text && text === safeText(text) && value.length + text.length <= 8192) {
|
|
456
|
+
Object.assign(draft, { text: left + text + right, cursor: cursor + text.length });
|
|
457
|
+
} else return;
|
|
458
|
+
notice = "";
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function requestStart() {
|
|
463
|
+
if (settings.warning) {
|
|
464
|
+
notice = settings.warning;
|
|
465
|
+
} else if (settings.hasListenerOverride && isRemoteAddress(address()) && !hasHttps()) {
|
|
466
|
+
notice = cliTr("非本机监听必须启用 HTTPS。请在访问设置中启用或生成证书。",
|
|
467
|
+
"Remote listening requires HTTPS. Enable it or generate a certificate in Access settings.");
|
|
468
|
+
} else if (unprotected() && !optedIn()) {
|
|
469
|
+
phase = "confirming";
|
|
470
|
+
selected = 0;
|
|
471
|
+
} else startWeb();
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function backFromConfirmation() {
|
|
475
|
+
phase = "idle";
|
|
476
|
+
selected = 0;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function startWeb(confirmed = false) {
|
|
480
|
+
phase = "starting";
|
|
481
|
+
selected = 0;
|
|
482
|
+
notice = "";
|
|
483
|
+
redraw();
|
|
484
|
+
const serverEnv = {
|
|
485
|
+
...env,
|
|
486
|
+
...(workspaces === undefined ? {} : { OMO_WEB_WORKSPACES: workspaces }),
|
|
487
|
+
...(confirmed ? { OMO_WEB_ALLOW_UNAUTHENTICATED: "1" } : {}),
|
|
488
|
+
};
|
|
489
|
+
const child = spawn("bun", ["--no-env-file", entry], {
|
|
490
|
+
env: serverEnv, stdio: ["ignore", "pipe", "pipe"], detached: !windows, windowsHide: true,
|
|
491
|
+
});
|
|
492
|
+
let errorMessage;
|
|
493
|
+
let configMessage;
|
|
494
|
+
const startup = setTimeout(() => {
|
|
495
|
+
errorMessage = cliTr("未收到监听地址。请重试或运行 omo-web serve 查看详情。",
|
|
496
|
+
"No listener receipt. Retry or run omo-web serve for details.");
|
|
497
|
+
stopWeb();
|
|
498
|
+
}, START_MS);
|
|
499
|
+
server = { child, startup, killTimer: undefined };
|
|
500
|
+
receiveListener(child.stdout, href => {
|
|
501
|
+
if (phase !== "starting" || child.exitCode !== null || child.signalCode !== null) return;
|
|
502
|
+
clearTimeout(startup);
|
|
503
|
+
url = href;
|
|
504
|
+
phase = "ready";
|
|
505
|
+
selected = 0;
|
|
506
|
+
redraw();
|
|
507
|
+
});
|
|
508
|
+
receiveLines(child.stderr, line => {
|
|
509
|
+
if (phase !== "starting" || configMessage || !line.startsWith(CONFIG_PREFIX)) return;
|
|
510
|
+
configMessage = safeText(stripVTControlCharacters(line.slice(CONFIG_PREFIX.length))).trim();
|
|
511
|
+
});
|
|
512
|
+
child.once("error", error => {
|
|
513
|
+
errorMessage = error.code === "ENOENT"
|
|
514
|
+
? cliTr("PATH 中找不到 Bun。请从 bun.sh 安装。", "Bun was not found on PATH. Install it from bun.sh.")
|
|
515
|
+
: cliTr(`无法运行 Bun (${error.code ?? "?"})。`, `Could not run Bun (${error.code ?? "?"}).`);
|
|
516
|
+
});
|
|
517
|
+
child.once("exit", () => {
|
|
518
|
+
clearTimeout(server.killTimer);
|
|
519
|
+
// The main server closes its resources on SIGTERM; reap the group if
|
|
520
|
+
// anything survived that cleanup or the server exited unexpectedly.
|
|
521
|
+
if (!windows) killServerGroup(child);
|
|
522
|
+
});
|
|
523
|
+
child.once("close", (code, signal) => {
|
|
524
|
+
clearTimeout(startup);
|
|
525
|
+
clearTimeout(server.killTimer);
|
|
526
|
+
if (exitCode !== undefined) {
|
|
527
|
+
settle(exitCode);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
stopped = phase === "stopping" && !errorMessage;
|
|
531
|
+
notice = stopped ? "" : (configMessage || errorMessage || cliTr(`Web 服务已退出 (${signal ?? code})。请重试或运行 omo-web serve。`,
|
|
532
|
+
`Web exited (${signal ?? code}). Retry or run omo-web serve.`));
|
|
533
|
+
server = undefined;
|
|
534
|
+
phase = "idle";
|
|
535
|
+
url = undefined;
|
|
536
|
+
selected = 0;
|
|
537
|
+
redraw();
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function stopWeb() {
|
|
542
|
+
if (!server || phase === "stopping") return;
|
|
543
|
+
phase = "stopping";
|
|
544
|
+
url = undefined;
|
|
545
|
+
selected = 0;
|
|
546
|
+
notice = "";
|
|
547
|
+
const { child, startup } = server;
|
|
548
|
+
clearTimeout(startup);
|
|
549
|
+
if (windows) {
|
|
550
|
+
stopWindowsServer(child);
|
|
551
|
+
server.killTimer = setTimeout(() => {
|
|
552
|
+
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
|
|
553
|
+
}, STOP_MS);
|
|
554
|
+
} else {
|
|
555
|
+
child.kill("SIGTERM");
|
|
556
|
+
server.killTimer = setTimeout(() => killServerGroup(child), STOP_MS);
|
|
557
|
+
}
|
|
558
|
+
redraw();
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function openBrowser() {
|
|
562
|
+
const current = server;
|
|
563
|
+
const commands = {
|
|
564
|
+
darwin: ["open", url],
|
|
565
|
+
win32: ["rundll32.exe", "url.dll,FileProtocolHandler", url],
|
|
566
|
+
};
|
|
567
|
+
const [command, ...args] = commands[process.platform] ?? ["xdg-open", url];
|
|
568
|
+
const browser = spawn(command, args, { stdio: "ignore", windowsHide: true, detached: !windows });
|
|
569
|
+
const failed = () => {
|
|
570
|
+
if (server !== current || phase !== "ready" || exitCode !== undefined) return;
|
|
571
|
+
notice = cliTr("无法打开浏览器。请手动打开上方地址。", "Could not open a browser. Open the URL above.");
|
|
572
|
+
redraw();
|
|
573
|
+
};
|
|
574
|
+
browser.once("error", failed);
|
|
575
|
+
browser.once("exit", code => { if (code !== 0) failed(); });
|
|
576
|
+
browser.unref();
|
|
577
|
+
notice = "";
|
|
578
|
+
redraw();
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function quit(code) {
|
|
582
|
+
if (exitCode !== undefined) return;
|
|
583
|
+
exitCode = code;
|
|
584
|
+
if (server) stopWeb();
|
|
585
|
+
else if (!saving) settle(code);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function onKey(text, key) {
|
|
589
|
+
if (exitCode !== undefined || !key) return;
|
|
590
|
+
if (key.ctrl && key.name === "c") return quit(130);
|
|
591
|
+
if (saving) return;
|
|
592
|
+
if (key.name === "paste-start" || key.name === "paste-end") {
|
|
593
|
+
pasting = key.name === "paste-start";
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
if (draft) editKey(text, key);
|
|
597
|
+
else if (pasting) return;
|
|
598
|
+
else if (key.name === "escape" && phase === "confirming") backFromConfirmation();
|
|
599
|
+
else if (key.name === "escape" && (phase === "settings" || phase === "networks")) go(phase === "settings" ? "idle" : "settings");
|
|
600
|
+
else if (key.name === "q" || key.name === "escape") return quit(0);
|
|
601
|
+
else {
|
|
602
|
+
const menu = activeMenu(viewport());
|
|
603
|
+
selected = Math.min(selected, menu.length - 1);
|
|
604
|
+
if (key.name === "return" || key.name === "enter") menu[selected][1]();
|
|
605
|
+
else if (key.name === "up" || key.name === "down") {
|
|
606
|
+
selected = (selected + (key.name === "up" ? -1 : 1) + menu.length) % menu.length;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
redraw();
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const wasRaw = input.isRaw;
|
|
613
|
+
const wasFlowing = input.readableFlowing === true;
|
|
614
|
+
const onInt = () => quit(130);
|
|
615
|
+
const onTerm = () => quit(143);
|
|
616
|
+
const onHangup = () => quit(129);
|
|
617
|
+
try {
|
|
618
|
+
process.on("SIGINT", onInt);
|
|
619
|
+
process.on("SIGTERM", onTerm);
|
|
620
|
+
process.on("SIGHUP", onHangup);
|
|
621
|
+
input.on("end", onHangup);
|
|
622
|
+
input.setRawMode(true);
|
|
623
|
+
output.write(`${CSI}?1049h${CSI}?2004h`);
|
|
624
|
+
emitKeypressEvents(input);
|
|
625
|
+
input.on("keypress", onKey);
|
|
626
|
+
input.resume();
|
|
627
|
+
output.on("resize", redraw);
|
|
628
|
+
render();
|
|
629
|
+
return await finished;
|
|
630
|
+
} finally {
|
|
631
|
+
clearImmediate(paint);
|
|
632
|
+
output.off("resize", redraw);
|
|
633
|
+
input.off("keypress", onKey);
|
|
634
|
+
input.off("end", onHangup);
|
|
635
|
+
if (!wasFlowing) input.pause();
|
|
636
|
+
try {
|
|
637
|
+
input.setRawMode(wasRaw);
|
|
638
|
+
} finally {
|
|
639
|
+
output.write(`${CSI}?2004l${CSI}?1049l${SHOW_CURSOR}`);
|
|
640
|
+
process.off("SIGINT", onInt);
|
|
641
|
+
process.off("SIGTERM", onTerm);
|
|
642
|
+
process.off("SIGHUP", onHangup);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|