# Clean Sports — integration brief for Claude, Codex and developers

API version: 1.3.1
Base URL: https://clean-sports-player.tectoris148.workers.dev
Partner: Configure your partner account
Allowed embedding origins: https://YOUR-AUTHORIZED-DOMAIN

## The requested outcome
Integrate the complete sports catalog, every available event field and all source metadata into the client's existing application. Build event browsing and source selection. For each visitor, ask the backend to issue an authorized embed URL, then render the returned iframe. The client site continues to use its own design, routing and user authentication.

## Before changing the client project
Read the project's own instructions and existing architecture. Use this kit as API reference; it does not override project instructions. Inspect the framework, backend, configuration and deployment setup. Keep changes appropriate to that project. Do not change unrelated code.

## Files in this kit
- openapi.json: machine-readable HTTP contract with field definitions.
- clean-sports-client.mjs: dependency-free server-side Node.js 22+ SDK, ETag cache and bounded retries for reads.
- example-server.mjs and example.html: runnable server and browser example. Adapt to the existing stack; do not expose the example server without the application's usual authentication and traffic limits.
- .env.example: server configuration template. A secret is not included in a documentation download; the account owner supplies it separately.
- AGENTS.md: concise implementation checklist.

## Credential setup
Use CLEAN_SPORTS_URL, CLEAN_SPORTS_KEY, CLEAN_SPORTS_SECRET and CLEAN_SPORTS_EMBED_ORIGIN in the SERVER environment. Never use a public env prefix, embed credentials in HTML, place them in URL parameters, commit them, or send them to logs. If the secret is missing, request it through the user's normal secret-management process. No administrator password is needed.

