@hasna/switcher 0.2.1 → 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.
@@ -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.1";
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}$/);
@@ -92,6 +93,8 @@ var urlSchema = z3.string().max(2000).superRefine((v, ctx) => {
92
93
  ctx.addIssue({ code: "custom", message: "Invalid endpoint URL" });
93
94
  }
94
95
  }).transform(endpoint);
96
+ var credentialCheckPath = z3.string().min(1).max(200).regex(/^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$/).refine((value) => !value.startsWith("/") && !value.split("/").some((part) => part === "." || part === ".."), "credentialCheck.path must be relative without dot segments");
97
+ var credentialCheckSchema = z3.object({ method: z3.enum(["GET", "HEAD"]).default("GET"), path: credentialCheckPath }).strict();
95
98
  var expiresOnSchema = z3.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
96
99
  const day = new Date(`${value}T00:00:00.000Z`);
97
100
  return Number.isFinite(day.getTime()) && day.toISOString().slice(0, 10) === value;
@@ -117,6 +120,7 @@ var providerInputSchema = z3.object({
117
120
  protocol: protocolSchema,
118
121
  credentialEnv: envRef.optional(),
119
122
  authStyle: z3.enum(["bearer", "x-api-key", "api-key"]).default("bearer"),
123
+ credentialCheck: credentialCheckSchema.optional(),
120
124
  catalogBaseUrl: urlSchema.optional(),
121
125
  catalogFormat: z3.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]).optional(),
122
126
  catalogAuthStyle: z3.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
@@ -135,6 +139,7 @@ var providerPresetSchema = z3.object({
135
139
  protocol: protocolSchema,
136
140
  baseUrl: urlSchema.optional(),
137
141
  authStyle: z3.enum(["bearer", "x-api-key", "api-key"]),
142
+ credentialCheck: credentialCheckSchema.optional(),
138
143
  catalogBaseUrl: urlSchema.optional(),
139
144
  catalogFormat: z3.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]),
140
145
  catalogAuthStyle: z3.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
@@ -166,6 +171,7 @@ var runUpdateSchema = z3.object({
166
171
  routingEvents: routingEventsSchema.optional(),
167
172
  routingEventsDropped: z3.number().int().min(0).max(1e6).optional()
168
173
  }).strict();
174
+ var catalogSchema = z3.object({ models: z3.array(modelSchema).max(1e4), refreshedAt: z3.string().datetime(), source: z3.enum(["remote", "manual"]) }).strict();
169
175
 
170
176
  class Fault extends Error {
171
177
  status;
@@ -210,6 +216,9 @@ function harnessEligible(model, harness) {
210
216
  }
211
217
 
212
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
+
213
222
  class Store {
214
223
  tail = Promise.resolve();
215
224
  async exclusive(action) {
@@ -247,13 +256,16 @@ class Store {
247
256
  await chmod(file, 384);
248
257
  }
249
258
  const store = new Store(sql, engine);
250
- await store.migrate();
259
+ if (config.migrate === false)
260
+ await store.verifySchema();
261
+ else
262
+ await store.migrate();
251
263
  return store;
252
264
  } catch (error) {
253
265
  await sql?.close().catch(() => {});
254
266
  const code = error?.code;
255
267
  if (engine === "sqlite" && ["SQLITE_BUSY", "SQLITE_BUSY_SNAPSHOT", "SQLITE_LOCKED"].includes(code ?? "") && Date.now() < deadline) {
256
- await new Promise((resolve2) => setTimeout(resolve2, Math.min(200, 20 * (attempt + 1))));
268
+ await new Promise((resolve) => setTimeout(resolve, Math.min(200, 20 * (attempt + 1))));
257
269
  continue;
258
270
  }
259
271
  throw new Fault(500, "storage_unavailable", "Database startup failed; check configuration, permissions and other database users.");
@@ -266,23 +278,66 @@ class Store {
266
278
  await tx.unsafe("SELECT pg_advisory_xact_lock(782034215)");
267
279
  await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_migrations (version INTEGER PRIMARY KEY)");
268
280
  const versions = await tx.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
269
- if (versions.some((v) => v.version > 1))
281
+ if (versions.some((v) => v.version > 2))
270
282
  throw new Error("Newer database schema");
271
- if (versions.length)
272
- return;
273
- await tx.unsafe("CREATE TABLE switcher_providers (id TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
274
- 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)");
275
- 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)");
276
- 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)");
277
- await tx.unsafe("CREATE TABLE switcher_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL)");
278
- await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (1)");
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
+ }
279
310
  });
