# External Integrations

**Analysis Date:** 2026-04-27

## APIs & External Services

**Anthropic Claude API:**
- Service: Claude API for real-time translation of game content to German
- What it's used for:
  - On-demand translation of feats, equipment, spells, items, conditions, and other PF2e content
  - Translates item effect text for alchemical items
  - Batches translations in groups for efficiency
  - Results cached in `Translation` table with quality ratings (HIGH/MEDIUM/LOW)
  - Fallback: System returns untranslated English names if API key not configured
  - Model: `claude-haiku-4-5-20251001` (lightweight model for cost-effective translations)

- SDK/Client: `@anthropic-ai/sdk` 0.71.2
- Auth: Environment variable `ANTHROPIC_API_KEY`
- Implementation: `server/src/modules/claude/claude.service.ts`
- Module: `server/src/modules/claude/claude.module.ts`
- Usage: Called by `server/src/modules/translations/translations.service.ts`

## Data Storage

**Databases:**
- PostgreSQL 16 (via Docker Compose or production instance)
  - Connection: Environment variable `DATABASE_URL`
  - Client: Prisma ORM 7.2.0 with PostgreSQL adapter
  - Schema: `server/prisma/schema.prisma` (25 models covering users, campaigns, characters, equipment, alchemy, battle, documents)
  - Migrations: Version-controlled in `server/prisma/migrations/`
  - Seeding: `server/prisma/seed.ts` (base data), `server/prisma/seed-equipment.ts` (5,482 PF2e items), `server/prisma/seed-feats.ts`

**File Storage:**
- Local filesystem only (currently)
  - Directory: Configured via `UPLOAD_DIR` env var (default `./uploads`)
  - Served via NestJS `ServeStaticModule` at `/uploads` endpoint
  - Max file size: `MAX_FILE_SIZE` env var (default 10MB)
  - Types supported: HTML, PDF (from schema `Document` model)

**Caching:**
- In-memory client state via Zustand (auth store): `client/src/features/auth/hooks/use-auth-store.ts`
- Server-side caching via TanStack React Query: Automatic cache of API responses with configurable stale times
- Translation cache in `Translation` table with `@@unique([type, englishName])` constraint
- No Redis or external cache layer currently

## Authentication & Identity

**Auth Provider:**
- Custom JWT-based authentication (no external OAuth provider)
  - Implementation: `server/src/modules/auth/auth.service.ts`
  - Strategy: Passport.js with JWT strategy (`server/src/modules/auth/strategies/jwt.strategy.ts`)
  
**Authentication Flow:**
1. Users register with username, email, password via `POST /api/auth/register`
2. Passwords hashed with bcrypt (salt rounds: 10, configurable)
3. Login returns JWT token valid for `JWT_EXPIRES_IN` (default "7d")
4. Client stores token in localStorage (persistent) or sessionStorage (session-only)
   - Determined by "Remember me" checkbox during login
   - Implementation: `client/src/shared/lib/api.ts`
5. Token attached to all subsequent requests via Authorization header
6. Token verified on WebSocket connection via `characters.gateway.ts` and `battle.gateway.ts`

**User Roles:**
- ADMIN - Full system access
- GM - Game Master, can manage campaigns, create NPCs, control battles
- PLAYER - Standard user, can own characters

**Guards:**
- Global JWT auth guard: `server/src/modules/auth/guards/jwt-auth.guard.ts`
- Role-based guard: `server/src/modules/auth/guards/roles.guard.ts`

## Monitoring & Observability

**Error Tracking:**
- None (no Sentry, Rollbar, or external service configured)
- Server logs to console via NestJS Logger
- Client console errors only

**Logs:**
- Server: NestJS Logger (console output in development, can be piped to file in production)
- Client: Browser console only
- No centralized logging infrastructure

## CI/CD & Deployment

**Hosting:**
- Not configured (manual deployment expected)
- Docker Compose available for local development

**CI Pipeline:**
- None detected
- ESLint, Prettier, and tests are run locally before commit

## WebSockets & Real-Time Communication

**Transport:**
- Socket.io 4.8.3
- Client library: `socket.io-client` 4.8.3
- Server: NestJS WebSocket gateways with Socket.io adapter