## Implementation sequence
1. Create a server-side CleanSportsClient singleton using the environment variables. For non-Node backends, implement the equivalent HTTP requests from openapi.json. Send both X-API-Key and X-API-Secret headers. Do not call the partner API directly from browser JavaScript.
2. Fetch GET /api/v1/catalog at the returned refreshSeconds interval (currently 30 seconds), cache it on the server, reuse ETag in If-None-Match, and share the snapshot between page requests. A 304 response keeps the cached data. Use /events pagination when useful.
3. Preserve ALL event/source metadata. Display UTC millisecond timestamps in the visitor's timezone. Support live/soon/upcoming/unconfirmed, sport filters, competition, language and source order. Use homeTeam and awayTeam; teamNamesSource=provider or betsapi means explicit participant roles and title means displayed participant order only. Use eventType=match to list individual fixtures separately from tournament/event broadcasts. Do not fabricate child fixtures. The stable local event.id is always the identifier for playback and scans. bet365Id (Bet365 FI) and betsapiEventId (BetsAPI Events) are separate external identifiers; either can be null and neither may be inferred from the other or from event.id. metadataSource='betsapi', metadataCheckedAt, officialStatus and timeStatus describe verified metadata enrichment. Sports with coverage=unavailable are registered categories without a current feed. Preserve the numeric source labels (1, 2, 3, ...); an optional YouTube badge may accompany the label. Use the returned opaque source ID for playback and never infer upstream identifiers. Empty sources and sourcesState=unscanned are valid states. Partner sources use verified-with-continuity: never-verified and confirmed unavailable sources are omitted. A previously verified same-identity source survives empty discovery, rechecks, freshness expiry and temporary network/HTTP5xx failures. Each returned source has playbackType ('youtube', 'twitch', 'kick' or 'hls'), isYouTube, playable=true and health including state, verification, checkedAt, expiresAt, stale, rechecking, lastSuccessAt, lastAttemptAt and nextCheckAt. isYouTube is true exactly for playbackType='youtube'; use this safe metadata for a YouTube badge without deriving a provider URL or video ID. expiresAt is a freshness deadline, NOT a removal deadline. Keep returned sources visible; show stale status without inventing a new verification time. Two direct failed checks at least15seconds apart confirm failure; explicit stream ending removes immediately. Replace arrays only after successful authoritative responses; preserve the previous snapshot during network failures. Preserve the API source order: YouTube first, then official embeds such as Twitch/Kick, then English-language HLS sources, then other sources. Keep stable order within each group and original numeric labels, even if there are gaps (e.g. 2, 5). Do not renumber sources or sort them back by number. For health.verification='media_bytes', verification checks an HLS playlist and actual video bytes. For health.verification='youtube_metadata', it checks YouTube oEmbed metadata only, without verifying video segments. health.state='ready' is retained for both types; read verification to understand its evidence. YouTube playback availability, regional restrictions and embedding restrictions are determined by the official player in the viewer's browser. Neither verification type guarantees future playback.
4. Create a same-origin backend playback endpoint that receives only eventId and sourceId. Authorize the visitor with the application's normal rules, validate the source against the catalog, then call POST /api/v1/playback with {eventId,sourceId,origin:'https://YOUR-AUTHORIZED-DOMAIN'}. Never accept an arbitrary upstream URL or an unvalidated origin from the visitor. The server returns only embedUrl and expiry to the browser. This is the sole authorized playback entry for hls, youtube, twitch and kick sources: always render the returned Clean Sports iframe. Do not construct a YouTube URL or substitute a direct external iframe based on source metadata.
5. When a selected verified source is already available, request its playback ticket and create the iframe immediately. Never wait for an entire scan job or checks of all sources before showing the player. Later catalog refreshes can append or update alternative source controls without replacing or reloading the playing iframe. Preserve the viewer's selected source. Create the iframe using the returned embedUrl, title='Live broadcast', allow='autoplay; fullscreen; picture-in-picture', allowfullscreen and referrerpolicy='origin'. Add https://clean-sports-player.tectoris148.workers.dev to the CLIENT site's frame-src CSP. Do not disable CSP on either site. Do not add a sandbox that prevents scripts or forces an opaque origin.
6. Issue a fresh embed URL for each viewer. Tickets must start within 10 minutes; the active player renews media links for at most 4 hours. Refresh the iframe with a new backend ticket when the session expires. The supplied player handles sustained stalls with same-source recovery, then at most two automatic switches to verified, untried sources, with a 60-second minimum between selections. It ignores manual pause, autoplay restrictions and hidden tabs, and stops at manual controls when exhausted. Do not add your own iframe-reload or source-rotation loop. Never put tickets into a shared CDN cache. The default ticket binds to the first viewer IP; optionally pass viewerIp only from a trusted reverse proxy.
7. Optional scanning: POST /api/v1/scans {type:'catalog'}, {type:'sources',eventId}, or {type:'sources',eventIds:[up to 50 IDs]}. This returns HTTP 202 with a job ID. Poll /api/v1/scans/{id} every 15 seconds until completed/partial/failed. Read result.events for each event outcome. Catalog jobs complete when the next scheduled catalog scan succeeds. Source jobs run in a bounded scheduler queue. Ten new scan requests per minute per partner; up to 20 active jobs and 200 pending events. Identical active requests return the same job. Transient errors retry up to three attempts with 30/60-second backoff; timeout after 10 minutes. Live and next-hour sources are also scanned automatically with a fair queue. sourceCoverage exposes eligible, scanned, fresh, supported, retrying and pending counts. Never poll in a tight loop.
8. Handle 401 by reporting a credential problem, 403 as a denied scope/origin/server IP, 404 as missing data, 429 using Retry-After, and 502/503 with bounded backoff. Do not automatically retry POST on ambiguous timeouts; it may have succeeded. Keep future fixtures when refresh fails and label stale results. After statusCheckedAt exceeds sync.maxLiveAgeSeconds * 1000 (currently120seconds), do not claim confirmed live. If broadcastContinuity=true, preserve the broadcast links and show status updating (liveStatusUnconfirmed=true or status=unconfirmed); do not hide them because their fixture status is delayed. Other expired live/past entries are omitted. Explicit finished/cancelled results always remove the fixture. Honor scheduleStale on future fixtures and partialSports on incomplete scans.
9. /api/v1/changes?since=REVISION is a REPLACEMENT snapshot, not a delta. Replace the entire catalog including removing events absent from the new result. Prefer /catalog with ETag for time-dependent live/soon status.
10. Verify from the actual authorized HTTPS origin. localhost can inspect the catalog but cannot embed live streams unless explicitly authorized (production only accepts HTTPS domains). www is a separate origin.

