# Production_Deployment_Security

**Generated**: 2026-02-26T14:14:25.165553
**Model**: gemini-3-flash-preview
**Tokens**: 1190
**Cost**: $0.0002

---

# Production Security and Deployment Guide for SubAIVA

This guide outlines the professional-grade architecture, security protocols, and deployment strategies for **SubAIVA**, a Cloudflare Workers application leveraging Durable Objects (DO) and SQLite.

---

## 1. API Authentication Patterns
For SubAIVA, we implement a multi-tier approach: **JWTs** for users and **API Keys** for machine-to-machine (M2M) traffic.

### JWT Implementation (using `jose`)
Avoid rolling your own crypto. Use the `jose` library for high-performance Web Crypto-based validation.

```typescript
import { jwtVerify, importSPKI } from 'jose';

export async function authenticate(request: Request, env: Env) {
  const authHeader = request.headers.get('Authorization');
  if (!authHeader?.startsWith('Bearer ')) throw new Error('Unauthorized');

  const token = authHeader.split(' ')[1];
  const publicKey = await importSPKI(env.JWT_PUBLIC_KEY, 'RS256');

  try {
    const { payload } = await jwtVerify(token, publicKey, {
      issuer: 'subaiva-auth',
      audience: 'subaiva-api',
    });
    return payload;
  } catch (e) {
    throw new Error('Invalid Token');
  }
}
```

---

## 2. Worker-Level Rate Limiting
While Cloudflare has WAF rate limiting, **Worker-level rate limiting** allows for granular, identity-based throttling using the `ratelimit` binding.

### `wrangler.jsonc` Configuration
```jsonc
{
  "unsafe": {
    "bindings": [
      {
        "name": "RATE_LIMITER",
        "type": "ratelimit",
        "namespace_id": "1001", // Example ID
        "simple": {
          "limit": 100,
          "period": 60
        }
      }
    ]
  }
}
```

### Implementation
```typescript
const { success } = await env.RATE_LIMITER.limit({ key: userIp });
if (!success) return new Response('Too Many Requests', { status: 429 });
```

---

## 3. CORS Configuration
Never use `Access-Control-Allow-Origin: *` in production. Use a strict allow-list.

```typescript
const ALLOWED_ORIGINS = ['https://app.subaiva.com', 'https://admin.subaiva.com'];

export function handleCORS(request: Request) {
  const origin = request.headers.get('Origin');
  if (origin && ALLOWED_ORIGINS.includes(origin)) {
    return {
      'Access-Control-Allow-Origin': origin,
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'Access-Control-Max-Age': '86400',
    };
  }
  return {};
}
```

---

## 4. Environment & Secrets Management
Use `wrangler.jsonc` for environments and `wrangler secret` for sensitive data.

### `wrangler.jsonc`
```jsonc
{
  "name": "subaiva-api",
  "main": "src/index.ts",
  "compatibility_date": "2024-05-01",
  "env": {
    "staging": {
      "vars": { "ENVIRONMENT": "staging", "API_URL": "https://staging-api.subaiva.com" },
      "durable_objects": { "bindings": [{ "name": "DATA_NODE", "class_name": "SubAivaData" }] }
    },
    "production": {
      "vars": { "ENVIRONMENT": "production", "API_URL": "https://api.subaiva.com" },
      "routes": [{ "pattern": "api.subaiva.com/*", "custom_domain": true }]
    }
  }
}
```

**Setting Secrets:**
```bash
wrangler secret put STRIPE_KEY --env production
wrangler secret put JWT_PUBLIC_KEY --env production
```

---

## 5. Monitoring and Alerting
1.  **Logpush:** Export logs to S3, Datadog, or New Relic for long-term retention.
2.  **Sentry Integration:** Use `toucan-js` for error tracking within the Worker.
3.  **Tail Sampling:** Use `wrangler tail` during deployments to monitor live errors.

```typescript
import { Toucan } from 'toucan-js';

export default {
  async fetch(request, env, ctx) {
    const sentry = new Toucan({ dsn: env.SENTRY_DSN, context: ctx, request });
    try {
      // Logic
    } catch (e) {
      sentry.captureException(e);
      return new Response('Internal Error', { status: 500 });
    }
  }
}
```

---

## 6. Durable Objects: SQLite & Data Security
Cloudflare automatically encrypts DO SQLite databases at rest. However, for **SubAIVA**, we implement application-level encryption for PII (Personally Identifiable Information).

### Field-Level Encryption in DO
```typescript
async function encryptData(text: string, key: CryptoKey) {
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const encoded = new TextEncoder().encode(text);
  const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, encoded);
  return { ciphertext, iv };
}
```

---

## 7. Compliance: GDPR & AU Privacy Act
### Data Locality (Jurisdictional Restrictions)
To comply with GDPR or Australian data residency, use **Durable Object Jurisdictions**.

```typescript
// Create a DO ID in the EU jurisdiction
let id = env.DATA_NODE.newUniqueId({ jurisdiction: 'eu' });
```

### Right to Erasure
Implement a "Hard Delete" method in your DO to ensure SQLite vacuuming removes data permanently.
```typescript
async deleteUser(userId: string) {
  this.sql.prepare("DELETE FROM users WHERE id = ?").run(userId);
  // Force storage cleanup
  await this.storage.deleteAlarm(); 
}
```

---

## 8. DDoS Protection
1.  **Cloudflare Shield:** Ensure "Under Attack Mode" is scriptable via API if needed.
2.  **IP Reputation:** Filter requests using `request.cf.asNumber` or `request.cf.botManagement.score`.
3.  **Durable Object Protection:** Never expose DOs directly. Always gate them behind a Worker that validates signatures/auth to prevent "CU (Compute Unit) Exhaustion" attacks.

---

## 9. Deployment & Rollbacks
### Zero-Downtime Pattern
Workers use a "blue-green" deployment model natively. When you run `wrangler deploy`, the new version is propagated globally, and only once healthy does traffic switch.

### Rollback Strategy
If a deployment fails health checks:
```bash
# List recent deployments
wrangler deployments list
# Rollback to a specific ID immediately
wrangler deployments rollback <DEPLOYMENT_ID>
```

### CI/CD Pipeline (GitHub Actions)
```yaml
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Deploy to Production
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CF_API_TOKEN }}
          command: deploy --env production
```

---

## 10. Error Handling and Graceful Degradation
Always implement a "Circuit Breaker" for external API calls (e.g., Stripe, OpenAI).

```typescript
async function fetchWithTimeout(resource: string, options = {}, timeout = 5000) {
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);
  try {
    const response = await fetch(resource, { ...options, signal: controller.signal });
    return response;
  } finally {
    clearTimeout(id);
  }
}
```

### Graceful Degradation Strategy
If the DO SQLite is overloaded, the Worker should fallback to a read-only state using **Cloudflare KV** for cached data to maintain "Read-Only" availability for SubAIVA users.

---

## Summary Checklist for SubAIVA Production
- [ ] `wrangler.jsonc` configured with `staging` and `production` environments.
- [ ] All secrets moved out of code into `wrangler secret`.
- [ ] JWT validation implemented with RS256.
- [ ] CORS origins restricted to specific subdomains.
- [ ] Durable Object Jurisdictions set for EU/AU users.
- [ ] Sentry/Logpush configured for observability.
- [ ] Rate limiting active on sensitive `/api/*` endpoints.