Просмотр документации
Документация

ORSP 1.6 Protocol & API Reference

Authoritative HTTP and JSON Schema reference for Origo Source Protocol (ORSP) 1.6, covering source discovery, core reading endpoints, rankings, anonymous covers, and OEP-0004/0005/0006 extensions.

На этой странице

This reference specifies the HTTP(S) contract and JSON schemas for Origo Source Protocol (ORSP) 1.6, the open reading source protocol used by Origo X. ORSP defines a clean, stateless, unauthenticated read-only boundary between reading clients and independent content providers.

Unlike client-side rule scrapers, ORSP transmits structured data only—never executable scraping scripts. If you are migrating declarative Legado (Reading 3.0) rules to ORSP or running them locally, see the Legado Compatibility & Adapter Guide. The normative specification, OpenAPI 3.1 contract, and conformance tools live in origo-source-protocol.

Transport Boundary & Protocol Headers

  • Naming: The product is Origo X, the source ecosystem is Origo Source, and the canonical protocol identifier is origo-source.
  • Transport Security: Production sources should serve discovery documents, API endpoints, EPUBs, and media over https:// using TLS 1.2 or newer. Clients must validate the certificate chain and hostname and must never silently downgrade HTTPS to HTTP. Plain http:// is permitted for local development and legacy public sources.
  • Versioning (major.minor): protocolVersion uses major.minor (such as 1.6) with no patch component. Minor revisions may add optional JSON fields, optional capabilities, or enum values with explicit fallback rules, but must never break existing 1.x fields or HTTP status semantics.
  • Protocol & Purpose Headers:
    • Accept: application/json: Clients should send this on core API requests.
    • X-Origo-Source-Protocol: Clients send their highest supported ORSP 1.x version (for example 1.6), and sources may echo their version in the response header. During migration, sources should also emit the legacy equivalent X-Open-Reading-Protocol.
    • X-Origo-Source-Request-Purpose: health-check: Advisory header sent by probes and source directories so operators can exclude health checks from reader metrics and rankings. It never grants access, elevates privileges, or bypasses rate limits. The legacy header X-Open-Reading-Request-Purpose carries identical advisory semantics, with the canonical header taking precedence.

Source Discovery

Every ORSP 1.6 source must publish a UTF-8 JSON discovery document at the site root:

GET /.well-known/origo-source.json

To continue serving installed 1.x readers, new 1.x sources must also serve a compatible discovery document at the legacy path with the exact same id, origin, apiBaseUrl, and capabilities (it must not HTTP-redirect to a document returning the new identifier):

GET /.well-known/open-reading-source.json

Discovery Fields

Field Type Required Description
protocol string Yes Must be origo-source on the canonical path (open-reading-source on the legacy alias)
protocolVersion string Yes major.minor string; 1.6 for this specification
id string Yes Globally scoped opaque source ID (3–200 chars, starts/ends with ASCII alphanumeric, middle allows A-Za-z0-9._-; reverse-DNS recommended)
name string Yes User-facing source title (1–120 chars)
apiBaseUrl string Yes Absolute HTTP(S) base URL ending with /, with no credentials, query string, or fragment
capabilities string[] Yes 4–64 unique capability strings; must include all four core capabilities: search, detail, catalog, content
description string No Source description (max 1000 chars)
iconUrl string No Absolute HTTP(S) icon URL
websiteUrl string No Absolute HTTP(S) homepage URL
languages string[] No Array of BCP 47 language tags (en, zh-CN, sr-Latn), max 100 items
supportedVersions string[] No Non-empty unique list of implemented ORSP versions; must include protocolVersion when present
maxCatalogPageSize integer No Maximum accepted pageSize on the catalog endpoint (1–1000; defaults to 100 when omitted)
contentTypes string[] No Up to 32 unique lowercase MIME types emitted by chapter responses (must not contain application/epub+zip)
operatorName string No Legal or operational entity responsible for rights inquiries
contactUrl string No Operator-controlled absolute HTTP(S) contact or rights-notice page
contentLicense string No Short license name or basis (such as CC BY 4.0 or Public Domain)
rightsStatement string No Concise statement describing content provenance or authorization scope

