# API Keys Scope

### 1. **Break Down the Feature Lifecycle**

#### 1.1 Define the Feature Goals

* **Purpose**: Securely generate and manage API keys used by organizations to authenticate webhook requests and access platform resources programmatically.
* **Desired Outcomes**:
  * Allow org admins to create and revoke keys
  * Only hashed API keys are stored for security
  * Allow platform to validate keys in `Authorization: Bearer` headers
* **Core User Interactions**:
  * Platform Admin:
    * View and revoke any API key
  * Organization Admin:
    * Create and revoke their own API keys
    * Label keys for tracking (e.g., “LRS Integration”)

***

#### 1.2 Establish Key Milestones

* **Data Creation**:
  * API key is generated (returned once), hashed, and stored
  * Optional expiration and labeling set at creation
* **Data Storage**:
  * Store under `/organizations/{orgId}/apiKeys/{keyId}` with `keyHash`, `revoked`, `expiresAt`, etc.
* **Data Retrieval**:
  * Only metadata can be retrieved; raw key is not shown after creation
* **Validation**:
  * Middleware decodes incoming bearer key, hashes, and compares with stored hashes
* **Revocation**:
  * Set `revoked: true` to deactivate a key
* **Automation (future)**:
  * Auto-expire keys
  * Notify org admin before expiration
  * Rate limiting and IP restrictions

***

#### 1.3 Prioritize MVP

* ✅ Key creation with label and expiration
* ✅ Store key hash securely
* ✅ Middleware-based validation for xAPI endpoints
* ✅ Revocation support
* 🔲 Usage logging and rotation reminders (future)
* 🔲 Scoped keys and rate limiting (future)

**Knowledge Gaps**:

* Determine if keys will need scopes (talk to integration partners)
* Decide on notification process for expiring or misused keys

***

### 2. **Identify Relevant Entities**

#### 2.1 List Entities

* Organization
* API Key

#### 2.2 Define Relationships

| Entity       | Relationships                                    |
| ------------ | ------------------------------------------------ |
| Organization | Has many API Keys                                |
| API Key      | Belongs to one Organization, used for validation |

***

### 3. **Plan API Routes**

#### 3.1 Define CRUD Operations

| Method | Route                                   | Purpose                           |
| ------ | --------------------------------------- | --------------------------------- |
| POST   | `/organizations/:orgId/api-keys`        | Create API key                    |
| GET    | `/organizations/:orgId/api-keys`        | List API key metadata             |
| GET    | `/organizations/:orgId/api-keys/:keyId` | View metadata for single key      |
| PATCH  | `/organizations/:orgId/api-keys/:keyId` | Update label, revoke key          |
| DELETE | `/organizations/:orgId/api-keys/:keyId` | Permanently delete key (optional) |

#### 3.2 Define Action-Specific Routes

None yet, but potential future routes:

* `/api-keys/:keyId/rotate`
* `/api-keys/:keyId/usage`

#### 3.3 Validate Input/Output

* Only allow org admins or platform admins to manage keys
* Only return key value at creation time
* Use strong hashing algorithm (e.g., bcrypt or SHA-256 + salt)

***

### 4. **Feature Breakdown with Example Usage**

#### Org Admin: Creating an API Key

1. Navigates to “Integration Settings”
2. Fills out a form with:
   * Name = “Webhook Key”
   * Expiration = “+90 days”
3. Hits submit:
   * Backend generates raw key, stores hash
   * Returns plaintext API key once

#### Example Response:

```json
{
  "success": true,
  "message": "API key created successfully.",
  "data": {
    "apiKey": "org_09d98ac0f5e4123a9b62..."
  }
}
```

***

### 5. **Use Flowcharts for Clarity**

#### Create API Key Flow

```plaintext
[User Clicks 'Generate API Key']
      ↓
[API Key Created on Server]
      ↓
[Raw Key Sent to User (Once Only)]
      ↓
[Hash Stored in DB with Metadata]
      ↓
[Subsequent Requests Use Bearer Key]
```
