Files
ccs/tests/unit/commands/env-command.test.ts
T
Kai (Tam Nhu) TranGitHubgithub-actions[bot] <github-actions[bot]@users.noreply.github.com>
051805074e feat: account safety, quota monitoring, and stability fixes (#530)
* fix(cliproxy): migrate deprecated gemini-claude-* model names to upstream claude-* names (#515)

* fix(cliproxy): migrate deprecated gemini-claude-* model names to upstream claude-* names

CLIProxyAPI registry no longer recognizes the gemini-claude-* prefix convention.
Model names in catalog, base config, and user settings are migrated to upstream
claude-* names. Auto-migration in env-builder rewrites existing user settings on
load and persists the change.

Closes #513

* fix: address code review feedback — sync UI layer and add migration tests

- Sync UI isNativeGeminiModel() with backend (remove gemini-claude- exclusion)
- Update UI model catalog agy entries from gemini-claude-* to claude-*
- Update CI/CD workflow and code-reviewer default model names
- Add unit tests for migrateDeprecatedModelNames() logic

* fix(hooks): isolate image type check before error-prone processing (#514)

* fix(hooks): isolate image type check before error-prone processing

Restructure processHook() into two phases so non-image Read calls
never see hook error messages. Phase 1 defensively checks tool name
and file extension, exiting 0 silently on any failure. Phase 2 only
runs for confirmed image/PDF files where errors are relevant.

Closes #511

* fix(hooks): sync image analyzer hook file on every profile launch

Add installImageAnalyzerHook() call to cliproxy executor, matching
the existing installWebSearchHook() pattern. This ensures the .cjs
file in ~/.ccs/hooks/ gets refreshed from the npm package on every
launch, so users receive hook updates after npm update.

* chore(release): 7.41.0-dev.1 [skip ci]

* fix(cliproxy): add fork:true for Claude model aliases in config generator (#523)

Config generator now outputs fork:true for Claude model alias entries,
ensuring both upstream (claude-*) and aliased (gemini-claude-*) model
names appear in /v1/models listings. Also preserves fork flag when
parsing user-added aliases during config regeneration.

Bumps config version to v7 to trigger regeneration on next ccs doctor.

Closes #522

* chore(release): 7.41.0-dev.2 [skip ci]

* feat(cliproxy): add account safety guards to prevent Google account bans (#516)

* feat(cliproxy): add account safety guards to prevent Google account bans

Implements cross-provider isolation to prevent Google from flagging
concurrent OAuth usage across different client IDs (ref: #509, #512).

Three pillars:
1. Auto-pause enforcement at session launch — conflicting accounts in
   other Google OAuth providers are paused so CLIProxyAPI can't use them,
   restored on session exit with crash recovery via auto-paused.json
2. Ban/disable detection — error responses matching Google ban patterns
   auto-pause the affected account to prevent further damage
3. Cross-provider conflict warnings during OAuth registration

Key design decisions:
- PID-based session tracking for crash recovery (dead PID = restore)
- Timestamp comparison prevents restoring ban-paused accounts on exit
- Schema validation on auto-paused.json prevents corrupted state
- Falls back to warn-only when another session is managing isolation

* fix(cliproxy): address code review feedback (attempt 1/5)

- Re-read auto-paused.json before write in enforceProviderIsolation to
  reduce concurrent write race window
- Use actual email from registry for display instead of raw accountId
- Export maskEmail for testability
- Add 27 unit tests covering ban detection, email masking,
  cross-provider duplicate detection, enforcement lifecycle,
  crash recovery, and timestamp-guarded restore

* fix(cliproxy): address remaining review feedback (attempt 2/5)

- Add handleBanDetection test verifying account pause on ban error
- Add warnCrossProviderDuplicates tests (true/false/non-Google)
- Document PID reuse limitation in isPidAlive JSDoc comment

* chore(release): 7.41.0-dev.3 [skip ci]

* feat(cliproxy): runtime quota monitoring during active sessions (#529)

* feat(cliproxy): add runtime quota monitoring during active sessions

Adds adaptive background quota polling to detect and respond to quota
exhaustion during active CLIProxy sessions. Prevents rate-limit-driven
account bans by auto-cooling exhausted accounts and switching defaults.

- Adaptive polling: 300s normal, 60s at 20% threshold, stops at 0%
- Stderr warnings at 20%, boxed exhaustion alerts at 0%
- Cooldown + default switch on exhaustion (existing patterns)
- Configurable via quota_management.runtime_monitor in config.yaml
- Timer.unref() prevents blocking process exit
- monitorStopped guard for in-flight poll safety

Closes #524

* fix: address code review feedback (attempt 1/5)

- M1: Round quotaPercent display with Math.round() to avoid ugly floats
- M2: Rename exhaust_threshold -> exhaustion_threshold for consistency
  with existing auto.exhaustion_threshold config field
- M3: Replace async not.toThrow() with direct await assertion pattern

* fix: address code review feedback (attempt 2/5)

- Remove .claude/agent-memory/ from tracking and add to .gitignore
- Unify cooldown_minutes default to 5 (was 10 in runtime_monitor, 5 in auto)
- Add threshold validation in startQuotaMonitor (warn > exhaustion)
- Document intentional post-switch monitoring gap in code comment

* chore(release): 7.41.0-dev.4 [skip ci]

* fix(cliproxy): mask email in ban detection and fix JSDoc default

- Use maskEmail() in handleBanDetection output for consistency
- Fix cooldown_minutes JSDoc: default is 5, not 10

* chore(release): 7.41.0-dev.5 [skip ci]

* fix(cliproxy): address all review feedback (Low + informational)

- Add sync constraint comment on process.exit handler (executor)
- Add TOCTOU race acceptability comment (account-safety)
- Mask email in handleQuotaExhaustion reason string
- Use realistic exhaustion_threshold (5) in test configs

* chore(release): 7.41.0-dev.6 [skip ci]

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-02-12 00:48:29 +07:00

216 lines
6.6 KiB
TypeScript

/**
* Unit tests for env-command.ts
*
* Tests pure utility functions: detectShell, formatExportLine, transformToOpenAI
*/
import { describe, it, expect, afterEach } from 'bun:test';
import {
detectShell,
formatExportLine,
transformToOpenAI,
parseFlag,
findProfile,
} from '../../../src/commands/env-command';
describe('env-command', () => {
describe('detectShell', () => {
const originalShell = process.env['SHELL'];
afterEach(() => {
if (originalShell !== undefined) {
process.env['SHELL'] = originalShell;
} else {
delete process.env['SHELL'];
}
});
it('returns explicit bash flag', () => {
expect(detectShell('bash')).toBe('bash');
});
it('returns explicit fish flag', () => {
expect(detectShell('fish')).toBe('fish');
});
it('returns explicit powershell flag', () => {
expect(detectShell('powershell')).toBe('powershell');
});
it('auto-detects bash from SHELL=/bin/zsh', () => {
process.env['SHELL'] = '/bin/zsh';
expect(detectShell('auto')).toBe('bash');
});
it('auto-detects bash from SHELL=/bin/bash', () => {
process.env['SHELL'] = '/bin/bash';
expect(detectShell()).toBe('bash');
});
it('auto-detects fish from SHELL=/usr/bin/fish', () => {
process.env['SHELL'] = '/usr/bin/fish';
expect(detectShell('auto')).toBe('fish');
});
it('defaults to bash when SHELL is empty', () => {
process.env['SHELL'] = '';
expect(detectShell()).toBe('bash');
});
it('ignores invalid flag and auto-detects', () => {
process.env['SHELL'] = '/bin/bash';
expect(detectShell('invalid')).toBe('bash');
});
it('auto-detects powershell from SHELL containing pwsh', () => {
process.env['SHELL'] = '/usr/local/bin/pwsh';
expect(detectShell('auto')).toBe('powershell');
});
});
describe('formatExportLine', () => {
it('formats bash export', () => {
expect(formatExportLine('bash', 'API_KEY', 'sk-123')).toBe("export API_KEY='sk-123'");
});
it('formats fish export', () => {
expect(formatExportLine('fish', 'API_KEY', 'sk-123')).toBe("set -gx API_KEY 'sk-123'");
});
it('formats powershell export', () => {
expect(formatExportLine('powershell', 'API_KEY', 'sk-123')).toBe(
"$env:API_KEY = 'sk-123'"
);
});
it('escapes single quotes in values', () => {
expect(formatExportLine('bash', 'VAL', "it's here")).toBe(
"export VAL='it'\\''s here'"
);
});
it('handles empty values', () => {
expect(formatExportLine('bash', 'EMPTY', '')).toBe("export EMPTY=''");
});
it('handles URLs with special characters', () => {
const url = 'http://127.0.0.1:8317/api/provider/gemini';
expect(formatExportLine('bash', 'BASE_URL', url)).toBe(`export BASE_URL='${url}'`);
});
it('prevents shell injection with $() in values', () => {
expect(formatExportLine('bash', 'TOKEN', 'safe$(whoami)')).toBe(
"export TOKEN='safe$(whoami)'"
);
});
it('prevents backtick injection in values', () => {
expect(formatExportLine('bash', 'TOKEN', 'safe`whoami`')).toBe(
"export TOKEN='safe`whoami`'"
);
});
it('escapes single quotes in fish values', () => {
expect(formatExportLine('fish', 'VAL', "it's here")).toBe("set -gx VAL 'it'\\''s here'");
});
it('escapes single quotes in powershell values', () => {
expect(formatExportLine('powershell', 'VAL', "it's here")).toBe(
"$env:VAL = 'it''s here'"
);
});
});
describe('transformToOpenAI', () => {
it('maps Anthropic vars to OpenAI format', () => {
const result = transformToOpenAI({
ANTHROPIC_BASE_URL: 'http://127.0.0.1:8317/api/provider/gemini',
ANTHROPIC_AUTH_TOKEN: 'ccs-internal-managed',
ANTHROPIC_MODEL: 'claude-sonnet-4-5',
});
expect(result).toEqual({
OPENAI_API_KEY: 'ccs-internal-managed',
OPENAI_BASE_URL: 'http://127.0.0.1:8317/api/provider/gemini',
LOCAL_ENDPOINT: 'http://127.0.0.1:8317/api/provider/gemini',
OPENAI_MODEL: 'claude-sonnet-4-5',
});
});
it('handles missing source vars gracefully', () => {
const result = transformToOpenAI({});
expect(result).toEqual({});
});
it('only extracts relevant vars', () => {
const result = transformToOpenAI({
ANTHROPIC_BASE_URL: 'http://localhost:8317',
ANTHROPIC_AUTH_TOKEN: 'key',
ANTHROPIC_MAX_TOKENS: '8096',
DISABLE_TELEMETRY: '1',
});
// OPENAI_API_KEY + OPENAI_BASE_URL + LOCAL_ENDPOINT (no OPENAI_MODEL when ANTHROPIC_MODEL absent)
expect(Object.keys(result)).toHaveLength(3);
expect(result['ANTHROPIC_MAX_TOKENS']).toBeUndefined();
});
it('omits OPENAI_MODEL when ANTHROPIC_MODEL absent', () => {
const result = transformToOpenAI({
ANTHROPIC_BASE_URL: 'http://localhost:8317',
ANTHROPIC_AUTH_TOKEN: 'key',
});
expect(result['OPENAI_MODEL']).toBeUndefined();
});
});
describe('parseFlag', () => {
it('parses --flag=value style', () => {
expect(parseFlag(['--format=openai'], 'format')).toBe('openai');
});
it('parses --flag value style', () => {
expect(parseFlag(['--format', 'openai'], 'format')).toBe('openai');
});
it('handles values containing =', () => {
expect(parseFlag(['--format=key=val=ue'], 'format')).toBe('key=val=ue');
});
it('returns undefined for missing flag', () => {
expect(parseFlag(['--shell', 'bash'], 'format')).toBeUndefined();
});
it('does not consume next flag as value', () => {
expect(parseFlag(['--format', '--shell'], 'format')).toBeUndefined();
});
});
describe('findProfile', () => {
it('finds profile as first positional arg', () => {
expect(findProfile(['gemini'], ['format', 'shell'])).toBe('gemini');
});
it('skips flags before profile', () => {
expect(findProfile(['--format', 'openai', 'gemini'], ['format', 'shell'])).toBe('gemini');
});
it('skips --flag=value style flags', () => {
expect(findProfile(['--format=openai', 'gemini'], ['format', 'shell'])).toBe('gemini');
});
it('handles profile before flags', () => {
expect(findProfile(['gemini', '--format', 'openai'], ['format', 'shell'])).toBe('gemini');
});
it('returns undefined when no positional args', () => {
expect(findProfile(['--format', 'openai', '--shell', 'fish'], ['format', 'shell'])).toBeUndefined();
});
it('skips multiple flag-value pairs', () => {
expect(findProfile(['--format', 'openai', '--shell', 'fish', 'codex'], ['format', 'shell'])).toBe('codex');
});
});
});