singularity-forge/src/resources/extensions/sf/provider-env-auth.js
Mikael Hugo 280303ef9a fix(lint): reformat 6 files touched during web dep upgrade
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-10 12:10:10 +02:00

70 lines
2.2 KiB
JavaScript

import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { getEnvApiKey } from "@singularity-forge/ai";
import { getAgentDir, SettingsManager } from "@singularity-forge/coding-agent";
const GOOGLE_ENV_AUTH_DEFAULT_OFF_PROVIDERS = new Set([
"google",
"google-gemini-cli",
]);
function readJson(path) {
try {
if (!existsSync(path)) return {};
return JSON.parse(readFileSync(path, "utf-8"));
} catch {
return {};
}
}
function readProviderEnvAuthSettings(cwd, agentDir) {
const globalSettings = readJson(join(agentDir, "settings.json"));
const projectSettings = readJson(join(cwd, ".sf", "settings.json"));
return {
...(globalSettings.providerEnvAuth ?? {}),
...(projectSettings.providerEnvAuth ?? {}),
providers: {
...(globalSettings.providerEnvAuth?.providers ?? {}),
...(projectSettings.providerEnvAuth?.providers ?? {}),
},
};
}
function getProviderEnvAuthMode(providerId, cwd) {
const agentDir = getAgentDir();
const settingsManager = SettingsManager.create(cwd, agentDir);
if (typeof settingsManager.getProviderEnvAuthMode === "function") {
return settingsManager.getProviderEnvAuthMode(providerId);
}
const settings = readProviderEnvAuthSettings(cwd, agentDir);
return (
settings.providers?.[providerId] ??
settings.default ??
(GOOGLE_ENV_AUTH_DEFAULT_OFF_PROVIDERS.has(providerId) ? "off" : "auto")
);
}
function getProviderEnvKey(providerId) {
const apiKey = getEnvApiKey(providerId);
if (apiKey) return apiKey;
if (providerId === "google") {
return (
process.env.GEMINI_API_KEY || process.env.GOOGLE_GENERATIVE_AI_API_KEY
);
}
return undefined;
}
/**
* Return the provider env API key only when Forge settings allow env auth.
*
* Purpose: keep SF extension-side provider heuristics aligned with the core
* providerEnvAuth policy so ambient env keys do not bypass settings.json.
*
* Consumer: doctor-providers.js and preferences-models.js when checking whether
* a provider is available from environment credentials.
*/
export function getConfiguredEnvApiKey(providerId, cwd = process.cwd()) {
if (getProviderEnvAuthMode(providerId, cwd) === "off") return undefined;
return getProviderEnvKey(providerId);
}