# @quantiya/codevibe-core

Core library for CodeVibe plugins — shared keychain, crypto, AppSync, authentication, session lifecycle, and network-resilience functionality. Used by [`@quantiya/codevibe-claude-plugin`](https://www.npmjs.com/package/@quantiya/codevibe-claude-plugin), [`@quantiya/codevibe-gemini-plugin`](https://www.npmjs.com/package/@quantiya/codevibe-gemini-plugin), and [`@quantiya/codevibe-codex-plugin`](https://www.npmjs.com/package/@quantiya/codevibe-codex-plugin).

**Current version:** `1.0.3`

## Installation

```bash
npm install @quantiya/codevibe-core
```

## Features

- **Keychain Management** — Secure storage for device keys and OAuth tokens using native keychain (macOS Keychain, Linux libsecret, Windows Credential Manager)
- **Cryptographic Services** — E2E encryption using ECDH P-256 and AES-256-GCM, with dedicated helpers for event content, metadata, and binary attachments
- **AppSync Client** — GraphQL API and WebSocket subscriptions for AWS AppSync, with automatic token refresh
- **Two-phase WebSocket reconnection** — exponential backoff (1s→60s) for 10 attempts, then persistent 5-minute retry indefinitely. Survives laptop sleep, network drops, DNS blips, and extended outages without ever giving up.
- **Session heartbeat system** — `startHeartbeat(sessionId)` sends `updateSession({ lastHeartbeatAt })` every 2 minutes so mobile clients can show desktop connectivity status (green/red dot with 5-minute staleness threshold)
- **Centralized session lifecycle** — `resumeOrCreateSession()` is the single source of truth for session fingerprint matching, reuse, and per-device ECDH session key distribution. Used identically by all three plugins.
- **WSL-aware networking** — auto-detects WSL via `/proc/sys/kernel/osrelease` and applies IPv4-first DNS ordering to work around broken WSL IPv6 stacks. Zero behavioral change on macOS, native Linux, and Windows.
- **Diagnostic fetch wrapper** — `fetchWithDiagnostics()` unpacks undici's generic "fetch failed" errors into detailed platform-specific messages (DNS failures, TLS clock skew, corporate MITM proxies, etc.) so failures are debuggable without trawling logs.
- **Cross-platform browser launcher** — `AuthService` opens the user's default browser during OAuth login via `wslview` → `cmd.exe` → `powershell.exe` → `xdg-open` fallback chain on Linux/WSL, native `open` on macOS, `cmd /c start` on Windows. Always prints the sign-in URL to stdout as a copy-paste fallback if automatic launching fails.
- **Authentication CLI** — Browser-based OAuth login/logout commands (Sign in with Apple / Sign in with Google via Cognito)
- **Prompt Parser** — Extracts numbered options from tmux pane snapshots so plugins can forward the exact options a CLI offers to mobile clients without hardcoding
- **Shared TypeScript types** — Events, sessions, attachments, encryption structures used across all plugins

## CLI Usage

```bash
# Sign in via browser (opens Cognito Hosted UI)
codevibe login

# Sign out
codevibe logout

# Check authentication status
codevibe status

# Reset device identity (destructive - old sessions become inaccessible)
codevibe reset-device

# Use specific environment
codevibe --env development login
```

## API Usage

### Keychain Manager

```typescript
import { keychainManager, DeviceIdentity } from '@quantiya/codevibe-core';

// Get or create device identity (stored in native keychain)
const identity = await keychainManager.getOrCreateDeviceIdentity();
console.log(identity.deviceId, identity.publicKey);

// Get OAuth tokens
const tokens = await keychainManager.getTokens('production');
if (tokens) {
  console.log(tokens.email, tokens.userId);
}
```

### Crypto Service

```typescript
import { cryptoService } from '@quantiya/codevibe-core';

// Generate key pair
const keyPair = cryptoService.generateKeyPair();

// Generate session key
const sessionKey = cryptoService.generateSessionKey();

// Encrypt content
const encrypted = cryptoService.encryptContent('Hello World', sessionKey);

// Decrypt content
const decrypted = cryptoService.decryptContent(encrypted, sessionKey);
```

### AppSync Client

```typescript
import { AppSyncClient, loadConfig } from '@quantiya/codevibe-core';

// Load environment configuration
loadConfig('production');

// Create client
const client = new AppSyncClient('production');

// Authenticate with stored tokens
const authenticated = await client.authenticateWithStoredTokens();
if (!authenticated) {
  console.log('Run "codevibe login" first');
  process.exit(1);
}

// Create session
const session = await client.createSession({
  userId: client.getCurrentUserId(),
  agentType: 'CLAUDE',
  projectPath: '/path/to/project',
});

// Subscribe to events
const unsubscribe = client.subscribeToEvents(session.sessionId, (event) => {
  console.log('Event received:', event);
});

// Clean up
unsubscribe();
```

### Auth Service

```typescript
import { authService, loadConfig } from '@quantiya/codevibe-core';

// Set environment
loadConfig('production');
authService.setEnvironment('production');

// Login (opens browser)
const tokens = await authService.login();

// Check status
const status = await authService.getStatus();
console.log(status.authenticated, status.tokens?.email);

// Logout
await authService.logout();
```

## Keychain Storage

All sensitive data is stored in the native system keychain:

- **Service Name:** `ai.quantiya.app.codevibe`
- **Device Identity:** Stored as `device-identity` account
- **Tokens:** Stored as `tokens-{environment}` accounts (e.g., `tokens-production`)

This ensures:
- Data persists across terminal sessions
- Data is encrypted at rest by the OS
- Data survives plugin reinstalls/updates
- Device identity is shared across all CodeVibe plugins

## Security

- Device keys are ECDH P-256 key pairs
- Session keys are 256-bit AES keys
- Content is encrypted with AES-256-GCM
- Session keys are encrypted per-device using ECDH
- OAuth tokens are stored securely in native keychain

## Development

```bash
# Install dependencies
npm install

# Build
npm run build

# Watch mode
npm run watch

# Local development with plugin
npm link
cd ../codevibe-claude-plugin
npm link @quantiya/codevibe-core
```

## License

MIT