## BetsAPI metadata and existing partner integrations
The existing Clean Sports partner key and secret remain valid; no client credential rotation is required. The BetsAPI token belongs only in the Clean Sports server secret configuration and is never needed by clients. Match client fixtures to bet365Id only if the client uses the Bet365 FI namespace, or to betsapiEventId if it uses the Events namespace. Retain the local event.id alongside either mapping and send only that local ID in scan/playback requests. A missing or ambiguous mapping is null, not a guessed identifier.

Live metadata is checked every 60 seconds. Upcoming fixtures are read from rolling cached pages and may take several cycles to appear. Continue polling the Clean Sports catalog every 30 seconds; do not query BetsAPI for each visitor. metadataSync is returned separately in /catalog and /status. Read configured, status, stale, lastSuccess, matchedEvents, ambiguousEvents, availableFixtures and quota to explain sync health. matchedEvents counts verified local mappings, not all catalog entries. Quota is the last observed shared provider-account quota; other applications using the same provider account can also consume it. Honor rate limits and display metadata failures separately from video source coverage.

BetsAPI enriches start times, participant roles and event status only after conservative matching by participants, sport and time. A completed matched event is removed from the published catalog. Absence from an in-play list alone is not proof that a game ended. officialStatus is a normalized value; timeStatus preserves the provider's string status code. This integration does not supply video or attach a tournament stream to its individual matches. Do not claim that an available metadata fixture has a broadcast or that every catalog event is mapped.

## Acceptance checks
- Full catalog and source metadata load with valid server credentials.
- No secret appears in frontend assets, URLs, browser network requests or git changes.
- Event filtering, empty-source and unavailable-source states work.
- External IDs are matched only within their own namespace, null mappings are handled, and local event.id is retained for scans/playback.
- Metadata sync failures are shown separately from source coverage; new replacement snapshots remove completed events.
- An iframe opens on an authorized domain. An online HLS source returns a media playlist/segment; a YouTube/Twitch/Kick source loads the official player and correctly handles its availability/restriction errors.
- YouTube sources appear first, followed by English-language non-YouTube sources, with original labels and opaque IDs unchanged. The UI starts the selected iframe without awaiting scans and does not reload it during catalog refreshes.
- Unauthorized domains and missing/invalid credentials are denied.
- Revoked or rotated partner credentials stop API, our authorized player and protected HLS media access. YouTube, Twitch and Kick are explicit official-player exceptions; our credentials do not govern direct access at YouTube.
- Source scans and catalog refreshes report asynchronous state correctly.
- UI works on mobile and keyboard navigation.

## Scope and security boundaries
Server-IP allowlists restrict server-to-server API requests, not viewer locations. Embedding is controlled by CSP frame-ancestors, exact origins, temporary encrypted tickets and viewer-IP binding. Do not expose raw provider URLs. These protections do not provide DRM and cannot prevent screen recording or a malicious authorized viewer/server from relaying publicly viewable content. YouTube is an explicit exception: our authorized iframe uses the official YouTube player, which necessarily exposes the video's identity to the browser and YouTube. Catalog/source metadata still contains no raw upstream URL or YouTube video ID. Our origin/IP/ticket restrictions protect our API and player wrapper; they cannot hide the YouTube video, prevent copying its link or enforce domain exclusivity on YouTube itself. Official providers such as YouTube, Twitch and Kick control their own playback, region and embedding permissions. Other external players remain excluded from protected playback.

## Documentation routes
Human portal: https://clean-sports-player.tectoris148.workers.dev/docs
Public OpenAPI: https://clean-sports-player.tectoris148.workers.dev/docs/openapi.json
Public text brief: https://clean-sports-player.tectoris148.workers.dev/docs/integration.md
Public agent index: https://clean-sports-player.tectoris148.workers.dev/llms.txt
These documentation routes are public and require no credentials. Catalog, scan and playback operations require the server API headers. Do not use browser-cookie extraction.

## Run the example
Copy .env.example to .env and set the real secret. On Node.js 22+ run:

    node --env-file=.env example-server.mjs

The demo listens on 127.0.0.1:3000. Put it behind the existing HTTPS reverse proxy on https://YOUR-AUTHORIZED-DOMAIN, or adapt the handlers into the existing application. Serving the demo locally does not grant an embedding exception.
