# Design System Server - API Specification (IMMUTABLE)

**Document Version:** 1.0-IMMUTABLE
**Created:** 2025-12-08
**Status:** Immutable Reference Document
**Lock Date:** 2025-12-08
**Authority:** Project Technical Specification

---

## 🔒 IMMUTABILITY NOTICE

This document defines the complete API specification for the Design System Server platform. Once committed, this specification becomes the source of truth and should not be modified without version bump and full audit trail.

**All changes to this specification MUST:**
1. Create new version (e.g., 1.1-IMMUTABLE)
2. Document reason for change in changelog
3. Include migration path for existing consumers
4. Be reviewed and approved by technical lead
5. Trigger client library updates

---

## API OVERVIEW

**API Base URL:** `https://dss.overbits.luz.uy/api` (Production)
**Development Base URL:** `http://localhost:3001/api`
**API Version:** 1.0
**Response Format:** JSON
**Authentication:** JWT Bearer Token
**Rate Limit:** 100 requests per 15 minutes per user

---

## AUTHENTICATION

### Login Endpoint
```
POST /auth/login
Content-Type: application/json

Request:
{
  "email": "user@example.com",
  "password": "password"
}

Response (200):
{
  "status": "success",
  "code": "LOGIN_SUCCESS",
  "message": "Login successful",
  "data": {
    "user": {
      "id": "uuid",
      "email": "user@example.com",
      "name": "User Name",
      "role": "admin|editor|viewer"
    },
    "tokens": {
      "accessToken": "jwt_token",
      "refreshToken": "jwt_token"
    }
  }
}
```

### Authorization Header
```
Authorization: Bearer <accessToken>
```

Token expiry: 1 hour (3600 seconds)
Refresh token expiry: 30 days

---

## STANDARD RESPONSE FORMAT

### Success Response
```json
{
  "status": "success",
  "code": "OPERATION_CODE",
  "message": "Human readable description",
  "data": {
    // Response-specific data
  }
}
```

HTTP Status: 200, 201, 202, 204

### Error Response
```json
{
  "status": "error",
  "code": "ERROR_CODE",
  "message": "Error description",
  "data": null
}
```

HTTP Status: 400, 401, 403, 404, 409, 500, 503

---

## HTTP STATUS CODES

| Code | Meaning | Use Case |
|------|---------|----------|
| 200 | OK | Successful GET/PUT request |
| 201 | Created | Resource created successfully (POST) |
| 202 | Accepted | Async operation queued |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Invalid input/validation error |
| 401 | Unauthorized | Missing or invalid JWT token |
| 403 | Forbidden | Valid token but insufficient permissions |
| 404 | Not Found | Resource does not exist |
| 409 | Conflict | Resource already exists (duplicate) |
| 500 | Internal Server Error | Unexpected server error |
| 503 | Service Unavailable | Server at capacity/maintenance |

---

## PHASE 1 ENDPOINTS (IMMUTABLE)

### Configuration
```
GET /config
Auth: None
Response: 200 OK
{
  "status": "success",
  "code": "CONFIG_RETRIEVED",
  "data": {
    "app": { "name": "Design System Server", "version": "1.0.0" },
    "features": { /* feature flags */ }
  }
}
```

### Server Logging
```
POST /logs
Auth: JWT (Required)
Request: { "level": "log|warn|error|info|debug", "message": "string", "context": {} }
Response: 201 Created
{
  "status": "success",
  "code": "LOG_CREATED",
  "data": { "logId": "uuid", "timestamp": "iso-string" }
}
```

### Browser Logging
```
POST /logs/browser
Auth: JWT (Required)
Request: { "level": "string", "message": "string", "url": "string", "userAgent": "string" }
Response: 201 Created
```

### Retrieve Logs
```
GET /logs?level=error&source=browser&limit=100&offset=0
Auth: JWT (Required)
Response: 200 OK
{
  "status": "success",
  "code": "LOGS_RETRIEVED",
  "data": {
    "total": 150,
    "limit": 100,
    "offset": 0,
    "logs": [{ "id": "uuid", "level": "string", "message": "string", "timestamp": "iso-string" }]
  }
}
```

---

## PHASE 2 ENDPOINTS (IMMUTABLE)

### Notifications (Server-Sent Events)
```
GET /notifications/events
Auth: JWT (Required)
Type: SSE (Server-Sent Events)
Response: 200 OK (persistent connection)

Events format:
data: {"type": "connection:established|notification", "timestamp": "iso-string", "data": {}}

Example notification:
data: {"type": "project:created", "timestamp": "2025-12-08T20:35:15.972Z", "data": {"projectId": "uuid"}}
```

