okami.mom/strata

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

Niko1221Merge f-split-fb4 (201d674e9) into f-split-int: cloudflared discovery, settings file, Gyro minimum engine, two models on two GPUs261145baa

main
5.4 KiB94 linesraw
1/** Install the official connector into Strata's own data folder, without sudo. */
2import { createHash } from 'node:crypto';
3import { execFile } from 'node:child_process';
4import { mkdir, mkdtemp, lstat, rename, rm, chmod, writeFile, access } from 'node:fs/promises';
5import { constants } from 'node:fs';
6import { join } from 'node:path';
7import { promisify } from 'node:util';
8import { require as requireAcquisition } from './acquisition.mjs';
9import { findConnector, skippedMessage } from './cloudflared-find.mjs';
10
11const run = promisify(execFile);
12const RELEASES = 'https://api.github.com/repos/cloudflare/cloudflared/releases/latest';
13const LIMIT = 128 * 1024 * 1024;
14
15export function connectorAsset(platform, arch) {
16  const cpu = { x64: 'amd64', arm64: 'arm64', ia32: '386', arm: 'arm' }[arch];
17  if (!cpu || !['darwin', 'linux', 'win32'].includes(platform) || platform === 'win32' && arch === 'arm64') {
18    throw new Error('Automatic connector setup is not available for this operating system and processor.');
19  }
20  return `cloudflared-${platform === 'win32' ? 'windows' : platform}-${cpu}${platform === 'darwin' ? '.tgz' : platform === 'win32' ? '.exe' : ''}`;
21}
22
23export function verifyConnector(bytes, digest) {
24  if (!/^sha256:[a-f0-9]{64}$/.test(digest ?? '') || `sha256:${createHash('sha256').update(bytes).digest('hex')}` !== digest) {
25    throw new Error('The connector download could not be verified. Retry the automatic setup.');
26  }
27}
28
29/**
30 * `componentDirectory` is where an optional, explicitly installed connector component would live (the local
31 * component folder). A connector found there is used as it is; one that is not there is never fetched while the app
32 * runs (acquisition.mjs), it is a notice.
33 */
34export function createConnectorInstaller({ directory, componentDirectory = null, platform = process.platform, arch = process.arch, fetchImpl = fetch, env = process.env, home, run: runVersion, usable, search }) {
35  const name = platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';
36  const binary = join(directory, name);
37  let installing = null, last = { found: null, skipped: [] };
38  /** Strata's own folder first, then the component folder, PATH and the usual install places (cloudflared-find.mjs). */
39  async function look() {
40    last = await findConnector({ directory, componentDirectory, platform, env, home, run: runVersion, usable, search });
41    return last;
42  }
43  async function locate() { return (await look()).found?.path ?? null; }
44  /** What is in use ({ path, version, source, label }), or null; set by the last look. */
45  const connector = () => last.found;
46  async function install() {
47    const existing = await locate();
48    if (existing) return existing;
49    const unusable = skippedMessage(last.skipped);
50    if (unusable) throw new Error(unusable);
51    requireAcquisition('The Cloudflare connector (cloudflared)', 'the optional connector component');
52    const name = connectorAsset(platform, arch);
53    await mkdir(directory, { recursive: true });
54    const stage = await mkdtemp(join(directory, '.install-'));
55    const request = url => fetchImpl(url, { signal: AbortSignal.timeout(120000), headers: { 'user-agent': 'Strata-connector-setup', accept: 'application/vnd.github+json' } });
56    try {
57      const metadata = await request(RELEASES);
58      if (!metadata.ok) throw new Error('Cloudflare’s download service is unavailable. Try again in a moment.');
59      const release = await metadata.json();
60      const asset = release.assets?.find(a => a.name === name);
61      if (!asset || !asset.browser_download_url?.startsWith('https://github.com/cloudflare/cloudflared/releases/download/')) throw new Error('No official connector download was found for this computer.');
62      if (asset.size > LIMIT) throw new Error('The connector download is unexpectedly large.');
63      const response = await request(asset.browser_download_url);
64      if (!response.ok || !response.body) throw new Error('The connector could not be downloaded. Check your connection and retry.');
65      const chunks = []; let size = 0;
66      for await (const chunk of response.body) {
67        size += chunk.byteLength;
68        if (size > LIMIT) throw new Error('The connector download is unexpectedly large.');
69        chunks.push(chunk);
70      }
71      const bytes = Buffer.concat(chunks);
72      verifyConnector(bytes, asset.digest);
73      const download = join(stage, name);
74      await writeFile(download, bytes, { mode: 0o600 });
75      let candidate = download;
76      if (platform === 'darwin') {
77        const { stdout } = await run('tar', ['-tzf', download], { timeout: 10000 });
78        const entry = stdout.split(/\r?\n/).find(p => p === 'cloudflared' || p === './cloudflared');
79        if (!entry) throw new Error('The connector package did not contain the expected executable.');
80        await run('tar', ['-xzf', download, '-C', stage, entry], { timeout: 10000 });
81        candidate = join(stage, 'cloudflared');
82      }
83      if (!(await lstat(candidate)).isFile()) throw new Error('The connector package contained an invalid executable.');
84      await chmod(candidate, 0o700);
85      await run(candidate, ['--version'], { timeout: 10000, windowsHide: true });
86      await rename(candidate, binary);
87      return binary;
88    } finally { await rm(stage, { recursive: true, force: true }); }
89  }
90  return { locate, connector, async inspect() { await look(); return last; }, ensure() {
91    if (!installing) installing = install().finally(() => { installing = null; });
92    return installing;
93  } };
94}