# PulseAI server delivery protocol

This contract is implemented locally and covered by SQLite handler tests. It does not establish a deployed customer installation, public ingress, live payment, or measured detector accuracy.

`POST /api/events` requires HTTPS, `Content-Type: application/json` and `Authorization: Bearer <per-site ingestion key>`. Keep the key in a server secret. The target domain must be ownership-verified and its owner must have a current server-verified subscription. Being signed in or preparing a domain does not grant paid analytics or ingestion.

```json
{
  "siteId": "owned-site-id",
  "events": [{
    "id": "b6999019-85f2-4c36-8acd-14fe60c853ec",
    "observedAt": "2026-10-19T12:00:00.000Z",
    "kind": "request",
    "path": "/pricing",
    "source": "other",
    "classification": "unknown",
    "action": "observed"
  }]
}
```

Generate the event ID when the source event is durably recorded. Its ID and observation timestamp are immutable across retries; do not generate them during each delivery attempt. IDs are 8–128 ASCII letters, digits, underscores or hyphens, beginning with a letter or digit. IDs must be unique within each batch and are deduplicated per site. Each batch is 1–50 events and at most 32 KiB. The timestamp must be UTC ISO text with seconds and optional 1–3 fractional digits, no older than seven days and at most five minutes in the future.

A successful HTTP 202 returns:

```json
{
  "accepted": 1,
  "duplicates": 0,
  "acceptedIds": ["b6999019-85f2-4c36-8acd-14fe60c853ec"],
  "rejectedIds": [],
  "receivedAt": "2026-10-19T12:01:00.000Z"
}
```

`accepted` counts newly stored events. `acceptedIds` includes both new and already stored IDs, allowing recovery after a lost acknowledgement. Delete only explicitly acknowledged IDs from a durable outbox. Retain all other IDs and retry unchanged with bounded exponential backoff and jitter after connection errors, timeouts, HTTP 429 or 503. Do not follow redirects or forward credentials to a different endpoint. Monitor pending count, oldest event age, failures and rejected events; a retry queue is not evidence of delivery.

HTTP 429 `MONTHLY_LIMIT_REACHED` inserts no new events and may include `acceptedIds` for duplicates already stored. HTTP 400 `EVENT_TIME_OUT_OF_RANGE` inserts none of the batch and includes `rejectedIds` for invalid or expired timestamps, plus an empty `acceptedIds`. Record these permanent rejections and retry any remaining valid events separately. Other HTTP 400 schema errors require a producer fix. HTTP 401/403/402 require key, domain or billing action; stop rapid retries and surface the failure.

One D1 batch transaction calculates unseen IDs, reserves their account-wide quota, inserts delivery receipts and telemetry, and obtains acknowledgements. A failed quota reservation inserts neither receipts nor telemetry. Concurrent handlers cannot consume the same allowance twice. Quota applies to the UTC month of first successful receipt; traffic charts use the original observation date. Receipt time is stored separately. Retries retain the original event and do not overwrite its measurements. Receipts follow the event retention expiry; historical pre-migration rows remain readable and have no invented producer or receipt timestamps.

