omo-web 0.1.0 → 0.1.2

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/bin/tui.js CHANGED
@@ -4,6 +4,10 @@ import { statSync } from "node:fs";
4
4
  import { delimiter, join, resolve } from "node:path";
5
5
  import { emitKeypressEvents } from "node:readline";
6
6
  import { stripVTControlCharacters } from "node:util";
7
+ import { parseProxyOrigin, passwordPattern, recommendedPasswordLength } from "./access-policy.js";
8
+ import { loadLauncherSettings } from "./launcher-settings.js";
9
+ import { generateCertificate } from "./launcher-tls.js";
10
+ import { interfaceAddresses, isRemoteAddress, loopbackAddress, wildcardAddress } from "./listen-address.js";
7
11
  import { cliTr } from "./locale.js";
8
12
 
9
13
  const CSI = "\x1b[";
@@ -12,13 +16,12 @@ const SHOW_CURSOR = `${CSI}?25h`;
12
16
  const HIDE_CURSOR = `${CSI}?25l`;
13
17
  const MAX_RECEIPT = 4096;
14
18
  const CONFIG_PREFIX = "OmO Web config: ";
19
+ const WARNING_PREFIX = "OmO Web warning: ";
15
20
  const START_MS = 30_000;
16
21
  const STOP_MS = 4_000;
17
22
  const REMOTE_WARNING = cliTr("警告:无密码保护", "Warning: No password protection");
18
- const REMOTE_RISK = [
19
- cliTr("0.0.0.0 无密码访问", "0.0.0.0 without a password"),
20
- cliTr("能连上的人可访问 OmO 和工作目录。", "Anyone who connects can access OmO and your working directories."),
21
- ];
23
+ const REMOTE_RISK = cliTr("能连上的人可访问 OmO 和工作目录。",
24
+ "Anyone who connects can access OmO and your working directories.");
22
25
  const windows = process.platform === "win32";
23
26
  const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
24
27
  const controls = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