**Character Updates (Real-Time Sync):**
- Gateway: `server/src/modules/characters/characters.gateway.ts`
- Namespace: `/characters`
- CORS configured from environment variable `CORS_ORIGINS`
- Authentication: JWT token verified on connection
- Update types:
  - `hp` - Health points (current, temp, max)
  - `conditions` - Add/remove/update character conditions
  - `item` - Add/remove inventory items
  - `inventory` - Bulk inventory updates
  - `money` - Update credits/currency
  - `level` - Character level changes
  - `equipment_status` - Mark items as equipped/unequipped/invested
  - `rest` - Rest cycle triggers (HP restore, condition cleanup)
  - `alchemy_vials` - Update alchemist versatile vials
  - `alchemy_formulas` - Add/remove formulae
  - `alchemy_prepared` - Update prepared alchemical items
  - `alchemy_state` - Update research field and advanced alchemy state
  - `dying` - Dying and recovery state

**Battle Updates (Real-Time Sync):**
- Gateway: `server/src/modules/battle/battle.gateway.ts`
- Update types:
  - `token_added` - New combatant token on map
  - `token_removed` - Token removed
  - `token_moved` - Position changed
  - `token_updated` - Stat/property updates
  - `token_hp_changed` - HP/damage tracking
  - `initiative_set` - Initiative order
  - `round_advanced` - Round counter
  - `session_updated` - Session state
  - `session_deleted` - Battle session ended

**Client Hooks:**
- `client/src/features/characters/hooks/use-character-socket.ts` - Character update subscriptions
- `client/src/features/battle/hooks/use-battle-socket.ts` - Battle update subscriptions
- Singleton socket pattern to prevent multiple connections
- Reference counting for cleanup on unmount

## Pathbuilder Integration

**Import Format:**
- Reads JSON export from Pathbuilder 2e character builder
- Stored as raw JSON blob in `Character.pathbuilderData` field
- Used to populate character stats, feats, skills, spells on initial import

**Data Mapping:**
- Character abilities (STR, DEX, CON, INT, WIS, CHA)
- Skills with proficiency levels
- Feats with sources (Class, Ancestry, General, Skill, Bonus, Archetype)
- Spells with traditions and prepared status
- Equipment and inventory
- Alchemy (if applicable)

**Endpoint:**
- `POST /api/characters/import-pathbuilder` - Import character from Pathbuilder JSON

## Equipment Database

**Data Source:**
- 5,482 Pathfinder 2e equipment items imported from JSON
- Seed script: `server/prisma/seed-equipment.ts`
- Source: JSON data files in `server/prisma/data/`

**Categories:**
- Weapons (with damage, range, properties)
- Armor (with AC, penalties, strength requirements)
- Shields (with HP, hardness, broken threshold)
- Consumables (potions, scrolls, talismans, etc.)
- General equipment

**API Endpoints:**
- `GET /api/equipment` - Search/list equipment
- `GET /api/equipment/categories` - List available categories
- `GET /api/equipment/weapons` - Weapon-specific query
- `GET /api/equipment/armor` - Armor-specific query

## External References

**Archon Omni Documentation (AONPRD):**
- Links stored in `Feat.url`, `Equipment.url`, `Spell.url`, `Trait.url`
- Frontend links to official Pathfinder 2e documentation
- No direct API integration, read-only external links

## Environment Configuration

**Required Environment Variables:**

Server (`server/.env`):
- `DATABASE_URL` - PostgreSQL connection string (e.g., `postgresql://user:pass@localhost:5432/dimension47?schema=public`)
- `JWT_SECRET` - Secret key for signing JWT tokens (minimum 32 characters recommended)
- `JWT_EXPIRES_IN` - Token expiration (default "7d")
- `PORT` - Server listen port (default 5000)
- `NODE_ENV` - Environment mode (development/production)
- `CORS_ORIGINS` - Comma-separated allowed origins (e.g., `http://localhost:5173,http://localhost:3000`)
- `ANTHROPIC_API_KEY` - Claude API key (optional, disables translations if missing)
- `UPLOAD_DIR` - File upload directory (default `./uploads`)
- `MAX_FILE_SIZE` - Max upload size in bytes (default 10485760 = 10MB)

Client (`client/.env`):
- `VITE_API_URL` - Backend API URL (e.g., `http://localhost:5000/api`)

**Secrets Location:**
- `.env` files (NOT committed to git, see `.gitignore`)
- Template files: `server/.env.example` and `client/.env.example`
- Developers copy examples to `.env` and fill in secrets

## Webhooks & Callbacks

**Incoming:**
- None configured

**Outgoing:**
- None configured

## Cross-Domain Communication

**CORS Policy:**
- Configured via `CORS_ORIGINS` environment variable
- Applied to HTTP endpoints and WebSocket connections
- Development allows all `localhost:*` origins
- Production requires explicit whitelist

---

*Integration audit: 2026-04-27*
