# COPPA Implementation Design

## Overview

Implementation of age verification and parental consent functionality to comply
with COPPA (Children's Online Privacy Protection Act) requirements, including
the 2025 amendments effective April 22, 2026.

## COPPA Requirements Summary

Based on FTC guidelines:

1. **Age Verification**: Users under 13 require verifiable parental consent
2. **Parental Consent Methods**: Email Plus (for internal use), Credit Card,
   Government ID, Knowledge-Based Auth
3. **Separate Consent**: Third-party disclosures require separate consent
4. **Data Security**: Written information security program required
5. **Data Retention**: No indefinite retention of children's personal
   information

## User Age Classification

| Category | Age Range | Requirements                                        |
| -------- | --------- | --------------------------------------------------- |
| MINOR    | Under 13  | Parental consent required for account creation      |
| TEEN     | 13-17     | Standard registration with age-appropriate features |
| ADULT    | 18+       | Full access                                         |

## Implementation Components

### 1. Age Verification Service (`services/auth/src/age-verification.ts`)

**Functions:**

- `calculateAge(dateOfBirth: Date): number` - Calculate age from DOB
- `classifyUser(dateOfBirth: Date): AgeClassification` - Return MINOR/TEEN/ADULT
- `validateDateOfBirth(dob: unknown): DateOfBirthValidation` - Validate DOB
  input
- `isMinor(dateOfBirth: Date): boolean` - Check if under 13
- `isMinorAge(age: number): boolean` - Check if age < 13
- `requiresParentalConsent(dateOfBirth: Date): boolean` - Check COPPA
  applicability
- `getAgeRestrictions(classification: AgeClassification): AgeRestrictions` - Get
  feature restrictions

**Types:**

```typescript
enum AgeClassification {
  MINOR = 'minor', // Under 13
  TEEN = 'teen', // 13-17
  ADULT = 'adult', // 18+
}

interface DateOfBirthValidation {
  valid: boolean;
  dateOfBirth?: Date;
  error?: string;
  age?: number;
  classification?: AgeClassification;
}

interface AgeRestrictions {
  requiresParentalConsent: boolean;
  canAccessSocialFeatures: boolean;
  canShareContent: boolean;
  canReceiveMarketing: boolean;
  dataRetentionDays: number;
}
```

### 2. Parental Consent Service (`services/auth/src/parental-consent.ts`)

**Consent Flow (Email Plus Method):**

1. Child attempts registration with DOB indicating under 13
2. System blocks direct registration, prompts for parent email
3. Parent receives invitation email with consent link
4. Parent clicks link, verifies identity (email confirmation + knowledge
   questions optional)
5. Parent grants/denies consent
6. If granted, child account is created with parent link
7. Confirmation sent to both parent and child

**Functions:**

- `initiateParentalConsent(childData, parentEmail): ConsentRequest` - Start
  consent flow
- `generateConsentToken(requestId): string` - Create secure token for parent
- `verifyConsentToken(token): ConsentRequest | null` - Validate token
- `grantConsent(requestId, parentData): ConsentGrant` - Parent approves
- `denyConsent(requestId, reason?): ConsentDenial` - Parent denies
- `getConsentStatus(requestId): ConsentStatus` - Check status
- `revokeConsent(childUserId, parentId): void` - Parent revokes consent
- `validateParentEmail(email): boolean` - Ensure parent != child email

**Types:**

```typescript
interface ParentalConsentRequest {
  id: string;
  childEmail: string;
  childName?: string;
  childDateOfBirth: Date;
  parentEmail: string;
  status: ConsentStatus;
  token: string;
  tokenExpiresAt: Date;
  createdAt: Date;
  updatedAt: Date;
  ipAddress: string;
  userAgent: string;
}

enum ConsentStatus {
  PENDING = 'pending',
  GRANTED = 'granted',
  DENIED = 'denied',
  EXPIRED = 'expired',
  REVOKED = 'revoked',
}

interface ConsentGrant {
  requestId: string;
  parentUserId: string;
  childUserId: string;
  grantedAt: Date;
  expiresAt?: Date; // Optional expiration for re-verification
  thirdPartyDisclosure: boolean; // Separate consent for third parties
}

interface ParentChildRelationship {
  id: string;
  parentUserId: string;
  childUserId: string;
  consentGrantId: string;
  status: 'active' | 'revoked';
  createdAt: Date;
  revokedAt?: Date;
}
```

### 3. Database Schema Updates

**Existing:** `user_profiles.date_of_birth` column already exists

**New Tables:**

```sql
-- Parental consent requests (pending invitations)
CREATE TABLE parental_consent_requests (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  child_email VARCHAR(255) NOT NULL,
  child_name VARCHAR(255),
  child_date_of_birth DATE NOT NULL,
  parent_email VARCHAR(255) NOT NULL,
  status VARCHAR(20) NOT NULL DEFAULT 'pending',
  token VARCHAR(512) NOT NULL,
  token_expires_at TIMESTAMP NOT NULL,
  ip_address VARCHAR(45),
  user_agent TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT chk_status CHECK (status IN ('pending', 'granted', 'denied', 'expired', 'revoked'))
);

-- Parent-child relationships
CREATE TABLE parent_child_relationships (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  parent_user_id UUID NOT NULL REFERENCES users(id),
  child_user_id UUID NOT NULL REFERENCES users(id),
  consent_request_id UUID REFERENCES parental_consent_requests(id),
  third_party_disclosure_consent BOOLEAN DEFAULT FALSE,
  status VARCHAR(20) NOT NULL DEFAULT 'active',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  revoked_at TIMESTAMP,
  CONSTRAINT chk_relationship_status CHECK (status IN ('active', 'revoked')),
  UNIQUE(parent_user_id, child_user_id)
);

-- Add columns to users table
ALTER TABLE users ADD COLUMN is_minor BOOLEAN DEFAULT FALSE;
ALTER TABLE users ADD COLUMN requires_parental_consent BOOLEAN DEFAULT FALSE;
ALTER TABLE users ADD COLUMN parental_consent_status VARCHAR(20);
```

### 4. Registration Flow Updates

**Modified Registration (`services/auth/src/registration-routes.ts`):**

```typescript
// Add to RegisterBody interface
interface RegisterBody {
  email: string;
  password: string;
  dateOfBirth?: string; // ISO date string
  parentEmail?: string; // Required if minor
}

// Registration flow:
// 1. Validate email and password (existing)
// 2. If dateOfBirth provided:
//    a. Validate and parse DOB
//    b. Calculate age classification
//    c. If MINOR:
//       - Require parentEmail
//       - Do NOT create account yet
//       - Create parental consent request
//       - Send email to parent
//       - Return pending status
//    d. If TEEN or ADULT:
//       - Continue with normal registration
// 3. If no dateOfBirth:
//    - For mixed-audience sites, assume adult
//    - For child-directed sites, require DOB
```

### 5. API Endpoints

**New Routes (`services/auth/src/parental-consent-routes.ts`):**

| Method | Path                                 | Description                                     |
| ------ | ------------------------------------ | ----------------------------------------------- |
| POST   | `/v1/auth/register-minor`            | Initiate minor registration with parent consent |
| GET    | `/v1/auth/consent/:token`            | Get consent request details (for parent)        |
| POST   | `/v1/auth/consent/:token/grant`      | Parent grants consent                           |
| POST   | `/v1/auth/consent/:token/deny`       | Parent denies consent                           |
| GET    | `/v1/auth/consent/status/:requestId` | Check consent request status                    |
| POST   | `/v1/auth/consent/:childId/revoke`   | Parent revokes consent                          |
| GET    | `/v1/users/:userId/children`         | List children for parent user                   |
| GET    | `/v1/users/:userId/parent`           | Get parent for child user                       |

### 6. Email Templates

**Parent Consent Request Email:**

- Subject: "Parental Consent Required - [App Name]"
- Body: Child's name, what they want to do, consent link, expiration time
- Clear explanation of data practices
- Link to privacy policy

**Consent Granted Confirmation:**

- To parent: Account created, how to manage child's account
- To child: Account now active

**Consent Denied Notification:**

- To child: Registration cannot proceed, alternative options

### 7. Security Considerations

1. **Token Security**: Use cryptographically secure random tokens, 48-hour
   expiration
2. **Rate Limiting**: Limit consent requests per IP/email to prevent abuse
3. **Parent Verification**: Parent email must be different from child email
4. **Audit Trail**: Log all consent-related actions in consent ledger
5. **Data Minimization**: Collect only necessary data from children
6. **Retention Limits**: Auto-delete consent requests after 30 days if not acted
   upon

## Implementation Order

1. ~~Research existing code~~ (Done)
2. ~~Research COPPA requirements~~ (Done)
3. ~~Design implementation~~ (This document)
4. Create age-verification.ts with tests (TDD)
5. Create parental-consent.ts with tests (TDD)
6. Add database migrations
7. Update registration routes
8. Create consent API routes
9. Add email templates
10. Update documentation

## Sources

- [FTC COPPA Rule](https://www.ftc.gov/legal-library/browse/rules/childrens-online-privacy-protection-rule-coppa)
- [FTC COPPA FAQ](https://www.ftc.gov/business-guidance/resources/complying-coppa-frequently-asked-questions)
- [FTC Verifiable Parental Consent Guide](https://www.ftc.gov/business-guidance/privacy-security/verifiable-parental-consent-childrens-online-privacy-rule)
- [2025 COPPA Amendments Analysis](https://www.whitecase.com/insight-alert/unpacking-ftcs-coppa-amendments-what-you-need-know)
