@hasna/switcher 0.2.2 → 0.2.4

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.2";
71
+ var VERSION = "0.2.4";
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,7 +256,10 @@ class Store {
251
256
  await chmod(file, 384);
252
257
  }
253
258
  const store = new Store(sql, engine);
254
- await store.migrate();
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(() => {});
@@ -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 > 1))
281
+ if (versions.some((v) => v.version > 2))
274
282
  throw new Error("Newer database schema");
275
- if (versions.length)
276
- return;
277
- await tx.unsafe("CREATE TABLE switcher_providers (id TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
278
- 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)");
279
- 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)");
280
- 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)");
281
- await tx.unsafe("CREATE TABLE switcher_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL)");
282
- 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
+ }
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 createHash2, timingSafeEqual } from "crypto";
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
@@ -681,7 +733,7 @@ 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
738
  var id = (v, label2) => {
687
739
  if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
@@ -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: createHash("sha256").update(stable(result)).digest("hex") };
798
+ return { ...result, digest: createHash2("sha256").update(stable(result)).digest("hex") };
747
799
  }
748
800
 
749
801
  // src/presets.ts
@@ -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.2",
902
+ version: "0.2.4",
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
- ready: {
4815
- 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
+ ]
4816
4992
  },
4817
4993
  reason: {
4818
4994
  type: "string"
4819
4995
  }
4820
4996
  },
4821
4997
  required: [
4822
- "ready"
4998
+ "status",
4999
+ "version",
5000
+ "backend"
4823
5001
  ],
4824
5002
  additionalProperties: false
4825
5003
  },
@@ -4887,12 +5065,27 @@ var openapi_default = {
4887
5065
  };
4888
5066
 
4889
5067
  // src/service.ts
4890
- var snapshot = (profile, provider, catalog) => createHash2("sha256").update(JSON.stringify([profile, provider, { models: catalog.models, source: catalog.source }])).digest("hex");
4891
- var hash = (s) => createHash2("sha256").update(s).digest();
4892
- function createHandler(store, apiKey, providerEnv = process.env, resolveCredential) {
4893
- 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)))
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(`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
+ });
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" } });
@@ -4906,15 +5099,23 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4906
5099
  if (request.method === "GET" && route2 === "/ready") {
4907
5100
  try {
4908
5101
  await store.ready();
4909
- return json({ ready: true });
5102
+ return json({ status: "ready", version: VERSION, backend: store.engine });
4910
5103
  } catch {
4911
- return json({ ready: false, reason: "Storage is unavailable." }, 503);
5104
+ return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
4912
5105
  }
4913
5106
  }
4914
- if (!timingSafeEqual(expected, hash(request.headers.get("authorization") ?? "")))
4915
- throw new Fault(401, "unauthorized", "A valid API bearer token is required.");
4916
5107
  if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
4917
5108
  return json(openapi_default);
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: route2, requiredScopes });
5116
+ if (!decision.ok)
5117
+ throw new Fault(decision.status, `auth_${decision.reason}`, decision.message);
5118
+ }
4918
5119
  const parts = route2.split("/").filter(Boolean);
4919
5120
  if (parts[0] !== "v1")
4920
5121
  throw new Fault(404, "not_found", "Route was not found.");
@@ -4938,7 +5139,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4938
5139
  const catalog = await store.get("catalogs", id2);
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
  }
@@ -4968,6 +5169,8 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
4968
5169
  if (replay.found)
4969
5170
  return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
4970
5171
  let refreshed;
5172
+ if (!expected && resource === "providers" && id2 && 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.");
4971
5174
  if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
4972
5175
  parse(z4.object({}).strict(), body);
4973
5176
  const provider = await store.get("providers", id2);
@@ -5006,7 +5209,29 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5006
5209
  if (!(e instanceof Fault && e.status === 404))
5007
5210
  throw e;
5008
5211
  }
5009
- return store.put("catalogs", { id: id2, ...catalog }, old?.version, db);
5212
+ const saved = await store.put("catalogs", { id: id2, ...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" && id2 && 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", [id2]);
5218
+ const provider = await store.get("providers", id2, 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", id2, db);
5229
+ } catch (error) {
5230
+ if (!(error instanceof Fault && error.status === 404))
5231
+ throw error;
5232
+ }
5233
+ const saved = await store.put("catalogs", { id: id2, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
5234
+ return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
5010
5235
  }
5011
5236
  if (resource === "launch-plans" && !id2 && request.method === "POST") {
5012
5237
  const { profileId } = parse(z4.object({ profileId: idSchema }).strict(), body);
@@ -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.");
@@ -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.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)))
5089
5320
  throw new Fault(500, "auth_config", "Use a random operator token of at least 24 characters.");
5090
- 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 });
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, options.apiKey, options.providerEnv, options.resolveCredential)
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
- 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.`);
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
- if (apiKey.length < 24)
5149
- 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;
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: process.env.HASNA_SWITCHER_DATABASE_URL,
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 }));
package/dist/server.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { CatalogCredentialResolver } from "./catalog";
2
2
  export type ServerOptions = {
3
- apiKey: string;
3
+ apiKey?: string;
4
+ signingSecret?: string;
4
5
  databaseUrl?: string;
5
6
  sqlitePath?: string;
6
7
  hostname?: string;
package/dist/service.d.ts CHANGED
@@ -1,3 +1,10 @@
1
+ import { type ApiKeyStatus, type AuthAuditHook } from "@hasna/contracts/auth";
1
2
  import { Store } from "./store";
2
3
  import { type CatalogCredentialResolver } from "./catalog";
3
- export declare function createHandler(store: Store, apiKey: string, providerEnv?: Record<string, string | undefined>, resolveCredential?: CatalogCredentialResolver): (request: Request) => Promise<Response>;
4
+ export type ServiceAuthentication = string | {
5
+ kind: "signed-api-key";
6
+ signingSecret: string | Buffer;
7
+ keyStatus: (kid: string) => ApiKeyStatus | Promise<ApiKeyStatus>;
8
+ audit?: AuthAuditHook;
9
+ };
10
+ export declare function createHandler(store: Store, authentication: ServiceAuthentication, providerEnv?: Record<string, string | undefined>, resolveCredential?: CatalogCredentialResolver): (request: Request) => Promise<Response>;
package/dist/store.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { SQL } from "bun";
2
+ import { type AuthQueryClient } from "@hasna/contracts/auth";
2
3
  type Connection = Pick<SQL, "unsafe">;
3
4
  export type Resource = "providers" | "profiles" | "runs" | "catalogs";
4
5
  export type RecordValue = {
@@ -16,9 +17,12 @@ export declare class Store {
16
17
  static open(config: {
17
18
  databaseUrl?: string;
18
19
  sqlitePath?: string;
20
+ migrate?: boolean;
19
21
  }): Promise<Store>;
20
22
  private migrate;
23
+ private verifySchema;
21
24
  ready(): Promise<void>;
25
+ authQueryClient(): AuthQueryClient;
22
26
  close(): Promise<void>;
23
27
  get<T>(kind: Resource, id: string, db?: Connection): Promise<T>;
24
28
  private read;