280
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
+ }
281
325
  async ready() {
282
326
  await this.exclusive(async () => {
283
327
  await this.sql.unsafe("SELECT 1");
284
328
  });
285
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
+ }
286
341
  async close() {
287
342
  await this.tail;
288
343
  await this.sql.close();
@@ -368,7 +423,8 @@ class Store {
368
423
  }
369
424
 
370
425
  // src/service.ts
371
- import { createHash as createHash2, timingSafeEqual } from "crypto";
426
+ import { createHash as createHash3, timingSafeEqual } from "crypto";
427
+ import { verifyApiKey } from "@hasna/contracts/auth";
372
428
  import { z as z4 } from "zod";
373
429
 
374
430
  // src/http.ts
@@ -450,7 +506,7 @@ async function waitForCatalogRetry(delayMs, deadline) {
450
506
  if (Date.now() + delayMs > deadline)
451
507
  throw catalogDeadlineFault();
452
508
  if (delayMs > 0)
453
- await new Promise((resolve2) => setTimeout(resolve2, delayMs));
509
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
454
510
  }
455
511
  async function fetchCatalogPage(url, headers, deadline) {
456
512
  for (let retry = 0;; retry++) {
@@ -558,8 +614,8 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
558
614
  candidate.outputModalities = capabilities.completion_chat ? ["text"] : [];
559
615
  }
560
616
  if (provider.catalogFormat === "together") {
561
- const modalities2 = { chat: ["text"], language: ["text"], code: ["text"], image: ["image"], audio: ["audio"], video: ["video"], embedding: ["embedding"], rerank: ["rerank"], moderation: ["classification"] };
562
- candidate.outputModalities = modalities2[row.type];
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];
563
619
  }
564
620
  if (provider.catalogFormat === "fireworks") {
565
621
  if (row.supportsImageInput === true)
@@ -677,11 +733,11 @@ async function discover(provider, env = process.env, resolveCredential) {
677
733
  }
678
734
 
679
735
  // src/model-policy.ts
680
- import { createHash } from "crypto";
736
+ import { createHash as createHash2 } from "crypto";
681
737
  var roles = ["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"];
682
- var id = (v, label2) => {
738
+ var id = (v, label) => {
683
739
  if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
684
- throw new Fault(400, "invalid_model_policy", `${label2} is invalid.`);
740
+ throw new Fault(400, "invalid_model_policy", `${label} is invalid.`);
685
741
  return v;
686
742
  };
687
743
  var uniq = (xs) => [...new Set(xs)];
@@ -739,7 +795,7 @@ function compileModelPolicy(model, catalog, policy) {
739
795
  if (Object.values(aliases).some((value) => !allowedModels.includes(value)))
740
796
  throw new Fault(422, "model_not_allowed", "A model alias target must be explicitly allowed by the launch policy.");
741
797
  const result = { version: 1, model: selected, roles: compiledRoles, allowedModels, aliases, fallbacks };
742
- return { ...result, digest: createHash("sha256").update(stable(result)).digest("hex") };
798
+ return { ...result, digest: createHash2("sha256").update(stable(result)).digest("hex") };
743
799
  }
744
800
 
745
801
  // src/presets.ts
@@ -752,17 +808,17 @@ var route = (protocol, baseUrl, options = {}) => ({
752
808
  notes: [],
753
809
  ...options
754
810
  });
755
- var preset = (id2, name, protocols, sources, alias) => parse(providerPresetSchema, {
756
- id: id2,
811
+ var preset = (id, name, protocols, sources, alias) => parse(providerPresetSchema, {
812
+ id,
757
813
  name,
758
814
  protocols,
759
815
  sources,
760
816
  credentialAliases: alias ? [alias] : [],
761
- credentialEnv: alias ? `SWITCHER_PROVIDER_${id2.toUpperCase().replace(/-/g, "_")}` : undefined,
817
+ credentialEnv: alias ? `SWITCHER_PROVIDER_${id.toUpperCase().replace(/-/g, "_")}` : undefined,
762
818
  verification: "documented"
763
819
  });
764
820
  var providerPresets = [
765
- ...["opencode", "opencode-go"].map((id2) => preset(id2, id2 === "opencode" ? "OpenCode Zen" : "OpenCode Go", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, id2 === "opencode" ? "https://opencode.ai/zen/v1" : "https://opencode.ai/zen/go/v1", {
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", {
766
822
  authStyle: protocol === "anthropic-messages" ? "x-api-key" : "bearer",
767
823
  catalogAuthStyle: "none",
768
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."]
@@ -772,7 +828,7 @@ var providerPresets = [
772
828
  route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
773
829
  route("anthropic-messages", "https://api.deepseek.com/anthropic/v1", { catalogBaseUrl: "https://api.deepseek.com" })
774
830
  ], ["https://api-docs.deepseek.com/guides/anthropic_api", "https://api-docs.deepseek.com/api/list-models", "https://api-docs.deepseek.com/updates/", "https://api-docs.deepseek.com/guides/responses_api/"], "DEEPSEEK_API_KEY"),
775
- preset("openrouter", "OpenRouter", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, "https://openrouter.ai/api/v1", { catalogAuthStyle: "none" })), ["https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties", "https://openrouter.ai/docs/guides/overview"], "OPENROUTER_API_KEY"),
831
+ preset("openrouter", "OpenRouter", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, "https://openrouter.ai/api/v1", { catalogAuthStyle: "none", credentialCheck: { method: "GET", path: "key" } })), ["https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties", "https://openrouter.ai/docs/guides/overview"], "OPENROUTER_API_KEY"),
776
832
  preset("anthropic", "Anthropic", [route("anthropic-messages", "https://api.anthropic.com/v1", { authStyle: "x-api-key" })], ["https://platform.claude.com/docs/en/api/overview", "https://platform.claude.com/docs/en/api/models/list"], "ANTHROPIC_API_KEY"),
777
833
  preset("gemini", "Google Gemini", [route("gemini-generate-content", "https://generativelanguage.googleapis.com/v1beta", {
778
834
  authStyle: "x-api-key",
@@ -832,8 +888,8 @@ var providerPresets = [
832
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"),
833
889
  ...["anthropic-messages", "openai-responses", "openai-chat"].map((protocol) => preset(`generic-${protocol}`, `Custom ${protocol}`, [route(protocol)], []))
834
890
  ];
835
- function getProviderPreset(id2) {
836
- const entry = providerPresets.find((p) => p.id === id2);
891
+ function getProviderPreset(id) {
892
+ const entry = providerPresets.find((p) => p.id === id);
837
893
  if (!entry)
838
894
  throw new Fault(404, "preset_not_found", "Unknown provider preset. Use switcher providers presets to list available presets.");
839
895
  return structuredClone(entry);
@@ -843,10 +899,13 @@ var openapi_default = {
843
899
  openapi: "3.0.3",
844
900
  info: {
845
901
  title: "Switcher API",
846
- version: "0.2.1",
902
+ version: "0.2.3",
847
903
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
848
904
  },
849
905
  security: [
906
+ {
907
+ apiKeyAuth: []
908
+ },
850
909
  {
851
910
  bearerAuth: []
852
911
  }
@@ -1600,6 +1659,73 @@ var openapi_default = {
1600
1659
  }
1601
1660
  }
1602
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
+ },
1603
1729
  responses: {
1604
1730
  "200": {
1605
1731
  description: "Success",
@@ -1987,6 +2113,36 @@ var openapi_default = {
1987
2113
  }
1988
2114
  },
1989
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": {
1990
2146
  get: {
1991
2147
  operationId: "openApi",
1992
2148
  parameters: [],
@@ -2012,12 +2168,18 @@ var openapi_default = {
2012
2168
  }
2013
2169
  }
2014
2170
  }
2015
- }
2171
+ },
2172
+ security: []
2016
2173
  }
2017
2174
  }
2018
2175
  },
2019
2176
  components: {
2020
2177
  securitySchemes: {
2178
+ apiKeyAuth: {
2179
+ type: "apiKey",
2180
+ in: "header",
2181
+ name: "x-api-key"
2182
+ },
2021
2183
  bearerAuth: {
2022
2184
  type: "http",
2023
2185
  scheme: "bearer"
@@ -2073,6 +2235,29 @@ var openapi_default = {
2073
2235
  "api-key"
2074
2236
  ]
2075
2237
  },
2238
+ credentialCheck: {
2239
+ type: "object",
2240
+ properties: {
2241
+ method: {
2242
+ type: "string",
2243
+ enum: [
2244
+ "GET",
2245
+ "HEAD"
2246
+ ],
2247
+ default: "GET"
2248
+ },
2249
+ path: {
2250
+ type: "string",
2251
+ minLength: 1,
2252
+ maxLength: 200,
2253
+ pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
2254
+ }
2255
+ },
2256
+ required: [
2257
+ "path"
2258
+ ],
2259
+ additionalProperties: false
2260
+ },
2076
2261
  catalogBaseUrl: {
2077
2262
  type: "string",
2078
2263
  maxLength: 2000
@@ -2182,6 +2367,29 @@ var openapi_default = {
2182
2367
  ],
2183
2368
  default: "bearer"
2184
2369
  },
2370
+ credentialCheck: {
2371
+ type: "object",
2372
+ properties: {
2373
+ method: {
2374
+ type: "string",
2375
+ enum: [
2376
+ "GET",
2377
+ "HEAD"
2378
+ ],
2379
+ default: "GET"
2380
+ },
2381
+ path: {
2382
+ type: "string",
2383
+ minLength: 1,
2384
+ maxLength: 200,
2385
+ pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
2386
+ }
2387
+ },
2388
+ required: [
2389
+ "path"
2390
+ ],
2391
+ additionalProperties: false
2392
+ },
2185
2393
  catalogBaseUrl: {
2186
2394
  type: "string",
2187
2395
  maxLength: 2000
@@ -2460,6 +2668,29 @@ var openapi_default = {
2460
2668
  ],
2461
2669
  default: "bearer"
2462
2670
  },
2671
+ credentialCheck: {
2672
+ type: "object",
2673
+ properties: {
2674
+ method: {
2675
+ type: "string",
2676
+ enum: [
2677
+ "GET",
2678
+ "HEAD"
2679
+ ],
2680
+ default: "GET"
2681
+ },
2682
+ path: {
2683
+ type: "string",
2684
+ minLength: 1,
2685
+ maxLength: 200,
2686
+ pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
2687
+ }
2688
+ },
2689
+ required: [
2690
+ "path"
2691
+ ],
2692
+ additionalProperties: false
2693
+ },
2463
2694
  catalogBaseUrl: {
2464
2695
  type: "string",
2465
2696
  maxLength: 2000
@@ -3521,10 +3752,12 @@ var openapi_default = {
3521
3752
  "name"
3522
3753
  ],
3523
3754
  additionalProperties: false
3524
- }
3755
+ },
3756
+ maxItems: 1e4
3525
3757
  },
3526
3758
  refreshedAt: {
3527
- type: "string"
3759
+ type: "string",
3760
+ format: "date-time"
3528
3761
  },
3529
3762
  source: {
3530
3763
  type: "string",
@@ -3582,6 +3815,29 @@ var openapi_default = {
3582
3815
  ],
3583
3816
  default: "bearer"
3584
3817
  },
3818
+ credentialCheck: {
3819
+ type: "object",
3820
+ properties: {
3821
+ method: {
3822
+ type: "string",
3823
+ enum: [
3824
+ "GET",
3825
+ "HEAD"
3826
+ ],
3827
+ default: "GET"
3828
+ },
3829
+ path: {
3830
+ type: "string",
3831
+ minLength: 1,
3832
+ maxLength: 200,
3833
+ pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
3834
+ }
3835
+ },
3836
+ required: [
3837
+ "path"
3838
+ ],
3839
+ additionalProperties: false
3840
+ },
3585
3841
  catalogBaseUrl: {
3586
3842
  type: "string",
3587
3843
  maxLength: 2000
@@ -4086,10 +4342,12 @@ var openapi_default = {
4086
4342
  "name"
4087
4343
  ],
4088
4344
  additionalProperties: false
4089
- }
4345
+ },
4346
+ maxItems: 1e4
4090
4347
  },
4091
4348
  refreshedAt: {
4092
- type: "string"
4349
+ type: "string",
4350
+ format: "date-time"
4093
4351
  },
4094
4352
  source: {
4095
4353
  type: "string",
@@ -4715,15 +4973,31 @@ var openapi_default = {
4715
4973
  Ready: {
4716
4974
  type: "object",
4717
4975
  properties: {
4718
- ready: {
4719
- type: "boolean"
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
+ ]
4720
4992
  },
4721
4993
  reason: {
4722
4994
  type: "string"
4723
4995
  }
4724
4996
  },
4725
4997
  required: [
4726
- "ready"
4998
+ "status",
4999
+ "version",
5000
+ "backend"
4727
5001
  ],
4728
5002
  additionalProperties: false
4729
5003
  },
@@ -4791,41 +5065,64 @@ var openapi_default = {
4791
5065
  };
4792
5066
 
4793
5067
  // src/service.ts
4794
- var snapshot = (profile, provider, catalog) => createHash2("sha256").update(JSON.stringify([profile, provider, { models: catalog.models, source: catalog.source }])).digest("hex");
4795
- var hash = (s) => createHash2("sha256").update(s).digest();
4796
- function createHandler(store, apiKey, providerEnv = process.env, resolveCredential) {
4797
- if (!apiKey || apiKey.length < 24)
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)))
4798
5081
  throw new Fault(500, "auth_config", "Set HASNA_SWITCHER_API_KEY to a random token of at least 24 characters.");
4799
- const expected = hash(`Bearer ${apiKey}`);
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
+ });
4800
5089
  return async (request) => {
4801
5090
  const requestId = crypto.randomUUID();
4802
5091
  const json = (body, status = 200) => Response.json(body, { status, headers: { "x-request-id": requestId, "cache-control": "no-store", "x-content-type-options": "nosniff" } });
4803
5092
  try {
4804
5093
  const url = new URL(request.url);
4805
- const route2 = url.pathname.replace(/\/$/, "");
4806
- if (request.method === "GET" && route2 === "/health")
5094
+ const route = url.pathname.replace(/\/$/, "");
5095
+ if (request.method === "GET" && route === "/health")
4807
5096
  return json({ status: "ok", version: VERSION, backend: store.engine });
4808
- if (request.method === "GET" && route2 === "/version")
5097
+ if (request.method === "GET" && route === "/version")
4809
5098
  return json({ version: VERSION });
4810
- if (request.method === "GET" && route2 === "/ready") {
5099
+ if (request.method === "GET" && route === "/ready") {
4811
5100
  try {
4812
5101
  await store.ready();
4813
- return json({ ready: true });
5102
+ return json({ status: "ready", version: VERSION, backend: store.engine });
4814
5103
  } catch {
4815
- return json({ ready: false, reason: "Storage is unavailable." }, 503);
5104
+ return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
4816
5105
  }
4817
5106
  }
4818
- if (!timingSafeEqual(expected, hash(request.headers.get("authorization") ?? "")))
4819
- throw new Fault(401, "unauthorized", "A valid API bearer token is required.");
4820
- if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
5107
+ if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route))
4821
5108
  return json(openapi_default);
4822
- const parts = route2.split("/").filter(Boolean);
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);
4823
5120
  if (parts[0] !== "v1")