### Notification Statistics
```
GET /notifications/stats
Auth: JWT (Required, Admin only)
Response: 200 OK
{
  "status": "success",
  "code": "NOTIFICATION_STATS",
  "data": {
    "totalSubscribers": 5,
    "userCount": 3,
    "byUser": { "user-id": 2, "user-id-2": 1 }
  }
}
```

### Test Notification
```
POST /notifications/test
Auth: JWT (Required)
Request: { "message": "string" }
Response: 200 OK
{
  "status": "success",
  "code": "TEST_NOTIFICATION_SENT",
  "data": { "timestamp": "iso-string" }
}
```

### List MCP Tools
```
GET /mcp/tools
Auth: JWT (Required)
Response: 200 OK
{
  "status": "success",
  "code": "MCP_TOOLS_LIST",
  "data": {
    "tools": [
      {
        "name": "dss-analyze-project",
        "description": "Analyze codebase for design patterns",
        "params": { "projectPath": "string", "depth": "number" }
      }
    ]
  }
}
```

### Execute MCP Tool
```
POST /mcp/tools/:name/execute
Auth: JWT (Required)
Request: { "projectPath": "string", "depth": 2 }
Response: 202 Accepted
{
  "status": "success",
  "code": "TOOL_EXECUTION_QUEUED",
  "data": { "estimatedDuration": "30-60 seconds" }
}
```

### Discover Project
```
POST /mcp/discover_project
Auth: JWT (Required)
Request: { "projectId": "uuid", "path": "string", "depth": 2 }
Response: 202 Accepted
{
  "status": "success",
  "code": "DISCOVERY_QUEUED",
  "data": {
    "discoveryId": "string",
    "estimatedTime": "2-5 minutes",
    "pollEndpoint": "/api/discovery/activity"
  }
}
```

### Get Quick Wins
```
POST /mcp/get_quick_wins
Auth: JWT (Required)
Request: { "projectId": "uuid", "path": "string" }
Response: 202 Accepted
{
  "status": "success",
  "code": "QUICK_WINS_ANALYSIS_QUEUED",
  "data": {
    "analysisId": "string",
    "expectedWins": ["string"],
    "estimatedTime": "1-3 minutes"
  }
}
```

### Tool Callback (Webhook)
```
POST /mcp/callback
Auth: None
Request: { "toolName": "string", "status": "completed|failed", "data": {}, "projectId": "uuid" }
Response: 200 OK
{
  "status": "success",
  "code": "CALLBACK_ACKNOWLEDGED",
  "data": null
}
```

---

## PHASE 3 ENDPOINTS (IMMUTABLE - DESIGNED, NOT YET IMPLEMENTED)

### Team Operations

#### List Teams
```
GET /teams
Auth: JWT (Required)
Response: 200 OK
{
  "status": "success",
  "code": "TEAMS_RETRIEVED",
  "data": {
    "teams": [
      {
        "id": "uuid",
        "name": "Design System",
        "description": "string",
        "ownerId": "uuid",
        "settings": {}
      }
    ]
  }
}
```

#### Create Team
```
POST /teams
Auth: JWT (Required)
Request: { "name": "string (required)", "description": "string (optional)" }
Response: 201 Created
{
  "status": "success",
  "code": "TEAM_CREATED",
  "data": { "team": { "id": "uuid", "name": "string", "ownerId": "uuid" } }
}
```

#### Get Team
```
GET /teams/:id
Auth: JWT (Required, must be team member)
Response: 200 OK
{
  "status": "success",
  "code": "TEAM_RETRIEVED",
  "data": { "team": { /* team object */ } }
}
```

#### Update Team
```
PUT /teams/:id
Auth: JWT (Required, admin only)
Request: { "name": "string", "description": "string" }
Response: 200 OK
{
  "status": "success",
  "code": "TEAM_UPDATED",
  "data": { "team": { /* updated team */ } }
}
```

#### Delete Team
```
DELETE /teams/:id
Auth: JWT (Required, owner only)
Response: 200 OK
{
  "status": "success",
  "code": "TEAM_DELETED",
  "data": null
}
```

### Team Member Management

#### List Members
```
GET /teams/:id/members
Auth: JWT (Required, team member)
Response: 200 OK
{
  "status": "success",
  "code": "TEAM_MEMBERS_RETRIEVED",
  "data": {
    "members": [
      {
        "id": "uuid",
        "teamId": "uuid",
        "userId": "uuid",
        "role": "admin|editor|viewer",
        "joinedAt": "iso-string"
      }
    ]
  }
}
```

