@hasna/switcher 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Dockerfile +38 -8
- package/README.md +14 -9
- package/dist/cli/index.js +992 -706
- package/dist/credentials.d.ts +18 -62
- package/dist/direct-launch.d.ts +2 -2
- package/dist/domain.d.ts +78 -4
- package/dist/generated/api.d.ts +109 -1
- package/dist/index.js +15 -11
- package/dist/mcp/index.js +1055 -95
- package/dist/mint/index.js +136 -0
- package/dist/mint-key.d.ts +34 -0
- package/dist/provider-credential-onboarding.d.ts +73 -0
- package/dist/sdk.d.ts +21 -1
- package/dist/sdk.js +15 -11
- package/dist/serve/index.js +350 -90
- package/dist/server.d.ts +2 -1
- package/dist/service.d.ts +8 -1
- package/dist/store.d.ts +4 -0
- package/hasna.contract.json +20 -6
- package/openapi.json +135 -9
- package/package.json +6 -3
package/dist/serve/index.js
CHANGED
|
@@ -9,6 +9,7 @@ import { join } from "path";
|
|
|
9
9
|
var {SQL } = globalThis.Bun;
|
|
10
10
|
import { chmod, mkdir } from "fs/promises";
|
|
11
11
|
import { dirname, resolve } from "path";
|
|
12
|
+
import { createHash } from "crypto";
|
|
12
13
|
|
|
13
14
|
// src/domain.ts
|
|
14
15
|
import { z as z3 } from "zod";
|
|
@@ -67,7 +68,7 @@ function canonicalPolicyJSON(value) {
|
|
|
67
68
|
}
|
|
68
69
|
|
|
69
70
|
// src/domain.ts
|
|
70
|
-
var VERSION = "0.2.
|
|
71
|
+
var VERSION = "0.2.3";
|
|
71
72
|
var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
72
73
|
var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
73
74
|
var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -170,6 +171,7 @@ var runUpdateSchema = z3.object({
|
|
|
170
171
|
routingEvents: routingEventsSchema.optional(),
|
|
171
172
|
routingEventsDropped: z3.number().int().min(0).max(1e6).optional()
|
|
172
173
|
}).strict();
|
|
174
|
+
var catalogSchema = z3.object({ models: z3.array(modelSchema).max(1e4), refreshedAt: z3.string().datetime(), source: z3.enum(["remote", "manual"]) }).strict();
|
|
173
175
|
|
|
174
176
|
class Fault extends Error {
|
|
175
177
|
status;
|
|
@@ -214,6 +216,9 @@ function harnessEligible(model, harness) {
|
|
|
214
216
|
}
|
|
215
217
|
|
|
216
218
|
// src/store.ts
|
|
219
|
+
import { apiKeyMigrations } from "@hasna/contracts/auth";
|
|
220
|
+
var authMigrationPlan = () => apiKeyMigrations().map((migration) => ({ ...migration, checksum: createHash("sha256").update(migration.sql).digest("hex") }));
|
|
221
|
+
|
|
217
222
|
class Store {
|
|
218
223
|
tail = Promise.resolve();
|
|
219
224
|
async exclusive(action) {
|
|
@@ -251,13 +256,16 @@ class Store {
|
|
|
251
256
|
await chmod(file, 384);
|
|
252
257
|
}
|
|
253
258
|
const store = new Store(sql, engine);
|
|
254
|
-
|
|
259
|
+
if (config.migrate === false)
|
|
260
|
+
await store.verifySchema();
|
|
261
|
+
else
|
|
262
|
+
await store.migrate();
|
|
255
263
|
return store;
|
|
256
264
|
} catch (error) {
|
|
257
265
|
await sql?.close().catch(() => {});
|
|
258
266
|
const code = error?.code;
|
|
259
267
|
if (engine === "sqlite" && ["SQLITE_BUSY", "SQLITE_BUSY_SNAPSHOT", "SQLITE_LOCKED"].includes(code ?? "") && Date.now() < deadline) {
|
|
260
|
-
await new Promise((
|
|
268
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(200, 20 * (attempt + 1))));
|
|
261
269
|
continue;
|
|
262
270
|
}
|
|
263
271
|
throw new Fault(500, "storage_unavailable", "Database startup failed; check configuration, permissions and other database users.");
|
|
@@ -270,23 +278,66 @@ class Store {
|
|
|
270
278
|
await tx.unsafe("SELECT pg_advisory_xact_lock(782034215)");
|
|
271
279
|
await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_migrations (version INTEGER PRIMARY KEY)");
|
|
272
280
|
const versions = await tx.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
|
|
273
|
-
if (versions.some((v) => v.version >
|
|
281
|
+
if (versions.some((v) => v.version > 2))
|
|
274
282
|
throw new Error("Newer database schema");
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
+
const applied = new Set(versions.map((v) => Number(v.version)));
|
|
284
|
+
if (!applied.has(1)) {
|
|
285
|
+
await tx.unsafe("CREATE TABLE switcher_providers (id TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
|
|
286
|
+
await tx.unsafe("CREATE TABLE switcher_profiles (id TEXT PRIMARY KEY, provider_id TEXT NOT NULL REFERENCES switcher_providers(id), version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
|
|
287
|
+
await tx.unsafe("CREATE TABLE switcher_catalogs (id TEXT PRIMARY KEY REFERENCES switcher_providers(id) ON DELETE CASCADE, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
|
|
288
|
+
await tx.unsafe("CREATE TABLE switcher_runs (id TEXT PRIMARY KEY, profile_id TEXT NOT NULL REFERENCES switcher_profiles(id), version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
|
|
289
|
+
await tx.unsafe("CREATE TABLE switcher_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL)");
|
|
290
|
+
await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (1)");
|
|
291
|
+
}
|
|
292
|
+
if (this.engine === "postgresql") {
|
|
293
|
+
await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_auth_migrations (id TEXT PRIMARY KEY, checksum TEXT NOT NULL)");
|
|
294
|
+
const migrations = authMigrationPlan();
|
|
295
|
+
const authRows = await tx.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
|
|
296
|
+
const known = new Map(migrations.map((migration) => [migration.id, migration.checksum]));
|
|
297
|
+
for (const row of authRows) {
|
|
298
|
+
if (known.get(String(row.id)) !== String(row.checksum))
|
|
299
|
+
throw new Error("Unknown or changed API-key migration");
|
|
300
|
+
}
|
|
301
|
+
const completed = new Set(authRows.map((row) => String(row.id)));
|
|
302
|
+
for (const migration of migrations)
|
|
303
|
+
if (!completed.has(migration.id)) {
|
|
304
|
+
await tx.unsafe(migration.sql);
|
|
305
|
+
await tx.unsafe("INSERT INTO switcher_auth_migrations(id,checksum) VALUES ($1,$2)", [migration.id, migration.checksum]);
|
|
306
|
+
}
|
|
307
|
+
if (!applied.has(2))
|
|
308
|
+
await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (2)");
|
|
309
|
+
}
|
|
283
310
|
});
|
|
284
311
|
}
|
|
312
|
+
async verifySchema() {
|
|
313
|
+
const versions = await this.sql.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
|
|
314
|
+
const applied = new Set(versions.map((row) => Number(row.version)));
|
|
315
|
+
if (!applied.has(1) || this.engine === "postgresql" && !applied.has(2) || versions.some((row) => Number(row.version) > 2))
|
|
316
|
+
throw new Error("Unsupported database schema");
|
|
317
|
+
if (this.engine === "postgresql") {
|
|
318
|
+
const expected = authMigrationPlan(), rows = await this.sql.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
|
|
319
|
+
const actual = new Map(rows.map((row) => [String(row.id), String(row.checksum)]));
|
|
320
|
+
if (actual.size !== expected.length || expected.some((migration) => actual.get(migration.id) !== migration.checksum))
|
|
321
|
+
throw new Error("Unsupported API-key schema");
|
|
322
|
+
await this.sql.unsafe("SELECT kid, app, agent, tid, scopes, token_hash, issued_at, expires_at, revoked_at, revoked_reason, last_used_at, created_by FROM api_keys LIMIT 0");
|
|
323
|
+
}
|
|
324
|
+
}
|
|
285
325
|
async ready() {
|
|
286
326
|
await this.exclusive(async () => {
|
|
287
327
|
await this.sql.unsafe("SELECT 1");
|
|
288
328
|
});
|
|
289
329
|
}
|
|
330
|
+
authQueryClient() {
|
|
331
|
+
if (this.engine !== "postgresql")
|
|
332
|
+
throw new Fault(500, "auth_config", "Signed API keys require the PostgreSQL backend.");
|
|
333
|
+
return {
|
|
334
|
+
many: async (sql, params = []) => await this.sql.unsafe(sql, [...params]),
|
|
335
|
+
get: async (sql, params = []) => (await this.sql.unsafe(sql, [...params]))[0] ?? null,
|
|
336
|
+
execute: async (sql, params = []) => {
|
|
337
|
+
await this.sql.unsafe(sql, [...params]);
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
}
|
|
290
341
|
async close() {
|
|
291
342
|
await this.tail;
|
|
292
343
|
await this.sql.close();
|
|
@@ -372,7 +423,8 @@ class Store {
|
|
|
372
423
|
}
|
|
373
424
|
|
|
374
425
|
// src/service.ts
|
|
375
|
-
import { createHash as
|
|
426
|
+
import { createHash as createHash3, timingSafeEqual } from "crypto";
|
|
427
|
+
import { verifyApiKey } from "@hasna/contracts/auth";
|
|
376
428
|
import { z as z4 } from "zod";
|
|
377
429
|
|
|
378
430
|
// src/http.ts
|
|
@@ -454,7 +506,7 @@ async function waitForCatalogRetry(delayMs, deadline) {
|
|
|
454
506
|
if (Date.now() + delayMs > deadline)
|
|
455
507
|
throw catalogDeadlineFault();
|
|
456
508
|
if (delayMs > 0)
|
|
457
|
-
await new Promise((
|
|
509
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
458
510
|
}
|
|
459
511
|
async function fetchCatalogPage(url, headers, deadline) {
|
|
460
512
|
for (let retry = 0;; retry++) {
|
|
@@ -562,8 +614,8 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
562
614
|
candidate.outputModalities = capabilities.completion_chat ? ["text"] : [];
|
|
563
615
|
}
|
|
564
616
|
if (provider.catalogFormat === "together") {
|
|
565
|
-
const
|
|
566
|
-
candidate.outputModalities =
|
|
617
|
+
const modalities = { chat: ["text"], language: ["text"], code: ["text"], image: ["image"], audio: ["audio"], video: ["video"], embedding: ["embedding"], rerank: ["rerank"], moderation: ["classification"] };
|
|
618
|
+
candidate.outputModalities = modalities[row.type];
|
|
567
619
|
}
|
|
568
620
|
if (provider.catalogFormat === "fireworks") {
|
|
569
621
|
if (row.supportsImageInput === true)
|
|
@@ -681,11 +733,11 @@ async function discover(provider, env = process.env, resolveCredential) {
|
|
|
681
733
|
}
|
|
682
734
|
|
|
683
735
|
// src/model-policy.ts
|
|
684
|
-
import { createHash } from "crypto";
|
|
736
|
+
import { createHash as createHash2 } from "crypto";
|
|
685
737
|
var roles = ["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"];
|
|
686
|
-
var id = (v,
|
|
738
|
+
var id = (v, label) => {
|
|
687
739
|
if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
|
|
688
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
740
|
+
throw new Fault(400, "invalid_model_policy", `${label} is invalid.`);
|
|
689
741
|
return v;
|
|
690
742
|
};
|
|
691
743
|
var uniq = (xs) => [...new Set(xs)];
|
|
@@ -743,7 +795,7 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
743
795
|
if (Object.values(aliases).some((value) => !allowedModels.includes(value)))
|
|
744
796
|
throw new Fault(422, "model_not_allowed", "A model alias target must be explicitly allowed by the launch policy.");
|
|
745
797
|
const result = { version: 1, model: selected, roles: compiledRoles, allowedModels, aliases, fallbacks };
|
|
746
|
-
return { ...result, digest:
|
|
798
|
+
return { ...result, digest: createHash2("sha256").update(stable(result)).digest("hex") };
|
|
747
799
|
}
|
|
748
800
|
|
|
749
801
|
// src/presets.ts
|
|
@@ -756,17 +808,17 @@ var route = (protocol, baseUrl, options = {}) => ({
|
|
|
756
808
|
notes: [],
|
|
757
809
|
...options
|
|
758
810
|
});
|
|
759
|
-
var preset = (
|
|
760
|
-
id
|
|
811
|
+
var preset = (id, name, protocols, sources, alias) => parse(providerPresetSchema, {
|
|
812
|
+
id,
|
|
761
813
|
name,
|
|
762
814
|
protocols,
|
|
763
815
|
sources,
|
|
764
816
|
credentialAliases: alias ? [alias] : [],
|
|
765
|
-
credentialEnv: alias ? `SWITCHER_PROVIDER_${
|
|
817
|
+
credentialEnv: alias ? `SWITCHER_PROVIDER_${id.toUpperCase().replace(/-/g, "_")}` : undefined,
|
|
766
818
|
verification: "documented"
|
|
767
819
|
});
|
|
768
820
|
var providerPresets = [
|
|
769
|
-
...["opencode", "opencode-go"].map((
|
|
821
|
+
...["opencode", "opencode-go"].map((id) => preset(id, id === "opencode" ? "OpenCode Zen" : "OpenCode Go", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, id === "opencode" ? "https://opencode.ai/zen/v1" : "https://opencode.ai/zen/go/v1", {
|
|
770
822
|
authStyle: protocol === "anthropic-messages" ? "x-api-key" : "bearer",
|
|
771
823
|
catalogAuthStyle: "none",
|
|
772
824
|
notes: ["Discovers the full live catalog. Claude requests are adapted to each model's documented native endpoint. Other harnesses require models compatible with their selected protocol. Go requires an active subscription and coding-agent session headers."]
|
|
@@ -836,8 +888,8 @@ var providerPresets = [
|
|
|
836
888
|
preset("siliconflow", "SiliconFlow", [route("openai-chat", "https://api.siliconflow.cn/v1", { catalogBaseUrl: "https://api.siliconflow.cn/v1", catalogFormat: "openai", notes: ["The official SiliconCloud OpenAPI contract defines GET /models with Bearer auth and data[] model rows; optional type and sub_type filters are available at the upstream endpoint."] })], ["https://github.com/siliconflow/siliconcloud/blob/main/openapi.yaml", "https://docs.siliconflow.cn/docs/userguide/quickstart", "https://docs.siliconflow.cn/docs/api/chat-completions-post"], "SILICONFLOW_API_KEY"),
|
|
837
889
|
...["anthropic-messages", "openai-responses", "openai-chat"].map((protocol) => preset(`generic-${protocol}`, `Custom ${protocol}`, [route(protocol)], []))
|
|
838
890
|
];
|
|
839
|
-
function getProviderPreset(
|
|
840
|
-
const entry = providerPresets.find((p) => p.id ===
|
|
891
|
+
function getProviderPreset(id) {
|
|
892
|
+
const entry = providerPresets.find((p) => p.id === id);
|
|
841
893
|
if (!entry)
|
|
842
894
|
throw new Fault(404, "preset_not_found", "Unknown provider preset. Use switcher providers presets to list available presets.");
|
|
843
895
|
return structuredClone(entry);
|
|
@@ -847,10 +899,13 @@ var openapi_default = {
|
|
|
847
899
|
openapi: "3.0.3",
|
|
848
900
|
info: {
|
|
849
901
|
title: "Switcher API",
|
|
850
|
-
version: "0.2.
|
|
902
|
+
version: "0.2.3",
|
|
851
903
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
852
904
|
},
|
|
853
905
|
security: [
|
|
906
|
+
{
|
|
907
|
+
apiKeyAuth: []
|
|
908
|
+
},
|
|
854
909
|
{
|
|
855
910
|
bearerAuth: []
|
|
856
911
|
}
|
|
@@ -1604,6 +1659,73 @@ var openapi_default = {
|
|
|
1604
1659
|
}
|
|
1605
1660
|
}
|
|
1606
1661
|
},
|
|
1662
|
+
responses: {
|
|
1663
|
+
"200": {
|
|
1664
|
+
description: "Success",
|
|
1665
|
+
content: {
|
|
1666
|
+
"application/json": {
|
|
1667
|
+
schema: {
|
|
1668
|
+
$ref: "#/components/schemas/Catalog"
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
},
|
|
1673
|
+
default: {
|
|
1674
|
+
description: "Structured error",
|
|
1675
|
+
content: {
|
|
1676
|
+
"application/json": {
|
|
1677
|
+
schema: {
|
|
1678
|
+
$ref: "#/components/schemas/Error"
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
},
|
|
1684
|
+
description: "Self-hosted/local server refresh. Hosted clients discover locally and commit catalog metadata through the version-checked catalog endpoint."
|
|
1685
|
+
}
|
|
1686
|
+
},
|
|
1687
|
+
"/v1/providers/{id}/catalog": {
|
|
1688
|
+
put: {
|
|
1689
|
+
operationId: "saveCatalog",
|
|
1690
|
+
parameters: [
|
|
1691
|
+
{
|
|
1692
|
+
name: "id",
|
|
1693
|
+
in: "path",
|
|
1694
|
+
required: true,
|
|
1695
|
+
schema: {
|
|
1696
|
+
type: "string"
|
|
1697
|
+
}
|
|
1698
|
+
},
|
|
1699
|
+
{
|
|
1700
|
+
name: "Idempotency-Key",
|
|
1701
|
+
in: "header",
|
|
1702
|
+
required: true,
|
|
1703
|
+
schema: {
|
|
1704
|
+
type: "string",
|
|
1705
|
+
minLength: 8,
|
|
1706
|
+
maxLength: 128
|
|
1707
|
+
}
|
|
1708
|
+
},
|
|
1709
|
+
{
|
|
1710
|
+
name: "If-Match",
|
|
1711
|
+
in: "header",
|
|
1712
|
+
required: true,
|
|
1713
|
+
schema: {
|
|
1714
|
+
type: "integer",
|
|
1715
|
+
minimum: 1
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
],
|
|
1719
|
+
requestBody: {
|
|
1720
|
+
required: true,
|
|
1721
|
+
content: {
|
|
1722
|
+
"application/json": {
|
|
1723
|
+
schema: {
|
|
1724
|
+
$ref: "#/components/schemas/Catalog"
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
},
|
|
1607
1729
|
responses: {
|
|
1608
1730
|
"200": {
|
|
1609
1731
|
description: "Success",
|
|
@@ -1991,6 +2113,36 @@ var openapi_default = {
|
|
|
1991
2113
|
}
|
|
1992
2114
|
},
|
|
1993
2115
|
"/v1/openapi.json": {
|
|
2116
|
+
get: {
|
|
2117
|
+
operationId: "openApiV1",
|
|
2118
|
+
parameters: [],
|
|
2119
|
+
responses: {
|
|
2120
|
+
"200": {
|
|
2121
|
+
description: "Success",
|
|
2122
|
+
content: {
|
|
2123
|
+
"application/json": {
|
|
2124
|
+
schema: {
|
|
2125
|
+
type: "object",
|
|
2126
|
+
additionalProperties: true
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
},
|
|
2131
|
+
default: {
|
|
2132
|
+
description: "Structured error",
|
|
2133
|
+
content: {
|
|
2134
|
+
"application/json": {
|
|
2135
|
+
schema: {
|
|
2136
|
+
$ref: "#/components/schemas/Error"
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
},
|
|
2142
|
+
security: []
|
|
2143
|
+
}
|
|
2144
|
+
},
|
|
2145
|
+
"/openapi.json": {
|
|
1994
2146
|
get: {
|
|
1995
2147
|
operationId: "openApi",
|
|
1996
2148
|
parameters: [],
|
|
@@ -2016,12 +2168,18 @@ var openapi_default = {
|
|
|
2016
2168
|
}
|
|
2017
2169
|
}
|
|
2018
2170
|
}
|
|
2019
|
-
}
|
|
2171
|
+
},
|
|
2172
|
+
security: []
|
|
2020
2173
|
}
|
|
2021
2174
|
}
|
|
2022
2175
|
},
|
|
2023
2176
|
components: {
|
|
2024
2177
|
securitySchemes: {
|
|
2178
|
+
apiKeyAuth: {
|
|
2179
|
+
type: "apiKey",
|
|
2180
|
+
in: "header",
|
|
2181
|
+
name: "x-api-key"
|
|
2182
|
+
},
|
|
2025
2183
|
bearerAuth: {
|
|
2026
2184
|
type: "http",
|
|
2027
2185
|
scheme: "bearer"
|
|
@@ -3594,10 +3752,12 @@ var openapi_default = {
|
|
|
3594
3752
|
"name"
|
|
3595
3753
|
],
|
|
3596
3754
|
additionalProperties: false
|
|
3597
|
-
}
|
|
3755
|
+
},
|
|
3756
|
+
maxItems: 1e4
|
|
3598
3757
|
},
|
|
3599
3758
|
refreshedAt: {
|
|
3600
|
-
type: "string"
|
|
3759
|
+
type: "string",
|
|
3760
|
+
format: "date-time"
|
|
3601
3761
|
},
|
|
3602
3762
|
source: {
|
|
3603
3763
|
type: "string",
|
|
@@ -4182,10 +4342,12 @@ var openapi_default = {
|
|
|
4182
4342
|
"name"
|
|
4183
4343
|
],
|
|
4184
4344
|
additionalProperties: false
|
|
4185
|
-
}
|
|
4345
|
+
},
|
|
4346
|
+
maxItems: 1e4
|
|
4186
4347
|
},
|
|
4187
4348
|
refreshedAt: {
|
|
4188
|
-
type: "string"
|
|
4349
|
+
type: "string",
|
|
4350
|
+
format: "date-time"
|
|
4189
4351
|
},
|
|
4190
4352
|
source: {
|
|
4191
4353
|
type: "string",
|
|
@@ -4811,15 +4973,31 @@ var openapi_default = {
|
|
|
4811
4973
|
Ready: {
|
|
4812
4974
|
type: "object",
|
|
4813
4975
|
properties: {
|
|
4814
|
-
|
|
4815
|
-
type: "
|
|
4976
|
+
status: {
|
|
4977
|
+
type: "string",
|
|
4978
|
+
enum: [
|
|
4979
|
+
"ready",
|
|
4980
|
+
"unavailable"
|
|
4981
|
+
]
|
|
4982
|
+
},
|
|
4983
|
+
version: {
|
|
4984
|
+
type: "string"
|
|
4985
|
+
},
|
|
4986
|
+
backend: {
|
|
4987
|
+
type: "string",
|
|
4988
|
+
enum: [
|
|
4989
|
+
"sqlite",
|
|
4990
|
+
"postgresql"
|
|
4991
|
+
]
|
|
4816
4992
|
},
|
|
4817
4993
|
reason: {
|
|
4818
4994
|
type: "string"
|
|
4819
4995
|
}
|
|
4820
4996
|
},
|
|
4821
4997
|
required: [
|
|
4822
|
-
"
|
|
4998
|
+
"status",
|
|
4999
|
+
"version",
|
|
5000
|
+
"backend"
|
|
4823
5001
|
],
|
|
4824
5002
|
additionalProperties: false
|
|
4825
5003
|
},
|
|
@@ -4887,41 +5065,64 @@ var openapi_default = {
|
|
|
4887
5065
|
};
|
|
4888
5066
|
|
|
4889
5067
|
// src/service.ts
|
|
4890
|
-
var
|
|
4891
|
-
var
|
|
4892
|
-
|
|
4893
|
-
|
|
5068
|
+
var providerCatalogFingerprint = (provider) => createHash3("sha256").update(JSON.stringify(provider)).digest("hex");
|
|
5069
|
+
var snapshot = (profile, provider, catalog) => createHash3("sha256").update(JSON.stringify([profile, provider, { models: catalog.models, source: catalog.source }])).digest("hex");
|
|
5070
|
+
var hash = (s) => createHash3("sha256").update(s).digest();
|
|
5071
|
+
function localApiKey(headers) {
|
|
5072
|
+
const direct = headers.get("x-api-key");
|
|
5073
|
+
if (direct)
|
|
5074
|
+
return direct;
|
|
5075
|
+
const authorization = headers.get("authorization") ?? "";
|
|
5076
|
+
return authorization.startsWith("Bearer ") ? authorization.slice("Bearer ".length) : "";
|
|
5077
|
+
}
|
|
5078
|
+
function createHandler(store, authentication, providerEnv = process.env, resolveCredential) {
|
|
5079
|
+
const localToken = typeof authentication === "string" ? authentication : undefined;
|
|
5080
|
+
if (localToken !== undefined && (localToken.length < 24 || /[\r\n]/.test(localToken)))
|
|
4894
5081
|
throw new Fault(500, "auth_config", "Set HASNA_SWITCHER_API_KEY to a random token of at least 24 characters.");
|
|
4895
|
-
const expected = hash(
|
|
5082
|
+
const expected = localToken === undefined ? undefined : hash(localToken);
|
|
5083
|
+
const verifier = typeof authentication === "string" ? undefined : verifyApiKey({
|
|
5084
|
+
app: "switcher",
|
|
5085
|
+
signingSecret: authentication.signingSecret,
|
|
5086
|
+
keyStatus: authentication.keyStatus,
|
|
5087
|
+
...authentication.audit ? { audit: authentication.audit } : {}
|
|
5088
|
+
});
|
|
4896
5089
|
return async (request) => {
|
|
4897
5090
|
const requestId = crypto.randomUUID();
|
|
4898
5091
|
const json = (body, status = 200) => Response.json(body, { status, headers: { "x-request-id": requestId, "cache-control": "no-store", "x-content-type-options": "nosniff" } });
|
|
4899
5092
|
try {
|
|
4900
5093
|
const url = new URL(request.url);
|
|
4901
|
-
const
|
|
4902
|
-
if (request.method === "GET" &&
|
|
5094
|
+
const route = url.pathname.replace(/\/$/, "");
|
|
5095
|
+
if (request.method === "GET" && route === "/health")
|
|
4903
5096
|
return json({ status: "ok", version: VERSION, backend: store.engine });
|
|
4904
|
-
if (request.method === "GET" &&
|
|
5097
|
+
if (request.method === "GET" && route === "/version")
|
|
4905
5098
|
return json({ version: VERSION });
|
|
4906
|
-
if (request.method === "GET" &&
|
|
5099
|
+
if (request.method === "GET" && route === "/ready") {
|
|
4907
5100
|
try {
|
|
4908
5101
|
await store.ready();
|
|
4909
|
-
return json({ ready:
|
|
5102
|
+
return json({ status: "ready", version: VERSION, backend: store.engine });
|
|
4910
5103
|
} catch {
|
|
4911
|
-
return json({
|
|
5104
|
+
return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
|
|
4912
5105
|
}
|
|
4913
5106
|
}
|
|
4914
|
-
if (
|
|
4915
|
-
throw new Fault(401, "unauthorized", "A valid API bearer token is required.");
|
|
4916
|
-
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
|
|
5107
|
+
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route))
|
|
4917
5108
|
return json(openapi_default);
|
|
4918
|
-
|
|
5109
|
+
if (expected) {
|
|
5110
|
+
const presented = hash(localApiKey(request.headers));
|
|
5111
|
+
if (!timingSafeEqual(expected, presented))
|
|
5112
|
+
throw new Fault(401, "unauthorized", "A valid API key is required.");
|
|
5113
|
+
} else {
|
|
5114
|
+
const requiredScopes = [request.method === "GET" || request.method === "HEAD" ? "switcher:read" : "switcher:write"];
|
|
5115
|
+
const decision = await verifier.authenticate(request.headers, { method: request.method, path: route, requiredScopes });
|
|
5116
|
+
if (!decision.ok)
|
|
5117
|
+
throw new Fault(decision.status, `auth_${decision.reason}`, decision.message);
|
|
5118
|
+
}
|
|
5119
|
+
const parts = route.split("/").filter(Boolean);
|
|
4919
5120
|
if (parts[0] !== "v1")
|
|
4920
5121
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
4921
5122
|
const resource = parts[1];
|
|
4922
|
-
const
|
|
4923
|
-
if (
|
|
4924
|
-
parse(idSchema,
|
|
5123
|
+
const id = parts[2];
|
|
5124
|
+
if (id)
|
|
5125
|
+
parse(idSchema, id);
|
|
4925
5126
|
const page = () => parse(z4.object({
|
|
4926
5127
|
limit: z4.coerce.number().int().min(1).max(1000).default(100),
|
|
4927
5128
|
offset: z4.coerce.number().int().min(0).max(1e6).default(0),
|
|
@@ -4929,16 +5130,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
4929
5130
|
}).strict(), Object.fromEntries(url.searchParams));
|
|
4930
5131
|
if (request.method === "GET") {
|
|
4931
5132
|
if (resource === "provider-presets" && parts.length <= 3)
|
|
4932
|
-
return json(
|
|
5133
|
+
return json(id ? getProviderPreset(id) : { data: providerPresets });
|
|
4933
5134
|
if (["providers", "profiles", "runs"].includes(resource) && parts.length <= 3) {
|
|
4934
5135
|
const kind = resource;
|
|
4935
|
-
return json(
|
|
5136
|
+
return json(id ? await store.get(kind, id) : await store.list(kind, page()));
|
|
4936
5137
|
}
|
|
4937
|
-
if (resource === "providers" &&
|
|
4938
|
-
const catalog = await store.get("catalogs",
|
|
5138
|
+
if (resource === "providers" && id && parts[3] === "models" && parts.length === 4) {
|
|
5139
|
+
const catalog = await store.get("catalogs", id);
|
|
4939
5140
|
const p = page();
|
|
4940
5141
|
const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
|
|
4941
|
-
return json({ ...catalog, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m), expired: modelExpired(m) })), total: filtered.length, ...p });
|
|
5142
|
+
return json({ ...catalog, providerVersion: undefined, providerFingerprint: undefined, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m), expired: modelExpired(m) })), total: filtered.length, ...p });
|
|
4942
5143
|
}
|
|
4943
5144
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
4944
5145
|
}
|
|
@@ -4957,7 +5158,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
4957
5158
|
throw new Fault(400, "invalid_json", "Request must contain valid JSON under 1 MiB.");
|
|
4958
5159
|
}
|
|
4959
5160
|
}
|
|
4960
|
-
const fingerprint = hash(JSON.stringify([request.method,
|
|
5161
|
+
const fingerprint = hash(JSON.stringify([request.method, route, body, request.headers.get("if-match")])).toString("hex");
|
|
4961
5162
|
const version = () => {
|
|
4962
5163
|
const v = request.headers.get("if-match");
|
|
4963
5164
|
if (!v || !/^[1-9]\d*$/.test(v))
|
|
@@ -4966,49 +5167,73 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
4966
5167
|
};
|
|
4967
5168
|
const replay = await store.replay(key, fingerprint);
|
|
4968
5169
|
if (replay.found)
|
|
4969
|
-
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
5170
|
+
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
|
|
4970
5171
|
let refreshed;
|
|
4971
|
-
if (resource === "providers" &&
|
|
5172
|
+
if (!expected && resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST")
|
|
5173
|
+
throw new Fault(422, "local_catalog_refresh_required", "Hosted Switcher never contacts provider URLs. Refresh with the local CLI or MCP client, which authenticates locally and commits catalog metadata only.");
|
|
5174
|
+
if (resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
4972
5175
|
parse(z4.object({}).strict(), body);
|
|
4973
|
-
const provider = await store.get("providers",
|
|
5176
|
+
const provider = await store.get("providers", id);
|
|
4974
5177
|
refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
|
|
4975
5178
|
}
|
|
4976
5179
|
const result = await store.mutate(key, fingerprint, async (db) => {
|
|
4977
5180
|
if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
|
|
4978
|
-
if (request.method === "DELETE" &&
|
|
4979
|
-
return store.remove(resource,
|
|
4980
|
-
if (request.method === "POST" && !
|
|
5181
|
+
if (request.method === "DELETE" && id)
|
|
5182
|
+
return store.remove(resource, id, version(), db);
|
|
5183
|
+
if (request.method === "POST" && !id || request.method === "PUT" && id) {
|
|
4981
5184
|
const value = resource === "providers" ? parse(providerInputSchema, body) : parse(profileInputSchema, body);
|
|
4982
|
-
if (
|
|
5185
|
+
if (id && value.id !== id)
|
|
4983
5186
|
throw new Fault(400, "id_mismatch", "Path and body IDs must match.");
|
|
4984
5187
|
if (resource === "profiles") {
|
|
4985
5188
|
const profile = value;
|
|
4986
5189
|
const provider = await store.get("providers", profile.providerId, db);
|
|
4987
5190
|
validateHarnessProvider(profile.harness, provider);
|
|
4988
5191
|
}
|
|
4989
|
-
const saved = await store.put(resource, value,
|
|
4990
|
-
if (resource === "providers" &&
|
|
4991
|
-
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [
|
|
5192
|
+
const saved = await store.put(resource, value, id ? version() : undefined, db);
|
|
5193
|
+
if (resource === "providers" && id)
|
|
5194
|
+
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id]);
|
|
4992
5195
|
return saved;
|
|
4993
5196
|
}
|
|
4994
5197
|
}
|
|
4995
|
-
if (resource === "providers" &&
|
|
5198
|
+
if (resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
4996
5199
|
if (store.engine === "postgresql")
|
|
4997
|
-
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [
|
|
4998
|
-
const provider = await store.get("providers",
|
|
5200
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id]);
|
|
5201
|
+
const provider = await store.get("providers", id, db);
|
|
4999
5202
|
if (!refreshed || provider.version !== refreshed.provider.version)
|
|
5000
5203
|
throw new Fault(409, "provider_changed", "Provider changed during discovery; refresh again.");
|
|
5001
5204
|
const catalog = refreshed.catalog;
|
|
5002
5205
|
let old;
|
|
5003
5206
|
try {
|
|
5004
|
-
old = await store.get("catalogs",
|
|
5207
|
+
old = await store.get("catalogs", id, db);
|
|
5005
5208
|
} catch (e) {
|
|
5006
5209
|
if (!(e instanceof Fault && e.status === 404))
|
|
5007
5210
|
throw e;
|
|
5008
5211
|
}
|
|
5009
|
-
|
|
5212
|
+
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5213
|
+
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
5010
5214
|
}
|
|
5011
|
-
if (resource === "
|
|
5215
|
+
if (resource === "providers" && id && parts[3] === "catalog" && parts.length === 4 && request.method === "PUT") {
|
|
5216
|
+
if (store.engine === "postgresql")
|
|
5217
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id]);
|
|
5218
|
+
const provider = await store.get("providers", id, db);
|
|
5219
|
+
if (provider.version !== version())
|
|
5220
|
+
throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
|
|
5221
|
+
const catalog = parse(catalogSchema, body);
|
|
5222
|
+
const expectedSource = provider.manualModels.length ? "manual" : "remote";
|
|
5223
|
+
if (catalog.source !== expectedSource)
|
|
5224
|
+
throw new Fault(422, "catalog_source_mismatch", "Catalog provenance does not match the current provider configuration.");
|
|
5225
|
+
catalog.refreshedAt = new Date().toISOString();
|
|
5226
|
+
let old;
|
|
5227
|
+
try {
|
|
5228
|
+
old = await store.get("catalogs", id, db);
|
|
5229
|
+
} catch (error) {
|
|
5230
|
+
if (!(error instanceof Fault && error.status === 404))
|
|
5231
|
+
throw error;
|
|
5232
|
+
}
|
|
5233
|
+
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5234
|
+
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
5235
|
+
}
|
|
5236
|
+
if (resource === "launch-plans" && !id && request.method === "POST") {
|
|
5012
5237
|
const { profileId } = parse(z4.object({ profileId: idSchema }).strict(), body);
|
|
5013
5238
|
const profile = await store.get("profiles", profileId, db);
|
|
5014
5239
|
const provider = await store.get("providers", profile.providerId, db);
|
|
@@ -5021,6 +5246,9 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5021
5246
|
throw new Fault(422, "catalog_missing", "Refresh the provider catalog before launching.");
|
|
5022
5247
|
throw e;
|
|
5023
5248
|
}
|
|
5249
|
+
const stored = catalog;
|
|
5250
|
+
if (stored.providerVersion !== undefined && stored.providerVersion !== provider.version || stored.providerFingerprint !== undefined && stored.providerFingerprint !== providerCatalogFingerprint(provider))
|
|
5251
|
+
throw new Fault(409, "catalog_provider_changed", "Catalog metadata belongs to an older provider configuration; refresh locally before launching.");
|
|
5024
5252
|
const selected = catalog.models.find((m) => m.id === profile.model);
|
|
5025
5253
|
if (!selected)
|
|
5026
5254
|
throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
|
|
@@ -5038,7 +5266,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5038
5266
|
warnings.push("Catalog snapshot is older than five minutes; refresh before launching.");
|
|
5039
5267
|
return { profile, provider, catalog, warnings, planToken: snapshot(profile, provider, catalog) };
|
|
5040
5268
|
}
|
|
5041
|
-
if (resource === "runs" && !
|
|
5269
|
+
if (resource === "runs" && !id && request.method === "POST") {
|
|
5042
5270
|
if (body?.modelPolicyVersion !== 1)
|
|
5043
5271
|
throw new Fault(409, "launcher_upgrade_required", "This API requires a launcher with automatic model policy version 1; upgrade the Switcher CLI/SDK.");
|
|
5044
5272
|
const input = parse(runInputSchema, body);
|
|
@@ -5063,16 +5291,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5063
5291
|
compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
|
|
5064
5292
|
return store.put("runs", { ...input, modelPolicy: profile.modelPolicy, providerId: provider.id, providerVersion: provider.version, profileVersion: profile.version, id: crypto.randomUUID(), status: "running", startedAt: new Date().toISOString() }, undefined, db);
|
|
5065
5293
|
}
|
|
5066
|
-
if (resource === "runs" &&
|
|
5294
|
+
if (resource === "runs" && id && request.method === "PATCH" && parts.length === 3) {
|
|
5067
5295
|
const input = parse(runUpdateSchema, body);
|
|
5068
|
-
const run = await store.get("runs",
|
|
5296
|
+
const run = await store.get("runs", id, db);
|
|
5069
5297
|
if (run.status !== "running")
|
|
5070
5298
|
throw new Fault(409, "run_finished", "Run has already finished.");
|
|
5071
5299
|
return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
|
|
5072
5300
|
}
|
|
5073
5301
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
5074
5302
|
});
|
|
5075
|
-
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
5303
|
+
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
|
|
5076
5304
|
} catch (error) {
|
|
5077
5305
|
const safe = error instanceof Fault ? error : new Fault(500, "internal_error", "Request failed.");
|
|
5078
5306
|
return json({ error: { code: safe.code, message: safe.message, requestId } }, safe.status);
|
|
@@ -5081,21 +5309,35 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5081
5309
|
}
|
|
5082
5310
|
|
|
5083
5311
|
// src/server.ts
|
|
5312
|
+
import { ApiKeyStore } from "@hasna/contracts/auth";
|
|
5084
5313
|
async function startServer(options) {
|
|
5085
5314
|
const port = options.port ?? 0;
|
|
5086
5315
|
if (!Number.isInteger(port) || port < 0 || port > 65535)
|
|
5087
5316
|
throw new Fault(400, "invalid_port", "Port must be an integer between 0 and 65535.");
|
|
5088
|
-
if (options.apiKey
|
|
5317
|
+
if (Boolean(options.apiKey) === Boolean(options.signingSecret))
|
|
5318
|
+
throw new Fault(500, "auth_config", "Configure exactly one local API token or hosted API signing secret.");
|
|
5319
|
+
if (options.apiKey && (options.apiKey.length < 24 || /[\r\n]/.test(options.apiKey)))
|
|
5089
5320
|
throw new Fault(500, "auth_config", "Use a random operator token of at least 24 characters.");
|
|
5090
|
-
|
|
5321
|
+
if (options.signingSecret && (options.signingSecret.length < 32 || /[\r\n]/.test(options.signingSecret)))
|
|
5322
|
+
throw new Fault(500, "auth_config", "Use an API signing secret of at least 32 characters.");
|
|
5323
|
+
if (options.signingSecret && !options.databaseUrl)
|
|
5324
|
+
throw new Fault(500, "storage_config", "Hosted signed-key authentication requires PostgreSQL; configure HASNA_SWITCHER_DATABASE_URL.");
|
|
5325
|
+
const store = await Store.open({ databaseUrl: options.databaseUrl, sqlitePath: options.sqlitePath, migrate: !options.signingSecret });
|
|
5091
5326
|
let server;
|
|
5092
5327
|
try {
|
|
5328
|
+
const authentication = options.apiKey ?? (() => {
|
|
5329
|
+
const keyStore = new ApiKeyStore(store.authQueryClient());
|
|
5330
|
+
return { kind: "signed-api-key", signingSecret: options.signingSecret, keyStatus: keyStore.keyStatus, audit: (event) => {
|
|
5331
|
+
if (event.outcome === "deny")
|
|
5332
|
+
console.error(`api_auth deny kid=${event.kid ?? "-"} reason=${event.reason ?? "-"} ${event.method ?? "-"} ${event.path ?? "-"}`);
|
|
5333
|
+
} };
|
|
5334
|
+
})();
|
|
5093
5335
|
server = Bun.serve({
|
|
5094
5336
|
hostname: options.hostname ?? "127.0.0.1",
|
|
5095
5337
|
port,
|
|
5096
5338
|
maxRequestBodySize: 1024 * 1024,
|
|
5097
5339
|
idleTimeout: 60,
|
|
5098
|
-
fetch: createHandler(store,
|
|
5340
|
+
fetch: createHandler(store, authentication, options.providerEnv, options.resolveCredential)
|
|
5099
5341
|
});
|
|
5100
5342
|
await store.ready();
|
|
5101
5343
|
} catch (error) {
|
|
@@ -5122,7 +5364,7 @@ async function startServer(options) {
|
|
|
5122
5364
|
|
|
5123
5365
|
// src/serve.ts
|
|
5124
5366
|
async function main(args = process.argv.slice(2)) {
|
|
5125
|
-
const { values } = parseArgs({ args, options: {
|
|
5367
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
|
|
5126
5368
|
host: { type: "string" },
|
|
5127
5369
|
port: { type: "string" },
|
|
5128
5370
|
"data-dir": { type: "string" },
|
|
@@ -5136,24 +5378,42 @@ async function main(args = process.argv.slice(2)) {
|
|
|
5136
5378
|
return;
|
|
5137
5379
|
}
|
|
5138
5380
|
if (values.help) {
|
|
5139
|
-
console.log(`switcher-serve --sqlite PATH | --data-dir DIR | inject HASNA_SWITCHER_DATABASE_URL
|
|
5381
|
+
console.log(`switcher-serve [migrate] --sqlite PATH | --data-dir DIR | inject HASNA_SWITCHER_DATABASE_URL
|
|
5140
5382
|
--host HOST (127.0.0.1) --port PORT (8080; 0 allocates a port) --json --version
|
|
5141
|
-
|
|
5383
|
+
Local/self-hosted auth: HASNA_SWITCHER_API_KEY (24+ characters). Hosted Postgres auth: HASNA_SWITCHER_API_SIGNING_KEY (32+ characters).
|
|
5384
|
+
The migrate command requires PostgreSQL and exits after applying the schema. Provider credentials: SWITCHER_PROVIDER_* environment references.`);
|
|
5142
5385
|
return;
|
|
5143
5386
|
}
|
|
5387
|
+
if (positionals.length > 1 || positionals[0] && positionals[0] !== "migrate")
|
|
5388
|
+
throw new Fault(400, "invalid_request", "Use switcher-serve, or switcher-serve migrate.");
|
|
5144
5389
|
const port = Number(values.port ?? process.env.PORT ?? 8080);
|
|
5145
5390
|
if (!Number.isInteger(port) || port < 0 || port > 65535)
|
|
5146
5391
|
throw new Fault(400, "invalid_port", "Port must be an integer between 0 and 65535.");
|
|
5147
|
-
const apiKey = process.env.HASNA_SWITCHER_API_KEY
|
|
5148
|
-
|
|
5149
|
-
|
|
5392
|
+
const apiKey = process.env.HASNA_SWITCHER_API_KEY;
|
|
5393
|
+
const signingSecret = process.env.HASNA_SWITCHER_API_SIGNING_KEY ?? process.env.HASNA_API_SIGNING_KEY ?? process.env.API_KEY_SIGNING_SECRET;
|
|
5394
|
+
const databaseUrl = process.env.HASNA_SWITCHER_DATABASE_URL;
|
|
5150
5395
|
if (values.sqlite && values["data-dir"])
|
|
5151
5396
|
throw new Fault(400, "storage_config", "Choose --sqlite or --data-dir.");
|
|
5397
|
+
if (positionals[0] === "migrate") {
|
|
5398
|
+
if (!databaseUrl)
|
|
5399
|
+
throw new Fault(500, "storage_config", "switcher-serve migrate requires HASNA_SWITCHER_DATABASE_URL.");
|
|
5400
|
+
if (values.sqlite || values["data-dir"] || process.env.HASNA_SWITCHER_SQLITE_PATH)
|
|
5401
|
+
throw new Fault(400, "storage_config", "switcher-serve migrate accepts only the PostgreSQL backend.");
|
|
5402
|
+
const store = await Store.open({ databaseUrl });
|
|
5403
|
+
try {
|
|
5404
|
+
await store.ready();
|
|
5405
|
+
} finally {
|
|
5406
|
+
await store.close();
|
|
5407
|
+
}
|
|
5408
|
+
console.log(JSON.stringify({ event: "migrated", version: VERSION, storage: "postgresql" }));
|
|
5409
|
+
return;
|
|
5410
|
+
}
|
|
5152
5411
|
const server = await startServer({
|
|
5153
|
-
apiKey,
|
|
5412
|
+
...apiKey ? { apiKey } : {},
|
|
5413
|
+
...signingSecret ? { signingSecret } : {},
|
|
5154
5414
|
hostname: values.host ?? "127.0.0.1",
|
|
5155
5415
|
port,
|
|
5156
|
-
databaseUrl
|
|
5416
|
+
databaseUrl,
|
|
5157
5417
|
sqlitePath: values.sqlite ?? (values["data-dir"] ? join(values["data-dir"], "switcher.db") : process.env.HASNA_SWITCHER_SQLITE_PATH)
|
|
5158
5418
|
});
|
|
5159
5419
|
console.log(JSON.stringify({ event: "listening", version: VERSION, url: server.url, storage: server.storage }));
|