4824
5121
  throw new Fault(404, "not_found", "Route was not found.");
4825
5122
  const resource = parts[1];
4826
- const id2 = parts[2];
4827
- if (id2)
4828
- parse(idSchema, id2);
5123
+ const id = parts[2];
5124
+ if (id)
5125
+ parse(idSchema, id);
4829
5126
  const page = () => parse(z4.object({
4830
5127
  limit: z4.coerce.number().int().min(1).max(1000).default(100),
4831
5128
  offset: z4.coerce.number().int().min(0).max(1e6).default(0),
@@ -4833,16 +5130,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4833
5130
  }).strict(), Object.fromEntries(url.searchParams));
4834
5131
  if (request.method === "GET") {
4835
5132
  if (resource === "provider-presets" && parts.length <= 3)
4836
- return json(id2 ? getProviderPreset(id2) : { data: providerPresets });
5133
+ return json(id ? getProviderPreset(id) : { data: providerPresets });
4837
5134
  if (["providers", "profiles", "runs"].includes(resource) && parts.length <= 3) {
4838
5135
  const kind = resource;
4839
- return json(id2 ? await store.get(kind, id2) : await store.list(kind, page()));
5136
+ return json(id ? await store.get(kind, id) : await store.list(kind, page()));
4840
5137
  }
4841
- if (resource === "providers" && id2 && parts[3] === "models" && parts.length === 4) {
4842
- const catalog = await store.get("catalogs", id2);
5138
+ if (resource === "providers" && id && parts[3] === "models" && parts.length === 4) {
5139
+ const catalog = await store.get("catalogs", id);
4843
5140
  const p = page();
4844
5141
  const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
4845
- 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 });
4846
5143
  }
