openapi: 3.0.3
info:
  title: Penny Sign API
  version: 1.0.0
  description: |
    E-signature API for Penny CRM. Create envelopes containing PDF documents, place text and signature
    fields for each signer, send them by email (or embed signing in the CRM), receive webhooks, and download
    the completed PDF with its Certificate of Completion and hash-chained audit trail.

    Coordinates are PDF points (1/72 inch) measured from the **top-left** corner of the page.
servers:
  - url: https://sign.example.com/api/v1
    description: Replace with your Penny Sign BASE_URL + /api/v1
security:
  - bearerAuth: []
tags:
  - name: Envelopes
  - name: Signing
  - name: Audit & Documents
  - name: Account
paths:
  /envelopes:
    post:
      tags: [Envelopes]
      summary: Create (and optionally send) an envelope
      description: |
        Send as `application/json` with base64 documents, or as `multipart/form-data` with one or more
        `documents` file parts plus a `payload` part containing the same JSON (without `documents`).
        Set `"status": "sent"` to send immediately; otherwise the envelope is a draft (`created`).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/EnvelopeCreate' }
          multipart/form-data:
            schema:
              type: object
              properties:
                payload: { type: string, description: JSON string of EnvelopeCreate (documents omitted) }
                documents: { type: array, items: { type: string, format: binary } }
      responses:
        '201': { description: Created, content: { application/json: { schema: { $ref: '#/components/schemas/Envelope' } } } }
        '400': { $ref: '#/components/responses/Error' }
        '401': { $ref: '#/components/responses/Error' }
    get:
      tags: [Envelopes]
      summary: List envelopes
      parameters:
        - { name: status, in: query, schema: { $ref: '#/components/schemas/EnvelopeStatus' } }
        - { name: external_ref, in: query, schema: { type: string } }
        - { name: updated_since, in: query, schema: { type: string, format: date-time } }
        - { name: limit, in: query, schema: { type: integer, default: 25, maximum: 100 } }
        - { name: offset, in: query, schema: { type: integer, default: 0 } }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/Envelope' } }
                  total: { type: integer }
                  limit: { type: integer }
                  offset: { type: integer }
  /envelopes/{id}:
    parameters: [{ $ref: '#/components/parameters/EnvelopeId' }]
    get:
      tags: [Envelopes]
      summary: Get an envelope (status, recipients, field values)
      responses:
        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/Envelope' } } } }
        '404': { $ref: '#/components/responses/Error' }
    delete:
      tags: [Envelopes]
      summary: Delete a draft envelope
      responses:
        '204': { description: Deleted }
        '409': { $ref: '#/components/responses/Error' }
  /envelopes/{id}/send:
    parameters: [{ $ref: '#/components/parameters/EnvelopeId' }]
    post:
      tags: [Envelopes]
      summary: Send a draft envelope
      description: Stamps the Envelope ID on every page, hashes the documents and emails the first routing-order signers.
      responses:
        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/Envelope' } } } }
        '409': { $ref: '#/components/responses/Error' }
  /envelopes/{id}/void:
    parameters: [{ $ref: '#/components/parameters/EnvelopeId' }]
    post:
      tags: [Envelopes]
      summary: Void an envelope that has not completed
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [reason], properties: { reason: { type: string } } } } }
      responses:
        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/Envelope' } } } }
  /envelopes/{id}/remind:
    parameters: [{ $ref: '#/components/parameters/EnvelopeId' }]
    post:
      tags: [Envelopes]
      summary: Re-send the signing email to signers who have not finished
      responses:
        '200': { description: OK, content: { application/json: { schema: { type: object, properties: { reminded: { type: array, items: { type: string } } } } } } }
  /envelopes/{id}/recipients/{recipientId}/signing-url:
    parameters:
      - { $ref: '#/components/parameters/EnvelopeId' }
      - { name: recipientId, in: path, required: true, schema: { type: string }, description: Recipient id or the client id you supplied }
    post:
      tags: [Signing]
      summary: Create an embedded signing URL
      description: |
        Returns a short-lived URL that opens the signing experience directly (e.g. in a new tab or iframe
        inside Penny CRM). When the signer finishes or declines they are redirected to `return_url` with
        `?event=signing_complete|decline&envelope_id=...`.
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                return_url: { type: string, format: uri }
                ttl_minutes: { type: integer, default: 15, minimum: 1, maximum: 1440 }
      responses:
        '201':
          description: Created
          content: { application/json: { schema: { type: object, properties: { url: { type: string }, expires_in_minutes: { type: integer } } } } }
  /envelopes/{id}/audit:
    parameters: [{ $ref: '#/components/parameters/EnvelopeId' }]
    get:
      tags: [Audit & Documents]
      summary: Audit trail events with hash-chain verification
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  envelope_id: { type: string }
                  integrity: { type: object, properties: { valid: { type: boolean }, events: { type: integer }, head_hash: { type: string } } }
                  events: { type: array, items: { $ref: '#/components/schemas/AuditEvent' } }
  /envelopes/{id}/certificate:
    parameters: [{ $ref: '#/components/parameters/EnvelopeId' }]
    get:
      tags: [Audit & Documents]
      summary: Certificate of Completion (PDF), generated live for in-progress envelopes
      responses:
        '200': { description: PDF, content: { application/pdf: { schema: { type: string, format: binary } } } }
  /envelopes/{id}/documents/combined:
    parameters: [{ $ref: '#/components/parameters/EnvelopeId' }]
    get:
      tags: [Audit & Documents]
      summary: Completed documents + Certificate of Completion as one PDF
      responses:
        '200': { description: PDF, content: { application/pdf: { schema: { type: string, format: binary } } } }
        '409': { $ref: '#/components/responses/Error' }
  /envelopes/{id}/documents/{documentId}:
    parameters:
      - { $ref: '#/components/parameters/EnvelopeId' }
      - { name: documentId, in: path, required: true, schema: { type: string } }
    get:
      tags: [Audit & Documents]
      summary: A single document as sent (Envelope ID stamped), or the original for drafts
      responses:
        '200': { description: PDF, content: { application/pdf: { schema: { type: string, format: binary } } } }
  /webhook-deliveries:
    get:
      tags: [Account]
      summary: Recent webhook delivery attempts (for debugging)
      responses: { '200': { description: OK } }
  /account:
    get:
      tags: [Account]
      summary: Get account settings
      responses: { '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/Account' } } } } }
    patch:
      tags: [Account]
      summary: Update account settings (company details, ERSD, time zone, webhook URL, brand colour)
      requestBody:
        content: { application/json: { schema: { $ref: '#/components/schemas/AccountUpdate' } } }
      responses: { '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/Account' } } } } }
  /account/email-test:
    post:
      tags: [Account]
      summary: Verify the saved SMTP login and send a test email
      requestBody:
        content: { application/json: { schema: { type: object, properties: { to: { type: string } } } } }
      responses:
        '200': { description: Sent }
        '400': { $ref: '#/components/responses/Error' }
  /account/webhook-secret:
    post:
      tags: [Account]
      summary: Rotate the webhook signing secret
      responses:
        '200': { description: OK, content: { application/json: { schema: { type: object, properties: { webhook_secret: { type: string } } } } } }
