openapi: 3.1.0
info:
  title: NumberOTP API
  version: 1.0.0
  description: >
    Official API for NumberOTP. Integrate direct, high-quality temporary phone numbers into your applications for seamless SMS OTP verification.

    ## Base URL
    ```
    https://api.numberotp.com/v1
    ```

    ---

    ## Authentication
    Send a `Bearer` token in the `Authorization` header:

    - **API key** (servers and scripts): create one in Dashboard → Developer. Prefixed `notp_`. Keys carry
      scopes — `read`, `buy`, `topup` (default: all three) — and can never manage keys, webhooks, devices or the account.
    - **Access token** (the NumberOTP apps, browser extension, CLI and MCP servers): from `POST /oauth/token`.
      Valid 15 minutes; refresh with the rotating refresh token. Sign-in flows: email code, password,
      Sign in with Google/Apple (ID token), and device sign-in (RFC 8628) for terminals and agents.

    ```
    Authorization: Bearer notp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ```

    ---

    ## Retries (Idempotency-Key)
    Buying, renting and starting a top-up accept an `Idempotency-Key` header (any unique string, ≤255 chars).
    Retrying with the same key returns the first response (with `Idempotent-Replayed: true`) — never a second
    number or a second charge. Keys are kept 24 hours. The official SDKs send one automatically.

    ---

    ## Live events
    `GET /events` streams your account's events (Server-Sent Events): a code arriving, an extra SMS, a number
    expiring and being refunded, a top-up completing. The apps and extension also get these as push notifications.

    ---

    ## Service & Country Identifiers
    NumberOTP uses short, provider-level identifiers — **not** human-readable names.

    - **Service**: a short alphabetic code (e.g. `wa` for WhatsApp, `tg` for Telegram, `go` for Google). Retrieve the full list from `GET /public/services`.
    - **Country**: a numeric string ID (e.g. `"0"` for Russia, `"187"` for the United States, `"16"` for the United Kingdom). Retrieve the full list from `GET /public/countries`.

    Always pass these identifiers — never pass display names like `"whatsapp"` or `"US"`.

    ---

    ## Webhooks (Zero-Latency Delivery)
    Configure a global **Webhook URL** in your Developer Dashboard (or pass `webhook_url` when buying). When an SMS arrives we POST the payload to your endpoint — within seconds, whichever way the code was detected. Webhook URLs must be public HTTPS URLs.

    ### Verifying the Payload Signature
    We sign every webhook body with HMAC SHA-256 using your **Webhook Secret** (available in your dashboard) and include it in the request header:

    ```
    x-numberotp-signature: sha256=<hmac_hex>
    ```

    Compute the expected signature server-side and compare it to reject tampered requests.

    **Webhook Payload Example:**
    ```json
    {
      "id": "act_8f7d98x",
      "phone_number": "14155552671",
      "service": "wa",
      "country": "187",
      "otp": "482910",
      "full_sms": "Your WhatsApp code is 482910. Do not share it with anyone.",
      "status": "received",
      "event": "activation.code_received",
      "event_id": "evt_3f1c9a7e2b4d6f8a0c1e3b5d"
    }
    ```

    `event` is `activation.code_received` for the first SMS, `activation.sms_received` for each later one, and
    `rental.sms_received` on rented numbers. Use `event_id` to ignore duplicates.

    ---

    ## Rate Limits
    Public endpoints: **100 requests/minute** per IP.
    Authenticated endpoints: subject to your account's API limit (configurable in the dashboard; `0` = unlimited).

servers:
  - url: https://api.numberotp.com/v1
    description: Production

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >
        API key (prefixed `notp_`) or an access token from `POST /oauth/token`. Example: `Authorization: Bearer notp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`

  schemas:
    Error:
      type: object
      properties:
        error:
          type: string
          example: "Service not available in this country"
        code:
          type: string
          description: Stable machine-readable error code (e.g. INSUFFICIENT_BALANCE, INVALID_STATE).
          example: "NO_NUMBERS_AVAILABLE"

    ActivationData:
      type: object
      properties:
        id:
          type: string
          description: Activation ID — use this to poll or wait for the OTP.
          example: "act_8f7d98x"
        phone_number:
          type: string
          description: The provisioned temporary phone number (digits only, no `+`).
          example: "14155552671"
        service:
          type: string
          description: Short service code.
          example: "wa"
        country:
          type: string
          description: Numeric country ID.
          example: "187"
        otp:
          type: string
          nullable: true
          description: Extracted OTP code. `null` if not yet received.
          example: "482910"
        full_sms:
          type: string
          nullable: true
          description: Full text of the received SMS. `null` if not yet received.
          example: "Your WhatsApp code is 482910."
        status:
          type: string
          enum: [waiting, received, finished, canceled, expired]
          example: "waiting"
        service_name:
          type: string
          example: "WhatsApp"
        sms:
          type: array
          description: Every SMS received on this number, oldest first.
          items:
            type: object
            properties:
              code: { type: string }
              text: { type: string }
              received_at: { type: string, format: date-time }
        cost:
          type: number
          description: Price paid (USD).
          example: 0.42
        pool:
          type: string
          enum: [pool1, pool2, pool3]
        created_at:
          type: string
          format: date-time
        expires_at:
          type: string
          format: date-time
          description: ISO 8601 timestamp when the 20-minute activation window closes.
          example: "2026-05-02T15:30:00.000Z"

    Me:
      type: object
      properties:
        id: { type: string }
        email: { type: string }
        name: { type: string, nullable: true }
        image: { type: string, nullable: true }
        email_verified: { type: boolean }
        balance: { type: number, example: 12.5 }
        on_hold: { type: number, description: Charged for numbers still waiting for an SMS — refunded if none arrives. }
        currency: { type: string, example: USD }
        open_numbers: { type: integer }
        loyalty:
          type: object
          nullable: true
          properties:
            level: { type: integer, minimum: 0, maximum: 5 }
            label: { type: string, example: Gold }
            discount: { type: number, example: 0.25 }
            progress_pct: { type: number }
            next_tier: { type: object, nullable: true }
        restrictions: { type: object, properties: { purchases_on_hold: { type: boolean } } }
        brand: { type: object, nullable: true, description: "A reseller's branding, for their customers." }
        auth: { type: object, properties: { via: { type: string, enum: [session, api_key, access_token] }, scopes: { type: array, items: { type: string } } } }
        iap_account_token: { type: string, nullable: true, description: "Pass as StoreKit appAccountToken / Play obfuscatedAccountId when buying credit packs." }

    IapTopupResult:
      type: object
      properties:
        success: { type: boolean }
        data:
          type: object
          properties:
            status: { type: string, enum: [credited, already_credited] }
            amount: { type: number, description: Balance added (USD) }
            balance: { type: number }
            transaction_id: { type: string }

    AppConfigResult:
      type: object
      properties:
        success: { type: boolean }
        data:
          type: object
          properties:
            min_version: { type: object, properties: { ios: { type: string }, android: { type: string } } }
            latest_version: { type: object, properties: { ios: { type: string, nullable: true }, android: { type: string, nullable: true } } }
            store_urls: { type: object, properties: { ios: { type: string, nullable: true }, android: { type: string, nullable: true } } }
            maintenance: { type: object, nullable: true, properties: { message: { type: string } } }
            iap:
              type: object
              properties:
                ios: { type: boolean }
                android: { type: boolean }
                products: { type: array, items: { type: object, properties: { id: { type: string }, credit: { type: number }, price_usd: { type: number } } } }
            web_topup: { type: object, properties: { url: { type: string }, ios_storefronts: { type: array, items: { type: string } }, android_regions: { type: array, items: { type: string } } } }
            links: { type: object, additionalProperties: { type: string } }

    Event:
      type: object
      properties:
        id: { type: string, example: evt_3f1c9a7e2b4d6f8a0c1e3b5d }
        type:
          type: string
          enum: [activation.code_received, activation.sms_received, activation.finished, activation.canceled, activation.expired, rental.sms_received, rental.expired, topup.completed, reminder.back_in_stock]
        created_at: { type: string, format: date-time }
        initiator: { type: string, enum: [user, system] }
        refunded: { type: boolean }
        data: { type: object, description: "The activation (same fields as ActivationData) — or, for topup.completed, { transaction_id, amount, method }; for reminder.back_in_stock, { reminder_id, service, service_name, country, country_name }." }

    ClientSession:
      type: object
      properties:
        id: { type: string }
        platform: { type: string, enum: [ios, android, extension, cli, mcp, other] }
        device_name: { type: string }
        scopes: { type: array, items: { type: string } }
        last_seen_at: { type: string, format: date-time }
        created_at: { type: string, format: date-time }
        current: { type: boolean }

    TokenResponse:
      type: object
      properties:
        access_token: { type: string }
        token_type: { type: string, example: Bearer }
        expires_in: { type: integer, example: 900 }
        refresh_token: { type: string, example: "notp_rt_…" }
        scope: { type: string, example: "read buy topup account" }
        session_id: { type: string }
        new_user: { type: boolean, description: Present on email-code / ID-token sign-in. }

    DeviceCode:
      type: object
      properties:
        device_code: { type: string }
        user_code: { type: string, example: BCDF-GHJK }
        verification_uri: { type: string, example: "https://www.numberotp.com/device" }
        verification_uri_complete: { type: string }
        expires_in: { type: integer, example: 600 }
        interval: { type: integer, example: 5 }

    OAuthError:
      type: object
      properties:
        error: { type: string, example: invalid_grant }
        error_description: { type: string }

  parameters:
    IdempotencyKey:
      in: header
      name: Idempotency-Key
      required: false
      schema: { type: string, maxLength: 255 }
      description: Retrying with the same key returns the first response instead of buying or charging again.

