# ADR-028: Micropub Implementation Strategy

## Status

Proposed

## Context

StarPunk needs a Micropub endpoint to achieve V1 release. Micropub is a W3C standard that allows external clients to create, update, and delete posts on a website. This is a critical IndieWeb building block that enables users to post from various apps and services.

### Current State
- StarPunk has working IndieAuth authentication (authorization endpoint with PKCE)
- Note CRUD operations exist in `starpunk/notes.py`
- File-based storage with SQLite metadata is implemented
- **Missing**: Micropub endpoint for external posting
- **Missing**: Token endpoint for API authentication

### Requirements Analysis

Based on the W3C Micropub specification review, we identified:

**Minimum Required Features:**
- Bearer token authentication (header or form parameter)
- Create posts via form-encoded requests
- HTTP 201 Created response with Location header
- Proper error responses with JSON error bodies

**Recommended Features:**
- JSON request support for complex operations
- Update and delete operations
- Query endpoints (config, source, syndicate-to)

**Optional Features (Not for V1):**
- Media endpoint for file uploads
- Syndication targets
- Complex post types beyond notes

## Decision

We will implement a **minimal but complete Micropub server** for V1, focusing on core functionality that enables real-world usage while deferring advanced features.

### Implementation Approach

1. **Token Management System**
   - New token endpoint (`/auth/token`) for IndieAuth code exchange
   - Secure token storage using SHA256 hashing
   - 90-day token expiry with scope validation
   - Database schema updates for token management

2. **Micropub Endpoint Architecture**
   - Single endpoint (`/micropub`) handling all operations
   - Support both form-encoded and JSON content types
   - Delegate to existing `notes.py` CRUD functions
   - Proper error handling and status codes

3. **V1 Feature Scope** (Simplified per user decision)
   - ✅ Create posts (form-encoded and JSON)
   - ✅ Query endpoints (config, source)
   - ✅ Bearer token authentication
   - ✅ Scope-based authorization (create only)
   - ❌ Media endpoint (post-V1)
   - ❌ Update operations (post-V1)
   - ❌ Delete operations (post-V1)
   - ❌ Syndication (post-V1)

### Technology Choices

| Component | Technology | Rationale |
|-----------|------------|-----------|
| Token Storage | SQLite with SHA256 hashing | Secure, consistent with existing database |
| Token Format | Random URL-safe strings | Simple, secure, no JWT complexity |
| Request Parsing | Flask built-in + custom normalization | Handles both form and JSON naturally |
| Response Format | JSON for errors, headers for success | Follows Micropub spec exactly |

## Rationale

### Why Minimal V1 Scope?

1. **Get to V1 Faster**: Core create functionality enables 90% of use cases
2. **Real Usage Feedback**: Deploy and learn from actual usage patterns
3. **Reduced Complexity**: Fewer edge cases and error conditions
4. **Clear Foundation**: Establish patterns before adding complexity

### Why Not JWT Tokens?

1. **Unnecessary Complexity**: JWT adds libraries and complexity
2. **No Distributed Validation**: Single-server system doesn't need it
3. **Simpler Revocation**: Database tokens are easily revoked
4. **Consistent with IndieAuth**: Random tokens match the pattern

### Why Reuse Existing CRUD?

1. **Proven Code**: `notes.py` already handles file/database sync
2. **Consistency**: Same validation and error handling
3. **Maintainability**: Single source of truth for note operations
4. **Atomic Operations**: Existing transaction handling

### Security Considerations

1. **Token Hashing**: Never store plaintext tokens
2. **Scope Enforcement**: Each operation checks required scopes
3. **HTTPS Required**: Enforce in production configuration
4. **Token Expiry**: 90-day lifetime limits exposure
5. **Single-Use Auth Codes**: Prevent replay attacks

## Consequences

### Positive

✅ **Enables V1 Release**: Removes the last blocker for V1
✅ **Real IndieWeb Participation**: Can post from standard clients
✅ **Clean Architecture**: Clear separation of concerns
✅ **Extensible Design**: Easy to add features later
✅ **Security First**: Proper token handling from day one

### Negative

⚠️ **Limited Initial Features**: No media uploads in V1
⚠️ **Database Migration Required**: Token schema changes needed
⚠️ **Client Testing Needed**: Must verify with real Micropub clients
⚠️ **Additional Complexity**: New endpoints and token management

### Neutral

- **8-10 Day Implementation**: Reasonable timeline for critical feature
- **New Dependencies**: None required (using existing libraries)
- **Documentation Burden**: Must document API for users

## Implementation Plan

### Phase 1: Token Infrastructure (Days 1-3)
- Token database schema and migration
- Token generation and storage functions
- Token endpoint for code exchange
- Scope validation helpers

### Phase 2: Micropub Core (Days 4-7)
- Main endpoint handler
- Property normalization for form/JSON
- Create post functionality
- Error response formatting

### Phase 3: Queries & Polish (Days 6-8)
- Config and source query endpoints
- Authorization endpoint with admin session check
- Discovery headers and links
- Client testing and documentation

**Note**: Timeline reduced from 8-10 days to 6-8 days due to V1 scope simplification (no update/delete)

## Alternatives Considered

### Alternative 1: Full Micropub Implementation
**Rejected**: Too complex for V1, would delay release by weeks

### Alternative 2: Custom API Instead of Micropub
**Rejected**: Breaks IndieWeb compatibility, requires custom clients

### Alternative 3: JWT-Based Tokens
**Rejected**: Unnecessary complexity for single-server system

### Alternative 4: Separate Media Endpoint First
**Rejected**: Not required for text posts, can add later

## Compliance

### Standards Compliance
- ✅ W3C Micropub specification
- ✅ IndieAuth specification for tokens
- ✅ OAuth 2.0 Bearer Token usage

### Project Principles
- ✅ Minimal code (reuses existing CRUD)
- ✅ Standards-first (follows W3C spec)
- ✅ No lock-in (standard protocols)
- ✅ Progressive enhancement (can add features)

## Risks and Mitigations

| Risk | Impact | Probability | Mitigation |
|------|--------|-------------|------------|
| Token security breach | High | Low | SHA256 hashing, HTTPS required |
| Client incompatibility | Medium | Medium | Test with 3+ clients before release |
| Scope creep | Medium | High | Strict V1 feature list |
| Performance issues | Low | Low | Simple operations, indexed database |

## Success Metrics

1. **Functional Success**
   - Posts can be created from Indigenous app
   - Posts can be created from Quill
   - Token endpoint works with IndieAuth flow

2. **Performance Targets**
   - Post creation < 500ms
   - Token validation < 50ms
   - Query responses < 200ms

3. **Security Requirements**
   - All tokens hashed in database
   - Expired tokens rejected
   - Invalid scopes return 403

## References

- [W3C Micropub Specification](https://www.w3.org/TR/micropub/)
- [IndieAuth Specification](https://www.w3.org/TR/indieauth/)
- [OAuth 2.0 Bearer Token Usage](https://tools.ietf.org/html/rfc6750)
- [Micropub Rocks Validator](https://micropub.rocks/)

## Related ADRs

- ADR-004: File-based Note Storage (storage layer)
- ADR-019: IndieAuth Implementation (authentication foundation)
- ADR-025: PKCE Authentication (security pattern)

## Version Impact

**Version Change**: 0.9.5 → 1.0.0 (V1 Release!)

This change represents the final feature for V1 release, warranting the major version increment to 1.0.0.

---

**Date**: 2024-11-24
**Author**: StarPunk Architecture Team
**Status**: Proposed