openapi: 3.1.0
info:
  title: peepless
  version: 0.5.0
  summary: The HTTP side of peepless, privacy-first daily counts.
  description: |
    The beacon endpoint that `createHandler` from `peepless/server` serves, and that the
    `peepless` browser client posts to; and the stats endpoint that `createStatsHandler`
    serves, for reading the numbers back.

    This file is the contract for everything that crosses the network. A test in
    `npm run check` (`src/openapi.test.ts`) sends every request example below to
    the handlers and checks the answer, so it can't drift from the code.

    From 1.0, fields are only ever added: a server ignores fields it doesn't know, and a
    client never requires a newer server.

    The counter names each beacon becomes are a separate contract, in `docs/counters.md`.
  license:
    name: MIT
    identifier: MIT
servers:
  - url: /
    description: The app's own origin. `/api/peepless` is the client's default `endpoint`; any path works.
tags:
  - name: beacon
    description: Counting, from the browser.
  - name: stats
    description: Reading the numbers back, from a server.
paths:
  /api/peepless:
    description: |
      Any method other than POST and OPTIONS answers 405 with `Allow: POST, OPTIONS`.
    post:
      tags: [beacon]
      operationId: sendBeacon
      summary: Count one page view, engaged visit or event.
      description: |
        Sent by the client with `navigator.sendBeacon` as a plain-text string, so the browser
        needs no CORS preflight; the body is JSON either way, and the `Content-Type` is not checked.

        The answer carries nothing a client needs: a bot, a beacon over the rate limit and a
        counted beacon all get 204, so a bot learns nothing from the reply. Errors have a small
        JSON body for whoever is debugging with curl.

        Nothing in the request is stored. The fields become counter names (`docs/counters.md`)
        and are forgotten; the User-Agent is read only to drop bots, the address only keys
        this minute's in-memory rate limit, and the country comes from the host's geo header.
      x-example-config:
        description: The handler options every example below is sent to.
        projects:
          my-app:
            origin: https://example.com
            events: [signed_up, exported]
            routes: [/, /blog/*, /app/*]
            campaigns: [newsletter, launch]
      parameters:
        - name: Origin
          in: header
          required: true
          description: |
            The page's origin, set by the browser. It must be one of the project's `origin`s,
            or the same with `www.` added or removed. Anything else answers 403.
          schema:
            type: string
            examples: [https://example.com]
      requestBody:
        required: true
        content:
          text/plain:
            schema:
              $ref: '#/components/schemas/Beacon'
            examples:
              arrival:
                summary: The first page of a visit, from a search engine
                value:
                  project: my-app
                  event: pageview
                  visit: true
                  ref: www.google.com
                  route: /blog/*
                x-headers:
                  x-vercel-ip-country: DE
                x-expect:
                  status: 204
                  counters: [pageview, visit, 'from:search', 'country:de', 'page:/blog/*']
              direct:
                summary: A visit with no referrer, on a host that sends no country
                value: { project: my-app, event: pageview, visit: true, ref: '' }
                x-expect:
                  status: 204
                  counters: [pageview, visit, 'from:direct', 'country:xx']
              next-page:
                summary: A later page of the same visit, on a page type the server doesn't list
                value: { project: my-app, event: pageview, route: /_other }
                x-expect:
                  status: 204
                  counters: [pageview, 'page:other']
              campaign:
                summary: A visit from a link tagged ?ref=newsletter, a tag the project lists
                value: { project: my-app, event: pageview, visit: true, ref: '', via: newsletter }
                x-expect:
                  status: 204
                  counters: [pageview, visit, 'from:direct', 'country:xx', 'via:newsletter']
              campaign-other:
                summary: A tag the server doesn't list counts as other, and is never stored
                value: { project: my-app, event: pageview, visit: true, ref: '', via: spring-sale }
                x-expect:
                  status: 204
                  counters: [pageview, visit, 'from:direct', 'country:xx', 'via:other']
              human:
                summary: The visit's first real input, or 10 seconds on screen
                value: { project: my-app, event: human }
                x-expect:
                  status: 204
                  counters: [human]
              event:
                summary: One of the project's own events
                value: { project: my-app, event: exported }
                x-expect:
                  status: 204
                  counters: [exported]
              unknown-fields:
                summary: Fields the server doesn't know are ignored
                value: { project: my-app, event: human, added_later: 1 }
                x-expect:
                  status: 204
                  counters: [human]
              bot:
                summary: A crawler, dropped without saying so
                value: { project: my-app, event: pageview }
                x-headers:
                  user-agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
                x-expect:
                  status: 204
                  counters: []
              not-listed:
                summary: An event the project doesn't list
                value: { project: my-app, event: deleted }
                x-expect:
                  status: 400
                  counters: []
              not-json:
                summary: A body that isn't a JSON object
                value: hello
                x-expect:
                  status: 400
                  counters: []
              wrong-origin:
                summary: A beacon from another site
                value: { project: my-app, event: human }
                x-headers:
                  origin: https://elsewhere.test
                x-expect:
                  status: 403
                  counters: []
              no-project:
                summary: A project the server doesn't have
                value: { project: other-app, event: human }
                x-expect:
                  status: 404
                  counters: []
              too-large:
                summary: A body over 1 KB, refused by its Content-Length before it is read
                value: { project: my-app, event: human }
                x-headers:
                  content-length: '5000'
                x-expect:
                  status: 413
                  counters: []
              store-down:
                summary: The database refused the write
                value: { project: my-app, event: human }
                x-store: failing
                x-expect:
                  status: 500
                  counters: []
          application/json:
            schema:
              $ref: '#/components/schemas/Beacon'
            description: Accepted too, for a client using fetch. It triggers a CORS preflight, which OPTIONS answers.
      responses:
        '204':
          description: Counted, or dropped without saying so (a bot's User-Agent, or over the rate limit).
          headers:
            Access-Control-Allow-Origin:
              $ref: '#/components/headers/AllowOrigin'
        '400':
          description: The body isn't a JSON object, or its event isn't one this project counts.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: The `Origin` isn't one of the project's origins.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: The server has no project by that name.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '413':
          description: The body is over 1 KB (by `Content-Length`, or once read).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: The store failed. The details go to the server's log, never into the answer.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    options:
      tags: [beacon]
      operationId: preflight
      summary: CORS preflight, for a fetch-based client. sendBeacon never sends one.
      responses:
        '204':
          description: Allowed.
          headers:
            Access-Control-Allow-Origin:
              $ref: '#/components/headers/AllowOrigin'
            Access-Control-Allow-Methods:
              schema: { type: string, const: POST }
  /api/peepless/stats:
    description: |
      Any method other than GET answers 405 with `Allow: GET`. Serve this on its own path, never
      the beacon's. It has no CORS headers: it is for a server (yours, a stats page's, a dashboard's),
      and its token never goes to a browser.
    get:
      tags: [stats]
      operationId: getStats
      summary: A project's numbers for a range of UTC days.
      description: |
        Reads the project's daily totals through the store's `read` and answers them as a
        `Summary`, the same object `summarize` returns, with the project and range added.

        A wrong token and a missing one get the same 401, checked before anything else, so a
        caller without the token learns nothing about which projects exist.
      security:
        - statsToken: []
      parameters:
        - name: project
          in: query
          required: true
          schema: { type: string, pattern: '^[a-z0-9][a-z0-9-]{0,63}$' }
          example: my-app
        - name: since
          in: query
          description: The first UTC day, inclusive. Default 29 days before `until`.
          schema: { type: string, format: date }
          example: '2026-12-01'
        - name: until
          in: query
          description: The last UTC day, inclusive. Default today (UTC). At most 366 days after `since`.
          schema: { type: string, format: date }
          example: '2026-12-03'
      x-example-config:
        description: The handler options and stored counts every example below is replayed against.
        token: an-example-token-of-some-length
        rows:
          my-app:
            - { day: '2026-12-01', counter: pageview, count: 10 }
            - { day: '2026-12-01', counter: visit, count: 4 }
            - { day: '2026-12-01', counter: human, count: 3 }
            - { day: '2026-12-01', counter: 'from:search', count: 3 }
            - { day: '2026-12-01', counter: 'from:direct', count: 1 }
            - { day: '2026-12-01', counter: 'country:de', count: 3 }
            - { day: '2026-12-01', counter: 'country:xx', count: 1 }
            - { day: '2026-12-01', counter: 'page:/blog/*', count: 6 }
            - { day: '2026-12-01', counter: 'page:other', count: 4 }
            - { day: '2026-12-01', counter: exported, count: 2 }
            - { day: '2026-12-03', counter: pageview, count: 2 }
            - { day: '2026-12-03', counter: visit, count: 1 }
            - { day: '2026-12-03', counter: 'from:direct', count: 1 }
            - { day: '2026-12-03', counter: 'country:de', count: 1 }
      x-examples:
        # Replayed by src/openapi.test.ts. A 200 must answer exactly the 200 response's example.
        ok:
          summary: Three days of numbers
          query: '?project=my-app&since=2026-12-01&until=2026-12-03'
          headers: { authorization: Bearer an-example-token-of-some-length }
          expect: { status: 200 }
        no-token:
          summary: No token
          query: '?project=my-app'
          expect: { status: 401 }
        wrong-token:
          summary: A wrong token, answered the same way as none
          query: '?project=my-app'
          headers: { authorization: Bearer not-the-token-at-all }
          expect: { status: 401 }
        bad-range:
          summary: A range over 366 days
          query: '?project=my-app&since=2025-01-01&until=2026-12-01'
          headers: { authorization: Bearer an-example-token-of-some-length }
          expect: { status: 400 }
        store-down:
          summary: The database refused the read
          query: '?project=my-app'
          headers: { authorization: Bearer an-example-token-of-some-length }
          store: failing
          expect: { status: 500 }
        no-token-set:
          summary: The server was given no token, so stats are off
          query: '?project=my-app'
          token: ''
          expect: { status: 503 }
      responses:
        '200':
          description: The numbers.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Stats' }
              example:
                project: my-app
                since: '2026-12-01'
                until: '2026-12-03'
                pageviews: 12
                visits: 5
                humans: 3
                sources: { direct: 2, search: 3 }
                campaigns: {}
                countries: { de: 4, xx: 1 }
                pages: { /blog/*: 6, other: 4 }
                events: { exported: 2 }
                days:
                  - { day: '2026-12-01', pageviews: 10, visits: 4, humans: 3 }
                  - { day: '2026-12-02', pageviews: 0, visits: 0, humans: 0 }
                  - { day: '2026-12-03', pageviews: 2, visits: 1, humans: 0 }
        '400':
          description: No valid `project`, or a range that isn't two UTC days in order and at most 366 days long.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401':
          description: The token is missing or wrong.
          headers:
            WWW-Authenticate:
              schema: { type: string, const: Bearer }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: The store failed. The details go to the server's log, never into the answer.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: The server has no token of at least 16 characters, so stats are off.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
components:
  securitySchemes:
    statsToken:
      type: http
      scheme: bearer
      description: The `token` given to `createStatsHandler`. A long random secret, never the database key.
  headers:
    AllowOrigin:
      description: The request's `Origin`, echoed back once it has been checked.
      schema: { type: string }
  schemas:
    Beacon:
      type: object
      description: |
        Everything the browser sends. Nothing here identifies a person: no id, cookie, URL,
        path or time. The client sends `visit`, `ref` and `via` only on the first page of a visit,
        and `route` only when it was given `routes`.
      required: [project, event]
      properties:
        project:
          type: string
          pattern: '^[a-z0-9][a-z0-9-]{0,63}$'
          description: The project's slug, a key of the handler's `projects`.
          examples: [my-app]
        event:
          type: string
          description: |
            `pageview`, `human` (an engaged visit: the first real input, or 10 seconds on
            screen, once per visit), or one of the project's own `events`, which match
            `^[a-z][a-z0-9_]{0,39}$`.
          examples: [pageview, human, exported]
        visit:
          type: boolean
          const: true
          description: On a page view, the first page of a visit from another site or from none. Absent otherwise.
        ref:
          type: string
          maxLength: 253
          description: On a visit, the referring site's hostname (never a path), or `""` for none.
          examples: [www.google.com, '']
        route:
          type: string
          maxLength: 100
          description: |
            On a page view, the page-type pattern the path matched (`/blog/*`, `/posts/[id]`),
            or `/_other` for none. Never the path itself. One the server doesn't list counts as `page:other`.
          examples: [/blog/*, /_other]
        via:
          type: string
          maxLength: 40
          description: |
            On a visit that arrived with `?ref=` (or `?utm_source=`), when the client was given
            `campaigns`: the tag if it is listed there, else `other`. The raw value never leaves the
            browser. The server counts `via:<tag>` for a tag the project lists and `via:other` for
            anything else, and only for projects with `campaigns`.
          examples: [newsletter, other]
      additionalProperties: true
    Stats:
      description: A `Summary` (what `summarize` returns), with the project and range it covers.
      allOf:
        - type: object
          required: [project, since, until]
          properties:
            project: { type: string }
            since: { type: string, format: date }
            until: { type: string, format: date }
        - $ref: '#/components/schemas/Summary'
    Summary:
      type: object
      description: |
        Totals for the range, built from counter names (`docs/counters.md`). Each map is
        ordered largest first.
      required: [pageviews, visits, humans, sources, campaigns, countries, pages, events, days]
      properties:
        pageviews: { type: integer, minimum: 0 }
        visits: { type: integer, minimum: 0 }
        humans: { type: integer, minimum: 0, description: 'Engaged visits: a real input, or 10 seconds on screen.' }
        sources: { $ref: '#/components/schemas/Counts', description: '`from:*`, by source key.' }
        campaigns: { $ref: '#/components/schemas/Counts', description: '`via:*`, by campaign tag. Empty for a project without `campaigns`.' }
        countries: { $ref: '#/components/schemas/Counts', description: '`country:*`, by lowercase country code; `xx` is unknown.' }
        pages: { $ref: '#/components/schemas/Counts', description: '`page:*`, by route pattern, or `other`.' }
        events: { $ref: '#/components/schemas/Counts', description: "The project's own events." }
        days:
          type: array
          description: Every day in the range, oldest first, zeros included.
          items:
            type: object
            required: [day, pageviews, visits, humans]
            properties:
              day: { type: string, format: date }
              pageviews: { type: integer, minimum: 0 }
              visits: { type: integer, minimum: 0 }
              humans: { type: integer, minimum: 0 }
    Counts:
      type: object
      additionalProperties: { type: integer, minimum: 0 }
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: string
          description: What was wrong, for a person reading it. Clients don't need to read it.
      additionalProperties: true
