Files
Kaname/src/lib/endpoint-probe.test.ts
T
Pascal LinxweilerandClaude Opus 5.5 0e0445a418 API for agents: tokens, /api/v1 for downloads, verify, repair, tags
Brings back the token API that 0.15 removed with deployments, for
models only, ported onto the current code (local models, lean client
bundles, MiB-rounded disk space):

- Scoped bearer tokens (models:read, downloads:create, models:verify,
  tags:write), stored as SHA-256, managed in Settings -> API tokens.
  Only /api/v1 accepts them; the rest stays OIDC-only.
- /api/v1: Hub lookup, library with the search filters, download
  requests through the add-model/queue path (idempotent), repair of
  missing or broken files, verify / deep verify, tags, job status with
  ?wait=, cancelling or withdrawing the token's own jobs, disk space.
- Guardrails for downloads and repairs: approval (default ask), max
  size per request, minimum free space incl. reserved bytes, agent jobs
  at once, author allowlist (new downloads only). Approve/reject in the
  UI, "requested by" badges and filter, activity log per token.
- Migration 0027 adds api_tokens, agent_activity and requested_by
  columns on models and jobs; job state pending_approval.
- docs/api.md, docs/agent/SKILL.md and the kaname curl helper; DB-backed
  API tests. The login gate test now expects /api/v1 to be left to
  token auth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:52:28 +01:00

102 lines
5.3 KiB
TypeScript

import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { after, before, describe, it } from "node:test";
import { detectEngine, normalizeBaseUrl, pickModel, probeEndpoint } from "./endpoint-probe";
describe("endpoint URLs", () => {
it("keeps the server root and drops /v1 and slashes", () => {
assert.equal(normalizeBaseUrl(" http://192.168.1.20:8080/v1/ "), "http://192.168.1.20:8080");
assert.equal(normalizeBaseUrl("https://llm.example.org/proxy/v1"), "https://llm.example.org/proxy");
assert.equal(normalizeBaseUrl("http://box:8000"), "http://box:8000");
});
it("refuses other schemes, credentials in the URL and queries", () => {
assert.throws(() => normalizeBaseUrl("ftp://box"), /http/);
assert.throws(() => normalizeBaseUrl("http://user:secret@box:8080"), /API key/);
assert.throws(() => normalizeBaseUrl("http://box:8080/?key=1"), /query/);
assert.throws(() => normalizeBaseUrl("box:8080 x"), /URL/);
});
});
describe("engine detection", () => {
it("tells llama.cpp, vLLM, SGLang and Ollama apart", () => {
const none = { props: null, version: null, sglang: null, ollama: null, models: null };
assert.equal(detectEngine({ ...none, props: { build_info: "b6123-abc", default_generation_settings: {} } }), "llama.cpp");
assert.equal(detectEngine({ ...none, models: { data: [{ id: "Qwen/Qwen3-8B", owned_by: "vllm" }] } }), "vllm");
assert.equal(detectEngine({ ...none, version: { version: "0.31.0" } }), "vllm");
assert.equal(detectEngine({ ...none, sglang: { version: "0.5.0" }, version: { version: "0.5.0" } }), "sglang");
assert.equal(detectEngine({ ...none, ollama: { version: "0.12.0" }, version: { version: "x" } }), "ollama");
assert.equal(detectEngine(none), null);
});
});
describe("probing a server", () => {
let server: Server;
let base = "";
const seen: { url: string; auth: string | undefined }[] = [];
before(async () => {
server = createServer((req, res) => {
seen.push({ url: req.url!, auth: req.headers.authorization });
const json = (status: number, v: unknown) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(v));
};
if (req.headers.authorization !== "Bearer sk-test") return json(401, { error: "no" });
if (req.url === "/v1/models") return json(200, { data: [{ id: "Qwen3-8B-Q4_K_M.gguf", owned_by: "llamacpp" }] });
if (req.url === "/props") return json(200, { build_info: "b6123-d812350", total_slots: 4, default_generation_settings: { n_ctx: 32768 } });
if (req.url === "/redirect") {
res.writeHead(302, { Location: "http://example.org/" });
return res.end();
}
return json(404, {});
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
after(() => server.close());
it("reads models, engine, version, context and slots, with the key as a bearer token", async () => {
const p = await probeEndpoint({ baseUrl: base, apiKey: "sk-test", engine: null });
assert.equal(p.ok, true);
assert.deepEqual(p.models, ["Qwen3-8B-Q4_K_M.gguf"]);
assert.equal(p.engine, "llama.cpp");
assert.equal(p.engineVersion, "b6123-d812350");
assert.equal(p.contextSize, 32768);
assert.equal(p.slots, 4);
assert.ok(seen.every((s) => s.auth === "Bearer sk-test"));
assert.ok(seen.every((s) => !s.url.includes("sk-test")), "the key never goes into a URL");
});
it("explains a refused key and an unreachable server", async () => {
const refused = await probeEndpoint({ baseUrl: base, apiKey: "wrong", engine: null });
assert.equal(refused.ok, false);
assert.match(refused.error!, /API key/);
const down = await probeEndpoint({ baseUrl: "http://127.0.0.1:9", apiKey: null, engine: null });
assert.equal(down.ok, false);
assert.match(down.error!, /Couldn't reach/);
});
it("picks the model to run", () => {
const probe = { ok: true, at: "", error: null, latencyMs: 1, models: ["a", "b"], engine: null, engineVersion: null, contextSize: null, slots: null };
assert.deepEqual(pickModel("b", probe), { model: "b" });
assert.match((pickModel("c", probe) as { error: string }).error, /doesn't list "c"/);
assert.match((pickModel(null, probe) as { error: string }).error, /several models/);
assert.deepEqual(pickModel(null, { ...probe, models: ["a"] }), { model: "a" });
});
});
describe("login gate", () => {
// proxy.ts gates every page and API route except Auth.js, the token API (/api/v1, which checks
// its bearer token in each route), the login page and static files.
const src = readFileSync(new URL("../proxy.ts", import.meta.url), "utf8");
const matcher = JSON.parse(`"${src.match(/matcher: \["([^"]+)"\]/)![1]}"`) as string;
const gated = (path: string) => new RegExp(`^${matcher}$`).test(path);
it("gates every API route except Auth.js and the token API", () => {
for (const p of ["/api/endpoints", "/api/endpoints/x/test", "/api/benchmarks", "/api/api-tokens", "/api/v1x", "/settings", "/loginx", "/"]) assert.ok(gated(p), p);
for (const p of ["/api/auth/signin", "/api/v1", "/api/v1/models", "/login", "/_next/static/x.js", "/favicon.ico"]) assert.ok(!gated(p), p);
});
});