@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/mcp/index.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// src/mcp.ts
|
|
5
5
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
6
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
7
|
-
import { z as
|
|
7
|
+
import { z as z7 } from "zod";
|
|
8
8
|
|
|
9
9
|
// src/runtime.ts
|
|
10
10
|
import { randomBytes } from "crypto";
|
|
@@ -69,7 +69,7 @@ function canonicalPolicyJSON(value) {
|
|
|
69
69
|
}
|
|
70
70
|
|
|
71
71
|
// src/domain.ts
|
|
72
|
-
var VERSION = "0.2.
|
|
72
|
+
var VERSION = "0.2.3";
|
|
73
73
|
var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
74
74
|
var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
75
75
|
var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -172,6 +172,7 @@ var runUpdateSchema = z3.object({
|
|
|
172
172
|
routingEvents: routingEventsSchema.optional(),
|
|
173
173
|
routingEventsDropped: z3.number().int().min(0).max(1e6).optional()
|
|
174
174
|
}).strict();
|
|
175
|
+
var catalogSchema = z3.object({ models: z3.array(modelSchema).max(1e4), refreshedAt: z3.string().datetime(), source: z3.enum(["remote", "manual"]) }).strict();
|
|
175
176
|
|
|
176
177
|
class Fault extends Error {
|
|
177
178
|
status;
|
|
@@ -182,6 +183,14 @@ class Fault extends Error {
|
|
|
182
183
|
this.code = code;
|
|
183
184
|
}
|
|
184
185
|
}
|
|
186
|
+
|
|
187
|
+
class CommandInterrupted extends Fault {
|
|
188
|
+
exitCode;
|
|
189
|
+
constructor(exitCode, message) {
|
|
190
|
+
super(499, "interrupted", message);
|
|
191
|
+
this.exitCode = exitCode;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
185
194
|
function parse(schema, value) {
|
|
186
195
|
const result = schema.safeParse(value);
|
|
187
196
|
if (!result.success)
|
|
@@ -348,6 +357,18 @@ function getProviderPreset(id) {
|
|
|
348
357
|
throw new Fault(404, "preset_not_found", "Unknown provider preset. Use switcher providers presets to list available presets.");
|
|
349
358
|
return structuredClone(entry);
|
|
350
359
|
}
|
|
360
|
+
function providerCredential(provider, env = process.env) {
|
|
361
|
+
if (!provider.credentialEnv)
|
|
362
|
+
return;
|
|
363
|
+
let value = env[provider.credentialEnv];
|
|
364
|
+
if (!value) {
|
|
365
|
+
const preset = providerPresets.find((p) => p.credentialEnv === provider.credentialEnv && p.protocols.some((route) => route.protocol === provider.protocol && (route.baseUrl ? new URL(route.baseUrl).origin === new URL(provider.baseUrl).origin : p.id === "azure-openai")));
|
|
366
|
+
value = preset?.credentialAliases.map((name) => env[name]).find(Boolean);
|
|
367
|
+
}
|
|
368
|
+
if (value && /[\r\n]/.test(value))
|
|
369
|
+
throw new Fault(422, "credential_invalid", "Provider credential contains invalid header characters.");
|
|
370
|
+
return value;
|
|
371
|
+
}
|
|
351
372
|
// src/desktop-apps.ts
|
|
352
373
|
import { execFile } from "child_process";
|
|
353
374
|
import { access, stat } from "fs/promises";
|
|
@@ -555,6 +576,9 @@ class SwitcherClient {
|
|
|
555
576
|
refreshModels(id, idempotencyKey) {
|
|
556
577
|
return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey });
|
|
557
578
|
}
|
|
579
|
+
saveCatalog(id, providerVersion, catalog, idempotencyKey) {
|
|
580
|
+
return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey });
|
|
581
|
+
}
|
|
558
582
|
listModels(id, options = {}) {
|
|
559
583
|
return this.request("GET", `/v1/providers/${encodeURIComponent(id)}/models?${this.query(options)}`);
|
|
560
584
|
}
|
|
@@ -597,6 +621,10 @@ function clientFromEnv(env = process.env, options = {}) {
|
|
|
597
621
|
var {SQL } = globalThis.Bun;
|
|
598
622
|
import { chmod, mkdir } from "fs/promises";
|
|
599
623
|
import { dirname, resolve } from "path";
|
|
624
|
+
import { createHash } from "crypto";
|
|
625
|
+
import { apiKeyMigrations } from "@hasna/contracts/auth";
|
|
626
|
+
var authMigrationPlan = () => apiKeyMigrations().map((migration) => ({ ...migration, checksum: createHash("sha256").update(migration.sql).digest("hex") }));
|
|
627
|
+
|
|
600
628
|
class Store {
|
|
601
629
|
tail = Promise.resolve();
|
|
602
630
|
async exclusive(action) {
|
|
@@ -634,13 +662,16 @@ class Store {
|
|
|
634
662
|
await chmod(file, 384);
|
|
635
663
|
}
|
|
636
664
|
const store = new Store(sql, engine);
|
|
637
|
-
|
|
665
|
+
if (config.migrate === false)
|
|
666
|
+
await store.verifySchema();
|
|
667
|
+
else
|
|
668
|
+
await store.migrate();
|
|
638
669
|
return store;
|
|
639
670
|
} catch (error) {
|
|
640
671
|
await sql?.close().catch(() => {});
|
|
641
672
|
const code = error?.code;
|
|
642
673
|
if (engine === "sqlite" && ["SQLITE_BUSY", "SQLITE_BUSY_SNAPSHOT", "SQLITE_LOCKED"].includes(code ?? "") && Date.now() < deadline) {
|
|
643
|
-
await new Promise((
|
|
674
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(200, 20 * (attempt + 1))));
|
|
644
675
|
continue;
|
|
645
676
|
}
|
|
646
677
|
throw new Fault(500, "storage_unavailable", "Database startup failed; check configuration, permissions and other database users.");
|
|
@@ -653,23 +684,66 @@ class Store {
|
|
|
653
684
|
await tx.unsafe("SELECT pg_advisory_xact_lock(782034215)");
|
|
654
685
|
await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_migrations (version INTEGER PRIMARY KEY)");
|
|
655
686
|
const versions = await tx.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
|
|
656
|
-
if (versions.some((v) => v.version >
|
|
687
|
+
if (versions.some((v) => v.version > 2))
|
|
657
688
|
throw new Error("Newer database schema");
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
689
|
+
const applied = new Set(versions.map((v) => Number(v.version)));
|
|
690
|
+
if (!applied.has(1)) {
|
|
691
|
+
await tx.unsafe("CREATE TABLE switcher_providers (id TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
|
|
692
|
+
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)");
|
|
693
|
+
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)");
|
|
694
|
+
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)");
|
|
695
|
+
await tx.unsafe("CREATE TABLE switcher_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL)");
|
|
696
|
+
await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (1)");
|
|
697
|
+
}
|
|
698
|
+
if (this.engine === "postgresql") {
|
|
699
|
+
await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_auth_migrations (id TEXT PRIMARY KEY, checksum TEXT NOT NULL)");
|
|
700
|
+
const migrations = authMigrationPlan();
|
|
701
|
+
const authRows = await tx.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
|
|
702
|
+
const known = new Map(migrations.map((migration) => [migration.id, migration.checksum]));
|
|
703
|
+
for (const row of authRows) {
|
|
704
|
+
if (known.get(String(row.id)) !== String(row.checksum))
|
|
705
|
+
throw new Error("Unknown or changed API-key migration");
|
|
706
|
+
}
|
|
707
|
+
const completed = new Set(authRows.map((row) => String(row.id)));
|
|
708
|
+
for (const migration of migrations)
|
|
709
|
+
if (!completed.has(migration.id)) {
|
|
710
|
+
await tx.unsafe(migration.sql);
|
|
711
|
+
await tx.unsafe("INSERT INTO switcher_auth_migrations(id,checksum) VALUES ($1,$2)", [migration.id, migration.checksum]);
|
|
712
|
+
}
|
|
713
|
+
if (!applied.has(2))
|
|
714
|
+
await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (2)");
|
|
715
|
+
}
|
|
666
716
|
});
|
|
667
717
|
}
|
|
718
|
+
async verifySchema() {
|
|
719
|
+
const versions = await this.sql.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
|
|
720
|
+
const applied = new Set(versions.map((row) => Number(row.version)));
|
|
721
|
+
if (!applied.has(1) || this.engine === "postgresql" && !applied.has(2) || versions.some((row) => Number(row.version) > 2))
|
|
722
|
+
throw new Error("Unsupported database schema");
|
|
723
|
+
if (this.engine === "postgresql") {
|
|
724
|
+
const expected = authMigrationPlan(), rows = await this.sql.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
|
|
725
|
+
const actual = new Map(rows.map((row) => [String(row.id), String(row.checksum)]));
|
|
726
|
+
if (actual.size !== expected.length || expected.some((migration) => actual.get(migration.id) !== migration.checksum))
|
|
727
|
+
throw new Error("Unsupported API-key schema");
|
|
728
|
+
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");
|
|
729
|
+
}
|
|
730
|
+
}
|
|
668
731
|
async ready() {
|
|
669
732
|
await this.exclusive(async () => {
|
|
670
733
|
await this.sql.unsafe("SELECT 1");
|
|
671
734
|
});
|
|
672
735
|
}
|
|
736
|
+
authQueryClient() {
|
|
737
|
+
if (this.engine !== "postgresql")
|
|
738
|
+
throw new Fault(500, "auth_config", "Signed API keys require the PostgreSQL backend.");
|
|
739
|
+
return {
|
|
740
|
+
many: async (sql, params = []) => await this.sql.unsafe(sql, [...params]),
|
|
741
|
+
get: async (sql, params = []) => (await this.sql.unsafe(sql, [...params]))[0] ?? null,
|
|
742
|
+
execute: async (sql, params = []) => {
|
|
743
|
+
await this.sql.unsafe(sql, [...params]);
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
}
|
|
673
747
|
async close() {
|
|
674
748
|
await this.tail;
|
|
675
749
|
await this.sql.close();
|
|
@@ -755,7 +829,8 @@ class Store {
|
|
|
755
829
|
}
|
|
756
830
|
|
|
757
831
|
// src/service.ts
|
|
758
|
-
import { createHash as
|
|
832
|
+
import { createHash as createHash3, timingSafeEqual } from "crypto";
|
|
833
|
+
import { verifyApiKey } from "@hasna/contracts/auth";
|
|
759
834
|
import { z as z4 } from "zod";
|
|
760
835
|
|
|
761
836
|
// src/auth.ts
|
|
@@ -803,7 +878,7 @@ async function waitForCatalogRetry(delayMs, deadline) {
|
|
|
803
878
|
if (Date.now() + delayMs > deadline)
|
|
804
879
|
throw catalogDeadlineFault();
|
|
805
880
|
if (delayMs > 0)
|
|
806
|
-
await new Promise((
|
|
881
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
807
882
|
}
|
|
808
883
|
async function fetchCatalogPage(url, headers, deadline) {
|
|
809
884
|
for (let retry = 0;; retry++) {
|
|
@@ -911,8 +986,8 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
911
986
|
candidate.outputModalities = capabilities.completion_chat ? ["text"] : [];
|
|
912
987
|
}
|
|
913
988
|
if (provider.catalogFormat === "together") {
|
|
914
|
-
const
|
|
915
|
-
candidate.outputModalities =
|
|
989
|
+
const modalities = { chat: ["text"], language: ["text"], code: ["text"], image: ["image"], audio: ["audio"], video: ["video"], embedding: ["embedding"], rerank: ["rerank"], moderation: ["classification"] };
|
|
990
|
+
candidate.outputModalities = modalities[row.type];
|
|
916
991
|
}
|
|
917
992
|
if (provider.catalogFormat === "fireworks") {
|
|
918
993
|
if (row.supportsImageInput === true)
|
|
@@ -1030,11 +1105,11 @@ async function discover(provider, env = process.env, resolveCredential) {
|
|
|
1030
1105
|
}
|
|
1031
1106
|
|
|
1032
1107
|
// src/model-policy.ts
|
|
1033
|
-
import { createHash } from "crypto";
|
|
1108
|
+
import { createHash as createHash2 } from "crypto";
|
|
1034
1109
|
var roles = ["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"];
|
|
1035
|
-
var id = (v,
|
|
1110
|
+
var id = (v, label) => {
|
|
1036
1111
|
if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
|
|
1037
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
1112
|
+
throw new Fault(400, "invalid_model_policy", `${label} is invalid.`);
|
|
1038
1113
|
return v;
|
|
1039
1114
|
};
|
|
1040
1115
|
var uniq = (xs) => [...new Set(xs)];
|
|
@@ -1092,17 +1167,20 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
1092
1167
|
if (Object.values(aliases).some((value) => !allowedModels.includes(value)))
|
|
1093
1168
|
throw new Fault(422, "model_not_allowed", "A model alias target must be explicitly allowed by the launch policy.");
|
|
1094
1169
|
const result = { version: 1, model: selected, roles: compiledRoles, allowedModels, aliases, fallbacks };
|
|
1095
|
-
return { ...result, digest:
|
|
1170
|
+
return { ...result, digest: createHash2("sha256").update(stable(result)).digest("hex") };
|
|
1096
1171
|
}
|
|
1097
1172
|
// openapi.json
|
|
1098
1173
|
var openapi_default = {
|
|
1099
1174
|
openapi: "3.0.3",
|
|
1100
1175
|
info: {
|
|
1101
1176
|
title: "Switcher API",
|
|
1102
|
-
version: "0.2.
|
|
1177
|
+
version: "0.2.3",
|
|
1103
1178
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
1104
1179
|
},
|
|
1105
1180
|
security: [
|
|
1181
|
+
{
|
|
1182
|
+
apiKeyAuth: []
|
|
1183
|
+
},
|
|
1106
1184
|
{
|
|
1107
1185
|
bearerAuth: []
|
|
1108
1186
|
}
|
|
@@ -1856,6 +1934,73 @@ var openapi_default = {
|
|
|
1856
1934
|
}
|
|
1857
1935
|
}
|
|
1858
1936
|
},
|
|
1937
|
+
responses: {
|
|
1938
|
+
"200": {
|
|
1939
|
+
description: "Success",
|
|
1940
|
+
content: {
|
|
1941
|
+
"application/json": {
|
|
1942
|
+
schema: {
|
|
1943
|
+
$ref: "#/components/schemas/Catalog"
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
},
|
|
1948
|
+
default: {
|
|
1949
|
+
description: "Structured error",
|
|
1950
|
+
content: {
|
|
1951
|
+
"application/json": {
|
|
1952
|
+
schema: {
|
|
1953
|
+
$ref: "#/components/schemas/Error"
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
},
|
|
1959
|
+
description: "Self-hosted/local server refresh. Hosted clients discover locally and commit catalog metadata through the version-checked catalog endpoint."
|
|
1960
|
+
}
|
|
1961
|
+
},
|
|
1962
|
+
"/v1/providers/{id}/catalog": {
|
|
1963
|
+
put: {
|
|
1964
|
+
operationId: "saveCatalog",
|
|
1965
|
+
parameters: [
|
|
1966
|
+
{
|
|
1967
|
+
name: "id",
|
|
1968
|
+
in: "path",
|
|
1969
|
+
required: true,
|
|
1970
|
+
schema: {
|
|
1971
|
+
type: "string"
|
|
1972
|
+
}
|
|
1973
|
+
},
|
|
1974
|
+
{
|
|
1975
|
+
name: "Idempotency-Key",
|
|
1976
|
+
in: "header",
|
|
1977
|
+
required: true,
|
|
1978
|
+
schema: {
|
|
1979
|
+
type: "string",
|
|
1980
|
+
minLength: 8,
|
|
1981
|
+
maxLength: 128
|
|
1982
|
+
}
|
|
1983
|
+
},
|
|
1984
|
+
{
|
|
1985
|
+
name: "If-Match",
|
|
1986
|
+
in: "header",
|
|
1987
|
+
required: true,
|
|
1988
|
+
schema: {
|
|
1989
|
+
type: "integer",
|
|
1990
|
+
minimum: 1
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
],
|
|
1994
|
+
requestBody: {
|
|
1995
|
+
required: true,
|
|
1996
|
+
content: {
|
|
1997
|
+
"application/json": {
|
|
1998
|
+
schema: {
|
|
1999
|
+
$ref: "#/components/schemas/Catalog"
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
},
|
|
1859
2004
|
responses: {
|
|
1860
2005
|
"200": {
|
|
1861
2006
|
description: "Success",
|
|
@@ -2243,6 +2388,36 @@ var openapi_default = {
|
|
|
2243
2388
|
}
|
|
2244
2389
|
},
|
|
2245
2390
|
"/v1/openapi.json": {
|
|
2391
|
+
get: {
|
|
2392
|
+
operationId: "openApiV1",
|
|
2393
|
+
parameters: [],
|
|
2394
|
+
responses: {
|
|
2395
|
+
"200": {
|
|
2396
|
+
description: "Success",
|
|
2397
|
+
content: {
|
|
2398
|
+
"application/json": {
|
|
2399
|
+
schema: {
|
|
2400
|
+
type: "object",
|
|
2401
|
+
additionalProperties: true
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
},
|
|
2406
|
+
default: {
|
|
2407
|
+
description: "Structured error",
|
|
2408
|
+
content: {
|
|
2409
|
+
"application/json": {
|
|
2410
|
+
schema: {
|
|
2411
|
+
$ref: "#/components/schemas/Error"
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
},
|
|
2417
|
+
security: []
|
|
2418
|
+
}
|
|
2419
|
+
},
|
|
2420
|
+
"/openapi.json": {
|
|
2246
2421
|
get: {
|
|
2247
2422
|
operationId: "openApi",
|
|
2248
2423
|
parameters: [],
|
|
@@ -2268,12 +2443,18 @@ var openapi_default = {
|
|
|
2268
2443
|
}
|
|
2269
2444
|
}
|
|
2270
2445
|
}
|
|
2271
|
-
}
|
|
2446
|
+
},
|
|
2447
|
+
security: []
|
|
2272
2448
|
}
|
|
2273
2449
|
}
|
|
2274
2450
|
},
|
|
2275
2451
|
components: {
|
|
2276
2452
|
securitySchemes: {
|
|
2453
|
+
apiKeyAuth: {
|
|
2454
|
+
type: "apiKey",
|
|
2455
|
+
in: "header",
|
|
2456
|
+
name: "x-api-key"
|
|
2457
|
+
},
|
|
2277
2458
|
bearerAuth: {
|
|
2278
2459
|
type: "http",
|
|
2279
2460
|
scheme: "bearer"
|
|
@@ -3846,10 +4027,12 @@ var openapi_default = {
|
|
|
3846
4027
|
"name"
|
|
3847
4028
|
],
|
|
3848
4029
|
additionalProperties: false
|
|
3849
|
-
}
|
|
4030
|
+
},
|
|
4031
|
+
maxItems: 1e4
|
|
3850
4032
|
},
|
|
3851
4033
|
refreshedAt: {
|
|
3852
|
-
type: "string"
|
|
4034
|
+
type: "string",
|
|
4035
|
+
format: "date-time"
|
|
3853
4036
|
},
|
|
3854
4037
|
source: {
|
|
3855
4038
|
type: "string",
|
|
@@ -4434,10 +4617,12 @@ var openapi_default = {
|
|
|
4434
4617
|
"name"
|
|
4435
4618
|
],
|
|
4436
4619
|
additionalProperties: false
|
|
4437
|
-
}
|
|
4620
|
+
},
|
|
4621
|
+
maxItems: 1e4
|
|
4438
4622
|
},
|
|
4439
4623
|
refreshedAt: {
|
|
4440
|
-
type: "string"
|
|
4624
|
+
type: "string",
|
|
4625
|
+
format: "date-time"
|
|
4441
4626
|
},
|
|
4442
4627
|
source: {
|
|
4443
4628
|
type: "string",
|
|
@@ -5063,15 +5248,31 @@ var openapi_default = {
|
|
|
5063
5248
|
Ready: {
|
|
5064
5249
|
type: "object",
|
|
5065
5250
|
properties: {
|
|
5066
|
-
|
|
5067
|
-
type: "
|
|
5251
|
+
status: {
|
|
5252
|
+
type: "string",
|
|
5253
|
+
enum: [
|
|
5254
|
+
"ready",
|
|
5255
|
+
"unavailable"
|
|
5256
|
+
]
|
|
5257
|
+
},
|
|
5258
|
+
version: {
|
|
5259
|
+
type: "string"
|
|
5260
|
+
},
|
|
5261
|
+
backend: {
|
|
5262
|
+
type: "string",
|
|
5263
|
+
enum: [
|
|
5264
|
+
"sqlite",
|
|
5265
|
+
"postgresql"
|
|
5266
|
+
]
|
|
5068
5267
|
},
|
|
5069
5268
|
reason: {
|
|
5070
5269
|
type: "string"
|
|
5071
5270
|
}
|
|
5072
5271
|
},
|
|
5073
5272
|
required: [
|
|
5074
|
-
"
|
|
5273
|
+
"status",
|
|
5274
|
+
"version",
|
|
5275
|
+
"backend"
|
|
5075
5276
|
],
|
|
5076
5277
|
additionalProperties: false
|
|
5077
5278
|
},
|
|
@@ -5139,41 +5340,64 @@ var openapi_default = {
|
|
|
5139
5340
|
};
|
|
5140
5341
|
|
|
5141
5342
|
// src/service.ts
|
|
5142
|
-
var
|
|
5143
|
-
var
|
|
5144
|
-
|
|
5145
|
-
|
|
5343
|
+
var providerCatalogFingerprint = (provider) => createHash3("sha256").update(JSON.stringify(provider)).digest("hex");
|
|
5344
|
+
var snapshot = (profile, provider, catalog) => createHash3("sha256").update(JSON.stringify([profile, provider, { models: catalog.models, source: catalog.source }])).digest("hex");
|
|
5345
|
+
var hash = (s) => createHash3("sha256").update(s).digest();
|
|
5346
|
+
function localApiKey(headers) {
|
|
5347
|
+
const direct = headers.get("x-api-key");
|
|
5348
|
+
if (direct)
|
|
5349
|
+
return direct;
|
|
5350
|
+
const authorization = headers.get("authorization") ?? "";
|
|
5351
|
+
return authorization.startsWith("Bearer ") ? authorization.slice("Bearer ".length) : "";
|
|
5352
|
+
}
|
|
5353
|
+
function createHandler(store, authentication, providerEnv = process.env, resolveCredential) {
|
|
5354
|
+
const localToken = typeof authentication === "string" ? authentication : undefined;
|
|
5355
|
+
if (localToken !== undefined && (localToken.length < 24 || /[\r\n]/.test(localToken)))
|
|
5146
5356
|
throw new Fault(500, "auth_config", "Set HASNA_SWITCHER_API_KEY to a random token of at least 24 characters.");
|
|
5147
|
-
const expected = hash(
|
|
5357
|
+
const expected = localToken === undefined ? undefined : hash(localToken);
|
|
5358
|
+
const verifier = typeof authentication === "string" ? undefined : verifyApiKey({
|
|
5359
|
+
app: "switcher",
|
|
5360
|
+
signingSecret: authentication.signingSecret,
|
|
5361
|
+
keyStatus: authentication.keyStatus,
|
|
5362
|
+
...authentication.audit ? { audit: authentication.audit } : {}
|
|
5363
|
+
});
|
|
5148
5364
|
return async (request) => {
|
|
5149
5365
|
const requestId = crypto.randomUUID();
|
|
5150
5366
|
const json = (body, status = 200) => Response.json(body, { status, headers: { "x-request-id": requestId, "cache-control": "no-store", "x-content-type-options": "nosniff" } });
|
|
5151
5367
|
try {
|
|
5152
5368
|
const url = new URL(request.url);
|
|
5153
|
-
const
|
|
5154
|
-
if (request.method === "GET" &&
|
|
5369
|
+
const route = url.pathname.replace(/\/$/, "");
|
|
5370
|
+
if (request.method === "GET" && route === "/health")
|
|
5155
5371
|
return json({ status: "ok", version: VERSION, backend: store.engine });
|
|
5156
|
-
if (request.method === "GET" &&
|
|
5372
|
+
if (request.method === "GET" && route === "/version")
|
|
5157
5373
|
return json({ version: VERSION });
|
|
5158
|
-
if (request.method === "GET" &&
|
|
5374
|
+
if (request.method === "GET" && route === "/ready") {
|
|
5159
5375
|
try {
|
|
5160
5376
|
await store.ready();
|
|
5161
|
-
return json({ ready:
|
|
5377
|
+
return json({ status: "ready", version: VERSION, backend: store.engine });
|
|
5162
5378
|
} catch {
|
|
5163
|
-
return json({
|
|
5379
|
+
return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
|
|
5164
5380
|
}
|
|
5165
5381
|
}
|
|
5166
|
-
if (
|
|
5167
|
-
throw new Fault(401, "unauthorized", "A valid API bearer token is required.");
|
|
5168
|
-
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
|
|
5382
|
+
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route))
|
|
5169
5383
|
return json(openapi_default);
|
|
5170
|
-
|
|
5384
|
+
if (expected) {
|
|
5385
|
+
const presented = hash(localApiKey(request.headers));
|
|
5386
|
+
if (!timingSafeEqual(expected, presented))
|
|
5387
|
+
throw new Fault(401, "unauthorized", "A valid API key is required.");
|
|
5388
|
+
} else {
|
|
5389
|
+
const requiredScopes = [request.method === "GET" || request.method === "HEAD" ? "switcher:read" : "switcher:write"];
|
|
5390
|
+
const decision = await verifier.authenticate(request.headers, { method: request.method, path: route, requiredScopes });
|
|
5391
|
+
if (!decision.ok)
|
|
5392
|
+
throw new Fault(decision.status, `auth_${decision.reason}`, decision.message);
|
|
5393
|
+
}
|
|
5394
|
+
const parts = route.split("/").filter(Boolean);
|
|
5171
5395
|
if (parts[0] !== "v1")
|
|
5172
5396
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
5173
5397
|
const resource = parts[1];
|
|
5174
|
-
const
|
|
5175
|
-
if (
|
|
5176
|
-
parse(idSchema,
|
|
5398
|
+
const id = parts[2];
|
|
5399
|
+
if (id)
|
|
5400
|
+
parse(idSchema, id);
|
|
5177
5401
|
const page = () => parse(z4.object({
|
|
5178
5402
|
limit: z4.coerce.number().int().min(1).max(1000).default(100),
|
|
5179
5403
|
offset: z4.coerce.number().int().min(0).max(1e6).default(0),
|
|
@@ -5181,16 +5405,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5181
5405
|
}).strict(), Object.fromEntries(url.searchParams));
|
|
5182
5406
|
if (request.method === "GET") {
|
|
5183
5407
|
if (resource === "provider-presets" && parts.length <= 3)
|
|
5184
|
-
return json(
|
|
5408
|
+
return json(id ? getProviderPreset(id) : { data: providerPresets });
|
|
5185
5409
|
if (["providers", "profiles", "runs"].includes(resource) && parts.length <= 3) {
|
|
5186
5410
|
const kind = resource;
|
|
5187
|
-
return json(
|
|
5411
|
+
return json(id ? await store.get(kind, id) : await store.list(kind, page()));
|
|
5188
5412
|
}
|
|
5189
|
-
if (resource === "providers" &&
|
|
5190
|
-
const catalog = await store.get("catalogs",
|
|
5413
|
+
if (resource === "providers" && id && parts[3] === "models" && parts.length === 4) {
|
|
5414
|
+
const catalog = await store.get("catalogs", id);
|
|
5191
5415
|
const p = page();
|
|
5192
5416
|
const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
|
|
5193
|
-
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 });
|
|
5417
|
+
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 });
|
|
5194
5418
|
}
|
|
5195
5419
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
5196
5420
|
}
|
|
@@ -5209,7 +5433,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5209
5433
|
throw new Fault(400, "invalid_json", "Request must contain valid JSON under 1 MiB.");
|
|
5210
5434
|
}
|
|
5211
5435
|
}
|
|
5212
|
-
const fingerprint = hash(JSON.stringify([request.method,
|
|
5436
|
+
const fingerprint = hash(JSON.stringify([request.method, route, body, request.headers.get("if-match")])).toString("hex");
|
|
5213
5437
|
const version = () => {
|
|
5214
5438
|
const v = request.headers.get("if-match");
|
|
5215
5439
|
if (!v || !/^[1-9]\d*$/.test(v))
|
|
@@ -5218,49 +5442,73 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5218
5442
|
};
|
|
5219
5443
|
const replay = await store.replay(key, fingerprint);
|
|
5220
5444
|
if (replay.found)
|
|
5221
|
-
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
5445
|
+
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
|
|
5222
5446
|
let refreshed;
|
|
5223
|
-
if (resource === "providers" &&
|
|
5447
|
+
if (!expected && resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST")
|
|
5448
|
+
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.");
|
|
5449
|
+
if (resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
5224
5450
|
parse(z4.object({}).strict(), body);
|
|
5225
|
-
const provider = await store.get("providers",
|
|
5451
|
+
const provider = await store.get("providers", id);
|
|
5226
5452
|
refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
|
|
5227
5453
|
}
|
|
5228
5454
|
const result = await store.mutate(key, fingerprint, async (db) => {
|
|
5229
5455
|
if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
|
|
5230
|
-
if (request.method === "DELETE" &&
|
|
5231
|
-
return store.remove(resource,
|
|
5232
|
-
if (request.method === "POST" && !
|
|
5456
|
+
if (request.method === "DELETE" && id)
|
|
5457
|
+
return store.remove(resource, id, version(), db);
|
|
5458
|
+
if (request.method === "POST" && !id || request.method === "PUT" && id) {
|
|
5233
5459
|
const value = resource === "providers" ? parse(providerInputSchema, body) : parse(profileInputSchema, body);
|
|
5234
|
-
if (
|
|
5460
|
+
if (id && value.id !== id)
|
|
5235
5461
|
throw new Fault(400, "id_mismatch", "Path and body IDs must match.");
|
|
5236
5462
|
if (resource === "profiles") {
|
|
5237
5463
|
const profile = value;
|
|
5238
5464
|
const provider = await store.get("providers", profile.providerId, db);
|
|
5239
5465
|
validateHarnessProvider(profile.harness, provider);
|
|
5240
5466
|
}
|
|
5241
|
-
const saved = await store.put(resource, value,
|
|
5242
|
-
if (resource === "providers" &&
|
|
5243
|
-
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [
|
|
5467
|
+
const saved = await store.put(resource, value, id ? version() : undefined, db);
|
|
5468
|
+
if (resource === "providers" && id)
|
|
5469
|
+
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id]);
|
|
5244
5470
|
return saved;
|
|
5245
5471
|
}
|
|
5246
5472
|
}
|
|
5247
|
-
if (resource === "providers" &&
|
|
5473
|
+
if (resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
5248
5474
|
if (store.engine === "postgresql")
|
|
5249
|
-
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [
|
|
5250
|
-
const provider = await store.get("providers",
|
|
5475
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id]);
|
|
5476
|
+
const provider = await store.get("providers", id, db);
|
|
5251
5477
|
if (!refreshed || provider.version !== refreshed.provider.version)
|
|
5252
5478
|
throw new Fault(409, "provider_changed", "Provider changed during discovery; refresh again.");
|
|
5253
5479
|
const catalog = refreshed.catalog;
|
|
5254
5480
|
let old;
|
|
5255
5481
|
try {
|
|
5256
|
-
old = await store.get("catalogs",
|
|
5482
|
+
old = await store.get("catalogs", id, db);
|
|
5257
5483
|
} catch (e) {
|
|
5258
5484
|
if (!(e instanceof Fault && e.status === 404))
|
|
5259
5485
|
throw e;
|
|
5260
5486
|
}
|
|
5261
|
-
|
|
5487
|
+
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5488
|
+
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
5489
|
+
}
|
|
5490
|
+
if (resource === "providers" && id && parts[3] === "catalog" && parts.length === 4 && request.method === "PUT") {
|
|
5491
|
+
if (store.engine === "postgresql")
|
|
5492
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id]);
|
|
5493
|
+
const provider = await store.get("providers", id, db);
|
|
5494
|
+
if (provider.version !== version())
|
|
5495
|
+
throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
|
|
5496
|
+
const catalog = parse(catalogSchema, body);
|
|
5497
|
+
const expectedSource = provider.manualModels.length ? "manual" : "remote";
|
|
5498
|
+
if (catalog.source !== expectedSource)
|
|
5499
|
+
throw new Fault(422, "catalog_source_mismatch", "Catalog provenance does not match the current provider configuration.");
|
|
5500
|
+
catalog.refreshedAt = new Date().toISOString();
|
|
5501
|
+
let old;
|
|
5502
|
+
try {
|
|
5503
|
+
old = await store.get("catalogs", id, db);
|
|
5504
|
+
} catch (error) {
|
|
5505
|
+
if (!(error instanceof Fault && error.status === 404))
|
|
5506
|
+
throw error;
|
|
5507
|
+
}
|
|
5508
|
+
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5509
|
+
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
5262
5510
|
}
|
|
5263
|
-
if (resource === "launch-plans" && !
|
|
5511
|
+
if (resource === "launch-plans" && !id && request.method === "POST") {
|
|
5264
5512
|
const { profileId } = parse(z4.object({ profileId: idSchema }).strict(), body);
|
|
5265
5513
|
const profile = await store.get("profiles", profileId, db);
|
|
5266
5514
|
const provider = await store.get("providers", profile.providerId, db);
|
|
@@ -5273,6 +5521,9 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5273
5521
|
throw new Fault(422, "catalog_missing", "Refresh the provider catalog before launching.");
|
|
5274
5522
|
throw e;
|
|
5275
5523
|
}
|
|
5524
|
+
const stored = catalog;
|
|
5525
|
+
if (stored.providerVersion !== undefined && stored.providerVersion !== provider.version || stored.providerFingerprint !== undefined && stored.providerFingerprint !== providerCatalogFingerprint(provider))
|
|
5526
|
+
throw new Fault(409, "catalog_provider_changed", "Catalog metadata belongs to an older provider configuration; refresh locally before launching.");
|
|
5276
5527
|
const selected = catalog.models.find((m) => m.id === profile.model);
|
|
5277
5528
|
if (!selected)
|
|
5278
5529
|
throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
|
|
@@ -5290,7 +5541,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5290
5541
|
warnings.push("Catalog snapshot is older than five minutes; refresh before launching.");
|
|
5291
5542
|
return { profile, provider, catalog, warnings, planToken: snapshot(profile, provider, catalog) };
|
|
5292
5543
|
}
|
|
5293
|
-
if (resource === "runs" && !
|
|
5544
|
+
if (resource === "runs" && !id && request.method === "POST") {
|
|
5294
5545
|
if (body?.modelPolicyVersion !== 1)
|
|
5295
5546
|
throw new Fault(409, "launcher_upgrade_required", "This API requires a launcher with automatic model policy version 1; upgrade the Switcher CLI/SDK.");
|
|
5296
5547
|
const input = parse(runInputSchema, body);
|
|
@@ -5315,16 +5566,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5315
5566
|
compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
|
|
5316
5567
|
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);
|
|
5317
5568
|
}
|
|
5318
|
-
if (resource === "runs" &&
|
|
5569
|
+
if (resource === "runs" && id && request.method === "PATCH" && parts.length === 3) {
|
|
5319
5570
|
const input = parse(runUpdateSchema, body);
|
|
5320
|
-
const run = await store.get("runs",
|
|
5571
|
+
const run = await store.get("runs", id, db);
|
|
5321
5572
|
if (run.status !== "running")
|
|
5322
5573
|
throw new Fault(409, "run_finished", "Run has already finished.");
|
|
5323
5574
|
return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
|
|
5324
5575
|
}
|
|
5325
5576
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
5326
5577
|
});
|
|
5327
|
-
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
5578
|
+
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
|
|
5328
5579
|
} catch (error) {
|
|
5329
5580
|
const safe = error instanceof Fault ? error : new Fault(500, "internal_error", "Request failed.");
|
|
5330
5581
|
return json({ error: { code: safe.code, message: safe.message, requestId } }, safe.status);
|
|
@@ -5333,21 +5584,35 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5333
5584
|
}
|
|
5334
5585
|
|
|
5335
5586
|
// src/server.ts
|
|
5587
|
+
import { ApiKeyStore } from "@hasna/contracts/auth";
|
|
5336
5588
|
async function startServer(options) {
|
|
5337
5589
|
const port = options.port ?? 0;
|
|
5338
5590
|
if (!Number.isInteger(port) || port < 0 || port > 65535)
|
|
5339
5591
|
throw new Fault(400, "invalid_port", "Port must be an integer between 0 and 65535.");
|
|
5340
|
-
if (options.apiKey
|
|
5592
|
+
if (Boolean(options.apiKey) === Boolean(options.signingSecret))
|
|
5593
|
+
throw new Fault(500, "auth_config", "Configure exactly one local API token or hosted API signing secret.");
|
|
5594
|
+
if (options.apiKey && (options.apiKey.length < 24 || /[\r\n]/.test(options.apiKey)))
|
|
5341
5595
|
throw new Fault(500, "auth_config", "Use a random operator token of at least 24 characters.");
|
|
5342
|
-
|
|
5596
|
+
if (options.signingSecret && (options.signingSecret.length < 32 || /[\r\n]/.test(options.signingSecret)))
|
|
5597
|
+
throw new Fault(500, "auth_config", "Use an API signing secret of at least 32 characters.");
|
|
5598
|
+
if (options.signingSecret && !options.databaseUrl)
|
|
5599
|
+
throw new Fault(500, "storage_config", "Hosted signed-key authentication requires PostgreSQL; configure HASNA_SWITCHER_DATABASE_URL.");
|
|
5600
|
+
const store = await Store.open({ databaseUrl: options.databaseUrl, sqlitePath: options.sqlitePath, migrate: !options.signingSecret });
|
|
5343
5601
|
let server;
|
|
5344
5602
|
try {
|
|
5603
|
+
const authentication = options.apiKey ?? (() => {
|
|
5604
|
+
const keyStore = new ApiKeyStore(store.authQueryClient());
|
|
5605
|
+
return { kind: "signed-api-key", signingSecret: options.signingSecret, keyStatus: keyStore.keyStatus, audit: (event) => {
|
|
5606
|
+
if (event.outcome === "deny")
|
|
5607
|
+
console.error(`api_auth deny kid=${event.kid ?? "-"} reason=${event.reason ?? "-"} ${event.method ?? "-"} ${event.path ?? "-"}`);
|
|
5608
|
+
} };
|
|
5609
|
+
})();
|
|
5345
5610
|
server = Bun.serve({
|
|
5346
5611
|
hostname: options.hostname ?? "127.0.0.1",
|
|
5347
5612
|
port,
|
|
5348
5613
|
maxRequestBodySize: 1024 * 1024,
|
|
5349
5614
|
idleTimeout: 60,
|
|
5350
|
-
fetch: createHandler(store,
|
|
5615
|
+
fetch: createHandler(store, authentication, options.providerEnv, options.resolveCredential)
|
|
5351
5616
|
});
|
|
5352
5617
|
await store.ready();
|
|
5353
5618
|
} catch (error) {
|
|
@@ -5387,7 +5652,19 @@ var SWITCHER_LOCAL_OPT_IN_ENV_KEYS = ["HASNA_SWITCHER_LOCAL", "SWITCHER_LOCAL"];
|
|
|
5387
5652
|
var SWITCHER_KEYCHAIN_ITEM = "hasna.credentials.switcher.api-key";
|
|
5388
5653
|
var SWITCHER_CREDENTIALS_FILE = "~/.hasna/switcher/config/credentials";
|
|
5389
5654
|
function isSwitcherLocalOptIn(env = process.env) {
|
|
5390
|
-
|
|
5655
|
+
let selected;
|
|
5656
|
+
for (const key of SWITCHER_LOCAL_OPT_IN_ENV_KEYS) {
|
|
5657
|
+
if (env[key] === undefined)
|
|
5658
|
+
continue;
|
|
5659
|
+
const value = env[key].trim().toLowerCase();
|
|
5660
|
+
const decision = !value || ["0", "false", "no", "off"].includes(value) ? false : ["1", "true", "yes", "on"].includes(value) ? true : undefined;
|
|
5661
|
+
if (decision === undefined)
|
|
5662
|
+
throw new Fault(400, "invalid_local_opt_in", `${key} must be one of 1, true, yes, on, 0, false, no, or off.`);
|
|
5663
|
+
if (selected !== undefined && selected !== decision)
|
|
5664
|
+
throw new Fault(400, "conflicting_local_opt_in", "HASNA_SWITCHER_LOCAL and SWITCHER_LOCAL must not disagree.");
|
|
5665
|
+
selected = decision;
|
|
5666
|
+
}
|
|
5667
|
+
return selected ?? false;
|
|
5391
5668
|
}
|
|
5392
5669
|
function switcherAuthorityEnvKeys() {
|
|
5393
5670
|
const keys = clientTransportEnvKeys("switcher");
|
|
@@ -5466,15 +5743,691 @@ async function openCliRuntime(env = process.env, resolveCredential) {
|
|
|
5466
5743
|
return { client: new SwitcherClient({ baseUrl: service.url, apiKey }), mode: "local", providerEnv, close: service.close };
|
|
5467
5744
|
}
|
|
5468
5745
|
|
|
5746
|
+
// src/credentials.ts
|
|
5747
|
+
import { z as z5 } from "zod";
|
|
5748
|
+
import { constants as constants2 } from "fs";
|
|
5749
|
+
import { open, readdir, unlink, link, lstat as lstat2, access as access2, stat as stat2, realpath, readlink, rename } from "fs/promises";
|
|
5750
|
+
import { join as join2, isAbsolute as isAbsolute2, dirname as dirname2, parse as pathParts, resolve as resolvePath, sep } from "path";
|
|
5751
|
+
import { createHash as createHash4, randomUUID } from "crypto";
|
|
5752
|
+
import { execFile as execFile2, spawn } from "child_process";
|
|
5753
|
+
import { promisify as promisify2 } from "util";
|
|
5754
|
+
import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
|
|
5755
|
+
var execute2 = promisify2(execFile2);
|
|
5756
|
+
var reference = z5.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
|
|
5757
|
+
var item = z5.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
|
|
5758
|
+
var vaultKeySchema = z5.string().max(500).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)*$/, "Use a vault key path, not an option or secret value");
|
|
5759
|
+
var keychain = z5.object({ kind: z5.literal("keychain"), service: item, account: item }).strict();
|
|
5760
|
+
var credentialTier = z5.enum(["argument", "override", "pointer", "profile", "keychain", "disk", "env"]);
|
|
5761
|
+
var operator = z5.discriminatedUnion("kind", [
|
|
5762
|
+
z5.object({ kind: z5.literal("contracts"), expectedSource: item.optional(), expectedTier: credentialTier.optional() }).strict(),
|
|
5763
|
+
z5.object({ kind: z5.literal("env") }).strict(),
|
|
5764
|
+
z5.object({ kind: z5.literal("keychain"), account: item.refine((value) => value.trim().length > 0 && value === value.trim(), "Vault account must be nonblank without surrounding whitespace") }).strict()
|
|
5765
|
+
]);
|
|
5766
|
+
var origin = z5.string().transform((value) => new URL(endpoint(value)).origin);
|
|
5767
|
+
var credentialBindingSchema = z5.object({
|
|
5768
|
+
schema: z5.literal(1),
|
|
5769
|
+
credentialEnv: reference,
|
|
5770
|
+
origins: z5.array(origin).min(1).max(30),
|
|
5771
|
+
requireProviderAuthentication: z5.literal(true).optional(),
|
|
5772
|
+
source: z5.discriminatedUnion("kind", [keychain, z5.object({
|
|
5773
|
+
kind: z5.literal("vault"),
|
|
5774
|
+
key: vaultKeySchema,
|
|
5775
|
+
url: z5.string().max(2000).transform(endpoint).optional(),
|
|
5776
|
+
executable: z5.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute2, "Secrets executable must be an absolute path"),
|
|
5777
|
+
operator
|
|
5778
|
+
}).strict()])
|
|
5779
|
+
}).strict().superRefine((binding, ctx) => {
|
|
5780
|
+
if (binding.source.kind === "vault" && binding.source.operator.kind !== "contracts" && !binding.source.url)
|
|
5781
|
+
ctx.addIssue({ code: "custom", path: ["source", "url"], message: "An explicit env or Keychain operator binding requires a vault URL." });
|
|
5782
|
+
if (binding.source.kind === "vault" && binding.source.operator.kind === "contracts" && Boolean(binding.source.operator.expectedSource) !== Boolean(binding.source.operator.expectedTier))
|
|
5783
|
+
ctx.addIssue({ code: "custom", path: ["source", "operator"], message: "A pinned Contracts operator requires both expectedSource and expectedTier." });
|
|
5784
|
+
});
|
|
5785
|
+
var fingerprint = (binding) => createHash4("sha256").update(JSON.stringify(binding)).digest("hex");
|
|
5786
|
+
|
|
5787
|
+
class CredentialBindings {
|
|
5788
|
+
env;
|
|
5789
|
+
directory;
|
|
5790
|
+
constructor(env = process.env) {
|
|
5791
|
+
this.env = env;
|
|
5792
|
+
this.directory = join2(switcherHome(env), "config", "credential-bindings");
|
|
5793
|
+
}
|
|
5794
|
+
path(name) {
|
|
5795
|
+
return join2(this.directory, parse(reference, name) + ".json");
|
|
5796
|
+
}
|
|
5797
|
+
async readableDirectory() {
|
|
5798
|
+
for (const path of [switcherHome(this.env), join2(switcherHome(this.env), "config"), this.directory]) {
|
|
5799
|
+
let info;
|
|
5800
|
+
try {
|
|
5801
|
+
info = await lstat2(path);
|
|
5802
|
+
} catch (error) {
|
|
5803
|
+
if (error.code === "ENOENT")
|
|
5804
|
+
return false;
|
|
5805
|
+
throw error;
|
|
5806
|
+
}
|
|
5807
|
+
if (!info.isDirectory() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
|
|
5808
|
+
throw new Fault(500, "credential_binding_permissions", "Credential binding directories must be real, owner-only directories (mode 0700).");
|
|
5809
|
+
}
|
|
5810
|
+
return true;
|
|
5811
|
+
}
|
|
5812
|
+
async get(name) {
|
|
5813
|
+
const path = this.path(name);
|
|
5814
|
+
if (!await this.readableDirectory())
|
|
5815
|
+
return;
|
|
5816
|
+
let file;
|
|
5817
|
+
try {
|
|
5818
|
+
file = await open(path, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
|
|
5819
|
+
} catch (error) {
|
|
5820
|
+
if (error.code === "ENOENT")
|
|
5821
|
+
return;
|
|
5822
|
+
throw new Fault(500, "credential_binding_unreadable", "Cannot safely open the local credential binding.");
|
|
5823
|
+
}
|
|
5824
|
+
try {
|
|
5825
|
+
const info = await file.stat();
|
|
5826
|
+
if (!info.isFile() || info.size > 32768 || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
|
|
5827
|
+
throw new Fault(500, "credential_binding_permissions", "Credential binding must be an owner-only regular file (mode 0600).");
|
|
5828
|
+
let value;
|
|
5829
|
+
try {
|
|
5830
|
+
value = JSON.parse(await file.readFile("utf8"));
|
|
5831
|
+
} catch {
|
|
5832
|
+
throw new Fault(500, "credential_binding_invalid", "Credential binding must contain valid JSON.");
|
|
5833
|
+
}
|
|
5834
|
+
const binding = parse(credentialBindingSchema, value);
|
|
5835
|
+
if (binding.credentialEnv !== name)
|
|
5836
|
+
throw new Fault(500, "credential_binding_invalid", "Credential binding reference does not match its filename.");
|
|
5837
|
+
return binding;
|
|
5838
|
+
} finally {
|
|
5839
|
+
await file.close();
|
|
5840
|
+
}
|
|
5841
|
+
}
|
|
5842
|
+
async list() {
|
|
5843
|
+
if (!await this.readableDirectory())
|
|
5844
|
+
return [];
|
|
5845
|
+
let entries;
|
|
5846
|
+
try {
|
|
5847
|
+
entries = await readdir(this.directory);
|
|
5848
|
+
} catch (error) {
|
|
5849
|
+
if (error.code === "ENOENT")
|
|
5850
|
+
return [];
|
|
5851
|
+
throw error;
|
|
5852
|
+
}
|
|
5853
|
+
const result = [];
|
|
5854
|
+
for (const name of entries.sort())
|
|
5855
|
+
if (/^SWITCHER_PROVIDER_[A-Z0-9_]+\.json$/.test(name)) {
|
|
5856
|
+
const binding = await this.get(name.slice(0, -5));
|
|
5857
|
+
if (binding)
|
|
5858
|
+
result.push(binding);
|
|
5859
|
+
}
|
|
5860
|
+
return result;
|
|
5861
|
+
}
|
|
5862
|
+
async bind(input) {
|
|
5863
|
+
const binding = parse(credentialBindingSchema, input);
|
|
5864
|
+
if (binding.source.kind === "vault")
|
|
5865
|
+
await validateVaultExecutable(binding.source.executable);
|
|
5866
|
+
await privateDirectory(switcherHome(this.env));
|
|
5867
|
+
await privateDirectory(join2(switcherHome(this.env), "config"));
|
|
5868
|
+
await privateDirectory(this.directory);
|
|
5869
|
+
const temporary = join2(this.directory, `.binding-${randomUUID()}`);
|
|
5870
|
+
const file = await open(temporary, "wx", 384);
|
|
5871
|
+
try {
|
|
5872
|
+
await file.writeFile(JSON.stringify(binding, null, 2) + `
|
|
5873
|
+
`);
|
|
5874
|
+
await file.sync();
|
|
5875
|
+
try {
|
|
5876
|
+
await link(temporary, this.path(binding.credentialEnv));
|
|
5877
|
+
} catch (error) {
|
|
5878
|
+
if (error.code !== "EEXIST")
|
|
5879
|
+
throw error;
|
|
5880
|
+
const existing = await this.get(binding.credentialEnv);
|
|
5881
|
+
if (existing && fingerprint(existing) === fingerprint(binding))
|
|
5882
|
+
return existing;
|
|
5883
|
+
throw new Fault(409, "credential_binding_exists", "A different binding already exists. Remove it explicitly before binding another credential account.");
|
|
5884
|
+
}
|
|
5885
|
+
} finally {
|
|
5886
|
+
await file.close();
|
|
5887
|
+
await unlink(temporary);
|
|
5888
|
+
}
|
|
5889
|
+
return binding;
|
|
5890
|
+
}
|
|
5891
|
+
async remove(name) {
|
|
5892
|
+
const binding = await this.get(name);
|
|
5893
|
+
if (!binding)
|
|
5894
|
+
throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
|
|
5895
|
+
await unlink(this.path(name));
|
|
5896
|
+
return { removed: name };
|
|
5897
|
+
}
|
|
5898
|
+
}
|
|
5899
|
+
async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
5900
|
+
let info, resolved;
|
|
5901
|
+
try {
|
|
5902
|
+
resolved = await realpath(path);
|
|
5903
|
+
await access2(resolved, constants2.X_OK);
|
|
5904
|
+
info = await stat2(resolved);
|
|
5905
|
+
if (!info.isFile())
|
|
5906
|
+
throw new Error;
|
|
5907
|
+
} catch {
|
|
5908
|
+
throw new Fault(422, "vault_exec_unavailable", "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.");
|
|
5909
|
+
}
|
|
5910
|
+
if (process.platform !== "win32" && (!permitWritableFile && info.mode & 18 || info.uid !== 0 && info.uid !== process.getuid?.()))
|
|
5911
|
+
throw new Fault(422, "vault_exec_permissions", "The secrets executable must be owned by this user or root and not writable by other users. Choose a trusted installation, or use credentials repair-executable REFERENCE --sha256 EXPECTED with the executable digest from a verified package artifact. Launch never repairs permissions automatically.");
|
|
5912
|
+
if (process.platform !== "win32") {
|
|
5913
|
+
const seen = new Set;
|
|
5914
|
+
const inspect = async (candidate) => {
|
|
5915
|
+
let prefix = pathParts(candidate).root;
|
|
5916
|
+
for (const part of candidate.slice(prefix.length).split(sep)) {
|
|
5917
|
+
if (!part)
|
|
5918
|
+
continue;
|
|
5919
|
+
prefix = join2(prefix, part);
|
|
5920
|
+
if (seen.has(prefix))
|
|
5921
|
+
continue;
|
|
5922
|
+
seen.add(prefix);
|
|
5923
|
+
if (seen.size > 256)
|
|
5924
|
+
throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
|
|
5925
|
+
const entry = await lstat2(prefix);
|
|
5926
|
+
const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
|
|
5927
|
+
if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
|
|
5928
|
+
throw new Fault(422, "vault_exec_permissions", "The secrets executable and its ancestor directories must not be replaceable by other users. Choose an installation owned by this user or root without group/public write permissions.");
|
|
5929
|
+
if (entry.isSymbolicLink())
|
|
5930
|
+
await inspect(resolvePath(dirname2(prefix), await readlink(prefix)));
|
|
5931
|
+
}
|
|
5932
|
+
};
|
|
5933
|
+
try {
|
|
5934
|
+
await inspect(path);
|
|
5935
|
+
await inspect(resolved);
|
|
5936
|
+
} catch (error) {
|
|
5937
|
+
if (error instanceof Fault)
|
|
5938
|
+
throw error;
|
|
5939
|
+
throw new Fault(422, "vault_exec_unavailable", "The secrets executable path changed or could not be verified. Retry with a trusted installation.");
|
|
5940
|
+
}
|
|
5941
|
+
}
|
|
5942
|
+
return resolved;
|
|
5943
|
+
}
|
|
5944
|
+
async function validateVaultExecutable(path) {
|
|
5945
|
+
return inspectVaultExecutable(path);
|
|
5946
|
+
}
|
|
5947
|
+
async function readKeychain(source) {
|
|
5948
|
+
if (process.platform !== "darwin")
|
|
5949
|
+
throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
|
|
5950
|
+
let stdout;
|
|
5951
|
+
try {
|
|
5952
|
+
({ stdout } = await execute2("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 }));
|
|
5953
|
+
} catch (error) {
|
|
5954
|
+
const status = error.code;
|
|
5955
|
+
if (status === 44)
|
|
5956
|
+
throw new Fault(422, "keychain_item_missing", "The configured Keychain item does not exist for that service and account; no alternate credential was selected.");
|
|
5957
|
+
throw new Fault(422, "keychain_unavailable", `The configured Keychain item could not be read (security exited ${typeof status === "number" ? status : "without a status"}); it is locked or inaccessible. No alternate credential was selected.`);
|
|
5958
|
+
}
|
|
5959
|
+
const value = stdout.replace(/\r?\n$/, "");
|
|
5960
|
+
if (!value || /[\x00-\x1f\x7f]/.test(value))
|
|
5961
|
+
throw new Fault(422, "keychain_item_invalid", "The configured Keychain item holds an unusable value; no alternate credential was selected.");
|
|
5962
|
+
return value;
|
|
5963
|
+
}
|
|
5964
|
+
|
|
5965
|
+
class CredentialResolver {
|
|
5966
|
+
env;
|
|
5967
|
+
keychainRead;
|
|
5968
|
+
bindings;
|
|
5969
|
+
constructor(env = process.env, keychainRead = readKeychain) {
|
|
5970
|
+
this.env = env;
|
|
5971
|
+
this.keychainRead = keychainRead;
|
|
5972
|
+
this.bindings = new CredentialBindings(env);
|
|
5973
|
+
}
|
|
5974
|
+
async resolve(provider) {
|
|
5975
|
+
if (!provider.credentialEnv)
|
|
5976
|
+
return;
|
|
5977
|
+
const binding = await this.bindings.get(provider.credentialEnv);
|
|
5978
|
+
if (!binding)
|
|
5979
|
+
return providerCredential(provider, this.env);
|
|
5980
|
+
if (!binding.origins.includes(new URL(provider.baseUrl).origin))
|
|
5981
|
+
throw new Fault(422, "credential_authority", "The local credential binding does not authorize this provider origin. Update the binding explicitly; no key was sent.");
|
|
5982
|
+
if (binding.source.kind === "keychain")
|
|
5983
|
+
return this.keychainRead(binding.source);
|
|
5984
|
+
return fetchVaultCredential(binding, this.env);
|
|
5985
|
+
}
|
|
5986
|
+
async check(name) {
|
|
5987
|
+
const binding = await this.bindings.get(name);
|
|
5988
|
+
if (!binding)
|
|
5989
|
+
throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
|
|
5990
|
+
if (binding.source.kind === "vault") {
|
|
5991
|
+
const output = await runVaultCommand(binding, ["get", binding.source.key, "--check"], this.env, {}, {
|
|
5992
|
+
captureBytes: 4096,
|
|
5993
|
+
oversizeCode: "vault_check_failed",
|
|
5994
|
+
oversizeMessage: "The secrets CLI returned an oversized check result."
|
|
5995
|
+
});
|
|
5996
|
+
const match = /^key=\S+ length=(\d+) sha256=([a-f0-9]{64})\s*$/.exec(output);
|
|
5997
|
+
if (!match)
|
|
5998
|
+
throw new Fault(422, "vault_check_failed", "The secrets CLI did not return a supported credential check result.");
|
|
5999
|
+
return { credentialEnv: name, source: "vault", available: true, length: Number(match[1]), sha256: match[2], providerAuthentication: "not tested" };
|
|
6000
|
+
}
|
|
6001
|
+
const value = await this.keychainRead(binding.source);
|
|
6002
|
+
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash4("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
|
|
6003
|
+
}
|
|
6004
|
+
}
|
|
6005
|
+
var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
|
|
6006
|
+
var DELIVERY_NONCE = "SWITCHER_CREDENTIAL_DELIVERY_NONCE";
|
|
6007
|
+
var DELIVERY_VALUE = "SWITCHER_CREDENTIAL_DELIVERY_VALUE";
|
|
6008
|
+
|
|
6009
|
+
class CredentialInterrupted extends CommandInterrupted {
|
|
6010
|
+
constructor(exitCode) {
|
|
6011
|
+
super(exitCode, "Credential lookup was interrupted; no harness was started.");
|
|
6012
|
+
}
|
|
6013
|
+
}
|
|
6014
|
+
async function resolveVaultOperatorEnvironment(binding, env, options = {}) {
|
|
6015
|
+
if (binding.source.kind !== "vault")
|
|
6016
|
+
throw new Fault(500, "credential_resolution", "Unexpected credential source.");
|
|
6017
|
+
const source = binding.source;
|
|
6018
|
+
let credential, url = source.url;
|
|
6019
|
+
try {
|
|
6020
|
+
if (source.operator.kind === "contracts") {
|
|
6021
|
+
const pair = () => {
|
|
6022
|
+
const keys = clientTransportEnvKeys3("secrets");
|
|
6023
|
+
const configuredUrl = keys.apiUrlKeys.map((name) => env[name]).find((value) => value !== undefined) ?? keychainConfigValue2("secrets", env, options.keychain)?.value ?? appConfigDiskValue2("secrets", env, keys.apiUrlKeys)?.value;
|
|
6024
|
+
const resolution = resolveClientTransport("secrets", env, { credentials: options });
|
|
6025
|
+
const key = resolveCredential("secrets", env, options);
|
|
6026
|
+
if (key?.tier === "pointer")
|
|
6027
|
+
throw new Fault(422, "vault_operator_pointer", "A Secrets operator cannot bootstrap itself through HASNA_SECRETS_API_KEY_REF. Configure its operator in Keychain, canonical config/credentials, or an explicit key override.");
|
|
6028
|
+
if (!key?.apiKey || key.source !== resolution.apiKeySource || key.tier !== resolution.apiKeyTier)
|
|
6029
|
+
throw new Fault(422, "vault_operator_changed", "The vault operator changed during resolution; no credential was sent. Retry after configuration is stable.");
|
|
6030
|
+
const boundUrl = source.url ? toV1BaseUrl(source.url) : resolution.baseUrl;
|
|
6031
|
+
if (resolution.apiUrlSource !== "default" && boundUrl !== resolution.baseUrl)
|
|
6032
|
+
throw new Fault(422, "vault_operator_authority", "The binding vault URL conflicts with the canonical Secrets API URL; no credential was sent.");
|
|
6033
|
+
if (configuredUrl !== undefined && toV1BaseUrl(configuredUrl) !== resolution.baseUrl)
|
|
6034
|
+
throw new Fault(422, "vault_operator_changed", "The vault authority changed during resolution; no credential was sent.");
|
|
6035
|
+
return { key, url: configuredUrl?.trim() ?? source.url ?? boundUrl.replace(/\/v1$/, "") };
|
|
6036
|
+
};
|
|
6037
|
+
const first = pair(), second = pair();
|
|
6038
|
+
if (first.key.apiKey !== second.key.apiKey || first.key.source !== second.key.source || first.key.tier !== second.key.tier || first.url !== second.url)
|
|
6039
|
+
throw new Fault(422, "vault_operator_changed", "The vault operator or authority changed during resolution; no credential was sent. Retry after configuration is stable.");
|
|
6040
|
+
if (source.operator.expectedSource && (second.key.source !== source.operator.expectedSource || second.key.tier !== source.operator.expectedTier))
|
|
6041
|
+
throw new Fault(422, "vault_operator_changed", `The selected Secrets account/source changed from ${source.operator.expectedSource}; no alternate account was selected. Restore that source or rebind explicitly.`);
|
|
6042
|
+
credential = second.key;
|
|
6043
|
+
url = second.url;
|
|
6044
|
+
} else {
|
|
6045
|
+
credential = source.operator.kind === "keychain" ? resolveCredential("secrets", { HASNA_STATION: source.operator.account }, { keychain: { ...options.keychain, enabled: true } }) : resolveCredential("secrets", Object.fromEntries(Object.entries(env).filter(([name]) => name === "HASNA_SECRETS_API_KEY")), { keychain: { enabled: false } });
|
|
6046
|
+
}
|
|
6047
|
+
} catch (error) {
|
|
6048
|
+
if (error instanceof Fault)
|
|
6049
|
+
throw error;
|
|
6050
|
+
const kind = error instanceof Error ? error.name : "";
|
|
6051
|
+
const detail = error instanceof Error ? error.message : "";
|
|
6052
|
+
const reason = /keychain|security exited/i.test(detail) ? "selected Secrets Keychain source is locked or inaccessible" : kind === "CredentialFileUnsafeError" ? "unsafe canonical config/credentials file" : kind === "ClientTransportConfigurationError" ? "invalid or missing canonical API URL/key" : source.operator.kind === "keychain" ? "unavailable pinned Keychain account" : "credential selection refused by Contracts (Keychain, canonical file, profile, or environment)";
|
|
6053
|
+
throw new Fault(422, "vault_operator_unavailable", `Cannot resolve the Secrets vault operator: ${reason}. Check the selected source in this terminal session; no alternate account was selected.`);
|
|
6054
|
+
}
|
|
6055
|
+
if (!credential?.apiKey)
|
|
6056
|
+
throw new Fault(422, "vault_operator_missing", "The selected vault operator has no credential. Use a canonical Contracts binding, restore its named Keychain account, or inject HASNA_SECRETS_API_KEY for an explicit env binding.");
|
|
6057
|
+
const allowed = /^(PATH|HOME|USER|LOGNAME|SHELL|LANG|LC_[A-Z_]+|TMPDIR|TEMP|TMP|HASNA_HOME|HASNA_CONFIG_HOME|HASNA_SECRETS_HOME|HASNA_STATION)$/;
|
|
6058
|
+
const next = Object.fromEntries(Object.entries(env).filter(([name]) => allowed.test(name)));
|
|
6059
|
+
next.HASNA_SECRETS_API_URL = url;
|
|
6060
|
+
next.HASNA_SECRETS_API_KEY = credential.apiKey;
|
|
6061
|
+
next.HASNA_SECRETS_API_KEY_OVERRIDE = credential.apiKey;
|
|
6062
|
+
if (binding.source.operator.kind === "keychain")
|
|
6063
|
+
next.HASNA_STATION = binding.source.operator.account;
|
|
6064
|
+
return { environment: next, source: credential.source, tier: credential.tier, url };
|
|
6065
|
+
}
|
|
6066
|
+
async function runVaultCommand(binding, args, env, delivery = {}, options = {}) {
|
|
6067
|
+
if (binding.source.kind !== "vault")
|
|
6068
|
+
throw new Fault(500, "credential_resolution", "Unexpected credential source.");
|
|
6069
|
+
if (process.platform === "win32")
|
|
6070
|
+
throw new Fault(422, "vault_exec_unavailable", "Vault CLI bindings currently require POSIX process groups; use runtime environment injection on Windows.");
|
|
6071
|
+
const executable = await validateVaultExecutable(binding.source.executable);
|
|
6072
|
+
const operator = options.operator ?? await resolveVaultOperatorEnvironment(binding, env);
|
|
6073
|
+
const childEnv = { ...operator.environment, ...delivery };
|
|
6074
|
+
return new Promise((resolveResult, reject) => {
|
|
6075
|
+
const child = spawn(executable, args, { env: childEnv, stdio: ["ignore", options.captureBytes ? "pipe" : "ignore", "ignore"], detached: true, shell: false });
|
|
6076
|
+
let failure;
|
|
6077
|
+
let output = "";
|
|
6078
|
+
let outputBytes = 0;
|
|
6079
|
+
let cleaned = false;
|
|
6080
|
+
const kill = () => {
|
|
6081
|
+
if (child.pid) {
|
|
6082
|
+
try {
|
|
6083
|
+
process.kill(-child.pid, "SIGKILL");
|
|
6084
|
+
} catch {}
|
|
6085
|
+
}
|
|
6086
|
+
};
|
|
6087
|
+
const interrupt = (signal) => {
|
|
6088
|
+
failure = new CredentialInterrupted(signal === "SIGINT" ? 130 : 143);
|
|
6089
|
+
process.exitCode = signal === "SIGINT" ? 130 : 143;
|
|
6090
|
+
kill();
|
|
6091
|
+
};
|
|
6092
|
+
const onInt = () => interrupt("SIGINT");
|
|
6093
|
+
const onTerm = () => interrupt("SIGTERM");
|
|
6094
|
+
process.on("SIGINT", onInt);
|
|
6095
|
+
process.on("SIGTERM", onTerm);
|
|
6096
|
+
const timeout = setTimeout(() => {
|
|
6097
|
+
failure = new Fault(504, "vault_timeout", "Credential lookup exceeded 20 seconds; no alternate credential was selected.");
|
|
6098
|
+
kill();
|
|
6099
|
+
}, 20000);
|
|
6100
|
+
const cleanup = () => {
|
|
6101
|
+
if (cleaned)
|
|
6102
|
+
return;
|
|
6103
|
+
cleaned = true;
|
|
6104
|
+
clearTimeout(timeout);
|
|
6105
|
+
process.off("SIGINT", onInt);
|
|
6106
|
+
process.off("SIGTERM", onTerm);
|
|
6107
|
+
kill();
|
|
6108
|
+
};
|
|
6109
|
+
child.stdout?.on("data", (chunk) => {
|
|
6110
|
+
outputBytes += chunk.length;
|
|
6111
|
+
if (outputBytes > (options.captureBytes ?? 0)) {
|
|
6112
|
+
failure = new Fault(422, options.oversizeCode ?? "vault_check_failed", options.oversizeMessage ?? "The secrets CLI returned an oversized result.");
|
|
6113
|
+
kill();
|
|
6114
|
+
} else
|
|
6115
|
+
output += chunk.toString("utf8");
|
|
6116
|
+
});
|
|
6117
|
+
child.once("error", () => {
|
|
6118
|
+
cleanup();
|
|
6119
|
+
reject(new Fault(422, "vault_exec_failed", "The configured secrets CLI could not start; check its executable and permissions."));
|
|
6120
|
+
});
|
|
6121
|
+
child.once("exit", cleanup);
|
|
6122
|
+
child.once("close", (code) => {
|
|
6123
|
+
if (failure)
|
|
6124
|
+
reject(failure);
|
|
6125
|
+
else if (code !== 0)
|
|
6126
|
+
reject(new Fault(422, options.lookupCode ?? "vault_lookup_failed", options.lookupMessage ?? "The secrets CLI could not read the configured key. Check vault access and conflicting local vault URL settings; no alternate account was selected."));
|
|
6127
|
+
else
|
|
6128
|
+
resolveResult(output);
|
|
6129
|
+
});
|
|
6130
|
+
});
|
|
6131
|
+
}
|
|
6132
|
+
async function fetchVaultCredential(binding, env) {
|
|
6133
|
+
if (binding.source.kind !== "vault")
|
|
6134
|
+
throw new Fault(500, "credential_resolution", "Unexpected credential source.");
|
|
6135
|
+
const nonce = crypto.randomUUID() + crypto.randomUUID();
|
|
6136
|
+
let value;
|
|
6137
|
+
const broker = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 65536, async fetch(request) {
|
|
6138
|
+
if (request.method !== "POST" || new URL(request.url).pathname !== "/credential" || request.headers.get("authorization") !== `Bearer ${nonce}` || value !== undefined)
|
|
6139
|
+
return new Response(null, { status: 404 });
|
|
6140
|
+
let candidate;
|
|
6141
|
+
try {
|
|
6142
|
+
candidate = await request.json();
|
|
6143
|
+
} catch {
|
|
6144
|
+
return new Response(null, { status: 400 });
|
|
6145
|
+
}
|
|
6146
|
+
if (typeof candidate !== "string" || !candidate || candidate.length > 64000 || /[\x00-\x1f\x7f]/.test(candidate))
|
|
6147
|
+
return new Response(null, { status: 400 });
|
|
6148
|
+
value = candidate;
|
|
6149
|
+
return new Response(null, { status: 204 });
|
|
6150
|
+
} });
|
|
6151
|
+
try {
|
|
6152
|
+
await runVaultCommand(binding, ["exec", binding.source.key, "--as", DELIVERY_VALUE, "--", process.execPath, process.argv[1], "__credential-delivery"], env, {
|
|
6153
|
+
[DELIVERY_URL]: broker.url.origin + "/credential",
|
|
6154
|
+
[DELIVERY_NONCE]: nonce
|
|
6155
|
+
});
|
|
6156
|
+
if (!value)
|
|
6157
|
+
throw new Fault(422, "vault_delivery_failed", "The secrets CLI completed without a valid credential handoff.");
|
|
6158
|
+
return value;
|
|
6159
|
+
} finally {
|
|
6160
|
+
await broker.stop(true);
|
|
6161
|
+
}
|
|
6162
|
+
}
|
|
6163
|
+
|
|
6164
|
+
// src/provider-credential-onboarding.ts
|
|
6165
|
+
import { z as z6 } from "zod";
|
|
6166
|
+
import { createHash as createHash5 } from "crypto";
|
|
6167
|
+
import { createInterface } from "readline/promises";
|
|
6168
|
+
var absent = (error) => error instanceof SwitcherError && error.status === 404;
|
|
6169
|
+
var secretMetadataSchema = z6.object({
|
|
6170
|
+
key: vaultKeySchema,
|
|
6171
|
+
type: z6.enum(["api_key", "password", "token", "credential", "other"]),
|
|
6172
|
+
label: z6.string().max(1000).nullable().optional(),
|
|
6173
|
+
expires_at: z6.string().max(200).nullable().optional(),
|
|
6174
|
+
created_at: z6.string().max(200),
|
|
6175
|
+
updated_at: z6.string().max(200)
|
|
6176
|
+
}).strict();
|
|
6177
|
+
var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
|
|
6178
|
+
var credentialOrigins = (provider) => {
|
|
6179
|
+
const origins = new Set([new URL(provider.baseUrl).origin]);
|
|
6180
|
+
const catalogAuthStyle = provider.catalogAuthStyle ?? provider.authStyle ?? "bearer";
|
|
6181
|
+
const catalogCredentialEnv = provider.catalogCredentialEnv ?? provider.credentialEnv;
|
|
6182
|
+
if (catalogAuthStyle !== "none" && provider.catalogBaseUrl && catalogCredentialEnv === provider.credentialEnv)
|
|
6183
|
+
origins.add(new URL(provider.catalogBaseUrl).origin);
|
|
6184
|
+
return [...origins];
|
|
6185
|
+
};
|
|
6186
|
+
var providerCredentialSetupCommand = (provider) => {
|
|
6187
|
+
if (!provider.credentialEnv)
|
|
6188
|
+
return "";
|
|
6189
|
+
const origins = credentialOrigins(provider).map((value) => ` --origin ${value}`).join("");
|
|
6190
|
+
return `switcher credentials bind ${provider.credentialEnv}${origins} --vault-key <vault-key>`;
|
|
6191
|
+
};
|
|
6192
|
+
var searchTerms = (provider) => {
|
|
6193
|
+
const fromReference = provider.credentialEnv?.replace(/^SWITCHER_PROVIDER_/, "").replace(/_API_KEY$/, "").toLowerCase().replace(/_/g, "-");
|
|
6194
|
+
const raw = [fromReference, provider.name.toLowerCase().replace(/[^a-z0-9]+/g, "-"), provider.id.toLowerCase()];
|
|
6195
|
+
return [...new Set(raw.flatMap((value) => value ? [value, ...value.split("-")] : []).filter((value) => value.length >= 3 && !new Set(["api", "key", "provider", "responses", "response", "messages", "message", "chat", "custom"]).has(value)))].slice(0, 4);
|
|
6196
|
+
};
|
|
6197
|
+
async function discoverVaultReferences(provider, env = process.env, vaultExecutable = Bun.which("secrets") ?? "") {
|
|
6198
|
+
if (!provider.credentialEnv)
|
|
6199
|
+
return [];
|
|
6200
|
+
if (!vaultExecutable)
|
|
6201
|
+
throw new Fault(422, "vault_exec_unavailable", "Hasna Secrets is not installed in this launcher process. Install it or run the exact credentials bind command with --vault-cli /absolute/path.");
|
|
6202
|
+
await validateVaultExecutable(vaultExecutable);
|
|
6203
|
+
const source = { kind: "vault", key: "switcher/provider-credential-discovery", executable: vaultExecutable, operator: { kind: "contracts" } };
|
|
6204
|
+
const provisional = parse(credentialBindingSchema, { schema: 1, credentialEnv: provider.credentialEnv, origins: credentialOrigins(provider), source });
|
|
6205
|
+
const operator = await resolveVaultOperatorEnvironment(provisional, env);
|
|
6206
|
+
const entries = new Map;
|
|
6207
|
+
for (const query of searchTerms(provider)) {
|
|
6208
|
+
const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
|
|
6209
|
+
captureBytes: 256 * 1024,
|
|
6210
|
+
oversizeCode: "vault_metadata_oversized",
|
|
6211
|
+
oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
|
|
6212
|
+
lookupCode: "vault_search_failed",
|
|
6213
|
+
lookupMessage: "Hasna Secrets could not search credential metadata. Check the selected vault/Keychain source; no alternate account was selected.",
|
|
6214
|
+
operator
|
|
6215
|
+
});
|
|
6216
|
+
let parsed;
|
|
6217
|
+
try {
|
|
6218
|
+
parsed = JSON.parse(output);
|
|
6219
|
+
} catch {
|
|
6220
|
+
throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned invalid credential metadata JSON.");
|
|
6221
|
+
}
|
|
6222
|
+
const result = secretMetadataSchema.array().max(1000).safeParse(parsed);
|
|
6223
|
+
if (!result.success)
|
|
6224
|
+
throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned an unsupported credential metadata shape.");
|
|
6225
|
+
for (const entry of result.data)
|
|
6226
|
+
entries.set(entry.key, entry);
|
|
6227
|
+
if (entries.size > 256)
|
|
6228
|
+
throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
|
|
6229
|
+
}
|
|
6230
|
+
return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((entry) => ({ account: operator.source, key: entry.key, url: operator.url, executable: vaultExecutable, operator: { kind: "contracts", expectedSource: operator.source, expectedTier: operator.tier } }));
|
|
6231
|
+
}
|
|
6232
|
+
async function selectVaultReference({ provider, matches }) {
|
|
6233
|
+
if (!process.stdin.isTTY || !process.stderr.isTTY)
|
|
6234
|
+
return;
|
|
6235
|
+
console.error(`Secrets account/source: ${cleanDisplay(matches[0]?.account ?? "unknown")}`);
|
|
6236
|
+
console.error(`Credential references matching ${cleanDisplay(provider.name)}:`);
|
|
6237
|
+
matches.forEach((match, index) => console.error(` ${index + 1}. ${cleanDisplay(match.key)}${match.account === matches[0]?.account ? "" : ` (account/source: ${cleanDisplay(match.account)})`}`));
|
|
6238
|
+
const reader = createInterface({ input: process.stdin, output: process.stderr });
|
|
6239
|
+
const cancellation = new AbortController;
|
|
6240
|
+
const cancel = () => cancellation.abort(new CommandInterrupted(130, "Credential setup was cancelled; no binding was saved and no harness was started."));
|
|
6241
|
+
const terminate = () => cancellation.abort(new CommandInterrupted(143, "Credential setup was interrupted; no binding was saved and no harness was started."));
|
|
6242
|
+
reader.on("SIGINT", cancel);
|
|
6243
|
+
reader.on("close", cancel);
|
|
6244
|
+
process.on("SIGINT", cancel);
|
|
6245
|
+
process.on("SIGTERM", terminate);
|
|
6246
|
+
try {
|
|
6247
|
+
for (;; ) {
|
|
6248
|
+
const answer = (await reader.question("Credential number (Ctrl-C cancels): ", { signal: cancellation.signal }).catch((error) => {
|
|
6249
|
+
throw cancellation.signal.aborted ? cancellation.signal.reason : error;
|
|
6250
|
+
})).trim();
|
|
6251
|
+
if (!answer || /^(q|quit|cancel)$/i.test(answer))
|
|
6252
|
+
return;
|
|
6253
|
+
if (/^[1-9]\d*$/.test(answer) && matches[Number(answer) - 1])
|
|
6254
|
+
return matches[Number(answer) - 1];
|
|
6255
|
+
console.error(`Enter a number from 1 to ${matches.length}, or q to cancel.`);
|
|
6256
|
+
}
|
|
6257
|
+
} finally {
|
|
6258
|
+
reader.off("SIGINT", cancel);
|
|
6259
|
+
reader.off("close", cancel);
|
|
6260
|
+
process.off("SIGINT", cancel);
|
|
6261
|
+
process.off("SIGTERM", terminate);
|
|
6262
|
+
reader.close();
|
|
6263
|
+
}
|
|
6264
|
+
}
|
|
6265
|
+
function authenticationProbe(provider) {
|
|
6266
|
+
if (provider.credentialCheck) {
|
|
6267
|
+
const root = provider.baseUrl.endsWith("/") ? provider.baseUrl : `${provider.baseUrl}/`;
|
|
6268
|
+
const url = new URL(provider.credentialCheck.path, root);
|
|
6269
|
+
if (url.origin !== new URL(provider.baseUrl).origin || !url.href.startsWith(root))
|
|
6270
|
+
throw new Fault(422, "provider_auth_check_invalid", "Provider authentication check must remain below its inference endpoint.");
|
|
6271
|
+
return { url, method: provider.credentialCheck.method ?? "GET", authStyle: provider.authStyle ?? "bearer" };
|
|
6272
|
+
}
|
|
6273
|
+
const base = new URL(provider.baseUrl);
|
|
6274
|
+
if (provider.credentialEnv === "SWITCHER_PROVIDER_OPENROUTER" && base.origin === "https://openrouter.ai" && base.pathname.replace(/\/+$/, "") === "/api/v1")
|
|
6275
|
+
return { url: new URL("https://openrouter.ai/api/v1/key"), method: "GET", authStyle: provider.authStyle ?? "bearer" };
|
|
6276
|
+
return;
|
|
6277
|
+
}
|
|
6278
|
+
async function verifyProviderAuthentication({ provider, credential, fetch: fetchImpl = fetch }) {
|
|
6279
|
+
const probe = authenticationProbe(provider);
|
|
6280
|
+
if (!probe)
|
|
6281
|
+
return { authenticated: false, unsupported: true };
|
|
6282
|
+
const [header, value] = authHeader(probe.authStyle, credential);
|
|
6283
|
+
const headers = { accept: "application/json", "user-agent": "hasna-switcher/credential-check" };
|
|
6284
|
+
headers[provider.catalogFormat === "gemini" && header === "x-api-key" ? "x-goog-api-key" : header] = value;
|
|
6285
|
+
if (provider.protocol === "anthropic-messages" && probe.url.hostname !== "openrouter.ai")
|
|
6286
|
+
headers["anthropic-version"] = "2023-06-01";
|
|
6287
|
+
let response;
|
|
6288
|
+
try {
|
|
6289
|
+
response = await fetchImpl(probe.url, { method: probe.method, headers, redirect: "manual", signal: AbortSignal.timeout(1e4) });
|
|
6290
|
+
} catch {
|
|
6291
|
+
throw new Fault(502, "provider_auth_unavailable", "Provider authentication check could not reach the configured authority. Retry without changing accounts.");
|
|
6292
|
+
}
|
|
6293
|
+
const status = response.status;
|
|
6294
|
+
await response.body?.cancel().catch(() => {});
|
|
6295
|
+
if (status >= 200 && status < 300)
|
|
6296
|
+
return { authenticated: true, status };
|
|
6297
|
+
if (status === 401 || status === 403)
|
|
6298
|
+
return { authenticated: false, status };
|
|
6299
|
+
if (status >= 300 && status < 400)
|
|
6300
|
+
throw new Fault(502, "provider_auth_unavailable", "Provider authentication check returned a redirect; credentials were not forwarded.");
|
|
6301
|
+
throw new Fault(502, "provider_auth_unavailable", `Provider authentication check returned HTTP ${status}; the selected credential was not replaced.`);
|
|
6302
|
+
}
|
|
6303
|
+
function providerCredentialFingerprint(provider) {
|
|
6304
|
+
return createHash5("sha256").update(JSON.stringify({
|
|
6305
|
+
id: provider.id,
|
|
6306
|
+
baseUrl: provider.baseUrl,
|
|
6307
|
+
protocol: provider.protocol,
|
|
6308
|
+
authStyle: provider.authStyle ?? "bearer",
|
|
6309
|
+
credentialEnv: provider.credentialEnv ?? null,
|
|
6310
|
+
credentialCheck: provider.credentialCheck ?? null
|
|
6311
|
+
})).digest("hex");
|
|
6312
|
+
}
|
|
6313
|
+
function preparedProviderCredential(provider, credential, fields) {
|
|
6314
|
+
const providerFingerprint = providerCredentialFingerprint(provider);
|
|
6315
|
+
const prepared = { ...fields, providerFingerprint };
|
|
6316
|
+
Object.defineProperty(prepared, "resolveCredential", { enumerable: false, configurable: false, writable: false, value: async (candidate) => {
|
|
6317
|
+
if (providerCredentialFingerprint(candidate) !== providerFingerprint)
|
|
6318
|
+
throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
|
|
6319
|
+
return credential;
|
|
6320
|
+
} });
|
|
6321
|
+
return Object.freeze(prepared);
|
|
6322
|
+
}
|
|
6323
|
+
async function ensureProviderCredential(provider, options = {}) {
|
|
6324
|
+
if (!provider.credentialEnv)
|
|
6325
|
+
return preparedProviderCredential(provider, undefined, { source: "not-required", configured: false, verified: false });
|
|
6326
|
+
const resolver = options.resolver ?? new CredentialResolver(options.env ?? process.env);
|
|
6327
|
+
const existing = await resolver.bindings.get(provider.credentialEnv);
|
|
6328
|
+
let credential = await resolver.resolve(provider);
|
|
6329
|
+
if (existing && !credential)
|
|
6330
|
+
throw new Fault(422, "credential_binding_unavailable", "The selected credential binding did not provide a usable value; no alternate account was selected.");
|
|
6331
|
+
let configured = false;
|
|
6332
|
+
if (!credential) {
|
|
6333
|
+
if (!(options.interactive ?? (process.stdin.isTTY && process.stderr.isTTY)))
|
|
6334
|
+
throw new Fault(400, "credential_setup_required", `Provider credential setup is required. Run: ${providerCredentialSetupCommand(provider)}. Or provide ${provider.credentialEnv} in this launch process.`);
|
|
6335
|
+
const discover = options.discoverVaultReferences ?? ((request) => discoverVaultReferences(request.provider, options.env ?? process.env, options.vaultExecutable));
|
|
6336
|
+
let matches;
|
|
6337
|
+
try {
|
|
6338
|
+
matches = await discover({ provider, credentialEnv: provider.credentialEnv });
|
|
6339
|
+
} catch (error) {
|
|
6340
|
+
if (error instanceof Fault && error.code === "vault_exec_unavailable")
|
|
6341
|
+
throw new Fault(error.status, error.code, `${error.message} Run: ${providerCredentialSetupCommand(provider)} --vault-cli /absolute/path/to/secrets.`);
|
|
6342
|
+
throw error;
|
|
6343
|
+
}
|
|
6344
|
+
if (!matches.length)
|
|
6345
|
+
throw new Fault(404, "credential_match_missing", `No matching Hasna Secrets credential reference was found for ${provider.name}. Run: ${providerCredentialSetupCommand(provider)}.`);
|
|
6346
|
+
const select = options.selectVaultReference ?? selectVaultReference;
|
|
6347
|
+
const candidate = await select({ provider, matches });
|
|
6348
|
+
if (!candidate)
|
|
6349
|
+
throw new CommandInterrupted(130, "Credential setup was cancelled; no binding was saved and no harness was started.");
|
|
6350
|
+
const selected = matches.find((match) => match.account === candidate.account && match.key === candidate.key && match.executable === candidate.executable && JSON.stringify(match.operator) === JSON.stringify(candidate.operator));
|
|
6351
|
+
if (!selected)
|
|
6352
|
+
throw new Fault(400, "credential_selection_invalid", "Choose one of the displayed credential references.");
|
|
6353
|
+
const source = { kind: "vault", key: selected.key, ...selected.url ? { url: selected.url } : {}, executable: selected.executable, operator: selected.operator };
|
|
6354
|
+
await resolver.bindings.bind(parse(credentialBindingSchema, { schema: 1, credentialEnv: provider.credentialEnv, origins: credentialOrigins(provider), requireProviderAuthentication: true, source }));
|
|
6355
|
+
configured = true;
|
|
6356
|
+
credential = await resolver.resolve(provider);
|
|
6357
|
+
if (!credential)
|
|
6358
|
+
throw new Fault(422, "vault_delivery_failed", "The selected credential reference did not provide a usable value; no alternate account was selected.");
|
|
6359
|
+
}
|
|
6360
|
+
const verify = options.verifyProviderAuthentication ?? ((request) => verifyProviderAuthentication(request));
|
|
6361
|
+
const result = await verify({ provider, credential });
|
|
6362
|
+
if (result.unsupported) {
|
|
6363
|
+
if (configured || existing?.requireProviderAuthentication)
|
|
6364
|
+
throw new Fault(422, "provider_auth_check_unsupported", `This provider has no configured non-inference authentication check.${configured ? " The selected binding was preserved." : ""} Configure credentialCheck before launch; no unverified credential was sent.`);
|
|
6365
|
+
return preparedProviderCredential(provider, credential, { source: existing ? "binding" : "environment", configured, verified: false });
|
|
6366
|
+
}
|
|
6367
|
+
if (!result.authenticated)
|
|
6368
|
+
throw new Fault(401, "provider_credential_rejected", `The provider rejected the selected credential${result.status ? ` with HTTP ${result.status}` : ""}. No alternate account was selected.${existing || configured ? ` To choose a different reference, run: switcher credentials remove ${provider.credentialEnv}.` : ""}`);
|
|
6369
|
+
return preparedProviderCredential(provider, credential, { source: existing || configured ? "binding" : "environment", configured, verified: true });
|
|
6370
|
+
}
|
|
6371
|
+
function catalogRequiresCredential(provider) {
|
|
6372
|
+
if (provider.manualModels.length)
|
|
6373
|
+
return false;
|
|
6374
|
+
return (provider.catalogAuthStyle ?? provider.authStyle) !== "none" && Boolean(provider.catalogCredentialEnv ?? provider.credentialEnv);
|
|
6375
|
+
}
|
|
6376
|
+
async function launchCatalog(client, provider, dryRun = false, options = {}) {
|
|
6377
|
+
if (!dryRun && options.clientSide) {
|
|
6378
|
+
const origins = credentialOrigins(provider);
|
|
6379
|
+
const resolve = async (candidate) => {
|
|
6380
|
+
if (options.credential && candidate.credentialEnv === provider.credentialEnv && origins.includes(new URL(candidate.baseUrl).origin))
|
|
6381
|
+
return options.credential;
|
|
6382
|
+
return options.resolveCredential?.(candidate);
|
|
6383
|
+
};
|
|
6384
|
+
const catalog = await discover(provider, {}, resolve);
|
|
6385
|
+
return client.saveCatalog(provider.id, provider.version, catalog);
|
|
6386
|
+
}
|
|
6387
|
+
if (!dryRun || !catalogRequiresCredential(provider))
|
|
6388
|
+
return client.refreshModels(provider.id);
|
|
6389
|
+
const models = [];
|
|
6390
|
+
let offset = 0, refreshedAt, source, total;
|
|
6391
|
+
for (let pageNumber = 0;pageNumber < 10; pageNumber++) {
|
|
6392
|
+
let page;
|
|
6393
|
+
try {
|
|
6394
|
+
page = await client.listModels(provider.id, { limit: 1000, offset });
|
|
6395
|
+
} catch (error) {
|
|
6396
|
+
if (absent(error))
|
|
6397
|
+
throw new Fault(400, "dry_run_catalog_unavailable", `Dry-run will not retrieve provider credentials. Refresh ${provider.id} explicitly with switcher models ${provider.id} --refresh, then rerun the plan.`);
|
|
6398
|
+
throw error;
|
|
6399
|
+
}
|
|
6400
|
+
if (total === undefined) {
|
|
6401
|
+
total = page.total;
|
|
6402
|
+
refreshedAt = page.refreshedAt;
|
|
6403
|
+
source = page.source;
|
|
6404
|
+
} else if (total !== page.total || refreshedAt !== page.refreshedAt || source !== page.source)
|
|
6405
|
+
throw new Fault(409, "catalog_changed", "The cached catalog changed while the dry-run plan was being read; retry.");
|
|
6406
|
+
for (const row of page.data) {
|
|
6407
|
+
const { codingEligible: _codingEligible, expired: _expired, ...model } = row;
|
|
6408
|
+
models.push(model);
|
|
6409
|
+
}
|
|
6410
|
+
offset += page.data.length;
|
|
6411
|
+
if (offset >= page.total)
|
|
6412
|
+
break;
|
|
6413
|
+
if (!page.data.length)
|
|
6414
|
+
throw new Fault(502, "invalid_catalog", "The cached catalog page did not advance.");
|
|
6415
|
+
}
|
|
6416
|
+
if (total === undefined || models.length !== total || !refreshedAt || !source)
|
|
6417
|
+
throw new Fault(502, "invalid_catalog", "The cached catalog exceeds the bounded dry-run reader or is incomplete.");
|
|
6418
|
+
return { models, refreshedAt, source };
|
|
6419
|
+
}
|
|
6420
|
+
|
|
5469
6421
|
// src/mcp.ts
|
|
5470
6422
|
var server = new McpServer({ name: "switcher", version: VERSION });
|
|
5471
6423
|
var runtime;
|
|
6424
|
+
var credentials = new CredentialResolver;
|
|
5472
6425
|
var clientFromEnv2 = () => {
|
|
5473
6426
|
if (!runtime)
|
|
5474
6427
|
throw new Fault(503, "unavailable", "Switcher API runtime is not open.");
|
|
5475
6428
|
return runtime.client;
|
|
5476
6429
|
};
|
|
5477
|
-
var page = { limit:
|
|
6430
|
+
var page = { limit: z7.number().int().min(1).max(1000).optional(), offset: z7.number().int().nonnegative().optional(), search: z7.string().optional() };
|
|
5478
6431
|
function tool(name, description, schema, run) {
|
|
5479
6432
|
server.tool(name, description, schema, async (input) => {
|
|
5480
6433
|
try {
|
|
@@ -5485,33 +6438,40 @@ function tool(name, description, schema, run) {
|
|
|
5485
6438
|
});
|
|
5486
6439
|
}
|
|
5487
6440
|
tool("providers_list", "List provider profiles.", page, (p) => clientFromEnv2().listProviders(p));
|
|
5488
|
-
tool("providers_get", "Get a provider.", { id:
|
|
6441
|
+
tool("providers_get", "Get a provider.", { id: z7.string() }, (p) => clientFromEnv2().getProvider(p.id));
|
|
5489
6442
|
tool("providers_create", "Create a provider using credential environment references only.", providerInputSchema.innerType().shape, (p) => clientFromEnv2().createProvider(p));
|
|
5490
|
-
tool("providers_update", "Replace a provider at its current version.", { provider: providerInputSchema, version:
|
|
5491
|
-
tool("providers_delete", "Delete an unreferenced provider.", { id:
|
|
5492
|
-
tool("models_list", "List catalog with capability information.", { id:
|
|
5493
|
-
const { id
|
|
5494
|
-
return clientFromEnv2().listModels(
|
|
6443
|
+
tool("providers_update", "Replace a provider at its current version.", { provider: providerInputSchema, version: z7.number().int() }, (p) => clientFromEnv2().updateProvider(p.provider, p.version));
|
|
6444
|
+
tool("providers_delete", "Delete an unreferenced provider.", { id: z7.string(), version: z7.number().int() }, (p) => clientFromEnv2().deleteProvider(p.id, p.version));
|
|
6445
|
+
tool("models_list", "List catalog with capability information.", { id: z7.string(), ...page }, (p) => {
|
|
6446
|
+
const { id, ...rest } = p;
|
|
6447
|
+
return clientFromEnv2().listModels(id, rest);
|
|
6448
|
+
});
|
|
6449
|
+
tool("models_add", "Add saved model metadata; discovery stays active unless the provider uses a manual catalog.", { providerId: z7.string(), model: modelSchema }, (p) => clientFromEnv2().addModel(p.providerId, p.model));
|
|
6450
|
+
tool("models_update", "Replace all saved metadata for a configured model.", { providerId: z7.string(), model: modelSchema }, (p) => clientFromEnv2().updateModel(p.providerId, p.model));
|
|
6451
|
+
tool("models_remove", "Remove saved model metadata; upstream catalog entries remain.", { providerId: z7.string(), modelId: modelSchema.shape.id }, (p) => clientFromEnv2().removeModel(p.providerId, p.modelId));
|
|
6452
|
+
tool("models_refresh", "Discover provider models.", { id: z7.string() }, async (p) => {
|
|
6453
|
+
const client = clientFromEnv2(), provider = await client.getProvider(p.id);
|
|
6454
|
+
if (runtime?.mode !== "remote")
|
|
6455
|
+
return client.refreshModels(provider.id);
|
|
6456
|
+
const prepared = await ensureProviderCredential(provider, { interactive: false, resolver: credentials });
|
|
6457
|
+
const credential = await prepared.resolveCredential(provider);
|
|
6458
|
+
return launchCatalog(client, provider, false, { clientSide: true, credential, resolveCredential: (candidate) => credentials.resolve(candidate) });
|
|
5495
6459
|
});
|
|
5496
|
-
tool("models_add", "Add saved model metadata; discovery stays active unless the provider uses a manual catalog.", { providerId: z5.string(), model: modelSchema }, (p) => clientFromEnv2().addModel(p.providerId, p.model));
|
|
5497
|
-
tool("models_update", "Replace all saved metadata for a configured model.", { providerId: z5.string(), model: modelSchema }, (p) => clientFromEnv2().updateModel(p.providerId, p.model));
|
|
5498
|
-
tool("models_remove", "Remove saved model metadata; upstream catalog entries remain.", { providerId: z5.string(), modelId: modelSchema.shape.id }, (p) => clientFromEnv2().removeModel(p.providerId, p.modelId));
|
|
5499
|
-
tool("models_refresh", "Discover provider models.", { id: z5.string() }, (p) => clientFromEnv2().refreshModels(p.id));
|
|
5500
6460
|
tool("profiles_list", "List harness launch profiles.", page, (p) => clientFromEnv2().listProfiles(p));
|
|
5501
|
-
tool("profiles_get", "Get a harness profile.", { id:
|
|
6461
|
+
tool("profiles_get", "Get a harness profile.", { id: z7.string() }, (p) => clientFromEnv2().getProfile(p.id));
|
|
5502
6462
|
tool("profiles_create", "Create a harness launch profile.", profileInputSchema.shape, (p) => clientFromEnv2().createProfile(p));
|
|
5503
|
-
tool("profiles_update", "Replace a harness profile at its version.", { profile: profileInputSchema, version:
|
|
5504
|
-
tool("profiles_delete", "Delete a profile without run history.", { id:
|
|
5505
|
-
tool("launch_plan", "Validate a local launch plan; does not execute a remote process.", { profileId:
|
|
6463
|
+
tool("profiles_update", "Replace a harness profile at its version.", { profile: profileInputSchema, version: z7.number().int() }, (p) => clientFromEnv2().updateProfile(p.profile, p.version));
|
|
6464
|
+
tool("profiles_delete", "Delete a profile without run history.", { id: z7.string(), version: z7.number().int() }, (p) => clientFromEnv2().deleteProfile(p.id, p.version));
|
|
6465
|
+
tool("launch_plan", "Validate a local launch plan; does not execute a remote process.", { profileId: z7.string() }, (p) => clientFromEnv2().launchPlan(p.profileId));
|
|
5506
6466
|
tool("runs_list", "List launch metadata.", page, (p) => clientFromEnv2().listRuns(p));
|
|
5507
|
-
tool("runs_get", "Get launch metadata.", { id:
|
|
6467
|
+
tool("runs_get", "Get launch metadata.", { id: z7.string() }, (p) => clientFromEnv2().getRun(p.id));
|
|
5508
6468
|
if (process.argv.includes("--version"))
|
|
5509
6469
|
console.log(VERSION);
|
|
5510
6470
|
else if (process.argv.includes("--help"))
|
|
5511
6471
|
console.log("switcher-mcp: authenticated Switcher API tools over MCP stdio. Resolves API URL/key through @hasna/contracts (Keychain, canonical config/credentials, or environment). With nothing configured it exits 1 before answering initialize and names those sources; HASNA_SWITCHER_LOCAL=1 deliberately serves the on-box store instead.");
|
|
5512
6472
|
else {
|
|
5513
6473
|
try {
|
|
5514
|
-
runtime = await openCliRuntime(process.env);
|
|
6474
|
+
runtime = await openCliRuntime(process.env, (provider) => credentials.resolve(provider));
|
|
5515
6475
|
} catch (error) {
|
|
5516
6476
|
const code = error instanceof Fault ? error.code : "remote_api_config_error";
|
|
5517
6477
|
console.error(`${code.toUpperCase()}: ${error instanceof Error ? error.message : "Switcher API configuration could not be resolved."}`);
|