4847
5144
  throw new Fault(404, "not_found", "Route was not found.");
4848
5145
  }
@@ -4861,7 +5158,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4861
5158
  throw new Fault(400, "invalid_json", "Request must contain valid JSON under 1 MiB.");
4862
5159
  }
4863
5160
  }
4864
- const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
5161
+ const fingerprint = hash(JSON.stringify([request.method, route, body, request.headers.get("if-match")])).toString("hex");
4865
5162
  const version = () => {
4866
5163
  const v = request.headers.get("if-match");
4867
5164
  if (!v || !/^[1-9]\d*$/.test(v))
@@ -4870,49 +5167,73 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4870
5167
  };
4871
5168
  const replay = await store.replay(key, fingerprint);
4872
5169
  if (replay.found)
4873
- return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
5170
+ return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
4874
5171
  let refreshed;
4875
- if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
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") {
4876
5175
  parse(z4.object({}).strict(), body);
4877
- const provider = await store.get("providers", id2);
5176
+ const provider = await store.get("providers", id);
4878
5177
  refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
4879
5178
  }
4880
5179
  const result = await store.mutate(key, fingerprint, async (db) => {
4881
5180
  if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
4882
- if (request.method === "DELETE" && id2)
4883
- return store.remove(resource, id2, version(), db);
4884
- if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
5181
+ if (request.method === "DELETE" && id)
5182
+ return store.remove(resource, id, version(), db);
5183
+ if (request.method === "POST" && !id || request.method === "PUT" && id) {
4885
5184
  const value = resource === "providers" ? parse(providerInputSchema, body) : parse(profileInputSchema, body);
4886
- if (id2 && value.id !== id2)
5185
+ if (id && value.id !== id)
4887
5186
  throw new Fault(400, "id_mismatch", "Path and body IDs must match.");
4888
5187
  if (resource === "profiles") {
4889
5188
  const profile = value;
4890
5189
  const provider = await store.get("providers", profile.providerId, db);
4891
5190
  validateHarnessProvider(profile.harness, provider);
4892
5191
  }
4893
- const saved = await store.put(resource, value, id2 ? version() : undefined, db);
4894
- if (resource === "providers" && id2)
4895
- await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
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]);
4896
5195
  return saved;
4897
5196
  }
