openapi: 3.1.0 info: title: Barzaman API version: 1.0.0 summary: Identity, accounts and workspaces of the Barzaman backend (other modules add their paths here). description: | REST conventions (brief §9, ADR-0016): * Versioned `/v1` paths, JSON bodies (`Content-Type: application/json`), UTF-8. * **`Idempotency-Key`** is required on every POST/PUT/PATCH/DELETE (8–128 chars of `[A-Za-z0-9_-:.]`, a new random value per user action). Responses are stored for 24 hours per user and route; a retry with the same key and identical request returns the original response with `Idempotent-Replayed: true`. The same key with a different body → `422 idempotency_key_mismatch`; while the first request is running → `409 idempotency_in_progress`. 401/403/429/5xx outcomes are not stored. Responses that carry credentials (sign-in, refresh, step-up, 2FA enrollment/activation, recovery codes, restore, invite creation) are stored encrypted and replayable for **10 minutes** only. * Errors are RFC 9457 `application/problem+json` with a stable `code` (`type` = `https://api.barzaman.ir/problems/{code}`); clients localize by `code`. `GET /problems/{code}` describes a code. * Lists are cursor-paginated: `?limit=1..200&cursor=…` → `{items, nextCursor}`. * Authentication: `Authorization: Bearer ` (EdDSA JWT, 15 minutes). Refresh with `POST /v1/auth/refresh` (rotating refresh token, 60 days, bound to `deviceId`). * Rate limits per IP, user and route answer `429 rate_limited` with `Retry-After`; successful limited routes expose `RateLimit-Limit` / `RateLimit-Remaining`. The client IP is taken from the edge (never from client-supplied forwarding headers); IPv6 clients are limited per /64. * Tracing: `X-Request-Id` (echoed or generated) and W3C `traceparent` are returned on every response. * Timestamps are ISO-8601 UTC strings; ids are UUIDs (v7 when created by the server). * Request bodies are limited to 1 MB unless stated otherwise. contact: name: Barzaman engineering url: https://barzaman.ir license: name: Proprietary identifier: LicenseRef-Barzaman-Proprietary servers: - url: https://api.barzaman.ir description: Production (region per deployment) - url: http://localhost:8080 description: Local development tags: - name: Public API description: 'Versioned REST API under `/api/v1` (1.3.12, Pro plan, key `api.webhooks`). Authenticate with a personal access token (`bzp_…`) or an OAuth access token; `read` scope for reads, `write` for changes. Limits per token: 120 requests/min, 60 writes/min (`X-RateLimit-Limit`, `X-RateLimit-Remaining`, 429 with `Retry-After`). Finance items stay hidden unless the user opted in.' - name: Webhooks description: 'HTTPS callbacks for `item.created`, `item.updated`, `item.completed`, `reminder.fired`, `booking.requested` (plus `ping` from "Send test"). Each POST carries `Barzaman-Event`, `Barzaman-Delivery`, `Barzaman-Webhook-Id`, `Barzaman-Timestamp` and `Barzaman-Signature: t=,v1=.")>`. Answer 2xx within 10 s; otherwise retried after 1 min, 5 min, 30 min, 2 h, 6 h and 12 h (7 attempts), then marked failed. 60 failed attempts in a row switch the webhook off. Redirects are not followed; only public HTTPS hosts. Deliveries are kept 30 days.' - name: Mini-apps description: 'API of the Telegram, Bale and Eitaa mini-app (app.barzaman.ir/mini/). The client posts the platform `initData`; the server verifies its HMAC (key = HMAC-SHA256("WebAppData", bot or app token)) and answers a 12-hour mini-app session (`bzm.…`).' - name: Auth description: Sign-up with a mobile number and password, sign-in with the phone + password or a one-time SMS code (older apps may still send a legacy username or e-mail), the legacy phone/e-mail OTP endpoints (kept for compatibility, unused by current clients), Google, Apple, sessions, 2FA, step-up. - name: Account description: Profile and preferences, devices, identities, deletion, export. - name: Workspaces description: Workspaces (sync scopes), members and invites. - name: System description: Health, readiness, metrics, keys, problem types. - name: Sync description: Operation-log sync (push, pull, snapshot, scopes) and the realtime WebSocket — wire format in docs/sync/SYNC_PROTOCOL.md. - name: Storage description: Attachments (signed resumable uploads, signed downloads with Range) and export archives. - name: Config description: Remote config, holidays, signed app releases and pricing (public, cacheable, ETag/304). - name: Billing description: Plans and prices, purchase verification (Cafe Bazaar, Myket, Google Play, App Store, Stripe, Paddle), Zarinpal web checkout, signed entitlement tokens, promo codes, invoices. - name: Webhooks description: Payment-provider notifications (App Store Server Notifications V2, Google Play RTDN via Pub/Sub, Stripe, Paddle) and bot updates — authenticated by provider signatures or secrets, not bearer tokens. - name: Push description: Web Push (VAPID, RFC 8030/8291/8292) subscriptions for the PWA and Telegram/Bale linking; the worker dispatches remote reminders every minute. - name: Support description: Public contact form and web account-deletion requests (honeypot, per-IP limits, self-hosted proof-of-work) and tickets from the app. - name: Referrals description: Invite friends — one code per account; a new account registered with it and the inviter each get 30 days of Plus (abuse guards; release 1.1). - name: Integrations description: Personal access tokens (`bzp_…`, hashed, scopes read/write, expiry, last use, audit), the integrations REST API and the MCP endpoint for AI assistants. Writes are sync operations every device pulls. - name: Internal description: Calls between the API and the Bale bot service (infra/bale-bot) on the internal docker network only — `X-Bot-Secret` required; hidden (404) for anything that came through the public proxy. - name: Calendar description: Private ICS subscribe URLs (Plus+) for Google, Apple and Outlook calendars. - name: Booking description: Public booking pages of professionals (Pro+), owner endpoints and the public, abuse-guarded booking flow. - name: Templates description: Publishing and sharing template trees (Pro+); previews and imports are free. - name: ItemShares description: Share one item with one person by phone, e-mail or username (1.3.14) - name: Admin description: Staff console API under /admin/v1 — separate staff sessions, mandatory TOTP, RBAC (owner, admin, support, content), optional IP allowlist, every action audited. security: - bearerAuth: [] paths: # ───────────────────────────── Auth ───────────────────────────── /v1/auth/register: post: operationId: registerWithPassword tags: [Auth] summary: Create an account with a mobile number and a password description: | Phone as E.164 (Iranian `09…` and Persian/Arabic digits are accepted and normalised to `+98…`). New usernames are not accepted: a `username` sent by an older app is ignored, whether or not it is taken, and on its own it is no identifier (`422 invalid_identifier`, field `phone`). `email` is optional, for older apps, and stored **unverified**. Without `displayName` the account gets a localized default (`کاربر برزمان`, `مستخدم برزمان`, `Barzaman user`), never derived from the phone. Release 1.2 (`PHONE_VERIFICATION=required`): `phone` (an Iranian mobile number) and `phoneCode` (from `POST /v1/auth/phone/code` with `purpose: signup`) are required and the phone is stored **verified**. Whether the number is taken (`409 identifier_taken`, field `phone`) is only answered after a valid code. Password: 8–128 characters, not only digits, not a common password, not containing an identifier (`weak_password` with extension `reason`: `too_short`, `too_long`, `all_digits`, `common`, `contains_identifier`). The response is the same as an OTP sign-in (`201`), plus `referral` when a `referralCode` was given (a bad code never fails the registration). security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: required: true content: application/json: schema: allOf: - $ref: '#/components/schemas/SignInContext' - type: object required: [password] properties: email: {type: string, format: email, deprecated: true} phone: {type: string, maxLength: 32, examples: ['09121234567']} phoneCode: {type: string, maxLength: 20, examples: ['482913'], description: SMS code proving `phone` (release 1.2)} password: {type: string, minLength: 8, maxLength: 128, writeOnly: true} displayName: {type: string, maxLength: 80} referralCode: {type: string, maxLength: 32} responses: '201': description: Signed in content: application/json: schema: allOf: - $ref: '#/components/schemas/SignInResult' - type: object properties: referral: {$ref: '#/components/schemas/ReferralOutcome'} '400': {description: '`otp_invalid` (extension `attemptsRemaining`), `otp_expired`, `otp_attempts_exceeded`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`identifier_taken` (extension `field`: phone or email)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {description: '`invalid_identifier` (`errors[].field` phone / phoneCode `required`), `weak_password`, `validation_failed`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/login: post: operationId: loginWithPassword tags: [Auth] summary: Sign in with a phone number (any digit style) and the password description: | `identifier` is the phone. Older apps may still send the legacy username or e-mail of an existing account; these keep working, including after the account verifies a phone. Failures always answer `401 invalid_credentials` (no account enumeration; unknown accounts cost the same Argon2id work). Throttled per identifier (5 failures → 1-minute lock, doubling per further failure up to 1 hour) and per IP (30 failures/hour): `429 rate_limited` with `Retry-After`. With TOTP enabled the response is `{status: mfa_required, mfaToken}` — complete it with `POST /v1/auth/2fa/challenge`. security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: required: true content: application/json: schema: allOf: - $ref: '#/components/schemas/SignInContext' - type: object required: [identifier, password] properties: identifier: {type: string, maxLength: 254} password: {type: string, maxLength: 512, writeOnly: true} responses: '200': {$ref: '#/components/responses/SignIn'} '401': {description: '`invalid_credentials`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '403': {$ref: '#/components/responses/Forbidden'} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/password/change: post: operationId: changePassword tags: [Auth] summary: Change the password (or set the first one for an account created by OTP); signs out every other session parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: required: true content: application/json: schema: type: object required: [newPassword] properties: currentPassword: {type: string, writeOnly: true, description: Required when the account already has a password} newPassword: {type: string, minLength: 8, maxLength: 128, writeOnly: true} responses: '204': {description: Changed} '400': {description: '`invalid_credentials` (wrong current password)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {description: '`weak_password`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/password/reset/request: post: operationId: requestPasswordReset tags: [Auth] summary: Ask for a password reset — a one-time link in the linked Bale chat, or the support contact description: | Always `202`. When the account has a linked Bale chat the bot sends a one-time link (`https://app.barzaman.ir/reset?token=…`, 30 minutes, single use) and `channel` is `bale`; otherwise (no such account, no linked chat, delivery failed) `channel` is `support` and the client shows the support link. No SMS or e-mail is ever sent. security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [identifier], properties: {identifier: {type: string, maxLength: 254}}}}}} responses: '202': description: Accepted content: application/json: schema: type: object required: [status, channel, supportUrl, supportEmail] properties: status: {const: accepted} channel: {type: string, enum: [bale, support]} expiresInMinutes: {type: integer, examples: [30]} supportUrl: {type: string, format: uri} supportEmail: {type: string, format: email} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/password/reset/confirm: post: operationId: confirmPasswordReset tags: [Auth] summary: Set a new password with the token of a reset link; signs out every session security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [token, newPassword], properties: {token: {type: string, maxLength: 200}, newPassword: {type: string, minLength: 8, maxLength: 128, writeOnly: true}}}}}} responses: '204': {description: Password set} '400': {description: '`reset_token_invalid` (unknown, expired or used)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {description: '`weak_password`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/phone/code: post: operationId: requestPhoneCode tags: [Auth] summary: Send an SMS code for sign-up, sign-in with a code, or password reset (release 1.2) description: | Iranian mobile numbers only (`09…`, `+98`, `0098`, Persian/Arabic digits; others `422 invalid_phone`). 6 digits from a CSPRNG, stored as an HMAC, valid 2 minutes, single use, 5 attempts. The answer is the same whether or not the number has an account: for `login` and `reset` nothing is sent to a number without one. Throttles (Valkey): growing resend cooldown per number (60 s, 120 s, …), hourly/daily caps per number, IP and device (`429 otp_throttled` with `Retry-After`). `503 sms_unavailable` while the SMS provider is down or misconfigured (fail fast; `Retry-After`). security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: required: true content: application/json: schema: type: object required: [phone, purpose, deviceId] properties: phone: {type: string, maxLength: 32, examples: ['09121234567']} purpose: {type: string, enum: [signup, login, reset]} deviceId: {$ref: '#/components/schemas/ClientDeviceId'} locale: {$ref: '#/components/schemas/Locale'} responses: '200': {description: Code sent (or, for an unknown number, silently not sent), content: {application/json: {schema: {$ref: '#/components/schemas/OtpRequestResult'}}}} '422': {description: '`invalid_phone`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} '503': {description: '`sms_unavailable`, `provider_not_configured`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/auth/phone/login: post: operationId: loginWithPhoneCode tags: [Auth] summary: Sign in with a one-time SMS code (purpose `login`) instead of the password description: An unknown number fails exactly like a wrong code (`otp_invalid`). Same response as a password sign-in (with `mfa_required` when TOTP is on). security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: required: true content: application/json: schema: allOf: - $ref: '#/components/schemas/SignInContext' - type: object required: [phone, code] properties: phone: {type: string, maxLength: 32} code: {type: string, maxLength: 20} challengeId: {type: string, format: uuid} responses: '200': {$ref: '#/components/responses/SignIn'} '400': {description: '`otp_invalid`, `otp_expired`, `otp_attempts_exceeded`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '403': {$ref: '#/components/responses/Forbidden'} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/password/reset/sms: post: operationId: resetPasswordWithSmsCode tags: [Auth] summary: Set a new password with an SMS code sent to the account's phone (purpose `reset`); the code also verifies the number. Signs out every session, then signs in when `deviceId` is sent security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [phone, code, newPassword], properties: {phone: {type: string, maxLength: 32}, code: {type: string, maxLength: 20}, newPassword: {type: string, minLength: 8, maxLength: 128, writeOnly: true}, deviceId: {type: string}, device: {type: object}}}}}} responses: '200': {description: 'Password set and signed in (same body as `/v1/auth/login`; may be `mfa_required`)'} '204': {description: 'Password set (no `deviceId` sent)'} '400': {description: '`otp_invalid`, `otp_expired`, `otp_attempts_exceeded`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {description: '`weak_password`, `invalid_phone`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/me/phone/code: post: operationId: requestMyPhoneCode tags: [Account] summary: Send a code to verify a (new) mobile number for the signed-in account description: Open to accounts without a verified phone (which get `403 phone_verification_required` everywhere else). parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [phone], properties: {phone: {type: string, maxLength: 32}, deviceId: {$ref: '#/components/schemas/ClientDeviceId'}, locale: {$ref: '#/components/schemas/Locale'}}}}}} responses: '200': {description: Code sent, content: {application/json: {schema: {$ref: '#/components/schemas/OtpRequestResult'}}}} '422': {description: '`invalid_phone`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} '503': {description: '`sms_unavailable`, `provider_not_configured`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/me/phone: post: operationId: verifyMyPhone tags: [Account] summary: Verify (or change to) a mobile number with its code; returns a new access token description: | The account keeps one phone: a previous number is replaced (and told by SMS when a sender line is configured). The new access token carries `pv: true`. Open to accounts without a verified phone. parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [phone, code], properties: {phone: {type: string, maxLength: 32}, code: {type: string, maxLength: 20}}}}}} responses: '200': description: Verified content: application/json: schema: type: object required: [accessToken, expiresIn, user] properties: accessToken: {type: string} expiresIn: {type: integer} user: {type: object} '400': {description: '`otp_invalid`, `otp_expired`, `otp_attempts_exceeded`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`identity_in_use`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/otp/request: post: operationId: requestPhoneOtp tags: [Auth] summary: Send a sign-in code by SMS description: | Sends a 6-digit code (valid 2 minutes, 5 attempts). Accepts E.164, `00` prefixes, Iranian national formats (`09…`) and Persian/Arabic digits. The response never reveals whether an account exists. Throttled per phone (exponential cooldown), IP, device and destination country. `purpose=link` (add this phone to the signed-in account) requires a bearer token with a fresh authentication (≤ 10 minutes). security: [{}, {bearerAuth: []}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [phone, deviceId] properties: phone: {type: string, maxLength: 32, examples: ['09121234567', '+989121234567']} purpose: {type: string, enum: [login, link], default: login} deviceId: {$ref: '#/components/schemas/ClientDeviceId'} locale: {$ref: '#/components/schemas/Locale'} responses: '200': {description: Code sent, content: {application/json: {schema: {$ref: '#/components/schemas/OtpRequestResult'}}}} '403': {$ref: '#/components/responses/Forbidden'} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} '502': {$ref: '#/components/responses/Problem'} '503': {$ref: '#/components/responses/Unavailable'} /v1/auth/otp/verify: post: operationId: verifyPhoneOtp tags: [Auth] summary: Verify an SMS code and sign in (creates the account on first sign-in) description: | Creates the user (region of the deployment), the personal workspace, the device and a session on first sign-in. When the account has 2FA enabled the response is `{status: "mfa_required", mfaToken}`; complete it with `POST /v1/auth/2fa/challenge`. security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: allOf: - $ref: '#/components/schemas/SignInContext' - type: object required: [phone, code] properties: phone: {type: string, maxLength: 32} code: {type: string, description: 6 digits (Persian/Arabic digits accepted), examples: ['482913']} challengeId: {type: string, format: uuid} responses: '200': {$ref: '#/components/responses/SignIn'} '400': {$ref: '#/components/responses/OtpProblem'} '403': {$ref: '#/components/responses/Forbidden'} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/email/request: post: operationId: requestEmailOtp tags: [Auth] summary: Send a sign-in code by e-mail (fa/ar RTL or en template) security: [{}, {bearerAuth: []}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [email, deviceId] properties: email: {type: string, format: email, maxLength: 254} purpose: {type: string, enum: [login, link], default: login} deviceId: {$ref: '#/components/schemas/ClientDeviceId'} locale: {$ref: '#/components/schemas/Locale'} responses: '200': {description: Code sent, content: {application/json: {schema: {$ref: '#/components/schemas/OtpRequestResult'}}}} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} '502': {$ref: '#/components/responses/Problem'} '503': {$ref: '#/components/responses/Unavailable'} /v1/auth/email/verify: post: operationId: verifyEmailOtp tags: [Auth] summary: Verify an e-mail code and sign in security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: allOf: - $ref: '#/components/schemas/SignInContext' - type: object required: [email, code] properties: email: {type: string, format: email} code: {type: string} challengeId: {type: string, format: uuid} responses: '200': {$ref: '#/components/responses/SignIn'} '400': {$ref: '#/components/responses/OtpProblem'} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/oauth/google: post: operationId: signInWithGoogle tags: [Auth] summary: Sign in with a Google ID token (GLOBAL region only) security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {$ref: '#/components/requestBodies/OAuthSignIn'} responses: '200': {$ref: '#/components/responses/SignIn'} '400': {$ref: '#/components/responses/Problem'} '403': {$ref: '#/components/responses/Forbidden'} '503': {$ref: '#/components/responses/Unavailable'} /v1/auth/oauth/apple: post: operationId: signInWithApple tags: [Auth] summary: Sign in with Apple (GLOBAL region only) description: '`nonce` is the raw nonce; the token may carry it raw or SHA-256 hashed.' security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {$ref: '#/components/requestBodies/OAuthSignIn'} responses: '200': {$ref: '#/components/responses/SignIn'} '400': {$ref: '#/components/responses/Problem'} '403': {$ref: '#/components/responses/Forbidden'} '503': {$ref: '#/components/responses/Unavailable'} /v1/auth/2fa/challenge: post: operationId: completeMfaChallenge tags: [Auth] summary: Complete a sign-in that requires 2FA (TOTP or recovery code) description: | The MFA token is single-use, valid 5 minutes, 5 attempts. Wrong second-factor codes are also counted per user across routes (10 per 15 minutes → `429 mfa_attempts_exceeded`). security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [mfaToken, code] properties: mfaToken: {type: string} code: {type: string, description: 6-digit TOTP code or a recovery code (XXXXX-XXXXX)} responses: '200': {$ref: '#/components/responses/SignIn'} '400': {$ref: '#/components/responses/Problem'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/refresh: post: operationId: refreshTokens tags: [Auth] summary: Rotate the refresh token and get a new access token description: | Every refresh returns a new refresh token; the old one stops working. Presenting a rotated token again revokes the whole session (`401 refresh_reused`), except within 10 seconds from the same device (`409 refresh_superseded` — re-read the stored token). Retry network failures with the same `Idempotency-Key` to receive the same new tokens. security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [refreshToken, deviceId] properties: refreshToken: {type: string} deviceId: {$ref: '#/components/schemas/ClientDeviceId'} appVersion: {type: string, maxLength: 50} responses: '200': description: New tokens content: application/json: schema: allOf: - $ref: '#/components/schemas/TokenBundle' - type: object properties: {status: {const: ok}} '401': {$ref: '#/components/responses/Unauthorized'} '403': {$ref: '#/components/responses/Forbidden'} '409': {$ref: '#/components/responses/Conflict'} /v1/auth/logout: post: operationId: logout tags: [Auth] summary: Sign out this session (or every session) parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] requestBody: content: application/json: schema: type: object properties: allDevices: {type: boolean, default: false} responses: '204': {description: Signed out} '401': {$ref: '#/components/responses/Unauthorized'} /v1/auth/sessions: get: operationId: listSessions tags: [Auth] summary: Active sessions of the account responses: '200': description: Sessions content: application/json: schema: type: object properties: items: {type: array, items: {$ref: '#/components/schemas/Session'}} nextCursor: {type: ['string', 'null']} '401': {$ref: '#/components/responses/Unauthorized'} /v1/auth/sessions/{id}: delete: operationId: revokeSession tags: [Auth] summary: Revoke a session (takes effect immediately, closes its WebSockets) parameters: - {$ref: '#/components/parameters/IdempotencyKey'} - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '204': {description: Revoked} '404': {$ref: '#/components/responses/NotFound'} /v1/auth/2fa/enroll: post: operationId: enrollTotp tags: [Auth] summary: Start TOTP enrollment (requires fresh authentication) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] responses: '200': description: Secret for the authenticator app content: application/json: schema: type: object properties: secret: {type: string, description: RFC 4648 base32} otpauthUri: {type: string, examples: ['otpauth://totp/Barzaman%3Aali%40example.com?secret=…&issuer=Barzaman&algorithm=SHA1&digits=6&period=30']} digits: {const: 6} period: {const: 30} algorithm: {const: SHA1} '401': {$ref: '#/components/responses/StepUp'} '409': {$ref: '#/components/responses/Conflict'} /v1/auth/2fa/verify: post: operationId: activateTotp tags: [Auth] summary: Confirm enrollment with a first code; returns recovery codes once parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {$ref: '#/components/requestBodies/Code'} responses: '200': description: 2FA enabled content: application/json: schema: type: object properties: enabled: {const: true} recoveryCodes: {type: array, items: {type: string}, minItems: 10, maxItems: 10} accessToken: {type: string} expiresIn: {type: integer} '400': {$ref: '#/components/responses/Problem'} '409': {$ref: '#/components/responses/Conflict'} /v1/auth/2fa/disable: post: operationId: disableTotp tags: [Auth] summary: Disable 2FA with a TOTP or recovery code parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {$ref: '#/components/requestBodies/Code'} responses: '200': {description: Disabled, content: {application/json: {schema: {type: object, properties: {enabled: {const: false}}}}}} '400': {$ref: '#/components/responses/Problem'} '409': {$ref: '#/components/responses/Conflict'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/2fa/recovery-codes: post: operationId: regenerateRecoveryCodes tags: [Auth] summary: Replace the recovery codes (requires a TOTP code) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {$ref: '#/components/requestBodies/Code'} responses: '200': {description: New codes, content: {application/json: {schema: {type: object, properties: {recoveryCodes: {type: array, items: {type: string}}}}}}} '400': {$ref: '#/components/responses/Problem'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/step-up/request: post: operationId: requestStepUpCode tags: [Auth] summary: Send a step-up code to the account's own phone or e-mail parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [channel] properties: channel: {type: string, enum: [phone, email]} deviceId: {$ref: '#/components/schemas/ClientDeviceId'} locale: {$ref: '#/components/schemas/Locale'} responses: '200': description: Code sent content: application/json: schema: allOf: - $ref: '#/components/schemas/OtpRequestResult' - type: object properties: {destination: {type: string, description: Masked phone or e-mail}} '409': {$ref: '#/components/responses/Conflict'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/auth/step-up: post: operationId: stepUp tags: [Auth] summary: Re-authenticate (password, OTP, TOTP or a fresh Google/Apple token) for sensitive actions description: | Sensitive routes answer `401 step_up_required` (with `maxAgeSeconds`) when the last strong authentication is older than 10 minutes. `method: password` (release 1.1) checks the account password with the same throttling as a password change: `400 invalid_credentials` when wrong, `409 no_identity_for_channel` when the account has no password yet, `429 rate_limited` while locked. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [method] properties: method: {type: string, enum: [password, otp, totp, google, apple]} password: {type: string, writeOnly: true, description: Required for method=password} channel: {type: string, enum: [phone, email], description: Required for method=otp} code: {type: string} idToken: {type: string} nonce: {type: string} responses: '200': description: Fresh access token content: application/json: schema: type: object properties: accessToken: {type: string} expiresIn: {type: integer} authTime: {type: string, format: date-time} stepUpValidFor: {type: integer, examples: [600]} '400': {description: '`invalid_credentials` (password), `otp_invalid`, `otp_expired`, `mfa_invalid`, `oauth_token_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {$ref: '#/components/responses/Conflict'} '429': {$ref: '#/components/responses/TooManyRequests'} # ───────────────────────────── Account ───────────────────────────── /v1/me: get: operationId: getMe tags: [Account] summary: The signed-in user (also allowed during the deletion grace period) responses: '200': {description: Profile, content: {application/json: {schema: {$ref: '#/components/schemas/User'}}}} '401': {$ref: '#/components/responses/Unauthorized'} patch: operationId: updateMe tags: [Account] summary: Update profile and preferences description: Unknown fields are ignored. Enum values are written in the app's canonical spelling (core enum names). parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object properties: displayName: {type: string, maxLength: 80} locale: {$ref: '#/components/schemas/Locale'} calendar: {type: string, enum: [gregorian, jalali, hijriUmmAlQura, hijriCivil], description: 'Aliases accepted: persian, hijri_umm_al_qura, hijri_civil'} digits: {type: string, enum: [latin, persian, arabicIndic], description: 'Alias: arabic_indic'} weekStart: {type: string, enum: [saturday, sunday, monday]} timeFormat: {type: string, enum: [h24, h12], description: 'Aliases: 24h, 12h'} timeZone: {type: string, description: IANA time zone, examples: [Asia/Tehran]} ageConfirmed: {type: boolean} responses: '200': {description: Updated profile, content: {application/json: {schema: {$ref: '#/components/schemas/User'}}}} '403': {$ref: '#/components/responses/Forbidden'} '422': {$ref: '#/components/responses/Validation'} /v1/me/devices: get: operationId: listDevices tags: [Account] summary: Devices that signed in to the account responses: '401': {$ref: '#/components/responses/Unauthorized'} '200': description: Devices content: application/json: schema: type: object properties: items: {type: array, items: {$ref: '#/components/schemas/Device'}} nextCursor: {type: ['string', 'null']} /v1/me/devices/{id}: delete: operationId: signOutDevice tags: [Account] summary: Remote sign-out of a device (revokes all its sessions) parameters: - {$ref: '#/components/parameters/IdempotencyKey'} - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '204': {description: Signed out} '404': {$ref: '#/components/responses/NotFound'} /v1/me/finance-sharing: get: operationId: getFinanceSharing tags: [Account] summary: Per-channel consent to share finance items outside the app (1.3.12) description: >- Channels telegram, bale, calendar and mcp (MCP and the REST API). All off by default; finance items (cheques, loans, installments, debts, bills, subscriptions) reach a channel only while it is enabled. responses: '401': {$ref: '#/components/responses/Unauthorized'} '200': description: Consents content: application/json: schema: type: object properties: channels: type: object additionalProperties: type: object properties: enabled: {type: boolean} consentedAt: {type: ['string', 'null'], format: date-time} revokedAt: {type: ['string', 'null'], format: date-time} /v1/me/finance-sharing/{channel}: put: operationId: setFinanceSharing tags: [Account] summary: Turn one finance sharing channel on (after the risk dialog) or off parameters: - {name: channel, in: path, required: true, schema: {type: string, enum: [telegram, bale, calendar, mcp]}} requestBody: required: true content: application/json: schema: type: object required: [enabled] properties: enabled: {type: boolean} acknowledged: {type: boolean, description: Required (true) to enable} responses: '200': {description: The consents (same body as GET)} '404': {$ref: '#/components/responses/NotFound'} '422': {description: acknowledged missing when enabling} /v1/me/identities: post: operationId: linkIdentity tags: [Account] summary: Link a phone, e-mail, Google or Apple identity (requires fresh authentication) description: For phone/e-mail, first request a code with `purpose=link`. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [kind] properties: kind: {type: string, enum: [phone, email, google, apple]} value: {type: string, description: Phone or e-mail} code: {type: string} idToken: {type: string} nonce: {type: string} responses: '201': {description: Linked, content: {application/json: {schema: {$ref: '#/components/schemas/Identity'}}}} '400': {$ref: '#/components/responses/OtpProblem'} '401': {$ref: '#/components/responses/StepUp'} '409': {$ref: '#/components/responses/Conflict'} /v1/me/identities/{id}: delete: operationId: unlinkIdentity tags: [Account] summary: Remove an identity (not the last one; requires fresh authentication) parameters: - {$ref: '#/components/parameters/IdempotencyKey'} - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '204': {description: Removed} '404': {$ref: '#/components/responses/NotFound'} '409': {$ref: '#/components/responses/Conflict'} /v1/me/delete: post: operationId: requestAccountDeletion tags: [Account] summary: Delete the account (fresh authentication; 30-day grace period) description: | Deactivates at once and signs out every session. Signing in again during the grace period is allowed (tokens then only reach `/v1/me`, `/v1/me/restore`, `/v1/me/export`, sessions and logout; other routes answer `403 account_pending_deletion`). After 30 days the worker erases the account; shared workspaces it solely owns pass to the longest-standing member. Store subscriptions must be cancelled separately (`subscriptionsNotice`). parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: content: application/json: schema: type: object properties: reason: {type: string, maxLength: 500} responses: '202': description: Scheduled content: application/json: schema: type: object properties: status: {const: pending_deletion} scheduledFor: {type: string, format: date-time} restoreUntil: {type: string, format: date-time} subscriptionsNotice: {type: boolean} '401': {$ref: '#/components/responses/StepUp'} /v1/me/restore: post: operationId: restoreAccount tags: [Account] summary: Cancel a pending deletion parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] responses: '200': description: Restored content: application/json: schema: type: object properties: user: {$ref: '#/components/schemas/User'} accessToken: {type: string} expiresIn: {type: integer} '409': {$ref: '#/components/responses/Conflict'} /v1/me/export: post: operationId: startExport tags: [Account] summary: Start a full-fidelity data export (fresh authentication) description: Returns the job already in progress when there is one (200). Never paywalled. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: content: application/json: schema: type: object properties: format: {type: string, enum: [barzaman], default: barzaman} responses: '202': {description: Queued, content: {application/json: {schema: {$ref: '#/components/schemas/ExportJob'}}}} '200': {description: Already in progress, content: {application/json: {schema: {$ref: '#/components/schemas/ExportJob'}}}} '401': {$ref: '#/components/responses/StepUp'} '429': {$ref: '#/components/responses/TooManyRequests'} '503': {$ref: '#/components/responses/Unavailable'} get: operationId: listExports tags: [Account] summary: Recent exports responses: '401': {$ref: '#/components/responses/Unauthorized'} '200': description: Export jobs content: application/json: schema: type: object properties: items: {type: array, items: {$ref: '#/components/schemas/ExportJob'}} nextCursor: {type: ['string', 'null']} /v1/me/export/{id}: get: operationId: getExport tags: [Account] summary: Export status (with a short-lived download URL when ready) parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}] responses: '200': {description: Export job, content: {application/json: {schema: {$ref: '#/components/schemas/ExportJob'}}}} '404': {$ref: '#/components/responses/NotFound'} # ───────────────────────────── Workspaces ───────────────────────────── /v1/workspaces: get: operationId: listWorkspaces tags: [Workspaces] summary: Workspaces the user belongs to parameters: [{$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}] responses: '200': description: Page of workspaces content: application/json: schema: type: object properties: items: {type: array, items: {$ref: '#/components/schemas/Workspace'}} nextCursor: {type: ['string', 'null']} '400': {$ref: '#/components/responses/Problem'} post: operationId: createWorkspace tags: [Workspaces] summary: Create a shared, classroom or clients workspace description: | `id` may be proposed by the client (a workspace created offline); re-sending it is idempotent for its owner. Plan limits: `sharing.maxShares` and, for classroom/clients, `sharing.level` ≥ `spaces` → `403 limit_exceeded` with `feature`. Since 1.3.12 Free has `sharing.maxShares` 0; creating invites and joining a shared space need `sharing.level` ≥ `basic` (class and client spaces may be joined on any plan). parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [kind, name] properties: id: {type: string, format: uuid} kind: {type: string, enum: [shared, classroom, clients]} name: {type: string, minLength: 1, maxLength: 100} color: {type: integer, minimum: 0, maximum: 4294967295, description: ARGB} icon: {type: string, pattern: '^[a-z0-9_.\-]{1,64}$'} settings: {type: object, description: Up to 50 keys / 16 KB} responses: '201': description: Created headers: {Location: {schema: {type: string}}} content: {application/json: {schema: {$ref: '#/components/schemas/Workspace'}}} '403': {$ref: '#/components/responses/Forbidden'} '409': {$ref: '#/components/responses/Conflict'} '422': {$ref: '#/components/responses/Validation'} /v1/workspaces/{id}: parameters: [{$ref: '#/components/parameters/WorkspaceId'}] get: operationId: getWorkspace tags: [Workspaces] summary: One workspace (404 for non-members) responses: '200': {description: Workspace, content: {application/json: {schema: {$ref: '#/components/schemas/Workspace'}}}} '404': {$ref: '#/components/responses/NotFound'} patch: operationId: updateWorkspace tags: [Workspaces] summary: Rename / recolor / change settings (owners); `null` clears color or icon parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object properties: name: {type: string, minLength: 1, maxLength: 100} color: {type: ['integer', 'null']} icon: {type: ['string', 'null']} settings: {type: object} responses: '200': {description: Updated, content: {application/json: {schema: {$ref: '#/components/schemas/Workspace'}}}} '403': {$ref: '#/components/responses/Forbidden'} '404': {$ref: '#/components/responses/NotFound'} delete: operationId: deleteWorkspace tags: [Workspaces] summary: Delete (owners; restorable for 30 days; not the personal workspace) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] responses: '204': {description: Deleted} '403': {$ref: '#/components/responses/Forbidden'} '404': {$ref: '#/components/responses/NotFound'} '409': {$ref: '#/components/responses/Conflict'} /v1/workspaces/{id}/restore: parameters: [{$ref: '#/components/parameters/WorkspaceId'}] post: operationId: restoreWorkspace tags: [Workspaces] summary: Restore a deleted workspace within 30 days (owners) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] responses: '200': {description: Restored, content: {application/json: {schema: {$ref: '#/components/schemas/Workspace'}}}} '403': {$ref: '#/components/responses/Forbidden'} '404': {$ref: '#/components/responses/NotFound'} /v1/workspaces/{id}/members: parameters: [{$ref: '#/components/parameters/WorkspaceId'}] get: operationId: listMembers tags: [Workspaces] summary: Members (display names only; no phone numbers or e-mails) parameters: [{$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}] responses: '200': description: Page of members content: application/json: schema: type: object properties: items: {type: array, items: {$ref: '#/components/schemas/Member'}} nextCursor: {type: ['string', 'null']} '404': {$ref: '#/components/responses/NotFound'} /v1/workspaces/{id}/members/{userId}: parameters: - {$ref: '#/components/parameters/WorkspaceId'} - {name: userId, in: path, required: true, schema: {type: string, format: uuid}} patch: operationId: updateMember tags: [Workspaces] summary: Change a member's role (owners; the last owner cannot be demoted) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [role] properties: role: {$ref: '#/components/schemas/Role'} responses: '200': {description: Updated, content: {application/json: {schema: {type: object, properties: {userId: {type: string}, role: {$ref: '#/components/schemas/Role'}}}}}} '403': {$ref: '#/components/responses/Forbidden'} '404': {$ref: '#/components/responses/NotFound'} '409': {$ref: '#/components/responses/Conflict'} delete: operationId: removeMember tags: [Workspaces] summary: Remove a member (owners) or leave (self); the last owner cannot leave parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] responses: '204': {description: Removed} '403': {$ref: '#/components/responses/Forbidden'} '404': {$ref: '#/components/responses/NotFound'} '409': {$ref: '#/components/responses/Conflict'} /v1/workspaces/{id}/invites: parameters: [{$ref: '#/components/parameters/WorkspaceId'}] post: operationId: createInvite tags: [Workspaces] summary: Create an invite (owners); the code and link token are shown once parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: content: application/json: schema: type: object properties: role: {type: string, enum: [editor, commenter, viewer], default: editor} maxUses: {type: integer, minimum: 1, maximum: 1000, default: 1} expiresInHours: {type: integer, minimum: 1, maximum: 720, default: 168} responses: '201': {description: Invite, content: {application/json: {schema: {$ref: '#/components/schemas/CreatedInvite'}}}} '403': {$ref: '#/components/responses/Forbidden'} '409': {$ref: '#/components/responses/Conflict'} get: operationId: listInvites tags: [Workspaces] summary: Invites of the workspace (owners; codes are never shown again) responses: '401': {$ref: '#/components/responses/Unauthorized'} '200': description: Invites content: application/json: schema: type: object properties: items: {type: array, items: {$ref: '#/components/schemas/Invite'}} nextCursor: {type: ['string', 'null']} /v1/workspaces/{id}/invites/{inviteId}: parameters: - {$ref: '#/components/parameters/WorkspaceId'} - {name: inviteId, in: path, required: true, schema: {type: string, format: uuid}} delete: operationId: revokeInvite tags: [Workspaces] summary: Revoke an invite (owners) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] responses: '204': {description: Revoked} '404': {$ref: '#/components/responses/NotFound'} /v1/invites/{code}: get: operationId: previewInvite tags: [Workspaces] summary: Preview an invite by code (XXXX-XXXX, case/dash-insensitive) or link token security: [{}, {bearerAuth: []}] parameters: [{$ref: '#/components/parameters/InviteCode'}] responses: '200': description: Preview content: application/json: schema: type: object properties: workspace: type: object properties: name: {type: string} kind: {type: string} memberCount: {type: integer} role: {$ref: '#/components/schemas/Role'} invitedBy: {type: ['string', 'null']} expiresAt: {type: string, format: date-time} '404': {$ref: '#/components/responses/NotFound'} '410': {$ref: '#/components/responses/Gone'} /v1/invites/{code}/accept: post: operationId: acceptInvite tags: [Workspaces] summary: Join the workspace (idempotent for existing members; roles are never lowered) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}, {$ref: '#/components/parameters/InviteCode'}] responses: '201': {description: Joined, content: {application/json: {schema: {$ref: '#/components/schemas/InviteAccepted'}}}} '200': {description: Already a member, content: {application/json: {schema: {$ref: '#/components/schemas/InviteAccepted'}}}} '403': {$ref: '#/components/responses/Forbidden'} '404': {$ref: '#/components/responses/NotFound'} '410': {$ref: '#/components/responses/Gone'} # ───────────────────────────── System ───────────────────────────── /healthz: get: operationId: healthz tags: [System] summary: Liveness security: [{}] responses: '200': {description: Alive, content: {application/json: {schema: {type: object, properties: {status: {const: ok}, version: {type: string}}}}}} /readyz: get: operationId: readyz tags: [System] summary: Readiness (PostgreSQL and Valkey reachable, not draining) security: [{}] responses: '200': {description: Ready, content: {application/json: {schema: {$ref: '#/components/schemas/Readiness'}}}} '503': {description: Not ready, content: {application/json: {schema: {$ref: '#/components/schemas/Readiness'}}}} /metrics: get: operationId: metrics tags: [System] summary: 'Prometheus metrics (private network, or Authorization: Bearer $METRICS_TOKEN)' security: [{}, {metricsToken: []}] responses: '200': {description: Text exposition format 0.0.4, content: {text/plain: {schema: {type: string}}}} '404': {$ref: '#/components/responses/NotFound'} /.well-known/jwks.json: get: operationId: getJwks tags: [System] summary: Public keys that verify access tokens (OKP Ed25519) security: [{}] responses: '200': description: JWKS content: application/json: schema: type: object properties: keys: type: array items: type: object properties: kty: {const: OKP} crv: {const: Ed25519} x: {type: string} kid: {type: string} alg: {const: EdDSA} use: {const: sig} /problems/{code}: get: operationId: describeProblem tags: [System] summary: Describe a problem type security: [{}] parameters: [{name: code, in: path, required: true, schema: {$ref: '#/components/schemas/ProblemCode'}}] responses: '200': {description: Problem type, content: {application/json: {schema: {type: object, properties: {type: {type: string}, code: {type: string}, title: {type: string}}}}}} '404': {$ref: '#/components/responses/NotFound'} # ───────────────────────────── Sync ───────────────────────────── /v1/sync/push: post: operationId: syncPush tags: [Sync] summary: Push operations (≤ 500 ops, ≤ 1 MB) applied in one transaction description: | Merge rules and op format: docs/sync/SYNC_PROTOCOL.md. Idempotent by `opId` (30 days) and by `Idempotency-Key` (24 h). Every op gets `applied`, `superseded` or `rejected` (`reason`: `not_member`, `read_only`, `limit_exceeded`, `scope_mismatch`, `entity_not_syncable`, `invalid_op`, `row_too_large`, `op_id_conflict`). A malformed op — including a value the server cannot store exactly (`invalid_op` detail `value_text`: U+0000 or an unpaired surrogate; `value_number`: a non-finite number; `value_too_deep`: nesting deeper than 64) — rejects only that op. Rate limit 120/min per user. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: {application/json: {schema: {$ref: '#/components/schemas/SyncPushRequest'}}} responses: '200': {description: Per-op results, content: {application/json: {schema: {$ref: '#/components/schemas/SyncPushResponse'}}}} '401': {$ref: '#/components/responses/Unauthorized'} '403': description: '`device_mismatch` (deviceId is not the session device), `device_limit_exceeded` (`limit`, `activeDevices`), `account_pending_deletion`' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} '409': description: 'Nothing applied: `clock_skew` (`serverTime`, `serverTimeMs`, `aheadMs`, `maxSkewMs`) or `schema_version_unsupported` (`minSchemaVersion`, `maxSchemaVersion`)' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} '413': {$ref: '#/components/responses/Problem'} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} '503': description: '`service_unavailable` (`Retry-After`): the workspace is busy with other pushes. Nothing was applied and the response is not stored under the Idempotency-Key — retry the same request.' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} /v1/sync/pull: get: operationId: syncPull tags: [Sync] summary: Rows changed after a cursor (current state, tombstones included), oldest change first parameters: - {name: scope, in: query, required: true, schema: {type: string, format: uuid}} - {name: cursor, in: query, description: '`nextCursor` of the previous page; absent = from the beginning', schema: {type: string}} - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 1000, default: 500}} responses: '200': {description: A page of rows, content: {application/json: {schema: {$ref: '#/components/schemas/SyncPullResponse'}}}} '400': {description: '`invalid_cursor`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`device_limit_exceeded`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '404': {description: '`workspace_not_found` (not a member)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '410': {description: '`resync_required`: the cursor is older than purged tombstones — download a snapshot', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/sync/snapshot: get: operationId: syncSnapshot tags: [Sync] summary: Paginated live rows of a scope as of the first page (first sync, resync) description: The last page returns `cursor`, a pull cursor at `snapshotSeq`; rows changed while paging arrive through that pull. parameters: - {name: scope, in: query, required: true, schema: {type: string, format: uuid}} - {name: pageToken, in: query, schema: {type: string}} - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 1000, default: 500}} responses: '200': {description: A snapshot page, content: {application/json: {schema: {$ref: '#/components/schemas/SyncSnapshotResponse'}}}} '400': {description: '`invalid_cursor`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`device_limit_exceeded`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '404': {description: '`workspace_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/sync/scopes: get: operationId: syncScopes tags: [Sync] summary: Scopes the caller syncs, with their latest sequence numbers and the accepted schema versions responses: '200': description: Scopes content: application/json: schema: type: object properties: items: {type: array, items: {$ref: '#/components/schemas/SyncScope'}} schemaVersion: {type: integer} minSchemaVersion: {type: integer} serverTime: {type: string, format: date-time} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`device_limit_exceeded`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/ws: get: operationId: realtimeSocket tags: [Sync] summary: Realtime WebSocket (sync nudges) description: | Authenticate with `Authorization: Bearer ` on the upgrade (native), or — browsers — with the subprotocol list `Sec-WebSocket-Protocol: barzaman.v1, bearer.` (the server selects `barzaman.v1` and never echoes the token), or by sending `{"type":"auth","accessToken":"…"}` as the first frame within 10 s. A bad token in the handshake is refused before the upgrade. Server messages: `ready`, `sync.scopes`, `sync.nudge` `{scope, serverSeq}`, `auth_expired`, `session_revoked`, `pong`. Client messages (JSON text frames ≤ 64 KB): `auth`, `sync.refresh`, `ping`. Pings every 25 s. Close codes (SYNC_PROTOCOL §7): 4001 (server shutdown, reconnect), 4003 (binary frame), 4009 (frame too big or inbound budget of 256 KB burst / 16 KB/s exceeded), 4011 (server error), 4401 (auth), 4403 (revoked), 4408 (too many connections). security: [{bearerAuth: []}, {}] parameters: - name: Sec-WebSocket-Protocol in: header required: false description: '`barzaman.v1, bearer.` (browser authentication)' schema: {type: string} responses: '101': {description: Switching protocols} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`account_pending_deletion` or origin not allowed', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} # ───────────────────────────── Storage ───────────────────────────── /v1/attachments/upload-url: post: operationId: createAttachmentUpload tags: [Storage] summary: Start (or resume) a signed, resumable upload description: | Propose `id` = the id of the `attachment` sync row. Calling again with the same `id`, workspace, size and SHA-256 resumes (fresh URL, current `receivedBytes`) — use a new Idempotency-Key for that. Limits: `storage.maxFileBytes` per file and `storage.bytes` per uploader (pending uploads count), using the more generous of the uploader's and the workspace owners' plans. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: {application/json: {schema: {$ref: '#/components/schemas/AttachmentUploadRequest'}}} responses: '201': {description: Upload session, content: {application/json: {schema: {$ref: '#/components/schemas/AttachmentUploadSession'}}}} '200': {description: Already complete (no upload URL), content: {application/json: {schema: {$ref: '#/components/schemas/AttachmentUploadSession'}}}} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`forbidden` (viewer/commenter) or `limit_exceeded` (`feature`, `limit`, `used`)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '404': {description: '`workspace_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`attachment_id_taken`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {$ref: '#/components/responses/Validation'} /v1/attachments/{id}/content: parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} - {name: exp, in: query, required: true, description: Signed URL expiry (Unix seconds), schema: {type: integer}} - {name: sig, in: query, required: true, description: "HMAC-SHA256 signature over method, path, expiry and signed parameters", schema: {type: string}} put: operationId: uploadAttachmentChunk tags: [Storage] summary: Append one chunk (signed URL from upload-url; no bearer token or Idempotency-Key) description: | Position from `Content-Range: bytes a-b/total`, or `?offset=a` with `Content-Length`, or neither (whole file). Every chunk but the last ≥ `minChunkBytes` (5 MB); each ≤ `maxChunkBytes` (64 MB). A chunk overlapping bytes already received is trimmed (safe retry); a gap answers `409 upload_offset_mismatch` with `receivedBytes`. security: [{}] parameters: - {name: offset, in: query, schema: {type: integer, minimum: 0}} - {name: Content-Range, in: header, schema: {type: string, examples: ['bytes 0-5242879/12582912']}} requestBody: required: true content: {application/octet-stream: {schema: {type: string, format: binary}}} responses: '200': {description: Progress, content: {application/json: {schema: {$ref: '#/components/schemas/UploadProgress'}}}} '400': {description: '`range_invalid`, `chunk_too_small`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '403': {description: '`signature_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '404': {description: '`attachment_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`upload_offset_mismatch` (`receivedBytes`), `upload_in_progress`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '410': {description: '`url_expired` — request a new session', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '411': {description: '`length_required`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '413': {$ref: '#/components/responses/Problem'} get: operationId: downloadAttachment tags: [Storage] summary: The file (signed URL from download-url), with single-range support description: 'Supports `Range`, `If-Range`, `If-None-Match` (ETag = "sha256"). Active content (HTML, SVG, XML, scripts) is served as `application/octet-stream` and always as an attachment.' security: [{}] parameters: - {name: disp, in: query, schema: {type: string, enum: [inline, attachment]}} - {name: Range, in: header, schema: {type: string, examples: ['bytes=0-1048575']}} responses: '200': {description: Whole file, content: {application/octet-stream: {schema: {type: string, format: binary}}}} '206': {description: Partial content (`Content-Range`), content: {application/octet-stream: {schema: {type: string, format: binary}}}} '304': {description: Not modified} '403': {description: '`signature_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '404': {description: '`attachment_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '410': {description: '`url_expired`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '416': {description: '`range_not_satisfiable` (`Content-Range: bytes */size`)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} head: operationId: headAttachment tags: [Storage] summary: The headers GET would send (real Content-Length / Content-Range), without the body security: [{}] parameters: - {name: disp, in: query, schema: {type: string, enum: [inline, attachment]}} - {name: Range, in: header, schema: {type: string}} responses: '200': {description: Whole-file headers} '206': {description: Partial-content headers} '304': {description: Not modified} '403': {description: '`signature_invalid`'} '404': {description: '`attachment_not_found`'} '410': {description: '`url_expired`'} '416': {description: '`range_not_satisfiable`'} /v1/attachments/{id}/complete: post: operationId: completeAttachmentUpload tags: [Storage] summary: Verify size and SHA-256 and publish the file parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} - {$ref: '#/components/parameters/IdempotencyKey'} responses: '200': {description: Completed (idempotent), content: {application/json: {schema: {$ref: '#/components/schemas/Attachment'}}}} '401': {$ref: '#/components/responses/Unauthorized'} '404': {description: '`attachment_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`upload_incomplete` (`receivedBytes`, `size`), `upload_in_progress`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {description: '`checksum_mismatch` — the upload restarts from byte 0', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/attachments/{id}: parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}] get: operationId: getAttachment tags: [Storage] summary: Attachment metadata (members of its workspace) responses: '200': {description: Attachment, content: {application/json: {schema: {$ref: '#/components/schemas/Attachment'}}}} '401': {$ref: '#/components/responses/Unauthorized'} '404': {description: '`attachment_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} delete: operationId: deleteAttachment tags: [Storage] summary: Delete (the file is removed after the 30-day trash window) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] responses: '204': {description: Deleted} '401': {$ref: '#/components/responses/Unauthorized'} '403': {$ref: '#/components/responses/Forbidden'} '404': {description: '`attachment_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/attachments/{id}/download-url: get: operationId: getAttachmentDownloadUrl tags: [Storage] summary: A signed download URL (15 minutes) parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} - {name: disposition, in: query, schema: {type: string, enum: [inline, attachment], default: attachment}} responses: '200': {description: Signed URL, content: {application/json: {schema: {$ref: '#/components/schemas/AttachmentDownload'}}}} '401': {$ref: '#/components/responses/Unauthorized'} '404': {description: '`attachment_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`upload_incomplete`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/exports/{id}/content: get: operationId: downloadExport tags: [Storage] summary: An export archive (signed URL from GET /v1/me/export/{id}, 1 hour), with Range description: 'ZIP: manifest.json, account.json, workspaces.json, data/.jsonl, attachments.jsonl, attachments// (docs/sync/SYNC_PROTOCOL.md §11).' security: [{}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} - {name: exp, in: query, required: true, schema: {type: integer}} - {name: sig, in: query, required: true, schema: {type: string}} - {name: Range, in: header, schema: {type: string}} responses: '200': {description: The archive, content: {application/zip: {schema: {type: string, format: binary}}}} '206': {description: Partial content, content: {application/zip: {schema: {type: string, format: binary}}}} '403': {description: '`signature_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '404': {$ref: '#/components/responses/NotFound'} '410': {description: '`url_expired`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} head: operationId: headExport tags: [Storage] summary: The headers GET would send (real Content-Length / Content-Range), without the body security: [{}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} - {name: exp, in: query, required: true, schema: {type: integer}} - {name: sig, in: query, required: true, schema: {type: string}} - {name: Range, in: header, schema: {type: string}} responses: '200': {description: Whole-archive headers} '206': {description: Partial-content headers} '403': {description: '`signature_invalid`'} '404': {description: Not found} '410': {description: '`url_expired`'} # ───────────────────────────── Config ───────────────────────────── /v1/config/remote: get: operationId: getRemoteConfig tags: [Config] summary: Versions, feature flags, kill switches and announcements for one client description: Cacheable 5 minutes (`Cache-Control public`); send `If-None-Match` to get 304. Never blocks offline use of local data. security: [{}] parameters: - {name: platform, in: query, required: true, schema: {type: string, enum: [android, ios, web]}} - {name: flavor, in: query, schema: {type: string, pattern: '^[a-z0-9_-]{1,30}$', examples: [direct, bazaar, myket, play, appstore, pwa-ir, pwa-global]}} - {name: version, in: query, required: true, description: 'App version, e.g. 1.4.2 or 1.4.2+87 (encode + as %2B)', schema: {type: string}} - {name: installId, in: query, description: Stable random install id for percentage rollouts, schema: {type: string, pattern: '^[A-Za-z0-9._:\-]{8,128}$'}} - {name: If-None-Match, in: header, schema: {type: string}} responses: '200': {description: Remote config, headers: {ETag: {schema: {type: string}}}, content: {application/json: {schema: {$ref: '#/components/schemas/RemoteConfig'}}}} '304': {description: Not modified} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/announcements: get: operationId: listAnnouncements tags: [Config] summary: Active announcements for the caller's plan and platform (ticket 1026) description: 'Optional bearer token: a signed-in caller also gets the announcements targeted at their plan; a guest counts as `free`. Not cacheable (`private, no-store`). Plan-targeted announcements never appear in `/v1/config/remote`.' security: [{}, {bearerAuth: []}] parameters: - {name: platform, in: query, schema: {type: string, enum: [android, ios, web], default: android}} - {name: flavor, in: query, schema: {type: string, pattern: '^[a-z0-9_-]{1,30}$'}} - {name: version, in: query, description: 'App version (version-targeted rows skip a client without one)', schema: {type: string}} responses: '200': description: Announcements, newest first (at most 50) content: application/json: schema: type: object properties: plan: {type: string, enum: [free, plus, pro, business]} items: {type: array, items: {$ref: '#/components/schemas/Announcement'}} '401': {$ref: '#/components/responses/Unauthorized'} '422': {$ref: '#/components/responses/Validation'} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/config/holidays: get: operationId: getHolidays tags: [Config] summary: Holidays of a country for a Gregorian year or a date range (≤ 400 days) description: For a Jalali or Hijri year the app converts the year to its Gregorian range with packages/core. Cacheable 1 hour. security: [{}] parameters: - {name: country, in: query, required: true, schema: {type: string, pattern: '^[A-Za-z]{2}$', examples: [IR, AF, IQ, SA, AE]}} - {name: year, in: query, schema: {type: integer, minimum: 1900, maximum: 2200}} - {name: from, in: query, schema: {type: string, format: date}} - {name: to, in: query, schema: {type: string, format: date}} - {name: If-None-Match, in: header, schema: {type: string}} responses: '200': {description: Holidays, headers: {ETag: {schema: {type: string}}}, content: {application/json: {schema: {$ref: '#/components/schemas/HolidayList'}}}} '304': {description: Not modified} '422': {$ref: '#/components/responses/Validation'} /v1/app/latest: get: operationId: getLatestRelease tags: [Config] summary: The newest published release of a direct-download flavor, signed with Ed25519 description: | `signature` = base64url(Ed25519(UTF-8(canonical JSON of the object without `signature`, `keyId`, `signatureAlgorithm`))) — keys sorted, no whitespace (the algorithm of core's EntitlementToken). The app verifies it with its pinned public key, then the download's size and SHA-256, before installing. security: [{}] parameters: - {name: flavor, in: query, required: true, schema: {type: string, pattern: '^[a-z0-9_-]{1,30}$', examples: [direct]}} - {name: channel, in: query, schema: {type: string, enum: [stable, beta], default: stable}} responses: '200': {description: Signed release manifest, content: {application/json: {schema: {$ref: '#/components/schemas/AppRelease'}}}} '304': {description: Not modified} '404': {description: '`release_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {$ref: '#/components/responses/Validation'} /v1/config/pricing: get: operationId: getPricing tags: [Config] summary: Plans and prices for a region and flavor (billing catalog passthrough; plan matrix without prices when billing is absent) security: [{}] parameters: - {name: region, in: query, schema: {type: string, enum: [IR, GLOBAL]}} - {name: flavor, in: query, schema: {type: string, pattern: '^[a-z0-9_-]{1,30}$'}} responses: '200': {description: Pricing, content: {application/json: {schema: {$ref: '#/components/schemas/Pricing'}}}} '304': {description: Not modified} '422': {$ref: '#/components/responses/Validation'} # ───────────────────────────── Billing ───────────────────────────── /v1/billing/catalog: get: operationId: getBillingCatalog tags: [Billing] summary: Plans with their prices (Toman, paid through Bale), honest feature lists and default limits description: | Release 1.1: `currency` is `IRT`; every plan has `prices: [{period, amountToman, amountRial}]` (owner prices, editable in the admin console; Business has none and a `contact`), `features` (the plan's feature-line ids from packages/core `PlanFeatures`, in display order), `inherits` and `featureKeys`; `paymentsEnabled` tells whether Bale checkout works. The 1.0 members (`id`, `name`, `description`, `highlights`, `limits`, `purchasable`, `redeemAvailable`, `trial`) are kept for 1.0 apps, which ignore prices without an `id`. Cacheable for 1 minute. security: [{}] parameters: - {name: region, in: query, schema: {type: string, enum: [IR, GLOBAL]}, description: Defaults to the deployment region} - {name: flavor, in: query, schema: {$ref: '#/components/schemas/Flavor'}} responses: '200': {description: Catalog, content: {application/json: {schema: {$ref: '#/components/schemas/BillingCatalog'}}}} '422': {$ref: '#/components/responses/Validation'} /v1/billing/bale/checkout: post: operationId: startBaleCheckout tags: [Billing] summary: Create an order and open its Bale invoice (pay in the Bale messenger) description: | Creates an order for the plan and period (amount in Rial = Toman × 10, paid for 1 hour; a fresh unpaid order of the same plan/period/price is returned again). The invoice is a Bale `sendInvoice` message: when the account has a known Bale chat it is sent there at once and `invoiceUrl` is the bot chat (`https://ble.ir/barzamanbot`); otherwise (or when Bale refuses, e.g. the bot is blocked) `invoiceUrl` is a one-time pay link `https://ble.ir/barzamanbot?start=pay_<24 chars>` — the bot sends the invoice to the chat that opens it. The app just opens `invoiceUrl`. Paying stacks: the new period starts when the account's current paid (or rewarded) time of the same or a higher plan ends. Poll `GET /v1/billing/orders/{orderId}`, then refresh `GET /v1/billing/entitlements`. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [plan, period], properties: {plan: {type: string, enum: [plus, pro]}, period: {type: string, enum: [month, year]}}}}}} responses: '201': description: Order content: application/json: schema: type: object required: [orderId, invoiceUrl, amountToman, expiresAt] properties: orderId: {type: string, format: uuid} invoiceUrl: {type: string, format: uri} amountToman: {type: integer} amountRial: {type: integer} plan: {type: string, enum: [plus, pro]} period: {type: string, enum: [month, year]} status: {const: pending} expiresAt: {type: string, format: date-time} '409': {description: '`price_unavailable`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {$ref: '#/components/responses/Validation'} '503': {description: '`provider_not_configured` (Bale tokens not set)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/billing/zibal/checkout: post: operationId: startZibalCheckout tags: [Billing] summary: Create an order and a Zibal card-gateway payment (the payment method of the apps) description: | `product` is `plus`, `pro` or `storage_100gb` (+100 GB for one month; `period` must be `month`). The Toman price is computed by the server and locked on the order (Rial = Toman × 10). The app opens `paymentUrl` (browser; the PWA in the same tab) and polls `GET /v1/billing/orders/{orderId}`. After paying, Zibal returns the browser to `GET /v1/billing/zibal/callback`, which verifies the payment server-side and redirects to `/billing/return?order=&status=paid|failed|pending`. Plan periods stack like Bale orders; add-on periods follow each other. Store flavors (bazaar, myket, play, appstore) get `403 checkout_not_allowed`. A fresh unpaid order of the same product/period/price is returned again. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [product], properties: {product: {type: string, enum: [plus, pro, storage_100gb, sms_50, sms_200, voice_100, voice_500, voice_1000, voice_10000, voice_custom]}, uses: {type: integer, minimum: 1, maximum: 100000, description: 'voice_custom only (required): uses to buy; price = unit price × uses'}, period: {type: string, enum: [month, year], default: month}, returnTo: {type: string, enum: [app, web], default: app}}}}}} responses: '201': description: Order content: application/json: schema: type: object required: [orderId, paymentUrl, amountToman, expiresAt] properties: orderId: {type: string, format: uuid} paymentUrl: {type: string, format: uri} amountToman: {type: integer} amountRial: {type: integer} product: {type: string, enum: [plus, pro, storage_100gb, sms_50, sms_200, voice_100, voice_500, voice_1000, voice_10000, voice_custom]} plan: {type: string, enum: [plus, pro, storage]} period: {type: string, enum: [month, year]} status: {const: pending} expiresAt: {type: string, format: date-time} '403': {description: '`checkout_not_allowed` (store flavor)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`price_unavailable`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {$ref: '#/components/responses/Validation'} '502': {description: '`provider_error` (Zibal refused or unreachable)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '503': {description: '`provider_not_configured` (ZIBAL_MERCHANT not set)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/billing/zibal/callback: get: operationId: zibalCallback tags: [Billing] summary: Zibal's return URL (browser redirect; parameters are never trusted on their own) security: [] parameters: - {name: success, in: query, schema: {type: string}} - {name: trackId, in: query, schema: {type: string}} - {name: orderId, in: query, schema: {type: string}} - {name: status, in: query, schema: {type: string}} responses: '303': {description: 'Redirect to `/billing/return?order=&status=`'} /v1/billing/storage: get: operationId: getStorageUsage tags: [Billing] summary: The caller's storage use against the plan's total plus storage add-ons responses: '200': description: Usage content: application/json: schema: type: object properties: usedBytes: {type: integer} limitBytes: {type: integer, description: '-1 = unlimited'} planLimitBytes: {type: integer} addonBytes: {type: integer} addonEndsAt: {type: [string, 'null'], format: date-time} overLimit: {type: boolean, description: 'Files stay readable; new uploads are refused'} /v1/billing/orders/{orderId}: get: operationId: getBillingOrder tags: [Billing] summary: Status of one of the caller's Bale orders parameters: [{name: orderId, in: path, required: true, schema: {type: string, format: uuid}}] responses: '200': description: Order content: application/json: schema: type: object required: [orderId, status, plan, period] properties: orderId: {type: string, format: uuid} status: {type: string, enum: [pending, paid, failed, expired]} plan: {type: string, enum: [plus, pro]} period: {type: string, enum: [month, year]} amountToman: {type: integer} createdAt: {type: string, format: date-time} expiresAt: {type: string, format: date-time} paidAt: {type: string, format: date-time} paidThrough: {type: string, format: date-time, description: End of the time this payment granted} '404': {$ref: '#/components/responses/NotFound'} /v1/billing/bale/link-code: post: operationId: createBaleLinkCode tags: [Billing] summary: One-time code (15 minutes) linking the caller's Bale chat (password reset, receipts, reminders) parameters: [{$ref: '#/components/parameters/IdempotencyKeyOptional'}] responses: '201': description: Code content: application/json: schema: type: object required: [code, botUrl, expiresAt] properties: code: {type: string, examples: [K7M2Q9XA]} botUrl: {type: string, format: uri, examples: ['https://ble.ir/barzamanbot?start=K7M2Q9XA']} botUsername: {type: string} expiresAt: {type: string, format: date-time} '503': {$ref: '#/components/responses/Unavailable'} /v1/billing/entitlements: get: operationId: getEntitlementToken tags: [Billing] summary: Signed entitlement token (offline plan proof) description: | `token` is a compact JWS — header `{alg: EdDSA, typ: entitlement+jwt, kid}` signed with the regional ENTITLEMENT key; claims `iss, sub, aud (barzaman-entitlements), jti, iat, exp, plan, limits, graceUntil, accountId, region` (NumericDate seconds). `exp` = iat + 7 days and `graceUntil` = iat + 30 days (IR) / 14 days (GLOBAL); both are capped at the paid-through date when the effective plan comes only from non-renewing sources (time packs, promo codes, staff comps). `signed` carries the same statement in the shape of core's `EntitlementToken` (snake_case, milliseconds) with `signature` = base64url Ed25519 over its canonical `signingPayload`, for `EntitlementVerifier` implementations. Apps pin the public key (`ENTITLEMENT_ED25519_PUBLIC_KEY`) and may check `kid` against `/v1/billing/entitlements/keys`. parameters: [] responses: '200': {description: Token, content: {application/json: {schema: {$ref: '#/components/schemas/EntitlementTokenResponse'}}}} '401': {$ref: '#/components/responses/Unauthorized'} '503': {$ref: '#/components/responses/Unavailable'} /v1/billing/entitlements/keys: get: operationId: getEntitlementKeys tags: [Billing] summary: Public key(s) that verify entitlement tokens (OKP Ed25519 JWKS) security: [{}] responses: '200': {description: JWKS, content: {application/json: {schema: {$ref: '#/components/schemas/Jwks'}}}} /v1/billing/subscriptions: get: operationId: getBillingStatus tags: [Billing] summary: Effective plan, its sources and the account's subscriptions responses: '200': {description: Status, content: {application/json: {schema: {$ref: '#/components/schemas/BillingStatus'}}}} '401': {$ref: '#/components/responses/Unauthorized'} /v1/billing/verify/{provider}: post: operationId: verifyPurchase tags: [Billing] summary: Verify a store purchase with the provider's server API and apply it description: | The server never trusts the client: the purchase is confirmed with Cafe Bazaar (Pardakht API), Myket (developer API), Google Play (purchases.subscriptionsv2 / products), the App Store (JWS + x5c chain to the pinned Apple Root CA G3), Stripe (Checkout Session) or Paddle (transaction). A purchase belongs to one account; set Play `obfuscatedAccountId` / StoreKit `appAccountToken` to the user id at purchase time. Play purchases are acknowledged. Idempotent by provider transaction id. parameters: - {name: provider, in: path, required: true, schema: {type: string, enum: [bazaar, myket, google_play, apple, stripe, paddle]}} - {$ref: '#/components/parameters/IdempotencyKey'} requestBody: required: true content: {application/json: {schema: {$ref: '#/components/schemas/StorePurchase'}}} responses: '200': {description: Applied, content: {application/json: {schema: {$ref: '#/components/schemas/VerifyResult'}}}} '401': {$ref: '#/components/responses/Unauthorized'} '409': {description: '`purchase_owned_by_another_account`, `purchase_pending`, `purchase_not_active` (extension `purchaseStatus`)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {description: '`unknown_product`, `purchase_invalid`, `validation_failed`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} '502': {description: '`provider_error`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '503': {$ref: '#/components/responses/Unavailable'} /v1/billing/restore: post: operationId: restorePurchases tags: [Billing] summary: Re-verify the store purchases the app holds and refresh the account's known subscriptions (at most 100 purchases per account per day; a refunded purchase stays revoked) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [provider] properties: provider: {type: string, enum: [bazaar, myket, google_play, apple, stripe, paddle]} purchases: {type: array, maxItems: 50, items: {$ref: '#/components/schemas/StorePurchase'}} responses: '200': description: Restored content: application/json: schema: type: object properties: restored: {type: integer} failures: {type: array, items: {type: object, properties: {index: {type: integer}, code: {type: string}}}} entitlements: {$ref: '#/components/schemas/EntitlementTokenResponse'} '401': {$ref: '#/components/responses/Unauthorized'} '503': {$ref: '#/components/responses/Unavailable'} /v1/billing/redeem: post: operationId: redeemPromoCode tags: [Billing] summary: Redeem a promo code (direct, pwa-ir, pwa-global, bazaar and myket builds only) description: The flavor is taken from the device recorded at sign-in (`flavor` in the body is used only when none was recorded). 10 attempts per hour per user. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: {application/json: {schema: {type: object, required: [code], properties: {code: {type: string, maxLength: 64}, flavor: {$ref: '#/components/schemas/Flavor'}}}}} responses: '200': description: Redeemed content: application/json: schema: type: object properties: redeemed: {type: object, properties: {plan: {type: string}, durationDays: {type: integer}, endsAt: {type: string, format: date-time}}} entitlements: {$ref: '#/components/schemas/EntitlementTokenResponse'} '403': {description: '`redeem_not_allowed`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`promo_already_redeemed`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '410': {description: '`promo_expired`, `promo_exhausted`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {description: '`promo_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/billing/trial: post: operationId: startTrial tags: [Billing] summary: Start the server-side trial (BILLING_TRIAL_DAYS; once per account, never after a purchase) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] responses: '201': {description: Started, content: {application/json: {schema: {type: object, properties: {entitlements: {$ref: '#/components/schemas/EntitlementTokenResponse'}}}}}} '409': {description: '`trial_unavailable`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/billing/web/checkout: post: operationId: startWebCheckout tags: [Billing] summary: Start a web checkout (Zarinpal for direct/pwa-ir; Stripe or Paddle for pwa-global) description: | Returns the provider page to open. Zarinpal returns to `GET /v1/billing/zarinpal/callback`, which verifies the payment and redirects to `returnUrl?attempt=…&status=succeeded|canceled|failed|pending`. `returnUrl` must be on the PWA or website origin or use the `barzaman://billing/…` deep link (default `{PUBLIC_APP_URL}/billing/return`). Poll `GET /v1/billing/web/checkout/{id}` for the outcome. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: {application/json: {schema: {type: object, required: [priceId], properties: {priceId: {type: string, format: uuid}, returnUrl: {type: string, maxLength: 500}, flavor: {$ref: '#/components/schemas/Flavor'}}}}} responses: '201': {description: Started, content: {application/json: {schema: {$ref: '#/components/schemas/CheckoutStarted'}}}} '403': {description: '`checkout_not_allowed` (store builds must use their store)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`price_unavailable`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {$ref: '#/components/responses/Validation'} '502': {description: '`provider_error`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '503': {$ref: '#/components/responses/Unavailable'} /v1/billing/web/checkout/{id}: get: operationId: getWebCheckout tags: [Billing] summary: Outcome of a web checkout parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}] responses: '200': {description: Status, content: {application/json: {schema: {$ref: '#/components/schemas/CheckoutStatus'}}}} '404': {description: '`checkout_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/billing/zarinpal/callback: get: operationId: zarinpalCallback tags: [Billing] summary: Zarinpal return URL — verifies the payment (exactly once) and redirects the payer security: [{}] parameters: - {name: Authority, in: query, required: true, schema: {type: string, maxLength: 64}} - {name: Status, in: query, required: true, description: 'Unauthenticated hint only: the payment is always verified with Zarinpal; NOK merely labels an unpaid attempt canceled instead of failed', schema: {type: string, enum: [OK, NOK]}} responses: '303': description: Redirect to the attempt's return URL with `attempt` and `status` (succeeded, canceled, failed, pending) headers: {Location: {schema: {type: string}}} '503': {$ref: '#/components/responses/Unavailable'} /v1/billing/invoices: get: operationId: listInvoices tags: [Billing] summary: The account's invoices, newest first parameters: [{$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}] responses: '200': description: Page content: application/json: schema: {type: object, properties: {items: {type: array, items: {$ref: '#/components/schemas/Invoice'}}, nextCursor: {type: [string, 'null']}}} '401': {$ref: '#/components/responses/Unauthorized'} # ───────────────────────────── Webhooks ───────────────────────────── /v1/webhooks/apple: post: operationId: appleNotification tags: [Webhooks] summary: App Store Server Notifications V2 (`signedPayload` verified against the pinned Apple root) security: [{}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [signedPayload], properties: {signedPayload: {type: string}}}}}} responses: '200': {description: Stored (processed or queued for retry), content: {application/json: {schema: {type: object, properties: {received: {const: true}}}}}} '401': {description: '`webhook_signature_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '503': {$ref: '#/components/responses/Unavailable'} /v1/webhooks/google: post: operationId: googlePlayRtdn tags: [Webhooks] summary: Google Play real-time developer notifications (Pub/Sub push; OIDC bearer or `?token=`) description: The notification only triggers a re-read of the purchase from the Play Developer API. security: [{}] parameters: [{name: token, in: query, schema: {type: string}, description: GOOGLE_PLAY_RTDN_TOKEN when OIDC push auth is not used}] requestBody: {required: true, content: {application/json: {schema: {type: object, properties: {message: {type: object, properties: {data: {type: string, format: byte}, messageId: {type: string}}}, subscription: {type: string}}}}}} responses: '204': {description: Acknowledged} '401': {description: '`webhook_signature_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '503': {$ref: '#/components/responses/Unavailable'} /v1/webhooks/stripe: post: operationId: stripeWebhook tags: [Webhooks] summary: Stripe events (`Stripe-Signature` HMAC over the raw body, 5-minute tolerance) security: [{}] parameters: [{name: Stripe-Signature, in: header, required: true, schema: {type: string}}] requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}} responses: '200': {description: Stored, content: {application/json: {schema: {type: object, properties: {received: {const: true}}}}}} '401': {description: '`webhook_signature_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/webhooks/paddle: post: operationId: paddleWebhook tags: [Webhooks] summary: Paddle Billing events (`Paddle-Signature` HMAC over the raw body) security: [{}] parameters: [{name: Paddle-Signature, in: header, required: true, schema: {type: string}}] requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}} responses: '200': {description: Stored, content: {application/json: {schema: {type: object, properties: {received: {const: true}}}}}} '401': {description: '`webhook_signature_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} # ───────────────────────────── Push ───────────────────────────── /v1/push/vapid-public-key: get: operationId: getVapidPublicKey tags: [Push] summary: VAPID application server key (use as `applicationServerKey` in PushManager.subscribe) security: [{}] responses: '200': {description: Key, content: {application/json: {schema: {type: object, properties: {publicKey: {type: string, description: 'Uncompressed P-256 point, base64url'}}}}}} '503': {$ref: '#/components/responses/Unavailable'} /v1/push/webpush/subscribe: post: operationId: subscribeWebPush tags: [Push] summary: Register this browser's push subscription (one per device, at most 10 per account — the oldest are dropped; endpoints of the major push services only) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/WebPushSubscription'}}}} responses: '201': {description: Registered, content: {application/json: {schema: {type: object, properties: {id: {type: string, format: uuid}, deviceId: {type: string}}}}}} '422': {description: '`push_endpoint_not_allowed`, `validation_failed`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '503': {$ref: '#/components/responses/Unavailable'} delete: operationId: unsubscribeWebPush tags: [Push] summary: Remove a subscription by endpoint or device id parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {required: true, content: {application/json: {schema: {type: object, properties: {endpoint: {type: string}, deviceId: {type: string}}}}}} responses: '204': {description: Removed} '404': {description: '`push_subscription_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/push/webpush/subscriptions: get: operationId: listWebPushSubscriptions tags: [Push] summary: The account's browser subscriptions (endpoints are never returned) responses: '200': {description: List, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {type: object, additionalProperties: true}}}}}}} /v1/push/webpush/test: post: operationId: testWebPush tags: [Push] summary: Send a test notification to the caller's browsers description: | Notification payloads (after RFC 8291 decryption in the service worker) are JSON: `{v: 1, type: reminder|test, title, body, tag, lang, dir, itemId, reminderId, occurrenceStart, fireAt, style, url}`. Remote reminders are sent by the worker every minute, exactly once per reminder occurrence and channel, honouring quiet hours and lock-screen privacy. parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] responses: '200': {description: Results per outcome, content: {application/json: {schema: {type: object, properties: {results: {type: object, additionalProperties: {type: integer}}}}}}} '404': {description: '`push_subscription_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/push/bots/link-code: post: operationId: createBotLinkCode tags: [Push] summary: One-time code (15 minutes) to link Telegram or Bale — send `/start ` to the bot parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [kind], properties: {kind: {type: string, enum: [telegram, bale]}}}}}} responses: '201': {description: Code, content: {application/json: {schema: {$ref: '#/components/schemas/BotLinkCode'}}}} '503': {$ref: '#/components/responses/Unavailable'} /v1/push/bots: get: operationId: listBotLinks tags: [Push] summary: Linked bot chats (remote reminders need the `reminders.remote` entitlement) responses: '200': {description: List, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {type: object, properties: {kind: {type: string}, username: {type: [string, 'null']}, active: {type: boolean}, linkedAt: {type: string, format: date-time}}}}}}}}} /v1/push/bots/{kind}: patch: operationId: updateBotPreferences tags: [Push] summary: Preferences of a linked chat — every reminder to the bot, morning digest time (HH:MM or null), active parameters: - {name: kind, in: path, required: true, schema: {type: string, enum: [telegram, bale]}} - {$ref: '#/components/parameters/IdempotencyKey'} requestBody: {required: true, content: {application/json: {schema: {type: object, properties: {reminders: {type: boolean}, active: {type: boolean}, digestTime: {type: [string, 'null'], pattern: '^([01][0-9]|2[0-3]):[0-5][0-9]$'}}}}}} responses: '200': {description: Links, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {$ref: '#/components/schemas/BotLink'}}}}}}} '404': {$ref: '#/components/responses/NotFound'} delete: operationId: unlinkBot tags: [Push] summary: Unlink a bot chat parameters: - {name: kind, in: path, required: true, schema: {type: string, enum: [telegram, bale]}} - {$ref: '#/components/parameters/IdempotencyKey'} responses: '204': {description: Unlinked} '404': {$ref: '#/components/responses/NotFound'} /v1/bots/{kind}/webhook: post: operationId: botWebhook tags: [Webhooks] summary: Telegram / Bale bot updates (secret in `X-Telegram-Bot-Api-Secret-Token`, or `?secret=` for Bale) security: [{}] parameters: - {name: kind, in: path, required: true, schema: {type: string, enum: [telegram, bale]}} - {name: X-Telegram-Bot-Api-Secret-Token, in: header, schema: {type: string}} - {name: secret, in: query, schema: {type: string}} requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}} responses: '200': {description: Accepted, content: {application/json: {schema: {type: object, properties: {ok: {const: true}}}}}} '401': {$ref: '#/components/responses/Unauthorized'} # ─────────────────────────── Bookings, calendar feeds, templates, activity ─────────────────────────── /v1/push/bots/rules: get: {operationId: listBotDeliveryRules, tags: [Push], summary: 'Per-type bot delivery rules, ids of sensitive types never sent to bots (health, medical, finance, lock-screen-private) and whether bot reminders are allowed (reminders.remote)', responses: {'200': {description: 'Rules: {rules, sensitiveTypeIds, remindersAllowed}'}}} /v1/push/bots/rules/{typeId}: put: {operationId: setBotDeliveryRule, tags: [Push], summary: 'Bot channels ({channels: [telegram, bale]}) for one item type (Pro: reminders.remote; sensitive types refused)', parameters: [{name: typeId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'200': {description: 'Rules'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/push/bots/{kind}/test: post: {operationId: sendBotTestMessage, tags: [Push], summary: 'Send a test message to a linked chat (5 per 10 minutes)', parameters: [{name: kind, in: path, required: true, schema: {type: string}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Sent'}, '404': {$ref: '#/components/responses/NotFound'}, '429': {$ref: '#/components/responses/TooManyRequests'}}} /v1/workspaces/{id}/activity: get: {operationId: listWorkspaceActivity, tags: [Workspaces], summary: 'Activity feed and comments of a shared workspace (members); query itemId, kinds (comma-separated), cursor, limit', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: itemId, in: query, schema: {type: string, format: uuid}}, {name: kinds, in: query, schema: {type: string}}, {name: cursor, in: query, schema: {type: string}}, {name: limit, in: query, schema: {type: integer}}], responses: {'200': {description: 'Entries'}, '404': {$ref: '#/components/responses/NotFound'}}} post: {operationId: postWorkspaceActivity, tags: [Workspaces], summary: 'Post {kind, itemId?, subjectId?, body?, data?}: comment needs commenter+, item / check-in / chore / session / swap kinds need editor+; data at most 4 KB; 120 per 10 minutes per user', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'201': {description: 'Entry'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}, '429': {$ref: '#/components/responses/TooManyRequests'}}} /v1/workspaces/{id}/activity/{entryId}: patch: {operationId: editWorkspaceComment, tags: [Workspaces], summary: 'Edit an own comment', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: entryId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'200': {description: 'Entry'}, '403': {$ref: '#/components/responses/Forbidden'}, '404': {$ref: '#/components/responses/NotFound'}}} delete: {operationId: deleteWorkspaceActivity, tags: [Workspaces], summary: 'Delete an entry (author or owner; server membership events cannot be deleted)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: entryId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Deleted'}, '403': {$ref: '#/components/responses/Forbidden'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/workspaces/{id}/summary: get: {operationId: workspaceSummary, tags: [Workspaces], summary: 'Per-member totals for the last N days (check-ins, study minutes, tests, chores, points, sessions, comments, last check-in)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: days, in: query, schema: {type: integer, default: 7}}], responses: {'200': {description: 'Summary'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/workspaces-overview: get: {operationId: workspacesOverview, tags: [Workspaces], summary: 'Every space the caller owns of a kind (e.g. clients) with its summary (counselor dashboard)', parameters: [{name: kind, in: query, schema: {type: string}}, {name: days, in: query, schema: {type: integer, default: 7}}], responses: {'200': {description: 'Spaces'}}} /v1/calendar/feeds: get: {operationId: listCalendarFeeds, tags: [Calendar], summary: 'ICS subscribe URLs of the account', responses: {'200': {description: 'Feeds'}}} post: {operationId: createCalendarFeed, tags: [Calendar], summary: 'Create a private ICS subscribe URL (Plus+: calendar.feeds; the bzc_ token is shown once, only its HMAC is stored; optional busy-only mode)', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'201': {description: 'Feed'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/calendar/feeds/{id}: delete: {operationId: revokeCalendarFeed, tags: [Calendar], summary: 'Revoke a feed (its URL returns 404 afterwards)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Revoked'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/calendar/fetch-ics: post: {operationId: fetchCalendarIcs, tags: [Calendar], summary: 'Fetch a public iCalendar URL (https or webcal) for a calendar subscription in the app (Plus+: calendar.feeds); public hosts only (SSRF guard on every redirect), at most 4 MB; nothing is stored', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [url], properties: {url: {type: string, maxLength: 500}}}}}}, responses: {'200': {description: 'The calendar text as {text}'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/calendar/subscriptions: get: {operationId: listCalendarSubscriptions, tags: [Calendar], summary: 'Calendars the account subscribed to by address (ticket 1066); the address itself is never returned', responses: {'200': {description: 'Subscriptions'}}} post: {operationId: createCalendarSubscription, tags: [Calendar], summary: 'Subscribe to an iCalendar address (Plus+: calendar.feeds). The server fetches it (SSRF guard, 4 MB) and writes its events into the personal workspace through sync with deterministic ids; when the server cannot reach it, the calling device may send the calendar text and becomes its only fetcher', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [url, name], properties: {url: {type: string, maxLength: 500}, name: {type: string, maxLength: 80}, color: {type: integer}, typeKey: {type: string}, text: {type: string}}}}}}, responses: {'201': {description: 'Subscription'}, '403': {$ref: '#/components/responses/Forbidden'}, '409': {description: 'Already subscribed'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/calendar/subscriptions/{id}/refresh: post: {operationId: refreshCalendarSubscription, tags: [Calendar], summary: 'Refresh now (server fetcher), or upload the calendar text from the designated fetcher device', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Subscription'}, '404': {$ref: '#/components/responses/NotFound'}, '409': {description: 'Another device fetches this calendar'}}} /v1/calendar/subscriptions/{id}: delete: {operationId: deleteCalendarSubscription, tags: [Calendar], summary: 'Unsubscribe; its events are deleted on every device through sync', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Removed'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/cal/{token}: get: {operationId: calendarFeedIcs, tags: [Calendar], summary: 'Public iCalendar feed ({token} is bzc_ + 32 characters, optionally with .ics): 30 days back to 180 days ahead, expanded occurrences, VALARMs from reminders; sensitive types (health, finance...) never included', security: [{}], parameters: [{name: token, in: path, required: true, schema: {type: string}}], responses: {'200': {description: iCalendar, content: {text/calendar: {schema: {type: string}}}}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/booking/page: get: {operationId: getBookingPage, tags: [Booking], summary: 'The professional''s booking page, weekly hours and services', responses: {'200': {description: 'Page'}}} put: {operationId: putBookingPage, tags: [Booking], summary: 'Create or update the booking page (Pro+: booking.page)', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'200': {description: 'Page'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/booking/handle: get: {operationId: checkBookingHandle, tags: [Booking], summary: 'Whether a public handle is available', parameters: [{name: handle, in: query, required: true, schema: {type: string}}], responses: {'200': {description: 'Availability'}}} /v1/booking/services: post: {operationId: createBookingService, tags: [Booking], summary: 'Add a service (at most 20)', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'201': {description: 'Service'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/booking/services/{id}: patch: {operationId: updateBookingService, tags: [Booking], summary: 'Update a service', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'200': {description: 'Service'}, '404': {$ref: '#/components/responses/NotFound'}}} delete: {operationId: deleteBookingService, tags: [Booking], summary: 'Delete a service', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Deleted'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/booking/bookings: get: {operationId: listBookings, tags: [Booking], summary: 'Bookings received', responses: {'200': {description: 'Bookings'}}} /v1/booking/bookings/{id}/{action}: post: {operationId: bookingAction, tags: [Booking], summary: 'Confirm, decline or cancel a booking (decline and cancel delete its sys.appointment item)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: action, in: path, required: true, schema: {type: string, enum: [confirm, decline, cancel]}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Booking'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/public/booking/manage/{code}: get: {operationId: publicManageBooking, tags: [Booking], summary: 'A client''s booking by its 12-character manage code', security: [{}], parameters: [{name: code, in: path, required: true, schema: {type: string}}], responses: {'200': {description: 'Booking'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/public/booking/manage/{code}/cancel: post: {operationId: publicCancelBooking, tags: [Booking], summary: 'Client cancels with the manage code', security: [{}], parameters: [{name: code, in: path, required: true, schema: {type: string}}], responses: {'200': {description: 'Cancelled'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/public/booking/{handle}: get: {operationId: publicBookingPage, tags: [Booking], summary: 'Public booking page', security: [{}], parameters: [{name: handle, in: path, required: true, schema: {type: string}}], responses: {'200': {description: 'Page'}, '404': {$ref: '#/components/responses/NotFound'}}} post: {operationId: publicCreateBooking, tags: [Booking], summary: 'Book a slot (honeypot website, startedAt at least 3 s old, 6 per hour per IP, at most 3 upcoming per phone, overlap re-checked under a row lock); returns the manage code', security: [{}], parameters: [{name: handle, in: path, required: true, schema: {type: string}}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'201': {description: 'Booking'}, '409': {description: Slot taken}, '422': {$ref: '#/components/responses/Validation'}, '429': {$ref: '#/components/responses/TooManyRequests'}}} /v1/public/booking/{handle}/slots: get: {operationId: publicBookingSlots, tags: [Booking], summary: 'Free slots (weekly hours minus breaks, days off, official holidays, notice, horizon, buffers and the professional''s own timed items)', security: [{}], parameters: [{name: handle, in: path, required: true, schema: {type: string}}], responses: {'200': {description: 'Slots'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/templates/shared: get: {operationId: listSharedTemplates, tags: [Templates], summary: 'Templates the account published', responses: {'200': {description: 'Templates'}}} post: {operationId: publishTemplate, tags: [Templates], summary: 'Publish {name, template} (Pro+: templates.publish; ids, people, status and absolute dates are removed; 500 nodes, 6 levels, 50 per user)', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'201': {description: 'Published (8-character code)'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/templates/shared/{code}: delete: {operationId: revokeSharedTemplate, tags: [Templates], summary: 'Unpublish', parameters: [{name: code, in: path, required: true, schema: {type: string}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Unpublished'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/templates/shared/{code}/imported: post: {operationId: countTemplateImport, tags: [Templates], summary: 'Record an import', parameters: [{name: code, in: path, required: true, schema: {type: string}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Counted'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/public/templates/{code}: get: {operationId: publicSharedTemplate, tags: [Templates], summary: 'Preview a shared template (no sign-in)', security: [{}], parameters: [{name: code, in: path, required: true, schema: {type: string}}], responses: {'200': {description: 'Template'}, '404': {$ref: '#/components/responses/NotFound'}}} # ─────────────── Server events, SMS reminders, shift swaps (1.3.12, agent D) ─────────────── /v1/events: get: {operationId: listServerEvents, tags: [Events], summary: 'Server events of the account after a cursor (after=0 → last 48 h only); docs/market/integration/server-events.md', parameters: [{name: after, in: query, schema: {type: integer, minimum: 0}}, {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 100}}], responses: {'200': {description: '{items, cursor, more}'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/events/seen: post: {operationId: markServerEventsSeen, tags: [Events], summary: 'Mark events up to {upTo} seen', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Marked'}}} /v1/reminders/sms: get: {operationId: smsReminderStatus, tags: [Reminders], summary: 'SMS reminder quota (reminders.smsCredits), credits, verified phone, limits and packs', responses: {'200': {description: 'Status'}}} put: {operationId: updateSmsReminders, tags: [Reminders], summary: 'Set {enabled?, dailyLimit? 1-50, quietStart?, quietEnd?} (minutes of day)', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Status'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/reminders/sms/history: get: {operationId: smsReminderHistory, tags: [Reminders], summary: 'Last 50 sends and credit movements', responses: {'200': {description: 'History'}}} /v1/shifts/swaps: get: {operationId: listShiftSwaps, tags: [Shifts], summary: 'Swap requests asked of me or mine (pending, and answered in the last 30 days)', parameters: [{name: workspaceId, in: query, schema: {type: string, format: uuid}}], responses: {'200': {description: 'List'}}} post: {operationId: requestShiftSwap, tags: [Shifts], summary: 'Ask a colleague (toUserId) or the whole rota space to take a duty (shifts.sharedRota)', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], responses: {'201': {description: 'Request'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/shifts/swaps/{id}/accept: post: {operationId: acceptShiftSwap, tags: [Shifts], summary: 'Take the duty', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Request'}, '409': {description: 'Already answered'}}} /v1/shifts/swaps/{id}/decline: post: {operationId: declineShiftSwap, tags: [Shifts], summary: 'Decline', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Request'}, '409': {description: 'Already answered'}}} /v1/shifts/swaps/{id}/cancel: post: {operationId: cancelShiftSwap, tags: [Shifts], summary: 'Withdraw my request', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Request'}, '409': {description: 'Already answered'}}} # ─────────────────────────── Item shares (1.3.14, ticket 1027) ─────────────────────────── /v1/item-shares: get: {operationId: listItemShares, tags: [ItemShares], summary: 'Shares I created (optionally of one itemId) with each recipient''s state: pending, accepted, done, declined', parameters: [{name: itemId, in: query, schema: {type: string, format: uuid}}], responses: {'200': {description: 'List'}}} post: {operationId: createItemShare, tags: [ItemShares], summary: 'Share one synced item {itemId, to (phone, e-mail or @username), permission view|edit, confirmSensitive?, locale?}. Needs sharing.level plus (403 limit_exceeded otherwise). Finance/health items → 409 share_sensitive_confirm {category} until confirmSensitive is true; vault items → 403 share_blocked_private. Unregistered phone/e-mail → invite by SMS (when ITEM_SHARE_SMS_ENABLED and the provider is configured) or SMTP e-mail, else delivery link; inviteLink/appLink are returned once. Re-sharing to the same person only updates the permission.', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [itemId, to], properties: {itemId: {type: string, format: uuid}, to: {type: string, maxLength: 320}, permission: {type: string, enum: [view, edit]}, confirmSensitive: {type: boolean}, locale: {type: string, enum: [fa, en, ar]}}}}}}, responses: {'201': {description: 'Share'}, '403': {$ref: '#/components/responses/Forbidden'}, '404': {$ref: '#/components/responses/NotFound'}, '409': {description: 'Sensitive item needs confirmation'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/item-shares/incoming: get: {operationId: listIncomingItemShares, tags: [ItemShares], summary: 'Shared with me (any plan). Pending invites sent to my verified phone or e-mail are attached to my account first.', responses: {'200': {description: 'List'}}} /v1/item-shares/claim: post: {operationId: claimItemShare, tags: [ItemShares], summary: 'Accept an invite link {token} after sign-up (30 days; single recipient)', requestBody: {required: true, content: {application/json: {schema: {type: object, required: [token], properties: {token: {type: string}}}}}}, responses: {'200': {description: 'Share'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/item-shares/{id}: get: {operationId: getItemShare, tags: [ItemShares], summary: 'The share with the live item (title, description, status, date/time) and comments (owner or recipient)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {description: 'Share'}, '404': {$ref: '#/components/responses/NotFound'}}} delete: {operationId: deleteItemShare, tags: [ItemShares], summary: 'Owner: stop sharing. Recipient: remove from my list (declines).', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'204': {description: 'Removed'}}} /v1/item-shares/{id}/accept: post: {operationId: acceptItemShare, tags: [ItemShares], summary: 'Accept (recipient; the owner gets item_share.accepted)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Share'}}} /v1/item-shares/{id}/decline: post: {operationId: declineItemShare, tags: [ItemShares], summary: 'Decline (recipient)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Share'}}} /v1/item-shares/{id}/done: post: {operationId: setItemShareDone, tags: [ItemShares], summary: 'Mark done {done: true|false} (owner or edit recipient; written to the owner''s item, source item_share; event item_share.done)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Share'}, '403': {description: 'share_view_only'}}} /v1/item-shares/{id}/comments: post: {operationId: commentItemShare, tags: [ItemShares], summary: 'Comment {body ≤ 1000} (owner or recipient; event item_share.comment)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'201': {description: 'Comment'}}} /admin/v1/orgs: get: {operationId: adminListOrgs, tags: [Admin], summary: 'Organisations (academies/schools) with seats and member counts; q = name substring (usersRead)', security: [{adminSession: []}], parameters: [{name: q, in: query, schema: {type: string}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/orgs/{id}: get: {operationId: adminGetOrg, tags: [Admin], summary: 'One organisation with members and classes (usersRead)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '404': {$ref: '#/components/responses/NotFound'}}} patch: {operationId: adminSetOrgSeats, tags: [Admin], summary: 'Set the seat count of an organisation (usersGrant; audited)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [seats], properties: {seats: {type: integer, minimum: 0, maximum: 100000}}}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}, '404': {$ref: '#/components/responses/NotFound'}}} /admin/v1/sms/usage: get: {operationId: adminSmsUsage, tags: [Admin], summary: 'SMS reminders by month, top senders, credits sold and granted (usersRead)', responses: {'200': {description: 'Usage'}}} /admin/v1/users/{id}/sms: get: {operationId: adminUserSms, tags: [Admin], summary: 'One account''s SMS quota, credits and sends (usersRead)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {description: 'Status'}}} /admin/v1/users/{id}/sms/credits: post: {operationId: adminGrantSmsCredits, tags: [Admin], summary: 'Grant {amount (±10000, not 0), note?} credits (usersGrant)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'201': {description: 'Status'}, '404': {$ref: '#/components/responses/NotFound'}}} # ─────────────────────────── Voice assistant (1.3.16) ─────────────────────────── /v1/assistant/voice/quota: get: {operationId: voiceQuota, tags: [Assistant], summary: 'Voice quick-add quota for the current period (Jalali month for calendar=jalali, else Gregorian; user time zone): {enabled, planAllowed, available, period, periodEnd, included, includedUsed, packTotal, packUsed, remaining, maxSeconds, maxBytes, packs[{product, uses, amount, currency IRT, perUse, bestValue}], custom{product voice_custom, unitPrice, min, max, active, currency}}. Packs are bought with POST /v1/billing/zibal/checkout {product: voice_100|voice_500|voice_1000|voice_10000} or {product: voice_custom, uses: N} (price = unitPrice × N, computed by the server)', responses: {'200': {description: 'Quota'}}} /v1/assistant/voice: post: {operationId: voiceQuickAdd, tags: [Assistant], summary: 'Raw audio body (audio/mp4|m4a|aac|wav|x-wav|mpeg|ogg|webm, ≤ 4 MiB, X-Audio-Duration-Ms ≤ 60000; X-Default-Date: today puts an undated item on today) → transcript (ASR relay) → item via the quick-add parser. Idempotency-Key required: a repeat returns the stored 201, 409 voice_in_progress while running. Failures are not charged. Uses: plan quickAdd.voiceMonthly first, then packs of the period.', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}, {name: X-Audio-Duration-Ms, in: header, schema: {type: integer, minimum: 0}}, {name: X-Default-Date, in: header, schema: {type: string, enum: [today]}}], requestBody: {required: true, content: {audio/*: {schema: {type: string, format: binary}}}}, responses: {'201': {description: '{requestId, transcript, items[{id, title, typeKey, start, allDay, reminders}], quota}'}, '403': {description: 'plan_required (feature quickAdd.voice)'}, '409': {description: 'voice_in_progress'}, '413': {description: 'audio_too_large'}, '422': {description: 'audio_too_long | audio_invalid | transcript_empty | item_refused'}, '429': {description: 'usage_limit_reached (quota)'}, '503': {description: 'asr_unavailable'}, '504': {description: 'asr_timeout'}}} /v1/assistant/voice/{id}/undo: post: {operationId: voiceUndo, tags: [Assistant], summary: 'Delete the items a voice request created (within 24 h; uses are not refunded) → {undone}', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {description: '{undone}'}, '404': {$ref: '#/components/responses/NotFound'}, '409': {description: 'undo_expired'}}} /admin/v1/assistant/voice/stats: get: {operationId: adminVoiceStats, tags: [Admin], summary: 'Voice requests, failures, seconds, by day, top users, error codes, pack uses (dashboard). No transcripts.', parameters: [{name: days, in: query, schema: {type: integer, minimum: 1, maximum: 365}}], responses: {'200': {description: 'Stats'}}} /admin/v1/assistant/voice/health: get: {operationId: adminVoiceHealth, tags: [Admin], summary: 'ASR relay /healthz from the API host {ok, configured, pinned, status, latencyMs, relay} (dashboard)', responses: {'200': {description: 'Health'}}} /admin/v1/assistant/voice/config: get: {operationId: adminVoiceConfig, tags: [Admin], summary: 'Voice packs {packs[{product, uses, amount (Toman), active}], custom{unitPrice (Toman), min, max, active}} (billingRead)', responses: {'200': {description: 'Config'}}} put: {operationId: adminSetVoiceConfig, tags: [Admin], summary: 'Set {packs?[{product voice_100|voice_500|voice_1000|voice_10000, uses? 1-100000, amount? Toman, active?}], custom?{unitPrice?, min?, max? (1-100000, min ≤ max), active?}} (billingCatalog; audited)', responses: {'200': {description: 'Config'}, '422': {$ref: '#/components/responses/Validation'}}} /admin/v1/users/{id}/voice: get: {operationId: adminUserVoice, tags: [Admin], summary: 'One account''s voice quota, history (no transcripts) and grants (usersRead)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {description: 'Status'}}} /admin/v1/users/{id}/voice/grants: post: {operationId: adminGrantVoiceUses, tags: [Admin], summary: 'Grant {uses 1-10000, note?} for the account''s current period (usersGrant; audited)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'201': {description: 'Quota'}, '404': {$ref: '#/components/responses/NotFound'}}} # ─────────────────────────── Academies (1.3.12, agent B) ─────────────────────────── /v1/orgs: get: {operationId: listOrgs, tags: [Academies], summary: 'Academies the account belongs to (role, seats), invitations to its verified phone numbers and whether it may create one', responses: {'200': {description: 'List'}}} post: {operationId: createOrg, tags: [Academies], summary: 'Create an academy {name, displayName?} (Business: org.admin and sharing.level org; 5 per account). The creator is its admin.', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'201': {description: 'Academy as the caller sees it'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}}} /v1/orgs/join: post: {operationId: joinOrg, tags: [Academies], summary: 'Join with a personal 8-character invite code {code} (single use)', parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Academy'}, '404': {$ref: '#/components/responses/NotFound'}, '409': {description: 'Already a member'}}} /v1/orgs/invitations/{memberId}/accept: post: {operationId: acceptOrgInvitation, tags: [Academies], summary: 'Accept an invitation sent to one of the verified phone numbers of the caller', parameters: [{name: memberId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Academy'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/orgs/{id}: get: {operationId: getOrg, tags: [Academies], summary: 'The academy as the caller sees it: admins and teachers see everyone; students see themselves and staff; parents see their linked children (phones and codes only for admins)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {description: 'Academy'}, '404': {$ref: '#/components/responses/NotFound'}}} patch: {operationId: renameOrg, tags: [Academies], summary: 'Rename {name} (admins; the owner must still be on Business)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Renamed'}, '403': {$ref: '#/components/responses/Forbidden'}}} delete: {operationId: deleteOrg, tags: [Academies], summary: 'Delete (owner only)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Deleted'}, '403': {$ref: '#/components/responses/Forbidden'}}} /v1/orgs/{id}/members: post: {operationId: inviteOrgMember, tags: [Academies], summary: 'Invite {role: admin|teacher|student|parent, displayName, phone?, seat?, childId?}; returns the personal code. Teachers and students take a seat by default; beyond the seats → 409 limit_exceeded (reason seats_full).', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'201': {description: 'Invited'}, '409': {description: 'Seats full or phone already invited'}}} /v1/orgs/{id}/members/{memberId}: patch: {operationId: updateOrgMember, tags: [Academies], summary: 'Change {role?, displayName?, seat?} (admins)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: memberId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Saved'}}} delete: {operationId: removeOrgMember, tags: [Academies], summary: 'Remove a member (admins) or leave (yourself)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: memberId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Removed'}}} /v1/orgs/{id}/members/{memberId}/code: post: {operationId: renewOrgInviteCode, tags: [Academies], summary: 'A new invite code for a member who has not joined yet (admins)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: memberId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Code'}}} /v1/orgs/{id}/members/{memberId}/progress: get: {operationId: orgStudentProgress, tags: [Academies], summary: 'Attendance totals, grade average, classes and latest records of a student (the student, linked parents, admins and teachers)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: memberId, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {description: 'Progress'}, '404': {$ref: '#/components/responses/NotFound'}}} /v1/orgs/{id}/links: put: {operationId: setOrgParentLinks, tags: [Academies], summary: 'Set the children of a parent {parentId, childIds} (admins)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Saved'}}} /v1/orgs/{id}/classes: post: {operationId: createOrgClass, tags: [Academies], summary: 'Add a weekly class {name, weekday 1-7, startMinute, durationMin, teacherId?, room?, studentIds?} (admins)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'201': {description: 'Created'}}} /v1/orgs/{id}/classes/{classId}: patch: {operationId: updateOrgClass, tags: [Academies], summary: 'Change a class (admins)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: classId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {description: 'Saved'}}} delete: {operationId: deleteOrgClass, tags: [Academies], summary: 'Delete a class (admins)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: classId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: 'Deleted'}}} /v1/orgs/{id}/classes/{classId}/records: get: {operationId: listOrgRecords, tags: [Academies], summary: 'Attendance and grades of a class (its teacher or admins; ?from=&to= YYYY-MM-DD)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: classId, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {description: 'Records'}}} post: {operationId: writeOrgRecords, tags: [Academies], summary: 'Record {kind: attendance|grade, day, title?, maxScore?, entries: [{studentId, status|score}]} for enrolled students (attendance replaces the status of that day)', parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: classId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'201': {description: 'Written'}, '403': {$ref: '#/components/responses/Forbidden'}, '422': {$ref: '#/components/responses/Validation'}}} # ─────────────────────────── Integrations ─────────────────────────── /v1/integrations: get: operationId: getIntegrations tags: [Integrations] summary: Bot configuration, linked chats with preferences, the MCP URL and whether remote reminders are allowed responses: '200': {description: Overview, content: {application/json: {schema: {type: object, properties: {mcpUrl: {type: string, format: uri}, restBaseUrl: {type: string, format: uri}, remindersAllowed: {type: boolean}, bots: {type: object}, links: {type: array, items: {$ref: '#/components/schemas/BotLink'}}}}}}} /v1/integrations/tokens: get: operationId: listPersonalTokens tags: [Integrations] summary: Personal access tokens (never the token itself; revoked ones for 30 days) responses: '200': {description: List, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {$ref: '#/components/schemas/PersonalToken'}}}}}}} post: operationId: createPersonalToken tags: [Integrations] summary: Create a personal access token — the response carries `token` once (at most 20 active) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [name, scopes] properties: name: {type: string, minLength: 1, maxLength: 60} scopes: {type: array, items: {type: string, enum: [read, write]}, minItems: 1, description: write implies read} expiresInDays: {type: integer, minimum: 1, maximum: 3650} responses: '201': {description: Created, content: {application/json: {schema: {allOf: [{$ref: '#/components/schemas/PersonalToken'}, {type: object, required: [token], properties: {token: {type: string, pattern: '^bzp_[A-Za-z0-9]{40}$'}}}]}}}} '409': {description: Too many active tokens} '422': {description: Validation failed} /v1/integrations/tokens/{id}: delete: operationId: revokePersonalToken tags: [Integrations] summary: Revoke a token (immediately) parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} - {$ref: '#/components/parameters/IdempotencyKey'} responses: '204': {description: Revoked} '404': {$ref: '#/components/responses/NotFound'} /v1/integrations/today: get: operationId: integrationsToday tags: [Integrations] summary: Today's items and the overdue count (scope read; finance types such as cheques and loans are left out unless the user shares them with assistants) security: [{personalToken: []}] responses: '200': {description: Summary, content: {application/json: {schema: {type: object, properties: {date: {type: string, format: date}, timeZone: {type: string}, items: {type: array, items: {$ref: '#/components/schemas/IntegrationItem'}}, openCount: {type: integer}, doneCount: {type: integer}, overdueCount: {type: integer}}}}}} '401': {$ref: '#/components/responses/Unauthorized'} /v1/integrations/items: get: operationId: integrationsListItems tags: [Integrations] summary: Items dated in a range (recurring items expanded), scope read security: [{personalToken: []}] parameters: - {name: range, in: query, schema: {type: string, enum: [today, tomorrow, week, overdue, custom], default: today}} - {name: from, in: query, schema: {type: string, format: date}} - {name: to, in: query, schema: {type: string, format: date}, description: at most 62 days after from} - {name: includeDone, in: query, schema: {type: boolean, default: true}} responses: '200': {description: Items, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {$ref: '#/components/schemas/IntegrationItem'}}}}}}} '401': {$ref: '#/components/responses/Unauthorized'} '422': {description: Validation failed} post: operationId: integrationsCreateItem tags: [Integrations] summary: Create an item from natural language (`text`, the app's quick-add parser) or structured fields — scope write; written as sync operations every device pulls security: [{personalToken: []}] requestBody: required: true content: application/json: schema: type: object properties: text: {type: string, maxLength: 500, example: 'میانترم چهارشنبه ساعت ۹ صبح یادآور'} title: {type: string, maxLength: 300} date: {type: string, format: date} time: {type: string, pattern: '^\d{2}:\d{2}$'} durationMinutes: {type: integer, minimum: 1, maximum: 43200} reminderMinutesBefore: {type: array, maxItems: 5, items: {type: integer, minimum: 0, maximum: 43200}} priority: {type: string, enum: [none, low, medium, high, urgent]} notes: {type: string, maxLength: 2000} responses: '201': {description: Created, content: {application/json: {schema: {type: object, properties: {item: {$ref: '#/components/schemas/IntegrationItem'}, typeKey: {type: string}, reminderOffsetsMinutes: {type: array, items: {type: integer}}, recurrence: {type: [string, 'null']}}}}}} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`insufficient_scope` (read-only token) or `limit_exceeded` (plan limit)'} '422': {description: Validation failed} /v1/integrations/items/search: get: operationId: integrationsSearchItems tags: [Integrations] summary: Items whose title contains `q` (scope read) security: [{personalToken: []}] parameters: - {name: q, in: query, required: true, schema: {type: string, maxLength: 100}} - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 50, default: 20}} responses: '200': {description: Items, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {$ref: '#/components/schemas/IntegrationItem'}}}}}}} /v1/integrations/items/{id}/complete: post: operationId: integrationsCompleteItem tags: [Integrations] summary: Mark done (or open again with done=false); recurring items take occurrenceStart — scope write security: [{personalToken: []}] parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}] requestBody: {content: {application/json: {schema: {type: object, properties: {occurrenceStart: {type: integer}, done: {type: boolean, default: true}}}}}} responses: '200': {description: Updated, content: {application/json: {schema: {type: object, properties: {item: {$ref: '#/components/schemas/IntegrationItem'}}}}}} '422': {description: Validation failed} /v1/integrations/items/{id}/snooze: post: operationId: integrationsSnoozeItem tags: [Integrations] summary: Remind again after `minutes` or tomorrow 09:00 (a one-time reminder on every device and linked bot) — scope write security: [{personalToken: []}] parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}] requestBody: {required: true, content: {application/json: {schema: {type: object, properties: {minutes: {type: integer, minimum: 1, maximum: 10080}, tomorrow: {type: boolean}}}}}} responses: '200': {description: Snoozed, content: {application/json: {schema: {type: object, properties: {id: {type: string}, remindAt: {type: string, format: date-time}}}}}} /v1/mcp: post: operationId: mcp tags: [Integrations] summary: Model Context Protocol server (Streamable HTTP, JSON-RPC 2.0; protocol 2025-11-25, 2025-06-18, 2025-03-26; stateless) description: | Methods: initialize, ping, tools/list, tools/call (get_today_summary, list_items, search_items, create_item, complete_item, snooze_item), notifications/* (202). Write tools need the write scope (the tool result has isError otherwise). `POST /v1/mcp/{token}` accepts the token in the path for clients that cannot send headers. GET and DELETE answer 405 (no server-initiated stream, no sessions). An unsupported MCP-Protocol-Version header answers 400. security: [{personalToken: []}] parameters: - {name: MCP-Protocol-Version, in: header, schema: {type: string}} requestBody: {required: true, content: {application/json: {schema: {oneOf: [{type: object}, {type: array}]}}}} responses: '200': {description: JSON-RPC response(s), content: {application/json: {schema: {oneOf: [{type: object}, {type: array}]}}}} '202': {description: Notification accepted} '400': {description: Parse error or unsupported protocol version} '401': {$ref: '#/components/responses/Unauthorized'} /internal/v1/bale/update: post: operationId: internalBaleUpdate tags: [Internal] summary: A Bale update (message or callback_query) forwarded by the bot service; linked chats are answered by the bot assistant through the bot service's /v1/bot-call security: [{botSecret: []}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [update], properties: {update: {type: object}}}}}} responses: '200': {description: Outcome, content: {application/json: {schema: {type: object, properties: {handled: {type: boolean}, linked: {type: boolean}}}}}} '404': {description: Hidden (no or wrong secret, or proxied)} # ───────────────────────────── Referrals ───────────────────────────── /v1/referrals/me: get: operationId: getMyReferrals tags: [Referrals] summary: The caller's invite code and link, and how many friends joined description: | A new account registered with the code (`referralCode` of `POST /v1/auth/register`) and the inviter each get 30 days of Plus, once per new account. Guards: not on a device the inviter uses, one reward per device id, at most 12 inviter rewards per rolling year (the new user is still rewarded). responses: '200': description: Referral state content: application/json: schema: type: object required: [code, link, invitedCount, rewardedDays] properties: code: {type: string, examples: [K7M2Q9XA]} link: {type: string, format: uri, examples: ['https://barzaman.ir/r/K7M2Q9XA']} invitedCount: {type: integer} rewardedDays: {type: integer, description: Days of Plus the caller earned as an inviter} rewardDays: {type: integer, examples: [30]} rewardPlan: {const: plus} remainingRewardsThisYear: {type: integer} # ───────────────────── Internal (bot service only) ───────────────────── /internal/v1/billing/bale/precheck: post: operationId: internalBalePrecheck tags: [Internal] summary: Verify a Bale pre_checkout_query (order pending, amount and currency match) security: [{botSecret: []}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [orderId, totalAmount, queryId], properties: {orderId: {type: string}, totalAmount: {type: integer, description: Rial}, currency: {type: string, examples: [IRR]}, queryId: {type: string}, baleUserId: {type: [integer, string]}}}}}} responses: '200': {description: Verdict, content: {application/json: {schema: {type: object, required: [ok], properties: {ok: {type: boolean}, reason: {type: string, enum: [not_found, not_pending, expired, amount_mismatch, currency_mismatch]}, message: {type: string, description: Localized text for answerPreCheckoutQuery}}}}}} '404': {$ref: '#/components/responses/NotFound'} /internal/v1/billing/bale/paid: post: operationId: internalBalePaid tags: [Internal] summary: A successful_payment — mark the order paid (idempotent), grant the stacked period, record purchase and invoice security: [{botSecret: []}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [orderId, totalAmount, telegramPaymentChargeId], properties: {orderId: {type: string}, totalAmount: {type: integer}, currency: {type: string}, telegramPaymentChargeId: {type: string}, providerPaymentChargeId: {type: [string, 'null']}, chatId: {type: [integer, string, 'null']}, baleUserId: {type: [integer, string, 'null']}, source: {type: string, enum: [update, inquiry]}}}}}} responses: '200': {description: Paid, content: {application/json: {schema: {type: object, properties: {status: {const: paid}, alreadyPaid: {type: boolean}, orderId: {type: string}, chatId: {type: [string, 'null']}, locale: {type: string}, plan: {type: string}, period: {type: string}, paidThrough: {type: string, format: date-time}, receiptText: {type: string}}}}}} '404': {$ref: '#/components/responses/NotFound'} '409': {description: '`payment_amount_mismatch`, `order_not_payable`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /internal/v1/billing/bale/pay-start: post: operationId: internalBalePayStart tags: [Internal] summary: '`/start pay_` — the order of a pay link and the invoice to send to that chat' description: | The first chat that opens a pay link claims the order (the same chat may open it again while unpaid; others get `other_chat`). The chat is remembered for invoices and receipts only (`via = payment`: no reminders, never password resets — a pay link may have been forwarded). security: [{botSecret: []}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [token, chatId], properties: {token: {type: string, pattern: '^pay_[A-Za-z0-9]{20,40}$'}, chatId: {type: [integer, string]}, username: {type: [string, 'null']}, languageCode: {type: [string, 'null']}}}}}} responses: '200': {description: Invoice to send, or a localized refusal, content: {application/json: {schema: {type: object, required: [ok], properties: {ok: {type: boolean}, orderId: {type: string}, title: {type: string, maxLength: 32}, description: {type: string, maxLength: 255}, label: {type: string}, amountRial: {type: integer}, text: {type: string}, locale: {type: string}, reason: {type: string, enum: [invalid, expired, paid, other_chat]}, message: {type: string}}}}}} /internal/v1/billing/bale/failed: post: operationId: internalBaleFailed tags: [Internal] summary: Bale reported an approved transaction as failed or rejected (reconciliation) security: [{botSecret: []}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [orderId, queryId, status], properties: {orderId: {type: string}, queryId: {type: string}, status: {type: string, enum: [failed, rejected]}}}}}} responses: '204': {description: Recorded} /internal/v1/billing/bale/unsettled: get: operationId: internalBaleUnsettled tags: [Internal] summary: Orders approved at pre-checkout 2 minutes – 48 hours ago that are neither paid nor failed security: [{botSecret: []}] responses: '200': {description: Orders, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {type: object, properties: {orderId: {type: string}, queryId: {type: string}, amountRial: {type: integer}, chatId: {type: [string, 'null']}, approvedAt: {type: string, format: date-time}}}}}}}}} /internal/v1/bale/link: post: operationId: internalBaleLink tags: [Internal] summary: '`/start ` — link a Bale chat to the account of a one-time code' security: [{botSecret: []}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [code, chatId], properties: {code: {type: string}, chatId: {type: [integer, string]}, username: {type: [string, 'null']}, languageCode: {type: [string, 'null']}}}}}} responses: '200': {description: Outcome, content: {application/json: {schema: {type: object, properties: {linked: {type: boolean}, locale: {type: string, enum: [fa, ar, en]}}}}}} /internal/v1/bale/stop: post: operationId: internalBaleStop tags: [Internal] summary: '`/stop` — no more notifications to the chat' security: [{botSecret: []}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [chatId], properties: {chatId: {type: [integer, string]}}}}}} responses: '200': {description: Outcome, content: {application/json: {schema: {type: object, properties: {stopped: {type: boolean}}}}}} /internal/v1/bale/password-reset: post: operationId: internalBalePasswordReset tags: [Internal] summary: '`/reset` — send a one-time reset link to this chat when it was linked from the app (never payment-only links)' security: [{botSecret: []}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [chatId], properties: {chatId: {type: [integer, string]}}}}}} responses: '200': {description: Outcome (linked false = the chat belongs to no account; sent false = cool-down), content: {application/json: {schema: {type: object, properties: {linked: {type: boolean}, sent: {type: boolean}, locale: {type: string, enum: [fa, ar, en]}}}}}} # ───────────────────────────── Support ───────────────────────────── /v1/public/pow-challenge: get: operationId: getPowChallenge tags: [Support] summary: Proof-of-work challenge for the public forms description: 'Find a decimal `solution` such that SHA-256("{challenge}:{solution}") starts with `bits` zero bits and send `{pow: {challenge, solution}}`. Each challenge is single-use and valid for 10 minutes.' security: [{}] parameters: [{name: purpose, in: query, schema: {type: string, enum: [support, deletion], default: support}}] responses: '200': {description: Challenge, content: {application/json: {schema: {$ref: '#/components/schemas/PowChallenge'}}}} /v1/public/support: post: operationId: createPublicTicket tags: [Support] summary: Website contact form description: | Spam defence without third-party CAPTCHAs: a honeypot field (`website`, must stay empty), per-IP limits (10/hour, 30/day) and adaptive proof-of-work — a few submissions per IP per hour pass freely; beyond that (or during a global surge) the answer is `428 pow_required` with a `challenge` to solve and resend. security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/PublicTicket'}}}} responses: '201': {description: Received, content: {application/json: {schema: {type: object, properties: {id: {type: string, format: uuid}, number: {type: integer}, status: {type: string}}}}}} '400': {description: '`pow_invalid` (extension `challenge`)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '422': {$ref: '#/components/responses/Validation'} '428': {description: '`pow_required` (extension `challenge`)', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/public/deletion-requests: post: operationId: createDeletionRequest tags: [Support] summary: Account deletion request from the web (for people who cannot sign in) description: Always answered the same way, so it never reveals whether an account exists. Staff process it in the admin console. security: [{}] parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [contact] properties: contact: {type: string, maxLength: 320, description: The account's e-mail address or phone number} message: {type: string, maxLength: 2000} locale: {$ref: '#/components/schemas/Locale'} website: {type: string, description: Honeypot — leave empty} pow: {$ref: '#/components/schemas/PowSolution'} responses: '202': {description: Received, content: {application/json: {schema: {type: object, properties: {id: {type: string, format: uuid}, status: {const: received}}}}}} '422': {$ref: '#/components/responses/Validation'} '428': {description: '`pow_required`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {$ref: '#/components/responses/TooManyRequests'} /v1/support/tickets: post: operationId: createAppTicket tags: [Support] summary: Ticket from the app, with optional diagnostics (≤ 16 KB; secret-looking keys are dropped) parameters: [{$ref: '#/components/parameters/IdempotencyKey'}] requestBody: required: true content: application/json: schema: type: object required: [subject, message] properties: subject: {type: string, minLength: 3, maxLength: 200} message: {type: string, minLength: 3, maxLength: 5000} category: {type: string, enum: [general, billing, bug, account, feature, privacy, other]} locale: {$ref: '#/components/schemas/Locale'} contact: {type: string, description: Optional e-mail/phone for replies outside the app} diagnostics: {type: object, additionalProperties: true, description: 'e.g. appVersion, platform, flavor, OS, sync state'} responses: '201': {description: Created, content: {application/json: {schema: {type: object, properties: {id: {type: string, format: uuid}, number: {type: integer}, status: {type: string}}}}}} '422': {$ref: '#/components/responses/Validation'} get: operationId: listAppTickets tags: [Support] summary: The account's tickets parameters: [{$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}] responses: '200': {description: Page, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {$ref: '#/components/schemas/SupportTicket'}}, nextCursor: {type: [string, 'null']}}}}}} /v1/support/tickets/{id}: get: operationId: getAppTicket tags: [Support] summary: A ticket with its conversation (staff-internal notes excluded) parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}] responses: '200': {description: Ticket, content: {application/json: {schema: {$ref: '#/components/schemas/SupportTicket'}}}} '404': {description: '`ticket_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /v1/support/tickets/{id}/messages: post: operationId: replyAppTicket tags: [Support] summary: Add a message to one of the account's tickets (reopens it) parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [message], properties: {message: {type: string, maxLength: 5000}}}}}} responses: '201': {description: Updated ticket, content: {application/json: {schema: {$ref: '#/components/schemas/SupportTicket'}}}} '404': {description: '`ticket_not_found`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`ticket_closed`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} # ───────────────────────────── Admin (/admin/v1) ───────────────────────────── /admin/v1/auth/login: post: operationId: adminLogin tags: [Admin] summary: Staff sign-in (Argon2id password; TOTP mandatory) description: | Returns a staff session token (`Authorization: Bearer bzs_…`; also set as the HttpOnly `bz_admin` cookie for same-origin consoles — cookie-authenticated mutations must send the admin `Origin`). `status`: `ok` (full session), `totp_required` (call `/auth/totp/verify`) or `totp_enrollment_required` (call `/auth/totp/enroll` then `/auth/totp/verify`). Until then only the `/auth/*` endpoints work. The bootstrap owner (ADMIN_BOOTSTRAP_EMAIL/PASSWORD) must change the password at first sign-in. 10 failures lock the account for 15 minutes. All admin endpoints honour the optional ADMIN_IP_ALLOWLIST. security: [{}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [email, password], properties: {email: {type: string}, password: {type: string}, totpCode: {type: string}}}}}} responses: '200': {description: Signed in (maybe pending the second factor), content: {application/json: {schema: {$ref: '#/components/schemas/AdminLogin'}}}} '401': {description: '`admin_credentials_invalid`, `admin_totp_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '403': {description: '`admin_ip_not_allowed`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {description: '`admin_account_locked`, `rate_limited`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /admin/v1/auth/me: get: {operationId: adminMe, tags: [Admin], summary: 'The signed-in staff member and session stage', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '401': {$ref: '#/components/responses/Unauthorized'}}} /admin/v1/auth/totp/enroll: post: {operationId: adminTotpEnroll, tags: [Admin], summary: 'Start TOTP enrolment (secret and otpauth URI shown once)', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '409': {$ref: '#/components/responses/Conflict'}}} /admin/v1/auth/totp/verify: post: operationId: adminTotpVerify tags: [Admin] summary: Confirm enrolment or complete sign-in with a TOTP code (rotates the session) description: | On success the calling password-stage session is revoked and a new full session is issued (token rotation): the body carries the new `token` and `expiresAt` (12 hours, 30-minute idle timeout) and the HttpOnly `bz_admin` cookie is re-issued with the full-session lifetime. Continue with the new token; a request that still sends the revoked token as `Authorization` is authenticated by the cookie instead when both belong to the same staff member (with the cookie's admin-`Origin` rule for mutations). A session can be rotated once: a concurrent second verification answers `401 token_invalid`. security: [{adminSession: []}] requestBody: {required: true, content: {application/json: {schema: {type: object, required: [code], properties: {code: {type: string}}}}}} responses: '200': description: Second factor verified; new full session headers: Set-Cookie: {description: '`bz_admin=; Path=/admin/v1; HttpOnly; SameSite=Strict; Secure; Max-Age=`', schema: {type: string}} content: {application/json: {schema: {$ref: '#/components/schemas/AdminLogin'}}} '401': {description: '`admin_totp_invalid`, `token_invalid`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '409': {description: '`mfa_not_enrolled`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} '429': {description: '`admin_account_locked`, `rate_limited`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}} /admin/v1/auth/logout: post: {operationId: adminLogout, tags: [Admin], summary: 'End the staff session', security: [{adminSession: []}], responses: {'204': {description: Signed out}}} /admin/v1/auth/password: post: {operationId: adminChangePassword, tags: [Admin], summary: 'Change the own password (ends other sessions)', security: [{adminSession: []}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [currentPassword, newPassword], properties: {currentPassword: {type: string}, newPassword: {type: string, minLength: 12}}}}}}, responses: {'204': {description: Changed}, '401': {$ref: '#/components/responses/Unauthorized'}, '422': {description: '`admin_weak_password`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}}}} /admin/v1/staff: get: {operationId: adminListStaff, tags: [Admin], summary: 'Staff accounts (owner)', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '403': {$ref: '#/components/responses/Forbidden'}}} post: {operationId: adminCreateStaff, tags: [Admin], summary: 'Create a staff account (owner; initial password must be changed)', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [email, role, password], properties: {email: {type: string}, role: {$ref: '#/components/schemas/StaffRole'}, password: {type: string}, displayName: {type: string}}}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}, '409': {description: '`staff_email_taken`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}}}} /admin/v1/staff/{id}: patch: {operationId: adminUpdateStaff, tags: [Admin], summary: 'Change role, status or name (owner; the last owner cannot be demoted)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, properties: {role: {$ref: '#/components/schemas/StaffRole'}, status: {type: string, enum: [active, disabled]}, displayName: {type: string}}}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}, '409': {description: '`admin_last_owner`', content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}}}}} /admin/v1/staff/{id}/reset-totp: post: {operationId: adminResetStaffTotp, tags: [Admin], summary: 'Reset a staff member''s TOTP (re-enrolment at next sign-in)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: Reset}}} /admin/v1/staff/{id}/reset-password: post: {operationId: adminResetStaffPassword, tags: [Admin], summary: 'Set a temporary password (must be changed at sign-in)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [password], properties: {password: {type: string}}}}}}, responses: {'204': {description: Reset}}} /admin/v1/dashboard: get: {operationId: adminDashboard, tags: [Admin], summary: 'Aggregate statistics only: users (total, new 7d/30d, by plan), active devices 7d, sync ops/day, active subscriptions (store sandbox flagged) and entitlements, revenue by currency excluding store sandbox purchases (revenue permission), pending tickets and deletion requests', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/audit: get: {operationId: adminAudit, tags: [Admin], summary: 'Audit log (filters actorType, actorId, action (trailing * = literal prefix; `_` and `%` match themselves), targetType, targetId, from, to)', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}, {name: actorType, in: query, schema: {type: string, enum: [user, staff, system]}}, {name: actorId, in: query, schema: {type: string}}, {name: action, in: query, schema: {type: string}}, {name: targetType, in: query, schema: {type: string}}, {name: targetId, in: query, schema: {type: string}}, {name: from, in: query, schema: {type: string, format: date-time}}, {name: to, in: query, schema: {type: string, format: date-time}}], responses: {'200': {$ref: '#/components/responses/AdminPage'}}} /admin/v1/users: get: {operationId: adminSearchUsers, tags: [Admin], summary: 'Search by user id, full phone, e-mail, exact username or part of the display name (results masked; audited); without q: newest users', security: [{adminSession: []}], parameters: [{name: q, in: query, schema: {type: string}}, {name: status, in: query, schema: {type: string, enum: [active, pending_deletion, disabled]}}, {$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}], responses: {'200': {$ref: '#/components/responses/AdminPage'}}} /admin/v1/users/{id}: get: {operationId: adminGetUser, tags: [Admin], summary: 'User details: masked identities, devices, subscriptions, grants (audited)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '404': {$ref: '#/components/responses/NotFound'}}} /admin/v1/users/{id}/identities: get: {operationId: adminRevealIdentities, tags: [Admin], summary: 'Unmasked sign-in identities (owner/admin; audited)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/users/{id}/sessions: get: {operationId: adminUserSessions, tags: [Admin], summary: 'Active sessions (IP addresses truncated)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/users/{id}/sessions/revoke: post: {operationId: adminRevokeUserSessions, tags: [Admin], summary: 'Sign the user out everywhere', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/users/{id}/disable: post: {operationId: adminDisableUser, tags: [Admin], summary: 'Disable an active account (ends every session)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {content: {application/json: {schema: {type: object, properties: {reason: {type: string, maxLength: 300}}}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}, '409': {$ref: '#/components/responses/Conflict'}}} /admin/v1/users/{id}/enable: post: {operationId: adminEnableUser, tags: [Admin], summary: 'Re-enable a disabled account', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '409': {$ref: '#/components/responses/Conflict'}}} /admin/v1/users/{id}/phone-exempt: post: {operationId: adminPhoneExempt, tags: [Admin], summary: 'Exempt an account from the phone requirement (store-review accounts) or remove the exemption; audited', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [exempt], properties: {exempt: {type: boolean}, reason: {type: string, maxLength: 300}}}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}, '404': {$ref: '#/components/responses/NotFound'}}} /admin/v1/users/{id}/password-reset: post: {operationId: adminIssuePasswordReset, tags: [Admin], summary: 'One-time password-reset link after staff checked the requester (support ticket). deliver bale sends it to the account Bale chat linked from the app (30 min); deliver link returns it once for hand-over (24 h). Audited; staff never see or set the password', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [deliver], properties: {deliver: {type: string, enum: [bale, link]}, ticketId: {type: string, format: uuid}}}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}, '409': {$ref: '#/components/responses/Conflict'}, '422': {$ref: '#/components/responses/Validation'}}} /admin/v1/users/{id}/grants: post: {operationId: adminGrantPlan, tags: [Admin], summary: 'Staff comp plan with an expiry (days or endsAt)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [plan], properties: {plan: {type: string, enum: [plus, pro, business]}, days: {type: integer, minimum: 1, maximum: 3660}, endsAt: {type: string, format: date-time}, note: {type: string, maxLength: 300}}}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/users/{id}/grants/{grantId}: delete: {operationId: adminRevokeGrant, tags: [Admin], summary: 'Revoke a staff comp, promo or trial grant', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {name: grantId, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: Revoked}, '409': {$ref: '#/components/responses/Conflict'}}} /admin/v1/test-accounts: get: {operationId: adminListTestAccounts, tags: [Admin], summary: 'Store-review / owner test accounts (fixed codes stored as HMACs)', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} post: {operationId: adminUpsertTestAccount, tags: [Admin], summary: 'Create or update a test account (guessable codes refused)', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [kind, identifier, code], properties: {kind: {type: string, enum: [phone, email]}, identifier: {type: string}, code: {type: string, pattern: '^\d{6}$'}, note: {type: string}, expiresDays: {type: integer}}}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}, '422': {$ref: '#/components/responses/Validation'}}} /admin/v1/test-accounts/{id}: patch: {operationId: adminToggleTestAccount, tags: [Admin], summary: 'Enable or disable', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [enabled], properties: {enabled: {type: boolean}}}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}}} delete: {operationId: adminDeleteTestAccount, tags: [Admin], summary: 'Delete a test account', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: Deleted}}} /admin/v1/billing/providers: get: {operationId: adminBillingProviders, tags: [Admin], summary: 'Which payment providers are configured (no secrets)', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/billing/products: get: {operationId: adminListProducts, tags: [Admin], summary: 'Plans', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/billing/products/{id}: patch: {operationId: adminUpdateProduct, tags: [Admin], summary: 'Plan names, descriptions, highlights, order, visibility', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, enum: [free, plus, pro, business]}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/billing/prices: get: {operationId: adminListPrices, tags: [Admin], summary: 'All prices (active and inactive)', security: [{adminSession: []}], parameters: [{name: region, in: query, schema: {type: string, enum: [IR, GLOBAL]}}, {name: provider, in: query, schema: {type: string}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} post: {operationId: adminCreatePrice, tags: [Admin], summary: 'Create a price (inactive unless active: true). Zarinpal and Myket sell time packs; amount, currency, provider and store product id are immutable afterwards', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/PriceInput'}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}, '409': {$ref: '#/components/responses/Conflict'}, '422': {$ref: '#/components/responses/Validation'}}} /admin/v1/billing/prices/{id}: patch: {operationId: adminUpdatePrice, tags: [Admin], summary: 'Activate/deactivate, label, flavors, order, trial days', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, properties: {active: {type: boolean}, label: {type: object}, flavors: {type: array, items: {type: string}}, sortOrder: {type: integer}, trialDays: {type: integer}}}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}, '422': {$ref: '#/components/responses/Validation'}}} /admin/v1/billing/promo-codes: get: {operationId: adminListPromoCodes, tags: [Admin], summary: 'Promo codes (hints only)', security: [{adminSession: []}], parameters: [{name: batch, in: query, schema: {type: string}}, {$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}], responses: {'200': {$ref: '#/components/responses/AdminPage'}}} post: {operationId: adminCreatePromoCodes, tags: [Admin], summary: 'One named code (code) or count random codes; plaintext codes are returned once', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [plan, durationDays], properties: {code: {type: string}, count: {type: integer, maximum: 1000}, plan: {type: string, enum: [plus, pro, business]}, durationDays: {type: integer}, maxRedemptions: {type: integer}, batch: {type: string}, note: {type: string}, startsAt: {type: string, format: date-time}, expiresAt: {type: string, format: date-time}, flavors: {type: array, items: {type: string, enum: [direct, pwa-ir, pwa-global, bazaar, myket]}}}}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/billing/promo-codes/{id}: get: {operationId: adminGetPromoCode, tags: [Admin], summary: 'A promo code', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} patch: {operationId: adminUpdatePromoCode, tags: [Admin], summary: 'Activate/deactivate, limit, expiry, note', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/billing/promo-codes/{id}/redemptions: get: {operationId: adminPromoRedemptions, tags: [Admin], summary: 'Usage of a code', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/billing/offers: get: {operationId: adminListOffers, tags: [Admin], summary: 'Discount offers (none by default), the products they may cover and the install bases (storePriced = never discounted)', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} post: {operationId: adminCreateOffer, tags: [Admin], summary: 'Create a discount offer (percent 1-90 or fixed Toman; products, periods, installBases, inclusive minVersion/maxVersion, startsAt/endsAt); audited', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [name, kind, value], properties: {name: {type: string, maxLength: 120}, kind: {type: string, enum: [percent, fixed]}, value: {type: integer, minimum: 1}, products: {type: array, items: {type: string, enum: [plus, pro, storage_100gb]}}, periods: {type: array, items: {type: string, enum: [month, year]}}, installBases: {type: array, items: {type: string, enum: [pwa, direct, bazaar, myket, play, ios, windows, macos, linux, miniapp, other]}}, minVersion: {type: [string, 'null']}, maxVersion: {type: [string, 'null']}, startsAt: {type: [string, 'null'], format: date-time}, endsAt: {type: [string, 'null'], format: date-time}, enabled: {type: boolean}}}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/billing/offers/{id}: patch: {operationId: adminUpdateOffer, tags: [Admin], summary: 'Edit or disable (enabled false) an offer; audited', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/news/config: get: {operationId: adminGetNewsConfig, tags: [Admin], summary: 'News on/off, feeds and per-feed daily / per-run caps (built-in defaults until saved)', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} put: {operationId: adminSetNewsConfig, tags: [Admin], summary: 'Save the news switch, feed list and caps; audited', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/news/status: get: {operationId: adminNewsStatus, tags: [Admin], summary: 'Stored item counts and the last fetch result of every feed (reachability)', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/news/refresh: post: {operationId: adminRefreshNews, tags: [Admin], summary: 'Fetch the enabled feeds now', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/billing/subscriptions: get: {operationId: adminListSubscriptions, tags: [Admin], summary: 'Subscriptions (filters userId, status, provider)', security: [{adminSession: []}], parameters: [{name: userId, in: query, schema: {type: string, format: uuid}}, {name: status, in: query, schema: {type: string}}, {name: provider, in: query, schema: {type: string}}, {$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}], responses: {'200': {$ref: '#/components/responses/AdminPage'}}} /admin/v1/billing/purchases: get: {operationId: adminListPurchases, tags: [Admin], summary: 'Verified purchases (filter userId)', security: [{adminSession: []}], parameters: [{name: userId, in: query, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}], responses: {'200': {$ref: '#/components/responses/AdminPage'}}} /admin/v1/support/tickets: get: {operationId: adminListTickets, tags: [Admin], summary: 'Tickets (filters status, number, q = subject substring, case-insensitive with `%`/`_` matched literally, or exact contact)', security: [{adminSession: []}], parameters: [{name: status, in: query, schema: {type: string, enum: [open, pending, answered, closed, spam]}}, {name: number, in: query, schema: {type: integer}}, {name: q, in: query, schema: {type: string}}, {$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}], responses: {'200': {$ref: '#/components/responses/AdminPage'}}} /admin/v1/support/tickets/{id}: get: {operationId: adminGetTicket, tags: [Admin], summary: 'Ticket with messages, internal notes and diagnostics', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '404': {$ref: '#/components/responses/NotFound'}}} patch: {operationId: adminUpdateTicket, tags: [Admin], summary: 'Status, priority, assignee', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, properties: {status: {type: string, enum: [open, pending, answered, closed, spam]}, priority: {type: string, enum: [low, normal, high]}, assigneeId: {type: [string, 'null']}}}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/support/tickets/{id}/reply: post: {operationId: adminReplyTicket, tags: [Admin], summary: 'Reply (e-mailed to e-mail contacts, pushed to the app) or add an internal note', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [message], properties: {message: {type: string, maxLength: 10000}, internal: {type: boolean}, status: {type: string, enum: [open, pending, answered, closed, spam]}}}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/deletion-requests: get: {operationId: adminListDeletionRequests, tags: [Admin], summary: 'Web deletion requests (source=web) or in-app account deletions in their grace period (source=account)', security: [{adminSession: []}], parameters: [{name: source, in: query, schema: {type: string, enum: [web, account], default: web}}, {name: status, in: query, schema: {type: string}}, {$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}], responses: {'200': {$ref: '#/components/responses/AdminPage'}}} /admin/v1/deletion-requests/{id}: patch: {operationId: adminProcessDeletionRequest, tags: [Admin], summary: 'Mark a web deletion request processed or rejected', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [status], properties: {status: {type: string, enum: [processed, rejected, open]}, note: {type: string, maxLength: 1000}}}}}}, responses: {'204': {description: Updated}}} /admin/v1/config/versions: get: {operationId: adminListClientVersions, tags: [Admin], summary: 'Minimum supported / latest client versions', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} put: {operationId: adminSetClientVersions, tags: [Admin], summary: 'Set versions for a platform and flavor (''*'' = any)', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [platform, flavor, minSupportedVersion, latestVersion], properties: {platform: {type: string}, flavor: {type: string}, minSupportedVersion: {type: string}, latestVersion: {type: string}}}}}}, responses: {'204': {description: Saved}}} /admin/v1/config/flags: get: {operationId: adminListFlags, tags: [Admin], summary: 'Feature flags and kill switches', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/config/flags/{key}: put: {operationId: adminUpsertFlag, tags: [Admin], summary: 'Create or update a flag / kill switch (targeting, rollout)', security: [{adminSession: []}], parameters: [{name: key, in: path, required: true, schema: {type: string}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [kind], properties: {kind: {type: string, enum: [flag, kill_switch]}, value: {}, enabled: {type: boolean}, description: {type: string}, platforms: {type: array, items: {type: string}}, flavors: {type: array, items: {type: string}}, minVersion: {type: string}, maxVersion: {type: string}, rolloutPercent: {type: integer, minimum: 0, maximum: 100}}}}}}, responses: {'204': {description: Saved}}} delete: {operationId: adminDeleteFlag, tags: [Admin], summary: 'Delete a flag', security: [{adminSession: []}], parameters: [{name: key, in: path, required: true, schema: {type: string}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: Deleted}}} /admin/v1/config/announcements: get: {operationId: adminListAnnouncements, tags: [Admin], summary: 'Announcements', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} post: {operationId: adminCreateAnnouncement, tags: [Admin], summary: 'Create an announcement ({fa, ar, en} texts, optional https url, audience: platforms / flavors / plans [free, plus, pro, business] / versions, startsAt-endsAt window)', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/config/announcements/{id}: put: {operationId: adminUpdateAnnouncement, tags: [Admin], summary: 'Replace an announcement', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, additionalProperties: true}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}}} delete: {operationId: adminDeleteAnnouncement, tags: [Admin], summary: 'Delete an announcement', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: Deleted}}} /admin/v1/config/holidays: get: {operationId: adminListHolidays, tags: [Admin], summary: 'Holidays of a country and Gregorian year', security: [{adminSession: []}], parameters: [{name: country, in: query, required: true, schema: {type: string}}, {name: year, in: query, required: true, schema: {type: integer}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} post: {operationId: adminUpsertHoliday, tags: [Admin], summary: 'Create or update a holiday (keyed by country, date and key)', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [country, date, key, name, isOff], properties: {country: {type: string}, date: {type: string, format: date}, key: {type: string}, name: {type: object}, isOff: {type: boolean}, isEstimated: {type: boolean}, kind: {type: string, enum: [official, religious, national, observance]}, calendar: {type: string, enum: [gregorian, jalali, hijri]}}}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/config/holidays/{id}: delete: {operationId: adminDeleteHoliday, tags: [Admin], summary: 'Delete a holiday', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: Deleted}}} /admin/v1/releases: get: {operationId: adminListReleases, tags: [Admin], summary: 'Direct-APK releases', security: [{adminSession: []}], parameters: [{name: flavor, in: query, schema: {type: string}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} post: {operationId: adminPublishRelease, tags: [Admin], summary: 'Publish a signed release (served by /v1/app/latest)', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [flavor, version, versionCode, url, sha256, sizeBytes], properties: {flavor: {type: string}, channel: {type: string, enum: [stable, beta]}, version: {type: string}, versionCode: {type: integer}, url: {type: string}, sha256: {type: string}, sizeBytes: {type: integer}, notes: {type: object}, mandatory: {type: boolean}, minSupportedVersionCode: {type: integer}, publishedAt: {type: string, format: date-time}}}}}}, responses: {'201': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/releases/{id}/withdraw: post: {operationId: adminWithdrawRelease, tags: [Admin], summary: 'Withdraw a release', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'204': {description: Withdrawn}}} /admin/v1/push/status: get: {operationId: adminPushStatus, tags: [Admin], summary: 'Push channels: configuration, subscription and link counts, deliveries in the last 24 h', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/push/bots/{kind}/webhook: post: {operationId: adminRegisterBotWebhook, tags: [Admin], summary: 'Register the Telegram bot''s webhook ({PUBLIC_API_URL}/v1/bots/{kind}/webhook with the secret). Refused (409) for Bale: its updates belong to the bot service''s long polling', security: [{adminSession: []}], parameters: [{name: kind, in: path, required: true, schema: {type: string, enum: [telegram, bale]}}, {$ref: '#/components/parameters/IdempotencyKey'}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '409': {$ref: '#/components/responses/Conflict'}, '503': {$ref: '#/components/responses/Unavailable'}}} /admin/v1/billing/orders: get: {operationId: adminListOrders, tags: [Admin], summary: 'Bale orders (filters status, plan, userId), newest first', security: [{adminSession: []}], parameters: [{name: status, in: query, schema: {type: string, enum: [pending, paid, failed, expired]}}, {name: plan, in: query, schema: {type: string, enum: [plus, pro]}}, {name: userId, in: query, schema: {type: string, format: uuid}}, {$ref: '#/components/parameters/Limit'}, {$ref: '#/components/parameters/Cursor'}], responses: {'200': {$ref: '#/components/responses/AdminPage'}, '422': {$ref: '#/components/responses/Validation'}}} /admin/v1/billing/orders/stats: get: {operationId: adminOrderStats, tags: [Admin], summary: 'Order counts by status, paid in the last 30 days and in total (Toman), whether payments are enabled', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/billing/pricing: get: {operationId: adminGetPricing, tags: [Admin], summary: 'USD rate in Toman, coefficients and the resulting prices (internal: never sent to clients)', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} put: {operationId: adminSetPricing, tags: [Admin], summary: 'Set the USD rate in Toman (1,000 – 1,000,000,000); prices follow (monthly = rate × coefficient rounded to 1,000, yearly = 10 × monthly)', security: [{adminSession: []}], parameters: [{$ref: '#/components/parameters/IdempotencyKey'}], requestBody: {required: true, content: {application/json: {schema: {type: object, required: [usdRateToman], properties: {usdRateToman: {type: integer, minimum: 1000, maximum: 1000000000}}}}}}, responses: {'200': {$ref: '#/components/responses/AdminJson'}, '422': {$ref: '#/components/responses/Validation'}}} /admin/v1/billing/orders/{id}/events: get: {operationId: adminOrderProviderEvents, tags: [Admin], summary: 'Provider audit trail of an order (Zibal request, callback, verify, inquiry answers)', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/referrals/stats: get: {operationId: adminReferralStats, tags: [Admin], summary: 'Referral totals, last 30 days, guard hits by reason, top inviters, recent referrals', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/reports: get: {operationId: adminReports, tags: [Admin], summary: 'Analytics for the last N days (Iran days) with the previous period for comparison: users (new, DAU/WAU/MAU, sync-active), paying accounts, conversion, churn, referrals, support (median first response), reminder deliveries, bots/tokens/OAuth, devices by platform and app version, daily series; revenue (Toman, paid Zibal/Bale orders, MRR) only with the revenue permission. Cached 2 minutes', security: [{adminSession: []}], parameters: [{name: days, in: query, schema: {type: integer, enum: [7, 30, 90, 365], default: 30}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '422': {$ref: '#/components/responses/Validation'}}} /admin/v1/integrations/overview: get: {operationId: adminIntegrationsOverview, tags: [Admin], summary: 'OAuth/MCP clients with grant counts, Telegram/Bale bot link counts, personal access token counts and reminder deliveries of the last 7 days (counts only; no tokens or chat ids)', security: [{adminSession: []}], responses: {'200': {$ref: '#/components/responses/AdminJson'}}} /admin/v1/users/{id}/timeline: get: {operationId: adminUserTimeline, tags: [Admin], summary: 'Account history, newest first (max 300): sign-up, devices, sessions, grants, orders (billing permission), tickets, referrals, bot links, tokens, OAuth grants, staff actions (audit permission). Audited', security: [{adminSession: []}], parameters: [{name: id, in: path, required: true, schema: {type: string, format: uuid}}], responses: {'200': {$ref: '#/components/responses/AdminJson'}, '404': {$ref: '#/components/responses/NotFound'}}} # ── Public API v1, webhooks, mini-apps (agent E, 1.3.12) ── /api/v1: get: operationId: apiV1Index tags: [Public API] summary: 'API index (version and documentation links)' security: [] responses: '200': {description: OK} /api/v1/me: get: operationId: apiV1Me tags: [Public API] summary: 'The token user, scopes, locale and time zone' security: [{personalToken: []}] responses: '200': {description: Me} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`limit_exceeded` (needs Pro, feature api.webhooks) or `insufficient_scope`'} '429': {description: '`rate_limited`'} /api/v1/today: get: operationId: apiV1Today tags: [Public API] summary: 'Today agenda and the overdue count' security: [{personalToken: []}] responses: '200': {description: Summary} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`limit_exceeded` (needs Pro, feature api.webhooks) or `insufficient_scope`'} '429': {description: '`rate_limited`'} /api/v1/items: get: operationId: apiV1ListItems tags: [Public API] summary: 'Items in a range (recurring items expanded)' security: [{personalToken: []}] parameters: - {name: range, in: query, schema: {type: string, enum: [today, tomorrow, week, overdue, custom], default: today}} - {name: from, in: query, schema: {type: string, format: date}} - {name: to, in: query, schema: {type: string, format: date}, description: at most 62 days after from} - {name: includeDone, in: query, schema: {type: boolean, default: true}} responses: '200': {description: Items, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {$ref: '#/components/schemas/IntegrationItem'}}}}}}} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`limit_exceeded` (needs Pro, feature api.webhooks) or `insufficient_scope`'} '429': {description: '`rate_limited`'} '422': {description: Validation failed} post: operationId: apiV1CreateItem tags: [Public API] summary: 'Create an item from `text` (quick-add parser) or `title` + fields (scope write); send Idempotency-Key to retry safely' security: [{personalToken: []}] requestBody: required: true content: {application/json: {schema: {type: object, properties: {text: {type: string, maxLength: 500}, title: {type: string, maxLength: 300}, date: {type: string, format: date}, time: {type: string, pattern: '^\d{2}:\d{2}$'}, durationMinutes: {type: integer}, reminderMinutesBefore: {type: array, items: {type: integer}}, priority: {type: string, enum: [none, low, medium, high, urgent]}, notes: {type: string, maxLength: 2000}}}}} responses: '201': {description: Created, content: {application/json: {schema: {type: object, properties: {item: {$ref: '#/components/schemas/IntegrationItem'}}}}}} '401': {$ref: '#/components/responses/Unauthorized'} '403': {description: '`limit_exceeded` (needs Pro, feature api.webhooks) or `insufficient_scope`'} '422': {description: Validation failed} /api/v1/items/search: get: operationId: apiV1SearchItems tags: [Public API] summary: 'Search titles' security: [{personalToken: []}] parameters: - {name: q, in: query, required: true, schema: {type: string, maxLength: 100}} - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 50, default: 20}} responses: '200': {description: Items} '401': {$ref: '#/components/responses/Unauthorized'} /api/v1/items/{id}: get: operationId: apiV1GetItem tags: [Public API] summary: 'One item' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '200': {description: Item} '404': {description: '`not_found`'} delete: operationId: apiV1DeleteItem tags: [Public API] summary: 'Delete an item (scope write)' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '204': {description: Deleted} '404': {description: '`not_found`'} /api/v1/items/{id}/complete: post: operationId: apiV1CompleteItem tags: [Public API] summary: 'Mark done (`done: false` reopens); `occurrenceStart` (UTC ms) for one occurrence' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} requestBody: required: true content: {application/json: {schema: {type: object, properties: {done: {type: boolean, default: true}, occurrenceStart: {type: integer}}}}} responses: '200': {description: Item} '404': {description: '`not_found`'} /api/v1/items/{id}/snooze: post: operationId: apiV1SnoozeItem tags: [Public API] summary: 'Snooze the reminder by `minutes` (1–10080) or to `tomorrow` 09:00' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} requestBody: required: true content: {application/json: {schema: {type: object, properties: {minutes: {type: integer}, tomorrow: {type: boolean}}}}} responses: '200': {description: OK} /api/v1/webhooks: get: operationId: apiV1ListWebhooks tags: [Webhooks] summary: 'List webhooks (also under /v1/developer/webhooks with the app session)' security: [{personalToken: []}] responses: '200': {description: Webhooks, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {$ref: '#/components/schemas/Webhook'}}}}}}} post: operationId: apiV1CreateWebhook tags: [Webhooks] summary: 'Create a webhook (at most 10); the response carries `secret` once' security: [{personalToken: []}] requestBody: required: true content: {application/json: {schema: {type: object, required: [url, events], properties: {url: {type: string, format: uri, description: public https URL}, events: {type: array, minItems: 1, items: {type: string, enum: [item.created, item.updated, item.completed, reminder.fired, booking.requested]}}, description: {type: string, maxLength: 120}}}}} responses: '201': {description: Created, content: {application/json: {schema: {$ref: '#/components/schemas/Webhook'}}}} '403': {description: '`limit_exceeded` (needs Pro, feature api.webhooks) or `insufficient_scope`'} '409': {description: '`conflict` (10 webhooks)'} '422': {description: Validation failed} /api/v1/webhooks/{id}: get: operationId: apiV1GetWebhook tags: [Webhooks] summary: 'One webhook' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '200': {description: Webhook, content: {application/json: {schema: {$ref: '#/components/schemas/Webhook'}}}} '404': {description: '`not_found`'} patch: operationId: apiV1UpdateWebhook tags: [Webhooks] summary: 'Change url, events, description or active (re-enabling resets the failure count)' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} requestBody: required: true content: {application/json: {schema: {type: object, properties: {url: {type: string}, events: {type: array, items: {type: string}}, description: {type: string}, active: {type: boolean}}}}} responses: '200': {description: OK} delete: operationId: apiV1DeleteWebhook tags: [Webhooks] summary: 'Delete a webhook and its delivery log' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '204': {description: Deleted} /api/v1/webhooks/{id}/test: post: operationId: apiV1TestWebhook tags: [Webhooks] summary: 'Send a `ping` now; returns the delivery' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '200': {description: Delivery, content: {application/json: {schema: {$ref: '#/components/schemas/WebhookDelivery'}}}} /api/v1/webhooks/{id}/rotate-secret: post: operationId: apiV1RotateWebhookSecret tags: [Webhooks] summary: 'New signing secret (shown once); the old one stops working at once' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '200': {description: OK} /api/v1/webhooks/{id}/deliveries: get: operationId: apiV1WebhookDeliveries tags: [Webhooks] summary: 'Delivery log, newest first (30 days)' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 50}} responses: '200': {description: Deliveries, content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {$ref: '#/components/schemas/WebhookDelivery'}}}}}}} /api/v1/webhooks/{id}/deliveries/{delivery}/redeliver: post: operationId: apiV1Redeliver tags: [Webhooks] summary: 'Send a delivery again (same event id)' security: [{personalToken: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} - {name: delivery, in: path, required: true, schema: {type: string, format: uuid}} responses: '200': {description: OK} /v1/developer: get: operationId: developerOverview tags: [Webhooks] summary: 'App settings data: plan, API base URL, webhooks, mini-app URLs and links (session)' security: [{bearerAuth: []}] responses: '200': {description: OK} /v1/mini/config: get: operationId: miniConfig tags: [Mini-apps] summary: 'Which platforms are configured' security: [] responses: '200': {description: OK} /v1/mini/session: post: operationId: miniSession tags: [Mini-apps] summary: 'Verify initData; a linked user gets a session, otherwise linked:false' security: [] requestBody: required: true content: {application/json: {schema: {type: object, required: [platform, initData], properties: {platform: {type: string, enum: [telegram, bale, eitaa]}, initData: {type: string, maxLength: 8192}}}}} responses: '200': {description: 'linked, token, expiresIn, locale, timeZone, calendar, digits, name'} '401': {description: '`init_data_invalid`'} '503': {description: '`provider_not_configured`'} /v1/mini/link: post: operationId: miniLink tags: [Mini-apps] summary: 'Link the messenger user with the 8-digit code from the app' security: [] requestBody: required: true content: {application/json: {schema: {type: object, required: [platform, initData, code], properties: {platform: {type: string}, initData: {type: string}, code: {type: string, pattern: '^[0-9]{8}$'}}}}} responses: '200': {description: Session} '400': {description: '`link_code_invalid`'} /v1/mini/link-code: post: operationId: miniLinkCode tags: [Mini-apps] summary: 'One-time 8-digit code (10 minutes) for linking a mini-app (app session)' security: [{bearerAuth: []}] responses: '201': {description: 'code, expiresAt'} /v1/mini/links: get: operationId: miniLinks tags: [Mini-apps] summary: 'Linked mini-app users (app session)' security: [{bearerAuth: []}] responses: '200': {description: OK} /v1/mini/links/{platform}: delete: operationId: miniUnlink tags: [Mini-apps] summary: 'Remove a mini-app link' security: [{bearerAuth: []}] parameters: - {name: platform, in: path, required: true, schema: {type: string, enum: [telegram, bale, eitaa]}} responses: '204': {description: Removed} /v1/mini/today: get: operationId: miniToday tags: [Mini-apps] summary: 'Today items, overdue, habits and prayer times (sensitive types hidden)' security: [{miniSession: []}] responses: '200': {description: OK} /v1/mini/items: get: operationId: miniItems tags: [Mini-apps] summary: 'Items of a range' security: [{miniSession: []}] parameters: - {name: range, in: query, schema: {type: string, enum: [today, tomorrow, week, overdue], default: week}} responses: '200': {description: OK} post: operationId: miniQuickAdd tags: [Mini-apps] summary: 'Quick add (natural language)' security: [{miniSession: []}] requestBody: required: true content: {application/json: {schema: {type: object, required: [text], properties: {text: {type: string, maxLength: 500}}}}} responses: '201': {description: Created} /v1/mini/items/{id}/complete: post: operationId: miniComplete tags: [Mini-apps] summary: 'Mark done or reopen' security: [{miniSession: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '200': {description: OK} /v1/mini/habits: get: operationId: miniHabits tags: [Mini-apps] summary: 'Today habits with progress' security: [{miniSession: []}] responses: '200': {description: OK} /v1/mini/habits/{id}/checkin: post: operationId: miniHabitCheckIn tags: [Mini-apps] summary: '+1 on today habit log' security: [{miniSession: []}] parameters: - {name: id, in: path, required: true, schema: {type: string, format: uuid}} responses: '200': {description: OK} /v1/mini/prayer: get: operationId: miniPrayer tags: [Mini-apps] summary: 'Prayer times at the saved location' security: [{miniSession: []}] parameters: - {name: date, in: query, schema: {type: string, format: date}} responses: '200': {description: OK} components: securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT (EdDSA, typ at+jwt, 15 minutes) metricsToken: type: http scheme: bearer personalToken: type: http scheme: bearer bearerFormat: Personal access token (bzp_ + 40 characters) miniSession: type: http scheme: bearer bearerFormat: Mini-app session (bzm.., 12 hours) botSecret: type: apiKey in: header name: X-Bot-Secret description: BOT_INTERNAL_SECRET shared by the API and the Bale bot service (internal network only) adminSession: type: http scheme: bearer bearerFormat: Opaque staff session (bzs_…), also accepted from the HttpOnly bz_admin cookie (used when no bearer, or a stale bearer of the same staff member, is sent; cookie-authenticated mutations need the admin Origin) parameters: IdempotencyKey: name: Idempotency-Key in: header required: true description: Unique per user action; reuse only to retry the identical request. schema: {type: string, pattern: '^[A-Za-z0-9_\-:.]{8,128}$'} IdempotencyKeyOptional: name: Idempotency-Key in: header required: false schema: {type: string, pattern: '^[A-Za-z0-9_\-:.]{8,128}$'} Limit: name: limit in: query schema: {type: integer, minimum: 1, maximum: 200, default: 50} Cursor: name: cursor in: query description: Opaque `nextCursor` of the previous page (tamper-evident). schema: {type: string} WorkspaceId: name: id in: path required: true schema: {type: string, format: uuid} InviteCode: name: code in: path required: true description: 8-character code (with or without dash) or the link token. schema: {type: string, maxLength: 128} requestBodies: Code: required: true content: application/json: schema: type: object required: [code] properties: code: {type: string, maxLength: 20} OAuthSignIn: required: true content: application/json: schema: allOf: - $ref: '#/components/schemas/SignInContext' - type: object required: [idToken] properties: idToken: {type: string, maxLength: 8192} nonce: {type: string, maxLength: 256} responses: AdminJson: description: JSON result (see the admin console contract) content: {application/json: {schema: {type: object, additionalProperties: true}}} AdminPage: description: Cursor page `{items, nextCursor}` content: {application/json: {schema: {type: object, properties: {items: {type: array, items: {type: object, additionalProperties: true}}, nextCursor: {type: [string, 'null']}}}}} Problem: description: Error (see `code`) content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} Validation: description: '`validation_failed` (or `invalid_phone` / `invalid_email`) with field errors' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} Unauthorized: description: '`auth_required`, `token_invalid`, `token_expired`, `session_revoked`, `refresh_invalid`, `refresh_reused`' headers: {WWW-Authenticate: {schema: {type: string}}} content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} StepUp: description: '`step_up_required` (extension `maxAgeSeconds`) or another 401 code' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} Forbidden: description: '`forbidden`, `account_pending_deletion`, `account_disabled`, `country_not_allowed`, `limit_exceeded`, `oauth_unavailable_in_region`' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} NotFound: description: '`not_found`, `route_not_found`, `workspace_not_found`, `member_not_found`, `invite_not_found`' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} Conflict: description: '`conflict`, `identity_in_use`, `last_owner`, `last_identity`, `mfa_*`, `refresh_superseded`, `workspace_id_taken`, `personal_workspace_immutable`, `idempotency_in_progress`, …' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} Gone: description: '`invite_expired`, `invite_revoked`, `invite_exhausted`' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} TooManyRequests: description: '`rate_limited`, `otp_throttled`, `otp_velocity_limited`, `otp_attempts_exceeded`, `mfa_attempts_exceeded` (extension `retryAfter` seconds)' headers: {Retry-After: {schema: {type: integer}}} content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} Unavailable: description: '`service_unavailable`, `provider_not_configured`, `export_unavailable`' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} OtpProblem: description: '`otp_invalid` (extension `attemptsRemaining`), `otp_expired`, `otp_attempts_exceeded`, `mfa_invalid`, `oauth_token_invalid`' content: {application/problem+json: {schema: {$ref: '#/components/schemas/Problem'}}} SignIn: description: Signed in, or a second factor is required content: application/json: schema: oneOf: - $ref: '#/components/schemas/SignInResult' - $ref: '#/components/schemas/MfaRequired' discriminator: {propertyName: status} schemas: Webhook: type: object properties: id: {type: string, format: uuid} url: {type: string} description: {type: string} events: {type: array, items: {type: string}} active: {type: boolean} disabledReason: {type: [string, 'null'], description: 'failing or plan'} consecutiveFailures: {type: integer} lastSuccessAt: {type: [string, 'null'], format: date-time} lastFailureAt: {type: [string, 'null'], format: date-time} createdAt: {type: string, format: date-time} updatedAt: {type: string, format: date-time} secret: {type: string, description: 'only on create and rotate-secret (whsec_...)'} WebhookDelivery: type: object properties: id: {type: string, format: uuid} event: {type: string} eventId: {type: string, description: same for every retry and redelivery} status: {type: string, enum: [pending, succeeded, failed]} attempts: {type: integer} nextAttemptAt: {type: [string, 'null'], format: date-time} lastStatus: {type: [integer, 'null']} lastError: {type: [string, 'null']} durationMs: {type: [integer, 'null']} createdAt: {type: string, format: date-time} deliveredAt: {type: [string, 'null'], format: date-time} payload: {type: object, description: 'id, type, createdAt, apiVersion, data (the exact POSTed body)'} BotLink: type: object properties: kind: {type: string, enum: [telegram, bale]} username: {type: [string, 'null']} active: {type: boolean} linkedAt: {type: string, format: date-time} reminders: {type: boolean, description: every reminder of the account is also sent to this chat (needs reminders.remote)} digestTime: {type: [string, 'null'], description: morning digest time (HH:MM in the user's zone)} PersonalToken: type: object properties: id: {type: string, format: uuid} name: {type: string} prefix: {type: string, description: first 12 characters, to tell tokens apart} scopes: {type: array, items: {type: string, enum: [read, write]}} createdAt: {type: string, format: date-time} expiresAt: {type: [string, 'null'], format: date-time} lastUsedAt: {type: [string, 'null'], format: date-time} useCount: {type: integer} revokedAt: {type: [string, 'null'], format: date-time} active: {type: boolean} IntegrationItem: type: object properties: id: {type: string, format: uuid} workspaceId: {type: string, format: uuid} title: {type: string} status: {type: string} date: {type: [string, 'null'], format: date} time: {type: [string, 'null']} allDay: {type: boolean} kind: {type: string, enum: [scheduled, due]} at: {type: [string, 'null'], format: date-time} endAt: {type: [string, 'null'], format: date-time} recurring: {type: boolean} occurrenceStart: {type: [integer, 'null'], description: UTC ms of the occurrence (recurring items)} Problem: type: object description: RFC 9457 problem details with a stable machine code. required: [type, title, status, code] properties: type: {type: string, format: uri, examples: ['https://api.barzaman.ir/problems/otp_invalid']} title: {type: string, description: English summary (clients localize by code)} status: {type: integer} code: {$ref: '#/components/schemas/ProblemCode'} detail: {type: string} instance: {type: string, description: Request path} requestId: {type: string} errors: type: array items: type: object required: [field, code] properties: field: {type: string, examples: [device.platform]} code: {type: string, enum: [required, type, invalid, too_short, too_long, one_of, out_of_range, undeliverable]} message: {type: string} retryAfter: {type: integer} attemptsRemaining: {type: integer} maxAgeSeconds: {type: integer} feature: {type: string, description: Entitlement key for limit_exceeded} limit: {type: integer} additionalProperties: true ProblemCode: type: string enum: - validation_failed - invalid_json - unsupported_media_type - payload_too_large - not_found - route_not_found - method_not_allowed - forbidden - conflict - internal_error - service_unavailable - timeout - rate_limited - invalid_cursor - feature_unavailable - provider_not_configured - limit_exceeded - origin_not_allowed - idempotency_key_required - idempotency_key_invalid - idempotency_key_mismatch - idempotency_in_progress - auth_required - token_invalid - insufficient_scope - token_expired - session_revoked - step_up_required - account_pending_deletion - account_disabled - invalid_phone - invalid_email - country_not_allowed - otp_throttled - otp_velocity_limited - otp_invalid - otp_expired - otp_attempts_exceeded - otp_delivery_failed - sms_unavailable - phone_verification_required - oauth_token_invalid - oauth_unavailable_in_region - refresh_invalid - refresh_reused - refresh_superseded - mfa_required - mfa_invalid - mfa_token_invalid - mfa_already_enabled - mfa_not_enabled - mfa_not_enrolled - mfa_attempts_exceeded - identity_in_use - no_identity_for_channel - last_identity - identifier_taken - invalid_identifier - weak_password - invalid_credentials - reset_token_invalid - account_not_pending_deletion - export_unavailable - export_in_progress - workspace_not_found - personal_workspace_immutable - last_owner - member_not_found - invite_not_found - invite_expired - invite_revoked - invite_exhausted - workspace_id_taken - clock_skew - schema_version_unsupported - resync_required - device_limit_exceeded - device_mismatch - signature_invalid - url_expired - attachment_not_found - attachment_id_taken - upload_offset_mismatch - upload_in_progress - upload_incomplete - chunk_too_small - range_invalid - range_not_satisfiable - checksum_mismatch - length_required - attachment_type_blocked - too_many_uploads - release_not_found - init_data_invalid - link_code_invalid - price_unavailable - unknown_product - purchase_invalid - purchase_pending - purchase_not_active - purchase_owned_by_another_account - provider_error - checkout_not_found - checkout_not_allowed - promo_invalid - promo_expired - promo_exhausted - promo_already_redeemed - redeem_not_allowed - trial_unavailable - webhook_signature_invalid - entitlement_signing_unavailable - usage_limit_reached - payment_amount_mismatch - order_not_payable - push_endpoint_not_allowed - push_subscription_not_found - pow_required - pow_invalid - ticket_not_found - ticket_closed - admin_credentials_invalid - admin_account_locked - admin_mfa_required - admin_totp_invalid - admin_ip_not_allowed - admin_password_change_required - admin_weak_password - staff_email_taken - admin_last_owner - form_expired - handle_taken - booking_page_missing - slot_taken - too_many_bookings - code_space - shift_over - swap_not_pending - item_not_found - share_blocked_private - share_sensitive_confirm - share_self - share_user_not_found - share_invite_invalid - share_view_only - plan_required - audio_too_large - audio_too_long - audio_invalid - transcript_empty - asr_unavailable - asr_timeout - item_refused - voice_in_progress - undo_expired Locale: type: string enum: [fa, ar, en] default: fa description: UI language; locale tags such as fa-IR are accepted (primary subtag used). ClientDeviceId: type: string pattern: '^[A-Za-z0-9._:\-]{8,128}$' description: Stable installation id generated by the client. DeviceInfo: type: object properties: platform: {type: string, enum: [android, ios, web, other]} model: {type: string, maxLength: 100} osVersion: {type: string, maxLength: 50} appVersion: {type: string, maxLength: 50} flavor: {type: string, maxLength: 30, examples: [bazaar, myket, direct, play, appstore, pwa-ir, pwa-global]} SignInContext: type: object required: [deviceId] properties: deviceId: {$ref: '#/components/schemas/ClientDeviceId'} device: {$ref: '#/components/schemas/DeviceInfo'} locale: {$ref: '#/components/schemas/Locale'} timeZone: {type: string, description: IANA zone used for a new account} personalWorkspaceId: type: string format: uuid description: Id of the local personal workspace the app used before signing up; adopted for a new account when free. OtpRequestResult: type: object required: [challengeId, expiresIn, resendIn, codeLength] properties: challengeId: {type: string, format: uuid} expiresIn: {type: integer, examples: [120]} resendIn: {type: integer, description: Seconds until another code may be requested, examples: [60]} codeLength: {const: 6} TokenBundle: type: object required: [tokenType, accessToken, expiresIn, refreshToken, sessionId, deviceId] properties: tokenType: {const: Bearer} accessToken: {type: string} expiresIn: {type: integer, examples: [900]} accessTokenExpiresAt: {type: string, format: date-time} refreshToken: {type: string, description: Opaque; store securely (Keychain/Keystore)} refreshTokenExpiresAt: {type: string, format: date-time} sessionId: {type: string, format: uuid} deviceId: {type: string, format: uuid, description: Server device id (JWT `did`)} SignInResult: allOf: - $ref: '#/components/schemas/TokenBundle' - type: object required: [status, user, isNewUser] properties: status: {const: ok} isNewUser: {type: boolean} user: {$ref: '#/components/schemas/User'} MfaRequired: type: object required: [status, mfaToken, mfaExpiresIn, methods] properties: status: {const: mfa_required} mfaToken: {type: string} mfaExpiresIn: {type: integer, examples: [300]} methods: {type: array, items: {type: string, enum: [totp, recovery_code]}} Identity: type: object properties: id: {type: string, format: uuid} kind: {type: string, enum: [phone, email, google, apple]} value: {type: ['string', 'null'], description: 'Phone or e-mail; the provider e-mail for google/apple'} verifiedAt: {type: string, format: date-time} lastUsedAt: {type: ['string', 'null'], format: date-time} User: type: object properties: id: {type: string, format: uuid} region: {type: string, enum: [IR, GLOBAL]} status: {type: string, enum: [active, pending_deletion, disabled]} displayName: {type: string} locale: {$ref: '#/components/schemas/Locale'} calendar: {type: string, enum: [gregorian, jalali, hijriUmmAlQura, hijriCivil]} digits: {type: string, enum: [latin, persian, arabicIndic]} weekStart: {type: string, enum: [saturday, sunday, monday]} timeFormat: {type: string, enum: [h24, h12]} timeZone: {type: string} ageConfirmed: {type: boolean} plan: {type: string, enum: [free, plus, pro, business]} mfaEnabled: {type: boolean} hasPassword: {type: boolean, description: The account has a password (accounts created by OTP in 1.0 may not — the app offers "Set a password")} personalWorkspaceId: {type: string, format: uuid} identities: {type: array, items: {$ref: '#/components/schemas/Identity'}} createdAt: {type: string, format: date-time} updatedAt: {type: string, format: date-time} deletion: type: ['object', 'null'] properties: requestedAt: {type: string, format: date-time} scheduledFor: {type: string, format: date-time} Session: type: object properties: id: {type: string, format: uuid} current: {type: boolean} authMethod: {type: string, enum: [phone_otp, email_otp, google, apple]} mfa: {type: boolean} createdAt: {type: string, format: date-time} lastSeenAt: {type: string, format: date-time} lastIp: {type: ['string', 'null']} device: type: object properties: id: {type: string, format: uuid} platform: {type: string} model: {type: string} osVersion: {type: string} appVersion: {type: string} flavor: {type: string} Device: type: object properties: id: {type: string, format: uuid} current: {type: boolean} platform: {type: string} model: {type: string} osVersion: {type: string} appVersion: {type: string} flavor: {type: string} createdAt: {type: string, format: date-time} lastSeenAt: {type: string, format: date-time} signedIn: {type: boolean} activeSessions: {type: integer} ExportJob: type: object properties: id: {type: string, format: uuid} status: {type: string, enum: [queued, running, ready, failed, expired]} format: {type: string, enum: [barzaman]} createdAt: {type: string, format: date-time} completedAt: {type: ['string', 'null'], format: date-time} expiresAt: {type: ['string', 'null'], format: date-time} sizeBytes: {type: ['integer', 'null']} sha256: {type: ['string', 'null']} downloadUrl: {type: ['string', 'null'], format: uri} Role: type: string enum: [owner, editor, commenter, viewer] Workspace: type: object properties: id: {type: string, format: uuid} kind: {type: string, enum: [personal, shared, classroom, clients, org_team]} name: {type: string} color: {type: ['integer', 'null']} icon: {type: ['string', 'null']} settings: {type: object} role: {$ref: '#/components/schemas/Role'} memberCount: {type: integer} createdAt: {type: string, format: date-time} updatedAt: {type: string, format: date-time} deletedAt: {type: string, format: date-time} purgeAfter: {type: string, format: date-time} Member: type: object properties: userId: {type: string, format: uuid} displayName: {type: string} role: {$ref: '#/components/schemas/Role'} joinedAt: {type: string, format: date-time} isYou: {type: boolean} Invite: type: object properties: id: {type: string, format: uuid} role: {$ref: '#/components/schemas/Role'} codeHint: {type: string, examples: ['K7••-••••']} maxUses: {type: integer} useCount: {type: integer} expiresAt: {type: string, format: date-time} createdAt: {type: string, format: date-time} status: {type: string, enum: [active, expired, exhausted, revoked]} CreatedInvite: type: object properties: id: {type: string, format: uuid} workspaceId: {type: string, format: uuid} role: {$ref: '#/components/schemas/Role'} code: {type: string, examples: ['K7MQ-X9PT']} token: {type: string} link: {type: string, format: uri, examples: ['https://app.barzaman.ir/invite/…']} maxUses: {type: integer} useCount: {type: integer} expiresAt: {type: string, format: date-time} createdAt: {type: string, format: date-time} InviteAccepted: type: object properties: joined: {type: boolean} workspace: {$ref: '#/components/schemas/Workspace'} Readiness: type: object properties: status: {type: string, enum: [ready, unavailable, draining]} checks: type: object properties: postgres: {type: string, enum: [ok, fail]} valkey: {type: string, enum: [ok, fail]} # ───────────────────────────── Sync ───────────────────────────── Hlc: type: string description: 'Hybrid logical clock `--`; canonical strings sort as text.' pattern: '^\d{15}-\d{5}-[A-Za-z0-9._:\-]{1,128}$' examples: ['001790533843749-00004-device-7f3a'] SyncOp: type: object required: [opId, scope, entity, entityId, kind, hlc] properties: opId: {type: string, format: uuid, description: Idempotency key of the operation (30 days)} scope: {type: string, format: uuid, description: Workspace id} entity: {type: string, pattern: '^[a-z][a-z0-9_]{0,63}$', description: Client table name, examples: [item, note_block, entity_tag]} entityId: {type: string, format: uuid} kind: {type: string, enum: [upsert, delete, restore]} hlc: {$ref: '#/components/schemas/Hlc'} patch: type: object description: 'upsert only: changed fields (snake_case column names → JSON values). Writing `status` implies `status_source` (default `user`).' additionalProperties: true maxProperties: 256 fieldHlc: {type: object, additionalProperties: {$ref: '#/components/schemas/Hlc'}, description: Per-field HLCs overriding `hlc`} baseFieldHlc: type: object description: '`note_block` text/data: the field HLC the edit started from (null = none) — enables conflict copies' additionalProperties: {oneOf: [{$ref: '#/components/schemas/Hlc'}, {type: 'null'}]} SyncPushRequest: type: object required: [deviceId, schemaVersion, ops] properties: deviceId: {type: string, pattern: '^[A-Za-z0-9._:\-]{8,128}$', description: The client device id of this session (also the HLC device part)} schemaVersion: {type: integer, minimum: 1, description: Client schema version; the server accepts its current and two previous versions} ops: {type: array, maxItems: 500, items: {$ref: '#/components/schemas/SyncOp'}} SyncOpResult: type: object required: [opId, status] properties: opId: {type: string, format: uuid} status: {type: string, enum: [applied, superseded, rejected]} serverSeq: {type: integer, description: 'applied: the row''s new sequence number'} duplicate: {type: boolean, description: The opId was processed before; the stored result is returned} reason: type: string enum: [not_member, read_only, limit_exceeded, scope_mismatch, entity_not_syncable, invalid_op, row_too_large, op_id_conflict] detail: {type: string, description: 'invalid_op: which part is malformed'} feature: {type: string, description: 'limit_exceeded: entitlement key'} limit: {type: integer} upgrade: {type: boolean} maxBytes: {type: integer} conflicts: type: array description: Note-block conflict copies created for this op items: type: object properties: field: {type: string} copyId: {type: string, format: uuid} SyncPushResponse: type: object properties: results: {type: array, items: {$ref: '#/components/schemas/SyncOpResult'}, description: '`results[i]` answers `ops[i]`'} scopes: type: array items: type: object properties: scope: {type: string, format: uuid} serverSeq: {type: integer} serverTime: {type: string, format: date-time} serverTimeMs: {type: integer} SyncRow: type: object properties: entity: {type: string} id: {type: string, format: uuid} fields: {type: object, additionalProperties: true} fieldHlc: {type: object, additionalProperties: {$ref: '#/components/schemas/Hlc'}} rowHlc: {type: string, description: Largest winning HLC among fields and tombstone registers} deletedHlc: {type: ['string', 'null']} restoredHlc: {type: ['string', 'null']} deleted: {type: boolean} deletedAt: {type: ['integer', 'null'], description: Physical ms of deletedHlc when deleted} serverSeq: {type: integer} SyncPullResponse: type: object properties: scope: {type: string, format: uuid} items: {type: array, items: {$ref: '#/components/schemas/SyncRow'}} nextCursor: {type: string} hasMore: {type: boolean} serverSeq: {type: integer} serverTime: {type: string, format: date-time} SyncSnapshotResponse: type: object properties: scope: {type: string, format: uuid} items: {type: array, items: {$ref: '#/components/schemas/SyncRow'}} snapshotSeq: {type: integer} hasMore: {type: boolean} nextPageToken: {type: ['string', 'null']} cursor: {type: ['string', 'null'], description: 'Last page: the pull cursor at snapshotSeq'} serverTime: {type: string, format: date-time} SyncScope: type: object properties: scope: {type: string, format: uuid} kind: {type: string, enum: [personal, shared, classroom, clients, org_team]} role: {$ref: '#/components/schemas/Role'} canWrite: {type: boolean} serverSeq: {type: integer} # ───────────────────────────── Storage ───────────────────────────── AttachmentUploadRequest: type: object required: [workspaceId, sha256, size, mime, fileName] properties: id: {type: string, format: uuid, description: Proposed id (= the `attachment` sync row id)} workspaceId: {type: string, format: uuid} sha256: {type: string, pattern: '^[0-9a-fA-F]{64}$'} size: {type: integer, minimum: 0} mime: {type: string, maxLength: 255, examples: [image/jpeg, application/pdf]} fileName: {type: string, maxLength: 255, description: No path separators or control characters} Attachment: type: object properties: id: {type: string, format: uuid} workspaceId: {type: string, format: uuid} status: {type: string, enum: [pending, complete]} fileName: {type: string} mime: {type: string} size: {type: integer} sha256: {type: string} receivedBytes: {type: integer} createdBy: {type: ['string', 'null'], format: uuid} createdAt: {type: string, format: date-time} completedAt: {type: ['string', 'null'], format: date-time} AttachmentUploadSession: allOf: - $ref: '#/components/schemas/Attachment' - type: object properties: uploadUrl: {type: ['string', 'null'], format: uri, description: Signed PUT URL (15 minutes); null when already complete} uploadMethod: {type: ['string', 'null'], enum: [PUT, null]} expiresAt: {type: ['string', 'null'], format: date-time} chunkBytes: {type: integer, description: Suggested chunk size} minChunkBytes: {type: integer} maxChunkBytes: {type: integer} UploadProgress: type: object properties: id: {type: string, format: uuid} receivedBytes: {type: integer} size: {type: integer} complete: {type: boolean, description: Every byte received — call complete next} AttachmentDownload: allOf: - $ref: '#/components/schemas/Attachment' - type: object properties: url: {type: string, format: uri} expiresAt: {type: string, format: date-time} # ───────────────────────────── Config ───────────────────────────── LocalizedText: type: object description: Text in every app language (missing languages fall back to English, then Persian). properties: fa: {type: string} ar: {type: string} en: {type: string} Announcement: type: object properties: id: {type: string, format: uuid} severity: {type: string, enum: [info, warning, critical]} title: {$ref: '#/components/schemas/LocalizedText'} body: {$ref: '#/components/schemas/LocalizedText'} url: {type: ['string', 'null'], format: uri} startsAt: {type: string, format: date-time} endsAt: {type: ['string', 'null'], format: date-time} dismissible: {type: boolean} plans: {type: ['array', 'null'], items: {type: string, enum: [free, plus, pro, business]}, description: 'Plan audience (null = every plan; only in GET /v1/announcements)'} RemoteConfig: type: object properties: platform: {type: string} flavor: {type: string} version: {type: string} minSupportedVersion: {type: string, description: '0.0.0 when unset'} latestVersion: {type: ['string', 'null']} updateRequired: {type: boolean, description: The version is below minSupportedVersion (never blocks offline use of local data)} updateAvailable: {type: boolean} flags: {type: object, additionalProperties: true} killSwitches: {type: object, additionalProperties: {type: boolean}, description: 'true = feature off'} announcements: {type: array, items: {$ref: '#/components/schemas/Announcement'}} ttlSeconds: {type: integer} Holiday: type: object properties: id: {type: string, format: uuid} key: {type: string, examples: [ir.nowruz.1]} date: {type: string, format: date, description: Gregorian date} name: {$ref: '#/components/schemas/LocalizedText'} isOff: {type: boolean} isEstimated: {type: boolean, description: Lunar dates not yet officially announced} kind: {type: string, enum: [official, religious, national, observance]} calendar: {type: string, enum: [gregorian, jalali, hijri], description: The calendar the holiday is defined in} source: {type: string} HolidayList: type: object properties: country: {type: string} from: {type: string, format: date} to: {type: string, format: date} items: {type: array, items: {$ref: '#/components/schemas/Holiday'}} updatedAt: {type: ['string', 'null'], format: date-time} AppRelease: type: object properties: flavor: {type: string} channel: {type: string, enum: [stable, beta]} version: {type: string} versionCode: {type: integer} url: {type: string, format: uri} sha256: {type: string} sizeBytes: {type: integer} notes: {$ref: '#/components/schemas/LocalizedText'} mandatory: {type: boolean} minSupportedVersionCode: {type: ['integer', 'null']} publishedAt: {type: string, format: date-time} signature: {type: string, description: base64url Ed25519 signature over the canonical JSON of the other fields} keyId: {type: string} signatureAlgorithm: {type: string, const: Ed25519} Pricing: type: object properties: region: {type: string, enum: [IR, GLOBAL]} flavor: {type: string} source: {type: string, enum: [billing, defaults]} pricesAvailable: {type: boolean} plans: type: array items: type: object properties: plan: {type: string, enum: [free, plus, pro, business]} tier: {type: integer} features: {type: object, additionalProperties: true} prices: {type: array, items: {type: object, additionalProperties: true}} additionalProperties: true # ── Billing, push, support and admin (billing/push/admin/support modules) ── Flavor: type: string enum: [bazaar, myket, direct, pwa-ir, play, appstore, pwa-global, dev] Price: type: object properties: id: {type: string, format: uuid} productId: {type: string, enum: [plus, pro, business]} plan: {type: string} provider: {type: string, enum: [zarinpal, bazaar, myket, google_play, apple, paddle, stripe]} kind: {type: string, enum: [subscription, time_pack]} billingPeriod: {type: [string, 'null'], enum: [month, quarter, half_year, year, null]} durationDays: {type: [integer, 'null']} currency: {type: string, examples: [IRR, USD]} amount: {type: integer, description: Minor units of the currency (IRR has none)} storeProductId: {type: [string, 'null'], description: SKU / product id / Stripe price / Paddle price} trialDays: {type: integer} label: {type: object, description: '{fa, ar, en}'} checkout: {type: string, enum: [web, store]} BillingCatalog: type: object properties: region: {type: string} flavor: {type: [string, 'null']} currency: {type: [string, 'null'], examples: [IRT]} purchasable: {type: boolean, description: '1.0 store/web prices only (false); release 1.1 clients use paymentsEnabled'} redeemAvailable: {type: boolean} trial: {type: [object, 'null'], properties: {plan: {type: string}, days: {type: integer}}} plans: type: array items: type: object properties: id: {type: string} plan: {type: string, enum: [free, plus, pro, business]} name: {type: object} description: {type: object} highlights: {type: array, items: {type: object}} limits: {type: object, additionalProperties: true, description: Default entitlement matrix of the plan (packages/core)} prices: {type: array, items: {$ref: '#/components/schemas/CatalogPlanPrice'}, description: Release 1.1 owner prices (empty for Free and Business)} legacyPrices: {type: array, items: {$ref: '#/components/schemas/Price'}, description: 1.0 store / web prices (only present when the owner activated some)} contact: {type: object, description: Business only, properties: {bale: {type: string, format: uri}, email: {type: string, format: email}}} inherits: {type: [string, 'null'], enum: [free, plus, pro, null]} features: {type: array, items: {type: string}, description: 'Feature-line ids of packages/core PlanFeatures (what the plan adds), in display order'} featureKeys: {type: array, items: {type: string}, description: Entitlement keys the lines rely on} paymentsEnabled: {type: boolean, description: Bale checkout is configured} ReferralOutcome: type: object required: [applied] properties: applied: {type: boolean, description: Whether the new account got the reward} reason: {type: string, enum: [invalid_code, self, device_reused, already_referred, error]} rewardDays: {type: integer, examples: [30]} rewardPlan: {const: plus} CatalogPlanPrice: type: object required: [period, amountToman, amountRial] properties: period: {type: string, enum: [month, year]} amountToman: {type: integer, examples: [100000]} amountRial: {type: integer, examples: [1000000]} EntitlementTokenResponse: type: object required: [token, keyId, plan, expiresAt, graceUntil, limits, signed] properties: token: {type: string, description: Compact JWS (EdDSA)} keyId: {type: string} plan: {type: string, enum: [free, plus, pro, business]} issuedAt: {type: string, format: date-time} expiresAt: {type: string, format: date-time} graceUntil: {type: string, format: date-time} limits: {type: object, additionalProperties: true} sources: {type: array, items: {$ref: '#/components/schemas/EntitlementSource'}} signed: type: object description: core EntitlementToken JSON (milliseconds) + base64url Ed25519 signature over its signingPayload properties: plan: {type: string} limits: {type: object, additionalProperties: true} issued_at: {type: integer} expires_at: {type: integer} grace_until: {type: integer} account_id: {type: string} signature: {type: string} EntitlementSource: type: object properties: source: {type: string, enum: [subscription, time_pack, promo, staff_comp, org_seat, trial, bale, referral], description: '`bale` = a Bale purchase, `referral` = an invite reward (release 1.1); otherwise the grant source'} plan: {type: string} startsAt: {type: string, format: date-time} endsAt: {type: [string, 'null'], format: date-time} renewing: {type: boolean} Jwks: type: object properties: keys: {type: array, items: {type: object, properties: {kty: {const: OKP}, crv: {const: Ed25519}, x: {type: string}, kid: {type: string}, alg: {const: EdDSA}, use: {const: sig}}}} BillingStatus: type: object properties: plan: {type: string} sources: {type: array, items: {$ref: '#/components/schemas/EntitlementSource'}} subscriptions: {type: array, items: {$ref: '#/components/schemas/Subscription'}} Subscription: type: object properties: id: {type: string, format: uuid} provider: {type: string} storeProductId: {type: [string, 'null']} plan: {type: string} status: {type: string, enum: [active, in_grace, on_hold, paused, canceled, expired, revoked, pending]} autoRenew: {type: boolean} currentPeriodStart: {type: [string, 'null'], format: date-time} currentPeriodEnd: {type: [string, 'null'], format: date-time} graceUntil: {type: [string, 'null'], format: date-time} environment: {type: string, enum: [production, sandbox]} StorePurchase: type: object description: 'Bazaar/Myket/Play: productId + purchaseToken (+ subscription). App Store: signedTransaction (+ signedRenewalInfo). Stripe/Paddle: checkoutId (Checkout Session / transaction id).' properties: productId: {type: string, maxLength: 200} purchaseToken: {type: string, maxLength: 4096} subscription: {type: boolean} signedTransaction: {type: string, description: StoreKit 2 Transaction.jwsRepresentation} signedRenewalInfo: {type: string} checkoutId: {type: string} VerifyResult: type: object properties: purchase: {type: object, properties: {id: {type: string, format: uuid}, status: {type: string}, subscriptionId: {type: [string, 'null']}}} entitlements: {$ref: '#/components/schemas/EntitlementTokenResponse'} CheckoutStarted: type: object properties: attemptId: {type: string, format: uuid} provider: {type: string, enum: [zarinpal, stripe, paddle]} redirectUrl: {type: string, format: uri} amount: {type: integer} currency: {type: string} plan: {type: string} CheckoutStatus: type: object properties: id: {type: string, format: uuid} provider: {type: string} status: {type: string, enum: [pending, succeeded, canceled, failed]} plan: {type: string} amount: {type: integer} currency: {type: string} createdAt: {type: string, format: date-time} completedAt: {type: [string, 'null'], format: date-time} Invoice: type: object properties: id: {type: string, format: uuid} number: {type: string, examples: [BZ-2026-0000001]} provider: {type: string} plan: {type: string} description: {type: object, description: '{fa, ar, en}'} amount: {type: [integer, 'null']} currency: {type: [string, 'null']} status: {type: string, enum: [paid, refunded, void]} reference: {type: [string, 'null']} issuedAt: {type: string, format: date-time} PriceInput: type: object required: [productId, region, flavors, provider, kind, currency, amount] properties: productId: {type: string, enum: [plus, pro, business]} region: {type: string, enum: [IR, GLOBAL]} flavors: {type: array, items: {$ref: '#/components/schemas/Flavor'}} provider: {type: string, enum: [zarinpal, bazaar, myket, google_play, apple, paddle, stripe]} kind: {type: string, enum: [subscription, time_pack]} billingPeriod: {type: string, enum: [month, quarter, half_year, year]} durationDays: {type: integer} currency: {type: string} amount: {type: integer} storeProductId: {type: string} trialDays: {type: integer} label: {type: object} sortOrder: {type: integer} active: {type: boolean} WebPushSubscription: type: object required: [endpoint, keys, deviceId] properties: endpoint: {type: string, format: uri, description: 'PushSubscription.endpoint (https on FCM, Mozilla, Apple or WNS push services)'} keys: {type: object, required: [p256dh, auth], properties: {p256dh: {type: string}, auth: {type: string}}} deviceId: {$ref: '#/components/schemas/ClientDeviceId'} timeZone: {type: string, examples: [Asia/Tehran]} locale: {$ref: '#/components/schemas/Locale'} userAgent: {type: string, maxLength: 300} BotLinkCode: type: object properties: kind: {type: string, enum: [telegram, bale]} code: {type: string, examples: [K7M2Q9XA]} botUsername: {type: [string, 'null']} deepLink: {type: [string, 'null'], format: uri} expiresAt: {type: string, format: date-time} PowChallenge: type: object properties: challenge: {type: string} algorithm: {const: SHA-256} bits: {type: integer} expiresAt: {type: string, format: date-time} PowSolution: type: object properties: challenge: {type: string} solution: {type: string, pattern: '^\d{1,12}$'} PublicTicket: type: object required: [contact, subject, message] properties: name: {type: string, maxLength: 100} contact: {type: string, maxLength: 320, description: E-mail address or phone number} subject: {type: string, minLength: 3, maxLength: 200} message: {type: string, minLength: 10, maxLength: 5000} locale: {$ref: '#/components/schemas/Locale'} category: {type: string, enum: [general, billing, bug, account, feature, privacy, other]} website: {type: string, description: Honeypot — leave empty} pow: {$ref: '#/components/schemas/PowSolution'} SupportTicket: type: object properties: id: {type: string, format: uuid} number: {type: integer} source: {type: string, enum: [web, app]} subject: {type: string} category: {type: string} status: {type: string, enum: [open, pending, answered, closed]} locale: {type: string} createdAt: {type: string, format: date-time} lastMessageAt: {type: string, format: date-time} messages: {type: array, items: {type: object, properties: {id: {type: string}, author: {type: string, enum: [requester, staff, system]}, body: {type: string}, createdAt: {type: string, format: date-time}}}} StaffRole: type: string enum: [owner, admin, support, content] description: 'owner: everything; admin: everything but staff management; support: users (read), sessions, tickets, deletion requests; content: announcements and holidays' AdminLogin: type: object properties: status: {type: string, enum: [ok, totp_required, totp_enrollment_required]} token: {type: string, description: 'Opaque staff session (bzs_…); 10 minutes until the second factor, then 12 hours (30-minute idle timeout). `/auth/totp/verify` returns a new token (session rotation).'} expiresAt: {type: string, format: date-time} staff: {type: object, additionalProperties: true}