refactor(quota): secure managed provider credentials (#2160)

- add shared owner-only credential storage for OpenCode Go, Ollama Cloud, and Cursor
- validate credentials before atomic writes using 0700 directories and 0600 files
- replace provider-specific credential routes with an allowlisted lifecycle API
- stop automatically reading Ollama's legacy cookie file
- stop reading or modifying Cursor's database during regular quota requests
- add explicit one-time Cursor credential import without mutating Cursor storage
- persist refreshed Cursor credentials only in OpenChamber-managed storage
- add Ollama Cloud and Cursor credential controls to provider settings
- preserve OpenCode Go tracking through the shared credential flow
- add VS Code credential management and Cursor quota parity
- reject authentication redirects, enforce request timeouts, and fail on unparseable usage pages
- mask stored secrets in API responses and extend quota security coverage
- update quota provider documentation
This commit is contained in:
Bohdan Triapitsyn
2026-07-12 16:21:38 +03:00
committed by GitHub
parent 3b92d97795
commit b09614fd68
20 changed files with 431 additions and 368 deletions
+22 -21
View File
@@ -1,7 +1,8 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { fetchOpenCodeGoUsage, readOpenCodeGoCredential } from './opencodeGoQuota';
import { fetchOpenCodeGoUsage } from './opencodeGoQuota';
import { readCredential } from './quotaCredentials';
type AuthEntry = Record<string, unknown> | string;
type AuthFile = Record<string, AuthEntry>;
@@ -124,7 +125,6 @@ export type ProviderResult = {
const OPENCODE_CONFIG_DIR = path.join(os.homedir(), '.config', 'opencode');
const OPENCODE_DATA_DIR = path.join(os.homedir(), '.local', 'share', 'opencode');
const AUTH_FILE = path.join(OPENCODE_DATA_DIR, 'auth.json');
const OLLAMA_CLOUD_COOKIE_PATH = path.join(os.homedir(), '.config', 'ollama-quota', 'cookie');
const ANTIGRAVITY_ACCOUNTS_PATHS = [
@@ -220,19 +220,6 @@ const readJsonFile = (filePath: string): Record<string, unknown> | null => {
}
};
const readTextFile = (filePath: string): string | null => {
if (!fs.existsSync(filePath)) {
return null;
}
try {
const content = fs.readFileSync(filePath, 'utf8').trim();
return content || null;
} catch (error) {
console.warn(`Failed to read text file: ${filePath}`, error);
return null;
}
};
const getAuthEntry = (auth: AuthFile, aliases: string[]) => {
for (const alias of aliases) {
if (auth[alias]) {
@@ -389,7 +376,9 @@ const durationToSeconds = (duration?: number, unit?: string) => {
export const listConfiguredQuotaProviders = () => {
const auth = readAuthFile();
const configured = new Set<string>();
if (readOpenCodeGoCredential()) configured.add('opencode-go');
if (readCredential('opencode-go')) configured.add('opencode-go');
if (readCredential('ollama-cloud')) configured.add('ollama-cloud');
if (readCredential('cursor')) configured.add('cursor');
const anthropicAuth = normalizeAuthEntry(getAuthEntry(auth, ['anthropic', 'claude']));
if (anthropicAuth && ((anthropicAuth as Record<string, unknown>).access || (anthropicAuth as Record<string, unknown>).token)) {
@@ -446,9 +435,6 @@ export const listConfiguredQuotaProviders = () => {
configured.add('github-copilot-addon');
}
if (readTextFile(OLLAMA_CLOUD_COOKIE_PATH)) {
configured.add('ollama-cloud');
}
const waferAuth = normalizeAuthEntry(getAuthEntry(auth, ['wafer', 'wafer-ai', 'wafer_ai', 'wafer.ai']));
if (waferAuth && ((waferAuth as Record<string, unknown>).key || (waferAuth as Record<string, unknown>).token)) {
@@ -1346,7 +1332,7 @@ const parseOllamaSettingsHtml = (html: string) => {
};
const fetchOllamaCloudQuota = async (): Promise<ProviderResult> => {
const cookie = readTextFile(OLLAMA_CLOUD_COOKIE_PATH);
const cookie = readCredential('ollama-cloud')?.cookie;
if (!cookie) {
return buildResult({
@@ -1395,6 +1381,19 @@ const fetchOllamaCloudQuota = async (): Promise<ProviderResult> => {
}
};
const fetchCursorQuota = async (): Promise<ProviderResult> => {
const accessToken = readCredential('cursor')?.accessToken;
if (!accessToken) return buildResult({ providerId: 'cursor', providerName: 'Cursor', ok: false, configured: false, error: 'Not configured' });
try {
const response = await fetch('https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage', { method: 'POST', headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json', 'Connect-Protocol-Version': '1' }, body: '{}', signal: AbortSignal.timeout(15_000) });
if (!response.ok) throw new Error(response.status === 401 ? 'Cursor session expired' : `API error: ${response.status}`);
const payload = await response.json() as Record<string, unknown>;
const plan = (payload.planUsage as Record<string, unknown> | undefined) ?? {};
const usedPercent = toNumber(plan.totalPercentUsed);
return buildResult({ providerId: 'cursor', providerName: 'Cursor', ok: true, configured: true, usage: { windows: { billing_cycle: toUsageWindow({ usedPercent, windowSeconds: null, resetAt: toTimestamp(payload.billingCycleEnd) }) } } });
} catch (error) { return buildResult({ providerId: 'cursor', providerName: 'Cursor', ok: false, configured: true, error: error instanceof Error ? error.message : 'Request failed' }); }
};
const fetchOpenRouterQuota = async (): Promise<ProviderResult> => {
const auth = readAuthFile();
const entry = normalizeAuthEntry(getAuthEntry(auth, ['openrouter'])) as Record<string, unknown> | null;
@@ -1895,7 +1894,7 @@ export const fetchQuotaForProvider = async (providerId: string): Promise<Provide
case 'wafer':
return fetchWaferQuota();
case 'opencode-go': {
const credential = readOpenCodeGoCredential();
const credential = readCredential('opencode-go') as { workspaceId: string; authCookie: string } | null;
if (!credential) return buildResult({ providerId, providerName: 'OpenCode Go', ok: false, configured: false, error: 'Not configured' });
try {
return buildResult({ providerId, providerName: 'OpenCode Go', ok: true, configured: true, usage: { windows: await fetchOpenCodeGoUsage(credential) } });
@@ -1903,6 +1902,8 @@ export const fetchQuotaForProvider = async (providerId: string): Promise<Provide
return buildResult({ providerId, providerName: 'OpenCode Go', ok: false, configured: true, error: error instanceof Error ? error.message : 'Request failed' });
}
}
case 'cursor':
return fetchCursorQuota();
default:
return buildResult({
providerId,