4898
5197
  }
4899
- if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
5198
+ if (resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
4900
5199
  if (store.engine === "postgresql")
4901
- await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id2]);
4902
- const provider = await store.get("providers", id2, db);
5200
+ await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id]);
5201
+ const provider = await store.get("providers", id, db);
4903
5202
  if (!refreshed || provider.version !== refreshed.provider.version)
4904
5203
  throw new Fault(409, "provider_changed", "Provider changed during discovery; refresh again.");
4905
5204
  const catalog = refreshed.catalog;
4906
5205
  let old;
4907
5206
  try {
4908
- old = await store.get("catalogs", id2, db);
5207
+ old = await store.get("catalogs", id, db);
4909
5208
  } catch (e) {
4910
5209
  if (!(e instanceof Fault && e.status === 404))
4911
5210
  throw e;
4912
5211
  }
4913
- return store.put("catalogs", { id: id2, ...catalog }, old?.version, db);
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 };
5214
+ }
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 };
4914
5235
  }
4915
- if (resource === "launch-plans" && !id2 && request.method === "POST") {
5236
+ if (resource === "launch-plans" && !id && request.method === "POST") {
4916
5237
  const { profileId } = parse(z4.object({ profileId: idSchema }).strict(), body);
4917
5238
  const profile = await store.get("profiles", profileId, db);
4918
5239
  const provider = await store.get("providers", profile.providerId, db);
@@ -4925,6 +5246,9 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4925
5246
  throw new Fault(422, "catalog_missing", "Refresh the provider catalog before launching.");
4926
5247
  throw e;
4927
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.");
4928
5252
  const selected = catalog.models.find((m) => m.id === profile.model);
4929
5253
  if (!selected)
4930
5254
  throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
@@ -4942,7 +5266,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4942
5266
  warnings.push("Catalog snapshot is older than five minutes; refresh before launching.");
4943
5267
  return { profile, provider, catalog, warnings, planToken: snapshot(profile, provider, catalog) };
4944
5268
  }
4945
- if (resource === "runs" && !id2 && request.method === "POST") {
5269
+ if (resource === "runs" && !id && request.method === "POST") {
4946
5270
  if (body?.modelPolicyVersion !== 1)
4947
5271
  throw new Fault(409, "launcher_upgrade_required", "This API requires a launcher with automatic model policy version 1; upgrade the Switcher CLI/SDK.");
4948
5272
  const input = parse(runInputSchema, body);
@@ -4967,16 +5291,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4967
5291
  compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
4968
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);
4969
5293
  }
4970
- if (resource === "runs" && id2 && request.method === "PATCH" && parts.length === 3) {
5294
+ if (resource === "runs" && id && request.method === "PATCH" && parts.length === 3) {
4971
5295
  const input = parse(runUpdateSchema, body);
4972
- const run = await store.get("runs", id2, db);
5296
+ const run = await store.get("runs", id, db);
4973
5297
  if (run.status !== "running")
4974
5298
  throw new Fault(409, "run_finished", "Run has already finished.");
4975
5299
  return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
4976
5300
  }
4977
5301
  throw new Fault(404, "not_found", "Route was not found.");
4978
5302
  });
