okami.mom/strata

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

Niko1221Merge f-022-refusals: environmental refusals repair or warn instead of blocking (audit items 1-4, 6, 8-10, 12-15)bcf88b738

main
6.9 KiB101 linesraw
1/** A supervised Cloudflare connector with a private, inference-only origin. */
2import { spawn } from 'node:child_process';
3import { probe, which } from './util.mjs';
4import { classifyRunning, describeConnector, otherTunnelMessage, ownTunnelMessage } from './cloudflared-find.mjs';
5
6/** A tunnel without a key is allowed (owner decision, 0.2.2); because the link is public the warning is stronger than the local one. */
7export const NO_KEY_TUNNEL_WARNING = 'No API key is set, so anyone who finds this link can use your model from the internet. Create an API key to protect it.';
8export function tunnelHostname(value) {
9  const hostname = String(value ?? '').trim().toLowerCase();
10  if (hostname.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(hostname)) throw new Error('Enter a hostname such as ai.example.com, without https:// or a path.');
11  return hostname;
12}
13export function createCloudflare({ origin, originUrl, hasKey, changed = () => {}, launch = spawn, locate = async () => process.platform === 'win32' ? (await probe('where.exe', ['cloudflared'])).split(/\r?\n/)[0] || null : which('cloudflared'), prepareConnector = null, connectorInfo = () => null, findRunning = async () => ({ running: false, kind: null, pids: [] }), timeoutMs = 45000 }) {
14  let binary = null, other = null, child = null, timer = null, busy = false, generation = 0;
15  let value = { status: 'idle', mode: null, url: null, error: null };
16  const state = () => {
17    const info = binary ? connectorInfo() : null;
18    return { ...value, warning: value.status === 'connected' && !hasKey() ? NO_KEY_TUNNEL_WARNING : null, installed: !!binary, originUrl, connector: info ? { path: info.path, version: info.version, source: info.source, label: info.label, summary: describeConnector(info) } : null, external: other?.running ? externalState() : null };
19  };
20  const update = patch => { value = { ...value, ...patch }; changed(state()); };
21  function externalState(token = '') {
22    const { own, others } = classifyRunning(other, { originUrl, token });
23    return { kind: other.kind, others, own, message: own.length ? ownTunnelMessage(own) : otherTunnelMessage(others) };
24  }
25  async function lookForOther() { try { other = await findRunning({ exclude: [child?.pid] }); } catch { other = null; } return other; }
26  async function inspect() { binary = await locate(); await lookForOther(); changed(state()); return state(); }
27  async function prepare() {
28    if (busy) throw new Error('Connector setup is already in progress.');
29    busy = true;
30    try {
31      binary = await locate();
32      if (!binary && prepareConnector) binary = await prepareConnector();
33      if (!binary) throw new Error('The connector could not be prepared automatically.');
34      update({ error: null });
35      return state();
36    } finally { busy = false; }
37  }
38  async function terminate() {
39    clearTimeout(timer); timer = null;
40    const processRef = child; child = null;
41    if (processRef) {
42      await new Promise(resolve => {
43        const fallback = setTimeout(() => { processRef.kill('SIGKILL'); resolve(); }, 1500);
44        processRef.once('exit', () => { clearTimeout(fallback); resolve(); });
45        processRef.kill('SIGTERM');
46      });
47    }
48    await origin.stop();
49  }
50  async function fail(message, id) {
51    if (id !== generation) return;
52    ++generation; busy = true; update({ status: 'stopping', error: message, url: null });
53    try { await terminate(); } finally { busy = false; update({ status: 'error' }); }
54  }
55  async function start(body) {
56    if (busy || ['starting', 'connected', 'stopping'].includes(value.status)) throw new Error('Stop the current tunnel before starting another.');
57    if (!['quick', 'domain'].includes(body.mode)) throw new Error('Choose a temporary URL or your own domain.');
58    const hostname = body.mode === 'domain' ? tunnelHostname(body.hostname) : null;
59    const token = body.mode === 'domain' ? String(body.token ?? '').trim() : '';
60    if (body.mode === 'domain' && (!/^[A-Za-z0-9+/=_-]{20,8192}$/.test(token))) throw new Error('Paste the tunnel token from Cloudflare, not the full installation command.');
61    busy = true; const id = ++generation;
62    update({ status: 'starting', mode: body.mode, url: null, error: null });
63    try {
64      binary = await locate();
65      if (!binary && prepareConnector) binary = await prepareConnector();
66      if (!binary) throw new Error('The connector could not be prepared automatically. Retry connector setup.');
67      // Strata's own tunnel (same port or same token) is never doubled up. Other cloudflared processes serve other tunnels and are left alone.
68      if ((await lookForOther())?.running) { const { own } = classifyRunning(other, { originUrl, token }); if (own.length) throw new Error(ownTunnelMessage(own)); }
69      await origin.start();
70      // Tokens never appear in command arguments, logs, saved settings, or API responses.
71      const env = { ...process.env };
72      for (const key of Object.keys(env)) if (key.startsWith('TUNNEL_')) delete env[key];
73      if (token) env.TUNNEL_TOKEN = token;
74      const args = ['tunnel', '--no-autoupdate', '--loglevel', 'info', '--grace-period', '1s', ...(hostname ? ['run'] : ['--url', originUrl])];
75      child = launch(binary, args, { env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
76      let tail = '', publicUrl = hostname ? `https://${hostname}` : null, registered = false;
77      const read = chunk => {
78        if (generation !== id) return;
79        tail = (tail + chunk.toString()).slice(-16384);
80        const match = tail.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com\b/);
81        if (!hostname && match) publicUrl = match[0];
82        if (/Registered tunnel connection/i.test(tail)) registered = true;
83        if (publicUrl && registered && value.status !== 'connected') { clearTimeout(timer); update({ status: 'connected', url: `${publicUrl}/v1` }); }
84      };
85      child.stdout?.on('data', read); child.stderr?.on('data', read);
86      child.once('error', () => { void fail('Cloudflared could not start. Check the installation and try again.', id); });
87      child.once('exit', () => { if (generation === id) { child = null; void fail('Cloudflared stopped. Check your network, token and Cloudflare configuration, then reconnect.', id); } });
88      timer = setTimeout(() => { void fail('Cloudflare did not connect in time. Check your internet connection and tunnel setup, then try again.', id); }, timeoutMs);
89      timer.unref?.();
90      return state();
91    } catch (e) {
92      ++generation; await terminate(); update({ status: 'error', url: null, error: e.message }); throw e;
93    } finally { busy = false; }
94  }
95  async function stop() {
96    if (busy) throw new Error('The tunnel is updating. Try again in a moment.');
97    busy = true; ++generation; update({ status: 'stopping', url: null, error: null });
98    try { await terminate(); update({ status: 'idle', mode: null }); return state(); } finally { busy = false; }
99  }
100  return { state, inspect, prepare, start, stop };
101}