neurastream 0.2.9 → 0.2.11
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/README.md +2 -0
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +31 -7
- package/src/cli/dispatch.ts +5 -1
- package/src/cli/ui.ts +52 -2
- package/src/core/owner-ui.ts +7 -0
- package/src/core/queue/lib.ts +3 -1
- package/src/core/tailscale.ts +30 -6
- package/src/core/ui-setup.ts +171 -0
- package/templates/systemd/neurastream-ui.service +4 -3
package/README.md
CHANGED
|
@@ -96,6 +96,8 @@ A plan parked for the owner has one line: `WAITING on owner: <what>`. That line
|
|
|
96
96
|
|
|
97
97
|
## Owner page (`neurastream ui`)
|
|
98
98
|
|
|
99
|
+
`neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
|
|
100
|
+
|
|
99
101
|
With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). It shows the plans whose `WAITING on owner:` line is open, with answer buttons; the guard unlock (`unlock 5/15/30`, `lock now`); the running agents; the queue; recent merges/CI; open incidents; agent scores; and machine health. No chat, no plan editing, no shell.
|
|
100
102
|
|
|
101
103
|
A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
|
package/package.json
CHANGED
|
@@ -20,7 +20,7 @@ import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync,
|
|
|
20
20
|
import { basename, dirname, join } from "node:path";
|
|
21
21
|
import type { Decision } from "../../core/adapter.ts";
|
|
22
22
|
import { loadConfig, type Config } from "../../core/config.ts";
|
|
23
|
-
import { nowSec } from "../../core/clock.ts";
|
|
23
|
+
import { nowSec, strftime } from "../../core/clock.ts";
|
|
24
24
|
import { runDetectorsGated } from "../../core/incident-detectors.ts";
|
|
25
25
|
import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
|
|
26
26
|
import { postReply } from "../../core/notify.ts";
|
|
@@ -291,13 +291,37 @@ function writeOwnerInboxCursor(n: number): void {
|
|
|
291
291
|
} catch {}
|
|
292
292
|
}
|
|
293
293
|
|
|
294
|
-
/** The user message one inbox record becomes, or null when
|
|
294
|
+
/** The user message one inbox record becomes, or null when the record is not one Main can act on.
|
|
295
|
+
* Records without `kind` are page answers (the original shape). */
|
|
295
296
|
export function ownerInboxMessage(rec: Record<string, unknown>): string | null {
|
|
296
|
-
const
|
|
297
|
-
const
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
297
|
+
const kind = rec.kind === undefined ? "answer" : asString(rec.kind);
|
|
298
|
+
const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
|
299
|
+
switch (kind) {
|
|
300
|
+
case "answer": {
|
|
301
|
+
const plan = asString(rec.plan);
|
|
302
|
+
const question = asString(rec.question);
|
|
303
|
+
const answer = asString(rec.answer);
|
|
304
|
+
if (!plan || !question || !answer) return null;
|
|
305
|
+
return `Owner answered on the phone page — ${basename(plan)}: ${question} → ${answer}`;
|
|
306
|
+
}
|
|
307
|
+
case "unlock": {
|
|
308
|
+
const minutes = num(rec.minutes);
|
|
309
|
+
const until = num(rec.until);
|
|
310
|
+
if (minutes === null || until === null) return null;
|
|
311
|
+
return `Owner unlocked the guards from the phone page for ${minutes} min (until ${strftime(until, "%H:%M")}). Do the step that waited on the unlock now.`;
|
|
312
|
+
}
|
|
313
|
+
case "lock":
|
|
314
|
+
return "Owner locked the guards from the phone page.";
|
|
315
|
+
case "reorder": {
|
|
316
|
+
const plan = asString(rec.plan);
|
|
317
|
+
const from = num(rec.from);
|
|
318
|
+
const to = num(rec.to);
|
|
319
|
+
if (!plan || from === null || to === null) return null;
|
|
320
|
+
return `Owner moved ${basename(plan)} from #${from} to #${to} on the phone page; INDEX.md has the new order — work by it.`;
|
|
321
|
+
}
|
|
322
|
+
default:
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
301
325
|
}
|
|
302
326
|
|
|
303
327
|
/** The JSONL rows after `cursor` (a row count), as records, plus the new cursor. A torn last row
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -62,6 +62,10 @@ export function helpText(): string {
|
|
|
62
62
|
" neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
|
|
63
63
|
" neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
|
|
64
64
|
" neurastream ui serve the owner's phone page on the tailnet address (ui.enabled, ui.owner_login)",
|
|
65
|
+
" neurastream ui on --login <tailscale login> [--port N]",
|
|
66
|
+
" one go: writes ui.enabled/owner_login (and port) into the config,",
|
|
67
|
+
" installs and restarts the neurastream-ui user unit, prints the phone",
|
|
68
|
+
" link; `neurastream ui off` stops and disables it, sets enabled: false",
|
|
65
69
|
" neurastream agents list | allow <slug>... | deny <slug>...",
|
|
66
70
|
" the subagent allow-list (## Allowed in notes/subagents.md)",
|
|
67
71
|
"",
|
|
@@ -82,7 +86,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
|
|
|
82
86
|
if (cmd === "init") return runInit(args);
|
|
83
87
|
if (cmd === "metrics") return runMetrics(args);
|
|
84
88
|
if (cmd === "incident") return runIncident(args);
|
|
85
|
-
if (cmd === "ui") return runUi();
|
|
89
|
+
if (cmd === "ui") return runUi(args);
|
|
86
90
|
if (cmd === "adapter") return runAdapterInstall(args);
|
|
87
91
|
if (cmd === "config") {
|
|
88
92
|
try {
|
package/src/cli/ui.ts
CHANGED
|
@@ -1,21 +1,71 @@
|
|
|
1
1
|
// `neurastream ui`: serve the owner's phone page on the tailnet address only. Refuses to start
|
|
2
2
|
// when the config has the page off or no owner login; the core startOwnerUi enforces the same
|
|
3
3
|
// two refusals. Runs until killed (systemd user unit templates/systemd/neurastream-ui.service).
|
|
4
|
+
// `ui on --login <email> [--port N]` / `ui off` set up and undo that whole setup in one command
|
|
5
|
+
// (the core lives in src/core/ui-setup.ts); plain `neurastream ui` keeps serving as today.
|
|
4
6
|
|
|
5
7
|
import { defaultRunSource } from "../adapters/omp/sessions.ts";
|
|
6
8
|
import { ConfigError, loadConfig, type Config } from "../core/config.ts";
|
|
7
9
|
import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer } from "../core/owner-ui.ts";
|
|
8
10
|
import { applyQueueEnv } from "../core/queue/env.ts";
|
|
9
|
-
import { realTailscale } from "../core/tailscale.ts";
|
|
11
|
+
import { realTailscale, type Tailscale } from "../core/tailscale.ts";
|
|
12
|
+
import { uiOff, uiOn, type Runner } from "../core/ui-setup.ts";
|
|
10
13
|
|
|
11
14
|
export interface UiDeps {
|
|
12
15
|
/** The merged config. Default: loadConfig(). */
|
|
13
16
|
cfg?: Config;
|
|
14
17
|
/** Starts the page. Default: startOwnerUi. */
|
|
15
18
|
start?: (opts: OwnerUiOptions) => OwnerUiServer;
|
|
19
|
+
/** Command runner for `ui on`/`ui off` (default: spawnSync of systemctl --user). */
|
|
20
|
+
runner?: Runner;
|
|
21
|
+
/** Tailscale seam for `ui on` (default: realTailscale). */
|
|
22
|
+
tailscale?: Tailscale;
|
|
23
|
+
/** HOME the `ui on`/`ui off` config and unit paths resolve against (default: homedir()). */
|
|
24
|
+
home?: string;
|
|
16
25
|
}
|
|
17
26
|
|
|
18
|
-
|
|
27
|
+
const UI_USAGE = "usage: neurastream ui [on --login <tailscale login> [--port N] | off]";
|
|
28
|
+
|
|
29
|
+
// `ui on|off` argument handling: --login is required for on (exit 1, nothing done without it),
|
|
30
|
+
// --port optional; anything else is a usage error (exit 2). No args reaches the serve path.
|
|
31
|
+
function runUiSetup(args: string[], deps: UiDeps): number {
|
|
32
|
+
const on = args[0] === "on";
|
|
33
|
+
let login: string | undefined;
|
|
34
|
+
let port: number | null = null;
|
|
35
|
+
for (let i = 1; i < args.length; i++) {
|
|
36
|
+
if (on && args[i] === "--login") {
|
|
37
|
+
login = args[i + 1];
|
|
38
|
+
i++;
|
|
39
|
+
} else if (on && args[i] === "--port") {
|
|
40
|
+
const n = Number(args[i + 1]);
|
|
41
|
+
if (!Number.isInteger(n) || n! <= 0 || n! > 65535) {
|
|
42
|
+
console.error(`neurastream ui on: --port needs a port number (1..65535), got "${args[i + 1] ?? ""}"`);
|
|
43
|
+
return 2;
|
|
44
|
+
}
|
|
45
|
+
port = n;
|
|
46
|
+
i++;
|
|
47
|
+
} else {
|
|
48
|
+
console.error(UI_USAGE);
|
|
49
|
+
return 2;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const setup = { home: deps.home, runner: deps.runner, tailscale: deps.tailscale };
|
|
53
|
+
if (on) {
|
|
54
|
+
if (!login) {
|
|
55
|
+
console.error("neurastream ui on: --login <tailscale login> is required — e.g. neurastream ui on --login me@example.com");
|
|
56
|
+
return 1;
|
|
57
|
+
}
|
|
58
|
+
return uiOn({ login, port, ...setup });
|
|
59
|
+
}
|
|
60
|
+
return uiOff(setup);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function runUi(args: string[] = [], deps: UiDeps = {}): Promise<number> {
|
|
64
|
+
if (args[0] === "on" || args[0] === "off") return runUiSetup(args, deps);
|
|
65
|
+
if (args.length) {
|
|
66
|
+
console.error(UI_USAGE);
|
|
67
|
+
return 2;
|
|
68
|
+
}
|
|
19
69
|
let cfg = deps.cfg;
|
|
20
70
|
if (!cfg) {
|
|
21
71
|
try {
|
package/src/core/owner-ui.ts
CHANGED
|
@@ -259,12 +259,19 @@ function handleUnlock(cfg: Config, fields: Record<string, string>, login: string
|
|
|
259
259
|
if (minutes !== "" && !/^\d+$/.test(minutes)) return textRes("minutes must be a number", 400);
|
|
260
260
|
const result = chatUnlock(minutes === "" ? "unlock" : `unlock ${minutes}`, cfg, `ui:${login}`, "ui");
|
|
261
261
|
if (!result.applied) return textRes("unlock refused: guards.chat_unlock is off", 409);
|
|
262
|
+
mkdirSync(stateDirPath(), { recursive: true });
|
|
263
|
+
appendFileSync(
|
|
264
|
+
inboxPath(),
|
|
265
|
+
`${JSON.stringify({ ts: nowSec(), kind: "unlock", minutes: result.minutes, until: result.until, login })}\n`,
|
|
266
|
+
);
|
|
262
267
|
return redirect();
|
|
263
268
|
}
|
|
264
269
|
|
|
265
270
|
function handleLock(cfg: Config, login: string): Response {
|
|
266
271
|
const result = chatUnlock("lock", cfg, `ui:${login}`, "ui");
|
|
267
272
|
if (!result.applied) return textRes("lock refused: guards.chat_unlock is off", 409);
|
|
273
|
+
mkdirSync(stateDirPath(), { recursive: true });
|
|
274
|
+
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "lock", login })}\n`);
|
|
268
275
|
return redirect();
|
|
269
276
|
}
|
|
270
277
|
|
package/src/core/queue/lib.ts
CHANGED
|
@@ -621,6 +621,8 @@ export interface ChatUnlockResult {
|
|
|
621
621
|
command?: "unlock" | "lock";
|
|
622
622
|
/** For an unlock: the minutes the existing mtime window stays open (for the owner notice). */
|
|
623
623
|
minutes?: number;
|
|
624
|
+
/** For an unlock: epoch seconds when the guard window closes (mtime + unlock_minutes). */
|
|
625
|
+
until?: number;
|
|
624
626
|
}
|
|
625
627
|
|
|
626
628
|
const CHAT_CMD = /^(unlock|lock)(?:\s+(\d+))?$/i;
|
|
@@ -657,7 +659,7 @@ export function chatUnlock(text: string, cfg: Config, source: string, word: "cha
|
|
|
657
659
|
try {
|
|
658
660
|
appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} UNLOCK ${word} source=${source} minutes=${n}\n`);
|
|
659
661
|
} catch {}
|
|
660
|
-
return { applied: true, command: "unlock", minutes: n };
|
|
662
|
+
return { applied: true, command: "unlock", minutes: n, until: Math.floor(past + minutes * 60) };
|
|
661
663
|
}
|
|
662
664
|
|
|
663
665
|
export function protectedHit(paths: string[]): string | null {
|
package/src/core/tailscale.ts
CHANGED
|
@@ -9,8 +9,10 @@ export interface Tailscale {
|
|
|
9
9
|
ip4(): string | null;
|
|
10
10
|
/** This machine's MagicDNS name (`Self.DNSName` of `tailscale status --self --json`), trailing dot stripped, or null on failure. */
|
|
11
11
|
dnsName(): string | null;
|
|
12
|
-
/** The login that owns the peer address (`
|
|
12
|
+
/** The login that owns the peer address (`UserProfile.LoginName` of `tailscale whois --json <peer>`), or null on failure. */
|
|
13
13
|
whois(peer: string): string | null;
|
|
14
|
+
/** Every `User[*].LoginName` of `tailscale status --json`, or null when tailscale fails or the answer is unreadable — callers then skip their login check with a printed warning, never refuse on a tailscale failure. */
|
|
15
|
+
logins(): string[] | null;
|
|
14
16
|
}
|
|
15
17
|
|
|
16
18
|
function firstStdoutLine(args: string[]): string | null {
|
|
@@ -20,6 +22,17 @@ function firstStdoutLine(args: string[]): string | null {
|
|
|
20
22
|
return line || null;
|
|
21
23
|
}
|
|
22
24
|
|
|
25
|
+
/** The login in `tailscale whois --json` output: multi-line JSON with the login at `UserProfile.LoginName`. Null when absent or unparseable. */
|
|
26
|
+
export function parseWhoisLogin(stdout: string): string | null {
|
|
27
|
+
try {
|
|
28
|
+
const parsed = JSON.parse(stdout) as { UserProfile?: { LoginName?: unknown } };
|
|
29
|
+
const login = parsed.UserProfile?.LoginName;
|
|
30
|
+
return typeof login === "string" && login ? login : null;
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
23
36
|
export const realTailscale: Tailscale = {
|
|
24
37
|
ip4() {
|
|
25
38
|
return firstStdoutLine(["ip", "-4"]);
|
|
@@ -36,12 +49,23 @@ export const realTailscale: Tailscale = {
|
|
|
36
49
|
}
|
|
37
50
|
},
|
|
38
51
|
whois(peer) {
|
|
39
|
-
const
|
|
40
|
-
if (
|
|
52
|
+
const r = spawnSync("tailscale", ["whois", "--json", peer], { encoding: "utf8", timeout: 8000 });
|
|
53
|
+
if (r.error || r.status !== 0) return null;
|
|
54
|
+
return parseWhoisLogin(r.stdout ?? "");
|
|
55
|
+
},
|
|
56
|
+
logins() {
|
|
41
57
|
try {
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
58
|
+
const r = spawnSync("tailscale", ["status", "--json"], { encoding: "utf8", timeout: 8000 });
|
|
59
|
+
if (r.error || r.status !== 0) return null;
|
|
60
|
+
const parsed = JSON.parse(r.stdout ?? "") as { User?: unknown };
|
|
61
|
+
const users = parsed.User;
|
|
62
|
+
if (typeof users !== "object" || users === null || Array.isArray(users)) return null;
|
|
63
|
+
const names: string[] = [];
|
|
64
|
+
for (const user of Object.values(users)) {
|
|
65
|
+
const login = (user as { LoginName?: unknown } | null)?.LoginName;
|
|
66
|
+
if (typeof login === "string" && login) names.push(login);
|
|
67
|
+
}
|
|
68
|
+
return names;
|
|
45
69
|
} catch {
|
|
46
70
|
return null;
|
|
47
71
|
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// `neurastream ui on|off` core (plan 20261025_0300_ui_on_off): one command sets ui.enabled /
|
|
2
|
+
// ui.owner_login (and ui.port) in the user's config.yml, installs the systemd user unit,
|
|
3
|
+
// starts it and prints the phone link; `off` stops the unit and sets ui.enabled back to false.
|
|
4
|
+
// Pure over an injected command runner and the Tailscale seam (src/cli/ui.ts wires the real
|
|
5
|
+
// ones), so tests record argv and never run systemctl or the tailscale binary.
|
|
6
|
+
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { homedir, tmpdir } from "node:os";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { ConfigError, configFile, loadConfig } from "./config.ts";
|
|
13
|
+
import { realTailscale, type Tailscale } from "./tailscale.ts";
|
|
14
|
+
|
|
15
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
16
|
+
export const UI_UNIT_TEMPLATE = join(HERE, "../../templates/systemd/neurastream-ui.service");
|
|
17
|
+
|
|
18
|
+
export interface RunnerResult {
|
|
19
|
+
status: number | null;
|
|
20
|
+
stderr: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type Runner = (args: string[]) => RunnerResult;
|
|
24
|
+
|
|
25
|
+
// Production runner: one systemctl (or any) command, stderr captured for the error path.
|
|
26
|
+
export const systemRunner: Runner = args => {
|
|
27
|
+
const r = spawnSync(args[0]!, args.slice(1), { encoding: "utf8", timeout: 30000 });
|
|
28
|
+
return { status: r.status, stderr: r.stderr ?? "" };
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export interface UiSetupOptions {
|
|
32
|
+
/** HOME the config file and the user unit resolve against. Default: the real home. */
|
|
33
|
+
home?: string;
|
|
34
|
+
/** Command runner. Default: systemRunner (spawnSync). */
|
|
35
|
+
runner?: Runner;
|
|
36
|
+
/** Tailscale seam. Default: realTailscale. */
|
|
37
|
+
tailscale?: Tailscale;
|
|
38
|
+
print?: (line: string) => void;
|
|
39
|
+
error?: (line: string) => void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface UiOnOptions extends UiSetupOptions {
|
|
43
|
+
login: string;
|
|
44
|
+
/** The --port N of the command line; null leaves the config's ui.port in place. */
|
|
45
|
+
port?: number | null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Line-based edit of the top-level `ui:` block: replaces only the enabled/owner_login/port
|
|
49
|
+
// lines inside it, keeps every other line of the file byte-for-byte (comments, order, other
|
|
50
|
+
// sections), and appends a fresh block when the config has none. Never re-serialises YAML.
|
|
51
|
+
function editUiBlock(text: string | null, values: { enabled: boolean; owner_login: string | null; port: number | null }): string {
|
|
52
|
+
const fresh = ["ui:", ` enabled: ${values.enabled}`];
|
|
53
|
+
if (values.owner_login !== null) fresh.push(` owner_login: ${values.owner_login}`);
|
|
54
|
+
if (values.port !== null) fresh.push(` port: ${values.port}`);
|
|
55
|
+
if (text === null) return `${fresh.join("\n")}\n`;
|
|
56
|
+
const lines = text.split("\n");
|
|
57
|
+
let start = -1;
|
|
58
|
+
for (let i = 0; i < lines.length; i++) {
|
|
59
|
+
if (/^ui\s*:(\s*(?:#.*)?)?$/.test(lines[i] ?? "")) {
|
|
60
|
+
start = i;
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (start === -1) {
|
|
65
|
+
const base = text === "" || text.endsWith("\n") ? text : `${text}\n`;
|
|
66
|
+
return `${base}${fresh.join("\n")}\n`;
|
|
67
|
+
}
|
|
68
|
+
let end = start + 1;
|
|
69
|
+
while (end < lines.length && (lines[end] === "" || /^[ \t]/.test(lines[end]!))) end++;
|
|
70
|
+
const setKey = (key: string, value: string): void => {
|
|
71
|
+
const re = new RegExp(`^([ \\t]+)${key}\\s*:.*$`);
|
|
72
|
+
for (let i = start + 1; i < end; i++) {
|
|
73
|
+
const line = lines[i]!;
|
|
74
|
+
if (re.test(line)) {
|
|
75
|
+
lines[i] = line.replace(re, `$1${key}: ${value}`);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// The block has no such key: insert after its last non-blank line, at two-space indent.
|
|
80
|
+
let at = start + 1;
|
|
81
|
+
for (let i = start + 1; i < end; i++) if (lines[i]!.trim() !== "") at = i + 1;
|
|
82
|
+
lines.splice(at, 0, ` ${key}: ${value}`);
|
|
83
|
+
};
|
|
84
|
+
setKey("enabled", String(values.enabled));
|
|
85
|
+
if (values.owner_login !== null) setKey("owner_login", values.owner_login);
|
|
86
|
+
if (values.port !== null) setKey("port", String(values.port));
|
|
87
|
+
return lines.join("\n");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Validates the edited text through loadConfig before anything is written: if it would not
|
|
91
|
+
// load, nothing is written and the caller reports the error (the real file stays untouched).
|
|
92
|
+
function checkEdited(edited: string, home: string, what: string, error: (line: string) => void): boolean {
|
|
93
|
+
const check = join(tmpdir(), `neurastream-ui-${what}-check-${process.pid}.yml`);
|
|
94
|
+
try {
|
|
95
|
+
writeFileSync(check, edited);
|
|
96
|
+
loadConfig({ file: check, home });
|
|
97
|
+
return true;
|
|
98
|
+
} catch (err) {
|
|
99
|
+
error(err instanceof ConfigError ? err.message : String(err));
|
|
100
|
+
return false;
|
|
101
|
+
} finally {
|
|
102
|
+
rmSync(check, { force: true });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function uiOn(opts: UiOnOptions): number {
|
|
107
|
+
const home = opts.home ?? homedir();
|
|
108
|
+
const runner = opts.runner ?? systemRunner;
|
|
109
|
+
const tailscale = opts.tailscale ?? realTailscale;
|
|
110
|
+
const print = opts.print ?? console.log;
|
|
111
|
+
const error = opts.error ?? console.error;
|
|
112
|
+
const file = configFile(home);
|
|
113
|
+
let cfg;
|
|
114
|
+
try {
|
|
115
|
+
cfg = loadConfig({ home });
|
|
116
|
+
} catch (err) {
|
|
117
|
+
error(err instanceof ConfigError ? err.message : String(err));
|
|
118
|
+
return 1;
|
|
119
|
+
}
|
|
120
|
+
const logins = tailscale.logins();
|
|
121
|
+
if (logins === null) {
|
|
122
|
+
error("neurastream ui: cannot read the tailnet logins (`tailscale status --json` failed) — skipping the login check");
|
|
123
|
+
} else if (!logins.includes(opts.login)) {
|
|
124
|
+
error(`neurastream ui: ${opts.login} is not a login on this tailnet. Logins seen: ${logins.join(", ")}`);
|
|
125
|
+
return 1;
|
|
126
|
+
}
|
|
127
|
+
const original = existsSync(file) ? readFileSync(file, "utf8") : null;
|
|
128
|
+
const edited = editUiBlock(original, { enabled: true, owner_login: opts.login, port: opts.port ?? null });
|
|
129
|
+
if (!checkEdited(edited, home, "on", error)) return 1;
|
|
130
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
131
|
+
writeFileSync(file, edited);
|
|
132
|
+
const unitPath = join(home, ".config", "systemd", "user", "neurastream-ui.service");
|
|
133
|
+
mkdirSync(dirname(unitPath), { recursive: true });
|
|
134
|
+
copyFileSync(UI_UNIT_TEMPLATE, unitPath);
|
|
135
|
+
for (const args of [
|
|
136
|
+
["systemctl", "--user", "daemon-reload"],
|
|
137
|
+
["systemctl", "--user", "enable", "neurastream-ui"],
|
|
138
|
+
["systemctl", "--user", "restart", "neurastream-ui"],
|
|
139
|
+
]) {
|
|
140
|
+
const r = runner(args);
|
|
141
|
+
if (r.status !== 0) {
|
|
142
|
+
if (r.stderr.trim()) error(r.stderr.trimEnd());
|
|
143
|
+
error("neurastream ui: systemctl failed — the config was already written; fix the unit and run `neurastream ui` (or this command again).");
|
|
144
|
+
return 1;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const name = tailscale.dnsName() ?? tailscale.ip4();
|
|
148
|
+
const port = opts.port ?? cfg.ui.port;
|
|
149
|
+
if (name) print(`http://${name}:${port}`);
|
|
150
|
+
else error("neurastream ui: could not read this machine's MagicDNS name or tailnet address (is tailscale up?) — the page is running, open it at http://<MagicDNS name>:" + port);
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function uiOff(opts: UiSetupOptions): number {
|
|
155
|
+
const home = opts.home ?? homedir();
|
|
156
|
+
const runner = opts.runner ?? systemRunner;
|
|
157
|
+
const error = opts.error ?? console.error;
|
|
158
|
+
const r = runner(["systemctl", "--user", "disable", "--now", "neurastream-ui"]);
|
|
159
|
+
if (r.status !== 0) {
|
|
160
|
+
if (r.stderr.trim()) error(r.stderr.trimEnd());
|
|
161
|
+
error("neurastream ui: systemctl failed — the config was not touched.");
|
|
162
|
+
return 1;
|
|
163
|
+
}
|
|
164
|
+
const file = configFile(home);
|
|
165
|
+
if (existsSync(file)) {
|
|
166
|
+
const edited = editUiBlock(readFileSync(file, "utf8"), { enabled: false, owner_login: null, port: null });
|
|
167
|
+
if (!checkEdited(edited, home, "off", error)) return 1;
|
|
168
|
+
writeFileSync(file, edited);
|
|
169
|
+
}
|
|
170
|
+
return 0;
|
|
171
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
# User unit for the owner's phone page (neurastream ui).
|
|
2
|
-
# ~/.config/systemd/user
|
|
3
|
-
#
|
|
1
|
+
# User unit for the owner's phone page (neurastream ui). `neurastream ui on --login <email>`
|
|
2
|
+
# copies this into ~/.config/systemd/user/ and enables + restarts it; `neurastream ui off`
|
|
3
|
+
# stops and disables it. Agents never install or start it — that is the owner's move, refused
|
|
4
|
+
# by the guards.
|
|
4
5
|
|
|
5
6
|
[Unit]
|
|
6
7
|
Description=neurastream owner page (neurastream ui)
|