security:
  - bearerAuth: []

paths:
  /public/services:
    get:
      operationId: listServices
      summary: List Services
      description: >
        Returns all services available for activation. Use the `code` field from each item as the `service` parameter when creating activations.

        Optionally filter by country numeric ID to see only services available in that country.
      security: []
      tags: [Public]
      parameters:
        - in: query
          name: country
          schema:
            type: string
          description: Numeric country ID to filter by (e.g. `"187"` for the United States, `"16"` for the United Kingdom). Omit for all countries.
          example: "187"
      responses:
        '200':
          description: List of available services
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    type: object
                    properties:
                      services:
                        type: array
                        items:
                          type: object
                          properties:
                            code:
                              type: string
                              description: Short service identifier — pass this as `service` in activation requests.
                              example: "wa"
                            name:
                              type: string
                              description: Human-readable name.
                              example: "WhatsApp"
                            count:
                              type: integer
                              description: Number of available numbers for this service.
                              example: 1842
                  source:
                    type: string
                    enum: [cache, db-cache, api]
                    example: "cache"
        '429':
          description: Rate limit exceeded (100 req/min per IP)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /public/countries:
    get:
      operationId: listCountries
      summary: List Countries
      description: >
        Returns all countries available for number provisioning. Use the `id` field from each item as the `country` parameter when creating activations.

        Optionally filter by service code to see only countries that have numbers available for that specific service.
      security: []
      tags: [Public]
      parameters:
        - in: query
          name: service
          schema:
            type: string
          description: Short service code to filter by (e.g. `"wa"`). Omit or pass `"any"` for all countries.
          example: "wa"
      responses:
        '200':
          description: List of available countries
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    type: object
                    description: >
                      Object map keyed by the numeric country ID string. Pass the key as `country` in activation requests.
                    additionalProperties:
                      type: object
                      properties:
                        name:
                          type: string
                          description: Country display name.
                          example: "United States"
                        code:
                          type: string
                          description: Numeric ID (same as the key).
                          example: "187"
                    example:
                      "187":
                        name: "United States"
                        code: "187"
                      "0":
                        name: "Russia"
                        code: "0"
                  source:
                    type: string
                    enum: [cache, db-cache, api]
                    example: "cache"
        '429':
          description: Rate limit exceeded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /public/prices:
    get:
      operationId: getPrices
      summary: Get Prices
      description: >
        Returns real-time pricing for all service/country combinations. Results are cached for up to 5 minutes.

        Use the `service` short code and numeric `country` ID to look up the price for a specific combination.
      security: []
      tags: [Public]
      parameters:
        - in: query
          name: service
          schema:
            type: string
          description: Short service code to filter (e.g. `"wa"`).
          example: "wa"
        - in: query
          name: country
          schema:
            type: string
          description: Numeric country ID to filter (e.g. `"187"`).
          example: "187"
      responses:
        '200':
          description: Pricing data
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    type: object
                    description: >
                      Nested map: `{ [countryId]: { [serviceCode]: { cost: number, count: number } } }`.
                    example:
                      "187":
                        "wa":
                          cost: 0.05
                          count: 1842
                  source:
                    type: string
                    enum: [cache, api]
                    example: "cache"
        '429':
          description: Rate limit exceeded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /public/rent-prices:
    get:
      operationId: getRentPrices
      summary: Get Rental Prices
      description: 'Rental prices for one service, by country and duration in hours: `data[countryId][hours]` is `{cost, count}`.'
      tags: [Public]
      security: []
      parameters:
        - { in: query, name: service, required: true, schema: { type: string }, example: tg }
      responses:
        '200':
          description: Prices
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    additionalProperties:
                      type: object
                      additionalProperties:
                        type: object
                        properties:
                          cost: { type: number }
                          count: { type: integer }

  /activations:
    post:
      operationId: createActivation
      summary: Purchase a Number
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      description: >
        Deducts balance from your account and provisions a temporary phone number for the requested service.

        Once an OTP SMS arrives (within 20 minutes), it is delivered via:
        1. **Webhook** — instantly POSTed to your configured global webhook URL, or the per-request `webhook_url` override.
        2. **Polling** — call `GET /activations/{id}` at your preferred interval.
        3. **Long-poll** — call `GET /activations/{id}/wait` to block until the OTP arrives or the window expires.

        If no OTP is received within 20 minutes, the charged amount is automatically refunded to your wallet.
      tags: [Activations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - service
                - country
              properties:
                service:
                  type: string
                  description: >
                    Short service code from `GET /public/services`. **Do not** pass the display name.
                  example: "wa"
                country:
                  type: string
                  description: >
                    Numeric country ID from `GET /public/countries`. **Do not** pass the country name or ISO code.
                  example: "187"
                webhook_url:
                  type: string
                  format: uri
                  description: >
                    Optional. Override your global webhook URL for this specific activation only.
                  example: "https://your-server.com/api/otp-callback"
                pool:
                  type: string
                  enum: [auto, pool1, pool2, pool3]
                  description: >
                    Optional (default "auto"). "auto" buys from the pool with the best measured delivery
                    rate for this service and country (weighed against price and stock, and your own recent
                    results unless you turned personalization off in Dashboard → Settings), switching to the
                    next pool automatically if one cannot supply a number. A specific pool is only ever that pool.
                  example: "auto"
                max_price:
                  type: number
                  description: >
                    Optional. Highest price (USD) you accept for this number. Pools above it are skipped;
                    if none remains the request fails instead of charging more.
                  example: 0.5
            example:
              service: "wa"
              country: "187"
              webhook_url: "https://your-server.com/api/otp-callback"
      responses:
        '200':
          description: Number provisioned successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    type: object
                    properties:
                      id:
                        type: string
                        description: Activation ID — use this for polling or waiting.
                        example: "act_8f7d98x"
                      phoneNumber:
                        type: string
                        description: Provisioned phone number (digits only, no `+`).
                        example: "14155552671"
                      expiresAt:
                        type: string
                        format: date-time
                        description: When the 20-minute window expires.
                        example: "2026-05-02T15:30:00.000Z"
                  balance:
                    type: number
                    description: Your remaining wallet balance after this purchase.
                    example: 4.75
        '401':
          description: Unauthorized — missing or invalid API key / session token
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '402':
          description: Insufficient balance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: Service not available in this country
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          description: API limit reached for this billing period
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /activations/{id}:
    get:
      operationId: getActivation
      summary: Poll Activation Status
      description: >
        Returns the current status of an activation. Safe to call repeatedly at any interval.

        If the OTP has already been received, it is returned immediately from the database without an upstream call.
        If the activation is still `waiting`, a live upstream check is made and the result is cached in the database.
      tags: [Activations]
      parameters:
        - in: path
          name: id
          required: true
          schema:
            type: string
          description: Activation ID returned by `POST /activations`.
          example: "act_8f7d98x"
      responses:
        '200':
          description: Activation status
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    $ref: '#/components/schemas/ActivationData'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '403':
          description: Forbidden — activation belongs to a different account
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: Activation not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /activations/{id}/wait:
    get:
      operationId: waitForCode
      summary: Wait for OTP (Long-Poll)
      description: >
        Blocks the HTTP connection until an OTP is received or the activation expires (up to 20 minutes).

        Useful for simple integrations that want a single blocking call rather than a polling loop.
        For production workloads with multiple concurrent activations, the **Webhook** approach is strongly preferred.
      tags: [Activations]
      parameters:
        - in: path
          name: id
          required: true
          schema:
            type: string
          description: Activation ID returned by `POST /activations`.
          example: "act_8f7d98x"
      responses:
        '200':
          description: OTP received
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    type: object
                    properties:
                      otp:
                        type: string
                        example: "482910"
                      full_sms:
                        type: string
                        example: "Your WhatsApp code is 482910."
                      status:
                        type: string
                        example: "received"
        '400':
          description: Activation already canceled or expired
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: false
                  error:
                    type: string
                  status:
                    type: string
                    enum: [canceled, expired]
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '408':
          description: Timeout — no OTP received within the polling window. Retry or wait for the webhook.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: false
                  error:
                    type: string
                    example: "Timeout waiting for OTP. Please poll again."
                  status:
                    type: string
                    example: "waiting"

  /rentals:
    post:
      operationId: createRental
      summary: Rent a Number
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      description: >
        Purchase a number for a fixed duration (2h, 4h, 12h, 24h, 48h, 72h, 96h, 120h, 144h, 168h, 336h, 504h, 720h).
        The number receives unlimited SMS during the rental window. Extend at any time via PATCH /rentals/{id}.


        **Reseller sub-users:** fully supported — authenticate with the sub-user's Bearer token.
        The reseller's markup is applied automatically; the reseller's buying balance is debited at platform cost.
        The reseller earns the markup profit immediately.


        **⚠ No refunds** for rentals or cancellations once a number is issued.
      tags: [Activations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [service, country, duration]
              properties:
                service: { type: string, example: "wa", description: "Service code (e.g. wa, tg, go)" }
                country: { type: string, example: "12", description: "Country ID from /public/countries" }
                duration: { type: integer, example: 168, description: "Duration in hours: 2, 4, 12, or multiples of 24 up to 720 (30 days)" }
            example:
              service: "wa"
              country: "12"
              duration: 168
      responses:
        '200':
          description: Number rented successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  data:
                    type: object
                    properties:
                      id: { type: string, example: "8675309" }
                      phoneNumber: { type: string, example: "12025551234" }
                      expiresAt: { type: string, format: date-time }
                      durationHours: { type: integer, example: 168 }
                  balance: { type: number, example: 14.38 }
        '400':
          description: Invalid duration or missing fields
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: "Invalid duration. Must be 2, 4, 12, or a multiple of 24 (up to 720 hours)."
        '402':
          description: Insufficient balance
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: Service not available for rental in this country
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: Reseller has insufficient buying credits (sub-user purchases only)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /rentals/{id}:
    get:
      operationId: getRental
      summary: Get Rental Status & SMS History
      tags: [Activations]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
          description: Activation ID returned by POST /rentals
      responses:
        '200':
          description: Rental details with SMS history
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      id: { type: string }
                      phoneNumber: { type: string }
                      status: { type: string, enum: [active, expired, finished, canceled] }
                      expiresAt: { type: string, format: date-time }
                      durationHours: { type: integer }
                      smsHistory:
                        type: array
                        items:
                          type: object
                          properties:
                            text: { type: string }
                            sender: { type: string }
                            receivedAt: { type: string, format: date-time }
    post:
      operationId: extendRental
      summary: Extend a Rental
      description: Add hours to an active rental. Same duration constraints as POST /rentals. **⚠ No refunds** once extended.
      tags: [Activations]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [hours]
              properties:
                hours: { type: integer, example: 24, description: "Additional hours: 2, 4, 12, or multiples of 24" }
            example:
              hours: 24
      responses:
        '200':
          description: Rental extended
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  newExpiresAt: { type: string, format: date-time }
                  cost: { type: number }
                  balance: { type: number }
        '402':
          description: Insufficient balance
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

    delete:
      operationId: cancelRental
      summary: Cancel a Rental
      description: Releases a rented number before it expires. **No refund.**
      tags: [Activations]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        '200': { description: Canceled }
        '409':
          description: Not active
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /rentals/{id}/extend-options:
    get:
      operationId: getRentalExtendOptions
      summary: Get Extension Prices
      description: 'Prices to extend this rental, by hours — e.g. `{"24": 0.54, "48": 1.08}`.'
      tags: [Activations]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        '200':
          description: Options
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { type: object, additionalProperties: { type: number } }

  /reseller/profile:
    get:
      operationId: getResellerProfile
      summary: Get Reseller Profile
      description: >
        Returns account info including buying balance, earned balance, reseller public ID,
        brand settings (name, logo, color), webhook URL, sub-user defaults, and markup version.
      tags: [Reseller]
      responses:
        '200':
          description: Reseller profile
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    type: object
                    properties:
                      id: { type: string, example: "64f3a..." }
                      email: { type: string, example: "you@company.com" }
                      name: { type: string, example: "Jane Smith" }
                      buyingBalance: { type: number, example: 42.50 }
                      earnedBalance: { type: number, example: 18.75 }
                      resellerPublicId: { type: string, example: "a26e2be6" }
                      brand:
                        type: object
                        properties:
                          name: { type: string, example: "Acme OTP" }
                          logoUrl: { type: string, example: "https://acme.com/logo.png" }
                          color: { type: string, example: "#6366f1" }
                      webhookUrl: { type: string, nullable: true, example: "https://acme.com/webhook" }
                      minSubUserTopup: { type: number, example: 10 }
                      allowSelfFundDefault: { type: boolean, example: true }
                      markupVersion: { type: integer, example: 3 }
                      publicSignupUrl: { type: string, example: "https://www.numberotp.com/join/a26e2be6" }
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '403':
          description: Not a reseller account
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    patch:
      operationId: updateResellerProfile
      summary: Update Brand, Webhook & Sub-User Settings
      description: Update brand fields, webhook URL/secret, and sub-user defaults. All fields optional — only provided keys are updated.
      tags: [Reseller]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                brandName: { type: string, example: "Acme OTP" }
                logoUrl: { type: string, example: "https://acme.com/logo.png" }
                color: { type: string, example: "#6366f1" }
                webhookUrl: { type: string, example: "https://acme.com/webhook" }
                webhookSecret: { type: string, example: "my-hmac-secret" }
                allowSelfFundDefault: { type: boolean, example: true }
                minSubUserTopup: { type: number, example: 10 }
            example:
              brandName: "Acme OTP"
              color: "#6366f1"
              webhookUrl: "https://acme.com/webhook"
              minSubUserTopup: 10
      responses:
        '200':
          description: Settings updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /reseller/markup:
    get:
      operationId: getResellerMarkup
      summary: Get Markup Configuration
      description: Returns the global price multiplier, per-service overrides, per-country overrides, and autoAdjustLoyalty flag.
      tags: [Reseller]
      responses:
        '200':
          description: Current markup config
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  data:
                    type: object
                    properties:
                      global: { type: number, example: 2.0, description: "Multiplier applied to all platform prices." }
                      overrides:
                        type: object
                        description: Per-service multiplier overrides keyed by service code.
                        example: { wa: 1.8, tg: 2.5 }
                      countryOverrides:
                        type: object
                        description: Per-country multiplier overrides keyed by numeric country ID.
                        example: { "187": 1.5 }
                      autoAdjustLoyalty: { type: boolean, example: false }
                      version: { type: integer, example: 3 }
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    patch:
      operationId: updateResellerMarkup
      summary: Update Markup
      description: >
        Set global multiplier and optional per-service/country overrides.
        Sub-user price = platform_price × countryOverride × serviceOverride × global.
        Busts the markup cache immediately on save.
      tags: [Reseller]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                global:
                  type: number
                  description: Multiplier applied to all prices. 1.0 = no markup.
                  example: 2.0
                overrides:
                  type: object
                  description: Per-service multipliers (keyed by service code).
                  example: { wa: 1.8 }
                countryOverrides:
                  type: object
                  description: Per-country multipliers (keyed by numeric country ID string).
                  example: { "187": 1.5 }
                autoAdjustLoyalty:
                  type: boolean
                  description: If true, loyalty discounts are passed through to sub-users.
                  example: false
            example:
              global: 2.0
              overrides: { wa: 1.8 }
              autoAdjustLoyalty: false
      responses:
        '200':
          description: Markup updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /reseller/users:
    get:
      operationId: listResellerUsers
      summary: List Sub-Users
      description: Returns all sub-users linked to this reseller account.
      tags: [Reseller]
      responses:
        '200':
          description: List of sub-users
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string, example: "64f3b..." }
                        email: { type: string, example: "user@example.com" }
                        name: { type: string, example: "John Doe" }
                        balance: { type: number, example: 12.50 }
                        suspended: { type: boolean, example: false }
                        allowSelfFund: { type: boolean, example: true }
                        createdAt: { type: string, format: date-time }
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    post:
      operationId: createResellerUser
      summary: Create Sub-User
      description: Manually create a sub-user. Optionally deduct initialBalance from your buying credits and allocate it to the new account.
      tags: [Reseller]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, password]
              properties:
                email: { type: string, example: "user@example.com" }
                password: { type: string, example: "securepassword" }
                name: { type: string, example: "John Doe" }
                initialBalance: { type: number, example: 5.00, description: "Deducted from reseller buying credits." }
                allowSelfFund: { type: boolean, example: true }
            example:
              email: "user@example.com"
              password: "securepassword"
              name: "John Doe"
              initialBalance: 5.00
      responses:
        '200':
          description: Sub-user created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  data:
                    type: object
                    properties:
                      id: { type: string }
                      email: { type: string }
        '409':
          description: Email already registered
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '402':
          description: Insufficient buying credits for initialBalance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /reseller/users/{subUserId}:
    get:
      operationId: getResellerUser
      summary: Get Sub-User Details
      description: Returns full profile for one sub-user.
      tags: [Reseller]
      parameters:
        - in: path
          name: subUserId
          required: true
          schema: { type: string }
          example: "64f3b..."
      responses:
        '200':
          description: Sub-user details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  data:
                    type: object
                    properties:
                      id: { type: string }
                      email: { type: string }
                      name: { type: string }
                      balance: { type: number }
                      suspended: { type: boolean }
                      allowSelfFund: { type: boolean }
                      createdAt: { type: string, format: date-time }
        '404':
          description: Sub-user not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    patch:
      operationId: updateResellerUser
      summary: Update Sub-User
      description: Adjust balance delta, toggle suspension, or change allowSelfFund. balanceDelta is atomic — positive adds funds from reseller buying credits, negative deducts from sub-user.
      tags: [Reseller]
      parameters:
        - in: path
          name: subUserId
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                balanceDelta: { type: number, example: 10.00 }
                suspended: { type: boolean, example: false }
                allowSelfFund: { type: boolean, example: true }
            example:
              balanceDelta: 10.00
              suspended: false
      responses:
        '200':
          description: Sub-user updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
        '402':
          description: Insufficient balance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    delete:
      operationId: deleteResellerUser
      summary: Delete Sub-User
      description: Permanently deletes the sub-user. Remaining balance is forfeited.
      tags: [Reseller]
      parameters:
        - in: path
          name: subUserId
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }

  /reseller/payout/convert:
    post:
      operationId: convertResellerEarnings
      summary: Convert Earned Balance → Buying Credits
      description: Instantly move funds from earned balance (sub-user revenue) to buying credits wallet. Zero fee. Guarded atomically against race conditions.
      tags: [Reseller]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [amount]
              properties:
                amount: { type: number, example: 15.00 }
            example:
              amount: 15.00
      responses:
        '200':
          description: Converted successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  data:
                    type: object
                    properties:
                      newEarnedBalance: { type: number, example: 3.75 }
                      newBuyingBalance: { type: number, example: 57.50 }
        '402':
          description: Insufficient earned balance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /reseller/payout/withdraw:
    post:
      operationId: withdrawResellerEarnings
      summary: Withdraw Earned Balance as Crypto
      description: Submit a crypto withdrawal request. Minimum $10. Processed within 24 hours.
      tags: [Reseller]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [amount, currency, cryptoAddress]
              properties:
                amount: { type: number, example: 25.00 }
                currency: { type: string, example: "USDT", description: "Crypto ticker: USDT, BTC, ETH, SOL, etc." }
                cryptoAddress: { type: string, example: "TYour...WalletAddress" }
            example:
              amount: 25.00
              currency: "USDT"
              cryptoAddress: "TYour...WalletAddress"
      responses:
        '200':
          description: Withdrawal queued
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  message: { type: string, example: "Withdrawal request submitted. You will receive $24.63 after a $0.37 processing fee. Processed within 24h." }
                  gross: { type: number, example: 25.00, description: "Amount requested (deducted from earned balance)" }
                  fee: { type: number, example: 0.38, description: "Processing fee (1.5%, min $0.50)" }
                  netAmount: { type: number, example: 24.62, description: "Amount you will actually receive" }
                  earnedBalance: { type: number, example: 74.38, description: "Remaining earned balance after deduction" }
                  transactionId: { type: string, example: "60d21b4667d0d8992e610c85" }
        '400':
          description: Insufficient earned balance or below minimum
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /reseller/payments/crypto:
    post:
      operationId: createResellerCryptoTopup
      summary: Top Up Buying Credits via Crypto
      description: Create a Cryptomus invoice to add buying credits. Minimum $20. Returns a checkout URL to redirect to.
      tags: [Reseller]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [amount]
              properties:
                amount: { type: number, example: 50.00 }
            example:
              amount: 50.00
      responses:
        '200':
          description: Invoice created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  url: { type: string, example: "https://pay.cryptomus.com/pay/8b03432e-385b-4670-8d06-064591096795" }
                  invoiceId: { type: string, example: "8b03432e-385b-4670-8d06-064591096795" }
                  transactionId: { type: string, example: "65bbe87b4098c17a31cff3e7" }

  /reseller/payments/card:
    post:
      operationId: createResellerCardTopup
      summary: Top Up Buying Credits via Card
      description: Create a card checkout link (Stripe Checkout) to add buying credits. Minimum $20. Returns a checkout URL to redirect to.
      tags: [Reseller]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [amount]
              properties:
                amount: { type: number, example: 50.00 }
            example:
              amount: 50.00
      responses:
        '200':
          description: Checkout link created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  url: { type: string, example: "https://pay.freecustom.email/..." }
                  transactionId: { type: string, example: "60d21b4667d0d8992e610c85" }
        '503':
          description: Card payments not configured or temporarily disabled on this platform
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /reseller-public/{resellerPublicId}/brand:
    get:
      operationId: getResellerBrand
      summary: Get Reseller Brand Info
      description: Returns white-label brand data (name, logo URL, color) for the signup page. No authentication required.
      security: []
      tags: [Reseller Public]
      parameters:
        - in: path
          name: resellerPublicId
          required: true
          schema: { type: string }
          example: "a26e2be6"
      responses:
        '200':
          description: Brand info
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  data:
                    type: object
                    properties:
                      brandName: { type: string, nullable: true, example: "Acme OTP" }
                      logoUrl: { type: string, nullable: true, example: "https://acme.com/logo.png" }
                      color: { type: string, nullable: true, example: "#6366f1" }
        '404':
          description: Reseller not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /reseller-public/{resellerPublicId}/signup:
    post:
      operationId: resellerSignup
      summary: Register as Sub-User
      description: >
        Creates a new account linked to this reseller. Requires a Cloudflare Turnstile token.
        Sends an email OTP for verification. Sub-users use `POST /api/auth/verify-email` next.
      security: []
      tags: [Reseller Public]
      parameters:
        - in: path
          name: resellerPublicId
          required: true
          schema: { type: string }
          example: "a26e2be6"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, password, turnstileToken]
              properties:
                email: { type: string, example: "newuser@example.com" }
                password: { type: string, example: "securepassword" }
                name: { type: string, example: "Jane Doe" }
                turnstileToken: { type: string, example: "0.xxxxx..." }
            example:
              email: "newuser@example.com"
              password: "securepassword"
              name: "Jane Doe"
              turnstileToken: "0.xxxxx..."
      responses:
        '200':
          description: Registration successful — OTP email sent
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  message: { type: string, example: "Account created. Check your email for the verification code." }
        '409':
          description: Email already registered
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: Reseller public ID not found or reseller disabled
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /reseller-public/{resellerPublicId}/topup/crypto:
    post:
      operationId: resellerSubUserCryptoTopup
      summary: Sub-User Crypto Top-Up
      description: >
        Creates a Cryptomus invoice for a sub-user to fund their own balance.
        Authenticate as the sub-user (Bearer notp_... API key or session cookie) — NOT as the reseller.
        Minimum = reseller's configured minSubUserTopup. Self-funding must be enabled by the reseller.
      tags: [Reseller Public]
      parameters:
        - in: path
          name: resellerPublicId
          required: true
          schema: { type: string }
          example: "a26e2be6"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [amount]
              properties:
                amount: { type: number, example: 20.00 }
            example:
              amount: 20.00
      responses:
        '200':
          description: Invoice created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  url: { type: string, example: "https://pay.cryptomus.com/pay/8b03432e-385b-4670-8d06-064591096795" }
                  invoiceId: { type: string, example: "8b03432e-385b-4670-8d06-064591096795" }
                  transactionId: { type: string, example: "60d21b4667d0d8992e610c85" }
        '401':
          description: Unauthorized — must authenticate as sub-user, not reseller
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: >
            Access denied. Either you authenticated as the reseller (use sub-user credentials instead),
            or self-funding is disabled. Contact your provider to enable it.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /reseller-public/{resellerPublicId}/topup/card:
    post:
      operationId: resellerSubUserCardTopup
      summary: Sub-User Card Top-Up
      description: >
        Creates a card checkout link (Stripe Checkout) for a sub-user to fund their own balance.
        Authenticate as the sub-user (Bearer notp_... API key or session cookie) — NOT as the reseller.
        Minimum = reseller's configured minSubUserTopup. Self-funding must be enabled by the reseller.
        Cards must be enabled on the platform.
      tags: [Reseller Public]
      parameters:
        - in: path
          name: resellerPublicId
          required: true
          schema: { type: string }
          example: "a26e2be6"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [amount]
              properties:
                amount: { type: number, example: 20.00 }
            example:
              amount: 20.00
      responses:
        '200':
          description: Checkout session created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean, example: true }
                  url: { type: string, example: "https://pay.freecustom.email/..." }
                  transactionId: { type: string, example: "60d21b4667d0d8992e610c85" }
        '401':
          description: Unauthorized — must authenticate as sub-user
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: >
            Access denied. Either you authenticated as the reseller (use sub-user credentials instead),
            or self-funding is disabled. Contact your provider to enable it.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: Card payments not configured on this platform
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /activations/{id}/finish:
    post:
      operationId: finishActivation
      summary: Mark Code as Used
      description: Closes a number that received its code (same as `PATCH /activations/{id}`). Not required — numbers close on their own when the window ends.
      tags: [Activations]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        '200':
          description: Activation finished
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/ActivationData' }
        '409':
          description: The activation hasn't received a code (or is already closed) — `code` is `INVALID_STATE`
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /activations/{id}/cancel:
    post:
      operationId: cancelActivation
      summary: Cancel and Refund
      description: Releases a number that hasn't received an SMS yet and refunds it in full (same as `DELETE /activations/{id}`). Safe to retry — it refunds once.
      tags: [Activations]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        '200':
          description: Canceled and refunded
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/ActivationData' }
        '409':
          description: Already received, canceled or expired — `code` is `INVALID_STATE`
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /activations/{id}/resend:
    post:
      operationId: requestAnotherSms
      summary: Request Another SMS
      description: >
        Asks for another SMS on a number that has already received one and is still open (for when the site asks
        you to request a new code). Free. The new SMS arrives as an `activation.sms_received` event and is appended
        to `sms`. Supported on Pool 1 numbers; others answer 409 `RESEND_NOT_SUPPORTED`.
      tags: [Activations]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        '200':
          description: Requested
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/ActivationData' }
        '409':
          description: Not open, no code yet, or not supported by this pool
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /user/activations:
    get:
      operationId: listActivations
      summary: List My Numbers
      description: Your one-time numbers, newest first. Open ones are synced with their pool first, so the list is current.
      tags: [Account]
      parameters:
        - in: query
          name: status
          schema: { type: string, enum: [waiting, received, finished, expired, canceled] }
        - in: query
          name: limit
          schema: { type: integer, minimum: 1, maximum: 200, default: 200 }
      responses:
        '200':
          description: Activations
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { type: array, items: { type: object } }

  /user/rentals:
    get:
      operationId: listRentals
      summary: List My Rentals
      tags: [Account]
      responses:
        '200':
          description: Rentals, newest first
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { type: array, items: { type: object } }

  /user/transactions:
    get:
      operationId: listTransactions
      summary: List Transactions
      description: Completed top-ups, purchases, refunds and adjustments, newest first.
      tags: [Account]
      responses:
        '200':
          description: Transactions
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { type: array, items: { type: object } }

  /user/reminders:
    get:
      operationId: listReminders
      summary: List Back-in-Stock Reminders
      tags: [Account]
      responses:
        '200': { description: Reminders }
    post:
      operationId: createReminder
      summary: Create a Back-in-Stock Reminder
      description: Emails you when a sold-out service/country comes back. Limits depend on your loyalty tier.
      tags: [Account]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [service, country]
              properties:
                service: { type: string, example: wa }
                country: { type: string, example: "16" }
                serviceName: { type: string }
                countryName: { type: string }
      responses:
        '200': { description: Created (or `alreadyExists`) }
        '400': { description: Above your tier's price cap }
        '409': { description: Active reminder limit reached }

  /user/reminders/{id}:
    delete:
      operationId: deleteReminder
      summary: Cancel a Reminder
      tags: [Account]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        '200': { description: Canceled }

  /user/apikeys:
    get:
      operationId: listApiKeys
      summary: List API Keys
      description: Requires a signed-in person (website, app or CLI) — an API key can't manage keys.
      tags: [Account]
      responses:
        '200': { description: Keys (never the secret), monthly usage and limit }
    post:
      operationId: createApiKey
      summary: Create an API Key
      description: The raw key is returned once — store it.
      tags: [Account]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string, example: "Production server" }
                scopes:
                  type: array
                  items: { type: string, enum: [read, buy, topup] }
                  description: Defaults to all three.
      responses:
        '200':
          description: Created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  rawKey: { type: string, example: "notp_0123456789abcdef0123456789abcdef" }
                  key: { type: object }
    delete:
      operationId: deleteApiKey
      summary: Delete an API Key
      tags: [Account]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [id], properties: { id: { type: string } } }
      responses:
        '200': { description: Deleted }

  /user/webhook:
    get:
      operationId: getWebhook
      summary: Get Webhook Settings
      tags: [Account]
      responses:
        '200': { description: Webhook URL and signing secret }
    post:
      operationId: setWebhook
      summary: Set Webhook URL
      tags: [Account]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                webhookUrl: { type: string, format: uri, description: Public HTTPS URL, or empty to turn webhooks off. }
      responses:
        '200': { description: Saved; returns the signing secret }

  /user/sessions:
    get:
      operationId: listSessions
      summary: List Connected Devices
      description: Apps, extensions, CLIs and MCP servers signed in to this account.
      tags: [Auth]
      responses:
        '200':
          description: Sessions
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { type: array, items: { $ref: '#/components/schemas/ClientSession' } }
    delete:
      operationId: revokeSessions
      summary: Sign Out a Device (or All)
      tags: [Auth]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - { type: object, required: [id], properties: { id: { type: string } } }
                - { type: object, required: [all], properties: { all: { type: boolean, const: true } } }
      responses:
        '200': { description: Signed out }

  /me:
    get:
      operationId: getMe
      summary: Get My Account
      description: Profile, balance, money on hold for numbers still waiting, loyalty tier and (for a reseller's customer) their branding — everything a home screen needs.
      tags: [Account]
      responses:
        '200':
          description: Account
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/Me' }
    delete:
      operationId: deleteMe
      summary: Delete My Account
      description: >
        Permanently deletes the account: email, name, sign-ins, API keys, connected devices and webhook are removed,
        numbers waiting for an SMS are released, and any remaining balance is forfeited. Requires a signed-in person
        and `{ "confirm": "DELETE" }`. Resellers with customers must contact support first (409 `RESELLER_HAS_SUB_USERS`).
      tags: [Account]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [confirm], properties: { confirm: { type: string, const: DELETE } } }
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema: { type: object, properties: { success: { type: boolean }, forfeited_balance: { type: number } } }

  /services/search:
    get:
      operationId: searchServices
      summary: Find a Service by Name or Domain
      description: >
        Turns what you have — a name, a code, a URL or a domain like `accounts.google.com` — into service codes,
        best match first. When nothing matches, `fallback` offers the catch-all "any other service" code.
      tags: [Public]
      security: []
      parameters:
        - { in: query, name: q, required: true, schema: { type: string }, example: discord.com }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 50, default: 10 } }
      responses:
        '200':
          description: Matches
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: array
                    items: { type: object, properties: { code: { type: string }, name: { type: string }, score: { type: integer } } }
                  fallback: { type: object, nullable: true }

  /payments/card:
    post:
      operationId: createCardTopup
      summary: Top Up by Card
      description: Returns a Stripe Checkout URL to open in a browser. When it's paid you get a `topup.completed` event.
      tags: [Wallet]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [amount], properties: { amount: { type: number, minimum: 5, example: 25 } } }
      responses:
        '200':
          description: Checkout started
          content:
            application/json:
              schema: { type: object, properties: { success: { type: boolean }, url: { type: string }, transaction_id: { type: string } } }

  /payments/crypto:
    post:
      operationId: createCryptoTopup
      summary: Top Up with Crypto
      description: Returns a crypto invoice URL. Top-ups of $50 or more get a 10% bonus.
      tags: [Wallet]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [amount], properties: { amount: { type: number, example: 50 } } }
      responses:
        '200':
          description: Invoice created
          content:
            application/json:
              schema: { type: object, properties: { success: { type: boolean }, url: { type: string }, invoiceId: { type: string }, transaction_id: { type: string } } }

  /topups/{id}:
    get:
      operationId: getTopup
      summary: Get Top-Up Status
      tags: [Wallet]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string }, description: "`transaction_id` from the top-up call" }
      responses:
        '200':
          description: Status
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      id: { type: string }
                      amount: { type: number }
                      method: { type: string, enum: [card, crypto, app_store, google_play] }
                      status: { type: string, enum: [pending, completed, failed] }

  /topups/apple:
    post:
      operationId: createAppleTopup
      summary: Credit an App Store Purchase
      description: >
        For the iOS app. Send the StoreKit 2 `Transaction.jwsRepresentation` of a credit pack bought with
        `appAccountToken` set to `iap_account_token` from `GET /me`. It is verified against Apple's root
        certificate and credited once per transaction — safe to retry; finish the StoreKit transaction only
        after a 200. Test (sandbox) purchases are accepted only for allowlisted accounts. Errors:
        `INVALID_PURCHASE`, `UNKNOWN_PRODUCT`, `PURCHASE_REVOKED`, `ACCOUNT_MISMATCH`, `SANDBOX_NOT_ALLOWED`.
      tags: [Wallet]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [signed_transaction], properties: { signed_transaction: { type: string } } }
      responses:
        '200': { description: Credited (or already credited), content: { application/json: { schema: { $ref: '#/components/schemas/IapTopupResult' } } } }

  /topups/google:
    post:
      operationId: createGoogleTopup
      summary: Credit a Google Play Purchase
      description: >
        For the Android app. Send the product id and purchase token of a credit pack bought with
        `obfuscatedAccountId` set to `iap_account_token` from `GET /me`. Checked with Google Play, credited
        once per order and consumed — safe to retry. Errors as for Apple, plus `PURCHASE_PENDING` and
        `IAP_UNAVAILABLE`.
      tags: [Wallet]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [product_id, purchase_token], properties: { product_id: { type: string }, purchase_token: { type: string } } }
      responses:
        '200': { description: Credited (or already credited), content: { application/json: { schema: { $ref: '#/components/schemas/IapTopupResult' } } } }

  /app/config:
    get:
      operationId: getAppConfig
      summary: App Configuration
      description: >
        No auth. What the mobile app needs at start: minimum supported version per platform, maintenance
        notice, the in-app credit packs, where store rules allow a web top-up link, and support links.
      tags: [Account]
      security: []
      responses:
        '200': { description: Configuration, content: { application/json: { schema: { $ref: '#/components/schemas/AppConfigResult' } } } }

  /events:
    get:
      operationId: streamEvents
      summary: Live Events (Server-Sent Events)
      description: >
        A `text/event-stream` of your account's events — `activation.code_received`, `activation.sms_received`,
        `activation.expired` (refunded), `activation.canceled`, `activation.finished`, `rental.sms_received`,
        `rental.expired`, `topup.completed`, `reminder.back_in_stock`. Each connection lasts ~55 s; reconnect with `Last-Event-ID` (EventSource does
        this for you) and nothing is missed — the last 200 events are kept for 7 days. `?once=1` returns pending
        events as JSON instead, for clients that would rather poll.
      tags: [Events]
      parameters:
        - { in: query, name: since, schema: { type: string }, description: "Stream id to resume after; `0` replays everything kept" }
        - { in: query, name: once, schema: { type: string, enum: ['1'] } }
      responses:
        '200':
          description: Event stream (or JSON with `once=1`)
          content:
            text/event-stream:
              schema: { type: string }
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/Event' } }
                  cursor: { type: string }

  /devices:
    get:
      operationId: listPushDevices
      summary: List Push Devices
      description: This account's push-registered devices, plus the VAPID public key a browser extension subscribes with.
      tags: [Events]
      responses:
        '200': { description: Devices and `web_push_public_key` }
    post:
      operationId: registerPushDevice
      summary: Register for Push Notifications
      description: Called by the mobile app (Expo push token) or browser extension (Push API subscription). Not available to API keys.
      tags: [Events]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - type: object
                  required: [kind, token]
                  properties:
                    kind: { type: string, const: expo }
                    token: { type: string, example: "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]" }
                    platform: { type: string, example: ios }
                    locale: { type: string, example: en, description: "Language for notification text: en, es, pt, fr, de, hi, ru or ar (a tag like pt-BR works too). Default en." }
                    show_code: { type: boolean, default: true, description: Show the code itself in the notification }
                - type: object
                  required: [kind, subscription]
                  properties:
                    kind: { type: string, const: webpush }
                    subscription:
                      type: object
                      properties:
                        endpoint: { type: string }
                        keys: { type: object, properties: { p256dh: { type: string }, auth: { type: string } } }
                    locale: { type: string, example: en, description: Language for notification text (as for expo) }
                    show_code: { type: boolean, default: true }
      responses:
        '200': { description: Registered }
    patch:
      operationId: updatePushDevice
      summary: Show or Hide Codes in Notifications
      tags: [Events]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [token, show_code], properties: { token: { type: string }, show_code: { type: boolean } } }
      responses:
        '200': { description: Updated }
    delete:
      operationId: unregisterPushDevice
      summary: Stop Push Notifications to a Device
      tags: [Events]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: Send `token` (the Expo token or Web Push endpoint), or the device `id` from List Push Devices.
              properties:
                token: { type: string }
                id: { type: string }
      responses:
        '200': { description: Removed }

  /oauth/token:
    post:
      operationId: oauthToken
      summary: Get Tokens
      description: >
        How apps, the browser extension, the CLI and MCP servers sign in. Returns a 15-minute access token and a
        60-day refresh token that rotates on every use (re-using an old one signs that device out).
        Errors follow RFC 6749 (`{ error, error_description }`).


        | grant_type | fields |
        |---|---|
        | `password` | `email`, `password` |
        | `refresh_token` | `refresh_token` |
        | `urn:ietf:params:oauth:grant-type:device_code` | `device_code` |
        | `urn:numberotp:params:grant-type:email_code` | `email`, `code`, `name?` — signs up new emails too |
        | `urn:numberotp:params:grant-type:id_token` | `provider` (`google`/`apple`), `id_token`, `nonce?`, `name?` |


        Optional on every grant: `platform` (`ios`, `android`, `extension`, `cli`, `mcp`), `device_name`, `scope`.
      tags: [Auth]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [grant_type], properties: { grant_type: { type: string } }, additionalProperties: true }
          application/x-www-form-urlencoded:
            schema: { type: object, required: [grant_type], properties: { grant_type: { type: string } }, additionalProperties: true }
      responses:
        '200':
          description: Tokens
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TokenResponse' }
        '400':
          description: "`invalid_grant`, `authorization_pending`, `slow_down`, `access_denied`, `expired_token`, …"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OAuthError' }

  /oauth/email-code:
    post:
      operationId: sendEmailCode
      summary: Email a Sign-In Code
      description: Sends a 6-digit code (valid 10 minutes) to exchange with the `email_code` grant. Same answer whether or not the account exists.
      tags: [Auth]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [email], properties: { email: { type: string, format: email } } }
      responses:
        '200': { description: Sent }
        '429': { description: Too many codes requested }

  /oauth/device/code:
    post:
      operationId: startDeviceSignIn
      summary: Start Device Sign-In
      description: >
        RFC 8628 device flow for the CLI, extension and MCP servers. Show `user_code`, open
        `verification_uri_complete` in a browser, then poll `/oauth/token` every `interval` seconds with
        `grant_type=urn:ietf:params:oauth:grant-type:device_code`.
      tags: [Auth]
      security: []
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                client: { type: string, enum: [cli, extension, mcp, other] }
                device_name: { type: string, example: "MacBook Pro — zsh" }
      responses:
        '200':
          description: Codes
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DeviceCode' }

  /oauth/device:
    get:
      operationId: getDeviceSignIn
      summary: Look Up a Device Code
      description: For the approval screen (numberotp.com/device, or the mobile app). Signed-in people only.
      tags: [Auth]
      parameters:
        - { in: query, name: user_code, required: true, schema: { type: string }, example: BCDF-GHJK }
      responses:
        '200': { description: The client asking to sign in }
        '404': { description: Invalid or expired }
    post:
      operationId: decideDeviceSignIn
      summary: Approve or Deny a Device
      tags: [Auth]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [user_code, action]
              properties:
                user_code: { type: string }
                action: { type: string, enum: [approve, deny] }
      responses:
        '200': { description: Decided }

  /oauth/revoke:
    post:
      operationId: revokeToken
      summary: Sign Out (Revoke a Refresh Token)
      tags: [Auth]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [token], properties: { token: { type: string } } }
      responses:
        '200': { description: Always 200 }


tags:
  - name: Auth
    description: Sign-in for apps, the browser extension, the CLI and MCP servers, and connected-device management.
  - name: Account
    description: Your profile, numbers, history, reminders, API keys and webhook.
  - name: Wallet
    description: Top-ups.
  - name: Events
    description: Live events (SSE) and push notification registration.
  - name: Public
    description: No authentication required. Rate-limited to 100 requests/minute per IP.
  - name: Activations
    description: Purchase numbers and retrieve OTP codes. All endpoints require authentication.
  - name: Reseller
    description: >
      Reseller management endpoints. Require Bearer authentication from a reseller-enabled account.
      Base URL: `https://api.numberotp.com/v1`
  - name: Reseller Public
    description: No authentication required. Called by sub-users on the reseller's white-label signup page.
