openapi: 3.1.0
info:
  title: Meshlet API
  version: 0.1.0-draft
  description: >
    Meshlet management API draft (Phase 0). Source of truth for the contract is
    docs/architecture/api-contract.md. Status codes and error codes follow the
    unified error structure. Config-mutating responses carry revision_id and
    apply_status (ADR-009).
    KNOWN GAP (2026-11-05 audit): endpoints added after 2026-10-15 - 2FA
    (/auth/2fa/*), service publishing (/networks/{id}/publish/*,
    /publish/routes/check, /agent/publish-health), task dispatch
    (/networks/{id}/tasks*, /agent/tasks/*), device labels, peer endpoint
    exchange and /update-manifest - are implemented in apps/server but NOT yet
    specified here; see the addendum table in
    docs/zh/architecture/api-contract.md. Do not generate clients from this
    file until those paths are added.
servers:
  - url: /api/v1
security:
  - sessionCookie: []
  - apiToken: []
tags:
  - name: auth
  - name: networks
  - name: devices
  - name: routes
  - name: aliases
  - name: segments
  - name: diagnostics
  - name: status
paths:
  /auth/bootstrap:
    post:
      security: []
      tags: [auth]
      summary: Create the first admin (empty database only; closes with 409 afterwards)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, password]
              properties:
                email: { type: string, format: email }
                password: { type: string, format: password, minLength: 12 }
      responses:
        "201":
          description: Admin created, session cookie set
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Session" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationError" }
  /auth/login:
    post:
      security: []
      tags: [auth]
      summary: Login (rate limited, 5 failed attempts per email per 15 min)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, password]
              properties:
                email: { type: string }
                password: { type: string, format: password }
      responses:
        "200":
          description: Session cookie set
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Session" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429":
          description: Too many failed attempts
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  /auth/logout:
    post:
      security: []
      tags: [auth]
      summary: Logout (revokes the session cookie if present)
      responses:
        "204": { description: No content }
  /auth/me:
    get:
      tags: [auth]
      summary: Current user
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/User" }
        "401": { $ref: "#/components/responses/Unauthorized" }
  /auth/tokens:
    post:
      tags: [auth]
      summary: Issue an API token for external systems (raw token returned once)
      description: >
        Machine credential for long-lived API callers (e.g. cockpit). The raw
        token (mlt_ + 64 hex) is returned exactly once; the server stores only
        the SHA-256 digest. Mutating request: still requires the CSRF header
        X-Requested-With: XMLHttpRequest.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ApiTokenCreate" }
      responses:
        "201":
          description: Token created; raw token appears only in this response
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApiTokenCreated" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "422": { $ref: "#/components/responses/ValidationError" }
    get:
      tags: [auth]
      summary: List the caller's API tokens (never includes token material)
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/ApiToken" }
        "401": { $ref: "#/components/responses/Unauthorized" }
  /auth/tokens/{token_id}:
    delete:
      tags: [auth]
      summary: Revoke an API token (takes effect immediately; owner only)
      parameters:
        - { name: token_id, in: path, required: true, schema: { type: string } }
      responses:
        "204": { description: Revoked }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
  /audit:
    get:
      tags: [auth]
      summary: Audit events (newest first, paginated)
      description: >
        Sensitive operations trail (§16.5): login success/failure, bootstrap,
        logout, network/invite/route/device/API-token mutations, config apply
        and rollback (failures included). Never contains passwords, private
        keys, invite tokens, or other long-lived secret material — only ids,
        names, scopes, and structured metadata. Read-only: no CSRF header
        required.
      parameters:
        - { name: limit, in: query, schema: { type: integer, default: 50, maximum: 500 } }
        - { name: offset, in: query, schema: { type: integer, default: 0 } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AuditPage" }
        "401": { $ref: "#/components/responses/Unauthorized" }
  /system/metrics:
    get:
      tags: [system]
      summary: Runtime metrics (Prometheus text format)
      description: >
        Operational metrics (§17.2): control-plane counters (config apply
        success/failure, rollback results, route conflicts, agent heartbeats,
        HTTP requests by route and status class, response bytes) and
        data-plane evidence gauges computed at scrape time from mesh state
        (devices online, active peers, last handshake time, interface state,
        alias apply status). Never judge end-to-end network health from a
        single metric — combine control-plane and data-plane sources (see
        docs/architecture/observability.md). Management-plane authentication
        required: session cookie or read-scope API token.
      responses:
        "200":
          description: OK
          content:
            text/plain:
              schema:
                type: string
              example: |
                # TYPE meshlet_config_apply_total counter
                meshlet_config_apply_total{result="applied"} 3
                meshlet_config_apply_total{result="failed"} 1
                meshlet_devices_online 2
        "401": { $ref: "#/components/responses/Unauthorized" }
  /system/backup:
    post:
      tags: [system]
      summary: Take a consistent local backup (§17.4)
      description: >
        Consistent single-file snapshot (SQLite online backup semantics): the
        file is independently openable, schema and migrations complete, content
        self-consistent at the backup moment. Writes only the configured
        [backup] dir — no external upload of any kind. Backups are never
        overwritten (same-name target → 409). Response carries the content
        summary read back from the backup file itself. Restore is offline:
        `meshlet-server restore <backup.db> [config.toml]` (§17.4); both
        backup and restore are audit-logged (system.backup / system.restore).
        Management-plane authentication required: session cookie or
        write-scope API token (CSRF guard applies).
      responses:
        "200":
          description: Backup written
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BackupResponse" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "409": { $ref: "#/components/responses/Conflict" }
        "503": { $ref: "#/components/responses/ServiceUnavailable" }
  /networks:
    get:
      tags: [networks]
      summary: List networks (paginated)
      parameters:
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
        - { name: offset, in: query, schema: { type: integer, minimum: 0, default: 0 } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/NetworkList" }
    post:
      tags: [networks]
      summary: Create network (CIDR validated, immutable after creation)
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/NetworkCreate" }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Network" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationError" }
  /networks/{network_id}/devices:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    get:
      tags: [devices]
      summary: List devices
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeviceList" }
  /networks/{network_id}/invites:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    post:
      tags: [devices]
      summary: Create one-time enrollment invite (token stored as digest, ADR-010)
      description: >
        The raw token is returned only in this response; the server stores the
        SHA-256 digest (§11.3). Invites support expiry, revocation and a use-count
        limit, and are never logged.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                expires_at: { type: string, format: date-time, description: Optional expiry, e.g. "2026-11-01T00:00:00Z" }
                max_uses: { type: integer, minimum: 1, default: 1 }
      responses:
        "201":
          description: Created; token shown once
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Invite" }
        "400": { $ref: "#/components/responses/Error" }
        "404": { $ref: "#/components/responses/Error" }
        "422": { $ref: "#/components/responses/Error" }

  /networks/{network_id}/invites/{invite_id}:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { name: invite_id, in: path, required: true, schema: { type: string } }
    delete:
      tags: [devices]
      summary: Revoke an invite (stops further enrollment, §11.3)
      responses:
        "204": { description: Revoked }
        "404": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Error" }

  # Agent-facing: no console session required. Private key never leaves the client (§11.2).
  /device-registrations:
    post:
      security: []
      tags: [devices]
      summary: Self-register a device with a bootstrap token (ZeroTier-style, §11.2b)
      description: >
        The device presents a long-lived, revocable bootstrap token (created by an
        operator in the control center) and its public key. The server records a
        pending registration — no virtual IP is allocated and the device does not
        appear in the desired config until an operator approves it. The response
        carries the agent Bearer credential, returned only once (§11.3); the
        credential stays valid through approval (the device id does not change).
        Unknown fields are rejected (no private key material may be sent, §11.2).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RegisterDevice" }
      responses:
        "201":
          description: Registration recorded, status pending
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RegisterDeviceResponse" }
        "400": { $ref: "#/components/responses/Error" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationError" }
  /networks/{network_id}/registrations:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    get:
      tags: [devices]
      summary: List pending device registrations (approval queue)
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeviceRegistrationList" }
        "404": { $ref: "#/components/responses/Error" }
  /networks/{network_id}/devices/{device_id}/approve:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { $ref: "#/components/parameters/DeviceId" }
    post:
      tags: [devices]
      summary: Approve a pending registration — device becomes Active
      description: >
        Allocates the virtual IP now (ADR-004), promotes the registration to a
        device row under the same device id (its agent credential keeps working),
        and records a new config revision (ADR-009). Revoking the device later
        follows the existing revoke flow.
      responses:
        "201":
          description: Approved; virtual IP allocated, revision recorded
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApproveRegistration" }
        "404": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Conflict" }
  /networks/{network_id}/devices/{device_id}/deny:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { $ref: "#/components/parameters/DeviceId" }
    post:
      tags: [devices]
      summary: Deny a pending registration — registration and credential removed
      description: >
        Removes the registration row and the agent credential issued at
        registration. No config revision is recorded: the desired config never
        contained pending devices.
      responses:
        "204": { description: Denied }
        "404": { $ref: "#/components/responses/Error" }
  /networks/{network_id}/bootstrap-tokens:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    post:
      tags: [devices]
      summary: Create a bootstrap token for device self-registration (§11.2b)
      description: >
        Long-lived, revocable, optionally use-count-limited enrollment entry
        credential. The raw token is returned only in this response; the server
        stores the SHA-256 digest (§11.3).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BootstrapTokenCreate" }
      responses:
        "201":
          description: Created; token shown once
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BootstrapTokenCreated" }
        "400": { $ref: "#/components/responses/Error" }
        "404": { $ref: "#/components/responses/Error" }
        "422": { $ref: "#/components/responses/ValidationError" }
    get:
      tags: [devices]
      summary: List bootstrap tokens (metadata only, no credential material)
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BootstrapTokenList" }
        "404": { $ref: "#/components/responses/Error" }
  /networks/{network_id}/bootstrap-tokens/{token_id}:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { name: token_id, in: path, required: true, schema: { type: string } }
    delete:
      tags: [devices]
      summary: Revoke a bootstrap token (stops further self-registrations; pending registrations unaffected)
      responses:
        "204": { description: Revoked }
        "404": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Error" }
  /enroll:
    post:
      security: []
      tags: [devices]
      summary: Enroll a device with an invite token (public key only)
      description: >
        The server validates and consumes the invite, allocates a virtual IP
        (ADR-004) and records the public key. Requests must not carry private key
        material — unknown fields are rejected with 422.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Enroll" }
      responses:
        "201":
          description: Device created; virtual IP assigned
          content:
            application/json:
              schema: { $ref: "#/components/schemas/EnrollResponse" }
        "400": { $ref: "#/components/responses/Error" }
        "404": { $ref: "#/components/responses/Error" }
        "409": { $ref: "#/components/responses/Error" }
        "422": { $ref: "#/components/responses/Error" }
  /agent/heartbeat:
    post:
      security:
        - agentToken: []
      tags: [devices]
      summary: Agent heartbeat / status report (§14.1)
      description: >
        Records the report time and, optionally, the latest WireGuard handshake
        the agent read locally. Authenticated with a Bearer agent token issued at
        enrollment — agent and management APIs are separate auth boundaries (§13.7).
      parameters:
        - name: Authorization
          in: header
          required: true
          schema: { type: string }
          description: Bearer <agent_token>
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Heartbeat" }
      responses:
        "200":
          description: Report recorded; current presence verdict returned
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HeartbeatResponse" }
        "400": { $ref: "#/components/responses/Error" }
        "401": { $ref: "#/components/responses/Error" }
        "404": { $ref: "#/components/responses/Error" }
        "422": { $ref: "#/components/responses/Error" }
  /agent/device/applied:
    post:
      security:
        - agentToken: []
      tags: [devices]
      summary: Report execution of the exact current device plan
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [desired_revision, plan_hash]
              properties:
                desired_revision: { type: integer, minimum: 1 }
                plan_hash: { type: string }
                error: { type: [string, "null"], maxLength: 4096 }
      responses:
        "204": { description: Receipt recorded; resource status recomputed from exact device receipts }
        "400": { description: Stale revision, mismatched hash, hub not applied, or invalid input }
        "401": { $ref: "#/components/responses/Unauthorized" }
  /agent/device/desired:
    get:
      security:
        - agentToken: []
      tags: [devices]
      summary: Desired data plane plan for the calling device (§16.4)
      description: >
        Returns the calling device's structured data plane plan: tunnel, routes,
        gateway-side NAT rules and the desired config hash. The server never
        sends shell commands — the agent consumes this typed object and replays
        its local backend only when something changed (ADR-007).
        `private_key` is always null (ADR-010: the private key never leaves the
        device). Returns 503 `dataplane_not_configured` when the server has
        `[dataplane] enabled = false`, so an agent retries instead of treating
        "not configured" as "already effective".
      parameters:
        - name: Authorization
          in: header
          required: true
          schema: { type: string }
          description: Bearer <agent_token>
      responses:
        "200":
          description: Desired plan for the calling device
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DevicePlan" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { $ref: "#/components/responses/NotFound" }
        "503": { $ref: "#/components/responses/ServiceUnavailable" }
  /networks/{network_id}/devices/{device_id}/revoke:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { $ref: "#/components/parameters/DeviceId" }
    post:
      tags: [devices]
      summary: Revoke device (full chain, section 11.5)
      description: >
        Marks the device revoked (immediately invalidates its agent token) and
        removes the LAN routes it published from the desired config, recording
        a new revision. Applying that revision removes the device's WireGuard
        peer; last-good recovery never restores peers for revoked devices.
        Idempotent: revoking an already-revoked device is 409.
      responses:
        "202":
          description: Accepted; carries revision
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RevisionRef" }
        "409": { $ref: "#/components/responses/Conflict" }
  /networks/{network_id}/routes:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    get:
      tags: [routes]
      summary: List LAN routes
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/LanRoute" }
    post:
      tags: [routes]
      summary: Publish LAN route (return-path mode required, ADR-005)
      description: >
        Rejected creates are never silent (archive §8.3): a destination that
        overlaps the overlay or an existing LAN route answers 409 naming the
        conflicting counterpart (existing route id and CIDR) and mutates
        nothing — existing routes are never overwritten. Clients should offer
        an equal-prefix Alias mapping for the remote LAN instead. Exception
        (ADR-006 flagship scenario): when both the new and the existing route
        are alias-mode, overlapping real LAN prefixes are accepted — two sites
        may each own a 192.168.1.0/24 reached through their distinct Alias
        prefixes; the externally visible forwarding prefixes are the Aliases
        (uniqueness enforced at Alias creation), and real prefixes never enter
        the tunnel forwarding plane.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/LanRouteCreate" }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LanRoute" }
        "409":
          description: >
            Destination overlaps the overlay or an existing route in this
            network; the message names the counterpart. Nothing is changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  /networks/{network_id}/routes/{route_id}:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { $ref: "#/components/parameters/RouteId" }
    get:
      tags: [routes]
      summary: Route detail
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LanRoute" }
    delete:
      tags: [routes]
      summary: Delete route
      responses:
        "204": { description: No content }
  /networks/{network_id}/aliases:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    get:
      tags: [aliases]
      summary: List aliases
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/AliasMapping" }
    post:
      tags: [aliases]
      summary: Create alias (equal prefix length enforced, ADR-006)
      description: >
        Binds a mapping to an alias-mode LAN route (archive §12.6): one
        mapping per route, the gateway must be active. `target_cidr` is NOT
        accepted — it is derived server-side from the bound route's
        destination, so a target mismatch is structurally impossible at
        creation. Prefix length must equal the target's (ADR-006) and the
        alias prefix must differ from it; both answer 400. Rejected creates
        are never silent (archive §8.3): the alias prefix overlapping the
        overlay, an existing alias, or an existing route destination answers
        409 naming the counterpart and mutates nothing (these overlaps count
        toward the route-conflict metric, §17.2).
        Protocol boundary (archive §9.6): an alias covers the IPv4/IPv6
        unicast routing layer only. Broadcast, multicast and L2-discovery
        protocols (ARP/NDP, mDNS, DHCP broadcast domains) are NOT carried
        across an alias — it is not an L2 bridge and not an application
        proxy. Applications that embed their own IP inside the protocol
        payload may break under translation, and controlled_snat rewrites
        the source IP seen on the LAN. The first release does not claim
        full protocol transparency. Kernel-side NAT execution is part of
        the data plane (ADR-007): until it lands, the revision apply
        reports deterministic failure instead of pretending success (§10.3).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AliasCreate" }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AliasMapping" }
        "400":
          description: >
            Bad CIDR, prefix length mismatch with the bound route, alias
            equal to its target, unknown translation_mode, or the route is
            not in alias mode.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Network, bound route (in this network), or gateway not found.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: >
            Prefix overlaps the overlay, an existing alias, or an existing
            route destination (message names the counterpart); gateway
            inactive; or the route already has a mapping (one per route,
            §12.6). Nothing is changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  /networks/{network_id}/aliases/{alias_id}:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { $ref: "#/components/parameters/AliasId" }
    get:
      tags: [aliases]
      summary: Alias detail
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AliasMapping" }
        "404": { description: Unknown alias (or network). }
    delete:
      tags: [aliases]
      summary: Delete alias (removes the bound route in the same revision, §12.6)
      description: >
        Ownership-unit cleanup (archive §12.6): the mapping and its bound
        alias-mode route are removed together and one revision records the
        change. Kernel-side NAT rule removal rides that revision's apply
        (ADR-007 — deterministic failure until the data plane lands).
        The bound route cannot outlive its alias: deleting the route instead
        cascades the alias the same way. There is no update path — change a
        mapping by deleting and recreating it (each records a new revision).
      responses:
        "204": { description: No content }
        "404": { description: Unknown alias (or network). }
  /networks/{network_id}/segments:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    get:
      tags: [segments]
      summary: List network segments
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Segment" }
    post:
      tags: [segments]
      summary: Create a non-default segment
      description: >
        A created segment must be a strict subnet of the network overlay and
        must not reuse an existing exact CIDR. `default` is immutable and is
        created by the network itself. Rejected creates record no revision.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SegmentCreate" }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Segment" }
        "400":
          description: Invalid CIDR, empty name, segment outside the overlay, or CIDR equal to the overlay.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: Network name is reserved, or an existing segment uses the same exact CIDR. Nothing is changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  /networks/{network_id}/segment-grants:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    get:
      tags: [segments]
      summary: List one-way segment grants
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/SegmentGrant" }
    post:
      tags: [segments]
      summary: Create a Pending segment grant
      description: >
        The source and destination must both exist in this network and must
        differ. A new grant always starts Pending; only Applied grants are
        included in the desired-config hash and plan visibility.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SegmentGrantCreate" }
      responses:
        "201":
          description: Created (status=pending)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SegmentGrant" }
        "400":
          description: Source and destination segments are the same.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Network, source segment, or destination segment is not in this network.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: An active grant already exists for this direction. Nothing is changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  /networks/{network_id}/segment-grants/{segment_grant_id}/apply:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { $ref: "#/components/parameters/SegmentGrantId" }
    post:
      tags: [segments]
      summary: Apply a Pending segment grant
      description: >
        Changes only Pending grants to Applied. This is a desired-state
        transition, not the network-wide revision apply endpoint; the new
        Applied entry changes the desired-config hash while Pending and
        Revoked entries do not.
      responses:
        "200":
          description: Applied
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SegmentGrant" }
        "404":
          description: Network or segment grant not found.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: Grant is already Applied or Revoked.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  /networks/{network_id}/segment-grants/{segment_grant_id}:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { $ref: "#/components/parameters/SegmentGrantId" }
    delete:
      tags: [segments]
      summary: Revoke a segment grant
      description: >
        Changes Pending or Applied grants to Revoked and records one
        revision. Revoked grants remain visible with `revoked_at` but are
        excluded from the desired-config hash; revoking twice is 409.
      responses:
        "204": { description: No content }
        "404":
          description: Network or segment grant not found.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: Grant is already Revoked.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  /networks/{network_id}/diagnostics:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    get:
      tags: [diagnostics]
      summary: Latest diagnostics snapshot (13 checks, §12.7)
      description: >
        Returns the most recent persisted diagnostics run for the network —
        the same JSON a POST produced, not a recompute. 404 when the network
        has never been diagnosed; an absent result is never rendered as a
        passing one.
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DiagnosticsReport" }
        "404": { $ref: "#/components/responses/NotFound" }
  /networks/{network_id}/host-forwards:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    get:
      tags: [routes]
      summary: List /32 host forwarding units
      description: >
        Each row is an atomic route-plus-alias unit. It forwards every IPv4
        protocol and port for one LAN host; this endpoint does not manage
        individual firewall port rules.
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/HostForward" }
    post:
      tags: [routes]
      summary: Forward all traffic for one LAN host
      description: >
        Creates a /32 alias-mode LAN route and its equal /32 alias in one
        desired-state revision. `dnat_snat` is the compatibility mode for LANs
        without a return route; `dnat_only` preserves the caller source address.
        Rejected creates mutate nothing and 409 names the conflicting overlay,
        route, or alias.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/HostForwardCreate" }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HostForward" }
        "400":
          description: Unknown NAT mode or invalid address.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Network or gateway device not found in this network.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: >
            Target or alias overlaps the overlay, an existing route, or an
            existing alias; or the gateway is inactive. Nothing is changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  /networks/{network_id}/host-forwards/{alias_id}:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { $ref: "#/components/parameters/AliasId" }
    delete:
      tags: [routes]
      summary: Delete a host forwarding unit
      description: >
        Removes the /32 alias and its bound route in the same ownership unit
        and records one revision.
      responses:
        "204": { description: No content }
        "404": { $ref: "#/components/responses/NotFound" }
    post:
      tags: [diagnostics]
      summary: Run diagnostics now and persist the snapshot
      description: >
        Computes the 13 checks, stores one snapshot row (diagnostics_runs) and
        returns the report. Check statuses use a closed vocabulary: pass /
        fail / warning / unavailable / not_applicable. unavailable is honest
        ignorance — the control plane cannot observe host-local facts
        (WireGuard interface, kernel routes, ip_forward, firewall, NAT rules),
        so those five checks carry an actionable command to run on the device
        instead of a green light. Registration (server_peer_configured) never
        proves the tunnel: handshake freshness (recent_handshake) is the only
        tunnel-level evidence (§12.4). The MTU check (mtu_planned) reports the
        planned tunnel_mtu from the server config: explicit value = pass,
        unset = warning (devices fall back to the WireGuard default 1420,
        which can blackhole large packets on small-MTU underlays, §7.5).
        Records a diagnostics.run audit event.
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DiagnosticsReport" }
        "404": { $ref: "#/components/responses/NotFound" }
  /system/status:
    get:
      security: []
      tags: [status]
      summary: Server status (implemented in apps/server spike)
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SystemStatus" }
  /networks/{network_id}/config-revisions:
    parameters: [ { $ref: "#/components/parameters/NetworkId" } ]
    get:
      tags: [status]
      summary: List config revisions
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/ConfigRevision" }
  /networks/{network_id}/config-revisions/{revision}:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { name: revision, in: path, required: true, schema: { type: integer, minimum: 1 } }
    get:
      tags: [status]
      summary: Config revision detail (apply_status)
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ConfigRevision" }
        "404": { $ref: "#/components/responses/NotFound" }
  /networks/{network_id}/config-revisions/{revision}/apply:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { name: revision, in: path, required: true, schema: { type: integer, minimum: 1 } }
    post:
      tags: [status]
      summary: Apply this revision to the actual network environment
      description: >
        Returns the revision view; apply_status is the verdict. The response is 200
        even when the apply failed — failures stay visible as failed + error_summary
        (§10.1/§10.3: an uncertain outcome is also failed, never faked success).
        Re-applying an already applied revision is idempotent and does not invoke the
        backend again; re-applying a failed revision is 409 — record a new revision
        instead (§10.4).
      responses:
        "200":
          description: OK (check apply_status in the body)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ConfigRevision" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
  /networks/{network_id}/config-revisions/{revision}/rollback:
    parameters:
      - { $ref: "#/components/parameters/NetworkId" }
      - { name: revision, in: path, required: true, schema: { type: integer, minimum: 1 } }
    post:
      tags: [status]
      summary: Roll back a failed revision (Meshlet-owned objects only, ADR-007)
      description: >
        Only failed (or an interrupted rollback_pending) revisions can be rolled
        back; applied revisions are undone by recording a new forward revision.
        Only the current (latest un-rolled-back) revision may be rolled back: a
        superseded failed revision is refused with 409 because undoing it would
        cross-touch objects the newer revision owns (§10.4). If the rollback
        cannot be confirmed the revision stays rollback_pending with a combined
        error_summary. Never wipes system routes (§10.3).
      responses:
        "200":
          description: OK (check apply_status in the body)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ConfigRevision" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
components:
  securitySchemes:
    sessionCookie:
      type: apiKey
      in: cookie
      name: meshlet_session
      description: >
        Console session cookie (HttpOnly, SameSite=Strict, Path=/api/v1).
        Mutating management requests must additionally send
        X-Requested-With: XMLHttpRequest (CSRF guard).
    agentToken:
      type: apiKey
      in: header
      name: Authorization
      description: >
        Bearer <agent_token> — the agent's control-plane credential issued at
        enrollment. Only returned once; the server stores the SHA-256 digest.
    apiToken:
      type: apiKey
      in: header
      name: Authorization
      description: >
        Bearer mlt_... — API token issued via POST /auth/tokens for external
        systems. Scopes: "read" (read endpoints only) or "write" (read+write).
        Revocable by its owner; the server stores only the SHA-256 digest and
        records throttled last_used_at for audit attribution. Valid only on the
        management API, never on /agent/heartbeat or /agent/device/desired.
        Mutating requests must still send X-Requested-With: XMLHttpRequest
        (same CSRF guard as sessions).
  parameters:
    NetworkId: { name: network_id, in: path, required: true, schema: { type: string } }
    DeviceId: { name: device_id, in: path, required: true, schema: { type: string } }
    RouteId: { name: route_id, in: path, required: true, schema: { type: string } }
    AliasId: { name: alias_id, in: path, required: true, schema: { type: string } }
    SegmentId: { name: segment_id, in: path, required: true, schema: { type: string } }
    SegmentGrantId: { name: segment_grant_id, in: path, required: true, schema: { type: string } }
  responses:
    Error:
      description: Error
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    Unauthorized:
      description: Unauthorized
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    Forbidden:
      description: Forbidden
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    NotFound:
      description: Not found
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    Conflict:
      description: Conflict (e.g. CIDR overlap)
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    ValidationError:
      description: Validation failed
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    ServiceUnavailable:
      description: Backup not configured (no [backup] dir)
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
  schemas:
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message]
          properties:
            code:
              type: string
              enum: [unauthorized, forbidden, not_found, conflict, validation_failed, too_many_requests, apply_failed, backup_not_configured, dataplane_not_configured, internal]
            message: { type: string }
            details: { type: object, additionalProperties: true }
    Session:
      type: object
      required: [user_id, email]
      properties:
        user_id: { type: string }
        email: { type: string, format: email }
    User:
      type: object
      properties:
        id: { type: string }
        email: { type: string, format: email }
    ApiTokenCreate:
      type: object
      required: [name, scopes]
      properties:
        name: { type: string, maxLength: 128, description: Human-readable label (e.g. cockpit, ci-pipeline) }
        scopes: { type: string, enum: [read, write], description: "write implies read" }
    ApiTokenCreated:
      type: object
      required: [id, token, name, scopes, created_at]
      properties:
        id: { type: string }
        token:
          type: string
          description: Raw token (mlt_ + 64 hex); returned exactly once, never stored in plaintext
        name: { type: string }
        scopes: { type: string, enum: [read, write] }
        created_at: { type: string, format: date-time }
    ApiToken:
      type: object
      description: Token view; carries no token material (digest-only storage)
      required: [id, name, scopes, created_at]
      properties:
        id: { type: string }
        name: { type: string }
        scopes: { type: string, enum: [read, write] }
        created_at: { type: string, format: date-time }
        last_used_at: { type: string, format: date-time, nullable: true, description: Throttled to 60s resolution }
        revoked_at: { type: string, format: date-time, nullable: true }
    AuditEvent:
      type: object
      description: >
        One sensitive-operation record. actor_id is null for events without a
        user actor (device enrollment via invite token, failed logins before
        authentication succeeds). detail is a JSON object serialized to text;
        by contract it never carries secret material.
      required: [id, created_at, action, target_type]
      properties:
        id: { type: integer }
        created_at: { type: string, format: date-time }
        actor_id: { type: string, nullable: true }
        action:
          type: string
          description: >
            Dotted verb: user.bootstrap / user.login / user.login_failed /
            user.logout / network.created / invite.created / invite.revoked /
            route.created / route.deleted / device.enrolled / device.revoked /
            api_token.created / api_token.revoked / revision.applied /
            revision.apply_failed / revision.rolled_back / revision.rollback_failed /
            system.backup / system.restore (§17.4)
        target_type: { type: string }
        target_id: { type: string, nullable: true }
        detail: { type: string, nullable: true, description: JSON-encoded structured metadata }
    AuditPage:
      type: object
      required: [total, events]
      properties:
        total: { type: integer }
        events:
          type: array
          items: { $ref: "#/components/schemas/AuditEvent" }
    Network:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        overlay_cidr: { type: string, examples: ["10.240.0.0/16"] }
        status: { type: string }
        created_at: { type: string, format: date-time }
        revision_id:
          type: integer
          description: Current desired config revision (ADR-009 — mutating responses carry revision_id + apply_status)
        apply_status: { $ref: "#/components/schemas/ConfigRevision/properties/apply_status" }
    NetworkCreate:
      type: object
      required: [name, overlay_cidr]
      properties:
        name: { type: string }
        overlay_cidr: { type: string, examples: ["10.240.0.0/16"] }
    NetworkList:
      type: object
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/Network" }
        total: { type: integer }
    Device:
      type: object
      properties:
        id: { type: string }
        network_id: { type: string }
        name: { type: string }
        virtual_ipv4: { type: string, format: ipv4 }
        public_key: { type: string, description: WireGuard public key registered on the server }
        fingerprint: { type: string, description: SHA-256 of the public key; the server never stores private key material (§11.2) }
        platform: { type: string, enum: [linux, windows] }
        status: { type: string, enum: [pending, active, revoked] }
        last_seen_at: { type: string, format: date-time, nullable: true }
        online_state:
          type: string
          enum: [online, tunnel_only, offline]
          description: >
            online = a fresh agent report; tunnel_only = only a fresh WireGuard
            handshake, which proves tunnel connectivity but not that the device
            works end to end (§12.4); offline = no fresh evidence.
        presence_source:
          type: string
          enum: [agent_report, handshake, enrollment, none]
          description: >
            The data source behind online_state (§12.2: never show a green "online"
            icon without saying which evidence produced it and when).
        revoked_at: { type: string, format: date-time, nullable: true }
    DeviceList:
      type: object
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/Device" }
        total: { type: integer }
    Invite:
      type: object
      required: [invite_id, token]
      properties:
        invite_id: { type: string }
        token: { type: string, description: 64 hex chars; only returned here, never stored plaintext (§11.3) }
        expires_at: { type: string, format: date-time }
    Enroll:
      type: object
      required: [invite_token, device_name, public_key, platform]
      additionalProperties: false
      properties:
        invite_token: { type: string }
        device_name: { type: string, minLength: 1 }
        public_key: { type: string, minLength: 1 }
        platform: { type: string, enum: [linux, windows] }
    EnrollResponse:
      type: object
      required: [device_id, network_id, virtual_ipv4, fingerprint, agent_token]
      properties:
        device_id: { type: string }
        network_id: { type: string }
        virtual_ipv4: { type: string, format: ipv4 }
        fingerprint: { type: string, description: SHA-256 of the public key }
        agent_token:
          type: string
          description: >
            64 hex chars; the agent's Bearer credential for /agent/heartbeat.
            Returned only here, only once — the server stores the SHA-256 digest.
        revision_id:
          type: integer
          description: Config revision produced by this enrollment (ADR-009)
        apply_status: { $ref: "#/components/schemas/ConfigRevision/properties/apply_status" }
    RegisterDevice:
      type: object
      required: [bootstrap_token, device_name, public_key, platform]
      additionalProperties: false
      properties:
        bootstrap_token: { type: string }
        device_name: { type: string, minLength: 1 }
        public_key: { type: string, minLength: 1 }
        platform: { type: string, enum: [linux, windows] }
    RegisterDeviceResponse:
      type: object
      required: [device_id, network_id, status, agent_token, requested_at]
      properties:
        device_id: { type: string, description: "dev-reg-N; kept as the device id after approval" }
        network_id: { type: string }
        status: { type: string, enum: [pending] }
        agent_token:
          type: string
          description: >
            64 hex chars; the agent's Bearer credential. Returned only here, only
            once (§11.3). Stays valid through approval — the device id does not
            change, so the credential is not rotated.
        requested_at: { type: string, format: date-time }
    DeviceRegistration:
      type: object
      required: [id, network_id, name, platform, public_key, requested_at]
      properties:
        id: { type: string }
        network_id: { type: string }
        name: { type: string }
        platform: { type: string, enum: [linux, windows] }
        public_key: { type: string }
        requested_at: { type: string, format: date-time }
        last_report_at: { type: [string, "null"], format: date-time, description: Pending devices keep reporting; the evidence lands here until approval }
        dataplane_evidence: { $ref: "#/components/schemas/DataplaneEvidence" }
    DeviceRegistrationList:
      type: array
      items: { $ref: "#/components/schemas/DeviceRegistration" }
    ApproveRegistration:
      type: object
      required: [device_id, network_id, virtual_ipv4, fingerprint, revision_id, apply_status, approved_at]
      properties:
        device_id: { type: string }
        network_id: { type: string }
        virtual_ipv4: { type: string, format: ipv4, description: Allocated at approval time (ADR-004) }
        fingerprint: { type: string, description: SHA-256 of the public key }
        revision_id: { type: integer, description: Config revision that brings the device into the desired config (ADR-009) }
        apply_status: { $ref: "#/components/schemas/ConfigRevision/properties/apply_status" }
        approved_at: { type: string, format: date-time }
    BootstrapTokenCreate:
      type: object
      required: []
      properties:
        max_uses: { type: integer, minimum: 1, description: Omit for unlimited (bootstrap tokens are long-lived entry credentials, not single-use invites) }
    BootstrapTokenCreated:
      type: object
      required: [token_id, token]
      properties:
        token_id: { type: string, description: "bt-N; id sequence shared with device registrations, monotonic in mesh_meta" }
        token: { type: string, description: 64 hex chars; only returned here, never stored plaintext (§11.3) }
        max_uses: { type: [integer, "null"] }
    BootstrapToken:
      type: object
      required: [id, network_id, used_count, created_at]
      properties:
        id: { type: string }
        network_id: { type: string }
        max_uses: { type: [integer, "null"] }
        used_count: { type: integer }
        created_at: { type: string, format: date-time }
        revoked_at: { type: [string, "null"], format: date-time }
    BootstrapTokenList:
      type: array
      items: { $ref: "#/components/schemas/BootstrapToken" }
    DataplaneEvidence:
      type: [object, "null"]
      description: Device-side dataplane readings (§7.5); null fields = not read.
      properties:
        tunnel_mtu: { type: [integer, "null"] }
        nat_rules_present: { type: [boolean, "null"] }
        nat_snat_rules_present: { type: [boolean, "null"] }
        mtu_probe_payload: { type: [integer, "null"] }
    Heartbeat:
      type: object
      additionalProperties: false
      properties:
        last_handshake_at:
          type: string
          format: date-time
          description: Latest WireGuard handshake as read locally via `wg show`.
    HeartbeatResponse:
      type: object
      required: [online_state, presence_source]
      properties:
        online_state: { type: string, enum: [online, tunnel_only, offline, pending], description: "pending = registration awaiting approval: no tunnel, agent keeps backing off" }
        presence_source: { type: string, enum: [agent_report, handshake, enrollment, none, registration], description: "registration = the pending registration's own heartbeat evidence" }
        last_seen_at: { type: string, format: date-time }
    PeerConfig:
      type: object
      required: [public_key, allowed_ips]
      properties:
        public_key: { type: string, description: Peer public key (hub key on devices) }
        allowed_ips:
          type: array
          items: { type: string }
          description: CIDRs routed to this peer; on a device = overlay + other devices' published LAN/alias prefixes (never its own, §7.2)
        endpoint: { type: string, nullable: true, description: "host:port, or null when the agent uses its local [dataplane] hub_endpoint" }
        persistent_keepalive_secs: { type: integer, nullable: true }
    TunnelConfig:
      type: object
      required: [name, address, address_prefix, peers]
      properties:
        name: { type: string, description: Managed WireGuard interface }
        address: { type: string, description: This device's overlay address (a.b.c.d) }
        address_prefix: { type: integer, description: Overlay prefix length }
        listen_port: { type: integer, nullable: true, description: Always null on devices }
        peers:
          type: array
          items: { $ref: "#/components/schemas/PeerConfig" }
        mtu: { type: integer, nullable: true }
        private_key:
          type: string
          nullable: true
          description: Always null — the server never carries a private key (ADR-010); the agent injects its own key locally.
    RouteConfig:
      type: object
      required: [destination, interface]
      properties:
        destination: { type: string, description: Destination CIDR }
        interface: { type: string }
        gateway:
          type: string
          nullable: true
          description: Next hop (a gateway device's overlay address), or null to route straight into the tunnel
    NatRule:
      type: object
      required: [chain, match_dest, action, owner]
      properties:
        source_cidr: { type: [string, "null"], description: Authorized source prefix }
        incoming_interface: { type: [string, "null"], description: Incoming managed interface for PREROUTING }
        chain: { type: string, enum: [prerouting, postrouting] }
        match_dest: { type: string, description: Destination CIDR the rule matches }
        action:
          description: >
            `{"net_map": {"to": "<cidr>"}}` for 1:1 equal-length prefix rewrite
            (NETMAP), or `"snat_to_gateway_lan"` for controlled SNAT whose source
            the gateway resolves locally from its interfaces.
          oneOf:
            - type: object
              required: [net_map]
              properties:
                net_map:
                  type: object
                  required: [to]
                  properties:
                    to: { type: string }
            - type: string
              enum: [snat_to_gateway_lan]
        owner:
          type: string
          description: Ownership comment (`meshlet alias {id}`) used to remove exactly this unit's rules (§12.6)
    DevicePlan:
      type: object
      required: [tunnel, routes, nat_rules, desired_config_hash]
      properties:
        desired_revision: { type: integer, description: Current hub-applied revision }
        hub_port: { type: [integer, "null"], description: Network-specific hub UDP port }
        hub_address: { type: [string, "null"], description: Hub overlay address for diagnostics }
        tunnel: { $ref: "#/components/schemas/TunnelConfig" }
        routes:
          type: array
          items: { $ref: "#/components/schemas/RouteConfig" }
        nat_rules:
          type: array
          items: { $ref: "#/components/schemas/NatRule" }
        desired_config_hash:
          type: string
          description: >
            SHA-256 of the serialized device plan with this hash field empty.
            Includes revision, MTU, hub public key and resources. This differs
            from the network revision ledger hash; receipts echo this exact hash.
    LanRoute:
      type: object
      required: [id, network_id, gateway_device_id, destination_cidr, route_mode, return_path_mode, status, revision_id, apply_status]
      properties:
        id: { type: string }
        network_id: { type: string }
        gateway_device_id: { type: string }
        destination_cidr: { type: string }
        route_mode: { type: string, enum: [direct, alias] }
        return_path_mode: { type: string, enum: [dual_route, controlled_snat] }
        status: { type: string, enum: [pending, applied, failed], description: The route's own desired-state status }
        revision_id: { type: integer, description: Config revision recorded by this change (ADR-009) }
        apply_status: { $ref: "#/components/schemas/ConfigRevision/properties/apply_status" }
    LanRouteCreate:
      type: object
      required: [gateway_device_id, destination_cidr, return_path_mode]
      properties:
        gateway_device_id: { type: string }
        destination_cidr: { type: string }
        route_mode: { type: string, enum: [direct, alias], default: direct }
        return_path_mode: { type: string, enum: [dual_route, controlled_snat] }
    AliasMapping:
      type: object
      required: [id, network_id, lan_route_id, alias_cidr, target_cidr, translation_mode, status, revision_id, apply_status]
      properties:
        id: { type: string }
        network_id: { type: string }
        lan_route_id: { type: string, description: The bound alias-mode route (one ownership unit, §12.6) }
        alias_cidr: { type: string }
        target_cidr: { type: string, description: Real LAN prefix, derived server-side from the bound route — never client-set }
        translation_mode: { type: string, enum: [dnat_only, dnat_snat] }
        status: { type: string, enum: [pending, applied, failed], description: The mapping's own desired-state status }
        revision_id: { type: integer, description: Config revision recorded by this change (ADR-009) }
        apply_status: { $ref: "#/components/schemas/ConfigRevision/properties/apply_status" }
    AliasCreate:
      type: object
      required: [lan_route_id, alias_cidr]
      properties:
        lan_route_id: { type: string, description: An alias-mode route of this network; one mapping per route }
        alias_cidr: { type: string, description: Must have same prefix length as target route CIDR }
        translation_mode: { type: string, enum: [dnat_only, dnat_snat], default: dnat_snat }
    Segment:
      type: object
      required: [id, network_id, name, cidr, status, created_at, revision_id]
      properties:
        id: { type: string }
        network_id: { type: string }
        name: { type: string }
        cidr: { type: string }
        status: { type: string, enum: [active, quarantined] }
        created_at: { type: string, format: date-time }
        revision_id: { type: integer }
    SegmentCreate:
      type: object
      required: [name, cidr]
      properties:
        name: { type: string, minLength: 1 }
        cidr: { type: string }
    SegmentGrant:
      type: object
      required: [id, network_id, source_segment_id, destination_segment_id, status, created_at, revoked_at, revision_id, apply_status]
      properties:
        id: { type: string }
        network_id: { type: string }
        source_segment_id: { type: string }
        destination_segment_id: { type: string }
        status: { type: string, enum: [pending, applied, revoked] }
        created_at: { type: string, format: date-time }
        revoked_at:
          type: [string, "null"]
          format: date-time
        revision_id: { type: integer }
        apply_status: { $ref: "#/components/schemas/ConfigRevision/properties/apply_status" }
    SegmentGrantCreate:
      type: object
      required: [source_segment_id, destination_segment_id]
      properties:
        source_segment_id: { type: string }
        destination_segment_id: { type: string }
    HostForward:
      type: object
      required: [id, network_id, gateway_device_id, target_ipv4, alias_ipv4, translation_mode, status, revision_id, apply_status]
      properties:
        id: { type: string, description: Alias id of the atomic host-forward unit }
        network_id: { type: string }
        gateway_device_id: { type: string }
        target_ipv4: { type: string, format: ipv4, description: Real LAN host address }
        alias_ipv4: { type: string, format: ipv4, description: Virtual host address visible in the overlay }
        translation_mode: { type: string, enum: [dnat_only, dnat_snat] }
        status: { type: string, enum: [pending, applied, failed] }
        revision_id: { type: integer, description: Config revision recorded by this change (ADR-009) }
        apply_status: { $ref: "#/components/schemas/ConfigRevision/properties/apply_status" }
    HostForwardCreate:
      type: object
      required: [gateway_device_id, target_ipv4, alias_ipv4]
      properties:
        gateway_device_id: { type: string }
        target_ipv4: { type: string, format: ipv4 }
        alias_ipv4: { type: string, format: ipv4 }
        translation_mode: { type: string, enum: [dnat_only, dnat_snat], default: dnat_snat }
    DiagnosticsReport:
      type: object
      required: [network_id, checked_at, checks]
      properties:
        network_id: { type: string }
        checked_at: { type: string, format: date-time, description: When this run was computed }
        checks:
          type: array
          minItems: 13
          maxItems: 13
          items: { $ref: "#/components/schemas/DiagnosticCheck" }
    DiagnosticCheck:
      type: object
      required: [id, name, layer, status, detail, suggestion]
      properties:
        id:
          type: string
          enum:
            - api_reachable
            - wg_interface_exists
            - server_peer_configured
            - recent_handshake
            - overlay_route_present
            - ip_forwarding_enabled
            - firewall_allows_forwarding
            - lan_gateway_agent_online
            - lan_route_published
            - alias_prefix_conflict
            - nat_rules_effective
            - config_revision_consistent
            - mtu_planned
          description: Stable check id (§12.7 numbering, order fixed by the server; mtu_planned appended last, §7.5)
        name: { type: string, description: Human-readable check name }
        layer:
          type: string
          enum: [control_plane, tunnel, routing, forwarding, alias]
          description: Fault layer this check diagnoses
        status:
          type: string
          enum: [pass, fail, warning, unavailable, not_applicable]
          description: >
            unavailable means the control plane cannot observe this host-local
            fact — it is not a pass. not_applicable means the network has no
            object for this check (distinct from pass).
        detail: { type: string, description: Observed facts, including why a value is unavailable }
        suggestion:
          type: string
          description: Actionable next step (command to run on the device); empty for passing checks
    ConfigRevision:
      type: object
      properties:
        network_id: { type: string }
        revision: { type: integer }
        desired_config_hash: { type: string }
        apply_status:
          type: string
          enum: [pending, applying, applied, failed, rollback_pending, rolled_back]
        created_at: { type: string, format: date-time }
        applied_at: { type: string, format: date-time, nullable: true }
        error_summary: { type: string, nullable: true }
        convergence:
          type: object
          description: Current revision only; hub execution is separate from device receipts and business health
          properties:
            device_apply_status: { type: string, enum: [pending, applied, failed, not_configured] }
            pending_device_ids: { type: array, items: { type: string } }
            device_errors: { type: object, additionalProperties: { type: string } }
            hub_recovery_error: { type: [string, "null"] }
            business_health: { type: string, enum: [not_probed] }
    RevisionRef:
      type: object
      required: [revision_id, apply_status]
      properties:
        revision_id: { type: integer, description: Monotonic per-network revision number (ADR-009) }
        apply_status: { $ref: "#/components/schemas/ConfigRevision/properties/apply_status" }
    SystemStatus:
      type: object
      required: [status, version]
      properties:
        status: { type: string, enum: [ok, degraded] }
        version: { type: string }
    BackupResponse:
      type: object
      description: Backup content summary read back from the backup file itself (§17.4)
      required: [path, created_at, bytes, networks, devices, routes, invites, revisions]
      properties:
        path: { type: string, description: "<dir>/meshlet-backup-<UTC timestamp>.db (millisecond precision)" }
        created_at: { type: string, format: date-time }
        bytes: { type: integer }
        networks: { type: integer }
        devices: { type: integer }
        routes: { type: integer }
        invites: { type: integer }
        revisions: { type: integer }
