okami.mom/strata

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

Niko1221Merge f-0243-gui into f-0243-rel (Chat.tsx and DropZone.tsx: the guifix clipboard helpers kept at the conflicts, copyAndTell stays for Markdown and Serving)061a28583

main
6.9 KiB112 linesraw
1import './helpers/isolate-profile.mjs';   // a test run never writes the owner's real Strata profile
2import test from 'node:test';
3import assert from 'node:assert/strict';
4import { spawn } from 'node:child_process';
5import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
6import { existsSync } from 'node:fs';
7import { tmpdir } from 'node:os';
8import { join } from 'node:path';
9import { createServer } from 'node:net';
10import { fileURLToPath, pathToFileURL } from 'node:url';
11import { AcquisitionRefused, forbidden, require as requireAcquisition } from '../server/acquisition.mjs';
12import * as engineInstall from '../server/engine-install.mjs';
13import { createConnectorInstaller } from '../server/cloudflared-install.mjs';
14
15const root = fileURLToPath(new URL('..', import.meta.url));
16const spy = pathToFileURL(fileURLToPath(new URL('./helpers/acquire-spy.mjs', import.meta.url))).href;
17const delay = ms => new Promise(r => setTimeout(r, ms));
18async function freePort() { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }
19
20test('the host-side switch: STRATA_NO_ACQUIRE or the packaged app forbids acquiring, nothing else does', () => {
21  assert.equal(forbidden({}), false);
22  for (const v of ['1', 'true', 'YES', 'on']) assert.equal(forbidden({ STRATA_NO_ACQUIRE: v }), true, v);
23  for (const v of ['0', 'false', '', 'no']) assert.equal(forbidden({ STRATA_NO_ACQUIRE: v }), false, v);
24  assert.equal(forbidden({ STRATA_PACKAGED: '1' }), true);
25  assert.throws(() => requireAcquisition('the llama.cpp engine', undefined, { STRATA_NO_ACQUIRE: '1' }), AcquisitionRefused);
26  assert.doesNotThrow(() => requireAcquisition('x', undefined, {}));
27});
28
29test('the llama.cpp and cloudflared fetches refuse before any request is made', async () => {
30  const previous = process.env.STRATA_NO_ACQUIRE;
31  process.env.STRATA_NO_ACQUIRE = '1';
32  const realFetch = globalThis.fetch;
33  let requests = 0;
34  globalThis.fetch = async () => { requests++; throw new Error('network'); };
35  const directory = await mkdtemp(join(tmpdir(), 'strata-no-acquire-'));
36  try {
37    await assert.rejects(engineInstall.install({ force: true }), err => err instanceof AcquisitionRefused && /llama\.cpp/.test(err.message) && err.status === 409);
38    await assert.rejects(engineInstall.findRelease(), AcquisitionRefused);
39    let connectorRequests = 0;
40    const installer = createConnectorInstaller({ directory, platform: 'linux', arch: 'x64', env: { STRATA_CLOUDFLARED_SEARCH: 'own' }, fetchImpl: async () => { connectorRequests++; return { ok: false }; } });
41    await assert.rejects(installer.ensure(), err => err instanceof AcquisitionRefused && /optional connector component/.test(err.message));
42    assert.equal(requests + connectorRequests, 0, 'nothing was requested');
43    assert.equal(existsSync(join(directory, '.install-')), false);
44  } finally {
45    globalThis.fetch = realFetch;
46    if (previous === undefined) delete process.env.STRATA_NO_ACQUIRE; else process.env.STRATA_NO_ACQUIRE = previous;
47    await rm(directory, { recursive: true, force: true });
48  }
49});
50
51test('a connector placed in the component folder is used as it is; it is never fetched', async () => {
52  const directory = await mkdtemp(join(tmpdir(), 'strata-connector-component-'));
53  const components = join(directory, 'components', 'cloudflared');
54  await mkdir(components, { recursive: true });
55  const name = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';
56  await writeFile(join(components, name), 'binary', { mode: 0o755 });
57  try {
58    const installer = createConnectorInstaller({ directory: join(directory, 'own'), componentDirectory: components, env: { STRATA_CLOUDFLARED_SEARCH: 'own' }, run: async () => 'cloudflared version 2026.5.0', fetchImpl: async () => { throw new Error('no network'); } });
59    assert.equal(await installer.locate(), join(components, name));
60    assert.equal(await installer.ensure(), join(components, name));
61  } finally { await rm(directory, { recursive: true, force: true }); }
62});
63
64async function runHost({ env, calls }) {
65  const home = await mkdtemp(join(tmpdir(), 'strata-no-acquire-host-'));
66  const log = join(home, 'spy.log');
67  await writeFile(log, '');
68  const port = await freePort(), base = `http://127.0.0.1:${port}`;
69  const host = spawn(process.execPath, ['--import', spy, 'server/index.mjs'], {
70    cwd: root, stdio: 'ignore',
71    env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_REAL_ENGINE: '1', STRATA_CLOUDFLARED_SEARCH: 'own', ACQUIRE_SPY_LOG: log, ...env },
72  });
73  const call = async (path, method = 'GET', body) => {
74    const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
75    return { status: response.status, body: await response.json().catch(() => null) };
76  };
77  try {
78    let up = false;
79    for (let i = 0; i < 100 && !up; i++) { try { up = (await call('/api/health')).status === 200; } catch { await delay(100); } }
80    assert.ok(up, 'host started');
81    const results = await calls(call);
82    await delay(300);
83    const lines = (await readFile(log, 'utf8')).split('\n').filter(Boolean).map(l => JSON.parse(l));
84    return { results, attempts: lines };
85  } finally {
86    host.kill();
87    await new Promise(r => host.once('exit', r));
88    await rm(home, { recursive: true, force: true });
89  }
90}
91
92const probes = async call => ({
93  health: await call('/api/health'),
94  binary: await call('/api/engine/binary', 'POST'),
95  tunnel: await call('/api/serving/tunnel', 'POST', { action: 'prepare' }),
96  control: await call('/api/control/status'),
97});
98
99test('the packaged host serves, and every download/install route is refused without one attempt', { timeout: 60000 }, async () => {
100  const { results, attempts } = await runHost({ env: { STRATA_PACKAGED: '1', STRATA_NO_ACQUIRE: '1' }, calls: probes });
101  assert.equal(results.health.status, 200);
102  assert.equal(results.binary.status, 409);
103  assert.match(results.binary.body.error ?? results.binary.body.message ?? JSON.stringify(results.binary.body), /never downloads/);
104  assert.ok(results.tunnel.status >= 400, 'preparing the connector is a refusal');
105  assert.equal(results.control.body.acquisition.forbidden, true);
106  assert.deepEqual(attempts, [], 'nothing tried to reach the internet or run an installer');
107});
108
109test('the spy is live: without the switch the same routes DO attempt to download (and are blocked)', { timeout: 60000 }, async () => {
110  const { attempts } = await runHost({ env: { STRATA_PACKAGED: '', STRATA_NO_ACQUIRE: '' }, calls: async call => { await call('/api/engine/binary', 'POST'); await call('/api/serving/tunnel', 'POST', { action: 'prepare' }); } });
111  assert.ok(attempts.some(a => a.kind === 'fetch' && /api\.github\.com\/repos\/ggml-org\/llama\.cpp/.test(a.detail)), JSON.stringify(attempts));
112});