A self-hosted, *arr-style daemon that keeps a local copy of every audiobook a user has bought on Audible, Libro.fm and Chirp. It syncs each account's library on a schedule, downloads new purchases promptly, back-fills the existing library slowly enough not to trip Audible's licence throttle, and hands finished books to Audiobookshelf. It also keeps a shelf of public-domain LibriVox books the user picks (see "LibriVox").
It is a separate product built on the same Rust core as the LibriSync app, not a fork:
server/ is its own crate that depends on native/rust-core by path, so every Audible
profile fix, throttle fix or client-profile change lands in both at once.
server/
Cargo.toml bin `librisync-server`, depends on ../native/rust-core
src/ axum HTTP API, scheduler, download queue, notifications
web/ React + Vite SPA (plain CSS, Nord palette), built into web/dist
and embedded in the binary with rust-embed
Dockerfile multi-stage: node (web) → rust (binary) → debian:trixie-slim + ffmpeg
docker/entrypoint.sh PUID/PGID/UMASK handling, then exec the binary under tini
Native core additions used by the server (both are plain Rust, no JNI, usable later by the app and the iOS port):
rust_core::pipeline— executes aDownloadPlanend to end with the systemffmpeg: resumable download, AAXC/AAX decrypt, ZIP extract, track join, validation, M4B or MP3-per-chapter output, tags, cover, Audiobookshelf sidecars. Stateless: no DB.rust_core::api::device_code— Amazon device-code ("code pair") Audible sign-in, plusaccount_from_registration, which builds the storedAccountfrom a registration.LibationError::error_code()— stable machine codes (license_throttled, …).
| Path | What |
|---|---|
/config/librisync.db |
the rust-core database (Accounts, Books, …) — same schema as the app |
/config/server.db |
server-only state: settings, users, sessions, queue, history, cooldowns, notifications, paired devices and their wants |
/config/logs/ |
rolling log files |
/config/work/ |
per-book scratch dirs (work/<queue id>/); partial downloads resume from here |
/audiobooks |
the library root (LIBRISYNC_LIBRARY_DIR) |
Env: LIBRISYNC_CONFIG_DIR (default /config), LIBRISYNC_LIBRARY_DIR (default
/audiobooks), LIBRISYNC_PORT (default 8383), LIBRISYNC_BIND (default 0.0.0.0),
LIBRISYNC_LOG (default info), FFMPEG_PATH / FFPROBE_PATH (default from PATH),
LIBRISYNC_URL_BASE (default empty: served at the root), LIBRISYNC_TRUSTED_PROXIES
(default empty: trust nobody's X-Forwarded-*), LIBRISYNC_APPLICATION_URL (overrides the
External URL setting; an invalid value is logged and ignored), LIBRISYNC_LIBRIVOX_SEED (LibriVox books to put on the shelf at
start-up),
PUID/PGID/UMASK/TZ (entrypoint only).
The core DB keeps the core's own schema untouched. Server state lives in server.db with
its own migrations, so the server can never break the app's schema or vice versa.
- Audible, device code (primary).
POST auth/create/codepair→ the UI shows "go to amazon.{tld}/code and enter ABC12" → the server pollsPOST auth/registerwith the code pair until it is confirmed (10 min). No password, PKCE or URL pasting; 2FA/CAPTCHA/CVF happen on Amazon's page. Registers with the current iPhone profile. Signing in again to an existing account replaces its registration; the old device is then deregistered (best effort). A sign-in cancelled while a poll is in flight never adds the account. - Audible, external browser (fallback). For pre-Amazon Audible accounts (legacy
DE/US/UK "Audible username" accounts) that device code does not cover: the UI shows the
sign-in URL, the user signs in and pastes the final
/ap/maplanding?...URL back. The PKCE verifier and serial live in memory for the 15-minute session. - Libro.fm / Chirp: email + password through
Provider::login. - LibriVox: no sign-in.
POST /login/librivoxcreates thelibrivoxaccount (the shelf); see "LibriVox". - No import from the app. The app has no account export, and sharing one device registration between the phone and the server would make two clients present as one device. The server registers its own device through the code sign-in instead.
- Token refresh is serialised per account: sync and download planning both refresh an expiring Audible token, under one lock, so two refreshes can never race to save.
Per enabled account, every syncIntervalHours (default 24) with ±30 min random jitter,
and on demand. Pages are fetched with the same policy as the app's runPagedSync: three
attempts per page with backoff, skip a page that still fails, stop after three
consecutive failures, cap at 500 pages. Books whose Books.created_at is at or after the
sync's start are new.
The first sync of an account that reads every page and every item (no skipped pages,
no unreadable items) establishes its baseline: everything found then is "existing
library" (back-fill), not "new". A first sync that skipped a page sets no baseline —
the books on that page would otherwise turn up on the next sync as "new purchases".
After three successful but incomplete syncs the baseline is set anyway (with a history
note): a page or item that fails every time would otherwise block every download.
Afterwards, new books are queued at new priority if autoDownloadNew is on, but at
most 10 per sync (the most recently purchased): more than that at once is almost
certainly library the baseline missed, not a shopping spree, so the excess is left to
back-fill's pacing (logged, with a syncCompleted history note).
One queue, persisted in server.db. Priorities: manual (0) > new (1) > backfill (2).
A worker pool of downloads.concurrency (default 1) takes the best eligible item.
Each item runs: plan (provider download_plan, which for Audible is the licence
request) → pipeline → import (record the output, history event, notifications,
Audiobookshelf scan). Plans are not persisted across restarts: signed URLs expire, so a
restarted item re-plans. Partial files in its work dir are reused when the plan's part
file names match.
A pipeline that fails with a network or HTTP error is run once more with the same plan straight away (its signed URLs are still valid), so a blip doesn't cost a licence; only then does the item go back to the queue to re-plan later.
Two books whose folder template renders the same folder never share it: when the folder
is already recorded for another book (downloads) or in use by another book's queue
item, [<book id>] is appended to the last component, and the chosen folder is recorded
on the queue row.
At most one LibriVox item is planning or running at a time, whatever
downloads.concurrency says: its files come from archive.org, a volunteer-run service.
The others wait with a waitingReason saying so; other stores keep using the free slots.
Only Audible licence requests are budgeted; DRM-free stores are limited by concurrency alone. Nobody knows Audible's real threshold, so the defaults are conservative and every number is a setting.
Audible throttles an Amazon customer, and one customer signed in for two marketplaces
is two accounts here (amzn1.account.X:us, amzn1.account.X:uk). So pacing state — the
cooldown, the spacing, the daily cap's request log, the "unavailable" hold and the
in-flight request — is kept per pacing key: the Amazon customer id for Audible
(identity.customer_info.user_id, else the account id before its :), the account id
for every other provider. It is kept when an account is removed, so removing and re-adding
an account doesn't forget a throttle. "Per account" below means per customer.
| Setting | Default |
|---|---|
audible.dailyLicenceCap |
20 per account, rolling 24 h, counting every licence request (granted or not) |
audible.spacingMinutes |
random 20–60 between licence requests per account (new/manual ignore the spacing but still count) |
backfill.window |
optional local-time window (e.g. 01:00–07:00) for back-fill only |
backfill.order |
newest_first (by purchase date) or oldest_first |
At most one licence request per account is in flight at a time, and a request's outcome
(cooldown, hold, granted probe, expired sign-in) is recorded before the next request
for that account may start. A force is spent by the request it allowed, whatever the
answer.
Refusals (modelled on Libation's backoff, lengthened for an unattended daemon):
| Refusal | Effect |
|---|---|
license_throttled (CustomerThrottled, or a 429) |
Account cooldown: no licence requests for that account for 24 h, doubling per consecutive throttle, capped at 7 days. After it expires the next request is a single probe; a success resets the level. |
A plan with licence_throttled (AAXC refused as throttled, served from the AAX fallback) |
The book downloads, but the request counts as throttled and starts the account cooldown exactly as above; it is not a successful probe, so the level is not reset. |
| Server error (5xx) or network error from the licence request | Account hold: no licence requests for that account for 30 min ("Audible unavailable, retrying at …"). The title counts an attempt (so one title Audible always fails on can't block the rest forever). |
license_denied for an eligibility reason |
Title backoff: 1 day, doubling, capped at 30 days. Other titles continue. An unthrottled refusal naming Ownership: RequesterEligibility (an Audible Plus title without a membership, or no longer owned) is reported as license_denied straight away — the core no longer tries the AAX fallback for it, which answered with something that wasn't audio. |
| Network / HTTP failure in the pipeline | Normal retry: up to 3 attempts with 5 min → 30 min → 2 h waits, then failed. No cooldown. |
| Validation failure (the source didn't decode) | One retry after 5 min — a re-plan, i.e. one more licence — then failed (counted in queue.validation_failures; a retry by hand resets it). The same store usually serves the same bad file again. |
| A downloaded part that is text, not media (an error page served with 200) | The core deletes it and fails with InvalidPlan: the item fails at once, without spending another licence. |
| Disk full, ffmpeg missing or broken, a folder that can't be written | The item fails at once (retrying would re-plan and spend another licence) and the whole queue pauses ("Downloads paused: disk full", shown in health) until the health monitor (every 5 min, a hold lasts at least 5 min) finds ffmpeg working and the library and work folders writable with ≥ 2 GB free — after a disk-full failure also ≥ 1 GB more free than when it paused — or the user retries the failed item. |
A manual download bypasses title backoff and spacing, but not an account cooldown or
hold unless the request says force: true (the UI warns that retrying into a throttle is
believed to extend it).
Titles a member added from the Plus catalogue are in the library (Books.is_ayce = 1) but
can only be licensed while the customer has a Plus membership; without one, every
licence request for them is refused. audible.includePlusCatalog (default off)
decides whether they are downloaded automatically. While it is off they are excluded:
back-fill never picks them, new purchases don't queue them (they are still recorded as
added), they are left out of /wanted and its estimate, and automatically queued ones
that haven't started are removed from the queue (when the switch is turned off, and on
every back-fill pass). A manual download is still allowed; if Audible refuses it, the
normal title backoff applies.
LibriVox books are public domain and free: no sign-in, no purchase library. rust-core's
providers::librivox holds the catalogue client (LibriVox's JSON feed API; links resolved
through the book page's feed link or archive.org's item metadata) and the plan: one plain
MP3 part per section with join_parts, a chapter per section. The pipeline joins them
into one AAC M4B (chapter times taken from the files, titles from the sections) or, for
MP3 output, cuts the joined MP3 back into one file per section without re-encoding.
On the server the librivox account is a shelf. It is created by POST /login/librivox (or implicitly by adding a book), with its baseline set at once, since
there is nothing to sync; a sync of it changes nothing and records no history. Books are
put on it by POST /librivox/books (ids or links; the web UI's search and paste list) or
by LIBRISYNC_LIBRIVOX_SEED at start-up, and are then ordinary library books: wanted by
back-fill (three queued at a time, as for other DRM-free stores, run one at a time),
downloadable by hand, skippable. Removing one from the shelf unlinks it
(BookAccounts.is_deleted), drops its queue item and download record, and leaves its files
alone. The catalogue sits behind a Catalog trait so the shelf is tested against
fixtures, without the network.
Seeding is idempotent and cheap to repeat: a bare id already on the shelf is skipped before any request; links are resolved (one request) and then checked. Failures are logged per entry and never stop the server.
Default folder template (Audiobookshelf-friendly, one folder per book, never a loose
file in an author folder): {author}/{series}/{seriesSequence} - {title} when the book
is in a series, else {author}/{title}. Tokens: {author} (first author), {authors},
{title}, {subtitle}, {series}, {seriesSequence}, {year}, {narrator},
{asin}, {provider}. Path components are sanitised (no / \ : * ? " < > |, no trailing
dots/spaces, ≤ 120 bytes). The audio file is {title}.m4b; MP3 output is
NN - Chapter Title.mp3. Sidecars (on by default): cover.jpg, desc.txt,
reader.txt, metadata.opf.
- Webhook: Sonarr-style JSON
{eventType, instanceName, applicationUrl, …}, configurable method, headers and per-event toggles. - Apprise: apprise-api server URL + configuration key or stateless URLs.
- Audiobookshelf: URL + API key + library id;
POST /api/libraries/:id/scanafter each imported book (debounced to one scan per minute).
Events: test, bookAdded, grab, download, downloadFailed, licenceThrottled,
authExpired, health, healthRestored.
Secrets are masked (********) in API responses: webhook URLs (their token is usually in
the path or query), passwords and secret-looking headers, Apprise configuration keys and
stateless URLs, Audiobookshelf API keys. Sending the mask back keeps the stored value —
only while the address (scheme, host, port) is unchanged; a changed address needs every
secret entered again, so a stored secret can never be redirected to another server.
- First start with no user: the UI shows a setup page that creates the admin
user (argon2 hash; at most two hashes run at once, so a login flood queues rather than
exhausting CPU and memory). Setup needs the one-time setup code the server prints to
its log at start-up (16 characters, in memory only, new on every start, spent by setup),
so whoever reaches a fresh server first over the internet can't claim it. There is no
loopback exemption: behind a reverse proxy on the same host every request comes from
loopback, and a proxy that doesn't add
X-Forwarded-Forwould make the internet look local. Sessions are anHttpOnly,SameSite=Laxcookie backed by thesessionstable, scoped to the URL base andSecurewhen the request came over HTTPS through a trusted proxy. - URL base (
LIBRISYNC_URL_BASE, the *arr "URL Base"): the reverse proxy passes/librisync/…through unchanged; the server strips the base before routing, so every route is the same as at the root, and answers404outside it. The UI is built with relative asset paths andindex.htmlis rewritten when served (absolute asset paths under the base, plus<meta name="librisync-base">for the router, API client, event stream and covers) — no<base href>, which would break the in-page#sectionlinks. - Trusted proxies (
LIBRISYNC_TRUSTED_PROXIES, IPs/CIDRs, default none): only when the TCP peer is one isX-Forwarded-For(right-most entry that isn't a trusted proxy) /X-Real-IPtaken as the client address andX-Forwarded-Proto/X-Forwarded-Hostbelieved (cookieSecure, CSRF host check, the pairing QR's address; device-plan URLs are server-relative and don't depend on them). Forwarding headers from an untrusted peer are ignored, with a one-time log warning naming the peer. - Failed credentials (
authlimit.rs, in memory): per client address and kind of credential, 5 free failures an hour, then waits of 1 s doubling to 60 s between attempts, and a 15-minute lockout at 20; a successful sign-in clears the address. Per user name, against spread-out guessing: once a name has 10 failures in the hour, only addresses that have failed for it are slowed (one try per 15 minutes) — a fresh address, i.e. the real admin, is never held back, so the limiter can't be turned into a lockout of the admin. Wrong pairing codes are also capped at 100 per 10 minutes server-wide (a large botnet still has ~1e-9 chance per code). Each failure is logged at WARN in a fixed, fail2ban-friendly form (Failed login for user '<u>' from <ip>,Invalid API key from <ip>,Invalid device token from <ip>,Invalid pairing code from <ip>,Invalid setup code from <ip>); user names are stripped of quotes and control characters first. - Every response carries
X-Content-Type-Options: nosniff,Referrer-Policy: same-origin,X-Frame-Options: DENYandContent-Security-Policy: frame-ancestors 'none'. Request bodies are capped at 1 MiB. - CSRF: a cookie-authenticated request other than GET/HEAD must carry
Sec-Fetch-Site: same-origin(ornone), or, from a browser that doesn't send it, anOriginmatchingHost/X-Forwarded-Host. API-key requests are exempt (browsers never add the key). Request bodies must beapplication/json. - The API key (generated on first start, shown under Settings → General) authenticates
X-Api-Keyor?apikey=.GET /pingis anonymous. - Device tokens (connected mode,
CONNECTED_MODE.md): each paired phone has its own 256-bit bearer token, stored only as a SHA-256 hash and revocable on its own. A token is obtained once, with a one-time pairing code (8 characters, 10 minutes, single use; also only hashed) or by presenting the API key toPOST /devices/pair. Wrong codes and keys are limited per client address as above, plus the server-wide cap on wrong codes, so a code can't be guessed in its lifetime (31^8 codes). A token can use the API except what would let a lost phone take over the server: the password, the API key (regenerating it, and reading it —GET /settingsmasks it for devices), device administration andPUT /settings. Bearer requests skip the CSRF check (browsers never attach them). The token travels in device plans' download headers, so the phone's engine authenticates file downloads the same way; files are served only from the book's recorded folder inside the library, after canonicalising (no.., no symlink escapes). - Account credentials live in
librisync.dbin/config. That volume is the secret; the README says so.
Widevine/xHE-AAC, multi-user, uploading to Audiobookshelf over its API, Postgres.