okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-021-iE' into f-021-int3616148bb

main
10.4 KiB193 linesraw
1/**
2 * Finding the Cloudflare connector (cloudflared) that is already on this computer.
3 *
4 * Strata used to look only in its own folders, so a cloudflared installed by the system (apt, brew, winget, a .deb) was
5 * reported as "not installed" (Linux tester, cloudflared 2026.5.0 in /usr/bin). Now the places are, in this order:
6 *   1. Strata's own connector folder
7 *   2. the optional connector component folder
8 *   3. every folder on PATH
9 *   4. the usual install places (/usr/bin, /usr/local/bin, ~/.local/bin, Homebrew, Program Files, winget/choco/scoop)
10 * The first one that runs `cloudflared --version` and is new enough is used; the answer says which one and from where.
11 * Nothing here downloads or installs anything.
12 */
13import { utf8Script } from './powershell-utf8.mjs';
14import { execFile } from 'node:child_process';
15import { access, stat } from 'node:fs/promises';
16import { constants } from 'node:fs';
17import { homedir } from 'node:os';
18import { win32, posix } from 'node:path';
19
20/** The quick tunnel flags Strata passes (tunnel --url, --no-autoupdate, --grace-period) and the "Registered tunnel connection" log line it waits for exist from 2022.1.0. */
21export const MIN_VERSION = '2022.1.0';
22
23export function parseVersion(text) {
24  const m = /(\d{4})\.(\d{1,2})\.(\d{1,3})/.exec(String(text ?? ''));
25  return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
26}
27export function versionAtLeast(found, minimum = MIN_VERSION) {
28  const a = Array.isArray(found) ? found : parseVersion(found), b = Array.isArray(minimum) ? minimum : parseVersion(minimum);
29  if (!a || !b) return true; // an unreadable version (a custom build) is not a reason to refuse it
30  for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
31  return true;
32}
33
34const SOURCE_LABEL = {
35  strata: 'Strata’s own connector folder',
36  component: 'the optional connector component',
37  path: 'found on your PATH',
38  system: 'a usual install location',
39  setting: 'chosen with the STRATA_CLOUDFLARED setting',
40};
41
42/** Candidate paths in search order, each as { path, source }. Pure: no disk access. */
43export function connectorCandidates({ directory, componentDirectory = null, platform = process.platform, env = process.env, home = homedir(), search = true } = {}) {
44  // STRATA_CLOUDFLARED=<file> uses exactly that connector; STRATA_CLOUDFLARED_SEARCH=own keeps the search to Strata's own folders.
45  const windows = platform === 'win32', p = windows ? win32 : posix;
46  const name = windows ? 'cloudflared.exe' : 'cloudflared';
47  if (env.STRATA_CLOUDFLARED) return [{ path: env.STRATA_CLOUDFLARED, source: 'setting' }];
48  if (env.STRATA_CLOUDFLARED_SEARCH === 'own') search = false;
49  const out = [], seen = new Set();
50  const add = (dir, source) => {
51    if (!dir) return;
52    const path = p.join(dir, name), key = windows ? path.toLowerCase() : path;
53    if (!seen.has(key)) { seen.add(key); out.push({ path, source }); }
54  };
55  add(directory, 'strata');
56  add(componentDirectory, 'component');
57  if (!search) return out;
58  const pathVariable = windows ? (env.Path ?? env.PATH ?? '') : (env.PATH ?? '');
59  for (const dir of pathVariable.split(windows ? ';' : ':')) add(dir.replace(/^"|"$/g, '').trim(), 'path');
60  if (windows) {
61    const roots = [env.ProgramFiles ?? 'C:\\Program Files', env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)'];
62    for (const root of roots) add(win32.join(root, 'cloudflared'), 'system');
63    if (env.LOCALAPPDATA) add(win32.join(env.LOCALAPPDATA, 'Microsoft', 'WinGet', 'Links'), 'system');
64    add(win32.join(env.ProgramData ?? 'C:\\ProgramData', 'chocolatey', 'bin'), 'system');
65    if (home) add(win32.join(home, 'scoop', 'shims'), 'system');
66  } else {
67    for (const dir of ['/usr/bin', '/usr/local/bin', '/opt/homebrew/bin', '/home/linuxbrew/.linuxbrew/bin', '/snap/bin', '/opt/cloudflared']) add(dir, 'system');
68    if (home) { add(posix.join(home, '.local', 'bin'), 'system'); add(posix.join(home, 'bin'), 'system'); add(posix.join(home, '.cloudflared'), 'system'); }
69  }
70  return out;
71}
72
73/** Runs `<path> --version`; resolves to the combined output, rejects when it does not run. */
74export function runVersion(path) {
75  return new Promise((resolve, reject) => {
76    execFile(path, ['--version'], { timeout: 10000, windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
77      if (error) reject(error); else resolve(`${stdout}\n${stderr}`.trim());
78    });
79  });
80}
81
82async function isRunnableFile(path, platform) {
83  try {
84    if (!(await stat(path)).isFile()) return false;
85    await access(path, platform === 'win32' ? constants.F_OK : constants.X_OK);
86    return true;
87  } catch { return false; }
88}
89
90/**
91 * The connector to use, and what was seen on the way.
92 * Resolves to { found: { path, version, source, label } | null, skipped: [{ path, source, reason, version? }] }.
93 * `tooOld` is set when something was found but every copy is older than the minimum version.
94 */
95export async function findConnector(options = {}) {
96  const platform = options.platform ?? process.platform;
97  const run = options.run ?? runVersion;
98  const usable = options.usable ?? (path => isRunnableFile(path, platform));
99  const skipped = [];
100  for (const candidate of connectorCandidates(options)) {
101    if (!(await usable(candidate.path))) continue;
102    let output;
103    try { output = await run(candidate.path); }
104    catch { skipped.push({ ...candidate, reason: 'does-not-run' }); continue; }
105    if (!/cloudflared/i.test(output) && !parseVersion(output)) { skipped.push({ ...candidate, reason: 'not-cloudflared' }); continue; }
106    const parsed = parseVersion(output), version = parsed ? parsed.join('.') : null;
107    if (!versionAtLeast(parsed)) { skipped.push({ ...candidate, reason: 'too-old', version }); continue; }
108    return { found: { path: candidate.path, version, source: candidate.source, label: SOURCE_LABEL[candidate.source] }, skipped };
109  }
110  return { found: null, skipped };
111}
112
113/** A person-readable sentence about what was found (shown in the Connector step and the review). */
114export function describeConnector(found) {
115  if (!found) return null;
116  return `${found.version ? `cloudflared ${found.version}` : 'cloudflared'} · ${found.path} (${found.label})`;
117}
118
119/** A person-readable reason when nothing usable was found but something unusable was. Null when nothing was seen. */
120export function skippedMessage(skipped) {
121  const old = skipped.find(s => s.reason === 'too-old');
122  if (old) return `The cloudflared at ${old.path} is version ${old.version}, which is too old. Strata needs ${MIN_VERSION} or newer. Update cloudflared, then retry.`;
123  const broken = skipped.find(s => s.reason === 'does-not-run' || s.reason === 'not-cloudflared');
124  if (broken) return `The file at ${broken.path} did not run as cloudflared. Reinstall cloudflared, then retry.`;
125  return null;
126}
127
128/**
129 * Which cloudflared processes run on this computer (a system service, one the person started, another program's tunnel)?
130 * `exclude` is the list of pids that belong to Strata itself. Resolves to { running, kind: 'service' | 'process' | null, pids, procs }
131 * where procs is [{ pid, command }] (the command line is for matching only: it can hold a tunnel token and is never shown).
132 * Failing to look is "not running": a missing ps must never block the tunnel.
133 */
134export async function findRunningConnector({ platform = process.platform, exclude = [], run = defaultProbe } = {}) {
135  const skip = new Set(exclude.filter(Number.isInteger));
136  let procs = [];
137  if (platform === 'win32') {
138    const out = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', utf8Script("Get-CimInstance Win32_Process -Filter \"Name='cloudflared.exe'\" | ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine)\" }")]);
139    procs = out.split(/\r?\n/).map(l => /^(\d+)\t(.*)$/.exec(l)).filter(Boolean).map(m => ({ pid: Number(m[1]), command: m[2] }));
140    if (!procs.length) {   // no PowerShell answer: at least the pids
141      const list = await run('tasklist', ['/FI', 'IMAGENAME eq cloudflared.exe', '/NH', '/FO', 'CSV']);
142      procs = [...list.matchAll(/"cloudflared\.exe","(\d+)"/gi)].map(m => ({ pid: Number(m[1]), command: '' }));
143    }
144  } else {
145    const out = await run('ps', ['-axo', 'pid=,comm=,args=']);
146    procs = out.split('\n').map(l => /^\s*(\d+)\s+(\S+)\s*(.*)$/.exec(l)).filter(m => m && /(^|\/)cloudflared$/.test(m[2])).map(m => ({ pid: Number(m[1]), command: m[3] }));
147  }
148  procs = procs.filter(p => !skip.has(p.pid));
149  if (!procs.length) return { running: false, kind: null, pids: [], procs: [] };
150  let kind = 'process';
151  if (platform === 'linux') {
152    const active = (await run('systemctl', ['is-active', 'cloudflared'])).trim();
153    if (active === 'active') kind = 'service';
154  } else if (platform === 'win32') {
155    const service = await run('sc.exe', ['query', 'Cloudflared']);
156    if (/RUNNING/.test(service)) kind = 'service';
157  }
158  return { running: true, kind, pids: procs.map(p => p.pid), procs };
159}
160
161/**
162 * Split the running connectors into Strata's own tunnel (same port: its command line has --url pointing at `originUrl`'s port; same tunnel:
163 * its command line holds the same token) and tunnels of something else, which are none of Strata's business.
164 */
165export function classifyRunning(running, { originUrl = '', token = '' } = {}) {
166  const port = /:(\d+)\/?$/.exec(String(originUrl))?.[1] ?? null;
167  const own = [], others = [];
168  for (const p of running?.procs ?? []) {
169    const cmd = p.command ?? '';
170    const samePort = !!port && new RegExp(`--url[= ]\\S*:${port}(?:/|\\s|$)`).test(cmd);
171    const sameToken = token.length >= 20 && cmd.includes(token);
172    (samePort || sameToken ? own : others).push(p.pid);
173  }
174  return { own, others };
175}
176
177const pidList = pids => pids.join(', ');
178/** Plain sentence about tunnels that are none of Strata's business (information only, never a refusal). */
179export function otherTunnelMessage(pids) {
180  if (!pids?.length) return null;
181  return pids.length === 1 ? `cloudflared is already running for another tunnel (PID ${pids[0]}).` : `cloudflared is already running for other tunnels (PIDs ${pidList(pids)}).`;
182}
183/** The refusal for Strata's own tunnel already running. */
184export function ownTunnelMessage(pids) {
185  if (!pids?.length) return null;
186  return `Strata’s tunnel for this address is already running (PID ${pidList(pids)}), so Strata did not start a second one. Stop it first (or use it as it is), then connect again here.`;
187}
188
189function defaultProbe(cmd, args) {
190  return new Promise(resolve => {
191    execFile(cmd, args, { timeout: 4000, windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout) => resolve(error ? '' : String(stdout)));
192  });
193}