Skip to content
SEUNGWOO CHOI edited this page Oct 21, 2026 · 3 revisions

API authentication and security

English · 한국어

Contract for Miroven-API 0.1.0. An independent security audit remains outstanding; see validation boundaries.

Trust boundary and vault envelope

The API authenticates email accounts and controls owner-scoped ciphertext access. The client encrypts/decrypts content and unlocks the vault. An email account or sign-in code alone cannot recover an encrypted vault.

Profile name, Bio, display ID, and image are encrypted in the same vault. The server observes the reserved ID, revision, ciphertext size, and change times, but cannot validate/decrypt the contents. The client validates fields and the 100×100px image on write and receive. The server enforces ciphertext limits, no profile file attachments, and account ownership. A display ID is not an authentication identity or globally unique username.

The recovery envelope contains a 48-byte AES-GCM-wrapped vault key, 12-byte nonce, and 16-byte recovery salt, encoded as canonical base64. Only recovery_format=base32-hkdf-sha256-v1, crypto_version=1, and key_version=1 are accepted. The API validates format/lengths, not key contents.

Email codes

  1. Submit email to /api/v1/auth/code/request. Validated addresses are normalized to lowercase; case-sensitive local parts are not separate identities.
  2. Store an HMAC-SHA-256 verifier in the DB and encrypted email/code in the mail-job payload. Do not log plaintext codes.
  3. The worker sends through SMTP and removes the payload. Default code/job lifetime is ten minutes.
  4. Verification consumes the code and creates a user/session. Failed attempts are committed separately so retries cannot bypass attempt limits.

Defaults: five verification attempts per code, five requests per email/hour, thirty requests per IP/hour, sixty seconds between resends, and 150 verification requests per IP/hour. PostgreSQL atomic upsert shares counters across instances; per-email transaction advisory locks serialize resends/verification.

Requests still return the same 202 when limited or awaiting resend. Responses do not reveal delivery or account existence. Verification failures use the same 401. Limits use fixed UTC windows and can permit bursts across window boundaries.

Signup domains and email languages

app/email/domains.json in Miroven-API defines 27 default signup domains: DEFAULT sends English (en), KR Korean (ko), and JP Japanese (ja). Match the whole validated, lowercased domain; similar suffixes and subdomains are not implicitly allowed. MIROVEN_EMAIL_DOMAINS_DEFAULT, MIROVEN_EMAIL_DOMAINS_KR, and MIROVEN_EMAIL_DOMAINS_JP replace each group with a comma-separated list. Empty groups are allowed, but an empty policy, invalid domains, duplicates, or overlapping groups fail startup.

An unlisted address without an existing account creates no challenge or mail job. Requests still return the same 202 and consume the existing rate budgets. Verification rechecks the current policy before creating a user, under the existing email lock; outstanding codes cannot bypass a tightened policy. Failures retain the generic 401. Existing users retain sessions, sign-in, sync, and deletion-code access after domain removal. After account deletion, registering the same address again follows the current signup policy.

New accounts also reject + and . in the local part (before @) for every domain group; domain dots remain valid. This is rechecked before user creation, including older outstanding codes. Existing exact addresses containing those characters retain sign-in and deletion. Do not strip these characters or merge alias identities; an alias of an existing address does not inherit that account's signup exception.

Public GET /api/v1/auth/policy returns domain_groups (DEFAULT, KR, JP), default_email_locale: "en", and existing_accounts_allowed: true. It contains no account information and is not cached. Client guidance must not block an existing user's sign-in. The additional blocked_local_part_characters: ["+", "."] field advertises the local-part rule. Clients tolerate older policy responses without that field.

English is canonical in app/email/locales/en.json; ko.json and ja.json translate the same keys and placeholders. Missing translated keys and unknown locales fall back to English. Startup validates messages/placeholders; tests also require complete shipped catalogs. The recipient domain selects language independently of UI/browser language. Unlisted existing addresses receive English for future requests.

New encrypted mail payloads include locale and absolute expires_at. Retries preserve the selected language, and messages display actual expiry in UTC. Old payloads without these optional fields use English and a generic expiry sentence. No DB or vault-format migration is needed. See API app/email/README.md for translation maintenance.

Sessions, Origin, and CSRF

  • Session tokens use 32 CSPRNG bytes; store only HMAC verifiers. Default expiry is thirty days without sliding refresh.
  • Cookies are HttpOnly, SameSite=Lax, Path=/ and Secure for HTTPS. Only development HTTP omits Secure.
  • Every state-changing API requires Origin to exactly match MIROVEN_PUBLIC_ORIGIN. Authenticated mutations also send X-CSRF-Token, obtained as csrf_token from login or /auth/session.
  • Derive CSRF tokens from the session token with a distinct HMAC purpose. Reloading/querying a session does not invalidate another tab's CSRF token.
  • Credential CORS allows only the configured app origin. MIROVEN_API_ORIGIN controls API host/Secure behavior, defaulting to the same-origin configuration when omitted. Use same-site HTTPS subdomains for split deployment; do not permit the website or Pages previews. Non-browser clients must also follow Origin/CSRF requirements.
  • Authentication actions serialize under the user row lock and recheck current revocation. A logged-out session is rejected on its next request.

Vault concurrency

Initial registration requires expected_version=0. Updates send the fetched version; success increments it. A concurrent update returns 409 vault_conflict. Ownership comes from the session; body user_id is forbidden.

Durable jobs and retention

Create mail jobs within the API transaction. Workers claim them with FOR UPDATE SKIP LOCKED and commit delivery results; process exit releases locks for retry. SMTP acceptance followed by a crash before DB commit may duplicate an email, but a code remains single-use.

Retry delivery up to five times with delays. Do not send expired, consumed, or exhausted codes. Clear payloads for successful, finally failed, or damaged jobs. Hourly cleanup removes codes/jobs/rate windows one day after expiry and expired sessions after one day.

Changing MIROVEN_SECRET_KEY invalidates existing sessions/code verifiers and pending mail decryption. All API/workers must share it. This key is separate from the client's vault decryption key.

Deployment conditions

Production rejects development secrets, HTTP origins, and development database passwords. Authenticated production SMTP requires STARTTLS. compose.yaml is development; use compose.production.yaml for integrated production or compose.truenas.yaml for an API-only host.

Default Uvicorn examples do not trust proxy headers. Configure trusted proxies explicitly or IP-based limits will be incorrect. General JSON bodies are limited to 64 KiB, sync push to 128 KiB; file streaming defaults to 4 MiB and thirty seconds. See sync protocol and deployment.

Errors must not disclose input values, SQL, or secrets; generate request IDs server-side. Do not log emails, codes, cookies, or plaintext. Preserve the AGPL source-access requirements for the version operated and record image provenance.

Browser account-switch defense

Authenticated vault/sync requests carry X-Miroven-User-ID. The server still authorizes by session and returns 409 auth_scope_changed when the hint differs. This blocks a stale tab from posting its vault under another tab's new cookie account. The hint alone never authenticates or selects ownership; the client additionally binds IndexedDB to API URL/user ID.

Clone this wiki locally