Capability Rules & Origin Isolation

  • Core Capabilities (Mandatory): search, detail, catalog, content.
  • Optional Standard Capabilities:
    • discover (v1/discover): Curated discovery shelves.
    • categories (v1/categories): Stable category taxonomy; declaring categories requires declaring browse.
    • browse (v1/browse): Paginated browsing by category or standard sort.
    • rankings (v1/rankings and v1/rankings/{rankingId}): Named paginated ranking snapshots.
  • Extension Namespaces: Extensions must use reverse-DNS domain:name syntax (such as top.xxread:chapter-updates) and must never claim the reserved orsp namespace. Advertising top.xxread:image-sequence requires image/sequence in contentTypes (and vice versa); advertising top.xxread:remote-audio requires audio/uri in contentTypes (and vice versa).
  • Composite Storage Key: Because there is no central ID authority, clients must key installed sources by at least (id, origin) rather than id alone. If two distinct origins advertise the same id, clients must surface the conflict to the user and never silently merge or overwrite an existing source.
{
  "protocol": "origo-source",
  "protocolVersion": "1.6",
  "id": "org.example.public-library",
  "name": "Example Public Library",
  "description": "Open public-domain catalog served via ORSP 1.6",
  "apiBaseUrl": "https://books.example.org/api/",
  "languages": ["en", "zh-CN"],
  "supportedVersions": ["1.6"],
  "maxCatalogPageSize": 200,
  "capabilities": [
    "search",
    "discover",
    "categories",
    "browse",
    "rankings",
    "detail",
    "catalog",
    "content",
    "top.xxread:chapter-updates",
    "top.xxread:publications"
  ],
  "contentTypes": ["text/plain", "text/html"],
  "operatorName": "Example Open Books Initiative",
  "contactUrl": "https://books.example.org/contact",
  "contentLicense": "Public Domain",
  "rightsStatement": "Distributes verified public-domain works and openly licensed texts only."
}

Data Model, Encoding & Anonymous Covers (OEP-0008)

Encoding & Identifiers

  • JSON Conventions: Requests and responses use UTF-8 and application/json with case-sensitive property names. Clients must ignore unknown JSON fields at any nesting depth and unknown optional capabilities. User-visible strings should be Unicode NFC normalized, and timestamps must use RFC 3339 date-time (preferably UTC Z).
  • Omission vs. null: When an optional member has no value, sources must omit the key rather than returning null unless the schema explicitly permits null.
  • Opaque Identifiers (OpaqueId): Book, chapter, section, category, and ranking IDs must be 1–200 chars matching ^[A-Za-z0-9._~-]+$ (RFC 3986 unreserved ASCII). Clients treat IDs as single opaque path segments without inferring structure. Deleted IDs must never be reassigned to a different logical resource.
  • Enums: Descriptive enums containing unknown (status, mediaKind) fall back to unknown for unrecognized values. Processing enums such as contentType must fail explicitly on unsupported values rather than guessing plain text.

Anonymous Book Covers (OEP-0008)

Books may carry a structured cover object alongside the legacy optional coverUrl string:

Member Type Required Meaning
cover.url string Yes Absolute HTTP(S) image URL fetchable via anonymous GET
cover.type string No Image media type (e.g. image/jpeg); must match the HTTP response Content-Type media type
cover.width integer No Positive pixel width
cover.height integer No Positive pixel height
  • Anonymous Delivery: Cover URLs must succeed on an anonymous GET without Cookie, Authorization, inferred Referer hotlink headers, or session tokens, returning 2xx with an image Content-Type (never a login page or HTML placeholder). Sources requiring upstream hotlink headers or tokens must proxy or cache images on their own origin and publish stable anonymous URLs.
  • Client Fallback Order: Readers display covers in order: cover -> coverUrl -> cover from fresh book detail -> generated or placeholder image. Missing width/height alone must never trigger a detail fetch, and cover failures must never discard book metadata.