The supported collectors send `kind: request` with `action: observed`. For custom event requirements, contact [PulseAI Support](https://pulseaianalytics.com/support) before implementing an integration. A source name or declaration remains a collector claim. No caller-selected classification grants verified operator identity. Updated collectors may attach a productId, detectorVersion and opaque verificationReceipt; only a matching server-held receipt can upgrade that request. The dashboard shows unknown traffic as Estimated human, an estimate that can include AI browser agents that do not identify themselves.

Current collectors may also send these optional fields. Each is a label, never the underlying value, and unknown values reject the batch:

- `reasons`: detection reason codes, from `signed_agent_header`, `automation_tool_ua`, `empty_user_agent`, `missing_accept_language`, `missing_fetch_metadata`, `missing_client_hints`, `headless_client_hint`, `generic_accept`, `high_request_rate`, `conflicting_agent_names` and `datacenter_network`. Browser-header signals use headers the collector reads and discards; the data-center signal uses Cloudflare edge network metadata where available. Signals suggest automation and can have innocent causes; they do not prove AI use.
- `referrerType`: `ai_assistant`, `search`, `social`, `other_site`, `internal` or `none`. Never send the referring URL.
- `referrerSource`: for AI assistants only, one of `chatgpt`, `perplexity`, `gemini`, `copilot`, `claude`, `deepseek`, `grok`, `meta_ai` or `you`.
- `country`: a two-letter code supplied by your hosting edge or a configured trusted proxy. PulseAI does not derive a country from an IP address.

Older collectors omit these fields and keep working.

Send a configured nonsensitive route scope by default, not a raw request URL. The receiver drops query strings and fragments, decodes common encodings, rejects control characters, and masks common identifier/sensitive route patterns. These patterns cannot recognize every custom secret: redact sensitive paths at the source. Never send IPs, visitor IDs, cookies, prompts, raw headers, request bodies, typed text or page content to /api/events. The separate authenticated /api/operator-verification endpoint accepts a transient public IP before minimization, returns a request-bound receipt, and stores only bounded result metadata. See [operator verification](https://pulseaianalytics.com/downloads/pulseai-operator-verification.md) for the exact contract and privacy limits.

Existing producers must preserve stable IDs and observation timestamps when upgrading. Updating a collector does not repair historical delivery gaps or past quota counts.

Signed-in owners may use `GET /api/sites`, add one domain, verify proof and rotate its key before purchasing. `lastReceivedAt: null` means no receipt time is available; domain preparation is not a working collector installation. `/api/dashboard` continues to require an active entitlement.

Privacy access is separate from the paid dashboard: `GET /api/account/export?cursor=` returns retained owner data in pages of at most 500 events and a `nextCursor`. It excludes ingestion hashes and verification secrets. `POST /api/account/delete` requires same origin and `{"confirm":"DELETE PULSEAI DATA"}`. It refuses current subscriptions, including canceled subscriptions whose access has not expired, to prevent deleting local data while billing continues. After expiry it transactionally removes the owner's local analytics, receipts, domains and monthly usage. It does not cancel subscriptions or delete ChatGPT identity, RevenueCat/processor records, contact tickets or hashed billing audit records; support must handle those requests with the relevant providers and record-retention obligations.

## Operator verification endpoint

POST /api/operator-verification uses the same site bearer key and requires a verified property and active entitlement. Supply exactly `{siteId,eventId,observedAt,productId,clientIp,ipSource,catalogVersion}`. `ipSource` is `direct_peer`, `trusted_proxy`, `cloudflare_edge` or `configured_log_field`; this is an authenticated collector report, not independent observation of its client. The current catalog version is `catalog-2026-11-11-d8e8b77-v3`; the previous version is still accepted. A successful call returns `{receiptId,status,reasonCode}`, where status is matched/mismatch/unavailable/unsupported. Attach only receiptId as verificationReceipt to the original event with matching productId and detectorVersion. Keep the event classification declared. Raw IPs are never persisted. Historical, unsupported and failed checks cannot promote the label. Receipts are immutable and bound to exact site/event/time/product/version. Mismatched receipts reject the entire event batch before quota reservation. Verification failure must not stop ordinary reporting. For a request signed with Web Bot Auth by an allowlisted signer (currently `chatgpt.com`, product `chatgpt-agent`), replace `clientIp` and `ipSource` with `signature`: `{signature,signatureInput,signatureAgent,method,authority,target}`, the raw values from that request. PulseAI checks the RFC 9421 Ed25519 signature against the signer's published keys and requires it to cover `@authority` and `signature-agent`, name this site and be valid at `observedAt`. The headers are never persisted. Limit 300 calls/site/minute; receipts expire after seven days and are bounded by the plan allowance. Privacy export includes up to 500 events and verification records combined per page.

## Page tag endpoint

`POST /api/collect` receives the separately installed browser page tag. It takes no key: it is addressed by the public Website ID and accepts page views only when `Origin` is the verified domain or a subdomain and the owner has an active subscription. Unknown, unverified or unsubscribed websites are silently discarded with an empty 204; malformed messages return 400. Bodies are at most 4 KiB of JSON sent as `text/plain`. A `pageview` message stores one event of kind `pageview` and counts toward the monthly allowance in addition to collector request events; an `update` message adds time in view or flags engagement or automation evidence and consumes no additional event. Collectors must not send kind `pageview` to `/api/events`. A desktop browser on a cloud hosting network can receive `datacenter_network`; this can also flag people behind cloud gateways. The Cloudflare collector sends that signal from version catalog-2026-11-11-d8e8b77-v3. The tag uses localStorage and sends per-page and session-start page IDs for updates, without a persistent visitor ID. See the [page tag guide](https://pulseaianalytics.com/downloads/pulseai-page-tag.md) for setup, consent considerations and estimation limits.
