@hasna/switcher 0.2.9 → 0.2.10
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/README.md +3 -1
- package/dist/cli/index.js +91 -39
- package/dist/mcp/index.js +78 -24
- package/dist/opencode-authentication.d.ts +11 -0
- package/dist/serve/index.js +2 -2
- package/openapi.json +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -412,7 +412,9 @@ Bind an existing vault key once, then launch without an external wrapper. New bi
|
|
|
412
412
|
|
|
413
413
|
Real launches now preflight the local inference credential before catalog refresh and before an interactive model picker. An existing environment credential is preserved without creating a binding. An existing binding remains authoritative, including its exact Secrets operator account and allowed provider origins; a locked source, an unauthorized destination, or rejected provider credential is terminal and never falls through to another account.
|
|
414
414
|
|
|
415
|
-
When a provider credential is missing in an interactive terminal, Switcher uses the trusted `secrets` executable on `PATH` to search metadata only. It displays the selected Secrets account/source and matching vault key references, asks which reference to bind, saves that reference through the existing immutable binding store, resolves the value through the authenticated loopback delivery path, and performs a bounded
|
|
415
|
+
When a provider credential is missing in an interactive terminal, Switcher uses the trusted `secrets` executable on `PATH` to search metadata only. It displays the selected Secrets account/source and matching vault key references, asks which reference to bind, saves that reference through the existing immutable binding store, resolves the value through the authenticated loopback delivery path, and performs a bounded provider authentication check before continuing the original launch. OpenRouter uses its authenticated `GET /api/v1/key` metadata endpoint; its public model catalog is never treated as proof that a key works. Custom providers may declare a relative `credentialCheck` (`GET` or `HEAD`) in provider JSON. Catalog configuration alone is never inferred to validate a credential because a catalog may be public or ignore invalid authorization.
|
|
416
|
+
|
|
417
|
+
OpenCode Zen checks its supplied key with one fixed synthetic question to the documented free `jev-1.13-free` model. Before sending the selected key, Switcher requires rejection of invalid keys through both the legacy and migrated routes: an existing legacy key may also have been migrated. Anonymous `public` credentials and whitespace-containing tokens are rejected. The check uses a shared ten-second deadline and bounded JSON responses, follows no redirects, sends no user prompt or project data, and has no paid-model fallback. The free alias is a limited-time provider offering; if the check becomes unavailable, launch stops with the selected binding preserved. This proves key authentication, not access to every paid model. The coding model and provider chosen for the actual launch remain unchanged. An explicitly configured `credentialCheck` retains precedence. See [OpenCode's Jev endpoint and free-model pricing](https://opencode.ai/docs/zen/#jev).
|
|
416
418
|
|
|
417
419
|
Discovery requests Secrets' full metadata array with a 257-row limit, preserving compatibility with compact-default and older Secrets CLIs. The extra row detects searches exceeding the 256-reference limit; discovery refuses these results before deduplication and also caps the combined references across searches. Each response remains limited to 256 KiB. This search never requests secret values; broader matches require an explicit vault-key binding.
|
|
418
420
|
|
package/dist/cli/index.js
CHANGED
|
@@ -514,7 +514,7 @@ function canonicalPolicyJSON(value) {
|
|
|
514
514
|
return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
515
515
|
}
|
|
516
516
|
// package.json
|
|
517
|
-
var version = "0.2.
|
|
517
|
+
var version = "0.2.10";
|
|
518
518
|
|
|
519
519
|
// src/version.ts
|
|
520
520
|
var VERSION = version;
|
|
@@ -2543,7 +2543,7 @@ var openapi_default = {
|
|
|
2543
2543
|
openapi: "3.0.3",
|
|
2544
2544
|
info: {
|
|
2545
2545
|
title: "Switcher API",
|
|
2546
|
-
version: "0.2.
|
|
2546
|
+
version: "0.2.10",
|
|
2547
2547
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2548
2548
|
},
|
|
2549
2549
|
security: [
|
|
@@ -11327,12 +11327,62 @@ import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile17 } from "
|
|
|
11327
11327
|
import { join as join20, resolve as resolve11 } from "path";
|
|
11328
11328
|
|
|
11329
11329
|
// src/provider-credential-onboarding.ts
|
|
11330
|
-
import { z as
|
|
11330
|
+
import { z as z9 } from "zod";
|
|
11331
11331
|
import { createHash as createHash11 } from "crypto";
|
|
11332
11332
|
import { createInterface } from "readline/promises";
|
|
11333
11333
|
|
|
11334
|
-
// src/
|
|
11334
|
+
// src/opencode-authentication.ts
|
|
11335
11335
|
import { z as z7 } from "zod";
|
|
11336
|
+
var endpoint3 = "https://opencode.ai/zen/v1/systemone";
|
|
11337
|
+
var body = JSON.stringify({
|
|
11338
|
+
model: "jev-1.13-free",
|
|
11339
|
+
state: "The fixed test number is 7.",
|
|
11340
|
+
questions: { match: { type: "noul", instructions: "Is the fixed test number 7?" } }
|
|
11341
|
+
});
|
|
11342
|
+
var responseSchema = z7.object({
|
|
11343
|
+
model: z7.enum(["jev-1.13", "jev-1.13.0", "jev-1.13-free"]),
|
|
11344
|
+
answers: z7.object({ match: z7.object({ type: z7.literal("noul"), noul: z7.number().finite().min(0).max(1) }) }),
|
|
11345
|
+
usage: z7.object({ input_tokens: z7.number().int().nonnegative(), output_tokens: z7.number().int().nonnegative() })
|
|
11346
|
+
});
|
|
11347
|
+
var authErrorSchema = z7.object({ error: z7.object({ type: z7.enum(["AuthError", "server_error"]) }) });
|
|
11348
|
+
var unavailable = () => new Fault(502, "provider_auth_unavailable", "OpenCode authentication could not be verified with its free check. The selected credential was preserved; no paid model was requested.");
|
|
11349
|
+
function supportsOpenCodeAuthentication(provider) {
|
|
11350
|
+
return provider.credentialEnv === "SWITCHER_PROVIDER_OPENCODE" && ["https://opencode.ai/zen/v1", "https://opencode.ai/zen/v1/"].includes(provider.baseUrl) && (["openai-chat", "openai-responses"].includes(provider.protocol) ? (provider.authStyle ?? "bearer") === "bearer" : provider.protocol === "anthropic-messages" && provider.authStyle === "x-api-key");
|
|
11351
|
+
}
|
|
11352
|
+
async function verifyOpenCodeAuthentication(credential, fetchImpl) {
|
|
11353
|
+
if (!credential || /[\s\x00-\x1f\x7f]/u.test(credential) || credential.toLowerCase() === "public")
|
|
11354
|
+
return { authenticated: false, status: 401 };
|
|
11355
|
+
const signal = AbortSignal.timeout(1e4);
|
|
11356
|
+
const request = async (value) => {
|
|
11357
|
+
try {
|
|
11358
|
+
const response = await fetchImpl(endpoint3, {
|
|
11359
|
+
method: "POST",
|
|
11360
|
+
redirect: "manual",
|
|
11361
|
+
cache: "no-store",
|
|
11362
|
+
signal,
|
|
11363
|
+
body,
|
|
11364
|
+
headers: { accept: "application/json", "content-type": "application/json", "user-agent": "hasna-switcher/credential-check", authorization: `Bearer ${value}` }
|
|
11365
|
+
});
|
|
11366
|
+
return { status: response.status, data: await boundedJson(response, 16 * 1024) };
|
|
11367
|
+
} catch {
|
|
11368
|
+
throw unavailable();
|
|
11369
|
+
}
|
|
11370
|
+
};
|
|
11371
|
+
for (const invalid3 of ["hasna-switcher-invalid-credential", "oc_sk_invalid"]) {
|
|
11372
|
+
const control = await request(invalid3);
|
|
11373
|
+
if (control.status !== 401 || !authErrorSchema.safeParse(control.data).success)
|
|
11374
|
+
throw unavailable();
|
|
11375
|
+
}
|
|
11376
|
+
const result = await request(credential);
|
|
11377
|
+
if ((result.status === 401 || result.status === 403) && authErrorSchema.safeParse(result.data).success)
|
|
11378
|
+
return { authenticated: false, status: result.status };
|
|
11379
|
+
if (result.status !== 200 || !responseSchema.safeParse(result.data).success)
|
|
11380
|
+
throw unavailable();
|
|
11381
|
+
return { authenticated: true, status: 200 };
|
|
11382
|
+
}
|
|
11383
|
+
|
|
11384
|
+
// src/credentials.ts
|
|
11385
|
+
import { z as z8 } from "zod";
|
|
11336
11386
|
import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
|
|
11337
11387
|
import { constants as constants5 } from "fs";
|
|
11338
11388
|
import { open as open3, readdir as readdir5, unlink, link, lstat as lstat6 } from "fs/promises";
|
|
@@ -11342,27 +11392,27 @@ import { execFile as execFile3, spawn } from "child_process";
|
|
|
11342
11392
|
import { promisify as promisify3 } from "util";
|
|
11343
11393
|
import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
|
|
11344
11394
|
var execute3 = promisify3(execFile3);
|
|
11345
|
-
var reference =
|
|
11346
|
-
var item =
|
|
11347
|
-
var vaultKeySchema =
|
|
11348
|
-
var keychain =
|
|
11349
|
-
var credentialTier =
|
|
11350
|
-
var operator =
|
|
11351
|
-
|
|
11352
|
-
|
|
11353
|
-
|
|
11395
|
+
var reference = z8.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
|
|
11396
|
+
var item = z8.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
|
|
11397
|
+
var vaultKeySchema = z8.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");
|
|
11398
|
+
var keychain = z8.object({ kind: z8.literal("keychain"), service: item, account: item }).strict();
|
|
11399
|
+
var credentialTier = z8.enum(["argument", "override", "pointer", "profile", "keychain", "disk", "env"]);
|
|
11400
|
+
var operator = z8.discriminatedUnion("kind", [
|
|
11401
|
+
z8.object({ kind: z8.literal("contracts"), expectedSource: item.optional(), expectedTier: credentialTier.optional() }).strict(),
|
|
11402
|
+
z8.object({ kind: z8.literal("env") }).strict(),
|
|
11403
|
+
z8.object({ kind: z8.literal("keychain"), account: item.refine((value) => value.trim().length > 0 && value === value.trim(), "Vault account must be nonblank without surrounding whitespace") }).strict()
|
|
11354
11404
|
]);
|
|
11355
|
-
var origin =
|
|
11356
|
-
var credentialBindingSchema =
|
|
11357
|
-
schema:
|
|
11405
|
+
var origin = z8.string().transform((value) => new URL(endpoint(value)).origin);
|
|
11406
|
+
var credentialBindingSchema = z8.object({
|
|
11407
|
+
schema: z8.literal(1),
|
|
11358
11408
|
credentialEnv: reference,
|
|
11359
|
-
origins:
|
|
11360
|
-
requireProviderAuthentication:
|
|
11361
|
-
source:
|
|
11362
|
-
kind:
|
|
11409
|
+
origins: z8.array(origin).min(1).max(30),
|
|
11410
|
+
requireProviderAuthentication: z8.literal(true).optional(),
|
|
11411
|
+
source: z8.discriminatedUnion("kind", [keychain, z8.object({
|
|
11412
|
+
kind: z8.literal("vault"),
|
|
11363
11413
|
key: vaultKeySchema,
|
|
11364
|
-
url:
|
|
11365
|
-
executable:
|
|
11414
|
+
url: z8.string().max(2000).transform(endpoint).optional(),
|
|
11415
|
+
executable: z8.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute15, "Secrets executable must be an absolute path"),
|
|
11366
11416
|
operator
|
|
11367
11417
|
}).strict()])
|
|
11368
11418
|
}).strict().superRefine((binding, ctx) => {
|
|
@@ -11783,13 +11833,13 @@ async function deliverVaultCredential() {
|
|
|
11783
11833
|
// src/provider-credential-onboarding.ts
|
|
11784
11834
|
var absent = (error) => error instanceof SwitcherError && error.status === 404;
|
|
11785
11835
|
var MAX_CREDENTIAL_MATCHES = 256;
|
|
11786
|
-
var secretMetadataSchema =
|
|
11836
|
+
var secretMetadataSchema = z9.object({
|
|
11787
11837
|
key: vaultKeySchema,
|
|
11788
|
-
type:
|
|
11789
|
-
label:
|
|
11790
|
-
expires_at:
|
|
11791
|
-
created_at:
|
|
11792
|
-
updated_at:
|
|
11838
|
+
type: z9.enum(["api_key", "password", "token", "credential", "other"]),
|
|
11839
|
+
label: z9.string().max(1000).nullable().optional(),
|
|
11840
|
+
expires_at: z9.string().max(200).nullable().optional(),
|
|
11841
|
+
created_at: z9.string().max(200),
|
|
11842
|
+
updated_at: z9.string().max(200)
|
|
11793
11843
|
}).strict();
|
|
11794
11844
|
var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
|
|
11795
11845
|
var credentialOrigins = (provider) => {
|
|
@@ -11898,6 +11948,8 @@ function authenticationProbe(provider) {
|
|
|
11898
11948
|
return;
|
|
11899
11949
|
}
|
|
11900
11950
|
async function verifyProviderAuthentication({ provider, credential, fetch: fetchImpl = fetch }) {
|
|
11951
|
+
if (!provider.credentialCheck && supportsOpenCodeAuthentication(provider))
|
|
11952
|
+
return verifyOpenCodeAuthentication(credential, fetchImpl);
|
|
11901
11953
|
const probe = authenticationProbe(provider);
|
|
11902
11954
|
if (!probe)
|
|
11903
11955
|
return { authenticated: false, unsupported: true };
|
|
@@ -13297,10 +13349,10 @@ import { spawn as spawn3 } from "child_process";
|
|
|
13297
13349
|
import { createInterface as createInterface2 } from "readline/promises";
|
|
13298
13350
|
import { basename as basename3, resolve as resolve10 } from "path";
|
|
13299
13351
|
var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
13300
|
-
var
|
|
13352
|
+
var unavailable2 = () => new Fault(422, "codex_session_discovery", "Native Codex session discovery failed. No conversation was started. Retry discovery or provide an exact session ID.");
|
|
13301
13353
|
async function listCodexSessions(prepared, cwd, query) {
|
|
13302
13354
|
if (!Number.isSafeInteger(query.limit) || query.limit < 1 || query.limit > 100 || query.cursor !== undefined && query.cursor.length > 4096 || query.searchTerm !== undefined && query.searchTerm.length > 1024 || cwd.length > 32768 || query.cwd !== undefined && query.cwd.length > 32768)
|
|
13303
|
-
throw
|
|
13355
|
+
throw unavailable2();
|
|
13304
13356
|
const nativeStateEnv = Object.fromEntries(Object.entries(prepared.env).filter(([name]) => ["CODEX_HOME", "CODEX_SQLITE_HOME"].includes(name)));
|
|
13305
13357
|
const child = spawn3(prepared.executable, [...prepared.args, "app-server"], {
|
|
13306
13358
|
cwd,
|
|
@@ -13321,7 +13373,7 @@ async function listCodexSessions(prepared, cwd, query) {
|
|
|
13321
13373
|
killTimer ??= setTimeout(() => child.kill("SIGKILL"), 2000);
|
|
13322
13374
|
killTimer.unref();
|
|
13323
13375
|
};
|
|
13324
|
-
const fail = (error =
|
|
13376
|
+
const fail = (error = unavailable2()) => {
|
|
13325
13377
|
if (!done) {
|
|
13326
13378
|
done = true;
|
|
13327
13379
|
rejectPage(error);
|
|
@@ -13348,7 +13400,7 @@ async function listCodexSessions(prepared, cwd, query) {
|
|
|
13348
13400
|
try {
|
|
13349
13401
|
responseBytes += chunk.length;
|
|
13350
13402
|
if (responseBytes > 16 * 1024 * 1024 || pending.length + chunk.length > 8 * 1024 * 1024)
|
|
13351
|
-
throw
|
|
13403
|
+
throw unavailable2();
|
|
13352
13404
|
pending = Buffer.concat([pending, chunk]);
|
|
13353
13405
|
let end;
|
|
13354
13406
|
while ((end = pending.indexOf(10)) >= 0) {
|
|
@@ -13358,20 +13410,20 @@ async function listCodexSessions(prepared, cwd, query) {
|
|
|
13358
13410
|
continue;
|
|
13359
13411
|
const message = JSON.parse(line.toString("utf8"));
|
|
13360
13412
|
if (!object6(message))
|
|
13361
|
-
throw
|
|
13413
|
+
throw unavailable2();
|
|
13362
13414
|
if (message.id === 1) {
|
|
13363
13415
|
if (initialized || message.error || !object6(message.result))
|
|
13364
|
-
throw
|
|
13416
|
+
throw unavailable2();
|
|
13365
13417
|
initialized = true;
|
|
13366
13418
|
send({ method: "initialized" });
|
|
13367
13419
|
send({ id: 2, method: "thread/list", params: { ...query, modelProviders: [], useStateDbOnly: false, sortKey: "updated_at", sortDirection: "desc" } });
|
|
13368
13420
|
} else if (message.id === 2) {
|
|
13369
13421
|
const page = message.result;
|
|
13370
13422
|
if (!initialized || message.error || !object6(page) || !Array.isArray(page.data) || page.data.length > query.limit || !(page.nextCursor === null || typeof page.nextCursor === "string") || typeof page.nextCursor === "string" && page.nextCursor.length > 4096)
|
|
13371
|
-
throw
|
|
13423
|
+
throw unavailable2();
|
|
13372
13424
|
const data2 = page.data.map((thread) => {
|
|
13373
13425
|
if (!object6(thread) || typeof thread.id !== "string" || !/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(thread.id) || typeof thread.cwd !== "string" || thread.cwd.length > 32768 || thread.name != null && typeof thread.name !== "string" || thread.preview !== undefined && typeof thread.preview !== "string")
|
|
13374
|
-
throw
|
|
13426
|
+
throw unavailable2();
|
|
13375
13427
|
return { id: thread.id, cwd: thread.cwd, name: thread.name, preview: thread.preview };
|
|
13376
13428
|
});
|
|
13377
13429
|
done = true;
|
|
@@ -13421,7 +13473,7 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
|
|
|
13421
13473
|
if (codexOptionTakesValue(nativeArgs[i])) {
|
|
13422
13474
|
if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
|
|
13423
13475
|
if (!nativeArgs[i + 1])
|
|
13424
|
-
throw
|
|
13476
|
+
throw unavailable2();
|
|
13425
13477
|
effectiveCwd = resolve10(cwd, nativeArgs[i + 1]);
|
|
13426
13478
|
}
|
|
13427
13479
|
i++;
|
|
@@ -13678,11 +13730,11 @@ async function launch(client, profileId, options = {}) {
|
|
|
13678
13730
|
} else
|
|
13679
13731
|
routingEventsDropped = Math.min(1e6, routingEventsDropped + 1);
|
|
13680
13732
|
};
|
|
13681
|
-
const finishRunOnce = async (candidate,
|
|
13733
|
+
const finishRunOnce = async (candidate, body2, message) => {
|
|
13682
13734
|
if (runFinalized)
|
|
13683
13735
|
return;
|
|
13684
13736
|
runFinalized = true;
|
|
13685
|
-
await client.finishRun(candidate.id, candidate.version, { ...
|
|
13737
|
+
await client.finishRun(candidate.id, candidate.version, { ...body2, routingEvents, routingEventsDropped }, crypto.randomUUID()).catch(() => console.error(message));
|
|
13686
13738
|
};
|
|
13687
13739
|
let cancelPreparation;
|
|
13688
13740
|
const preparationCancellation = new Promise((_, reject2) => {
|
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 z8 } from "zod";
|
|
8
8
|
|
|
9
9
|
// src/runtime.ts
|
|
10
10
|
import { randomBytes } from "crypto";
|
|
@@ -69,7 +69,7 @@ function canonicalPolicyJSON(value) {
|
|
|
69
69
|
return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
70
70
|
}
|
|
71
71
|
// package.json
|
|
72
|
-
var version = "0.2.
|
|
72
|
+
var version = "0.2.10";
|
|
73
73
|
|
|
74
74
|
// src/version.ts
|
|
75
75
|
var VERSION = version;
|
|
@@ -1197,7 +1197,7 @@ var openapi_default = {
|
|
|
1197
1197
|
openapi: "3.0.3",
|
|
1198
1198
|
info: {
|
|
1199
1199
|
title: "Switcher API",
|
|
1200
|
-
version: "0.2.
|
|
1200
|
+
version: "0.2.10",
|
|
1201
1201
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
1202
1202
|
},
|
|
1203
1203
|
security: [
|
|
@@ -6216,18 +6216,70 @@ async function fetchVaultCredential(binding, env) {
|
|
|
6216
6216
|
}
|
|
6217
6217
|
|
|
6218
6218
|
// src/provider-credential-onboarding.ts
|
|
6219
|
-
import { z as
|
|
6219
|
+
import { z as z7 } from "zod";
|
|
6220
6220
|
import { createHash as createHash5 } from "crypto";
|
|
6221
6221
|
import { createInterface } from "readline/promises";
|
|
6222
|
+
|
|
6223
|
+
// src/opencode-authentication.ts
|
|
6224
|
+
import { z as z6 } from "zod";
|
|
6225
|
+
var endpoint2 = "https://opencode.ai/zen/v1/systemone";
|
|
6226
|
+
var body = JSON.stringify({
|
|
6227
|
+
model: "jev-1.13-free",
|
|
6228
|
+
state: "The fixed test number is 7.",
|
|
6229
|
+
questions: { match: { type: "noul", instructions: "Is the fixed test number 7?" } }
|
|
6230
|
+
});
|
|
6231
|
+
var responseSchema = z6.object({
|
|
6232
|
+
model: z6.enum(["jev-1.13", "jev-1.13.0", "jev-1.13-free"]),
|
|
6233
|
+
answers: z6.object({ match: z6.object({ type: z6.literal("noul"), noul: z6.number().finite().min(0).max(1) }) }),
|
|
6234
|
+
usage: z6.object({ input_tokens: z6.number().int().nonnegative(), output_tokens: z6.number().int().nonnegative() })
|
|
6235
|
+
});
|
|
6236
|
+
var authErrorSchema = z6.object({ error: z6.object({ type: z6.enum(["AuthError", "server_error"]) }) });
|
|
6237
|
+
var unavailable = () => new Fault(502, "provider_auth_unavailable", "OpenCode authentication could not be verified with its free check. The selected credential was preserved; no paid model was requested.");
|
|
6238
|
+
function supportsOpenCodeAuthentication(provider) {
|
|
6239
|
+
return provider.credentialEnv === "SWITCHER_PROVIDER_OPENCODE" && ["https://opencode.ai/zen/v1", "https://opencode.ai/zen/v1/"].includes(provider.baseUrl) && (["openai-chat", "openai-responses"].includes(provider.protocol) ? (provider.authStyle ?? "bearer") === "bearer" : provider.protocol === "anthropic-messages" && provider.authStyle === "x-api-key");
|
|
6240
|
+
}
|
|
6241
|
+
async function verifyOpenCodeAuthentication(credential, fetchImpl) {
|
|
6242
|
+
if (!credential || /[\s\x00-\x1f\x7f]/u.test(credential) || credential.toLowerCase() === "public")
|
|
6243
|
+
return { authenticated: false, status: 401 };
|
|
6244
|
+
const signal = AbortSignal.timeout(1e4);
|
|
6245
|
+
const request = async (value) => {
|
|
6246
|
+
try {
|
|
6247
|
+
const response = await fetchImpl(endpoint2, {
|
|
6248
|
+
method: "POST",
|
|
6249
|
+
redirect: "manual",
|
|
6250
|
+
cache: "no-store",
|
|
6251
|
+
signal,
|
|
6252
|
+
body,
|
|
6253
|
+
headers: { accept: "application/json", "content-type": "application/json", "user-agent": "hasna-switcher/credential-check", authorization: `Bearer ${value}` }
|
|
6254
|
+
});
|
|
6255
|
+
return { status: response.status, data: await boundedJson(response, 16 * 1024) };
|
|
6256
|
+
} catch {
|
|
6257
|
+
throw unavailable();
|
|
6258
|
+
}
|
|
6259
|
+
};
|
|
6260
|
+
for (const invalid of ["hasna-switcher-invalid-credential", "oc_sk_invalid"]) {
|
|
6261
|
+
const control = await request(invalid);
|
|
6262
|
+
if (control.status !== 401 || !authErrorSchema.safeParse(control.data).success)
|
|
6263
|
+
throw unavailable();
|
|
6264
|
+
}
|
|
6265
|
+
const result = await request(credential);
|
|
6266
|
+
if ((result.status === 401 || result.status === 403) && authErrorSchema.safeParse(result.data).success)
|
|
6267
|
+
return { authenticated: false, status: result.status };
|
|
6268
|
+
if (result.status !== 200 || !responseSchema.safeParse(result.data).success)
|
|
6269
|
+
throw unavailable();
|
|
6270
|
+
return { authenticated: true, status: 200 };
|
|
6271
|
+
}
|
|
6272
|
+
|
|
6273
|
+
// src/provider-credential-onboarding.ts
|
|
6222
6274
|
var absent = (error) => error instanceof SwitcherError && error.status === 404;
|
|
6223
6275
|
var MAX_CREDENTIAL_MATCHES = 256;
|
|
6224
|
-
var secretMetadataSchema =
|
|
6276
|
+
var secretMetadataSchema = z7.object({
|
|
6225
6277
|
key: vaultKeySchema,
|
|
6226
|
-
type:
|
|
6227
|
-
label:
|
|
6228
|
-
expires_at:
|
|
6229
|
-
created_at:
|
|
6230
|
-
updated_at:
|
|
6278
|
+
type: z7.enum(["api_key", "password", "token", "credential", "other"]),
|
|
6279
|
+
label: z7.string().max(1000).nullable().optional(),
|
|
6280
|
+
expires_at: z7.string().max(200).nullable().optional(),
|
|
6281
|
+
created_at: z7.string().max(200),
|
|
6282
|
+
updated_at: z7.string().max(200)
|
|
6231
6283
|
}).strict();
|
|
6232
6284
|
var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
|
|
6233
6285
|
var credentialOrigins = (provider) => {
|
|
@@ -6336,6 +6388,8 @@ function authenticationProbe(provider) {
|
|
|
6336
6388
|
return;
|
|
6337
6389
|
}
|
|
6338
6390
|
async function verifyProviderAuthentication({ provider, credential, fetch: fetchImpl = fetch }) {
|
|
6391
|
+
if (!provider.credentialCheck && supportsOpenCodeAuthentication(provider))
|
|
6392
|
+
return verifyOpenCodeAuthentication(credential, fetchImpl);
|
|
6339
6393
|
const probe = authenticationProbe(provider);
|
|
6340
6394
|
if (!probe)
|
|
6341
6395
|
return { authenticated: false, unsupported: true };
|
|
@@ -6487,7 +6541,7 @@ var clientFromEnv2 = () => {
|
|
|
6487
6541
|
throw new Fault(503, "unavailable", "Switcher API runtime is not open.");
|
|
6488
6542
|
return runtime.client;
|
|
6489
6543
|
};
|
|
6490
|
-
var page = { limit:
|
|
6544
|
+
var page = { limit: z8.number().int().min(1).max(1000).optional(), offset: z8.number().int().nonnegative().optional(), search: z8.string().optional() };
|
|
6491
6545
|
function tool(name, description, schema, run) {
|
|
6492
6546
|
server.tool(name, description, schema, async (input) => {
|
|
6493
6547
|
try {
|
|
@@ -6498,18 +6552,18 @@ function tool(name, description, schema, run) {
|
|
|
6498
6552
|
});
|
|
6499
6553
|
}
|
|
6500
6554
|
tool("providers_list", "List provider profiles.", page, (p) => clientFromEnv2().listProviders(p));
|
|
6501
|
-
tool("providers_get", "Get a provider.", { id:
|
|
6555
|
+
tool("providers_get", "Get a provider.", { id: z8.string() }, (p) => clientFromEnv2().getProvider(p.id));
|
|
6502
6556
|
tool("providers_create", "Create a provider using credential environment references only.", providerInputSchema.innerType().shape, (p) => clientFromEnv2().createProvider(p));
|
|
6503
|
-
tool("providers_update", "Replace a provider at its current version.", { provider: providerInputSchema, version:
|
|
6504
|
-
tool("providers_delete", "Delete an unreferenced provider.", { id:
|
|
6505
|
-
tool("models_list", "List catalog with capability information.", { id:
|
|
6557
|
+
tool("providers_update", "Replace a provider at its current version.", { provider: providerInputSchema, version: z8.number().int() }, (p) => clientFromEnv2().updateProvider(p.provider, p.version));
|
|
6558
|
+
tool("providers_delete", "Delete an unreferenced provider.", { id: z8.string(), version: z8.number().int() }, (p) => clientFromEnv2().deleteProvider(p.id, p.version));
|
|
6559
|
+
tool("models_list", "List catalog with capability information.", { id: z8.string(), ...page }, (p) => {
|
|
6506
6560
|
const { id: id2, ...rest } = p;
|
|
6507
6561
|
return clientFromEnv2().listModels(id2, rest);
|
|
6508
6562
|
});
|
|
6509
|
-
tool("models_add", "Add saved model metadata; discovery stays active unless the provider uses a manual catalog.", { providerId:
|
|
6510
|
-
tool("models_update", "Replace all saved metadata for a configured model.", { providerId:
|
|
6511
|
-
tool("models_remove", "Remove saved model metadata; upstream catalog entries remain.", { providerId:
|
|
6512
|
-
tool("models_refresh", "Discover provider models.", { id:
|
|
6563
|
+
tool("models_add", "Add saved model metadata; discovery stays active unless the provider uses a manual catalog.", { providerId: z8.string(), model: modelSchema }, (p) => clientFromEnv2().addModel(p.providerId, p.model));
|
|
6564
|
+
tool("models_update", "Replace all saved metadata for a configured model.", { providerId: z8.string(), model: modelSchema }, (p) => clientFromEnv2().updateModel(p.providerId, p.model));
|
|
6565
|
+
tool("models_remove", "Remove saved model metadata; upstream catalog entries remain.", { providerId: z8.string(), modelId: modelSchema.shape.id }, (p) => clientFromEnv2().removeModel(p.providerId, p.modelId));
|
|
6566
|
+
tool("models_refresh", "Discover provider models.", { id: z8.string() }, async (p) => {
|
|
6513
6567
|
const client = clientFromEnv2(), provider = await client.getProvider(p.id);
|
|
6514
6568
|
if (runtime?.mode !== "remote")
|
|
6515
6569
|
return client.refreshModels(provider.id);
|
|
@@ -6518,13 +6572,13 @@ tool("models_refresh", "Discover provider models.", { id: z7.string() }, async (
|
|
|
6518
6572
|
return launchCatalog(client, provider, false, { clientSide: true, credential, resolveCredential: (candidate) => credentials.resolve(candidate) });
|
|
6519
6573
|
});
|
|
6520
6574
|
tool("profiles_list", "List harness launch profiles.", page, (p) => clientFromEnv2().listProfiles(p));
|
|
6521
|
-
tool("profiles_get", "Get a harness profile.", { id:
|
|
6575
|
+
tool("profiles_get", "Get a harness profile.", { id: z8.string() }, (p) => clientFromEnv2().getProfile(p.id));
|
|
6522
6576
|
tool("profiles_create", "Create a harness launch profile.", profileInputSchema.shape, (p) => clientFromEnv2().createProfile(p));
|
|
6523
|
-
tool("profiles_update", "Replace a harness profile at its version.", { profile: profileInputSchema, version:
|
|
6524
|
-
tool("profiles_delete", "Delete a profile without run history.", { id:
|
|
6525
|
-
tool("launch_plan", "Validate a local launch plan; does not execute a remote process.", { profileId:
|
|
6577
|
+
tool("profiles_update", "Replace a harness profile at its version.", { profile: profileInputSchema, version: z8.number().int() }, (p) => clientFromEnv2().updateProfile(p.profile, p.version));
|
|
6578
|
+
tool("profiles_delete", "Delete a profile without run history.", { id: z8.string(), version: z8.number().int() }, (p) => clientFromEnv2().deleteProfile(p.id, p.version));
|
|
6579
|
+
tool("launch_plan", "Validate a local launch plan; does not execute a remote process.", { profileId: z8.string() }, (p) => clientFromEnv2().launchPlan(p.profileId));
|
|
6526
6580
|
tool("runs_list", "List launch metadata.", page, (p) => clientFromEnv2().listRuns(p));
|
|
6527
|
-
tool("runs_get", "Get launch metadata.", { id:
|
|
6581
|
+
tool("runs_get", "Get launch metadata.", { id: z8.string() }, (p) => clientFromEnv2().getRun(p.id));
|
|
6528
6582
|
if (process.argv.includes("--version"))
|
|
6529
6583
|
console.log(VERSION);
|
|
6530
6584
|
else if (process.argv.includes("--help"))
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type ProviderInput } from "./domain";
|
|
2
|
+
export declare function supportsOpenCodeAuthentication(provider: ProviderInput): boolean;
|
|
3
|
+
/** A valid supplied key is required even though this fixed synthetic request is free.
|
|
4
|
+
* Anonymous responses alone are not authentication evidence: first require rejection
|
|
5
|
+
* of invalid keys through both legacy and migrated routing. A legacy-shaped
|
|
6
|
+
* selected key may have been migrated, which cannot be inferred from its prefix.
|
|
7
|
+
*/
|
|
8
|
+
export declare function verifyOpenCodeAuthentication(credential: string, fetchImpl: typeof fetch): Promise<{
|
|
9
|
+
authenticated: boolean;
|
|
10
|
+
status: number;
|
|
11
|
+
}>;
|
package/dist/serve/index.js
CHANGED
|
@@ -68,7 +68,7 @@ function canonicalPolicyJSON(value) {
|
|
|
68
68
|
return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
69
69
|
}
|
|
70
70
|
// package.json
|
|
71
|
-
var version = "0.2.
|
|
71
|
+
var version = "0.2.10";
|
|
72
72
|
|
|
73
73
|
// src/version.ts
|
|
74
74
|
var VERSION = version;
|
|
@@ -922,7 +922,7 @@ var openapi_default = {
|
|
|
922
922
|
openapi: "3.0.3",
|
|
923
923
|
info: {
|
|
924
924
|
title: "Switcher API",
|
|
925
|
-
version: "0.2.
|
|
925
|
+
version: "0.2.10",
|
|
926
926
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
927
927
|
},
|
|
928
928
|
security: [
|
package/openapi.json
CHANGED
package/package.json
CHANGED