4979
- return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
5303
+ return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
4980
5304
  } catch (error) {
4981
5305
  const safe = error instanceof Fault ? error : new Fault(500, "internal_error", "Request failed.");
4982
5306
  return json({ error: { code: safe.code, message: safe.message, requestId } }, safe.status);
@@ -4985,21 +5309,35 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4985
5309
  }
4986
5310
 
4987
5311
  // src/server.ts
5312
+ import { ApiKeyStore } from "@hasna/contracts/auth";
4988
5313
  async function startServer(options) {
4989
5314
  const port = options.port ?? 0;
4990
5315
  if (!Number.isInteger(port) || port < 0 || port > 65535)
4991
5316
  throw new Fault(400, "invalid_port", "Port must be an integer between 0 and 65535.");
4992
- if (options.apiKey.length < 24 || /[\r\n]/.test(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)))
4993
5320
  throw new Fault(500, "auth_config", "Use a random operator token of at least 24 characters.");
4994
- const store = await Store.open({ databaseUrl: options.databaseUrl, sqlitePath: options.sqlitePath });
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 });
4995
5326
  let server;
4996
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
+ })();
4997
5335
  server = Bun.serve({
4998
5336
  hostname: options.hostname ?? "127.0.0.1",
4999
5337
  port,
5000
5338
  maxRequestBodySize: 1024 * 1024,
5001
5339
  idleTimeout: 60,
5002
- fetch: createHandler(store, options.apiKey, options.providerEnv, options.resolveCredential)
5340
+ fetch: createHandler(store, authentication, options.providerEnv, options.resolveCredential)
5003
5341
  });