@@ -139,17 +142,27 @@ export async function startTui({ entry, version }) {
139
142
  const color = process.env.NO_COLOR === undefined;
140
143
  const ink = (sgr, text) => color ? `${CSI}${sgr}m${text}${CSI}0m` : text;
141
144
  const cwd = process.cwd();
142
- const unprotected = process.env.OMO_WEB_HOST === "0.0.0.0" && !process.env.OMO_WEB_PASSWORD_FILE;
143
- const optedIn = process.env.OMO_WEB_ALLOW_UNAUTHENTICATED === "1";
145
+ const settings = await loadLauncherSettings(process.env);
146
+ let env = settings.effectiveEnv();
147
+ const address = () => env.OMO_WEB_HOST ?? loopbackAddress;
148
+ const proxyOrigin = () => env.OMO_WEB_PROXY_ORIGIN;
149
+ const unprotected = () => (isRemoteAddress(address()) || Boolean(proxyOrigin())) && !env.OMO_WEB_PASSWORD_FILE;
150
+ const optedIn = () => env.OMO_WEB_ALLOW_UNAUTHENTICATED === "1";
151
+ const hasPassword = () => Boolean(env.OMO_WEB_PASSWORD_FILE);
152
+ const hasHttps = () => Boolean(env.OMO_WEB_TLS_CERT && env.OMO_WEB_TLS_KEY && env.OMO_WEB_ORIGIN);
153
+ const switchLabel = on => on ? cliTr("开", "On") : cliTr("关", "Off");
144
154
  let workspaces;
145
155
  let draft;
156
+ let saving;
157
+ let networks = [];
146
158
  let pasting = false;
147
159
  let selected = 0;
148
160
  let server;
149
161
  let url;
162
+ let startupWarning = "";
150
163
  let phase = "idle";
151
164
  let stopped = false;
152
- let notice = "";
165
+ let notice = settings.warning;
153
166
  let exitCode;
154
167
  let settle;
155
168
  let paint;
@@ -158,8 +171,10 @@ export async function startTui({ entry, version }) {
158
171
  const directoriesLabel = cliTr("工作目录", "Working directories");
159
172
  const quitAction = [cliTr("退出", "Quit"), () => quit(0)];
160
173
  const stopAction = [cliTr("停止服务", "Stop web"), stopWeb];
174
+ const backAction = [cliTr("返回", "Back"), () => go("idle")];
161
175
  const menus = {
162
- idle: [[cliTr("启动服务", "Start web"), requestStart], [directoriesLabel, editWorkspaces], quitAction],
176
+ idle: [[cliTr("启动服务", "Start web"), requestStart], [directoriesLabel, editWorkspaces],
177
+ [cliTr("访问设置", "Access settings"), () => go("settings")], quitAction],
163
178
  confirming: [
164
179
  [cliTr("返回", "Back"), backFromConfirmation],
165
180
  [cliTr("仅本次无密码启动", "Start once without a password"), () => startWeb(true)],
@@ -171,6 +186,8 @@ export async function startTui({ entry, version }) {
171
186
  const status = {
172
187
  idle: [() => notice ? cliTr("待机 / 见提示", "Idle / see notice")
173
188
  : stopped ? cliTr("已停止", "Stopped") : cliTr("待机", "Idle"), "36"],
189
+ settings: [() => cliTr("访问设置", "Access settings"), "36;1"],
190
+ networks: [() => cliTr("监听地址", "Listen address"), "36;1"],
174
191
  confirming: [() => cliTr("确认远程访问", "Confirm remote access"), "33;1"],
175
192
  starting: [() => cliTr("启动中", "Starting"), "33;1"],
176
193
  ready: [() => cliTr("监听中", "Listening"), "32;1"],
@@ -184,10 +201,31 @@ export async function startTui({ entry, version }) {
184
201
  width: Math.min(72, (output.columns || 80) - 4),
185
202
  height: Math.max(1, (output.rows || 24) - 1),
186
203
  });
187
- const riskLines = width => REMOTE_RISK.flatMap(line => fold(line, width));
204
+ const riskLines = width => [cliTr(`${proxyOrigin() || address()} 无密码访问`, `${proxyOrigin() || address()} without a password`), REMOTE_RISK]
205
+ .flatMap(line => fold(line, width));
188
206
  const confirmationFits = ({ width, height }) => width >= 32 && riskLines(width).length + 2 <= height;
189
- const activeMenu = dimensions => phase === "confirming" && !confirmationFits(dimensions)
190
- ? menus.confirming.slice(0, 1) : menus[phase];
207
+ function activeMenu(dimensions) {
208
+ if (phase === "settings") return [
209
+ [cliTr(`监听地址:${address()}`, `Listen address: ${address()}`), () => {
210
+ networks = interfaceAddresses();
211
+ go("networks");
212
+ }],
213
+ [cliTr(`密码:${switchLabel(hasPassword())}`, `Password: ${switchLabel(hasPassword())}`), togglePassword],
214
+ [cliTr("设置 / 修改密码", "Set / change password"), editPassword],
215
+ [cliTr(`HTTPS:${switchLabel(hasHttps())}`, `HTTPS: ${switchLabel(hasHttps())}`), toggleHttps],
216
+ [cliTr("生成 SSL 自签证书", "Generate self-signed SSL certificate"), editCertificate],
217
+ [cliTr(`代理入口:${proxyOrigin() || "关"}`, `Proxy origin: ${proxyOrigin() || "Off"}`), editProxyOrigin],
218
+ backAction,
219
+ ];
220
+ if (phase === "networks") return [
221
+ [cliTr(`仅本机 (${loopbackAddress})`, `Loopback only (${loopbackAddress})`), () => chooseAddress(loopbackAddress)],
222
+ [cliTr(`全部 IPv4 网卡 (${wildcardAddress})`, `All IPv4 interfaces (${wildcardAddress})`), () => chooseAddress(wildcardAddress)],
223
+ ...networks.map(({ name, address: ip, cidr }) =>
224
+ [`${cidr ?? ip} — ${name}`, () => chooseAddress(ip)]),
225
+ [cliTr("返回", "Back"), () => go("settings")],
226
+ ];
227
+ return phase === "confirming" && !confirmationFits(dimensions) ? menus.confirming.slice(0, 1) : menus[phase];
228
+ }
191
229
 
192
230
  function render() {
193
231
  paint = undefined;
@@ -210,29 +248,35 @@ export async function startTui({ entry, version }) {
210
248
  ink("36", `+${"-".repeat(width)}+`),
211
249
  ] : fold(`OmO Web / ${label}`, width).map(line => ink(tone, line));
212
250
  const short = text => fold(text, width)[0];
213
- const editorTitle = ink("1", short(cliTr("编辑目录", "Edit directories")));
251
+ const editorTitle = draft && ink("1", short(draft.title));
214
252
  const menu = activeMenu(dimensions);
215
253
  const focus = Math.min(selected, menu.length - 1);
216
254
  const actions = menu.map(([action], index) => index === focus
217
255
  ? ink("7;1", short(`> ${action} `)) : short(` ${action}`));
218
256
  const message = notice ? fold(notice, width).slice(0, 2).map(line => ink("33;1", line)) : [];
219
- const warning = unprotected && (optedIn || server) && phase !== "confirming"
257
+ const warning = unprotected() && (optedIn() || server) && phase !== "confirming"
220
258
  ? fold(REMOTE_WARNING, width).map(line => ink("33;1", line)) : [];
259
+ if (phase === "ready" && startupWarning) warning.push(...fold(startupWarning, width).map(line => ink("33;1", line)));
221
260
  const risk = phase === "confirming" && menu.length > 1
222
261
  ? riskLines(width).map(line => ink("33;1", line)) : [];
223
262
  let editor;
224
263
  let lines;
225
264
  if (draft) {
226
- editor = editorLine(draft, Math.max(2, width - 2));
265
+ editor = editorLine(draft.masked ? { ...draft, text: "*".repeat(draft.text.length) } : draft, Math.max(2, width - 2));
227
266
  lines = [...header, "", editorTitle, `> ${editor}`, "",
228
- ...fold(cliTr(`用 "${delimiter}" 分隔路径,留空使用启动目录。`,
229
- `Separate paths with "${delimiter}". Empty uses the launch directory.`), width),
267
+ ...fold(draft.hint, width),
230
268
  ...message, "", ...fold(cliTr("Enter 确认 / Esc 取消 / Ctrl+U 清空", "Enter confirm / Esc cancel / Ctrl+U clear"), width)];
231
269
  } else if (phase === "confirming") {
232
270
  lines = [...header, "", ...risk, "", ...actions, "",
233
271
  ...fold(menu.length > 1
234
272
  ? cliTr("↑/↓ 移动 / Enter 选择 / Esc 返回", "Up/Down move / Enter select / Esc back")
235
273
  : cliTr("请放大终端以查看风险提示。", "Enlarge the terminal to review the risk."), width)];
274
+ } else if (phase === "settings" || phase === "networks") {
275
+ const hint = phase === "networks" ? cliTr("选择监听网卡,不会修改防火墙规则。", "Select a listen interface; firewall rules are unchanged.")
276
+ : cliTr("Enter 修改 · 保存后下次启动生效 · Esc 返回", "Enter to edit · Applies on the next start · Esc back");
277
+ const origin = phase === "settings" && hasHttps() ? fold(cliTr(`HTTPS 地址:${env.OMO_WEB_ORIGIN}`,
278
+ `HTTPS URL: ${env.OMO_WEB_ORIGIN}`), width) : [];
279
+ lines = [...header, "", ...actions, "", ...message, ...origin, ...fold(hint, width)];
236
280
  } else {
237
281
  const paths = activePaths();
238
282
  const urlRows = url ? fold(url, Math.max(2, width - 2)) : [];
@@ -242,7 +286,11 @@ export async function startTui({ entry, version }) {
242
286
  const directories = paths.length ? paths.slice(0, pathCount).map(path => ` ${pathLabel(path, width - 2)}`)
243
287
  : [short(cliTr(" (未配置)", " (none configured)"))];
244
288
  if (paths.length > pathCount) directories.push(short(cliTr(` 另有 ${paths.length - pathCount} 个`, ` +${paths.length - pathCount} more`)));
245
- lines = [...header, ...warning, "", ...details, ink("1", short(directoriesLabel)), ...directories,
289
+ const connection = phase === "idle" ? [
290
+ short(cliTr(` ${address()} · ${hasHttps() ? "HTTPS" : "HTTP"} · 密码${switchLabel(hasPassword())}`,
291
+ ` ${address()} · ${hasHttps() ? "HTTPS" : "HTTP"} · Password ${switchLabel(hasPassword())}`)),
292
+ ] : [];
293
+ lines = [...header, ...warning, "", ...details, ...connection, ink("1", short(directoriesLabel)), ...directories,
246
294
  "", ...actions, ...message, "", ...fold(cliTr("↑/↓ 移动 / Enter 选择 / Q 退出", "Up/Down move / Enter select / Q quit"), width)];
247
295
  }
248
296
  for (let blank = lines.lastIndexOf(""); lines.length > height && blank >= 0; blank = lines.lastIndexOf("")) {
@@ -257,7 +305,11 @@ export async function startTui({ entry, version }) {
257
305
  lines = [...risk, ...actions];
258
306
  } else {
259
307
  const compactStatus = ink(tone, short(`OmO Web / ${label}`));
260
- lines = warning.length && height > 1
308
+ if (phase === "settings" || phase === "networks") {
309
+ const slots = Math.max(1, height - 1 - message.length);
310
+ const first = Math.max(0, Math.min(focus - Math.floor(slots / 2), actions.length - slots));
311
+ lines = height > 1 ? [compactStatus, ...actions.slice(first, first + slots), ...message] : [actions[focus]];
312
+ } else lines = actions.length > height ? [actions[focus]] : warning.length && height > 1
261
313
  ? [compactStatus, ...warning.slice(0, Math.max(1, height - 2)), actions[focus]]
262
314
  : [...actions, ...message, compactStatus];
263
315
  }
@@ -270,9 +322,146 @@ export async function startTui({ entry, version }) {
270
322
  paint ??= setImmediate(render);
271
323
  }
272
324
 
325
+ function go(next) {
326
+ phase = next;
327
+ selected = 0;
328
+ notice = "";
329
+ }
330
+
331
+ function runSetting(action) {
332
+ notice = cliTr("正在保存…", "Saving…");
333
+ saving = Promise.resolve().then(action).then(message => {
334
+ env = settings.effectiveEnv();
335
+ notice = message ?? cliTr("已保存,下次启动生效。", "Saved. Applies on the next start.");
336
+ }).catch(error => {
337
+ if (!(error instanceof Error)) throw error;
338
+ notice = error.message;
339
+ }).finally(() => {
340
+ saving = undefined;
341
+ if (exitCode !== undefined) settle(exitCode);
342
+ else redraw();
343
+ });
344
+ redraw();
345
+ }
346
+
347
+ function chooseAddress(host) {
348
+ runSetting(async () => {
349
+ await settings.save({ OMO_WEB_HOST: host, OMO_WEB_ALLOW_UNAUTHENTICATED: null });
350
+ go("settings");
351
+ });
352
+ }
353
+
354
+ function togglePassword() {
355
+ runSetting(async () => {
356
+ if (!await settings.setPasswordEnabled(!hasPassword())) {
357
+ editPassword();
358
+ return "";
359
+ }
360
+ });
361
+ }
362
+
363
+ function editPassword() {
364
+ draft = {
365
+ masked: true, text: "", cursor: 0, title: cliTr("新密码", "New password"),
366
+ hint: cliTr("1–128 个可打印 ASCII 字符,建议至少 20 个。输入仅显示星号。",
367
+ "1–128 printable ASCII characters. Aim for at least 20; input is masked."),
368
+ submit(password) {
369
+ if (!passwordPattern.test(password)) {
370
+ notice = cliTr("请使用 1–128 个可打印 ASCII 字符。", "Use 1–128 printable ASCII characters.");
371
+ return;
372
+ }
373
+ runSetting(async () => {
374
+ await settings.changePassword(password);
375
+ draft = undefined;
376
+ if (password.length < recommendedPasswordLength) return cliTr(
377
+ "已保存。密码较短,建议使用至少 20 个字符。",
378
+ "Saved. Short password; use at least 20 characters for better protection.");
379
+ });
380
+ },
381
+ };
382
+ notice = "";
383
+ }
384
+
385
+ function editProxyOrigin() {
386
+ const text = proxyOrigin() ?? "";
387
+ draft = {
388
+ text, cursor: text.length, title: cliTr("外部 HTTPS 入口", "External HTTPS origin"),
389
+ hint: cliTr("例如 https://web.example.com;代理保留 Host。清空可关闭。",
390
+ "E.g. https://web.example.com. Preserve Host. Empty disables."),
391
+ submit(value) {
392
+ const origin = value === "" ? null : parseProxyOrigin(value);
393
+ if (origin === undefined) {
394
+ notice = cliTr("请输入不含路径或尾部斜杠的 HTTPS origin。",
395
+ "Enter an HTTPS origin without a path or trailing slash.");
396
+ return;
397
+ }
398
+ runSetting(async () => {
399
+ await settings.save({ OMO_WEB_PROXY_ORIGIN: origin?.origin ?? null, OMO_WEB_ALLOW_UNAUTHENTICATED: null });
400
+ draft = undefined;
401
+ });
402
+ },
403
+ };
404
+ notice = "";
405
+ }
406
+
407
+ function toggleHttps() {
408
+ runSetting(async () => {
409
+ if (!await settings.setHttpsEnabled(!hasHttps())) {
410
+ editCertificate();
411
+ return "";
412
+ }
413
+ });
414
+ }
415
+
416
+ function editCertificate() {
417
+ let current;
418
+ try {
419
+ if (env.OMO_WEB_ORIGIN) current = new URL(env.OMO_WEB_ORIGIN).hostname;
420
+ } catch (error) {
421
+ if (!(error instanceof TypeError)) throw error;
422
+ }
423
+ const text = current ?? (address() === wildcardAddress ? interfaceAddresses()[0]?.address ?? loopbackAddress : address());
424
+ draft = {
425
+ text, cursor: text.length, title: cliTr("证书主机名", "Certificate host"),
426
+ hint: cliTr("浏览器使用的 IP 或 DNS 名。需 OpenSSL;请核验证书。",
427
+ "Browser IP or DNS name. Requires OpenSSL. Verify the certificate."),
428
+ submit(host) {
429
+ runSetting(async () => {
430
+ const path = await generateCertificate(settings, host, Number(env.OMO_WEB_PORT ?? "4317"));
431
+ draft = undefined;
432
+ return cliTr(`证书已生成:${path}`, `Certificate generated: ${path}`);
433
+ });
434
+ },
435
+ };
436
+ notice = "";
437
+ }
438
+
273
439
  function editWorkspaces() {
274
440
  const text = configured() || cwd;
275
- draft = { text, cursor: text.length };
441
+ draft = {
442
+ text, cursor: text.length, title: cliTr("编辑目录", "Edit directories"),
443
+ hint: cliTr(`用 "${delimiter}" 分隔路径,留空使用启动目录。`,
444
+ `Separate paths with "${delimiter}". Empty uses the launch directory.`),
445
+ submit: applyWorkspaces,
446
+ };
447
+ notice = "";
448
+ }
449
+
450
+ function applyWorkspaces(text) {
451
+ const paths = text.split(delimiter).filter(Boolean).map(path => resolve(cwd, path));
452
+ for (const path of paths) {
453
+ try {
454
+ if (statSync(path, { throwIfNoEntry: false })?.isDirectory()) continue;
455
+ notice = cliTr(`不是目录:${path}`, `Not a directory: ${path}`);
456
+ } catch (error) {
457
+ if (!(error instanceof Error)) throw error;
458
+ notice = cliTr(`无法使用目录 (${error.code ?? "?"}):${path}`,
459
+ `Cannot use directory (${error.code ?? "?"}): ${path}`);
460
+ }
461
+ return;
462
+ }
463
+ workspaces = paths.join(delimiter);
464
+ draft = undefined;
276
465
  notice = "";
277
466
  }
278
467
 
@@ -281,43 +470,34 @@ export async function startTui({ entry, version }) {
281
470
  draft = undefined;
282
471
  notice = "";
283
472
  } else if (!pasting && (key.name === "return" || key.name === "enter")) {
284
- const paths = draft.text.split(delimiter).filter(Boolean).map(path => resolve(cwd, path));
285
- for (const path of paths) {
286
- try {
287
- if (statSync(path, { throwIfNoEntry: false })?.isDirectory()) continue;
288
- notice = cliTr(`不是目录:${path}`, `Not a directory: ${path}`);
289
- } catch (error) {
290
- if (!(error instanceof Error)) throw error;
291
- notice = cliTr(`无法使用目录 (${error.code ?? "?"}):${path}`,
292
- `Cannot use directory (${error.code ?? "?"}): ${path}`);
293
- }
294
- return;
295
- }
296
- workspaces = paths.join(delimiter);
297
- draft = undefined;
298
- notice = "";
473
+ draft.submit(draft.text);
299
474
  } else {
300
475
  const { text: value, cursor } = draft;
301
476
  const left = value.slice(0, cursor), right = value.slice(cursor);
302
477
  const previous = () => cursor - (glyphs(left).at(-1)?.length ?? 0);
303
478
  const next = () => cursor + (glyphs(right)[0]?.length ?? 0);
304
- if (!pasting && key.ctrl && key.name === "u") draft = { text: "", cursor: 0 };
479
+ if (!pasting && key.ctrl && key.name === "u") Object.assign(draft, { text: "", cursor: 0 });
305
480
  else if (!pasting && key.name === "left") draft.cursor = previous();
306
481
  else if (!pasting && key.name === "right") draft.cursor = next();
307
482
  else if (!pasting && key.name === "home") draft.cursor = 0;
308
483
  else if (!pasting && key.name === "end") draft.cursor = value.length;
309
484
  else if (!pasting && key.name === "backspace") {
310
- draft = { text: value.slice(0, previous()) + right, cursor: previous() };
485
+ Object.assign(draft, { text: value.slice(0, previous()) + right, cursor: previous() });
311
486
  } else if (!pasting && key.name === "delete") draft.text = left + value.slice(next());
312
487
  else if (!key.ctrl && !key.meta && text && text === safeText(text) && value.length + text.length <= 8192) {
313
- draft = { text: left + text + right, cursor: cursor + text.length };
488
+ Object.assign(draft, { text: left + text + right, cursor: cursor + text.length });
314
489
  } else return;
315
490
  notice = "";
316
491
  }
317
492
  }
318
493
 
319
494
  function requestStart() {
320
- if (unprotected && !optedIn) {
495
+ if (settings.warning) {
496
+ notice = settings.warning;
497
+ } else if (settings.hasListenerOverride && isRemoteAddress(address()) && !hasHttps()) {
498
+ notice = cliTr("非本机监听必须启用 HTTPS。请在访问设置中启用或生成证书。",
499
+ "Remote listening requires HTTPS. Enable it or generate a certificate in Access settings.");
500
+ } else if (unprotected() && !optedIn()) {
321
501
  phase = "confirming";
322
502
  selected = 0;
323
503
  } else startWeb();
@@ -332,14 +512,15 @@ export async function startTui({ entry, version }) {
332
512
  phase = "starting";
333
513
  selected = 0;
334
514
  notice = "";
515
+ startupWarning = "";
335
516
  redraw();
336
- const env = {
337
- ...process.env,
517
+ const serverEnv = {
518
+ ...env,
338
519
  ...(workspaces === undefined ? {} : { OMO_WEB_WORKSPACES: workspaces }),
339
520
  ...(confirmed ? { OMO_WEB_ALLOW_UNAUTHENTICATED: "1" } : {}),
340
521
  };
341
522
  const child = spawn("bun", ["--no-env-file", entry], {
342
- env, stdio: ["ignore", "pipe", "pipe"], detached: !windows, windowsHide: true,
523
+ env: serverEnv, stdio: ["ignore", "pipe", "pipe"], detached: !windows, windowsHide: true,
343
524
  });
344
525
  let errorMessage;
345
526
  let configMessage;
@@ -358,6 +539,10 @@ export async function startTui({ entry, version }) {
358
539
  redraw();
359
540
  });
360
541
  receiveLines(child.stderr, line => {
542
+ if ((phase === "starting" || phase === "ready") && line.startsWith(WARNING_PREFIX)) {
543
+ startupWarning = safeText(stripVTControlCharacters(line.slice(WARNING_PREFIX.length))).trim();
544
+ redraw();
545
+ }
361
546
  if (phase !== "starting" || configMessage || !line.startsWith(CONFIG_PREFIX)) return;
362
547
  configMessage = safeText(stripVTControlCharacters(line.slice(CONFIG_PREFIX.length))).trim();
363
548
  });
@@ -434,12 +619,13 @@ export async function startTui({ entry, version }) {
434
619
  if (exitCode !== undefined) return;
435
620
  exitCode = code;
436
621
  if (server) stopWeb();
437
- else settle(code);
622
+ else if (!saving) settle(code);
438
623
  }
439
624
 
440
625
  function onKey(text, key) {
441
626
  if (exitCode !== undefined || !key) return;
442
627
  if (key.ctrl && key.name === "c") return quit(130);
628
+ if (saving) return;
443
629
  if (key.name === "paste-start" || key.name === "paste-end") {
444
630
  pasting = key.name === "paste-start";
445
631
  return;
@@ -447,6 +633,7 @@ export async function startTui({ entry, version }) {
447
633
  if (draft) editKey(text, key);
448
634
  else if (pasting) return;
449
635
  else if (key.name === "escape" && phase === "confirming") backFromConfirmation();
636
+ else if (key.name === "escape" && (phase === "settings" || phase === "networks")) go(phase === "settings" ? "idle" : "settings");
450
637
  else if (key.name === "q" || key.name === "escape") return quit(0);
451
638
  else {
452
639
  const menu = activeMenu(viewport());
@@ -1,5 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { join, resolve } from "node:path";
3
+ import { passwordPattern } from "./access-policy.js";
3
4
 
4
5
  const identity = String.raw`
5
6
  $ErrorActionPreference = 'Stop'
@@ -56,9 +57,13 @@ export function readWindowsPasswordFile(path) {
56
57
  }
57
58
 
58
59
  export async function createWindowsPasswordFile(path, password) {
60
+ if (!passwordPattern.test(password)) throw new Error("Invalid password.");
61
+ await createWindowsPrivateFile(path, Buffer.from(`${password}\n`, "ascii"));
62
+ }
63
+
64
+ export async function createWindowsPrivateFile(path, bytes) {
59
65
  await powershell(String.raw`
60
- $password = [Console]::In.ReadToEnd()
61
- if ($password -notmatch '\A[\x20-\x7E]{20,128}\z') { throw 'Invalid password' }
66
+ $bytes = [Convert]::FromBase64String([Console]::In.ReadToEnd())
62
67
  $acl = [System.Security.AccessControl.FileSecurity]::new()
63
68
  $acl.SetOwner($sid)
64
69
  $acl.SetAccessRuleProtection($true, $false)
@@ -67,10 +72,9 @@ export async function createWindowsPasswordFile(path, password) {
67
72
  $file = [IO.FileStream]::new($path, [IO.FileMode]::CreateNew,
68
73
  [System.Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None, 4096, [IO.FileOptions]::None, $acl)
69
74
  try {
70
- $bytes = [Text.Encoding]::ASCII.GetBytes($password + [char]10)
71
75
  $file.Write($bytes, 0, $bytes.Length)
72
76
  } finally {
73
77
  $file.Dispose()
74
78
  }
75
- `, path, password);
79
+ `, path, bytes.toString("base64"));
76
80
  }