From 0b0e35d7279d9b86d99f2063234965f51468c0c1 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 01:36:19 +0100 Subject: [PATCH] [repo] Docs first: CLAUDE.md, FORMATS.md (formats, DRM, hostile input, positions), DEPENDENCIES.md, deps and fixtures scripts --- CLAUDE.md | 38 +++++++++ README.md | 8 ++ docs/DEPENDENCIES.md | 152 +++++++++++++++++++++++++++++++++++ docs/FORMATS.md | 106 ++++++++++++++++++++++++ fixtures-fetch/fetch.mjs | 35 ++++++++ fixtures-fetch/manifest.json | 4 + rustfmt.toml | 2 + scripts/deps.mjs | 67 +++++++++++++++ 8 files changed, 412 insertions(+) create mode 100644 CLAUDE.md create mode 100644 README.md create mode 100644 docs/DEPENDENCIES.md create mode 100644 docs/FORMATS.md create mode 100644 fixtures-fetch/fetch.mjs create mode 100644 fixtures-fetch/manifest.json create mode 100644 rustfmt.toml create mode 100644 scripts/deps.mjs diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..5f71bac --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,38 @@ +# Liber Domi — core (public) + +Liber (Latin: book) is the Domi home for books. This repository is the **public, MPL-2.0 core** +(`https://gitea.marek-novak.cz/mnovak/Liber-public`; the roadmap calls it `LiberPublic`): pure Rust, no network, +no UI, no clock. The app lives in the private `Liber` repo (`https://gitea.marek-novak.cz/mnovak/Liber`) and depends +on this one **by git tag**, never by a path. The roadmap and the day pages are in the app repo (`docs/01_books.md`). + +## Layout +``` +crates/liber-format EPUB 2/3, FB2 (+ .fb2.zip), TXT, DRM-free MOBI/AZW3 -> one Document; the zip reader and + writer; the sanitizer (whitelist, no scripts, no remote URLs); positions (CFI + text quote) +crates/liber-library book identity (ISBN, text fingerprint), the library model, the event log and its merge + (sync semantics), stats, Goodreads/StoryGraph CSV import, the liber-export format +fixtures-fetch/ sha256-pinned hostile corpora -> fixtures/fetched/ (never in git; the tests generate theirs) +docs/ FORMATS.md (formats, limits, positions, DRM), DEPENDENCIES.md (every crate, its licence) +scripts/deps.mjs regenerates the crate table in DEPENDENCIES.md; exits 1 on a licence outside the allowed set +``` +Direction: `liber-library -> liber-format`. Neither crate opens files, sockets or reads the clock: bytes in, values +out; time and ids are parameters (`tests/purity.rs` checks the sources). + +## Commands +``` +cargo test --workspace # every mandatory test +node scripts/deps.mjs # licence table; must exit 0 +``` +On the dev PC `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C: is off limits). + +## Rules +- Commits: `[] : `. **No AI attribution, ever**: no `Co-Authored-By`, no session + links, no "Generated with". +- **Licence rule:** a crate is recorded in `docs/DEPENDENCIES.md` before it is used. Allowed: MIT, Apache-2.0, BSD, + Zlib, MPL-2.0 (and the interpretations listed there). Anything else: stop and report. +- **Hostile input:** every outside file is hostile. Explicit `Limits`; no allocation sized from a number read out + of a file; nothing outside the input is ever resolved (no external entities, no remote URLs). +- **DRM:** detected and refused with "This book is DRM-protected, so Liber cannot open it." There is no decrypt path. +- No binaries in git: fixtures are generated by the tests or fetched by `fixtures-fetch/`. +- Branch -> PR on Gitea (`$GITEA_TOKEN`, never echoed, never written) -> self-review in the PR body -> merge + `--no-ff` -> push -> `git rev-parse HEAD origin/main` twice the same -> tag `vX.Y.Z`. diff --git a/README.md b/README.md new file mode 100644 index 0000000..cd71ec3 --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +# Liber Domi — core + +The public, MPL-2.0 core of Liber Domi, the Domi home for books: e-book formats (EPUB, FB2, TXT, DRM-free +MOBI/AZW3) into one sanitized document model, positions that survive re-rendering, the library model and its +event-log merge, stats, Goodreads/StoryGraph import and the `liber-export` format. Pure Rust: no network, no UI, +no clock. See `docs/FORMATS.md` and `docs/DEPENDENCIES.md`. + +Liber never removes DRM: protected books are detected and refused. diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md new file mode 100644 index 0000000..6b7c554 --- /dev/null +++ b/docs/DEPENDENCIES.md @@ -0,0 +1,152 @@ +# Dependencies and their licences + +Every crate Liber's core uses, with its licence, recorded **before** it is used. The rule (from Pictor): code only +under MIT, Apache-2.0, BSD, Zlib or MPL-2.0, or an OS codec. Anything else: the feature waits. +Data and model licences (dictionaries, voices, translation models) are not code: they are listed in the app's +`docs/DEPENDENCIES.md` and decided by Mark before use. Day 1 uses none. + +## The allowed set, as checked by `scripts/deps.mjs` + +| Licence (SPDX) | Why it is allowed | +| :-- | :-- | +| MIT, MIT-0 | named in the rule | +| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the rule | +| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the rule ("BSD") | +| Zlib | named in the rule | +| MPL-2.0 | named in the rule | +| ISC | **interpretation, as in Pictor (Mark to confirm)**: BSD-style | +| Unicode-3.0, Unicode-DFS-2016 | **interpretation, as in Pictor (Mark to confirm)**: MIT-style licence of Unicode's data tables (`unicode-ident`, `unicode-normalization`) | +| BSL-1.0, CC0-1.0 | **interpretation, as in Pictor (Mark to confirm)** | +| Unlicense | only inside an `OR` with MIT (`csv`: "Unlicense/MIT"), so MIT is the branch that passes; Unlicense alone is not in the set | + +An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. + +## Direct dependencies + +| Crate | Version | Licence | Used by | For | +| :-- | :-- | :-- | :-- | :-- | +| quick-xml | 0.42 | MIT | liber-format | OPF, NCX, nav, container.xml, FB2 and well-formed XHTML; never resolves external entities | +| html5ever | 0.40 | MIT OR Apache-2.0 | liber-format | tag-soup HTML: MOBI text, and XHTML chapters that are not well-formed | +| markup5ever_rcdom | 0.40 | MIT OR Apache-2.0 | liber-format | the tree html5ever builds into (walked once, depth-capped, then dropped) | +| encoding_rs | 0.8 | (Apache-2.0 OR MIT) AND BSD-3-Clause | liber-format | Windows-1250/1251/1252, ISO-8859-2, UTF-16 decoding | +| chardetng | 1 | Apache-2.0 OR MIT | liber-format | encoding detection for TXT | +| miniz_oxide | 0.8 | MIT OR Zlib OR Apache-2.0 | liber-format | inflate (with an output cap) and deflate for the zip reader and writer | +| crc32fast | 1 | MIT OR Apache-2.0 | liber-format | zip CRC-32 | +| sha2 | 0.10 | MIT OR Apache-2.0 | liber-format, liber-library | content hashes, fingerprints, ids | +| base64 | 0.22 | MIT OR Apache-2.0 | liber-format | FB2 `binary` images | +| unicode-normalization | 0.1 | (MIT OR Apache-2.0) AND Unicode-3.0 | liber-format | NFKC for the text fingerprint | +| serde, serde_json | 1 | MIT OR Apache-2.0 | both | the document model to the app, the export format, the event log | +| thiserror | 2 | MIT OR Apache-2.0 | both | error types | +| csv | 1 | Unlicense OR MIT | liber-library | Goodreads and StoryGraph CSV import, CSV export | +| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | random mutations of books, generated histories | + +Versions are the ones `cargo` resolved on 2026-11-17; the table below is generated from `Cargo.lock`. + +## Every crate in Cargo.lock + + +100 crates; 0 outside the allowed set. + +| Crate | Version | Licence | Allowed | +| :-- | :-- | :-- | :-- | +| adler2 | 2.0.1 | 0BSD OR MIT OR Apache-2.0 | yes | +| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes | +| base64 | 0.22.1 | MIT OR Apache-2.0 | yes | +| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes | +| bit-vec | 0.10.2 | Apache-2.0 OR MIT | yes | +| bitflags | 2.13.2 | MIT OR Apache-2.0 | yes | +| block-buffer | 0.10.4 | MIT OR Apache-2.0 | yes | +| borsh | 1.8.1 | MIT OR Apache-2.0 | yes | +| borsh-derive | 1.8.1 | Apache-2.0 | yes | +| bytes | 1.12.1 | MIT | yes | +| cfg_aliases | 0.2.2 | MIT | yes | +| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes | +| chacha20 | 0.10.2 | MIT OR Apache-2.0 | yes | +| chardetng | 1.0.0 | Apache-2.0 OR MIT | yes | +| core_detect | 1.0.0 | MIT/Apache-2.0 | yes | +| cpufeatures | 0.2.17 | MIT OR Apache-2.0 | yes | +| cpufeatures | 0.3.1 | MIT OR Apache-2.0 | yes | +| crc32fast | 1.5.5 | MIT OR Apache-2.0 | yes | +| crypto-common | 0.1.7 | MIT OR Apache-2.0 | yes | +| csv | 1.4.0 | Unlicense/MIT | yes | +| csv-core | 0.1.13 | Unlicense/MIT | yes | +| digest | 0.10.7 | MIT OR Apache-2.0 | yes | +| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes | +| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes | +| errno | 0.3.15 | MIT OR Apache-2.0 | yes | +| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes | +| fnv | 1.0.7 | Apache-2.0 / MIT | yes | +| generic-array | 0.14.7 | MIT | yes | +| getrandom | 0.4.3 | MIT OR Apache-2.0 | yes | +| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes | +| html5ever | 0.40.1 | MIT OR Apache-2.0 | yes | +| indexmap | 2.14.2 | Apache-2.0 OR MIT | yes | +| itoa | 1.0.19 | MIT OR Apache-2.0 | yes | +| libc | 0.2.191 | MIT OR Apache-2.0 | yes | +| linux-raw-sys | 0.12.1 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | yes | +| lock_api | 0.4.14 | MIT OR Apache-2.0 | yes | +| log | 0.4.35 | MIT OR Apache-2.0 | yes | +| markup5ever | 0.40.0 | MIT OR Apache-2.0 | yes | +| markup5ever_rcdom | 0.40.1+unofficial | MIT OR Apache-2.0 | yes | +| memchr | 2.8.3 | Unlicense OR MIT | yes | +| miniz_oxide | 0.8.9 | MIT OR Zlib OR Apache-2.0 | yes | +| multiversion_no_op | 1.0.0 | Apache-2.0 OR MIT | yes | +| new_debug_unreachable | 1.0.6 | MIT | yes | +| num-traits | 0.2.19 | MIT OR Apache-2.0 | yes | +| once_cell | 1.21.4 | MIT OR Apache-2.0 | yes | +| parking_lot | 0.12.5 | MIT OR Apache-2.0 | yes | +| parking_lot_core | 0.9.12 | MIT OR Apache-2.0 | yes | +| phf | 0.14.0 | MIT | yes | +| phf_codegen | 0.14.0 | MIT | yes | +| phf_generator | 0.14.0 | MIT | yes | +| phf_shared | 0.14.0 | MIT | yes | +| precomputed-hash | 0.1.1 | MIT | yes | +| proc-macro-crate | 3.5.0 | MIT OR Apache-2.0 | yes | +| proc-macro2 | 1.0.107 | MIT OR Apache-2.0 | yes | +| proptest | 1.12.0 | MIT OR Apache-2.0 | yes | +| quick-error | 1.2.3 | MIT/Apache-2.0 | yes | +| quick-xml | 0.42.0 | MIT | yes | +| quote | 1.0.47 | MIT OR Apache-2.0 | yes | +| r-efi | 6.0.0 | MIT OR Apache-2.0 OR LGPL-2.1-or-later | yes | +| rand | 0.10.4 | MIT OR Apache-2.0 | yes | +| rand_core | 0.10.1 | MIT OR Apache-2.0 | yes | +| rand_xorshift | 0.5.0 | MIT OR Apache-2.0 | yes | +| redox_syscall | 0.5.18 | MIT | yes | +| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes | +| rustix | 1.1.6 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | yes | +| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes | +| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes | +| ryu | 1.0.23 | Apache-2.0 OR BSL-1.0 | yes | +| scopeguard | 1.2.0 | MIT OR Apache-2.0 | yes | +| serde | 1.0.229 | MIT OR Apache-2.0 | yes | +| serde_core | 1.0.229 | MIT OR Apache-2.0 | yes | +| serde_derive | 1.0.229 | MIT OR Apache-2.0 | yes | +| serde_json | 1.0.154 | MIT OR Apache-2.0 | yes | +| sha2 | 0.10.9 | MIT OR Apache-2.0 | yes | +| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes | +| siphasher | 1.0.4 | MIT OR Apache-2.0 | yes | +| smallvec | 1.16.5 | MIT OR Apache-2.0 | yes | +| string_cache | 0.11.0 | MIT OR Apache-2.0 | yes | +| string_cache_codegen | 0.11.2 | MIT OR Apache-2.0 | yes | +| syn | 3.0.10 | MIT OR Apache-2.0 | yes | +| tempfile | 3.27.0 | MIT OR Apache-2.0 | yes | +| tendril | 0.5.1 | MIT OR Apache-2.0 | yes | +| thiserror | 2.0.21 | MIT OR Apache-2.0 | yes | +| thiserror-impl | 2.0.21 | MIT OR Apache-2.0 | yes | +| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes | +| toml_datetime | 1.1.3+spec-1.1.0 | MIT OR Apache-2.0 | yes | +| toml_edit | 0.25.19+spec-1.1.0 | MIT OR Apache-2.0 | yes | +| toml_parser | 1.1.5+spec-1.1.0 | MIT OR Apache-2.0 | yes | +| typenum | 1.20.1 | MIT OR Apache-2.0 | yes | +| unarray | 0.1.4 | MIT OR Apache-2.0 | yes | +| unicode-ident | 1.0.27 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes | +| unicode-normalization | 0.1.26 | (MIT OR Apache-2.0) AND Unicode-3.0 | yes | +| version_check | 0.9.5 | MIT/Apache-2.0 | yes | +| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes | +| web_atoms | 0.3.0 | MIT OR Apache-2.0 | yes | +| windows-link | 0.2.1 | MIT OR Apache-2.0 | yes | +| windows-sys | 0.61.2 | MIT OR Apache-2.0 | yes | +| winnow | 1.0.5 | MIT | yes | +| xml5ever | 0.40.0 | MIT OR Apache-2.0 | yes | +| zmij | 1.0.23 | MIT | yes | + diff --git a/docs/FORMATS.md b/docs/FORMATS.md new file mode 100644 index 0000000..e067334 --- /dev/null +++ b/docs/FORMATS.md @@ -0,0 +1,106 @@ +# 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 `` inside an SVG cover survives, as an ``), 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 `` (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 (``) 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="#"`, 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=""`; 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{ "#": 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, `
…
`, 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:)`, 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. diff --git a/fixtures-fetch/fetch.mjs b/fixtures-fetch/fetch.mjs new file mode 100644 index 0000000..e3a63a8 --- /dev/null +++ b/fixtures-fetch/fetch.mjs @@ -0,0 +1,35 @@ +#!/usr/bin/env node +// Fetches the corpora in manifest.json into ../fixtures/fetched/, refusing any file whose sha256 differs from the +// pinned one. Nothing fetched is ever committed (.gitignore). Usage: node fixtures-fetch/fetch.mjs +import { createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, writeFileSync, existsSync, renameSync } from 'node:fs'; +import { dirname, join, basename } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = dirname(fileURLToPath(import.meta.url)); +const out = join(here, '..', 'fixtures', 'fetched'); +const manifest = JSON.parse(readFileSync(join(here, 'manifest.json'), 'utf8')); +mkdirSync(out, { recursive: true }); +let bad = 0; +for (const f of manifest.files) { + if (!/^[0-9a-f]{64}$/.test(f.sha256) || basename(f.name) !== f.name || !f.url.startsWith('https://')) { + console.error(`skip ${f.name}: the manifest entry is not pinned (https URL, plain name, sha256)`); + bad++; + continue; + } + const target = join(out, f.name); + if (existsSync(target) && createHash('sha256').update(readFileSync(target)).digest('hex') === f.sha256) { + console.log(`ok ${f.name} (cached)`); + continue; + } + const res = await fetch(f.url, { redirect: 'follow' }); + if (!res.ok) { console.error(`fail ${f.name}: HTTP ${res.status}`); bad++; continue; } + const buf = Buffer.from(await res.arrayBuffer()); + const got = createHash('sha256').update(buf).digest('hex'); + if (got !== f.sha256) { console.error(`fail ${f.name}: sha256 ${got} is not the pinned ${f.sha256}`); bad++; continue; } + writeFileSync(target + '.part', buf); + renameSync(target + '.part', target); + console.log(`ok ${f.name}`); +} +console.log(`${manifest.files.length} pinned, ${bad} failed`); +process.exit(bad ? 1 : 0); diff --git a/fixtures-fetch/manifest.json b/fixtures-fetch/manifest.json new file mode 100644 index 0000000..5b76c16 --- /dev/null +++ b/fixtures-fetch/manifest.json @@ -0,0 +1,4 @@ +{ + "comment": "Extra hostile or real-world corpora, fetched by fetch.mjs into fixtures/fetched/ (never in git). Each entry: { \"name\": \"file name\", \"url\": \"https://…\", \"sha256\": \"64 hex\", \"why\": \"what it exercises\" }. The mandatory tests generate their own fixtures and need none of these; tests/corpus.rs opens whatever is here.", + "files": [] +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..c775577 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max" diff --git a/scripts/deps.mjs b/scripts/deps.mjs new file mode 100644 index 0000000..d51518e --- /dev/null +++ b/scripts/deps.mjs @@ -0,0 +1,67 @@ +#!/usr/bin/env node +// Regenerates the "Every crate in Cargo.lock" table in docs/DEPENDENCIES.md from `cargo metadata` +// and exits 1 when a crate's licence is outside the allowed set (or missing). +// Usage: node scripts/deps.mjs [--check] (--check: do not rewrite the file, only verify it is current) +import { execFileSync } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..'); +const docPath = join(root, 'docs', 'DEPENDENCIES.md'); + +export const ALLOWED = new Set([ + 'MIT', 'MIT-0', 'Apache-2.0', 'Apache-2.0 WITH LLVM-exception', 'BSD-2-Clause', 'BSD-3-Clause', '0BSD', + 'Zlib', 'MPL-2.0', 'ISC', 'Unicode-3.0', 'Unicode-DFS-2016', 'BSL-1.0', 'CC0-1.0', +]); + +// Minimal SPDX evaluator: OR / AND / WITH and parentheses. Old crates write "MIT/Apache-2.0" for OR. +export function allowed(expr) { + if (!expr) return false; + const tokens = expr.replace(/\//g, ' OR ').replace(/\(/g, ' ( ').replace(/\)/g, ' ) ').split(/\s+/).filter(Boolean); + let i = 0; + function primary() { + if (tokens[i] === '(') { i++; const v = orExpr(); i++; return v; } + let id = tokens[i++]; + if (tokens[i] === 'WITH') { id += ` WITH ${tokens[i + 1]}`; i += 2; } + return ALLOWED.has(id); + } + function andExpr() { let v = primary(); while (tokens[i] === 'AND') { i++; v = primary() && v; } return v; } + function orExpr() { let v = andExpr(); while (tokens[i] === 'OR') { i++; v = andExpr() || v; } return v; } + return orExpr(); +} + +function main() { + // Every package in Cargo.lock (all platforms): a crate that is locked must be listed, whatever it is built for. + const meta = JSON.parse(execFileSync('cargo', ['metadata', '--format-version', '1', '--locked'], { + cwd: root, maxBuffer: 1 << 28, encoding: 'utf8', + })); + // resolve.nodes lists every package the lockfile resolves (all targets). + + const used = new Set(meta.resolve.nodes.map((n) => n.id)); + const workspace = new Set(meta.workspace_members); + const rows = meta.packages + .filter((p) => used.has(p.id) && !workspace.has(p.id)) + .map((p) => ({ name: p.name, version: p.version, licence: p.license ?? (p.license_file ? `file: ${p.license_file}` : '') })) + .sort((a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version)); + const bad = rows.filter((r) => !allowed(r.licence)); + const table = [ + `${rows.length} crates; ${bad.length} outside the allowed set.`, + '', + '| Crate | Version | Licence | Allowed |', + '| :-- | :-- | :-- | :-- |', + ...rows.map((r) => `| ${r.name} | ${r.version} | ${r.licence || '(none)'} | ${allowed(r.licence) ? 'yes' : '**NO**'} |`), + ].join('\n'); + const doc = readFileSync(docPath, 'utf8'); + const next = doc.replace(/[\s\S]*/, `\n${table}\n`); + if (process.argv.includes('--check')) { + if (next !== doc) { console.error('docs/DEPENDENCIES.md is out of date: run node scripts/deps.mjs'); process.exit(1); } + } else if (next !== doc) { + writeFileSync(docPath, next); + } + for (const r of bad) console.error(`not allowed: ${r.name} ${r.version} (${r.licence || 'no licence field'})`); + console.log(`${rows.length} crates, ${bad.length} not allowed`); + process.exit(bad.length ? 1 : 0); +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) main();