5004
5342
  await store.ready();
5005
5343
  } catch (error) {
@@ -5026,7 +5364,7 @@ async function startServer(options) {
5026
5364
 
5027
5365
  // src/serve.ts
5028
5366
  async function main(args = process.argv.slice(2)) {
5029
- const { values } = parseArgs({ args, options: {
5367
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
5030
5368
  host: { type: "string" },
5031
5369
  port: { type: "string" },
5032
5370
  "data-dir": { type: "string" },
@@ -5040,24 +5378,42 @@ async function main(args = process.argv.slice(2)) {
5040
5378
  return;
5041
5379
  }
5042
5380
  if (values.help) {
5043
- 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
5044
5382
  --host HOST (127.0.0.1) --port PORT (8080; 0 allocates a port) --json --version
5045
- Requires HASNA_SWITCHER_API_KEY (24+ characters). Provider credentials: SWITCHER_PROVIDER_* environment references.`);
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.`);
5046
5385
  return;
5047
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.");
5048
5389
  const port = Number(values.port ?? process.env.PORT ?? 8080);
5049
5390
  if (!Number.isInteger(port) || port < 0 || port > 65535)
5050
5391
  throw new Fault(400, "invalid_port", "Port must be an integer between 0 and 65535.");
5051
- const apiKey = process.env.HASNA_SWITCHER_API_KEY ?? "";
5052
- if (apiKey.length < 24)
5053
- throw new Fault(500, "auth_config", "Set HASNA_SWITCHER_API_KEY to a random token of at least 24 characters.");
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;
5054
5395
  if (values.sqlite && values["data-dir"])
5055
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
+ }
5056
5411
  const server = await startServer({
5057
- apiKey,
5412
+ ...apiKey ? { apiKey } : {},
5413
+ ...signingSecret ? { signingSecret } : {},
5058
5414
  hostname: values.host ?? "127.0.0.1",
5059
5415
  port,
5060
- databaseUrl: process.env.HASNA_SWITCHER_DATABASE_URL,
5416
+ databaseUrl,
5061
5417
  sqlitePath: values.sqlite ?? (values["data-dir"] ? join(values["data-dir"], "switcher.db") : process.env.HASNA_SWITCHER_SQLITE_PATH)
5062
5418
  });
5063
5419
  console.log(JSON.stringify({ event: "listening", version: VERSION, url: server.url, storage: server.storage }));