#### Add Member
```
POST /teams/:id/members
Auth: JWT (Required, admin only)
Request: { "userId": "uuid (required)", "role": "viewer|editor|admin" }
Response: 201 Created
{
  "status": "success",
  "code": "MEMBER_ADDED",
  "data": { "member": { /* member object */ } }
}
```

#### Update Member Role
```
PUT /teams/:id/members/:memberId
Auth: JWT (Required, admin only)
Request: { "role": "admin|editor|viewer" }
Response: 200 OK
{
  "status": "success",
  "code": "MEMBER_UPDATED",
  "data": { "member": { /* updated member */ } }
}
```

#### Remove Member
```
DELETE /teams/:id/members/:memberId
Auth: JWT (Required, admin only)
Response: 200 OK
{
  "status": "success",
  "code": "MEMBER_REMOVED",
  "data": null
}
```

### Team Settings

#### Get Settings
```
GET /teams/:id/settings
Auth: JWT (Required, team member)
Response: 200 OK
{
  "status": "success",
  "code": "TEAM_SETTINGS_RETRIEVED",
  "data": {
    "settings": {
      "teamId": "uuid",
      "allowMemberInvites": boolean,
      "requireApprovalForProjects": boolean,
      "defaultRole": "viewer",
      "features": {}
    }
  }
}
```

#### Update Settings
```
PUT /teams/:id/settings
Auth: JWT (Required, admin only)
Request: { "allowMemberInvites": boolean, "defaultRole": "string" }
Response: 200 OK
{
  "status": "success",
  "code": "TEAM_SETTINGS_UPDATED",
  "data": { "settings": { /* updated settings */ } }
}
```

### Team Dashboard

#### Get Dashboard
```
GET /teams/:id/dashboard
Auth: JWT (Required, team member)
Response: 200 OK
{
  "status": "success",
  "code": "TEAM_DASHBOARD_RETRIEVED",
  "data": {
    "dashboard": {
      "teamId": "uuid",
      "memberCount": 5,
      "activeMembers": 4,
      "stats": {
        "projectsCreatedThisMonth": 3,
        "componentsCreatedThisMonth": 12,
        "tokensUpdatedThisMonth": 47
      },
      "recentActivity": []
    }
  }
}
```

---

## PHASE 4 ENDPOINTS (IMMUTABLE - DESIGNED, NOT YET IMPLEMENTED)

### Discovery & Analysis

#### Start Discovery Scan
```
POST /discovery/scan
Auth: JWT (Required)
Request: { "projectId": "uuid (required)", "type": "project-analysis|quick-wins|component-audit|token-extraction" }
Response: 202 Accepted
{
  "status": "success",
  "code": "DISCOVERY_SCAN_STARTED",
  "data": {
    "discoveryId": "uuid",
    "status": "queued",
    "estimatedTime": "2-5 minutes"
  }
}
```

#### Get Discovery Activity
```
GET /discovery/activity?projectId=uuid&limit=50&offset=0
Auth: JWT (Required)
Response: 200 OK
{
  "status": "success",
  "code": "DISCOVERY_ACTIVITY_RETRIEVED",
  "data": {
    "total": 100,
    "limit": 50,
    "offset": 0,
    "activities": [
      {
        "id": "uuid",
        "projectId": "uuid",
        "type": "project-analysis",
        "status": "completed",
        "progress": 100,
        "startedAt": "iso-string",
        "completedAt": "iso-string"
      }
    ]
  }
}
```

#### Get Discovery Statistics
```
GET /discovery/stats
Auth: JWT (Required)
Response: 200 OK
{
  "status": "success",
  "code": "DISCOVERY_STATS_RETRIEVED",
  "data": {
    "stats": {
      "total": 50,
      "byType": { "project-analysis": 30, "quick-wins": 15, "component-audit": 5 },
      "byStatus": { "completed": 45, "running": 3, "failed": 2 },
      "recentCompleted": { /* discovery object */ }
    }
  }
}
```

---

## PHASE 5 ENDPOINTS (IMMUTABLE - ROADMAP)

