openapi: 3.1.1
info:
  title: Perfai Security API
  version: "1.1.0"
  description: >
    Partner-facing REST API for automating Perfai security testing: register apps,
    trigger security tests and vision (browser-automation) runs, poll run status,
    and retrieve vulnerability findings. All endpoints are JWT-authenticated and
    scoped to the caller's organization; cross-tenant access returns 404 (never
    403) to prevent enumeration. Errors follow RFC 9457 Problem Details.
servers:
  - url: https://api.perfai.ai/v1
    description: Perfai cloud
  - url: https://api.{customerDomain}/v1
    description: On-premise deployment
    variables:
      customerDomain:
        default: example.com

security:
  - bearerAuth: []

tags:
  - name: Apps
    description: App catalog — list, register, and poll registration.
  - name: Security Agent
    description: Trigger security tests and poll their lifecycle.
  - name: Vision Agent
    description: Trigger vision (browser-automation) runs and poll their lifecycle. Always browserless.
  - name: Vulnerabilities
    description: Retrieve security findings.
  - name: Reports
    description: List an app's security reports and download them as PDF.
  - name: Tasks
    description: Poll any asynchronous operation started by this API.

paths:
  /apps:
    get:
      tags: [Apps]
      operationId: listApps
      summary: List apps
      description: Returns apps visible to the authenticated tenant, paginated, newest first.
      parameters:
        - { name: page, in: query, schema: { type: integer, minimum: 1, default: 1 } }
        - { name: pageSize, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
        - { name: search, in: query, description: Case-insensitive partial match on app label / name., schema: { type: string } }
      responses:
        "200":
          description: Paginated app list.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AppsListResponse" }
        "401": { $ref: "#/components/responses/Unauthorized" }
    post:
      tags: [Apps]
      operationId: registerApp
      summary: Register app
      description: >
        Registers a target app and drives it to a testable state. No security test
        is auto-triggered — trigger tests explicitly via
        POST /apps/{appId}/security-agent. Onboarding depends on the input:
        (a) URL only, no credentials, no spec (the DEFAULT, createTestAccounts not
        false) — the platform runs full autonomous onboarding like the console
        "Automatic" prompt: it creates test accounts (auto sign-up), validates
        logins, discovers roles, provisions RBAC accounts, maps the app and
        completes registration (response carries an `onboarding` handle). If it
        can't sign up (no public sign-up / CAPTCHA / SSO / unreachable) it pauses
        and emails the caller rather than degrading to an unauthenticated test.
        (b) credentials and/or a spec supplied — the platform uses them and
        schedules the registration-completing run. (c) createTestAccounts=false
        with no spec — a browserless pass maps your API surface
        (pollable `specExtraction` handle) for an unauthenticated test. The app
        resource is created synchronously (201 + Location header) with
        registrationStatus IN_PROGRESS; poll GET /apps/{appId} until
        registrationStatus is COMPLETED, then trigger a test. Registration is
        completed by onboarding, not by a security test. Supplied
        credentials are stored encrypted and never returned.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RegisterApp" }
            examples:
              minimal:
                summary: URL only — autonomous onboarding with auto sign-up (default)
                value:
                  label: Payments App
                  appUrl: https://payments.example.com
              unauthenticated:
                summary: Unauthenticated / public app (no account creation)
                value:
                  label: Payments App
                  appUrl: https://payments.example.com
                  createTestAccounts: false
              withCredentials:
                summary: Registration with tenant credentials
                value:
                  label: Payments App
                  appUrl: https://payments.example.com
                  tenantOneCredentials:
                    - role: Admin
                      username: admin@example.com
                      password: "••••••••"
                    - role: User
                      username: user@example.com
                      password: "••••••••"
                  tenantTwoCredentials:
                    - role: Admin
                      username: tenant2-admin@example.com
                      password: "••••••••"
              specFirst:
                summary: Advanced — supply your own API spec
                value:
                  label: Payments App
                  appUrl: https://payments.example.com
                  spec: https://payments.example.com/openapi.json
      responses:
        "201":
          description: App registered; onboarding in progress.
          headers:
            Location:
              description: URL of the created app resource (poll for registrationStatus).
              schema: { type: string }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RegisterAppResponse" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/InsufficientCredits" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "409":
          description: >
            A usable app (COMPLETED, or actively onboarding) already exists for this
            URL — app-already-registered, includes the existing appId to reuse. A
            stopped app (INTERRUPTED, NEEDS_INPUT, COMPLETED_PARTIAL or CANCELLED, or
            a long-stuck IN_PROGRESS) is replaced with
            a fresh 201 instead (see the `replaced` field). If an app for this URL
            exists that was not registered through this API, it is never replaced —
            app-registered-outside-api.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "503":
          description: >
            onboarding-unavailable — this deployment does not have the onboarding
            workflow engine enabled, so autonomous sign-up cannot run. Register
            with a `spec` or with tenant credentials instead.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "500":
          description: registration-failed — the app was not registered; retry the request.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /apps/{appId}:
    get:
      tags: [Apps]
      operationId: getApp
      summary: Get app (poll registration)
      description: >
        Returns a single app including registrationStatus, with `reason` and
        `message` explaining it. Stop polling on COMPLETED, COMPLETED_PARTIAL,
        NEEDS_INPUT, INTERRUPTED or CANCELLED.
      parameters:
        - $ref: "#/components/parameters/AppId"
      responses:
        "200":
          description: The app.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AppDetail" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
    delete:
      tags: [Apps]
      operationId: deleteApp
      summary: Delete app
      description: >
        Permanently deletes an app you registered via this API and ALL of its
        data — runs, findings, mappings, and stored credentials. Irreversible.
        Only apps registered through this API can be deleted here; an app created
        in the console (or predating API source tracking) returns 409 — delete it
        in the console instead. Rate limit 5 requests / 60 s per IP.
      parameters:
        - $ref: "#/components/parameters/AppId"
      responses:
        "200":
          description: App and all of its data deleted.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeleteAppResponse" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: >
            app-registered-outside-api — the app was created in the console, not
            via this API, and cannot be deleted through it.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /apps/{appId}/security-agent:
    post:
      tags: [Security Agent]
      operationId: runSecurityAgent
      summary: Run Security Agent
      description: >
        Asynchronously schedules a security test for the app. Rate limit 10 requests / 60 s per IP.
      parameters:
        - $ref: "#/components/parameters/AppId"
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TriggerSecurityRun" }
      responses:
        "202":
          description: Run scheduled.
          headers:
            Location:
              description: Status URL for the run.
              schema: { type: string }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SecurityRunResponse" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/InsufficientCredits" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: A run is already active (run-already-active).
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /apps/{appId}/vulnerabilities:
    get:
      tags: [Vulnerabilities]
      operationId: getVulnerabilities
      summary: Get vulnerabilities
      description: >
        Returns security findings for the app. While a test is active the response
        carries status RUN_IN_PROGRESS — poll the run status endpoint and retry
        once COMPLETED.
      parameters:
        - $ref: "#/components/parameters/AppId"
        - { name: page, in: query, schema: { type: integer, minimum: 1, default: 1 } }
        - { name: pageSize, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
        - name: search
          in: query
          description: Free-text filter across the finding's text fields.
          schema: { type: string }
        - name: severity
          in: query
          description: Only return findings of this severity (case-insensitive).
          schema: { type: string, enum: [Critical, High, Medium, Low] }
        - name: isFixed
          in: query
          description: Filter by whether Perfai has confirmed the finding is fixed.
          schema: { type: boolean }
        - name: isDismissed
          in: query
          description: Filter by whether the finding has been dismissed as accepted risk.
          schema: { type: boolean }
      responses:
        "200":
          description: Findings (COMPLETED | NO_RUNS) or an in-progress marker (RUN_IN_PROGRESS).
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/VulnerabilitiesCompleted"
                  - $ref: "#/components/schemas/VulnerabilitiesInProgress"
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

  /vulnerabilities/{vulnerabilityId}:
    get:
      tags: [Vulnerabilities]
      operationId: getVulnerability
      summary: Get vulnerability
      description: >
        Returns a single security finding by id, scoped to your organization.
        Full finding detail is a paid feature — a free-tier (trial) organization
        receives 402.
      parameters:
        - $ref: "#/components/parameters/VulnerabilityId"
      responses:
        "200":
          description: The finding.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Vulnerability" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/UpgradeRequired" }
        "404": { $ref: "#/components/responses/NotFound" }

  /vulnerabilities/{vulnerabilityId}/dismiss:
    post:
      tags: [Vulnerabilities]
      operationId: dismissVulnerability
      summary: Dismiss vulnerability
      description: >
        Marks a finding as accepted risk so it stops appearing in the open findings
        list. The dismissal is recorded with the caller and comment, and later tests
        will not re-raise the finding. Reverse it with the reopen endpoint.
      parameters:
        - $ref: "#/components/parameters/VulnerabilityId"
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/VulnerabilityAction" }
      responses:
        "200":
          description: Finding dismissed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/VulnerabilityActionResponse" }
        "400": { description: Finding is already dismissed. }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { description: Caller has the Viewer role and cannot modify findings. }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /vulnerabilities/{vulnerabilityId}/fix:
    post:
      tags: [Vulnerabilities]
      operationId: markVulnerabilityFixed
      summary: Mark vulnerability fixed
      description: >
        Records that you have fixed the finding. This is a claim pending
        verification, not a verified result: if the next security test still detects
        the finding, the claim is dropped and the finding stays open. Reported
        separately from isFixed, which the platform sets on its own once a finding
        stops being detected.
      parameters:
        - $ref: "#/components/parameters/VulnerabilityId"
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/VulnerabilityAction" }
      responses:
        "200":
          description: Fix claim recorded.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/VulnerabilityActionResponse" }
        "400": { description: "Finding is already marked fixed, or is dismissed — reopen it first." }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { description: Caller has the Viewer role and cannot modify findings. }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /vulnerabilities/{vulnerabilityId}/reopen:
    post:
      tags: [Vulnerabilities]
      operationId: reopenVulnerability
      summary: Reopen vulnerability
      description: >
        Returns a finding to the open list. Undoes a dismissal or a fix claim —
        whichever state the finding is in.
      parameters:
        - $ref: "#/components/parameters/VulnerabilityId"
      responses:
        "200":
          description: Finding reopened.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/VulnerabilityActionResponse" }
        "400": { description: Finding is already open. }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { description: Caller has the Viewer role and cannot modify findings. }
        "404": { $ref: "#/components/responses/NotFound" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /apps/{appId}/reports:
    get:
      tags: [Reports]
      operationId: listReports
      summary: Get reports
      description: >
        Lists the security reports generated for the app, newest first. Each item
        carries a downloadUrl for fetching the PDF. Security reports are a paid
        feature — a free-tier (trial) organization receives 402.
      parameters:
        - $ref: "#/components/parameters/AppId"
        - { name: page, in: query, schema: { type: integer, minimum: 1, default: 1 } }
        - { name: pageSize, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
      responses:
        "200":
          description: The app's security reports (data may be empty).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SecurityReportsListResponse" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/UpgradeRequired" }
        "404": { $ref: "#/components/responses/NotFound" }

  /reports/{reportId}:
    get:
      tags: [Reports]
      operationId: getReport
      summary: Download report
      description: >
        Downloads a security report as a PDF. On success the body is the raw PDF
        (application/pdf), not JSON — store the bytes wherever you like. Only
        security reports registered to your organization are accessible. Security
        reports are a paid feature — a free-tier (trial) organization receives 402.
      parameters:
        - $ref: "#/components/parameters/ReportId"
      responses:
        "200":
          description: The report PDF.
          content:
            application/pdf:
              schema: { type: string, format: binary }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/UpgradeRequired" }
        "404": { $ref: "#/components/responses/NotFound" }

  /apps/{appId}/account-setup:
    post:
      tags: [Apps]
      operationId: runAccountSetup
      summary: Run Account Setup
      description: >
        Supplies test-account credentials for an app that cannot sign itself up —
        one with no public sign-up page, or behind a CAPTCHA, SSO wall or
        invite-only flow. Onboarding pauses in that situation rather than
        degrading to an unauthenticated test; submitting credentials here
        resumes it. Uses the same tenantOneCredentials / tenantTwoCredentials
        shape as register. Poll the returned taskId.
      parameters:
        - { $ref: "#/components/parameters/AppId" }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CreateTestAccounts" }
      responses:
        "200":
          description: Credentials stored; onboarding resumed if it was waiting on them.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CreateTestAccountsResponse" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: >
            App was not registered through this API
            (app-registered-outside-api) — add its credentials in the console.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /apps/{appId}/vision-agent:
    post:
      tags: [Vision Agent]
      operationId: runVisionAgent
      summary: Run Vision Agent
      description: >
        Asynchronously launches a vision (browser-automation) run for the app.
        Partner-triggered runs always execute browserless on the background
        browser pool — there is no mode parameter. Credentials are resolved
        server-side from the app's stored authentication; none travel in the
        request. Rate limit 5 requests / 60 s per IP.
      parameters:
        - $ref: "#/components/parameters/AppId"
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TriggerVisionRun" }
            examples:
              map:
                summary: Re-map the app (default)
                value: { operation: map }
              validateLogin:
                summary: Verify stored credentials still work
                value: { operation: validate-login }
      responses:
        "202":
          description: Vision run accepted.
          headers:
            Location:
              description: Status URL for the vision run.
              schema: { type: string }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/VisionRunResponse" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/InsufficientCredits" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: Vision run already active (vision-run-already-active, includes activeVisionRunId).
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "500":
          description: vision-task-create-failed — the run was not created; retry the request.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /tasks/{taskId}:
    get:
      tags: [Tasks]
      operationId: getTask
      summary: Get task status
      description: >
        Returns the current state of any task on this API — a registration, a
        security test, or a Vision Agent run. Every action that starts work
        returns a taskId; poll this URL until state is COMPLETED,
        COMPLETED_PARTIAL, NEEDS_INPUT, INTERRUPTED or CANCELLED.
      parameters:
        - { $ref: "#/components/parameters/TaskId" }
      responses:
        "200":
          description: Current task state.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Task" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >
        JWT login token tied to your Perfai user (not a separate API key). Obtain it
        via POST /api/v1/auth/token with your username and password (use the returned
        id_token) — the same login the web console performs. Carries org, user, and
        role; short-lived.

  parameters:
    AppId:
      name: appId
      in: path
      required: true
      schema: { type: string }
      description: MongoDB ObjectId of the app (from GET /apps or POST /apps).
    ReportId:
      name: reportId
      in: path
      required: true
      schema: { type: string }
      description: MongoDB ObjectId of the report (from GET /apps/{appId}/reports).
    TaskId:
      name: taskId
      in: path
      required: true
      schema: { type: string }
      description: >
        Task identifier returned by register, run-security-agent or
        run-vision-agent (for example task_wf_683def5678901abcd1234abc).
        Opaque — pass it back verbatim, do not parse it.
    VulnerabilityId:
      name: vulnerabilityId
      in: path
      required: true
      schema: { type: string }
      description: >
        MongoDB ObjectId of the finding — the `id` of an item from
        GET /apps/{appId}/vulnerabilities.

  responses:
    BadRequest:
      description: Validation error.
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    Unauthorized:
      description: Missing or expired JWT.
    Forbidden:
      description: Caller's role does not permit this operation (Viewer is read-only).
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    NotFound:
      description: Resource not found or belongs to a different tenant.
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    UpgradeRequired:
      description: The requested feature (e.g. reports) is paid — the organization is on the free tier and must upgrade.
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    InsufficientCredits:
      description: Organization credit balance exhausted (billing-enabled deployments only).
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    RateLimited:
      description: Rate limit exceeded. Back off and retry after the Retry-After header value.
      headers:
        Retry-After:
          schema: { type: integer }
          description: Seconds to wait before retrying.

  schemas:
    Problem:
      type: object
      description: RFC 9457 Problem Details.
      properties:
        type: { type: string, description: "Error type URI, e.g. https://perfai.ai/errors/app-already-registered" }
        title: { type: string }
      additionalProperties: true

    AppSummary:
      type: object
      properties:
        appId: { type: string }
        label: { type: string }
        appUrl: { type: string }
        basePath: { type: string }
        registrationStatus: { $ref: "#/components/schemas/RegistrationStatus" }
        reason: { $ref: "#/components/schemas/StateReason" }
        message: { $ref: "#/components/schemas/StateMessage" }
        createdAt: { type: [string, "null"], format: date-time }
        scheduleType:
          type: string
          enum: [none, nightly, custom, weekly_saturday, biweekly_saturday, monthly_first]
          description: >
            How often this app is re-tested automatically. Apps inherit your
            organization default at registration and fall back to `nightly`, so an
            app may be on a recurring cadence you did not request here — each run
            consumes credits. Change it in the console (Edit app); this API does
            not set it, matching the console prompt.
          example: nightly

    AppDetail:
      $ref: "#/components/schemas/AppSummary"

    DeleteAppResponse:
      type: object
      description: Confirmation that an app and all of its data were deleted.
      properties:
        appId: { type: string, description: The deleted app's id. }
        status: { type: string, enum: [DELETED], description: Always DELETED on success. }
        previousRegistrationStatus:
          oneOf:
            - $ref: "#/components/schemas/RegistrationStatus"
            - type: "null"
          description: The app's registrationStatus at the moment it was deleted.

    AppsListResponse:
      type: object
      properties:
        data:
          type: array
          items: { $ref: "#/components/schemas/AppSummary" }
        total: { type: integer }
        page: { type: integer }
        pageSize: { type: integer }

    SecurityReport:
      type: object
      description: One security report for an app.
      properties:
        reportId: { type: string, description: "Report id — pass to GET /reports/{reportId} (or use downloadUrl) to download the PDF." }
        appId: { type: string, description: The app this report belongs to. }
        reportType: { type: string, enum: [security], description: "Always \"security\" on this API." }
        format: { type: string, enum: [pdf], description: Report file format. }
        issuesCount: { type: [integer, "null"], description: Number of issues the report covers. }
        apiName: { type: string, description: App name at the time the report was generated. }
        runNumber: { type: [integer, "null"], description: Security test number the report was generated from. }
        createdAt: { type: [string, "null"], description: When the report was generated. }
        createdByEmail: { type: string, description: Who generated the report. }
        downloadUrl: { type: string, description: "Absolute URL to download the PDF (a GET returns application/pdf); relative when PUBLIC_API_BASE_URL is unset." }

    SecurityReportsListResponse:
      type: object
      properties:
        data:
          type: array
          items: { $ref: "#/components/schemas/SecurityReport" }
        total: { type: integer }
        page: { type: integer }
        pageSize: { type: integer }

    RegistrationStatus:
      type: string
      enum: [PENDING, IN_PROGRESS, NEEDS_INPUT, COMPLETED, COMPLETED_PARTIAL, INTERRUPTED, CANCELLED]
      description: >
        Onboarding state. Never FAILED.

        NEEDS_INPUT — onboarding stopped and is waiting for something only you
        can supply (`reason` says what: needs_login, out_of_credits,
        app_unreachable, …). Answer a login pause with
        POST /v1/apps/{appId}/account-setup.

        COMPLETED_PARTIAL — onboarding produced results, but part of it did not
        run (`reason` says why; needs_login means logged-in areas were not
        tested).

        INTERRUPTED — onboarding stopped on our side before producing a result.

        CANCELLED — a user stopped it.

        COMPLETED, COMPLETED_PARTIAL, INTERRUPTED and CANCELLED are terminal.
        Stop polling on NEEDS_INPUT too: nothing changes until you act.

    StateReason:
      type: [string, "null"]
      description: >
        Why a task or app is in its state. Null when the state needs no
        explanation. New values may be added; show `message` for any you do not
        recognise.
      enum:
        - needs_login
        - needs_roles
        - needs_access
        - needs_app_url
        - needs_spec
        - app_unreachable
        - out_of_credits
        - no_response
        - paused
        - partial_coverage
        - our_side_error
        - dependency_lost
        - null

    StateMessage:
      type: string
      description: One sentence for the user — the same wording the console shows for this state.
      example: We hit a snag — we're on it. Your results so far are saved.

    RoleCredential:
      type: object
      required: [role, username, password]
      additionalProperties: false
      description: >
        One authentication for a tenant: a role plus its username/password login.
        The API style (REST vs GraphQL) is detected automatically.
      properties:
        role: { type: string, maxLength: 100, description: 'Role this login represents (e.g. "Admin", "User", or a custom RBAC role). Drives privilege derivation and role-based access testing.' }
        username: { type: string, maxLength: 320, description: Username or email used to authenticate. }
        password: { type: string, maxLength: 1024, description: Password. Encrypted at rest; never logged or returned. }
        loginUrl: { type: string, format: uri, maxLength: 2048, description: URL where these credentials authenticate. Defaults to the app URL. }

    RegisterApp:
      type: object
      required: [appUrl]
      additionalProperties: false
      properties:
        label: { type: string, maxLength: 150, description: 'Human-readable app name. Optional — defaults to the host of appUrl when omitted.' }
        appUrl: { type: string, format: uri, maxLength: 2048, description: Base URL of the application under test (http/https). }
        spec:
          type: [string, "null"]
          maxLength: 2000000
          description: Advanced. A URL to your app's OpenAPI definition (or inline content) — provide it to skip discovery. Omit to let the platform map your API surface. REST/GraphQL is detected automatically.
        tenantOneCredentials:
          type: array
          maxItems: 20
          items: { $ref: "#/components/schemas/RoleCredential" }
          description: >
            Credentials for the primary tenant, one entry per role. Optional —
            omit to have the platform auto-create accounts (default), or for
            unauthenticated / public apps (with createTestAccounts=false). Each is
            stored as an encrypted auth record; admin/user/rbac roles are derived
            from the set.
        tenantTwoCredentials:
          type: array
          maxItems: 20
          items: { $ref: "#/components/schemas/RoleCredential" }
          description: Credentials for a second tenant, used for cross-tenant (BOLA) testing. Optional.
        createTestAccounts:
          type: boolean
          default: true
          description: >
            Whether the platform autonomously creates test accounts (auto sign-up)
            when no credentials are supplied — mirroring the console "Automatic"
            onboarding. Default true. Only applies when BOTH credentials AND spec
            are omitted; ignored otherwise. Set false to register for an
            unauthenticated (public-endpoint-only) test — no accounts are created,
            so authenticated / RBAC / cross-tenant (BOLA) tests will not run.
        skipEndpoints:
          type: array
          maxItems: 200
          items: { type: string, maxLength: 500, pattern: '^(\*|[A-Za-z]+):[^:]+$' }
          description: >
            Endpoints to exclude from every security test of this app, as
            "method:path" entries. Use it to keep destructive or disruptive
            operations out of scope — account deletion, logout, payment capture.
            Method may be a verb or "*"; path may use "**" as a glob. Applied as a
            blocklist, only when no include-filter is in force for the run.
          example: ["DELETE:/api/v1/users/{id}", "POST:/api/v1/payments/capture", "*:/internal/**"]
        headers:
          type: array
          maxItems: 50
          items: { type: string, maxLength: 4096 }
          description: >
            Extra HTTP headers sent with requests to the application under test, as
            "Name: value" entries — a gateway API key, a tenant selector, a feature
            flag the app requires. Sent as supplied; never returned by the API.
          example: ["X-Api-Key: 9f8c1e02-5b6a-4b1e", "X-Tenant-Id: acme"]
        maxSteps:
          type: integer
          minimum: 1
          maximum: 1000
          description: >
            How many exploration steps the platform may take while mapping your
            API surface. Raise it for large apps with deep navigation or many
            nested workflows — a mapping missing endpoints is the usual reason to.
            Higher values map more thoroughly but lengthen registration. Applies
            only when the platform maps the app itself (no `spec` supplied). Omit
            to use your organization's configured value,
            which itself defaults to 150.
          example: 300

    SpecExtraction:
      type: object
      description: Present only when createTestAccounts=false and no spec was supplied and an API-surface mapping run was enqueued.
      properties:
        taskId: { type: string }
        state: { $ref: "#/components/schemas/VisionRunState" }
        statusUrl: { type: string, description: Poll this until the vision run reaches COMPLETED. }

    Onboarding:
      type: object
      description: Present when the platform started autonomous onboarding (auto sign-up) because no credentials/spec were supplied and createTestAccounts was not false.
      properties:
        mode: { type: string, example: auto-signup, description: Onboarding mode driving this registration. }
        message: { type: string, description: Human-readable note on what the platform is doing. }

    RegisterAppResponse:
      type: object
      properties:
        appId: { type: string }
        registrationStatus:
          allOf:
            - $ref: "#/components/schemas/RegistrationStatus"
          description: >
            Returned as IN_PROGRESS. The platform completes onboarding on its own;
            poll GET /apps/{appId} until COMPLETED. Registration is NOT completed by
            a security test — a test requires COMPLETED as a precondition.
        reason: { $ref: "#/components/schemas/StateReason" }
        message: { $ref: "#/components/schemas/StateMessage" }
        createdAt: { type: string, format: date-time }
        statusUrl: { type: string }
        onboarding:
          oneOf:
            - $ref: "#/components/schemas/Onboarding"
            - type: "null"
          description: Present on the default auto-signup path.
        specExtraction:
          oneOf:
            - $ref: "#/components/schemas/SpecExtraction"
            - type: "null"
          description: Present only on the createTestAccounts=false no-spec path. Absent when a spec/credentials were supplied, auto-signup ran, or the vision run could not be enqueued.
        replaced:
          oneOf:
            - $ref: "#/components/schemas/Replaced"
            - type: "null"
          description: >
            Present when this registration replaced a previous, unusable app for
            the same URL (INTERRUPTED/NEEDS_INPUT/COMPLETED_PARTIAL/CANCELLED/PENDING,
            or a stuck IN_PROGRESS). A
            COMPLETED or actively-onboarding app is reused via 409 instead.

    Replaced:
      type: object
      description: The previous unusable app for this URL that this registration replaced.
      properties:
        previousAppId: { type: string }
        previousStatus:
          allOf:
            - $ref: "#/components/schemas/RegistrationStatus"
          description: "The replaced app's state: INTERRUPTED, NEEDS_INPUT, COMPLETED_PARTIAL, CANCELLED, PENDING, or a stuck IN_PROGRESS."


    CreateTestAccounts:
      type: object
      additionalProperties: false
      required: [tenantOneCredentials]
      properties:
        tenantOneCredentials:
          type: array
          minItems: 1
          maxItems: 20
          description: >
            Credentials for the primary tenant, one entry per role. At least one
            is required — without a usable account the app cannot be tested
            authenticated.
          items: { $ref: "#/components/schemas/RoleCredential" }
        tenantTwoCredentials:
          type: array
          maxItems: 20
          description: >
            Credentials for a second tenant. Supply these to enable cross-tenant
            (BOLA) testing; without a second tenant those checks cannot run.
          items: { $ref: "#/components/schemas/RoleCredential" }

    CreateTestAccountsResponse:
      type: object
      required: [appId, taskId, accountsSaved, onboardingResumed, statusUrl]
      properties:
        appId: { type: string }
        taskId:
          type: string
          description: Registration task handle — poll GET /v1/tasks/{taskId}.
          example: task_reg_683abc1234567890abcdef12
        accountsSaved:
          type: integer
          description: How many tenant credential sets were stored.
          example: 2
        onboardingResumed:
          type: boolean
          description: >
            True when onboarding was paused waiting for these credentials and has
            now resumed. False means they are stored but nothing was waiting on
            them.
          example: true
        statusUrl: { type: string }

    TriggerSecurityRun:
      type: object
      additionalProperties: false
      description: >
        No request body — it runs all available test categories for the app
        identified by the appId path segment.

    SecurityRunState:
      type: string
      description: Same vocabulary as TaskState. Never FAILED.
      enum: [QUEUED, RUNNING, NEEDS_INPUT, COMPLETED, COMPLETED_PARTIAL, INTERRUPTED, CANCELLED]

    SecurityRunResponse:
      type: object
      properties:
        taskId: { type: string }
        appId: { type: string }
        state: { $ref: "#/components/schemas/SecurityRunState" }
        reason: { $ref: "#/components/schemas/StateReason" }
        message: { $ref: "#/components/schemas/StateMessage" }
        createdAt: { type: [string, "null"], format: date-time }
        updatedAt: { type: [string, "null"], format: date-time }
        statusUrl: { type: string }
        runNumber: { type: integer, description: Monotonically increasing counter per app (status endpoint only). }

    TriggerVisionRun:
      type: object
      additionalProperties: false
      properties:
        operation:
          type: string
          enum: [map, validate-login, discover-roles, verify-rbac]
          default: map
          description: >
            map — explore the app and generate/refresh the API spec;
            validate-login — verify stored credentials still work;
            discover-roles — discover RBAC roles;
            verify-rbac — re-verify role capabilities.

    TaskState:
      type: string
      description: >
        Shared lifecycle vocabulary for every task. Never FAILED; `reason` and
        `message` on the task say why it is in its state.

        NEEDS_INPUT means the work has stopped and is waiting for something only
        you can supply — working test accounts, a credit top-up, a reachable
        app. A login pause is answered with POST /v1/apps/{appId}/account-setup,
        after which the task returns to RUNNING. Stop polling on it: nothing
        will change until you act.

        COMPLETED_PARTIAL means the work produced results but part of it did not
        run (`reason` says why).

        INTERRUPTED means the work stopped on our side before producing a result
        — deliberately not folded into COMPLETED, because "completed with zero
        findings" and "we do not know what it would have found" are different
        answers.

        CANCELLED means a user stopped the work before it finished.

        COMPLETED, COMPLETED_PARTIAL, INTERRUPTED and CANCELLED are terminal.
      enum: [QUEUED, RUNNING, NEEDS_INPUT, COMPLETED, COMPLETED_PARTIAL, INTERRUPTED, CANCELLED]

    Intervention:
      type: object
      description: >
        What the platform is waiting for while a task is NEEDS_INPUT.

        Most pauses are cleared by changing something in your own application —
        granting a permission, clearing a CAPTCHA, or fixing whatever made a step
        fail repeatedly. Supplying test-account credentials is the one case this
        API can answer directly, via POST /v1/apps/{appId}/account-setup.
        For every other type, resolving the pause is a console action; this
        endpoint reports it so you know what to fix.
      required: [type, title, fields]
      properties:
        type:
          type: string
          enum: [manual_credentials, otp_mfa, role_define, permission_fix, manual_account, generic_confirm]
          example: generic_confirm
        title:
          type: string
          example: This step keeps failing and needs your input to continue
        reason:
          type: string
          description: Underlying failure that caused the pause, when one was recorded.
        fields:
          type: array
          description: >
            Values the platform would need to continue automatically. Often empty —
            most pauses need a change in your application rather than data from you.
          items:
            type: object
            required: [key, label, type, required]
            properties:
              key: { type: string, example: username }
              label: { type: string, example: Username / email }
              type: { type: string, enum: [text, password, otp, select] }
              required: { type: boolean }
              options: { type: array, items: { type: string } }
        expiresAt:
          type: string
          format: date-time
          nullable: true

    SecurityTestResult:
      type: object
      properties:
        runNumber:
          type: integer
          description: Sequence number of this test among the app's security tests.
          example: 7
        vulnerabilitiesUrl:
          type: string
          description: >
            Where to read the findings. Present only once state is COMPLETED — a
            partial, interrupted or waiting test has no trustworthy findings to offer.
          example: https://api.perfai.ai/v1/apps/683abc1234567890abcdef12/vulnerabilities
        intervention:
          $ref: "#/components/schemas/Intervention"

    VisionRunResult:
      type: object
      properties:
        operation:
          type: string
          description: The vision operation this run performed.
          example: map

    RegistrationResult:
      type: object
      properties:
        registrationStatus:
          allOf:
            - $ref: "#/components/schemas/RegistrationStatus"
          description: Onboarding state of the app. Always agrees with the task `state`.
          example: IN_PROGRESS
        intervention:
          $ref: "#/components/schemas/Intervention"

    Task:
      type: object
      required: [taskId, type, appId, state, reason, message, createdAt, updatedAt, result]
      properties:
        taskId:
          type: string
          description: Opaque task identifier. Pass it back verbatim; do not parse it.
          example: task_wf_683def5678901abcd1234abc
        type:
          type: string
          description: What kind of work this task represents.
          enum: [security-agent, vision-agent, registration]
          example: security-agent
        appId:
          type: string
          example: 683abc1234567890abcdef12
        state: { $ref: "#/components/schemas/TaskState" }
        reason: { $ref: "#/components/schemas/StateReason" }
        message: { $ref: "#/components/schemas/StateMessage" }
        createdAt: { type: string, format: date-time, nullable: true }
        updatedAt:
          type: string
          format: date-time
          nullable: true
          description: Null if the task has not changed since it was created.
        result:
          description: >
            Type-specific detail; the shape follows `type`.
          oneOf:
            - { $ref: "#/components/schemas/SecurityTestResult" }
            - { $ref: "#/components/schemas/VisionRunResult" }
            - { $ref: "#/components/schemas/RegistrationResult" }

    VisionRunState:
      type: string
      description: Same vocabulary as TaskState. Never FAILED.
      enum: [QUEUED, RUNNING, NEEDS_INPUT, COMPLETED, COMPLETED_PARTIAL, INTERRUPTED, CANCELLED]

    VisionRunResponse:
      type: object
      properties:
        taskId: { type: string }
        appId: { type: string }
        operation: { type: string, description: Vision operation (internally created runs may surface their raw task type). }
        state: { $ref: "#/components/schemas/VisionRunState" }
        reason: { $ref: "#/components/schemas/StateReason" }
        message: { $ref: "#/components/schemas/StateMessage" }
        createdAt: { type: [string, "null"], format: date-time }
        updatedAt: { type: [string, "null"], format: date-time }
        statusUrl: { type: string }

    Vulnerability:
      type: object
      description: >
        A security finding, projected onto the public contract — internal test
        plumbing (token, decodedKey, errors, buildDetails) is never emitted. This
        is the same detail the Perfai dashboard shows a user. Only id, label,
        severity, path and method are present on every finding; every other field
        is conditional and omitted when the scan produced no value for it.
      properties:
        id: { type: string, description: "Finding identifier. Always present." }
        label: { type: string, description: "Canonical finding name from the security-category registry. Always present." }
        title: { type: string }
        severity: { type: string, enum: [Critical, High, Medium, Low], description: "Always present." }
        path: { type: string, description: "API path where the issue was found. Always present." }
        method: { type: string, description: "HTTP method of the affected endpoint. Always present." }
        uiPath: { type: string, description: "UI route the finding was reproduced through." }
        updated_severity: { type: string, description: "Severity after a manual override." }
        impact: { type: string, description: "Business and security impact summary." }
        issueType: { type: string, description: "security or privacy." }
        action: { type: string, description: "Action classification the scanner assigned." }
        intent: { type: string, description: "Intended request behaviour the test exercised." }
        owasp: { type: string, description: "OWASP API Security Top 10 reference (e.g. API1:2023)." }
        cwe: { type: string, description: "CWE identifier (e.g. CWE-639)." }
        cvss_score: { type: number, description: "CVSS v3 base score (0.0-10.0)." }
        cvss_vector: { type: string, description: "CVSS v3 vector string." }
        isPII: { type: boolean }
        isPCI: { type: boolean }
        isHIPAA: { type: boolean }
        explainer: { type: string, description: "Technical explanation of the vulnerability." }
        remediation: { type: string, description: "Recommended fix." }
        additionalDetails:
          type: object
          additionalProperties: true
          description: >
            Deep-dive analysis when available: description, StepsToReproduce,
            impact_analysis, mitigation, long_solution, references, conclusion,
            copilot_prompt, workingExamples. Which keys are present varies by
            finding.
        request: { type: string, description: "cURL reproducer for the authenticated request." }
        response: { type: object, description: "Response body observed for the authenticated request." }
        unsecureRequest: { type: string, description: "cURL reproducer for the same call made without authentication." }
        unsecuredResponse: { type: object, description: "Response body observed for the unauthenticated request." }
        requestSchema: { type: object, description: "JSON Schema of the request body." }
        responseSchema: { type: object, description: "JSON Schema of the response body." }
        fields: { type: array, items: { type: object }, description: "Affected or sensitive fields, each with a name, data type and location." }
        isFixed:
          type: boolean
          description: >
            Set by the platform once a previously-reported finding stops being
            detected by a later test. Not settable by callers.
        isDismissed: { type: boolean }
        fixClaimed:
          type: boolean
          description: >
            Someone asserted this finding is fixed — a claim pending
            verification, distinct from isFixed. If the next test still detects
            the finding, the claim is dropped and the finding stays open.
        fixClaimedAt: { type: [string, "null"], format: date-time }
        fixClaimedByEmail: { type: [string, "null"] }
        fixComment: { type: [string, "null"] }
        isCustomIssue: { type: boolean, description: "true for a manually created finding." }
        created_on: { type: [string, "null"], format: date-time }
        updated_on: { type: [string, "null"], format: date-time }
      additionalProperties: true

    VulnerabilityAction:
      type: object
      properties:
        comment:
          type: string
          maxLength: 1000
          description: >
            Why the finding was dismissed or marked fixed. Stored on the finding
            and, for dismissals, on the audit record.
      additionalProperties: false

    VulnerabilityActionResponse:
      type: object
      required: [status, vulnerability]
      properties:
        status:
          type: string
          enum: [DISMISSED, FIX_CLAIMED, OPEN]
          description: State of the finding after the action.
        vulnerability: { $ref: "#/components/schemas/Vulnerability" }

    VulnerabilitiesCompleted:
      type: object
      properties:
        status: { type: string, enum: [COMPLETED, NO_RUNS] }
        data:
          type: array
          items: { $ref: "#/components/schemas/Vulnerability" }
        total: { type: integer }
        page: { type: integer }
        pageSize: { type: integer }
        lastRunId: { type: [string, "null"] }
        lastRunCompletedAt: { type: [string, "null"], format: date-time }

    VulnerabilitiesInProgress:
      type: object
      properties:
        status: { type: string, enum: [RUN_IN_PROGRESS] }
        message: { type: string }
        activeRunId: { type: string }
        activeRunState: { $ref: "#/components/schemas/SecurityRunState" }