components:
  securitySchemes:
    bearerAuth: { type: http, scheme: bearer, description: 'API key, e.g. `Authorization: Bearer psk_live_...`' }
  parameters:
    EnvelopeId: { name: id, in: path, required: true, schema: { type: string }, description: Envelope ID (uppercase UUID) }
  responses:
    Error:
      description: Error
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: object
                properties:
                  code: { type: string, example: validation_error }
                  message: { type: string }
                  details: {}
  schemas:
    EnvelopeStatus: { type: string, enum: [created, sent, delivered, completed, declined, voided] }
    EnvelopeCreate:
      type: object
      required: [subject, recipients, fields]
      properties:
        subject: { type: string, maxLength: 200, example: 'Privacy Authority.pdf' }
        message: { type: string, maxLength: 5000, description: Shown in the email and on the signing welcome screen }
        status: { type: string, enum: [created, sent], default: created }
        sender:
          type: object
          description: The Envelope Originator shown on the certificate (defaults to the account)
          properties:
            name: { type: string }
            email: { type: string }
            address: { type: string, description: 'Lines separated by newline or comma' }
            ip: { type: string, description: 'IP of the CRM user who sent it (recorded on the certificate)' }
        external_ref: { type: string, description: Your Penny CRM record id; echoed in webhooks }
        metadata: { type: object, additionalProperties: true }
        webhook_url: { type: string, description: Overrides the account webhook URL for this envelope }
        timezone: { type: string, example: Pacific/Auckland }
        expires_in_days: { type: integer }
        documents:
          type: array
          items:
            type: object
            required: [file_base64]
            properties:
              name: { type: string }
              file_base64: { type: string, format: byte }
        recipients:
          type: array
          items: { $ref: '#/components/schemas/RecipientCreate' }
        fields:
          type: array
          items: { $ref: '#/components/schemas/FieldCreate' }
    RecipientCreate:
      type: object
      required: [name, email]
      properties:
        id: { type: string, description: 'Your id for this recipient, referenced by fields[].recipient_id (default "1", "2"...)' }
        name: { type: string }
        email: { type: string }
        role: { type: string, enum: [signer, cc], default: signer }
        routing_order: { type: integer, default: 1, description: Lower numbers sign first; equal numbers sign in parallel }
        access_code: { type: string, description: 'Optional code the signer must enter (share it separately, e.g. by SMS)' }
    FieldCreate:
      type: object
      required: [type]
      properties:
        id: { type: string, description: Your id; returned in recipient.completed webhook field_values }
        type: { type: string, enum: [signature, initials, text, date, date_signed, full_name, email_address, checkbox] }
        recipient_id: { type: string, default: '1' }
        document_index: { type: integer, default: 0 }
        page: { type: integer, default: 1 }
        x: { type: number, description: Points from left edge }
        y: { type: number, description: Points from top edge }
        width: { type: number }
        height: { type: number }
        anchor:
          type: object
          description: Place the field at every occurrence of this text instead of x/y. The text is hidden on the sent document.
          properties:
            text: { type: string, example: '/sig1/' }
            x_offset: { type: number, default: 0 }
            y_offset: { type: number, default: 0 }
            ignore_if_missing: { type: boolean, default: false }
            hide: { type: boolean, default: true }
        required: { type: boolean, default: true, description: 'Checkboxes default to optional' }
        label: { type: string, description: Shown to the signer as the field name / tooltip }
        placeholder: { type: string }
        value: { type: string, description: Pre-filled value the signer can edit (or fixed if read_only) }
        read_only: { type: boolean, default: false }
        font_size: { type: number, default: 11 }
        max_length: { type: integer }
        validation: { type: string, enum: [email, number, phone, date] }
        tab_order: { type: integer }
    Envelope:
      type: object
      properties:
        id: { type: string }
        status: { $ref: '#/components/schemas/EnvelopeStatus' }
        subject: { type: string }
        message: { type: string }
        external_ref: { type: string }
        sender: { type: object }
        created_at: { type: string, format: date-time }
        sent_at: { type: string, format: date-time }
        delivered_at: { type: string, format: date-time, description: Certified Delivered - all signers have viewed }
        signing_complete_at: { type: string, format: date-time }
        completed_at: { type: string, format: date-time }
        documents: { type: array, items: { type: object } }
        recipients: { type: array, items: { $ref: '#/components/schemas/Recipient' } }
        fields: { type: array, items: { type: object } }
        final_sha256: { type: string }
        links: { type: object }
    Recipient:
      type: object
      properties:
        id: { type: string }
        client_id: { type: string }
        role: { type: string }
        name: { type: string }
        email: { type: string }
        routing_order: { type: integer }
        status: { type: string, enum: [created, sent, delivered, completed, declined] }
        sent_at: { type: string }
        viewed_at: { type: string }
        signed_at: { type: string }
        declined_at: { type: string }
        decline_reason: { type: string }
        ersd_accepted_at: { type: string }
        signed_from_ip: { type: string }
        signed_on_mobile: { type: boolean }
        signature_adoption: { type: string, enum: ['Drawn on Device', 'Pre-selected Style', 'Uploaded Signature'] }
    AuditEvent:
      type: object
      properties:
        seq: { type: integer }
        at: { type: string, format: date-time }
        type: { type: string }
        recipient_id: { type: string }
        actor_name: { type: string }
        actor_email: { type: string }
        ip: { type: string }
        user_agent: { type: string }
        details: { type: object }
        prev_hash: { type: string }
        hash: { type: string }
    Account:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        address: { type: string }
        email: { type: string }
        timezone: { type: string }
        date_format: { type: string }
        ersd_contact_email: { type: string }
        ersd_created_at: { type: string }
        paper_copy_fee: { type: string }
        webhook_url: { type: string }
        brand_color: { type: string }
    AccountUpdate:
      type: object
      properties:
        name: { type: string }
        address: { type: string }
        email: { type: string }
        timezone: { type: string }
        date_format: { type: string, enum: ['DD/MM/YYYY', 'MM/DD/YYYY', 'YYYY-MM-DD'] }
        ersd_contact_email: { type: string }
        ersd_text: { type: string, description: 'Custom disclosure. Placeholders {{company}} {{email}} {{fee}} {{product}}; lines starting "## " are headings' }
        paper_copy_fee: { type: string }
        webhook_url: { type: string }
        brand_color: { type: string, example: '#1f4fd6' }
        smtp:
          nullable: true
          description: 'Send email from your own mailbox. null reverts to the server default.'
          type: object
          properties:
            provider: { type: string, enum: [google], description: 'Preset for smtp.gmail.com:465 (Google Workspace / Gmail)' }
            host: { type: string }
            port: { type: integer }
            secure: { type: boolean }
            user: { type: string, example: sign@yourfirm.co.nz }
            pass: { type: string, description: 'App password; write-only, encrypted at rest' }
            from: { type: string, example: 'Your Firm <sign@yourfirm.co.nz>' }
