Repository navigation
API Sync Protocol
English · 한국어
Miroven-API synchronization contract. Exact request/response schemas are defined by contracts/openapi.json in the API checkout. All routes below have prefix /api/v1. Ownership comes from session cookies; mutations require Origin and X-CSRF-Token, not a body user ID.
Deploy the current API with its full Alembic head, including 0005_subscriptions for effective quota queries and 0006_sync_budgets for sync database accounting. 0004_attachments describes the multi-photo minimum, not the full current schema.
The server never decrypts journal entries, photos, or profiles. The client uses AES-256-GCM with per-document keys, sync crypto v1, and these AAD strings:
content AAD: private-journal:sync:{entry|blob}:{id}:r{revision}:v1
key AAD: private-journal:sync:{entry|blob}:data-key:{id}:v1
Entry fields ciphertext, content_nonce, wrapped_data_key, and key_nonce are canonical base64; crypto_version=1. Nonces are twelve bytes, wrapped keys 48 bytes, and entry ciphertext 16–65,536 bytes including GCM tag. JSON push bodies are at most 128 KiB.
Photo bytes can serialize the existing {version, ciphertext, contentNonce, wrappedDataKey, keyNonce} envelope. The server validates size, SHA-256, ownership, and references without interpreting that envelope; the client must encrypt file contents.
POST /sync/push takes one operation:
{
"operation_id": "<UUID>",
"entry_id": "<UUID>",
"base_revision": 0,
"revision": 1,
"change_type": "upsert",
"payload": {
"ciphertext": "<base64>",
"content_nonce": "<base64>",
"wrapped_data_key": "<base64>",
"key_nonce": "<base64>",
"crypto_version": 1
},
"blob_id": null
}- Require
revision = base_revision + 1, initially base zero. Upload photos first, then link their returned IDs; entry ID/revision must match the operation. - New clients use
attachment_version: 2,blob_ids: [UUID, ...](zero to four unique IDs), andblob_id: null. Link all files in one push, preserving order in the change document. Validate every file's user/entry/revision and ready state; one failure commits none of the links. Legacy singleblob_idrequests and idempotent retries remain supported. - Once an entry/tombstone uses v2, attachment v1 writes return 409
client_update_required. New clients resaving single-photo legacy data still use v2 links. -
change_type=deleteaccepts no payload or blob IDs and creates a tombstone. Revisions persist after deletion so stale writes cannot resurrect entries. - Success: 200
{outcome: "accepted", revision, cursor}. Same operation ID and same parsed request returns the original response; omitted defaults and explicit null normalize equivalently. - Reusing an operation ID with different data returns 409
operation_mismatch; wrong base revision returns 409revision_conflict. Failed operations are not stored as successes. - Under the user row lock, compare revision, link files, update current state/history, persist the idempotent result, and advance cursor in one transaction. Commit failure rolls back everything.
entry_id=00000000-0000-4000-8000-000000000001 is reserved for one profile per account, using /sync/push, /sync/changes, and /sync/snapshot. Session ownership separates identical UUIDs across users. Do not use it for ordinary journal entries.
Profile upserts require encrypted payloads with the same 16–65,536-byte ciphertext/128-KiB request limits. Decrypted text contains { name, bio, handle, avatar }: name 1–30 characters, Bio 0–160, display ID 3–20 letters/digits/underscores, avatar a PNG data URL reduced to at most 100×100px or null. The display ID is unrelated to authentication and has no uniqueness check. Clients validate before encryption and after decryption. Servers cannot inspect fields/image dimensions; they see profile ID/revision/size/time.
The image stays inside the payload. Linking blob_id or nonempty blob_ids returns 422 invalid_request. Uploading /blobs for this UUID passes authentication/CSRF/vault checks then returns 422 profile_attachment_forbidden, without reserving/storing a file. Profiles cannot carry journal photos, quotes, or pinning.
Revision, idempotency, concurrent writes, cursor expiry, and snapshot recovery follow ordinary entries. Resolve conflicts by choosing local/remote profile without creating journal copies. Delete uses a payload/file-free tombstone; clients show defaults but retain server revision and use the latest base for subsequent writes.
Exclude the profile and its tombstone from max_entries and /account/usage.entries; profile operations remain possible at the journal quota. Keep its history/snapshots. /account/usage.storage_bytes sums blob bytes including pending reservations, not ordinary/profile payloads. Do not duplicate the profile in blob storage. Include the initial local profile in Outbox when preparing recovery, and include its current state/history/snapshots in account deletion and DB backup/restore. No separate profile data migration is added. See client profile.
GET /sync/changes?cursor=...&limit=50 returns {items, next_cursor, has_more}; limit is 1–100. Each item includes its fields and change cursor. Cursors are HMAC-signed opaque strings containing user, server generation, and position. Do not parse their JSON or convert to numbers.
User counters advance under the same user lock as writes, avoiding global-sequence commit-order gaps. Pull uses that lock too, so it cannot skip an in-flight commit.
- Omitted initial cursor means position zero; cleaned history returns 410
cursor_expired. - Tampered/cross-account/wrong-kind/out-of-range cursors return 400
invalid_cursor; changed server generation returns 410cursor_expired. - Empty pages still return valid
next_cursor; never jump to an unread head. - A push response cursor identifies that operation, not a completed global pull position. Do not save it directly as local pull cursor, which could skip another device's earlier changes.
- History defaults to ninety days; successful operation idempotency records remain for the account lifetime independently of history cleanup.
Start with GET /sync/snapshot?limit=50, then use returned next_cursor. Responses contain {items, next_cursor, has_more, resume_cursor}. Under user lock, copy current entries/tombstones to DB snapshot tables and fix the baseline head; later edits/deletes do not change pages. All pages share resume_cursor.
Default expiry: one hour; maximum five concurrent snapshots per account. Excess returns 429 snapshot_limit; expiry returns 410 snapshot_expired. Keep completed snapshots until expiry so a lost final response can be retried. Snapshots retain current entries/deletions even after change history expires.
Client recovery must collect all pages in temporary storage while preserving Outbox/conflicts, reconcile with current local state only after completion, retain unsent local items absent from the server, atomically commit the result and resume_cursor, then pull subsequent changes. Handle stale Outbox through revision conflict resolution; never discard/ACK everything because history expired. Do not reuse old numeric cursors; separate local sync scope by API URL/account.
Deploy server migration 0004_attachments before the client. entry_blobs, change_blobs, and snapshot_blobs use composite foreign keys for ownership/references. Retain photos referenced by history or active snapshots. Per-file maximum remains 4 MiB and account quota sums all files. v2 entries/history/snapshots block migration downgrade; reverting requires a pre-deployment backup.
POST /blobs?blob_id=<UUID>&entry_id=<UUID>&revision=1 streams ciphertext with Content-Type: application/octet-stream. Response: {blob_id, entry_id, revision, size, sha256}.
- Authenticate, then release the DB connection before receiving the body. Spool beyond 64 KiB to a temporary file. Default transfer deadline is thirty seconds. The per-file limit is the effective account
blob_max_bytes(Free default 4 MiB, Pro default 16 MiB); see subscription limits. - Revalidate the session after upload; logout/account deletion during transfer prevents storage.
- Same blob ID, bytes, entry, and revision returns the same response. Different data/metadata returns 409
blob_mismatch. Generate storage keys server-side, never from user paths. - Default Free account storage is 100 MiB including reservations/unlinked files; Pro limits and active account overrides can differ. Use the effective limits from
/account/usage; excess returns 409storage_limit. - State:
pending → ready → linked. Commit the pending reservation before external writes, preserving traceability/retry after failure. A successful entry push links it. -
GET /blobs/{blob_id}serves owner-authorized linked files only. Pending/ready/cross-account files return 404; size/SHA-256 mismatch or storage errors return 503.
Local storage uses temporary write, fsync, and exclusive hard link on a persistent volume. S3 writes to an existing private bucket using If-None-Match: *, never overwriting. Retries verify checksums; both backends enforce download limits.
The mail worker runs hourly cleanup in bounded batches, skipping busy user locks until next time. Remove expired snapshots/copies; prune only the expired contiguous history prefix and update floor in the same transaction without skipping fresh changes. After a default 24-hour grace period, delete only files unreferenced by current entries, history, or valid snapshots. Failed external deletion retains DB metadata for retry; reservation keys also track abandoned local temporary writes.
The default Free journal quota is 10,000 per account including tombstones but excluding profile. Pro and active account overrides use their effective entry_limit. Long-term compaction of tombstones/idempotent results is not implemented. Back up DB and blobs together; restoring one alone can mismatch photos and entries. See operations.
For S3 set MIROVEN_STORAGE_BACKEND=s3, MIROVEN_S3_BUCKET, MIROVEN_S3_REGION, and optionally MIROVEN_S3_ENDPOINT_URL for compatible providers. Supply access/secret together or use the SDK IAM credential chain. The API does not create buckets or configure public policies. Grant GetObject/PutObject/DeleteObject for the server prefix; keep the bucket private. Verify If-None-Match and SDK request compatibility with the real provider. Changing backend/bucket/prefix does not migrate existing files.
Shared storage/API tests use local storage and Moto, not actual AWS/other-provider permissions/TLS/operations. Docker smoke checks encrypted entry/photo round trips with existing AAD between two HTTP clients and local volumes. See validation boundaries for browser/physical-device scope.
Migration 0006_sync_budgets is part of the current required Alembic head. It backfills the UTF-8 JSON byte count of existing current documents and change history without deleting content or idempotency receipts. Stop API/worker writers and take a paired backup before upgrade. The backfill scans existing documents and locks sync_states; allow a maintenance window on large databases. Downgrade removes only the new accounting columns, retaining journal data, but the old server no longer enforces these protections. Re-upgrade recalculates usage and starts a new hourly window.
These positive account-wide operational settings apply to every plan, independently of blob quotas and subscription overrides:
| Setting | Default | Meaning |
|---|---|---|
MIROVEN_SYNC_STORAGE_QUOTA_BYTES |
134217728 (128 MiB) | Logical JSON bytes in current entry/profile/tombstone documents plus retained change history |
MIROVEN_SYNC_OPERATION_LIMIT |
1000000 | Lifetime accepted operations/receipts, using the monotonically increasing sync head |
MIROVEN_SYNC_HOURLY_OPERATIONS |
20000 | Successful new operations per UTC clock hour |
MIROVEN_SYNC_HOURLY_BYTES |
67108864 (64 MiB) | Successful new documents' logical JSON ingress bytes per UTC clock hour |
Document bytes use UTF-8 JSON with the same separators as PostgreSQL JSONB::text for the validated sync schema; they include base64 ciphertext, envelope fields, IDs, revisions, metadata, and attachment IDs. A write replaces the current document and adds a full history copy, so charge 2 * new_document_bytes - previous_current_document_bytes. This is not compressed database/index/WAL/disk usage. /account/usage.storage_bytes remains blob-only. No request, response, encryption, AAD, revision, or cursor encoding changes are introduced.
The authenticated user lock serializes reservations, new documents/history/receipts, and maintenance. Commit/validation/storage-reference failures roll back the reservation. Exact operation-ID retries return their original receipt before checking any budgets and do not consume another slot; mismatched retries still return operation_mismatch. Receipt records remain for the account lifetime: they are not silently evicted. On reaching the lifetime cap, new writes (including deletion operations) require an operator to review/raise configuration; history cleanup does not reset the sync head. Account deletion remains available.
New growth exceeding the byte budget returns 409 sync_storage_limit; the receipt cap returns 409 sync_operation_limit; the hourly count or byte cap returns 429 sync_rate_limited. The existing client retains the pending operation for these errors, rather than treating them as revision conflicts or acknowledging them. Read access and snapshot recovery continue at a write limit. Hourly limits reset at UTC hour boundaries; a write larger than the entire hourly byte budget needs a configuration change. Defaults allow large offline queues to drain over multiple hours.
Retention cleanup releases only pruned history bytes under the same lock and preserves receipts/cursors/blob references. Lowered limits or migrated over-limit data are not deleted; net byte-reducing writes may proceed while over the document quota, subject to the receipt/hourly caps. Current-document bytes cannot be reclaimed by aging history. Adjust capacity after reviewing real usage and keep originals/backups.
Snapshot copies are excluded from the primary write budget so recovery remains usable. Each frozen copy retains at most the current-document bytes present when it is created, with at most max_snapshots copies per account (default five, TTL one hour). Lowering the budget or shrinking documents does not shrink existing snapshots before expiry, and grandfathered over-limit data can produce larger snapshots. Retention and expired-snapshot cleanup must keep running. Receipt metadata is bounded by the lifetime operation cap and fixed-size validated result fields. Actual total disk use and aggregate usage across accounts still need operational monitoring/capacity management.
- Client development · 클라이언트 개발
- Self-hosting · 자체 호스팅
- PWA, offline use, and updates · PWA·오프라인·업데이트
- Client performance · 클라이언트 성능
- Architecture · 아키텍처
- Cryptographic format · 암호화 형식
- Image processing · 사진 처리
- Security model · 보안 경계
- Product principles · 제품 원칙
- Dependency licenses · 의존성 라이선스
- Account and sync · 계정과 동기화
- Backup and recovery · 백업과 복구
- Entry quotes · 기록 인용
- Profile document · 프로필 문서