Core Reading Endpoints

All endpoint paths resolve relative to apiBaseUrl and use safe, idempotent GET requests.

1. Search Books: GET v1/search

GET v1/search?q={query}&page={page}&pageSize={pageSize}
  • q: Required; trimmed length must be 1–200 Unicode scalar values.
  • page: Optional 1-based integer, default 1.
  • pageSize: Optional integer 1–100, default 20.
{
  "items": [
    {
      "id": "book-1001",
      "title": "Example Book",
      "author": "Example Author",
      "description": "Concise synopsis",
      "cover": {
        "url": "https://books.example.org/covers/1001.jpg",
        "type": "image/jpeg",
        "width": 600,
        "height": 900
      },
      "coverUrl": "https://books.example.org/covers/1001.jpg",
      "categories": ["Fiction"],
      "status": "completed",
      "latestChapter": "Chapter 30",
      "language": "en",
      "mediaKind": "text",
      "type": 8,
      "updatedAt": "2026-07-11T10:00:00Z"
    }
  ],
  "page": 1,
  "pageSize": 20,
  "total": 1,
  "hasMore": false
}
  • items, page, pageSize, and hasMore are required (total is optional). Every Book requires id and title.
  • status accepts ongoing, completed, hiatus, or unknown.
  • mediaKind accepts text, image-sequence, remote-audio, or unknown; sources may also include the legacy integer type bridge (8 for text, 64 for image sequence, 32 for remote audio).

2. Book Detail: GET v1/books/{bookId}

Returns the shared Book object with richer synopsis or metadata. Field meanings must remain consistent with search results. Sources advertising OEP-0005 or OEP-0004 may optionally expose catalogVersion, chapterCount, or publications here.

3. Chapter Catalog: GET v1/books/{bookId}/chapters

GET v1/books/{bookId}/chapters?page={page}&pageSize={pageSize}
  • page defaults to 1; pageSize defaults to 100 and is capped by discovery maxCatalogPageSize (or 100 if omitted). Exceeding the cap must return 400.
  • Pages must be deterministically ordered by (order, id) ascending, where order is a non-negative integer.
{
  "items": [
    {
      "id": "chapter-1",
      "title": "Chapter 1: Departure",
      "order": 1,
      "updatedAt": "2026-07-11T10:00:00Z"
    }
  ],
  "page": 1,
  "pageSize": 100,
  "total": 1,
  "hasMore": false
}

4. Chapter Content: GET v1/books/{bookId}/chapters/{chapterId}

{
  "bookId": "book-1001",
  "chapterId": "chapter-1",
  "title": "Chapter 1: Departure",
  "contentType": "text/html",
  "content": "<p>Chapter body text.</p>",
  "baseUrl": "https://books.example.org/books/book-1001/"
}
  • bookId and chapterId must exactly match the requested path parameters.
  • Core text contentType values are text/plain, text/markdown (CommonMark), and text/html (an HTML fragment, not a full document). Relative URLs resolve against baseUrl when present, or the final chapter request URL otherwise.
  • Sources must strip <script>, event-handler attributes (on*), <iframe>, active form controls, and dangerous URI schemes from HTML and embedded Markdown HTML; clients must also sanitize before rendering.

Optional Standard Capabilities: Discovery, Categories, Browse & Rankings

Clients may call these endpoints only when advertised in capabilities:

Curated Discovery: GET v1/discover

Returns {"sections": [{"id": "featured", "title": "Featured", "items": [...]}]}. Each section contains at most 100 books; empty sections should be omitted. Ordering must be deterministic for an unchanged dataset, and clients must not assume personalization unless explicitly documented outside ORSP.

Categories & Browse: GET v1/categories and GET v1/browse

  • GET v1/categories returns {"items": [{"id": "fiction", "name": "Fiction"}]}. Each id must work verbatim as the category query parameter on v1/browse.
  • GET v1/browse?category={categoryId}&sort={sort}&page={page}&pageSize={pageSize}:
    • sort defaults to latest (descending by updatedAt, placing undated books last) and also supports popular. Unsupported sort values must return 400.
    • Passing category to a source that does not declare categories must return 400.
    • Multi-source aggregators must preserve (sourceId, origin) attribution and balance items across sources rather than merging resources by matching IDs or letting one source's timestamps dominate.