### 5A: Figma Integration (9 endpoints)
1. `GET /figma/health` - API health check
2. `POST /figma/extract-variables` - Extract Figma variables
3. `POST /figma/extract-components` - Extract components
4. `POST /figma/extract-styles` - Extract design tokens
5. `POST /figma/sync-tokens` - Bidirectional sync
6. `POST /figma/visual-diff` - Visual comparison
7. `POST /figma/validate-components` - Validate compliance
8. `POST /figma/generate-code` - Generate code
9. `POST /figma/export-assets` - Export assets

### 5B: QA/Testing (2 endpoints)
1. `POST /qa/screenshot-compare` - Visual regression
2. `POST /test/run` - Execute tests

### 5C: Services (6+ endpoints)
1. `POST /claude/chat` - Claude AI chat
2. `POST /ai/chat` - Generic AI chat
3. `POST /dss/save-tokens` - Save design tokens
4. `POST /navigation/generate` - Generate navigation
5. `POST /system/reset` - Admin reset (DANGEROUS)
6. `GET /assets/list` - List design assets

---

## ERROR CODES REFERENCE

| Code | HTTP | Meaning |
|------|------|---------|
| VALIDATION_ERROR | 400 | Invalid input validation |
| UNAUTHORIZED | 401 | Missing/invalid JWT |
| FORBIDDEN | 403 | Insufficient permissions |
| NOT_FOUND | 404 | Resource doesn't exist |
| DUPLICATE_KEY | 409 | Resource already exists |
| TEAM_NOT_FOUND | 404 | Team doesn't exist |
| MEMBER_NOT_FOUND | 404 | Team member doesn't exist |
| PROJECT_NOT_FOUND | 404 | Project doesn't exist |
| TOOL_NOT_FOUND | 404 | MCP tool not found |
| TOOL_EXECUTION_QUEUED | 202 | Tool queued successfully |
| DISCOVERY_QUEUED | 202 | Discovery queued |
| INTERNAL_SERVER_ERROR | 500 | Unexpected error |
| SERVICE_UNAVAILABLE | 503 | Server at capacity |

---

## ROLE-BASED ACCESS CONTROL (RBAC)

### Role Definitions
- **Admin** - Full control, can manage team, members, settings
- **Editor** - Can create/edit projects, components, tokens
- **Viewer** - Read-only access, cannot modify anything

### Permission Matrix
| Action | Admin | Editor | Viewer |
|--------|-------|--------|--------|
| Create Team | ✓ | ✗ | ✗ |
| Update Team | ✓ | ✗ | ✗ |
| Delete Team | ✓ (owner) | ✗ | ✗ |
| Manage Members | ✓ | ✗ | ✗ |
| Create Project | ✓ | ✓ | ✗ |
| Edit Project | ✓ | ✓ | ✗ |
| View Project | ✓ | ✓ | ✓ |
| Delete Project | ✓ | ✓ (owner) | ✗ |

---

## VERSIONING & CHANGELOG

### Version History
- **1.0-IMMUTABLE** (2025-12-08) - Initial API specification
  - Phase 1-2: 12 endpoints implemented
  - Phase 3-4: 15 endpoints designed
  - Phase 5: 17+ endpoints planned

### Change Process
All changes to this specification require:
1. Version number increment
2. Detailed change documentation
3. Migration guide for clients
4. Technical lead approval
5. Client notification period (minimum 30 days for breaking changes)

---

## DEPLOYMENT CHECKLIST

### Before Deploying
- [ ] All endpoints tested locally with curl
- [ ] Database migrations prepared and tested
- [ ] Error handling implemented for all cases
- [ ] RBAC verified on protected endpoints
- [ ] Rate limiting configured
- [ ] Logging configured
- [ ] Monitoring alerts set up

### Rollback Plan
- [ ] Database rollback scripts prepared
- [ ] Code rollback procedure documented
- [ ] Backup of production data taken
- [ ] Team notified of deployment

### Post-Deployment
- [ ] Verify all endpoints responding
- [ ] Monitor error logs
- [ ] Check performance metrics
- [ ] Verify database persistence
- [ ] Test RBAC in production

---

## SUPPORT & DOCUMENTATION

**API Documentation:** This specification
**Implementation Guide:** `/PHASE_3_4_5_IMPLEMENTATION.md`
**Error Handling:** See ERROR CODES REFERENCE section
**Authentication:** See AUTHENTICATION section
**Rate Limiting:** 100 requests per 15 minutes per user

---

**Status:** 🔒 IMMUTABLE - DO NOT MODIFY WITHOUT VERSION BUMP
**Last Updated:** 2025-12-08
**Next Review:** After Phase 3 implementation
**Maintained By:** Technical Lead
