@hasna/switcher 0.2.8 → 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 +4 -2
- package/dist/cli/index.js +197 -234
- package/dist/credentials.d.ts +2 -12
- package/dist/domain.d.ts +1 -1
- package/dist/index.js +16 -16
- package/dist/mcp/index.js +127 -90
- package/dist/opencode-authentication.d.ts +11 -0
- package/dist/sdk.js +16 -16
- package/dist/serve/index.js +13 -9
- package/dist/version.d.ts +1 -0
- package/hasna.contract.json +1 -1
- package/openapi.json +1 -1
- package/package.json +2 -2
package/dist/cli/index.js
CHANGED
|
@@ -513,9 +513,13 @@ var routingEventsSchema = z3.array(routingEventSchema).max(1000);
|
|
|
513
513
|
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
|
+
// package.json
|
|
517
|
+
var version = "0.2.10";
|
|
518
|
+
|
|
519
|
+
// src/version.ts
|
|
520
|
+
var VERSION = version;
|
|
516
521
|
|
|
517
522
|
// src/domain.ts
|
|
518
|
-
var VERSION = "0.2.7";
|
|
519
523
|
var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "antigravity", "junie", "aider", "kilo"]);
|
|
520
524
|
var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
521
525
|
var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -1364,12 +1368,12 @@ async function detectChatGPTApp(appPath, system = host) {
|
|
|
1364
1368
|
const bundleId = await field("CFBundleIdentifier");
|
|
1365
1369
|
if (bundleId !== "com.openai.codex")
|
|
1366
1370
|
continue;
|
|
1367
|
-
const name = await field("CFBundleExecutable"),
|
|
1371
|
+
const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
|
|
1368
1372
|
if (!/^[A-Za-z0-9 _-]+$/.test(name))
|
|
1369
1373
|
continue;
|
|
1370
1374
|
const executable = join3(path, "Contents/MacOS", name), codexExecutable = join3(path, "Contents/Resources/codex");
|
|
1371
1375
|
if (await system.executable(executable) && await system.executable(codexExecutable))
|
|
1372
|
-
return { path, executable, codexExecutable, bundleId, version };
|
|
1376
|
+
return { path, executable, codexExecutable, bundleId, version: version2 };
|
|
1373
1377
|
} catch {}
|
|
1374
1378
|
}
|
|
1375
1379
|
throw new Fault(404, "app_not_installed", "Install the current ChatGPT/Codex macOS app or use --app-path with its absolute .app path. Legacy ChatGPT Classic cannot run custom Codex providers.");
|
|
@@ -1392,12 +1396,12 @@ async function detectClaudeDesktopApp(appPath, system = host) {
|
|
|
1392
1396
|
const bundleId = await field("CFBundleIdentifier");
|
|
1393
1397
|
if (bundleId !== "com.anthropic.claudefordesktop")
|
|
1394
1398
|
continue;
|
|
1395
|
-
const name = await field("CFBundleExecutable"),
|
|
1399
|
+
const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
|
|
1396
1400
|
if (!/^[A-Za-z0-9 _-]+$/.test(name))
|
|
1397
1401
|
continue;
|
|
1398
1402
|
const executable = join3(path, "Contents/MacOS", name);
|
|
1399
1403
|
if (await system.executable(executable))
|
|
1400
|
-
return { path, executable, bundleId, version };
|
|
1404
|
+
return { path, executable, bundleId, version: version2 };
|
|
1401
1405
|
} catch {}
|
|
1402
1406
|
}
|
|
1403
1407
|
throw new Fault(404, "app_not_installed", "Install the current Claude macOS desktop app or supply its absolute .app path with --app-path.");
|
|
@@ -1543,17 +1547,17 @@ class SwitcherClient {
|
|
|
1543
1547
|
createProvider(input, idempotencyKey) {
|
|
1544
1548
|
return this.request("POST", "/v1/providers", input, { idempotencyKey });
|
|
1545
1549
|
}
|
|
1546
|
-
updateProvider(input,
|
|
1547
|
-
return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
|
|
1550
|
+
updateProvider(input, version2, idempotencyKey) {
|
|
1551
|
+
return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
|
|
1548
1552
|
}
|
|
1549
|
-
deleteProvider(id,
|
|
1550
|
-
return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
|
|
1553
|
+
deleteProvider(id, version2, idempotencyKey) {
|
|
1554
|
+
return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
|
|
1551
1555
|
}
|
|
1552
1556
|
async editModel(providerId, operation, value) {
|
|
1553
1557
|
const model = typeof value === "string" ? undefined : parse2(modelSchema, value);
|
|
1554
1558
|
const id = model?.id ?? parse2(modelSchema.shape.id, value);
|
|
1555
1559
|
const provider = await this.getProvider(providerId);
|
|
1556
|
-
const { version, updatedAt, ...input } = provider;
|
|
1560
|
+
const { version: version2, updatedAt, ...input } = provider;
|
|
1557
1561
|
const manual = provider.manualModels.some((item) => item.id === id);
|
|
1558
1562
|
const additional = (provider.additionalModels ?? []).some((item) => item.id === id);
|
|
1559
1563
|
if (operation === "add" && (manual || additional))
|
|
@@ -1565,7 +1569,7 @@ class SwitcherClient {
|
|
|
1565
1569
|
const additionalModels = (provider.additionalModels ?? []).filter((item) => item.id !== id);
|
|
1566
1570
|
if (operation !== "remove")
|
|
1567
1571
|
(useManual ? manualModels : additionalModels).push(model);
|
|
1568
|
-
return this.updateProvider({ ...input, manualModels, additionalModels },
|
|
1572
|
+
return this.updateProvider({ ...input, manualModels, additionalModels }, version2);
|
|
1569
1573
|
}
|
|
1570
1574
|
addModel(providerId, model) {
|
|
1571
1575
|
return this.editModel(providerId, "add", model);
|
|
@@ -1594,11 +1598,11 @@ class SwitcherClient {
|
|
|
1594
1598
|
createProfile(input, idempotencyKey) {
|
|
1595
1599
|
return this.request("POST", "/v1/profiles", input, { idempotencyKey });
|
|
1596
1600
|
}
|
|
1597
|
-
updateProfile(input,
|
|
1598
|
-
return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
|
|
1601
|
+
updateProfile(input, version2, idempotencyKey) {
|
|
1602
|
+
return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
|
|
1599
1603
|
}
|
|
1600
|
-
deleteProfile(id,
|
|
1601
|
-
return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
|
|
1604
|
+
deleteProfile(id, version2, idempotencyKey) {
|
|
1605
|
+
return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
|
|
1602
1606
|
}
|
|
1603
1607
|
launchPlan(profileId, idempotencyKey) {
|
|
1604
1608
|
return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey });
|
|
@@ -1612,8 +1616,8 @@ class SwitcherClient {
|
|
|
1612
1616
|
createRun(input, idempotencyKey) {
|
|
1613
1617
|
return this.request("POST", "/v1/runs", { ...input, modelPolicyVersion: 1 }, { idempotencyKey });
|
|
1614
1618
|
}
|
|
1615
|
-
finishRun(id,
|
|
1616
|
-
return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version, idempotencyKey });
|
|
1619
|
+
finishRun(id, version2, input, idempotencyKey) {
|
|
1620
|
+
return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version: version2, idempotencyKey });
|
|
1617
1621
|
}
|
|
1618
1622
|
}
|
|
1619
1623
|
function clientFromEnv(env = process.env, options = {}) {
|
|
@@ -2051,8 +2055,8 @@ class Store {
|
|
|
2051
2055
|
}
|
|
2052
2056
|
return value;
|
|
2053
2057
|
}
|
|
2054
|
-
async remove(kind, id,
|
|
2055
|
-
const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id,
|
|
2058
|
+
async remove(kind, id, version2, db) {
|
|
2059
|
+
const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id, version2]);
|
|
2056
2060
|
if (!rows.length)
|
|
2057
2061
|
throw new Fault(409, "version_conflict", "Entry changed or is missing; reload before retrying.");
|
|
2058
2062
|
return { deleted: id };
|
|
@@ -2539,7 +2543,7 @@ var openapi_default = {
|
|
|
2539
2543
|
openapi: "3.0.3",
|
|
2540
2544
|
info: {
|
|
2541
2545
|
title: "Switcher API",
|
|
2542
|
-
version: "0.2.
|
|
2546
|
+
version: "0.2.10",
|
|
2543
2547
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2544
2548
|
},
|
|
2545
2549
|
security: [
|
|
@@ -6851,7 +6855,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6851
6855
|
}
|
|
6852
6856
|
}
|
|
6853
6857
|
const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
|
|
6854
|
-
const
|
|
6858
|
+
const version2 = () => {
|
|
6855
6859
|
const v = request.headers.get("if-match");
|
|
6856
6860
|
if (!v || !/^[1-9]\d*$/.test(v))
|
|
6857
6861
|
throw new Fault(428, "version_required", "Supply the current numeric version in If-Match.");
|
|
@@ -6871,7 +6875,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6871
6875
|
const result = await store.mutate(key, fingerprint, async (db) => {
|
|
6872
6876
|
if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
|
|
6873
6877
|
if (request.method === "DELETE" && id2)
|
|
6874
|
-
return store.remove(resource, id2,
|
|
6878
|
+
return store.remove(resource, id2, version2(), db);
|
|
6875
6879
|
if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
|
|
6876
6880
|
const value = resource === "providers" ? parse2(providerInputSchema, body) : parse2(profileInputSchema, body);
|
|
6877
6881
|
if (id2 && value.id !== id2)
|
|
@@ -6881,7 +6885,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6881
6885
|
const provider = await store.get("providers", profile.providerId, db);
|
|
6882
6886
|
validateHarnessProvider(profile.harness, provider);
|
|
6883
6887
|
}
|
|
6884
|
-
const saved = await store.put(resource, value, id2 ?
|
|
6888
|
+
const saved = await store.put(resource, value, id2 ? version2() : undefined, db);
|
|
6885
6889
|
if (resource === "providers" && id2)
|
|
6886
6890
|
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
|
|
6887
6891
|
return saved;
|
|
@@ -6908,7 +6912,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6908
6912
|
if (store.engine === "postgresql")
|
|
6909
6913
|
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR UPDATE", [id2]);
|
|
6910
6914
|
const provider = await store.get("providers", id2, db);
|
|
6911
|
-
if (provider.version !==
|
|
6915
|
+
if (provider.version !== version2())
|
|
6912
6916
|
throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
|
|
6913
6917
|
const catalog = parse2(catalogSchema, body);
|
|
6914
6918
|
const expectedSource = provider.manualModels.length ? "manual" : "remote";
|
|
@@ -6988,7 +6992,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6988
6992
|
const run = await store.get("runs", id2, db);
|
|
6989
6993
|
if (run.status !== "running")
|
|
6990
6994
|
throw new Fault(409, "run_finished", "Run has already finished.");
|
|
6991
|
-
return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() },
|
|
6995
|
+
return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version2(), db);
|
|
6992
6996
|
}
|
|
6993
6997
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
6994
6998
|
});
|
|
@@ -10195,41 +10199,41 @@ var versionAtLeast2 = (raw, minimum) => {
|
|
|
10195
10199
|
}
|
|
10196
10200
|
return true;
|
|
10197
10201
|
};
|
|
10198
|
-
function validateHarnessVersion(harness,
|
|
10199
|
-
if (harness === "antigravity" &&
|
|
10202
|
+
function validateHarnessVersion(harness, version2) {
|
|
10203
|
+
if (harness === "antigravity" && version2?.trim() !== "1.2.5")
|
|
10200
10204
|
throw new Error("Antigravity CLI 1.2.5 is required by the verified native adapter.");
|
|
10201
|
-
if (harness === "junie" && !/\b3196\.5\b/.test(
|
|
10205
|
+
if (harness === "junie" && !/\b3196\.5\b/.test(version2 ?? ""))
|
|
10202
10206
|
throw new Error("Junie build 3196.5 is required by the verified custom model adapter.");
|
|
10203
|
-
if (harness === "kilo" && !versionAtLeast2(
|
|
10207
|
+
if (harness === "kilo" && !versionAtLeast2(version2, [7, 5, 15]))
|
|
10204
10208
|
throw new Error("Kilo >=7.5.15 is required by this scoped provider bridge.");
|
|
10205
|
-
if (harness === "omp" && !versionAtLeast2(
|
|
10209
|
+
if (harness === "omp" && !versionAtLeast2(version2, [18, 1, 11]))
|
|
10206
10210
|
throw new Error("OMP >=18.1.11 is required for the native catalog and persistent session adapter.");
|
|
10207
|
-
if (harness === "dsh" && (!versionAtLeast2(
|
|
10211
|
+
if (harness === "dsh" && (!versionAtLeast2(version2, [0, 1, 2]) || /\b0\.1\.2-/.test(version2 ?? "") && !/\b0\.1\.2-rc\.[1-9]\d*(?:\b|$)/.test(version2 ?? "")))
|
|
10208
10212
|
throw new Error("DeepSeek Harness (dsh) >=0.1.2-rc.1 is required for the native profile adapter.");
|
|
10209
|
-
if (harness === "aider" && !/^(?:aider\s+)?0\.86\.2(?:\s|$)/i.test(
|
|
10213
|
+
if (harness === "aider" && !/^(?:aider\s+)?0\.86\.2(?:\s|$)/i.test(version2 ?? ""))
|
|
10210
10214
|
throw new Error("Aider 0.86.2 is required by the verified native configuration adapter.");
|
|
10211
|
-
if (harness === "claude" && !versionAtLeast2(
|
|
10215
|
+
if (harness === "claude" && !versionAtLeast2(version2, [2, 1, 257]))
|
|
10212
10216
|
throw new Error("Claude Code >=2.1.257 is required for a full native modelPicker.");
|
|
10213
|
-
if (harness === "pi" && !versionAtLeast2(
|
|
10217
|
+
if (harness === "pi" && !versionAtLeast2(version2, [0, 85, 1]))
|
|
10214
10218
|
throw new Error("Pi >=0.85.1 is required by this catalog adapter.");
|
|
10215
|
-
if (harness === "codex" && !versionAtLeast2(
|
|
10219
|
+
if (harness === "codex" && !versionAtLeast2(version2, [0, 153, 0]))
|
|
10216
10220
|
throw new Error("Codex >=0.153.0 is required by this catalog adapter.");
|
|
10217
|
-
if (harness === "grok" && !versionAtLeast2(
|
|
10221
|
+
if (harness === "grok" && !versionAtLeast2(version2, [1, 0, 13]))
|
|
10218
10222
|
throw new Error("Grok Build >=1.0.13 is required by this remote catalog adapter.");
|
|
10219
|
-
if (harness === "cline" && !versionAtLeast2(
|
|
10223
|
+
if (harness === "cline" && !versionAtLeast2(version2, [3, 0, 61]))
|
|
10220
10224
|
throw new Error("Cline >=3.0.61 is required by this native provider adapter.");
|
|
10221
|
-
if (harness === "prime-agent" && !versionAtLeast2(
|
|
10225
|
+
if (harness === "prime-agent" && !versionAtLeast2(version2, [0, 9, 2]))
|
|
10222
10226
|
throw new Error("Prime Agent >=0.9.2 is required by this catalog adapter.");
|
|
10223
|
-
if (harness === "opencode" && !versionAtLeast2(
|
|
10227
|
+
if (harness === "opencode" && !versionAtLeast2(version2, [1, 18, 0]))
|
|
10224
10228
|
throw new Error("Legacy OpenCode >=1.18.0 is required by this catalog adapter.");
|
|
10225
10229
|
if (harness === "opencode2") {
|
|
10226
|
-
const preview =
|
|
10227
|
-
if (!(preview && Number(preview[1]) >= 19157) && !versionAtLeast2(
|
|
10230
|
+
const preview = version2?.match(/opencode2.*beta-(\d+)/i);
|
|
10231
|
+
if (!(preview && Number(preview[1]) >= 19157) && !versionAtLeast2(version2, [2, 0, 0]))
|
|
10228
10232
|
throw new Error("OpenCode 2 beta-19157 or newer is required for isolated provider configuration; legacy OpenCode is not supported by this adapter.");
|
|
10229
10233
|
}
|
|
10230
|
-
if (harness === "hermes" && !versionAtLeast2(
|
|
10234
|
+
if (harness === "hermes" && !versionAtLeast2(version2, [0, 21, 0]))
|
|
10231
10235
|
throw new Error("Hermes Agent >=0.21.0 is required by this provider and session adapter.");
|
|
10232
|
-
if (harness === "gemini" && !/^0\.58\.0$/.test(
|
|
10236
|
+
if (harness === "gemini" && !/^0\.58\.0$/.test(version2?.trim() ?? ""))
|
|
10233
10237
|
throw new Error("Gemini CLI 0.58.0 is required by the verified native settings and argument contract.");
|
|
10234
10238
|
}
|
|
10235
10239
|
async function jsonFile(dir, name, value) {
|
|
@@ -11323,41 +11327,92 @@ import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile17 } from "
|
|
|
11323
11327
|
import { join as join20, resolve as resolve11 } from "path";
|
|
11324
11328
|
|
|
11325
11329
|
// src/provider-credential-onboarding.ts
|
|
11326
|
-
import { z as
|
|
11330
|
+
import { z as z9 } from "zod";
|
|
11327
11331
|
import { createHash as createHash11 } from "crypto";
|
|
11328
11332
|
import { createInterface } from "readline/promises";
|
|
11329
11333
|
|
|
11330
|
-
// src/
|
|
11334
|
+
// src/opencode-authentication.ts
|
|
11331
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";
|
|
11386
|
+
import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
|
|
11332
11387
|
import { constants as constants5 } from "fs";
|
|
11333
|
-
import { open as open3, readdir as readdir5, unlink, link, lstat as lstat6
|
|
11334
|
-
import { join as join16, isAbsolute as isAbsolute15
|
|
11388
|
+
import { open as open3, readdir as readdir5, unlink, link, lstat as lstat6 } from "fs/promises";
|
|
11389
|
+
import { join as join16, isAbsolute as isAbsolute15 } from "path";
|
|
11335
11390
|
import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
|
|
11336
11391
|
import { execFile as execFile3, spawn } from "child_process";
|
|
11337
11392
|
import { promisify as promisify3 } from "util";
|
|
11338
11393
|
import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
|
|
11339
11394
|
var execute3 = promisify3(execFile3);
|
|
11340
|
-
var reference =
|
|
11341
|
-
var item =
|
|
11342
|
-
var vaultKeySchema =
|
|
11343
|
-
var keychain =
|
|
11344
|
-
var credentialTier =
|
|
11345
|
-
var operator =
|
|
11346
|
-
|
|
11347
|
-
|
|
11348
|
-
|
|
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()
|
|
11349
11404
|
]);
|
|
11350
|
-
var origin =
|
|
11351
|
-
var credentialBindingSchema =
|
|
11352
|
-
schema:
|
|
11405
|
+
var origin = z8.string().transform((value) => new URL(endpoint(value)).origin);
|
|
11406
|
+
var credentialBindingSchema = z8.object({
|
|
11407
|
+
schema: z8.literal(1),
|
|
11353
11408
|
credentialEnv: reference,
|
|
11354
|
-
origins:
|
|
11355
|
-
requireProviderAuthentication:
|
|
11356
|
-
source:
|
|
11357
|
-
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"),
|
|
11358
11413
|
key: vaultKeySchema,
|
|
11359
|
-
url:
|
|
11360
|
-
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"),
|
|
11361
11416
|
operator
|
|
11362
11417
|
}).strict()])
|
|
11363
11418
|
}).strict().superRefine((binding, ctx) => {
|
|
@@ -11486,131 +11541,37 @@ function credentialReference(selector) {
|
|
|
11486
11541
|
throw new Fault(400, "credential_reference_required", "Use the explicit SWITCHER_PROVIDER_ reference for this provider.");
|
|
11487
11542
|
return parse2(reference, name);
|
|
11488
11543
|
}
|
|
11489
|
-
|
|
11490
|
-
|
|
11491
|
-
|
|
11492
|
-
|
|
11493
|
-
|
|
11494
|
-
|
|
11495
|
-
|
|
11496
|
-
|
|
11497
|
-
|
|
11498
|
-
|
|
11499
|
-
|
|
11500
|
-
|
|
11501
|
-
|
|
11502
|
-
|
|
11503
|
-
|
|
11504
|
-
|
|
11505
|
-
|
|
11506
|
-
|
|
11507
|
-
if (!part)
|
|
11508
|
-
continue;
|
|
11509
|
-
prefix = join16(prefix, part);
|
|
11510
|
-
if (seen.has(prefix))
|
|
11511
|
-
continue;
|
|
11512
|
-
seen.add(prefix);
|
|
11513
|
-
if (seen.size > 256)
|
|
11514
|
-
throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
|
|
11515
|
-
const entry = await lstat6(prefix);
|
|
11516
|
-
const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
|
|
11517
|
-
if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
|
|
11518
|
-
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.");
|
|
11519
|
-
if (entry.isSymbolicLink())
|
|
11520
|
-
await inspect(resolvePath(dirname8(prefix), await readlink(prefix)));
|
|
11521
|
-
}
|
|
11522
|
-
};
|
|
11523
|
-
try {
|
|
11524
|
-
await inspect(path);
|
|
11525
|
-
await inspect(resolved);
|
|
11526
|
-
} catch (error) {
|
|
11527
|
-
if (error instanceof Fault)
|
|
11528
|
-
throw error;
|
|
11529
|
-
throw new Fault(422, "vault_exec_unavailable", "The secrets executable path changed or could not be verified. Retry with a trusted installation.");
|
|
11530
|
-
}
|
|
11531
|
-
}
|
|
11532
|
-
return resolved;
|
|
11544
|
+
function vaultExecutableFault(error) {
|
|
11545
|
+
if (!(error instanceof ExecutableTrustError))
|
|
11546
|
+
throw error;
|
|
11547
|
+
const codes = {
|
|
11548
|
+
invalid_request: "invalid_request",
|
|
11549
|
+
executable_unavailable: "vault_exec_unavailable",
|
|
11550
|
+
executable_permissions: "vault_exec_permissions",
|
|
11551
|
+
executable_repair_unsafe: "vault_exec_repair_unsafe",
|
|
11552
|
+
executable_digest_mismatch: "vault_exec_digest_mismatch"
|
|
11553
|
+
};
|
|
11554
|
+
const messages = {
|
|
11555
|
+
invalid_request: error.message,
|
|
11556
|
+
executable_unavailable: "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.",
|
|
11557
|
+
executable_permissions: "The secrets executable and its ancestor directories must be owned by this user or root and not writable by other users. Use credentials repair-executable REFERENCE --sha256 EXPECTED with the executable digest from a verified package artifact. Launch never repairs permissions automatically.",
|
|
11558
|
+
executable_repair_unsafe: error.message,
|
|
11559
|
+
executable_digest_mismatch: "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed."
|
|
11560
|
+
};
|
|
11561
|
+
throw new Fault(error.status, codes[error.code], messages[error.code]);
|
|
11533
11562
|
}
|
|
11534
11563
|
async function validateVaultExecutable(path) {
|
|
11535
|
-
|
|
11564
|
+
try {
|
|
11565
|
+
return await validateExecutable(path);
|
|
11566
|
+
} catch (error) {
|
|
11567
|
+
return vaultExecutableFault(error);
|
|
11568
|
+
}
|
|
11536
11569
|
}
|
|
11537
11570
|
async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
11538
|
-
if (!/^[a-f0-9]{64}$/.test(expectedSha256))
|
|
11539
|
-
throw new Fault(400, "invalid_request", "--sha256 requires the SHA256 of the executable member from a verified package artifact.");
|
|
11540
|
-
if (!isAbsolute15(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path))
|
|
11541
|
-
throw new Fault(400, "invalid_request", "Secrets executable must be an absolute path without control characters.");
|
|
11542
|
-
if (process.platform === "win32")
|
|
11543
|
-
throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
|
|
11544
|
-
const resolved = await inspectVaultExecutable(path, true);
|
|
11545
|
-
const file = await open3(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
11546
|
-
const unsafe = () => new Fault(422, "vault_exec_repair_unsafe", "Executable ownership, type, links or contents changed; no trusted repair can be confirmed.");
|
|
11547
|
-
let temporary;
|
|
11548
11571
|
try {
|
|
11549
|
-
|
|
11550
|
-
|
|
11551
|
-
|
|
11552
|
-
throw unsafe();
|
|
11553
|
-
const sameFile = (info) => info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.uid === before.uid && info.nlink === before.nlink && info.mode === before.mode && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
|
|
11554
|
-
const hash2 = async (target) => {
|
|
11555
|
-
const digest = createHash10("sha256");
|
|
11556
|
-
const buffer = Buffer.alloc(1024 * 1024);
|
|
11557
|
-
let position = 0;
|
|
11558
|
-
while (true) {
|
|
11559
|
-
const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
|
|
11560
|
-
if (!bytesRead)
|
|
11561
|
-
break;
|
|
11562
|
-
position += bytesRead;
|
|
11563
|
-
if (position > limit)
|
|
11564
|
-
throw unsafe();
|
|
11565
|
-
const bytes = buffer.subarray(0, bytesRead);
|
|
11566
|
-
digest.update(bytes);
|
|
11567
|
-
if (target)
|
|
11568
|
-
await target.writeFile(bytes);
|
|
11569
|
-
}
|
|
11570
|
-
if (position !== before.size || !sameFile(await file.stat()))
|
|
11571
|
-
throw unsafe();
|
|
11572
|
-
if (digest.digest("hex") !== expectedSha256)
|
|
11573
|
-
throw new Fault(422, "vault_exec_digest_mismatch", "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed.");
|
|
11574
|
-
};
|
|
11575
|
-
await hash2();
|
|
11576
|
-
const mode = before.mode & 511 & ~18;
|
|
11577
|
-
const changed = mode !== (before.mode & 511);
|
|
11578
|
-
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat6(resolved)))
|
|
11579
|
-
throw unsafe();
|
|
11580
|
-
if (!changed) {
|
|
11581
|
-
await validateVaultExecutable(path);
|
|
11582
|
-
return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
|
|
11583
|
-
}
|
|
11584
|
-
temporary = join16(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
|
|
11585
|
-
const replacement = await open3(temporary, "wx", 384);
|
|
11586
|
-
try {
|
|
11587
|
-
await hash2(replacement);
|
|
11588
|
-
await replacement.chmod(mode);
|
|
11589
|
-
await replacement.sync();
|
|
11590
|
-
const ready = await replacement.stat();
|
|
11591
|
-
if (!ready.isFile() || ready.nlink !== 1 || ready.uid !== before.uid || ready.size !== before.size)
|
|
11592
|
-
throw unsafe();
|
|
11593
|
-
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat6(resolved)))
|
|
11594
|
-
throw unsafe();
|
|
11595
|
-
await rename2(temporary, resolved);
|
|
11596
|
-
temporary = undefined;
|
|
11597
|
-
const installed = await lstat6(resolved);
|
|
11598
|
-
if (installed.dev !== ready.dev || installed.ino !== ready.ino || await validateVaultExecutable(path) !== resolved)
|
|
11599
|
-
throw unsafe();
|
|
11600
|
-
const directory = await open3(dirname8(resolved), constants5.O_RDONLY | constants5.O_DIRECTORY | constants5.O_NOFOLLOW);
|
|
11601
|
-
try {
|
|
11602
|
-
await directory.sync();
|
|
11603
|
-
} finally {
|
|
11604
|
-
await directory.close();
|
|
11605
|
-
}
|
|
11606
|
-
} finally {
|
|
11607
|
-
await replacement.close();
|
|
11608
|
-
}
|
|
11609
|
-
return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
|
|
11610
|
-
} finally {
|
|
11611
|
-
await file.close();
|
|
11612
|
-
if (temporary)
|
|
11613
|
-
await unlink(temporary);
|
|
11572
|
+
return await repairExecutablePermissions(path, expectedSha256);
|
|
11573
|
+
} catch (error) {
|
|
11574
|
+
return vaultExecutableFault(error);
|
|
11614
11575
|
}
|
|
11615
11576
|
}
|
|
11616
11577
|
function bindingTarget(selector, override, allowedOrigins) {
|
|
@@ -11872,13 +11833,13 @@ async function deliverVaultCredential() {
|
|
|
11872
11833
|
// src/provider-credential-onboarding.ts
|
|
11873
11834
|
var absent = (error) => error instanceof SwitcherError && error.status === 404;
|
|
11874
11835
|
var MAX_CREDENTIAL_MATCHES = 256;
|
|
11875
|
-
var secretMetadataSchema =
|
|
11836
|
+
var secretMetadataSchema = z9.object({
|
|
11876
11837
|
key: vaultKeySchema,
|
|
11877
|
-
type:
|
|
11878
|
-
label:
|
|
11879
|
-
expires_at:
|
|
11880
|
-
created_at:
|
|
11881
|
-
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)
|
|
11882
11843
|
}).strict();
|
|
11883
11844
|
var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
|
|
11884
11845
|
var credentialOrigins = (provider) => {
|
|
@@ -11987,6 +11948,8 @@ function authenticationProbe(provider) {
|
|
|
11987
11948
|
return;
|
|
11988
11949
|
}
|
|
11989
11950
|
async function verifyProviderAuthentication({ provider, credential, fetch: fetchImpl = fetch }) {
|
|
11951
|
+
if (!provider.credentialCheck && supportsOpenCodeAuthentication(provider))
|
|
11952
|
+
return verifyOpenCodeAuthentication(credential, fetchImpl);
|
|
11990
11953
|
const probe = authenticationProbe(provider);
|
|
11991
11954
|
if (!probe)
|
|
11992
11955
|
return { authenticated: false, unsupported: true };
|
|
@@ -12535,13 +12498,13 @@ async function inspectOri(options = {}) {
|
|
|
12535
12498
|
const versionResult = await readOnly(executable, ["--version"], environment, options.cwd);
|
|
12536
12499
|
if (versionResult.code !== 0)
|
|
12537
12500
|
throw new OriBackendError("ori_unavailable", "Ori could not report its version; install it or pass an explicit executable.");
|
|
12538
|
-
const
|
|
12539
|
-
if (!
|
|
12501
|
+
const version2 = parseVersion(versionResult.stdout);
|
|
12502
|
+
if (!version2)
|
|
12540
12503
|
throw new OriBackendError("invalid_contract", "Ori --version did not report a version.");
|
|
12541
12504
|
const inventoryResult = await readOnly(executable, ["harness", "list", "--json"], environment, options.cwd);
|
|
12542
12505
|
if (inventoryResult.code !== 0)
|
|
12543
12506
|
throw new OriBackendError("ori_unavailable", "Ori could not report its harness inventory.");
|
|
12544
|
-
return { executable, version, harnesses: parseHarnesses(inventoryResult.stdout) };
|
|
12507
|
+
return { executable, version: version2, harnesses: parseHarnesses(inventoryResult.stdout) };
|
|
12545
12508
|
}
|
|
12546
12509
|
function assertSupportedOriVersion(contract) {
|
|
12547
12510
|
if (!/^0\.12\./.test(contract.version))
|
|
@@ -12661,7 +12624,7 @@ import { fileURLToPath } from "url";
|
|
|
12661
12624
|
|
|
12662
12625
|
// src/desktop-state.ts
|
|
12663
12626
|
import { Database as Database3 } from "bun:sqlite";
|
|
12664
|
-
import { readFile as readFile7, writeFile as writeFile14, rm as rm3, lstat as lstat7, rename as
|
|
12627
|
+
import { readFile as readFile7, writeFile as writeFile14, rm as rm3, lstat as lstat7, rename as rename2, chmod as chmod2 } from "fs/promises";
|
|
12665
12628
|
async function safeDesktopRead(path) {
|
|
12666
12629
|
try {
|
|
12667
12630
|
const info = await lstat7(path);
|
|
@@ -12678,7 +12641,7 @@ async function writeDesktopPrivate(path, text) {
|
|
|
12678
12641
|
const temporary = path + "." + crypto.randomUUID() + ".tmp";
|
|
12679
12642
|
try {
|
|
12680
12643
|
await writeFile14(temporary, text, { mode: 384, flag: "wx" });
|
|
12681
|
-
await
|
|
12644
|
+
await rename2(temporary, path);
|
|
12682
12645
|
} finally {
|
|
12683
12646
|
await rm3(temporary, { force: true });
|
|
12684
12647
|
}
|
|
@@ -12710,18 +12673,18 @@ async function desktopLease(path) {
|
|
|
12710
12673
|
}
|
|
12711
12674
|
|
|
12712
12675
|
// src/native-state.ts
|
|
12713
|
-
import { lstat as lstat8, mkdir as mkdir11, open as open4, opendir, readlink
|
|
12676
|
+
import { lstat as lstat8, mkdir as mkdir11, open as open4, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
|
|
12714
12677
|
import { constants as constants7 } from "fs";
|
|
12715
12678
|
import { homedir as homedir9 } from "os";
|
|
12716
|
-
import { dirname as
|
|
12679
|
+
import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
|
|
12717
12680
|
function nativeStateRequested(tool, environment = process.env, explicit = false) {
|
|
12718
12681
|
const suffix = tool.toUpperCase();
|
|
12719
12682
|
return explicit || environment[`HASNA_${suffix}_STATE_HOME`] !== undefined || environment[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
|
|
12720
12683
|
}
|
|
12721
|
-
function validateNativeStateVersion(tool,
|
|
12684
|
+
function validateNativeStateVersion(tool, version2) {
|
|
12722
12685
|
if (tool !== "codex")
|
|
12723
12686
|
return;
|
|
12724
|
-
const match =
|
|
12687
|
+
const match = version2?.match(/(\d+)\.(\d+)\.(\d+)/), actual = match?.slice(1).map(Number);
|
|
12725
12688
|
if (!actual || actual[0] !== 0 || actual[1] < 154)
|
|
12726
12689
|
throw new Fault(422, "native_state_version", "Shared Codex state requires Codex 0.154.0 or newer, whose metadata and resume protocol has been acceptance-tested by Switcher.");
|
|
12727
12690
|
}
|
|
@@ -12766,25 +12729,25 @@ function credentialOverlay(path) {
|
|
|
12766
12729
|
return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
|
|
12767
12730
|
}
|
|
12768
12731
|
async function assertSafeAncestors(path) {
|
|
12769
|
-
for (let parent = path;; parent =
|
|
12732
|
+
for (let parent = path;; parent = dirname8(parent)) {
|
|
12770
12733
|
const ancestor = await lstat8(parent);
|
|
12771
12734
|
const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
|
|
12772
12735
|
if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
|
|
12773
12736
|
throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
|
|
12774
|
-
if (parent ===
|
|
12737
|
+
if (parent === dirname8(parent))
|
|
12775
12738
|
break;
|
|
12776
12739
|
}
|
|
12777
12740
|
}
|
|
12778
12741
|
async function assertNativeStateDirectory(path) {
|
|
12779
12742
|
const entry = await info(path);
|
|
12780
|
-
if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || await
|
|
12743
|
+
if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
|
|
12781
12744
|
throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
|
|
12782
|
-
await assertSafeAncestors(
|
|
12745
|
+
await assertSafeAncestors(dirname8(path));
|
|
12783
12746
|
}
|
|
12784
12747
|
async function ensureNativeStateDirectory(path, create = true) {
|
|
12785
12748
|
if (await info(path))
|
|
12786
12749
|
return assertNativeStateDirectory(path);
|
|
12787
|
-
await ensureNativeStateDirectory(
|
|
12750
|
+
await ensureNativeStateDirectory(dirname8(path), create);
|
|
12788
12751
|
if (!create)
|
|
12789
12752
|
return;
|
|
12790
12753
|
await mkdir11(path, { mode: 448 }).catch((error) => {
|
|
@@ -12880,9 +12843,9 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
|
|
|
12880
12843
|
if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
|
|
12881
12844
|
const path = resolve9(home, value), entry = await info(path);
|
|
12882
12845
|
const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
|
|
12883
|
-
if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await
|
|
12846
|
+
if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
|
|
12884
12847
|
throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
|
|
12885
|
-
await assertSafeAncestors(
|
|
12848
|
+
await assertSafeAncestors(dirname8(path));
|
|
12886
12849
|
const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW).catch(() => {
|
|
12887
12850
|
throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
|
|
12888
12851
|
});
|
|
@@ -13036,14 +12999,14 @@ async function projectNativeStateUnlocked(state, overlayHome) {
|
|
|
13036
12999
|
await assertCodexDatabaseRedirectSafe(state, overlayHome);
|
|
13037
13000
|
for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
|
|
13038
13001
|
const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
|
|
13039
|
-
await ensureNativeStateDirectory(
|
|
13040
|
-
await ensureNativeStateDirectory(
|
|
13002
|
+
await ensureNativeStateDirectory(dirname8(target), false);
|
|
13003
|
+
await ensureNativeStateDirectory(dirname8(destination), false);
|
|
13041
13004
|
const source = await info(target), existing = await info(destination);
|
|
13042
13005
|
if (source && (source.isSymbolicLink() || source.uid !== process.getuid?.() || (source.mode & 18) !== 0 || source.isFile() && source.nlink !== 1 || (entry.kind === "directory" ? !source.isDirectory() : !source.isFile())))
|
|
13043
13006
|
throw new Fault(422, "native_state_entry", "A shared native state entry has an unsupported type, owner or permissions.");
|
|
13044
13007
|
if (source?.isDirectory())
|
|
13045
13008
|
await assertShareableTree(target);
|
|
13046
|
-
if (existing && (!existing.isSymbolicLink() || resolve9(
|
|
13009
|
+
if (existing && (!existing.isSymbolicLink() || resolve9(dirname8(destination), await readlink(destination)) !== target))
|
|
13047
13010
|
throw new Fault(409, "native_state_migration_required", "This launch profile already contains native state. Preserve and migrate its noncredential state before linking the shared corpus.");
|
|
13048
13011
|
}
|
|
13049
13012
|
const createdLinks = [];
|
|
@@ -13051,7 +13014,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
|
|
|
13051
13014
|
try {
|
|
13052
13015
|
for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
|
|
13053
13016
|
const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
|
|
13054
|
-
const targetParent =
|
|
13017
|
+
const targetParent = dirname8(target), destinationParent = dirname8(destination);
|
|
13055
13018
|
if (!await info(targetParent))
|
|
13056
13019
|
await createTrackedDirectory(targetParent, createdDirectories);
|
|
13057
13020
|
else
|
|
@@ -13079,7 +13042,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
|
|
|
13079
13042
|
} catch (error) {
|
|
13080
13043
|
for (const item2 of createdLinks.reverse()) {
|
|
13081
13044
|
try {
|
|
13082
|
-
if ((await info(item2.destination))?.isSymbolicLink() && resolve9(
|
|
13045
|
+
if ((await info(item2.destination))?.isSymbolicLink() && resolve9(dirname8(item2.destination), await readlink(item2.destination)) === item2.target)
|
|
13083
13046
|
await unlink2(item2.destination);
|
|
13084
13047
|
} catch {}
|
|
13085
13048
|
}
|
|
@@ -13251,7 +13214,7 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
|
|
|
13251
13214
|
// src/claude-desktop-launch.ts
|
|
13252
13215
|
import { createHash as createHash13 } from "crypto";
|
|
13253
13216
|
import { execFile as execFile5 } from "child_process";
|
|
13254
|
-
import { access as
|
|
13217
|
+
import { access as access4, rm as rm5, writeFile as writeFile16 } from "fs/promises";
|
|
13255
13218
|
import { homedir as homedir10, userInfo as userInfo2 } from "os";
|
|
13256
13219
|
import { join as join19 } from "path";
|
|
13257
13220
|
import { promisify as promisify5 } from "util";
|
|
@@ -13260,7 +13223,7 @@ var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
|
|
|
13260
13223
|
var claudeDesktopDataDirectory = () => join19(homedir10(), "Library/Application Support/Claude-3p");
|
|
13261
13224
|
async function assertAvailable(userData) {
|
|
13262
13225
|
for (const path of [join19("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
13263
|
-
if (await
|
|
13226
|
+
if (await access4(path).then(() => true, () => false))
|
|
13264
13227
|
throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
|
|
13265
13228
|
let openFiles;
|
|
13266
13229
|
try {
|
|
@@ -13288,8 +13251,8 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
13288
13251
|
validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
|
|
13289
13252
|
if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
|
|
13290
13253
|
throw new Fault(400, "desktop_arguments", "Claude desktop uses its own effort and permission controls; native CLI arguments and Codex-only launch controls are not accepted.");
|
|
13291
|
-
const
|
|
13292
|
-
if (
|
|
13254
|
+
const version2 = app.version.split(".").map(Number);
|
|
13255
|
+
if (version2.length < 3 || version2.some((n) => !Number.isSafeInteger(n)) || version2[0] < 1 || version2[0] === 1 && version2[1] < 52386)
|
|
13293
13256
|
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
|
|
13294
13257
|
const userData = system?.userData ?? claudeDesktopDataDirectory();
|
|
13295
13258
|
const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
|
|
@@ -13386,10 +13349,10 @@ import { spawn as spawn3 } from "child_process";
|
|
|
13386
13349
|
import { createInterface as createInterface2 } from "readline/promises";
|
|
13387
13350
|
import { basename as basename3, resolve as resolve10 } from "path";
|
|
13388
13351
|
var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
13389
|
-
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.");
|
|
13390
13353
|
async function listCodexSessions(prepared, cwd, query) {
|
|
13391
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)
|
|
13392
|
-
throw
|
|
13355
|
+
throw unavailable2();
|
|
13393
13356
|
const nativeStateEnv = Object.fromEntries(Object.entries(prepared.env).filter(([name]) => ["CODEX_HOME", "CODEX_SQLITE_HOME"].includes(name)));
|
|
13394
13357
|
const child = spawn3(prepared.executable, [...prepared.args, "app-server"], {
|
|
13395
13358
|
cwd,
|
|
@@ -13410,7 +13373,7 @@ async function listCodexSessions(prepared, cwd, query) {
|
|
|
13410
13373
|
killTimer ??= setTimeout(() => child.kill("SIGKILL"), 2000);
|
|
13411
13374
|
killTimer.unref();
|
|
13412
13375
|
};
|
|
13413
|
-
const fail = (error =
|
|
13376
|
+
const fail = (error = unavailable2()) => {
|
|
13414
13377
|
if (!done) {
|
|
13415
13378
|
done = true;
|
|
13416
13379
|
rejectPage(error);
|
|
@@ -13437,7 +13400,7 @@ async function listCodexSessions(prepared, cwd, query) {
|
|
|
13437
13400
|
try {
|
|
13438
13401
|
responseBytes += chunk.length;
|
|
13439
13402
|
if (responseBytes > 16 * 1024 * 1024 || pending.length + chunk.length > 8 * 1024 * 1024)
|
|
13440
|
-
throw
|
|
13403
|
+
throw unavailable2();
|
|
13441
13404
|
pending = Buffer.concat([pending, chunk]);
|
|
13442
13405
|
let end;
|
|
13443
13406
|
while ((end = pending.indexOf(10)) >= 0) {
|
|
@@ -13447,20 +13410,20 @@ async function listCodexSessions(prepared, cwd, query) {
|
|
|
13447
13410
|
continue;
|
|
13448
13411
|
const message = JSON.parse(line.toString("utf8"));
|
|
13449
13412
|
if (!object6(message))
|
|
13450
|
-
throw
|
|
13413
|
+
throw unavailable2();
|
|
13451
13414
|
if (message.id === 1) {
|
|
13452
13415
|
if (initialized || message.error || !object6(message.result))
|
|
13453
|
-
throw
|
|
13416
|
+
throw unavailable2();
|
|
13454
13417
|
initialized = true;
|
|
13455
13418
|
send({ method: "initialized" });
|
|
13456
13419
|
send({ id: 2, method: "thread/list", params: { ...query, modelProviders: [], useStateDbOnly: false, sortKey: "updated_at", sortDirection: "desc" } });
|
|
13457
13420
|
} else if (message.id === 2) {
|
|
13458
13421
|
const page = message.result;
|
|
13459
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)
|
|
13460
|
-
throw
|
|
13423
|
+
throw unavailable2();
|
|
13461
13424
|
const data2 = page.data.map((thread) => {
|
|
13462
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")
|
|
13463
|
-
throw
|
|
13426
|
+
throw unavailable2();
|
|
13464
13427
|
return { id: thread.id, cwd: thread.cwd, name: thread.name, preview: thread.preview };
|
|
13465
13428
|
});
|
|
13466
13429
|
done = true;
|
|
@@ -13510,7 +13473,7 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
|
|
|
13510
13473
|
if (codexOptionTakesValue(nativeArgs[i])) {
|
|
13511
13474
|
if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
|
|
13512
13475
|
if (!nativeArgs[i + 1])
|
|
13513
|
-
throw
|
|
13476
|
+
throw unavailable2();
|
|
13514
13477
|
effectiveCwd = resolve10(cwd, nativeArgs[i + 1]);
|
|
13515
13478
|
}
|
|
13516
13479
|
i++;
|
|
@@ -13767,11 +13730,11 @@ async function launch(client, profileId, options = {}) {
|
|
|
13767
13730
|
} else
|
|
13768
13731
|
routingEventsDropped = Math.min(1e6, routingEventsDropped + 1);
|
|
13769
13732
|
};
|
|
13770
|
-
const finishRunOnce = async (candidate,
|
|
13733
|
+
const finishRunOnce = async (candidate, body2, message) => {
|
|
13771
13734
|
if (runFinalized)
|
|
13772
13735
|
return;
|
|
13773
13736
|
runFinalized = true;
|
|
13774
|
-
await client.finishRun(candidate.id, candidate.version, { ...
|
|
13737
|
+
await client.finishRun(candidate.id, candidate.version, { ...body2, routingEvents, routingEventsDropped }, crypto.randomUUID()).catch(() => console.error(message));
|
|
13775
13738
|
};
|
|
13776
13739
|
let cancelPreparation;
|
|
13777
13740
|
const preparationCancellation = new Promise((_, reject2) => {
|
|
@@ -13998,7 +13961,7 @@ async function resolveLaunchProvider(client, selector, options = {}) {
|
|
|
13998
13961
|
existing = await client.getProvider(desired.id);
|
|
13999
13962
|
}
|
|
14000
13963
|
}
|
|
14001
|
-
const { version, updatedAt, ...input } = existing;
|
|
13964
|
+
const { version: version2, updatedAt, ...input } = existing;
|
|
14002
13965
|
const { additionalModels: _savedAdditions, credentialCheck: savedCredentialCheck, ...savedSettings } = parse2(providerInputSchema, input);
|
|
14003
13966
|
const { additionalModels: _presetAdditions, credentialCheck: presetCredentialCheck, ...presetSettings } = desired;
|
|
14004
13967
|
if (JSON.stringify(savedSettings) !== JSON.stringify(presetSettings) || savedCredentialCheck !== undefined && JSON.stringify(savedCredentialCheck) !== JSON.stringify(presetCredentialCheck))
|
|
@@ -14074,7 +14037,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
14074
14037
|
import { createHash as createHash15 } from "crypto";
|
|
14075
14038
|
import { constants as constants8 } from "fs";
|
|
14076
14039
|
import { lstat as lstat9, open as open5, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
|
|
14077
|
-
import { basename as basename4, dirname as
|
|
14040
|
+
import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join21, relative as relative6, resolve as resolve12 } from "path";
|
|
14078
14041
|
var MAX_FILES = 1e5;
|
|
14079
14042
|
var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
|
|
14080
14043
|
var refused = () => new Fault(409, "native_state_import_conflict", "Native state import found changed, unsafe or divergent data. No existing file will be replaced. Keep the original directory and resolve the conflict explicitly.");
|
|
@@ -14241,8 +14204,8 @@ async function planNativeStateImport(state, source, selection) {
|
|
|
14241
14204
|
async function visit(path, kind) {
|
|
14242
14205
|
if (++seen > MAX_FILES || path.split("/").length > 32)
|
|
14243
14206
|
throw refused();
|
|
14244
|
-
await ensureNativeStateDirectory(
|
|
14245
|
-
await ensureNativeStateDirectory(
|
|
14207
|
+
await ensureNativeStateDirectory(dirname9(join21(source, path)), false);
|
|
14208
|
+
await ensureNativeStateDirectory(dirname9(join21(state.home, path)), false);
|
|
14246
14209
|
const from = join21(source, path), to = join21(state.home, path), entry = await info2(from), target = await info2(to);
|
|
14247
14210
|
if (!entry)
|
|
14248
14211
|
return;
|
|
@@ -14316,14 +14279,14 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
14316
14279
|
throw refused();
|
|
14317
14280
|
const requiredDirectories = new Set([plan.state.home]);
|
|
14318
14281
|
for (const path of plan.directories) {
|
|
14319
|
-
for (let directory = join21(plan.state.home, path);inside3(plan.state.home, directory); directory =
|
|
14282
|
+
for (let directory = join21(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
|
|
14320
14283
|
requiredDirectories.add(directory);
|
|
14321
14284
|
if (directory === plan.state.home)
|
|
14322
14285
|
break;
|
|
14323
14286
|
}
|
|
14324
14287
|
}
|
|
14325
14288
|
for (const file of plan.files.filter((file2) => !file2.existing)) {
|
|
14326
|
-
for (let directory =
|
|
14289
|
+
for (let directory = dirname9(join21(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
|
|
14327
14290
|
requiredDirectories.add(directory);
|
|
14328
14291
|
if (directory === plan.state.home)
|
|
14329
14292
|
break;
|
|
@@ -14344,7 +14307,7 @@ async function applyNativeStateImportUnlocked(plan) {
|
|
|
14344
14307
|
for (const file of plan.files) {
|
|
14345
14308
|
if (file.existing)
|
|
14346
14309
|
continue;
|
|
14347
|
-
const target = join21(plan.state.home, file.path), temporary = join21(
|
|
14310
|
+
const target = join21(plan.state.home, file.path), temporary = join21(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
|
|
14348
14311
|
staged.push({ temporary, target });
|
|
14349
14312
|
const copied = await fingerprint2(join21(plan.source, file.path), temporary);
|
|
14350
14313
|
if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
|