107 lines
9.1 KiB
Markdown
107 lines
9.1 KiB
Markdown
# Formats, limits and positions
|
||
|
||
`liber-format` turns a book file (bytes) into one `Document`. It never touches the file system or the network: the
|
||
app reads the file and hands over the bytes, and gets back plain values. Every input is hostile.
|
||
|
||
## 1. Formats
|
||
|
||
| Format | Detected by | What is read | Not read (v0.1) |
|
||
| :-- | :-- | :-- | :-- |
|
||
| EPUB 2 / 3 | zip + `mimetype` = `application/epub+zip`, or `META-INF/container.xml` | OPF metadata (title, creators, language, identifiers, publisher, date, description, subjects, calibre and EPUB 3 series), spine (with `linear`), the EPUB 3 nav or the NCX table of contents, XHTML chapters, raster images, footnotes (`epub:type` footnote / endnote / rearnote / note, and `aside`) | publisher CSS and embedded fonts (Liber uses its own typography), SVG and MathML (only an `<image>` inside an SVG cover survives, as an `<img>`), audio and video, fixed layout |
|
||
| FB2 | XML whose root is `FictionBook` | `title-info` (title, authors, genres, language, annotation, sequence = series), every `body` (`notes` bodies become footnotes), sections, titles, epigraphs, poems, cites, tables, `binary` images (base64) | styles, `document-info` |
|
||
| FB2 in a zip (`.fb2.zip`) | zip with exactly one `.fb2` entry | as FB2 | |
|
||
| TXT | anything else that decodes as text | encoding detection (BOM, then UTF-8, then `chardetng` with the Czech hint: Windows-1250, ISO-8859-2, Windows-1252, …); paragraphs by blank lines (or by lines when there are none); chapters by heading lines (`Chapter 3`, `Kapitola 3`, `Kapitel 3`, `CHAPTER IV`, a lone Roman numeral), else every ~40,000 characters at a paragraph break | |
|
||
| MOBI / AZW3 (KF8) | PalmDB at offset 60: `BOOKMOBI` | record 0 (PalmDOC + MOBI headers, EXTH: author, publisher, description, ISBN, language, title), text records (no compression, PalmDOC LZ77, or HUFF/CDIC) with the trailing entries removed, images by `recindex` / `kindle:embed`, chapters split at `<mbp:pagebreak>` (MOBI 6) or at the KF8 skeleton boundaries (`aid` files); TOC from headings | the NCX index, KF8 `FDST` flows after the first (CSS, SVG), fonts |
|
||
| PDF | `%PDF-` | nothing: `open` answers `FormatError::Pdf`, and the app opens it read-only in its PDF view | |
|
||
|
||
KFX (`CONT`, `\xeaDRMION\xee`) and Topaz (`TPZ`) are refused: KFX is DRM-protected or unsupported, Topaz is always
|
||
DRM-protected.
|
||
|
||
## 2. DRM
|
||
|
||
Liber detects DRM and refuses the book with one sentence: **"This book is DRM-protected, so Liber cannot open it."**
|
||
There is no decrypt path anywhere in the code.
|
||
|
||
| Format | Marker |
|
||
| :-- | :-- |
|
||
| EPUB | `META-INF/rights.xml` (Adobe ADEPT); `META-INF/license.lcpl` (Readium LCP); `META-INF/sinf.xml` (Apple FairPlay); `META-INF/encryption.xml` with any `EncryptionMethod` other than font obfuscation (`http://www.idpf.org/2008/embedding`, `http://ns.adobe.com/pdf/enc#RC`) |
|
||
| MOBI / AZW3 | the PalmDOC header's encryption type (record 0, offset 12) is not 0 |
|
||
| KFX | `\xeaDRMION\xee` anywhere in the first bytes, or the `CONT` container |
|
||
| Topaz | `TPZ` magic |
|
||
|
||
An EPUB whose only encrypted resources are obfuscated fonts opens normally: Liber does not use publisher fonts, so
|
||
the obfuscated files are simply not read.
|
||
|
||
## 3. Hostile input
|
||
|
||
| Threat | Rule | Test |
|
||
| :-- | :-- | :-- |
|
||
| zip slip | an entry name that is absolute (`/x`, `\x`, `C:x`), contains `..` as a segment, a backslash, a NUL or a control character refuses the whole book (`FormatError::Unsafe`) | `hostile.rs` |
|
||
| symlinks | an entry whose Unix mode (external attributes, made by Unix) is a symlink refuses the book | `hostile.rs` |
|
||
| zip bombs | per entry: inflated at most `max_entry` bytes (`max_xml` for XML documents) and at most `max_ratio` times its compressed size (entries over 1 MiB); in total `max_total`; at most `max_entries` entries. Inflation stops at the cap: the declared sizes are never trusted | `hostile.rs` |
|
||
| truncated or malformed zip | no end-of-central-directory, a central entry pointing past the end, a bad local header, a CRC mismatch, ZIP64, encryption, a method other than stored/deflate: `Malformed` or `Unsupported` | `hostile.rs` |
|
||
| XXE, billion laughs | a DOCTYPE that declares entities (`<!ENTITY`) refuses the book; only the five XML entities, numeric references and the HTML named entities are resolved; nothing external is ever loaded (quick-xml and html5ever cannot) | `hostile.rs` |
|
||
| scripts and active content | the sanitizer is a whitelist: elements and attributes not listed below are dropped; `script`, `style`, `iframe`, `object`, `embed`, `form` and its controls, `audio`, `video`, `canvas`, `template`, `noscript`, `link`, `meta`, `base`, `svg` (except its cover `<image>`) and `math` are dropped with their content; every `on*` handler, `style`, `class`, `srcset` attribute is dropped | `hostile.rs` |
|
||
| remote URLs | links never keep an `href`: an internal link becomes `data-href="<chapter>#<id>"`, an external link becomes its plain text. Images never keep a `src`: a resolvable raster image (PNG, JPEG, GIF, WebP, sniffed by content) becomes `data-img="<index>"`; anything else, remote included, is dropped. CSS and fonts are never read | `hostile.rs` |
|
||
| deep nesting | elements deeper than `max_depth` are unwrapped (their text kept); no recursion is unbounded | `hostile.rs` |
|
||
| sizes from the file | MOBI record counts and offsets are checked against the file; PalmDOC output is capped at the declared text length and `max_text`; a HUFF/CDIC table is checked before use | `hostile.rs`, `mobi.rs` |
|
||
| everything else | random mutations of valid books never panic and finish in bounded time (`proptest`) | `fuzz.rs` |
|
||
|
||
`Limits::default()`: input 1 GiB, 10,000 zip entries, 64 MiB per entry, 512 MiB in total, ratio 100, 32 MiB per XML
|
||
document (an XML entry is inflated at most to that), depth 256, 5,000 chapters, 5,000 images, 256 MiB of text.
|
||
|
||
Rendering (the app): the chapter is inserted with `DOMParser` as `application/xhtml+xml` into a WebView whose Content
|
||
Security Policy is `default-src 'none'`, with `img-src blob:` for the book's images and no `connect-src`. The book's
|
||
markup never reaches `innerHTML`.
|
||
|
||
## 4. The document model
|
||
|
||
```
|
||
Document format, metadata, chapters[], toc[], footnotes{ "<chapter>#<id>": xhtml }, images[], cover, warnings[]
|
||
Chapter href (stable id), title?, linear, xhtml (sanitized), root (the sanitized tree), text_len (UTF-16)
|
||
Image index, media_type, bytes
|
||
```
|
||
|
||
A chapter's `xhtml` is one well-formed element, `<div xmlns="http://www.w3.org/1999/xhtml">…</div>`, built from
|
||
`root` by the serializer: adjacent text nodes are merged and nothing is normalised, so the browser's XML parser
|
||
gives back exactly the same tree. Kept elements: `p div span section article aside header footer main nav h1–h6
|
||
blockquote pre code em i strong b u s sub sup small br hr ul ol li dl dt dd table thead tbody tfoot tr td th caption
|
||
colgroup col figure figcaption img a abbr cite q dfn kbd samp var mark ruby rt rp bdi bdo wbr time del ins`; unknown
|
||
elements are unwrapped. Kept attributes: `id`, `title`, `lang` (from `xml:lang` too), `dir`, `colspan`, `rowspan`,
|
||
`alt`, `epub:type` (as `data-epub-type`), and the generated `data-href` and `data-img`.
|
||
|
||
## 5. Positions
|
||
|
||
**A point** is a CFI over the sanitized chapter: `epubcfi(/6/<2(n+1)>!/4<steps>:<offset>)`, where `n` is the
|
||
chapter's index, `/4` is the chapter root, an even step `2k` is the k-th child element and an odd step `2k+1` the
|
||
text between child elements k and k+1, and `offset` counts UTF-16 code units (what the WebView counts). EPUB, FB2,
|
||
TXT and MOBI use the same scheme, so the app has one position type. Because the sanitizer is deterministic, the same
|
||
file always gives the same tree, and font, size and theme changes never touch the tree (the reader paints
|
||
highlights with the CSS Custom Highlight API, so the DOM is never modified).
|
||
|
||
**An anchor** (a highlight, a note, a bookmark) stores the start and end CFIs, the chapter's content hash, and a text
|
||
quote: the exact text, 32 characters before and 32 after.
|
||
|
||
**Resolving an anchor** against a document gives:
|
||
|
||
| Result | When |
|
||
| :-- | :-- |
|
||
| `Exact` | the chapter hash matches; or both CFIs resolve, the text between them equals the quote and the context matches |
|
||
| `Approximate` | the quote is found elsewhere (same chapter first, then the others), the best occurrence chosen by its context; or found after collapsing whitespace and case |
|
||
| `Lost` | the quote is nowhere: the app lists it beside the book, never at a guessed place |
|
||
|
||
A changed edition can therefore move a highlight or lose it, but never point it at other text.
|
||
|
||
## 6. Identity
|
||
|
||
- `isbn`: the first identifier that is a valid ISBN-13 or ISBN-10 (check digit verified), as ISBN-13.
|
||
- `fingerprint`: SHA-256 of the book's text, NFKC-normalised, lowercased, letters and digits only. The same text
|
||
from two sources (EPUB and AZW3 made from it) gives the same fingerprint; another edition does not.
|
||
|
||
## 7. Gaps (v0.1)
|
||
|
||
- Publisher CSS is dropped: centring, small caps and drop caps are lost. A safe CSS subset is a later step.
|
||
- MOBI: no NCX index (TOC from headings); KF8 only the first flow.
|
||
- SVG pages other than a cover image, MathML, fixed-layout EPUB, audio/video overlays.
|
||
- PDF positions are page numbers (the app), not CFIs.
|