Repository navigation
API Operations
English · 한국어
Default storage is PostgreSQL plus a local blob volume. Commands run from the API checkout with .env.production and compose.production.yaml; replace the Compose filename with compose.api.yaml for API-only deployment. See deployment.
- While signed in, request a fresh code with
POST /api/v1/auth/code/request. Consumed sign-in codes cannot be reused; existing email/IP limits and the sixty-second resend interval apply. - Send
DELETE /api/v1/accountwith JSON{"code":"123456"}, exact Origin, session cookie, andX-CSRF-Token. Multi-account clients also sendX-Miroven-User-ID. Code lifetime/attempt limits match login; an additional per-account hourly deletion-attempt limit applies. - A 202 immediately revokes all sessions. Deletion state and the job are created in one transaction. Uploads recheck sessions before storage, preventing new files after deletion acceptance.
- Use the returned
deletion_tokeninAuthorization: Bearer …to queryGET /api/v1/account/deletion. Cookies/URL parameters cannot authorize it. The token grants no other API access, is not stored plaintext in the DB, and is valid for thirty days. - The worker deletes files, then cascades users, sessions, vault, entries, operation results, change history, and snapshots, also removing email codes/mail jobs. For more than 100 files, remove references first and process batches of 100. Repeating an external file deletion after a pre-commit crash is safe. Empty local directories can remain.
Storage deletion failures retry with exponential delay up to one hour. Ten consecutive failures mark a job failed while access remains blocked. Unfinished jobs are not removed merely because receipts expire; completed receipts are cleaned one day after expiry. Receipt IDs equal user UUIDs so old backups can reapply deletions. Completion retains no user FK, email, or file list, but UUIDs still require restricted access.
After correcting the failure, retry a failed job:
docker compose --env-file .env.production -f compose.production.yaml run --rm --no-deps worker python -m app.worker --retry-deletion DELETION_UUIDDB errors/process termination roll back and release jobs for another worker; jobs are not permanently held in a processing state. Workers separate claims with SKIP LOCKED. SMTP acceptance before commit may duplicate a single-use code email. Request a new code when the old one expires or is exhausted.
GET /api/v1/account/usage returns storage_bytes, storage_limit_bytes, entries, entry_limit, blob_max_bytes, effective plan, subscription_status, current_period_end, and cancel_at_period_end. Limits are the effective per-account values, including active overrides. Reserved/unlinked uploads and old photos retained by history/snapshots count toward bytes. Entry counts include tombstones. Lowering quotas never deletes existing data; user locks serialize reservations/new entries, and idempotent retries do not double-charge. Vault/authentication data and DB size are not blob usage.
Use the image's python -m app.server entry point, which logs only request ID, HTTP method, route template, and status. It excludes raw URL/query, blob UUID, bodies, email, codes, cookies, headers, exception messages, tracebacks, and raw SQLAlchemy/SMTP errors. Worker errors expose class names only. Direct uvicorn execution bypasses this setup. Production nginx/Caddy raw access/error logs are disabled. Development Mailpit retains plaintext emails and must not ship in production.
Monitor container state/restarts, readiness, HTTP 5xx/429, free disk, oldest pending job available_at, failed deletion jobs, last successful backup, and restore drills. Do not expose DB/API ports outside the proxy or print personal information during manual diagnosis.
Current default limits in app/config.py are:
| Effective plan | Blob storage | Journal entries, including tombstones | Per encrypted file |
|---|---|---|---|
| Free | 100 MiB | 10,000 | 4 MiB |
| Pro | 5 GiB | 100,000 | 16 MiB |
Operators can configure Free limits with MIROVEN_STORAGE_QUOTA_BYTES, MIROVEN_MAX_ENTRIES, MIROVEN_BLOB_MAX_BYTES, and Pro limits with the corresponding MIROVEN_PRO_... settings. Pro uses at least the configured Free limits. Per-account storage/entry overrides apply only while entitlement is active; there is no per-account file-size override. Use the returned limits rather than inferring quotas from the plan name. The profile is excluded from entry counts; encrypted document payloads are not blob usage. Lower limits never delete existing content.
app/subscriptions.py evaluates entitlements at request time. active, trialing, and past_due retain entitlement until a supplied period end; canceled retains it only with a future period end. An elapsed period end or explicit expired status removes entitlement, returns Free limits, and stops applying overrides. cancel_at_period_end alone does not end entitlement early. No payment checkout, provider billing integration or automatic charge collection is implemented.
Set MIROVEN_ADMIN_EMAILS to a comma-separated administrator allowlist and restart the API to apply configuration. An empty list disables GET /admin with 404. Open /admin on the API origin and authenticate using the ordinary email-code/session flow; initial signup still obeys the domain/local-part policy. The HTML page itself grants no privilege: each administrator API requires an allowlisted signed-in account, and mutations also require Origin and CSRF checks. Keep the website and preview origins outside credential CORS.
| Operation | Route |
|---|---|
| Metadata/usage/subscription statistics | GET /api/v1/admin/stats |
| Search/filter/paginate accounts | GET /api/v1/admin/users |
| Account metadata and effective limits | GET /api/v1/admin/users/{user_id} |
| Set subscription and quota overrides | PUT /api/v1/admin/users/{user_id}/subscription |
| Retry a failed account deletion | POST /api/v1/admin/deletions/{deletion_id}/retry |
The subscription PUT sets plan, status, optional period boundaries, cancel_at_period_end, storage/entry overrides, provider and note. It replaces those fields: omitted optional values reset to null/defaults rather than preserving old values. Read the existing account detail before editing; use contracts/openapi.json for exact constraints. Deletion retry accepts only a failed task, resetting its attempts and schedule; it does not restore the account. Statistics and user search expose emails and operational metadata to administrators, never decrypted journal/profile content or photos. Restrict access and keep those responses out of shared logs.
The host needs Python 3.12 and Docker Compose. API/workers must belong only to this project. Stop external writers, replicas, and migrations first. The script stops running API/workers, creates pg_dump and a blob tar, then restarts only services previously running. The API is unavailable during backup; the DB container must stay running.
python scripts/backup_restore.py backup backups/2026-10-17 --env-file .env.production -f compose.production.yaml
python scripts/backup_restore.py verify backups/2026-10-17Only new destination folders are allowed. Success requires db.dump, blobs.tar, and a SHA-256 manifest. Hashes detect integrity damage, not malicious tampering with a signed guarantee. Encrypt/restrict the full backup: even with encrypted blobs, the DB includes email, session verifiers, and mail jobs. Separately encrypt/store SECRET_KEY, environment, and image digests. Without the server secret, sessions, deletion receipts, and unsent jobs cannot be restored intact. On Windows, apply ACLs rather than relying on directory mode.
The script rejects S3. For S3, stop all writers and capture the DB dump plus a complete same-point-in-time copy of the dedicated bucket/prefix as one set. Verify each DB storage_key against size/SHA-256. Versioning, replication, and Object Lock may leave older versions behind delete markers; account for them in deletion/retention procedures. Actual provider backup/restore remains unverified; the validated default layout uses local blobs.
Default operating policy: daily backups, at most seven days retention, no extra long-term archive. Online deletion completes with the worker; old backups can retain isolated ciphertext/email for up to seven days. Operators must remove expired backups daily and enforce the same policy for external copies/S3 versions. Configure expiration schedules on the host; this repository does not automatically delete unrelated host files.
Keep a current deletion ledger independently of backups. Export receipt UUIDs after deletion requests and at regular backups; automated export should replace it at least every five minutes. Requests after the last export may be absent after failure: collect/merge their receipts too. If that gap cannot be established, do not expose an old restored backup to users. The ledger must be newer than all retained backups and kept for thirty days.
# UUIDs only, no emails; encrypt and restrict the output separately.
docker compose --env-file .env.production -f compose.production.yaml run --rm --no-deps -T worker python scripts/deletion_ledger.py export > deletion-ledger.jsonRestore only to a new Compose project, empty DB, and empty blob volume. Never overwrite existing data. Verify project name, environment, domain, and volumes; start only the DB first. Use the same SECRET_KEY and compatible images.
docker compose --env-file .env.production -f compose.production.yaml -p miroven-restore up -d --wait db
python scripts/backup_restore.py restore backups/2026-10-17 --env-file .env.production -f compose.production.yaml -p miroven-restore
# Feed the latest ledger on stdin with the API still stopped.
docker compose --env-file .env.production -f compose.production.yaml -p miroven-restore run --rm --no-deps -T worker python scripts/deletion_ledger.py apply < deletion-ledger.json
docker compose --env-file .env.production -f compose.production.yaml -p miroven-restore run --rm --no-deps worker python scripts/check_integrity.pyThe stdin example uses a POSIX shell. In PowerShell, use Get-Content -Raw deletion-ledger.json | docker compose ... run --rm --no-deps -T worker python scripts/deletion_ledger.py apply, substituting the full Compose options above for ....
Ledger application blocks restored accounts, revokes sessions, and recreates deletion jobs. Start the worker and confirm every ledger deletion is complete before checking migrations/readiness, email, login, and decryption on two devices, then connecting external traffic. Failed restoration does not auto-start services. Isolate partial volumes for diagnosis and retry in another empty project.
- Record image digests, schema revision, and environment. Export the latest deletion ledger, create a stopped-service backup, and verify it.
- Stop traffic and API/workers. Set new image tags in the environment; retain the DB.
- Run
docker compose --env-file .env.production -f compose.production.yaml run --rm --no-deps migrateto apply the selected API source's full Alembichead, require exit zero, thenup -d --waitwith the same configuration. Attachment support alone is not the complete current schema; account/limit queries also require0005_subscriptions, and sync database accounting requires0006_sync_budgets. - Check internal readiness/integrity, login, entry/photo decryption, and deletion status before opening traffic. Stop new-version writers on failure.
- Return to old images only if schema compatibility is confirmed. Never automatically perform destructive downgrades. Otherwise restore the old image/backup pair to a new project and reapply the latest deletion ledger. Ordinary writes after the backup can be lost; communicate the recovery point.
docker compose down preserves volumes. Do not attempt production recovery with down --volumes. Attachment v2 entries/history/snapshots block downgrading migration 0004_attachments; reverting requires the pre-deployment backup. See launch checks.
The per-account reserved UUID 00000000-0000-4000-8000-000000000001 is included in current encrypted documents, change history, snapshots, DB backup/restore, and account deletion. Its image is inside the payload, with no separate blob. No separate table/data migration is needed. It is excluded from journal entry limits/counts and blob usage. See profile contract.
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 · 프로필 문서