Multiple Named Rankings (OEP-0007): rankings

Sources declaring rankings implement:

GET v1/rankings
GET v1/rankings/{rankingId}?page={page}&pageSize={pageSize}

The collection returns up to 100 ranking definitions with required id, title, and optional description, period (realtime, daily, weekly, monthly, all-time), and categoryId (only permitted when categories is also advertised):

{
  "items": [
    {
      "id": "weekly-popular",
      "title": "Weekly Popular",
      "description": "Most read books this week",
      "period": "weekly",
      "categoryId": "fiction"
    }
  ]
}

Each paginated ranking response includes required ranking, snapshotId, items, page, pageSize, hasMore, and optional snapshotAt, total:

{
  "ranking": {
    "id": "weekly-popular",
    "title": "Weekly Popular",
    "period": "weekly"
  },
  "snapshotId": "weekly-popular-2026-w30",
  "snapshotAt": "2026-07-26T00:00:00Z",
  "items": [
    {
      "rank": 1,
      "previousRank": 3,
      "score": 9850,
      "scoreLabel": "9,850 reads",
      "book": {
        "id": "book-1001",
        "title": "Example Book"
      }
    }
  ],
  "page": 1,
  "pageSize": 20,
  "total": 1,
  "hasMore": false
}
  • rank is the 1-based absolute position across the entire snapshot (the first item on page N must have rank == (N - 1) * pageSize + 1), unique and ascending.
  • Clients must compare snapshotId across pages and restart from page 1 if the snapshot changes. Unknown ranking IDs return 404 with RANKING_NOT_FOUND. Rankings are authoritative only within a (source, rankingId, snapshotId) tuple.

Namespaced Extension Profiles (OEP-0004 / 0005 / 0006)

Chapter Updates & Consistent Catalog Refresh (top.xxread:chapter-updates, OEP-0005)

Because updatedAt, chapter counts, and latestChapter titles miss mid-book insertions, renames, or body edits, OEP-0005 adds an update-state probe and version pinning:

  • Update State Endpoint: GET v1/books/{bookId}/updates
{
  "bookId": "book-1001",
  "catalogVersion": "catalog-12",
  "chapterCount": 2,
  "updatedAt": "2026-10-13T08:00:00Z",
  "latestChapter": {
    "id": "chapter-2",
    "title": "Chapter 2: Deeper",
    "order": 1,
    "contentVersion": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
  }
}
  • catalogVersion is an opaque 1–200 char ASCII token that must change whenever chapter IDs, titles, order, body content, or publications change, and remain stable otherwise. Clients test equality only (latestChapter must be omitted if chapterCount == 0).
  • contentVersion is the lowercase 64-char SHA-256 of the exact UTF-8 content string (with no implicit newline or Unicode normalization), exposed on both catalog items and chapter content responses.
  • Version Pinning: When this capability is declared, clients may pass ?catalogVersion={token} to v1/books/{bookId}/chapters and v1/books/{bookId}/chapters/{chapterId}. If the requested snapshot is no longer current, the source must never silently serve another snapshot; it must return 409 Conflict with X_CATALOG_VERSION_CONFLICT (evaluated prior to conditional 304). Malformed tokens return 400 INVALID_PARAMETER.

Complete EPUB Publications (top.xxread:publications, OEP-0004)

  • GET v1/books/{bookId}/publications returns {"items": [Publication]} (optionally also mirrored on book detail).
  • Each Publication defines an immutable opaque id, absolute HTTP(S) href, mediaType: "application/epub+zip", positive bytes, and lowercase 64-char sha256 of the complete EPUB file.
  • Content updates must allocate a new id; clients verify both bytes and sha256 before importing. Sources must never return an EPUB archive as chapter content.

