npm package: @relayplane/auth-gate
Description: Auth Gate - authentication and authorization for agent operations
Author: RelayPlane
Latest version: 0.1.0

# @relayplane/auth-gate

Auth Gate — authentication and authorization for agent operations.

## Overview

The Auth Gate validates incoming requests, detects auth type (API vs consumer), determines execution mode, and enforces consumer auth restrictions based on workspace settings.

Key features:

- **Auth type detection**: API keys vs consumer subscriptions
- **Execution mode detection**: Interactive, background, scheduled
- **Consumer auth restrictions**: Safe defaults aligned with provider ToS
- **Enforcement modes**: `recommended` (default) vs `permissive`
- **Ledger integration**: Emits auth events for audit

## Installation

```bash
pnpm add @relayplane/auth-gate
```

## Quick Start

```typescript
import { createAuthGate, MemoryAuthProfileStorage } from '@relayplane/auth-gate';

// Create storage and gate
const storage = new MemoryAuthProfileStorage();
const gate = createAuthGate({ storage });

// Seed test data
const { apiProfile, consumerProfile } = await storage.seedTestData('ws_123');

// Validate an API request (background) - allowed
const apiResult = await gate.validate({
  workspace_id: 'ws_123',
  auth_profile_id: apiProfile.profile_id,
  metadata: { session_type: 'background' },
});
console.log(apiResult.allow); // true

// Validate a consumer request (background) - blocked in recommended mode
const consumerResult = await gate.validate({
  workspace_id: 'ws_123',
  auth_profile_id: consumerProfile.profile_id,
  metadata: { session_type: 'background' },
});
console.log(consumerResult.allow); // false
console.log(consumerResult.reason); // "Consumer auth is restricted..."
```

## Enforcement Modes

### `recommended` (default)

Safe defaults aligned with typical provider ToS:

| Context | Consumer Auth | API Auth |
|---------|---------------|----------|
| Interactive | ✅ Allowed | ✅ Allowed |
| Background | ❌ Blocked | ✅ Allowed |
| Scheduled | ❌ Blocked | ✅ Allowed |
| Spawned agents | ❌ Blocked | ✅ Allowed |
| Fallback chains | ❌ Blocked | ✅ Allowed |

### `permissive`

For power users who understand provider ToS implications:

| Context | Consumer Auth | API Auth |
|---------|---------------|----------|
| All contexts | ⚠️ Allowed with warning | ✅ Allowed |

When consumer auth is used in automation contexts in permissive mode:
- `auth_risk=true` is set in ledger
- `policy_override=true` is set
- Warning message included in response

## Automation Detection

The Auth Gate detects automation contexts via:

1. `X-RelayPlane-Automated: true` header
2. `session_type: 'background'` metadata
3. `scheduler_triggered: true` metadata
4. `parent_run_id` present (spawned agents)
5. `fallback_chain_position > 0`

## Execution Mode Detection

| Signal | Execution Mode |
|--------|----------------|
| `scheduler_triggered=true` | `scheduled` |
| `session_type='background'` | `background` |
| `parent_run_id` present | `background` |
| Default | `interactive` |

## API Reference

### AuthGate

```typescript
const gate = createAuthGate({
  storage: AuthProfileStorage,
  ledger?: Ledger,
  defaultSettings?: Partial<WorkspaceAuthSettings>,
});

// Validate a request
const result = await gate.validate({
  workspace_id: string,
  auth_profile_id?: string,
  api_key?: string,
  metadata: RequestMetadata,
});

// Create context from successful validation
const context = gate.createContext(request, result);

// Emit auth event to ledger
await gate.emitAuthEvent(run_id, result);
```

### AuthResult

```typescript
interface AuthResult {
  allow: boolean;
  auth_profile?: AuthProfile;
  execution_mode: ExecutionMode;
  ledger_flags: {
    auth_type: 'api' | 'consumer';
    execution_mode: ExecutionMode;
    auth_risk: boolean;
    policy_override: boolean;
  };
  reason?: string;           // If denied
  guidance_url?: string;     // Migration guidance
  warning?: string;          // If allowed with warning
}
```

## Storage Backends

### MemoryAuthProfileStorage

In-memory storage for testing and development:

```typescript
const storage = new MemoryAuthProfileStorage();

// Create profile
const profileId = await storage.createProfile({
  workspace_id: 'ws_123',
  name: 'API Keys',
  type: 'api',
  providers: [...],
  automation_allowed: true,
  interactive_only: false,
});

// Set workspace settings
await storage.updateWorkspaceSettings('ws_123', {
  auth_enforcement_mode: 'recommended',
  default_auth_profile_id: profileId,
});
```

### Custom Storage

Implement `AuthProfileStorage` interface for production:

```typescript
interface AuthProfileStorage {
  getProfile(profile_id: string): Promise<AuthProfile | null>;
  getProfileByApiKey(api_key: string): Promise<AuthProfile | null>;
  getWorkspaceProfiles(workspace_id: string): Promise<AuthProfile[]>;
  getWorkspaceSettings(workspace_id: string): Promise<WorkspaceAuthSettings | null>;
  createProfile(...): Promise<string>;
  updateProfile(...): Promise<void>;
  deleteProfile(...): Promise<void>;
  updateWorkspaceSettings(...): Promise<void>;
}
```

## License

MIT