Image Sequences & Remote Audio (top.xxread:image-sequence, top.xxread:remote-audio, OEP-0006)

Both profiles reuse GET v1/books/{bookId}/chapters/{chapterId} with content: "":

  • image/sequence: Requires non-empty ordered images (1–2000 items; audio must be absent). Each item has required url and optional mimeType, width, height, alt, expiresAt, and headers.
  • audio/uri: Requires audio object (images must be absent) with required url and optional mimeType, durationSeconds (> 0, <= 315360000), transport (file or hls), expiresAt, and headers.
  • Safe Request Hints (headers): Restricted strictly to Referer, Origin, and Accept in canonical spelling; must never carry Authorization, Cookie, Host, proxy credentials, or user identifiers, and must never be forwarded across origins on redirect.
  • Revision Fingerprints vs. File Hashes: For media chapters, contentVersion is a source-generated 64-char SHA-256 revision fingerprint over ordered assets and media semantics—not a hash of "" and never a substitute for file-level sha256 verification. On signed URL expiration (401/403/404/410), readers may refresh chapter metadata once and retry if the URL changed.

HTTP Caching, Status Codes & Error Envelope

Caching & Redirect Policy

  • Discovery, shelves, categories, browse, detail, catalog, and content endpoints should emit ETag (or Cache-Control / Last-Modified) and return an empty-body 304 Not Modified on matching If-None-Match. Per-page catalog ETags are URI-scoped and cannot verify whole-book catalog consistency across different page URLs.
  • Redirect limits: maximum 5 redirects per request, HTTP(S) targets only, no silent HTTPS-to-HTTP downgrade, and no credential or private-header forwarding across origins.

Status Codes & Error Envelope

All error responses with bodies must use the standard envelope:

{
  "error": {
    "code": "BOOK_NOT_FOUND",
    "message": "The requested book does not exist",
    "retryable": false,
    "requestId": "request-7f3a"
  }
}
Status Standard Code Condition
304 — Selected representation unchanged (If-None-Match); empty body
400 INVALID_PARAMETER Missing, malformed, or out-of-range query parameter or path ID
404 BOOK_NOT_FOUND Unknown bookId
404 CHAPTER_NOT_FOUND Unknown chapterId within the book
404 RANKING_NOT_FOUND Unknown rankingId
404 ROUTE_NOT_FOUND Undefined source endpoint path
405 METHOD_NOT_ALLOWED Unsupported HTTP method; include Allow response header
409 X_CATALOG_VERSION_CONFLICT OEP-0005: requested catalogVersion no longer matches current catalog
429 RATE_LIMITED Client exceeded rate limit; include Retry-After
500 INTERNAL_ERROR Unexpected server error (never expose stack traces, cookies, or internal URLs)
503 UNAVAILABLE Temporary outage or upstream saturation; may include Retry-After

All unprefixed uppercase error codes are reserved for the ORSP specification; source-specific codes must start with X_ (for example X_REGION_BLOCKED).

Security Hardening & Conformance Tooling

  • Security Posture: All source responses are untrusted input. Readers and source proxies enforce SSRF and DNS-rebinding defenses (blocking loopback, link-local, and private network ranges), bounded timeouts, decompressed payload limits against zip/gzip bombs, and bounded image decode dimensions. Browser-facing sources must configure appropriate CORS headers.
  • Validation Tools (origo-source-protocol):
    • scripts/probe_source.py: Bounded, read-only structural probe that sends X-Origo-Source-Protocol: 1.6 and X-Origo-Source-Request-Purpose: health-check, pins resolved public IP addresses (loopback requires explicit opt-in), and verifies discovery, core, and extension contracts without harvesting book bodies.
    • tool/conformance_test.dart & tool/discovery_conformance_test.dart: Official Dart conformance suites validating Core Reading, Discovery, Rankings, OEP-0008 anonymous covers, redirect loop caps, and oversized payload rejection.

See also: Origo Source Overview, Building an Origo Source, Extension Profiles Guide, Legado Compatibility & Adapter Guide.

Нашли проблему в руководстве? Предложить правку